Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
#include "ComputeCAxisReferenceMisalignments.hpp"

#include "simplnx/Common/Numbers.hpp"
#include "simplnx/Common/TypesUtility.hpp"
#include "simplnx/DataStructure/DataArray.hpp"
#include "simplnx/Utilities/DataArrayUtilities.hpp"
#include "simplnx/Utilities/ThrottledMessageHandler.hpp"

#include <EbsdLib/Core/EbsdLibConstants.h>
#include <EbsdLib/Orientation/OrientationMatrix.hpp>
#include <EbsdLib/Orientation/Quaternion.hpp>

#include <fmt/ranges.h>
#include <fmt/format.h>

#include <algorithm>
#include <cmath>
Expand All @@ -26,105 +24,6 @@ namespace
{
constexpr usize k_ChunkTuples = 4096;
constexpr std::string_view k_ProgressLabel = "Computing C-Axis Reference Misalignments";

/**
* @brief Names the type of a selected object for a type error.
* @param object Selected object.
* @return For a DataArray, its element type (for example "float64"); otherwise the object type name (for example "StringArray").
*/
std::string DescribeObjectType(const DataObject& object)
{
if(const auto* dataArrayPtr = dynamic_cast<const IDataArray*>(&object); dataArrayPtr != nullptr)
{
return DataTypeToString(dataArrayPtr->getDataType()).str();
}
return object.getTypeName();
}

/**
* @brief Makes the error for a path that does not name an array of the required type.
* @param dataStructure Holds the selected object, if any.
* @param path Selected path.
* @param label User-facing name of the input, for the message.
* @param requiredType Accepted element types, quoted, for the message (for example "'bool' or 'uint8'").
* @param errorCode Code of the error.
* @return An error that says whether the path is missing or names the type it has.
*/
Result<> MakeArrayTypeError(const DataStructure& dataStructure, const DataPath& path, std::string_view label, std::string_view requiredType, int32 errorCode)
{
const auto* objectPtr = dataStructure.getData(path);
if(objectPtr == nullptr)
{
return MakeErrorResult(errorCode, fmt::format("{} path '{}' does not exist. Select an array of type {}.", label, path.toString(), requiredType));
}
return MakeErrorResult(
errorCode, fmt::format("{} path '{}' has type '{}', but type {} is required. Select an array of type {}.", label, path.toString(), DescribeObjectType(*objectPtr), requiredType, requiredType));
}

/**
* @brief Checks that an array has exactly the required component shape.
* @param array Array to check.
* @param path Path of the array, for the message.
* @param label User-facing name of the input, for the message.
* @param componentShape Required component shape.
* @param errorCode Code returned when the shape differs.
* @return An error naming both shapes, or a valid result.
*/
Result<> ValidateComponentShape(const IDataArray& array, const DataPath& path, std::string_view label, const ShapeType& componentShape, int32 errorCode)
{
if(array.getComponentShape() != componentShape)
{
return MakeErrorResult(errorCode, fmt::format("{} array '{}' has component shape {{{}}}, but component shape {{{}}} is required. Select an array with component shape {{{}}}.", label,
path.toString(), fmt::join(array.getComponentShape(), ", "), fmt::join(componentShape, ", "), fmt::join(componentShape, ", ")));
}
return {};
}

/**
* @brief Checks, without throwing, that a path resolves to an ArrayType with the required component shape.
* @tparam ArrayType Required concrete DataArray type.
* @param dataStructure Holds the array.
* @param path Path of the array.
* @param label User-facing name of the input, for the messages.
* @param typeName Required element type, quoted, for the messages (for example "'float32'").
* @param componentShape Required component shape.
* @param typeErrorCode Code returned when the path is missing or has another type.
* @param shapeErrorCode Code returned when the component shape differs.
* @return The first failed check, or a valid result.
*/
template <typename ArrayType>
Result<> ValidateArray(const DataStructure& dataStructure, const DataPath& path, std::string_view label, std::string_view typeName, const ShapeType& componentShape, int32 typeErrorCode,
int32 shapeErrorCode)
{
const auto* arrayPtr = dataStructure.getDataAs<ArrayType>(path);
if(arrayPtr == nullptr)
{
return MakeArrayTypeError(dataStructure, path, label, typeName, typeErrorCode);
}
return ValidateComponentShape(*arrayPtr, path, label, componentShape, shapeErrorCode);
}

/**
* @brief Checks that a sibling input has the tuple count of the quaternion array.
* @param dataStructure Holds both arrays.
* @param array Sibling input.
* @param path Path of the sibling input.
* @param label User-facing name of the sibling input, for the message.
* @param quatsPath Path of the quaternion array.
* @param quatsTupleCount Tuple count of the quaternion array.
* @param errorCode Code returned when the counts differ.
* @return An error naming both paths and both counts, or a valid result.
*/
Result<> ValidateTupleCount(const DataStructure& dataStructure, const IDataArray& array, const DataPath& path, std::string_view label, const DataPath& quatsPath, usize quatsTupleCount,
int32 errorCode)
{
if(!CheckArraysHaveSameTupleCount(dataStructure, {quatsPath, path}))
{
return MakeErrorResult(errorCode, fmt::format("{} array '{}' has {} tuples, but Input Quaternions array '{}' has {} tuples. Select arrays with one tuple per quaternion.", label, path.toString(),
array.getNumberOfTuples(), quatsPath.toString(), quatsTupleCount));
}
return {};
}
} // namespace

// -----------------------------------------------------------------------------
Expand All @@ -137,93 +36,12 @@ ComputeCAxisReferenceMisalignments::ComputeCAxisReferenceMisalignments(DataStruc
{
}

// -----------------------------------------------------------------------------
Result<> ComputeCAxisReferenceMisalignments::ValidateReferenceDirection(const std::vector<float32>& referenceDirection)
{
if(referenceDirection.size() != 3)
{
return MakeErrorResult(k_ReferenceDirectionSizeError, fmt::format("Reference Direction [{}] has {} components. Enter exactly three sample-frame components [X, Y, Z].",
fmt::join(referenceDirection, ", "), referenceDirection.size()));
}
const float64 norm = std::hypot(static_cast<float64>(referenceDirection[0]), static_cast<float64>(referenceDirection[1]), static_cast<float64>(referenceDirection[2]));
if(!std::isfinite(referenceDirection[0]) || !std::isfinite(referenceDirection[1]) || !std::isfinite(referenceDirection[2]) || norm <= k_MinReferenceDirectionNorm)
{
return MakeErrorResult(k_InvalidReferenceDirectionError,
fmt::format("Reference Direction [{}, {}, {}] must contain finite components and have length greater than {}. Enter a nonzero sample-frame direction, such as [0, 0, 1].",
referenceDirection[0], referenceDirection[1], referenceDirection[2], k_MinReferenceDirectionNorm));
}
return {};
}

// -----------------------------------------------------------------------------
Result<> ComputeCAxisReferenceMisalignments::ValidateInputs(const DataStructure& dataStructure, const ComputeCAxisReferenceMisalignmentsInputValues& inputValues)
{
if(auto result = ValidateReferenceDirection(inputValues.ReferenceDirection); result.invalid())
{
return result;
}

const DataPath& quatsPathRef = inputValues.QuatsArrayPath;
if(auto result = ValidateArray<Float32Array>(dataStructure, quatsPathRef, "Input Quaternions", "'float32'", ShapeType{4}, k_InvalidQuatsArrayError, k_QuatsComponentShapeError); result.invalid())
{
return result;
}
const usize quatsTupleCount = dataStructure.getDataRefAs<Float32Array>(quatsPathRef).getNumberOfTuples();

const DataPath& phasesPathRef = inputValues.PhasesArrayPath;
if(auto result = ValidateArray<Int32Array>(dataStructure, phasesPathRef, "Phases", "'int32'", ShapeType{1}, k_InvalidPhasesArrayError, k_PhasesComponentShapeError); result.invalid())
{
return result;
}
if(auto result = ValidateTupleCount(dataStructure, dataStructure.getDataRefAs<Int32Array>(phasesPathRef), phasesPathRef, "Phases", quatsPathRef, quatsTupleCount, k_TupleCountMismatchError);
result.invalid())
{
return result;
}

if(inputValues.UseMask)
{
const DataPath& maskPathRef = inputValues.MaskArrayPath;
const auto* maskPtr = dataStructure.getDataAs<IDataArray>(maskPathRef);
if(maskPtr == nullptr || (maskPtr->getDataType() != DataType::boolean && maskPtr->getDataType() != DataType::uint8))
{
return MakeArrayTypeError(dataStructure, maskPathRef, "Mask", "'bool' or 'uint8'", k_InvalidMaskArrayError);
}
if(auto result = ValidateComponentShape(*maskPtr, maskPathRef, "Mask", ShapeType{1}, k_MaskComponentShapeError); result.invalid())
{
return result;
}
if(auto result = ValidateTupleCount(dataStructure, *maskPtr, maskPathRef, "Mask", quatsPathRef, quatsTupleCount, k_TupleCountMismatchError); result.invalid())
{
return result;
}
}

return ValidateArray<UInt32Array>(dataStructure, inputValues.CrystalStructuresArrayPath, "Crystal Structures", "'uint32'", ShapeType{1}, k_InvalidCrystalStructuresArrayError,
k_CrystalStructuresComponentShapeError);
}

// -----------------------------------------------------------------------------
Result<> ComputeCAxisReferenceMisalignments::operator()()
{
if(auto validation = ValidateInputs(m_DataStructure, *m_InputValues); validation.invalid())
{
return validation;
}
const auto& quatsStoreRef = m_DataStructure.getDataRefAs<Float32Array>(m_InputValues->QuatsArrayPath).getDataStoreRef();
const usize total = quatsStoreRef.getNumberOfTuples();
if(auto validation = ValidateArray<Float32Array>(m_DataStructure, m_InputValues->OutputArrayPath, "Output", "'float32'", ShapeType{1}, k_InvalidOutputArrayError, k_OutputComponentShapeError);
validation.invalid())
{
return validation;
}
auto& outputStoreRef = m_DataStructure.getDataRefAs<Float32Array>(m_InputValues->OutputArrayPath).getDataStoreRef();
if(outputStoreRef.getNumberOfTuples() != total)
{
return MakeErrorResult(k_OutputTupleCountMismatchError,
fmt::format("Output array '{}' has {} tuples, but Input Quaternions array '{}' has {} tuples. Create the output array with one tuple per quaternion.",
m_InputValues->OutputArrayPath.toString(), outputStoreRef.getNumberOfTuples(), m_InputValues->QuatsArrayPath.toString(), total));
}

const auto& referenceValuesRef = m_InputValues->ReferenceDirection;
Eigen::Vector3d referenceDirection(referenceValuesRef[0], referenceValuesRef[1], referenceValuesRef[2]);
Expand All @@ -245,7 +63,7 @@ Result<> ComputeCAxisReferenceMisalignments::operator()()

const auto& phasesStoreRef = m_DataStructure.getDataRefAs<Int32Array>(m_InputValues->PhasesArrayPath).getDataStoreRef();

// ValidateInputs guarantees that an enabled mask is exactly one of these types.
// Preflight guarantees that an enabled mask is exactly one of these types.
const BoolArray* boolMaskPtr = nullptr;
const UInt8Array* byteMaskPtr = nullptr;
if(m_InputValues->UseMask)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,6 @@ struct ORIENTATIONANALYSIS_EXPORT ComputeCAxisReferenceMisalignmentsInputValues
class ORIENTATIONANALYSIS_EXPORT ComputeCAxisReferenceMisalignments
{
public:
/**
* @brief The reference direction has a non-finite component or a near-zero length.
*/
static constexpr int32 k_InvalidReferenceDirectionError = -98710;
/**
* @brief The Phases array or the enabled mask has a different tuple count than the quaternion array.
*/
static constexpr int32 k_TupleCountMismatchError = -98711;
/**
* @brief An unmasked phase value is not an index into the Crystal Structures array.
*/
Expand All @@ -56,63 +48,6 @@ class ORIENTATIONANALYSIS_EXPORT ComputeCAxisReferenceMisalignments
* @brief Warning: some unmasked tuples have a known non-hexagonal crystal structure.
*/
static constexpr int32 k_NonHexagonalPhasesWarning = -98713;
/**
* @brief The reference direction does not have exactly three components.
*/
static constexpr int32 k_ReferenceDirectionSizeError = -98714;
/**
* @brief The quaternion path does not resolve to a float32 array.
*/
static constexpr int32 k_InvalidQuatsArrayError = -98715;
/**
* @brief The quaternion array does not have component shape {4}.
*/
static constexpr int32 k_QuatsComponentShapeError = -98716;
/**
* @brief The Phases path does not resolve to an int32 array.
*/
static constexpr int32 k_InvalidPhasesArrayError = -98717;
/**
* @brief The Phases array does not have component shape {1}.
*/
static constexpr int32 k_PhasesComponentShapeError = -98718;
/**
* @brief The enabled mask path does not resolve to a bool or uint8 array.
*/
static constexpr int32 k_InvalidMaskArrayError = -98719;
/**
* @brief The enabled mask array does not have component shape {1}.
*/
static constexpr int32 k_MaskComponentShapeError = -98720;
/**
* @brief The Crystal Structures path does not resolve to a uint32 array.
*/
static constexpr int32 k_InvalidCrystalStructuresArrayError = -98721;
/**
* @brief The Crystal Structures array does not have component shape {1}.
*/
static constexpr int32 k_CrystalStructuresComponentShapeError = -98722;
/**
* @brief The output path does not resolve to a float32 array.
*/
static constexpr int32 k_InvalidOutputArrayError = -98723;
/**
* @brief The output array does not have component shape {1}.
*/
static constexpr int32 k_OutputComponentShapeError = -98724;
/**
* @brief The output array has a different tuple count than the quaternion array.
*/
static constexpr int32 k_OutputTupleCountMismatchError = -98725;
/**
* @brief Preflight: the output path equals the path of an input array.
*/
static constexpr int32 k_OutputPathCollisionError = -98726;

/**
* @brief Reference directions at or below this dimensionless norm are treated as zero.
*/
static constexpr float64 k_MinReferenceDirectionNorm = 1.0e-12;

/**
* @brief Initializes the executor. All arguments must outlive this instance.
Expand All @@ -133,33 +68,17 @@ class ORIENTATIONANALYSIS_EXPORT ComputeCAxisReferenceMisalignments
ComputeCAxisReferenceMisalignments& operator=(const ComputeCAxisReferenceMisalignments&) = delete;
ComputeCAxisReferenceMisalignments& operator=(ComputeCAxisReferenceMisalignments&&) noexcept = delete;

/**
* @brief Validates the reference direction. ValidateInputs() calls it.
* @param referenceDirection Three finite sample-frame components.
* @return k_ReferenceDirectionSizeError for a size other than three, or
* k_InvalidReferenceDirectionError for a non-finite component or a near-zero norm.
*/
static Result<> ValidateReferenceDirection(const std::vector<float32>& referenceDirection);

/**
* @brief Makes every input check that preflight data can answer. preflightImpl() and operator()() both call it.
*
* Checks the reference direction, and the types and component shapes of the quaternion, Phases,
* and Crystal Structures arrays. Checks the mask only when UseMask is set. Phases and the enabled
* mask must have one tuple per quaternion. The output is not checked because preflight has not
* created it yet. Array lookups do not throw.
* @param dataStructure Holds the selected arrays.
* @param inputValues Identifies the arrays and the reference direction. OutputArrayPath is not read.
* @return The error of the first failed check, or a valid result.
*/
static Result<> ValidateInputs(const DataStructure& dataStructure, const ComputeCAxisReferenceMisalignmentsInputValues& inputValues);

/**
* @brief Writes one angle per quaternion tuple using checked bulk I/O.
*
* Validates the reference direction, the input arrays and the output array (float32,
* component shape {1}, one tuple per quaternion tuple) before any read.
* @return Errors for invalid references or arrays, phase indices, or I/O.
* @pre ReferenceDirection has three finite components and a length greater than 1.0e-12.
* @pre QuatsArrayPath names a float32 array with component shape {4}.
* @pre PhasesArrayPath names an int32 array with component shape {1}.
* @pre CrystalStructuresArrayPath names a uint32 array with component shape {1}.
* @pre When UseMask is set, MaskArrayPath names a bool or uint8 array with component shape {1}.
* @pre OutputArrayPath names a float32 array with component shape {1}. Phases, the enabled mask and
* the output have one tuple per quaternion tuple.
* @return Errors for phase indices outside Crystal Structures, or for I/O.
* A warning counts only unmasked tuples with known non-hexagonal structures.
* UnknownCrystalStructure does not contribute to the count.
* Cancellation leaves only completed chunks written.
Expand Down
Loading