Results#
FrameResult owns Python copies of native indexing output. A result with no
identified patterns is valid and can still contain detected peaks and frame
statistics.
Results files#
See Results files for writing, loading, and converting.
- class lauelab.indexing.ResultsWriter(path, *, crystal, geometry, peak_params, index_params, detector_index, detector_id, cosmic_filter, overwrite=False, compression=None)[source]#
Write indexing results incrementally to one HDF5 file.
Notes
Every
append()checks the result type and the frame identity before touching the file. If a write then raises, for any reason including malformed result content, the file is left with a partially appended frame and the writer is marked failed:failedbecomes True,errorholds the exception, and further appends are refused. There is no transactional recovery; the file is not a valid results file and the run must be rewritten from the start.validate_results_file()detects such a file.- append(result, frame_id=None)[source]#
Append one frame result and its ragged peaks and patterns.
- Parameters:
result (FrameResult) – The frame result to store.
frame_id – Unique string or integer identity; defaults to the zero-based append position. All identities in one file share one kind.
- Raises:
RuntimeError – If the writer is not open or has failed earlier.
TypeError, ValueError – If
resultis not aFrameResultorframe_idis not a unique identity of the file’s kind. These are raised before anything is written, so the writer remains usable.Exception – Any error raised while writing, including one caused by malformed result content such as a sample position of the wrong length, marks the writer failed and propagates.
- class lauelab.indexing.XmlResultsWriter(path, *, overwrite=False)[source]#
Write frame results to one LaueGo
AllStepsXML document incrementally.- Parameters:
- failed#
True once a write to the file raised. The document may then be truncated or malformed; further appends are refused.
- Type:
Notes
Output is byte-identical to
write_combined_xmlfor the same steps, and each step is serialized, written, and flushed when it arrives, so memory use does not grow with the number of frames. Use the writer as a context manager; leaving the block writes the closing tag and closes the file even when the body raised. After a failed write,close()first truncates the file back to the end of the last completely written step, so the document stays well formed up to that step whenever the filesystem still accepts the closing tag.This is the auxiliary output of an indexing run. A caller that also writes an HDF5 results file should treat a failure here as a warning about the XML alone; the HDF5 file is unaffected.
- append(item)[source]#
Append one
FrameResultor LaueGoStep.- Raises:
RuntimeError – If the writer is not open, has already failed, or the result has no XML snapshot.
TypeError – If
itemis neither aFrameResultnor aStep.OSError – If writing fails. The writer is then marked
failed.
- close()[source]#
Write the closing tag and close the file. Safe to call twice.
After a failed append the file is truncated to the end of the last complete step and the closing tag is still attempted, so that the document ends properly whenever the filesystem allows; a second failure is recorded in
errorand not raised again.
- lauelab.indexing.validate_results_file(path, *, frame_ids=None, n_frames=None)[source]#
Check the structure of a closed indexing-results file with bounded reads.
- Parameters:
- Returns:
ResultsFileSummary – Counts and provenance read during the check.
- Raises:
OSError – If the file cannot be opened as HDF5.
InvalidResultsFile – If the format marker or version is wrong; a group or dataset is missing or has the wrong dtype or trailing shape; per-frame, per-peak, per-pattern, or per-assignment datasets disagree in length; an offsets dataset does not start at zero, increase monotonically, and end at its group’s row count;
n_peaks,n_patterns, orn_indexeddisagree with the offsets; pattern ranks do not restart at zero within each frame; an assignment refers outside its owning frame; frame identities repeat; or the file does not matchframe_idsorn_frames.
- Return type:
Notes
The check reads dataset shapes and dtypes, the per-frame and per-pattern bookkeeping arrays (identities, counts, ranks, offsets), and root attributes. Assignment peak indices are checked in bounded chunks. Peak values, reciprocal lattices, and other assignment arrays are not read. It establishes that the file is complete and self-consistent, not that the science in it is right; a valid file can describe an incomplete run.
- class lauelab.indexing.ResultsFileSummary(path, version, n_frames, n_peaks, n_patterns, n_assignments, frame_ids, has_crystal, has_geometry_text, created, lauelab_version, source=None)[source]#
Counts and provenance of a validated indexing-results file.
- Parameters:
path (Path) – The validated file.
version (int) – Layout version.
n_frames (int) – Row counts of the four record groups.
n_peaks (int) – Row counts of the four record groups.
n_patterns (int) – Row counts of the four record groups.
n_assignments (int) – Row counts of the four record groups.
frame_ids (tuple) – Frame identities in file order, as strings or integers.
has_crystal (bool) – Whether the file carries a crystal group.
has_geometry_text (bool) – Whether the geometry XML text is embedded.
created (str) – Root attributes written by the producer.
lauelab_version (str) – Root attributes written by the producer.
source (str | None) – The XML document a converted file came from, or None.
- lauelab.is_results_file(path)[source]#
Return whether path carries the lauelab indexing-results format marker.
This reads only the root
formatattribute. It tells a results file apart from other HDF5 files such as detector frames; it does not check that the file is complete or consistent. Uselauelab.indexing.validate_results_file()for that.
- lauelab.partial_path(final)[source]#
Return the in-progress name for final: the same name with
.partialappended.- Parameters:
final (str | Path) – Destination the finished file will have.
- Returns:
pathlib.Path –
finalwith.partialadded after its full name, in the same directory, so thatpublish_file()can rename it into place.- Return type:
Path
- lauelab.publish_file(partial, final, *, overwrite=False)[source]#
Move a closed, validated file into its final name in the same directory.
- Parameters:
partial (str | Path) – The finished file, normally from
partial_path(). It must be closed; publish after every writer has released it.final (str | Path) – Destination path in the same directory as
partial.overwrite (bool) – Replace an existing
final. The default refuses to clobber: an existing destination raisesFileExistsErrorandpartialis left in place. The refusal is atomic with respect to another publisher on filesystems that support hard links.
- Returns:
pathlib.Path –
final.- Raises:
FileNotFoundError – If
partialdoes not exist.ValueError – If the two paths are not in the same directory.
FileExistsError – If
finalexists andoverwriteis False.OSError – For other filesystem failures.
- Return type:
Path
Notes
The rename is one filesystem operation, so a reader never observes a half-written
final. This function does not validate content; call the format’s validator onpartialfirst.
File layout#
Format lauelab-indexing-results, version 1. Root attributes are format, version, lauelab_version, created, and, for a converted file, source. The run group has no datasets; its attributes are program, detector_index, detector_id, cosmic_filter, and one attribute per PeakParams and IndexParams field. The crystal group carries name, space_group, setting, and source as attributes and is absent when the run had no crystal. The geometry group carries path as an attribute.
A converted file carries only the run attributes the XML recorded, when present: program, peak_program, cosmic_filter, max_rfactor, max_peaks, min_separation, peak_shape, mask_file, kev_max_calc, kev_max_test, angle_tolerance_deg, cone_deg, and hkl_prefer.
n is the row count of the group. Rows of peaks, patterns, and assignments are grouped by owner; the rows of owner i are offsets[i] to offsets[i + 1] of the matching offsets dataset, which has one more entry than there are owners. Absent values are NaN for floating-point datasets, -1 for scan_numbers, beam_bad, and light_on, and the empty string for string datasets. Coordinates in peaks are zero-based frame pixel (x, y) values.
Dataset |
dtype |
Shape |
Units |
Meaning |
|---|---|---|---|---|
|
|
|
nm, deg |
|
|
string |
|
Element symbol per atom |
|
|
string |
|
Site label per atom |
|
|
|
|
fractional |
Fractional coordinates |
|
|
|
Site occupancy |
|
|
string |
scalar |
Geometry file text; present when the file was readable at write time |
|
|
|
|
Frame identifier |
|
|
|
|
um |
Sample |
|
|
|
um |
Sample depth passed to the geometry conversion |
|
|
|
Scan number |
|
|
|
|
keV |
Incident energy |
|
|
|
s |
Detector exposure time |
|
|
|
Acquisition flags, |
|
|
|
|
unspecified |
Acquisition values without an established unit; no conversion applied |
|
string |
|
Detector identifier |
|
|
string |
|
Source HDF5 path |
|
|
string |
|
Point ID recorded in the point file at |
|
|
|
|
Zero-based depth index of that frame, |
|
|
string |
|
Acquisition metadata strings |
|
|
|
|
Frame shape as |
|
|
|
|
Full-detector |
|
|
|
|
Pixel grouping factors |
|
|
|
|
Detected peaks |
|
|
|
|
Identified patterns |
|
|
|
|
Peak-search threshold |
|
|
|
|
Automatic-threshold ratio; |
|
|
|
|
Sum of unmasked pixel values |
|
|
|
|
Sum of pixel values above the threshold |
|
|
|
|
Pixels above the threshold |
|
|
|
|
Effective peak-fit parameters |
|
|
|
|
Effective fit box size |
|
|
|
|
s |
Stage timing |
|
|
|
Row range of each frame in |
|
|
|
|
Row range of each frame in |
|
|
|
|
pixel |
Fitted peak coordinate |
|
|
|
Fitted intensity, integral, and background |
|
|
|
|
pixel |
Fitted half-widths |
|
|
|
deg |
Fitted tilt |
|
|
|
Normalized fit residual |
|
|
|
|
Unit scattering vector |
|
|
|
|
Pattern index within its frame |
|
|
|
|
1/nm |
Rows |
|
|
|
Native goodness score |
|
|
|
|
deg |
Root-mean-square angular error |
|
|
|
Assignments in the pattern |
|
|
|
|
Row range of each pattern in |
|
|
|
|
Zero-based index into the owning frame’s peaks |
|
|
|
|
Miller indices |
|
|
|
|
deg |
Angular error |
|
|
|
keV |
Photon energy |
|
|
|
Predicted intensity |
Frame Result#
- class lauelab.indexing.FrameResult(peaks, patterns, threshold_used, total_sum, sum_above_threshold, num_above_threshold, peaksearch_seconds, indexing_seconds, threshold_ratio=4.0, peak_minwidth=0.0, peak_maxwidth=0.0, peak_max_cent_to_fit=0.0, peak_boxsize=0, metadata={}, input_image=None, image_shape=(0, 0), start=(0, 0), group=(1, 1), depth=None, source=None, image=None)[source]#
Self-contained result of processing one diffraction frame.
- Parameters:
peaks (numpy.ndarray) – Structured peak array with shape
(n,). Fields arefit_x,fit_y,intens,integral,hwhm_x,hwhm_y,tilt,chisq,background, and the three-componentqhatvector.patterns (tuple[lauelab.indexing.indexer.Pattern, ...]) – Crystal orientations identified in the frame.
threshold_used (float) – Intensity threshold used by peak search. This is
NaNwhen automatic thresholding receives no unmasked nonzero pixels.total_sum (float) – Sum of unmasked raw frame pixel values.
sum_above_threshold (float) – Sum of pixel values above
threshold_used.num_above_threshold (int) – Number of pixels above
threshold_used.peak_minwidth (float) – Effective fitting parameters configured by the native peak search.
peak_maxwidth (float) – Effective fitting parameters configured by the native peak search.
peak_max_cent_to_fit (float) – Effective fitting parameters configured by the native peak search.
peak_boxsize (int) – Effective fitting parameters configured by the native peak search.
peaksearch_seconds (float) – Elapsed peak-search time in seconds.
indexing_seconds (float) – Elapsed orientation-indexing time in seconds. Pixel-to-q conversion is not included in either timing field.
threshold_ratio (float) – Resolved automatic-threshold ratio supplied to native peak search, or
NaNwhen an absolute threshold made the ratio inactive.metadata (Mapping[str, object]) – Experiment metadata copied into the result.
input_image (str | None) – Source HDF5 path, or None for an in-memory frame. For a
ScanFramethis is the point file’s path;sourceholds the point and depth.source (lauelab.indexing._frame.ScanFrame | None) – The
ScanFramethat selected the frame, or None for an array or a per-frame HDF5 file.image_shape (tuple[int, int]) – Frame shape as
(rows, columns).start (tuple[int, int]) – Zero-based detector
(x, y)origin of the frame.group (tuple[int, int]) – Detector-pixel grouping factors as
(x, y).depth (float | None) – Physical sample depth in micrometres used by the geometry conversion, or None when no depth applied. For HDF5 input this is the explicit argument when one was given, otherwise the file’s
entry1/depth.image (numpy.ndarray | None) – Retained contiguous frame in its input dtype, or None when image retention was disabled. This array can alias a contiguous array supplied by the caller. Native smoothing uses a separate working copy.
Notes
Native result memory is released before this object is returned. The dataclass is frozen, but contained arrays and the metadata mapping may remain mutable. A result with no patterns is valid and has
indexedset to False.- property indexed_peak_indices: numpy.ndarray#
Sorted unique peak indices assigned to any pattern.
- Returns:
numpy.ndarray – One-dimensional array of zero-based indices into
peaks.
- property unindexed_peak_indices: numpy.ndarray#
Sorted peak indices not assigned to a pattern.
- Returns:
numpy.ndarray – One-dimensional array of zero-based indices into
peaks.
- write_xml(path)[source]#
Write this result in the LaueGo XML format.
- Parameters:
path (str | Path) – Destination XML file. An existing file is replaced.
- Raises:
RuntimeError – If the result was constructed manually without an XML snapshot.
OSError – If the destination cannot be written.
Indexed Pattern#
See the results guide for the reciprocal-basis convention used by Pattern.reciprocal.
- class lauelab.indexing.Pattern(euler_deg, rotation, reciprocal, goodness, rms_error_deg, hkl, pk_index, err_deg, energy_kev, pred_intens)[source]#
One crystal orientation identified in a diffraction frame.
- Parameters:
euler_deg (numpy.ndarray) – Euler angles in degrees, with shape
(3,).rotation (numpy.ndarray) – Orientation rotation matrix with shape
(3, 3).reciprocal (numpy.ndarray) – Reciprocal-lattice matrix with shape
(3, 3)in1/nm. Rows area*,b*, andc*; a Miller-index row maps to reciprocal space asq = hkl @ reciprocal.goodness (float) – Native indexer’s goodness score for the pattern.
rms_error_deg (float) – Root-mean-square angular indexing error in degrees.
hkl (numpy.ndarray) – Integer Miller indices with shape
(n, 3).pk_index (numpy.ndarray) – Zero-based indices into the frame’s peak array, with shape
(n,).err_deg (numpy.ndarray) – Per-peak angular errors in degrees, with shape
(n,).energy_kev (numpy.ndarray) – Per-peak photon energies in keV, with shape
(n,).pred_intens (numpy.ndarray) – Per-peak predicted intensities, with shape
(n,).
Notes
The dataclass is frozen, but its NumPy arrays remain mutable. Each pattern owns Python arrays copied from the native result.