NeuXtalViz.models package#
Submodules#
NeuXtalViz.models.base_model module#
NeuXtalVizModel#
Base model for crystallographic and reciprocal lattice operations using Mantid workspaces.
This class provides methods for handling UB matrices, checking oriented lattices, and computing various crystallographic and reciprocal axes and transformations for visualization and analysis.
Attributes#
- UBnp.ndarray or None
The 3x3 UB matrix for the current workspace, or None if not set.
Methods#
- has_UB(ws)
Check if the oriented lattice exists on a workspace.
- set_UB(UB)
Update the UB-matrix.
- get_oriented_lattice_parameters()
Obtain the oriented lattice parameters (a, b, c, alpha, beta, gamma, u, v).
- orientation_matrix()
Return the current UB matrix (orientation matrix).
- get_transform(reciprocal)
Transformation matrix describing the reciprocal or crystal axes.
- ab_star_axes(), bc_star_axes(), ca_star_axes()
Cartesian camera/upward view vectors for various axes.
- ab_axes(), bc_axes(), ca_axes()
Cartesian camera/upward view vectors for reciprocal axes.
- get_vector(axes_type, ind)
Vector corresponding to a particular crystallographic direction.
- class NeuXtalVizModel[source]#
Bases:
objectMethods
ab_axes()\(c^*\)-direction in cartesian coordinates.
\(c\)-direction in cartesian coordinates.
bc_axes()\(a^*\)-direction in cartesian coordinates.
\(a\)-direction in cartesian coordinates.
ca_axes()\(b^*\)-direction in cartesian coordinates.
\(b\)-direction in cartesian coordinates.
calculate_camera_parameters(direction, roll)Calculate roll, elevation, and azimuth from camera direction and roll.
files_exist(files)Check if the specified files exist and are readable.
Obtain the oriented lattice parameters.
get_transform([reciprocal])Transformation matrix describing the reciprocal or crystal axes.
get_vector(axes_type, ind)Vector corresponding to a particular crystallographic direction.
has_UB(ws)Check if the oriented lattice exists on a workspace.
Return the current UB matrix (orientation matrix).
rotate_camera_azimuth(position, focal_point, ...)Rotate the camera left/right about a global up axis.
rotate_camera_elevation(position, ...)Tilt the camera up/down about its right axis.
rotate_camera_roll(position, focal_point, ...)Apply a roll about the current viewing axis.
set_UB(UB)Update the UB-matrix.
- ab_axes()[source]#
\(c^*\)-direction in cartesian coordinates.
- Returns:
- camera3 element 1d array
Cartesian camera view vector.
- upward3 element 1d array
Cartesian upward view vector.
- ab_star_axes()[source]#
\(c\)-direction in cartesian coordinates.
- Returns:
- camera3 element 1d array
Cartesian camera view vector.
- upward3 element 1d array
Cartesian upward view vector.
- bc_axes()[source]#
\(a^*\)-direction in cartesian coordinates.
- Returns:
- camera3 element 1d array
Cartesian camera view vector.
- upward3 element 1d array
Cartesian upward view vector.
- bc_star_axes()[source]#
\(a\)-direction in cartesian coordinates.
- Returns:
- camera3 element 1d array
Cartesian camera view vector.
- upward3 element 1d array
Cartesian upward view vector.
- ca_axes()[source]#
\(b^*\)-direction in cartesian coordinates.
- Returns:
- camera3 element 1d array
Cartesian camera view vector.
- upward3 element 1d array
Cartesian upward view vector.
- ca_star_axes()[source]#
\(b\)-direction in cartesian coordinates.
- Returns:
- camera3 element 1d array
Cartesian camera view vector.
- upward3 element 1d array
Cartesian upward view vector.
- calculate_camera_parameters(direction, roll)[source]#
Calculate roll, elevation, and azimuth from camera direction and roll.
- Parameters:
- directionarray-like, shape (3,)
Camera viewing direction.
- rollfloat
Camera roll angle in degrees.
- Returns:
- roll, elevation, azimuthfloat
Camera roll, elevation, and azimuth angles in degrees.
- files_exist(files)[source]#
Check if the specified files exist and are readable.
- Parameters:
- fileslist of str
List of file paths to check.
- Returns:
- existbool
True if all files exist and are readable, False otherwise.
- get_oriented_lattice_parameters()[source]#
Obtain the oriented lattice parameters.
- Returns:
- a, b, cfloat
Lattice constants.
- alpha, beta, gammafloat
Lattice angles.
- u, vnp.ndarray
Normalized u and v vectors.
- get_transform(reciprocal=True)[source]#
Transformation matrix describing the reciprocal or crystal axes.
- Parameters:
- reciprocalbool, optional
Option for the reciprocal (True) or crystal lattice axes (False). Default is True.
- Returns:
- T3x3 element 2d array
Normalized transformation matrix.
- get_vector(axes_type, ind)[source]#
Vector corresponding to a particular crystallographic direction.
- Parameters:
- axes_typestr, [hkl] or [uvw]
Miller index or fractional coordinate.
- ind3-element 1d array-like
Indices.
- Returns:
- vec3 element 1d array
Cartesian vector.
- has_UB(ws)[source]#
Check if the oriented lattice exists on a workspace.
- Parameters:
- wsstr
Name of workspace.
- Returns:
- olbool
True if oriented lattice exists, False otherwise.
- orientation_matrix()[source]#
Return the current UB matrix (orientation matrix).
- Returns:
- np.ndarray
The UB matrix.
- rotate_camera_azimuth(position, focal_point, up, angle_deg)[source]#
Rotate the camera left/right about a global up axis.
- Parameters:
- position, focal_point, uparray-like
Current camera position, focal point, and up vector.
- angle_degfloat
Azimuth angle in degrees (positive rotates to the right).
- Returns:
- new_position, new_focal_point, new_upndarray
Updated camera state after applying the azimuth.
- rotate_camera_elevation(position, focal_point, up, angle_deg)[source]#
Tilt the camera up/down about its right axis.
- Parameters:
- position, focal_point, uparray-like
Current camera position, focal point, and up vector.
- angle_degfloat
Elevation angle in degrees (positive tilts up).
- Returns:
- new_position, new_focal_point, new_upndarray
Updated camera state after applying the elevation.
- rotate_camera_roll(position, focal_point, up, angle_deg)[source]#
Apply a roll about the current viewing axis.
- Parameters:
- position, focal_point, uparray-like
Current camera position, focal point, and up vector.
- angle_degfloat
Roll angle in degrees (positive is counter‑clockwise).
- Returns:
- new_position, new_focal_point, new_upndarray
Updated camera state after applying the roll.
NeuXtalViz.models.crystal_structure_tools module#
- class CrystalStructureModel[source]#
Bases:
NeuXtalVizModelModel for crystal structure and space group handling using Mantid.
Wraps a Mantid
crystalsample workspace to manage the crystal structure (lattice, space group, and scatterers), compute the UB matrix, and generate derived crystallographic information such as structure factors, chemical formula, and atom positions.Methods
ab_axes()\(c^*\)-direction in cartesian coordinates.
ab_star_axes()\(c\)-direction in cartesian coordinates.
bc_axes()\(a^*\)-direction in cartesian coordinates.
bc_star_axes()\(a\)-direction in cartesian coordinates.
ca_axes()\(b^*\)-direction in cartesian coordinates.
ca_star_axes()\(b\)-direction in cartesian coordinates.
calculate_F2(h, k, l)Calculate the structure factor and symmetry equivalents of a reflection.
Calculate and set the UB matrix from the current crystal structure.
calculate_camera_parameters(direction, roll)Calculate roll, elevation, and azimuth from camera direction and roll.
Determine which lattice parameters are fixed by the lattice system.
files_exist(files)Check if the specified files exist and are readable.
generate_F2([d_min])Generate unique reflections and their structure factors down to d_min.
Generate symmetry-equivalent atom positions within the unit cell.
generate_hkl_list([d_min])Generate every allowed reflection and its d-spacing down to d_min.
Generate the list of alternative settings (symbols) for a space group.
Generate the list of space groups belonging to a crystal system.
get_UB_from_vectors(u_vector, v_vector)Build a sample-orientation UB matrix from two crystallographic directions, independent of the model's own
self.UB.get_absorption_dict(wavelength[, volume])Compute absorption and scattering parameters for the sample material.
Get the chemical formula and Z parameter of the crystal structure.
Get the crystal system of the current crystal structure.
get_euler_angles(u_vector, v_vector, UB)Compute Euler angles that orient a sample face along given directions.
get_incident_path_length(mesh, UB, u_vector)Sample radius along the incident beam direction.
Get the lattice constants of the current unit cell.
Get the lattice system of the current crystal structure.
get_material_dict(chemical_formula, ...)Build a Mantid material dictionary for the sample.
get_oriented_lattice_parameters()Obtain the oriented lattice parameters.
get_periodic_table(atom)Create a periodic table model for isotope selection of an element.
Get the point group name of the current crystal structure.
Get the list of scatterers of the current crystal structure.
Get the current space group setting (Hermann-Mauguin symbol).
Get the space group of the current crystal structure.
get_transform([reciprocal])Transformation matrix describing the reciprocal or crystal axes.
Normalized orientation matrix (unit a*/b*/c* Cartesian columns) for a given UB matrix.
Get the transformation matrix from fractional to Cartesian coordinates.
Get the volume of the current unit cell.
get_vector(axes_type, ind)Vector corresponding to a particular crystallographic direction.
has_UB(ws)Check if the oriented lattice exists on a workspace.
Check whether the sample workspace has a crystal structure set.
load_CIF(filename)Load a crystal structure from a CIF file and recompute the UB matrix.
orientation_matrix()Return the current UB matrix (orientation matrix).
predict_transmission(hkls, ds, wavelength, ...)Predict the transmission and absorption-weighted path length (T-bar) of every given reflection for a monochromatic rotation experiment.
rotate_camera_azimuth(position, focal_point, ...)Rotate the camera left/right about a global up axis.
rotate_camera_elevation(position, ...)Tilt the camera up/down about its right axis.
rotate_camera_roll(position, focal_point, ...)Apply a roll about the current viewing axis.
Return the triangulated mesh of the sample shape for visualization.
save_ins(filename)Set the sample material and save the crystal structure to an INS file.
set_UB(UB)Update the UB-matrix.
set_crystal_structure(params, space_group, ...)Set the crystal structure on the sample workspace and recompute UB.
Set the sample material from the chemical formula and number density.
set_sample_shape(ws, mat_dict, alpha, beta, ...)Set the ellipsoid sample shape and material on a workspace.
update_lattice_parameters(a, b, c, alpha, ...)Update the lattice parameters, keeping the current setting and atoms.
update_parameters(params)Symmetrize lattice parameters according to the current lattice system.
write_ellipsoid_stl(params)Build a triaxial ellipsoid mesh and save it as a temporary STL file.
- calculate_F2(h, k, l)[source]#
Calculate the structure factor and symmetry equivalents of a reflection.
- Parameters:
- h, k, lfloat
Miller indices of the reflection.
- Returns:
- equivalentslist of V3D
Symmetry-equivalent HKL reflections under the point group.
- dfloat
d-spacing of the reflection.
- F2float
Squared structure factor of the reflection.
- calculate_UB()[source]#
Calculate and set the UB matrix from the current crystal structure.
Computes the UB matrix from the unit cell metric tensor using Cholesky decomposition, sets it on the
crystalworkspace, and stores it on the model viaset_UB().
- constrain_parameters()[source]#
Determine which lattice parameters are fixed by the lattice system.
- Returns:
- paramslist of bool
Six flags, one per lattice parameter in the order
[a, b, c, alpha, beta, gamma], where True indicates the parameter is constrained (dependent on a/alpha) and should be disabled for editing.
- generate_F2(d_min=0.7)[source]#
Generate unique reflections and their structure factors down to d_min.
- Parameters:
- d_minfloat, optional
Minimum d-spacing to generate reflections for (default 0.7).
- Returns:
- hklsnumpy.ndarray
Array of unique HKL indices, sorted by decreasing d-spacing.
- dsnumpy.ndarray
Array of d-spacings corresponding to hkls.
- F2snumpy.ndarray
Array of squared structure factors corresponding to hkls.
- generate_atom_positions()[source]#
Generate symmetry-equivalent atom positions within the unit cell.
For each scatterer, applies the space group’s equivalent positions, wraps into the unit cell, extends to unit cell corners/edges/faces so atoms on cell boundaries are included, and transforms fractional coordinates into Cartesian coordinates.
- Returns:
- atom_dictdict
Dictionary keyed by atom symbol, where each value is a tuple
(coordinates, occupancies, indices): coordinates is a list of 3-element Cartesian coordinates, occupancies is a list of the corresponding site occupancies, and indices is a list of the originating scatterer index for each position.
- generate_hkl_list(d_min=0.7)[source]#
Generate every allowed reflection and its d-spacing down to d_min.
Unlike
generate_F2()(the Factors tab, which reduces to symmetry-unique reflections viagetUniqueHKLsUsingFilter), this returns every symmetry-equivalent allowed reflection via Mantid’sReflectionGenerator.getHKLsUsingFilter– the absorption/transmission prediction is per-reflection (each equivalent has its own Q direction and therefore its own goniometer setting and absorption path), so the full set is needed, not just one representative per family.Absorption is centrosymmetric though: reversing (h,k,l) to (-h,-k,-l) swaps the incident/outgoing beam directions through the sample, and an ellipsoid (like every shape supported here) is itself inversion-symmetric about its center, so T(hkl) == T(-hkl) exactly. Only one reflection from each such Friedel pair is kept (whichever has the first nonzero index positive), halving the simulation work for no loss of information.
- Parameters:
- d_minfloat, optional
Minimum d-spacing (default 0.7).
- Returns:
- hkls(N, 3) ndarray
Miller indices of every allowed reflection, one per centrosymmetric (Friedel) pair.
- ds(N,) ndarray
d-spacing of each reflection.
- static generate_settings_from_space_group(sg)[source]#
Generate the list of alternative settings (symbols) for a space group.
A static method (uses no instance state) – see
generate_space_groups_from_crystal_system().- Parameters:
- sgstr
Space group formatted as
"{number}: {symbol}", as returned bygenerate_space_groups_from_crystal_system()orget_space_group().
- Returns:
- settingslist of str
Subscribed space group symbols (settings) sharing the same space group number as sg.
- static generate_space_groups_from_crystal_system(system)[source]#
Generate the list of space groups belonging to a crystal system.
A static method (uses no instance state) so it can be reused by other tools (e.g. the Volume Slicer’s delta-PDF Transform tab) without instantiating a full
CrystalStructureModel, which would create/clobber its own"crystal"sample workspace.- Parameters:
- systemstr
Name of the crystal system (e.g.
"Cubic","Hexagonal"), matching a member ofPointGroup.CrystalSystem.
- Returns:
- space_grouplist of str
Space groups formatted as
"{number}: {symbol}", one per unique space group number in the crystal system.
- get_UB_from_vectors(u_vector, v_vector)[source]#
Build a sample-orientation UB matrix from two crystallographic directions, independent of the model’s own
self.UB.Distinct from
get_euler_angles()(which orients the shape mesh relative to whatever orientation the crystal already has): this defines the crystal’s own orientation for the absorption prediction –u_vectoris aligned with the local z axis and, together withv_vector, fixes an orthonormal frame U, independent of the arbitrary Busing-Levy default incalculate_UB(). B comes directly from the lattice metric tensor, not fromself.UB.- Parameters:
- u_vector3-element 1d array-like
Crystallographic direction to align with the local z axis.
- v_vector3-element 1d array-like
Crystallographic direction used together with u_vector to define the orientation plane.
- Returns:
- UB(3, 3) ndarray
Orientation matrix
U @ B, or None if the vectors are collinear.
- get_absorption_dict(wavelength, volume=None)[source]#
Compute absorption and scattering parameters for the sample material.
- Parameters:
- wavelengthfloat
Incident wavelength, in Angstrom (the absorption cross section is wavelength-dependent).
- volumefloat, optional
Sample volume (cm^3), for shapes whose Mantid
Sampleobject can’t report its own volume – in practice only the ellipsoid (aMeshObject, which exposes novolume()method), whose volume is instead computed from the PyVista mesh inwrite_ellipsoid_stl(). If None, the volume is read directly from the sample shape (CSG shapes only).
- Returns:
- abs_dictdict
Dictionary with keys:
sigma_a: float, absorption cross section (barn).sigma_s: float, total scattering cross section (barn).mu_a: float, linear absorption coefficient (1/cm).mu_s: float, linear scattering coefficient (1/cm).N: float, total number of atoms.M: float, relative molecular mass (g/mol).n: float, effective number density (1/Angstrom^3).rho: float, mass density (g/cm^3).V: float, sample volume (cm^3).m: float, sample mass (g).
- get_chemical_formula_z_parameter()[source]#
Get the chemical formula and Z parameter of the crystal structure.
Groups scatterers by atom type, accounting for symmetry multiplicity and site occupancy, to build the reduced chemical formula and the number of formula units per unit cell.
- Returns:
- chemical_formulastr
Chemical formula with per-atom subscripts, hyphen-separated for multi-element formulas.
- Zint
Number of formula units per unit cell (greatest common divisor of the per-atom site multiplicities).
- get_crystal_system()[source]#
Get the crystal system of the current crystal structure.
- Returns:
- crystal_systemstr
Name of the crystal system (e.g.
"Cubic").
- get_euler_angles(u_vector, v_vector, UB)[source]#
Compute Euler angles that orient a sample face along given directions.
The u_vector and v_vector are Miller index / fractional coordinate directions that are transformed to Cartesian coordinates via
UBto build a rotation matrix, which is then decomposed into ZYX Euler angles via Mantid’s ownGoniometer(matchinggarnet.reduction.sample.SampleMaterial.set_shapeexactly, rather than scipy’s rotation decomposition, so the angles are guaranteed to be in the convention Mantid’s ownLoadSampleShape(XDegrees/YDegrees/ZDegrees) expects).Note this takes an explicit
UBrather than readingself.UB: the shape must be oriented relative to the same orientation used for the rest of the absorption prediction (typically the sample-orientation UB fromget_UB_from_vectors()), not the model’s own default (Busing-Levy) orientation, or the shape and the beam/goniometer geometry would be computed in inconsistent frames.- Parameters:
- u_vector3-element 1d array-like
Crystallographic direction to align with the sample’s primary (height/thickness) axis.
- v_vector3-element 1d array-like
Crystallographic direction used together with u_vector to define the orientation plane.
- UB(3, 3) ndarray
Orientation matrix to transform u_vector/v_vector into Cartesian coordinates.
- Returns:
- alpha, beta, gammafloat
Rotation angles in degrees about the X, Y, and Z axes respectively, or None if the vectors are collinear.
- get_incident_path_length(mesh, UB, u_vector)[source]#
Sample radius along the incident beam direction.
Matches
AddAbsorptionWeightedPathLengths’s single-path formula (see its C++ source): the total single-path length is the sample’s radius along the outgoing direction (per point, already used directly as|vertex|when coloring the mesh) plus a constant term – the sample’s radius along the fixed incident beam direction. Found by looking up the mesh’s own vertex closest to the beam direction (rather than an independent analytic/rotation-matrix calculation), so it is guaranteed self-consistent with the mesh actually being drawn.- Parameters:
- mesh(N, 3, 3) ndarray
Triangle vertex coordinates, from
sample_mesh().- UB(3, 3) ndarray
Sample orientation matrix, from
get_UB_from_vectors()(orself.UB).- u_vector3-element 1d array-like
Beam-direction crystallographic direction (the sample U vector).
- Returns:
- r_incidentfloat
Sample radius (cm) along the incident beam direction.
- get_lattice_constants()[source]#
Get the lattice constants of the current unit cell.
- Returns:
- paramstuple of float
Lattice parameters
(a, b, c, alpha, beta, gamma).
- get_lattice_system()[source]#
Get the lattice system of the current crystal structure.
- Returns:
- lattice_systemstr
Name of the lattice system (e.g.
"Rhombohedral").
- get_material_dict(chemical_formula, z_parameter, volume)[source]#
Build a Mantid material dictionary for the sample.
- Parameters:
- chemical_formulastr
Chemical formula of the sample material.
- z_parameterfloat
Number of formula units per unit cell.
- volumefloat
Unit cell volume in Angstrom^3.
- Returns:
- mat_dictdict
Dictionary with keys
"ChemicalFormula","ZParameter", and"UnitCellVolume", suitable for theMaterialargument of Mantid’sSetSamplealgorithm.
- get_periodic_table(atom)[source]#
Create a periodic table model for isotope selection of an element.
- Parameters:
- atomstr
Element or isotope symbol to initialize the periodic table model with.
- Returns:
- modelPeriodicTableModel
Periodic table model for selecting an isotope of atom.
- get_point_group_name()[source]#
Get the point group name of the current crystal structure.
- Returns:
- point_group_namestr
Name of the point group (e.g.
"2/m (unique axis b)").
- get_scatterers()[source]#
Get the list of scatterers of the current crystal structure.
- Returns:
- scattererslist of list
List of scatterers, each formatted as
[atom, x, y, z, occupancy, Uiso], where atom is a str and the remaining values are floats.
- get_setting()[source]#
Get the current space group setting (Hermann-Mauguin symbol).
- Returns:
- settingstr
Hermann-Mauguin symbol of the current space group setting.
- get_space_group()[source]#
Get the space group of the current crystal structure.
- Returns:
- space_groupstr
Space group formatted as
"{number}: {symbol}".
- get_transform_from_UB(UB)[source]#
Normalized orientation matrix (unit a*/b*/c* Cartesian columns) for a given UB matrix.
Same normalization as the base model’s
get_transform, but operating on a caller-suppliedUB(e.g. fromget_UB_from_vectors()) instead ofself.UB– used to orient the a*/b*/c* arrows drawn next to the absorption sample without touching the model’s own stored orientation (which the Structure tab’s unit-cell view depends on).- Parameters:
- UB(3, 3) ndarray
Orientation matrix.
- Returns:
- T(3, 3) ndarray
UBwith each column normalized to unit length.
- get_unit_cell_transform()[source]#
Get the transformation matrix from fractional to Cartesian coordinates.
- Returns:
- Anumpy.ndarray
3x3 upper-triangular transformation matrix obtained from the Cholesky decomposition of the unit cell metric tensor.
- get_unit_cell_volume()[source]#
Get the volume of the current unit cell.
- Returns:
- volumefloat
Unit cell volume.
- has_crystal_structure()[source]#
Check whether the sample workspace has a crystal structure set.
- Returns:
- has_structurebool
True if the
crystalworkspace sample has a crystal structure, False otherwise.
- load_CIF(filename)[source]#
Load a crystal structure from a CIF file and recompute the UB matrix.
- Parameters:
- filenamestr
Path to the CIF file to load.
- predict_transmission(hkls, ds, wavelength, shape_params, mat_dict, alpha, beta, gamma, UB)[source]#
Predict the transmission and absorption-weighted path length (T-bar) of every given reflection for a monochromatic rotation experiment.
Builds a
LeanElasticPeakpeaks workspace with one peak per hkl (Q = 2*pi*UB*hkl, using the givenUB), each given its own unique run number (each peak is an independent simulated “setting”), computes a goniometer setting for each via Mantid’sHFIRCalculateGoniometer(constant wavelength, vertical-axis rotation – no user-specified goniometer axes are needed), drops any reflection whose goniometer matrix comes back NaN (not reachable by a single vertical-axis rotation at this wavelength – kept in the result as NaN rows rather than silently dropped), sets the ellipsoid sample shape/material, then runs Mantid’sAddAbsorptionWeightedPathLengths(Monte Carlo) to get T-bar per peak and derives the transmissionT = exp(-mu * Tbar).- Parameters:
- hkls(N, 3) ndarray
Miller indices, from
generate_hkl_list().- ds(N,) ndarray
d-spacing of each reflection, from
generate_hkl_list().- wavelengthfloat
Incident wavelength, in Angstrom.
- shape_paramslist of float
Ellipsoid thickness, width, and height, in mm.
- mat_dictdict
Material dictionary from
get_material_dict().- alpha, beta, gammafloat
Shape orientation Euler angles from
get_euler_angles()(shape U/V vectors).- UB(3, 3) ndarray
Sample orientation matrix used for
Q = 2*pi*UB*hkl, fromget_UB_from_vectors()(sample U/V vectors), orself.UBif the sample U/V vectors weren’t set.
- Returns:
- hkls(M, 3) ndarray
Miller indices, sorted by decreasing d-spacing then increasing h, k, l.
- ds(M,) ndarray
d-spacing of each reflection.
- Ts(M,) ndarray
Transmission of each reflection (NaN if unreachable at this wavelength).
- Tbars(M,) ndarray
Absorption-weighted path length (cm) of each reflection (NaN if unreachable at this wavelength).
- volumefloat
Ellipsoid volume, in cm^3.
- sample_mesh()[source]#
Return the triangulated mesh of the sample shape for visualization.
- Returns:
- meshndarray
Array of triangle vertices describing the sample shape mesh, scaled from meters to centimeters.
- save_ins(filename)[source]#
Set the sample material and save the crystal structure to an INS file.
- Parameters:
- filenamestr
Path of the INS file to write.
- set_crystal_structure(params, space_group, scatterers)[source]#
Set the crystal structure on the sample workspace and recompute UB.
- Parameters:
- paramslist of float
Lattice parameters
[a, b, c, alpha, beta, gamma].- space_groupstr
Space group symbol or setting (Hermann-Mauguin symbol) used to build the
CrystalStructure.- scattererslist of list
List of scatterers, each formatted as
[atom, x, y, z, occupancy, Uiso].
- set_material()[source]#
Set the sample material from the chemical formula and number density.
Computes the chemical formula and Z parameter from the current crystal structure and derives the sample number density from the unit cell volume, then applies it to the
crystalworkspace.
- set_sample_shape(ws, mat_dict, alpha, beta, gamma, ellipsoid_stl)[source]#
Set the ellipsoid sample shape and material on a workspace.
Loads the mesh built by
write_ellipsoid_stl()via Mantid’sLoadSampleShape(rotated by alpha/beta/gamma about X, Y, Z in that order), then sets the material separately.LoadSampleShaperequires a workspace with a real instrument (specifically a “sample holder” component) – a bareLeanElasticPeakworkspace has none, so the mesh is instead loaded onto a throwaway scratch workspace (which does have a default instrument) and its resultingSample(shape) is copied ontowsviasetSample.- Parameters:
- wsstr
Name of the workspace to set the sample on.
- mat_dictdict
Material dictionary from
get_material_dict().- alpha, beta, gammafloat
Rotation angles in degrees for the ellipsoid mesh’s
LoadSampleShapeorientation.- ellipsoid_stlstr
Path to the ellipsoid STL file from
write_ellipsoid_stl().
- update_lattice_parameters(a, b, c, alpha, beta, gamma)[source]#
Update the lattice parameters, keeping the current setting and atoms.
- Parameters:
- a, b, cfloat
Lattice constants.
- alpha, beta, gammafloat
Lattice angles in degrees.
- update_parameters(params)[source]#
Symmetrize lattice parameters according to the current lattice system.
Copies dependent parameters (e.g. b, c from a for cubic systems) so that the returned parameters are consistent with the lattice system’s constraints.
- Parameters:
- paramsarray-like
Lattice parameters
[a, b, c, alpha, beta, gamma].
- Returns:
- paramslist of float
Lattice parameters with dependent values overwritten to match their independent counterparts per the lattice system.
- write_ellipsoid_stl(params)[source]#
Build a triaxial ellipsoid mesh and save it as a temporary STL file.
Mantid’s shape system (CSG XML /
SetSample) has no native ellipsoid primitive, so the ellipsoid is instead built as a unit icosphere non-uniformly scaled to the requested semi-axis lengths, then loaded as the sample shape viaset_sample_shape()’sLoadSampleShapecall.- Parameters:
- paramslist of float
Thickness, width, and height, in mm.
- Returns:
- pathstr
Path to the written temporary
.stlfile. The caller is responsible for deleting it onceLoadSampleShapehas consumed it.- volumefloat
Ellipsoid volume in cm^3 (from the PyVista mesh directly – Mantid’s
MeshObjectshape has novolume()method, so this is needed byget_absorption_dict()).
NeuXtalViz.models.experiment_planner module#
- class CrystalPlan(use, opt, axes, limits, wavelength, d_min, point_group, lattice_centering)[source]#
Bases:
objectGenetic algorithm for optimizing experiment plans in NeuXtalViz.
This class generates, recombines, and evaluates sets of orientations and settings to maximize experiment coverage and completeness.
Methods
crossover(n_orient, best, selection)Produce the next generation's gene workspaces via elitism and crossover.
fitness(peaks[, n])Score a peaks workspace by resolution-weighted completeness.
generation(i, j)Randomly generate one orientation "gene" and predict its peaks.
initialization(n_orient, n_indiv)Create the initial population of individuals for the genetic algorithm.
mutation(n_orient, n_indiv, mutation_rate)Randomly mutate genes of the current generation and re-evaluate fitness.
optimize(n_orient, n_indiv, n_gener, ...)Run the genetic algorithm to find an optimized set of orientations.
recombination(n_orient, j)Combine an individual's per-orientation predicted peaks into one workspace.
- crossover(n_orient, best, selection)[source]#
Produce the next generation’s gene workspaces via elitism and crossover.
Clones the gene workspaces of the elite individuals in
bestunchanged, then for each parent pair inselectionproduces offspring by swapping orientation genes between the two parents (a single split point whenn_orient > 1, or independent copies of each parent whenn_orient == 1). Renames all resulting workspaces with the"peak"prefix and rebuildsself.genesto reflect the new generation’s gene angles.- Parameters:
- n_orientint
Number of orientations (goniometer settings) per individual.
- bestarray-like of int
Indices of the elite individuals to carry over unchanged.
- selectionlist of array-like
List of parent-index pairs selected for crossover.
- fitness(peaks, n=5)[source]#
Score a peaks workspace by resolution-weighted completeness.
Splits the d-spacing range
[self.d_min, self.d_max]inton - 1shells (evenly spaced in1/d**2), computes the reflection completeness in each shell viaCountReflections, and sums the completeness values weighted so that higher-resolution (smaller d-spacing) shells count more.- Parameters:
- peaksstr
Name of the peaks workspace to evaluate.
- nint, optional
Number of d-spacing shell boundaries (giving
n - 1shells). Default is 5.
- Returns:
- fitfloat
Resolution-weighted completeness fitness score.
- generation(i, j)[source]#
Randomly generate one orientation “gene” and predict its peaks.
Draws a random goniometer angle within
self.limitsfor each non-fixed axis, records the drawn angles inself.genesunder the key"peaks_{i}_{j}", sets the instrument goniometer to those angles, and predicts peaks into a workspace of that name (tagged with run numberi + self.offset).- Parameters:
- iint
Orientation index within an individual.
- jint
Individual index within the population.
- initialization(n_orient, n_indiv)[source]#
Create the initial population of individuals for the genetic algorithm.
For each of
n_indivindividuals, randomly generatesn_orientorientation genes (seegeneration()), combines their predicted peaks into one workspace per individual (seerecombination()), and evaluates its fitness.- Parameters:
- n_orientint
Number of orientations (goniometer settings) per individual.
- n_indivint
Number of individuals in the population.
- Returns:
- fitndarray
Fitness score of each individual in the initial population.
- mutation(n_orient, n_indiv, mutation_rate)[source]#
Randomly mutate genes of the current generation and re-evaluate fitness.
For each individual, each orientation gene has probability
mutation_rateof being replaced by a freshly randomized orientation (seegeneration()); unchanged genes are left in place. Recombines each individual’s genes (seerecombination()) and recomputes its fitness.- Parameters:
- n_orientint
Number of orientations (goniometer settings) per individual.
- n_indivint
Number of individuals in the population.
- mutation_ratefloat
Probability, in
[0, 1], that any given gene is mutated.
- Returns:
- fitndarray
Fitness score of each individual after mutation.
- optimize(n_orient, n_indiv, n_gener, n_elite, mutation_rate)[source]#
Run the genetic algorithm to find an optimized set of orientations.
Initializes a population (
initialization()), then forn_genergenerations ranks individuals by fitness, carries the topn_eliteforward unchanged, fills the remainder of the population via fitness-proportional selection and crossover (crossover()), and applies random mutation (mutation()). Returns the orientation angles of the best-scoring individual from the final generation, and clones its combined peaks workspace to"combined".- Parameters:
- n_orientint
Number of orientations (goniometer settings) per individual.
- n_indivint
Number of individuals in the population.
- n_generint
Number of generations to evolve.
- n_eliteint
Number of top individuals carried over unchanged each generation.
- mutation_ratefloat
Probability, in
[0, 1], that any given gene is mutated each generation.
- Returns:
- valueslist
Orientation angle list for each of the
n_orientgoniometer settings of the best individual found.
- recombination(n_orient, j)[source]#
Combine an individual’s per-orientation predicted peaks into one workspace.
Sequentially combines the
n_orientgene peak workspaces"peaks_{i}_{j}"(foriinrange(n_orient)), starting from the base"crystal_plan"peaks workspace, into a single peaks workspace named"peaks_{j}".- Parameters:
- n_orientint
Number of orientations (goniometer settings) for individual
j.- jint
Individual index within the population.
- class ExperimentModel[source]#
Bases:
NeuXtalVizModelModel for managing experiment planning, instrument setup, and crystallographic calculations in NeuXtalViz.
This class provides methods for initializing instruments, handling calibration and mask files, managing sample and plan workspaces, performing peak prediction, and calculating experiment statistics.
Methods
ab_axes()\(c^*\)-direction in cartesian coordinates.
ab_star_axes()\(c\)-direction in cartesian coordinates.
add_mesh(mesh_angles, wavelength, d_min, ...)Add one orientation per point of a regular goniometer-angle mesh.
add_orientation(angles, wavelength, d_min, rows)Predict and store peaks for a single goniometer orientation.
add_plane(hkl_1, hkl_2, wavelength, d_min, ...)Add orientations that keep the scattering plane defined by hkl_1/hkl_2 accessible, spanning max_deg in rotation about the plane normal.
bc_axes()\(a^*\)-direction in cartesian coordinates.
bc_star_axes()\(a\)-direction in cartesian coordinates.
ca_axes()\(b^*\)-direction in cartesian coordinates.
ca_star_axes()\(b\)-direction in cartesian coordinates.
calculate_camera_parameters(direction, roll)Calculate roll, elevation, and azimuth from camera direction and roll.
calculate_footprint(wavelength, d_min[, n])Build the reciprocal-space "footprint" workspace covering the instrument's detector solid angle over the wavelength band.
calculate_harmonics(hkl, wavelength, ...)Find harmonic reflections overlapping a given reflection's beam.
calculate_hkl_limits(d_min)Calculate maximum Miller indices reachable at a minimum d-spacing.
calculate_individual_peak(hkl, wavelength, ...)Scan goniometer settings for a single HKL and keep valid ones.
calculate_projections(hkl_1, hkl_2)Compute orthonormal u, v, w axes for a scattering plane.
calculate_rotations(angles, U, V, W, normal, ...)Compute (or reuse) reciprocal-space coverage over a set of goniometer orientations and slice it onto an HKL plane.
calculate_statistics(point_group, ...)Compute per-shell and cumulative completeness/redundancy statistics.
Reset the
combinedpeaks workspace to be empty.compute_plane_angles(hkl_1, hkl_2, axes, ...)Return the deduplicated motor-angle array for the scattering plane defined by hkl_1 / hkl_2 without modifying any workspace.
copy_UB()Copy the UB matrix from the
coverageworkspace into the model's cached UB matrix (NeuXtalVizModel.UB).copy_to_instrument_pc(filename)Copy a file to the TOPAZ instrument PC data share, if applicable.
create_plan(table)Build the
plantable workspace from an experiment plan tuple.create_sample(instrument, mode, UB, ...)Create the
sampleworkspace and record experiment settings.crystal_plan(*args)Construct a
CrystalPlangenetic-algorithm optimizer.delete_angles(rows)Delete plan rows/orientations from the
combinedworkspace and renumber the remaining runs to be contiguous.downsample(arr[, n])Reduce a sequence to at most
nrepresentative elements.extract_data(ws)Extract bin-center coordinate grids, signal, and errors from an MD workspace.
Build a mesh of detector-bank quadrilaterals for 3D rendering.
files_exist(files)Check if the specified files exist and are readable.
generate_axes(axes, polarities)Build and cache
SetGoniometeraxis-string templates.generate_table(row)Build a sorted HKL/d-spacing/wavelength table for one plan row.
get_UB()Get the UB matrix currently set on the
coverageworkspace.get_angles(gamma, nu)Look up the cached goniometer setting nearest a detector position.
get_autoreduce_instrument(instrument)Get the autoreduce instrument definition file path for a given instrument.
get_axes_polarities(instrument, mode)Get the goniometer rotation axes and their polarities for a mode.
get_calibration_file_path(instrument)Get the shared calibration directory for a given instrument.
get_counting_options(instrument)Get the counting condition options for an instrument.
get_coverage_info(point_group, ...[, row])Build reciprocal-space point-cloud data for the coverage plot.
get_crystal_system_point_groups(crystal_system)Get the point groups belonging to a crystal system.
get_goniometer_axes(instrument, mode)Get Mantid
SetGoniometeraxis-string templates for a mode.get_goniometers(instrument, mode)Get goniometer axis names with their angle limits for a mode.
Compute (or return cached) 2D detector-coverage occupancy image.
get_instrument_directory(instrument)Get the file path for a given instrument.
get_instrument_name(instrument)Get the short Mantid instrument name for an instrument identifier.
Extract detector-frame angles and HKLs for the current row's peaks.
get_modes(instrument)Get the available goniometer modes for an instrument.
get_motors(instrument)Get auxiliary motor names and default values for an instrument.
get_oriented_lattice_parameters()Obtain the oriented lattice parameters.
Look up a cached Laue peak (and any co-located peaks) by index.
get_peak_selection(gamma, nu)Find the cached Laue peak nearest a given detector position.
get_point_group_centering(point_group)Get the allowed lattice centerings for a point group.
get_scan_log(instrument)Get the process-variable/title log name for an instrument.
get_setting(free_angles, limits)Combine free (variable) angles with fixed-limit angles into a full per-axis goniometer setting.
get_symmetry(point_group, centering)Coerce point group and centering to plain strings.
get_transform([reciprocal])Transformation matrix describing the reciprocal or crystal axes.
get_vanadium_file_path(instrument)Get the shared vanadium directory for a given instrument.
get_vector(axes_type, ind)Vector corresponding to a particular crystallographic direction.
get_wavelength(instrument)Get the default wavelength (range) for an instrument.
grouping_list(detectors, cols, rows, c, r)Build a Mantid GroupingPattern string from a detectors table.
has_UB()Check whether the
coverageworkspace has an oriented lattice.hsl_to_rgb(hue, saturation, lightness)Convert HSL color values to RGB.
individual_peak(hkl, wavelength, axes, ...)Find goniometer settings that bring a peak (or its symmetry equivalents) into the detector range.
initialize_instrument(instrument, logs, cal, ...)Build the
instrument,goniometer, and related workspaces.load_UB(filename)Load a UB matrix from an ISAW UB file onto the
coverageworkspace and update the model's cached UB matrix.load_experiment(filename)Load a previously saved experiment (plan + sample) from Nexus.
orientation_matrix()Return the current UB matrix (orientation matrix).
Delete the
instrument,combined,filtered, andfootprintworkspaces if they exist, and clear the cached instrument background image.reslice_last(U, V, W, normal, value, thickness)Re-slice the most-recently computed coverage workspace without rebuilding the footprint or coverage map.
rotate_camera_azimuth(position, focal_point, ...)Rotate the camera left/right about a global up axis.
rotate_camera_elevation(position, ...)Tilt the camera up/down about its right axis.
rotate_camera_roll(position, focal_point, ...)Apply a roll about the current viewing axis.
save_experiment(filename)Save the
plan(andsample, if present) workspaces to Nexus.save_plan(filename)Write the active (used) rows of the
plantable to a CSV file.select_scan_near_equator(Rs, motor_angles, ...)Select, for each of a set of scan angles about
w, the goniometer setting fromRsthat best matches that orientation while keeping the scattering plane near the equatorial plane.set_UB(UB)Update the UB-matrix.
set_path(filename)Remember the directory of a file for use as the default directory.
simultaneous_peaks(hkl_1, hkl_2, wavelength, ...)Find goniometer settings placing two reflections on detectors simultaneously.
simultaneous_peaks_hkl(hkl_1, hkl_2, ...[, step])Scan goniometer settings for a pair of HKLs and keep settings where both reflections simultaneously satisfy the wavelength range and land on active detectors.
swap_angles(rows)Swap the run numbers of two plan rows/orientations.
to_index(Q, Q_max, scale, n)Convert Q-coordinate value(s) to a clipped voxel-grid index.
update_goniometer_motors(limits, motors, ...)Record goniometer motor limits and auxiliary motor/file settings as sample logs so they can be restored by
load_experiment().update_sample(crytsal_system, point_group, ...)Record crystal-symmetry information as sample logs.
validate_projection(proj)Validate and unpack a 3x3 HKL projection matrix.
- add_mesh(mesh_angles, wavelength, d_min, rows, free_angles, all_angles)[source]#
Add one orientation per point of a regular goniometer-angle mesh.
Builds an N-dimensional grid over the free goniometer axes and calls
add_orientation()for every grid point.- Parameters:
- mesh_anglestuple
(limits, ns)wherelimitsis the per-axis (min, max) angle range andnsis the per-axis number of grid points.- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom).
- d_minfloat
Minimum d-spacing (Angstrom).
- rowsint
Row-number offset; grid point
iis stored as run numberrows + iin thecombinedworkspace.- free_angleslist of str
Names of the axes that vary across the mesh, in the order their values should be reported.
- all_angleslist of str
Names of all goniometer axes, in axis order (used to map
free_anglesnames to grid-point indices).
- Returns:
- valueslist of ndarray
For each mesh point, the values of the
free_anglesaxes at that point.
- add_orientation(angles, wavelength, d_min, rows)[source]#
Predict and store peaks for a single goniometer orientation.
Sets the goniometer to
angleson theinstrumentworkspace, predicts peaks with Mantid’sPredictPeaks, removes duplicate and dead/masked-detector peaks, tags them with run numberrows, and merges them into thecombinedworkspace.- Parameters:
- anglessequence of float
Per-axis goniometer angle values, formatted into the cached
self.axestemplates.- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom). If min and max are equal, a +/-2.5% band is used instead.
- d_minfloat
Minimum d-spacing (Angstrom).
- rowsint
Run number to assign to the predicted peaks – identifies this orientation/row in the
combinedworkspace. May be an existing row index being recalculated, or one past the last existing row to append a new orientation.
- add_plane(hkl_1, hkl_2, wavelength, d_min, rows, free_angles, all_angles, axes, polarities, limits, max_deg=360, n_steps=360, step=1)[source]#
Add orientations that keep the scattering plane defined by hkl_1/hkl_2 accessible, spanning max_deg in rotation about the plane normal.
Returns the list of free-angle values (same format as add_mesh).
- Parameters:
- hkl_1, hkl_2array-like, shape (3,)
Two in-plane Miller-index vectors defining the scattering plane.
- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom).
- d_minfloat
Minimum d-spacing (Angstrom).
- rowsint
Row-number offset; the i-th selected orientation is stored as run number
rows + iin thecombinedworkspace.- free_angleslist of str
Names of the axes that vary, in the order their values should be reported.
- all_angleslist of str
Names of all goniometer axes, in axis order.
- axeslist
Per-axis (x, y, z) rotation-axis direction components.
- polaritieslist
Per-axis rotation sense/polarity.
- limitssequence of (float, float)
Per-axis (min, max) angle limits, in degrees.
- max_degfloat, optional
Total scan range about the plane normal, in degrees. Default is 360.
- n_stepsint, optional
Number of scan steps over
max_deg. Default is 360.- stepfloat, optional
Base angular step size for
_calculate_matrices(), in degrees. Default is 1.
- Returns:
- valueslist of ndarray
For each selected orientation, the values of the
free_anglesaxes at that orientation.
- calculate_footprint(wavelength, d_min, n=200)[source]#
Build the reciprocal-space “footprint” workspace covering the instrument’s detector solid angle over the wavelength band.
For every unmasked detector pixel, traces a line in Q-space (voxelized on an
n``x``n``x``ngrid out toQ_max) from the minimum to maximum incident wavenumber, and marks the traversed voxels. Creates and populates the"footprint"MD workspace; does nothing if it already exists.- Parameters:
- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom).
- d_minfloat
Minimum d-spacing (Angstrom), used to set the Q-space extent (
Q_max = 2 * pi / d_min).- nint, optional
Number of voxels along each axis of the footprint grid. Default is 200.
- calculate_harmonics(hkl, wavelength, wavelength_band)[source]#
Find harmonic reflections overlapping a given reflection’s beam.
- Parameters:
- hklarray-like, shape (3,)
Miller index of the reference reflection.
- wavelengthfloat
Wavelength (Angstrom) at which the reference reflection is observed.
- wavelength_band2-tuple of float
Minimum and maximum wavelength (Angstrom) of the instrument’s usable band.
- Returns:
- hkl_harmonicslist
For each harmonic order, the reduced-integer HKL if it is an exact (order-1) harmonic, otherwise None.
- lamda_harmonicslist of float
Wavelength (Angstrom) at which each corresponding harmonic order is observed.
- calculate_hkl_limits(d_min)[source]#
Calculate maximum Miller indices reachable at a minimum d-spacing.
- Parameters:
- d_minfloat
Minimum d-spacing (in Angstrom).
- Returns:
- h_max, k_max, l_maxint
Maximum h, k, l indices consistent with
d_mingiven the oriented lattice on thecoverageworkspace.
- calculate_individual_peak(hkl, wavelength, axes, polarities, limits, step=1)[source]#
Scan goniometer settings for a single HKL and keep valid ones.
Adds a peak with the given HKL to the
peakworkspace, rotates its Q vector through every goniometer setting produced by_calculate_matrices(), and keeps only settings where the resulting wavelength is in range and the scattered beam does not fall on an already-masked/dead detector.- Parameters:
- hklarray-like, shape (3,)
Miller index of the target reflection.
- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom). If min and max are equal, a +/-2.5% band is used instead.
- axeslist
Per-axis (x, y, z) rotation-axis direction components.
- polaritieslist
Per-axis rotation sense/polarity.
- limitssequence of (float, float)
Per-axis (min, max) angle limits, in degrees.
- stepfloat, optional
Base angular step size, in degrees. Default is 1.
- Returns:
- settingsndarray, shape (n_valid, n_axes)
Per-axis angle values for each valid goniometer setting.
- valuestuple of ndarray
(gamma, nu, lamda, d)– detector gamma/nu angles (degrees), wavelength (Angstrom), and d-spacing (Angstrom; scalar, same for all settings) for each valid setting.
- calculate_projections(hkl_1, hkl_2)[source]#
Compute orthonormal u, v, w axes for a scattering plane.
- Parameters:
- hkl_1, hkl_2array-like, shape (3,)
Two in-plane Miller-index vectors defining the scattering plane.
- Returns:
- u, v, wndarray, shape (3,)
Orthonormal basis: u along hkl_1 in Q-space, w = u × v (normal), v recomputed to ensure right-handed orthonormal frame.
- calculate_rotations(angles, U, V, W, normal, value, thickness, mesh, point_group='1', use_symmetry=False, factor=2)[source]#
Compute (or reuse) reciprocal-space coverage over a set of goniometer orientations and slice it onto an HKL plane.
Builds a coverage MD workspace (cached under a name derived from the goniometer axes/angles and, if symmetry is applied, the point group) by rotating the footprint into reciprocal space for each orientation in
anglesand, ifuse_symmetryis True, applying the Laue point-group symmetry equivalents. If a matching coverage workspace already exists, it is reused instead of being recomputed. The resulting 3D coverage is then sliced onto the requested HKL plane via_slice_meshmap().- Parameters:
- anglesarray-like
Either a list of goniometer angle tuples (if
meshis False), or(limits, ns)describing a grid of angles to mesh over (ifmeshis True).- U, V, Wndarray, shape (3,)
HKL projection basis vectors defining the slice plane.
- normallist of int
One-hot vector selecting which of U, V, W is the slice normal.
- valuefloat
Slice position along the normal direction.
- thicknessfloat
Slice half-thickness along the normal direction.
- meshbool
If True,
anglesis(limits, ns)and a meshgrid of goniometer angles is generated; if False,anglesis already an explicit list of angle tuples.- point_groupstr, optional
Point group symbol used to generate symmetry equivalents when
use_symmetryis True. Default is “1”.- use_symmetrybool, optional
Whether to fold in Laue point-group symmetry equivalents when accumulating coverage. Default is False.
- factorint, optional
Upsampling factor applied to the coverage array along each axis before binning into the MD workspace. Default is 2.
- Returns:
- slice_dictdict
Slice dictionary as returned by
_slice_meshmap().
- calculate_statistics(point_group, lattice_centering, use, d_min)[source]#
Compute per-shell and cumulative completeness/redundancy statistics.
Filters the
combinedworkspace down to the active rows, computes overall and per-resolution-shell statistics (both with and without point-group symmetry applied), and computes the row-by-row cumulative statistics via_cumulative_stats(). Also builds themissingworkspace of symmetry-predicted but unobserved reflections.- Parameters:
- point_groupstr
Point group symbol.
- lattice_centeringstr
Lattice centering symbol.
- uselist of bool
Per-row flag (one per plan row/run number) indicating whether that orientation’s peaks should be included.
- d_minfloat
Minimum d-spacing (Angstrom).
- Returns:
- symtuple
(shel_sym, comp_sym, mult_sym, refl_sym)– per-shell labels, completeness (%), redundancy, and unique-reflection counts with point-group symmetry applied (first entry is the “Overall” row).- asymtuple
Same layout as
symbut computed in point group “1” (no symmetry applied).- cumsymtuple
(x, comp_cumsym, mult_cumsym, refl_cumsym)– row numbers and cumulative symmetric completeness/redundancy/unique counts as a function of row.- cumasymtuple
(x, comp_cumasym, mult_cumasym, refl_cumasym)– same ascumsymbut without symmetry applied.Returns None instead if the
combinedworkspace does not exist or has no peaks after filtering to the active rows.
- compute_plane_angles(hkl_1, hkl_2, axes, polarities, limits, max_deg=360, n_steps=60, step=1, n_eq=(0, 1, 0))[source]#
Return the deduplicated motor-angle array for the scattering plane defined by hkl_1 / hkl_2 without modifying any workspace.
Settings are chosen to keep the scattering plane close to the equatorial plane (defined by n_eq) while scanning around the plane normal.
- Parameters:
- hkl_1, hkl_2array-like, shape (3,)
Two in-plane Miller-index vectors defining the scattering plane.
- axeslist
Per-axis (x, y, z) rotation-axis direction components.
- polaritieslist
Per-axis rotation sense/polarity.
- limitssequence of (float, float)
Per-axis (min, max) angle limits, in degrees.
- max_degfloat, optional
Total scan range about the plane normal, in degrees. Default is 360.
- n_stepsint, optional
Number of scan steps over
max_deg. Default is 60.- stepfloat, optional
Base angular step size for
_calculate_matrices(), in degrees. Default is 1.- n_eq3-tuple of float, optional
Direction defining the equatorial plane normal. Default is
(0, 1, 0).
- Returns:
- unique_angleslist of ndarray, shape (n_axes,)
One entry per unique goniometer setting selected.
- copy_UB()[source]#
Copy the UB matrix from the
coverageworkspace into the model’s cached UB matrix (NeuXtalVizModel.UB).
- copy_to_instrument_pc(filename)[source]#
Copy a file to the TOPAZ instrument PC data share, if applicable.
Only copies the file when it lives under an SNS TOPAZ IPTS directory; otherwise this is a no-op.
- Parameters:
- filenamestr
Path of the file to copy, expected to start with
/SNS/TOPAZ/IPTS-<n>/....
- create_plan(table)[source]#
Build the
plantable workspace from an experiment plan tuple.- Parameters:
- tabletuple
8-tuple
(pv, names, titles, settings, comments, counts, values, use)wherepvis the name of the process-variable (title) column,namesare the motor/axis column names,titlesare the row titles/labels,settingsare the per-row lists of motor angles,commentsare per-row comment strings,countsare per-row “wait for” counting-condition values,valuesare per-row target count values, anduseare per-row booleans indicating whether the row is active.
- create_sample(instrument, mode, UB, wavelength, d_min)[source]#
Create the
sampleworkspace and record experiment settings.Stores the UB matrix and the instrument, mode, wavelength range, and minimum d-spacing as sample logs for later retrieval (e.g. by
load_experiment()).- Parameters:
- instrumentstr
Instrument identifier.
- modestr
Goniometer/experiment mode name.
- UB3x3 array-like
UB matrix to set on the sample workspace.
- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom).
- d_minfloat
Minimum d-spacing (Angstrom).
- crystal_plan(*args)[source]#
Construct a
CrystalPlangenetic-algorithm optimizer.- Parameters:
- *args
Positional arguments forwarded to
CrystalPlan, i.e.use,opt,axes,limits,wavelength,d_min,point_group,lattice_centering.
- Returns:
- crystal_planCrystalPlan
The constructed optimizer instance.
- delete_angles(rows)[source]#
Delete plan rows/orientations from the
combinedworkspace and renumber the remaining runs to be contiguous.- Parameters:
- rowslist of int
Run numbers (plan rows) to delete.
- downsample(arr, n=14)[source]#
Reduce a sequence to at most
nrepresentative elements.Always keeps the first and last elements; for short sequences keeps every other element, for longer sequences picks approximately evenly-spaced indices.
- Parameters:
- arrsequence
Sequence of values to downsample.
- nint, optional
Target number of interior samples to keep. Default is 14.
- Returns:
- sampledlist
Downsampled list of elements from
arr.
- extract_data(ws)[source]#
Extract bin-center coordinate grids, signal, and errors from an MD workspace.
- Parameters:
- wsstr
Name of the MD workspace to extract from.
- Returns:
- coordslist of ndarray
Meshgrid (
indexing="ij") of bin-center coordinates for each non-integrated dimension ofws.- signalndarray
Signal array of
ws, squeezed to drop singleton dimensions.- errorsndarray
Standard errors (square root of the error-squared array) of
ws, squeezed to drop singleton dimensions.
- extract_instrument_view()[source]#
Build a mesh of detector-bank quadrilaterals for 3D rendering.
Uses the bank-corner coordinates computed by
initialize_instrument()(self.xc,self.yc,self.zc).- Returns:
- inst_dictdict
Dictionary with keys
"points"(Nx3 array of corner coordinates),"faces"(PyVista-style face connectivity array), and"radius"(max extent along each axis).
- generate_axes(axes, polarities)[source]#
Build and cache
SetGoniometeraxis-string templates.Stores the result on
self.axesfor use byadd_orientation(),calculate_rotations(), and theCrystalPlangenetic algorithm.- Parameters:
- axeslist
Per-axis (x, y, z) rotation-axis direction components, as returned by
get_axes_polarities().- polaritieslist
Per-axis rotation sense/polarity, as returned by
get_axes_polarities().
- generate_table(row)[source]#
Build a sorted HKL/d-spacing/wavelength table for one plan row.
- Parameters:
- rowint
Run number (plan row) to filter peaks for, taken from the
combinedworkspace. If -1 and amissingworkspace exists (fromcalculate_statistics()), that workspace of missing reflections is used instead.
- Returns:
- tablelist of list
One row per peak, each
[h, k, l, d, lamda]sorted by descending d-spacing (and h, k, l as tie-breakers).
- get_UB()[source]#
Get the UB matrix currently set on the
coverageworkspace.- Returns:
- UB3x3 ndarray or None
UB matrix, or None if no oriented lattice is set.
- get_angles(gamma, nu)[source]#
Look up the cached goniometer setting nearest a detector position.
Searches the settings previously computed by
individual_peak()orsimultaneous_peaks()for the one whose detector (gamma, nu) is closest to the given position, and records the corresponding HKL(s) inself.hkl/self.hkl_altand a descriptive comment inself.comment.- Parameters:
- gammafloat
Detector gamma angle (degrees) to search near.
- nufloat
Detector nu angle (degrees) to search near.
- Returns:
- anglesndarray
Per-axis goniometer angle values for the matched setting.
- gamma, nufloat
Detector gamma/nu angles of the matched primary reflection.
- lamdafloat
Wavelength (Angstrom) of the matched primary reflection.
- dfloat
d-spacing (Angstrom) of the matched primary reflection.
- gamma_alt, nu_altfloat or None
Detector gamma/nu angles of the matched secondary reflection (for simultaneous-peaks results), or None if not applicable.
- lamda_altfloat or None
Wavelength of the matched secondary reflection, or None.
- d_altfloat or None
d-spacing of the matched secondary reflection, or None.
- get_autoreduce_instrument(instrument)[source]#
Get the autoreduce instrument definition file path for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- str
Instrument definition file path.
- get_axes_polarities(instrument, mode)[source]#
Get the goniometer rotation axes and their polarities for a mode.
- Parameters:
- instrumentstr
Instrument identifier.
- modestr
Goniometer mode name.
- Returns:
- axeslist
Per-axis (x, y, z) rotation-axis direction components.
- polaritieslist
Per-axis rotation sense/polarity (+1 or -1).
- get_calibration_file_path(instrument)[source]#
Get the shared calibration directory for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- filepathstr
File path to the instrument’s shared calibration directory.
- get_counting_options(instrument)[source]#
Get the counting condition options for an instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- countingobject
The instrument’s “Counting” configuration entry (e.g. a list of available counting/”wait for” conditions).
- get_coverage_info(point_group, lattice_centering, draw_all, color, row=None)[source]#
Build reciprocal-space point-cloud data for the coverage plot.
Reduces observed HKLs to symmetry-independent representatives (applying the lattice centering condition), counts redundancy per representative, and colors each point either by direction on a sphere or by redundancy.
- Parameters:
- point_groupstr
Point group symbol used to generate symmetry equivalents.
- lattice_centeringstr
Lattice centering symbol; only reflections satisfying its centering condition are counted.
- draw_allbool
If True, use all active peaks (
filteredworkspace); if False, restrict to the currently selected row (tableworkspace).- colorstr
Coloring scheme: “Sphere” to color by direction, or “Redundancy” to color by observation count.
- rowint or None, optional
If -1, use the
missingreflections workspace instead offiltered/table. Default is None.
- Returns:
- coverage_dictdict or None
Dictionary with keys
"colors"(per-point RGB uint8),"sizes"(normalized redundancy per point),"coords"(Cartesian reciprocal-space coordinates),"axis_coords"and"axis_colors"(coordinates/colors for the (100), (010), (001) axis markers), and"type"(name of the workspace used). Returns None if nofilteredworkspace exists yet.
- get_crystal_system_point_groups(crystal_system)[source]#
Get the point groups belonging to a crystal system.
- Parameters:
- crystal_systemstr
Crystal system name (e.g. “Cubic”, “Tetragonal”).
- Returns:
- point_groupslist of str
Point group symbols for the given crystal system.
- get_goniometer_axes(instrument, mode)[source]#
Get Mantid
SetGoniometeraxis-string templates for a mode.- Parameters:
- instrumentstr
Instrument identifier.
- modestr
Goniometer mode name.
- Returns:
- axeslist of str
Per-axis template strings of the form
"{},x,y,z,polarity,type"(with a{}placeholder for the angle value) suitable for formatting and passing toSetGoniometer.
- get_goniometers(instrument, mode)[source]#
Get goniometer axis names with their angle limits for a mode.
- Parameters:
- instrumentstr
Instrument identifier.
- modestr
Goniometer mode name.
- Returns:
- goniometerslist of tuple
One
(name, min_angle, max_angle)tuple per goniometer axis.
- get_instrument_background()[source]#
Compute (or return cached) 2D detector-coverage occupancy image.
Bins the instrument’s
gamma/nudetector angles into a 2D histogram to show which regions of angular space are covered by active (unmasked) detectors. Result is cached onself.instrument_background.- Returns:
- instrument_backgrounddict or None
Dictionary with keys
"img"(occupancy image, 1 where detectors exist),"xedges","yedges"(bin edges in gamma/nu), or None if no detector angle data is available.
- get_instrument_directory(instrument)[source]#
Get the file path for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- filepathstr
File path to instrument experiment data.
- get_instrument_name(instrument)[source]#
Get the short Mantid instrument name for an instrument identifier.
- Parameters:
- instrumentstr
Instrument identifier (key into
beamlines).
- Returns:
- namestr
Mantid instrument name.
- get_laue_info()[source]#
Extract detector-frame angles and HKLs for the current row’s peaks.
Computes gamma/nu detector angles, wavelength, and d-spacing for every peak in the
tableworkspace, and caches the results asself.lamda_peaks,self.gamma_peaks,self.nu_peaks,self.d_peaks, andself.hkl_peaksfor later lookup byget_peak_index()/get_peak_selection().- Returns:
- gamma_peaks, nu_peaksndarray
Detector gamma/nu angles (degrees) for each peak.
- lamda_peaksndarray
Wavelength (Angstrom) for each peak.
- d_peaksndarray
d-spacing (Angstrom) for each peak.
Returns None if the
tableworkspace does not exist.
- get_modes(instrument)[source]#
Get the available goniometer modes for an instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- modeslist of str
Names of the goniometer modes defined for the instrument.
- get_motors(instrument)[source]#
Get auxiliary motor names and default values for an instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- motorslist of tuple
One
(name, value)tuple per auxiliary motor, or an empty list if the instrument defines no motors.
- get_peak_index(i)[source]#
Look up a cached Laue peak (and any co-located peaks) by index.
Uses the arrays cached by
get_laue_info().- Parameters:
- iint
Index into the cached peak arrays.
- Returns:
- gamma, nufloat
Detector gamma/nu angles (degrees) of peak
i.- lamdasndarray
Wavelengths (Angstrom) of all peaks at the same detector position as peak
i(e.g. harmonics).- hklndarray, shape (3,)
Miller index of peak
i.- wlfloat
Wavelength (Angstrom) of peak
i.- iint
The (unchanged) input index, echoed back for convenience.
Returns None if no peaks are cached.
- get_peak_selection(gamma, nu)[source]#
Find the cached Laue peak nearest a given detector position.
Uses the arrays cached by
get_laue_info().- Parameters:
- gammafloat
Detector gamma angle (degrees) to search near.
- nufloat
Detector nu angle (degrees) to search near.
- Returns:
- gamma, nufloat
Detector gamma/nu angles (degrees) of the matched peak.
- lamdasndarray
Wavelengths (Angstrom) of all peaks at the same detector position as the match (e.g. harmonics).
- hklndarray, shape (3,)
Miller index of the matched peak.
- wlfloat
Wavelength (Angstrom) of the matched peak.
- iint
Index of the matched peak in the cached arrays.
Returns None if no peaks are cached.
- get_point_group_centering(point_group)[source]#
Get the allowed lattice centerings for a point group.
- Parameters:
- point_groupstr
Point group symbol.
- Returns:
- centeringslist of str
Allowed lattice centering symbols for the given point group.
- get_scan_log(instrument)[source]#
Get the process-variable/title log name for an instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- titlestr
Name of the instrument’s scan title/process-variable log.
- get_setting(free_angles, limits)[source]#
Combine free (variable) angles with fixed-limit angles into a full per-axis goniometer setting.
- Parameters:
- free_anglessequence of float
Values for the axes whose limits are not fixed (min != max), in axis order.
- limitssequence of (float, float)
Per-axis (min, max) angle limits.
- Returns:
- settinglist of float
Full per-axis angle setting: the fixed limit value for axes with
min == max, otherwise the next value fromfree_angles.
- get_symmetry(point_group, centering)[source]#
Coerce point group and centering to plain strings.
- Parameters:
- point_groupstr
Point group symbol.
- centeringstr
Lattice centering symbol.
- Returns:
- pgstr
Point group symbol as a string.
- lcstr
Lattice centering symbol as a string.
- get_vanadium_file_path(instrument)[source]#
Get the shared vanadium directory for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- filepathstr
File path to the instrument’s shared Vanadium directory.
- get_wavelength(instrument)[source]#
Get the default wavelength (range) for an instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- wavelengthfloat or list of float
Single wavelength, or [min, max] wavelength range (Angstrom).
- grouping_list(detectors, cols, rows, c, r)[source]#
Build a Mantid GroupingPattern string from a detectors table.
- Parameters:
- detectorsstr
Name of the preprocessed detectors table workspace.
- cols, rowsint
Number of columns and rows per bank (before grouping).
- c, rint
Grouping factors along columns and rows.
- Returns:
- str
Comma-separated grouping pattern suitable for GroupDetectors.
- has_UB()[source]#
Check whether the
coverageworkspace has an oriented lattice.- Returns:
- has_ubbool
True if the
coverageworkspace has a UB matrix set.
- hsl_to_rgb(hue, saturation, lightness)[source]#
Convert HSL color values to RGB.
- Parameters:
- huearray-like
Hue values, in degrees (0-360).
- saturationarray-like
Saturation values (0-1), broadcastable with
hue.- lightnessarray-like
Lightness values (0-1), broadcastable with
hue.
- Returns:
- rgbndarray, shape (…, 3)
RGB values (0-1) corresponding to each input HSL triple.
- individual_peak(hkl, wavelength, axes, polarities, limits, equiv, pg, step=1)[source]#
Find goniometer settings that bring a peak (or its symmetry equivalents) into the detector range.
Aggregates results from
calculate_individual_peak()over the requested HKL and (optionally) all of its point-group equivalents, and caches the combined results onself.angles*attributes for later lookup viaget_angles().- Parameters:
- hklarray-like, shape (3,)
Miller index of the target reflection.
- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom).
- axeslist
Per-axis (x, y, z) rotation-axis direction components.
- polaritieslist
Per-axis rotation sense/polarity.
- limitssequence of (float, float)
Per-axis (min, max) angle limits, in degrees.
- equivbool
If True, also search settings for all symmetry-equivalent HKLs of
hklunder point grouppg.- pgstr
Point group symbol used to generate symmetry equivalents.
- stepfloat, optional
Base angular step size, in degrees. Default is 1.
- Returns:
- gamma, nu, lamda, dndarray
Detector gamma/nu angles (degrees), wavelength (Angstrom), and d-spacing (Angstrom) for each goniometer setting found that places the peak on an active detector.
- initialize_instrument(instrument, logs, cal, gon, mask)[source]#
Build the
instrument,goniometer, and related workspaces.Loads the empty instrument definition (or autoreduce IDF), applies sample logs, calibration, goniometer parameter, and mask files, then groups detectors and precomputes bank-corner coordinates used for the instrument 3D view and background occupancy plot.
- Parameters:
- instrumentstr
Instrument identifier (key into
beamlines).- logsdict
Mapping of auxiliary motor names to numeric values (from
get_motors()/the view’s motor table), added as sample logs on the instrument workspace before (re)loading the instrument definition, so motor-dependent geometry is applied.- calstr
Path to a calibration file (
.xmlparameter file or ISAW DetCal file), or an empty string if none.- gonstr
Path to a goniometer parameter XML file, or an empty string if none.
- maskstr
Path to a mask file, or an empty string if none.
- load_UB(filename)[source]#
Load a UB matrix from an ISAW UB file onto the
coverageworkspace and update the model’s cached UB matrix.- Parameters:
- filenamestr
Path to the ISAW UB matrix file.
- load_experiment(filename)[source]#
Load a previously saved experiment (plan + sample) from Nexus.
Restores the UB matrix and rebuilds the plan table contents and experiment configuration from the sample logs written by
create_sample(),update_sample(), andupdate_goniometer_motors().- Parameters:
- filenamestr
Path to the Nexus file to load.
- Returns:
- plantuple
(titles, settings, comments, counts, values, use)– the plan table contents, in the same layout consumed bycreate_plan().- configtuple
(instrument, mode, wl, d_min, lims, vals, cal, gon, mask)– the instrument/goniometer configuration, wherewlis either a single wavelength or a [min, max] pair,limsare the goniometer axis limits, andvalsare the auxiliary motor values.- symmtuple
(cs, pg, lc)– crystal system, point group, and lattice centering.
- remove_instrument()[source]#
Delete the
instrument,combined,filtered, andfootprintworkspaces if they exist, and clear the cached instrument background image.
- reslice_last(U, V, W, normal, value, thickness)[source]#
Re-slice the most-recently computed coverage workspace without rebuilding the footprint or coverage map.
Returns the same
slice_dictascalculate_rotations(), orNoneif no coverage workspace is available yet.
- save_experiment(filename)[source]#
Save the
plan(andsample, if present) workspaces to Nexus.- Parameters:
- filenamestr
Output Nexus file path.
- save_plan(filename)[source]#
Write the active (used) rows of the
plantable to a CSV file.- Parameters:
- filenamestr
Output CSV file path.
- select_scan_near_equator(Rs, motor_angles, u, v, w, max_deg=360, n_steps=60, n_eq=(0, 1, 0), normal_weight=10.0)[source]#
Select, for each of a set of scan angles about
w, the goniometer setting fromRsthat best matches that orientation while keeping the scattering plane near the equatorial plane.- Parameters:
- Rsarray-like, shape (n_settings, 3, 3)
Candidate goniometer rotation matrices.
- motor_anglesarray-like, shape (n_settings, n_axes)
Per-axis motor angles corresponding to each matrix in
Rs.- u, v, warray-like, shape (3,)
Orthonormal scattering-plane basis (
u,vin-plane,wnormal), as returned bycalculate_projections().- max_degfloat, optional
Total scan range about the plane normal
w, in degrees. Default is 360.- n_stepsint, optional
Number of scan steps over
max_deg. Default is 60.- n_eq3-tuple of float, optional
Direction defining the equatorial plane normal. Default is
(0, 1, 0).- normal_weightfloat, optional
Weight penalizing deviation of the scattering plane from the equatorial plane relative to orientation match. Default is 10.0.
- Returns:
- selected_Rsndarray, shape (n_steps, 3, 3)
Best-matching rotation matrix for each scan step.
- selected_anglesndarray, shape (n_steps, n_axes)
Motor angles corresponding to
selected_Rs.
- set_path(filename)[source]#
Remember the directory of a file for use as the default directory.
- Parameters:
- filenamestr
File path whose containing directory should be stored.
- simultaneous_peaks(hkl_1, hkl_2, wavelength, axes, polarities, limits, equiv, pg, step=1)[source]#
Find goniometer settings placing two reflections on detectors simultaneously.
Considers every distinct pair drawn from the point-group equivalents of
hkl_1andhkl_2(or just the two HKLs themselves ifequivis False), and aggregates the valid settings found bysimultaneous_peaks_hkl()for each pair. Caches the combined results onself.angles*attributes for later lookup viaget_angles().- Parameters:
- hkl_1, hkl_2array-like, shape (3,)
Miller indices of the two target reflections.
- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom).
- axeslist
Per-axis (x, y, z) rotation-axis direction components.
- polaritieslist
Per-axis rotation sense/polarity.
- limitssequence of (float, float)
Per-axis (min, max) angle limits, in degrees.
- equivbool
If True, search over all symmetry-equivalent HKL pairs under point group
pg.- pgstr
Point group symbol used to generate symmetry equivalents.
- stepfloat, optional
Base angular step size, in degrees. Default is 1.
- Returns:
- values0tuple of ndarray
(gamma, nu, lamda, d)for thehkl_1-side reflection at each valid goniometer setting.- values1tuple of ndarray
(gamma, nu, lamda, d)for thehkl_2-side reflection at each valid goniometer setting.
- simultaneous_peaks_hkl(hkl_1, hkl_2, wavelength, axes, polarities, limits, step=1)[source]#
Scan goniometer settings for a pair of HKLs and keep settings where both reflections simultaneously satisfy the wavelength range and land on active detectors.
- Parameters:
- hkl_1, hkl_2array-like, shape (3,)
Miller indices of the two target reflections.
- wavelength2-tuple of float
Minimum and maximum wavelength (Angstrom). If min and max are equal, a +/-2.5% band is used instead.
- axeslist
Per-axis (x, y, z) rotation-axis direction components.
- polaritieslist
Per-axis rotation sense/polarity.
- limitssequence of (float, float)
Per-axis (min, max) angle limits, in degrees.
- stepfloat, optional
Base angular step size, in degrees. Default is 1.
- Returns:
- anglesndarray, shape (n_valid, n_axes)
Per-axis angle values for each valid goniometer setting.
- values0tuple of ndarray
(gamma0, nu0, lamda0, d0)for thehkl_1reflection at each valid setting.- values1tuple of ndarray
(gamma1, nu1, lamda1, d1)for thehkl_2reflection at each valid setting.
- swap_angles(rows)[source]#
Swap the run numbers of two plan rows/orientations.
- Parameters:
- rows2-element sequence of int
The pair of run numbers to swap in the
combinedworkspace.
- to_index(Q, Q_max, scale, n)[source]#
Convert Q-coordinate value(s) to a clipped voxel-grid index.
- Parameters:
- Qarray-like
Q-coordinate value(s) (inverse Angstrom).
- Q_maxfloat
Maximum Q extent of the grid (inverse Angstrom).
- scalefloat
Conversion factor from Q to index units, typically
(n - 1) / (2 * Q_max).- nint
Number of voxels along this axis.
- Returns:
- idxndarray of int
Voxel index (indices) clipped to
[0, n - 1].
- update_goniometer_motors(limits, motors, cal, gon, mask)[source]#
Record goniometer motor limits and auxiliary motor/file settings as sample logs so they can be restored by
load_experiment().- Parameters:
- limitsarray-like
Per-axis (min, max) angle limits, flattened and stored as the
"limits"sample log.- motorsdict
Mapping of auxiliary motor names to their values.
- calstr
Calibration file path, stored as the
"cal"sample log.- gonstr
Goniometer parameter file path, stored as the
"gon"sample log.- maskstr
Mask file path, stored as the
"mask"sample log.
- update_sample(crytsal_system, point_group, lattice_centering)[source]#
Record crystal-symmetry information as sample logs.
- Parameters:
- crytsal_systemstr
Crystal system name.
- point_groupstr
Point group symbol.
- lattice_centeringstr
Lattice centering symbol.
- validate_projection(proj)[source]#
Validate and unpack a 3x3 HKL projection matrix.
- Parameters:
- projarray-like
Flat or nested sequence of 9 values, reshaped to a 3x3 projection matrix whose rows/columns are the U, V, W vectors.
- Returns:
- U, V, Wndarray, shape (3,)
Rows of the reshaped projection matrix.
- invalidbool
True if the projection matrix is singular (determinant close to zero), meaning U, V, W do not form a valid basis.
NeuXtalViz.models.periodic_table module#
- class AtomModel(atm='H')[source]#
Bases:
objectModel providing isotope, neutron scattering, and identity data for an element.
- Parameters:
- atmstr, optional
Chemical symbol of the element. Default is
"H".
- Attributes:
- atmstr
Chemical symbol of the element.
- isotopeslist
Mass numbers of the isotopes available for this element.
- namestr
Full element name.
- atom_dictdict
Isotope-specific atomic data, populated by
generate_data().- neutron_dictdict
Isotope-specific neutron scattering data, populated by
generate_data().
Methods
generate_data(iso)Compute atomic and neutron scattering data for a given isotope.
Return the available isotope mass numbers for the element.
Return the chemical symbol and full name of the element.
- generate_data(iso)[source]#
Compute atomic and neutron scattering data for a given isotope.
Populates the atom_dict and neutron_dict attributes.
- Parameters:
- isoint
Mass number of the isotope to look up.
- class PeriodicTableModel(atom)[source]#
Bases:
objectModel holding the currently selected periodic table element/isotope.
- Parameters:
- atomstr
Chemical symbol of the initially selected element (e.g.
"H").
- Attributes:
- valuestr
Chemical symbol of the currently selected element.
Methods
get_atom_model(atm)Create an
AtomModelfor the given element symbol.
NeuXtalViz.models.ub_tools module#
- class UBModel[source]#
Bases:
NeuXtalVizModelModel for UB matrix and peak table operations in NeuXtalViz.
Provides methods for loading, saving, and manipulating crystallographic data, including peak finding, UB matrix determination, lattice refinement, and clustering. Integrates with Mantid algorithms for data processing and supports both conventional and modulated structures.
Methods
ab_axes()\(c^*\)-direction in cartesian coordinates.
ab_star_axes()\(c\)-direction in cartesian coordinates.
add_peak(ind, val, horz, vert)Add a peak to the peaks table.
add_peak_from_hkl(ind, hkl)Add a peak to the peaks workspace using HKL coordinates.
avoid_aluminum_contamination(d_min, d_max[, ...])Flag peaks coincident with aluminum powder ring reflections.
avoid_contamination(sample, d_min, d_max[, ...])Remove peaks in the peaks table that coincide with powder rings.
avoid_copper_contamination(d_min, d_max[, delta])Flag peaks coincident with copper powder ring reflections.
avoid_iron_contamination(d_min, d_max[, delta])Flag peaks coincident with iron powder ring reflections.
bc_axes()\(a^*\)-direction in cartesian coordinates.
bc_star_axes()\(a\)-direction in cartesian coordinates.
ca_axes()\(b^*\)-direction in cartesian coordinates.
ca_star_axes()\(b\)-direction in cartesian coordinates.
calculate_camera_parameters(direction, roll)Calculate roll, elevation, and azimuth from camera direction and roll.
calculate_clim(data[, method])Calculate the color limits for the given data using the specified method.
calculate_fractional(mod_vec_1, mod_vec_2, ...)Calculate the fractional coordinates from the given modulation vectors and integer coordinates.
calculate_highlight(Q1, Q2)Calculate the angle between two Q vectors.
Calculate hkl values without rounding.
calculate_hkl_position(ind, h, k, l)Calculate the HKL position for a given peak index and Miller indices.
calculate_instrument_view(ind, d_min, d_max)Calculate the instrument view for a given peak index and d-spacing range.
calculate_integer(mod_vec_1, mod_vec_2, ...)Calculate the integer coordinates from the given modulation vectors and HKL coordinates.
calculate_peaks(hkl_1, hkl_2, a, b, c, ...)Calculate d-spacing and angle between two HKL planes.
calibrate_data(instrument, det_cal, gon_cal, ...)Calibrate the loaded data using detector, goniometer, and tube calibration files.
Check if a backup of the peaks table exists to undo a filter operation.
centroid_peaks(peak_radius)Re-center peak locations using centroid within given radius
Delete the backup workspace used to undo peak filtering, if present.
Clear the intensity values of all peaks in the peaks table.
cluster_peaks(peak_info[, eps, min_samples])Cluster peaks using DBSCAN algorithm.
convert_data(instrument, wavelength, lorentz)Convert loaded data to Q-space using Mantid algorithms.
Copy the UB matrix from the Q workspace to the cell workspace.
Copy the UB matrix from the peaks workspace to the cell workspace.
Copy the UB matrix from the cell workspace to the Q workspace.
Copy the UB matrix from the cell workspace to the peaks workspace.
delete_peak(no)Delete a single peak row from the current peaks workspace.
delete_peak_rows(numbers)Delete multiple peak rows from the current peaks workspace.
delete_peaks(peaks)Remove peaks.
determine_UB_with_lattice_parameters(a, b, ...)Determine UB with prior known lattice parameters.
determine_UB_with_niggli_cell(min_d, max_d)Determine UB with primitive lattice using min/max lattice constant.
extract_roi(horz, vert, horz_roi, vert_roi, val)Extract a region of interest (ROI) from the instrument view.
files_exist(files)Check if the specified files exist and are readable.
filter_peaks(name, operator, value)Filter out peaks based on value and operator.
find_UB_from_scattering_plane(constants, ...)Calculate the UB matrix from a scattering plane and one peak.
find_peaks(min_dist[, density, max_peaks, ...])Harvest strong peak locations from Q-sample into a peaks table.
Obtain possible transforms compatabile with a unit cell lattice.
get_Q(d)Convert to Q momentum transfer magnitude.
Extract Q-space information from the model.
get_Q_status([files])Get a status code describing the state of the Q-sample data.
get_UB()Retrieve the UB matrix from the oriented lattice.
Get a status code describing whether a UB matrix is available.
get_alignment_info(run_number[, tilts])Compare observed and UB-predicted Q vectors for peaks in a run.
Extract all goniometer matrices.
get_autoreduce_instrument(instrument)Get the autoreduce instrument definition file path for a given instrument.
get_calibration_file_path(instrument)Get the calibration file path for a given instrument.
Get cluster information for peaks based on UB and peak table.
get_d(Q)Convert to d-spacing.
Get the minimum d-spacing among the current peaks, capped at 0.7.
get_default_d_min(instrument)Get the default minimum d-spacing for a given instrument.
get_example_file_path(instrument)Get the example data file path for a given instrument.
get_files(instrument, IPTS, runs, exp)Get the appropriate data files for a given instrument, IPTS, and run numbers.
get_goniometer_axes(instrument)Get goniometer axis names for a given instrument.
get_goniometers(instrument)Get goniometer settings for a given instrument.
Check if the Q volume data exists.
Return the display-name key (e.g. 'TOPAZ') for the instrument embedded in the loaded Q workspace, or None if unrecognised.
get_instrument_name(instrument)Get the instrument name string for a given instrument identifier.
Get the errors in the lattice constants from the oriented lattice.
Get the lattice constants from the oriented lattice.
get_lite_file_path(instrument)Get the LITE file path for a given instrument.
Obtain the maximum d-spacing from the oriented lattice.
Get the modulation vectors stored on the oriented lattice.
Get the run numbers associated with the currently loaded data.
get_oriented_lattice_parameters()Obtain the oriented lattice parameters.
get_peak(i)Get a specific peak's information by index.
Extract detailed information for each peak in the current table.
Get a status code describing the state of the peaks table.
get_raw_file_path(instrument)Get the raw data file path for a given instrument.
get_run_goniometer(ind)Return goniometer Euler angles for the selected run.
Get the sample directions from the UB matrix.
get_shared_file_path(instrument, ipts)Get the shared file path for a given instrument and IPTS.
get_slice_info(U, V, W, normal, value, ...)Get the slicing information for a given normal and value.
get_slice_z_extent(U, V, W, normal)Get the minimum and maximum extent along the slice normal direction.
get_transform([reciprocal])Transformation matrix describing the reciprocal or crystal axes.
get_vanadium_file_path(instrument)Get the vanadium calibration file path for a given instrument.
get_vector(axes_type, ind)Vector corresponding to a particular crystallographic direction.
get_wavelength(instrument)Get the wavelength for a given instrument.
has_Q()Check if the Q workspace exists in Mantid.
has_UB()Check if the UB matrix is defined on the sample.
Check if the peaks table exists in Mantid.
index_peaks([tol, sat_tol, mod_vec_1, ...])Index the peaks and calculate the lattice parameter uncertainties.
integrate_peaks(peak_radius[, ...])Integrate peaks using spherical or ellipsoidal regions.
is_mono(wavelength)Check whether a wavelength band corresponds to monochromatic beam.
Check if the data has been sliced.
load_Q(filename)Load Q file.
load_UB(filename)Load UB from file.
load_data(instrument, IPTS, runs, exp, time_stop)Load experimental data for a given instrument and run parameters.
load_peaks(filename)Load peaks file.
make_Q(Q_max)Bin the converted MD workspace into a 3D Q-sample volume for display.
orientation_matrix()Return the current UB matrix (orientation matrix).
possible_conventional_cells([max_error, ...])List possible conventional cells.
predict_modulated_peaks(d_min, lamda_min, ...)Predict the modulated peak positions based on main peaks.
predict_peaks(centering, d_min, lamda_min, ...)Predict peak Q-sample locations with UB and lattice centering.
predict_satellite_peaks(d_min, lamda_min, ...)Locate satellite peaks from goniometer angles.
refine_UB_with_constraints(cell[, tol])Refine UB with constraints corresponding to lattice system.
refine_UB_without_constraints([tol, sat_tol])Refine UB with unconstrained lattice parameters.
refine_U_only(a, b, c, alpha, beta, gamma)Refine the U orientation only.
remove_duplicate_peaks(peaks)Omit duplicate peaks from different based on indexing.
renumber_runs_by_index(ws, peaks)Re-label the runs by index based on goniometer setting.
roi_scan_to_hkl(ind, val, horz, vert)Convert a ROI scan position to HKL coordinates.
rotate_camera_azimuth(position, focal_point, ...)Rotate the camera left/right about a global up axis.
rotate_camera_elevation(position, ...)Tilt the camera up/down about its right axis.
rotate_camera_roll(position, focal_point, ...)Apply a roll about the current viewing axis.
save_Q(filename)Save Q file.
save_UB(filename)Save UB to file.
save_peaks(filename)Save the current peaks table to a file.
save_roi_mask(instrument, filename)Save a detector mask XML file for the current instrument-view ROI.
select_cell(number[, tol])Transform to conventional cell using form number.
set_UB(UB)Update the UB-matrix.
set_goniometer(peaks, R)Set the goniometer matrix for a peaks workspace.
set_manual_UB(constants, directions)Set the unit cell parameters and directions manually.
set_peak(i, hkl, int_hkl, int_mnp)Set the HKL, integer HKL, and integer MNP values for a specific peak.
simplify_vector(vec)Simplify a vector to its primitive integer form.
Save a backup copy of the current peaks table before filtering.
sort_peaks_by_d(peaks)Sort peaks table by descending d-spacing.
sort_peaks_by_hkl(peaks)Sort peaks table by descending hkl values.
transform_lattice(transform[, tol])Apply a cell transformation to the lattice.
Restore the peaks table from the filter-peaks backup, if available.
Update the UB matrix on the sample and synchronize with Mantid workspaces.
validate_projection(proj)Validate and unpack a 3x3 projection matrix into its row vectors.
- add_peak(ind, val, horz, vert)[source]#
Add a peak to the peaks table.
- Parameters:
- indint
Index of the run.
- valfloat
Peak value (e.g., d-spacing or angle).
- horzfloat
Horizontal coordinate (e.g., angle or hkl).
- vertfloat
Vertical coordinate (e.g., angle or hkl).
- add_peak_from_hkl(ind, hkl)[source]#
Add a peak to the peaks workspace using HKL coordinates.
- Parameters:
- indint
Index of the run/goniometer setting to use.
- hkllist
Miller indices [h, k, l] of the peak to add.
- avoid_aluminum_contamination(d_min, d_max, delta=0.1)[source]#
Flag peaks coincident with aluminum powder ring reflections.
Arblaster, J. W. Selected Values of the Crystallographic Properties of Elements; ASM International, 2018
- Parameters:
- d_min, d_maxfloat
Minimum and maximum d-spacing range over which to generate aluminum reflections.
- deltafloat, optional
Tolerance in momentum transfer used to match peaks against aluminum reflections. The default is 0.1.
- avoid_contamination(sample, d_min, d_max, delta=0.1)[source]#
Remove peaks in the peaks table that coincide with powder rings.
Peaks whose momentum transfer is within delta of a reflection generated from sample, or whose d-spacing exceeds d_max, are flagged and removed from the peaks table.
- Parameters:
- sampleCrystalStructure
Crystal structure of the contaminant phase used to generate candidate powder-ring reflections.
- d_min, d_maxfloat
Minimum and maximum d-spacing range over which to generate reflections.
- deltafloat, optional
Tolerance in momentum transfer used to match peaks against the generated reflections. The default is 0.1.
- avoid_copper_contamination(d_min, d_max, delta=0.1)[source]#
Flag peaks coincident with copper powder ring reflections.
Arblaster, J. W. Selected Values of the Crystallographic Properties of Elements; ASM International, 2018
- Parameters:
- d_min, d_maxfloat
Minimum and maximum d-spacing range over which to generate copper reflections.
- deltafloat, optional
Tolerance in momentum transfer used to match peaks against copper reflections. The default is 0.1.
- avoid_iron_contamination(d_min, d_max, delta=0.1)[source]#
Flag peaks coincident with iron powder ring reflections.
Arblaster, J. W. Selected Values of the Crystallographic Properties of Elements; ASM International, 2018
- Parameters:
- d_min, d_maxfloat
Minimum and maximum d-spacing range over which to generate iron reflections.
- deltafloat, optional
Tolerance in momentum transfer used to match peaks against iron reflections. The default is 0.1.
- calculate_clim(data, method='normal')[source]#
Calculate the color limits for the given data using the specified method.
- Parameters:
- datanp.ndarray
Input data for which to calculate color limits.
- methodstr, optional
Method for calculating limits (‘normal’, ‘boxplot’, or ‘min/max’). Default is ‘normal’.
- Returns:
- tuple
Lower and upper color limits.
- calculate_fractional(mod_vec_1, mod_vec_2, mod_vec_3, int_hkl, int_mnp)[source]#
Calculate the fractional coordinates from the given modulation vectors and integer coordinates.
- Parameters:
- mod_vec_1, mod_vec_2, mod_vec_3list
Modulation vectors.
- int_hkllist
Integer HKL coordinates.
- int_mnplist
Integer MNP coordinates.
- Returns:
- np.ndarray
Calculated fractional coordinates.
- calculate_highlight(Q1, Q2)[source]#
Calculate the angle between two Q vectors.
- Parameters:
- Q1, Q2array_like
Q vectors (in reciprocal space) to compare.
- Returns:
- phifloat
Angle between Q1 and Q2 in degrees.
- calculate_hkl_position(ind, h, k, l)[source]#
Calculate the HKL position for a given peak index and Miller indices.
- Parameters:
- indint
Index of the peak.
- h, k, lint
Miller indices.
- Returns:
- tuple
Calculated values (x, gamma, nu) for the given HKL.
- calculate_instrument_view(ind, d_min, d_max)[source]#
Calculate the instrument view for a given peak index and d-spacing range.
- Parameters:
- indint
Index of the peak.
- d_min, d_maxfloat
Minimum and maximum d-spacing values.
- Returns:
- inst_viewdict
Instrument view data including d, gamma, nu, and counts.
- calculate_integer(mod_vec_1, mod_vec_2, mod_vec_3, hkl)[source]#
Calculate the integer coordinates from the given modulation vectors and HKL coordinates.
- Parameters:
- mod_vec_1, mod_vec_2, mod_vec_3list
Modulation vectors.
- hkllist
HKL coordinates.
- Returns:
- tuple
Best integer coordinates (int_hkl, int_mnp) that minimize the error.
- calculate_peaks(hkl_1, hkl_2, a, b, c, alpha, beta, gamma)[source]#
Calculate d-spacing and angle between two HKL planes.
- Parameters:
- hkl_1, hkl_2list
Miller indices for the two planes.
- a, b, cfloat
Lattice constants in angstroms.
- alpha, beta, gammafloat
Lattice angles in degrees.
- Returns:
- tuple
d-spacing for the two planes and the angle between them.
- calibrate_data(instrument, det_cal, gon_cal, tube_cal)[source]#
Calibrate the loaded data using detector, goniometer, and tube calibration files.
- Parameters:
- instrumentstr
Instrument identifier.
- det_calstr
Detector calibration file.
- tube_calstr
Tube calibration file.
- gon_calstr
Goniometer calibration file.
- can_undo_filter_peaks()[source]#
Check if a backup of the peaks table exists to undo a filter operation.
- Returns:
- bool
True if a filter-peaks backup workspace exists, False otherwise.
- centroid_peaks(peak_radius)[source]#
Re-center peak locations using centroid within given radius
- Parameters:
- peak_radiusfloat
Integration region radius.
- clear_filter_peaks_backup()[source]#
Delete the backup workspace used to undo peak filtering, if present.
- cluster_peaks(peak_info, eps=0.025, min_samples=15)[source]#
Cluster peaks using DBSCAN algorithm.
- Parameters:
- peak_infodict
Dictionary containing peak information (coordinates, inverse transform, etc.).
- epsfloat, optional
The maximum distance between two samples for one to be considered as in the neighborhood of the other. Default is 0.025.
- min_samplesint, optional
The number of samples in a neighborhood for a point to be considered as a core point. Default is 15.
- Returns:
- successbool
True if clustering is successful, False otherwise.
- convert_data(instrument, wavelength, lorentz, min_d=None, force_reload=False)[source]#
Convert loaded data to Q-space using Mantid algorithms.
- Parameters:
- instrumentstr
Instrument identifier.
- wavelengthfloat
Wavelength in angstroms.
- lorentzbool
Whether to apply Lorentz correction.
- min_dfloat, optional
Minimum d-spacing. Default is None.
- force_reloadbool, optional
Force reconversion of cached MD workspaces.
- delete_peak(no)[source]#
Delete a single peak row from the current peaks workspace.
- Parameters:
- noint
Row index of the peak to delete.
- delete_peak_rows(numbers)[source]#
Delete multiple peak rows from the current peaks workspace.
- Parameters:
- numberslist
Row indices of the peaks to delete.
- determine_UB_with_lattice_parameters(a, b, c, alpha, beta, gamma, tol=0.1)[source]#
Determine UB with prior known lattice parameters.
- Parameters:
- a, b, cfloat
Lattice constants in angstroms.
- alpha, beta, gammafloat
Lattice angles in degrees.
- tolfloat, optional
Indexing tolerance. The default is 0.1.
- determine_UB_with_niggli_cell(min_d, max_d, tol=0.1)[source]#
Determine UB with primitive lattice using min/max lattice constant.
- Parameters:
- min_dfloat
Minimum lattice parameter in ansgroms.
- max_dfloat
Maximum lattice parameter in angstroms.
- tolfloat, optional
Indexing tolerance. The default is 0.1.
- extract_roi(horz, vert, horz_roi, vert_roi, val)[source]#
Extract a region of interest (ROI) from the instrument view.
- Parameters:
- horz, vertfloat
Horizontal and vertical coordinates for the ROI center.
- horz_roi, vert_roifloat
Horizontal and vertical ROI sizes.
- valfloat
Value at the ROI center.
- Returns:
- dict
Extracted ROI data including label, x, and y values.
- filter_peaks(name, operator, value)[source]#
Filter out peaks based on value and operator.
- Parameters:
- namestr
Filter name.
- operatorfloat
Filter operator.
- valuefloat
The filter value.
- find_UB_from_scattering_plane(constants, directions)[source]#
Calculate the UB matrix from a scattering plane and one peak.
- Parameters:
- constantslist
Lattice constants and angles [a, b, c, alpha, beta, gamma] in angstroms and degrees.
- directionslist
Two non-parallel vectors [u1, u2, u3, v1, v2, v3] defining the scattering plane.
- find_peaks(min_dist, density=1000, max_peaks=50, edge_pixels=0)[source]#
Harvest strong peak locations from Q-sample into a peaks table.
- Parameters:
- min_distfloat
Minimum distance enforcing lower limit of peak spacing.
- densityint, optional
Threshold density. The default is 1000.
- max_peaksint, optional
Maximum number of peaks to find. The default is 50.
- edge_pixels: int, optional
Nnumber of edge pixels to exclude. The default is 0.
- generate_lattice_transforms(cell)[source]#
Obtain possible transforms compatabile with a unit cell lattice.
- Parameters:
- cellstr
Latttice system.
- Returns:
- transformsdict
Transform dictionary with symmetry operation as key.
- get_Q(d)[source]#
Convert to Q momentum transfer magnitude.
- Parameters:
- dfloat
Interplanar d-spacing.
- Returns:
- Qfloat
Momentum transfer.
- get_Q_info()[source]#
Extract Q-space information from the model.
- Returns:
- Q_infodict
Dictionary containing Q-space signal, min/max limits, spacing, and optionally x, y, z coordinates.
- get_Q_status(files=None)[source]#
Get a status code describing the state of the Q-sample data.
- Parameters:
- fileslist, optional
List of data file paths to check for existence. If None, the status is reported as if the files do not exist.
- Returns:
- statusint
1 if the files do not exist (or none were given), 2 if the files exist but Q-sample data has not yet been calculated, 3 if Q-sample data is ready.
- get_UB()[source]#
Retrieve the UB matrix from the oriented lattice.
- Returns:
- UBndarray
3x3 UB matrix if present, else None.
- get_UB_status()[source]#
Get a status code describing whether a UB matrix is available.
- Returns:
- statusint
0 if no UB matrix is defined, 1 if a UB matrix is available.
- get_alignment_info(run_number, tilts=(0.0, 0.0, 0.0))[source]#
Compare observed and UB-predicted Q vectors for peaks in a run.
Applies an optional goniometer tilt correction (yaw, pitch, roll) and computes, for each indexed peak belonging to run_number, the observed Q-sample vector (tilt-corrected) and the corresponding UB-predicted Q vector, for use in goniometer alignment analysis.
- Parameters:
- run_numberint
Run number to select peaks from.
- tiltstuple, optional
Goniometer tilt angles (yaw, pitch, roll) in degrees applied as an extra rotation before comparing to the goniometer matrix. The default is (0.0, 0.0, 0.0).
- Returns:
- infodict or None
Dictionary with keys “run_number”, “observed”, “predicted”, “observed_hkl”, and “tilts”, or None if there are no peaks, no UB matrix, or no indexed peaks for the given run.
- get_all_goniometer_matrices(ws)[source]#
Extract all goniometer matrices.
- Parameters:
- wsstr
Name of workspace with goniometer indexing.
- Returns:
- Rs: list
Goniometer matrices.
- get_autoreduce_instrument(instrument)[source]#
Get the autoreduce instrument definition file path for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- str
Instrument definition file path.
- get_calibration_file_path(instrument)[source]#
Get the calibration file path for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- str
Calibration file path.
- get_cluster_info()[source]#
Get cluster information for peaks based on UB and peak table.
- Returns:
- clustersdict
Dictionary with cluster coordinates, points, numbers, translation vectors, and transforms.
- get_d(Q)[source]#
Convert to d-spacing.
- Parameters:
- Qfloat
Momentum transfer.
- Returns:
- dfloat
Interplanar d-spacing.
- get_d_min()[source]#
Get the minimum d-spacing among the current peaks, capped at 0.7.
- Returns:
- d_minfloat
Smallest peak d-spacing found, or 0.7 angstroms if no peak has a smaller d-spacing (or no peaks are present).
- get_default_d_min(instrument)[source]#
Get the default minimum d-spacing for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- d_minfloat
Minimum d-spacing in angstroms.
- get_example_file_path(instrument)[source]#
Get the example data file path for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- filepathstr
File path to raw data.
- get_files(instrument, IPTS, runs, exp)[source]#
Get the appropriate data files for a given instrument, IPTS, and run numbers.
- Parameters:
- instrumentstr
Instrument identifier.
- IPTSstr
IPTS number.
- runslist
List of run numbers.
- expstr
Experiment identifier.
- Returns:
- filenameslist
List of file paths to load.
- idfstr or None
Instrument definition file path if using raw files, else None.
- groupingstr
Grouping pattern for the instrument.
- rawbool or None
True if using raw files, False if using LITE files.
- messagestr
Message indicating which files are being used or if files do not exist.
- get_goniometer_axes(instrument)[source]#
Get goniometer axis names for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- axeslist
List of goniometer axis names.
- get_goniometers(instrument)[source]#
Get goniometer settings for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- settingslist
List of goniometer settings.
- get_has_Q_vol()[source]#
Check if the Q volume data exists.
- Returns:
- has_Q_volbool
True if Q volume data exists, False otherwise.
- get_instrument_from_Q()[source]#
Return the display-name key (e.g. ‘TOPAZ’) for the instrument embedded in the loaded Q workspace, or None if unrecognised.
- Returns:
- keystr or None
Instrument identifier key matching an entry in beamlines, or None if the instrument could not be determined.
- get_instrument_name(instrument)[source]#
Get the instrument name string for a given instrument identifier.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- namestr
Instrument name.
- get_lattice_constant_errors()[source]#
Get the errors in the lattice constants from the oriented lattice.
- Returns:
- errorslist
List of errors in lattice constants.
- get_lattice_constants()[source]#
Get the lattice constants from the oriented lattice.
- Returns:
- paramslist
List of lattice constants [a, b, c, alpha, beta, gamma].
- get_lite_file_path(instrument)[source]#
Get the LITE file path for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- filepathstr
File path to LITE file.
- get_max_d_spacing(ws)[source]#
Obtain the maximum d-spacing from the oriented lattice.
- Parameters:
- wsstr
Workspace with UB defined on oriented lattice.
- Returns:
- d_maxfloat
Maximum d-spacing.
- get_modulation_info()[source]#
Get the modulation vectors stored on the oriented lattice.
- Returns:
- mod_vecslist or None
List of the three modulation vectors (V3D), or None if there are no peaks or no UB matrix defined.
- get_number_workspaces()[source]#
Get the run numbers associated with the currently loaded data.
- Returns:
- runslist or None
List of run numbers for the loaded “data” workspace, or None if no data has been loaded.
- get_peak(i)[source]#
Get a specific peak’s information by index.
- Parameters:
- iint
Index of the peak.
- Returns:
- dict or None
Peak information dictionary or None if index is out of range.
- get_peak_info()[source]#
Extract detailed information for each peak in the current table.
- Returns:
- list of dict
List of dictionaries with peak properties (hkl, d-spacing, intensity, etc.).
- get_peaks_status()[source]#
Get a status code describing the state of the peaks table.
- Returns:
- statusint
0 if there is no peaks table or it is empty, 1 if peaks exist but none are indexed, 2 if at least one peak is indexed.
- get_raw_file_path(instrument)[source]#
Get the raw data file path for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- filepathstr
File path to raw data.
- get_run_goniometer(ind)[source]#
Return goniometer Euler angles for the selected run.
- Parameters:
- indint
Index of the run/goniometer setting.
- Returns:
- anglestuple or None
Goniometer Euler angles (in degrees) for the given run index, or None if Q-sample data, wavelength info, or a valid index is not available.
- get_sample_directions()[source]#
Get the sample directions from the UB matrix.
- Returns:
- directionslist
List of simplified sample direction vectors.
Get the shared file path for a given instrument and IPTS.
- Parameters:
- instrumentstr
Instrument identifier.
- iptsstr
IPTS number.
- Returns:
- str
Shared file path.
- get_slice_info(U, V, W, normal, value, thickness, width)[source]#
Get the slicing information for a given normal and value.
- Parameters:
- U, V, Wlist
Normalized direction cosines for the slice.
- normallist
Normal vector for the slice.
- valuefloat
Value at which to slice.
- thicknessfloat
Thickness of the slice.
- widthfloat
Width of the output histogram bins.
- Returns:
- dict
Dictionary with slice information including extents, bins, and transform.
- get_slice_z_extent(U, V, W, normal)[source]#
Get the minimum and maximum extent along the slice normal direction.
- Parameters:
- U, V, Wlist
Normalized direction cosines defining the slice basis vectors.
- normallist
Normal vector for the slice.
- Returns:
- z_minfloat or None
Minimum extent along the normal direction, or None if no UB/Q data.
- z_maxfloat or None
Maximum extent along the normal direction, or None if no UB/Q data.
- get_vanadium_file_path(instrument)[source]#
Get the vanadium calibration file path for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- str
Vanadium calibration file path.
- get_wavelength(instrument)[source]#
Get the wavelength for a given instrument.
- Parameters:
- instrumentstr
Instrument identifier.
- Returns:
- wavelengthfloat
Wavelength in angstroms.
- has_Q()[source]#
Check if the Q workspace exists in Mantid.
- Returns:
- bool
True if Q workspace exists, False otherwise.
- has_UB()[source]#
Check if the UB matrix is defined on the sample.
- Returns:
- bool
True if UB matrix is present, False otherwise.
- has_peaks()[source]#
Check if the peaks table exists in Mantid.
- Returns:
- bool
True if peaks table exists, False otherwise.
- index_peaks(tol=0.1, sat_tol=None, mod_vec_1=[0, 0, 0], mod_vec_2=[0, 0, 0], mod_vec_3=[0, 0, 0], max_order=0, cross_terms=False, round_hkl=True)[source]#
Index the peaks and calculate the lattice parameter uncertainties.
- Parameters:
- tolfloat, optional
Indexing tolerance. The default is 0.1.
- sat_tolfloat, optional
Satellite indexing tolerance. The default is None.
- mod_vec_1, mod_vec_2, mod_vec_3list, optional
Modulation vectors. The default is [0,0,0].
- max_orderint, optional
Maximum order greater than zero for satellites. The default is 0.
- cross_termsbool, optional
Include modulation cross terms. The default is False.
- round_hklbool, optional
Round integers to integer. The default is True.
- Returns:
- indexinglist
Result of indexing including number indexed and errors.
- integrate_peaks(peak_radius, background_inner_fact=1, background_outer_fact=1.5, method='sphere', centroid=True)[source]#
Integrate peaks using spherical or ellipsoidal regions. Ellipsoid integration adapts itself to the peak distribution.
- Parameters:
- peak_radiusfloat
Integration region radius.
- background_inner_factfloat, optional
Factor of peak radius for background shell. The default is 1.
- background_outer_factfloat, optional
Factor of peak radius for background shell. The default is 1.5.
- methodstr, optional
Integration method. The default is ‘sphere’.
- centroidstr, optional
Shift peak position to centroid. The default is True.
- is_mono(wavelength)[source]#
Check whether a wavelength band corresponds to monochromatic beam.
- Parameters:
- wavelengthlist
Wavelength band [min, max] in angstroms.
- Returns:
- bool
True if the minimum and maximum wavelength are equal (monochromatic beam), False otherwise.
- is_sliced()[source]#
Check if the data has been sliced.
- Returns:
- slicedbool
True if data is sliced, False otherwise.
- load_Q(filename)[source]#
Load Q file.
- Parameters:
- filenamestr
Name of Q file with extension .nxs.
- Returns:
- d_minfloat
Minimum d-spacing derived from Q_max.
- wavelengthlist or None
[lambda_min, lambda_max] for DGS data, None otherwise.
- load_UB(filename)[source]#
Load UB from file.
- Parameters:
- filenamestr
Name of UB file with extension .mat.
- load_data(instrument, IPTS, runs, exp, time_stop, force_reload=False, progress=None, stop_event=None)[source]#
Load experimental data for a given instrument and run parameters.
- Parameters:
- instrumentstr
Instrument identifier.
- IPTSstr
IPTS number.
- runslist
List of run numbers.
- expstr
Experiment identifier.
- time_stopfloat
Time to stop loading data.
- force_reloadbool, optional
Force reloading already cached workspaces instead of reusing them.
- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure), called once per run as it loads. Reports within 10-40% – the sub-range the caller (seeUBToolsPresenter.convert_Q_process) budgets for this step, bookended by its own “Data loading…”/”Data loaded…” messages at 10/40.- stop_eventthreading.Event, optional
Cooperative-cancellation event (injected by the worker infrastructure), checked between runs.
- Returns:
- bool
True if the “data” workspace was successfully loaded/grouped, False if no files were found, loading was stopped early, or loading failed.
- load_peaks(filename)[source]#
Load peaks file.
- Parameters:
- filenamestr
Name of peaks file (can be .nxs or .integrate, .peaks, etc.).
- make_Q(Q_max)[source]#
Bin the converted MD workspace into a 3D Q-sample volume for display.
Creates the “Q3D” histogram volume and associated peaks/lattice workspaces, then computes a normalized, outlier-masked log signal array for rendering.
- Parameters:
- Q_maxfloat
Maximum extent of the Q-sample volume along each axis, and the radius beyond which voxels are masked out.
- possible_conventional_cells(max_error=0.2, permutations=True)[source]#
List possible conventional cells.
- Parameters:
- max_errorfloat, optional
Max scalar error to report form numbers. The default is 0.2.
- permutationsbool, optional
Allow permutations of the lattice. The default is True.
- Returns:
- valslist
List of form results.
- predict_modulated_peaks(d_min, lamda_min, lamda_max, mod_vec_1=[0, 0, 0], mod_vec_2=[0, 0, 0], mod_vec_3=[0, 0, 0], max_order=0, cross_terms=False)[source]#
Predict the modulated peak positions based on main peaks.
- Parameters:
- centeringstr
Lattice centering that provides the reflection condition.
- d_minfloat
The lower d-spacing resolution to predict peaks.
- lamda_min, lamda_maxfloat
The wavelength band over which to predict peaks.
- mod_vec_1, mod_vec_2, mod_vec_3list, optional
Modulation vectors. The default is [0,0,0].
- max_orderint, optional
Maximum order greater than zero for satellites. The default is 0.
- cross_termsbool, optional
Include modulation cross terms. The default is False.
- predict_peaks(centering, d_min, lamda_min, lamda_max, edge_pixels=0)[source]#
Predict peak Q-sample locations with UB and lattice centering.
Symbol
Reflection condition
P
None
I
\(h+k+l=2n\)
F
\(h,k,l\) unmixed
R
None
R(obv)
\(-h+k+l=3n\)
R(rev)
\(h-k+l=3n\)
A
\(k+l=2n\)
B
\(l+h=2n\)
C
\(h+k=2n\)
- Parameters:
- centeringstr
Lattice centering that provides the reflection condition.
- d_minfloat
The lower d-spacing resolution to predict peaks.
- lamda_min, lamda_maxfloat
The wavelength band over which to predict peaks.
- edge_pixels: int, optional
Nnumber of edge pixels to exclude. The default is 0.
- predict_satellite_peaks(d_min, lamda_min, lamda_max, mod_vec_1=[0, 0, 0], mod_vec_2=[0, 0, 0], mod_vec_3=[0, 0, 0], max_order=0, cross_terms=False)[source]#
Locate satellite peaks from goniometer angles.
- Parameters:
- d_minfloat
The lower d-spacing resolution to predict peaks.
- lamda_minfloat
Minimum wavelength.
- lamda_maxfloat
Maximum wavelength.
- mod_vec_1, mod_vec_2, mod_vec_3list, optional
Modulation vectors. The default is [0,0,0].
- max_orderint, optional
Maximum order greater than zero for satellites. The default is 0.
- cross_termsbool, optional
Include modulation cross terms. The default is False.
- refine_UB_with_constraints(cell, tol=0.1)[source]#
Refine UB with constraints corresponding to lattice system.
Lattice system
Lengths
Angles
Cubic
\(a=b=c\)
\(α=β=γ=90\)
Hexagonal
\(a=b\)
\(α=β=90,γ=120\)
Rhombohedral
\(a=b=c\)
\(α=β=γ\)
Tetragonal
\(a=b\)
\(α=β=γ=90\)
Orthorhombic
None
\(α=β=γ=90\)
Monoclinic
None
\(α=γ=90\)
Triclinic
None
None
- Parameters:
- cellfloat
Lattice system.
- tolfloat, optional
Indexing tolerance. The default is 0.1.
- refine_UB_without_constraints(tol=0.1, sat_tol=None)[source]#
Refine UB with unconstrained lattice parameters.
- Parameters:
- tolfloat, optional
Indexing tolerance. The default is 0.1.
- sat_tolfloat, optional
Satellite indexing tolerance. The default is None.
- refine_U_only(a, b, c, alpha, beta, gamma)[source]#
Refine the U orientation only.
- Parameters:
- a, b, cfloat
Lattice constants in angstroms.
- alpha, beta, gammafloat
Lattice angles in degrees.
- remove_duplicate_peaks(peaks)[source]#
Omit duplicate peaks from different based on indexing. Table will be sorted.
- Parameters:
- peaksstr
Name of peaks table.
- renumber_runs_by_index(ws, peaks)[source]#
Re-label the runs by index based on goniometer setting.
- Parameters:
- wsstr
Name of workspace with goniometer indexing.
- peaksstr
Name of peaks table.
- roi_scan_to_hkl(ind, val, horz, vert)[source]#
Convert a ROI scan position to HKL coordinates.
- Parameters:
- indint
Index of the run.
- valfloat
Peak value (e.g., d-spacing or angle).
- horzfloat
Horizontal coordinate (e.g., angle or hkl).
- vertfloat
Vertical coordinate (e.g., angle or hkl).
- Returns:
- np.ndarray
Calculated HKL coordinates.
- save_UB(filename)[source]#
Save UB to file.
- Parameters:
- filenamestr
Name of UB file with extension .mat.
- save_peaks(filename)[source]#
Save the current peaks table to a file.
- Parameters:
- filenamestr
Name of peaks file with extension .nxs.
- save_roi_mask(instrument, filename)[source]#
Save a detector mask XML file for the current instrument-view ROI.
Loads an empty instrument definition, determines which detectors fall within the current ROI box (in gamma/nu), and writes a Mantid mask file selecting those detectors.
- Parameters:
- instrumentstr
Instrument identifier.
- filenamestr
Output path for the saved mask XML file.
- Returns:
- successbool
True if the mask was saved successfully, False otherwise.
- messagestr
Description of the outcome or error.
- select_cell(number, tol=0.1)[source]#
Transform to conventional cell using form number.
- Parameters:
- numberint
Form number.
- tolfloat, optional
Indexing tolerance. The default is 0.1.
- set_goniometer(peaks, R)[source]#
Set the goniometer matrix for a peaks workspace.
- Parameters:
- peaksstr
Name of peaks workspace.
- R3x3 array-like
Goniometer rotation matrix.
- set_manual_UB(constants, directions)[source]#
Set the unit cell parameters and directions manually.
- Parameters:
- constantslist
List of unit cell parameters [a, b, c, alpha, beta, gamma].
- directionslist
List of direction indices [u1, u2, u3, v1, v2, v3].
- set_peak(i, hkl, int_hkl, int_mnp)[source]#
Set the HKL, integer HKL, and integer MNP values for a specific peak.
- Parameters:
- iint
Index of the peak.
- hkllist
HKL coordinates.
- int_hkllist
Integer HKL coordinates.
- int_mnplist
Integer MNP coordinates.
- simplify_vector(vec)[source]#
Simplify a vector to its primitive integer form.
- Parameters:
- vecnp.ndarray
Input vector.
- Returns:
- int_vecnp.ndarray
Simplified integer vector.
- snapshot_filter_peaks()[source]#
Save a backup copy of the current peaks table before filtering.
Does nothing if there is no peaks table. Any existing backup is cleared first.
- sort_peaks_by_d(peaks)[source]#
Sort peaks table by descending d-spacing.
- Parameters:
- peaksstr
Name of peaks table.
- sort_peaks_by_hkl(peaks)[source]#
Sort peaks table by descending hkl values.
- Parameters:
- peaksstr
Name of peaks table.
- transform_lattice(transform, tol=0.1)[source]#
Apply a cell transformation to the lattice.
- Parameters:
- transform3x3 array-like
Transform to apply to hkl values.
- tolfloat, optional
Indexing tolerance. The default is 0.1.
- undo_filter_peaks()[source]#
Restore the peaks table from the filter-peaks backup, if available.
Replaces the current peaks table with the backup snapshot taken by snapshot_filter_peaks. Does nothing if no backup exists.
- validate_projection(proj)[source]#
Validate and unpack a 3x3 projection matrix into its row vectors.
- Parameters:
- projarray_like
Projection matrix, given as 9 values reshaped into 3x3, whose rows define the U, V, W basis vectors of the slice.
- Returns:
- U, V, Wndarray
Rows of the projection matrix.
- invalidbool
True if the projection matrix is singular (determinant close to zero), False otherwise.
NeuXtalViz.models.utilities module#
- class ParallelTasks(function, args)[source]#
Bases:
objectRun a function over chunks of values in parallel worker processes.
- Parameters:
- functioncallable
Function to execute in each worker process. It is called as
function(chunk, *args, proc)wherechunkis a subset of the values to process andprocis the worker/process index.- argstuple
Additional positional arguments passed to function after the chunk of values and before the process index.
Methods
run_tasks(values, n_proc)Split values into chunks and run the stored function in parallel.
- SaveMDToAscii(workspace, filename, exclude_integrated=True, format='%.6e')[source]#
Save an MDHistoToWorkspace to an ASCII file (column format).
- Parameters:
- workspacestr
Name of workspace as string.
- filenamestr
Path to output file.
- exclude_integratedbool, optional
Exclude integrated dimensions with bin size of one. Default is True.
- formatstr, optional
Column format. Default is “%.6e”.
NeuXtalViz.models.volume_slicer module#
- class VolumeSlicerModel[source]#
Bases:
NeuXtalVizModelModel for slicing and cutting reciprocal-space MD histogram volumes.
Wraps Mantid MD histogram workspaces (
histo/volume) to load and downsample 3D reciprocal-space data, and to produce 2D slices and 1D cuts of that data along axes aligned with the UB/W orientation matrices for visualization.Methods
ab_axes()\(c^*\)-direction in cartesian coordinates.
ab_star_axes()\(c\)-direction in cartesian coordinates.
activate_workspace(display_name[, progress, ...])Make a registered workspace the active one for slicing/cutting.
bc_axes()\(a^*\)-direction in cartesian coordinates.
bc_star_axes()\(a\)-direction in cartesian coordinates.
build_bond_network(nx, ny, nz, site_enabled)Build the distinct bond (separation-vector) set and unit-cell-edge wireframe for the bond-network viewer.
ca_axes()\(b^*\)-direction in cartesian coordinates.
ca_star_axes()\(b\)-direction in cartesian coordinates.
calculate_camera_parameters(direction, roll)Calculate roll, elevation, and azimuth from camera direction and roll.
calculate_clim(trans[, method, symmetric_zero])Calculate color limits for visualization based on a method.
calculate_pdf(input_display_name, ...[, ...])Zero-pad and Fourier-transform a (typically blurred) workspace.
combine_workspaces(ws_a, coeff_a, ws_b, ...)Compute
coeff_a * ws_a - coeff_b * ws_band register the result.delete_workspace(display_name)Remove a registered workspace and delete its backing workspace.
files_exist(files)Check if the specified files exist and are readable.
get_cut_info(axis, value[, thickness])Get cut information for a given axis and value.
get_histo_info(normal)Get histogram information for a given normal direction.
get_normal_plane(ind)Get the normal vector for a plane given an index vector.
get_oriented_lattice_parameters()Obtain the oriented lattice parameters.
get_slice_info(normal, value[, thickness, ...])Get slice information for a given normal and value.
get_transform([reciprocal])Get the transformation matrix for the current UB and W matrices.
Get projection, transform, and scale matrices for the current UB and W.
get_vector(axes_type, ind)Vector corresponding to a particular crystallographic direction.
has_UB(ws)Check if the oriented lattice exists on a workspace.
is_cut()Check if a cut workspace exists in Mantid.
Check if a histogram workspace is loaded in Mantid.
Check if a slice workspace exists in Mantid.
load_bond_cif(filename[, progress, stop_event])Load a CIF for the bond-network viewer.
load_md_histo_workspace(filename[, display_name])Load a Mantid MD histogram workspace from a file, register it, and make it the active workspace.
Preview the display name that would be auto-assigned to the next
load_md_histo_workspace()call, without consuming the load counter (so the preview stays accurate if the caller doesn't end up loading, e.g. the user cancels a naming prompt).Compute the orientation matrix for the current UB and W matrices.
register_workspace(display_name, ws_name[, ...])Register a workspace so it can be selected via the workspace combo.
rename_workspace(old_display_name, ...)Rename a registered workspace's display name.
rotate_camera_azimuth(position, focal_point, ...)Rotate the camera left/right about a global up axis.
rotate_camera_elevation(position, ...)Tilt the camera up/down about its right axis.
rotate_camera_roll(position, focal_point, ...)Apply a roll about the current viewing axis.
run_blur(input_display_name, ...[, ...])NaN-Gaussian-blur the gaps (e.g. from a Bragg punch) closed.
run_bragg_punch(input_display_name, ...[, ...])Punch Bragg-reflection outliers and mask the low-Q region.
run_karen(input_display_name, ...[, ...])Remove Bragg-peak outliers with the KAREN algorithm.
sample_bond_correlations(geometry, display_name)Sample a 3D-ΔPDF workspace at each bond's separation vector.
save_cut(filename)Save the current cut workspace to an ASCII file.
save_md_workspace(display_name, filename)Save a registered workspace's backing MD workspace to a file.
save_slice(filename)Save the current slice workspace to an ASCII file.
set_B()Set the B matrix from the UB of the loaded histogram workspace.
set_UB(UB)Update the UB-matrix.
set_W()Set the W matrix from the workspace log if available, otherwise identity.
- activate_workspace(display_name, progress=None, stop_event=None, **kwargs)[source]#
Make a registered workspace the active one for slicing/cutting.
Clones the registered workspace into the fixed internal
"histo"slot (deleting any previous"histo"/"volume"/"slice"/"cut"first to bound memory use) and re-runs the same setupload_md_histo_workspaceperforms afterLoadMD, so the existing slice/cut pipeline is otherwise untouched.- Parameters:
- display_namestr
Display name previously passed to
register_workspace().- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure) – cloning/downsampling can take a while for a large workspace.- stop_eventthreading.Event, optional
Unused; accepted because the presenter runs this on a worker thread, which always passes it (injected by the worker infrastructure).
- build_bond_network(nx, ny, nz, site_enabled, tolerance=0.001, progress=None, stop_event=None, **kwargs)[source]#
Build the distinct bond (separation-vector) set and unit-cell-edge wireframe for the bond-network viewer.
Bonds are not found via a covalent-radius distance cutoff – that isn’t a meaningful criterion here (this tool samples 3D-ΔPDF correlation strength at a separation vector; it doesn’t need “is this a real chemical bond”). Instead, this follows the same construction as the reference
DiffuseRefinementscript’sinitialize_unit_cell_atoms+pair_expansion:Every enabled site is expanded by the space group’s symmetry operations into all of its equivalent positions within the unit cell, each wrapped into
[0, 1).Every pairwise separation vector between these expanded positions is computed (the full N×N set, not just an upper triangle) – these are the bonds within the unit cell.
Each is wrapped into
[0, 1)(a unit cell’s own fractional coordinates always span that range) and deduplicated (within tolerance) to the set of distinct new positions.Periodic images of each are then generated by adding every requested lattice translation to it, and each resulting vector is explicitly unioned with its own negation before deduping again. This step is required, not optional: wrapping to
[0, 1)in step 3 is one-sided (it shifts negative components up by 1, never shifts positive ones down), so a vector’s negation is generally not produced naturally by this same translation loop at the mirror translation – verified empirically (corundum): without this explicit union, 34-66% of the extended set was missing its negation partner, not a rare edge effect. Explicitly including it also has the side benefit of centering the final set on the origin regardless of where the wrapped unit_cell_bonds themselves happen to sit, matching the unit-cell wireframe (see below).
- Parameters:
- nx, ny, nzint
Number of unit cells to repeat along a, b, c in each direction (translations run
-n...+ninclusive along each axis, i.e.2n+1cells – an odd count is what keeps the translation range closed under negation, which is what makes the extended bond set centrosymmetric; see above).- site_enabledlist of bool
One flag per site returned by
load_bond_cif()(same order); disabled sites (and all of their symmetry-equivalent copies) are excluded.- tolerancefloat, optional
Fractional-coordinate tolerance used to collapse separation vectors that are effectively the same crystallographic bond (default 1e-3).
- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure).- stop_eventthreading.Event, optional
Cooperative-cancellation event (injected by the worker infrastructure).
- Returns:
- geometrydict
Dictionary with keys
"bond_vectors"((N, 3) array of Cartesian separation vectors, Angstrom, each measured from an implicit origin) and"edges"(list of (p0, p1) Cartesian line segments for the repeated unit-cell wireframe). None if cancelled via stop_event.
- calculate_clim(trans, method='normal', symmetric_zero=False)[source]#
Calculate color limits for visualization based on a method.
- Parameters:
- transnp.ndarray
Signal array to calculate color limits for (clipped in place and also returned).
- methodstr, optional
Method for calculation: ‘normal’ (mean +/- 3 sigma), ‘boxplot’ (quartiles +/- 1.5 IQR), or any other value for plain min/max (default ‘normal’).
- symmetric_zerobool, optional
If True, force the computed limits to be symmetric about zero (
cmax = max(abs(cmin), abs(cmax)),cmin = -cmax) before clipping – for signed data (e.g. a delta-PDF result) displayed with a zero-aware transfer function (default False).
- Returns:
- transnp.ndarray
The input array with values clipped to the calculated color limits.
- calculate_pdf(input_display_name, output_display_name, Q_outer, window='None', progress=None, stop_event=None, **kwargs)[source]#
Zero-pad and Fourier-transform a (typically blurred) workspace.
Runs, on
input_display_name(typically the output ofrun_blur(), though any registered workspace may be used directly): a zero-pad out toQ_outer, an optional apodization window to suppress FFT series-termination ripples, then an FFT to real space. Registers the result as a new real-space workspace (seeself.workspace_registry).- Parameters:
- input_display_namestr
Display name of the (already-registered) workspace to transform.
- output_display_namestr
Display name for the delta-PDF result.
- Q_outerfloat
Zero-pad extent, in Å⁻¹.
- windowstr, optional
Apodization window applied before the FFT:
"None"(default),"Lorch", or"Hann"– see_apodization_window().- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure).- stop_eventthreading.Event, optional
Cooperative-cancellation event (injected by the worker infrastructure).
- Returns:
- display_namestr
output_display_name, unchanged – re-running this step with the same output name overwrites its previous result in place rather than accumulating new entries.
- combine_workspaces(ws_a, coeff_a, ws_b, coeff_b, output_display_name)[source]#
Compute
coeff_a * ws_a - coeff_b * ws_band register the result.Uses explicit Mantid algorithms with explicit output names throughout (a scalar
WorkspaceSingleValuemultiplied viaMultiplyMD, thenMinusMD) rather than Python operator overloads, which infer their output name from the caller’s frame and are unreliable to use inside a method.- Parameters:
- ws_a, ws_bstr
Display names of two already-registered workspaces.
- coeff_a, coeff_bfloat
Scale factors applied before subtracting.
- output_display_namestr
Display name for the combined result (disambiguated if it collides with an existing one).
- Returns:
- display_namestr
The (possibly disambiguated) display name actually used.
- Raises:
- ValueError
If
ws_aandws_bdo not share common binning (same number of dimensions, bins, and extents per dimension).MinusMDoperates element-wise on the signal arrays, so mismatched binning would silently combine voxels that don’t correspond to the same point in reciprocal space.
- delete_workspace(display_name)[source]#
Remove a registered workspace and delete its backing workspace.
If
display_nameis currently active, the active"histo"/"volume"/"slice"/"cut"scratch workspaces are independent clones and are left as they are – they simply won’t correspond to any registry entry until a different workspace is activated.- Parameters:
- display_namestr
Display name to remove.
- get_cut_info(axis, value, thickness=0.01)[source]#
Get cut information for a given axis and value.
- Parameters:
- axisarray-like
Axis along which to cut (e.g., [1,0,0]).
- valuefloat
Position along the axis to cut.
- thicknessfloat, optional
Thickness of the cut (default 0.01).
- Returns:
- dict
Dictionary containing x, y, e, label, value, and title.
- get_histo_info(normal)[source]#
Get histogram information for a given normal direction.
- Parameters:
- normalarray-like
Normal vector for the slicing direction.
- Returns:
- dict
Dictionary containing signal, limits, spacing, labels, and transforms.
- get_normal_plane(ind)[source]#
Get the normal vector for a plane given an index vector.
- Parameters:
- indarray-like
One-hot index vector (e.g.
[1, 0, 0]) selecting the slicing axis in the W-projected basis.
- Returns:
- vecnp.ndarray or None
Normal vector for the plane in Cartesian coordinates, or None if no UB matrix has been set.
- get_slice_info(normal, value, thickness=0.01, xlim=None, ylim=None)[source]#
Get slice information for a given normal and value.
- Parameters:
- normalarray-like
Normal vector for the slicing direction.
- valuefloat
Position along the normal to slice.
- thicknessfloat, optional
Thickness of the slice (default 0.01).
- xlimlist, optional
X-axis limits for the slice (default None).
- ylimlist, optional
Y-axis limits for the slice (default None).
- Returns:
- dict
Dictionary containing x, y, labels, signal, transform, aspect, value, and title.
- get_transform(reciprocal=True)[source]#
Get the transformation matrix for the current UB and W matrices.
Overrides
NeuXtalVizModel.get_transform()to account for the additional W matrix (projection into the slicing basis). Returns None if no UB matrix is set.- Parameters:
- reciprocalbool, optional
If True, return reciprocal transformation; else real space (default True).
- Returns:
- Tnp.ndarray or None
Normalized 3x3 transformation matrix, or None if no UB matrix has been set.
- get_transforms()[source]#
Get projection, transform, and scale matrices for the current UB and W.
- Returns:
- pnp.ndarray
Projection matrix, normalized so its first diagonal element is 1.
- tnp.ndarray
Transform matrix, normalized by the column norms of the Cholesky factor.
- snp.ndarray
Scale factors (column norms of p).
- is_cut()[source]#
Check if a cut workspace exists in Mantid.
- Returns:
- bool
True if ‘cut’ workspace exists, False otherwise.
- is_histo_loaded()[source]#
Check if a histogram workspace is loaded in Mantid.
- Returns:
- bool
True if ‘histo’ workspace exists, False otherwise.
- is_sliced()[source]#
Check if a slice workspace exists in Mantid.
- Returns:
- bool
True if ‘slice’ workspace exists, False otherwise.
- load_bond_cif(filename, progress=None, stop_event=None, **kwargs)[source]#
Load a CIF for the bond-network viewer.
- Parameters:
- filenamestr
Path to the CIF file to load.
- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure).- stop_eventthreading.Event, optional
Unused; accepted because the presenter runs this on a worker thread, which always passes it (injected by the worker infrastructure).
- Returns:
- siteslist of dict
One entry per asymmetric-unit site, each with keys
"label"(an auto-generated"{element}{n}"label, since Mantid’s CrystalStructure does not retain the CIF’s own _atom_site_label values),"element", and fractional"x"/"y"/"z". Unchecking a site in the atom table excludes it from every pair considered bybuild_bond_network().
- load_md_histo_workspace(filename, display_name=None)[source]#
Load a Mantid MD histogram workspace from a file, register it, and make it the active workspace.
The file is loaded into its own stable, registry-backed workspace (not directly into
"histo"), so it survives later calls toactivate_workspace()for other registered workspaces –"histo"itself is just a scratch slot that gets deleted/recreated on every activation.- Parameters:
- filenamestr
Path to the Mantid MD histogram file to load.
- display_namestr, optional
User-facing name for the workspace combo. Defaults to a sequential
"data","data_2","data_3", … name (the counter never repeats, even across renamed/deleted entries), disambiguated further if it still collides with an already-registered name.
- next_load_display_name()[source]#
Preview the display name that would be auto-assigned to the next
load_md_histo_workspace()call, without consuming the load counter (so the preview stays accurate if the caller doesn’t end up loading, e.g. the user cancels a naming prompt).- Returns:
- display_namestr
The sequential
"data"/"data_2"/… name that would be used next, disambiguated against the current registry.
- orientation_matrix()[source]#
Compute the orientation matrix for the current UB and W matrices.
Overrides
NeuXtalVizModel.orientation_matrix()to account for the additional W matrix (projection into the slicing basis).- Returns:
- Unp.ndarray
3x3 orientation matrix combining the UB and W matrices.
- register_workspace(display_name, ws_name, space='reciprocal')[source]#
Register a workspace so it can be selected via the workspace combo.
- Parameters:
- display_namestr
User-facing name shown in the workspace combo box.
- ws_namestr
Actual Mantid AnalysisDataService workspace name.
- spacestr, optional
Either
"reciprocal"(default) for ordinary Q-space data, or"real"for a delta-PDF (direct-space) result. Drives which physical basis matrix and axis labeling (hkl vs. uvw) is used when this workspace is active.
- rename_workspace(old_display_name, new_display_name)[source]#
Rename a registered workspace’s display name.
Only the registry entry’s key changes – the underlying Mantid workspace name is left as-is, so this is safe to call whether or not the workspace is currently active.
- Parameters:
- old_display_namestr
Current display name (registry key).
- new_display_namestr
New display name. Disambiguated if it collides with another already-registered name.
- Returns:
- new_display_namestr
The (possibly disambiguated) display name actually used.
- run_blur(input_display_name, output_display_name, Q_blur, progress=None, stop_event=None, **kwargs)[source]#
NaN-Gaussian-blur the gaps (e.g. from a Bragg punch) closed.
Runs, on
input_display_name(typically the output ofrun_bragg_punch(), though any registered workspace may be used directly): a NaN-aware Gaussian blur of scaleQ_blurfilling the gaps left by the punch/cut. A separate, inspectable step – the result can be sliced/viewed like any ordinary reciprocal-space workspace before runningcalculate_pdf()on it.- Parameters:
- input_display_namestr
Display name of the (already-registered) workspace to blur.
- output_display_namestr
Display name for the blurred result.
- Q_blurfloat
Gaussian blur scale, in Å⁻¹.
- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure).- stop_eventthreading.Event, optional
Cooperative-cancellation event (injected by the worker infrastructure).
- Returns:
- display_namestr
output_display_name, unchanged – re-running this step with the same output name overwrites its previous result in place rather than accumulating new entries.
- run_bragg_punch(input_display_name, output_display_name, space_group, Q_size, Q_inner, outlier=1.5, progress=None, stop_event=None, **kwargs)[source]#
Punch Bragg-reflection outliers and mask the low-Q region.
For every allowed reflection (per
space_group) within the workspace’s extent, examines an ellipsoidal region of half-widthQ_size(in Å⁻¹) around that reflection and removes (sets to NaN) only the voxels that are statistical outliers relative to that local region – following the interquartile-range (Tukey’s fences) approach used by rmc-discord’spunch: a voxel is rejected if it falls outside[Q1 - outlier*IQR, Q3 + outlier*IQR], whereQ1/Q3are the 25th/75th percentiles of the ellipsoid’s own values andIQR = Q3 - Q1. Unlike unconditionally blanking the whole ellipsoid, this keeps genuine diffuse scattering that happens to sit near a Bragg peak. The low-Q region withinQ_innerof the origin is masked separately (that’s a beamstop/forward-scattering cut, not a peak). The result is registered as a new (still reciprocal-space) workspace – a separate, inspectable step that can be sliced/viewed like any ordinary reciprocal-space workspace before runningrun_blur()on it.- Parameters:
- input_display_namestr
Display name of the (already-registered) workspace to punch.
- output_display_namestr
Display name for the punched result.
- space_groupstr
Space-group symbol understood by
mantid.geometry.SpaceGroupFactory.createSpaceGroup.- Q_sizefloat
Half-width, in Å⁻¹, of the ellipsoidal region examined around each allowed reflection.
- Q_innerfloat
Inner cut radius, in Å⁻¹.
- outlierfloat, optional
Tukey’s-fences scale factor applied to each reflection’s local IQR (default 1.5, the conventional value).
- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure).- stop_eventthreading.Event, optional
Cooperative-cancellation event (injected by the worker infrastructure).
- Returns:
- display_namestr
output_display_name, unchanged – re-running this step with the same output name overwrites its previous result in place rather than accumulating new entries.
- run_karen(input_display_name, output_display_name, width, z_score=3.0, progress=None, stop_event=None, **kwargs)[source]#
Remove Bragg-peak outliers with the KAREN algorithm.
An alternative to
run_bragg_punch()+run_blur(), following Mantid’sDeltaPDF3D“KAREN” method: a moving-window median filter estimates a local median and median absolute deviation (MAD) at every voxel; voxels more thanz_score(robust, MAD-based) standard deviations from the local median are replaced withmedian + 2.2*MAD. Since this replaces outliers in place rather than punching NaNs out, no separate fill/blur step is needed beforecalculate_pdf(). A separate, inspectable step – the result can be sliced/viewed like any ordinary reciprocal-space workspace.- Parameters:
- input_display_namestr
Display name of the (already-registered) workspace to filter.
- output_display_namestr
Display name for the KAREN-filtered result.
- widthfloat
Moving-window size, in Å⁻¹ – the same meaning as
run_blur()’sQ_blur, converted per-axis into filter-window bins.- z_scorefloat, optional
Outlier cutoff, in estimated standard deviations (1.4826*MAD) from the local median (default 3.0, matching Mantid’s
DeltaPDF3D“KAREN” method).- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure).- stop_eventthreading.Event, optional
Cooperative-cancellation event (injected by the worker infrastructure).
- Returns:
- display_namestr
output_display_name, unchanged – re-running this step with the same output name overwrites its previous result in place rather than accumulating new entries.
- sample_bond_correlations(geometry, display_name, tolerance=0.001, progress=None, stop_event=None, **kwargs)[source]#
Sample a 3D-ΔPDF workspace at each bond’s separation vector.
Maps each bond’s Cartesian separation vector to its nearest grid coordinate in the workspace’s own real-space basis and reads that voxel’s signed value directly – no neighborhood search or shell integration is performed.
A ΔPDF value at real-space vector
rreflects the correlated pair-density for atom pairs separated byr– since this depends only on the separation (not the pair’s absolute position), every translationally-equivalent copy of a bond across the supercell samples the identical grid location automatically, with no separate symmetry-family grouping step needed.Reads
display_name’s own UB/W directly (via_read_ub_w()), not the CIF’s own basis, nor self.UB/self.W (whatever’s active in the Slice tab) – the workspace sampled here can be any registered real-space result the user selects, and need not be the active one. Its own UB/W need not agree with the CIF’s basis either, if it was built with a non-identity W_MATRIX projection.- Parameters:
- geometrydict
Geometry dictionary from
build_bond_network()(only"bond_vectors"is used).- display_namestr
Display name of a registered real-space (3D-ΔPDF) workspace – see self.workspace_registry.
- tolerancefloat, optional
Per-axis slack (in grid-index units, applied independently to x, y, and z), allowed when checking that a bond’s nearest grid coordinate falls within the workspace’s extent – guards against floating-point roundoff putting an on-boundary index just outside
[0, n_bins)(default 1e-3).- progresscallable, optional
progress(message, percent)callback (injected by the worker infrastructure).- stop_eventthreading.Event, optional
Cooperative-cancellation event (injected by the worker infrastructure).
- Returns:
- values(len(bond_vectors),) ndarray or None
Signed ΔPDF value sampled for each bond (NaN where the vector falls outside the workspace’s extent, or its nearest voxel is itself NaN). None if
display_nameisn’t a registered real-space workspace, or if cancelled via stop_event.
- save_cut(filename)[source]#
Save the current cut workspace to an ASCII file.
- Parameters:
- filenamestr
Output filename for the cut.
- save_md_workspace(display_name, filename)[source]#
Save a registered workspace’s backing MD workspace to a file.
- Parameters:
- display_namestr
Display name previously passed to
register_workspace()(or returned by one of the load/derived-workspace steps below).- filenamestr
Output file path (
.nxs).