Skip to content
Draft
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
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ set(${PLUGIN_NAME}_SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR})
# These are all the filters in the plugin. All filters should be kept in the
# SimplnxReview/src/SimplnxReview/Filters/ directory.
set(FilterList
ComputeArrayNormFilter
ComputeGroupingDensityFilter
ComputeLocalAverageCAxisMisalignmentsFilter
ComputeMicroTextureRegionsFilter
Expand All @@ -44,6 +45,7 @@ set(ActionList
# This should be integrated with the `create_simplnx_plugin` function call
# ------------------------------------------------------------------------------
set(AlgorithmList
ComputeArrayNorm
ComputeGroupingDensity
ComputeLocalAverageCAxisMisalignments
ComputeMicroTextureRegions
Expand Down
32 changes: 32 additions & 0 deletions docs/ComputeArrayNormFilter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Compute Array Norm

## Group (Subgroup)

SimplnxReview (Statistics)

## Description

This **Filter** computes the p<sup>th</sup> norm of an **Attribute Array**. Specifically, for each tuple of the array, the following is computed:

$$\left\| \mathbf{x} \right\| _p := \bigg( \sum_{i=1}^n \left| x_i \right| ^p \bigg) ^{1/p}$$

where $n$ is the number of components for the **Attribute Array**.

- When $p = 2$, this results in the *Euclidean norm*
- When $p = 1$, this results in the *Manhattan norm* (also called the *taxicab norm*)

The p-space value may be any real number greater than or equal to zero. When $0 \leq p < 1$, the result may not strictly be a *norm* in the exact mathematical sense. Additionally, when $p = 0$, the result is simply the number of components for the **Attribute Array**.

**Note:** If the input array is a scalar array (1 component), the output array will contain the same values as the input array, but in 32-bit floating point precision.

% Auto generated parameter table will be inserted here

## Example Pipelines

## License & Copyright

Please see the description file distributed with this plugin.

## DREAM3D-NX Help

If you need help, need to file a bug report or want to request a new feature, please head over to the [DREAM3DNX-Issues](https://github.com/BlueQuartzSoftware/DREAM3DNX-Issues/discussions) GitHub site where the community of DREAM3D-NX users can help answer your questions.
87 changes: 87 additions & 0 deletions src/SimplnxReview/Filters/Algorithms/ComputeArrayNorm.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#include "ComputeArrayNorm.hpp"

#include "simplnx/DataStructure/DataArray.hpp"
#include "simplnx/Utilities/DataArrayUtilities.hpp"
#include "simplnx/Utilities/FilterUtilities.hpp"

#include <cmath>

using namespace nx::core;

namespace
{
template <typename T>
class ComputeNormImpl
{
public:
ComputeNormImpl(const IDataArray& inputArray, Float32Array& normArray, float32 pSpace)
: m_InputArray(dynamic_cast<const DataArray<T>&>(inputArray))
, m_NormArray(normArray)
, m_PSpace(pSpace)
{
}

void operator()() const
{
const auto& inputStore = m_InputArray.getDataStoreRef();
auto& normStore = m_NormArray.getDataStoreRef();

usize numTuples = m_InputArray.getNumberOfTuples();
usize numComponents = m_InputArray.getNumberOfComponents();

for(usize i = 0; i < numTuples; i++)
{
float32 normTmp = 0.0f;
for(usize j = 0; j < numComponents; j++)
{
float32 value = static_cast<float32>(inputStore[numComponents * i + j]);
normTmp += std::pow(std::abs(value), m_PSpace);
}
normStore[i] = std::pow(normTmp, 1.0f / m_PSpace);
}
Comment on lines +32 to +41
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for(usize i = 0; i < numTuples; i++)
{
float32 normTmp = 0.0f;
for(usize j = 0; j < numComponents; j++)
{
float32 value = static_cast<float32>(inputStore[numComponents * i + j]);
normTmp += std::pow(std::abs(value), m_PSpace);
}
normStore[i] = std::pow(normTmp, 1.0f / m_PSpace);
}
const float32 normPSpace = 1.0f / m_PSpace;
for(usize i = 0; i < numTuples; i++)
{
float32 normTmp = 0.0f;
for(usize j = 0; j < numComponents; j++)
{
float32 value = static_cast<float32>(inputStore[numComponents * i + j]);
normTmp += std::pow(std::abs(value), m_PSpace);
}
normStore[i] = std::pow(normTmp, normPSpace);
}

division is an expensive operation so we preform the math once and cache it so it doesn't have to be recalculated in a tight loop. Of course there is a chance the compiler would catch this and optimize it, but this takes the guesswork out of it.

}

private:
const DataArray<T>& m_InputArray;
Float32Array& m_NormArray;
float32 m_PSpace;
};

struct ComputeNormFunctor
{
template <typename T>
void operator()(const IDataArray& inputArray, Float32Array& normArray, float32 pSpace)
{
ComputeNormImpl<T>(inputArray, normArray, pSpace)();
}
};
} // namespace

// -----------------------------------------------------------------------------
ComputeArrayNorm::ComputeArrayNorm(DataStructure& dataStructure, const IFilter::MessageHandler& mesgHandler, const std::atomic_bool& shouldCancel, ComputeArrayNormInputValues* inputValues)
: m_DataStructure(dataStructure)
, m_InputValues(inputValues)
, m_ShouldCancel(shouldCancel)
, m_MessageHandler(mesgHandler)
{
}

// -----------------------------------------------------------------------------
ComputeArrayNorm::~ComputeArrayNorm() noexcept = default;

// -----------------------------------------------------------------------------
const std::atomic_bool& ComputeArrayNorm::getCancel()
{
return m_ShouldCancel;
}

// -----------------------------------------------------------------------------
Result<> ComputeArrayNorm::operator()()
{
const auto& inputArray = m_DataStructure.getDataRefAs<IDataArray>(m_InputValues->SelectedArrayPath);
auto& normArray = m_DataStructure.getDataRefAs<Float32Array>(m_InputValues->NormArrayPath);

ExecuteDataFunction(ComputeNormFunctor{}, inputArray.getDataType(), inputArray, normArray, m_InputValues->PSpace);

return {};
}
45 changes: 45 additions & 0 deletions src/SimplnxReview/Filters/Algorithms/ComputeArrayNorm.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#pragma once

#include "SimplnxReview/SimplnxReview_export.hpp"

#include "simplnx/DataStructure/DataPath.hpp"
#include "simplnx/DataStructure/DataStructure.hpp"
#include "simplnx/Filter/IFilter.hpp"

namespace nx::core
{

struct SIMPLNXREVIEW_EXPORT ComputeArrayNormInputValues
{
float32 PSpace;
DataPath SelectedArrayPath;
DataPath NormArrayPath;
};

/**
* @class ComputeArrayNorm
* @brief This algorithm computes the p-th norm of an Attribute Array.
*/
class SIMPLNXREVIEW_EXPORT ComputeArrayNorm
{
public:
ComputeArrayNorm(DataStructure& dataStructure, const IFilter::MessageHandler& mesgHandler, const std::atomic_bool& shouldCancel, ComputeArrayNormInputValues* inputValues);
~ComputeArrayNorm() noexcept;

ComputeArrayNorm(const ComputeArrayNorm&) = delete;
ComputeArrayNorm(ComputeArrayNorm&&) noexcept = delete;
ComputeArrayNorm& operator=(const ComputeArrayNorm&) = delete;
ComputeArrayNorm& operator=(ComputeArrayNorm&&) noexcept = delete;

Result<> operator()();

const std::atomic_bool& getCancel();

private:
DataStructure& m_DataStructure;
const ComputeArrayNormInputValues* m_InputValues = nullptr;
const std::atomic_bool& m_ShouldCancel;
const IFilter::MessageHandler& m_MessageHandler;
};

} // namespace nx::core
149 changes: 149 additions & 0 deletions src/SimplnxReview/Filters/ComputeArrayNormFilter.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
#include "ComputeArrayNormFilter.hpp"

#include "SimplnxReview/Filters/Algorithms/ComputeArrayNorm.hpp"

#include "simplnx/DataStructure/DataArray.hpp"
#include "simplnx/DataStructure/DataPath.hpp"
#include "simplnx/Filter/Actions/CreateArrayAction.hpp"
#include "simplnx/Parameters/ArraySelectionParameter.hpp"
#include "simplnx/Parameters/DataObjectNameParameter.hpp"
#include "simplnx/Parameters/NumberParameter.hpp"
#include "simplnx/Utilities/SIMPLConversion.hpp"

using namespace nx::core;

namespace nx::core
{
//------------------------------------------------------------------------------
std::string ComputeArrayNormFilter::name() const
{
return FilterTraits<ComputeArrayNormFilter>::name.str();
}

//------------------------------------------------------------------------------
std::string ComputeArrayNormFilter::className() const
{
return FilterTraits<ComputeArrayNormFilter>::className;
}

//------------------------------------------------------------------------------
Uuid ComputeArrayNormFilter::uuid() const
{
return FilterTraits<ComputeArrayNormFilter>::uuid;
}

//------------------------------------------------------------------------------
std::string ComputeArrayNormFilter::humanName() const
{
return "Compute Array Norm";
}

//------------------------------------------------------------------------------
std::vector<std::string> ComputeArrayNormFilter::defaultTags() const
{
return {className(), "Statistics", "DREAM3DReview"};
}

//------------------------------------------------------------------------------
Parameters ComputeArrayNormFilter::parameters() const
{
Parameters params;

params.insertSeparator(Parameters::Separator{"Input Parameter"});
params.insert(std::make_unique<Float32Parameter>(k_PSpace_Key, "p-Space Value", "p-Value used for computing the norm (2 = Euclidean, 1 = Manhattan)", 2.0f));

params.insertSeparator(Parameters::Separator{"Input Data"});
params.insert(std::make_unique<ArraySelectionParameter>(k_SelectedArrayPath_Key, "Input Attribute Array", "The input array for computing the norm", DataPath{},
ArraySelectionParameter::AllowedTypes{DataType::int8, DataType::uint8, DataType::int16, DataType::uint16, DataType::int32, DataType::uint32,
DataType::int64, DataType::uint64, DataType::float32, DataType::float64},
ArraySelectionParameter::AllowedComponentShapes{}));

params.insertSeparator(Parameters::Separator{"Output Data"});
params.insert(std::make_unique<DataObjectNameParameter>(k_NormArrayName_Key, "Norm Array Name", "The name of the output norm array", "Norm"));

return params;
}

//------------------------------------------------------------------------------
IFilter::UniquePointer ComputeArrayNormFilter::clone() const
{
return std::make_unique<ComputeArrayNormFilter>();
}

//------------------------------------------------------------------------------
IFilter::VersionType ComputeArrayNormFilter::parametersVersion() const
{
return 1;
}

//------------------------------------------------------------------------------
IFilter::PreflightResult ComputeArrayNormFilter::preflightImpl(const DataStructure& dataStructure, const Arguments& filterArgs, const MessageHandler& messageHandler,
const std::atomic_bool& shouldCancel, const ExecutionContext& executionContext) const
{
auto pSpaceValue = filterArgs.value<float32>(k_PSpace_Key);
auto pSelectedArrayPathValue = filterArgs.value<DataPath>(k_SelectedArrayPath_Key);
auto pNormArrayNameValue = filterArgs.value<std::string>(k_NormArrayName_Key);

PreflightResult preflightResult;
nx::core::Result<OutputActions> resultOutputActions;
std::vector<PreflightValue> preflightUpdatedValues;

if(pSpaceValue < 0.0f)
{
return {MakeErrorResult<OutputActions>(-11002, "p-space value must be greater than or equal to 0")};
}

const auto* inputArray = dataStructure.getDataAs<IDataArray>(pSelectedArrayPathValue);
if(inputArray == nullptr)
{
return {MakeErrorResult<OutputActions>(-11003, fmt::format("Cannot find the selected input array at path '{}'", pSelectedArrayPathValue.toString()))};
}

DataPath normArrayPath = pSelectedArrayPathValue.replaceName(pNormArrayNameValue);

{
auto createArrayAction = std::make_unique<CreateArrayAction>(DataType::float32, inputArray->getTupleShape(), std::vector<usize>{1}, normArrayPath);
resultOutputActions.value().appendAction(std::move(createArrayAction));
}

return {std::move(resultOutputActions), std::move(preflightUpdatedValues)};
Comment on lines +87 to +109
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
PreflightResult preflightResult;
nx::core::Result<OutputActions> resultOutputActions;
std::vector<PreflightValue> preflightUpdatedValues;
if(pSpaceValue < 0.0f)
{
return {MakeErrorResult<OutputActions>(-11002, "p-space value must be greater than or equal to 0")};
}
const auto* inputArray = dataStructure.getDataAs<IDataArray>(pSelectedArrayPathValue);
if(inputArray == nullptr)
{
return {MakeErrorResult<OutputActions>(-11003, fmt::format("Cannot find the selected input array at path '{}'", pSelectedArrayPathValue.toString()))};
}
DataPath normArrayPath = pSelectedArrayPathValue.replaceName(pNormArrayNameValue);
{
auto createArrayAction = std::make_unique<CreateArrayAction>(DataType::float32, inputArray->getTupleShape(), std::vector<usize>{1}, normArrayPath);
resultOutputActions.value().appendAction(std::move(createArrayAction));
}
return {std::move(resultOutputActions), std::move(preflightUpdatedValues)};
nx::core::Result<OutputActions> resultOutputActions;
if(pSpaceValue < 0.0f)
{
return MakePreflightErrorResult(-11002, "p-space value must be greater than or equal to 0");
}
const auto* inputArray = dataStructure.getDataAs<IDataArray>(pSelectedArrayPathValue);
if(inputArray == nullptr)
{
return MakePreflightErrorResult(-11003, fmt::format("Cannot find the selected input array at path '{}'", pSelectedArrayPathValue.toString()));
}
DataPath normArrayPath = pSelectedArrayPathValue.replaceName(pNormArrayNameValue);
{
auto createArrayAction = std::make_unique<CreateArrayAction>(DataType::float32, inputArray->getTupleShape(), std::vector<usize>{1}, normArrayPath);
resultOutputActions.value().appendAction(std::move(createArrayAction));
}
return {std::move(resultOutputActions)};

}

//------------------------------------------------------------------------------
Result<> ComputeArrayNormFilter::executeImpl(DataStructure& dataStructure, const Arguments& filterArgs, const PipelineFilter* pipelineNode, const MessageHandler& messageHandler,
const std::atomic_bool& shouldCancel, const ExecutionContext& executionContext) const
{
ComputeArrayNormInputValues inputValues;

inputValues.PSpace = filterArgs.value<float32>(k_PSpace_Key);
inputValues.SelectedArrayPath = filterArgs.value<DataPath>(k_SelectedArrayPath_Key);
inputValues.NormArrayPath = inputValues.SelectedArrayPath.replaceName(filterArgs.value<std::string>(k_NormArrayName_Key));

return ComputeArrayNorm(dataStructure, messageHandler, shouldCancel, &inputValues)();
}

namespace
{
namespace SIMPL
{
constexpr StringLiteral k_SelectedArrayPathKey = "SelectedArrayPath";
constexpr StringLiteral k_NormArrayPathKey = "NormArrayPath";
constexpr StringLiteral k_PSpaceKey = "PSpace";
} // namespace SIMPL
} // namespace

Result<Arguments> ComputeArrayNormFilter::FromSIMPLJson(const nlohmann::json& json)
{
Arguments args = ComputeArrayNormFilter().getDefaultArguments();

std::vector<Result<>> results;

results.push_back(SIMPLConversion::ConvertParameter<SIMPLConversion::FloatFilterParameterConverter<float32>>(args, json, SIMPL::k_PSpaceKey, k_PSpace_Key));
results.push_back(SIMPLConversion::ConvertParameter<SIMPLConversion::DataArraySelectionFilterParameterConverter>(args, json, SIMPL::k_SelectedArrayPathKey, k_SelectedArrayPath_Key));
results.push_back(SIMPLConversion::ConvertParameter<SIMPLConversion::DataArrayCreationToDataObjectNameFilterParameterConverter>(args, json, SIMPL::k_NormArrayPathKey, k_NormArrayName_Key));

Result<> conversionResult = MergeResults(std::move(results));

return ConvertResultTo<Arguments>(std::move(conversionResult), std::move(args));
}
} // namespace nx::core
Loading
Loading