diff --git a/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.cpp b/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.cpp index 21122184d8..85eef1fa2d 100644 --- a/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.cpp +++ b/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.cpp @@ -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 #include #include -#include +#include #include #include @@ -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(&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 -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(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 // ----------------------------------------------------------------------------- @@ -137,93 +36,12 @@ ComputeCAxisReferenceMisalignments::ComputeCAxisReferenceMisalignments(DataStruc { } -// ----------------------------------------------------------------------------- -Result<> ComputeCAxisReferenceMisalignments::ValidateReferenceDirection(const std::vector& 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(referenceDirection[0]), static_cast(referenceDirection[1]), static_cast(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(dataStructure, quatsPathRef, "Input Quaternions", "'float32'", ShapeType{4}, k_InvalidQuatsArrayError, k_QuatsComponentShapeError); result.invalid()) - { - return result; - } - const usize quatsTupleCount = dataStructure.getDataRefAs(quatsPathRef).getNumberOfTuples(); - - const DataPath& phasesPathRef = inputValues.PhasesArrayPath; - if(auto result = ValidateArray(dataStructure, phasesPathRef, "Phases", "'int32'", ShapeType{1}, k_InvalidPhasesArrayError, k_PhasesComponentShapeError); result.invalid()) - { - return result; - } - if(auto result = ValidateTupleCount(dataStructure, dataStructure.getDataRefAs(phasesPathRef), phasesPathRef, "Phases", quatsPathRef, quatsTupleCount, k_TupleCountMismatchError); - result.invalid()) - { - return result; - } - - if(inputValues.UseMask) - { - const DataPath& maskPathRef = inputValues.MaskArrayPath; - const auto* maskPtr = dataStructure.getDataAs(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(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(m_InputValues->QuatsArrayPath).getDataStoreRef(); const usize total = quatsStoreRef.getNumberOfTuples(); - if(auto validation = ValidateArray(m_DataStructure, m_InputValues->OutputArrayPath, "Output", "'float32'", ShapeType{1}, k_InvalidOutputArrayError, k_OutputComponentShapeError); - validation.invalid()) - { - return validation; - } auto& outputStoreRef = m_DataStructure.getDataRefAs(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]); @@ -245,7 +63,7 @@ Result<> ComputeCAxisReferenceMisalignments::operator()() const auto& phasesStoreRef = m_DataStructure.getDataRefAs(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) diff --git a/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.hpp b/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.hpp index 3189560ac3..dca31312dd 100644 --- a/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.hpp +++ b/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.hpp @@ -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. */ @@ -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. @@ -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& 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. diff --git a/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/ComputeCAxisReferenceMisalignmentsFilter.cpp b/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/ComputeCAxisReferenceMisalignmentsFilter.cpp index 91ecc93b32..a356ddcf0b 100644 --- a/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/ComputeCAxisReferenceMisalignmentsFilter.cpp +++ b/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/ComputeCAxisReferenceMisalignmentsFilter.cpp @@ -2,6 +2,7 @@ #include "OrientationAnalysis/Filters/Algorithms/ComputeCAxisReferenceMisalignments.hpp" +#include "simplnx/Common/TypesUtility.hpp" #include "simplnx/DataStructure/DataArray.hpp" #include "simplnx/DataStructure/DataPath.hpp" #include "simplnx/Filter/Actions/CreateArrayAction.hpp" @@ -9,7 +10,12 @@ #include "simplnx/Parameters/BoolParameter.hpp" #include "simplnx/Parameters/DataObjectNameParameter.hpp" #include "simplnx/Parameters/VectorParameter.hpp" +#include "simplnx/Utilities/DataArrayUtilities.hpp" +#include + +#include +#include #include #include #include @@ -35,6 +41,156 @@ ComputeCAxisReferenceMisalignmentsInputValues CreateInputValues(const Arguments& inputValues.OutputArrayPath = inputValues.QuatsArrayPath.replaceName(filterArgs.value(ComputeCAxisReferenceMisalignmentsFilter::k_CAxisReferenceMisalignmentsArrayName_Key)); return inputValues; } + +/** + * @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(&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, without throwing, that a path resolves to an ArrayType. + * + * ArraySelectionParameter applies its type list only to IDataArray, so a StringArray reaches preflightImpl(). + * @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 message. + * @param typeName Required element type, quoted, for the message (for example "'float32'"). + * @param errorCode Code returned when the path is missing or has another type. + * @return An error naming the type found, or a valid result. + */ +template +Result<> ValidateArrayType(const DataStructure& dataStructure, const DataPath& path, std::string_view label, std::string_view typeName, int32 errorCode) +{ + if(dataStructure.getDataAs(path) == nullptr) + { + return MakeArrayTypeError(dataStructure, path, label, typeName, errorCode); + } + return {}; +} + +/** + * @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. + * @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) +{ + if(!CheckArraysHaveSameTupleCount(dataStructure, {quatsPath, path})) + { + return MakeErrorResult(ComputeCAxisReferenceMisalignmentsFilter::k_TupleCountMismatchError, + 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 {}; +} + +/** + * @brief Checks that the reference direction is finite and not near zero. VectorParameter guarantees three components. + * @param referenceDirection Three sample-frame components. + * @return k_InvalidReferenceDirectionError for a non-finite component or a near-zero norm, or a valid result. + */ +Result<> ValidateReferenceDirection(const std::vector& referenceDirection) +{ + const float64 norm = std::hypot(static_cast(referenceDirection[0]), static_cast(referenceDirection[1]), static_cast(referenceDirection[2])); + if(!std::isfinite(referenceDirection[0]) || !std::isfinite(referenceDirection[1]) || !std::isfinite(referenceDirection[2]) || + norm <= ComputeCAxisReferenceMisalignmentsFilter::k_MinReferenceDirectionNorm) + { + return MakeErrorResult(ComputeCAxisReferenceMisalignmentsFilter::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], ComputeCAxisReferenceMisalignmentsFilter::k_MinReferenceDirectionNorm)); + } + return {}; +} + +/** + * @brief Makes the input checks that the parameters cannot make. + * + * Checks that the reference direction is finite and not near zero. + * Checks that each selected array is a DataArray of the required type. + * Checks the mask only when UseMask is set. + * Phases and the enabled mask must have one tuple per quaternion. + * The parameters already check existence, element types of DataArrays and component shapes. + * 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. + */ +Result<> 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 = ValidateArrayType(dataStructure, quatsPathRef, "Input Quaternions", "'float32'", ComputeCAxisReferenceMisalignmentsFilter::k_InvalidQuatsArrayError); result.invalid()) + { + return result; + } + const usize quatsTupleCount = dataStructure.getDataRefAs(quatsPathRef).getNumberOfTuples(); + + const DataPath& phasesPathRef = inputValues.PhasesArrayPath; + if(auto result = ValidateArrayType(dataStructure, phasesPathRef, "Phases", "'int32'", ComputeCAxisReferenceMisalignmentsFilter::k_InvalidPhasesArrayError); result.invalid()) + { + return result; + } + if(auto result = ValidateTupleCount(dataStructure, dataStructure.getDataRefAs(phasesPathRef), phasesPathRef, "Phases", quatsPathRef, quatsTupleCount); result.invalid()) + { + return result; + } + + if(inputValues.UseMask) + { + const DataPath& maskPathRef = inputValues.MaskArrayPath; + const auto* maskPtr = dataStructure.getDataAs(maskPathRef); + if(maskPtr == nullptr || (maskPtr->getDataType() != DataType::boolean && maskPtr->getDataType() != DataType::uint8)) + { + return MakeArrayTypeError(dataStructure, maskPathRef, "Mask", "'bool' or 'uint8'", ComputeCAxisReferenceMisalignmentsFilter::k_InvalidMaskArrayError); + } + if(auto result = ValidateTupleCount(dataStructure, *maskPtr, maskPathRef, "Mask", quatsPathRef, quatsTupleCount); result.invalid()) + { + return result; + } + } + + return ValidateArrayType(dataStructure, inputValues.CrystalStructuresArrayPath, "Crystal Structures", "'uint32'", + ComputeCAxisReferenceMisalignmentsFilter::k_InvalidCrystalStructuresArrayError); +} } // namespace namespace nx::core @@ -120,7 +276,7 @@ IFilter::PreflightResult ComputeCAxisReferenceMisalignmentsFilter::preflightImpl const std::atomic_bool& shouldCancel, const ExecutionContext& executionContext) const { const ComputeCAxisReferenceMisalignmentsInputValues inputValues = CreateInputValues(filterArgs); - Result<> validationResult = ComputeCAxisReferenceMisalignments::ValidateInputs(dataStructure, inputValues); + Result<> validationResult = ValidateInputs(dataStructure, inputValues); if(validationResult.invalid()) { return {ConvertResultTo(std::move(validationResult), {})}; @@ -135,7 +291,7 @@ IFilter::PreflightResult ComputeCAxisReferenceMisalignmentsFilter::preflightImpl { if(inputValues.OutputArrayPath == inputRef.second) { - return {MakeErrorResult(ComputeCAxisReferenceMisalignments::k_OutputPathCollisionError, + return {MakeErrorResult(k_OutputPathCollisionError, fmt::format("The output array path '{}' is the path of the selected {} array. Change the C-Axis Reference Misalignments name '{}' to a " "name that no input array uses.", inputValues.OutputArrayPath.toString(), inputRef.first, inputValues.OutputArrayPath.getTargetName()))}; diff --git a/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/ComputeCAxisReferenceMisalignmentsFilter.hpp b/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/ComputeCAxisReferenceMisalignmentsFilter.hpp index c0cb465951..cb6f1cd763 100644 --- a/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/ComputeCAxisReferenceMisalignmentsFilter.hpp +++ b/src/Plugins/OrientationAnalysis/src/OrientationAnalysis/Filters/ComputeCAxisReferenceMisalignmentsFilter.hpp @@ -38,6 +38,40 @@ class ORIENTATIONANALYSIS_EXPORT ComputeCAxisReferenceMisalignmentsFilter : publ static constexpr StringLiteral k_CrystalStructuresArrayPath_Key = "crystal_structures_array_path"; static constexpr StringLiteral k_CAxisReferenceMisalignmentsArrayName_Key = "c_axis_reference_misalignments_array_name"; + /** + * @brief Preflight: the reference direction has a non-finite component or a near-zero length. + */ + static constexpr int32 k_InvalidReferenceDirectionError = -98710; + /** + * @brief Preflight: the Phases array or the enabled mask has a different tuple count than the quaternion array. + */ + static constexpr int32 k_TupleCountMismatchError = -98711; + /** + * @brief Preflight: the quaternion path does not resolve to a float32 array. + */ + static constexpr int32 k_InvalidQuatsArrayError = -98715; + /** + * @brief Preflight: the Phases path does not resolve to an int32 array. + */ + static constexpr int32 k_InvalidPhasesArrayError = -98717; + /** + * @brief Preflight: the enabled mask path does not resolve to a bool or uint8 array. + */ + static constexpr int32 k_InvalidMaskArrayError = -98719; + /** + * @brief Preflight: the Crystal Structures path does not resolve to a uint32 array. + */ + static constexpr int32 k_InvalidCrystalStructuresArrayError = -98721; + /** + * @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 Returns the name of the filter. * @return Registered filter name. diff --git a/src/Plugins/OrientationAnalysis/test/ComputeCAxisReferenceMisalignmentsTest.cpp b/src/Plugins/OrientationAnalysis/test/ComputeCAxisReferenceMisalignmentsTest.cpp index 8ca2f68e33..12d7b1646f 100644 --- a/src/Plugins/OrientationAnalysis/test/ComputeCAxisReferenceMisalignmentsTest.cpp +++ b/src/Plugins/OrientationAnalysis/test/ComputeCAxisReferenceMisalignmentsTest.cpp @@ -35,7 +35,6 @@ namespace { using FilterType = ComputeCAxisReferenceMisalignmentsFilter; using AlgorithmType = ComputeCAxisReferenceMisalignments; -using InputValuesType = ComputeCAxisReferenceMisalignmentsInputValues; using EulerType = std::array; constexpr float64 k_Radians = numbers::pi / 180.0; constexpr float32 k_NaN = std::numeric_limits::quiet_NaN(); @@ -185,38 +184,6 @@ void ExecuteAndCheck(DataStructure& ds, const Arguments& args, const UnitTest::A const Result<> result = ExecuteInScope(ds, args, scope, groupName); REQUIRE(result.warnings().empty()); } - -// Valid inputs for a direct algorithm call: two tuples, a uint8 mask, and the pre-created output. -DataStructure MakeDirectCallData() -{ - DataStructure ds = MakeData({{0, 30, 0}, {0, 45, 0}}, {2}); - REQUIRE_NOTHROW(ds.getDataRefAs(k_Quats.getParent())); - const auto parentId = ds.getDataRefAs(k_Quats.getParent()).getId(); - CreateArray(ds, k_Mask, {2}, 1, parentId).fill(1); - CreateArray(ds, k_Output, {2}, 1, parentId); - REQUIRE(AttributeMatrix::Create(ds, "Other", {3}) != nullptr); - return ds; -} - -InputValuesType MakeDirectCallInputValues() -{ - InputValuesType inputValues; - inputValues.ReferenceDirection = {0.0F, 0.0F, 1.0F}; - inputValues.UseMask = true; - inputValues.QuatsArrayPath = k_Quats; - inputValues.PhasesArrayPath = k_Phases; - inputValues.MaskArrayPath = k_Mask; - inputValues.CrystalStructuresArrayPath = k_CrystalStructures; - inputValues.OutputArrayPath = k_Output; - return inputValues; -} - -Result<> RunAlgorithm(DataStructure& ds, const InputValuesType& inputValues) -{ - const std::atomic_bool shouldCancel = false; - const IFilter::MessageHandler messageHandler{}; - return AlgorithmType(ds, messageHandler, shouldCancel, &inputValues)(); -} } // namespace TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: cell and feature analytical oracle", "[OrientationAnalysis][ComputeCAxisReferenceMisalignments]") @@ -648,20 +615,10 @@ TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: invalid refe auto ds = MakeData({{0, 30, 0}}, {1}); auto result = FilterType().preflight(ds, MakeArgs(reference)); REQUIRE(result.outputActions.invalid()); - REQUIRE(result.outputActions.errors()[0].code == AlgorithmType::k_InvalidReferenceDirectionError); + REQUIRE(result.outputActions.errors()[0].code == FilterType::k_InvalidReferenceDirectionError); UnitTest::CheckArraysInheritTupleDims(ds); } -TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: reference with wrong component count", "[OrientationAnalysis][ComputeCAxisReferenceMisalignments]") -{ - // VectorParameter rejects a wrong-sized vector before preflightImpl, so only a direct call reaches this check. - const auto reference = GENERATE(std::vector{}, std::vector{0.0F, 1.0F}, std::vector{0.0F, 0.0F, 1.0F, 0.0F}); - const Result<> result = AlgorithmType::ValidateReferenceDirection(reference); - SIMPLNX_RESULT_REQUIRE_INVALID(result); - REQUIRE(result.errors().size() == 1); - REQUIRE(result.errors()[0].code == AlgorithmType::k_ReferenceDirectionSizeError); -} - TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: tuple mismatch", "[OrientationAnalysis][ComputeCAxisReferenceMisalignments]") { const auto scenario = GENERATE(from_range(UnitTest::SelectAlgorithmTestScenariosForInMemoryStores())); @@ -685,7 +642,7 @@ TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: tuple mismat } auto result = FilterType().preflight(ds, args); REQUIRE(result.outputActions.invalid()); - REQUIRE(result.outputActions.errors()[0].code == AlgorithmType::k_TupleCountMismatchError); + REQUIRE(result.outputActions.errors()[0].code == FilterType::k_TupleCountMismatchError); const auto& messageRef = result.outputActions.errors()[0].message; REQUIRE(messageRef.find(mismatchMask ? "Mask array" : "Phases array") == 0); REQUIRE(messageRef.find("Quats") != std::string::npos); @@ -747,7 +704,7 @@ TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: output name auto result = FilterType().preflight(ds, args); REQUIRE(result.outputActions.invalid()); REQUIRE(result.outputActions.errors().size() == 1); - REQUIRE(result.outputActions.errors()[0].code == AlgorithmType::k_OutputPathCollisionError); + REQUIRE(result.outputActions.errors()[0].code == FilterType::k_OutputPathCollisionError); REQUIRE(result.outputActions.errors()[0].message.find("Orientations/" + inputName) != std::string::npos); REQUIRE(ds.getDataRefAs(k_Quats.replaceName(inputName)).getNumberOfComponents() == (inputName == "Quats" ? 4 : 1)); } @@ -761,18 +718,15 @@ TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: preflight re const auto parentId = ds.getDataRefAs(k_Quats.getParent()).getId(); const DataPath stringsPath({"Orientations", "Strings"}); REQUIRE(StringArray::CreateWithValues(ds, stringsPath.getTargetName(), {2}, {"a", "b"}, parentId) != nullptr); - const bool useMask = GENERATE(false, true); + // Each row selects the StringArray for one input and gives the code of that input's type check. + const auto [inputKey, expectedCode] = GENERATE(std::make_pair(std::string(FilterType::k_QuatsArrayPath_Key), FilterType::k_InvalidQuatsArrayError), + std::make_pair(std::string(FilterType::k_PhasesArrayPath_Key), FilterType::k_InvalidPhasesArrayError), + std::make_pair(std::string(FilterType::k_MaskArrayPath_Key), FilterType::k_InvalidMaskArrayError), + std::make_pair(std::string(FilterType::k_CrystalStructuresArrayPath_Key), FilterType::k_InvalidCrystalStructuresArrayError)); + CAPTURE(inputKey); + const bool useMask = inputKey == FilterType::k_MaskArrayPath_Key; auto args = MakeArgs({0, 0, 1}, useMask); - int32 expectedCode = AlgorithmType::k_InvalidMaskArrayError; - if(useMask) - { - args.insertOrAssign(FilterType::k_MaskArrayPath_Key, std::make_any(stringsPath)); - } - else - { - args.insertOrAssign(FilterType::k_QuatsArrayPath_Key, std::make_any(stringsPath)); - expectedCode = AlgorithmType::k_InvalidQuatsArrayError; - } + args.insertOrAssign(inputKey, std::make_any(stringsPath)); IFilter::PreflightResult result; REQUIRE_NOTHROW(result = FilterType().preflight(ds, args)); REQUIRE(result.outputActions.invalid()); @@ -781,141 +735,3 @@ TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: preflight re REQUIRE(result.outputActions.errors()[0].message.find("has type 'StringArray'") != std::string::npos); REQUIRE(ds.getDataAs(k_Output) == nullptr); } - -TEST_CASE("OrientationAnalysis::ComputeCAxisReferenceMisalignments: algorithm validates its own inputs", "[OrientationAnalysis][ComputeCAxisReferenceMisalignments]") -{ - DataStructure ds = MakeDirectCallData(); - InputValuesType inputValues = MakeDirectCallInputValues(); - REQUIRE_NOTHROW(ds.getDataRefAs(k_Quats.getParent())); - const auto parentId = ds.getDataRefAs(k_Quats.getParent()).getId(); - REQUIRE_NOTHROW(ds.getDataRefAs(DataPath({"Other"}))); - const auto otherId = ds.getDataRefAs(DataPath({"Other"})).getId(); - const DataPath wrongPath({"Orientations", "Wrong"}); - const DataPath otherPath({"Other", "Mismatched"}); - // 0 means the inputs are valid and the call must succeed. - int32 expectedCode = 0; - // A phrase that only the message of the expected condition contains, when the code alone is not enough. - std::string expectedPhrase; - - SECTION("Valid inputs succeed") - { - } - SECTION("Missing quaternion array") - { - inputValues.QuatsArrayPath = DataPath({"Orientations", "Missing"}); - expectedCode = AlgorithmType::k_InvalidQuatsArrayError; - expectedPhrase = "does not exist"; - } - SECTION("Quaternion array of the wrong type") - { - CreateArray(ds, wrongPath, {2}, 4, parentId); - inputValues.QuatsArrayPath = wrongPath; - expectedCode = AlgorithmType::k_InvalidQuatsArrayError; - expectedPhrase = "has type 'float64', but type 'float32' is required"; - } - SECTION("Quaternion array with five components") - { - CreateArray(ds, wrongPath, {2}, 5, parentId); - inputValues.QuatsArrayPath = wrongPath; - expectedCode = AlgorithmType::k_QuatsComponentShapeError; - } - SECTION("Phases array of the wrong type") - { - CreateArray(ds, wrongPath, {2}, 1, parentId); - inputValues.PhasesArrayPath = wrongPath; - expectedCode = AlgorithmType::k_InvalidPhasesArrayError; - } - SECTION("Phases array with two components") - { - CreateArray(ds, wrongPath, {2}, 2, parentId); - inputValues.PhasesArrayPath = wrongPath; - expectedCode = AlgorithmType::k_PhasesComponentShapeError; - } - SECTION("Phases array with a different tuple count") - { - CreateArray(ds, otherPath, {3}, 1, otherId); - inputValues.PhasesArrayPath = otherPath; - expectedCode = AlgorithmType::k_TupleCountMismatchError; - expectedPhrase = "Phases array 'Other/Mismatched' has 3 tuples"; - } - SECTION("Mask array of the wrong type") - { - CreateArray(ds, wrongPath, {2}, 1, parentId); - inputValues.MaskArrayPath = wrongPath; - expectedCode = AlgorithmType::k_InvalidMaskArrayError; - expectedPhrase = "has type 'int32', but type 'bool' or 'uint8' is required"; - } - SECTION("Mask array with two components") - { - CreateArray(ds, wrongPath, {2}, 2, parentId); - inputValues.MaskArrayPath = wrongPath; - expectedCode = AlgorithmType::k_MaskComponentShapeError; - } - SECTION("Mask array with a different tuple count") - { - CreateArray(ds, otherPath, {3}, 1, otherId); - inputValues.MaskArrayPath = otherPath; - expectedCode = AlgorithmType::k_TupleCountMismatchError; - expectedPhrase = "Mask array 'Other/Mismatched' has 3 tuples"; - } - SECTION("Crystal Structures array of the wrong type") - { - CreateArray(ds, otherPath, {3}, 1, otherId); - inputValues.CrystalStructuresArrayPath = otherPath; - expectedCode = AlgorithmType::k_InvalidCrystalStructuresArrayError; - } - SECTION("Crystal Structures array with two components") - { - CreateArray(ds, otherPath, {3}, 2, otherId); - inputValues.CrystalStructuresArrayPath = otherPath; - expectedCode = AlgorithmType::k_CrystalStructuresComponentShapeError; - } - SECTION("Missing output array") - { - inputValues.OutputArrayPath = DataPath({"Orientations", "Missing"}); - expectedCode = AlgorithmType::k_InvalidOutputArrayError; - } - SECTION("Output array with two components") - { - CreateArray(ds, wrongPath, {2}, 2, parentId); - inputValues.OutputArrayPath = wrongPath; - expectedCode = AlgorithmType::k_OutputComponentShapeError; - } - SECTION("Output array with a different tuple count") - { - CreateArray(ds, otherPath, {3}, 1, otherId); - inputValues.OutputArrayPath = otherPath; - expectedCode = AlgorithmType::k_OutputTupleCountMismatchError; - } - SECTION("Non-finite reference direction") - { - inputValues.ReferenceDirection = {k_NaN, 0.0F, 1.0F}; - expectedCode = AlgorithmType::k_InvalidReferenceDirectionError; - } - SECTION("Reference direction with two components") - { - inputValues.ReferenceDirection = {0.0F, 1.0F}; - expectedCode = AlgorithmType::k_ReferenceDirectionSizeError; - } - SECTION("Phase outside the Crystal Structures array") - { - REQUIRE_NOTHROW(ds.getDataRefAs(k_Phases)); - ds.getDataRefAs(k_Phases)[1] = 5; - expectedCode = AlgorithmType::k_PhaseOutOfRangeError; - } - CAPTURE(expectedCode); - Result<> result; - REQUIRE_NOTHROW(result = RunAlgorithm(ds, inputValues)); - if(expectedCode == 0) - { - SIMPLNX_RESULT_REQUIRE_VALID(result); - return; - } - SIMPLNX_RESULT_REQUIRE_INVALID(result); - REQUIRE(result.errors().size() == 1); - REQUIRE(result.errors()[0].code == expectedCode); - if(!expectedPhrase.empty()) - { - REQUIRE(result.errors()[0].message.find(expectedPhrase) != std::string::npos); - } -}