diff --git a/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h b/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h index ff0ccf657b..89fe0f38d2 100644 --- a/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h +++ b/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h @@ -1,215 +1,215 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkRenderingTestHelper_h #define mitkRenderingTestHelper_h #include #include #include #include #include class vtkRenderWindow; class vtkRenderer; namespace mitk { class MITKTESTINGHELPER_EXPORT RenderingTestHelper { public: /** @brief Generate a rendering test helper object including a render window of the size width * height (in pixel). @param width @param height @param argc Number of parameters. (here: Images) "Usage: [filename1 filenam2 -V referenceScreenshot (optional -T /directory/to/save/differenceImage)] @param argv Given parameters. If no data is inserted via commandline, you can add data later via AddNodeToDataStorage(). @param antiAliasing The anti-aliasing mode. **/ RenderingTestHelper( int width, int height, int argc, char *argv[], AntiAliasing antiAliasing = AntiAliasing::None); /** @brief Generate a rendering test helper object including a render window of the size width * height (in * pixel).*/ RenderingTestHelper( int width, int height, AntiAliasing antiAliasing = AntiAliasing::None); /** Default destructor */ ~RenderingTestHelper(); /** @brief Getter for the vtkRenderer. **/ vtkRenderer *GetVtkRenderer(); /** @brief Getter for the vtkRenderWindow which should be used to call vtkRegressionTestImage. **/ vtkRenderWindow *GetVtkRenderWindow(); /** @brief Method can be used to save a screenshot (e.g. reference screenshot as a .png file. @param fileName The filename of the new screenshot (including path). **/ void SaveAsPNG(std::string fileName); /** - * @brief SetStopRenderWindow Convenience method to make the renderwindow hold after rendering. Usefull for + * @brief SetStopRenderWindow Convenience method to make the renderwindow hold after rendering. Useful for * debugging. * @param automaticallyCloseRenderWindow Flag indicating whether the renderwindow should automatically close (false, default) or stay open - * (true). Usefull for debugging. + * (true). Useful for debugging. */ void SetAutomaticallyCloseRenderWindow(bool automaticallyCloseRenderWindow); /** @brief This method set the property of the member datastorage @param propertyKey @param property Set a property for each image in the datastorage m_DataStorage. If you want to set the property for a single data node, use GetDataStorage() and set the property yourself for the destinct node. **/ void SetImageProperty(const char *propertyKey, mitk::BaseProperty *property); /** @brief Set the view direction of the renderwindow (e.g. sagittal, coronal, axial) **/ void SetViewDirection(mitk::SliceNavigationController::ViewDirection viewDirection); /** @brief Reorient the slice (e.g. rotation and translation like the swivel mode). **/ void ReorientSlices(mitk::Point3D origin, mitk::Vector3D rotation); /** @brief Render everything into an mitkRenderWindow. Call SetViewDirection() and SetProperty() before this method. **/ void Render(); /** @brief Returns the datastorage, in order to modify the data inside a rendering test. **/ mitk::DataStorage::Pointer GetDataStorage(); /** * @brief SetMapperID Change between Standard2D and 3D mappers. * @param id Enum mitk::BaseRenderer::StandardMapperSlot which defines the mapper. */ void SetMapperID(mitk::BaseRenderer::StandardMapperSlot id); /** * @brief AddNodeToStorage Add a node to the datastorage and perform a reinit which is necessary for rendering. * @param node The data you want to add. */ void AddNodeToStorage(mitk::DataNode::Pointer node); /** * @brief SetMapperIDToRender3D Convenience method to render in a 3D renderwindow. * @warning Does not add helper objects like the image planes to render images in 3D. */ void SetMapperIDToRender3D(); /** * @brief SetMapperIDToRender2D Convenience method to render in a 2D renderwindow. */ void SetMapperIDToRender2D(); /** * @brief SaveReferenceScreenShot Convenience method to save a reference screen shot. * @param fileName Path/to/save/the/png/file. */ void SaveReferenceScreenShot(std::string fileName); /** * @brief CompareRenderWindowAgainstReference Convenience method to compare the image rendered in the internal renderwindow against a reference screen shot. * Usage of vtkTesting::Test: vtkTesting::Test( argc, argv, vtkRenderWindow, threshold ) Set a vtkRenderWindow containing the desired scene. This is automatically rendered. vtkTesting::Test() automatically searches in argc and argv[] for a path a valid image with -V. If the test failed with the first image (foo.png) it checks if there are images of the form foo_N.png (where N=1,2,3...) and compare against them. This allows for multiple valid images. * @param argc Number of arguments. * @param argv Arguments must(!) contain the term "-V Path/To/Valid/Image.png" * @param threshold Allowed difference between two images. Default = 10.0 and was taken from VTK. * @return True if the images are equal regarding the threshold. False in all other cases. */ bool CompareRenderWindowAgainstReference(int argc, char *argv[], double threshold = 10.0); /** - * @brief The ArgcHelperClass class is a convinience class to convert a vector + * @brief The ArgcHelperClass class is a convenience class to convert a vector * of strings to the standard c++ argv and argc arguments. This is necessary for * the vtkTesting::Test, since is requires the reference image (and other * optional parameters) via command line. */ class ArgcHelperClass { private: /** * Members for conversion. */ std::vector argv; std::vector> argvec; public: ArgcHelperClass(const std::vector &argstrings) : argv(argstrings.size() + 1), argvec(argstrings.size() + 1) { std::vector cmdArgs; cmdArgs.push_back(mitk::IOUtil::GetProgramPath()); cmdArgs.insert(cmdArgs.end(), argstrings.begin(), argstrings.end()); for (std::size_t i = 0; i < cmdArgs.size(); ++i) { argvec[i].assign(cmdArgs[i].begin(), cmdArgs[i].end()); argvec[i].push_back('\0'); argv[i] = &argvec[i][0]; } } char **GetArgv() { return &argv[0]; } int GetArgc() { return argv.size(); } }; protected: /** * @brief Initialize Internal method to initialize the renderwindow and set the datastorage. * @param width Height of renderwindow. * @param height Width of renderwindow. * @param antiAliasing The anti-aliasing mode. */ void Initialize( int width, int height, AntiAliasing antiAliasing = AntiAliasing::None); /** @brief This method tries to load the given file into a member datastorage, in order to render it. @param filename The filename of the file to be loaded (including path). **/ void AddToStorage(const std::string &filename); /** @brief This method tries to parse the given argv for files (e.g. images) and load them into a member datastorage, in order to render it. @param argc Number of parameters. @param argv Given parameters. **/ void SetInputFileNames(int argc, char *argv[]); mitk::RenderWindow::Pointer m_RenderWindow; //<< Contains the mitkRenderWindow into which the test renders the data mitk::DataStorage::Pointer m_DataStorage; //<< Contains the mitkDataStorage which contains the data to be rendered bool m_AutomaticallyCloseRenderWindow; //<< Flag indicating whether the renderwindow should automatically close (true, - // default) or stay open (false). Usefull for debugging. + // default) or stay open (false). Useful for debugging. }; } // namespace mitk #endif diff --git a/Modules/Core/TestingHelper/include/mitkTestingMacros.h b/Modules/Core/TestingHelper/include/mitkTestingMacros.h index f838eeffe0..9c7b982eb7 100644 --- a/Modules/Core/TestingHelper/include/mitkTestingMacros.h +++ b/Modules/Core/TestingHelper/include/mitkTestingMacros.h @@ -1,392 +1,392 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkTestingMacros_h #define mitkTestingMacros_h #include #include #include #include #include #include #include #include #include #include namespace mitk { /** @brief Indicate a failed test. */ class TestFailedException : public std::exception { public: TestFailedException() {} }; } /** * @brief Output some text without generating a terminating newline. Include * * @ingroup MITKTestingAPI */ #define MITK_TEST_OUTPUT_NO_ENDL(x) std::cout x; /** * @brief Output some text. * * @ingroup MITKTestingAPI */ #define MITK_TEST_OUTPUT(x) MITK_TEST_OUTPUT_NO_ENDL(x << "\n") /** * @brief Do some general test preparations. Must be called first in the * main test function. * * @deprecatedSince{2013_09} Use MITK_TEST_SUITE_REGISTRATION instead. * @ingroup MITKTestingAPI */ #define MITK_TEST_BEGIN(testName) \ std::string mitkTestName(#testName); \ mitk::TestManager::GetInstance()->Initialize(); \ try \ { /** * @brief Fail and finish test with message MSG * * @deprecatedSince{2013_09} Use CPPUNIT_FAIL instead * @ingroup MITKTestingAPI */ #define MITK_TEST_FAILED_MSG(MSG) \ MITK_TEST_OUTPUT(MSG) \ throw mitk::TestFailedException(); /** * @brief Must be called last in the main test function. * * @deprecatedSince{2013_09} Use MITK_TEST_SUITE_REGISTRATION instead. * @ingroup MITKTestingAPI */ #define MITK_TEST_END() \ } \ catch (const mitk::TestFailedException &) \ { \ MITK_TEST_OUTPUT(<< "Further test execution skipped.") \ mitk::TestManager::GetInstance()->TestFailed(); \ } \ catch (const std::exception &ex) \ { \ - MITK_TEST_OUTPUT(<< "std::exception occured " << ex.what()) \ + MITK_TEST_OUTPUT(<< "std::exception occurred " << ex.what()) \ mitk::TestManager::GetInstance()->TestFailed(); \ } \ if (mitk::TestManager::GetInstance()->NumberOfFailedTests() > 0) \ { \ MITK_TEST_OUTPUT(<< mitkTestName << ": [DONE FAILED] , subtests passed: " \ << mitk::TestManager::GetInstance()->NumberOfPassedTests() \ << " failed: " \ << mitk::TestManager::GetInstance()->NumberOfFailedTests()) \ return EXIT_FAILURE; \ } \ else \ { \ MITK_TEST_OUTPUT(<< mitkTestName << ": " << mitk::TestManager::GetInstance()->NumberOfPassedTests() \ << " tests [DONE PASSED]") \ return EXIT_SUCCESS; \ } /** * @deprecatedSince{2013_09} Use CPPUNIT_ASSERT or CPPUNIT_ASSERT_MESSAGE instead. */ #define MITK_TEST_CONDITION(COND, MSG) \ MITK_TEST_OUTPUT_NO_ENDL(<< MSG) \ if (!(COND)) \ { \ mitk::TestManager::GetInstance()->TestFailed(); \ MITK_TEST_OUTPUT(<< " [FAILED]\n" \ << "In " \ << __FILE__ \ << ", line " \ << __LINE__ \ << ": " #COND " : [FAILED]") \ } \ else \ { \ MITK_TEST_OUTPUT(<< " [PASSED]") \ mitk::TestManager::GetInstance()->TestPassed(); \ } /** * @deprecatedSince{2013_09} Use CPPUNIT_ASSERT or CPPUNIT_ASSERT_MESSAGE instead. */ #define MITK_TEST_CONDITION_REQUIRED(COND, MSG) \ MITK_TEST_OUTPUT_NO_ENDL(<< MSG) \ if (!(COND)) \ { \ MITK_TEST_FAILED_MSG(<< " [FAILED]\n" \ << " +--> in " \ << __FILE__ \ << ", line " \ << __LINE__ \ << ", expression is false: \"" #COND "\"") \ } \ else \ { \ MITK_TEST_OUTPUT(<< " [PASSED]") \ mitk::TestManager::GetInstance()->TestPassed(); \ } /** * \brief Begin block which should be checked for exceptions * * @deprecatedSince{2013_09} Use CPPUNIT_ASSERT_THROW instead. * @ingroup MITKTestingAPI * * This macro, together with MITK_TEST_FOR_EXCEPTION_END, can be used * to test whether a code block throws an expected exception. The test FAILS if the * exception is NOT thrown. A simple example: * MITK_TEST_FOR_EXCEPTION_BEGIN(itk::ImageFileReaderException) typedef itk::ImageFileReader< itk::Image > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName("/tmp/not-existing"); reader->Update(); MITK_TEST_FOR_EXCEPTION_END(itk::ImageFileReaderException) * */ #define MITK_TEST_FOR_EXCEPTION_BEGIN(EXCEPTIONCLASS) \ try \ { /** * @deprecatedSince{2013_09} */ #define MITK_TEST_FOR_EXCEPTION_END(EXCEPTIONCLASS) \ mitk::TestManager::GetInstance()->TestFailed(); \ MITK_TEST_OUTPUT(<< "Expected an '" << #EXCEPTIONCLASS << "' exception. [FAILED]") \ } \ catch (const EXCEPTIONCLASS &) \ { \ MITK_TEST_OUTPUT(<< "Caught an expected '" << #EXCEPTIONCLASS << "' exception. [PASSED]") \ mitk::TestManager::GetInstance()->TestPassed(); \ } /** * @brief Simplified version of MITK_TEST_FOR_EXCEPTION_BEGIN / END for * a single statement * * @deprecatedSince{2013_09} Use CPPUNIT_ASSERT_THROW instead. * @ingroup MITKTestingAPI */ #define MITK_TEST_FOR_EXCEPTION(EXCEPTIONCLASS, STATEMENT) \ MITK_TEST_FOR_EXCEPTION_BEGIN(EXCEPTIONCLASS) \ STATEMENT; \ MITK_TEST_FOR_EXCEPTION_END(EXCEPTIONCLASS) /** * @brief Testing macro to test if two objects are equal. * * @ingroup MITKTestingAPI * * This macro uses mitk::eps and the corresponding mitk::Equal methods for all * comparisons and will give verbose output on the dashboard/console. * Feel free to implement mitk::Equal for your own datatype or purpose. * * @param EXPECTED First object. * @param ACTUAL Second object. * @param MSG Message to appear with the test. * @throw Throws mitkException if a nullptr pointer is given as input. */ #define MITK_ASSERT_EQUAL(EXPECTED, ACTUAL, MSG) \ if (((EXPECTED).IsNull()) || ((ACTUAL).IsNull())) \ { \ mitkThrow() << "mitk::Equal does not work with nullptr pointer input."; \ } \ CPPUNIT_ASSERT_MESSAGE(MSG, mitk::Equal(*(EXPECTED), *(ACTUAL), mitk::eps, true)) /** * @brief Testing macro to test if two objects are not equal. * * @ingroup MITKTestingAPI * * This macro uses mitk::eps and the corresponding mitk::Equal methods for all * comparisons and will give verbose output on the dashboard/console. * * @deprecatedSince{2013_09} Use MITK_ASSERT_NOT_EQUAL instead. * * @param OBJ1 First object. * @param OBJ2 Second object. * @param MSG Message to appear with the test. * * \sa MITK_TEST_EQUAL */ #define MITK_TEST_NOT_EQUAL(OBJ1, OBJ2, MSG) \ CPPUNIT_ASSERT_MESSAGE(MSG, !mitk::Equal(*(OBJ1), *(OBJ2), mitk::eps, true)) /** * @brief Testing macro to test if two objects are not equal. * * @ingroup MITKTestingAPI * * This macro uses mitk::eps and the corresponding mitk::Equal methods for all * comparisons and will give verbose output on the dashboard/console. * * @param OBJ1 First object. * @param OBJ2 Second object. * @param MSG Message to appear with the test. * @throw Throws mitkException if a nullptr pointer is given as input. * * \sa MITK_ASSERT_EQUAL */ #define MITK_ASSERT_NOT_EQUAL(OBJ1, OBJ2, MSG) \ if (((OBJ1).IsNull()) || ((OBJ2).IsNull())) \ { \ mitkThrow() << "mitk::Equal does not work with nullptr pointer input."; \ } \ CPPUNIT_ASSERT_MESSAGE(MSG, !mitk::Equal(*(OBJ1), *(OBJ2), mitk::eps, true)) /** * @brief Registers the given test suite. * * @ingroup MITKTestingAPI * * @param TESTSUITE_NAME The name of the test suite class, without "TestSuite" * at the end. */ #define MITK_TEST_SUITE_REGISTRATION(TESTSUITE_NAME) \ int TESTSUITE_NAME##Test(int /*argc*/, char * /*argv*/ []) \ { \ int result = 0; \ try \ { \ CppUnit::TextUi::TestRunner runner; \ runner.addTest(TESTSUITE_NAME##TestSuite::suite()); \ result = runner.run() ? 0 : 1; \ } \ catch (const mitk::TestNotRunException& e) \ { \ MITK_WARN << "Test not run: " << e.GetDescription(); \ result = 77; \ } \ return result; \ } /** * @brief Adds a test to the current test suite. * * @ingroup MITKTestingAPI * * Use this macro after the CPPUNIT_TEST_SUITE() macro to add test cases. * The macro internally just calls the CPPUNIT_TEST macro. * - * @param TESTMETHOD The name of the member funtion test. + * @param TESTMETHOD The name of the member function test. */ #define MITK_TEST(TESTMETHOD) CPPUNIT_TEST(TESTMETHOD) /** * @brief Adds a parameterized test to the current test suite. * * @ingroup MITKTestingAPI * * Use this macro after the CPPUNIT_TEST_SUITE() macro to add test cases * which need custom parameters. * * @param TESTMETHOD The name of the member function test. * @param ARGS A std::vector object containing test parameter. * * @note Use the macro MITK_PARAMETERIZED_TEST only if you know what * you are doing. If you are not sure, use MITK_TEST instead. */ #define MITK_PARAMETERIZED_TEST(TESTMETHOD, ARGS) \ \ { \ std::string testName = #TESTMETHOD; \ for (std::size_t i = 0; i < ARGS.size(); ++i) \ { \ testName += "_" + ARGS[i]; \ } \ CPPUNIT_TEST_SUITE_ADD_TEST((new mitk::TestCaller( \ context.getTestNameFor(testName), &TestFixtureType::TESTMETHOD, context.makeFixture(), args))); \ } /** * @brief Adds a parameterized test to the current test suite. * * @ingroup MITKTestingAPI * * Use this macro after the CPPUNIT_TEST_SUITE() macro to add test cases * which need parameters from the command line. * * @warning Use the macro MITK_PARAMETERIZED_CMD_LINE_TEST only * if you know what you are doing. If you are not sure, use * MITK_TEST instead. MITK_PARAMETERIZED_CMD_LINE_TEST is meant * for migrating from ctest to CppUnit. If you implement new * tests, the MITK_TEST macro will be sufficient. * * @param TESTMETHOD The name of the member function test. */ #define MITK_PARAMETERIZED_CMD_LINE_TEST(TESTMETHOD) \ CPPUNIT_TEST_SUITE_ADD_TEST((new mitk::TestCaller( \ context.getTestNameFor(#TESTMETHOD), &TestFixtureType::TESTMETHOD, context.makeFixture()))); /** * @brief Adds a parameterized test to the current test suite. * * @ingroup MITKTestingAPI * * Use this macro after the CPPUNIT_TEST_SUITE() macro to add test cases * which need one custom parameter. * * @param TESTMETHOD The name of the member function test. * @param arg1 A custom string parameter being passed to the fixture. * * @note Use the macro MITK_PARAMETERIZED_TEST_1 only if you know what * you are doing. If you are not sure, use MITK_TEST instead. * * @see MITK_PARAMETERIZED_TEST */ #define MITK_PARAMETERIZED_TEST_1(TESTMETHOD, arg1) \ \ { \ std::vector args; \ args.push_back(arg1); \ MITK_PARAMETERIZED_TEST(TESTMETHOD, args) \ } /** * @brief Adds a parameterized test to the current test suite. * * @ingroup MITKTestingAPI * * Use this macro after the CPPUNIT_TEST_SUITE() macro to add test cases * which need two custom parameter. * * @param TESTMETHOD The name of the member function test. * @param arg1 A custom string parameter being passed to the fixture. * @param arg2 * * @note Use the macro MITK_PARAMETERIZED_TEST_2 only if you know what * you are doing. If you are not sure, use MITK_TEST instead. * * @see MITK_PARAMETERIZED_TEST */ #define MITK_PARAMETERIZED_TEST_2(TESTMETHOD, arg1, arg2) \ \ { \ std::vector args; \ args.push_back(arg1); \ args.push_back(arg2); \ MITK_PARAMETERIZED_TEST(TESTMETHOD, args) \ } #endif diff --git a/Modules/Core/test/DirectOverlayTest.cpp b/Modules/Core/test/DirectOverlayTest.cpp index 79d3ea7406..91157c5226 100644 --- a/Modules/Core/test/DirectOverlayTest.cpp +++ b/Modules/Core/test/DirectOverlayTest.cpp @@ -1,249 +1,249 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include #include #include #include #include #include #include //#include class DirectOverlayTestClass { public: template static void InternalThreshold(const itk::Image *image, mitk::Image::Pointer &output, const double th[]) { typedef itk::Image InputImageType; typedef itk::Image OutputImageType; typedef itk::BinaryThresholdImageFilter BinaryThresholdFilterType; typename BinaryThresholdFilterType::Pointer thresholder = BinaryThresholdFilterType::New(); thresholder->SetInput(image); thresholder->SetLowerThreshold(th[0]); thresholder->SetUpperThreshold(th[1]); thresholder->SetInsideValue(255); thresholder->SetOutsideValue(0); thresholder->Update(); output = mitk::ImportItkImage(thresholder->GetOutput()); // mitk::IOUtil::Save( output, "/tmp/out.nii" ); std::cout << "extra line"; } template static void InternalThreshold2(const itk::Image *image, itk::Image::Pointer &output, const double th[]) { typedef itk::Image InputImageType; typedef itk::Image OutputImageType; typedef itk::BinaryThresholdImageFilter BinaryThresholdFilterType; typename BinaryThresholdFilterType::Pointer thresholder = BinaryThresholdFilterType::New(); thresholder->SetInput(image); thresholder->SetLowerThreshold(th[0]); thresholder->SetUpperThreshold(th[1]); thresholder->SetInsideValue(255); thresholder->SetOutsideValue(0); thresholder->Update(); output = thresholder->GetOutput(); } static void TestOverlay(mitk::Image::Pointer original, mitk::Image::Pointer truth, const double lower, const double upper) { mitk::Image::Pointer overlayImage; const double th[] = {lower, upper}; typedef itk::Image ImageType; ImageType::Pointer itkOverlayImage = ImageType::New(); AccessByItk_2(original, InternalThreshold, overlayImage, th); /* AccessFixedDimensionByItk_2( original, InternalThreshold2, 3, itkOverlayImage, th ); overlayImage = mitk::ImportItkImage( itkOverlayImage ); */ // mitk::IOUtil::Save(truth, "/tmp/truth_TestOverlay.nii"); try { // mitk::Image::Pointer temp = overlayImage; mitk::IOUtil::Save(overlayImage, "/tmp/overlayImage_TestOverlay.nrrd"); } catch (const itk::ExceptionObject &e) { MITK_ERROR << "Save image: exception : " << e.what(); } typedef itk::Image InputImageType; InputImageType::Pointer overlayItk; try { mitk::CastToItkImage(overlayImage, overlayItk); } catch (const mitk::Exception &e) { - MITK_ERROR << "(CAST) Catched exception while creating accessor " << e.what(); + MITK_ERROR << "(CAST) Caught exception while creating accessor " << e.what(); // MITK_TEST_FAILED_MSG("Exception for ouverlay image"); } /* typedef itk::ImageFileWriter< InputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName("/tmp/overlayITK_TestOverlay.nii"); writer->SetInput(overlayItk); writer->Update(); */ InputImageType::Pointer truthItk; mitk::CastToItkImage(truth, truthItk); bool difference = false; /* try { typedef unsigned int TPixel; itk::ImageRegionConstIteratorWithIndex< InputImageType > iter( truthItk, truthItk->GetLargestPossibleRegion() ); iter.GoToBegin(); mitk::ImagePixelReadAccessor< TPixel, 3 > readAccessor( overlayImage, overlayImage->GetVolumeData(0), mitk::ImageAccessorBase::ExceptionIfLocked ); while( !iter.IsAtEnd() ) { TPixel ref = iter.Get(); TPixel val = readAccessor.GetPixelByIndex( iter.GetIndex() ); difference |= ( ref != val ); //if( difference ) //{ std::cout << iter.GetIndex() << ":" << ref << " ? " << val << "\n"; //} ++iter; } } catch( const mitk::Exception &e) { - MITK_ERROR << "Catched exception while creating accessor "<< e.what(); + MITK_ERROR << "Caught exception while creating accessor "<< e.what(); //MITK_TEST_FAILED_MSG("Exception for ouverlay image"); } */ /* typedef itk::Testing::ComparisonImageFilter ComparisonImageFilterType; ComparisonImageFilterType::Pointer comp = ComparisonImageFilterType::New(); comp->SetValidInput(truthItk); comp->SetTestInput(overlayItk); try { comp->Update(); } catch( const itk::ExceptionObject& e) { MITK_ERROR << "ITK Exception: " << e.what(); } */ typedef unsigned int TPixel; itk::ImageRegionConstIteratorWithIndex iter(truthItk, truthItk->GetLargestPossibleRegion()); itk::ImageRegionConstIteratorWithIndex iter2(overlayItk, overlayItk->GetLargestPossibleRegion()); iter.GoToBegin(); unsigned int counter = 0; while (!iter.IsAtEnd() && !iter2.IsAtEnd()) { TPixel ref = iter.Get(); TPixel val = iter2.Get(); if (ref != val) { counter++; // std::cout << iter.GetIndex() << ":" << ref << " ? " << val << "\n"; } ++iter; ++iter2; } std::cout << "Differs in " << counter << "voxels" << std::endl; MITK_TEST_CONDITION_REQUIRED( // comp->GetNumberOfPixelsWithDifferences() == 0, counter == 0, "Comparing overlay with ground truth") } static void TestDirectOverlay(char *in, char *gt, const int lower, const int upper) { mitk::Image::Pointer original = mitk::IOUtil::Load(in); mitk::Image::Pointer truth = mitk::IOUtil::Load(gt); if (original.IsNotNull() && original->GetDimension() == 3 && truth.IsNotNull() && truth->GetDimension() == 3 && upper > lower) { TestOverlay(original, truth, lower, upper); } else { MITK_TEST_FAILED_MSG(<< "Invalid parameters"); } } }; int DirectOverlayTest(int argc, char *argv[]) { MITK_TEST_BEGIN("DirectOverlay") MITK_TEST_CONDITION_REQUIRED(argc >= 5, "File to load has been specified on the command line"); unsigned int lower = 0, upper = 0; try { sscanf(argv[3], "%u", &lower); sscanf(argv[4], "%u", &upper); // lower = boost::lexical_cast(argv[3]); // upper = boost::lexical_cast(argv[4]); MITK_INFO << "Got values: " << lower << " : " << upper; } catch (std::exception &e) { MITK_TEST_FAILED_MSG(<< e.what()); } DirectOverlayTestClass::TestDirectOverlay(argv[1], argv[2], lower, upper); MITK_TEST_END() } diff --git a/Modules/Core/test/files.cmake b/Modules/Core/test/files.cmake index 9aa105bf67..1a8abcb9b6 100644 --- a/Modules/Core/test/files.cmake +++ b/Modules/Core/test/files.cmake @@ -1,198 +1,198 @@ # tests with no extra command line parameter set(MODULE_TESTS # IMPORTANT: If you plan to deactivate / comment out a test please write a bug number to the commented out line of code. # # Example: #mitkMyTest #this test is commented out because of bug 12345 # # It is important that the bug is open and that the test will be activated again before the bug is closed. This assures that # no test is forgotten after it was commented out. If there is no bug for your current problem, please add a new one and # mark it as critical. ################## DISABLED TESTS ################################################# - #mitkAbstractTransformGeometryTest.cpp #seems as tested class mitkExternAbstractTransformGeometry doesnt exist any more + #mitkAbstractTransformGeometryTest.cpp #seems as tested class mitkExternAbstractTransformGeometry doesn't exist any more #mitkStateMachineContainerTest.cpp #rewrite test, indirect since no longer exported Bug 14529 #mitkRegistrationBaseTest.cpp #tested class mitkRegistrationBase doesn't exist any more #mitkSegmentationInterpolationTest.cpp #file doesn't exist! #mitkPipelineSmartPointerCorrectnessTest.cpp #file doesn't exist! #mitkITKThreadingTest.cpp #test outdated because itk::Semaphore was removed from ITK #mitkAbstractTransformPlaneGeometryTest.cpp #mitkVtkAbstractTransformPlaneGeometry doesn't exist any more #mitkTestUtilSharedLibrary.cpp #Linker problem with this test... #mitkTextOverlay2DSymbolsRenderingTest.cpp #Implementation of the tested feature is not finished yet. Ask Christoph or see bug 15104 for details. ################# RUNNING TESTS ################################################### mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkDataNodeTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkDispatcherTest.cpp mitkEnumerationPropertyTest.cpp mitkFileReaderRegistryTest.cpp #mitkFileWriterRegistryTest.cpp mitkFloatToStringTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometry3DEqualTest.cpp mitkGeometryDataIOTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkImageCastTest.cpp mitkImageDataItemTest.cpp mitkImageGeneratorTest.cpp mitkIOUtilTest.cpp mitkBaseDataTest.cpp mitkImportItkImageTest.cpp mitkGrabItkImageMemoryTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetTest.cpp mitkPointSetEqualTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetOnEmptyTest.cpp mitkPointSetLocaleTest.cpp mitkPointSetWriterTest.cpp mitkPointSetPointOperationsTest.cpp mitkProgressBarTest.cpp mitkPropertyTest.cpp mitkPropertyListTest.cpp mitkPropertyPersistenceTest.cpp mitkPropertyPersistenceInfoTest.cpp mitkPropertyRelationRuleBaseTest.cpp mitkPropertyRelationsTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkSurfaceTest.cpp mitkSurfaceEqualTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeGeometryTest.cpp mitkProportionalTimeGeometryTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp mitkStepperTest.cpp mitkRenderingManagerTest.cpp mitkCompositePixelValueToStringTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkNodePredicateDataPropertyTest.cpp mitkNodePredicateFunctionTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp mitkExceptionTest.cpp mitkExtractSliceFilterTest.cpp mitkLogTest.cpp mitkImageDimensionConverterTest.cpp mitkLoggingAdapterTest.cpp mitkUIDGeneratorTest.cpp mitkPlanePositionManagerTest.cpp mitkAffineTransformBaseTest.cpp mitkPropertyAliasesTest.cpp mitkPropertyDescriptionsTest.cpp mitkPropertyExtensionsTest.cpp mitkPropertyFiltersTest.cpp mitkPropertyKeyPathTest.cpp mitkTinyXMLTest.cpp mitkRawImageFileReaderTest.cpp mitkInteractionEventTest.cpp mitkLookupTableTest.cpp mitkSTLFileReaderTest.cpp mitkPointTypeConversionTest.cpp mitkVectorTypeConversionTest.cpp mitkMatrixTypeConversionTest.cpp mitkArrayTypeConversionTest.cpp mitkSurfaceToImageFilterTest.cpp mitkBaseGeometryTest.cpp mitkImageToSurfaceFilterTest.cpp mitkEqualTest.cpp mitkLineTest.cpp mitkArbitraryTimeGeometryTest.cpp mitkItkImageIOTest.cpp mitkLevelWindowManagerTest.cpp mitkVectorPropertyTest.cpp mitkTemporoSpatialStringPropertyTest.cpp mitkPropertyNameHelperTest.cpp mitkNodePredicateGeometryTest.cpp mitkNodePredicateSubGeometryTest.cpp mitkPreferenceListReaderOptionsFunctorTest.cpp mitkGenericIDRelationRuleTest.cpp mitkSourceImageRelationRuleTest.cpp mitkTemporalJoinImagesFilterTest.cpp ) set(MODULE_RENDERING_TESTS mitkPointSetDataInteractorTest.cpp mitkSurfaceVtkMapper2DTest.cpp mitkSurfaceVtkMapper2D3DTest.cpp ) # test with image filename as an extra command line parameter set(MODULE_IMAGE_TESTS mitkImageTimeSelectorTest.cpp #only runs on images mitkImageAccessorTest.cpp #only runs on images ) set(MODULE_SURFACE_TESTS mitkSurfaceVtkWriterTest.cpp #only runs on surfaces ) # list of images for which the tests are run set(MODULE_TESTIMAGE US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd Png2D-bw.png ) set(MODULE_TESTSURFACE binary.stl ball.stl ) set(MODULE_CUSTOM_TESTS mitkDataStorageTest.cpp mitkDataNodeTest.cpp mitkEventConfigTest.cpp mitkPointSetLocaleTest.cpp mitkImageTest.cpp mitkImageVtkMapper2DTest.cpp mitkImageVtkMapper2DLevelWindowTest.cpp mitkImageVtkMapper2DOpacityTest.cpp mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp mitkImageVtkMapper2DColorTest.cpp mitkImageVtkMapper2DSwivelTest.cpp mitkImageVtkMapper2DTransferFunctionTest.cpp mitkImageVtkMapper2DOpacityTransferFunctionTest.cpp mitkImageVtkMapper2DLookupTableTest.cpp mitkSurfaceVtkMapper3DTest.cpp mitkVolumeCalculatorTest.cpp mitkLevelWindowManagerTest.cpp mitkPointSetVtkMapper2DTest.cpp mitkPointSetVtkMapper2DImageTest.cpp mitkPointSetVtkMapper2DGlyphTypeTest.cpp mitkPointSetVtkMapper2DTransformedPointsTest.cpp mitkVTKRenderWindowSizeTest.cpp mitkMultiComponentImageDataComparisonFilterTest.cpp mitkImageToItkTest.cpp mitkImageSliceSelectorTest.cpp mitkPointSetReaderTest.cpp mitkImageEqualTest.cpp mitkRotatedSlice4DTest.cpp mitkPlaneGeometryDataMapper2DTest.cpp ) # Currently not working on windows because of a rendering timing issue # see bug 18083 for details if(NOT WIN32) set(MODULE_CUSTOM_TESTS ${MODULE_CUSTOM_TESTS} mitkSurfaceDepthSortingTest.cpp) endif() set(RESOURCE_FILES Interactions/AddAndRemovePoints.xml Interactions/globalConfig.xml Interactions/StatemachineTest.xml Interactions/StatemachineConfigTest.xml ) diff --git a/Modules/Core/test/mitkAbstractTransformGeometryTest.cpp b/Modules/Core/test/mitkAbstractTransformGeometryTest.cpp index ff8defb0c3..01051a9e7e 100644 --- a/Modules/Core/test/mitkAbstractTransformGeometryTest.cpp +++ b/Modules/Core/test/mitkAbstractTransformGeometryTest.cpp @@ -1,241 +1,241 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkExternAbstractTransformGeometry.h" #include "mitkImage.h" #include "mitkPlaneGeometry.h" #include "mitkSlicedGeometry3D.h" #include #include int mitkAbstractTransformGeometryTest(int /*argc*/, char * /*argv*/ []) { mitk::Point3D origin; mitk::Vector3D right, bottom; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM; std::cout << "Initializing an x-/y-plane (xyPlane) as parameter plane by InitializeStandardPlane(rightVector, " "downVector, spacing = nullptr): " << std::endl; mitk::PlaneGeometry::Pointer xyPlane = mitk::PlaneGeometry::New(); width = 100; widthInMM = width; height = 200; heightInMM = height; mitk::ScalarType bounds[6] = {0, width, 0, height, 0, 1}; mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); xyPlane->InitializeStandardPlane(right, bottom); xyPlane->SetOrigin(origin); xyPlane->SetSizeInUnits(width, height); std::cout << "Creating AbstractTransformGeometry: " << std::endl; mitk::ExternAbstractTransformGeometry::Pointer abstractgeometry = mitk::ExternAbstractTransformGeometry::New(); std::cout << "Setting xyPlane as parameter plane of AbstractTransformGeometry: " << std::endl; abstractgeometry->SetPlane(xyPlane); std::cout << "Testing whether the bounds of xyPlane and the parametric bounds of AbstractTransformGeometry are equal: "; if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(xyPlane->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(xyPlane->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; - std::cout << "Testing whether the parametic bounds of AbstractTransformGeometry and the bounds of the plane accessed " + std::cout << "Testing whether the parametric bounds of AbstractTransformGeometry and the bounds of the plane accessed " "from there are equal: "; if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; - std::cout << "Change parametic bounds of AbstractTransformGeometry and test whether they are equal to the bounds of " + std::cout << "Change parametric bounds of AbstractTransformGeometry and test whether they are equal to the bounds of " "the plane accessed from there: " << std::endl; height = 300; bounds[3] = height; abstractgeometry->SetParametricBounds(bounds); if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Initializing an phi-/theta-plane (sphereParameterPlane) as parameter plane by " "InitializeStandardPlane(rightVector, downVector, spacing = nullptr): " << std::endl; mitk::PlaneGeometry::Pointer sphereParameterPlane = mitk::PlaneGeometry::New(); width = 100; widthInMM = 2 * vnl_math::pi; height = 200; heightInMM = vnl_math::pi; mitk::ScalarType radiusInMM = 2.5; mitk::FillVector3D(origin, radiusInMM, 0, widthInMM); mitk::FillVector3D(right, 0, 0, -widthInMM); mitk::FillVector3D(bottom, 0, heightInMM, 0); sphereParameterPlane->InitializeStandardPlane(right, bottom); sphereParameterPlane->SetOrigin(origin); sphereParameterPlane->SetSizeInUnits(width, height); std::cout << "Creating an vtkSphericalTransform (sphericalTransform) to use with sphereParameterPlane: " << std::endl; vtkSphericalTransform *sphericalTransform = vtkSphericalTransform::New(); std::cout << "Setting sphereParameterPlane as parameter plane and sphericalTransform as transform of " "AbstractTransformGeometry: " << std::endl; abstractgeometry->SetPlane(sphereParameterPlane); abstractgeometry->SetVtkAbstractTransform(sphericalTransform); std::cout << "Testing whether the bounds of sphereParameterPlane and the parametric bounds of " "AbstractTransformGeometry are equal: "; if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(sphereParameterPlane->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(sphereParameterPlane->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; - std::cout << "Testing whether the parametic bounds of AbstractTransformGeometry and the bounds of the plane accessed " + std::cout << "Testing whether the parametric bounds of AbstractTransformGeometry and the bounds of the plane accessed " "from there are equal: "; if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mapping Map(pt2d_mm(phi=Pi,theta=Pi/2.0), pt3d_mm) and compare with expected (-radius, 0, 0): "; mitk::Point2D pt2d_mm; mitk::Point3D pt3d_mm, expected_pt3d_mm; pt2d_mm[0] = vnl_math::pi; pt2d_mm[1] = vnl_math::pi_over_2; mitk::FillVector3D(expected_pt3d_mm, -radiusInMM, 0, 0); abstractgeometry->Map(pt2d_mm, pt3d_mm); if (mitk::Equal(pt3d_mm, expected_pt3d_mm) == false) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mapping Map(pt3d_mm, pt2d_mm) and compare with expected: "; mitk::Point2D testpt2d_mm; abstractgeometry->Map(pt3d_mm, testpt2d_mm); if (mitk::Equal(pt2d_mm, testpt2d_mm) == false) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing IndexToWorld(pt2d_units, pt2d_mm) and compare with expected: "; mitk::Point2D pt2d_units; pt2d_units[0] = width / 2.0; pt2d_units[1] = height / 2.0; pt2d_mm[0] = widthInMM / 2.0; pt2d_mm[1] = heightInMM / 2.0; abstractgeometry->IndexToWorld(pt2d_units, testpt2d_mm); if (mitk::Equal(pt2d_mm, testpt2d_mm) == false) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; - std::cout << "Change parametic bounds of AbstractTransformGeometry and test whether they are equal to the bounds of " + std::cout << "Change parametric bounds of AbstractTransformGeometry and test whether they are equal to the bounds of " "the plane accessed from there: " << std::endl; height = 300; bounds[3] = height; abstractgeometry->SetParametricBounds(bounds); if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing IndexToWorld(pt2d_units, pt2d_mm) and compare with expected: "; pt2d_units[0] = width / 2.0; pt2d_units[1] = height / 2.0; pt2d_mm[0] = widthInMM / 2.0; pt2d_mm[1] = heightInMM / 2.0; abstractgeometry->IndexToWorld(pt2d_units, testpt2d_mm); if (mitk::Equal(pt2d_mm, testpt2d_mm) == false) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; // std::cout << "Testing availability and type (PlaneGeometry) of first geometry in the SlicedGeometry3D: "; // mitk::PlaneGeometry* accessedplanegeometry3 = // dynamic_cast(slicedWorldGeometry->GetGeometry2D(0)); // if(accessedplanegeometry3==nullptr) //{ // std::cout<<"[FAILED]"<GetAxisVector(0), planegeometry3->GetAxisVector(0))==false) || // (mitk::Equal(accessedplanegeometry3->GetAxisVector(1), planegeometry3->GetAxisVector(1))==false) || // (mitk::Equal(accessedplanegeometry3->GetAxisVector(2), planegeometry3->GetAxisVector(2))==false)) //{ // std::cout<<"[FAILED]"<Delete(); std::cout << "[TEST DONE]" << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Core/test/mitkAbstractTransformPlaneGeometryTest.cpp b/Modules/Core/test/mitkAbstractTransformPlaneGeometryTest.cpp index fdd87e7df8..d23d7c4f80 100644 --- a/Modules/Core/test/mitkAbstractTransformPlaneGeometryTest.cpp +++ b/Modules/Core/test/mitkAbstractTransformPlaneGeometryTest.cpp @@ -1,242 +1,242 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkImage.h" #include "mitkPlaneGeometry.h" #include "mitkSlicedGeometry3D.h" #include "mitkVtkAbstractTransformPlaneGeometry.h" #include #include #include #include int mitkVtkAbstractTransformPlaneGeometryTest(int argc, char *argv[]) { mitk::Point3D origin; mitk::Vector3D right, bottom; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM; std::cout << "Initializing an x-/y-plane (xyPlane) as parameter plane by InitializeStandardPlane(rightVector, " "downVector, spacing = nullptr): " << std::endl; mitk::PlaneGeometry::Pointer xyPlane = mitk::PlaneGeometry::New(); width = 100; widthInMM = width; height = 200; heightInMM = height; mitk::ScalarType bounds[6] = {0, width, 0, height, 0, 1}; mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); xyPlane->InitializeStandardPlane(right, bottom); xyPlane->SetOrigin(origin); xyPlane->SetSizeInUnits(width, height); std::cout << "Creating VtkAbstractTransformPlaneGeometry: " << std::endl; mitk::VtkAbstractTransformPlaneGeometry::Pointer abstractgeometry = mitk::VtkAbstractTransformPlaneGeometry::New(); std::cout << "Setting xyPlane as parameter plane of VtkAbstractTransformPlaneGeometry: " << std::endl; abstractgeometry->SetPlane(xyPlane); std::cout << "Testing whether the bounds of xyPlane and the parametric bounds of VtkAbstractTransformPlaneGeometry " "are equal: "; if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(xyPlane->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(xyPlane->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; - std::cout << "Testing whether the parametic bounds of VtkAbstractTransformPlaneGeometry and the bounds of the plane " + std::cout << "Testing whether the parametric bounds of VtkAbstractTransformPlaneGeometry and the bounds of the plane " "accessed from there are equal: "; if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; - std::cout << "Change parametic bounds of VtkAbstractTransformPlaneGeometry and test whether they are equal to the " + std::cout << "Change parametric bounds of VtkAbstractTransformPlaneGeometry and test whether they are equal to the " "bounds of the plane accessed from there: " << std::endl; height = 300; bounds[3] = height; abstractgeometry->SetParametricBounds(bounds); if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Initializing an phi-/theta-plane (sphereParameterPlane) as parameter plane by " "InitializeStandardPlane(rightVector, downVector, spacing = nullptr): " << std::endl; mitk::PlaneGeometry::Pointer sphereParameterPlane = mitk::PlaneGeometry::New(); width = 100; widthInMM = 2 * vnl_math::pi; height = 200; heightInMM = vnl_math::pi; mitk::ScalarType radiusInMM = 2.5; mitk::FillVector3D(origin, radiusInMM, 0, widthInMM); mitk::FillVector3D(right, 0, 0, -widthInMM); mitk::FillVector3D(bottom, 0, heightInMM, 0); sphereParameterPlane->InitializeStandardPlane(right, bottom); sphereParameterPlane->SetOrigin(origin); sphereParameterPlane->SetSizeInUnits(width, height); std::cout << "Creating an vtkSphericalTransform (sphericalTransform) to use with sphereParameterPlane: " << std::endl; vtkSphericalTransform *sphericalTransform = vtkSphericalTransform::New(); std::cout << "Setting sphereParameterPlane as parameter plane and sphericalTransform as transform of " "VtkAbstractTransformPlaneGeometry: " << std::endl; abstractgeometry->SetPlane(sphereParameterPlane); abstractgeometry->SetVtkAbstractTransform(sphericalTransform); std::cout << "Testing whether the bounds of sphereParameterPlane and the parametric bounds of " "VtkAbstractTransformPlaneGeometry are equal: "; if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(sphereParameterPlane->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(sphereParameterPlane->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; - std::cout << "Testing whether the parametic bounds of VtkAbstractTransformPlaneGeometry and the bounds of the plane " + std::cout << "Testing whether the parametric bounds of VtkAbstractTransformPlaneGeometry and the bounds of the plane " "accessed from there are equal: "; if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mapping Map(pt2d_mm(phi=Pi,theta=Pi/2.0), pt3d_mm) and compare with expected (-radius, 0, 0): "; mitk::Point2D pt2d_mm; mitk::Point3D pt3d_mm, expected_pt3d_mm; pt2d_mm[0] = vnl_math::pi; pt2d_mm[1] = vnl_math::pi_over_2; mitk::FillVector3D(expected_pt3d_mm, -radiusInMM, 0, 0); abstractgeometry->Map(pt2d_mm, pt3d_mm); if (mitk::Equal(pt3d_mm, expected_pt3d_mm) == false) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mapping Map(pt3d_mm, pt2d_mm) and compare with expected: "; mitk::Point2D testpt2d_mm; abstractgeometry->Map(pt3d_mm, testpt2d_mm); if (mitk::Equal(pt2d_mm, testpt2d_mm) == false) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing IndexToWorld(pt2d_units, pt2d_mm) and compare with expected: "; mitk::Point2D pt2d_units; pt2d_units[0] = width / 2.0; pt2d_units[1] = height / 2.0; pt2d_mm[0] = widthInMM / 2.0; pt2d_mm[1] = heightInMM / 2.0; abstractgeometry->IndexToWorld(pt2d_units, testpt2d_mm); if (mitk::Equal(pt2d_mm, testpt2d_mm) == false) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; - std::cout << "Change parametic bounds of VtkAbstractTransformPlaneGeometry and test whether they are equal to the " + std::cout << "Change parametric bounds of VtkAbstractTransformPlaneGeometry and test whether they are equal to the " "bounds of the plane accessed from there: " << std::endl; height = 300; bounds[3] = height; abstractgeometry->SetParametricBounds(bounds); if ((mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMinimum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMinimum()) == false) || (mitk::Equal(const_cast(abstractgeometry->GetParametricBoundingBox())->GetMaximum(), const_cast(abstractgeometry->GetPlane()->GetBoundingBox())->GetMaximum()) == false)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing IndexToWorld(pt2d_units, pt2d_mm) and compare with expected: "; pt2d_units[0] = width / 2.0; pt2d_units[1] = height / 2.0; pt2d_mm[0] = widthInMM / 2.0; pt2d_mm[1] = heightInMM / 2.0; abstractgeometry->IndexToWorld(pt2d_units, testpt2d_mm); if (mitk::Equal(pt2d_mm, testpt2d_mm) == false) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; // std::cout << "Testing availability and type (PlaneGeometry) of first geometry in the SlicedGeometry3D: "; // mitk::PlaneGeometry* accessedplanegeometry3 = // dynamic_cast(slicedWorldGeometry->GetGeometry2D(0)); // if(accessedplanegeometry3==nullptr) //{ // std::cout<<"[FAILED]"<GetAxisVector(0), planegeometry3->GetAxisVector(0))==false) || // (mitk::Equal(accessedplanegeometry3->GetAxisVector(1), planegeometry3->GetAxisVector(1))==false) || // (mitk::Equal(accessedplanegeometry3->GetAxisVector(2), planegeometry3->GetAxisVector(2))==false)) //{ // std::cout<<"[FAILED]"<SetElement(i, j, i + j * j); // just some not trivial value // set the expected homogenous matrix result expectedHomogenousMatrix = vtkMatrix4x4::New(); expectedHomogenousMatrix->Zero(); expectedHomogenousMatrix->SetElement(0, 1, -1); expectedHomogenousMatrix->SetElement(1, 0, 1); expectedHomogenousMatrix->SetElement(0, 3, 2); expectedHomogenousMatrix->SetElement(1, 3, 3); expectedHomogenousMatrix->SetElement(2, 3, 4); expectedHomogenousMatrix->SetElement(3, 3, 1); } static void TearDown() { if (homogenMatrix) homogenMatrix->Delete(); if (expectedHomogenousMatrix) expectedHomogenousMatrix->Delete(); } /** * This first test basically assures that we understand the usage of AffineTransform3D correct. * Meaning that the rotation is set by SetMatrix and the translation is set by SetOffset */ static void testIfPointIsTransformedAsExpected(void) { Setup(); /** construct the transformation */ AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); /** Let a point be transformed by the AffineTransform3D */ Point3D pointTransformedByAffineTransform3D = transform->TransformPoint(originalPoint); /** assert that the transformation was successful */ bool pointCorrect = true; for (int i = 0; i < 3; i++) // only first three since no homogenous coordinates pointCorrect &= Equal(pointTransformedByAffineTransform3D[i], expectedPointAfterTransformation[i]); - MITK_TEST_CONDITION(pointCorrect, "Point has been correctly transformed by AffineTranform3D") + MITK_TEST_CONDITION(pointCorrect, "Point has been correctly transformed by AffineTransform3D") TearDown(); } /** * This test ensures that the function TransferItkTransformToVtkMatrix translates the AffineTransform3D * correctly to a VtkMatrix4x4 */ static void testTransferItkTransformToVtkMatrix(void) { Setup(); AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); bool allElementsEqual = true; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) allElementsEqual &= Equal(homogenMatrix->GetElement(i, j), expectedHomogenousMatrix->GetElement(i, j)); MITK_TEST_CONDITION(allElementsEqual, "Homogenous Matrix is set as expected") TearDown(); } /** * This test basically is just a sanity check and should be PASSED exactly when both * testTransferItkTransformToVtkMatrix and testIfPointIsTransformedAsExpected are PASSED. * Tests if we get the same * result by using the AffineTransform3D to transform a point or the vtkMatrix4x4 which we got by applying * the TransferItkTransformToVtkMatrix function. This test e.g. ensures we made no mistake in our * reference results. * */ static void testIfBothTransformationsProduceSameResults(void) { Setup(); /** * create both a AffineTransform3D * and let this AffineTransform describe also a homogenous 4x4 Matrix vtkMatrix * by using our transfer method */ AffineTransform3D::Pointer transform = AffineTransform3D::New(); transform->SetOffset(offset); transform->SetMatrix(rotation); TransferItkTransformToVtkMatrix(transform.GetPointer(), homogenMatrix); /** Let a point be transformed by the AffineTransform3D and by homogenMatrix */ Point3D pointTransformedByAffineTransform3D = transform->TransformPoint(originalPoint); double *pointTransformedByHomogenous = homogenMatrix->MultiplyDoublePoint(originalPointDouble); /* check if results match */ bool pointsMatch = true; for (int i = 0; i < 3; i++) // only first three since no homogenous coordinates pointsMatch &= Equal(pointTransformedByAffineTransform3D[i], pointTransformedByHomogenous[i]); bool homogenousComponentCorrect = Equal(1, pointTransformedByHomogenous[3]); MITK_TEST_CONDITION(pointsMatch && homogenousComponentCorrect, "Point transformed by AffineTransform and homogenous coordinates match") TearDown(); } /** * This test shall ensure and document the basic functionality of the * itk AffineTransformation functionality and test some basic transformation functionalities provided by mitk. */ int mitkAffineTransformBaseTest(int /*argc*/, char * /*argv*/ []) { MITK_TEST_BEGIN("AffineTransformationBaseTest"); testIfPointIsTransformedAsExpected(); testTransferItkTransformToVtkMatrix(); testIfBothTransformationsProduceSameResults(); MITK_TEST_END(); } diff --git a/Modules/Core/test/mitkArbitraryTimeGeometryTest.cpp b/Modules/Core/test/mitkArbitraryTimeGeometryTest.cpp index 68f3ed89c5..fa2987808b 100644 --- a/Modules/Core/test/mitkArbitraryTimeGeometryTest.cpp +++ b/Modules/Core/test/mitkArbitraryTimeGeometryTest.cpp @@ -1,531 +1,531 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkArbitraryTimeGeometry.h" #include "mitkGeometry3D.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include class mitkArbitraryTimeGeometryTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkArbitraryTimeGeometryTestSuite); // Test the append method MITK_TEST(CountTimeSteps); MITK_TEST(GetMinimumTimePoint); MITK_TEST(GetMaximumTimePoint); MITK_TEST(GetTimeBounds); MITK_TEST(IsValidTimePoint); MITK_TEST(TimeStepToTimePoint); MITK_TEST(TimePointToTimeStep); MITK_TEST(GetGeometryCloneForTimeStep); MITK_TEST(GetGeometryForTimeStep); MITK_TEST(GetGeometryForTimePoint); MITK_TEST(IsValid); MITK_TEST(Expand); MITK_TEST(ReplaceTimeStepGeometries); MITK_TEST(ClearAllGeometries); MITK_TEST(AppendNewTimeStep); MITK_TEST(HasCollapsedFinalTimeStep); CPPUNIT_TEST_SUITE_END(); private: mitk::Geometry3D::Pointer m_Geometry1; mitk::Geometry3D::Pointer m_Geometry2; mitk::Geometry3D::Pointer m_Geometry3; mitk::Geometry3D::Pointer m_Geometry3_5; mitk::Geometry3D::Pointer m_Geometry4; mitk::Geometry3D::Pointer m_Geometry5; mitk::Geometry3D::Pointer m_InvalidGeometry; mitk::Geometry3D::Pointer m_NewGeometry; mitk::TimePointType m_Geometry1MinTP; mitk::TimePointType m_Geometry2MinTP; mitk::TimePointType m_Geometry3MinTP; mitk::TimePointType m_Geometry3_5MinTP; mitk::TimePointType m_Geometry4MinTP; mitk::TimePointType m_Geometry5MinTP; mitk::TimePointType m_NewGeometryMinTP; mitk::TimePointType m_Geometry1MaxTP; mitk::TimePointType m_Geometry2MaxTP; mitk::TimePointType m_Geometry3MaxTP; mitk::TimePointType m_Geometry3_5MaxTP; mitk::TimePointType m_Geometry4MaxTP; mitk::TimePointType m_Geometry5MaxTP; mitk::TimePointType m_NewGeometryMaxTP; mitk::ArbitraryTimeGeometry::Pointer m_emptyTimeGeometry; mitk::ArbitraryTimeGeometry::Pointer m_initTimeGeometry; mitk::ArbitraryTimeGeometry::Pointer m_12345TimeGeometry; mitk::ArbitraryTimeGeometry::Pointer m_123TimeGeometry; mitk::ArbitraryTimeGeometry::Pointer m_123TimeGeometryWithCollapsedEnd; mitk::ArbitraryTimeGeometry::Pointer m_123TimeGeometryWithCollapsedInterim; public: void setUp() override { m_Geometry1 = mitk::Geometry3D::New(); m_Geometry2 = mitk::Geometry3D::New(); m_Geometry3 = mitk::Geometry3D::New(); m_Geometry3_5 = mitk::Geometry3D::New(); m_Geometry4 = mitk::Geometry3D::New(); m_Geometry5 = mitk::Geometry3D::New(); m_Geometry1MinTP = 1; m_Geometry2MinTP = 2; m_Geometry3MinTP = 3; m_Geometry3_5MinTP = 3.5; m_Geometry4MinTP = 4; m_Geometry5MinTP = 5; m_Geometry1MaxTP = 1.9; m_Geometry2MaxTP = 2.9; m_Geometry3MaxTP = 3.9; m_Geometry3_5MaxTP = 3.9; m_Geometry4MaxTP = 4.9; m_Geometry5MaxTP = 5.9; m_NewGeometry = mitk::Geometry3D::New(); m_NewGeometryMinTP = 20; m_NewGeometryMaxTP = 21.9; mitk::Point3D origin(42); m_NewGeometry->SetOrigin(origin); m_emptyTimeGeometry = mitk::ArbitraryTimeGeometry::New(); m_emptyTimeGeometry->ClearAllGeometries(); m_initTimeGeometry = mitk::ArbitraryTimeGeometry::New(); m_initTimeGeometry->Initialize(); m_12345TimeGeometry = mitk::ArbitraryTimeGeometry::New(); m_12345TimeGeometry->ClearAllGeometries(); m_12345TimeGeometry->AppendNewTimeStep(m_Geometry1, m_Geometry1MinTP, m_Geometry1MaxTP); m_12345TimeGeometry->AppendNewTimeStep(m_Geometry2, m_Geometry2MinTP, m_Geometry2MaxTP); m_12345TimeGeometry->AppendNewTimeStep(m_Geometry3, m_Geometry3MinTP, m_Geometry3MaxTP); m_12345TimeGeometry->AppendNewTimeStep(m_Geometry4, m_Geometry4MinTP, m_Geometry4MaxTP); m_12345TimeGeometry->AppendNewTimeStep(m_Geometry5, m_Geometry5MinTP, m_Geometry5MaxTP); m_123TimeGeometry = mitk::ArbitraryTimeGeometry::New(); m_123TimeGeometry->ClearAllGeometries(); m_123TimeGeometry->AppendNewTimeStep(m_Geometry1, m_Geometry1MinTP, m_Geometry1MaxTP); m_123TimeGeometry->AppendNewTimeStep(m_Geometry2, m_Geometry2MinTP, m_Geometry2MaxTP); m_123TimeGeometry->AppendNewTimeStep(m_Geometry3, m_Geometry3MinTP, m_Geometry3MaxTP); m_123TimeGeometryWithCollapsedEnd = mitk::ArbitraryTimeGeometry::New(); m_123TimeGeometryWithCollapsedEnd->ClearAllGeometries(); m_123TimeGeometryWithCollapsedEnd->AppendNewTimeStep(m_Geometry1, m_Geometry1MinTP, m_Geometry1MaxTP); m_123TimeGeometryWithCollapsedEnd->AppendNewTimeStep(m_Geometry2, m_Geometry2MinTP, m_Geometry2MaxTP); m_123TimeGeometryWithCollapsedEnd->AppendNewTimeStep(m_Geometry3, m_Geometry3MinTP, m_Geometry3MinTP); m_123TimeGeometryWithCollapsedInterim = mitk::ArbitraryTimeGeometry::New(); m_123TimeGeometryWithCollapsedInterim->ClearAllGeometries(); m_123TimeGeometryWithCollapsedInterim->AppendNewTimeStep(m_Geometry1, m_Geometry1MinTP, m_Geometry1MaxTP); m_123TimeGeometryWithCollapsedInterim->AppendNewTimeStep(m_Geometry2, m_Geometry2MinTP, m_Geometry2MinTP); m_123TimeGeometryWithCollapsedInterim->AppendNewTimeStep(m_Geometry3, m_Geometry3MinTP, m_Geometry3MaxTP); } void tearDown() override {} void CountTimeSteps() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->CountTimeSteps() == 0, "Testing CountTimeSteps with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->CountTimeSteps() == 1, "Testing CountTimeSteps with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->CountTimeSteps() == 5, "Testing CountTimeSteps with m_12345TimeGeometry"); } void GetMinimumTimePoint() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetMinimumTimePoint() == 0.0, "Testing GetMinimumTimePoint with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetMinimumTimePoint() == 0.0, "Testing GetMinimumTimePoint with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetMinimumTimePoint() == 1.0, "Testing GetMinimumTimePoint with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetMinimumTimePoint(2) == 0.0, "Testing GetMinimumTimePoint(2) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetMinimumTimePoint(2) == 0.0, "Testing GetMinimumTimePoint(2) with m_initTimeGeometry"); /////////////////////////////////////// - // Workarround T27883. See https://phabricator.mitk.org/T27883#219473 for more details. - // This workarround should be removed/reevaluated as soon as T28262 is solved and we know + // Workaround T27883. See https://phabricator.mitk.org/T27883#219473 for more details. + // This workaround should be removed/reevaluated as soon as T28262 is solved and we know // how time geometries should behave in the future! MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetMinimumTimePoint(2) == 3.0, "Testing GetMinimumTimePoint(2) with m_12345TimeGeometry"); // Deactivated falling original test // MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetMinimumTimePoint(2) == 2.9, // "Testing GetMinimumTimePoint(2) with m_12345TimeGeometry"); - // End of workarround for T27883 + // End of workaround for T27883 ////////////////////////////////////// } void GetMaximumTimePoint() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetMaximumTimePoint() == 0.0, "Testing GetMaximumTimePoint with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetMaximumTimePoint() == 1.0, "Testing GetMaximumTimePoint with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetMaximumTimePoint() == 5.9, "Testing GetMaximumTimePoint with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetMaximumTimePoint(2) == 0.0, "Testing GetMaximumTimePoint(2) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetMaximumTimePoint(2) == 0.0, "Testing GetMaximumTimePoint(2) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetMaximumTimePoint(2) == 3.9, "Testing GetMaximumTimePoint(2) with m_12345TimeGeometry"); } void GetTimeBounds() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetMaximumTimePoint(2) == 0.0, "Testing GetMaximumTimePoint(2) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetMaximumTimePoint(2) == 0.0, "Testing GetMaximumTimePoint(2) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetMaximumTimePoint(2) == 3.9, "Testing GetMaximumTimePoint(2) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetTimeBounds()[0] == 0.0, "Testing GetTimeBounds lower part with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetTimeBounds()[0] == 0.0, "Testing GetTimeBounds lower part with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetTimeBounds()[0] == 1.0, "Testing GetTimeBounds lower part with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetTimeBounds()[1] == 0.0, "Testing GetTimeBounds with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetTimeBounds()[1] == 1.0, "Testing GetTimeBounds with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetTimeBounds()[1] == 5.9, "Testing GetTimeBounds with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetTimeBounds(3)[0] == 0.0, "Testing GetTimeBounds(3) lower part with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetTimeBounds(3)[0] == 0.0, "Testing GetTimeBounds(3) lower part with m_initTimeGeometry"); /////////////////////////////////////// - // Workarround T27883. See https://phabricator.mitk.org/T27883#219473 for more details. - // This workarround should be removed/reevaluated as soon as T28262 is solved and we know + // Workaround T27883. See https://phabricator.mitk.org/T27883#219473 for more details. + // This workaround should be removed/reevaluated as soon as T28262 is solved and we know // how time geometries should behave in the future! MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetTimeBounds(3)[0] == 4.0, "Testing GetTimeBounds(3) lower part with m_12345TimeGeometry"); // Deactivated falling original test // MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetTimeBounds(3)[0] == 3.9, // "Testing GetTimeBounds(3) lower part with m_12345TimeGeometry"); - // End of workarround for T27883 + // End of workaround for T27883 ////////////////////////////////////// MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetTimeBounds(3)[1] == 0.0, "Testing GetTimeBounds(3) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetTimeBounds(3)[1] == 0.0, "Testing GetTimeBounds(3) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetTimeBounds(3)[1] == 4.9, "Testing GetTimeBounds(3) with m_12345TimeGeometry"); } void IsValidTimePoint() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimePoint(-1) == false, "Testing IsValidTimePoint(-1) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimePoint(-1) == false, "Testing IsValidTimePoint(-1) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimePoint(-1) == false, "Testing IsValidTimePoint(-1) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimePoint(0) == false, "Testing IsValidTimePoint(0) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimePoint(0) == true, "Testing IsValidTimePoint(0) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimePoint(0) == false, "Testing IsValidTimePoint(0) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimePoint(1) == false, "Testing IsValidTimePoint(1) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimePoint(1) == false, "Testing IsValidTimePoint(1) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimePoint(1) == true, "Testing IsValidTimePoint(1) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimePoint(2.5) == false, "Testing IsValidTimePoint(2.5) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimePoint(2.5) == false, "Testing IsValidTimePoint(2.5) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimePoint(2.5) == true, "Testing IsValidTimePoint(2.5) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimePoint(5.89) == false, "Testing IsValidTimePoint(5.89) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimePoint(5.89) == false, "Testing IsValidTimePoint(5.89) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimePoint(5.89) == true, "Testing IsValidTimePoint(5.89) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimePoint(10) == false, "Testing IsValidTimePoint(10) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimePoint(10) == false, "Testing IsValidTimePoint(10) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimePoint(10) == false, "Testing IsValidTimePoint(10) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimeStep(0) == false, "Testing IsValidTimeStep(0) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimeStep(0) == true, "Testing IsValidTimeStep(0) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimeStep(0) == true, "Testing IsValidTimeStep(0) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimeStep(1) == false, "Testing IsValidTimeStep(1) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimeStep(1) == false, "Testing IsValidTimeStep(1) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimeStep(1) == true, "Testing IsValidTimeStep(1) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValidTimeStep(6) == false, "Testing IsValidTimeStep(6) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValidTimeStep(6) == false, "Testing IsValidTimeStep(6) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValidTimeStep(6) == false, "Testing IsValidTimeStep(6) with m_12345TimeGeometry"); //checked collapsed cases MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometryWithCollapsedInterim->IsValidTimePoint(m_123TimeGeometryWithCollapsedInterim->GetMaximumTimePoint()) == false, - "Testing that m_123TimeGeometryWithCollapsedInterim does not inclued the max bound in validity"); + "Testing that m_123TimeGeometryWithCollapsedInterim does not included the max bound in validity"); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometryWithCollapsedEnd->IsValidTimePoint(m_123TimeGeometryWithCollapsedEnd->GetMaximumTimePoint()) == true, - "Testing that m_123TimeGeometryWithCollapsedEnd does inclued the max bound in validity, because it has an collapsed final time step. (see also T27259)"); + "Testing that m_123TimeGeometryWithCollapsedEnd does included the max bound in validity, because it has an collapsed final time step. (see also T27259)"); } void TimeStepToTimePoint() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->TimeStepToTimePoint(0) == 0.0, "Testing TimeStepToTimePoint(0) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->TimeStepToTimePoint(0) == 0.0, "Testing TimeStepToTimePoint(0) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->TimeStepToTimePoint(0) == 1.0, "Testing TimeStepToTimePoint(0) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->TimeStepToTimePoint(1) == 0.0, "Testing TimeStepToTimePoint(1) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->TimeStepToTimePoint(1) == 0.0, "Testing TimeStepToTimePoint(1) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->TimeStepToTimePoint(1) == 2.0, "Testing TimeStepToTimePoint(1) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->TimeStepToTimePoint(6) == 0.0, "Testing TimeStepToTimePoint(6) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->TimeStepToTimePoint(6) == 0.0, "Testing TimeStepToTimePoint(6) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->TimeStepToTimePoint(6) == 0.0, "Testing TimeStepToTimePoint(6) with m_12345TimeGeometry"); } void TimePointToTimeStep() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->TimePointToTimeStep(0.0) == 0, "Testing TimePointToTimeStep(0.0) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->TimePointToTimeStep(0.0) == 0, "Testing TimePointToTimeStep(0.0) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->TimePointToTimeStep(0.0) == 0, "Testing TimePointToTimeStep(0.0) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->TimePointToTimeStep(0.5) == 0, "Testing TimePointToTimeStep(0.5) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->TimePointToTimeStep(0.5) == 0, "Testing TimePointToTimeStep(0.5) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->TimePointToTimeStep(0.5) == 0, "Testing TimePointToTimeStep(0.5) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->TimePointToTimeStep(3.5) == 0, "Testing TimePointToTimeStep(3.5) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->TimePointToTimeStep(3.5) == m_initTimeGeometry->CountTimeSteps(), "Testing TimePointToTimeStep(3.5) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->TimePointToTimeStep(3.5) == 2, "Testing TimePointToTimeStep(3.5) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->TimePointToTimeStep(5.8) == 0, "Testing TimePointToTimeStep(5.8) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->TimePointToTimeStep(5.8) == m_initTimeGeometry->CountTimeSteps(), "Testing TimePointToTimeStep(5.8) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->TimePointToTimeStep(5.8) == 4, "Testing TimePointToTimeStep(5.8) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->TimePointToTimeStep(5.9) == m_12345TimeGeometry->CountTimeSteps(), "Testing TimePointToTimeStep(5.9) with m_12345TimeGeometry"); //checked collapsed cases MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometryWithCollapsedInterim->TimePointToTimeStep(m_123TimeGeometryWithCollapsedInterim->GetMaximumTimePoint()) == m_123TimeGeometryWithCollapsedInterim->CountTimeSteps(), - "Testing m_123TimeGeometryWithCollapsedInterim does not map the max time poit."); + "Testing m_123TimeGeometryWithCollapsedInterim does not map the max time point."); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometryWithCollapsedEnd->TimePointToTimeStep(m_123TimeGeometryWithCollapsedEnd->GetMaximumTimePoint()) == 2, "Testing that m_123TimeGeometryWithCollapsedEnd does map the max bound, because it has an collapsed final time step. (see also T27259)"); } void GetGeometryCloneForTimeStep() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetGeometryCloneForTimeStep(0).IsNull(), "Testing GetGeometryCloneForTimeStep(0) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetGeometryCloneForTimeStep(0).IsNotNull(), "Testing GetGeometryCloneForTimeStep(0) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetGeometryCloneForTimeStep(0).IsNotNull(), "Testing GetGeometryCloneForTimeStep(0) with m_12345TimeGeometry"); } void GetGeometryForTimeStep() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetGeometryForTimeStep(0).IsNull(), "Testing GetGeometryForTimePoint(0) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetGeometryForTimeStep(0).IsNotNull(), "Testing GetGeometryForTimePoint(0) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetGeometryForTimeStep(1).IsNull(), "Testing GetGeometryForTimePoint(1) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED( m_12345TimeGeometry->GetGeometryForTimeStep(0).GetPointer() == m_Geometry1.GetPointer(), "Testing GetGeometryForTimePoint(0) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED( m_12345TimeGeometry->GetGeometryForTimeStep(3).GetPointer() == m_Geometry4.GetPointer(), "Testing GetGeometryForTimePoint(3) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED( m_12345TimeGeometry->GetGeometryForTimeStep(4).GetPointer() == m_Geometry5.GetPointer(), "Testing GetGeometryForTimePoint(4) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetGeometryForTimeStep(5).IsNull(), "Testing GetGeometryForTimePoint(5) with m_12345TimeGeometry"); } void GetGeometryForTimePoint() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetGeometryForTimePoint(0).IsNull(), "Testing GetGeometryForTimeStep(0) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetGeometryForTimePoint(0).IsNotNull(), "Testing GetGeometryForTimeStep(0) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetGeometryForTimePoint(0).IsNull(), "Testing GetGeometryForTimeStep(0) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetGeometryForTimePoint(1.5).IsNull(), "Testing GetGeometryForTimeStep(1.5) with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->GetGeometryForTimePoint(1.5).IsNull(), "Testing GetGeometryForTimeStep(1.5) with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED( m_12345TimeGeometry->GetGeometryForTimePoint(1.5).GetPointer() == m_Geometry1.GetPointer(), "Testing GetGeometryForTimeStep(1.5) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED( m_12345TimeGeometry->GetGeometryForTimePoint(3.5).GetPointer() == m_Geometry3.GetPointer(), "Testing GetGeometryForTimeStep(3.5) with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetGeometryForTimePoint(5.9).IsNull(), "Testing GetGeometryForTimeStep(5.9) with m_12345TimeGeometry"); } void IsValid() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->IsValid() == false, "Testing IsValid() with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->IsValid() == true, "Testing IsValid() with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->IsValid() == true, "Testing IsValid() with m_12345TimeGeometry"); } void Expand() { m_12345TimeGeometry->Expand(3); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->CountTimeSteps() == 5, "Testing Expand(3) doesn't change m_12345TimeGeometry"); m_12345TimeGeometry->Expand(7); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->CountTimeSteps() == 7, "Testing Expand(7) with m_12345TimeGeometry"); } void ReplaceTimeStepGeometries() { // Test replace time step geometries m_12345TimeGeometry->ReplaceTimeStepGeometries(m_NewGeometry); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->CountTimeSteps() == 5, "Testing ReplaceTimeStepGeometries() with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED( m_12345TimeGeometry->GetGeometryForTimeStep(0)->GetOrigin() == m_NewGeometry->GetOrigin(), "Testing ReplaceTimeStepGeometries(): check if first geometry of m_12345TimeGeometry " "was replaced m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED( m_12345TimeGeometry->GetGeometryForTimeStep(4)->GetOrigin() == m_NewGeometry->GetOrigin(), "Testing ReplaceTimeStepGeometries(): check if last geometry of m_12345TimeGeometry " "was replaced m_12345TimeGeometry"); } void ClearAllGeometries() { // Test clear all geometries m_12345TimeGeometry->ClearAllGeometries(); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->CountTimeSteps() == 0, "Testing ClearAllGeometries() with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetMinimumTimePoint() == 0, "Testing ClearAllGeometries() with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->GetMaximumTimePoint() == 0, "Testing ClearAllGeometries() with m_12345TimeGeometry"); } void AppendNewTimeStep() { // Test append MITK_TEST_FOR_EXCEPTION(mitk::Exception, m_123TimeGeometry->AppendNewTimeStep(nullptr, 0, 1)); MITK_TEST_FOR_EXCEPTION(mitk::Exception, m_123TimeGeometry->AppendNewTimeStep(m_Geometry3_5,m_Geometry3_5MinTP,m_Geometry3_5MaxTP)); MITK_TEST_FOR_EXCEPTION(mitk::Exception, m_123TimeGeometry->AppendNewTimeStep(m_Geometry4, m_Geometry4MaxTP, m_Geometry4MinTP)); //valid but inverted bounds m_emptyTimeGeometry->AppendNewTimeStep(m_Geometry4, m_Geometry4MinTP, m_Geometry4MaxTP); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->CountTimeSteps() == 1, "Testing AppendNewTimeStep() with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetMinimumTimePoint() == 4, "Testing ClearAllGeometries() with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->GetMaximumTimePoint() == 4.9, "Testing ClearAllGeometries() with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometry->CountTimeSteps() == 3, "Testing AppendNewTimeStep() with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometry->GetMinimumTimePoint() == 1, "Testing ClearAllGeometries() with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometry->GetMaximumTimePoint() == 3.9, "Testing ClearAllGeometries() with m_emptyTimeGeometry"); m_123TimeGeometry->AppendNewTimeStep(m_Geometry4, m_Geometry4MinTP, m_Geometry4MaxTP); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometry->CountTimeSteps() == 4, "Testing AppendNewTimeStep() with m_123TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometry->GetMinimumTimePoint() == 1, "Testing AppendNewTimeStep() with m_123TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometry->GetMaximumTimePoint() == 4.9, "Testing AppendNewTimeStep() with m_123TimeGeometry"); /////////////////////////////////////// - // Workarround T27883. See https://phabricator.mitk.org/T27883#219473 for more details. - // This workarround should be removed/reevaluated as soon as T28262 is solved and we know + // Workaround T27883. See https://phabricator.mitk.org/T27883#219473 for more details. + // This workaround should be removed/reevaluated as soon as T28262 is solved and we know // how time geometries should behave in the future! MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometry->GetMinimumTimePoint(3) == 4.0, "Testing AppendNewTimeStep() with m_123TimeGeometry"); // Deactivated falling original test // MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometry->GetMinimumTimePoint(3) == 3.9, // "Testing AppendNewTimeStep() with m_123TimeGeometry"); - // End of workarround for T27883 + // End of workaround for T27883 ////////////////////////////////////// } void HasCollapsedFinalTimeStep() { MITK_TEST_CONDITION_REQUIRED(m_emptyTimeGeometry->HasCollapsedFinalTimeStep() == false, "Testing HasCollapsedFinalTimeStep() with m_emptyTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_initTimeGeometry->HasCollapsedFinalTimeStep() == false, "Testing HasCollapsedFinalTimeStep() with m_initTimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_12345TimeGeometry->HasCollapsedFinalTimeStep() == false, "Testing HasCollapsedFinalTimeStep() with m_12345TimeGeometry"); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometryWithCollapsedEnd->HasCollapsedFinalTimeStep() == true, "Testing HasCollapsedFinalTimeStep() with m_123TimeGeometryWithCollapsedEnd"); MITK_TEST_CONDITION_REQUIRED(m_123TimeGeometryWithCollapsedInterim->HasCollapsedFinalTimeStep() == false, "Testing HasCollapsedFinalTimeStep() with m_123TimeGeometryWithCollapsedInterim"); } }; MITK_TEST_SUITE_REGISTRATION(mitkArbitraryTimeGeometry) diff --git a/Modules/Core/test/mitkBaseGeometryTest.cpp b/Modules/Core/test/mitkBaseGeometryTest.cpp index b975f48661..dad9c06c3a 100644 --- a/Modules/Core/test/mitkBaseGeometryTest.cpp +++ b/Modules/Core/test/mitkBaseGeometryTest.cpp @@ -1,1680 +1,1680 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkTestingMacros.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class vtkMatrix4x4; class vtkMatrixToLinearTransform; class vtkLinearTransform; typedef itk::BoundingBox BoundingBox; typedef itk::BoundingBox BoundingBoxType; typedef BoundingBoxType::BoundsArrayType BoundsArrayType; typedef BoundingBoxType::Pointer BoundingBoxPointer; // Dummy instance of abstract base class class DummyTestClass : public mitk::BaseGeometry { public: DummyTestClass(){}; DummyTestClass(const DummyTestClass &other) : BaseGeometry(other){}; ~DummyTestClass() override{}; mitkClassMacro(DummyTestClass, mitk::BaseGeometry); itkNewMacro(Self); mitkNewMacro1Param(Self, const Self &); itk::LightObject::Pointer InternalClone() const override { Self::Pointer newGeometry = new Self(*this); newGeometry->UnRegister(); return newGeometry.GetPointer(); } protected: void PrintSelf(std::ostream & /*os*/, itk::Indent /*indent*/) const override{}; //##Documentation //## @brief Pre- and Post-functions are empty in BaseGeometry //## //## These virtual functions allow for a different beahiour in subclasses. //## Do implement them in every subclass of BaseGeometry. If not needed, use {}. //## If this class is inherited from a subclass of BaseGeometry, call {Superclass::Pre...();};, example: // SlicedGeometry3D class void PreSetSpacing(const mitk::Vector3D &/*aSpacing*/) override{}; }; class mitkBaseGeometryTestSuite : public mitk::TestFixture { // List of Tests CPPUNIT_TEST_SUITE(mitkBaseGeometryTestSuite); // Constructor MITK_TEST(TestConstructors); MITK_TEST(TestInitialize); // Set MITK_TEST(TestSetOrigin); MITK_TEST(TestSetBounds); MITK_TEST(TestSetFloatBounds); MITK_TEST(TestSetFloatBoundsDouble); MITK_TEST(TestSetFrameOfReferenceID); MITK_TEST(TestSetIndexToWorldTransform); MITK_TEST(TestSetIndexToWorldTransformWithoutChangingSpacing); MITK_TEST(TestSetIndexToWorldTransform_WithPointerToSameTransform); MITK_TEST(TestSetSpacing); MITK_TEST(TestTransferItkToVtkTransform); MITK_TEST(TestSetIndexToWorldTransformByVtkMatrix); MITK_TEST(TestSetIdentity); MITK_TEST(TestSetImageGeometry); // Equal MITK_TEST(Equal_CloneAndOriginal_ReturnsTrue); MITK_TEST(Equal_DifferentOrigin_ReturnsFalse); MITK_TEST(Equal_DifferentIndexToWorldTransform_ReturnsFalse); MITK_TEST(Equal_DifferentSpacing_ReturnsFalse); MITK_TEST(Equal_InputIsNull_ReturnsFalse); MITK_TEST(Equal_DifferentBoundingBox_ReturnsFalse); MITK_TEST(Equal_Transforms_MinorDifferences_And_Eps); // other Functions MITK_TEST(TestComposeTransform); MITK_TEST(TestComposeVtkMatrix); MITK_TEST(TestTranslate); MITK_TEST(TestIndexToWorld); MITK_TEST(TestExecuteOperation); MITK_TEST(TestCalculateBoundingBoxRelToTransform); // MITK_TEST(TestSetTimeBounds); MITK_TEST(TestIs2DConvertable); MITK_TEST(TestGetCornerPoint); MITK_TEST(TestExtentInMM); MITK_TEST(TestGetAxisVector); MITK_TEST(TestGetCenter); MITK_TEST(TestGetDiagonalLength); MITK_TEST(TestGetExtent); MITK_TEST(TestIsInside); MITK_TEST(TestGetMatrixColumn); // test IsSubGeometry MITK_TEST(IsSubGeometry_Spacing); MITK_TEST(IsSubGeometry_TransformMatrix); MITK_TEST(IsSubGeometry_Bounds_Image); MITK_TEST(IsSubGeometry_Bounds_NoneImage); MITK_TEST(IsSubGeometry_Grid_Image); MITK_TEST(IsSubGeometry_Grid_NoneImage); MITK_TEST(IsSubGeometry_Bounds_Oblique_Image); MITK_TEST(IsSubGeometry_Bounds_Oblique_NoneImage); MITK_TEST(IsSubGeometry_Grid_Oblique_Image); MITK_TEST(IsSubGeometry_Grid_Oblique_NoneImage); CPPUNIT_TEST_SUITE_END(); // Used Variables private: mitk::Point3D aPoint; float aFloatSpacing[3]; mitk::Vector3D aSpacing; mitk::AffineTransform3D::Pointer aTransform; BoundingBoxPointer aBoundingBox; mitk::AffineTransform3D::MatrixType aMatrix; mitk::Point3D anotherPoint; mitk::Vector3D anotherSpacing; BoundingBoxPointer anotherBoundingBox; BoundingBoxPointer aThirdBoundingBox; mitk::AffineTransform3D::Pointer anotherTransform; mitk::AffineTransform3D::Pointer aThirdTransform; mitk::AffineTransform3D::MatrixType anotherMatrix; mitk::AffineTransform3D::MatrixType aThirdMatrix; DummyTestClass::Pointer aDummyGeometry; DummyTestClass::Pointer anotherDummyGeometry; DummyTestClass::Pointer aDummyGeometryOblique; public: // Set up for variables void setUp() override { mitk::FillVector3D(aFloatSpacing, 1, 1, 1); mitk::FillVector3D(aSpacing, 1, 1, 1); mitk::FillVector3D(aPoint, 0, 0, 0); // Transform aTransform = mitk::AffineTransform3D::New(); aTransform->SetIdentity(); aMatrix.SetIdentity(); anotherTransform = mitk::AffineTransform3D::New(); anotherMatrix.SetIdentity(); anotherMatrix(1, 1) = 2; anotherTransform->SetMatrix(anotherMatrix); aThirdTransform = mitk::AffineTransform3D::New(); aThirdMatrix.SetIdentity(); aThirdMatrix(1, 1) = 7; aThirdTransform->SetMatrix(aThirdMatrix); // Bounding Box float bounds[6] = { 0, 1, 0, 1, 0, 1 }; mitk::BoundingBox::BoundsArrayType b; const float* input = bounds; int j = 0; for (mitk::BoundingBox::BoundsArrayType::Iterator it = b.Begin(); j < 6; ++j) *it++ = (mitk::ScalarType) * input++; aBoundingBox = BoundingBoxType::New(); BoundingBoxType::PointsContainer::Pointer pointscontainer = BoundingBoxType::PointsContainer::New(); BoundingBoxType::PointType p; BoundingBoxType::PointIdentifier pointid; for (pointid = 0; pointid < 2; ++pointid) { unsigned int i; for (i = 0; i < 3; ++i) { p[i] = bounds[2 * i + pointid]; } pointscontainer->InsertElement(pointid, p); } aBoundingBox->SetPoints(pointscontainer); aBoundingBox->ComputeBoundingBox(); anotherBoundingBox = BoundingBoxType::New(); p[0] = 11; p[1] = 12; p[2] = 13; pointscontainer->InsertElement(1, p); anotherBoundingBox->SetPoints(pointscontainer); anotherBoundingBox->ComputeBoundingBox(); aThirdBoundingBox = BoundingBoxType::New(); p[0] = 22; p[1] = 23; p[2] = 24; pointscontainer->InsertElement(1, p); aThirdBoundingBox->SetPoints(pointscontainer); aThirdBoundingBox->ComputeBoundingBox(); mitk::FillVector3D(anotherPoint, 2, 3, 4); mitk::FillVector3D(anotherSpacing, 5, 6.5, 7); aDummyGeometry = DummyTestClass::New(); aDummyGeometry->Initialize(); anotherDummyGeometry = aDummyGeometry->Clone(); aDummyGeometryOblique = DummyTestClass::New(); aDummyGeometryOblique->Initialize(); auto newBounds = aDummyGeometryOblique->GetBounds(); newBounds[0] = 0; newBounds[1] = 5; newBounds[2] = 10; newBounds[3] = 20; newBounds[4] = 30; newBounds[5] = 40; aDummyGeometryOblique->SetBounds(newBounds); aDummyGeometryOblique->GetMatrixColumn(0); auto obliqueTransform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::OutputVectorType rotationAxis(0.); rotationAxis[1] = 1.; obliqueTransform->Rotate3D(rotationAxis, 0.6); mitk::AffineTransform3D::OutputVectorType translation; translation[0] = 100.; translation[1] = -50.; translation[2] = -150.; obliqueTransform->SetTranslation(translation); aDummyGeometryOblique->SetIndexToWorldTransform(obliqueTransform); } void tearDown() override { aDummyGeometry = nullptr; anotherDummyGeometry = nullptr; } // Test functions void TestSetOrigin() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetOrigin(anotherPoint); CPPUNIT_ASSERT(mitk::Equal(anotherPoint, dummy->GetOrigin())); // undo changes, new and changed object need to be the same! dummy->SetOrigin(aPoint); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "TestSetOrigin"); } void TestSetImageGeometry() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetImageGeometry(true); CPPUNIT_ASSERT(dummy->GetImageGeometry()); // undo changes, new and changed object need to be the same! dummy->SetImageGeometry(false); CPPUNIT_ASSERT(dummy->GetImageGeometry() == false); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "TestSetImageGeometry"); } void TestSetFloatBounds() { float bounds[6] = {0, 11, 0, 12, 0, 13}; DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetFloatBounds(bounds); MITK_ASSERT_EQUAL(BoundingBox::ConstPointer(dummy->GetBoundingBox()), anotherBoundingBox, "BoundingBox equality"); // Wrong bounds, test needs to fail bounds[1] = 7; dummy->SetFloatBounds(bounds); MITK_ASSERT_NOT_EQUAL( BoundingBox::ConstPointer(dummy->GetBoundingBox()), anotherBoundingBox, "BoundingBox not equal"); // undo changes, new and changed object need to be the same! float originalBounds[6] = {0, 1, 0, 1, 0, 1}; dummy->SetFloatBounds(originalBounds); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Undo and equal"); } void TestSetBounds() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetBounds(anotherBoundingBox->GetBounds()); MITK_ASSERT_EQUAL(BoundingBox::ConstPointer(dummy->GetBoundingBox()), anotherBoundingBox, "Setting bounds"); // Test needs to fail now dummy->SetBounds(aThirdBoundingBox->GetBounds()); MITK_ASSERT_NOT_EQUAL( BoundingBox::ConstPointer(dummy->GetBoundingBox()), anotherBoundingBox, "Setting unequal bounds"); // undo changes, new and changed object need to be the same! dummy->SetBounds(aBoundingBox->GetBounds()); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Undo set bounds"); } void TestSetFloatBoundsDouble() { double bounds[6] = {0, 11, 0, 12, 0, 13}; DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetFloatBounds(bounds); MITK_ASSERT_EQUAL(BoundingBox::ConstPointer(dummy->GetBoundingBox()), anotherBoundingBox, "Float bounds"); // Test needs to fail now bounds[3] = 7; dummy->SetFloatBounds(bounds); MITK_ASSERT_NOT_EQUAL( BoundingBox::ConstPointer(dummy->GetBoundingBox()), anotherBoundingBox, "Float bounds unequal"); // undo changes, new and changed object need to be the same! double originalBounds[6] = {0, 1, 0, 1, 0, 1}; dummy->SetFloatBounds(originalBounds); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Undo set float bounds"); } void TestSetFrameOfReferenceID() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetFrameOfReferenceID(5); CPPUNIT_ASSERT(dummy->GetFrameOfReferenceID() == 5); // undo changes, new and changed object need to be the same! dummy->SetFrameOfReferenceID(0); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Undo set frame of reference"); } void TestSetIndexToWorldTransform() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransform(anotherTransform); MITK_ASSERT_EQUAL(anotherTransform, mitk::AffineTransform3D::Pointer(dummy->GetIndexToWorldTransform()), "Compare IndexToWorldTransform 1"); // Test needs to fail now dummy->SetIndexToWorldTransform(aThirdTransform); MITK_ASSERT_NOT_EQUAL(anotherTransform, mitk::AffineTransform3D::Pointer(dummy->GetIndexToWorldTransform()), "Compare IndexToWorldTransform 2"); // undo changes, new and changed object need to be the same! dummy->SetIndexToWorldTransform(aTransform); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Compare IndexToWorldTransform 3"); } void TestSetIndexToWorldTransformWithoutChangingSpacing() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransformWithoutChangingSpacing(anotherTransform); CPPUNIT_ASSERT(mitk::Equal(aSpacing, dummy->GetSpacing(), mitk::eps, true)); // calculate a new version of anotherTransform, so that the spacing should be the same as the original spacing of // aTransform. mitk::AffineTransform3D::MatrixType::InternalMatrixType vnlmatrix; vnlmatrix = anotherTransform->GetMatrix().GetVnlMatrix(); mitk::VnlVector col; col = vnlmatrix.get_column(0).as_ref(); col.normalize(); col *= aSpacing[0]; vnlmatrix.set_column(0, col); col = vnlmatrix.get_column(1).as_ref(); col.normalize(); col *= aSpacing[1]; vnlmatrix.set_column(1, col); col = vnlmatrix.get_column(2).as_ref(); col.normalize(); col *= aSpacing[2]; vnlmatrix.set_column(2, col); mitk::Matrix3D matrix; matrix = vnlmatrix; anotherTransform->SetMatrix(matrix); CPPUNIT_ASSERT(mitk::Equal(*anotherTransform, *(dummy->GetIndexToWorldTransform()), mitk::eps, true)); } void TestSetIndexToWorldTransform_WithPointerToSameTransform() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetOrigin(anotherPoint); dummy->SetIndexToWorldTransform(anotherTransform); dummy->SetSpacing(anotherSpacing); mitk::AffineTransform3D::Pointer testTransfrom = dummy->GetIndexToWorldTransform(); mitk::Vector3D modifiedPoint = anotherPoint.GetVectorFromOrigin() * 2.; testTransfrom->SetOffset(modifiedPoint); dummy->SetIndexToWorldTransform(testTransfrom); CPPUNIT_ASSERT(mitk::Equal(modifiedPoint, dummy->GetOrigin().GetVectorFromOrigin())); } void TestSetIndexToWorldTransformByVtkMatrix() { vtkMatrix4x4 *vtkmatrix; vtkmatrix = vtkMatrix4x4::New(); vtkmatrix->Identity(); vtkmatrix->SetElement(1, 1, 2); DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransformByVtkMatrix(vtkmatrix); MITK_ASSERT_EQUAL(anotherTransform, mitk::AffineTransform3D::Pointer(dummy->GetIndexToWorldTransform()), "Compare IndexToWorldTransformByVtkMatrix 1"); // test needs to fail now vtkmatrix->SetElement(1, 1, 7); dummy->SetIndexToWorldTransformByVtkMatrix(vtkmatrix); MITK_ASSERT_NOT_EQUAL(anotherTransform, mitk::AffineTransform3D::Pointer(dummy->GetIndexToWorldTransform()), "Compare IndexToWorldTransformByVtkMatrix 2"); // undo changes, new and changed object need to be the same! vtkmatrix->SetElement(1, 1, 1); dummy->SetIndexToWorldTransformByVtkMatrix(vtkmatrix); vtkmatrix->Delete(); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Compare IndexToWorldTransformByVtkMatrix 3"); } void TestSetIdentity() { DummyTestClass::Pointer dummy = DummyTestClass::New(); // Change IndextoWorldTransform and Origin dummy->SetIndexToWorldTransform(anotherTransform); dummy->SetOrigin(anotherPoint); // Set Identity should reset ITWT and Origin dummy->SetIdentity(); MITK_ASSERT_EQUAL( aTransform, mitk::AffineTransform3D::Pointer(dummy->GetIndexToWorldTransform()), "Test set identity 1"); CPPUNIT_ASSERT(mitk::Equal(aPoint, dummy->GetOrigin())); CPPUNIT_ASSERT(mitk::Equal(aSpacing, dummy->GetSpacing())); // new and changed object need to be the same! DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Test set identity 2"); } void TestSetSpacing() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetSpacing(anotherSpacing); CPPUNIT_ASSERT(mitk::Equal(anotherSpacing, dummy->GetSpacing())); // undo changes, new and changed object need to be the same! dummy->SetSpacing(aSpacing); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Dummy spacing"); } void TestTransferItkToVtkTransform() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransform(anotherTransform); // calls TransferItkToVtkTransform mitk::AffineTransform3D::Pointer dummyTransform = dummy->GetIndexToWorldTransform(); CPPUNIT_ASSERT(mitk::MatrixEqualElementWise(anotherMatrix, dummyTransform->GetMatrix())); } void TestConstructors() { // test standard constructor DummyTestClass::Pointer dummy1 = DummyTestClass::New(); bool test = dummy1->IsValid(); CPPUNIT_ASSERT(test == true); CPPUNIT_ASSERT(dummy1->GetFrameOfReferenceID() == 0); CPPUNIT_ASSERT(dummy1->GetIndexToWorldTransformLastModified() == 0); CPPUNIT_ASSERT(mitk::Equal(dummy1->GetSpacing(), aSpacing)); CPPUNIT_ASSERT(mitk::Equal(dummy1->GetOrigin(), aPoint)); CPPUNIT_ASSERT(dummy1->GetImageGeometry() == false); MITK_ASSERT_EQUAL( - mitk::AffineTransform3D::Pointer(dummy1->GetIndexToWorldTransform()), aTransform, "Contructor test 1"); + mitk::AffineTransform3D::Pointer(dummy1->GetIndexToWorldTransform()), aTransform, "Constructor test 1"); MITK_ASSERT_EQUAL( mitk::BaseGeometry::BoundingBoxType::ConstPointer(dummy1->GetBoundingBox()), aBoundingBox, "Constructor test 2"); DummyTestClass::Pointer dummy2 = DummyTestClass::New(); dummy2->SetOrigin(anotherPoint); float bounds[6] = {0, 11, 0, 12, 0, 13}; dummy2->SetFloatBounds(bounds); dummy2->SetIndexToWorldTransform(anotherTransform); dummy2->SetSpacing(anotherSpacing); DummyTestClass::Pointer dummy3 = DummyTestClass::New(*dummy2); - MITK_ASSERT_EQUAL(dummy3, dummy2, "Dummy contructor"); + MITK_ASSERT_EQUAL(dummy3, dummy2, "Dummy constructor"); } // Equal Tests void Equal_CloneAndOriginal_ReturnsTrue() { MITK_ASSERT_EQUAL(aDummyGeometry, anotherDummyGeometry, "Clone test"); } void Equal_DifferentOrigin_ReturnsFalse() { anotherDummyGeometry->SetOrigin(anotherPoint); MITK_ASSERT_NOT_EQUAL(aDummyGeometry, anotherDummyGeometry, "Different origin test"); } void Equal_DifferentIndexToWorldTransform_ReturnsFalse() { anotherDummyGeometry->SetIndexToWorldTransform(anotherTransform); MITK_ASSERT_NOT_EQUAL(aDummyGeometry, anotherDummyGeometry, "Different index to world"); } void Equal_DifferentSpacing_ReturnsFalse() { anotherDummyGeometry->SetSpacing(anotherSpacing); MITK_ASSERT_NOT_EQUAL(aDummyGeometry, anotherDummyGeometry, "Different spacing"); } void Equal_InputIsNull_ReturnsFalse() { DummyTestClass::Pointer geometryNull = nullptr; CPPUNIT_ASSERT_THROW(MITK_ASSERT_EQUAL(geometryNull, anotherDummyGeometry, "Input is null"), mitk::Exception); } void Equal_DifferentBoundingBox_ReturnsFalse() { // create different bounds to make the comparison false mitk::ScalarType bounds[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; anotherDummyGeometry->SetBounds(bounds); MITK_ASSERT_NOT_EQUAL(aDummyGeometry, anotherDummyGeometry, "Different bounding box"); } void Equal_Transforms_MinorDifferences_And_Eps() { // Verifies that the eps parameter is evaluated properly // when comparing two mitk::BaseGeometry::TransformTypes aMatrix.SetIdentity(); anotherMatrix.SetIdentity(); aMatrix(0, 1) = 0.0002; aTransform->SetMatrix(aMatrix); anotherMatrix(0, 1) = 0.0002; anotherTransform->SetMatrix(anotherMatrix); anotherTransform->SetMatrix(aMatrix); CPPUNIT_ASSERT_MESSAGE("Exact same transforms are mitk::Equal() for eps=mitk::eps", mitk::Equal(*aTransform, *anotherTransform, mitk::eps, true)); CPPUNIT_ASSERT_MESSAGE("Exact same transforms are mitk::Equal() for eps=vnl_math::eps", mitk::Equal(*aTransform, *anotherTransform, vnl_math::eps, true)); anotherMatrix(0, 1) = 0.0002 + mitk::eps; anotherTransform->SetMatrix(anotherMatrix); CPPUNIT_ASSERT_MESSAGE("Transforms of diff mitk::eps are !mitk::Equal() for eps=vnl_math::eps", !mitk::Equal(*aTransform, *anotherTransform, vnl_math::eps, true)); CPPUNIT_ASSERT_MESSAGE("Transforms of diff mitk::eps are !mitk::Equal() for eps=mitk::eps-1%", !mitk::Equal(*aTransform, *anotherTransform, mitk::eps * 0.99, true)); CPPUNIT_ASSERT_MESSAGE("Transforms of diff mitk::eps _are_ mitk::Equal() for eps=mitk::eps+1%", mitk::Equal(*aTransform, *anotherTransform, mitk::eps * 1.01, true)); } void TestComposeTransform() { // Create Transformations to set and compare mitk::AffineTransform3D::Pointer transform1; transform1 = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType matrix1; matrix1.SetIdentity(); matrix1(1, 1) = 2; transform1->SetMatrix(matrix1); // Spacing = 2 mitk::AffineTransform3D::Pointer transform2; transform2 = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType matrix2; matrix2.SetIdentity(); matrix2(1, 1) = 2; transform2->SetMatrix(matrix2); // Spacing = 2 mitk::AffineTransform3D::Pointer transform3; transform3 = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType matrix3; matrix3.SetIdentity(); matrix3(1, 1) = 4; transform3->SetMatrix(matrix3); // Spacing = 4 mitk::AffineTransform3D::Pointer transform4; transform4 = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType matrix4; matrix4.SetIdentity(); matrix4(1, 1) = 0.25; transform4->SetMatrix(matrix4); // Spacing = 0.25 // Vector to compare spacing mitk::Vector3D expectedSpacing; expectedSpacing.Fill(1.0); expectedSpacing[1] = 4; DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransform(transform1); // Spacing = 2 dummy->Compose(transform2); // Spacing = 4 CPPUNIT_ASSERT(mitk::Equal(dummy->GetSpacing(), expectedSpacing)); MITK_ASSERT_EQUAL( transform3, mitk::AffineTransform3D::Pointer(dummy->GetIndexToWorldTransform()), "Compose transform 2"); // 4=4 // undo changes, new and changed object need to be the same! dummy->Compose(transform4); // Spacing = 1 DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Compose transform 3"); // 1=1 } void TestComposeVtkMatrix() { // Create Transformations to set and compare mitk::AffineTransform3D::Pointer transform1; transform1 = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType matrix1; matrix1.SetIdentity(); matrix1(1, 1) = 2; transform1->SetMatrix(matrix1); // Spacing = 2 vtkMatrix4x4 *vtkmatrix2; vtkmatrix2 = vtkMatrix4x4::New(); vtkmatrix2->Identity(); vtkmatrix2->SetElement(1, 1, 2); // Spacing = 2 mitk::AffineTransform3D::Pointer transform3; transform3 = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType matrix3; matrix3.SetIdentity(); matrix3(1, 1) = 4; transform3->SetMatrix(matrix3); // Spacing = 4 vtkMatrix4x4 *vtkmatrix4; vtkmatrix4 = vtkMatrix4x4::New(); vtkmatrix4->Identity(); vtkmatrix4->SetElement(1, 1, 0.25); // Spacing = 0.25 // Vector to compare spacing mitk::Vector3D expectedSpacing; expectedSpacing.Fill(1.0); expectedSpacing[1] = 4; DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransform(transform1); // Spacing = 2 dummy->Compose(vtkmatrix2); // Spacing = 4 vtkmatrix2->Delete(); MITK_ASSERT_EQUAL( transform3, mitk::AffineTransform3D::Pointer(dummy->GetIndexToWorldTransform()), "Compose vtk matrix"); // 4=4 CPPUNIT_ASSERT(mitk::Equal(dummy->GetSpacing(), expectedSpacing)); // undo changes, new and changed object need to be the same! dummy->Compose(vtkmatrix4); // Spacing = 1 vtkmatrix4->Delete(); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Compose vtk"); // 1=1 } void TestTranslate() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetOrigin(anotherPoint); CPPUNIT_ASSERT(mitk::Equal(anotherPoint, dummy->GetOrigin())); // use some random values for translation mitk::Vector3D translationVector; translationVector.SetElement(0, 17.5f); translationVector.SetElement(1, -32.3f); translationVector.SetElement(2, 4.0f); // compute ground truth mitk::Point3D tmpResult = anotherPoint + translationVector; dummy->Translate(translationVector); CPPUNIT_ASSERT(mitk::Equal(dummy->GetOrigin(), tmpResult)); // undo changes translationVector *= -1; dummy->Translate(translationVector); CPPUNIT_ASSERT(mitk::Equal(dummy->GetOrigin(), anotherPoint)); // undo changes, new and changed object need to be the same! translationVector.SetElement(0, -1 * anotherPoint[0]); translationVector.SetElement(1, -1 * anotherPoint[1]); translationVector.SetElement(2, -1 * anotherPoint[2]); dummy->Translate(translationVector); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Translate test"); } // a part of the test requires axis-parallel coordinates int testIndexAndWorldConsistency(DummyTestClass::Pointer dummyGeometry) { // Testing consistency of index and world coordinate systems mitk::Point3D origin = dummyGeometry->GetOrigin(); mitk::Point3D dummyPoint; // Testing index->world->index conversion consistency dummyGeometry->WorldToIndex(origin, dummyPoint); dummyGeometry->IndexToWorld(dummyPoint, dummyPoint); CPPUNIT_ASSERT(mitk::EqualArray(dummyPoint, origin, 3, mitk::eps, true)); // Testing WorldToIndex(origin, mitk::Point3D)==(0,0,0) mitk::Point3D globalOrigin; mitk::FillVector3D(globalOrigin, 0, 0, 0); mitk::Point3D originContinuousIndex; dummyGeometry->WorldToIndex(origin, originContinuousIndex); CPPUNIT_ASSERT(mitk::EqualArray(originContinuousIndex, globalOrigin, 3, mitk::eps, true)); // Testing WorldToIndex(origin, itk::Index)==(0,0,0) itk::Index<3> itkindex; dummyGeometry->WorldToIndex(origin, itkindex); itk::Index<3> globalOriginIndex; mitk::vtk2itk(globalOrigin, globalOriginIndex); CPPUNIT_ASSERT(mitk::EqualArray(itkindex, globalOriginIndex, 3, mitk::eps, true)); // Testing WorldToIndex(origin-0.5*spacing, itk::Index)==(0,0,0) mitk::Vector3D halfSpacingStep = dummyGeometry->GetSpacing() * 0.5; mitk::Matrix3D rotation; mitk::Point3D originOffCenter = origin - halfSpacingStep; dummyGeometry->WorldToIndex(originOffCenter, itkindex); CPPUNIT_ASSERT(mitk::EqualArray(itkindex, globalOriginIndex, 3, mitk::eps, true)); // Testing WorldToIndex(origin+0.5*spacing-eps, itk::Index)==(0,0,0) originOffCenter = origin + halfSpacingStep; originOffCenter -= 0.0001; dummyGeometry->WorldToIndex(originOffCenter, itkindex); CPPUNIT_ASSERT(mitk::EqualArray(itkindex, globalOriginIndex, 3, mitk::eps, true)); // Testing WorldToIndex(origin+0.5*spacing, itk::Index)==(1,1,1)"); originOffCenter = origin + halfSpacingStep; itk::Index<3> global111; mitk::FillVector3D(global111, 1, 1, 1); dummyGeometry->WorldToIndex(originOffCenter, itkindex); CPPUNIT_ASSERT(mitk::EqualArray(itkindex, global111, 3, mitk::eps, true)); // Testing WorldToIndex(GetCenter())==BoundingBox.GetCenter mitk::Point3D center = dummyGeometry->GetCenter(); mitk::Point3D centerContIndex; dummyGeometry->WorldToIndex(center, centerContIndex); mitk::BoundingBox::ConstPointer boundingBox = dummyGeometry->GetBoundingBox(); mitk::BoundingBox::PointType centerBounds = boundingBox->GetCenter(); CPPUNIT_ASSERT(mitk::Equal(centerContIndex, centerBounds)); // Testing GetCenter()==IndexToWorld(BoundingBox.GetCenter) center = dummyGeometry->GetCenter(); mitk::Point3D centerBoundsInWorldCoords; dummyGeometry->IndexToWorld(centerBounds, centerBoundsInWorldCoords); CPPUNIT_ASSERT(mitk::Equal(center, centerBoundsInWorldCoords)); // Test using random point, // Testing consistency of index and world coordinate systems mitk::Point3D point; mitk::FillVector3D(point, 3.5, -2, 4.6); // Testing index->world->index conversion consistency dummyGeometry->WorldToIndex(point, dummyPoint); dummyGeometry->IndexToWorld(dummyPoint, dummyPoint); CPPUNIT_ASSERT(mitk::EqualArray(dummyPoint, point, 3, mitk::eps, true)); return EXIT_SUCCESS; } int testIndexAndWorldConsistencyForVectors(DummyTestClass::Pointer dummyGeometry) { // Testing consistency of index and world coordinate systems for vectors mitk::Vector3D xAxisMM = dummyGeometry->GetAxisVector(0); mitk::Vector3D xAxisContinuousIndex; mitk::Point3D p, pIndex, origin; origin = dummyGeometry->GetOrigin(); p[0] = xAxisMM[0] + origin[0]; p[1] = xAxisMM[1] + origin[1]; p[2] = xAxisMM[2] + origin[2]; dummyGeometry->WorldToIndex(p, pIndex); dummyGeometry->WorldToIndex(xAxisMM, xAxisContinuousIndex); CPPUNIT_ASSERT(mitk::Equal(xAxisContinuousIndex[0], pIndex[0])); CPPUNIT_ASSERT(mitk::Equal(xAxisContinuousIndex[1], pIndex[1])); CPPUNIT_ASSERT(mitk::Equal(xAxisContinuousIndex[2], pIndex[2])); dummyGeometry->IndexToWorld(xAxisContinuousIndex, xAxisContinuousIndex); dummyGeometry->IndexToWorld(pIndex, p); CPPUNIT_ASSERT(xAxisContinuousIndex == xAxisMM); CPPUNIT_ASSERT(mitk::Equal(xAxisContinuousIndex[0], p[0] - origin[0])); CPPUNIT_ASSERT(mitk::Equal(xAxisContinuousIndex[1], p[1] - origin[1])); CPPUNIT_ASSERT(mitk::Equal(xAxisContinuousIndex[2], p[2] - origin[2])); // Test consictency for random vector mitk::Vector3D vector; mitk::FillVector3D(vector, 2.5, -3.2, 8.1); mitk::Vector3D vectorContinuousIndex; p[0] = vector[0] + origin[0]; p[1] = vector[1] + origin[1]; p[2] = vector[2] + origin[2]; dummyGeometry->WorldToIndex(p, pIndex); dummyGeometry->WorldToIndex(vector, vectorContinuousIndex); CPPUNIT_ASSERT(mitk::Equal(vectorContinuousIndex[0], pIndex[0])); CPPUNIT_ASSERT(mitk::Equal(vectorContinuousIndex[1], pIndex[1])); CPPUNIT_ASSERT(mitk::Equal(vectorContinuousIndex[2], pIndex[2])); dummyGeometry->IndexToWorld(vectorContinuousIndex, vectorContinuousIndex); dummyGeometry->IndexToWorld(pIndex, p); CPPUNIT_ASSERT(vectorContinuousIndex == vector); CPPUNIT_ASSERT(mitk::Equal(vectorContinuousIndex[0], p[0] - origin[0])); CPPUNIT_ASSERT(mitk::Equal(vectorContinuousIndex[1], p[1] - origin[1])); CPPUNIT_ASSERT(mitk::Equal(vectorContinuousIndex[2], p[2] - origin[2])); return EXIT_SUCCESS; } int testIndexAndWorldConsistencyForIndex(DummyTestClass::Pointer dummyGeometry) { // Testing consistency of index and world coordinate systems // creating testing data itk::Index<4> itkIndex4, itkIndex4b; itk::Index<3> itkIndex3, itkIndex3b; itk::Index<2> itkIndex2, itkIndex2b; itk::Index<3> mitkIndex, mitkIndexb; itkIndex4[0] = itkIndex4[1] = itkIndex4[2] = itkIndex4[3] = 4; itkIndex3[0] = itkIndex3[1] = itkIndex3[2] = 6; itkIndex2[0] = itkIndex2[1] = 2; mitkIndex[0] = mitkIndex[1] = mitkIndex[2] = 13; - // check for constistency + // check for consistency mitk::Point3D point; dummyGeometry->IndexToWorld(itkIndex2, point); dummyGeometry->WorldToIndex(point, itkIndex2b); CPPUNIT_ASSERT(((itkIndex2b[0] == itkIndex2[0]) && (itkIndex2b[1] == itkIndex2[1]))); // Testing itk::index<2> for IndexToWorld/WorldToIndex consistency dummyGeometry->IndexToWorld(itkIndex3, point); dummyGeometry->WorldToIndex(point, itkIndex3b); CPPUNIT_ASSERT( ((itkIndex3b[0] == itkIndex3[0]) && (itkIndex3b[1] == itkIndex3[1]) && (itkIndex3b[2] == itkIndex3[2]))); // Testing itk::index<3> for IndexToWorld/WorldToIndex consistency dummyGeometry->IndexToWorld(itkIndex4, point); dummyGeometry->WorldToIndex(point, itkIndex4b); CPPUNIT_ASSERT(((itkIndex4b[0] == itkIndex4[0]) && (itkIndex4b[1] == itkIndex4[1]) && (itkIndex4b[2] == itkIndex4[2]) && (itkIndex4b[3] == 0))); // Testing itk::index<3> for IndexToWorld/WorldToIndex consistency dummyGeometry->IndexToWorld(mitkIndex, point); dummyGeometry->WorldToIndex(point, mitkIndexb); CPPUNIT_ASSERT( ((mitkIndexb[0] == mitkIndex[0]) && (mitkIndexb[1] == mitkIndex[1]) && (mitkIndexb[2] == mitkIndex[2]))); // Testing mitk::Index for IndexToWorld/WorldToIndex consistency return EXIT_SUCCESS; } void TestIndexToWorld() { DummyTestClass::Pointer dummy = DummyTestClass::New(); testIndexAndWorldConsistency(dummy); testIndexAndWorldConsistencyForVectors(dummy); testIndexAndWorldConsistencyForIndex(dummy); // Geometry must not have changed DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Dummy index to world"); // Test with other geometries dummy->SetOrigin(anotherPoint); testIndexAndWorldConsistency(dummy); testIndexAndWorldConsistencyForVectors(dummy); testIndexAndWorldConsistencyForIndex(dummy); dummy->SetIndexToWorldTransform(anotherTransform); testIndexAndWorldConsistency(dummy); testIndexAndWorldConsistencyForVectors(dummy); testIndexAndWorldConsistencyForIndex(dummy); dummy->SetOrigin(anotherPoint); testIndexAndWorldConsistency(dummy); testIndexAndWorldConsistencyForVectors(dummy); testIndexAndWorldConsistencyForIndex(dummy); dummy->SetSpacing(anotherSpacing); testIndexAndWorldConsistency(dummy); testIndexAndWorldConsistencyForVectors(dummy); testIndexAndWorldConsistencyForIndex(dummy); } void TestExecuteOperation() { DummyTestClass::Pointer dummy = DummyTestClass::New(); // Do same Operations with new Dummy and compare DummyTestClass::Pointer newDummy = DummyTestClass::New(); // Test operation Nothing auto opN = new mitk::Operation(mitk::OpNOTHING); dummy->ExecuteOperation(opN); MITK_ASSERT_EQUAL(dummy, newDummy, "Dummy execute operation 1"); // Test operation Move auto opP = new mitk::PointOperation(mitk::OpMOVE, anotherPoint); dummy->ExecuteOperation(opP); CPPUNIT_ASSERT(mitk::Equal(anotherPoint, dummy->GetOrigin())); newDummy->SetOrigin(anotherPoint); MITK_ASSERT_EQUAL(dummy, newDummy, "Dummy execute operation 2"); // Test operation Scale, Scale sets spacing to scale+1 mitk::Point3D spacing; spacing[0] = anotherSpacing[0] - 1.; spacing[1] = anotherSpacing[1] - 1.; spacing[2] = anotherSpacing[2] - 1.; auto opS = new mitk::ScaleOperation(mitk::OpSCALE, spacing, anotherPoint); dummy->ExecuteOperation(opS); CPPUNIT_ASSERT(mitk::Equal(anotherSpacing, dummy->GetSpacing())); newDummy->SetSpacing(anotherSpacing); MITK_ASSERT_EQUAL(dummy, newDummy, "Dummy execute operation 3"); // change Geometry to test more cases dummy->SetIndexToWorldTransform(anotherTransform); dummy->SetSpacing(anotherSpacing); // Testing a rotation of the geometry double angle = 35.0; mitk::Vector3D rotationVector; mitk::FillVector3D(rotationVector, 1, 0, 0); mitk::Point3D center = dummy->GetCenter(); auto opR = new mitk::RotationOperation(mitk::OpROTATE, center, rotationVector, angle); dummy->ExecuteOperation(opR); mitk::Matrix3D rotation; mitk::GetRotation(dummy, rotation); mitk::Vector3D voxelStep = rotation * anotherSpacing; mitk::Vector3D voxelStepIndex; dummy->WorldToIndex(voxelStep, voxelStepIndex); mitk::Vector3D expectedVoxelStepIndex; expectedVoxelStepIndex.Fill(1); CPPUNIT_ASSERT(mitk::Equal(voxelStepIndex, expectedVoxelStepIndex)); delete opR; delete opN; delete opS; delete opP; } void TestCalculateBoundingBoxRelToTransform() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetExtentInMM(0, 15); dummy->SetExtentInMM(1, 20); dummy->SetExtentInMM(2, 8); mitk::BoundingBox::Pointer dummyBoundingBox = dummy->CalculateBoundingBoxRelativeToTransform(anotherTransform); mitk::BoundingBox::PointsContainer::Pointer pointscontainer = mitk::BoundingBox::PointsContainer::New(); mitk::BoundingBox::PointIdentifier pointid = 0; unsigned char i; mitk::AffineTransform3D::Pointer inverse = mitk::AffineTransform3D::New(); anotherTransform->GetInverse(inverse); for (i = 0; i < 8; ++i) pointscontainer->InsertElement(pointid++, inverse->TransformPoint(dummy->GetCornerPoint(i))); mitk::BoundingBox::Pointer result = mitk::BoundingBox::New(); result->SetPoints(pointscontainer); result->ComputeBoundingBox(); MITK_ASSERT_EQUAL(result, dummyBoundingBox, "BBox rel to transform"); // dummy still needs to be unchanged, except for extend DummyTestClass::Pointer newDummy = DummyTestClass::New(); newDummy->SetExtentInMM(0, 15); newDummy->SetExtentInMM(1, 20); newDummy->SetExtentInMM(2, 8); MITK_ASSERT_EQUAL(dummy, newDummy, "Dummy BBox"); } // void TestSetTimeBounds(){ // mitk::TimeBounds timeBounds; // timeBounds[0] = 1; // timeBounds[1] = 9; // DummyTestClass::Pointer dummy = DummyTestClass::New(); // dummy->SetTimeBounds(timeBounds); // mitk::TimeBounds timeBounds2 = dummy->GetTimeBounds(); // CPPUNIT_ASSERT(timeBounds[0]==timeBounds2[0]); // CPPUNIT_ASSERT(timeBounds[1]==timeBounds2[1]); // //undo changes, new and changed object need to be the same! // timeBounds[0]=mitk::ScalarTypeNumericTraits::NonpositiveMin(); // timeBounds[1]=mitk::ScalarTypeNumericTraits::max(); // DummyTestClass::Pointer newDummy = DummyTestClass::New(); // CPPUNIT_ASSERT(mitk::Equal(dummy,newDummy,mitk::eps,true)); //} void TestIs2DConvertable() { DummyTestClass::Pointer dummy = DummyTestClass::New(); // new initialized geometry is 2D convertable CPPUNIT_ASSERT(dummy->Is2DConvertable()); // Wrong Spacing needs to fail dummy->SetSpacing(anotherSpacing); CPPUNIT_ASSERT(dummy->Is2DConvertable() == false); // undo dummy->SetSpacing(aSpacing); CPPUNIT_ASSERT(dummy->Is2DConvertable()); // Wrong Origin needs to fail dummy->SetOrigin(anotherPoint); CPPUNIT_ASSERT(dummy->Is2DConvertable() == false); // undo dummy->SetOrigin(aPoint); CPPUNIT_ASSERT(dummy->Is2DConvertable()); // third dimension must not be transformed mitk::AffineTransform3D::Pointer dummyTransform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType dummyMatrix; dummyMatrix.SetIdentity(); dummyTransform->SetMatrix(dummyMatrix); dummy->SetIndexToWorldTransform(dummyTransform); // identity matrix is 2DConvertable CPPUNIT_ASSERT(dummy->Is2DConvertable()); dummyMatrix(0, 2) = 3; dummyTransform->SetMatrix(dummyMatrix); CPPUNIT_ASSERT(dummy->Is2DConvertable() == false); dummyMatrix.SetIdentity(); dummyMatrix(1, 2) = 0.4; dummyTransform->SetMatrix(dummyMatrix); CPPUNIT_ASSERT(dummy->Is2DConvertable() == false); dummyMatrix.SetIdentity(); dummyMatrix(2, 2) = 3; dummyTransform->SetMatrix(dummyMatrix); CPPUNIT_ASSERT(dummy->Is2DConvertable() == false); dummyMatrix.SetIdentity(); dummyMatrix(2, 1) = 3; dummyTransform->SetMatrix(dummyMatrix); CPPUNIT_ASSERT(dummy->Is2DConvertable() == false); dummyMatrix.SetIdentity(); dummyMatrix(2, 0) = 3; dummyTransform->SetMatrix(dummyMatrix); CPPUNIT_ASSERT(dummy->Is2DConvertable() == false); // undo changes, new and changed object need to be the same! dummyMatrix.SetIdentity(); dummyTransform->SetMatrix(dummyMatrix); DummyTestClass::Pointer newDummy = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy, newDummy, "Is 2D convertable"); } void TestGetCornerPoint() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransform(anotherTransform); double bounds[6] = {0, 11, 0, 12, 0, 13}; dummy->SetFloatBounds(bounds); mitk::Point3D corner, refCorner; // Corner 0 mitk::FillVector3D(refCorner, bounds[0], bounds[2], bounds[4]); refCorner = anotherTransform->TransformPoint(refCorner); corner = dummy->GetCornerPoint(0); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); corner = dummy->GetCornerPoint(true, true, true); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); // Corner 1 mitk::FillVector3D(refCorner, bounds[0], bounds[2], bounds[5]); refCorner = anotherTransform->TransformPoint(refCorner); corner = dummy->GetCornerPoint(1); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); corner = dummy->GetCornerPoint(true, true, false); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); // Corner 2 mitk::FillVector3D(refCorner, bounds[0], bounds[3], bounds[4]); refCorner = anotherTransform->TransformPoint(refCorner); corner = dummy->GetCornerPoint(2); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); corner = dummy->GetCornerPoint(true, false, true); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); // Corner 3 mitk::FillVector3D(refCorner, bounds[0], bounds[3], bounds[5]); refCorner = anotherTransform->TransformPoint(refCorner); corner = dummy->GetCornerPoint(3); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); corner = dummy->GetCornerPoint(true, false, false); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); // Corner 4 mitk::FillVector3D(refCorner, bounds[1], bounds[2], bounds[4]); refCorner = anotherTransform->TransformPoint(refCorner); corner = dummy->GetCornerPoint(4); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); corner = dummy->GetCornerPoint(false, true, true); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); // Corner 5 mitk::FillVector3D(refCorner, bounds[1], bounds[2], bounds[5]); refCorner = anotherTransform->TransformPoint(refCorner); corner = dummy->GetCornerPoint(5); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); corner = dummy->GetCornerPoint(false, true, false); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); // Corner 6 mitk::FillVector3D(refCorner, bounds[1], bounds[3], bounds[4]); refCorner = anotherTransform->TransformPoint(refCorner); corner = dummy->GetCornerPoint(6); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); corner = dummy->GetCornerPoint(false, false, true); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); // Corner 7 mitk::FillVector3D(refCorner, bounds[1], bounds[3], bounds[5]); refCorner = anotherTransform->TransformPoint(refCorner); corner = dummy->GetCornerPoint(7); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); corner = dummy->GetCornerPoint(false, false, false); CPPUNIT_ASSERT(mitk::Equal(refCorner, corner)); // Wrong Corner needs to fail CPPUNIT_ASSERT_THROW(dummy->GetCornerPoint(20), itk::ExceptionObject); // dummy geometry must not have changed! DummyTestClass::Pointer newDummy = DummyTestClass::New(); newDummy->SetIndexToWorldTransform(anotherTransform); newDummy->SetFloatBounds(bounds); MITK_ASSERT_EQUAL(dummy, newDummy, "Corner point"); } void TestExtentInMM() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetExtentInMM(0, 50); CPPUNIT_ASSERT(mitk::Equal(50., dummy->GetExtentInMM(0))); // Vnl Matrix has changed. The next line only works because the spacing is 1! CPPUNIT_ASSERT( mitk::Equal(50., dummy->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(0).magnitude())); // Smaller extent than original dummy->SetExtentInMM(0, 5); CPPUNIT_ASSERT(mitk::Equal(5., dummy->GetExtentInMM(0))); CPPUNIT_ASSERT( mitk::Equal(5., dummy->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(0).magnitude())); dummy->SetExtentInMM(1, 4); CPPUNIT_ASSERT(mitk::Equal(4., dummy->GetExtentInMM(1))); CPPUNIT_ASSERT( mitk::Equal(4., dummy->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(1).magnitude())); dummy->SetExtentInMM(2, 2.5); CPPUNIT_ASSERT(mitk::Equal(2.5, dummy->GetExtentInMM(2))); CPPUNIT_ASSERT( mitk::Equal(2.5, dummy->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(2).magnitude())); } void TestGetAxisVector() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransform(anotherTransform); double bounds[6] = {0, 11, 0, 12, 0, 13}; dummy->SetFloatBounds(bounds); mitk::Vector3D vector; mitk::FillVector3D(vector, bounds[1], 0, 0); dummy->IndexToWorld(vector, vector); CPPUNIT_ASSERT(mitk::Equal(dummy->GetAxisVector(0), vector)); mitk::FillVector3D(vector, 0, bounds[3], 0); dummy->IndexToWorld(vector, vector); CPPUNIT_ASSERT(mitk::Equal(dummy->GetAxisVector(1), vector)); mitk::FillVector3D(vector, 0, 0, bounds[5]); dummy->IndexToWorld(vector, vector); CPPUNIT_ASSERT(mitk::Equal(dummy->GetAxisVector(2), vector)); } void TestGetCenter() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransform(anotherTransform); double bounds[6] = {0, 11, 2, 12, 1, 13}; dummy->SetFloatBounds(bounds); mitk::Point3D refCenter; for (int i = 0; i < 3; i++) refCenter.SetElement(i, (bounds[2 * i] + bounds[2 * i + 1]) / 2.0); dummy->IndexToWorld(refCenter, refCenter); CPPUNIT_ASSERT(mitk::Equal(dummy->GetCenter(), refCenter)); } void TestGetDiagonalLength() { DummyTestClass::Pointer dummy = DummyTestClass::New(); double bounds[6] = {1, 3, 5, 8, 7.5, 11.5}; dummy->SetFloatBounds(bounds); // 3-1=2, 8-5=3, 11.5-7.5=4; 2^2+3^2+4^2 = 29 double expectedLength = sqrt(29.); CPPUNIT_ASSERT(mitk::Equal(expectedLength, dummy->GetDiagonalLength(), mitk::eps, true)); CPPUNIT_ASSERT(mitk::Equal(29., dummy->GetDiagonalLength2(), mitk::eps, true)); // dummy must not have changed DummyTestClass::Pointer newDummy = DummyTestClass::New(); newDummy->SetFloatBounds(bounds); MITK_ASSERT_EQUAL(dummy, newDummy, "Diagonal length"); } void TestGetExtent() { DummyTestClass::Pointer dummy = DummyTestClass::New(); double bounds[6] = {1, 3, 5, 8, 7.5, 11.5}; dummy->SetFloatBounds(bounds); CPPUNIT_ASSERT(mitk::Equal(2., dummy->GetExtent(0))); CPPUNIT_ASSERT(mitk::Equal(3., dummy->GetExtent(1))); CPPUNIT_ASSERT(mitk::Equal(4., dummy->GetExtent(2))); // dummy must not have changed DummyTestClass::Pointer newDummy = DummyTestClass::New(); newDummy->SetFloatBounds(bounds); MITK_ASSERT_EQUAL(dummy, newDummy, "Extend"); } void TestIsInside() { DummyTestClass::Pointer dummy = DummyTestClass::New(); double bounds[6] = {1, 3, 5, 8, 7.5, 11.5}; dummy->SetFloatBounds(bounds); mitk::Point3D insidePoint; mitk::Point3D outsidePoint; mitk::FillVector3D(insidePoint, 2, 6, 7.6); mitk::FillVector3D(outsidePoint, 0, 9, 8.2); CPPUNIT_ASSERT(dummy->IsIndexInside(insidePoint)); CPPUNIT_ASSERT(false == dummy->IsIndexInside(outsidePoint)); dummy->IndexToWorld(insidePoint, insidePoint); dummy->IndexToWorld(outsidePoint, outsidePoint); CPPUNIT_ASSERT(dummy->IsInside(insidePoint)); CPPUNIT_ASSERT(false == dummy->IsInside(outsidePoint)); // dummy must not have changed DummyTestClass::Pointer newDummy = DummyTestClass::New(); newDummy->SetFloatBounds(bounds); MITK_ASSERT_EQUAL(dummy, newDummy, "Is inside"); } void TestInitialize() { // test standard constructor DummyTestClass::Pointer dummy1 = DummyTestClass::New(); DummyTestClass::Pointer dummy2 = DummyTestClass::New(); dummy2->SetOrigin(anotherPoint); dummy2->SetBounds(anotherBoundingBox->GetBounds()); // mitk::TimeBounds timeBounds; // timeBounds[0] = 1; // timeBounds[1] = 9; // dummy2->SetTimeBounds(timeBounds); dummy2->SetIndexToWorldTransform(anotherTransform); dummy2->SetSpacing(anotherSpacing); dummy1->InitializeGeometry(dummy2); MITK_ASSERT_EQUAL(dummy1, dummy2, "Initialize 1"); dummy1->Initialize(); DummyTestClass::Pointer dummy3 = DummyTestClass::New(); MITK_ASSERT_EQUAL(dummy3, dummy1, "Initialize 2"); } void TestGetMatrixColumn() { DummyTestClass::Pointer dummy = DummyTestClass::New(); dummy->SetIndexToWorldTransform(anotherTransform); mitk::Vector3D testVector, refVector; testVector.SetVnlVector(dummy->GetMatrixColumn(0)); mitk::FillVector3D(refVector, 1, 0, 0); CPPUNIT_ASSERT(testVector == refVector); testVector.SetVnlVector(dummy->GetMatrixColumn(1)); mitk::FillVector3D(refVector, 0, 2, 0); CPPUNIT_ASSERT(testVector == refVector); testVector.SetVnlVector(dummy->GetMatrixColumn(2)); mitk::FillVector3D(refVector, 0, 0, 1); CPPUNIT_ASSERT(testVector == refVector); // dummy must not have changed DummyTestClass::Pointer newDummy = DummyTestClass::New(); newDummy->SetIndexToWorldTransform(anotherTransform); MITK_ASSERT_EQUAL(dummy, newDummy, "GetMatrixColumn"); } void IsSubGeometry_Spacing() { CPPUNIT_ASSERT(mitk::IsSubGeometry(*aDummyGeometry, *aDummyGeometry, mitk::eps, true)); for (unsigned int i = 0; i < 3; ++i) { mitk::Vector3D wrongSpacing = aDummyGeometry->GetSpacing(); wrongSpacing[i] += mitk::eps * 2; auto wrongGeometry = aDummyGeometry->Clone(); wrongGeometry->SetSpacing(wrongSpacing); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometry, mitk::eps, true)); } for (unsigned int i = 0; i < 3; ++i) { mitk::Vector3D wrongSpacing = aDummyGeometry->GetSpacing(); wrongSpacing[i] -= mitk::eps * 2; auto wrongGeometry = aDummyGeometry->Clone(); wrongGeometry->SetSpacing(wrongSpacing); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometry, mitk::eps, true)); } } void IsSubGeometry_TransformMatrix() { CPPUNIT_ASSERT(mitk::IsSubGeometry(*aDummyGeometry, *aDummyGeometry, mitk::eps, true)); for (unsigned int i = 0; i < 3; ++i) { for (unsigned int j = 0; j < 3; ++j) { itk::Matrix wrongMatrix = aDummyGeometry->GetIndexToWorldTransform()->GetMatrix(); wrongMatrix[i][j] += mitk::eps * 2; auto wrongGeometry = aDummyGeometry->Clone(); wrongGeometry->GetIndexToWorldTransform()->SetMatrix(wrongMatrix); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometry, mitk::eps, true)); } } } void IsSubGeometry_Bounds_NoneImage() { IsSubGeometry_Bounds_internal(false); } void IsSubGeometry_Bounds_Image() { IsSubGeometry_Bounds_internal(true); } void IsSubGeometry_Bounds_internal(bool isImage) { auto newBounds = aDummyGeometry->GetBounds(); newBounds[0] = 10; newBounds[1] = 20; newBounds[2] = 10; newBounds[3] = 20; newBounds[4] = 10; newBounds[5] = 20; aDummyGeometry->SetBounds(newBounds); aDummyGeometry->SetImageGeometry(isImage); CPPUNIT_ASSERT(mitk::IsSubGeometry(*aDummyGeometry, *aDummyGeometry, mitk::eps, true)); for (unsigned int i = 0; i < 6; ++i) { auto legalBounds = newBounds; if (i % 2 == 0) { legalBounds[i] += 1; } else { legalBounds[i] -= 1; } auto legalGeometry = aDummyGeometry->Clone(); legalGeometry->SetBounds(legalBounds); CPPUNIT_ASSERT(mitk::IsSubGeometry(*legalGeometry, *aDummyGeometry, mitk::eps, true)); } for (unsigned int i = 0; i < 6; ++i) { auto wrongBounds = aDummyGeometry->GetBounds(); if (i % 2 == 0) { wrongBounds[i] -= 1; } else { wrongBounds[i] += 1; } auto wrongGeometry = aDummyGeometry->Clone(); wrongGeometry->SetBounds(wrongBounds); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometry, mitk::eps, true)); } } void IsSubGeometry_Grid_Image() { IsSubGeometry_Grid_internal(true); } void IsSubGeometry_Grid_NoneImage() { IsSubGeometry_Grid_internal(false); } void IsSubGeometry_Grid_internal(bool isImage) { auto newBounds = aDummyGeometry->GetBounds(); newBounds[0] = 0; newBounds[1] = 20; newBounds[2] = 0; newBounds[3] = 20; newBounds[4] = 0; newBounds[5] = 20; aDummyGeometry->SetBounds(newBounds); aDummyGeometry->SetImageGeometry(isImage); auto smallerGeometry = aDummyGeometry->Clone(); newBounds[0] = 5; newBounds[1] = 10; newBounds[2] = 5; newBounds[3] = 10; newBounds[4] = 5; newBounds[5] = 10; smallerGeometry->SetBounds(newBounds); //legal negative shift for (unsigned int i = 0; i < 3; ++i) { auto legalOrigin = smallerGeometry->GetOrigin(); legalOrigin[i] -= smallerGeometry->GetSpacing()[i]; auto legalGeometry = smallerGeometry->Clone(); legalGeometry->SetOrigin(legalOrigin); CPPUNIT_ASSERT(mitk::IsSubGeometry(*legalGeometry, *aDummyGeometry, mitk::eps, true)); } //legal positive shift for (unsigned int i = 0; i < 3; ++i) { auto legalOrigin = smallerGeometry->GetOrigin(); legalOrigin[i] += smallerGeometry->GetSpacing()[i]; auto legalGeometry = smallerGeometry->Clone(); legalGeometry->SetOrigin(legalOrigin); CPPUNIT_ASSERT(mitk::IsSubGeometry(*legalGeometry, *aDummyGeometry, mitk::eps, true)); } //wrong negative shift for (unsigned int i = 0; i < 3; ++i) { auto wrongOrigin = smallerGeometry->GetOrigin(); wrongOrigin[i] -= 2 * mitk::eps; auto wrongGeometry = smallerGeometry->Clone(); wrongGeometry->SetOrigin(wrongOrigin); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometry, mitk::eps, true)); } //wrong positive shift for (unsigned int i = 0; i < 3; ++i) { auto wrongOrigin = smallerGeometry->GetOrigin(); wrongOrigin[i] += 2 * mitk::eps; auto wrongGeometry = smallerGeometry->Clone(); wrongGeometry->SetOrigin(wrongOrigin); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometry, mitk::eps, true)); } } void IsSubGeometry_Bounds_Oblique_NoneImage() { IsSubGeometry_Bounds_Oblique_internal(false); } void IsSubGeometry_Bounds_Oblique_Image() { IsSubGeometry_Bounds_Oblique_internal(true); } void IsSubGeometry_Bounds_Oblique_internal(bool isImage) { auto newBounds = aDummyGeometryOblique->GetBounds(); aDummyGeometryOblique->SetImageGeometry(isImage); //REMARK: used NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION to compensate rounding errors that //are interoduced when transforming points/indeces due to the oblique geometry. CPPUNIT_ASSERT(mitk::IsSubGeometry(*aDummyGeometryOblique, *aDummyGeometryOblique, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION, true)); for (unsigned int i = 0; i < 6; ++i) { auto legalBounds = newBounds; if (i % 2 == 0) { legalBounds[i] += 1; } else { legalBounds[i] -= 1; } auto legalGeometry = aDummyGeometryOblique->Clone(); legalGeometry->SetBounds(legalBounds); CPPUNIT_ASSERT(mitk::IsSubGeometry(*legalGeometry, *aDummyGeometryOblique, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION, true)); } for (unsigned int i = 0; i < 6; ++i) { auto wrongBounds = newBounds; if (i % 2 == 0) { wrongBounds[i] -= 1; } else { wrongBounds[i] += 1; } auto wrongGeometry = aDummyGeometryOblique->Clone(); wrongGeometry->SetBounds(wrongBounds); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometryOblique, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION, true)); } } void IsSubGeometry_Grid_Oblique_NoneImage() { IsSubGeometry_Grid_Oblique_internal(false); } void IsSubGeometry_Grid_Oblique_Image() { IsSubGeometry_Grid_Oblique_internal(true); } void IsSubGeometry_Grid_Oblique_internal(bool isImage) { auto newBounds = aDummyGeometryOblique->GetBounds(); newBounds[0] = 0; newBounds[1] = 20; newBounds[2] = 0; newBounds[3] = 20; newBounds[4] = 0; newBounds[5] = 20; aDummyGeometryOblique->SetBounds(newBounds); aDummyGeometryOblique->SetImageGeometry(isImage); auto smallerGeometry = aDummyGeometryOblique->Clone(); newBounds[0] = 5; newBounds[1] = 10; newBounds[2] = 5; newBounds[3] = 10; newBounds[4] = 5; newBounds[5] = 10; smallerGeometry->SetBounds(newBounds); //REMARK: used NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION in the following checks //to compensate rounding errors that are interoduced when transforming points/indeces //due to the oblique geometry. //legal negative shift for (unsigned int i = 0; i < 3; ++i) { auto legalOrigin = smallerGeometry->GetOrigin(); mitk::Point3D index; smallerGeometry->WorldToIndex(legalOrigin, index); index[i] -= 1; smallerGeometry->IndexToWorld(index, legalOrigin); auto legalGeometry = smallerGeometry->Clone(); legalGeometry->SetOrigin(legalOrigin); CPPUNIT_ASSERT(mitk::IsSubGeometry(*legalGeometry, *aDummyGeometryOblique, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION, true)); } //legal positive shift for (unsigned int i = 0; i < 3; ++i) { auto legalOrigin = smallerGeometry->GetOrigin(); mitk::Point3D index; smallerGeometry->WorldToIndex(legalOrigin, index); index[i] += 1; smallerGeometry->IndexToWorld(index, legalOrigin); auto legalGeometry = smallerGeometry->Clone(); legalGeometry->SetOrigin(legalOrigin); CPPUNIT_ASSERT(mitk::IsSubGeometry(*legalGeometry, *aDummyGeometryOblique, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION, true)); } //wrong negative shift for (unsigned int i = 0; i < 3; ++i) { auto wrongOrigin = smallerGeometry->GetOrigin(); wrongOrigin[i] -= 2 * mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION; auto wrongGeometry = smallerGeometry->Clone(); wrongGeometry->SetOrigin(wrongOrigin); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometryOblique, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION, true)); } //wrong positive shift for (unsigned int i = 0; i < 3; ++i) { auto wrongOrigin = smallerGeometry->GetOrigin(); wrongOrigin[i] += 2 * mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION; auto wrongGeometry = smallerGeometry->Clone(); wrongGeometry->SetOrigin(wrongOrigin); CPPUNIT_ASSERT(!mitk::IsSubGeometry(*wrongGeometry, *aDummyGeometryOblique, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION, mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION, true)); } } }; // end class mitkBaseGeometryTestSuite MITK_TEST_SUITE_REGISTRATION(mitkBaseGeometry) diff --git a/Modules/Core/test/mitkClippedSurfaceBoundsCalculatorTest.cpp b/Modules/Core/test/mitkClippedSurfaceBoundsCalculatorTest.cpp index 3afe051d94..65f234967d 100644 --- a/Modules/Core/test/mitkClippedSurfaceBoundsCalculatorTest.cpp +++ b/Modules/Core/test/mitkClippedSurfaceBoundsCalculatorTest.cpp @@ -1,795 +1,795 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkTestingMacros.h" #include #include "mitkClippedSurfaceBoundsCalculator.h" #include "mitkGeometry3D.h" #include "mitkNumericTypes.h" #include "mitkPlaneGeometry.h" static void CheckPlanesInsideBoundingBoxOnlyOnOneSlice(mitk::BaseGeometry::Pointer geometry3D) { // Check planes which are inside the bounding box mitk::ClippedSurfaceBoundsCalculator *calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize(mitk::MakePixelType(), *(geometry3D.GetPointer())); // Check planes which are only on one slice: // Slice 0 mitk::Point3D origin; origin[0] = 511; origin[1] = 0; origin[2] = 0; mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); mitk::PlaneGeometry::Pointer planeOnSliceZero = mitk::PlaneGeometry::New(); planeOnSliceZero->InitializePlane(origin, normal); calculator->SetInput(planeOnSliceZero, image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 0, "Check if plane is on slice 0"); // Slice 3 origin[2] = 3; mitk::PlaneGeometry::Pointer planeOnSliceThree = mitk::PlaneGeometry::New(); planeOnSliceThree->InitializePlane(origin, normal); planeOnSliceThree->SetImageGeometry(false); calculator->SetInput(planeOnSliceThree, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 3 && minMax.second == 3, "Check if plane is on slice 3"); // Slice 17 origin[2] = 17; mitk::PlaneGeometry::Pointer planeOnSliceSeventeen = mitk::PlaneGeometry::New(); planeOnSliceSeventeen->InitializePlane(origin, normal); calculator->SetInput(planeOnSliceSeventeen, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 17 && minMax.second == 17, "Check if plane is on slice 17"); // Slice 20 origin[2] = 19; mitk::PlaneGeometry::Pointer planeOnSliceTwenty = mitk::PlaneGeometry::New(); planeOnSliceTwenty->InitializePlane(origin, normal); calculator->SetInput(planeOnSliceTwenty, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 19 && minMax.second == 19, "Check if plane is on slice 19"); delete calculator; } static void CheckPlanesInsideBoundingBox(mitk::BaseGeometry::Pointer geometry3D) { // Check planes which are inside the bounding box mitk::ClippedSurfaceBoundsCalculator *calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize(mitk::MakePixelType(), *(geometry3D.GetPointer())); // Check planes which are only on one slice: // Slice 0 mitk::Point3D origin; origin[0] = 510; // Set to 511.9 so that the intersection point is inside the bounding box origin[1] = 0; origin[2] = 0; mitk::Vector3D normal; mitk::FillVector3D(normal, 1, 0, 0); mitk::PlaneGeometry::Pointer planeSagittalOne = mitk::PlaneGeometry::New(); planeSagittalOne->InitializePlane(origin, normal); calculator->SetInput(planeSagittalOne, image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); // Slice 3 origin[0] = 256; MITK_INFO << "Case1 origin: " << origin; mitk::PlaneGeometry::Pointer planeSagittalTwo = mitk::PlaneGeometry::New(); planeSagittalTwo->InitializePlane(origin, normal); MITK_INFO << "PlaneNormal: " << planeSagittalTwo->GetNormal(); MITK_INFO << "PlaneOrigin: " << planeSagittalTwo->GetOrigin(); calculator->SetInput(planeSagittalTwo, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); // Slice 17 origin[0] = 0; // Set to 0.1 so that the intersection point is inside the bounding box mitk::PlaneGeometry::Pointer planeOnSliceSeventeen = mitk::PlaneGeometry::New(); planeOnSliceSeventeen->InitializePlane(origin, normal); calculator->SetInput(planeOnSliceSeventeen, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); // Crooked planes: origin[0] = 0; origin[1] = 507; origin[2] = 0; normal[0] = 1; normal[1] = -1; normal[2] = 1; mitk::PlaneGeometry::Pointer planeCrookedOne = mitk::PlaneGeometry::New(); planeCrookedOne->InitializePlane(origin, normal); calculator->SetInput(planeCrookedOne, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 5, "Check if plane is from slice 0 to slice 5 with inclined plane"); origin[0] = 512; origin[1] = 0; origin[2] = 16; mitk::PlaneGeometry::Pointer planeCrookedTwo = mitk::PlaneGeometry::New(); planeCrookedTwo->InitializePlane(origin, normal); calculator->SetInput(planeCrookedTwo, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 16 && minMax.second == 19, "Check if plane is from slice 16 to slice 19 with inclined plane"); origin[0] = 510; origin[1] = 0; origin[2] = 0; normal[1] = 0; normal[2] = 0.04; mitk::PlaneGeometry::Pointer planeCrookedThree = mitk::PlaneGeometry::New(); planeCrookedThree->InitializePlane(origin, normal); calculator->SetInput(planeCrookedThree, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19 with inclined plane"); delete calculator; } static void CheckPlanesOutsideOfBoundingBox(mitk::BaseGeometry::Pointer geometry3D) { // Check planes which are outside of the bounding box mitk::ClippedSurfaceBoundsCalculator *calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize(mitk::MakePixelType(), *(geometry3D.GetPointer())); // In front of the bounding box mitk::Point3D origin; origin[0] = 510; origin[1] = 0; origin[2] = -5; mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); mitk::PlaneGeometry::Pointer planeInFront = mitk::PlaneGeometry::New(); planeInFront->InitializePlane(origin, normal); calculator->SetInput(planeInFront, image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); // Behind the bounding box origin[2] = 515; mitk::PlaneGeometry::Pointer planeBehind = mitk::PlaneGeometry::New(); planeBehind->InitializePlane(origin, normal); calculator->SetInput(planeBehind, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); // Above origin[1] = 515; mitk::FillVector3D(normal, 0, 1, 0); mitk::PlaneGeometry::Pointer planeAbove = mitk::PlaneGeometry::New(); planeAbove->InitializePlane(origin, normal); calculator->SetInput(planeAbove, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); // Below origin[1] = -5; mitk::PlaneGeometry::Pointer planeBelow = mitk::PlaneGeometry::New(); planeBelow->InitializePlane(origin, normal); calculator->SetInput(planeBelow, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); // Left side origin[0] = -5; mitk::FillVector3D(normal, 1, 0, 0); mitk::PlaneGeometry::Pointer planeLeftSide = mitk::PlaneGeometry::New(); planeLeftSide->InitializePlane(origin, normal); calculator->SetInput(planeLeftSide, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); // Right side origin[1] = 515; mitk::PlaneGeometry::Pointer planeRightSide = mitk::PlaneGeometry::New(); planeRightSide->InitializePlane(origin, normal); calculator->SetInput(planeRightSide, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == std::numeric_limits::max(), "Check if min value hasn't been set"); MITK_TEST_CONDITION(minMax.second == std::numeric_limits::min(), "Check if max value hasn't been set"); delete calculator; } static void CheckIntersectionPointsOfTwoGeometry3D(mitk::BaseGeometry::Pointer firstGeometry3D, mitk::BaseGeometry::Pointer secondGeometry3D) { mitk::ClippedSurfaceBoundsCalculator *calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer firstImage = mitk::Image::New(); firstImage->Initialize(mitk::MakePixelType(), *(firstGeometry3D.GetPointer())); calculator->SetInput(secondGeometry3D, firstImage); calculator->Update(); auto minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 19, "Check if plane is from slice 0 to slice 19"); delete calculator; } static void CheckIntersectionWithPointCloud(mitk::BaseGeometry::Pointer geometry3D) { // Check planes which are inside the bounding box mitk::Image::Pointer image = mitk::Image::New(); image->Initialize(mitk::MakePixelType(), *(geometry3D.GetPointer())); { mitk::Point3D pnt1, pnt2; pnt1[0] = 3; pnt1[1] = 5; pnt1[2] = 3; pnt2[0] = 8; pnt2[1] = 3; pnt2[2] = 8; mitk::ClippedSurfaceBoundsCalculator::PointListType pointlist; pointlist.push_back(pnt1); pointlist.push_back(pnt2); mitk::ClippedSurfaceBoundsCalculator calculator; calculator.SetInput(pointlist, image); calculator.Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxZ = calculator.GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMaxZ.first == 3 && minMaxZ.second == 8, "Check if points span from slice 3 to slice 8 in axial"); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxX = calculator.GetMinMaxSpatialDirectionX(); MITK_TEST_CONDITION(minMaxX.first == 3 && minMaxX.second == 5, "Check if points span from slice 3 to slice 5 in sagittal"); } { mitk::Point3D pnt1, pnt2; pnt1.Fill(-3); pnt2.Fill(600); mitk::ClippedSurfaceBoundsCalculator::PointListType pointlist; pointlist.push_back(pnt1); pointlist.push_back(pnt2); mitk::ClippedSurfaceBoundsCalculator calculator; calculator.SetInput(pointlist, image); calculator.Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxZ = calculator.GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMaxZ.first == 0 && minMaxZ.second == 19, "Check if points are correctly clipped to slice 0 and slice 19 in axial"); mitk::ClippedSurfaceBoundsCalculator::OutputType minMaxX = calculator.GetMinMaxSpatialDirectionX(); MITK_TEST_CONDITION(minMaxX.first == 0 && minMaxX.second == 511, "Check if points are correctly clipped to slice 0 and slice 511 in sagittal"); } } static void CheckIntersectionWithRotatedGeometry() { // Define origin for second Geometry3D; mitk::Point3D origin3; origin3[0] = -45.25; origin3[1] = -113.22; origin3[2] = 0.62; // Define normal: mitk::Vector3D normal3; normal3[0] = -0.02; normal3[1] = -0.18; normal3[2] = 2.99; mitk::Vector3D spacing; spacing[0] = 1.43; spacing[1] = 1.43; spacing[2] = 3.0; // Initialize PlaneGeometry: mitk::PlaneGeometry::Pointer planeGeometry3 = mitk::PlaneGeometry::New(); planeGeometry3->InitializePlane(origin3, normal3); planeGeometry3->SetSpacing(spacing); mitk::BoundingBox::BoundsArrayType moreBounds = planeGeometry3->GetBounds(); moreBounds[0] = 0; moreBounds[1] = 64; moreBounds[2] = 0; moreBounds[3] = 140; moreBounds[4] = 0; moreBounds[5] = 1; planeGeometry3->SetBounds(moreBounds); // Initialize SlicedGeometry3D: mitk::SlicedGeometry3D::Pointer rotatedSlicedGeometry3D = mitk::SlicedGeometry3D::New(); rotatedSlicedGeometry3D->InitializeEvenlySpaced(dynamic_cast(planeGeometry3.GetPointer()), 25); rotatedSlicedGeometry3D->SetImageGeometry(true); mitk::AffineTransform3D *geom = rotatedSlicedGeometry3D->GetIndexToWorldTransform(); mitk::AffineTransform3D::MatrixType matrix; matrix[0][0] = 1.43; matrix[0][1] = -0.01; matrix[0][2] = -0.02; matrix[0][0] = 0.01; matrix[1][1] = 1.43; matrix[2][2] = -0.18; matrix[0][0] = 0.01; matrix[1][1] = 0.08; matrix[2][2] = 2.99; geom->SetMatrix(matrix); mitk::ClippedSurfaceBoundsCalculator *calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize(mitk::MakePixelType(), *(rotatedSlicedGeometry3D.GetPointer())); // Check planes which are only on one slice: { // last Slice mitk::Point3D origin; origin[0] = -47.79; origin[1] = 81.41; origin[2] = 84.34; mitk::Vector3D normal; mitk::FillVector3D(normal, 0.02, 0.18, -2.99); mitk::Vector3D spacing; spacing[0] = 1.43; spacing[1] = 1.43; spacing[2] = 3.0; mitk::PlaneGeometry::Pointer planeOnSliceZero = mitk::PlaneGeometry::New(); planeOnSliceZero->InitializePlane(origin, normal); planeOnSliceZero->SetSpacing(spacing); calculator->SetInput(planeOnSliceZero, image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 24 && minMax.second == 24, "Check if plane is on slice 24"); } { // Slice 0-24 mitk::Point3D origin; origin[0] = -45; origin[1] = -105; origin[2] = 35; mitk::Vector3D normal; mitk::FillVector3D(normal, 1.43, 0.01, 0.01); mitk::Vector3D spacing; spacing[0] = 1.43; spacing[1] = 3.0; spacing[2] = 1.43; mitk::PlaneGeometry::Pointer planeOnSliceZero = mitk::PlaneGeometry::New(); planeOnSliceZero->InitializePlane(origin, normal); planeOnSliceZero->SetSpacing(spacing); calculator->SetInput(planeOnSliceZero, image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionZ(); MITK_TEST_CONDITION(minMax.first != minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 24, "Check if plane is on slices 0-24"); } delete calculator; } static void CheckIntersectionWithRotatedGeometry90() { // Define origin for second Geometry3D; mitk::Point3D origin3; origin3[0] = 0.0; origin3[1] = 0.0; origin3[2] = 0.0; // Define normal: mitk::Vector3D normal3; normal3[0] = 0; normal3[1] = 0; normal3[2] = 1; mitk::Vector3D spacing; spacing[0] = 1.0; spacing[1] = 2.0; spacing[2] = 1.0; // Initialize PlaneGeometry: mitk::PlaneGeometry::Pointer planeGeometry3 = mitk::PlaneGeometry::New(); planeGeometry3->InitializePlane(origin3, normal3); planeGeometry3->SetSpacing(spacing); mitk::BoundingBox::BoundsArrayType moreBounds = planeGeometry3->GetBounds(); moreBounds[0] = 0; moreBounds[1] = 50; moreBounds[2] = 0; moreBounds[3] = 50; moreBounds[4] = 0; moreBounds[5] = 1; planeGeometry3->SetBounds(moreBounds); // Initialize SlicedGeometry3D: mitk::SlicedGeometry3D::Pointer rotatedSlicedGeometry3D = mitk::SlicedGeometry3D::New(); rotatedSlicedGeometry3D->InitializeEvenlySpaced(dynamic_cast(planeGeometry3.GetPointer()), 50); rotatedSlicedGeometry3D->SetImageGeometry(true); // Set the rotation to zero (identity times spacing matrix) because the default makes a rotation mitk::AffineTransform3D *geom = rotatedSlicedGeometry3D->GetIndexToWorldTransform(); mitk::AffineTransform3D::MatrixType matrix; matrix[0][0] = spacing[0]; matrix[0][1] = 0.0; matrix[0][2] = 0.0; matrix[1][0] = 0.0; matrix[1][1] = spacing[1]; matrix[1][2] = 0.0; matrix[2][0] = 0.0; matrix[2][1] = 0.0; matrix[2][2] = spacing[2]; geom->SetMatrix(matrix); mitk::ClippedSurfaceBoundsCalculator *calculator = new mitk::ClippedSurfaceBoundsCalculator(); mitk::Image::Pointer image = mitk::Image::New(); image->Initialize(mitk::MakePixelType(), *(rotatedSlicedGeometry3D.GetPointer())); // construct the planes in y direction { // first Slice in Y direction mitk::Point3D originFirstSlice; originFirstSlice[0] = 0.0; originFirstSlice[1] = -1.0; originFirstSlice[2] = 0.0; mitk::Vector3D normalFitrstSlice; mitk::FillVector3D(normalFitrstSlice, 0.0, 1.0, 0.0); mitk::Vector3D spacingFirstSlice; spacingFirstSlice[0] = 1.0; spacingFirstSlice[1] = 1.0; spacingFirstSlice[2] = 1.0; mitk::PlaneGeometry::Pointer planeOnFirstSlice = mitk::PlaneGeometry::New(); planeOnFirstSlice->InitializePlane(originFirstSlice, normalFitrstSlice); planeOnFirstSlice->SetSpacing(spacingFirstSlice); // last Slice in Y Direction mitk::Point3D originLastSlice; originLastSlice[0] = 0.0; originLastSlice[1] = 99.0; originLastSlice[2] = 0.0; mitk::Vector3D normalLastSlice; mitk::FillVector3D(normalLastSlice, 0.0, 1.0, 0.0); mitk::Vector3D spacingLastSlice; spacingLastSlice[0] = 1.0; spacingLastSlice[1] = 1.0; spacingLastSlice[2] = 1.0; mitk::PlaneGeometry::Pointer planeOnLastSlice = mitk::PlaneGeometry::New(); planeOnLastSlice->InitializePlane(originLastSlice, normalLastSlice); planeOnLastSlice->SetSpacing(spacingLastSlice); // calculate the intersection on the last slice calculator->SetInput(planeOnLastSlice, image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionY(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 49 && minMax.second == 49, "Check if plane is on slice 49"); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; // calculate the intersection on the first slice calculator->SetInput(planeOnFirstSlice, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionY(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 0, "Check if plane is on slice 0"); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; } - // now we make a rotation of the Image about 270 degrees around Z Axis to get an aligment on the positiv x axis + // now we make a rotation of the Image about 270 degrees around Z Axis to get an alignment on the positive x axis double angleInDegrees = 270 * itk::Math::pi / 180; mitk::AffineTransform3D::MatrixType matrix2; matrix2[0][0] = cos(angleInDegrees); matrix2[0][1] = -sin(angleInDegrees); matrix2[0][2] = 0.0; matrix2[1][0] = sin(angleInDegrees); matrix2[1][1] = cos(angleInDegrees); matrix2[1][2] = 0.0; matrix2[2][0] = 0.0; matrix2[2][1] = 0.0; matrix2[2][2] = 1.0; // multiplie the identity with the transformation matrix mitk::AffineTransform3D::MatrixType TransformationMatrix = matrix2 * matrix; // initialize the image with the new rotation Matrix geom->SetMatrix(TransformationMatrix); image->Initialize(mitk::MakePixelType(), *(rotatedSlicedGeometry3D.GetPointer())); { // first Slice in X Diection mitk::Point3D originFirstSlice; originFirstSlice[0] = -1.0; originFirstSlice[1] = 0.0; originFirstSlice[2] = 0.0; mitk::Vector3D normalFitrstSlice; mitk::FillVector3D(normalFitrstSlice, 1.0, 0.0, 0.0); mitk::Vector3D spacingFirstSlice; spacingFirstSlice[0] = 1.0; spacingFirstSlice[1] = 1.0; spacingFirstSlice[2] = 1.0; mitk::PlaneGeometry::Pointer planeOnFirstSlice = mitk::PlaneGeometry::New(); planeOnFirstSlice->InitializePlane(originFirstSlice, normalFitrstSlice); planeOnFirstSlice->SetSpacing(spacingFirstSlice); // last Slice in X Direction mitk::Point3D originLastSlice; originLastSlice[0] = 99.0; originLastSlice[1] = 0.0; originLastSlice[2] = 0.0; mitk::Vector3D normalLastSlice; mitk::FillVector3D(normalLastSlice, 1.0, 0.0, 0.0); mitk::Vector3D spacingLastSlice; spacingLastSlice[0] = 1.0; spacingLastSlice[1] = 1.0; spacingLastSlice[2] = 1.0; mitk::PlaneGeometry::Pointer planeOnLastSlice = mitk::PlaneGeometry::New(); planeOnLastSlice->InitializePlane(originLastSlice, normalLastSlice); planeOnLastSlice->SetSpacing(spacingLastSlice); calculator->SetInput(planeOnLastSlice, image); calculator->Update(); mitk::ClippedSurfaceBoundsCalculator::OutputType minMax = calculator->GetMinMaxSpatialDirectionY(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 49 && minMax.second == 49, "Check if plane is on slice 49"); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; calculator->SetInput(planeOnFirstSlice, image); calculator->Update(); minMax = calculator->GetMinMaxSpatialDirectionY(); MITK_TEST_CONDITION(minMax.first == minMax.second, "Check if plane is only on one slice"); MITK_TEST_CONDITION(minMax.first == 0 && minMax.second == 0, "Check if plane is on slice 0"); MITK_INFO << "min: " << minMax.first << " max: " << minMax.second; } delete calculator; } int mitkClippedSurfaceBoundsCalculatorTest(int, char *[]) { // always start with this! MITK_TEST_BEGIN("ClippedSurfaceBoundsCalculator"); /** The class mitkClippedSurfaceBoundsCalculator calculates the intersection points of a PlaneGeometry and a * Geometry3D. * This unit test checks if the correct min and max values for the three spatial directions (x, y, z) * are calculated. To test this we define artificial PlaneGeometries and Geometry3Ds and test different * scenarios: * * 1. planes which are inside the bounding box of a 3D geometry but only on one slice * 2. planes which are outside of the bounding box * 3. planes which are inside the bounding box but over more than one slice * * Note: Currently rotated geometries are not tested! */ /********************* Define Geometry3D ***********************/ // Define origin: mitk::Point3D origin; origin[0] = 511; origin[1] = 0; origin[2] = 0; // Define normal: mitk::Vector3D normal; mitk::FillVector3D(normal, 0, 0, 1); // Initialize PlaneGeometry: mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New(); planeGeometry->InitializePlane(origin, normal); // Set Bounds: mitk::BoundingBox::BoundsArrayType bounds = planeGeometry->GetBounds(); bounds[0] = 0; bounds[1] = 512; bounds[2] = 0; bounds[3] = 512; bounds[4] = 0; bounds[5] = 1; planeGeometry->SetBounds(bounds); // Initialize SlicedGeometry3D: mitk::SlicedGeometry3D::Pointer slicedGeometry3D = mitk::SlicedGeometry3D::New(); slicedGeometry3D->InitializeEvenlySpaced(dynamic_cast(planeGeometry.GetPointer()), 20); mitk::BaseGeometry::Pointer geometry3D = dynamic_cast(slicedGeometry3D.GetPointer()); geometry3D->SetImageGeometry(true); // Define origin for second Geometry3D; mitk::Point3D origin2; origin2[0] = 511; origin2[1] = 60; origin2[2] = 0; // Define normal: mitk::Vector3D normal2; mitk::FillVector3D(normal2, 0, 1, 0); // Initialize PlaneGeometry: mitk::PlaneGeometry::Pointer planeGeometry2 = mitk::PlaneGeometry::New(); planeGeometry2->InitializePlane(origin2, normal2); // Initialize SlicedGeometry3D: mitk::SlicedGeometry3D::Pointer secondSlicedGeometry3D = mitk::SlicedGeometry3D::New(); secondSlicedGeometry3D->InitializeEvenlySpaced(dynamic_cast(planeGeometry2.GetPointer()), 20); mitk::BaseGeometry::Pointer secondGeometry3D = dynamic_cast(secondSlicedGeometry3D.GetPointer()); secondGeometry3D->SetImageGeometry(true); /***************************************************************/ CheckPlanesInsideBoundingBoxOnlyOnOneSlice(geometry3D); CheckPlanesOutsideOfBoundingBox(geometry3D); CheckPlanesInsideBoundingBox(geometry3D); CheckIntersectionPointsOfTwoGeometry3D(geometry3D, secondGeometry3D); CheckIntersectionWithPointCloud(geometry3D); CheckIntersectionWithRotatedGeometry(); CheckIntersectionWithRotatedGeometry90(); /** ToDo: * test also rotated 3D geometry! */ MITK_TEST_END(); } diff --git a/Modules/Core/test/mitkDataStorageTest.cpp b/Modules/Core/test/mitkDataStorageTest.cpp index ac24c8ea2f..428fd93240 100644 --- a/Modules/Core/test/mitkDataStorageTest.cpp +++ b/Modules/Core/test/mitkDataStorageTest.cpp @@ -1,874 +1,874 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include "mitkColorProperty.h" #include "mitkDataNode.h" #include "mitkGroupTagProperty.h" #include "mitkImage.h" #include "mitkReferenceCountWatcher.h" #include "mitkStringProperty.h" #include "mitkSurface.h" #include "mitkDataStorage.h" #include "mitkIOUtil.h" #include "mitkMessage.h" #include "mitkNodePredicateAnd.h" #include "mitkNodePredicateData.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateDimension.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateOr.h" #include "mitkNodePredicateProperty.h" #include "mitkNodePredicateSource.h" #include "mitkStandaloneDataStorage.h" //#include "mitkPicFileReader.h" #include "mitkTestingMacros.h" void TestDataStorage(mitk::DataStorage *ds, std::string filename); namespace mitk { class TestStandaloneDataStorage : public StandaloneDataStorage { public: mitkClassMacro(TestStandaloneDataStorage, mitk::DataStorage); itkFactorylessNewMacro(Self) itkCloneMacro(Self) std::map GetModifiedObserverTags() const { return m_NodeModifiedObserverTags; } std::map GetDeletedObserverTags() const { return m_NodeDeleteObserverTags; } protected: TestStandaloneDataStorage() {} }; } class DSEventReceiver // Helper class for event testing { public: const mitk::DataNode *m_NodeAdded; const mitk::DataNode *m_NodeRemoved; DSEventReceiver() : m_NodeAdded(nullptr), m_NodeRemoved(nullptr) {} void OnAdd(const mitk::DataNode *node) { m_NodeAdded = node; } void OnRemove(const mitk::DataNode *node) { m_NodeRemoved = node; } }; /// /// \brief a class for checking if the datastorage is really thread safe /// /// Therefore it listens to a node contained in the datastorage. when this node /// gets removed and deleted, this class gets informed by calling OnObjectDelete(). /// in OnObjectDelete() an empty node gets added. this must not cause a deadlock /// struct ItkDeleteEventListener { ItkDeleteEventListener(mitk::DataStorage *ds) : m_Node(nullptr), m_DataStorage(ds), m_DeleteObserverTag(0) {} void SetNode(mitk::DataNode *_Node) { if (m_Node) return; m_Node = _Node; itk::MemberCommand::Pointer onObjectDelete = itk::MemberCommand::New(); onObjectDelete->SetCallbackFunction(this, &ItkDeleteEventListener::OnObjectDelete); m_DeleteObserverTag = m_Node->AddObserver(itk::DeleteEvent(), onObjectDelete); } void OnObjectDelete(const itk::Object * /*caller*/, const itk::EventObject &) { mitk::DataNode::Pointer node = mitk::DataNode::New(); m_DataStorage->Add(node); // SHOULD NOT CAUSE A DEADLOCK! m_DataStorage->Remove(node); // tidy up: remove the empty node again m_Node = nullptr; } protected: mitk::DataNode *m_Node; mitk::DataStorage::Pointer m_DataStorage; unsigned int m_DeleteObserverTag; }; //## Documentation //## main testing method //## NOTE: the current Singleton implementation of DataTreeStorage will lead to crashes if a testcase fails //## and therefore mitk::DataStorage::ShutdownSingleton() is not called. int mitkDataStorageTest(int argc, char *argv[]) { MITK_TEST_BEGIN("DataStorageTest"); // muellerm: test observer tag remove mitk::TestStandaloneDataStorage::Pointer testDS = mitk::TestStandaloneDataStorage::New(); mitk::DataNode::Pointer n1 = mitk::DataNode::New(); testDS->Add(n1); MITK_TEST_CONDITION_REQUIRED(testDS->GetModifiedObserverTags().size() == 1, "Testing if modified" " observer was added."); MITK_TEST_CONDITION_REQUIRED(testDS->GetDeletedObserverTags().size() == 1, "Testing if delete" " observer was added."); testDS->Remove(n1); MITK_TEST_CONDITION_REQUIRED(testDS->GetModifiedObserverTags().size() == 0, "Testing if modified" " observer was removed."); MITK_TEST_CONDITION_REQUIRED(testDS->GetDeletedObserverTags().size() == 0, "Testing if delete" " observer was removed."); /* Create StandaloneDataStorage */ MITK_TEST_OUTPUT(<< "Create StandaloneDataStorage : "); mitk::StandaloneDataStorage::Pointer sds; try { sds = mitk::StandaloneDataStorage::New(); MITK_TEST_CONDITION_REQUIRED(sds.IsNotNull(), "Testing Instatiation"); } catch (...) { MITK_TEST_FAILED_MSG(<< "Exception during creation of StandaloneDataStorage"); } MITK_TEST_OUTPUT(<< "Testing StandaloneDataStorage: "); MITK_TEST_CONDITION_REQUIRED(argc > 1, "Testing correct test invocation"); TestDataStorage(sds, argv[1]); // TODO: Add specific StandaloneDataStorage Tests here sds = nullptr; MITK_TEST_END(); } //##Documentation //## @brief Test for the DataStorage class and its associated classes (e.g. the predicate classes) //## This method will be called once for each subclass of DataStorage void TestDataStorage(mitk::DataStorage *ds, std::string filename) { /* DataStorage valid? */ MITK_TEST_CONDITION_REQUIRED(ds != nullptr, "DataStorage valid?"); // Take the ItkImageFile Reader for the .nrrd data format. // (was previously pic which is now deprecated format) mitk::Image::Pointer image = mitk::IOUtil::Load(filename); // create some DataNodes to fill the ds mitk::DataNode::Pointer n1 = mitk::DataNode::New(); // node with image and name property // mitk::Image::Pointer image = mitk::Image::New(); // unsigned int imageDimensions[] = { 10, 10, 10, 10 }; // mitk::PixelType pt(typeid(int)); // image->Initialize( pt, 4, imageDimensions ); n1->SetData(image); n1->SetProperty("name", mitk::StringProperty::New("Node 1 - Image Node")); mitk::DataStorage::SetOfObjects::Pointer parents1 = mitk::DataStorage::SetOfObjects::New(); mitk::DataNode::Pointer n2 = mitk::DataNode::New(); // node with surface and name and color properties mitk::Surface::Pointer surface = mitk::Surface::New(); n2->SetData(surface); n2->SetProperty("name", mitk::StringProperty::New("Node 2 - Surface Node")); mitk::Color color; color.Set(1.0f, 1.0f, 0.0f); n2->SetColor(color); n2->SetProperty("Resection Proposal 1", mitk::GroupTagProperty::New()); mitk::DataStorage::SetOfObjects::Pointer parents2 = mitk::DataStorage::SetOfObjects::New(); parents2->InsertElement(0, n1); // n1 (image node) is source of n2 (surface node) mitk::DataNode::Pointer n3 = mitk::DataNode::New(); // node without data but with name property n3->SetProperty("name", mitk::StringProperty::New("Node 3 - Empty Node")); n3->SetProperty("Resection Proposal 1", mitk::GroupTagProperty::New()); n3->SetProperty("Resection Proposal 2", mitk::GroupTagProperty::New()); mitk::DataStorage::SetOfObjects::Pointer parents3 = mitk::DataStorage::SetOfObjects::New(); parents3->InsertElement(0, n2); // n2 is source of n3 mitk::DataNode::Pointer n4 = mitk::DataNode::New(); // node without data but with color property n4->SetColor(color); n4->SetProperty("Resection Proposal 2", mitk::GroupTagProperty::New()); mitk::DataStorage::SetOfObjects::Pointer parents4 = mitk::DataStorage::SetOfObjects::New(); parents4->InsertElement(0, n2); parents4->InsertElement(1, n3); // n2 and n3 are sources of n4 mitk::DataNode::Pointer n5 = mitk::DataNode::New(); // extra node n5->SetProperty("name", mitk::StringProperty::New("Node 5")); try /* adding objects */ { /* Add an object */ ds->Add(n1, parents1); MITK_TEST_CONDITION_REQUIRED((ds->GetAll()->Size() == 1) && (ds->GetAll()->GetElement(0) == n1), "Testing Adding a new object"); /* Check exception on adding the same object again */ MITK_TEST_OUTPUT(<< "Check exception on adding the same object again: "); MITK_TEST_FOR_EXCEPTION(std::exception, ds->Add(n1, parents1)); MITK_TEST_CONDITION(ds->GetAll()->Size() == 1, "Test if object count is correct after exception"); /* Add an object that has a source object */ ds->Add(n2, parents2); MITK_TEST_CONDITION_REQUIRED(ds->GetAll()->Size() == 2, "Testing Adding an object that has a source object"); /* Add some more objects needed for further tests */ ds->Add(n3, parents3); // n3 object that has name property and one parent ds->Add(n4, parents4); // n4 object that has color property ds->Add(n5); // n5 has no parents MITK_TEST_CONDITION_REQUIRED(ds->GetAll()->Size() == 5, "Adding some more objects needed for further tests"); } catch (...) { - MITK_TEST_FAILED_MSG(<< "Exeption during object creation"); + MITK_TEST_FAILED_MSG(<< "Exception during object creation"); } try /* object retrieval methods */ { /* Requesting all Objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetAll(); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((stlAll.size() == 5) // check if all tree nodes are in resultset && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n5) != stlAll.end()), "Testing GetAll()"); } /* Requesting a named object */ { mitk::NodePredicateProperty::Pointer predicate( mitk::NodePredicateProperty::New("name", mitk::StringProperty::New("Node 2 - Surface Node"))); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n2), "Requesting a named object"); } /* Requesting objects of specific data type */ { mitk::NodePredicateDataType::Pointer predicate(mitk::NodePredicateDataType::New("Image")); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n1), "Requesting objects of specific data type") } /* Requesting objects of specific dimension */ { mitk::NodePredicateDimension::Pointer predicate(mitk::NodePredicateDimension::New(4)); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n1), "Requesting objects of specific dimension") } /* Requesting objects with specific data object */ { mitk::NodePredicateData::Pointer predicate(mitk::NodePredicateData::New(image)); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n1), "Requesting objects with specific data object") } /* Requesting objects with nullptr data */ { mitk::NodePredicateData::Pointer predicate(mitk::NodePredicateData::New(nullptr)); mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 3) && (std::find(all->begin(), all->end(), n3) != all->end()) && (std::find(all->begin(), all->end(), n4) != all->end()) && (std::find(all->begin(), all->end(), n5) != all->end()), "Requesting objects with nullptr data"); } /* Requesting objects that meet a conjunction criteria */ { mitk::NodePredicateDataType::Pointer p1 = mitk::NodePredicateDataType::New("Surface"); mitk::NodePredicateProperty::Pointer p2 = mitk::NodePredicateProperty::New("color", mitk::ColorProperty::New(color)); mitk::NodePredicateAnd::Pointer predicate = mitk::NodePredicateAnd::New(); predicate->AddPredicate(p1); predicate->AddPredicate(p2); // objects must be of datatype "Surface" and have red color (= n2) const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 1) && (all->GetElement(0) == n2), "Requesting objects that meet a conjunction criteria"); } /* Requesting objects that meet a disjunction criteria */ { mitk::NodePredicateDataType::Pointer p1(mitk::NodePredicateDataType::New("Image")); mitk::NodePredicateProperty::Pointer p2( mitk::NodePredicateProperty::New("color", mitk::ColorProperty::New(color))); mitk::NodePredicateOr::Pointer predicate = mitk::NodePredicateOr::New(); predicate->AddPredicate(p1); predicate->AddPredicate(p2); // objects must be of datatype "Surface" or have red color (= n1, n2, n4) const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); MITK_TEST_CONDITION((all->Size() == 3) && (std::find(all->begin(), all->end(), n1) != all->end()) && (std::find(all->begin(), all->end(), n2) != all->end()) && (std::find(all->begin(), all->end(), n4) != all->end()), "Requesting objects that meet a disjunction criteria"); } /* Requesting objects that do not meet a criteria */ { mitk::ColorProperty::Pointer cp = mitk::ColorProperty::New(color); mitk::NodePredicateProperty::Pointer proppred(mitk::NodePredicateProperty::New("color", cp)); mitk::NodePredicateNot::Pointer predicate(mitk::NodePredicateNot::New(proppred)); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(predicate); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 3) // check if correct objects are in resultset && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n5) != stlAll.end()), "Requesting objects that do not meet a criteria"); } /* Requesting *direct* source objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n3, nullptr, true); // Get direct parents of n3 (=n2) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 1) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()), "Requesting *direct* source objects"); } /* Requesting *all* source objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n3, nullptr, false); // Get all parents of n3 (= n1 + n2) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 2) && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()), "Requesting *all* source objects"); // check if n1 and n2 are the resultset } /* Requesting *all* sources of object with multiple parents */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, nullptr, false); // Get all parents of n4 (= n1 + n2 + n3) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 3) && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) // check if n1 and n2 and n3 are the resultset , "Requesting *all* sources of object with multiple parents"); } /* Requesting *direct* derived objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n1, nullptr, true); // Get direct childs of n1 (=n2) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 1) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) // check if n1 is the resultset , "Requesting *direct* derived objects"); } ///* Requesting *direct* derived objects with multiple parents/derivations */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n2, nullptr, true); // Get direct childs of n2 (=n3 + n4) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 2) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) // check if n3 is the resultset && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()) // check if n4 is the resultset , "Requesting *direct* derived objects with multiple parents/derivations"); } //* Requesting *all* derived objects */ { const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n1, nullptr, false); // Get all childs of n1 (=n2, n3, n4) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 3) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()), "Requesting *all* derived objects"); } /* Checking for circular source relationships */ { parents1->InsertElement(0, n4); // make n1 derived from n4 (which is derived from n2, which is derived from n1) const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources( n4, nullptr, false); // Get all parents of n4 (= n1 + n2 + n3, not n4 itself and not multiple versions of the nodes!) std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION( (all->Size() == 3) && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) // check if n1 and n2 and n3 are the resultset , "Checking for circular source relationships"); } ///* Checking for circular derivation relationships can not be performed, because the internal derivations /// datastructure // can not be accessed from the outside. (Therefore it should not be possible to create these circular relations // */ //* Checking GroupTagProperty */ { mitk::GroupTagProperty::Pointer tp = mitk::GroupTagProperty::New(); mitk::NodePredicateProperty::Pointer pred(mitk::NodePredicateProperty::New("Resection Proposal 1", tp)); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(pred); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 2) // check if n2 and n3 are in resultset && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()), "Checking GroupTagProperty"); } /* Checking GroupTagProperty 2 */ { mitk::GroupTagProperty::Pointer tp = mitk::GroupTagProperty::New(); mitk::NodePredicateProperty::Pointer pred(mitk::NodePredicateProperty::New("Resection Proposal 2", tp)); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSubset(pred); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 2) // check if n3 and n4 are in resultset && (std::find(stlAll.begin(), stlAll.end(), n3) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()), "Checking GroupTagProperty 2"); } /* Checking direct sources with condition */ { mitk::NodePredicateDataType::Pointer pred = mitk::NodePredicateDataType::New("Surface"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, pred, true); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 1) // check if n2 is in resultset && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()), "checking direct sources with condition"); } /* Checking all sources with condition */ { mitk::NodePredicateDataType::Pointer pred = mitk::NodePredicateDataType::New("Image"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, pred, false); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 1) // check if n1 is in resultset && (std::find(stlAll.begin(), stlAll.end(), n1) != stlAll.end()), "Checking all sources with condition"); } /* Checking all sources with condition with empty resultset */ { mitk::NodePredicateDataType::Pointer pred = mitk::NodePredicateDataType::New("VesselTree"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetSources(n4, pred, false); MITK_TEST_CONDITION(all->Size() == 0, "Checking all sources with condition with empty resultset"); // check if resultset is empty } /* Checking direct derivations with condition */ { mitk::NodePredicateProperty::Pointer pred = mitk::NodePredicateProperty::New("color"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n1, pred, true); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 1) // check if n2 is in resultset && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()), "Checking direct derivations with condition"); } /* Checking all derivations with condition */ { mitk::NodePredicateProperty::Pointer pred = mitk::NodePredicateProperty::New("color"); const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetDerivations(n1, pred, false); std::vector stlAll = all->CastToSTLConstContainer(); MITK_TEST_CONDITION((all->Size() == 2) // check if n2 and n4 are in resultset && (std::find(stlAll.begin(), stlAll.end(), n2) != stlAll.end()) && (std::find(stlAll.begin(), stlAll.end(), n4) != stlAll.end()), "Checking direct derivations with condition"); } /* Checking named node method */ MITK_TEST_CONDITION(ds->GetNamedNode("Node 2 - Surface Node") == n2, "Checking named node method"); MITK_TEST_CONDITION(ds->GetNamedNode(std::string("Node 2 - Surface Node")) == n2, "Checking named node(std::string) method"); /* Checking named node method with wrong name */ MITK_TEST_CONDITION(ds->GetNamedNode("This name does not exist") == nullptr, "Checking named node method with wrong name"); /* Checking named object method */ MITK_TEST_CONDITION(ds->GetNamedObject("Node 1 - Image Node") == image, "Checking named object method"); MITK_TEST_CONDITION(ds->GetNamedObject(std::string("Node 1 - Image Node")) == image, "Checking named object(std::string) method"); /* Checking named object method with wrong DataType */ MITK_TEST_CONDITION(ds->GetNamedObject("Node 1 - Image Node") == nullptr, "Checking named object method with wrong DataType"); /* Checking named object method with wrong name */ MITK_TEST_CONDITION(ds->GetNamedObject("This name does not exist") == nullptr, "Checking named object method with wrong name"); /* Checking GetNamedDerivedNode with valid name and direct derivation only */ MITK_TEST_CONDITION(ds->GetNamedDerivedNode("Node 2 - Surface Node", n1, true) == n2, "Checking GetNamedDerivedNode with valid name & direct derivation only"); /* Checking GetNamedDerivedNode with invalid Name and direct derivation only */ MITK_TEST_CONDITION(ds->GetNamedDerivedNode("wrong name", n1, true) == nullptr, "Checking GetNamedDerivedNode with invalid name & direct derivation only"); /* Checking GetNamedDerivedNode with invalid Name and direct derivation only */ MITK_TEST_CONDITION(ds->GetNamedDerivedNode("Node 3 - Empty Node", n1, false) == n3, "Checking GetNamedDerivedNode with invalid name & direct derivation only"); /* Checking GetNamedDerivedNode with valid Name but direct derivation only */ MITK_TEST_CONDITION(ds->GetNamedDerivedNode("Node 3 - Empty Node", n1, true) == nullptr, "Checking GetNamedDerivedNode with valid Name but direct derivation only"); /* Checking GetNode with valid predicate */ { mitk::NodePredicateDataType::Pointer p(mitk::NodePredicateDataType::New("Image")); MITK_TEST_CONDITION(ds->GetNode(p) == n1, "Checking GetNode with valid predicate"); } /* Checking GetNode with invalid predicate */ { mitk::NodePredicateDataType::Pointer p(mitk::NodePredicateDataType::New("PointSet")); MITK_TEST_CONDITION(ds->GetNode(p) == nullptr, "Checking GetNode with invalid predicate"); } } // object retrieval methods catch (...) { - MITK_TEST_FAILED_MSG(<< "Exeption during object retrieval (GetXXX() Methods)"); + MITK_TEST_FAILED_MSG(<< "Exception during object retrieval (GetXXX() Methods)"); } try /* object removal methods */ { /* Checking removal of a node without relations */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); int refCountbeforeDS = watcher->GetReferenceCount(); ds->Add(extra); MITK_TEST_CONDITION(ds->GetNamedNode("extra") == extra, "Adding extra node"); ds->Remove(extra); MITK_TEST_CONDITION((ds->GetNamedNode("extra") == nullptr) && (refCountbeforeDS == watcher->GetReferenceCount()), "Checking removal of a node without relations"); extra = nullptr; } /* Checking removal of a node with a parent */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); int refCountbeforeDS = watcher->GetReferenceCount(); ds->Add(extra, n1); // n1 is parent of extra MITK_TEST_CONDITION((ds->GetNamedNode("extra") == extra) && (ds->GetDerivations(n1)->Size() == 2) // n2 and extra should be derived from n1 , "Adding extra node"); ds->Remove(extra); MITK_TEST_CONDITION((ds->GetNamedNode("extra") == nullptr) && (refCountbeforeDS == watcher->GetReferenceCount()) && (ds->GetDerivations(n1)->Size() == 1), "Checking removal of a node with a parent"); extra = nullptr; } /* Checking removal of a node with two parents */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); int refCountbeforeDS = watcher->GetReferenceCount(); mitk::DataStorage::SetOfObjects::Pointer p = mitk::DataStorage::SetOfObjects::New(); p->push_back(n1); p->push_back(n2); ds->Add(extra, p); // n1 and n2 are parents of extra MITK_TEST_CONDITION((ds->GetNamedNode("extra") == extra) && (ds->GetDerivations(n1)->Size() == 2) // n2 and extra should be derived from n1 && (ds->GetDerivations(n2)->Size() == 3), "add extra node"); ds->Remove(extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == nullptr) && (refCountbeforeDS == watcher->GetReferenceCount()) && (ds->GetDerivations(n1)->Size() == 1) // after remove, only n2 should be derived from n1 && (ds->GetDerivations(n2)->Size() == 2) // after remove, only n3 and n4 should be derived from n2 , "Checking removal of a node with two parents"); extra = nullptr; } /* Checking removal of a node with two derived nodes */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); int refCountbeforeDS = watcher->GetReferenceCount(); ds->Add(extra); mitk::DataNode::Pointer d1 = mitk::DataNode::New(); d1->SetProperty("name", mitk::StringProperty::New("d1")); ds->Add(d1, extra); mitk::DataNode::Pointer d2 = mitk::DataNode::New(); d2->SetProperty("name", mitk::StringProperty::New("d2")); ds->Add(d2, extra); MITK_TEST_CONDITION((ds->GetNamedNode("extra") == extra) && (ds->GetNamedNode("d1") == d1) && (ds->GetNamedNode("d2") == d2) && (ds->GetSources(d1)->Size() == 1) // extra should be source of d1 && (ds->GetSources(d2)->Size() == 1) // extra should be source of d2 && (ds->GetDerivations(extra)->Size() == 2) // d1 and d2 should be derived from extra , "add extra node"); ds->Remove(extra); MITK_TEST_CONDITION((ds->GetNamedNode("extra") == nullptr) && (ds->GetNamedNode("d1") == d1) && (ds->GetNamedNode("d2") == d2) && (refCountbeforeDS == watcher->GetReferenceCount()) && (ds->GetSources(d1)->Size() == 0) // after remove, d1 should not have a source anymore && (ds->GetSources(d2)->Size() == 0) // after remove, d2 should not have a source anymore , "Checking removal of a node with two derived nodes"); extra = nullptr; } /* Checking removal of a node with two parents and two derived nodes */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); mitk::ReferenceCountWatcher::Pointer n1watcher = new mitk::ReferenceCountWatcher(n1); int refCountbeforeDS = watcher->GetReferenceCount(); mitk::DataStorage::SetOfObjects::Pointer p = mitk::DataStorage::SetOfObjects::New(); p->push_back(n1); p->push_back(n2); ds->Add(extra, p); // n1 and n2 are parents of extra mitk::DataNode::Pointer d1 = mitk::DataNode::New(); d1->SetProperty("name", mitk::StringProperty::New("d1x")); ds->Add(d1, extra); mitk::DataNode::Pointer d2 = mitk::DataNode::New(); d2->SetProperty("name", mitk::StringProperty::New("d2x")); ds->Add(d2, extra); MITK_TEST_CONDITION((ds->GetNamedNode("extra") == extra) && (ds->GetNamedNode("d1x") == d1) && (ds->GetNamedNode("d2x") == d2) && (ds->GetSources(d1)->Size() == 1) // extra should be source of d1 && (ds->GetSources(d2)->Size() == 1) // extra should be source of d2 && (ds->GetDerivations(n1)->Size() == 2) // n2 and extra should be derived from n1 && (ds->GetDerivations(n2)->Size() == 3) // n3, n4 and extra should be derived from n2 && (ds->GetDerivations(extra)->Size() == 2) // d1 and d2 should be derived from extra , "add extra node"); ds->Remove(extra); MITK_TEST_CONDITION( (ds->GetNamedNode("extra") == nullptr) && (ds->GetNamedNode("d1x") == d1) && (ds->GetNamedNode("d2x") == d2) && (refCountbeforeDS == watcher->GetReferenceCount()) && (ds->GetDerivations(n1)->Size() == 1) // after remove, only n2 should be derived from n1 && (ds->GetDerivations(n2)->Size() == 2) // after remove, only n3 and n4 should be derived from n2 && (ds->GetSources(d1)->Size() == 0) // after remove, d1 should not have a source anymore && (ds->GetSources(d2)->Size() == 0) // after remove, d2 should not have a source anymore , "Checking removal of a node with two parents and two derived nodes"); extra = nullptr; } } catch (...) { - MITK_TEST_FAILED_MSG(<< "Exeption during object removal methods"); + MITK_TEST_FAILED_MSG(<< "Exception during object removal methods"); } /* Checking for node is it's own parent exception */ { MITK_TEST_FOR_EXCEPTION_BEGIN(std::exception); mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::DataStorage::SetOfObjects::Pointer p = mitk::DataStorage::SetOfObjects::New(); p->push_back(n1); p->push_back(extra); // extra is parent of extra!!! ds->Add(extra, p); MITK_TEST_FOR_EXCEPTION_END(std::exception); } /* Checking reference count of node after add and remove */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); extra->SetProperty("name", mitk::StringProperty::New("extra")); mitk::DataStorage::SetOfObjects::Pointer p = mitk::DataStorage::SetOfObjects::New(); p->push_back(n1); p->push_back(n3); ds->Add(extra, p); extra = nullptr; ds->Remove(ds->GetNamedNode("extra")); MITK_TEST_CONDITION(watcher->GetReferenceCount() == 0, "Checking reference count of node after add and remove"); } /* Checking removal of a node with two derived nodes [ dataStorage->GetDerivations( rootNode )] see bug #3426 */ { mitk::DataNode::Pointer extra = mitk::DataNode::New(); extra->SetProperty("name", mitk::StringProperty::New("extra")); ds->Add(extra); mitk::DataNode::Pointer d1y = mitk::DataNode::New(); d1y->SetProperty("name", mitk::StringProperty::New("d1y")); mitk::ReferenceCountWatcher::Pointer watcherD1y = new mitk::ReferenceCountWatcher(d1y); int refCountbeforeDS = watcherD1y->GetReferenceCount(); ds->Add(d1y, extra); mitk::DataNode::Pointer d2y = mitk::DataNode::New(); d2y->SetProperty("name", mitk::StringProperty::New("d2y")); ds->Add(d2y, extra); MITK_TEST_CONDITION((ds->GetNamedNode("extra") == extra) && (ds->GetNamedNode("d1y") == d1y) && (ds->GetNamedNode("d2y") == d2y) && (ds->GetSources(d1y)->Size() == 1) // extra should be source of d1y && (ds->GetSources(d2y)->Size() == 1) // extra should be source of d2y && (ds->GetDerivations(extra)->Size() == 2) // d1y and d2y should be derived from extra , "add extra node"); ds->Remove(ds->GetDerivations(extra)); MITK_TEST_CONDITION((ds->GetNamedNode("extra") == extra) && (ds->GetNamedNode("d1y") == nullptr) // d1y should be nullptr now && (ds->GetNamedNode("d2y") == nullptr) // d2y should be nullptr now && (refCountbeforeDS == watcherD1y->GetReferenceCount()), "Checking removal of subset of two derived nodes from one parent node"); ds->Remove(extra); MITK_TEST_CONDITION((ds->GetNamedNode("extra") == nullptr), "Checking removal of a parent node"); extra = nullptr; } /* Checking GetGrouptags() */ { const std::set groupTags = ds->GetGroupTags(); MITK_TEST_CONDITION((groupTags.size() == 2) && (std::find(groupTags.begin(), groupTags.end(), "Resection Proposal 1") != groupTags.end()) && (std::find(groupTags.begin(), groupTags.end(), "Resection Proposal 2") != groupTags.end()), "Checking GetGrouptags()"); } /* Checking Event handling */ DSEventReceiver listener; try { ds->AddNodeEvent += mitk::MessageDelegate1(&listener, &DSEventReceiver::OnAdd); ds->RemoveNodeEvent += mitk::MessageDelegate1(&listener, &DSEventReceiver::OnRemove); mitk::DataNode::Pointer extra = mitk::DataNode::New(); mitk::ReferenceCountWatcher::Pointer watcher = new mitk::ReferenceCountWatcher(extra); ds->Add(extra); MITK_TEST_CONDITION(listener.m_NodeAdded == extra.GetPointer(), "Checking AddEvent"); ds->Remove(extra); MITK_TEST_CONDITION(listener.m_NodeRemoved == extra.GetPointer(), "Checking RemoveEvent"); /* RemoveListener */ ds->AddNodeEvent -= mitk::MessageDelegate1(&listener, &DSEventReceiver::OnAdd); ds->RemoveNodeEvent -= mitk::MessageDelegate1(&listener, &DSEventReceiver::OnRemove); listener.m_NodeAdded = nullptr; listener.m_NodeRemoved = nullptr; ds->Add(extra); ds->Remove(extra); MITK_TEST_CONDITION((listener.m_NodeRemoved == nullptr) && (listener.m_NodeAdded == nullptr), "Checking RemoveListener"); std::cout << "Pointer handling after event handling: " << std::flush; extra = nullptr; // delete reference to the node. its memory should be freed now MITK_TEST_CONDITION(watcher->GetReferenceCount() == 0, "Pointer handling after event handling"); } catch (...) { /* cleanup */ ds->AddNodeEvent -= mitk::MessageDelegate1(&listener, &DSEventReceiver::OnAdd); ds->RemoveNodeEvent -= mitk::MessageDelegate1(&listener, &DSEventReceiver::OnRemove); MITK_TEST_FAILED_MSG(<< "Exception during object removal methods"); } // Checking ComputeBoundingGeometry3D method*/ const mitk::DataStorage::SetOfObjects::ConstPointer all = ds->GetAll(); auto geometry = ds->ComputeBoundingGeometry3D(); MITK_TEST_CONDITION(geometry->CountTimeSteps() == 4, "Test for number or time steps with ComputeBoundingGeometry()"); mitk::TimeBounds timebounds = geometry->GetTimeBounds(); MITK_TEST_CONDITION((timebounds[0] == 0) && (timebounds[1] == 4), "Test for timebounds with ComputeBoundingGeometry()"); for (unsigned int i = 0; i < geometry->CountTimeSteps(); i++) { mitk::BaseGeometry::Pointer subGeometry = geometry->GetGeometryForTimeStep(i); mitk::TimeBounds bounds = geometry->GetTimeBounds(i); MITK_TEST_CONDITION((bounds[0] == i) && (bounds[1] == i + 1), "Test for timebounds of geometry at different time steps with ComputeBoundingGeometry()"); } geometry = ds->ComputeBoundingGeometry3D(all); MITK_TEST_CONDITION(geometry->CountTimeSteps() == 4, "Test for number or time steps with ComputeBoundingGeometry(allNodes)"); timebounds = geometry->GetTimeBounds(); MITK_TEST_CONDITION((timebounds[0] == 0) && (timebounds[1] == 4), "Test for timebounds with ComputeBoundingGeometry(allNodes)"); for (unsigned int i = 0; i < geometry->CountTimeSteps(); i++) { mitk::BaseGeometry::Pointer subGeometry = geometry->GetGeometryForTimeStep(i); mitk::TimeBounds bounds = geometry->GetTimeBounds(i); MITK_TEST_CONDITION((bounds[0] == i) && (bounds[1] == i + 1), "Test for timebounds of geometry at different time steps with ComputeBoundingGeometry()"); } // test for thread safety of DataStorage try { mitk::StandaloneDataStorage::Pointer standaloneDataStorage = mitk::StandaloneDataStorage::New(); ItkDeleteEventListener listener(standaloneDataStorage); { mitk::DataNode::Pointer emptyNode = mitk::DataNode::New(); mitk::DataNode *pEmptyNode = emptyNode; listener.SetNode(emptyNode); standaloneDataStorage->Add(emptyNode); emptyNode = nullptr; // emptyNode is still alive because standaloneDataStorage // owns it standaloneDataStorage->Remove(pEmptyNode); // this should not freeze the whole thing } } catch (...) { MITK_TEST_FAILED_MSG(<< "Exception during testing DataStorage thread safe"); } /* Clear DataStorage */ ds->Remove(ds->GetAll()); MITK_TEST_CONDITION(ds->GetAll()->Size() == 0, "Checking Clear DataStorage"); } diff --git a/Modules/Core/test/mitkEventConfigTest.cpp b/Modules/Core/test/mitkEventConfigTest.cpp index 10687260f9..35eeb3a5ce 100644 --- a/Modules/Core/test/mitkEventConfigTest.cpp +++ b/Modules/Core/test/mitkEventConfigTest.cpp @@ -1,169 +1,169 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkEventConfig.h" #include "mitkInteractionEvent.h" #include "mitkInteractionEventConst.h" #include "mitkInteractionKeyEvent.h" #include "mitkMouseMoveEvent.h" #include "mitkMousePressEvent.h" #include "mitkMouseReleaseEvent.h" #include "mitkMouseWheelEvent.h" #include "mitkPropertyList.h" #include "mitkTestingMacros.h" #include "usGetModuleContext.h" #include "usModule.h" #include #include #include int mitkEventConfigTest(int argc, char *argv[]) { MITK_TEST_BEGIN("EventConfig") if (argc != 2) { MITK_ERROR << "Test needs configuration test file as parameter."; return -1; } /* * Loads a test a Config file and test if Config is build up correctly, * and if mapping from mitkEvents to EventVariant names works properly. * Indirectly this also tests the EventFactory Class, since we also test if the events have been constructed properly. * * The configuration object is constructed in three different ways, * each one is tested here. */ - // Construction using compiled-in resrouces: + // Construction using compiled-in resources: us::Module *module = us::GetModuleContext()->GetModule(); mitk::EventConfig newConfig("StatemachineConfigTest.xml", module); MITK_TEST_CONDITION_REQUIRED(newConfig.IsValid() == true, "01 Check if file can be loaded and is valid"); /* * Test the global properties: * Test if stored values match the ones in the test config file. */ mitk::PropertyList::Pointer properties = newConfig.GetAttributes(); std::string prop1, prop2; MITK_TEST_CONDITION_REQUIRED(properties->GetStringProperty("property1", prop1) && prop1 == "yes" && properties->GetStringProperty("scrollModus", prop2) && prop2 == "leftright", "02 Check Global Properties"); /* * Check if Events get mapped to the proper Variants */ mitk::Point2D pos; mitk::MousePressEvent::Pointer mpe1 = mitk::MousePressEvent::New(nullptr, pos, mitk::InteractionEvent::MiddleMouseButton | mitk::InteractionEvent::LeftMouseButton, mitk::InteractionEvent::ControlKey | mitk::InteractionEvent::AltKey, mitk::InteractionEvent::LeftMouseButton); mitk::MousePressEvent::Pointer standard1 = mitk::MousePressEvent::New(nullptr, pos, mitk::InteractionEvent::LeftMouseButton, mitk::InteractionEvent::NoKey, mitk::InteractionEvent::LeftMouseButton); mitk::MouseMoveEvent::Pointer mme1 = mitk::MouseMoveEvent::New(nullptr, pos, mitk::InteractionEvent::RightMouseButton | mitk::InteractionEvent::LeftMouseButton, mitk::InteractionEvent::ShiftKey); mitk::MouseMoveEvent::Pointer mme2 = mitk::MouseMoveEvent::New(nullptr, pos, mitk::InteractionEvent::RightMouseButton, mitk::InteractionEvent::ShiftKey); mitk::MouseWheelEvent::Pointer mwe1 = mitk::MouseWheelEvent::New( nullptr, pos, mitk::InteractionEvent::RightMouseButton, mitk::InteractionEvent::ShiftKey, -2); mitk::InteractionKeyEvent::Pointer ke = mitk::InteractionKeyEvent::New(nullptr, "l", mitk::InteractionEvent::NoKey); MITK_TEST_CONDITION_REQUIRED(newConfig.GetMappedEvent(mpe1.GetPointer()) == "Variant1" && newConfig.GetMappedEvent(standard1.GetPointer()) == "Standard1" && newConfig.GetMappedEvent(mme1.GetPointer()) == "Move2" && newConfig.GetMappedEvent(ke.GetPointer()) == "Key1" && newConfig.GetMappedEvent(mme2.GetPointer()) == "" // does not exist in file , "03 Check Mouse- and Key-Events "); // Construction providing a input stream std::ifstream configStream(argv[1]); mitk::EventConfig newConfig2(configStream); MITK_TEST_CONDITION_REQUIRED(newConfig2.IsValid() == true, "01 Check if file can be loaded and is valid"); /* * Test the global properties: * Test if stored values match the ones in the test config file. */ properties = newConfig2.GetAttributes(); MITK_TEST_CONDITION_REQUIRED(properties->GetStringProperty("property1", prop1) && prop1 == "yes" && properties->GetStringProperty("scrollModus", prop2) && prop2 == "leftright", "02 Check Global Properties"); /* * Check if Events get mapped to the proper Variants */ MITK_TEST_CONDITION_REQUIRED(newConfig2.GetMappedEvent(mpe1.GetPointer()) == "Variant1" && newConfig2.GetMappedEvent(standard1.GetPointer()) == "Standard1" && newConfig2.GetMappedEvent(mme1.GetPointer()) == "Move2" && newConfig2.GetMappedEvent(ke.GetPointer()) == "Key1" && newConfig2.GetMappedEvent(mme2.GetPointer()) == "" // does not exist in file , "03 Check Mouse- and Key-Events "); // always end with this! // Construction providing a property list std::vector configDescription; mitk::PropertyList::Pointer propertyList1 = mitk::PropertyList::New(); propertyList1->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass().c_str(), "MousePressEvent"); propertyList1->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant().c_str(), "MousePressEventVariant"); propertyList1->SetStringProperty("Modifiers", "CTRL,ALT"); configDescription.push_back(propertyList1); mitk::PropertyList::Pointer propertyList2 = mitk::PropertyList::New(); propertyList2->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass().c_str(), "MOUSERELEASEEVENT"); propertyList2->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant().c_str(), "MouseReleaseEventVariant"); propertyList2->SetStringProperty("Modifiers", "SHIFT"); configDescription.push_back(propertyList2); mitk::PropertyList::Pointer propertyList3 = mitk::PropertyList::New(); propertyList3->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventClass().c_str(), "MOUSERELEASEEVENT"); propertyList3->SetStringProperty(mitk::InteractionEventConst::xmlParameterEventVariant().c_str(), "MouseReleaseEventVariant"); propertyList3->SetStringProperty("Modifiers", "ALT"); configDescription.push_back(propertyList3); mitk::EventConfig newConfig3(configDescription); mitk::MousePressEvent::Pointer mousePress1 = mitk::MousePressEvent::New(nullptr, pos, mitk::InteractionEvent::NoButton, mitk::InteractionEvent::AltKey | mitk::InteractionEvent::ControlKey, mitk::InteractionEvent::NoButton); mitk::MouseReleaseEvent::Pointer mouseRelease1 = mitk::MouseReleaseEvent::New( nullptr, pos, mitk::InteractionEvent::NoButton, mitk::InteractionEvent::ShiftKey, mitk::InteractionEvent::NoButton); // create a second event with the same name but different modifiers... mitk::MouseReleaseEvent::Pointer mouseRelease2 = mitk::MouseReleaseEvent::New( nullptr, pos, mitk::InteractionEvent::NoButton, mitk::InteractionEvent::AltKey, mitk::InteractionEvent::NoButton); MITK_TEST_CONDITION_REQUIRED(newConfig3.GetMappedEvent(mousePress1.GetPointer()) == "MousePressEventVariant" && newConfig3.GetMappedEvent(mouseRelease1.GetPointer()) == "MouseReleaseEventVariant" && newConfig3.GetMappedEvent(mouseRelease2.GetPointer()) == "MouseReleaseEventVariant", "04 Check Mouseevents from PropertyLists"); MITK_TEST_END() } diff --git a/Modules/Core/test/mitkExceptionTest.cpp b/Modules/Core/test/mitkExceptionTest.cpp index ca22e0a12f..416d085c1c 100644 --- a/Modules/Core/test/mitkExceptionTest.cpp +++ b/Modules/Core/test/mitkExceptionTest.cpp @@ -1,365 +1,365 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Testing #include "mitkTestFixture.h" #include "mitkTestingMacros.h" // std includes #include // MITK includes #include "mitkException.h" #include "mitkExceptionMacro.h" #include "mitkTestingMacros.h" #include // ITK includes #include #include // VTK includes #include class SpecializedTestException : public mitk::Exception { public: mitkExceptionClassMacro(SpecializedTestException, mitk::Exception); }; class mitkExceptionTestSuite : public itk::Object, public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkExceptionTestSuite); MITK_TEST(TestExceptionConstructor_Success); MITK_TEST(TestSpecializedExceptionConstructor_Success); MITK_TEST(TestExceptionMessageStreamAddingString_Success); MITK_TEST(TestExceptionMessageStreamAddingSingleChars_Success); MITK_TEST(TestExceptionMessageStreamAddingObject_Success); MITK_TEST(TestSpecializedExceptionMessageStreamAddingString); MITK_TEST(TestExceptionMessageStreamThrowing_Success); MITK_TEST(TestMitkThrowMacroThrowing_Success); MITK_TEST(TestMitkThrowMacroMessage_Success); MITK_TEST(TestMitkThrowMacroException_Success); MITK_TEST(TestMitkThrowMacroSpezcializedException); MITK_TEST(TestGetNumberOfRethrows_Success); MITK_TEST(TestGetRethrowDataWithNegativNumber_Success); MITK_TEST(TestGetRethrowDataWithNumberZero_Success); MITK_TEST(TestGetRethrowDataWithNumberOne_Success); MITK_TEST(TestAddRethrowData_Success); MITK_TEST(TestFirstRethrowDataAreStoredProperly_Success); MITK_TEST(TestSecondRethrowDataAreStoredProperly_Success); MITK_TEST(TestRethrowMacro_Success); CPPUNIT_TEST_SUITE_END(); private: bool m_ExceptionThrown; std::string m_MessageText; std::string m_Message; std::string m_File; int m_Line; mitk::Exception m_E = mitk::Exception("test.cpp", 155, "", ""); mitk::Exception m_MyException = mitk::Exception("testfile.cpp", 111, "testmessage"); public: mitkClassMacroItkParent(mitkExceptionTestSuite, itk::Object); itkFactorylessNewMacro(Self) itkCloneMacro(Self) void throwExceptionManually() // this method is ONLY to test the constructor and no code example // normally exceptions should only be thrown by using the exception macro! { throw mitk::Exception("test.cpp", 155, "", ""); } void throwSpecializedExceptionManually() // this method is ONLY to test the constructor and no code example // normally exceptions should only be thrown by using the exception macro! { throw SpecializedTestException("test.cpp", 155, "", ""); } void throwExceptionManually(std::string message1, std::string message2) // this method is ONLY to test methods of mitk::Exception and no code example // normally exceptions should only be thrown by using the exception macro! { throw mitk::Exception("testfile.cpp", 155, message1.c_str(), "") << message2; } - void throwExceptionWithThrowMacro() { mitkThrow() << "TEST EXCEPION THROWING WITH mitkThrow()"; } + void throwExceptionWithThrowMacro() { mitkThrow() << "TEST EXCEPTION THROWING WITH mitkThrow()"; } void throwExceptionWithThrowMacro(std::string message) { mitkThrow() << message.c_str(); } void throwSpecializedExceptionWithThrowMacro(std::string message) { mitkThrowException(mitk::Exception) << message; } void throwSpecializedExceptionWithThrowMacro2(std::string message) { mitkThrowException(SpecializedTestException) << message; } void reThrowExceptionWithReThrowMacro(std::string messageThrow, std::string messageReThrow) { try { throwExceptionWithThrowMacro(messageThrow); } catch (mitk::Exception &e) { mitkReThrow(e) << messageReThrow; } } void setUp() override { m_ExceptionThrown = false; m_MessageText = ""; m_Message = "invalid"; m_File = "invalid"; m_Line = -1; } void tearDown() override { m_ExceptionThrown = false; m_MessageText = ""; m_Message = ""; m_File = ""; m_Line = 0; } void TestExceptionConstructor_Success() { try { this->throwExceptionManually(); } catch (const mitk::Exception &) { m_ExceptionThrown = true; } CPPUNIT_ASSERT_MESSAGE("Testing constructor of mitkException", m_ExceptionThrown); } void TestSpecializedExceptionConstructor_Success() { try { this->throwSpecializedExceptionManually(); } catch (const SpecializedTestException &) { m_ExceptionThrown = true; } CPPUNIT_ASSERT_MESSAGE("Testing constructor specialized exception (deriving from mitkException)", m_ExceptionThrown); } //##### this methods are ONLY to test the streaming operators of the exceptions and //##### NO code example. Please do not instantiate exceptions by yourself in normal code! //##### Normally exceptions should only be thrown by using the exception macro! void TestExceptionMessageStreamAddingString_Success() { m_MyException << " and additional stream"; CPPUNIT_ASSERT_MESSAGE("Testing mitkException message stream (adding std::string)", m_MyException.GetDescription() == std::string("testmessage and additional stream")); } void TestExceptionMessageStreamAddingSingleChars_Success() { m_MyException.SetDescription("testmessage2"); m_MyException << ' ' << 'a' << 'n' << 'd' << ' ' << 'c' << 'h' << 'a' << 'r' << 's'; CPPUNIT_ASSERT_MESSAGE("Testing mitkException message stream (adding single chars)", m_MyException.GetDescription() == std::string("testmessage2 and chars")); } void TestExceptionMessageStreamAddingObject_Success() { m_MyException.SetDescription("testmessage3"); m_MyException << m_MyException; // adding the object itself makes no sense but should work CPPUNIT_ASSERT_MESSAGE("Testing mitkException message stream (adding object)", m_MyException.GetDescription() != std::string("")); } void TestSpecializedExceptionMessageStreamAddingString() { SpecializedTestException mySpecializedException = SpecializedTestException("testfile.cpp", 111, "testmessage", "test"); mySpecializedException << " and additional stream"; CPPUNIT_ASSERT_MESSAGE("Testing specialized exception message stream (adding std::string)", mySpecializedException.GetDescription() == std::string("testmessage and additional stream")); } void TestExceptionMessageStreamThrowing_Success() { std::string thrownMessage = ""; try { this->throwExceptionManually("message1", " and message2"); } catch (const mitk::Exception &e) { thrownMessage = e.GetDescription(); m_ExceptionThrown = true; } CPPUNIT_ASSERT_MESSAGE("Testing throwing and streaming of mitk::Exception together.", m_ExceptionThrown && (thrownMessage == std::string("message1 and message2"))); } void TestMitkThrowMacroThrowing_Success() { // case 1: test throwing try { this->throwExceptionWithThrowMacro(); } catch (const mitk::Exception &) { m_ExceptionThrown = true; } CPPUNIT_ASSERT_MESSAGE("Testing mitkThrow()", m_ExceptionThrown); } void TestMitkThrowMacroMessage_Success() { // case 2: test message text try { this->throwExceptionWithThrowMacro("test123"); } catch (const mitk::Exception &e) { m_ExceptionThrown = true; m_MessageText = e.GetDescription(); } CPPUNIT_ASSERT_MESSAGE("Testing message test of mitkThrow()", (m_ExceptionThrown && (m_MessageText == "test123"))); } void TestMitkThrowMacroException_Success() { // case 3: specialized exception / command mitkThrow(mitk::Exception) try { this->throwSpecializedExceptionWithThrowMacro("test123"); } catch (const mitk::Exception &e) { m_ExceptionThrown = true; m_MessageText = e.GetDescription(); } CPPUNIT_ASSERT_MESSAGE("Testing special exception with mitkThrow(mitk::Exception)", m_ExceptionThrown && m_MessageText == "test123"); } void TestMitkThrowMacroSpezcializedException() { // case 4: specialized exception / command mitkThrow(mitk::SpecializedException) try { this->throwSpecializedExceptionWithThrowMacro2("test123"); } catch (const SpecializedTestException &e) { m_ExceptionThrown = true; m_MessageText = e.GetDescription(); } CPPUNIT_ASSERT_MESSAGE("Testing special exception with mitkThrow(mitk::SpecializedException)", m_ExceptionThrown && m_MessageText == "test123"); } //##### this methods are ONLY to test methods of mitk::Exception and no code example //##### normally exceptions should only be instantiated and thrown by using the exception macros! void TestGetNumberOfRethrows_Success() { // first: testing rethrow information methods, when no information is stored // case 1.1: method GetNumberOfRethrows() CPPUNIT_ASSERT_MESSAGE("Testing GetNumberOfRethrows() with empty rethrow information", m_E.GetNumberOfRethrows() == 0); } void TestGetRethrowDataWithNegativNumber_Success() { // case 1.2: GetRethrowData() with negative number m_E.GetRethrowData(-1, m_File, m_Line, m_Message); CPPUNIT_ASSERT_MESSAGE("Testing GetRethrowData() with invalid rethrow number (negative).", ((m_File == "") && (m_Line == 0) && (m_Message == ""))); } void TestGetRethrowDataWithNumberZero_Success() { // case 1.3: GetRethrowData() with number 0 m_E.GetRethrowData(0, m_File, m_Line, m_Message); CPPUNIT_ASSERT_MESSAGE("Testing GetRethrowData() with non-existing rethrow number (0).", ((m_File == "") && (m_Line == 0) && (m_Message == ""))); } void TestGetRethrowDataWithNumberOne_Success() { // case 1.4: GetRethrowData() with number 1 m_E.GetRethrowData(1, m_File, m_Line, m_Message); CPPUNIT_ASSERT_MESSAGE("Testing GetRethrowData() with non-existing rethrow number (1).", ((m_File == "") && (m_Line == 0) && (m_Message == ""))); } void TestAddRethrowData_Success() { // second: add rethrow data m_E.AddRethrowData("test2.cpp", 10, "Rethrow one"); CPPUNIT_ASSERT_MESSAGE("Testing adding of rethrow data.", m_E.GetNumberOfRethrows() == 1); m_E.AddRethrowData("test3.cpp", 15, "Rethrow two"); CPPUNIT_ASSERT_MESSAGE("Testing adding of more rethrow data.", m_E.GetNumberOfRethrows() == 2); } void TestFirstRethrowDataAreStoredProperly_Success() { // third: test if this rethrow data was stored properly m_E.AddRethrowData("test2.cpp", 10, "Rethrow one"); m_E.GetRethrowData(0, m_File, m_Line, m_Message); CPPUNIT_ASSERT_MESSAGE("Testing stored information of first rethrow.", ((m_File == "test2.cpp") && (m_Line == 10) && (m_Message == "Rethrow one"))); } void TestSecondRethrowDataAreStoredProperly_Success() { m_E.AddRethrowData("test2.cpp", 10, "Rethrow one"); m_E.AddRethrowData("test3.cpp", 15, "Rethrow two"); m_E.GetRethrowData(1, m_File, m_Line, m_Message); CPPUNIT_ASSERT_MESSAGE("Testing stored information of second rethrow.", ((m_File == "test3.cpp") && (m_Line == 15) && (m_Message == "Rethrow two"))); } void TestRethrowMacro_Success() { // case 1: test throwing try { this->reThrowExceptionWithReThrowMacro("Test original message.", "Test rethrow message."); } catch (const mitk::Exception &e) { m_Message = e.GetDescription(); m_ExceptionThrown = true; } CPPUNIT_ASSERT_MESSAGE("Testing mitkReThrow()", m_ExceptionThrown); CPPUNIT_ASSERT_MESSAGE("Testing message/descriprion after rethrow.", m_Message == "Test original message.Test rethrow message."); } }; MITK_TEST_SUITE_REGISTRATION(mitkException) diff --git a/Modules/Core/test/mitkExtractSliceFilterTest.cpp b/Modules/Core/test/mitkExtractSliceFilterTest.cpp index 6bb27c7e6b..3dc6ef8139 100644 --- a/Modules/Core/test/mitkExtractSliceFilterTest.cpp +++ b/Modules/Core/test/mitkExtractSliceFilterTest.cpp @@ -1,1069 +1,1069 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // use this to create the test volume on the fly #define CREATE_VOLUME // use this to save the created volume //#define SAVE_VOLUME // use this to calculate the error from the sphere mathematical model to our pixel based one //#define CALC_TESTFAILURE_DEVIATION // use this to render an oblique slice through a specified image //#define SHOW_SLICE_IN_RENDER_WINDOW // use this to have infos printed in mbilog //#define EXTRACTOR_DEBUG /*these are the deviations calculated by the function CalcTestFailureDeviation (see for details)*/ #define Testfailure_Deviation_Mean_128 0.853842 #define Testfailure_Deviation_Volume_128 0.145184 #define Testfailure_Deviation_Diameter_128 1.5625 #define Testfailure_Deviation_Mean_256 0.397693 #define Testfailure_Deviation_Volume_256 0.0141357 #define Testfailure_Deviation_Diameter_256 0.78125 #define Testfailure_Deviation_Mean_512 0.205277 #define Testfailure_Deviation_Volume_512 0.01993 #define Testfailure_Deviation_Diameter_512 0.390625 class mitkExtractSliceFilterTestClass { public: static void TestSlice(mitk::PlaneGeometry *planeGeometry, std::string testname) { TestPlane = planeGeometry; TestName = testname; mitk::ScalarType centerCoordValue = TestvolumeSize / 2.0; mitk::ScalarType center[3] = {centerCoordValue, centerCoordValue, centerCoordValue}; mitk::Point3D centerIndex(center); double radius = TestvolumeSize / 4.0; if (TestPlane->Distance(centerIndex) >= radius) return; // outside sphere // feed ExtractSliceFilter mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(); slicer->SetInput(TestVolume); slicer->SetWorldGeometry(TestPlane); slicer->Update(); MITK_TEST_CONDITION_REQUIRED(slicer->GetOutput() != nullptr, "Extractor returned a slice"); mitk::Image::Pointer reslicedImage = slicer->GetOutput(); AccessFixedDimensionByItk(reslicedImage, TestSphereRadiusByItk, 2); AccessFixedDimensionByItk(reslicedImage, TestSphereAreaByItk, 2); /* double devArea, devDiameter; if(TestvolumeSize == 128.0){ devArea = Testfailure_Deviation_Volume_128; devDiameter = Testfailure_Deviation_Diameter_128; } else if(TestvolumeSize == 256.0){devArea = Testfailure_Deviation_Volume_256; devDiameter = Testfailure_Deviation_Diameter_256;} else if (TestvolumeSize == 512.0){devArea = Testfailure_Deviation_Volume_512; devDiameter = Testfailure_Deviation_Diameter_512;} else{devArea = Testfailure_Deviation_Volume_128; devDiameter = Testfailure_Deviation_Diameter_128;} */ std::string areatestName = TestName.append(" area"); std::string diametertestName = TestName.append(" testing diameter"); // TODO think about the deviation, 1% makes no sense at all MITK_TEST_CONDITION(std::abs(100 - testResults.percentageAreaCalcToPixel) < 1, areatestName); MITK_TEST_CONDITION(std::abs(100 - testResults.percentageRadiusToPixel) < 1, diametertestName); #ifdef EXTRACTOR_DEBUG MITK_INFO << TestName << " >>> " << "planeDistanceToSphereCenter: " << testResults.planeDistanceToSphereCenter; MITK_INFO << "area in pixels: " << testResults.areaInPixel << " <-> area in mm: " << testResults.areaCalculated << " = " << testResults.percentageAreaCalcToPixel << "%"; MITK_INFO << "calculated diameter: " << testResults.diameterCalculated << " <-> diameter in mm: " << testResults.diameterInMM << " <-> diameter in pixel: " << testResults.diameterInPixel << " = " << testResults.percentageRadiusToPixel << "%"; #endif } /* * get the radius of the slice of a sphere based on pixel distance from edge to edge of the circle. */ template static void TestSphereRadiusByItk(itk::Image *inputImage) { typedef itk::Image InputImageType; // set the index to the middle of the image's edge at x and y axis typename InputImageType::IndexType currentIndexX; currentIndexX[0] = (int)(TestvolumeSize / 2.0); currentIndexX[1] = 0; typename InputImageType::IndexType currentIndexY; currentIndexY[0] = 0; currentIndexY[1] = (int)(TestvolumeSize / 2.0); // remember the last pixel value double lastValueX = inputImage->GetPixel(currentIndexX); double lastValueY = inputImage->GetPixel(currentIndexY); // storage for the index marks std::vector indicesX; std::vector indicesY; /*Get four indices on the edge of the circle*/ while (currentIndexX[1] < TestvolumeSize && currentIndexX[0] < TestvolumeSize) { // move x direction currentIndexX[1] += 1; // move y direction currentIndexY[0] += 1; if (inputImage->GetPixel(currentIndexX) > lastValueX) { // mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexX[0]; markIndex[1] = currentIndexX[1]; indicesX.push_back(markIndex); } else if (inputImage->GetPixel(currentIndexX) < lastValueX) { // mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexX[0]; markIndex[1] = currentIndexX[1] - 1; // value inside the sphere indicesX.push_back(markIndex); } if (inputImage->GetPixel(currentIndexY) > lastValueY) { // mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexY[0]; markIndex[1] = currentIndexY[1]; indicesY.push_back(markIndex); } else if (inputImage->GetPixel(currentIndexY) < lastValueY) { // mark the current index typename InputImageType::IndexType markIndex; markIndex[0] = currentIndexY[0]; markIndex[1] = currentIndexY[1] - 1; // value inside the sphere indicesY.push_back(markIndex); } // found both marks? if (indicesX.size() == 2 && indicesY.size() == 2) break; // the new 'last' values lastValueX = inputImage->GetPixel(currentIndexX); lastValueY = inputImage->GetPixel(currentIndexY); } /* *If we are here we found the four marks on the edge of the circle. *For the case our plane is rotated and shifted, we have to calculate the center of the circle, *else the center is the intersection of both straight lines between the marks. *When we have the center, the diameter of the circle will be checked to the reference value(math!). */ // each distance from the first mark of each direction to the center of the straight line between the marks double distanceToCenterX = std::abs(indicesX[0][1] - indicesX[1][1]) / 2.0; // double distanceToCenterY = std::abs(indicesY[0][0] - indicesY[1][0]) / 2.0; // the center of the straight lines typename InputImageType::IndexType centerX; // typename InputImageType::IndexType centerY; centerX[0] = indicesX[0][0]; centerX[1] = indicesX[0][1] + distanceToCenterX; // TODO think about implicit cast to int. this is not the real center of the image, which could be between two // pixels // centerY[0] = indicesY[0][0] + distanceToCenterY; // centerY[1] = inidcesY[0][1]; typename InputImageType::IndexType currentIndex(centerX); lastValueX = inputImage->GetPixel(currentIndex); long sumpixels = 0; std::vector diameterIndices; // move up while (currentIndex[1] < TestvolumeSize) { currentIndex[1] += 1; if (inputImage->GetPixel(currentIndex) != lastValueX) { typename InputImageType::IndexType markIndex; markIndex[0] = currentIndex[0]; markIndex[1] = currentIndex[1] - 1; diameterIndices.push_back(markIndex); break; } sumpixels++; lastValueX = inputImage->GetPixel(currentIndex); } currentIndex[1] -= sumpixels; // move back to center to go in the other direction lastValueX = inputImage->GetPixel(currentIndex); // move down while (currentIndex[1] >= 0) { currentIndex[1] -= 1; if (inputImage->GetPixel(currentIndex) != lastValueX) { typename InputImageType::IndexType markIndex; markIndex[0] = currentIndex[0]; markIndex[1] = currentIndex[1]; // outside sphere because we want to calculate the distance from edge to edge diameterIndices.push_back(markIndex); break; } sumpixels++; lastValueX = inputImage->GetPixel(currentIndex); } /* *Now sumpixels should be the apromximate diameter of the circle. This is checked with the calculated diameter from *the plane transformation(math). */ mitk::Point3D volumeCenter; volumeCenter[0] = volumeCenter[1] = volumeCenter[2] = TestvolumeSize / 2.0; double planeDistanceToSphereCenter = TestPlane->Distance(volumeCenter); double sphereRadius = TestvolumeSize / 4.0; // calculate the radius of the circle cut from the sphere by the plane double diameter = 2.0 * std::sqrt(std::pow(sphereRadius, 2) - std::pow(planeDistanceToSphereCenter, 2)); double percentageRadiusToPixel = 100 / diameter * sumpixels; /* *calculate the radius in mm by the both marks of the center line by using the world coordinates */ // get the points as 3D coordinates mitk::Vector3D diameterPointRight, diameterPointLeft; diameterPointRight[2] = diameterPointLeft[2] = 0.0; diameterPointLeft[0] = diameterIndices[0][0]; diameterPointLeft[1] = diameterIndices[0][1]; diameterPointRight[0] = diameterIndices[1][0]; diameterPointRight[1] = diameterIndices[1][1]; // transform to worldcoordinates TestVolume->GetGeometry()->IndexToWorld(diameterPointLeft, diameterPointLeft); TestVolume->GetGeometry()->IndexToWorld(diameterPointRight, diameterPointRight); // euklidian distance double diameterInMM = ((diameterPointLeft * -1.0) + diameterPointRight).GetNorm(); testResults.diameterInMM = diameterInMM; testResults.diameterCalculated = diameter; testResults.diameterInPixel = sumpixels; testResults.percentageRadiusToPixel = percentageRadiusToPixel; testResults.planeDistanceToSphereCenter = planeDistanceToSphereCenter; } /*brute force the area pixel by pixel*/ template static void TestSphereAreaByItk(itk::Image *inputImage) { typedef itk::Image InputImageType; typedef itk::ImageRegionConstIterator ImageIterator; ImageIterator imageIterator(inputImage, inputImage->GetLargestPossibleRegion()); imageIterator.GoToBegin(); int sumPixelsInArea = 0; while (!imageIterator.IsAtEnd()) { if (inputImage->GetPixel(imageIterator.GetIndex()) == pixelValueSet) sumPixelsInArea++; ++imageIterator; } mitk::Point3D volumeCenter; volumeCenter[0] = volumeCenter[1] = volumeCenter[2] = TestvolumeSize / 2.0; double planeDistanceToSphereCenter = TestPlane->Distance(volumeCenter); double sphereRadius = TestvolumeSize / 4.0; // calculate the radius of the circle cut from the sphere by the plane double radius = std::sqrt(std::pow(sphereRadius, 2) - std::pow(planeDistanceToSphereCenter, 2)); double areaInMM = 3.14159265358979 * std::pow(radius, 2); testResults.areaCalculated = areaInMM; testResults.areaInPixel = sumPixelsInArea; testResults.percentageAreaCalcToPixel = 100 / areaInMM * sumPixelsInArea; } /* * random a voxel. define plane through this voxel. reslice at the plane. compare the pixel vaues of the voxel * in the volume with the pixel value in the resliced image. * there are some indice shifting problems which causes the test to fail for oblique planes. seems like the chosen - * worldcoordinate is not corrresponding to the index in the 2D image. and so the pixel values are not the same as + * worldcoordinate is not corresponding to the index in the 2D image. and so the pixel values are not the same as * expected. */ static void PixelvalueBasedTest() { /* setup itk image */ typedef itk::Image ImageType; typedef itk::ImageRegionConstIterator ImageIterator; ImageType::Pointer image = ImageType::New(); ImageType::IndexType start; start[0] = start[1] = start[2] = 0; ImageType::SizeType size; size[0] = size[1] = size[2] = 32; ImageType::RegionType imgRegion; imgRegion.SetSize(size); imgRegion.SetIndex(start); image->SetRegions(imgRegion); image->SetSpacing(1.0); image->Allocate(); ImageIterator imageIterator(image, image->GetLargestPossibleRegion()); imageIterator.GoToBegin(); unsigned short pixelValue = 0; // fill the image with distinct values while (!imageIterator.IsAtEnd()) { image->SetPixel(imageIterator.GetIndex(), pixelValue); ++imageIterator; ++pixelValue; } /* end setup itk image */ mitk::Image::Pointer imageInMitk; CastToMitkImage(image, imageInMitk); /*mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New(); writer->SetInput(imageInMitk); std::string file = "C:\\Users\\schroedt\\Desktop\\cube.nrrd"; writer->SetFileName(file); writer->Update();*/ PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Coronal); PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Sagittal); PixelvalueBasedTestByPlane(imageInMitk, mitk::PlaneGeometry::Axial); } static void PixelvalueBasedTestByPlane(mitk::Image *imageInMitk, mitk::PlaneGeometry::PlaneOrientation orientation) { typedef itk::Image ImageType; // set the seed of the rand function srand((unsigned)time(nullptr)); /* setup a random orthogonal plane */ int sliceindex = 17; // rand() % 32; bool isFrontside = true; bool isRotated = false; if (orientation == mitk::PlaneGeometry::Axial) { /*isFrontside = false; isRotated = true;*/ } mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); plane->InitializeStandardPlane(imageInMitk->GetGeometry(), orientation, sliceindex, isFrontside, isRotated); mitk::Point3D origin = plane->GetOrigin(); mitk::Vector3D normal; normal = plane->GetNormal(); normal.Normalize(); origin += normal * 0.5; // pixelspacing is 1, so half the spacing is 0.5 plane->SetOrigin(origin); // we dont need this any more, because we are only testing orthogonal planes /*mitk::Vector3D rotationVector; rotationVector[0] = randFloat(); rotationVector[1] = randFloat(); rotationVector[2] = randFloat(); float degree = randFloat() * 180.0; mitk::RotationOperation* op = new mitk::RotationOperation(mitk::OpROTATE, plane->GetCenter(), rotationVector, degree); plane->ExecuteOperation(op); delete op;*/ /* end setup plane */ /* define a point in the 3D volume. * add the two axis vectors of the plane (each multiplied with a * random number) to the origin. now the two random numbers * become our index coordinates in the 2D image, because the * length of the axis vectors is 1. */ mitk::Point3D planeOrigin = plane->GetOrigin(); mitk::Vector3D axis0, axis1; axis0 = plane->GetAxisVector(0); axis1 = plane->GetAxisVector(1); axis0.Normalize(); axis1.Normalize(); unsigned char n1 = 7; // rand() % 32; unsigned char n2 = 13; // rand() % 32; mitk::Point3D testPoint3DInWorld; testPoint3DInWorld = planeOrigin + (axis0 * n1) + (axis1 * n2); // get the index of the point in the 3D volume ImageType::IndexType testPoint3DInIndex; imageInMitk->GetGeometry()->WorldToIndex(testPoint3DInWorld, testPoint3DInIndex); itk::Index<3> testPoint2DInIndex; /* end define a point in the 3D volume.*/ // do reslicing at the plane mitk::ExtractSliceFilter::Pointer slicer = mitk::ExtractSliceFilter::New(); slicer->SetInput(imageInMitk); slicer->SetWorldGeometry(plane); slicer->Update(); mitk::Image::Pointer slice = slicer->GetOutput(); // Get TestPoiont3D as Index in Slice slice->GetGeometry()->WorldToIndex(testPoint3DInWorld, testPoint2DInIndex); mitk::Point3D p, sliceIndexToWorld, imageIndexToWorld; p[0] = testPoint2DInIndex[0]; p[1] = testPoint2DInIndex[1]; p[2] = testPoint2DInIndex[2]; slice->GetGeometry()->IndexToWorld(p, sliceIndexToWorld); p[0] = testPoint3DInIndex[0]; p[1] = testPoint3DInIndex[1]; p[2] = testPoint3DInIndex[2]; imageInMitk->GetGeometry()->IndexToWorld(p, imageIndexToWorld); itk::Index<2> testPoint2DIn2DIndex; testPoint2DIn2DIndex[0] = testPoint2DInIndex[0]; testPoint2DIn2DIndex[1] = testPoint2DInIndex[1]; typedef mitk::ImagePixelReadAccessor VolumeReadAccessorType; typedef mitk::ImagePixelReadAccessor SliceReadAccessorType; VolumeReadAccessorType VolumeReadAccessor(imageInMitk); SliceReadAccessorType SliceReadAccessor(slice); // compare the pixelvalues of the defined point in the 3D volume with the value of the resliced image unsigned short valueAt3DVolume = VolumeReadAccessor.GetPixelByIndex(testPoint3DInIndex); unsigned short valueAtSlice = SliceReadAccessor.GetPixelByIndex(testPoint2DIn2DIndex); // valueAt3DVolume == valueAtSlice is not always working. because of rounding errors // indices are shifted MITK_TEST_CONDITION(valueAt3DVolume == valueAtSlice, "comparing pixelvalues for orthogonal plane"); vtkSmartPointer imageInVtk = imageInMitk->GetVtkImageData(); vtkSmartPointer sliceInVtk = slice->GetVtkImageData(); double PixelvalueByMitkOutput = sliceInVtk->GetScalarComponentAsDouble(n1, n2, 0, 0); // double valueVTKinImage = imageInVtk->GetScalarComponentAsDouble(testPoint3DInIndex[0], testPoint3DInIndex[1], // testPoint3DInIndex[2], 0); /* Test that everything is working equally if vtkoutput is used instead of the default output * from mitk ImageToImageFilter */ mitk::ExtractSliceFilter::Pointer slicerWithVtkOutput = mitk::ExtractSliceFilter::New(); slicerWithVtkOutput->SetInput(imageInMitk); slicerWithVtkOutput->SetWorldGeometry(plane); slicerWithVtkOutput->SetVtkOutputRequest(true); slicerWithVtkOutput->Update(); vtkSmartPointer vtkImageByVtkOutput = slicerWithVtkOutput->GetVtkOutput(); double PixelvalueByVtkOutput = vtkImageByVtkOutput->GetScalarComponentAsDouble(n1, n2, 0, 0); MITK_TEST_CONDITION(PixelvalueByMitkOutput == PixelvalueByVtkOutput, - "testing convertion of image output vtk->mitk by reslicer"); + "testing conversion of image output vtk->mitk by reslicer"); /*================ mbilog outputs ===========================*/ #ifdef EXTRACTOR_DEBUG MITK_INFO << "\n" << "TESTINFO index: " << sliceindex << " orientation: " << orientation << " frontside: " << isFrontside << " rotated: " << isRotated; MITK_INFO << "\n" << "slice index to world: " << sliceIndexToWorld; MITK_INFO << "\n" << "image index to world: " << imageIndexToWorld; MITK_INFO << "\n" << "vtk: slice: " << PixelvalueByMitkOutput << ", image: " << valueVTKinImage; MITK_INFO << "\n" << "testPoint3D InWorld" << testPoint3DInWorld << " is " << testPoint2DInIndex << " in 2D"; MITK_INFO << "\n" << "randoms: " << ((int)n1) << ", " << ((int)n2); MITK_INFO << "\n" << "point is inside plane: " << plane->IsInside(testPoint3DInWorld) << " and volume: " << imageInMitk->GetGeometry()->IsInside(testPoint3DInWorld); MITK_INFO << "\n" << "volume idx: " << testPoint3DInIndex << " = " << valueAt3DVolume; MITK_INFO << "\n" << "volume world: " << testPoint3DInWorld << " = " << valueAt3DVolumeByWorld; MITK_INFO << "\n" << "slice idx: " << testPoint2DInIndex << " = " << valueAtSlice; itk::Index<3> curr; curr[0] = curr[1] = curr[2] = 0; for (int i = 0; i < 32; ++i) { for (int j = 0; j < 32; ++j) { ++curr[1]; if (SliceReadAccessor.GetPixelByIndex(curr) == valueAt3DVolume) { MITK_INFO << "\n" << valueAt3DVolume << " MATCHED mitk " << curr; } } curr[1] = 0; ++curr[0]; } typedef itk::Image Image2DType; Image2DType::Pointer img = Image2DType::New(); CastToItkImage(slice, img); typedef itk::ImageRegionConstIterator Iterator2D; Iterator2D iter(img, img->GetLargestPossibleRegion()); iter.GoToBegin(); while (!iter.IsAtEnd()) { if (img->GetPixel(iter.GetIndex()) == valueAt3DVolume) MITK_INFO << "\n" << valueAt3DVolume << " MATCHED itk " << iter.GetIndex(); ++iter; } #endif // EXTRACTOR_DEBUG } /* random a float value */ static float randFloat() { return (((float)rand() + 1.0) / ((float)RAND_MAX + 1.0)) + (((float)rand() + 1.0) / ((float)RAND_MAX + 1.0)) / ((float)RAND_MAX + 1.0); } /* create a sphere with the size of the given testVolumeSize*/ static void InitializeTestVolume() { #ifdef CREATE_VOLUME // do sphere creation ItkVolumeGeneration(); #ifdef SAVE_VOLUME // save in file mitk::ImageWriter::Pointer writer = mitk::ImageWriter::New(); writer->SetInput(TestVolume); std::string file; std::ostringstream filename; filename << "C:\\home\\schroedt\\MITK\\Modules\\ImageExtraction\\Testing\\Data\\sphere_"; filename << TestvolumeSize; filename << ".nrrd"; file = filename.str(); writer->SetFileName(file); writer->Update(); #endif // SAVE_VOLUME #endif #ifndef CREATE_VOLUME // read from file mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance(); std::string filename = locator->FindFile("sphere_512.nrrd.mhd", "Modules/ImageExtraction/Testing/Data"); TestVolume = mitk::IOUtil::Load(filename); #endif #ifdef CALC_TESTFAILURE_DEVIATION // get the TestFailureDeviation in % AccessFixedDimensionByItk(TestVolume, CalcTestFailureDeviation, 3); #endif } // the test result of the sphere reslice struct SliceProperties { double planeDistanceToSphereCenter; double diameterInMM; double diameterInPixel; double diameterCalculated; double percentageRadiusToPixel; double areaCalculated; double areaInPixel; double percentageAreaCalcToPixel; }; static mitk::Image::Pointer TestVolume; static double TestvolumeSize; static mitk::PlaneGeometry::Pointer TestPlane; static std::string TestName; static unsigned char pixelValueSet; static SliceProperties testResults; static double TestFailureDeviation; private: /* * Generate a sphere with a radius of TestvolumeSize / 4.0 */ static void ItkVolumeGeneration() { typedef itk::Image TestVolumeType; typedef itk::ImageRegionConstIterator ImageIterator; TestVolumeType::Pointer sphereImage = TestVolumeType::New(); TestVolumeType::IndexType start; start[0] = start[1] = start[2] = 0; TestVolumeType::SizeType size; size[0] = size[1] = size[2] = TestvolumeSize; TestVolumeType::RegionType imgRegion; imgRegion.SetSize(size); imgRegion.SetIndex(start); sphereImage->SetRegions(imgRegion); sphereImage->SetSpacing(1.0); sphereImage->Allocate(); sphereImage->FillBuffer(0); mitk::Vector3D center; center[0] = center[1] = center[2] = TestvolumeSize / 2.0; double radius = TestvolumeSize / 4.0; double pixelValue = pixelValueSet; ImageIterator imageIterator(sphereImage, sphereImage->GetLargestPossibleRegion()); imageIterator.GoToBegin(); mitk::Vector3D currentVoxelInIndex; while (!imageIterator.IsAtEnd()) { currentVoxelInIndex[0] = imageIterator.GetIndex()[0]; currentVoxelInIndex[1] = imageIterator.GetIndex()[1]; currentVoxelInIndex[2] = imageIterator.GetIndex()[2]; double distanceToCenter = (center + (currentVoxelInIndex * -1.0)).GetNorm(); // if distance to center is smaller then the radius of the sphere if (distanceToCenter < radius) { sphereImage->SetPixel(imageIterator.GetIndex(), pixelValue); } ++imageIterator; } CastToMitkImage(sphereImage, TestVolume); } - /* calculate the devation of the voxel object to the mathematical sphere object. + /* calculate the deviation of the voxel object to the mathematical sphere object. * this is use to make a statement about the accuracy of the resliced image, eg. the circle's diameter or area. */ template static void CalcTestFailureDeviation(itk::Image *inputImage) { typedef itk::Image InputImageType; typedef itk::ImageRegionConstIterator ImageIterator; ImageIterator iterator(inputImage, inputImage->GetLargestPossibleRegion()); iterator.GoToBegin(); int volumeInPixel = 0; while (!iterator.IsAtEnd()) { if (inputImage->GetPixel(iterator.GetIndex()) == pixelValueSet) volumeInPixel++; ++iterator; } double diameter = TestvolumeSize / 2.0; double volumeCalculated = (1.0 / 6.0) * 3.14159265358979 * std::pow(diameter, 3); double volumeDeviation = std::abs(100 - (100 / volumeCalculated * volumeInPixel)); typename InputImageType::IndexType index; index[0] = index[1] = TestvolumeSize / 2.0; index[2] = 0; int sumpixels = 0; while (index[2] < TestvolumeSize) { if (inputImage->GetPixel(index) == pixelValueSet) sumpixels++; index[2] += 1; } double diameterDeviation = std::abs(100 - (100 / diameter * sumpixels)); #ifdef DEBUG MITK_INFO << "volume deviation: " << volumeDeviation << " diameter deviation:" << diameterDeviation; #endif mitkExtractSliceFilterTestClass::TestFailureDeviation = (volumeDeviation + diameterDeviation) / 2.0; } }; /*================ #END class ================*/ -/*================#BEGIN Instanciation of members ================*/ +/*================#BEGIN Instantiation of members ================*/ mitk::Image::Pointer mitkExtractSliceFilterTestClass::TestVolume = mitk::Image::New(); double mitkExtractSliceFilterTestClass::TestvolumeSize = 256.0; mitk::PlaneGeometry::Pointer mitkExtractSliceFilterTestClass::TestPlane = mitk::PlaneGeometry::New(); std::string mitkExtractSliceFilterTestClass::TestName = ""; unsigned char mitkExtractSliceFilterTestClass::pixelValueSet = 255; mitkExtractSliceFilterTestClass::SliceProperties mitkExtractSliceFilterTestClass::testResults = { -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}; double mitkExtractSliceFilterTestClass::TestFailureDeviation = 0.0; -/*================ #END Instanciation of members ================*/ +/*================ #END Instantiation of members ================*/ /*================ #BEGIN test main ================*/ int mitkExtractSliceFilterTest(int /*argc*/, char * /*argv*/ []) { MITK_TEST_BEGIN("mitkExtractSliceFilterTest") // pixelvalue based testing mitkExtractSliceFilterTestClass::PixelvalueBasedTest(); // initialize sphere test volume mitkExtractSliceFilterTestClass::InitializeTestVolume(); mitk::Vector3D spacing = mitkExtractSliceFilterTestClass::TestVolume->GetGeometry()->GetSpacing(); // the center of the sphere = center of image double sphereCenter = mitkExtractSliceFilterTestClass::TestvolumeSize / 2.0; double planeSize = mitkExtractSliceFilterTestClass::TestvolumeSize; /* axial plane */ mitk::PlaneGeometry::Pointer geometryAxial = mitk::PlaneGeometry::New(); geometryAxial->InitializeStandardPlane( planeSize, planeSize, spacing, mitk::PlaneGeometry::Axial, sphereCenter, false, true); geometryAxial->ChangeImageGeometryConsideringOriginOffset(true); mitk::Point3D origin = geometryAxial->GetOrigin(); mitk::Vector3D normal; normal = geometryAxial->GetNormal(); normal.Normalize(); origin += normal * 0.5; // pixelspacing is 1, so half the spacing is 0.5 // geometryAxial->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometryAxial, "Testing axial plane"); /* end axial plane */ /* sagittal plane */ mitk::PlaneGeometry::Pointer geometrySagittal = mitk::PlaneGeometry::New(); geometrySagittal->InitializeStandardPlane( planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, sphereCenter, true, false); geometrySagittal->ChangeImageGeometryConsideringOriginOffset(true); origin = geometrySagittal->GetOrigin(); normal = geometrySagittal->GetNormal(); normal.Normalize(); origin += normal * 0.5; // pixelspacing is 1, so half the spacing is 0.5 // geometrySagittal->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometrySagittal, "Testing sagittal plane"); /* sagittal plane */ /* sagittal shifted plane */ mitk::PlaneGeometry::Pointer geometrySagittalShifted = mitk::PlaneGeometry::New(); geometrySagittalShifted->InitializeStandardPlane( planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, (sphereCenter - 14), true, false); geometrySagittalShifted->ChangeImageGeometryConsideringOriginOffset(true); origin = geometrySagittalShifted->GetOrigin(); normal = geometrySagittalShifted->GetNormal(); normal.Normalize(); origin += normal * 0.5; // pixelspacing is 1, so half the spacing is 0.5 // geometrySagittalShifted->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometrySagittalShifted, "Testing sagittal plane shifted"); /* end sagittal shifted plane */ /* coronal plane */ mitk::PlaneGeometry::Pointer geometryCoronal = mitk::PlaneGeometry::New(); geometryCoronal->InitializeStandardPlane( planeSize, planeSize, spacing, mitk::PlaneGeometry::Coronal, sphereCenter, true, false); geometryCoronal->ChangeImageGeometryConsideringOriginOffset(true); origin = geometryCoronal->GetOrigin(); normal = geometryCoronal->GetNormal(); normal.Normalize(); origin += normal * 0.5; // pixelspacing is 1, so half the spacing is 0.5 // geometryCoronal->SetOrigin(origin); mitkExtractSliceFilterTestClass::TestSlice(geometryCoronal, "Testing coronal plane"); /* end coronal plane */ /* oblique plane */ mitk::PlaneGeometry::Pointer obliquePlane = mitk::PlaneGeometry::New(); obliquePlane->InitializeStandardPlane( planeSize, planeSize, spacing, mitk::PlaneGeometry::Sagittal, sphereCenter, true, false); obliquePlane->ChangeImageGeometryConsideringOriginOffset(true); origin = obliquePlane->GetOrigin(); normal = obliquePlane->GetNormal(); normal.Normalize(); origin += normal * 0.5; // pixelspacing is 1, so half the spacing is 0.5 // obliquePlane->SetOrigin(origin); mitk::Vector3D rotationVector; rotationVector[0] = 0.2; rotationVector[1] = 0.4; rotationVector[2] = 0.62; float degree = 37.0; mitk::RotationOperation *op = new mitk::RotationOperation(mitk::OpROTATE, obliquePlane->GetCenter(), rotationVector, degree); obliquePlane->ExecuteOperation(op); delete op; mitkExtractSliceFilterTestClass::TestSlice(obliquePlane, "Testing oblique plane"); /* end oblique plane */ #ifdef SHOW_SLICE_IN_RENDER_WINDOW /*================ #BEGIN vtk render code ================*/ // set reslicer for renderwindow mitk::Image::Pointer pic = mitk::IOUtil::Load(filename); vtkSmartPointer slicer = vtkSmartPointer::New(); slicer->SetInput(pic->GetVtkImageData()); mitk::PlaneGeometry::Pointer obliquePl = mitk::PlaneGeometry::New(); obliquePl->InitializeStandardPlane( pic->GetGeometry(), mitk::PlaneGeometry::Sagittal, pic->GetGeometry()->GetCenter()[0], true, false); obliquePl->ChangeImageGeometryConsideringOriginOffset(true); mitk::Point3D origin2 = obliquePl->GetOrigin(); mitk::Vector3D n; n = obliquePl->GetNormal(); n.Normalize(); origin2 += n * 0.5; // pixelspacing is 1, so half the spacing is 0.5 obliquePl->SetOrigin(origin2); mitk::Vector3D rotation; rotation[0] = 0.534307; rotation[1] = 0.000439605; rotation[2] = 0.423017; MITK_INFO << rotation; mitk::RotationOperation *operation = new mitk::RotationOperation(mitk::OpROTATE, obliquePl->GetCenter(), rotationVector, degree); obliquePl->ExecuteOperation(operation); delete operation; double origin[3]; origin[0] = obliquePl->GetOrigin()[0]; origin[1] = obliquePl->GetOrigin()[1]; origin[2] = obliquePl->GetOrigin()[2]; slicer->SetResliceAxesOrigin(origin); mitk::Vector3D right, bottom, normal; right = obliquePl->GetAxisVector(0); bottom = obliquePl->GetAxisVector(1); normal = obliquePl->GetNormal(); right.Normalize(); bottom.Normalize(); normal.Normalize(); double cosines[9]; mitk::vnl2vtk(right.GetVnlVector(), cosines); // x mitk::vnl2vtk(bottom.GetVnlVector(), cosines + 3); // y mitk::vnl2vtk(normal.GetVnlVector(), cosines + 6); // n slicer->SetResliceAxesDirectionCosines(cosines); slicer->SetOutputDimensionality(2); slicer->Update(); // set vtk renderwindow vtkSmartPointer vtkPlane = vtkSmartPointer::New(); vtkPlane->SetOrigin(0.0, 0.0, 0.0); // These two points define the axes of the plane in combination with the origin. // Point 1 is the x-axis and point 2 the y-axis. // Each plane is transformed according to the view (axial, coronal and sagittal) afterwards. vtkPlane->SetPoint1(1.0, 0.0, 0.0); // P1: (xMax, yMin, depth) vtkPlane->SetPoint2(0.0, 1.0, 0.0); // P2: (xMin, yMax, depth) // these are not the correct values for all slices, only a square plane by now vtkSmartPointer imageMapper = vtkSmartPointer::New(); imageMapper->SetInputConnection(vtkPlane->GetOutputPort()); vtkSmartPointer lookupTable = vtkSmartPointer::New(); // built a default lookuptable lookupTable->SetRampToLinear(); lookupTable->SetSaturationRange(0.0, 0.0); lookupTable->SetHueRange(0.0, 0.0); lookupTable->SetValueRange(0.0, 1.0); lookupTable->Build(); // map all black values to transparent lookupTable->SetTableValue(0, 0.0, 0.0, 0.0, 0.0); lookupTable->SetRange(-255.0, 255.0); // lookupTable->SetRange(-1022.0, 1184.0);//pic3D range vtkSmartPointer texture = vtkSmartPointer::New(); texture->SetInput(slicer->GetOutput()); texture->SetLookupTable(lookupTable); texture->SetMapColorScalarsThroughLookupTable(true); vtkSmartPointer imageActor = vtkSmartPointer::New(); imageActor->SetMapper(imageMapper); imageActor->SetTexture(texture); // Setup renderers vtkSmartPointer renderer = vtkSmartPointer::New(); renderer->AddActor(imageActor); // Setup render window vtkSmartPointer renderWindow = vtkSmartPointer::New(); renderWindow->AddRenderer(renderer); // Setup render window interactor vtkSmartPointer renderWindowInteractor = vtkSmartPointer::New(); vtkSmartPointer style = vtkSmartPointer::New(); renderWindowInteractor->SetInteractorStyle(style); // Render and start interaction renderWindowInteractor->SetRenderWindow(renderWindow); // renderer->AddViewProp(imageActor); renderWindow->Render(); renderWindowInteractor->Start(); // always end with this! /*================ #END vtk render code ================*/ #endif // SHOW_SLICE_IN_RENDER_WINDOW MITK_TEST_END() } diff --git a/Modules/Core/test/mitkGeometry3DEqualTest.cpp b/Modules/Core/test/mitkGeometry3DEqualTest.cpp index 345b7637c8..858bcc6967 100644 --- a/Modules/Core/test/mitkGeometry3DEqualTest.cpp +++ b/Modules/Core/test/mitkGeometry3DEqualTest.cpp @@ -1,113 +1,113 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkGeometry3D.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" class mitkGeometry3DEqualTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGeometry3DEqualTestSuite); MITK_TEST(Equal_CloneAndOriginal_ReturnsTrue); MITK_TEST(Equal_DifferentOrigin_ReturnsFalse); MITK_TEST(Equal_DifferentIndexToWorldTransform_ReturnsFalse); MITK_TEST(Equal_DifferentSpacing_ReturnsFalse); MITK_TEST(Equal_DifferentImageGeometry_ReturnsFalse); MITK_TEST(Equal_DifferentBoundingBox_ReturnsFalse); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different test methods. All members are initialized via setUp().*/ mitk::Geometry3D::Pointer m_Geometry3D; mitk::Geometry3D::Pointer m_AnotherGeometry3D; public: /** -* @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members +* @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used members * for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_Geometry3D = mitk::Geometry3D::New(); m_Geometry3D->Initialize(); m_AnotherGeometry3D = m_Geometry3D->Clone(); } void tearDown() override { m_Geometry3D = nullptr; m_AnotherGeometry3D = nullptr; } void Equal_CloneAndOriginal_ReturnsTrue() { MITK_ASSERT_EQUAL(m_Geometry3D, m_AnotherGeometry3D, "A clone should be equal to its original."); } void Equal_DifferentOrigin_ReturnsFalse() { mitk::Point3D origin; origin[0] = 0.0; origin[1] = 0.0; origin[2] = 1.0 + 2 * mitk::eps; m_AnotherGeometry3D->SetOrigin(origin); MITK_ASSERT_NOT_EQUAL(m_Geometry3D, m_AnotherGeometry3D, "Origin was modified. Result should be false."); } void Equal_DifferentIndexToWorldTransform_ReturnsFalse() { // Create another index to world transform and make it different somehow mitk::AffineTransform3D::Pointer differentIndexToWorldTransform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType differentMatrix; differentMatrix.SetIdentity(); differentMatrix(1, 1) = 2; differentIndexToWorldTransform->SetMatrix(differentMatrix); m_AnotherGeometry3D->SetIndexToWorldTransform(differentIndexToWorldTransform); MITK_ASSERT_NOT_EQUAL( m_Geometry3D, m_AnotherGeometry3D, "IndexToWorldTransform was modified. Result should be false."); } void Equal_DifferentSpacing_ReturnsFalse() { mitk::Vector3D differentSpacing; differentSpacing[0] = 1.0; differentSpacing[1] = 1.0 + 2 * mitk::eps; differentSpacing[2] = 1.0; m_AnotherGeometry3D->SetSpacing(differentSpacing); MITK_ASSERT_NOT_EQUAL(m_Geometry3D, m_AnotherGeometry3D, "Spacing was modified. Result should be false."); } void Equal_DifferentImageGeometry_ReturnsFalse() { m_AnotherGeometry3D->SetImageGeometry(true); MITK_ASSERT_NOT_EQUAL( m_Geometry3D, m_AnotherGeometry3D, "One Geometry is image, the other is not. Result should be false."); } void Equal_DifferentBoundingBox_ReturnsFalse() { // create different bounds to make the comparison false mitk::ScalarType bounds[] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; m_AnotherGeometry3D->SetBounds(bounds); MITK_ASSERT_NOT_EQUAL(m_Geometry3D, m_AnotherGeometry3D, "Bounds are different. Result should be false."); } }; MITK_TEST_SUITE_REGISTRATION(mitkGeometry3DEqual) diff --git a/Modules/Core/test/mitkGeometry3DTest.cpp b/Modules/Core/test/mitkGeometry3DTest.cpp index ae6f8592be..caa5fc4d1a 100644 --- a/Modules/Core/test/mitkGeometry3DTest.cpp +++ b/Modules/Core/test/mitkGeometry3DTest.cpp @@ -1,622 +1,622 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkGeometry3D.h" #include #include #include "mitkInteractionConst.h" #include "mitkRotationOperation.h" #include #include #include "mitkTestingMacros.h" #include #include bool testGetAxisVectorVariants(mitk::Geometry3D *geometry) { int direction; for (direction = 0; direction < 3; ++direction) { mitk::Vector3D frontToBack(0.); switch (direction) { case 0: frontToBack = geometry->GetCornerPoint(false, false, false) - geometry->GetCornerPoint(true, false, false); break; // 7-3 case 1: frontToBack = geometry->GetCornerPoint(false, false, false) - geometry->GetCornerPoint(false, true, false); break; // 7-5 case 2: frontToBack = geometry->GetCornerPoint(false, false, false) - geometry->GetCornerPoint(false, false, true); break; // 7-2 } std::cout << "Testing GetAxisVector(int) vs GetAxisVector(bool, bool, bool): "; if (mitk::Equal(geometry->GetAxisVector(direction), frontToBack) == false) { std::cout << "[FAILED]" << std::endl; return false; } std::cout << "[PASSED]" << std::endl; } return true; } bool testGetAxisVectorExtent(mitk::Geometry3D *geometry) { int direction; for (direction = 0; direction < 3; ++direction) { if (mitk::Equal(geometry->GetAxisVector(direction).GetNorm(), geometry->GetExtentInMM(direction)) == false) { std::cout << "[FAILED]" << std::endl; return false; } std::cout << "[PASSED]" << std::endl; } return true; } // a part of the test requires axis-parallel coordinates int testIndexAndWorldConsistency(mitk::Geometry3D *geometry3d) { MITK_TEST_OUTPUT(<< "Testing consistency of index and world coordinate systems: "); mitk::Point3D origin = geometry3d->GetOrigin(); mitk::Point3D dummy; MITK_TEST_OUTPUT(<< " Testing index->world->index conversion consistency"); geometry3d->WorldToIndex(origin, dummy); geometry3d->IndexToWorld(dummy, dummy); MITK_TEST_CONDITION_REQUIRED(dummy == origin, ""); MITK_TEST_OUTPUT(<< " Testing WorldToIndex(origin, mitk::Point3D)==(0,0,0)"); mitk::Point3D globalOrigin; mitk::FillVector3D(globalOrigin, 0, 0, 0); mitk::Point3D originContinuousIndex; geometry3d->WorldToIndex(origin, originContinuousIndex); MITK_TEST_CONDITION_REQUIRED(originContinuousIndex == globalOrigin, ""); MITK_TEST_OUTPUT(<< " Testing WorldToIndex(origin, itk::Index)==(0,0,0)"); itk::Index<3> itkindex; geometry3d->WorldToIndex(origin, itkindex); itk::Index<3> globalOriginIndex; mitk::vtk2itk(globalOrigin, globalOriginIndex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT(<< " Testing WorldToIndex(origin-0.5*spacing, itk::Index)==(0,0,0)"); mitk::Vector3D halfSpacingStep = geometry3d->GetSpacing() * 0.5; mitk::Matrix3D rotation; mitk::Point3D originOffCenter = origin - halfSpacingStep; geometry3d->WorldToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT(<< " Testing WorldToIndex(origin+0.5*spacing-eps, itk::Index)==(0,0,0)"); originOffCenter = origin + halfSpacingStep; originOffCenter -= 0.0001; geometry3d->WorldToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT(<< " Testing WorldToIndex(origin+0.5*spacing, itk::Index)==(1,1,1)"); originOffCenter = origin + halfSpacingStep; itk::Index<3> global111; mitk::FillVector3D(global111, 1, 1, 1); geometry3d->WorldToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == global111, ""); MITK_TEST_OUTPUT(<< " Testing WorldToIndex(GetCenter())==BoundingBox.GetCenter: "); mitk::Point3D center = geometry3d->GetCenter(); mitk::Point3D centerContIndex; geometry3d->WorldToIndex(center, centerContIndex); mitk::BoundingBox::ConstPointer boundingBox = geometry3d->GetBoundingBox(); mitk::BoundingBox::PointType centerBounds = boundingBox->GetCenter(); // itk assumes corner based geometry. If our geometry is center based (imageGoe == true), everything needs to be // shifted if (geometry3d->GetImageGeometry()) { centerBounds[0] -= 0.5; centerBounds[1] -= 0.5; centerBounds[2] -= 0.5; } MITK_TEST_CONDITION_REQUIRED(mitk::Equal(centerContIndex, centerBounds), ""); MITK_TEST_OUTPUT(<< " Testing GetCenter()==IndexToWorld(BoundingBox.GetCenter): "); center = geometry3d->GetCenter(); mitk::Point3D centerBoundsInWorldCoords; geometry3d->IndexToWorld(centerBounds, centerBoundsInWorldCoords); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(center, centerBoundsInWorldCoords), ""); return EXIT_SUCCESS; } int testIndexAndWorldConsistencyForVectors(mitk::Geometry3D *geometry3d) { MITK_TEST_OUTPUT(<< "Testing consistency of index and world coordinate systems for vectors: "); mitk::Vector3D xAxisMM = geometry3d->GetAxisVector(0); mitk::Vector3D xAxisContinuousIndex; mitk::Vector3D xAxisContinuousIndexDeprecated; mitk::Point3D p, pIndex, origin; origin = geometry3d->GetOrigin(); p[0] = xAxisMM[0]; p[1] = xAxisMM[1]; p[2] = xAxisMM[2]; geometry3d->WorldToIndex(p, pIndex); geometry3d->WorldToIndex(xAxisMM, xAxisContinuousIndexDeprecated); geometry3d->WorldToIndex(xAxisMM, xAxisContinuousIndex); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == pIndex[0], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == pIndex[1], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == pIndex[2], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == xAxisContinuousIndexDeprecated[0], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == xAxisContinuousIndexDeprecated[1], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == xAxisContinuousIndexDeprecated[2], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[0] == pIndex[0], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[1] == pIndex[1], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[2] == pIndex[2], ""); geometry3d->IndexToWorld(xAxisContinuousIndex, xAxisContinuousIndex); geometry3d->IndexToWorld(xAxisContinuousIndexDeprecated, xAxisContinuousIndexDeprecated); geometry3d->IndexToWorld(pIndex, p); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex == xAxisMM, ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[0] == p[0], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[1] == p[1], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndex[2] == p[2], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated == xAxisMM, ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[0] == p[0], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[1] == p[1], ""); MITK_TEST_CONDITION_REQUIRED(xAxisContinuousIndexDeprecated[2] == p[2], ""); return EXIT_SUCCESS; } int testIndexAndWorldConsistencyForIndex(mitk::Geometry3D *geometry3d) { MITK_TEST_OUTPUT(<< "Testing consistency of index and world coordinate systems: "); // creating testing data itk::Index<4> itkIndex4, itkIndex4b; itk::Index<3> itkIndex3, itkIndex3b; itk::Index<2> itkIndex2, itkIndex2b; itk::Index<3> mitkIndex, mitkIndexb; itkIndex4[0] = itkIndex4[1] = itkIndex4[2] = itkIndex4[3] = 4; itkIndex3[0] = itkIndex3[1] = itkIndex3[2] = 6; itkIndex2[0] = itkIndex2[1] = 2; mitkIndex[0] = mitkIndex[1] = mitkIndex[2] = 13; - // check for constistency + // check for consistency mitk::Point3D point; geometry3d->IndexToWorld(itkIndex2, point); geometry3d->WorldToIndex(point, itkIndex2b); MITK_TEST_CONDITION_REQUIRED(((itkIndex2b[0] == itkIndex2[0]) && (itkIndex2b[1] == itkIndex2[1])), "Testing itk::index<2> for IndexToWorld/WorldToIndex consistency"); geometry3d->IndexToWorld(itkIndex3, point); geometry3d->WorldToIndex(point, itkIndex3b); MITK_TEST_CONDITION_REQUIRED( ((itkIndex3b[0] == itkIndex3[0]) && (itkIndex3b[1] == itkIndex3[1]) && (itkIndex3b[2] == itkIndex3[2])), "Testing itk::index<3> for IndexToWorld/WorldToIndex consistency"); geometry3d->IndexToWorld(itkIndex4, point); geometry3d->WorldToIndex(point, itkIndex4b); MITK_TEST_CONDITION_REQUIRED(((itkIndex4b[0] == itkIndex4[0]) && (itkIndex4b[1] == itkIndex4[1]) && (itkIndex4b[2] == itkIndex4[2]) && (itkIndex4b[3] == 0)), "Testing itk::index<3> for IndexToWorld/WorldToIndex consistency"); geometry3d->IndexToWorld(mitkIndex, point); geometry3d->WorldToIndex(point, mitkIndexb); MITK_TEST_CONDITION_REQUIRED( ((mitkIndexb[0] == mitkIndex[0]) && (mitkIndexb[1] == mitkIndex[1]) && (mitkIndexb[2] == mitkIndex[2])), "Testing mitk::Index for IndexToWorld/WorldToIndex consistency"); return EXIT_SUCCESS; } #include int testItkImageIsCenterBased() { MITK_TEST_OUTPUT(<< "Testing whether itk::Image coordinates are center-based."); typedef itk::Image ItkIntImage3D; ItkIntImage3D::Pointer itkintimage = ItkIntImage3D::New(); ItkIntImage3D::SizeType size; size.Fill(10); mitk::Point3D origin; mitk::FillVector3D(origin, 2, 3, 7); itkintimage->Initialize(); itkintimage->SetRegions(size); itkintimage->SetOrigin(origin); std::cout << "[PASSED]" << std::endl; MITK_TEST_OUTPUT(<< " Testing itk::Image::TransformPhysicalPointToContinuousIndex(origin)==(0,0,0)"); mitk::Point3D globalOrigin; mitk::FillVector3D(globalOrigin, 0, 0, 0); itk::ContinuousIndex originContinuousIndex; itkintimage->TransformPhysicalPointToContinuousIndex(origin, originContinuousIndex); MITK_TEST_CONDITION_REQUIRED(originContinuousIndex == globalOrigin, ""); MITK_TEST_OUTPUT(<< " Testing itk::Image::TransformPhysicalPointToIndex(origin)==(0,0,0)"); itk::Index<3> itkindex; itkintimage->TransformPhysicalPointToIndex(origin, itkindex); itk::Index<3> globalOriginIndex; mitk::vtk2itk(globalOrigin, globalOriginIndex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT(<< " Testing itk::Image::TransformPhysicalPointToIndex(origin-0.5*spacing)==(0,0,0)"); mitk::Vector3D halfSpacingStep = itkintimage->GetSpacing() * 0.5; mitk::Matrix3D rotation; mitk::Point3D originOffCenter = origin - halfSpacingStep; itkintimage->TransformPhysicalPointToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT( << " Testing itk::Image::TransformPhysicalPointToIndex(origin+0.5*spacing-eps, itk::Index)==(0,0,0)"); originOffCenter = origin + halfSpacingStep; originOffCenter -= 0.0001; itkintimage->TransformPhysicalPointToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == globalOriginIndex, ""); MITK_TEST_OUTPUT(<< " Testing itk::Image::TransformPhysicalPointToIndex(origin+0.5*spacing, itk::Index)==(1,1,1)"); originOffCenter = origin + halfSpacingStep; itk::Index<3> global111; mitk::FillVector3D(global111, 1, 1, 1); itkintimage->TransformPhysicalPointToIndex(originOffCenter, itkindex); MITK_TEST_CONDITION_REQUIRED(itkindex == global111, ""); MITK_TEST_OUTPUT(<< "=> Yes, itk::Image coordinates are center-based."); return EXIT_SUCCESS; } int testGeometry3D(bool imageGeometry) { // Build up a new image Geometry mitk::Geometry3D::Pointer geometry3d = mitk::Geometry3D::New(); float bounds[] = {-10.0, 17.0, -12.0, 188.0, 13.0, 211.0}; MITK_TEST_OUTPUT(<< "Initializing"); geometry3d->Initialize(); MITK_TEST_OUTPUT(<< "Setting ImageGeometry to " << imageGeometry); geometry3d->SetImageGeometry(imageGeometry); MITK_TEST_OUTPUT(<< "Setting bounds by SetFloatBounds(): " << bounds); geometry3d->SetFloatBounds(bounds); MITK_TEST_OUTPUT(<< "Testing AxisVectors"); if (testGetAxisVectorVariants(geometry3d) == false) return EXIT_FAILURE; if (testGetAxisVectorExtent(geometry3d) == false) return EXIT_FAILURE; MITK_TEST_OUTPUT(<< "Creating an AffineTransform3D transform"); mitk::AffineTransform3D::MatrixType matrix; matrix.SetIdentity(); matrix(1, 1) = 2; mitk::AffineTransform3D::Pointer transform; transform = mitk::AffineTransform3D::New(); transform->SetMatrix(matrix); MITK_TEST_OUTPUT(<< "Testing a SetIndexToWorldTransform"); geometry3d->SetIndexToWorldTransform(transform); MITK_TEST_OUTPUT(<< "Testing correctness of value returned by GetSpacing"); const mitk::Vector3D &spacing1 = geometry3d->GetSpacing(); mitk::Vector3D expectedSpacing; expectedSpacing.Fill(1.0); expectedSpacing[1] = 2; if (mitk::Equal(spacing1, expectedSpacing) == false) { MITK_TEST_OUTPUT(<< " [FAILED]"); return EXIT_FAILURE; } MITK_TEST_OUTPUT(<< "Testing a Compose(transform)"); geometry3d->Compose(transform); MITK_TEST_OUTPUT(<< "Testing correctness of value returned by GetSpacing"); const mitk::Vector3D &spacing2 = geometry3d->GetSpacing(); expectedSpacing[1] = 4; if (mitk::Equal(spacing2, expectedSpacing) == false) { MITK_TEST_OUTPUT(<< " [FAILED]"); return EXIT_FAILURE; } MITK_TEST_OUTPUT(<< "Testing correctness of SetSpacing"); mitk::Vector3D newspacing; mitk::FillVector3D(newspacing, 1.5, 2.5, 3.5); geometry3d->SetSpacing(newspacing); const mitk::Vector3D &spacing3 = geometry3d->GetSpacing(); if (mitk::Equal(spacing3, newspacing) == false) { MITK_TEST_OUTPUT(<< " [FAILED]"); return EXIT_FAILURE; } - // Seperate Test function for Index and World consistency + // Separate Test function for Index and World consistency testIndexAndWorldConsistency(geometry3d); testIndexAndWorldConsistencyForVectors(geometry3d); testIndexAndWorldConsistencyForIndex(geometry3d); MITK_TEST_OUTPUT(<< "Testing a rotation of the geometry"); double angle = 35.0; mitk::Vector3D rotationVector; mitk::FillVector3D(rotationVector, 1, 0, 0); mitk::Point3D center = geometry3d->GetCenter(); auto op = new mitk::RotationOperation(mitk::OpROTATE, center, rotationVector, angle); geometry3d->ExecuteOperation(op); MITK_TEST_OUTPUT(<< "Testing mitk::GetRotation() and success of rotation"); mitk::Matrix3D rotation; mitk::GetRotation(geometry3d, rotation); mitk::Vector3D voxelStep = rotation * newspacing; mitk::Vector3D voxelStepIndex; geometry3d->WorldToIndex(voxelStep, voxelStepIndex); mitk::Vector3D expectedVoxelStepIndex; expectedVoxelStepIndex.Fill(1); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(voxelStepIndex, expectedVoxelStepIndex), ""); delete op; std::cout << "[PASSED]" << std::endl; MITK_TEST_OUTPUT(<< "Testing that ImageGeometry is still " << imageGeometry); MITK_TEST_CONDITION_REQUIRED(geometry3d->GetImageGeometry() == imageGeometry, ""); // Test if the translate function moves the origin correctly. mitk::Point3D oldOrigin = geometry3d->GetOrigin(); // use some random values for translation mitk::Vector3D translationVector; translationVector.SetElement(0, 17.5f); translationVector.SetElement(1, -32.3f); translationVector.SetElement(2, 4.0f); // compute ground truth mitk::Point3D tmpResult = geometry3d->GetOrigin() + translationVector; geometry3d->Translate(translationVector); MITK_TEST_CONDITION(mitk::Equal(geometry3d->GetOrigin(), tmpResult), "Testing if origin was translated."); translationVector *= -1; // vice versa geometry3d->Translate(translationVector); MITK_TEST_CONDITION(mitk::Equal(geometry3d->GetOrigin(), oldOrigin), "Testing if the translation could be done vice versa."); return EXIT_SUCCESS; } int testGeometryAfterCasting() { // Epsilon. Allowed difference for rotationvalue float eps = 0.0001; // Cast ITK and MITK images and see if geometry stays typedef itk::Image Image2DType; typedef itk::Image Image3DType; // Create 3D ITK Image from Scratch, cast to 3D MITK image, compare Geometries Image3DType::Pointer image3DItk = Image3DType::New(); Image3DType::RegionType myRegion; Image3DType::SizeType mySize; Image3DType::IndexType myIndex; Image3DType::SpacingType mySpacing; Image3DType::DirectionType myDirection, rotMatrixX, rotMatrixY, rotMatrixZ; mySpacing[0] = 31; mySpacing[1] = 0.1; mySpacing[2] = 2.9; myIndex[0] = -15; myIndex[1] = 15; myIndex[2] = 12; mySize[0] = 10; mySize[1] = 2; mySize[2] = 5; myRegion.SetSize(mySize); myRegion.SetIndex(myIndex); image3DItk->SetSpacing(mySpacing); image3DItk->SetRegions(myRegion); image3DItk->Allocate(); image3DItk->FillBuffer(0); myDirection.SetIdentity(); rotMatrixX.SetIdentity(); rotMatrixY.SetIdentity(); rotMatrixZ.SetIdentity(); mitk::Image::Pointer mitkImage; - // direction [row] [coloum] + // direction [row] [column] MITK_TEST_OUTPUT(<< "Casting a rotated 3D ITK Image to a MITK Image and check if Geometry is still same"); for (double rotX = 0; rotX < itk::Math::pi * 2; rotX += itk::Math::pi * 0.4) { // Set Rotation X rotMatrixX[1][1] = cos(rotX); rotMatrixX[1][2] = -sin(rotX); rotMatrixX[2][1] = sin(rotX); rotMatrixX[2][2] = cos(rotX); for (double rotY = 0; rotY < itk::Math::pi * 2; rotY += itk::Math::pi * 0.3) { // Set Rotation Y rotMatrixY[0][0] = cos(rotY); rotMatrixY[0][2] = sin(rotY); rotMatrixY[2][0] = -sin(rotY); rotMatrixY[2][2] = cos(rotY); for (double rotZ = 0; rotZ < itk::Math::pi * 2; rotZ += itk::Math::pi * 0.2) { // Set Rotation Z rotMatrixZ[0][0] = cos(rotZ); rotMatrixZ[0][1] = -sin(rotZ); rotMatrixZ[1][0] = sin(rotZ); rotMatrixZ[1][1] = cos(rotZ); // Multiply matrizes myDirection = myDirection * rotMatrixX * rotMatrixY * rotMatrixZ; image3DItk->SetDirection(myDirection); mitk::CastToMitkImage(image3DItk, mitkImage); const mitk::AffineTransform3D::MatrixType &matrix = mitkImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { double mitkValue = matrix[row][col] / mitkImage->GetGeometry()->GetSpacing()[col]; double itkValue = myDirection[row][col]; double diff = mitkValue - itkValue; // if you decrease this value, you can see that there might be QUITE high inaccuracy!!! if (diff > eps) // need to check, how exact it SHOULD be .. since it is NOT EXACT! { std::cout << "Had a difference of : " << diff; std::cout << "Error: Casting altered Geometry!"; std::cout << "ITK Matrix:\n" << myDirection; std::cout << "Mitk Matrix (With Spacing):\n" << matrix; std::cout << "Mitk Spacing: " << mitkImage->GetGeometry()->GetSpacing(); MITK_TEST_CONDITION_REQUIRED(false == true, ""); return false; } } } } } } // Create 2D ITK Image from Scratch, cast to 2D MITK image, compare Geometries Image2DType::Pointer image2DItk = Image2DType::New(); Image2DType::RegionType myRegion2D; Image2DType::SizeType mySize2D; Image2DType::IndexType myIndex2D; Image2DType::SpacingType mySpacing2D; Image2DType::DirectionType myDirection2D, rotMatrix; mySpacing2D[0] = 31; mySpacing2D[1] = 0.1; myIndex2D[0] = -15; myIndex2D[1] = 15; mySize2D[0] = 10; mySize2D[1] = 2; myRegion2D.SetSize(mySize2D); myRegion2D.SetIndex(myIndex2D); image2DItk->SetSpacing(mySpacing2D); image2DItk->SetRegions(myRegion2D); image2DItk->Allocate(); image2DItk->FillBuffer(0); myDirection2D.SetIdentity(); rotMatrix.SetIdentity(); - // direction [row] [coloum] + // direction [row] [column] MITK_TEST_OUTPUT(<< "Casting a rotated 2D ITK Image to a MITK Image and check if Geometry is still same"); for (double rotTheta = 0; rotTheta < itk::Math::pi * 2; rotTheta += itk::Math::pi * 0.2) { // Set Rotation rotMatrix[0][0] = cos(rotTheta); rotMatrix[0][1] = -sin(rotTheta); rotMatrix[1][0] = sin(rotTheta); rotMatrix[1][1] = cos(rotTheta); // Multiply matrizes myDirection2D = myDirection2D * rotMatrix; image2DItk->SetDirection(myDirection2D); mitk::CastToMitkImage(image2DItk, mitkImage); const mitk::AffineTransform3D::MatrixType &matrix = mitkImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(); // Compare MITK and ITK matrix for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { double mitkValue = matrix[row][col] / mitkImage->GetGeometry()->GetSpacing()[col]; if ((row == 2) && (col == row)) { if (mitkValue != 1) { MITK_TEST_OUTPUT(<< "After casting a 2D ITK to 3D MITK images, MITK matrix values for 0|2, 1|2, 2|0, 2|1 " "MUST be 0 and value for 2|2 must be 1"); return false; } } else if ((row == 2) || (col == 2)) { if (mitkValue != 0) { MITK_TEST_OUTPUT(<< "After casting a 2D ITK to 3D MITK images, MITK matrix values for 0|2, 1|2, 2|0, 2|1 " "MUST be 0 and value for 2|2 must be 1"); return false; } } else { double itkValue = myDirection2D[row][col]; double diff = mitkValue - itkValue; // if you decrease this value, you can see that there might be QUITE high inaccuracy!!! if (diff > eps) // need to check, how exact it SHOULD be .. since it is NOT EXACT! { std::cout << "Had a difference of : " << diff; std::cout << "Error: Casting altered Geometry!"; std::cout << "ITK Matrix:\n" << myDirection2D; std::cout << "Mitk Matrix (With Spacing):\n" << matrix; std::cout << "Mitk Spacing: " << mitkImage->GetGeometry()->GetSpacing(); MITK_TEST_CONDITION_REQUIRED(false == true, ""); return false; } } } } } // THIS WAS TESTED: // 2D ITK -> 2D MITK, // 3D ITK -> 3D MITK, // Still need to test: 2D MITK Image with ADDITIONAL INFORMATION IN MATRIX -> 2D ITK // 1. Possibility: 3x3 MITK matrix can be converted without loss into 2x2 ITK matrix // 2. Possibility: 3x3 MITK matrix can only be converted with loss into 2x2 ITK matrix // .. before implementing this, we wait for further development in geometry classes (e.g. Geoemtry3D::SetRotation(..)) return EXIT_SUCCESS; } int mitkGeometry3DTest(int /*argc*/, char * /*argv*/ []) { MITK_TEST_BEGIN(mitkGeometry3DTest); int result; MITK_TEST_CONDITION_REQUIRED((result = testItkImageIsCenterBased()) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running main part of test with ImageGeometry = false"); MITK_TEST_CONDITION_REQUIRED((result = testGeometry3D(false)) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running main part of test with ImageGeometry = true"); MITK_TEST_CONDITION_REQUIRED((result = testGeometry3D(true)) == EXIT_SUCCESS, ""); MITK_TEST_OUTPUT(<< "Running test to see if Casting MITK to ITK and the other way around destroys geometry"); MITK_TEST_CONDITION_REQUIRED((result = testGeometryAfterCasting()) == EXIT_SUCCESS, ""); MITK_TEST_END(); return EXIT_SUCCESS; } diff --git a/Modules/Core/test/mitkGrabItkImageMemoryTest.cpp b/Modules/Core/test/mitkGrabItkImageMemoryTest.cpp index af4e83d959..a5388d0fd1 100644 --- a/Modules/Core/test/mitkGrabItkImageMemoryTest.cpp +++ b/Modules/Core/test/mitkGrabItkImageMemoryTest.cpp @@ -1,120 +1,120 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkITKImageImport.h" #include "mitkTestingMacros.h" #include "mitkImagePixelReadAccessor.h" #include #include "mitkImageAccessByItk.h" /** * An ITK-based filter for thresholding. * * The filter represents the typical usage of ITK-like filters inside MITK. It is to be called for an mitk::Image * by using the AccessByItk macro. The filter executes the binary threshold filter and imports the result into the * output by using the ImportItkImage method. * * @param output mitk::Image to hold the result of the filter * @param th[] two double values to set the lower/upper threshold */ //! [ItkThresholdFilter] template static void ItkThresholdFilter(const itk::Image *image, mitk::Image::Pointer &output, const double th[]) { typedef itk::Image InputImageType; typedef itk::ThresholdImageFilter ThresholdFilterType; typename ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New(); thresholder->SetInput(image); thresholder->ThresholdOutside(th[0], th[1]); thresholder->Update(); try { output = mitk::GrabItkImageMemory(thresholder->GetOutput()); } catch ( const itk::ExceptionObject & ) { MITK_TEST_FAILED_MSG(<< "Thresholding computation failed"); } } //! [ItkThresholdFilter] /** * Creates an mitk::Image, executes the binary threshold filter through AccessByItk and * checks whether the image data was correctly imported back to an mitk::Image. */ template bool Assert_ItkImportWithinAccessByItkSucceded_ReturnsTrue() { // data for 3x3x3 image const unsigned int dimensions[3] = {3, 3, 3}; auto image_data = new TPixel[27]; // ground truth for result check auto ground_truth = new TPixel[27]; double threshold[2] = {90.0, 180.0}; // fill image for (unsigned int i = 0; i < 27; i++) { image_data[i] = static_cast(i * 10); ground_truth[i] = 0; if (image_data[i] >= threshold[0] && image_data[i] <= threshold[1]) ground_truth[i] = static_cast(i * 10); } mitk::Image::Pointer input = mitk::Image::New(); input->Initialize(mitk::MakeScalarPixelType(), 3, dimensions); input->SetImportVolume(image_data); //! [OutOfScopeCall] mitk::Image::Pointer output = mitk::Image::New(); AccessByItk_2(input, ItkThresholdFilter, output, threshold); //! [OutOfScopeCall] mitk::ImagePixelReadAccessor readAccessor(output); const TPixel *output_data = readAccessor.GetData(); bool equal = true; for (unsigned int i = 0; i < 27; i++) { equal &= (ground_truth[i] == output_data[i]); if (!equal) { MITK_INFO << " :: At position " << i << " : " << ground_truth[i] << " ? " << output_data[i] << "\n"; break; } } MITK_TEST_CONDITION(equal, " Imported output data equals the ground truth"); return equal; } int mitkGrabItkImageMemoryTest(int /*argc*/, char * /*argv*/ []) { MITK_TEST_BEGIN("mitkGrabItkImageMemoryTest") Assert_ItkImportWithinAccessByItkSucceded_ReturnsTrue(); // "Import successful on 3D short"); - Assert_ItkImportWithinAccessByItkSucceded_ReturnsTrue(); // "Import succesfull on float"); - Assert_ItkImportWithinAccessByItkSucceded_ReturnsTrue(); // "Import succesfull on uchar"); - Assert_ItkImportWithinAccessByItkSucceded_ReturnsTrue(); // "Import succesfull on int"); + Assert_ItkImportWithinAccessByItkSucceded_ReturnsTrue(); // "Import successful on float"); + Assert_ItkImportWithinAccessByItkSucceded_ReturnsTrue(); // "Import successful on uchar"); + Assert_ItkImportWithinAccessByItkSucceded_ReturnsTrue(); // "Import successful on int"); MITK_TEST_END() } diff --git a/Modules/Core/test/mitkImageEqualTest.cpp b/Modules/Core/test/mitkImageEqualTest.cpp index 5c0c412ec6..97f351627b 100644 --- a/Modules/Core/test/mitkImageEqualTest.cpp +++ b/Modules/Core/test/mitkImageEqualTest.cpp @@ -1,121 +1,121 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkImage.h" #include "mitkImageGenerator.h" #include "mitkImageSliceSelector.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" class mitkImageEqualTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkImageEqualTestSuite); MITK_TEST(Equal_CloneAndOriginal_ReturnsTrue); MITK_TEST(Equal_DifferentImageGeometry_ReturnsFalse); MITK_TEST(Equal_DifferentPixelTypes_ReturnsFalse); MITK_TEST(Equal_DifferentDimensions_ReturnsFalse); MITK_TEST(Equal_DifferentDimensionalities_ReturnsFalse); MITK_TEST(Equal_DifferentPixelValues_ReturnsFalse); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different (sub-)tests. All members are initialized via setUp().*/ mitk::Image::Pointer m_Image; mitk::Image::Pointer m_AnotherImage; public: /** -* @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members +* @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used members * for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { // generate a gradient test image m_Image = mitk::ImageGenerator::GenerateGradientImage(3u, 3u, 1u); m_AnotherImage = m_Image->Clone(); } void tearDown() override { m_Image = nullptr; m_AnotherImage = nullptr; } void Equal_CloneAndOriginal_ReturnsTrue() { MITK_ASSERT_EQUAL(m_Image, m_Image->Clone(), "A clone should be equal to its original."); } void Equal_DifferentImageGeometry_ReturnsFalse() { mitk::Point3D origin; origin[0] = 0.0; origin[1] = 0.0; origin[2] = mitk::eps * 1.01; m_AnotherImage->GetGeometry()->SetOrigin(origin); MITK_ASSERT_NOT_EQUAL(m_Image, m_AnotherImage, "One origin was modified. Result should be false."); } void Equal_DifferentPixelTypes_ReturnsFalse() { m_AnotherImage = mitk::ImageGenerator::GenerateGradientImage(3u, 3u, 1u); MITK_ASSERT_NOT_EQUAL( m_Image, m_AnotherImage, "One pixel type is float, the other unsigned char. Result should be false."); } void Equal_DifferentDimensions_ReturnsFalse() { m_AnotherImage = mitk::ImageGenerator::GenerateGradientImage(5u, 7u, 3u); MITK_ASSERT_NOT_EQUAL( m_Image, m_AnotherImage, "Dimensions of first image are: (3, 3, 1). Dimensions of second image are: (5, 7, 3). Result should be false."); } void Equal_DifferentDimensionalities_ReturnsFalse() { // Select the first slice of a 2D image and compare it to the 3D original mitk::ImageSliceSelector::Pointer sliceSelector = mitk::ImageSliceSelector::New(); sliceSelector->SetInput(m_Image); sliceSelector->SetSliceNr(0); sliceSelector->Update(); m_AnotherImage = sliceSelector->GetOutput(); MITK_ASSERT_NOT_EQUAL(m_Image, m_AnotherImage, "First image is 3D. Second image is 2D. Result should be false."); } void Equal_DifferentPixelValues_ReturnsFalse() { // todo: Replace the random images via simpler images with fixed values. m_Image = mitk::ImageGenerator::GenerateRandomImage(3u, 3u); m_AnotherImage = mitk::ImageGenerator::GenerateRandomImage(3u, 3u); MITK_ASSERT_NOT_EQUAL(m_Image, m_AnotherImage, "We compare two random images. Result should be false."); } void Equal_EpsilonDifference_ReturnsTrue() { m_Image = mitk::ImageGenerator::GenerateRandomImage(10, 10); m_AnotherImage = m_Image->Clone(); CPPUNIT_ASSERT_MESSAGE("Epsilon = 0.0 --> double images should not be regarded as equal", !mitk::Equal(*m_Image, *m_AnotherImage, 0, true)); CPPUNIT_ASSERT_MESSAGE("Epsilon = 0.001 --> double images should be regarded as equal", mitk::Equal(*m_Image, *m_AnotherImage, 0.001, true)); } }; MITK_TEST_SUITE_REGISTRATION(mitkImageEqual) diff --git a/Modules/Core/test/mitkImageTest.cpp b/Modules/Core/test/mitkImageTest.cpp index 18abf3c780..8dd349ecbf 100644 --- a/Modules/Core/test/mitkImageTest.cpp +++ b/Modules/Core/test/mitkImageTest.cpp @@ -1,538 +1,538 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // mitk includes #include "mitkException.h" #include "mitkIOUtil.h" #include "mitkImageGenerator.h" #include "mitkImagePixelReadAccessor.h" #include "mitkImageReadAccessor.h" #include "mitkPixelTypeMultiplex.h" #include #include #include #include #include #include "mitkImageSliceSelector.h" // itk includes #include #include // stl includes #include // vtk includes #include // Checks if reference count is correct after using GetVtkImageData() bool ImageVtkDataReferenceCheck(const char *fname) { const std::string filename = std::string(fname); try { mitk::Image::Pointer image = mitk::IOUtil::Load(filename); MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(), "Non-nullptr image") vtkImageData *vtk = image->GetVtkImageData(); if (vtk == nullptr) return false; } catch (...) { MITK_TEST_FAILED_MSG(<< "Could not read file for testing: " << filename); return false; } return true; } template void TestRandomPixelAccess(const mitk::PixelType /*ptype*/, mitk::Image::Pointer image, mitk::Point3D &point, mitk::ScalarType &value) { // generate a random point in world coordinates mitk::Point3D xMax, yMax, zMax, xMaxIndex, yMaxIndex, zMaxIndex; xMaxIndex.Fill(0.0f); yMaxIndex.Fill(0.0f); zMaxIndex.Fill(0.0f); xMaxIndex[0] = image->GetLargestPossibleRegion().GetSize()[0]; yMaxIndex[1] = image->GetLargestPossibleRegion().GetSize()[1]; zMaxIndex[2] = image->GetLargestPossibleRegion().GetSize()[2]; image->GetGeometry()->IndexToWorld(xMaxIndex, xMax); image->GetGeometry()->IndexToWorld(yMaxIndex, yMax); image->GetGeometry()->IndexToWorld(zMaxIndex, zMax); MITK_INFO << "Origin " << image->GetGeometry()->GetOrigin()[0] << " " << image->GetGeometry()->GetOrigin()[1] << " " << image->GetGeometry()->GetOrigin()[2] << ""; MITK_INFO << "MaxExtend " << xMax[0] << " " << yMax[1] << " " << zMax[2] << ""; itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer randomGenerator = itk::Statistics::MersenneTwisterRandomVariateGenerator::New(); randomGenerator->Initialize(std::rand()); // initialize with random value, to get sensible random points for the image point[0] = randomGenerator->GetUniformVariate(image->GetGeometry()->GetOrigin()[0], xMax[0]); point[1] = randomGenerator->GetUniformVariate(image->GetGeometry()->GetOrigin()[1], yMax[1]); point[2] = randomGenerator->GetUniformVariate(image->GetGeometry()->GetOrigin()[2], zMax[2]); MITK_INFO << "RandomPoint " << point[0] << " " << point[1] << " " << point[2] << ""; // test values and max/min mitk::ScalarType imageMin = image->GetStatistics()->GetScalarValueMin(); mitk::ScalarType imageMax = image->GetStatistics()->GetScalarValueMax(); // test accessing PixelValue with coordinate leading to a negative index const mitk::Point3D geom_origin = image->GetGeometry()->GetOrigin(); const mitk::Point3D geom_center = image->GetGeometry()->GetCenter(); // shift position from origin outside of the image ( in the opposite direction to [center-origin] vector which points // in the inside) mitk::Point3D position = geom_origin + (geom_origin - geom_center); MITK_INFO << "Testing access outside of the image"; unsigned int dim = image->GetDimension(); if (dim == 3 || dim == 4) { mitk::ImagePixelReadAccessor imAccess3(image, image->GetVolumeData(0)); // Comparison ?>=0 not needed since all position[i] and timestep are unsigned int // (position[0]>=0 && position[1] >=0 && position[2]>=0 && timestep>=0) // bug-11978 : we still need to catch index with negative values if (point[0] < 0 || point[1] < 0 || point[2] < 0) { MITK_WARN << "Given position (" << point << ") is out of image range, returning 0."; } else { value = static_cast(imAccess3.GetPixelByWorldCoordinates(point)); MITK_TEST_CONDITION((value >= imageMin && value <= imageMax), "Value returned is between max/min"); } itk::Index<3> itkIndex; image->GetGeometry()->WorldToIndex(position, itkIndex); MITK_TEST_FOR_EXCEPTION_BEGIN(mitk::Exception); imAccess3.GetPixelByIndexSafe(itkIndex); MITK_TEST_FOR_EXCEPTION_END(mitk::Exception); } MITK_INFO << imageMin << " " << imageMax << " " << value << ""; } class mitkImageTestClass { public: void SetClonedGeometry_None_ClonedEqualInput() { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(100, 100, 100, 1, 0.2, 0.3, 0.4); //----------------- // geometry information for image mitk::Point3D origin; mitk::Vector3D right, bottom; mitk::Vector3D spacing; mitk::FillVector3D(origin, 17.0, 19.92, 7.83); mitk::FillVector3D(right, 1.0, 2.0, 3.0); mitk::FillVector3D(bottom, 0.0, -3.0, 2.0); mitk::FillVector3D(spacing, 0.78, 0.91, 2.23); // InitializeStandardPlane(rightVector, downVector, spacing) mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); planegeometry->InitializeStandardPlane(100, 100, right, bottom, &spacing); planegeometry->SetOrigin(origin); planegeometry->ChangeImageGeometryConsideringOriginOffset(true); image->SetClonedGeometry(planegeometry); mitk::BaseGeometry::Pointer imageGeometry = image->GetGeometry(); MITK_ASSERT_EQUAL(imageGeometry, planegeometry, "Matrix elements of cloned matrix equal original matrix"); } }; int mitkImageTest(int argc, char *argv[]) { MITK_TEST_BEGIN(mitkImageTest); mitkImageTestClass tester; tester.SetClonedGeometry_None_ClonedEqualInput(); // Create Image out of nowhere mitk::Image::Pointer imgMem = mitk::Image::New(); mitk::PixelType pt = mitk::MakeScalarPixelType(); unsigned int dim[] = {100, 100, 20}; MITK_TEST_CONDITION_REQUIRED(imgMem.IsNotNull(), "An image was created. "); // Initialize image imgMem->Initialize(pt, 3, dim); MITK_TEST_CONDITION_REQUIRED(imgMem->IsInitialized(), "Image::IsInitialized() ?"); MITK_TEST_CONDITION_REQUIRED(imgMem->GetPixelType() == pt, "PixelType was set correctly."); int *p = nullptr; int *p2 = nullptr; try { mitk::ImageReadAccessor imgMemAcc(imgMem); p = (int *)imgMemAcc.GetData(); } catch ( const mitk::Exception &e ) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION(p != nullptr, "GetData() returned not-nullptr pointer."); // filling image const unsigned int size = dim[0] * dim[1] * dim[2]; for (unsigned int i = 0; i < size; ++i, ++p) *p = (signed int)i; // Getting it again and compare with filled values: try { mitk::ImageReadAccessor imgMemAcc(imgMem); p2 = (int *)imgMemAcc.GetData(); } catch ( const mitk::Exception &e ) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION(p2 != nullptr, "GetData() returned not-nullptr pointer."); bool isEqual = true; for (unsigned int i = 0; i < size; ++i, ++p2) { if (*p2 != (signed int)i) { isEqual = false; } } MITK_TEST_CONDITION(isEqual, "The values previously set as data are correct [pixelwise comparison]."); // Testing GetSliceData() and compare with filled values: try { mitk::ImageReadAccessor imgMemAcc(imgMem, imgMem->GetSliceData(dim[2] / 2)); p2 = (int *)imgMemAcc.GetData(); } catch ( const mitk::Exception &e ) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION_REQUIRED(p2 != nullptr, "Valid slice data returned"); unsigned int xy_size = dim[0] * dim[1]; unsigned int start_mid_slice = (dim[2] / 2) * xy_size; isEqual = true; for (unsigned int i = 0; i < xy_size; ++i, ++p2) { if (*p2 != (signed int)(i + start_mid_slice)) { isEqual = false; } } MITK_TEST_CONDITION(isEqual, "The SliceData are correct [pixelwise comparison]. "); imgMem = mitk::Image::New(); // testing re-initialization of test image mitk::PixelType pType = mitk::MakePixelType(); imgMem->Initialize(pType, 3, dim); MITK_TEST_CONDITION_REQUIRED(imgMem->GetDimension() == 3, "Testing initialization parameter dimension!"); MITK_TEST_CONDITION_REQUIRED(imgMem->GetPixelType() == pType, "Testing initialization parameter pixeltype!"); MITK_TEST_CONDITION_REQUIRED( imgMem->GetDimension(0) == dim[0] && imgMem->GetDimension(1) == dim[1] && imgMem->GetDimension(2) == dim[2], "Testing initialization of dimensions!"); MITK_TEST_CONDITION(imgMem->IsInitialized(), "Image is initialized."); // Setting volume again: try { mitk::ImageReadAccessor imgMemAcc(imgMem); imgMem->SetVolume(imgMemAcc.GetData()); } catch ( const mitk::Exception &e ) { MITK_ERROR << e.what(); } //----------------- // geometry information for image mitk::Point3D origin; mitk::Vector3D right, bottom; mitk::Vector3D spacing; mitk::FillVector3D(origin, 17.0, 19.92, 7.83); mitk::FillVector3D(right, 1.0, 2.0, 3.0); mitk::FillVector3D(bottom, 0.0, -3.0, 2.0); mitk::FillVector3D(spacing, 0.78, 0.91, 2.23); // InitializeStandardPlane(rightVector, downVector, spacing) mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); planegeometry->InitializeStandardPlane(100, 100, right, bottom, &spacing); planegeometry->SetOrigin(origin); planegeometry->SetImageGeometry(true); // Testing Initialize(const mitk::PixelType& type, const mitk::Geometry3D& geometry, unsigned int slices) with // PlaneGeometry and GetData(): "; imgMem->Initialize(mitk::MakePixelType(), *planegeometry); MITK_TEST_CONDITION_REQUIRED( imgMem->GetGeometry()->GetOrigin() == static_cast(planegeometry)->GetOrigin(), "Testing correct setting of geometry via initialize!"); try { mitk::ImageReadAccessor imgMemAcc(imgMem); p = (int *)imgMemAcc.GetData(); } catch ( const mitk::Exception &e ) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION_REQUIRED(p != nullptr, "GetData() returned valid pointer."); // Testing Initialize(const mitk::PixelType& type, int sDim, const mitk::PlaneGeometry& geometry) and GetData(): "; imgMem->Initialize(mitk::MakePixelType(), 40, *planegeometry); try { mitk::ImageReadAccessor imgMemAcc(imgMem); p = (int *)imgMemAcc.GetData(); } catch ( const mitk::Exception &e ) { MITK_ERROR << e.what(); } MITK_TEST_CONDITION_REQUIRED(p != nullptr, "GetData() returned valid pointer."); //----------------- // testing origin information and methods MITK_TEST_CONDITION_REQUIRED(mitk::Equal(imgMem->GetGeometry()->GetOrigin(), origin), "Testing correctness of origin via GetGeometry()->GetOrigin(): "); // Setting origin via SetOrigin(origin): "; mitk::FillVector3D(origin, 37.0, 17.92, 27.83); imgMem->SetOrigin(origin); // Test origin MITK_TEST_CONDITION_REQUIRED(mitk::Equal(imgMem->GetGeometry()->GetOrigin(), origin), "Testing correctness of changed origin via GetGeometry()->GetOrigin(): "); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetSlicedGeometry()->GetPlaneGeometry(0)->GetOrigin(), origin), "Testing correctness of changed origin via GetSlicedGeometry()->GetPlaneGeometry(0)->GetOrigin(): "); //----------------- // testing spacing information and methodsunsigned int dim[]={100,100,20}; MITK_TEST_CONDITION_REQUIRED(mitk::Equal(imgMem->GetGeometry()->GetSpacing(), spacing), "Testing correct spacing from Geometry3D!"); mitk::FillVector3D(spacing, 7.0, 0.92, 1.83); imgMem->SetSpacing(spacing); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(imgMem->GetGeometry()->GetSpacing(), spacing), "Testing correctness of changed spacing via GetGeometry()->GetSpacing(): "); MITK_TEST_CONDITION_REQUIRED( mitk::Equal(imgMem->GetSlicedGeometry()->GetPlaneGeometry(0)->GetSpacing(), spacing), "Testing correctness of changed spacing via GetSlicedGeometry()->GetPlaneGeometry(0)->GetSpacing(): "); mitk::Image::Pointer vecImg = mitk::Image::New(); try { mitk::ImageReadAccessor imgMemAcc(imgMem); vecImg->Initialize(imgMem->GetPixelType(), *imgMem->GetGeometry(), 2 /* #channels */, 0 /*tDim*/); vecImg->SetImportChannel(const_cast(imgMemAcc.GetData()), 0, mitk::Image::CopyMemory); vecImg->SetImportChannel(const_cast(imgMemAcc.GetData()), 1, mitk::Image::CopyMemory); mitk::ImageReadAccessor vecImgAcc(vecImg); mitk::ImageReadAccessor vecImgAcc0(vecImg, vecImg->GetChannelData(0)); mitk::ImageReadAccessor vecImgAcc1(vecImg, vecImg->GetChannelData(1)); MITK_TEST_CONDITION_REQUIRED(vecImgAcc0.GetData() != nullptr && vecImgAcc1.GetData() != nullptr, "Testing set and return of channel data!"); MITK_TEST_CONDITION_REQUIRED(vecImg->IsValidSlice(0, 0, 1), ""); MITK_TEST_OUTPUT(<< " Testing whether CopyMemory worked"); MITK_TEST_CONDITION_REQUIRED(imgMemAcc.GetData() != vecImgAcc.GetData(), ""); MITK_TEST_OUTPUT(<< " Testing destruction after SetImportChannel"); vecImg = nullptr; MITK_TEST_CONDITION_REQUIRED(vecImg.IsNull(), "testing destruction!"); } catch ( const mitk::Exception &e ) { MITK_ERROR << e.what(); } //----------------- MITK_TEST_OUTPUT(<< "Testing initialization via vtkImageData"); MITK_TEST_OUTPUT(<< " Setting up vtkImageData"); vtkImageData *vtkimage = vtkImageData::New(); vtkimage->Initialize(); vtkimage->SetDimensions(2, 3, 4); double vtkorigin[] = {-350, -358.203, -1363.5}; vtkimage->SetOrigin(vtkorigin); mitk::Point3D vtkoriginAsMitkPoint; mitk::vtk2itk(vtkorigin, vtkoriginAsMitkPoint); double vtkspacing[] = {1.367, 1.367, 2}; vtkimage->SetSpacing(vtkspacing); vtkimage->AllocateScalars(VTK_SHORT, 1); std::cout << "[PASSED]" << std::endl; MITK_TEST_OUTPUT(<< " Testing mitk::Image::Initialize(vtkImageData*, ...)"); mitk::Image::Pointer mitkByVtkImage = mitk::Image::New(); mitkByVtkImage->Initialize(vtkimage); MITK_TEST_CONDITION_REQUIRED(mitkByVtkImage->IsInitialized(), ""); vtkimage->Delete(); MITK_TEST_OUTPUT(<< " Testing whether spacing has been correctly initialized from vtkImageData"); mitk::Vector3D spacing2 = mitkByVtkImage->GetGeometry()->GetSpacing(); mitk::Vector3D vtkspacingAsMitkVector; mitk::vtk2itk(vtkspacing, vtkspacingAsMitkVector); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(spacing2, vtkspacingAsMitkVector), ""); MITK_TEST_OUTPUT( << " Testing whether GetSlicedGeometry(0)->GetOrigin() has been correctly initialized from vtkImageData"); mitk::Point3D origin2 = mitkByVtkImage->GetSlicedGeometry(0)->GetOrigin(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(origin2, vtkoriginAsMitkPoint), ""); MITK_TEST_OUTPUT(<< " Testing whether GetGeometry()->GetOrigin() has been correctly initialized from vtkImageData"); origin2 = mitkByVtkImage->GetGeometry()->GetOrigin(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(origin2, vtkoriginAsMitkPoint), ""); MITK_TEST_OUTPUT(<< " Testing if vtkOrigin is (0, 0, 0). This behaviour is due to historical development of MITK. " - "Aslo see bug 5050!"); + "Also see bug 5050!"); vtkImageData *vtkImage = imgMem->GetVtkImageData(); auto vtkOrigin = vtkImage->GetOrigin(); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(vtkOrigin[0], 0), "testing vtkOrigin[0] to be 0"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(vtkOrigin[1], 0), "testing vtkOrigin[1] to be 0"); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(vtkOrigin[2], 0), "testing vtkOrigin[2] to be 0"); // testing access by index coordinates and by world coordinates MITK_TEST_CONDITION_REQUIRED(argc == 2, "Check if test image is accessible!"); const std::string filename = std::string(argv[1]); mitk::Image::Pointer image; try { image = mitk::IOUtil::Load(filename); MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(), "Non-nullptr image") } catch (...) { MITK_TEST_FAILED_MSG(<< "Could not read file for testing: " << filename); return 0; } mitk::Point3D point; mitk::ScalarType value = -1.; mitkPixelTypeMultiplex3( TestRandomPixelAccess, image->GetImageDescriptor()->GetChannelTypeById(0), image, point, value) { // testing the clone method of mitk::Image mitk::Image::Pointer cloneImage = image->Clone(); MITK_TEST_CONDITION_REQUIRED(cloneImage->GetDimension() == image->GetDimension(), "Clone (testing dimension)"); MITK_TEST_CONDITION_REQUIRED(cloneImage->GetPixelType() == image->GetPixelType(), "Clone (testing pixel type)"); // After cloning an image the geometry of both images should be equal too MITK_TEST_CONDITION_REQUIRED(cloneImage->GetGeometry()->GetOrigin() == image->GetGeometry()->GetOrigin(), "Clone (testing origin)"); MITK_TEST_CONDITION_REQUIRED(cloneImage->GetGeometry()->GetSpacing() == image->GetGeometry()->GetSpacing(), "Clone (testing spacing)"); MITK_TEST_CONDITION_REQUIRED( mitk::MatrixEqualElementWise(cloneImage->GetGeometry()->GetIndexToWorldTransform()->GetMatrix(), image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix()), "Clone (testing transformation matrix)"); MITK_TEST_CONDITION_REQUIRED( mitk::MatrixEqualElementWise(cloneImage->GetTimeGeometry() ->GetGeometryForTimeStep(cloneImage->GetDimension(3) - 1) ->GetIndexToWorldTransform() ->GetMatrix(), cloneImage->GetTimeGeometry() ->GetGeometryForTimeStep(image->GetDimension(3) - 1) ->GetIndexToWorldTransform() ->GetMatrix()), "Clone(testing time sliced geometry)"); for (unsigned int i = 0u; i < cloneImage->GetDimension(); ++i) { MITK_TEST_CONDITION_REQUIRED(cloneImage->GetDimension(i) == image->GetDimension(i), "Clone (testing dimension " << i << ")"); } } // access via itk if (image->GetDimension() > 3) // CastToItk only works with 3d images so we need to check for 4d images { mitk::ImageTimeSelector::Pointer selector = mitk::ImageTimeSelector::New(); selector->SetTimeNr(0); selector->SetInput(image); selector->Update(); image = selector->GetOutput(); } if (image->GetDimension() == 3) { typedef itk::Image ItkFloatImage3D; ItkFloatImage3D::Pointer itkimage; try { mitk::CastToItkImage(image, itkimage); MITK_TEST_CONDITION_REQUIRED(itkimage.IsNotNull(), "Test conversion to itk::Image!"); } catch ( const std::exception &e ) { MITK_INFO << e.what(); } mitk::Point3D itkPhysicalPoint; image->GetGeometry()->WorldToItkPhysicalPoint(point, itkPhysicalPoint); MITK_INFO << "ITKPoint " << itkPhysicalPoint[0] << " " << itkPhysicalPoint[1] << " " << itkPhysicalPoint[2] << ""; mitk::Point3D backTransformedPoint; image->GetGeometry()->ItkPhysicalPointToWorld(itkPhysicalPoint, backTransformedPoint); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(point, backTransformedPoint), "Testing world->itk-physical->world consistency"); itk::Index<3> idx; bool status = itkimage->TransformPhysicalPointToIndex(itkPhysicalPoint, idx); MITK_INFO << "ITK Index " << idx[0] << " " << idx[1] << " " << idx[2] << ""; if (status && value != -1.) { float valByItk = itkimage->GetPixel(idx); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(valByItk, value), "Compare value of pixel returned by mitk in comparison to itk"); } else { MITK_WARN << "Index is out buffered region!"; } } else { MITK_INFO << "Image does not contain three dimensions, some test cases are skipped!"; } // clone generated 3D image with one slice in z direction (cf. bug 11058) auto *threeDdim = new unsigned int[3]; threeDdim[0] = 100; threeDdim[1] = 200; threeDdim[2] = 1; mitk::Image::Pointer threeDImage = mitk::Image::New(); threeDImage->Initialize(mitk::MakeScalarPixelType(), 3, threeDdim); mitk::Image::Pointer cloneThreeDImage = threeDImage->Clone(); // check that the clone image has the same dimensionality as the source image MITK_TEST_CONDITION_REQUIRED(cloneThreeDImage->GetDimension() == 3, "Testing if the clone image initializes with 3D!"); MITK_TEST_CONDITION_REQUIRED(ImageVtkDataReferenceCheck(argv[1]), "Checking reference count of Image after using GetVtkImageData()"); MITK_TEST_END(); } diff --git a/Modules/Core/test/mitkImageToSurfaceFilterTest.cpp b/Modules/Core/test/mitkImageToSurfaceFilterTest.cpp index 7288503d2b..3e86268336 100644 --- a/Modules/Core/test/mitkImageToSurfaceFilterTest.cpp +++ b/Modules/Core/test/mitkImageToSurfaceFilterTest.cpp @@ -1,150 +1,150 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkException.h" #include "mitkImageToSurfaceFilter.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include bool CompareSurfacePointPositions(mitk::Surface::Pointer s1, mitk::Surface::Pointer s2) { vtkPoints *p1 = s1->GetVtkPolyData()->GetPoints(); vtkPoints *p2 = s2->GetVtkPolyData()->GetPoints(); if (p1->GetNumberOfPoints() != p2->GetNumberOfPoints()) return false; for (int i = 0; i < p1->GetNumberOfPoints(); ++i) { if (p1->GetPoint(i)[0] != p2->GetPoint(i)[0] || p1->GetPoint(i)[1] != p2->GetPoint(i)[1] || p1->GetPoint(i)[2] != p2->GetPoint(i)[2]) { return true; } } return false; } class mitkImageToSurfaceFilterTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkImageToSurfaceFilterTestSuite); MITK_TEST(testImageToSurfaceFilterInitialization); MITK_TEST(testInput); MITK_TEST(testSurfaceGeneration); MITK_TEST(testDecimatePromeshDecimation); MITK_TEST(testQuadricDecimation); MITK_TEST(testSmoothingOfSurface); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different test methods. All members are initialized via setUp().*/ mitk::Image::Pointer m_BallImage; public: /** - * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used + * @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used * members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_BallImage = mitk::IOUtil::Load(GetTestDataFilePath("BallBinary30x30x30.nrrd")); } void tearDown() override {} void testImageToSurfaceFilterInitialization() { mitk::ImageToSurfaceFilter::Pointer testObject = mitk::ImageToSurfaceFilter::New(); CPPUNIT_ASSERT_MESSAGE("Testing instantiation of test object", testObject.IsNotNull()); // testing initialization of member variables! CPPUNIT_ASSERT_MESSAGE("Testing initialization of threshold member variable", testObject->GetThreshold() == 1.0f); CPPUNIT_ASSERT_MESSAGE("Testing initialization of smooth member variable", testObject->GetSmooth() == false); CPPUNIT_ASSERT_MESSAGE("Testing initialization of decimate member variable", testObject->GetDecimate() == mitk::ImageToSurfaceFilter::NoDecimation); CPPUNIT_ASSERT_MESSAGE("Testing initialization of target reduction member variable", testObject->GetTargetReduction() == 0.95f); } void testInput() { mitk::ImageToSurfaceFilter::Pointer testObject = mitk::ImageToSurfaceFilter::New(); testObject->SetInput(m_BallImage); CPPUNIT_ASSERT_MESSAGE("Testing set / get input!", testObject->GetInput() == m_BallImage); } void testSurfaceGeneration() { mitk::ImageToSurfaceFilter::Pointer testObject = mitk::ImageToSurfaceFilter::New(); testObject->SetInput(m_BallImage); testObject->Update(); mitk::Surface::Pointer resultSurface = nullptr; resultSurface = testObject->GetOutput(); CPPUNIT_ASSERT_MESSAGE("Testing surface generation!", testObject->GetOutput() != nullptr); } void testDecimatePromeshDecimation() { mitk::ImageToSurfaceFilter::Pointer testObject = mitk::ImageToSurfaceFilter::New(); testObject->SetInput(m_BallImage); testObject->Update(); mitk::Surface::Pointer resultSurface = nullptr; resultSurface = testObject->GetOutput(); mitk::Surface::Pointer testSurface1 = testObject->GetOutput()->Clone(); testObject->SetDecimate(mitk::ImageToSurfaceFilter::DecimatePro); testObject->SetTargetReduction(0.5f); testObject->Update(); mitk::Surface::Pointer testSurface2 = testObject->GetOutput()->Clone(); CPPUNIT_ASSERT_MESSAGE("Testing DecimatePro mesh decimation!", testSurface1->GetVtkPolyData()->GetPoints()->GetNumberOfPoints() > testSurface2->GetVtkPolyData()->GetPoints()->GetNumberOfPoints()); } void testQuadricDecimation() { mitk::ImageToSurfaceFilter::Pointer testObject = mitk::ImageToSurfaceFilter::New(); testObject->SetInput(m_BallImage); testObject->Update(); mitk::Surface::Pointer resultSurface = nullptr; resultSurface = testObject->GetOutput(); mitk::Surface::Pointer testSurface1 = testObject->GetOutput()->Clone(); testObject->SetDecimate(mitk::ImageToSurfaceFilter::QuadricDecimation); testObject->SetTargetReduction(0.5f); testObject->Update(); mitk::Surface::Pointer testSurface3 = testObject->GetOutput()->Clone(); CPPUNIT_ASSERT_MESSAGE("Testing QuadricDecimation mesh decimation!", testSurface1->GetVtkPolyData()->GetPoints()->GetNumberOfPoints() > testSurface3->GetVtkPolyData()->GetPoints()->GetNumberOfPoints()); } void testSmoothingOfSurface() { mitk::ImageToSurfaceFilter::Pointer testObject = mitk::ImageToSurfaceFilter::New(); testObject->SetInput(m_BallImage); testObject->Update(); mitk::Surface::Pointer resultSurface = nullptr; resultSurface = testObject->GetOutput(); mitk::Surface::Pointer testSurface1 = testObject->GetOutput()->Clone(); testObject->SetSmooth(true); testObject->SetDecimate(mitk::ImageToSurfaceFilter::NoDecimation); testObject->Update(); mitk::Surface::Pointer testSurface4 = testObject->GetOutput()->Clone(); CPPUNIT_ASSERT_MESSAGE("Testing smoothing of surface changes point data!", CompareSurfacePointPositions(testSurface1, testSurface4)); } }; MITK_TEST_SUITE_REGISTRATION(mitkImageToSurfaceFilter) diff --git a/Modules/Core/test/mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp b/Modules/Core/test/mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp index fe18d6cbde..2ac597cf87 100644 --- a/Modules/Core/test/mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp +++ b/Modules/Core/test/mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp @@ -1,87 +1,87 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // MITK #include "mitkDataNode.h" #include "mitkIOUtil.h" #include "mitkRenderingTestHelper.h" #include "mitkTestingMacros.h" #include // VTK #include #include int mitkImageVtkMapper2DResliceInterpolationPropertyTest(int argc, char *argv[]) { try { mitk::RenderingTestHelper openGlTest(640, 480); } catch (const mitk::TestNotRunException &e) { MITK_WARN << "Test not run: " << e.GetDescription(); return 77; } // load all arguments into a datastorage, take last argument as reference // setup a renderwindow of fixed size X*Y // render the datastorage // compare rendering to reference image // note: this test is supposed to test the reslice interpolation modes not the swiveling itself MITK_TEST_BEGIN("mitkImageVtkMapper2DResliceInterpolationPropertyTest") mitk::RenderingTestHelper renderingHelper(640, 480, argc, argv); - // get resliceInterpolation from comandline arg + // get resliceInterpolation from commandline arg int resliceInterpolation = atoi(argv[argc - 4]); // Set interpolation mode for rendering renderingHelper.SetImageProperty("reslice interpolation", mitk::VtkResliceInterpolationProperty::New(resliceInterpolation)); /*+++rotate plane+++*/ // center point for rotation mitk::Point3D centerPoint; centerPoint.Fill(0.0f); // vector for rotating the slice mitk::Vector3D rotationVector; rotationVector.SetElement(0, 0.2); rotationVector.SetElement(1, 0.3); rotationVector.SetElement(2, 0.5); // sets a swivel direction for the image // new version of setting the center point: mitk::Image::Pointer image = static_cast( renderingHelper.GetDataStorage()->GetNode(mitk::NodePredicateDataType::New("Image"))->GetData()); // get the center point of the image centerPoint = image->GetGeometry()->GetCenter(); - // rotate the image arround its own center + // rotate the image around its own center renderingHelper.ReorientSlices(centerPoint, rotationVector); // threshold for CompareRenderWindowAgainstReference double threshold = 0.35; // difference between interpolation modes is very small //### Usage of CompareRenderWindowAgainstReference: See docu of mitkRrenderingTestHelper MITK_TEST_CONDITION(renderingHelper.CompareRenderWindowAgainstReference(argc, argv, threshold) == true, "CompareRenderWindowAgainstReference test result positive?"); // use this to generate a reference screenshot or save the file: if (false) { renderingHelper.Render(); renderingHelper.SaveReferenceScreenShot("C:\\Users\\schroedt\\Pictures\\RenderingTestData\\Pic3dRefLinear.png"); } MITK_TEST_END(); } diff --git a/Modules/Core/test/mitkImageVtkMapper2DSwivelTest.cpp b/Modules/Core/test/mitkImageVtkMapper2DSwivelTest.cpp index 69ab654ca0..8f62328eab 100644 --- a/Modules/Core/test/mitkImageVtkMapper2DSwivelTest.cpp +++ b/Modules/Core/test/mitkImageVtkMapper2DSwivelTest.cpp @@ -1,72 +1,72 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // MITK #include "mitkImage.h" #include "mitkRenderingTestHelper.h" #include "mitkTestingMacros.h" #include // VTK #include int mitkImageVtkMapper2DSwivelTest(int argc, char *argv[]) { try { mitk::RenderingTestHelper openGlTest(640, 480); } catch (const mitk::TestNotRunException &e) { MITK_WARN << "Test not run: " << e.GetDescription(); return 77; } // load all arguments into a datastorage, take last argument as reference // setup a renderwindow of fixed size X*Y // render the datastorage // compare rendering to reference image MITK_TEST_BEGIN("mitkImageVtkMapper2DSwivelTest") mitk::RenderingTestHelper renderingHelper(640, 480, argc, argv); // center point for rotation mitk::Point3D centerPoint; centerPoint.Fill(0.0f); // vector for rotating the slice mitk::Vector3D rotationVector; rotationVector.SetElement(0, 0.2); rotationVector.SetElement(1, 0.3); rotationVector.SetElement(2, 0.5); // sets a swivel direction for the image // new version of setting the center point: mitk::Image::Pointer image = static_cast( renderingHelper.GetDataStorage()->GetNode(mitk::NodePredicateDataType::New("Image"))->GetData()); // get the center point of the image centerPoint = image->GetGeometry()->GetCenter(); - // rotate the image arround its own center + // rotate the image around its own center renderingHelper.ReorientSlices(centerPoint, rotationVector); //### Usage of CompareRenderWindowAgainstReference: See docu of mitkRrenderingTestHelper MITK_TEST_CONDITION(renderingHelper.CompareRenderWindowAgainstReference(argc, argv) == true, "CompareRenderWindowAgainstReference test result positive?"); // use this to generate a reference screenshot or save the file: if (false) { renderingHelper.SaveReferenceScreenShot( "/media/hdd/thomasHdd/Pictures/RenderingTestData/pic3dSwivel640x480REF.png"); } MITK_TEST_END(); } diff --git a/Modules/Core/test/mitkImportItkImageTest.cpp b/Modules/Core/test/mitkImportItkImageTest.cpp index 1ce29b55b1..123f01f9f8 100644 --- a/Modules/Core/test/mitkImportItkImageTest.cpp +++ b/Modules/Core/test/mitkImportItkImageTest.cpp @@ -1,306 +1,306 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkITKImageImport.h" #include "mitkImageCast.h" #include "mitkTestingMacros.h" #include "mitkImagePixelReadAccessor.h" #include #include /** * Create a test image with random pixel values. The image size is determined by the input parameter. * * @param size the number of voxels in each dimension */ template typename itk::Image::Pointer CreateTestImageRandom(short int size) { typedef typename itk::Image ImageType; itk::Size regionSize; regionSize.Fill(size); typename itk::RandomImageSource::Pointer randomImageSource = itk::RandomImageSource::New(); randomImageSource->SetNumberOfWorkUnits(1); // to produce non-random results randomImageSource->SetSize(regionSize); randomImageSource->Update(); return randomImageSource->GetOutput(); } /** * Create a test vector image (with two components) with a single pixel value. The image size is determined by the input * parameter. * * @param value the pixel value the created image is filled with * @param size the number of voxels in each dimension */ template typename itk::VectorImage::Pointer CreateTestVectorImageFixedValue( size_t size, const itk::VariableLengthVector &value) { typedef typename itk::VectorImage ImageType; typedef typename ImageType::Pointer ImagePointer; typename ImageType::RegionType imageRegion; typename ImageType::RegionType::SizeType regionSize; regionSize.Fill(size); typename ImageType::RegionType::IndexType regionIndex; regionIndex.Fill(0); imageRegion.SetSize(regionSize); imageRegion.SetIndex(regionIndex); typename ImageType::SpacingType imageSpacing; imageSpacing.Fill(1.0f); typename ImageType::PointType imageOrigin; imageOrigin.Fill(0.0f); ImagePointer itkImage = ImageType::New(); itkImage->SetVectorLength(value.GetNumberOfElements()); itkImage->SetRegions(imageRegion); itkImage->SetOrigin(imageOrigin); itkImage->SetSpacing(imageSpacing); itkImage->Allocate(); itkImage->FillBuffer(value); return itkImage; } /** * Create a test image with a single pixel value. The image size is determined by the input parameter. * * @param value the pixel value the created image is filled with * @param size the number of voxels in each dimension */ template typename itk::Image::Pointer CreateTestImageFixedValue(size_t size, TPixel value) { typedef typename itk::Image ImageType; typedef typename ImageType::Pointer ImagePointer; typename ImageType::RegionType imageRegion; typename ImageType::RegionType::SizeType regionSize; regionSize.Fill(size); typename ImageType::RegionType::IndexType regionIndex; regionIndex.Fill(0); imageRegion.SetSize(regionSize); imageRegion.SetIndex(regionIndex); typename ImageType::SpacingType imageSpacing; imageSpacing.Fill(1.0f); typename ImageType::PointType imageOrigin; imageOrigin.Fill(0.0f); ImagePointer itkImage = ImageType::New(); itkImage->SetRegions(imageRegion); itkImage->SetOrigin(imageOrigin); itkImage->SetSpacing(imageSpacing); itkImage->Allocate(); itkImage->FillBuffer(value); return itkImage; } /** * Compares the meta information of both given images for equality. */ template bool Assert_ImageMetaData_AreEqual(typename ImageType::Pointer itkImage, mitk::Image::Pointer mitkImage) { bool return_value = true; typename ImageType::RegionType itkRegion = itkImage->GetLargestPossibleRegion(); typename ImageType::SizeType itkImageSize = itkRegion.GetSize(); // check dimension for (unsigned int idx = 0; idx < mitkImage->GetDimension(); idx++) { return_value &= (itkImageSize[idx] == mitkImage->GetDimension(idx)); } MITK_TEST_CONDITION(return_value, " - Dimensions equal!") // check pixel type bool ptype_compare = (mitkImage->GetPixelType() == mitk::MakePixelType()); return_value &= ptype_compare; MITK_TEST_CONDITION(ptype_compare, " - Pixel types equal!") mitk::BaseGeometry *imageGeometry = mitkImage->GetGeometry(); const mitk::Point3D origin = imageGeometry->GetOrigin(); bool origin_compare = true; for (unsigned int idx = 0; idx < 3; idx++) { origin_compare &= (itkImage->GetOrigin()[idx] == origin[idx]); } return_value &= origin_compare; MITK_TEST_CONDITION(origin_compare, " - Origin equals!") return return_value; } /** * Generates a random itk image and imports it to mitk image through ImportItkImage and compares the values * voxel-wise afterwards */ template void Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue() { std::stringstream msg; msg << "Current type: (Random Image, " << VDimension << "D):" << typeid(TPixel).name() << "\n"; std::cout << msg.str(); bool assert_value = true; typedef typename itk::Image ImageType; typedef typename ImageType::Pointer ImagePointer; ImagePointer itkImage = CreateTestImageRandom(5); mitk::Image::Pointer output_import = mitk::ImportItkImage(itkImage); itk::ImageRegionConstIteratorWithIndex iter(itkImage, itkImage->GetLargestPossibleRegion()); iter.GoToBegin(); mitk::ImagePixelReadAccessor readAccessor(output_import); bool difference = false; while (!iter.IsAtEnd()) { TPixel ref = iter.Get(); TPixel val = readAccessor.GetPixelByIndex(iter.GetIndex()); difference |= (ref != val); if (difference) { std::cout << iter.GetIndex() << ":" << ref << " ? " << val << "\n"; } ++iter; } assert_value = Assert_ImageMetaData_AreEqual(itkImage, output_import); MITK_TEST_CONDITION(assert_value && (!difference), "Pixel values are same in voxel-wise comparison."); } /** * Generates an itk image with fixed pixel value and imports it to mitk image through ImportItkImage * and compares the values voxel-wise afterwards */ template void Assert_ItkImageImportSucceded_ReturnsTrue() { std::stringstream msg; msg << "Current type: " << VDimension << "D):" << typeid(TPixel).name() << "\n"; std::cout << msg.str(); bool assert_value = true; typedef typename itk::Image ImageType; typedef typename ImageType::Pointer ImagePointer; ImagePointer itkImage = CreateTestImageFixedValue(5, itk::NumericTraits::min()); mitk::Image::Pointer output_import = mitk::ImportItkImage(itkImage); itk::ImageRegionConstIteratorWithIndex iter(itkImage, itkImage->GetLargestPossibleRegion()); iter.GoToBegin(); mitk::ImagePixelReadAccessor readAccessor(output_import); bool difference = false; while (!iter.IsAtEnd()) { TPixel ref = iter.Get(); TPixel val = readAccessor.GetPixelByIndex(iter.GetIndex()); difference |= (ref != val); if (difference) { std::cout << iter.GetIndex() << ":" << ref << " ? " << val << "\n"; } ++iter; } assert_value = Assert_ImageMetaData_AreEqual(itkImage, output_import); MITK_TEST_CONDITION(assert_value && (!difference), "Pixel values are same in voxel-wise comparison."); } void Assert_ItkVectorImageImportAndCast_ReturnsTrue() { typedef itk::VectorImage ImageType; ImageType::PixelType value; value.SetSize(2); value.SetElement(0, 1); value.SetElement(0, 2); ImageType::Pointer itkImage = CreateTestVectorImageFixedValue(5, value); mitk::Image::Pointer mitkImage = mitk::ImportItkImage(itkImage); mitk::PixelType pixelType = mitkImage->GetPixelType(); MITK_TEST_CONDITION(pixelType.GetPixelType() == itk::IOPixelEnum::VECTOR, "Vector image pixel type") MITK_TEST_CONDITION(pixelType.GetComponentType() == itk::IOComponentEnum::SHORT, "Vector image component type") mitk::Image::Pointer mitkImage2; mitk::CastToMitkImage(itkImage, mitkImage2); mitk::PixelType pixelType2 = mitkImage2->GetPixelType(); MITK_TEST_CONDITION(pixelType == pixelType2, "ImportItkImage and CastToMitkImage produce same pixel types") ImageType::Pointer itkImageOut; mitk::CastToItkImage(mitkImage, itkImageOut); MITK_TEST_CONDITION(pixelType == mitk::MakePixelType(2), "MITK pixel type equals ITK pixel type") typedef itk::VectorImage IntImageType; IntImageType::Pointer itkIntImageOut; mitk::CastToItkImage(mitkImage, itkIntImageOut); MITK_TEST_CONDITION(!(pixelType == mitk::MakePixelType(2)), "MITK pixel type != ITK pixel type") mitk::Image::Pointer mitkImage3; mitk::CastToMitkImage(itkImageOut, mitkImage3); MITK_ASSERT_EQUAL(mitkImage, mitkImage3, "Equality for vector images"); } int mitkImportItkImageTest(int /*argc*/, char * /*argv*/ []) { MITK_TEST_BEGIN("mitkImportItkImageTest") - Assert_ItkImageImportSucceded_ReturnsTrue(); // "Import succesfull on 3D short"); - Assert_ItkImageImportSucceded_ReturnsTrue(); // "Import succesfull on float"); - Assert_ItkImageImportSucceded_ReturnsTrue(); // "Import succesfull on uchar"); - Assert_ItkImageImportSucceded_ReturnsTrue(); // "Import succesfull on int"); - - Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import succesfull on 3D short"); - Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import succesfull on float"); - Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import succesfull on uchar"); - Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import succesfull on int"); - - Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import succesfull on 3D short"); - Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import succesfull on float"); - Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import succesfull on uchar"); - Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import succesfull on int"); + Assert_ItkImageImportSucceded_ReturnsTrue(); // "Import successful on 3D short"); + Assert_ItkImageImportSucceded_ReturnsTrue(); // "Import successful on float"); + Assert_ItkImageImportSucceded_ReturnsTrue(); // "Import successful on uchar"); + Assert_ItkImageImportSucceded_ReturnsTrue(); // "Import successful on int"); + + Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import successful on 3D short"); + Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import successful on float"); + Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import successful on uchar"); + Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import successful on int"); + + Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import successful on 3D short"); + Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import successful on float"); + Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import successful on uchar"); + Assert_ItkImageImportRandomValuesSucceded_ReturnsTrue(); // "Import successful on int"); Assert_ItkVectorImageImportAndCast_ReturnsTrue(); MITK_TEST_END() } diff --git a/Modules/Core/test/mitkItkImageIOTest.cpp b/Modules/Core/test/mitkItkImageIOTest.cpp index a9d8d6d9eb..e35cd8d340 100644 --- a/Modules/Core/test/mitkItkImageIOTest.cpp +++ b/Modules/Core/test/mitkItkImageIOTest.cpp @@ -1,428 +1,428 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkException.h" #include #include #include #include "mitkIOUtil.h" #include #include "mitkITKImageImport.h" #include #include "itksys/SystemTools.hxx" #include #include #include #ifdef WIN32 #include "process.h" #else #include #endif class mitkItkImageIOTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkItkImageIOTestSuite); MITK_TEST(TestImageWriterJpg); MITK_TEST(TestImageWriterPng1); MITK_TEST(TestImageWriterPng2); MITK_TEST(TestImageWriterPng3); MITK_TEST(TestImageWriterSimple); MITK_TEST(TestWrite3DImageWithOnePlane); MITK_TEST(TestWrite3DImageWithTwoPlanes); MITK_TEST(TestWrite3DplusT_ArbitraryTG); MITK_TEST(TestWrite3DplusT_ProportionalTG); CPPUNIT_TEST_SUITE_END(); public: void setUp() override {} void tearDown() override {} void TestImageWriterJpg() { TestImageWriter("NrrdWritingTestImage.jpg"); } void TestImageWriterPng1() { TestImageWriter("Png2D-bw.png"); } void TestImageWriterPng2() { TestImageWriter("RenderingTestData/rgbImage.png"); } void TestImageWriterPng3() { TestImageWriter("RenderingTestData/rgbaImage.png"); } void TestWrite3DplusT_ArbitraryTG() { TestImageWriter("3D+t-ITKIO-TestData/LinearModel_4D_arbitrary_time_geometry.nrrd"); } void TestWrite3DplusT_ProportionalTG() { TestImageWriter("3D+t-ITKIO-TestData/LinearModel_4D_prop_time_geometry.nrrd"); } void TestImageWriterSimple() { // TODO } std::string AppendExtension(const std::string &filename, const char *extension) { std::string new_filename = filename; new_filename += extension; return new_filename; } bool CompareImageMetaData(mitk::Image::Pointer image, mitk::Image::Pointer reference, bool checkPixelType = true) { // switch to AreIdentical() methods as soon as Bug 11925 (Basic comparison operators) is fixed if (image->GetDimension() != reference->GetDimension()) { MITK_ERROR << "The image dimension differs: IN (" << image->GetDimension() << ") REF(" << reference->GetDimension() << ")"; return false; } // pixel type if (checkPixelType && (image->GetPixelType() != reference->GetPixelType() && image->GetPixelType().GetBitsPerComponent() != reference->GetPixelType().GetBitsPerComponent())) { MITK_ERROR << "Pixeltype differs ( image=" << image->GetPixelType().GetPixelTypeAsString() << "[" << image->GetPixelType().GetBitsPerComponent() << "]" << " reference=" << reference->GetPixelType().GetPixelTypeAsString() << "[" << reference->GetPixelType().GetBitsPerComponent() << "]" << " )"; return false; } return true; } /* Test writing picture formats like *.bmp, *.png, *.tiff or *.jpg NOTE: Saving as picture format must ignore PixelType comparison - not all bits per components are supported (see specification of the format) */ void TestPictureWriting(mitk::Image *image, const std::string &filename, const std::string &extension) { const std::string fullFileName = AppendExtension(filename, extension.c_str()); mitk::Image::Pointer singleSliceImage = nullptr; if (image->GetDimension() == 3) { mitk::ExtractSliceFilter::Pointer extractFilter = mitk::ExtractSliceFilter::New(); extractFilter->SetInput(image); extractFilter->SetWorldGeometry(image->GetSlicedGeometry()->GetPlaneGeometry(0)); extractFilter->Update(); singleSliceImage = extractFilter->GetOutput(); // test 3D writing in format supporting only 2D mitk::IOUtil::Save(image, fullFileName); // test images unsigned int foundImagesCount = 0; - // if the image only contains one sinlge slice the itkImageSeriesWriter won't add a number like + // if the image only contains one single slice the itkImageSeriesWriter won't add a number like // filename.XX.extension if (image->GetDimension(2) == 1) { std::stringstream series_filenames; series_filenames << filename << extension; mitk::Image::Pointer compareImage = mitk::IOUtil::Load(series_filenames.str()); if (compareImage.IsNotNull()) { foundImagesCount++; MITK_TEST_CONDITION( CompareImageMetaData(singleSliceImage, compareImage, false), "Image meta data unchanged after writing and loading again. "); // ignore bits per component } remove(series_filenames.str().c_str()); } else // test the whole slice stack { for (unsigned int i = 0; i < image->GetDimension(2); i++) { std::stringstream series_filenames; series_filenames << filename << "." << i + 1 << extension; mitk::Image::Pointer compareImage = mitk::IOUtil::Load(series_filenames.str()); if (compareImage.IsNotNull()) { foundImagesCount++; MITK_TEST_CONDITION( CompareImageMetaData(singleSliceImage, compareImage, false), "Image meta data unchanged after writing and loading again. "); // ignore bits per component } remove(series_filenames.str().c_str()); } } MITK_TEST_CONDITION(foundImagesCount == image->GetDimension(2), "All 2D-Slices of a 3D image were stored correctly."); } else if (image->GetDimension() == 2) { singleSliceImage = image; } // test 2D writing if (singleSliceImage.IsNotNull()) { try { mitk::IOUtil::Save(singleSliceImage, fullFileName); mitk::Image::Pointer compareImage = mitk::IOUtil::Load(fullFileName.c_str()); - MITK_TEST_CONDITION_REQUIRED(compareImage.IsNotNull(), "Image stored was succesfully loaded again"); + MITK_TEST_CONDITION_REQUIRED(compareImage.IsNotNull(), "Image stored was successfully loaded again"); MITK_TEST_CONDITION_REQUIRED( CompareImageMetaData(singleSliceImage, compareImage, false), "Image meta data unchanged after writing and loading again. "); // ignore bits per component remove(fullFileName.c_str()); } catch (itk::ExceptionObject &e) { MITK_TEST_FAILED_MSG(<< "Exception during file writing for ." << extension << ": " << e.what()); } } } /** * test for writing NRRDs */ void TestNRRDWriting(const mitk::Image *image) { CPPUNIT_ASSERT_MESSAGE("Internal error. Passed reference image is null.", image); std::ofstream tmpStream; std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.nrrd"); tmpStream.close(); try { mitk::IOUtil::Save(image, tmpFilePath); mitk::Image::Pointer compareImage = mitk::IOUtil::Load(tmpFilePath); - CPPUNIT_ASSERT_MESSAGE("Image stored in NRRD format was succesfully loaded again", compareImage.IsNotNull()); + CPPUNIT_ASSERT_MESSAGE("Image stored in NRRD format was successfully loaded again", compareImage.IsNotNull()); - /*It would make sence to check the images as well (see commented cppunit assert), + /*It would make sense to check the images as well (see commented cppunit assert), but currently there seems to be a problem (exception) with most of the test images (partly it seems to be a problem when try to access the pixel content by AccessByItk_1 in mitk::CompareImageDataFilter. This problem should be dealt with in Bug 19533 - mitkITKImageIOTest needs improvement */ // CPPUNIT_ASSERT_MESSAGE("Images are equal.", mitk::Equal(*image, *compareImage, mitk::eps, true)); CPPUNIT_ASSERT_MESSAGE( "TimeGeometries are equal.", mitk::Equal(*(image->GetTimeGeometry()), *(compareImage->GetTimeGeometry()), mitk::eps, true)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Error, read image has different UID", image->GetUID(), compareImage->GetUID()); remove(tmpFilePath.c_str()); } catch (...) { std::remove(tmpFilePath.c_str()); CPPUNIT_FAIL("Exception during NRRD file writing"); } } /** * test for writing MHDs */ void TestMHDWriting(const mitk::Image *image) { CPPUNIT_ASSERT_MESSAGE("Internal error. Passed reference image is null.", image); std::ofstream tmpStream; std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX.mhd"); tmpStream.close(); std::string tmpFilePathWithoutExt = tmpFilePath.substr(0, tmpFilePath.size() - 4); try { mitk::IOUtil::Save(image, tmpFilePath); mitk::Image::Pointer compareImage = mitk::IOUtil::Load(tmpFilePath); - CPPUNIT_ASSERT_MESSAGE("Image stored in MHD format was succesfully loaded again! ", compareImage.IsNotNull()); + CPPUNIT_ASSERT_MESSAGE("Image stored in MHD format was successfully loaded again! ", compareImage.IsNotNull()); CPPUNIT_ASSERT_MESSAGE(".mhd file exists", itksys::SystemTools::FileExists(mitk::Utf8Util::Local8BitToUtf8(tmpFilePathWithoutExt + ".mhd").c_str())); CPPUNIT_ASSERT_MESSAGE(".raw or .zraw exists", itksys::SystemTools::FileExists(mitk::Utf8Util::Local8BitToUtf8(tmpFilePathWithoutExt + ".raw").c_str()) || itksys::SystemTools::FileExists(mitk::Utf8Util::Local8BitToUtf8(tmpFilePathWithoutExt + ".zraw").c_str())); - /*It would make sence to check the images as well (see commented cppunit assert), + /*It would make sense to check the images as well (see commented cppunit assert), but currently there seems to be a problem (exception) with most of the test images (partly it seems to be a problem when try to access the pixel content by AccessByItk_1 in mitk::CompareImageDataFilter. This problem should be dealt with in Bug 19533 - mitkITKImageIOTest needs improvement */ // CPPUNIT_ASSERT_MESSAGE("Images are equal.", mitk::Equal(*image, *compareImage, mitk::eps, true)); CPPUNIT_ASSERT_MESSAGE("TimeGeometries are equal.", mitk::Equal(*(image->GetTimeGeometry()), *(compareImage->GetTimeGeometry()), 5e-4, true)); CPPUNIT_ASSERT_EQUAL_MESSAGE("Error, read image has different UID", image->GetUID(), compareImage->GetUID()); // delete remove(tmpFilePath.c_str()); remove((tmpFilePathWithoutExt + ".raw").c_str()); remove((tmpFilePathWithoutExt + ".zraw").c_str()); } catch (...) { CPPUNIT_FAIL("Exception during.mhd file writing"); } } /** * test for "ImageWriter". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ void TestImageWriter(std::string sourcefile) { sourcefile = GetTestDataFilePath(sourcefile); // load image CPPUNIT_ASSERT_MESSAGE("Checking whether source image exists", itksys::SystemTools::FileExists(mitk::Utf8Util::Local8BitToUtf8(sourcefile).c_str())); mitk::Image::Pointer image = nullptr; try { image = mitk::IOUtil::Load(sourcefile); } catch (...) { CPPUNIT_FAIL("Exception during file loading:"); } CPPUNIT_ASSERT_MESSAGE("loaded image not nullptr", image.IsNotNull()); // write ITK .mhd image (2D and 3D only) if (image->GetDimension() <= 3) { TestMHDWriting(image); } // testing more component image writing as nrrd files TestNRRDWriting(image); std::ofstream tmpStream; std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, "XXXXXX"); tmpStream.close(); TestPictureWriting(image, tmpFilePath, ".png"); TestPictureWriting(image, tmpFilePath, ".jpg"); TestPictureWriting(image, tmpFilePath, ".tiff"); TestPictureWriting(image, tmpFilePath, ".bmp"); // always end with this! } /** * Try to write a 3D image with only one plane (a 2D images in disguise for all intents and purposes) */ void TestWrite3DImageWithOnePlane() { typedef itk::Image ImageType; ImageType::Pointer itkImage = ImageType::New(); ImageType::IndexType start; start.Fill(0); ImageType::SizeType size; size[0] = 100; size[1] = 100; size[2] = 1; ImageType::RegionType region; region.SetSize(size); region.SetIndex(start); itkImage->SetRegions(region); itkImage->Allocate(); itkImage->FillBuffer(0); itk::ImageRegionIterator imageIterator(itkImage, itkImage->GetLargestPossibleRegion()); // Make two squares while (!imageIterator.IsAtEnd()) { if ((imageIterator.GetIndex()[0] > 5 && imageIterator.GetIndex()[0] < 20) && (imageIterator.GetIndex()[1] > 5 && imageIterator.GetIndex()[1] < 20)) { imageIterator.Set(255); } if ((imageIterator.GetIndex()[0] > 50 && imageIterator.GetIndex()[0] < 70) && (imageIterator.GetIndex()[1] > 50 && imageIterator.GetIndex()[1] < 70)) { imageIterator.Set(60); } ++imageIterator; } mitk::Image::Pointer image = mitk::ImportItkImage(itkImage); mitk::IOUtil::Save(image, mitk::IOUtil::CreateTemporaryFile("3Dto2DTestImageXXXXXX.nrrd")); mitk::IOUtil::Save(image, mitk::IOUtil::CreateTemporaryFile("3Dto2DTestImageXXXXXX.png")); } /** * Try to write a 3D image with only one plane (a 2D images in disguise for all intents and purposes) */ void TestWrite3DImageWithTwoPlanes() { typedef itk::Image ImageType; ImageType::Pointer itkImage = ImageType::New(); ImageType::IndexType start; start.Fill(0); ImageType::SizeType size; size[0] = 100; size[1] = 100; size[2] = 2; ImageType::RegionType region; region.SetSize(size); region.SetIndex(start); itkImage->SetRegions(region); itkImage->Allocate(); itkImage->FillBuffer(0); itk::ImageRegionIterator imageIterator(itkImage, itkImage->GetLargestPossibleRegion()); // Make two squares while (!imageIterator.IsAtEnd()) { if ((imageIterator.GetIndex()[0] > 5 && imageIterator.GetIndex()[0] < 20) && (imageIterator.GetIndex()[1] > 5 && imageIterator.GetIndex()[1] < 20)) { imageIterator.Set(255); } if ((imageIterator.GetIndex()[0] > 50 && imageIterator.GetIndex()[0] < 70) && (imageIterator.GetIndex()[1] > 50 && imageIterator.GetIndex()[1] < 70)) { imageIterator.Set(60); } ++imageIterator; } mitk::Image::Pointer image = mitk::ImportItkImage(itkImage); mitk::IOUtil::Save(image, mitk::IOUtil::CreateTemporaryFile("3Dto2DTestImageXXXXXX.nrrd")); CPPUNIT_ASSERT_THROW(mitk::IOUtil::Save(image, mitk::IOUtil::CreateTemporaryFile("3Dto2DTestImageXXXXXX.png")), mitk::Exception); } }; MITK_TEST_SUITE_REGISTRATION(mitkItkImageIO) diff --git a/Modules/Core/test/mitkLevelWindowManagerTest.cpp b/Modules/Core/test/mitkLevelWindowManagerTest.cpp index 43cddaee66..588b2056cc 100644 --- a/Modules/Core/test/mitkLevelWindowManagerTest.cpp +++ b/Modules/Core/test/mitkLevelWindowManagerTest.cpp @@ -1,439 +1,439 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include #include #include #include #include #include #include #include class mitkLevelWindowManagerTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkLevelWindowManagerTestSuite); MITK_TEST(TestModes); MITK_TEST(TestSetLevelWindowProperty); MITK_TEST(TestVisibilityPropertyChanged); MITK_TEST(TestLayerPropertyChanged); MITK_TEST(TestImageRenderingModePropertyChanged); MITK_TEST(TestImageForLevelWindowPropertyChanged); MITK_TEST(TestSelectedPropertyChanged); MITK_TEST(TestRemoveDataNodes); MITK_TEST(TestCombinedPropertiesChanged); CPPUNIT_TEST_SUITE_END(); private: mitk::LevelWindowManager::Pointer m_LevelWindowManager; mitk::StandaloneDataStorage::Pointer m_DataManager; std::string m_ImagePath1; std::string m_ImagePath2; std::string m_ImagePath3; mitk::DataNode::Pointer m_DataNode1; mitk::DataNode::Pointer m_DataNode2; mitk::DataNode::Pointer m_DataNode3; mitk::Image::Pointer m_mitkMultiComponentImage; mitk::Image::Pointer m_mitkImageComponent1; mitk::Image::Pointer m_mitkImageComponent2; bool AssertImageForLevelWindowProperty(bool assert1, bool assert2, bool assert3) { bool imageForLevelWindowProperty1, imageForLevelWindowProperty2, imageForLevelWindowProperty3; m_DataNode1->GetBoolProperty("imageForLevelWindow", imageForLevelWindowProperty1); m_DataNode2->GetBoolProperty("imageForLevelWindow", imageForLevelWindowProperty2); m_DataNode3->GetBoolProperty("imageForLevelWindow", imageForLevelWindowProperty3); return (assert1 == imageForLevelWindowProperty1) && (assert2 == imageForLevelWindowProperty2) && (assert3 == imageForLevelWindowProperty3); } bool AssertLevelWindowProperty(bool assert1, bool assert2, bool assert3) { auto levelWindowProperty1 = dynamic_cast(m_DataNode1->GetProperty("levelwindow")); auto levelWindowProperty2 = dynamic_cast(m_DataNode2->GetProperty("levelwindow")); auto levelWindowProperty3 = dynamic_cast(m_DataNode3->GetProperty("levelwindow")); // Check if the active level window property of the manager is equal to any of the level window properties of the nodes auto managerLevelWindowProperty = m_LevelWindowManager->GetLevelWindowProperty(); return (assert1 == (managerLevelWindowProperty == levelWindowProperty1)) && (assert2 == (managerLevelWindowProperty == levelWindowProperty2)) && (assert3 == (managerLevelWindowProperty == levelWindowProperty3)); } public: void setUp() override { m_LevelWindowManager = mitk::LevelWindowManager::New(); m_DataManager = mitk::StandaloneDataStorage::New(); CPPUNIT_ASSERT_NO_THROW_MESSAGE("DataStorage could not be set for the new level window manager", m_LevelWindowManager->SetDataStorage(m_DataManager)); CPPUNIT_ASSERT_MESSAGE("DataStorage could not be retrieved from the new level window manager", m_DataManager == m_LevelWindowManager->GetDataStorage()); m_ImagePath1 = GetTestDataFilePath("Pic3D.nrrd"); m_ImagePath2 = GetTestDataFilePath("UltrasoundImages/4D_TEE_Data_MV.dcm"); m_ImagePath3 = GetTestDataFilePath("RenderingTestData/defaultWatermark.png"); // add multiple objects to the data storage => property observers will be created m_DataNode1 = mitk::IOUtil::Load(m_ImagePath1, *m_DataManager)->GetElement(0); m_DataNode2 = mitk::IOUtil::Load(m_ImagePath2, *m_DataManager)->GetElement(0); CPPUNIT_ASSERT_MESSAGE("Not two relevant nodes found in the data storage", m_LevelWindowManager->GetRelevantNodes()->size() == 2); CPPUNIT_ASSERT_MESSAGE("Not two observers created for the relevant nodes", m_LevelWindowManager->GetNumberOfObservers() == 2); m_DataNode1->SetIntProperty("layer", 1); m_DataNode2->SetIntProperty("layer", 2); bool isImageForLevelWindow1, isImageForLevelWindow2; m_DataNode1->GetBoolProperty("imageForLevelWindow", isImageForLevelWindow1); m_DataNode2->GetBoolProperty("imageForLevelWindow", isImageForLevelWindow2); CPPUNIT_ASSERT_MESSAGE("Initial \"imageForLevelWindow\" property not exclusively set for node 2", !isImageForLevelWindow1 && isImageForLevelWindow2); m_DataNode3 = mitk::IOUtil::Load(m_ImagePath3, *m_DataManager)->GetElement(0); CPPUNIT_ASSERT_MESSAGE("Not three relevant nodes found in the data storage", m_LevelWindowManager->GetRelevantNodes()->size() == 3); CPPUNIT_ASSERT_MESSAGE("Not three observers created for the relevant nodes", m_LevelWindowManager->GetNumberOfObservers() == 3); m_DataNode3->SetIntProperty("layer", 3); AssertImageForLevelWindowProperty(false, false, true); } void tearDown() override {} void TestModes() { CPPUNIT_ASSERT_MESSAGE("AutoTopMost mode is not enabled per default", m_LevelWindowManager->IsAutoTopMost()); CPPUNIT_ASSERT_MESSAGE("SelectedImagesMode mode is not disabled per default", !m_LevelWindowManager->IsSelectedImages()); m_LevelWindowManager->SetSelectedImages(true); CPPUNIT_ASSERT_MESSAGE("AutoTopMost mode was not disabled on mode switch", !m_LevelWindowManager->IsAutoTopMost()); CPPUNIT_ASSERT_MESSAGE("SelectedImagesMode mode was not enabled on mode switch", m_LevelWindowManager->IsSelectedImages()); m_LevelWindowManager->SetSelectedImages(false); CPPUNIT_ASSERT_MESSAGE("AutoTopMost mode was not disabled on mode switch", !m_LevelWindowManager->IsAutoTopMost()); CPPUNIT_ASSERT_MESSAGE("SelectedImagesMode mode was not disabled on mode switch", !m_LevelWindowManager->IsSelectedImages()); m_LevelWindowManager->SetSelectedImages(true); // to enable "SelectedImagesMode" m_LevelWindowManager->SetAutoTopMostImage(true); CPPUNIT_ASSERT_MESSAGE("AutoTopMost mode was not enabled on mode switch", m_LevelWindowManager->IsAutoTopMost()); CPPUNIT_ASSERT_MESSAGE("SelectedImagesMode mode was not disabled on mode switch", !m_LevelWindowManager->IsSelectedImages()); } void TestSetLevelWindowProperty() { m_LevelWindowManager->SetAutoTopMostImage(false); // Setting the level window property of the manager // will make the corresponding node be the "imageForLevelWindow" node. auto levelWindowProperty = dynamic_cast(m_DataNode1->GetProperty("levelwindow")); m_LevelWindowManager->SetLevelWindowProperty(levelWindowProperty); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); levelWindowProperty = dynamic_cast(m_DataNode2->GetProperty("levelwindow")); m_LevelWindowManager->SetLevelWindowProperty(levelWindowProperty); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); levelWindowProperty = dynamic_cast(m_DataNode3->GetProperty("levelwindow")); m_LevelWindowManager->SetLevelWindowProperty(levelWindowProperty); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); levelWindowProperty = mitk::LevelWindowProperty::New(); //CPPUNIT_ASSERT_THROW_MESSAGE("Expected exception for an invalid level window property was not thrown", //m_LevelWindowManager->SetLevelWindowProperty(levelWindowProperty), mitk::Exception); } void TestVisibilityPropertyChanged() { // Hiding a node will make the "next" node be the "imageForLevelWindow" node, if // the hidden node was the "imageForLevelWindow" node before. "Next" is dependent on the node layer. m_DataNode3->SetVisibility(false); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); m_DataNode2->SetVisibility(false); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); m_DataNode1->SetVisibility(false); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("LevelWindowProperty is not null", !m_LevelWindowManager->GetLevelWindowProperty()); m_DataNode3->SetVisibility(true); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); } void TestLayerPropertyChanged() { m_DataNode3->SetIntProperty("layer", itk::NumericTraits::min()); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); m_DataNode2->SetIntProperty("layer", itk::NumericTraits::min()); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); m_DataNode1->SetIntProperty("layer", itk::NumericTraits::min()); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("LevelWindowProperty is not null", !m_LevelWindowManager->GetLevelWindowProperty()); m_DataNode3->SetIntProperty("layer", 1); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); } void TestImageRenderingModePropertyChanged() { // checking the default rendering mode auto renderingMode = dynamic_cast(m_DataNode3->GetProperty("Image Rendering.Mode")); CPPUNIT_ASSERT_MESSAGE("Initial \"Image Rendering.Mode\" property not set to \"RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR\"", mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR == renderingMode->GetRenderingMode()); // Changing the "Image Rendering.Mode" of a node to either "LOOKUPTABLE_COLOR" or // "COLORTRANSFERFUNCTION_COLOR" will ignore this node for the level window m_DataNode3->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New( mitk::RenderingModeProperty::LOOKUPTABLE_COLOR)); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); m_DataNode2->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New( mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_COLOR)); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); m_DataNode1->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New( mitk::RenderingModeProperty::LOOKUPTABLE_COLOR)); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("LevelWindowProperty is not null", !m_LevelWindowManager->GetLevelWindowProperty()); m_DataNode3->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New( mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR)); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); } void TestImageForLevelWindowPropertyChanged() { m_LevelWindowManager->SetAutoTopMostImage(false); m_DataNode1->SetBoolProperty("imageForLevelWindow", true); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); m_DataNode2->SetBoolProperty("imageForLevelWindow", true); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); m_DataNode3->SetBoolProperty("imageForLevelWindow", true); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); // The top level node will alsways be used as a fall back node // if no specific mode is selected. m_DataNode3->SetBoolProperty("imageForLevelWindow", false); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); } void TestSelectedPropertyChanged() { // Selecting a node will make this node be the "imageForLevelWindow" node, if // the "SelectedImagesMode" is enabled (disabled per default). m_DataNode1->SetSelected(true); // selection mode not enabled - node3 stays the "imageForLevelWindow" node CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); // This will immediately check for the selected node (node 1). m_LevelWindowManager->SetSelectedImages(true); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); // Second node will be selected (node 1 and node 2 selected). // It is not specified which data node will be used for the "imageForLevelWindow" / "levelwindow" property, // since the data storage access to the nodes is non-deterministic. // At least check for any valid level window property. m_DataNode2->SetSelected(true); CPPUNIT_ASSERT_MESSAGE("LevelWindowProperty is null", m_LevelWindowManager->GetLevelWindowProperty()); // Third node will be selected (node 1, node 2 and node 3 selected) // It is not specified which data node will be used for the "imageForLevelWindow" / "levelwindow" property, // since the data storage access to the nodes is non-deterministic. // At least check for any valid level window property. m_DataNode3->SetSelected(true); auto usedLevelWindowProperty = m_LevelWindowManager->GetLevelWindowProperty(); CPPUNIT_ASSERT_MESSAGE("LevelWindowProperty is null", usedLevelWindowProperty); // All three nodes are selected: Check if only one node has the "imageForLevelWindow" property set and this node's // "levelwindow" property is used by the level window manager. auto levelWindowProperty1 = dynamic_cast(m_DataNode1->GetProperty("imageForLevelWindow")); if (usedLevelWindowProperty == levelWindowProperty1) { CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); } auto levelWindowProperty2 = dynamic_cast(m_DataNode2->GetProperty("imageForLevelWindow")); if (usedLevelWindowProperty == levelWindowProperty2) { CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); } auto levelWindowProperty3 = dynamic_cast(m_DataNode3->GetProperty("imageForLevelWindow")); if (usedLevelWindowProperty == levelWindowProperty3) { CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); } m_DataNode1->SetSelected(false); m_DataNode2->SetSelected(false); m_DataNode3->SetSelected(false); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("LevelWindowProperty is not null", !m_LevelWindowManager->GetLevelWindowProperty()); } void TestCombinedPropertiesChanged() { m_LevelWindowManager->SetSelectedImages(true); m_DataNode1->SetSelected(true); // selection mode enabled - node1 becomes the "imageForLevelWindow" node CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); m_DataNode2->SetIntProperty("layer", itk::NumericTraits::max()); // selection mode enabled - node1 stays the "imageForLevelWindow" node CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); m_DataNode1->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New( mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_COLOR)); // selection mode enabled - but node1 is ignored - no active level window property CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, false)); m_DataNode3->SetBoolProperty("imageForLevelWindow", true); // selection mode enabled - no valid node selected, no active level window property CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, false)); m_LevelWindowManager->SetSelectedImages(false); // no mode enabled - however, level window is not modified / updated CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, false)); m_LevelWindowManager->Update(itk::ModifiedEvent()); // no mode enabled - level window is modified / updated with topmost visible node2 as fallback CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); m_DataNode3->SetBoolProperty("imageForLevelWindow", true); // no mode enabled - use node3 with "imageForLevelWindow" property set CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); m_DataNode3->SetVisibility(false); // node3 with "imageForLevelWindow" property not visible - use topmost visible node2 as fallback CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); m_DataNode2->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New( mitk::RenderingModeProperty::LOOKUPTABLE_COLOR)); // fallback node2 is ignored - but "imageForLevelWindow" and "levelWindow" stay "true" for node2 CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); m_LevelWindowManager->SetAutoTopMostImage(true); // no visible node exists that is not ignored CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, false)); auto levelWindowProperty = dynamic_cast(m_DataNode3->GetProperty("levelwindow")); - m_LevelWindowManager->SetLevelWindowProperty(levelWindowProperty); // explicitely set the level window to node3 + m_LevelWindowManager->SetLevelWindowProperty(levelWindowProperty); // explicitly set the level window to node3 CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); m_DataNode1->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New( mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR)); // auto topmost mode enabled - node1 is the only visible non-ignored node CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); m_DataNode2->SetProperty("Image Rendering.Mode", mitk::RenderingModeProperty::New( mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR)); // auto topmost mode enabled - node2 is topmost visible node CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, true, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, true, false)); m_DataNode2->SetIntProperty("layer", itk::NumericTraits::min()); // auto topmost mode enabled - node1 is topmost visible node CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(true, false, false)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(true, false, false)); m_DataNode3->SetVisibility(true); // auto topmost mode enabled - node3 is topmost visible node CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", AssertImageForLevelWindowProperty(false, false, true)); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", AssertLevelWindowProperty(false, false, true)); } void TestRemoveDataNodes() { m_DataManager->Remove(m_DataNode3); CPPUNIT_ASSERT_MESSAGE("Node not correctly removed", m_LevelWindowManager->GetRelevantNodes()->size() == 2); CPPUNIT_ASSERT_MESSAGE("Observer not correctly removed", m_LevelWindowManager->GetNumberOfObservers() == 2); bool isImageForLevelWindow1, isImageForLevelWindow2; m_DataNode1->GetBoolProperty("imageForLevelWindow", isImageForLevelWindow1); m_DataNode2->GetBoolProperty("imageForLevelWindow", isImageForLevelWindow2); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", !isImageForLevelWindow1 && isImageForLevelWindow2); auto levelWindowProperty1 = dynamic_cast(m_DataNode1->GetProperty("levelwindow")); auto levelWindowProperty2 = dynamic_cast(m_DataNode2->GetProperty("levelwindow")); auto managerLevelWindowProperty = m_LevelWindowManager->GetLevelWindowProperty(); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", (false == (managerLevelWindowProperty == levelWindowProperty1)) && (true == (managerLevelWindowProperty == levelWindowProperty2))); m_DataManager->Remove(m_DataNode2); CPPUNIT_ASSERT_MESSAGE("Node not correctly removed", m_LevelWindowManager->GetRelevantNodes()->size() == 1); CPPUNIT_ASSERT_MESSAGE("Observer not correctly removed", m_LevelWindowManager->GetNumberOfObservers() == 1); m_DataNode1->GetBoolProperty("imageForLevelWindow", isImageForLevelWindow1); CPPUNIT_ASSERT_MESSAGE("\"imageForLevelWindow\" property not correctly set", isImageForLevelWindow1); levelWindowProperty1 = dynamic_cast(m_DataNode1->GetProperty("levelwindow")); managerLevelWindowProperty = m_LevelWindowManager->GetLevelWindowProperty(); CPPUNIT_ASSERT_MESSAGE("\"levelwindow\" property not correctly set", true == (managerLevelWindowProperty == levelWindowProperty1)); m_DataManager->Remove(m_DataNode1); CPPUNIT_ASSERT_MESSAGE("Node not correctly removed", m_LevelWindowManager->GetRelevantNodes()->size() == 0); CPPUNIT_ASSERT_MESSAGE("Observer not correctly removed", m_LevelWindowManager->GetNumberOfObservers() == 0); CPPUNIT_ASSERT_MESSAGE("LevelWindowProperty is not null", !m_LevelWindowManager->GetLevelWindowProperty()); } }; MITK_TEST_SUITE_REGISTRATION(mitkLevelWindowManager) diff --git a/Modules/Core/test/mitkLevelWindowTest.cpp b/Modules/Core/test/mitkLevelWindowTest.cpp index 0953bb9c49..9e391cdae7 100644 --- a/Modules/Core/test/mitkLevelWindowTest.cpp +++ b/Modules/Core/test/mitkLevelWindowTest.cpp @@ -1,966 +1,966 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkImageWriteAccessor.h" #include "mitkLevelWindow.h" #include /* -* Reseting the Levelwindow to default values: +* Resetting the Levelwindow to default values: * i.e. Range = -1000..1000, Level = 0 and Window = 500 */ void resetLevelWindow(mitk::LevelWindow &lw) { // Default window bounds lw.SetRangeMinMax(-10000, 10000); lw.SetLevelWindow(0, 500, false); if (lw.GetRangeMin() != -10000 || lw.GetRangeMax() != 10000 || lw.GetLevel() != 0 || lw.GetWindow() != 500) { std::cout << "[Failed] To reset Levelwindow" << std::endl; } } int mitkLevelWindowTest(int, char *[]) { std::cout << "Testing mitk::LevelWindow " << std::endl; std::cout << "Testing mitk::LevelWindow constructor with Level and Window "; auto levWin = new mitk::LevelWindow(256, 500); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetDefaultWindow "; mitk::ScalarType defaultWindow = levWin->GetDefaultWindow(); if (!(defaultWindow == 500)) { std::cout << defaultWindow << " [FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetDefaultLevel "; mitk::ScalarType defaultLevel = levWin->GetDefaultLevel(); if (!(defaultLevel == 256)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetWindow "; mitk::ScalarType window = levWin->GetWindow(); if (!(window == 500)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetMin "; if (!(levWin->GetLowerWindowBound() == 6)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetMax "; if (!(levWin->GetUpperWindowBound() == 506)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetLevel "; mitk::ScalarType level = levWin->GetLevel(); if (!(level == 256)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetWindow : GetDefaultWindow "; if (!(defaultWindow == window)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetLevel : GetDefaultLevel "; if (!(defaultLevel == level)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetLevelWindow "; levWin->SetLevelWindow(20, 100); if (!(levWin->GetLevel() == 20)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } if (!(levWin->GetWindow() == 100)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetLevelWindow "; levWin->SetLevelWindow(levWin->GetDefaultLevel(), levWin->GetDefaultWindow()); if (!(levWin->GetLevel() == 256) && !(levWin->GetWindow() == 500)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetDefaultLevelWindow "; levWin->SetDefaultLevelWindow(20, 200); if (!(levWin->GetDefaultLevel() == 20) && !(levWin->GetDefaultWindow() == 200)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow ResetDefaultLevelWindow "; levWin->SetLevelWindow(100, 50); levWin->ResetDefaultLevelWindow(); // double a = levWin->GetLevel(); // double d = levWin->GetWindow(); if (!((levWin->GetLevel() == 20) && (levWin->GetWindow() == 200))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetWindowBounds "; levWin->SetWindowBounds(0, 2); if (!((levWin->GetLowerWindowBound() == 0) && (levWin->GetUpperWindowBound() == 2) && (levWin->GetLevel() == 1) && (levWin->GetWindow() == 2))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with rangemin = rangemax"; levWin->SetRangeMinMax(2000, 2000); if (!(levWin->GetRangeMin() == 1999 && levWin->GetRangeMax() == 2000)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with rangemin > rangemax"; levWin->SetRangeMinMax(2100, 2000); if (!(levWin->GetRangeMin() == 2000 && levWin->GetRangeMax() == 2100)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax "; levWin->SetRangeMinMax(-1000, 2000); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetRangeMin "; if (!(levWin->GetRangeMin() == -1000)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetRangeMax "; if (!(levWin->GetRangeMax() == 2000)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetRange "; if (!((levWin->GetRangeMax() - levWin->GetRangeMin()) == levWin->GetRange())) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetDefaultBoundaries with rangemin = rangemax"; levWin->SetDefaultBoundaries(2000, 2000); if (!(levWin->GetDefaultLowerBound() == 1999 && levWin->GetDefaultUpperBound() == 2000)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetDefaultBoundaries with rangemin > rangemax"; levWin->SetDefaultBoundaries(2100, 2000); if (!(levWin->GetDefaultLowerBound() == 2000 && levWin->GetDefaultUpperBound() == 2100)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetDefaultBoundaries "; levWin->SetDefaultBoundaries(-2000, 8000); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetDefaultLowerBound "; if (!(levWin->GetDefaultLowerBound() == -2000)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow GetDefaultUpperBound "; if (!(levWin->GetDefaultUpperBound() == 8000)) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow ResetDefaultRangeMinMax "; levWin->ResetDefaultRangeMinMax(); if (!((levWin->GetRangeMin() == levWin->GetDefaultLowerBound()) && (levWin->GetRangeMax() == levWin->GetDefaultUpperBound()))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow minRange > maxRange "; levWin->SetRangeMinMax(2000, 1000); if (!((levWin->GetRangeMin() == 1000) && (levWin->GetRangeMax() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetRangeMinMax(2000, -1000); if (!((levWin->GetRangeMin() == -1000) && (levWin->GetRangeMax() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetRangeMinMax(-2000, -3000); if (!((levWin->GetRangeMin() == -3000) && (levWin->GetRangeMax() == -2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetRangeMinMax(0, -1000); if (!((levWin->GetRangeMin() == -1000) && (levWin->GetRangeMax() == 0))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetRangeMinMax(2000, 0); if (!((levWin->GetRangeMin() == 0) && (levWin->GetRangeMax() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetRangeMinMax(-10000, 10000); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow defaultMinRange > defaultMaxRange "; levWin->SetDefaultBoundaries(2000, 1000); if (!((levWin->GetDefaultLowerBound() == 1000) && (levWin->GetDefaultUpperBound() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetDefaultBoundaries(2000, -1000); if (!((levWin->GetDefaultLowerBound() == -1000) && (levWin->GetDefaultUpperBound() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetDefaultBoundaries(-2000, -3000); if (!((levWin->GetDefaultLowerBound() == -3000) && (levWin->GetDefaultUpperBound() == -2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetDefaultBoundaries(0, -1000); if (!((levWin->GetDefaultLowerBound() == -1000) && (levWin->GetDefaultUpperBound() == 0))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetDefaultBoundaries(2000, 0); if (!((levWin->GetDefaultLowerBound() == 0) && (levWin->GetDefaultUpperBound() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetDefaultBoundaries(-10000, 10000); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min > max "; levWin->SetWindowBounds(2000, 1000); if (!((levWin->GetLowerWindowBound() == 1000) && (levWin->GetUpperWindowBound() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetWindowBounds(2000, -1000); if (!((levWin->GetLowerWindowBound() == -1000) && (levWin->GetUpperWindowBound() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetWindowBounds(-2000, -3000); if (!((levWin->GetLowerWindowBound() == -3000) && (levWin->GetUpperWindowBound() == -2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetWindowBounds(0, -1000); if (!((levWin->GetLowerWindowBound() == -1000) && (levWin->GetUpperWindowBound() == 0))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->SetWindowBounds(2000, 0); if (!((levWin->GetLowerWindowBound() == 0) && (levWin->GetUpperWindowBound() == 2000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; // minmax > maxrange, minmax < minrange, minmaxrange, min < minrange & max > minrange // max < minrange & min > minrange, min > maxrange & max < maxrange, min < minrange & max > maxrange // min > maxrange & max < minrange std::cout << "Testing mitk::LevelWindow max > min > maxrange autoexpand = FALSE"; levWin->SetWindowBounds(11000, 12000, false); if (!((levWin->GetLowerWindowBound() == 9999) && (levWin->GetUpperWindowBound() == 10000))) { std::cout << "[FAILED]" << levWin->GetLowerWindowBound() << "," << levWin->GetUpperWindowBound() << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow max > min > maxrange autoexpand = TRUE"; levWin->SetWindowBounds(11000, 12000); if (!((levWin->GetLowerWindowBound() == 11000) && (levWin->GetUpperWindowBound() == 12000))) { std::cout << "[FAILED]" << levWin->GetLowerWindowBound() << "," << levWin->GetUpperWindowBound() << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; // Reset default window resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min > max > maxrange autoexpand = FALSE"; levWin->SetWindowBounds(12000, 11000, false); if (!((levWin->GetLowerWindowBound() == 9999) && (levWin->GetUpperWindowBound() == 10000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min > max > maxrange autoexpand = TRUE"; levWin->SetWindowBounds(12000, 11000); if (!((levWin->GetLowerWindowBound() == 11000) && (levWin->GetUpperWindowBound() == 12000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min < max < minrange autoexpand = FALSE"; levWin->SetWindowBounds(-12000, -11000, false); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == -9999))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min < max < minrange autoexpand = TRUE"; levWin->SetWindowBounds(-12000, -11000); if (!((levWin->GetLowerWindowBound() == -12000) && (levWin->GetUpperWindowBound() == -11000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow max < min < minrange autoexpand = FALSE"; levWin->SetWindowBounds(-11000, -12000, false); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == -9999))) { std::cout << "[FAILED]: Expected (-10000, -9999): " << levWin->GetLowerWindowBound() << " - " << levWin->GetUpperWindowBound() << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow max < min < minrange autoexpand = TRUE"; levWin->SetWindowBounds(-11000, -12000); if (!((levWin->GetLowerWindowBound() == -12000) && (levWin->GetUpperWindowBound() == -11000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min < maxrang & max > maxrange autoexpand = FALSE"; levWin->SetWindowBounds(9999, 12000, false); if (!((levWin->GetLowerWindowBound() == 9999) && (levWin->GetUpperWindowBound() == 10000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min < maxrang & max > maxrange autoexpand = TRUE"; levWin->SetWindowBounds(9999, 12000); if (!((levWin->GetLowerWindowBound() == 9999) && (levWin->GetUpperWindowBound() == 12000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min < minrange & max > minrange autoexpand = FALSE"; levWin->SetWindowBounds(-11000, -9999, false); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == -9999))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min < minrange & max > minrange autoexpand = TRUE"; levWin->SetWindowBounds(-11000, -9999); if (!((levWin->GetLowerWindowBound() == -11000) && (levWin->GetUpperWindowBound() == -9999))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min < minrange & max > maxrange autoexpand = FALSE"; levWin->SetWindowBounds(-11000, 11000, false); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == 10000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min < minrange & max > maxrange autoexpand = TRUE"; levWin->SetWindowBounds(-11000, 11000); if (!((levWin->GetLowerWindowBound() == -11000) && (levWin->GetUpperWindowBound() == 11000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow maxrange > min = max > minrange autoexpand = FALSE"; levWin->SetWindowBounds(5000, 5000, false); if (!((levWin->GetLowerWindowBound() == 4999.5) && (levWin->GetUpperWindowBound() == 5000.5))) { std::cout << "[FAILED]: Expected (4999.5, 5000.5): " << levWin->GetLowerWindowBound() << " - " << levWin->GetUpperWindowBound() << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow maxrange > min = max > minrange autoexpand = TRUE"; levWin->SetWindowBounds(5000, 5000); if (!((levWin->GetLowerWindowBound() == 4999.5) && (levWin->GetUpperWindowBound() == 5000.5))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min = max = minrange autoexpand = FALSE"; levWin->SetWindowBounds(-10000, -10000, false); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == -9999))) { std::cout << "[FAILED]: Expected (-10000, -9999): " << levWin->GetLowerWindowBound() << " - " << levWin->GetUpperWindowBound() << " . " << levWin->GetRangeMin() << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min = max = minrange autoexpand = TRUE"; levWin->SetWindowBounds(-10000, -10000); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == -9999))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min = max = maxrange autoexpand = FALSE"; levWin->SetWindowBounds(10000, 10000, false); if (!((levWin->GetLowerWindowBound() == 9999) && (levWin->GetUpperWindowBound() == 10000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min = max = maxrange autoexpand = TRUE"; levWin->SetWindowBounds(10000, 10000); if (!((levWin->GetLowerWindowBound() == 9999) && (levWin->GetUpperWindowBound() == 10000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min = max > maxrange autoexpand = FALSE"; levWin->SetWindowBounds(11000, 11000, false); if (!((levWin->GetLowerWindowBound() == 9999) && (levWin->GetUpperWindowBound() == 10000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min = max > maxrange autoexpand = TRUE"; levWin->SetWindowBounds(11000, 11000); if (!((levWin->GetLowerWindowBound() == 10999) && (levWin->GetUpperWindowBound() == 11000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min = max < minrange autoexpand = FALSE"; levWin->SetWindowBounds(-11000, -11000, false); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == -9999))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min = max < minrange autoexpand = TRUE"; levWin->SetWindowBounds(-11000, -11000); if (!((levWin->GetLowerWindowBound() == -11000) && (levWin->GetUpperWindowBound() == -10999))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow maxrange > min > minrange > max autoexpand = FALSE"; levWin->SetWindowBounds(-9000, -11000, false); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == -9000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow maxrange > min > minrange > max autoexpand = TRUE"; levWin->SetWindowBounds(-9000, -11000, true); if (!((levWin->GetLowerWindowBound() == -11000) && (levWin->GetUpperWindowBound() == -9000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow min > maxrange > minrange > max autoexpand = FALSE"; levWin->SetWindowBounds(11000, -11000, false); if (!((levWin->GetLowerWindowBound() == -10000) && (levWin->GetUpperWindowBound() == 10000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow min > maxrange > minrange > max autoexpand = TRUE"; levWin->SetWindowBounds(11000, -11000); if (!((levWin->GetLowerWindowBound() == -11000) && (levWin->GetUpperWindowBound() == 11000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow SetRangeMinMax with maxrange < min < max autoexpand = FALSE"; levWin->SetRangeMinMax(-20000, -15000); if (!((levWin->GetLowerWindowBound() == -15001) && (levWin->GetUpperWindowBound() == -15000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with minrange > maxrange & maxrange < min < max "; levWin->ResetDefaultLevelWindow(); levWin->SetRangeMinMax(-15000, -20000); if (!((levWin->GetLowerWindowBound() == -15001) && (levWin->GetUpperWindowBound() == -15000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with minrange < min < maxrange < max autoexpand = FALSE"; levWin->SetRangeMinMax(-80, 1000); levWin->SetWindowBounds(-1000, 110, false); if (!((levWin->GetLowerWindowBound() == -80) && (levWin->GetUpperWindowBound() == 110))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with minrange < min < maxrange < max autoexpand = TRUE"; levWin->SetRangeMinMax(-80, 1000); levWin->SetWindowBounds(-1000, 110); if (!((levWin->GetLowerWindowBound() == -1000) && (levWin->GetUpperWindowBound() == 110))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow SetRangeMinMax with maxrange < minrange & minrange < min < maxrange < max " "autoexpand = FALSE"; levWin->SetRangeMinMax(1000, -80); levWin->SetWindowBounds(-1000, 110, false); if (!((levWin->GetLowerWindowBound() == -80) && (levWin->GetUpperWindowBound() == 110))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with maxrange < minrange & minrange < min < maxrange < max " "autoexpand = TRUE"; levWin->SetRangeMinMax(1000, -80); levWin->SetWindowBounds(-1000, 110); if (!((levWin->GetLowerWindowBound() == -1000) && (levWin->GetUpperWindowBound() == 110))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; resetLevelWindow(*levWin); std::cout << "Testing mitk::LevelWindow SetRangeMinMax with min < minrange < maxrange SetRangeMinMax(20, 110); if (!((levWin->GetLowerWindowBound() == 20) && (levWin->GetUpperWindowBound() == 110))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with minRange > maxRange & min < maxrange < max "; levWin->SetWindowBounds(-90, 1000); levWin->SetRangeMinMax(100, -80); if (!((levWin->GetLowerWindowBound() == -80) && (levWin->GetUpperWindowBound() == 100))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with minRange > maxRange & min < minrange < maxrange SetRangeMinMax(20, 100); if (!((levWin->GetLowerWindowBound() == 20) && (levWin->GetUpperWindowBound() == 100))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with min < max < minrange "; levWin->SetRangeMinMax(20000, 15000); if (!((levWin->GetLowerWindowBound() == 15000) && (levWin->GetUpperWindowBound() == 15001))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with minrange > maxrange & min < max < minrange "; levWin->SetRangeMinMax(20000, 15000); if (!((levWin->GetLowerWindowBound() == 15000) && (levWin->GetUpperWindowBound() == 15001))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetRangeMinMax with min < minrange SetRangeMinMax(-20000, -15000); if (!((levWin->GetLowerWindowBound() == -15001) && (levWin->GetUpperWindowBound() == -15000))) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } levWin->ResetDefaultRangeMinMax(); levWin->ResetDefaultLevelWindow(); std::cout << "[PASSED]" << std::endl; // auch für default levelwindow und default range // Create Image out of nowhere mitk::Image::Pointer image; // mitk::PixelType pt(typeid(int)); unsigned int dim[] = {100, 100, 20}; std::cout << "Creating image: "; image = mitk::Image::New(); // image->DebugOn(); image->Initialize(mitk::MakePixelType(), 3, dim); mitk::ImageWriteAccessor imAccess(image); auto *p = (int *)imAccess.GetData(); int size = dim[0] * dim[1] * dim[2]; int i; for (i = 0; i < size; ++i, ++p) *p = i; std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow SetAuto "; mitk::LevelWindow levelwindow; levelwindow.SetAuto(image); std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow constructor with mitkLevelWindow "; const mitk::LevelWindow *lw = new mitk::LevelWindow(levelwindow); if (!(lw->GetRange() == levelwindow.GetRange())) { std::cout << "[FAILED]" << std::endl; delete lw; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing mitk::LevelWindow destructor "; delete levWin; delete lw; std::cout << "[PASSED]" << std::endl; mitk::LevelWindow levelWindow(50, 100); levelWindow.SetRangeMinMax(0, 100); // test range restriction/adaption for SetLevelWindow and SetWindowBounds std::cout << "Testing range restriction of mitk::LevelWindow::SetWindowBounds() autoexpand = FALSE"; mitk::ScalarType initialUpperBound = levelWindow.GetUpperWindowBound(); mitk::ScalarType initialLowerBound = levelWindow.GetLowerWindowBound(); levelWindow.SetWindowBounds(-10, 110, false); if (levelWindow.GetUpperWindowBound() != initialUpperBound || levelWindow.GetLowerWindowBound() != initialLowerBound) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing range restriction of mitk::LevelWindow::SetWindowBounds() autoexpand = TRUE"; levelWindow.SetWindowBounds(-10, 110); if (levelWindow.GetUpperWindowBound() != 110 || levelWindow.GetLowerWindowBound() != -10) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; levelWindow.SetRangeMinMax(0, 100); levelWindow.SetLevelWindow(50, 100); std::cout << "Testing range restriction of mitk::LevelWindow::SetLevelWindow() autoexpand = FALSE"; levelWindow.SetLevelWindow(60, 100, false); if (levelWindow.GetUpperWindowBound() != initialUpperBound) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing range restriction of mitk::LevelWindow::SetLevelWindow() autoexpand = TRUE"; levelWindow.SetLevelWindow(60, 100); if (levelWindow.GetUpperWindowBound() != initialUpperBound + 10) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; levelWindow.SetRangeMinMax(0, 100); levelWindow.SetLevelWindow(50, 100); std::cout << "Testing range restriction of mitk::LevelWindow::SetLevelWindow() autoexpand = FALSE"; levelWindow.SetLevelWindow(40, 100, false); if (levelWindow.GetLowerWindowBound() != initialLowerBound) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing range restriction of mitk::LevelWindow::SetLevelWindow() autoexpand = TRUE"; levelWindow.SetLevelWindow(40, 100); if (levelWindow.GetLowerWindowBound() != initialLowerBound - 10) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing range adaption of mitk::LevelWindow::SetWindowBounds()"; - levelWindow.SetWindowBounds(-10, 90, true); // ture == force + levelWindow.SetWindowBounds(-10, 90, true); // true == force if (levelWindow.GetUpperWindowBound() != 90.0 || levelWindow.GetLowerWindowBound() != -10.0) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing range adaption of mitk::LevelWindow::SetWindowBounds()"; - levelWindow.SetWindowBounds(-20, 110, true); // ture == force + levelWindow.SetWindowBounds(-20, 110, true); // true == force if (levelWindow.GetUpperWindowBound() != 110.0 || levelWindow.GetLowerWindowBound() != -20.0) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing range adaption of mitk::LevelWindow::SetLevelWindow()"; - levelWindow.SetLevelWindow(50, 140, true); // ture == force + levelWindow.SetLevelWindow(50, 140, true); // true == force if (levelWindow.GetUpperWindowBound() != 120.0 || levelWindow.GetLowerWindowBound() != -20.0) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Testing c'tor with x-ray values (formerly did not expand range enough)"; mitk::LevelWindow crLevelWindow(16352, 16444); if (crLevelWindow.GetLevel() != 16352.0 || crLevelWindow.GetWindow() != 16444.0) { std::cout << "[FAILED]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "[PASSED]" << std::endl; std::cout << "[TEST DONE]" << std::endl; return EXIT_SUCCESS; } diff --git a/Modules/Core/test/mitkLogTest.cpp b/Modules/Core/test/mitkLogTest.cpp index 716d93c6cf..03ec18cf4e 100644 --- a/Modules/Core/test/mitkLogTest.cpp +++ b/Modules/Core/test/mitkLogTest.cpp @@ -1,300 +1,300 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkCommon.h" #include "mitkTestingMacros.h" #include #include #include #include #include #include /** Documentation * * @brief this class provides an accessible BackendCout to determine whether this backend was * used to process a message or not. * It is needed for the disable / enable backend test. */ class TestBackendCout : public mbilog::BackendCout { public: TestBackendCout() { m_Called = false; mbilog::BackendCout(); } void ProcessMessage(const mbilog::LogMessage &l) override { m_Called = true; mbilog::BackendCout::ProcessMessage(l); } bool WasCalled() { return m_Called; } private: bool m_Called; }; /** Documentation * * @brief Objects of this class can start an internal thread by calling the Start() method. * The thread is then logging messages until the method Stop() is called. The class * can be used to test if logging is thread-save by using multiple objects and let * them log simuntanously. */ class mitkTestLoggingThread : public itk::Object { public: mitkClassMacroItkParent(mitkTestLoggingThread, itk::Object); itkFactorylessNewMacro(Self); int NumberOfMessages; protected: mitkTestLoggingThread() : NumberOfMessages(0), LoggingRunning(true) { } ~mitkTestLoggingThread() { this->Stop(); } bool LoggingRunning; std::thread Thread; void LogMessages() { auto ThreadID = Thread.get_id(); while (LoggingRunning) { MITK_INFO << "Test info stream in thread" << ThreadID << "\n even with newlines"; MITK_WARN << "Test warning stream in thread " << ThreadID << ". " << "Even with a very long text, even without meaning or implied meaning or content, just a long " "sentence to see whether something has problems with long sentences or output in files or into " "windows or commandlines or whatever."; MITK_DEBUG << "Test debugging stream in thread " << ThreadID; MITK_ERROR << "Test error stream in thread " << ThreadID; MITK_FATAL << "Test fatal stream in thread " << ThreadID; NumberOfMessages += 5; } } static void ThreadStartTracking(void *instance) { auto* thisthread = reinterpret_cast(instance); if (thisthread != nullptr) thisthread->LogMessages(); } public: std::thread::id Start() { LoggingRunning = true; Thread = std::thread(this->ThreadStartTracking, this); return Thread.get_id(); } void Stop() { LoggingRunning = false; if(Thread.joinable()) Thread.join(); } }; /** Documentation * - * @brief This class holds static test methods to sturcture the test of the mitk logging mechanism. + * @brief This class holds static test methods to structure the test of the mitk logging mechanism. */ class mitkLogTestClass { public: static void TestSimpleLog() { bool testSucceded = true; try { MITK_INFO << "Test info stream."; MITK_WARN << "Test warning stream."; MITK_DEBUG << "Test debugging stream."; // only activated if cmake variable is on! // so no worries if you see no output for this line MITK_ERROR << "Test error stream."; MITK_FATAL << "Test fatal stream."; } catch (const mitk::Exception &) { testSucceded = false; } MITK_TEST_CONDITION_REQUIRED(testSucceded, "Test logging streams."); } static void TestObjectInfoLogging() { bool testSucceded = true; try { int i = 123; float f = .32234; double d = 123123; std::string testString = "testString"; std::stringstream testStringStream; testStringStream << "test" << "String" << "Stream"; mitk::Point3D testMitkPoint; testMitkPoint.Fill(2); MITK_INFO << i; MITK_INFO << f; MITK_INFO << d; MITK_INFO << testString; MITK_INFO << testStringStream.str(); MITK_INFO << testMitkPoint; } catch (const mitk::Exception &) { testSucceded = false; } MITK_TEST_CONDITION_REQUIRED(testSucceded, "Test logging of object information."); } static void TestThreadSaveLog(bool toFile) { bool testSucceded = true; try { if (toFile) { std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/testthreadlog.log"; itksys::SystemTools::RemoveFile(mitk::Utf8Util::Local8BitToUtf8(filename).c_str()); // remove old file, we do not want to append to large files mitk::LoggingBackend::SetLogFile(filename.c_str()); } unsigned int numberOfThreads = 20; unsigned int threadRuntimeInMilliseconds = 2000; std::vector threadIDs; std::vector threads; for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { // initialize threads... threads.push_back(mitkTestLoggingThread::New()); std::cout << "Created " << threadIdx << ". thread." << std::endl; } for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { // start them std::cout << "Start " << threadIdx << ". thread." << std::endl; threadIDs.push_back(threads[threadIdx]->Start()); std::cout << threadIdx << ". thread has ID " << threadIDs[threadIdx] << std::endl; } // wait for some time (milliseconds) itksys::SystemTools::Delay(threadRuntimeInMilliseconds); for (unsigned int threadIdx = 0; threadIdx < numberOfThreads; ++threadIdx) { // stop them and wait for them to end std::cout << "Stop " << threadIdx << ". thread." << std::endl; threads[threadIdx]->Stop(); std::cout << "Terminated " << threadIdx << ". thread (" << threads[threadIdx]->NumberOfMessages << " messages)." << std::endl; } } catch (std::exception &e) { MITK_ERROR << "exception during 'TestThreadSaveLog': " << e.what(); testSucceded = false; } catch (...) { MITK_ERROR << "unknown exception during 'TestThreadSaveLog'"; testSucceded = false; } - // if no error occured until now, everything is ok + // if no error occurred until now, everything is ok MITK_TEST_CONDITION_REQUIRED(testSucceded, "Test logging in different threads."); } static void TestLoggingToFile() { std::string filename = mitk::StandardFileLocations::GetInstance()->GetOptionDirectory() + "/testlog.log"; mitk::LoggingBackend::SetLogFile(filename.c_str()); MITK_INFO << "Test logging to default filename: " << mitk::LoggingBackend::GetLogFile(); MITK_TEST_CONDITION_REQUIRED(itksys::SystemTools::FileExists(mitk::Utf8Util::Local8BitToUtf8(filename).c_str()), "Testing if log file exists."); // TODO delete log file? } static void TestAddAndRemoveBackends() { mbilog::BackendCout myBackend = mbilog::BackendCout(); mbilog::RegisterBackend(&myBackend); MITK_INFO << "Test logging"; mbilog::UnregisterBackend(&myBackend); - // if no error occured until now, everything is ok + // if no error occurred until now, everything is ok MITK_TEST_CONDITION_REQUIRED(true, "Test add/remove logging backend."); } static void TestDefaultBackend() { // not possible now, because we cannot unregister the mitk logging backend in the moment. If such a method is added // to mbilog utility one may add this test. } static void TestEnableDisableBackends() { TestBackendCout myCoutBackend = TestBackendCout(); mbilog::RegisterBackend(&myCoutBackend); mbilog::DisableBackends(mbilog::Console); MITK_INFO << "There should be no output!"; bool success = !myCoutBackend.WasCalled(); mbilog::EnableBackends(mbilog::Console); MITK_INFO << "Now there should be an output."; success &= myCoutBackend.WasCalled(); mbilog::UnregisterBackend(&myCoutBackend); MITK_TEST_CONDITION_REQUIRED(success, "Test disable / enable logging backends.") } }; int mitkLogTest(int /* argc */, char * /*argv*/ []) { // always start with this! MITK_TEST_BEGIN("Log") - MITK_TEST_OUTPUT(<< "TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURED!") + MITK_TEST_OUTPUT(<< "TESTING ALL LOGGING OUTPUTS, ERROR MESSAGES ARE ALSO TESTED AND NOT MEANING AN ERROR OCCURRED!") mitkLogTestClass::TestSimpleLog(); mitkLogTestClass::TestObjectInfoLogging(); mitkLogTestClass::TestLoggingToFile(); mitkLogTestClass::TestAddAndRemoveBackends(); mitkLogTestClass::TestThreadSaveLog(false); // false = to console mitkLogTestClass::TestThreadSaveLog(true); // true = to file mitkLogTestClass::TestEnableDisableBackends(); // TODO actually test file somehow? // always end with this! MITK_TEST_END() } diff --git a/Modules/Core/test/mitkMaterialTest.cpp b/Modules/Core/test/mitkMaterialTest.cpp index 0669196246..9c21d77dc0 100644 --- a/Modules/Core/test/mitkMaterialTest.cpp +++ b/Modules/Core/test/mitkMaterialTest.cpp @@ -1,358 +1,358 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkBaseProperty.h" #include "mitkBaseRenderer.h" #include "mitkDataNode.h" #include "mitkMaterial.h" #include "mitkTestingMacros.h" #include #include #include /** * Simple example for a test for the () class "ClassName". * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (). */ class MaterialTest { public: mitk::Material::Pointer myMP; MaterialTest() { myMP = nullptr; } void testConstructor() { myMP = mitk::Material::New(); MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(), "Testing instantiation") } void testConstructorWithColorOpacity() { mitk::Color color; color.Set(0, 0, 0); double opacity = 1.0f; myMP = mitk::Material::New(color, opacity); MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(), "Testing instantiation") MITK_TEST_CONDITION(color == myMP->GetColor(), "Testing if a Color object was set correctly") MITK_TEST_CONDITION(opacity == myMP->GetOpacity(), "Testing if a Opacity object was set correctly") } void testConstructorWithRedGreenBlueOpacity() { mitk::Material::Color color; color.Set(0, 0, 0); double opacity = 1.0f; double rgb = 0; myMP = mitk::Material::New(rgb, rgb, rgb, opacity); MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(), "Testing instantiation") MITK_TEST_CONDITION(color == myMP->GetColor(), "Testing if a Color object was set correctly") MITK_TEST_CONDITION(opacity == myMP->GetOpacity(), "Testing if a Opacity object was set correctly") } void testConstructorRedGreenBlueColorCoefficientSpecularCoefficientSpecularPowerOpacity() { mitk::Material::Color color; color.Set(0, 0, 0); double opacity = 1.0f; double rgb = 0; double colorCoefficient = 0; double specularCoefficient = 0; double specularPower = 0; myMP = mitk::Material::New(rgb, rgb, rgb, colorCoefficient, specularCoefficient, specularPower, opacity); MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(), "Testing instantiation") MITK_TEST_CONDITION(color == myMP->GetColor(), "Testing if a Color object was set correctly") MITK_TEST_CONDITION(opacity == myMP->GetOpacity(), "Testing if a Opacity object was set correctly") MITK_TEST_CONDITION(specularCoefficient == myMP->GetSpecularCoefficient(), "Testing if a Coefficient object was set correctly") MITK_TEST_CONDITION(specularPower == myMP->GetSpecularPower(), "Testing if a SpecularPower object was set correctly") MITK_TEST_CONDITION(colorCoefficient == myMP->GetColorCoefficient(), "Testing if a colorCoefficient object was set correctly") } void testConstructorColorColorCoefficientSpecularCoefficientSpecularPowerOpacity() { mitk::Material::Color color; color.Set(0, 0, 0); double opacity = 1.0f; double rgb = 0; double colorCoefficient = 0; double specularCoefficient = 0; double specularPower = 0; myMP = mitk::Material::New(rgb, rgb, rgb, colorCoefficient, specularCoefficient, specularPower, opacity); MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(), "Testing instantiation") MITK_TEST_CONDITION(color == myMP->GetColor(), "Testing if a Color object was set correctly") MITK_TEST_CONDITION(opacity == myMP->GetOpacity(), "Testing if a Opacity object was set correctly") MITK_TEST_CONDITION(specularCoefficient == myMP->GetSpecularCoefficient(), "Testing if a Coefficient object was set correctly") MITK_TEST_CONDITION(specularPower == myMP->GetSpecularPower(), "Testing if a SpecularPower object was set correctly") } void testConstructorPropertyRedGreenBlueOpacityAndName() { mitk::Material::Pointer reference = myMP; double opacity = 1.0f; double rgb = 0; std::string name = "Hans Wurst"; myMP = mitk::Material::New(*reference, rgb, rgb, rgb, opacity, name); MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(), "Testing instantiation") MITK_TEST_CONDITION(opacity == myMP->GetOpacity(), "Testing if a Opacity object was set correctly") // MITK_TEST_CONDITION( name.compare(myMP->GetName(),0,9), "Testing if a Name object was set correctly" ) } void testSetColor() { mitk::Material::Color color; color.Set(0, 0, 0); myMP = mitk::Material::New(); myMP->SetColor(color); MITK_TEST_CONDITION_REQUIRED(myMP.IsNotNull(), "Testing instantiation") MITK_TEST_CONDITION(color == myMP->GetColor(), "Testing if a color was set correctly") color.Set(0, 0, 0); myMP->SetColor(color); MITK_TEST_CONDITION(color == myMP->GetColor(), "Testing if a color was set correctly") } void testSetColorCoefficient() { double colorCoefficient = 0; myMP = mitk::Material::New(); myMP->SetColorCoefficient(colorCoefficient); MITK_TEST_CONDITION(colorCoefficient == myMP->GetColorCoefficient(), "Testing if a colorcoefficent was set correctly") } void testSetSpecularColor() { mitk::Material::Color color; color.Set(0, 0, 0); myMP = mitk::Material::New(); myMP->SetSpecularColor(color); MITK_TEST_CONDITION(color == myMP->GetSpecularColor(), "Testing if a SpecularColor was set correctly") } void testSetSpecularCoefficient() { myMP = mitk::Material::New(); double specularCoefficient = 1; myMP->SetSpecularCoefficient(specularCoefficient); MITK_TEST_CONDITION(specularCoefficient == myMP->GetSpecularCoefficient(), "Testing if a SpecularCoefficient was set correctly") } void testSetSpecularPower() { myMP = mitk::Material::New(); double specularPower = 1; myMP->SetSpecularPower(specularPower); MITK_TEST_CONDITION(specularPower == myMP->GetSpecularPower(), "Testing if a SpecularPower was set correctly") } void testSetOpacity() { myMP = mitk::Material::New(); double opacity = 1; myMP->SetOpacity(opacity); MITK_TEST_CONDITION(opacity == myMP->GetOpacity(), "Testing if a Opacity was set correctly") } void testSetInterpolation() { myMP = mitk::Material::New(); mitk::Material::InterpolationType interpolation = mitk::Material::Flat; myMP->SetInterpolation(interpolation); MITK_TEST_CONDITION(interpolation == myMP->GetInterpolation(), "Testing if a Interpolation was set correctly") } void testSetRepresentation() { myMP = mitk::Material::New(); mitk::Material::RepresentationType representation = mitk::Material::Wireframe; myMP->SetRepresentation(representation); MITK_TEST_CONDITION(representation == myMP->GetRepresentation(), "Testing if a Representation was set correctly") } void testSetLineWidth() { myMP = mitk::Material::New(); double lineWidth = 1; myMP->SetLineWidth(lineWidth); MITK_TEST_CONDITION(lineWidth == myMP->GetLineWidth(), "Testing if a LineWidth was set correctly") } void testInitialize() { mitk::Material::Color color; color.Set(0, 0, 0); double opacity = 1.0f; double rgb = 0; double colorCoefficient = 0; double specularCoefficient = 0; double specularPower = 0; myMP = mitk::Material::New(rgb, rgb, rgb, colorCoefficient, specularCoefficient, specularPower, opacity); double lineWidth = 1; myMP->SetLineWidth(lineWidth); mitk::Material::RepresentationType representation = mitk::Material::Wireframe; myMP->SetRepresentation(representation); mitk::Material::InterpolationType interpolation = mitk::Material::Flat; myMP->SetInterpolation(interpolation); myMP->SetSpecularColor(color); std::string name = "Hans Wurst"; myMP->SetName(name); mitk::Material::Pointer myMP2 = mitk::Material::New(); myMP2->Initialize(*myMP); - MITK_TEST_CONDITION(*myMP == *myMP2, "testing equality after .Intitialize") + MITK_TEST_CONDITION(*myMP == *myMP2, "testing equality after .Initialize") } void testOperatorequality() { { mitk::Material::Color color; color.Set(0, 0, 0); double opacity = 1.0f; double rgb = 0; double colorCoefficient = 0; double specularCoefficient = 0; double specularPower = 0; myMP = mitk::Material::New(rgb, rgb, rgb, colorCoefficient, specularCoefficient, specularPower, opacity); double lineWidth = 1; myMP->SetLineWidth(lineWidth); mitk::Material::RepresentationType representation = mitk::Material::Wireframe; myMP->SetRepresentation(representation); mitk::Material::InterpolationType interpolation = mitk::Material::Flat; myMP->SetInterpolation(interpolation); myMP->SetSpecularColor(color); std::string name = "Hans Wurst"; myMP->SetName(name); mitk::Material::Color color2; color2.Set(0, 0, 0); double opacity2 = 1.0f; double rgb2 = 0; double colorCoefficient2 = 0; double specularCoefficient2 = 0; double specularPower2 = 0; mitk::Material::Pointer myMP2 = mitk::Material::New(rgb2, rgb2, rgb2, colorCoefficient2, specularCoefficient2, specularPower2, opacity2); double lineWidth2 = 1; myMP2->SetLineWidth(lineWidth2); mitk::Material::RepresentationType representation2 = mitk::Material::Wireframe; myMP2->SetRepresentation(representation2); mitk::Material::InterpolationType interpolation2 = mitk::Material::Flat; myMP2->SetInterpolation(interpolation2); myMP2->SetSpecularColor(color2); std::string name2 = "Hans Wurst"; myMP2->SetName(name2); MITK_TEST_CONDITION(*myMP == *myMP2, "testing equality Operator") } { mitk::Material::Color color; color.Set(0, 0, 0); double opacity = 1.0f; double rgb = 0; double colorCoefficient = 0; double specularCoefficient = 0; double specularPower = 0; myMP = mitk::Material::New(rgb, rgb, rgb, colorCoefficient, specularCoefficient, specularPower, opacity); double lineWidth = 1; myMP->SetLineWidth(lineWidth); mitk::Material::RepresentationType representation = mitk::Material::Wireframe; myMP->SetRepresentation(representation); mitk::Material::InterpolationType interpolation = mitk::Material::Flat; myMP->SetInterpolation(interpolation); myMP->SetSpecularColor(color); std::string name = "Hans Wurst"; myMP->SetName(name); mitk::Material::Color color2; color2.Set(0, 0, 0); double opacity2 = 1.0f; double rgb2 = 1; double colorCoefficient2 = 0; double specularCoefficient2 = 0; double specularPower2 = 0; mitk::Material::Pointer myMP2 = mitk::Material::New(rgb2, rgb2, rgb2, colorCoefficient2, specularCoefficient2, specularPower2, opacity2); double lineWidth2 = 1; myMP2->SetLineWidth(lineWidth2); mitk::Material::RepresentationType representation2 = mitk::Material::Wireframe; myMP2->SetRepresentation(representation2); mitk::Material::InterpolationType interpolation2 = mitk::Material::Flat; myMP2->SetInterpolation(interpolation2); myMP2->SetSpecularColor(color2); std::string name2 = "Hans Wurst"; myMP2->SetName(name2); MITK_TEST_CONDITION(!(*myMP == *myMP2), "testing equality Operator") } } void testAssignable() { mitk::Material::Pointer materialProp = mitk::Material::New(); MITK_TEST_CONDITION(myMP->Assignable(*materialProp), "testing Assignable with Material") } void testOperatorAssign() { mitk::Material::Pointer myMP2 = mitk::Material::New(); *myMP2 = *myMP; MITK_TEST_CONDITION(*myMP == *myMP2, "Testing Assignment Operator") } }; int mitkMaterialTest(int /* argc */, char * /*argv*/ []) { // always start with this! MITK_TEST_BEGIN("Material") MaterialTest materialTest; materialTest.testConstructor(); materialTest.testConstructorWithColorOpacity(); materialTest.testConstructorWithRedGreenBlueOpacity(); materialTest.testConstructorRedGreenBlueColorCoefficientSpecularCoefficientSpecularPowerOpacity(); materialTest.testConstructorColorColorCoefficientSpecularCoefficientSpecularPowerOpacity(); materialTest.testConstructorPropertyRedGreenBlueOpacityAndName(); materialTest.testAssignable(); materialTest.testOperatorAssign(); materialTest.testSetColor(); materialTest.testSetColorCoefficient(); materialTest.testSetSpecularColor(); materialTest.testSetSpecularCoefficient(); materialTest.testSetSpecularPower(); materialTest.testSetOpacity(); materialTest.testSetInterpolation(); materialTest.testSetRepresentation(); materialTest.testSetLineWidth(); materialTest.testInitialize(); materialTest.testOperatorequality(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. // write your own tests here and use the macros from mitkTestingMacros.h !!! // do not write to std::cout and do not return from this function yourself! // always end with this! MITK_TEST_END() } diff --git a/Modules/Core/test/mitkMessageTest.cpp b/Modules/Core/test/mitkMessageTest.cpp index 891aba839d..1929f4e583 100644 --- a/Modules/Core/test/mitkMessageTest.cpp +++ b/Modules/Core/test/mitkMessageTest.cpp @@ -1,300 +1,300 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkMessage.h" #include "mitkTestingMacros.h" #include namespace mitk { class mitkMessageTestTestClass { public: // dummy class to send around class Package { public: Package(int content = 43) : m_Content(content) {} void Clear() { m_Content = 0; } bool operator==(const Package &other) { return m_Content == other.m_Content; } private: int m_Content; }; class MessageSenderClass { public: // message without any parameters, pure notification Message<> WaveHand; // message without any parameters, pure notification Message<> ShowFinger; // message with one parameter of type std::string Message1 Say; // message with one parameter of type double Message1 WalkMeters; // message with one parameter of class type Package Message1 GivePackage; // message with two parameters of type int and float Message2 ShoutAgeAndFootSize; void DoShowFinger() { ShowFinger.Send(); // ShowFinger() does the same } void DoWaveHand() { WaveHand(); // WaveHand.Send() does the same } void DoSay(const std::string &words) { Say(words); } void DoWalk(double meters) { WalkMeters(meters); } void DoGivePackage(const Package &package) { GivePackage.Send(package); } void DoShoutAgeAndFootSize(int age, float size) { ShoutAgeAndFootSize(age, size); } }; // Receiver class remembers events received. // Will tell about received events when asked. class MessageReceiverClass { public: MessageReceiverClass() { Amnesia(); } void OnWaveHand() { m_HandWaved = true; } bool HandWaved() { return m_HandWaved; } void OnSay(const std::string &words) { m_WordsSaid = words; } const std::string WordsSaid() { return m_WordsSaid; } void OnWalk(double meters) { m_MetersWalked = meters; } double MetersWalked() { return m_MetersWalked; } void OnGivePackage(const Package &p) { m_PackageReceived = p; } Package PackageReceived() { return m_PackageReceived; } void OnShoutAgeAndFootSize(int age, float footSize) { m_Age = age; m_FootSize = footSize; } int Age() { return m_Age; } float FootSize() { return m_FootSize; } void Amnesia() { m_HandWaved = false; m_WordsSaid.clear(); m_MetersWalked = 0.0; m_PackageReceived.Clear(); m_Age = 0; m_FootSize = 0.0; } void RegisterObservers(MessageSenderClass &sender) { sender.WaveHand += MessageDelegate(this, &MessageReceiverClass::OnWaveHand); sender.ShowFinger += MessageDelegate( this, &MessageReceiverClass::OnWaveHand); // we cannot see clearly, misinterpret this sender.Say += MessageDelegate1(this, &MessageReceiverClass::OnSay); sender.WalkMeters += MessageDelegate1(this, &MessageReceiverClass::OnWalk); sender.GivePackage += MessageDelegate1(this, &MessageReceiverClass::OnGivePackage); sender.ShoutAgeAndFootSize += MessageDelegate2(this, &MessageReceiverClass::OnShoutAgeAndFootSize); } private: bool m_HandWaved; std::string m_WordsSaid; double m_MetersWalked; Package m_PackageReceived; int m_Age; float m_FootSize; }; /* MessageMacro Test classes */ class Law { private: std::string m_Description; public: Law(const std::string &law) : m_Description(law) {} std::string GetDescription() const { return m_Description; } }; // The NewtonMachine will issue specific events class NewtonMachine { mitkNewMessageMacro(AnalysisStarted); mitkNewMessage1Macro(AnalysisStopped, bool); mitkNewMessage1Macro(LawDiscovered, const Law &); // mitkNewMessageWithReturnMacro(PatentFiled, bool); public: void StartAnalysis() { // send the "started" signal m_AnalysisStartedMessage(); // we found a new law of nature by creating one :-) Law massLaw("Unit tests are mandatory!"); m_LawDiscoveredMessage(massLaw); } void StopAnalysis() { // send the "stop" message with true, indicating // that an error occurred m_AnalysisStoppedMessage(true); } bool PatentLaw() { // bool patentAccepted = m_PatentFiledMessage(); // return patentAccepted; // m_PatentFiledMessage(); return false; } }; class Observer { private: NewtonMachine *m_Machine; public: Observer(NewtonMachine *machine) : m_Machine(machine), m_MachineStarted(false), m_MachineStopped(false), m_Error(false), m_Law("NONE") { // Add "observers", i.e. function pointers to the machine m_Machine->AddAnalysisStartedListener(::mitk::MessageDelegate(this, &Observer::MachineStarted)); m_Machine->AddAnalysisStoppedListener( ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); m_Machine->AddLawDiscoveredListener( ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); // m_Machine->AddPatentFiledListener( // ::mitk::MessageDelegate(this, &Observer::ReviewPatent)); } ~Observer() { // Always remove your observers when finished m_Machine->RemoveAnalysisStartedListener(::mitk::MessageDelegate(this, &Observer::MachineStarted)); m_Machine->RemoveAnalysisStoppedListener( ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); m_Machine->RemoveLawDiscoveredListener( ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); // m_Machine->RemoveLawDiscoveredListener( // ::mitk::MessageDelegate(this, &Observer::ReviewPatent)); } void MachineStarted() { m_MachineStarted = true; } void MachineStopped(bool error) { m_MachineStopped = true; m_Error = error; } void LawDiscovered(const Law &law) { m_Law = law; } bool ReviewPatent() { m_PatentReviewed = true; return false; // laws of nature are not patentable. } bool m_MachineStarted; bool m_MachineStopped; bool m_Error; Law m_Law; bool m_PatentReviewed; }; }; // end test class } // end namespace int mitkMessageTest(int /* argc */, char * /*argv*/ []) { MITK_TEST_BEGIN("Message") mitk::mitkMessageTestTestClass::MessageSenderClass sender; mitk::mitkMessageTestTestClass::MessageReceiverClass receiver; MITK_TEST_CONDITION_REQUIRED(true, "Testing instantiation"); receiver.RegisterObservers(sender); MITK_TEST_CONDITION_REQUIRED(true, "Testing registration to messages"); MITK_TEST_CONDITION_REQUIRED((sender.DoWaveHand(), // This is called "comma operator". Don't ask, read! receiver.HandWaved()), "Message without parameters"); receiver.Amnesia(); MITK_TEST_CONDITION_REQUIRED((sender.DoShowFinger(), receiver.HandWaved()), "Message without parameters"); receiver.Amnesia(); MITK_TEST_CONDITION_REQUIRED((sender.DoSay("Blooodworsch"), receiver.WordsSaid() == "Blooodworsch"), "Message with std::string parameter"); receiver.Amnesia(); MITK_TEST_CONDITION_REQUIRED((sender.DoWalk(2.67), (receiver.MetersWalked() - 2.67) < 0.0001), "Message with double parameter"); receiver.Amnesia(); mitk::mitkMessageTestTestClass::Package package(8); MITK_TEST_CONDITION_REQUIRED((sender.DoGivePackage(package), receiver.PackageReceived() == package), "Message with class parameter"); receiver.Amnesia(); MITK_TEST_CONDITION_REQUIRED( (sender.DoShoutAgeAndFootSize(46, 30.5), (receiver.Age() == 46 && (receiver.FootSize() - 30.5 < 0.0001))), "Message with int AND float parameter"); receiver.Amnesia(); mitk::mitkMessageTestTestClass::NewtonMachine newtonMachine; mitk::mitkMessageTestTestClass::Observer observer1(&newtonMachine); mitk::mitkMessageTestTestClass::Observer observer2(&newtonMachine); // This will send two events to registered observers newtonMachine.StartAnalysis(); MITK_TEST_CONDITION(observer1.m_MachineStarted == true, "Message from Message Macro send to receiver 1"); MITK_TEST_CONDITION(observer2.m_MachineStarted == true, "Message from Message Macro send to receiver 2"); MITK_TEST_CONDITION(observer1.m_Law.GetDescription() == std::string("Unit tests are mandatory!"), "Message1 from Message Macro send to receiver 1"); MITK_TEST_CONDITION(observer2.m_Law.GetDescription() == std::string("Unit tests are mandatory!"), "Message1 from Message Macro send to receiver 2"); // This will send one event to registered observers newtonMachine.StopAnalysis(); MITK_TEST_CONDITION(observer1.m_MachineStopped == true, "Message1 from Message Macro send to receiver 1"); MITK_TEST_CONDITION(observer1.m_Error == true, "Message1 parameter from Message Macro send to receiver 1"); MITK_TEST_CONDITION(observer2.m_MachineStopped == true, "Message1 from Message Macro send to receiver 2"); MITK_TEST_CONDITION(observer2.m_Error == true, "Message1 parameter from Message Macro send to receiver 2"); - /* Message with return type tests are work in progess... */ + /* Message with return type tests are work in progress... */ // bool patentSuccessful = newtonMachine.PatentLaw(); // what with return types from multiple observers? // MITK_TEST_CONDITION((observer1.m_PatentReviewed == true) && (patentSuccessful == false), // "Message with return type from Message Macro send to receiver 1"); // // MITK_TEST_CONDITION((observer2.m_PatentReviewed == true) && (patentSuccessful == false), // "Message with return type from Message Macro send to receiver 2"); MITK_TEST_END(); } diff --git a/Modules/Core/test/mitkNodePredicateDataPropertyTest.cpp b/Modules/Core/test/mitkNodePredicateDataPropertyTest.cpp index 6beaf49348..0602c40f92 100644 --- a/Modules/Core/test/mitkNodePredicateDataPropertyTest.cpp +++ b/Modules/Core/test/mitkNodePredicateDataPropertyTest.cpp @@ -1,115 +1,115 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkGeometry3D.h" #include "mitkBaseDataTestImplementation.h" #include "mitkNodePredicateDataProperty.h" #include "mitkDataNode.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include "mitkStringProperty.h" class mitkNodePredicateDataPropertyTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkNodePredicateDataPropertyTestSuite); MITK_TEST(Check_InvalidConstructor); MITK_TEST(Check_InvalidCheckNode); MITK_TEST(Check_CheckName); MITK_TEST(Check_CheckNameAndValue); CPPUNIT_TEST_SUITE_END(); private: mitk::BaseDataTestImplementation::Pointer m_Data; mitk::BaseDataTestImplementation::Pointer m_OtherData; mitk::DataNode::Pointer m_Node; mitk::DataNode::Pointer m_NullNode; mitk::DataNode::Pointer m_NullDataNode; mitk::DataNode::Pointer m_OtherNode; mitk::DataNode::Pointer m_NoPropNode; mitk::StringProperty::Pointer m_RefProperty; public: /** - * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members + * @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used members * for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_RefProperty = mitk::StringProperty::New("value1"); m_Data = mitk::BaseDataTestImplementation::New(); m_Data->SetProperty("prop1", mitk::StringProperty::New("value1")); m_Data->SetProperty("prop2", mitk::StringProperty::New("value2")); m_OtherData = mitk::BaseDataTestImplementation::New(); m_OtherData->SetProperty("prop1", mitk::StringProperty::New("othervalue")); m_NullNode = nullptr; m_NullDataNode = mitk::DataNode::New(); m_Node = mitk::DataNode::New(); m_Node->SetData(m_Data); m_OtherNode = mitk::DataNode::New(); m_OtherNode->SetData(m_OtherData); m_NoPropNode = mitk::DataNode::New(); m_NoPropNode->SetData(mitk::BaseDataTestImplementation::New()); } void tearDown() override { m_Node = nullptr; m_NullNode = nullptr; m_NullDataNode = nullptr; m_OtherNode = nullptr; m_Data = nullptr; m_OtherData = nullptr; } void Check_InvalidConstructor() { CPPUNIT_ASSERT_THROW(mitk::NodePredicateDataProperty::New(""), mitk::Exception); } void Check_InvalidCheckNode() { mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New("aProp"); CPPUNIT_ASSERT_THROW(predicate->CheckNode(nullptr), mitk::Exception); } void Check_CheckName() { mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New("prop1"); CPPUNIT_ASSERT(!predicate->CheckNode(m_NullDataNode)); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(predicate->CheckNode(m_OtherNode)); CPPUNIT_ASSERT(!predicate->CheckNode(m_NoPropNode)); } void Check_CheckNameAndValue() { mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New("prop1", m_RefProperty); CPPUNIT_ASSERT(!predicate->CheckNode(m_NullDataNode)); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(m_OtherNode)); CPPUNIT_ASSERT(!predicate->CheckNode(m_NoPropNode)); } }; MITK_TEST_SUITE_REGISTRATION(mitkNodePredicateDataProperty) diff --git a/Modules/Core/test/mitkNodePredicateGeometryTest.cpp b/Modules/Core/test/mitkNodePredicateGeometryTest.cpp index 1883a5af2b..e5a2790ec6 100644 --- a/Modules/Core/test/mitkNodePredicateGeometryTest.cpp +++ b/Modules/Core/test/mitkNodePredicateGeometryTest.cpp @@ -1,188 +1,188 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkGeometry3D.h" #include "mitkBaseDataTestImplementation.h" #include "mitkNodePredicateGeometry.h" #include "mitkDataNode.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include "mitkProportionalTimeGeometry.h" class mitkNodePredicateGeometryTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkNodePredicateGeometryTestSuite); MITK_TEST(Check_InvalidConstructor); MITK_TEST(Check_CloneAndOriginal); MITK_TEST(Check_DifferentOrigin); MITK_TEST(Check_DifferentIndexToWorldTransform); MITK_TEST(Check_DifferentSpacing); MITK_TEST(Check_DifferentBoundingBox); CPPUNIT_TEST_SUITE_END(); private: mitk::BaseDataTestImplementation::Pointer m_Data; mitk::DataNode::Pointer m_Node; mitk::Geometry3D::Pointer m_RefGeometry; mitk::TimeGeometry::Pointer m_RefTimeGeometry; mitk::Geometry3D::Pointer m_AnotherGeometry3D; public: /** -* @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members +* @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used members * for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_RefGeometry = mitk::Geometry3D::New(); m_RefGeometry->Initialize(); mitk::ProportionalTimeGeometry::Pointer tgeo = mitk::ProportionalTimeGeometry::New(); tgeo->Initialize(m_RefGeometry, 1); m_RefTimeGeometry = tgeo.GetPointer(); m_Data = mitk::BaseDataTestImplementation::New(); m_Data->SetClonedGeometry(m_RefGeometry); m_Node = mitk::DataNode::New(); m_Node->SetData(m_Data); m_AnotherGeometry3D = m_RefGeometry->Clone(); } void tearDown() override { m_RefGeometry = nullptr; m_RefTimeGeometry = nullptr; m_AnotherGeometry3D = nullptr; m_Data = nullptr; } void Check_InvalidConstructor() { m_RefGeometry = nullptr; m_RefTimeGeometry = nullptr; CPPUNIT_ASSERT_THROW(mitk::NodePredicateGeometry::New(m_RefGeometry, 3), mitk::Exception); CPPUNIT_ASSERT_THROW(mitk::NodePredicateGeometry::New(m_RefGeometry), mitk::Exception); CPPUNIT_ASSERT_THROW(mitk::NodePredicateGeometry::New(m_RefTimeGeometry), mitk::Exception); } void Check_CloneAndOriginal() { mitk::NodePredicateGeometry::Pointer predicate = mitk::NodePredicateGeometry::New(m_RefGeometry); mitk::NodePredicateGeometry::Pointer predicateTime = mitk::NodePredicateGeometry::New(m_RefTimeGeometry); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(predicateTime->CheckNode(m_Node)); } void Check_DifferentOrigin() { mitk::NodePredicateGeometry::Pointer predicate = mitk::NodePredicateGeometry::New(m_RefGeometry); mitk::NodePredicateGeometry::Pointer predicateTime = mitk::NodePredicateGeometry::New(m_RefTimeGeometry); mitk::Point3D origin; origin[0] = 0.0; origin[1] = 0.0; origin[2] = 1.0; m_AnotherGeometry3D->SetOrigin(origin); m_Data->SetClonedGeometry(m_AnotherGeometry3D); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(!predicateTime->CheckNode(m_Node)); predicate = mitk::NodePredicateGeometry::New(m_AnotherGeometry3D); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); } void Check_DifferentIndexToWorldTransform() { mitk::NodePredicateGeometry::Pointer predicate = mitk::NodePredicateGeometry::New(m_RefGeometry); mitk::NodePredicateGeometry::Pointer predicateTime = mitk::NodePredicateGeometry::New(m_RefTimeGeometry); mitk::AffineTransform3D::Pointer differentIndexToWorldTransform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType differentMatrix; differentMatrix.SetIdentity(); differentMatrix(1, 1) = 2; differentIndexToWorldTransform->SetMatrix(differentMatrix); m_AnotherGeometry3D->SetIndexToWorldTransform(differentIndexToWorldTransform); m_Data->SetClonedGeometry(m_AnotherGeometry3D); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(!predicateTime->CheckNode(m_Node)); predicate = mitk::NodePredicateGeometry::New(m_AnotherGeometry3D); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); } void Check_DifferentSpacing() { mitk::NodePredicateGeometry::Pointer predicate = mitk::NodePredicateGeometry::New(m_RefGeometry); mitk::NodePredicateGeometry::Pointer predicateTime = mitk::NodePredicateGeometry::New(m_RefTimeGeometry); mitk::Vector3D differentSpacing; differentSpacing[0] = 1.0; differentSpacing[1] = 2.0; differentSpacing[2] = 3.0+3* mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION; m_AnotherGeometry3D->SetSpacing(differentSpacing); m_Data->SetClonedGeometry(m_AnotherGeometry3D); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(!predicateTime->CheckNode(m_Node)); //check with altered geometry as reference (sanity check). mitk::NodePredicateGeometry::Pointer predicate2 = mitk::NodePredicateGeometry::New(m_AnotherGeometry3D); CPPUNIT_ASSERT(predicate2->CheckNode(m_Node)); - //check less strict precission checkings + //check less strict precision checkings differentSpacing[0] = 1.0; differentSpacing[1] = 1.0; differentSpacing[2] = 1.0 + 3 * mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION; m_AnotherGeometry3D->SetSpacing(differentSpacing); m_Data->SetClonedGeometry(m_AnotherGeometry3D); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(!predicateTime->CheckNode(m_Node)); predicate->SetCheckPrecision(1e-3); predicateTime->SetCheckPrecision(1e-3); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(predicateTime->CheckNode(m_Node)); } void Check_DifferentBoundingBox() { mitk::NodePredicateGeometry::Pointer predicate = mitk::NodePredicateGeometry::New(m_RefGeometry); mitk::NodePredicateGeometry::Pointer predicateTime = mitk::NodePredicateGeometry::New(m_RefTimeGeometry); mitk::ScalarType bounds[] = { 0.0, 0.0, 0.0, 1.0, 2.0, 3.0 }; m_AnotherGeometry3D->SetBounds(bounds); m_Data->SetClonedGeometry(m_AnotherGeometry3D); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); CPPUNIT_ASSERT(!predicateTime->CheckNode(m_Node)); predicate = mitk::NodePredicateGeometry::New(m_AnotherGeometry3D); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); } }; MITK_TEST_SUITE_REGISTRATION(mitkNodePredicateGeometry) diff --git a/Modules/Core/test/mitkNodePredicateSubGeometryTest.cpp b/Modules/Core/test/mitkNodePredicateSubGeometryTest.cpp index fd01017681..0864dac46e 100644 --- a/Modules/Core/test/mitkNodePredicateSubGeometryTest.cpp +++ b/Modules/Core/test/mitkNodePredicateSubGeometryTest.cpp @@ -1,244 +1,244 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkGeometry3D.h" #include "mitkBaseDataTestImplementation.h" #include "mitkNodePredicateSubGeometry.h" #include "mitkNodePredicateGeometry.h" #include "mitkDataNode.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" class mitkNodePredicateSubGeometryTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkNodePredicateSubGeometryTestSuite); MITK_TEST(Check_InvalidConstructor); MITK_TEST(Check_Spacing); MITK_TEST(Check_TransformMatrix); MITK_TEST(Check_Bounds); MITK_TEST(Check_Grid); CPPUNIT_TEST_SUITE_END(); private: mitk::BaseDataTestImplementation::Pointer m_Data; mitk::DataNode::Pointer m_Node; mitk::Geometry3D::Pointer m_RefGeometry; mitk::Geometry3D::Pointer m_AnotherGeometry3D; public: /** -* @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members +* @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used members * for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_RefGeometry = mitk::Geometry3D::New(); m_RefGeometry->Initialize(); m_Data = mitk::BaseDataTestImplementation::New(); m_Data->SetClonedGeometry(m_RefGeometry); m_Node = mitk::DataNode::New(); m_Node->SetData(m_Data); m_AnotherGeometry3D = m_RefGeometry->Clone(); } void tearDown() override { m_RefGeometry = nullptr; m_AnotherGeometry3D = nullptr; m_Data = nullptr; } void Check_InvalidConstructor() { m_RefGeometry = nullptr; CPPUNIT_ASSERT_THROW(mitk::NodePredicateSubGeometry::New(m_RefGeometry, 3), mitk::Exception); CPPUNIT_ASSERT_THROW(mitk::NodePredicateSubGeometry::New(m_RefGeometry), mitk::Exception); } void Check_CloneAndOriginal() { mitk::NodePredicateSubGeometry::Pointer predicate = mitk::NodePredicateSubGeometry::New(m_RefGeometry); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); } void Check_Spacing() { mitk::NodePredicateSubGeometry::Pointer predicate = mitk::NodePredicateSubGeometry::New(m_RefGeometry); for (unsigned int i = 0; i < 3; ++i) { mitk::Vector3D wrongSpacing = m_RefGeometry->GetSpacing(); wrongSpacing[i] += mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION * 2; auto wrongGeometry = m_RefGeometry->Clone(); wrongGeometry->SetSpacing(wrongSpacing); m_Node->GetData()->SetGeometry(wrongGeometry); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); } for (unsigned int i = 0; i < 3; ++i) { mitk::Vector3D wrongSpacing = m_RefGeometry->GetSpacing(); wrongSpacing[i] -= mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION * 2; auto wrongGeometry = m_RefGeometry->Clone(); wrongGeometry->SetSpacing(wrongSpacing); m_Node->GetData()->SetGeometry(wrongGeometry); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); } } void Check_TransformMatrix() { mitk::NodePredicateSubGeometry::Pointer predicate = mitk::NodePredicateSubGeometry::New(m_RefGeometry); for (unsigned int i = 0; i < 3; ++i) { for (unsigned int j = 0; j < 3; ++j) { itk::Matrix wrongMatrix = m_RefGeometry->GetIndexToWorldTransform()->GetMatrix(); wrongMatrix[i][j] += mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_DIRECTION_PRECISION * 2; auto wrongGeometry = m_RefGeometry->Clone(); wrongGeometry->GetIndexToWorldTransform()->SetMatrix(wrongMatrix); m_Node->GetData()->SetGeometry(wrongGeometry); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); } } } void Check_Bounds() { auto newBounds = m_RefGeometry->GetBounds(); newBounds[0] = 10; newBounds[1] = 20; newBounds[2] = 10; newBounds[3] = 20; newBounds[4] = 10; newBounds[5] = 20; m_RefGeometry->SetBounds(newBounds); mitk::NodePredicateSubGeometry::Pointer predicate = mitk::NodePredicateSubGeometry::New(m_RefGeometry); for (unsigned int i = 0; i < 6; ++i) { auto legalBounds = newBounds; if (i % 2 == 0) { legalBounds[i] += 1; } else { legalBounds[i] -= 1; } auto legalGeometry = m_RefGeometry->Clone(); legalGeometry->SetBounds(legalBounds); m_Node->GetData()->SetGeometry(legalGeometry); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); } for (unsigned int i = 0; i < 6; ++i) { auto wrongBounds = m_RefGeometry->GetBounds(); if (i % 2 == 0) { wrongBounds[i] -= 1; } else { wrongBounds[i] += 1; } auto wrongGeometry = m_RefGeometry->Clone(); wrongGeometry->SetBounds(wrongBounds); m_Node->GetData()->SetGeometry(wrongGeometry); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); } } void Check_Grid() { auto newBounds = m_RefGeometry->GetBounds(); newBounds[0] = 0; newBounds[1] = 20; newBounds[2] = 0; newBounds[3] = 20; newBounds[4] = 0; newBounds[5] = 20; m_RefGeometry->SetBounds(newBounds); mitk::NodePredicateSubGeometry::Pointer predicate = mitk::NodePredicateSubGeometry::New(m_RefGeometry); auto smallerGeometry = m_RefGeometry->Clone(); newBounds[0] = 5; newBounds[1] = 10; newBounds[2] = 5; newBounds[3] = 10; newBounds[4] = 5; newBounds[5] = 10; smallerGeometry->SetBounds(newBounds); //legal negative shift for (unsigned int i = 0; i < 3; ++i) { auto legalOrigin = smallerGeometry->GetOrigin(); legalOrigin[i] -= smallerGeometry->GetSpacing()[i]; auto legalGeometry = smallerGeometry->Clone(); legalGeometry->SetOrigin(legalOrigin); m_Node->GetData()->SetGeometry(legalGeometry); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); } //legal positive shift for (unsigned int i = 0; i < 3; ++i) { auto legalOrigin = smallerGeometry->GetOrigin(); legalOrigin[i] += smallerGeometry->GetSpacing()[i]; auto legalGeometry = smallerGeometry->Clone(); legalGeometry->SetOrigin(legalOrigin); m_Node->GetData()->SetGeometry(legalGeometry); CPPUNIT_ASSERT(predicate->CheckNode(m_Node)); } //wrong negative shift for (unsigned int i = 0; i < 3; ++i) { auto wrongOrigin = smallerGeometry->GetOrigin(); wrongOrigin[i] -= 2 * mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION; auto wrongGeometry = smallerGeometry->Clone(); wrongGeometry->SetOrigin(wrongOrigin); m_Node->GetData()->SetGeometry(wrongGeometry); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); } //wrong positive shift for (unsigned int i = 0; i < 3; ++i) { auto wrongOrigin = smallerGeometry->GetOrigin(); wrongOrigin[i] += 2 * mitk::NODE_PREDICATE_GEOMETRY_DEFAULT_CHECK_COORDINATE_PRECISION; auto wrongGeometry = smallerGeometry->Clone(); wrongGeometry->SetOrigin(wrongOrigin); m_Node->GetData()->SetGeometry(wrongGeometry); CPPUNIT_ASSERT(!predicate->CheckNode(m_Node)); } } }; MITK_TEST_SUITE_REGISTRATION(mitkNodePredicateSubGeometry) diff --git a/Modules/Core/test/mitkPixelTypeTest.cpp b/Modules/Core/test/mitkPixelTypeTest.cpp index 3bafd0bff5..0f4ad40e51 100644 --- a/Modules/Core/test/mitkPixelTypeTest.cpp +++ b/Modules/Core/test/mitkPixelTypeTest.cpp @@ -1,241 +1,241 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ // Testing #include "mitkTestFixture.h" #include "mitkTestingMacros.h" // std includes #include // MITK includes #include "mitkPixelType.h" #include // ITK includes #include "itkImage.h" #include // VTK includes #include struct MyObscurePixelType { typedef float ValueType; static const size_t Length = 2; }; //## Documentation //## main testing method class mitkPixelTypeTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPixelTypeTestSuite); MITK_TEST(GetComponentType_Success); MITK_TEST(GetPixelTypeAsString_Success); MITK_TEST(GetBpePtype_Success); MITK_TEST(GetNumberOfComponentsPtype_Success); MITK_TEST(GetBitsPerComponentPtype_Success); MITK_TEST(GetBpeItkPtype_Success); MITK_TEST(GetNumberOfComponentsItkPtype_Success); MITK_TEST(GetBitsPerComponentItkPtype_Success); MITK_TEST(ConstructorWithBrackets_Success); MITK_TEST(InitializeWithEqualSign_Success); MITK_TEST(EqualityOperator_Success); MITK_TEST(NotEqualityOperator_Success); MITK_TEST(GetPixelTypeUnknown_Success); MITK_TEST(SetLengthCorrectly_Success); MITK_TEST(ValueTypeCorresponds_Success); MITK_TEST(ImageTypeTraitInt3D_Success); MITK_TEST(ImageTypeTraitShort2D_Success); MITK_TEST(ImageTypeTraitVectorShort3D_Success); MITK_TEST(ImageTypeTraitItkInt3D_Success); MITK_TEST(ImageTypeTraitItkShort2D_Success); MITK_TEST(ImageTypeTraitItkVectorShort3D_Success); CPPUNIT_TEST_SUITE_END(); private: typedef itk::Image, 3> ItkImageType; typedef itk::Image MyObscureImageType; typedef itk::VectorImage VectorImageType; typedef itk::Image> FixedVectorImageType; public: void setUp() override { } void tearDown() override { } void GetComponentType_Success() { mitk::PixelType ptype = mitk::MakePixelType(); MITK_INFO << "m_Ptype = mitk::MakePixelType();"; MITK_INFO << "m_ItkPtype = mitk::MakePixelType();\n with itk::Image, 3> ItkImageType"; CPPUNIT_ASSERT_MESSAGE("GetComponentType()", ptype.GetComponentType() == itk::IOComponentEnum::INT); } void GetPixelTypeAsString_Success() { mitk::PixelType ptype = mitk::MakePixelType(); MITK_INFO << ptype.GetPixelTypeAsString(); MITK_INFO << typeid(ItkImageType).name(); } void GetBpePtype_Success() { mitk::PixelType ptype = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("[m_Ptype] GetBpe()", ptype.GetBpe() == 8 * sizeof(int) * 5); } void GetNumberOfComponentsPtype_Success() { mitk::PixelType ptype = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("[ptype]GetNumberOfComponents()", ptype.GetNumberOfComponents() == 5); } void GetBitsPerComponentPtype_Success() { mitk::PixelType ptype = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("[ptype]GetBitsPerComponent()", ptype.GetBitsPerComponent() == 8 * sizeof(int)); } void GetBpeItkPtype_Success() { mitk::PixelType itkPtype = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("[itkPType] GetBpe()", itkPtype.GetBpe() == 8 * sizeof(int) * 5); } void GetNumberOfComponentsItkPtype_Success() { mitk::PixelType itkPtype = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("[itkPType] GetNumberOfComponents()", itkPtype.GetNumberOfComponents() == 5); } void GetBitsPerComponentItkPtype_Success() { mitk::PixelType itkPtype = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("[itkPType] GetBitsPerComponent()", itkPtype.GetBitsPerComponent() == 8 * sizeof(int)); } void ConstructorWithBrackets_Success() { mitk::PixelType ptype = mitk::MakePixelType(); mitk::PixelType ptype2(ptype); CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)- GetComponentType()", ptype2.GetComponentType() == itk::IOComponentEnum::INT); CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetPixelType(", ptype2.GetPixelType() == ptype.GetPixelType()); CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetComponentType(", ptype2.GetComponentType() == ptype.GetComponentType()); CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetBpe()", ptype2.GetBpe() == 8 * sizeof(int) * 5); CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetNumberOfComponents()", ptype2.GetNumberOfComponents() == 5); CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetBitsPerComponent()", ptype2.GetBitsPerComponent() == 8 * sizeof(int)); } void InitializeWithEqualSign_Success() { mitk::PixelType ptype = mitk::MakePixelType(); mitk::PixelType ptype2 = ptype; CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetComponentType()", ptype2.GetComponentType() == itk::IOComponentEnum::INT); CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetPixelType(", ptype2.GetPixelType() == ptype.GetPixelType()); CPPUNIT_ASSERT_MESSAGE("ptype2( ptype)-GetComponentType(", ptype2.GetComponentType() == ptype.GetComponentType()); CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetBpe()", ptype2.GetBpe() == 8 * sizeof(int) * 5); CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetNumberOfComponents()", ptype2.GetNumberOfComponents() == 5); CPPUNIT_ASSERT_MESSAGE("ptype2 = ptype- GetBitsPerComponent()", ptype2.GetBitsPerComponent() == 8 * sizeof(int)); } void EqualityOperator_Success() { mitk::PixelType ptype = mitk::MakePixelType(); mitk::PixelType ptype2 = ptype; CPPUNIT_ASSERT_MESSAGE("operator ==", ptype == ptype2); } void NotEqualityOperator_Success() { mitk::PixelType ptype = mitk::MakePixelType(); mitk::PixelType ptype3 = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("operator !=", ptype != ptype3); } void GetPixelTypeUnknown_Success() { // test instantiation mitk::PixelType obscurePixelType = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("PixelTypeId is 'UNKNOWN' ", obscurePixelType.GetPixelType() == itk::IOPixelEnum::UNKNOWNPIXELTYPE); } void SetLengthCorrectly_Success() { mitk::PixelType obscurePixelType = mitk::MakePixelType(); - CPPUNIT_ASSERT_MESSAGE("Lenght was set correctly", obscurePixelType.GetNumberOfComponents() == MyObscurePixelType::Length); + CPPUNIT_ASSERT_MESSAGE("Length was set correctly", obscurePixelType.GetNumberOfComponents() == MyObscurePixelType::Length); } void ValueTypeCorresponds_Success() { mitk::PixelType obscurePixelType = mitk::MakePixelType(); CPPUNIT_ASSERT_MESSAGE("ValueType corresponds.", obscurePixelType.GetComponentType() == mitk::MapPixelComponentType::value); } void ImageTypeTraitInt3D_Success() { // test ImageTypeTrait traits class CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid int 3D equals ITK typeid", typeid(mitk::ImageTypeTrait::ImageType) == typeid(itk::Image)); CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is no vector image", (mitk::ImageTypeTrait::IsVectorImage == false)); } void ImageTypeTraitShort2D_Success() { CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid short 2D equals ITK typeid", typeid(mitk::ImageTypeTrait, 3>::ImageType) == typeid(itk::Image, 3>)); CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is no vector image", (mitk::ImageTypeTrait, 3>::IsVectorImage == false)); } void ImageTypeTraitVectorShort3D_Success() { CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid short 3D equals ITK typeid", typeid(mitk::ImageTypeTrait, 3>::ImageType) == typeid(itk::VectorImage)); CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is a vector image", (mitk::ImageTypeTrait, 3>::IsVectorImage == true)); } void ImageTypeTraitItkInt3D_Success() { CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid ITK int 3D equals ITK typeid", typeid(mitk::ImageTypeTrait>::ImageType) == typeid(itk::Image)); CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is no vector image", (mitk::ImageTypeTrait>::IsVectorImage == false)); } void ImageTypeTraitItkShort2D_Success() { CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid ITK short 2D equals ITK typeid", typeid(mitk::ImageTypeTrait, 3>>::ImageType) == typeid(itk::Image, 3>)); CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is no vector image", (mitk::ImageTypeTrait, 3>>::IsVectorImage == false)); } void ImageTypeTraitItkVectorShort3D_Success() { CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait typeid ITK short 3D equals ITK typeid", typeid(mitk::ImageTypeTrait>::ImageType) == typeid(itk::VectorImage)); CPPUNIT_ASSERT_MESSAGE("ImageTypeTrait is a vector image", (mitk::ImageTypeTrait>::IsVectorImage == true)); } }; MITK_TEST_SUITE_REGISTRATION(mitkPixelType) diff --git a/Modules/Core/test/mitkPlaneGeometryTest.cpp b/Modules/Core/test/mitkPlaneGeometryTest.cpp index bf61cc4606..376771613d 100644 --- a/Modules/Core/test/mitkPlaneGeometryTest.cpp +++ b/Modules/Core/test/mitkPlaneGeometryTest.cpp @@ -1,1093 +1,1093 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkAffineTransform3D.h" #include "mitkBaseGeometry.h" #include "mitkGeometry3D.h" #include "mitkInteractionConst.h" #include "mitkLine.h" #include "mitkPlaneGeometry.h" #include "mitkRotationOperation.h" #include "mitkSlicedGeometry3D.h" #include "mitkThinPlateSplineCurvedGeometry.h" #include #include #include #include #include #include #include #include static const mitk::ScalarType testEps = 1E-9; // the epsilon used in this test == at least float precision. class mitkPlaneGeometryTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPlaneGeometryTestSuite); MITK_TEST(TestInitializeStandardPlane); MITK_TEST(TestProjectPointOntoPlane); MITK_TEST(TestPlaneGeometryCloning); MITK_TEST(TestInheritance); MITK_TEST(TestSetExtendInMM); MITK_TEST(TestRotate); MITK_TEST(TestClone); MITK_TEST(TestPlaneComparison); MITK_TEST(TestAxialInitialization); MITK_TEST(TestCoronalInitialization); MITK_TEST(TestSagittalInitialization); MITK_TEST(TestLefthandedCoordinateSystem); MITK_TEST(TestDominantAxesError); MITK_TEST(TestCheckRotationMatrix); // Currently commented out, see See bug 15990 // MITK_TEST(testPlaneGeometryInitializeOrder); MITK_TEST(TestIntersectionPoint); MITK_TEST(TestCase1210); CPPUNIT_TEST_SUITE_END(); private: // private test members that are initialized by setUp() mitk::PlaneGeometry::Pointer planegeometry; mitk::Point3D origin; mitk::Vector3D right, bottom, normal, spacing; mitk::ScalarType width, height; mitk::ScalarType widthInMM, heightInMM, thicknessInMM; public: void setUp() override { planegeometry = mitk::PlaneGeometry::New(); width = 100; widthInMM = width; height = 200; heightInMM = height; thicknessInMM = 1.0; mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); mitk::FillVector3D(normal, 0, 0, thicknessInMM); mitk::FillVector3D(spacing, 1.0, 1.0, thicknessInMM); planegeometry->InitializeStandardPlane(right, bottom); planegeometry->SetOrigin(origin); planegeometry->SetSpacing(spacing); } void tearDown() override {} // This test verifies inheritance behaviour, this test will fail if the behaviour changes in the future void TestInheritance() { mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); mitk::Geometry3D::Pointer g3d = dynamic_cast(plane.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Planegeometry should not be castable to Geometry 3D", g3d.IsNull()); mitk::BaseGeometry::Pointer base = dynamic_cast(plane.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Planegeometry should be castable to BaseGeometry", base.IsNotNull()); g3d = mitk::Geometry3D::New(); base = dynamic_cast(g3d.GetPointer()); CPPUNIT_ASSERT_MESSAGE("Geometry3D should be castable to BaseGeometry", base.IsNotNull()); mitk::SlicedGeometry3D::Pointer sliced = mitk::SlicedGeometry3D::New(); g3d = dynamic_cast(sliced.GetPointer()); CPPUNIT_ASSERT_MESSAGE("SlicedGeometry3D should not be castable to Geometry3D", g3d.IsNull()); mitk::ThinPlateSplineCurvedGeometry::Pointer thin = mitk::ThinPlateSplineCurvedGeometry::New(); plane = dynamic_cast(thin.GetPointer()); CPPUNIT_ASSERT_MESSAGE("AbstractTransformGeometry should be castable to PlaneGeometry", plane.IsNotNull()); plane = mitk::PlaneGeometry::New(); mitk::AbstractTransformGeometry::Pointer atg = dynamic_cast(plane.GetPointer()); CPPUNIT_ASSERT_MESSAGE("PlaneGeometry should not be castable to AbstractTransofrmGeometry", atg.IsNull()); } void TestDominantAxesError() { auto image = mitk::IOUtil::Load(GetTestDataFilePath("NotQuiteARotationMatrix.nrrd")); auto matrix = image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().transpose(); std::vector< int > axes = mitk::PlaneGeometry::CalculateDominantAxes(matrix); CPPUNIT_ASSERT_MESSAGE("Domiant axes cannot be determined in this dataset. Output should be default ordering.", axes.at(0)==0 && axes.at(1)==1 && axes.at(2)==2); } void TestCheckRotationMatrix() { auto image = mitk::IOUtil::Load(GetTestDataFilePath("NotQuiteARotationMatrix.nrrd")); bool is_rotation = mitk::PlaneGeometry::CheckRotationMatrix(image->GetGeometry()->GetIndexToWorldTransform(), 1e-8); CPPUNIT_ASSERT_MESSAGE("Since the test data matrix is not quite a rotation matrix, this should be detected.", !is_rotation); } void TestLefthandedCoordinateSystem() { /** * @brief This method tests InitializeStandardPlane() and IndexToWorld() * with a left-handed coordinate orientation or indexToWorldMatrix. * * Of course this test does not use standard Parameters, which are right-handed. * See also discussion of bug #11477: https://phabricator.mitk.org/T11477 */ planegeometry = mitk::PlaneGeometry::New(); width = 100; widthInMM = 5; height = 200; heightInMM = 3; thicknessInMM = 1.0; mitk::FillVector3D(right, widthInMM, 0, 0); mitk::FillVector3D(bottom, 0, heightInMM, 0); // This one negative sign results in lefthanded coordinate orientation and det(matrix) < 0. mitk::FillVector3D(normal, 0, 0, -thicknessInMM); mitk::AffineTransform3D::Pointer transform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType matrix; mitk::AffineTransform3D::MatrixType::InternalMatrixType &vnl_matrix = matrix.GetVnlMatrix(); vnl_matrix.set_column(0, right); vnl_matrix.set_column(1, bottom); vnl_matrix.set_column(2, normal); // making sure that we didn't screw up this special test case or else fail deadly: assert(vnl_determinant(vnl_matrix) < 0.0); transform->SetIdentity(); transform->SetMatrix(matrix); planegeometry->InitializeStandardPlane(width, height, transform); // Crux of the matter. CPPUNIT_ASSERT_MESSAGE( "Testing if IndexToWorldMatrix is correct after InitializeStandardPlane( width, height, transform ) ", mitk::MatrixEqualElementWise(planegeometry->GetIndexToWorldTransform()->GetMatrix(), matrix)); mitk::Point3D p_index; p_index[0] = 10.; p_index[1] = 10.; p_index[2] = 0.; mitk::Point3D p_world; mitk::Point3D p_expectedResult; p_expectedResult[0] = 50.; p_expectedResult[1] = 30.; p_expectedResult[2] = 0.; ((mitk::BaseGeometry::Pointer)planegeometry)->IndexToWorld(p_index, p_world); // Crux of the matter. CPPUNIT_ASSERT_MESSAGE("Testing if IndexToWorld(a,b) function works correctly with lefthanded matrix ", mitk::Equal(p_world, p_expectedResult, testEps)); } // See bug 1210 // Test does not use standard Parameters void TestCase1210() { mitk::PlaneGeometry::Pointer planegeometry = mitk::PlaneGeometry::New(); mitk::Point3D origin; mitk::Vector3D right, down, spacing; mitk::FillVector3D(origin, 4.5, 7.3, 11.2); mitk::FillVector3D(right, 1.015625, 1.015625, 1.1999969482421875); mitk::FillVector3D(down, 1.4012984643248170709237295832899161312802619418765e-45, 0, 0); mitk::FillVector3D(spacing, 0, 1.4713633875410579244699160624544119378442750389703e-43, 9.2806360452222355258639080851310540729807238879469e-32); std::cout << "Testing InitializeStandardPlane(rightVector, downVector, spacing = nullptr): " << std::endl; CPPUNIT_ASSERT_NO_THROW(planegeometry->InitializeStandardPlane(right, down, &spacing)); /* std::cout << "Testing width, height and thickness (in units): "; if((mitk::Equal(planegeometry->GetExtent(0),width)==false) || (mitk::Equal(planegeometry->GetExtent(1),height)==false) || (mitk::Equal(planegeometry->GetExtent(2),1)==false) ) { std::cout<<"[FAILED]"<GetExtentInMM(0),widthInMM)==false) || (mitk::Equal(planegeometry->GetExtentInMM(1),heightInMM)==false) || (mitk::Equal(planegeometry->GetExtentInMM(2),thicknessInMM)==false) ) { std::cout<<"[FAILED]"< 0. * */ // Test does not use standard Parameters void TestIntersectionPoint() { // init plane with its parameter mitk::PlaneGeometry::Pointer myPlaneGeometry = mitk::PlaneGeometry::New(); mitk::Point3D origin; origin[0] = 0.0; origin[1] = 2.0; origin[2] = 0.0; mitk::Vector3D normal; normal[0] = 0.0; normal[1] = 1.0; normal[2] = 0.0; myPlaneGeometry->InitializePlane(origin, normal); // generate points and line for intersection testing // point distance of given line > 1 mitk::Point3D pointP1; pointP1[0] = 2.0; pointP1[1] = 1.0; pointP1[2] = 0.0; mitk::Point3D pointP2; pointP2[0] = 2.0; pointP2[1] = 4.0; pointP2[2] = 0.0; mitk::Vector3D lineDirection; lineDirection[0] = pointP2[0] - pointP1[0]; lineDirection[1] = pointP2[1] - pointP1[1]; lineDirection[2] = pointP2[2] - pointP1[2]; mitk::Line3D xingline(pointP1, lineDirection); mitk::Point3D calcXingPoint; myPlaneGeometry->IntersectionPoint(xingline, calcXingPoint); // point distance of given line < 1 mitk::Point3D pointP3; pointP3[0] = 2.0; pointP3[1] = 2.2; pointP3[2] = 0.0; mitk::Point3D pointP4; pointP4[0] = 2.0; pointP4[1] = 1.7; pointP4[2] = 0.0; mitk::Vector3D lineDirection2; lineDirection2[0] = pointP4[0] - pointP3[0]; lineDirection2[1] = pointP4[1] - pointP3[1]; lineDirection2[2] = pointP4[2] - pointP3[2]; mitk::Line3D xingline2(pointP3, lineDirection2); mitk::Point3D calcXingPoint2; myPlaneGeometry->IntersectionPoint(xingline2, calcXingPoint2); // intersection points must be the same CPPUNIT_ASSERT_MESSAGE("Failed to calculate Intersection Point", calcXingPoint == calcXingPoint2); } /** * @brief This method tests method ProjectPointOntoPlane. * * See also bug #3409. */ // Test does not use standard Parameters void TestProjectPointOntoPlane() { mitk::PlaneGeometry::Pointer myPlaneGeometry = mitk::PlaneGeometry::New(); // create normal mitk::Vector3D normal; normal[0] = 0.0; normal[1] = 0.0; normal[2] = 1.0; // create origin mitk::Point3D origin; origin[0] = -27.582859; origin[1] = 50; origin[2] = 200.27742; // initialize plane geometry myPlaneGeometry->InitializePlane(origin, normal); - // output to descripe the test + // output to describe the test std::cout << "Testing PlaneGeometry according to bug #3409" << std::endl; std::cout << "Our normal is: " << normal << std::endl; std::cout << "So ALL projected points should have exactly the same z-value!" << std::endl; // create a number of points mitk::Point3D myPoints[5]; myPoints[0][0] = -27.582859; myPoints[0][1] = 50.00; myPoints[0][2] = 200.27742; myPoints[1][0] = -26.58662; myPoints[1][1] = 50.00; myPoints[1][2] = 200.19026; myPoints[2][0] = -26.58662; myPoints[2][1] = 50.00; myPoints[2][2] = 200.33124; myPoints[3][0] = 104.58662; myPoints[3][1] = 452.12313; myPoints[3][2] = 866.41236; myPoints[4][0] = -207.58662; myPoints[4][1] = 312.00; myPoints[4][2] = -300.12346; // project points onto plane mitk::Point3D myProjectedPoints[5]; for (unsigned int i = 0; i < 5; ++i) { myProjectedPoints[i] = myPlaneGeometry->ProjectPointOntoPlane(myPoints[i]); } // compare z-values with z-value of plane (should be equal) bool allPointsOnPlane = true; for (auto &myProjectedPoint : myProjectedPoints) { if (fabs(myProjectedPoint[2] - origin[2]) > mitk::sqrteps) { allPointsOnPlane = false; } } CPPUNIT_ASSERT_MESSAGE("All points lie not on the same plane", allPointsOnPlane); } void TestPlaneGeometryCloning() { mitk::PlaneGeometry::Pointer geometry2D = createPlaneGeometry(); try { mitk::PlaneGeometry::Pointer clone = geometry2D->Clone(); itk::Matrix matrix = clone->GetIndexToWorldTransform()->GetMatrix(); CPPUNIT_ASSERT_MESSAGE("Test if matrix element exists...", matrix[0][0] == 31); double origin = geometry2D->GetOrigin()[0]; CPPUNIT_ASSERT_MESSAGE("First Point of origin as expected...", mitk::Equal(origin, 8)); double spacing = geometry2D->GetSpacing()[0]; CPPUNIT_ASSERT_MESSAGE("First Point of spacing as expected...", mitk::Equal(spacing, 31)); } catch (...) { CPPUNIT_FAIL("Error during access on a member of cloned geometry"); } - // direction [row] [coloum] + // direction [row] [column] MITK_TEST_OUTPUT(<< "Casting a rotated 2D ITK Image to a MITK Image and check if Geometry is still same"); } void TestPlaneGeometryInitializeOrder() { mitk::Vector3D mySpacing; mySpacing[0] = 31; mySpacing[1] = 0.1; mySpacing[2] = 5.4; mitk::Point3D myOrigin; myOrigin[0] = 8; myOrigin[1] = 9; myOrigin[2] = 10; mitk::AffineTransform3D::Pointer myTransform = mitk::AffineTransform3D::New(); itk::Matrix transMatrix; transMatrix.Fill(0); transMatrix[0][0] = 1; transMatrix[1][1] = 2; transMatrix[2][2] = 4; myTransform->SetMatrix(transMatrix); mitk::PlaneGeometry::Pointer geometry2D1 = mitk::PlaneGeometry::New(); geometry2D1->SetIndexToWorldTransform(myTransform); geometry2D1->SetSpacing(mySpacing); geometry2D1->SetOrigin(myOrigin); mitk::PlaneGeometry::Pointer geometry2D2 = mitk::PlaneGeometry::New(); geometry2D2->SetSpacing(mySpacing); geometry2D2->SetOrigin(myOrigin); geometry2D2->SetIndexToWorldTransform(myTransform); mitk::PlaneGeometry::Pointer geometry2D3 = mitk::PlaneGeometry::New(); geometry2D3->SetIndexToWorldTransform(myTransform); geometry2D3->SetSpacing(mySpacing); geometry2D3->SetOrigin(myOrigin); geometry2D3->SetIndexToWorldTransform(myTransform); CPPUNIT_ASSERT_MESSAGE("Origin of Geometry 1 matches that of Geometry 2.", mitk::Equal(geometry2D1->GetOrigin(), geometry2D2->GetOrigin())); CPPUNIT_ASSERT_MESSAGE("Origin of Geometry 1 match those of Geometry 3.", mitk::Equal(geometry2D1->GetOrigin(), geometry2D3->GetOrigin())); CPPUNIT_ASSERT_MESSAGE("Origin of Geometry 2 match those of Geometry 3.", mitk::Equal(geometry2D2->GetOrigin(), geometry2D3->GetOrigin())); CPPUNIT_ASSERT_MESSAGE("Spacing of Geometry 1 match those of Geometry 2.", mitk::Equal(geometry2D1->GetSpacing(), geometry2D2->GetSpacing())); CPPUNIT_ASSERT_MESSAGE("Spacing of Geometry 1 match those of Geometry 3.", mitk::Equal(geometry2D1->GetSpacing(), geometry2D3->GetSpacing())); CPPUNIT_ASSERT_MESSAGE("Spacing of Geometry 2 match those of Geometry 3.", mitk::Equal(geometry2D2->GetSpacing(), geometry2D3->GetSpacing())); CPPUNIT_ASSERT_MESSAGE("Transformation of Geometry 1 match those of Geometry 2.", compareMatrix(geometry2D1->GetIndexToWorldTransform()->GetMatrix(), geometry2D2->GetIndexToWorldTransform()->GetMatrix())); CPPUNIT_ASSERT_MESSAGE("Transformation of Geometry 1 match those of Geometry 3.", compareMatrix(geometry2D1->GetIndexToWorldTransform()->GetMatrix(), geometry2D3->GetIndexToWorldTransform()->GetMatrix())); CPPUNIT_ASSERT_MESSAGE("Transformation of Geometry 2 match those of Geometry 3.", compareMatrix(geometry2D2->GetIndexToWorldTransform()->GetMatrix(), geometry2D3->GetIndexToWorldTransform()->GetMatrix())); } void TestInitializeStandardPlane() { CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: width", mitk::Equal(planegeometry->GetExtent(0), width, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: height", mitk::Equal(planegeometry->GetExtent(1), height, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: depth", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: width in mm", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: heght in mm", mitk::Equal(planegeometry->GetExtentInMM(1), heightInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: depth in mm", mitk::Equal(planegeometry->GetExtentInMM(2), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: AxisVectorRight", mitk::Equal(planegeometry->GetAxisVector(0), right, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: AxisVectorBottom", mitk::Equal(planegeometry->GetAxisVector(1), bottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with default Spacing: AxisVectorNormal", mitk::Equal(planegeometry->GetAxisVector(2), normal, testEps)); mitk::Vector3D spacing; thicknessInMM = 1.5; normal.Normalize(); normal *= thicknessInMM; mitk::FillVector3D(spacing, 1.0, 1.0, thicknessInMM); planegeometry->InitializeStandardPlane(right.GetVnlVector(), bottom.GetVnlVector(), &spacing); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: width", mitk::Equal(planegeometry->GetExtent(0), width, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: height", mitk::Equal(planegeometry->GetExtent(1), height, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: depth", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: width in mm", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: height in mm", mitk::Equal(planegeometry->GetExtentInMM(1), heightInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: depth in mm", mitk::Equal(planegeometry->GetExtentInMM(2), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: AxisVectorRight", mitk::Equal(planegeometry->GetAxisVector(0), right, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: AxisVectorBottom", mitk::Equal(planegeometry->GetAxisVector(1), bottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing correct Standard Plane initialization with custom Spacing: AxisVectorNormal", mitk::Equal(planegeometry->GetAxisVector(2), normal, testEps)); ; } void TestSetExtendInMM() { normal.Normalize(); normal *= thicknessInMM; planegeometry->SetExtentInMM(2, thicknessInMM); CPPUNIT_ASSERT_MESSAGE("Testing SetExtentInMM(2, ...), querying by GetExtentInMM(2): ", mitk::Equal(planegeometry->GetExtentInMM(2), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing SetExtentInMM(2, ...), querying by GetAxisVector(2) and comparing to normal: ", mitk::Equal(planegeometry->GetAxisVector(2), normal, testEps)); planegeometry->SetOrigin(origin); CPPUNIT_ASSERT_MESSAGE("Testing SetOrigin", mitk::Equal(planegeometry->GetOrigin(), origin, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() after SetOrigin: Right", mitk::Equal(planegeometry->GetAxisVector(0), right, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() after SetOrigin: Bottom", mitk::Equal(planegeometry->GetAxisVector(1), bottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() after SetOrigin: Normal", mitk::Equal(planegeometry->GetAxisVector(2), normal, testEps)); mappingTests2D(planegeometry, width, height, widthInMM, heightInMM, origin, right, bottom); } void TestRotate() { // Changing the IndexToWorldTransform to a rotated version by SetIndexToWorldTransform() (keep origin): mitk::AffineTransform3D::Pointer transform = mitk::AffineTransform3D::New(); mitk::AffineTransform3D::MatrixType::InternalMatrixType vnlmatrix; vnlmatrix = planegeometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix(); mitk::VnlVector axis(3); mitk::FillVector3D(axis, 1.0, 1.0, 1.0); axis.normalize(); vnl_quaternion rotation(axis, 0.223); vnlmatrix = rotation.rotation_matrix_transpose() * vnlmatrix; mitk::Matrix3D matrix; matrix = vnlmatrix; transform->SetMatrix(matrix); transform->SetOffset(planegeometry->GetIndexToWorldTransform()->GetOffset()); right.SetVnlVector(rotation.rotation_matrix_transpose() * right.GetVnlVector()); bottom.SetVnlVector(rotation.rotation_matrix_transpose() * bottom.GetVnlVector()); normal.SetVnlVector(rotation.rotation_matrix_transpose() * normal.GetVnlVector()); planegeometry->SetIndexToWorldTransform(transform); // The origin changed,because m_Origin=m_IndexToWorldTransform->GetOffset()+GetAxisVector(2)*0.5 // and the AxisVector changes due to the rotation. In other words: the rotation was done around // the corner of the box, not around the planes origin. Now change it to a rotation around // the origin, simply by re-setting the origin to the original one: planegeometry->SetOrigin(origin); CPPUNIT_ASSERT_MESSAGE("Testing whether SetIndexToWorldTransform kept origin: ", mitk::Equal(planegeometry->GetOrigin(), origin, testEps)); mitk::Point2D point; point[0] = 4; point[1] = 3; mitk::Point2D dummy; planegeometry->WorldToIndex(point, dummy); planegeometry->IndexToWorld(dummy, dummy); CPPUNIT_ASSERT_MESSAGE("Testing consistency of index and world coordinates.", dummy == point); CPPUNIT_ASSERT_MESSAGE("Testing width of rotated version: ", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing height of rotated version: ", mitk::Equal(planegeometry->GetExtentInMM(1), heightInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing thickness of rotated version: ", mitk::Equal(planegeometry->GetExtentInMM(2), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of rotated version: right ", mitk::Equal(planegeometry->GetAxisVector(0), right, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of rotated version: bottom", mitk::Equal(planegeometry->GetAxisVector(1), bottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of rotated version: normal", mitk::Equal(planegeometry->GetAxisVector(2), normal, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing GetAxisVector(direction).GetNorm() != planegeometry->GetExtentInMM(direction) of rotated version: ", mitk::Equal(planegeometry->GetAxisVector(0).GetNorm(), planegeometry->GetExtentInMM(0), testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing GetAxisVector(direction).GetNorm() != planegeometry->GetExtentInMM(direction) of rotated version: ", mitk::Equal(planegeometry->GetAxisVector(1).GetNorm(), planegeometry->GetExtentInMM(1), testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing GetAxisVector(direction).GetNorm() != planegeometry->GetExtentInMM(direction) of rotated version: ", mitk::Equal(planegeometry->GetAxisVector(2).GetNorm(), planegeometry->GetExtentInMM(2), testEps)); mappingTests2D(planegeometry, width, height, widthInMM, heightInMM, origin, right, bottom); width *= 2; height *= 3; planegeometry->SetSizeInUnits(width, height); CPPUNIT_ASSERT_MESSAGE("Testing SetSizeInUnits() of rotated version: ", mitk::Equal(planegeometry->GetExtent(0), width, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing SetSizeInUnits() of rotated version: ", mitk::Equal(planegeometry->GetExtent(1), height, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing SetSizeInUnits() of rotated version: ", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width (in mm) of version with changed size in units: ", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing height (in mm) of version with changed size in units: ", mitk::Equal(planegeometry->GetExtentInMM(1), heightInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing thickness (in mm) of version with changed size in units: ", mitk::Equal(planegeometry->GetExtentInMM(2), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of version with changed size in units: right ", mitk::Equal(planegeometry->GetAxisVector(0), right, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of version with changed size in units: bottom", mitk::Equal(planegeometry->GetAxisVector(1), bottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of version with changed size in units: normal", mitk::Equal(planegeometry->GetAxisVector(2), normal, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing GetAxisVector(direction).GetNorm() != planegeometry->GetExtentInMM(direction) of rotated version: ", mitk::Equal(planegeometry->GetAxisVector(0).GetNorm(), planegeometry->GetExtentInMM(0), testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing GetAxisVector(direction).GetNorm() != planegeometry->GetExtentInMM(direction) of rotated version: ", mitk::Equal(planegeometry->GetAxisVector(1).GetNorm(), planegeometry->GetExtentInMM(1), testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing GetAxisVector(direction).GetNorm() != planegeometry->GetExtentInMM(direction) of rotated version: ", mitk::Equal(planegeometry->GetAxisVector(2).GetNorm(), planegeometry->GetExtentInMM(2), testEps)); mappingTests2D(planegeometry, width, height, widthInMM, heightInMM, origin, right, bottom); } void TestClone() { mitk::PlaneGeometry::Pointer clonedplanegeometry = dynamic_cast(planegeometry->Clone().GetPointer()); // Cave: Statement below is negated! CPPUNIT_ASSERT_MESSAGE("Testing Clone(): ", !((clonedplanegeometry.IsNull()) || (clonedplanegeometry->GetReferenceCount() != 1))); CPPUNIT_ASSERT_MESSAGE("Testing origin of cloned version: ", mitk::Equal(clonedplanegeometry->GetOrigin(), origin, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width (in units) of cloned version: ", mitk::Equal(clonedplanegeometry->GetExtent(0), width, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing height (in units) of cloned version: ", mitk::Equal(clonedplanegeometry->GetExtent(1), height, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing extent (in units) of cloned version: ", mitk::Equal(clonedplanegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width (in mm) of cloned version: ", mitk::Equal(clonedplanegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing height (in mm) of cloned version: ", mitk::Equal(clonedplanegeometry->GetExtentInMM(1), heightInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing thickness (in mm) of cloned version: ", mitk::Equal(clonedplanegeometry->GetExtentInMM(2), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of cloned version: right", mitk::Equal(clonedplanegeometry->GetAxisVector(0), right, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of cloned version: bottom", mitk::Equal(clonedplanegeometry->GetAxisVector(1), bottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of cloned version: normal", mitk::Equal(clonedplanegeometry->GetAxisVector(2), normal, testEps)); mappingTests2D(clonedplanegeometry, width, height, widthInMM, heightInMM, origin, right, bottom); } void TestSagittalInitialization() { mitk::Point3D cornerpoint0 = planegeometry->GetCornerPoint(0); mitk::PlaneGeometry::Pointer clonedplanegeometry = planegeometry->Clone(); // Testing InitializeStandardPlane(clonedplanegeometry, planeorientation = Sagittal, zPosition = 0, frontside=true): planegeometry->InitializeStandardPlane(clonedplanegeometry, mitk::PlaneGeometry::Sagittal); mitk::Vector3D newright, newbottom, newnormal; mitk::ScalarType newthicknessInMM; newright = bottom; newthicknessInMM = widthInMM / width * 1.0; // extent in normal direction is 1; newnormal = right; newnormal.Normalize(); newnormal *= newthicknessInMM; newbottom = normal; newbottom.Normalize(); newbottom *= thicknessInMM; CPPUNIT_ASSERT_MESSAGE("Testing GetCornerPoint(0) of sagittally initialized version:", mitk::Equal(planegeometry->GetCornerPoint(0), cornerpoint0, testEps)); // ok, corner was fine, so we can dare to believe the origin is ok. origin = planegeometry->GetOrigin(); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in units) of sagittally initialized version: ", mitk::Equal(planegeometry->GetExtent(0), height, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in units) of sagittally initialized version: ", mitk::Equal(planegeometry->GetExtent(1), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in units) of sagittally initialized version: ", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in mm) of sagittally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(0), heightInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in mm) of sagittally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(1), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in mm) of sagittally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(2), newthicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of sagittally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(0), newright, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of sagittally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(1), newbottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of sagittally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(2), newnormal, testEps)); mappingTests2D(planegeometry, height, 1, heightInMM, thicknessInMM, origin, newright, newbottom); // set origin back to the one of the axial slice: origin = clonedplanegeometry->GetOrigin(); // Testing backside initialization: InitializeStandardPlane(clonedplanegeometry, planeorientation = Axial, zPosition // = 0, frontside=false, rotated=true): planegeometry->InitializeStandardPlane(clonedplanegeometry, mitk::PlaneGeometry::Axial, 0, false, true); mitk::Point3D backsideorigin; backsideorigin = origin + clonedplanegeometry->GetAxisVector(1); //+clonedplanegeometry->GetAxisVector(2); CPPUNIT_ASSERT_MESSAGE("Testing origin of backsidedly, axially initialized version: ", mitk::Equal(planegeometry->GetOrigin(), backsideorigin, testEps)); mitk::Point3D backsidecornerpoint0; backsidecornerpoint0 = cornerpoint0 + clonedplanegeometry->GetAxisVector(1); //+clonedplanegeometry->GetAxisVector(2); CPPUNIT_ASSERT_MESSAGE("Testing GetCornerPoint(0) of sagittally initialized version: ", mitk::Equal(planegeometry->GetCornerPoint(0), backsidecornerpoint0, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in units) of backsidedly, axially initialized version " "(should be same as in mm due to unit spacing, except for thickness, which is always 1): ", mitk::Equal(planegeometry->GetExtent(0), width, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in units) of backsidedly, axially initialized version " "(should be same as in mm due to unit spacing, except for thickness, which is always 1): ", mitk::Equal(planegeometry->GetExtent(1), height, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in units) of backsidedly, axially initialized version " "(should be same as in mm due to unit spacing, except for thickness, which is always 1): ", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in mm) of backsidedly, axially initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in mm) of backsidedly, axially initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(1), heightInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width, height and thickness (in mm) of backsidedly, axially initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(2), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of backsidedly, axially initialized version: ", mitk::Equal(planegeometry->GetAxisVector(0), right, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of backsidedly, axially initialized version: ", mitk::Equal(planegeometry->GetAxisVector(1), -bottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of backsidedly, axially initialized version: ", mitk::Equal(planegeometry->GetAxisVector(2), normal, testEps)); // T22254: Flipped sign mappingTests2D(planegeometry, width, height, widthInMM, heightInMM, backsideorigin, right, -bottom); } void TestCoronalInitialization() { mitk::Point3D cornerpoint0 = planegeometry->GetCornerPoint(0); mitk::PlaneGeometry::Pointer clonedplanegeometry = dynamic_cast(planegeometry->Clone().GetPointer()); //-------- mitk::Vector3D newright, newbottom, newnormal; mitk::ScalarType newthicknessInMM; // Testing InitializeStandardPlane(clonedplanegeometry, planeorientation = Coronal, zPosition = 0, frontside=true) planegeometry->InitializeStandardPlane(clonedplanegeometry, mitk::PlaneGeometry::Coronal); newright = right; newbottom = normal; newbottom.Normalize(); newbottom *= thicknessInMM; newthicknessInMM = heightInMM / height * 1.0 /*extent in normal direction is 1*/; newnormal = -bottom; newnormal.Normalize(); newnormal *= newthicknessInMM; CPPUNIT_ASSERT_MESSAGE("Testing GetCornerPoint(0) of coronally initialized version: ", mitk::Equal(planegeometry->GetCornerPoint(0), cornerpoint0, testEps)); // ok, corner was fine, so we can dare to believe the origin is ok. origin = planegeometry->GetOrigin(); CPPUNIT_ASSERT_MESSAGE("Testing width (in units) of coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(0), width, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing height (in units) of coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(1), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing thickness (in units) of coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width (in mm) of coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing height (in mm) of coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(1), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing thickness (in mm) of coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(2), newthicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(0), newright, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(1), newbottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(2), -newnormal, testEps)); // T22254: Flipped sign mappingTests2D(planegeometry, width, 1, widthInMM, thicknessInMM, origin, newright, newbottom); // Changing plane to in-plane unit spacing using SetSizeInUnits: planegeometry->SetSizeInUnits(planegeometry->GetExtentInMM(0), planegeometry->GetExtentInMM(1)); CPPUNIT_ASSERT_MESSAGE("Testing origin of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetOrigin(), origin, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in units) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in units) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(1), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in units) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in mm) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in mm) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(1), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in mm) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(2), newthicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(0), newright, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(1), newbottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(2), -newnormal, testEps)); // T22254: Flipped sign mappingTests2D(planegeometry, widthInMM, thicknessInMM, widthInMM, thicknessInMM, origin, newright, newbottom); // Changing plane to unit spacing also in normal direction using SetExtentInMM(2, 1.0): planegeometry->SetExtentInMM(2, 1.0); newnormal.Normalize(); CPPUNIT_ASSERT_MESSAGE("Testing origin of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetOrigin(), origin, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in units) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in units) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(1), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in units) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in mm) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in mm) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(1), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE( "Testing width, height and thickness (in mm) of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(2), 1.0, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(0), newright, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(1), newbottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of unit spaced, coronally initialized version: ", mitk::Equal(planegeometry->GetAxisVector(2), -newnormal, testEps)); // T22254: Flipped sign mappingTests2D(planegeometry, widthInMM, thicknessInMM, widthInMM, thicknessInMM, origin, newright, newbottom); } void TestAxialInitialization() { mitk::Point3D cornerpoint0 = planegeometry->GetCornerPoint(0); // Clone, move, rotate and test for 'IsParallel' and 'IsOnPlane' mitk::PlaneGeometry::Pointer clonedplanegeometry = dynamic_cast(planegeometry->Clone().GetPointer()); CPPUNIT_ASSERT_MESSAGE("Testing Clone(): ", !((clonedplanegeometry.IsNull()) || (clonedplanegeometry->GetReferenceCount() != 1))); std::cout << "Testing InitializeStandardPlane(clonedplanegeometry, planeorientation = Axial, zPosition = 0, " "frontside=true): " << std::endl; planegeometry->InitializeStandardPlane(clonedplanegeometry); CPPUNIT_ASSERT_MESSAGE("Testing origin of axially initialized version: ", mitk::Equal(planegeometry->GetOrigin(), origin)); CPPUNIT_ASSERT_MESSAGE("Testing GetCornerPoint(0) of axially initialized version: ", mitk::Equal(planegeometry->GetCornerPoint(0), cornerpoint0)); CPPUNIT_ASSERT_MESSAGE("Testing width (in units) of axially initialized version (should be same as in mm due to " "unit spacing, except for thickness, which is always 1): ", mitk::Equal(planegeometry->GetExtent(0), width, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing height (in units) of axially initialized version (should be same as in mm due to " "unit spacing, except for thickness, which is always 1): ", mitk::Equal(planegeometry->GetExtent(1), height, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing thickness (in units) of axially initialized version (should be same as in mm due " "to unit spacing, except for thickness, which is always 1): ", mitk::Equal(planegeometry->GetExtent(2), 1, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing width (in mm) of axially initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(0), widthInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing height (in mm) of axially initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(1), heightInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing thickness (in mm) of axially initialized version: ", mitk::Equal(planegeometry->GetExtentInMM(2), thicknessInMM, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of axially initialized version: ", mitk::Equal(planegeometry->GetAxisVector(0), right, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of axially initialized version: ", mitk::Equal(planegeometry->GetAxisVector(1), bottom, testEps)); CPPUNIT_ASSERT_MESSAGE("Testing GetAxisVector() of axially initialized version: ", mitk::Equal(planegeometry->GetAxisVector(2), normal, testEps)); mappingTests2D(planegeometry, width, height, widthInMM, heightInMM, origin, right, bottom); } void TestPlaneComparison() { // Clone, move, rotate and test for 'IsParallel' and 'IsOnPlane' mitk::PlaneGeometry::Pointer clonedplanegeometry2 = dynamic_cast(planegeometry->Clone().GetPointer()); CPPUNIT_ASSERT_MESSAGE("Testing Clone(): ", !((clonedplanegeometry2.IsNull()) || (clonedplanegeometry2->GetReferenceCount() != 1))); - CPPUNIT_ASSERT_MESSAGE("Testing wheter original and clone are at the same position", + CPPUNIT_ASSERT_MESSAGE("Testing whether original and clone are at the same position", clonedplanegeometry2->IsOnPlane(planegeometry.GetPointer())); CPPUNIT_ASSERT_MESSAGE(" Asserting that origin is on the plane cloned plane:", clonedplanegeometry2->IsOnPlane(origin)); mitk::VnlVector newaxis(3); mitk::FillVector3D(newaxis, 1.0, 1.0, 1.0); newaxis.normalize(); vnl_quaternion rotation2(newaxis, 0.0); mitk::Vector3D clonednormal = clonedplanegeometry2->GetNormal(); mitk::Point3D clonedorigin = clonedplanegeometry2->GetOrigin(); auto planerot = new mitk::RotationOperation(mitk::OpROTATE, origin, clonedplanegeometry2->GetAxisVector(0), 180.0); clonedplanegeometry2->ExecuteOperation(planerot); CPPUNIT_ASSERT_MESSAGE(" Asserting that a flipped plane is still on the original plane: ", clonedplanegeometry2->IsOnPlane(planegeometry.GetPointer())); clonedorigin += clonednormal; clonedplanegeometry2->SetOrigin(clonedorigin); CPPUNIT_ASSERT_MESSAGE("Testing if the translated (cloned, flipped) plane is parallel to its origin plane: ", clonedplanegeometry2->IsParallel(planegeometry)); delete planerot; planerot = new mitk::RotationOperation(mitk::OpROTATE, origin, clonedplanegeometry2->GetAxisVector(0), 0.5); clonedplanegeometry2->ExecuteOperation(planerot); - CPPUNIT_ASSERT_MESSAGE("Testing if a non-paralell plane gets recognized as not paralell [rotation +0.5 degree] : ", + CPPUNIT_ASSERT_MESSAGE("Testing if a non-parallel plane gets recognized as not parallel [rotation +0.5 degree] : ", !clonedplanegeometry2->IsParallel(planegeometry)); delete planerot; planerot = new mitk::RotationOperation(mitk::OpROTATE, origin, clonedplanegeometry2->GetAxisVector(0), -1.0); clonedplanegeometry2->ExecuteOperation(planerot); - CPPUNIT_ASSERT_MESSAGE("Testing if a non-paralell plane gets recognized as not paralell [rotation -0.5 degree] : ", + CPPUNIT_ASSERT_MESSAGE("Testing if a non-parallel plane gets recognized as not parallel [rotation -0.5 degree] : ", !clonedplanegeometry2->IsParallel(planegeometry)); delete planerot; planerot = new mitk::RotationOperation(mitk::OpROTATE, origin, clonedplanegeometry2->GetAxisVector(0), 360.5); clonedplanegeometry2->ExecuteOperation(planerot); - CPPUNIT_ASSERT_MESSAGE("Testing if a non-paralell plane gets recognized as paralell [rotation 360 degree] : ", + CPPUNIT_ASSERT_MESSAGE("Testing if a non-parallel plane gets recognized as parallel [rotation 360 degree] : ", clonedplanegeometry2->IsParallel(planegeometry)); } private: // helper Methods for the Tests mitk::PlaneGeometry::Pointer createPlaneGeometry() { mitk::Vector3D mySpacing; mySpacing[0] = 31; mySpacing[1] = 0.1; mySpacing[2] = 5.4; mitk::Point3D myOrigin; myOrigin[0] = 8; myOrigin[1] = 9; myOrigin[2] = 10; mitk::AffineTransform3D::Pointer myTransform = mitk::AffineTransform3D::New(); itk::Matrix transMatrix; transMatrix.Fill(0); transMatrix[0][0] = 1; transMatrix[1][1] = 2; transMatrix[2][2] = 4; myTransform->SetMatrix(transMatrix); mitk::PlaneGeometry::Pointer geometry2D = mitk::PlaneGeometry::New(); geometry2D->SetIndexToWorldTransform(myTransform); geometry2D->SetSpacing(mySpacing); geometry2D->SetOrigin(myOrigin); return geometry2D; } bool compareMatrix(itk::Matrix left, itk::Matrix right) { bool equal = true; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) equal &= mitk::Equal(left[i][j], right[i][j]); return equal; } /** * This function tests for correct mapping and is called several times from other tests **/ void mappingTests2D(const mitk::PlaneGeometry *planegeometry, const mitk::ScalarType &width, const mitk::ScalarType &height, const mitk::ScalarType &widthInMM, const mitk::ScalarType &heightInMM, const mitk::Point3D &origin, const mitk::Vector3D &right, const mitk::Vector3D &bottom) { std::cout << "Testing mapping Map(pt2d_mm(x=widthInMM/2.3,y=heightInMM/2.5), pt3d_mm) and compare with expected: "; mitk::Point2D pt2d_mm; mitk::Point3D pt3d_mm, expected_pt3d_mm; pt2d_mm[0] = widthInMM / 2.3; pt2d_mm[1] = heightInMM / 2.5; expected_pt3d_mm = origin + right * (pt2d_mm[0] / right.GetNorm()) + bottom * (pt2d_mm[1] / bottom.GetNorm()); planegeometry->Map(pt2d_mm, pt3d_mm); CPPUNIT_ASSERT_MESSAGE( "Testing mapping Map(pt2d_mm(x=widthInMM/2.3,y=heightInMM/2.5), pt3d_mm) and compare with expected", mitk::Equal(pt3d_mm, expected_pt3d_mm, testEps)); std::cout << "Testing mapping Map(pt3d_mm, pt2d_mm) and compare with expected: "; mitk::Point2D testpt2d_mm; planegeometry->Map(pt3d_mm, testpt2d_mm); std::cout << std::setprecision(12) << "Expected pt2d_mm " << pt2d_mm << std::endl; std::cout << std::setprecision(12) << "Result testpt2d_mm " << testpt2d_mm << std::endl; std::cout << std::setprecision(12) << "10*mitk::eps " << 10 * mitk::eps << std::endl; // This eps is temporarily set to 10*mitk::eps. See bug #15037 for details. CPPUNIT_ASSERT_MESSAGE("Testing mapping Map(pt3d_mm, pt2d_mm) and compare with expected", mitk::Equal(pt2d_mm, testpt2d_mm, 10 * mitk::eps)); std::cout << "Testing IndexToWorld(pt2d_units, pt2d_mm) and compare with expected: "; mitk::Point2D pt2d_units; pt2d_units[0] = width / 2.0; pt2d_units[1] = height / 2.0; pt2d_mm[0] = widthInMM / 2.0; pt2d_mm[1] = heightInMM / 2.0; planegeometry->IndexToWorld(pt2d_units, testpt2d_mm); std::cout << std::setprecision(12) << "Expected pt2d_mm " << pt2d_mm << std::endl; std::cout << std::setprecision(12) << "Result testpt2d_mm " << testpt2d_mm << std::endl; std::cout << std::setprecision(12) << "10*mitk::eps " << 10 * mitk::eps << std::endl; // This eps is temporarily set to 10*mitk::eps. See bug #15037 for details. CPPUNIT_ASSERT_MESSAGE("Testing IndexToWorld(pt2d_units, pt2d_mm) and compare with expected: ", mitk::Equal(pt2d_mm, testpt2d_mm, 10 * mitk::eps)); std::cout << "Testing WorldToIndex(pt2d_mm, pt2d_units) and compare with expected: "; mitk::Point2D testpt2d_units; planegeometry->WorldToIndex(pt2d_mm, testpt2d_units); std::cout << std::setprecision(12) << "Expected pt2d_units " << pt2d_units << std::endl; std::cout << std::setprecision(12) << "Result testpt2d_units " << testpt2d_units << std::endl; std::cout << std::setprecision(12) << "10*mitk::eps " << 10 * mitk::eps << std::endl; // This eps is temporarily set to 10*mitk::eps. See bug #15037 for details. CPPUNIT_ASSERT_MESSAGE("Testing WorldToIndex(pt2d_mm, pt2d_units) and compare with expected:", mitk::Equal(pt2d_units, testpt2d_units, 10 * mitk::eps)); } }; MITK_TEST_SUITE_REGISTRATION(mitkPlaneGeometry) diff --git a/Modules/Core/test/mitkPointSetEqualTest.cpp b/Modules/Core/test/mitkPointSetEqualTest.cpp index d00871cfd4..c03b5a4acf 100644 --- a/Modules/Core/test/mitkPointSetEqualTest.cpp +++ b/Modules/Core/test/mitkPointSetEqualTest.cpp @@ -1,102 +1,102 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPointSet.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" /** * @brief mitkPointSetEqualTestSuite A test class for Equal methods in mitk::PointSet. */ class mitkPointSetEqualTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPointSetEqualTestSuite); MITK_TEST(Equal_CloneAndOriginal_ReturnsTrue); MITK_TEST(Equal_DifferentGeometries_ReturnsFalse); MITK_TEST(Equal_DifferentNumberOfPoints_ReturnsFalse); MITK_TEST(Equal_DifferentPoints_ReturnsFalse); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different (sub-)tests. All members are initialized via setUp().*/ mitk::PointSet::Pointer m_PointSet; mitk::PointSet::Pointer m_AnotherPointSet; public: /** -* @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members +* @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used members * for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_PointSet = mitk::PointSet::New(); m_AnotherPointSet = m_PointSet->Clone(); } void tearDown() override { m_PointSet = nullptr; m_AnotherPointSet = nullptr; } void Equal_CloneAndOriginal_ReturnsTrue() { mitk::PointSet::Pointer newPointSet = mitk::PointSet::New(); MITK_ASSERT_EQUAL(newPointSet, newPointSet->Clone(), "A clone should be equal to its original."); } void Equal_DifferentGeometries_ReturnsFalse() { mitk::Point3D origin; origin[0] = 0.0; origin[1] = 0.0; origin[2] = 1.0 + 2 * mitk::eps; m_AnotherPointSet->GetGeometry()->SetOrigin(origin); MITK_ASSERT_NOT_EQUAL(m_PointSet, m_AnotherPointSet, "Origin was modified. Result should be false."); } void Equal_DifferentNumberOfPoints_ReturnsFalse() { mitk::Point3D tmpPoint; tmpPoint[0] = 1.0; tmpPoint[1] = 1.0; tmpPoint[2] = 1.0; m_PointSet->InsertPoint(1, tmpPoint); m_PointSet->InsertPoint(2, tmpPoint); m_AnotherPointSet->InsertPoint(1, tmpPoint); MITK_ASSERT_NOT_EQUAL( m_PointSet, m_AnotherPointSet, "One pointset has two points the other has one. Result should be false."); } void Equal_DifferentPoints_ReturnsFalse() { mitk::Point3D tmpPoint; tmpPoint[0] = 1.0; tmpPoint[1] = 1.0; tmpPoint[2] = 1.0; m_PointSet->InsertPoint(1, tmpPoint); tmpPoint[0] = 1.0 + 2 * mitk::eps; m_AnotherPointSet->InsertPoint(1, tmpPoint); MITK_ASSERT_NOT_EQUAL( m_PointSet, m_AnotherPointSet, "Two pointsets with different points. Result should be false."); } }; MITK_TEST_SUITE_REGISTRATION(mitkPointSetEqual) diff --git a/Modules/Core/test/mitkPreferenceListReaderOptionsFunctorTest.cpp b/Modules/Core/test/mitkPreferenceListReaderOptionsFunctorTest.cpp index 0559a8df0f..0a9a8bc80a 100644 --- a/Modules/Core/test/mitkPreferenceListReaderOptionsFunctorTest.cpp +++ b/Modules/Core/test/mitkPreferenceListReaderOptionsFunctorTest.cpp @@ -1,219 +1,219 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPreferenceListReaderOptionsFunctor.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include #include #include #include #include namespace mitk { class TestFileReaderService : public mitk::AbstractFileReader { public: TestFileReaderService(const std::string &description) : AbstractFileReader(CustomMimeType("TestMimeType"), description) { Options options; options["o1"] = 0; this->SetDefaultOptions(options); m_ServiceRegistration = RegisterService(); }; ~TestFileReaderService() override { }; using AbstractFileReader::Read; std::vector> DoRead() override { std::vector> result; return result; }; ConfidenceLevel GetConfidenceLevel() const override { return Supported; }; private: TestFileReaderService * Clone() const override { return new TestFileReaderService(*this); }; us::ServiceRegistration m_ServiceRegistration; }; } // namespace mitk class mitkPreferenceListReaderOptionsFunctorTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPreferenceListReaderOptionsFunctorTestSuite); MITK_TEST(UsePreferenceList); MITK_TEST(UseBlackList); MITK_TEST(UseNoList); MITK_TEST(UseBlackAndPreferenceList); MITK_TEST(UseOverlappingBlackAndPreferenceList); MITK_TEST(UsePreferenceListWithInexistantReaders); MITK_TEST(UseAllBlackedList); MITK_TEST(SetOptions); CPPUNIT_TEST_SUITE_END(); private: std::string m_ImagePath; mitk::PreferenceListReaderOptionsFunctor::ListType preference; mitk::PreferenceListReaderOptionsFunctor::ListType black; mitk::PreferenceListReaderOptionsFunctor::ListType emptyList; mitk::TestFileReaderService* m_NormalService; mitk::TestFileReaderService* m_PrefService; mitk::TestFileReaderService* m_BlackService; mitk::CustomMimeType* m_TestMimeType; public: void setUp() override { m_ImagePath = GetTestDataFilePath("BallBinary30x30x30.nrrd"); - preference = { "Prefered Test Service" }; + preference = { "Preferred Test Service" }; black = { "Unwanted Test Service" }; emptyList = {}; m_TestMimeType = new mitk::CustomMimeType("TestMimeType"); m_TestMimeType->AddExtension("nrrd"); m_TestMimeType->SetCategory(mitk::IOMimeTypes::CATEGORY_IMAGES()); m_TestMimeType->SetComment("Test mime type"); us::ModuleContext *context = us::GetModuleContext(); us::ServiceProperties props; props[us::ServiceConstants::SERVICE_RANKING()] = 100; context->RegisterService(m_TestMimeType, props); m_NormalService = new mitk::TestFileReaderService("Normal Test Service"); - m_PrefService = new mitk::TestFileReaderService("Prefered Test Service"); + m_PrefService = new mitk::TestFileReaderService("Preferred Test Service"); m_BlackService = new mitk::TestFileReaderService("Unwanted Test Service"); } void tearDown() override { delete m_PrefService; delete m_BlackService; delete m_NormalService; delete m_TestMimeType; } void UsePreferenceList() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, emptyList); CPPUNIT_ASSERT(true == functor(info)); auto description = info.m_ReaderSelector.GetSelected().GetDescription(); - CPPUNIT_ASSERT_EQUAL(std::string("Prefered Test Service"), description); + CPPUNIT_ASSERT_EQUAL(std::string("Preferred Test Service"), description); CPPUNIT_ASSERT("0" == info.m_ReaderSelector.GetSelected().GetReader()->GetOptions()["o1"].ToString()); } void UseNoList() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(emptyList, emptyList); CPPUNIT_ASSERT(true == functor(info)); auto description = info.m_ReaderSelector.GetSelected().GetDescription(); CPPUNIT_ASSERT_EQUAL(std::string("Normal Test Service"), description); } void UseBlackList() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(emptyList, black); CPPUNIT_ASSERT(true == functor(info)); auto description = info.m_ReaderSelector.GetSelected().GetDescription(); CPPUNIT_ASSERT(description != "Unwanted Test Service"); } void UseBlackAndPreferenceList() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, black); CPPUNIT_ASSERT(true == functor(info)); auto description = info.m_ReaderSelector.GetSelected().GetDescription(); - CPPUNIT_ASSERT_EQUAL(std::string("Prefered Test Service"), description); + CPPUNIT_ASSERT_EQUAL(std::string("Preferred Test Service"), description); } void UseOverlappingBlackAndPreferenceList() { mitk::IOUtil::LoadInfo info(m_ImagePath); - black.push_back("Prefered Test Service"); + black.push_back("Preferred Test Service"); black.push_back("Normal Test Service"); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, black); CPPUNIT_ASSERT(true == functor(info)); auto description = info.m_ReaderSelector.GetSelected().GetDescription(); CPPUNIT_ASSERT_EQUAL(std::string("ITK NrrdImageIO"), description); } void UsePreferenceListWithInexistantReaders() { mitk::IOUtil::LoadInfo info(m_ImagePath); preference.push_back("InexistantReader"); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, emptyList); CPPUNIT_ASSERT(true == functor(info)); auto description = info.m_ReaderSelector.GetSelected().GetDescription(); - CPPUNIT_ASSERT_EQUAL(std::string("Prefered Test Service"), description); + CPPUNIT_ASSERT_EQUAL(std::string("Preferred Test Service"), description); } void UseAllBlackedList() { mitk::IOUtil::LoadInfo info(m_ImagePath); for (const auto &reader : info.m_ReaderSelector.Get()) { black.push_back(reader.GetDescription()); } mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(emptyList, black); CPPUNIT_ASSERT_THROW(functor(info), mitk::Exception); } void SetOptions() { mitk::IOUtil::LoadInfo info(m_ImagePath); mitk::IFileReader::Options options; options.insert(std::make_pair("o1", 42)); mitk::PreferenceListReaderOptionsFunctor functor = mitk::PreferenceListReaderOptionsFunctor(preference, options); CPPUNIT_ASSERT(true == functor(info)); auto description = info.m_ReaderSelector.GetSelected().GetDescription(); - CPPUNIT_ASSERT_EQUAL(std::string("Prefered Test Service"), description); + CPPUNIT_ASSERT_EQUAL(std::string("Preferred Test Service"), description); CPPUNIT_ASSERT("42" == info.m_ReaderSelector.GetSelected().GetReader()->GetOption("o1").ToString()); } }; MITK_TEST_SUITE_REGISTRATION(mitkPreferenceListReaderOptionsFunctor) diff --git a/Modules/Core/test/mitkPropertyPersistenceTest.cpp b/Modules/Core/test/mitkPropertyPersistenceTest.cpp index c4b0bc305a..01f2b4413c 100644 --- a/Modules/Core/test/mitkPropertyPersistenceTest.cpp +++ b/Modules/Core/test/mitkPropertyPersistenceTest.cpp @@ -1,309 +1,309 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkIOMimeTypes.h" #include "mitkPropertyPersistence.h" #include "mitkStringProperty.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include #include #include class mitkPropertyPersistenceTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPropertyPersistenceTestSuite); MITK_TEST(AddInfo); MITK_TEST(GetInfo); MITK_TEST(GetInfo_mime); MITK_TEST(GetInfoByKey); MITK_TEST(HasInfo); MITK_TEST(RemoveAllInfo); MITK_TEST(RemoveInfo); MITK_TEST(RemoveInfo_withMime); CPPUNIT_TEST_SUITE_END(); private: mitk::PropertyPersistenceInfo::Pointer info1; mitk::PropertyPersistenceInfo::Pointer info2; mitk::PropertyPersistenceInfo::Pointer info3; mitk::PropertyPersistenceInfo::Pointer info4; mitk::PropertyPersistenceInfo::Pointer info5; mitk::PropertyPersistenceInfo::Pointer info6; mitk::PropertyPersistenceInfo::Pointer infoX; mitk::PropertyPersistenceInfo::Pointer infoX2; std::string prop1; std::string prop2; std::string prop3; std::string prop4; std::string prop5; std::string prop6; std::string propX; std::string keyX; std::string propXTemplate; std::string keyXTemplate; std::string propX2; mitk::IPropertyPersistence *service; static bool checkExistance(const mitk::PropertyPersistence::InfoResultType &infos, const mitk::PropertyPersistenceInfo *info) { auto predicate = [info](const mitk::PropertyPersistenceInfo::ConstPointer &x) { return infosAreEqual(info, x); }; auto finding = std::find_if(infos.begin(), infos.end(), predicate); bool result = finding != infos.end(); return result; } static bool infosAreEqual(const mitk::PropertyPersistenceInfo *ref, const mitk::PropertyPersistenceInfo *info) { bool result = true; if (!info || !ref) { return false; } result = result && ref->GetName() == info->GetName(); result = result && ref->GetKey() == info->GetKey(); result = result && ref->GetMimeTypeName() == info->GetMimeTypeName(); return result; } public: void setUp() override { service = mitk::CreateTestInstancePropertyPersistence(); prop1 = "prop1"; prop2 = "prop1"; prop3 = "prop1"; prop4 = "prop4"; prop5 = "prop5"; propX = "prop(\\d*)"; keyX = "key(\\d*)"; propXTemplate = "prop$1"; keyXTemplate = "key.$1"; propX2 = "otherprop(\\d*)"; info1 = mitk::PropertyPersistenceInfo::New(); info1->SetNameAndKey(prop1, "key1"); info2 = mitk::PropertyPersistenceInfo::New(prop2, "mime2"); info2->SetNameAndKey(prop2, "key2"); info3 = mitk::PropertyPersistenceInfo::New(prop3, "mime3"); info3->SetNameAndKey(prop3, "key3"); info4 = mitk::PropertyPersistenceInfo::New(prop4, "mime2"); info4->SetNameAndKey(prop4, "key2"); info5 = mitk::PropertyPersistenceInfo::New(prop5, "mime5"); info5->SetNameAndKey(prop5, "key5"); infoX = mitk::PropertyPersistenceInfo::New("", "mimeX"); infoX->UseRegEx(propX, propXTemplate, keyX, keyXTemplate); infoX2 = mitk::PropertyPersistenceInfo::New(); infoX2->UseRegEx(propX2, propXTemplate); service->AddInfo(info1, false); service->AddInfo(info2, false); service->AddInfo(info3, false); service->AddInfo(info4, false); service->AddInfo(info5, false); service->AddInfo(infoX, false); service->AddInfo(infoX2, false); } void tearDown() override { delete service; } void AddInfo() { mitk::PropertyPersistenceInfo::Pointer info2_new = mitk::PropertyPersistenceInfo::New(prop2, "otherMime"); info2_new->SetNameAndKey(prop2, "newKey"); mitk::PropertyPersistenceInfo::Pointer info2_otherKey = mitk::PropertyPersistenceInfo::New("prop2", "mime2"); info2_otherKey->SetNameAndKey(prop2, "otherKey"); mitk::PropertyPersistenceInfo::Pointer info_newPropNKey = mitk::PropertyPersistenceInfo::New("", "otherMime"); info_newPropNKey->SetNameAndKey("newProp", "newKey"); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (no overwrite) -> no adding", !service->AddInfo(info2_otherKey, false)); CPPUNIT_ASSERT_MESSAGE( "Testing addinfo of already existing info (no overwrite) -> no adding -> key should not be changed.", service->GetInfo(prop2, "mime2", false).front()->GetKey() == "key2"); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of already existing info (overwrite) -> adding", service->AddInfo(info2_otherKey, true)); CPPUNIT_ASSERT_MESSAGE( "Testing addinfo of already existing info (no overwrite) -> adding -> key should be changed.", service->GetInfo(prop2, "mime2", false).front()->GetKey() == "otherKey"); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding", service->AddInfo(info2_new, false)); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (other mime type; no overwrite) -> adding -> info exists.", !service->GetInfo(prop2, "otherMime", false).empty()); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding", service->AddInfo(info_newPropNKey, false)); CPPUNIT_ASSERT_MESSAGE("Testing addinfo of info (new prop name; no overwrite) -> adding ->info exists.", !service->GetInfo("newProp", "otherMime", false).empty()); } void GetInfo() { mitk::PropertyPersistence::InfoResultType infos = service->GetInfo(prop1, false); CPPUNIT_ASSERT(infos.size() == 3); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info1)); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info2)); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info3)); infos = service->GetInfo(prop4, false); CPPUNIT_ASSERT(infos.size() == 1); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info4)); infos = service->GetInfo("unkown", false); - CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown prop.", infos.empty()); + CPPUNIT_ASSERT_MESSAGE("Check size of result for unknown prop.", infos.empty()); infos = service->GetInfo("prop101", false); CPPUNIT_ASSERT(infos.empty()); infos = service->GetInfo("prop101", true); CPPUNIT_ASSERT(infos.size() == 1); CPPUNIT_ASSERT_MESSAGE("Check Name of expected element 1.", infos.front()->GetName() == "prop101"); CPPUNIT_ASSERT_MESSAGE("Check Key of expected element 1.", infos.front()->GetKey() == "key.101"); CPPUNIT_ASSERT_MESSAGE("Check MimeTypeName of expected element 1.", infos.front()->GetMimeTypeName() == "mimeX"); } void GetInfoByKey() { mitk::PropertyPersistence::InfoResultType infos = service->GetInfoByKey("key2", false); CPPUNIT_ASSERT(infos.size() == 2); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info2)); CPPUNIT_ASSERT_MESSAGE("Check expected element 2.", checkExistance(infos, info4)); infos = service->GetInfoByKey("key5", false); CPPUNIT_ASSERT(infos.size() == 1); CPPUNIT_ASSERT_MESSAGE("Check expected element 1.", checkExistance(infos, info5)); infos = service->GetInfoByKey("unkownkey", false); - CPPUNIT_ASSERT_MESSAGE("Check size of result for unkown key.", infos.empty()); + CPPUNIT_ASSERT_MESSAGE("Check size of result for unknown key.", infos.empty()); infos = service->GetInfoByKey("key101", false); CPPUNIT_ASSERT_MESSAGE("Check size of result for key101.", infos.empty()); infos = service->GetInfoByKey("key101", true); CPPUNIT_ASSERT(infos.size() == 1); CPPUNIT_ASSERT_MESSAGE("Check Name of expected element 1.", infos.front()->GetName() == "prop101"); CPPUNIT_ASSERT_MESSAGE("Check Key of expected element 1.", infos.front()->GetKey() == "key101"); CPPUNIT_ASSERT_MESSAGE("Check MimeTypeName of expected element 1.", infos.front()->GetMimeTypeName() == "mimeX"); } void GetInfo_mime() { mitk::PropertyPersistence::InfoResultType infos = service->GetInfo(prop1, "mime2", false, false); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing element, no wildcard allowed, wildcard exists).", infosAreEqual(info2, infos.front())); infos = service->GetInfo(prop1, "mime2", true, false); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing element, wildcard allowed, wildcard exists).", infosAreEqual(info2, infos.front())); infos = service->GetInfo(prop1, "unknownmime", false, false); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, no wildcard allowed, wildcard exists).", infos.empty()); infos = service->GetInfo(prop1, "unknownmime", true, false); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, wildcard allowed, wildcard exists).", infosAreEqual(info1, infos.front())); infos = service->GetInfo(prop4, "unknownmime", false, false); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, no wildcard allowed).", infos.empty()); infos = service->GetInfo(prop4, "unknownmime", true, false); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting element, wildcard allowed).", infos.empty()); infos = service->GetInfo("prop101", "unknownmime", false, true); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, regex allowed).", infos.empty()); infos = service->GetInfo("prop101", "mimeX", false, true); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (existing mime, no wildcard allowed, regex allowed).", infos.size() == 1); infos = service->GetInfo("otherprop", "unknownmime", false, false); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, no regex allowed).", infos.empty()); infos = service->GetInfo("otherprop", "unknownmime", true, false); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, wildcard allowed, no regex allowed).", infos.empty()); infos = service->GetInfo("otherprop", "unknownmime", false, true); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, no wildcard allowed, regex allowed).", infos.empty()); infos = service->GetInfo("otherprop", "unknownmime", true, true); CPPUNIT_ASSERT_MESSAGE("Check GetInfos (inexisting mime, wildcard allowed, regex allowed).", infos.size() == 1); } void HasInfo() { CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", service->HasInfo(prop1)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfo(prop4)); - CPPUNIT_ASSERT_MESSAGE("Check HasInfos (unkown prop)", !service->HasInfo("unkownProp")); + CPPUNIT_ASSERT_MESSAGE("Check HasInfos (unknown prop)", !service->HasInfo("unkownProp")); } void RemoveAllInfo() { CPPUNIT_ASSERT_NO_THROW(service->RemoveAllInfo()); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfo(prop1)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfo(prop4)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfo(prop5)); } void RemoveInfo() { CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop1)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop1)", !service->HasInfo(prop1, false)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", service->HasInfo(prop4, false)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfo(prop5, false)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop4)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop4)", !service->HasInfo(prop4, false)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", service->HasInfo(prop5, false)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5)); CPPUNIT_ASSERT_MESSAGE("Check HasInfos (prop5)", !service->HasInfo(prop5, false)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo("unknown_prop")); } void RemoveInfo_withMime() { CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop1, "mime2")); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos if info was removed", service->GetInfo(prop1, "mime2", false).empty()); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of same property name still exists", !service->GetInfo(prop1, "mime3", false).empty()); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if other info of other property name but same mime still exists", !service->GetInfo(prop4, "mime2", false).empty()); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5, "wrongMime")); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5 with wrong mime", service->HasInfo(prop5, false)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo(prop5, "mime5")); CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos on prop 5", !service->HasInfo(prop5, false)); CPPUNIT_ASSERT_NO_THROW(service->RemoveInfo("unkown_prop", "mime2")); - CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if unkown property name but exting mime was used", + CPPUNIT_ASSERT_MESSAGE("Check RemoveInfos, if unknown property name but existing mime was used", service->HasInfo(prop4, false)); } }; MITK_TEST_SUITE_REGISTRATION(mitkPropertyPersistence) diff --git a/Modules/Core/test/mitkPropertyRelationRuleBaseTest.cpp b/Modules/Core/test/mitkPropertyRelationRuleBaseTest.cpp index a4cd0f314c..f52b5a0166 100644 --- a/Modules/Core/test/mitkPropertyRelationRuleBaseTest.cpp +++ b/Modules/Core/test/mitkPropertyRelationRuleBaseTest.cpp @@ -1,1146 +1,1146 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkPropertyRelationRuleBase.h" #include "mitkDataNode.h" #include "mitkPointSet.h" #include "mitkStringProperty.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include /** This class is used to test PropertyRelationRuleBase and get access to internals where needed to test them as well. */ namespace mitk { class TestRule : public mitk::PropertyRelationRuleBase { public: mitkClassMacro(TestRule, mitk::PropertyRelationRuleBase); itkFactorylessNewMacro(Self); itkCloneMacro(Self); using RuleIDType = PropertyRelationRuleBase::RuleIDType; using RelationUIDType = PropertyRelationRuleBase::RelationUIDType; using RelationUIDVectorType = PropertyRelationRuleBase::RelationUIDVectorType; RuleIDType GetRuleID() const override { if (m_AbstractMode) { return "TestRule"; } else { return "TestRule_type1"; } }; std::string GetDisplayName() const override { return "TestDisplayName"; } std::string GetSourceRoleName() const override { return "source role"; } std::string GetDestinationRoleName() const override { return "destination role"; } bool m_AbstractMode; bool IsAbstract() const override { return m_AbstractMode; } using Superclass::GetRootKeyPath; using Superclass::Connect; protected: TestRule() : m_AbstractMode(false) { }; ~TestRule() override = default; using InstanceIDType = PropertyRelationRuleBase::InstanceIDType; using InstanceIDVectorType = PropertyRelationRuleBase::InstanceIDVectorType; bool IsSupportedRuleID(const RuleIDType& ruleID) const override { if (m_AbstractMode) { return ruleID.find(this->GetRuleID()) == 0; } else { return Superclass::IsSupportedRuleID(ruleID); } }; DataRelationUIDVectorType GetRelationUIDs_DataLayer(const IPropertyProvider* source, const IPropertyProvider* destination, const InstanceIDVectorType& instances_IDLayer) const override { DataRelationUIDVectorType result; mitk::BaseProperty::ConstPointer destProp; if (destination != nullptr) { destProp = destination->GetConstProperty("name"); } if (destProp.IsNotNull()) { auto destRegExStr = PropertyKeyPathToPropertyRegEx(Superclass::GetRootKeyPath().AddAnyElement().AddElement("dataHandle")); auto regEx = std::regex(destRegExStr); std::smatch instance_matches; auto keys = source->GetPropertyKeys(); for (const auto &key : keys) { if (std::regex_search(key, instance_matches, regEx)) { auto sourceProp = source->GetConstProperty(key); if (sourceProp->GetValueAsString() == destProp->GetValueAsString()) { if (instance_matches.size()>1) { auto finding = std::find(instances_IDLayer.begin(), instances_IDLayer.end(), instance_matches[1]); if (finding == instances_IDLayer.end()) { result.emplace_back(this->GetRelationUIDByInstanceID(source, instance_matches[1]), this->GetRuleIDByInstanceID(source, instance_matches[1])); } } } } } } if (result.empty() && instances_IDLayer.empty()) { auto refNameProp = source->GetConstProperty("referencedName"); if (refNameProp.IsNotNull() && (destProp.IsNull() || destProp->GetValueAsString() == refNameProp->GetValueAsString())) { result.emplace_back(refNameProp->GetValueAsString(),""); } } return result; }; void Connect_datalayer(IPropertyOwner *source, const IPropertyProvider *destination, const InstanceIDType &instanceID) const override { auto destProp = destination->GetConstProperty("name"); source->SetProperty("referencedName", StringProperty::New(destProp->GetValueAsString())); source->SetProperty( PropertyKeyPathToPropertyName(Superclass::GetRootKeyPath().AddElement(instanceID).AddElement("dataHandle")), StringProperty::New(destProp->GetValueAsString())); }; void Disconnect_datalayer(IPropertyOwner *source, const RelationUIDType & relationUID) const override { source->RemoveProperty("referencedName"); try { auto instanceID = this->GetInstanceIDByRelationUID(source, relationUID); source->RemoveProperty( PropertyKeyPathToPropertyName(Superclass::GetRootKeyPath().AddElement(instanceID).AddElement("dataHandle"))); } catch(...) { } }; }; } // namespace mitk class mitkPropertyRelationRuleBaseTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPropertyRelationRuleBaseTestSuite); MITK_TEST(GetRootKeyPath); MITK_TEST(IsSourceCandidate); MITK_TEST(IsDestinationCandidate); MITK_TEST(IsSource); MITK_TEST(HasRelation); MITK_TEST(GetExistingRelations); MITK_TEST(GetRelationUIDs); MITK_TEST(GetSourceCandidateIndicator); MITK_TEST(GetDestinationCandidateIndicator); MITK_TEST(GetConnectedSourcesDetector); MITK_TEST(GetSourcesDetector); MITK_TEST(GetDestinationsDetector); MITK_TEST(GetDestinationDetector); MITK_TEST(Connect); MITK_TEST(Disconnect); MITK_TEST(Disconnect_partial_ID); MITK_TEST(Disconnect_partial_Data); MITK_TEST(Connect_abstract); MITK_TEST(Disconnect_abstract); MITK_TEST(GetRIIPropertyKeyPath); CPPUNIT_TEST_SUITE_END(); private: mitk::TestRule::Pointer rule; mitk::TestRule::Pointer abstractRule; mitk::DataNode::Pointer unRelated; mitk::PointSet::Pointer unRelated_1_data; mitk::DataNode::Pointer source_implicit_1; mitk::DataNode::Pointer source_data_1; mitk::DataNode::Pointer source_idOnly_1; mitk::DataNode::Pointer source_1; mitk::DataNode::Pointer source_multi; mitk::DataNode::Pointer source_otherRule; mitk::DataNode::Pointer source_otherTypeRule; //relevant for abstract rule checks. Abstract rule should see it concrete rule not. mitk::DataNode::Pointer dest_1; mitk::PointSet::Pointer dest_1_data; mitk::DataNode::Pointer dest_2; mitk::PointSet::Pointer dest_2_data; bool hasRelationProperties(mitk::IPropertyProvider *provider, std::string instance = "") const { auto keyPath = mitk::PropertyRelationRuleBase::GetRootKeyPath(); if (!instance.empty()) { keyPath.AddElement(instance); } auto prefix = mitk::PropertyKeyPathToPropertyName(keyPath); auto keys = provider->GetPropertyKeys(); for (const auto &key : keys) { if (key.find(prefix) == 0) { return true; } } return false; } public: void setUp() override { rule = mitk::TestRule::New(); abstractRule = mitk::TestRule::New(); abstractRule->m_AbstractMode = true; unRelated = mitk::DataNode::New(); unRelated->SetName("unRelated"); unRelated_1_data = mitk::PointSet::New(); unRelated->SetData(unRelated_1_data); dest_1 = mitk::DataNode::New(); dest_1->SetName("dest_1"); dest_1_data = mitk::PointSet::New(); dest_1->SetData(dest_1_data); dest_2 = mitk::DataNode::New(); dest_2->SetName("dest_2"); dest_2_data = mitk::PointSet::New(); dest_2->SetData(dest_2_data); source_implicit_1 = mitk::DataNode::New(); source_implicit_1->AddProperty("referencedName", mitk::StringProperty::New(dest_1->GetName())); source_idOnly_1 = mitk::DataNode::New(); std::string name = "MITK.Relations.1.relationUID"; source_idOnly_1->AddProperty(name.c_str(), mitk::StringProperty::New("uid1")); name = "MITK.Relations.1.destinationUID"; source_idOnly_1->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1_data->GetUID())); name = "MITK.Relations.1.ruleID"; source_idOnly_1->AddProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); source_data_1 = mitk::DataNode::New(); source_data_1->AddProperty("referencedName", mitk::StringProperty::New(dest_1->GetName())); name = "MITK.Relations.1.relationUID"; source_data_1->AddProperty(name.c_str(), mitk::StringProperty::New("uid2")); name = "MITK.Relations.1.dataHandle"; source_data_1->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1->GetName())); name = "MITK.Relations.1.ruleID"; source_data_1->AddProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); name = "MITK.Relations.2.relationUID"; source_data_1->AddProperty(name.c_str(), mitk::StringProperty::New("uid10"), nullptr, true); name = "MITK.Relations.2.destinationUID"; source_data_1->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1_data->GetUID())); name = "MITK.Relations.2.ruleID"; source_data_1->AddProperty(name.c_str(), mitk::StringProperty::New("TestRule_othertype")); source_1 = mitk::DataNode::New(); source_1->AddProperty("referencedName", mitk::StringProperty::New(dest_1->GetName())); name = "MITK.Relations.1.relationUID"; source_1->AddProperty(name.c_str(), mitk::StringProperty::New("uid3"), nullptr, true); name = "MITK.Relations.1.destinationUID"; source_1->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1_data->GetUID())); name = "MITK.Relations.1.dataHandle"; source_1->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1->GetName())); name = "MITK.Relations.1.ruleID"; source_1->AddProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); name = "MITK.Relations.2.relationUID"; source_1->AddProperty(name.c_str(), mitk::StringProperty::New("uid8"), nullptr, true); name = "MITK.Relations.2.destinationUID"; source_1->AddProperty(name.c_str(), mitk::StringProperty::New(dest_2_data->GetUID())); name = "MITK.Relations.2.ruleID"; source_1->AddProperty(name.c_str(), mitk::StringProperty::New("TestRule_othertype")); source_multi = mitk::DataNode::New(); source_multi->AddProperty("referencedName", mitk::StringProperty::New(dest_1->GetName())); name = "MITK.Relations.1.relationUID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New("uid4"), nullptr, true); name = "MITK.Relations.1.destinationUID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1_data->GetUID())); name = "MITK.Relations.1.ruleID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); name = "MITK.Relations.1.dataHandle"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1->GetName())); name = "MITK.Relations.4.relationUID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New("uid5")); name = "MITK.Relations.4.destinationUID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New(dest_2_data->GetUID())); name = "MITK.Relations.4.ruleID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); name = "MITK.Relations.2.relationUID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New("uid6")); name = "MITK.Relations.2.destinationUID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New("unknown")); name = "MITK.Relations.2.ruleID"; source_multi->AddProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); source_otherRule = mitk::DataNode::New(); name = "MITK.Relations.1.relationUID"; source_otherRule->AddProperty(name.c_str(), mitk::StringProperty::New("uid7")); name = "MITK.Relations.1.destinationUID"; source_otherRule->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1_data->GetUID())); name = "MITK.Relations.1.ruleID"; source_otherRule->AddProperty(name.c_str(), mitk::StringProperty::New("otherRuleID")); source_otherTypeRule = mitk::DataNode::New(); name = "MITK.Relations.1.relationUID"; source_otherTypeRule->AddProperty(name.c_str(), mitk::StringProperty::New("uid9")); name = "MITK.Relations.1.destinationUID"; source_otherTypeRule->AddProperty(name.c_str(), mitk::StringProperty::New(dest_1_data->GetUID())); name = "MITK.Relations.1.ruleID"; source_otherTypeRule->AddProperty(name.c_str(), mitk::StringProperty::New("TestRule_othertype")); } void tearDown() override {} void GetRootKeyPath() { mitk::PropertyKeyPath ref; ref.AddElement("MITK").AddElement("Relations"); CPPUNIT_ASSERT(mitk::PropertyRelationRuleBase::GetRootKeyPath() == ref); } void IsSourceCandidate() { CPPUNIT_ASSERT(rule->IsSourceCandidate(mitk::DataNode::New())); CPPUNIT_ASSERT(!rule->IsSourceCandidate(nullptr)); } void IsDestinationCandidate() { CPPUNIT_ASSERT(rule->IsDestinationCandidate(mitk::DataNode::New())); CPPUNIT_ASSERT(!rule->IsDestinationCandidate(nullptr)); } void IsSource() { CPPUNIT_ASSERT_THROW_MESSAGE( "Violated precondition (nullptr) does not throw.", rule->IsSource(nullptr), itk::ExceptionObject); CPPUNIT_ASSERT(!rule->IsSource(unRelated)); CPPUNIT_ASSERT(rule->IsSource(source_implicit_1)); CPPUNIT_ASSERT(rule->IsSource(source_data_1)); CPPUNIT_ASSERT(rule->IsSource(source_idOnly_1)); CPPUNIT_ASSERT(rule->IsSource(source_1)); CPPUNIT_ASSERT(rule->IsSource(source_multi)); CPPUNIT_ASSERT(!rule->IsSource(source_otherRule)); CPPUNIT_ASSERT(!rule->IsSource(source_otherTypeRule)); CPPUNIT_ASSERT(!abstractRule->IsSource(unRelated)); CPPUNIT_ASSERT(abstractRule->IsSource(source_implicit_1)); CPPUNIT_ASSERT(abstractRule->IsSource(source_data_1)); CPPUNIT_ASSERT(abstractRule->IsSource(source_idOnly_1)); CPPUNIT_ASSERT(abstractRule->IsSource(source_1)); CPPUNIT_ASSERT(abstractRule->IsSource(source_multi)); CPPUNIT_ASSERT(!abstractRule->IsSource(source_otherRule)); CPPUNIT_ASSERT(abstractRule->IsSource(source_otherTypeRule)); } void HasRelation() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->HasRelation(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->HasRelation(source_1, nullptr), itk::ExceptionObject); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated)); CPPUNIT_ASSERT(!rule->HasRelation(unRelated, dest_1)); CPPUNIT_ASSERT(!rule->HasRelation(source_otherRule, dest_1)); CPPUNIT_ASSERT(!rule->HasRelation(source_otherTypeRule, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_implicit_1, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(rule->HasRelation(source_data_1, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!rule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!rule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(rule->HasRelation(source_idOnly_1, dest_1)); CPPUNIT_ASSERT(!rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(!rule->HasRelation(source_1, dest_2)); CPPUNIT_ASSERT(!rule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!rule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!rule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(rule->HasRelation(source_multi, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(rule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(rule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(rule->HasRelation(source_multi, dest_2)); CPPUNIT_ASSERT(!rule->HasRelation(source_multi, dest_2, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(rule->HasRelation(source_multi, dest_2, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!rule->HasRelation(source_multi, dest_2, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_1, unRelated)); CPPUNIT_ASSERT(!abstractRule->HasRelation(unRelated, dest_1)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_otherRule, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_otherTypeRule, dest_1)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_otherTypeRule, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_otherTypeRule, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_otherTypeRule, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_implicit_1, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_data_1, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_idOnly_1, dest_1)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_2)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_multi, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_multi, dest_2)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_multi, dest_2, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_multi, dest_2, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_multi, dest_2, mitk::PropertyRelationRuleBase::RelationType::Complete)); } void GetExistingRelations() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->GetExistingRelations(nullptr), itk::ExceptionObject); CPPUNIT_ASSERT(rule->GetExistingRelations(unRelated).empty()); CPPUNIT_ASSERT(rule->GetExistingRelations(source_otherRule).empty()); CPPUNIT_ASSERT(rule->GetExistingRelations(source_otherTypeRule).empty()); auto uids = rule->GetExistingRelations(source_implicit_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == dest_1->GetName()); uids = rule->GetExistingRelations(source_idOnly_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid1"); uids = rule->GetExistingRelations(source_data_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid2"); uids = rule->GetExistingRelations(source_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid3"); uids = rule->GetExistingRelations(source_multi); CPPUNIT_ASSERT(uids.size() == 3); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid4") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid5") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid6") != uids.end()); CPPUNIT_ASSERT(abstractRule->GetExistingRelations(unRelated).empty()); CPPUNIT_ASSERT(abstractRule->GetExistingRelations(source_otherRule).empty()); uids = abstractRule->GetExistingRelations(source_implicit_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == dest_1->GetName()); uids = abstractRule->GetExistingRelations(source_idOnly_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid1"); uids = abstractRule->GetExistingRelations(source_data_1); CPPUNIT_ASSERT(uids.size() == 2); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid2") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid10") != uids.end()); uids = abstractRule->GetExistingRelations(source_1); CPPUNIT_ASSERT(uids.size() == 2); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid3") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid8") != uids.end()); uids = abstractRule->GetExistingRelations(source_multi); CPPUNIT_ASSERT(uids.size() == 3); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid4") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid5") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid6") != uids.end()); uids = abstractRule->GetExistingRelations(source_otherTypeRule); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid9"); } void GetRelationUIDs() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->GetRelationUIDs(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->GetRelationUIDs(source_1, nullptr), itk::ExceptionObject); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_1, unRelated).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_1, dest_2).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(unRelated, dest_1).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_otherRule, dest_1).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_otherTypeRule, dest_1).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_idOnly_1, dest_1).front() == "uid1"); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_data_1, dest_1).front() == "uid2"); auto uids = rule->GetRelationUIDs(source_1, dest_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid3"); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_multi, dest_1).front() == "uid4"); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_multi, dest_2).front() == "uid5"); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_1, unRelated).empty()); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(unRelated, dest_1).empty()); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_otherRule, dest_1).empty()); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_otherTypeRule, dest_1).front() == "uid9"); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_idOnly_1, dest_1).front() == "uid1"); uids = abstractRule->GetRelationUIDs(source_data_1, dest_1); CPPUNIT_ASSERT(uids.size() == 2); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid2") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid10") != uids.end()); uids = abstractRule->GetRelationUIDs(source_1, dest_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid3") != uids.end()); uids = abstractRule->GetRelationUIDs(source_1, dest_2); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid8") != uids.end()); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_1, dest_1).front() == "uid3"); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_multi, dest_1).front() == "uid4"); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_multi, dest_2).front() == "uid5"); } void GetSourceCandidateIndicator() { auto predicate = rule->GetSourceCandidateIndicator(); CPPUNIT_ASSERT(predicate->CheckNode(mitk::DataNode::New())); CPPUNIT_ASSERT(!predicate->CheckNode(nullptr)); } void GetDestinationCandidateIndicator() { auto predicate = rule->GetDestinationCandidateIndicator(); CPPUNIT_ASSERT(predicate->CheckNode(mitk::DataNode::New())); CPPUNIT_ASSERT(!predicate->CheckNode(nullptr)); } void GetConnectedSourcesDetector() { auto predicate = rule->GetConnectedSourcesDetector(); CPPUNIT_ASSERT(!predicate->CheckNode(nullptr)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherTypeRule)); auto predicate2 = abstractRule->GetConnectedSourcesDetector(); CPPUNIT_ASSERT(!predicate2->CheckNode(nullptr)); CPPUNIT_ASSERT(!predicate2->CheckNode(unRelated)); CPPUNIT_ASSERT(predicate2->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(predicate2->CheckNode(source_data_1)); CPPUNIT_ASSERT(predicate2->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate2->CheckNode(source_1)); CPPUNIT_ASSERT(predicate2->CheckNode(source_multi)); CPPUNIT_ASSERT(!predicate2->CheckNode(source_otherRule)); CPPUNIT_ASSERT(predicate2->CheckNode(source_otherTypeRule)); } void GetSourcesDetector() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->GetSourcesDetector(nullptr), itk::ExceptionObject); auto predicate = rule->GetSourcesDetector(dest_1); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); predicate = rule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); predicate = rule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); predicate = rule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); predicate = rule->GetSourcesDetector(dest_2); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); predicate = abstractRule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); predicate = abstractRule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); predicate = abstractRule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(!predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); predicate = abstractRule->GetSourcesDetector(dest_1); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule)); CPPUNIT_ASSERT(predicate->CheckNode(source_otherTypeRule)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_data_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_1)); CPPUNIT_ASSERT(predicate->CheckNode(source_multi)); } void GetDestinationsDetector() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->GetDestinationsDetector(nullptr), itk::ExceptionObject); auto predicate = rule->GetDestinationsDetector(source_otherRule); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_otherTypeRule); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_implicit_1); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_implicit_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_implicit_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_implicit_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_data_1); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_data_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_data_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_data_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_idOnly_1); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_idOnly_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_idOnly_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_idOnly_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); predicate = rule->GetDestinationsDetector(source_1); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2)); predicate = rule->GetDestinationsDetector(source_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2)); predicate = rule->GetDestinationsDetector(source_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2)); predicate = rule->GetDestinationsDetector(source_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2)); predicate = rule->GetDestinationsDetector(source_multi); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(predicate->CheckNode(dest_2)); predicate = rule->GetDestinationsDetector(source_multi, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2)); predicate = rule->GetDestinationsDetector(source_multi, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(predicate->CheckNode(dest_2)); predicate = rule->GetDestinationsDetector(source_multi, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2)); predicate = abstractRule->GetDestinationsDetector(source_otherTypeRule); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); predicate = abstractRule->GetDestinationsDetector(source_otherTypeRule); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); } void GetDestinationDetector() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->GetDestinationDetector(nullptr, "uid1"), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (relation uid is invalid) does not throw.", rule->GetDestinationDetector(source_1, "invalid uid"), itk::ExceptionObject); auto predicate = rule->GetDestinationDetector(source_1, "uid3"); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2)); predicate = rule->GetDestinationDetector(source_multi, "uid5"); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1)); CPPUNIT_ASSERT(predicate->CheckNode(dest_2)); } void Connect() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->Connect(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Connect(source_1, nullptr), itk::ExceptionObject); // check upgrade of an implicit connection CPPUNIT_ASSERT(!rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); rule->Connect(source_implicit_1, dest_1); CPPUNIT_ASSERT(rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); // check upgrade of an data connection CPPUNIT_ASSERT(!rule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); rule->Connect(source_data_1, dest_1); CPPUNIT_ASSERT(rule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); std::string name = "MITK.Relations.1.destinationUID"; auto prop = source_data_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE( "Destination uid was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == dest_1_data->GetUID()); // check actualization of an id only connection CPPUNIT_ASSERT(!rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); rule->Connect(source_idOnly_1, dest_1); CPPUNIT_ASSERT(rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); - CPPUNIT_ASSERT_MESSAGE("Additional relation was defined instead of updating exting one.", + CPPUNIT_ASSERT_MESSAGE("Additional relation was defined instead of updating existing one.", rule->GetExistingRelations(source_1).size() == 1); name = "MITK.Relations.1.dataHandle"; prop = source_idOnly_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE( "Data layer information was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect data layer information not stored.", prop->GetValueAsString() == dest_1->GetName()); prop = source_idOnly_1->GetProperty("referencedName"); CPPUNIT_ASSERT_MESSAGE( "Data layer information was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect data layer information was stored.", prop->GetValueAsString() == dest_1->GetName()); // check actualization of an existing connection rule->Connect(source_1, dest_1); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); - CPPUNIT_ASSERT_MESSAGE("Additional relation was defined instead of updating exting one.", + CPPUNIT_ASSERT_MESSAGE("Additional relation was defined instead of updating existing one.", rule->GetExistingRelations(source_1).size() == 1); // check new connection auto newConnectUID = rule->Connect(source_multi, unRelated); CPPUNIT_ASSERT(rule->HasRelation(source_multi, unRelated, mitk::PropertyRelationRuleBase::RelationType::Complete)); name = "MITK.Relations.5.dataHandle"; prop = source_multi->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE( "Data layer information was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect data layer information was stored.", prop->GetValueAsString() == unRelated->GetName()); prop = source_multi->GetProperty("referencedName"); CPPUNIT_ASSERT_MESSAGE( "Data layer information was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect data layer information was stored.", prop->GetValueAsString() == unRelated->GetName()); name = "MITK.Relations.5.destinationUID"; prop = source_multi->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE( "Destination uid was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == unRelated_1_data->GetUID()); auto storedRelationUIDs = rule->GetRelationUIDs(source_multi, unRelated); CPPUNIT_ASSERT_MESSAGE( "Relation uid was not stored for given source and destination.", storedRelationUIDs.size() == 1); CPPUNIT_ASSERT_MESSAGE("Incorrect Relation uid was stored.", storedRelationUIDs[0] == newConnectUID); } void Disconnect() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->Disconnect(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Disconnect(source_1, nullptr), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Disconnect(nullptr, "uid"), itk::ExceptionObject); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); rule->Disconnect(source_1, unRelated); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT_MESSAGE("Data property was illegaly removed.", source_1->GetProperty("referencedName")); rule->Disconnect(source_1, dest_2); CPPUNIT_ASSERT(!rule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(this->hasRelationProperties(source_1)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); rule->Disconnect(source_1, dest_1); CPPUNIT_ASSERT(!rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!this->hasRelationProperties(source_1, "1")); CPPUNIT_ASSERT_MESSAGE("Data of other rule type was removed.",this->hasRelationProperties(source_1, "2")); CPPUNIT_ASSERT(rule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); rule->Disconnect(source_multi, dest_1); CPPUNIT_ASSERT(!rule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "1")); CPPUNIT_ASSERT(this->hasRelationProperties(source_multi, "2")); CPPUNIT_ASSERT(this->hasRelationProperties(source_multi, "4")); rule->Disconnect(source_multi, "uid6"); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "1")); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "2")); CPPUNIT_ASSERT(this->hasRelationProperties(source_multi, "4")); rule->Disconnect(source_multi, "unkownRelationUID"); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "1")); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "2")); CPPUNIT_ASSERT(this->hasRelationProperties(source_multi, "4")); rule->Disconnect(source_otherTypeRule, dest_1); CPPUNIT_ASSERT_MESSAGE("Data of other rule type was removed.", this->hasRelationProperties(source_otherTypeRule, "1")); } void Disconnect_partial_ID() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->Disconnect(nullptr, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Disconnect(source_1, nullptr, mitk::PropertyRelationRuleBase::RelationType::ID), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Disconnect(nullptr, "uid", mitk::PropertyRelationRuleBase::RelationType::ID), itk::ExceptionObject); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); rule->Disconnect(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT_MESSAGE("Data property was illegaly removed.", source_1->GetProperty("referencedName")); rule->Disconnect(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); rule->Disconnect(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(rule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); rule->Disconnect(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!this->hasRelationProperties(source_1, "1")); CPPUNIT_ASSERT_MESSAGE("Data of other rule type was removed.", this->hasRelationProperties(source_1, "2")); } void Disconnect_partial_Data() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->Disconnect(nullptr, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Disconnect(source_1, nullptr, mitk::PropertyRelationRuleBase::RelationType::Data), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Disconnect(nullptr, "uid", mitk::PropertyRelationRuleBase::RelationType::Data), itk::ExceptionObject); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); rule->Disconnect(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT_MESSAGE("Data property was illegaly removed.", source_1->GetProperty("referencedName")); rule->Disconnect(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); rule->Disconnect(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(!rule->HasRelation(source_data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); rule->Disconnect(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); } void Connect_abstract() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (abstract does not connect) does not throw.", abstractRule->Connect(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (abstract does not connect) does not throw.", abstractRule->Connect(source_1, nullptr), itk::ExceptionObject); } void Disconnect_abstract() { CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::ID)); abstractRule->Disconnect(source_1, dest_2); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!this->hasRelationProperties(source_1, "2")); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); abstractRule->Disconnect(source_1, dest_1); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!this->hasRelationProperties(source_1, "1")); CPPUNIT_ASSERT(abstractRule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); abstractRule->Disconnect(source_multi, dest_1); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_multi, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "1")); CPPUNIT_ASSERT(this->hasRelationProperties(source_multi, "2")); CPPUNIT_ASSERT(this->hasRelationProperties(source_multi, "4")); abstractRule->Disconnect(source_multi, "uid6"); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "1")); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "2")); CPPUNIT_ASSERT(this->hasRelationProperties(source_multi, "4")); abstractRule->Disconnect(source_multi, "unkownRelationUID"); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "1")); CPPUNIT_ASSERT(!this->hasRelationProperties(source_multi, "2")); CPPUNIT_ASSERT(this->hasRelationProperties(source_multi, "4")); abstractRule->Disconnect(source_otherTypeRule, dest_1); CPPUNIT_ASSERT_MESSAGE("Data of other rule type was removed.", !this->hasRelationProperties(source_otherTypeRule, "1")); } void GetRIIPropertyKeyPath() { auto path = mitk::PropertyRelationRuleBase::GetRootKeyPath(); mitk::PropertyKeyPath referencePath({ "MITK", "Relations" }); CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIPropertyKeyPath("a","1"); referencePath = { "MITK", "Relations", "1", "a" }; CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIPropertyKeyPath("", "1"); referencePath = { "MITK", "Relations", "1"}; CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIPropertyKeyPath("a", ""); referencePath = mitk::PropertyRelationRuleBase::GetRootKeyPath().AddAnyElement().AddElement("a"); CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIRelationUIDPropertyKeyPath(); referencePath = mitk::PropertyRelationRuleBase::GetRootKeyPath().AddAnyElement().AddElement("relationUID"); CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIRelationUIDPropertyKeyPath("1"); referencePath = { "MITK", "Relations", "1", "relationUID" }; CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIRuleIDPropertyKeyPath(); referencePath = mitk::PropertyRelationRuleBase::GetRootKeyPath().AddAnyElement().AddElement("ruleID"); CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIRuleIDPropertyKeyPath("1"); referencePath = { "MITK", "Relations", "1", "ruleID" }; CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIDestinationUIDPropertyKeyPath(); referencePath = mitk::PropertyRelationRuleBase::GetRootKeyPath().AddAnyElement().AddElement("destinationUID"); CPPUNIT_ASSERT(referencePath == path); path = mitk::PropertyRelationRuleBase::GetRIIDestinationUIDPropertyKeyPath("1"); referencePath = { "MITK", "Relations", "1", "destinationUID" }; CPPUNIT_ASSERT(referencePath == path); } }; MITK_TEST_SUITE_REGISTRATION(mitkPropertyRelationRuleBase) diff --git a/Modules/Core/test/mitkRawImageFileReaderTest.cpp b/Modules/Core/test/mitkRawImageFileReaderTest.cpp index 018481299f..845d05e7d9 100644 --- a/Modules/Core/test/mitkRawImageFileReaderTest.cpp +++ b/Modules/Core/test/mitkRawImageFileReaderTest.cpp @@ -1,62 +1,62 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkIOConstants.h" #include "mitkIOUtil.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" class mitkRawImageFileReaderTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkRawImageFileReaderTestSuite); MITK_TEST(testReadFile); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different test methods. All members are initialized via setUp().*/ std::string m_ImagePath; - std::string m_ImagePathNrrdRef; // corresponding mhd path for comparision + std::string m_ImagePathNrrdRef; // corresponding mhd path for comparison public: /** - * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used + * @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used * members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_ImagePath = GetTestDataFilePath("brain.raw"); m_ImagePathNrrdRef = GetTestDataFilePath("brainHalfSize.nrrd"); // we need half size because the brain file has // spacing 2 and this reader doesn't support spacing } void tearDown() override {} void testReadFile() { mitk::IFileReader::Options options; options[mitk::IOConstants::DIMENSION()] = 3; options[mitk::IOConstants::PIXEL_TYPE()] = mitk::IOConstants::PIXEL_TYPE_FLOAT(); options[mitk::IOConstants::SIZE_X()] = 91; options[mitk::IOConstants::SIZE_Y()] = 109; options[mitk::IOConstants::SIZE_Z()] = 91; options[mitk::IOConstants::ENDIANNESS()] = mitk::IOConstants::ENDIANNESS_LITTLE(); mitk::Image::Pointer readFile = mitk::IOUtil::Load(m_ImagePath, options); CPPUNIT_ASSERT_MESSAGE("Testing reading a raw file.", readFile.IsNotNull()); // compare with the reference image mitk::Image::Pointer compareImage = mitk::IOUtil::Load(m_ImagePathNrrdRef); MITK_ASSERT_EQUAL( compareImage, readFile, "Testing if image is equal to the same image as reference file loaded with mitk"); } }; MITK_TEST_SUITE_REGISTRATION(mitkRawImageFileReader) diff --git a/Modules/Core/test/mitkSTLFileReaderTest.cpp b/Modules/Core/test/mitkSTLFileReaderTest.cpp index aa2823ea1a..de2a938607 100644 --- a/Modules/Core/test/mitkSTLFileReaderTest.cpp +++ b/Modules/Core/test/mitkSTLFileReaderTest.cpp @@ -1,65 +1,65 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkIOUtil.h" #include "mitkImage.h" #include "mitkSlicedGeometry3D.h" #include "mitkSurface.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include #include #include #include class mitkSTLFileReaderTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkSTLFileReaderTestSuite); MITK_TEST(testReadFile); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different test methods. All members are initialized via setUp().*/ std::string m_SurfacePath; public: /** - * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used + * @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used * members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_SurfacePath = GetTestDataFilePath("ball.stl"); } void tearDown() override {} void testReadFile() { // Read STL-Image from file mitk::Surface::Pointer surface = mitk::IOUtil::Load(m_SurfacePath); // check some basic stuff CPPUNIT_ASSERT_MESSAGE("Reader output not nullptr", surface.IsNotNull()); CPPUNIT_ASSERT_MESSAGE("IsInitialized()", surface->IsInitialized()); CPPUNIT_ASSERT_MESSAGE("mitk::Surface::SetVtkPolyData()", (surface->GetVtkPolyData() != nullptr)); CPPUNIT_ASSERT_MESSAGE("Availability of geometry", (surface->GetGeometry() != nullptr)); // use vtk stl reader for reference vtkSmartPointer myVtkSTLReader = vtkSmartPointer::New(); myVtkSTLReader->SetFileName(m_SurfacePath.c_str()); myVtkSTLReader->Update(); vtkSmartPointer myVtkPolyData = myVtkSTLReader->GetOutput(); // vtkPolyData from vtkSTLReader directly int n = myVtkPolyData->GetNumberOfPoints(); // vtkPolyData from mitkSTLFileReader int m = surface->GetVtkPolyData()->GetNumberOfPoints(); CPPUNIT_ASSERT_MESSAGE("Number of Points in VtkPolyData", (n == m)); } }; MITK_TEST_SUITE_REGISTRATION(mitkSTLFileReader) diff --git a/Modules/Core/test/mitkSourceImageRelationRuleTest.cpp b/Modules/Core/test/mitkSourceImageRelationRuleTest.cpp index 71ac772ba4..c0189e6068 100644 --- a/Modules/Core/test/mitkSourceImageRelationRuleTest.cpp +++ b/Modules/Core/test/mitkSourceImageRelationRuleTest.cpp @@ -1,973 +1,973 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkSourceImageRelationRule.h" #include "mitkDataNode.h" #include "mitkPointSet.h" #include "mitkStringProperty.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include "mitkPropertyNameHelper.h" #include "mitkTemporoSpatialStringProperty.h" #include "mitkPropertyNameHelper.h" #include class mitkSourceImageRelationRuleTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkSourceImageRelationRuleTestSuite); MITK_TEST(ConstructionAndGetter); MITK_TEST(IsSourceCandidate); MITK_TEST(IsDestinationCandidate); MITK_TEST(IsSource); MITK_TEST(HasRelation); MITK_TEST(GetExistingRelations); MITK_TEST(GetRelationUIDs); MITK_TEST(GetSourceCandidateIndicator); MITK_TEST(GetDestinationCandidateIndicator); MITK_TEST(GetConnectedSourcesDetector); MITK_TEST(GetSourcesDetector); MITK_TEST(GetDestinationsDetector); MITK_TEST(GetDestinationDetector); MITK_TEST(Connect); MITK_TEST(Disconnect); MITK_TEST(Connect_abstract); MITK_TEST(Disconnect_abstract); CPPUNIT_TEST_SUITE_END(); private: mitk::SourceImageRelationRule::Pointer rule; mitk::SourceImageRelationRule::Pointer abstractRule; mitk::Image::Pointer unRelated; mitk::DataNode::Pointer unRelated_Node; mitk::Image::Pointer source_implicit_1; mitk::DataNode::Pointer source_implicit_1_Node; mitk::Image::Pointer source_Data_1; mitk::DataNode::Pointer source_Data_1_Node; mitk::Image::Pointer source_idOnly_1; mitk::DataNode::Pointer source_idOnly_1_Node; mitk::Image::Pointer source_1; mitk::DataNode::Pointer source_1_Node; mitk::Image::Pointer source_otherRule; mitk::DataNode::Pointer source_otherRule_Node; mitk::Image::Pointer source_otherPurpose; mitk::DataNode::Pointer source_otherPurpose_Node; //relevant for abstract rule checks. Abstract rule should see it concrete rule not. mitk::DataNode::Pointer dest_1_Node; mitk::Image::Pointer dest_1; mitk::DataNode::Pointer dest_2_Node; mitk::Image::Pointer dest_2; bool hasRelationProperties(mitk::IPropertyProvider *provider, std::string instance = "") const { auto keyPath = mitk::PropertyRelationRuleBase::GetRootKeyPath(); if (!instance.empty()) { keyPath.AddElement(instance); } auto prefix = mitk::PropertyKeyPathToPropertyName(keyPath); auto keys = provider->GetPropertyKeys(); for (const auto &key : keys) { if (key.find(prefix) == 0) { return true; } } return false; } std::vector GetReferenceSequenceIndices(const mitk::IPropertyProvider * source, const mitk::IPropertyProvider * destination) const { std::vector result; auto destInstanceUIDProp = destination->GetConstProperty(mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0018)); if (destInstanceUIDProp.IsNull()) { return result; } mitk::PropertyKeyPath referencedInstanceUIDs; referencedInstanceUIDs.AddElement("DICOM").AddElement("0008").AddAnySelection("2112").AddElement("0008").AddElement("1155"); auto sourceRegExStr = PropertyKeyPathToPropertyRegEx(referencedInstanceUIDs);; auto regEx = std::regex(sourceRegExStr); std::vector keys; //workaround until T24729 is done. Please remove if T24728 is done keys = source->GetPropertyKeys(); //end workaround for T24729 for (const auto &key : keys) { if (std::regex_match(key, regEx)) { auto refUIDProp = source->GetConstProperty(key); if (*refUIDProp == *destInstanceUIDProp) { mitk::PropertyKeyPath finding = mitk::PropertyNameToPropertyKeyPath(key); result.push_back(std::to_string(finding.GetNode(2).selection)); } } } return result; }; void SetDICOMReferenceInfo(mitk::IPropertyOwner* owner, const std::string& instanceUID, const std::string& classUID, const std::string& purpose, unsigned int sequElement) { mitk::PropertyKeyPath refInstanceUIDPath; refInstanceUIDPath.AddElement("DICOM").AddElement("0008").AddSelection("2112", sequElement).AddElement("0008").AddElement("1155"); owner->SetProperty(PropertyKeyPathToPropertyName(refInstanceUIDPath), mitk::TemporoSpatialStringProperty::New(instanceUID)); mitk::PropertyKeyPath refClassUIDPath; refClassUIDPath.AddElement("DICOM").AddElement("0008").AddSelection("2112", sequElement).AddElement("0008").AddElement("1150"); owner->SetProperty(PropertyKeyPathToPropertyName(refClassUIDPath), mitk::TemporoSpatialStringProperty::New(classUID)); mitk::PropertyKeyPath purposePath; purposePath.AddElement("DICOM").AddElement("0008").AddSelection("2112", sequElement).AddElement("0040").AddSelection("a170", 0).AddElement("0008").AddElement("0104"); owner->SetProperty(PropertyKeyPathToPropertyName(purposePath), mitk::TemporoSpatialStringProperty::New(purpose)); } bool IsCorrectDICOMReference(const mitk::IPropertyOwner* owner, const std::string& instanceUID, const std::string& classUID, const std::string& purpose, unsigned int sequElement) const { mitk::PropertyKeyPath refInstanceUIDPath; refInstanceUIDPath.AddElement("DICOM").AddElement("0008").AddSelection("2112", sequElement).AddElement("0008").AddElement("1155"); auto prop = owner->GetConstProperty(PropertyKeyPathToPropertyName(refInstanceUIDPath)); if (prop->GetValueAsString() != instanceUID) { return false; } mitk::PropertyKeyPath refClassUIDPath; refClassUIDPath.AddElement("DICOM").AddElement("0008").AddSelection("2112", sequElement).AddElement("0008").AddElement("1150"); prop = owner->GetConstProperty(PropertyKeyPathToPropertyName(refClassUIDPath)); if (prop->GetValueAsString() != classUID) { return false; } mitk::PropertyKeyPath purposePath; purposePath.AddElement("DICOM").AddElement("0008").AddSelection("2112", sequElement).AddElement("0040").AddSelection("a170", 0).AddElement("0008").AddElement("0104"); prop = owner->GetConstProperty(PropertyKeyPathToPropertyName(purposePath)); if (prop->GetValueAsString() != purpose) { return false; } return true; } public: void setUp() override { auto instanceUIDPropName = mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0018); auto classUIDPropName = mitk::GeneratePropertyNameForDICOMTag(0x0008, 0x0016); rule = mitk::SourceImageRelationRule::New("Test"); abstractRule = mitk::SourceImageRelationRule::New(); unRelated = mitk::Image::New(); unRelated->SetProperty(instanceUIDPropName, mitk::TemporoSpatialStringProperty::New("unRelated")); unRelated->SetProperty(classUIDPropName, mitk::TemporoSpatialStringProperty::New("image")); unRelated_Node = mitk::DataNode::New(); unRelated_Node->SetData(unRelated); dest_1_Node = mitk::DataNode::New(); dest_1_Node->SetName("dest_1"); dest_1 = mitk::Image::New(); dest_1->SetProperty(instanceUIDPropName, mitk::TemporoSpatialStringProperty::New("dest_1")); dest_1->SetProperty(classUIDPropName, mitk::TemporoSpatialStringProperty::New("image")); dest_1_Node->SetData(dest_1); dest_2_Node = mitk::DataNode::New(); dest_2_Node->SetName("dest_2"); dest_2 = mitk::Image::New(); dest_2->SetProperty(instanceUIDPropName, mitk::TemporoSpatialStringProperty::New("dest_2")); dest_2->SetProperty(classUIDPropName, mitk::TemporoSpatialStringProperty::New("image")); dest_2_Node->SetData(dest_2); source_implicit_1 = mitk::Image::New(); SetDICOMReferenceInfo(source_implicit_1, "dest_1", "image", "Test", 0); source_implicit_1_Node = mitk::DataNode::New(); source_implicit_1_Node->SetData(source_implicit_1); source_idOnly_1 = mitk::Image::New(); std::string name = "MITK.Relations.1.relationUID"; source_idOnly_1->SetProperty(name.c_str(), mitk::StringProperty::New("uid1")); name = "MITK.Relations.1.destinationUID"; source_idOnly_1->SetProperty(name.c_str(), mitk::StringProperty::New(dest_1->GetUID())); name = "MITK.Relations.1.ruleID"; source_idOnly_1->SetProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); source_idOnly_1_Node = mitk::DataNode::New(); source_idOnly_1_Node->SetData(source_idOnly_1); source_Data_1 = mitk::Image::New(); SetDICOMReferenceInfo(source_Data_1, "dest_1", "image", "Test", 0); SetDICOMReferenceInfo(source_Data_1, "dest_2", "image", "otherpurpose", 1); name = "MITK.Relations.1.relationUID"; source_Data_1->SetProperty(name.c_str(), mitk::StringProperty::New("uid2")); name = "MITK.Relations.1.ruleID"; source_Data_1->SetProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); name = "MITK.Relations.1.SourceImageSequenceItem"; source_Data_1->SetProperty(name.c_str(), mitk::StringProperty::New("0")); name = "MITK.Relations.2.relationUID"; source_Data_1->SetProperty(name.c_str(), mitk::StringProperty::New("uid10")); name = "MITK.Relations.2.SourceImageSequenceItem"; source_Data_1->SetProperty(name.c_str(), mitk::StringProperty::New("1")); name = "MITK.Relations.2.ruleID"; source_Data_1->SetProperty(name.c_str(), mitk::StringProperty::New("SourceImageRelation otherpurpose")); source_Data_1_Node = mitk::DataNode::New(); source_Data_1_Node->SetData(source_Data_1); source_1 = mitk::Image::New(); SetDICOMReferenceInfo(source_1, "dest_1", "image", "Test", 0); SetDICOMReferenceInfo(source_1, "dest_2", "image", "otherpurpose", 1); name = "MITK.Relations.1.relationUID"; source_1->SetProperty(name.c_str(), mitk::StringProperty::New("uid3")); name = "MITK.Relations.1.destinationUID"; source_1->SetProperty(name.c_str(), mitk::StringProperty::New(dest_1->GetUID())); name = "MITK.Relations.1.ruleID"; source_1->SetProperty(name.c_str(), mitk::StringProperty::New(rule->GetRuleID())); name = "MITK.Relations.1.SourceImageSequenceItem"; source_1->SetProperty(name.c_str(), mitk::StringProperty::New("0")); name = "MITK.Relations.2.relationUID"; source_1->SetProperty(name.c_str(), mitk::StringProperty::New("uid8")); name = "MITK.Relations.2.destinationUID"; source_1->SetProperty(name.c_str(), mitk::StringProperty::New(dest_2->GetUID())); name = "MITK.Relations.2.ruleID"; source_1->SetProperty(name.c_str(), mitk::StringProperty::New("SourceImageRelation otherpurpose")); name = "MITK.Relations.2.SourceImageSequenceItem"; source_1->SetProperty(name.c_str(), mitk::StringProperty::New("1")); source_1_Node = mitk::DataNode::New(); source_1_Node->SetData(source_1); source_otherRule = mitk::Image::New(); name = "MITK.Relations.1.relationUID"; source_otherRule->SetProperty(name.c_str(), mitk::StringProperty::New("uid7")); name = "MITK.Relations.1.destinationUID"; source_otherRule->SetProperty(name.c_str(), mitk::StringProperty::New(dest_1->GetUID())); name = "MITK.Relations.1.ruleID"; source_otherRule->SetProperty(name.c_str(), mitk::StringProperty::New("otherRuleID")); source_otherRule_Node = mitk::DataNode::New(); source_otherRule_Node->SetData(source_otherRule); source_otherPurpose = mitk::Image::New(); name = "MITK.Relations.1.relationUID"; source_otherPurpose->SetProperty(name.c_str(), mitk::StringProperty::New("uid9")); name = "MITK.Relations.1.destinationUID"; source_otherPurpose->SetProperty(name.c_str(), mitk::StringProperty::New(dest_1->GetUID())); name = "MITK.Relations.1.ruleID"; source_otherPurpose->SetProperty(name.c_str(), mitk::StringProperty::New("SourceImageRelation otherpurpose")); source_otherPurpose_Node = mitk::DataNode::New(); source_otherPurpose_Node->SetData(source_otherPurpose); } void tearDown() override {} void ConstructionAndGetter() { CPPUNIT_ASSERT(abstractRule->IsAbstract()); CPPUNIT_ASSERT(!rule->IsAbstract()); CPPUNIT_ASSERT_EQUAL(abstractRule->GetRuleID(), std::string("SourceImageRelation")); CPPUNIT_ASSERT_EQUAL(abstractRule->GetDisplayName(), std::string("Abstract image to image relation")); CPPUNIT_ASSERT_EQUAL(abstractRule->GetSourceRoleName(), std::string("derived data")); CPPUNIT_ASSERT_EQUAL(abstractRule->GetDestinationRoleName(), std::string("source image")); CPPUNIT_ASSERT_EQUAL(rule->GetRuleID(), std::string("SourceImageRelation Test")); CPPUNIT_ASSERT_EQUAL(rule->GetDisplayName(), std::string("Test relation")); CPPUNIT_ASSERT_EQUAL(rule->GetSourceRoleName(), std::string("derived data")); CPPUNIT_ASSERT_EQUAL(rule->GetDestinationRoleName(), std::string("source image")); rule = mitk::SourceImageRelationRule::New("Test2", "DisplayName2"); CPPUNIT_ASSERT_EQUAL(rule->GetRuleID(), std::string("SourceImageRelation Test2")); CPPUNIT_ASSERT_EQUAL(rule->GetDisplayName(), std::string("DisplayName2")); CPPUNIT_ASSERT_EQUAL(rule->GetSourceRoleName(), std::string("derived data")); CPPUNIT_ASSERT_EQUAL(rule->GetDestinationRoleName(), std::string("source image")); rule = mitk::SourceImageRelationRule::New("Test3", "DisplayName3", "s", "d"); CPPUNIT_ASSERT_EQUAL(rule->GetRuleID(), std::string("SourceImageRelation Test3")); CPPUNIT_ASSERT_EQUAL(rule->GetDisplayName(), std::string("DisplayName3")); CPPUNIT_ASSERT_EQUAL(rule->GetSourceRoleName(), std::string("s")); CPPUNIT_ASSERT_EQUAL(rule->GetDestinationRoleName(), std::string("d")); } void IsSourceCandidate() { CPPUNIT_ASSERT(rule->IsSourceCandidate(mitk::DataNode::New())); CPPUNIT_ASSERT(!rule->IsSourceCandidate(nullptr)); } void IsDestinationCandidate() { CPPUNIT_ASSERT(rule->IsDestinationCandidate(this->dest_1_Node)); CPPUNIT_ASSERT(rule->IsDestinationCandidate(this->dest_1)); CPPUNIT_ASSERT(!rule->IsDestinationCandidate(mitk::DataNode::New())); CPPUNIT_ASSERT(!rule->IsDestinationCandidate(nullptr)); } void IsSource() { CPPUNIT_ASSERT_THROW_MESSAGE( "Violated precondition (nullptr) does not throw.", rule->IsSource(nullptr), itk::ExceptionObject); CPPUNIT_ASSERT(!rule->IsSource(unRelated)); CPPUNIT_ASSERT(rule->IsSource(source_implicit_1)); CPPUNIT_ASSERT(rule->IsSource(source_Data_1)); CPPUNIT_ASSERT(rule->IsSource(source_idOnly_1)); CPPUNIT_ASSERT(rule->IsSource(source_1)); CPPUNIT_ASSERT(!rule->IsSource(source_otherRule)); CPPUNIT_ASSERT(!rule->IsSource(source_otherPurpose)); CPPUNIT_ASSERT(rule->IsSource(source_implicit_1_Node)); CPPUNIT_ASSERT(rule->IsSource(source_Data_1_Node)); CPPUNIT_ASSERT(rule->IsSource(source_idOnly_1_Node)); CPPUNIT_ASSERT(rule->IsSource(source_1_Node)); CPPUNIT_ASSERT(!rule->IsSource(source_otherRule_Node)); CPPUNIT_ASSERT(!rule->IsSource(source_otherPurpose_Node)); CPPUNIT_ASSERT(!abstractRule->IsSource(unRelated)); CPPUNIT_ASSERT(abstractRule->IsSource(source_implicit_1)); CPPUNIT_ASSERT(abstractRule->IsSource(source_Data_1)); CPPUNIT_ASSERT(abstractRule->IsSource(source_idOnly_1)); CPPUNIT_ASSERT(abstractRule->IsSource(source_1)); CPPUNIT_ASSERT(!abstractRule->IsSource(source_otherRule)); CPPUNIT_ASSERT(abstractRule->IsSource(source_otherPurpose)); CPPUNIT_ASSERT(!abstractRule->IsSource(unRelated_Node)); CPPUNIT_ASSERT(abstractRule->IsSource(source_implicit_1_Node)); CPPUNIT_ASSERT(abstractRule->IsSource(source_Data_1_Node)); CPPUNIT_ASSERT(abstractRule->IsSource(source_idOnly_1_Node)); CPPUNIT_ASSERT(abstractRule->IsSource(source_1_Node)); CPPUNIT_ASSERT(!abstractRule->IsSource(source_otherRule_Node)); CPPUNIT_ASSERT(abstractRule->IsSource(source_otherPurpose_Node)); } void HasRelation() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->HasRelation(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->HasRelation(source_1, nullptr), itk::ExceptionObject); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!rule->HasRelation(unRelated, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!rule->HasRelation(source_otherRule, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!rule->HasRelation(source_otherPurpose, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(rule->HasRelation(source_implicit_1, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(rule->HasRelation(source_Data_1, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(rule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!rule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!rule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(rule->HasRelation(source_idOnly_1, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(!rule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!abstractRule->HasRelation(unRelated, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_otherRule, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_otherPurpose, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_otherPurpose, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_otherPurpose, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_otherPurpose, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_otherPurpose, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_implicit_1, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_Data_1, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_idOnly_1, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::ID)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::Complete)); } void GetExistingRelations() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->GetExistingRelations(nullptr), itk::ExceptionObject); CPPUNIT_ASSERT(rule->GetExistingRelations(unRelated).empty()); CPPUNIT_ASSERT(rule->GetExistingRelations(source_otherRule).empty()); CPPUNIT_ASSERT(rule->GetExistingRelations(source_otherPurpose).empty()); auto uids = rule->GetExistingRelations(source_implicit_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "DICOM.0008.2112.[0].0008.1155"); uids = rule->GetExistingRelations(source_idOnly_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid1"); uids = rule->GetExistingRelations(source_Data_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid2"); uids = rule->GetExistingRelations(source_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid3"); CPPUNIT_ASSERT(abstractRule->GetExistingRelations(unRelated).empty()); CPPUNIT_ASSERT(abstractRule->GetExistingRelations(source_otherRule).empty()); uids = abstractRule->GetExistingRelations(source_implicit_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "DICOM.0008.2112.[0].0008.1155"); uids = abstractRule->GetExistingRelations(source_idOnly_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid1"); uids = abstractRule->GetExistingRelations(source_Data_1); CPPUNIT_ASSERT(uids.size() == 2); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid2") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid10") != uids.end()); uids = abstractRule->GetExistingRelations(source_1); CPPUNIT_ASSERT(uids.size() == 2); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid3") != uids.end()); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid8") != uids.end()); uids = abstractRule->GetExistingRelations(source_otherPurpose); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid9"); } void GetRelationUIDs() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->GetRelationUIDs(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->GetRelationUIDs(source_1, nullptr), itk::ExceptionObject); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_1, unRelated).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_1, dest_2).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(unRelated, dest_1).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_otherRule, dest_1).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_otherPurpose, dest_1).empty()); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_idOnly_1, dest_1).front() == "uid1"); CPPUNIT_ASSERT(rule->GetRelationUIDs(source_Data_1, dest_1).front() == "uid2"); auto uids = rule->GetRelationUIDs(source_1, dest_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(uids.front() == "uid3"); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_1, unRelated).empty()); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(unRelated, dest_1).empty()); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_otherRule, dest_1).empty()); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_otherPurpose, dest_1).front() == "uid9"); CPPUNIT_ASSERT(abstractRule->GetRelationUIDs(source_idOnly_1, dest_1).front() == "uid1"); uids = abstractRule->GetRelationUIDs(source_Data_1, dest_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid2") != uids.end()); uids = abstractRule->GetRelationUIDs(source_1, dest_1); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid3") != uids.end()); uids = abstractRule->GetRelationUIDs(source_1, dest_2); CPPUNIT_ASSERT(uids.size() == 1); CPPUNIT_ASSERT(std::find(uids.begin(), uids.end(), "uid8") != uids.end()); } void GetSourceCandidateIndicator() { auto predicate = rule->GetSourceCandidateIndicator(); CPPUNIT_ASSERT(predicate->CheckNode(mitk::DataNode::New())); CPPUNIT_ASSERT(!predicate->CheckNode(nullptr)); } void GetDestinationCandidateIndicator() { auto predicate = rule->GetDestinationCandidateIndicator(); CPPUNIT_ASSERT(predicate->CheckNode(this->dest_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(mitk::DataNode::New())); CPPUNIT_ASSERT(!predicate->CheckNode(nullptr)); } void GetConnectedSourcesDetector() { auto predicate = rule->GetConnectedSourcesDetector(); CPPUNIT_ASSERT(!predicate->CheckNode(nullptr)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherPurpose_Node)); auto predicate2 = abstractRule->GetConnectedSourcesDetector(); CPPUNIT_ASSERT(!predicate2->CheckNode(nullptr)); CPPUNIT_ASSERT(!predicate2->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(predicate2->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(predicate2->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(predicate2->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(predicate2->CheckNode(source_1_Node)); CPPUNIT_ASSERT(!predicate2->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(predicate2->CheckNode(source_otherPurpose_Node)); } void GetSourcesDetector() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->GetSourcesDetector(nullptr), itk::ExceptionObject); auto predicate = rule->GetSourcesDetector(dest_1); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherPurpose_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_1_Node)); predicate = rule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherPurpose_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_1_Node)); predicate = rule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherPurpose_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_1_Node)); predicate = rule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherPurpose_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_1_Node)); predicate = rule->GetSourcesDetector(dest_2, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherPurpose_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_1_Node)); predicate = abstractRule->GetSourcesDetector(dest_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_otherPurpose_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_1_Node)); predicate = abstractRule->GetSourcesDetector(dest_1); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(source_otherRule_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_otherPurpose_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_implicit_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_Data_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_idOnly_1_Node)); CPPUNIT_ASSERT(predicate->CheckNode(source_1_Node)); } void GetDestinationsDetector() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->GetDestinationsDetector(nullptr), itk::ExceptionObject); auto predicate = rule->GetDestinationsDetector(source_otherRule); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_otherPurpose); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_implicit_1); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_implicit_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_implicit_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_implicit_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_Data_1); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_Data_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_Data_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_Data_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_idOnly_1); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_idOnly_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_idOnly_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_idOnly_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(!predicate->CheckNode(dest_1_Node)); predicate = rule->GetDestinationsDetector(source_1); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2_Node)); predicate = rule->GetDestinationsDetector(source_1, mitk::PropertyRelationRuleBase::RelationType::Data); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2_Node)); predicate = rule->GetDestinationsDetector(source_1, mitk::PropertyRelationRuleBase::RelationType::ID); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2_Node)); predicate = rule->GetDestinationsDetector(source_1, mitk::PropertyRelationRuleBase::RelationType::Complete); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2_Node)); predicate = abstractRule->GetDestinationsDetector(source_otherPurpose); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); predicate = abstractRule->GetDestinationsDetector(source_otherPurpose); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); } void GetDestinationDetector() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->GetDestinationDetector(nullptr, "uid1"), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (relation uid is invalid) does not throw.", rule->GetDestinationDetector(source_1, "invalid uid"), itk::ExceptionObject); auto predicate = rule->GetDestinationDetector(source_1, "uid3"); CPPUNIT_ASSERT(!predicate->CheckNode(unRelated_Node)); CPPUNIT_ASSERT(predicate->CheckNode(dest_1_Node)); CPPUNIT_ASSERT(!predicate->CheckNode(dest_2_Node)); } void Connect() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->Connect(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Connect(source_1, nullptr), itk::ExceptionObject); // check upgrade of an implicit connection CPPUNIT_ASSERT(rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); rule->Connect(source_implicit_1, dest_1); CPPUNIT_ASSERT(rule->HasRelation(source_implicit_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); auto dcmRefs = GetReferenceSequenceIndices(source_implicit_1, dest_1); CPPUNIT_ASSERT_MESSAGE("Additional dicom reference was defined instead of using the existing one.", dcmRefs.size() == 1); CPPUNIT_ASSERT_MESSAGE("Dicom reference is not correct.", IsCorrectDICOMReference(source_implicit_1, "dest_1", "image", "Test", 0)); // check upgrade and reuse of an Data connection (no new relation should be generated). CPPUNIT_ASSERT(rule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Data)); rule->Connect(source_Data_1, dest_1); CPPUNIT_ASSERT(rule->HasRelation(source_Data_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); auto relUID = rule->GetRelationUIDs(source_Data_1, dest_1); CPPUNIT_ASSERT(relUID.size() == 1); std::string name = "MITK.Relations.1.destinationUID"; auto prop = source_Data_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE( "Destination uid was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == dest_1->GetUID()); name = "MITK.Relations.1.ruleID"; prop = source_Data_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect ruleID was stored.", prop->GetValueAsString() == rule->GetRuleID()); name = "MITK.Relations.1.SourceImageSequenceItem"; prop = source_Data_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == "0"); dcmRefs = GetReferenceSequenceIndices(source_Data_1, dest_1); CPPUNIT_ASSERT_MESSAGE("Additional dicom reference was defined instead of using the existing one.", dcmRefs.size() == 1); CPPUNIT_ASSERT_MESSAGE("Dicom reference is not correct.", IsCorrectDICOMReference(source_Data_1, "dest_1", "image", "Test", 0)); // check actualization of an id only connection rule->Connect(source_idOnly_1, dest_1); CPPUNIT_ASSERT(rule->HasRelation(source_idOnly_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); - CPPUNIT_ASSERT_MESSAGE("Additional relation was defined instead of updating exting one.", + CPPUNIT_ASSERT_MESSAGE("Additional relation was defined instead of updating existing one.", rule->GetExistingRelations(source_1).size() == 1); // check actualization of an existing connection rule->Connect(source_1, dest_1); CPPUNIT_ASSERT(rule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); - CPPUNIT_ASSERT_MESSAGE("Additional relation was defined instead of updating exting one.", + CPPUNIT_ASSERT_MESSAGE("Additional relation was defined instead of updating existing one.", rule->GetExistingRelations(source_1).size() == 1); name = "MITK.Relations.1.destinationUID"; prop = source_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE( "Destination uid was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == dest_1->GetUID()); name = "MITK.Relations.1.ruleID"; prop = source_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect ruleID was stored.", prop->GetValueAsString() == rule->GetRuleID()); name = "MITK.Relations.1.SourceImageSequenceItem"; prop = source_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == "0"); dcmRefs = GetReferenceSequenceIndices(source_1, dest_1); CPPUNIT_ASSERT_MESSAGE("Additional dicom reference was defined instead of using the existing one.", dcmRefs.size() == 1); CPPUNIT_ASSERT_MESSAGE("Dicom reference is not correct.", IsCorrectDICOMReference(source_1, "dest_1", "image", "Test", 0)); // check creation of an new connection rule->Connect(unRelated, dest_1); CPPUNIT_ASSERT(rule->HasRelation(unRelated, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); - CPPUNIT_ASSERT_MESSAGE("Relation was not defined instead of updating exting one.", + CPPUNIT_ASSERT_MESSAGE("Relation was not defined instead of updating existing one.", rule->GetExistingRelations(unRelated).size() == 1); name = "MITK.Relations.1.destinationUID"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == dest_1->GetUID()); name = "MITK.Relations.1.ruleID"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect ruleID was stored.", prop->GetValueAsString() == rule->GetRuleID()); name = "MITK.Relations.1.SourceImageSequenceItem"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == "0"); dcmRefs = GetReferenceSequenceIndices(unRelated, dest_1); CPPUNIT_ASSERT_MESSAGE("Additional dicom reference was defined instead of using the existing one.", dcmRefs.size() == 1); - CPPUNIT_ASSERT_MESSAGE("Dicom reference squence is corrupted. Should be just an index 0.", dcmRefs[0] == "0"); + CPPUNIT_ASSERT_MESSAGE("Dicom reference sequence is corrupted. Should be just an index 0.", dcmRefs[0] == "0"); CPPUNIT_ASSERT_MESSAGE("Dicom reference is not correct.", IsCorrectDICOMReference(unRelated, "dest_1", "image", "Test", 0)); // check creation of a 2nd connection of the same purpose rule->Connect(unRelated, dest_2); CPPUNIT_ASSERT(rule->HasRelation(unRelated, dest_2, mitk::PropertyRelationRuleBase::RelationType::Complete)); CPPUNIT_ASSERT_MESSAGE("Additional relation was not defined.", rule->GetExistingRelations(unRelated).size() == 2); name = "MITK.Relations.1.destinationUID"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == dest_1->GetUID()); name = "MITK.Relations.1.ruleID"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect ruleID was stored.", prop->GetValueAsString() == rule->GetRuleID()); name = "MITK.Relations.1.SourceImageSequenceItem"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == "0"); name = "MITK.Relations.2.destinationUID"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == dest_2->GetUID()); name = "MITK.Relations.2.ruleID"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect ruleID was stored.", prop->GetValueAsString() == rule->GetRuleID()); name = "MITK.Relations.2.SourceImageSequenceItem"; prop = unRelated->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == "1"); dcmRefs = GetReferenceSequenceIndices(unRelated, dest_2); CPPUNIT_ASSERT_MESSAGE("Additional dicom reference was not defined.", dcmRefs.size() == 1); CPPUNIT_ASSERT_MESSAGE("Dicom reference is not correct.", IsCorrectDICOMReference(unRelated, "dest_1", "image", "Test", 0)); CPPUNIT_ASSERT_MESSAGE("Dicom reference is not correct.", IsCorrectDICOMReference(unRelated, "dest_2", "image", "Test", 1)); } void Disconnect() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (source is nullptr) does not throw.", rule->Disconnect(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Disconnect(source_1, nullptr), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (destination is nullptr) does not throw.", rule->Disconnect(nullptr, "uid"), itk::ExceptionObject); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); rule->Disconnect(source_1, unRelated); CPPUNIT_ASSERT(!rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT_MESSAGE("Other relationData property was removed.", IsCorrectDICOMReference(source_1, "dest_1", "image", "Test", 0)); //check if index correction is correct, when disconnecting rule->Connect(source_1, dest_2); rule->Connect(source_1, unRelated); rule->Disconnect(source_1, dest_2); CPPUNIT_ASSERT(!rule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(rule->HasRelation(source_1, unRelated, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(this->hasRelationProperties(source_1, "1")); CPPUNIT_ASSERT(this->hasRelationProperties(source_1, "2")); CPPUNIT_ASSERT(!this->hasRelationProperties(source_1, "3")); CPPUNIT_ASSERT(this->hasRelationProperties(source_1, "4")); CPPUNIT_ASSERT_MESSAGE("Dicom reference to dest_1 has been removed.", IsCorrectDICOMReference(source_1, "dest_1", "image", "Test", 0)); CPPUNIT_ASSERT_MESSAGE("Dicom reference to dest_2 (other purpose) has been removed or has not a corrected sequence index (1 instead of 2).", IsCorrectDICOMReference(source_1, "dest_2", "image", "otherpurpose", 1)); CPPUNIT_ASSERT_MESSAGE("Dicom reference to unRelated has been removed or has not a corrected sequence index (1 instead of 2).", IsCorrectDICOMReference(source_1, "unRelated", "image", "Test", 2)); std::string name = "MITK.Relations.4.destinationUID"; auto prop = source_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE( "Destination uid was not stored with the correct key. Already existing session should be used.", prop); CPPUNIT_ASSERT_MESSAGE("Incorrect destination uid was stored.", prop->GetValueAsString() == unRelated->GetUID()); name = "MITK.Relations.4.SourceImageSequenceItem"; prop = source_1->GetProperty(name.c_str()); CPPUNIT_ASSERT_MESSAGE("SourceImageSequenceItem was not actualized correctly.", prop->GetValueAsString() == "2"); rule->Disconnect(source_otherPurpose, dest_1); CPPUNIT_ASSERT_MESSAGE("Data of other rule purpose was removed.", this->hasRelationProperties(source_otherPurpose, "1")); } void Connect_abstract() { CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (abstract does not connect) does not throw.", abstractRule->Connect(nullptr, dest_1), itk::ExceptionObject); CPPUNIT_ASSERT_THROW_MESSAGE("Violated precondition (abstract does not connect) does not throw.", abstractRule->Connect(source_1, nullptr), itk::ExceptionObject); } void Disconnect_abstract() { CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::Complete)); abstractRule->Disconnect(source_1, dest_2); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_1, dest_2, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!this->hasRelationProperties(source_1, "2")); CPPUNIT_ASSERT(abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::Complete)); abstractRule->Disconnect(source_1, dest_1); CPPUNIT_ASSERT(!abstractRule->HasRelation(source_1, dest_1, mitk::PropertyRelationRuleBase::RelationType::None)); CPPUNIT_ASSERT(!this->hasRelationProperties(source_1, "1")); abstractRule->Disconnect(source_otherPurpose, dest_1); CPPUNIT_ASSERT_MESSAGE("Data of other rule type was removed.", !this->hasRelationProperties(source_otherPurpose, "1")); } }; MITK_TEST_SUITE_REGISTRATION(mitkSourceImageRelationRule) diff --git a/Modules/Core/test/mitkSurfaceEqualTest.cpp b/Modules/Core/test/mitkSurfaceEqualTest.cpp index 5cfaebe32b..9bfaa33cdb 100644 --- a/Modules/Core/test/mitkSurfaceEqualTest.cpp +++ b/Modules/Core/test/mitkSurfaceEqualTest.cpp @@ -1,188 +1,188 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkSurface.h" #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include #include #include #include #include /** * @brief mitkPointSetEqualTestSuite A test class for Equal methods in mitk::PointSet. */ class mitkSurfaceEqualTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkSurfaceEqualTestSuite); MITK_TEST(Equal_CloneAndOriginalOneTimestep_ReturnsTrue); MITK_TEST(Equal_CloneAndOriginalTwoTimesteps_ReturnsTrue); MITK_TEST(Equal_OneTimeStepVSTwoTimeStep_ReturnsFalse); MITK_TEST(Equal_TwoTimeStepsDifferentPoints_ReturnsFalse); MITK_TEST(Equal_DifferentPoints_ReturnsFalse); MITK_TEST(Equal_SurfaceWithPolygonSurfaceWithPolyLine_ReturnsFalse); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different (sub-)tests. All members are initialized via setUp().*/ mitk::Surface::Pointer m_Surface3D; mitk::Surface::Pointer m_Surface3DTwoTimeSteps; vtkSmartPointer m_PointsOne; vtkSmartPointer m_PointsTwo; vtkSmartPointer m_PolygonArrayTwo; vtkSmartPointer m_PolyDataOne; public: /** -* @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used members +* @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used members * for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { // generate two sets of points m_PointsOne = vtkSmartPointer::New(); m_PointsOne->InsertNextPoint(0.0, 0.0, 0.0); m_PointsOne->InsertNextPoint(1.0, 0.0, 0.0); m_PointsOne->InsertNextPoint(0.0, 1.0, 0.0); m_PointsOne->InsertNextPoint(1.0, 1.0, 0.0); m_PointsTwo = vtkSmartPointer::New(); m_PointsTwo->InsertNextPoint(0.0, 0.0, 0.0); m_PointsTwo->InsertNextPoint(0.0, 0.0, 2.0); m_PointsTwo->InsertNextPoint(0.0, 1.0, 0.0); m_PointsTwo->InsertNextPoint(0.0, 1.0, 2.0); // generate two polygons vtkSmartPointer polygonOne = vtkSmartPointer::New(); polygonOne->GetPointIds()->SetNumberOfIds(4); polygonOne->GetPointIds()->SetId(0, 0); polygonOne->GetPointIds()->SetId(1, 1); polygonOne->GetPointIds()->SetId(2, 2); polygonOne->GetPointIds()->SetId(3, 3); vtkSmartPointer polygonTwo = vtkSmartPointer::New(); polygonTwo->GetPointIds()->SetNumberOfIds(4); polygonTwo->GetPointIds()->SetId(0, 3); polygonTwo->GetPointIds()->SetId(1, 2); polygonTwo->GetPointIds()->SetId(2, 0); polygonTwo->GetPointIds()->SetId(3, 1); // generate polydatas vtkSmartPointer polygonArrayOne = vtkSmartPointer::New(); polygonArrayOne->InsertNextCell(polygonOne); m_PolyDataOne = vtkSmartPointer::New(); m_PolyDataOne->SetPoints(m_PointsOne); m_PolyDataOne->SetPolys(polygonArrayOne); m_PolygonArrayTwo = vtkSmartPointer::New(); m_PolygonArrayTwo->InsertNextCell(polygonTwo); vtkSmartPointer polyDataTwo = vtkSmartPointer::New(); polyDataTwo->SetPoints(m_PointsOne); polyDataTwo->SetPolys(m_PolygonArrayTwo); // generate surfaces m_Surface3D = mitk::Surface::New(); m_Surface3D->SetVtkPolyData(m_PolyDataOne); m_Surface3DTwoTimeSteps = mitk::Surface::New(); m_Surface3DTwoTimeSteps->SetVtkPolyData(m_PolyDataOne, 0); m_Surface3DTwoTimeSteps->SetVtkPolyData(polyDataTwo, 1); } void tearDown() override { m_Surface3D = nullptr; m_Surface3DTwoTimeSteps = nullptr; m_PolyDataOne = nullptr; m_PolygonArrayTwo = nullptr; m_PointsOne = nullptr; m_PointsTwo = nullptr; } void Equal_CloneAndOriginalOneTimestep_ReturnsTrue() { MITK_ASSERT_EQUAL(m_Surface3D, m_Surface3D->Clone(), "A one timestep clone should be equal to its original."); } void Equal_CloneAndOriginalTwoTimesteps_ReturnsTrue() { MITK_ASSERT_EQUAL(m_Surface3DTwoTimeSteps, m_Surface3DTwoTimeSteps->Clone(), "A two timestep clone should be equal to its original."); } void Equal_OneTimeStepVSTwoTimeStep_ReturnsFalse() { MITK_ASSERT_NOT_EQUAL( m_Surface3D, m_Surface3DTwoTimeSteps, "A one timestep and two timestep surface should not be equal."); } void Equal_TwoTimeStepsDifferentPoints_ReturnsFalse() { vtkSmartPointer polyDataDifferentPoints = vtkSmartPointer::New(); polyDataDifferentPoints->SetPoints(m_PointsTwo); polyDataDifferentPoints->SetPolys(m_PolygonArrayTwo); mitk::Surface::Pointer surface3DTwoTimeStepsDifferentPoints = mitk::Surface::New(); surface3DTwoTimeStepsDifferentPoints->SetVtkPolyData(m_PolyDataOne, 0); surface3DTwoTimeStepsDifferentPoints->SetVtkPolyData(polyDataDifferentPoints, 1); // The geometry also changes, because the second pointset has a different geometry/extent. MITK_ASSERT_NOT_EQUAL(surface3DTwoTimeStepsDifferentPoints, m_Surface3DTwoTimeSteps, "A surface with the same timesteps and different points should not be equal."); } void Equal_SurfaceWithPolygonSurfaceWithPolyLine_ReturnsFalse() { // generate a line vtkSmartPointer polyLineOne = vtkSmartPointer::New(); polyLineOne->GetPointIds()->SetNumberOfIds(2); polyLineOne->GetPointIds()->SetId(0, 0); polyLineOne->GetPointIds()->SetId(1, 1); vtkSmartPointer polyLineArrayOne = vtkSmartPointer::New(); polyLineArrayOne->InsertNextCell(polyLineOne); vtkSmartPointer polyDataLine = vtkSmartPointer::New(); polyDataLine->SetPoints(m_PointsOne); polyDataLine->SetLines(polyLineArrayOne); mitk::Surface::Pointer surface3DLine = mitk::Surface::New(); surface3DLine->SetVtkPolyData(polyDataLine); MITK_ASSERT_NOT_EQUAL(m_Surface3D, surface3DLine, "A surface with the same timesteps and points and the same " "number of cells, but different types of cells should not be " "equal."); } void Equal_DifferentPoints_ReturnsFalse() { mitk::Surface::Pointer surfaceWithADifferentPoint = m_Surface3D->Clone(); // modify points. m_Surface3D contains m_PointsOne surfaceWithADifferentPoint->GetVtkPolyData()->SetPoints(m_PointsTwo); MITK_ASSERT_NOT_EQUAL(m_Surface3D, surfaceWithADifferentPoint, "A surface with a single timestep and different points should not be equal."); } }; MITK_TEST_SUITE_REGISTRATION(mitkSurfaceEqual) diff --git a/Modules/Core/test/mitkSurfaceToImageFilterTest.cpp b/Modules/Core/test/mitkSurfaceToImageFilterTest.cpp index 6229d1b1bf..3b93328eef 100644 --- a/Modules/Core/test/mitkSurfaceToImageFilterTest.cpp +++ b/Modules/Core/test/mitkSurfaceToImageFilterTest.cpp @@ -1,253 +1,253 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include #include #include #include #include "mitkSurfaceToImageFilter.h" #include "mitkTestFixture.h" #include class mitkSurfaceToImageFilterTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkSurfaceToImageFilterTestSuite); MITK_TEST(test3DSurfaceValidOutput); MITK_TEST(test3DSurfaceCorrect); MITK_TEST(test3DSurfaceIn4DImage); CPPUNIT_TEST_SUITE_END(); private: /** Members used inside the different test methods. All members are initialized via setUp().*/ mitk::Surface::Pointer m_Surface; public: /** - * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used + * @brief Setup Always call this method before each Test-case to ensure correct and new initialization of the used * members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { m_Surface = mitk::IOUtil::Load(GetTestDataFilePath("ball.stl")); } void tearDown() override {} void test3DSurfaceValidOutput() { mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); mitk::Image::Pointer additionalInputImage = mitk::Image::New(); additionalInputImage->Initialize(mitk::MakeScalarPixelType(), *m_Surface->GetTimeGeometry()); // Arrange the filter surfaceToImageFilter->MakeOutputBinaryOn(); surfaceToImageFilter->SetInput(m_Surface); surfaceToImageFilter->SetImage(additionalInputImage); surfaceToImageFilter->Update(); CPPUNIT_ASSERT_MESSAGE( "SurfaceToImageFilter_AnyInputImageAndModeSetToBinary_ResultIsImageWithUCHARPixelType", surfaceToImageFilter->GetOutput()->GetPixelType().GetComponentType() == itk::IOComponentEnum::UCHAR); surfaceToImageFilter->SetUShortBinaryPixelType(true); surfaceToImageFilter->Update(); CPPUNIT_ASSERT_MESSAGE( "SurfaceToImageFilter_AnyInputImageAndModeSetToBinary_ResultIsImageWithUCHARPixelType", surfaceToImageFilter->GetOutput()->GetPixelType().GetComponentType() == itk::IOComponentEnum::USHORT); } void test3DSurfaceCorrect() { mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); // todo I don't know if this image is always needed. There is no documentation of the filter. Use git blame and ask // the author. mitk::Image::Pointer additionalInputImage = mitk::Image::New(); auto *dims = new unsigned int[3]; dims[0] = 32; dims[1] = 32; dims[2] = 32; additionalInputImage->Initialize(mitk::MakeScalarPixelType(), 3, dims); additionalInputImage->SetOrigin(m_Surface->GetGeometry()->GetOrigin()); additionalInputImage->GetGeometry()->SetIndexToWorldTransform(m_Surface->GetGeometry()->GetIndexToWorldTransform()); // Arrange the filter // The docu does not really tell if this is always needed. Could we skip SetImage in any case? surfaceToImageFilter->MakeOutputBinaryOn(); surfaceToImageFilter->SetInput(m_Surface); surfaceToImageFilter->SetImage(additionalInputImage); surfaceToImageFilter->Update(); mitk::ImagePixelReadAccessor outputReader(surfaceToImageFilter->GetOutput()); itk::Index<3> idx; bool valuesCorrect = true; // Values outside the ball should be 0 idx[0] = 0; idx[1] = 0, idx[2] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 0; idx[1] = 15, idx[2] = 15; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 15; idx[1] = 15, idx[2] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 15; idx[1] = 0, idx[2] = 15; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 5; idx[1] = 9, idx[2] = 23; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); // Values inside the ball should be 1 idx[0] = 15; idx[1] = 15, idx[2] = 15; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 31; idx[1] = 15, idx[2] = 15; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 2; idx[1] = 15, idx[2] = 15; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 15; idx[1] = 15, idx[2] = 2; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 15; idx[1] = 2, idx[2] = 15; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 6; idx[1] = 9, idx[2] = 23; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); CPPUNIT_ASSERT_MESSAGE("SurfaceToImageFilter_BallSurfaceAsInput_OutputCorrect", valuesCorrect == true); } void test3DSurfaceIn4DImage() { mitk::SurfaceToImageFilter::Pointer surfaceToImageFilter = mitk::SurfaceToImageFilter::New(); mitk::Image::Pointer additionalInputImage = mitk::Image::New(); auto *dims = new unsigned int[4]; dims[0] = 32; dims[1] = 32; dims[2] = 32; dims[3] = 2; additionalInputImage->Initialize(mitk::MakeScalarPixelType(), 4, dims); additionalInputImage->SetOrigin(m_Surface->GetGeometry()->GetOrigin()); additionalInputImage->GetGeometry()->SetIndexToWorldTransform(m_Surface->GetGeometry()->GetIndexToWorldTransform()); mitk::Image::Pointer secondStep = additionalInputImage->Clone(); unsigned int size = sizeof(unsigned char); for (unsigned int i = 0; i < secondStep->GetDimension(); ++i) { size *= secondStep->GetDimension(i); } { mitk::ImageWriteAccessor accessor(secondStep); memset(accessor.GetData(), 1, size); } additionalInputImage->GetTimeGeometry()->Expand(2); additionalInputImage->GetGeometry(1)->SetSpacing(secondStep->GetGeometry()->GetSpacing()); additionalInputImage->GetGeometry(1)->SetOrigin(secondStep->GetGeometry()->GetOrigin()); additionalInputImage->GetGeometry(1)->SetIndexToWorldTransform( secondStep->GetGeometry()->GetIndexToWorldTransform()); { mitk::ImageReadAccessor readAccess(secondStep); additionalInputImage->SetImportVolume(readAccess.GetData(), 0); additionalInputImage->SetImportVolume(readAccess.GetData(), 1); } // Arrange the filter surfaceToImageFilter->MakeOutputBinaryOn(); surfaceToImageFilter->SetInput(m_Surface); surfaceToImageFilter->SetImage(additionalInputImage); surfaceToImageFilter->Update(); mitk::ImagePixelReadAccessor outputReader(surfaceToImageFilter->GetOutput()); itk::Index<4> idx; bool valuesCorrect = true; // Values outside the ball should be 0 idx[0] = 0; idx[1] = 0, idx[2] = 0; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 0; idx[1] = 15, idx[2] = 15; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 15; idx[1] = 15, idx[2] = 0; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 15; idx[1] = 0, idx[2] = 15; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 5; idx[1] = 9, idx[2] = 23; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); - // Values inside the ball should be 1 hould be 1 + // Values inside the ball should be 1 idx[0] = 15; idx[1] = 15, idx[2] = 15; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 31; idx[1] = 15, idx[2] = 15; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 2; idx[1] = 15, idx[2] = 15; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 15; idx[1] = 15, idx[2] = 2; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 15; idx[1] = 2, idx[2] = 15; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); idx[0] = 6; idx[1] = 9, idx[2] = 23; idx[3] = 0; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 1); - // Values inside the ball but in the second timestep hould be 0 + // Values inside the ball but in the second timestep should be 0 idx[0] = 15; idx[1] = 15, idx[2] = 15; idx[3] = 1; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 31; idx[1] = 15, idx[2] = 15; idx[3] = 1; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 2; idx[1] = 15, idx[2] = 15; idx[3] = 1; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 15; idx[1] = 15, idx[2] = 2; idx[3] = 1; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 15; idx[1] = 2, idx[2] = 15; idx[3] = 1; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); idx[0] = 6; idx[1] = 9, idx[2] = 23; idx[3] = 1; valuesCorrect = valuesCorrect && (outputReader.GetPixelByIndex(idx) == 0); CPPUNIT_ASSERT_MESSAGE("SurfaceToImageFilter_BallSurfaceAsInput_Output4DCorrect", valuesCorrect == true); } }; MITK_TEST_SUITE_REGISTRATION(mitkSurfaceToImageFilter) diff --git a/Modules/Core/test/mitkTimeGeometryTest.cpp b/Modules/Core/test/mitkTimeGeometryTest.cpp index 332311a1b7..73abe034fd 100644 --- a/Modules/Core/test/mitkTimeGeometryTest.cpp +++ b/Modules/Core/test/mitkTimeGeometryTest.cpp @@ -1,862 +1,862 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkGeometry3D.h" #include "mitkTimeGeometry.h" #include "mitkInteractionConst.h" #include "mitkRotationOperation.h" #include #include #include "mitkTestingMacros.h" #include #include #include "mitkImageGenerator.h" #include "mitkPointSet.h" #include #include static const mitk::ScalarType test_eps = 1E-6; /* some reference values in the test seem to have been calculated with float precision. Thus, set this to float precision epsilon.*/ static const mitk::ScalarType test_eps_square = 1E-3; class mitkTimeGeometryTestClass { public: void Translation_Image_MovedOrigin(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { // DimX, DimY, DimZ, mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::BaseGeometry::Pointer geometry = image->GetTimeGeometry()->GetGeometryForTimeStep(0); mitk::Point3D imageOrigin = geometry->GetOrigin(); mitk::Point3D expectedOrigin; expectedOrigin[0] = 0; expectedOrigin[1] = 0; expectedOrigin[2] = 0; MITK_TEST_CONDITION(mitk::Equal(imageOrigin, expectedOrigin), "Original origin match expected origin"); expectedOrigin[0] = 0.325; expectedOrigin[1] = 0.487; expectedOrigin[2] = 0.78; mitk::Vector3D translationVector; translationVector[0] = expectedOrigin[0]; translationVector[1] = expectedOrigin[1]; translationVector[2] = expectedOrigin[2]; for (mitk::TimeStepType timeStep = 0; timeStep < image->GetTimeGeometry()->CountTimeSteps(); ++timeStep) { image->GetTimeGeometry()->GetGeometryForTimeStep(timeStep)->Translate(translationVector); } imageOrigin = image->GetGeometry(0)->GetOrigin(); MITK_TEST_CONDITION(mitk::Equal(imageOrigin, expectedOrigin), "Translated origin match expected origin"); expectedOrigin[0] = 2 * translationVector[0]; expectedOrigin[1] = 2 * translationVector[1]; expectedOrigin[2] = 2 * translationVector[2]; for (mitk::TimeStepType timeStep = 0; timeStep < image->GetTimeGeometry()->CountTimeSteps(); ++timeStep) { image->GetTimeGeometry()->GetGeometryForTimeStep(timeStep)->Translate(translationVector); } imageOrigin = image->GetGeometry(0)->GetOrigin(); MITK_TEST_CONDITION(mitk::Equal(imageOrigin, expectedOrigin), "Translated origin match expected origin"); } void Rotate_Image_RotatedPoint(mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int /*DimT*/) { mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); // DimX, DimY, DimZ, dataNode->SetData(baseData); ds->Add(dataNode); mitk::BaseGeometry::Pointer geometry = baseData->GetTimeGeometry()->GetGeometryForTimeStep(0); mitk::Point3D expectedPoint; expectedPoint[0] = 3 * 0.5; expectedPoint[1] = 3 * 0.33; expectedPoint[2] = 3 * 0.78; mitk::Point3D originalPoint; originalPoint[0] = 3; originalPoint[1] = 3; originalPoint[2] = 3; mitk::Point3D worldPoint; geometry->IndexToWorld(originalPoint, worldPoint); MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Index-to-World without rotation as expected "); mitk::Point3D pointOfRotation; pointOfRotation[0] = 0; pointOfRotation[1] = 0; pointOfRotation[2] = 0; mitk::Vector3D vectorOfRotation; vectorOfRotation[0] = 1; vectorOfRotation[1] = 0.5; vectorOfRotation[2] = 0.2; mitk::ScalarType angleOfRotation = 73.0; auto rotation = new mitk::RotationOperation(mitk::OpROTATE, pointOfRotation, vectorOfRotation, angleOfRotation); baseData->GetTimeGeometry()->ExecuteOperation(rotation); delete rotation; expectedPoint[0] = 2.6080379; expectedPoint[1] = -0.75265157; expectedPoint[2] = 1.1564401; baseData->GetGeometry(0)->IndexToWorld(originalPoint, worldPoint); MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Rotation returns expected values "); } void Scale_Image_ScaledPoint(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { // DimX, DimY, DimZ, mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::BaseGeometry::Pointer geometry = image->GetTimeGeometry()->GetGeometryForTimeStep(0); mitk::Point3D expectedPoint; expectedPoint[0] = 3 * 0.5; expectedPoint[1] = 3 * 0.33; expectedPoint[2] = 3 * 0.78; mitk::Point3D originalPoint; originalPoint[0] = 3; originalPoint[1] = 3; originalPoint[2] = 3; mitk::Point3D worldPoint; geometry->IndexToWorld(originalPoint, worldPoint); MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Index-to-World with old Scaling as expected "); mitk::Vector3D newSpacing; newSpacing[0] = 2; newSpacing[1] = 1.254; newSpacing[2] = 0.224; image->SetSpacing(newSpacing); expectedPoint[0] = 3 * 2; expectedPoint[1] = 3 * 1.254; expectedPoint[2] = 3 * 0.224; image->GetGeometry(0)->IndexToWorld(originalPoint, worldPoint); MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint), "Index-toWorld with new Scaling returns expected values "); } void GetMinimumTimePoint_4DBaseData_Zero(mitk::BaseData *baseData, unsigned int /*DimT*/) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimePointType expectedTimePoint = geometry->GetMinimumTimePoint(); MITK_TEST_CONDITION(mitk::Equal(expectedTimePoint, 0), "Returns correct minimum time point "); } void GetMaximumTimePoint_4DBaseData_DimT(mitk::BaseData *baseData, unsigned int DimT) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimePointType expectedTimePoint = geometry->GetMaximumTimePoint(); MITK_TEST_CONDITION(mitk::Equal(expectedTimePoint, DimT), "Returns correct maximum time point "); } void CountTimeSteps_Image_ReturnDimT( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimeStepType expectedTimeSteps = geometry->CountTimeSteps(); MITK_TEST_CONDITION(mitk::Equal(expectedTimeSteps, DimT), "Returns correct number of time Steps "); } void GetMinimumTimePoint_3DImage_Min(mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int /*DimT*/) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimePointType expectedTimePoint = geometry->GetMinimumTimePoint(); MITK_TEST_CONDITION(mitk::Equal(expectedTimePoint, -std::numeric_limits().max()), "Returns correct minimum time point "); } void GetMaximumTimePoint_3DImage_Max(mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int /*DimT*/) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimePointType expectedTimePoint = geometry->GetMaximumTimePoint(); MITK_INFO << expectedTimePoint; MITK_INFO << std::numeric_limits().max(); MITK_TEST_CONDITION(mitk::Equal(expectedTimePoint, std::numeric_limits().max()), "Returns correct maximum time point "); } void GetTimeBounds_4DImage_ZeroAndDimT(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::TimeGeometry::Pointer geometry = image->GetTimeGeometry(); mitk::TimeBounds expectedTimeBounds = geometry->GetTimeBounds(); MITK_TEST_CONDITION(mitk::Equal(expectedTimeBounds[0], 0), "Returns correct minimum time point "); MITK_TEST_CONDITION(mitk::Equal(expectedTimeBounds[1], DimT), "Returns correct maximum time point "); } void GetTimeBounds_3DImage_ZeroAndDimT(mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int /*DimT*/) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimeBounds expectedTimeBounds = geometry->GetTimeBounds(); MITK_TEST_CONDITION(mitk::Equal(expectedTimeBounds[0], -std::numeric_limits().max()), "Returns correct minimum time point "); MITK_TEST_CONDITION(mitk::Equal(expectedTimeBounds[1], std::numeric_limits().max()), "Returns correct maximum time point "); } void IsValidTimePoint_ImageValidTimePoint_True( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); bool isValid = geometry->IsValidTimePoint(DimT - 1); MITK_TEST_CONDITION(mitk::Equal(isValid, true), "Is valid time Point correct minimum time point "); } void IsValidTimePoint_ImageNegativInvalidTimePoint_False(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::TimeGeometry::Pointer geometry = image->GetTimeGeometry(); bool isValid = geometry->IsValidTimePoint(-static_cast(DimT)); MITK_TEST_CONDITION(mitk::Equal(isValid, false), "Is invalid time Point correct minimum time point "); } void IsValidTimePoint_ImageInvalidTimePoint_False(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::TimeGeometry::Pointer geometry = image->GetTimeGeometry(); bool isValid = geometry->IsValidTimePoint(DimT + 1); MITK_TEST_CONDITION(mitk::Equal(isValid, false), "Is invalid time Point correct minimum time point "); } void IsValidTimeStep_ImageValidTimeStep_True( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); bool isValid = geometry->IsValidTimeStep(DimT - 1); MITK_TEST_CONDITION(mitk::Equal(isValid, true), "Is valid time Point correct minimum time point "); } void IsValidTimeStep_ImageNegativInvalidTimeStep_False( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); bool isValid = geometry->IsValidTimeStep(-static_cast(DimT)); MITK_TEST_CONDITION(mitk::Equal(isValid, false), "Is invalid time Point correct minimum time point "); } void IsValidTimeStep_ImageInvalidTimeStep_False( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); bool isValid = geometry->IsValidTimeStep(DimT); MITK_TEST_CONDITION(mitk::Equal(isValid, false), "Is invalid time Point correct minimum time point "); } void TimeStepToTimePoint_ImageValidTimeStep_TimePoint( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimePointType timePoint = geometry->TimeStepToTimePoint(DimT - 1); MITK_TEST_CONDITION(mitk::Equal(timePoint, DimT - 1), "Calculated right time Point for Time Step "); } void TimeStepToTimePoint_ImageInvalidTimeStep_TimePoint( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimePointType timePoint = geometry->TimeStepToTimePoint(DimT + 1); MITK_TEST_CONDITION(mitk::Equal(timePoint, DimT + 1), "Calculated right time Point for invalid Time Step "); } void TimePointToTimeStep_ImageValidTimePoint_TimePoint( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::TimeStepType timePoint = geometry->TimePointToTimeStep(DimT - 0.5); MITK_TEST_CONDITION(mitk::Equal(timePoint, DimT - 1), "Calculated right time step for valid time point"); } void TimePointToTimeStep_4DImageInvalidTimePoint_TimePoint(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::TimeGeometry::Pointer geometry = image->GetTimeGeometry(); mitk::TimeStepType timePoint = geometry->TimePointToTimeStep(DimT + 1.5); MITK_TEST_CONDITION(mitk::Equal(timePoint, DimT + 1), "Calculated right time step for invalid time point"); } void TimePointToTimeStep_4DImageNegativInvalidTimePoint_TimePoint(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::TimeGeometry::Pointer geometry = image->GetTimeGeometry(); mitk::TimePointType negativTimePoint = (-1.0 * DimT) - 1.5; mitk::TimeStepType timePoint = geometry->TimePointToTimeStep(negativTimePoint); - MITK_TEST_CONDITION(mitk::Equal(timePoint, 0), "Calculated right time step for negativ invalid time point"); + MITK_TEST_CONDITION(mitk::Equal(timePoint, 0), "Calculated right time step for negative invalid time point"); } void GetGeometryForTimeStep_BaseDataValidTimeStep_CorrectGeometry(mitk::BaseData *baseData, mitk::ScalarType inputX, mitk::ScalarType inputY, mitk::ScalarType inputZ, mitk::ScalarType outputX, mitk::ScalarType outputY, mitk::ScalarType outputZ, unsigned int DimT) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryForTimeStep(DimT - 1); MITK_TEST_CONDITION(geometry3D.IsNotNull(), "Non-zero geometry returned"); mitk::Point3D expectedPoint; expectedPoint[0] = outputX; expectedPoint[1] = outputY; expectedPoint[2] = outputZ; mitk::Point3D originalPoint; originalPoint[0] = inputX; originalPoint[1] = inputY; originalPoint[2] = inputZ; mitk::Point3D worldPoint; geometry3D->IndexToWorld(originalPoint, worldPoint); - MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Geometry transformation match expection. "); + MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Geometry transformation matches expectation. "); } void GetGeometryForTimeStep_ImageInvalidTimeStep_NullPointer( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryForTimeStep(DimT + 1); MITK_TEST_CONDITION(geometry3D.IsNull(), "Null-Pointer geometry returned"); } void GetGeometryForTimePoint_BaseDataValidTimePoint_CorrectGeometry(mitk::BaseData *baseData, mitk::ScalarType inputX, mitk::ScalarType inputY, mitk::ScalarType inputZ, mitk::ScalarType outputX, mitk::ScalarType outputY, mitk::ScalarType outputZ, unsigned int DimT) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryForTimePoint(DimT - 0.5); MITK_TEST_CONDITION(geometry3D.IsNotNull(), "Non-zero geometry returned"); mitk::Point3D expectedPoint; expectedPoint[0] = outputX; expectedPoint[1] = outputY; expectedPoint[2] = outputZ; mitk::Point3D originalPoint; originalPoint[0] = inputX; originalPoint[1] = inputY; originalPoint[2] = inputZ; mitk::Point3D worldPoint; geometry3D->IndexToWorld(originalPoint, worldPoint); - MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Geometry transformation match expection. "); + MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Geometry transformation matches expectation. "); } void GetGeometryForTimePoint_4DImageInvalidTimePoint_NullPointer(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::TimeGeometry::Pointer geometry = image->GetTimeGeometry(); mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryForTimePoint(DimT + 1); MITK_TEST_CONDITION(geometry3D.IsNull(), "Null-Pointer geometry returned with invalid time point"); } void GetGeometryForTimePoint_4DImageNEgativInvalidTimePoint_NullPointer(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::TimeGeometry::Pointer geometry = image->GetTimeGeometry(); mitk::TimePointType timePoint = (-1.0 * (DimT)) - 1; mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryForTimePoint(timePoint); - MITK_TEST_CONDITION(geometry3D.IsNull(), "Null-Pointer geometry returned with invalid negativ time point"); + MITK_TEST_CONDITION(geometry3D.IsNull(), "Null-Pointer geometry returned with invalid negative time point"); } void GetGeometryCloneForTimeStep_BaseDataValidTimeStep_CorrectGeometry(mitk::BaseData *baseData, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryCloneForTimeStep(DimT - 1); MITK_TEST_CONDITION(geometry3D.IsNotNull(), "Non-zero geometry returned"); mitk::Point3D expectedPoint; mitk::Point3D originalPoint; originalPoint[0] = 3; originalPoint[1] = 3; originalPoint[2] = 3; mitk::Point3D worldPoint; geometry3D->IndexToWorld(originalPoint, expectedPoint); mitk::Vector3D translationVector; translationVector[0] = 5; translationVector[1] = 8; translationVector[2] = 7; geometry3D->Translate(translationVector); geometry3D = geometry->GetGeometryForTimeStep(DimT - 1); geometry3D->IndexToWorld(originalPoint, worldPoint); MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint), "Geometry transformation not changed. "); } void GetGeometryCloneForTimeStep_ImageInvalidTimeStep_NullPointer( mitk::BaseData *baseData, unsigned int /*DimX*/, unsigned int /*DimY*/, unsigned int /*DimZ*/, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryCloneForTimeStep(DimT + 1); MITK_TEST_CONDITION(geometry3D.IsNull(), "Null-Pointer geometry returned"); } void SetTimeStepGeometry_BaseDataValidTimeStep_CorrectGeometry(mitk::BaseData *baseData, mitk::ScalarType scaleX, mitk::ScalarType scaleY, mitk::ScalarType scaleZ, unsigned int DimT) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryCloneForTimeStep(DimT - 1); MITK_TEST_CONDITION(geometry3D.IsNotNull(), "Non-zero geometry returned"); mitk::Vector3D translationVector; translationVector[0] = 5; translationVector[1] = 8; translationVector[2] = 7; geometry3D->Translate(translationVector); geometry->SetTimeStepGeometry(geometry3D, DimT - 1); mitk::Point3D expectedPoint; expectedPoint[0] = 3 * scaleX + 5; expectedPoint[1] = 3 * scaleY + 8; expectedPoint[2] = 3 * scaleZ + 7; mitk::Point3D originalPoint; originalPoint[0] = 3; originalPoint[1] = 3; originalPoint[2] = 3; mitk::Point3D worldPoint; geometry->GetGeometryForTimeStep(DimT - 1)->IndexToWorld(originalPoint, worldPoint); - MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Geometry transformation match expection. "); + MITK_TEST_CONDITION(mitk::Equal(worldPoint, expectedPoint, test_eps), "Geometry transformation matches expectation. "); } void Expand_BaseDataDoubleSize_SizeChanged(mitk::BaseData *baseData, unsigned int DimT) { mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); - MITK_TEST_CONDITION(geometry->CountTimeSteps() == DimT, "Number of time Steps match expection. "); + MITK_TEST_CONDITION(geometry->CountTimeSteps() == DimT, "Number of time Steps matches expectation. "); geometry->Expand(DimT * 2); - MITK_TEST_CONDITION(geometry->CountTimeSteps() == DimT * 2, "Number of time Steps match expection. "); + MITK_TEST_CONDITION(geometry->CountTimeSteps() == DimT * 2, "Number of time Steps matches expectation. "); mitk::BaseGeometry::Pointer geometry3D = geometry->GetGeometryForTimeStep(DimT * 2 - 1); MITK_TEST_CONDITION(geometry3D.IsNotNull(), "Non-zero geometry is generated. "); } void CheckBounds_BaseData_PointsAsExpected(mitk::BaseData *baseData, mitk::ScalarType minX, mitk::ScalarType minY, mitk::ScalarType minZ, mitk::ScalarType maxX, mitk::ScalarType maxY, mitk::ScalarType maxZ) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::Point3D expectedPoint; expectedPoint[0] = minX; expectedPoint[1] = minY; expectedPoint[2] = minZ; mitk::Point3D point = geometry->GetCornerPointInWorld(0); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 0 as expected "); point = geometry->GetCornerPointInWorld(true, true, true); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 0 as expected "); point = geometry->GetCornerPointInWorld(1); expectedPoint[0] = minX; expectedPoint[1] = minY; expectedPoint[2] = maxZ; MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "GBounding Point 1 as expected "); point = geometry->GetCornerPointInWorld(true, true, false); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 1 as expected "); point = geometry->GetCornerPointInWorld(2); expectedPoint[0] = minX; expectedPoint[1] = maxY; expectedPoint[2] = minZ; MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 2 as expected "); point = geometry->GetCornerPointInWorld(true, false, true); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 2 as expected "); point = geometry->GetCornerPointInWorld(3); expectedPoint[0] = minX; expectedPoint[1] = maxY; expectedPoint[2] = maxZ; MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 3 as expected "); point = geometry->GetCornerPointInWorld(true, false, false); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 3 as expected "); point = geometry->GetCornerPointInWorld(4); expectedPoint[0] = maxX; expectedPoint[1] = minY; expectedPoint[2] = minZ; MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 4 as expected "); point = geometry->GetCornerPointInWorld(false, true, true); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 4 as expected "); point = geometry->GetCornerPointInWorld(5); expectedPoint[0] = maxX; expectedPoint[1] = minY; expectedPoint[2] = maxZ; MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 5 as expected "); point = geometry->GetCornerPointInWorld(false, true, false); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 5 as expected "); point = geometry->GetCornerPointInWorld(6); expectedPoint[0] = maxX; expectedPoint[1] = maxY; expectedPoint[2] = minZ; MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 6 as expected "); point = geometry->GetCornerPointInWorld(false, false, true); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 6 as expected "); point = geometry->GetCornerPointInWorld(7); expectedPoint[0] = maxX; expectedPoint[1] = maxY; expectedPoint[2] = maxZ; MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 7 as expected "); point = geometry->GetCornerPointInWorld(false, false, false); MITK_TEST_CONDITION(mitk::Equal(expectedPoint, point, test_eps), "Bounding Point 7 as expected "); } void CheckLength_BaseData_AsExpected(mitk::BaseData *baseData, double length, double squareLength) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); double dimension = geometry->GetDiagonalLengthInWorld(); MITK_TEST_CONDITION(mitk::Equal(dimension, length, test_eps), "Length as expected "); dimension = geometry->GetDiagonalLength2InWorld(); MITK_TEST_CONDITION(mitk::Equal(dimension, squareLength, test_eps_square), "Square length as expected "); } void CheckPointInside_BaseDataPointInside_True(mitk::BaseData *baseData, mitk::ScalarType pointX, mitk::ScalarType pointY, mitk::ScalarType pointZ) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::Point3D expectedPoint; expectedPoint[0] = pointX; expectedPoint[1] = pointY; expectedPoint[2] = pointZ; bool isInside = geometry->IsWorldPointInside(expectedPoint); MITK_TEST_CONDITION(isInside, "Point is inside Image..."); } void CheckPointInside_BaseDataPointOutside_False(mitk::BaseData *baseData, mitk::ScalarType pointX, mitk::ScalarType pointY, mitk::ScalarType pointZ) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::Point3D expectedPoint; expectedPoint[0] = pointX; expectedPoint[1] = pointY; expectedPoint[2] = pointZ; bool isInside = geometry->IsWorldPointInside(expectedPoint); MITK_TEST_CONDITION(!isInside, "Point is outside Image..."); } void CheckBounds_Image_AsSet(unsigned int DimX, unsigned int DimY, unsigned int DimZ, unsigned int DimT) { mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(DimX, DimY, DimZ, DimT, 0.5, 0.33, 0.78, 100); mitk::TimeGeometry::Pointer geometry = image->GetTimeGeometry(); mitk::BoundingBox::BoundsArrayType bound = geometry->GetBoundsInWorld(); bool isEqual = true; isEqual = isEqual && mitk::Equal(bound[0], -0.5 * 0.5, test_eps); isEqual = isEqual && mitk::Equal(bound[1], 29.5 * 0.5, test_eps); isEqual = isEqual && mitk::Equal(bound[2], -0.5 * 0.33, test_eps); isEqual = isEqual && mitk::Equal(bound[3], 24.5 * 0.33, test_eps); isEqual = isEqual && mitk::Equal(bound[4], -0.5 * 0.78, test_eps); isEqual = isEqual && mitk::Equal(bound[5], 19.5 * 0.78, test_eps); MITK_TEST_CONDITION(isEqual, "Bounds as precalculated..."); } void CheckBounds_BaseData_AsSet(mitk::BaseData *baseData, mitk::ScalarType minBoundX, mitk::ScalarType maxBoundX, mitk::ScalarType minBoundY, mitk::ScalarType maxBoundY, mitk::ScalarType minBoundZ, mitk::ScalarType maxBoundZ) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); mitk::BoundingBox::BoundsArrayType bound = geometry->GetBoundsInWorld(); bool isEqual = true; isEqual = isEqual && mitk::Equal(bound[0], minBoundX); isEqual = isEqual && mitk::Equal(bound[1], maxBoundX); isEqual = isEqual && mitk::Equal(bound[2], minBoundY); isEqual = isEqual && mitk::Equal(bound[3], maxBoundY); isEqual = isEqual && mitk::Equal(bound[4], minBoundZ); isEqual = isEqual && mitk::Equal(bound[5], maxBoundZ); MITK_TEST_CONDITION(isEqual, "Bounds as precalculated..."); } void CheckExtent_BaseData_AsSet(mitk::BaseData *baseData, double extentX, double extentY, double extentZ) { baseData->Update(); mitk::TimeGeometry::Pointer geometry = baseData->GetTimeGeometry(); bool isEqual = true; isEqual = isEqual && mitk::Equal(geometry->GetExtentInWorld(0), extentX, test_eps); // 30*0.5); isEqual = isEqual && mitk::Equal(geometry->GetExtentInWorld(1), extentY, test_eps); // 25*0.33); isEqual = isEqual && mitk::Equal(geometry->GetExtentInWorld(2), extentZ, test_eps); // 20*0.78); MITK_TEST_CONDITION(isEqual, "Extent as precalculated..."); } mitk::PointSet::Pointer makePointset() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::Point3D pointA, pointB, pointC; pointA.Fill(1); pointB.Fill(2); pointC.Fill(3); pointSet->SetPoint(1, pointA); pointSet->SetPoint(2, pointB); pointSet->SetPoint(3, pointC); pointSet->Update(); MITK_INFO << pointSet->GetPoint(0); MITK_INFO << pointSet->GetPoint(1); MITK_INFO << pointSet->GetPoint(2); MITK_INFO << pointSet->GetPoint(3); mitk::PointSet::Pointer pointSet2 = pointSet->Clone(); MITK_INFO << pointSet2->GetPoint(0); MITK_INFO << pointSet2->GetPoint(1); MITK_INFO << pointSet2->GetPoint(2); MITK_INFO << pointSet2->GetPoint(3); return pointSet; } }; int mitkTimeGeometryTest(int /*argc*/, char * /*argv*/ []) { MITK_TEST_BEGIN(mitkTimeGeometryTest); mitkTimeGeometryTestClass testClass; MITK_TEST_OUTPUT(<< "Test for 3D image"); mitk::Image::Pointer image = mitk::ImageGenerator::GenerateRandomImage(30, 25, 20, 1, 0.5, 0.33, 0.78, 100); testClass.Translation_Image_MovedOrigin(30, 25, 20, 1); testClass.Rotate_Image_RotatedPoint(image->Clone(), 30, 25, 20, 1); testClass.Scale_Image_ScaledPoint(30, 25, 20, 1); testClass.CountTimeSteps_Image_ReturnDimT(image->Clone(), 30, 25, 20, 1); testClass.GetMinimumTimePoint_3DImage_Min(image->Clone(), 30, 25, 20, 1); testClass.GetMaximumTimePoint_3DImage_Max(image->Clone(), 30, 25, 20, 1); testClass.GetTimeBounds_3DImage_ZeroAndDimT(image->Clone(), 30, 25, 20, 1); testClass.IsValidTimePoint_ImageValidTimePoint_True(image->Clone(), 30, 25, 20, 1); testClass.IsValidTimeStep_ImageValidTimeStep_True(image->Clone(), 30, 25, 20, 1); testClass.IsValidTimeStep_ImageNegativInvalidTimeStep_False(image->Clone(), 30, 25, 20, 1); testClass.IsValidTimeStep_ImageInvalidTimeStep_False(image->Clone(), 30, 25, 20, 1); testClass.TimeStepToTimePoint_ImageValidTimeStep_TimePoint(image->Clone(), 30, 25, 20, 1); testClass.TimeStepToTimePoint_ImageInvalidTimeStep_TimePoint(image->Clone(), 30, 25, 20, 1); testClass.TimePointToTimeStep_ImageValidTimePoint_TimePoint(image->Clone(), 30, 25, 20, 1); testClass.GetGeometryForTimeStep_BaseDataValidTimeStep_CorrectGeometry( image->Clone(), 3, 3, 3, 3 * 0.5, 3 * 0.33, 3 * 0.78, 1); testClass.GetGeometryForTimeStep_ImageInvalidTimeStep_NullPointer(image->Clone(), 30, 25, 20, 1); testClass.GetGeometryForTimePoint_BaseDataValidTimePoint_CorrectGeometry( image->Clone(), 3, 3, 3, 3 * 0.5, 3 * 0.33, 3 * 0.78, 1); testClass.GetGeometryCloneForTimeStep_BaseDataValidTimeStep_CorrectGeometry(image->Clone(), 1); testClass.GetGeometryCloneForTimeStep_ImageInvalidTimeStep_NullPointer(image->Clone(), 30, 25, 20, 1); testClass.SetTimeStepGeometry_BaseDataValidTimeStep_CorrectGeometry(image->Clone(), 0.5, 0.33, 0.78, 1); testClass.Expand_BaseDataDoubleSize_SizeChanged(image->Clone(), 1); testClass.CheckBounds_BaseData_PointsAsExpected( image->Clone(), -0.5 * 0.5, -0.5 * 0.33, -0.5 * 0.78, 29.5 * 0.5, 24.5 * 0.33, 19.5 * 0.78); testClass.CheckLength_BaseData_AsExpected(image->Clone(), 23.160796233014466, 536.42248214721712); testClass.CheckPointInside_BaseDataPointInside_True(image->Clone(), 10, 5, 5); testClass.CheckPointInside_BaseDataPointOutside_False(image->Clone(), 100, 500, 100); testClass.CheckBounds_Image_AsSet(30, 25, 20, 1); testClass.CheckExtent_BaseData_AsSet(image->Clone(), 30 * 0.5, 25 * 0.33, 20 * 0.78); MITK_TEST_OUTPUT(<< "Test for 2D image"); image = mitk::ImageGenerator::GenerateRandomImage(30, 25, 1, 1, 0.5, 0.33, 0.78, 100); testClass.Translation_Image_MovedOrigin(30, 25, 1, 1); testClass.Rotate_Image_RotatedPoint(image->Clone(), 30, 25, 1, 1); testClass.Scale_Image_ScaledPoint(30, 25, 1, 1); testClass.CountTimeSteps_Image_ReturnDimT(image->Clone(), 30, 25, 1, 1); testClass.GetMinimumTimePoint_3DImage_Min(image->Clone(), 30, 25, 1, 1); testClass.GetMaximumTimePoint_3DImage_Max(image->Clone(), 30, 25, 1, 1); testClass.GetTimeBounds_3DImage_ZeroAndDimT(image->Clone(), 30, 25, 1, 1); testClass.IsValidTimePoint_ImageValidTimePoint_True(image->Clone(), 30, 25, 1, 1); testClass.IsValidTimeStep_ImageValidTimeStep_True(image->Clone(), 30, 25, 1, 1); testClass.IsValidTimeStep_ImageNegativInvalidTimeStep_False(image->Clone(), 30, 25, 1, 1); testClass.IsValidTimeStep_ImageInvalidTimeStep_False(image->Clone(), 30, 25, 1, 1); testClass.TimeStepToTimePoint_ImageValidTimeStep_TimePoint(image->Clone(), 30, 25, 1, 1); testClass.TimeStepToTimePoint_ImageInvalidTimeStep_TimePoint(image->Clone(), 30, 25, 1, 1); testClass.TimePointToTimeStep_ImageValidTimePoint_TimePoint(image->Clone(), 30, 25, 1, 1); testClass.GetGeometryForTimeStep_BaseDataValidTimeStep_CorrectGeometry( image->Clone(), 3, 3, 3, 3 * 0.5, 3 * 0.33, 3 * 0.78, 1); testClass.GetGeometryForTimeStep_ImageInvalidTimeStep_NullPointer(image->Clone(), 30, 25, 1, 1); testClass.GetGeometryForTimePoint_BaseDataValidTimePoint_CorrectGeometry( image->Clone(), 3, 3, 3, 3 * 0.5, 3 * 0.33, 3 * 0.78, 1); testClass.GetGeometryCloneForTimeStep_BaseDataValidTimeStep_CorrectGeometry(image->Clone(), 1); testClass.GetGeometryCloneForTimeStep_ImageInvalidTimeStep_NullPointer(image->Clone(), 30, 25, 1, 1); testClass.SetTimeStepGeometry_BaseDataValidTimeStep_CorrectGeometry(image->Clone(), 0.5, 0.33, 0.78, 1); testClass.Expand_BaseDataDoubleSize_SizeChanged(image->Clone(), 1); testClass.CheckBounds_BaseData_PointsAsExpected( image->Clone(), -0.5 * 0.5, -0.5 * 0.33, -0.5 * 0.78, 29.5 * 0.5, 24.5 * 0.33, 0.5 * 0.78); testClass.CheckLength_BaseData_AsExpected(image->Clone(), 17.1368287615, 293.6709); testClass.CheckPointInside_BaseDataPointInside_True(image->Clone(), 10, 5, 0); testClass.CheckPointInside_BaseDataPointOutside_False(image->Clone(), 100, 500, 0.5); testClass.CheckExtent_BaseData_AsSet(image->Clone(), 30 * 0.5, 25 * 0.33, 1 * 0.78); MITK_TEST_OUTPUT(<< "Test for 3D+time image"); image = mitk::ImageGenerator::GenerateRandomImage(30, 25, 20, 5, 0.5, 0.33, 0.78, 100); testClass.Translation_Image_MovedOrigin(30, 25, 20, 5); // Test with 3D+t-Image testClass.Rotate_Image_RotatedPoint(image->Clone(), 30, 25, 20, 5); // Test with 3D+t-Image testClass.Scale_Image_ScaledPoint(30, 25, 20, 5); // Test with 3D+t-Image testClass.CountTimeSteps_Image_ReturnDimT(image->Clone(), 30, 25, 20, 5); testClass.GetMinimumTimePoint_4DBaseData_Zero(image->Clone(), 5); testClass.GetMaximumTimePoint_4DBaseData_DimT(image->Clone(), 5); testClass.GetTimeBounds_4DImage_ZeroAndDimT(30, 25, 20, 5); testClass.IsValidTimePoint_ImageValidTimePoint_True(image->Clone(), 30, 25, 20, 5); testClass.IsValidTimePoint_ImageNegativInvalidTimePoint_False(30, 25, 20, 5); testClass.IsValidTimePoint_ImageInvalidTimePoint_False(30, 25, 20, 5); testClass.IsValidTimeStep_ImageValidTimeStep_True(image->Clone(), 30, 25, 20, 5); testClass.IsValidTimeStep_ImageNegativInvalidTimeStep_False(image->Clone(), 30, 25, 20, 5); testClass.IsValidTimeStep_ImageInvalidTimeStep_False(image->Clone(), 30, 25, 20, 5); testClass.TimeStepToTimePoint_ImageValidTimeStep_TimePoint(image->Clone(), 30, 25, 20, 5); testClass.TimeStepToTimePoint_ImageInvalidTimeStep_TimePoint(image->Clone(), 30, 25, 20, 5); testClass.TimePointToTimeStep_ImageValidTimePoint_TimePoint(image->Clone(), 30, 25, 20, 5); testClass.TimePointToTimeStep_4DImageInvalidTimePoint_TimePoint(30, 25, 20, 5); testClass.TimePointToTimeStep_4DImageNegativInvalidTimePoint_TimePoint(30, 25, 20, 5); testClass.GetGeometryForTimeStep_BaseDataValidTimeStep_CorrectGeometry( image->Clone(), 3, 3, 3, 3 * 0.5, 3 * 0.33, 3 * 0.78, 5); testClass.GetGeometryForTimeStep_ImageInvalidTimeStep_NullPointer(image->Clone(), 30, 25, 20, 5); testClass.GetGeometryForTimePoint_BaseDataValidTimePoint_CorrectGeometry( image->Clone(), 3, 3, 3, 3 * 0.5, 3 * 0.33, 3 * 0.78, 5); testClass.GetGeometryForTimePoint_4DImageInvalidTimePoint_NullPointer(30, 25, 20, 5); testClass.GetGeometryForTimePoint_4DImageNEgativInvalidTimePoint_NullPointer(30, 25, 20, 5); testClass.GetGeometryCloneForTimeStep_BaseDataValidTimeStep_CorrectGeometry(image->Clone(), 5); testClass.GetGeometryCloneForTimeStep_ImageInvalidTimeStep_NullPointer(image->Clone(), 30, 25, 20, 5); testClass.SetTimeStepGeometry_BaseDataValidTimeStep_CorrectGeometry(image->Clone(), 0.5, 0.33, 0.78, 5); testClass.Expand_BaseDataDoubleSize_SizeChanged(image->Clone(), 5); testClass.CheckBounds_BaseData_PointsAsExpected( image->Clone(), -0.5 * 0.5, -0.5 * 0.33, -0.5 * 0.78, 29.5 * 0.5, 24.5 * 0.33, 19.5 * 0.78); testClass.CheckLength_BaseData_AsExpected(image->Clone(), 23.160796233014466, 536.42248214721712); testClass.CheckPointInside_BaseDataPointInside_True(image->Clone(), 10, 5, 5); testClass.CheckPointInside_BaseDataPointOutside_False(image->Clone(), 100, 100, 500); testClass.CheckBounds_Image_AsSet(30, 25, 20, 5); testClass.CheckExtent_BaseData_AsSet(image->Clone(), 30 * 0.5, 25 * 0.33, 20 * 0.78); /* MITK_TEST_OUTPUT(<< "Test for 2D+time image"); testClass.Translation_Image_MovedOrigin(30,25,1 ,5); // Test with 2D+t-Image testClass.Rotate_Image_RotatedPoint(30,25,1 ,5); // Test with 2D+t-Image testClass.Scale_Image_ScaledPoint(30,25,1 ,5); // Test with 2D+t-Image */ mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); mitk::Point3D pointA, pointB, pointC; pointA.Fill(1); pointB.Fill(2); pointC.Fill(3); pointSet->SetPoint(0, pointA); pointSet->SetPoint(1, pointB); pointSet->SetPoint(2, pointC); testClass.CountTimeSteps_Image_ReturnDimT(pointSet->Clone(), 30, 25, 20, 1); // testClass.GetMinimumTimePoint_3DImage_Min(pointSet->Clone(),30,25,20,1); // testClass.GetMaximumTimePoint_3DImage_Max(pointSet->Clone(),30,25,20,1); // testClass.GetTimeBounds_3DImage_ZeroAndDimT(pointSet->Clone(),30,25,20,1); testClass.IsValidTimePoint_ImageValidTimePoint_True(pointSet->Clone(), 30, 25, 20, 1); testClass.IsValidTimeStep_ImageValidTimeStep_True(pointSet->Clone(), 30, 25, 20, 1); testClass.IsValidTimeStep_ImageNegativInvalidTimeStep_False(pointSet->Clone(), 30, 25, 20, 1); testClass.IsValidTimeStep_ImageInvalidTimeStep_False(pointSet->Clone(), 30, 25, 20, 1); testClass.TimeStepToTimePoint_ImageValidTimeStep_TimePoint(pointSet->Clone(), 30, 25, 20, 1); testClass.TimeStepToTimePoint_ImageInvalidTimeStep_TimePoint(pointSet->Clone(), 30, 25, 20, 1); testClass.TimePointToTimeStep_ImageValidTimePoint_TimePoint(pointSet->Clone(), 30, 25, 20, 1); testClass.GetGeometryForTimeStep_BaseDataValidTimeStep_CorrectGeometry(pointSet->Clone(), 3, 3, 3, 3, 3, 3, 1); testClass.GetGeometryForTimeStep_ImageInvalidTimeStep_NullPointer(pointSet->Clone(), 30, 25, 20, 1); testClass.GetGeometryForTimePoint_BaseDataValidTimePoint_CorrectGeometry(pointSet->Clone(), 3, 3, 3, 3, 3, 3, 1); testClass.GetGeometryCloneForTimeStep_BaseDataValidTimeStep_CorrectGeometry(pointSet->Clone(), 1); testClass.GetGeometryCloneForTimeStep_ImageInvalidTimeStep_NullPointer(pointSet->Clone(), 30, 25, 20, 1); testClass.SetTimeStepGeometry_BaseDataValidTimeStep_CorrectGeometry(pointSet->Clone(), 1, 1, 1, 1); testClass.Expand_BaseDataDoubleSize_SizeChanged(pointSet->Clone(), 1); testClass.CheckBounds_BaseData_PointsAsExpected(pointSet->Clone(), 1, 1, 1, 3, 3, 3); testClass.CheckLength_BaseData_AsExpected(pointSet->Clone(), 3.46410161, 12); testClass.CheckPointInside_BaseDataPointInside_True(pointSet->Clone(), 2, 2, 3); testClass.CheckPointInside_BaseDataPointOutside_False(pointSet->Clone(), 4, 5, 1); testClass.CheckBounds_BaseData_AsSet(pointSet->Clone(), 1, 3, 1, 3, 1, 3); testClass.CheckExtent_BaseData_AsSet(pointSet->Clone(), 2, 2, 2); MITK_TEST_END(); return EXIT_SUCCESS; } diff --git a/Modules/Core/test/mitkVerboseLimitedLinearUndoTest.cpp b/Modules/Core/test/mitkVerboseLimitedLinearUndoTest.cpp index f5a00644ec..b768bddb07 100644 --- a/Modules/Core/test/mitkVerboseLimitedLinearUndoTest.cpp +++ b/Modules/Core/test/mitkVerboseLimitedLinearUndoTest.cpp @@ -1,132 +1,132 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkInteractionConst.h" #include "mitkOperation.h" #include "mitkUndoController.h" #include "mitkVerboseLimitedLinearUndo.h" #include "mitkTestingMacros.h" #include int g_GlobalCounter = 0; namespace mitk { /** * @brief Class to check that the destructor of object Operation is called and memory freed **/ class TestOperation : public Operation { public: TestOperation(OperationType operationType) : Operation(operationType) { g_GlobalCounter++; }; ~TestOperation() override { g_GlobalCounter--; }; }; } // namespace /** * @brief Test of the LimitedLinearUndo object * * This test was motivated by bug 3248 which had to check memory leakage * while using mitkOperations within the UndoMechanism. * OperationObjects are added to the UndoController and stored within * two lists (m_UndoList and m_RedoList) inside LimitedLinearUndo and * derived from this VerboseLimitedLinearUndo. When using Undo during * runtime operations are moved from UndoList to RedoList. In case of * a new interaction, causing new operations to be stored in the UndoList * the RedoList needs to be cleared. For this, the operations and all * connected objects need to be deleted and memory to be freed. * And this what this test checks! * * argc and argv are the command line parameters which were passed to * the ADD_TEST command in the CMakeLists.txt file. For the automatic * tests, argv is either empty for the simple tests or contains the filename * of a test image for the image tests (see CMakeLists.txt). */ int mitkVerboseLimitedLinearUndoTest(int /* argc */, char * /*argv*/ []) { // always start with this! MITK_TEST_BEGIN("VerboseLimitedLinearUndo") // an UndoController for the management auto myUndoController = new mitk::UndoController(); // set model, even if it is verboseLimitedLinearUndo by default; this already is tested by UndoControllerTest! myUndoController->SwitchUndoModel(mitk::UndoController::VERBOSE_LIMITEDLINEARUNDO); for (int i = 0; i < 2; i++) { auto doOp = new mitk::TestOperation(mitk::OpTEST); auto undoOp = new mitk::TestOperation(mitk::OpTEST); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(nullptr, doOp, undoOp, "Test"); myUndoController->SetOperationEvent(operationEvent); // increase the ID to separate the operationEvents from each other. Otherwise they would be undone all together at // once. mitk::OperationEvent::IncCurrObjectEventId(); } - // now 2 * 2 operation should have been instanciated + // now 2 * 2 operation should have been instantiated MITK_TEST_CONDITION_REQUIRED(g_GlobalCounter == 4, "checking initialization of mitkOperation"); // undo one operation; 1 operationEvent element in undo list, 1 in Redo list myUndoController->Undo(); // sending two new OperationEvents: RedoList should be deleted and memory of operations freed for (int i = 0; i < 2; i++) { auto doOp = new mitk::TestOperation(mitk::OpTEST); auto undoOp = new mitk::TestOperation(mitk::OpTEST); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(nullptr, doOp, undoOp, "Test"); myUndoController->SetOperationEvent(operationEvent); // increase the ID to separate the operationEvents from each other. Otherwise they would be undone all together at // once. mitk::OperationEvent::IncCurrObjectEventId(); } // 2 operations should have been deleted, 4 should have been added MITK_TEST_CONDITION_REQUIRED(g_GlobalCounter == 6, "checking adding of operations"); // two operations to RedoList myUndoController->Undo(); myUndoController->ClearRedoList(); // one operationEvent containing 2 operations should have been deleted MITK_TEST_CONDITION_REQUIRED(g_GlobalCounter == 4, "checking deleting RedoList"); // clear all myUndoController->Clear(); MITK_TEST_CONDITION_REQUIRED(g_GlobalCounter == 0, "checking deleting all operations in UndoModel"); // sending two new OperationEvents for (int i = 0; i < 2; i++) { auto doOp = new mitk::TestOperation(mitk::OpTEST); auto undoOp = new mitk::TestOperation(mitk::OpTEST); mitk::OperationEvent *operationEvent = new mitk::OperationEvent(nullptr, doOp, undoOp, "Test"); myUndoController->SetOperationEvent(operationEvent); // increase the ID to separate the operationEvents from each other. Otherwise they would be undone all together at // once. mitk::OperationEvent::IncCurrObjectEventId(); } MITK_TEST_CONDITION_REQUIRED(g_GlobalCounter == 4, "checking added operations in UndoModel"); delete myUndoController; // after deleting UndoController g_GlobalCounter will still be 4 because m_CurrentUndoModel inside myUndoModel is a // static singleton MITK_TEST_CONDITION_REQUIRED(g_GlobalCounter == 4, "checking singleton UndoModel"); // always end with this! MITK_TEST_END() // operations will be deleted after terminating the application }