diff --git a/Utilities/ITK/CMake/CTestCustom.cmake.in b/Utilities/ITK/CMake/CTestCustom.cmake.in index 3b6e5afae88b322d2c2b3fdeca4c41ba51838f0a..fb439d3d85c48b47749bbc9f673fd80cdd7dc99e 100644 --- a/Utilities/ITK/CMake/CTestCustom.cmake.in +++ b/Utilities/ITK/CMake/CTestCustom.cmake.in @@ -90,8 +90,10 @@ set(CTEST_CUSTOM_WARNING_EXCEPTION ".*include.opencv2.*warning.*" ".*core.vidl.*warning.*" ".*core.vnl.vnl_matrix_fixed.h.*warning.*" - # DCMTK + # ExternalProject: Git writes status to stderr + "Cloning into.*" "Note: checking out.*" + "HEAD is now at.*" # FFTW ExternalProject ".*fftw[fd]/src/fftw[fd]./*" "libtool: install: warning: relinking .libfftw3f?_threads.la." diff --git a/Utilities/ITK/CMake/FindKWStyle.cmake b/Utilities/ITK/CMake/FindKWStyle.cmake index 9a4bc46b316d791278d5037a76b097afedb5b76f..6f912cbfdee6a41428ce1d08ad47a347f8ca10f4 100644 --- a/Utilities/ITK/CMake/FindKWStyle.cmake +++ b/Utilities/ITK/CMake/FindKWStyle.cmake @@ -31,12 +31,19 @@ if(KWSTYLE_EXECUTABLE) ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE ) - string(REPLACE - "Version: " - "" - KWSTYLE_VERSION_STRING - ${KWSTYLE_VERSION_STRING} - ) + if(KWSTYLE_VERSION_STRING) + # string(REPLACE ..) fails if the input is an empty string + string(REPLACE + "Version: " + "" + KWSTYLE_VERSION_STRING + ${KWSTYLE_VERSION_STRING} + ) + else(KWSTYLE_VERSION_STRING) + # CMake's find_package_handle_standard_args has a bug where the + # version empty string ("") is always acceptable + set(KWSTYLE_VERSION_STRING "?") + endif(KWSTYLE_VERSION_STRING) endif(KWSTYLE_EXECUTABLE) include(FindPackageHandleStandardArgs) diff --git a/Utilities/ITK/CMake/ITKExternalData.cmake b/Utilities/ITK/CMake/ITKExternalData.cmake index 40d33ca248394ae43f36577dbb12b981b9ee8171..10efbca041050a2c9dec7829b6297a0d2f4f3760 100644 --- a/Utilities/ITK/CMake/ITKExternalData.cmake +++ b/Utilities/ITK/CMake/ITKExternalData.cmake @@ -27,16 +27,18 @@ set(ExternalData_URL_TEMPLATES "" CACHE STRING "Additional URL templates for the ExternalData CMake script to look for testing data. E.g. file:///var/bigharddrive/%(algo)/%(hash)") mark_as_advanced(ExternalData_URL_TEMPLATES) -list(APPEND ExternalData_URL_TEMPLATES - # Data published by MIDAS - "http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" +if(NOT ITK_FORBID_DOWNLOADS) + list(APPEND ExternalData_URL_TEMPLATES + # Data published by MIDAS + "http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" - # Data published by developers using git-gerrit-push. - "http://www.itk.org/files/ExternalData/%(algo)/%(hash)" + # Data published by developers using git-gerrit-push. + "http://www.itk.org/files/ExternalData/%(algo)/%(hash)" - # Mirror supported by the Slicer community. - "http://slicer.kitware.com/midas3/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" - ) + # Mirror supported by the Slicer community. + "http://slicer.kitware.com/midas3/api/rest?method=midas.bitstream.download&checksum=%(hash)&algorithm=%(algo)" + ) +endif() # Tell ExternalData commands to transform raw files to content links. # TODO: Condition this feature on presence of our pre-commit hook. diff --git a/Utilities/ITK/CMake/ITKGroups.cmake b/Utilities/ITK/CMake/ITKGroups.cmake index 7b3d906fe37aa70d47c76941185d084971d46138..6e3912417e9f4a1d61dc020770b356fa69c809fc 100644 --- a/Utilities/ITK/CMake/ITKGroups.cmake +++ b/Utilities/ITK/CMake/ITKGroups.cmake @@ -1,5 +1,18 @@ # Set a list of group names -set(group_list Core IO Filtering Registration Segmentation Numerics Video ThirdParty Bridge Nonunit Compatibility) +set(group_list + Core + IO + Filtering + Registration + Segmentation + Numerics + Video + ThirdParty + Bridge + Nonunit + Compatibility + Remote + ) set(Core_documentation "This group of modules contain the toolkit framework used by other modules. There are common base classes for data objects and process @@ -44,22 +57,33 @@ used by other ITK modules.") set(Nonunit_documentation "This group of modules are intended to make use of an extensive set of the toolkit modules.") -# Set a module name list for each group +set(Remote_documentation "This group of modules is for ITK based code that have +additional third-party dependencies not bundled with the toolkit, +new algorithms or implementations seeking greater exposure and adoption, +algorithms that hope to eventually be integrated into the toolkit, +niche algorithms with limited application, and Modules in progress that do not +yet have the test coverage and cross-platform standards required by the main toolkit. +The modules are OFF by default in ITK's CMake configuration. +Note that these modules do get the same level of support and backwards +compatibility as other modules in the toolkit.") + +#------------------------------------------------ +# Find the modules in each group and the module name line in itk-module.cmake foreach( group ${group_list} ) - set( ${group}_module_list ) - file( GLOB_RECURSE _module_files ${ITK_SOURCE_DIR}/Modules/${group}/itk-module.cmake ) - foreach( _module_f ${_module_files} ) - get_filename_component (module_file_dir ${_module_f} PATH) - if (NOT EXISTS "${module_file_dir}/itk-module-init.cmake") - file( STRINGS ${_module_f} _module_line REGEX "itk_module[ \n]*\\([ \n]*ITK[A-Za-z0-9]*" ) - string( REGEX MATCH "ITK[A-Za-z0-9]*" _module_name ${_module_line} ) - list( APPEND ${group}_module_list ${_module_name} ) - endif() + set( _${group}_module_list ) + file( GLOB_RECURSE _${group}_module_files ${ITK_SOURCE_DIR}/Modules/${group}/itk-module.cmake ) + foreach( _module_file ${_${group}_module_files} ) + file( STRINGS ${_module_file} _module_line REGEX "itk_module[ \n]*\\([ \n]*[A-Za-z0-9]*" ) + string( REGEX MATCH "(\\([ \n]*)([A-Za-z0-9]*)" _module_name ${_module_line} ) + set( _module_name ${CMAKE_MATCH_2} ) + set( _${_module_name}_module_line ${_module_line} ) + list( APPEND _${group}_module_list ${_module_name} ) endforeach() endforeach() #------------------------------------------------ -#------------------------------------------------ +# Set up Doxygen Group descriptions + set( group_list_dox ) foreach(group ${group_list} ) set( group_list_dox @@ -70,7 +94,7 @@ foreach(group ${group_list} ) ${${group}_documentation} */\n" ) - foreach(mod ${${group}_module_list} ) + foreach(mod ${_${group}_module_list} ) set( group_list_dox "${group_list_dox} /** \\defgroup ${mod} Module ${mod} @@ -87,6 +111,22 @@ configure_file( #------------------------------------------------ # Turn on the ITK_BUILD option for each group + +# Set a module name list for each group and exclude +# Modules that should be OFF +foreach( group ${group_list} ) + set( _${group}_on_module_list ) + list( LENGTH _${group}_module_list _num_modules ) + set( _current_module 0 ) + while( ${_current_module} LESS ${_num_modules} ) + list( GET _${group}_module_list ${_current_module} _module_name ) + if( NOT ITK_MODULE_${_module_name}_EXCLUDE_FROM_DEFAULT ) + list( APPEND _${group}_on_module_list ${_module_name} ) + endif() + math( EXPR _current_module "${_current_module} + 1" ) + endwhile() +endforeach() + if("$ENV{DASHBOARD_TEST_FROM_CTEST}" STREQUAL "") # developer build option(ITKGroup_Core "Request building core modules" ON) @@ -94,7 +134,7 @@ endif() foreach( group ${group_list}) option(ITKGroup_${group} "Request building ${group} modules" OFF) if (ITKGroup_${group}) - foreach (itk-module ${${group}_module_list} ) + foreach (itk-module ${_${group}_on_module_list} ) list(APPEND ITK_MODULE_${itk-module}_REQUEST_BY ITKGroup_${group}) endforeach() endif() diff --git a/Utilities/ITK/CMake/ITKModuleDoxygen.cmake b/Utilities/ITK/CMake/ITKModuleDoxygen.cmake index 8399a8a3ceb63cd04835ccfb6f7ad9a1fb16c48e..e42900225e2804e598d104ec8f1740494d68576d 100644 --- a/Utilities/ITK/CMake/ITKModuleDoxygen.cmake +++ b/Utilities/ITK/CMake/ITKModuleDoxygen.cmake @@ -12,7 +12,7 @@ macro( itk_module_doxygen _name ) # _content defines the content of the ${_name}.dox file set( _content "/**\n" ) - set( _content "${_content} \\defgroup ${_name} ${_name} \n" ) + set( _content "${_content} \\defgroup ${_name} Module ${_name} \n" ) set( _content "${_content} ${ITK_MODULE_${_name}_DESCRIPTION} \n" ) set( _content "${_content} \\par Dependencies:\n" ) diff --git a/Utilities/ITK/CMake/ITKModuleEnablement.cmake b/Utilities/ITK/CMake/ITKModuleEnablement.cmake index 0ad6156fbd882722585ced3182e599452077e7e5..a615392dc94556633a3f5ca82269b8699a226878 100644 --- a/Utilities/ITK/CMake/ITKModuleEnablement.cmake +++ b/Utilities/ITK/CMake/ITKModuleEnablement.cmake @@ -76,6 +76,12 @@ endforeach() # options or ITKGroup_* options. option(ITK_BUILD_DEFAULT_MODULES "Build the default ITK modules." ON) +#---------------------------------------------------------------------- +# Provide an option to build the tests of dependencies of a module when +# BUILD_TESTING is ON. +option(ITK_BUILD_ALL_MODULES_FOR_TESTS "Build the tests of module dependencies." OFF) +mark_as_advanced(ITK_BUILD_ALL_MODULES_FOR_TESTS) + # To maintain backward compatibility if(DEFINED ITK_BUILD_ALL_MODULES) message(WARNING "ITK_BUILD_ALL_MODULES is deprecated, please remove this entry from the CMake " @@ -112,7 +118,7 @@ macro(itk_module_enable itk-module _needed_by) foreach(dep IN LISTS ITK_MODULE_${itk-module}_DEPENDS) itk_module_enable(${dep} ${itk-module}) endforeach() - if(${itk-module}_TESTED_BY) + if(${itk-module}_TESTED_BY AND (ITK_BUILD_DEFAULT_MODULES OR ITK_BUILD_ALL_MODULES_FOR_TESTS OR Module_${itk-module})) itk_module_enable(${${itk-module}_TESTED_BY} "") endif() endif() diff --git a/Utilities/ITK/CMake/ITKModuleHeaderTest.cmake b/Utilities/ITK/CMake/ITKModuleHeaderTest.cmake index 292289c3338e4a7fda13b8c91b3be3ce715024f8..90c0d1c7d9583c0624237bc74b99463ac9b619e7 100644 --- a/Utilities/ITK/CMake/ITKModuleHeaderTest.cmake +++ b/Utilities/ITK/CMake/ITKModuleHeaderTest.cmake @@ -23,6 +23,7 @@ macro( itk_module_headertest _name ) if( NOT ${_name}_THIRD_PARTY AND EXISTS ${${_name}_SOURCE_DIR}/include AND PYTHON_EXECUTABLE + AND NOT (PYTHON_VERSION_STRING VERSION_LESS 2.6) AND NOT (${_name} STREQUAL ITKTestKernel) AND NOT (CMAKE_GENERATOR MATCHES "^Visual Studio 10.*")) diff --git a/Utilities/ITK/CMake/ITKModuleMacros.cmake b/Utilities/ITK/CMake/ITKModuleMacros.cmake index 510a7ec19d1e715583ed043478d4805c6ea3e86b..c32a29eda33a0af9b7301d55e14d07567cc6f00f 100644 --- a/Utilities/ITK/CMake/ITKModuleMacros.cmake +++ b/Utilities/ITK/CMake/ITKModuleMacros.cmake @@ -6,6 +6,11 @@ include(${_ITKModuleMacros_DIR}/ITKModuleAPI.cmake) include(${_ITKModuleMacros_DIR}/ITKModuleDoxygen.cmake) include(${_ITKModuleMacros_DIR}/ITKModuleHeaderTest.cmake) +# With Apple's GGC <=4.2 and LLVM-GCC <=4.2 visibility of template +# don't work. Set the option to off and hide it. +if(APPLE AND CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.3") + set( USE_COMPILER_HIDDEN_VISIBILITY OFF CACHE INTERNAL "" ) +endif() include(GenerateExportHeader) if(ITK_CPPCHECK_TEST) diff --git a/Utilities/ITK/CMake/ITKModuleRemote.cmake b/Utilities/ITK/CMake/ITKModuleRemote.cmake index 5241728c54884b9d5b3376ae5f562a51e03a360a..34b8a8ea66dc628a1d057fe357f32b80a045c564 100644 --- a/Utilities/ITK/CMake/ITKModuleRemote.cmake +++ b/Utilities/ITK/CMake/ITKModuleRemote.cmake @@ -67,7 +67,7 @@ function(_git_update git_executable git_repository git_tag module_dir) # Is the hash checkout out that we want? if(NOT ("${tag_hash}" STREQUAL "${head_hash}")) execute_process( - COMMAND "${git_executable}" fetch + COMMAND "${git_executable}" fetch "${git_repository}" WORKING_DIRECTORY "${module_dir}" RESULT_VARIABLE error_code ) @@ -133,6 +133,7 @@ function(itk_fetch_module _name _description) endif() if(Module_${_name}) + itk_download_attempt_check(Module_${_name}) include(CMakeParseArguments) cmake_parse_arguments(_fetch_options "" "GIT_REPOSITORY;GIT_TAG" "" ${ARGN}) find_package(Git) diff --git a/Utilities/ITK/CMake/ITKSetStandardCompilerFlags.cmake b/Utilities/ITK/CMake/ITKSetStandardCompilerFlags.cmake index f7c410ffccbb555bc505a95e28c3af389d225c36..d449517b8e449fd2a11d158cf77d2f85c27a55bc 100644 --- a/Utilities/ITK/CMake/ITKSetStandardCompilerFlags.cmake +++ b/Utilities/ITK/CMake/ITKSetStandardCompilerFlags.cmake @@ -110,7 +110,6 @@ function(check_compiler_warning_flags c_warning_flags_var cxx_warning_flags_var) -Wwrite-strings -funit-at-a-time -Wno-strict-overflow - -Wno-unused-local-typedefs ) # Check this list on C++ compiler only @@ -190,8 +189,10 @@ macro(check_compiler_platform_flags) #----------------------------------------------------------------------------- #ITK requires special compiler flags on some platforms. if(CMAKE_COMPILER_IS_GNUCXX) - # GCC's -Warray-bounds has been shown to throw false positives with -O3 on 4.7 and 4.8. - if(UNIX AND "${CMAKE_CXX_COMPILER_VERSION}" VERSION_GREATER "4.6" AND "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.9") + # GCC's -Warray-bounds has been shown to throw false positives with -O3 on 4.8. + if(UNIX AND ( + ("${CMAKE_CXX_COMPILER_VERSION}" VERSION_EQUAL "4.8") OR + ("${CMAKE_CXX_COMPILER_VERSION}" VERSION_GREATER "4.8" AND "${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS "4.9") )) set(ITK_REQUIRED_CXX_FLAGS "${ITK_REQUIRED_CXX_FLAGS} -Wno-array-bounds") endif() diff --git a/Utilities/ITK/CMake/UseITK.cmake b/Utilities/ITK/CMake/UseITK.cmake index 063dd9a59bfdf6293ea28b80b0767e3f5b363de4..a674ea70d895ad2957da849eec0aaf0faa22c6c7 100644 --- a/Utilities/ITK/CMake/UseITK.cmake +++ b/Utilities/ITK/CMake/UseITK.cmake @@ -33,9 +33,9 @@ endmacro() # a list of image IOs to be registered when the corresponding modules are enabled set(LIST_OF_IMAGEIO_FORMATS - Nifti Nrrd Gipl HDF5 JPEG GDCM BMP LSM PNG TIFF VTK Stimulate BioRad Meta MRC + Nifti Nrrd Gipl HDF5 JPEG GDCM BMP LSM PNG TIFF VTK Stimulate BioRad Meta MRC GE4 GE5 MINC - MGH SCIFIO + MGH SCIFIO FDF ) # Set each IO format's module name and factory name @@ -48,6 +48,12 @@ set(Gipl_module_name ITKIOGIPL) set(MGH_module_name MGHIO) set(MGH_factory_name MGHImageIO) +set(GE4_module_name ITKIOGE) +set(GE4_factory_name GE4ImageIO) +set(GE5_module_name ITKIOGE) +set(GE5_factory_name GE5ImageIO) + + set(SCIFIO_module_name SCIFIO) set(SCIFIO_factory_name SCIFIOImageIO) diff --git a/Utilities/ITK/CMake/itkExternal_FFTW.cmake b/Utilities/ITK/CMake/itkExternal_FFTW.cmake index d1e1e4b3d158afd43d6d24f656f8a09bb740b777..798a7826960a4ea5215607aa1efc8cbe03022249 100644 --- a/Utilities/ITK/CMake/itkExternal_FFTW.cmake +++ b/Utilities/ITK/CMake/itkExternal_FFTW.cmake @@ -53,11 +53,17 @@ else() set(FFTW_SHARED_FLAG --enable-shared) endif() + set(_fftw_target_version 3.3.3) + set(_fftw_url_md5 "0a05ca9c7b3bfddc8278e7c40791a1c2") + set(_fftw_url "http://midas3.kitware.com/midas/api/rest?method=midas.bitstream.download&checksum=${_fftw_url_md5}&name=fftw-${_fftw_target_version}.tar.gz") + if(ITK_USE_FFTWF) + itk_download_attempt_check(FFTW) ExternalProject_add(fftwf PREFIX fftwf - URL "http://www.fftw.org/fftw-3.3.2.tar.gz" - URL_MD5 6977ee770ed68c85698c7168ffa6e178 + URL "${_fftw_url}" + URL_MD5 "${_fftw_url_md5}" + DOWNLOAD_NAME "fftw-${_fftw_target_version}.tar.gz" CONFIGURE_COMMAND env "CC=${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}" @@ -77,10 +83,12 @@ else() endif() if(ITK_USE_FFTWD) + itk_download_attempt_check(FFTW) ExternalProject_add(fftwd PREFIX fftwd - URL "http://www.fftw.org/fftw-3.3.2.tar.gz" - URL_MD5 6977ee770ed68c85698c7168ffa6e178 + URL "${_fftw_url}" + URL_MD5 "${_fftw_url_md5}" + DOWNLOAD_NAME "fftw-${_fftw_target_version}.tar.gz" CONFIGURE_COMMAND env "CC=${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}" diff --git a/Utilities/ITK/CMake/itkOpenCL.cmake b/Utilities/ITK/CMake/itkOpenCL.cmake index dafdd97bd57106cbee9e38e60fb4c02fd431cbb5..f1ce6c0419e45b913a85d0bdc1e424bc1ae765e0 100644 --- a/Utilities/ITK/CMake/itkOpenCL.cmake +++ b/Utilities/ITK/CMake/itkOpenCL.cmake @@ -38,13 +38,14 @@ if (ITK_USE_GPU) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE} "${${GPUFILTER_KERNELNAME}_KernelString}") - add_custom_target(${GPUFILTER_KERNELNAME}_Target - SOURCES ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE}) - add_dependencies(${GPUFILTER_KERNELNAME}_Target ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE}) - add_dependencies(${GPUFILTER_KERNELNAME}_Target ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt) configure_file(${OPENCL_FILE} - ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE}.cl COPYONLY) - add_dependencies(${GPUFILTER_KERNELNAME}_Target ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE}.cl) + ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE}.cl COPYONLY) + add_custom_target(${GPUFILTER_KERNELNAME}_Target + DEPENDS + ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE} + ${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt + ${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE}.cl + ) set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/${OUTPUT_FILE} PROPERTIES GENERATED ON) set(${SRC_VAR} ${${SRC_VAR}} ${OUTPUT_FILE}) diff --git a/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in b/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in deleted file mode 100644 index 5e82e7054b2e7c1b773ef96f6b5bd1403ccae775..0000000000000000000000000000000000000000 --- a/Utilities/ITK/CMake/itkSampleBuildTest.cmake.in +++ /dev/null @@ -1,144 +0,0 @@ -# -# This is a recommended file for ITK dashboard submissions -# The generated file will use the current settings in the CMakeCache.txt file -# The file should be copied, edited if necessary and moved to another location -# -# This file was generated from -# @ITK_SOURCE_DIR@/CMake/itkSampleBuildTest.cmake -# - -###################### -# Set the Dashboard to one of Nightly, Continuous or Experimental -# -set(DASHBOARD Nightly) -set(DASHBOARD Continuous) -set(DASHBOARD Experimental) - -###################### -# Set the Default Build Type to one of Release, Debug, RelWithDebInfo -# or MinSizeRel -# -set(DEFAULT_BUILD_TYPE "Debug") -set(DEFAULT_BUILD_TYPE "RelWithDebInfo") -set(DEFAULT_BUILD_TYPE "MinSizeRel") -set(DEFAULT_BUILD_TYPE "Release") - -if("@CMAKE_BUILD_TYPE@" STREQUAL "") - set(BUILD_TYPE ${DEFAULT_BUILD_TYPE}) -else() - set(BUILD_TYPE @CMAKE_BUILD_TYPE@) -endif() - - -# These are the the locations of the source and binary directory -set(CTEST_SOURCE_DIRECTORY "@ITK_SOURCE_DIR@") -set(CTEST_BINARY_DIRECTORY "@ITK_BINARY_DIR@") - -# The ctest command to use for running the dashboard -set(CTEST_COMMAND - "@CMAKE_COMMAND@ -P \"${CTEST_BINARY_DIRECTORY}/CMake/RemoveTemporaryFiles.cmake\"" - "@CMAKE_CTEST_COMMAND@ -D ${DASHBOARD} -A \"${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}\"" -) - -# CMake/RemoveTemporaryFiles.cmake must exist before the CTEST_COMMAND runs -if(NOT EXISTS ${CTEST_BINARY_DIRECTORY}/CMake/RemoveTemporaryFiles.cmake) - set(CTEST_CMAKE_COMMAND "@CMAKE_COMMAND@") -endif() - -# CMakeCache.txt must exist before the CTEST_COMMAND runs -if(NOT EXISTS ${CTEST_BINARY_DIRECTORY}/CMakeCache.txt) - set(CTEST_CMAKE_COMMAND "@CMAKE_COMMAND@") -endif() - -# Specify how long to run the continuous in minutes -if(${DASHBOARD} STREQUAL "Continuous") - set(CTEST_CONTINUOUS_DURATION 1080) - set(CTEST_CONTINUOUS_MINIMUM_INTERVAL 15) -endif() - -# Set defaults -set(CTEST_START_WITH_EMPTY_BINARY_DIRECTORY FALSE) -set(CTEST_START_WITH_EMPTY_BINARY_DIRECTORY_ONCE FALSE) - -# For Nightly builds, this should be TRUE -if(${DASHBOARD} STREQUAL "Nightly") - set(CTEST_START_WITH_EMPTY_BINARY_DIRECTORY TRUE) -else() - set(CTEST_START_WITH_EMPTY_BINARY_DIRECTORY FALSE) -endif() - -# For Continuous builds. this should be TRUE -if(${DASHBOARD} STREQUAL "Continuous") - set(CTEST_START_WITH_EMPTY_BINARY_DIRECTORY_ONCE TRUE) -else() - set(CTEST_START_WITH_EMPTY_BINARY_DIRECTORY_ONCE FALSE) -endif() - -# For Experimental builds, these should be FALSE -if(${DASHBOARD} STREQUAL "Experimental") - set(CTEST_START_WITH_EMPTY_BINARY_DIRECTORY FALSE) - set(CTEST_START_WITH_EMPTY_BINARY_DIRECTORY_ONCE FALSE) -endif() - -# This is the initial cache to use for the binary tree, be careful to escape -# any quotes inside of this string if you use it -set(CTEST_INITIAL_CACHE " -SITE:STRING=@SITE@ -BUILDNAME:STRING=@BUILDNAME@ -CVSCOMMAND:FILEPATH=@CVSCOMMAND@ -CVS_UPDATE_OPTIONS:STRING=-d -A -P - -CMAKE_C_FLAGS_RELEASE:STRING=@CMAKE_C_FLAGS_RELEASE@ -CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=@CMAKE_C_FLAGS_RELWITHDEBINFO@ -CMAKE_CXX_FLAGS_RELEASE:STRING=@CMAKE_CXX_FLAGS_RELEASE@ -CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=@CMAKE_CXX_FLAGS_RELWITHDEBINFO@ - -TCL_TCLSH:FILEPATH=@TCL_TCLSH@ -CMAKE_BUILD_TOOL:INTERNAL=@CMAKE_BUILD_TOOL@ -CMAKE_MAKE_PROGRAM:FILEPATH=@CMAKE_MAKE_PROGRAM@ -CMAKE_GENERATOR:INTERNAL=@CMAKE_GENERATOR@ -CMAKE_CXX_COMPILER:FILEPATH=@CMAKE_CXX_COMPILER@ -CMAKE_CXX_FLAGS:STRING=@CMAKE_CXX_FLAGS@ -CMAKE_C_COMPILER:FILEPATH=@CMAKE_C_COMPILER@ -CMAKE_C_FLAGS:STRING=@CMAKE_C_FLAGS@ -CMAKE_CONFIGURATION_TYPES:STRING=${BUILD_TYPE} -CMAKE_BUILD_TYPE:STRING=${BUILD_TYPE} - -BUILD_SHARED_LIBS:BOOL=@BUILD_SHARED_LIBS@ -BUILD_TESTING:BOOL=@BUILD_TESTING@ -BUILD_EXAMPLES:BOOL=@BUILD_EXAMPLES@ - -ITK_USE_PATENTED:BOOL=@ITK_USE_PATENTED@ -ITK_USE_CONCEPT_CHECKING:BOOL=@ITK_USE_CONCEPT_CHECKING@ - -ITK_USE_SYSTEM_GDCM:BOOL=@ITK_USE_SYSTEM_GDCM@ -ITK_USE_SYSTEM_JPEG:BOOL=@ITK_USE_SYSTEM_JPEG@ -ITK_USE_SYSTEM_PNG:BOOL=@ITK_USE_SYSTEM_PNG@ -ITK_USE_SYSTEM_TIFF:BOOL=@ITK_USE_SYSTEM_TIFF@ -ITK_USE_SYSTEM_VXL:BOOL=@ITK_USE_SYSTEM_VXL@ -ITK_USE_SYSTEM_ZLIB:BOOL=@ITK_USE_SYSTEM_ZLIB@ - -ITK_LEGACY_REMOVE:BOOL=@ITK_LEGACY_REMOVE@ -ITK_LEGACY_SILENT:BOOL=@ITK_LEGACY_SILENT@ -ITK_FUTURE_LEGACY_REMOVE:BOOL=@ITK_FUTURE_LEGACY_REMOVE@ -GDCM_LEGACY_REMOVE:BOOL=@GDCM_LEGACY_REMOVE@ -GDCM_LEGACY_SILENT:BOOL=@GDCM_LEGACY_SILENT@ - -ITK_USE_KWSTYLE:BOOL=@ITK_USE_KWSTYLE@ -KWSTYLE_EXECUTABLE:PATH=@KWSTYLE_EXECUTABLE@ -KWSTYLE_USE_VIM_FORMAT:BOOL=@KWSTYLE_USE_VIM_FORMAT@ -KWSTYLE_USE_GCC_FORMAT:BOOL=@KWSTYLE_USE_GCC_FORMAT@ -KWSTYLE_USE_MSVC_FORMAT:BOOL=@KWSTYLE_USE_MSVC_FORMAT@ - -ITK_CSWIG_JAVA:BOOL=@ITK_CSWIG_JAVA@ -ITK_CSWIG_PYTHON:BOOL=@ITK_CSWIG_PYTHON@ -ITK_CSWIG_TCL:BOOL=@ITK_CSWIG_TCL@ - -ITK_WRAPPING:BOOL=@ITK_WRAPPING@ -ITK_USE_FFTWD:BOOL=@USE_FFTWD@ -ITK_USE_FFTWF:BOOL=@USE_FFTWF@ -") - -# Set any extra envionment variables here -set(CTEST_ENVIRONMENT - ) diff --git a/Utilities/ITK/CMake/pre-commit b/Utilities/ITK/CMake/pre-commit old mode 100644 new mode 100755 diff --git a/Utilities/ITK/CMakeLists.txt b/Utilities/ITK/CMakeLists.txt index c8b0a46219c6f0016667d9e61ed8caa82360c95d..253ec0bca9d4dc2bbe112e5730d50b1601218166 100644 --- a/Utilities/ITK/CMakeLists.txt +++ b/Utilities/ITK/CMakeLists.txt @@ -1,15 +1,25 @@ -cmake_minimum_required(VERSION 2.8.6 FATAL_ERROR) -include(CMakeDependentOption) -# -# use ExternalProject -include(ExternalProject) - if(WIN32) - cmake_minimum_required(VERSION 2.8.8) + cmake_minimum_required(VERSION 2.8.8 FATAL_ERROR) +else() + cmake_minimum_required(VERSION 2.8.6 FATAL_ERROR) endif() +foreach(p + CMP0025 # CMake 3.0 + CMP0042 # CMake 3.0 + ) + if(POLICY ${p}) + cmake_policy(SET ${p} NEW) + endif() +endforeach() + project(ITK) +include(CMakeDependentOption) +# +# use ExternalProject +include(ExternalProject) + if( CMAKE_HOST_WIN32 ) string( LENGTH "${CMAKE_CURRENT_SOURCE_DIR}" n ) @@ -44,7 +54,7 @@ set(main_project_name ${_ITKModuleMacros_DEFAULT_LABEL}) #----------------------------------------------------------------------------- # ITK version number. set(ITK_VERSION_MAJOR "4") -set(ITK_VERSION_MINOR "5") +set(ITK_VERSION_MINOR "6") set(ITK_VERSION_PATCH "0") if(NOT ITK_INSTALL_RUNTIME_DIR) @@ -89,16 +99,33 @@ endif() #----------------------------------------------------------------------------- -# Enable runinng cppcheck for each module on its source and test directories. +# Enable running cppcheck for each module on its source and test directories. option(ITK_CPPCHECK_TEST "Run cppcheck for static code analysis" OFF) mark_as_advanced(ITK_CPPCHECK_TEST) +#----------------------------------------------------------------------------- +# Forbid downloading resources from the network during a build. This helps +# when building on systems without network connectivity to determine which +# resources much be obtained manually and made available to the build. +option(ITK_FORBID_DOWNLOADS "Do not download source code or data from the network" OFF) +mark_as_advanced(ITK_FORBID_DOWNLOADS) +macro(itk_download_attempt_check _name) + if(ITK_FORBID_DOWNLOADS) + message(SEND_ERROR "Attempted to download ${_name} when ITK_FORBID_DOWNLOADS is ON") + endif() +endmacro() #----------------------------------------------------------------------------- # Enable the download and use of BrainWeb datasets. # When this data is available, additional 3D tests are enabled. option(ITK_USE_BRAINWEB_DATA "Download and use BrainWeb data for advanced testing" OFF) mark_as_advanced(ITK_USE_BRAINWEB_DATA) +if(ITK_BRAINWEB_DATA_ROOT) + message(WARNING + "ITK_BRAINWEB_DATA_ROOT is not longer supported!" + "Please update to ITK_USE_BRAINWEB_DATA." + ) +endif() #----------------------------------------------------------------------------- # ITK wrapper for add_test that automatically sets the test's LABELS property @@ -133,9 +160,17 @@ macro(itk_memcheck_ignore) set_property(GLOBAL APPEND PROPERTY CTEST_CUSTOM_MEMCHECK_IGNORE ${ARGN}) endmacro() +#----------------------------------------------------------------------------- +# Python Wrapping +option(ITK_WRAP_PYTHON "Build python support" OFF) + #----------------------------------------------------------------------------- # ITK build configuration options. -option(BUILD_SHARED_LIBS "Build ITK with shared libraries." OFF) +if(ITK_WRAP_PYTHON) + option(BUILD_SHARED_LIBS "Build ITK with shared libraries." ON) +else() + option(BUILD_SHARED_LIBS "Build ITK with shared libraries." OFF) +endif() set(ITK_BUILD_SHARED_LIBS ${BUILD_SHARED_LIBS}) include(ITKSetStandardCompilerFlags) @@ -170,7 +205,11 @@ set(ITK_MODULES_DIR "${ITK_BINARY_DIR}/${ITK_INSTALL_PACKAGE_DIR}/Modules") # Provide compatibility options. option(ITKV3_COMPATIBILITY "Enable compatibility with ITK3.x when possible." OFF) option(ITK_LEGACY_REMOVE "Remove all legacy code completely." OFF) -option(ITK_LEGACY_SILENT "Silence all legacy code messages." OFF) +if(ITK_WRAP_PYTHON) + option(ITK_LEGACY_SILENT "Silence all legacy code messages." ON) +else() + option(ITK_LEGACY_SILENT "Silence all legacy code messages." OFF) +endif() # The ITK_FUTURE_LEGACY_REMOVE is a very advanced feature only # available to developers at configuration time by manually # adding this to the CMakeCache.txt -DITK_FUTURE_LEGACY_REMOVE:BOOL=ON @@ -178,7 +217,7 @@ set( ITK_FUTURE_LEGACY_REMOVE 0 CACHE INTERNAL "Remove code that will become leg mark_as_advanced(ITK_LEGACY_SILENT ITK_LEGACY_REMOVE ITK_V3_COMPATIBILITY) # The disabling of legacy code, and the ITKv3 compatibility option can not both be -# requested. If removal of legacy code is requested, then ITKV3_COMPATIBILITY must +# requested. If removal of legacy code is requested, then ITKV3_COMPATIBILITY must # be off. if(ITKV3_COMPATIBILITY AND ITK_LEGACY_REMOVE) message(FATAL_ERROR "Invlaid configuration: ITKV3_COMPATIBILITY AND ITK_LEGACY_REMOVE can not both be ON") @@ -354,15 +393,11 @@ endif() #----------------------------------------------------------------------------- # The subdirectories added below this line should use only the public -# interface with find_package(ITK). Set ITK_DIR to use this ITK build. +# interface with find_package(ITK). Set ITK_DIR to use this ITK build. set(ITK_DIR "${ITK_BINARY_DIR}") include(Wrapping/itkWrapSetup.cmake) if(ITK_WRAPPING) - if(ITK_USE_64BITS_IDS AND WIN32) - message(FATAL_ERROR "WRAPPING with ITK_USE_64BITS_IDS is not supported on Windows. -Please turn of ITK_USE_64BITS_IDS.") - endif() add_subdirectory(Wrapping) endif() @@ -374,6 +409,6 @@ endif() # Provide an option for generating documentation. add_subdirectory(Utilities/Doxygen) -# Create target to download data from the ITKData group. This must come after +# Create target to download data from the ITKData group. This must come after # all tests have been added that reference the group, so we put it last. ExternalData_Add_Target(ITKData) diff --git a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkExponentialDeformationFieldImageFilter.hxx b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkExponentialDeformationFieldImageFilter.hxx index 833e32e35933ee4e6a6d4b0866e45bda2519a512..14f8b45470a05b471440c26a5ce571b99564a14e 100644 --- a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkExponentialDeformationFieldImageFilter.hxx +++ b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkExponentialDeformationFieldImageFilter.hxx @@ -114,7 +114,7 @@ ExponentialDeformationFieldImageFilter< TInputImage, TOutputImage > maxnorm2 /= vnl_math_sqr(minpixelspacing); InputPixelRealValueType numiterfloat = 2.0 - + 0.5 * vcl_log(maxnorm2) / vnl_math::ln2; + + 0.5 * std::log(maxnorm2) / vnl_math::ln2; if ( numiterfloat >= 0.0 ) { diff --git a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkInverseDeformationFieldImageFilter.hxx b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkInverseDeformationFieldImageFilter.hxx index 965a6b006a524e7654b253c969927fc249345d94..237bec569580732458fcb5b6b16b360d34ff1613 100644 --- a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkInverseDeformationFieldImageFilter.hxx +++ b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkInverseDeformationFieldImageFilter.hxx @@ -133,7 +133,6 @@ InverseDeformationFieldImageFilter< TInputImage, TOutputImage > typedef typename InputImageType::RegionType InputRegionType; typedef typename InputImageType::SizeType InputSizeType; - typedef typename InputImageType::IndexType InputIndexType; InputRegionType region; diff --git a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkIterativeInverseDeformationFieldImageFilter.hxx b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkIterativeInverseDeformationFieldImageFilter.hxx index f8d7fdf6787db7f6e82af32fdb3c07ae424ca965..1bd7c496233c1fb917b2ebf8ec64c8d08731b0cb 100644 --- a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkIterativeInverseDeformationFieldImageFilter.hxx +++ b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkIterativeInverseDeformationFieldImageFilter.hxx @@ -51,7 +51,7 @@ void IterativeInverseDeformationFieldImageFilter< TInputImage, TOutputImage > { itkExceptionMacro("\n Input is missing."); } - if ( !TInputImage::ImageDimension == TOutputImage::ImageDimension ) + if ( ! ( TInputImage::ImageDimension == TOutputImage::ImageDimension ) ) { itkExceptionMacro("\n Image Dimensions must be the same."); } @@ -150,9 +150,9 @@ void IterativeInverseDeformationFieldImageFilter< TInputImage, TOutputImage > smallestError = 0; for ( unsigned int j = 0; j < ImageDimension; j++ ) { - smallestError += vcl_pow(mappedPoint[j] + forwardVector[j] - originalPoint[j], 2); + smallestError += std::pow(mappedPoint[j] + forwardVector[j] - originalPoint[j], 2); } - smallestError = vcl_sqrt(smallestError); + smallestError = std::sqrt(smallestError); } // iteration loop @@ -174,9 +174,9 @@ void IterativeInverseDeformationFieldImageFilter< TInputImage, TOutputImage > tmp = 0; for ( unsigned int l = 0; l < ImageDimension; l++ ) { - tmp += vcl_pow(mappedPoint[l] + forwardVector[l] - originalPoint[l], 2); + tmp += std::pow(mappedPoint[l] + forwardVector[l] - originalPoint[l], 2); } - tmp = vcl_sqrt(tmp); + tmp = std::sqrt(tmp); if ( tmp < smallestError ) { smallestError = tmp; @@ -194,9 +194,9 @@ void IterativeInverseDeformationFieldImageFilter< TInputImage, TOutputImage > tmp = 0; for ( unsigned int l = 0; l < ImageDimension; l++ ) { - tmp += vcl_pow(mappedPoint[l] + forwardVector[l] - originalPoint[l], 2); + tmp += std::pow(mappedPoint[l] + forwardVector[l] - originalPoint[l], 2); } - tmp = vcl_sqrt(tmp); + tmp = std::sqrt(tmp); if ( tmp < smallestError ) { smallestError = tmp; diff --git a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkOtsuThresholdImageCalculator.h b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkOtsuThresholdImageCalculator.h index f292cd9d7530ae6ca18ecdebb71e0cd2112353d5..58927eef97ded8c89ad874f6ea5440fe665b94f5 100644 --- a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkOtsuThresholdImageCalculator.h +++ b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkOtsuThresholdImageCalculator.h @@ -99,7 +99,7 @@ public: protected: OtsuThresholdImageCalculator(); virtual ~OtsuThresholdImageCalculator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: OtsuThresholdImageCalculator(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkOtsuThresholdImageCalculator.hxx b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkOtsuThresholdImageCalculator.hxx index 288fda57325e277e7534bf78fa08647a28093c0d..971050e5c2c320f1d6f1541c1d4baba37e2d0429 100644 --- a/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkOtsuThresholdImageCalculator.hxx +++ b/Utilities/ITK/Modules/Compatibility/V3Compatibility/include/itkOtsuThresholdImageCalculator.hxx @@ -33,7 +33,7 @@ template< typename TInputImage > OtsuThresholdImageCalculator< TInputImage > ::OtsuThresholdImageCalculator() { - m_Image = NULL; + m_Image = ITK_NULLPTR; m_Threshold = NumericTraits< PixelType >::Zero; m_NumberOfHistogramBins = 128; m_RegionSetByUser = false; @@ -98,7 +98,7 @@ OtsuThresholdImageCalculator< TInputImage > } else { - binNumber = (unsigned int)vcl_ceil( ( value - imageMin ) * binMultiplier ) - 1; + binNumber = (unsigned int)std::ceil( ( value - imageMin ) * binMultiplier ) - 1; if ( binNumber == m_NumberOfHistogramBins ) // in case of rounding errors { binNumber -= 1; diff --git a/Utilities/ITK/Modules/Core/Common/include/VNLSparseLUSolverTraits.h b/Utilities/ITK/Modules/Core/Common/include/VNLSparseLUSolverTraits.h index c4671037d44aa774248ea421eac8a22392abf233..eb6e35d10f5cc73a11027dd9d2bed3e07ce89bf9 100644 --- a/Utilities/ITK/Modules/Core/Common/include/VNLSparseLUSolverTraits.h +++ b/Utilities/ITK/Modules/Core/Common/include/VNLSparseLUSolverTraits.h @@ -87,7 +87,7 @@ public: static bool Solve(const MatrixType & iA, const VectorType & iB, VectorType & oX) { SolverType solver( iA ); - oX = solver.solve( iB ); + Solve( solver, iB, oX ); return true; } @@ -98,9 +98,7 @@ public: VectorType & oX, VectorType & oY, VectorType & oZ ) { SolverType solver( iA ); - oX = solver.solve( iBx ); - oY = solver.solve( iBy ); - oZ = solver.solve( iBz ); + Solve( solver, iBx, iBy, iBz, oX, oY, oZ ); return true; } @@ -111,12 +109,35 @@ public: VectorType & oX, VectorType & oY) { SolverType solver( iA ); - oX = solver.solve( iBx ); - oY = solver.solve( iBy ); + Solve( solver, iBx, iBy, oX, oY ); return true; } + /** \brief Solve the linear system \f$ iA \cdot oX = iB \f$ factoring the internal matrix if needed */ + static void Solve( SolverType & solver, const VectorType & iB, VectorType & oX ) + { + oX = solver.solve( iB ); + } + + /** \brief Solve the linear systems: \f$ iA \cdot oX = iBx \f$, \f$ iA \cdot oY = iBy \f$, \f$ iA \cdot oZ = iBz \f$ factoring the internal matrix if needed */ + static void Solve( SolverType & solver, + const VectorType & iBx, const VectorType & iBy, const VectorType & iBz, + VectorType & oX, VectorType & oY, VectorType & oZ ) + { + oX = solver.solve( iBx ); + oY = solver.solve( iBy ); + oZ = solver.solve( iBz ); + } + + /** \brief Solve the linear systems: \f$ iA \cdot oX = iBx \f$, \f$ iA \cdot oY = iBy \f$ factoring the internal matrix if needed */ + static void Solve( SolverType & solver, + const VectorType & iBx, const VectorType & iBy, + VectorType & oX, VectorType & oY ) + { + oX = solver.solve( iBx ); + oY = solver.solve( iBy ); + } }; #endif diff --git a/Utilities/ITK/Modules/Core/Common/include/itkAnnulusOperator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkAnnulusOperator.hxx index b410982da92b9b754e5e73234c3d91e2105014d8..fbdf6d828e7a0de472712010712198dc6a287397 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkAnnulusOperator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkAnnulusOperator.hxx @@ -166,13 +166,13 @@ AnnulusOperator< TPixel, TDimension, TAllocator > double mean = sumNotExterior / num; double var = ( sumNotExteriorSq - ( sumNotExterior * sumNotExterior / num ) ) / ( num - 1.0 ); - double std = vcl_sqrt(var); + double std = std::sqrt(var); // convert std to a scaling factor k such that // // || (coeffP - mean) / k || = 1.0 // - double k = std * vcl_sqrt(num - 1.0); + double k = std * std::sqrt(num - 1.0); // Run through the kernel again, shifting and normalizing the // elements that are not exterior to the annulus. This forces the diff --git a/Utilities/ITK/Modules/Core/Common/include/itkArray.h b/Utilities/ITK/Modules/Core/Common/include/itkArray.h index af25a65c7ddedbf0ef39668d4a75f7308a7b1795..b66c636ac43f9e5e6c2d3e8706fefe761152b1e9 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkArray.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkArray.h @@ -41,21 +41,21 @@ namespace itk * * Template parameters for class Array: * - * - TValueType = Element type stored at each location in the array. + * - TValue = Element type stored at each location in the array. * * \ingroup DataRepresentation * \ingroup ITKCommon */ -template< typename TValueType > -class Array : public vnl_vector< TValueType > +template< typename TValue > +class Array : public vnl_vector< TValue > { public: /** The element type stored at each location in the Array. */ - typedef TValueType ValueType; - typedef Array Self; - typedef vnl_vector< TValueType > VnlVectorType; - typedef typename vnl_vector< TValueType>::size_type SizeValueType; + typedef TValue ValueType; + typedef Array Self; + typedef vnl_vector< TValue > VnlVectorType; + typedef typename vnl_vector< TValue>::size_type SizeValueType; public: @@ -78,6 +78,14 @@ public: * memory when this object is destroyed. */ Array(ValueType *data, SizeValueType sz, bool LetArrayManageMemory = false); +#if defined ( ITK_FUTURE_LEGACY_REMOVE ) + /** Constructor that initializes array with contents from a user supplied + * const buffer. The pointer to the buffer and the length is specified. By default, + * the array does a deep copy of the const pointer data, so the array class also + * manages memory. */ + Array(const ValueType *datain, SizeValueType sz); + +#else // defined ( ITK_FUTURE_LEGACY_REMOVE ) /** Constructor that initializes array with contents from a user supplied * buffer. The pointer to the buffer and the length is specified. By default, * the array does not manage the memory of the buffer. It merely points to @@ -86,6 +94,7 @@ public: * memory when this object is destroyed. */ Array(const ValueType *data, SizeValueType sz, bool LetArrayManageMemory = false); +#endif /** Constructor to initialize an array from another of any data type */ template< typename TArrayValue > @@ -95,12 +104,12 @@ public: this->SetSize( r.GetSize() ); for( SizeValueType i=0; i<r.GetSize(); i++ ) { - this->operator[](i) = static_cast< TValueType >( r[i] ); + this->operator[](i) = static_cast< TValue >( r[i] ); } } /** Set the all the elements of the array to the specified value */ - void Fill(TValueType const & v) + void Fill(TValue const & v) { this->fill(v); } @@ -117,11 +126,11 @@ public: { return static_cast<SizeValueType >( this->size() ); } /** Get one element */ - const TValueType & GetElement(SizeValueType i) const + const TValue & GetElement(SizeValueType i) const { return this->operator[](i); } /** Set one element */ - void SetElement(SizeValueType i, const TValueType & value) + void SetElement(SizeValueType i, const TValue & value) { this->operator[](i) = value; } /** Destructively set the size to that given. Will lose data. */ @@ -135,7 +144,7 @@ public: * the responsibility of freeing the memory for this data. If * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. */ - void SetData(TValueType *data, bool LetArrayManageMemory = false); + void SetData(TValue *data, bool LetArrayManageMemory = false); /** Similar to the previous method. In the above method, the size must be * separately set prior to using user-supplied data. This introduces an @@ -146,7 +155,7 @@ public: * the responsibility of freeing the memory for this data. If * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. */ - void SetData(TValueType *data, SizeValueType sz, + void SetData(TValue *data, SizeValueType sz, bool LetArrayManageMemory = false); @@ -157,13 +166,20 @@ public: * means that subclasses cannot allocate memory. */ ~Array(); + void swap(Array &other) + { + using std::swap; + this->VnlVectorType::swap(other); + swap(this->m_LetArrayManageMemory, other.m_LetArrayManageMemory); + } + private: bool m_LetArrayManageMemory; }; -template< typename TValueType > -std::ostream & operator<<(std::ostream & os, const Array< TValueType > & arr) +template< typename TValue > +std::ostream & operator<<(std::ostream & os, const Array< TValue > & arr) { os << "["; const unsigned int length = arr.size(); @@ -184,6 +200,13 @@ std::ostream & operator<<(std::ostream & os, const Array< TValueType > & arr) template<> ITKCommon_EXPORT std::ostream & operator<< <double> (std::ostream & os, const Array< double > & arr); template<> ITKCommon_EXPORT std::ostream & operator<< <float> (std::ostream & os, const Array< float > & arr); + +template<typename T> +inline void swap( Array<T> &a, Array<T> &b ) +{ + a.swap(b); +} + } // namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Modules/Core/Common/include/itkArray.hxx b/Utilities/ITK/Modules/Core/Common/include/itkArray.hxx index 47cf6bec393810f7ed644470a1b3dfd3d72058ee..654fa5d3b32d1a6aac11961d6bf2fa342d1120fc 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkArray.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkArray.hxx @@ -24,18 +24,18 @@ namespace itk { /** Default constructor */ -template< typename TValueType > -Array< TValueType > -::Array():vnl_vector< TValueType >() +template< typename TValue > +Array< TValue > +::Array():vnl_vector< TValue >() { m_LetArrayManageMemory = true; } /** Copy constructor */ -template < typename TValueType > -Array<TValueType> +template < typename TValue > +Array<TValue> ::Array(const Self & rhs) - : vnl_vector<TValueType>(rhs), + : vnl_vector<TValue>(rhs), // The vnl vector copy constructor creates new memory // no matter the setting of let array manage memory of rhs m_LetArrayManageMemory(true) @@ -43,42 +43,62 @@ Array<TValueType> } /** Constructor with size */ -template< typename TValueType > -Array< TValueType > -::Array(SizeValueType dimension):vnl_vector< TValueType >(dimension) +template< typename TValue > +Array< TValue > +::Array(SizeValueType dimension) + : vnl_vector< TValue >(dimension), + // The vnl vector copy constructor creates new memory + // no matter the setting of let array manage memory of rhs + m_LetArrayManageMemory(true) { - m_LetArrayManageMemory = true; } /** Constructor with user specified data */ -template< typename TValueType > -Array< TValueType > -::Array(ValueType *datain, SizeValueType sz, bool LetArrayManageMemory) +template< typename TValue > +Array< TValue > +::Array(ValueType *datain, SizeValueType sz, bool LetArrayManageMemory): + m_LetArrayManageMemory(LetArrayManageMemory) { - vnl_vector< TValueType >::data = datain; - vnl_vector< TValueType >::num_elmts = sz; - m_LetArrayManageMemory = LetArrayManageMemory; + vnl_vector< TValue >::data = datain; + vnl_vector< TValue >::num_elmts = sz; } -/** Constructor with user specified data */ -template< typename TValueType > -Array< TValueType > -::Array(const ValueType *datain, SizeValueType sz, bool LetArrayManageMemory) +#if defined ( ITK_FUTURE_LEGACY_REMOVE ) +/** Constructor with user specified const data */ +template< typename TValue > +Array< TValue > +::Array(const ValueType *datain, SizeValueType sz): + vnl_vector< TValue >( datain, sz), + // The vnl vector copy constructor creates new memory + // no matter the setting of let array manage memory of rhs + m_LetArrayManageMemory(true) +{ +} + +#else // defined ( ITK_FUTURE_LEGACY_REMOVE ) +/** Constructor with user specified const data */ +template< typename TValue > +Array< TValue > +::Array(const ValueType *datain, SizeValueType sz, bool /* LetArrayManageMemory */): + /* NOTE: The 3rd argument "LetArrayManageMemory, was never valid to use, but is + * preserved to maintain backwards compatibility*/ + vnl_vector< TValue >( datain, sz), + // The vnl vector copy constructor creates new memory + // no matter the setting of let array manage memory of rhs + m_LetArrayManageMemory(true) { - vnl_vector< TValueType >::data = const_cast< TValueType * >( datain ); - // Argh!! Discard constness WRONG.!! - vnl_vector< TValueType >::num_elmts = sz; - m_LetArrayManageMemory = LetArrayManageMemory; } +#endif + /** Destructor */ -template< typename TValueType > -Array< TValueType > +template< typename TValue > +Array< TValue > ::~Array() { if ( !m_LetArrayManageMemory ) { - vnl_vector< TValueType >::data = 0; + vnl_vector< TValue >::data = ITK_NULLPTR; } } @@ -87,16 +107,16 @@ Array< TValueType > * the responsibility of freeing the memory for this data. If * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. */ -template< typename TValueType > +template< typename TValue > void -Array< TValueType > -::SetData(TValueType *datain, bool LetArrayManageMemory) +Array< TValue > +::SetData(TValue *datain, bool LetArrayManageMemory) { if ( m_LetArrayManageMemory ) { - vnl_vector< TValueType >::destroy(); + vnl_vector< TValue >::destroy(); } - vnl_vector< TValueType >::data = datain; + vnl_vector< TValue >::data = datain; m_LetArrayManageMemory = LetArrayManageMemory; } @@ -109,22 +129,22 @@ Array< TValueType > * the responsibility of freeing the memory for this data. If * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. */ -template< typename TValueType > +template< typename TValue > void -Array< TValueType > -::SetData(TValueType *datain, SizeValueType sz, bool LetArrayManageMemory) +Array< TValue > +::SetData(TValue *datain, SizeValueType sz, bool LetArrayManageMemory) { if ( m_LetArrayManageMemory ) { - vnl_vector< TValueType >::destroy(); + vnl_vector< TValue >::destroy(); } - vnl_vector< TValueType >::data = datain; - vnl_vector< TValueType >::num_elmts = sz; + vnl_vector< TValue >::data = datain; + vnl_vector< TValue >::num_elmts = sz; m_LetArrayManageMemory = LetArrayManageMemory; } -template< typename TValueType > -void Array< TValueType > +template< typename TValue > +void Array< TValue > ::SetSize(SizeValueType sz) { if ( this->size() != sz ) @@ -133,7 +153,7 @@ void Array< TValueType > // on a resize if ( !m_LetArrayManageMemory ) { - vnl_vector< TValueType >::data = 0; + vnl_vector< TValue >::data = ITK_NULLPTR; } // Call the superclass's set_size @@ -145,10 +165,10 @@ void Array< TValueType > } } -template< typename TValueType > -const typename Array< TValueType > +template< typename TValue > +const typename Array< TValue > ::Self & -Array< TValueType > +Array< TValue > ::operator=(const Self & rhs) { if ( this != &rhs ) @@ -166,10 +186,10 @@ Array< TValueType > return *this; } -template< typename TValueType > -const typename Array< TValueType > +template< typename TValue > +const typename Array< TValue > ::Self & -Array< TValueType > +Array< TValue > ::operator=(const VnlVectorType & rhs) { if ( this != &rhs ) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkArray2D.h b/Utilities/ITK/Modules/Core/Common/include/itkArray2D.h index dbe36adf44adb49bc6f153da3c9278311b54e146..52f87fb61aa3f172bae9798fb25e7a401e705555 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkArray2D.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkArray2D.h @@ -35,20 +35,20 @@ namespace itk * * Template parameters for class Array2D: * - * - TValueType = Element type stored at each location in the array. + * - TValue = Element type stored at each location in the array. * * \ingroup DataRepresentation * \ingroup ITKCommon */ -template< typename TValueType > -class Array2D: public vnl_matrix< TValueType > +template< typename TValue > +class Array2D: public vnl_matrix< TValue > { public: /** The element type stored at each location in the Array2D. */ - typedef TValueType ValueType; - typedef Array2D Self; - typedef vnl_matrix< TValueType > VnlMatrixType; + typedef TValue ValueType; + typedef Array2D Self; + typedef vnl_matrix< TValue > VnlMatrixType; Array2D(); Array2D(unsigned int rows, unsigned int cols); @@ -59,7 +59,7 @@ public: const Self & operator=(const VnlMatrixType & matrix); - void Fill(TValueType const & v) { this->fill(v); } + void Fill(TValue const & v) { this->fill(v); } /** Destructively set the size to that given. Will lose data. */ void SetSize(unsigned int m, unsigned int n); @@ -69,8 +69,8 @@ public: ~Array2D() {} }; -template< typename TValueType > -std::ostream & operator<<(std::ostream & os, const Array2D< TValueType > & arr) +template< typename TValue > +std::ostream & operator<<(std::ostream & os, const Array2D< TValue > & arr) { const unsigned int numberOfRows = arr.rows(); const unsigned int numberOfColumns = arr.cols(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkArray2D.hxx b/Utilities/ITK/Modules/Core/Common/include/itkArray2D.hxx index dde69c98a34a4f41fe535791c002c0de63c9098d..32194711c2dcda57313a40fa50deb103af856b41 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkArray2D.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkArray2D.hxx @@ -23,34 +23,34 @@ namespace itk { /** Default constructor */ -template< typename TValueType > -Array2D< TValueType > -::Array2D():vnl_matrix< TValueType >() +template< typename TValue > +Array2D< TValue > +::Array2D():vnl_matrix< TValue >() {} /** Constructor with number of rows and columns as arguments */ -template< typename TValueType > -Array2D< TValueType > +template< typename TValue > +Array2D< TValue > ::Array2D(unsigned int numberOfRows, unsigned int numberOfCols): - vnl_matrix< TValueType >(numberOfRows, numberOfCols) + vnl_matrix< TValue >(numberOfRows, numberOfCols) {} /** Constructor from a vnl_matrix */ -template< typename TValueType > -Array2D< TValueType > -::Array2D(const VnlMatrixType & matrix):vnl_matrix< TValueType >(matrix) +template< typename TValue > +Array2D< TValue > +::Array2D(const VnlMatrixType & matrix):vnl_matrix< TValue >(matrix) {} /** Copy Constructor */ -template< typename TValueType > -Array2D< TValueType > -::Array2D(const Self & array):vnl_matrix< TValueType >(array) +template< typename TValue > +Array2D< TValue > +::Array2D(const Self & array):vnl_matrix< TValue >(array) {} /** Assignment Operator from Array */ -template< typename TValueType > -const Array2D< TValueType > & -Array2D< TValueType > +template< typename TValue > +const Array2D< TValue > & +Array2D< TValue > ::operator=(const Self & array) { this->VnlMatrixType::operator=(array); @@ -58,9 +58,9 @@ Array2D< TValueType > } /** Assignment Operator from vnl_matrix */ -template< typename TValueType > -const Array2D< TValueType > & -Array2D< TValueType > +template< typename TValue > +const Array2D< TValue > & +Array2D< TValue > ::operator=(const VnlMatrixType & matrix) { this->VnlMatrixType::operator=(matrix); @@ -68,8 +68,8 @@ Array2D< TValueType > } /** Set the size of the array */ -template< typename TValueType > -void Array2D< TValueType > +template< typename TValue > +void Array2D< TValue > ::SetSize(unsigned int m, unsigned int n) { this->set_size(m, n); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkAtanRegularizedHeavisideStepFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkAtanRegularizedHeavisideStepFunction.hxx index cfcc1cd09c7f628b5cccd2b728b4444e8f2be50e..7901f5918defdfc1a0ed7c44b0eb7a4b3235ec33 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkAtanRegularizedHeavisideStepFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkAtanRegularizedHeavisideStepFunction.hxx @@ -39,7 +39,7 @@ AtanRegularizedHeavisideStepFunction< TInput, TOutput > ::Evaluate(const InputType & input) const { const RealType t = static_cast< RealType >( input ) * this->GetOneOverEpsilon(); - return 0.5 + static_cast< OutputType >( vnl_math::one_over_pi * vcl_atan( t ) ); + return 0.5 + static_cast< OutputType >( vnl_math::one_over_pi * std::atan( t ) ); } /** Evaluate the derivative at the specified input position */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkAutoPointer.h b/Utilities/ITK/Modules/Core/Common/include/itkAutoPointer.h index b578f436219127a38d234352041b1a2264b19f28..6b627a4463db8d1d1b78ecfede336b999fab7da9 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkAutoPointer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkAutoPointer.h @@ -51,7 +51,7 @@ public: typedef AutoPointer Self; /** Constructor. */ - AutoPointer ():m_Pointer(0), m_IsOwner(false) + AutoPointer ():m_Pointer(ITK_NULLPTR), m_IsOwner(false) {} /** Copy constructor. */ @@ -85,7 +85,7 @@ public: { delete m_Pointer; } - m_Pointer = 0; + m_Pointer = ITK_NULLPTR; m_IsOwner = false; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkAutoPointerDataObjectDecorator.h b/Utilities/ITK/Modules/Core/Common/include/itkAutoPointerDataObjectDecorator.h index f292c6e193a1b2e733b6c5a6c7a748756eb3388f..8af6bdf6b371d79af11b8657519fd7d78510025f 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkAutoPointerDataObjectDecorator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkAutoPointerDataObjectDecorator.h @@ -87,7 +87,7 @@ public: protected: AutoPointerDataObjectDecorator(); ~AutoPointerDataObjectDecorator(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; protected: diff --git a/Utilities/ITK/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.hxx index 91234a3d2d4cc41f6c9d844e92e9fb47b44b0354..691386acfc447f7d1b8003f92b08de3238979bc4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.hxx @@ -34,7 +34,7 @@ BSplineInterpolationWeightFunction< TCoordRep, VSpaceDimension, VSplineOrder > { // Initialize the number of weights; m_NumberOfWeights = - static_cast< unsigned int >( vcl_pow( static_cast< double >( SplineOrder + 1 ), + static_cast< unsigned int >( std::pow( static_cast< double >( SplineOrder + 1 ), static_cast< double >( SpaceDimension ) ) ); // Initialize support region is a hypercube of length SplineOrder + 1 @@ -46,8 +46,7 @@ BSplineInterpolationWeightFunction< TCoordRep, VSpaceDimension, VSplineOrder > typedef Image< char, SpaceDimension > CharImageType; typename CharImageType::Pointer tempImage = CharImageType::New(); tempImage->SetRegions(m_SupportSize); - tempImage->Allocate(); - tempImage->FillBuffer(0); + tempImage->Allocate(true); // initialize buffer to zero typedef ImageRegionConstIteratorWithIndex< CharImageType > IteratorType; IteratorType iterator( tempImage, tempImage->GetBufferedRegion() ); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.hxx index 57774e41e2cfc9c1c25c470fc589366d1947bc2d..07cf52486c93384eddc1a7dfc4f735bb8ccd58fe 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.hxx @@ -28,7 +28,7 @@ BinaryThresholdSpatialFunction< TFunction > { m_LowerThreshold = NumericTraits< FunctionOutputType >::NonpositiveMin(); m_UpperThreshold = NumericTraits< FunctionOutputType >::max(); - m_Function = NULL; + m_Function = ITK_NULLPTR; } template< typename TFunction > diff --git a/Utilities/ITK/Modules/Core/Common/include/itkBoundingBox.h b/Utilities/ITK/Modules/Core/Common/include/itkBoundingBox.h index 543b4effbce86443d27c66f127da6fb36be24807..16fc7fa61741810218815b7f6df9e101288ea8b4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkBoundingBox.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkBoundingBox.h @@ -164,7 +164,7 @@ public: bool IsInside(const PointType &) const; /** Method Compute the Modified Time based on changed to the components. */ - ModifiedTimeType GetMTime(void) const; + virtual ModifiedTimeType GetMTime(void) const ITK_OVERRIDE; /** Duplicates this bounding box */ Pointer DeepCopy() const; @@ -172,7 +172,7 @@ public: protected: BoundingBox(); virtual ~BoundingBox(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; typedef typename PointsContainer::ConstIterator ConstIterator; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkBoundingBox.hxx b/Utilities/ITK/Modules/Core/Common/include/itkBoundingBox.hxx index 71f5ebd71bb0310bdee57db888f6725d50dc99b2..a818c406885272a0ead9b3dc4de5f05a1613eff7 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkBoundingBox.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkBoundingBox.hxx @@ -98,12 +98,12 @@ BoundingBox< TPointIdentifier, VPointDimension, TCoordRep, TPointsContainer > radius[i] = m_Bounds[2 * i + 1] - center[i]; } - for ( unsigned int j = 0; j < vcl_pow(2.0, (double)VPointDimension); j++ ) + for ( unsigned int j = 0; j < std::pow(2.0, (double)VPointDimension); j++ ) { PointType pnt; for ( unsigned int i = 0; i < VPointDimension; i++ ) { - pnt[i] = center[i] + vcl_pow( -1.0, ( (double)( j / ( int( vcl_pow(2.0, (double)i) ) ) ) ) ) + pnt[i] = center[i] + std::pow( -1.0, ( (double)( j / ( int( std::pow(2.0, (double)i) ) ) ) ) ) * radius[i]; } @@ -118,7 +118,7 @@ BoundingBox< TPointIdentifier, VPointDimension, TCoordRep, TPointsContainer > template< typename TPointIdentifier, int VPointDimension, typename TCoordRep, typename TPointsContainer > BoundingBox< TPointIdentifier, VPointDimension, TCoordRep, TPointsContainer > -::BoundingBox():m_PointsContainer(NULL) +::BoundingBox():m_PointsContainer(ITK_NULLPTR) { m_Bounds.Fill(NumericTraits< CoordRepType >::Zero); m_CornersContainer = PointsContainer::New(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkCellInterface.h b/Utilities/ITK/Modules/Core/Common/include/itkCellInterface.h index a668aa478479fa14a8711cd5e16d71255c5cdd42..50a4d5d92aba6c06769a5791685f63ea5cc37898 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkCellInterface.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkCellInterface.h @@ -204,7 +204,7 @@ public: return ( *pos ).second; } } - return 0; + return ITK_NULLPTR; } void AddVisitor(VisitorType *v) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkChildTreeIterator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkChildTreeIterator.hxx index 116f23bf717ed2bbdddbd38a9ffacc5d448523cc..fd25efab7460d71a39f37f20cabb4e05a04c1303 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkChildTreeIterator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkChildTreeIterator.hxx @@ -50,7 +50,7 @@ template< typename TTreeType > bool ChildTreeIterator< TTreeType >::GoToChild(ChildIdentifier number) { - if ( m_ParentNode->GetChild(number) == NULL ) + if ( m_ParentNode->GetChild(number) == ITK_NULLPTR ) { return false; } @@ -69,7 +69,7 @@ ChildTreeIterator< TTreeType >::GoToParent() { TreeNodeType *parent = m_ParentNode->GetParent(); - if ( parent == NULL ) + if ( parent == ITK_NULLPTR ) { return false; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkColorTable.h b/Utilities/ITK/Modules/Core/Common/include/itkColorTable.h index 9c735a4c8a9a8f367e7376b889e49c33c06fd376..b30b7e03d50b94bd59b3d95461949208492bf78f 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkColorTable.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkColorTable.h @@ -108,7 +108,7 @@ public: protected: ColorTable(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; unsigned int m_NumberOfColors; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkColorTable.hxx b/Utilities/ITK/Modules/Core/Common/include/itkColorTable.hxx index e0ef0d62186b1e0242ed8aa9b9e577d0daaf1329..7b2ade8a8b259b18cbde06334007bc7437dbeff4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkColorTable.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkColorTable.hxx @@ -386,7 +386,7 @@ ColorTable< TPixel > } else { - return NULL; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkCommand.h b/Utilities/ITK/Modules/Core/Common/include/itkCommand.h index d7dd1af366c437b3a1b1814edb23bc32885a369c..c9032fbe5a5df4652cb0e8634e6b34a94afe8482 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkCommand.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkCommand.h @@ -117,7 +117,7 @@ public: } /** Invoke the member function. */ - virtual void Execute(Object *caller, const EventObject & event) + virtual void Execute(Object *caller, const EventObject & event) ITK_OVERRIDE { if ( m_MemberFunction ) { @@ -126,7 +126,7 @@ public: } /** Invoke the member function with a const object. */ - virtual void Execute(const Object *caller, const EventObject & event) + virtual void Execute(const Object *caller, const EventObject & event) ITK_OVERRIDE { if ( m_ConstMemberFunction ) { @@ -135,15 +135,16 @@ public: } protected: - T * m_This; TMemberFunctionPointer m_MemberFunction; TConstMemberFunctionPointer m_ConstMemberFunction; - MemberCommand(): - m_This( NULL ), - m_MemberFunction( NULL ), - m_ConstMemberFunction( NULL ) + + MemberCommand() : + m_This( ITK_NULLPTR ), + m_MemberFunction( ITK_NULLPTR ), + m_ConstMemberFunction( ITK_NULLPTR ) {} + virtual ~MemberCommand(){} private: @@ -187,7 +188,7 @@ public: } /** Invoke the member function. */ - virtual void Execute(Object *, const EventObject & event) + virtual void Execute(Object *, const EventObject & event) ITK_OVERRIDE { if ( m_MemberFunction ) { @@ -196,7 +197,7 @@ public: } /** Invoke the member function with a const object */ - virtual void Execute(const Object *, const EventObject & event) + virtual void Execute(const Object *, const EventObject & event) ITK_OVERRIDE { if ( m_MemberFunction ) { @@ -207,7 +208,12 @@ public: protected: T * m_This; TMemberFunctionPointer m_MemberFunction; - ReceptorMemberCommand():m_MemberFunction(0) {} + + ReceptorMemberCommand() : + m_This( ITK_NULLPTR ), + m_MemberFunction( ITK_NULLPTR ) + {} + virtual ~ReceptorMemberCommand() {} private: @@ -250,7 +256,7 @@ public: } /** Invoke the callback function. */ - virtual void Execute(Object *, const EventObject &) + virtual void Execute(Object *, const EventObject &) ITK_OVERRIDE { if ( m_MemberFunction ) { @@ -258,7 +264,7 @@ public: } } - virtual void Execute(const Object *, const EventObject &) + virtual void Execute(const Object *, const EventObject &) ITK_OVERRIDE { if ( m_MemberFunction ) { @@ -269,10 +275,12 @@ public: protected: T * m_This; TMemberFunctionPointer m_MemberFunction; - SimpleMemberCommand(): - m_This( NULL ), - m_MemberFunction( NULL ) + + SimpleMemberCommand() : + m_This( ITK_NULLPTR ), + m_MemberFunction( ITK_NULLPTR ) {} + virtual ~SimpleMemberCommand() {} private: @@ -315,7 +323,7 @@ public: } /** Invoke the const member method callback. */ - virtual void Execute(Object *, const EventObject &) + virtual void Execute(Object *, const EventObject &) ITK_OVERRIDE { if ( m_MemberFunction ) { @@ -323,7 +331,7 @@ public: } } - virtual void Execute(const Object *, const EventObject &) + virtual void Execute(const Object *, const EventObject &) ITK_OVERRIDE { if ( m_MemberFunction ) { @@ -334,10 +342,12 @@ public: protected: const T * m_This; TMemberFunctionPointer m_MemberFunction; - SimpleConstMemberCommand(): + + SimpleConstMemberCommand() : m_This( NULL ), m_MemberFunction( NULL ) {} + virtual ~SimpleConstMemberCommand() {} private: @@ -391,7 +401,7 @@ public: { m_ClientDataDeleteCallback = f; } /** Execute the callback function. */ - void Execute(Object *caller, const EventObject & event) + virtual void Execute(Object *caller, const EventObject & event) ITK_OVERRIDE { if ( m_Callback ) { @@ -400,7 +410,7 @@ public: } /** Execute the callback function with a const Object */ - void Execute(const Object *caller, const EventObject & event) + virtual void Execute(const Object *caller, const EventObject & event) ITK_OVERRIDE { if ( m_ConstCallback ) { @@ -409,11 +419,12 @@ public: } protected: - CStyleCommand():m_ClientData(0), m_Callback(0), m_ConstCallback(0), - m_ClientDataDeleteCallback(0) - { - // not implemented - } + CStyleCommand() : + m_ClientData( ITK_NULLPTR ), + m_Callback( ITK_NULLPTR ), + m_ConstCallback( ITK_NULLPTR ), + m_ClientDataDeleteCallback( ITK_NULLPTR ) + {} ~CStyleCommand() { diff --git a/Utilities/ITK/Modules/Core/Common/include/itkConceptChecking.h b/Utilities/ITK/Modules/Core/Common/include/itkConceptChecking.h index 7ae9319e76f290c788e6e0f652ea5e377b547f3c..c73c754c570adfeddbab5c1fccab888edb649da1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkConceptChecking.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkConceptChecking.h @@ -591,13 +591,13 @@ struct HasNumericTraits { struct Constraints { void constraints() { - typedef typename NumericTraits< T >::ValueType ValueType; - typedef typename NumericTraits< T >::PrintType PrintType; - typedef typename NumericTraits< T >::AbsType AbsType; - typedef typename NumericTraits< T >::AccumulateType AccumulateType; - typedef typename NumericTraits< T >::RealType RealType; - typedef typename NumericTraits< T >::ScalarRealType ScalarRealType; - typedef typename NumericTraits< T >::FloatType FloatType; + Detail::UniqueType< typename NumericTraits< T >::ValueType >(); + Detail::UniqueType< typename NumericTraits< T >::PrintType >(); + Detail::UniqueType< typename NumericTraits< T >::AbsType >(); + Detail::UniqueType< typename NumericTraits< T >::AccumulateType >(); + Detail::UniqueType< typename NumericTraits< T >::RealType >(); + Detail::UniqueType< typename NumericTraits< T >::ScalarRealType >(); + Detail::UniqueType< typename NumericTraits< T >::FloatType >(); T a; bool b; @@ -625,7 +625,7 @@ struct HasPixelTraits { struct Constraints { void constraints() { - typedef typename PixelTraits< T >::ValueType ValueType; + Detail::UniqueType< typename PixelTraits< T >::ValueType >(); unsigned int a = PixelTraits< T >::Dimension; Detail::IgnoreUnusedVariable(a); } @@ -640,7 +640,7 @@ struct HasValueType { struct Constraints { void constraints() { - typedef typename T::ValueType ValueType; + Detail::UniqueType< typename T::ValueType >(); } }; @@ -669,7 +669,7 @@ struct HasJoinTraits { struct Constraints { void constraints() { - typedef typename JoinTraits< T1, T2 >::ValueType ValueType; + Detail::UniqueType< typename JoinTraits< T1, T2 >::ValueType >(); } }; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkConditionalConstIterator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkConditionalConstIterator.hxx index dcc85fe467d3d35b572fe0fedf4a84f56385f809..57d91f973f935ce68b69832f494b01801b085e81 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkConditionalConstIterator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkConditionalConstIterator.hxx @@ -24,7 +24,7 @@ namespace itk { template< typename TImageType > ConditionalConstIterator< TImageType > -::ConditionalConstIterator() +::ConditionalConstIterator() : m_IsAtEnd(false) {} template< typename TImageType > diff --git a/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIterator.h index 7dafc77c8c8911d8e583ee1cfc4920807768e26a..f92c65a6daa7703b8d4aa687affeb9a6f8b48ebb 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIterator.h @@ -57,12 +57,12 @@ public: typedef typename TImage::InternalPixelType InternalPixelType; typedef typename TImage::PixelType PixelType; - /** Save the image dimension. */ - itkStaticConstMacro(Dimension, unsigned int, TImage::ImageDimension); - /** Type used to refer to space dimensions */ typedef unsigned int DimensionValueType; + /** Save the image dimension. */ + itkStaticConstMacro(Dimension, DimensionValueType, TImage::ImageDimension); + /** Standard class typedefs. */ typedef ConstNeighborhoodIterator Self; typedef Neighborhood< InternalPixelType *, @@ -115,7 +115,7 @@ public: const RegionType & region) { this->Initialize(radius, ptr, region); - for ( unsigned int i = 0; i < Dimension; i++ ) + for ( DimensionValueType i = 0; i < Dimension; i++ ) { m_InBounds[i] = false; } this->ResetBoundaryCondition(); m_NeighborhoodAccessorFunctor = ptr->GetNeighborhoodAccessor(); @@ -130,7 +130,7 @@ public: /** Computes the internal, N-d offset of a pixel array position n from * (0,0, ..., 0) in the "upper-left" corner of the neighborhood. */ - OffsetType ComputeInternalIndex(NeighborIndexType n) const; + OffsetType ComputeInternalIndex(const NeighborIndexType n) const; /** Returns the array of upper loop bounds used during iteration. */ IndexType GetBound() const diff --git a/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIterator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIterator.hxx index a89a84bba7498cee361c337749b3f218be666465..3d63f26219d8362b37e30529a602aa9968d9814a 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIterator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIterator.hxx @@ -146,7 +146,7 @@ ConstNeighborhoodIterator< TImage, TBoundaryCondition > template< typename TImage, typename TBoundaryCondition > typename ConstNeighborhoodIterator< TImage, TBoundaryCondition >::OffsetType ConstNeighborhoodIterator< TImage, TBoundaryCondition > -::ComputeInternalIndex(NeighborIndexType n) const +::ComputeInternalIndex(const NeighborIndexType n) const { OffsetType ans; long D = (long)Dimension; @@ -166,9 +166,9 @@ typename ConstNeighborhoodIterator< TImage, TBoundaryCondition >::RegionType ConstNeighborhoodIterator< TImage, TBoundaryCondition > ::GetBoundingBoxAsImageRegion() const { + const IndexValueType zero = NumericTraits< IndexValueType >::Zero; RegionType ans; - IndexValueType zero = NumericTraits< IndexValueType >::Zero; ans.SetIndex( this->GetIndex(zero) ); ans.SetSize( this->GetSize() ); @@ -177,17 +177,19 @@ ConstNeighborhoodIterator< TImage, TBoundaryCondition > template< typename TImage, typename TBoundaryCondition > ConstNeighborhoodIterator< TImage, TBoundaryCondition > -::ConstNeighborhoodIterator() +::ConstNeighborhoodIterator() : + m_IsInBounds(false), + m_IsInBoundsValid(false), + m_NeedToUseBoundaryCondition(false) { IndexType zeroIndex; zeroIndex.Fill(0); - SizeType zeroSize; zeroSize.Fill(0); m_Bound.Fill(0); - m_Begin = 0; + m_Begin = ITK_NULLPTR; m_BeginIndex.Fill(0); - // m_ConstImage - m_End = 0; + + m_End = ITK_NULLPTR; m_EndIndex.Fill(0); m_Loop.Fill(0); m_Region.SetIndex(zeroIndex); @@ -202,9 +204,6 @@ ConstNeighborhoodIterator< TImage, TBoundaryCondition > this->ResetBoundaryCondition(); - m_IsInBounds = false; - m_IsInBoundsValid = false; - m_BoundaryCondition = &m_InternalBoundaryCondition; } @@ -411,8 +410,9 @@ ConstNeighborhoodIterator< TImage, TBoundaryCondition > m_NeedToUseBoundaryCondition = false; for ( DimensionValueType i = 0; i < Dimension; ++i ) { - OffsetValueType overlapLow = static_cast< OffsetValueType >( ( rStart[i] - static_cast<OffsetValueType>( this->GetRadius(i) ) ) - bStart[i] ); - OffsetValueType overlapHigh = static_cast< OffsetValueType >( ( bStart[i] + bSize[i] ) + const OffsetValueType overlapLow = static_cast< OffsetValueType >( ( rStart[i] + - static_cast<OffsetValueType>( this->GetRadius(i) ) ) - bStart[i] ); + const OffsetValueType overlapHigh = static_cast< OffsetValueType >( ( bStart[i] + bSize[i] ) - ( rStart[i] + rSize[i] + static_cast<OffsetValueType>( this->GetRadius(i) ) ) ); if ( overlapLow < 0 ) // out of bounds condition, define a region of diff --git a/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.hxx b/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.hxx index 54dbd1ab2446a5c77ebfa917c5ae28565c2994be..05beba989166f8cbfaaf50c64ace0ab7ef251cde 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.hxx @@ -162,6 +162,7 @@ ConstNeighborhoodIteratorWithOnlyIndex< TImage > m_IsInBounds = false; m_IsInBoundsValid = false; + m_NeedToUseBoundaryCondition = false; } template< typename TImage > diff --git a/Utilities/ITK/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.h index 2633872ae722e68c09c5cbf0996b3bb5fd0bb5d8..b510022cc71a4365798dc7b9bba3f61cdca2ed2c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.h @@ -117,7 +117,7 @@ public: /** Const Interator */ struct ConstIterator { - ConstIterator() { m_NeighborhoodIterator = 0; } + ConstIterator() { m_NeighborhoodIterator = ITK_NULLPTR; } ConstIterator(Self *s) { m_NeighborhoodIterator = s; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkCovariantVector.h b/Utilities/ITK/Modules/Core/Common/include/itkCovariantVector.h index 5aac44b9aee0edb34ecdc4081fe40ada877404e5..ee340758c1a389f7c55283a43b416932780cd09c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkCovariantVector.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkCovariantVector.h @@ -243,7 +243,7 @@ inline CovariantVector< T, NVectorDimension > operator*(const T & scalar, const CovariantVector< T, NVectorDimension > & v) { - return v * scalar; + return v.operator*(scalar); } /** Performs the scalar product of a covariant with a contravariant. diff --git a/Utilities/ITK/Modules/Core/Common/include/itkCovariantVector.hxx b/Utilities/ITK/Modules/Core/Common/include/itkCovariantVector.hxx index 7e8ee48401d1b66fe20428533065e5d287a1388d..3d143ed470c8939debb56c6fbd6cadf7b22fcfa4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkCovariantVector.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkCovariantVector.hxx @@ -194,7 +194,7 @@ typename CovariantVector< T, NVectorDimension >::RealValueType CovariantVector< T, NVectorDimension > ::GetNorm(void) const { - return vcl_sqrt( this->GetSquaredNorm() ); + return std::sqrt( this->GetSquaredNorm() ); } /** diff --git a/Utilities/ITK/Modules/Core/Common/include/itkCreateObjectFunction.h b/Utilities/ITK/Modules/Core/Common/include/itkCreateObjectFunction.h index a5d8c91365cd7d9387034b46932b80575450998b..ca4c2fb77527c4bc00b73ff8ffe6d8b47ee8fca5 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkCreateObjectFunction.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkCreateObjectFunction.h @@ -67,7 +67,7 @@ public: /** Methods from itk:LightObject. */ itkFactorylessNewMacro(Self); - LightObject::Pointer CreateObject() { return T::New().GetPointer(); } + virtual LightObject::Pointer CreateObject() ITK_OVERRIDE { return T::New().GetPointer(); } protected: CreateObjectFunction() {} diff --git a/Utilities/ITK/Modules/Core/Common/include/itkDataObject.h b/Utilities/ITK/Modules/Core/Common/include/itkDataObject.h index 5ec0b557abb7926c37aed3fc3778e2eb2ce8ae15..bbed8ff002ab0c8dd15407c2a3e40774dc4d0fac 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkDataObject.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkDataObject.h @@ -124,7 +124,7 @@ protected: * specific exception subtypes. The default is to print out the * location where the exception was first thrown and any description * provided by the ``thrower''. */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; }; /*----------------------------Data Object--------------------------------*/ @@ -481,7 +481,7 @@ public: protected: DataObject(); ~DataObject(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Propagate a call to ResetPipeline(). Called only from ProcessObject. */ virtual void PropagateResetPipeline(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkDataObjectDecorator.h b/Utilities/ITK/Modules/Core/Common/include/itkDataObjectDecorator.h index 779154f9c85c63ee60ead3a91f060d9df07d9917..f75b7aff21e1b74555edc7b11096b7b63061da54 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkDataObjectDecorator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkDataObjectDecorator.h @@ -74,6 +74,7 @@ public: /** Typedef for the component type (object being decorated) */ typedef T ComponentType; + typedef typename T::Pointer ComponentPointer; typedef typename T::ConstPointer ComponentConstPointer; /** Method for creation through the object factory. */ @@ -83,15 +84,49 @@ public: itkTypeMacro(DataObjectDecorator, DataObject); /** Set the contained object */ - virtual void Set(const T *val); + virtual void Set( const ComponentType *val); /** Get the contained object */ - virtual const T * Get() const; + virtual const ComponentType * Get() const; + virtual ComponentType * GetModifiable(); + + /** The most recent MTime of this object and the held component */ + virtual ModifiedTimeType GetMTime() const ITK_OVERRIDE; + + /** Restore the data object to its initial state. This means + * releasing the help component. + */ + virtual void Initialize() ITK_OVERRIDE; + + /** \brief Graft the content of one decorator onto another + * + * The DataObject is dynamically_cast to this type, if successful + * then the component pointer is copies to that both decorators + * refer to the same object. + */ + virtual void Graft( const DataObject * ) ITK_OVERRIDE; + void Graft( const Self * decorator ); + + /** Method to aid in dynamic Graft of polymorphic types. + * + * To this method by default a raw pointer must be used or explicit + * template parameter must be provided. + */ + template <typename TOther> + void Graft( const DataObjectDecorator<TOther> * decorator ) + { + ComponentType *component = const_cast< ComponentType * >( dynamic_cast< const ComponentType * >( decorator->Get() ) ); + if ( !component ) + { + return; + } + this->Set( component ); + } protected: DataObjectDecorator(); ~DataObjectDecorator(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; protected: @@ -99,7 +134,7 @@ private: DataObjectDecorator(const Self &); //purposely not implemented void operator=(const Self &); //purposely not implemented - ComponentConstPointer m_Component; + ComponentPointer m_Component; }; } // end namespace itk diff --git a/Utilities/ITK/Modules/Core/Common/include/itkDataObjectDecorator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkDataObjectDecorator.hxx index d947bf9ef2762d2e3823c3ba78409421109e0cd1..bd786133ee397501f03153b3a712eec62ea4a410 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkDataObjectDecorator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkDataObjectDecorator.hxx @@ -29,6 +29,7 @@ #define __itkDataObjectDecorator_hxx #include "itkDataObjectDecorator.h" +#include <algorithm> namespace itk { @@ -37,7 +38,7 @@ namespace itk */ template< typename T > DataObjectDecorator< T > -::DataObjectDecorator():m_Component() +::DataObjectDecorator() {} /** @@ -54,11 +55,11 @@ DataObjectDecorator< T > template< typename T > void DataObjectDecorator< T > -::Set(const T *val) +::Set( const ComponentType *val) { if ( m_Component != val ) { - m_Component = val; + m_Component = const_cast<ComponentType*>(val); this->Modified(); } } @@ -71,7 +72,84 @@ const T * DataObjectDecorator< T > ::Get() const { - return m_Component; + return m_Component.GetPointer(); +} + +/** + * + */ +template< typename T > +T * +DataObjectDecorator< T > +::GetModifiable() +{ + return m_Component.GetPointer(); +} + +/** + * + */ +template< typename T > +ModifiedTimeType +DataObjectDecorator< T > +::GetMTime() const +{ + const ModifiedTimeType t = Superclass::GetMTime(); + if (m_Component.IsNotNull()) + { + return std::max(t, m_Component->GetMTime()); + } + return t; +} + +/** + * + */ +template< typename T > +void +DataObjectDecorator< T > +::Initialize() +{ + Superclass::Initialize(); + + // make sure the MTime does not change + if ( m_Component.IsNull()) + { + return; + } + if ( m_Component->GetMTime() > Superclass::GetMTime() ) + { + this->SetTimeStamp(m_Component->GetTimeStamp()); + } + m_Component = ITK_NULLPTR; +} + +/** + * + */ +template< typename T > +void +DataObjectDecorator< T > +::Graft( const DataObject *data ) +{ + const Self *decorator = dynamic_cast< const Self * >( data ); + this->Graft(decorator); +} + +/** + * + */ +template< typename T > +void +DataObjectDecorator< T > +::Graft( const Self *data ) +{ + if ( !data ) + { + return; + } + + this->Set(data->m_Component); } /** diff --git a/Utilities/ITK/Modules/Core/Common/include/itkDefaultVectorPixelAccessorFunctor.h b/Utilities/ITK/Modules/Core/Common/include/itkDefaultVectorPixelAccessorFunctor.h index ecc85c4be7f8e09057dcbca76571a8d734e8ef86..d3c37c8262c5bda31e699055c5c803995b4f3ae1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkDefaultVectorPixelAccessorFunctor.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkDefaultVectorPixelAccessorFunctor.h @@ -76,6 +76,9 @@ public: return image->GetVectorLength(); } + + DefaultVectorPixelAccessorFunctor () : m_Begin(ITK_NULLPTR) {} + /** Set the PixelAccessor. This is set at construction time by the image iterators. * The type PixelAccessorType is obtained from the ImageType over which the iterators * are templated. diff --git a/Utilities/ITK/Modules/Core/Common/include/itkDiffusionTensor3D.hxx b/Utilities/ITK/Modules/Core/Common/include/itkDiffusionTensor3D.hxx index 5dabb615412e8af9c0cb79e22f8bf990a999376b..65bd6b96d76f0a602bde677413a7e19de737e18c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkDiffusionTensor3D.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkDiffusionTensor3D.hxx @@ -127,7 +127,7 @@ DiffusionTensor3D< T > ::GetFractionalAnisotropy() const { // Computed as - // FA = vcl_sqrt(1.5*sum(sum(N.*N))/sum((sum(D.*D)))) + // FA = std::sqrt(1.5*sum(sum(N.*N))/sum((sum(D.*D)))) // where N = D - ((1/3)*trace(D)*eye(3,3)) // equation (28) in // http://lmi.bwh.harvard.edu/papers/pdfs/2002/westinMEDIA02.pdf @@ -138,7 +138,7 @@ DiffusionTensor3D< T > const RealValueType trace = this->GetTrace(); const RealValueType anisotropy = 3.0 * isp - trace * trace; // sometimes anisotropy has been reported to be a small negative - // number, and then vcl_sqrt returns NaN. If it is a small + // number, and then std::sqrt returns NaN. If it is a small // negative number, the obvious thing is to round to zero. If // it is a larger negative number, I'm not sure what the proper // result would be. In either case, returning zero makes as much @@ -146,7 +146,7 @@ DiffusionTensor3D< T > if(anisotropy > 0.0) { const RealValueType fractionalAnisotropy = - static_cast< RealValueType >( vcl_sqrt( anisotropy / ( 2.0 * isp ) ) ); + static_cast< RealValueType >( std::sqrt( anisotropy / ( 2.0 * isp ) ) ); return fractionalAnisotropy; } } @@ -180,10 +180,10 @@ DiffusionTensor3D< T > } const RealValueType relativeAnisotropySquared = - static_cast< RealValueType >( anisotropy / ( vcl_sqrt(3.0) * trace ) ); + static_cast< RealValueType >( anisotropy / ( std::sqrt(3.0) * trace ) ); const RealValueType relativeAnisotropy = - static_cast< RealValueType >( vcl_sqrt(relativeAnisotropySquared) ); + static_cast< RealValueType >( std::sqrt(relativeAnisotropySquared) ); return relativeAnisotropy; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkDirectory.h b/Utilities/ITK/Modules/Core/Common/include/itkDirectory.h index ec463de659a7dd986c48ea76cb83e13a4008135e..f47f602638dc47faf413c7d76cccbd1819ba95f5 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkDirectory.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkDirectory.h @@ -66,7 +66,7 @@ public: protected: Directory(); ~Directory(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: Directory(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkDomainThreader.hxx b/Utilities/ITK/Modules/Core/Common/include/itkDomainThreader.hxx index ab3531546bf5cced7c83d0fbbe147f1a95bbbb35..fef3af85123e595624d5532556399e4dcac69166 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkDomainThreader.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkDomainThreader.hxx @@ -30,7 +30,7 @@ DomainThreader< TDomainPartitioner, TAssociate > this->m_DomainPartitioner = DomainPartitionerType::New(); this->m_MultiThreader = MultiThreader::New(); this->m_NumberOfThreadsUsed = 0; - this->m_Associate = NULL; + this->m_Associate = ITK_NULLPTR; } template< typename TDomainPartitioner, typename TAssociate > @@ -149,7 +149,7 @@ DomainThreader< TDomainPartitioner, TAssociate > subdomain); // Execute the actual method with appropriate sub-domain. - // If the threadID is greater than the total number of regions + // If the threadId is greater than the total number of regions // that PartitionDomain will create, don't use this thread. // Sometimes the threads dont break up very well and it is just // as efficient to leave a few threads idle. diff --git a/Utilities/ITK/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.hxx index dde7903019f36023fa66d8f0982e194210e20dc6..778e4077e28e9b43c2f9c14f722f67c51f0dab5f 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.hxx @@ -27,7 +27,7 @@ template< unsigned int VDimension, typename TInput > EllipsoidInteriorExteriorSpatialFunction< VDimension, TInput > ::EllipsoidInteriorExteriorSpatialFunction() { - m_Orientations = NULL; + m_Orientations = ITK_NULLPTR; m_Axes.Fill(1.0f); // Lengths of ellipsoid axes. m_Center.Fill(0.0f); // Origin of ellipsoid } @@ -72,7 +72,7 @@ EllipsoidInteriorExteriorSpatialFunction< VDimension, TInput > { orientationVector[j] = m_Orientations[i][j]; } - distanceSquared += vcl_pow( static_cast< double >( ( orientationVector * pointVector ) / ( .5 * m_Axes[i] ) ), + distanceSquared += std::pow( static_cast< double >( ( orientationVector * pointVector ) / ( .5 * m_Axes[i] ) ), static_cast< double >( 2 ) ); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkEquivalencyTable.h b/Utilities/ITK/Modules/Core/Common/include/itkEquivalencyTable.h index 083498c37ecf6b78ab34ef890a48d5304b41b037..86cddbbfcd3efe3e8e9b1626d0f2d0f9c8237193 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkEquivalencyTable.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkEquivalencyTable.h @@ -140,7 +140,7 @@ protected: EquivalencyTable(const Self &); // purposely not implemented void operator=(const Self &); // purposely not implemented - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; HashTableType m_HashMap; }; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkEventObject.h b/Utilities/ITK/Modules/Core/Common/include/itkEventObject.h index 0a57d236c1da90e6f4565e1d32c51b12937ef7f9..f4488570acbe01126307cb5c7a7b196ed75a3d9d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkEventObject.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkEventObject.h @@ -143,6 +143,7 @@ itkEventMacro(AbortEvent, AnyEvent) itkEventMacro(ModifiedEvent, AnyEvent) itkEventMacro(InitializeEvent, AnyEvent) itkEventMacro(IterationEvent, AnyEvent) +itkEventMacro(MultiResolutionIterationEvent,IterationEvent) itkEventMacro(PickEvent, AnyEvent) itkEventMacro(StartPickEvent, PickEvent) itkEventMacro(EndPickEvent, PickEvent) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkExceptionObject.h b/Utilities/ITK/Modules/Core/Common/include/itkExceptionObject.h index abae28ff0ace43296f40a912498f0be5cbed6f50..2765bee111650c1550e6750ff37374f5bb212168 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkExceptionObject.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkExceptionObject.h @@ -104,8 +104,7 @@ public: virtual unsigned int GetLine() const; /** Provide std::exception::what() implementation. */ - virtual const char * what() const - throw( ); + virtual const char * what() const throw( ) ITK_OVERRIDE; private: /** \class ReferenceCounterInterface @@ -165,7 +164,7 @@ inline std::ostream & operator<<(std::ostream & os, ExceptionObject & e) * \ingroup ITKSystemObjects * \ingroup ITKCommon */ -class MemoryAllocationError:public ExceptionObject +class ITKCommon_EXPORT MemoryAllocationError:public ExceptionObject { public: /** Default constructor. Needed to ensure the exception object can be @@ -185,10 +184,9 @@ public: const std::string & loc):ExceptionObject(file, lineNumber, desc, loc) {} /** Virtual destructor needed for subclasses. Has to have empty throw(). */ - virtual ~MemoryAllocationError() - throw( ) {} + virtual ~MemoryAllocationError() throw( ); - virtual const char * GetNameOfClass() const + virtual const char * GetNameOfClass() const ITK_OVERRIDE { return "MemoryAllocationError"; } }; @@ -197,7 +195,7 @@ public: * \ingroup ITKSystemObjects * \ingroup ITKCommon */ -class RangeError:public ExceptionObject +class ITKCommon_EXPORT RangeError:public ExceptionObject { public: /** Default constructor. Needed to ensure the exception object can be @@ -211,10 +209,9 @@ public: RangeError(const std::string & file, unsigned int lineNumber):ExceptionObject(file, lineNumber) {} /** Virtual destructor needed for subclasses. Has to have empty throw(). */ - virtual ~RangeError() - throw( ) {} + virtual ~RangeError() throw( ); - virtual const char * GetNameOfClass() const + virtual const char * GetNameOfClass() const ITK_OVERRIDE { return "RangeError"; } }; @@ -224,7 +221,7 @@ public: * \ingroup ITKSystemObjects * \ingroup ITKCommon */ -class InvalidArgumentError:public ExceptionObject +class ITKCommon_EXPORT InvalidArgumentError:public ExceptionObject { public: /** @@ -244,10 +241,9 @@ public: InvalidArgumentError(const std::string & file, unsigned int lineNumber):ExceptionObject(file, lineNumber) {} /** Virtual destructor needed for subclasses. Has to have empty throw(). */ - virtual ~InvalidArgumentError() - throw( ) {} + virtual ~InvalidArgumentError() throw( ); - virtual const char * GetNameOfClass() const + virtual const char * GetNameOfClass() const ITK_OVERRIDE { return "InvalidArgumentError"; } }; @@ -256,7 +252,7 @@ public: * \ingroup ITKSystemObjects * \ingroup ITKCommon */ -class IncompatibleOperandsError:public ExceptionObject +class ITKCommon_EXPORT IncompatibleOperandsError:public ExceptionObject { public: /** Default constructor. Needed to ensure the exception object can be @@ -270,10 +266,9 @@ public: IncompatibleOperandsError(const std::string & file, unsigned int lineNumber):ExceptionObject(file, lineNumber) {} /** Virtual destructor needed for subclasses. Has to have empty throw(). */ - virtual ~IncompatibleOperandsError() - throw( ) {} + virtual ~IncompatibleOperandsError() throw( ); - virtual const char * GetNameOfClass() const + virtual const char * GetNameOfClass() const ITK_OVERRIDE { return "IncompatibleOperandsError"; } }; @@ -282,7 +277,7 @@ public: * \ingroup ITKSystemObjects * \ingroup ITKCommon */ -class ProcessAborted:public ExceptionObject +class ITKCommon_EXPORT ProcessAborted:public ExceptionObject { public: /** Default constructor. Needed to ensure the exception object can be @@ -305,10 +300,9 @@ public: } /** Virtual destructor needed for subclasses. Has to have empty throw(). */ - virtual ~ProcessAborted() - throw( ) {} + virtual ~ProcessAborted() throw( ); - virtual const char * GetNameOfClass() const + virtual const char * GetNameOfClass() const ITK_OVERRIDE { return "ProcessAborted"; } }; } // end namespace itk diff --git a/Utilities/ITK/Modules/Core/Common/include/itkFastMutexLock.h b/Utilities/ITK/Modules/Core/Common/include/itkFastMutexLock.h index 14a623b18d4521d6451a8bb71691d4350aa03259..cf3c8c24eb3325696c4fa8e1610092624bb053f2 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkFastMutexLock.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkFastMutexLock.h @@ -82,7 +82,7 @@ protected: ~FastMutexLock() {} SimpleFastMutexLock m_SimpleFastMutexLock; - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: FastMutexLock(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkFileOutputWindow.h b/Utilities/ITK/Modules/Core/Common/include/itkFileOutputWindow.h index e033d0b30ad9f186773c9b3d8e7cc46ddd71377e..8d6c278d0cbb44fd2904a35f2f91e774f656bd17 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkFileOutputWindow.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkFileOutputWindow.h @@ -51,7 +51,7 @@ public: itkTypeMacro(FileOutputWindow, OutputWindow); /** Send a string to display. */ - virtual void DisplayText(const char *); + virtual void DisplayText(const char *) ITK_OVERRIDE; /** Set the filename for the log file */ itkSetStringMacro(FileName); @@ -75,7 +75,7 @@ public: protected: FileOutputWindow(); virtual ~FileOutputWindow(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void Initialize(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.hxx index 33339f6a78169763d2e0b84a829014bf8ed9cd65..8db72b61b769d8936b99a05fed682e410267352a 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.hxx @@ -29,7 +29,7 @@ FiniteCylinderSpatialFunction< VDimension, TInput > { // a normalized {1,1,...1} vector is // { 1.0 / sqrt( VDmim ), ... } - const double orientationVal = 1.0 / vcl_sqrt(static_cast<double>(VDimension)); + const double orientationVal = 1.0 / std::sqrt(static_cast<double>(VDimension)); m_Orientation.Fill(orientationVal); m_NormalizedOrientation.Fill(orientationVal); m_AxisLength = 1.0f; // Length of cylinder axis. @@ -59,7 +59,7 @@ FiniteCylinderSpatialFunction< VDimension, TInput > { norm += this->m_Orientation[i] * this->m_Orientation[i]; } - norm = vcl_sqrt(norm); + norm = std::sqrt(norm); if(norm == 0.0) // avoid divide by zero { itkExceptionMacro(<< "Degenerate orientation vector " << this->m_Orientation); @@ -97,8 +97,8 @@ FiniteCylinderSpatialFunction< VDimension, TInput > //the point is within the length of the cylinder along the medial axis const double distanceFromCenter = dot_product( medialAxisVector.GetVnlVector(), pointVector.GetVnlVector() ); - if ( vcl_fabs(distanceFromCenter) <= ( halfAxisLength ) - && m_Radius >= vcl_sqrt( vcl_pow(pointVector.GetVnlVector().magnitude(), 2.0) - vcl_pow(distanceFromCenter, 2.0) ) ) + if ( std::fabs(distanceFromCenter) <= ( halfAxisLength ) + && m_Radius >= std::sqrt( std::pow(pointVector.GetVnlVector().magnitude(), 2.0) - std::pow(distanceFromCenter, 2.0) ) ) { return 1; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkFixedArray.h b/Utilities/ITK/Modules/Core/Common/include/itkFixedArray.h index e11a2d7617f7355dbb22211f3b2512dde424b655..5b3254326115572a5d3fec4fa08705a17fee6572 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkFixedArray.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkFixedArray.h @@ -31,7 +31,7 @@ namespace itk * assigned to one another, and size information is known for function * returns. * - * \tparam TValueType Element type stored at each location in the array. + * \tparam TValue Element type stored at each location in the array. * \tparam VLength = Length of the array. * * The length of the array is fixed at compile time. If you wish to @@ -46,7 +46,7 @@ namespace itk * \wikiexample{Utilities/FixedArray,C-style array} * \endwiki */ -template< typename TValueType, unsigned int VLength = 3 > +template< typename TValue, unsigned int VLength = 3 > class FixedArray { public: @@ -57,7 +57,7 @@ public: itkStaticConstMacro(Dimension, unsigned int, VLength); /** The element type stored at each location in the FixedArray. */ - typedef TValueType ValueType; + typedef TValue ValueType; /** A type representing the C-array version of this FixedArray. */ typedef ValueType CArray[VLength]; @@ -142,7 +142,7 @@ public: Iterator i = this->Begin(); while ( i != this->End() ) { - *i++ = static_cast< TValueType >( *input++ ); + *i++ = static_cast< TValue >( *input++ ); } } @@ -169,13 +169,13 @@ public: template< typename TFixedArrayValueType > FixedArray & operator=(const FixedArray< TFixedArrayValueType, VLength > & r) { - if ( (void *)r.Begin() != (void *)m_InternalArray ) + if ( (const void *)r.Begin() != (const void *)m_InternalArray ) { typename FixedArray< TFixedArrayValueType, VLength >::ConstIterator input = r.Begin(); Iterator i = this->Begin(); while ( i != this->End() ) { - *i++ = static_cast< TValueType >( *input++ ); + *i++ = static_cast< TValue >( *input++ ); } } return *this; @@ -200,8 +200,20 @@ public: const_reference operator[](unsigned short index) const { return m_InternalArray[index]; } reference operator[](int index) { return m_InternalArray[index]; } const_reference operator[](int index) const { return m_InternalArray[index]; } +// false positive warnings with GCC 4.9 +#if defined( __GNUC__ ) +#if ( __GNUC__ == 4 ) && ( __GNUC_MINOR__ == 9 ) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Warray-bounds" +#endif +#endif reference operator[](unsigned int index) { return m_InternalArray[index]; } const_reference operator[](unsigned int index) const { return m_InternalArray[index]; } +#if defined( __GNUC__ ) +#if ( __GNUC__ == 4 ) && ( __GNUC_MINOR__ == 9 ) +#pragma GCC diagnostic pop +#endif +#endif reference operator[](long index) { return m_InternalArray[index]; } const_reference operator[](long index) const { return m_InternalArray[index]; } reference operator[](unsigned long index) { return m_InternalArray[index]; } @@ -257,8 +269,8 @@ public: static FixedArray Filled(const ValueType &); }; -template< typename TValueType, unsigned int VLength > -std::ostream & operator<<(std::ostream & os, const FixedArray< TValueType, VLength > & arr); +template< typename TValue, unsigned int VLength > +std::ostream & operator<<(std::ostream & os, const FixedArray< TValue, VLength > & arr); } // namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Utilities/ITK/Modules/Core/Common/include/itkFixedArray.hxx b/Utilities/ITK/Modules/Core/Common/include/itkFixedArray.hxx index 0af8d54b962c3f90af393ebc17394811ef07f0e3..764ca94448630864e42462adcdec92fe381d351f 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkFixedArray.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkFixedArray.hxx @@ -26,16 +26,16 @@ namespace itk * Default constructor uses compiler's default initialization of memory. * For efficiency, no initialization to zero is done. */ -template< typename TValueType, unsigned int VLength > -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +FixedArray< TValue, VLength > ::FixedArray() {} /** * Constructor to initialize entire array to one value. */ -template< typename TValueType, unsigned int VLength > -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +FixedArray< TValue, VLength > ::FixedArray(const ValueType & r) { for ( Iterator i = Begin(); i != End(); ++i ) @@ -49,8 +49,8 @@ FixedArray< TValueType, VLength > * Values are copied individually instead of with a binary copy. This * allows the ValueType's assignment operator to be executed. */ -template< typename TValueType, unsigned int VLength > -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +FixedArray< TValue, VLength > ::FixedArray(const ValueType r[VLength]) { ConstIterator input = r; @@ -67,9 +67,9 @@ FixedArray< TValueType, VLength > * Values are copied individually instead of with a binary copy. This * allows the ValueType's assignment operator to be executed. */ -template< typename TValueType, unsigned int VLength > -FixedArray< TValueType, VLength > & -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +FixedArray< TValue, VLength > & +FixedArray< TValue, VLength > ::operator=(const ValueType r[VLength]) { if ( r != m_InternalArray ) @@ -87,9 +87,9 @@ FixedArray< TValueType, VLength > /** * Operator != compares different types of arrays. */ -template< typename TValueType, unsigned int VLength > +template< typename TValue, unsigned int VLength > bool -FixedArray< TValueType, VLength > +FixedArray< TValue, VLength > ::operator==(const FixedArray & r) const { ConstIterator i = this->Begin(); @@ -111,9 +111,9 @@ FixedArray< TValueType, VLength > /** * Get an Iterator for the beginning of the FixedArray. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::Iterator -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::Iterator +FixedArray< TValue, VLength > ::Begin() { return Iterator(m_InternalArray); @@ -122,9 +122,9 @@ FixedArray< TValueType, VLength > /** * Get a ConstIterator for the beginning of the FixedArray. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::ConstIterator -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::ConstIterator +FixedArray< TValue, VLength > ::Begin() const { return ConstIterator(m_InternalArray); @@ -133,9 +133,9 @@ FixedArray< TValueType, VLength > /** * Get an Iterator for the end of the FixedArray. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::Iterator -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::Iterator +FixedArray< TValue, VLength > ::End() { return Iterator(m_InternalArray + VLength); @@ -144,9 +144,9 @@ FixedArray< TValueType, VLength > /** * Get a ConstIterator for the end of the FixedArray. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::ConstIterator -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::ConstIterator +FixedArray< TValue, VLength > ::End() const { return ConstIterator(m_InternalArray + VLength); @@ -155,9 +155,9 @@ FixedArray< TValueType, VLength > /** * Get a begin ReverseIterator. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::ReverseIterator -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::ReverseIterator +FixedArray< TValue, VLength > ::rBegin() { return ReverseIterator(m_InternalArray + VLength); @@ -166,9 +166,9 @@ FixedArray< TValueType, VLength > /** * Get a begin ConstReverseIterator. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::ConstReverseIterator -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::ConstReverseIterator +FixedArray< TValue, VLength > ::rBegin() const { return ConstReverseIterator(m_InternalArray + VLength); @@ -177,9 +177,9 @@ FixedArray< TValueType, VLength > /** * Get an end ReverseIterator. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::ReverseIterator -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::ReverseIterator +FixedArray< TValue, VLength > ::rEnd() { return ReverseIterator(m_InternalArray); @@ -188,9 +188,9 @@ FixedArray< TValueType, VLength > /** * Get an end ConstReverseIterator. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::ConstReverseIterator -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::ConstReverseIterator +FixedArray< TValue, VLength > ::rEnd() const { return ConstReverseIterator(m_InternalArray); @@ -199,9 +199,9 @@ FixedArray< TValueType, VLength > /** * Get the size of the FixedArray. */ -template< typename TValueType, unsigned int VLength > -typename FixedArray< TValueType, VLength >::SizeType -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +typename FixedArray< TValue, VLength >::SizeType +FixedArray< TValue, VLength > ::Size() const { return VLength; @@ -210,9 +210,9 @@ FixedArray< TValueType, VLength > /** * Fill all elements of the array with the given value. */ -template< typename TValueType, unsigned int VLength > +template< typename TValue, unsigned int VLength > void -FixedArray< TValueType, VLength > +FixedArray< TValue, VLength > ::Fill(const ValueType & value) { Iterator i = this->Begin(); @@ -226,9 +226,9 @@ FixedArray< TValueType, VLength > /** * Return an FixedArray with all elements assigned to the given value. */ -template< typename TValueType, unsigned int VLength > -FixedArray< TValueType, VLength > -FixedArray< TValueType, VLength > +template< typename TValue, unsigned int VLength > +FixedArray< TValue, VLength > +FixedArray< TValue, VLength > ::Filled(const ValueType & value) { FixedArray< ValueType, VLength > array; @@ -236,8 +236,8 @@ FixedArray< TValueType, VLength > return array; } -template< typename TValueType, unsigned int VLength > -std::ostream & operator<<(std::ostream & os, const FixedArray< TValueType, VLength > & arr) +template< typename TValue, unsigned int VLength > +std::ostream & operator<<(std::ostream & os, const FixedArray< TValue, VLength > & arr) { os << "["; if ( VLength == 1 ) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkFloodFilledFunctionConditionalConstIterator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkFloodFilledFunctionConditionalConstIterator.hxx index c7d79107a77ab0fae4c7dcf6eaf3282efdfa2ac7..3235740794e820638298de0ace6a092bc2a7d441 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkFloodFilledFunctionConditionalConstIterator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkFloodFilledFunctionConditionalConstIterator.hxx @@ -65,6 +65,7 @@ FloodFilledFunctionConditionalConstIterator< TImage, TFunction > // Set up the temporary image this->InitializeIterator(); + } template< typename TImage, typename TFunction > @@ -72,6 +73,9 @@ void FloodFilledFunctionConditionalConstIterator< TImage, TFunction > ::InitializeIterator() { + m_FoundUncheckedNeighbor = false; + m_IsValidIndex = false; + // Get the origin and spacing from the image in simple arrays m_ImageOrigin = this->m_Image->GetOrigin(); m_ImageSpacing = this->m_Image->GetSpacing(); @@ -84,8 +88,7 @@ FloodFilledFunctionConditionalConstIterator< TImage, TFunction > m_TemporaryPointer->SetLargestPossibleRegion(tempRegion); m_TemporaryPointer->SetBufferedRegion(tempRegion); m_TemporaryPointer->SetRequestedRegion(tempRegion); - m_TemporaryPointer->Allocate(); - m_TemporaryPointer->FillBuffer(NumericTraits< typename TTempImage::PixelType >::Zero); + m_TemporaryPointer->Allocate(true); // initialize buffer to zero // Initialize the queue by adding the start index assuming one of // the m_Seeds is "inside" This might not be true, in which diff --git a/Utilities/ITK/Modules/Core/Common/include/itkFloodFilledSpatialFunctionConditionalConstIterator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkFloodFilledSpatialFunctionConditionalConstIterator.hxx index 6476719d13742a72ac82e4587c648bb2fcaa5a04..91c3e7b24e9885dc1ba93a345a3116e4d3085e84 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkFloodFilledSpatialFunctionConditionalConstIterator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkFloodFilledSpatialFunctionConditionalConstIterator.hxx @@ -113,7 +113,7 @@ FloodFilledSpatialFunctionConditionalConstIterator< TImage, TFunction > unsigned int counter; unsigned int counterCopy; unsigned int dim = TImage::ImageDimension; - unsigned int numReps = static_cast< unsigned int >( vcl_pow( + unsigned int numReps = static_cast< unsigned int >( std::pow( static_cast< double >( 2.0 ), static_cast< double >( dim ) ) ); @@ -160,7 +160,7 @@ FloodFilledSpatialFunctionConditionalConstIterator< TImage, TFunction > unsigned int counter; unsigned int counterCopy; unsigned int dim = TImage::ImageDimension; - unsigned int numReps = static_cast< unsigned int >( vcl_pow( + unsigned int numReps = static_cast< unsigned int >( std::pow( static_cast< double >( 2.0 ), static_cast< double >( dim ) ) ); IndexType tempIndex; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkFrustumSpatialFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkFrustumSpatialFunction.hxx index f2552f5281a7bb7d94d0b6f3bd7ca1178866faa4..2f0eba556f3eb9c38fb063bf40b2b4a79079db37 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkFrustumSpatialFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkFrustumSpatialFunction.hxx @@ -77,22 +77,22 @@ FrustumSpatialFunction< VImageDimension, TInput > const double dy = relativePosition[1]; const double dz = relativePosition[2]; - const double distanceXZ = vcl_sqrt(dx * dx + dz * dz); + const double distanceXZ = std::sqrt(dx * dx + dz * dz); - const double deg2rad = vcl_atan(1.0f) / 45.0; + const double deg2rad = std::atan(1.0f) / 45.0; // Check planes along Y - const double angleY = vcl_atan2(dy, distanceXZ); - if ( vcl_fabs(angleY) > m_ApertureAngleY * deg2rad ) + const double angleY = std::atan2(dy, distanceXZ); + if ( std::fabs(angleY) > m_ApertureAngleY * deg2rad ) { return 0; } // Check planes along X - const double angleX = vcl_atan2(dx, dz); + const double angleX = std::atan2(dx, dz); - if ( vcl_cos(angleX + ( 180.0 + m_AngleZ ) * deg2rad) < - vcl_cos(deg2rad * m_ApertureAngleX) ) + if ( std::cos(angleX + ( 180.0 + m_AngleZ ) * deg2rad) < + std::cos(deg2rad * m_ApertureAngleX) ) { return 0; } @@ -105,22 +105,22 @@ FrustumSpatialFunction< VImageDimension, TInput > const double dy = relativePosition[1]; const double dz = relativePosition[2]; - const double distanceYZ = vcl_sqrt(dy * dy + dz * dz); + const double distanceYZ = std::sqrt(dy * dy + dz * dz); - const double deg2rad = vcl_atan(1.0f) / 45.0; + const double deg2rad = std::atan(1.0f) / 45.0; // Check planes along X - const double angleX = vcl_atan2(dx, distanceYZ); - if ( vcl_fabs(angleX) > m_ApertureAngleX * deg2rad ) + const double angleX = std::atan2(dx, distanceYZ); + if ( std::fabs(angleX) > m_ApertureAngleX * deg2rad ) { return 0; } // Check planes along Y - const double angleY = vcl_atan2(dy, dz); + const double angleY = std::atan2(dy, dz); - if ( vcl_cos(angleY + ( 180.0 + m_AngleZ ) * deg2rad) < - vcl_cos(deg2rad * m_ApertureAngleY) ) + if ( std::cos(angleY + ( 180.0 + m_AngleZ ) * deg2rad) < + std::cos(deg2rad * m_ApertureAngleY) ) { return 0; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.hxx index 4965d08e4badc0ecad5a162068df12719bb8b65c..70d2e8118e968274f8c1cde42db8708d7eb03594 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.hxx @@ -59,7 +59,7 @@ GaussianDerivativeSpatialFunction< TOutput, VImageDimension, TInput > prefixDenom *= m_Sigma[i]; } - prefixDenom *= 2 * vcl_pow(2 * vnl_math::pi, VImageDimension / 2.0); + prefixDenom *= 2 * std::pow(2 * vnl_math::pi, VImageDimension / 2.0); } else { @@ -75,7 +75,7 @@ GaussianDerivativeSpatialFunction< TOutput, VImageDimension, TInput > / ( 2 * m_Sigma[m_Direction] * m_Sigma[m_Direction] ); } - double value = -2 * ( position[m_Direction] - m_Mean[m_Direction] ) * m_Scale * ( 1 / prefixDenom ) * vcl_exp( + double value = -2 * ( position[m_Direction] - m_Mean[m_Direction] ) * m_Scale * ( 1 / prefixDenom ) * std::exp( -1 * suffixExp); return (TOutput)value; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkGaussianKernelFunction.h b/Utilities/ITK/Modules/Core/Common/include/itkGaussianKernelFunction.h index cb1728fd38ba58f52cf10670a2a4c8047fe04411..a53fcd60d9ac2a40710c30734bf71c97da0d2264 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkGaussianKernelFunction.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkGaussianKernelFunction.h @@ -55,10 +55,10 @@ public: /** Evaluate the function. */ inline TRealValueType Evaluate(const TRealValueType & u) const - { return ( vcl_exp( static_cast< TRealValueType >(-0.5) * vnl_math_sqr(u) ) * m_Factor ); } + { return ( std::exp( static_cast< TRealValueType >(-0.5) * vnl_math_sqr(u) ) * m_Factor ); } protected: - GaussianKernelFunction(): m_Factor( NumericTraits< TRealValueType >::One / vcl_sqrt(static_cast< TRealValueType >(2.0 * vnl_math::pi )) ) {}; + GaussianKernelFunction(): m_Factor( NumericTraits< TRealValueType >::One / std::sqrt(static_cast< TRealValueType >(2.0 * vnl_math::pi )) ) {}; virtual ~GaussianKernelFunction() {}; void PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkGaussianOperator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkGaussianOperator.hxx index f5a61cbbd340aee3c410497b0335e5eb7e0b284d..0339bc7657a3a45b2fed97c2cc1cb0b44c69be11 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkGaussianOperator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkGaussianOperator.hxx @@ -35,7 +35,7 @@ GaussianOperator< TPixel, VDimension, TAllocator > typename CoefficientVector::iterator it; - const double et = vcl_exp(-m_Variance); + const double et = std::exp(-m_Variance); const double cap = 1.0 - m_MaximumError; // Create the kernel coefficients as a std::vector @@ -84,7 +84,7 @@ double GaussianOperator< TPixel, VDimension, TAllocator > ::ModifiedBesselI0(double y) { - const double d = vcl_fabs(y); + const double d = std::fabs(y); double accumulator; if ( d < 3.75 ) @@ -98,7 +98,7 @@ GaussianOperator< TPixel, VDimension, TAllocator > else { const double m = 3.75 / d; - accumulator = ( vcl_exp(d) / vcl_sqrt(d) ) * ( 0.39894228 + m * ( 0.1328592e-1 + accumulator = ( std::exp(d) / std::sqrt(d) ) * ( 0.39894228 + m * ( 0.1328592e-1 + m * ( 0.225319e-2 + m * ( -0.157565e-2 + m * ( 0.916281e-2 @@ -123,7 +123,7 @@ double GaussianOperator< TPixel, VDimension, TAllocator > ::ModifiedBesselI1(double y) { - const double d = vcl_fabs(y); + const double d = std::fabs(y); double accumulator; if ( d < 3.75 ) @@ -143,7 +143,7 @@ GaussianOperator< TPixel, VDimension, TAllocator > accumulator = 0.39894228 + m * ( -0.3988024e-1 + m * ( -0.362018e-2 + m * ( 0.163801e-2 + m * ( -0.1031555e-1 + m * accumulator ) ) ) ); - accumulator *= ( vcl_exp(d) / vcl_sqrt(d) ); + accumulator *= ( std::exp(d) / std::sqrt(d) ); } if ( y < 0.0 ) @@ -179,16 +179,16 @@ GaussianOperator< TPixel, VDimension, TAllocator > } else { - toy = 2.0 / vcl_fabs(y); + toy = 2.0 / std::fabs(y); qip = accumulator = 0.0; qi = 1.0; - for ( j = 2 * ( n + (int)vcl_sqrt(ACCURACY * n) ); j > 0; j-- ) + for ( j = 2 * ( n + (int)std::sqrt(ACCURACY * n) ); j > 0; j-- ) { qim = qip + j * toy * qi; qip = qi; qi = qim; - if ( vcl_fabs(qi) > 1.0e10 ) + if ( std::fabs(qi) > 1.0e10 ) { accumulator *= 1.0e-10; qi *= 1.0e-10; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkGaussianSpatialFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkGaussianSpatialFunction.hxx index 4f8e90343cd8ac0f05175b3dac7e1e5b7abdd074..2abd853258cf80043e9875d69be5bddc19c48b5d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkGaussianSpatialFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkGaussianSpatialFunction.hxx @@ -54,7 +54,7 @@ GaussianSpatialFunction< TOutput, VImageDimension, TInput > if ( m_Normalized ) { - const double squareRootOfTwoPi = vcl_sqrt(2.0 * vnl_math::pi); + const double squareRootOfTwoPi = std::sqrt(2.0 * vnl_math::pi); for ( unsigned int i = 0; i < VImageDimension; i++ ) { @@ -70,7 +70,7 @@ GaussianSpatialFunction< TOutput, VImageDimension, TInput > / ( 2 * m_Sigma[i] * m_Sigma[i] ); } - double value = m_Scale * ( 1 / prefixDenom ) * vcl_exp(-1 * suffixExp); + double value = m_Scale * ( 1 / prefixDenom ) * std::exp(-1 * suffixExp); return (TOutput)value; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkHexahedronCell.hxx b/Utilities/ITK/Modules/Core/Common/include/itkHexahedronCell.hxx index a0c162c2b7d3aec51442e00f8647428956eb8323..910db0f23e30eb051a668e4ae2b336b0bbe7b12f 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkHexahedronCell.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkHexahedronCell.hxx @@ -397,7 +397,7 @@ HexahedronCell< TCellInterface > d = vnl_determinant(mat); //d=vtkMath::Determinant3x3(rcol,scol,tcol); - if ( vcl_abs(d) < 1.e-20 ) + if ( std::abs(d) < 1.e-20 ) { return false; } @@ -438,17 +438,17 @@ HexahedronCell< TCellInterface > } // check for convergence - if ( ( ( vcl_abs(pcoords[0] - params[0]) ) < ITK_HEX_CONVERGED ) - && ( ( vcl_abs(pcoords[1] - params[1]) ) < ITK_HEX_CONVERGED ) - && ( ( vcl_abs(pcoords[2] - params[2]) ) < ITK_HEX_CONVERGED ) ) + if ( ( ( std::abs(pcoords[0] - params[0]) ) < ITK_HEX_CONVERGED ) + && ( ( std::abs(pcoords[1] - params[1]) ) < ITK_HEX_CONVERGED ) + && ( ( std::abs(pcoords[2] - params[2]) ) < ITK_HEX_CONVERGED ) ) { converged = 1; } // Test for bad divergence (S.Hirschberg 11.12.2001) - else if ( ( vcl_abs(pcoords[0]) > ITK_DIVERGED ) - || ( vcl_abs(pcoords[1]) > ITK_DIVERGED ) - || ( vcl_abs(pcoords[2]) > ITK_DIVERGED ) ) + else if ( ( std::abs(pcoords[0]) > ITK_DIVERGED ) + || ( std::abs(pcoords[1]) > ITK_DIVERGED ) + || ( std::abs(pcoords[2]) > ITK_DIVERGED ) ) { return -1; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImage.h b/Utilities/ITK/Modules/Core/Common/include/itkImage.h index 071c29ccfef9fea6b8a2573099f1bc657a62a4ff..ead13809db20bb46fee7f4cc389cf92853d2b1c1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImage.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImage.h @@ -169,7 +169,7 @@ public: /** Allocate the image memory. The size of the image must * already be set, e.g. by calling SetRegions(). */ - void Allocate(); + virtual void Allocate(bool initializePixels = false) ITK_OVERRIDE; /** Restore the data object to its initial state. This means releasing * memory. */ @@ -227,9 +227,9 @@ public: /** Return a pointer to the beginning of the buffer. This is used by * the image iterator class. */ virtual TPixel * GetBufferPointer() - { return m_Buffer ? m_Buffer->GetBufferPointer() : 0; } + { return m_Buffer ? m_Buffer->GetBufferPointer() : ITK_NULLPTR; } virtual const TPixel * GetBufferPointer() const - { return m_Buffer ? m_Buffer->GetBufferPointer() : 0; } + { return m_Buffer ? m_Buffer->GetBufferPointer() : ITK_NULLPTR; } /** Return a pointer to the container. */ PixelContainer * GetPixelContainer() diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImage.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImage.hxx index e763c185ee8d4b33aab89cfd3bf1e9316a586d90..b8104444d66e46ca0f5d63f3f53422664a17aee7 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImage.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImage.hxx @@ -44,18 +44,17 @@ Image< TPixel, VImageDimension > m_Buffer = PixelContainer::New(); } -//---------------------------------------------------------------------------- template< typename TPixel, unsigned int VImageDimension > void Image< TPixel, VImageDimension > -::Allocate() +::Allocate(bool initializePixels) { SizeValueType num; this->ComputeOffsetTable(); num = static_cast<SizeValueType>(this->GetOffsetTable()[VImageDimension]); - m_Buffer->Reserve(num); + m_Buffer->Reserve(num, initializePixels); } template< typename TPixel, unsigned int VImageDimension > @@ -113,16 +112,7 @@ Image< TPixel, VImageDimension > if ( data ) { // Attempt to cast data to an Image - const Self *imgData; - - try - { - imgData = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - return; - } + const Self * const imgData = dynamic_cast< const Self * >( data ); if ( imgData ) { diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageAlgorithm.h b/Utilities/ITK/Modules/Core/Common/include/itkImageAlgorithm.h index ab2929ae060ecd87ae01372b5007f76eb7abde3f..434ba2b33dfab5158a5d247db610e8253c707a26 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageAlgorithm.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageAlgorithm.h @@ -175,6 +175,34 @@ private: }; /** \endcond */ + /** Unary functor just for static_cast operator */ + template<typename TInputType, typename TOutputType> + struct StaticCast + : public std::unary_function<TInputType,TOutputType> + { + TOutputType operator() (const TInputType i) { return static_cast<TOutputType>(i); } + }; + + + /** Function to dispatch to std::copy or std::transform. */ + template<typename TType> + static TType* CopyHelper(const TType *first, const TType *last, TType *result) + { + // Note: On some MS compilers the following may generate a + // warning. Please include itkMacro.h before <algorithm> or + // another stl header to avoid. + return std::copy(first, last, result); + } + +/** \cond HIDE_SPECIALIZATION_DOCUMENTATION */ + template<typename TInputType, typename TOutputType> + static TOutputType* CopyHelper(const TInputType *first, const TInputType *last, TOutputType *result) + { + return std::transform(first, last, result, StaticCast<TInputType,TOutputType>()); + } +/** \endcond */ + + }; } // end namespace itk diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageAlgorithm.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageAlgorithm.hxx index 3ad765cd572e5497bd037f98e8a566a9374601f2..0bb860613ec4f1430aca3188c64e7487193066e4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageAlgorithm.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageAlgorithm.hxx @@ -131,10 +131,7 @@ void ImageAlgorithm::DispatchedCopy( const InputImageType *inImage, const typename InputImageType::InternalPixelType* inBuffer = in + inOffset*NumberOfInternalComponents; typename OutputImageType::InternalPixelType* outBuffer = out + outOffset*NumberOfInternalComponents; - // Note: On some MS compilers the following may generate a - // warning. Please include itkMacro.h before <algorithm> or - // another stl header to avoid. - std::copy(inBuffer, + CopyHelper(inBuffer, inBuffer+sizeOfChunkInInternalComponents , outBuffer); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageBase.h b/Utilities/ITK/Modules/Core/Common/include/itkImageBase.h index 37a878272536b2415217367bb1637d6b64663a2f..8c3e1d4c84c81b4c144b1017581ca32ed62666b0 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageBase.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageBase.h @@ -164,7 +164,7 @@ public: typedef Matrix< SpacePrecisionType, VImageDimension, VImageDimension > DirectionType; /** Restore object to initialized state. */ - void Initialize(); + virtual void Initialize() ITK_OVERRIDE; /** Image dimension. The dimension of an image is fixed at construction. */ static unsigned int GetImageDimension() @@ -232,8 +232,9 @@ public: * * This method should be pure virtual, if backwards compatibility * was not required. + * */ - virtual void Allocate() {} + virtual void Allocate(bool initialize=false); /** Set the region object that defines the size and starting index * for the largest possible region this image could represent. This @@ -279,7 +280,7 @@ public: * the object to be modified. This method is called internally by * the pipeline and therefore bypasses the modified time * calculation. */ - virtual void SetRequestedRegion( const DataObject *data ); + virtual void SetRequestedRegion( const DataObject *data ) ITK_OVERRIDE; /** Get the region object that defines the size and starting index * for the region of the image requested (i.e., the region of the @@ -589,7 +590,7 @@ public: * ImageBase has more meta-data than its DataObject. Thus, it must * provide its own version of CopyInformation() in order to copy the * LargestPossibleRegion from the input parameter. */ - virtual void CopyInformation(const DataObject *data); + virtual void CopyInformation(const DataObject *data) ITK_OVERRIDE; /** Graft the data and information from one image to another. This * is a convenience method to setup a second image with all the meta @@ -601,7 +602,7 @@ public: * simply calls CopyInformation() and copies the region ivars. * Subclasses of ImageBase are responsible for copying the pixel * container. */ - virtual void Graft(const DataObject *data); + virtual void Graft(const DataObject *data) ITK_OVERRIDE; /** Update the information for this DataObject so that it can be used * as an output of a ProcessObject. This method is used the pipeline @@ -610,7 +611,7 @@ public: * ProcessObject::UpdateOutputInformation() which determines modified * times, LargestPossibleRegions, and any extra meta data like spacing, * origin, etc. */ - virtual void UpdateOutputInformation(); + virtual void UpdateOutputInformation() ITK_OVERRIDE; /** UpdateOutputData() is part of the pipeline infrastructure to * communicate between ProcessObjects and DataObjects. The method of @@ -619,12 +620,12 @@ public: * input's requested region to zero, to indicate that it does not * need to be updated or executed. */ - virtual void UpdateOutputData(); + virtual void UpdateOutputData() ITK_OVERRIDE; /** Set the RequestedRegion to the LargestPossibleRegion. This * forces a filter to produce all of the output in one execution * (i.e. not streaming) on the next call to Update(). */ - virtual void SetRequestedRegionToLargestPossibleRegion(); + virtual void SetRequestedRegionToLargestPossibleRegion() ITK_OVERRIDE; /** Determine whether the RequestedRegion is outside of the * BufferedRegion. This method returns true if the RequestedRegion @@ -635,7 +636,7 @@ public: * inside the BufferedRegion from the previous execution (and the * current filter is up to date), then a given filter does not need * to re-execute */ - virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); + virtual bool RequestedRegionIsOutsideOfTheBufferedRegion() ITK_OVERRIDE; /** Verify that the RequestedRegion is within the * LargestPossibleRegion. If the RequestedRegion is not within the @@ -645,7 +646,7 @@ public: * used by PropagateRequestedRegion(). PropagateRequestedRegion() * throws a InvalidRequestedRegionError exception is the requested * region is not within the LargestPossibleRegion. */ - virtual bool VerifyRequestedRegion(); + virtual bool VerifyRequestedRegion() ITK_OVERRIDE; /** INTERNAL This method is used internally by filters to copy meta-data from * the output to the input. Users should not have a need to use this method. @@ -671,7 +672,7 @@ public: protected: ImageBase(); ~ImageBase(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Calculate the offsets needed to move from one pixel to the next * along a row, column, slice, volume, etc. These offsets are based diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageBase.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageBase.hxx index ed5d9e0a88c83709b82c59dd88938e15153c4637..5a58598bfe195dba1bacd731ccc168fa8d85461d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageBase.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageBase.hxx @@ -53,6 +53,13 @@ ImageBase< VImageDimension > m_PhysicalPointToIndex.SetIdentity(); } +template< unsigned int VImageDimension > +void +ImageBase< VImageDimension > +::Allocate(bool) +{ +} + /** * */ @@ -302,16 +309,7 @@ ImageBase< VImageDimension > if ( data ) { // Attempt to cast data to an ImageBase - const ImageBase< VImageDimension > *imgData; - - try - { - imgData = dynamic_cast< const ImageBase< VImageDimension > * >( data ); - } - catch ( ... ) - { - return; - } + const ImageBase< VImageDimension > * const imgData = dynamic_cast< const ImageBase< VImageDimension > * >( data ); if ( imgData ) { @@ -341,16 +339,7 @@ ImageBase< VImageDimension > { typedef ImageBase< VImageDimension > ImageBaseType; - const ImageBaseType *image; - - try - { - image = dynamic_cast< const ImageBaseType * >( data ); - } - catch ( ... ) - { - return; - } + const ImageBaseType *image = dynamic_cast< const ImageBaseType * >( data ); if ( !image ) { diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageConstIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkImageConstIterator.h index 45cc30cc715b8fc5d71adec483ad1f6e62f80ebe..2d064a604eab59f40769fcba994c944e335d375b 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageConstIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageConstIterator.h @@ -133,8 +133,8 @@ public: m_PixelAccessor(), m_PixelAccessorFunctor() { - m_Image = 0; - m_Buffer = 0; + m_Image = ITK_NULLPTR; + m_Buffer = ITK_NULLPTR; m_Offset = 0; m_BeginOffset = 0; m_EndOffset = 0; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageConstIteratorWithIndex.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageConstIteratorWithIndex.hxx index 3007e3f0df0172fc711850cc145822a582be4c11..3b3160a85b0185fe643fabe0af02883adbcdcf66 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageConstIteratorWithIndex.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageConstIteratorWithIndex.hxx @@ -29,9 +29,9 @@ template< typename TImage > ImageConstIteratorWithIndex< TImage > ::ImageConstIteratorWithIndex() { - m_Position = 0; - m_Begin = 0; - m_End = 0; + m_Position = ITK_NULLPTR; + m_Begin = ITK_NULLPTR; + m_End = ITK_NULLPTR; m_Remaining = false; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageDuplicator.h b/Utilities/ITK/Modules/Core/Common/include/itkImageDuplicator.h index 0a7af144f1a1e914a6552980af7e056266e84363..04e5272aa9e404e0b10386d2d998d2efac2102f8 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageDuplicator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageDuplicator.h @@ -86,7 +86,7 @@ public: protected: ImageDuplicator(); virtual ~ImageDuplicator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: ImageDuplicator(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageDuplicator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageDuplicator.hxx index 0e4fb7528a86a186a1835ae9828ee1f85dd377f2..25f5021680656791af8cabe482ffe876b14519f7 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageDuplicator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageDuplicator.hxx @@ -28,8 +28,8 @@ template< typename TInputImage > ImageDuplicator< TInputImage > ::ImageDuplicator() { - m_InputImage = NULL; - m_Output = NULL; + m_InputImage = ITK_NULLPTR; + m_Output = ITK_NULLPTR; m_InternalImageTime = 0; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageIORegion.h b/Utilities/ITK/Modules/Core/Common/include/itkImageIORegion.h index 0c3e3599da1ad940f839c3433601673d1b4abddd..fba7c86cdd0d24ccdece7e7774ee301748efcf0d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageIORegion.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageIORegion.h @@ -83,7 +83,7 @@ public: unsigned int GetRegionDimension() const; /** Return the region type. Images are described with structured regions. */ - virtual RegionType GetRegionType() const; + virtual RegionType GetRegionType() const ITK_OVERRIDE; /** Constructor. ImageIORegion is a lightweight object that is not reference * counted, so the constructor is public. */ @@ -152,7 +152,7 @@ protected: * including superclasses. Typically not called by the user (use Print() * instead) but used in the hierarchical print process to combine the * output of several classes. */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: unsigned int m_ImageDimension; @@ -160,13 +160,14 @@ private: SizeType m_Size; }; + // Declare operator<< extern ITKCommon_EXPORT std::ostream & operator<<(std::ostream & os, const ImageIORegion & region); + /** \class ImageIORegionAdaptor * \brief Helper class for converting ImageRegions into ImageIORegions and back. * - * * \ingroup ITKCommon */ template< unsigned int VDimension > @@ -197,12 +198,12 @@ public: const unsigned int ioDimension = outIORegion.GetImageDimension(); const unsigned int imageDimension = VDimension; - unsigned int minDimension = ( ioDimension > imageDimension ) ? imageDimension : ioDimension; + const unsigned int minDimension = std::min( ioDimension, imageDimension ); - ImageSizeType size = inImageRegion.GetSize(); - ImageIndexType index = inImageRegion.GetIndex(); + const ImageSizeType & size = inImageRegion.GetSize(); + const ImageIndexType & index = inImageRegion.GetIndex(); - for ( unsigned int i = 0; i < minDimension; i++ ) + for( unsigned int i = 0; i < minDimension; ++i ) { outIORegion.SetSize(i, size[i]); outIORegion.SetIndex(i, index[i] - largestRegionIndex[i]); @@ -211,7 +212,7 @@ public: // // Fill in the remaining codimension (if any) with default values // - for ( unsigned int k = minDimension; k < ioDimension; k++ ) + for( unsigned int k = minDimension; k < ioDimension; ++k ) { outIORegion.SetSize(k, 1); // Note that default size in IO is 1 not 0 outIORegion.SetIndex(k, 0); @@ -242,9 +243,9 @@ public: const unsigned int ioDimension = inIORegion.GetImageDimension(); const unsigned int imageDimension = VDimension; - unsigned int minDimension = ( ioDimension > imageDimension ) ? imageDimension : ioDimension; + const unsigned int minDimension = std::min( ioDimension, imageDimension ); - for ( unsigned int i = 0; i < minDimension; i++ ) + for( unsigned int i = 0; i < minDimension; ++i ) { size[i] = inIORegion.GetSize(i); index[i] = inIORegion.GetIndex(i) + largestRegionIndex[i]; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.h b/Utilities/ITK/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.h index 1d5f9877cb94c3b07f37444fab787978b32a12ab..8a22f45088d9026cac60c5a88ba5a55e65cb9fc5 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.h @@ -130,7 +130,11 @@ public: typedef typename PixelContainer::Pointer PixelContainerPointer; /** Default constructor. Needed since we provide a cast constructor. */ - ImageLinearConstIteratorWithIndex():ImageConstIteratorWithIndex< TImage >(), m_Direction(0) {} + ImageLinearConstIteratorWithIndex() : + ImageConstIteratorWithIndex< TImage >(), + m_Jump(0), + m_Direction(0) + {} /** Constructor establishes an iterator to walk a particular image and a * particular region of that image. */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageRandomNonRepeatingConstIteratorWithIndex.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageRandomNonRepeatingConstIteratorWithIndex.hxx index 7d788f1c74ced78636177260fb825021314d16ac..c7f7373a36259303811d8fadf9ee287bb4416fac 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageRandomNonRepeatingConstIteratorWithIndex.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageRandomNonRepeatingConstIteratorWithIndex.hxx @@ -30,7 +30,7 @@ ImageRandomNonRepeatingConstIteratorWithIndex< TImage > m_NumberOfPixelsInRegion = 0L; m_NumberOfSamplesRequested = 0L; m_NumberOfSamplesDone = 0L; - m_Permutation = NULL; + m_Permutation = ITK_NULLPTR; } /** Constructor establishes an iterator to walk a particular image and a diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageRegion.h b/Utilities/ITK/Modules/Core/Common/include/itkImageRegion.h index 4b0d200acc004729ae86632f68d6fee624580ad9..5fb26120e782eb3368001f150670b00eba7bc94d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageRegion.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageRegion.h @@ -104,7 +104,7 @@ public: typedef ImageRegion< itkGetStaticConstMacro(SliceDimension) > SliceRegion; /** Return the region type. Images are described with structured regions. */ - virtual typename Superclass::RegionType GetRegionType() const + virtual typename Superclass::RegionType GetRegionType() const ITK_OVERRIDE { return Superclass::ITK_STRUCTURED_REGION; } /** Constructor. ImageRegion is a lightweight object that is not reference @@ -308,7 +308,7 @@ protected: * including superclasses. Typically not called by the user (use Print() * instead) but used in the hierarchical print process to combine the * output of several classes. */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: IndexType m_Index; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterBase.h b/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterBase.h index 097030f113ebb0d463e2f63cdff26be545ae905c..663b6054da9a1ccf318cf24ea61c18006126e83a 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterBase.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterBase.h @@ -143,7 +143,7 @@ protected: IndexValueType regionIndex[], SizeValueType regionSize[] ) const = 0; - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: ImageRegionSplitterBase(const ImageRegionSplitterBase &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterDirection.h b/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterDirection.h index 012260580f3198de647890be79421da4d039e84e..9ffba72fca6ba9ed0b5b61d0deee75949237f5eb 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterDirection.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterDirection.h @@ -63,15 +63,15 @@ protected: virtual unsigned int GetNumberOfSplitsInternal(unsigned int dim, const IndexValueType regionIndex[], const SizeValueType regionSize[], - unsigned int requestedNumber) const; + unsigned int requestedNumber) const ITK_OVERRIDE; virtual unsigned int GetSplitInternal(unsigned int dim, unsigned int i, unsigned int numberOfPieces, IndexValueType regionIndex[], - SizeValueType regionSize[]) const; + SizeValueType regionSize[]) const ITK_OVERRIDE; - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: ImageRegionSplitterDirection(const ImageRegionSplitterDirection &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterMultidimensional.h b/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterMultidimensional.h index 1e3a41c53ec0b7340f23dc6667a380408ea9599e..86c168afb36ad7efa88fe5916db53a66ed24fb4f 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterMultidimensional.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterMultidimensional.h @@ -78,15 +78,15 @@ protected: virtual unsigned int GetNumberOfSplitsInternal(unsigned int dim, const IndexValueType regionIndex[], const SizeValueType regionSize[], - unsigned int requestedNumber) const; + unsigned int requestedNumber) const ITK_OVERRIDE; virtual unsigned int GetSplitInternal(unsigned int dim, unsigned int i, unsigned int numberOfPieces, IndexValueType regionIndex[], - SizeValueType regionSize[]) const; + SizeValueType regionSize[]) const ITK_OVERRIDE; - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: ImageRegionSplitterMultidimensional(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterSlowDimension.h b/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterSlowDimension.h index 4d8ec86729143373390507e56e57777723255bab..a4327f33d4c7a4f6818a9a95d272380b7585f781 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterSlowDimension.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageRegionSplitterSlowDimension.h @@ -66,13 +66,13 @@ protected: virtual unsigned int GetNumberOfSplitsInternal( unsigned int dim, const IndexValueType regionIndex[], const SizeValueType regionSize[], - unsigned int requestedNumber ) const; + unsigned int requestedNumber ) const ITK_OVERRIDE; virtual unsigned int GetSplitInternal( unsigned int dim, unsigned int i, unsigned int numberOfPieces, IndexValueType regionIndex[], - SizeValueType regionSize[] ) const; + SizeValueType regionSize[] ) const ITK_OVERRIDE; private: ImageRegionSplitterSlowDimension(const ImageRegionSplitterSlowDimension &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageScanlineConstIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkImageScanlineConstIterator.h index 18e7a3a8cbb28683e34a486a4ff04a32ae01816e..e6922a604b17728680496984f3ed70f0c99cf52a 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageScanlineConstIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageScanlineConstIterator.h @@ -174,7 +174,7 @@ public: */ void GoToBeginOfLine(void) { - this->Offset = m_SpanBeginOffset; + this->m_Offset = m_SpanBeginOffset; } /** Go to the past end pixel of the current line. @@ -187,7 +187,7 @@ public: */ void GoToEndOfLine(void) { - this->Offset = m_SpanEndOffset; + this->m_Offset = m_SpanEndOffset; } /** Test if the index is at the end of line diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.h b/Utilities/ITK/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.h index bdfc8014f6d307623b65555a33ee474b22a1b5d2..bbd6105df3286896ed3641c1cc6b2e3b8464e682 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.h @@ -136,10 +136,12 @@ public: * particular region of that image. */ ImageSliceConstIteratorWithIndex(const ImageType *ptr, const RegionType & region): - ImageConstIteratorWithIndex< TImage >(ptr, region) + ImageConstIteratorWithIndex< TImage >(ptr, region), + m_PixelJump(0), + m_LineJump(0), + m_Direction_A(0), + m_Direction_B(1) { - m_Direction_A = 0; - m_Direction_B = 1; } /** Constructor that can be used to cast from an ImageIterator to an diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageSource.h b/Utilities/ITK/Modules/Core/Common/include/itkImageSource.h index 848c5d667252f9ee0a02c2ae0cba5793248b69e1..a695f278ff61885d422448a62f9d2d65593d3b52 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageSource.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageSource.h @@ -230,7 +230,7 @@ public: * multiple outputs of different types, then that class must provide * an implementation of MakeOutput(). */ using Superclass::MakeOutput; - virtual ProcessObject::DataObjectPointer MakeOutput(ProcessObject::DataObjectPointerArraySizeType idx); + virtual ProcessObject::DataObjectPointer MakeOutput(ProcessObject::DataObjectPointerArraySizeType idx) ITK_OVERRIDE; protected: ImageSource(); @@ -251,7 +251,7 @@ protected: * instead. * * \sa ThreadedGenerateData() */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** If an imaging filter can be implemented as a multithreaded * algorithm, the filter will provide an implementation of @@ -332,22 +332,22 @@ protected: */ virtual const ImageRegionSplitterBase* GetImageRegionSplitter(void) const; - /** Split the output's RequestedRegion into "num" pieces, returning + /** Split the output's RequestedRegion into "pieces" pieces, returning * region "i" as "splitRegion". This method is called concurrently - * "num" times. The regions must not overlap. The method returns the number of pieces that - * the routine is capable of splitting the output RequestedRegion, - * i.e. return value is less than or equal to "num". + * "pieces" times. The regions must not overlap. The method returns the number + * of pieces that the routine is capable of splitting the output RequestedRegion, + * i.e. return value is less than or equal to "pieces". * * To override the algorithm used split the image this method should - * no longer be overridden. It stead the algorithm should be - * implemented in a ImageRegionSplitter class, and the + * no longer be overridden. Instead, the algorithm should be + * implemented in a ImageRegionSplitterBase class, and the * GetImageRegionSplitter should overridden to return the splitter * object with the desired algorithm. * * \sa GetImageRegionSplitter **/ virtual - unsigned int SplitRequestedRegion(unsigned int i, unsigned int num, OutputImageRegionType & splitRegion); + unsigned int SplitRequestedRegion(unsigned int i, unsigned int pieces, OutputImageRegionType & splitRegion); /** Static function used as a "callback" by the MultiThreader. The threading * library will call this routine for each thread, which will delegate the diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageSource.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageSource.hxx index 74f5cba0339e94ed38a30bf8b84d5bd3c330a073..595bbea0a63c8ba811723562d401245a432c355a 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageSource.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageSource.hxx @@ -103,7 +103,7 @@ ImageSource< TOutputImage > TOutputImage *out = dynamic_cast< TOutputImage * > ( this->ProcessObject::GetOutput(idx) ); - if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL ) + if ( out == ITK_NULLPTR && this->ProcessObject::GetOutput(idx) != ITK_NULLPTR ) { itkWarningMacro (<< "Unable to convert output number " << idx << " to type " << typeid( OutputImageType ).name () ); } @@ -172,7 +172,7 @@ ImageSource< TOutputImage > template< typename TOutputImage > unsigned int ImageSource< TOutputImage > -::SplitRequestedRegion(unsigned int i, unsigned int num, OutputImageRegionType & splitRegion) +::SplitRequestedRegion(unsigned int i, unsigned int pieces, OutputImageRegionType & splitRegion) { const ImageRegionSplitterBase * splitter = this->GetImageRegionSplitter(); @@ -180,7 +180,7 @@ ImageSource< TOutputImage > OutputImageType *outputPtr = this->GetOutput(); splitRegion = outputPtr->GetRequestedRegion(); - return splitter->GetSplit( i, num, splitRegion ); + return splitter->GetSplit( i, pieces, splitRegion ); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageToImageFilter.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageToImageFilter.hxx index 59f44fac45bd22be1a362584466ae593be1e602b..76492bb4cb5ed3cfee0638f210deda2073fe5472 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageToImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageToImageFilter.hxx @@ -100,7 +100,7 @@ ImageToImageFilter< TInputImage, TOutputImage > const TInputImage *in = dynamic_cast< const TInputImage * > ( this->ProcessObject::GetInput(idx) ); - if ( in == NULL && this->ProcessObject::GetInput(idx) != NULL ) + if ( in == ITK_NULLPTR && this->ProcessObject::GetInput(idx) != ITK_NULLPTR ) { itkWarningMacro (<< "Unable to convert input number " << idx << " to type " << typeid( InputImageType ).name () ); } @@ -177,7 +177,7 @@ ImageToImageFilter< TInputImage, TOutputImage > typedef ImageBase< InputImageDimension > ImageBaseType; - ImageBaseType *inputPtr1 = 0; + ImageBaseType *inputPtr1 = ITK_NULLPTR; InputDataObjectIterator it(this); for(; !it.IsAtEnd(); ++it ) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageTransformer.h b/Utilities/ITK/Modules/Core/Common/include/itkImageTransformer.h index 168b43aa47c6e79653a15919b48598a082110eab..6a7b48b1bb6935c293f48a52b4fa15770fe627f4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageTransformer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageTransformer.h @@ -109,9 +109,9 @@ public: * an input to a filter. */ virtual void PushBackInput(const InputImageType *image); - virtual void PopBackInput(); + virtual void PopBackInput() ITK_OVERRIDE; virtual void PushFrontInput(const InputImageType *image); - virtual void PopFrontInput(); + virtual void PopFrontInput() ITK_OVERRIDE; protected: ImageTransformer(); @@ -130,7 +130,7 @@ protected: * * \sa ProcessObject::GenerateInputRequestedRegion(), * ImageSource::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion(); + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; /** A version of GenerateData() specific for image processing * filters. This implementation will split the processing across @@ -147,7 +147,7 @@ protected: * instead. * * \sa ThreadedGenerateData() */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** If an imaging filter can be implemented as a multithreaded * algorithm, the filter will provide an implementation of @@ -228,9 +228,9 @@ protected: * methods from the superclass. * NOTE: The same code resides in ImageToImageFilter */ - void PushBackInput(const DataObject *input) + virtual void PushBackInput(const DataObject *input) ITK_OVERRIDE { Superclass::PushBackInput(input); } - void PushFrontInput(const DataObject *input) + virtual void PushFrontInput(const DataObject *input) ITK_OVERRIDE { Superclass::PushFrontInput(input); } /** Internal structure used for passing image data into the threading library diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageTransformer.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageTransformer.hxx index d4ab10c351d4aea8ca257d4d096087373a08183a..d6174f16a67b04813be76734c5d4c9143660ef84 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageTransformer.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageTransformer.hxx @@ -99,7 +99,7 @@ ImageTransformer< TInputImage > { if ( this->GetNumberOfInputs() < 1 ) { - return 0; + return ITK_NULLPTR; } return itkDynamicCastInDebugMode< TInputImage * > diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.h b/Utilities/ITK/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.h index 5fd867b9a7ef0d06c35a9ec8e784806642d8e75b..7aea58cb423fa8d478ac708d0bac167da58a44f7 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.h @@ -32,22 +32,22 @@ namespace itk */ /* Can we template of Image type instead, but require that Image be of type - * Image< Vector< TValueType, NVectorDimension >, VImageDimension > ? */ -template< typename TValueType, + * Image< Vector< TValue, NVectorDimension >, VImageDimension > ? */ +template< typename TValue, unsigned int NVectorDimension, unsigned int VImageDimension > class ImageVectorOptimizerParametersHelper - : public OptimizerParametersHelper< TValueType > + : public OptimizerParametersHelper< TValue > { public: /** The element type stored at each location in the Array. */ - typedef TValueType ValueType; - typedef ImageVectorOptimizerParametersHelper Self; - typedef OptimizerParametersHelper< TValueType > Superclass; + typedef TValue ValueType; + typedef ImageVectorOptimizerParametersHelper Self; + typedef OptimizerParametersHelper< TValue > Superclass; /** Image type that this class expects. */ - typedef Image< Vector<TValueType, NVectorDimension>, + typedef Image< Vector<TValue, NVectorDimension>, VImageDimension > ParameterImageType; typedef typename ParameterImageType::Pointer ParameterImagePointer; @@ -61,10 +61,10 @@ public: /** Set a new data pointer for *both* the Array and parameter image, * pointing both to a different memory block. * The size of the new memroy block must be the same as current size of - * Array and the parameter image's buffer, in elements of TValueType. + * Array and the parameter image's buffer, in elements of TValue. * Memory must be managed by caller afterwards. */ virtual void MoveDataPointer(CommonContainerType* container, - TValueType * pointer ); + TValue * pointer ); /** Set an image that holds the parameter data. \c container is a pointer * of type itkArray to the object to which this helper is assigned. diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.hxx index f69ecaa2389c01947bf1f8712e797801216fa1ce..ffbb1fa60c7c08907b55ac632ed40183e40289ad 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.hxx @@ -24,29 +24,29 @@ namespace itk { /** Default contstructor */ -template< typename TValueType, +template< typename TValue, unsigned int NVectorDimension, unsigned int VImageDimension > -ImageVectorOptimizerParametersHelper< TValueType, NVectorDimension, VImageDimension > +ImageVectorOptimizerParametersHelper< TValue, NVectorDimension, VImageDimension > ::ImageVectorOptimizerParametersHelper() { - m_ParameterImage = NULL; + m_ParameterImage = ITK_NULLPTR; } /** Move the data pointer */ -template< typename TValueType, +template< typename TValue, unsigned int NVectorDimension, unsigned int VImageDimension > void -ImageVectorOptimizerParametersHelper< TValueType, NVectorDimension, VImageDimension > -::MoveDataPointer( CommonContainerType* container, TValueType * pointer ) +ImageVectorOptimizerParametersHelper< TValue, NVectorDimension, VImageDimension > +::MoveDataPointer( CommonContainerType* container, TValue * pointer ) { if( m_ParameterImage.IsNull() ) { itkGenericExceptionMacro("ImageVectorOptimizerParametersHelper::" "MoveDataPointer: m_ParameterImage must be defined."); } - // The buffer for Image<Vector> points to Vector type, not TValueType, so + // The buffer for Image<Vector> points to Vector type, not TValue, so // have to cast. typedef typename ParameterImageType::PixelContainer::Element vectorElement; vectorElement* vectorPointer = reinterpret_cast<vectorElement *>(pointer); @@ -59,23 +59,23 @@ ImageVectorOptimizerParametersHelper< TValueType, NVectorDimension, VImageDimens } /** Set parameter image */ -template< typename TValueType, +template< typename TValue, unsigned int NVectorDimension, unsigned int VImageDimension > void -ImageVectorOptimizerParametersHelper< TValueType, NVectorDimension, VImageDimension > +ImageVectorOptimizerParametersHelper< TValue, NVectorDimension, VImageDimension > ::SetParametersObject(CommonContainerType * container, LightObject * object) { - if( object == NULL ) + if( object == ITK_NULLPTR ) { - m_ParameterImage = NULL; + m_ParameterImage = ITK_NULLPTR; return; } else { ParameterImageType* image = dynamic_cast<ParameterImageType *>( object ); - if( image == NULL ) + if( image == ITK_NULLPTR ) { itkGenericExceptionMacro( "ImageVectorOptimizerParametersHelper::SetParametersObject: object is " @@ -84,10 +84,10 @@ ImageVectorOptimizerParametersHelper< TValueType, NVectorDimension, VImageDimens } m_ParameterImage = image; //The PixelContainer for Image<Vector> points to type Vector, so we have - // to determine the number of raw elements of type TValueType in the buffer + // to determine the number of raw elements of type TValue in the buffer // and cast a pointer to it for assignment to the Array data pointer. unsigned int sz = image->GetPixelContainer()->Size() * NVectorDimension; - TValueType* valuePointer = reinterpret_cast<TValueType *> + TValue* valuePointer = reinterpret_cast<TValue *> ( image->GetPixelContainer()->GetBufferPointer() ); //Set the Array's pointer to the image data buffer. By default it will // not manage the memory. diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImportImageContainer.h b/Utilities/ITK/Modules/Core/Common/include/itkImportImageContainer.h index b6eaafc1a9db152bebf8517de3320a2ae5c6c274..ed33e0496aaa39eb8257fc9245c1979b92ee8bf4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImportImageContainer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkImportImageContainer.h @@ -105,8 +105,11 @@ public: * container. However, in this particular case, Reserve as a Resize * semantics that is kept for backward compatibility reasons. * + * If UseDefaultConstructor is true, then * the default constructor is used + * to initialize each element. POD date types initialize to zero. + * * \sa SetImportPointer() */ - void Reserve(ElementIdentifier num); + void Reserve(ElementIdentifier num, const bool UseDefaultConstructor = false); /** Tell the container to try to minimize its memory usage for * storage of the current number of elements. If new memory is @@ -139,9 +142,14 @@ protected: /** PrintSelf routine. Normally this is a protected internal method. It is * made public here so that Image can call this method. Users should not * call this method but should call Print() instead. */ - void PrintSelf(std::ostream & os, Indent indent) const; - - virtual TElement * AllocateElements(ElementIdentifier size) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + + /** + * Allocates elements of the array. If UseDefaultConstructor is true, then + * the default constructor is used to initialize each element. POD date types + * initialize to zero. + */ + virtual TElement * AllocateElements(ElementIdentifier size, bool UseDefaultConstructor = false) const; virtual void DeallocateManagedMemory(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImportImageContainer.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImportImageContainer.hxx index d22c90a754066c23ba754e9d0148daf4ddabdaa7..cf29eb3f95e0c22ddd32f1170bfe1aff69569634 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImportImageContainer.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImportImageContainer.hxx @@ -36,7 +36,7 @@ template< typename TElementIdentifier, typename TElement > ImportImageContainer< TElementIdentifier, TElement > ::ImportImageContainer() { - m_ImportPointer = 0; + m_ImportPointer = ITK_NULLPTR; m_ContainerManageMemory = true; m_Capacity = 0; m_Size = 0; @@ -56,7 +56,7 @@ ImportImageContainer< TElementIdentifier, TElement > template< typename TElementIdentifier, typename TElement > void ImportImageContainer< TElementIdentifier, TElement > -::Reserve(ElementIdentifier size) +::Reserve(ElementIdentifier size, const bool UseDefaultConstructor ) { // Reserve has a Resize semantics. We keep it that way for // backwards compatibility . @@ -65,7 +65,7 @@ ImportImageContainer< TElementIdentifier, TElement > { if ( size > m_Capacity ) { - TElement *temp = this->AllocateElements(size); + TElement *temp = this->AllocateElements(size, UseDefaultConstructor); // only copy the portion of the data used in the old buffer std::copy(m_ImportPointer, m_ImportPointer+m_Size, @@ -87,7 +87,7 @@ ImportImageContainer< TElementIdentifier, TElement > } else { - m_ImportPointer = this->AllocateElements(size); + m_ImportPointer = this->AllocateElements(size, UseDefaultConstructor); m_Capacity = size; m_Size = size; m_ContainerManageMemory = true; @@ -109,7 +109,7 @@ ImportImageContainer< TElementIdentifier, TElement > if ( m_Size < m_Capacity ) { const TElementIdentifier size = m_Size; - TElement * temp = this->AllocateElements(size); + TElement * temp = this->AllocateElements(size, false); std::copy(m_ImportPointer, m_ImportPointer+m_Size, temp); @@ -170,7 +170,7 @@ ImportImageContainer< TElementIdentifier, TElement > template< typename TElementIdentifier, typename TElement > TElement *ImportImageContainer< TElementIdentifier, TElement > -::AllocateElements(ElementIdentifier size) const +::AllocateElements(ElementIdentifier size, bool UseDefaultConstructor ) const { // Encapsulate all image memory allocation here to throw an // exception when memory allocation fails even when the compiler @@ -179,11 +179,18 @@ TElement *ImportImageContainer< TElementIdentifier, TElement > try { - data = new TElement[size]; + if ( UseDefaultConstructor ) + { + data = new TElement[size](); //POD types initialized to 0, others use default constructor. + } + else + { + data = new TElement[size]; //Faster but uninitialized + } } catch ( ... ) { - data = 0; + data = ITK_NULLPTR; } if ( !data ) { @@ -205,7 +212,7 @@ void ImportImageContainer< TElementIdentifier, TElement > { delete[] m_ImportPointer; } - m_ImportPointer = 0; + m_ImportPointer = ITK_NULLPTR; m_Capacity = 0; m_Size = 0; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkImportImageFilter.hxx b/Utilities/ITK/Modules/Core/Common/include/itkImportImageFilter.hxx index 3b32dee2eac86bb7cef334ffe66cb120ec744c50..5d444456da4e3ad026629fae96cba68854428ddd 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkImportImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkImportImageFilter.hxx @@ -39,7 +39,7 @@ ImportImageFilter< TPixel, VImageDimension > } m_Direction.SetIdentity(); - m_ImportPointer = 0; + m_ImportPointer = ITK_NULLPTR; m_FilterManageMemory = false; m_Size = 0; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkInOrderTreeIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkInOrderTreeIterator.h index 92a56ec6c81bde5aea16781cf7dcba13a8bc593a..8983316ed50ef9c8aa714a07cbb8af19d11fa904 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkInOrderTreeIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkInOrderTreeIterator.h @@ -83,7 +83,7 @@ InOrderTreeIterator< TTreeType >::GetType() const template< typename TTreeType > bool InOrderTreeIterator< TTreeType >::HasNext() const { - if ( const_cast< TreeNodeType * >( FindNextNode() ) != NULL ) + if ( const_cast< TreeNodeType * >( FindNextNode() ) != ITK_NULLPTR ) { return true; } @@ -104,9 +104,9 @@ template< typename TTreeType > const typename InOrderTreeIterator< TTreeType >::TreeNodeType * InOrderTreeIterator< TTreeType >::FindNextNode() const { - if ( this->m_Position == NULL ) + if ( this->m_Position == ITK_NULLPTR ) { - return NULL; + return ITK_NULLPTR; } if ( this->m_Position->HasChildren() ) @@ -116,7 +116,7 @@ InOrderTreeIterator< TTreeType >::FindNextNode() const if ( !this->m_Position->HasParent() ) { - return NULL; + return ITK_NULLPTR; } TreeNodeType *child = this->m_Position; @@ -128,7 +128,7 @@ InOrderTreeIterator< TTreeType >::FindNextNode() const while ( childPosition < lastChildPosition ) { TreeNodeType *help = parent->GetChild(childPosition + 1); - if ( help != NULL ) + if ( help != ITK_NULLPTR ) { return help; } @@ -143,7 +143,7 @@ InOrderTreeIterator< TTreeType >::FindNextNode() const // Subtree if ( parent->ChildPosition(this->m_Root) >= 0 ) { - return NULL; + return ITK_NULLPTR; } childPosition = parent->ChildPosition(child); lastChildPosition = parent->CountChildren() - 1; @@ -151,13 +151,13 @@ InOrderTreeIterator< TTreeType >::FindNextNode() const while ( childPosition < lastChildPosition ) { TreeNodeType *help = parent->GetChild(childPosition + 1); - if ( help != NULL ) + if ( help != ITK_NULLPTR ) { return help; } } } - return NULL; + return ITK_NULLPTR; } /** Clone function */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkInPlaceImageFilter.hxx b/Utilities/ITK/Modules/Core/Common/include/itkInPlaceImageFilter.hxx index 7ee526743d480d40c319478345fc4c4184699328..37633910af375fd510ac817bd145454fd151f607 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkInPlaceImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkInPlaceImageFilter.hxx @@ -85,7 +85,7 @@ InPlaceImageFilter< TInputImage, TOutputImage > // additionally the buffered and requested regions of the input and // output must match. bool rMatch = true; - if( inputPtr != NULL && (unsigned int)InputImageDimension == (unsigned int)OutputImageDimension ) + if( inputPtr != ITK_NULLPTR && (unsigned int)InputImageDimension == (unsigned int)OutputImageDimension ) { for( unsigned int i=0; i<(unsigned int)InputImageDimension; i++ ) { @@ -103,7 +103,7 @@ InPlaceImageFilter< TInputImage, TOutputImage > { rMatch = false; } - if ( inputPtr != NULL && + if ( inputPtr != ITK_NULLPTR && this->GetInPlace() && this->CanRunInPlace() && rMatch ) @@ -111,7 +111,7 @@ InPlaceImageFilter< TInputImage, TOutputImage > // Graft this first input to the output. Later, we'll need to // remove the input's hold on the bulk data. // - OutputImagePointer inputAsOutput = NULL; + OutputImagePointer inputAsOutput = ITK_NULLPTR; if ( IsSame<TInputImage, TOutputImage>() ) { inputAsOutput = reinterpret_cast<TOutputImage *>( const_cast< TInputImage * >( inputPtr ) ); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkIndex.h b/Utilities/ITK/Modules/Core/Common/include/itkIndex.h index d151d14cecec1f09c158d53048cc6d79cc720829..d4f1e86c3bf3c1b2119c6b31173490d587e9d2f1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkIndex.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkIndex.h @@ -220,10 +220,24 @@ public: return !same; } +// false positive warnings with GCC 4.9 +#if defined( __GNUC__ ) +#if ( __GNUC__ == 4 ) && ( __GNUC_MINOR__ == 9 ) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Warray-bounds" +#endif +#endif /** Access an element of the index. Elements are numbered * 0, ..., VIndexDimension-1. No bounds checking is performed. */ IndexValueType & operator[](unsigned int dim) - { return m_Index[dim]; } + { + return m_Index[dim]; + } +#if defined( __GNUC__ ) +#if ( __GNUC__ == 4 ) && ( __GNUC_MINOR__ == 9 ) +#pragma GCC diagnostic pop +#endif +#endif /** Access an element of the index. Elements are numbered * 0, ..., VIndexDimension-1. This version can only be an rvalue. diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLeafTreeIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkLeafTreeIterator.h index 2aef92db5aa5b2fe12c8b635b6627c8965a102b8..b76d057e4d09e57065d5c49fccee9490b79ecbb4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLeafTreeIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkLeafTreeIterator.h @@ -84,7 +84,7 @@ LeafTreeIterator< TTreeType >::LeafTreeIterator(const TTreeType *tree): /** Constructor */ template< typename TTreeType > LeafTreeIterator< TTreeType >::LeafTreeIterator(TTreeType *tree): - TreeIteratorBase< TTreeType >(tree, NULL) + TreeIteratorBase< TTreeType >(tree, ITK_NULLPTR) { this->m_Begin = const_cast< TreeNodeType * >( this->FindNextNode() ); // // @@ -115,11 +115,11 @@ LeafTreeIterator< TTreeType >::GetType() const template< typename TTreeType > bool LeafTreeIterator< TTreeType >::HasNext() const { - if ( this->m_Position == NULL ) + if ( this->m_Position == ITK_NULLPTR ) { return false; } - if ( const_cast< TreeNodeType * >( FindNextNode() ) != NULL ) + if ( const_cast< TreeNodeType * >( FindNextNode() ) != ITK_NULLPTR ) { return true; } @@ -145,7 +145,7 @@ LeafTreeIterator< TTreeType >::FindNextNode() const ++it; // go next if ( it.IsAtEnd() ) { - return NULL; + return ITK_NULLPTR; } if ( !it.HasChild() ) @@ -162,7 +162,7 @@ LeafTreeIterator< TTreeType >::FindNextNode() const ++it; } - return NULL; + return ITK_NULLPTR; } /** Clone function */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLevelOrderTreeIterator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkLevelOrderTreeIterator.hxx index 1c54fe257a43da3914b470a627425118756721f8..1f4f3bfc91040ba5068e99c94a5db50e2e44ba46 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLevelOrderTreeIterator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkLevelOrderTreeIterator.hxx @@ -30,7 +30,7 @@ LevelOrderTreeIterator< TTreeType > { m_StartLevel = -1; m_EndLevel = endLevel; - if ( start != NULL ) + if ( start != ITK_NULLPTR ) { m_Queue.push(start); this->m_Position = const_cast< TreeNodeType * >( start ); @@ -54,7 +54,7 @@ LevelOrderTreeIterator< TTreeType > { m_StartLevel = startLevel; m_EndLevel = endLevel; - if ( start != NULL ) + if ( start != ITK_NULLPTR ) { m_Queue.push(start); this->m_Position = const_cast< TreeNodeType * >( start ); @@ -125,14 +125,14 @@ LevelOrderTreeIterator< TTreeType >::FindNextNode() const do { node = FindNextNodeHelp(); - if ( node == NULL ) + if ( node == ITK_NULLPTR ) { - return NULL; + return ITK_NULLPTR; } level = GetLevel(node); if ( level > m_EndLevel ) { - return NULL; + return ITK_NULLPTR; } } while ( level < m_StartLevel ); @@ -145,7 +145,7 @@ template< typename TTreeType > int LevelOrderTreeIterator< TTreeType >::GetLevel() const { - if ( this->m_Position == NULL ) + if ( this->m_Position == ITK_NULLPTR ) { return -1; } @@ -165,7 +165,7 @@ template< typename TTreeType > int LevelOrderTreeIterator< TTreeType >::GetLevel(const TreeNodeType *node) const { - if ( node == NULL ) + if ( node == ITK_NULLPTR ) { return -1; } @@ -186,15 +186,15 @@ LevelOrderTreeIterator< TTreeType >::FindNextNodeHelp() const { if ( m_Queue.empty() ) { - return NULL; + return ITK_NULLPTR; } const TreeNodeType *currentNode = m_Queue.front(); m_Queue.pop(); - if ( currentNode == NULL ) + if ( currentNode == ITK_NULLPTR ) { - return NULL; + return ITK_NULLPTR; } int size = currentNode->CountChildren(); @@ -202,7 +202,7 @@ LevelOrderTreeIterator< TTreeType >::FindNextNodeHelp() const for ( int i = 0; i < size; i++ ) { TreeNodeType *child = dynamic_cast< TreeNodeType * >( currentNode->GetChild(i) ); - if ( child != NULL ) + if ( child != ITK_NULLPTR ) { m_Queue.push(child); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLightObject.h b/Utilities/ITK/Modules/Core/Common/include/itkLightObject.h index 37b33d91a45fe3a47fd92d0f38b5ed4473dc711c..1f9e3f4f9cbdfff1a1329f4013ecdb4fe0dc1fbe 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLightObject.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkLightObject.h @@ -162,6 +162,16 @@ private: LightObject(const Self &); //purposely not implemented void operator=(const Self &); //purposely not implemented }; + +/** + * This operator allows all subclasses of LightObject to be printed via <<. + * It in turn invokes the Print method, which in turn will invoke the + * PrintSelf method that all objects should define, if they have anything + * interesting to print out. + */ +std::ostream & +operator<<(std::ostream & os, const LightObject & o); + } // end namespace itk #endif diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLightProcessObject.h b/Utilities/ITK/Modules/Core/Common/include/itkLightProcessObject.h index 911489e03bbe2e5ec9bc21a42d0e3f4233ceee6f..5a78173aacd70dae6c4654667d9ce34e2bf9360c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLightProcessObject.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkLightProcessObject.h @@ -116,7 +116,7 @@ public: protected: LightProcessObject(); ~LightProcessObject(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** This method causes the filter to generate its output. */ virtual void GenerateData() {} diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLoggerBase.h b/Utilities/ITK/Modules/Core/Common/include/itkLoggerBase.h index 26b7b833e29e2fd13524978dd4d56b881e7b7483..a799345b9bad86e8c043cdc4ee14554d2d70dc28 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLoggerBase.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkLoggerBase.h @@ -169,7 +169,7 @@ protected: virtual ~LoggerBase(); /** Print contents of a LoggerBase */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; protected: diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLoggerManager.h b/Utilities/ITK/Modules/Core/Common/include/itkLoggerManager.h index 547e2737b080aeb71f5e01864eb33a4cd72e2b19..9b75fe1bf438dc6a1e82fb8a9f8e635b5af7520b 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLoggerManager.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkLoggerManager.h @@ -99,7 +99,7 @@ protected: virtual ~LoggerManager() {} /** Print contents of a LoggerManager */ - void PrintSelf(std::ostream & s, Indent indent) const; + virtual void PrintSelf(std::ostream & s, Indent indent) const ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLoggerOutput.h b/Utilities/ITK/Modules/Core/Common/include/itkLoggerOutput.h index 57af276f46787f49819bb3a8a3ff1195b594a67f..cbd4856487b684f620e03e0e6a6ef20724cabefd 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLoggerOutput.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkLoggerOutput.h @@ -64,27 +64,27 @@ public: typedef Logger *LoggerType; /** Send a string to display. */ - virtual void DisplayText(const char *t); + virtual void DisplayText(const char *t) ITK_OVERRIDE; /** Send a string as an error message to display. * The default implementation calls DisplayText() but subclasses * could present this message differently. */ - virtual void DisplayErrorText(const char *t); + virtual void DisplayErrorText(const char *t) ITK_OVERRIDE; /** Send a string as a warningmessage to display. * The default implementation calls DisplayText() but subclasses * could present this message differently. */ - virtual void DisplayWarningText(const char *t); + virtual void DisplayWarningText(const char *t) ITK_OVERRIDE; /** Send a string as a message to display. * The default implementation calls DisplayText() but subclasses * could present this message differently. */ - virtual void DisplayGenericOutputText(const char *t); + virtual void DisplayGenericOutputText(const char *t) ITK_OVERRIDE; /** Send a string as a debug message to display. * The default implementation calls DisplayText() but subclasses * could present this message differently. */ - virtual void DisplayDebugText(const char *t); + virtual void DisplayDebugText(const char *t) ITK_OVERRIDE; itkSetMacro(Logger, LoggerType); @@ -96,9 +96,9 @@ public: } protected: - LoggerOutput():m_Logger(0) {} + LoggerOutput():m_Logger(ITK_NULLPTR) {} virtual ~LoggerOutput() {} - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: Logger *m_Logger; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLoggerThreadWrapper.h b/Utilities/ITK/Modules/Core/Common/include/itkLoggerThreadWrapper.h index ba9e3367f6139ae9ff329cf786391a6e90b1f198..7b36bcc7979b95b6aabd961ae7e5e9933522a090 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLoggerThreadWrapper.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkLoggerThreadWrapper.h @@ -61,8 +61,7 @@ public: SET_PRIORITY_LEVEL, SET_LEVEL_FOR_FLUSHING, ADD_LOG_OUTPUT, - WRITE, - FLUSH + WRITE } OperationType; /** Set the priority level for the current logger. Only messages that have diff --git a/Utilities/ITK/Modules/Core/Common/include/itkLoggerThreadWrapper.hxx b/Utilities/ITK/Modules/Core/Common/include/itkLoggerThreadWrapper.hxx index 16f617d10f24250f8e675b64692f51bf3b3073b6..7f387df9da536b4031105c31386aaaec851cb664 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkLoggerThreadWrapper.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkLoggerThreadWrapper.hxx @@ -139,12 +139,10 @@ void LoggerThreadWrapper< SimpleLoggerType >::Flush() this->m_LevelQ.pop(); this->m_MessageQ.pop(); break; - case Self::FLUSH: - this->SimpleLoggerType::Flush(); - break; } this->m_OperationQ.pop(); } + this->SimpleLoggerType::Flush(); this->m_Output->Flush(); this->m_Mutex.Unlock(); } @@ -174,62 +172,54 @@ ITK_THREAD_RETURN_TYPE LoggerThreadWrapper< SimpleLoggerType >::ThreadFunction(v { struct MultiThreader:: ThreadInfoStruct *pInfo = (struct MultiThreader::ThreadInfoStruct *)pInfoStruct; - if ( pInfo == NULL ) + if ( ( pInfo != ITK_NULLPTR ) && ( pInfo->UserData != ITK_NULLPTR ) ) { - return ITK_THREAD_RETURN_VALUE; - } - if ( pInfo->UserData == NULL ) - { - return ITK_THREAD_RETURN_VALUE; - } - - LoggerThreadWrapper *pLogger = (LoggerThreadWrapper *)pInfo->UserData; - - while ( 1 ) - { + LoggerThreadWrapper *pLogger = (LoggerThreadWrapper *)pInfo->UserData; - pInfo->ActiveFlagLock->Lock(); - int activeFlag = *pInfo->ActiveFlag; - pInfo->ActiveFlagLock->Unlock(); - if ( !activeFlag ) + while ( 1 ) { - break; - } - pLogger->m_Mutex.Lock(); - while ( !pLogger->m_OperationQ.empty() ) - { - switch ( pLogger->m_OperationQ.front() ) + pInfo->ActiveFlagLock->Lock(); + int activeFlag = *pInfo->ActiveFlag; + pInfo->ActiveFlagLock->Unlock(); + if ( !activeFlag ) + { + break; + } + + pLogger->m_Mutex.Lock(); + while ( !pLogger->m_OperationQ.empty() ) { - case Self::SET_PRIORITY_LEVEL: - pLogger->m_PriorityLevel = pLogger->m_LevelQ.front(); - pLogger->m_LevelQ.pop(); - break; - - case Self::SET_LEVEL_FOR_FLUSHING: - pLogger->m_LevelForFlushing = pLogger->m_LevelQ.front(); - pLogger->m_LevelQ.pop(); - break; - - case Self::ADD_LOG_OUTPUT: - pLogger->m_Output->AddLogOutput( pLogger->m_OutputQ.front() ); - pLogger->m_OutputQ.pop(); - break; - - case Self::WRITE: - pLogger->SimpleLoggerType::Write( pLogger->m_LevelQ.front(), pLogger->m_MessageQ.front() ); - pLogger->m_LevelQ.pop(); - pLogger->m_MessageQ.pop(); - break; - case Self::FLUSH: - pLogger->SimpleLoggerType::Flush(); - break; + switch ( pLogger->m_OperationQ.front() ) + { + case Self::SET_PRIORITY_LEVEL: + pLogger->m_PriorityLevel = pLogger->m_LevelQ.front(); + pLogger->m_LevelQ.pop(); + break; + + case Self::SET_LEVEL_FOR_FLUSHING: + pLogger->m_LevelForFlushing = pLogger->m_LevelQ.front(); + pLogger->m_LevelQ.pop(); + break; + + case Self::ADD_LOG_OUTPUT: + pLogger->m_Output->AddLogOutput( pLogger->m_OutputQ.front() ); + pLogger->m_OutputQ.pop(); + break; + + case Self::WRITE: + pLogger->SimpleLoggerType::Write( pLogger->m_LevelQ.front(), pLogger->m_MessageQ.front() ); + pLogger->m_LevelQ.pop(); + pLogger->m_MessageQ.pop(); + break; + } + pLogger->m_OperationQ.pop(); } - pLogger->m_OperationQ.pop(); + pLogger->m_Mutex.Unlock(); + pLogger->SimpleLoggerType::Flush(); + itksys::SystemTools::Delay(pLogger->GetDelay()); } - pLogger->m_Mutex.Unlock(); - itksys::SystemTools::Delay(pLogger->GetDelay()); } return ITK_THREAD_RETURN_VALUE; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMacro.h b/Utilities/ITK/Modules/Core/Common/include/itkMacro.h index 0d8ef3b1b6dad696e2a4793bbf0bef39da2d0536..61d601c666855fc3b6c3c0a95973beb2bd2a2367 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMacro.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMacro.h @@ -118,6 +118,23 @@ namespace itk #endif #endif +#if __cplusplus >= 201103L +// In c++11 the override keyword allows you to explicity define that a function +// is intended to override the base-class version. This makes the code more +// managable and fixes a set of common hard-to-find bugs. +#define ITK_OVERRIDE override +// In c++11 there is an explicit nullptr type that introduces a new keyword to +// serve as a distinguished null pointer constant: nullptr. It is of type +// nullptr_t, which is implicitly convertible and comparable to any pointer type +// or pointer-to-member type. It is not implicitly convertible or comparable to +// integral types, except for bool. +#define ITK_NULLPTR nullptr +#else +#define ITK_OVERRIDE +#define ITK_NULLPTR NULL +#endif + + /** Define two object creation methods. The first method, New(), * creates an object from a class, potentially deferring to a factory. * The second method, CreateAnother(), creates an object from an @@ -147,7 +164,7 @@ namespace itk static Pointer New(void) \ { \ Pointer smartPtr = ::itk::ObjectFactory< x >::Create(); \ - if ( smartPtr.GetPointer() == NULL ) \ + if ( smartPtr.GetPointer() == ITK_NULLPTR ) \ { \ smartPtr = new x; \ } \ @@ -156,7 +173,7 @@ namespace itk } #define itkCreateAnotherMacro(x) \ - virtual::itk::LightObject::Pointer CreateAnother(void) const \ + virtual::itk::LightObject::Pointer CreateAnother(void) const ITK_OVERRIDE \ { \ ::itk::LightObject::Pointer smartPtr; \ smartPtr = x::New().GetPointer(); \ @@ -196,7 +213,7 @@ namespace itk rawPtr->UnRegister(); \ return smartPtr; \ } \ - virtual::itk::LightObject::Pointer CreateAnother(void) const \ + virtual::itk::LightObject::Pointer CreateAnother(void) const ITK_OVERRIDE \ { \ ::itk::LightObject::Pointer smartPtr; \ smartPtr = x::New().GetPointer(); \ @@ -275,7 +292,7 @@ extern ITKCommon_EXPORT void OutputWindowDisplayDebugText(const char *); #if defined( ITK_CPP_FUNCTION ) #if defined( _WIN32 ) && !defined( __MINGW32__ ) && !defined( CABLE_CONFIGURATION ) \ - && !defined( CSWIG ) + && !defined( __GCCXML__ ) #define ITK_LOCATION __FUNCSIG__ #elif defined( __GNUC__ ) #define ITK_LOCATION __PRETTY_FUNCTION__ @@ -399,7 +416,7 @@ itkTypeMacro(newexcp, parentexcp); // itkLegacyMacro(void MyMethod()); #if defined( ITK_LEGACY_REMOVE ) #define itkLegacyMacro(method) /* no ';' */ -#elif defined( ITK_LEGACY_SILENT ) || defined( ITK_LEGACY_TEST ) || defined( CSWIG ) +#elif defined( ITK_LEGACY_SILENT ) || defined( ITK_LEGACY_TEST ) || defined( __GCCXML__ ) // Provide legacy methods with no warnings. #define itkLegacyMacro(method) method #else @@ -539,68 +556,6 @@ itkTypeMacro(newexcp, parentexcp); #define ITK_FRIEND_TEMPLATE_FUNCTION_ARGUMENT(T) #endif -//============================================================================= -/* Choose a way to prevent template instantiation on this platform. - - ITK_TEMPLATE_DO_NOT_INSTANTIATE = use #pragma do_not_instantiate to - prevent instantiation - - ITK_TEMPLATE_EXTERN = use extern template to prevent instantiation -*/ -#if defined( __INTEL_COMPILER ) && __INTEL_COMPILER >= 700 -#define ITK_TEMPLATE_EXTERN 1 -#elif defined( __GNUC__ ) && __GNUC__ >= 3 -#define ITK_TEMPLATE_EXTERN 1 -#elif defined( _MSC_VER ) -#define ITK_TEMPLATE_EXTERN 1 -#endif -#if !defined( ITK_TEMPLATE_DO_NOT_INSTANTIATE ) -#define ITK_TEMPLATE_DO_NOT_INSTANTIATE 0 -#endif -#if !defined( ITK_TEMPLATE_EXTERN ) -#define ITK_TEMPLATE_EXTERN 0 -#endif - -/* Define a macro to explicitly instantiate a template. - - ITK_TEMPLATE_EXPORT(X) = - Explicitly instantiate X, where X is of the form N(a1[,a2...,aN]). - examples: ITK_TEMPLATE_EXPORT(1(class Foo<int>)) - ITK_TEMPLATE_EXPORT(2(class Bar<int, char>)) - Use one level of expansion delay to allow user code to have - a macro determining the number of arguments. */ -#define ITK_TEMPLATE_EXPORT(x) ITK_TEMPLATE_EXPORT_DELAY(x) -#define ITK_TEMPLATE_EXPORT_DELAY(x) template ITK_TEMPLATE_##x; - -/* Define a macro to prevent template instantiations. - - ITK_TEMPLATE_IMPORT(X) = - Prevent instantiation of X, where X is of the form N(a1[,a2...,aN]). - examples: ITK_TEMPLATE_IMPORT(1(class Foo<int>)) - ITK_TEMPLATE_IMPORT(2(class Bar<int, char>)) - Use one level of expansion delay to allow user code to have - a macro determining the number of arguments. -*/ -#if ITK_TEMPLATE_EXTERN -#define ITK_TEMPLATE_IMPORT_DELAY(x) extern template ITK_TEMPLATE_##x; -#elif ITK_TEMPLATE_DO_NOT_INSTANTIATE -#define ITK_TEMPLATE_IMPORT_DELAY(x) \ - ITK_TEMPLATE_IMPORT_IMPL(do_not_instantiate ITK_TEMPLATE_##x) -#define ITK_TEMPLATE_IMPORT_IMPL(x) _Pragma(#x) -#endif -#if defined( ITK_TEMPLATE_IMPORT_DELAY ) -#define ITK_TEMPLATE_IMPORT(x) ITK_TEMPLATE_IMPORT_DELAY(x) -#define ITK_TEMPLATE_IMPORT_WORKS 1 -#else -#define ITK_TEMPLATE_IMPORT(x) -#define ITK_TEMPLATE_IMPORT_WORKS 0 -#endif - -//============================================================================= - -/* Define macros to export and import template instantiations for each - library in ITK. */ -#define ITK_EXPORT_ITKCommon(c, x, n) \ - ITK_EXPORT_TEMPLATE(ITKCommon_EXPORT, c, x, n) -#define ITK_IMPORT_ITKCommon(c, x, n) \ - ITK_IMPORT_TEMPLATE(ITKCommon_EXPORT, c, x, n) - //-------------------------------------------------------------------------------- // Helper macros for Template Meta-Programming techniques of for-loops // unrolling @@ -703,6 +658,7 @@ TTarget itkDynamicCastInDebugMode(TSource x) #else return static_cast<TTarget>(x); #endif +} // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! @@ -721,7 +677,7 @@ TTarget itkDynamicCastInDebugMode(TSource x) virtual void Set##name(const type *_arg) \ { \ itkDebugMacro("setting input " #name " to " << _arg); \ - if ( _arg != static_cast< type * >( this->ProcessObject::GetInput(#name) ) ) \ + if ( _arg != itkDynamicCastInDebugMode< type * >( this->ProcessObject::GetInput(#name) ) ) \ { \ this->ProcessObject::SetInput( #name, const_cast< type * >( _arg ) ); \ this->Modified(); \ @@ -732,9 +688,8 @@ TTarget itkDynamicCastInDebugMode(TSource x) #define itkGetInputMacro(name, type) \ virtual const type * Get##name() const \ { \ - itkDebugMacro( "returning input " << #name " of " \ - << static_cast< const type * >( this->ProcessObject::GetInput(#name) ) ); \ - return static_cast< const type * >( this->ProcessObject::GetInput(#name) ); \ + itkDebugMacro( "returning input " << #name " of " << this->ProcessObject::GetInput(#name) ); \ + return itkDynamicCastInDebugMode< const type * >( this->ProcessObject::GetInput(#name) ); \ } /** Set a decorated input. This defines the Set"name"() and a Set"name"Input() method */ @@ -742,7 +697,7 @@ TTarget itkDynamicCastInDebugMode(TSource x) virtual void Set##name##Input(const SimpleDataObjectDecorator< type > *_arg) \ { \ itkDebugMacro("setting input " #name " to " << _arg); \ - if ( _arg != static_cast< SimpleDataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ) ) \ + if ( _arg != itkDynamicCastInDebugMode< SimpleDataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ) ) \ { \ this->ProcessObject::SetInput( #name, const_cast< SimpleDataObjectDecorator< type > * >( _arg ) ); \ this->Modified(); \ @@ -753,7 +708,7 @@ TTarget itkDynamicCastInDebugMode(TSource x) typedef SimpleDataObjectDecorator< type > DecoratorType; \ itkDebugMacro("setting input " #name " to " << _arg); \ const DecoratorType *oldInput = \ - static_cast< const DecoratorType * >( \ + itkDynamicCastInDebugMode< const DecoratorType * >( \ this->ProcessObject::GetInput(#name) ); \ if ( oldInput && oldInput->Get() == _arg ) \ { \ @@ -768,18 +723,17 @@ TTarget itkDynamicCastInDebugMode(TSource x) #define itkGetDecoratedInputMacro(name, type) \ virtual const SimpleDataObjectDecorator< type > * Get##name##Input() const \ { \ - itkDebugMacro( "returning input " << #name " of " \ - << static_cast< const SimpleDataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ) ); \ - return static_cast< const SimpleDataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ); \ + itkDebugMacro( "returning input " << #name " of " << this->ProcessObject::GetInput(#name) ); \ + return itkDynamicCastInDebugMode< const SimpleDataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ); \ } \ virtual const type & Get##name() const \ { \ itkDebugMacro("Getting input " #name); \ typedef SimpleDataObjectDecorator< type > DecoratorType; \ const DecoratorType *input = \ - static_cast< const DecoratorType * >( \ + itkDynamicCastInDebugMode< const DecoratorType * >( \ this->ProcessObject::GetInput(#name) ); \ - if( input == NULL ) \ + if( input == ITK_NULLPTR ) \ { \ itkExceptionMacro(<<"input" #name " is not set"); \ } \ @@ -800,7 +754,7 @@ TTarget itkDynamicCastInDebugMode(TSource x) virtual void Set##name##Input(const DataObjectDecorator< type > *_arg) \ { \ itkDebugMacro("setting input " #name " to " << _arg); \ - if ( _arg != static_cast< DataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ) ) \ + if ( _arg != itkDynamicCastInDebugMode< DataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ) ) \ { \ this->ProcessObject::SetInput( #name, const_cast< DataObjectDecorator< type > * >( _arg ) ); \ this->Modified(); \ @@ -811,7 +765,7 @@ TTarget itkDynamicCastInDebugMode(TSource x) typedef DataObjectDecorator< type > DecoratorType; \ itkDebugMacro("setting input " #name " to " << _arg); \ const DecoratorType *oldInput = \ - static_cast< const DecoratorType * >( \ + itkDynamicCastInDebugMode< const DecoratorType * >( \ this->ProcessObject::GetInput(#name) ); \ if ( oldInput && oldInput->Get() == _arg ) \ { \ @@ -829,20 +783,19 @@ TTarget itkDynamicCastInDebugMode(TSource x) #define itkGetDecoratedObjectInputMacro(name, type) \ virtual const DataObjectDecorator< type > * Get##name##Input() const \ { \ - itkDebugMacro( "returning input " << #name " of " \ - << static_cast< const DataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ) ); \ - return static_cast< const DataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ); \ + itkDebugMacro( "returning input " << #name " of "<< this->ProcessObject::GetInput(#name) ); \ + return itkDynamicCastInDebugMode< const DataObjectDecorator< type > * >( this->ProcessObject::GetInput(#name) ); \ } \ virtual const type * Get##name() const \ { \ itkDebugMacro("Getting input " #name); \ typedef DataObjectDecorator< type > DecoratorType; \ const DecoratorType *input = \ - static_cast< const DecoratorType * >( \ + itkDynamicCastInDebugMode< const DecoratorType * >( \ this->ProcessObject::GetInput(#name) ); \ - if( input == NULL ) \ + if( input == ITK_NULLPTR ) \ { \ - itkExceptionMacro(<<"input" #name " is not set"); \ + return ITK_NULLPTR; \ } \ return input->Get(); \ } @@ -1137,6 +1090,17 @@ class kernel \ return kernel::GetOpenCLSource(); \ } -} +// A useful macro in the PrintSelf method for printing member variables +// which are pointers to object based on the LightObject class. +#define itkPrintSelfObjectMacro(name) \ + if (static_cast<const LightObject*>(this->m_##name) == ITK_NULLPTR) \ + { \ + os << indent << #name << ": (null)" << std::endl; \ + } \ + else \ + { \ + os << indent << #name << ": " << std::endl; \ + this->m_##name->Print(os,indent.GetNextIndent()); \ + } #endif //end of itkMacro.h diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMath.h b/Utilities/ITK/Modules/Core/Common/include/itkMath.h index 5727098c3cdf4423187e0f914dc07216d7ba9a7a..6e3372d591bb202e6d9de6f0bc070620be2da9e4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMath.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMath.h @@ -261,7 +261,7 @@ FloatAlmostEqual( T x1, T x2, { // Check if the numbers are really close -- needed // when comparing numbers near zero. - const T absDifference = vcl_abs(x1 - x2); + const T absDifference = std::abs(x1 - x2); if ( absDifference <= maxAbsoluteDifference ) { return true; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMemoryProbe.h b/Utilities/ITK/Modules/Core/Common/include/itkMemoryProbe.h index 5f30c4bc34f6b8aaca96f47ecdb631b5a5478001..a1940c9ff92357d6d8f8088a4b7a96c69f673534 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMemoryProbe.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMemoryProbe.h @@ -51,7 +51,7 @@ public: typedef double MeanMemoryLoadType; protected: - virtual MemoryLoadType GetInstantValue(void) const; + virtual MemoryLoadType GetInstantValue(void) const ITK_OVERRIDE; private: mutable MemoryUsageObserver m_MemoryObserver; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMemoryUsageObserver.h b/Utilities/ITK/Modules/Core/Common/include/itkMemoryUsageObserver.h index 14abe98abedef3471362f83cd331d510aab36df7..2356acf11ea3471b7961f75b1673a0fd4dd494a9 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMemoryUsageObserver.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMemoryUsageObserver.h @@ -95,7 +95,7 @@ class ITKCommon_EXPORT MacOSXMemoryUsageObserver:public MemoryUsageObserverBase public: /** destructor */ virtual ~MacOSXMemoryUsageObserver(); - virtual MemoryLoadType GetMemoryUsage(); + virtual MemoryLoadType GetMemoryUsage() ITK_OVERRIDE; }; #endif // Mac OS X @@ -115,7 +115,7 @@ class ITKCommon_EXPORT SysResourceMemoryUsageObserver:public MemoryUsageObserver public: /** destructor */ virtual ~SysResourceMemoryUsageObserver(); - virtual MemoryLoadType GetMemoryUsage(); + virtual MemoryLoadType GetMemoryUsage() ITK_OVERRIDE; }; #if !defined( __APPLE__ ) && !defined( __SUNPRO_CC ) && !defined ( __sun__ ) && !defined( __FreeBSD__ ) \ && !defined( __OpenBSD__ ) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h b/Utilities/ITK/Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h index 7007e6772c7abf5a1e9f67425287ff7349a2a622..6d441ff978dc2a287a67abd00b51e0bf3784c0d1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h @@ -22,9 +22,9 @@ #include "itkObjectFactory.h" #include "itkRandomVariateGeneratorBase.h" #include "itkIntTypes.h" -#include "vcl_ctime.h" #include "vnl/vnl_math.h" #include <climits> +#include <ctime> namespace itk { @@ -33,7 +33,9 @@ namespace Statistics /** \class MersenneTwisterRandomVariateGenerator * \brief MersenneTwisterRandom random variate generator * - * \warning This class is NOT reentrant. + * \warning This class's instance methods are NOT neither reentrant + * nor thread-safe, but static methods are both. That is to say you + * can use separate objects concurrently. * * This notice was included with the original implementation. * The only changes made were to obfuscate the author's email addresses. @@ -119,16 +121,19 @@ public: itkTypeMacro(MersenneTwisterRandomVariateGenerator, RandomVariateGeneratorBase); - /** Method for creation through the object factory. - This method allocates a new instance of a Mersenne Twister, - and initializes it with the seed from the global instance. */ + /** \brief Method for creation through the object factory. + * + * This method allocates a new instance of a Mersenne Twister, + * and initializes it with the seed from the global instance. + */ static Pointer New(); /** returns the global Merseene Twister instance - This method returns a Singleton of the Mersenne Twister. - The seed is initialized from the wall clock, but can be - set using SetSeed(). - */ + * + * This method returns a Singleton of the Mersenne Twister. + * The seed is initialized from the wall clock, but can be + * set using SetSeed(). + */ static Pointer GetInstance(); /** Length of state vector */ @@ -137,7 +142,7 @@ public: /** initialize with a simple IntegerType */ void Initialize(const IntegerType oneSeed); - /* Initialize with vcl_clock time */ + /* Initialize with clock time */ void Initialize(); /** Get a random variate in the range [0, 1] */ @@ -182,16 +187,16 @@ public: * values together, otherwise the generator state can be learned after * reading 624 consecutive values. */ - virtual double GetVariate(); + virtual double GetVariate() ITK_OVERRIDE; /** Same as GetVariate() */ double operator()(); - // Re-seeding functions with same behavior as initializers + /** Re-seeding functions with same behavior as initializers */ inline void SetSeed(const IntegerType oneSeed); - // inline void SetSeed(IntegerType *bigSeed, const IntegerType seedLength = StateVectorLength); inline void SetSeed(); - // Return the current seed + + /** Return the current seed */ IntegerType GetSeed() { return this->m_Seed; }; /* @@ -203,24 +208,7 @@ public: protected: inline MersenneTwisterRandomVariateGenerator(); virtual ~MersenneTwisterRandomVariateGenerator() {} - virtual void PrintSelf(std::ostream & os, Indent indent) const - { - Superclass::PrintSelf(os, indent); - - // Print state vector contents - os << indent << "State vector: " << state << std::endl; - os << indent; - register const IntegerType *s = state; - register int i = StateVectorLength; - for (; i--; os << *s++ << "\t" ) {} - os << std::endl; - - //Print next value to be gotten from state - os << indent << "Next value to be gotten from state: " << pNext << std::endl; - - //Number of values left before reload - os << indent << "Values left before next reload: " << left << std::endl; - } + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; // period parameter itkStaticConstMacro (M, unsigned int, 397); @@ -247,42 +235,21 @@ protected: return m ^ ( mixBits(s0, s1) >> 1 ) ^ ( -static_cast<int32_t>(loBit(s1)) & 0x9908b0df ); } - static IntegerType hash(vcl_time_t t, vcl_clock_t c); - - static Pointer m_Instance; -}; // end of class - -// Declare inlined functions.... (must be declared in the header) + static IntegerType hash(time_t t, clock_t c); -inline MersenneTwisterRandomVariateGenerator::IntegerType -MersenneTwisterRandomVariateGenerator::hash(vcl_time_t t, vcl_clock_t c) -{ - // Get a IntegerType from t and c - // Better than IntegerType(x) in case x is floating point in [0,1] - // Based on code by Lawrence Kirby: fred at genesis dot demon dot co dot uk +private: - static IntegerType differ = 0; // guarantee time-based seeds will change + /** Internal method to actually create a new object. */ + static Pointer CreateInstance(); - IntegerType h1 = 0; - unsigned char *p = (unsigned char *)&t; + // Static/Global Variable need to be thread-safely accessed + static Pointer m_StaticInstance; + static SimpleFastMutexLock m_StaticInstanceLock; + static IntegerType m_StaticDiffer; - const unsigned int sizeOfT = static_cast< unsigned int >( sizeof(t) ); - for ( unsigned int i = 0; i < sizeOfT; ++i ) - { - h1 *= UCHAR_MAX + 2U; - h1 += p[i]; - } - IntegerType h2 = 0; - p = (unsigned char *)&c; +}; // end of class - const unsigned int sizeOfC = static_cast< unsigned int >( sizeof(c) ); - for ( unsigned int j = 0; j < sizeOfC; ++j ) - { - h2 *= UCHAR_MAX + 2U; - h2 += p[j]; - } - return ( h1 + differ++ ) ^ h2; -} +// Declare inlined functions.... (must be declared in the header) inline void MersenneTwisterRandomVariateGenerator::Initialize(const IntegerType seed) @@ -292,9 +259,9 @@ MersenneTwisterRandomVariateGenerator::Initialize(const IntegerType seed) // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier. // In previous versions, most significant bits (MSBs) of the seed affect // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. - register IntegerType *s = state; - register IntegerType *r = state; - register IntegerType i = 1; + IntegerType *s = state; + IntegerType *r = state; + IntegerType i = 1; *s++ = seed & 0xffffffffUL; for ( i = 1; i < MersenneTwisterRandomVariateGenerator::StateVectorLength; ++i ) @@ -312,11 +279,11 @@ MersenneTwisterRandomVariateGenerator::reload() // matthew dot bellew at home dot com // get rid of VS warning - register int index = static_cast< int >( + int index = static_cast< int >( M - MersenneTwisterRandomVariateGenerator::StateVectorLength ); - register IntegerType *p = state; - register int i; + IntegerType *p = state; + int i; for ( i = MersenneTwisterRandomVariateGenerator::StateVectorLength - M; i--; ++p ) { @@ -331,58 +298,6 @@ MersenneTwisterRandomVariateGenerator::reload() left = MersenneTwisterRandomVariateGenerator::StateVectorLength, pNext = state; } - /* -#define SVL 624 -inline void -MersenneTwisterRandomVariateGenerator::SetSeed( - IntegerType *const bigSeed, const IntegerType seedLength) -{ - // Seed the generator with an array of IntegerType's - // There are 2^19937-1 possible initial states. This function allows - // all of those to be accessed by providing at least 19937 bits (with a - // default seed length of StateVectorLength = 624 IntegerType's). - // Any bits above the lower 32 - // in each element are discarded. - // Just call seed() if you want to get array from /dev/urandom - Initialize(19650218UL); - register IntegerType i = 1; - register IntegerType j = 0; - register int k; - if ( StateVectorLength > seedLength ) - { - k = StateVectorLength; - } - else - { - k = seedLength; - } - for (; k; --k ) - { - state[i] = - state[i] ^ ( ( state[i - 1] ^ ( state[i - 1] >> 30 ) ) * 1664525UL ); - state[i] += ( bigSeed[j] & 0xffffffffUL ) + j; - state[i] &= 0xffffffffUL; - ++i; ++j; - if ( i >= StateVectorLength ) { state[0] = state[StateVectorLength - 1]; i = 1; } - if ( j >= seedLength ) { j = 0; } - } - for ( k = StateVectorLength - 1; k; --k ) - { - state[i] = - state[i] ^ ( ( state[i - 1] ^ ( state[i - 1] >> 30 ) ) * 1566083941UL ); - state[i] -= i; - state[i] &= 0xffffffffUL; - ++i; - if ( i >= SVL ) - { - state[0] = state[StateVectorLength - 1]; i = 1; - } - } - state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array - reload(); -} - */ - inline void MersenneTwisterRandomVariateGenerator::Initialize() { @@ -401,7 +316,7 @@ inline void MersenneTwisterRandomVariateGenerator::SetSeed() { // use time() and clock() to generate a unlikely-to-repeat seed. - SetSeed( hash( vcl_time(0), vcl_clock() ) ); + SetSeed( hash( time(ITK_NULLPTR), clock() ) ); } /** Get an integer variate in [0, 2^32-1] */ @@ -411,8 +326,7 @@ MersenneTwisterRandomVariateGenerator::GetIntegerVariate() if ( left == 0 ) { reload(); } --left; - register IntegerType s1; - s1 = *pNext++; + IntegerType s1 = *pNext++; s1 ^= ( s1 >> 11 ); s1 ^= ( s1 << 7 ) & 0x9d2c5680; s1 ^= ( s1 << 15 ) & 0xefc60000; @@ -507,11 +421,11 @@ MersenneTwisterRandomVariateGenerator::GetNormalVariate( { // Return a real number from a normal (Gaussian) distribution with given // mean and variance by Box-Muller method - double r = vcl_sqrt(-2.0 * vcl_log( 1.0 - GetVariateWithOpenRange() ) * variance); + double r = std::sqrt(-2.0 * std::log( 1.0 - GetVariateWithOpenRange() ) * variance); double phi = 2.0 * vnl_math::pi * GetVariateWithOpenUpperRange(); - return mean + r *vcl_cos(phi); + return mean + r *std::cos(phi); } /* Access to a uniform random number distribution */ @@ -537,12 +451,6 @@ MersenneTwisterRandomVariateGenerator::operator()() return GetVariate(); } -inline -MersenneTwisterRandomVariateGenerator::MersenneTwisterRandomVariateGenerator() -{ - SetSeed (121212); -} - /* Change log from MTRand.h */ // Change log: // diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObject.h b/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObject.h index f1d5499b6020654f8dda741a7b357297cf186699..8e3040cf0627bf210c3aab1268d94bf0f308f122 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObject.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObject.h @@ -30,8 +30,8 @@ #include "itkMetaDataDictionary.h" #include "itkMacro.h" -#include "itkCommand.h" -#include "itkFastMutexLock.h" +#include "itkArray.h" +#include "itkMatrix.h" #include <cstring> @@ -85,33 +85,13 @@ public: /** Run-time type information (and related methods). */ itkTypeMacro(MetaDataObject, MetaDataObjectBase); - /** - * Default constructor with no initialization. - * \author Hans J. Johnson - */ - MetaDataObject(void); - /** - * Default virtual Destructor - * \author Hans J. Johnson - */ - virtual ~MetaDataObject(void); - /** - * Initializer constructor that sets m_MetaDataObjectValue to InitializerValue - * \author Hans J. Johnson - */ - MetaDataObject(const MetaDataObjectType InitializerValue); - /** - * Copy constructor that sets m_MetaDataObjectValue to TemplateObject.m_MetaDataObjectValue - * \author Hans J. Johnson - */ - MetaDataObject(const MetaDataObject< MetaDataObjectType > & TemplateObject); /** * The definition of this function is necessary to fulfill * the interface of the MetaDataObjectBase * \author Hans J. Johnson * \return A pointer to a const char array containing the unique type name. */ - virtual const char * GetMetaDataObjectTypeName(void) const; + virtual const char * GetMetaDataObjectTypeName() const ITK_OVERRIDE; /** * The definition of this function is necessary to fulfill @@ -119,32 +99,35 @@ public: * \author Hans J. Johnson * \return A constant reference to a std::type_info object */ - virtual const std::type_info & GetMetaDataObjectTypeInfo(void) const; + virtual const std::type_info & GetMetaDataObjectTypeInfo() const ITK_OVERRIDE; /** * Function to return the stored value of type MetaDataObjectType. * \author Hans J. Johnson * \return a constant reference to a MetaDataObjectType */ - const MetaDataObjectType & GetMetaDataObjectValue(void) const; + const MetaDataObjectType & GetMetaDataObjectValue() const; /** * Function to set the stored value of type MetaDataObjectType. * \author Hans J. Johnson - * \param NewValue A constant reference to at MetaDataObjectType. + * \param newValue A constant reference to at MetaDataObjectType. */ - void SetMetaDataObjectValue(const MetaDataObjectType & NewValue); + void SetMetaDataObjectValue(const MetaDataObjectType & newValue); /** * Defines the default behavior for printing out this element * \param os An output stream */ - virtual void Print(std::ostream & os) const; + virtual void Print(std::ostream & os) const ITK_OVERRIDE; + +protected: + MetaDataObject(); + virtual ~MetaDataObject(); private: - // This is made private to force the use of the - // MetaDataObject<MetaDataObjectType>::New() operator! - //void * operator new(SizeValueType nothing) {};//purposefully not implemented + MetaDataObject(const Self &); // purposely not implemented + void operator=(const Self &); // purposely not implemented /** * A variable to store this derived type. @@ -195,47 +178,68 @@ inline bool ExposeMetaData(const MetaDataDictionary & Dictionary, const std::str const MetaDataObjectBase::ConstPointer baseObjectSmartPointer = Dictionary[key]; - if ( baseObjectSmartPointer.IsNull() || strcmp( typeid( T ).name(), baseObjectSmartPointer->GetMetaDataObjectTypeName() ) != 0 ) + MetaDataObject< T > const * const TempMetaDataObject = dynamic_cast< MetaDataObject< T > const * >( baseObjectSmartPointer.GetPointer() ); + if ( TempMetaDataObject == ITK_NULLPTR ) { return false; } - { - MetaDataObject< T > const * const TempMetaDataObject = dynamic_cast< MetaDataObject< T > const * >( baseObjectSmartPointer.GetPointer() ); - if ( TempMetaDataObject != NULL ) - { - outval = TempMetaDataObject->GetMetaDataObjectValue(); - } - else - { - return false; - } - } + + outval = TempMetaDataObject->GetMetaDataObjectValue(); return true; } + +#ifndef ITK_TEMPLATE_EXPLICIT_MetaDataObject +// Explicit instantiation is required to ensure correct dynamic_cast +// behavior across shared libraries. +#if defined( ITKCommon_EXPORTS ) +// don't use export +#define ITKCommon_EXPORT_EXPLICIT +#else +// only import/hidden +#define ITKCommon_EXPORT_EXPLICIT ITKCommon_EXPORT +#endif +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< bool >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< unsigned char >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< char >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< signed char >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< unsigned short >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< short >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< unsigned int >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< int >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< unsigned long >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< long >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< float >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< double >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< std::string >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< std::vector<float> >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< std::vector<double> >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< std::vector<std::vector<float> > >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< std::vector<std::vector<double> > >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< Array<char> >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< Array<int> >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< Array<float> >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< Array<double> >; +extern template class ITKCommon_EXPORT_EXPLICIT MetaDataObject< Matrix<double> >; +#undef ITKCommon_EXPORT_EXPLICIT +#endif + } // end namespace itk /** - * \def NATIVE_TYPE_METADATAPRINT( TYPE_NAME ) + * \def ITK_NATIVE_TYPE_METADATAPRINT( TYPE_NAME ) * \brief An ugly macro to facilitate creating a simple implementation of * the MetaDataObject<Type>::Print() function for types that * have operator<< defined. * \param TYPE_NAME the native type parameter type */ -#define NATIVE_TYPE_METADATAPRINT(TYPE_NAME) \ +#define ITK_NATIVE_TYPE_METADATAPRINT(TYPE_NAME) \ template< > \ void \ - itk::MetaDataObject< TYPE_NAME > \ + ::itk::MetaDataObject< TYPE_NAME > \ ::Print(std::ostream & os) const \ { \ os << this->m_MetaDataObjectValue << std::endl; \ } \ - template< > \ - void \ - itk::MetaDataObject< const TYPE_NAME > \ - ::Print(std::ostream & os) const \ - { \ - os << this->m_MetaDataObjectValue << std::endl; \ - } /** * \def ITK_OBJECT_TYPE_METADATAPRINT_1COMMA( TYPE_NAME_PART1, TYPE_NAME_PART2 ) @@ -253,13 +257,6 @@ inline bool ExposeMetaData(const MetaDataDictionary & Dictionary, const std::str { \ this->m_MetaDataObjectValue->Print(os); \ } \ - template< > \ - void \ - itk::MetaDataObject< const TYPE_NAME_PART1, TYPE_NAME_PART2 > \ - ::Print(std::ostream & os) const \ - { \ - this->m_MetaDataObjectValue->Print(os); \ - } /** * \def ITK_IMAGE_TYPE_METADATAPRINT( STORAGE_TYPE ) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObject.hxx b/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObject.hxx index 9554055aab0036fab2b0e3aedfe0ca3d74608047..1290b8e27c5d49118943b1ff7bec9ccb4a552075 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObject.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObject.hxx @@ -32,40 +32,24 @@ namespace itk { -template< typename MetaDataObjectType > -MetaDataObject< MetaDataObjectType > -::MetaDataObject(void) -{ - //Nothing to do, m_MetaDataObjectValue takes this types default value. -} - -template< typename MetaDataObjectType > -MetaDataObject< MetaDataObjectType > -::~MetaDataObject(void) -{ - //Nothing to do here. -} template< typename MetaDataObjectType > MetaDataObject< MetaDataObjectType > -::MetaDataObject(const MetaDataObjectType InitializerValue): - m_MetaDataObjectValue(InitializerValue) +::MetaDataObject() { - //Nothing to be done here + // m_MetaDataObjectValue takes this types default value. } template< typename MetaDataObjectType > MetaDataObject< MetaDataObjectType > -::MetaDataObject(const MetaDataObject< MetaDataObjectType > & TemplateObject): - Superclass(), m_MetaDataObjectValue(TemplateObject.m_MetaDataObjectValue) +::~MetaDataObject() { - //Nothing to be done here } template< typename MetaDataObjectType > const char * MetaDataObject< MetaDataObjectType > -::GetMetaDataObjectTypeName(void) const +::GetMetaDataObjectTypeName() const { return typeid( MetaDataObjectType ).name(); } @@ -73,7 +57,7 @@ MetaDataObject< MetaDataObjectType > template< typename MetaDataObjectType > const std::type_info & MetaDataObject< MetaDataObjectType > -::GetMetaDataObjectTypeInfo(void) const +::GetMetaDataObjectTypeInfo() const { return typeid( MetaDataObjectType ); } @@ -81,7 +65,7 @@ MetaDataObject< MetaDataObjectType > template< typename MetaDataObjectType > const MetaDataObjectType & MetaDataObject< MetaDataObjectType > -::GetMetaDataObjectValue(void) const +::GetMetaDataObjectValue() const { return m_MetaDataObjectValue; } @@ -89,9 +73,9 @@ MetaDataObject< MetaDataObjectType > template< typename MetaDataObjectType > void MetaDataObject< MetaDataObjectType > -::SetMetaDataObjectValue(const MetaDataObjectType & NewValue) +::SetMetaDataObjectValue(const MetaDataObjectType & newValue) { - m_MetaDataObjectValue = NewValue; + m_MetaDataObjectValue = newValue; } template< typename MetaDataObjectType > @@ -101,6 +85,7 @@ MetaDataObject< MetaDataObjectType > { Superclass::Print(os); } + } // end namespace itk #endif diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObjectBase.h b/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObjectBase.h index da4476ad4f043929da65bb0f44404857f5ef3950..0ab5995e3432d31377aa1bffedb73c7013dad6c2 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObjectBase.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMetaDataObjectBase.h @@ -44,7 +44,7 @@ namespace itk * \author Hans J. Johnson * \ingroup ITKCommon */ -class ITKCommon_EXPORT MetaDataObjectBase:public LightObject +class ITKCommon_EXPORT MetaDataObjectBase: public LightObject { public: /** Smart pointer typedef support. */ @@ -60,32 +60,25 @@ public: * \author Hans J. Johnson * \return A pointer to a const char array containing the unique type name. */ - virtual const char * GetMetaDataObjectTypeName(void) const; + virtual const char * GetMetaDataObjectTypeName() const; /** * \author Hans J. Johnson * \return A constant reference to a std::type_info object */ - virtual const std::type_info & GetMetaDataObjectTypeInfo(void) const; + virtual const std::type_info & GetMetaDataObjectTypeInfo() const; /** * Defines the default behavior for printing out this element * \param os An output stream */ - virtual void Print(std::ostream & os) const; + virtual void Print( std::ostream & os ) const; protected: - /** Method for creation through the object factory. */ - // Should not be able to construct a new MetaDataObjectBase -// static Pointer New(void); -/** - * Default destructor - */ - virtual ~MetaDataObjectBase(); MetaDataObjectBase(); + virtual ~MetaDataObjectBase(); private: - //void * operator new(size_t nothing) {};//purposefully not implemented MetaDataObjectBase(const Self &); //purposely not implemented void operator=(const Self &); //purposely not implemented }; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMinimumMaximumImageCalculator.h b/Utilities/ITK/Modules/Core/Common/include/itkMinimumMaximumImageCalculator.h index 45d5ea458dab8bece81c3969dabbb44697830d8a..64c594ac91504f3da2caa8c488d82ee54e4009f5 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMinimumMaximumImageCalculator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMinimumMaximumImageCalculator.h @@ -104,7 +104,7 @@ public: protected: MinimumMaximumImageCalculator(); virtual ~MinimumMaximumImageCalculator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: MinimumMaximumImageCalculator(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMinimumMaximumImageCalculator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkMinimumMaximumImageCalculator.hxx index fae3dcb6408ef7dc7ef12a23bb87d41a3e1d0a3f..8978b279902dd3e5db56a26fbad248527065742b 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMinimumMaximumImageCalculator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkMinimumMaximumImageCalculator.hxx @@ -151,8 +151,7 @@ MinimumMaximumImageCalculator< TInputImage > << std::endl; os << indent << "Index of Minimum: " << m_IndexOfMinimum << std::endl; os << indent << "Index of Maximum: " << m_IndexOfMaximum << std::endl; - os << indent << "Image: " << std::endl; - m_Image->Print( os, indent.GetNextIndent() ); + itkPrintSelfObjectMacro( Image ); os << indent << "Region: " << std::endl; m_Region.Print( os, indent.GetNextIndent() ); os << indent << "Region set by User: " << m_RegionSetByUser << std::endl; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMultiThreader.h b/Utilities/ITK/Modules/Core/Common/include/itkMultiThreader.h index abdec58bc0cde9d664468113b8b65c8dd057e412..e5589fba3c0a5ce994b03ec6ff3d216c236864d5 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMultiThreader.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMultiThreader.h @@ -147,7 +147,7 @@ public: protected: MultiThreader(); ~MultiThreader(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: MultiThreader(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMultipleLogOutput.h b/Utilities/ITK/Modules/Core/Common/include/itkMultipleLogOutput.h index 7db2e55001bf8cac1638c360cb3a59d2eb2184b9..b49e277d25e20f0a801f8a2e684e51475e34a4d2 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMultipleLogOutput.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMultipleLogOutput.h @@ -59,16 +59,16 @@ public: void AddLogOutput(OutputType *output); /** Broadcast a flush operation to all the output streams */ - virtual void Flush(); + virtual void Flush() ITK_OVERRIDE; /** Write to multiple outputs */ - virtual void Write(double timestamp); + virtual void Write(double timestamp) ITK_OVERRIDE; /** Write to multiple outputs */ - virtual void Write(const std::string & content); + virtual void Write(const std::string & content) ITK_OVERRIDE; /** Write to a buffer */ - virtual void Write(const std::string & content, double timestamp); + virtual void Write(const std::string & content, double timestamp) ITK_OVERRIDE; protected: /** Constructor */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkMutexLock.h b/Utilities/ITK/Modules/Core/Common/include/itkMutexLock.h index ba5d4fa1261661ed9d433e5c907912ac891fd022..1c412421cca5aa6015c777d12e7bc46034087fd5 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkMutexLock.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkMutexLock.h @@ -120,7 +120,7 @@ protected: ~MutexLock() {} SimpleMutexLock m_SimpleMutexLock; - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: MutexLock(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkNeighborhoodAllocator.h b/Utilities/ITK/Modules/Core/Common/include/itkNeighborhoodAllocator.h index 6bf63b2249241a989451b77505baa1e70002818d..808d889cbded0477f4e828c759f89c9ddedede01 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkNeighborhoodAllocator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkNeighborhoodAllocator.h @@ -18,6 +18,7 @@ #ifndef __itkNeighborhoodAllocator_h #define __itkNeighborhoodAllocator_h #include <iostream> +#include "itkMacro.h" namespace itk { @@ -51,7 +52,7 @@ public: typedef const TPixel * const_iterator; /** Default constructor */ - NeighborhoodAllocator():m_ElementCount(0), m_Data(0) {} + NeighborhoodAllocator():m_ElementCount(0), m_Data(ITK_NULLPTR) {} /** Default destructor */ ~NeighborhoodAllocator() diff --git a/Utilities/ITK/Modules/Core/Common/include/itkNeighborhoodIterator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkNeighborhoodIterator.hxx index 893d9115ffd3b34b26923d450bf8efa16594f992..e2c7c1c3353279591a7209256f270316216a0813 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkNeighborhoodIterator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkNeighborhoodIterator.hxx @@ -99,8 +99,8 @@ void NeighborhoodIterator< TImage, TBoundaryCondition > ::SetPixel(const unsigned n, const PixelType & v, bool & status) { - register unsigned int i; - OffsetType temp; + unsigned int i; + OffsetType temp; typename OffsetType::OffsetValueType OverlapLow, OverlapHigh; @@ -161,9 +161,9 @@ void NeighborhoodIterator< TImage, TBoundaryCondition > ::SetNeighborhood(const NeighborhoodType & N) { - register unsigned int i; - OffsetType OverlapLow, OverlapHigh, temp; - bool flag; + unsigned int i; + OffsetType OverlapLow, OverlapHigh, temp; + bool flag; const Iterator _end = this->End(); Iterator this_it; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkNumberToString.h b/Utilities/ITK/Modules/Core/Common/include/itkNumberToString.h index e95e939891cd3c78975663dda00a097cad75f5f6..9d00b289926641ef01da088ea2363050442b08d4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkNumberToString.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkNumberToString.h @@ -39,7 +39,7 @@ namespace itk * * \ingroup ITKCommon */ -template< typename TValueType> +template< typename TValue> class NumberToString { public: @@ -47,7 +47,7 @@ public: m_DoubleToStringConverter(double_conversion::DoubleToStringConverter::EcmaScriptConverter()) { } - std::string operator() (TValueType val); + std::string operator() (TValue val); private: NumberToString & operator=(const NumberToString &); // not defined diff --git a/Utilities/ITK/Modules/Core/Common/include/itkNumberToString.hxx b/Utilities/ITK/Modules/Core/Common/include/itkNumberToString.hxx index 9a35941f0a2fe5eb247c3623eb35d8dd78c6c1cc..337e0a4c6486c9b1b7b5d087b10d808ae8c45e3c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkNumberToString.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkNumberToString.hxx @@ -26,11 +26,11 @@ namespace itk { -template<typename TValueType> -std::string NumberToString<TValueType>::operator() (TValueType val) +template<typename TValue> +std::string NumberToString<TValue>::operator() (TValue val) { std::ostringstream output; - output << static_cast<typename NumericTraits<TValueType>::PrintType>(val); + output << static_cast<typename NumericTraits<TValue>::PrintType>(val); return output.str(); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkNumericTraits.h b/Utilities/ITK/Modules/Core/Common/include/itkNumericTraits.h index c20d3e6470de6440799e25f4f6434ce63ef9d905..64bea4b2481d0d501e911a4b24c53159a3942259 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkNumericTraits.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkNumericTraits.h @@ -26,30 +26,30 @@ #define itkNUMERIC_TRAITS_MIN_MAX_MACRO() \ static ValueType min() \ { \ - return vcl_numeric_limits< ValueType >::min(); \ + return std::numeric_limits< ValueType >::min(); \ } \ static ValueType max() \ { \ - return vcl_numeric_limits< ValueType >::max(); \ + return std::numeric_limits< ValueType >::max(); \ } \ static ValueType min(ValueType) \ { \ - return vcl_numeric_limits< ValueType >::min(); \ + return std::numeric_limits< ValueType >::min(); \ } \ static ValueType max(ValueType) \ { \ - return vcl_numeric_limits< ValueType >::max(); \ + return std::numeric_limits< ValueType >::max(); \ } \ -#include "vcl_limits.h" // for vcl_numeric_limits +#include "vcl_limits.h" // for std::numeric_limits #include <complex> namespace itk { // forward decare to avoid circular dependencies -template< typename TValueType, unsigned int VLength> class FixedArray; +template< typename TValue, unsigned int VLength> class FixedArray; /** \class NumericTraits * \brief Define additional traits for native types such as int or float. @@ -67,11 +67,11 @@ template< typename TValueType, unsigned int VLength> class FixedArray; * \endwiki */ template< typename T > -class NumericTraits:public vcl_numeric_limits< T > +class NumericTraits:public std::numeric_limits< T > { public: /** The type of this limits trait object. */ - typedef vcl_numeric_limits< T > TraitsType; + typedef std::numeric_limits< T > TraitsType; /** Return the type of this native type. */ typedef T ValueType; @@ -79,7 +79,7 @@ public: /** Return the type that can be printed. */ typedef T PrintType; - /** Return value of vcl_abs(). */ + /** Return value of std::abs(). */ typedef T AbsType; /** Accumulation of addition and multiplication. */ @@ -142,12 +142,13 @@ public: * VariableLengthVector will provide a different implementation * where a vector of the correct size is built. */ - static void SetLength(T &, const unsigned int s) + static void SetLength(T & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } /** Return the length of the scalar. This API is needed for * VariableLengthVector because @@ -209,7 +210,7 @@ public: */ template< > -class NumericTraits< bool > :public vcl_numeric_limits< bool > +class NumericTraits< bool > :public std::numeric_limits< bool > { public: typedef bool ValueType; @@ -246,12 +247,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -262,7 +264,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< char > :public vcl_numeric_limits< char > +class NumericTraits< char > :public std::numeric_limits< char > { public: typedef char ValueType; @@ -300,12 +302,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -315,7 +318,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< signed char > :public vcl_numeric_limits< signed char > +class NumericTraits< signed char > :public std::numeric_limits< signed char > { public: typedef signed char ValueType; @@ -352,12 +355,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -367,7 +371,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< unsigned char > :public vcl_numeric_limits< unsigned char > +class NumericTraits< unsigned char > :public std::numeric_limits< unsigned char > { public: typedef unsigned char ValueType; @@ -384,7 +388,7 @@ public: itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static unsigned char NonpositiveMin() { return vcl_numeric_limits< ValueType >::min(); } + static unsigned char NonpositiveMin() { return std::numeric_limits< ValueType >::min(); } static bool IsPositive(unsigned char val) { return val != Zero; } static bool IsNonpositive(unsigned char val) { return val == Zero; } static bool IsNegative(unsigned char val) { return val ? false : false; } @@ -402,12 +406,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -416,7 +421,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< short > :public vcl_numeric_limits< short > +class NumericTraits< short > :public std::numeric_limits< short > { public: typedef short ValueType; @@ -432,7 +437,7 @@ public: static const short ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static short NonpositiveMin() { return vcl_numeric_limits< ValueType >::min(); } + static short NonpositiveMin() { return std::numeric_limits< ValueType >::min(); } static bool IsPositive(short val) { return val > Zero; } static bool IsNonpositive(short val) { return val <= Zero; } static bool IsNegative(short val) { return val < Zero; } @@ -450,12 +455,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -465,7 +471,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< unsigned short > :public vcl_numeric_limits< unsigned short > +class NumericTraits< unsigned short > :public std::numeric_limits< unsigned short > { public: typedef unsigned short ValueType; @@ -481,7 +487,7 @@ public: static const unsigned short ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static unsigned short NonpositiveMin() { return vcl_numeric_limits< ValueType >::min(); } + static unsigned short NonpositiveMin() { return std::numeric_limits< ValueType >::min(); } static bool IsPositive(unsigned short val) { return val != Zero; } static bool IsNonpositive(unsigned short val) { return val == Zero; } static bool IsNegative(unsigned short val) { return val ? false : false; } @@ -499,12 +505,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -513,7 +520,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< int > :public vcl_numeric_limits< int > +class NumericTraits< int > :public std::numeric_limits< int > { public: typedef int ValueType; @@ -529,7 +536,7 @@ public: static const int ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static int NonpositiveMin() { return vcl_numeric_limits< ValueType >::min(); } + static int NonpositiveMin() { return std::numeric_limits< ValueType >::min(); } static bool IsPositive(int val) { return val > Zero; } static bool IsNonpositive(int val) { return val <= Zero; } static bool IsNegative(int val) { return val < Zero; } @@ -547,12 +554,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -562,7 +570,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< unsigned int > :public vcl_numeric_limits< unsigned int > +class NumericTraits< unsigned int > :public std::numeric_limits< unsigned int > { public: typedef unsigned int ValueType; @@ -579,8 +587,8 @@ public: static unsigned int min(void) { return 0; } static unsigned int max(void) { return static_cast< unsigned int >( -1 ); } - static unsigned int min(unsigned int) { return vcl_numeric_limits< ValueType >::min(); } - static unsigned int max(unsigned int) { return vcl_numeric_limits< ValueType >::max(); } + static unsigned int min(unsigned int) { return std::numeric_limits< ValueType >::min(); } + static unsigned int max(unsigned int) { return std::numeric_limits< ValueType >::max(); } static unsigned int NonpositiveMin() { return 0; } static bool IsPositive(unsigned int val) { return val != Zero; } static bool IsNonpositive(unsigned int val) { return val == Zero; } @@ -599,12 +607,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -614,7 +623,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< long > :public vcl_numeric_limits< long > +class NumericTraits< long > :public std::numeric_limits< long > { public: typedef long ValueType; @@ -630,7 +639,7 @@ public: static const long ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static long NonpositiveMin() { return vcl_numeric_limits< ValueType >::min(); } + static long NonpositiveMin() { return std::numeric_limits< ValueType >::min(); } static bool IsPositive(long val) { return val > Zero; } static bool IsNonpositive(long val) { return val <= Zero; } static bool IsNegative(long val) { return val < Zero; } @@ -648,12 +657,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -663,7 +673,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< unsigned long > :public vcl_numeric_limits< unsigned long > +class NumericTraits< unsigned long > :public std::numeric_limits< unsigned long > { public: typedef unsigned long ValueType; @@ -679,7 +689,7 @@ public: static const unsigned long ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static unsigned long NonpositiveMin() { return vcl_numeric_limits< ValueType >::min(); } + static unsigned long NonpositiveMin() { return std::numeric_limits< ValueType >::min(); } static bool IsPositive(unsigned long val) { return val != Zero; } static bool IsNonpositive(unsigned long val) { return val == Zero; } static bool IsNegative(unsigned long) { return false; } @@ -697,12 +707,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -712,7 +723,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< float > :public vcl_numeric_limits< float > +class NumericTraits< float > :public std::numeric_limits< float > { public: typedef float ValueType; @@ -728,7 +739,7 @@ public: static const float ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static float NonpositiveMin() { return -vcl_numeric_limits< ValueType >::max(); } + static float NonpositiveMin() { return -std::numeric_limits< ValueType >::max(); } static bool IsPositive(float val) { return val > Zero; } static bool IsNonpositive(float val) { return val <= Zero; } static bool IsNegative(float val) { return val < Zero; } @@ -746,12 +757,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -761,7 +773,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< double > :public vcl_numeric_limits< double > +class NumericTraits< double > :public std::numeric_limits< double > { public: typedef double ValueType; @@ -777,7 +789,7 @@ public: static const double ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static double NonpositiveMin() { return -vcl_numeric_limits< ValueType >::max(); } + static double NonpositiveMin() { return -std::numeric_limits< ValueType >::max(); } static bool IsPositive(double val) { return val > Zero; } static bool IsNonpositive(double val) { return val <= Zero; } static bool IsNegative(double val) { return val < Zero; } @@ -795,12 +807,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -810,7 +823,7 @@ public: * \ingroup ITKCommon */ template< > -class NumericTraits< long double > :public vcl_numeric_limits< long double > +class NumericTraits< long double > :public std::numeric_limits< long double > { public: typedef long double ValueType; @@ -834,7 +847,7 @@ public: static const long double ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static long double NonpositiveMin() { return -vcl_numeric_limits< ValueType >::max(); } + static long double NonpositiveMin() { return -std::numeric_limits< ValueType >::max(); } static bool IsPositive(long double val) { return val > Zero; } static bool IsNonpositive(long double val) { return val <= Zero; } static bool IsNegative(long double val) { return val < Zero; } @@ -852,12 +865,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -885,8 +899,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -911,12 +925,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -944,8 +959,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -970,12 +985,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1003,8 +1019,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1029,12 +1045,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1062,8 +1079,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1088,12 +1105,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1121,8 +1139,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1147,12 +1165,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1180,8 +1199,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1206,12 +1225,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1239,8 +1259,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1265,12 +1285,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1298,8 +1319,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1324,12 +1345,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1357,8 +1379,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< Self >::min(); } - static Self max() { return vcl_numeric_limits< Self >::max(); } + static Self min() { return std::numeric_limits< Self >::min(); } + static Self max() { return std::numeric_limits< Self >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1383,12 +1405,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1416,8 +1439,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< ValueType >::min(); } - static Self max() { return vcl_numeric_limits< ValueType >::max(); } + static Self min() { return std::numeric_limits< ValueType >::min(); } + static Self max() { return std::numeric_limits< ValueType >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1442,12 +1465,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1475,8 +1499,8 @@ public: static const Self ITKCommon_EXPORT Zero; static const Self ITKCommon_EXPORT One; - static Self min() { return vcl_numeric_limits< ValueType >::min(); } - static Self max() { return vcl_numeric_limits< ValueType >::max(); } + static Self min() { return std::numeric_limits< ValueType >::min(); } + static Self max() { return std::numeric_limits< ValueType >::max(); } static Self min(Self) { return min(); } static Self max(Self) { return max(); } static Self NonpositiveMin() @@ -1501,12 +1525,13 @@ public: mv[0] = v.real(); mv[1] = v.imag(); } - static void SetLength(Self &, const unsigned int s) + static void SetLength(Self & m, const unsigned int s) { if ( s != 2 ) { itkGenericExceptionMacro(<< "Cannot set the size of a complex to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1517,7 +1542,7 @@ public: */ template< > class NumericTraits< long long > : - public vcl_numeric_limits< long long > + public std::numeric_limits< long long > { public: typedef long long ValueType; @@ -1533,7 +1558,7 @@ public: static const ValueType ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static ValueType NonpositiveMin() { return vcl_numeric_limits< ValueType >::min(); } + static ValueType NonpositiveMin() { return std::numeric_limits< ValueType >::min(); } static bool IsPositive(ValueType val) { return val > Zero; } static bool IsNonpositive(ValueType val) { return val <= Zero; } static bool IsNegative(ValueType val) { return val < Zero; } @@ -1551,12 +1576,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; @@ -1567,7 +1593,7 @@ public: */ template< > class NumericTraits< unsigned long long > : - public vcl_numeric_limits< unsigned long long > + public std::numeric_limits< unsigned long long > { public: typedef unsigned long long ValueType; @@ -1583,7 +1609,7 @@ public: static const ValueType ITKCommon_EXPORT One; itkNUMERIC_TRAITS_MIN_MAX_MACRO(); - static ValueType NonpositiveMin() { return vcl_numeric_limits< ValueType >::min(); } + static ValueType NonpositiveMin() { return std::numeric_limits< ValueType >::min(); } static bool IsPositive(ValueType val) { return val != Zero; } static bool IsNonpositive(ValueType val) { return val == Zero; } static bool IsNegative(ValueType) { return false; } @@ -1601,12 +1627,13 @@ public: { mv[0] = v; } - static void SetLength(ValueType &, const unsigned int s) + static void SetLength(ValueType & m, const unsigned int s) { if ( s != 1 ) { itkGenericExceptionMacro(<< "Cannot set the size of a scalar to " << s); } + m = NumericTraits< ValueType >::Zero; } }; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkNumericTraitsFixedArrayPixel.h b/Utilities/ITK/Modules/Core/Common/include/itkNumericTraitsFixedArrayPixel.h index 7420968dbd8a4d97cf28c6339a64acb21c1bdfe6..1db158e8800fb156b8ae1cb491ac6020f2a6b296 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkNumericTraitsFixedArrayPixel.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkNumericTraitsFixedArrayPixel.h @@ -184,10 +184,10 @@ public: // a macro to define and initialize static member variables #define itkStaticNumericTraitsGenericArrayMacro(GENERIC_ARRAY, T, D) \ template< > \ - const GENERIC_ARRAY< T, D > NumericTraits< GENERIC_ARRAY< T, D > >::Zero = GENERIC_ARRAY< T, D >( \ + ITKCommon_EXPORT const GENERIC_ARRAY< T, D > NumericTraits< GENERIC_ARRAY< T, D > >::Zero = GENERIC_ARRAY< T, D >( \ NumericTraits< T >::Zero); \ template< > \ - const GENERIC_ARRAY< T, D > NumericTraits< GENERIC_ARRAY< T, D > >::One = GENERIC_ARRAY< T, D >( \ + ITKCommon_EXPORT const GENERIC_ARRAY< T, D > NumericTraits< GENERIC_ARRAY< T, D > >::One = GENERIC_ARRAY< T, D >( \ NumericTraits< T >::One); // diff --git a/Utilities/ITK/Modules/Core/Common/include/itkNumericTraitsStdVector.h b/Utilities/ITK/Modules/Core/Common/include/itkNumericTraitsStdVector.h index 8929379eca64521dbb59a268c61ba2ff908f6373..682edf8dd82a66371db9a6d682949fa0513e0ab8 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkNumericTraitsStdVector.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkNumericTraitsStdVector.h @@ -130,6 +130,9 @@ public: /** Resize the input vector to the specified size */ static void SetLength(std::vector< T > & m, const unsigned int s) { + // since std::vector often holds types that have no NumericTraits::Zero, + // allow resize() to call the type's default constructor + m.clear(); m.resize(s); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkObject.h b/Utilities/ITK/Modules/Core/Common/include/itkObject.h index 550452655bbb3e3f8ab335e7fe131bca1f948604..fe0f158452ca3526a1e57b922a792ef334b15512 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkObject.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkObject.h @@ -71,7 +71,7 @@ public: * object that is exactly the same type as the referring object. * This is useful in cases where an object has been cast back to a * base class. */ - virtual LightObject::Pointer CreateAnother() const; + virtual LightObject::Pointer CreateAnother() const ITK_OVERRIDE; /** Standard part of all itk objects. */ itkTypeMacro(Object, LightObject); @@ -99,13 +99,13 @@ public: virtual void Modified() const; /** Increase the reference count (mark as used by another object). */ - virtual void Register() const; + virtual void Register() const ITK_OVERRIDE; /** Decrease the reference count (release by another object). */ - virtual void UnRegister() const; + virtual void UnRegister() const ITK_OVERRIDE; /** Sets the reference count (use with care) */ - virtual void SetReferenceCount(int); + virtual void SetReferenceCount(int) ITK_OVERRIDE; /** This is a global flag that controls whether any debug, warning * or error messages are displayed. */ @@ -187,7 +187,7 @@ protected: * including superclasses. Typically not called by the user (use Print() * instead) but used in the hierarchical print process to combine the * output of several classes. */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; bool PrintObservers(std::ostream & os, Indent indent) const; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkObjectFactoryBase.h b/Utilities/ITK/Modules/Core/Common/include/itkObjectFactoryBase.h index 5151fa129d73ad6f1d1d555789e8a4457df81943..5e6936c25945d544504b554f1d4bdf1f49a05a57 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkObjectFactoryBase.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkObjectFactoryBase.h @@ -195,7 +195,7 @@ public: }; protected: - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Register object creation information with the factory. */ void RegisterOverride(const char *classOverride, diff --git a/Utilities/ITK/Modules/Core/Common/include/itkObjectStore.h b/Utilities/ITK/Modules/Core/Common/include/itkObjectStore.h index 4f2bf1ef7189535ed8de764f5b22d93f6da4035c..2e9d195ad10dc3dc18383e06a85881ea6d8ca908 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkObjectStore.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkObjectStore.h @@ -127,7 +127,7 @@ public: protected: ObjectStore(); ~ObjectStore(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Returns a new size to grow. */ SizeValueType GetGrowthSize(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkOctree.h b/Utilities/ITK/Modules/Core/Common/include/itkOctree.h index bc1e4435bcc9afe2fa15e799ad059bf23721a763..bdabce2e15642fe14397be86af41dc2bd12bbdb4 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkOctree.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkOctree.h @@ -128,7 +128,7 @@ public: ImageTypePointer GetImage(); - virtual void BuildFromBuffer(const void *buffer, const unsigned int xsize, const unsigned int ysize, const unsigned int zsize); + virtual void BuildFromBuffer(const void *buffer, const unsigned int xsize, const unsigned int ysize, const unsigned int zsize) ITK_OVERRIDE; void BuildFromImage(Image< TPixel, 3 > *fromImage); @@ -142,19 +142,19 @@ public: int GetValue(const unsigned int Dim0, const unsigned int Dim1, const unsigned int Dim2); - virtual void SetWidth(unsigned int width); + virtual void SetWidth(unsigned int width) ITK_OVERRIDE; - virtual void SetDepth(unsigned int depth); + virtual void SetDepth(unsigned int depth) ITK_OVERRIDE; - virtual unsigned int GetWidth(); + virtual unsigned int GetWidth() ITK_OVERRIDE; - virtual unsigned int GetDepth(); + virtual unsigned int GetDepth() ITK_OVERRIDE; - virtual OctreeNode * GetTree(); + virtual OctreeNode * GetTree() ITK_OVERRIDE; - virtual const char * GetColorTable() const; + virtual const char * GetColorTable() const ITK_OVERRIDE; - virtual int GetColorTableSize() const; + virtual int GetColorTableSize() const ITK_OVERRIDE; private: Octree(const Self &); // purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParameters.h b/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParameters.h index 4ab9cb5371f2cee99e88528b3a0b27a6c8f23fe8..a54d11c45d9a180773ea641072d8b1bc6fb03fa7 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParameters.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParameters.h @@ -30,22 +30,22 @@ namespace itk * \ingroup ITKCommon */ -template< typename TValueType > -class OptimizerParameters : public Array< TValueType > +template< typename TValue > +class OptimizerParameters : public Array< TValue > { public: /** The element type stored at each location in the Array. */ - typedef TValueType ValueType; - typedef OptimizerParameters Self; - typedef Array< TValueType > Superclass; - typedef Superclass ArrayType; - typedef typename Superclass::VnlVectorType VnlVectorType; - typedef typename Superclass::SizeValueType SizeValueType; + typedef TValue ValueType; + typedef OptimizerParameters Self; + typedef Array< TValue > Superclass; + typedef Superclass ArrayType; + typedef typename Superclass::VnlVectorType VnlVectorType; + typedef typename Superclass::SizeValueType SizeValueType; /** Helper class for managing different types of parameter * data. */ - typedef OptimizerParametersHelper< TValueType > OptimizerParametersHelperType; + typedef OptimizerParametersHelper< TValue > OptimizerParametersHelperType; /** Default constructor. It is created with an empty array * it has to be allocated later by assignment */ @@ -69,10 +69,10 @@ public: /** Set a new data pointer for the parameter data, pointing it to a different * memory block. The size of the new memory block must equal the current - * size, in elements of TValueType. + * size, in elements of TValue. * This call is passed to the assigned OptimizerParametersHelper. * \warning Memory must be managed by caller after this call. */ - virtual void MoveDataPointer( TValueType * pointer ); + virtual void MoveDataPointer( TValue * pointer ); /** Set an object that holds the parameters. Used by the helper of * derived classes that use an object other than itkArray to hold parameter diff --git a/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParameters.hxx b/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParameters.hxx index ea92a9b295430e4d24c7a175551492afdff72c2d..25ff6de81f10e30805a70751bfdb9f303ca1289b 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParameters.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParameters.hxx @@ -24,18 +24,18 @@ namespace itk { /** Default contstructor */ -template< typename TValueType > -OptimizerParameters< TValueType > -::OptimizerParameters() : Array< TValueType >() +template< typename TValue > +OptimizerParameters< TValue > +::OptimizerParameters() : Array< TValue >() { this->Initialize(); } /** Copy constructor */ -template< typename TValueType > -OptimizerParameters< TValueType > +template< typename TValue > +OptimizerParameters< TValue > ::OptimizerParameters(const OptimizerParameters& rhs) - : Array< TValueType >(rhs) + : Array< TValue >(rhs) { //Note: don't copy the OptimizerParametersHelper. //The Array copy constructor will allocate new memory @@ -46,29 +46,29 @@ OptimizerParameters< TValueType > } /** Constructor with size */ -template< typename TValueType > -OptimizerParameters< TValueType > +template< typename TValue > +OptimizerParameters< TValue > ::OptimizerParameters(SizeValueType dimension) - : Array< TValueType >(dimension) + : Array< TValue >(dimension) { this->Initialize(); } /** Constructor with Array assignment */ -template< typename TValueType > -OptimizerParameters< TValueType > +template< typename TValue > +OptimizerParameters< TValue > ::OptimizerParameters(const ArrayType& array) - : Array< TValueType >(array) + : Array< TValue >(array) { this->Initialize(); } -template< typename TValueType > +template< typename TValue > void -OptimizerParameters< TValueType > +OptimizerParameters< TValue > ::Initialize() { - this->m_Helper = NULL; + this->m_Helper = ITK_NULLPTR; // Set the default OptimizerParametersHelper OptimizerParametersHelperType* helper = new OptimizerParametersHelperType; // OptimizerParameters will manage this memory. @@ -76,16 +76,16 @@ OptimizerParameters< TValueType > } /** Destructor */ -template< typename TValueType > -OptimizerParameters< TValueType > +template< typename TValue > +OptimizerParameters< TValue > ::~OptimizerParameters() { delete this->m_Helper; } -template< typename TValueType > +template< typename TValue > void -OptimizerParameters< TValueType > +OptimizerParameters< TValue > ::SetHelper( OptimizerParametersHelperType* helper ) { delete this->m_Helper; @@ -93,10 +93,10 @@ OptimizerParameters< TValueType > } /** Copy operator for self */ -template< typename TValueType > -const typename OptimizerParameters< TValueType > +template< typename TValue > +const typename OptimizerParameters< TValue > ::Self & -OptimizerParameters< TValueType > +OptimizerParameters< TValue > ::operator=(const Self & rhs) { //Note: there's no need to copy the OptimizerParametersHelper. @@ -105,10 +105,10 @@ OptimizerParameters< TValueType > return *this; } -template< typename TValueType > -const typename OptimizerParameters< TValueType > +template< typename TValue > +const typename OptimizerParameters< TValue > ::Self & -OptimizerParameters< TValueType > +OptimizerParameters< TValue > ::operator=(const ArrayType & rhs) { // Call the superclass implementation @@ -116,10 +116,10 @@ OptimizerParameters< TValueType > return *this; } -template< typename TValueType > -const typename OptimizerParameters< TValueType > +template< typename TValue > +const typename OptimizerParameters< TValue > ::Self & -OptimizerParameters< TValueType > +OptimizerParameters< TValue > ::operator=(const VnlVectorType & rhs) { // Call the superclass implementation @@ -127,12 +127,12 @@ OptimizerParameters< TValueType > return *this; } -template< typename TValueType > +template< typename TValue > void -OptimizerParameters< TValueType > -::MoveDataPointer( TValueType * pointer ) +OptimizerParameters< TValue > +::MoveDataPointer( TValue * pointer ) { - if( m_Helper == NULL ) + if( m_Helper == ITK_NULLPTR ) { itkGenericExceptionMacro("OptimizerParameters::MoveDataPointer: " "m_Helper must be set."); @@ -140,12 +140,12 @@ OptimizerParameters< TValueType > this->m_Helper->MoveDataPointer( this, pointer ); } -template< typename TValueType > +template< typename TValue > void -OptimizerParameters< TValueType > +OptimizerParameters< TValue > ::SetParametersObject( LightObject * object ) { - if( m_Helper == NULL ) + if( m_Helper == ITK_NULLPTR ) { itkGenericExceptionMacro("OptimizerParameters::SetParameterObject: " "m_Helper must be set."); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParametersHelper.h b/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParametersHelper.h index f7939f03f0b6872349387acbab1a57901e99ec75..79da61da7d83506991f7a7bf91feaf3ba2855dbe 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParametersHelper.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkOptimizerParametersHelper.h @@ -30,24 +30,24 @@ namespace itk * \ingroup ITKCommon */ -template< typename TValueType > +template< typename TValue > class OptimizerParametersHelper { public: /** The element type stored at each location in the Array. */ - typedef TValueType ValueType; - typedef OptimizerParametersHelper Self; + typedef TValue ValueType; + typedef OptimizerParametersHelper Self; /** Type of common data object used by OptimizerParameters. */ - typedef Array< TValueType > CommonContainerType; + typedef Array< TValue > CommonContainerType; /** Default constructor. Nothing to do. */ OptimizerParametersHelper(){} /** Set a new data pointer for the parameter data, pointing it to a different * memory block. The size of the new memory block must equal the current - * size, in elements of TValueType. + * size, in elements of TValue. * This call is passed to the assigned OptimizerParametersHelper. * \warning Memory must be managed by caller after this call. * \c container is the OptimizerParameters object to which this helper @@ -56,7 +56,7 @@ public: * which this helper is assigned. */ virtual void MoveDataPointer(CommonContainerType* container, - TValueType * pointer ) + TValue * pointer ) { container->SetData( pointer, container->GetSize(), false /*LetArrayManageMemory*/); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkOutputWindow.h b/Utilities/ITK/Modules/Core/Common/include/itkOutputWindow.h index 5d80c39af527202c963198cc4ad66df736b5f4bf..6813624a9b07290e32374ba25c2d8e5117fcc73d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkOutputWindow.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkOutputWindow.h @@ -100,7 +100,7 @@ public: protected: OutputWindow(); virtual ~OutputWindow(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: OutputWindow(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPhasedArray3DSpecialCoordinatesImage.h b/Utilities/ITK/Modules/Core/Common/include/itkPhasedArray3DSpecialCoordinatesImage.h index 3ad6424d31e4ee3bcfe5d868968ec186ef1baa6f..ae9d78d6e9e7ef2de69674b2aa1834acb010f25c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPhasedArray3DSpecialCoordinatesImage.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkPhasedArray3DSpecialCoordinatesImage.h @@ -55,13 +55,13 @@ namespace itk * * azimuth = arctan(x/y) * elevation = arctan(y/z) - * radius = vcl_sqrt(x^2 + y^2 + z^2) + * radius = std::sqrt(x^2 + y^2 + z^2) * * The reversed transforms are: * - * z = radius / vcl_sqrt(1 + (tan(azimuth))^2 + (tan(elevation))^2 ); - * x = z * vcl_tan(azimuth) - * y = z * vcl_tan(elevation) + * z = radius / std::sqrt(1 + (tan(azimuth))^2 + (tan(elevation))^2 ); + * x = z * std::tan(azimuth) + * y = z * std::tan(elevation) * * PhasedArray3DSpecialCoordinatesImages are templated over a pixel * type and follow the SpecialCoordinatesImage interface. The data in @@ -188,9 +188,9 @@ public: double maxElevation = region.GetSize(1) - 1; // Convert Cartesian coordinates into angular coordinates - TCoordRep azimuth = vcl_atan(point[0] / point[2]); - TCoordRep elevation = vcl_atan(point[1] / point[2]); - TCoordRep radius = vcl_sqrt(point[0] * point[0] + TCoordRep azimuth = std::atan(point[0] / point[2]); + TCoordRep elevation = std::atan(point[1] / point[2]); + TCoordRep radius = std::sqrt(point[0] * point[0] + point[1] * point[1] + point[2] * point[2]); @@ -222,9 +222,9 @@ public: double maxElevation = region.GetSize(1) - 1; // Convert Cartesian coordinates into angular coordinates - TCoordRep azimuth = vcl_atan(point[0] / point[2]); - TCoordRep elevation = vcl_atan(point[1] / point[2]); - TCoordRep radius = vcl_sqrt(point[0] * point[0] + TCoordRep azimuth = std::atan(point[0] / point[2]); + TCoordRep elevation = std::atan(point[1] / point[2]); + TCoordRep radius = std::sqrt(point[0] * point[0] + point[1] * point[1] + point[2] * point[2]); @@ -266,11 +266,11 @@ public: TCoordRep radius = ( index[2] * m_RadiusSampleSize ) + m_FirstSampleDistance; // Convert the angular coordinates into Cartesian coordinates - TCoordRep tanOfAzimuth = vcl_tan(azimuth); - TCoordRep tanOfElevation = vcl_tan(elevation); + TCoordRep tanOfAzimuth = std::tan(azimuth); + TCoordRep tanOfElevation = std::tan(elevation); point[2] = static_cast< TCoordRep >( radius - / vcl_sqrt(1 + / std::sqrt(1 + tanOfAzimuth * tanOfAzimuth + tanOfElevation * tanOfElevation) ); point[1] = static_cast< TCoordRep >( point[2] * tanOfElevation ); @@ -303,11 +303,11 @@ public: + m_FirstSampleDistance; // Convert the angular coordinates into Cartesian coordinates - TCoordRep tanOfAzimuth = vcl_tan(azimuth); - TCoordRep tanOfElevation = vcl_tan(elevation); + TCoordRep tanOfAzimuth = std::tan(azimuth); + TCoordRep tanOfElevation = std::tan(elevation); point[2] = static_cast< TCoordRep >( - radius / vcl_sqrt( + radius / std::sqrt( 1.0 + tanOfAzimuth * tanOfAzimuth + tanOfElevation * tanOfElevation) ); point[1] = static_cast< TCoordRep >( point[2] * tanOfElevation ); point[0] = static_cast< TCoordRep >( point[2] * tanOfAzimuth ); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPixelTraits.h b/Utilities/ITK/Modules/Core/Common/include/itkPixelTraits.h index ca12008e34a9c79737edc4c11b256d61a80c3fd1..a70e3c36857cad387710902a607068997eece230 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPixelTraits.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkPixelTraits.h @@ -191,11 +191,11 @@ public: * of the JoinTraits are specializations of the base template. * \ingroup ITKCommon */ -template< typename TValueType1, typename TValueType2 > +template< typename TValue1, typename TValue2 > class JoinTraits { public: - typedef TValueType1 ValueType; + typedef TValue1 ValueType; }; /** \cond HIDE_SPECIALIZATION_DOCUMENTATION */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPoint.h b/Utilities/ITK/Modules/Core/Common/include/itkPoint.h index b7641b73aaba79130b4e6d10eab7dbb0429d7d19..547d6b2ad4c035775159fd46e2e1dde6a9f35ed2 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPoint.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkPoint.h @@ -257,7 +257,7 @@ public: template< typename TCoordRepB > RealType EuclideanDistanceTo(const Point< TCoordRepB, NPointDimension > & pa) const { - const double distance = vcl_sqrt( + const double distance = std::sqrt( static_cast< double >( this->SquaredEuclideanDistanceTo(pa) ) ); return static_cast< RealType >( distance ); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPointSet.h b/Utilities/ITK/Modules/Core/Common/include/itkPointSet.h index e8a3c1c0b75165433bee8b95929727c686f2f1b0..eede45047a55a864d64c6d883b98f2b2c5a51e17 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPointSet.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkPointSet.h @@ -144,7 +144,7 @@ public: /** PointSet-level operation interface. */ void PassStructure(Self *inputPointSet); - virtual void Initialize(void); + virtual void Initialize(void) ITK_OVERRIDE; PointIdentifier GetNumberOfPoints(void) const; @@ -175,23 +175,23 @@ public: bool GetPointData(PointIdentifier, PixelType *) const; /** Methods to manage streaming. */ - virtual void UpdateOutputInformation(); + virtual void UpdateOutputInformation() ITK_OVERRIDE; - virtual void SetRequestedRegionToLargestPossibleRegion(); + virtual void SetRequestedRegionToLargestPossibleRegion() ITK_OVERRIDE; - virtual void CopyInformation(const DataObject *data); + virtual void CopyInformation(const DataObject *data) ITK_OVERRIDE; - virtual void Graft(const DataObject *data); + virtual void Graft(const DataObject *data) ITK_OVERRIDE; - virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); + virtual bool RequestedRegionIsOutsideOfTheBufferedRegion() ITK_OVERRIDE; - virtual bool VerifyRequestedRegion(); + virtual bool VerifyRequestedRegion() ITK_OVERRIDE; /** Set the requested region from this data object to match the requested * region of the data object passed in as a parameter. This method * implements the API from DataObject. The data object parameter must be * castable to a PointSet. */ - virtual void SetRequestedRegion(const DataObject *data); + virtual void SetRequestedRegion(const DataObject *data) ITK_OVERRIDE; /** Set/Get the Requested region */ virtual void SetRequestedRegion(const RegionType & region); @@ -207,7 +207,7 @@ protected: /** Constructor for use by New() method. */ PointSet(); ~PointSet() {} - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; // If the RegionType is ITK_UNSTRUCTURED_REGION, then the following // variables represent the maximum number of region that the data diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPointSet.hxx b/Utilities/ITK/Modules/Core/Common/include/itkPointSet.hxx index 44f0de41ce12a3d9df47798e2f845066d65d6910..08d16129249fdc50741212ec58ce95f70ff0c422 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPointSet.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkPointSet.hxx @@ -50,7 +50,7 @@ PointSet< TPixelType, VDimension, TMeshTraits > os << indent << "Maximum Number Of Regions: " << m_MaximumNumberOfRegions << std::endl; os << indent << "Point Data Container pointer: " - << ( ( this->m_PointDataContainer ) ? this->m_PointDataContainer.GetPointer() : 0 ) << std::endl; + << ( ( this->m_PointDataContainer ) ? this->m_PointDataContainer.GetPointer() : ITK_NULLPTR ) << std::endl; os << indent << "Size of Point Data Container: " << ( ( this->m_PointDataContainer ) ? this->m_PointDataContainer->Size() : 0 ) << std::endl; } @@ -308,8 +308,8 @@ PointSet< TPixelType, VDimension, TMeshTraits > { Superclass::Initialize(); - m_PointsContainer = 0; - m_PointDataContainer = 0; + m_PointsContainer = ITK_NULLPTR; + m_PointDataContainer = ITK_NULLPTR; } /****************************************************************************** @@ -323,8 +323,8 @@ PointSet< TPixelType, VDimension, TMeshTraits > template< typename TPixelType, unsigned int VDimension, typename TMeshTraits > PointSet< TPixelType, VDimension, TMeshTraits > ::PointSet(): - m_PointsContainer(0), - m_PointDataContainer(0) + m_PointsContainer(ITK_NULLPTR), + m_PointDataContainer(ITK_NULLPTR) { // If we used unstructured regions instead of structured regions, then @@ -374,19 +374,7 @@ void PointSet< TPixelType, VDimension, TMeshTraits > ::CopyInformation(const DataObject *data) { - const PointSet *pointSet = NULL; - - try - { - pointSet = dynamic_cast< const PointSet * >( data ); - } - catch ( ... ) - { - // pointer could not be cast back down - itkExceptionMacro( << "itk::PointSet::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( PointSet * ).name() ); - } + const PointSet *pointSet = dynamic_cast< const PointSet * >( data ); if ( !pointSet ) { @@ -413,19 +401,7 @@ PointSet< TPixelType, VDimension, TMeshTraits > // Copy Meta Data this->CopyInformation(data); - const Self *pointSet = NULL; - - try - { - pointSet = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - // pointer could not be cast back down - itkExceptionMacro( << "itk::PointSet::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *pointSet = dynamic_cast< const Self * >( data ); if ( !pointSet ) { diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPolygonCell.hxx b/Utilities/ITK/Modules/Core/Common/include/itkPolygonCell.hxx index 0059d01c34c88e65a48b34e2691910c840932a89..b03b40758bec4c4f1436f686a02d93d485f0e24a 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPolygonCell.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkPolygonCell.hxx @@ -298,7 +298,7 @@ PolygonCell< TCellInterface > } else { - return NULL; + return ITK_NULLPTR; } } @@ -318,7 +318,7 @@ PolygonCell< TCellInterface > } else { - return NULL; + return ITK_NULLPTR; } } @@ -337,7 +337,7 @@ PolygonCell< TCellInterface > } else { - return NULL; + return ITK_NULLPTR; } } @@ -357,7 +357,7 @@ PolygonCell< TCellInterface > } else { - return NULL; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPostOrderTreeIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkPostOrderTreeIterator.h index 511902c20208e4fc03b759a13d2ce0170407f652..68bbb2a552f964299536234af81e31a0cedbd145 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPostOrderTreeIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkPostOrderTreeIterator.h @@ -63,16 +63,16 @@ protected: /** Constructor */ template< typename TTreeType > PostOrderTreeIterator< TTreeType >::PostOrderTreeIterator(TTreeType *tree): - TreeIteratorBase< TTreeType >(tree, NULL) + TreeIteratorBase< TTreeType >(tree, ITK_NULLPTR) { - if ( tree->GetRoot() == 0 ) + if ( tree->GetRoot() == ITK_NULLPTR ) { - this->m_Begin = 0; + this->m_Begin = ITK_NULLPTR; } else { const TreeNodeType *root = dynamic_cast<const TreeNodeType *>(tree->GetRoot()); - if(root == 0) + if(root == ITK_NULLPTR) { itkGenericExceptionMacro(<< "Can't downcast root node to TreeNodeType *"); } @@ -95,7 +95,7 @@ template< typename TTreeType > bool PostOrderTreeIterator< TTreeType >::HasNext() const { - if ( const_cast< TreeNodeType * >( FindNextNode() ) != NULL ) + if ( const_cast< TreeNodeType * >( FindNextNode() ) != ITK_NULLPTR ) { return true; } @@ -116,22 +116,22 @@ template< typename TTreeType > const typename PostOrderTreeIterator< TTreeType >::TreeNodeType * PostOrderTreeIterator< TTreeType >::FindNextNode() const { - if ( this->m_Position == NULL || this->m_Position == this->m_Root ) + if ( this->m_Position == ITK_NULLPTR || this->m_Position == this->m_Root ) { - return NULL; + return ITK_NULLPTR; } TreeNodeType *sister = const_cast< TreeNodeType * >( FindSister(this->m_Position) ); - if ( sister != NULL ) + if ( sister != ITK_NULLPTR ) { return FindMostRightLeaf(sister); } - if(this->m_Position->GetParent() == 0) + if(this->m_Position->GetParent() == ITK_NULLPTR) { - return 0; + return ITK_NULLPTR; } TreeNodeType *rval = dynamic_cast<TreeNodeType *>(this->m_Position->GetParent()); - if(rval == 0) + if(rval == ITK_NULLPTR) { itkGenericExceptionMacro(<< "Can't downcast to TreeNodeType *"); } @@ -145,11 +145,11 @@ PostOrderTreeIterator< TTreeType >::FindSister(TreeNodeType *node) const { if ( !node->HasParent() ) { - return NULL; + return ITK_NULLPTR; } TreeNodeType *parent = dynamic_cast<TreeNodeType *>(node->GetParent()); - if(parent == 0) + if(parent == ITK_NULLPTR) { itkGenericExceptionMacro(<< "Can't downcast to TreeNodeType *"); } @@ -159,21 +159,21 @@ PostOrderTreeIterator< TTreeType >::FindSister(TreeNodeType *node) const while ( childPosition < lastChildPosition ) { - if(parent->GetChild(childPosition + 1) == 0) + if(parent->GetChild(childPosition + 1) == ITK_NULLPTR) { childPosition++; } else { TreeNodeType *sister = dynamic_cast<TreeNodeType *>(parent->GetChild(childPosition + 1)); - if ( sister == 0) + if ( sister == ITK_NULLPTR) { itkGenericExceptionMacro(<< "Can't downcast to TreeNodeType *"); } return sister; } } - return NULL; + return ITK_NULLPTR; } /** Find the most right leaf */ @@ -189,23 +189,23 @@ PostOrderTreeIterator< TTreeType >::FindMostRightLeaf(TreeNodeType *node) const do { - if(node->GetChild(i) == 0) + if(node->GetChild(i) == ITK_NULLPTR) { - helpNode = 0; + helpNode = ITK_NULLPTR; } else { helpNode = dynamic_cast<TreeNodeType *>(node->GetChild(i)); - if(helpNode == 0) + if(helpNode == ITK_NULLPTR) { itkGenericExceptionMacro(<< "Can't downcast to TreeNodeType *"); } } i++; } - while ( helpNode == NULL && i < childCount ); + while ( helpNode == ITK_NULLPTR && i < childCount ); - if ( helpNode == NULL ) + if ( helpNode == ITK_NULLPTR ) { return node; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPreOrderTreeIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkPreOrderTreeIterator.h index 4bbb71b1a2908b0ad1b720ff8727962f3f16530a..c3b2c71921c88c792a708be185726903e79ae15c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPreOrderTreeIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkPreOrderTreeIterator.h @@ -83,7 +83,7 @@ template< typename TTreeType > bool PreOrderTreeIterator< TTreeType >::HasNext() const { - if ( const_cast< TreeNodeType * >( FindNextNode() ) != NULL ) + if ( const_cast< TreeNodeType * >( FindNextNode() ) != ITK_NULLPTR ) { return true; } @@ -104,9 +104,9 @@ template< typename TTreeType > const typename PreOrderTreeIterator< TTreeType >::TreeNodeType * PreOrderTreeIterator< TTreeType >::FindNextNode() const { - if ( this->m_Position == NULL ) + if ( this->m_Position == ITK_NULLPTR ) { - return NULL; + return ITK_NULLPTR; } if ( this->m_Position->HasChildren() ) { @@ -115,7 +115,7 @@ PreOrderTreeIterator< TTreeType >::FindNextNode() const if ( !this->m_Position->HasParent() ) { - return NULL; + return ITK_NULLPTR; } TreeNodeType *child = this->m_Position; @@ -124,7 +124,7 @@ PreOrderTreeIterator< TTreeType >::FindNextNode() const // Are we a subtree? Then we are done. if ( parent && parent->ChildPosition(this->m_Root) >= 0 ) { - return NULL; + return ITK_NULLPTR; } int childPosition = parent->ChildPosition(child); @@ -134,7 +134,7 @@ PreOrderTreeIterator< TTreeType >::FindNextNode() const { TreeNodeType *help = dynamic_cast< TreeNodeType * >( parent->GetChild(childPosition + 1) ); - if ( help != NULL ) + if ( help != ITK_NULLPTR ) { return help; } @@ -149,7 +149,7 @@ PreOrderTreeIterator< TTreeType >::FindNextNode() const // Subtree if ( parent->ChildPosition(this->m_Root) >= 0 ) { - return NULL; + return ITK_NULLPTR; } childPosition = parent->ChildPosition(child); @@ -159,13 +159,13 @@ PreOrderTreeIterator< TTreeType >::FindNextNode() const { TreeNodeType *help = dynamic_cast< TreeNodeType * >( parent->GetChild(childPosition + 1) ); - if ( help != NULL ) + if ( help != ITK_NULLPTR ) { return help; } } } - return NULL; + return ITK_NULLPTR; } /** Clone function */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkPriorityQueueContainer.hxx b/Utilities/ITK/Modules/Core/Common/include/itkPriorityQueueContainer.hxx index 3e1e3f111450948905809bfc0e36e19bb649ff22..fbd0ad4936d22a1135e4e8253f6d92e9dd085f33 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkPriorityQueueContainer.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkPriorityQueueContainer.hxx @@ -133,7 +133,10 @@ ElementWrapperPointerInterface< TElement, TElementIdentifier >::m_ElementNotFoun // MinPriorityQueueElementWrapper // ----------------------------------------------------------------------------- template< typename TElement, typename TElementPriority, typename TElementIdentifier > MinPriorityQueueElementWrapper< TElement, TElementPriority, TElementIdentifier >:: -MinPriorityQueueElementWrapper() : m_Priority(0), m_Location( Superclass::m_ElementNotFound ) +MinPriorityQueueElementWrapper() : + m_Element(0), + m_Priority(0), + m_Location( Superclass::m_ElementNotFound ) {} // ----------------------------------------------------------------------------- diff --git a/Utilities/ITK/Modules/Core/Common/include/itkProcessObject.h b/Utilities/ITK/Modules/Core/Common/include/itkProcessObject.h index 02a2e3b1b5fd52846a2536381190424d6303cf87..4e9f31e8f60904ccc4eeda875541c56f27118966 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkProcessObject.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkProcessObject.h @@ -436,7 +436,7 @@ protected: void operator=( const Self & ); // purposely not implemented }; - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; // // Input Methods @@ -449,9 +449,9 @@ protected: /** Method used internally for getting an indexed input. */ DataObject * GetInput(DataObjectPointerArraySizeType idx) - { return idx < m_IndexedInputs.size() ? m_IndexedInputs[idx]->second : NULL; } + { return idx < m_IndexedInputs.size() ? m_IndexedInputs[idx]->second : ITK_NULLPTR; } const DataObject * GetInput(DataObjectPointerArraySizeType idx) const - { return idx < m_IndexedInputs.size() ? m_IndexedInputs[idx]->second : NULL; } + { return idx < m_IndexedInputs.size() ? m_IndexedInputs[idx]->second : ITK_NULLPTR; } /** Set an input */ virtual void SetInput(const DataObjectIdentifierType & key, DataObject *input); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkProgressAccumulator.h b/Utilities/ITK/Modules/Core/Common/include/itkProgressAccumulator.h index 1450dfc77e5c3a82d414648472ffe1f3d0e63763..8a2a05fdcf4f4c70965d831321384257c66d3c02 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkProgressAccumulator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkProgressAccumulator.h @@ -114,7 +114,7 @@ public: protected: ProgressAccumulator(); virtual ~ProgressAccumulator(); - void PrintSelf(std::ostream & s, Indent indent) const; + virtual void PrintSelf(std::ostream & s, Indent indent) const ITK_OVERRIDE; private: /** Command for observing progress of pipeline filters */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkQuadrilateralCell.hxx b/Utilities/ITK/Modules/Core/Common/include/itkQuadrilateralCell.hxx index e462a4a900180c15ec51214ecb3c6a2f3dabce6e..720bea5d6631810454e868af4f6500bff79faa6b 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkQuadrilateralCell.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkQuadrilateralCell.hxx @@ -360,7 +360,7 @@ QuadrilateralCell< TCellInterface > d = vnl_determinant(mat); //d=vtkMath::Determinant2x2(rcol,scol); - if ( vcl_abs(d) < 1.e-20 ) + if ( std::abs(d) < 1.e-20 ) { return false; } @@ -389,15 +389,15 @@ QuadrilateralCell< TCellInterface > } // check for convergence - if ( ( ( vcl_abs(pcoords[0] - params[0]) ) < ITK_QUAD_CONVERGED ) - && ( ( vcl_abs(pcoords[1] - params[1]) ) < ITK_QUAD_CONVERGED ) ) + if ( ( ( std::abs(pcoords[0] - params[0]) ) < ITK_QUAD_CONVERGED ) + && ( ( std::abs(pcoords[1] - params[1]) ) < ITK_QUAD_CONVERGED ) ) { converged = 1; } // Test for bad divergence (S.Hirschberg 11.12.2001) - else if ( ( vcl_abs(pcoords[0]) > ITK_DIVERGED ) - || ( vcl_abs(pcoords[1]) > ITK_DIVERGED ) ) + else if ( ( std::abs(pcoords[0]) > ITK_DIVERGED ) + || ( std::abs(pcoords[1]) > ITK_DIVERGED ) ) { return -1; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkRGBAPixel.h b/Utilities/ITK/Modules/Core/Common/include/itkRGBAPixel.h index e27ac352707efce9512739e6586af9b543e2213f..f3411e1734dcc3b7ec253303fbc8d34d172a07d1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkRGBAPixel.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkRGBAPixel.h @@ -112,7 +112,7 @@ public: /** Return the value for the Nth component. */ ComponentType GetScalarValue() const { - return static_cast< ComponentType >( vcl_sqrt( + return static_cast< ComponentType >( std::sqrt( static_cast< double >( this->operator[](0) ) * static_cast< double >( this->operator[](0) ) + static_cast< double >( this->operator[](1) ) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkRGBPixel.h b/Utilities/ITK/Modules/Core/Common/include/itkRGBPixel.h index 67d5d78df477b49144702b4b6bddc6eaeb243838..081a0c6e68a35074237dcab4d3507a2c02394fd6 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkRGBPixel.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkRGBPixel.h @@ -119,7 +119,7 @@ public: /** Return the value for the Nth component. */ ComponentType GetScalarValue() const { - return static_cast< ComponentType >( vcl_sqrt( + return static_cast< ComponentType >( std::sqrt( static_cast< double >( this->operator[](0) ) * static_cast< double >( this->operator[](0) ) + static_cast< double >( this->operator[](1) ) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkRealTimeClock.h b/Utilities/ITK/Modules/Core/Common/include/itkRealTimeClock.h index a1424dae5b4ed2f698da1946a86c420dcd3dea10..21b0d2452562201931af1e5748fa50765dc87aaa 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkRealTimeClock.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkRealTimeClock.h @@ -74,7 +74,7 @@ protected: virtual ~RealTimeClock(); /** Print the object information in a stream. */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: FrequencyType m_Frequency; @@ -84,7 +84,7 @@ private: // We hide this method in the private section, because it returns the // modified time of the itk::Object. That modified time is ambiguous with // the role of the RealTimeStamp. - virtual const TimeStamp & GetTimeStamp() const; + virtual const TimeStamp & GetTimeStamp() const ITK_OVERRIDE; }; } // end of namespace itk diff --git a/Utilities/ITK/Modules/Core/Common/include/itkResourceProbe.h b/Utilities/ITK/Modules/Core/Common/include/itkResourceProbe.h index 1618e3ce5f9b11a007d0df2532f38ba51cf3782c..1175a79a1c8c6e7c1753b2622c6f617effdc72af 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkResourceProbe.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkResourceProbe.h @@ -61,7 +61,11 @@ public: /** Start counting the change of value */ void Start(void); - /** Stop counting the change of value */ + /** Stop counting the change of value. + * + * If a matching Start() has not been called before, there is no + * effect. + **/ void Stop(void); /** Returns the number of times that the probe has been started */ @@ -83,6 +87,9 @@ public: */ MeanType GetMean(void) const; + /** Reset the probe */ + void Reset(void); + private: ValueType m_StartValue; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkResourceProbe.hxx b/Utilities/ITK/Modules/Core/Common/include/itkResourceProbe.hxx index 8e59ac0defc9748b9f3029edc58005583e1484cb..47b669320962f14a715207d6d89507dadc14549b 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkResourceProbe.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkResourceProbe.hxx @@ -39,10 +39,7 @@ ResourceProbe< ValueType, MeanType > ::ResourceProbe(const std::string & type, const std::string & unit): m_TypeString(type), m_UnitString(unit) { - this->m_TotalValue = NumericTraits< ValueType >::ZeroValue(); - this->m_StartValue = NumericTraits< ValueType >::ZeroValue(); - this->m_NumberOfStarts = NumericTraits< CountType >::ZeroValue(); - this->m_NumberOfStops = NumericTraits< CountType >::ZeroValue(); + this->Reset(); } /** Destructor */ @@ -51,6 +48,18 @@ ResourceProbe< ValueType, MeanType > ::~ResourceProbe() {} +/** Reset */ +template< typename ValueType, typename MeanType > +void +ResourceProbe< ValueType, MeanType > +::Reset(void) +{ + this->m_TotalValue = NumericTraits< ValueType >::ZeroValue(); + this->m_StartValue = NumericTraits< ValueType >::ZeroValue(); + this->m_NumberOfStarts = NumericTraits< CountType >::ZeroValue(); + this->m_NumberOfStops = NumericTraits< CountType >::ZeroValue(); +} + /** Returns the type probed value */ template< typename ValueType, typename MeanType > std::string @@ -87,7 +96,7 @@ ResourceProbe< ValueType, MeanType > { if ( this->m_NumberOfStops == this->m_NumberOfStarts ) { - itkGenericExceptionMacro(<< "Can't stop a probe that has not been started."); + return; } this->m_TotalValue += this->GetInstantValue() - this->m_StartValue; this->m_NumberOfStops++; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkRootTreeIterator.h b/Utilities/ITK/Modules/Core/Common/include/itkRootTreeIterator.h index d8412f47250fe190d2af45fb8fb7c05b7cfb7b95..0be5e6059d96e1b063479b77b466935e8c5fbb7e 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkRootTreeIterator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkRootTreeIterator.h @@ -83,7 +83,7 @@ template< typename TTreeType > bool RootTreeIterator< TTreeType >::HasNext() const { - if ( const_cast< TreeNodeType * >( FindNextNode() ) != NULL ) + if ( const_cast< TreeNodeType * >( FindNextNode() ) != ITK_NULLPTR ) { return true; } @@ -104,13 +104,13 @@ template< typename TTreeType > const typename RootTreeIterator< TTreeType >::TreeNodeType * RootTreeIterator< TTreeType >::FindNextNode() const { - if ( this->m_Position == NULL ) + if ( this->m_Position == ITK_NULLPTR ) { - return NULL; + return ITK_NULLPTR; } if ( this->m_Position == this->m_Root ) { - return NULL; + return ITK_NULLPTR; } return this->m_Position->GetParent(); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.hxx b/Utilities/ITK/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.hxx index 0bec08f1302b5a67928cfd2c022342aea340be01..39fd4dab71996bd6c3cb9842092d6bb5d636edc1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.hxx @@ -96,8 +96,7 @@ ShapedFloodFilledFunctionConditionalConstIterator< TImage, TFunction > m_TempPtr->SetLargestPossibleRegion(tempRegion); m_TempPtr->SetBufferedRegion(tempRegion); m_TempPtr->SetRequestedRegion(tempRegion); - m_TempPtr->Allocate(); - m_TempPtr->FillBuffer(NumericTraits< typename TTempImage::PixelType >::Zero); + m_TempPtr->Allocate(true); // initialize buffer to zero // Initialize the queue by adding the start index assuming one of // the m_Seeds is "inside" This might not be true, in which diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSimpleDataObjectDecorator.h b/Utilities/ITK/Modules/Core/Common/include/itkSimpleDataObjectDecorator.h index 570999b581716bb33ecbdc9126aae08d151292c6..e5c256f1f6f10b7820990c85da2f3a2229534cea 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSimpleDataObjectDecorator.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkSimpleDataObjectDecorator.h @@ -91,7 +91,7 @@ public: protected: SimpleDataObjectDecorator(); ~SimpleDataObjectDecorator(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; protected: diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.hxx index b3161b78c6014c9de3cec2c06d742ee2e1bb37cf..f6e282cf72680e19d9636cefee227ec6f0ea0229 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.hxx @@ -54,7 +54,7 @@ SinRegularizedHeavisideStepFunction< TInput, TOutput > const RealType angleFactor = 0.5 * vnl_math::pi * this->GetOneOverEpsilon(); const RealType angle = input * angleFactor; - return static_cast< OutputType >( 0.5 * ( 1.0 + vcl_sin( angle ) ) ); + return static_cast< OutputType >( 0.5 * ( 1.0 + std::sin( angle ) ) ); } } } @@ -73,7 +73,7 @@ SinRegularizedHeavisideStepFunction< TInput, TOutput > const RealType angleFactor = 0.5 * vnl_math::pi * this->GetOneOverEpsilon(); const RealType angle = input * angleFactor; - return static_cast< OutputType >( 0.5 * angleFactor * vcl_cos(angle) ); + return static_cast< OutputType >( 0.5 * angleFactor * std::cos(angle) ); } } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSmapsFileParser.h b/Utilities/ITK/Modules/Core/Common/include/itkSmapsFileParser.h index 2a6493b921c4c061fab5e032305b1f9632e13582..694e8b98296a2dd4ca9c00dd9a369c3e7415b3da 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSmapsFileParser.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkSmapsFileParser.h @@ -169,10 +169,10 @@ public: virtual ~SmapsData_2_6(); /** Returns the heap usage in kB of the process */ - virtual MemoryLoadType GetHeapUsage(); + virtual MemoryLoadType GetHeapUsage() ITK_OVERRIDE; /** Returns the stack usage in kB of the process */ - virtual MemoryLoadType GetStackUsage(); + virtual MemoryLoadType GetStackUsage() ITK_OVERRIDE; /** fill the smaps data */ friend ITKCommon_EXPORT std::istream & operator>>(std::istream & smapsStream, @@ -198,10 +198,10 @@ public: virtual ~VMMapData_10_2(); /** Returns the heap usage in kB of the process */ - virtual MemoryLoadType GetHeapUsage(); + virtual MemoryLoadType GetHeapUsage() ITK_OVERRIDE; /** Returns the stack usage in kB of the process */ - virtual MemoryLoadType GetStackUsage(); + virtual MemoryLoadType GetStackUsage() ITK_OVERRIDE; /** fill the smaps data */ friend ITKCommon_EXPORT std::istream & operator>>(std::istream & stream, diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSmapsFileParser.hxx b/Utilities/ITK/Modules/Core/Common/include/itkSmapsFileParser.hxx index 534b6587f37e50a9744e9a0a5be40bce4f892e05..6d3ec0dfd9d240150de3a06923b3621b3791a47a 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSmapsFileParser.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkSmapsFileParser.hxx @@ -178,8 +178,8 @@ void VMMapFileParser< TVMMapDataType >::ReadFile(const std::string & mapFileLoca std::stringstream vmmapCommand; vmmapCommand << "vmmap " << getpid(); - FILE *vmmapCommandOutput = NULL; - if ( ( vmmapCommandOutput = popen(vmmapCommand.str().c_str(), "r") ) == NULL ) + FILE *vmmapCommandOutput = ITK_NULLPTR; + if ( ( vmmapCommandOutput = popen(vmmapCommand.str().c_str(), "r") ) == ITK_NULLPTR ) { itkGenericExceptionMacro(<< "Error using pmap. Can execute pmap command"); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSmartPointer.h b/Utilities/ITK/Modules/Core/Common/include/itkSmartPointer.h index bbadd922abed1c0f4fe3d2db19081d472d4a4eb1..3ab7bde9b3670058cb02a53676b4693c3727b7c1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSmartPointer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkSmartPointer.h @@ -39,6 +39,16 @@ namespace itk * \ingroup DataAccess * \ingroup ITKCommon */ +#if __cplusplus >= 201103L +// In c++11 there is an explicit nullptr type that introduces a new keyword to +// serve as a distinguished null pointer constant: nullptr. It is of type +// nullptr_t, which is implicitly convertible and comparable to any pointer type +// or pointer-to-member type. It is not implicitly convertible or comparable to +// integral types, except for bool. +#define SP_ITK_NULLPTR nullptr +#else +#define SP_ITK_NULLPTR NULL +#endif template< typename TObjectType > class SmartPointer { @@ -47,7 +57,7 @@ public: /** Constructor */ SmartPointer () - { m_Pointer = 0; } + { m_Pointer = SP_ITK_NULLPTR; } /** Copy constructor */ SmartPointer (const SmartPointer< ObjectType > & p): @@ -63,7 +73,7 @@ public: ~SmartPointer () { this->UnRegister(); - m_Pointer = 0; + m_Pointer = SP_ITK_NULLPTR; } /** Overload operator -> */ @@ -76,9 +86,9 @@ public: /** Test if the pointer has been initialized */ bool IsNotNull() const - { return m_Pointer != 0; } + { return m_Pointer != SP_ITK_NULLPTR; } bool IsNull() const - { return m_Pointer == 0; } + { return m_Pointer == SP_ITK_NULLPTR; } /** Template comparison operators. */ template< typename TR > @@ -117,14 +127,9 @@ public: /** Overload operator assignment. */ SmartPointer & operator=(ObjectType *r) { - if ( m_Pointer != r ) - { - ObjectType *tmp = m_Pointer; //avoid recursive unregisters by retaining - // temporarily - m_Pointer = r; - this->Register(); - if ( tmp ) { tmp->UnRegister(); } - } + SmartPointer temp(r); + temp.swap(*this); + return *this; } @@ -143,6 +148,13 @@ public: return m_Pointer; } + void swap(SmartPointer &other) + { + ObjectType *tmp = this->m_Pointer; + this->m_Pointer = other.m_Pointer; + other.m_Pointer = tmp; + } + private: /** The pointer to the object referred to by this smart pointer. */ ObjectType *m_Pointer; @@ -164,6 +176,13 @@ std::ostream & operator<<(std::ostream & os, SmartPointer< T > p) p.Print(os); return os; } + +template<typename T> +inline void swap( SmartPointer<T> &a, SmartPointer<T> &b ) +{ + a.swap(b); +} + } // end namespace itk #endif diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSmartPointerForwardReference.h b/Utilities/ITK/Modules/Core/Common/include/itkSmartPointerForwardReference.h index 6a823969b18f18b3f3093e940a9db71a0894026c..84e98e2341d03ed984e39496a417d9df63a04604 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSmartPointerForwardReference.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkSmartPointerForwardReference.h @@ -50,7 +50,7 @@ class SmartPointerForwardReference public: /** Constructor */ SmartPointerForwardReference () - { m_Pointer = 0; } + { m_Pointer = ITK_NULLPTR; } /** Const constructor */ SmartPointerForwardReference (const SmartPointerForwardReference< T > & p); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSparseFieldLayer.h b/Utilities/ITK/Modules/Core/Common/include/itkSparseFieldLayer.h index 707c88196b48b6c1220f5731ff657cea6fd778ae..286072fc6b84d81abd57086eaf9e68ee756b35b8 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSparseFieldLayer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkSparseFieldLayer.h @@ -70,7 +70,7 @@ public: } ConstSparseFieldLayerIterator() - { m_Pointer = 0; } + { m_Pointer = ITK_NULLPTR; } ConstSparseFieldLayerIterator(TNodeType *p) { m_Pointer = p; } @@ -257,7 +257,7 @@ public: protected: SparseFieldLayer(); ~SparseFieldLayer(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: SparseFieldLayer(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSparseFieldLayer.hxx b/Utilities/ITK/Modules/Core/Common/include/itkSparseFieldLayer.hxx index a10ffe80efa92cdab10dfc4177c4253d1f61260a..36676aec8acfed63aafc993ef447d399b7f9bb97 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSparseFieldLayer.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkSparseFieldLayer.hxx @@ -19,7 +19,6 @@ #define __itkSparseFieldLayer_hxx #include "itkSparseFieldLayer.h" #include <cmath> -#include "vcl_cmath.h" namespace itk { @@ -68,7 +67,7 @@ SparseFieldLayer< TNodeType > unsigned int size, regionsize; size = Size(); regionsize = static_cast< unsigned int >( - vcl_ceil( static_cast< float >( size ) / static_cast< float >( num ) ) ); + std::ceil( static_cast< float >( size ) / static_cast< float >( num ) ) ); ConstIterator position = Begin(); ConstIterator last = End(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSpatialOrientationAdapter.h b/Utilities/ITK/Modules/Core/Common/include/itkSpatialOrientationAdapter.h index d8d315220e061d99f98eab7780bdf3b0ed840d3a..5c7a4bf8176c9623bd66736c29d659443ef5c6c2 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSpatialOrientationAdapter.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkSpatialOrientationAdapter.h @@ -95,10 +95,10 @@ public: SpatialOrientationAdapter() {} /** convert from direction cosines. */ - virtual OrientationType FromDirectionCosines(const DirectionType & Dir); + virtual OrientationType FromDirectionCosines(const DirectionType & Dir) ITK_OVERRIDE; /** convert to direction cosines. */ - virtual DirectionType ToDirectionCosines(const OrientationType & Or); + virtual DirectionType ToDirectionCosines(const OrientationType & Or) ITK_OVERRIDE; }; } // namespace itk diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSpecialCoordinatesImage.h b/Utilities/ITK/Modules/Core/Common/include/itkSpecialCoordinatesImage.h index 41a6fddfb2d02642cd4cfc9f19571cb515605c83..f1068db5b37770b85724198464630fdbb19cda45 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSpecialCoordinatesImage.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkSpecialCoordinatesImage.h @@ -170,7 +170,7 @@ public: /** Allocate the image memory. The size of the image must * already be set, e.g. by calling SetRegions(). */ - void Allocate(); + virtual void Allocate(bool initialize=false) ITK_OVERRIDE; /** Restore the data object to its initial state. This means releasing * memory. */ @@ -226,7 +226,7 @@ public: /** Return a pointer to the beginning of the buffer. This is used by * the image iterator class. */ TPixel * GetBufferPointer() { return m_Buffer ? m_Buffer->GetBufferPointer() : 0; } - const TPixel * GetBufferPointer() const { return m_Buffer ? m_Buffer->GetBufferPointer() : 0; } + const TPixel * GetBufferPointer() const { return m_Buffer ? m_Buffer->GetBufferPointer() : ITK_NULLPTR; } /** Return a pointer to the container. */ PixelContainer * GetPixelContainer() { return m_Buffer.GetPointer(); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSpecialCoordinatesImage.hxx b/Utilities/ITK/Modules/Core/Common/include/itkSpecialCoordinatesImage.hxx index e9242313c69fcb70a7f4ec21bbb9bd6fb51a81a0..a10d5230cbe3ed7c189f3a15de414f34a5911e6d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSpecialCoordinatesImage.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkSpecialCoordinatesImage.hxx @@ -43,14 +43,14 @@ SpecialCoordinatesImage< TPixel, VImageDimension > template< typename TPixel, unsigned int VImageDimension > void SpecialCoordinatesImage< TPixel, VImageDimension > -::Allocate() +::Allocate(bool initialize) { SizeValueType num; this->ComputeOffsetTable(); num = static_cast<SizeValueType>(this->GetOffsetTable()[VImageDimension]); - m_Buffer->Reserve(num); + m_Buffer->Reserve(num,initialize); } template< typename TPixel, unsigned int VImageDimension > diff --git a/Utilities/ITK/Modules/Core/Common/include/itkStdStreamLogOutput.h b/Utilities/ITK/Modules/Core/Common/include/itkStdStreamLogOutput.h index b41143c3b655fa1c5dca71b3eef614999f4a50d5..025bbddf91d294d726b783f9f6e4ebfd0fc93be6 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkStdStreamLogOutput.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkStdStreamLogOutput.h @@ -62,16 +62,16 @@ public: void SetStream(StreamType & Stream); /** flush a buffer */ - virtual void Flush(); + virtual void Flush() ITK_OVERRIDE; /** Write to multiple outputs */ - virtual void Write(double timestamp); + virtual void Write(double timestamp) ITK_OVERRIDE; /** Write to a buffer */ - virtual void Write(std::string const & content); + virtual void Write(std::string const & content) ITK_OVERRIDE; /** Write to a buffer */ - virtual void Write(std::string const & content, double timestamp); + virtual void Write(std::string const & content, double timestamp) ITK_OVERRIDE; protected: /** Constructor */ @@ -80,7 +80,7 @@ protected: /** Destructor */ virtual ~StdStreamLogOutput(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Core/Common/include/itkStdStreamStateSave.h b/Utilities/ITK/Modules/Core/Common/include/itkStdStreamStateSave.h new file mode 100644 index 0000000000000000000000000000000000000000..6f8be5cb4731e3c141effe9147137db2e0505149 --- /dev/null +++ b/Utilities/ITK/Modules/Core/Common/include/itkStdStreamStateSave.h @@ -0,0 +1,69 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkStdStreamStateSave_h +#define __itkStdStreamStateSave_h + +#include <iostream> +#include <string> + +namespace itk +{ +/** \class StdStreamStateSave + * + * \brief Save a stream's format state and restore it upon destruction + * + * An RAII class to provide an exception safe mechanism to restore the + * format state of a stream. The class holds a resource (the stream's + * format state) and resets the resource to a default state upon destruction. + * + * Typical usage: + \code{.cpp} + itk::StdStreamStateSave coutState(std::cout); + std::cout.precision(20); + std::cout.hex(); + ... + return; + \endcode + * + * \ingroup ITKCommon + */ + +class StdStreamStateSave +{ +public: + explicit StdStreamStateSave(std::ios& stream) : + m_Ios(stream), + m_State(NULL) + { + m_State.copyfmt(stream); + } + ~StdStreamStateSave() + { + m_Ios.copyfmt(m_State); + } + +private: + StdStreamStateSave(const StdStreamStateSave &); //purposely not implemented + void operator=(const StdStreamStateSave &); //purposely not implemented + + std::ios& m_Ios; + std::ios m_State; +}; +} + +#endif diff --git a/Utilities/ITK/Modules/Core/Common/include/itkStreamingImageFilter.hxx b/Utilities/ITK/Modules/Core/Common/include/itkStreamingImageFilter.hxx index e356cb916a29cb2ee6623455695f43b02c37e4ba..1c5784d598bd9d0db8faa612cd5c70aa0053463c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkStreamingImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkStreamingImageFilter.hxx @@ -143,15 +143,19 @@ StreamingImageFilter< TInputImage, TOutputImage > << " inputs are required but only " << ninputs << " are specified."); return; } - this->SetAbortGenerateData(0); - this->UpdateProgress(0.0); - this->m_Updating = true; /** - * Tell all Observers that the filter is starting + * Tell all Observers that the filter is starting, before emiting + * the 0.0 Progress event */ this->InvokeEvent( StartEvent() ); + + this->SetAbortGenerateData(0); + this->UpdateProgress(0.0); + this->m_Updating = true; + + /** * Allocate the output buffer. */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSymmetricEigenAnalysis.hxx b/Utilities/ITK/Modules/Core/Common/include/itkSymmetricEigenAnalysis.hxx index 5e9fe18d98dd23dee293b5843358c507f4ce8110..e540766f5b0b63b3c12164b47a8f0e91a8d1f685 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSymmetricEigenAnalysis.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkSymmetricEigenAnalysis.hxx @@ -147,7 +147,7 @@ SymmetricEigenAnalysis< TMatrix, TVector, TEigenMatrix >::ReduceToTridiagonalMat e2[i] = scale * scale * h; f = d[l]; - d__1 = vcl_sqrt(h); + d__1 = std::sqrt(h); g = ( -1.0 ) * vnl_math_sgn0(f) * vnl_math_abs(d__1); e[i] = scale * g; h -= f * g; @@ -267,7 +267,7 @@ const } f = d[l]; - d__1 = vcl_sqrt(h); + d__1 = std::sqrt(h); g = ( -1.0 ) * vnl_math_sgn0(f) * vnl_math_abs(d__1); e[i] = scale * g; h -= f * g; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.hxx index 2529567f22bd2f424a71458f72201e066298f052..d463a0f967fcd7facf3a4a27a9ee7923c92ad95d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.hxx @@ -25,12 +25,13 @@ namespace itk { template< unsigned int VDimension, typename TInput > SymmetricEllipsoidInteriorExteriorSpatialFunction< VDimension, TInput > -::SymmetricEllipsoidInteriorExteriorSpatialFunction() +::SymmetricEllipsoidInteriorExteriorSpatialFunction() : + m_UniqueAxis(10), // Length of unique axis + m_SymmetricAxes(5), // Length of symmetric axes + m_VectorRatio(0.0) // Vector ratio { m_Center.Fill(0.0); // Origin of ellipsoid m_Orientation.Fill(1.0); // Orientation of unique axis - m_UniqueAxis = 10; // Length of unique axis - m_SymmetricAxes = 5; // Length of symmetric axes } template< unsigned int VDimension, typename TInput > @@ -56,10 +57,10 @@ SymmetricEllipsoidInteriorExteriorSpatialFunction< VDimension, TInput > pointVector[i] = position[i] - m_Center[i]; } - uniqueTerm = vcl_pow( static_cast< double >( ( ( pointVector * m_Orientation ) / ( .5 * m_UniqueAxis ) ) ), + uniqueTerm = std::pow( static_cast< double >( ( ( pointVector * m_Orientation ) / ( .5 * m_UniqueAxis ) ) ), static_cast< double >( 2 ) ); symmetricVector = pointVector - ( m_Orientation * ( pointVector * m_Orientation ) ); - symmetricTerm = vcl_pow( + symmetricTerm = std::pow( static_cast< double >( ( ( symmetricVector.GetNorm() ) / ( .5 * m_SymmetricAxes ) ) ), static_cast< double >( 2 ) ); if ( ( uniqueTerm + symmetricTerm ) >= 0 && ( uniqueTerm + symmetricTerm ) <= 1 ) diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTetrahedronCell.hxx b/Utilities/ITK/Modules/Core/Common/include/itkTetrahedronCell.hxx index eeecc9032fa482f3cc413f16225fb6ed45923a84..33ab4fe88ba325e10828a59b01d06ef348474ec8 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTetrahedronCell.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkTetrahedronCell.hxx @@ -208,7 +208,7 @@ TetrahedronCell< TCellInterface > for ( i = 0; i < 4; i++ ) { this->GetFace (i, triangle); - triangle->EvaluatePosition(x, points, closest, pc, &dist2, NULL); + triangle->EvaluatePosition(x, points, closest, pc, &dist2, ITK_NULLPTR); if ( dist2 < *minDist2 ) { diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTextOutput.h b/Utilities/ITK/Modules/Core/Common/include/itkTextOutput.h index 80033864a8b0bcab24dcf55f087f006a54a33df5..3828b4c6f3fb441cfc36a499de0d6ba995c88142 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTextOutput.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkTextOutput.h @@ -37,7 +37,7 @@ public: /** New macro for creation of through a Smart Pointer */ itkNewMacro(TextOutput); - virtual void DisplayText(const char *s) + virtual void DisplayText(const char *s) ITK_OVERRIDE { std::cout << s << std::endl; } protected: diff --git a/Utilities/ITK/Modules/Core/Common/include/itkThreadLogger.h b/Utilities/ITK/Modules/Core/Common/include/itkThreadLogger.h index 01c49465bd7ed3747b52656b74e454a03de295ed..96416f1ca2216bf4dc9ea6ea54bdef50941b0002 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkThreadLogger.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkThreadLogger.h @@ -72,16 +72,16 @@ public: /** Set the priority level for the current logger. Only messages that have * priorities equal or greater than the one set here will be posted to the * current outputs. */ - virtual void SetPriorityLevel(PriorityLevelType level); + virtual void SetPriorityLevel(PriorityLevelType level) ITK_OVERRIDE; /** Get the priority level for the current logger. Only messages that have * priorities equal or greater than the one set here will be posted to the * current outputs. */ - virtual PriorityLevelType GetPriorityLevel() const; + virtual PriorityLevelType GetPriorityLevel() const ITK_OVERRIDE; - virtual void SetLevelForFlushing(PriorityLevelType level); + virtual void SetLevelForFlushing(PriorityLevelType level) ITK_OVERRIDE; - virtual PriorityLevelType GetLevelForFlushing() const; + virtual PriorityLevelType GetLevelForFlushing() const ITK_OVERRIDE; /** Set the delay in milliseconds between checks to see if there are any * low priority messages to be processed. @@ -94,11 +94,11 @@ public: virtual DelayType GetDelay() const; /** Registers another output stream with the multiple output. */ - virtual void AddLogOutput(OutputType *output); + virtual void AddLogOutput(OutputType *output) ITK_OVERRIDE; - virtual void Write(PriorityLevelType level, std::string const & content); + virtual void Write(PriorityLevelType level, std::string const & content) ITK_OVERRIDE; - virtual void Flush(); + virtual void Flush() ITK_OVERRIDE; protected: @@ -109,7 +109,7 @@ protected: virtual ~ThreadLogger(); /** Print contents of a ThreadLogger */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; static ITK_THREAD_RETURN_TYPE ThreadFunction(void *); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkThreadedIndexedContainerPartitioner.h b/Utilities/ITK/Modules/Core/Common/include/itkThreadedIndexedContainerPartitioner.h index 557f8470374178c2df00032d0e01232574023942..360fe0f88f34fbad831f0b21db8aba82a1e2fad1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkThreadedIndexedContainerPartitioner.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkThreadedIndexedContainerPartitioner.h @@ -79,7 +79,7 @@ public: ThreadIdType PartitionDomain(const ThreadIdType threadId, const ThreadIdType requestedTotal, const DomainType& completeIndexRange, - DomainType& subIndexRange) const; + DomainType& subIndexRange) const ITK_OVERRIDE; protected: ThreadedIndexedContainerPartitioner(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkThreadedIteratorRangePartitioner.hxx b/Utilities/ITK/Modules/Core/Common/include/itkThreadedIteratorRangePartitioner.hxx index d5eeb578e6292f576af9b082b79d8ae823b946e5..efdff86d21c276738eda190dfdd337b8e4142d8c 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkThreadedIteratorRangePartitioner.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkThreadedIteratorRangePartitioner.hxx @@ -22,6 +22,8 @@ #include "itkThreadedIteratorRangePartitioner.h" #include "itkMath.h" +#include <iterator> + namespace itk { @@ -48,12 +50,8 @@ ThreadedIteratorRangePartitioner< TIterator > // overallIndexRange is expected to be inclusive // determine the actual number of pieces that will be generated - typename DomainType::IteratorType it; - ThreadIdType count = NumericTraits< ThreadIdType >::Zero; - for( it = completeDomain.Begin(); it != completeDomain.End(); ++it ) - { - ++count; - } + ThreadIdType count = std::distance( completeDomain.Begin(), completeDomain.End() ); + ThreadIdType valuesPerThread = Math::Ceil<ThreadIdType>( static_cast< double >( count ) / static_cast< double >( requestedTotal )); ThreadIdType maxThreadIdUsed = @@ -66,22 +64,14 @@ ThreadedIteratorRangePartitioner< TIterator > return maxThreadIdUsed + 1; } - // Split the domain range - it = completeDomain.Begin(); const ThreadIdType startIndexCount = threadId * valuesPerThread; - for( ThreadIdType ii = 0; ii < startIndexCount; ++ii ) - { - ++it; - } - subDomain.m_Begin = it; + subDomain.m_Begin = completeDomain.Begin(); + std::advance(subDomain.m_Begin, startIndexCount ); + if (threadId < maxThreadIdUsed) { - const ThreadIdType endIndexCount = valuesPerThread; - for( ThreadIdType ii = 0; ii < endIndexCount; ++ii ) - { - ++it; - } - subDomain.m_End = it; + subDomain.m_End = subDomain.m_Begin; + std::advance(subDomain.m_End, valuesPerThread ); } if (threadId == maxThreadIdUsed) { diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTimeProbe.h b/Utilities/ITK/Modules/Core/Common/include/itkTimeProbe.h index 276ae13e2438f59d7d1658e7bd3dc585f4249301..474fb9fff7309c9f095cb854db3d4198eb952356 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTimeProbe.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkTimeProbe.h @@ -65,7 +65,7 @@ public: /** Get the current time. * Warning: the returned value is not the elapsed time since the last Start() call. */ - virtual RealTimeClock::TimeStampType GetInstantValue(void) const; + virtual TimeStampType GetInstantValue(void) const ITK_OVERRIDE; /** Returns the average times passed between the starts and stops of the * probe. See the RealTimeClock for details on the precision and units of @@ -75,6 +75,9 @@ public: */ itkLegacyMacro(TimeStampType GetMeanTime(void) const); + /** Get a handle to m_RealTimeClock. */ + itkGetConstObjectMacro( RealTimeClock, RealTimeClock ); + private: RealTimeClock::Pointer m_RealTimeClock; }; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx b/Utilities/ITK/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx index 62f805776c3ff2b06cbe21301421cf895d476c20..bd5f26ff936b068a102d207d50785e506fc541e3 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx @@ -47,7 +47,7 @@ TorusInteriorExteriorSpatialFunction< VDimension, TInput > double y = position[1] - m_Origin[1]; double z = position[2] - m_Origin[2]; - double k = vcl_pow(m_MajorRadius - vcl_sqrt(x * x + y * y), 2.0) + z * z; + double k = std::pow(m_MajorRadius - std::sqrt(x * x + y * y), 2.0) + z * z; if ( k <= ( m_MinorRadius * m_MinorRadius ) ) { diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTreeChangeEvent.h b/Utilities/ITK/Modules/Core/Common/include/itkTreeChangeEvent.h index a20d00735b2deb4736e26da190f76e8428a55c53..c77d2e9f8711697f6712dfe3449a37ee57420e9d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTreeChangeEvent.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkTreeChangeEvent.h @@ -40,7 +40,7 @@ public: /** Constructor */ TreeChangeEvent(): - m_ChangePosition( NULL ) + m_ChangePosition( ITK_NULLPTR ) {} /** Copy constructor */ @@ -50,13 +50,13 @@ public: virtual ~TreeChangeEvent() {} /** Get the event name */ - virtual const char * GetEventName() const { return "TreeChangeEvent"; } + virtual const char * GetEventName() const ITK_OVERRIDE { return "TreeChangeEvent"; } /** Check the event */ - virtual bool CheckEvent(const::itk::EventObject *e) const { return (dynamic_cast< const Self * >( e ) != NULL); } + virtual bool CheckEvent(const::itk::EventObject *e) const ITK_OVERRIDE { return (dynamic_cast< const Self * >( e ) != ITK_NULLPTR); } /** Make the event object */ - virtual::itk::EventObject * MakeObject() const { return new Self(*m_ChangePosition); } + virtual::itk::EventObject * MakeObject() const ITK_OVERRIDE { return new Self(*m_ChangePosition); } /** Get the change position */ const TreeIteratorBase< TTreeType > & GetChangePosition() const { return *m_ChangePosition; } @@ -125,7 +125,7 @@ public: virtual const char * GetEventName() const { return "TreeAddEvent"; } /** Check event function */ - virtual bool CheckEvent(const::itk::EventObject *e) const { return (dynamic_cast< const Self * >( e ) != NULL); } + virtual bool CheckEvent(const::itk::EventObject *e) const { return (dynamic_cast< const Self * >( e ) != ITK_NULLPTR); } /** Make the event object */ virtual::itk::EventObject * MakeObject() const { return new Self(*this->m_ChangePosition); } @@ -160,7 +160,7 @@ public: virtual const char * GetEventName() const { return "TreeRemoveEvent"; } /** Check the event */ - virtual bool CheckEvent(const::itk::EventObject *e) const { return (dynamic_cast< const Self * >( e ) != NULL); } + virtual bool CheckEvent(const::itk::EventObject *e) const { return (dynamic_cast< const Self * >( e ) != ITK_NULLPTR); } /** Make the event object */ virtual::itk::EventObject * MakeObject() const { return new Self(*this->m_ChangePosition); } @@ -190,7 +190,7 @@ public: virtual const char * GetEventName() const { return "TreePruneEvent"; } - virtual bool CheckEvent(const::itk::EventObject *e) const { return (dynamic_cast< const Self * >( e ) != NULL); } + virtual bool CheckEvent(const::itk::EventObject *e) const { return (dynamic_cast< const Self * >( e ) != ITK_NULLPTR); } virtual::itk::EventObject * MakeObject() const { return new Self(*this->m_ChangePosition); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTreeContainer.h b/Utilities/ITK/Modules/Core/Common/include/itkTreeContainer.h index 309dd8384f0938ec914a48655e6c7517d3adf01f..85ccd4ba01d1a6436a57afa3baf6d012fac01866 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTreeContainer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkTreeContainer.h @@ -29,23 +29,23 @@ namespace itk * This class derives from the TreeContainerBase class. * The class is templated over the type of the elements. * - * \tparam TValueType Element type stored at each location in the Tree. + * \tparam TValue Element type stored at each location in the Tree. * * \ingroup DataRepresentation * \ingroup ITKCommon */ -template< typename TValueType > -class TreeContainer:public TreeContainerBase< TValueType > +template< typename TValue > +class TreeContainer:public TreeContainerBase< TValue > { public: /** Standard typedefs */ - typedef TreeContainerBase< TValueType > Superclass; - typedef TreeContainer< TValueType > Self; - typedef SmartPointer< Self > Pointer; - typedef SmartPointer< const Self > ConstPointer; - typedef TValueType ValueType; - typedef TreeNode< ValueType > TreeNodeType; + typedef TreeContainerBase< TValue > Superclass; + typedef TreeContainer< TValue > Self; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + typedef TValue ValueType; + typedef TreeNode< ValueType > TreeNodeType; /** Iterators typedef */ typedef TreeIteratorBase< Self > IteratorType; @@ -61,34 +61,34 @@ public: TreeContainer(int defaultChildrenCount); /** Constructor */ - TreeContainer(TreeContainer< TValueType > & tree); + TreeContainer(TreeContainer< TValue > & tree); /** Set the root as an element */ - virtual bool SetRoot(const TValueType element); + virtual bool SetRoot(const TValue element); /** The the root as an iterator position */ bool SetRoot(IteratorType & pos); /** Set the root as a tree node */ - virtual bool SetRoot(TreeNode< TValueType > *node); + virtual bool SetRoot(TreeNode< TValue > *node); /** Return true if the element is in the tree */ - bool Contains(const TValueType element); + bool Contains(const TValue element); /** Return the number of elements in the tree */ int Count() const; /** Return true if the element is a leaf */ - bool IsLeaf(const TValueType element); + bool IsLeaf(const TValue element); /** Return true if the element is a root */ - bool IsRoot(const TValueType element); + bool IsRoot(const TValue element); /** Clear the tree */ bool Clear(); /** operator equal */ - bool operator==(TreeContainer< TValueType > & tree); + bool operator==(TreeContainer< TValue > & tree); /** Swap the iterators */ bool Swap(IteratorType & v, IteratorType & w); @@ -97,10 +97,10 @@ public: const TreeNodeType * GetRoot() const { return m_Root.GetPointer(); } /** Add a child to a given parent using values */ - bool Add(const TValueType child, const TValueType parent); + bool Add(const TValue child, const TValue parent); /** Get node given a value */ - const TreeNodeType * GetNode(TValueType val) const; + const TreeNodeType * GetNode(TValue val) const; protected: diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTreeContainer.hxx b/Utilities/ITK/Modules/Core/Common/include/itkTreeContainer.hxx index 9074eac12e640061dee4338b91bb39d814ed7bdb..d9e04778d152ffd7cdf15d3a268bc93390cc9d45 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTreeContainer.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkTreeContainer.hxx @@ -23,17 +23,17 @@ namespace itk { /** Constructor */ -template< typename TValueType > -TreeContainer< TValueType >::TreeContainer() +template< typename TValue > +TreeContainer< TValue >::TreeContainer() { - m_Root = NULL; + m_Root = ITK_NULLPTR; this->SetSubtree(false); m_DefaultChildrenCount = 2; } /** Constructor with default children count */ -template< typename TValueType > -TreeContainer< TValueType >::TreeContainer(int dcc) +template< typename TValue > +TreeContainer< TValue >::TreeContainer(int dcc) { m_Root = NULL; this->SetSubtree(false); @@ -41,8 +41,8 @@ TreeContainer< TValueType >::TreeContainer(int dcc) } /** Constructor by adding a tree */ -template< typename TValueType > -TreeContainer< TValueType >::TreeContainer(TreeContainer< TValueType > & ) +template< typename TValue > +TreeContainer< TValue >::TreeContainer(TreeContainer< TValue > & ) { m_Root = NULL; this->SetSubtree(false); @@ -50,34 +50,34 @@ TreeContainer< TValueType >::TreeContainer(TreeContainer< TValueType > & ) } /** Destructor */ -template< typename TValueType > -TreeContainer< TValueType >::~TreeContainer() +template< typename TValue > +TreeContainer< TValue >::~TreeContainer() {} /** Set the root of the tree */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::SetRoot(const TValueType element) +TreeContainer< TValue >::SetRoot(const TValue element) { m_Root = TreeNodeType::New(); m_Root->Set(element); - m_Root->SetParent(NULL); + m_Root->SetParent(ITK_NULLPTR); return true; } /** Set the root of the tree */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::SetRoot(TreeNode< TValueType > *node) +TreeContainer< TValue >::SetRoot(TreeNode< TValue > *node) { m_Root = node; return true; } /** Count the number of nodes in the tree */ -template< typename TValueType > +template< typename TValue > int -TreeContainer< TValueType >::Count() const +TreeContainer< TValue >::Count() const { if ( !m_Root ) { @@ -95,19 +95,19 @@ TreeContainer< TValueType >::Count() const } /** Swap the iterators */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::Swap(IteratorType & v, IteratorType & w) +TreeContainer< TValue >::Swap(IteratorType & v, IteratorType & w) { - TreeNode< TValueType > *nv = v.GetNode(); - TreeNode< TValueType > *nw = w.GetNode(); + TreeNode< TValue > *nv = v.GetNode(); + TreeNode< TValue > *nw = w.GetNode(); if ( nv == NULL || nw == NULL ) { return false; } - TreeNode< TValueType > *pv = nv->GetParent(); - TreeNode< TValueType > *pw = nw->GetParent(); + TreeNode< TValue > *pv = nv->GetParent(); + TreeNode< TValue > *pw = nw->GetParent(); if ( pv == NULL && pw == NULL ) { @@ -136,9 +136,9 @@ TreeContainer< TValueType >::Swap(IteratorType & v, IteratorType & w) } /** Return true if the tree contains this element */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::Contains(const TValueType element) +TreeContainer< TValue >::Contains(const TValue element) { PreOrderTreeIterator< Self > it(this, m_Root); it.GoToBegin(); @@ -154,9 +154,9 @@ TreeContainer< TValueType >::Contains(const TValueType element) } /** Equal operator */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::operator==(TreeContainer< TValueType > & tree) +TreeContainer< TValue >::operator==(TreeContainer< TValue > & tree) { PreOrderTreeIterator< Self > it(this, m_Root); it.GoToBegin(); @@ -177,9 +177,9 @@ TreeContainer< TValueType >::operator==(TreeContainer< TValueType > & tree) } /** Return true if the given element is a leaf of the tree */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::IsLeaf(TValueType element) +TreeContainer< TValue >::IsLeaf(TValue element) { PreOrderTreeIterator< Self > it(this, m_Root); it.GoToBegin(); @@ -201,9 +201,9 @@ TreeContainer< TValueType >::IsLeaf(TValueType element) } /** Return true of the node containing the element is the root */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::IsRoot(TValueType element) +TreeContainer< TValue >::IsRoot(TValue element) { PreOrderTreeIterator< Self > it(this, m_Root); it.GoToBegin(); @@ -226,19 +226,19 @@ TreeContainer< TValueType >::IsRoot(TValueType element) } /** Clear the tree */ -template< typename TValueType > -bool TreeContainer< TValueType >::Clear() +template< typename TValue > +bool TreeContainer< TValue >::Clear() { PreOrderTreeIterator< Self > it(this, m_Root); bool success = it.Remove(); - m_Root = NULL; + m_Root = ITK_NULLPTR; return success; } /** Get node given a value */ -template< typename TValueType > -const TreeNode< TValueType > * -TreeContainer< TValueType >::GetNode(TValueType val) const +template< typename TValue > +const TreeNode< TValue > * +TreeContainer< TValue >::GetNode(TValue val) const { PreOrderTreeIterator< Self > it(this, m_Root); it.GoToBegin(); @@ -250,26 +250,26 @@ TreeContainer< TValueType >::GetNode(TValueType val) const } ++it; } - return NULL; + return ITK_NULLPTR; } /** Set the root of the tree from the iterator position */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::SetRoot(IteratorType & pos) +TreeContainer< TValue >::SetRoot(IteratorType & pos) { if ( this->m_SubTree ) { return false; } - TreeNode< TValueType > *node = pos.GetNode(); + TreeNode< TValue > *node = pos.GetNode(); if ( node == NULL ) { return false; } - TreeNode< TValueType > *parent = node->GetParent(); - TreeNode< TValueType > *help = NULL; + TreeNode< TValue > *parent = node->GetParent(); + TreeNode< TValue > *help = NULL; if ( parent == NULL ) { @@ -297,13 +297,13 @@ TreeContainer< TValueType >::SetRoot(IteratorType & pos) } /** Add a child to a given parent */ -template< typename TValueType > +template< typename TValue > bool -TreeContainer< TValueType >::Add(const TValueType child, const TValueType parent) +TreeContainer< TValue >::Add(const TValue child, const TValue parent) { if ( !m_Root ) { - std::cout << "TreeContainer<TValueType>::Add() : The tree is empty" << std::endl; + std::cout << "TreeContainer<TValue>::Add() : The tree is empty" << std::endl; return false; } // Find the first node in the tree that has the parent value @@ -322,9 +322,9 @@ TreeContainer< TValueType >::Add(const TValueType child, const TValueType parent } /** Print self */ -template< typename TValueType > +template< typename TValue > void -TreeContainer< TValueType >::PrintSelf(std::ostream & os, Indent indent) const +TreeContainer< TValue >::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Number of objects = " << this->Count() << std::endl; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTreeContainerBase.h b/Utilities/ITK/Modules/Core/Common/include/itkTreeContainerBase.h index 2c702c1ac83c1b9708a6a4f8bc0c56d65955f85b..0aa2c394e37f04be7d05f5f34ed756ec3a8824b0 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTreeContainerBase.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkTreeContainerBase.h @@ -30,7 +30,7 @@ namespace itk * \ingroup DataRepresentation * \ingroup ITKCommon */ -template< typename TValueType > +template< typename TValue > class TreeContainerBase:public Object { public: @@ -40,35 +40,35 @@ public: typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; - typedef TValueType ValueType; + typedef TValue ValueType; /** Run-time type information (and related methods). */ itkTypeMacro(TreeContainerBase, Object); /** Set the root element. * A new node is created and the element is added to the node */ - virtual bool SetRoot(const TValueType element) = 0; + virtual bool SetRoot(const TValue element) = 0; /** Set the root has a node */ - virtual bool SetRoot(TreeNode< TValueType > *node) = 0; + virtual bool SetRoot(TreeNode< TValue > *node) = 0; /** Return true if the tree contains the element */ - virtual bool Contains(const TValueType element) = 0; + virtual bool Contains(const TValue element) = 0; /** Return the number of nodes in the tree */ virtual int Count() const = 0; /** Return if the element is a leaf */ - virtual bool IsLeaf(const TValueType element) = 0; + virtual bool IsLeaf(const TValue element) = 0; /** Return if the element is root */ - virtual bool IsRoot(const TValueType element) = 0; + virtual bool IsRoot(const TValue element) = 0; /** Clear the tree */ virtual bool Clear() = 0; /** Get the root as a node */ - virtual const TreeNode< TValueType > * GetRoot() const = 0; + virtual const TreeNode< TValue > * GetRoot() const = 0; /** Set if the tree is a subtree */ void SetSubtree(bool val) { m_SubTree = val; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTreeIteratorBase.hxx b/Utilities/ITK/Modules/Core/Common/include/itkTreeIteratorBase.hxx index 623033118c8dd0adce753fd3d0d71ea4fef8f14a..931c63a65e5c712fa9c2c5298f6e6f12609e7c0e 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTreeIteratorBase.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkTreeIteratorBase.hxx @@ -53,7 +53,7 @@ TreeIteratorBase< TTreeType >::TreeIteratorBase(TTreeType *tree, const TreeNodeT m_Position = const_cast< TreeNodeType * >( m_Root ); m_Tree = tree; m_Begin = m_Position; - m_End = NULL; + m_End = ITK_NULLPTR; } /** Constructor */ @@ -71,7 +71,7 @@ TreeIteratorBase< TTreeType >::TreeIteratorBase(const TTreeType *tree, const Tre m_Position = const_cast< TreeNodeType * >( m_Root ); m_Tree = const_cast< TTreeType * >( tree ); m_Begin = m_Position; - m_End = NULL; + m_End = ITK_NULLPTR; } /** Return the current value of the node */ @@ -98,13 +98,9 @@ template< typename TTreeType > bool TreeIteratorBase< TTreeType >::Add(ValueType element) { - if ( m_Position == NULL && m_Root == NULL ) + if ( m_Position == ITK_NULLPTR && m_Root == ITK_NULLPTR ) { - bool returnValue = false; - if ( m_Tree ) - { - returnValue = const_cast< TTreeType * >( m_Tree )->SetRoot(element); - } + bool returnValue = const_cast< TTreeType * >( m_Tree )->SetRoot(element); // signal AddEvent for self m_Root = dynamic_cast< const TreeNodeType * >( const_cast< TTreeType * >( m_Tree )->GetRoot() ); m_Position = const_cast< TreeNodeType * >( m_Root ); @@ -112,7 +108,7 @@ TreeIteratorBase< TTreeType >::Add(ValueType element) m_Tree->InvokeEvent( TreeAddEvent< TTreeType >(*this) ); return returnValue; } - else if ( m_Position == NULL ) + else if ( m_Position == ITK_NULLPTR ) { return false; } @@ -169,7 +165,7 @@ template< typename TTreeType > bool TreeIteratorBase< TTreeType >::IsRoot() const { - if ( m_Root == NULL ) + if ( m_Root == ITK_NULLPTR ) { return false; } @@ -196,13 +192,13 @@ TreeIteratorBase< TTreeType >::Add(TTreeType & subTree) return false; } - if ( m_Root == NULL ) + if ( m_Root == ITK_NULLPTR ) { m_Root = static_cast< const TreeNodeType * >( subTree.GetRoot() ); } else { - if ( m_Position == NULL ) + if ( m_Position == ITK_NULLPTR ) { return false; } @@ -227,11 +223,11 @@ template< typename TTreeType > bool TreeIteratorBase< TTreeType >::HasChild(int number) const { - if ( m_Position == NULL ) + if ( m_Position == ITK_NULLPTR ) { return false; } - if ( m_Position->GetChild(number) != NULL ) + if ( m_Position->GetChild(number) != ITK_NULLPTR ) { return true; } @@ -261,7 +257,7 @@ TreeIteratorBase< TTreeType >::RemoveChild(int number) } TreeNodeType *child = dynamic_cast< TreeNodeType * >( m_Position->GetChild(number) ); - if ( child != NULL ) + if ( child != ITK_NULLPTR ) { // signal PruneEvent (node plus all children are removed) TreeIteratorBase< TTreeType > *childIterator = Clone(); @@ -283,7 +279,7 @@ template< typename TTreeType > int TreeIteratorBase< TTreeType >::CountChildren() const { - if ( m_Position == NULL ) + if ( m_Position == ITK_NULLPTR ) { return -1; } @@ -295,7 +291,7 @@ template< typename TTreeType > bool TreeIteratorBase< TTreeType >::HasParent() const { - return ( m_Position != NULL && m_Position->GetParent() != NULL ); + return ( m_Position != ITK_NULLPTR && m_Position->GetParent() != ITK_NULLPTR ); } /** Disconnect the tree */ @@ -303,7 +299,7 @@ template< typename TTreeType > bool TreeIteratorBase< TTreeType >::Disconnect() { - if ( m_Position == NULL ) + if ( m_Position == ITK_NULLPTR ) { return false; } @@ -331,7 +327,7 @@ TreeIteratorBase< TTreeType >::Disconnect() m_Tree->InvokeEvent( TreeRemoveEvent< TTreeType >(*this) ); - m_Position = NULL; + m_Position = ITK_NULLPTR; return true; } @@ -343,7 +339,7 @@ TreeIteratorBase< TTreeType >::Children() itkGenericOutputMacro("Not implemented yet"); ::itk::ExceptionObject e_(__FILE__, __LINE__, "Not implemented yet", ITK_LOCATION); throw e_; /* Explicit naming to work around Intel compiler bug. */ - return 0; + return ITK_NULLPTR; } /** Return the first parent found */ @@ -351,9 +347,9 @@ template< typename TTreeType > const typename TreeIteratorBase< TTreeType >::TreeNodeType * TreeIteratorBase< TTreeType >::GetParent() const { - if ( m_Position == NULL ) + if ( m_Position == ITK_NULLPTR ) { - return NULL; + return ITK_NULLPTR; } return m_Position->GetParent(); @@ -366,21 +362,21 @@ TreeIteratorBase< TTreeType > *TreeIteratorBase< TTreeType >::Parents() itkGenericOutputMacro("Not implemented yet"); ::itk::ExceptionObject e_(__FILE__, __LINE__, "Not implemented yet", ITK_LOCATION); throw e_; /* Explicit naming to work around Intel compiler bug. */ - return 0; + return ITK_NULLPTR; } /** Go to a child */ template< typename TTreeType > bool TreeIteratorBase< TTreeType >::GoToChild(ChildIdentifier number) { - if ( m_Position == NULL ) + if ( m_Position == ITK_NULLPTR ) { return false; } TreeNodeType *next = dynamic_cast< TreeNodeType * >( m_Position->GetChild(number) ); - if ( next == NULL ) + if ( next == ITK_NULLPTR ) { return false; } @@ -392,7 +388,7 @@ bool TreeIteratorBase< TTreeType >::GoToChild(ChildIdentifier number) template< typename TTreeType > bool TreeIteratorBase< TTreeType >::GoToParent() { - if ( m_Position == NULL ) + if ( m_Position == ITK_NULLPTR ) { return false; } @@ -412,18 +408,18 @@ TreeIteratorBase< TTreeType > *TreeIteratorBase< TTreeType >::GetChild(int numbe { if ( !m_Position ) { - return NULL; + return ITK_NULLPTR; } TreeNodeType *child = dynamic_cast< TreeNodeType * >( m_Position->GetChild(number) ); if ( !child ) { - return NULL; + return ITK_NULLPTR; } // return new WalkTreeIterator<ValueType,P>( child, m_Root, m_Tree, getType() // ); - return NULL; + return ITK_NULLPTR; } /** Count the number of nodes from the beginning */ @@ -481,7 +477,7 @@ template< typename TTreeType > bool TreeIteratorBase< TTreeType >::Remove() { - if ( m_Position == NULL ) + if ( m_Position == ITK_NULLPTR ) { return false; } @@ -497,13 +493,13 @@ TreeIteratorBase< TTreeType >::Remove() } else if ( m_Root == m_Position ) { - m_Root = NULL; - m_Tree->SetRoot( (TreeNodeType *)NULL ); + m_Root = ITK_NULLPTR; + m_Tree->SetRoot( (TreeNodeType *)ITK_NULLPTR ); // this won't do anything if root is already != NULL ==> root cannot be // removed } - m_Position->SetParent(NULL); // we don't have a parent anymore + m_Position->SetParent(ITK_NULLPTR); // we don't have a parent anymore m_Tree->InvokeEvent( TreePruneEvent< TTreeType >(*this) ); while ( m_Position->CountChildren() > 0 ) // remove all children { @@ -512,8 +508,8 @@ TreeIteratorBase< TTreeType >::Remove() m_Position->Remove(child); } - position = NULL; - m_Position = NULL; // Smart pointer, deletes *m_Position + position = ITK_NULLPTR; + m_Position = ITK_NULLPTR; // Smart pointer, deletes *m_Position m_Tree->Modified(); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTreeIteratorClone.h b/Utilities/ITK/Modules/Core/Common/include/itkTreeIteratorClone.h index 0b4b2aa17719208bf13f7ea48667853c76c65b0e..8fdd8dfb66af08b08208cbd008a59b4a014a61d3 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTreeIteratorClone.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkTreeIteratorClone.h @@ -43,8 +43,8 @@ public: /** Copy constructor */ TreeIteratorClone (const TreeIteratorClone< ObjectType > & p) { - m_Pointer = 0; - if ( p.m_Pointer != NULL ) + m_Pointer = ITK_NULLPTR; + if ( p.m_Pointer != ITK_NULLPTR ) { m_Pointer = p.m_Pointer->Clone(); } @@ -63,7 +63,7 @@ public: /** Constructor to reference p */ TreeIteratorClone (const ObjectType & p) { - m_Pointer = 0; + m_Pointer = ITK_NULLPTR; m_Pointer = const_cast< ObjectType * >( &p )->Clone(); } @@ -71,7 +71,7 @@ public: ~TreeIteratorClone () { delete m_Pointer; - m_Pointer = 0; + m_Pointer = ITK_NULLPTR; } /** Overload operator -> */ @@ -112,8 +112,8 @@ public: if ( m_Pointer != r ) { delete m_Pointer; - m_Pointer = 0; - if ( r != NULL ) + m_Pointer = ITK_NULLPTR; + if ( r != ITK_NULLPTR ) { m_Pointer = const_cast< ObjectType * >( r )->Clone(); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTreeNode.h b/Utilities/ITK/Modules/Core/Common/include/itkTreeNode.h index 336217a147851a4b9a5e4995403acdfd7ee6e26e..406080e594e905b764ec41faad8c77524002db8d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTreeNode.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkTreeNode.h @@ -34,19 +34,19 @@ namespace itk * * The class is templated over the type of the elements. * - * \tparam TValueType = Element type stored in the node + * \tparam TValue = Element type stored in the node * * \ingroup DataRepresentation * \ingroup ITKCommon */ -template< typename TValueType > +template< typename TValue > class TreeNode:public Object { public: /** Standard typedefs */ typedef Object Superclass; - typedef TreeNode< TValueType > Self; + typedef TreeNode< TValue > Self; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef std::vector< Pointer > ChildrenListType; @@ -59,10 +59,10 @@ public: itkTypeMacro(TreeNode, Object); /** Get the value of the node */ - const TValueType & Get() const; + const TValue & Get() const; /** Set the current value of the node */ - TValueType Set(const TValueType data); + TValue Set(const TValue data); /** Get the child node */ Self * GetChild(ChildIdentifier number) const; @@ -86,7 +86,7 @@ public: bool Remove(Self *n); /** Get the number of children given a name and depth */ - ChildIdentifier GetNumberOfChildren(unsigned int depth = 0, char *name = NULL) const; + ChildIdentifier GetNumberOfChildren(unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Replace a given child by a new one */ bool ReplaceChild(Self *oldChild, Self *newChild); @@ -95,7 +95,7 @@ public: ChildIdentifier ChildPosition(const Self *node) const; /** Return the child position given a value */ - ChildIdentifier ChildPosition(TValueType node) const; + ChildIdentifier ChildPosition(TValue node) const; /** Add a child to the node */ void AddChild(Self *node); @@ -105,7 +105,7 @@ public: /** Get the children list */ #if !defined( CABLE_CONFIGURATION ) - virtual ChildrenListType * GetChildren(unsigned int depth = 0, char *name = NULL) const; + virtual ChildrenListType * GetChildren(unsigned int depth = 0, char *name = ITK_NULLPTR) const; #endif @@ -115,13 +115,13 @@ public: #endif /** Set the data of the node */ - //virtual void SetData(TValueType data) {m_Data = data;} + //virtual void SetData(TValue data) {m_Data = data;} protected: TreeNode(); virtual ~TreeNode(); - TValueType m_Data; + TValue m_Data; Self *m_Parent; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTreeNode.hxx b/Utilities/ITK/Modules/Core/Common/include/itkTreeNode.hxx index 8daa9f28c7f2fbdb3e86092f9f249ce258d0100b..732db30f29bd785d193e38423966449db3f2b787 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTreeNode.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkTreeNode.hxx @@ -18,20 +18,21 @@ #ifndef __itkTreeNode_hxx #define __itkTreeNode_hxx +#include "itkMacro.h" #include "itkTreeNode.h" #include <cstring> namespace itk { /** Constructor */ -template< typename TValueType > -TreeNode< TValueType > -::TreeNode():m_Parent(NULL) +template< typename TValue > +TreeNode< TValue > +::TreeNode():m_Parent(ITK_NULLPTR) {} /** Destructor */ -template< typename TValueType > -TreeNode< TValueType > +template< typename TValue > +TreeNode< TValue > ::~TreeNode() { if ( m_Parent ) @@ -43,26 +44,26 @@ TreeNode< TValueType > for ( ChildIdentifier i = numberOfChildren; i > 0; i-- ) { - m_Children[i - 1]->SetParent(NULL); + m_Children[i - 1]->SetParent(ITK_NULLPTR); } m_Children.clear(); - m_Parent = NULL; + m_Parent = ITK_NULLPTR; m_Data = 0; } /** Return the parent node */ -template< typename TValueType > -TreeNode< TValueType > * -TreeNode< TValueType > +template< typename TValue > +TreeNode< TValue > * +TreeNode< TValue > ::GetParent() const { return m_Parent; } /** Get a child */ -template< typename TValueType > -TreeNode< TValueType > * -TreeNode< TValueType > +template< typename TValue > +TreeNode< TValue > * +TreeNode< TValue > ::GetChild(ChildIdentifier number) const { const ChildIdentifier numberOfChildren = static_cast< ChildIdentifier >( m_Children.size() ); @@ -73,50 +74,50 @@ TreeNode< TValueType > } else { - return NULL; + return ITK_NULLPTR; } } /** Set the value of a node */ -template< typename TValueType > -TValueType -TreeNode< TValueType > -::Set(const TValueType data) +template< typename TValue > +TValue +TreeNode< TValue > +::Set(const TValue data) { - TValueType help = m_Data; + TValue help = m_Data; m_Data = data; return help; } /** Get the data of node */ -template< typename TValueType > -const TValueType & -TreeNode< TValueType > +template< typename TValue > +const TValue & +TreeNode< TValue > ::Get() const { return m_Data; } /** Return true if has a parent */ -template< typename TValueType > +template< typename TValue > bool -TreeNode< TValueType > +TreeNode< TValue > ::HasParent() const { return ( m_Parent ) ? true : false; } /** Set the parent node */ -template< typename TValueType > +template< typename TValue > void -TreeNode< TValueType > -::SetParent(TreeNode< TValueType > *node) +TreeNode< TValue > +::SetParent(TreeNode< TValue > *node) { //keep ourself alive just a bit longer Pointer ourself = this; - if ( m_Parent != NULL ) + if ( m_Parent != ITK_NULLPTR ) { m_Parent->Remove(this); } @@ -124,27 +125,27 @@ TreeNode< TValueType > } /** Return true if the node has children */ -template< typename TValueType > +template< typename TValue > bool -TreeNode< TValueType > +TreeNode< TValue > ::HasChildren() const { return ( m_Children.size() > 0 ) ? true : false; } /** Return the number of children */ -template< typename TValueType > -typename TreeNode< TValueType >::ChildIdentifier -TreeNode< TValueType > +template< typename TValue > +typename TreeNode< TValue >::ChildIdentifier +TreeNode< TValue > ::CountChildren() const { return static_cast< ChildIdentifier >( m_Children.size() ); } /** Remove a child node from the current node */ -template< typename TValueType > +template< typename TValue > bool -TreeNode< TValueType > +TreeNode< TValue > ::Remove(Self *n) { typename std::vector< Pointer >::iterator pos; @@ -154,16 +155,16 @@ TreeNode< TValueType > //keep node alive just a bit longer Pointer position = n; m_Children.erase(pos); - n->SetParent(NULL); + n->SetParent(ITK_NULLPTR); return true; } return false; } /** Replace a child by a new one */ -template< typename TValueType > +template< typename TValue > bool -TreeNode< TValueType > +TreeNode< TValue > ::ReplaceChild(Self *oldChild, Self *newChild) { const ChildIdentifier numberOfChildren = static_cast< ChildIdentifier >( m_Children.size() ); @@ -180,9 +181,9 @@ TreeNode< TValueType > } /** Return the child position given a node */ -template< typename TValueType > +template< typename TValue > OffsetValueType -TreeNode< TValueType > +TreeNode< TValue > ::ChildPosition(const Self *node) const { const ChildIdentifier numberOfChildren = static_cast< ChildIdentifier >( m_Children.size() ); @@ -198,10 +199,10 @@ TreeNode< TValueType > } /** Return the child position given an element, the first child found. */ -template< typename TValueType > -typename TreeNode< TValueType >::ChildIdentifier -TreeNode< TValueType > -::ChildPosition(TValueType element) const +template< typename TValue > +typename TreeNode< TValue >::ChildIdentifier +TreeNode< TValue > +::ChildPosition(TValue element) const { const ChildIdentifier numberOfChildren = static_cast< ChildIdentifier >( m_Children.size() ); @@ -216,9 +217,9 @@ TreeNode< TValueType > } /** Add a child node */ -template< typename TValueType > +template< typename TValue > void -TreeNode< TValueType > +TreeNode< TValue > ::AddChild(Self *node) { Pointer nodeKeepAlive = node; @@ -228,9 +229,9 @@ TreeNode< TValueType > } /** Add a child at a specific position in the children list */ -template< typename TValueType > +template< typename TValue > void -TreeNode< TValueType > +TreeNode< TValue > ::AddChild(ChildIdentifier number, Self *node) { const ChildIdentifier numberOfChildren = static_cast< ChildIdentifier >( m_Children.size() ); @@ -241,7 +242,7 @@ TreeNode< TValueType > m_Children.resize(childId); for ( ChildIdentifier i = numberOfChildren; i <= childId; i++ ) { - m_Children[i] = NULL; + m_Children[i] = ITK_NULLPTR; } m_Children[number] = node; return; @@ -251,9 +252,9 @@ TreeNode< TValueType > } /** Get the number of children given a name and a depth */ -template< typename TValueType > -typename TreeNode< TValueType >::ChildIdentifier -TreeNode< TValueType > +template< typename TValue > +typename TreeNode< TValue >::ChildIdentifier +TreeNode< TValue > ::GetNumberOfChildren(unsigned int depth, char *name) const { typename ChildrenListType::const_iterator it = m_Children.begin(); @@ -262,7 +263,7 @@ TreeNode< TValueType > ChildIdentifier cnt = 0; while ( it != itEnd ) { - if ( name == NULL || strstr(typeid( **it ).name(), name) ) + if ( name == ITK_NULLPTR || strstr(typeid( **it ).name(), name) ) { ++cnt; } @@ -285,9 +286,9 @@ TreeNode< TValueType > /** Get children given a name and a depth */ #if !defined( CABLE_CONFIGURATION ) -template< typename TValueType > -typename TreeNode< TValueType >::ChildrenListType * -TreeNode< TValueType > +template< typename TValue > +typename TreeNode< TValue >::ChildrenListType * +TreeNode< TValue > ::GetChildren(unsigned int depth, char *name) const { ChildrenListType *children = new ChildrenListType; @@ -299,7 +300,7 @@ TreeNode< TValueType > while ( childrenListIt != childrenListEnd ) { - if ( name == NULL || strstr(typeid( **childrenListIt ).name(), name) ) + if ( name == ITK_NULLPTR || strstr(typeid( **childrenListIt ).name(), name) ) { children->push_back(*childrenListIt); } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTriangleCell.hxx b/Utilities/ITK/Modules/Core/Common/include/itkTriangleCell.hxx index 745beb095694267eefddd975b8beab28b1ece845..52b280b757ca224506d84351dbb4abc6f56fe52d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTriangleCell.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkTriangleCell.hxx @@ -374,7 +374,7 @@ TriangleCell< TCellInterface >::ComputeArea(PointsContainer *iPoints) CoordRepType c = p[1].EuclideanDistanceTo(p[0]); CoordRepType s = 0.5 * ( a + b + c ); - return vcl_sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) ); + return std::sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) ); } template< typename TCellInterface > @@ -507,7 +507,6 @@ TriangleCell< TCellInterface > // u32 is orthogonal to v12 // const double dotproduct = v12 * v32; - typedef typename VectorType::ValueType VectorValueType; VectorType u12 = v12 - v32 * ( dotproduct / v32.GetSquaredNorm() ); VectorType u32 = v32 - v12 * ( dotproduct / v12.GetSquaredNorm() ); diff --git a/Utilities/ITK/Modules/Core/Common/include/itkTriangleHelper.hxx b/Utilities/ITK/Modules/Core/Common/include/itkTriangleHelper.hxx index 20ef3b69f59bd75be3c394d105dab4fdb71c9fcd..73946e8f73d94627c14bfbe338279a0ee9ff994b 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkTriangleHelper.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkTriangleHelper.hxx @@ -65,7 +65,7 @@ TriangleHelper< TPoint >::ComputeNormal(const PointType & iA, if ( l2 != 0.0 ) { - w /= vcl_sqrt(l2); + w /= std::sqrt(l2); } return w; @@ -83,14 +83,14 @@ TriangleHelper< TPoint >::Cotangent(const PointType & iA, if ( v21_l2 != NumericTraits< CoordRepType >::Zero ) { - v21 /= vcl_sqrt(v21_l2); + v21 /= std::sqrt(v21_l2); } VectorType v23 = iC - iB; CoordRepType v23_l2 = v23.GetSquaredNorm(); if ( v23_l2 != NumericTraits< CoordRepType >::Zero ) { - v23 /= vcl_sqrt(v23_l2); + v23 /= std::sqrt(v23_l2); } CoordRepType bound(0.999999); @@ -98,7 +98,7 @@ TriangleHelper< TPoint >::Cotangent(const PointType & iA, CoordRepType cos_theta = vnl_math_max( -bound, vnl_math_min(bound, v21 * v23) ); - return 1.0 / vcl_tan( vcl_acos(cos_theta) ); + return 1.0 / std::tan( std::acos(cos_theta) ); } template< typename TPoint > @@ -146,11 +146,11 @@ TriangleHelper< TPoint >::ComputeAngle(const PointType & iP1, if ( v21_l2 != 0.0 ) { - v21 /= vcl_sqrt(v21_l2); + v21 /= std::sqrt(v21_l2); } if ( v23_l2 != 0.0 ) { - v23 /= vcl_sqrt(v23_l2); + v23 /= std::sqrt(v23_l2); } CoordRepType bound(0.999999); @@ -158,7 +158,7 @@ TriangleHelper< TPoint >::ComputeAngle(const PointType & iP1, CoordRepType cos_theta = vnl_math_max( -bound, vnl_math_min(bound, v21 * v23) ); - return vcl_acos(cos_theta); + return std::acos(cos_theta); } template< typename TPoint > @@ -233,7 +233,7 @@ TriangleHelper< TPoint >::ComputeArea(const PointType & iP1, CoordRepType s = 0.5 * ( a + b + c ); - return static_cast< CoordRepType >( vcl_sqrt ( s * ( s - a ) * ( s - b ) * ( s - c ) ) ); + return static_cast< CoordRepType >( std::sqrt ( s * ( s - a ) * ( s - b ) * ( s - c ) ) ); } template< typename TPoint > diff --git a/Utilities/ITK/Modules/Core/Common/include/itkValarrayImageContainer.h b/Utilities/ITK/Modules/Core/Common/include/itkValarrayImageContainer.h index a2d5ecefa8d8f637f849a252a6ce9d6a689f32f8..1ff33d1935104488321853cbf060fa312f255660 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkValarrayImageContainer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkValarrayImageContainer.h @@ -106,7 +106,7 @@ public: } else { - return NULL; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVariableLengthVector.h b/Utilities/ITK/Modules/Core/Common/include/itkVariableLengthVector.h index 3b339e1aaaa501d822f97455db1d31c29ee832d8..1cafed39babc570be93e3b8148dac8668afeae0d 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVariableLengthVector.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkVariableLengthVector.h @@ -72,14 +72,14 @@ namespace itk * \wikiexample{SimpleOperations/VariableLengthVector,Variable length vector} * \endwiki */ -template< typename TValueType > +template< typename TValue > class VariableLengthVector { public: /** The element type stored at each location in the Array. */ - typedef TValueType ValueType; - typedef TValueType ComponentType; + typedef TValue ValueType; + typedef TValue ComponentType; typedef typename NumericTraits< ValueType >::RealType RealValueType; typedef VariableLengthVector Self; @@ -134,14 +134,14 @@ public: /** Copy constructer.. Override the default non-templated copy constructor * that the compiler provides */ - VariableLengthVector(const VariableLengthVector< TValueType > & v); + VariableLengthVector(const VariableLengthVector< TValue > & v); /** Set the all the elements of the array to the specified value */ - void Fill(TValueType const & v); + void Fill(TValue const & v); /** Assignment operator */ template< typename T > - const VariableLengthVector< TValueType > & operator= + const VariableLengthVector< TValue > & operator= (const VariableLengthVector< T > & v) { if ( m_Data == static_cast< void * >( const_cast< T * > @@ -160,22 +160,22 @@ public: /** Assignment operators */ const Self & operator=(const Self & v); - const Self & operator=(TValueType const & v); + const Self & operator=(TValue const & v); /** Return the number of elements in the Array */ inline unsigned int Size(void) const { return m_NumElements; } inline unsigned int GetNumberOfElements(void) const { return m_NumElements; } /** Return reference to the element at specified index. No range checking. */ - TValueType & operator[](unsigned int i) { return this->m_Data[i]; } + TValue & operator[](unsigned int i) { return this->m_Data[i]; } /** Return reference to the element at specified index. No range checking. */ - TValueType const & operator[](unsigned int i) const { return this->m_Data[i]; } + TValue const & operator[](unsigned int i) const { return this->m_Data[i]; } /** Get one element */ - inline const TValueType & GetElement(unsigned int i) const { return m_Data[i]; } + inline const TValue & GetElement(unsigned int i) const { return m_Data[i]; } /** Set one element */ - void SetElement(unsigned int i, const TValueType & value) { m_Data[i] = value; } + void SetElement(unsigned int i, const TValue & value) { m_Data[i] = value; } /** Set the size to that given. * @@ -200,7 +200,7 @@ public: * the responsibility of freeing the memory for this data. If * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. */ - void SetData(TValueType *data, bool LetArrayManageMemory = false); + void SetData(TValue *data, bool LetArrayManageMemory = false); /** Similar to the previous method. In the above method, the size must be * separately set prior to using user-supplied data. This introduces an @@ -211,7 +211,7 @@ public: * the responsibility of freeing the memory for this data. If * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. */ - void SetData(TValueType *data, unsigned int sz, bool LetArrayManageMemory = false); + void SetData(TValue *data, unsigned int sz, bool LetArrayManageMemory = false); /** This destructor is not virtual for performance reasons. However, this * means that subclasses cannot allocate memory. */ @@ -226,9 +226,9 @@ public: void Reserve(ElementIdentifier); /** Allocate memory of certain size and return it. */ - TValueType * AllocateElements(ElementIdentifier size) const; + TValue * AllocateElements(ElementIdentifier size) const; - const TValueType * GetDataPointer() const { return m_Data; } + const TValue * GetDataPointer() const { return m_Data; } /** Element-wise vector addition. The vectors do not have to have * the same element type. The input vector elements are cast to the @@ -316,7 +316,7 @@ public: } /** Add scalar 's' to each element of the vector.*/ - inline Self operator+(TValueType s) const + inline Self operator+(TValue s) const { Self result(m_NumElements); @@ -328,7 +328,7 @@ public: } /** Subtract scalar 's' from each element of the vector.*/ - inline Self operator-(TValueType s) const + inline Self operator-(TValue s) const { Self result(m_NumElements); @@ -398,7 +398,7 @@ public: } /** Subtract scalar 's' from each element of the current vector. */ - inline Self & operator-=(TValueType s) + inline Self & operator-=(TValue s) { for ( ElementIdentifier i = 0; i < m_NumElements; i++ ) { @@ -426,7 +426,7 @@ public: } /** Add scalar 's' to each element of the vector. */ - inline Self & operator+=(TValueType s) + inline Self & operator+=(TValue s) { for ( ElementIdentifier i = 0; i < m_NumElements; i++ ) { @@ -481,23 +481,24 @@ private: bool m_LetArrayManageMemory; // if true, the array is responsible // for memory of data - TValueType * m_Data; // Array to hold data + TValue * m_Data; // Array to hold data ElementIdentifier m_NumElements; }; /** Premultiply Operator for product of a VariableLengthVector and a scalar. - * VariableLengthVector< TValueType > = T * VariableLengthVector< TValueType > + * VariableLengthVector< TValue > = T * VariableLengthVector< TValue > */ -template< typename TValueType, typename T > +template< typename TValue, typename T > inline -VariableLengthVector< TValueType > -operator*(const T & scalar, const VariableLengthVector< TValueType > & v) +VariableLengthVector< TValue > +operator*(const T & scalar, const VariableLengthVector< TValue > & v) { - return v * scalar; + return v.operator*(scalar); } -template< typename TValueType > -std::ostream & operator<<(std::ostream & os, const VariableLengthVector< TValueType > & arr) + +template< typename TValue > +std::ostream & operator<<(std::ostream & os, const VariableLengthVector< TValue > & arr) { const unsigned int length = arr.Size(); const signed int last = (unsigned int)length - 1; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVariableLengthVector.hxx b/Utilities/ITK/Modules/Core/Common/include/itkVariableLengthVector.hxx index 50134672e4a015b9dde447f08b42623290823063..fbe93d1c7624167c9987551618152fcbad940367 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVariableLengthVector.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkVariableLengthVector.hxx @@ -26,26 +26,26 @@ namespace itk { /** Default constructor */ -template< typename TValueType > -VariableLengthVector< TValueType > +template< typename TValue > +VariableLengthVector< TValue > ::VariableLengthVector():m_LetArrayManageMemory(true), - m_Data(0), + m_Data(ITK_NULLPTR), m_NumElements(0) {} /** Constructor with size */ -template< typename TValueType > -VariableLengthVector< TValueType > +template< typename TValue > +VariableLengthVector< TValue > ::VariableLengthVector(unsigned int length): m_LetArrayManageMemory(true), - m_Data(0) + m_Data(ITK_NULLPTR) { Reserve(length); } /** Constructor with user specified data */ -template< typename TValueType > -VariableLengthVector< TValueType > +template< typename TValue > +VariableLengthVector< TValue > ::VariableLengthVector(ValueType *datain, unsigned int sz, bool LetArrayManageMemory): m_LetArrayManageMemory(LetArrayManageMemory), m_Data(datain), @@ -53,8 +53,8 @@ VariableLengthVector< TValueType > {} /** Constructor with user specified data */ -template< typename TValueType > -VariableLengthVector< TValueType > +template< typename TValue > +VariableLengthVector< TValue > ::VariableLengthVector(const ValueType *datain, unsigned int sz, bool LetArrayManageMemory): m_LetArrayManageMemory(LetArrayManageMemory) { @@ -64,9 +64,9 @@ VariableLengthVector< TValueType > /** Copy constructer.. Override the default non-templated copy constructor * that the compiler provides */ -template< typename TValueType > -VariableLengthVector< TValueType > -::VariableLengthVector(const VariableLengthVector< TValueType > & v) +template< typename TValue > +VariableLengthVector< TValue > +::VariableLengthVector(const VariableLengthVector< TValue > & v) { m_NumElements = v.Size(); m_Data = this->AllocateElements(m_NumElements); @@ -78,8 +78,8 @@ VariableLengthVector< TValueType > } /** Destructor */ -template< typename TValueType > -VariableLengthVector< TValueType > +template< typename TValue > +VariableLengthVector< TValue > ::~VariableLengthVector() { // if data exists and we are responsible for its memory, get rid of it.. @@ -90,15 +90,15 @@ VariableLengthVector< TValueType > } /** Reserve memory of certain size for m_Data */ -template< typename TValueType > -void VariableLengthVector< TValueType > +template< typename TValue > +void VariableLengthVector< TValue > ::Reserve(ElementIdentifier size) { if ( m_Data ) { if ( size > m_NumElements ) { - TValueType *temp = this->AllocateElements(size); + TValue *temp = this->AllocateElements(size); // only copy the portion of the data used in the old buffer std::copy(m_Data, m_Data+m_NumElements, @@ -121,19 +121,19 @@ void VariableLengthVector< TValueType > } /** Allocate memory of certain size and return it */ -template< typename TValueType > -TValueType *VariableLengthVector< TValueType > +template< typename TValue > +TValue *VariableLengthVector< TValue > ::AllocateElements(ElementIdentifier size) const { - TValueType *data; + TValue *data; try { - data = new TValueType[size]; + data = new TValue[size]; } catch ( ... ) { - data = 0; + data = ITK_NULLPTR; } if ( !data ) { @@ -149,10 +149,10 @@ TValueType *VariableLengthVector< TValueType > * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. Note that you need to explicitly * set the number of elements. */ -template< typename TValueType > +template< typename TValue > void -VariableLengthVector< TValueType > -::SetData(TValueType *datain, bool LetArrayManageMemory) +VariableLengthVector< TValue > +::SetData(TValue *datain, bool LetArrayManageMemory) { // Free any existing data if we manage its memory if ( m_LetArrayManageMemory ) @@ -173,10 +173,10 @@ VariableLengthVector< TValueType > * the responsibility of freeing the memory for this data. If * "LetArrayManageMemory" is true, then this class will free the * memory when this object is destroyed. */ -template< typename TValueType > +template< typename TValue > void -VariableLengthVector< TValueType > -::SetData(TValueType *datain, unsigned int sz, bool LetArrayManageMemory) +VariableLengthVector< TValue > +::SetData(TValue *datain, unsigned int sz, bool LetArrayManageMemory) { // Free any existing data if we manage its memory if ( m_LetArrayManageMemory ) @@ -190,14 +190,14 @@ VariableLengthVector< TValueType > } -template< typename TValueType > -void VariableLengthVector< TValueType > +template< typename TValue > +void VariableLengthVector< TValue > ::DestroyExistingData() { // Free any existing data if we manage its memory. if ( !m_LetArrayManageMemory ) { - m_Data = 0; + m_Data = ITK_NULLPTR; m_NumElements = 0; return; } @@ -207,14 +207,14 @@ void VariableLengthVector< TValueType > if ( m_NumElements > 0 ) { delete[] m_Data; - m_Data = 0; + m_Data = ITK_NULLPTR; m_NumElements = 0; } } } -template< typename TValueType > -void VariableLengthVector< TValueType > +template< typename TValue > +void VariableLengthVector< TValue > ::SetSize(unsigned int sz, bool destroyExistingData) { if ( destroyExistingData ) @@ -230,7 +230,7 @@ void VariableLengthVector< TValueType > return; } - TValueType *temp = this->AllocateElements(sz); + TValue *temp = this->AllocateElements(sz); if ( sz > m_NumElements ) { @@ -258,9 +258,9 @@ void VariableLengthVector< TValueType > } /** Set the all the elements of the array to the specified value */ -template< typename TValueType > -void VariableLengthVector< TValueType > -::Fill(TValueType const & v) +template< typename TValue > +void VariableLengthVector< TValue > +::Fill(TValue const & v) { for ( ElementIdentifier i = 0; i < m_NumElements; i++ ) { @@ -269,9 +269,9 @@ void VariableLengthVector< TValueType > } /** Assignment operator */ -template< typename TValueType > -const VariableLengthVector< TValueType > & -VariableLengthVector< TValueType > +template< typename TValue > +const VariableLengthVector< TValue > & +VariableLengthVector< TValue > ::operator=(const Self & v) { if ( this != &v ) @@ -286,18 +286,18 @@ VariableLengthVector< TValueType > } /** Assignment operator */ -template< typename TValueType > -const VariableLengthVector< TValueType > & -VariableLengthVector< TValueType > -::operator=(TValueType const & v) +template< typename TValue > +const VariableLengthVector< TValue > & +VariableLengthVector< TValue > +::operator=(TValue const & v) { this->Fill(v); return *this; } -template< typename TValueType > -VariableLengthVector< TValueType > & -VariableLengthVector< TValueType > +template< typename TValue > +VariableLengthVector< TValue > & +VariableLengthVector< TValue > ::operator-() { for ( ElementIdentifier i = 0; i < m_NumElements; i++ ) @@ -307,9 +307,9 @@ VariableLengthVector< TValueType > return *this; } -template< typename TValueType > +template< typename TValue > bool -VariableLengthVector< TValueType > +VariableLengthVector< TValue > ::operator==(const Self & v) const { if ( m_NumElements != v.Size() ) @@ -326,9 +326,9 @@ VariableLengthVector< TValueType > return true; } -template< typename TValueType > +template< typename TValue > bool -VariableLengthVector< TValueType > +VariableLengthVector< TValue > ::operator!=(const Self & v) const { if ( m_NumElements != v.Size() ) @@ -348,20 +348,20 @@ VariableLengthVector< TValueType > /** * Returns vector's Euclidean Norm */ -template< typename TValueType > -typename VariableLengthVector< TValueType >::RealValueType -VariableLengthVector< TValueType > +template< typename TValue > +typename VariableLengthVector< TValue >::RealValueType +VariableLengthVector< TValue > ::GetNorm(void) const { - return (RealValueType)( vcl_sqrt( double( this->GetSquaredNorm() ) ) ); + return (RealValueType)( std::sqrt( double( this->GetSquaredNorm() ) ) ); } /** * Returns vector's Squared Euclidean Norm */ -template< typename TValueType > -typename VariableLengthVector< TValueType >::RealValueType -VariableLengthVector< TValueType > +template< typename TValue > +typename VariableLengthVector< TValue >::RealValueType +VariableLengthVector< TValue > ::GetSquaredNorm(void) const { RealValueType sum = 0.0; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVector.h b/Utilities/ITK/Modules/Core/Common/include/itkVector.h index 334bc78389abadbbd58387e7c5270908530840b5..0af2f4c55a63e88be075808f376f0338683e3dd1 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVector.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkVector.h @@ -252,7 +252,7 @@ inline Vector< T, NVectorDimension > operator*(const T & scalar, const Vector< T, NVectorDimension > & v) { - return v * scalar; + return v.operator*( scalar); } /** Print content to an ostream */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVector.hxx b/Utilities/ITK/Modules/Core/Common/include/itkVector.hxx index 332aa443d9e922295fada168dbeecdfa800398fc..7c953f7be0a8e2434567e345c59ba424d160dbb3 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVector.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkVector.hxx @@ -129,7 +129,7 @@ typename Vector< T, TVectorDimension >::RealValueType Vector< T, TVectorDimension > ::GetNorm(void) const { - return RealValueType( vcl_sqrt( double( this->GetSquaredNorm() ) ) ); + return RealValueType( std::sqrt( double( this->GetSquaredNorm() ) ) ); } template< typename T, unsigned int TVectorDimension > diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVectorContainer.h b/Utilities/ITK/Modules/Core/Common/include/itkVectorContainer.h index f7c6f05b4fd0fe39576ab6921fdfe6aff4a21e03..bc029c6a739bfedac3666a479c6afbfcda40bda8 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVectorContainer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkVectorContainer.h @@ -200,7 +200,7 @@ private: class ConstIterator { public: - ConstIterator() {} + ConstIterator():m_Pos(0) {} ConstIterator(size_type d, const VectorConstIterator & i):m_Pos(d), m_Iter(i) {} ConstIterator(const Iterator & r) { m_Pos = r.m_Pos; m_Iter = r.m_Iter; } ConstIterator & operator*() { return *this; } diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVectorImage.h b/Utilities/ITK/Modules/Core/Common/include/itkVectorImage.h index 16efe49daefc9058ef928a593d6e040adb2707fc..fada3d66eb556ce3ea5088d82a0f5f2ed2b93729 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVectorImage.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkVectorImage.h @@ -198,7 +198,7 @@ public: /** Allocate the image memory. The size of the image must * already be set, e.g. by calling SetRegions(). */ - void Allocate(); + virtual void Allocate(bool UseDefaultConstructor = false) ITK_OVERRIDE; /** Restore the data object to its initial state. This means releasing * memory. */ @@ -276,11 +276,11 @@ public: * the image iterator class. */ InternalPixelType * GetBufferPointer() { - return m_Buffer ? m_Buffer->GetBufferPointer() : 0; + return m_Buffer ? m_Buffer->GetBufferPointer() : ITK_NULLPTR; } const InternalPixelType * GetBufferPointer() const { - return m_Buffer ? m_Buffer->GetBufferPointer() : 0; + return m_Buffer ? m_Buffer->GetBufferPointer() : ITK_NULLPTR; } /** Return a pointer to the container. */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVectorImage.hxx b/Utilities/ITK/Modules/Core/Common/include/itkVectorImage.hxx index 910cb11d94af6f772cda35bc128aac864dd0a1c3..e59629fd919ef6ca366721fd378cf24c9f6ecf16 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVectorImage.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkVectorImage.hxx @@ -47,7 +47,7 @@ VectorImage< TPixel, VImageDimension > template< typename TPixel, unsigned int VImageDimension > void VectorImage< TPixel, VImageDimension > -::Allocate() +::Allocate(const bool UseDefaultConstructor) { if ( m_VectorLength == 0 ) { @@ -58,7 +58,7 @@ VectorImage< TPixel, VImageDimension > this->ComputeOffsetTable(); num = this->GetOffsetTable()[VImageDimension]; - m_Buffer->Reserve(num * m_VectorLength); + m_Buffer->Reserve(num * m_VectorLength,UseDefaultConstructor); } template< typename TPixel, unsigned int VImageDimension > @@ -117,38 +117,27 @@ void VectorImage< TPixel, VImageDimension > ::Graft(const DataObject *data) { + if(data == ITK_NULLPTR) + { + return; + } // call the superclass' implementation Superclass::Graft(data); - if ( data ) - { - // Attempt to cast data to an Image - const Self *imgData; + // Attempt to cast data to an Image + const Self *imgData = dynamic_cast< const Self * >( data ); - try - { - imgData = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - return; - } - - // Copy from VectorImage< TPixel, dim > - if ( imgData ) - { - // Now copy anything remaining that is needed - this->SetPixelContainer( const_cast< PixelContainer * > - ( imgData->GetPixelContainer() ) ); - } - else - { - // pointer could not be cast back down - itkExceptionMacro( << "itk::VectorImage::Graft() cannot cast " - << typeid( data ).name() << " to " - << typeid( const Self * ).name() ); - } + if( imgData == ITK_NULLPTR ) + { + // pointer could not be cast back down + itkExceptionMacro( << "itk::VectorImage::Graft() cannot cast " + << typeid( data ).name() << " to " + << typeid( const Self * ).name() ); } + // Copy from VectorImage< TPixel, dim > + // Now copy anything remaining that is needed + this->SetPixelContainer( const_cast< PixelContainer * > + ( imgData->GetPixelContainer() ) ); } //---------------------------------------------------------------------------- diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVectorImageNeighborhoodAccessorFunctor.h b/Utilities/ITK/Modules/Core/Common/include/itkVectorImageNeighborhoodAccessorFunctor.h index 81e6f09038cf918553e16b1c195bc08216d4bcc7..42eb9d26185d92292e4635c0642213a4d463bce6 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVectorImageNeighborhoodAccessorFunctor.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkVectorImageNeighborhoodAccessorFunctor.h @@ -54,9 +54,9 @@ public: *ImageBoundaryConditionConstPointerType; VectorImageNeighborhoodAccessorFunctor(VectorLengthType length): - m_VectorLength(length), m_OffsetMultiplier(length - 1), m_Begin(NULL) {} + m_VectorLength(length), m_OffsetMultiplier(length - 1), m_Begin(ITK_NULLPTR) {} VectorImageNeighborhoodAccessorFunctor(): - m_VectorLength(0), m_OffsetMultiplier(0), m_Begin(NULL) {} + m_VectorLength(0), m_OffsetMultiplier(0), m_Begin(ITK_NULLPTR) {} /** Set the pointer index to the start of the buffer. * This must be set by the iterators to the starting location of the buffer. diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVersor.h b/Utilities/ITK/Modules/Core/Common/include/itkVersor.h index 3deab342cdb8d1b3a8fa74150503e55d657d4490..7f2b4d854a1335f2d406150a5f9c021c59757aaa 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVersor.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkVersor.h @@ -203,7 +203,7 @@ public: /** Set the versor using the right part. * the magnitude of the vector given is assumed to - * be equal to vcl_sin(angle/2). + * be equal to std::sin(angle/2). * This method will compute internally the scalar * part that preserve the Versor as a unit quaternion. */ void Set(const VectorType & axis); @@ -271,7 +271,7 @@ private: } static inline ValueType Epsilon() { - return Epsilon((ValueType *)0); + return Epsilon((ValueType *)ITK_NULLPTR); } /** Component parallel to x axis. */ diff --git a/Utilities/ITK/Modules/Core/Common/include/itkVersor.hxx b/Utilities/ITK/Modules/Core/Common/include/itkVersor.hxx index e388e602c64e96d3a8d442110918f3bbb4c05fce..66d138c4b215d8e440f2370a8b8829cee9335f55 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkVersor.hxx +++ b/Utilities/ITK/Modules/Core/Common/include/itkVersor.hxx @@ -174,7 +174,7 @@ Versor< T > const double epsilon = 1e-300; - if ( vcl_fabs(1.0f - square) < epsilon ) + if ( std::fabs(1.0f - square) < epsilon ) { return true; } @@ -222,7 +222,7 @@ Versor< T > { const ValueType tensor = static_cast< ValueType >( - vcl_sqrt(m_X * m_X + m_Y * m_Y + m_Z * m_Z + m_W * m_W) ); + std::sqrt(m_X * m_X + m_Y * m_Y + m_Z * m_Z + m_W * m_W) ); return tensor; } @@ -235,7 +235,7 @@ Versor< T > { const ValueType tensor = this->GetTensor(); - if ( vcl_fabs(tensor) < 1e-20 ) + if ( std::fabs(tensor) < 1e-20 ) { ExceptionObject except; except.SetDescription("Attempt to normalize a \ @@ -261,7 +261,7 @@ Versor< T > const RealType ay = static_cast< RealType >( m_Y ); const RealType az = static_cast< RealType >( m_Z ); - const RealType vectorNorm = vcl_sqrt(ax * ax + ay * ay + az * az); + const RealType vectorNorm = std::sqrt(ax * ax + ay * ay + az * az); if ( vectorNorm == NumericTraits< RealType >::Zero ) { @@ -313,9 +313,9 @@ Versor< T > const RealType ay = static_cast< RealType >( m_Y ); const RealType az = static_cast< RealType >( m_Z ); - const RealType vectorNorm = vcl_sqrt(ax * ax + ay * ay + az * az); + const RealType vectorNorm = std::sqrt(ax * ax + ay * ay + az * az); - const ValueType angle = 2.0 * vcl_atan2( vectorNorm, static_cast< RealType >( m_W ) ); + const ValueType angle = 2.0 * std::atan2( vectorNorm, static_cast< RealType >( m_W ) ); return angle; } @@ -326,8 +326,8 @@ Versor< T > Versor< T > ::SquareRoot(void) const { - const ValueType newScalar = vcl_sqrt( static_cast< double >( 1.0 + m_W ) ); - const double sqrtOfTwo = vcl_sqrt(2.0f); + const ValueType newScalar = std::sqrt( static_cast< double >( 1.0 + m_W ) ); + const double sqrtOfTwo = std::sqrt(2.0f); const double factor = 1.0f / ( newScalar * sqrtOfTwo ); @@ -363,8 +363,8 @@ Versor< T > { const RealType vectorNorm = axis.GetNorm(); - const RealType cosangle2 = vcl_cos(angle / 2.0); - const RealType sinangle2 = vcl_sin(angle / 2.0); + const RealType cosangle2 = std::cos(angle / 2.0); + const RealType sinangle2 = std::sin(angle / 2.0); const RealType factor = sinangle2 / vectorNorm; @@ -385,30 +385,30 @@ Versor< T > //Keep the epsilon value large enough so that the alternate routes of //computing the quaternion are used to within floating point precision of the //math to be used. Using 1e-30 results in degenerate matries for rotations - //near vnl_math::pi due to imprecision of the math. 0.5/vcl_sqrt(trace) is + //near vnl_math::pi due to imprecision of the math. 0.5/std::sqrt(trace) is //not accurate to 1e-30, so the resulting matrices would have very large //errors. By decreasing this epsilon value to a higher tolerance, the //alternate stable methods for conversion are used. // - //The use of vcl_numeric_limits< T >::epsilon() was not consistent with + //The use of std::numeric_limits< T >::epsilon() was not consistent with //the rest of the ITK toolkit with respect to epsilon values for //determining rotational orthogonality, and it occasionally //prevented the conversion between different rigid transform types. - const T epsilon = Self::Epsilon(); // vnl_sqrt( vcl_numeric_limits< T >::epsilon() ); + const T epsilon = Self::Epsilon(); // vnl_sqrt( std::numeric_limits< T >::epsilon() ); // Use a slightly less epsilon for detecting difference - const T epsilonDiff = Self::Epsilon(); //vcl_numeric_limits< T >::epsilon() * 10.0; + const T epsilonDiff = Self::Epsilon(); //std::numeric_limits< T >::epsilon() * 10.0; const vnl_matrix< T > m( mat.GetVnlMatrix() ); //check for orthonormality and that it isn't a reflection const vnl_matrix_fixed< T, 3, 3 > & I = m*m.transpose(); - if( vcl_abs( I[0][1] ) > epsilon || vcl_abs( I[0][2] ) > epsilon || - vcl_abs( I[1][0] ) > epsilon || vcl_abs( I[1][2] ) > epsilon || - vcl_abs( I[2][0] ) > epsilon || vcl_abs( I[2][1] ) > epsilon || - vcl_abs( I[0][0] - itk::NumericTraits<T>::One ) > epsilonDiff || - vcl_abs( I[1][1] - itk::NumericTraits<T>::One ) > epsilonDiff || - vcl_abs( I[2][2] - itk::NumericTraits<T>::One ) > epsilonDiff || + if( std::abs( I[0][1] ) > epsilon || std::abs( I[0][2] ) > epsilon || + std::abs( I[1][0] ) > epsilon || std::abs( I[1][2] ) > epsilon || + std::abs( I[2][0] ) > epsilon || std::abs( I[2][1] ) > epsilon || + std::abs( I[0][0] - itk::NumericTraits<T>::One ) > epsilonDiff || + std::abs( I[1][1] - itk::NumericTraits<T>::One ) > epsilonDiff || + std::abs( I[2][2] - itk::NumericTraits<T>::One ) > epsilonDiff || vnl_det( I ) < 0 ) { itkGenericExceptionMacro(<< "The following matrix does not represent rotation to within an epsion of " @@ -423,7 +423,7 @@ Versor< T > if ( trace > epsilon ) { - const double s = 0.5 / vcl_sqrt(trace); + const double s = 0.5 / std::sqrt(trace); m_W = 0.25 / s; m_X = ( m(2, 1) - m(1, 2) ) * s; m_Y = ( m(0, 2) - m(2, 0) ) * s; @@ -433,7 +433,7 @@ Versor< T > { if ( m(0, 0) > m(1, 1) && m(0, 0) > m(2, 2) ) { - const double s = 2.0 * vcl_sqrt( 1.0 + m(0, 0) - m(1, 1) - m(2, 2) ); + const double s = 2.0 * std::sqrt( 1.0 + m(0, 0) - m(1, 1) - m(2, 2) ); m_X = 0.25 * s; m_Y = ( m(0, 1) + m(1, 0) ) / s; m_Z = ( m(0, 2) + m(2, 0) ) / s; @@ -443,7 +443,7 @@ Versor< T > { if ( m(1, 1) > m(2, 2) ) { - const double s = 2.0 * vcl_sqrt( 1.0 + m(1, 1) - m(0, 0) - m(2, 2) ); + const double s = 2.0 * std::sqrt( 1.0 + m(1, 1) - m(0, 0) - m(2, 2) ); m_X = ( m(0, 1) + m(1, 0) ) / s; m_Y = 0.25 * s; m_Z = ( m(1, 2) + m(2, 1) ) / s; @@ -451,7 +451,7 @@ Versor< T > } else { - const double s = 2.0 * vcl_sqrt( 1.0 + m(2, 2) - m(0, 0) - m(1, 1) ); + const double s = 2.0 * std::sqrt( 1.0 + m(2, 2) - m(0, 0) - m(1, 1) ); m_X = ( m(0, 2) + m(2, 0) ) / s; m_Y = ( m(1, 2) + m(2, 1) ) / s; m_Z = 0.25 * s; @@ -468,7 +468,6 @@ void Versor< T > ::Set(const VectorType & axis) { - typedef typename VectorType::RealValueType VectorRealValueType; const ValueType sinangle2 = axis.GetNorm(); if ( sinangle2 > NumericTraits< ValueType >::One ) { @@ -479,7 +478,7 @@ Versor< T > throw exception; } - const ValueType cosangle2 = vcl_sqrt(NumericTraits< double >::One - sinangle2 * sinangle2); + const ValueType cosangle2 = std::sqrt(NumericTraits< double >::One - sinangle2 * sinangle2); m_X = axis[0]; m_Y = axis[1]; @@ -541,8 +540,8 @@ void Versor< T > ::SetRotationAroundX(ValueType angle) { - const ValueType sinangle2 = vcl_sin(angle / 2.0); - const ValueType cosangle2 = vcl_cos(angle / 2.0); + const ValueType sinangle2 = std::sin(angle / 2.0); + const ValueType cosangle2 = std::cos(angle / 2.0); m_X = sinangle2; m_Y = NumericTraits< T >::Zero; @@ -556,8 +555,8 @@ void Versor< T > ::SetRotationAroundY(ValueType angle) { - const ValueType sinangle2 = vcl_sin(angle / 2.0); - const ValueType cosangle2 = vcl_cos(angle / 2.0); + const ValueType sinangle2 = std::sin(angle / 2.0); + const ValueType cosangle2 = std::cos(angle / 2.0); m_X = NumericTraits< T >::Zero; m_Y = sinangle2; @@ -571,8 +570,8 @@ void Versor< T > ::SetRotationAroundZ(ValueType angle) { - const ValueType sinangle2 = vcl_sin(angle / 2.0); - const ValueType cosangle2 = vcl_cos(angle / 2.0); + const ValueType sinangle2 = std::sin(angle / 2.0); + const ValueType cosangle2 = std::cos(angle / 2.0); m_X = NumericTraits< T >::Zero; m_Y = NumericTraits< T >::Zero; diff --git a/Utilities/ITK/Modules/Core/Common/include/itkWeakPointer.h b/Utilities/ITK/Modules/Core/Common/include/itkWeakPointer.h index 33fa7bd4002f1cc3ba323a03995a4084d78a7d46..2a4e48115de64c65faa237307a9a64e3824b09c6 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkWeakPointer.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkWeakPointer.h @@ -49,7 +49,7 @@ public: /** Constructor. */ WeakPointer () - { m_Pointer = 0; } + { m_Pointer = ITK_NULLPTR; } /** Copy constructor. */ WeakPointer (const WeakPointer< ObjectType > & p):m_Pointer(p.m_Pointer) {} @@ -59,7 +59,7 @@ public: /** Destructor. */ ~WeakPointer () - { m_Pointer = 0; } + { m_Pointer = ITK_NULLPTR; } /** Overload operator ->. */ ObjectType * operator->() const diff --git a/Utilities/ITK/Modules/Core/Common/include/itkWin32Header.h b/Utilities/ITK/Modules/Core/Common/include/itkWin32Header.h index f4f209f62b663e369f32d0cdddf4547c24ed9ac6..eca7f85cddfbdca9fc72cb5805a6334c8515c322 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkWin32Header.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkWin32Header.h @@ -68,6 +68,9 @@ // 'identifier' : identifier was truncated to 'number' characters in the debug information #pragma warning ( disable : 4786 ) + +// nonstandard extension used : 'extern' before template explicit instantiation +#pragma warning ( disable : 4231 ) #endif // _MSC_VER #endif diff --git a/Utilities/ITK/Modules/Core/Common/include/itkXMLFileOutputWindow.h b/Utilities/ITK/Modules/Core/Common/include/itkXMLFileOutputWindow.h index 5096a11b9d3649db8ee0446c3d7fb5b51c0420dc..1c7e02bb7e35d6f6a463ce49e5404cb01516884e 100644 --- a/Utilities/ITK/Modules/Core/Common/include/itkXMLFileOutputWindow.h +++ b/Utilities/ITK/Modules/Core/Common/include/itkXMLFileOutputWindow.h @@ -62,19 +62,19 @@ public: itkTypeMacro(XMLFileOutputWindow, FileOutputWindow); /** Send a string to the XML file. */ - virtual void DisplayText(const char *); + virtual void DisplayText(const char *) ITK_OVERRIDE; /** Send an error string to the XML file. */ - virtual void DisplayErrorText(const char *); + virtual void DisplayErrorText(const char *) ITK_OVERRIDE; /** Send a warning string to the XML file. */ - virtual void DisplayWarningText(const char *); + virtual void DisplayWarningText(const char *) ITK_OVERRIDE; /** Send a generic output string to the XML file. */ - virtual void DisplayGenericOutputText(const char *); + virtual void DisplayGenericOutputText(const char *) ITK_OVERRIDE; /** Send a debug string to the XML file. */ - virtual void DisplayDebugText(const char *); + virtual void DisplayDebugText(const char *) ITK_OVERRIDE; /** Put the text into the log file without processing it. */ virtual void DisplayTag(const char *); @@ -82,7 +82,7 @@ public: protected: XMLFileOutputWindow(); virtual ~XMLFileOutputWindow(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void Initialize(); diff --git a/Utilities/ITK/Modules/Core/Common/src/CMakeLists.txt b/Utilities/ITK/Modules/Core/Common/src/CMakeLists.txt index 78fe78020cfdca06904f4bdfd8a83818edade89e..e2630b390fb1e87969f2bc5063af1af9aeb47706 100644 --- a/Utilities/ITK/Modules/Core/Common/src/CMakeLists.txt +++ b/Utilities/ITK/Modules/Core/Common/src/CMakeLists.txt @@ -25,6 +25,7 @@ itkRealTimeInterval.cxx itkOctreeNode.cxx itkNumericTraitsFixedArrayPixel.cxx itkMultiThreader.cxx +itkMetaDataObject.cxx itkMetaDataDictionary.cxx itkDataObject.cxx itkThreadLogger.cxx @@ -78,10 +79,11 @@ itkStoppingCriterionBase.cxx itkCompensatedSummation.cxx itkArrayOutputSpecialization.cxx itkNumberToString.cxx +itkSmartPointerForwardReferenceProcessObject.cxx ) if(WIN32) - set(ITKCommon_SRCS ${ITKCommon_SRCS};itkWin32OutputWindow.cxx;itkSmartPointerForwardReferenceProcessObject.cxx) + set(ITKCommon_SRCS ${ITKCommon_SRCS};itkWin32OutputWindow.cxx) endif() # Prevent optimization from affecting the floating point calculation. @@ -104,6 +106,11 @@ elseif( MSVC ) set_source_files_properties( itkCompensatedSummation.cxx PROPERTIES COMPILE_FLAGS -fp:precise ) endif() +if( CMAKE_CXX_COMPILER_ID MATCHES Clang AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.0" ) + # this file contains explicitly instantiated template classes which are not correcly exported with the hidden visibility flag + set_source_files_properties( itkSmartPointerForwardReferenceProcessObject.cxx PROPERTIES COMPILE_FLAGS -fvisibility=default ) +endif() + ### generating libraries add_library( ITKCommon ${ITK_LIBRARY_BUILD_TYPE} ${ITKCommon_SRCS}) diff --git a/Utilities/ITK/Modules/Core/Common/src/itkConditionVariablePThreads.cxx b/Utilities/ITK/Modules/Core/Common/src/itkConditionVariablePThreads.cxx index 1a7a07873665a08eceaffda15509329293c28ca2..de0bd7ea4e00bb7b8192b7f2cefd5ed53184648a 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkConditionVariablePThreads.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkConditionVariablePThreads.cxx @@ -21,7 +21,7 @@ namespace itk { ConditionVariable::ConditionVariable() { - pthread_cond_init(&m_ConditionVariable.m_ConditionVariable, NULL); + pthread_cond_init(&m_ConditionVariable.m_ConditionVariable, ITK_NULLPTR); } ConditionVariable::~ConditionVariable() diff --git a/Utilities/ITK/Modules/Core/Common/src/itkDataObject.cxx b/Utilities/ITK/Modules/Core/Common/src/itkDataObject.cxx index 33a27d421399746121aa49eaaecd6f1b354cd69e..95f2f87cd727e180360d48640742a45eb9b10f5f 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkDataObject.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkDataObject.cxx @@ -26,24 +26,6 @@ * *=========================================================================*/ #include "itkProcessObject.h" -/** The inclusion of itkSmartPointerForwardReference.hxx is needed here - * because this is one of the very few cases where - * itkSmartPointerForwardReference.h does not include - * itkSmartPointerForwardReference.hxx - * - * Ensure that the implicitly instantiated methods and operators are - * exported for the linker. - */ -#if __GNUC__ >= 4 -#pragma GCC visibility push(default) -#endif -#include "itkSmartPointerForwardReference.hxx" -#if __GNUC__ >= 4 -#pragma GCC visibility pop -#endif - -// Manual instantiation is necessary to prevent link errors -template class ITKCommon_EXPORT itk::SmartPointerForwardReference< itk::ProcessObject >; namespace itk { @@ -52,17 +34,17 @@ bool DataObject:: m_GlobalReleaseDataFlag = false; DataObjectError ::DataObjectError(): - ExceptionObject(), m_DataObject(0) + ExceptionObject(), m_DataObject(ITK_NULLPTR) {} DataObjectError ::DataObjectError(const char *file, unsigned int lineNumber): - ExceptionObject(file, lineNumber), m_DataObject(0) + ExceptionObject(file, lineNumber), m_DataObject(ITK_NULLPTR) {} DataObjectError ::DataObjectError(const std::string & file, unsigned int lineNumber): - ExceptionObject(file, lineNumber), m_DataObject(0) + ExceptionObject(file, lineNumber), m_DataObject(ITK_NULLPTR) {} DataObjectError @@ -151,7 +133,7 @@ InvalidRequestedRegionError //---------------------------------------------------------------------------- DataObject::DataObject():m_UpdateMTime() { - m_Source = 0; + m_Source = ITK_NULLPTR; m_SourceOutputName = ""; m_ReleaseDataFlag = false; @@ -226,7 +208,7 @@ DataObject // disconnect ourselves from the current process object if ( m_Source ) { - m_Source->SetOutput(m_SourceOutputName, NULL); + m_Source->SetOutput(m_SourceOutputName, ITK_NULLPTR); } // set our release data flag to off by default (purposely done after @@ -249,7 +231,7 @@ DataObject itkDebugMacro("disconnecting source " << arg << ", source output name " << name); - m_Source = 0; + m_Source = ITK_NULLPTR; m_SourceOutputName = ""; this->Modified(); return true; diff --git a/Utilities/ITK/Modules/Core/Common/src/itkExceptionObject.cxx b/Utilities/ITK/Modules/Core/Common/src/itkExceptionObject.cxx index f8d28aacf7180c06fdd2e3accfa9e8646400cc53..89e45a7f6df537c2c5913ba3225e93be277b743a 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkExceptionObject.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkExceptionObject.cxx @@ -94,14 +94,14 @@ public: /** Increase the reference count (mark as used by another object). * Delegates the counting to its LightObject superclass */ - virtual void Register() const + virtual void Register() const ITK_OVERRIDE { this->LightObject::Register(); } /** Decrease the reference count (release by another object). * Delegates the counting to its LightObject superclass */ - virtual void UnRegister() const + virtual void UnRegister() const ITK_OVERRIDE { this->LightObject::UnRegister(); } @@ -135,8 +135,8 @@ ExceptionObject::ExceptionObject( unsigned int lineNumber, const char *desc, const char *loc): - m_ExceptionData( ReferenceCountedExceptionData::ConstNew(file == 0 ? "":file, lineNumber, desc == 0 ? "":desc, loc == - 0 ? "":loc) ) + m_ExceptionData( ReferenceCountedExceptionData::ConstNew(file == ITK_NULLPTR ? "":file, lineNumber, desc == ITK_NULLPTR ? "":desc, loc == + ITK_NULLPTR ? "":loc) ) {} ExceptionObject::ExceptionObject( @@ -213,7 +213,7 @@ ExceptionObject::operator==(const ExceptionObject & orig) } else { - return ( thisData != 0 ) && ( origData != 0 ) + return ( thisData != ITK_NULLPTR ) && ( origData != ITK_NULLPTR ) && thisData->m_Location == origData->m_Location && thisData->m_Description == origData->m_Description && thisData->m_File == origData->m_File @@ -343,4 +343,30 @@ ExceptionObject // Print trailer os << indent << std::endl; } + +MemoryAllocationError::~MemoryAllocationError() + throw( ) +{ +} + +RangeError::~RangeError() + throw( ) +{ +} + +InvalidArgumentError::~InvalidArgumentError() + throw( ) +{ +} + +IncompatibleOperandsError::~IncompatibleOperandsError() + throw( ) +{ +} + +ProcessAborted::~ProcessAborted() throw( ) +{ +} + + } // end namespace itk diff --git a/Utilities/ITK/Modules/Core/Common/src/itkFileOutputWindow.cxx b/Utilities/ITK/Modules/Core/Common/src/itkFileOutputWindow.cxx index b71c6c8845eac8b3a3b621419386f009636bf904..9576d84325e2543ce388a4233c04fc679bcc8749 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkFileOutputWindow.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkFileOutputWindow.cxx @@ -27,7 +27,7 @@ FileOutputWindow { m_Flush = false; m_Append = false; - m_Stream = 0; + m_Stream = ITK_NULLPTR; m_FileName = ""; } @@ -35,7 +35,7 @@ FileOutputWindow ::~FileOutputWindow() { delete m_Stream; - m_Stream = 0; + m_Stream = ITK_NULLPTR; } void diff --git a/Utilities/ITK/Modules/Core/Common/src/itkFloatingPointExceptions.cxx b/Utilities/ITK/Modules/Core/Common/src/itkFloatingPointExceptions.cxx index 17cfc9989c248eb0a20cbba28598146437741e4f..426c7155ec459c30f5516cdf2aaffb957d66457e 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkFloatingPointExceptions.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkFloatingPointExceptions.cxx @@ -498,7 +498,7 @@ FloatingPointExceptions act.sa_sigaction = fhdl; sigemptyset(&act.sa_mask); act.sa_flags = SA_SIGINFO; - sigaction(SIGFPE,&act,0); + sigaction(SIGFPE,&act,ITK_NULLPTR); FloatingPointExceptions::m_Enabled = true; } void diff --git a/Utilities/ITK/Modules/Core/Common/src/itkLightObject.cxx b/Utilities/ITK/Modules/Core/Common/src/itkLightObject.cxx index aa64a74e241d3eae8541af7d1a0db4327f500a6f..020475368b9b451670a195349ada2f92fc5f2181 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkLightObject.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkLightObject.cxx @@ -58,7 +58,7 @@ LightObject::New() Pointer smartPtr; LightObject *rawPtr = ::itk::ObjectFactory< LightObject >::Create(); - if ( rawPtr == NULL ) + if ( rawPtr == ITK_NULLPTR ) { rawPtr = new LightObject; } @@ -286,7 +286,7 @@ LightObject #ifdef GCC_USEDEMANGLE char const *mangledName = typeid( *this ).name(); int status; - char * unmangled = abi::__cxa_demangle(mangledName, 0, 0, &status); + char * unmangled = abi::__cxa_demangle(mangledName, ITK_NULLPTR, ITK_NULLPTR, &status); os << indent << "RTTI typeinfo: "; @@ -325,12 +325,6 @@ LightObject ::PrintTrailer( std::ostream & itkNotUsed(os), Indent itkNotUsed(indent) ) const {} -/** - * This operator allows all subclasses of LightObject to be printed via <<. - * It in turn invokes the Print method, which in turn will invoke the - * PrintSelf method that all objects should define, if they have anything - * interesting to print out. - */ std::ostream & operator<<(std::ostream & os, const LightObject & o) { diff --git a/Utilities/ITK/Modules/Core/Common/src/itkLoggerManager.cxx b/Utilities/ITK/Modules/Core/Common/src/itkLoggerManager.cxx index 3892d670d3a53886798256dc9702c5f727f1275b..a848c74cbcf116b28939926227ff31ff4b5a6ff1 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkLoggerManager.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkLoggerManager.cxx @@ -61,7 +61,7 @@ LoggerManager::GetLogger(const NameType & name) if ( loggerItr == this->m_LoggerSet.end() ) { - return NULL; + return ITK_NULLPTR; } return loggerItr->second.GetPointer(); } diff --git a/Utilities/ITK/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx b/Utilities/ITK/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx index d6792219705b8aa3ceb6f10fad1204a1e2838220..e1f647ab8dca7e4576b0919dd4f5d207c5b865d3 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx @@ -16,15 +16,23 @@ * *=========================================================================*/ #include "itkMersenneTwisterRandomVariateGenerator.h" +#include "itkSimpleFastMutexLock.h" +#include "itkMutexLockHolder.h" + namespace itk { namespace Statistics { -MersenneTwisterRandomVariateGenerator::Pointer MersenneTwisterRandomVariateGenerator:: m_Instance = 0; + +// Static/Global variables +MersenneTwisterRandomVariateGenerator::Pointer MersenneTwisterRandomVariateGenerator::m_StaticInstance = ITK_NULLPTR; +SimpleFastMutexLock MersenneTwisterRandomVariateGenerator::m_StaticInstanceLock; +MersenneTwisterRandomVariateGenerator::IntegerType MersenneTwisterRandomVariateGenerator::m_StaticDiffer = 0; MersenneTwisterRandomVariateGenerator::Pointer -MersenneTwisterRandomVariateGenerator::New() +MersenneTwisterRandomVariateGenerator +::CreateInstance() { // Try the factory first MersenneTwisterRandomVariateGenerator::Pointer obj = ObjectFactory< Self >::Create(); @@ -34,11 +42,20 @@ MersenneTwisterRandomVariateGenerator::New() obj = new MersenneTwisterRandomVariateGenerator; // Remove extra reference from construction. obj->UnRegister(); - obj->SetSeed ( GetInstance()->GetSeed() ); } return obj; } + +MersenneTwisterRandomVariateGenerator::Pointer +MersenneTwisterRandomVariateGenerator +::New() +{ + MersenneTwisterRandomVariateGenerator::Pointer obj = MersenneTwisterRandomVariateGenerator::CreateInstance(); + obj->SetSeed ( GetInstance()->GetSeed() ); + return obj; +} + /** * Return the single instance of the MersenneTwisterRandomVariateGenerator */ @@ -46,22 +63,73 @@ MersenneTwisterRandomVariateGenerator::Pointer MersenneTwisterRandomVariateGenerator ::GetInstance() { - if ( !MersenneTwisterRandomVariateGenerator::m_Instance ) + MutexLockHolder<SimpleFastMutexLock> mutexHolder(m_StaticInstanceLock); + + if ( !m_StaticInstance ) { - // Try the factory first - MersenneTwisterRandomVariateGenerator::m_Instance = ObjectFactory< Self >::Create(); - // if the factory did not provide one, then create it here - if ( !MersenneTwisterRandomVariateGenerator::m_Instance ) - { - MersenneTwisterRandomVariateGenerator::m_Instance = new MersenneTwisterRandomVariateGenerator; - // Remove extra reference from construction. - MersenneTwisterRandomVariateGenerator::m_Instance->UnRegister(); - } + m_StaticInstance = MersenneTwisterRandomVariateGenerator::CreateInstance(); } /** * return the instance */ - return MersenneTwisterRandomVariateGenerator::m_Instance; + return m_StaticInstance; } + +MersenneTwisterRandomVariateGenerator +::MersenneTwisterRandomVariateGenerator() +{ + SetSeed (121212); +} + +MersenneTwisterRandomVariateGenerator::IntegerType +MersenneTwisterRandomVariateGenerator +::hash(time_t t, clock_t c) +{ + // Get a IntegerType from t and c + // Better than IntegerType(x) in case x is floating point in [0,1] + // Based on code by Lawrence Kirby: fred at genesis dot demon dot co dot uk + + IntegerType h1 = 0; + unsigned char *p = (unsigned char *)&t; + + const unsigned int sizeOfT = static_cast< unsigned int >( sizeof(t) ); + for ( unsigned int i = 0; i < sizeOfT; ++i ) + { + h1 *= UCHAR_MAX + 2U; + h1 += p[i]; + } + IntegerType h2 = 0; + p = (unsigned char *)&c; + + const unsigned int sizeOfC = static_cast< unsigned int >( sizeof(c) ); + for ( unsigned int j = 0; j < sizeOfC; ++j ) + { + h2 *= UCHAR_MAX + 2U; + h2 += p[j]; + } + return ( h1 + m_StaticDiffer++ ) ^ h2; +} + +void +MersenneTwisterRandomVariateGenerator +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + // Print state vector contents + os << indent << "State vector: " << state << std::endl; + os << indent; + const IntegerType *s = state; + int i = StateVectorLength; + for (; i--; os << *s++ << "\t" ) {} + os << std::endl; + + //Print next value to be gotten from state + os << indent << "Next value to be gotten from state: " << pNext << std::endl; + + //Number of values left before reload + os << indent << "Values left before next reload: " << left << std::endl; +} + } } diff --git a/Utilities/ITK/Modules/Core/Common/src/itkMetaDataDictionary.cxx b/Utilities/ITK/Modules/Core/Common/src/itkMetaDataDictionary.cxx index d9be43c6190ad4675f5854dc7a46c589da96b063..70792636b6414a9f2377a8264fed0326cf164306 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkMetaDataDictionary.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkMetaDataDictionary.cxx @@ -29,7 +29,7 @@ MetaDataDictionary ::~MetaDataDictionary() { delete m_Dictionary; - m_Dictionary = 0; + m_Dictionary = ITK_NULLPTR; } MetaDataDictionary diff --git a/Utilities/ITK/Modules/Core/Common/src/itkMetaDataObject.cxx b/Utilities/ITK/Modules/Core/Common/src/itkMetaDataObject.cxx new file mode 100644 index 0000000000000000000000000000000000000000..b972422bb91d02fe9930046f5c163501f02842e7 --- /dev/null +++ b/Utilities/ITK/Modules/Core/Common/src/itkMetaDataObject.cxx @@ -0,0 +1,47 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#define ITK_TEMPLATE_EXPLICIT_MetaDataObject +#include "itkMetaDataObject.h" + +namespace itk +{ + +template class ITKCommon_EXPORT MetaDataObject< bool >; +template class ITKCommon_EXPORT MetaDataObject< unsigned char >; +template class ITKCommon_EXPORT MetaDataObject< char >; +template class ITKCommon_EXPORT MetaDataObject< signed char >; +template class ITKCommon_EXPORT MetaDataObject< unsigned short >; +template class ITKCommon_EXPORT MetaDataObject< short >; +template class ITKCommon_EXPORT MetaDataObject< unsigned int >; +template class ITKCommon_EXPORT MetaDataObject< int >; +template class ITKCommon_EXPORT MetaDataObject< unsigned long >; +template class ITKCommon_EXPORT MetaDataObject< long >; +template class ITKCommon_EXPORT MetaDataObject< float >; +template class ITKCommon_EXPORT MetaDataObject< double >; +template class ITKCommon_EXPORT MetaDataObject< std::string >; +template class ITKCommon_EXPORT MetaDataObject< Array<char> >; +template class ITKCommon_EXPORT MetaDataObject< Array<int> >; +template class ITKCommon_EXPORT MetaDataObject< Array<float> >; +template class ITKCommon_EXPORT MetaDataObject< Array<double> >; +template class ITKCommon_EXPORT MetaDataObject< Matrix<double> >; +template class ITKCommon_EXPORT MetaDataObject< std::vector<float> >; +template class ITKCommon_EXPORT MetaDataObject< std::vector<double> >; +template class ITKCommon_EXPORT MetaDataObject< std::vector<std::vector<double> > >; +template class ITKCommon_EXPORT MetaDataObject< std::vector<std::vector<float> > >; + +} // end namespace itk diff --git a/Utilities/ITK/Modules/Core/Common/src/itkMetaDataObjectBase.cxx b/Utilities/ITK/Modules/Core/Common/src/itkMetaDataObjectBase.cxx index 1c6d927e3ead6ba5c718d1ea81bc360a2a70f7da..491c4a2d5f5d87be8ea0c121524f7afc0c7344a2 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkMetaDataObjectBase.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkMetaDataObjectBase.cxx @@ -15,39 +15,44 @@ * limitations under the License. * *=========================================================================*/ -#include "itkFastMutexLock.h" +#include "itkMetaDataObjectBase.h" -void -itk::MetaDataObjectBase -::Print(std::ostream & os) const +namespace itk +{ + +MetaDataObjectBase +::MetaDataObjectBase() +{ +} + + +MetaDataObjectBase +::~MetaDataObjectBase() { - os << "[UNKNOWN_PRINT_CHARACTERISTICS]" << std::endl; } + const char * -itk::MetaDataObjectBase -::GetMetaDataObjectTypeName(void) const +MetaDataObjectBase +::GetMetaDataObjectTypeName() const { return typeid( itk::MetaDataObjectBase ).name(); } + const std::type_info & -itk::MetaDataObjectBase -::GetMetaDataObjectTypeInfo(void) const +MetaDataObjectBase +::GetMetaDataObjectTypeInfo() const { return typeid( itk::MetaDataObjectBase ); } -itk::MetaDataObjectBase -::MetaDataObjectBase() -{ - //Nothing to do here -} -itk::MetaDataObjectBase -::~MetaDataObjectBase() +void +MetaDataObjectBase +::Print( std::ostream & os ) const { - //std::cout << " MetaDataObjectBase Deleteing: " << this << - // std::endl; - //Nothing to do here + os << "[UNKNOWN_PRINT_CHARACTERISTICS]" << std::endl; } + +} // end namespace itk diff --git a/Utilities/ITK/Modules/Core/Common/src/itkMultiThreader.cxx b/Utilities/ITK/Modules/Core/Common/src/itkMultiThreader.cxx index 5ed730f2b46e95f3d5f6f36da09194f92c68f292..705471bef83975d7915f08da2bc255e59f307647 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkMultiThreader.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkMultiThreader.cxx @@ -187,19 +187,19 @@ MultiThreader::MultiThreader() for ( ThreadIdType i = 0; i < ITK_MAX_THREADS; i++ ) { m_ThreadInfoArray[i].ThreadID = i; - m_ThreadInfoArray[i].ActiveFlag = 0; - m_ThreadInfoArray[i].ActiveFlagLock = 0; + m_ThreadInfoArray[i].ActiveFlag = ITK_NULLPTR; + m_ThreadInfoArray[i].ActiveFlagLock = ITK_NULLPTR; - m_MultipleMethod[i] = 0; - m_MultipleData[i] = 0; + m_MultipleMethod[i] = ITK_NULLPTR; + m_MultipleData[i] = ITK_NULLPTR; m_SpawnedThreadActiveFlag[i] = 0; - m_SpawnedThreadActiveFlagLock[i] = 0; + m_SpawnedThreadActiveFlagLock[i] = ITK_NULLPTR; m_SpawnedThreadInfoArray[i].ThreadID = i; } - m_SingleMethod = 0; - m_SingleData = 0; + m_SingleMethod = ITK_NULLPTR; + m_SingleData = ITK_NULLPTR; m_NumberOfThreads = this->GetGlobalDefaultNumberOfThreads(); } @@ -241,7 +241,6 @@ void MultiThreader::SingleMethodExecute() if ( !m_SingleMethod ) { itkExceptionMacro(<< "No single method set!"); - return; } // obey the global maximum number of threads limit @@ -292,7 +291,7 @@ void MultiThreader::SingleMethodExecute() m_ThreadInfoArray[0].NumberOfThreads = m_NumberOfThreads; m_SingleMethod( (void *)( &m_ThreadInfoArray[0] ) ); } - catch ( ProcessAborted & excp ) + catch ( ProcessAborted & ) { // Need cleanup and rethrow ProcessAborted // close down other threads @@ -306,7 +305,7 @@ void MultiThreader::SingleMethodExecute() {} } // rethrow - throw &excp; + throw; } catch ( std::exception & e ) { diff --git a/Utilities/ITK/Modules/Core/Common/src/itkMultiThreaderPThreads.cxx b/Utilities/ITK/Modules/Core/Common/src/itkMultiThreaderPThreads.cxx index cb0079495cd9b750804090b1dda1242636051ac1..64623fdde8d817d883c950152996b275c17c4b81 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkMultiThreaderPThreads.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkMultiThreaderPThreads.cxx @@ -65,7 +65,7 @@ ThreadIdType MultiThreader::GetGlobalDefaultNumberOfThreadsByPlatform() // hw.logicalcpu takes into account cores/CPUs that are // disabled because of power management. size_t dataLen = sizeof( int ); // 'num' is an 'int' - int result = sysctlbyname ("hw.logicalcpu", &num, &dataLen, NULL, 0); + int result = sysctlbyname ("hw.logicalcpu", &num, &dataLen, ITK_NULLPTR, 0); if ( result == -1 ) { num = 1; @@ -88,7 +88,7 @@ void MultiThreader::MultipleMethodExecute() for ( thread_loop = 0; thread_loop < m_NumberOfThreads; thread_loop++ ) { - if ( m_MultipleMethod[thread_loop] == (ThreadFunctionType)0 ) + if ( m_MultipleMethod[thread_loop] == (ThreadFunctionType)ITK_NULLPTR ) { itkExceptionMacro(<< "No multiple method set for: " << thread_loop); return; @@ -138,7 +138,7 @@ void MultiThreader::MultipleMethodExecute() // waits for each of the other processes to exit for ( thread_loop = 1; thread_loop < m_NumberOfThreads; thread_loop++ ) { - pthread_join(process_id[thread_loop], 0); + pthread_join(process_id[thread_loop], ITK_NULLPTR); } } @@ -206,10 +206,10 @@ void MultiThreader::TerminateThread(ThreadIdType ThreadID) m_SpawnedThreadActiveFlag[ThreadID] = 0; m_SpawnedThreadActiveFlagLock[ThreadID]->Unlock(); - pthread_join(m_SpawnedThreadProcessID[ThreadID], 0); + pthread_join(m_SpawnedThreadProcessID[ThreadID], ITK_NULLPTR); - m_SpawnedThreadActiveFlagLock[ThreadID] = 0; - m_SpawnedThreadActiveFlagLock[ThreadID] = 0; + m_SpawnedThreadActiveFlagLock[ThreadID] = ITK_NULLPTR; + m_SpawnedThreadActiveFlagLock[ThreadID] = ITK_NULLPTR; } void @@ -217,7 +217,7 @@ MultiThreader ::WaitForSingleMethodThread(ThreadProcessIDType threadHandle) { // Using POSIX threads - if ( pthread_join(threadHandle, 0) ) + if ( pthread_join(threadHandle, ITK_NULLPTR) ) { itkExceptionMacro(<< "Unable to join thread."); } diff --git a/Utilities/ITK/Modules/Core/Common/src/itkMutexLockPThreads.cxx b/Utilities/ITK/Modules/Core/Common/src/itkMutexLockPThreads.cxx index 05d4c4adad94af5b0c1fb256ee3d58af0510738c..87f784f53a7d8604cc2fedacd28eaeeef9bd7253 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkMutexLockPThreads.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkMutexLockPThreads.cxx @@ -32,7 +32,7 @@ namespace itk // Construct a new MutexLock SimpleMutexLock::SimpleMutexLock() { - pthread_mutex_init(&m_MutexLock, NULL); + pthread_mutex_init(&m_MutexLock, ITK_NULLPTR); } // Destruct the MutexVariable diff --git a/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsDiffusionTensor3DPixel.cxx b/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsDiffusionTensor3DPixel.cxx index 93ac5667baccf47586c008ff51c2bc4e7ee1ae84..46b67e65168b07ad983bfbf76ccf4e50b15ed7de 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsDiffusionTensor3DPixel.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsDiffusionTensor3DPixel.cxx @@ -28,10 +28,10 @@ namespace itk #define DIFFUSIONTENSOR3DPIXELSTATICTRAITSMACRO(T) \ template< > \ - const DiffusionTensor3D< T > NumericTraits< DiffusionTensor3D< T > >::Zero = DiffusionTensor3D< T >( \ + ITKCommon_EXPORT const DiffusionTensor3D< T > NumericTraits< DiffusionTensor3D< T > >::Zero = DiffusionTensor3D< T >( \ NumericTraits< T >::Zero); \ template< > \ - const DiffusionTensor3D< T > NumericTraits< DiffusionTensor3D< T > >::One = DiffusionTensor3D< T >( \ + ITKCommon_EXPORT const DiffusionTensor3D< T > NumericTraits< DiffusionTensor3D< T > >::One = DiffusionTensor3D< T >( \ NumericTraits< T >::One); // diff --git a/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsRGBAPixel.cxx b/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsRGBAPixel.cxx index eaa95b76bcd609ed444f5e886b6bd175729402e9..b2140b9c50bc7b2d9e25b60dc038934fc727081e 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsRGBAPixel.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsRGBAPixel.cxx @@ -29,9 +29,9 @@ namespace itk // #define RGBAPIXELSTATICTRAITSMACRO(T) \ template< > \ - const RGBAPixel< T > NumericTraits< RGBAPixel< T > >::Zero = RGBAPixel< T >(NumericTraits< T >::Zero); \ + ITKCommon_EXPORT const RGBAPixel< T > NumericTraits< RGBAPixel< T > >::Zero = RGBAPixel< T >(NumericTraits< T >::Zero); \ template< > \ - const RGBAPixel< T > NumericTraits< RGBAPixel< T > >::One = RGBAPixel< T >(NumericTraits< T >::One); + ITKCommon_EXPORT const RGBAPixel< T > NumericTraits< RGBAPixel< T > >::One = RGBAPixel< T >(NumericTraits< T >::One); // // List here the specializations of the Traits: diff --git a/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsRGBPixel.cxx b/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsRGBPixel.cxx index c249f781016ca243ab69da99a22c32b74ff3bcde..dce599d24b2895741188e37722fbbbd784a3eed6 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsRGBPixel.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkNumericTraitsRGBPixel.cxx @@ -29,9 +29,9 @@ namespace itk // #define RGBPIXELSTATICTRAITSMACRO(T) \ template< > \ - const RGBPixel< T > NumericTraits< RGBPixel< T > >::Zero = RGBPixel< T >(NumericTraits< T >::Zero); \ + ITKCommon_EXPORT const RGBPixel< T > NumericTraits< RGBPixel< T > >::Zero = RGBPixel< T >(NumericTraits< T >::Zero); \ template< > \ - const RGBPixel< T > NumericTraits< RGBPixel< T > >::One = RGBPixel< T >(NumericTraits< T >::One); + ITKCommon_EXPORT const RGBPixel< T > NumericTraits< RGBPixel< T > >::One = RGBPixel< T >(NumericTraits< T >::One); // // List here the specializations of the Traits: diff --git a/Utilities/ITK/Modules/Core/Common/src/itkObject.cxx b/Utilities/ITK/Modules/Core/Common/src/itkObject.cxx index 8c70c5fe5421ccf2b4224dd51bddf1593b821c11..016b00c3e646662e630c72d16126ec151bfc06f7 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkObject.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkObject.cxx @@ -26,6 +26,7 @@ * *=========================================================================*/ #include "itkCommand.h" +#include <algorithm> namespace itk { @@ -34,7 +35,7 @@ namespace itk */ bool Object:: m_GlobalWarningDisplay = true; -class Observer +class ITKCommon_HIDDEN Observer { public: Observer(Command *c, @@ -50,11 +51,12 @@ public: unsigned long m_Tag; }; -class SubjectImplementation +class ITKCommon_HIDDEN SubjectImplementation { public: - SubjectImplementation() { m_Count = 0; } + SubjectImplementation() : m_ListModified(false) { m_Count = 0; } ~SubjectImplementation(); + unsigned long AddObserver(const EventObject & event, Command *cmd); unsigned long AddObserver(const EventObject & event, Command *cmd) const; @@ -73,6 +75,35 @@ public: bool PrintObservers(std::ostream & os, Indent indent) const; + bool m_ListModified; + +protected: + + // RAII of ListModified state to ensure exception safety + struct SaveRestoreListModified + { + // save the list modified flag, and reset to false + SaveRestoreListModified(SubjectImplementation *s) + : m_Subject(s), m_Save(s->m_ListModified) + { + m_Subject->m_ListModified = false; + } + + // restore modify flag, and propagate if modified + ~SaveRestoreListModified() + { + m_Subject->m_ListModified = m_Save||m_Subject->m_ListModified; + } + + SubjectImplementation *m_Subject; + bool m_Save; + }; + + template<typename TObject> + void InvokeEventRecursion(const EventObject & event, + TObject *self, + std::list< Observer * >::reverse_iterator &i); + private: std::list< Observer * > m_Observers; unsigned long m_Count; @@ -121,6 +152,7 @@ SubjectImplementation::RemoveObserver(unsigned long tag) { delete ( *i ); m_Observers.erase(i); + m_ListModified = true; return; } } @@ -135,36 +167,73 @@ SubjectImplementation::RemoveAllObservers() delete ( *i ); } m_Observers.clear(); + m_ListModified = true; } void SubjectImplementation::InvokeEvent(const EventObject & event, Object *self) { - for ( std::list< Observer * >::iterator i = m_Observers.begin(); - i != m_Observers.end(); ++i ) - { - const EventObject *e = ( *i )->m_Event; - if ( e->CheckEvent(&event) ) - { - ( *i )->m_Command->Execute(self, event); - } - } + // While an event is being invoked, it's possible to remove + // observers, or another event to be invoked. All methods which + // remove observers mark the list as modified with the + // m_ListModified flag. The modified flag is save to the stack and + // marked false before recursively saving the current list. + + SaveRestoreListModified save(this); + + std::list< Observer * >::reverse_iterator i = m_Observers.rbegin(); + InvokeEventRecursion( event, self, i ); } void SubjectImplementation::InvokeEvent(const EventObject & event, const Object *self) { - for ( std::list< Observer * >::iterator i = m_Observers.begin(); - i != m_Observers.end(); ++i ) + SaveRestoreListModified save(this); + + std::list< Observer * >::reverse_iterator i = m_Observers.rbegin(); + InvokeEventRecursion( event, self, i ); +} + +template<typename TObject> +void +SubjectImplementation::InvokeEventRecursion( const EventObject & event, + TObject *self, + std::list< Observer * >::reverse_iterator &i) +{ + // This method recursively visits the list of observers in reverse + // order so that on the last recursion the first observer can be + // executed. Each iteration saves the list element on the + // stack. Each observer's execution could potentially modify the + // observer list, by placing the entire list on the stack we save the + // list when the event is first invoked. If observers are removed + // during execution, then the current list is search for the current + // observer save on the stack. + + while (i != m_Observers.rend()) { - const EventObject *e = ( *i )->m_Event; - if ( e->CheckEvent(&event) ) + + // save observer + const Observer *o = *i; + + if ( o->m_Event->CheckEvent(&event) ) { - ( *i )->m_Command->Execute(self, event); + InvokeEventRecursion( event, self, ++i ); + + if ( !m_ListModified || + std::find(m_Observers.begin(), m_Observers.end(), o) != m_Observers.end() ) + { + o->m_Command->Execute(self, event); + } + + return; } + + ++i; } + + return; } Command * @@ -178,7 +247,7 @@ SubjectImplementation::GetCommand(unsigned long tag) return ( *i )->m_Command; } } - return 0; + return ITK_NULLPTR; } bool @@ -209,7 +278,12 @@ SubjectImplementation::PrintObservers(std::ostream & os, Indent indent) const { const EventObject *e = ( *i )->m_Event; const Command * c = ( *i )->m_Command; - os << indent << e->GetEventName() << "(" << c->GetNameOfClass() << ")\n"; + os << indent << e->GetEventName() << "(" << c->GetNameOfClass(); + if (!c->GetObjectName().empty()) + { + os << " \"" << c->GetObjectName() << "\""; + } + os << ")\n"; } return true; } @@ -220,7 +294,7 @@ Object::New() Pointer smartPtr; Object *rawPtr = ::itk::ObjectFactory< Object >::Create(); - if ( rawPtr == NULL ) + if ( rawPtr == ITK_NULLPTR ) { rawPtr = new Object; } @@ -345,7 +419,14 @@ Object /** * If there is a delete method, invoke it. */ - this->InvokeEvent( DeleteEvent() ); + try + { + this->InvokeEvent( DeleteEvent() ); + } + catch(...) + { + itkWarningMacro("Exception occurred in DeleteEvent Observer!"); + } } Superclass::UnRegister(); @@ -367,7 +448,14 @@ Object /** * If there is a delete method, invoke it. */ - this->InvokeEvent( DeleteEvent() ); + try + { + this->InvokeEvent( DeleteEvent() ); + } + catch(...) + { + itkWarningMacro("Exception occurred in DeleteEvent Observer!"); + } } Superclass::SetReferenceCount(ref); @@ -424,7 +512,7 @@ Object { return this->m_SubjectImplementation->GetCommand(tag); } - return NULL; + return ITK_NULLPTR; } void @@ -497,8 +585,8 @@ Object ::Object(): LightObject(), m_Debug(false), - m_SubjectImplementation(NULL), - m_MetaDataDictionary(NULL), + m_SubjectImplementation(ITK_NULLPTR), + m_MetaDataDictionary(ITK_NULLPTR), m_ObjectName() { this->Modified(); @@ -536,7 +624,7 @@ MetaDataDictionary & Object ::GetMetaDataDictionary(void) { - if ( m_MetaDataDictionary == NULL ) + if ( m_MetaDataDictionary == ITK_NULLPTR ) { m_MetaDataDictionary = new MetaDataDictionary; } @@ -547,7 +635,7 @@ const MetaDataDictionary & Object ::GetMetaDataDictionary(void) const { - if ( m_MetaDataDictionary == NULL ) + if ( m_MetaDataDictionary == ITK_NULLPTR ) { m_MetaDataDictionary = new MetaDataDictionary; } @@ -558,7 +646,7 @@ void Object ::SetMetaDataDictionary(const MetaDataDictionary & rhs) { - if ( m_MetaDataDictionary == NULL ) + if ( m_MetaDataDictionary == ITK_NULLPTR ) { m_MetaDataDictionary = new MetaDataDictionary; } diff --git a/Utilities/ITK/Modules/Core/Common/src/itkObjectFactoryBase.cxx b/Utilities/ITK/Modules/Core/Common/src/itkObjectFactoryBase.cxx index 8843852db69f426d62a72eb2bd53b0b095af87bf..ffcf8e8d616e61aac5685d4a3b61aba66406be25 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkObjectFactoryBase.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkObjectFactoryBase.cxx @@ -134,7 +134,7 @@ ObjectFactoryBase::GetStrictVersionChecking() /** - * Create an instance of a named itk object using the loaded + * Create an instance of a named ITK object using the loaded * factories */ LightObject::Pointer @@ -154,7 +154,7 @@ ObjectFactoryBase return newobject; } } - return 0; + return ITK_NULLPTR; } std::list< LightObject::Pointer > @@ -222,9 +222,9 @@ void ObjectFactoryBase ::RegisterInternal() { - // Guaranee that no internal factories have already been registered. - itkAssertOrThrowMacro( ObjectFactoryBasePrivate::m_RegisteredFactories->empty(), - "Factories unexpectedlly already registered!" ); + // Guarantee that no internal factories have already been registered. + itkAssertInDebugAndIgnoreInReleaseMacro( ObjectFactoryBasePrivate::m_RegisteredFactories->empty() ); + ObjectFactoryBasePrivate::m_RegisteredFactories->clear(); // Register all factories registered by the // "RegisterFactoryInternal" method @@ -413,6 +413,15 @@ ObjectFactoryBase newfactory->m_LibraryHandle = (void *)lib; newfactory->m_LibraryPath = fullpath; newfactory->m_LibraryDate = 0; // unused for now... + + // ObjectFactoryBase::RegisterFactory may raise an exception if + // a user enables StrictVersionChecking and a library in "path" + // is a conflicting version; this exception should be propagated + // to the user and not caught by ITK + // + // Do not edit the next comment line! It is intended to be parsed + // by the Coverity analyzer. + // coverity[fun_call_w_exception] if (!ObjectFactoryBase::RegisterFactory(newfactory)) { DynamicLoader::CloseLibrary(lib); @@ -446,7 +455,7 @@ ObjectFactoryBase */ ObjectFactoryBase::ObjectFactoryBase() { - m_LibraryHandle = 0; + m_LibraryHandle = ITK_NULLPTR; m_LibraryDate = 0; m_OverrideMap = new OverRideMap; } @@ -470,7 +479,7 @@ void ObjectFactoryBase ::RegisterFactoryInternal(ObjectFactoryBase *factory) { - if ( factory->m_LibraryHandle != NULL ) + if ( factory->m_LibraryHandle != ITK_NULLPTR ) { itkGenericExceptionMacro( "A dynamic factory tried to be loaded internally!" ); } @@ -497,7 +506,7 @@ bool ObjectFactoryBase ::RegisterFactory(ObjectFactoryBase *factory, InsertionPositionType where, size_t position) { - if ( factory->m_LibraryHandle == 0 ) + if ( factory->m_LibraryHandle == ITK_NULLPTR ) { const char nonDynamicName[] = "Non-Dynamicaly loaded factory"; factory->m_LibraryPath = nonDynamicName; @@ -692,7 +701,7 @@ ObjectFactoryBase } } delete ObjectFactoryBasePrivate::m_RegisteredFactories; - ObjectFactoryBasePrivate::m_RegisteredFactories = 0; + ObjectFactoryBasePrivate::m_RegisteredFactories = ITK_NULLPTR; ObjectFactoryBasePrivate::m_Initialized = false; } } @@ -733,7 +742,7 @@ ObjectFactoryBase return ( *i ).second.m_CreateObject->CreateObject(); } } - return 0; + return ITK_NULLPTR; } std::list< LightObject::Pointer > diff --git a/Utilities/ITK/Modules/Core/Common/src/itkOctreeNode.cxx b/Utilities/ITK/Modules/Core/Common/src/itkOctreeNode.cxx index 5f0a6c6a4aa7e8b597fad12c0fc5defb0b26ff45..6752b6494bedc335b2c82d53b931f15d1f615413 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkOctreeNode.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkOctreeNode.cxx @@ -27,8 +27,8 @@ namespace itk */ OctreeNode::OctreeNode(void) { - m_Parent = 0; - m_Branch = 0; + m_Parent = ITK_NULLPTR; + m_Branch = ITK_NULLPTR; } OctreeNode::~OctreeNode(void) diff --git a/Utilities/ITK/Modules/Core/Common/src/itkOutputWindow.cxx b/Utilities/ITK/Modules/Core/Common/src/itkOutputWindow.cxx index 4d1d37fd0d8b5895cf8fc1bcff16c3da3e1ed7da..6e59fc8d0fb6093034ed7be665789a2e6e39e11c 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkOutputWindow.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkOutputWindow.cxx @@ -34,7 +34,7 @@ namespace itk { -OutputWindow::Pointer OutputWindow:: m_Instance = 0; +OutputWindow::Pointer OutputWindow:: m_Instance = ITK_NULLPTR; /** * Prompting off by default diff --git a/Utilities/ITK/Modules/Core/Common/src/itkProcessObject.cxx b/Utilities/ITK/Modules/Core/Common/src/itkProcessObject.cxx index c8221e7f5a88598802c68ecc129b9ee9c3ce018d..40af8ebe15a08713bb6561bbe0df986f0aae1fcb 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkProcessObject.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkProcessObject.cxx @@ -129,7 +129,7 @@ ProcessObject // let the output know we no longer want to associate with the object it->second->DisconnectSource(this, it->first); // let go of our reference to the data object - it->second = 0; + it->second = ITK_NULLPTR; } } } @@ -159,7 +159,7 @@ ProcessObject if (num < 1 ) { - m_IndexedInputs[0]->second = NULL; + m_IndexedInputs[0]->second = ITK_NULLPTR; } } else @@ -224,7 +224,7 @@ ProcessObject // if primary or required set to null if ( key == m_IndexedInputs[0]->first || this->IsRequiredInputName(key) ) { - this->SetInput(key, NULL); + this->SetInput(key, ITK_NULLPTR); return; } @@ -233,7 +233,7 @@ ProcessObject { if ( m_IndexedInputs[i]->first == key ) { - this->SetNthInput(i, NULL); + this->SetNthInput(i, ITK_NULLPTR); if ( i == m_IndexedInputs.size() - 1 ) { // remove the last indexed input @@ -385,7 +385,7 @@ ProcessObject // if primary or required set to null if ( key == m_IndexedOutputs[0]->first ) { - this->SetOutput( key, NULL ); + this->SetOutput( key, ITK_NULLPTR ); return; } @@ -394,7 +394,7 @@ ProcessObject { if ( m_IndexedOutputs[i]->first == key ) { - this->SetNthOutput(i, NULL); + this->SetNthOutput(i, ITK_NULLPTR); if ( i == m_IndexedOutputs.size() - 1 ) { // remove the last indexed input @@ -560,7 +560,7 @@ ProcessObject if (num < 1 ) { - m_IndexedOutputs[0]->second = NULL; + m_IndexedOutputs[0]->second = ITK_NULLPTR; } } else @@ -588,7 +588,7 @@ ProcessObject DataObjectPointerMap::iterator it = m_Outputs.find(key); if ( it == m_Outputs.end() ) { - return NULL; + return ITK_NULLPTR; } return it->second.GetPointer(); } @@ -600,7 +600,7 @@ ProcessObject DataObjectPointerMap::const_iterator it = m_Outputs.find(key); if ( it == m_Outputs.end() ) { - return NULL; + return ITK_NULLPTR; } return it->second.GetPointer(); } @@ -734,7 +734,7 @@ ProcessObject { return m_IndexedOutputs.size(); } - return this->GetPrimaryOutput() != NULL; + return this->GetPrimaryOutput() != ITK_NULLPTR; } // ProcessObject::ConstDataObjectPointerArray @@ -771,7 +771,7 @@ ProcessObject DataObjectPointerMap::iterator it = m_Inputs.find(key); if ( it == m_Inputs.end() ) { - return NULL; + return ITK_NULLPTR; } return it->second.GetPointer(); } @@ -783,7 +783,7 @@ ProcessObject DataObjectPointerMap::const_iterator it = m_Inputs.find(key); if ( it == m_Inputs.end() ) { - return NULL; + return ITK_NULLPTR; } return it->second.GetPointer(); } @@ -1006,7 +1006,7 @@ ProcessObject { return m_IndexedInputs.size(); } - return this->GetPrimaryInput() != NULL; + return this->GetPrimaryInput() != ITK_NULLPTR; } // ProcessObject::ConstDataObjectPointerArray @@ -1365,7 +1365,7 @@ ProcessObject */ for( NameSet::const_iterator it = this->m_RequiredInputNames.begin(); it != this->m_RequiredInputNames.end(); ++it ) { - if ( this->GetInput( *it ) == NULL ) + if ( this->GetInput( *it ) == ITK_NULLPTR ) { itkExceptionMacro(<< "Input " << *it << " is required but not set."); } @@ -1377,7 +1377,7 @@ ProcessObject NameSet::const_iterator i = m_RequiredInputNames.begin(); while (i != m_RequiredInputNames.end()) { - if ( this->GetInput(*i) == NULL ) + if ( this->GetInput(*i) == ITK_NULLPTR ) { itkExceptionMacro( << "Required Input " << *i << "is not specified!" << " The required inputs are expected to be the first inputs."); @@ -1732,12 +1732,12 @@ ProcessObject { this->GenerateData(); } - catch ( ProcessAborted & excp ) + catch ( ProcessAborted & ) { this->InvokeEvent( AbortEvent() ); this->ResetPipeline(); this->RestoreInputReleaseDataFlags(); - throw &excp; + throw; } catch (...) { diff --git a/Utilities/ITK/Modules/Core/Common/src/itkProgressAccumulator.cxx b/Utilities/ITK/Modules/Core/Common/src/itkProgressAccumulator.cxx index 5bad3431297aa33cf4225254bf891c74feba0e45..77587f9a1980d874c3c6a0cbc8690bbf59257e21 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkProgressAccumulator.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkProgressAccumulator.cxx @@ -22,7 +22,7 @@ namespace itk ProgressAccumulator ::ProgressAccumulator() { - m_MiniPipelineFilter = 0; + m_MiniPipelineFilter = ITK_NULLPTR; // Initialize the progress values m_AccumulatedProgress = 0.0f; diff --git a/Utilities/ITK/Modules/Core/Common/src/itkRealTimeClock.cxx b/Utilities/ITK/Modules/Core/Common/src/itkRealTimeClock.cxx index 473be65febd2e686c425df44f4f35017f684d5e4..f65967ae4d63059313a0db89cce17b5663e5e2ff 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkRealTimeClock.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkRealTimeClock.cxx @@ -81,6 +81,8 @@ RealTimeClock::RealTimeClock():m_Frequency(1) this->m_Origin -= this->m_Difference; #else this->m_Frequency = 1e6; + this->m_Difference = 0.0; + this->m_Origin = 0.0; #endif // defined(WIN32) || defined(_WIN32) } @@ -100,7 +102,7 @@ RealTimeClock::GetTimeInSeconds() const return value; #else struct timeval tval; - ::gettimeofday(&tval, 0); + ::gettimeofday(&tval, ITK_NULLPTR); TimeStampType value = static_cast< TimeStampType >( tval.tv_sec ) + static_cast< TimeStampType >( tval.tv_usec ) / this->m_Frequency; @@ -129,14 +131,14 @@ RealTimeClock::GetRealTimeStamp() const typedef RealTimeStamp::SecondsCounterType SecondsCounterType; typedef RealTimeStamp::MicroSecondsCounterType MicroSecondsCounterType; - SecondsCounterType iseconds = vcl_floor( seconds ); - MicroSecondsCounterType useconds = vcl_floor( ( seconds - iseconds ) * 1e6 ); + SecondsCounterType iseconds = std::floor( seconds ); + MicroSecondsCounterType useconds = std::floor( ( seconds - iseconds ) * 1e6 ); RealTimeStamp value( iseconds, useconds ); return value; #else struct timeval tval; - ::gettimeofday(&tval, 0); + ::gettimeofday(&tval, ITK_NULLPTR); RealTimeStamp value( static_cast<RealTimeStamp::SecondsCounterType>(tval.tv_sec), static_cast<RealTimeStamp::MicroSecondsCounterType>(tval.tv_usec) ); return value; diff --git a/Utilities/ITK/Modules/Core/Common/src/itkSimpleFastMutexLockPThreads.cxx b/Utilities/ITK/Modules/Core/Common/src/itkSimpleFastMutexLockPThreads.cxx index efebe8e9ef0de5196e36950e1ad1f8e13ecae95e..90f21bd5e7d7cdec242099279c3f72db9b10556c 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkSimpleFastMutexLockPThreads.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkSimpleFastMutexLockPThreads.cxx @@ -32,7 +32,10 @@ namespace itk // Construct a new SimpleMutexLock SimpleFastMutexLock::SimpleFastMutexLock() { - pthread_mutex_init(&( m_FastMutexLock ), NULL); + pthread_mutexattr_t mta; + pthread_mutexattr_init(&mta); + pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&( m_FastMutexLock ), &mta); } // Destruct the SimpleMutexVariable diff --git a/Utilities/ITK/Modules/Core/Common/src/itkSimpleFilterWatcher.cxx b/Utilities/ITK/Modules/Core/Common/src/itkSimpleFilterWatcher.cxx index 27a2902a4e8277cf87168c72ecaa3682c764fc6d..1e56339c7d0a49df7af3b9858549215ec20db48e 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkSimpleFilterWatcher.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkSimpleFilterWatcher.cxx @@ -75,20 +75,23 @@ SimpleFilterWatcher } SimpleFilterWatcher -::SimpleFilterWatcher() -{ - // Initialize state - m_Steps = 0; - m_Comment = "Not watching an object"; - m_TestAbort = false; - m_Iterations = 0; +::SimpleFilterWatcher() : + m_Steps(0), + m_Iterations(0), #if defined( _COMPILER_VERSION ) && ( _COMPILER_VERSION == 730 ) - m_Quiet = true; + m_Quiet(true), #else - m_Quiet = false; + m_Quiet(false), #endif - - m_Process = 0; + m_TestAbort(false), + m_Comment("Not watching an object"), + m_Process(ITK_NULLPTR), + m_StartTag(0), + m_EndTag(0), + m_ProgressTag(0), + m_IterationTag(0), + m_AbortTag(0) +{ } SimpleFilterWatcher diff --git a/Utilities/ITK/Modules/Core/Common/src/itkSmapsFileParser.cxx b/Utilities/ITK/Modules/Core/Common/src/itkSmapsFileParser.cxx index 8d63b031f134a093bc75791aa9735a5b53fed68a..08e532f6a8d22161fef714f7ce2513525d7ad507 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkSmapsFileParser.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkSmapsFileParser.cxx @@ -370,7 +370,7 @@ SmapsData_2_6::~SmapsData_2_6() std::istream & operator>>(std::istream & smapsStream, SmapsData_2_6 & data) { - SmapsRecord *record = NULL; + SmapsRecord *record = ITK_NULLPTR; // reset the records from a previous parsing data.Reset(); @@ -428,7 +428,7 @@ VMMapData_10_2 std::istream & operator>>(std::istream & stream, VMMapData_10_2 & data) { - MapRecord *record = NULL; + MapRecord *record = ITK_NULLPTR; // reset the records from a previous parsing data.Reset(); diff --git a/Utilities/ITK/Modules/Core/Common/src/itkSmartPointerForwardReferenceProcessObject.cxx b/Utilities/ITK/Modules/Core/Common/src/itkSmartPointerForwardReferenceProcessObject.cxx index b6524cb2f33683907a5138451d53b8fd7d4bc459..24d3dfcb52e7e8e335cffbd1e9346a77b9b46b38 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkSmartPointerForwardReferenceProcessObject.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkSmartPointerForwardReferenceProcessObject.cxx @@ -16,7 +16,24 @@ * *=========================================================================*/ #include "itkSmartPointerForwardReference.h" +/** The inclusion of itkSmartPointerForwardReference.hxx is needed here + * because this is one of the very few cases where + * itkSmartPointerForwardReference.h does not include + * itkSmartPointerForwardReference.hxx + * + * Ensure that the implicitly instantiated methods and operators are + * exported for the linker. + */ +#if __GNUC__ >= 4 +#pragma GCC visibility push(default) +#endif #include "itkSmartPointerForwardReference.hxx" +#if __GNUC__ >= 4 +#pragma GCC visibility pop +#endif + + #include "itkProcessObject.h" +// Manual instantiation is necessary to prevent link errors template class ITKCommon_EXPORT itk::SmartPointerForwardReference< itk::ProcessObject >; diff --git a/Utilities/ITK/Modules/Core/Common/src/itkStdStreamLogOutput.cxx b/Utilities/ITK/Modules/Core/Common/src/itkStdStreamLogOutput.cxx index ee54da47daf7eb2c2de1d542571c10dc0fc59106..99f206bf0bff4d3a38d807976df31ae892af22d2 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkStdStreamLogOutput.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkStdStreamLogOutput.cxx @@ -23,7 +23,7 @@ namespace itk /** Constructor */ StdStreamLogOutput::StdStreamLogOutput() { - this->m_Stream = 0; + this->m_Stream = ITK_NULLPTR; } /** Destructor */ diff --git a/Utilities/ITK/Modules/Core/Common/src/itkThreadLogger.cxx b/Utilities/ITK/Modules/Core/Common/src/itkThreadLogger.cxx index c381dea462a0f53919da2c04d7dbcd2802eb5d60..cfa1a71e5329d8373e55259a57299bd6a2a96ea3 100644 --- a/Utilities/ITK/Modules/Core/Common/src/itkThreadLogger.cxx +++ b/Utilities/ITK/Modules/Core/Common/src/itkThreadLogger.cxx @@ -180,12 +180,12 @@ ThreadLogger { struct MultiThreader:: ThreadInfoStruct *pInfo = (struct MultiThreader::ThreadInfoStruct *)pInfoStruct; - if ( pInfo == NULL ) + if ( pInfo == ITK_NULLPTR ) { return ITK_THREAD_RETURN_VALUE; } - if ( pInfo->UserData == NULL ) + if ( pInfo->UserData == ITK_NULLPTR ) { return ITK_THREAD_RETURN_VALUE; } diff --git a/Utilities/ITK/Modules/Core/Common/wrapping/ITKCommonBase.wrap b/Utilities/ITK/Modules/Core/Common/wrapping/ITKCommonBase.wrap index ff5c7b5755afabba7696e47b7b0a90fdad7a56c4..eff06f421c3fe7f564a06da198736ea4baf4b898 100644 --- a/Utilities/ITK/Modules/Core/Common/wrapping/ITKCommonBase.wrap +++ b/Utilities/ITK/Modules/Core/Common/wrapping/ITKCommonBase.wrap @@ -31,6 +31,7 @@ itk_wrap_simple_class("itk::DynamicLoader" POINTER) itk_wrap_simple_class("itk::ObjectFactoryBase" POINTER) itk_wrap_simple_class("itk::OutputWindow" POINTER) itk_wrap_simple_class("itk::Version" POINTER) +itk_wrap_simple_class("itk::RealTimeClock" POINTER) itk_wrap_simple_class("itk::RealTimeInterval") itk_wrap_simple_class("itk::RealTimeStamp") itk_wrap_simple_class("itk::TimeStamp") diff --git a/Utilities/ITK/Modules/Core/Common/wrapping/itkArray2D.wrap b/Utilities/ITK/Modules/Core/Common/wrapping/itkArray2D.wrap index 1c99e0c423d48582288031c331b9419f241230a7..0d0a2a88cec58fa2b07911bc39f288fc17768904 100644 --- a/Utilities/ITK/Modules/Core/Common/wrapping/itkArray2D.wrap +++ b/Utilities/ITK/Modules/Core/Common/wrapping/itkArray2D.wrap @@ -1,5 +1,4 @@ itk_wrap_class("itk::Array2D") - itk_wrap_template("${ITKM_D}" "${ITKT_D}") UNIQUE(types "D;${WRAP_ITK_REAL}") foreach(t ${types}) itk_wrap_template("${ITKM_${t}}" "${ITKT_${t}}") diff --git a/Utilities/ITK/Modules/Core/Common/wrapping/itkDiffusionTensor3D.wrap b/Utilities/ITK/Modules/Core/Common/wrapping/itkDiffusionTensor3D.wrap index 2d0177261cc617a33b5f85f060baccd83db8555f..93070a2c89f09b33cac145744519a077376ddece 100644 --- a/Utilities/ITK/Modules/Core/Common/wrapping/itkDiffusionTensor3D.wrap +++ b/Utilities/ITK/Modules/Core/Common/wrapping/itkDiffusionTensor3D.wrap @@ -1,7 +1,8 @@ -itk_wrap_class("itk::DiffusionTensor3D") - itk_wrap_filter_dims(d 3) - if(d) +itk_wrap_filter_dims(has_d_3 3) + +if(has_d_3) + itk_wrap_class("itk::DiffusionTensor3D") itk_wrap_template("${ITKM_F}" "${ITKT_F}") itk_wrap_template("${ITKM_D}" "${ITKT_D}") - endif(d) -itk_end_wrap_class() + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Core/Common/wrapping/itkNumericTraits.wrap b/Utilities/ITK/Modules/Core/Common/wrapping/itkNumericTraits.wrap index 741e3972a2d625d700d1f2cef0a868cee5e2808b..181549811ec3ece845198321cddca8af6b1206ad 100644 --- a/Utilities/ITK/Modules/Core/Common/wrapping/itkNumericTraits.wrap +++ b/Utilities/ITK/Modules/Core/Common/wrapping/itkNumericTraits.wrap @@ -16,7 +16,7 @@ if(WIN32) endif(WIN32) # the superclass -itk_wrap_class(vcl_numeric_limits EXPLICIT_SPECIALIZATION) +itk_wrap_class(std::numeric_limits EXPLICIT_SPECIALIZATION) # the basic types foreach(t UC US UI UL SC SS SI SL F D LD B) itk_wrap_template("${ITKM_${t}}" "${ITKT_${t}}") diff --git a/Utilities/ITK/Modules/Core/Common/wrapping/itkVectorContainer.wrap b/Utilities/ITK/Modules/Core/Common/wrapping/itkVectorContainer.wrap index 7ff5a1823576e79c36fc54ac273b442e1c287512..f01e30eb7de44d04a0bb96c715e6f751437f5d27 100644 --- a/Utilities/ITK/Modules/Core/Common/wrapping/itkVectorContainer.wrap +++ b/Utilities/ITK/Modules/Core/Common/wrapping/itkVectorContainer.wrap @@ -1,15 +1,14 @@ itk_wrap_include("set") -# double is always needed by KernelTransform -UNIQUE(real_types "${WRAP_ITK_REAL};D") itk_wrap_class("itk::VectorContainer" POINTER) + # double is always needed by KernelTransform + UNIQUE(real_types "${WRAP_ITK_REAL};D") foreach(t ${real_types}) itk_wrap_template("${ITKM_UL}${ITKM_${t}}" "${ITKT_UL},${ITKT_${t}}") itk_wrap_template("${ITKM_UC}${ITKM_${t}}" "${ITKT_UC},${ITKT_${t}}") endforeach(t) foreach(d ${ITK_WRAP_DIMS}) foreach(t ${real_types}) - itk_wrap_template("${ITKM_UL}${ITKM_${t}}" "${ITKT_UL},${ITKT_${t}}") itk_wrap_template("${ITKM_UL}${ITKM_V${t}${d}}" "${ITKT_UL},${ITKT_V${t}${d}}") itk_wrap_template("${ITKM_UL}${ITKM_P${t}${d}}" "${ITKT_UL},${ITKT_P${t}${d}}") itk_wrap_template("${ITKM_UL}M${ITKM_${t}}${d}${d}" "${ITKT_UL}, itk::Matrix< ${ITKT_${t}}, ${d}, ${d} >") @@ -19,10 +18,6 @@ itk_wrap_class("itk::VectorContainer" POINTER) itk_wrap_template("${ITKM_UC}${ITKM_O${d}}" "${ITKT_UC},${ITKT_O${d}}") itk_wrap_template("${ITKM_UI}${ITKM_CID${d}}" "${ITKT_UI},${ITKT_CID${d}}") endforeach(d) - foreach(t ${WRAP_ITK_REAL}) - itk_wrap_template("${ITKM_UL}${ITKM_${t}}" "${ITKT_UL},${ITKT_${t}}") - itk_wrap_template("${ITKM_UC}${ITKM_${t}}" "${ITKT_UC},${ITKT_${t}}") - endforeach(t) itk_wrap_template("${ITKM_UC}${ITKM_SS}" "${ITKT_UC},${ITKT_SS}") # used in FastMarchingExtensionImageFilter itk_wrap_template("${ITKM_UI}${ITKM_VUC1}" "${ITKT_UI},${ITKT_VUC1}") diff --git a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkDenseFiniteDifferenceImageFilter.hxx b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkDenseFiniteDifferenceImageFilter.hxx index 950a8eeff0d21f648e1e497ab9c250431bd9cd52..48540151d0eac693a9632b264c77c39fc114e0a0 100644 --- a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkDenseFiniteDifferenceImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkDenseFiniteDifferenceImageFilter.hxx @@ -230,9 +230,7 @@ DenseFiniteDifferenceImageFilter< TInputImage, TOutputImage >::TimeStepType DenseFiniteDifferenceImageFilter< TInputImage, TOutputImage > ::ThreadedCalculateChange(const ThreadRegionType & regionToProcess, ThreadIdType) { - typedef typename OutputImageType::RegionType RegionType; typedef typename OutputImageType::SizeType SizeType; - typedef typename OutputImageType::IndexType IndexType; typedef typename FiniteDifferenceFunctionType::NeighborhoodType NeighborhoodIteratorType; typedef ImageRegionIterator< UpdateBufferType > UpdateIteratorType; diff --git a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceFunction.h b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceFunction.h index 3ab2046341a2a0229e2b1872397c8e87a09b6bc2..b6121d37de25da3a9dbe5cb9871cb81e9fb06494 100644 --- a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceFunction.h +++ b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceFunction.h @@ -186,7 +186,7 @@ protected: FiniteDifferenceFunction(); ~FiniteDifferenceFunction() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; RadiusType m_Radius; PixelRealType m_ScaleCoefficients[ImageDimension]; diff --git a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceFunction.hxx b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceFunction.hxx index ace80678ab0d36a7cb2cbb3efb8e2b911c85189a..f7ad83e0297c71c9ffa0276b2fa56699c3aea6ac 100644 --- a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceFunction.hxx +++ b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceFunction.hxx @@ -86,7 +86,6 @@ FiniteDifferenceFunction< TImageType >::ComputeNeighborhoodScales() const NeighborhoodScalesType neighborhoodScales; neighborhoodScales.Fill(0.0); - typedef typename NeighborhoodScalesType::ComponentType NeighborhoodScaleType; for ( unsigned int i = 0; i < ImageDimension; i++ ) { if ( this->m_Radius[i] > 0 ) diff --git a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceImageFilter.hxx b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceImageFilter.hxx index 20fc860025a10db8749c19ffb56f8c9941c60d32..5ba6f80623fddc3ec2700540989bb4a01dcba78b 100644 --- a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceImageFilter.hxx @@ -31,7 +31,7 @@ FiniteDifferenceImageFilter< TInputImage, TOutputImage > { m_UseImageSpacing = true; m_ElapsedIterations = 0; - m_DifferenceFunction = 0; + m_DifferenceFunction = ITK_NULLPTR; m_NumberOfIterations = NumericTraits< IdentifierType >::max(); m_MaximumRMSError = 0.0; m_RMSChange = 0.0; @@ -264,7 +264,7 @@ FiniteDifferenceImageFilter< TInputImage, TOutputImage > if ( this->m_UseImageSpacing ) { const TOutputImage *outputImage = this->GetOutput(); - if ( outputImage == NULL ) + if ( outputImage == ITK_NULLPTR ) { itkExceptionMacro("Output image is NULL"); } diff --git a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceSparseImageFilter.hxx b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceSparseImageFilter.hxx index 30d6a0a6804e917ef2aa765b8ecb0c76bdff996c..3ac48a8852d155b627da692449fa666cd63afb67 100644 --- a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceSparseImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceSparseImageFilter.hxx @@ -26,7 +26,7 @@ template< typename TInputImageType, typename TSparseOutputImageType > FiniteDifferenceSparseImageFilter< TInputImageType, TSparseOutputImageType > ::FiniteDifferenceSparseImageFilter() { - m_SparseFunction = 0; + m_SparseFunction = ITK_NULLPTR; m_PrecomputeFlag = false; } diff --git a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceSparseImageFunction.h b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceSparseImageFunction.h index 0eb74dc5ca2cb6a50520c725a24473becda202b5..cc4c7cc73d232ff89511558ac93b3c063d1e7216 100644 --- a/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceSparseImageFunction.h +++ b/Utilities/ITK/Modules/Core/FiniteDifference/include/itkFiniteDifferenceSparseImageFunction.h @@ -85,7 +85,7 @@ public: void *, const FloatOffsetType &) { - return static_cast< PixelType >( 0 ); + return static_cast< PixelType >( ITK_NULLPTR ); } /** The update called from the FiniteDifferenceSparseImageFilter. This diff --git a/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUImage.h b/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUImage.h index 672798b92509164cda9819b1eb45cfff04cea2c9..bd3b9f7a280458bd5e135a9837e302128e8e351d 100644 --- a/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUImage.h +++ b/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUImage.h @@ -76,7 +76,7 @@ public: // // Allocate CPU and GPU memory space // - void Allocate(); + virtual void Allocate(bool initialize=false) ITK_OVERRIDE; virtual void Initialize(); diff --git a/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUImage.hxx b/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUImage.hxx index d9fe78ec1e8a3131f829927f84d6bf1edf6d0982..8b1e2b4107a14234bd4d4ce943a622f230b6639d 100644 --- a/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUImage.hxx +++ b/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUImage.hxx @@ -36,10 +36,10 @@ GPUImage< TPixel, VImageDimension >::~GPUImage() } template <typename TPixel, unsigned int VImageDimension> -void GPUImage< TPixel, VImageDimension >::Allocate() +void GPUImage< TPixel, VImageDimension >::Allocate(bool initialize) { // allocate CPU memory - calling Allocate() in superclass - Superclass::Allocate(); + Superclass::Allocate(initialize); // allocate GPU memory this->ComputeOffsetTable(); diff --git a/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUInPlaceImageFilter.hxx b/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUInPlaceImageFilter.hxx index 0f108ae84671f3be7adc97b18d1cef06f2ea30ec..40c187716c1ecb388bf0805dd3324c28df8384ef 100644 --- a/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUInPlaceImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUInPlaceImageFilter.hxx @@ -74,7 +74,7 @@ GPUInPlaceImageFilter< TInputImage, TOutputImage, TParentImageFilter > // Graft this first input to the output. Later, we'll need to // remove the input's hold on the bulk data. // - OutputImagePointer inputAsOutput = + OutputImagePointer inputAsOutput = dynamic_cast< TOutputImage * >( const_cast< TInputImage * >( this->GetInput() ) ); if ( inputAsOutput ) { diff --git a/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUReduction.hxx b/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUReduction.hxx index 5df0393147e4e11f644964a5bd51a921dbcd8c79..2032aa1ab5541824ade5f1f203c5d6f12f79103d 100644 --- a/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUReduction.hxx +++ b/Utilities/ITK/Modules/Core/GPUCommon/include/itkGPUReduction.hxx @@ -36,6 +36,12 @@ GPUReduction< TElement > m_GPUKernelManager = GPUKernelManager::New(); m_GPUDataManager = NULL; + m_ReduceGPUKernelHandle = 0; + m_TestGPUKernelHandle = 0; + + m_Size = 0; + m_SmallBlock = false; + } template< typename TElement > GPUReduction< TElement > diff --git a/Utilities/ITK/Modules/Core/GPUCommon/src/itkGPUDataManager.cxx b/Utilities/ITK/Modules/Core/GPUCommon/src/itkGPUDataManager.cxx index c6c9da0f5d863fc860e036ceb60aca0a83e13f96..70ac2e1b9cfbef153ff2dde991093e447ac4d0d7 100644 --- a/Utilities/ITK/Modules/Core/GPUCommon/src/itkGPUDataManager.cxx +++ b/Utilities/ITK/Modules/Core/GPUCommon/src/itkGPUDataManager.cxx @@ -147,7 +147,6 @@ bool GPUDataManager::Update() if( m_IsGPUBufferDirty && m_IsCPUBufferDirty ) { itkExceptionMacro("Cannot make up-to-date buffer because both CPU and GPU buffers are dirty"); - return false; } this->UpdateGPUBuffer(); diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAbsImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAbsImageAdaptor.h index 37de8a5d55c2f88970d55bbd447a7191e69f712f..aefc64595a71a9251ebbb90879fe13faae5a2f1c 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAbsImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAbsImageAdaptor.h @@ -25,7 +25,7 @@ namespace itk namespace Accessor { /** \class AbsPixelAccessor - * \brief Give access to the vcl_abs() function of a value + * \brief Give access to the std::abs() function of a value * * AbsPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -62,7 +62,7 @@ public: } // end namespace Accessor /** \class AbsImageAdaptor - * \brief Presents an image as being composed of the vcl_abs() of its pixels + * \brief Presents an image as being composed of the std::abs() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAcosImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAcosImageAdaptor.h index c3cfc90dafb02d73f4fc1cd3f0249a722fea9a82..a57c20628516a9525d6942990f69a2dd12a7a008 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAcosImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAcosImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class AcosPixelAccessor - * \brief Give access to the vcl_acos() function of a value + * \brief Give access to the std::acos() function of a value * * AcosPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -51,15 +51,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_acos( (double)input ); } + { output = (TInternalType)std::acos( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_acos( (double)input ); } + { return (TExternalType)std::acos( (double)input ); } }; } // end namespace Accessor /** \class AcosImageAdaptor - * \brief Presents an image as being composed of the vcl_acos() of its pixels + * \brief Presents an image as being composed of the std::acos() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAsinImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAsinImageAdaptor.h index 856799ba7a27fc14507730ccb225cd2e25a7466a..8745635595acf2c372b5dc46fdc95d8a03a2d856 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAsinImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAsinImageAdaptor.h @@ -27,7 +27,7 @@ namespace Accessor { /** * \class AsinPixelAccessor - * \brief Give access to the vcl_asin() function of a value + * \brief Give access to the std::asin() function of a value * * AsinPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -51,16 +51,16 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_asin( (double)input ); } + { output = (TInternalType)std::asin( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_asin( (double)input ); } + { return (TExternalType)std::asin( (double)input ); } }; } // end namespace Accessor /** * \class AsinImageAdaptor - * \brief Presents an image as being composed of the vcl_asin() of its pixels + * \brief Presents an image as being composed of the std::asin() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAtanImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAtanImageAdaptor.h index e4759e9488f9cef3845cec0ae2df79d2037e2bc4..a45842b7e1f2c767ef9939b1914890391867f2c3 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAtanImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkAtanImageAdaptor.h @@ -27,7 +27,7 @@ namespace Accessor { /** * \class AtanPixelAccessor - * \brief Give access to the vcl_atan() function of a value + * \brief Give access to the std::atan() function of a value * * AtanPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -52,16 +52,16 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_atan( (double)input ); } + { output = (TInternalType)std::atan( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_atan( (double)input ); } + { return (TExternalType)std::atan( (double)input ); } }; } // end namespace Accessor /** * \class AtanImageAdaptor - * \brief Presents an image as being composed of the vcl_atan() of its pixels + * \brief Presents an image as being composed of the std::atan() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkComplexToModulusImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkComplexToModulusImageAdaptor.h index adc8d6b2010040e6f05a846d4dbc2f28cf690a78..19849bc1c82bbb49e53e4c802abb84d32c5127e2 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkComplexToModulusImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkComplexToModulusImageAdaptor.h @@ -54,14 +54,14 @@ public: static inline TExternalType Get(const TInternalType & input) { - return (TExternalType)( vcl_sqrt( input.real() * input.real() + return (TExternalType)( std::sqrt( input.real() * input.real() + input.imag() * input.imag() ) ); } }; } // end namespace Accessor /** \class ComplexToModulusImageAdaptor - * \brief Presents a complex image as being composed of vcl_abs() part + * \brief Presents a complex image as being composed of std::abs() part * of its pixels. * * Additional casting is performed according to the input and output image diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkComplexToPhaseImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkComplexToPhaseImageAdaptor.h index d63315d3dcac99c85c3856883c3c7cfd34ce20a8..814a673d9ff1aac39607e67e7c139aa49340b603 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkComplexToPhaseImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkComplexToPhaseImageAdaptor.h @@ -53,7 +53,7 @@ public: { output = (TInternalType)( input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)( vcl_atan2( input.imag(), input.real() ) ); } + { return (TExternalType)( std::atan2( input.imag(), input.real() ) ); } }; } // end namespace Accessor diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkCosImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkCosImageAdaptor.h index 86da7f39304ae70ab7173e1e1300f3413c8c97c1..b710895414661498767dcc4b8fb2379ca428b9d3 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkCosImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkCosImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class CosPixelAccessor - * \brief Give access to the vcl_cos() function of a value + * \brief Give access to the std::cos() function of a value * * CosPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -49,15 +49,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_cos( (double)input ); } + { output = (TInternalType)std::cos( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_cos( (double)input ); } + { return (TExternalType)std::cos( (double)input ); } }; } // end namespace Accessor /** \class CosImageAdaptor - * \brief Presents an image as being composed of the vcl_cos() of its pixels + * \brief Presents an image as being composed of the std::cos() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkExpImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkExpImageAdaptor.h index 033866f936d9e6476a03777ec2d49a6cd3b80462..e4f584bf813151e7663800ba708fe5468388f221 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkExpImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkExpImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class ExpPixelAccessor - * \brief Give access to the vcl_exp() function of a value + * \brief Give access to the std::exp() function of a value * * ExpPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -49,15 +49,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_exp( (double)input ); } + { output = (TInternalType)std::exp( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_exp( (double)input ); } + { return (TExternalType)std::exp( (double)input ); } }; } // end namespace Accessor /** \class ExpImageAdaptor - * \brief Presents an image as being composed of the vcl_exp() of its pixels + * \brief Presents an image as being composed of the std::exp() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkExpNegativeImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkExpNegativeImageAdaptor.h index a75bce3504d3195294e5109287f85080f0667582..ac3622838cfca49f6f6f6c865a2626f892d9a93c 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkExpNegativeImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkExpNegativeImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class ExpNegativePixelAccessor - * \brief Give access to the vcl_exp() function of a value + * \brief Give access to the std::exp() function of a value * * ExpNegativePixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -49,15 +49,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = static_cast< TInternalType >( vcl_exp( -static_cast< double >( input ) ) ); } + { output = static_cast< TInternalType >( std::exp( -static_cast< double >( input ) ) ); } static inline TExternalType Get(const TInternalType & input) - { return static_cast< TExternalType >( vcl_exp( -static_cast< double >( input ) ) ); } + { return static_cast< TExternalType >( std::exp( -static_cast< double >( input ) ) ); } }; } // end namespace Accessor /** \class ExpNegativeImageAdaptor - * \brief Presents an image as being composed of the vcl_exp() of its pixels + * \brief Presents an image as being composed of the std::exp() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkImageAdaptor.h index 720cfd0e062bd9d01508a0b8eb50811569edcd27..98bc573eb22fe95513e03fe9fbeb8a4c136c4c88 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkImageAdaptor.h @@ -187,10 +187,7 @@ public: virtual const RegionType & GetBufferedRegion() const; /** Allocate the image memory. Dimension and Size must be set a priori. */ - inline void Allocate() - { - m_Image->Allocate(); - } + virtual void Allocate(bool initialize = false) ITK_OVERRIDE; /** Restore the data object to its initial state. This means releasing * memory. */ @@ -316,8 +313,7 @@ public: virtual void SetRequestedRegionToLargestPossibleRegion(); - virtual void PropagateRequestedRegion() - throw ( InvalidRequestedRegionError ); + virtual void PropagateRequestedRegion(); virtual void UpdateOutputData(); diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkImageAdaptor.hxx b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkImageAdaptor.hxx index 48f48c42c717a882e17f15ba8f8fa56a646377e0..b75c7b4331d5f61ff11da412d2acb93ddd0ffffc 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkImageAdaptor.hxx +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkImageAdaptor.hxx @@ -45,6 +45,13 @@ ImageAdaptor< TImage, TAccessor > ::~ImageAdaptor() {} +template< typename TImage, typename TAccessor > +void +ImageAdaptor< TImage, TAccessor > +::Allocate(bool initialize) +{ + m_Image->Allocate(initialize); +} //---------------------------------------------------------------------------- template< typename TImage, typename TAccessor > void @@ -185,7 +192,6 @@ template< typename TImage, typename TAccessor > void ImageAdaptor< TImage, TAccessor > ::PropagateRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' method first, then delegate Superclass::PropagateRequestedRegion(); diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkLog10ImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkLog10ImageAdaptor.h index f24702c28036af6ca51ee8659af3d292f204232a..c39c02ca0fac9287706f87fa45d2d9d42a742b37 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkLog10ImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkLog10ImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class Log10PixelAccessor - * \brief Give access to the vcl_log10() function of a value + * \brief Give access to the std::log10() function of a value * * Log10PixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -50,15 +50,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_log10( (double)input ); } + { output = (TInternalType)std::log10( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_log10( (double)input ); } + { return (TExternalType)std::log10( (double)input ); } }; } // end namespace Accessor /** \class Log10ImageAdaptor - * \brief Presents an image as being composed of the vcl_log10() of its pixels + * \brief Presents an image as being composed of the std::log10() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkLogImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkLogImageAdaptor.h index 65e9259bf2986e9c44f3cb0dd283db7024d9ba12..d2cd6a39c0d54bd38a0657854b837421efc82a6c 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkLogImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkLogImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class LogPixelAccessor - * \brief Give access to the vcl_log() function of a value + * \brief Give access to the std::log() function of a value * * LogPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -50,15 +50,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_log( (double)input ); } + { output = (TInternalType)std::log( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_log( (double)input ); } + { return (TExternalType)std::log( (double)input ); } }; } // end namespace Accessor /** \class LogImageAdaptor - * \brief Presents an image as being composed of the vcl_log() of its pixels + * \brief Presents an image as being composed of the std::log() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkSinImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkSinImageAdaptor.h index 2b6e86a42b00c3e0a89a7413aa3513198b83c4d8..92653305fb2d93c067c97c92598fb343765daad3 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkSinImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkSinImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class SinPixelAccessor - * \brief Give access to the vcl_sin() function of a value + * \brief Give access to the std::sin() function of a value * * SinPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -49,15 +49,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_sin( (double)input ); } + { output = (TInternalType)std::sin( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_sin( (double)input ); } + { return (TExternalType)std::sin( (double)input ); } }; } // end namespace Accessor /** \class SinImageAdaptor - * \brief Presents an image as being composed of the vcl_sin() of its pixels + * \brief Presents an image as being composed of the std::sin() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkSqrtImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkSqrtImageAdaptor.h index 6e8a5b2a7ad05ad88a0a638ef1b42d005e5f367e..41b137f2e909761a75ea299d7e8e621562ab7a0e 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkSqrtImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkSqrtImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class SqrtPixelAccessor - * \brief Give access to the vcl_sqrt() function of a value + * \brief Give access to the std::sqrt() function of a value * * SqrtPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -49,15 +49,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_sqrt( (double)input ); } + { output = (TInternalType)std::sqrt( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_sqrt( (double)input ); } + { return (TExternalType)std::sqrt( (double)input ); } }; } // end namespace Accessor /** \class SqrtImageAdaptor - * \brief Presents an image as being composed of the vcl_sqrt() of its pixels + * \brief Presents an image as being composed of the std::sqrt() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkTanImageAdaptor.h b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkTanImageAdaptor.h index 7770aeb5c5b978786b24e317a67986c26b37be4d..c7d994a3d58ea53ba6cd89d78fd3fadfeab07181 100644 --- a/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkTanImageAdaptor.h +++ b/Utilities/ITK/Modules/Core/ImageAdaptors/include/itkTanImageAdaptor.h @@ -26,7 +26,7 @@ namespace itk namespace Accessor { /** \class TanPixelAccessor - * \brief Give access to the vcl_tan() function of a value + * \brief Give access to the std::tan() function of a value * * TanPixelAccessor is templated over an internal type and an * external type representation. This class cast the input @@ -49,15 +49,15 @@ public: typedef TInternalType InternalType; static inline void Set(TInternalType & output, const TExternalType & input) - { output = (TInternalType)vcl_tan( (double)input ); } + { output = (TInternalType)std::tan( (double)input ); } static inline TExternalType Get(const TInternalType & input) - { return (TExternalType)vcl_tan( (double)input ); } + { return (TExternalType)std::tan( (double)input ); } }; } // end namespace Accessor /** \class TanImageAdaptor - * \brief Presents an image as being composed of the vcl_tan() of its pixels + * \brief Presents an image as being composed of the std::tan() of its pixels * * Additional casting is performed according to the input and output image * types following C++ default casting rules. diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineDecompositionImageFilter.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineDecompositionImageFilter.hxx index cbfc53a0e8d505d50a0d3a0e5ddf191eb61a9093..e94ec2070581d855bcba66d8062704cc0531b3ba 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineDecompositionImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineDecompositionImageFilter.hxx @@ -140,7 +140,7 @@ BSplineDecompositionImageFilter< TInputImage, TOutputImage > { case 3: m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(3.0) - 2.0; + m_SplinePoles[0] = std::sqrt(3.0) - 2.0; break; case 0: m_NumberOfPoles = 0; @@ -150,18 +150,18 @@ BSplineDecompositionImageFilter< TInputImage, TOutputImage > break; case 2: m_NumberOfPoles = 1; - m_SplinePoles[0] = vcl_sqrt(8.0) - 3.0; + m_SplinePoles[0] = std::sqrt(8.0) - 3.0; break; case 4: m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt( 664.0 - vcl_sqrt(438976.0) ) + vcl_sqrt(304.0) - 19.0; - m_SplinePoles[1] = vcl_sqrt( 664.0 + vcl_sqrt(438976.0) ) - vcl_sqrt(304.0) - 19.0; + m_SplinePoles[0] = std::sqrt( 664.0 - std::sqrt(438976.0) ) + std::sqrt(304.0) - 19.0; + m_SplinePoles[1] = std::sqrt( 664.0 + std::sqrt(438976.0) ) - std::sqrt(304.0) - 19.0; break; case 5: m_NumberOfPoles = 2; - m_SplinePoles[0] = vcl_sqrt( 135.0 / 2.0 - vcl_sqrt(17745.0 / 4.0) ) + vcl_sqrt(105.0 / 4.0) + m_SplinePoles[0] = std::sqrt( 135.0 / 2.0 - std::sqrt(17745.0 / 4.0) ) + std::sqrt(105.0 / 4.0) - 13.0 / 2.0; - m_SplinePoles[1] = vcl_sqrt( 135.0 / 2.0 + vcl_sqrt(17745.0 / 4.0) ) - vcl_sqrt(105.0 / 4.0) + m_SplinePoles[1] = std::sqrt( 135.0 / 2.0 + std::sqrt(17745.0 / 4.0) ) - std::sqrt(105.0 / 4.0) - 13.0 / 2.0; break; default: @@ -191,7 +191,7 @@ BSplineDecompositionImageFilter< TInputImage, TOutputImage > if ( m_Tolerance > 0.0 ) { horizon = (typename TInputImage::SizeValueType) - vcl_ceil( vcl_log(m_Tolerance) / vcl_log( vcl_fabs(z) ) ); + std::ceil( std::log(m_Tolerance) / std::log( std::fabs(z) ) ); } if ( horizon < m_DataLength[m_IteratorDirection] ) { @@ -208,7 +208,7 @@ BSplineDecompositionImageFilter< TInputImage, TOutputImage > { /* full loop */ iz = 1.0 / z; - z2n = vcl_pow( z, (double)( m_DataLength[m_IteratorDirection] - 1L ) ); + z2n = std::pow( z, (double)( m_DataLength[m_IteratorDirection] - 1L ) ); sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; z2n *= z2n * iz; for ( unsigned int n = 1; n <= ( m_DataLength[m_IteratorDirection] - 2 ); n++ ) diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineInterpolateImageFunction.h b/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineInterpolateImageFunction.h index ebb82283b51dad29317d7d21242665c10a564283..8253505c597f8b054abf1ac65a1b0b69c1518f8d 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineInterpolateImageFunction.h +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineInterpolateImageFunction.h @@ -152,13 +152,13 @@ public: } virtual OutputType Evaluate(const PointType & point, - ThreadIdType threadID) const + ThreadIdType threadId) const { ContinuousIndexType index; this->GetInputImage()->TransformPhysicalPointToContinuousIndex(point, index); - return ( this->EvaluateAtContinuousIndex(index, threadID) ); + return ( this->EvaluateAtContinuousIndex(index, threadId) ); } virtual OutputType EvaluateAtContinuousIndex(const ContinuousIndexType & @@ -178,7 +178,7 @@ public: virtual OutputType EvaluateAtContinuousIndex(const ContinuousIndexType & index, - ThreadIdType threadID) const; + ThreadIdType threadId) const; CovariantVectorType EvaluateDerivative(const PointType & point) const { @@ -191,13 +191,13 @@ public: } CovariantVectorType EvaluateDerivative(const PointType & point, - ThreadIdType threadID) const + ThreadIdType threadId) const { ContinuousIndexType index; this->GetInputImage()->TransformPhysicalPointToContinuousIndex(point, index); - return ( this->EvaluateDerivativeAtContinuousIndex(index, threadID) ); + return ( this->EvaluateDerivativeAtContinuousIndex(index, threadId) ); } CovariantVectorType EvaluateDerivativeAtContinuousIndex( @@ -222,7 +222,7 @@ public: CovariantVectorType EvaluateDerivativeAtContinuousIndex( const ContinuousIndexType & x, - ThreadIdType threadID) const; + ThreadIdType threadId) const; void EvaluateValueAndDerivative(const PointType & point, OutputType & value, @@ -242,7 +242,7 @@ public: void EvaluateValueAndDerivative(const PointType & point, OutputType & value, CovariantVectorType & deriv, - ThreadIdType threadID) const + ThreadIdType threadId) const { ContinuousIndexType index; @@ -251,7 +251,7 @@ public: this->EvaluateValueAndDerivativeAtContinuousIndex(index, value, deriv, - threadID); + threadId); } void EvaluateValueAndDerivativeAtContinuousIndex( @@ -283,7 +283,7 @@ public: const ContinuousIndexType & x, OutputType & value, CovariantVectorType & deriv, - ThreadIdType threadID) const; + ThreadIdType threadId) const; /** Get/Sets the Spline Order, supports 0th - 5th order splines. The default * is a 3rd order spline. */ @@ -315,19 +315,19 @@ public: protected: /** The following methods take working space (evaluateIndex, weights, weightsDerivative) - * that is managed by the caller. If threadID is known, the working variables are looked - * up in the thread indexed arrays. If threadID is not known, working variables are made + * that is managed by the caller. If threadId is known, the working variables are looked + * up in the thread indexed arrays. If threadId is not known, working variables are made * on the stack and passed to these methods. The stack allocation should be ok since * these methods do not store the working variables, i.e. they are not expected to * be available beyond the scope of the function call. * * This was done to allow for two types of re-entrancy. The first is when a threaded * filter, e.g. InterpolateImagePointsFilter calls EvaluateAtContinuousIndex from multiple - * threads without passing a threadID. So, EvaluateAtContinuousIndex must be thread safe. + * threads without passing a threadId. So, EvaluateAtContinuousIndex must be thread safe. * This is handled with the stack-based allocation of the working space. * * The second form of re-entrancy involves methods that call EvaluateAtContinuousIndex - * from multiple threads, but pass a threadID. In this case, we can gain a little efficiency + * from multiple threads, but pass a threadId. In this case, we can gain a little efficiency * (hopefully) by looking up pre-allocated working space in arrays that are indexed by thread. * The efficiency gain is likely dependent on the size of the working variables, which are * in-turn dependent on the dimensionality of the image and the order of the spline. diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineInterpolateImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineInterpolateImageFunction.hxx index e07a750997c18c33a45062fe6cff85a8e9700882..cc4a416ae62b58b99949f15857fe1442c3e97474 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineInterpolateImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkBSplineInterpolateImageFunction.hxx @@ -47,9 +47,9 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > ::BSplineInterpolateImageFunction() { m_NumberOfThreads = 1; - m_ThreadedEvaluateIndex = NULL; - m_ThreadedWeights = NULL; - m_ThreadedWeightsDerivative = NULL; + m_ThreadedEvaluateIndex = ITK_NULLPTR; + m_ThreadedWeights = ITK_NULLPTR; + m_ThreadedWeightsDerivative = ITK_NULLPTR; m_CoefficientFilter = CoefficientFilter::New(); m_Coefficients = CoefficientImageType::New(); @@ -65,13 +65,13 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > ::~BSplineInterpolateImageFunction() { delete[] m_ThreadedEvaluateIndex; - m_ThreadedEvaluateIndex = NULL; + m_ThreadedEvaluateIndex = ITK_NULLPTR; delete[] m_ThreadedWeights; - m_ThreadedWeights = NULL; + m_ThreadedWeights = ITK_NULLPTR; delete[] m_ThreadedWeightsDerivative; - m_ThreadedWeightsDerivative = NULL; + m_ThreadedWeightsDerivative = ITK_NULLPTR; } /** @@ -111,7 +111,7 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > } else { - m_Coefficients = NULL; + m_Coefficients = ITK_NULLPTR; } } @@ -151,12 +151,12 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > ::OutputType BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > ::EvaluateAtContinuousIndex(const ContinuousIndexType & x, - ThreadIdType threadID) const + ThreadIdType threadId) const { // FIXME -- Review this "fix" and ensure it works. #if 1 - vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadID] ); - vnl_matrix< double > *weights = &( m_ThreadedWeights[threadID] ); + vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadId] ); + vnl_matrix< double > *weights = &( m_ThreadedWeights[threadId] ); // Pass evaluateIndex, weights by reference. Different threadIDs get // different instances. return this->EvaluateAtContinuousIndexInternal(x, *evaluateIndex, *weights); @@ -164,14 +164,14 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > // FIXME - Should copy matrices to the stack for thread safety. // This method is being called by multiple threads through // EvaluateAtContinuousIndex( const ContinuousIndexType & x). - // When that method delegates here, it passes threadID = 0. + // When that method delegates here, it passes threadId = 0. // This causes problems because multiple threads end up writing // on the same matrices. // Other methods will probably be affected by the same issue. For // example EvaluateDerivativeAtContinuousIndex and // EvaluateValueAndDerivativeAtContinuousIndex. - vnl_matrix< long > evaluateIndex = ( m_ThreadedEvaluateIndex[threadID] ); - vnl_matrix< double > weights = ( m_ThreadedWeights[threadID] ); + vnl_matrix< long > evaluateIndex = ( m_ThreadedEvaluateIndex[threadId] ); + vnl_matrix< double > weights = ( m_ThreadedWeights[threadId] ); // compute the interpolation indexes this->DetermineRegionOfSupport( ( evaluateIndex ), x, m_SplineOrder ); @@ -208,14 +208,14 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > ::CovariantVectorType BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > ::EvaluateDerivativeAtContinuousIndex(const ContinuousIndexType & x, - ThreadIdType threadID) const + ThreadIdType threadId) const { // FIXME -- Review this "fix" and ensure it works. #if 1 - vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadID] ); - vnl_matrix< double > *weights = &( m_ThreadedWeights[threadID] ); + vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadId] ); + vnl_matrix< double > *weights = &( m_ThreadedWeights[threadId] ); vnl_matrix< double > *weightsDerivative = - &( m_ThreadedWeightsDerivative[threadID] ); + &( m_ThreadedWeightsDerivative[threadId] ); return this->EvaluateDerivativeAtContinuousIndexInternal(x, *evaluateIndex, @@ -223,10 +223,10 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > *weightsDerivative); #else - vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadID] ); - vnl_matrix< double > *weights = &( m_ThreadedWeights[threadID] ); + vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadId] ); + vnl_matrix< double > *weights = &( m_ThreadedWeights[threadId] ); vnl_matrix< double > *weightsDerivative = - &( m_ThreadedWeightsDerivative[threadID] ); + &( m_ThreadedWeightsDerivative[threadId] ); this->DetermineRegionOfSupport( ( *evaluateIndex ), x, m_SplineOrder ); @@ -290,14 +290,14 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > ::EvaluateValueAndDerivativeAtContinuousIndex(const ContinuousIndexType & x, OutputType & value, CovariantVectorType & derivativeValue, - ThreadIdType threadID) const + ThreadIdType threadId) const { // FIXME -- Review this "fix" and ensure it works. #if 1 - vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadID] ); - vnl_matrix< double > *weights = &( m_ThreadedWeights[threadID] ); + vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadId] ); + vnl_matrix< double > *weights = &( m_ThreadedWeights[threadId] ); vnl_matrix< double > *weightsDerivative = - &( m_ThreadedWeightsDerivative[threadID] ); + &( m_ThreadedWeightsDerivative[threadId] ); this->EvaluateValueAndDerivativeAtContinuousIndexInternal(x, value, @@ -306,10 +306,10 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > *weights, *weightsDerivative); #else - vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadID] ); - vnl_matrix< double > *weights = &( m_ThreadedWeights[threadID] ); + vnl_matrix< long > * evaluateIndex = &( m_ThreadedEvaluateIndex[threadId] ); + vnl_matrix< double > *weights = &( m_ThreadedWeights[threadId] ); vnl_matrix< double > *weightsDerivative = - &( m_ThreadedWeightsDerivative[threadID] ); + &( m_ThreadedWeightsDerivative[threadId] ); this->DetermineRegionOfSupport( ( *evaluateIndex ), x, m_SplineOrder ); @@ -667,7 +667,7 @@ BSplineInterpolateImageFunction< TImageType, TCoordRep, TCoefficientType > const float halfOffset = splineOrder & 1 ? 0.0 : 0.5; for ( unsigned int n = 0; n < ImageDimension; n++ ) { - long indx = (long)vcl_floor( (float)x[n] + halfOffset ) - splineOrder / 2; + long indx = (long)std::floor( (float)x[n] + halfOffset ) - splineOrder / 2; for ( unsigned int k = 0; k <= splineOrder; k++ ) { evaluateIndex[n][k] = indx++; diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkCentralDifferenceImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkCentralDifferenceImageFunction.hxx index ad4b11878c1205f39e98bfd1d7769ef0b77656ce..8ca0eada435ceecba868f2701e93ea988bb255ba 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkCentralDifferenceImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkCentralDifferenceImageFunction.hxx @@ -54,7 +54,7 @@ CentralDifferenceImageFunction< TInputImage, TCoordRep, TOutputType > // Verify the output vector is the right size. // OutputType of VariablelengthVector will have size 0 until allocated, so this // case can't be tested. - if( inputData != NULL ) + if( inputData != ITK_NULLPTR ) { SizeValueType nComponents = OutputConvertType::GetNumberOfComponents(); if( nComponents > 0 ) @@ -81,7 +81,7 @@ CentralDifferenceImageFunction< TInputImage, TCoordRep, TOutputType > if ( interpolator != this->m_Interpolator ) { this->m_Interpolator = interpolator; - if( this->GetInputImage() != NULL ) + if( this->GetInputImage() != ITK_NULLPTR ) { this->m_Interpolator->SetInputImage( this->GetInputImage() ); } @@ -286,7 +286,6 @@ CentralDifferenceImageFunction< TInputImage, TCoordRep, TOutputType > { typedef typename PointType::ValueType PointValueType; typedef typename OutputType::ValueType DerivativeValueType; - typedef typename ContinuousIndexType::ValueType ContinuousIndexValueType; PointType neighPoint1 = point; PointType neighPoint2 = point; @@ -354,8 +353,6 @@ CentralDifferenceImageFunction< TInputImage, TCoordRep, TOutputType > ::EvaluateSpecialized(const PointType & point, OutputType & derivative, OutputTypeSpecializationStructType<Type>) const { typedef typename PointType::ValueType PointValueType; - typedef typename OutputType::ValueType DerivativeValueType; - typedef typename ContinuousIndexType::ValueType ContinuousIndexValueType; const InputImageType *inputImage = this->GetInputImage(); const unsigned int numberComponents = inputImage->GetNumberOfComponentsPerPixel(); diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianBlurImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianBlurImageFunction.hxx index cdc41f39191076925097e1d7e7da9f9aff8053cf..9daeedb1687e96eb6e4234bb57eb99369e82a416 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianBlurImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianBlurImageFunction.hxx @@ -222,8 +222,7 @@ GaussianBlurImageFunction< TInputImage, TOutput > typename InternalImageType::RegionType region; region.SetSize(size); m_InternalImage->SetRegions(region); - m_InternalImage->Allocate(); - m_InternalImage->FillBuffer(0); + m_InternalImage->Allocate(true); // initialize buffer to zero } /** Evaluate the function at the specifed point */ diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianDerivativeImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianDerivativeImageFunction.hxx index 96e3f500a6680340dfa848fabaff48a73954a8d5..424476d362a4a30a337dcdda152348995beaf175 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianDerivativeImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianDerivativeImageFunction.hxx @@ -284,7 +284,8 @@ GaussianDerivativeImageFunction< TInputImage, TOutput > for ( unsigned int ii = 0; ii < itkGetStaticConstMacro(ImageDimension2); ++ii ) { // Apply each gaussian kernel to a subset of the image - InputPixelType value = static_cast< double >( this->GetInputImage()->GetPixel(index) ); + typedef typename OutputType::RealValueType OutputRealValueType; + OutputRealValueType value = static_cast< OutputRealValueType >( this->GetInputImage()->GetPixel(index) ); // gaussian blurring first for ( unsigned int direction = 0; direction < itkGetStaticConstMacro(ImageDimension2); ++direction ) @@ -308,7 +309,7 @@ GaussianDerivativeImageFunction< TInputImage, TOutput > m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; - gradient[ii] = value; + gradient[ii] = static_cast< typename OutputType::ComponentType >( value ); } return gradient; diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianInterpolateImageFunction.h b/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianInterpolateImageFunction.h index e33cedc1a9b7a5600453a456d56ab32f3a2a1181..1f9599251d12bebae9fff6dc743b592f84743300 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianInterpolateImageFunction.h +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianInterpolateImageFunction.h @@ -150,7 +150,7 @@ public: virtual OutputType EvaluateAtContinuousIndex( const ContinuousIndexType & cindex ) const { - return this->EvaluateAtContinuousIndex( cindex, NULL ); + return this->EvaluateAtContinuousIndex( cindex, ITK_NULLPTR ); } protected: diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianInterpolateImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianInterpolateImageFunction.hxx index d4b9028cd4471d9d1e5d1b08404dfe65b69caf47..fc23341a88715d73126b7999a2829d2f326a7088 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianInterpolateImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkGaussianInterpolateImageFunction.hxx @@ -111,9 +111,9 @@ GaussianInterpolateImageFunction<TImageType, TCoordRep> { int boundingBoxSize = static_cast<int>( this->m_BoundingBoxEnd[d] - this->m_BoundingBoxStart[d] + 0.5 ); - int begin = vnl_math_max( 0, static_cast<int>( vcl_floor( cindex[d] - + int begin = vnl_math_max( 0, static_cast<int>( std::floor( cindex[d] - this->m_BoundingBoxStart[d] - this->m_CutoffDistance[d] ) ) ); - int end = vnl_math_min( boundingBoxSize, static_cast<int>( vcl_ceil( + int end = vnl_math_min( boundingBoxSize, static_cast<int>( std::ceil( cindex[d] - this->m_BoundingBoxStart[d] + this->m_CutoffDistance[d] ) ) ); region.SetIndex( d, begin ); region.SetSize( d, end - begin ); @@ -189,10 +189,10 @@ GaussianInterpolateImageFunction<TImageType, TCoordRep> int boundingBoxSize = static_cast<int>( this->m_BoundingBoxEnd[dimension] - this->m_BoundingBoxStart[dimension] + 0.5 ); - int begin = vnl_math_max( 0, static_cast<int>( vcl_floor( cindex - + int begin = vnl_math_max( 0, static_cast<int>( std::floor( cindex - this->m_BoundingBoxStart[dimension] - this->m_CutoffDistance[dimension] ) ) ); - int end = vnl_math_min( boundingBoxSize, static_cast<int>( vcl_ceil( cindex - + int end = vnl_math_min( boundingBoxSize, static_cast<int>( std::ceil( cindex - this->m_BoundingBoxStart[dimension] + this->m_CutoffDistance[dimension] ) ) ); @@ -206,7 +206,7 @@ GaussianInterpolateImageFunction<TImageType, TCoordRep> RealType g_last = 0.0; if( evaluateGradient ) { - g_last = vnl_math::two_over_sqrtpi * vcl_exp( -vnl_math_sqr( t ) ); + g_last = vnl_math::two_over_sqrtpi * std::exp( -vnl_math_sqr( t ) ); } for( int i = begin; i < end; i++ ) @@ -216,7 +216,7 @@ GaussianInterpolateImageFunction<TImageType, TCoordRep> erfArray[i] = e_now - e_last; if( evaluateGradient ) { - RealType g_now = vnl_math::two_over_sqrtpi * vcl_exp( -vnl_math_sqr( t ) ); + RealType g_now = vnl_math::two_over_sqrtpi * std::exp( -vnl_math_sqr( t ) ); gerfArray[i] = g_now - g_last; g_last = g_now; } diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkImageFunction.hxx index d00e5de698ef44c0f71fea5517374525e1f11430..6ffe2caeb59d80ad95c77bb876d8b970ac71320c 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkImageFunction.hxx @@ -29,7 +29,7 @@ template< typename TInputImage, typename TOutput, typename TCoordRep > ImageFunction< TInputImage, TOutput, TCoordRep > ::ImageFunction() { - m_Image = NULL; + m_Image = ITK_NULLPTR; m_StartIndex.Fill(0); m_EndIndex.Fill(0); m_StartContinuousIndex.Fill(0.0f); diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkLabelImageGaussianInterpolateImageFunction.h b/Utilities/ITK/Modules/Core/ImageFunction/include/itkLabelImageGaussianInterpolateImageFunction.h index 9694f2c13d41550e16e5e547dee753169a7681da..d38ea357a76a661d523e385a537ea3b374f7301d 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkLabelImageGaussianInterpolateImageFunction.h +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkLabelImageGaussianInterpolateImageFunction.h @@ -104,7 +104,7 @@ public: virtual OutputType EvaluateAtContinuousIndex( const ContinuousIndexType & cindex ) const { - return this->EvaluateAtContinuousIndex( cindex, NULL ); + return this->EvaluateAtContinuousIndex( cindex, ITK_NULLPTR ); } protected: diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkLabelImageGaussianInterpolateImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkLabelImageGaussianInterpolateImageFunction.hxx index 9cd3103731d4b24f9e27b53d5d83d483178edc50..ff642a07b3538474077887df25e07c9777c1cecb 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkLabelImageGaussianInterpolateImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkLabelImageGaussianInterpolateImageFunction.hxx @@ -57,9 +57,9 @@ LabelImageGaussianInterpolateImageFunction<TInputImage, TCoordRep, TPixelCompare { const int boundingBoxSize = static_cast<int>( this->m_BoundingBoxEnd[d] - this->m_BoundingBoxStart[d] + 0.5 ); - const int begin = vnl_math_max( 0, static_cast<int>( vcl_floor( cindex[d] - + const int begin = vnl_math_max( 0, static_cast<int>( std::floor( cindex[d] - this->m_BoundingBoxStart[d] - this->m_CutoffDistance[d] ) ) ); - const int end = vnl_math_min( boundingBoxSize, static_cast<int>( vcl_ceil( + const int end = vnl_math_min( boundingBoxSize, static_cast<int>( std::ceil( cindex[d] - this->m_BoundingBoxStart[d] + this->m_CutoffDistance[d] ) ) ); region.SetIndex( d, begin ); region.SetSize( d, end - begin ); diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkLinearInterpolateImageFunction.h b/Utilities/ITK/Modules/Core/ImageFunction/include/itkLinearInterpolateImageFunction.h index 8f020fda950ab20bfbbad2142686a3e1cb4ec316..f7ce7e40ac7abffb161a9f7f167194d23b25e045 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkLinearInterpolateImageFunction.h +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkLinearInterpolateImageFunction.h @@ -19,6 +19,7 @@ #define __itkLinearInterpolateImageFunction_h #include "itkInterpolateImageFunction.h" +#include "itkVariableLengthVector.h" namespace itk { @@ -495,6 +496,32 @@ private: virtual inline OutputType EvaluateUnoptimized( const ContinuousIndexType & index) const; + + /** \brief A method to generically set all components to zero + */ + template<typename RealTypeScalarRealType> + void + MakeZeroInitializer(const TInputImage * const inputImagePtr, + VariableLengthVector<RealTypeScalarRealType> & tempZeros) const + { + // Variable length vector version to get the size of the pixel correct. + typename TInputImage::IndexType idx; + idx.Fill(0); + const typename TInputImage::PixelType & tempPixel = inputImagePtr->GetPixel(idx); + const unsigned int sizeOfVarLengthVector = tempPixel.GetSize(); + tempZeros.SetSize(sizeOfVarLengthVector); + tempZeros.Fill(NumericTraits< RealTypeScalarRealType >::ZeroValue()); + } + + template<typename RealTypeScalarRealType> + void + MakeZeroInitializer(const TInputImage * const itkNotUsed( inputImagePtr ), + RealTypeScalarRealType & tempZeros) const + { + // All other cases + tempZeros = NumericTraits< RealTypeScalarRealType >::ZeroValue(); + } + }; } // end namespace itk diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkLinearInterpolateImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkLinearInterpolateImageFunction.hxx index d087a26101a065214fb4cba467c6a7692c67081e..f15a8a3be3f24bcd7c01389eb6ec4dc5fc3848c6 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkLinearInterpolateImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkLinearInterpolateImageFunction.hxx @@ -18,6 +18,7 @@ #ifndef __itkLinearInterpolateImageFunction_hxx #define __itkLinearInterpolateImageFunction_hxx +#include "itkConceptChecking.h" #include "itkLinearInterpolateImageFunction.h" #include "vnl/vnl_math.h" @@ -56,6 +57,7 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > this->Superclass::PrintSelf(os, indent); } + /** * Evaluate at image index position */ @@ -65,16 +67,16 @@ typename LinearInterpolateImageFunction< TInputImage, TCoordRep > LinearInterpolateImageFunction< TInputImage, TCoordRep > ::EvaluateUnoptimized(const ContinuousIndexType & index) const { - unsigned int dim; // index over dimension - + // Avoid the smartpointer de-reference in the loop for + // "return m_InputImage.GetPointer()" + const TInputImage * const inputImagePtr = this->GetInputImage(); /** * Compute base index = closet index below point * Compute distance from point to base index */ IndexType baseIndex; InternalComputationType distance[ImageDimension]; - - for ( dim = 0; dim < ImageDimension; dim++ ) + for ( unsigned int dim = 0; dim < ImageDimension; ++dim ) { baseIndex[dim] = Math::Floor< IndexValueType >(index[dim]); distance[dim] = index[dim] - static_cast< InternalComputationType >( baseIndex[dim] ); @@ -87,26 +89,28 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > */ // When RealType is VariableLengthVector, 'value' will be resized properly // below when it's assigned again. - typedef typename NumericTraits< RealType >::ScalarRealType RealTypeScalarRealType; + Concept::Detail::UniqueType< typename NumericTraits< RealType >::ScalarRealType >(); + RealType value; - value = NumericTraits< RealTypeScalarRealType >::Zero; + // Initialize variable "value" with overloaded function so that + // in the case of variable length vectors the "value" is initialized + // to all zeros of length equal to the InputImagePtr first pixel length. + this->MakeZeroInitializer( inputImagePtr, value ); - typedef typename NumericTraits< InputPixelType >::ScalarRealType InputPixelScalarRealType; - InputPixelScalarRealType totalOverlap = NumericTraits< InputPixelScalarRealType >::Zero; - bool firstOverlap = true; + Concept::Detail::UniqueType< typename NumericTraits< InputPixelType >::ScalarRealType >(); for ( unsigned int counter = 0; counter < m_Neighbors; ++counter ) { - InternalComputationType overlap = 1.0; // fraction overlap + InternalComputationType overlap = 1.0; // fraction overlap unsigned int upper = counter; // each bit indicates upper/lower neighbour - IndexType neighIndex; + IndexType neighIndex( baseIndex ); // get neighbor index and overlap fraction - for ( dim = 0; dim < ImageDimension; dim++ ) + for ( unsigned int dim = 0; dim < ImageDimension; ++dim ) { if ( upper & 1 ) { - neighIndex[dim] = baseIndex[dim] + 1; + ++(neighIndex[dim]); // Take care of the case where the pixel is just // in the outer upper boundary of the image grid. if ( neighIndex[dim] > this->m_EndIndex[dim] ) @@ -117,7 +121,6 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > } else { - neighIndex[dim] = baseIndex[dim]; // Take care of the case where the pixel is just // in the outer lower boundary of the image grid. if ( neighIndex[dim] < this->m_StartIndex[dim] ) @@ -129,32 +132,7 @@ LinearInterpolateImageFunction< TInputImage, TCoordRep > upper >>= 1; } - - // Update output value only if overlap is not zero. - // Overlap can be 0 when one or more index dims is an integer. - // There will always be at least one iteration of 'counter' loop - // that has overlap > 0, even if index is out of bounds. - if ( overlap ) - { - if( firstOverlap ) - { - // Performing the first assignment of value like this allows - // VariableLengthVector type to be resized properly. - value = static_cast< RealType >( this->GetInputImage()->GetPixel(neighIndex) ) * overlap; - firstOverlap = false; - } - else - { - value += static_cast< RealType >( this->GetInputImage()->GetPixel(neighIndex) ) * overlap; - } - totalOverlap += overlap; - } - - if ( totalOverlap == 1.0 ) - { - // finished - break; - } + value += static_cast< RealType >( inputImagePtr->GetPixel(neighIndex) ) * overlap; } return ( static_cast< OutputType >( value ) ); diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkMahalanobisDistanceThresholdImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkMahalanobisDistanceThresholdImageFunction.hxx index be8d2c0bbbd557867e5107db76b9bdbb22ca1349..0e4e88037b420ce8b9040082e3c3c3f207172fea 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkMahalanobisDistanceThresholdImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkMahalanobisDistanceThresholdImageFunction.hxx @@ -143,14 +143,14 @@ MahalanobisDistanceThresholdImageFunction< TInputImage, TCoordRep > // Deal with cases that are barely negative. // In theory they should never appear, but // they may happen and would produce NaNs - // in the vcl_sqrt + // in the std::sqrt if ( mahalanobisDistanceSquared < 0.0 ) { mahalanobisDistance = 0.0; } else { - mahalanobisDistance = vcl_sqrt(mahalanobisDistanceSquared); + mahalanobisDistance = std::sqrt(mahalanobisDistanceSquared); } return mahalanobisDistance; diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkRayCastInterpolateImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkRayCastInterpolateImageFunction.hxx index 9ce9866c412366e767348692207430f34c3ade8b..596def191eb214b6e129d9337a5be7878af66079 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkRayCastInterpolateImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkRayCastInterpolateImageFunction.hxx @@ -107,7 +107,7 @@ public: if ( m_ValidRay ) { - return vcl_sqrt(m_VoxelIncrement[0] * spacing[0] * m_VoxelIncrement[0] * spacing[0] + return std::sqrt(m_VoxelIncrement[0] * spacing[0] * m_VoxelIncrement[0] * spacing[0] + m_VoxelIncrement[1] * spacing[1] * m_VoxelIncrement[1] * spacing[1] + m_VoxelIncrement[2] * spacing[2] * m_VoxelIncrement[2] * spacing[2]); } @@ -432,10 +432,10 @@ RayCastHelper< TInputImage, TCoordRep > + C * m_BoundingCorner[c1][2] ); // initialise plane value and normalise - m_BoundingPlane[j][0] = A / vcl_sqrt(A * A + B * B + C * C); - m_BoundingPlane[j][1] = B / vcl_sqrt(A * A + B * B + C * C); - m_BoundingPlane[j][2] = C / vcl_sqrt(A * A + B * B + C * C); - m_BoundingPlane[j][3] = D / vcl_sqrt(A * A + B * B + C * C); + m_BoundingPlane[j][0] = A / std::sqrt(A * A + B * B + C * C); + m_BoundingPlane[j][1] = B / std::sqrt(A * A + B * B + C * C); + m_BoundingPlane[j][2] = C / std::sqrt(A * A + B * B + C * C); + m_BoundingPlane[j][3] = D / std::sqrt(A * A + B * B + C * C); if ( ( A * A + B * B + C * C ) == 0 ) { @@ -765,9 +765,9 @@ RayCastHelper< TInputImage, TCoordRep > // Calculate the number of voxels in each direction - xNum = vcl_fabs(m_RayVoxelStartPosition[0] - m_RayVoxelEndPosition[0]); - yNum = vcl_fabs(m_RayVoxelStartPosition[1] - m_RayVoxelEndPosition[1]); - zNum = vcl_fabs(m_RayVoxelStartPosition[2] - m_RayVoxelEndPosition[2]); + xNum = std::fabs(m_RayVoxelStartPosition[0] - m_RayVoxelEndPosition[0]); + yNum = std::fabs(m_RayVoxelStartPosition[1] - m_RayVoxelEndPosition[1]); + zNum = std::fabs(m_RayVoxelStartPosition[2] - m_RayVoxelEndPosition[2]); // The direction iterated in is that with the greatest number of voxels // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -972,9 +972,9 @@ RayCastHelper< TInputImage, TCoordRep > startOK = false; endOK = false; - Istart[0] = (int)vcl_floor(m_RayVoxelStartPosition[0]); - Istart[1] = (int)vcl_floor(m_RayVoxelStartPosition[1]); - Istart[2] = (int)vcl_floor(m_RayVoxelStartPosition[2]); + Istart[0] = (int)std::floor(m_RayVoxelStartPosition[0]); + Istart[1] = (int)std::floor(m_RayVoxelStartPosition[1]); + Istart[2] = (int)std::floor(m_RayVoxelStartPosition[2]); if ( ( Istart[0] >= 0 ) && ( Istart[0] + Idirn[0] < m_NumberOfVoxelsInX ) && ( Istart[1] >= 0 ) && ( Istart[1] + Idirn[1] < m_NumberOfVoxelsInY ) @@ -991,13 +991,13 @@ RayCastHelper< TInputImage, TCoordRep > m_TotalRayVoxelPlanes--; } - Istart[0] = (int)vcl_floor(m_RayVoxelStartPosition[0] + Istart[0] = (int)std::floor(m_RayVoxelStartPosition[0] + m_TotalRayVoxelPlanes * m_VoxelIncrement[0]); - Istart[1] = (int)vcl_floor(m_RayVoxelStartPosition[1] + Istart[1] = (int)std::floor(m_RayVoxelStartPosition[1] + m_TotalRayVoxelPlanes * m_VoxelIncrement[1]); - Istart[2] = (int)vcl_floor(m_RayVoxelStartPosition[2] + Istart[2] = (int)std::floor(m_RayVoxelStartPosition[2] + m_TotalRayVoxelPlanes * m_VoxelIncrement[2]); if ( ( Istart[0] >= 0 ) && ( Istart[0] + Idirn[0] < m_NumberOfVoxelsInX ) @@ -1062,7 +1062,7 @@ RayCastHelper< TInputImage, TCoordRep > for ( i = 0; i < 4; i++ ) { - m_RayIntersectionVoxels[i] = 0; + m_RayIntersectionVoxels[i] = ITK_NULLPTR; } for ( i = 0; i < 3; i++ ) { @@ -1121,7 +1121,7 @@ RayCastHelper< TInputImage, TCoordRep > m_RayIntersectionVoxels[0] = m_RayIntersectionVoxels[1] = m_RayIntersectionVoxels[2] = - m_RayIntersectionVoxels[3] = NULL; + m_RayIntersectionVoxels[3] = ITK_NULLPTR; } break; } @@ -1153,7 +1153,7 @@ RayCastHelper< TInputImage, TCoordRep > m_RayIntersectionVoxels[0] = m_RayIntersectionVoxels[1] = m_RayIntersectionVoxels[2] = - m_RayIntersectionVoxels[3] = NULL; + m_RayIntersectionVoxels[3] = ITK_NULLPTR; } break; } @@ -1185,7 +1185,7 @@ RayCastHelper< TInputImage, TCoordRep > m_RayIntersectionVoxels[0] = m_RayIntersectionVoxels[1] = m_RayIntersectionVoxels[2] = - m_RayIntersectionVoxels[3] = NULL; + m_RayIntersectionVoxels[3] = ITK_NULLPTR; } break; } @@ -1261,20 +1261,20 @@ RayCastHelper< TInputImage, TCoordRep > { case TRANSVERSE_IN_X: { - y = m_Position3Dvox[1].GetSum() - vcl_floor(m_Position3Dvox[1].GetSum()); - z = m_Position3Dvox[2].GetSum() - vcl_floor(m_Position3Dvox[2].GetSum()); + y = m_Position3Dvox[1].GetSum() - std::floor(m_Position3Dvox[1].GetSum()); + z = m_Position3Dvox[2].GetSum() - std::floor(m_Position3Dvox[2].GetSum()); break; } case TRANSVERSE_IN_Y: { - y = m_Position3Dvox[0].GetSum() - vcl_floor(m_Position3Dvox[0].GetSum()); - z = m_Position3Dvox[2].GetSum() - vcl_floor(m_Position3Dvox[2].GetSum()); + y = m_Position3Dvox[0].GetSum() - std::floor(m_Position3Dvox[0].GetSum()); + z = m_Position3Dvox[2].GetSum() - std::floor(m_Position3Dvox[2].GetSum()); break; } case TRANSVERSE_IN_Z: { - y = m_Position3Dvox[0].GetSum() - vcl_floor(m_Position3Dvox[0].GetSum()); - z = m_Position3Dvox[1].GetSum() - vcl_floor(m_Position3Dvox[1].GetSum()); + y = m_Position3Dvox[0].GetSum() - std::floor(m_Position3Dvox[0].GetSum()); + z = m_Position3Dvox[1].GetSum() - std::floor(m_Position3Dvox[1].GetSum()); break; } default: @@ -1284,7 +1284,6 @@ RayCastHelper< TInputImage, TCoordRep > err.SetDescription("The ray traversal direction is unset " "- GetCurrentIntensity()."); throw err; - return 0; } } @@ -1386,7 +1385,7 @@ RayCastHelper< TInputImage, TCoordRep > for ( i = 0; i < 4; i++ ) { - m_RayIntersectionVoxels[i] = 0; + m_RayIntersectionVoxels[i] = ITK_NULLPTR; } for ( i = 0; i < 3; i++ ) { diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.h b/Utilities/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.h index bb76f4e50d73ca9650e6c06adf6a859cfff2b484..d3ed80b4079ed2ca94125b2e2dbccb7ea4897935 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.h +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.h @@ -39,7 +39,7 @@ class CosineWindowFunction { public: inline TOutput operator()(const TInput & A) const - { return (TOutput)vcl_cos(A * m_Factor); } + { return (TOutput)std::cos(A * m_Factor); } private: /** Equal to \f$ \frac{\pi}{2 m} \f$ */ @@ -59,7 +59,7 @@ class HammingWindowFunction { public: inline TOutput operator()(const TInput & A) const - { return (TOutput)0.54 + 0.46 * vcl_cos(A * m_Factor); } + { return (TOutput)0.54 + 0.46 * std::cos(A * m_Factor); } private: /** Equal to \f$ \frac{\pi}{m} \f$ */ @@ -104,7 +104,7 @@ public: { if ( A == 0.0 ) { return (TOutput)1.0; } double z = m_Factor * A; - return (TOutput)( vcl_sin(z) / z ); + return (TOutput)( std::sin(z) / z ); } private: @@ -127,7 +127,7 @@ public: inline TOutput operator()(const TInput & A) const { return (TOutput) - ( 0.42 + 0.5 * vcl_cos(A * m_Factor1) + 0.08 * vcl_cos(A * m_Factor2) ); + ( 0.42 + 0.5 * std::cos(A * m_Factor1) + 0.08 * std::cos(A * m_Factor2) ); } private: @@ -341,7 +341,7 @@ private: { double px = vnl_math::pi * x; - return ( x == 0.0 ) ? 1.0 : vcl_sin(px) / px; + return ( x == 0.0 ) ? 1.0 : std::sin(px) / px; } }; } // namespace itk diff --git a/Utilities/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.hxx b/Utilities/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.hxx index dca39413dbb79272083a6c3b202f7c4b6d4a9381..54b540ae4ff4fc21aabbfbf76b46dd3c0672c183 100644 --- a/Utilities/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.hxx +++ b/Utilities/ITK/Modules/Core/ImageFunction/include/itkWindowedSincInterpolateImageFunction.hxx @@ -123,7 +123,7 @@ WindowedSincInterpolateImageFunction< TInputImage, VRadius, // Call the parent implementation Superclass::SetInputImage(image); - if ( image == NULL ) + if ( image == ITK_NULLPTR ) { return; } @@ -239,7 +239,7 @@ WindowedSincInterpolateImageFunction< TInputImage, VRadius, { // Increment the offset, taking it through the range // (dist + rad - 1, ..., dist - rad), i.e. all x - // such that vcl_abs(x) <= rad + // such that std::abs(x) <= rad x -= 1.0; // Compute the weight for this m diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkBinaryMask3DMeshSource.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkBinaryMask3DMeshSource.hxx index 88f7a1bb4caceed8fea9fb3d53d0e671c7bd9f4b..5129d8deaf59002360d9af9ad4c7b44c52b31d0a 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkBinaryMask3DMeshSource.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkBinaryMask3DMeshSource.hxx @@ -26,40 +26,45 @@ namespace itk { template< typename TInputImage, typename TOutputMesh > BinaryMask3DMeshSource< TInputImage, TOutputMesh > -::BinaryMask3DMeshSource() +::BinaryMask3DMeshSource() : + m_RegionOfInterestProvidedByUser(false), + m_LastRow(ITK_NULLPTR), + m_LastFrame(ITK_NULLPTR), + m_CurrentRow(ITK_NULLPTR), + m_CurrentFrame(ITK_NULLPTR), + m_CurrentRowIndex(0), + m_CurrentFrameIndex(0), + m_LastRowNum(0), + m_LastFrameNum(0), + m_CurrentRowNum(200), + m_CurrentFrameNum(2000), + m_NumberOfNodes(0), + m_NumberOfCells(0), + m_NodeLimit(2000), + m_CellLimit(4000), + m_ImageWidth(0), + m_ImageHeight(0), + m_ImageDepth(0), + m_ColFlag(0), + m_RowFlag(0), + m_FrameFlag(0), + m_LastRowIndex(0), + m_LastVoxelIndex(0), + m_LastFrameIndex(0), + m_PointFound(0), + m_ObjectValue(NumericTraits< InputPixelType >::One), + m_OutputMesh(ITK_NULLPTR), + m_InputImage(ITK_NULLPTR) { // Modify superclass default values, can be overridden by subclasses this->SetNumberOfRequiredInputs(1); - m_RegionOfInterestProvidedByUser = false; - SizeType size; size.Fill( 0 ); m_RegionOfInterest.SetSize(size); - m_NumberOfCells = 0; - m_NumberOfNodes = 0; - - m_NodeLimit = 2000; - m_CellLimit = 4000; - m_LastRowIndex = 0; - m_LastVoxelIndex = 0; - m_LastFrameIndex = 0; - m_CurrentRowIndex = 0; - m_CurrentFrameIndex = 0; - m_CurrentFrame = 0; - m_CurrentRow = 0; - m_LastRow = 0; - m_LastRowNum = 0; - m_LastFrameNum = 0; - m_LastFrame = 0; - m_CurrentRowNum = 200; - m_CurrentFrameNum = 2000; this->GetOutput()->GetPoints()->Reserve(m_NodeLimit); this->GetOutput()->GetCells()->Reserve(m_CellLimit); - m_OutputMesh = 0; - m_InputImage = 0; - m_ObjectValue = NumericTraits< InputPixelType >::One; } template< typename TInputImage, typename TOutputMesh > @@ -1055,12 +1060,12 @@ BinaryMask3DMeshSource< TInputImage, TOutputMesh > m_LastFrameIndex = 0; m_CurrentRowIndex = 0; m_CurrentFrameIndex = 0; - m_CurrentFrame = 0; - m_CurrentRow = 0; - m_LastRow = 0; + m_CurrentFrame = ITK_NULLPTR; + m_CurrentRow = ITK_NULLPTR; + m_LastRow = ITK_NULLPTR; m_LastRowNum = 0; m_LastFrameNum = 0; - m_LastFrame = 0; + m_LastFrame = ITK_NULLPTR; m_CurrentRowNum = 200; m_CurrentFrameNum = 2000; m_OutputMesh = this->GetOutput(); @@ -1294,7 +1299,7 @@ BinaryMask3DMeshSource< TInputImage, TOutputMesh > free (m_LastRow[i]); } free (m_LastRow); - m_LastRow = NULL; + m_LastRow = ITK_NULLPTR; } m_LastRowNum = 0; } @@ -1341,7 +1346,7 @@ BinaryMask3DMeshSource< TInputImage, TOutputMesh > free (m_LastFrame[i]); } free (m_LastFrame); - m_LastFrame = 0; + m_LastFrame = ITK_NULLPTR; } } @@ -2578,7 +2583,7 @@ BinaryMask3DMeshSource< TInputImage, TOutputMesh > if ( ( end - start ) > 1 ) { - mid = static_cast< int >( vcl_floor( static_cast< float >( ( start + end ) / 2 ) ) ); + mid = static_cast< int >( std::floor( static_cast< float >( ( start + end ) / 2 ) ) ); if ( lindex == m_LastRow[mid][0] ) { m_PointFound = 1; @@ -2623,7 +2628,7 @@ BinaryMask3DMeshSource< TInputImage, TOutputMesh > if ( ( end - start ) > 1 ) { - mid = static_cast< int >( vcl_floor( static_cast< float >( ( start + end ) / 2 ) ) ); + mid = static_cast< int >( std::floor( static_cast< float >( ( start + end ) / 2 ) ) ); if ( lindex == m_LastFrame[mid][0] ) { m_PointFound = 1; diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkConnectedRegionsMeshFilter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkConnectedRegionsMeshFilter.hxx index 9a85247531f7e8f272627de51df57af5236816e0..2b1ca381e7c02736ae18bd846f1b941f05657914 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkConnectedRegionsMeshFilter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkConnectedRegionsMeshFilter.hxx @@ -41,9 +41,13 @@ namespace itk */ template< typename TInputMesh, typename TOutputMesh > ConnectedRegionsMeshFilter< TInputMesh, TOutputMesh > -::ConnectedRegionsMeshFilter() +::ConnectedRegionsMeshFilter() : + m_ExtractionMode(Self::LargestRegion), + m_NumberOfCellsInRegion(NumericTraits< SizeValueType >::Zero), + m_RegionNumber(NumericTraits< IdentifierType >::Zero), + m_Wave(ITK_NULLPTR), + m_Wave2(ITK_NULLPTR) { - m_ExtractionMode = Self::LargestRegion; m_ClosestPoint.Fill(0); } @@ -287,7 +291,7 @@ ConnectedRegionsMeshFilter< TInputMesh, TOutputMesh > delete m_Wave; delete m_Wave2; - m_Wave = m_Wave2 = 0; + m_Wave = m_Wave2 = ITK_NULLPTR; itkDebugMacro (<< "Extracted " << m_RegionNumber << " region(s)"); diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkInteriorExteriorMeshFilter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkInteriorExteriorMeshFilter.hxx index 11371688a4003071081b09b5082278c0dcd4f840..e1190eb0e4e64f38189ce24d6c42a04ec721cabb 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkInteriorExteriorMeshFilter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkInteriorExteriorMeshFilter.hxx @@ -59,16 +59,12 @@ InteriorExteriorMeshFilter< TInputMesh, TOutputMesh, TSpatialFunction > ::GenerateData(void) { typedef typename TInputMesh::PointsContainer InputPointsContainer; - typedef typename TOutputMesh::PointsContainer OutputPointsContainer; typedef typename TInputMesh::PointsContainerConstPointer InputPointsContainerConstPointer; - typedef typename TOutputMesh::PointsContainerPointer OutputPointsContainerPointer; typedef typename TInputMesh::PointDataContainer InputPointDataContainer; - typedef typename TOutputMesh::PointDataContainer OutputPointDataContainer; typedef typename TInputMesh::PointDataContainerConstPointer InputPointDataContainerConstPointer; - typedef typename TOutputMesh::PointDataContainerPointer OutputPointDataContainerPointer; const InputMeshType *inputMesh = this->GetInput(); OutputMeshPointer outputMesh = this->GetOutput(); diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkMesh.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkMesh.hxx index 0e9a57ce88d1d6fe14c96c3d6f18a046b3f647cf..fbd786d95cd1b9ee11aa7a952c352e0d7f38a716 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkMesh.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkMesh.hxx @@ -48,7 +48,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > os << indent << "Number Of Cells: " << ( ( m_CellsContainer ) ? m_CellsContainer->Size() : 0 ) << std::endl; os << indent << "Cell Data Container pointer: " - << ( ( m_CellDataContainer ) ? m_CellDataContainer.GetPointer() : 0 ) << std::endl; + << ( ( m_CellDataContainer ) ? m_CellDataContainer.GetPointer() : ITK_NULLPTR ) << std::endl; os << indent << "Size of Cell Data Container: " << ( ( m_CellDataContainer ) ? m_CellDataContainer->Size() : 0 ) << std::endl; os << indent << "Number of explicit cell boundary assignments: " @@ -280,7 +280,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > /** * Ask the container if the cell identifier exists. */ - CellType * cellptr = 0; + CellType * cellptr = ITK_NULLPTR; const bool found = m_CellsContainer->GetElementIfIndexExists(cellId, &cellptr); if ( found ) { @@ -514,9 +514,9 @@ Mesh< TPixelType, VDimension, TMeshTraits > this->ReleaseCellsMemory(); - m_CellsContainer = 0; - m_CellDataContainer = 0; - m_CellLinksContainer = 0; + m_CellsContainer = ITK_NULLPTR; + m_CellDataContainer = ITK_NULLPTR; + m_CellLinksContainer = ITK_NULLPTR; } /** @@ -613,7 +613,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > * and put them in the output set except for the cell through which the * request was made. First we empty the output set. */ - if ( cellSet != 0 ) + if ( cellSet != ITK_NULLPTR ) { cellSet->erase( cellSet->begin(), cellSet->end() ); @@ -720,7 +720,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > */ currentCells->erase(cellId); CellIdentifier numberOfNeighboringCells = currentCells->size(); - if ( cellSet != 0 ) + if ( cellSet != ITK_NULLPTR ) { *cellSet = *currentCells; } @@ -783,7 +783,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > * Loop through UsingCells and put them in the output set. First * we empty the output set. */ - if ( cellSet != 0 ) + if ( cellSet != ITK_NULLPTR ) { cellSet->erase( cellSet->begin(), cellSet->end() ); @@ -869,7 +869,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > * this set to the output cell set. */ CellIdentifier numberOfNeighboringCells = currentCells->size(); - if ( cellSet != 0 ) + if ( cellSet != ITK_NULLPTR ) { *cellSet = *currentCells; } @@ -911,7 +911,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > if ( m_BoundaryAssignmentsContainers[dimension]-> GetElementIfIndexExists(assignId, &boundaryId) ) { - CellType * boundaryptr = 0; + CellType * boundaryptr = ITK_NULLPTR; const bool found = m_CellsContainer-> GetElementIfIndexExists(boundaryId, &boundaryptr); if ( found ) @@ -1138,19 +1138,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > { this->Superclass::CopyInformation(data); - const Self *mesh = NULL; - - try - { - mesh = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - // mesh could not be cast back down - itkExceptionMacro( << "itk::Mesh::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *mesh = dynamic_cast< const Self * >( data ); if ( !mesh ) { @@ -1170,19 +1158,7 @@ Mesh< TPixelType, VDimension, TMeshTraits > { this->Superclass::Graft(data); - const Self *mesh = NULL; - - try - { - mesh = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - // mesh could not be cast back down - itkExceptionMacro( << "itk::Mesh::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *mesh = dynamic_cast< const Self * >( data ); if ( !mesh ) { diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkMeshRegion.h b/Utilities/ITK/Modules/Core/Mesh/include/itkMeshRegion.h index 052e5079e5598f08728ba00884a5c4cf50734729..d861e1571c5c1d8d880e392276e0b500b2a81701 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkMeshRegion.h +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkMeshRegion.h @@ -67,7 +67,7 @@ public: virtual ~MeshRegion(); /** Return the region type. Meshes are described with unstructured regions. */ - virtual RegionType GetRegionType() const + virtual RegionType GetRegionType() const ITK_OVERRIDE { return Superclass::ITK_UNSTRUCTURED_REGION; } /** Get the number of regions. */ diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkMeshSource.h b/Utilities/ITK/Modules/Core/Mesh/include/itkMeshSource.h index 79db8a303cddc87c985e813476a8dc9ccd6aa70a..d03baa7220818e000a362cfbad3ec04fb5d278e9 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkMeshSource.h +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkMeshSource.h @@ -139,17 +139,17 @@ public: * an implementation of MakeOutput(). */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; protected: MeshSource(); virtual ~MeshSource() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Requested region of Mesh is specified as i of N unstructured regions. * Since all DataObjects should be able to set the requested region in * unstructured form, just copy output->RequestedRegion all inputs. */ - void GenerateInputRequestedRegion(); + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; private: MeshSource(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkParametricSpaceToImageSpaceMeshFilter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkParametricSpaceToImageSpaceMeshFilter.hxx index 672c86b5fc1746f0c4dbc031be05a33f37321c20..09560f66e89b408567ee5ceba18a62fe8dc3d77e 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkParametricSpaceToImageSpaceMeshFilter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkParametricSpaceToImageSpaceMeshFilter.hxx @@ -56,13 +56,11 @@ ParametricSpaceToImageSpaceMeshFilter< TInputMesh, TOutputMesh > typedef typename TInputMesh::PointsContainer InputPointsContainer; typedef typename TOutputMesh::PointsContainer OutputPointsContainer; - typedef typename TInputMesh::PointsContainerPointer InputPointsContainerPointer; typedef typename TOutputMesh::PointsContainerPointer OutputPointsContainerPointer; typedef typename TInputMesh::PointDataContainer InputPointDataContainer; typedef typename TOutputMesh::PointDataContainer OutputPointDataContainer; - typedef typename TInputMesh::PointDataContainerPointer InputPointDataContainerPointer; typedef typename TOutputMesh::PointDataContainerPointer OutputPointDataContainerPointer; const InputMeshType *inputMesh = this->GetInput(); diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkRegularSphereMeshSource.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkRegularSphereMeshSource.hxx index 3efae9788b11bcf82d9f966bb82c90b36d5a5789..a10617a7768f83ea06d5cc965e3850e367793624 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkRegularSphereMeshSource.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkRegularSphereMeshSource.hxx @@ -299,7 +299,7 @@ RegularSphereMeshSource< TOutputMesh > // set output outputMesh->Graft(result); - result->SetCells(NULL); + result->SetCells(ITK_NULLPTR); } } diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMesh.h b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMesh.h index c994236d8bb1e2bca5ad130cf4b6781c82f6abd8..e3d2b22b1c0b538159c8270b497c65d3ca222d2a 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMesh.h +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMesh.h @@ -170,7 +170,7 @@ public: /** * Get all neighbor points with a specified radius */ - NeighborListType * GetNeighbors(PointIdentifier pointId, unsigned int radius, NeighborListType *list = NULL) const; + NeighborListType * GetNeighbors(PointIdentifier pointId, unsigned int radius, NeighborListType *list = ITK_NULLPTR) const; /** * Add a neighbor to a point. diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMesh.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMesh.hxx index dfd76c359155306852ce0d07d6479201bfc8b0fa..09976bf836f4fe16228472bcf448c25ceef9eb6b 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMesh.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMesh.hxx @@ -80,17 +80,15 @@ SimplexMesh< TPixelType, VDimension, TMeshTraits > mesh = dynamic_cast< const Superclass * >( data ); - if ( mesh ) - { - this->m_MaximumNumberOfRegions = mesh->GetMaximumNumberOfRegions(); - } - else + if ( mesh == ITK_NULLPTR ) { // pointer could not be cast back down itkExceptionMacro( << "itk::Mesh::CopyInformation() cannot cast " << typeid( data ).name() << " to " << typeid( Superclass * ).name() ); } + + this->m_MaximumNumberOfRegions = mesh->GetMaximumNumberOfRegions(); } template< typename TPixelType, unsigned int VDimension, typename TMeshTraits > @@ -288,7 +286,7 @@ typename SimplexMesh< TPixelType, VDimension, TMeshTraits >::NeighborListType * SimplexMesh< TPixelType, VDimension, TMeshTraits > ::GetNeighbors(PointIdentifier idx, unsigned int radius, NeighborListType *list) const { - if ( list == NULL ) + if ( list == ITK_NULLPTR ) { list = new NeighborListType(); IndexArray neighborArray = GetNeighbors(idx); diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshAdaptTopologyFilter.h b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshAdaptTopologyFilter.h index d249fbffba4f714cce9d95d05505661ab5ea9005..c3117ac5a042e5b49ae35b8cd7573041aedcd87e 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshAdaptTopologyFilter.h +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshAdaptTopologyFilter.h @@ -134,11 +134,11 @@ public: double meanCurvature = 0; PointIdentifier refPoint = *it; double val = mesh->GetMeanCurvature(*it++); - meanCurvature += vcl_abs(val); + meanCurvature += std::abs(val); PointIdentifier id1 = *it; val = mesh->GetMeanCurvature(*it++); - meanCurvature += vcl_abs(val); + meanCurvature += std::abs(val); PointIdentifier id2; @@ -152,7 +152,7 @@ public: area += ComputeArea(refPoint, id1, id2); id1 = id2; val = mesh->GetMeanCurvature(*it); - meanCurvature += vcl_abs(val); + meanCurvature += std::abs(val); cnt++; it++; } @@ -181,7 +181,7 @@ public: mesh->GetPoint(p1, &v1); mesh->GetPoint(p2, &v2); mesh->GetPoint(p3, &v3); - return vcl_abs (itk_cross_3d( ( v2 - v1 ).GetVnlVector(), ( v3 - v1 ).GetVnlVector() ).two_norm() / 2.0); + return std::abs (itk_cross_3d( ( v2 - v1 ).GetVnlVector(), ( v3 - v1 ).GetVnlVector() ).two_norm() / 2.0); } typename DoubleValueMapType::Pointer GetAreaMap() diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshAdaptTopologyFilter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshAdaptTopologyFilter.hxx index e65fc769947d198f79c44da5468caf3468f9d0ef..131f464c410eb607a15bc9e8807f975342da155f 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshAdaptTopologyFilter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshAdaptTopologyFilter.hxx @@ -33,14 +33,15 @@ namespace itk { template< typename TInputMesh, typename TOutputMesh > -SimplexMeshAdaptTopologyFilter< TInputMesh, TOutputMesh >::SimplexMeshAdaptTopologyFilter() +SimplexMeshAdaptTopologyFilter< TInputMesh, TOutputMesh >::SimplexMeshAdaptTopologyFilter() : + m_IdOffset(0), + m_Threshold(0.5), + m_SelectionMethod(0), + m_ModifiedCount(0), + m_Output(TOutputMesh::New()) { - m_Output = TOutputMesh::New(); this->ProcessObject::SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput( 0, m_Output.GetPointer() ); - m_ModifiedCount = 0; - m_SelectionMethod = 0; - m_Threshold = 0.5; } template< typename TInputMesh, typename TOutputMesh > diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.h b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.h index fa90b3b32d7a7490e13b471997d8a9df707c2109..209d8f0cc0c17eddbc0744453d81a9b0e3da0301 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.h +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.h @@ -176,7 +176,7 @@ protected: protected: SimplexMeshVolumeCalculator(); virtual ~SimplexMeshVolumeCalculator(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: SimplexMeshVolumeCalculator(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.hxx index fb83cebc381eac3d10b520c6355fccd6dca8a185..133e4fa82089d49e3a18adeba18b711ffc6472ab 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.hxx @@ -27,12 +27,24 @@ namespace itk */ template< typename TInputMesh > SimplexMeshVolumeCalculator< TInputMesh > -::SimplexMeshVolumeCalculator() +::SimplexMeshVolumeCalculator() : + m_Volume(0.0), + m_VolumeX(0.0), + m_VolumeY(0.0), + m_VolumeZ(0.0), + m_Area(0.0), + m_Kx(0.0), + m_Ky(0.0), + m_Kz(0.0), + m_Wxyz(0.0), + m_Wxy(0.0), + m_Wxz(0.0), + m_Wyz(0.0), + m_Muncx(0), + m_Muncy(0), + m_Muncz(0), + m_NumberOfTriangles(0) { - m_Volume = m_VolumeX = m_VolumeY = m_VolumeZ = 0.0; - m_Area = 0.0; - m_Kx = m_Ky = m_Kz = 0.0; - m_NumberOfTriangles = 0; } template< typename TInputMesh > @@ -75,7 +87,7 @@ void SimplexMeshVolumeCalculator< TInputMesh > m_Volume = ( m_Kx * m_VolumeX + m_Ky * m_VolumeY + m_Kz * m_VolumeZ ); - m_Volume = vcl_fabs(m_Volume); + m_Volume = std::fabs(m_Volume); } template< typename TInputMesh > @@ -139,7 +151,7 @@ SimplexMeshVolumeCalculator< TInputMesh > // Normalize normal // - length = vcl_sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]); + length = std::sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]); if ( length != 0.0 ) { u[0] /= length; @@ -153,7 +165,7 @@ SimplexMeshVolumeCalculator< TInputMesh > // Determine max unit normal component... // - absu[0] = vcl_fabs(u[0]); absu[1] = vcl_fabs(u[1]); absu[2] = vcl_fabs(u[2]); + absu[0] = std::fabs(u[0]); absu[1] = std::fabs(u[1]); absu[2] = std::fabs(u[2]); if ( ( absu[0] > absu[1] ) && ( absu[0] > absu[2] ) ) { m_Muncx++; @@ -196,11 +208,11 @@ SimplexMeshVolumeCalculator< TInputMesh > // Area of a triangle using Heron's formula... // - a = vcl_sqrt(ii[1] + jj[1] + kk[1]); - b = vcl_sqrt(ii[0] + jj[0] + kk[0]); - c = vcl_sqrt(ii[2] + jj[2] + kk[2]); + a = std::sqrt(ii[1] + jj[1] + kk[1]); + b = std::sqrt(ii[0] + jj[0] + kk[0]); + c = std::sqrt(ii[2] + jj[2] + kk[2]); s = 0.5 * ( a + b + c ); - area = vcl_sqrt( vcl_fabs( s * ( s - a ) * ( s - b ) * ( s - c ) ) ); + area = std::sqrt( std::fabs( s * ( s - a ) * ( s - b ) * ( s - c ) ) ); // Volume elements ... // diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkSphereMeshSource.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkSphereMeshSource.hxx index e7d78cfa118739c68f428ffd464c677e852bfa64..6b45d7b45ab7ca5736433067a372c65d0091d132 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkSphereMeshSource.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkSphereMeshSource.hxx @@ -90,7 +90,7 @@ SphereMeshSource< TOutputMesh > { for ( v = vbeg, j = 0; j < m_ResolutionY; v += vstep, j++ ) { - if ( vcl_cos(u) > 0 ) + if ( std::cos(u) > 0 ) { signu = 1; } @@ -98,7 +98,7 @@ SphereMeshSource< TOutputMesh > { signu = -1; } - if ( vcl_cos(v) > 0 ) + if ( std::cos(v) > 0 ) { signv = 1; } @@ -107,10 +107,10 @@ SphereMeshSource< TOutputMesh > signv = -1; } - p1[0] = m_Scale[0] * signu * ( vcl_pow( (float)( vcl_fabs( vcl_cos(u) ) ), (float)m_Squareness1 ) ) * signv - * ( vcl_pow( (float)( vcl_fabs( vcl_cos(v) ) ), (float)m_Squareness2 ) ) + m_Center[0]; + p1[0] = m_Scale[0] * signu * ( std::pow( (float)( std::fabs( std::cos(u) ) ), (float)m_Squareness1 ) ) * signv + * ( std::pow( (float)( std::fabs( std::cos(v) ) ), (float)m_Squareness2 ) ) + m_Center[0]; - if ( vcl_sin(v) > 0 ) + if ( std::sin(v) > 0 ) { signv = 1; } @@ -119,10 +119,10 @@ SphereMeshSource< TOutputMesh > signv = -1; } - p1[1] = m_Scale[1] * signu * ( vcl_pow( (float)( vcl_fabs( vcl_cos(u) ) ), (float)m_Squareness1 ) ) * signv - * ( vcl_pow( (float)( vcl_fabs( vcl_sin(v) ) ), (float)m_Squareness2 ) ) + m_Center[1]; + p1[1] = m_Scale[1] * signu * ( std::pow( (float)( std::fabs( std::cos(u) ) ), (float)m_Squareness1 ) ) * signv + * ( std::pow( (float)( std::fabs( std::sin(v) ) ), (float)m_Squareness2 ) ) + m_Center[1]; - if ( vcl_sin(u) > 0 ) + if ( std::sin(u) > 0 ) { signu = 1; } @@ -131,7 +131,7 @@ SphereMeshSource< TOutputMesh > signu = -1; } - p1[2] = m_Scale[2] * signu * ( vcl_pow( (float)( vcl_fabs( vcl_sin(u) ) ), (float)m_Squareness1 ) ) + p1[2] = m_Scale[2] * signu * ( std::pow( (float)( std::fabs( std::sin(u) ) ), (float)m_Squareness1 ) ) + m_Center[2]; point.Value() = p1; @@ -140,21 +140,21 @@ SphereMeshSource< TOutputMesh > } // calculate the south pole node - p1[0] = ( m_Scale[0] * ( vcl_pow( (float)( vcl_fabs( vcl_cos(-vnl_math::pi / 2) ) ), 1.0f ) ) - * ( vcl_pow( (float)( vcl_fabs( vcl_cos(0.0) ) ), 1.0f ) ) + m_Center[0] ); - p1[1] = ( m_Scale[1] * ( vcl_pow( (float)( vcl_fabs( vcl_cos(-vnl_math::pi / 2) ) ), 1.0f ) ) - * ( vcl_pow( (float)( vcl_fabs( vcl_sin(0.0) ) ), 1.0f ) ) + m_Center[1] ); - p1[2] = ( m_Scale[2] * -1 * ( vcl_pow( (float)( vcl_fabs( vcl_sin(-vnl_math::pi / 2) ) ), 1.0f ) ) + p1[0] = ( m_Scale[0] * ( std::pow( (float)( std::fabs( std::cos(-vnl_math::pi / 2) ) ), 1.0f ) ) + * ( std::pow( (float)( std::fabs( std::cos(0.0) ) ), 1.0f ) ) + m_Center[0] ); + p1[1] = ( m_Scale[1] * ( std::pow( (float)( std::fabs( std::cos(-vnl_math::pi / 2) ) ), 1.0f ) ) + * ( std::pow( (float)( std::fabs( std::sin(0.0) ) ), 1.0f ) ) + m_Center[1] ); + p1[2] = ( m_Scale[2] * -1 * ( std::pow( (float)( std::fabs( std::sin(-vnl_math::pi / 2) ) ), 1.0f ) ) + m_Center[2] ); point.Value() = p1; ++point; // calculate the north pole node - p1[0] = ( m_Scale[0] * ( vcl_pow( (float)( vcl_fabs( vcl_cos(vnl_math::pi / 2) ) ), 1.0f ) ) - * ( vcl_pow(vcl_fabs( vcl_cos(0.0) ), 1.0) ) + m_Center[0] ); - p1[1] = ( m_Scale[1] * ( vcl_pow( (float)( vcl_fabs( vcl_cos(vnl_math::pi / 2) ) ), 1.0f ) ) - * ( vcl_pow(vcl_fabs( vcl_sin(0.0) ), 1.0) ) + m_Center[1] ); - p1[2] = ( m_Scale[2] * ( vcl_pow( (float)( vcl_fabs( vcl_sin(vnl_math::pi / 2) ) ), 1.0f ) ) + p1[0] = ( m_Scale[0] * ( std::pow( (float)( std::fabs( std::cos(vnl_math::pi / 2) ) ), 1.0f ) ) + * ( std::pow(std::fabs( std::cos(0.0) ), 1.0) ) + m_Center[0] ); + p1[1] = ( m_Scale[1] * ( std::pow( (float)( std::fabs( std::cos(vnl_math::pi / 2) ) ), 1.0f ) ) + * ( std::pow(std::fabs( std::sin(0.0) ), 1.0) ) + m_Center[1] ); + p1[2] = ( m_Scale[2] * ( std::pow( (float)( std::fabs( std::sin(vnl_math::pi / 2) ) ), 1.0f ) ) + m_Center[2] ); point.Value() = p1; ++point; diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkTransformMeshFilter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkTransformMeshFilter.hxx index 52f765df96dad7db39bc4698b2b2aa42cc913a65..1ea6c7f00333eda63c2c4613d8e20a114051bf91 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkTransformMeshFilter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkTransformMeshFilter.hxx @@ -30,7 +30,7 @@ template< typename TInputMesh, typename TOutputMesh, typename TTransform > TransformMeshFilter< TInputMesh, TOutputMesh, TTransform > ::TransformMeshFilter() { - m_Transform = 0; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. } /** diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkTriangleMeshToBinaryImageFilter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkTriangleMeshToBinaryImageFilter.hxx index 329079ad7551d8388c2c98c3b7244bf059de6eff..dc4f140c8e694b2aac12c1738cf84b6479f5d992 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkTriangleMeshToBinaryImageFilter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkTriangleMeshToBinaryImageFilter.hxx @@ -45,7 +45,7 @@ TriangleMeshToBinaryImageFilter< TInputMesh, TOutputImage > m_Direction.GetVnlMatrix().set_identity(); m_Tolerance = 1e-5; - m_InfoImage = NULL; + m_InfoImage = ITK_NULLPTR; } /** Destructor */ @@ -167,7 +167,7 @@ TriangleMeshToBinaryImageFilter< TInputMesh, TOutputImage > // Get the input and output pointers OutputImagePointer OutputImage = this->GetOutput(); - if ( m_InfoImage == NULL ) + if ( m_InfoImage == ITK_NULLPTR ) { if ( m_Size[0] == 0 || m_Size[1] == 0 || m_Size[2] == 0 ) { @@ -292,8 +292,8 @@ TriangleMeshToBinaryImageFilter< TInputMesh, TOutputImage > std::swap(p1, p2); } - int zmin = (int)( vcl_ceil(p1[2]) ); - int zmax = (int)( vcl_ceil(p2[2]) ); + int zmin = (int)( std::ceil(p1[2]) ); + int zmax = (int)( std::ceil(p2[2]) ); if ( zmin > extent[5] || zmax < extent[4] ) { @@ -370,8 +370,8 @@ TriangleMeshToBinaryImageFilter< TInputMesh, TOutputImage > continue; } double temp = 1.0 / ( Y2 - Y1 ); - int ymin = (int)( vcl_ceil(Y1) ); - int ymax = (int)( vcl_ceil(Y2) ); + int ymin = (int)( std::ceil(Y1) ); + int ymax = (int)( std::ceil(Y2) ); for ( int y = ymin; y < ymax; y++ ) { double r = ( Y2 - y ) * temp; @@ -545,8 +545,8 @@ TriangleMeshToBinaryImageFilter< TInputMesh, TOutputImage > for ( int i = 0; i < n; i++ ) { - int x1 = (int)( vcl_ceil(nlist[2 * i]) ); - int x2 = (int)( vcl_floor(nlist[2 * i + 1]) ); + int x1 = (int)( std::ceil(nlist[2 * i]) ); + int x2 = (int)( std::floor(nlist[2 * i + 1]) ); if ( x2 < extent[0] || x1 > ( extent[1] ) ) { diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkTriangleMeshToSimplexMeshFilter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkTriangleMeshToSimplexMeshFilter.hxx index 66571808a897517296580f1af612f930f95928e1..dd1918d6248fea8d70dfa611105c8827106b8e43 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkTriangleMeshToSimplexMeshFilter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkTriangleMeshToSimplexMeshFilter.hxx @@ -23,14 +23,21 @@ namespace itk { template< typename TInputMesh, typename TOutputMesh > TriangleMeshToSimplexMeshFilter< TInputMesh, TOutputMesh > -::TriangleMeshToSimplexMeshFilter() +::TriangleMeshToSimplexMeshFilter() : + m_FaceSet(ITK_NULLPTR), + m_Edges(ITK_NULLPTR), + m_EdgeNeighborList(ITK_NULLPTR), + m_VertexNeighborList(ITK_NULLPTR), + m_LineCellIndices(ITK_NULLPTR), + m_CellIdxOffset(0), + m_IdOffset(0), + m_EdgeCellId(0), + m_HandledEdgeIds(IdVectorType::New()) { OutputMeshPointer output = TOutputMesh::New(); this->ProcessObject::SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput( 0, output.GetPointer() ); - m_HandledEdgeIds = IdVectorType::New(); - m_FaceSet = NULL; } template< typename TInputMesh, typename TOutputMesh > diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataReader.h b/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataReader.h index 0db59a6804401d6eb00f93f1a598d33036050dcd..f24fb9c99e5cabb48891dd6d7a09a806be354f6f 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataReader.h +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataReader.h @@ -33,7 +33,13 @@ namespace itk * Use vtkTriangleFilter to convert your mesh to a triangle mesh. * Caviet2: itkVTKPolyDataReader can only read vtk legacy files. * Caveat3: itkVTKPolyDataReader cannot read binary vtk files. + * + * This class may be deprecated in the future. The MeshFileReader is + * preferred. + * * \ingroup ITKMesh + * + * \sa MeshFileReader */ template< typename TOutputMesh > class VTKPolyDataReader:public MeshSource< TOutputMesh > diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataWriter.h b/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataWriter.h index 6a5049661002555a5399098185f5c0f0587af449..5a5b28efa3ee2dd897a85c58c8deac2e10d43566 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataWriter.h +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataWriter.h @@ -30,7 +30,13 @@ namespace itk * * Caveat: The input to itkVTKPolyDataWriter must be a triangle mesh. * Use vtkTriangleFilter to convert your mesh to a triangle mesh. + * + * This class may be deprecated in the future. The MeshFileWriter is + * preferred. + * * \ingroup ITKMesh + * + * \sa MeshFileWriter */ template< typename TInputMesh > class VTKPolyDataWriter:public Object @@ -95,7 +101,7 @@ protected: InputMeshPointer m_Input; - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: VTKPolyDataWriter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataWriter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataWriter.hxx index b0319d3455b20cab44ca1fead243d744be23cd3d..b741738ac972c1e5ea5d6e2e4c854e265d7ac477 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataWriter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkVTKPolyDataWriter.hxx @@ -32,7 +32,7 @@ template< typename TInputMesh > VTKPolyDataWriter< TInputMesh > ::VTKPolyDataWriter() { - this->m_Input = NULL; + this->m_Input = ITK_NULLPTR; this->m_FileName = ""; } diff --git a/Utilities/ITK/Modules/Core/Mesh/include/itkWarpMeshFilter.hxx b/Utilities/ITK/Modules/Core/Mesh/include/itkWarpMeshFilter.hxx index 8686f5e243d2cefd1717dd443b90fbdbef4d5b18..31bd89caefe9adaf44bcd46417c28f99a51095d8 100644 --- a/Utilities/ITK/Modules/Core/Mesh/include/itkWarpMeshFilter.hxx +++ b/Utilities/ITK/Modules/Core/Mesh/include/itkWarpMeshFilter.hxx @@ -78,7 +78,6 @@ WarpMeshFilter< TInputMesh, TOutputMesh, TDisplacementField > typedef typename TInputMesh::PointsContainer InputPointsContainer; typedef typename TOutputMesh::PointsContainer OutputPointsContainer; - typedef typename TInputMesh::PointsContainerPointer InputPointsContainerPointer; typedef typename TOutputMesh::PointsContainerPointer OutputPointsContainerPointer; const InputMeshType * inputMesh = this->GetInput(); diff --git a/Utilities/ITK/Modules/Core/Mesh/src/itkSimplexMeshGeometry.cxx b/Utilities/ITK/Modules/Core/Mesh/src/itkSimplexMeshGeometry.cxx index 63a06e8f2917ed358c6163f392cc3eaf5a0d0db7..e5709a1ef29f0ab686638e4ddf299785f9186cac 100644 --- a/Utilities/ITK/Modules/Core/Mesh/src/itkSimplexMeshGeometry.cxx +++ b/Utilities/ITK/Modules/Core/Mesh/src/itkSimplexMeshGeometry.cxx @@ -40,24 +40,28 @@ SimplexMeshGeometry normal.Fill(0); externalForce.Fill(0); internalForce.Fill(0); + closestAttractor.Fill(0); circleRadius = 0; circleCenter.Fill(0); sphereRadius = 0; distance = 0; phi = 0; + multiplier = 0.0; + forceIndex = 0; neighborIndices.Fill( NumericTraits< IdentifierType >::max() ); neighbors.Fill(p); meanCurvature = c; - neighborSet = NULL; + neighborSet = ITK_NULLPTR; + closestAttractorIndex = 0; } SimplexMeshGeometry ::~SimplexMeshGeometry() { delete this->neighborSet; - this->neighborSet = NULL; + this->neighborSet = ITK_NULLPTR; } void @@ -157,7 +161,7 @@ SimplexMeshGeometry } else { - this->neighborSet = NULL; + this->neighborSet = ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Core/Mesh/wrapping/itkImageToMeshFilter.wrap b/Utilities/ITK/Modules/Core/Mesh/wrapping/itkImageToMeshFilter.wrap index 1836f3f07ada085f41749295da63ccf186cf4c23..8fba37df4df0f79708dfa9f0f2ad3538805550cd 100644 --- a/Utilities/ITK/Modules/Core/Mesh/wrapping/itkImageToMeshFilter.wrap +++ b/Utilities/ITK/Modules/Core/Mesh/wrapping/itkImageToMeshFilter.wrap @@ -7,7 +7,10 @@ itk_wrap_class("itk::ImageToMeshFilter" POINTER) endforeach(t) endforeach(d) # For BinaryMask3DMeshSource - foreach(t ${WRAP_ITK_INT}) - itk_wrap_template("${ITKM_I${t}3}M${ITKM_D}3ST${ITKM_D}33${ITKM_D}${ITKM_D}" "${ITKT_I${t}3}, itk::Mesh< ${ITKT_D},3,itk::DefaultStaticMeshTraits< ${ITKT_D},3,3,${ITKT_D},${ITKT_D} > >") - endforeach(t) + itk_wrap_filter_dims(has_d_3 3) + if(has_d_3) + foreach(t ${WRAP_ITK_INT}) + itk_wrap_template("${ITKM_I${t}3}M${ITKM_D}3ST${ITKM_D}33${ITKM_D}${ITKM_D}" "${ITKT_I${t}3}, itk::Mesh< ${ITKT_D},3,itk::DefaultStaticMeshTraits< ${ITKT_D},3,3,${ITKT_D},${ITKT_D} > >") + endforeach(t) + endif(has_d_3) itk_end_wrap_class() diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkGeometricalQuadEdge.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkGeometricalQuadEdge.hxx index 6750fa44828cccd0315b166ce972fa25e0f6d090..6eb0596043a1423b1abd42bd6b923c0f69b76611 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkGeometricalQuadEdge.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkGeometricalQuadEdge.hxx @@ -30,7 +30,7 @@ template< typename TVRef, typename TFRef, const typename GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual >::OriginRefType GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual >::m_NoPoint = - vcl_numeric_limits< OriginRefType >::max(); + std::numeric_limits< OriginRefType >::max(); /** * Constructor @@ -38,10 +38,12 @@ GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual >::m_NoPoi template< typename TVRef, typename TFRef, typename TPrimalData, typename TDualData, bool PrimalDual > GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual > -::GeometricalQuadEdge() +::GeometricalQuadEdge() : + m_Origin(m_NoPoint), + m_Data(), + m_DataSet(false), + m_LineCellIdent(0) { - this->m_Origin = m_NoPoint; - this->m_DataSet = false; } /** @@ -304,7 +306,7 @@ GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual >::GetNext if ( this->IsOriginInternal() ) { itkQEDebugMacro("Internal point."); - return ( 0 ); + return ( ITK_NULLPTR ); } // Update reference @@ -331,7 +333,7 @@ GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual >::GetNext // No border edge found itkQEDebugMacro("Unfound border edge."); - return ( 0 ); + return ( ITK_NULLPTR ); } /** @@ -665,7 +667,7 @@ GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual > { const Self *p1 = this->GetSym(); - if ( p1 == NULL ) + if ( p1 == ITK_NULLPTR ) { return false; // FIXME: Is this the right answer ? } @@ -682,7 +684,7 @@ GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual > { const DualType *p1 = this->GetRot(); - if ( p1 == NULL ) + if ( p1 == ITK_NULLPTR ) { return false; // FIXME: Is this the right answer ? } @@ -699,7 +701,7 @@ GeometricalQuadEdge< TVRef, TFRef, TPrimalData, TDualData, PrimalDual > { const DualType *p1 = this->GetInvRot(); - if ( p1 == NULL ) + if ( p1 == ITK_NULLPTR ) { return false; // FIXME: Is this the right answer ? } diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdge.h b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdge.h index 546f71bc19b692e773a5ce68b98b57f5c186b790..1ff77604d36d57c5353abc65c10fae9d8e27389f 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdge.h +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdge.h @@ -403,7 +403,7 @@ public: inline const Self * GetInvDnext() const { return this->GetDprev(); } /** Queries. */ - inline bool IsHalfEdge() const { return ( ( m_Onext == this ) || ( m_Rot == NULL ) ); } + inline bool IsHalfEdge() const { return ( ( m_Onext == this ) || ( m_Rot == ITK_NULLPTR ) ); } inline bool IsIsolated() const { return ( this == this->GetOnext() ); } bool IsEdgeInOnextRing(Self *testEdge) const; diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMesh.h b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMesh.h index de1f594cd55f55f402279b934b542f07573f92a3..200a64ef4cb7e072424ff80d0fa9372482041d90 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMesh.h +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMesh.h @@ -304,7 +304,7 @@ public: int dimension) const { (void)dimension; - return ( (BoundaryAssignmentsContainerPointer)0 ); + return ( (BoundaryAssignmentsContainerPointer)ITK_NULLPTR ); } #endif diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMesh.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMesh.hxx index 41f48aeb4c786db53c919527d488e0c8fcb7b1fc..ba7f56cb28b108e9ed3cbeec96ed074e6fd2e983 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMesh.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMesh.hxx @@ -26,12 +26,12 @@ namespace itk template< typename TPixel, unsigned int VDimension, typename TTraits > const typename QuadEdgeMesh< TPixel, VDimension, TTraits >::PointIdentifier QuadEdgeMesh< TPixel, VDimension, TTraits >::m_NoPoint = - vcl_numeric_limits< PointIdentifier >::max(); + std::numeric_limits< PointIdentifier >::max(); template< typename TPixel, unsigned int VDimension, typename TTraits > const typename QuadEdgeMesh< TPixel, VDimension, TTraits >::CellIdentifier QuadEdgeMesh< TPixel, VDimension, TTraits >::m_NoFace = - vcl_numeric_limits< CellIdentifier >::max(); + std::numeric_limits< CellIdentifier >::max(); /** * Restore the mesh to its initial state. Useful for data pipeline updates @@ -82,19 +82,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > ::Graft(const DataObject *data) { this->Superclass::Graft(data); - const Self *mesh = 0; - - try - { - mesh = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - // mesh could not be cast back down - itkExceptionMacro( << "itk::QuadEdgeMesh::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *mesh = dynamic_cast< const Self * >( data ); if ( !mesh ) { @@ -331,7 +319,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > /////////////////////////////////////////////////////////////// // Back to dealing with the geometrical references. First // make sure the oldOrigin's edge entry won't be used any more: - oldOrigin.SetEdge( (QEPrimal *)0 ); + oldOrigin.SetEdge( (QEPrimal *)ITK_NULLPTR ); this->SetPoint(oldOriginId, oldOrigin); // We need to inform the edges ranging from a->Onext() to b that @@ -671,7 +659,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > if ( orgPid == destPid ) { itkDebugMacro("Creating an edge between the same point."); - return ( (QEPrimal *)0 ); + return ( (QEPrimal *)ITK_NULLPTR ); } // Make sure the points are already in the QuadEdgeMesh container: @@ -679,12 +667,12 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > || !( this->GetPoints()->IndexExists(destPid) ) ) { itkDebugMacro("One of the points not in the PointSet."); - return ( (QEPrimal *)0 ); + return ( (QEPrimal *)ITK_NULLPTR ); } // Make sure the edge is not already in the container QEPrimal *e = this->FindEdge(orgPid, destPid); - if ( e != (QEPrimal *)0 ) + if ( e != (QEPrimal *)ITK_NULLPTR ) { itkDebugMacro("Edge already in QuadEdgeMesh."); return e; @@ -698,7 +686,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > if ( eOrigin->IsOriginInternal() ) { itkDebugMacro("No room for a new edge in the Origin() ring."); - return ( (QEPrimal *)0 ); + return ( (QEPrimal *)ITK_NULLPTR ); } } @@ -709,7 +697,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > if ( eDestination->IsOriginInternal() ) { itkDebugMacro("No room for a new edge in the Destination() ring."); - return ( (QEPrimal *)0 ); + return ( (QEPrimal *)ITK_NULLPTR ); } } @@ -793,7 +781,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > // Check if the edge exists QEPrimal *e = this->FindEdge(orgPid, destPid); - if ( e == (QEPrimal *)0 ) + if ( e == (QEPrimal *)ITK_NULLPTR ) { itkDebugMacro("Edge missing in mesh."); return; @@ -825,7 +813,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > } else { - pOrigin.SetEdge( (QEPrimal *)0 ); + pOrigin.SetEdge( (QEPrimal *)ITK_NULLPTR ); } } @@ -840,7 +828,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > } else { - pDestination.SetEdge( (QEPrimal *)0 ); + pDestination.SetEdge( (QEPrimal *)ITK_NULLPTR ); } } @@ -860,7 +848,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > { PolygonCellType *pcell = dynamic_cast< PolygonCellType * >( cit.Value() ); bool toDelete = false; - if ( pcell != (PolygonCellType *)0 ) + if ( pcell != (PolygonCellType *)ITK_NULLPTR ) { QEPrimal *edge = pcell->GetEdgeRingEntry(); typename QEPrimal::IteratorGeom it = edge->BeginGeomLnext(); @@ -976,7 +964,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > } else { - pOrigin.SetEdge( (QEPrimal *)0 ); + pOrigin.SetEdge( (QEPrimal *)ITK_NULLPTR ); } } @@ -991,7 +979,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > } else { - pDestination.SetEdge( (QEPrimal *)0 ); + pDestination.SetEdge( (QEPrimal *)ITK_NULLPTR ); } } // ------------------------------------------------------------------ @@ -1125,7 +1113,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > { if ( this->GetEdgeCells()->size() == 0 ) { - return ( (QEPrimal *)0 ); + return ( (QEPrimal *)ITK_NULLPTR ); } const CellsContainer* edgeCells = this->GetEdgeCells(); @@ -1147,7 +1135,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > if( !this->GetEdgeCells()->GetElementIfIndexExists( eid, &c ) ) { itkDebugMacro("No such edge in container"); - return ( (QEPrimal *)0 ); + return ( (QEPrimal *)ITK_NULLPTR ); } EdgeCellType *e = dynamic_cast< EdgeCellType * >( c ); @@ -1188,7 +1176,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > ++it; } } - return ( static_cast< QEPrimal * >( NULL ) ); + return ( static_cast< QEPrimal * >( ITK_NULLPTR ) ); } /** @@ -1198,10 +1186,10 @@ typename QuadEdgeMesh< TPixel, VDimension, TTraits >::EdgeCellType * QuadEdgeMesh< TPixel, VDimension, TTraits > ::FindEdgeCell(const PointIdentifier & pid0, const PointIdentifier & pid1) const { - EdgeCellType *result = (EdgeCellType *)0; + EdgeCellType *result = (EdgeCellType *)ITK_NULLPTR; QEPrimal * EdgeGeom = FindEdge(pid0, pid1); - if ( EdgeGeom != (QEPrimal *)0 ) + if ( EdgeGeom != (QEPrimal *)ITK_NULLPTR ) { CellIdentifier LineIdent = EdgeGeom->GetIdent(); if ( LineIdent != m_NoPoint ) @@ -1273,7 +1261,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > { itkDebugMacro("Edge [" << i << " " << ( ( i + 1 ) % N ) << " has a left face."); - return (QEPrimal *)NULL; + return (QEPrimal *)ITK_NULLPTR; } } } @@ -1301,7 +1289,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > const PointIdentifier numberOfPoints = static_cast< PointIdentifier >( points.size() ); typedef std::vector< QEPrimal * > QEList; - QEList FaceQEList( numberOfPoints, NULL ); + QEList FaceQEList( numberOfPoints, ITK_NULLPTR ); // Now create edge list and create missing edges if needed. for ( PointIdentifier i = 0; i < numberOfPoints; i++ ) @@ -1313,7 +1301,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > if ( !edge && CheckEdges ) { QEPrimal *entry = this->AddEdgeWithSecurePointList(pid0, pid1); - if ( entry == (QEPrimal *)0 ) + if ( entry == (QEPrimal *)ITK_NULLPTR ) { return ( entry ); } @@ -1349,7 +1337,7 @@ QuadEdgeMesh< TPixel, VDimension, TTraits > { // FIXME throw exception here instead itkDebugMacro("entry == NULL"); - return (QEPrimal *)NULL; + return (QEPrimal *)ITK_NULLPTR; } this->AddFace(entry); diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshBoundaryEdgesMeshFunction.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshBoundaryEdgesMeshFunction.hxx index eb5317f512708dd61cd99799019a27a3e38a911d..fea43a3d437ac51835d6a648310628c7aad2544b 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshBoundaryEdgesMeshFunction.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshBoundaryEdgesMeshFunction.hxx @@ -67,7 +67,7 @@ const { itkWarningMacro("Entry edge has not face adjacency."); delete ResultList; - return ( (OutputType)0 ); + return ( (OutputType)ITK_NULLPTR ); } // Store this edge as representative of it's Lnext() ring i.e. diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.h b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.h index 72328baa7c895b85646ae64e25eab81b616b484d..02cc8eaf9869e38ae3cdb2730c079fc6b684d4aa 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.h +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.h @@ -63,7 +63,7 @@ public: } protected: - QuadEdgeMeshEulerOperatorDeleteCenterVertexFunction(){} + QuadEdgeMeshEulerOperatorDeleteCenterVertexFunction() : m_OldPointID(0) {} ~QuadEdgeMeshEulerOperatorDeleteCenterVertexFunction(){} private: diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.hxx index be8deb99014e9577b9dd1f688400578c5a5cec9c..b328502123b7fbb93111895e75589bd2d5320881 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.hxx @@ -29,19 +29,19 @@ QuadEdgeMeshEulerOperatorDeleteCenterVertexFunction< TMesh, TQEType >::Evaluate( if ( !g ) { itkDebugMacro("Input is not an edge."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( !this->m_Mesh ) { itkDebugMacro("No mesh present."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( !g->IsInternal() ) { itkDebugMacro("The edge is either border or wire."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } // None of the incident facets of g->GetDestination() is a hole. @@ -58,7 +58,7 @@ QuadEdgeMeshEulerOperatorDeleteCenterVertexFunction< TMesh, TQEType >::Evaluate( if ( !one_edge->IsInternal() ) { itkDebugMacro("DeleteVertex requires a full one-ring, i.e. no holes."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } pList.push_back( one_edge->GetDestination() ); } @@ -91,7 +91,7 @@ QuadEdgeMeshEulerOperatorDeleteCenterVertexFunction< TMesh, TQEType >::Evaluate( itkDebugMacro( "DeleteVertex requires at least two distinct \ facets incident to the facets that are incident to g->GetDestination()." ); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } // let's do the job now. diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.hxx index 3d2e8464371a2bb99bbe1197da0d8bde4ece7051..a9d2ad84a79cbbffb8a2197a2c1153bd787f35d2 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.hxx @@ -98,7 +98,7 @@ QuadEdgeMeshEulerOperatorFlipEdgeFunction< TMesh, TQEType >::CheckStatus(QEType } if ( this->m_Mesh->FindEdge( h->GetOnext()->GetDestination(), - h->GetSym()->GetOnext()->GetDestination() ) != 0 ) + h->GetSym()->GetOnext()->GetDestination() ) != ITK_NULLPTR ) { m_EdgeStatus = EXISTING_OPPOSITE_EDGE; return; @@ -134,22 +134,22 @@ QuadEdgeMeshEulerOperatorFlipEdgeFunction< TMesh, TQEType >::Evaluate(QEType *h) return Process(h); case EDGE_NULL: itkDebugMacro("No Edge to flip."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); case MESH_NULL: itkDebugMacro("No mesh present."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); case NON_INTERNAL_EDGE: itkDebugMacro("Can only flip internal edge."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); case NON_TRIANGULAR_LEFT_FACE: itkDebugMacro("Can only flip edge for triangles."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); case NON_TRIANGULAR_RIGHT_FACE: itkDebugMacro("Can only flip edge for triangles."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); case EXISTING_OPPOSITE_EDGE: itkDebugMacro("The opposite edge already exists."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } } diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorJoinFacetFunction.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorJoinFacetFunction.hxx index e0f470b195453fa7ef09f78b657ed7b2c38f5db7..efebd230522cbe0e85288b651521d13536d29a0d 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorJoinFacetFunction.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorJoinFacetFunction.hxx @@ -43,7 +43,7 @@ QuadEdgeMeshEulerOperatorJoinFacetFunction< TMesh, TQEType >::Evaluate(QEType *e if ( !e->IsInternal() ) { itkDebugMacro("The edge is either border or wire."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } // Initial state Final state // diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorJoinVertexFunction.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorJoinVertexFunction.hxx index 3ab3a81e39665ccf6864228ad57d3090351f0863..6401f00e101979dbd71b7d86046d21b5bb07a6c5 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorJoinVertexFunction.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorJoinVertexFunction.hxx @@ -120,9 +120,9 @@ QuadEdgeMeshEulerOperatorJoinVertexFunction< TMesh, TQEType >::Evaluate(QEType * case SAMOSA_CONFIG: // Eye case case EYE_CONFIG: - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); case EDGE_JOINING_DIFFERENT_BORDERS: - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } } @@ -197,7 +197,7 @@ QuadEdgeMeshEulerOperatorJoinVertexFunction< TMesh, TQEType >::Process(QEType *e if ( QEType::m_NoPoint != zip->Evaluate(leftZip) ) { itkDebugMacro("Zip must return NoPoint (left)."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } } else @@ -217,7 +217,7 @@ QuadEdgeMeshEulerOperatorJoinVertexFunction< TMesh, TQEType >::Process(QEType *e if ( QEType::m_NoPoint != zip->Evaluate(riteZip) ) { itkDebugMacro("Zip must return NoPoint (right)."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } } else @@ -283,7 +283,7 @@ QuadEdgeMeshEulerOperatorJoinVertexFunction< TMesh, TQEType >::ProcessIsolatedFa // it now retuns one edge from NewDest or NewOrg if there are any // else NULL QEType *temp = this->m_Mesh->FindEdge(dest); - if ( temp != 0 ) + if ( temp != ITK_NULLPTR ) { return temp; } diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h index 5e269b53649e37f657bf2d03c25c40e1940492d4..0a0f6e0f6e82858f3bc91670a3e8db352b593e54 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h @@ -61,13 +61,13 @@ public: if ( !e ) { itkDebugMacro("Input is not an edge."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( !this->m_Mesh ) { itkDebugMacro("No mesh present."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } m_SplitVertex->SetInput(this->m_Mesh); diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitFacetFunction.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitFacetFunction.hxx index 12c6ad4596c088dfa17cab35d708a196de5f2e5a..738b8e36a6d83c140c32e16d5f8fab5cef1d1505 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitFacetFunction.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitFacetFunction.hxx @@ -45,32 +45,32 @@ QuadEdgeMeshEulerOperatorSplitFacetFunction< TMesh, TQEType >::Evaluate(QEType * if ( !h || !g ) { itkDebugMacro("At least one of the Input is not an edge."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( !this->m_Mesh ) { itkDebugMacro("No mesh present."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( h == g ) { itkDebugMacro("Provided edges should be different."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( h->GetLeft() != g->GetLeft() ) { itkDebugMacro("The edges are not around the same face."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( ( h->GetLnext() == g ) || ( g->GetLnext() == h ) ) { itkDebugMacro("Provided edges should NOT be consecutive."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } typedef typename MeshType::VertexRefType VertexRefType; diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitVertexFunction.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitVertexFunction.hxx index 3055c0b410a4f9dc63b75feea0939e4085a97890..cdef635e7545981f6e86b2e112e9acd457d8397b 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitVertexFunction.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshEulerOperatorSplitVertexFunction.hxx @@ -29,25 +29,25 @@ QuadEdgeMeshEulerOperatorSplitVertexFunction< TMesh, TQEType >::Evaluate(QEType if ( !this->m_Mesh ) { itkDebugMacro("No mesh present."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } - if ( ( h == (QEType *)( 0 ) ) || ( g == (QEType *)( 0 ) ) ) + if ( ( h == (QEType *)ITK_NULLPTR ) || ( g == (QEType *)ITK_NULLPTR ) ) { itkDebugMacro("One or more argument(s) is(are) null."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( h == g ) { itkDebugMacro("The two half-edges are the same. No antenna allowed."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } if ( h->GetDestination() != g->GetDestination() ) { itkDebugMacro("The two half-edges must be incident to the same vertex."); - return ( (QEType *)0 ); + return ( (QEType *)ITK_NULLPTR ); } // delete the faces diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshFrontIterator.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshFrontIterator.hxx index f79bd89daa6e5a9d08a585a75bbb110bad5b8c15..0db88cdcdfef0acc837b2fff89f22aa5e6515e56 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshFrontIterator.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshFrontIterator.hxx @@ -24,10 +24,13 @@ namespace itk { // --------------------------------------------------------------------- template< typename TMesh, typename TQE > -QuadEdgeMeshFrontBaseIterator< TMesh, TQE >::QuadEdgeMeshFrontBaseIterator(MeshType *mesh, - bool start, - QEType *seed): - m_Mesh(mesh), m_Seed(seed), m_Start(start) +QuadEdgeMeshFrontBaseIterator< TMesh, TQE >:: +QuadEdgeMeshFrontBaseIterator(MeshType *mesh, bool start, QEType *seed) : + m_Mesh(mesh), + m_Seed(seed), + m_Start(start), + m_Front(ITK_NULLPTR), + m_CurrentEdge(ITK_NULLPTR) { if ( !mesh ) { @@ -122,7 +125,7 @@ QuadEdgeMeshFrontBaseIterator< TMesh, TQE >::operator++() // All the edge->Origin() neighbours were already visited. Remove // the edge from the front, and move to next edge... m_Front->pop_front(); - m_CurrentEdge = (QEType *)0; + m_CurrentEdge = (QEType *)ITK_NULLPTR; return ( this->operator++() ); } @@ -143,7 +146,7 @@ QuadEdgeMeshFrontBaseIterator< TMesh, TQE >::FindDefaultSeed() { return edge->GetRot(); } - return (QEType *)0; + return (QEType *)ITK_NULLPTR; } } #endif diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshFunctionBase.h b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshFunctionBase.h index 4d5a998ffcc3f1c09ffab9c9d318b255e4bfa077..bd6c6eb3a10c3ec4ad71bc1cd574f42d39554912 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshFunctionBase.h +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshFunctionBase.h @@ -86,7 +86,7 @@ public: protected: QuadEdgeMeshFunctionBase() { - m_Mesh = (MeshType *)0; + m_Mesh = (MeshType *)ITK_NULLPTR; } ~QuadEdgeMeshFunctionBase(){} diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshPoint.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshPoint.hxx index 704a7150276562a5d2f997012636d693d030e281..b9d6cf347ecaa12ec339a16dfc597461e4ed3452 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshPoint.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshPoint.hxx @@ -28,7 +28,7 @@ void QuadEdgeMeshPoint< TCoordRep, VPointDimension, TQuadEdge > ::Initialize() { - m_Edge = static_cast< TQuadEdge * >( NULL ); + m_Edge = static_cast< TQuadEdge * >( ITK_NULLPTR ); } // --------------------------------------------------------------------- diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshPolygonCell.h b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshPolygonCell.h index f94f0c6b8ba56ce3d01fc42fe3fd86b2d0649396..fe76f16e0527dc4486fc92042a26511af394ea82 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshPolygonCell.h +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshPolygonCell.h @@ -173,7 +173,7 @@ public: MakePointIds(); if ( m_PointIds.size() == 0 ) { - return ( static_cast< PointIdIterator >( 0 ) ); + return ( static_cast< PointIdIterator >( ITK_NULLPTR ) ); } else { @@ -186,7 +186,7 @@ public: // NOTE ALEX: should update the array on the fly to make it faster if ( m_PointIds.size() == 0 ) { - return ( static_cast< PointIdIterator >( 0 ) ); + return ( static_cast< PointIdIterator >( ITK_NULLPTR ) ); } else { @@ -200,7 +200,7 @@ public: MakePointIds(); if ( m_PointIds.size() == 0 ) { - return ( static_cast< PointIdIterator >( 0 ) ); + return ( static_cast< PointIdIterator >( ITK_NULLPTR ) ); } else { @@ -213,7 +213,7 @@ public: // NOTE ALEX: should update the array on the fly to make it faster if ( m_PointIds.size() == 0 ) { - return ( static_cast< PointIdIterator >( 0 ) ); + return ( static_cast< PointIdIterator >( ITK_NULLPTR ) ); } else { diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshToQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshToQuadEdgeMeshFilter.h index 56040cad2a7dd8fa0d2bb45e478b8029b8c7b754..71b479e42a4afa2aadddbcf9d1547ee55e055f5f 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshToQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshToQuadEdgeMeshFilter.h @@ -182,7 +182,7 @@ void CopyMeshToMeshPointData(const TInputMesh *in, TOutputMesh *out) const InputPointDataContainer *inputPointData = in->GetPointData(); - if ( inputPointData == NULL ) + if ( inputPointData == ITK_NULLPTR ) { // There is nothing to copy return; diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshTopologyChecker.h b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshTopologyChecker.h index 4649e771389a004cdd3d718830db334d0e4bd5b5..577dc9651e756062986bcd68f6ad7045212c0998 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshTopologyChecker.h +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshTopologyChecker.h @@ -76,7 +76,7 @@ public: protected: QuadEdgeMeshTopologyChecker(); ~QuadEdgeMeshTopologyChecker(){} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: QuadEdgeMeshTopologyChecker(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshTopologyChecker.hxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshTopologyChecker.hxx index 3ba9cdbc8aec4553ecf6d4063dc6f50a666c90b4..3e75a30312aacb07e95e2b1162a1829182753e9b 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshTopologyChecker.hxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/include/itkQuadEdgeMeshTopologyChecker.hxx @@ -31,7 +31,7 @@ QuadEdgeMeshTopologyChecker< TMesh > m_ExpectedNumberOfFaces = NumericTraits< CellIdentifier >::Zero; m_ExpectedNumberOfBoundaries = NumericTraits< CellIdentifier >::Zero; m_ExpectedGenus = NumericTraits< OffsetValueType >::Zero; - m_Mesh = NULL; + m_Mesh = ITK_NULLPTR; } template< typename TMesh > diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/src/itkQuadEdge.cxx b/Utilities/ITK/Modules/Core/QuadEdgeMesh/src/itkQuadEdge.cxx index 1cea8a87b29a8f1af814e4deb3edd70c460b1ddd..f7177ffe14cffc83e2dd74b5ea1c0654c9223be3 100644 --- a/Utilities/ITK/Modules/Core/QuadEdgeMesh/src/itkQuadEdge.cxx +++ b/Utilities/ITK/Modules/Core/QuadEdgeMesh/src/itkQuadEdge.cxx @@ -24,15 +24,15 @@ QuadEdge ::QuadEdge() { this->m_Onext = this; - this->m_Rot = NULL; + this->m_Rot = ITK_NULLPTR; } // --------------------------------------------------------------------- QuadEdge ::~QuadEdge() { - this->m_Onext = NULL; - this->m_Rot = NULL; + this->m_Onext = ITK_NULLPTR; + this->m_Rot = ITK_NULLPTR; } // --------------------------------------------------------------------- @@ -440,7 +440,7 @@ QuadEdge ConstIterator it = this->BeginOnext(); while ( it != this->EndOnext() ) { - if ( it.Value() == NULL ) + if ( it.Value() == ITK_NULLPTR ) { return false; } diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkAffineGeometryFrame.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkAffineGeometryFrame.h index d1fd626162e437390346aa6a994a8189aa3dc48f..1458ba6d513afaba910ffc1e14f775abcec78d0c 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkAffineGeometryFrame.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkAffineGeometryFrame.h @@ -92,13 +92,13 @@ public: virtual void Initialize(); /** Clone the geometry frame */ - virtual LightObject::Pointer InternalClone() const; + virtual LightObject::Pointer InternalClone() const ITK_OVERRIDE; protected: AffineGeometryFrame(); virtual ~AffineGeometryFrame(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** used in clone to initialize the newly created geometry */ virtual void InitializeGeometry(Self *newGeometry) const; diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkAffineGeometryFrame.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkAffineGeometryFrame.hxx index d24fe6d6122f79f6b8d39212a246d521f5304c79..41a1ecdcada3593479b1023a6a517f4521312ea0 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkAffineGeometryFrame.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkAffineGeometryFrame.hxx @@ -27,14 +27,14 @@ template< typename TScalar, unsigned int NDimensions > AffineGeometryFrame< TScalar, NDimensions > ::AffineGeometryFrame() { - m_BoundingBox = NULL; + m_BoundingBox = ITK_NULLPTR; m_IndexToObjectTransform = TransformType::New(); m_IndexToObjectTransform->SetIdentity(); m_ObjectToNodeTransform = TransformType::New(); m_ObjectToNodeTransform->SetIdentity(); m_IndexToNodeTransform = TransformType::New(); m_IndexToNodeTransform->SetIdentity(); - m_IndexToWorldTransform = 0; + m_IndexToWorldTransform = ITK_NULLPTR; } /** Destructor */ diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkArrowSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkArrowSpatialObject.hxx index f6511d3b4b21237b76d4d5aa23c5fbce6e1fddce..c4fd475ebe36bb862d26c8d1c9a7b5f83e85433f 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkArrowSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkArrowSpatialObject.hxx @@ -104,7 +104,7 @@ ArrowSpatialObject< TDimension > { itkDebugMacro("Checking the point [" << point << "] is on the Line"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { @@ -184,7 +184,7 @@ ArrowSpatialObject< TDimension > m_Length = m_Direction.GetSquaredNorm(); if ( m_Length != 0.0 ) { - m_Length = vcl_sqrt(m_Length); + m_Length = std::sqrt(m_Length); } else { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBlobSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBlobSpatialObject.h index 03303528b3536d180b4e10f76636d1bc1bad4c7c..2262a4a1b59f3f6918948793d94f260cedbb0bf8 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBlobSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBlobSpatialObject.h @@ -92,14 +92,14 @@ public: /** Returns true if the Blob is evaluable at the requested point, * false otherwise. */ bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns the value of the Blob at that point. * Currently this function returns a binary value, * but it might want to return a degree of membership * in case of fuzzy Blobs. */ bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns true if the point is inside the Blob, false otherwise. */ bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBlobSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBlobSpatialObject.hxx index 4d3907c52c2fc67f605d238018aabe1e10f8b829..2f968c076fc3082eca61aed4a04c16bf7350e713 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBlobSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBlobSpatialObject.hxx @@ -164,12 +164,12 @@ BlobSpatialObject< TDimension > typename PointType::VectorType difference = transformedPoint - it->GetPosition(); - if ( vcl_fabs(difference[0]) <= 0.5 - && vcl_fabs(difference[1]) <= 0.5 ) + if ( std::fabs(difference[0]) <= 0.5 + && std::fabs(difference[1]) <= 0.5 ) { if ( TDimension == 3 ) { - if ( vcl_fabs(difference[2]) <= 0.5 ) + if ( std::fabs(difference[2]) <= 0.5 ) { return true; } @@ -193,7 +193,7 @@ BlobSpatialObject< TDimension > ::IsInside(const PointType & point, unsigned int depth, char *name) const { itkDebugMacro("Checking the point [" << point << "] is inside the blob"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBoxSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBoxSpatialObject.h index 9faff6d3550d8c7d368823f435c7842cde221d00..46ba3d0836bf0edd5bc2f0e03314f1ce2cc26c47 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBoxSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBoxSpatialObject.h @@ -61,13 +61,13 @@ public: * That's useful for fuzzy objects. */ virtual bool ValueAt(const PointType & point, double & value, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Return true if the object provides a method to evaluate the value * at the specified point, false otherwise. */ virtual bool IsEvaluableAt(const PointType & point, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Test whether a point is inside or outside the object */ virtual bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBoxSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBoxSpatialObject.hxx index 0cbaad6d008ebfe5babc4bd9fe832cd3268e6380..f71e43b70aa24536e143eb872a3214567f857e4b 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBoxSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkBoxSpatialObject.hxx @@ -91,7 +91,7 @@ BoxSpatialObject< TDimension > itkDebugMacro("Checking the point [" << point << "] is inside the AxisAlignedBox"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { @@ -135,22 +135,27 @@ BoxSpatialObject< TDimension > bb->SetMinimum(pntMin); bb->SetMaximum(pntMax); - - const_cast< BoundingBoxType * >( this->GetBounds() )->SetMinimum(pntMin); - const_cast< BoundingBoxType * >( this->GetBounds() )->SetMinimum(pntMax); - bb->ComputeBoundingBox(); + // Next Transform the corners of the bounding box typedef typename BoundingBoxType::PointsContainer PointsContainer; const PointsContainer *corners = bb->GetCorners(); - typename BoundingBoxType::PointsContainer::const_iterator - it = corners->begin(); + typename PointsContainer::Pointer transformedCorners = PointsContainer::New(); + transformedCorners->Reserve(corners->size()); + + typename PointsContainer::const_iterator it = corners->begin(); + typename PointsContainer::iterator itTrans = transformedCorners->begin(); while ( it != corners->end() ) { PointType pnt = this->GetIndexToWorldTransform()->TransformPoint(*it); - const_cast< BoundingBoxType * >( this->GetBounds() )->ConsiderPoint(pnt); + *itTrans = pnt; ++it; + ++itTrans; } + + // refresh the bounding box with the transformed corners + const_cast< BoundingBoxType * >( this->GetBounds() )->SetPoints(transformedCorners); + this->GetBounds()->ComputeBoundingBox(); } return true; } diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkContourSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkContourSpatialObject.h index cf6d16a8e6d98e856b7b9cb1cead5527b6867d38..c4141b69b24ae6b091b7e6139d4f15966b264741 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkContourSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkContourSpatialObject.h @@ -135,14 +135,14 @@ public: * Note: For this class, this will always return false. -GH */ bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns the value of the Contour at that point. * Currently this function returns a binary value, * but it might want to return a degree of membership * in case of fuzzy Contours. */ bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns true if the point is inside the Contour, false otherwise. */ bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkCylinderSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkCylinderSpatialObject.h index 169bbd1e130460bb554e95daf7f86c2abe7a8e2c..5a1b3bacb4e8b20db0fc0c958e1316e89e7c310e 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkCylinderSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkCylinderSpatialObject.h @@ -64,18 +64,18 @@ public: * That's useful for fuzzy objects. */ virtual bool ValueAt(const PointType & point, double & value, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const ITK_OVERRIDE; /** Return true if the object provides a method to evaluate the value * at the specified point, false otherwise. */ virtual bool IsEvaluableAt(const PointType & point, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const ITK_OVERRIDE; /** Test whether a point is inside or outside the object */ virtual bool IsInside(const PointType & point, unsigned int depth, - char *) const; + char *) const ITK_OVERRIDE; /** Test whether a point is inside or outside the object * For computational speed purposes, it is faster if the method does not @@ -85,7 +85,7 @@ public: /** Get the boundaries of a specific object. This function needs to * be called every time one of the object's components is * changed. */ - virtual bool ComputeLocalBoundingBox() const; + virtual bool ComputeLocalBoundingBox() const ITK_OVERRIDE; protected: CylinderSpatialObject(const Self &); //purposely not implemented @@ -98,7 +98,7 @@ protected: double m_Height; /** Print the object informations in a stream. */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; }; } // end namespace itk diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkEllipseSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkEllipseSpatialObject.h index d92f07d9b1290177147e3c49ef6daf9ed3ea9378..648b6055a8385a5f9e768607dd8d350481764835 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkEllipseSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkEllipseSpatialObject.h @@ -73,13 +73,13 @@ public: * That's useful for fuzzy objects. */ virtual bool ValueAt(const PointType & point, double & value, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Return true if the object provides a method to evaluate the value * at the specified point, false otherwise. */ virtual bool IsEvaluableAt(const PointType & point, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Test whether a point is inside or outside the object */ virtual bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkEllipseSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkEllipseSpatialObject.hxx index 8a4fc62b821780741b65cfe488057c1edda0509f..b773d739c9915fc6c4222537b52fb8ec2b85aeb8 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkEllipseSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkEllipseSpatialObject.hxx @@ -102,7 +102,7 @@ EllipseSpatialObject< TDimension > { itkDebugMacro("Checking the point [" << point << "] is inside the Ellipse"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkGaussianSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkGaussianSpatialObject.h index cf6d9fc02abe49a99dbe4829893ded4d325b30cf..5a5313e450306b034153fc7a37570f1077edd71a 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkGaussianSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkGaussianSpatialObject.h @@ -85,13 +85,13 @@ public: /** Returns the value of the Gaussian at the given point. */ virtual bool ValueAt(const PointType & point, ScalarType & value, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Return true if the object provides a method to evaluate the value * at the specified point, false otherwise. */ virtual bool IsEvaluableAt(const PointType & point, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Test whether a point is inside or outside the object */ virtual bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkGaussianSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkGaussianSpatialObject.hxx index 68924ad59c78b5655e0e4b80b8d8ec3e1fa925f6..cb033bfb50101559e214152591cc902b396a68fc 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkGaussianSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkGaussianSpatialObject.hxx @@ -117,7 +117,7 @@ GaussianSpatialObject< TDimension > itkDebugMacro("Checking the point [" << point << "] is inside the GaussianSpatialObject"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { @@ -207,7 +207,7 @@ GaussianSpatialObject< TDimension > if ( IsInside(point, 0, name) ) { const double zsq = this->SquaredZScore(point); - value = m_Maximum * (ScalarType)vcl_exp(-zsq / 2.0); + value = m_Maximum * (ScalarType)std::exp(-zsq / 2.0); return true; } else if ( Superclass::IsEvaluableAt(point, depth, name) ) diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageMaskSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageMaskSpatialObject.h index c83fd4e0b31da988dc9e9a4317821e37cac9ef3d..c33e8745730786ee6f7654479fdf356f3398d569 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageMaskSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageMaskSpatialObject.h @@ -84,6 +84,11 @@ public: * volumes. */ RegionType GetAxisAlignedBoundingBoxRegion() const; + /** Get the boundaries of a specific object. This function needs to + * be called every time one of the object's components is + * changed. */ + virtual bool ComputeLocalBoundingBox() const; + protected: ImageMaskSpatialObject(const Self &); //purposely not implemented void operator=(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageMaskSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageMaskSpatialObject.hxx index 96fa5e59eea2528654f742eaca1c8a30dfcb34a7..f3f5c07b7897693d4ad31ad185b953f66f9bd9e1 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageMaskSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageMaskSpatialObject.hxx @@ -85,7 +85,7 @@ bool ImageMaskSpatialObject< TDimension > ::IsInside(const PointType & point, unsigned int depth, char *name) const { - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { @@ -248,6 +248,70 @@ ImageMaskSpatialObject< TDimension > return region; } +template< unsigned int TDimension > +bool +ImageMaskSpatialObject< TDimension > +::ComputeLocalBoundingBox() const +{ + itkDebugMacro("Computing ImageMaskSpatialObject bounding box"); + + if ( this->GetBoundingBoxChildrenName().empty() + || strstr( typeid( Self ).name(), + this->GetBoundingBoxChildrenName().c_str() ) ) + { + + // First get the region bounding box... + RegionType boundingRegion = GetAxisAlignedBoundingBoxRegion(); + const typename RegionType::IndexType index = boundingRegion.GetIndex(); + const typename RegionType::SizeType size = boundingRegion.GetSize(); + + //Now find the corners (by index) + typedef VectorContainer< unsigned int, typename RegionType::IndexType > + IndexContainerType; + + typename IndexContainerType::Pointer cornerInds = IndexContainerType::New(); + + unsigned int c = 0; + cornerInds->InsertElement(c++, index); + for ( unsigned int i = 0; i < ImageType::ImageDimension; ++i ) + { + unsigned int curSize = cornerInds->Size(); + for ( unsigned int ii = 0; ii < curSize; ++ii) + { + IndexType tmpIndex = cornerInds->ElementAt(ii); + tmpIndex[i] += size[i]; + cornerInds->InsertElement(c++,tmpIndex); + } + } + + // Next Transform the corners of the bounding box + typedef typename BoundingBoxType::PointsContainer PointsContainer; + typename PointsContainer::Pointer transformedCorners = PointsContainer::New(); + transformedCorners->Reserve(cornerInds->size()); + + typename IndexContainerType::const_iterator it = cornerInds->begin(); + typename PointsContainer::iterator itTrans = transformedCorners->begin(); + while ( it != cornerInds->end() ) + { + PointType origPnt; + for ( unsigned int i = 0; i < ImageType::ImageDimension; ++i ) + { + origPnt[i] = static_cast< typename PointType::CoordRepType>( (*it)[i]); + } + PointType pnt = this->GetIndexToWorldTransform()->TransformPoint(origPnt); + *itTrans = pnt; + ++it; + ++itTrans; + } + + // refresh the bounding box with the transformed corners + const_cast< BoundingBoxType * >( this->GetBounds() )->SetPoints(transformedCorners); + this->GetBounds()->ComputeBoundingBox(); + } + return true; +} + + /** Print the object */ template< unsigned int TDimension > void diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageSpatialObject.h index fd2a9e760387e0d85b72f1688a421d4dd8443bb6..22dcb87b9e84aed26521481eccdde31d82cc086c 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageSpatialObject.h @@ -79,13 +79,13 @@ public: /** Return true if the object is evaluable at the requested point, * and else otherwise. */ bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns the value of the image at the requested point. * If the point is not inside the object, then an exception is thrown. * \sa ExceptionObject */ bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns true if the point is inside, false otherwise. */ bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageSpatialObject.hxx index 884254ea2caae47b9c3e6271bb7a9101aca7bc91..8a27401ee99c3ac9b991b02077b790dd5ad170ff 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkImageSpatialObject.hxx @@ -38,7 +38,7 @@ ImageSpatialObject< TDimension, PixelType > } this->ComputeBoundingBox(); - this->InternalSetPixelType(static_cast<const PixelType *>(0)); + this->InternalSetPixelType(static_cast<const PixelType *>(ITK_NULLPTR)); m_Interpolator = NNInterpolatorType::New(); } @@ -123,7 +123,7 @@ bool ImageSpatialObject< TDimension, PixelType > ::IsInside(const PointType & point, unsigned int depth, char *name) const { - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLandmarkSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLandmarkSpatialObject.h index a13f1da7f4c0aba06bee83b40d89e578bfd6dd52..6d2a68c95e754035ebf3f4b81de6209b2df883f8 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLandmarkSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLandmarkSpatialObject.h @@ -84,14 +84,14 @@ public: /** Returns true if the Landmark is evaluable at the requested point, * false otherwise. */ bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns the value of the Landmark at that point. * Currently this function returns a binary value, * but it might want to return a degree of membership * in case of fuzzy Landmarks. */ bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns true if the point is inside the Landmark, false otherwise. */ bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLandmarkSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLandmarkSpatialObject.hxx index 8501cdb8cca958e0228ba84efdfef132c2de6ab4..2d309876571a553812c1b1a62d94f82a53ce21d5 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLandmarkSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLandmarkSpatialObject.hxx @@ -180,7 +180,7 @@ LandmarkSpatialObject< TDimension > { itkDebugMacro("Checking the point [" << point << "] is inside the blob"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLineSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLineSpatialObject.h index c51d0af8c4bcf771760ef3062ca3b48b190f278d..7412c0b5ccd15eeb2166d17bb700bc8e75547c78 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLineSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLineSpatialObject.h @@ -88,14 +88,14 @@ public: /** Returns true if the line is evaluable at the requested point, * false otherwise. */ bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns the value of the line at that point. * Currently this function returns a binary value, * but it might want to return a degree of membership * in case of fuzzy Lines. */ bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns true if the point is inside the line, false otherwise. */ bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLineSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLineSpatialObject.hxx index b4e51dda9e65ed8c40d982e332ba23ed73c43434..80f3f4f366dfc78c0bd99a35a425750551a3a4a2 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLineSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkLineSpatialObject.hxx @@ -160,7 +160,7 @@ LineSpatialObject< TDimension > { itkDebugMacro("Checking the point [" << point << "] is on the Line"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMeshSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMeshSpatialObject.h index 049d1d404a93324bf06825da682d39f42378670e..57cbfa3351500225f23366591990d650d4c85f96 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMeshSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMeshSpatialObject.h @@ -73,13 +73,13 @@ public: /** Return true if the object is evaluable at the requested point, * and else otherwise. */ bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns the value of the Mesh at the requested point. * If the point is not inside the object, then an exception is thrown. * \sa ExceptionObject */ bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns true if the point is inside, false otherwise. */ bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMeshSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMeshSpatialObject.hxx index 5b2e643dc0c6c10f8fdcc9a4c9dd780527b643ab..0de92aa756a106aca5060d254f3ae75e822214fb 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMeshSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMeshSpatialObject.hxx @@ -85,7 +85,7 @@ MeshSpatialObject< TMesh > { double minDist = 0.0; const bool pointIsInside = it.Value()->EvaluatePosition( - position, m_Mesh->GetPoints(), NULL, NULL, &minDist, NULL); + position, m_Mesh->GetPoints(), ITK_NULLPTR, ITK_NULLPTR, &minDist, ITK_NULLPTR); if ( pointIsInside && minDist <= this->m_IsInsidePrecision ) { @@ -95,7 +95,7 @@ MeshSpatialObject< TMesh > else { if ( it.Value()->EvaluatePosition(position, m_Mesh->GetPoints(), - NULL, NULL, NULL, NULL) ) + ITK_NULLPTR, ITK_NULLPTR, ITK_NULLPTR, ITK_NULLPTR) ) { return true; } @@ -112,7 +112,7 @@ bool MeshSpatialObject< TMesh > ::IsInside(const PointType & point, unsigned int depth, char *name) const { - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaArrowConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaArrowConverter.hxx index ee5bee44a7330c7a63dfd59f68ae2d4f188ef55f..f8900cef6ae8e16dafbc743a090e2b89e481b8f9 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaArrowConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaArrowConverter.hxx @@ -44,7 +44,7 @@ MetaArrowConverter< NDimensions > ::MetaObjectToSpatialObject( const MetaObjectType *mo ) { const ArrowMetaObjectType *metaArrow = dynamic_cast<const MetaArrow *>(mo); - if(metaArrow == 0) + if(metaArrow == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaArrow"); } diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaBlobConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaBlobConverter.hxx index da5abe5cd56f0372b3f20f52abdfc0db5ffff476..be86b0d4559580b86ac0ff549749f6838b4cd0a1 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaBlobConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaBlobConverter.hxx @@ -43,16 +43,13 @@ MetaBlobConverter< NDimensions > ::MetaObjectToSpatialObject(const MetaObjectType *mo) { const BlobMetaObjectType *Blob = dynamic_cast<const BlobMetaObjectType *>(mo); - if(Blob == 0) + if(Blob == ITK_NULLPTR) { itkExceptionMacro(<< "Can't downcast MetaObject to BlobMetaObject"); } typename BlobSpatialObjectType::Pointer blob = BlobSpatialObjectType::New(); - //typedef BlobSpatialObjectType::VectorType VectorType; - typedef vnl_vector< double > VectorType; - unsigned int ndims = Blob->NDims(); double spacing[NDimensions]; for ( unsigned int ii = 0; ii < ndims; ii++ ) @@ -70,7 +67,6 @@ MetaBlobConverter< NDimensions > blob->GetProperty()->SetAlpha(Blob->Color()[3]); typedef itk::SpatialObjectPoint< NDimensions > BlobPointType; - typedef BlobPointType * BlobPointPointer; MetaBlob::PointListType::const_iterator it2 = Blob->GetPoints().begin(); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaContourConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaContourConverter.hxx index 26cf919907214bbad6a3e494b10e1e3449be1411..5936d894fb19f24adcb3a304614ba8fe56fd0bd4 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaContourConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaContourConverter.hxx @@ -44,7 +44,7 @@ MetaContourConverter< NDimensions > ::MetaObjectToSpatialObject(const MetaObjectType *mo) { const ContourMetaObjectType *contourMO = dynamic_cast<const MetaContour *>(mo); - if(contourMO == 0) + if(contourMO == ITK_NULLPTR) { itkExceptionMacro(<< "Can't downcast MetaObject to MetaContour"); } diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaDTITubeConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaDTITubeConverter.hxx index 7d36dd4ec7e9facd512e70cb921ca8e56ade6a91..c89d3421950e468f5cd83db179560dbca8a5a4fb 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaDTITubeConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaDTITubeConverter.hxx @@ -43,7 +43,7 @@ MetaDTITubeConverter< NDimensions > ::MetaObjectToSpatialObject(const MetaObjectType *mo) { const MetaDTITube *tube = dynamic_cast<const MetaDTITube *>(mo); - if(tube == 0) + if(tube == ITK_NULLPTR) { itkExceptionMacro(<< "Can't downcast MetaObject to MetaDTITube"); } @@ -69,7 +69,6 @@ MetaDTITubeConverter< NDimensions > tubeSO->GetProperty()->SetAlpha(tube->Color()[3]); typedef itk::DTITubeSpatialObjectPoint< NDimensions > TubePointType; - typedef TubePointType * TubePointPointer; MetaDTITube::PointListType::const_iterator it2 = tube->GetPoints().begin(); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaEllipseConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaEllipseConverter.hxx index 0ab8c381586ae88af82a2cad391e4af1b8e9ae93..0a1a1931c420e8eb94bff20ba4b7e55b86399911 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaEllipseConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaEllipseConverter.hxx @@ -43,7 +43,7 @@ MetaEllipseConverter< NDimensions > ::MetaObjectToSpatialObject(const MetaObjectType *mo) { const EllipseMetaObjectType *ellipseMO = dynamic_cast<const EllipseMetaObjectType *>(mo); - if(ellipseMO == 0) + if(ellipseMO == ITK_NULLPTR) { itkExceptionMacro(<< "Can't downcast MetaObject to EllipseMetaObject"); } diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaGaussianConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaGaussianConverter.hxx index d98d998a1437bde5ee73ae923ebc8a54cbbaa3ea..6e93c12aeb5db3afafbf9b2b34e0471d1fe7f471 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaGaussianConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaGaussianConverter.hxx @@ -44,7 +44,7 @@ MetaGaussianConverter< NDimensions > { const GaussianMetaObjectType *gaussian = dynamic_cast<const GaussianMetaObjectType *>(mo); - if(gaussian == 0) + if(gaussian == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaGaussian" ); } diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaGroupConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaGroupConverter.hxx index 9a260834b87373770ec26f631145d5aa88328878..55fe0bd62c10d5f4612a6af59348c67086fc410d 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaGroupConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaGroupConverter.hxx @@ -43,7 +43,7 @@ MetaGroupConverter< NDimensions > ::MetaObjectToSpatialObject(const MetaObjectType *mo) { const GroupMetaObjectType *group = dynamic_cast<const GroupMetaObjectType *>(mo); - if(group == 0) + if(group == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaGroup" ); } diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaImageConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaImageConverter.hxx index 9157ec4cc2f1d6abec1cf9e426222041a1727792..1788ca3a856a465587b74b99dccfae37e093e951 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaImageConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaImageConverter.hxx @@ -53,7 +53,6 @@ MetaImageConverter< NDimensions, PixelType, TSpatialObjectType > { typename ImageType::Pointer rval = ImageType::New(); - typedef typename ImageType::Pointer ImagePointer; typedef typename ImageType::SizeType SizeType; typedef typename ImageType::SpacingType SpacingType; typedef typename ImageType::RegionType RegionType; @@ -96,7 +95,7 @@ MetaImageConverter< NDimensions, PixelType, TSpatialObjectType > const ImageMetaObjectType *imageMO = dynamic_cast<const ImageMetaObjectType *>(mo); - if(imageMO == 0) + if(imageMO == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaImage" ); } @@ -137,8 +136,6 @@ MetaImageConverter< NDimensions, PixelType, TSpatialObjectType > itkExceptionMacro(<< "Can't downcast SpatialObject to ImageSpatialObject"); } typedef typename ImageType::ConstPointer ImageConstPointer; - typedef typename ImageType::SizeType SizeType; - typedef typename ImageType::RegionType RegionType; ImageConstPointer SOImage = imageSO->GetImage(); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaLandmarkConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaLandmarkConverter.hxx index 07583f9218e835a222edef7444628c7198a941ff..3b4ea53a2f971ecf01a19a33a762376eb551eab9 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaLandmarkConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaLandmarkConverter.hxx @@ -44,7 +44,7 @@ MetaLandmarkConverter< NDimensions > { const LandmarkMetaObjectType *landmarkMO = dynamic_cast<const LandmarkMetaObjectType *>(mo); - if(landmarkMO == 0) + if(landmarkMO == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaLandmark"); } @@ -52,9 +52,6 @@ MetaLandmarkConverter< NDimensions > LandmarkSpatialObjectPointer landmarkSO = LandmarkSpatialObjectType::New(); - //typedef LandmarkSpatialObjectType::VectorType VectorType; - typedef vnl_vector< double > VectorType; - unsigned int ndims = landmarkMO->NDims(); double spacing[NDimensions]; for ( unsigned int ii = 0; ii < ndims; ii++ ) diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaLineConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaLineConverter.hxx index bece3da1ff64881a6d16d34a139f373da0476252..7611c0372e639d3d1de7507c938dd3430217abfd 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaLineConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaLineConverter.hxx @@ -44,7 +44,7 @@ MetaLineConverter< NDimensions > { const LineMetaObjectType *lineMO = dynamic_cast<const LineMetaObjectType *>(mo); - if(lineMO == 0) + if(lineMO == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaLine" ); } @@ -68,7 +68,6 @@ MetaLineConverter< NDimensions > lineSO->GetProperty()->SetAlpha(lineMO->Color()[3]); typedef itk::LineSpatialObjectPoint< NDimensions > LinePointType; - typedef LinePointType * LinePointPointer; typedef MetaLine::PointListType ListType; ListType::const_iterator it2 = lineMO->GetPoints().begin(); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaMeshConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaMeshConverter.hxx index 89d6932902a55572108329f7e34b4a07225ace1e..66c5a051c91532c4a18e58522aa815b6209b814e 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaMeshConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaMeshConverter.hxx @@ -49,7 +49,7 @@ MetaMeshConverter< NDimensions, PixelType, TMeshTraits > { const MeshMetaObjectType *_mesh = dynamic_cast<const MeshMetaObjectType *>(mo); - if(_mesh == 0) + if(_mesh == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaMesh"); } @@ -244,7 +244,7 @@ MetaMeshConverter< NDimensions, PixelType, TMeshTraits > { std::cout << "MetaMeshConverter : GetMesh() returned a NULL Pointer" << std::endl; - return NULL; + return ITK_NULLPTR; } // fill in the Mesh information diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSceneConverter.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSceneConverter.h index d00ef086c9ee12034732b27abd45c659ad00da51..34492efc216582c718018639a1ad943617d9cfe4 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSceneConverter.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSceneConverter.h @@ -67,7 +67,7 @@ public: /** write out a Scene SpatialObject */ bool WriteMeta(SceneType *scene, const char *fileName, unsigned int depth = MaximumDepth, - char *spatialObjectTypeName = NULL); + char *spatialObjectTypeName = ITK_NULLPTR); const MetaEvent * GetEvent() const { return m_Event; } void SetEvent(MetaEvent *event) { m_Event = event; } @@ -99,7 +99,7 @@ public: MetaScene * CreateMetaScene(SceneType *scene, unsigned int depth = MaximumDepth, - char *name = NULL); + char *name = ITK_NULLPTR); ScenePointer CreateSpatialObjectScene(MetaScene *scene); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSceneConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSceneConverter.hxx index 18fa8b511342c41f0930f654ee3ef73cd7669199..b495895f7ef3d8df5168599a3588f029cddd1a14 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSceneConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSceneConverter.hxx @@ -47,7 +47,7 @@ MetaSceneConverter< NDimensions, PixelType, TMeshTraits > { // default behaviour of scene converter is not to save transform // with each spatial object. - m_Event = NULL; + m_Event = ITK_NULLPTR; m_BinaryPoints = false; m_TransformPrecision = 6; m_WriteImagesInSeparateFile = false; @@ -336,7 +336,6 @@ MetaSceneConverter< NDimensions, PixelType, TMeshTraits > } else if ( spatialObjectTypeName == "MeshSpatialObject" ) { - typedef itk::Mesh< PixelType, NDimensions, TMeshTraits > MeshType; currentMeta = this->SpatialObjectToMetaObject< MetaMeshConverter< NDimensions, PixelType, TMeshTraits > > ( *it ); } else diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSurfaceConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSurfaceConverter.hxx index 9b3a70ce4e2b7b58d9593b940585853b1323b898..97b4974e7233898281aec73d5e31d19631d9da20 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSurfaceConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaSurfaceConverter.hxx @@ -43,7 +43,7 @@ MetaSurfaceConverter< NDimensions > ::MetaObjectToSpatialObject(const MetaObjectType *mo) { const SurfaceMetaObjectType *surfaceMO = dynamic_cast<const SurfaceMetaObjectType *>(mo); - if(surfaceMO == 0) + if(surfaceMO == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaSurface"); } @@ -66,7 +66,6 @@ MetaSurfaceConverter< NDimensions > surfaceSO->GetProperty()->SetAlpha(surfaceMO->Color()[3]); typedef typename SurfaceSpatialObjectType::SurfacePointType SurfacePointType; - typedef SurfacePointType * SurfacePointPointer; typedef SurfaceMetaObjectType::PointListType ListType; diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaTubeConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaTubeConverter.hxx index e444e96f54554e41ff98613f681f789c8315fa4e..eb002a312bb10189a4e0e0c08d6d689089741056 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaTubeConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaTubeConverter.hxx @@ -44,7 +44,7 @@ MetaTubeConverter< NDimensions > { const TubeMetaObjectType *tubeMO = dynamic_cast<const TubeMetaObjectType *>(mo); - if(tubeMO == 0) + if(tubeMO == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaTube" ); } @@ -69,7 +69,6 @@ MetaTubeConverter< NDimensions > tubeSO->GetProperty()->SetAlpha(tubeMO->Color()[3]); typedef itk::TubeSpatialObjectPoint< NDimensions > TubePointType; - typedef TubePointType * TubePointPointer; typedef MetaTube::PointListType ListType; ListType::const_iterator it2 = tubeMO->GetPoints().begin(); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaVesselTubeConverter.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaVesselTubeConverter.hxx index 6fea80609962fab8528809dcc089c707d95776a0..dbf2fe6a49863523459c8bd3908aabfd2eb93fa3 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaVesselTubeConverter.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkMetaVesselTubeConverter.hxx @@ -44,7 +44,7 @@ MetaVesselTubeConverter< NDimensions > { const VesselTubeMetaObjectType *vesselTubeMO = dynamic_cast<const VesselTubeMetaObjectType *>(mo); - if(vesselTubeMO == 0) + if(vesselTubeMO == ITK_NULLPTR) { itkExceptionMacro(<< "Can't convert MetaObject to MetaVesselTube" ); } @@ -72,7 +72,6 @@ MetaVesselTubeConverter< NDimensions > vesselTubeSO->GetProperty()->SetAlpha(vesselTubeMO->Color()[3]); typedef itk::VesselTubeSpatialObjectPoint< NDimensions > VesselTubePointType; - typedef VesselTubePointType * TubePointPointer; typedef VesselTubeMetaObjectType::PointListType ListType; ListType::const_iterator it2 = vesselTubeMO->GetPoints().begin(); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPlaneSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPlaneSpatialObject.h index 4a5d1ec49711f33bbec492849c8f66deb451e015..dde4ee157809a7f54a4ce235ea1679e179b6f70d 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPlaneSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPlaneSpatialObject.h @@ -61,12 +61,12 @@ public: /** Returns a degree of membership to the object. * That's useful for fuzzy objects. */ virtual bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** return ture if the object provides a method to evaluate the value * at the specified point, else otherwise. */ virtual bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Test whether a point is inside or outside the object */ virtual bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPlaneSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPlaneSpatialObject.hxx index 8386bd6f41e983ef89cad7c447bf939191c77dfe..bb5fbec3b56d5a7eada2457de56c4cd02661e42a 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPlaneSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPlaneSpatialObject.hxx @@ -81,7 +81,7 @@ PlaneSpatialObject< TDimension > { itkDebugMacro("Checking the point [" << point << "is inside the plane"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPointBasedSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPointBasedSpatialObject.h index 09e347a1a43d2f56c917800d30aa6123258b03a6..cef6c53ebda044b0806b6441241c91ca38503fbb 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPointBasedSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPointBasedSpatialObject.h @@ -62,7 +62,7 @@ public: { itkWarningMacro(<< "PointBasedSpatialObject::GetPoint() is not implemented" << " in the base class" << std::endl); - return 0; + return ITK_NULLPTR; } virtual SpatialObjectPointType * @@ -70,7 +70,7 @@ public: { itkWarningMacro(<< "PointBasedSpatialObject::GetPoint() is not implemented" << " in the base class" << std::endl); - return 0; + return ITK_NULLPTR; } /** Return the number of points in the list */ diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonGroupSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonGroupSpatialObject.h index 2c7a8b0b1fe6ec786e57a02f5a2940490b26a1f6..89b60a8a98ad9d862cff9fcfd30859c9f60db0c8 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonGroupSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonGroupSpatialObject.h @@ -97,7 +97,7 @@ public: /** Test whether a point is inside or outside the object. */ virtual bool IsInside(const PointType & point, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; protected: PolygonGroupSpatialObject(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonGroupSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonGroupSpatialObject.hxx index b2ab53eace3ed8e6119171d032b5b1142896543f..7457086c0028b0e9673924948dd2931cc659cb08 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonGroupSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonGroupSpatialObject.hxx @@ -70,7 +70,7 @@ bool PolygonGroupSpatialObject< TDimension >::IsClosed() { PolygonSpatialObject< TDimension > *curstrand = dynamic_cast< PolygonSpatialObject< TDimension > * >( ( *it ).GetPointer() ); - if ( curstrand != 0 ) + if ( curstrand != ITK_NULLPTR ) { if ( !curstrand->IsClosed() ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonSpatialObject.hxx index 507f1228493a59ebf332af6d83c3a217e65081b8..73b24e8f04fe8a7fd405650c0bffb29559a0197f 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkPolygonSpatialObject.hxx @@ -138,10 +138,10 @@ PolygonSpatialObject< TDimension > ::MeasureArea() const { //To find the area of a planar polygon not in the x-y plane, use: - //2 A(P) = vcl_abs(N . (sum_{i=0}^{n-1} (v_i x v_{i+1}))) + //2 A(P) = std::abs(N . (sum_{i=0}^{n-1} (v_i x v_{i+1}))) //where N is a unit vector normal to the plane. The `.' represents the //dot product operator, the `x' represents the cross product operator, - // and vcl_abs() is the absolute value function. + // and std::abs() is the absolute value function. double area = 0.0; int numpoints = this->NumberOfPoints(); int X, Y; @@ -411,7 +411,7 @@ bool PolygonSpatialObject< TDimension > ::IsInside(const PointType & point) const { - return this->IsInside(point, 0, NULL); + return this->IsInside(point, 0, ITK_NULLPTR); } template< unsigned int TDimension > diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSceneSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSceneSpatialObject.h index c83a14c81304e76105610f2650f5a9b3b8cf43c8..c9cbdfc5f0b475182595d018bef430eb98aa66df 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSceneSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSceneSpatialObject.h @@ -71,12 +71,12 @@ public: * \warning This function creates a new list therefore * the user is responsible for the deletion of the list. */ ObjectListType * GetObjects(unsigned int depth = MaximumDepth, - char *name = NULL); + char *name = ITK_NULLPTR); /** Returns the number of children currently assigned to * the SceneSpatialObject object. */ unsigned int GetNumberOfObjects(unsigned int depth = MaximumDepth, - char *name = NULL); + char *name = ITK_NULLPTR); /** Set the list of pointers to children to the list passed as * argument. */ @@ -84,7 +84,7 @@ public: /** Returns the latest modified time of all the objects contained * in this SceneSpatialObject object. */ - ModifiedTimeType GetMTime(void) const; + virtual ModifiedTimeType GetMTime(void) const ITK_OVERRIDE; /** Get/Set the ParentID */ void SetParentId(int parentid) { m_ParentId = parentid; } @@ -122,7 +122,7 @@ protected: virtual ~SceneSpatialObject(); /** Print the object informations in a stream. */ - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Parent ID : default = -1 */ int m_ParentId; diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSceneSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSceneSpatialObject.hxx index 46c3b8047afa4d0479a0fb482014c22130ce1f1d..f263f8c220f9a5136aa4670881fb667dd731f12d 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSceneSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSceneSpatialObject.hxx @@ -26,7 +26,7 @@ namespace itk /** Constructor */ template< unsigned int TSpaceDimension > SceneSpatialObject< TSpaceDimension > -::SceneSpatialObject() +::SceneSpatialObject() : m_ParentId(0) {} /** Destructor */ @@ -106,7 +106,7 @@ SceneSpatialObject< TSpaceDimension > while ( it != itEnd ) { - if ( name == NULL || strstr(typeid( **it ).name(), name) ) + if ( name == ITK_NULLPTR || strstr(typeid( **it ).name(), name) ) { newList->push_back(*it); } @@ -155,7 +155,7 @@ SceneSpatialObject< TSpaceDimension > unsigned int cnt = 0; while ( it != itEnd ) { - if ( name == NULL || strstr(typeid( **it ).name(), name) ) + if ( name == ITK_NULLPTR || strstr(typeid( **it ).name(), name) ) { cnt++; } @@ -247,7 +247,7 @@ SceneSpatialObject< TSpaceDimension > it++; } - return NULL; + return ITK_NULLPTR; } template< unsigned int TSpaceDimension > @@ -268,7 +268,7 @@ SceneSpatialObject< TSpaceDimension > SpatialObject< TSpaceDimension > *parentObject = static_cast< SpatialObject< TSpaceDimension > * > ( this->GetObjectById(parentId) ); - if ( parentObject == NULL ) + if ( parentObject == ITK_NULLPTR ) { ret = false; ++it; diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObject.h index 706ccb717a08f1e43c790b54b9b8b8ae0262e699..203a0662000f32423e53453aa01b0231a3688093 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObject.h @@ -167,7 +167,7 @@ public: /** Returns the value at a point */ virtual bool ValueAt(const PointType & point, double & value, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Returns true if the object can provide a "meaningful" value at * a point. Often defaults to returning same answer as IsInside, but @@ -177,12 +177,12 @@ public: */ virtual bool IsEvaluableAt(const PointType & point, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Returns true if a point is inside the object. */ virtual bool IsInside(const PointType & point, unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Returns true if a point is inside the object - provided * to make spatial objects compatible with spatial functions @@ -198,11 +198,11 @@ public: short unsigned int order, OutputVectorType & value, unsigned int depth = 0, - char *name = NULL); + char *name = ITK_NULLPTR); /** Returns the latest modified time of the spatial object, and * any of its components. */ - ModifiedTimeType GetMTime(void) const; + virtual ModifiedTimeType GetMTime(void) const ITK_OVERRIDE; /** Returns the latest modified time of the spatial object, but not * the modification time of the children */ @@ -249,7 +249,7 @@ public: * region of the data object passed in as a parameter. This method * implements the API from DataObject. The data object parameter must be * castable to an ImageBase. */ - virtual void SetRequestedRegion(const DataObject *data); + virtual void SetRequestedRegion(const DataObject *data) ITK_OVERRIDE; /** Get the region object that defines the size and starting index * for the region of the image requested (i.e., the region of the @@ -315,7 +315,7 @@ public: * ImageBase has more meta-data than its DataObject. Thus, it must * provide its own version of CopyInformation() in order to copy the * LargestPossibleRegion from the input parameter. */ - virtual void CopyInformation(const DataObject *data); + virtual void CopyInformation(const DataObject *data) ITK_OVERRIDE; /** Update the information for this DataObject so that it can be used * as an output of a ProcessObject. This method is used the pipeline @@ -324,12 +324,12 @@ public: * ProcessObject::UpdateOutputInformation() which determines modified * times, LargestPossibleRegions, and any extra meta data like spacing, * origin, etc. */ - virtual void UpdateOutputInformation(); + virtual void UpdateOutputInformation() ITK_OVERRIDE; /** Set the RequestedRegion to the LargestPossibleRegion. This * forces a filter to produce all of the output in one execution * (i.e. not streaming) on the next call to Update(). */ - virtual void SetRequestedRegionToLargestPossibleRegion(); + virtual void SetRequestedRegionToLargestPossibleRegion() ITK_OVERRIDE; /** Determine whether the RequestedRegion is outside of the * BufferedRegion. This method returns true if the RequestedRegion @@ -340,7 +340,7 @@ public: * inside the BufferedRegion from the previous execution (and the * current filter is up to date), then a given filter does not need * to re-execute */ - virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); + virtual bool RequestedRegionIsOutsideOfTheBufferedRegion() ITK_OVERRIDE; /** Verify that the RequestedRegion is within the * LargestPossibleRegion. If the RequestedRegion is not within the @@ -350,7 +350,7 @@ public: * used by PropagateRequestedRegion(). PropagateRequestedRegion() * throws a InvalidRequestedRegionError exception is the requested * region is not within the LargestPossibleRegion. */ - virtual bool VerifyRequestedRegion(); + virtual bool VerifyRequestedRegion() ITK_OVERRIDE; /** Returns a pointer to the property object applied to this class. */ PropertyType * GetProperty(void); @@ -369,7 +369,7 @@ public: itkGetConstReferenceMacro(ParentId, int); /** Specify that the object has been updated */ - virtual void Update(void); + virtual void Update(void) ITK_OVERRIDE; /** Set the tree container */ itkSetObjectMacro(TreeNode, TreeNodeType) @@ -447,11 +447,11 @@ public: * \warning User is responsible for freeing the list, but not the elements of * the list. */ virtual ChildrenListType * GetChildren(unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Returns the number of children currently assigned to the object. */ unsigned int GetNumberOfChildren(unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; /** Set the list of pointers to children to the list passed as argument. */ void SetChildren(ChildrenListType & children); @@ -491,8 +491,8 @@ public: return false; } - /** Get the bounding box of the object. - * This function calls ComputeBoundingBox() */ + /** Get a pointer to the bounding box of the object. + * The extents and the position of the box are not computed. */ virtual BoundingBoxType * GetBoundingBox() const; /** Set/Get the depth at which the bounding box is computed */ @@ -537,7 +537,7 @@ protected: /** Destructor. */ virtual ~SpatialObject(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Calculate the offsets needed to move from one pixel to the next * along a row, column, slice, volume, etc. These offsets are based diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObject.hxx index 544f2df700ebd0adc1709836f01f372297d48323..db097fce1e1badcaf416a54a3e6f1b733627d2d8 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObject.hxx @@ -35,7 +35,7 @@ SpatialObject< TDimension > m_Bounds = BoundingBoxType::New(); m_BoundsMTime = 0; m_Property = PropertyType::New(); - m_TreeNode = NULL; + m_TreeNode = ITK_NULLPTR; m_ObjectToWorldTransform = TransformType::New(); m_ObjectToWorldTransform->SetIdentity(); @@ -593,7 +593,7 @@ SpatialObject< TDimension > { if ( !m_TreeNode ) { - return 0; + return ITK_NULLPTR; } typename TreeNodeType::ChildrenListType * children = @@ -668,7 +668,7 @@ SpatialObject< TDimension > { return m_TreeNode->GetParent()->Get(); } - return NULL; + return ITK_NULLPTR; } /** Get the parent of the spatial object */ @@ -681,7 +681,7 @@ SpatialObject< TDimension > { return m_TreeNode->GetParent()->Get(); } - return NULL; + return ITK_NULLPTR; } /** Set the parent of the spatial object */ @@ -845,17 +845,15 @@ SpatialObject< TDimension > { const SpatialObject *imgData = dynamic_cast< const SpatialObject * >( data ); - if ( imgData ) - { - m_RequestedRegion = imgData->GetRequestedRegion(); - } - else + if ( imgData == ITK_NULLPTR) { // pointer could not be cast back down itkExceptionMacro( << "itk::ImageBase::SetRequestedRegion(const DataObject *) cannot cast " << typeid( data ).name() << " to " << typeid( SpatialObject * ).name() ); } + + m_RequestedRegion = imgData->GetRequestedRegion(); } template< unsigned int TDimension > @@ -979,12 +977,7 @@ void SpatialObject< TDimension > imgData = dynamic_cast< const SpatialObject * >( data ); - if ( imgData ) - { - // Copy the meta data for this data type - m_LargestPossibleRegion = imgData->GetLargestPossibleRegion(); - } - else + if ( imgData == ITK_NULLPTR ) { // pointer could not be cast back down itkExceptionMacro( << "itk::SpatialObject::CopyInformation() cannot cast " @@ -992,6 +985,9 @@ void SpatialObject< TDimension > << typeid( SpatialObject * ).name() ); } + // Copy the meta data for this data type + m_LargestPossibleRegion = imgData->GetLargestPossibleRegion(); + // check if we are the same type const Self *source = dynamic_cast< const Self * >( data ); if ( !source ) diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectDuplicator.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectDuplicator.h index 760f82bc06f79d4bcb0b402db7d54e871145f341..c4ae31ccf5a4ab75100350ce98bec60f963ec21e 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectDuplicator.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectDuplicator.h @@ -67,7 +67,7 @@ public: protected: SpatialObjectDuplicator(); virtual ~SpatialObjectDuplicator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void CopyObject(const InternalSpatialObjectType *source, InternalSpatialObjectType *destination); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectDuplicator.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectDuplicator.hxx index dd7c6412b99a9530b67d8128eebcc479740a2b8b..fb8f4cb0f91f991b3d62df08e8873bee504d4486 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectDuplicator.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectDuplicator.hxx @@ -28,8 +28,8 @@ template< typename TInputSpatialObject > SpatialObjectDuplicator< TInputSpatialObject > ::SpatialObjectDuplicator() { - m_Input = NULL; - m_Output = NULL; + m_Input = ITK_NULLPTR; + m_Output = ITK_NULLPTR; m_InternalSpatialObjectTime = 0; SpatialObjectFactoryBase::RegisterDefaultSpatialObjects(); } @@ -50,7 +50,7 @@ SpatialObjectDuplicator< TInputSpatialObject > typedef itk::SpatialObject< TInputSpatialObject::ObjectDimension > SOType; SOType *newSO = dynamic_cast< SOType * >( i.GetPointer() ); - if ( newSO == NULL ) + if ( newSO == ITK_NULLPTR ) { std::cout << "Could not create an instance of " << value << std::endl << "The usual cause of this error is not registering the " diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectFactoryBase.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectFactoryBase.h index fa0c854a77ccaec7f45e5495455e6b213a491369..82097740f0317ff9483f33f8d18df5cc53081fd8 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectFactoryBase.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectFactoryBase.h @@ -47,9 +47,9 @@ public: typedef SmartPointer< const Self > ConstPointer; /** Class methods used to interface with the registered factories. */ - virtual const char * GetITKSourceVersion(void) const; + virtual const char * GetITKSourceVersion(void) const ITK_OVERRIDE; - virtual const char * GetDescription(void) const; + virtual const char * GetDescription(void) const ITK_OVERRIDE; /** Run-time type information (and related methods). */ itkTypeMacro(SpatialObjectFactoryBase, ObjectFactoryBase); @@ -63,7 +63,7 @@ public: /** Register this SpatialObject */ static SpatialObjectFactoryBase * GetFactory() { - if ( m_Factory == 0 ) + if ( m_Factory == ITK_NULLPTR ) { // Make and register the factory SpatialObjectFactoryBase::Pointer p = SpatialObjectFactoryBase::New(); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectProperty.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectProperty.h index 123f0e5bb01573ec69ff80399394080a6393054d..ebba2b6142468a349caf4f78989812b1dbd6e16b 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectProperty.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectProperty.h @@ -81,7 +81,7 @@ public: protected: - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void Modified(void){ m_MTime++; } diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectToImageStatisticsCalculator.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectToImageStatisticsCalculator.h index 1d044ee5fae12598713661657d21d0e2d250363c..2d44127bd0aa9fe29c708f7c390b76e80098478a 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectToImageStatisticsCalculator.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectToImageStatisticsCalculator.h @@ -111,7 +111,7 @@ public: protected: SpatialObjectToImageStatisticsCalculator(); virtual ~SpatialObjectToImageStatisticsCalculator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; bool ComputeStatistics(); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectToImageStatisticsCalculator.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectToImageStatisticsCalculator.hxx index ed899c53dd83119e70618f05ef1a1b8e5099c0f4..1ea5305a7d434af1831f1e3373b24bd4fc3ccd31 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectToImageStatisticsCalculator.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectToImageStatisticsCalculator.hxx @@ -32,8 +32,8 @@ template< typename TInputImage, typename TInputSpatialObject, unsigned int TSamp SpatialObjectToImageStatisticsCalculator< TInputImage, TInputSpatialObject, TSampleDimension > ::SpatialObjectToImageStatisticsCalculator() { - m_Image = NULL; - m_SpatialObject = NULL; + m_Image = ITK_NULLPTR; + m_SpatialObject = ITK_NULLPTR; m_Mean.Fill(0); m_CovarianceMatrix.SetIdentity(); m_SampleDirection = TSampleDimension - 1; diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeContainer.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeContainer.h index 43aac3e46f934bbd22108febd6078e97dfebe4ca..df2115a1529bdf6c63b128533d1a13c567203d54 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeContainer.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeContainer.h @@ -38,7 +38,7 @@ class SpatialObject; * * Template parameters for class Array: * - * - TValueType = Element type stored at each location in the array. + * - TValue = Element type stored at each location in the array. * * \ingroup DataRepresentation * \ingroup ITKSpatialObjects diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeNode.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeNode.h index 4baf6ab3a21834b56be162713f65f62d2486d5ae..83dcffc17a04e29e5c6a806b2293891a775166ee 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeNode.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeNode.h @@ -69,7 +69,7 @@ public: /** Return a list of children (the list should be deleted by the user */ #if !defined( CABLE_CONFIGURATION ) virtual ChildrenListType * GetChildren(unsigned int depth = 0, - char *name = NULL) const; + char *name = ITK_NULLPTR) const; #endif diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeNode.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeNode.hxx index f17c0c556e4a54b2563efab2b7ac8b119343e5c4..0620529e7f5b07c0e78306052532fd2f501661d3 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeNode.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSpatialObjectTreeNode.hxx @@ -32,7 +32,7 @@ SpatialObjectTreeNode< TDimension > m_NodeToParentNodeTransform->SetIdentity(); m_NodeToWorldTransform = TransformType::New(); m_NodeToWorldTransform->SetIdentity(); - this->m_Parent = NULL; + this->m_Parent = ITK_NULLPTR; } template< unsigned int TDimension > @@ -88,7 +88,7 @@ SpatialObjectTreeNode< TDimension > while ( childrenListIt != childrenListEnd ) { - if ( name == NULL || strstr(typeid( *( ( *childrenListIt )->Get() ) ).name(), + if ( name == ITK_NULLPTR || strstr(typeid( *( ( *childrenListIt )->Get() ) ).name(), name) ) { children->push_back(*childrenListIt); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSurfaceSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSurfaceSpatialObject.h index fd59873fcba91545a0f351068e4dfc5359545174..e87bbc686aaa61e2c4672b5d36d9cc7fe63aa9ea 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSurfaceSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSurfaceSpatialObject.h @@ -84,14 +84,14 @@ public: /** Returns true if the Surface is evaluable at the requested point, * false otherwise. */ bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns the value of the Surface at that point. * Currently this function returns a binary value, * but it might want to return a degree of membership * in case of fuzzy Surfaces. */ bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns true if the point is inside the Surface, false otherwise. */ bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSurfaceSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSurfaceSpatialObject.hxx index c075a086d63cc7cc50fff42fa0c83b27fd29b457..2851fdbdd770a24dbd84de4d0c4f08cc4b2eac88 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSurfaceSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkSurfaceSpatialObject.hxx @@ -176,7 +176,7 @@ SurfaceSpatialObject< TDimension > { itkDebugMacro("Checking the point [" << point << "is on the surface"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { @@ -369,7 +369,7 @@ SurfaceSpatialObject< TDimension > + v2[0] * ( v3[1] - v1[1] ) + v3[0] * ( v1[1] - v2[1] ) ); - absvec = -vcl_sqrt ( (double)( ( coa * coa ) + ( cob * cob ) + ( coc * coc ) ) ); + absvec = -std::sqrt ( (double)( ( coa * coa ) + ( cob * cob ) + ( coc * coc ) ) ); if ( absvec == 0 ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkTubeSpatialObject.h b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkTubeSpatialObject.h index 1a9c423ee25199ae33733c8d809298d8ddc7dc31..387b05f1e1043a0f79b4c8cf0a04c047229e535a 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkTubeSpatialObject.h +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkTubeSpatialObject.h @@ -113,14 +113,14 @@ public: /** Returns true if the tube is evaluable at the requested point, * false otherwise. */ bool IsEvaluableAt(const PointType & point, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns the value of the tube at that point. * Currently this function returns a binary value, * but it might want to return a degree of membership * in case of fuzzy tubes. */ bool ValueAt(const PointType & point, double & value, - unsigned int depth = 0, char *name = NULL) const; + unsigned int depth = 0, char *name = ITK_NULLPTR) const; /** Returns true if the point is inside the tube, false otherwise. */ bool IsInside(const PointType & point, diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkTubeSpatialObject.hxx b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkTubeSpatialObject.hxx index b234523d44a210e20efe7a7159d17544012eeb7a..149c8077ef8185584ea24ae8a44293af1bc19d90 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/include/itkTubeSpatialObject.hxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/include/itkTubeSpatialObject.hxx @@ -240,7 +240,7 @@ TubeSpatialObject< TDimension, TTubePointType > double lambda = A / B; if ( ( ( it != m_Points.begin() ) - && ( lambda > -( ( *it ).GetRadius() / ( 2 * vcl_sqrt(B) ) ) ) + && ( lambda > -( ( *it ).GetRadius() / ( 2 * std::sqrt(B) ) ) ) && ( lambda < 0 ) ) || ( ( lambda <= 1.0 ) && ( lambda >= 0.0 ) ) ) @@ -297,7 +297,7 @@ TubeSpatialObject< TDimension, TTubePointType > it++; } - double dist = vcl_sqrt(minSquareDist); + double dist = std::sqrt(minSquareDist); if ( dist <= ( ( *min ).GetRadius() ) ) { return true; @@ -314,7 +314,7 @@ TubeSpatialObject< TDimension, TTubePointType > { itkDebugMacro("Checking the point [" << point << "] is inside the tube"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { @@ -408,7 +408,7 @@ TubeSpatialObject< TDimension, TTubePointType > l = l + t[i] * t[i]; } - l = vcl_sqrt(l); + l = std::sqrt(l); if ( l == 0 ) { std::cerr << "TubeSpatialObject::ComputeTangentAndNormals() : "; @@ -545,7 +545,7 @@ TubeSpatialObject< TDimension, TTubePointType > // check if we are the same type const Self *source = dynamic_cast< const Self * >( data ); - if ( !source ) + if ( source == ITK_NULLPTR ) { std::cout << "CopyInformation: objects are not of the same type" << std::endl; diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/src/itkArrowSpatialObject.cxx b/Utilities/ITK/Modules/Core/SpatialObjects/src/itkArrowSpatialObject.cxx index 7cccfc55ea30ad6fd4ee097da187c7fdb1894ed9..191012bd841077236fed08d177fd0503ba81f2bd 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/src/itkArrowSpatialObject.cxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/src/itkArrowSpatialObject.cxx @@ -43,7 +43,7 @@ ArrowSpatialObject< 3 > if ( m_Length != 0.0 ) { - m_Length = vcl_sqrt(m_Length); + m_Length = std::sqrt(m_Length); } else { @@ -70,11 +70,11 @@ ArrowSpatialObject< 3 > { if ( m_Direction[0] < 0.0 ) { - anglez = vnl_math::pi + vcl_atan(m_Direction[1] / m_Direction[0]); + anglez = vnl_math::pi + std::atan(m_Direction[1] / m_Direction[0]); } else { - anglez = vcl_atan(m_Direction[1] / m_Direction[0]); + anglez = std::atan(m_Direction[1] / m_Direction[0]); } } const double angley = -asin(m_Direction[2]); diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/src/itkCylinderSpatialObject.cxx b/Utilities/ITK/Modules/Core/SpatialObjects/src/itkCylinderSpatialObject.cxx index 21ae20f6a97a91fb5858ca0bd3761bbe437ac39c..97ae629052ffae85a984ccceadf87e9a65c3479b 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/src/itkCylinderSpatialObject.cxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/src/itkCylinderSpatialObject.cxx @@ -72,7 +72,7 @@ bool CylinderSpatialObject double lambda = A / B; if ( ( - ( lambda > -( m_Radius / ( 2 * vcl_sqrt(B) ) ) ) + ( lambda > -( m_Radius / ( 2 * std::sqrt(B) ) ) ) && ( lambda < 0 ) ) || ( ( lambda <= 1.0 ) && ( lambda >= 0.0 ) ) ) @@ -103,7 +103,7 @@ bool CylinderSpatialObject { itkDebugMacro("Checking the point [" << point << "] is inside the Cylinder"); - if ( name == NULL ) + if ( name == ITK_NULLPTR ) { if ( IsInside(point) ) { diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/src/itkSpatialObjectFactoryBase.cxx b/Utilities/ITK/Modules/Core/SpatialObjects/src/itkSpatialObjectFactoryBase.cxx index 94abf8e9f15136100a9c2acc6f0da0b5f034eda7..cf56156b8c6e308f1f50797133a19e1f0e0baec8 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/src/itkSpatialObjectFactoryBase.cxx +++ b/Utilities/ITK/Modules/Core/SpatialObjects/src/itkSpatialObjectFactoryBase.cxx @@ -24,7 +24,7 @@ namespace itk { -SpatialObjectFactoryBase *SpatialObjectFactoryBase:: m_Factory = 0; +SpatialObjectFactoryBase *SpatialObjectFactoryBase:: m_Factory = ITK_NULLPTR; SpatialObjectFactoryBase::SpatialObjectFactoryBase() {} diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/wrapping/itkDTITubeSpatialObject.wrap b/Utilities/ITK/Modules/Core/SpatialObjects/wrapping/itkDTITubeSpatialObject.wrap index 9fa7071991c9489b1004ac5440927beae2167616..6efaab6550a408a4e16bd16263a24b8fcc4d6d53 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/wrapping/itkDTITubeSpatialObject.wrap +++ b/Utilities/ITK/Modules/Core/SpatialObjects/wrapping/itkDTITubeSpatialObject.wrap @@ -1,12 +1,7 @@ -itk_wrap_class("itk::DTITubeSpatialObject" POINTER_WITH_SUPERCLASS) -# foreach(d ${ITK_WRAP_DIMS}) -# itk_wrap_template(${d} ${d}) -# endforeach(d) +itk_wrap_filter_dims(has_d_3 3) - # seems to be usable only with dim=3 - itk_wrap_filter_dims(d 3) - if(d) +if(has_d_3) + itk_wrap_class("itk::DTITubeSpatialObject" POINTER_WITH_SUPERCLASS) itk_wrap_template(3 3) - endif(d) - -itk_end_wrap_class() + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Core/SpatialObjects/wrapping/itkDTITubeSpatialObjectPoint.wrap b/Utilities/ITK/Modules/Core/SpatialObjects/wrapping/itkDTITubeSpatialObjectPoint.wrap index 7dd4e404f0e642b2b00416f0f9d502762950277a..b8377e9f686807185c2d50f21349c808d5038ef6 100644 --- a/Utilities/ITK/Modules/Core/SpatialObjects/wrapping/itkDTITubeSpatialObjectPoint.wrap +++ b/Utilities/ITK/Modules/Core/SpatialObjects/wrapping/itkDTITubeSpatialObjectPoint.wrap @@ -1,12 +1,7 @@ -itk_wrap_class("itk::DTITubeSpatialObjectPoint") -# foreach(d ${ITK_WRAP_DIMS}) -# itk_wrap_template("${d}" "${d}") -# endforeach(d) +itk_wrap_filter_dims(has_d_3 3) - # seems to be usable only with dim=3 - itk_wrap_filter_dims(d 3) - if(d) +if(has_d_3) + itk_wrap_class("itk::DTITubeSpatialObjectPoint") itk_wrap_template(3 3) - endif(d) - -itk_end_wrap_class() + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkAffineTransform.h b/Utilities/ITK/Modules/Core/Transform/include/itkAffineTransform.h index cfce1abe576c8701a370a78453bb0e46d32f8ea9..e4708dca7a6cbf4e85075470f5c22b33d42b37da 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkAffineTransform.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkAffineTransform.h @@ -179,8 +179,8 @@ public: * rotation angle is in radians. The axis of rotation goes * through the origin. The transformation is given by * - * y[axis1] = vcl_cos(angle)*x[axis1] + vcl_sin(angle)*x[axis2] - * y[axis2] = -sin(angle)*x[axis1] + vcl_cos(angle)*x[axis2]. + * y[axis1] = std::cos(angle)*x[axis1] + std::sin(angle)*x[axis2] + * y[axis2] = -sin(angle)*x[axis1] + std::cos(angle)*x[axis2]. * * All coordinates other than axis1 and axis2 are unchanged; * a rotation of pi/2 radians will carry +axis1 into +axis2. diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkAffineTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkAffineTransform.hxx index a2addf141abca8449bd77398bad1b30aba1f0d55..80ddcc40ddf04aaf085c1081143d76e71f5141d9 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkAffineTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkAffineTransform.hxx @@ -152,10 +152,10 @@ AffineTransform< TScalar, NDimensions > } trans[i][i] = 1.0; } - trans[axis1][axis1] = vcl_cos(angle); - trans[axis1][axis2] = vcl_sin(angle); - trans[axis2][axis1] = -vcl_sin(angle); - trans[axis2][axis2] = vcl_cos(angle); + trans[axis1][axis1] = std::cos(angle); + trans[axis1][axis2] = std::sin(angle); + trans[axis2][axis1] = -std::sin(angle); + trans[axis2][axis2] = std::cos(angle); if ( pre ) { this->SetVarMatrix(this->GetMatrix() * trans); @@ -180,10 +180,10 @@ AffineTransform< TScalar, NDimensions > { MatrixType trans; - trans[0][0] = vcl_cos(angle); - trans[0][1] = -vcl_sin(angle); - trans[1][0] = vcl_sin(angle); - trans[1][1] = vcl_cos(angle); + trans[0][0] = std::cos(angle); + trans[0][1] = -std::sin(angle); + trans[1][0] = std::sin(angle); + trans[1][1] = std::cos(angle); if ( pre ) { this->SetVarMatrix(this->GetMatrix() * trans); @@ -211,16 +211,16 @@ AffineTransform< TScalar, NDimensions > ScalarType q0, q1, q2, q3; // Convert the axis to a unit vector - r = vcl_sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]); + r = std::sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]); x1 = axis[0] / r; x2 = axis[1] / r; x3 = axis[2] / r; // Compute quaternion elements - q0 = vcl_cos(angle / 2.0); - q1 = x1 * vcl_sin(angle / 2.0); - q2 = x2 * vcl_sin(angle / 2.0); - q3 = x3 * vcl_sin(angle / 2.0); + q0 = std::cos(angle / 2.0); + q1 = x1 * std::sin(angle / 2.0); + q2 = x2 * std::sin(angle / 2.0); + q3 = x3 * std::sin(angle / 2.0); // Compute elements of the rotation matrix trans[0][0] = q0 * q0 + q1 * q1 - q2 * q2 - q3 * q3; @@ -297,7 +297,7 @@ AffineTransform< TScalar, NDimensions > { Pointer inv = New(); - return this->GetInverse(inv) ? inv.GetPointer() : NULL; + return this->GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } /** Compute a distance between two affine transforms */ @@ -318,7 +318,7 @@ AffineTransform< TScalar, NDimensions > term = this->GetOffset()[i] - other->GetOffset()[i]; result += term * term; } - return vcl_sqrt(result); + return std::sqrt(result); } /** Compute a distance between self and the identity transform */ @@ -347,7 +347,7 @@ AffineTransform< TScalar, NDimensions > result += term * term; } - return vcl_sqrt(result); + return std::sqrt(result); } } // namespace diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkAzimuthElevationToCartesianTransform.h b/Utilities/ITK/Modules/Core/Transform/include/itkAzimuthElevationToCartesianTransform.h index 02001bd3f8da3c36fe824c633ffa2a144ecedde2..2feb3d9cddad061d02fc3d160414f4f55bbd6177 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkAzimuthElevationToCartesianTransform.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkAzimuthElevationToCartesianTransform.h @@ -37,15 +37,15 @@ namespace itk * * The equations form performing the conversion from azimuth-elevation * coordinates to cartesian coordinates are as follows: - * z = vcl_sqrt((r^2*(cos(azimuth))^2)/(1 + (cos(azimuth))^2 * + * z = std::sqrt((r^2*(cos(azimuth))^2)/(1 + (cos(azimuth))^2 * * (tan(elevation))^2); - * x = z * vcl_tan(azimuth) - * y = z * vcl_tan(elevation) + * x = z * std::tan(azimuth) + * y = z * std::tan(elevation) * * The reversed transforms are: * azimuth = arctan(x/y) * elevation = arctan(y/z) - * r = vcl_sqrt(x^2 + y^2 + z^2) + * r = std::sqrt(x^2 + y^2 + z^2) * * In this class, we can also set what a "forward" transform means. If we call * SetForwardAzimuthElevationToCartesian(), a forward transform will return diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkAzimuthElevationToCartesianTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkAzimuthElevationToCartesianTransform.hxx index a076f1a6746c644ac0703c784094c227508f5287..79bcb6093ed923fb65827c7e0ade26e8d32026ce 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkAzimuthElevationToCartesianTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkAzimuthElevationToCartesianTransform.hxx @@ -107,13 +107,13 @@ AzimuthElevationToCartesianTransform< TScalar, - ( ( m_MaxElevation - 1 ) / 2.0 ) ); ScalarType r = ( m_FirstSampleDistance + point[2] ) * m_RadiusSampleSize; - ScalarType cosOfAzimuth = vcl_cos(Azimuth); - ScalarType tanOfElevation = vcl_tan(Elevation); + ScalarType cosOfAzimuth = std::cos(Azimuth); + ScalarType tanOfElevation = std::tan(Elevation); - result[2] = vcl_sqrt( ( r * r * cosOfAzimuth * cosOfAzimuth ) + result[2] = std::sqrt( ( r * r * cosOfAzimuth * cosOfAzimuth ) / ( 1 + cosOfAzimuth * cosOfAzimuth * tanOfElevation * tanOfElevation ) ); - result[0] = result[2] * vcl_tan(Azimuth); + result[0] = result[2] * std::tan(Azimuth); result[1] = result[2] * tanOfElevation; return result; } @@ -126,11 +126,11 @@ AzimuthElevationToCartesianTransform< TScalar, NDimensions >::TransformCartesian { InputPointType result; // Converted point - result[0] = ( vcl_atan(point[0] / point[2]) ) * ( 360 / ( 2 * vnl_math::pi ) ) + result[0] = ( std::atan(point[0] / point[2]) ) * ( 360 / ( 2 * vnl_math::pi ) ) + ( ( m_MaxAzimuth - 1 ) / 2.0 ); - result[1] = ( vcl_atan(point[1] / point[2]) ) * ( 360 / ( 2 * vnl_math::pi ) ) + result[1] = ( std::atan(point[1] / point[2]) ) * ( 360 / ( 2 * vnl_math::pi ) ) + ( ( m_MaxElevation - 1 ) / 2.0 ); - result[2] = ( ( vcl_sqrt(point[0] * point[0] + result[2] = ( ( std::sqrt(point[0] * point[0] + point[1] * point[1] + point[2] * point[2]) / m_RadiusSampleSize ) - m_FirstSampleDistance ); diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineBaseTransform.h b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineBaseTransform.h index 4ef12aebcab491f5e9803d77a0bc2c90b9c3a2ff..cb6d8e8b6c97159fceb9e1c1ab00ea81f0738d2e 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineBaseTransform.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineBaseTransform.h @@ -249,7 +249,6 @@ public: virtual OutputVectorType TransformVector( const InputVectorType & ) const { itkExceptionMacro( << "Method not applicable for deformable transform." ); - return OutputVectorType(); } /** Method to transform a vnl_vector - @@ -257,7 +256,6 @@ public: virtual OutputVnlVectorType TransformVector( const InputVnlVectorType & ) const { itkExceptionMacro( << "Method not applicable for deformable transform. " ); - return OutputVnlVectorType(); } /** Method to transform a CovariantVector - @@ -267,7 +265,6 @@ public: const InputCovariantVectorType & ) const { itkExceptionMacro( << "Method not applicable for deformable transfrom. " ); - return OutputCovariantVectorType(); } /** Get Jacobian at a point. A very specialized function just for BSplines */ diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineDeformableTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineDeformableTransform.hxx index 145eb8c17d3441bf6a26fd05f4272b2e3d91e840..be80556be3a391a15e727f4dfcbc92a6732382f7 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineDeformableTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineDeformableTransform.hxx @@ -507,7 +507,7 @@ BSplineDeformableTransform<TScalar, NDimensions, VSplineOrder> } // if no coefficients are set, this isn't a proper BSpline Transform - if( this->m_CoefficientImages[0]->GetBufferPointer() == 0) + if( this->m_CoefficientImages[0]->GetBufferPointer() == ITK_NULLPTR) { itkExceptionMacro( "B-spline coefficients have not been set" ); } diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransform.hxx index 1b4e2303d438ab24c15af444315d4a71f67c9a43..73fe63254e29161f2d12311ec39e7604090d4663 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransform.hxx @@ -218,8 +218,7 @@ BSplineTransform<TScalar, NDimensions, VSplineOrder> } } this->m_CoefficientImages[0]->SetDirection( direction ); - this->m_CoefficientImages[0]->Allocate(); - this->m_CoefficientImages[0]->FillBuffer( 0 ); + this->m_CoefficientImages[0]->Allocate(true); // initializes buffer to zero // Copy the information to the rest of the images for( unsigned int i = 1; i < SpaceDimension; i++ ) @@ -227,8 +226,7 @@ BSplineTransform<TScalar, NDimensions, VSplineOrder> this->m_CoefficientImages[i]->CopyInformation( this->m_CoefficientImages[0] ); this->m_CoefficientImages[i]->SetRegions( this->m_CoefficientImages[0]->GetLargestPossibleRegion() ); - this->m_CoefficientImages[i]->Allocate(); - this->m_CoefficientImages[i]->FillBuffer( 0 ); + this->m_CoefficientImages[i]->Allocate(true); // initialize buffer to zero } } diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransformInitializer.h b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransformInitializer.h index f68aba59115938d8c2f134ccd8a2c4c2d46b7801..2921fe1b0c37f05356189bb0e4cc72be0e63623b 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransformInitializer.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransformInitializer.h @@ -100,7 +100,7 @@ protected: BSplineTransformInitializer(); ~BSplineTransformInitializer(); - void PrintSelf( std::ostream & os, Indent indent ) const; + virtual void PrintSelf( std::ostream & os, Indent indent ) const ITK_OVERRIDE; private: BSplineTransformInitializer( const Self & ); //purposely not diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransformInitializer.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransformInitializer.hxx index 98a4d693f22aff10f3420690045f0d4d4beeedcf..4310de769a6b8397586388d17f76f2e5797b5175 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransformInitializer.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkBSplineTransformInitializer.hxx @@ -30,7 +30,7 @@ namespace itk template<typename TTransform, typename TImage> BSplineTransformInitializer<TTransform, TImage> ::BSplineTransformInitializer() : - m_Transform( NULL ), + m_Transform( ITK_NULLPTR ), m_SetTransformDomainMeshSizeViaInitializer( false ) { this->m_TransformDomainMeshSize.Fill( 1 ); @@ -123,7 +123,7 @@ BSplineTransformInitializer<TTransform, TImage> // We also store the corners using the point set class which gives us easy // access to the bounding box. - const CoordRepType BSplineTransformDomainEpsilon = vcl_pow( 2.0, -3 ); + const CoordRepType BSplineTransformDomainEpsilon = std::pow( 2.0, -3 ); ContinuousIndexType startIndex; for( unsigned int i = 0; i < SpaceDimension; i++ ) @@ -132,7 +132,7 @@ BSplineTransformInitializer<TTransform, TImage> BSplineTransformDomainEpsilon; } - for( unsigned int d = 0; d < vcl_pow( 2.0, SpaceDimension ); d++ ) + for( unsigned int d = 0; d < std::pow( 2.0, SpaceDimension ); d++ ) { ContinuousIndexType whichIndex; for( unsigned int i = 0; i < SpaceDimension; i++ ) @@ -200,7 +200,7 @@ BSplineTransformInitializer<TTransform, TImage> for( unsigned int i = 0; i < SpaceDimension; i++ ) { PointIdentifier oppositeCornerId = static_cast<PointIdentifier>( - vcl_pow( 2.0, static_cast<int>( i ) ) ) ^ transformDomainOriginId; + std::pow( 2.0, static_cast<int>( i ) ) ) ^ transformDomainOriginId; PointType corner; corner.Fill( 0.0 ); diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkCenteredAffineTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkCenteredAffineTransform.hxx index 4b0fa73ca6d07bb7a73ea9f7cb737ae32a50e3d3..fdc234b6176096d1a164e05b318e32fece21f8d8 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkCenteredAffineTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkCenteredAffineTransform.hxx @@ -182,7 +182,7 @@ CenteredAffineTransform<TScalar, NDimensions> { Pointer inv = New(); - return this->GetInverse(inv) ? inv.GetPointer() : NULL; + return this->GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } } // namespace diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkCenteredEuler3DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkCenteredEuler3DTransform.hxx index ba7d473d5133e3bfdf263aaca2eec1e696b7b51c..fa0a4a3d375ca9460e4a477dec7c7a292f72751c 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkCenteredEuler3DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkCenteredEuler3DTransform.hxx @@ -80,7 +80,6 @@ CenteredEuler3DTransform<TScalar> this->SetVarRotation(angleX, angleY, angleZ); CenterType newCenter; - typedef typename CenterType::ValueType CenterValueType; newCenter[0] = parameters[3]; newCenter[1] = parameters[4]; newCenter[2] = parameters[5]; @@ -139,12 +138,12 @@ CenteredEuler3DTransform<TScalar> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { // need to check if angles are in the right order - const double cx = vcl_cos( this->GetAngleX() ); - const double sx = vcl_sin( this->GetAngleX() ); - const double cy = vcl_cos( this->GetAngleY() ); - const double sy = vcl_sin( this->GetAngleY() ); - const double cz = vcl_cos( this->GetAngleZ() ); - const double sz = vcl_sin( this->GetAngleZ() ); + const double cx = std::cos( this->GetAngleX() ); + const double sx = std::sin( this->GetAngleX() ); + const double cy = std::cos( this->GetAngleY() ); + const double sy = std::sin( this->GetAngleY() ); + const double cz = std::cos( this->GetAngleZ() ); + const double sz = std::sin( this->GetAngleZ() ); jacobian.SetSize( 3, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); @@ -217,7 +216,7 @@ CenteredEuler3DTransform<TScalar> { Pointer inv = New(); - return this->GetInverse(inv) ? inv.GetPointer() : NULL; + return this->GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } // Print self diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkCenteredRigid2DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkCenteredRigid2DTransform.hxx index 1123f4754e7bcc6a12e81dc61fd2bbfb848e2327..b9d72a5bc70509a791cac15c78d0375f2cac941b 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkCenteredRigid2DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkCenteredRigid2DTransform.hxx @@ -130,8 +130,8 @@ void CenteredRigid2DTransform<TScalar> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { - const double ca = vcl_cos( this->GetAngle() ); - const double sa = vcl_sin( this->GetAngle() ); + const double ca = std::cos( this->GetAngle() ); + const double sa = std::sin( this->GetAngle() ); jacobian.SetSize( 2, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); @@ -212,7 +212,7 @@ CenteredRigid2DTransform<TScalar> { Pointer inv = New(); - return GetInverse(inv) ? inv.GetPointer() : NULL; + return GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } // Create and return an clone transformation diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkCenteredSimilarity2DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkCenteredSimilarity2DTransform.hxx index 87dbf25d40d00f17a7a6bb57df69baa054388046..6a14af804e94252f36c5b8e21cbb232f88e8f620 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkCenteredSimilarity2DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkCenteredSimilarity2DTransform.hxx @@ -119,8 +119,8 @@ CenteredSimilarity2DTransform<TScalar> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { const double angle = this->GetAngle(); - const double ca = vcl_cos(angle); - const double sa = vcl_sin(angle); + const double ca = std::cos(angle); + const double sa = std::sin(angle); jacobian.SetSize( 2, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); @@ -218,7 +218,7 @@ CenteredSimilarity2DTransform<TScalar> { return inv.GetPointer(); } - return NULL; + return ITK_NULLPTR; } // Create and return a clone of the transformation diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkCompositeTransform.h b/Utilities/ITK/Modules/Core/Transform/include/itkCompositeTransform.h index cdeda5cfd218fdcd9e21bb969be8acfd7a1aacbe..785de0c0af5d40e3e2f6ce6c3135d5ba6093a452 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkCompositeTransform.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkCompositeTransform.h @@ -358,7 +358,18 @@ public: * Compute the Jacobian with respect to the parameters for the compositie * transform using Jacobian rule. See comments in the implementation. */ - virtual void ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & j) const; + virtual void ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & j) const ITK_OVERRIDE; + + /** + * Expanded interface to Compute the Jacobian with respect to the parameters for the compositie + * transform using Jacobian rule. This version takes in temporary + * variables to avoid excessive constructions. + * NOTE: outJacobian and jacobianWithRespectToPosition MUST be sized + * prior to the call; outJacobian's size should be + * [NDimensions, this->GetNumberOfLocalParameters() ] + * jacobianWithRespectToPosition size == [ NDimensions, NDimensions ] + */ + virtual void ComputeJacobianWithRespectToParametersCachedTemporaries( const InputPointType & p, JacobianType & outJacobian, JacobianType & jacobianWithRespectToPosition ) const ITK_OVERRIDE; protected: CompositeTransform(); diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkCompositeTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkCompositeTransform.hxx index 1bf79cfae1d23e936a39fe05d8740e10deebdc6b..5d9fa7daabc12ee0a75d8984af978c845511d05d 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkCompositeTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkCompositeTransform.hxx @@ -653,7 +653,7 @@ CompositeTransform<TScalar, NDimensions> } else { - return NULL; + return ITK_NULLPTR; } } @@ -661,14 +661,27 @@ template <typename TScalar, unsigned int NDimensions> void CompositeTransform<TScalar, NDimensions> -::ComputeJacobianWithRespectToParameters( const InputPointType & p, JacobianType & j ) const +::ComputeJacobianWithRespectToParameters( const InputPointType & p, JacobianType & outJacobian ) const { /* Returns a concatenated MxN array, holding the Jacobian of each sub * transform that is selected for optimization. The order is the same * as that in which they're applied, i.e. reverse order. * M rows = dimensionality of the transforms * N cols = total number of parameters in the selected sub transforms. */ - j.SetSize( NDimensions, this->GetNumberOfLocalParameters() ); + outJacobian.SetSize( NDimensions, this->GetNumberOfLocalParameters() ); + JacobianType jacobianWithRespectToPosition(NDimensions, NDimensions); + this->ComputeJacobianWithRespectToParametersCachedTemporaries( p, outJacobian, jacobianWithRespectToPosition ); +} + +template +<typename TScalar, unsigned int NDimensions> +void +CompositeTransform<TScalar, NDimensions> +::ComputeJacobianWithRespectToParametersCachedTemporaries( const InputPointType & p, JacobianType & outJacobian, JacobianType & jacobianWithRespectToPosition ) const +{ + //NOTE: This must have been done outside of outJacobian.SetSize( NDimensions, this->GetNumberOfLocalParameters() ); + //NOTE: assert( outJacobian.GetSize == ( NDimensions, this->GetNumberOfLocalParameters() ) ) + //NOTE: assert( jacobianWithRespectToPosition.GetSize == (NDimensions, NDimensions) ) NumberOfParametersType offset = NumericTraits< NumberOfParametersType >::Zero; @@ -715,12 +728,12 @@ CompositeTransform<TScalar, NDimensions> * */ for( signed long tind = (signed long) this->GetNumberOfTransforms() - 1; - tind >= 0; tind-- ) + tind >= 0; --tind ) { /* Get a raw pointer for efficiency, avoiding SmartPointer register/unregister */ - const TransformType * transform = this->GetNthTransformConstPointer( tind ); + const TransformType * const transform = this->GetNthTransformConstPointer( tind ); - NumberOfParametersType offsetLast = offset; + const NumberOfParametersType offsetLast = offset; if( this->GetNthTransformToOptimize( tind ) ) { @@ -729,12 +742,11 @@ CompositeTransform<TScalar, NDimensions> * better */ // to do: why parameters are listed from N-1 to 1??? - typename TransformType::JacobianType current_jacobian; - NumberOfParametersType numberOfLocalParameters = transform->GetNumberOfLocalParameters(); + const NumberOfParametersType numberOfLocalParameters = transform->GetNumberOfLocalParameters(); - current_jacobian.SetSize( NDimensions, numberOfLocalParameters ); + typename TransformType::JacobianType current_jacobian( NDimensions, numberOfLocalParameters ); transform->ComputeJacobianWithRespectToParameters( transformedPoint, current_jacobian ); - j.update( current_jacobian, 0, offset ); + outJacobian.update( current_jacobian, 0, offset ); offset += numberOfLocalParameters; } @@ -744,28 +756,24 @@ CompositeTransform<TScalar, NDimensions> * jacobian by multiplying the current matrix jumping over the * first transform. The matrix here refers to dT/dx at the point. * For example, in the affine transform, this is the affine matrix. - * TODO1: for general transform, there should be something like + * + * TODO: for general transform, there should be something like * GetPartialDerivativeOfPointCoordinates * * Also, noted the multiplication contains all the affine matrix from * all transforms no matter they are going to be optimized or not - * */ // update every old term by left multiplying dTk / dT{k-1} // do this before computing the transformedPoint for the next iteration if( offsetLast > 0 ) { + transform->ComputeJacobianWithRespectToPosition(transformedPoint, jacobianWithRespectToPosition); - JacobianType old_j = j.extract(NDimensions, offsetLast, 0, 0); - - JacobianType j1; - - j1.SetSize(NDimensions, NDimensions); - - transform->ComputeJacobianWithRespectToPosition(transformedPoint, j1); + const JacobianType & old_j = outJacobian.extract(NDimensions, offsetLast, 0, 0); + const JacobianType & update_j = jacobianWithRespectToPosition * old_j; - j.update(j1 * old_j, 0, 0); + outJacobian.update(update_j, 0, 0); // itkExceptionMacro(" To sort out with new ComputeJacobianWithRespectToPosition prototype "); } @@ -1074,8 +1082,13 @@ CompositeTransform<TScalar, NDimensions> /* The input values are in a monolithic block, so we have to point * to the subregion corresponding to the individual subtransform. * This simply creates an Array object with data pointer, no - * memory is allocated or copied. */ - DerivativeType subUpdate( &( (update.data_block() )[offset]), + * memory is allocated or copied. + * NOTE: the use of const_cast is used to avoid a deep copy in the underlying vnl_vector + * by using LetArrayManageMemory=false, and being very careful here we can + * ensure that casting away consteness does not result in memory corruption. */ + typename DerivativeType::ValueType * nonConstDataRefForPerformance = + const_cast< typename DerivativeType::ValueType * >( &( (update.data_block() )[offset]) ); + const DerivativeType subUpdate( nonConstDataRefForPerformance, subtransform->GetNumberOfParameters(), false ); /* This call will also call SetParameters, so don't need to call it * expliclity here. */ diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkEuler2DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkEuler2DTransform.hxx index 7824867ef8d5c2b6b0ece58f56157eb6a8fbdf16..0b38f4afafa05b5dc17eec7821abab3520211e76 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkEuler2DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkEuler2DTransform.hxx @@ -69,7 +69,7 @@ Euler2DTransform< TScalar > { Pointer inv = New(); - return GetInverse(inv) ? inv.GetPointer() : NULL; + return GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } // Create and return an inverse transformation diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkEuler3DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkEuler3DTransform.hxx index 2e129fb8fa7d9dbf6e618631878b6c1c18a7252b..fa666a0a579122894550d43f5d2cd91204fcbb4d 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkEuler3DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkEuler3DTransform.hxx @@ -152,45 +152,45 @@ Euler3DTransform<TScalar> { if( m_ComputeZYX ) { - m_AngleY = -vcl_asin(this->GetMatrix()[2][0]); - double C = vcl_cos(m_AngleY); - if( vcl_fabs(C) > 0.00005 ) + m_AngleY = -std::asin(this->GetMatrix()[2][0]); + double C = std::cos(m_AngleY); + if( std::fabs(C) > 0.00005 ) { double x = this->GetMatrix()[2][2] / C; double y = this->GetMatrix()[2][1] / C; - m_AngleX = vcl_atan2(y, x); + m_AngleX = std::atan2(y, x); x = this->GetMatrix()[0][0] / C; y = this->GetMatrix()[1][0] / C; - m_AngleZ = vcl_atan2(y, x); + m_AngleZ = std::atan2(y, x); } else { m_AngleX = NumericTraits<ScalarType>::Zero; double x = this->GetMatrix()[1][1]; double y = -this->GetMatrix()[0][1]; - m_AngleZ = vcl_atan2(y, x); + m_AngleZ = std::atan2(y, x); } } else { - m_AngleX = vcl_asin(this->GetMatrix()[2][1]); - double A = vcl_cos(m_AngleX); - if( vcl_fabs(A) > 0.00005 ) + m_AngleX = std::asin(this->GetMatrix()[2][1]); + double A = std::cos(m_AngleX); + if( std::fabs(A) > 0.00005 ) { double x = this->GetMatrix()[2][2] / A; double y = -this->GetMatrix()[2][0] / A; - m_AngleY = vcl_atan2(y, x); + m_AngleY = std::atan2(y, x); x = this->GetMatrix()[1][1] / A; y = -this->GetMatrix()[0][1] / A; - m_AngleZ = vcl_atan2(y, x); + m_AngleZ = std::atan2(y, x); } else { m_AngleZ = NumericTraits<ScalarType>::Zero; double x = this->GetMatrix()[0][0]; double y = this->GetMatrix()[1][0]; - m_AngleY = vcl_atan2(y, x); + m_AngleY = std::atan2(y, x); } } this->ComputeMatrix(); @@ -203,12 +203,12 @@ Euler3DTransform<TScalar> ::ComputeMatrix(void) { // need to check if angles are in the right order - const ScalarType cx = vcl_cos(m_AngleX); - const ScalarType sx = vcl_sin(m_AngleX); - const ScalarType cy = vcl_cos(m_AngleY); - const ScalarType sy = vcl_sin(m_AngleY); - const ScalarType cz = vcl_cos(m_AngleZ); - const ScalarType sz = vcl_sin(m_AngleZ); + const ScalarType cx = std::cos(m_AngleX); + const ScalarType sx = std::sin(m_AngleX); + const ScalarType cy = std::cos(m_AngleY); + const ScalarType sy = std::sin(m_AngleY); + const ScalarType cz = std::cos(m_AngleZ); + const ScalarType sz = std::sin(m_AngleZ); const ScalarType one = NumericTraits<ScalarType>::One; const ScalarType zero = NumericTraits<ScalarType>::Zero; @@ -245,12 +245,12 @@ Euler3DTransform<TScalar> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { // need to check if angles are in the right order - const double cx = vcl_cos(m_AngleX); - const double sx = vcl_sin(m_AngleX); - const double cy = vcl_cos(m_AngleY); - const double sy = vcl_sin(m_AngleY); - const double cz = vcl_cos(m_AngleZ); - const double sz = vcl_sin(m_AngleZ); + const double cx = std::cos(m_AngleX); + const double sx = std::sin(m_AngleX); + const double cy = std::cos(m_AngleY); + const double sy = std::sin(m_AngleY); + const double cz = std::cos(m_AngleZ); + const double sz = std::sin(m_AngleZ); jacobian.SetSize( 3, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkLandmarkBasedTransformInitializer.h b/Utilities/ITK/Modules/Core/Transform/include/itkLandmarkBasedTransformInitializer.h index 4ba99812a82960d8a629796c763b98066e65c03d..ce71fc752604c00d577e1ebd5936512b79d109e9 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkLandmarkBasedTransformInitializer.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkLandmarkBasedTransformInitializer.h @@ -147,7 +147,7 @@ protected: LandmarkBasedTransformInitializer(); ~LandmarkBasedTransformInitializer(){} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; // Supported Transform types typedef enum { diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkLandmarkBasedTransformInitializer.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkLandmarkBasedTransformInitializer.hxx index 1aab569782cc9de0f2715c895d988392a6df67af..a37ec56308dc4d6e11c853a1acc6ad2f92bd7feb 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkLandmarkBasedTransformInitializer.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkLandmarkBasedTransformInitializer.hxx @@ -59,7 +59,7 @@ LandmarkBasedTransformInitializer< TTransform, TFixedImage, TMovingImage > { AffineTransformType *transform = dynamic_cast<AffineTransformType *>(this->m_Transform.GetPointer()); - if ( transform == 0 ) + if ( transform == ITK_NULLPTR ) { itkExceptionMacro( << "AffineTransform Expected but transform is " << this->m_Transform->GetNameOfClass() ); @@ -211,7 +211,7 @@ LandmarkBasedTransformInitializer< TTransform, TFixedImage, TMovingImage > itkDebugMacro("Internal Initialize VersorRigid3DTransformType"); VersorRigid3DTransformType *transform = dynamic_cast< VersorRigid3DTransformType * >( this->m_Transform.GetPointer() ); - if ( transform == 0 ) + if ( transform == ITK_NULLPTR ) { itkExceptionMacro( << "VersorRigid3DTransformType Expected but transform is " << this->m_Transform->GetNameOfClass() ); @@ -249,7 +249,6 @@ LandmarkBasedTransformInitializer< TTransform, TFixedImage, TMovingImage > typedef typename VersorRigid3DTransformType::OutputVectorType VectorType; typedef typename VersorRigid3DTransformType::OutputPointType PointType; - typedef typename VersorRigid3DTransformType::CenterType RotationCenterType; // Compute the centroids PointType fixedCentroid; @@ -406,7 +405,7 @@ LandmarkBasedTransformInitializer< TTransform, TFixedImage, TMovingImage > Rigid2DTransformType *transform = dynamic_cast< Rigid2DTransformType * >(this->m_Transform.GetPointer() ); - if ( transform == 0 ) + if ( transform == ITK_NULLPTR ) { itkExceptionMacro( << "VersorRigid3DTransformType Expected but transform is " << this->m_Transform->GetNameOfClass() ); @@ -425,7 +424,7 @@ LandmarkBasedTransformInitializer< TTransform, TFixedImage, TMovingImage > return; } - const double PI = 4.0 * vcl_atan(1.0); + const double PI = 4.0 * std::atan(1.0); typedef typename Rigid2DTransformType::OutputVectorType VectorType; typedef typename Rigid2DTransformType::OutputPointType PointType; @@ -510,9 +509,9 @@ LandmarkBasedTransformInitializer< TTransform, TFixedImage, TMovingImage > } itkDebugMacro(<< "Dot Product of landmarks: " << s_dot << " Cross Product: " << s_cross); - if ( vcl_fabs(s_dot) > 0.00005 ) + if ( std::fabs(s_dot) > 0.00005 ) { - rotationAngle = vcl_atan2(s_cross, s_dot); + rotationAngle = std::atan2(s_cross, s_dot); } else { @@ -554,7 +553,7 @@ LandmarkBasedTransformInitializer< TTransform, TFixedImage, TMovingImage > itkExceptionMacro("Different number of fixed and moving landmarks"); return; } - this->InternalInitializeTransform(static_cast<TTransform *>(0)); + this->InternalInitializeTransform(static_cast<TTransform *>(ITK_NULLPTR)); } template< typename TTransform, typename TFixedImage, typename TMovingImage > diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkMatrixOffsetTransformBase.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkMatrixOffsetTransformBase.hxx index 24bd8d5f0cc64dfdf6b283a37cd8d460802fe2ad..ad8999a4bd10a365857b96b242923b7d0a712374 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkMatrixOffsetTransformBase.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkMatrixOffsetTransformBase.hxx @@ -528,7 +528,7 @@ MatrixOffsetTransformBase<TScalar, NInputDimensions, NOutputDimensions> { Pointer inv = New(); - return GetInverse(inv) ? inv.GetPointer() : NULL; + return GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } // Get fixed parameters @@ -540,7 +540,6 @@ MatrixOffsetTransformBase<TScalar, NInputDimensions, NOutputDimensions> { this->m_FixedParameters = fp; InputPointType c; - typedef typename ParametersType::ValueType ParameterValueType; for( unsigned int i = 0; i < NInputDimensions; i++ ) { c[i] = this->m_FixedParameters[i]; diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkMultiTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkMultiTransform.hxx index 374d08e7befb24777ed33eda59825ea663f4bdc8..4d86a320a186cb896efeb609e9dab941f8233a87 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkMultiTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkMultiTransform.hxx @@ -341,8 +341,13 @@ MultiTransform<TScalar, NDimensions, NSubDimensions> /* The input values are in a monolithic block, so we have to point * to the subregion corresponding to the individual subtransform. * This simply creates an Array object with data pointer, no - * memory is allocated or copied. */ - DerivativeType subUpdate( &( (update.data_block() )[offset]), subtransform->GetNumberOfParameters(), false ); + * memory is allocated or copied. + * NOTE: the use of const_cast is used to avoid a deep copy in the underlying vnl_vector + * by using LetArrayManageMemory=false, and being very careful here we can + * ensure that casting away consteness does not result in memory corruption. */ + typename DerivativeType::ValueType * nonConstDataRefForPerformance = + const_cast< typename DerivativeType::ValueType * >( &( (update.data_block() )[offset]) ); + const DerivativeType subUpdate( nonConstDataRefForPerformance, subtransform->GetNumberOfParameters(), false ); /* This call will also call SetParameters, so don't need to call it * expliclity here. */ subtransform->UpdateTransformParameters( subUpdate, factor ); diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkQuaternionRigidTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkQuaternionRigidTransform.hxx index 9e6efff1caa83d5cb673863a73984339b2b375d8..3537b6714ce0d338c4e51419a36ad8f43319fc4d 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkQuaternionRigidTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkQuaternionRigidTransform.hxx @@ -28,8 +28,8 @@ QuaternionRigidTransform<TScalar> ::QuaternionRigidTransform() : Superclass(ParametersDimension) { - m_Rotation = VnlQuaternionType(0, 0, 0, 1); // axis * vcl_sin(t/2), - // vcl_cos(t/2) + m_Rotation = VnlQuaternionType(0, 0, 0, 1); // axis * std::sin(t/2), + // std::cos(t/2) } // Constructor with default arguments @@ -37,8 +37,8 @@ template <typename TScalar> QuaternionRigidTransform<TScalar>::QuaternionRigidTransform(unsigned int parametersDimension) : Superclass(parametersDimension) { - m_Rotation = VnlQuaternionType(0, 0, 0, 1); // axis * vcl_sin(t/2), - // vcl_cos(t/2) + m_Rotation = VnlQuaternionType(0, 0, 0, 1); // axis * std::sin(t/2), + // std::cos(t/2) } // Constructor with explicit arguments diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkRigid2DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkRigid2DTransform.hxx index 7d611caacdd3ad2f7311d563cef785eb154e9ead..6bce0ba9d9dd61e43e794df849614a144b6656f4 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkRigid2DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkRigid2DTransform.hxx @@ -100,14 +100,14 @@ Rigid2DTransform<TScalar> vnl_matrix<TScalar> r(2, 2); r = svd.U() * svd.V().transpose(); - m_Angle = vcl_acos(r[0][0]); + m_Angle = std::acos(r[0][0]); if( r[1][0] < 0.0 ) { m_Angle = -m_Angle; } - if( r[1][0] - vcl_sin(m_Angle) > 0.000001 ) + if( r[1][0] - std::sin(m_Angle) > 0.000001 ) { itkWarningMacro( "Bad Rotation Matrix " << this->GetMatrix() ); } @@ -159,7 +159,7 @@ Rigid2DTransform<TScalar> { Pointer inv = New(); - return GetInverse(inv) ? inv.GetPointer() : NULL; + return GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } // Create and return a clone of the transformation @@ -200,7 +200,7 @@ void Rigid2DTransform<TScalar> ::SetAngleInDegrees(TScalar angle) { - const TScalar angleInRadians = angle * vcl_atan(1.0) / 45.0; + const TScalar angleInRadians = angle * std::atan(1.0) / 45.0; this->SetAngle(angleInRadians); } @@ -211,8 +211,8 @@ void Rigid2DTransform<TScalar> ::ComputeMatrix(void) { - const MatrixValueType ca = vcl_cos(m_Angle); - const MatrixValueType sa = vcl_sin(m_Angle); + const MatrixValueType ca = std::cos(m_Angle); + const MatrixValueType sa = std::sin(m_Angle); MatrixType rotationMatrix; @@ -287,8 +287,8 @@ Rigid2DTransform<TScalar>::ComputeJacobianWithRespectToParameters(const InputPoi j.SetSize( OutputSpaceDimension, this->GetNumberOfLocalParameters() ); j.Fill(0.0); - const double ca = vcl_cos( this->GetAngle() ); - const double sa = vcl_sin( this->GetAngle() ); + const double ca = std::cos( this->GetAngle() ); + const double sa = std::sin( this->GetAngle() ); const double cx = this->GetCenter()[0]; const double cy = this->GetCenter()[1]; diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkRigid3DPerspectiveTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkRigid3DPerspectiveTransform.hxx index 1cc255202617d93516a206333489975dffc7b2e9..96021688728993e281b4f8bbfe894e7a3fdea1f5 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkRigid3DPerspectiveTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkRigid3DPerspectiveTransform.hxx @@ -85,7 +85,7 @@ Rigid3DPerspectiveTransform<TScalar> axis[2] = parameters[2]; if( norm > NumericTraits<double>::Zero ) { - norm = vcl_sqrt(norm); + norm = std::sqrt(norm); } double epsilon = 1e-10; @@ -150,8 +150,8 @@ template <typename TScalar> void Rigid3DPerspectiveTransform<TScalar>::SetRotation(const Vector<TScalar, 3> & axis, double angle) { - const double sinus = vcl_sin(angle / 2.0); - const double cosinus = vcl_cos(angle / 2.0); + const double sinus = std::sin(angle / 2.0); + const double cosinus = std::cos(angle / 2.0); Vector<TScalar, 3> norm; norm = axis; diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkRigid3DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkRigid3DTransform.hxx index ea5798c91a14e303d91d5b1e63d4dbc5d65781f5..43e7e7407cfbd69fb78cd7b994dc867244dd219d 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkRigid3DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkRigid3DTransform.hxx @@ -165,7 +165,7 @@ typename Rigid3DTransform< TScalar >::InverseTransformBasePointer Rigid3DTransform< TScalar >::GetInverseTransform() const { Pointer inv = New(); - return this->GetInverse(inv) ? inv.GetPointer() : NULL; + return this->GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } template< typename TScalar > diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkScalableAffineTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkScalableAffineTransform.hxx index 02cc7bdbb3fe50fe108d65845442ebdc9e70bf33..89a4852f429736efa1eda32444dc97e85b350cb7 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkScalableAffineTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkScalableAffineTransform.hxx @@ -170,7 +170,7 @@ ScalableAffineTransform< TScalar, NDimensions > { Pointer inv = New(); - return this->GetInverse(inv) ? inv.GetPointer() : NULL; + return this->GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } /** Set the scale of the transformation */ diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkScaleLogarithmicTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkScaleLogarithmicTransform.hxx index 514bc9e580b123805a665c84e91daac57b8ba204..08ba1a47f9afaafbc7b96f7aac4623f8b842ecb3 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkScaleLogarithmicTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkScaleLogarithmicTransform.hxx @@ -45,7 +45,7 @@ ScaleLogarithmicTransform<ScalarType, NDimensions> for( unsigned int i = 0; i < SpaceDimension; i++ ) { - scales[i] = vcl_exp(parameters[i]); + scales[i] = std::exp(parameters[i]); } // Save parameters. Needed for proper operation of TransformUpdateParameters. if( ¶meters != &(this->m_Parameters) ) @@ -71,7 +71,7 @@ const typename ScaleLogarithmicTransform<TScalar, NDimensions>::ParametersType // Transfer the translation part for( unsigned int i = 0; i < SpaceDimension; i++ ) { - this->m_Parameters[i] = vcl_log(scales[i]); + this->m_Parameters[i] = std::log(scales[i]); } itkDebugMacro(<< "After getting parameters " << this->m_Parameters); diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkScaleSkewVersor3DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkScaleSkewVersor3DTransform.hxx index fd7d2829f60d02d87e4bede52a1f2f5865c7ad45..63222de8e3f6a68c8ea78ce4b13a7f9a9ac68cac 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkScaleSkewVersor3DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkScaleSkewVersor3DTransform.hxx @@ -88,7 +88,7 @@ ScaleSkewVersor3DTransform<TScalar> axis[2] = parameters[2]; if( norm > 0 ) { - norm = vcl_sqrt(norm); + norm = std::sqrt(norm); } double epsilon = 1e-10; @@ -137,7 +137,7 @@ ScaleSkewVersor3DTransform<TScalar> // // Parameters are ordered as: // -// p[0:2] = right part of the versor (axis times vcl_sin(t/2)) +// p[0:2] = right part of the versor (axis times std::sin(t/2)) // p[3:5] = translation components // p[6:8] = Scale // p[9:14] = Skew {xy, xz, yx, yz, zx, zy} diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkScaleTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkScaleTransform.hxx index d7881e6964f54f49f45fcf01606abfca2a0abfbf..24eb4b7775ff18e068653e53fcd68d115716fad3 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkScaleTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkScaleTransform.hxx @@ -44,7 +44,6 @@ void ScaleTransform<ScalarType, NDimensions> ::SetParameters(const ParametersType & parameters) { - typedef typename ParametersType::ValueType ParameterValueType; for( unsigned int i = 0; i < SpaceDimension; i++ ) { m_Scale[i] = parameters[i]; @@ -199,7 +198,7 @@ ScaleTransform<ScalarType, NDimensions> { return inv.GetPointer(); } - return NULL; + return ITK_NULLPTR; } // Compute the Jacobian of the transformation diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkScaleVersor3DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkScaleVersor3DTransform.hxx index 6ebca1f6831e0f70ad76e70301280ab559b9ccff..38945b8d4fbfbdcc68ac78cbfc2b3a02c12ab301 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkScaleVersor3DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkScaleVersor3DTransform.hxx @@ -91,7 +91,7 @@ ScaleVersor3DTransform<TScalar> axis[2] = parameters[2]; if( norm > 0 ) { - norm = vcl_sqrt(norm); + norm = std::sqrt(norm); } double epsilon = 1e-10; @@ -132,7 +132,7 @@ ScaleVersor3DTransform<TScalar> // // Parameters are ordered as: // -// p[0:2] = right part of the versor (axis times vcl_sin(t/2)) +// p[0:2] = right part of the versor (axis times std::sin(t/2)) // p[3:5] = translation components // p[6:8] = Scale // diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkSimilarity2DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkSimilarity2DTransform.hxx index c024d0e123b9b1fedd6fd91b75e4fda240fd7bed..323c79dd7b76776edf21778735f111a63aedebf2 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkSimilarity2DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkSimilarity2DTransform.hxx @@ -128,8 +128,8 @@ Similarity2DTransform<TScalar> { const double angle = this->GetAngle(); - const double cc = vcl_cos(angle); - const double ss = vcl_sin(angle); + const double cc = std::cos(angle); + const double ss = std::sin(angle); const MatrixValueType ca = cc * m_Scale; const MatrixValueType sa = ss * m_Scale; @@ -148,17 +148,17 @@ void Similarity2DTransform<TScalar> ::ComputeMatrixParameters(void) { - m_Scale = vcl_sqrt( vnl_math_sqr(this->GetMatrix()[0][0]) + m_Scale = std::sqrt( vnl_math_sqr(this->GetMatrix()[0][0]) + vnl_math_sqr(this->GetMatrix()[0][1]) ); - this->SetVarAngle( vcl_acos(this->GetMatrix()[0][0] / m_Scale) ); + this->SetVarAngle( std::acos(this->GetMatrix()[0][0] / m_Scale) ); if( this->GetMatrix()[1][0] < 0.0 ) { this->SetVarAngle( -this->GetAngle() ); } - if( ( this->GetMatrix()[1][0] / m_Scale ) - vcl_sin( this->GetAngle() ) > 0.000001 ) + if( ( this->GetMatrix()[1][0] / m_Scale ) - std::sin( this->GetAngle() ) > 0.000001 ) { std::cout << "Bad Rotation Matrix" << std::endl; } @@ -170,8 +170,8 @@ Similarity2DTransform<TScalar> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { const double angle = this->GetAngle(); - const double ca = vcl_cos(angle); - const double sa = vcl_sin(angle); + const double ca = std::cos(angle); + const double sa = std::sin(angle); jacobian.SetSize( 2, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); @@ -255,7 +255,7 @@ Similarity2DTransform<TScalar> { return inv.GetPointer(); } - return NULL; + return ITK_NULLPTR; } // Create and return a clone of the transformation diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkSimilarity3DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkSimilarity3DTransform.hxx index 8c132b4394fd041a05e4756ae71144a5a19d1a88..8c152d9e98c1cd88fdac61924561a7701a0d3541 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkSimilarity3DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkSimilarity3DTransform.hxx @@ -144,7 +144,7 @@ Similarity3DTransform<TScalar> axis[2] = parameters[2]; if( norm > 0 ) { - norm = vcl_sqrt(norm); + norm = std::sqrt(norm); } double epsilon = 1e-10; @@ -180,7 +180,7 @@ Similarity3DTransform<TScalar> // // Parameters are ordered as: // -// p[0:2] = right part of the versor (axis times vcl_sin(t/2)) +// p[0:2] = right part of the versor (axis times std::sin(t/2)) // p[3:5} = translation components // p[6:6} = scaling factor (isotropic) // diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkThinPlateR2LogRSplineKernelTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkThinPlateR2LogRSplineKernelTransform.hxx index b035ca829bb642d7df695f4bd81bb93d91ab9991..57958f024f096c03e4db01764edafb6ec1678b17 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkThinPlateR2LogRSplineKernelTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkThinPlateR2LogRSplineKernelTransform.hxx @@ -30,7 +30,7 @@ ThinPlateR2LogRSplineKernelTransform< TScalar, NDimensions >::ComputeG(const Inp gmatrix.fill(NumericTraits< TScalar >::Zero); const TScalar R2logR = - ( r > 1e-8 ) ? r *r *vcl_log(r):NumericTraits< TScalar >::Zero; + ( r > 1e-8 ) ? r *r *std::log(r):NumericTraits< TScalar >::Zero; gmatrix.fill_diagonal(R2logR); } @@ -51,7 +51,7 @@ ThinPlateR2LogRSplineKernelTransform< TScalar, NDimensions >::ComputeDeformation InputVectorType position = thisPoint - sp->Value(); const TScalar r = position.GetNorm(); const TScalar R2logR = - ( r > 1e-8 ) ? r *r *vcl_log(r):NumericTraits< TScalar >::Zero; + ( r > 1e-8 ) ? r *r *std::log(r):NumericTraits< TScalar >::Zero; for ( unsigned int odim = 0; odim < NDimensions; odim++ ) { result[odim] += R2logR * this->m_DMatrix(odim, lnd); diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkTransform.h b/Utilities/ITK/Modules/Core/Transform/include/itkTransform.h index 0f376c302e0cb788539089d8b21eab97f91285c8..5e5127f9fa7a4d19e8a2c8ef900825e72e2fe626 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkTransform.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkTransform.h @@ -192,7 +192,6 @@ public: { itkExceptionMacro( "TransformVector(const InputVectorType &)" "is unimplemented for " << this->GetNameOfClass() ); - return OutputVectorType(); } /** Method to transform a vector at a given location. @@ -208,7 +207,6 @@ public: { itkExceptionMacro( "TransformVector( const InputVnlVectorType & ) is " "unimplemented for " << this->GetNameOfClass() ); - return OutputVnlVectorType(); } /** Method to transform a vnl_vector, at a point. @@ -225,7 +223,6 @@ public: { itkExceptionMacro( "TransformVector( const InputVectorPixelType & ) is " "unimplemented for " << this->GetNameOfClass() ); - return OutputVectorPixelType(); } /** Method to transform a vector stored in a VectorImage, at a point. @@ -241,7 +238,6 @@ public: { itkExceptionMacro( "TransformCovariantVector( const InputCovariantVectorType & ) is " "unimplemented for " << this->GetNameOfClass() ); - return OutputCovariantVectorType(); } /** Method to transform a CovariantVector, using a point. Global transforms * can ignore the \c point parameter. Local transforms (e.g. deformation @@ -259,7 +255,6 @@ public: { itkExceptionMacro( "TransformCovariantVector(const InputVectorPixelType &)" "is unimplemented for " << this->GetNameOfClass() ); - return OutputVectorPixelType(); } /** Method to transform a CovariantVector, using a point. Global transforms @@ -279,7 +274,6 @@ public: itkExceptionMacro( "TransformDiffusionTensor3D( const InputDiffusionTensor3DType & ) is " "unimplemented for " << this->GetNameOfClass() ); - return OutputDiffusionTensor3DType(); } /** Method to transform a diffusion tensor at a point. Global transforms @@ -298,7 +292,6 @@ public: itkExceptionMacro( "TransformDiffusionTensor( const InputVectorPixelType & ) is " "unimplemented for " << this->GetNameOfClass() ); - return OutputVectorPixelType(); } virtual OutputVectorPixelType TransformDiffusionTensor3D( @@ -321,7 +314,6 @@ public: itkExceptionMacro( "TransformSymmetricSecondRankTensor( const InputSymmetricSecondRankTensorType & ) is " "unimplemented for " << this->GetNameOfClass() ); - return OutputSymmetricSecondRankTensorType(); } /** Method to transform a ssr tensor stored in a VectorImage */ @@ -331,7 +323,6 @@ public: itkExceptionMacro( "TransformSymmetricSecondRankTensor( const InputVectorPixelType & ) is " "unimplemented for " << this->GetNameOfClass() ); - return OutputVectorPixelType(); } /** Method to transform a diffusion tensor stored in a VectorImage, at @@ -429,7 +420,7 @@ public: */ virtual InverseTransformBasePointer GetInverseTransform() const { - return NULL; + return ITK_NULLPTR; } /** Generate a platform independent name */ @@ -505,12 +496,12 @@ public: * will most likely occur during multi-threading. * To avoid repeatitive memory allocation, pass in 'jacobian' with its size * already set. */ - virtual void ComputeJacobianWithRespectToParameters(const InputPointType & itkNotUsed(p), JacobianType & itkNotUsed(jacobian) ) const + virtual void ComputeJacobianWithRespectToParameters(const InputPointType & itkNotUsed(p), JacobianType & itkNotUsed(jacobian) ) const = 0; + + virtual void ComputeJacobianWithRespectToParametersCachedTemporaries(const InputPointType & p, JacobianType & jacobian, JacobianType & itkNotUsed(jacobianWithRespectToPosition) ) const { - itkExceptionMacro( - "ComputeJacobianWithRespectToParamters( InputPointType, JacobianType" - " is unimplemented for " << this->GetNameOfClass() ); - return; + //NOTE: default implementation is not optimized, and just falls back to original methods. + this->ComputeJacobianWithRespectToParameters(p, jacobian); } @@ -524,7 +515,6 @@ public: itkExceptionMacro( "ComputeJacobianWithRespectToPosition( InputPointType, JacobianType" " is unimplemented for " << this->GetNameOfClass() ); - return; } diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkTransform.hxx index 52b2c49dc7af1b48738a884b37147e2e1d59fe1a..f62bec64dea3dc84c6ed47802187b5376f6197e3 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkTransform.hxx @@ -71,7 +71,7 @@ std::string Transform<TScalar, NInputDimensions, NOutputDimensions> n << GetNameOfClass(); n << "_"; - n << this->GetTransformTypeAsString(static_cast<TScalar *>(0) ); + n << this->GetTransformTypeAsString(static_cast<TScalar *>(ITK_NULLPTR) ); n << "_" << this->GetInputSpaceDimension() << "_" << this->GetOutputSpaceDimension(); return n.str(); } diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkTranslationTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkTranslationTransform.hxx index 4ce0db39d2e52ab2fc56fa638c0e5661e2ff73d1..21aa6f60df826a0ac008db4622c8408699080eae 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkTranslationTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkTranslationTransform.hxx @@ -59,7 +59,6 @@ TranslationTransform<TScalar, NDimensions> this->m_Parameters = parameters; } - typedef typename ParametersType::ValueType ParameterValueType; bool modified = false; for( unsigned int i = 0; i < SpaceDimension; i++ ) { @@ -174,7 +173,7 @@ TranslationTransform<TScalar, NDimensions> { Pointer inv = New(); - return GetInverse(inv) ? inv.GetPointer() : NULL; + return GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } // Compute the Jacobian in one position diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkVersorRigid3DTransform.h b/Utilities/ITK/Modules/Core/Transform/include/itkVersorRigid3DTransform.h index cd761f6b5dcf3c3ef51cc3d775b8434e97c40d58..ebd6bb37dc76b485ec84d93545b67a4470fd2420 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkVersorRigid3DTransform.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkVersorRigid3DTransform.h @@ -86,6 +86,8 @@ public: /** Versor type. */ typedef typename Superclass::VersorType VersorType; + typedef typename VersorType::VectorType VectorType; + typedef typename Superclass::AxisType AxisType; typedef typename Superclass::AngleType AngleType; @@ -93,6 +95,8 @@ public: typedef typename Superclass::TranslationValueType TranslationValueType; typedef typename Superclass::ParameterValueType ParameterValueType; + typedef Array<ParameterValueType> DerivativeType; + /** Set the transformation from a container of parameters * This is typically used by optimizers. * There are 6 parameters. The first three represent the @@ -101,6 +105,15 @@ public: virtual const ParametersType & GetParameters(void) const; + /** Update the transform's parameters by the values in \c update. + * \param update must be of the same length as returned by + * GetNumberOfParameters(). Throw an exception otherwise. + * \param factor is a scalar multiplier for each value in \c update. + * SetParameters is called at the end of this method, to allow the transform + * to perform any required operations on the updated parameters - typically + * a conversion to member variables for use in TransformPoint. */ + virtual void UpdateTransformParameters( const DerivativeType & update, TScalar factor = 1.0 ); + /** This method computes the Jacobian matrix of the transformation. * given point or vector, returning the transformed point or * vector. The rank of the Jacobian will also indicate if the diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkVersorRigid3DTransform.hxx b/Utilities/ITK/Modules/Core/Transform/include/itkVersorRigid3DTransform.hxx index 8bdb9be26a6d8c39441abb5f82dc205b2bd5ea67..bde3a6656a4f4fd2b3da9013d26ed3abacb67e29 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkVersorRigid3DTransform.hxx +++ b/Utilities/ITK/Modules/Core/Transform/include/itkVersorRigid3DTransform.hxx @@ -71,7 +71,7 @@ VersorRigid3DTransform<TScalar> axis[2] = parameters[2]; if( norm > 0 ) { - norm = vcl_sqrt(norm); + norm = std::sqrt(norm); } double epsilon = 1e-10; @@ -106,7 +106,7 @@ VersorRigid3DTransform<TScalar> // // Parameters are ordered as: // -// p[0:2] = right part of the versor (axis times vcl_sin(t/2)) +// p[0:2] = right part of the versor (axis times std::sin(t/2)) // p[3:5} = translation components // @@ -131,6 +131,92 @@ const typename VersorRigid3DTransform<TScalar>::ParametersType return this->m_Parameters; } +template <typename TScalar> +void +VersorRigid3DTransform<TScalar> +::UpdateTransformParameters( const DerivativeType & update, TScalar factor ) +{ + SizeValueType numberOfParameters = this->GetNumberOfParameters(); + + if( update.Size() != numberOfParameters ) + { + itkExceptionMacro("Parameter update size, " << update.Size() << ", must " + " be same as transform parameter size, " + << numberOfParameters << std::endl); + } + + /* Make sure m_Parameters is updated to reflect the current values in + * the transform's other parameter-related variables. This is effective for + * managing the parallel variables used for storing parameter data, + * but inefficient. However for small global transforms, shouldn't be + * too bad. Dense-field transform will want to make sure m_Parameters + * is always updated whenever the transform is changed, so GetParameters + * can be skipped in their implementations of UpdateTransformParameters. + */ + this->GetParameters(); + + VectorType rightPart; + + for ( unsigned int i = 0; i < 3; i++ ) + { + rightPart[i] = this->m_Parameters[i]; + } + + VersorType currentRotation; + currentRotation.Set(rightPart); + + // The gradient indicate the contribution of each one + // of the axis to the direction of highest change in + // the function + VectorType axis; + axis[0] = update[0]; + axis[1] = update[1]; + axis[2] = update[2]; + + // gradientRotation is a rotation along the + // versor direction which maximize the + // variation of the cost function in question. + // An additional Exponentiation produce a jump + // of a particular length along the versor gradient + // direction. + + VersorType gradientRotation; + gradientRotation.Set( axis, factor * axis.GetNorm() ); + + // + // Composing the currentRotation with the gradientRotation + // produces the new Rotation versor + // + VersorType newRotation = currentRotation * gradientRotation; + + ParametersType newParameters( numberOfParameters ); + + newParameters[0] = newRotation.GetX(); + newParameters[1] = newRotation.GetY(); + newParameters[2] = newRotation.GetZ(); + + // Optimize the non-versor parameters as the + // RegularStepGradientDescentOptimizer + for ( unsigned int k = 3; k < numberOfParameters; k++ ) + { + newParameters[k] = this->m_Parameters[k] + update[k] * factor; + } + + /* Call SetParameters with the updated parameters. + * SetParameters in most transforms is used to assign the input params + * to member variables, possibly with some processing. The member variables + * are then used in TransformPoint. + * In the case of dense-field transforms that are updated in blocks from + * a threaded implementation, SetParameters doesn't do this, and is + * optimized to not copy the input parameters when == m_Parameters. + */ + this->SetParameters( newParameters ); + + /* Call Modified, following behavior of other transform when their + * parameters change, e.g. MatrixOffsetTransformBase */ + this->Modified(); +} + template <typename TScalar> void VersorRigid3DTransform<TScalar> diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkVersorTransform.h b/Utilities/ITK/Modules/Core/Transform/include/itkVersorTransform.h index 25ae492bab0a365255deeb2c5a528f97210abc0a..4b7e756d1e0b58d3469db359eb82073a7f94ceb5 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkVersorTransform.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkVersorTransform.h @@ -100,7 +100,7 @@ public: * There are 3 parameters. They represent the components * of the right part of the versor. This can be seen * as the components of the vector parallel to the rotation - * axis and multiplied by vcl_sin( angle / 2 ). */ + * axis and multiplied by std::sin( angle / 2 ). */ void SetParameters(const ParametersType & parameters); /** Get the Transformation Parameters. */ diff --git a/Utilities/ITK/Modules/Core/Transform/include/itkv3Rigid3DTransform.h b/Utilities/ITK/Modules/Core/Transform/include/itkv3Rigid3DTransform.h index 5b2b236f7431b7e78124614ded13f64640e640af..a8d7f809494ce818576b05d86a8787ad7a9aee88 100644 --- a/Utilities/ITK/Modules/Core/Transform/include/itkv3Rigid3DTransform.h +++ b/Utilities/ITK/Modules/Core/Transform/include/itkv3Rigid3DTransform.h @@ -117,7 +117,7 @@ public: virtual InverseTransformBasePointer GetInverseTransform() const { Pointer inv = New(); - return this->GetInverse(inv) ? inv.GetPointer() : NULL; + return this->GetInverse(inv) ? inv.GetPointer() : ITK_NULLPTR; } protected: diff --git a/Utilities/ITK/Modules/Core/Transform/wrapping/itkVersorTransform.wrap b/Utilities/ITK/Modules/Core/Transform/wrapping/itkVersorTransform.wrap index a0bdcb6bd825ada37ae9d70355dc8a76fcab4d6c..06b2d98dabd347e2eac70aea8b8b01013619e1f5 100644 --- a/Utilities/ITK/Modules/Core/Transform/wrapping/itkVersorTransform.wrap +++ b/Utilities/ITK/Modules/Core/Transform/wrapping/itkVersorTransform.wrap @@ -1,6 +1,7 @@ -itk_wrap_class("itk::VersorTransform" POINTER) - itk_wrap_filter_dims(d3 3) - if(d3) +itk_wrap_filter_dims(has_d_3 3) + +if(has_d_3) + itk_wrap_class("itk::VersorTransform" POINTER) itk_wrap_template("${ITKM_D}" "${ITKT_D}") - endif(d3) -itk_end_wrap_class() + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionFunction.h b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionFunction.h index 7d4be7a01cdf7e243a5999ded191498bc7e1aa71..ebb87560c897d75c9578dc3b27378b8041d0e570 100644 --- a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionFunction.h +++ b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionFunction.h @@ -214,7 +214,7 @@ public: * so it's safe to return a null value. */ virtual void * GetGlobalDataPointer() const { - return 0; + return ITK_NULLPTR; } /** Does nothing. No global data is used in this class of equations. */ diff --git a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionImageFilter.hxx index 47770a86858f84bd8b06c954a643030b1a82cbde..5480e8e85793bb23c62c69480459e27aa2424fbd 100644 --- a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkAnisotropicDiffusionImageFilter.hxx @@ -33,7 +33,7 @@ AnisotropicDiffusionImageFilter< TInputImage, TOutputImage > m_ConductanceParameter = 1.0; m_ConductanceScalingParameter = 1.0; m_ConductanceScalingUpdateInterval = 1; - m_TimeStep = 0.5 / vcl_pow( 2.0, static_cast< double >( ImageDimension ) ); + m_TimeStep = 0.5 / std::pow( 2.0, static_cast< double >( ImageDimension ) ); m_FixedAverageGradientMagnitude = 1.0; m_GradientMagnitudeIsFixed = false; } @@ -72,14 +72,14 @@ AnisotropicDiffusionImageFilter< TInputImage, TOutputImage > { minSpacing = 1.0; } - if ( m_TimeStep > ( minSpacing / vcl_pow(2.0, static_cast< double >( ImageDimension ) + 1) ) ) + if ( m_TimeStep > ( minSpacing / std::pow(2.0, static_cast< double >( ImageDimension ) + 1) ) ) { - // f->SetTimeStep(1.0 / vcl_pow(2.0, + // f->SetTimeStep(1.0 / std::pow(2.0, // static_cast<double>(ImageDimension))); itkWarningMacro( << "Anisotropic diffusion unstable time step: " << m_TimeStep << std::endl << "Stable time step for this image must be smaller than " - << minSpacing / vcl_pow( 2.0, static_cast< double >( ImageDimension + 1 ) ) ); + << minSpacing / std::pow( 2.0, static_cast< double >( ImageDimension + 1 ) ) ); } if ( m_GradientMagnitudeIsFixed == false ) diff --git a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureAnisotropicDiffusionImageFilter.h b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureAnisotropicDiffusionImageFilter.h index 701fa4e86cb2892223282e69385aafd42a0ef23f..a2e1040004cfd950033b245f80a19cc5928dee29 100644 --- a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureAnisotropicDiffusionImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureAnisotropicDiffusionImageFilter.h @@ -100,7 +100,7 @@ protected: virtual void InitializeIteration() { Superclass::InitializeIteration(); - if ( this->GetTimeStep() > 0.5 / vcl_pow( 2.0, static_cast< double >( ImageDimension ) ) ) + if ( this->GetTimeStep() > 0.5 / std::pow( 2.0, static_cast< double >( ImageDimension ) ) ) { itkWarningMacro( << "Anisotropic diffusion is using a time step which may introduce instability into the solution."); diff --git a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureNDAnisotropicDiffusionFunction.hxx b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureNDAnisotropicDiffusionFunction.hxx index 20174e3d7b2b5a785c97c454f554c2c103fc36dc..e558fcf6e060f7243889085dc4f9a5434479c426 100644 --- a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureNDAnisotropicDiffusionFunction.hxx +++ b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkCurvatureNDAnisotropicDiffusionFunction.hxx @@ -28,7 +28,8 @@ double CurvatureNDAnisotropicDiffusionFunction< TImage > template< typename TImage > CurvatureNDAnisotropicDiffusionFunction< TImage > -::CurvatureNDAnisotropicDiffusionFunction() +::CurvatureNDAnisotropicDiffusionFunction() : + m_K(0.0) { unsigned int i, j; RadiusType r; @@ -123,8 +124,8 @@ CurvatureNDAnisotropicDiffusionFunction< TImage > grad_mag_sq_d += 0.25f * ( dx[j] + dx_dim ) * ( dx[j] + dx_dim ); } } - grad_mag = vcl_sqrt(m_MIN_NORM + grad_mag_sq); - grad_mag_d = vcl_sqrt(m_MIN_NORM + grad_mag_sq_d); + grad_mag = std::sqrt(m_MIN_NORM + grad_mag_sq); + grad_mag_d = std::sqrt(m_MIN_NORM + grad_mag_sq_d); // Conductance Terms if ( m_K == 0.0 ) @@ -134,8 +135,8 @@ CurvatureNDAnisotropicDiffusionFunction< TImage > } else { - Cx = vcl_exp(grad_mag_sq / m_K); - Cxd = vcl_exp(grad_mag_sq_d / m_K); + Cx = std::exp(grad_mag_sq / m_K); + Cxd = std::exp(grad_mag_sq_d / m_K); } // First order normalized finite-difference conductance products dx_forward_Cn = ( dx_forward[i] / grad_mag ) * Cx; @@ -164,7 +165,7 @@ CurvatureNDAnisotropicDiffusionFunction< TImage > + vnl_math_sqr( vnl_math_min(dx_forward[i], 0.0) ); } } - return static_cast< PixelType >( vcl_sqrt(propagation_gradient) * speed ); + return static_cast< PixelType >( std::sqrt(propagation_gradient) * speed ); } } // end namespace itk diff --git a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkGradientNDAnisotropicDiffusionFunction.hxx b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkGradientNDAnisotropicDiffusionFunction.hxx index 9117446052ae262f60675e2595647aec7e8cf140..85de432e5ba0437a89a1e3a1574710edbe2253ff 100644 --- a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkGradientNDAnisotropicDiffusionFunction.hxx +++ b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkGradientNDAnisotropicDiffusionFunction.hxx @@ -29,7 +29,8 @@ double GradientNDAnisotropicDiffusionFunction< TImage > template< typename TImage > GradientNDAnisotropicDiffusionFunction< TImage > -::GradientNDAnisotropicDiffusionFunction() +::GradientNDAnisotropicDiffusionFunction() : + m_K(0.0) { unsigned int i, j; RadiusType r; @@ -144,8 +145,8 @@ GradientNDAnisotropicDiffusionFunction< TImage > } else { - Cx = vcl_exp( ( vnl_math_sqr(dx_forward) + accum ) / m_K ); - Cxd = vcl_exp( ( vnl_math_sqr(dx_backward) + accum_d ) / m_K ); + Cx = std::exp( ( vnl_math_sqr(dx_forward) + accum ) / m_K ); + Cxd = std::exp( ( vnl_math_sqr(dx_backward) + accum_d ) / m_K ); } // Conductance modified first order derivatives. diff --git a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorCurvatureAnisotropicDiffusionImageFilter.h b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorCurvatureAnisotropicDiffusionImageFilter.h index 6608fb77f4e72d4cc9f171d1f272872e83f3e93f..bb2542a26b531a1d9065c23f60bb36c0dc331928 100644 --- a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorCurvatureAnisotropicDiffusionImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorCurvatureAnisotropicDiffusionImageFilter.h @@ -107,7 +107,7 @@ protected: virtual void InitializeIteration() { Superclass::InitializeIteration(); - if ( this->GetTimeStep() > 0.5 / vcl_pow( 2.0, static_cast< double >( ImageDimension ) ) ) + if ( this->GetTimeStep() > 0.5 / std::pow( 2.0, static_cast< double >( ImageDimension ) ) ) { itkWarningMacro( << "Anisotropic diffusion has attempted to use a time step which may introduce instability into the solution."); diff --git a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorCurvatureNDAnisotropicDiffusionFunction.hxx b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorCurvatureNDAnisotropicDiffusionFunction.hxx index 1cfcea29615334c0ed01341f8fa0b96aa83981df..c71b9ba8534ca7a9ff88e88fb5cb3939a0a6fe6a 100644 --- a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorCurvatureNDAnisotropicDiffusionFunction.hxx +++ b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorCurvatureNDAnisotropicDiffusionFunction.hxx @@ -143,8 +143,8 @@ VectorCurvatureNDAnisotropicDiffusionFunction< TImage > } } - grad_mag[k] = vcl_sqrt(m_MIN_NORM + grad_mag_sq[k]); - grad_mag_d[k] = vcl_sqrt(m_MIN_NORM + grad_mag_sq_d[k]); + grad_mag[k] = std::sqrt(m_MIN_NORM + grad_mag_sq[k]); + grad_mag_d[k] = std::sqrt(m_MIN_NORM + grad_mag_sq_d[k]); // this grad mag should depend only on the current k for ( i = 0; i < ImageDimension; i++ ) { @@ -174,8 +174,8 @@ VectorCurvatureNDAnisotropicDiffusionFunction< TImage > } else { - Cx[i] = vcl_exp(grad_mag_sq_tmp / m_K); - Cxd[i] = vcl_exp(grad_mag_sq_d_tmp / m_K); + Cx[i] = std::exp(grad_mag_sq_tmp / m_K); + Cxd[i] = std::exp(grad_mag_sq_d_tmp / m_K); } } @@ -213,7 +213,7 @@ VectorCurvatureNDAnisotropicDiffusionFunction< TImage > } } - ans[k] = vcl_sqrt(propagation_gradient) * speed; + ans[k] = std::sqrt(propagation_gradient) * speed; } return ans; diff --git a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorGradientNDAnisotropicDiffusionFunction.hxx b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorGradientNDAnisotropicDiffusionFunction.hxx index d79807c129cc93bfc4770965291ca90f18c19a51..bdf49ee4b1b5413401225b013559727823a8df24 100644 --- a/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorGradientNDAnisotropicDiffusionFunction.hxx +++ b/Utilities/ITK/Modules/Filtering/AnisotropicSmoothing/include/itkVectorGradientNDAnisotropicDiffusionFunction.hxx @@ -147,8 +147,8 @@ VectorGradientNDAnisotropicDiffusionFunction< TImage > } else { - Cx[i] = vcl_exp(GradMag / m_K); - Cxd[i] = vcl_exp(GradMag_d / m_K); + Cx[i] = std::exp(GradMag / m_K); + Cxd[i] = std::exp(GradMag_d / m_K); } } diff --git a/Utilities/ITK/Modules/Filtering/AntiAlias/include/itkAntiAliasBinaryImageFilter.hxx b/Utilities/ITK/Modules/Filtering/AntiAlias/include/itkAntiAliasBinaryImageFilter.hxx index 5e54b7a13d336951a7e36654a4acf316b28ce197..26ee95c5b55f2f101c0205d542d84503e64bb596 100644 --- a/Utilities/ITK/Modules/Filtering/AntiAlias/include/itkAntiAliasBinaryImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/AntiAlias/include/itkAntiAliasBinaryImageFilter.hxx @@ -59,7 +59,7 @@ template< typename TInputImage, typename TOutputImage > AntiAliasBinaryImageFilter< TInputImage, TOutputImage > ::AntiAliasBinaryImageFilter() { - m_InputImage = NULL; + m_InputImage = ITK_NULLPTR; m_CurvatureFunction = CurvatureFunctionType::New(); this->SetDifferenceFunction(m_CurvatureFunction); diff --git a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkCompositeValleyFunction.h b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkCompositeValleyFunction.h index 1f20f68abf147d4ee69c83ce1d5eac41f2173a6a..0198506346bb73a438a358cebfbc4cdaeefa2bad 100644 --- a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkCompositeValleyFunction.h +++ b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkCompositeValleyFunction.h @@ -136,7 +136,7 @@ public: } /** Evalaute the function at point x. */ - inline MeasureType Evaluate(MeasureType x) + virtual inline MeasureType Evaluate(MeasureType x) ITK_OVERRIDE { MeasureType res = 1; diff --git a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.h b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.h index c9b0574811e10e61ac9b1aa19a26f9697017fb96..dc8680c15cbdb5652b07adb298a956e73d3dba07 100644 --- a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.h +++ b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.h @@ -124,7 +124,7 @@ public: protected: MRASlabIdentifier(); virtual ~MRASlabIdentifier() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: MRASlabIdentifier(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.hxx b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.hxx index 8d5afaf569367e270d74bae71b60ae82d6e6217b..60900530c7f290275a4212ab8cdae344402137d1 100644 --- a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.hxx +++ b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRASlabIdentifier.hxx @@ -31,7 +31,7 @@ template< typename TInputImage > MRASlabIdentifier< TInputImage > ::MRASlabIdentifier() { - m_Image = 0; + m_Image = ITK_NULLPTR; m_NumberOfSamples = 10; m_BackgroundMinimumThreshold = NumericTraits< ImagePixelType >::min(); m_Tolerance = 0.0; diff --git a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRIBiasFieldCorrectionFilter.h b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRIBiasFieldCorrectionFilter.h index d4551e496fb6c237a5945b905470f68aaf24df5f..000276231b16a4ae17818090965e9ecde083e28a 100644 --- a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRIBiasFieldCorrectionFilter.h +++ b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRIBiasFieldCorrectionFilter.h @@ -122,12 +122,12 @@ public: /** Gets the total energy value of an image or a slice using the * given parameters. */ - MeasureType GetValue(const ParametersType & parameters) const; + virtual MeasureType GetValue(const ParametersType & parameters) const ITK_OVERRIDE; /** Dummy implementation to confirm to the SingleValuedCostFunction * interfaces. It is pure virtual in the superclass */ void GetDerivative( const ParametersType & itkNotUsed(parameters), - DerivativeType & itkNotUsed(derivative) ) const + DerivativeType & itkNotUsed(derivative) ) const ITK_OVERRIDE {} /** Set Mean and Sigma for the normal distributions @@ -137,7 +137,7 @@ public: void InitializeDistributions(Array< double > classMeans, Array< double > classSigmas); - unsigned int GetNumberOfParameters(void) const; + virtual unsigned int GetNumberOfParameters(void) const ITK_OVERRIDE; protected: /** Constructor: */ @@ -470,13 +470,13 @@ protected: bool CheckMaskImage(ImageMaskType *mask); protected: - /** Converts image data from source to target applying vcl_log(pixel + 1) + /** Converts image data from source to target applying std::log(pixel + 1) * to all pixels. If the source pixel has negative value, it sets * the value of the corresponding pixel in the targe image as zero. */ void Log1PImage(InternalImageType *source, InternalImageType *target); - /** Converts image data from source to target applying vcl_exp(pixel) - 1 + /** Converts image data from source to target applying std::exp(pixel) - 1 * to all pixels. */ void ExpImage(InternalImageType *source, InternalImageType *target); diff --git a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRIBiasFieldCorrectionFilter.hxx b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRIBiasFieldCorrectionFilter.hxx index 39d4845fbccfbd441096e8efddb9fcb8e4d3a314..f6e6f9f88e08250de0f7d749ccd15e3ec3a2055c 100644 --- a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRIBiasFieldCorrectionFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkMRIBiasFieldCorrectionFilter.hxx @@ -28,13 +28,13 @@ template< typename TImage, typename TImageMask, typename TBiasField > MRIBiasEnergyFunction< TImage, TImageMask, TBiasField > ::MRIBiasEnergyFunction() { - m_BiasField = 0; + m_BiasField = ITK_NULLPTR; for ( unsigned int i = 0; i < SpaceDimension; i++ ) { m_SamplingFactor[i] = 1; } - m_Mask = NULL; - m_Image = NULL; + m_Mask = ITK_NULLPTR; + m_Image = ITK_NULLPTR; } template< typename TImage, typename TImageMask, typename TBiasField > @@ -52,7 +52,7 @@ MRIBiasEnergyFunction< TImage, TImageMask, TBiasField > ::~MRIBiasEnergyFunction() { delete m_InternalEnergyFunction; - m_InternalEnergyFunction = 0; + m_InternalEnergyFunction = ITK_NULLPTR; } template< typename TImage, typename TImageMask, typename TBiasField > @@ -60,7 +60,7 @@ unsigned int MRIBiasEnergyFunction< TImage, TImageMask, TBiasField > ::GetNumberOfParameters(void) const { - if ( m_BiasField == 0 ) + if ( m_BiasField == ITK_NULLPTR ) { return 0; } @@ -82,7 +82,7 @@ MRIBiasEnergyFunction< TImage, TImageMask, TBiasField > itkExceptionMacro(<< "EnergyFunction is null"); } - if ( m_BiasField == 0 ) + if ( m_BiasField == ITK_NULLPTR ) { itkExceptionMacro(<< "BiasField is null"); } @@ -211,8 +211,8 @@ template< typename TInputImage, typename TOutputImage, typename TMaskImage > MRIBiasFieldCorrectionFilter< TInputImage, TOutputImage, TMaskImage > ::MRIBiasFieldCorrectionFilter() { - m_InputMask = 0; - m_OutputMask = 0; + m_InputMask = ITK_NULLPTR; + m_OutputMask = ITK_NULLPTR; m_BiasMultiplicative = true; m_BiasFieldDegree = 3; @@ -220,12 +220,12 @@ MRIBiasFieldCorrectionFilter< TInputImage, TOutputImage, TMaskImage > m_VolumeCorrectionMaximumIteration = 2000; m_InterSliceCorrectionMaximumIteration = 4000; m_OptimizerGrowthFactor = 1.05; - m_OptimizerShrinkFactor = vcl_pow(m_OptimizerGrowthFactor, -0.25); + m_OptimizerShrinkFactor = std::pow(m_OptimizerGrowthFactor, -0.25); - m_EnergyFunction = 0; + m_EnergyFunction = ITK_NULLPTR; m_NormalVariateGenerator = NormalVariateGeneratorType::New(); //m_NormalVariateGenerator->Initialize(3024); - m_NormalVariateGenerator->Initialize( time(NULL) ); + m_NormalVariateGenerator->Initialize( time(ITK_NULLPTR) ); if ( ImageDimension == 3 ) { @@ -578,12 +578,12 @@ throw ( ExceptionObject ) const unsigned int size = m_TissueClassMeans.Size(); for ( unsigned int i = 0; i < size; i++ ) { - m_TissueClassSigmas[i] = vcl_log( 1.0 + m_TissueClassSigmas[i] + m_TissueClassSigmas[i] = std::log( 1.0 + m_TissueClassSigmas[i] / ( m_TissueClassMeans[i] + 1.0 ) ); - m_TissueClassMeans[i] = vcl_log(m_TissueClassMeans[i] + 1.0); + m_TissueClassMeans[i] = std::log(m_TissueClassMeans[i] + 1.0); } - m_OptimizerInitialRadius = vcl_log(1.0 + m_OptimizerInitialRadius); + m_OptimizerInitialRadius = std::log(1.0 + m_OptimizerInitialRadius); this->Log1PImage( m_InternalInput.GetPointer(), m_InternalInput.GetPointer() ); @@ -932,12 +932,12 @@ MRIBiasFieldCorrectionFilter< TInputImage, TOutputImage, TMaskImage > const unsigned int size = m_TissueClassMeans.Size(); for ( unsigned int i = 0; i < size; i++ ) { - m_TissueClassMeans[i] = vcl_exp(m_TissueClassMeans[i]) - 1.0; - m_TissueClassSigmas[i] = vcl_exp(m_TissueClassSigmas[i]) + m_TissueClassMeans[i] = std::exp(m_TissueClassMeans[i]) - 1.0; + m_TissueClassSigmas[i] = std::exp(m_TissueClassSigmas[i]) * ( 1.0 + m_TissueClassMeans[i] ) - m_TissueClassMeans[i]; } - m_OptimizerInitialRadius = vcl_exp(m_OptimizerInitialRadius) - 1.0; + m_OptimizerInitialRadius = std::exp(m_OptimizerInitialRadius) - 1.0; } if ( m_GeneratingOutput ) @@ -1034,7 +1034,7 @@ MRIBiasFieldCorrectionFilter< TInputImage, TOutputImage, TMaskImage > } else { - t_iter.Set( vcl_log(pixel + 1) ); + t_iter.Set( std::log(pixel + 1) ); } ++s_iter; @@ -1063,7 +1063,7 @@ MRIBiasFieldCorrectionFilter< TInputImage, TOutputImage, TMaskImage > { temp = s_iter.Get(); //t_iter.Set( m_EnergyFunction->GetEnergy0(temp)); - temp = vcl_exp(temp) - 1; + temp = std::exp(temp) - 1; t_iter.Set( (InternalImagePixelType)temp ); ++s_iter; diff --git a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkN4BiasFieldCorrectionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkN4BiasFieldCorrectionImageFilter.hxx index e8ff59366e2b0b0c29eb8d9cc00c08c8b41e6ea7..add2c38fec2ff6982966104742dd193bb8e2bf41 100644 --- a/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkN4BiasFieldCorrectionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/BiasCorrection/include/itkN4BiasFieldCorrectionImageFilter.hxx @@ -52,7 +52,7 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> { this->SetNumberOfRequiredInputs( 1 ); - this->m_LogBiasFieldControlPointLattice = NULL; + this->m_LogBiasFieldControlPointLattice = ITK_NULLPTR; this->m_NumberOfFittingLevels.Fill( 1 ); this->m_NumberOfControlPoints.Fill( 4 ); @@ -105,7 +105,7 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> { if( It.Get() > NumericTraits<typename InputImageType::PixelType>::Zero ) { - It.Set( vcl_log( static_cast< RealType >( It.Get() ) ) ); + It.Set( std::log( static_cast< RealType >( It.Get() ) ) ); } } } @@ -124,9 +124,7 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> RealImagePointer logBiasField = RealImageType::New(); logBiasField->CopyInformation( inputImage ); logBiasField->SetRegions( inputImage->GetLargestPossibleRegion() ); - logBiasField->Allocate(); - logBiasField->FillBuffer( 0.0 ); - + logBiasField->Allocate(true); // initialize buffer to zero // Iterate until convergence or iterative exhaustion. unsigned int maximumNumberOfLevels = 1; @@ -305,10 +303,10 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> // histogram to a power of 2. RealType exponent = - vcl_ceil( vcl_log( static_cast<RealType>( this->m_NumberOfHistogramBins ) ) / - vcl_log( 2.0 ) ) + 1; + std::ceil( std::log( static_cast<RealType>( this->m_NumberOfHistogramBins ) ) / + std::log( 2.0 ) ) + 1; unsigned int paddedHistogramSize = static_cast<unsigned int>( - vcl_pow( static_cast<RealType>( 2.0 ), exponent ) + 0.5 ); + std::pow( static_cast<RealType>( 2.0 ), exponent ) + 0.5 ); unsigned int histogramOffset = static_cast<unsigned int>( 0.5 * ( paddedHistogramSize - this->m_NumberOfHistogramBins ) ); @@ -331,8 +329,8 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> // Create the Gaussian filter. RealType scaledFWHM = this->m_BiasFieldFullWidthAtHalfMaximum / histogramSlope; - RealType expFactor = 4.0 * vcl_log( 2.0 ) / vnl_math_sqr( scaledFWHM ); - RealType scaleFactor = 2.0 * vcl_sqrt( vcl_log( 2.0 ) + RealType expFactor = 4.0 * std::log( 2.0 ) / vnl_math_sqr( scaledFWHM ); + RealType scaleFactor = 2.0 * std::sqrt( std::log( 2.0 ) / vnl_math::pi ) / scaledFWHM; vnl_vector< vcl_complex<RealType> > F( paddedHistogramSize, @@ -344,11 +342,11 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> for( unsigned int n = 1; n <= halfSize; n++ ) { F[n] = F[paddedHistogramSize - n] = vcl_complex<RealType>( scaleFactor * - vcl_exp( -vnl_math_sqr( static_cast<RealType>( n ) ) * expFactor ), 0.0 ); + std::exp( -vnl_math_sqr( static_cast<RealType>( n ) ) * expFactor ), 0.0 ); } if( paddedHistogramSize % 2 == 0 ) { - F[halfSize] = vcl_complex<RealType>( scaleFactor * vcl_exp( 0.25 * + F[halfSize] = vcl_complex<RealType>( scaleFactor * std::exp( 0.25 * -vnl_math_sqr( static_cast<RealType>( paddedHistogramSize ) ) * expFactor ), 0.0 ); } @@ -434,8 +432,7 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> RealImagePointer sharpenedImage = RealImageType::New(); sharpenedImage->CopyInformation( inputImage ); sharpenedImage->SetRegions( inputImage->GetLargestPossibleRegion() ); - sharpenedImage->Allocate(); - sharpenedImage->FillBuffer( 0.0 ); + sharpenedImage->Allocate(true); // initialize buffer to zero ImageRegionIterator<RealImageType> ItC( sharpenedImage, sharpenedImage->GetLargestPossibleRegion() ); @@ -661,7 +658,7 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> && ( !confidenceImage || confidenceImage->GetPixel( It.GetIndex() ) > 0.0 ) ) { - RealType pixel = vcl_exp( It.Get() ); + RealType pixel = std::exp( It.Get() ); N += 1.0; if( N > 1.0 ) @@ -671,7 +668,7 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> mu = mu * ( 1.0 - 1.0 / N ) + pixel / N; } } - sigma = vcl_sqrt( sigma / ( N - 1.0 ) ); + sigma = std::sqrt( sigma / ( N - 1.0 ) ); return ( sigma / mu ); } @@ -704,15 +701,7 @@ N4BiasFieldCorrectionImageFilter<TInputImage, TMaskImage, TOutputImage> os << indent << "CurrentLevel: " << this->m_CurrentLevel << std::endl; os << indent << "ElapsedIterations: " << this->m_ElapsedIterations << std::endl; - if ( this->m_LogBiasFieldControlPointLattice ) - { - os << indent << "LogBiasFieldControlPointLattice:" << std::endl; - this->m_LogBiasFieldControlPointLattice->Print( os, indent.GetNextIndent() ); - } - else - { - os << indent << "LogBiasFieldControlPointLattice: " << "(null)" << std::endl; - } + itkPrintSelfObjectMacro( LogBiasFieldControlPointLattice ); } } // end namespace itk diff --git a/Utilities/ITK/Modules/Filtering/BiasCorrection/src/itkCacheableScalarFunction.cxx b/Utilities/ITK/Modules/Filtering/BiasCorrection/src/itkCacheableScalarFunction.cxx index 76105b51532e406bffa80b72ff42c12ee23259c1..9cb503a112cbf24a348a022ad09e747520771f95 100644 --- a/Utilities/ITK/Modules/Filtering/BiasCorrection/src/itkCacheableScalarFunction.cxx +++ b/Utilities/ITK/Modules/Filtering/BiasCorrection/src/itkCacheableScalarFunction.cxx @@ -20,9 +20,14 @@ namespace itk { CacheableScalarFunction -::CacheableScalarFunction() +::CacheableScalarFunction() : + m_NumberOfSamples(0), + m_CacheTable(0), + m_CacheUpperBound(0.0), + m_CacheLowerBound(0.0), + m_TableInc(0.0), + m_CacheAvailable(false) { - m_CacheAvailable = false; } void diff --git a/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkBinaryClosingByReconstructionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkBinaryClosingByReconstructionImageFilter.hxx index 45d655de3802258755c212fc2518e85485834baa..30abb67b7be0b84d9fa97e119856bf2416e9208f 100644 --- a/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkBinaryClosingByReconstructionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkBinaryClosingByReconstructionImageFilter.hxx @@ -26,7 +26,6 @@ #include "itkConstantPadImageFilter.h" #include "itkConstNeighborhoodIterator.h" #include "itkNeighborhoodIterator.h" -#include "itkProgressReporter.h" namespace itk { diff --git a/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkBinaryThinningImageFilter.hxx b/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkBinaryThinningImageFilter.hxx index eeb81bb7564aefcea6f2ea912694c6f5b39110ce..c0c283bcee79ff904f1b2b2681e5635335220267 100644 --- a/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkBinaryThinningImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkBinaryThinningImageFilter.hxx @@ -201,16 +201,16 @@ BinaryThinningImageFilter< TInputImage, TOutputImage > // First find the total number of transitions, and then // divide by 2. const PixelType transitions = ( - vcl_abs( static_cast< int >( p3 + std::abs( static_cast< int >( p3 - p2 ) ) - + vcl_abs( static_cast< int >( p4 + + std::abs( static_cast< int >( p4 - p3 ) ) - + vcl_abs( static_cast< int >( p5 - p4 ) ) + vcl_abs( static_cast< int >( p6 - p5 ) ) - + vcl_abs( static_cast< int >( p7 + + std::abs( static_cast< int >( p5 - p4 ) ) + std::abs( static_cast< int >( p6 - p5 ) ) + + std::abs( static_cast< int >( p7 - p6 ) ) - + vcl_abs( static_cast< int >( p8 + + std::abs( static_cast< int >( p8 - p7 ) ) - + vcl_abs( static_cast< int >( p9 - p8 ) ) + vcl_abs( static_cast< int >( p2 - p9 ) ) + + std::abs( static_cast< int >( p9 - p8 ) ) + std::abs( static_cast< int >( p2 - p9 ) ) ) / 2; if ( transitions == 1 ) diff --git a/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkObjectMorphologyImageFilter.hxx b/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkObjectMorphologyImageFilter.hxx index 9e116f0f30699a892296a1c8cdc04c74858a6691..8fbff7a6c949c5558834dded27fa9f16b4f98431 100644 --- a/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkObjectMorphologyImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/BinaryMathematicalMorphology/include/itkObjectMorphologyImageFilter.hxx @@ -189,7 +189,7 @@ ObjectMorphologyImageFilter< TInputImage, TOutputImage, TKernel > ::IsObjectPixelOnBoundary(const InputNeighborhoodIteratorType & iNIter) { static const unsigned int s = - (unsigned int)vcl_pow( (double)3.0, + (unsigned int)std::pow( (double)3.0, (double)( ImageDimension ) ); PixelType tf; diff --git a/Utilities/ITK/Modules/Filtering/Colormap/include/itkColormapFunction.h b/Utilities/ITK/Modules/Filtering/Colormap/include/itkColormapFunction.h index 5e4da6883b0cba9ae4aceef8cc92931e81540e58..d10ffe58cc4325087f48b665426c8cfbd1dd4875 100644 --- a/Utilities/ITK/Modules/Filtering/Colormap/include/itkColormapFunction.h +++ b/Utilities/ITK/Modules/Filtering/Colormap/include/itkColormapFunction.h @@ -123,7 +123,7 @@ protected: return rescaled; } - void PrintSelf(std::ostream & os, Indent indent) const + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE { Superclass::PrintSelf(os, indent); diff --git a/Utilities/ITK/Modules/Filtering/Convolution/include/itkFFTConvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Convolution/include/itkFFTConvolutionImageFilter.hxx index 0377242025562f711f908a5d38af233e124fdedc..bb9f3366be1c0b0b689d1553a7605483531a7603 100644 --- a/Utilities/ITK/Modules/Filtering/Convolution/include/itkFFTConvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Convolution/include/itkFFTConvolutionImageFilter.hxx @@ -77,8 +77,8 @@ FFTConvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPre const KernelImageType* kernelImage = this->GetKernelImage(); - InternalComplexImagePointerType input = NULL; - InternalComplexImagePointerType kernel = NULL; + InternalComplexImagePointerType input = ITK_NULLPTR; + InternalComplexImagePointerType kernel = ITK_NULLPTR; this->PrepareInputs( localInput, kernelImage, input, kernel, progress, 0.7f ); typedef MultiplyImageFilter< InternalComplexImageType, @@ -91,8 +91,8 @@ FFTConvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPre progress->RegisterInternalFilter( multiplyFilter, 0.1 ); // Free up the memory for the prepared inputs - input = NULL; - kernel = NULL; + input = ITK_NULLPTR; + kernel = ITK_NULLPTR; this->ProduceOutput( multiplyFilter->GetOutput(), progress, 0.2 ); } @@ -193,8 +193,8 @@ FFTConvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPre transformedInput = imageFFTFilter->GetOutput(); transformedInput->DisconnectPipeline(); - imageFFTFilter->SetInput( NULL ); - imageFFTFilter = NULL; + imageFFTFilter->SetInput( ITK_NULLPTR ); + imageFFTFilter = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > @@ -214,7 +214,7 @@ FFTConvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPre kernelUpperBound[i] = padSize[i] - kernelSize[i]; } - InternalImagePointerType paddedKernelImage = NULL; + InternalImagePointerType paddedKernelImage = ITK_NULLPTR; float paddingWeight = 0.2f; if ( this->GetNormalize() ) @@ -331,7 +331,6 @@ FFTConvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPre typedef ExtractImageFilter< InternalImageType, OutputImageType > ExtractFilterType; typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New(); - extractFilter->SetDirectionCollapseToIdentity(); extractFilter->InPlaceOn(); extractFilter->GraftOutput( this->GetOutput() ); @@ -353,9 +352,16 @@ FFTConvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPre progress->RegisterInternalFilter( extractFilter, progressWeight ); extractFilter->Update(); - // Graft the output of the crop filter back onto this - // filter's output. - this->GraftOutput( extractFilter->GetOutput() ); + OutputImageType *extractedImage = extractFilter->GetOutput(); + OutputImageType *output = this->GetOutput(); + + // Only manually copy the buffer via the pixel container. + // The output meta-data of the extract filter is not correct and + // different that the GenerateOutputInformation method. So just copy + // the buffer. + output->SetBufferedRegion(extractedImage->GetBufferedRegion()); + output->SetPixelContainer(extractedImage->GetPixelContainer()); + } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > diff --git a/Utilities/ITK/Modules/Filtering/Convolution/include/itkMaskedFFTNormalizedCorrelationImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Convolution/include/itkMaskedFFTNormalizedCorrelationImageFilter.hxx index 7e9a5382105de16b30dd44b244aabdc1270916f7..6f8cc4ccd5e16cfa2019ad8411bd26b5f298183f 100644 --- a/Utilities/ITK/Modules/Filtering/Convolution/include/itkMaskedFFTNormalizedCorrelationImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Convolution/include/itkMaskedFFTNormalizedCorrelationImageFilter.hxx @@ -119,14 +119,14 @@ void MaskedFFTNormalizedCorrelationImageFilter<TInputImage, TOutputImage, TMaskI InputImagePointer movingImage = InputImageType::New(); movingImage->Graft( this->GetMovingImage() ); - MaskImagePointer fixedMask = NULL; + MaskImagePointer fixedMask = ITK_NULLPTR; if( this->GetFixedImageMask() ) { fixedMask = MaskImageType::New(); fixedMask->Graft( this->GetFixedImageMask() ); } - MaskImagePointer movingMask = NULL; + MaskImagePointer movingMask = ITK_NULLPTR; if( this->GetMovingImageMask() ) { movingMask = MaskImageType::New(); @@ -146,9 +146,9 @@ void MaskedFFTNormalizedCorrelationImageFilter<TInputImage, TOutputImage, TMaskI movingImage = this->PreProcessImage( movingImage,movingMask ); InputImagePointer rotatedMovingImage = this->RotateImage<InputImageType>( movingImage ); - movingImage = NULL; + movingImage = ITK_NULLPTR; MaskImagePointer rotatedMovingMask = this->RotateImage<MaskImageType>( movingMask); - movingMask = NULL; + movingMask = ITK_NULLPTR; // The combinedImageSize is the size resulting from the correlation of the two images. RealSizeType combinedImageSize; @@ -168,10 +168,10 @@ void MaskedFFTNormalizedCorrelationImageFilter<TInputImage, TOutputImage, TMaskI // separation. FFTImagePointer fixedFFT = this->CalculateForwardFFT<InputImageType,FFTImageType>( fixedImage, FFTImageSize ); FFTImagePointer fixedMaskFFT = this->CalculateForwardFFT<MaskImageType,FFTImageType>( fixedMask, FFTImageSize ); - fixedMask = NULL; + fixedMask = ITK_NULLPTR; FFTImagePointer rotatedMovingFFT = this->CalculateForwardFFT<InputImageType,FFTImageType>( rotatedMovingImage, FFTImageSize ); FFTImagePointer rotatedMovingMaskFFT = this->CalculateForwardFFT<MaskImageType,FFTImageType>( rotatedMovingMask, FFTImageSize ); - rotatedMovingMask = NULL; + rotatedMovingMask = ITK_NULLPTR; // Only 6 IFFTs are needed. // Compute and save some of these rather than computing them multiple times. @@ -188,31 +188,31 @@ void MaskedFFTNormalizedCorrelationImageFilter<TInputImage, TOutputImage, TMaskI RealImagePointer numerator = this->ElementSubtraction<RealImageType>( this->CalculateInverseFFT<FFTImageType,RealImageType>(this->ElementProduct<FFTImageType,FFTImageType>(fixedFFT,rotatedMovingFFT),combinedImageSize), this->ElementQuotient<RealImageType>(this->ElementProduct<RealImageType,RealImageType>(fixedCumulativeSumImage,rotatedMovingCumulativeSumImage),numberOfOverlapPixels)); - fixedFFT = NULL; // No longer needed - rotatedMovingFFT = NULL; // No longer needed + fixedFFT = ITK_NULLPTR; // No longer needed + rotatedMovingFFT = ITK_NULLPTR; // No longer needed // Calculate the fixed part of the masked FFT NCC denominator. FFTImagePointer fixedSquaredFFT = this->CalculateForwardFFT<RealImageType,FFTImageType>( this->ElementProduct<InputImageType,RealImageType>(fixedImage,fixedImage), FFTImageSize ); - fixedImage = NULL; // No longer needed + fixedImage = ITK_NULLPTR; // No longer needed RealImagePointer fixedDenom = this->ElementSubtraction<RealImageType>( this->CalculateInverseFFT<FFTImageType,RealImageType>(this->ElementProduct<FFTImageType,FFTImageType>(fixedSquaredFFT,rotatedMovingMaskFFT),combinedImageSize), this->ElementQuotient<RealImageType>(this->ElementProduct<RealImageType,RealImageType>(fixedCumulativeSumImage,fixedCumulativeSumImage),numberOfOverlapPixels)); - fixedSquaredFFT = NULL; // No longer needed - rotatedMovingMaskFFT = NULL; // No longer needed - fixedCumulativeSumImage = NULL; // No longer needed + fixedSquaredFFT = ITK_NULLPTR; // No longer needed + rotatedMovingMaskFFT = ITK_NULLPTR; // No longer needed + fixedCumulativeSumImage = ITK_NULLPTR; // No longer needed // Ensure that the result is positive. fixedDenom = this->ElementPositive<RealImageType>(fixedDenom); // Calculate the moving part of the masked FFT NCC denominator. FFTImagePointer rotatedMovingSquaredFFT = this->CalculateForwardFFT<RealImageType,FFTImageType>( this->ElementProduct<InputImageType,RealImageType>(rotatedMovingImage,rotatedMovingImage), FFTImageSize ); - rotatedMovingImage = NULL; // No longer needed + rotatedMovingImage = ITK_NULLPTR; // No longer needed RealImagePointer rotatedMovingDenom = this->ElementSubtraction<RealImageType>( this->CalculateInverseFFT<FFTImageType,RealImageType>(this->ElementProduct<FFTImageType,FFTImageType>(fixedMaskFFT,rotatedMovingSquaredFFT),combinedImageSize), this->ElementQuotient<RealImageType>(this->ElementProduct<RealImageType,RealImageType>(rotatedMovingCumulativeSumImage,rotatedMovingCumulativeSumImage),numberOfOverlapPixels)); - rotatedMovingSquaredFFT = NULL; // No longer needed - fixedMaskFFT = NULL; // No longer needed - rotatedMovingCumulativeSumImage = NULL; // No longer needed + rotatedMovingSquaredFFT = ITK_NULLPTR; // No longer needed + fixedMaskFFT = ITK_NULLPTR; // No longer needed + rotatedMovingCumulativeSumImage = ITK_NULLPTR; // No longer needed // Ensure that the result is positive. rotatedMovingDenom = this->ElementPositive<RealImageType>(rotatedMovingDenom); @@ -221,14 +221,14 @@ void MaskedFFTNormalizedCorrelationImageFilter<TInputImage, TOutputImage, TMaskI sqrtFilter->SetInput( this->ElementProduct<RealImageType,RealImageType>(fixedDenom,rotatedMovingDenom) ); sqrtFilter->Update(); RealImagePointer denominator = sqrtFilter->GetOutput(); - fixedDenom = NULL; // No longer needed - rotatedMovingDenom = NULL; // No longer needed + fixedDenom = ITK_NULLPTR; // No longer needed + rotatedMovingDenom = ITK_NULLPTR; // No longer needed // Determine a tolerance on the precision of the denominator values. const double precisionTolerance = CalculatePrecisionTolerance<RealImageType>( denominator ); RealImagePointer NCC = this->ElementQuotient<RealImageType>(numerator,denominator); - numerator = NULL; // No longer needed + numerator = ITK_NULLPTR; // No longer needed // Given the numberOfOverlapPixels, we can check that the m_RequiredNumberOfOverlappingPixels is not set higher than // the actual maximum overlap voxels. If it is, we set m_RequiredNumberOfOverlappingPixels to be this maximum. @@ -236,7 +236,7 @@ void MaskedFFTNormalizedCorrelationImageFilter<TInputImage, TOutputImage, TMaskI typename CalculatorType::Pointer calculator = CalculatorType::New(); calculator->SetImage(numberOfOverlapPixels); calculator->ComputeMaximum(); - m_MaximumNumberOfOverlappingPixels = calculator->GetMaximum(); + m_MaximumNumberOfOverlappingPixels = static_cast< SizeValueType >( calculator->GetMaximum() ); if( m_RequiredNumberOfOverlappingPixels > m_MaximumNumberOfOverlappingPixels ) { m_RequiredNumberOfOverlappingPixels = (SizeValueType)m_MaximumNumberOfOverlappingPixels; @@ -562,11 +562,11 @@ MaskedFFTNormalizedCorrelationImageFilter<TInputImage, TOutputImage, TMaskImage> double precisionTolerance=0.0F; if( typeid(inputImage->GetPixel(index)) == typeid(double) ) { - precisionTolerance = 1000.0 * vcl_pow(2.0,-52) * vcl_pow(2,vcl_floor(vcl_log(calculator->GetMaximum())/vcl_log(2.0))); + precisionTolerance = 1000.0 * std::pow(2.0,-52) * std::pow(2,std::floor(std::log(calculator->GetMaximum())/std::log(2.0))); } else if( typeid(inputImage->GetPixel(index)) == typeid(float) ) { - precisionTolerance = 1000.0 * vcl_pow(2.0,-23) * vcl_pow(2,vcl_floor(vcl_log(calculator->GetMaximum())/vcl_log(2.0))); + precisionTolerance = 1000.0 * std::pow(2.0,-23) * std::pow(2,std::floor(std::log(calculator->GetMaximum())/std::log(2.0))); } else { diff --git a/Utilities/ITK/Modules/Filtering/Convolution/include/itkNormalizedCorrelationImageFilter.h b/Utilities/ITK/Modules/Filtering/Convolution/include/itkNormalizedCorrelationImageFilter.h index abb1fc7f0fa47a66a47acc6e02b367a5c6cf466f..131bc515cffeb30c0b2d66f39587ad8f332e5543 100644 --- a/Utilities/ITK/Modules/Filtering/Convolution/include/itkNormalizedCorrelationImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/Convolution/include/itkNormalizedCorrelationImageFilter.h @@ -142,8 +142,7 @@ protected: * region is expanded by the radius of the template. If the request * extends past the LargestPossibleRegion for the input, the request * is cropped by the LargestPossibleRegion. */ - void GenerateInputRequestedRegion() - throw ( InvalidRequestedRegionError ); + void GenerateInputRequestedRegion(); /** NormalizedCorrelationImageFilter can be implemented as a * multithreaded filter. Therefore, this implementation provides a diff --git a/Utilities/ITK/Modules/Filtering/Convolution/include/itkNormalizedCorrelationImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Convolution/include/itkNormalizedCorrelationImageFilter.hxx index fe1203e562a52e20abd4ff5ab69609a8cfc1e08a..584fa31ce8a38c8b2d8edc874d3a8709082fde1c 100644 --- a/Utilities/ITK/Modules/Filtering/Convolution/include/itkNormalizedCorrelationImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Convolution/include/itkNormalizedCorrelationImageFilter.hxx @@ -46,7 +46,6 @@ template< typename TInputImage, typename TMaskImage, typename TOutputImage, type void NormalizedCorrelationImageFilter< TInputImage, TMaskImage, TOutputImage, TOperatorValueType > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); @@ -121,13 +120,13 @@ NormalizedCorrelationImageFilter< TInputImage, TMaskImage, TOutputImage, TOperat static_cast< OutputPixelRealType >( this->GetOperator().Size() ); OutputPixelRealType mean = sum / num; OutputPixelRealType var = ( sumOfSquares - ( sum * sum / num ) ) / ( num - 1.0 ); - OutputPixelRealType std = vcl_sqrt(var); + OutputPixelRealType std = std::sqrt(var); // convert std to a scaling factor k such that // // || (coeff - mean) / k || = 1.0 // - double k = std * vcl_sqrt(num - 1.0); + double k = std * std::sqrt(num - 1.0); // normalize the template for ( ntIt = normalizedTemplate.Begin(), tIt = this->GetOperator().Begin(); @@ -208,7 +207,7 @@ NormalizedCorrelationImageFilter< TInputImage, TMaskImage, TOutputImage, TOperat sum += value; sumOfSquares += ( value * value ); } - denominator = vcl_sqrt( sumOfSquares - ( sum * sum / realTemplateSize ) ); + denominator = std::sqrt( sumOfSquares - ( sum * sum / realTemplateSize ) ); it.Value() = numerator / denominator; @@ -244,7 +243,7 @@ NormalizedCorrelationImageFilter< TInputImage, TMaskImage, TOutputImage, TOperat sum += value; sumOfSquares += ( value * value ); } - denominator = vcl_sqrt( sumOfSquares - ( sum * sum / realTemplateSize ) ); + denominator = std::sqrt( sumOfSquares - ( sum * sum / realTemplateSize ) ); it.Value() = numerator / denominator; } diff --git a/Utilities/ITK/Modules/Filtering/CurvatureFlow/include/itkMinMaxCurvatureFlowFunction.hxx b/Utilities/ITK/Modules/Filtering/CurvatureFlow/include/itkMinMaxCurvatureFlowFunction.hxx index 9b69b7c42115d5f9645ddf7e47ca48bcaf3c46af..9f849aeed66594429a68a5759f373cbff3751eb6 100644 --- a/Utilities/ITK/Modules/Filtering/CurvatureFlow/include/itkMinMaxCurvatureFlowFunction.hxx +++ b/Utilities/ITK/Modules/Filtering/CurvatureFlow/include/itkMinMaxCurvatureFlowFunction.hxx @@ -116,10 +116,13 @@ MinMaxCurvatureFlowFunction< TImage > } // normalize the operator so that it sums to one - for ( opIter = m_StencilOperator.Begin(); opIter < opEnd; ++opIter ) + if (numPixelsInSphere != 0) { - *opIter = static_cast< PixelType >( (double)*opIter - / (double)numPixelsInSphere ); + for ( opIter = m_StencilOperator.Begin(); opIter < opEnd; ++opIter ) + { + *opIter = static_cast< PixelType >( (double)*opIter + / (double)numPixelsInSphere ); + } } } @@ -157,7 +160,7 @@ MinMaxCurvatureFlowFunction< TImage > if ( gradMagnitude == 0.0 ) { return threshold; } - gradMagnitude = vcl_sqrt( (double)gradMagnitude ); + gradMagnitude = std::sqrt( (double)gradMagnitude ); // Search for all position in the neighborhood perpendicular to // the gradient and at a distance of StencilRadius from center. @@ -190,7 +193,7 @@ MinMaxCurvatureFlowFunction< TImage > vectorMagnitude += static_cast< PixelType >( vnl_math_sqr(diff) ); } - vectorMagnitude = vcl_sqrt( (double)vectorMagnitude ); + vectorMagnitude = std::sqrt( (double)vectorMagnitude ); if ( vectorMagnitude != 0.0 ) { @@ -264,7 +267,7 @@ MinMaxCurvatureFlowFunction< TImage > if ( gradMagnitude == 0.0 ) { return threshold; } - gradMagnitude = vcl_sqrt( (double)gradMagnitude ) + gradMagnitude = std::sqrt( (double)gradMagnitude ) / static_cast< PixelType >( m_StencilRadius ); for ( j = 0; j < imageDimension; j++ ) @@ -335,7 +338,7 @@ MinMaxCurvatureFlowFunction< TImage > if ( gradMagnitude == 0.0 ) { return threshold; } - gradMagnitude = vcl_sqrt( (double)gradMagnitude ) + gradMagnitude = std::sqrt( (double)gradMagnitude ) / static_cast< PixelType >( m_StencilRadius ); for ( j = 0; j < imageDimension; j++ ) @@ -352,7 +355,7 @@ MinMaxCurvatureFlowFunction< TImage > { gradient[2] = -1.0; } - theta = vcl_acos( (double)gradient[2] ); + theta = std::acos( (double)gradient[2] ); if ( gradient[0] == 0 ) { @@ -360,13 +363,13 @@ MinMaxCurvatureFlowFunction< TImage > } else { - phi = vcl_atan( (double)gradient[1] / (double)gradient[0] ); + phi = std::atan( (double)gradient[1] / (double)gradient[0] ); } - double cosTheta = vcl_cos(theta); - double sinTheta = vcl_sin(theta); - double cosPhi = vcl_cos(phi); - double sinPhi = vcl_sin(phi); + double cosTheta = std::cos(theta); + double sinTheta = std::sin(theta); + double cosPhi = std::cos(phi); + double sinPhi = std::sin(phi); double rSinTheta = m_StencilRadius * sinTheta; double rCosThetaCosPhi = m_StencilRadius * cosTheta * cosPhi; diff --git a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkInverseDeconvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkInverseDeconvolutionImageFilter.hxx index 0db544a1750ee7da59db7b3dc3a75110d3188a62..57cdf92efefe073c679995b1bbf1f65823ab8fa2 100644 --- a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkInverseDeconvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkInverseDeconvolutionImageFilter.hxx @@ -47,8 +47,8 @@ InverseDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInter const KernelImageType* kernelImage = this->GetKernelImage(); - InternalComplexImagePointerType input = NULL; - InternalComplexImagePointerType kernel = NULL; + InternalComplexImagePointerType input = ITK_NULLPTR; + InternalComplexImagePointerType kernel = ITK_NULLPTR; this->PrepareInputs( localInput, kernelImage, input, kernel, progress, 0.7 ); @@ -68,8 +68,8 @@ InverseDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInter progress->RegisterInternalFilter( inverseFilter, 0.1 ); // Free up the memory for the prepared inputs - input = NULL; - kernel = NULL; + input = ITK_NULLPTR; + kernel = ITK_NULLPTR; this->ProduceOutput( inverseFilter->GetOutput(), progress, 0.2 ); } diff --git a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkIterativeDeconvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkIterativeDeconvolutionImageFilter.hxx index 1b397a5337bbab546703ebb689828ae849f375ec..f299ae3d6b3316fcfe2993f02f96bb4e50496d06 100644 --- a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkIterativeDeconvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkIterativeDeconvolutionImageFilter.hxx @@ -31,8 +31,8 @@ IterativeDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInt m_NumberOfIterations = 1; m_Iteration = 0; m_StopIteration = false; - m_TransferFunction = NULL; - m_CurrentEstimate = NULL; + m_TransferFunction = ITK_NULLPTR; + m_CurrentEstimate = ITK_NULLPTR; m_InputMTime = 0L; m_KernelMTime = 0L; } @@ -41,8 +41,8 @@ template< typename TInputImage, typename TKernelImage, typename TOutputImage, ty IterativeDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPrecision > ::~IterativeDeconvolutionImageFilter() { - m_TransferFunction = NULL; - m_CurrentEstimate = NULL; + m_TransferFunction = ITK_NULLPTR; + m_CurrentEstimate = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > @@ -82,8 +82,8 @@ IterativeDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInt { this->CropOutput( m_CurrentEstimate, progress, progressWeight ); - m_CurrentEstimate = NULL; - m_TransferFunction = NULL; + m_CurrentEstimate = ITK_NULLPTR; + m_TransferFunction = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > diff --git a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkLandweberDeconvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkLandweberDeconvolutionImageFilter.hxx index a27503d8c63dae3e0e413419912c90b0394c45a5..8a2c4e4dd236898747b1b1b0adeeee5b183a8b1a 100644 --- a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkLandweberDeconvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkLandweberDeconvolutionImageFilter.hxx @@ -28,14 +28,14 @@ LandweberDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInt ::LandweberDeconvolutionImageFilter() { m_Alpha = 0.1; - m_TransformedInput = NULL; + m_TransformedInput = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > LandweberDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPrecision > ::~LandweberDeconvolutionImageFilter() { - m_TransformedInput = NULL; + m_TransformedInput = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > @@ -99,8 +99,8 @@ LandweberDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInt { this->Superclass::Finish( progress, progressWeight ); - m_LandweberFilter = NULL; - m_IFFTFilter = NULL; + m_LandweberFilter = ITK_NULLPTR; + m_IFFTFilter = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > diff --git a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkParametricBlindLeastSquaresDeconvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkParametricBlindLeastSquaresDeconvolutionImageFilter.hxx index 59808f35269332a1f11025dafb67a58570eeb03b..0266a2969128f010a65f8ce646a07e8a2cc3b64f 100644 --- a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkParametricBlindLeastSquaresDeconvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkParametricBlindLeastSquaresDeconvolutionImageFilter.hxx @@ -103,7 +103,7 @@ ParametricBlindLeastSquaresDeconvolutionImageFilter< TInputImage, TKernelImage, { // Compute the new padded, shifted, and transformed kernel m_KernelSource->UpdateLargestPossibleRegion(); - InternalComplexImagePointerType preparedKernel = NULL; + InternalComplexImagePointerType preparedKernel = ITK_NULLPTR; this->PrepareKernel( m_KernelSource->GetOutput(), preparedKernel, progress, 0.0 ); m_DifferenceFilter->SetInput1( m_TransformedCurrentEstimate ); @@ -266,10 +266,10 @@ ParametricBlindLeastSquaresDeconvolutionImageFilter< TInputImage, TKernelImage, this->Superclass::Finish( progress, progressWeight ); - m_TransformedInput = NULL; - m_TransformedCurrentEstimate = NULL; - m_DifferenceFilter = NULL; - m_ImageUpdateFilter = NULL; + m_TransformedInput = ITK_NULLPTR; + m_TransformedCurrentEstimate = ITK_NULLPTR; + m_DifferenceFilter = ITK_NULLPTR; + m_ImageUpdateFilter = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage > diff --git a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkProjectedIterativeDeconvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkProjectedIterativeDeconvolutionImageFilter.hxx index cb4abf3f3ae73975bdec6cb4ce1582996d2e5e2e..839f25869c175bf92ebdfdda231a72c884cfaaee 100644 --- a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkProjectedIterativeDeconvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkProjectedIterativeDeconvolutionImageFilter.hxx @@ -27,14 +27,14 @@ template< typename TSuperclass > ProjectedIterativeDeconvolutionImageFilter< TSuperclass > ::ProjectedIterativeDeconvolutionImageFilter() { - m_ProjectionFilter = NULL; + m_ProjectionFilter = ITK_NULLPTR; } template< typename TSuperclass > ProjectedIterativeDeconvolutionImageFilter< TSuperclass > ::~ProjectedIterativeDeconvolutionImageFilter() { - m_ProjectionFilter = NULL; + m_ProjectionFilter = ITK_NULLPTR; } template< typename TSuperclass > diff --git a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkRichardsonLucyDeconvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkRichardsonLucyDeconvolutionImageFilter.hxx index 8dd63cc4061d0b4e4f7999611bf9bbc7c4b4d9fb..c9f5fba7314719221137a70f4d0b86922611a7cf 100644 --- a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkRichardsonLucyDeconvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkRichardsonLucyDeconvolutionImageFilter.hxx @@ -27,14 +27,14 @@ template< typename TInputImage, typename TKernelImage, typename TOutputImage, ty RichardsonLucyDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPrecision > ::RichardsonLucyDeconvolutionImageFilter() { - m_PaddedInput = NULL; + m_PaddedInput = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > RichardsonLucyDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInternalPrecision > ::~RichardsonLucyDeconvolutionImageFilter() { - m_PaddedInput = NULL; + m_PaddedInput = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > @@ -142,14 +142,14 @@ RichardsonLucyDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, { this->Superclass::Finish( progress, progressWeight ); - m_ComplexMultiplyFilter1 = NULL; - m_IFFTFilter1 = NULL; - m_DivideFilter = NULL; - m_FFTFilter = NULL; - m_ConjugateAdaptor = NULL; - m_ComplexMultiplyFilter2 = NULL; - m_IFFTFilter2 = NULL; - m_MultiplyFilter = NULL; + m_ComplexMultiplyFilter1 = ITK_NULLPTR; + m_IFFTFilter1 = ITK_NULLPTR; + m_DivideFilter = ITK_NULLPTR; + m_FFTFilter = ITK_NULLPTR; + m_ConjugateAdaptor = ITK_NULLPTR; + m_ComplexMultiplyFilter2 = ITK_NULLPTR; + m_IFFTFilter2 = ITK_NULLPTR; + m_MultiplyFilter = ITK_NULLPTR; } template< typename TInputImage, typename TKernelImage, typename TOutputImage, typename TInternalPrecision > diff --git a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkTikhonovDeconvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkTikhonovDeconvolutionImageFilter.hxx index 25f39fac0ec51bb9582aac86334e21958bde2d0d..250acd385357b506f57c1ffb83e046d035bc2564 100644 --- a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkTikhonovDeconvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkTikhonovDeconvolutionImageFilter.hxx @@ -47,8 +47,8 @@ TikhonovDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInte const KernelImageType* kernelImage = this->GetKernelImage(); - InternalComplexImagePointerType input = NULL; - InternalComplexImagePointerType kernel = NULL; + InternalComplexImagePointerType input = ITK_NULLPTR; + InternalComplexImagePointerType kernel = ITK_NULLPTR; this->PrepareInputs( localInput, kernelImage, input, kernel, progress, 0.7 ); @@ -69,8 +69,8 @@ TikhonovDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TInte progress->RegisterInternalFilter( tikhonovFilter, 0.1 ); // Free up the memory for the prepared inputs - input = NULL; - kernel = NULL; + input = ITK_NULLPTR; + kernel = ITK_NULLPTR; this->ProduceOutput( tikhonovFilter->GetOutput(), progress, 0.2 ); } diff --git a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkWienerDeconvolutionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkWienerDeconvolutionImageFilter.hxx index 9a7b3637a8c8dbec6beaf8cb173b5e2fda29148a..09322f5d5dd2fe91552ff2ad6d5237ea3b570661 100644 --- a/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkWienerDeconvolutionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Deconvolution/include/itkWienerDeconvolutionImageFilter.hxx @@ -47,8 +47,8 @@ WienerDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TIntern const KernelImageType* kernelImage = this->GetKernelImage(); - InternalComplexImagePointerType input = NULL; - InternalComplexImagePointerType kernel = NULL; + InternalComplexImagePointerType input = ITK_NULLPTR; + InternalComplexImagePointerType kernel = ITK_NULLPTR; this->PrepareInputs( localInput, kernelImage, input, kernel, progress, 0.7 ); @@ -68,8 +68,8 @@ WienerDeconvolutionImageFilter< TInputImage, TKernelImage, TOutputImage, TIntern progress->RegisterInternalFilter( wienerFilter, 0.1 ); // Free up the memory for the prepared inputs - input = NULL; - kernel = NULL; + input = ITK_NULLPTR; + kernel = ITK_NULLPTR; this->ProduceOutput( wienerFilter->GetOutput(), progress, 0.2 ); } diff --git a/Utilities/ITK/Modules/Filtering/Denoising/include/itkPatchBasedDenoisingBaseImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Denoising/include/itkPatchBasedDenoisingBaseImageFilter.hxx index 4c31f95cf40e5b1d7794a07b346d537d4f0c57e2..b0324c0849b0d2f1776ae377a5d97fb8dc73f2ce 100644 --- a/Utilities/ITK/Modules/Filtering/Denoising/include/itkPatchBasedDenoisingBaseImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Denoising/include/itkPatchBasedDenoisingBaseImageFilter.hxx @@ -54,8 +54,8 @@ PatchBasedDenoisingBaseImageFilter<TInputImage, TOutputImage> m_ManualReinitialization = false; m_State = UNINITIALIZED; - m_InputImage = 0; - m_OutputImage = 0; + m_InputImage = ITK_NULLPTR; + m_OutputImage = ITK_NULLPTR; } template <typename TInputImage, typename TOutputImage> @@ -249,7 +249,7 @@ PatchBasedDenoisingBaseImageFilter<TInputImage, TOutputImage> { const typename Self::Pointer thisPtr = const_cast< Self* >(this); // cache input image, if it has not yet been set. - if(thisPtr->m_InputImage == 0) + if(thisPtr->m_InputImage == ITK_NULLPTR) { thisPtr->m_InputImage = this->GetInput(); } diff --git a/Utilities/ITK/Modules/Filtering/Denoising/include/itkPatchBasedDenoisingImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Denoising/include/itkPatchBasedDenoisingImageFilter.hxx index f06e6a314ac3ab734261b3bbeeb99c5562846b1b..4e535833612668aa486c933195bd98a3ba3e218b 100644 --- a/Utilities/ITK/Modules/Filtering/Denoising/include/itkPatchBasedDenoisingImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Denoising/include/itkPatchBasedDenoisingImageFilter.hxx @@ -35,44 +35,31 @@ namespace itk template <typename TInputImage, typename TOutputImage> PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> -::PatchBasedDenoisingImageFilter() +::PatchBasedDenoisingImageFilter() : + m_UpdateBuffer(OutputImageType::New()), + m_NumPixelComponents(0), // not valid until Initialize() + m_NumIndependentComponents(0), // not valid until Initialize() + m_TotalNumberPixels(0), // not valid until an image is provided + m_UseSmoothDiscPatchWeights(true), + m_UseFastTensorComputations(true), + m_KernelBandwidthSigmaIsSet(false), + m_ZeroPixel(), // not valid until Initialize() + m_KernelBandwidthFractionPixelsForEstimation(0.20), + m_ComputeConditionalDerivatives(false), + m_MinSigma(NumericTraits<RealValueType>::min() * 100), // to avoid divide by zero + m_MinProbability(NumericTraits<RealValueType>::min() * 100), // to avoid divide by zero + m_SigmaUpdateDecimationFactor(static_cast<unsigned int> + (Math::Round<double>(1.0 / m_KernelBandwidthFractionPixelsForEstimation))), + m_SigmaUpdateConvergenceTolerance(0.01), // desired accuracy of Newton-Raphson sigma estimation + m_KernelBandwidthMultiplicationFactor(1.0), + m_NoiseSigma(0.0), + m_NoiseSigmaSquared(0.0), + m_NoiseSigmaIsSet(false), + m_Sampler(ITK_NULLPTR), // not valid until a sampler is provided + m_SearchSpaceList(ListAdaptorType::New()) { - m_SearchSpaceList = ListAdaptorType::New(); - m_UpdateBuffer = OutputImageType::New(); - - // patch weights - m_UseSmoothDiscPatchWeights = true; - - // - m_UseFastTensorComputations = true; - // by default, turn off automatic kernel bandwidth sigma estimation this->KernelBandwidthEstimationOff(); - // minimum probability, used to avoid divide by zero - m_MinProbability = NumericTraits<RealValueType>::min() * 100; - // minimum sigma allowed, used to avoid divide by zero - m_MinSigma = NumericTraits<RealValueType>::min() * 100; - - m_ComputeConditionalDerivatives = false; - m_KernelBandwidthFractionPixelsForEstimation = 0.20; - m_SigmaUpdateDecimationFactor = static_cast<unsigned int> - (Math::Round<double>(1.0 / m_KernelBandwidthFractionPixelsForEstimation) ); - // desired accuracy of Newton-Raphson sigma estimation - m_SigmaUpdateConvergenceTolerance = 0.01; - m_KernelBandwidthMultiplicationFactor = 1.0; - - m_NoiseSigmaIsSet = false; - m_KernelBandwidthSigmaIsSet = false; - - m_TotalNumberPixels = 0; // won't be valid until an image is provided - m_Sampler = 0; // won't be valid until a sampler is provided - m_NumPixelComponents = 0; // won't be valid until Initialize() gets - // called - m_NumIndependentComponents = 0; // won't be valid until Initialize() gets - // called - // m_IntensityRescaleInvFactor won't be allocated until Initialize() gets - // called - // because we need the input image first. } template <typename TInputImage, typename TOutputImage> @@ -354,7 +341,7 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> newStruct.minNorm[ic] = 0; newStruct.maxNorm[ic] = 0; } - newStruct.sampler = NULL; + newStruct.sampler = ITK_NULLPTR; m_ThreadData.push_back(newStruct); } @@ -845,8 +832,8 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> if (foundMinMax) { threadData.validNorms[0] = 1; - threadData.minNorm[0] = vcl_sqrt(minNorm[0]); - threadData.maxNorm[0] = vcl_sqrt(maxNorm[0]); + threadData.minNorm[0] = std::sqrt(minNorm[0]); + threadData.maxNorm[0] = std::sqrt(maxNorm[0]); itkDebugMacro( <<"threadData minNorm: " << minNorm[0] << ", maxNorm: " << maxNorm[0] ); @@ -972,7 +959,7 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> RealTensorValueT n, sqrtn, s; n = I1div3 * I1div3 - I2/3; s = I1div3 * I1div3 * I1div3 - I1*I2/6 + I3/2; - sqrtn = vcl_sqrt(n); + sqrtn = std::sqrt(n); // now check for some degenerate cases // if these occur, default to the standard eigen analysis @@ -993,7 +980,7 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> // Compute phi = (acos((s/n) * sqrt(1/n)) / 3) RealTensorValueT phi; - phi = vcl_acos( (s/n) * 1/sqrtn) / 3; + phi = std::acos( (s/n) * 1/sqrtn) / 3; // Now compute the eigenvalues // lambda1 = I1/3 + 2*sqrt(n)*cos(phi) @@ -1003,8 +990,8 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> // lambda3 also = I1 - lambda1 - lambda2 RealTensorValueT lambda1, lambda2, lambda3; - lambda1 = I1div3 + 2 * sqrtn * vcl_cos(phi); - lambda2 = I1div3 - 2*sqrtn * vcl_cos(vnl_math::pi/3 + phi); + lambda1 = I1div3 + 2 * sqrtn * std::cos(phi); + lambda2 = I1div3 - 2*sqrtn * std::cos(vnl_math::pi/3 + phi); lambda3 = I1 - lambda1 - lambda2; eigenVals[0] = lambda1; @@ -1052,7 +1039,7 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> // eigenVec = e / sqrt(e'e) RealTensorValueT norm, sqrtnorm; norm = ex * ex + ey * ey + ez * ez; - sqrtnorm = vcl_sqrt(norm); + sqrtnorm = std::sqrt(norm); eigenVecs(i,0) = ex / sqrtnorm; eigenVecs(i,1) = ey / sqrtnorm; eigenVecs(i,2) = ez / sqrtnorm; @@ -1077,10 +1064,8 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> EigenVectorsCacheType& eigenVecsCache, RealType& symMatrixLogMap, RealArrayType& geodesicDist) { - typedef typename PixelType::MatrixType MatrixType; typedef typename RealType::EigenValuesArrayType RealEigenValuesArrayType; typedef typename RealType::EigenVectorsMatrixType RealEigenVectorsMatrixType; - typedef typename RealType::MatrixType RealMatrixType; EigenValuesArrayType eigenVals; EigenVectorsMatrixType eigenVecs; RealEigenValuesArrayType YEigenVals; @@ -1109,8 +1094,8 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> if (cacheIndex >= eigenValsCache.size() ) { - eigenValsCache.resize(cacheIndex+1, 0); - eigenVecsCache.resize(cacheIndex+1, 0); + eigenValsCache.resize(cacheIndex+1, ITK_NULLPTR); + eigenVecsCache.resize(cacheIndex+1, ITK_NULLPTR); } delete eigenValsCache[cacheIndex]; @@ -1143,9 +1128,9 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> factor2 = spdMatrixB[2] * eigenVecs(0,0) + spdMatrixB[4] * eigenVecs(0,1) + spdMatrixB[5] * eigenVecs(0,2); Y[0] = ( eigenVecs(0,0) * factor0 + eigenVecs(0,1) * factor1 + eigenVecs(0,2) * factor2 ) / eigenVals[0]; - Y[1] = ( eigenVecs(1,0) * factor0 + eigenVecs(1,1) * factor1 + eigenVecs(1,2) * factor2 ) / vcl_sqrt( + Y[1] = ( eigenVecs(1,0) * factor0 + eigenVecs(1,1) * factor1 + eigenVecs(1,2) * factor2 ) / std::sqrt( eigenVals[0] * eigenVals[1]); - Y[2] = ( eigenVecs(2,0) * factor0 + eigenVecs(2,1) * factor1 + eigenVecs(2,2) * factor2 ) / vcl_sqrt( + Y[2] = ( eigenVecs(2,0) * factor0 + eigenVecs(2,1) * factor1 + eigenVecs(2,2) * factor2 ) / std::sqrt( eigenVals[0] * eigenVals[2]); factor0 = spdMatrixB[0] * eigenVecs(1,0) + spdMatrixB[1] * eigenVecs(1,1) + spdMatrixB[2] * eigenVecs(1,2); @@ -1153,7 +1138,7 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> factor2 = spdMatrixB[2] * eigenVecs(1,0) + spdMatrixB[4] * eigenVecs(1,1) + spdMatrixB[5] * eigenVecs(1,2); Y[3] = ( eigenVecs(1,0) * factor0 + eigenVecs(1,1) * factor1 + eigenVecs(1,2) * factor2 ) / eigenVals[1]; - Y[4] = ( eigenVecs(2,0) * factor0 + eigenVecs(2,1) * factor1 + eigenVecs(2,2) * factor2 ) / vcl_sqrt( + Y[4] = ( eigenVecs(2,0) * factor0 + eigenVecs(2,1) * factor1 + eigenVecs(2,2) * factor2 ) / std::sqrt( eigenVals[1] * eigenVals[2]); factor0 = spdMatrixB[0] * eigenVecs(2,0) + spdMatrixB[1] * eigenVecs(2,1) + spdMatrixB[2] * eigenVecs(2,2); @@ -1187,11 +1172,11 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> // these calculations can be optimized as follows. for (unsigned int ii = 0; ii < 3; ++ii) { - YEigenVals[ii] = vcl_log(vnl_math_max(RealValueType(1e-15),YEigenVals[ii]) ); + YEigenVals[ii] = std::log(vnl_math_max(RealValueType(1e-15),YEigenVals[ii]) ); } - const RealValueType eigVal0 = vcl_sqrt(eigenVals[0]); - const RealValueType eigVal1 = vcl_sqrt(eigenVals[1]); - const RealValueType eigVal2 = vcl_sqrt(eigenVals[2]); + const RealValueType eigVal0 = std::sqrt(eigenVals[0]); + const RealValueType eigVal1 = std::sqrt(eigenVals[1]); + const RealValueType eigVal2 = std::sqrt(eigenVals[2]); const RealValueType YEigVal0 = YEigenVals[0]; const RealValueType YEigVal1 = YEigenVals[1]; const RealValueType YEigVal2 = YEigenVals[2]; @@ -1263,7 +1248,6 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> { typedef typename RealType::EigenValuesArrayType RealEigenValuesArrayType; typedef typename RealType::EigenVectorsMatrixType RealEigenVectorsMatrixType; - typedef typename RealType::MatrixType RealMatrixType; RealEigenValuesArrayType eigenVals; RealEigenVectorsMatrixType eigenVecs; RealEigenValuesArrayType YEigenVals; @@ -1308,9 +1292,9 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> factor2 = symMatrix[2] * eigenVecs(0,0) + symMatrix[4] * eigenVecs(0,1) + symMatrix[5] * eigenVecs(0,2); Y[0] = ( eigenVecs(0,0) * factor0 + eigenVecs(0,1) * factor1 + eigenVecs(0,2) * factor2 ) / eigenVals[0]; - Y[1] = ( eigenVecs(1,0) * factor0 + eigenVecs(1,1) * factor1 + eigenVecs(1,2) * factor2 ) / vcl_sqrt( + Y[1] = ( eigenVecs(1,0) * factor0 + eigenVecs(1,1) * factor1 + eigenVecs(1,2) * factor2 ) / std::sqrt( eigenVals[0] * eigenVals[1]); - Y[2] = ( eigenVecs(2,0) * factor0 + eigenVecs(2,1) * factor1 + eigenVecs(2,2) * factor2 ) / vcl_sqrt( + Y[2] = ( eigenVecs(2,0) * factor0 + eigenVecs(2,1) * factor1 + eigenVecs(2,2) * factor2 ) / std::sqrt( eigenVals[0] * eigenVals[2]); factor0 = symMatrix[0] * eigenVecs(1,0) + symMatrix[1] * eigenVecs(1,1) + symMatrix[2] * eigenVecs(1,2); @@ -1318,7 +1302,7 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> factor2 = symMatrix[2] * eigenVecs(1,0) + symMatrix[4] * eigenVecs(1,1) + symMatrix[5] * eigenVecs(1,2); Y[3] = ( eigenVecs(1,0) * factor0 + eigenVecs(1,1) * factor1 + eigenVecs(1,2) * factor2 ) / eigenVals[1]; - Y[4] = ( eigenVecs(2,0) * factor0 + eigenVecs(2,1) * factor1 + eigenVecs(2,2) * factor2 ) / vcl_sqrt( + Y[4] = ( eigenVecs(2,0) * factor0 + eigenVecs(2,1) * factor1 + eigenVecs(2,2) * factor2 ) / std::sqrt( eigenVals[1] * eigenVals[2]); factor0 = symMatrix[0] * eigenVecs(2,0) + symMatrix[1] * eigenVecs(2,1) + symMatrix[2] * eigenVecs(2,2); @@ -1350,11 +1334,11 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> for (unsigned int ii = 0; ii < 3; ++ii) { - YEigenVals[ii] = vcl_exp(YEigenVals[ii]); + YEigenVals[ii] = std::exp(YEigenVals[ii]); } - const RealValueType eigVal0 = vcl_sqrt(eigenVals[0]); - const RealValueType eigVal1 = vcl_sqrt(eigenVals[1]); - const RealValueType eigVal2 = vcl_sqrt(eigenVals[2]); + const RealValueType eigVal0 = std::sqrt(eigenVals[0]); + const RealValueType eigVal1 = std::sqrt(eigenVals[1]); + const RealValueType eigVal2 = std::sqrt(eigenVals[2]); const RealValueType YEigVal0 = YEigenVals[0]; const RealValueType YEigVal1 = YEigenVals[1]; const RealValueType YEigVal2 = YEigenVals[2]; @@ -1858,7 +1842,7 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> squaredNorm[ic] += centerPatchSquaredNorm[ic]; const RealValueType sigmaKernel = m_KernelBandwidthSigma[ic]; - const RealValueType distanceJointEntropy = vcl_sqrt(squaredNorm[ic]); + const RealValueType distanceJointEntropy = std::sqrt(squaredNorm[ic]); const RealValueType gaussianJointEntropy = exp(-vnl_math_sqr(distanceJointEntropy / sigmaKernel) / 2.0); @@ -1875,7 +1859,7 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> if (m_ComputeConditionalDerivatives) { const RealValueType distancePatchEntropySquared = squaredNorm[ic] - centerPatchSquaredNorm[ic]; - const RealValueType distancePatchEntropy = vcl_sqrt(distancePatchEntropySquared); + const RealValueType distancePatchEntropy = std::sqrt(distancePatchEntropySquared); const RealValueType gaussianPatchEntropy = exp(-vnl_math_sqr(distancePatchEntropy / sigmaKernel) / 2.0); probPatchEntropy[ic] += gaussianPatchEntropy; @@ -2573,26 +2557,9 @@ PatchBasedDenoisingImageFilter<TInputImage, TOutputImage> os << indent << "KernelBandwidthMultiplicationFactor: " << m_KernelBandwidthMultiplicationFactor << std::endl; - if (m_Sampler) - { - os << indent << "Sampler: " << std::endl; - m_Sampler->Print(os,indent.GetNextIndent() ); - } - else - { - os << indent << "Sampler: " << "(None)" << std::endl; - } + itkPrintSelfObjectMacro( Sampler ); + itkPrintSelfObjectMacro( UpdateBuffer ); - if (m_UpdateBuffer) - { - os << indent << "Update buffer:\n"; - m_UpdateBuffer->Print(os, indent.GetNextIndent() ); - os << std::endl; - } - else - { - os << indent << "Update buffer is NULL" << std::endl; - } os << std::endl; } diff --git a/Utilities/ITK/Modules/Filtering/DiffusionTensorImage/include/itkDiffusionTensor3DReconstructionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DiffusionTensorImage/include/itkDiffusionTensor3DReconstructionImageFilter.hxx index 4e018db0485efd8c8175fc6267c8fa09ee3b02d7..e5c5a22878818495828c30d76234726dbe0ce52f 100644 --- a/Utilities/ITK/Modules/Filtering/DiffusionTensorImage/include/itkDiffusionTensor3DReconstructionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DiffusionTensorImage/include/itkDiffusionTensor3DReconstructionImageFilter.hxx @@ -24,6 +24,7 @@ #include "itkArray.h" #include "itkImageMaskSpatialObject.h" #include "vnl/vnl_vector.h" +#include "itkProgressReporter.h" namespace itk { @@ -43,7 +44,7 @@ DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, m_NumberOfBaselineImages = 1; m_Threshold = NumericTraits< ReferencePixelType >::min(); m_GradientImageTypeEnumeration = Else; - m_GradientDirectionContainer = NULL; + m_GradientDirectionContainer = ITK_NULLPTR; m_TensorBasis.set_identity(); m_BValue = 1.0; m_MaskImagePresent = false; @@ -181,7 +182,7 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, TTensorPixelType, TMaskImageType > ::ThreadedGenerateData(const OutputImageRegionType & outputRegionForThread, - ThreadIdType) + ThreadIdType threadId) { typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >( this->ProcessObject::GetOutput(0) ); @@ -242,6 +243,8 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, // "A Dual Tensor Basis Solution to the Stejskal-Tanner Equations for // DT-MRI" + ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); + while ( !it.IsAtEnd() ) { @@ -275,7 +278,7 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, } else { - B[i] = -vcl_log( static_cast< double >( b ) / static_cast< double >( b0 ) ) / this->m_BValue; + B[i] = -std::log( static_cast< double >( b ) / static_cast< double >( b0 ) ) / this->m_BValue; } ++( *gradientItContainer[i] ); @@ -309,6 +312,7 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, oit.Set(tensor); ++oit; ++it; + progress.CompletedPixel(); } for ( unsigned int i = 0; i < gradientItContainer.size(); i++ ) @@ -323,7 +327,7 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, GradientIteratorType; typedef typename GradientImagesType::PixelType GradientVectorType; - typename GradientImagesType::Pointer gradientImagePointer = NULL; + typename GradientImagesType::Pointer gradientImagePointer = ITK_NULLPTR; // Would have liked a dynamic_cast here, but seems SGI doesn't like it // The enum will ensure that an inappropriate cast is not done @@ -353,6 +357,8 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, } } + ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); + while ( !git.IsAtEnd() ) { GradientVectorType b = git.Get(); @@ -395,7 +401,7 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, else { B[i] = - -vcl_log( static_cast< double >( b[gradientind[i]] ) / static_cast< double >( b0 ) ) / this->m_BValue; + -std::log( static_cast< double >( b[gradientind[i]] ) / static_cast< double >( b0 ) ) / this->m_BValue; } } @@ -420,6 +426,7 @@ void DiffusionTensor3DReconstructionImageFilter< TReferenceImagePixelType, oit.Set(tensor); ++oit; // Output (reconstructed tensor image) iterator ++git; // Gradient image iterator + progress.CompletedPixel(); } } } diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkComposeDisplacementFieldsImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkComposeDisplacementFieldsImageFilter.hxx index e06b71729e53a057a7504c5dc4d6d388355958b2..05f83649d57682558ae4f94df0095ae16423d1f6 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkComposeDisplacementFieldsImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkComposeDisplacementFieldsImageFilter.hxx @@ -129,10 +129,8 @@ void ComposeDisplacementFieldsImageFilter<InputImage, TOutputImage> ::PrintSelf( std::ostream& os, Indent indent ) const { - os << "Interpolator:" << std::endl; - this->m_Interpolator->Print( os, indent ); - Superclass::PrintSelf( os, indent ); + itkPrintSelfObjectMacro( Interpolator ); } } //end namespace itk diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkConstantVelocityFieldTransform.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkConstantVelocityFieldTransform.hxx index abd28e466c90e203cbc5204dce0422efe66110bf..69b0dab878c706be8e5a513192484aed3d4e1338 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkConstantVelocityFieldTransform.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkConstantVelocityFieldTransform.hxx @@ -34,7 +34,7 @@ namespace itk template <typename TScalar, unsigned int NDimensions> ConstantVelocityFieldTransform<TScalar, NDimensions> ::ConstantVelocityFieldTransform() : - m_ConstantVelocityField( NULL ), + m_ConstantVelocityField( ITK_NULLPTR ), m_CalculateNumberOfIntegrationStepsAutomatically( false ), m_ConstantVelocityFieldSetTime( 0 ) { @@ -118,7 +118,7 @@ ConstantVelocityFieldTransform<TScalar, NDimensions> } else { - return NULL; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.h b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.h index 187dc688deefb902e4cf2b52afe7d6e139eacde8..67cc4dbe274f467670875cb6f5b44b323b44eedb 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.h +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.h @@ -171,8 +171,7 @@ public: * pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** Set the derivative weights according to the spacing of the input image (1/spacing). Use this option if you want to calculate the Jacobian diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx index 09c3a7eea56d7c705cb9e09a8c35b91928240d08..83e19bf71266f1ef8248f2461b76ca09cfa348d6 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldJacobianDeterminantFilter.hxx @@ -92,7 +92,6 @@ template< typename TInputImage, typename TRealType, typename TOutputImage > void DisplacementFieldJacobianDeterminantFilter< TInputImage, TRealType, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldToBSplineImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldToBSplineImageFilter.hxx index e2b73dbfb54341ebb71e0a19909baefd999e120f..dbb20a5b5e22676a0f9907e76e2045a41c4c2ea9 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldToBSplineImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldToBSplineImageFilter.hxx @@ -43,7 +43,7 @@ DisplacementFieldToBSplineImageFilter<TInputImage, TOutputImage> this->m_NumberOfFittingLevels.Fill( 1 ); this->m_NumberOfControlPoints.Fill( 4 ); - this->m_DisplacementFieldControlPointLattice = NULL; + this->m_DisplacementFieldControlPointLattice = ITK_NULLPTR; } template<typename TInputImage, typename TOutputImage> @@ -84,9 +84,6 @@ DisplacementFieldToBSplineImageFilter<TInputImage, TOutputImage> typename PointSetType::Pointer fieldPoints = PointSetType::New(); fieldPoints->Initialize(); - typedef typename ImporterType::OutputImageType ImporterOutputImageType; - typedef typename ImporterOutputImageType::RegionType ImporterRegionType; - typedef typename InputFieldType::PointType InputFieldPointType; typedef ContinuousIndex<typename InputFieldPointType::CoordRepType, ImageDimension> ContinuousIndexType; diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldTransform.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldTransform.hxx index 7074baa697cfe445d65ed3a89782d9439d73de14..16550f13d8d86be579a434205ce2d30f2eb61f6c 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldTransform.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkDisplacementFieldTransform.hxx @@ -35,8 +35,8 @@ template <typename TScalar, unsigned int NDimensions> DisplacementFieldTransform<TScalar, NDimensions>::DisplacementFieldTransform() : Superclass( 0 ) { - this->m_DisplacementField = NULL; - this->m_InverseDisplacementField = NULL; + this->m_DisplacementField = ITK_NULLPTR; + this->m_InverseDisplacementField = ITK_NULLPTR; this->m_FixedParameters.SetSize( NDimensions * ( NDimensions + 3 ) ); this->m_FixedParameters.Fill( 0.0 ); @@ -151,7 +151,7 @@ DisplacementFieldTransform<TScalar, NDimensions> } else { - return NULL; + return ITK_NULLPTR; } } @@ -377,7 +377,7 @@ void DisplacementFieldTransform<TScalar, NDimensions> if( !this->m_InverseDisplacementField.IsNull() ) { - this->m_InverseDisplacementField = NULL; + this->m_InverseDisplacementField = ITK_NULLPTR; } this->Modified(); /* Store this separately for use in smoothing because we only want diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkExponentialDisplacementFieldImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkExponentialDisplacementFieldImageFilter.hxx index 77dfd85e2bc5c5a2c905b6dea4e1398c3832a032..bf3c903bc108fdd0831301263ff6a1c15c8ee19c 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkExponentialDisplacementFieldImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkExponentialDisplacementFieldImageFilter.hxx @@ -113,7 +113,7 @@ ExponentialDisplacementFieldImageFilter< TInputImage, TOutputImage > maxnorm2 /= vnl_math_sqr(minpixelspacing); InputPixelRealValueType numiterfloat = 2.0 - + 0.5 * vcl_log(maxnorm2) / vnl_math::ln2; + + 0.5 * std::log(maxnorm2) / vnl_math::ln2; if ( numiterfloat >= 0.0 ) { diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkGaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform.h b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkGaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform.h index 10900368fbbc8d9f941d8b56555e0088b1d2a961..8fddd4dcc973d665804335e33cfe0e67bf987449 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkGaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform.h +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkGaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform.h @@ -52,7 +52,7 @@ public: TimeVaryingVelocityFieldTransform ); /** New macro for creation of through a Smart Pointer */ - itkSimpleNewMacro( Self ); + itkNewMacro( Self ); /** Dimension of the time varying velocity field. */ itkStaticConstMacro( TimeVaryingVelocityFieldDimension, unsigned int, NDimensions+1 ); diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkGaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkGaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform.hxx index d196ef67968cca33b2f509115315ddfed11cd1fd..0c26da584e879ec28ab0ccab893593bc9f1d9679 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkGaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkGaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform.hxx @@ -33,12 +33,13 @@ namespace itk template<typename TScalar, unsigned int NDimensions> GaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform<TScalar, NDimensions> -::GaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform() +::GaussianSmoothingOnUpdateTimeVaryingVelocityFieldTransform() : + m_GaussianSmoothingTempFieldModifiedTime(0), + m_GaussianSpatialSmoothingVarianceForTheUpdateField(3.0), + m_GaussianSpatialSmoothingVarianceForTheTotalField(0.5), + m_GaussianTemporalSmoothingVarianceForTheUpdateField(0.25), + m_GaussianTemporalSmoothingVarianceForTheTotalField(0.0) { - this->m_GaussianSpatialSmoothingVarianceForTheUpdateField = 3.0; - this->m_GaussianSpatialSmoothingVarianceForTheTotalField = 0.5; - this->m_GaussianTemporalSmoothingVarianceForTheUpdateField = 0.25; - this->m_GaussianTemporalSmoothingVarianceForTheTotalField = 0.0; } template<typename TScalar, unsigned int NDimensions> diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInverseDisplacementFieldImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInverseDisplacementFieldImageFilter.hxx index c9ca36094a9f2a13ff006eeab2e0e1e7191f8cc9..230f744284c5badda04f6f03ce7ee1f796bf84e1 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInverseDisplacementFieldImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInverseDisplacementFieldImageFilter.hxx @@ -134,7 +134,6 @@ InverseDisplacementFieldImageFilter< TInputImage, TOutputImage > typedef typename InputImageType::RegionType InputRegionType; typedef typename InputImageType::SizeType InputSizeType; - typedef typename InputImageType::IndexType InputIndexType; InputRegionType region; diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.h b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.h index 5696eadb00510f97cb275daf04dbf715334aa6e3..84550bc3f056703983ca2d6edda1e632d1d071b4 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.h @@ -20,6 +20,8 @@ #include "itkImageToImageFilter.h" #include "itkVectorInterpolateImageFunction.h" +#include "itkVectorLinearInterpolateImageFunction.h" +#include "itkSimpleFastMutexLock.h" namespace itk { @@ -73,6 +75,8 @@ public: typedef typename VectorType::ComponentType RealType; typedef Image<RealType, ImageDimension> RealImageType; typedef VectorInterpolateImageFunction<InputFieldType, RealType> InterpolatorType; + typedef VectorLinearInterpolateImageFunction <InputFieldType, RealType> + DefaultInterpolatorType; /** Get the interpolator. */ itkGetModifiableObjectMacro( Interpolator, InterpolatorType ); @@ -169,6 +173,7 @@ private: SpacingType m_DisplacementFieldSpacing; bool m_DoThreadedEstimateInverse; bool m_EnforceBoundaryCondition; + SimpleFastMutexLock m_Mutex; }; diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.hxx index 0103d31ea18d371e2b8be14e31a2fb942ec1bcbd..75258d23ef53637cd439f55b9350361413594baa 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkInvertDisplacementFieldImageFilter.hxx @@ -23,7 +23,7 @@ #include "itkComposeDisplacementFieldsImageFilter.h" #include "itkImageDuplicator.h" #include "itkImageRegionIterator.h" -#include "itkVectorLinearInterpolateImageFunction.h" +#include "itkMutexLockHolder.h" namespace itk { @@ -34,19 +34,20 @@ namespace itk template<typename TInputImage, typename TOutputImage> InvertDisplacementFieldImageFilter<TInputImage, TOutputImage> ::InvertDisplacementFieldImageFilter() : - m_MaximumNumberOfIterations( 20 ), - m_MaxErrorToleranceThreshold( 0.1 ), - m_MeanErrorToleranceThreshold( 0.001 ) + m_Interpolator(DefaultInterpolatorType::New()), + m_MaximumNumberOfIterations(20), + m_MaxErrorToleranceThreshold(0.1), + m_MeanErrorToleranceThreshold(0.001), + + m_ComposedField(DisplacementFieldType::New()), + m_ScaledNormImage(RealImageType::New()), + m_MaxErrorNorm(0.0), + m_MeanErrorNorm(0.0), + m_Epsilon(0.0), + m_DoThreadedEstimateInverse(false), + m_EnforceBoundaryCondition(true) { this->SetNumberOfRequiredInputs( 1 ); - - typedef VectorLinearInterpolateImageFunction <InputFieldType, RealType> DefaultInterpolatorType; - typename DefaultInterpolatorType::Pointer interpolator = DefaultInterpolatorType::New(); - this->m_Interpolator = interpolator; - - this->m_ComposedField = DisplacementFieldType::New(); - this->m_ScaledNormImage = RealImageType::New(); - this->m_EnforceBoundaryCondition = true; } template<typename TInputImage, typename TOutputImage> @@ -109,8 +110,9 @@ InvertDisplacementFieldImageFilter<TInputImage, TOutputImage> this->m_ScaledNormImage->CopyInformation( displacementField ); this->m_ScaledNormImage->SetRegions( displacementField->GetRequestedRegion() ); - this->m_ScaledNormImage->Allocate(); - this->m_ScaledNormImage->FillBuffer( 0.0 ); + this->m_ScaledNormImage->Allocate(true); // initialize + // buffer + // to zero SizeValueType numberOfPixelsInRegion = ( displacementField->GetRequestedRegion() ).GetNumberOfPixels(); this->m_MaxErrorNorm = NumericTraits<RealType>::max(); @@ -211,6 +213,8 @@ InvertDisplacementFieldImageFilter<TInputImage, TOutputImage> else { VectorType inverseSpacing; + RealType localMean = NumericTraits<RealType>::Zero; + RealType localMax = NumericTraits<RealType>::Zero; for( unsigned int d = 0; d < ImageDimension; ++d ) { inverseSpacing[d]=1.0/this->m_DisplacementFieldSpacing[d]; @@ -223,17 +227,25 @@ InvertDisplacementFieldImageFilter<TInputImage, TOutputImage> { scaledNorm += vnl_math_sqr( displacement[d] * inverseSpacing[d] ); } - scaledNorm = vcl_sqrt( scaledNorm ); + scaledNorm = std::sqrt( scaledNorm ); - this->m_MeanErrorNorm += scaledNorm; - if( this->m_MaxErrorNorm < scaledNorm ) + localMean += scaledNorm; + if( localMax < scaledNorm ) { - this->m_MaxErrorNorm = scaledNorm; + localMax = scaledNorm; } ItS.Set( scaledNorm ); ItE.Set( -displacement ); } + { + MutexLockHolder<SimpleFastMutexLock> holder(m_Mutex); + this->m_MeanErrorNorm += localMean; + if( this->m_MaxErrorNorm < localMax ) + { + this->m_MaxErrorNorm = localMax; + } + } } } @@ -244,8 +256,7 @@ InvertDisplacementFieldImageFilter<TInputImage, TOutputImage> { Superclass::PrintSelf( os, indent ); - os << "Interpolator:" << std::endl; - this->m_Interpolator->Print( os, indent ); + itkPrintSelfObjectMacro( Interpolator ); os << "Maximum number of iterations: " << this->m_MaximumNumberOfIterations << std::endl; os << "Max error tolerance threshold: " << this->m_MaxErrorToleranceThreshold << std::endl; diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkIterativeInverseDisplacementFieldImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkIterativeInverseDisplacementFieldImageFilter.hxx index 98eaa4e18c7e9f285a0f1593bf8ce8168c9fc676..6012b41e1a314ddd5a184a132dd7d68101ca4783 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkIterativeInverseDisplacementFieldImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkIterativeInverseDisplacementFieldImageFilter.hxx @@ -146,9 +146,9 @@ void IterativeInverseDisplacementFieldImageFilter< TInputImage, TOutputImage > smallestError = 0; for ( unsigned int j = 0; j < ImageDimension; j++ ) { - smallestError += vcl_pow(mappedPoint[j] + forwardVector[j] - originalPoint[j], 2); + smallestError += std::pow(mappedPoint[j] + forwardVector[j] - originalPoint[j], 2); } - smallestError = vcl_sqrt(smallestError); + smallestError = std::sqrt(smallestError); } // iteration loop @@ -170,9 +170,9 @@ void IterativeInverseDisplacementFieldImageFilter< TInputImage, TOutputImage > tmp = 0; for ( unsigned int l = 0; l < ImageDimension; l++ ) { - tmp += vcl_pow(mappedPoint[l] + forwardVector[l] - originalPoint[l], 2); + tmp += std::pow(mappedPoint[l] + forwardVector[l] - originalPoint[l], 2); } - tmp = vcl_sqrt(tmp); + tmp = std::sqrt(tmp); if ( tmp < smallestError ) { smallestError = tmp; @@ -190,9 +190,9 @@ void IterativeInverseDisplacementFieldImageFilter< TInputImage, TOutputImage > tmp = 0; for ( unsigned int l = 0; l < ImageDimension; l++ ) { - tmp += vcl_pow(mappedPoint[l] + forwardVector[l] - originalPoint[l], 2); + tmp += std::pow(mappedPoint[l] + forwardVector[l] - originalPoint[l], 2); } - tmp = vcl_sqrt(tmp); + tmp = std::sqrt(tmp); if ( tmp < smallestError ) { smallestError = tmp; diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingBSplineVelocityFieldTransform.h b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingBSplineVelocityFieldTransform.h index d2dbfd4e35576e3302cbac1fd0023683fea39bcf..4e866137e61d85298f95120d8a9ed3347dff94d0 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingBSplineVelocityFieldTransform.h +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingBSplineVelocityFieldTransform.h @@ -79,7 +79,7 @@ public: itkTypeMacro( TimeVaryingBSplineVelocityFieldTransform, VelocityFieldTransform ); /** New macro for creation of through a Smart Pointer */ - itkSimpleNewMacro( Self ); + itkNewMacro( Self ); /** InverseTransform type. */ typedef typename Superclass::InverseTransformBasePointer InverseTransformBasePointer; diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingBSplineVelocityFieldTransform.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingBSplineVelocityFieldTransform.hxx index 446f448a62b76f2ade820c83a3a9f45f3193aa67..80f3d186ab69c45f9581ba624abee4e3219efee0 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingBSplineVelocityFieldTransform.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingBSplineVelocityFieldTransform.hxx @@ -109,6 +109,7 @@ TimeVaryingBSplineVelocityFieldTransform<TScalar, NDimensions> inverseIntegrator->SetInput( bspliner->GetOutput() ); inverseIntegrator->SetLowerTimeBound( this->GetUpperTimeBound() ); inverseIntegrator->SetUpperTimeBound( this->GetLowerTimeBound() ); + if( this->GetVelocityFieldInterpolator() ) { inverseIntegrator->SetVelocityFieldInterpolator( this->GetModifiableVelocityFieldInterpolator() ); diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingVelocityFieldIntegrationImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingVelocityFieldIntegrationImageFilter.hxx index 8cc010bdec83a5dc63dfd3db2b6c2ae58b1b25f8..33d8ffc0e19b871ff11b38be8cecfc455e23e790 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingVelocityFieldIntegrationImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTimeVaryingVelocityFieldIntegrationImageFilter.hxx @@ -93,7 +93,6 @@ TimeVaryingVelocityFieldIntegrationImageFilter typedef typename DisplacementFieldType::SpacingType SpacingType; typedef typename DisplacementFieldType::PointType OriginType; typedef typename DisplacementFieldType::DirectionType DirectionType; - typedef typename DisplacementFieldType::RegionType RegionType; SizeType size; SpacingType spacing; diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTransformToDisplacementFieldFilter.h b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTransformToDisplacementFieldFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..96efc5996b41a96a42d19b920c2183092112f2a4 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTransformToDisplacementFieldFilter.h @@ -0,0 +1,201 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkTransformToDisplacementFieldFilter_h +#define __itkTransformToDisplacementFieldFilter_h + +#include "itkDataObjectDecorator.h" +#include "itkTransform.h" +#include "itkImageSource.h" + +namespace itk +{ +/** \class TransformToDisplacementFieldFilter + * \brief Generate a displacement field from a coordinate transform + * + * Output information (spacing, size and direction) for the output + * image should be set. This information has the normal defaults of + * unit spacing, zero origin and identity direction. Optionally, the + * output information can be obtained from a reference image. If the + * reference image is provided and UseReferenceImage is On, then the + * spacing, origin and direction of the reference image will be used. + * + * Since this filter produces an image which is a different size than + * its input, it needs to override several of the methods defined + * in ProcessObject in order to properly manage the pipeline execution model. + * In particular, this filter overrides + * ProcessObject::GenerateOutputInformation(). + * + * This filter is implemented as a multithreaded filter. It provides a + * ThreadedGenerateData() method for its implementation. + * + * \author Marius Staring, Leiden University Medical Center, The Netherlands. + * + * This class was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/1387 + * + * \ingroup GeometricTransform + * \ingroup ITKDisplacementField + */ +template< typename TOutputImage, + typename TScalar = double > +class TransformToDisplacementFieldFilter: + public ImageSource< TOutputImage > +{ +public: + /** Standard class typedefs. */ + typedef TransformToDisplacementFieldFilter Self; + typedef ImageSource< TOutputImage > Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + typedef TOutputImage OutputImageType; + typedef typename OutputImageType::RegionType OutputImageRegionType; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(TransformToDisplacementFieldFilter, ImageSource); + + /** Number of dimensions. */ + itkStaticConstMacro(ImageDimension, unsigned int, TOutputImage::ImageDimension); + + /** Typedefs for transform. */ + typedef Transform< TScalar, ImageDimension, ImageDimension > TransformType; + typedef DataObjectDecorator< TransformType > TransformInputType; + + /** Typedefs for output image. */ + typedef typename OutputImageType::PixelType PixelType; + typedef typename PixelType::ValueType PixelValueType; + typedef typename OutputImageType::RegionType RegionType; + typedef typename RegionType::SizeType SizeType; + typedef typename OutputImageType::IndexType IndexType; + typedef typename OutputImageType::PointType PointType; + typedef typename OutputImageType::SpacingType SpacingType; + typedef typename OutputImageType::PointType OriginType; + typedef typename OutputImageType::DirectionType DirectionType; + + /** Typedef the reference image ImageBase. */ + typedef ImageBase< ImageDimension > ReferenceImageBaseType; + + /** Get/Set the coordinate transformation. + * Set the coordinate transform to use for resampling. Note that this must + * be in physical coordinates and it is the output-to-input transform, NOT + * the input-to-output transform that you might naively expect. */ + using Superclass::SetInput; + virtual void SetInput( const TransformInputType * transform ); + const TransformInputType * GetInput() const; + itkSetGetDecoratedObjectInputMacro(Transform, TransformType); + + /** Set/Get the start index of the output largest possible region. + * The default is an index of all zeros. */ + itkSetMacro(OutputStartIndex, IndexType); + itkGetConstReferenceMacro(OutputStartIndex, IndexType); + + /** Set/Get the size of the output image. */ + itkSetMacro(Size, SizeType); + itkGetConstReferenceMacro(Size, SizeType); + + /** Set the output image spacing. */ + itkSetMacro(OutputSpacing, SpacingType); + virtual void SetOutputSpacing(const SpacePrecisionType *values); + + /** Get the output image spacing. */ + itkGetConstReferenceMacro(OutputSpacing, SpacingType); + + /** Set the output image origin. */ + itkSetMacro(OutputOrigin, OriginType); + virtual void SetOutputOrigin(const SpacePrecisionType *values); + + /** Get the output image origin. */ + itkGetConstReferenceMacro(OutputOrigin, OriginType); + + /** Set the output direction cosine matrix. */ + itkSetMacro(OutputDirection, DirectionType); + itkGetConstReferenceMacro(OutputDirection, DirectionType); + + /** Set a reference image to use to define the output information. + * By default, output information is specificed through the + * SetOutputSpacing, Origin, and Direction methods. Alternatively, + * this method can be used to specify an image from which to + * copy the information. UseReferenceImageOn must be set to utilize the + * reference image. */ + itkSetInputMacro(ReferenceImage, ReferenceImageBaseType); + + /** Get the reference image that is defining the output information. */ + itkGetInputMacro(ReferenceImage, ReferenceImageBaseType); + + /** Turn on/off whether a specified reference image should be used to define + * the output information. */ + itkSetMacro(UseReferenceImage, bool); + itkBooleanMacro(UseReferenceImage); + itkGetConstMacro(UseReferenceImage, bool); + +#ifdef ITK_USE_CONCEPT_CHECKING + // Begin concept checking + itkStaticConstMacro(PixelDimension, unsigned int, + PixelType::Dimension); + itkConceptMacro( SameDimensionCheck, + ( Concept::SameDimension< ImageDimension, PixelDimension > ) ); + // End concept checking +#endif + +protected: + TransformToDisplacementFieldFilter(); + virtual ~TransformToDisplacementFieldFilter() {} + + /** Produces a Vector Image. */ + virtual void GenerateOutputInformation(); + + /** TransformToDisplacementFieldFilter can be implemented as a multithreaded + * filter. + */ + virtual void ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId ); + + /** Default implementation for resampling that works for any + * transformation type. + */ + void NonlinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId ); + + /** Faster implementation for resampling that works for with linear + * transformation types. + */ + void LinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId ); + + virtual void PrintSelf(std::ostream & os, Indent indent) const; + +private: + TransformToDisplacementFieldFilter( const Self & ); //purposely not implemented + void operator=( const Self & ); //purposely not implemented + + /** Member variables. */ + SizeType m_Size; // size of the output region + IndexType m_OutputStartIndex; // start index of the output region + SpacingType m_OutputSpacing; // output image spacing + OriginType m_OutputOrigin; // output image origin + DirectionType m_OutputDirection; // output image direction cosines + bool m_UseReferenceImage; + +}; +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkTransformToDisplacementFieldFilter.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTransformToDisplacementFieldFilter.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTransformToDisplacementFieldFilter.hxx new file mode 100644 index 0000000000000000000000000000000000000000..2221b00c131ff026107e812ff76f67227aaca7fe --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkTransformToDisplacementFieldFilter.hxx @@ -0,0 +1,300 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkTransformToDisplacementFieldFilter_hxx +#define __itkTransformToDisplacementFieldFilter_hxx + +#include "itkTransformToDisplacementFieldFilter.h" + +#include "itkIdentityTransform.h" +#include "itkProgressReporter.h" +#include "itkImageRegionIteratorWithIndex.h" +#include "itkImageLinearIteratorWithIndex.h" + +namespace itk +{ + +template< typename TOutputImage, typename TScalarType > +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::TransformToDisplacementFieldFilter(): + m_UseReferenceImage( false ) +{ + this->m_OutputSpacing.Fill(1.0); + this->m_OutputOrigin.Fill(0.0); + this->m_OutputDirection.SetIdentity(); + + this->m_Size.Fill(0); + this->m_OutputStartIndex.Fill(0); + + this->SetNumberOfRequiredInputs( 1 ); + this->SetPrimaryInputName( "Transform" ); + + // #1 "ReferenceImage" optional + Self::AddRequiredInputName("ReferenceImage",1); + Self::RemoveRequiredInputName("ReferenceImage"); +} + + +template< typename TOutputImage, typename TScalarType > +void +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Size: " << this->m_Size << std::endl; + os << indent << "OutputStartIndex: " << this->m_OutputStartIndex << std::endl; + os << indent << "OutputSpacing: " << this->m_OutputSpacing << std::endl; + os << indent << "OutputOrigin: " << this->m_OutputOrigin << std::endl; + os << indent << "OutputDirection: " << this->m_OutputDirection << std::endl; + os << indent << "UseReferenceImage: "; + if( this->m_UseReferenceImage ) + { + os << "On" << std::endl; + } + else + { + os << "Off" << std::endl; + } +} + + +template< typename TOutputImage, typename TScalarType > +void +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::SetOutputSpacing(const SpacePrecisionType *spacing) +{ + SpacingType ss(spacing); + this->SetOutputSpacing(ss); +} + + +template< typename TOutputImage, typename TScalarType > +void +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::SetOutputOrigin(const SpacePrecisionType *origin) +{ + OriginType pp(origin); + this->SetOutputOrigin(pp); +} + +template< typename TOutputImage, typename TScalarType > +void +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::SetInput( const TransformInputType * input ) +{ + if( input != itkDynamicCastInDebugMode< TransformInputType * >( this->ProcessObject::GetPrimaryInput() ) ) + { + // Process object is not const-correct so the const_cast is required here + this->ProcessObject::SetNthInput( 0, const_cast< TransformInputType * >( input ) ); + this->Modified(); + } +} + +template< typename TOutputImage, typename TScalarType > +const typename TransformToDisplacementFieldFilter< TOutputImage, TScalarType >::TransformInputType * +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::GetInput() const +{ + return itkDynamicCastInDebugMode< const TransformInputType * >( this->GetPrimaryInput() ); +} + + +template< typename TOutputImage, typename TScalarType > +void +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::GenerateOutputInformation(void) +{ + OutputImageType * output = this->GetOutput(); + if ( !output ) + { + return; + } + + const ReferenceImageBaseType *referenceImage = this->GetReferenceImage(); + + // Set the size of the output region + if ( m_UseReferenceImage && referenceImage ) + { + output->SetLargestPossibleRegion( + referenceImage->GetLargestPossibleRegion() ); + } + else + { + typename TOutputImage::RegionType outputLargestPossibleRegion; + outputLargestPossibleRegion.SetSize(m_Size); + outputLargestPossibleRegion.SetIndex(m_OutputStartIndex); + output->SetLargestPossibleRegion(outputLargestPossibleRegion); + } + + // Set spacing and origin + if ( m_UseReferenceImage && referenceImage ) + { + output->SetSpacing( referenceImage->GetSpacing() ); + output->SetOrigin( referenceImage->GetOrigin() ); + output->SetDirection( referenceImage->GetDirection() ); + } + else + { + output->SetSpacing(m_OutputSpacing); + output->SetOrigin(m_OutputOrigin); + output->SetDirection(m_OutputDirection); + } +} + + +template< typename TOutputImage, typename TScalarType > +void +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId ) +{ + const TransformType * transform = this->GetInput()->Get(); + // Check whether we can use a fast path for resampling. Fast path + // can be used if the transformation is linear. Transform respond + // to the IsLinear() call. + if ( transform->IsLinear() ) + { + this->LinearThreadedGenerateData(outputRegionForThread, threadId); + return; + } + + // Otherwise, we use the normal method where the transform is called + // for computing the transformation of every point. + this->NonlinearThreadedGenerateData(outputRegionForThread, threadId); +} + + +template< typename TOutputImage, typename TScalarType > +void +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::NonlinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId ) +{ + // Get the output pointer + OutputImageType * output = this->GetOutput(); + const TransformType * transform = this->GetInput()->Get(); + + // Create an iterator that will walk the output region for this thread. + typedef ImageRegionIteratorWithIndex< TOutputImage > OutputIteratorType; + OutputIteratorType outIt( output, outputRegionForThread ); + + // Define a few variables that will be used to translate from an input pixel + // to an output pixel + PointType outputPoint; // Coordinates of output pixel + PointType transformedPoint; // Coordinates of transformed pixel + PixelType displacement; // the difference + + // Support for progress methods/callbacks + ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); + + // Walk the output region + outIt.GoToBegin(); + while ( !outIt.IsAtEnd() ) + { + // Determine the index of the current output pixel + output->TransformIndexToPhysicalPoint( outIt.GetIndex(), outputPoint ); + + // Compute corresponding input pixel position + transformedPoint = transform->TransformPoint( outputPoint ); + + displacement = transformedPoint - outputPoint; + + // Set it + outIt.Set( displacement ); + + // Update progress and iterator + progress.CompletedPixel(); + ++outIt; + } +} + + +template< typename TOutputImage, typename TScalarType > +void +TransformToDisplacementFieldFilter< TOutputImage, TScalarType > +::LinearThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, ThreadIdType threadId ) +{ + // Get the output pointer + OutputImageType * output = this->GetOutput(); + const TransformType * transform = this->GetInput()->Get(); + + // Create an iterator that will walk the output region for this thread. + typedef ImageLinearIteratorWithIndex< TOutputImage > OutputIteratorType; + OutputIteratorType outIt( output, outputRegionForThread ); + + outIt.SetDirection(0); + + // Define a few indices that will be used to translate from an input pixel + // to an output pixel + PointType outputPoint; // Coordinates of current output pixel + PointType transformedPoint; // Coordinates of transformed pixel + PixelType displacement; // the difference + + IndexType index; + + // Support for progress methods/callbacks + ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); + + // Determine the position of the first pixel in the scanline + outIt.GoToBegin(); + index = outIt.GetIndex(); + output->TransformIndexToPhysicalPoint( index, outputPoint ); + + // Compute corresponding transformed pixel position + transformedPoint = transform->TransformPoint( outputPoint ); + + // Compare with the ResampleImageFilter + + // Compute delta + PointType outputPointNeighbour; + PointType transformedPointNeighbour; + typedef typename PointType::VectorType VectorType; + VectorType delta; + ++index[0]; + output->TransformIndexToPhysicalPoint( index, outputPointNeighbour ); + transformedPointNeighbour = transform->TransformPoint( outputPointNeighbour ); + delta = transformedPointNeighbour - transformedPoint - ( outputPointNeighbour - outputPoint ); + + // loop over the vector image + while ( !outIt.IsAtEnd() ) + { + // Get current point + index = outIt.GetIndex(); + output->TransformIndexToPhysicalPoint( index, outputPoint ); + + // Compute transformed point + transformedPoint = transform->TransformPoint( outputPoint ); + + while ( !outIt.IsAtEndOfLine() ) + { + displacement = transformedPoint - outputPoint; + + // Set it + outIt.Set( displacement ); + + // Update stuff + progress.CompletedPixel(); + ++outIt; + transformedPoint += delta; + } + + outIt.NextLine(); + } +} + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkVelocityFieldTransform.hxx b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkVelocityFieldTransform.hxx index b20e67601433a7efeebbfef8110c146ccc49f8a2..ef86cd8c50755ddccd37fac56e060d9e6eff6a7b 100644 --- a/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkVelocityFieldTransform.hxx +++ b/Utilities/ITK/Modules/Filtering/DisplacementField/include/itkVelocityFieldTransform.hxx @@ -116,7 +116,7 @@ VelocityFieldTransform<TScalar, NDimensions> } else { - return NULL; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkApproximateSignedDistanceMapImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkApproximateSignedDistanceMapImageFilter.hxx index 9601c9e87bfd9755733d9c2ab492bbe3b0c15152..acc07811a311844405c932bca964aba785060156 100644 --- a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkApproximateSignedDistanceMapImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkApproximateSignedDistanceMapImageFilter.hxx @@ -23,7 +23,6 @@ #include "itkNumericTraits.h" #include "itkImageScanlineIterator.h" #include "itkProgressAccumulator.h" -#include "vcl_cmath.h" namespace itk { @@ -70,7 +69,7 @@ ApproximateSignedDistanceMapImageFilter< TInputImage, TOutputImage > // double, // which is the general SizeValueType. maximumDistance = - static_cast< OutputSizeValueType >( vcl_sqrt( static_cast< double >( maximumDistance ) ) ); + static_cast< OutputSizeValueType >( std::sqrt( static_cast< double >( maximumDistance ) ) ); // Allocate the output this->AllocateOutputs(); diff --git a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkContourDirectedMeanDistanceImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkContourDirectedMeanDistanceImageFilter.hxx index 98fa990c6d196d856aad89da08d8b0a8261d8e24..269670486dd13c3092acb1188735d4cfec835acc 100644 --- a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkContourDirectedMeanDistanceImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkContourDirectedMeanDistanceImageFilter.hxx @@ -38,7 +38,7 @@ ContourDirectedMeanDistanceImageFilter< TInputImage1, TInputImage2 > this->SetNumberOfRequiredInputs(2); m_UseImageSpacing = true; - m_DistanceMap = NULL; + m_DistanceMap = ITK_NULLPTR; m_ContourDirectedMeanDistance = NumericTraits< RealType >::Zero; } diff --git a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkDanielssonDistanceMapImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkDanielssonDistanceMapImageFilter.hxx index f42132093141dbf643ee752899ee43ad4dcf1cbe..bb356f960c0bfc5b0aa91fcb05e0bfe4c8ddfb88 100644 --- a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkDanielssonDistanceMapImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkDanielssonDistanceMapImageFilter.hxx @@ -296,7 +296,7 @@ DanielssonDistanceMapImageFilter< TInputImage, TOutputImage, TVoronoiImage > } else { - dt.Set( static_cast< OutputPixelType >( vcl_sqrt(distance) ) ); + dt.Set( static_cast< OutputPixelType >( std::sqrt(distance) ) ); } ++ot; ++ct; diff --git a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.hxx index c8efb0b7c3d6427c0e1c78dd10a17a2571c3832d..2bbde651d1f70d5d93fd10a5d8c492e1531ef53b 100644 --- a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkDirectedHausdorffDistanceImageFilter.hxx @@ -32,7 +32,7 @@ DirectedHausdorffDistanceImageFilter< TInputImage1, TInputImage2 > // this filter requires two input images this->SetNumberOfRequiredInputs(2); - m_DistanceMap = NULL; + m_DistanceMap = ITK_NULLPTR; m_DirectedHausdorffDistance = NumericTraits< RealType >::Zero; m_AverageHausdorffDistance = NumericTraits< RealType >::Zero; m_UseImageSpacing = true; @@ -182,7 +182,7 @@ DirectedHausdorffDistanceImageFilter< TInputImage1, TInputImage2 > } // clean up - m_DistanceMap = NULL; + m_DistanceMap = ITK_NULLPTR; } template< typename TInputImage1, typename TInputImage2 > diff --git a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkFastChamferDistanceImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkFastChamferDistanceImageFilter.hxx index 47ab7e514c4734f18cbb30fed3dac8e4be178f42..7053f7c508f703f240e2df1914046d8609587dc7 100644 --- a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkFastChamferDistanceImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkFastChamferDistanceImageFilter.hxx @@ -46,12 +46,12 @@ FastChamferDistanceImageFilter< TInputImage, TOutputImage > itkWarningMacro(<< "Dimension " << ImageDimension << " with Default weights "); for ( unsigned int i = 1; i <= ImageDimension; i++ ) { - m_Weights[i - 1] = vcl_sqrt( static_cast< float >( i ) ); + m_Weights[i - 1] = std::sqrt( static_cast< float >( i ) ); } } m_MaximumDistance = 10.0; - m_NarrowBand = 0; + m_NarrowBand = ITK_NULLPTR; } template< typename TInputImage, typename TOutputImage > @@ -214,7 +214,7 @@ void FastChamferDistanceImageFilter< TInputImage, TOutputImage > // Update the narrow band if ( m_NarrowBand.IsNotNull() ) { - if ( vcl_fabs( (float)center_value ) <= m_NarrowBand->GetTotalRadius() ) + if ( std::fabs( (float)center_value ) <= m_NarrowBand->GetTotalRadius() ) { node.m_Index = it.GetIndex(); //Check node state. @@ -223,7 +223,7 @@ void FastChamferDistanceImageFilter< TInputImage, TOutputImage > { node.m_NodeState += SIGN_MASK; } - if ( vcl_fabs( (float)center_value ) < m_NarrowBand->GetInnerRadius() ) + if ( std::fabs( (float)center_value ) < m_NarrowBand->GetInnerRadius() ) { node.m_NodeState += INNER_MASK; } diff --git a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkIsoContourDistanceImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkIsoContourDistanceImageFilter.hxx index ef0a303df403a0b365907d0226c47212635f913c..b0eb71d4c2a2b974b6fd88fed5b153a91bbe676e 100644 --- a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkIsoContourDistanceImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkIsoContourDistanceImageFilter.hxx @@ -37,7 +37,7 @@ IsoContourDistanceImageFilter< TInputImage, TOutputImage > m_FarValue = 10 * NumericTraits< PixelType >::One; m_NarrowBanding = false; - m_NarrowBand = NULL; + m_NarrowBand = ITK_NULLPTR; m_Barrier = Barrier::New(); } @@ -263,8 +263,6 @@ IsoContourDistanceImageFilter< TInputImage, TOutputImage > //3. Computation over the narrowband ConstBandIterator bandIt = m_NarrowBandRegion[threadId].Begin; ConstBandIterator bandEnd = m_NarrowBandRegion[threadId].End; - typedef ImageRegionConstIterator< InputImageType > ConstIteratorType; - typedef ImageRegionIterator< OutputImageType > IteratorType; unsigned int n; @@ -371,20 +369,20 @@ IsoContourDistanceImageFilter< TInputImage, TOutputImage > grad[ng] = ( grad0[ng] * alpha0 + grad1[ng] * alpha1 ) / ( 2. * static_cast< PixelRealType >( m_Spacing[ng] ) ); norm += grad[ng] * grad[ng]; } - norm = vcl_sqrt( norm ); + norm = std::sqrt( norm ); if ( norm > NumericTraits< PixelRealType >::min() ) { - PixelRealType val = vcl_fabs( grad[n] ) * m_Spacing[n] / norm / diff; + PixelRealType val = std::fabs( grad[n] ) * m_Spacing[n] / norm / diff; PixelRealType valNew0 = val0 * val; PixelRealType valNew1 = val1 * val; - if ( vcl_fabs( static_cast< double >( valNew0 ) ) < vcl_fabs( static_cast< double >( outNeigIt.GetNext(n, 0) ) ) ) + if ( std::fabs( static_cast< double >( valNew0 ) ) < std::fabs( static_cast< double >( outNeigIt.GetNext(n, 0) ) ) ) { outNeigIt.SetNext( n, 0, static_cast< PixelType >( valNew0 ) ); } - if ( vcl_fabs( static_cast< double >( valNew1 ) ) < vcl_fabs( static_cast< double >( outNeigIt.GetNext(n, 1) ) ) ) + if ( std::fabs( static_cast< double >( valNew1 ) ) < std::fabs( static_cast< double >( outNeigIt.GetNext(n, 1) ) ) ) { outNeigIt.SetNext( n, 1, static_cast< PixelType >( valNew1 ) ); } diff --git a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkReflectiveImageRegionConstIterator.hxx b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkReflectiveImageRegionConstIterator.hxx index 0ca9cf5782344f9d2482eb627d98ea686d07fed5..7df49bc00c91b7d881c926d51a8a6b9ec72bb697 100644 --- a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkReflectiveImageRegionConstIterator.hxx +++ b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkReflectiveImageRegionConstIterator.hxx @@ -52,7 +52,7 @@ template< typename TImage > ReflectiveImageRegionConstIterator< TImage > ::ReflectiveImageRegionConstIterator(const Self & it) { - this->Operator = ( it ); + this->operator= ( it ); this->GoToBegin(); } diff --git a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkSignedMaurerDistanceMapImageFilter.hxx b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkSignedMaurerDistanceMapImageFilter.hxx index ed748aff2cf781cc71c1fe6f90d827dc825eb20f..c07d550296f9261ba68e6d5d0e4b31f032e4ea9b 100644 --- a/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkSignedMaurerDistanceMapImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/DistanceMap/include/itkSignedMaurerDistanceMapImageFilter.hxx @@ -34,9 +34,11 @@ SignedMaurerDistanceMapImageFilter< TInputImage, TOutputImage > ::SignedMaurerDistanceMapImageFilter(): m_BackgroundValue( NumericTraits< InputPixelType >::Zero ), m_Spacing(0.0), + m_CurrentDimension(0), m_InsideIsPositive(false), m_UseImageSpacing(true), - m_SquaredDistance(false) + m_SquaredDistance(false), + m_InputCache(ITK_NULLPTR) {} template< typename TInputImage, typename TOutputImage > @@ -79,9 +81,9 @@ SignedMaurerDistanceMapImageFilter< TInputImage, TOutputImage > double range = static_cast< double >( requestedRegionSize[splitAxis] ); unsigned int valuesPerThread = - static_cast< unsigned int >( vcl_ceil( range / static_cast< double >( num ) ) ); + static_cast< unsigned int >( std::ceil( range / static_cast< double >( num ) ) ); unsigned int maxThreadIdUsed = - static_cast< unsigned int >( vcl_ceil( range / static_cast< double >( valuesPerThread ) ) ) - 1; + static_cast< unsigned int >( std::ceil( range / static_cast< double >( valuesPerThread ) ) ) - 1; // Split the region if ( i < maxThreadIdUsed ) @@ -286,7 +288,7 @@ SignedMaurerDistanceMapImageFilter< TInputImage, TOutputImage > // cast to a real type is required on some platforms const OutputPixelType outputValue = static_cast< OutputPixelType >( - vcl_sqrt( static_cast< OutputRealType >( vnl_math_abs( Ot.Get() ) ) ) ); + std::sqrt( static_cast< OutputRealType >( vnl_math_abs( Ot.Get() ) ) ) ); if ( It.Get() != this->m_BackgroundValue ) { diff --git a/Utilities/ITK/Modules/Filtering/FFT/include/itkFFTWCommon.h b/Utilities/ITK/Modules/Filtering/FFT/include/itkFFTWCommon.h index 90546b447c0535c76ee7f77b8731121bf6a8b144..ad0dfea2d501b3ddc6bf6109e9ec4862a9766d1d 100644 --- a/Utilities/ITK/Modules/Filtering/FFT/include/itkFFTWCommon.h +++ b/Utilities/ITK/Modules/Filtering/FFT/include/itkFFTWCommon.h @@ -130,7 +130,7 @@ public: roflags = flags | FFTW_WISDOM_ONLY; } PlanType plan = fftwf_plan_dft_c2r(rank,n,in,out,roflags); - if( plan == NULL ) + if( plan == ITK_NULLPTR ) { // no wisdom available for that plan if( canDestroyInput ) @@ -222,7 +222,7 @@ public: roflags = flags | FFTW_WISDOM_ONLY; } PlanType plan = fftwf_plan_dft_r2c(rank,n,in,out,roflags); - if( plan == NULL ) + if( plan == ITK_NULLPTR ) { // no wisdom available for that plan if( canDestroyInput ) @@ -316,7 +316,7 @@ public: roflags = flags | FFTW_WISDOM_ONLY; } PlanType plan = fftwf_plan_dft(rank,n,in,out,sign,roflags); - if( plan == NULL ) + if( plan == ITK_NULLPTR ) { // no wisdom available for that plan if( canDestroyInput ) @@ -431,7 +431,7 @@ public: roflags = flags | FFTW_WISDOM_ONLY; } PlanType plan = fftw_plan_dft_c2r(rank,n,in,out,roflags); - if( plan == NULL ) + if( plan == ITK_NULLPTR ) { // no wisdom available for that plan if( canDestroyInput ) @@ -522,7 +522,7 @@ public: roflags = flags | FFTW_WISDOM_ONLY; } PlanType plan = fftw_plan_dft_r2c(rank,n,in,out,roflags); - if( plan == NULL ) + if( plan == ITK_NULLPTR ) { // no wisdom available for that plan if( canDestroyInput ) @@ -616,7 +616,7 @@ public: roflags = flags | FFTW_WISDOM_ONLY; } PlanType plan = fftw_plan_dft(rank,n,in,out,sign,roflags); - if( plan == NULL ) + if( plan == ITK_NULLPTR ) { // no wisdom available for that plan if( canDestroyInput ) diff --git a/Utilities/ITK/Modules/Filtering/FFT/include/itkFFTWGlobalConfiguration.h b/Utilities/ITK/Modules/Filtering/FFT/include/itkFFTWGlobalConfiguration.h index 391e6804b5be01e15865fc29d66043e1e678dede..5ac65252a16fb5fe9ae5fd689725eb0e049890f7 100644 --- a/Utilities/ITK/Modules/Filtering/FFT/include/itkFFTWGlobalConfiguration.h +++ b/Utilities/ITK/Modules/Filtering/FFT/include/itkFFTWGlobalConfiguration.h @@ -83,7 +83,7 @@ class ManualWisdomFilenameGenerator: public WisdomFilenameGeneratorBase { this->m_WisdomFilename=wfn; } - virtual std::string GenerateWisdomFilename(const std::string itkNotUsed(baseCacheDirectory) ) const + virtual std::string GenerateWisdomFilename(const std::string itkNotUsed(baseCacheDirectory) ) const ITK_OVERRIDE { return this->m_WisdomFilename; } @@ -94,7 +94,7 @@ class ManualWisdomFilenameGenerator: public WisdomFilenameGeneratorBase class SimpleWisdomFilenameGenerator: public WisdomFilenameGeneratorBase { public: - virtual std::string GenerateWisdomFilename(const std::string baseCacheDirectory) const + virtual std::string GenerateWisdomFilename(const std::string baseCacheDirectory) const ITK_OVERRIDE { return baseCacheDirectory+FFTWPathSep+".itksimple.wisdom"; } @@ -103,7 +103,7 @@ class SimpleWisdomFilenameGenerator: public WisdomFilenameGeneratorBase class HostnameWisdomFilenameGenerator: public WisdomFilenameGeneratorBase { public: - virtual std::string GenerateWisdomFilename(const std::string baseCacheDirectory) const + virtual std::string GenerateWisdomFilename(const std::string baseCacheDirectory) const ITK_OVERRIDE { itksys::SystemInformation hostInfo; @@ -130,7 +130,7 @@ public: m_UseSteppingCode(true) {} - virtual std::string GenerateWisdomFilename(const std::string baseCacheDirectory) const + virtual std::string GenerateWisdomFilename(const std::string baseCacheDirectory) const ITK_OVERRIDE { //Now build the hardware string by system interogation itksys::SystemInformation hardwareInfo; diff --git a/Utilities/ITK/Modules/Filtering/FFT/src/itkFFTWGlobalConfiguration.cxx b/Utilities/ITK/Modules/Filtering/FFT/src/itkFFTWGlobalConfiguration.cxx index 3d8fd71169aa56f00ec528c7bb69014a90aa4519..b513f92c17c4dbf3e7e1d70cdf2f9b6ce677d951 100644 --- a/Utilities/ITK/Modules/Filtering/FFT/src/itkFFTWGlobalConfiguration.cxx +++ b/Utilities/ITK/Modules/Filtering/FFT/src/itkFFTWGlobalConfiguration.cxx @@ -88,7 +88,7 @@ static bool isDeclineString(std::string response) } itk::SimpleFastMutexLock itk::FFTWGlobalConfiguration::m_CreationLock; -itk::FFTWGlobalConfiguration::Pointer itk::FFTWGlobalConfiguration::m_Instance=NULL; +itk::FFTWGlobalConfiguration::Pointer itk::FFTWGlobalConfiguration::m_Instance=ITK_NULLPTR; FFTWGlobalConfiguration::Pointer FFTWGlobalConfiguration diff --git a/Utilities/ITK/Modules/Filtering/FFT/wrapping/itkFFTWGlobalConfiguration.wrap b/Utilities/ITK/Modules/Filtering/FFT/wrapping/itkFFTWGlobalConfiguration.wrap index d9ec81a1df975fc23c76ac3b162cd1f011d90051..d8629933df2267a27eaa8b2f54aee98a4d191cc9 100644 --- a/Utilities/ITK/Modules/Filtering/FFT/wrapping/itkFFTWGlobalConfiguration.wrap +++ b/Utilities/ITK/Modules/Filtering/FFT/wrapping/itkFFTWGlobalConfiguration.wrap @@ -7,4 +7,5 @@ if(ITK_USE_FFTWF OR ITK_USE_FFTWD) itk_wrap_simple_class("itk::SimpleWisdomFilenameGenerator") itk_wrap_simple_class("itk::HostnameWisdomFilenameGenerator") itk_wrap_simple_class("itk::HardwareWisdomFilenameGenerator") + itk_wrap_simple_class("itk::SimpleFastMutexLock") endif() diff --git a/Utilities/ITK/Modules/Filtering/FFT/wrapping/itkMagnitudeAndPhaseToComplexImageFilter.wrap b/Utilities/ITK/Modules/Filtering/FFT/wrapping/itkMagnitudeAndPhaseToComplexImageFilter.wrap new file mode 100644 index 0000000000000000000000000000000000000000..f25dc6060bb08e47f5522286b2a7158f8be1b4c5 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/FFT/wrapping/itkMagnitudeAndPhaseToComplexImageFilter.wrap @@ -0,0 +1,9 @@ +itk_wrap_class("itk::MagnitudeAndPhaseToComplexImageFilter" POINTER_WITH_SUPERCLASS) + foreach(d ${ITK_WRAP_DIMS}) + foreach(t ${WRAP_ITK_REAL}) + foreach(c ${WRAP_ITK_COMPLEX_REAL}) + itk_wrap_template("${ITKM_I${t}${d}}${ITKM_I${t}${d}}${ITKM_I${c}${d}}" "${ITKT_I${t}${d}},${ITKT_I${t}${d}},${ITKT_I${c}${d}}") + endforeach(c) + endforeach(t) + endforeach(d) +itk_end_wrap_class() diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingBase.hxx b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingBase.hxx index e76a1c55bef80f7199b4f92847ff2f88df91105d..e78c05bd962cec4967c071f502543ca1b5be7f42 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingBase.hxx +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingBase.hxx @@ -33,10 +33,10 @@ FastMarchingBase() { this->ProcessObject::SetNumberOfRequiredInputs(0); - m_TrialPoints = NULL; - m_AlivePoints = NULL; - m_ProcessedPoints = NULL; - m_ForbiddenPoints = NULL; + m_TrialPoints = ITK_NULLPTR; + m_AlivePoints = ITK_NULLPTR; + m_ProcessedPoints = ITK_NULLPTR; + m_ForbiddenPoints = ITK_NULLPTR; //m_Heap = PriorityQueueType::New(); m_SpeedConstant = 1.; diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingExtensionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingExtensionImageFilter.hxx index ad699889e9a839d19620cf5f2e51d7911bd7b19b..56c9656642aeed375acc1969e8e0383e2a718e9b 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingExtensionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingExtensionImageFilter.hxx @@ -27,8 +27,8 @@ template< typename TLevelSet, typename TAuxValue, unsigned int VAuxDimension, FastMarchingExtensionImageFilter< TLevelSet, TAuxValue, VAuxDimension, TSpeedImage > ::FastMarchingExtensionImageFilter() { - m_AuxAliveValues = NULL; - m_AuxTrialValues = NULL; + m_AuxAliveValues = ITK_NULLPTR; + m_AuxTrialValues = ITK_NULLPTR; this->ProcessObject::SetNumberOfRequiredOutputs(1 + AuxDimension); @@ -66,7 +66,7 @@ FastMarchingExtensionImageFilter< TLevelSet, TAuxValue, VAuxDimension, TSpeedIma { if ( idx >= AuxDimension || this->GetNumberOfIndexedOutputs() < idx + 2 ) { - return NULL; + return ITK_NULLPTR; } return this->m_AuxImages[idx]; diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingExtensionImageFilterBase.hxx b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingExtensionImageFilterBase.hxx index 9c929658c8b6812cf84f4ff19fac332e9bda2bfd..1227e6d0fdb06786303d3ebc8e207ee4118567f7 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingExtensionImageFilterBase.hxx +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingExtensionImageFilterBase.hxx @@ -28,8 +28,8 @@ template< typename TInput, typename TOutput, FastMarchingExtensionImageFilterBase< TInput, TOutput, TAuxValue, VAuxDimension > ::FastMarchingExtensionImageFilterBase() { - m_AuxiliaryAliveValues = NULL; - m_AuxiliaryTrialValues = NULL; + m_AuxiliaryAliveValues = ITK_NULLPTR; + m_AuxiliaryTrialValues = ITK_NULLPTR; this->ProcessObject::SetNumberOfRequiredOutputs(1 + AuxDimension); @@ -38,7 +38,7 @@ FastMarchingExtensionImageFilterBase< TInput, TOutput, TAuxValue, VAuxDimension { ptr = AuxImageType::New(); this->ProcessObject::SetNthOutput( k + 1, ptr.GetPointer() ); - this->m_AuxImages[k] = 0; + this->m_AuxImages[k] = ITK_NULLPTR; } } @@ -67,7 +67,7 @@ FastMarchingExtensionImageFilterBase< TInput, TOutput, TAuxValue, VAuxDimension { if ( idx >= AuxDimension || this->GetNumberOfIndexedOutputs() < idx + 2 ) { - return NULL; + return ITK_NULLPTR; } return static_cast< AuxImageType * >( this->ProcessObject::GetOutput(idx + 1) ); diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilter.h b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilter.h index b30fc6579ed2065445fdfd6cee2befe166701bb3..d734337ad957ceb7b207eae9282540facf15dd16 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilter.h @@ -136,6 +136,7 @@ public: class AxisNodeType:public NodeType { public: + AxisNodeType() : m_Axis(0) {} int GetAxis() const { return m_Axis; } void SetAxis(int axis) { m_Axis = axis; } const AxisNodeType & operator=(const NodeType & node) diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilter.hxx b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilter.hxx index 8f7ca73616d639fdd90364370a85d64c21896c87..a4761abe508bf15e027112cd58fb84ccb69f540a 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilter.hxx @@ -46,10 +46,10 @@ FastMarchingImageFilter< TLevelSet, TSpeedImage > m_OutputDirection.SetIdentity(); m_OverrideOutputInformation = false; - m_AlivePoints = NULL; - m_OutsidePoints = NULL; - m_TrialPoints = NULL; - m_ProcessedPoints = NULL; + m_AlivePoints = ITK_NULLPTR; + m_OutsidePoints = ITK_NULLPTR; + m_TrialPoints = ITK_NULLPTR; + m_ProcessedPoints = ITK_NULLPTR; m_SpeedConstant = 1.0; m_InverseSpeed = -1.0; @@ -94,7 +94,7 @@ FastMarchingImageFilter< TLevelSet, TSpeedImage > Superclass::GenerateOutputInformation(); // use user-specified output information - if ( this->GetInput() == NULL || m_OverrideOutputInformation ) + if ( this->GetInput() == ITK_NULLPTR || m_OverrideOutputInformation ) { LevelSetPointer output = this->GetOutput(); output->SetLargestPossibleRegion(m_OutputRegion); @@ -499,7 +499,7 @@ FastMarchingImageFilter< TLevelSet, TSpeedImage > throw err; } - solution = ( vcl_sqrt(discrim) + bb ) / aa; + solution = ( std::sqrt(discrim) + bb ) / aa; } else { diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilterBase.hxx b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilterBase.hxx index a5acf5eb065c8b4599d424f69f187afe476b5f03..42bed2bbdb2875d85151a5e75dc7f8b20a802652 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilterBase.hxx +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageFilterBase.hxx @@ -67,7 +67,7 @@ FastMarchingImageFilterBase() m_OutputDirection.SetIdentity(); m_OverrideOutputInformation = false; - m_InputCache = NULL; + m_InputCache = ITK_NULLPTR; m_LabelImage = LabelImageType::New(); } // ----------------------------------------------------------------------------- @@ -373,7 +373,7 @@ Solve( OutputImageType* oImage, <<"Discriminant of quadratic equation is negative" ); } - oSolution = ( vcl_sqrt(discrim) + bb ) / aa; + oSolution = ( std::sqrt(discrim) + bb ) / aa; } else { diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageToNodePairContainerAdaptor.hxx b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageToNodePairContainerAdaptor.hxx index 7fd01483dccecf178e1527b8d479c079adf902aa..8884b702d3f6cbb360f589fead9190dc38e63ac1 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageToNodePairContainerAdaptor.hxx +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingImageToNodePairContainerAdaptor.hxx @@ -28,8 +28,8 @@ namespace itk template< typename TInput, typename TOutput, typename TImage > FastMarchingImageToNodePairContainerAdaptor< TInput, TOutput, TImage > ::FastMarchingImageToNodePairContainerAdaptor() : - m_AliveImage( NULL ), m_TrialImage( NULL ), m_ForbiddenImage( NULL ), - m_AlivePoints( NULL ), m_TrialPoints( NULL ), m_ForbiddenPoints( NULL ), + m_AliveImage( ITK_NULLPTR ), m_TrialImage( ITK_NULLPTR ), m_ForbiddenImage( ITK_NULLPTR ), + m_AlivePoints( ITK_NULLPTR ), m_TrialPoints( ITK_NULLPTR ), m_ForbiddenPoints( ITK_NULLPTR ), m_AliveValue( NumericTraits< OutputPixelType >::Zero ), m_TrialValue( NumericTraits< OutputPixelType >::Zero ), m_IsForbiddenImageBinaryMask( false ) diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingQuadEdgeMeshFilterBase.hxx b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingQuadEdgeMeshFilterBase.hxx index edaa26091a736800242c8044b6bbf915b696cc0a..acd479a0b1b8a0526b9279712f71b387145c6a82 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingQuadEdgeMeshFilterBase.hxx +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingQuadEdgeMeshFilterBase.hxx @@ -31,7 +31,7 @@ template< typename TInput, typename TOutput > FastMarchingQuadEdgeMeshFilterBase< TInput, TOutput > ::FastMarchingQuadEdgeMeshFilterBase() : Superclass() { - this->m_InputMesh = 0; + this->m_InputMesh = ITK_NULLPTR; } template< typename TInput, typename TOutput > @@ -270,7 +270,7 @@ FastMarchingQuadEdgeMeshFilterBase< TInput, TOutput > if( sq_norm1 > epsilon ) { - norm1 = vcl_sqrt( sq_norm1 ); + norm1 = std::sqrt( sq_norm1 ); OutputVectorRealType inv_norm1 = 1. / norm1; Edge1 *= inv_norm1; @@ -281,7 +281,7 @@ FastMarchingQuadEdgeMeshFilterBase< TInput, TOutput > if( sq_norm2 > epsilon ) { - norm2 = vcl_sqrt( sq_norm2 ); + norm2 = std::sqrt( sq_norm2 ); OutputVectorRealType inv_norm2 = 1. / norm2; Edge2 *= inv_norm2; @@ -364,7 +364,7 @@ FastMarchingQuadEdgeMeshFilterBase< TInput, TOutput > OutputVectorRealType t = large_value; OutputVectorRealType CosAngle = iDot; - OutputVectorRealType SinAngle = vcl_sqrt( 1. - iDot * iDot ); + OutputVectorRealType SinAngle = std::sqrt( 1. - iDot * iDot ); OutputVectorRealType u = iVal2 - iVal1; @@ -382,14 +382,14 @@ FastMarchingQuadEdgeMeshFilterBase< TInput, TOutput > { if( vnl_math_abs( f2 ) > epsilon ) { - t = ( -f1 - vcl_sqrt( delta ) ) / f2; + t = ( -f1 - std::sqrt( delta ) ) / f2; // test if we must must choose the other solution if( ( t < u ) || ( iNorm2 * ( t - u ) / t < iNorm1 * CosAngle ) || ( iNorm1 / CosAngle < iNorm2 * ( t - u ) / t ) ) { - t = ( -f1 + vcl_sqrt( delta ) ) / f2; + t = ( -f1 + std::sqrt( delta ) ) / f2; } } else @@ -466,7 +466,7 @@ FastMarchingQuadEdgeMeshFilterBase< TInput, TOutput > Vector2DType v1; v1[0] = dot; - v1[1] = vcl_sqrt( 1. - dot * dot ); + v1[1] = std::sqrt( 1. - dot * dot ); Vector2DType v2; v2[0] = 1.; @@ -534,7 +534,7 @@ FastMarchingQuadEdgeMeshFilterBase< TInput, TOutput > Matrix2DType rotation; rotation[0][0] = dot; - rotation[0][1] = vcl_sqrt( 1. - dot * dot ); + rotation[0][1] = std::sqrt( 1. - dot * dot ); rotation[1][0] = - rotation[0][1]; rotation[1][1] = dot; @@ -578,7 +578,7 @@ FastMarchingQuadEdgeMeshFilterBase< TInput, TOutput > if( oSqNorm > epsilon ) { - oNorm = vcl_sqrt( oSqNorm ); + oNorm = std::sqrt( oSqNorm ); OutputVectorRealType temp_norm = x_start1.GetNorm(); if( temp_norm > epsilon ) { diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingReachedTargetNodesStoppingCriterion.h b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingReachedTargetNodesStoppingCriterion.h index 9de3b5711f20ae31114fcffbd235a9c301a49134..4c445f6223ce465907ae66673c17aeaa9b4e42cf 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingReachedTargetNodesStoppingCriterion.h +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingReachedTargetNodesStoppingCriterion.h @@ -147,13 +147,15 @@ public: protected: /** Constructor */ - FastMarchingReachedTargetNodesStoppingCriterion() : Superclass() + FastMarchingReachedTargetNodesStoppingCriterion() : + Superclass(), + m_TargetCondition(AllTargets), + m_NumberOfTargetsToBeReached(0), + m_TargetOffset(NumericTraits< OutputPixelType >::Zero), + m_StoppingValue(NumericTraits< OutputPixelType >::Zero), + m_Satisfied(false), + m_Initialized(false) { - m_TargetCondition = AllTargets; - m_TargetOffset = NumericTraits< OutputPixelType >::Zero; - m_StoppingValue = NumericTraits< OutputPixelType >::Zero; - m_Satisfied = false; - m_Initialized = false; } /** Destructor */ diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingStoppingCriterionBase.h b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingStoppingCriterionBase.h index 36106b780840e1a5c3d1ccb586f7bb12c960b608..93672c11aa1fec454cd57aefe710f291ff16be8a 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingStoppingCriterionBase.h +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingStoppingCriterionBase.h @@ -70,7 +70,7 @@ public: protected: /** Constructor */ - FastMarchingStoppingCriterionBase() : Superclass(), m_Domain( NULL ) + FastMarchingStoppingCriterionBase() : Superclass(), m_Domain( ITK_NULLPTR ) { m_CurrentValue = NumericTraits< OutputPixelType >::Zero; m_PreviousValue = NumericTraits< OutputPixelType >::Zero; diff --git a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingUpwindGradientImageFilter.hxx b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingUpwindGradientImageFilter.hxx index a141a3bce89c268d42de1040a6e950700d06b1c9..279647a883a9dd8a0c971d6faa2f4c4a04d3fa16 100644 --- a/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingUpwindGradientImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/FastMarching/include/itkFastMarchingUpwindGradientImageFilter.hxx @@ -33,8 +33,8 @@ template< typename TLevelSet, typename TSpeedImage > FastMarchingUpwindGradientImageFilter< TLevelSet, TSpeedImage > ::FastMarchingUpwindGradientImageFilter() { - m_TargetPoints = NULL; - m_ReachedTargetPoints = NULL; + m_TargetPoints = ITK_NULLPTR; + m_ReachedTargetPoints = ITK_NULLPTR; m_GradientImage = GradientImageType::New(); m_GenerateGradientImage = false; m_TargetOffset = 1.0; diff --git a/Utilities/ITK/Modules/Filtering/GPUAnisotropicSmoothing/include/itkGPUAnisotropicDiffusionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/GPUAnisotropicSmoothing/include/itkGPUAnisotropicDiffusionImageFilter.hxx index 017b752c6f0286423c77ad120ce45b053cac1df2..7b82262f94ed050f95304393359317e29c39aa11 100644 --- a/Utilities/ITK/Modules/Filtering/GPUAnisotropicSmoothing/include/itkGPUAnisotropicDiffusionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/GPUAnisotropicSmoothing/include/itkGPUAnisotropicDiffusionImageFilter.hxx @@ -59,14 +59,14 @@ GPUAnisotropicDiffusionImageFilter< TInputImage, TOutputImage, TParentImageFilte { minSpacing = 1.0; } - if ( this->GetTimeStep() > ( minSpacing / vcl_pow(2.0, static_cast< double >( ImageDimension ) + 1) ) ) + if ( this->GetTimeStep() > ( minSpacing / std::pow(2.0, static_cast< double >( ImageDimension ) + 1) ) ) { - // f->SetTimeStep(1.0 / vcl_pow(2.0, + // f->SetTimeStep(1.0 / std::pow(2.0, // static_cast<double>(ImageDimension))); itkWarningMacro( << "Anisotropic diffusion unstable time step: " << this->GetTimeStep() << std::endl << "Stable time step for this image must be smaller than " - << minSpacing / vcl_pow( 2.0, static_cast< double >( ImageDimension + 1 ) ) ); + << minSpacing / std::pow( 2.0, static_cast< double >( ImageDimension + 1 ) ) ); } if ( this->m_GradientMagnitudeIsFixed == false ) diff --git a/Utilities/ITK/Modules/Filtering/GPUImageFilterBase/include/itkGPUNeighborhoodOperatorImageFilter.h b/Utilities/ITK/Modules/Filtering/GPUImageFilterBase/include/itkGPUNeighborhoodOperatorImageFilter.h index 46e2e4fa9ac8039d40f82eb92faa74d5672e2311..491bb269e0175fdfd597e2b20197a0b8253f5a8b 100644 --- a/Utilities/ITK/Modules/Filtering/GPUImageFilterBase/include/itkGPUNeighborhoodOperatorImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/GPUImageFilterBase/include/itkGPUNeighborhoodOperatorImageFilter.h @@ -131,8 +131,7 @@ public: * execution model. * * \sa ProcessObject::GenerateInputRequestedRegion() - virtual void GenerateInputRequestedRegion() - throw ( InvalidRequestedRegionError );*/ + virtual void GenerateInputRequestedRegion();*/ #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Utilities/ITK/Modules/Filtering/GPUImageFilterBase/include/itkGPUNeighborhoodOperatorImageFilter.hxx b/Utilities/ITK/Modules/Filtering/GPUImageFilterBase/include/itkGPUNeighborhoodOperatorImageFilter.hxx index 91cef5cb6ae02b1f532cce1dc65f549054ef0f97..a3c9c01f2cda9c97c767102271d34d5db66dd481 100644 --- a/Utilities/ITK/Modules/Filtering/GPUImageFilterBase/include/itkGPUNeighborhoodOperatorImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/GPUImageFilterBase/include/itkGPUNeighborhoodOperatorImageFilter.hxx @@ -32,7 +32,6 @@ template< typename TInputImage, typename TOutputImage, typename TOperatorValueTy void GPUNeighborhoodOperatorImageFilter< TInputImage, TOutputImage, TOperatorValueType > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/GPUSmoothing/include/itkGPUDiscreteGaussianImageFilter.h b/Utilities/ITK/Modules/Filtering/GPUSmoothing/include/itkGPUDiscreteGaussianImageFilter.h index a12146d0ee65b1de28a1e72234fef9771972b519..1d11bd8368f58090feee082bea1af2501d296740 100644 --- a/Utilities/ITK/Modules/Filtering/GPUSmoothing/include/itkGPUDiscreteGaussianImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/GPUSmoothing/include/itkGPUDiscreteGaussianImageFilter.h @@ -96,8 +96,7 @@ public: typedef GPUNeighborhoodOperatorImageFilter< InputImageType, OutputImageType, RealOutputPixelValueType > SingleFilterType; - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); protected: GPUDiscreteGaussianImageFilter(); diff --git a/Utilities/ITK/Modules/Filtering/GPUSmoothing/include/itkGPUDiscreteGaussianImageFilter.hxx b/Utilities/ITK/Modules/Filtering/GPUSmoothing/include/itkGPUDiscreteGaussianImageFilter.hxx index 5a99896c01ec91247c0f6b0fcab3f349c06f3c01..a0b8d00263b86fe27f105051170a1cfa1399c0d4 100644 --- a/Utilities/ITK/Modules/Filtering/GPUSmoothing/include/itkGPUDiscreteGaussianImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/GPUSmoothing/include/itkGPUDiscreteGaussianImageFilter.hxx @@ -67,7 +67,6 @@ template< typename TInputImage, typename TOutputImage > void GPUDiscreteGaussianImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageCompose/include/itkComposeImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageCompose/include/itkComposeImageFilter.hxx index 06c789edfb5c52e9e9b7612617c0b4951bfebbee..4322df359fbb756dd3f20873773a426748380e62 100644 --- a/Utilities/ITK/Modules/Filtering/ImageCompose/include/itkComposeImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageCompose/include/itkComposeImageFilter.hxx @@ -20,6 +20,7 @@ #include "itkComposeImageFilter.h" #include "itkImageRegionIterator.h" +#include "itkProgressReporter.h" namespace itk { @@ -114,8 +115,10 @@ template< typename TInputImage, typename TOutputImage > void ComposeImageFilter< TInputImage, TOutputImage > ::ThreadedGenerateData(const RegionType & outputRegionForThread, - ThreadIdType) + ThreadIdType threadId) { + ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); + typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >( this->ProcessObject::GetOutput(0) ); @@ -140,6 +143,7 @@ ComposeImageFilter< TInputImage, TOutputImage > ComputeOutputPixel( pix, inputItContainer ); oit.Set(pix); ++oit; + progress.CompletedPixel(); } } } // end namespace itk diff --git a/Utilities/ITK/Modules/Filtering/ImageCompose/wrapping/itkJoinSeriesImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageCompose/wrapping/itkJoinSeriesImageFilter.wrap index dfe884753cd58a90776a994ba965da2ef2a55fe5..82cf0f1f30aad2c141a23d199a2541ec0eca641e 100644 --- a/Utilities/ITK/Modules/Filtering/ImageCompose/wrapping/itkJoinSeriesImageFilter.wrap +++ b/Utilities/ITK/Modules/Filtering/ImageCompose/wrapping/itkJoinSeriesImageFilter.wrap @@ -1,13 +1,24 @@ -itk_wrap_class("itk::JoinSeriesImageFilter" POINTER) - foreach(d1 ${ITK_WRAP_DIMS}) - foreach(d2 ${ITK_WRAP_DIMS}) - if("${d1}" LESS "${d2}") - foreach(t ${WRAP_ITK_SCALAR}) - itk_wrap_template("${ITKM_I${t}${d1}}${ITKM_I${t}${d2}}" - "${ITKT_I${t}${d1}},${ITKT_I${t}${d2}}") - endforeach(t) - endif("${d1}" LESS "${d2}") - endforeach(d2) - endforeach(d1) +# Check if we have the right dimensions before wrapping +foreach(d1 ${ITK_WRAP_DIMS}) + foreach(d2 ${ITK_WRAP_DIMS}) + if("${d1}" LESS "${d2}") + set(wrappable true) + endif("${d1}" LESS "${d2}") + endforeach(d2) +endforeach(d1) -itk_end_wrap_class() +# Wrap if allowed +if(wrappable) + itk_wrap_class("itk::JoinSeriesImageFilter" POINTER) + foreach(d1 ${ITK_WRAP_DIMS}) + foreach(d2 ${ITK_WRAP_DIMS}) + if("${d1}" LESS "${d2}") + foreach(t ${WRAP_ITK_SCALAR}) + itk_wrap_template("${ITKM_I${t}${d1}}${ITKM_I${t}${d2}}" + "${ITKT_I${t}${d1}},${ITKT_I${t}${d2}}") + endforeach(t) + endif("${d1}" LESS "${d2}") + endforeach(d2) + endforeach(d1) + itk_end_wrap_class() +endif(wrappable) diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkBilateralImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkBilateralImageFilter.h index 29940669c804a18cd22d045902528147e14bc30b..e082cce7ff2b98432881ccc541f903bd27f0eb2b 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkBilateralImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkBilateralImageFilter.h @@ -200,8 +200,7 @@ protected: * an implementation for GenerateInputRequestedRegion() in order to * inform the pipeline execution model. * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); private: BilateralImageFilter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkBilateralImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkBilateralImageFilter.hxx index 82761dddd806baf6ae48357d00b215b95103323c..abe41efe1674d9000a91ecf1e4c7146dc0bde15a 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkBilateralImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkBilateralImageFilter.hxx @@ -57,7 +57,6 @@ template< typename TInputImage, typename TOutputImage > void BilateralImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region @@ -82,7 +81,7 @@ throw( InvalidRequestedRegionError ) { radius[i] = ( typename TInputImage::SizeType::SizeValueType ) - vcl_ceil(m_DomainMu * m_DomainSigma[i] / this->GetInput()->GetSpacing()[i]); + std::ceil(m_DomainMu * m_DomainSigma[i] / this->GetInput()->GetSpacing()[i]); } } else @@ -131,8 +130,8 @@ BilateralImageFilter< TInputImage, TOutputImage > { // Build a small image of the N-dimensional Gaussian used for domain filter // - // Gaussian image size will be (2*vcl_ceil(2.5*sigma)+1) x - // (2*vcl_ceil(2.5*sigma)+1) + // Gaussian image size will be (2*std::ceil(2.5*sigma)+1) x + // (2*std::ceil(2.5*sigma)+1) unsigned int i; typename InputImageType::SizeType radius; @@ -149,7 +148,7 @@ BilateralImageFilter< TInputImage, TOutputImage > { radius[i] = ( typename TInputImage::SizeType::SizeValueType ) - vcl_ceil(m_DomainMu * m_DomainSigma[i] / inputSpacing[i]); + std::ceil(m_DomainMu * m_DomainSigma[i] / inputSpacing[i]); domainKernelSize[i] = 2 * radius[i] + 1; } } @@ -223,7 +222,7 @@ BilateralImageFilter< TInputImage, TOutputImage > // denominator (normalization factor) for Gaussian used for range double rangeGaussianDenom; - rangeGaussianDenom = m_RangeSigma * vcl_sqrt(2.0 * vnl_math::pi); + rangeGaussianDenom = m_RangeSigma * std::sqrt(2.0 * vnl_math::pi); // Maximum delta for the dynamic range double tableDelta; @@ -242,7 +241,7 @@ BilateralImageFilter< TInputImage, TOutputImage > for ( i = 0, v = 0.0; i < m_NumberOfRangeGaussianSamples; ++i, v += tableDelta ) { - m_RangeGaussianTable[i] = vcl_exp(-0.5 * v * v / rangeVariance) / rangeGaussianDenom; + m_RangeGaussianTable[i] = std::exp(-0.5 * v * v / rangeVariance) / rangeGaussianDenom; } } diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkCannyEdgeDetectionImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkCannyEdgeDetectionImageFilter.h index 428d34a2d3f3ffb91f48c7121f5e0b4a32c0078a..6c2213bf5c45be54b049cd3cc4a6ae5b2f5a60b4 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkCannyEdgeDetectionImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkCannyEdgeDetectionImageFilter.h @@ -28,11 +28,11 @@ namespace itk { -template< typename TValueType > +template< typename TValue > class ListNode { public: - TValueType m_Value; + TValue m_Value; ListNode *Next; ListNode *Previous; @@ -40,7 +40,9 @@ public: /** \class CannyEdgeDetectionImageFilter * \brief This filter is an implementation of a Canny edge detector for - * scalar-valued images. Based on John Canny's paper "A Computational Approach + * scalar-valued images. + * + * Based on John Canny's paper "A Computational Approach * to Edge Detection"(IEEE Transactions on Pattern Analysis and Machine * Intelligence, Vol. PAMI-8, No.6, November 1986), there are four major steps * used in the edge-detection scheme: @@ -174,7 +176,9 @@ public: } } - /** TODO: Document in the ITKv4 migration guide that + /** \brief Set the Threshold value for detected edges. + * + * TODO: Document in the ITKv4 migration guide that * the SetThreshold member function was removed from * the CannyEdgeDetectionImageFilter, and that both * UpperThreshold and LowerThreshold need to be set. @@ -182,8 +186,6 @@ public: * change "myfilter->SetThrehsold" to "myfilter->SetUpperThreshold", * and add "myfilter->SetLowerThreshold(GetUpperThreshold()/2.0)" */ - - ///* Set the Threshold value for detected edges. */ itkSetMacro(UpperThreshold, OutputImagePixelType); itkGetConstMacro(UpperThreshold, OutputImagePixelType); @@ -202,8 +204,7 @@ public: * pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkCannyEdgeDetectionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkCannyEdgeDetectionImageFilter.hxx index 18b3887855920bfcc1f0fc5ef79ead9b491838b5..e690aec5208e4e9b4f40b603ce117d90e42681f1 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkCannyEdgeDetectionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkCannyEdgeDetectionImageFilter.hxx @@ -78,8 +78,8 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage >::CannyEdgeDetectionIm m_NodeStore = ListNodeStorageType::New(); m_NodeList = ListType::New(); - m_InputImage = 0; - m_OutputImage = 0; + m_InputImage = ITK_NULLPTR; + m_OutputImage = ITK_NULLPTR; } template< typename TInputImage, typename TOutputImage > @@ -101,7 +101,6 @@ template< typename TInputImage, typename TOutputImage > void CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); @@ -117,7 +116,7 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > ImageRegionIterator< TOutputImage > it; - void *globalData = 0; + void *globalData = ITK_NULLPTR; // Here input is the result from the gaussian filter // output is the update buffer. @@ -505,7 +504,7 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > m_ComputeCannyEdge1stDerivativeOper); } - gradMag = vcl_sqrt( (double)gradMag ); + gradMag = std::sqrt( (double)gradMag ); derivPos = zero; for ( unsigned int i = 0; i < ImageDimension; i++ ) { @@ -593,12 +592,9 @@ CannyEdgeDetectionImageFilter< TInputImage, TOutputImage > << m_Center << std::endl; os << "Stride: " << m_Stride << std::endl; - os << "Gaussian Filter: " << std::endl; - m_GaussianFilter->Print( os, indent.GetNextIndent() ); - os << "Multiply image Filter: " << std::endl; - m_MultiplyImageFilter->Print( os, indent.GetNextIndent() ); - os << "UpdateBuffer1: " << std::endl; - m_UpdateBuffer1->Print( os, indent.GetNextIndent() ); + itkPrintSelfObjectMacro( GaussianFilter ); + itkPrintSelfObjectMacro( MultiplyImageFilter ); + itkPrintSelfObjectMacro( UpdateBuffer1 ); } } //end of itk namespace #endif diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.h index 16c72feaa56f061d828140cca7522c36be46a25e..e35ab5d32b6ae40252c08e10a301b72d9f540ac4 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.h @@ -113,8 +113,7 @@ public: * inform the pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); protected: DerivativeImageFilter() diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.hxx index 8ff20d4d9634b5cb8425f1bfcf9d8e66e9431bbe..c20fe3511a8c64e5356c7f12ee7389e6297af336 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkDerivativeImageFilter.hxx @@ -30,7 +30,6 @@ template< typename TInputImage, typename TOutputImage > void DerivativeImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessian3DToVesselnessMeasureImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessian3DToVesselnessMeasureImageFilter.hxx index 277b06198505444a11bcdce0eaf0b2cc29f3932e..95f81f83face319d7174918283d64a53fe44e49f 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessian3DToVesselnessMeasureImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessian3DToVesselnessMeasureImageFilter.hxx @@ -86,12 +86,12 @@ Hessian3DToVesselnessMeasureImageFilter< TPixel > if ( eigenValue[2] <= 0 ) { lineMeasure = - vcl_exp( -0.5 * vnl_math_sqr( eigenValue[2] / ( m_Alpha1 * normalizeValue ) ) ); + std::exp( -0.5 * vnl_math_sqr( eigenValue[2] / ( m_Alpha1 * normalizeValue ) ) ); } else { lineMeasure = - vcl_exp( -0.5 * vnl_math_sqr( eigenValue[2] / ( m_Alpha2 * normalizeValue ) ) ); + std::exp( -0.5 * vnl_math_sqr( eigenValue[2] / ( m_Alpha2 * normalizeValue ) ) ); } lineMeasure *= normalizeValue; diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessianRecursiveGaussianImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessianRecursiveGaussianImageFilter.h index 30b8a86e6efc84b281b20a70acb02c3758569db7..753a76d8139fee18d16dabf01092fff5bedb993b 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessianRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessianRecursiveGaussianImageFilter.h @@ -140,8 +140,7 @@ public: * an implementation for GenerateInputRequestedRegion in order to inform * the pipeline execution model. * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessianRecursiveGaussianImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessianRecursiveGaussianImageFilter.hxx index 39a734147905e363b4bbac127eff6dc6cd04e1f5..27610a3f554ff971239d909940c151ee3fa01685 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessianRecursiveGaussianImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHessianRecursiveGaussianImageFilter.hxx @@ -139,7 +139,6 @@ template< typename TInputImage, typename TOutputImage > void HessianRecursiveGaussianImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DCirclesImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DCirclesImageFilter.hxx index 0f2021f63b4572f8d918049435f1a8994995d1ce..b99b233a424cca7b436bb7ad92df907d115a31a1 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DCirclesImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DCirclesImageFilter.hxx @@ -98,8 +98,8 @@ HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType > m_RadiusImage->SetOrigin( inputImage->GetOrigin() ); m_RadiusImage->SetSpacing( inputImage->GetSpacing() ); m_RadiusImage->SetDirection( inputImage->GetDirection() ); - m_RadiusImage->Allocate(); - m_RadiusImage->FillBuffer(0); + m_RadiusImage->Allocate(true); // initialize + // buffer to zero ImageRegionConstIteratorWithIndex< InputImageType > image_it( inputImage, inputImage->GetRequestedRegion() ); image_it.GoToBegin(); @@ -119,9 +119,9 @@ HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType > double Vy = grad[1]; // if the gradient is not flat - if ( ( vcl_fabs(Vx) > 1 ) || ( vcl_fabs(Vy) > 1 ) ) + if ( ( std::fabs(Vx) > 1 ) || ( std::fabs(Vy) > 1 ) ) { - double norm = vcl_sqrt(Vx * Vx + Vy * Vy); + double norm = std::sqrt(Vx * Vx + Vy * Vy); Vx /= norm; Vy /= norm; @@ -132,10 +132,10 @@ HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType > do { - index[0] = (IndexValueType)( point[0] - i * ( Vx * vcl_cos(angle) + Vy * vcl_sin(angle) ) ); - index[1] = (IndexValueType)( point[1] - i * ( Vx * vcl_sin(angle) + Vy * vcl_cos(angle) ) ); + index[0] = (IndexValueType)( point[0] - i * ( Vx * std::cos(angle) + Vy * std::sin(angle) ) ); + index[1] = (IndexValueType)( point[1] - i * ( Vx * std::sin(angle) + Vy * std::cos(angle) ) ); - distance = vcl_sqrt( ( index[1] - point[1] ) * ( index[1] - point[1] ) + distance = std::sqrt( ( index[1] - point[1] ) * ( index[1] - point[1] ) + ( index[0] - point[0] ) * ( index[0] - point[0] ) ); if ( outputImage->GetRequestedRegion().IsInside(index) ) @@ -192,8 +192,8 @@ HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType > outputImage->SetOrigin( this->GetOutput(0)->GetOrigin() ); outputImage->SetSpacing( this->GetOutput(0)->GetSpacing() ); outputImage->SetDirection( this->GetOutput(0)->GetDirection() ); - outputImage->Allocate(); - outputImage->FillBuffer(0); + outputImage->Allocate(true); // initialize + // buffer to zero ImageRegionConstIteratorWithIndex< OutputImageType > image_it( this->GetOutput(0), this->GetOutput( 0)->GetRequestedRegion() ); @@ -228,7 +228,7 @@ HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType > CirclesListSizeType circles = 0; bool found; - const double nPI = 4.0 * vcl_atan(1.0); + const double nPI = 4.0 * std::atan(1.0); // Find maxima do @@ -260,8 +260,8 @@ HoughTransform2DCirclesImageFilter< TInputPixelType, TOutputPixelType > { for ( double length = 0; length < m_DiscRadiusRatio * Circle->GetRadius()[0]; length += 1 ) { - index[0] = (IndexValueType)( it_input.GetIndex()[0] + length * vcl_cos(angle) ); - index[1] = (IndexValueType)( it_input.GetIndex()[1] + length * vcl_sin(angle) ); + index[0] = (IndexValueType)( it_input.GetIndex()[0] + length * std::cos(angle) ); + index[1] = (IndexValueType)( it_input.GetIndex()[1] + length * std::sin(angle) ); if ( postProcessImage->GetLargestPossibleRegion().IsInside(index) ) { postProcessImage->SetPixel(index, 0); diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DLinesImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DLinesImageFilter.h index 88c02adba1092be0bfe233ff3823c47dfc1b2a44..88ee7f5716e5f1b7537c431858cd296e3ac68140 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DLinesImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DLinesImageFilter.h @@ -34,9 +34,11 @@ namespace itk * to be extracted. The output is the image of the accumulator. * GetLines() returns a list of LinesSpatialObjects. * - * Lines are parameterized in the form: R = x*vcl_cos(Teta)+y*vcl_sin(Teta) - * where R is the perpendicular distance from the origin and Teta - * the angle with the normal. + * Lines are parameterized in the form: + * + * \f$ R = x \cos(\theta) + y \sin(\theta) \f$ + * where \f$R\f$ is the perpendicular distance from the origin and + * \f$\theta\f$ the angle with the normal. * * The output is the accumulator array: * -The first dimension (X) represents the distance R from the corner diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DLinesImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DLinesImageFilter.hxx index aceaeaaccb9703629e910f35dc1001397110f906..9677c57051b0fb1515754bcae17f8002c09a768b 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DLinesImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkHoughTransform2DLinesImageFilter.hxx @@ -38,7 +38,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > m_Variance = 5; m_OldModifiedTime = 0; m_OldNumberOfLines = 0; - m_SimplifyAccumulator = NULL; + m_SimplifyAccumulator = ITK_NULLPTR; } template< typename TInputPixelType, typename TOutputPixelType > @@ -74,7 +74,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > Size< 2 > size; size[0] = - (SizeValueType)( vcl_sqrt(m_AngleResolution * m_AngleResolution + (SizeValueType)( std::sqrt(m_AngleResolution * m_AngleResolution + input->GetLargestPossibleRegion().GetSize()[0] * input->GetLargestPossibleRegion().GetSize()[0]) ); size[1] = (SizeValueType)m_AngleResolution; @@ -114,7 +114,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > this->AllocateOutputs(); outputImage->FillBuffer(0); - const double nPI = 4.0 * vcl_atan(1.0); + const double nPI = 4.0 * std::atan(1.0); ImageRegionConstIteratorWithIndex< InputImageType > image_it( inputImage, inputImage->GetRequestedRegion() ); image_it.GoToBegin(); @@ -129,7 +129,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > { index[0] = // m_R - (IndexValueType)( image_it.GetIndex()[0] * vcl_cos(angle) + image_it.GetIndex()[1] * vcl_sin(angle) ); + (IndexValueType)( image_it.GetIndex()[0] * std::cos(angle) + image_it.GetIndex()[1] * std::sin(angle) ); // m_Theta index[1] = (IndexValueType)( ( m_AngleResolution / 2 ) + m_AngleResolution * angle / ( 2 * nPI ) ); @@ -170,8 +170,9 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > m_SimplifyAccumulator->SetOrigin( inputImage->GetOrigin() ); m_SimplifyAccumulator->SetSpacing( inputImage->GetSpacing() ); m_SimplifyAccumulator->SetDirection( inputImage->GetDirection() ); - m_SimplifyAccumulator->Allocate(); - m_SimplifyAccumulator->FillBuffer(0); + m_SimplifyAccumulator->Allocate(true); // initialize + // buffer + // to zero Index< 2 > index; Index< 2 > maxIndex; @@ -182,7 +183,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > ImageRegionConstIteratorWithIndex< InputImageType > image_it( inputImage, inputImage->GetRequestedRegion() ); image_it.GoToBegin(); - const double nPI = 4.0 * vcl_atan(1.0); + const double nPI = 4.0 * std::atan(1.0); while ( !image_it.IsAtEnd() ) { @@ -195,7 +196,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > for ( double angle = -nPI; angle < nPI; angle += nPI / m_AngleResolution ) { // m_R - index[0] = (IndexValueType)( image_it.GetIndex()[0] * vcl_cos(angle) + image_it.GetIndex()[1] * vcl_sin(angle) ); + index[0] = (IndexValueType)( image_it.GetIndex()[0] * std::cos(angle) + image_it.GetIndex()[1] * std::sin(angle) ); // m_Theta index[1] = (IndexValueType)( ( m_AngleResolution / 2 ) + m_AngleResolution * angle / ( 2 * nPI ) ); @@ -277,7 +278,7 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > itk::ImageRegionIterator< InternalImageType > it_input( postProcessImage, postProcessImage->GetLargestPossibleRegion() ); - const double nPI = 4.0 * vcl_atan(1.0); + const double nPI = 4.0 * std::atan(1.0); itk::Index< 2 > index; @@ -301,9 +302,9 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > double radius = it_input.GetIndex()[0]; double teta = ( ( it_input.GetIndex()[1] ) * 2 * nPI / this->GetAngleResolution() ) - nPI; - double Vx = radius * vcl_cos(teta); - double Vy = radius * vcl_sin(teta); - double norm = vcl_sqrt(Vx * Vx + Vy * Vy); + double Vx = radius * std::cos(teta); + double Vy = radius * std::sin(teta); + double norm = std::sqrt(Vx * Vx + Vy * Vy); double VxNorm = Vx / norm; double VyNorm = Vy / norm; @@ -343,8 +344,8 @@ HoughTransform2DLinesImageFilter< TInputPixelType, TOutputPixelType > { for ( double length = 0; length < m_DiscRadius; length += 1 ) { - index[0] = (IndexValueType)( it_input.GetIndex()[0] + length * vcl_cos(angle) ); - index[1] = (IndexValueType)( it_input.GetIndex()[1] + length * vcl_sin(angle) ); + index[0] = (IndexValueType)( it_input.GetIndex()[0] + length * std::cos(angle) ); + index[1] = (IndexValueType)( it_input.GetIndex()[1] + length * std::sin(angle) ); if ( postProcessImage->GetBufferedRegion().IsInside(index) ) { postProcessImage->SetPixel(index, 0); diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianImageFilter.h index 34abe973712a360e72801015213def0917f73050..e8fe1ef6a868fd05685aa5641bd81dc9a66b56eb 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianImageFilter.h @@ -100,8 +100,7 @@ public: * inform the pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** Enable/Disable using the image spacing information in * calculations. Use this option if you want derivatives in diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianImageFilter.hxx index 9e62c8591a9995be3cb6d33e9c4aeab354cc3a45..ccc4d14660c598547627ee8701c5a5c080103c29 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianImageFilter.hxx @@ -38,7 +38,6 @@ template< typename TInputImage, typename TOutputImage > void LaplacianImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianSharpeningImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianSharpeningImageFilter.h index e2b94bb6adf5d371bafb302ab8bcd09a67da35fa..b92ccaf63ed4176dad09e42c57c3eb6314d8469e 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianSharpeningImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianSharpeningImageFilter.h @@ -91,8 +91,7 @@ public: * execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** Enable/Disable using the image spacing information in * calculations. Use this option if you want derivatives in diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianSharpeningImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianSharpeningImageFilter.hxx index 2ee50169680113893d38269a5e8c577b95985b19..231519137b2c293a8161f722f5b51356f0d5471c 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianSharpeningImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkLaplacianSharpeningImageFilter.hxx @@ -40,7 +40,6 @@ template< typename TInputImage, typename TOutputImage > void LaplacianSharpeningImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. This should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkMaskFeaturePointSelectionFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkMaskFeaturePointSelectionFilter.hxx index 7776d1573b261c294296535e9fb210c1330989c8..460ea1e9496981737c046b5125a9c8df6b4c11d4 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkMaskFeaturePointSelectionFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkMaskFeaturePointSelectionFilter.hxx @@ -149,7 +149,7 @@ MaskFeaturePointSelectionFilter< TImage, TMask, TFeatures > const TMask * mask = this->GetMaskImage(); - if ( mask == NULL ) + if ( mask == ITK_NULLPTR ) { // create all 1s selectionMap selectionMap->FillBuffer( NumericTraits< MapPixelType >::One ); diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkSobelEdgeDetectionImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkSobelEdgeDetectionImageFilter.h index 8202d04b7bbefea1f5c5c406d4d74f30d2597849..414d74edeb74f7c122f69874221513d07cd8fc6a 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkSobelEdgeDetectionImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkSobelEdgeDetectionImageFilter.h @@ -102,8 +102,7 @@ public: * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkSobelEdgeDetectionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkSobelEdgeDetectionImageFilter.hxx index ec9d7315097e794b96a9ca0cb1f87a6a87a6c56c..499059e30390b8295f4cdf0d4d4f6b6498e9b942 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkSobelEdgeDetectionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkSobelEdgeDetectionImageFilter.hxx @@ -31,7 +31,6 @@ template< typename TInputImage, typename TOutputImage > void SobelEdgeDetectionImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkZeroCrossingImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkZeroCrossingImageFilter.h index 4d26a0d10cb74c13352caa38c4875fe21ce1393c..7ea62524e42c2f83a4a0d2bac83a364272ad4ec1 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkZeroCrossingImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkZeroCrossingImageFilter.h @@ -103,8 +103,7 @@ public: * pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** Set/Get the label value for zero-crossing pixels. */ itkSetMacro(ForegroundValue, OutputImagePixelType); diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkZeroCrossingImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkZeroCrossingImageFilter.hxx index d84037160bc3955d9ba7874db3561b5891f326c3..d9a2ccc1fdc722a8a822c0a653f3847f0b618362 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkZeroCrossingImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/include/itkZeroCrossingImageFilter.hxx @@ -31,7 +31,6 @@ template< typename TInputImage, typename TOutputImage > void ZeroCrossingImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/wrapping/itkHessian3DToVesselnessMeasureImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageFeature/wrapping/itkHessian3DToVesselnessMeasureImageFilter.wrap index 3544b0b54e770a2d7c0fd16716d14f7bc56a3ab1..fbde315f935c30a95ad4772a21241957a49c480f 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/wrapping/itkHessian3DToVesselnessMeasureImageFilter.wrap +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/wrapping/itkHessian3DToVesselnessMeasureImageFilter.wrap @@ -1,8 +1,9 @@ -itk_wrap_class("itk::Hessian3DToVesselnessMeasureImageFilter" POINTER) - itk_wrap_filter_dims(d3 3) - if(d3) +itk_wrap_filter_dims(has_d_3 3) + +if(has_d_3) + itk_wrap_class("itk::Hessian3DToVesselnessMeasureImageFilter" POINTER) foreach(t ${WRAP_ITK_SCALAR}) itk_wrap_template("${ITKM_${t}}" "${ITKT_${t}}") endforeach(t) - endif(d3) -itk_end_wrap_class() + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Filtering/ImageFeature/wrapping/itkMaskFeaturePointSelectionFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageFeature/wrapping/itkMaskFeaturePointSelectionFilter.wrap index 3a90ab548a92833b4cea0a6b0ca5a00d1188c69b..712dc4b9ec16b23b75737ffe7fd4c470707d0067 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFeature/wrapping/itkMaskFeaturePointSelectionFilter.wrap +++ b/Utilities/ITK/Modules/Filtering/ImageFeature/wrapping/itkMaskFeaturePointSelectionFilter.wrap @@ -1,3 +1,7 @@ -itk_wrap_class("itk::MaskFeaturePointSelectionFilter" POINTER_WITH_2_SUPERCLASSES) - itk_wrap_image_filter("${WRAP_ITK_REAL}" 1 3) -itk_end_wrap_class() +itk_wrap_filter_dims(has_d_3 3) + +if(has_d_3) + itk_wrap_class("itk::MaskFeaturePointSelectionFilter" POINTER_WITH_2_SUPERCLASSES) + itk_wrap_image_filter("${WRAP_ITK_REAL}" 1 3) + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkBinaryFunctorImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkBinaryFunctorImageFilter.hxx index 11bbe40ce575ce0c0a70c385691f2e0205cb710d..46cca9c8ad3f30d4dae44e6fcabf6e5441928018 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkBinaryFunctorImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkBinaryFunctorImageFilter.hxx @@ -90,7 +90,7 @@ BinaryFunctorImageFilter< TInputImage1, TInputImage2, TOutputImage, TFunction > itkDebugMacro("Getting constant 1"); const DecoratedInput1ImagePixelType *input = dynamic_cast< const DecoratedInput1ImagePixelType * >( this->ProcessObject::GetInput(0) ); - if( input == NULL ) + if( input == ITK_NULLPTR ) { itkExceptionMacro(<<"Constant 1 is not set"); } @@ -151,7 +151,7 @@ BinaryFunctorImageFilter< TInputImage1, TInputImage2, TOutputImage, TFunction > itkDebugMacro("Getting constant 2"); const DecoratedInput2ImagePixelType *input = dynamic_cast< const DecoratedInput2ImagePixelType * >( this->ProcessObject::GetInput(1) ); - if( input == NULL ) + if( input == ITK_NULLPTR ) { itkExceptionMacro(<<"Constant 2 is not set"); } @@ -165,7 +165,7 @@ void BinaryFunctorImageFilter< TInputImage1, TInputImage2, TOutputImage, TFunction > ::GenerateOutputInformation() { - const DataObject * input = NULL; + const DataObject * input = ITK_NULLPTR; Input1ImagePointer inputPtr1 = dynamic_cast< const TInputImage1 * >( ProcessObject::GetInput(0) ); Input2ImagePointer inputPtr2 = diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkBoxImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkBoxImageFilter.h index 153956324d9f7347d99986403e3a43df6a90f490..5bc48abd7a5a86e202c3477a9da15fd02a3b0934 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkBoxImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkBoxImageFilter.h @@ -79,13 +79,13 @@ public: itkGetConstReferenceMacro(Radius, RadiusType); - void GenerateInputRequestedRegion(); - protected: BoxImageFilter(); ~BoxImageFilter() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void GenerateInputRequestedRegion(); + + virtual void PrintSelf(std::ostream & os, Indent indent) const; private: BoxImageFilter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.h index 82dc69b372ed73dfe94a249342f4f305e9c001f3..fadce0c67a7192c32f55318533f962f208909d90 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.h @@ -161,8 +161,7 @@ protected: * region is expanded by the radius of the template. If the request * extends past the LargestPossibleRegion for the input, the request * is cropped by the LargestPossibleRegion. */ - void GenerateInputRequestedRegion() - throw ( InvalidRequestedRegionError ); + void GenerateInputRequestedRegion(); /** MaskNeighborhoodOperatorImageFilter can be implemented as a * multithreaded filter. Therefore, this implementation provides a diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.hxx index 0e955c58ff447d3746be26926f06cbcc8ae7a4f1..9b744f443aa8f2d82cfc8e01642b33a665bec842 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkMaskNeighborhoodOperatorImageFilter.hxx @@ -46,7 +46,6 @@ template< typename TInputImage, typename TMaskImage, typename TOutputImage, type void MaskNeighborhoodOperatorImageFilter< TInputImage, TMaskImage, TOutputImage, TOperatorValueType > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNeighborhoodOperatorImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNeighborhoodOperatorImageFilter.h index b558a9383ed5f6ab03207ab394800ebc6af393f7..8ebbe25b305b4020752b0afa85cdb05f2d7808a8 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNeighborhoodOperatorImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNeighborhoodOperatorImageFilter.h @@ -133,8 +133,7 @@ public: * execution model. * * \sa ProcessObject::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw ( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNeighborhoodOperatorImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNeighborhoodOperatorImageFilter.hxx index ca88c6f15c6ab22b5202237aabcec55c11fb370f..814054498792279bcceb5cdfa894b9e5af68e054 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNeighborhoodOperatorImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNeighborhoodOperatorImageFilter.hxx @@ -32,7 +32,6 @@ template< typename TInputImage, typename TOutputImage, typename TOperatorValueTy void NeighborhoodOperatorImageFilter< TInputImage, TOutputImage, TOperatorValueType > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNoiseImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNoiseImageFilter.hxx index b45507ee28749a158c55e0005ab85b437afc9cb2..a312c76f8aa0bbfebfc84a6c9b5cb1a9d37f920f 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNoiseImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNoiseImageFilter.hxx @@ -92,7 +92,7 @@ NoiseImageFilter< TInputImage, TOutputImage > // calculate the standard deviation value var = ( sumOfSquares - ( sum * sum / num ) ) / ( num - 1.0 ); - it.Set( static_cast< OutputPixelType >( vcl_sqrt(var) ) ); + it.Set( static_cast< OutputPixelType >( std::sqrt(var) ) ); ++bit; ++it; diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNullImageToImageFilterDriver.hxx b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNullImageToImageFilterDriver.hxx index 5f87ce60e1224172bc275d175f539c0b36d99274..fa141a671d35365d9e474a60be13602891211086 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNullImageToImageFilterDriver.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkNullImageToImageFilterDriver.hxx @@ -49,7 +49,7 @@ class NullImageToImageFilterDriver { public: NullImageToImageFilterDriver(): - m_Filter( NULL ) + m_Filter( ITK_NULLPTR ) {}; typedef typename TInputImage::SizeType ImageSizeType; diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkRecursiveSeparableImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkRecursiveSeparableImageFilter.hxx index a83b6dac8dd16dff48017ec9fad52c36064f3418..9a29ed62d5bf7d8615a0b4334b7e0ed0c6f94898 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkRecursiveSeparableImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkRecursiveSeparableImageFilter.hxx @@ -33,14 +33,29 @@ RecursiveSeparableImageFilter< TInputImage, TOutputImage > m_N1( 1.0 ), m_N2( 1.0 ), m_N3( 1.0 ), - m_Direction( 0 ) + m_D1( 0.0 ), + m_D2( 0.0 ), + m_D3( 0.0 ), + m_D4( 0.0 ), + m_M1( 0.0 ), + m_M2( 0.0 ), + m_M3( 0.0 ), + m_M4( 0.0 ), + m_BN1( 0.0 ), + m_BN2( 0.0 ), + m_BN3( 0.0 ), + m_BN4( 0.0 ), + m_BM1( 0.0 ), + m_BM2( 0.0 ), + m_BM3( 0.0 ), + m_BM4( 0.0 ), + m_Direction( 0 ), + m_ImageRegionSplitter(ImageRegionSplitterDirection::New()) { this->SetNumberOfRequiredOutputs(1); this->SetNumberOfRequiredInputs(1); this->InPlaceOff(); - - this->m_ImageRegionSplitter = ImageRegionSplitterDirection::New(); } /** @@ -263,9 +278,9 @@ RecursiveSeparableImageFilter< TInputImage, TOutputImage > const unsigned int ln = region.GetSize()[this->m_Direction]; - RealType *inps = 0; - RealType *outs = 0; - RealType *scratch = 0; + RealType *inps = ITK_NULLPTR; + RealType *outs = ITK_NULLPTR; + RealType *scratch = ITK_NULLPTR; try { diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.h index eafdce29d539e692a553a497eda50bf68e1c078b..841a344040685388850bb1ce3ebbbef1f282f997 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.h @@ -120,8 +120,7 @@ public: * execution model. * * \sa ProcessObject::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw ( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking @@ -133,7 +132,10 @@ public: #endif protected: - VectorNeighborhoodOperatorImageFilter() {} + VectorNeighborhoodOperatorImageFilter() : + m_BoundsCondition(ITK_NULLPTR) + {} + virtual ~VectorNeighborhoodOperatorImageFilter() {} /** VectorNeighborhoodOperatorImageFilter can be implemented as a diff --git a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.hxx index 688a8df6739d1fce85f60c2c1782ec6a761dd0d7..d612a82fb68abae4e48c0fcf0c543ea9c7e2fe30 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFilterBase/include/itkVectorNeighborhoodOperatorImageFilter.hxx @@ -31,7 +31,6 @@ template< typename TInputImage, typename TOutputImage > void VectorNeighborhoodOperatorImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapContourOverlayImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapContourOverlayImageFilter.h index 420b08d4e392a12b5de5f787f951737576a978db..e90d6e20c1a573dd18d60d633121bd3ec7dc6bb9 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapContourOverlayImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapContourOverlayImageFilter.h @@ -174,6 +174,20 @@ public: itkSetMacro( SliceDimension, int ); itkGetConstReferenceMacro( SliceDimension, int ); + /** Set/Get the overlay functor - defaults to a reasonable set of colors. + * This can be used to apply a different colormap. + */ + virtual void SetFunctor(const FunctorType & functor) + { + if ( m_Functor != functor ) + { + m_Functor = functor; + this->Modified(); + } + } + FunctorType & GetFunctor() { return m_Functor; } + const FunctorType & GetFunctor() const { return m_Functor; } + protected: LabelMapContourOverlayImageFilter(); ~LabelMapContourOverlayImageFilter() {}; @@ -212,6 +226,7 @@ private: SizeType m_ContourThickness; SizeType m_DilationRadius; int m_SliceDimension; + FunctorType m_Functor; LabelMapPointer m_TempImage; diff --git a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapContourOverlayImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapContourOverlayImageFilter.hxx index aee2783ea0a2824f04341fe7afcd4df857b04241..51475229ba7197ddde86de28c99e381af7454e2c 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapContourOverlayImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapContourOverlayImageFilter.hxx @@ -129,10 +129,9 @@ LabelMapContourOverlayImageFilter<TLabelMap, TFeatureImage, TOutputImage> typedef typename SliceKernelType::RadiusType RadiusType; RadiusType srad; srad.Fill(NumericTraits<typename RadiusType::SizeValueType>::Zero); - int j=0; - for( int i=0; i<ImageDimension; i++ ) + for( unsigned int i=0, j=0; i<ImageDimension; i++ ) { - if( j != m_SliceDimension ) + if( j != static_cast< unsigned int >( m_SliceDimension ) ) { srad[j] = m_ContourThickness[i]; j++; @@ -215,7 +214,7 @@ LabelMapContourOverlayImageFilter<TLabelMap, TFeatureImage, TOutputImage> LabelMapType * input = const_cast<LabelMapType *>(this->GetInput()); const FeatureImageType * input2 = this->GetFeatureImage(); - FunctorType function; + FunctorType function( m_Functor ); function.SetBackgroundValue( input->GetBackgroundValue() ); function.SetOpacity( m_Opacity ); @@ -252,7 +251,7 @@ LabelMapContourOverlayImageFilter<TLabelMap, TFeatureImage, TOutputImage> LabelMapType * input = const_cast<LabelMapType *>(this->GetInput()); const FeatureImageType * input2 = this->GetFeatureImage(); - FunctorType function; + FunctorType function( m_Functor ); function.SetBackgroundValue( input->GetBackgroundValue() ); function.SetOpacity( m_Opacity ); diff --git a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapOverlayImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapOverlayImageFilter.h index a6001dd26f1c2545829db98cf4c34c82740d1986..e35047db7b1f5e9598fa4c5810bb5408c21b6675 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapOverlayImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapOverlayImageFilter.h @@ -132,6 +132,20 @@ public: itkSetMacro( Opacity, double ); itkGetConstReferenceMacro( Opacity, double ); + /** Set/Get the overlay functor - defaults to a reasonable set of colors. + * This can be used to apply a different colormap. + */ + virtual void SetFunctor(const FunctorType& functor) + { + if ( m_Functor != functor ) + { + m_Functor = functor; + this->Modified(); + } + } + FunctorType & GetFunctor() { return m_Functor; } + const FunctorType & GetFunctor() const { return m_Functor; } + protected: LabelMapOverlayImageFilter(); ~LabelMapOverlayImageFilter() {}; @@ -160,6 +174,7 @@ private: double m_Opacity; typename Barrier::Pointer m_Barrier; + FunctorType m_Functor; }; // end of class diff --git a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapOverlayImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapOverlayImageFilter.hxx index f00448063a2a4645d837d96cbaf200d3fa3530cf..3a19d7216b76d20c093325bfef0f631935ae99bc 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapOverlayImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapOverlayImageFilter.hxx @@ -91,7 +91,7 @@ LabelMapOverlayImageFilter<TLabelMap, TFeatureImage, TOutputImage> LabelMapType * input = const_cast<LabelMapType *>(this->GetInput()); const FeatureImageType * input2 = this->GetFeatureImage(); - FunctorType function; + FunctorType function( m_Functor ); function.SetBackgroundValue( input->GetBackgroundValue() ); function.SetOpacity( m_Opacity ); @@ -127,7 +127,7 @@ LabelMapOverlayImageFilter<TLabelMap, TFeatureImage, TOutputImage> LabelMapType * input = const_cast<LabelMapType *>(this->GetInput()); const FeatureImageType * input2 = this->GetFeatureImage(); - FunctorType function; + FunctorType function( m_Functor ); function.SetBackgroundValue( input->GetBackgroundValue() ); function.SetOpacity( m_Opacity ); diff --git a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapToRGBImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapToRGBImageFilter.hxx index ae5e3515d5822aac754e90cd1477b86511e4528d..9c72c5ec77b9f65c7a9349d787418f855d23c3f2 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapToRGBImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelMapToRGBImageFilter.hxx @@ -56,8 +56,6 @@ LabelMapToRGBImageFilter<TInputImage, TOutputImage> { const typename LabelObjectType::LabelType & label = labelObject->GetLabel(); - typedef typename LabelObjectType::LengthType LengthType; - FunctorType function; function.SetBackgroundValue( this->GetInput()->GetBackgroundValue() ); diff --git a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelOverlayFunctor.h b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelOverlayFunctor.h index 21525c74fab35d2daf0ab4828efc025e1d384327..9c0b9fea5f77227ba1c423cf1be62e965815a6aa 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelOverlayFunctor.h +++ b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelOverlayFunctor.h @@ -52,6 +52,7 @@ public: // provide some default value for external use (outside // LabelOverlayFunctorImageFilter) Inside LabelOverlayFunctorImageFilter, // the values are always initialized + m_Opacity = 1.0; m_BackgroundValue = NumericTraits< TLabel >::Zero; } @@ -87,10 +88,15 @@ public: bool operator!=(const LabelOverlayFunctor & l) const { - bool value = l.m_Opacity != m_Opacity - || m_BackgroundValue != l.m_BackgroundValue; + bool areDifferent = l.m_Opacity != m_Opacity + || l.m_BackgroundValue != m_BackgroundValue + || l.m_RGBFunctor != m_RGBFunctor; + return areDifferent; + } - return value; + bool operator==(const LabelOverlayFunctor & l) const + { + return !(*this != l); } ~LabelOverlayFunctor() {} diff --git a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelToRGBFunctor.h b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelToRGBFunctor.h index 93b8797dc4f4162ac91604a84c68237a439750cc..be0e1813704daa7aa2ae0a42cf1fa0ce62909068 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelToRGBFunctor.h +++ b/Utilities/ITK/Modules/Filtering/ImageFusion/include/itkLabelToRGBFunctor.h @@ -55,8 +55,6 @@ public: LabelToRGBFunctor() { - TRGBPixel rgbPixel; - typedef typename TRGBPixel::ValueType ValueType; // the following colors are from "R", and named: @@ -152,10 +150,22 @@ public: bool operator!=(const Self & l) const { - const bool areDifferent = m_BackgroundColor != l.m_BackgroundColor - || m_BackgroundValue != l.m_BackgroundValue; + if ( m_BackgroundColor != l.m_BackgroundColor + || m_BackgroundValue != l.m_BackgroundValue + || m_Colors.size() != l.m_Colors.size() ) + { + return true; + } - return areDifferent; + // We need to check each color to see if it's different + for ( typename std::vector< TRGBPixel >::size_type i = 0; i < m_Colors.size(); ++i ) + { + if ( m_Colors[i] != l.m_Colors[i] ) + { + return true; + } + } + return false; } bool operator==(const Self & other) const diff --git a/Utilities/ITK/Modules/Filtering/ImageFusion/wrapping/CMakeLists.txt b/Utilities/ITK/Modules/Filtering/ImageFusion/wrapping/CMakeLists.txt index 7bd8f98437c2cd57ebf489526d397e51dd09fb63..ff6ec64811e185773b2aee0337801c4335e8508d 100644 --- a/Utilities/ITK/Modules/Filtering/ImageFusion/wrapping/CMakeLists.txt +++ b/Utilities/ITK/Modules/Filtering/ImageFusion/wrapping/CMakeLists.txt @@ -1,3 +1,14 @@ itk_wrap_module(ITKImageFusion) + +# Save default includes so they can be reseted afterwards +set(tmp_default_includes ${WRAPPER_DEFAULT_INCLUDE}) + +# Add itkStatisticsLabelObject.h, it is not automatically detected +# (but it maybe should) +set(WRAPPER_DEFAULT_INCLUDE ${WRAPPER_DEFAULT_INCLUDE} "itkStatisticsLabelObject.h") + itk_auto_load_submodules() itk_end_wrap_module() + +# Reset the WRAPPER_DEFAULT_INCLUDE to original value +set(WRAPPER_DEFAULT_INCLUDE ${tmp_default_includes}) diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.h index ff0035929295949764d273c6dcffeea954e588a9..8cfd1ea4293387c09ade5886216119cc9deb80b6 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.h @@ -103,8 +103,7 @@ public: * in order to inform the pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** Use the image spacing information in calculations. Use this option if you * want derivatives in physical space. Default is UseImageSpacingOn. */ @@ -170,8 +169,8 @@ private: // An overloaded method which may transform the gradient to a // physical vector and converts to the correct output pixel type. - template <typename TValueType> - void SetOutputPixel( ImageRegionIterator< VectorImage<TValueType,OutputImageDimension> > &it, CovariantVectorType &gradient ) + template <typename TValue> + void SetOutputPixel( ImageRegionIterator< VectorImage<TValue,OutputImageDimension> > &it, CovariantVectorType &gradient ) { if ( this->m_UseImageDirection ) { diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.hxx index 3ac9d07a7c66aa2f9411ce150c59ad7711852c45..29fc4f767d5e0cdba6345dac564ff99990b8c81f 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientImageFilter.hxx @@ -52,7 +52,6 @@ template< typename TInputImage, typename TOperatorValueType, typename TOutputVal void GradientImageFilter< TInputImage, TOperatorValueType, TOutputValueType, TOutputImageType > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.h index b287b7d0fcc1ae9cf3b7c9d4dba0473e2be2b05e..4b300d935d0a17dd7f514621d7dc25950bf4d308 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.h @@ -82,8 +82,7 @@ public: * pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** Use the image spacing information in calculations. Use this option if you * want derivatives in physical space. Default is UseImageSpacingOn. */ diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.hxx index 9186ecf31f39cfcd12e8a765468dc6251d6a3448..abcca42d65b3b9fe0475ef7f369462c3801a6ccb 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeImageFilter.hxx @@ -41,7 +41,6 @@ template< typename TInputImage, typename TOutputImage > void GradientMagnitudeImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); @@ -185,7 +184,7 @@ GradientMagnitudeImageFilter< TInputImage, TOutputImage > const RealType g = SIP(x_slice[i], bit, op[i]); a += g * g; } - it.Value() = static_cast< OutputPixelType >( vcl_sqrt(a) ); + it.Value() = static_cast< OutputPixelType >( std::sqrt(a) ); ++bit; ++it; progress.CompletedPixel(); diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeRecursiveGaussianImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeRecursiveGaussianImageFilter.h index 2ead44bf13ad860052c303e96192ba5bdcb94384..618d33a9ea17a0baa5820c190718feb08dbc7bb2 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeRecursiveGaussianImageFilter.h @@ -154,8 +154,7 @@ protected: * implementation for GenerateInputRequestedRegion in order to * inform the pipeline execution model. \sa * ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** GradientMagnitudeRecursiveGaussianImageFilter produces all of * the output. Therefore, it needs to provide an implementation of diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeRecursiveGaussianImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeRecursiveGaussianImageFilter.hxx index 1e6f142714cea2aec0fa0d91041a7643501fcd4b..8bc9f9a4dd0cec2f1b677e2703c5284f4005ee9c 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeRecursiveGaussianImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientMagnitudeRecursiveGaussianImageFilter.hxx @@ -149,7 +149,6 @@ template< typename TInputImage, typename TOutputImage > void GradientMagnitudeRecursiveGaussianImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientRecursiveGaussianImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientRecursiveGaussianImageFilter.h index 8c03d1fb98a12a4fc4038f0f6148b79948243a3c..2defe262b5ebdc78e42d03e43ec2ccd698d37ca9 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientRecursiveGaussianImageFilter.h @@ -148,8 +148,7 @@ public: * an implementation for GenerateInputRequestedRegion in order to inform * the pipeline execution model. * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** The UseImageDirection flag determines whether the gradients are * computed with respect to the image grid or with respect to the physical @@ -187,8 +186,8 @@ protected: private: - template <typename TValueType> - void TransformOutputPixel( ImageRegionIterator< VectorImage<TValueType, ImageDimension> > &it ) + template <typename TValue> + void TransformOutputPixel( ImageRegionIterator< VectorImage<TValue, ImageDimension> > &it ) { // To transform Variable length vector we need to convert to and // fro the CovariantVectorType @@ -220,8 +219,8 @@ private: DefaultConvertPixelTraits<OutputPixelType>::SetNthComponent( nc*ImageDimension+dim, correctedGradient, correctedComponentGradient[dim] ); } - it.Set(correctedGradient); } + it.Set(correctedGradient); } template <template<typename, unsigned int> class P, class T, unsigned int N> diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientRecursiveGaussianImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientRecursiveGaussianImageFilter.hxx index 81e4877cf76fadd7996d497e4f342ef1657df15b..e678ed8a0334347bcfe4b1be83c4265b13923919 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientRecursiveGaussianImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkGradientRecursiveGaussianImageFilter.hxx @@ -131,7 +131,6 @@ template< typename TInputImage, typename TOutputImage > void GradientRecursiveGaussianImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.h index 82319da5f0e506c734ad1011550aad6aa83dffbc..5ffae2acb14a0eece19c0555813df074142ae992 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.h @@ -194,8 +194,7 @@ public: * pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); /** Set the derivative weights according to the spacing of the input image (1/spacing). Use this option if you want to calculate the gradient in the @@ -309,7 +308,7 @@ protected: } accum += sum; } - return vcl_sqrt(accum); + return std::sqrt(accum); } TRealType EvaluateAtNeighborhood3D(const ConstNeighborhoodIteratorType & it) const diff --git a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.hxx index 1e3eb5f7948d1dd6175a162db31b224df8d619fd..9e91414e365399f3eac30cf8c9c9cbaddde005ca 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGradient/include/itkVectorGradientMagnitudeImageFilter.hxx @@ -107,7 +107,6 @@ template< typename TInputImage, typename TRealType, typename TOutputImage > void VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); @@ -167,7 +166,7 @@ VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > { itkExceptionMacro(<< "Component weights must be positive numbers"); } - m_SqrtComponentWeights[i] = vcl_sqrt(m_ComponentWeights[i]); + m_SqrtComponentWeights[i] = std::sqrt(m_ComponentWeights[i]); } // Set the weights on the derivatives. @@ -308,12 +307,12 @@ VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > if ( D < -epsilon ) // D < 0, three real solutions, by far the common case. { - double phi = 1.0 / 3.0 * vcl_acos( -q / vcl_sqrt(-cb_p) ); - double t = 2.0 * vcl_sqrt(-p); + double phi = 1.0 / 3.0 * std::acos( -q / std::sqrt(-cb_p) ); + double t = 2.0 * std::sqrt(-p); - s[0] = t * vcl_cos(phi); - s[1] = -t *vcl_cos(phi + dpi / 3); - s[2] = -t *vcl_cos(phi - dpi / 3); + s[0] = t * std::cos(phi); + s[1] = -t *std::cos(phi + dpi / 3); + s[2] = -t *std::cos(phi - dpi / 3); num = 3; } @@ -335,7 +334,7 @@ VectorGradientMagnitudeImageFilter< TInputImage, TRealType, TOutputImage > else // Only one real solution. This case misses a double root on rare // occasions with very large char eqn coefficients. { - double sqrt_D = vcl_sqrt(D); + double sqrt_D = std::sqrt(D); double u = vnl_math_cuberoot(sqrt_D - q); double v = -vnl_math_cuberoot(sqrt_D + q); diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineCenteredResampleImageFilterBase.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineCenteredResampleImageFilterBase.hxx index d82415a51b79c6fe34d00ac36776fb9336691d11..f622e51bc12e9758a841162bc5478201f05d02c0 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineCenteredResampleImageFilterBase.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineCenteredResampleImageFilterBase.hxx @@ -349,7 +349,7 @@ void BSplineCenteredResampleImageFilterBase< TInputImage, TOutputImage > outVal2 = 0; for ( IndexValueType k = -k0; k < this->m_HSize; k += 2L ) { - IndexValueType kk = vcl_abs( static_cast< int >( k ) ); + IndexValueType kk = std::abs( static_cast< int >( k ) ); i1 = inK + ( k + 1L ) / 2L; if ( i1 < 0L ) { diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFilter.hxx index a04ff5baa4b89379a710a9158f17d8eac535b8dd..53132f256010057dc0ce970cb993b423d9f1262a 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFilter.hxx @@ -67,7 +67,7 @@ BSplineControlPointImageFilter<InputImage, TOutputImage> this->m_NumberOfLevels.Fill( 1 ); this->m_CloseDimension.Fill( 0 ); - this->m_BSplineEpsilon = vcl_numeric_limits<RealType>::epsilon(); + this->m_BSplineEpsilon = std::numeric_limits<RealType>::epsilon(); } template<typename InputImage, typename TOutputImage> @@ -158,7 +158,7 @@ BSplineControlPointImageFilter<TInputPointImage, TOutputImage> } for( unsigned int j = 0; j < C.cols(); j++ ) { - RealType c = vcl_pow( static_cast<RealType>( 2.0 ), + RealType c = std::pow( static_cast<RealType>( 2.0 ), static_cast<RealType>( C.cols()-j-1 ) ); for( unsigned int k = 0; k < C.rows(); k++) { @@ -206,7 +206,7 @@ BSplineControlPointImageFilter<InputImage, TOutputImage> maximumNumberOfSpans = numberOfSpans; } } - this->m_BSplineEpsilon = 100 * vcl_numeric_limits<RealType>::epsilon(); + this->m_BSplineEpsilon = 100 * std::numeric_limits<RealType>::epsilon(); while( static_cast<RealType>( maximumNumberOfSpans ) == static_cast<RealType>( maximumNumberOfSpans ) - this->m_BSplineEpsilon ) { @@ -397,9 +397,9 @@ BSplineControlPointImageFilter<TInputImage, TOutputImage> // determine the actual number of pieces that will be generated typename SizeType::SizeValueType range = requestedRegionSize[splitAxis]; - unsigned int valuesPerThread = static_cast<unsigned int>( vcl_ceil( + unsigned int valuesPerThread = static_cast<unsigned int>( std::ceil( range / static_cast<double>( num ) ) ); - unsigned int maxThreadIdUsed = static_cast<unsigned int>( vcl_ceil( + unsigned int maxThreadIdUsed = static_cast<unsigned int>( std::ceil( range / static_cast<double>( valuesPerThread ) ) - 1 ); // Split the region @@ -638,7 +638,7 @@ BSplineControlPointImageFilter<InputImage, TOutputImage> Superclass::PrintSelf( os, indent ); for( unsigned int i = 0; i < ImageDimension; i++ ) { - this->m_Kernel[i]->Print( os, indent ); + this->m_Kernel[i]->Print( os, indent.GetNextIndent() ); } os << indent << "Spline order: " << this->m_SplineOrder << std::endl; os << indent << "Close dimension: " << this->m_CloseDimension << std::endl; diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFunction.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFunction.hxx index 5634b547f582cf298a607bc57fc4c6a29038a7d3..f3ccdbb92b646533d7be54cb57e54131df47092a 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFunction.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineControlPointImageFunction.hxx @@ -47,9 +47,9 @@ BSplineControlPointImageFunction<TInputImage, TCoordRep> this->m_CloseDimension.Fill( 0 ); - this->m_NeighborhoodWeightImage = NULL; + this->m_NeighborhoodWeightImage = ITK_NULLPTR; - this->m_BSplineEpsilon = vcl_numeric_limits<CoordRepType>::epsilon(); + this->m_BSplineEpsilon = std::numeric_limits<CoordRepType>::epsilon(); } template<typename TInputImage, typename TCoordRep> @@ -114,7 +114,7 @@ BSplineControlPointImageFunction<TInputImage, TCoordRep> maximumNumberOfSpans = numberOfSpans; } } - this->m_BSplineEpsilon = 100 * vcl_numeric_limits<CoordRepType>::epsilon(); + this->m_BSplineEpsilon = 100 * std::numeric_limits<CoordRepType>::epsilon(); while( static_cast<CoordRepType>( maximumNumberOfSpans ) == static_cast<CoordRepType>( maximumNumberOfSpans ) - this->m_BSplineEpsilon ) { diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineDownsampleImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineDownsampleImageFilter.hxx index 3f77eb02edabafd9bbd59da9415e7bfe6a02ee81..139d6a171f807793f62150ad76f8d8b1da1ae4d1 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineDownsampleImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineDownsampleImageFilter.hxx @@ -152,8 +152,8 @@ BSplineDownsampleImageFilter< TInputImage, TOutputImage, ResamplerType > //TODO: Verify this is being rounded correctly. outputSpacing[i] = inputSpacing[i] * (double)2; //TODO: Verify this is being rounded correctly. - outputSize[i] = (unsigned int)vcl_floor( (double)( inputSize[i] / 2.0 ) ); - outputStartIndex[i] = (int)vcl_ceil( (double)inputStartIndex[i] / 2.0 ); + outputSize[i] = (unsigned int)std::floor( (double)( inputSize[i] / 2.0 ) ); + outputStartIndex[i] = (int)std::ceil( (double)inputStartIndex[i] / 2.0 ); } outputPtr->SetSpacing(outputSpacing); diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineResampleImageFilterBase.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineResampleImageFilterBase.hxx index 734d517649c2404b654d9d5229be7e20ca0b6bbf..47d1cbbaad23a48100136878511a88b7ed48bbe5 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineResampleImageFilterBase.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineResampleImageFilterBase.hxx @@ -250,7 +250,10 @@ void BSplineResampleImageFilterBase< TInputImage, TOutputImage > } if ( i2 > (int)inModK ) { - i2 = i2 % inModK; + if (inModK) + { + i2 = i2 % inModK; + } // Removed because i1 can never be greater than inModK, right? //if (i2 > inModK) //i2=inModK-i2; //TODO: I don't think this is correct. diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineScatteredDataPointSetToImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineScatteredDataPointSetToImageFilter.hxx index cc03803500701844349ef8e52f11c23d438ce080..01d07e3a59eb8a18f1f069410b19b1603a505fcd 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineScatteredDataPointSetToImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineScatteredDataPointSetToImageFilter.hxx @@ -66,7 +66,7 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> this->m_NumberOfLevels.Fill( 1 ); this->m_MaximumNumberOfLevels = 1; - this->m_PhiLattice = NULL; + this->m_PhiLattice = ITK_NULLPTR; this->m_PsiLattice = PointDataImageType::New(); this->m_InputPointData = PointDataContainerType::New(); this->m_OutputPointData = PointDataContainerType::New(); @@ -74,9 +74,10 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> this->m_PointWeights = WeightsContainerType::New(); this->m_UsePointWeights = false; - this->m_BSplineEpsilon = vcl_numeric_limits<RealType>::epsilon(); + this->m_BSplineEpsilon = std::numeric_limits<RealType>::epsilon(); this->m_IsFittingComplete = false; + this->m_CurrentLevel = 0; } template<typename TInputPointSet, typename TOutputImage> @@ -130,7 +131,7 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> } for( unsigned int j = 0; j < C.cols(); j++ ) { - RealType c = vcl_pow( static_cast<RealType>( 2.0 ), + RealType c = std::pow( static_cast<RealType>( 2.0 ), static_cast<RealType>( C.cols() ) - j - 1 ); for( unsigned int k = 0; k < C.rows(); k++ ) @@ -268,7 +269,7 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> maximumNumberOfSpans = numberOfSpans; } } - this->m_BSplineEpsilon = 100 * vcl_numeric_limits<RealType>::epsilon(); + this->m_BSplineEpsilon = 100 * std::numeric_limits<RealType>::epsilon(); while( static_cast<RealType>( maximumNumberOfSpans ) == static_cast<RealType>( maximumNumberOfSpans ) - this->m_BSplineEpsilon ) { @@ -511,9 +512,9 @@ BSplineScatteredDataPointSetToImageFilter<TInputPointSet, TOutputImage> // determine the actual number of pieces that will be generated typename SizeType::SizeValueType range = requestedRegionSize[splitAxis]; - unsigned int valuesPerThread = static_cast<unsigned int>( vcl_ceil( + unsigned int valuesPerThread = static_cast<unsigned int>( std::ceil( range / static_cast<double>( num ) ) ); - unsigned int maxThreadIdUsed = static_cast<unsigned int>( vcl_ceil( + unsigned int maxThreadIdUsed = static_cast<unsigned int>( std::ceil( range / static_cast<double>( valuesPerThread ) ) - 1 ); // Split the region diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineUpsampleImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineUpsampleImageFilter.hxx index fa05ce78f17218d7125bd21dbd3cb5a666718b81..40d77ee504358afc195de124e73b5bdc17b0c13e 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineUpsampleImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBSplineUpsampleImageFilter.hxx @@ -164,8 +164,8 @@ BSplineUpsampleImageFilter< TInputImage, TOutputImage, ResamplerType > //TODO: Verify this is being rounded correctly. outputSpacing[i] = inputSpacing[i] / (double)2; //TODO: Verify this is being rounded correctly. - outputSize[i] = (unsigned int)vcl_floor( (double)( inputSize[i] * 2.0 ) ); - outputStartIndex[i] = (int)vcl_ceil( (double)inputStartIndex[i] * 2.0 ); + outputSize[i] = (unsigned int)std::floor( (double)( inputSize[i] * 2.0 ) ); + outputStartIndex[i] = (int)std::ceil( (double)inputStartIndex[i] * 2.0 ); } outputPtr->SetSpacing(outputSpacing); diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBinShrinkImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBinShrinkImageFilter.h index fe6383fb6448e59d8adf65219262aef64c8bf62d..cf46fcafd2bb0963374e6cc42b9037b54376342e 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBinShrinkImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBinShrinkImageFilter.h @@ -32,7 +32,7 @@ namespace itk * * The output image size in each dimension is given by: * - * outputSize[j] = max( vcl_floor(inputSize[j]/shrinkFactor[j]), 1 ); + * outputSize[j] = max( std::floor(inputSize[j]/shrinkFactor[j]), 1 ); * * The algorithm implemented can be describe with the following * equation for 2D: diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBinShrinkImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBinShrinkImageFilter.hxx index 5aa266a5916a50fccef95bd4f637fa64da2ab612..801cc45c7bbb1f0d7219300dfe335b827d582879 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBinShrinkImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkBinShrinkImageFilter.hxx @@ -142,7 +142,7 @@ BinShrinkImageFilter<TInputImage,TOutputImage> // allocate acumulate line const size_t ln = outputRegionForThread.GetSize(0); - AccumulatePixelType *accBuffer = 0; + AccumulatePixelType *accBuffer = ITK_NULLPTR; accBuffer = new AccumulatePixelType[ln]; try diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkChangeInformationImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkChangeInformationImageFilter.hxx index a9620643931f707b2fa34b0c1da6d1f5fbf81f41..8b64b94c8b40cf9035ac5e27b882f48317a62a16 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkChangeInformationImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkChangeInformationImageFilter.hxx @@ -32,7 +32,7 @@ template< typename TInputImage > ChangeInformationImageFilter< TInputImage > ::ChangeInformationImageFilter() { - m_ReferenceImage = 0; + m_ReferenceImage = ITK_NULLPTR; m_ChangeSpacing = false; m_ChangeOrigin = false; diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkConstantPadImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkConstantPadImageFilter.hxx index 4cc643611a7a2286ae06268bb0e24baab51bda85..033d723c58b5bec3d1d1e01ba7c2485d13b41778 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkConstantPadImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkConstantPadImageFilter.hxx @@ -31,7 +31,7 @@ template< typename TInputImage, typename TOutputImage > ConstantPadImageFilter< TInputImage, TOutputImage > ::ConstantPadImageFilter() { - m_InternalBoundaryCondition.SetConstant( NumericTraits< OutputImagePixelType >::Zero ); + m_InternalBoundaryCondition.SetConstant( NumericTraits< OutputImagePixelType >::ZeroValue() ); this->InternalSetBoundaryCondition( &m_InternalBoundaryCondition ); } diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkExpandImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkExpandImageFilter.hxx index d02986ccf6f0f14d9621cb684e38e776f095c9b6..f5a88b7bd63282dee27970c5a8b76867c777cc2b 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkExpandImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkExpandImageFilter.hxx @@ -221,11 +221,11 @@ ExpandImageFilter< TInputImage, TOutputImage > for ( i = 0; i < TInputImage::ImageDimension; i++ ) { inputRequestedRegionSize[i] = - (SizeValueType)vcl_ceil( (double)outputRequestedRegionSize[i] + (SizeValueType)std::ceil( (double)outputRequestedRegionSize[i] / (double)m_ExpandFactors[i] ) + 1; inputRequestedRegionStartIndex[i] = - (SizeValueType)vcl_floor( (double)outputRequestedRegionStartIndex[i] + (SizeValueType)std::floor( (double)outputRequestedRegionStartIndex[i] / (double)m_ExpandFactors[i] ); } diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkInterpolateImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkInterpolateImageFilter.hxx index f76c7661f3e6fce62bf66c466f77fc64e9b5a367..6bae701956891d4fb4bf339e28ceaa6397bc98b0 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkInterpolateImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkInterpolateImageFilter.hxx @@ -46,7 +46,7 @@ InterpolateImageFilter< TInputImage, TOutputImage > // Set default distance to 0,5 m_Distance = 0.5; - m_IntermediateImage = NULL; + m_IntermediateImage = ITK_NULLPTR; } /** @@ -164,7 +164,7 @@ InterpolateImageFilter< TInputImage, TOutputImage > ::AfterThreadedGenerateData() { // Clean up intermediate memory usage - m_IntermediateImage = NULL; + m_IntermediateImage = ITK_NULLPTR; } /** diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkPadImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkPadImageFilter.hxx index de35ad31bd93755b733e4b4853b9a300875fcf51..5aa93ba729f060b564dbe8dc08db0779a47c9abb 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkPadImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkPadImageFilter.hxx @@ -41,7 +41,7 @@ PadImageFilter< TInputImage, TOutputImage > m_PadUpperBound[j] = 0; } - m_BoundaryCondition = NULL; + m_BoundaryCondition = ITK_NULLPTR; } /** diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkResampleImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkResampleImageFilter.h index 8b30fa72d283f69a01e8f8ba9cd9e23c8de2be1d..95f2ebfb4cce5c0c6f36ced95d3b4f02b5a01ebc 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkResampleImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkResampleImageFilter.h @@ -26,6 +26,8 @@ #include "itkLinearInterpolateImageFunction.h" #include "itkSize.h" #include "itkDefaultConvertPixelTraits.h" +#include "itkDataObjectDecorator.h" + namespace itk { @@ -121,8 +123,11 @@ public: */ typedef Transform< TTransformPrecisionType, itkGetStaticConstMacro(ImageDimension), - itkGetStaticConstMacro(ImageDimension) > TransformType; - typedef typename TransformType::ConstPointer TransformPointerType; + itkGetStaticConstMacro(ImageDimension) > TransformType; + typedef typename TransformType::ConstPointer TransformPointerType; + typedef DataObjectDecorator<TransformType> DecoratedTransformType; + typedef typename DecoratedTransformType::Pointer DecoratedTransformPointer; + /** Interpolator typedef. */ typedef InterpolateImageFunction< InputImageType, @@ -185,8 +190,7 @@ public: * the filter uses an Identity transform. You must provide a different * transform here, before attempting to run the filter, if you do not want to * use the default Identity transform. */ - itkSetConstObjectMacro(Transform, TransformType); - itkGetConstObjectMacro(Transform, TransformType); + itkSetGetDecoratedObjectInputMacro(Transform, TransformType); /** Get/Set the interpolator function. The default is * LinearInterpolateImageFunction<InputImageType, @@ -247,10 +251,10 @@ public: * this method can be used to specify an image from which to * copy the information. UseReferenceImageOn must be set to utilize the * reference image. */ - void SetReferenceImage(const ReferenceImageBaseType *image); + itkSetInputMacro(ReferenceImage, ReferenceImageBaseType); /** Get the reference image that is defining the output information. */ - const ReferenceImageBaseType * GetReferenceImage() const; + itkGetInputMacro(ReferenceImage, ReferenceImageBaseType); /** Turn on/off whether a specified reference image should be used to define * the output information. */ @@ -338,7 +342,6 @@ private: void operator=(const Self &); //purposely not implemented SizeType m_Size; // Size of the output image - TransformPointerType m_Transform; // Transform InterpolatorPointerType m_Interpolator; // Image function for // interpolation ExtrapolatorPointerType m_Extrapolator; // Image function for diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkResampleImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkResampleImageFilter.hxx index 86f26d3496aaac934b61ef22d5386d122c49f0fd..d2ed52eee7f70954be25f6df0b9bf13b6b4ab2a8 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkResampleImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkResampleImageFilter.hxx @@ -48,13 +48,23 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra m_Size.Fill(0); m_OutputStartIndex.Fill(0); - m_Transform = - IdentityTransform< TTransformPrecisionType, ImageDimension >::New(); + // Pipeline input configuration + + // implicit: + // #0 "Primary" required + + // #1 "ReferenceImage" optional + Self::AddRequiredInputName("ReferenceImage",1); + Self::RemoveRequiredInputName("ReferenceImage"); + + // "Transform" required ( not numbered ) + Self::AddRequiredInputName("Transform"); + Self::SetTransform(IdentityTransform< TTransformPrecisionType, ImageDimension >::New()); m_Interpolator = dynamic_cast< InterpolatorType * > ( LinearInterpolatorType::New().GetPointer() ); - m_Extrapolator = NULL; + m_Extrapolator = ITK_NULLPTR; m_DefaultPixelValue = NumericTraits<PixelType>::ZeroValue( m_DefaultPixelValue ); @@ -84,7 +94,7 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra os << indent << "OutputSpacing: " << m_OutputSpacing << std::endl; os << indent << "OutputOrigin: " << m_OutputOrigin << std::endl; os << indent << "OutputDirection: " << m_OutputDirection << std::endl; - os << indent << "Transform: " << m_Transform.GetPointer() << std::endl; + os << indent << "Transform: " << this->GetTransform() << std::endl; os << indent << "Interpolator: " << m_Interpolator.GetPointer() << std::endl; os << indent << "Extrapolator: " << m_Extrapolator.GetPointer() << std::endl; os << indent << "UseReferenceImage: " << ( m_UseReferenceImage ? "On" : "Off" ) @@ -155,10 +165,6 @@ void ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTransformPrecisionType > ::BeforeThreadedGenerateData() { - if ( !m_Transform ) - { - itkExceptionMacro(<< "Transform not set"); - } if ( !m_Interpolator ) { @@ -204,11 +210,11 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra ::AfterThreadedGenerateData() { // Disconnect input image from the interpolator - m_Interpolator->SetInputImage(NULL); + m_Interpolator->SetInputImage(ITK_NULLPTR); if( !m_Extrapolator.IsNull() ) { // Disconnect input image from the extrapolator - m_Extrapolator->SetInputImage(NULL); + m_Extrapolator->SetInputImage(ITK_NULLPTR); } } @@ -243,7 +249,7 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra // Check whether we can use a fast path for resampling. Fast path // can be used if the transformation is linear. Transform respond // to the IsLinear() call. - if ( this->m_Transform->GetTransformCategory() == TransformType::Linear ) + if ( this->GetTransform()->GetTransformCategory() == TransformType::Linear ) { this->LinearThreadedGenerateData(outputRegionForThread, threadId); return; @@ -309,10 +315,14 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra ThreadIdType threadId) { // Get the output pointers - OutputImagePointer outputPtr = this->GetOutput(); + OutputImageType *outputPtr = this->GetOutput(); // Get this input pointers - InputImageConstPointer inputPtr = this->GetInput(); + const InputImageType *inputPtr = this->GetInput(); + + // Get the input transform + const TransformType *transformPtr = this->GetTransform(); + // Create an iterator that will walk the output region for this thread. typedef ImageRegionIteratorWithIndex< TOutputImage > OutputIterator; @@ -348,7 +358,7 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra outputPtr->TransformIndexToPhysicalPoint(outIt.GetIndex(), outputPoint); // Compute corresponding input pixel position - inputPoint = this->m_Transform->TransformPoint(outputPoint); + inputPoint = transformPtr->TransformPoint(outputPoint); inputPtr->TransformPhysicalPointToContinuousIndex(inputPoint, inputIndex); PixelType pixval; @@ -393,10 +403,13 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra ThreadIdType threadId) { // Get the output pointers - OutputImagePointer outputPtr = this->GetOutput(); + OutputImageType *outputPtr = this->GetOutput(); // Get this input pointers - InputImageConstPointer inputPtr = this->GetInput(); + const InputImageType *inputPtr = this->GetInput(); + + // Get the input transform + const TransformType *transformPtr = this->GetTransform(); // Create an iterator that will walk the output region for this thread. typedef ImageLinearIteratorWithIndex< TOutputImage > OutputIterator; @@ -443,7 +456,7 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra outputPtr->TransformIndexToPhysicalPoint(index, outputPoint); // Compute corresponding input pixel position - inputPoint = this->m_Transform->TransformPoint(outputPoint); + inputPoint = transformPtr->TransformPoint(outputPoint); inputPtr->TransformPhysicalPointToContinuousIndex(inputPoint, inputIndex); // As we walk across a scan line in the output image, we trace @@ -464,7 +477,7 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra // ++index[0]; outputPtr->TransformIndexToPhysicalPoint(index, tmpOutputPoint); - tmpInputPoint = this->m_Transform->TransformPoint(tmpOutputPoint); + tmpInputPoint = transformPtr->TransformPoint(tmpOutputPoint); inputPtr->TransformPhysicalPointToContinuousIndex(tmpInputPoint, tmpInputIndex); delta = tmpInputIndex - inputIndex; @@ -481,7 +494,7 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra // Compute corresponding input pixel continuous index, this index // will incremented in the scanline loop - inputPoint = this->m_Transform->TransformPoint(outputPoint); + inputPoint = transformPtr->TransformPoint(outputPoint); inputPtr->TransformPhysicalPointToContinuousIndex(inputPoint, inputIndex); while ( !outIt.IsAtEndOfLine() ) @@ -548,47 +561,6 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra inputPtr->SetRequestedRegionToLargestPossibleRegion(); } -/** - * Get the reference image that will provide the grid parameters for the output image. - */ -template< typename TInputImage, - typename TOutputImage, - typename TInterpolatorPrecisionType, - typename TTransformPrecisionType > -const typename ResampleImageFilter< TInputImage, - TOutputImage, - TInterpolatorPrecisionType, - TTransformPrecisionType > -::ReferenceImageBaseType * -ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTransformPrecisionType > -::GetReferenceImage() const -{ - Self * surrogate = const_cast< Self * >( this ); - const ReferenceImageBaseType *referenceImage = - static_cast< const ReferenceImageBaseType * >( surrogate->ProcessObject::GetInput(1) ); - - return referenceImage; -} - -/** - * Set the reference image that will provide the grid parameters for the output image. - */ -template< typename TInputImage, - typename TOutputImage, - typename TInterpolatorPrecisionType, - typename TTransformPrecisionType > -void -ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTransformPrecisionType > -::SetReferenceImage(const ReferenceImageBaseType *image) -{ - itkDebugMacro("setting input ReferenceImage to " << image); - if ( image != static_cast< const ReferenceImageBaseType * >( this->ProcessObject::GetInput(1) ) ) - { - this->ProcessObject::SetNthInput( 1, const_cast< ReferenceImageBaseType * >( image ) ); - this->Modified(); - } -} - /** * Inform pipeline of required output region */ @@ -604,7 +576,7 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra Superclass::GenerateOutputInformation(); // get pointers to the input and output - OutputImagePointer outputPtr = this->GetOutput(); + OutputImageType *outputPtr = this->GetOutput(); if ( !outputPtr ) { return; @@ -654,14 +626,6 @@ ResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType, TTra { ModifiedTimeType latestTime = Object::GetMTime(); - if ( m_Transform ) - { - if ( latestTime < m_Transform->GetMTime() ) - { - latestTime = m_Transform->GetMTime(); - } - } - if ( m_Interpolator ) { if ( latestTime < m_Interpolator->GetMTime() ) diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkShrinkImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkShrinkImageFilter.h index 392ac3542573e6f789fa74fe4dd1d1ec6ae3e6d9..cf8bd7eba2d933779be363f701d5bea13e5584c0 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkShrinkImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkShrinkImageFilter.h @@ -40,7 +40,7 @@ namespace itk * in each dimension. The algorithm implemented is a simple subsample. * The output image size in each dimension is given by: * - * outputSize[j] = max( vcl_floor(inputSize[j]/shrinkFactor[j]), 1 ); + * outputSize[j] = max( std::floor(inputSize[j]/shrinkFactor[j]), 1 ); * * NOTE: The physical centers of the input and output will be the * same. Because of this, the Origin of the output may not be the same diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkShrinkImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkShrinkImageFilter.hxx index ee78866274d7653eb2ec8ce008b5903b8770b0c4..b7d4317b1a3522a245d7781f4f548a01a94da0d7 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkShrinkImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkShrinkImageFilter.hxx @@ -311,7 +311,7 @@ ShrinkImageFilter< TInputImage, TOutputImage > // Round down so that all output pixels fit input input region outputSize[i] = static_cast<SizeValueType>( - vcl_floor( (double)inputSize[i] / (double)m_ShrinkFactors[i] ) ); + std::floor( (double)inputSize[i] / (double)m_ShrinkFactors[i] ) ); if ( outputSize[i] < 1 ) { @@ -321,7 +321,7 @@ ShrinkImageFilter< TInputImage, TOutputImage > // Because of the later origin shift this starting index is not // critical outputStartIndex[i] = static_cast<IndexValueType>( - vcl_ceil( (double)inputStartIndex[i] / (double)m_ShrinkFactors[i] ) ); + std::ceil( (double)inputStartIndex[i] / (double)m_ShrinkFactors[i] ) ); } outputPtr->SetSpacing(outputSpacing); diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkSliceBySliceImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkSliceBySliceImageFilter.hxx index f86ba074020d475b994a4eabff4a5813fce13289..91ff4ecf6f9d7910f3fa7e4767a9f09476d372dd 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkSliceBySliceImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkSliceBySliceImageFilter.hxx @@ -30,8 +30,8 @@ SliceBySliceImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalOutputImageType > ::SliceBySliceImageFilter() { - m_InputFilter = NULL; - m_OutputFilter = NULL; + m_InputFilter = ITK_NULLPTR; + m_OutputFilter = ITK_NULLPTR; this->m_Dimension = ImageDimension - 1; m_SliceIndex = 0; } @@ -113,7 +113,7 @@ SliceBySliceImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, { OutputFilterType *outputFilter = dynamic_cast< OutputFilterType * >( filter ); - if ( outputFilter == NULL && filter != NULL ) + if ( outputFilter == ITK_NULLPTR && filter != ITK_NULLPTR ) { // TODO: can it be replaced by a concept check ? itkExceptionMacro( @@ -130,6 +130,11 @@ SliceBySliceImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalOutputImageType > ::SetInputFilter(InputFilterType *filter) { + if ( !filter ) + { + itkExceptionMacro("InputFilter cannot be NULL."); + } + if ( m_InputFilter.GetPointer() != filter ) { this->Modified(); @@ -146,6 +151,11 @@ SliceBySliceImageFilter< TInputImage, TOutputImage, TInputFilter, TOutputFilter, TInternalOutputImageType > ::SetOutputFilter(OutputFilterType *filter) { + if ( !filter ) + { + itkExceptionMacro("OutputFilter cannot be NULL."); + } + if ( m_OutputFilter.GetPointer() != filter ) { this->Modified(); diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkTileImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkTileImageFilter.hxx index 2a932d823ad55d309bc88c57727edb77e4154e9f..875f41fbe9d39147d17e1bc2b1e9bfdab2ec3dd3 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkTileImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkTileImageFilter.hxx @@ -26,6 +26,7 @@ #include "itkPasteImageFilter.h" #include "itkImportImageContainer.h" #include "itkNumericTraitsRGBPixel.h" +#include "itkProgressAccumulator.h" namespace itk { @@ -42,6 +43,9 @@ void TileImageFilter< TInputImage, TOutputImage > ::GenerateData() { + ProgressAccumulator::Pointer progress = ProgressAccumulator::New(); + progress->SetMiniPipelineFilter(this); + typename TOutputImage::Pointer output = this->GetOutput(); @@ -52,6 +56,19 @@ TileImageFilter< TInputImage, TOutputImage > output->FillBuffer(m_DefaultPixelValue); ImageRegionIterator< TileImageType > it( m_TileImage, m_TileImage->GetBufferedRegion() ); + it.GoToBegin(); + + SizeValueType numPastes = 0; + while ( !it.IsAtEnd() ) + { + if ( it.Get().m_ImageNumber >= 0 ) + { + ++numPastes; + } + ++it; + } + const float progressContrib = 1.0f/numPastes; + it.GoToBegin(); while ( !it.IsAtEnd() ) { @@ -62,6 +79,8 @@ TileImageFilter< TInputImage, TOutputImage > paste->SetDestinationImage(output); paste->InPlaceOn(); + progress->RegisterInternalFilter(paste, progressContrib); + // Create a temporary image that has the same dimensions as the // output image. The additional dimensions are set to 1. The // temporary image will use the same container as the input diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkVectorResampleImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkVectorResampleImageFilter.hxx index e2200c70a1dfd0cc5853c87b84be099b481bd2f7..6a5f5adc4b401da66fc699a117d7f3a5218850e3 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkVectorResampleImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkVectorResampleImageFilter.hxx @@ -133,7 +133,7 @@ VectorResampleImageFilter< TInputImage, TOutputImage, TInterpolatorPrecisionType ::AfterThreadedGenerateData() { // Disconnect input image from the interpolator - m_Interpolator->SetInputImage(NULL); + m_Interpolator->SetInputImage(ITK_NULLPTR); } /** diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkWarpImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkWarpImageFilter.hxx index d884fb74d3ab002d2d52bbb4cf498a334588ca78..95df7b7f55f7f38aa69e09f9e9a16862a48260fb 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkWarpImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/include/itkWarpImageFilter.hxx @@ -50,6 +50,8 @@ WarpImageFilter< TInputImage, TOutputImage, TDisplacementField > m_Interpolator = static_cast< InterpolatorType * >( interp.GetPointer() ); + + m_DefFieldSizeSame = false; } /** @@ -203,7 +205,7 @@ WarpImageFilter< TInputImage, TOutputImage, TDisplacementField > ::AfterThreadedGenerateData() { // Disconnect input image from interpolator - m_Interpolator->SetInputImage(NULL); + m_Interpolator->SetInputImage(ITK_NULLPTR); } template< typename TInputImage, typename TOutputImage, typename TDisplacementField > diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkBinShrinkImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkBinShrinkImageFilter.wrap index b49ece81f7e7ceade6241bb5cad9eabe98696b53..32499b13b504b3d9102133ef8bf3ade9bfc943b3 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkBinShrinkImageFilter.wrap +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkBinShrinkImageFilter.wrap @@ -1,5 +1,4 @@ itk_wrap_class("itk::BinShrinkImageFilter" POINTER) - itk_wrap_image_filter("${WRAP_ITK_SCALAR}" 2) itk_wrap_image_filter("${WRAP_ITK_RGB}" 2) itk_wrap_image_filter("${WRAP_ITK_RGBA}" 2) # VS9 (2008) does not correctly implicitly cast itk::Vector for operator += diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkOrientImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkOrientImageFilter.wrap index ca2167536ac38ee87810415394903f10b15395a8..641375f125d411d45ebfde6ee210ec5a8e227be9 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkOrientImageFilter.wrap +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkOrientImageFilter.wrap @@ -1,3 +1,7 @@ -itk_wrap_class("itk::OrientImageFilter" POINTER) - itk_wrap_image_filter("${WRAP_ITK_ALL_TYPES}" 2 3) -itk_end_wrap_class() +itk_wrap_filter_dims(has_d_3 3) + +if(has_d_3) + itk_wrap_class("itk::OrientImageFilter" POINTER) + itk_wrap_image_filter("${WRAP_ITK_ALL_TYPES}" 2 3) + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkSliceBySliceImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkSliceBySliceImageFilter.wrap index 03fac31374b3f082ca0a88ff7b029c01fcfff234..e179e1457befd230e174acd0b575804f9f723e4b 100644 --- a/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkSliceBySliceImageFilter.wrap +++ b/Utilities/ITK/Modules/Filtering/ImageGrid/wrapping/itkSliceBySliceImageFilter.wrap @@ -1,13 +1,22 @@ -itk_wrap_class("itk::SliceBySliceImageFilter" POINTER) - foreach(d ${ITK_WRAP_DIMS}) - math(EXPR d_1 "${d} - 1") - itk_wrap_filter_dims(has_d_1 ${d_1}) - if(has_d_1) - # avoid the vector and covariant vector types: the type - # Image< Vector< T, N >, N-1 > is not wrapped - itk_wrap_image_filter("${WRAP_ITK_SCALAR}" 2 ${d}) - itk_wrap_image_filter("${WRAP_ITK_RGB}" 2 ${d}) - itk_wrap_image_filter("${WRAP_ITK_COMPLEX_REAL}" 2 ${d}) - endif(has_d_1) - endforeach(d) -itk_end_wrap_class() +# Check if we have the right dimensions before wrapping +foreach(d ${ITK_WRAP_DIMS}) + math(EXPR d_1 "${d} - 1") +endforeach(d) +itk_wrap_filter_dims(has_d_1 ${d_1}) + +# Wrap if allowed +if(has_d_1) + itk_wrap_class("itk::SliceBySliceImageFilter" POINTER) + foreach(d ${ITK_WRAP_DIMS}) + math(EXPR d_1 "${d} - 1") + itk_wrap_filter_dims(has_d_1 ${d_1}) + if(has_d_1) + # avoid the vector and covariant vector types: the type + # Image< Vector< T, N >, N-1 > is not wrapped + itk_wrap_image_filter("${WRAP_ITK_SCALAR}" 2 ${d}) + itk_wrap_image_filter("${WRAP_ITK_RGB}" 2 ${d}) + itk_wrap_image_filter("${WRAP_ITK_COMPLEX_REAL}" 2 ${d}) + endif(has_d_1) + endforeach(d) + itk_end_wrap_class() +endif(has_d_1) diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAcosImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAcosImageFilter.h index 03abc442dac8661a600256d4a5965782fbf48ca0..eceb9853643181685d061738842f41fac4781fb4 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAcosImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAcosImageFilter.h @@ -48,7 +48,7 @@ public: inline TOutput operator()(const TInput & A) const { - return static_cast< TOutput >( vcl_acos( static_cast< double >( A ) ) ); + return static_cast< TOutput >( std::acos( static_cast< double >( A ) ) ); } }; } @@ -63,8 +63,8 @@ public: * each pixel does do the following: * * \li cast the pixel value to \c double, - * \li apply the \c vcl_acos() function to the \c double value - * \li cast the \c double value resulting from \c vcl_acos() to the pixel type + * \li apply the \c std::acos() function to the \c double value + * \li cast the \c double value resulting from \c std::acos() to the pixel type * of the output image * \li store the casted value into the output image. * diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAdaptImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAdaptImageFilter.h index 1551a41e5428668b61ea69beeef33b5b7cf3e582..722a53434ebd271ddd9dfd67e63da85a497f860e 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAdaptImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAdaptImageFilter.h @@ -100,7 +100,7 @@ private: * (i.e. short to float) or can extract a subcomponent of a pixel * (i.e. extract the green component of an RGB pixel. * AdaptImageFilter could also be used for performing simple - * arithmetic operations at a pixel (i.e. taking the vcl_sqrt() or vcl_sin() + * arithmetic operations at a pixel (i.e. taking the std::sqrt() or std::sin() * of a pixel); however, these types of operations could also be * accomplished using the itk::UnaryImageFilter. * diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAsinImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAsinImageFilter.h index b169fa5ea75d6bc066e123f5a5cdf933af0ffc75..daaa413827e5b211ecc8e3994ae9c6857f0774d7 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAsinImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAsinImageFilter.h @@ -49,7 +49,7 @@ public: inline TOutput operator()(const TInput & A) const { return static_cast< TOutput >( - vcl_asin( + std::asin( static_cast< double >( A ) ) ); @@ -66,8 +66,8 @@ public: * each pixel does the following: * * \li cast the pixel value to \c double, - * \li apply the \c vcl_asin() function to the \c double value, - * \li cast the \c double value resulting from \c vcl_asin() to the + * \li apply the \c std::asin() function to the \c double value, + * \li cast the \c double value resulting from \c std::asin() to the * pixel type of the output image, * \li store the casted value into the output image. * diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAtan2ImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAtan2ImageFilter.h index 8d72fa6f2c71fcd1838d41485d2af4f51acda053..6ad463c691fb55a36cbcb9ce2457e20a085313be 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAtan2ImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAtan2ImageFilter.h @@ -49,7 +49,7 @@ public: inline TOutput operator()(const TInput1 & A, const TInput2 & B) const { return static_cast< TOutput >( - vcl_atan2( + std::atan2( static_cast< double >( A ), static_cast< double >( B ) ) ); @@ -69,7 +69,7 @@ public: * Numeric conversions (castings) are done by the C++ defaults. * * Both pixel input types are cast to \c double in order to be - * used as parameters of \c vcl_atan2(). The resulting \c double value + * used as parameters of \c std::atan2(). The resulting \c double value * is cast to the output pixel type. * * \ingroup IntensityImageFilters diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAtanImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAtanImageFilter.h index c75f8cabf3fa71f264c487903752689928085f53..f722794f149b89b19e16826a0b09831375166c27 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAtanImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkAtanImageFilter.h @@ -48,7 +48,7 @@ public: inline TOutput operator()(const TInput & A) const { - return static_cast< TOutput >( vcl_atan( static_cast< double >( A ) ) ); + return static_cast< TOutput >( std::atan( static_cast< double >( A ) ) ); } }; } @@ -62,8 +62,8 @@ public: * each pixel does the following: * * \li cast the pixel value to \c double, - * \li apply the \c vcl_atan() function to the \c double value, - * \li cast the \c double value resulting from \c vcl_atan() to the pixel + * \li apply the \c std::atan() function to the \c double value, + * \li cast the \c double value resulting from \c std::atan() to the pixel * type of the output image, * \li store the cast value into the output image. * diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkBinaryMagnitudeImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkBinaryMagnitudeImageFilter.h index e8fafc53e5fc02e064e0586f8abf3269ae1d670c..f4dd6c208bec3d1bac75ea7a416b907137d0b891 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkBinaryMagnitudeImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkBinaryMagnitudeImageFilter.h @@ -51,7 +51,7 @@ public: const double dA = static_cast< double >( A ); const double dB = static_cast< double >( B ); - return static_cast< TOutput >( vcl_sqrt(dA * dA + dB * dB) ); + return static_cast< TOutput >( std::sqrt(dA * dA + dB * dB) ); } }; } @@ -70,7 +70,7 @@ public: * \li cast the input 2 pixel value to \c double * \li compute the sum of squares of the two pixel values * \li compute the square root of the sum - * \li cast the \c double value resulting from \c vcl_sqrt() to the pixel type of the output image + * \li cast the \c double value resulting from \c std::sqrt() to the pixel type of the output image * \li store the cast value into the output image. * * The filter expects all images to have the same dimension diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkComplexToModulusImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkComplexToModulusImageFilter.h index 2df75bd9ce2ee67ec9513e96cae457ec37934d9e..9fb8db4b67a1fa0ac08f87cf7cde399851979212 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkComplexToModulusImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkComplexToModulusImageFilter.h @@ -49,7 +49,7 @@ public: inline TOutput operator()(const TInput & A) const { - return (TOutput)( vcl_sqrt( A.real() * A.real() + return (TOutput)( std::sqrt( A.real() * A.real() + A.imag() * A.imag() ) ); } }; diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkComplexToPhaseImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkComplexToPhaseImageFilter.h index 92689cd740dc9455983dbc79f5e6e18ceb7d82e8..e54c72100c316a73fb40fc144b0746d0232c7e9e 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkComplexToPhaseImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkComplexToPhaseImageFilter.h @@ -49,7 +49,7 @@ public: inline TOutput operator()(const TInput & A) const { - return (TOutput)( vcl_atan2( A.imag(), A.real() ) ); + return (TOutput)( std::atan2( A.imag(), A.real() ) ); } }; } diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkCosImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkCosImageFilter.h index b68b41f2f17f05908a3d3c4ff2b8a7a6da2a1cb5..3598d6dabde755b7010a197696342cf6fbdbe80b 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkCosImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkCosImageFilter.h @@ -48,7 +48,7 @@ public: inline TOutput operator()(const TInput & A) const { - return static_cast< TOutput >( vcl_cos( static_cast< double >( A ) ) ); + return static_cast< TOutput >( std::cos( static_cast< double >( A ) ) ); } }; } @@ -62,8 +62,8 @@ public: * each pixel does the following: * * \li cast the pixel value to \c double, - * \li apply the \c vcl_cos() function to the \c double value, - * \li cast the \c double value resulting from \c vcl_cos() to the pixel type of the output image, + * \li apply the \c std::cos() function to the \c double value, + * \li cast the \c double value resulting from \c std::cos() to the pixel type of the output image, * \li store the cast value into the output image. * * The filter expects both images to have the same dimension (e.g. both diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkDivideImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkDivideImageFilter.h index d15c76c7ff9c86d25a6a82a2df63a138d1c3e928..28f485dae3d67f55663b1e2ccec62c235cac5df4 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkDivideImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkDivideImageFilter.h @@ -136,7 +136,7 @@ protected: const typename Superclass::DecoratedInput2ImagePixelType *input = dynamic_cast< const typename Superclass::DecoratedInput2ImagePixelType * >( this->ProcessObject::GetInput(1) ); - if( input != NULL && input->Get() == itk::NumericTraits< typename TInputImage2::PixelType >::Zero ) + if( input != ITK_NULLPTR && input->Get() == itk::NumericTraits< typename TInputImage2::PixelType >::Zero ) { itkGenericExceptionMacro(<<"The constant value used as denominator should not be set to zero"); } diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkEdgePotentialImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkEdgePotentialImageFilter.h index 0c669067ccf6075ed1c315e2c3a784cfd62a309e..9d83337c5b9d93e8ace46c7394d8c52fb9e205ed 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkEdgePotentialImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkEdgePotentialImageFilter.h @@ -54,7 +54,7 @@ public: inline TOutput operator()(const TInput & A) const { - return static_cast< TOutput >( vcl_exp( -1.0 * A.GetNorm() ) ); + return static_cast< TOutput >( std::exp( -1.0 * A.GetNorm() ) ); } }; } diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkExpImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkExpImageFilter.h index 3d5387c29df6cd4bf1c480902b4453a8987166f1..dd6af5345f3cc8df7897acacce7da799494c3854 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkExpImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkExpImageFilter.h @@ -48,14 +48,14 @@ public: inline TOutput operator()(const TInput & A) const { - return (TOutput)vcl_exp( (double)A ); + return (TOutput)std::exp( (double)A ); } }; } /** \class ExpImageFilter * \brief Computes the exponential function of each pixel. * - * The computation is performed using vcl_exp(x). + * The computation is performed using std::exp(x). * * \ingroup IntensityImageFilters * \ingroup MultiThreaded diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkExpNegativeImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkExpNegativeImageFilter.h index 7fb6ca647d1f002590d95f08c072ce083fb4d279..30e7a03a37389a6a825d96e5eda2b0c63a44842f 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkExpNegativeImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkExpNegativeImageFilter.h @@ -53,7 +53,7 @@ public: inline TOutput operator()(const TInput & A) const { - return static_cast< TOutput >( vcl_exp( -m_Factor * static_cast< double >( A ) ) ); + return static_cast< TOutput >( std::exp( -m_Factor * static_cast< double >( A ) ) ); } /** Sets the value 'K' used in the function evaluation exp(-K.x). */ @@ -74,7 +74,7 @@ private: /** \class ExpNegativeImageFilter * \brief Computes the function exp(-K.x) for each input pixel. * - * Every output pixel is equal to vcl_exp(-K.x ). where x is the + * Every output pixel is equal to std::exp(-K.x ). where x is the * intensity of the homologous input pixel, and K is a user-provided * constant. * diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkHistogramMatchingImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkHistogramMatchingImageFilter.hxx index 54498e36fd40be01e60cea4cab6dee95d4c370e2..560cb7d3590f5a61a4e923672b4a7d7d55601cb2 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkHistogramMatchingImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkHistogramMatchingImageFilter.hxx @@ -30,28 +30,34 @@ namespace itk */ template< typename TInputImage, typename TOutputImage, typename THistogramMeasurement > HistogramMatchingImageFilter< TInputImage, TOutputImage, THistogramMeasurement > -::HistogramMatchingImageFilter() +::HistogramMatchingImageFilter() : + m_NumberOfHistogramLevels(256), + m_NumberOfMatchPoints(1), + m_ThresholdAtMeanIntensity(true), + m_SourceIntensityThreshold(NumericTraits<InputPixelType>::Zero), + m_ReferenceIntensityThreshold(NumericTraits<InputPixelType>::Zero), + m_OutputIntensityThreshold(NumericTraits<OutputPixelType>::Zero), + m_SourceMinValue(NumericTraits<THistogramMeasurement>::Zero), + m_SourceMaxValue(NumericTraits<THistogramMeasurement>::Zero), + m_SourceMeanValue(NumericTraits<THistogramMeasurement>::Zero), + m_ReferenceMinValue(NumericTraits<THistogramMeasurement>::Zero), + m_ReferenceMaxValue(NumericTraits<THistogramMeasurement>::Zero), + m_ReferenceMeanValue(NumericTraits<THistogramMeasurement>::Zero), + m_OutputMinValue(NumericTraits<THistogramMeasurement>::Zero), + m_OutputMaxValue(NumericTraits<THistogramMeasurement>::Zero), + m_OutputMeanValue(NumericTraits<THistogramMeasurement>::Zero), + m_SourceHistogram(HistogramType::New()), + m_ReferenceHistogram(HistogramType::New()), + m_OutputHistogram(HistogramType::New()), + m_LowerGradient(0.0), + m_UpperGradient(0.0) { this->SetNumberOfRequiredInputs(2); - m_NumberOfHistogramLevels = 256; - m_NumberOfMatchPoints = 1; - m_QuantileTable.set_size(3, m_NumberOfMatchPoints + 2); m_QuantileTable.fill(0); m_Gradients.set_size(m_NumberOfMatchPoints + 1); m_Gradients.fill(0); - - m_ThresholdAtMeanIntensity = true; - m_SourceIntensityThreshold = 0; - m_ReferenceIntensityThreshold = 0; - m_LowerGradient = 0.0; - m_UpperGradient = 0.0; - - // Create histograms. - m_SourceHistogram = HistogramType::New(); - m_ReferenceHistogram = HistogramType::New(); - m_OutputHistogram = HistogramType::New(); } /* @@ -398,7 +404,7 @@ HistogramMatchingImageFilter< TInputImage, TOutputImage, THistogramMeasurement > const THistogramMeasurement minValue, const THistogramMeasurement maxValue) { - { + { // allocate memory for the histogram typename HistogramType::SizeType size; typename HistogramType::MeasurementVectorType lowerBound; @@ -416,15 +422,15 @@ HistogramMatchingImageFilter< TInputImage, TOutputImage, THistogramMeasurement > //Initialize with equally spaced bins. histogram->Initialize(size, lowerBound, upperBound); histogram->SetToZero(); - } - - typename HistogramType::MeasurementVectorType measurement; - measurement.SetSize(1); + } + typename HistogramType::IndexType index(1); + typename HistogramType::MeasurementVectorType measurement(1); typedef typename HistogramType::MeasurementType MeasurementType; measurement[0] = NumericTraits< MeasurementType >::Zero; { + // put each image pixel into the histogram typedef ImageRegionConstIterator< InputImageType > ConstIterator; ConstIterator iter( image, image->GetBufferedRegion() ); @@ -439,7 +445,8 @@ HistogramMatchingImageFilter< TInputImage, TOutputImage, THistogramMeasurement > { // add sample to histogram measurement[0] = value; - histogram->IncreaseFrequencyOfMeasurement(measurement, 1); + histogram->GetIndex( measurement, index ); + histogram->IncreaseFrequencyOfIndex( index, 1 ); } ++iter; } diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkIntensityWindowingImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkIntensityWindowingImageFilter.h index 489e9eee54f59b86a39f264ac60e16a79e59447d..caa53407f9b53c90da4a4e186ed3eeed137110e1 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkIntensityWindowingImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkIntensityWindowingImageFilter.h @@ -32,7 +32,13 @@ class IntensityWindowingTransform { public: typedef typename NumericTraits< TInput >::RealType RealType; - IntensityWindowingTransform() {} + IntensityWindowingTransform() : + m_Factor(0.0), + m_Offset(0.0), + m_OutputMaximum(0), + m_OutputMinimum(0), + m_WindowMaximum(0), + m_WindowMinimum(0) {} ~IntensityWindowingTransform() {} bool operator!=(const IntensityWindowingTransform & other) const { diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkLog10ImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkLog10ImageFilter.h index b2be24f3e200879063092ad4939aecbeed5d4f16..7c07d32e38ef4938865863bff39b7858993084ec 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkLog10ImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkLog10ImageFilter.h @@ -48,14 +48,14 @@ public: inline TOutput operator()(const TInput & A) const { - return static_cast< TOutput >( vcl_log10( static_cast< double >( A ) ) ); + return static_cast< TOutput >( std::log10( static_cast< double >( A ) ) ); } }; } /** \class Log10ImageFilter * \brief Computes the log10 of each pixel. * - * The computation is performed using vcl_log10(x). + * The computation is performed using std::log10(x). * * \ingroup IntensityImageFilters * \ingroup MultiThreaded diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkLogImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkLogImageFilter.h index 9403b615501c3364a75129c6a2d4b22240bfbbb6..38f02bee0221a3220f50457aaf7e185dc63a0e5e 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkLogImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkLogImageFilter.h @@ -48,7 +48,7 @@ public: inline TOutput operator()(const TInput & A) const { - return static_cast< TOutput >( vcl_log( static_cast< double >( A ) ) ); + return static_cast< TOutput >( std::log( static_cast< double >( A ) ) ); } }; } diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMagnitudeAndPhaseToComplexImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMagnitudeAndPhaseToComplexImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..f13cebb9679fd38f60e7d2fe49950ff5f9b53ed3 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMagnitudeAndPhaseToComplexImageFilter.h @@ -0,0 +1,142 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkMagnitudeAndPhaseToComplexImageFilter_h +#define __itkMagnitudeAndPhaseToComplexImageFilter_h + +#include "itkBinaryFunctorImageFilter.h" + +namespace itk +{ +/** \class MagnitudeAndPhaseToComplexImageFilter + * + * \brief Implements pixel-wise conversion of magnitude and phase data into + * complex voxels. + * + * This filter is parametrized over the types of the two + * input images and the type of the output image. + * + * The filter expect all images to have the same dimension + * (e.g. all 2D, or all 3D, or all ND) + * + * \ingroup IntensityImageFilters MultiThreaded + * + * \weakgroup FourierTransform + * + * \author Simon K. Warfield simon.warfield@childrens.harvard.edu + * + * \note Attribution Notice. This research work was made possible by Grant + * Number R01 RR021885 (PI Simon K. Warfield, Ph.D.) from the National Center + * for Research Resources (NCRR), a component of the National Institutes of + * Health (NIH). Its contents are solely the responsibility of the authors + * and do not necessarily represent the official view of NCRR or NIH. + * + * This class was taken from the Insight Journal paper: + * http://hdl.handle.net/1926/326 + * + * \sa ComposeImageFilter + * + * \ingroup ITKImageIntensity + */ +namespace Functor +{ +template< typename TInput1, typename TInput2, typename TOutput > +class MagnitudeAndPhaseToComplex +{ +public: + MagnitudeAndPhaseToComplex() {} + ~MagnitudeAndPhaseToComplex() {} + bool operator!=(const MagnitudeAndPhaseToComplex &) const + { + return false; + } + + bool operator==(const MagnitudeAndPhaseToComplex & other) const + { + return !( *this != other ); + } + + inline std::complex< TOutput > operator()(const TInput1 & A, const TInput2 & B) const + { + return std::complex< TOutput >( std::polar( static_cast< TOutput >( A ), static_cast< TOutput >( B ) ) ); + } +}; +} + +template< typename TInputImage1, + typename TInputImage2 = TInputImage1, + typename TOutputImage = itk::Image< std::complex< typename TInputImage1::PixelType >, + TInputImage1::ImageDimension > > +class MagnitudeAndPhaseToComplexImageFilter: + public BinaryFunctorImageFilter< + TInputImage1, + TInputImage2, + TOutputImage, + Functor::MagnitudeAndPhaseToComplex< + typename TInputImage1::PixelType, + typename TInputImage2::PixelType, + typename TOutputImage::PixelType::value_type > > + +{ +public: + /** Standard class typedefs. */ + typedef MagnitudeAndPhaseToComplexImageFilter Self; + + typedef BinaryFunctorImageFilter< + TInputImage1, + TInputImage2, + TOutputImage, + Functor::MagnitudeAndPhaseToComplex< + typename TInputImage1::PixelType, + typename TInputImage2::PixelType, + typename TOutputImage::PixelType::value_type > > Superclass; + + typedef typename TInputImage1::PixelType InputPixel1Type; + typedef typename TInputImage2::PixelType InputPixel2Type; + typedef typename TOutputImage::PixelType OutputPixelType; + + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(MagnitudeAndPhaseToComplexImageFilter, BinaryFunctorImageFilter); + +#ifdef ITK_USE_CONCEPT_CHECKING + // Begin concept checking + itkConceptMacro( Input1ConvertibleToDoubleCheck, + ( Concept::Convertible< InputPixel1Type, double > ) ); + itkConceptMacro( Input2ConvertibleToDoubleCheck, + ( Concept::Convertible< InputPixel2Type, double > ) ); + itkConceptMacro( DoubleConvertibleToOutputCheck, + ( Concept::Convertible< double, OutputPixelType > ) ); + // End concept checking +#endif + +protected: + MagnitudeAndPhaseToComplexImageFilter() {} + virtual ~MagnitudeAndPhaseToComplexImageFilter() {} + +private: + MagnitudeAndPhaseToComplexImageFilter(const Self &); //purposely not implemented + void operator=(const Self &); //purposely not implemented +}; +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMaskImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMaskImageFilter.h index 5e3d95457cfaa790a2dfe11978801edba9c31e44..fb319cd80c398ceaf8508dff43f574e13b4e6282 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMaskImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMaskImageFilter.h @@ -40,7 +40,7 @@ public: MaskInput() { m_MaskingValue = NumericTraits< TMask >::ZeroValue(); - InitializeOutsideValue( static_cast<TOutput*>( NULL ) ); + InitializeOutsideValue( static_cast<TOutput*>( ITK_NULLPTR ) ); } ~MaskInput() {} bool operator!=(const MaskInput &) const @@ -93,14 +93,14 @@ private: template < typename TPixelType > void InitializeOutsideValue( TPixelType * ) { - this->m_OutsideValue = NumericTraits< TPixelType >::Zero; + this->m_OutsideValue = NumericTraits< TPixelType >::ZeroValue(); } - template < typename TValueType > - void InitializeOutsideValue( VariableLengthVector<TValueType> * ) + template < typename TValue > + void InitializeOutsideValue( VariableLengthVector<TValue> * ) { // set the outside value to be of zero length - this->m_OutsideValue = VariableLengthVector< TValueType >(0); + this->m_OutsideValue = VariableLengthVector< TValue >(0); } TOutput m_OutsideValue; @@ -221,7 +221,7 @@ public: void BeforeThreadedGenerateData() { typedef typename TOutputImage::PixelType PixelType; - this->CheckOutsideValue( static_cast<PixelType*>(NULL) ); + this->CheckOutsideValue( static_cast<PixelType*>(ITK_NULLPTR) ); } #ifdef ITK_USE_CONCEPT_CHECKING @@ -262,12 +262,12 @@ private: VariableLengthVector< TValue > currentValue = this->GetFunctor().GetOutsideValue(); VariableLengthVector< TValue > zeroVector( currentValue.GetSize() ); - zeroVector.Fill( NumericTraits< TValue >::Zero ); + zeroVector.Fill( NumericTraits< TValue >::ZeroValue() ); if ( currentValue == zeroVector ) { zeroVector.SetSize( this->GetOutput()->GetVectorLength() ); - zeroVector.Fill( NumericTraits< TValue >::Zero ); + zeroVector.Fill( NumericTraits< TValue >::ZeroValue() ); this->GetFunctor().SetOutsideValue( zeroVector ); } else if ( this->GetFunctor().GetOutsideValue().GetSize() != diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMaskNegatedImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMaskNegatedImageFilter.h index c39d70224167510b51ab75126bc749a269bc7271..ca453784a975baea8d334e8f30ca063562f2bb18 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMaskNegatedImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkMaskNegatedImageFilter.h @@ -37,7 +37,7 @@ public: typedef typename NumericTraits< TInput >::AccumulateType AccumulatorType; MaskNegatedInput() - : m_OutsideValue(NumericTraits< TOutput >::Zero) + : m_OutsideValue(NumericTraits< TOutput >::ZeroValue()) , m_MaskingValue(NumericTraits< TMask >::ZeroValue()) { } diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkNormalizeImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkNormalizeImageFilter.hxx index 59793351f91ccb7699f6a78da10466dd694e1271..6507b11f30f2ad00f535c5c0ab7e79c8254d9db0 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkNormalizeImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkNormalizeImageFilter.hxx @@ -28,7 +28,7 @@ template< typename TInputImage, typename TOutputImage > NormalizeImageFilter< TInputImage, TOutputImage > ::NormalizeImageFilter() { - m_StatisticsFilter = 0; + m_StatisticsFilter = ITK_NULLPTR; m_StatisticsFilter = StatisticsImageFilter< TInputImage >::New(); m_ShiftScaleFilter = ShiftScaleImageFilter< TInputImage, TOutputImage >::New(); } diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPolylineMask2DImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPolylineMask2DImageFilter.hxx index 20e26916dd67ebcd1b65bc5363befcd3e7e7a674..a21c1a319b5d13a44652801bfc872d5ee1794e8b 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPolylineMask2DImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPolylineMask2DImageFilter.hxx @@ -83,7 +83,6 @@ void PolylineMask2DImageFilter< TInputImage, TPolyline, TOutputImage > typedef typename TOutputImage::PixelType PixelType; typedef ImageRegionIterator< TOutputImage > OutputImageIteratorType; - typedef typename TPolyline::Pointer PolylinePointer; typedef typename TPolyline::VertexType VertexType; typedef typename TPolyline::VertexListType VertexListType; @@ -105,7 +104,6 @@ void PolylineMask2DImageFilter< TInputImage, TPolyline, TOutputImage > outputImagePtr->SetLargestPossibleRegion( inputImagePtr->GetLargestPossibleRegion() ); outputImagePtr->Allocate(); - typedef typename VertexListType::Pointer VertexListPointer; const VertexListType *container = polylinePtr->GetVertexList(); diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPolylineMaskImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPolylineMaskImageFilter.hxx index 439503086fd4f230cfd536cfbee2dd92041306c0..4e9d352599109e3adebfc622975e45df85d84860 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPolylineMaskImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPolylineMaskImageFilter.hxx @@ -188,14 +188,11 @@ void PolylineMaskImageFilter< TInputImage, TPolyline, TVector, TOutputImage > typedef typename TInputImage::SpacingType InputImageSpacingType; typedef ImageRegionConstIterator< TInputImage > InputImageConstIteratorType; - typedef typename TOutputImage::IndexType ImageIndexType; typedef typename TOutputImage::PixelType PixelType; typedef ImageRegionIterator< TOutputImage > OutputImageIteratorType; - typedef typename TPolyline::Pointer PolylinePointer; typedef typename TPolyline::VertexType VertexType; typedef typename TPolyline::VertexListType VertexListType; - typedef typename TPolyline::IndexType PolylineIndexType; typedef Point< double, 3 > OriginType; @@ -219,14 +216,13 @@ void PolylineMaskImageFilter< TInputImage, TPolyline, TVector, TOutputImage > outputImagePtr->SetRequestedRegion( inputImagePtr->GetRequestedRegion() ); outputImagePtr->SetBufferedRegion( inputImagePtr->GetBufferedRegion() ); outputImagePtr->SetLargestPossibleRegion( inputImagePtr->GetLargestPossibleRegion() ); - outputImagePtr->Allocate(); - outputImagePtr->FillBuffer(0); + outputImagePtr->Allocate(true); // initialize + // buffer to zero InputImageConstIteratorType inputIt( inputImagePtr, inputImagePtr->GetLargestPossibleRegion() ); OutputImageIteratorType outputIt( outputImagePtr, outputImagePtr->GetLargestPossibleRegion() ); typedef NearestNeighborInterpolateImageFunction< TInputImage, double > InterpolatorType; - typedef typename InterpolatorType::OutputType OutputType; typedef typename InterpolatorType::PointType InterpolatorPointType; /* Generate the transformation matrix */ @@ -394,16 +390,15 @@ void PolylineMaskImageFilter< TInputImage, TPolyline, TVector, TOutputImage > projectionImagePtr->SetRequestedRegion(projectionRegion); projectionImagePtr->SetBufferedRegion(projectionRegion); projectionImagePtr->SetLargestPossibleRegion(projectionRegion); - projectionImagePtr->Allocate(); - projectionImagePtr->FillBuffer(0); + projectionImagePtr->Allocate(true); // initialize + // buffer + // to zero typedef ImageRegionIterator< ProjectionImageType > ProjectionImageIteratorType; ProjectionImageIteratorType projectionIt( projectionImagePtr, projectionImagePtr->GetLargestPossibleRegion() ); itkDebugMacro(<< "Rotation matrix" << m_RotationMatrix); - typedef typename VertexListType::Pointer VertexListPointer; - const VertexListType *container = polylinePtr->GetVertexList(); typename VertexListType::ConstIterator piter = container->Begin(); diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPowImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPowImageFilter.h index 2573e563f69e7f2ad0118d8a5b94fcc95cb339cc..f7694133bc2b953f62de451aeb4544e199e03bb6 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPowImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkPowImageFilter.h @@ -51,7 +51,7 @@ public: { typedef typename NumericTraits< TInput1 >::RealType RealType; - return static_cast< TOutput >( vcl_pow(static_cast<RealType>(A),static_cast<RealType>(B)) ); + return static_cast< TOutput >( std::pow(static_cast<RealType>(A),static_cast<RealType>(B)) ); } }; } @@ -67,7 +67,7 @@ public: * * The total operation over one pixel will be * \code - * output_pixel = static_cast< TOutput >( vcl_pow(static_cast<RealType>(A),static_cast<RealType>(B)) ); + * output_pixel = static_cast< TOutput >( std::pow(static_cast<RealType>(A),static_cast<RealType>(B)) ); * \endcode * * The pow function can be applied to two images with the following: diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkShiftScaleImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkShiftScaleImageFilter.hxx index fdea7afc78796c2e28d901015157698226b4a990..68bbd39c3ea7706e7c53c54290827f51bfcf1231 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkShiftScaleImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkShiftScaleImageFilter.hxx @@ -35,8 +35,8 @@ ShiftScaleImageFilter< TInputImage, TOutputImage > m_OverflowCount = 0; m_ThreadUnderflow.SetSize(1); m_ThreadOverflow.SetSize(1); - m_InputImage = 0; - m_OutputImage = 0; + m_InputImage = ITK_NULLPTR; + m_OutputImage = ITK_NULLPTR; } template< typename TInputImage, typename TOutputImage > diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSigmoidImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSigmoidImageFilter.h index ea1f2d65065db3065d9e0cb6d082f60cb460c0fa..5bddb63d07f6d55196b530c253a9bcdde9a8d01a 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSigmoidImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSigmoidImageFilter.h @@ -79,7 +79,7 @@ public: inline TOutput operator()(const TInput & A) const { const double x = ( static_cast< double >( A ) - m_Beta ) / m_Alpha; - const double e = 1.0 / ( 1.0 + vcl_exp(-x) ); + const double e = 1.0 / ( 1.0 + std::exp(-x) ); const double v = ( m_OutputMaximum - m_OutputMinimum ) * e + m_OutputMinimum; diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSinImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSinImageFilter.h index c02332e33da86f4018c5ac0f9fa8058010dc9e3e..a7e442c8fa1222e176fc3d7a4324ff7dbd271840 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSinImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSinImageFilter.h @@ -47,13 +47,13 @@ public: } inline TOutput operator()(const TInput & A) const - { return (TOutput)vcl_sin( (double)A ); } + { return (TOutput)std::sin( (double)A ); } }; } /** \class SinImageFilter * \brief Computes the sine of each pixel. * - * The computations are performed using vcl_sin(x). + * The computations are performed using std::sin(x). * * \ingroup IntensityImageFilters * \ingroup MultiThreaded diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSqrtImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSqrtImageFilter.h index edae9a727d00edadbe1c59c2a72757f087cdb440..c16cd17c68c599bfa2630ba76fa61d8de40119aa 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSqrtImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkSqrtImageFilter.h @@ -48,14 +48,14 @@ public: inline TOutput operator()(const TInput & A) const { - return (TOutput)vcl_sqrt( (double)A ); + return (TOutput)std::sqrt( (double)A ); } }; } /** \class SqrtImageFilter * \brief Computes the square root of each pixel. * - * The computations are performed using vcl_sqrt(x). + * The computations are performed using std::sqrt(x). * * \ingroup IntensityImageFilters * \ingroup MultiThreaded diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkTanImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkTanImageFilter.h index e7ec8afd811fa81bbc25c145ce5212a8fa57cf06..96cca56231de9729cb90be95009f223f02b92fdf 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkTanImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkTanImageFilter.h @@ -47,13 +47,13 @@ public: } inline TOutput operator()(const TInput & A) const - { return (TOutput)vcl_tan( (double)A ); } + { return (TOutput)std::tan( (double)A ); } }; } /** \class TanImageFilter * \brief Computes the tangent of each input pixel. * - * The computations are performed using vcl_tan(x). + * The computations are performed using std::tan(x). * * \ingroup IntensityImageFilters * \ingroup MultiThreaded diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkTernaryMagnitudeImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkTernaryMagnitudeImageFilter.h index 4630de258a842eff919961b40a0778c2493cb76f..6bcbcf2e6bd99a44d0bbd1264b4cff45bef11a16 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkTernaryMagnitudeImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkTernaryMagnitudeImageFilter.h @@ -48,7 +48,7 @@ public: inline TOutput operator()(const TInput1 & A, const TInput2 & B, const TInput3 & C) const - { return (TOutput)vcl_sqrt( (double)( A * A + B * B + C * C ) ); } + { return (TOutput)std::sqrt( (double)( A * A + B * B + C * C ) ); } }; } /** \class TernaryMagnitudeImageFilter diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorExpandImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorExpandImageFilter.hxx index 133e0adbf8b1bc7aa181400ab45f39d1b38e2062..7dbd137445412e020dfccdda5bf0149e73b6e17f 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorExpandImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorExpandImageFilter.hxx @@ -259,11 +259,11 @@ VectorExpandImageFilter< TInputImage, TOutputImage > for ( i = 0; i < TInputImage::ImageDimension; i++ ) { inputRequestedRegionSize[i] = - (SizeValueType)vcl_ceil( (double)outputRequestedRegionSize[i] + (SizeValueType)std::ceil( (double)outputRequestedRegionSize[i] / (double)m_ExpandFactors[i] ) + 1; inputRequestedRegionStartIndex[i] = - (IndexValueType)vcl_floor( (double)outputRequestedRegionStartIndex[i] + (IndexValueType)std::floor( (double)outputRequestedRegionStartIndex[i] / (double)m_ExpandFactors[i] ); } diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorRescaleIntensityImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorRescaleIntensityImageFilter.h index 4444c7e5434b535ef736eb284db8d2f2b6d6a944..be0db949ba8b69950676d5f4442517582d23591a 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorRescaleIntensityImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorRescaleIntensityImageFilter.h @@ -31,7 +31,7 @@ class VectorMagnitudeLinearTransform { public: typedef typename NumericTraits< typename TInput::ValueType >::RealType RealType; - VectorMagnitudeLinearTransform() {} + VectorMagnitudeLinearTransform() : m_Factor(0.0) {} ~VectorMagnitudeLinearTransform() {} void SetFactor(RealType a) { m_Factor = a; } itkStaticConstMacro(VectorDimension, unsigned int, TInput::Dimension); diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorRescaleIntensityImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorRescaleIntensityImageFilter.hxx index d8aa214fcb54004c59e51a61a61da582612f3b4d..a8ddfd64b39c159aa8341f4737f2c40592516609 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorRescaleIntensityImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkVectorRescaleIntensityImageFilter.hxx @@ -38,12 +38,12 @@ namespace itk */ template< typename TInputImage, typename TOutputImage > VectorRescaleIntensityImageFilter< TInputImage, TOutputImage > -::VectorRescaleIntensityImageFilter() +::VectorRescaleIntensityImageFilter() : + m_Scale(1.0), + m_Shift(1.0), + m_InputMaximumMagnitude(NumericTraits< InputRealType >::Zero), + m_OutputMaximumMagnitude(NumericTraits< OutputRealType >::Zero) { - m_OutputMaximumMagnitude = NumericTraits< OutputRealType >::Zero; - m_InputMaximumMagnitude = NumericTraits< InputRealType >::Zero; - - m_Scale = 1.0; } /** @@ -101,7 +101,7 @@ VectorRescaleIntensityImageFilter< TInputImage, TOutputImage > ++it; } - m_InputMaximumMagnitude = vcl_sqrt(maximumSquaredMagnitude); + m_InputMaximumMagnitude = std::sqrt(maximumSquaredMagnitude); m_Scale = static_cast< InputRealType >( m_OutputMaximumMagnitude ) / static_cast< InputRealType >( m_InputMaximumMagnitude ); diff --git a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkWeightedAddImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkWeightedAddImageFilter.h index 2cfc50ade610406435f1d8b17592b4a0ced160ca..660a7b6bb6f2424e7354d4a59f558a53e1f5deda 100644 --- a/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkWeightedAddImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageIntensity/include/itkWeightedAddImageFilter.h @@ -36,7 +36,7 @@ class WeightedAdd2 public: typedef typename NumericTraits< TInput1 >::AccumulateType AccumulatorType; typedef typename NumericTraits< TInput1 >::RealType RealType; - WeightedAdd2() {} + WeightedAdd2() : m_Alpha(0.0), m_Beta(0.0) {} ~WeightedAdd2() {} bool operator!=(const WeightedAdd2 & other) const { diff --git a/Utilities/ITK/Modules/Filtering/ImageLabel/include/itkBinaryContourImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageLabel/include/itkBinaryContourImageFilter.hxx index ca320504912fbf687c181be9fbf2d7f22d2c07b2..da64605d6f335429c18fc6c78c2076202259bbb2 100644 --- a/Utilities/ITK/Modules/Filtering/ImageLabel/include/itkBinaryContourImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageLabel/include/itkBinaryContourImageFilter.hxx @@ -289,7 +289,7 @@ void BinaryContourImageFilter< TInputImage, TOutputImage > ::AfterThreadedGenerateData() { - m_Barrier = NULL; + m_Barrier = ITK_NULLPTR; m_ForegroundLineMap.clear(); m_BackgroundLineMap.clear(); } diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/CMakeLists.txt b/Utilities/ITK/Modules/Filtering/ImageNoise/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..a117184ed7a5c6e3f56dc15d8684700faf29a633 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/CMakeLists.txt @@ -0,0 +1,2 @@ +project(ITKImageNoise) +itk_module_impl() diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkAdditiveGaussianNoiseImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkAdditiveGaussianNoiseImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..ffa1efc0c8b5a00c67881ec63f23757851bc505c --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkAdditiveGaussianNoiseImageFilter.h @@ -0,0 +1,105 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkAdditiveGaussianNoiseImageFilter_h +#define __itkAdditiveGaussianNoiseImageFilter_h + +#include "itkNoiseBaseImageFilter.h" + +namespace itk +{ + +/** \class AdditiveGaussianNoiseImageFilter + * + * \brief Alter an image with additive gaussian white noise. + * + * \author Gaetan Lehmann + * + * This code was contributed in the Insight Journal paper "Noise + * Simulation". http://hdl.handle.net/10380/3158 + * + * \ingroup ITKImageNoise + */ +template <class TInputImage, class TOutputImage=TInputImage> +class AdditiveGaussianNoiseImageFilter : + public NoiseBaseImageFilter<TInputImage,TOutputImage > +{ +public: + /** Standard class typedefs. */ + typedef AdditiveGaussianNoiseImageFilter Self; + typedef NoiseBaseImageFilter< TInputImage,TOutputImage > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(AdditiveGaussianNoiseImageFilter, NoiseBaseImageFilter); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + itkGetConstMacro(Mean, double); + itkSetMacro(Mean, double); + + itkGetConstMacro(StandardDeviation, double); + itkSetMacro(StandardDeviation, double); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputConvertibleToOutputCheck, + (Concept::Convertible<typename TInputImage::PixelType, + typename TOutputImage::PixelType>) ); + /** End concept checking */ +#endif + +protected: + AdditiveGaussianNoiseImageFilter(); + virtual ~AdditiveGaussianNoiseImageFilter() { + } + + void PrintSelf(std::ostream &os, Indent indent) const; + + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId ); + +private: + AdditiveGaussianNoiseImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + double m_Mean; + double m_StandardDeviation; + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkAdditiveGaussianNoiseImageFilter.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkAdditiveGaussianNoiseImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkAdditiveGaussianNoiseImageFilter.hxx new file mode 100644 index 0000000000000000000000000000000000000000..a2dc34ebe7b53fb413db52ed32f39380c4f87b26 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkAdditiveGaussianNoiseImageFilter.hxx @@ -0,0 +1,100 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkAdditiveGaussianNoiseImageFilter_hxx +#define __itkAdditiveGaussianNoiseImageFilter_hxx + +#include "itkAdditiveGaussianNoiseImageFilter.h" +#include "itkImageScanlineIterator.h" +#include "itkProgressReporter.h" +#include "itkNormalVariateGenerator.h" + +namespace itk +{ + +template <class TInputImage, class TOutputImage> +AdditiveGaussianNoiseImageFilter<TInputImage, TOutputImage> +::AdditiveGaussianNoiseImageFilter() +{ + m_Mean = 0.0; + m_StandardDeviation = 1.0; +} + +template <class TInputImage, class TOutputImage> +void +AdditiveGaussianNoiseImageFilter<TInputImage, TOutputImage> +::ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread, + ThreadIdType threadId) +{ + const InputImageType* inputPtr = this->GetInput(); + OutputImageType* outputPtr = this->GetOutput(0); + + // create a random generator per thread + typename Statistics::NormalVariateGenerator::Pointer randn = Statistics::NormalVariateGenerator::New(); + const uint32_t seed = Self::Hash(this->GetSeed(),threadId); + // convert the seed bit for bit to int32 + randn->Initialize(*static_cast<int32_t*>( (void*)&seed) ); + + // Define the portion of the input to walk for this thread, using + // the CallCopyOutputRegionToInputRegion method allows for the input + // and output images to be different dimensions + InputImageRegionType inputRegionForThread; + this->CallCopyOutputRegionToInputRegion(inputRegionForThread, outputRegionForThread); + + // Define the iterators + ImageScanlineConstIterator<TInputImage> inputIt(inputPtr, inputRegionForThread); + ImageScanlineIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels() ); + + inputIt.GoToBegin(); + outputIt.GoToBegin(); + + while ( !inputIt.IsAtEnd() ) + { + while ( !inputIt.IsAtEndOfLine() ) + { + const double out = inputIt.Get() + m_Mean + m_StandardDeviation * randn->GetVariate(); + outputIt.Set( Self::ClampCast(out) ); + ++inputIt; + ++outputIt; + } + inputIt.NextLine(); + outputIt.NextLine(); + progress.CompletedPixel(); // potential exception thrown here + } +} + +template <class TInputImage, class TOutputImage> +void +AdditiveGaussianNoiseImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, + Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Mean: " + << static_cast<typename NumericTraits<double>::PrintType>(m_Mean) + << std::endl; + os << indent << "StandardDeviation: " + << static_cast<typename NumericTraits<double>::PrintType>(m_StandardDeviation) + << std::endl; +} + +} /* namespace itk */ + +#endif // __itkAdditiveGaussianNoiseImageFilter_hxx diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkNoiseBaseImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkNoiseBaseImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..3e18be148fdb7abe321a5f223fdfbfbf4c29f266 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkNoiseBaseImageFilter.h @@ -0,0 +1,91 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkNoiseBaseImageFilter_h +#define __itkNoiseBaseImageFilter_h + +#include "itkInPlaceImageFilter.h" +#include <vcl_ctime.h> + +namespace itk +{ + +/** \class NoiseBaseImageFilter + * + * \brief An Abstract Base class for Noise image filters + * + * This class add common methods for setting a seed for the random + * generators used to generate the noise. + * + * \sa InPlaceImageFilter + * \ingroup ITKImageNoise + */ +template <class TInputImage, class TOutputImage=TInputImage> +class NoiseBaseImageFilter : + public InPlaceImageFilter<TInputImage,TOutputImage > +{ +public: + /** Standard class typedefs. */ + typedef NoiseBaseImageFilter Self; + typedef InPlaceImageFilter<TInputImage,TOutputImage > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Run-time type information (and related methods). */ + itkTypeMacro(NoiseBaseImageFilter, InPlaceImageFilter); + + /** Seed for random initialization */ + itkGetConstMacro(Seed, uint32_t); + itkSetMacro(Seed, uint32_t); + + /** Set the seed to a value initialized with the current time and + * process clock. */ + virtual void SetSeed(); + +protected: + NoiseBaseImageFilter(); + + virtual ~NoiseBaseImageFilter() = 0; + + void PrintSelf(std::ostream &os, Indent indent) const; + + inline static uint32_t Hash(uint32_t a, uint32_t b) + { + // Knuth's Multiplicative Method for hashing + return (a+b)*2654435761u; + } + + // Clamp and round the input value to the output + static OutputImagePixelType ClampCast(const double &value); + +private: + NoiseBaseImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + uint32_t m_Seed; + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkNoiseBaseImageFilter.hxx" +#endif + +#endif // __itkNoiseBaseImageFilter_h diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkNoiseBaseImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkNoiseBaseImageFilter.hxx new file mode 100644 index 0000000000000000000000000000000000000000..0fa632a21ee6be3d3ec3a732313c08090116f914 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkNoiseBaseImageFilter.hxx @@ -0,0 +1,89 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkNoiseBaseImageFilter_hxx +#define __itkNoiseBaseImageFilter_hxx + +#include "itkNoiseBaseImageFilter.h" +#include <ctime> + +namespace itk +{ + +template <class TInputImage, class TOutputImage> +NoiseBaseImageFilter<TInputImage, TOutputImage> +::NoiseBaseImageFilter() + : m_Seed(0) +{ + Self::SetSeed(); + + this->InPlaceOff(); +} + +template <class TInputImage, class TOutputImage> +NoiseBaseImageFilter<TInputImage, TOutputImage> +::~NoiseBaseImageFilter() +{ +} + +template <class TInputImage, class TOutputImage> +void +NoiseBaseImageFilter<TInputImage, TOutputImage> +::SetSeed() +{ + time_t t; + + time(&t); + this->SetSeed(Hash(t,clock() ) ); +} + +template <class TInputImage, class TOutputImage> +typename NoiseBaseImageFilter<TInputImage, TOutputImage>::OutputImagePixelType +NoiseBaseImageFilter<TInputImage, TOutputImage> +::ClampCast(const double &value) +{ + if (value >= (double)NumericTraits<OutputImagePixelType>::max() ) + { + return NumericTraits<OutputImagePixelType>::max(); + } + else if(value <= (double)NumericTraits<OutputImagePixelType>::NonpositiveMin() ) + { + return NumericTraits<OutputImagePixelType>::NonpositiveMin(); + } + else if (NumericTraits<OutputImagePixelType>::is_integer) + { + return Math::Round<OutputImagePixelType>(value); + } + else + { + return static_cast<OutputImagePixelType>(value); + } +} + +template <class TInputImage, class TOutputImage> +void +NoiseBaseImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream &os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Seed: " << static_cast<typename NumericTraits<uint32_t>::PrintType>(m_Seed) << std::endl; +} + +} + +#endif // __itkNoiseBaseImageFilter_hxx diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSaltAndPepperNoiseImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSaltAndPepperNoiseImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..768c4555661be7b5eff54a3ed17ae09352d9d223 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSaltAndPepperNoiseImageFilter.h @@ -0,0 +1,106 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#ifndef __itkSaltAndPepperNoiseImageFilter_h +#define __itkSaltAndPepperNoiseImageFilter_h + +#include "itkNoiseBaseImageFilter.h" + +namespace itk +{ + +/** \class SaltAndPepperNoiseImageFilter + * + * \brief Alter an image with fixed value impulse noise, often called salt and pepper noise. + * + * Pixel alteration occurs at a user defined probability. + * Salt and pepper pixel are equally distributed. + * + * \author Gaetan Lehmann + * + * This code was contributed in the Insight Journal paper "Noise + * Simulation". http://hdl.handle.net/10380/3158 + * + * \ingroup ITKImageNoise + */ +template <class TInputImage, class TOutputImage=TInputImage> +class SaltAndPepperNoiseImageFilter : + public NoiseBaseImageFilter<TInputImage,TOutputImage > +{ +public: + /** Standard class typedefs. */ + typedef SaltAndPepperNoiseImageFilter Self; + typedef NoiseBaseImageFilter< TInputImage,TOutputImage > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(SaltAndPepperNoiseImageFilter, NoiseBaseImageFilter); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + itkGetConstMacro(Probability, double); + itkSetMacro(Probability, double); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputConvertibleToOutputCheck, + (Concept::Convertible<typename TInputImage::PixelType, + typename TOutputImage::PixelType>) ); + /** End concept checking */ +#endif + +protected: + SaltAndPepperNoiseImageFilter(); + virtual ~SaltAndPepperNoiseImageFilter() { + } + + void PrintSelf(std::ostream &os, Indent indent) const; + + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, + ThreadIdType threadId ); + +private: + SaltAndPepperNoiseImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + double m_Probability; + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkSaltAndPepperNoiseImageFilter.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSaltAndPepperNoiseImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSaltAndPepperNoiseImageFilter.hxx new file mode 100644 index 0000000000000000000000000000000000000000..bdbcc4279de0a913b9643d54a162468050fa04a0 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSaltAndPepperNoiseImageFilter.hxx @@ -0,0 +1,111 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkSaltAndPepperNoiseImageFilter_hxx +#define __itkSaltAndPepperNoiseImageFilter_hxx + +#include "itkSaltAndPepperNoiseImageFilter.h" +#include "itkMersenneTwisterRandomVariateGenerator.h" +#include "itkImageScanlineIterator.h" +#include "itkProgressReporter.h" + +namespace itk +{ + +template <class TInputImage, class TOutputImage> +SaltAndPepperNoiseImageFilter<TInputImage, TOutputImage> +::SaltAndPepperNoiseImageFilter() +{ + m_Probability = 0.01; +} + +template <class TInputImage, class TOutputImage> +void +SaltAndPepperNoiseImageFilter<TInputImage, TOutputImage> +::ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread, ThreadIdType threadId) +{ + const InputImageType* inputPtr = this->GetInput(); + OutputImageType* outputPtr = this->GetOutput(0); + + // create a random generator per thread + typename Statistics::MersenneTwisterRandomVariateGenerator::Pointer rand = + Statistics::MersenneTwisterRandomVariateGenerator::New(); + const uint32_t seed = Self::Hash(this->GetSeed(),threadId); + rand->Initialize(seed); + + // Define the portion of the input to walk for this thread, using + // the CallCopyOutputRegionToInputRegion method allows for the input + // and output images to be different dimensions + InputImageRegionType inputRegionForThread; + this->CallCopyOutputRegionToInputRegion(inputRegionForThread, outputRegionForThread); + + // Define the iterators + ImageScanlineConstIterator<TInputImage> inputIt(inputPtr, inputRegionForThread); + ImageScanlineIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels() ); + + inputIt.GoToBegin(); + outputIt.GoToBegin(); + + while ( !inputIt.IsAtEnd() ) + { + while ( !inputIt.IsAtEndOfLine() ) + { + if( rand->GetVariate() < m_Probability ) + { + if( rand->GetVariate() < 0.5 ) + { + // salt + outputIt.Set( NumericTraits<OutputImagePixelType>::max() ); + } + else + { + // pepper + outputIt.Set( NumericTraits<OutputImagePixelType>::NonpositiveMin() ); + } + } + else + { + // keep the data unchanged + outputIt.Set( (OutputImagePixelType) inputIt.Get() ); + } + ++inputIt; + ++outputIt; + } + inputIt.NextLine(); + outputIt.NextLine(); + progress.CompletedPixel(); // potential exception thrown here + } +} + +template <class TInputImage, class TOutputImage> +void +SaltAndPepperNoiseImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, + Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Probability: " + << static_cast<typename NumericTraits<double>::PrintType>(this->GetProbability() ) + << std::endl; +} + +} /* namespace itk */ + +#endif // __itkSaltAndPepperNoiseImageFilter_hxx diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkShotNoiseImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkShotNoiseImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..2b8ae39137402cbf2392b0fa581b69d0c34f744c --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkShotNoiseImageFilter.h @@ -0,0 +1,109 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkShotNoiseImageFilter_h +#define __itkShotNoiseImageFilter_h + +#include "itkNoiseBaseImageFilter.h" + +namespace itk +{ + +/** \class ShotNoiseImageFilter + * + * \brief Alter an image with shot noise. + * + * The shot noise follows a Poisson distribution. + * + * \author Gaetan Lehmann + * + * This code was contributed in the Insight Journal paper "Noise + * Simulation". http://hdl.handle.net/10380/3158 + * + * \ingroup ITKImageNoise + */ +template <class TInputImage, class TOutputImage=TInputImage> +class ShotNoiseImageFilter : + public NoiseBaseImageFilter<TInputImage,TOutputImage > +{ +public: + /** Standard class typedefs. */ + typedef ShotNoiseImageFilter Self; + typedef NoiseBaseImageFilter< TInputImage,TOutputImage > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(ShotNoiseImageFilter, NoiseBaseImageFilter); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + /** \brief a value to map the pixel value to the actual number of photon. + * + * This value defaults to 1.0. The scaling can be seen as the + * inverse of the gain used during the acquisition. The noisy signal + * is then scaled back to its input intensity range. + */ + itkGetConstMacro(Scale, double); + itkSetMacro(Scale, double); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputConvertibleToOutputCheck, + (Concept::Convertible<typename TInputImage::PixelType, + typename TOutputImage::PixelType>) ); + /** End concept checking */ +#endif + +protected: + ShotNoiseImageFilter(); + virtual ~ShotNoiseImageFilter() { + } + + void PrintSelf(std::ostream &os, Indent indent) const; + + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId ); + +private: + ShotNoiseImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + double m_Scale; + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkShotNoiseImageFilter.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkShotNoiseImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkShotNoiseImageFilter.hxx new file mode 100644 index 0000000000000000000000000000000000000000..908c1d784277986bec254acc1aa0a9db30c5f71f --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkShotNoiseImageFilter.hxx @@ -0,0 +1,123 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkShotNoiseImageFilter_hxx +#define __itkShotNoiseImageFilter_hxx + +#include "itkShotNoiseImageFilter.h" +#include "itkMersenneTwisterRandomVariateGenerator.h" +#include "itkImageScanlineIterator.h" +#include "itkProgressReporter.h" +#include "itkNormalVariateGenerator.h" + +namespace itk +{ + +template <class TInputImage, class TOutputImage> +ShotNoiseImageFilter<TInputImage, TOutputImage> +::ShotNoiseImageFilter() + : m_Scale(1.0) +{ +} + +template <class TInputImage, class TOutputImage> +void +ShotNoiseImageFilter<TInputImage, TOutputImage> +::ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread, ThreadIdType threadId) +{ + const InputImageType* inputPtr = this->GetInput(); + OutputImageType* outputPtr = this->GetOutput(0); + + // create a random generator per thread + typename Statistics::MersenneTwisterRandomVariateGenerator::Pointer rand = + Statistics::MersenneTwisterRandomVariateGenerator::New(); + const uint32_t seed = Self::Hash(this->GetSeed(),threadId); + rand->Initialize(seed); + typename Statistics::NormalVariateGenerator::Pointer randn = Statistics::NormalVariateGenerator::New(); + randn->Initialize(*static_cast<int32_t*>( (void*)&seed) ); + + // Define the portion of the input to walk for this thread, using + // the CallCopyOutputRegionToInputRegion method allows for the input + // and output images to be different dimensions + InputImageRegionType inputRegionForThread; + this->CallCopyOutputRegionToInputRegion(inputRegionForThread, outputRegionForThread); + + // Define the iterators + ImageScanlineConstIterator<TInputImage> inputIt(inputPtr, inputRegionForThread); + ImageScanlineIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels() ); + + inputIt.GoToBegin(); + outputIt.GoToBegin(); + + while ( !inputIt.IsAtEnd() ) + { + while ( !inputIt.IsAtEndOfLine() ) + { + const double in = m_Scale * inputIt.Get(); + + // The value of >=50, is the lambda value in a Poisson + // distribution where a Gaussian distribution make a "good" + // approximation of the Poisson. This could be considered to be + // exposed as an advance parameter in the future. + if( in < 50 ) + { + const double L = std::exp( -in ); + long k = 0; + double p = 1.0; + + do + { + k += 1; + p *= rand->GetVariate(); + } + while( p > L ); + + // clip the output to the actual supported range + outputIt.Set( Self::ClampCast( (k-1)/m_Scale ) ); + } + else + { + const double out = in + std::sqrt( in ) * randn->GetVariate(); + outputIt.Set( Self::ClampCast( out/m_Scale ) ); + } + ++inputIt; + ++outputIt; + } + inputIt.NextLine(); + outputIt.NextLine(); + progress.CompletedPixel(); // potential exception thrown here + } +} + +template <class TInputImage, class TOutputImage> +void +ShotNoiseImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, + Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Scale: " + << static_cast<typename NumericTraits<double>::PrintType>(this->GetScale() ) + << std::endl; +} + +} /* namespace itk */ + +#endif // __itkShotNoiseImageFilter_hxx diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSpeckleNoiseImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSpeckleNoiseImageFilter.h new file mode 100644 index 0000000000000000000000000000000000000000..22d8f5af5ccd0ced8937cb06a72a782277a1ba19 --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSpeckleNoiseImageFilter.h @@ -0,0 +1,105 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#ifndef __itkSpeckleNoiseImageFilter_h +#define __itkSpeckleNoiseImageFilter_h + +#include "itkNoiseBaseImageFilter.h" + +namespace itk +{ + +/** \class SpeckleNoiseImageFilter + * + * \brief Alter an image with speckle (multiplicative) noise. + * + * The speckle noise follows a Gamma distribution of mean 1 and standard deviation + * provided by the user. The noise is proportional to the pixel intensity. + * + * \author Gaetan Lehmann + * + * This code was contributed in the Insight Journal paper "Noise + * Simulation". http://hdl.handle.net/10380/3158 + * + * \ingroup ITKImageNoise + */ +template <class TInputImage, class TOutputImage=TInputImage> +class SpeckleNoiseImageFilter : + public NoiseBaseImageFilter<TInputImage,TOutputImage > +{ +public: + /** Standard class typedefs. */ + typedef SpeckleNoiseImageFilter Self; + typedef NoiseBaseImageFilter< TInputImage,TOutputImage > Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(SpeckleNoiseImageFilter, NoiseBaseImageFilter); + + /** Superclass typedefs. */ + typedef typename Superclass::OutputImageType OutputImageType; + typedef typename Superclass::OutputImagePointer OutputImagePointer; + typedef typename Superclass::OutputImageRegionType OutputImageRegionType; + typedef typename Superclass::OutputImagePixelType OutputImagePixelType; + + /** Some convenient typedefs. */ + typedef TInputImage InputImageType; + typedef typename InputImageType::Pointer InputImagePointer; + typedef typename InputImageType::ConstPointer InputImageConstPointer; + typedef typename InputImageType::RegionType InputImageRegionType; + typedef typename InputImageType::PixelType InputImagePixelType; + + itkGetConstMacro(StandardDeviation, double); + itkSetMacro(StandardDeviation, double); + +#ifdef ITK_USE_CONCEPT_CHECKING + /** Begin concept checking */ + itkConceptMacro(InputConvertibleToOutputCheck, + (Concept::Convertible<typename TInputImage::PixelType, + typename TOutputImage::PixelType>) ); + /** End concept checking */ +#endif + +protected: + SpeckleNoiseImageFilter(); + virtual ~SpeckleNoiseImageFilter() { + } + + void PrintSelf(std::ostream &os, Indent indent) const; + + void ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId ); + +private: + SpeckleNoiseImageFilter(const Self&); //purposely not implemented + void operator=(const Self&); //purposely not implemented + + double m_StandardDeviation; + +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkSpeckleNoiseImageFilter.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSpeckleNoiseImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSpeckleNoiseImageFilter.hxx new file mode 100644 index 0000000000000000000000000000000000000000..5fba05f564a75237ae31aa8c258802387de7903f --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/include/itkSpeckleNoiseImageFilter.hxx @@ -0,0 +1,134 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#ifndef __itkSpeckleNoiseImageFilter_hxx +#define __itkSpeckleNoiseImageFilter_hxx + +#include "itkSpeckleNoiseImageFilter.h" +#include "itkMersenneTwisterRandomVariateGenerator.h" +#include "itkImageScanlineIterator.h" +#include "itkProgressReporter.h" + +namespace itk +{ + +template <class TInputImage, class TOutputImage> +SpeckleNoiseImageFilter<TInputImage, TOutputImage> +::SpeckleNoiseImageFilter() +{ + m_StandardDeviation = 1.0; +} + +template <class TInputImage, class TOutputImage> +void +SpeckleNoiseImageFilter<TInputImage, TOutputImage> +::ThreadedGenerateData( const OutputImageRegionType &outputRegionForThread, ThreadIdType threadId) +{ + const InputImageType* inputPtr = this->GetInput(); + OutputImageType* outputPtr = this->GetOutput(0); + + // create a random generator per thread + typename Statistics::MersenneTwisterRandomVariateGenerator::Pointer rand = + Statistics::MersenneTwisterRandomVariateGenerator::New(); + const uint32_t seed = Self::Hash(this->GetSeed(),threadId); + rand->Initialize(seed); + + // Define the portion of the input to walk for this thread, using + // the CallCopyOutputRegionToInputRegion method allows for the input + // and output images to be different dimensions + InputImageRegionType inputRegionForThread; + this->CallCopyOutputRegionToInputRegion(inputRegionForThread, outputRegionForThread); + + // Define the iterators + ImageScanlineConstIterator<TInputImage> inputIt(inputPtr, inputRegionForThread); + ImageScanlineIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); + + ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels() ); + + inputIt.GoToBegin(); + outputIt.GoToBegin(); + + // choose the value of the gamma distribution so that the mean is 1 and the + // variance depend + // on m_StandardDeviation + const double theta = m_StandardDeviation * m_StandardDeviation; + const double k = 1 / theta; + + const double floork = Math::Floor<double>( k ); + const double delta = k - floork; + const double v0 = Math::e / ( Math::e + delta ); + + while ( !inputIt.IsAtEnd() ) + { + while ( !inputIt.IsAtEndOfLine() ) + { + // first generate the gamma distributed random variable + // ref http://en.wikipedia.org/wiki/Gamma_distribution#Generating_gamma-distributed_random_variables + double xi; + double nu; + do + { + const double v1 = 1.0 - rand->GetVariateWithOpenUpperRange(); // open *lower* range -- (0,1] + const double v2 = 1.0 - rand->GetVariateWithOpenUpperRange(); + const double v3 = 1.0 - rand->GetVariateWithOpenUpperRange(); + if( v1 <= v0 ) + { + xi = std::pow( v2, 1 / delta ); + nu = v3 * std::pow( xi, delta - 1.0 ); + } + else + { + xi = 1.0 - std::log( v2 ); + nu = v3 * std::exp( -xi ); + } + } + while( nu > std::exp( -xi ) * std::pow( xi, delta - 1.0 ) ); + double gamma = xi; + for( int i=0; i<floork; i++ ) + { + gamma -= std::log( 1.0 - rand->GetVariateWithOpenUpperRange() ); + } + gamma *= theta; + // ok, so now apply multiplicative noise + const double out = gamma * inputIt.Get(); + outputIt.Set( Self::ClampCast( out ) ); + ++inputIt; + ++outputIt; + } + inputIt.NextLine(); + outputIt.NextLine(); + progress.CompletedPixel(); // potential exception thrown here + } +} + +template <class TInputImage, class TOutputImage> +void +SpeckleNoiseImageFilter<TInputImage, TOutputImage> +::PrintSelf(std::ostream& os, + Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "StandardDeviation: " + << static_cast<typename NumericTraits<double>::PrintType>(this->GetStandardDeviation() ) + << std::endl; +} + +} /* namespace itk */ + +#endif // __itkSpeckleNoiseImageFilter_hxx diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/itk-module.cmake b/Utilities/ITK/Modules/Filtering/ImageNoise/itk-module.cmake new file mode 100644 index 0000000000000000000000000000000000000000..45cce6c3c6e96b911e905f648e404dba109a198d --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/itk-module.cmake @@ -0,0 +1,13 @@ +set(DOCUMENTATION "This module con stains classes to simulate and +evaluate noise. The classes were originally contributed via the +Insight Journal (http://hdl.handle.net/10380/3158).") + +itk_module(ITKImageNoise + DEPENDS + ITKImageFilterBase + ITKStatistics + TEST_DEPENDS + ITKTestKernel + DESCRIPTION + "${DOCUMENTATION}" +) diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkAdditiveGaussianNoiseImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkAdditiveGaussianNoiseImageFilter.wrap new file mode 100644 index 0000000000000000000000000000000000000000..dbe51d5c38d0cde19d572e41bef2b01bdd56eb7c --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkAdditiveGaussianNoiseImageFilter.wrap @@ -0,0 +1,3 @@ +wrap_class("itk::AdditiveGaussianNoiseImageFilter" POINTER) + wrap_image_filter_scalar(2) +end_wrap_class() diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkPeakSignalToNoiseRatioCalculator.wrap b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkPeakSignalToNoiseRatioCalculator.wrap new file mode 100644 index 0000000000000000000000000000000000000000..dd9895fad61177851733c5c9d000016c6ef15d6a --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkPeakSignalToNoiseRatioCalculator.wrap @@ -0,0 +1,3 @@ +wrap_class("itk::PeakSignalToNoiseRatioCalculator" POINTER) + wrap_image_filter_scalar(1) +end_wrap_class() diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkSaltAndPepperNoiseImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkSaltAndPepperNoiseImageFilter.wrap new file mode 100644 index 0000000000000000000000000000000000000000..36d1242fa2a62d71aa651fbabf742ba861840daf --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkSaltAndPepperNoiseImageFilter.wrap @@ -0,0 +1,3 @@ +wrap_class("itk::SaltAndPepperNoiseImageFilter" POINTER) + wrap_image_filter_scalar(2) +end_wrap_class() diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkShotNoiseImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkShotNoiseImageFilter.wrap new file mode 100644 index 0000000000000000000000000000000000000000..bfca9b04626bd6a98b003c1cc513e68af61f9e3d --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkShotNoiseImageFilter.wrap @@ -0,0 +1,3 @@ +wrap_class("itk::ShotNoiseImageFilter" POINTER) + wrap_image_filter_scalar(2) +end_wrap_class() diff --git a/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkSpeckleNoiseImageFilter.wrap b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkSpeckleNoiseImageFilter.wrap new file mode 100644 index 0000000000000000000000000000000000000000..f9f307452016629801e99743ac5cee301c70ed9f --- /dev/null +++ b/Utilities/ITK/Modules/Filtering/ImageNoise/wrapping/itkSpeckleNoiseImageFilter.wrap @@ -0,0 +1,3 @@ +wrap_class("itk::SpeckleNoiseImageFilter" POINTER) + wrap_image_filter_scalar(2) +end_wrap_class() diff --git a/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaborImageSource.hxx b/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaborImageSource.hxx index ad51622d574e717e7ae521f448c90fd1263ac864..eb52d0c596edc560998168437064da97e5c51565 100644 --- a/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaborImageSource.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaborImageSource.hxx @@ -80,7 +80,7 @@ GaborImageSource< TOutputImage > { sum += vnl_math_sqr( ( evalPoint[i] - this->m_Mean[i] ) / this->m_Sigma[i] ); } - double value = vcl_exp(-0.5 * sum) * gabor->Evaluate(evalPoint[0] - this->m_Mean[0]); + double value = std::exp(-0.5 * sum) * gabor->Evaluate(evalPoint[0] - this->m_Mean[0]); // Set the pixel value to the function value outIt.Set( static_cast< PixelType >( value ) ); diff --git a/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaborKernelFunction.h b/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaborKernelFunction.h index 5f9f5116a5b2a50ea34f0bf684778020549bdb36..0d0c31f4c52f9226b369c893b330ee0a51e40cbd 100644 --- a/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaborKernelFunction.h +++ b/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaborKernelFunction.h @@ -65,17 +65,17 @@ public: inline TRealValueType Evaluate(const TRealValueType & u) const { TRealValueType parameter = vnl_math_sqr(u / this->m_Sigma); - TRealValueType envelope = vcl_exp(static_cast< TRealValueType >(-0.5) * parameter); + TRealValueType envelope = std::exp(static_cast< TRealValueType >(-0.5) * parameter); TRealValueType phase = static_cast< TRealValueType >(2.0 * vnl_math::pi) * this->m_Frequency * u + this->m_PhaseOffset; if ( this->m_CalculateImaginaryPart ) { - return envelope * vcl_sin(phase); + return envelope * std::sin(phase); } else { - return envelope * vcl_cos(phase); + return envelope * std::cos(phase); } } diff --git a/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaussianImageSource.hxx b/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaussianImageSource.hxx index e75682c74be97e0d45d6c45ac78bf22326a51962..25546a7fde9f4516f6eb205d0bf24d21bd3f2ca1 100644 --- a/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaussianImageSource.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageSources/include/itkGaussianImageSource.hxx @@ -133,7 +133,6 @@ GaussianImageSource< TOutputImage > // Create and initialize a new gaussian function typedef itk::GaussianSpatialFunction< double, NDimensions > FunctionType; - typedef typename FunctionType::InputType FunctionPositionType; typename FunctionType::Pointer pGaussian = FunctionType::New(); pGaussian->SetSigma(m_Sigma); diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkAdaptiveHistogramEqualizationImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkAdaptiveHistogramEqualizationImageFilter.hxx index d6698b77574df32b0446eff5b4815940f93278c8..61aa3731605003bee363da1e11f29540159f1869 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkAdaptiveHistogramEqualizationImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkAdaptiveHistogramEqualizationImageFilter.hxx @@ -42,7 +42,7 @@ AdaptiveHistogramEqualizationImageFilter< TImageType > s = vnl_math_sgn(u - v); ad = vnl_math_abs( 2.0 * ( u - v ) ); - return 0.5 *s *vcl_pow(ad, m_Alpha) - m_Beta * 0.5 * s * ad + m_Beta * u; + return 0.5 *s *std::pow(ad, m_Alpha) - m_Beta * 0.5 * s * ad + m_Beta * u; } template< typename TImageType > diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkHistogramAlgorithmBase.h b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkHistogramAlgorithmBase.h index da7630a1139b356c7090ec445a384b2a93afcb2e..245baa8da7705670b9ee2f9e6368f1768c1c5854 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkHistogramAlgorithmBase.h +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkHistogramAlgorithmBase.h @@ -78,7 +78,7 @@ public: protected: HistogramAlgorithmBase(); virtual ~HistogramAlgorithmBase() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; virtual void Compute() = 0; diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkHistogramAlgorithmBase.hxx b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkHistogramAlgorithmBase.hxx index 8de6140e7d487a526b87e28c42619d1b7533efa7..26bf6dc28a74faaee1990c00934852ce63071486 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkHistogramAlgorithmBase.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkHistogramAlgorithmBase.hxx @@ -26,7 +26,7 @@ template< typename TInputHistogram > HistogramAlgorithmBase< TInputHistogram > ::HistogramAlgorithmBase() { - m_InputHistogram = 0; + m_InputHistogram = ITK_NULLPTR; } template< typename TInputHistogram > @@ -36,15 +36,8 @@ HistogramAlgorithmBase< TInputHistogram > { Superclass::PrintSelf(os, indent); - os << indent << "Input Histogram: "; - if ( m_InputHistogram.IsNotNull() ) - { - os << m_InputHistogram << std::endl; - } - else - { - os << "not set." << std::endl; - } + itkPrintSelfObjectMacro(InputHistogram); + } } // end of namespace itk diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImageMomentsCalculator.h b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImageMomentsCalculator.h index eb486c1dad7ccd317d46eb5231c6939527874932..2a08fe5ff924a2a4736edf33eb76c5f7080e1fa8 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImageMomentsCalculator.h +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImageMomentsCalculator.h @@ -202,7 +202,7 @@ public: protected: ImageMomentsCalculator(); virtual ~ImageMomentsCalculator(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: ImageMomentsCalculator(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImageMomentsCalculator.hxx b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImageMomentsCalculator.hxx index 89b19fb75583e709bb1a2368f4a8a2548305fe79..962c15224074243b74e6f65db74c8ad102e15437 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImageMomentsCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImageMomentsCalculator.hxx @@ -53,8 +53,8 @@ template< typename TImage > ImageMomentsCalculator< TImage >::ImageMomentsCalculator(void) { m_Valid = false; - m_Image = NULL; - m_SpatialObjectMask = NULL; + m_Image = ITK_NULLPTR; + m_SpatialObjectMask = ITK_NULLPTR; m_M0 = NumericTraits< ScalarType >::Zero; m_M1.Fill(NumericTraits< typename VectorType::ValueType >::Zero); m_M2.Fill(NumericTraits< typename MatrixType::ValueType >::Zero); @@ -183,7 +183,7 @@ ImageMomentsCalculator< TImage >::Compute() vnl_diag_matrix< double > pm = eigen.D; for ( unsigned int i = 0; i < ImageDimension; i++ ) { - m_Pm[i] = pm(i, i) * m_M0; + m_Pm[i] = pm(i) * m_M0; } m_Pa = eigen.V.transpose(); @@ -195,7 +195,7 @@ ImageMomentsCalculator< TImage >::Compute() for ( unsigned int i = 0; i < ImageDimension; i++ ) { - det *= eigenval(i, i); + det *= eigenval(i); } for ( unsigned int i = 0; i < ImageDimension; i++ ) diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImagePCADecompositionCalculator.h b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImagePCADecompositionCalculator.h index 9d3aae03a4fb54a5fa35af228e3b7a9b2e60a096..678c1faef8b84967f85409c97d0d38cd7e979f5a 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImagePCADecompositionCalculator.h +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImagePCADecompositionCalculator.h @@ -129,7 +129,7 @@ public: protected: ImagePCADecompositionCalculator(); virtual ~ImagePCADecompositionCalculator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void CalculateBasisMatrix(void); diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImagePCADecompositionCalculator.hxx b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImagePCADecompositionCalculator.hxx index 5ee1885a8253d2959201470b208249e94f92eeca..ce442da1d739c25d4dde51c1d4d708d97469756b 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImagePCADecompositionCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkImagePCADecompositionCalculator.hxx @@ -30,8 +30,8 @@ template< typename TInputImage, typename TBasisImage > ImagePCADecompositionCalculator< TInputImage, TBasisImage > ::ImagePCADecompositionCalculator() { - m_Image = NULL; - m_MeanImage = NULL; + m_Image = ITK_NULLPTR; + m_MeanImage = ITK_NULLPTR; m_BasisMatrixCalculated = false; m_NumPixels = 0; } diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelOverlapMeasuresImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelOverlapMeasuresImageFilter.h index 443f0fae30c2510dbf492cfb8efdb986d4a788dc..f36663f74b73cc58db64bdabcfb356e96b9a1c42 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelOverlapMeasuresImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelOverlapMeasuresImageFilter.h @@ -196,9 +196,6 @@ protected: /** Multi-thread version GenerateData. */ void ThreadedGenerateData( const RegionType&, ThreadIdType ); - // Override since the filter needs all the data for the algorithm - void GenerateInputRequestedRegion(); - // Override since the filter produces all of its output void EnlargeOutputRequestedRegion( DataObject *data ); diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelOverlapMeasuresImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelOverlapMeasuresImageFilter.hxx index b62ceb9f8ba1651879c70cc445f2b1868e88a897..30cd66e5f87c9d536c82dcda7a689a3a7a129005 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelOverlapMeasuresImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelOverlapMeasuresImageFilter.hxx @@ -33,26 +33,6 @@ LabelOverlapMeasuresImageFilter<TLabelImage> this->SetNumberOfRequiredInputs( 2 ); } -template<typename TLabelImage> -void -LabelOverlapMeasuresImageFilter<TLabelImage> -::GenerateInputRequestedRegion() -{ - Superclass::GenerateInputRequestedRegion(); - if( this->GetSourceImage() ) - { - LabelImagePointer source = const_cast - <LabelImageType *>( this->GetSourceImage() ); - source->SetRequestedRegionToLargestPossibleRegion(); - } - if( this->GetTargetImage() ) - { - LabelImagePointer target = const_cast - <LabelImageType *>( this->GetTargetImage() ); - target->SetRequestedRegionToLargestPossibleRegion(); - } -} - template<typename TLabelImage> void LabelOverlapMeasuresImageFilter<TLabelImage> diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelStatisticsImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelStatisticsImageFilter.h index d0e72d4a4db8e868f2cb8e0bb612820eb1ab5e17..b57447ae3a4a79484c3f7da8c90362f77e8a27b0 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelStatisticsImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelStatisticsImageFilter.h @@ -140,7 +140,7 @@ public: m_BoundingBox[i] = NumericTraits< IndexValueType >::max(); m_BoundingBox[i + 1] = NumericTraits< IndexValueType >::NonpositiveMin(); } - m_Histogram = 0; + m_Histogram = ITK_NULLPTR; } // constructor with histogram enabled @@ -346,9 +346,6 @@ protected: outputRegionForThread, ThreadIdType threadId); - // Override since the filter needs all the data for the algorithm - void GenerateInputRequestedRegion(); - // Override since the filter produces all of its output void EnlargeOutputRequestedRegion(DataObject *data); diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelStatisticsImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelStatisticsImageFilter.hxx index 4e21957f06ad883668ac86992224d8a9ff1618a1..3122835276ceea0bbf676480dd553df96ccf9849 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelStatisticsImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkLabelStatisticsImageFilter.hxx @@ -19,8 +19,8 @@ #define __itkLabelStatisticsImageFilter_hxx #include "itkLabelStatisticsImageFilter.h" -#include "itkImageRegionIterator.h" -#include "itkImageRegionConstIteratorWithIndex.h" +#include "itkImageLinearConstIteratorWithIndex.h" +#include "itkImageScanlineConstIterator.h" #include "itkProgressReporter.h" namespace itk @@ -38,29 +38,6 @@ LabelStatisticsImageFilter< TInputImage, TLabelImage > m_ValidLabelValues.clear(); } -template< typename TInputImage, typename TLabelImage > -void -LabelStatisticsImageFilter< TInputImage, TLabelImage > -::GenerateInputRequestedRegion() -{ - Superclass::GenerateInputRequestedRegion(); - if ( this->GetInput() ) - { - InputImagePointer image = - const_cast< typename Superclass::InputImageType * >( this->GetInput() ); - if ( image ) - { - image->SetRequestedRegionToLargestPossibleRegion(); - } - } - if ( this->GetLabelInput() ) - { - LabelImagePointer label = - const_cast< TLabelImage * >( this->GetLabelInput() ); - label->SetRequestedRegionToLargestPossibleRegion(); - } -} - template< typename TInputImage, typename TLabelImage > void LabelStatisticsImageFilter< TInputImage, TLabelImage > @@ -153,31 +130,34 @@ LabelStatisticsImageFilter< TInputImage, TLabelImage > } } + + typename MapType::mapped_type &labelStats = ( *mapIt ).second; + // accumulate the information from this thread - ( *mapIt ).second.m_Count += ( *threadIt ).second.m_Count; - ( *mapIt ).second.m_Sum += ( *threadIt ).second.m_Sum; - ( *mapIt ).second.m_SumOfSquares += ( *threadIt ).second.m_SumOfSquares; + labelStats.m_Count += ( *threadIt ).second.m_Count; + labelStats.m_Sum += ( *threadIt ).second.m_Sum; + labelStats.m_SumOfSquares += ( *threadIt ).second.m_SumOfSquares; - if ( ( *mapIt ).second.m_Minimum > ( *threadIt ).second.m_Minimum ) + if ( labelStats.m_Minimum > ( *threadIt ).second.m_Minimum ) { - ( *mapIt ).second.m_Minimum = ( *threadIt ).second.m_Minimum; + labelStats.m_Minimum = ( *threadIt ).second.m_Minimum; } - if ( ( *mapIt ).second.m_Maximum < ( *threadIt ).second.m_Maximum ) + if ( labelStats.m_Maximum < ( *threadIt ).second.m_Maximum ) { - ( *mapIt ).second.m_Maximum = ( *threadIt ).second.m_Maximum; + labelStats.m_Maximum = ( *threadIt ).second.m_Maximum; } //bounding box is min,max pairs - int dimension = ( *mapIt ).second.m_BoundingBox.size() / 2; + int dimension = labelStats.m_BoundingBox.size() / 2; for ( int ii = 0; ii < ( dimension * 2 ); ii += 2 ) { - if ( ( *mapIt ).second.m_BoundingBox[ii] > ( *threadIt ).second.m_BoundingBox[ii] ) + if ( labelStats.m_BoundingBox[ii] > ( *threadIt ).second.m_BoundingBox[ii] ) { - ( *mapIt ).second.m_BoundingBox[ii] = ( *threadIt ).second.m_BoundingBox[ii]; + labelStats.m_BoundingBox[ii] = ( *threadIt ).second.m_BoundingBox[ii]; } - if ( ( *mapIt ).second.m_BoundingBox[ii + 1] < ( *threadIt ).second.m_BoundingBox[ii + 1] ) + if ( labelStats.m_BoundingBox[ii + 1] < ( *threadIt ).second.m_BoundingBox[ii + 1] ) { - ( *mapIt ).second.m_BoundingBox[ii + 1] = ( *threadIt ).second.m_BoundingBox[ii + 1]; + labelStats.m_BoundingBox[ii + 1] = ( *threadIt ).second.m_BoundingBox[ii + 1]; } } @@ -189,7 +169,7 @@ LabelStatisticsImageFilter< TInputImage, TLabelImage > for ( unsigned int bin = 0; bin < m_NumBins[0]; bin++ ) { index[0] = bin; - ( *mapIt ).second.m_Histogram->IncreaseFrequency( bin, ( *threadIt ).second.m_Histogram->GetFrequency(bin) ); + labelStats.m_Histogram->IncreaseFrequency( bin, ( *threadIt ).second.m_Histogram->GetFrequency(bin) ); } } } // end of thread map iterator loop @@ -200,12 +180,14 @@ LabelStatisticsImageFilter< TInputImage, TLabelImage > mapIt != m_LabelStatistics.end(); ++mapIt ) { + typename MapType::mapped_type &labelStats = ( *mapIt ).second; + // mean - ( *mapIt ).second.m_Mean = ( *mapIt ).second.m_Sum - / static_cast< RealType >( ( *mapIt ).second.m_Count ); + labelStats.m_Mean = labelStats.m_Sum + / static_cast< RealType >( labelStats.m_Count ); // variance - if ( ( *mapIt ).second.m_Count > 1 ) + if ( labelStats.m_Count > 1 ) { // unbiased estimate of variance LabelStatistics & ls = mapIt->second; @@ -216,11 +198,11 @@ LabelStatisticsImageFilter< TInputImage, TLabelImage > } else { - ( *mapIt ).second.m_Variance = NumericTraits< RealType >::Zero; + labelStats.m_Variance = NumericTraits< RealType >::Zero; } // sigma - ( *mapIt ).second.m_Sigma = vcl_sqrt( ( *mapIt ).second.m_Variance ); + labelStats.m_Sigma = std::sqrt( labelStats.m_Variance ); } { @@ -242,85 +224,103 @@ LabelStatisticsImageFilter< TInputImage, TLabelImage > ::ThreadedGenerateData(const RegionType & outputRegionForThread, ThreadIdType threadId) { - RealType value; - LabelPixelType label; - ImageRegionConstIteratorWithIndex< TInputImage > it (this->GetInput(), + typename HistogramType::IndexType histogramIndex(1); + typename HistogramType::MeasurementVectorType histogramMeasurement(1); + + const SizeValueType size0 = outputRegionForThread.GetSize(0); + if( size0 == 0) + { + return; + } + + ImageLinearConstIteratorWithIndex< TInputImage > it (this->GetInput(), outputRegionForThread); - ImageRegionConstIterator< TLabelImage > labelIt (this->GetLabelInput(), - outputRegionForThread); + + ImageScanlineConstIterator< TLabelImage > labelIt (this->GetLabelInput(), + outputRegionForThread); + MapIterator mapIt; // support progress methods/callbacks - ProgressReporter progress( this, threadId, - outputRegionForThread.GetNumberOfPixels() ); + const size_t numberOfLinesToProcess = outputRegionForThread.GetNumberOfPixels() / size0; + ProgressReporter progress( this, threadId, numberOfLinesToProcess ); // do the work while ( !it.IsAtEnd() ) { - value = static_cast< RealType >( it.Get() ); - label = labelIt.Get(); - - // is the label already in this thread? - mapIt = m_LabelStatisticsPerThread[threadId].find(label); - if ( mapIt == m_LabelStatisticsPerThread[threadId].end() ) + while ( !it.IsAtEndOfLine() ) { - // create a new statistics object - typedef typename MapType::value_type MapValueType; - if ( m_UseHistograms ) + const RealType & value = static_cast< RealType >( it.Get() ); + + const LabelPixelType & label = labelIt.Get(); + + // is the label already in this thread? + mapIt = m_LabelStatisticsPerThread[threadId].find(label); + if ( mapIt == m_LabelStatisticsPerThread[threadId].end() ) + { + // create a new statistics object + typedef typename MapType::value_type MapValueType; + if ( m_UseHistograms ) + { + mapIt = m_LabelStatisticsPerThread[threadId].insert( MapValueType( label, + LabelStatistics(m_NumBins[0], m_LowerBound, + m_UpperBound) ) ).first; + } + else + { + mapIt = m_LabelStatisticsPerThread[threadId].insert( MapValueType( label, + LabelStatistics() ) ).first; + } + } + + typename MapType::mapped_type &labelStats = ( *mapIt ).second; + + // update the values for this label and this thread + if ( value < labelStats.m_Minimum ) { - mapIt = m_LabelStatisticsPerThread[threadId].insert( MapValueType( label, - LabelStatistics(m_NumBins[0], m_LowerBound, - m_UpperBound) ) ).first; + labelStats.m_Minimum = value; } - else + if ( value > labelStats.m_Maximum ) { - mapIt = m_LabelStatisticsPerThread[threadId].insert( MapValueType( label, - LabelStatistics() ) ).first; + labelStats.m_Maximum = value; } - } - - // update the values for this label and this thread - if ( value < ( *mapIt ).second.m_Minimum ) - { - ( *mapIt ).second.m_Minimum = value; - } - if ( value > ( *mapIt ).second.m_Maximum ) - { - ( *mapIt ).second.m_Maximum = value; - } - // bounding box is min,max pairs - for ( unsigned int i = 0; i < ( 2 * it.GetImageDimension() ); i += 2 ) - { - typename ImageRegionConstIteratorWithIndex< TInputImage >::IndexType index = it.GetIndex(); - if ( ( *mapIt ).second.m_BoundingBox[i] > index[i / 2] ) + // bounding box is min,max pairs + for ( unsigned int i = 0; i < ( 2 * TInputImage::ImageDimension ); i += 2 ) { - ( *mapIt ).second.m_BoundingBox[i] = index[i / 2]; + const IndexType & index = it.GetIndex(); + if ( labelStats.m_BoundingBox[i] > index[i / 2] ) + { + labelStats.m_BoundingBox[i] = index[i / 2]; + } + if ( labelStats.m_BoundingBox[i + 1] < index[i / 2] ) + { + labelStats.m_BoundingBox[i + 1] = index[i / 2]; + } } - if ( ( *mapIt ).second.m_BoundingBox[i + 1] < index[i / 2] ) + + labelStats.m_Sum += value; + labelStats.m_SumOfSquares += ( value * value ); + labelStats.m_Count++; + + // if enabled, update the histogram for this label + if ( m_UseHistograms ) { - ( *mapIt ).second.m_BoundingBox[i + 1] = index[i / 2]; + histogramMeasurement[0] = value; + labelStats.m_Histogram->GetIndex(histogramMeasurement, histogramIndex); + labelStats.m_Histogram->IncreaseFrequencyOfIndex(histogramIndex, 1); } - } - ( *mapIt ).second.m_Sum += value; - ( *mapIt ).second.m_SumOfSquares += ( value * value ); - ( *mapIt ).second.m_Count++; - // if enabled, update the histogram for this label - if ( m_UseHistograms ) - { - typename HistogramType::MeasurementVectorType meas; - meas.SetSize(1); - meas[0] = value; - ( *mapIt ).second.m_Histogram->IncreaseFrequencyOfMeasurement(meas, 1); + ++labelIt; + ++it; } - - ++it; - ++labelIt; + labelIt.NextLine(); + it.NextLine(); progress.CompletedPixel(); } + } template< typename TInputImage, typename TLabelImage > @@ -563,7 +563,7 @@ LabelStatisticsImageFilter< TInputImage, TLabelImage > if ( mapIt == m_LabelStatistics.end() ) { // label does not exist, return a default value - return 0; + return ITK_NULLPTR; } else { diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkStandardDeviationProjectionImageFilter.h b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkStandardDeviationProjectionImageFilter.h index 768c3dec4a85bb87c6efc3a2a7c3a12abcb17c15..fef3bba82368bd796e0f9c403c2b15b5abe82d97 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkStandardDeviationProjectionImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkStandardDeviationProjectionImageFilter.h @@ -88,7 +88,7 @@ public: { squaredSum += vnl_math_sqr(*it - mean); } - return vcl_sqrt( squaredSum / ( m_Size - 1 ) ); + return std::sqrt( squaredSum / ( m_Size - 1 ) ); } TAccumulate m_Sum; diff --git a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkStatisticsImageFilter.hxx b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkStatisticsImageFilter.hxx index 6b3debb0df7dff9507611e22420ec99df26deb2c..ec918ee7dc80024fb9aa4d4d9c909689d6fe7643 100644 --- a/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkStatisticsImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/ImageStatistics/include/itkStatisticsImageFilter.hxx @@ -287,7 +287,7 @@ StatisticsImageFilter< TInputImage > // unbiased estimate variance = ( sumOfSquares - ( sum * sum / static_cast< RealType >( count ) ) ) / ( static_cast< RealType >( count ) - 1 ); - sigma = vcl_sqrt(variance); + sigma = std::sqrt(variance); // Set the outputs this->GetMinimumOutput()->Set(minimum); diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkAttributeLabelObject.h b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkAttributeLabelObject.h index e5785a3fa1408303ba4af7197f48bebc496a305a..7b47fa66d4426c7567bdfa523b9b1f1c554a95ab 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkAttributeLabelObject.h +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkAttributeLabelObject.h @@ -120,7 +120,7 @@ public: // copy the data of the current type if possible const Self * src = dynamic_cast<const Self *>( lo ); - if( src == NULL ) + if( src == ITK_NULLPTR ) { return; } diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryGrindPeakImageFilter.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryGrindPeakImageFilter.hxx index 0ff79ec0a00f1197bede6029389f65452cddeac6..e7e69e37afdd0a1c4dca2a3951d8570485d201ed 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryGrindPeakImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryGrindPeakImageFilter.hxx @@ -81,7 +81,7 @@ BinaryGrindPeakImageFilter<TInputImage> labelizer->SetOutputBackgroundValue( m_BackgroundValue ); labelizer->SetFullyConnected( m_FullyConnected ); labelizer->SetNumberOfThreads( this->GetNumberOfThreads() ); - progress->RegisterInternalFilter(labelizer, .6f); + progress->RegisterInternalFilter(labelizer, .65f); typedef typename LabelizerType::OutputImageType LabelMapType; typedef typename itk::ShapeOpeningLabelMapFilter< LabelMapType > OpeningType; @@ -99,7 +99,7 @@ BinaryGrindPeakImageFilter<TInputImage> binarizer->SetBackgroundValue( m_BackgroundValue ); binarizer->SetBackgroundImage( this->GetInput() ); binarizer->SetNumberOfThreads( this->GetNumberOfThreads() ); - progress->RegisterInternalFilter(binarizer, .2f); + progress->RegisterInternalFilter(binarizer, .25f); binarizer->GraftOutput( this->GetOutput() ); binarizer->Update(); diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryImageToLabelMapFilter.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryImageToLabelMapFilter.hxx index 244aa8ef99d0f42612e666d6123096e559d0858a..1cd20b82168b4b1ab3f740625ef6c68c90237ae9 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryImageToLabelMapFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryImageToLabelMapFilter.hxx @@ -368,7 +368,7 @@ BinaryImageToLabelMapFilter< TInputImage, TOutputImage > } this->m_NumberOfLabels.clear(); - this->m_Barrier = NULL; + this->m_Barrier = ITK_NULLPTR; m_LineMap.clear(); } diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryShapeKeepNObjectsImageFilter.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryShapeKeepNObjectsImageFilter.hxx index c9baf2d82d81ff7c5da0bf34a5d2a99ad14b612c..2c1990beca0689fcba0569ecff259a3a6f3ce58d 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryShapeKeepNObjectsImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryShapeKeepNObjectsImageFilter.hxx @@ -25,13 +25,14 @@ namespace itk { template< typename TInputImage > BinaryShapeKeepNObjectsImageFilter< TInputImage > -::BinaryShapeKeepNObjectsImageFilter() +::BinaryShapeKeepNObjectsImageFilter() : + m_FullyConnected(false), + m_BackgroundValue(NumericTraits< OutputImagePixelType >::NonpositiveMin()), + m_ForegroundValue(NumericTraits< OutputImagePixelType >::max()), + m_NumberOfObjects(0), + m_ReverseOrdering(false), + m_Attribute(LabelObjectType::NUMBER_OF_PIXELS) { - m_BackgroundValue = NumericTraits< OutputImagePixelType >::NonpositiveMin(); - m_ForegroundValue = NumericTraits< OutputImagePixelType >::max(); - m_FullyConnected = false; - m_ReverseOrdering = false; - m_Attribute = LabelObjectType::NUMBER_OF_PIXELS; } template< typename TInputImage > diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryStatisticsKeepNObjectsImageFilter.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryStatisticsKeepNObjectsImageFilter.hxx index ba2d79ca6c298261c92e4341ad78b8e7c448a43d..cadae9ad27c61fa8c22cc1f6fa45448123122fd9 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryStatisticsKeepNObjectsImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkBinaryStatisticsKeepNObjectsImageFilter.hxx @@ -25,13 +25,14 @@ namespace itk { template< typename TInputImage, typename TFeatureImage > BinaryStatisticsKeepNObjectsImageFilter< TInputImage, TFeatureImage > -::BinaryStatisticsKeepNObjectsImageFilter() +::BinaryStatisticsKeepNObjectsImageFilter() : + m_FullyConnected(false), + m_BackgroundValue(NumericTraits< OutputImagePixelType >::NonpositiveMin()), + m_ForegroundValue(NumericTraits< OutputImagePixelType >::max()), + m_NumberOfObjects(0), + m_ReverseOrdering(false), + m_Attribute(LabelObjectType::MEAN) { - m_BackgroundValue = NumericTraits< OutputImagePixelType >::NonpositiveMin(); - m_ForegroundValue = NumericTraits< OutputImagePixelType >::max(); - m_FullyConnected = false; - m_ReverseOrdering = false; - m_Attribute = LabelObjectType::MEAN; this->SetNumberOfRequiredInputs(2); } diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMap.h b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMap.h index df7d0968e14e804041e6e06f99dfa0b183d731aa..88f407511efa4b1a728d7b36320da3ed8508dfd7 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMap.h +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMap.h @@ -136,7 +136,7 @@ public: virtual void Initialize(); /** */ - virtual void Allocate(); + virtual void Allocate(bool initialize = false) ITK_OVERRIDE; virtual void Graft(const DataObject *data); diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMap.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMap.hxx index 3c079a6ea53f5641cf8cc1db596c0d8017d8482f..c5335098b653b5112fb6a9d5d2da86d66eec77d3 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMap.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMap.hxx @@ -76,7 +76,7 @@ LabelMap< TLabelObject > template< typename TLabelObject > void LabelMap< TLabelObject > -::Allocate() +::Allocate(bool) { this->Initialize(); } @@ -86,37 +86,27 @@ void LabelMap< TLabelObject > ::Graft(const DataObject *data) { + if(data == ITK_NULLPTR) + { + return; // nothing to do + } // call the superclass' implementation Superclass::Graft(data); - if ( data ) - { - // Attempt to cast data to an Image - const Self *imgData; - - try - { - imgData = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - return; - } + // Attempt to cast data to an Image + const Self *imgData = dynamic_cast< const Self * >( data ); - if ( imgData ) - { - // Now copy anything remaining that is needed - m_LabelObjectContainer = imgData->m_LabelObjectContainer; - m_BackgroundValue = imgData->m_BackgroundValue; - } - else - { - // pointer could not be cast back down - itkExceptionMacro( << "itk::Image::Graft() cannot cast " - << typeid( data ).name() << " to " - << typeid( const Self * ).name() ); - } + if ( imgData == ITK_NULLPTR ) + { + // pointer could not be cast back down + itkExceptionMacro( << "itk::Image::Graft() cannot cast " + << typeid( data ).name() << " to " + << typeid( const Self * ).name() ); } + + // Now copy anything remaining that is needed + m_LabelObjectContainer = imgData->m_LabelObjectContainer; + m_BackgroundValue = imgData->m_BackgroundValue; } template< typename TLabelObject > @@ -412,7 +402,7 @@ void LabelMap< TLabelObject > ::AddLabelObject(LabelObjectType *labelObject) { - itkAssertOrThrowMacro( ( labelObject != NULL ), "Input LabelObject can't be Null" ); + itkAssertOrThrowMacro( ( labelObject != ITK_NULLPTR ), "Input LabelObject can't be Null" ); m_LabelObjectContainer[labelObject->GetLabel()] = labelObject; this->Modified(); @@ -423,7 +413,7 @@ void LabelMap< TLabelObject > ::PushLabelObject(LabelObjectType *labelObject) { - itkAssertOrThrowMacro( ( labelObject != NULL ), "Input LabelObject can't be Null" ); + itkAssertOrThrowMacro( ( labelObject != ITK_NULLPTR ), "Input LabelObject can't be Null" ); if ( m_LabelObjectContainer.empty() ) { @@ -488,7 +478,7 @@ void LabelMap< TLabelObject > ::RemoveLabelObject(LabelObjectType *labelObject) { - itkAssertOrThrowMacro( ( labelObject != NULL ), "Input LabelObject can't be Null" ); + itkAssertOrThrowMacro( ( labelObject != ITK_NULLPTR ), "Input LabelObject can't be Null" ); // modified is called in RemoveLabel() this->RemoveLabel( labelObject->GetLabel() ); } diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMapToLabelImageFilter.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMapToLabelImageFilter.hxx index d6457dbd816b70efb3f199b4c410294c8a48a4b4..4653c8d32d087491e40a552ec261166e3be56786 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMapToLabelImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelMapToLabelImageFilter.hxx @@ -30,7 +30,7 @@ template< typename TInputImage, typename TOutputImage > LabelMapToLabelImageFilter< TInputImage, TOutputImage > ::LabelMapToLabelImageFilter() { - m_OutputImage = 0; + m_OutputImage = ITK_NULLPTR; } diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObject.h b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObject.h index a2c4d773450bba3110c47cbfbae272cf1c3677c6..9dd7baccc6adf2727bdb2f4385bdcc984c64165f 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObject.h +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObject.h @@ -362,7 +362,7 @@ public: protected: LabelObject(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: LabelObject(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObject.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObject.hxx index a9277c423a4a4c74a9a869810dabc4497502822b..28d70f736777c4881d4fc8a153300868b924424e 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObject.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObject.hxx @@ -270,7 +270,7 @@ template< typename TLabel, unsigned int VImageDimension > void LabelObject< TLabel, VImageDimension >::CopyAttributesFrom(const Self *src) { - itkAssertOrThrowMacro ( ( src != NULL ), "Null Pointer" ); + itkAssertOrThrowMacro ( ( src != ITK_NULLPTR ), "Null Pointer" ); m_Label = src->m_Label; } @@ -279,7 +279,7 @@ template< typename TLabel, unsigned int VImageDimension > void LabelObject< TLabel, VImageDimension >::CopyAllFrom(const Self *src) { - itkAssertOrThrowMacro ( ( src != NULL ), "Null Pointer" ); + itkAssertOrThrowMacro ( ( src != ITK_NULLPTR ), "Null Pointer" ); m_LineContainer = src->m_LineContainer; // also copy the attributes this->CopyAttributesFrom(src); diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObjectLine.h b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObjectLine.h index e26118f5ee69a5f3ef682d955378f39836a50079..0054f05e9e01bbf01a0b34600167b303b1f5abd9 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObjectLine.h +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObjectLine.h @@ -47,9 +47,9 @@ public: typedef Index< VImageDimension > IndexType; typedef SizeValueType LengthType; - LabelObjectLine() {} - virtual ~LabelObjectLine() {} + LabelObjectLine(); LabelObjectLine(const IndexType & idx, const LengthType & length); + virtual ~LabelObjectLine() {} /** * Set/Get Index diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObjectLine.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObjectLine.hxx index a5988ed525d7dc4fae09d79eeb775b98de38a73e..3522359e205ba3f30cb213acc6db0ead6640019e 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObjectLine.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkLabelObjectLine.hxx @@ -23,12 +23,18 @@ namespace itk { template< unsigned int VImageDimension > -LabelObjectLine< VImageDimension >::LabelObjectLine(const IndexType & idx, const LengthType & length) +LabelObjectLine< VImageDimension >::LabelObjectLine() : + m_Length( NumericTraits< SizeValueType >::Zero ) { - this->SetIndex(idx); - this->SetLength(length); + m_Index.Fill( NumericTraits< IndexValueType >::Zero ); } +template< unsigned int VImageDimension > +LabelObjectLine< VImageDimension >::LabelObjectLine(const IndexType & idx, const LengthType & length) : + m_Index( idx ), + m_Length( length ) +{} + template< unsigned int VImageDimension > void LabelObjectLine< VImageDimension >::SetIndex(const IndexType & idx) { diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkObjectByObjectLabelMapFilter.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkObjectByObjectLabelMapFilter.hxx index d99765bf543c39b27a7e0273214399e771c29ce6..28d32c68e936a72d67b6d57975389419a15ad801 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkObjectByObjectLabelMapFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkObjectByObjectLabelMapFilter.hxx @@ -42,8 +42,8 @@ ObjectByObjectLabelMapFilter<TInputImage, TOutputImage, TInputFilter, TOutputFil m_KeepLabels = true; m_InternalForegroundValue = itk::NumericTraits< InternalOutputPixelType >::max(); - m_InputFilter = NULL; - m_OutputFilter = NULL; + m_InputFilter = ITK_NULLPTR; + m_OutputFilter = ITK_NULLPTR; m_Select = SelectType::New(); @@ -80,7 +80,7 @@ ObjectByObjectLabelMapFilter<TInputImage, TOutputImage, TInputFilter, TOutputFil ::SetFilter( InputFilterType * filter ) { OutputFilterType * outputFilter = dynamic_cast< OutputFilterType * >( filter ); - if( outputFilter == NULL && filter != NULL ) + if( outputFilter == ITK_NULLPTR && filter != ITK_NULLPTR ) { // TODO: can it be replaced by a concept check ? itkExceptionMacro("Wrong output filter type. Use SetOutputFilter() and SetInputFilter() instead of SetFilter() when input and output filter types are different."); diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkShapeLabelMapFilter.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkShapeLabelMapFilter.hxx index 8445a708eee460c0f11aa3482cb9f4dabb72ee45..ef2a5fd7dd791eeedeb1f5c7375f495604c5a6ac 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkShapeLabelMapFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkShapeLabelMapFilter.hxx @@ -299,7 +299,7 @@ ShapeLabelMapFilter< TImage, TLabelImage > vnl_diag_matrix< double > pm = eigen.D; for ( unsigned int i = 0; i < ImageDimension; i++ ) { - principalMoments[i] = pm(i, i); + principalMoments[i] = pm(i); } MatrixType principalAxes = eigen.V.transpose(); @@ -311,7 +311,7 @@ ShapeLabelMapFilter< TImage, TLabelImage > for ( unsigned int i = 0; i < ImageDimension; i++ ) { - det *= eigenval(i, i); + det *= eigenval(i); } for ( unsigned int i = 0; i < ImageDimension; i++ ) @@ -328,8 +328,8 @@ ShapeLabelMapFilter< TImage, TLabelImage > } else if ( principalMoments[0] != 0 ) { - elongation = vcl_sqrt(principalMoments[ImageDimension - 1] / principalMoments[ImageDimension - 2]); - flatness = vcl_sqrt(principalMoments[1] / principalMoments[0]); + elongation = std::sqrt(principalMoments[ImageDimension - 1] / principalMoments[ImageDimension - 2]); + flatness = std::sqrt(principalMoments[1] / principalMoments[0]); } double physicalSize = nbOfPixels * sizePerPixel; @@ -343,12 +343,12 @@ ShapeLabelMapFilter< TImage, TLabelImage > { edet *= principalMoments[i]; } - edet = vcl_pow(edet, 1.0 / ImageDimension); + edet = std::pow(edet, 1.0 / ImageDimension); for ( unsigned int i = 0; i < ImageDimension; i++ ) { if ( edet != 0.0 ) { - ellipsoidDiameter[i] = 2.0 *equivalentRadius *vcl_sqrt(principalMoments[i] / edet); + ellipsoidDiameter[i] = 2.0 *equivalentRadius *std::sqrt(principalMoments[i] / edet); } else { @@ -392,8 +392,6 @@ ShapeLabelMapFilter< TImage, TLabelImage > typedef typename std::deque< IndexType > IndexListType; IndexListType idxList; - typedef typename LabelObjectType::LengthType LengthType; - typedef typename itk::ConstNeighborhoodIterator< LabelImageType > NeighborIteratorType; SizeType neighborHoodRadius; neighborHoodRadius.Fill(1); @@ -443,7 +441,7 @@ ShapeLabelMapFilter< TImage, TLabelImage > for ( unsigned int i = 0; i < ImageDimension; i++ ) { const OffsetValueType indexDifference = ( iIt1->operator[](i) - iIt2->operator[](i) ); - length += vcl_pow(indexDifference * spacing[i], 2); + length += std::pow(indexDifference * spacing[i], 2); } if ( feretDiameter < length ) { @@ -452,7 +450,7 @@ ShapeLabelMapFilter< TImage, TLabelImage > } } // Final computation - feretDiameter = vcl_sqrt(feretDiameter); + feretDiameter = std::sqrt(feretDiameter); // Finally put the values in the label object labelObject->SetFeretDiameter(feretDiameter); @@ -506,7 +504,7 @@ ShapeLabelMapFilter< TImage, TLabelImage > // a data structure to store the number of intercepts on each direction typedef typename std::map<OffsetType, SizeValueType, typename OffsetType::LexicographicCompare> MapInterceptType; MapInterceptType intercepts; - // int nbOfDirections = (int)vcl_pow( 2.0, (int)ImageDimension ) - 1; + // int nbOfDirections = (int)std::pow( 2.0, (int)ImageDimension ) - 1; // intecepts.resize(nbOfDirections + 1); // code begins at position 1 // now iterate over the vectors of lines @@ -693,10 +691,10 @@ ShapeLabelMapFilter< TImage, TLabelImage > double dx = spacing[0]; double dy = spacing[1]; double dz = spacing[2]; - double dxy = vcl_sqrt( spacing[0]*spacing[0] + spacing[1]*spacing[1] ); - double dxz = vcl_sqrt( spacing[0]*spacing[0] + spacing[2]*spacing[2] ); - double dyz = vcl_sqrt( spacing[1]*spacing[1] + spacing[2]*spacing[2] ); - double dxyz = vcl_sqrt( spacing[0]*spacing[0] + spacing[1]*spacing[1] + spacing[2]*spacing[2] ); + double dxy = std::sqrt( spacing[0]*spacing[0] + spacing[1]*spacing[1] ); + double dxz = std::sqrt( spacing[0]*spacing[0] + spacing[2]*spacing[2] ); + double dyz = std::sqrt( spacing[1]*spacing[1] + spacing[2]*spacing[2] ); + double dxyz = std::sqrt( spacing[0]*spacing[0] + spacing[1]*spacing[1] + spacing[2]*spacing[2] ); double vol = spacing[0]*spacing[1]*spacing[2]; // 'magical numbers', corresponding to area of voronoi partition on the @@ -748,7 +746,7 @@ ShapeLabelMapFilter< TImage, TLabelImage > Superclass::AfterThreadedGenerateData(); // Release the label image - m_LabelImage = NULL; + m_LabelImage = ITK_NULLPTR; } template< typename TImage, typename TLabelImage > diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkShapeLabelObject.h b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkShapeLabelObject.h index 732bbd8cdda15f23d73e7797acd8751d76820bc7..2d3b0ec1581c051c2f02572b19bcb968198d4f83 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkShapeLabelObject.h +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkShapeLabelObject.h @@ -521,7 +521,7 @@ public: // copy the data of the current type if possible const Self *src = dynamic_cast< const Self * >( lo ); - if ( src == NULL ) + if ( src == ITK_NULLPTR ) { return; } diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkStatisticsLabelMapFilter.hxx b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkStatisticsLabelMapFilter.hxx index 2182480f3bd121a5c7ba86188c688eecb4bbeaf4..f909bc2038b12cfe8cd69c8b2968d624302fd6db 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkStatisticsLabelMapFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkStatisticsLabelMapFilter.hxx @@ -67,16 +67,15 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > typedef typename LabelObjectType::HistogramType HistogramType; - typename HistogramType::SizeType histogramSize; - histogramSize.SetSize(1); + typename HistogramType::IndexType histogramIndex(1); + typename HistogramType::MeasurementVectorType mv(1); + typename HistogramType::SizeType histogramSize(1); histogramSize.Fill(m_NumberOfBins); - typename HistogramType::MeasurementVectorType featureImageMin; - featureImageMin.SetSize(1); + typename HistogramType::MeasurementVectorType featureImageMin(1); featureImageMin.Fill(m_Minimum); - typename HistogramType::MeasurementVectorType featureImageMax; - featureImageMax.SetSize(1); + typename HistogramType::MeasurementVectorType featureImageMax(1); featureImageMax.Fill(m_Maximum); typename HistogramType::Pointer histogram = HistogramType::New(); @@ -103,8 +102,7 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > VectorType principalMoments; principalMoments.Fill(0); - typename HistogramType::MeasurementVectorType mv; - mv.SetSize(1); + // iterate over all the indexes typename LabelObjectType::ConstIndexIterator it( labelObject ); while( ! it.IsAtEnd() ) @@ -112,7 +110,8 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > const IndexType & idx = it.GetIndex(); const FeatureImagePixelType & v = featureImage->GetPixel(idx); mv[0] = v; - histogram->IncreaseFrequencyOfMeasurement(mv, 1); + histogram->GetIndex(mv, histogramIndex); + histogram->IncreaseFrequencyOfIndex(histogramIndex, 1); // update min and max if ( v <= min ) @@ -128,9 +127,9 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > //increase the sums sum += v; - sum2 += vcl_pow( (double)v, 2 ); - sum3 += vcl_pow( (double)v, 3 ); - sum4 += vcl_pow( (double)v, 4 ); + sum2 += std::pow( (double)v, 2 ); + sum3 += std::pow( (double)v, 3 ); + sum4 += std::pow( (double)v, 4 ); // moments PointType physicalPosition; @@ -152,11 +151,11 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > // final computations const typename HistogramType::AbsoluteFrequencyType & totalFreq = histogram->GetTotalFrequency(); const double mean = sum / totalFreq; - const double variance = ( sum2 - ( vcl_pow(sum, 2) / totalFreq ) ) / ( totalFreq - 1 ); - const double sigma = vcl_sqrt(variance); + const double variance = ( sum2 - ( std::pow(sum, 2) / totalFreq ) ) / ( totalFreq - 1 ); + const double sigma = std::sqrt(variance); const double mean2 = mean * mean; double skewness; - if(vcl_abs(variance * sigma) > itk::NumericTraits<double>::min()) + if(std::abs(variance * sigma) > itk::NumericTraits<double>::min()) { skewness = ( ( sum3 - 3.0 * mean * sum2 ) / totalFreq + 2.0 * mean * mean2 ) / ( variance * sigma ); } @@ -165,7 +164,7 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > skewness = 0.0; } double kurtosis; - if(vcl_abs(variance) > itk::NumericTraits<double>::min()) + if(std::abs(variance) > itk::NumericTraits<double>::min()) { kurtosis = ( ( sum4 - 4.0 * mean * sum3 + 6.0 * mean2 * sum2 ) / totalFreq - 3.0 * mean2 * mean2 ) / @@ -224,8 +223,8 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > vnl_diag_matrix< double > pm = eigen.D; for ( unsigned int i = 0; i < ImageDimension; i++ ) { - // principalMoments[i] = 4 * vcl_sqrt( pm(i,i) ); - principalMoments[i] = pm(i, i); + // principalMoments[i] = 4 * std::sqrt( pm(i,i) ); + principalMoments[i] = pm(i); } principalAxes = eigen.V.transpose(); @@ -237,7 +236,7 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > for ( unsigned int i = 0; i < ImageDimension; i++ ) { - det *= eigenval(i, i); + det *= eigenval(i); } for ( unsigned int i = 0; i < ImageDimension; i++ ) @@ -254,8 +253,8 @@ StatisticsLabelMapFilter< TImage, TFeatureImage > { // elongation = principalMoments[ImageDimension-1] / // principalMoments[0]; - elongation = vcl_sqrt(principalMoments[ImageDimension - 1] / principalMoments[ImageDimension - 2]); - flatness = vcl_sqrt(principalMoments[1] / principalMoments[0]); + elongation = std::sqrt(principalMoments[ImageDimension - 1] / principalMoments[ImageDimension - 2]); + flatness = std::sqrt(principalMoments[1] / principalMoments[0]); } } else diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkStatisticsLabelObject.h b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkStatisticsLabelObject.h index 3cc82e4282ffc634e144fc5eebd269ef2766fe12..60639d8f5535fdf245d27d17cbe57bda7c7f778f 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/include/itkStatisticsLabelObject.h +++ b/Utilities/ITK/Modules/Filtering/LabelMap/include/itkStatisticsLabelObject.h @@ -248,7 +248,7 @@ public: // copy the data of the current type if possible const Self *src = dynamic_cast< const Self * >( lo ); - if ( src == NULL ) + if ( src == ITK_NULLPTR ) { return; } @@ -528,7 +528,7 @@ protected: m_Kurtosis = 0; m_Skewness = 0; m_WeightedElongation = 0; - m_Histogram = NULL; + m_Histogram = ITK_NULLPTR; m_WeightedFlatness = 0; } @@ -553,15 +553,7 @@ protected: // os << indent << "CentralMoments: " << std::endl << m_CentralMoments; os << indent << "WeightedPrincipalMoments: " << m_WeightedPrincipalMoments << std::endl; os << indent << "WeightedPrincipalAxes: " << std::endl << m_WeightedPrincipalAxes; - os << indent << "Histogram: "; - if ( m_Histogram.IsNull() ) - { - os << "NULL" << std::endl; - } - else - { - m_Histogram->Print(os, indent); - } + itkPrintSelfObjectMacro( Histogram ); } private: diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/src/itkGeometryUtilities.cxx b/Utilities/ITK/Modules/Filtering/LabelMap/src/itkGeometryUtilities.cxx index 9f811d9d5730add20d6f8be0376c426cd2c91c48..171fa97cec17644d3bbad818eed383514a4cba9b 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/src/itkGeometryUtilities.cxx +++ b/Utilities/ITK/Modules/Filtering/LabelMap/src/itkGeometryUtilities.cxx @@ -55,7 +55,7 @@ GeometryUtilities } else { - return vcl_sqrt(vnl_math::pi) * DoubleFactorial(n) / vcl_pow(2, ( n + 1 ) / 2.0); + return std::sqrt(vnl_math::pi) * DoubleFactorial(n) / std::pow(2, ( n + 1 ) / 2.0); } } @@ -65,7 +65,7 @@ GeometryUtilities { const double dbldim = static_cast< double >( dim ); - return vcl_pow(vnl_math::pi, dbldim * 0.5) * vcl_pow(radius, dbldim) / GammaN2p1(dim); + return std::pow(vnl_math::pi, dbldim * 0.5) * std::pow(radius, dbldim) / GammaN2p1(dim); } double @@ -79,7 +79,7 @@ double GeometryUtilities ::HyperSphereRadiusFromVolume(const int dim, const double volume) { - return vcl_pow(volume * GammaN2p1(dim) / vcl_pow(vnl_math::pi, dim * 0.5), 1.0 / dim); + return std::pow(volume * GammaN2p1(dim) / std::pow(vnl_math::pi, dim * 0.5), 1.0 / dim); } } // end of itk namespace diff --git a/Utilities/ITK/Modules/Filtering/LabelMap/wrapping/CMakeLists.txt b/Utilities/ITK/Modules/Filtering/LabelMap/wrapping/CMakeLists.txt index 7cedd05c98f6cf2a0fd60fb446d51120bdd07676..e87014f1f23acaa970f53e678dafeaf7fa562ddf 100644 --- a/Utilities/ITK/Modules/Filtering/LabelMap/wrapping/CMakeLists.txt +++ b/Utilities/ITK/Modules/Filtering/LabelMap/wrapping/CMakeLists.txt @@ -10,5 +10,16 @@ set(WRAPPER_LIBRARY_GROUPS itkInPlaceLabelMapFilter itkChangeRegionLabelMapFilter ) + +# Save default includes so they can be reseted afterwards +set(tmp_default_includes ${WRAPPER_DEFAULT_INCLUDE}) + +# Add itkStatisticsLabelObject.h, it is not automatically detected +# (but it maybe should) +set(WRAPPER_DEFAULT_INCLUDE ${WRAPPER_DEFAULT_INCLUDE} "itkStatisticsLabelObject.h") + itk_auto_load_submodules() itk_end_wrap_module() + +# Reset the WRAPPER_DEFAULT_INCLUDE to original value +set(WRAPPER_DEFAULT_INCLUDE ${tmp_default_includes}) diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkClosingByReconstructionImageFilter.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkClosingByReconstructionImageFilter.hxx index c68b46501b528b8d2c6be3dcb434cef7d4818389..8382192fe958c26088fb774bf3d01894584858f9 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkClosingByReconstructionImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkClosingByReconstructionImageFilter.hxx @@ -80,6 +80,8 @@ ClosingByReconstructionImageFilter< TInputImage, TOutputImage, TKernel > dilate->SetInput( this->GetInput() ); dilate->SetKernel(this->m_Kernel); + progress->RegisterInternalFilter(dilate, .5); + // Delegate to a dilate filter. typename ReconstructionByErosionImageFilter< TInputImage, TInputImage >::Pointer erode = ReconstructionByErosionImageFilter< TInputImage, TInputImage >::New(); @@ -90,6 +92,7 @@ ClosingByReconstructionImageFilter< TInputImage, TOutputImage, TKernel > if ( m_PreserveIntensities ) { + progress->RegisterInternalFilter(erode, .25); erode->Update(); typename TInputImage::Pointer tempImage = TInputImage::New(); tempImage->SetRegions ( dilate->GetOutput()->GetBufferedRegion() ); @@ -133,6 +136,7 @@ ClosingByReconstructionImageFilter< TInputImage, TOutputImage, TKernel > } else { + progress->RegisterInternalFilter(erode, .5); erode->GraftOutput( this->GetOutput() ); erode->Update(); this->GraftOutput( erode->GetOutput() ); diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkFlatStructuringElement.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkFlatStructuringElement.hxx index b7a67218099464d89da1c57a3391b3828ceb3137..e8379fe0dd2932d21f66bb2a2058e2d6564699ea 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkFlatStructuringElement.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkFlatStructuringElement.hxx @@ -102,15 +102,15 @@ FlatStructuringElement< VDimension > while ( theta <= M_PI / 2.0 + 0.0001 ) { LType2 O; - O[0] = k1 * vcl_cos(theta); - O[1] = k2 * vcl_sin(theta); + O[0] = k1 * std::cos(theta); + O[1] = k2 * std::sin(theta); if ( !res.CheckParallel(O) ) { //std::cout << O << std::endl; res.AddLine(O); } - O[0] = k1 * vcl_cos(-theta); - O[1] = k2 * vcl_sin(-theta); + O[0] = k1 * std::cos(-theta); + O[1] = k2 * std::sin(-theta); if ( !res.CheckParallel(O) ) { //std::cout << O << std::endl; @@ -123,9 +123,9 @@ FlatStructuringElement< VDimension > res.ComputeBufferFromLines(); } -// O[0] = k1 * vcl_cos(phi) * vcl_cos(theta); -// O[1] = k2 * vcl_cos(phi) * vcl_sin(theta); -// O[2] = k3 * vcl_sin(theta); +// O[0] = k1 * std::cos(phi) * std::cos(theta); +// O[1] = k2 * std::cos(phi) * std::sin(theta); +// O[2] = k3 * std::sin(theta); template< unsigned int VDimension > void @@ -148,7 +148,7 @@ FlatStructuringElement< VDimension > case 12: { // dodecahedron - float phi = ( 1.0 + vcl_sqrt(5.0) ) / 2.0; + float phi = ( 1.0 + std::sqrt(5.0) ) / 2.0; float b = 1.0 / phi; float c = 2.0 - phi; unsigned facets = 12; @@ -317,7 +317,7 @@ FlatStructuringElement< VDimension > case 20: { // Icosahedron - float phi = ( 1.0 + vcl_sqrt(5.0) ) / 2.0; + float phi = ( 1.0 + std::sqrt(5.0) ) / 2.0; float a = 0.5; float b = 1.0 / ( 2.0 * phi ); unsigned facets = 20; @@ -518,8 +518,8 @@ FlatStructuringElement< VDimension > // create triangular facet approximation to a sphere - begin with // unit sphere // total number of facets is 8 * (4^iterations) - unsigned int facets = 8 * (int)vcl_pow( (double)4, iterations ); - float sqrt2 = vcl_sqrt(2.0); + unsigned int facets = 8 * (int)std::pow( (double)4, iterations ); + float sqrt2 = std::sqrt(2.0); // std::cout << facets << " facets" << std::endl; typedef std::vector< FacetType3 > FacetArrayType; FacetArrayType FacetArray; @@ -926,7 +926,7 @@ FlatStructuringElement< VDimension >::CheckParallel(LType NewVec) const LType LL = m_Lines[i]; LL.Normalize(); float L = NN * LL; - if ( ( 1.0 - vcl_fabs(L) ) < 0.000001 ) { return ( true ); } + if ( ( 1.0 - std::fabs(L) ) < 0.000001 ) { return ( true ); } } return ( false ); } diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleDilateImageFilter.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleDilateImageFilter.hxx index 8b26005d2f98da3d6c1bd4cd7b101ab0211a36c7..32d01aad966c0c50161ce6e2bf4070536ee24b03 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleDilateImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleDilateImageFilter.hxx @@ -55,16 +55,9 @@ void GrayscaleDilateImageFilter< TInputImage, TOutputImage, TKernel > ::SetKernel(const KernelType & kernel) { - const FlatKernelType *flatKernel = NULL; + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - } - catch ( ... ) - {} - - if ( flatKernel != NULL && flatKernel->GetDecomposable() ) + if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() ) { m_AnchorFilter->SetKernel(*flatKernel); m_Algorithm = ANCHOR; @@ -119,14 +112,7 @@ void GrayscaleDilateImageFilter< TInputImage, TOutputImage, TKernel > ::SetAlgorithm(int algo) { - const FlatKernelType *flatKernel = NULL; - - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); - } - catch ( ... ) - {} + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); if ( m_Algorithm != algo ) { @@ -138,11 +124,11 @@ GrayscaleDilateImageFilter< TInputImage, TOutputImage, TKernel > { m_HistogramFilter->SetKernel( this->GetKernel() ); } - else if ( flatKernel != NULL && flatKernel->GetDecomposable() && algo == ANCHOR ) + else if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() && algo == ANCHOR ) { m_AnchorFilter->SetKernel(*flatKernel); } - else if ( flatKernel != NULL && flatKernel->GetDecomposable() && algo == VHGW ) + else if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() && algo == VHGW ) { m_VHGWFilter->SetKernel(*flatKernel); } diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleErodeImageFilter.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleErodeImageFilter.hxx index bddc5fc81c6fcb29f4ba02cf723d7e7ba8022149..342ff61228adaf8dacd41428f22bc90101f14183 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleErodeImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleErodeImageFilter.hxx @@ -55,16 +55,9 @@ void GrayscaleErodeImageFilter< TInputImage, TOutputImage, TKernel > ::SetKernel(const KernelType & kernel) { - const FlatKernelType *flatKernel = NULL; + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - } - catch ( ... ) - {} - - if ( flatKernel != NULL && flatKernel->GetDecomposable() ) + if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() ) { m_AnchorFilter->SetKernel(*flatKernel); m_Algorithm = ANCHOR; @@ -119,14 +112,7 @@ void GrayscaleErodeImageFilter< TInputImage, TOutputImage, TKernel > ::SetAlgorithm(int algo) { - const FlatKernelType *flatKernel = NULL; - - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); - } - catch ( ... ) - {} + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); if ( m_Algorithm != algo ) { @@ -138,11 +124,11 @@ GrayscaleErodeImageFilter< TInputImage, TOutputImage, TKernel > { m_HistogramFilter->SetKernel( this->GetKernel() ); } - else if ( flatKernel != NULL && flatKernel->GetDecomposable() && algo == ANCHOR ) + else if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() && algo == ANCHOR ) { m_AnchorFilter->SetKernel(*flatKernel); } - else if ( flatKernel != NULL && flatKernel->GetDecomposable() && algo == VHGW ) + else if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() && algo == VHGW ) { m_VHGWFilter->SetKernel(*flatKernel); } diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalClosingImageFilter.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalClosingImageFilter.hxx index 45e712beac6f582fcaacf1999295c316435874e5..4e940e19938d3ba3228b1afdd85dbe6a5c8c485b 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalClosingImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalClosingImageFilter.hxx @@ -47,16 +47,9 @@ void GrayscaleMorphologicalClosingImageFilter< TInputImage, TOutputImage, TKernel > ::SetKernel(const KernelType & kernel) { - const FlatKernelType *flatKernel = NULL; + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - } - catch ( ... ) - {} - - if ( flatKernel != NULL && flatKernel->GetDecomposable() ) + if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() ) { m_AnchorFilter->SetKernel(*flatKernel); m_Algorithm = ANCHOR; @@ -100,14 +93,7 @@ void GrayscaleMorphologicalClosingImageFilter< TInputImage, TOutputImage, TKernel > ::SetAlgorithm(int algo) { - const FlatKernelType *flatKernel = NULL; - - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); - } - catch ( ... ) - {} + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); if ( m_Algorithm != algo ) { @@ -121,11 +107,11 @@ GrayscaleMorphologicalClosingImageFilter< TInputImage, TOutputImage, TKernel > m_HistogramErodeFilter->SetKernel( this->GetKernel() ); m_HistogramDilateFilter->SetKernel( this->GetKernel() ); } - else if ( flatKernel != NULL && flatKernel->GetDecomposable() && algo == ANCHOR ) + else if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() && algo == ANCHOR ) { m_AnchorFilter->SetKernel(*flatKernel); } - else if ( flatKernel != NULL && flatKernel->GetDecomposable() && algo == VHGW ) + else if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() && algo == VHGW ) { m_VanHerkGilWermanDilateFilter->SetKernel(*flatKernel); m_VanHerkGilWermanErodeFilter->SetKernel(*flatKernel); diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalOpeningImageFilter.h b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalOpeningImageFilter.h index cfd7561c3eb935e624d1bddf626017393f705688..507a69eefb6bde50178df48d279f78c5e4c3e064 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalOpeningImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalOpeningImageFilter.h @@ -115,12 +115,12 @@ public: virtual void Modified() const; /** define values used to determine which algorithm to use */ - enum { + enum AlgorithmType { BASIC = 0, HISTO = 1, ANCHOR = 2, VHGW = 3 - } AlgorithmChoice; + }; /** A safe border is added to input image to avoid borders effects * and remove it once the closing is done */ diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalOpeningImageFilter.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalOpeningImageFilter.hxx index 1cfdce1dbc560395c465c3389c9403d6e1688195..e1710f10246d4a7d8e931602aaa478a0b2ce2147 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalOpeningImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkGrayscaleMorphologicalOpeningImageFilter.hxx @@ -29,17 +29,17 @@ namespace itk { template< typename TInputImage, typename TOutputImage, typename TKernel > GrayscaleMorphologicalOpeningImageFilter< TInputImage, TOutputImage, TKernel > -::GrayscaleMorphologicalOpeningImageFilter() +::GrayscaleMorphologicalOpeningImageFilter() : + m_HistogramDilateFilter(HistogramDilateFilterType::New()), + m_HistogramErodeFilter(HistogramErodeFilterType::New()), + m_BasicDilateFilter(BasicDilateFilterType::New()), + m_BasicErodeFilter(BasicErodeFilterType::New()), + m_VanHerkGilWermanDilateFilter(VanHerkGilWermanDilateFilterType::New()), + m_VanHerkGilWermanErodeFilter(VanHerkGilWermanErodeFilterType::New()), + m_AnchorFilter(AnchorFilterType::New()), + m_Algorithm(HISTO), + m_SafeBorder(true) { - m_BasicDilateFilter = BasicDilateFilterType::New(); - m_BasicErodeFilter = BasicErodeFilterType::New(); - m_HistogramDilateFilter = HistogramDilateFilterType::New(); - m_HistogramErodeFilter = HistogramErodeFilterType::New(); - m_VanHerkGilWermanDilateFilter = VanHerkGilWermanDilateFilterType::New(); - m_VanHerkGilWermanErodeFilter = VanHerkGilWermanErodeFilterType::New(); - m_AnchorFilter = AnchorFilterType::New(); - m_Algorithm = HISTO; - m_SafeBorder = true; } template< typename TInputImage, typename TOutputImage, typename TKernel > @@ -47,16 +47,9 @@ void GrayscaleMorphologicalOpeningImageFilter< TInputImage, TOutputImage, TKernel > ::SetKernel(const KernelType & kernel) { - const FlatKernelType *flatKernel = NULL; + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - } - catch ( ... ) - {} - - if ( flatKernel != NULL && flatKernel->GetDecomposable() ) + if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() ) { m_AnchorFilter->SetKernel(*flatKernel); m_Algorithm = ANCHOR; @@ -100,14 +93,7 @@ void GrayscaleMorphologicalOpeningImageFilter< TInputImage, TOutputImage, TKernel > ::SetAlgorithm(int algo) { - const FlatKernelType *flatKernel = NULL; - - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); - } - catch ( ... ) - {} + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); if ( m_Algorithm != algo ) { @@ -121,11 +107,11 @@ GrayscaleMorphologicalOpeningImageFilter< TInputImage, TOutputImage, TKernel > m_HistogramDilateFilter->SetKernel( this->GetKernel() ); m_HistogramErodeFilter->SetKernel( this->GetKernel() ); } - else if ( flatKernel != NULL && flatKernel->GetDecomposable() && algo == ANCHOR ) + else if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() && algo == ANCHOR ) { m_AnchorFilter->SetKernel(*flatKernel); } - else if ( flatKernel != NULL && flatKernel->GetDecomposable() && algo == VHGW ) + else if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() && algo == VHGW ) { m_VanHerkGilWermanDilateFilter->SetKernel(*flatKernel); m_VanHerkGilWermanErodeFilter->SetKernel(*flatKernel); diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkKernelImageFilter.h b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkKernelImageFilter.h index 36fca25a68af9dcbfbb44298cb971d0ca269d5ca..45e9cffb22b4b654a95919cf4668ae948f39eb77 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkKernelImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkKernelImageFilter.h @@ -29,8 +29,6 @@ namespace itk * * This filter provides the code to store the radius information about the * neighborhood used in the subclasses. - * It also conveniently reimplement the GenerateInputRequestedRegion() so - * that region is well defined for the porvided radius. * * \author Gaetan Lehmann * \ingroup ITKMathematicalMorphology diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkMorphologicalGradientImageFilter.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkMorphologicalGradientImageFilter.hxx index 7993f289bae418e3cdcb76a9265024779ac9cd65..01d9dd71360be5f468a06e740165c6003cd5ed5e 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkMorphologicalGradientImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkMorphologicalGradientImageFilter.hxx @@ -44,16 +44,9 @@ void MorphologicalGradientImageFilter< TInputImage, TOutputImage, TKernel > ::SetKernel(const KernelType & kernel) { - const FlatKernelType *flatKernel = NULL; + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &kernel ); - } - catch ( ... ) - {} - - if ( flatKernel != NULL && flatKernel->GetDecomposable() ) + if ( flatKernel != ITK_NULLPTR && flatKernel->GetDecomposable() ) { m_AnchorDilateFilter->SetKernel(*flatKernel); m_AnchorErodeFilter->SetKernel(*flatKernel); @@ -96,14 +89,7 @@ void MorphologicalGradientImageFilter< TInputImage, TOutputImage, TKernel > ::SetAlgorithm(int algo) { - const FlatKernelType *flatKernel = NULL; - - try - { - flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); - } - catch ( ... ) - {} + const FlatKernelType *flatKernel = dynamic_cast< const FlatKernelType * >( &this->GetKernel() ); if ( m_Algorithm != algo ) { diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkMovingHistogramImageFilter.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkMovingHistogramImageFilter.hxx index c0e39088db38ce41d2c5d9479871d6e030704af3..c6d9818ffff5b747d7d1e026200c148affb5b1ad 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkMovingHistogramImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkMovingHistogramImageFilter.hxx @@ -96,8 +96,6 @@ MovingHistogramImageFilter< TInputImage, TOutputImage, TKernel, THistogram > InputLineIteratorType InLineIt(inputImage, outputRegionForThread); InLineIt.SetDirection(BestDirection); - typedef ImageRegionIterator< OutputImageType > OutputIteratorType; - //OutputIteratorType oit(outputImage, outputRegionForThread); InLineIt.GoToBegin(); IndexType LineStart; //PrevLineStart = InLineIt.GetIndex(); diff --git a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkSharedMorphologyUtilities.hxx b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkSharedMorphologyUtilities.hxx index b0cb87097789875a28ed6ac11b13961000229d48..1102e0a8fe4e8835b56b48ebefb16e567f069c6d 100644 --- a/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkSharedMorphologyUtilities.hxx +++ b/Utilities/ITK/Modules/Filtering/MathematicalMorphology/include/itkSharedMorphologyUtilities.hxx @@ -94,12 +94,12 @@ int ComputeStartEnd(const typename TImage::IndexType StartIndex, unsigned perpdir = 0; for ( unsigned i = 0; i < TImage::RegionType::ImageDimension; i++ ) { - if ( vcl_fabs(line[i]) > domdir ) + if ( std::fabs(line[i]) > domdir ) { - domdir = vcl_fabs(line[i]); + domdir = std::fabs(line[i]); perpdir = i; } - if ( vcl_fabs(line[i]) > tol ) + if ( std::fabs(line[i]) > tol ) { int P1 = ImStart[i] - StartIndex[i]; int P2 = ImStart[i] + ImSize[i] - 1 - StartIndex[i]; @@ -132,8 +132,8 @@ int ComputeStartEnd(const typename TImage::IndexType StartIndex, } } } - sPos = (int)( Tnear * vcl_fabs(line[perpdir]) + 0.5 ); - ePos = (int)( Tfar * vcl_fabs(line[perpdir]) + 0.5 ); + sPos = (int)( Tnear * std::fabs(line[perpdir]) + 0.5 ); + ePos = (int)( Tfar * std::fabs(line[perpdir]) + 0.5 ); //std::cout << Tnear << " " << Tfar << std::endl; if ( Tfar < Tnear ) // seems to need some margin @@ -304,9 +304,9 @@ MakeEnlargedFace(const typename TInputImage::ConstPointer itkNotUsed(input), // figure out the dominant direction of the line for ( unsigned i = 0; i < TInputImage::RegionType::ImageDimension; i++ ) { - if ( vcl_fabs(line[i]) > MaxComp ) + if ( std::fabs(line[i]) > MaxComp ) { - MaxComp = vcl_fabs(line[i]); + MaxComp = std::fabs(line[i]); DomDir = i; } } @@ -358,7 +358,7 @@ MakeEnlargedFace(const typename TInputImage::ConstPointer itkNotUsed(input), { if ( i != NonFaceDim ) { - int Pad = Math::Ceil< int >( (float)( NonFaceLen ) * line[i] / vcl_fabs(line[NonFaceDim]) ); + int Pad = Math::Ceil< int >( (float)( NonFaceLen ) * line[i] / std::fabs(line[NonFaceDim]) ); if ( Pad < 0 ) { // just increase the size - no need to change the start @@ -415,7 +415,7 @@ unsigned int GetLinePixels(const TLine line) for ( unsigned int i = 0; i < TLine::Dimension; i++ ) { - float tt = vcl_fabs(line[i] / N); + float tt = std::fabs(line[i] / N); if ( tt > correction ) { correction = tt; } } diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkChainCodePath2D.h b/Utilities/ITK/Modules/Filtering/Path/include/itkChainCodePath2D.h index fe01f8ce3806cc2584a61baada8de598ca2b37bc..90bf60ee5defceccf7a228f53963eaa02b1e1370 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkChainCodePath2D.h +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkChainCodePath2D.h @@ -82,16 +82,16 @@ public: // Functions inherited from Path /** Evaluate the chaincode for the offset at the specified path-position. */ - virtual OutputType Evaluate(const InputType & input) const; + virtual OutputType Evaluate(const InputType & input) const ITK_OVERRIDE; /** Like Evaluate(), but returns the index at the specified path-position. */ - virtual IndexType EvaluateToIndex(const InputType & input) const; + virtual IndexType EvaluateToIndex(const InputType & input) const ITK_OVERRIDE; /** Increment the input variable passed by reference and return the offset * stored at the previous path-position. If the chaincode is unable to be * incremented, input is not changed and an offset of zero is returned, which * may be used to check for the end of the chain code. */ - virtual OffsetType IncrementInput(InputType & input) const; + virtual OffsetType IncrementInput(InputType & input) const ITK_OVERRIDE; // Functions specific to ChainCodePath and its descendents @@ -99,7 +99,7 @@ public: itkNewMacro(Self); /** How many steps in the chaincode? */ - inline ChainCodeSizeType NumberOfSteps() const { return m_Chain2D.size(); } + virtual inline ChainCodeSizeType NumberOfSteps() const ITK_OVERRIDE { return m_Chain2D.size(); } /** Insert a new step into the chaincode at a specified position */ inline void InsertStep(InputType position, int encodedStep) @@ -108,7 +108,7 @@ public: this->Modified(); } - inline void InsertStep(InputType position, OffsetType step) + virtual inline void InsertStep(InputType position, OffsetType step) ITK_OVERRIDE { m_Chain2D.insert( m_Chain2D.begin() + position, EncodeOffset(step) ); this->Modified(); @@ -121,14 +121,14 @@ public: this->Modified(); } - inline void ChangeStep(InputType position, OffsetType step) + virtual inline void ChangeStep(InputType position, OffsetType step) ITK_OVERRIDE { m_Chain2D[position] = EncodeOffset(step); this->Modified(); } /** Remove all steps from the chain code */ - virtual inline void Clear() + virtual inline void Clear() ITK_OVERRIDE { m_Chain2D.clear(); this->Modified(); @@ -139,7 +139,7 @@ public: protected: ChainCodePath2D(); ~ChainCodePath2D(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Encode and Decode between an offset and a Freeman code */ inline int EncodeOffset(OffsetType step) const diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkChainCodeToFourierSeriesPathFilter.hxx b/Utilities/ITK/Modules/Filtering/Path/include/itkChainCodeToFourierSeriesPathFilter.hxx index 220c18475ebbefa02c44d196da8ed470e02346f1..12b9d178682f22e0c352b5ad8a8e093271baf58a 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkChainCodeToFourierSeriesPathFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkChainCodeToFourierSeriesPathFilter.hxx @@ -63,7 +63,7 @@ ChainCodeToFourierSeriesPathFilter< TInputChainCodePath, TOutputFourierSeriesPat numSteps = inputPtr->NumberOfSteps(); outputPtr->Clear(); - const double nPI = 4.0 * vcl_atan(1.0); + const double nPI = 4.0 * std::atan(1.0); // Adjust our private copy of numHarmonics if necessary if ( numHarmonics <= 1 ) @@ -92,8 +92,8 @@ ChainCodeToFourierSeriesPathFilter< TInputChainCodePath, TOutputFourierSeriesPat indexVector[d] = index[d]; } - cosCoefficient += indexVector * ( vcl_cos(theta) / numSteps ); - sinCoefficient += indexVector * ( vcl_sin(theta) / numSteps ); + cosCoefficient += indexVector * ( std::cos(theta) / numSteps ); + sinCoefficient += indexVector * ( std::sin(theta) / numSteps ); } outputPtr->AddHarmonic(cosCoefficient, sinCoefficient); diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkFourierSeriesPath.hxx b/Utilities/ITK/Modules/Filtering/Path/include/itkFourierSeriesPath.hxx index c19d60ae3b5bda005bcf138ce96e3c5b4a7c0bd6..eb01807b45c80d87ac46dcdb9f016b6e2fe9da73 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkFourierSeriesPath.hxx +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkFourierSeriesPath.hxx @@ -35,7 +35,7 @@ FourierSeriesPath< VDimension > numHarmonics = m_CosCoefficients->Size(); output.Fill(0); - const double PI = 4.0 * vcl_atan(1.0); + const double PI = 4.0 * std::atan(1.0); if ( numHarmonics > 0 ) { output += m_CosCoefficients->ElementAt(0); } @@ -43,8 +43,8 @@ FourierSeriesPath< VDimension > { // input defined over [0,1] maps to theta defined over [0,2pi * n] theta = PI * 2.0 * n * input; - output += ( m_CosCoefficients->ElementAt(n) * vcl_cos(theta) - + m_SinCoefficients->ElementAt(n) * vcl_sin(theta) ) * 2.0; + output += ( m_CosCoefficients->ElementAt(n) * std::cos(theta) + + m_SinCoefficients->ElementAt(n) * std::sin(theta) ) * 2.0; } return output; @@ -62,14 +62,14 @@ FourierSeriesPath< VDimension > numHarmonics = m_CosCoefficients->Size(); output.Fill(0); - const double PI = 4.0 * vcl_atan(1.0); + const double PI = 4.0 * std::atan(1.0); for ( int n = 1; n < numHarmonics; n++ ) { // input defined over [0,1] maps to theta defined over [0,2pi * n] theta = PI * 2.0 * n * input; - output += ( m_SinCoefficients->ElementAt(n) * vcl_cos(theta) - - m_CosCoefficients->ElementAt(n) * vcl_sin(theta) ) * ( 2.0 * n ); + output += ( m_SinCoefficients->ElementAt(n) * std::cos(theta) + - m_CosCoefficients->ElementAt(n) * std::sin(theta) ) * ( 2.0 * n ); } return output; diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkHilbertPath.hxx b/Utilities/ITK/Modules/Filtering/Path/include/itkHilbertPath.hxx index fa9c1e7dcb421754f410eb4f3209868b2f8e102b..8523fa8599436c80c501232a1d29646fe9ae4490 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkHilbertPath.hxx +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkHilbertPath.hxx @@ -179,7 +179,7 @@ HilbertPath<TIndexValue, VDimension> return x; } - PathIndexType m = static_cast<PathIndexType>( vcl_ceil( vcl_log( static_cast<double>(x) ) / vcl_log( 2.0 ) ) ) + 1; + PathIndexType m = static_cast<PathIndexType>( std::ceil( std::log( static_cast<double>(x) ) / std::log( 2.0 ) ) ) + 1; PathIndexType i = x; PathIndexType j = 1; diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkImageAndPathToImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Path/include/itkImageAndPathToImageFilter.hxx index 0bafb78e1ed02505f5ddb101dde857b491a73797..d6702f5cfedfbfdeab97f502874ce7cbfc14fdc4 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkImageAndPathToImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkImageAndPathToImageFilter.hxx @@ -62,7 +62,7 @@ ImageAndPathToImageFilter< TInputImage, TInputPath, TOutputImage > ::GetNonConstImageInput(void) { TInputImage * temp_return=dynamic_cast< TInputImage * >( this->ProcessObject::GetInput(0) ); - if(temp_return == NULL) + if(temp_return == ITK_NULLPTR) { itkExceptionMacro("Invalid type conversion in GetNonConstImageInput()") } @@ -94,7 +94,7 @@ ImageAndPathToImageFilter< TInputImage, TInputPath, TOutputImage > ::GetNonConstPathInput(void) { TInputPath * temp_return = dynamic_cast< TInputPath * >( this->ProcessObject::GetInput(1) ); - if(temp_return == NULL) + if(temp_return == ITK_NULLPTR) { itkExceptionMacro("Invalid type conversion in GetNonConstPathInput()") } diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkOrthogonalSwath2DPathFilter.hxx b/Utilities/ITK/Modules/Filtering/Path/include/itkOrthogonalSwath2DPathFilter.hxx index 7809035af965db9a7d7c9f5822a0ff93f17bed5b..ad4528d546ec0a08a7f278211305ecfdc0baa287 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkOrthogonalSwath2DPathFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkOrthogonalSwath2DPathFilter.hxx @@ -37,9 +37,9 @@ OrthogonalSwath2DPathFilter< TParametricPath, TSwathMeritImage > size[0] = 0; size[1] = 0; m_SwathSize = size; - m_StepValues = NULL; - m_MeritValues = NULL; - m_OptimumStepsValues = NULL; + m_StepValues = ITK_NULLPTR; + m_MeritValues = ITK_NULLPTR; + m_OptimumStepsValues = ITK_NULLPTR; m_FinalOffsetValues = OrthogonalCorrectionTableType::New(); } diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkOrthogonallyCorrected2DParametricPath.h b/Utilities/ITK/Modules/Filtering/Path/include/itkOrthogonallyCorrected2DParametricPath.h index e74adaa8a6d53814adc30c94963604f4c6a6f796..1eb36c5b61521dded996b7eb105773a32dfc9d61 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkOrthogonallyCorrected2DParametricPath.h +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkOrthogonallyCorrected2DParametricPath.h @@ -73,7 +73,7 @@ public: typedef OrthogonalCorrectionTableType::ElementIdentifier OrthogonalCorrectionTableSizeType; /** Return the location of the parametric path at the specified location. */ - virtual OutputType Evaluate(const InputType & input) const; + virtual OutputType Evaluate(const InputType & input) const ITK_OVERRIDE; /** Set pointer to the original path. The path MUST be continuous in its * first derivative to prevent discontinuities in the corrected path. The @@ -90,19 +90,19 @@ public: itkNewMacro(Self); /** Needed for Pipelining */ - virtual void Initialize(void) + virtual void Initialize(void) ITK_OVERRIDE { - this->m_OriginalPath = NULL; - this->m_OrthogonalCorrectionTable = NULL; + this->m_OriginalPath = ITK_NULLPTR; + this->m_OrthogonalCorrectionTable = ITK_NULLPTR; } /** These are determined by the original path */ - virtual inline InputType StartOfInput() const + virtual inline InputType StartOfInput() const ITK_OVERRIDE { return m_OriginalPath->StartOfInput(); } - virtual inline InputType EndOfInput() const + virtual inline InputType EndOfInput() const ITK_OVERRIDE { return m_OriginalPath->EndOfInput(); } @@ -110,7 +110,7 @@ public: protected: OrthogonallyCorrected2DParametricPath(); ~OrthogonallyCorrected2DParametricPath(){} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: OrthogonallyCorrected2DParametricPath(const Self &); //purposely not diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkPath.h b/Utilities/ITK/Modules/Filtering/Path/include/itkPath.h index d40e4715ec1ce0db7fb1c3a05c571476396e15b2..bc66820a20b3a32333f272b06ac0b8483038bf01 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkPath.h +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkPath.h @@ -111,7 +111,7 @@ protected: Path(); ~Path(){} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; itkGetConstMacro(ZeroOffset, OffsetType); itkGetConstMacro(ZeroIndex, IndexType); diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkPathFunctions.h b/Utilities/ITK/Modules/Filtering/Path/include/itkPathFunctions.h index a6eb924d81570411b0c9df0ebe07dcc460a9a1fc..f40e2b10534261375aa0f236eac778d402e99ecf 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkPathFunctions.h +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkPathFunctions.h @@ -35,9 +35,7 @@ void MakeChainCodeTracePath(TChainCodePath & chainPath, { typedef typename TChainCodePath::OffsetType OffsetType; typedef typename TChainCodePath::InputType ChainInputType; - typedef typename TChainCodePath::OutputType ChainOutputType; typedef typename TPathInput::InputType InPathInputType; - typedef typename TPathInput::OutputType InPathOutputType; OffsetType offset, tempOffset, zeroOffset; InPathInputType inPathInput; @@ -86,9 +84,7 @@ void MakeFourierSeriesPathTraceChainCode(TFourierSeriesPath & FSPath, typedef typename TFourierSeriesPath::VectorType VectorType; typedef typename TFourierSeriesPath::InputType FSInputType; - typedef typename TFourierSeriesPath::OutputType FSOutputType; typedef typename TChainCodePath::InputType ChainInputType; - typedef typename TChainCodePath::OutputType ChainOutputType; IndexType index; VectorType indexVector; @@ -98,7 +94,7 @@ void MakeFourierSeriesPathTraceChainCode(TFourierSeriesPath & FSPath, int dimension = OffsetType::GetOffsetDimension(); unsigned numSteps = chainPath.NumberOfSteps(); - const double PI = 4.0 * vcl_atan(1.0); + const double PI = 4.0 * std::atan(1.0); FSPath.Clear(); @@ -128,8 +124,8 @@ void MakeFourierSeriesPathTraceChainCode(TFourierSeriesPath & FSPath, { indexVector[d] = index[d]; } - cosCoefficient += indexVector * ( vcl_cos(theta) / numSteps ); - sinCoefficient += indexVector * ( vcl_sin(theta) / numSteps ); + cosCoefficient += indexVector * ( std::cos(theta) / numSteps ); + sinCoefficient += indexVector * ( std::sin(theta) / numSteps ); } FSPath.AddHarmonic(cosCoefficient, sinCoefficient); diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkPathSource.h b/Utilities/ITK/Modules/Filtering/Path/include/itkPathSource.h index ce43ff6556711adc50d40c773c066412066f538f..60b6cc06c885f796971b03d44e20875dc7293d2c 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkPathSource.h +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkPathSource.h @@ -168,12 +168,12 @@ public: * an implementation of MakeOutput(). */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; protected: PathSource(); virtual ~PathSource() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; // Inherit the empty ProcessObject::GenerateData() diff --git a/Utilities/ITK/Modules/Filtering/Path/include/itkPolyLineParametricPath.hxx b/Utilities/ITK/Modules/Filtering/Path/include/itkPolyLineParametricPath.hxx index 5a85694b6be42951a456d489023345fe31b8218a..3d4d52931b67fb704ae3a3505dcf61d0ca08e67e 100644 --- a/Utilities/ITK/Modules/Filtering/Path/include/itkPolyLineParametricPath.hxx +++ b/Utilities/ITK/Modules/Filtering/Path/include/itkPolyLineParametricPath.hxx @@ -84,7 +84,7 @@ PolyLineParametricPath<VDimension> ::IncrementInput(InputType & input) const { //Save this input index since we will use it to calculate the offset - const OutputType originalIndex = this->EvaluateToIndex(input); + const IndexType originalIndex = this->EvaluateToIndex(input); InputType potentialTimestep = itk::NumericTraits< InputType >::ZeroValue(); bool timeStepSmallEnough = false; @@ -92,7 +92,7 @@ PolyLineParametricPath<VDimension> { if (input == this->EndOfInput()) { - const OutputType finalIndex = this->EvaluateToIndex(this->EndOfInput()); + const IndexType finalIndex = this->EvaluateToIndex(this->EndOfInput()); OffsetType finalOffset; for (unsigned int i = 0; i < VDimension; ++i) { @@ -102,7 +102,7 @@ PolyLineParametricPath<VDimension> } //Check to make sure we aren't already at a place with an offset of 1 pixel - const OutputType potentialIndex = this->EvaluateToIndex(input); + const IndexType potentialIndex = this->EvaluateToIndex(input); //For some reason, there's no way to convert OutputType to OffsetType OffsetType offset; for (unsigned int i = 0; i < VDimension; ++i) @@ -146,7 +146,7 @@ PolyLineParametricPath<VDimension> const InputType timestep = potentialTimestep; //Get the index at the next timestep so we can calculate the offset - const OutputType nextIndex = this->EvaluateToIndex(input + timestep); + const IndexType nextIndex = this->EvaluateToIndex(input + timestep); //For some reason, there's no way to convert OutputType to OffsetType OffsetType offset; diff --git a/Utilities/ITK/Modules/Filtering/Path/src/itkOrthogonallyCorrected2DParametricPath.cxx b/Utilities/ITK/Modules/Filtering/Path/src/itkOrthogonallyCorrected2DParametricPath.cxx index 66e3ff4e9419d7cb1df0e0ae7f68280b37ead3f2..399267239de349e97433ea3b29bdc7912ab79ac1 100644 --- a/Utilities/ITK/Modules/Filtering/Path/src/itkOrthogonallyCorrected2DParametricPath.cxx +++ b/Utilities/ITK/Modules/Filtering/Path/src/itkOrthogonallyCorrected2DParametricPath.cxx @@ -91,7 +91,7 @@ OrthogonallyCorrected2DParametricPath OrthogonallyCorrected2DParametricPath ::OrthogonallyCorrected2DParametricPath() { - m_OriginalPath = NULL; + m_OriginalPath = ITK_NULLPTR; m_OrthogonalCorrectionTable = OrthogonalCorrectionTableType::New(); } diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkBorderQuadEdgeMeshFilter.hxx b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkBorderQuadEdgeMeshFilter.hxx index 9ad40295cf7f2581a019c6ab79783bca904cc029..114f42dc1c755f122a022f0cdebb9fc355fa2e50 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkBorderQuadEdgeMeshFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkBorderQuadEdgeMeshFilter.hxx @@ -56,7 +56,7 @@ void BorderQuadEdgeMeshFilter< TInputMesh, TOutputMesh > ::ComputeBoundary() { - InputQEType *bdryEdge = NULL; + InputQEType *bdryEdge = ITK_NULLPTR; switch( m_BorderPick ) { @@ -215,7 +215,7 @@ BorderQuadEdgeMeshFilter< TInputMesh, TOutputMesh > std::vector< InputCoordRepType > tetas(NbBoundaryPt, 0.0); tetas[0] = static_cast< InputCoordRepType >( - vcl_acos( ( two_r - dist ) * inv_two_r ) ); + std::acos( ( two_r - dist ) * inv_two_r ) ); MapPointIdentifierIterator BoundaryPtIterator = this->m_BoundaryPtMap.begin(); @@ -232,7 +232,7 @@ BorderQuadEdgeMeshFilter< TInputMesh, TOutputMesh > dist = pt1.SquaredEuclideanDistanceTo(pt2); - tetas[j] = tetas[j - 1] + vcl_acos( ( two_r - dist ) * inv_two_r ); + tetas[j] = tetas[j - 1] + std::acos( ( two_r - dist ) * inv_two_r ); ++j; ++BoundaryPtIterator; @@ -242,7 +242,7 @@ BorderQuadEdgeMeshFilter< TInputMesh, TOutputMesh > if ( this->m_Radius == 0.0 ) { - this->m_Radius = vcl_pow(vcl_sqrt(r), a); + this->m_Radius = std::pow(std::sqrt(r), a); } for ( MapPointIdentifierIterator @@ -253,8 +253,8 @@ BorderQuadEdgeMeshFilter< TInputMesh, TOutputMesh > id = BoundaryPtMapIterator->first; j = BoundaryPtMapIterator->second; - pt1[0] = this->m_Radius * static_cast< InputCoordRepType >( vcl_cos(a * tetas[j]) ); - pt1[1] = this->m_Radius * static_cast< InputCoordRepType >( vcl_sin(a * tetas[j]) ); + pt1[0] = this->m_Radius * static_cast< InputCoordRepType >( std::cos(a * tetas[j]) ); + pt1[1] = this->m_Radius * static_cast< InputCoordRepType >( std::sin(a * tetas[j]) ); pt1[2] = 0.0; this->m_Border[j] = pt1; diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkCleanQuadEdgeMeshFilter.hxx b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkCleanQuadEdgeMeshFilter.hxx index eadb20f43d4266b7da03c59a6386162fff8946c3..15db09af11c2f27b39417e82b5db117484e78edf 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkCleanQuadEdgeMeshFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkCleanQuadEdgeMeshFilter.hxx @@ -141,7 +141,7 @@ CleanQuadEdgeMeshFilter< TInputMesh, TOutputMesh > while ( p_it != p_end ) { id = p_it->Index(); - if ( output->FindEdge(id) == 0 ) + if ( output->FindEdge(id) == ITK_NULLPTR ) { output->DeletePoint(id); } diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDecimationQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDecimationQuadEdgeMeshFilter.h index 776e0f58d278b9b7550a105270678de74c657643..a52981e031386626922be37462c92bac90c512d4 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDecimationQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDecimationQuadEdgeMeshFilter.h @@ -59,7 +59,7 @@ protected: DecimationQuadEdgeMeshFilter() { this->m_Iteration = 0; - this->m_OutputMesh = 0; + this->m_OutputMesh = ITK_NULLPTR; } ~DecimationQuadEdgeMeshFilter() {} diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDelaunayConformingQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDelaunayConformingQuadEdgeMeshFilter.h index 5f9f4b955c61c6959439f3c63eb1ab98e69111e0..327688ac4ac538874e8c021cfcd70d9580ce3306 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDelaunayConformingQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDelaunayConformingQuadEdgeMeshFilter.h @@ -22,7 +22,6 @@ #include "itkPriorityQueueContainer.h" #include "itkQuadEdgeMeshToQuadEdgeMeshFilter.h" #include "itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.h" -#include "vcl_cmath.h" #include "vnl/vnl_math.h" namespace itk @@ -171,7 +170,7 @@ protected: if ( den != 0. ) { - dotA /= vcl_sqrt(den); + dotA /= std::sqrt(den); } if ( dotA > 1. ) @@ -188,7 +187,7 @@ protected: if ( den != 0. ) { - dotB /= vcl_sqrt(den); + dotB /= std::sqrt(den); } if ( dotB > 1. ) @@ -201,7 +200,7 @@ protected: dotB = -1.; } - return ( vcl_acos(dotA) + vcl_acos(dotB) - vnl_math::pi ); + return ( std::acos(dotA) + std::acos(dotB) - vnl_math::pi ); } private: diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDelaunayConformingQuadEdgeMeshFilter.hxx b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDelaunayConformingQuadEdgeMeshFilter.hxx index 60bf1b57012d10bd80c0366cf614805b7b12cd15..67eea4fdced1e38452e680162ed4660f34adcefa 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDelaunayConformingQuadEdgeMeshFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDelaunayConformingQuadEdgeMeshFilter.hxx @@ -55,7 +55,7 @@ void DelaunayConformingQuadEdgeMeshFilter< TInputMesh, TOutputMesh >::Initialize { OutputMeshType *output = this->GetOutput(); - OutputEdgeCellType *edge = 0; + OutputEdgeCellType *edge = ITK_NULLPTR; CriterionValueType value = 0.; @@ -140,7 +140,7 @@ void DelaunayConformingQuadEdgeMeshFilter< TInputMesh, TOutputMesh >::Process() m_QueueMapper.erase(edge); qe = m_FlipEdge->Evaluate(qe); - if ( qe != 0 ) + if ( qe != ITK_NULLPTR ) { ++this->m_NumberOfEdgeFlips; list_qe[4] = qe; diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteCurvatureQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteCurvatureQuadEdgeMeshFilter.h index c5cc34dbb98623890eb864f6886686ff80f335b7..b918ea20f8c51c42b7f1d8db9752fac71308bbae 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteCurvatureQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteCurvatureQuadEdgeMeshFilter.h @@ -69,7 +69,7 @@ public: #endif protected: - DiscreteCurvatureQuadEdgeMeshFilter() : m_OutputMesh(0) {} + DiscreteCurvatureQuadEdgeMeshFilter() : m_OutputMesh(ITK_NULLPTR) {} virtual ~DiscreteCurvatureQuadEdgeMeshFilter() {} virtual OutputCurvatureType EstimateCurvature(const OutputPointType & iP) = 0; diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteGaussianCurvatureQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteGaussianCurvatureQuadEdgeMeshFilter.h index 5a7800337d90f988f1acf047c1702a9a7d4cf5d5..2d1c5d1e50bb0a9cef8499437db4fb43088cfae8 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteGaussianCurvatureQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteGaussianCurvatureQuadEdgeMeshFilter.h @@ -85,7 +85,7 @@ protected: OutputQEType *qe = iP.GetEdge(); - if ( qe != 0 ) + if ( qe != ITK_NULLPTR ) { OutputQEType *qe_it = qe; OutputQEType *qe_it2; diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMaximumCurvatureQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMaximumCurvatureQuadEdgeMeshFilter.h index 6c45ef07477520ee4e0a33704c9472e83ceb3b36..7e999238b3e4ba9f841a40a863402cd121043fea 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMaximumCurvatureQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMaximumCurvatureQuadEdgeMeshFilter.h @@ -78,7 +78,7 @@ protected: virtual OutputCurvatureType EstimateCurvature(const OutputPointType & iP) { this->ComputeMeanAndGaussianCurvatures(iP); - return this->m_Mean + vcl_sqrt( this->ComputeDelta() ); + return this->m_Mean + std::sqrt( this->ComputeDelta() ); } private: diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMeanCurvatureQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMeanCurvatureQuadEdgeMeshFilter.h index b59b817bd7bde88f8de39a53f2c6cac76a2d8ccd..d95f87f74e3bd0ed651f7a0a6822712d83958a50 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMeanCurvatureQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMeanCurvatureQuadEdgeMeshFilter.h @@ -95,7 +95,7 @@ protected: OutputVectorType normal; normal.Fill(0.); - if ( qe != 0 ) + if ( qe != ITK_NULLPTR ) { if ( qe != qe->GetOnext() ) { diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMinimumCurvatureQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMinimumCurvatureQuadEdgeMeshFilter.h index f0b81132382b641d2276029d900a4e4c8e8c2939..8dd173d3925a7addb93818417049a3656742e64d 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMinimumCurvatureQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscreteMinimumCurvatureQuadEdgeMeshFilter.h @@ -78,7 +78,7 @@ protected: virtual OutputCurvatureType EstimateCurvature(const OutputPointType & iP) { this->ComputeMeanAndGaussianCurvatures(iP); - return this->m_Mean - vcl_sqrt( this->ComputeDelta() ); + return this->m_Mean - std::sqrt( this->ComputeDelta() ); } private: diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscretePrincipalCurvaturesQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscretePrincipalCurvaturesQuadEdgeMeshFilter.h index 89a8a78e74edd3e3f92a4bf7f31e9a6d6aaa01ba..8903a7308ef1bf77e61d5ebaf6e41697134fbcff 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscretePrincipalCurvaturesQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkDiscretePrincipalCurvaturesQuadEdgeMeshFilter.h @@ -87,7 +87,7 @@ protected: m_Mean = 0.; m_Gaussian = 0.; - if ( qe != 0 ) + if ( qe != ITK_NULLPTR ) { OutputVectorType Laplace; Laplace.Fill(0.); diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkEdgeDecimationQuadEdgeMeshFilter.hxx b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkEdgeDecimationQuadEdgeMeshFilter.hxx index 9967b37782714a34eb3bdae6610b853be78ec550..66d4aecbf7d59c76b160abd0ecc90c3dd1432f23 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkEdgeDecimationQuadEdgeMeshFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkEdgeDecimationQuadEdgeMeshFilter.hxx @@ -23,9 +23,13 @@ namespace itk { template< typename TInput, typename TOutput, typename TCriterion > -EdgeDecimationQuadEdgeMeshFilter< TInput, TOutput, - TCriterion >::EdgeDecimationQuadEdgeMeshFilter():Superclass(), - m_Relocate(true), m_CheckOrientation(false) +EdgeDecimationQuadEdgeMeshFilter< TInput, TOutput,TCriterion >:: +EdgeDecimationQuadEdgeMeshFilter() : + Superclass(), + m_Relocate(true), + m_CheckOrientation(false), + m_Element(ITK_NULLPTR) + { m_JoinVertexFunction = OperatorType::New(); m_PriorityQueue = PriorityQueueType::New(); @@ -103,7 +107,7 @@ IsEdgeOKToBeProcessed(OutputQEType *) #endif { #ifdef NDEBUG - if ( iEdge == 0 ) + if ( iEdge == ITK_NULLPTR ) { itkDebugMacro("iEdge == 0, at iteration: " << this->m_Iteration); return false; @@ -118,13 +122,13 @@ IsEdgeOKToBeProcessed(OutputQEType *) } OutputMeshPointer output = this->GetOutput(); - if ( output->FindEdge(id_org) == 0 ) + if ( output->FindEdge(id_org) == ITK_NULLPTR ) { itkDebugMacro("output->FindEdge( id_org ) == 0, at iteration: " << this->m_Iteration); return false; } - if ( iEdge->GetSym() == 0 ) + if ( iEdge->GetSym() == ITK_NULLPTR ) { itkDebugMacro("iEdge->GetSym() == 0, at iteration: " << this->m_Iteration); @@ -138,13 +142,13 @@ IsEdgeOKToBeProcessed(OutputQEType *) << this->m_Iteration); return false; } - if ( output->FindEdge(id_dest) == 0 ) + if ( output->FindEdge(id_dest) == ITK_NULLPTR ) { itkDebugMacro("output->FindEdge( id_dest ) == 0, at iteration: " << this->m_Iteration); return false; } - if ( output->FindEdge(id_org, id_dest) == 0 ) + if ( output->FindEdge(id_org, id_dest) == ITK_NULLPTR ) { itkDebugMacro("output->FindEdge( id_org, id_dest ) == 0, at iteration: " << this->m_Iteration); @@ -372,7 +376,7 @@ EdgeDecimationQuadEdgeMeshFilter< TInput, TOutput, TCriterion >::ProcessWithoutA DeletePoint(old_id, new_id); OutputQEType *edge = this->m_OutputMesh->FindEdge(new_id); - if ( edge == 0 ) + if ( edge == ITK_NULLPTR ) { itkDebugMacro("edge == 0, at iteration " << this->m_Iteration); return false; diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkNormalQuadEdgeMeshFilter.hxx b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkNormalQuadEdgeMeshFilter.hxx index d08ab05cbb395bb29254d6353d4cc5a900b58d4d..561a0afd19e0ca7355ed3a233362df991ace41fc 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkNormalQuadEdgeMeshFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkNormalQuadEdgeMeshFilter.hxx @@ -73,7 +73,7 @@ NormalQuadEdgeMeshFilter< TInputMesh, TOutputMesh > { poly = dynamic_cast< OutputPolygonType * >( cell_it.Value() ); - if ( poly != 0 ) + if ( poly != ITK_NULLPTR ) { if ( poly->GetNumberOfPoints() == 3 ) { @@ -146,7 +146,7 @@ NormalQuadEdgeMeshFilter< TInputMesh, TOutputMesh > OutputPolygonType *poly = dynamic_cast< OutputPolygonType * >( outputMesh->GetCells()->GetElement(iCId) ); - if ( poly != 0 ) // this test should be removed... + if ( poly != ITK_NULLPTR ) // this test should be removed... { // this test should be removed... if ( poly->GetNumberOfPoints() == 3 ) @@ -209,7 +209,7 @@ NormalQuadEdgeMeshFilter< TInputMesh, TOutputMesh > v *= norm_v; } return static_cast< OutputVertexNormalComponentType >( - vcl_acos(u * v) ); + std::acos(u * v) ); } case AREA: { diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkParameterizationQuadEdgeMeshFilter.hxx b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkParameterizationQuadEdgeMeshFilter.hxx index ce089ea268c94e8d760c66d8e0f0743c7a216700..6fe33b866972486863ac8b5575b4db32a64c5551 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkParameterizationQuadEdgeMeshFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkParameterizationQuadEdgeMeshFilter.hxx @@ -27,8 +27,8 @@ template< typename TInputMesh, typename TOutputMesh, typename TSolverTraits > ParameterizationQuadEdgeMeshFilter< TInputMesh, TOutputMesh, TSolverTraits > ::ParameterizationQuadEdgeMeshFilter() { - this->m_CoefficientsMethod = 0; - this->m_BorderTransform = 0; + this->m_CoefficientsMethod = ITK_NULLPTR; + this->m_BorderTransform = ITK_NULLPTR; } // --------------------------------------------------------------------- diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkQuadEdgeMeshDecimationCriteria.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkQuadEdgeMeshDecimationCriteria.h index d778c824454f8eb8085c2ee912f88b30534aa6fe..a4a9234e61df952ccb1ab9b1d212c3cb338b29de 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkQuadEdgeMeshDecimationCriteria.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkQuadEdgeMeshDecimationCriteria.h @@ -80,7 +80,7 @@ protected: } ~QuadEdgeMeshDecimationCriterion() {} - void PrintSelf(std::ostream & os, Indent indent) const + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE { Superclass::PrintSelf(os, indent); os << indent << "TopologicalChange: " diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkQuadricDecimationQuadEdgeMeshFilter.hxx b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkQuadricDecimationQuadEdgeMeshFilter.hxx index 9337036290adab272cee2dca697e81ac53b11af5..e3fe44a51c7f9122728b4bf82cfd7391a8dee134 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkQuadricDecimationQuadEdgeMeshFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkQuadricDecimationQuadEdgeMeshFilter.hxx @@ -51,7 +51,7 @@ QuadricDecimationQuadEdgeMeshFilter< TInput, TOutput, TCriterion > p_id = it->Index(); qe = output->FindEdge(p_id); - if ( qe != 0 ) + if ( qe != ITK_NULLPTR ) { qe_it = qe; do diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkSmoothingQuadEdgeMeshFilter.hxx b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkSmoothingQuadEdgeMeshFilter.hxx index b44cc027c2e04dda5d746fcadb69c48c6b95e582..1a0f8c97b42526cb3eced590007cd61a27352759 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkSmoothingQuadEdgeMeshFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkSmoothingQuadEdgeMeshFilter.hxx @@ -26,7 +26,7 @@ template< typename TInputMesh, typename TOutputMesh > SmoothingQuadEdgeMeshFilter< TInputMesh, TOutputMesh > ::SmoothingQuadEdgeMeshFilter() { - this->m_CoefficientsMethod = 0; + this->m_CoefficientsMethod = ITK_NULLPTR; this->m_DelaunayConforming = false; this->m_NumberOfIterations = 1; this->m_RelaxationFactor = static_cast< OutputCoordType >( 1.0 ); @@ -98,7 +98,7 @@ void SmoothingQuadEdgeMeshFilter< TInputMesh, TOutputMesh >::GenerateData() { p = it.Value(); qe = p.GetEdge(); - if ( qe != 0 ) + if ( qe != ITK_NULLPTR ) { r = p; v.Fill(0.0); diff --git a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkSquaredEdgeLengthDecimationQuadEdgeMeshFilter.h b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkSquaredEdgeLengthDecimationQuadEdgeMeshFilter.h index d21cdfb597c4376bee52743c08bb667427e85999..151cb4c5ad7f1a62665dafd11100553549403bec 100644 --- a/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkSquaredEdgeLengthDecimationQuadEdgeMeshFilter.h +++ b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/include/itkSquaredEdgeLengthDecimationQuadEdgeMeshFilter.h @@ -73,8 +73,9 @@ protected: SquaredEdgeLengthDecimationQuadEdgeMeshFilter(); virtual ~SquaredEdgeLengthDecimationQuadEdgeMeshFilter(); - /** - * Compute the measure value for iEdge. + // keep the start of this documentation text on very first comment line, + // it prevents a Doxygen bug + /** Compute the measure value for iEdge. * * \param[in] iEdge * \return measure value, here the squared edge length @@ -90,8 +91,9 @@ protected: return static_cast< MeasureType >( org.SquaredEuclideanDistanceTo(dest) ); } - /** - * Calculate the position of the remaining vertex from collapsing iEdge. + // keep the start of this documentation text on very first comment line, + // it prevents a Doxygen bug + /** Calculate the position of the remaining vertex from collapsing iEdge. * * \param[in] iEdge * \return the optimal point location diff --git a/Utilities/ITK/Modules/Core/QuadEdgeMesh/wrapping/itkMatrixCoefficients.wrap b/Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/wrapping/itkMatrixCoefficients.wrap similarity index 100% rename from Utilities/ITK/Modules/Core/QuadEdgeMesh/wrapping/itkMatrixCoefficients.wrap rename to Utilities/ITK/Modules/Filtering/QuadEdgeMeshFiltering/wrapping/itkMatrixCoefficients.wrap diff --git a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.h b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.h index af3d275e34d8adf9172dc0c3c5725c5c68fccc69..0013d04899d7e69e17427b9d6d641c64a8ffb3f2 100644 --- a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.h @@ -218,8 +218,7 @@ public: * provide an implementation for GenerateInputRequestedRegion() in * order to inform the pipeline execution model. * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.hxx index d8f8ed1ec878a9514024f8bb649abc96fc7ad93b..d3699ab6f86f52b062e106a8d035d8a64c36f5ae 100644 --- a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkDiscreteGaussianImageFilter.hxx @@ -31,7 +31,6 @@ template< typename TInputImage, typename TOutputImage > void DiscreteGaussianImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkRecursiveGaussianImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkRecursiveGaussianImageFilter.hxx index a5ec5c57a6f06e4c24951eca888ee931a2960743..e2c44bb79d4a50ac96bebe7a0e6a991cff4d9ee2 100644 --- a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkRecursiveGaussianImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkRecursiveGaussianImageFilter.hxx @@ -241,12 +241,12 @@ RecursiveGaussianImageFilter< TInputImage, TOutputImage > ScalarRealType & N0, ScalarRealType & N1, ScalarRealType & N2, ScalarRealType & N3, ScalarRealType & SN, ScalarRealType & DN, ScalarRealType & EN) { - ScalarRealType Sin1 = vcl_sin(W1 / sigmad); - ScalarRealType Sin2 = vcl_sin(W2 / sigmad); - ScalarRealType Cos1 = vcl_cos(W1 / sigmad); - ScalarRealType Cos2 = vcl_cos(W2 / sigmad); - ScalarRealType Exp1 = vcl_exp(L1 / sigmad); - ScalarRealType Exp2 = vcl_exp(L2 / sigmad); + ScalarRealType Sin1 = std::sin(W1 / sigmad); + ScalarRealType Sin2 = std::sin(W2 / sigmad); + ScalarRealType Cos1 = std::cos(W1 / sigmad); + ScalarRealType Cos2 = std::cos(W2 / sigmad); + ScalarRealType Exp1 = std::exp(L1 / sigmad); + ScalarRealType Exp2 = std::exp(L2 / sigmad); N0 = A1 + A2; N1 = Exp2 * ( B2 * Sin2 - ( A2 + 2 * A1 ) * Cos2 ); @@ -273,12 +273,12 @@ RecursiveGaussianImageFilter< TInputImage, TOutputImage > ScalarRealType W1, ScalarRealType L1, ScalarRealType W2, ScalarRealType L2, ScalarRealType & SD, ScalarRealType & DD, ScalarRealType & ED) { - // const ScalarRealType Sin1 = vcl_sin(W1 / sigmad); - // const ScalarRealType Sin2 = vcl_sin(W2 / sigmad); - const ScalarRealType Cos1 = vcl_cos(W1 / sigmad); - const ScalarRealType Cos2 = vcl_cos(W2 / sigmad); - const ScalarRealType Exp1 = vcl_exp(L1 / sigmad); - const ScalarRealType Exp2 = vcl_exp(L2 / sigmad); + // const ScalarRealType Sin1 = std::sin(W1 / sigmad); + // const ScalarRealType Sin2 = std::sin(W2 / sigmad); + const ScalarRealType Cos1 = std::cos(W1 / sigmad); + const ScalarRealType Cos2 = std::cos(W2 / sigmad); + const ScalarRealType Exp1 = std::exp(L1 / sigmad); + const ScalarRealType Exp2 = std::exp(L2 / sigmad); this->m_D4 = Exp1 * Exp1 * Exp2 * Exp2; this->m_D3 = -2 * Cos1 * Exp1 * Exp2 * Exp2; diff --git a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkSmoothingRecursiveGaussianImageFilter.h b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkSmoothingRecursiveGaussianImageFilter.h index c01f6ee67d387e1f77dc9a509a722c91523aa437..5d5cdff4b4c8b1f8f6c05e7f5ad63b3723ed362e 100644 --- a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkSmoothingRecursiveGaussianImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkSmoothingRecursiveGaussianImageFilter.h @@ -163,8 +163,7 @@ protected: * an implementation for GenerateInputRequestedRegion in order to inform * the pipeline execution model. * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); // Override since the filter produces the entire dataset void EnlargeOutputRequestedRegion(DataObject *output); diff --git a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkSmoothingRecursiveGaussianImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkSmoothingRecursiveGaussianImageFilter.hxx index b1e11f163d8640eb430c538dcf335475bfa72bae..f9b32306a5e8af13948a3852dd3aaa0b5364bdd6 100644 --- a/Utilities/ITK/Modules/Filtering/Smoothing/include/itkSmoothingRecursiveGaussianImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Smoothing/include/itkSmoothingRecursiveGaussianImageFilter.hxx @@ -184,7 +184,6 @@ template< typename TInputImage, typename TOutputImage > void SmoothingRecursiveGaussianImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // Call the superclass' implementation of this method. This should // copy the output requested region to the input requested region. diff --git a/Utilities/ITK/Modules/Filtering/SpatialFunction/include/itkSpatialFunctionImageEvaluatorFilter.hxx b/Utilities/ITK/Modules/Filtering/SpatialFunction/include/itkSpatialFunctionImageEvaluatorFilter.hxx index 2638efdd3aa089cb2dc533a26c01bf5c20d722a4..549c716bd5614c1c42268845cc7af5c6f7aec5e0 100644 --- a/Utilities/ITK/Modules/Filtering/SpatialFunction/include/itkSpatialFunctionImageEvaluatorFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/SpatialFunction/include/itkSpatialFunctionImageEvaluatorFilter.hxx @@ -30,7 +30,7 @@ SpatialFunctionImageEvaluatorFilter< TSpatialFunction, TInputImage, TOutputImage itkDebugMacro(<< "SpatialFunctionImageEvaluatorFilter::SpatialFunctionImageEvaluatorFilter() called"); // Set the internal function to null - this->m_PixelFunction = 0; + this->m_PixelFunction = ITK_NULLPTR; } template< typename TSpatialFunction, typename TInputImage, typename TOutputImage > diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdCalculator.h b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdCalculator.h index a8c25c0a3faaa4241e01a09fa33c8ab1cacd4acd..3e2fe7e5ce7cc5697489bce81c903015a8275cc8 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdCalculator.h +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdCalculator.h @@ -75,7 +75,7 @@ public: { if ( this->GetNumberOfInputs() < 1 ) { - return 0; + return ITK_NULLPTR; } return static_cast< const HistogramType * >( this->ProcessObject::GetInput(0) ); } @@ -84,13 +84,13 @@ public: { if ( this->GetNumberOfOutputs() < 1 ) { - return 0; + return ITK_NULLPTR; } return static_cast< DecoratedOutputType * >( this->ProcessObject::GetOutput(0) ); } using Superclass::MakeOutput; - virtual typename DataObject::Pointer MakeOutput(DataObjectPointerArraySizeType) + virtual typename DataObject::Pointer MakeOutput(DataObjectPointerArraySizeType) ITK_OVERRIDE { return DecoratedOutputType::New().GetPointer(); } diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdImageFilter.h b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdImageFilter.h index 3acfb4ee3830098887c5e6b1dafcc2bffb1ad401..55942bdd60236cad726d6186678f222adfa13185 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdImageFilter.h @@ -163,7 +163,7 @@ public: itkGetConstMacro(NumberOfHistogramBins, unsigned int); /** Does histogram generator compute min and max from data? - * Default is false for all but char types */ + * Default is true for all but char types */ itkSetMacro(AutoMinimumMaximum, bool); itkGetConstMacro(AutoMinimumMaximum, bool); itkBooleanMacro(AutoMinimumMaximum); diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdImageFilter.hxx index 7e98d028a21640bb460337a4adf3a5b396ac7ee7..702ae6b549beaac819a8a6cf93b4df26a51e1bde 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHistogramThresholdImageFilter.hxx @@ -38,10 +38,12 @@ HistogramThresholdImageFilter<TInputImage, TOutputImage, TMaskImage> m_InsideValue = NumericTraits<OutputPixelType>::max(); m_Threshold = NumericTraits<InputPixelType>::Zero; m_MaskValue = NumericTraits<MaskPixelType>::max(); - m_Calculator = NULL; + m_Calculator = ITK_NULLPTR; m_MaskOutput = true; - if( typeid(ValueType) == typeid(signed char) || typeid(ValueType) == typeid(unsigned char) ) + if( typeid(ValueType) == typeid(signed char) + || typeid(ValueType) == typeid(unsigned char) + || typeid(ValueType) == typeid(char)) { m_AutoMinimumMaximum = false; } @@ -132,7 +134,7 @@ HistogramThresholdImageFilter<TInputImage, TOutputImage, TMaskImage> this->GraftOutput( thresholder->GetOutput() ); } m_Threshold = m_Calculator->GetThreshold(); - m_Calculator->SetInput( NULL ); + m_Calculator->SetInput( ITK_NULLPTR ); } template<typename TInputImage, typename TOutputImage, typename TMaskImage> @@ -158,12 +160,15 @@ HistogramThresholdImageFilter<TInputImage,TOutputImage,TMaskImage> << static_cast<typename NumericTraits<OutputPixelType>::PrintType>(m_OutsideValue) << std::endl; os << indent << "InsideValue: " << static_cast<typename NumericTraits<OutputPixelType>::PrintType>(m_InsideValue) << std::endl; - os << indent << "Calculator: "; - m_Calculator->Print( os, indent.GetNextIndent() ); + itkPrintSelfObjectMacro( Calculator ); + os << indent << "AutoMinimumMaximim: " << m_AutoMinimumMaximum << std::endl; os << indent << "Threshold (computed): " << static_cast<typename NumericTraits<InputPixelType>::PrintType>(m_Threshold) << std::endl; os << indent << "Mask image in use: " << (bool)(this->GetMaskImage() ) << std::endl; os << indent << "Masking of output: " << this->GetMaskOutput() << std::endl; + os << indent << "MaskValue: " << static_cast<typename NumericTraits<OutputPixelType>::PrintType>(m_MaskValue) << std::endl; + + itkPrintSelfObjectMacro(Calculator); } diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHuangThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHuangThresholdCalculator.hxx index d1ca32e5abd678b192bd0789680830ab99833b9d..9a7e17399e16a40b1eb6d0815a169549eaa156da 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHuangThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkHuangThresholdCalculator.hxx @@ -87,7 +87,7 @@ HuangThresholdCalculator<THistogram, TOutput> for( size_t i = 1; i < Smu.size(); i++) { double mu = 1. / ( 1. + static_cast< double >( i ) / C ); - Smu[i] = -mu * vcl_log( mu ) - (1. - mu) * vcl_log( 1. - mu ); + Smu[i] = -mu * std::log( mu ) - (1. - mu) * std::log( 1. - mu ); } // calculate the threshold diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkKittlerIllingworthThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkKittlerIllingworthThresholdCalculator.hxx index 7313e764799e462880b170523dd51b4ceaeaac10..50fffe933d6a73afa72da5ab3179194a1979a7c2 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkKittlerIllingworthThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkKittlerIllingworthThresholdCalculator.hxx @@ -180,7 +180,7 @@ KittlerIllingworthThresholdCalculator<THistogram, TOutput> //The terms of the quadratic equation to be solved. double w0 = 1.0/sigma2-1.0/tau2; double w1 = mu/sigma2-nu/tau2; - double w2 = (mu*mu)/sigma2 - (nu*nu)/tau2 + vcl_log10((sigma2*(q*q))/(tau2*p*p)); + double w2 = (mu*mu)/sigma2 - (nu*nu)/tau2 + std::log10((sigma2*(q*q))/(tau2*p*p)); //If the next threshold would be imaginary, return with the current one. double sqterm = (w1*w1)-w0*w2; @@ -212,7 +212,7 @@ KittlerIllingworthThresholdCalculator<THistogram, TOutput> { //The updated threshold is the integer part of the solution of the quadratic equation. Tprev = threshold; - double temp = (w1+vcl_sqrt(sqterm))/w0; + double temp = (w1+std::sqrt(sqterm))/w0; // not sure if this condition is really useful if (vnl_math_isnan(temp)) diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx index 4738352394e09f12eb6f2b67e9c74101ac2ef5ce..cc608c5a7c0b9c31f4d7231a28d7ec371618a3c4 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkLiThresholdCalculator.hxx @@ -111,7 +111,7 @@ LiThresholdCalculator<THistogram, TOutput> // //#define IS_NEG( x ) ( ( x ) < -DBL_EPSILON ) //DBL_EPSILON = 2.220446049250313E-16 - temp = ( mean_back - mean_obj ) / ( vcl_log ( mean_back ) - vcl_log ( mean_obj ) ); + temp = ( mean_back - mean_obj ) / ( std::log ( mean_back ) - std::log ( mean_obj ) ); if (temp < -2.220446049250313E-16) new_thresh = (int) (temp - 0.5); @@ -120,7 +120,7 @@ LiThresholdCalculator<THistogram, TOutput> /* Stop the iterations when the difference between the new and old threshold values is less than the tolerance */ } - while ( vcl_abs ( new_thresh - old_thresh ) > tolerance ); + while ( std::abs ( new_thresh - old_thresh ) > tolerance ); this->GetOutput()->Set( static_cast<OutputType>( histogram->GetMeasurement( histthresh, 0 ) ) ); } diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkMaximumEntropyThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkMaximumEntropyThresholdCalculator.hxx index 374c758e03eaaf42249e5b3c03d57c2e89f26a23..13407658d75e68748b8923aa5f1091c79b5ae058 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkMaximumEntropyThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkMaximumEntropyThresholdCalculator.hxx @@ -82,7 +82,7 @@ MaximumEntropyThresholdCalculator<THistogram, TOutput> first_bin=0; for (ih = 0; (unsigned)ih < size; ih++ ) { - if ( !(vcl_abs(P1[ih])<tolerance)) + if ( !(std::abs(P1[ih])<tolerance)) { first_bin = ih; break; @@ -93,7 +93,7 @@ MaximumEntropyThresholdCalculator<THistogram, TOutput> last_bin=size - 1; for (ih = size - 1; ih >= first_bin; ih-- ) { - if ( !(vcl_abs(P2[ih])<tolerance)) + if ( !(std::abs(P2[ih])<tolerance)) { last_bin = ih; break; @@ -112,7 +112,7 @@ MaximumEntropyThresholdCalculator<THistogram, TOutput> { if ( histogram->GetFrequency(ih, 0) != 0 ) { - ent_back -= ( norm_histo[ih] / P1[it] ) * vcl_log ( norm_histo[ih] / P1[it] ); + ent_back -= ( norm_histo[ih] / P1[it] ) * std::log ( norm_histo[ih] / P1[it] ); } } @@ -122,7 +122,7 @@ MaximumEntropyThresholdCalculator<THistogram, TOutput> { if (histogram->GetFrequency(ih, 0) != 0) { - ent_obj -= ( norm_histo[ih] / P2[it] ) * vcl_log ( norm_histo[ih] / P2[it] ); + ent_obj -= ( norm_histo[ih] / P2[it] ) * std::log ( norm_histo[ih] / P2[it] ); } } diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkMomentsThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkMomentsThresholdCalculator.hxx index c518d0ce814158d9a4b4c9b6a3c1b7694dfd1739..63da1090e2cbb1de2339d40685d29e0a782553e3 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkMomentsThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkMomentsThresholdCalculator.hxx @@ -74,8 +74,8 @@ MomentsThresholdCalculator<THistogram, TOutput> cd = m0 * m2 - m1 * m1; c0 = ( -m2 * m2 + m1 * m3 ) / cd; c1 = ( m0 * -m3 + m2 * m1 ) / cd; - z0 = 0.5 * ( -c1 - vcl_sqrt ( c1 * c1 - 4.0 * c0 ) ); - z1 = 0.5 * ( -c1 + vcl_sqrt ( c1 * c1 - 4.0 * c0 ) ); + z0 = 0.5 * ( -c1 - std::sqrt ( c1 * c1 - 4.0 * c0 ) ); + z1 = 0.5 * ( -c1 + std::sqrt ( c1 * c1 - 4.0 * c0 ) ); p0 = ( z1 - m1 ) / ( z1 - z0 ); /* Fraction of the object pixels in the target binary image */ // The threshold is the gray-level closest diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuMultipleThresholdsCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuMultipleThresholdsCalculator.hxx index fbf7c334c4afc8570dcedff911643a3640e0f80d..b83b72596aebeba065da68c01780f470ed8a4e71 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuMultipleThresholdsCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuMultipleThresholdsCalculator.hxx @@ -18,6 +18,7 @@ #ifndef __itkOtsuMultipleThresholdsCalculator_hxx #define __itkOtsuMultipleThresholdsCalculator_hxx +#include "itkMath.h" #include "itkOtsuMultipleThresholdsCalculator.h" namespace itk @@ -53,11 +54,8 @@ OtsuMultipleThresholdsCalculator< TInputHistogram > { typename TInputHistogram::ConstPointer histogram = this->GetInputHistogram(); - SizeValueType numberOfHistogramBins = histogram->Size(); - SizeValueType numberOfClasses = classMean.size(); - - MeanType meanOld; - FrequencyType freqOld; + const SizeValueType numberOfHistogramBins = histogram->Size(); + const SizeValueType numberOfClasses = classMean.size(); unsigned int k; int j; @@ -73,8 +71,8 @@ OtsuMultipleThresholdsCalculator< TInputHistogram > // threshold ++thresholdIndexes[j]; - meanOld = classMean[j]; - freqOld = classFrequency[j]; + const MeanType meanOld = classMean[j]; + const FrequencyType freqOld = classFrequency[j]; classFrequency[j] += histogram->GetFrequency(thresholdIndexes[j]); @@ -165,7 +163,7 @@ OtsuMultipleThresholdsCalculator< TInputHistogram > typename TInputHistogram::ConstIterator end = histogram->End(); MeanType globalMean = NumericTraits< MeanType >::Zero; - FrequencyType globalFrequency = histogram->GetTotalFrequency(); + const FrequencyType globalFrequency = histogram->GetTotalFrequency(); while ( iter != end ) { globalMean += static_cast< MeanType >( iter.GetMeasurementVector()[0] ) @@ -232,12 +230,29 @@ OtsuMultipleThresholdsCalculator< TInputHistogram > classMean[numberOfClasses - 1] = NumericTraits< MeanType >::Zero; } + // + // The "volatile" modifier is used here for preventing the variable from + // being kept in 80 bit FPU registers when using 32-bit x86 processors with + // SSE instructions disabled. A case that arised in the Debian 32-bits + // distribution. + // +#ifndef ITK_COMPILER_SUPPORTS_SSE2_32 + volatile VarianceType maxVarBetween = NumericTraits< VarianceType >::Zero; +#else VarianceType maxVarBetween = NumericTraits< VarianceType >::Zero; +#endif + // + // The introduction of the "volatile" modifier forces the compiler to keep + // the variable in memory and therefore store it in the IEEE float/double + // format. In this way making numerical results consistent across platforms. + // + for ( j = 0; j < numberOfClasses; j++ ) { - maxVarBetween += (static_cast< VarianceType >( classFrequency[j] ) / static_cast< VarianceType >( globalFrequency )) + maxVarBetween += (static_cast< VarianceType >( classFrequency[j] )) * static_cast< VarianceType >( ( classMean[j] ) * ( classMean[j] ) ); } + maxVarBetween /= static_cast< VarianceType >( globalFrequency ); // Sum the relevant weights for valley emphasis WeightType valleyEmphasisFactor = NumericTraits< WeightType >::Zero; @@ -255,7 +270,24 @@ OtsuMultipleThresholdsCalculator< TInputHistogram > // yields maximum between-class variance while ( Self::IncrementThresholds(thresholdIndexes, globalMean, classMean, classFrequency) ) { + + // + // The "volatile" modifier is used here for preventing the variable from + // being kept in 80 bit FPU registers when using 32-bit x86 processors with + // SSE instructions disabled. A case that arised in the Debian 32-bits + // distribution. + // +#ifndef ITK_COMPILER_SUPPORTS_SSE2_32 + volatile VarianceType varBetween = NumericTraits< VarianceType >::Zero; +#else VarianceType varBetween = NumericTraits< VarianceType >::Zero; +#endif + // + // The introduction of the "volatile" modifier forces the compiler to keep + // the variable in memory and therefore store it in the IEEE float/double + // format. In this way making numerical results consistent across platforms. + // + for ( j = 0; j < numberOfClasses; j++ ) { // The true between-class variance \sigma_B^2 for any number of classes is defined as: @@ -270,9 +302,10 @@ OtsuMultipleThresholdsCalculator< TInputHistogram > // Since we are looking for the argmax, the second term can be ignored because it is a constant, leading to the simpler // (\sum_{k=1}^{M} \omega_k \mu_k^2), which is what is implemented here. // Although this is no longer truly a "between class variance", we keep that name since it is only different by a constant. - varBetween += (static_cast< VarianceType >( classFrequency[j] ) / static_cast< VarianceType >( globalFrequency )) + varBetween += (static_cast< VarianceType >( classFrequency[j] )) * static_cast< VarianceType >( ( classMean[j] ) * ( classMean[j] ) ); } + varBetween /= static_cast< VarianceType >( globalFrequency ); if (m_ValleyEmphasis) { @@ -286,7 +319,9 @@ OtsuMultipleThresholdsCalculator< TInputHistogram > varBetween = varBetween * valleyEmphasisFactor; } - if ( varBetween > maxVarBetween ) + const unsigned int maxUlps = 1; + if ( varBetween > maxVarBetween && + !Math::FloatAlmostEqual( maxVarBetween, varBetween, maxUlps) ) { maxVarBetween = varBetween; maxVarThresholdIndexes = thresholdIndexes; diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuThresholdCalculator.h b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuThresholdCalculator.h index d776f8a9f0badf63adab7e480ff1ca8431a8fd2c..8ef8478d180335ec2dec04197e3968b53ef78f7f 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuThresholdCalculator.h +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuThresholdCalculator.h @@ -72,6 +72,7 @@ protected: m_OtsuMultipleThresholdsCalculator = OtsuMultipleThresholdsCalculator<THistogram>::New(); } virtual ~OtsuThresholdCalculator() {}; + void PrintSelf(std::ostream & os, Indent indent) const; void GenerateData(void); private: diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuThresholdCalculator.hxx index db135a1b42f1dd97d9b3f978254e61779b7f77af..176320bc96a7c71060c4ee3753c967e25cc7d45b 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkOtsuThresholdCalculator.hxx @@ -36,6 +36,18 @@ OtsuThresholdCalculator< THistogram, TOutput > this->GetOutput()->Set( static_cast<OutputType>( m_OtsuMultipleThresholdsCalculator->GetOutput()[0] ) ); this->UpdateProgress(1.0); } + + +template< typename THistogram, typename TOutput > +void +OtsuThresholdCalculator< THistogram, TOutput > +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + itkPrintSelfObjectMacro(OtsuMultipleThresholdsCalculator); +} + } // end namespace itk #endif diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkRenyiEntropyThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkRenyiEntropyThresholdCalculator.hxx index c7c2ea87e8604e3a512ac94cc96e1cd7ccca26e1..9aa5dba42c069422516da50d3478cfa039dfb39a 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkRenyiEntropyThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkRenyiEntropyThresholdCalculator.hxx @@ -73,7 +73,7 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> m_FirstBin=0; for(ih = 0; ih < m_Size; ih++ ) { - if( !( vcl_abs( P1[ih] ) < tolerance ) ) + if( !( std::abs( P1[ih] ) < tolerance ) ) { m_FirstBin = ih; break; @@ -84,7 +84,7 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> m_LastBin = static_cast< InstanceIdentifier >( m_Size - 1 ); for(ih = m_Size - 1; ih >= m_FirstBin; ih-- ) { - if( !( vcl_abs( P2[ih] ) < tolerance ) ) + if( !( std::abs( P2[ih] ) < tolerance ) ) { m_LastBin = ih; break; @@ -123,9 +123,9 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> // Adjust beta values // note t_star1, t_star2, t_star3 are unsigned - if( vcl_abs( static_cast< double >( t_star1 ) - static_cast< double >( t_star2 ) ) <= 5. ) + if( std::abs( static_cast< double >( t_star1 ) - static_cast< double >( t_star2 ) ) <= 5. ) { - if( vcl_abs( static_cast< double >( t_star2 ) - static_cast< double >( t_star3 ) ) <= 5. ) + if( std::abs( static_cast< double >( t_star2 ) - static_cast< double >( t_star3 ) ) <= 5. ) { beta1 = 1.; beta2 = 2.; @@ -140,7 +140,7 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> } else { - if( vcl_abs( static_cast< double >( t_star2 ) - static_cast< double >( t_star3 ) ) <= 5. ) + if( std::abs( static_cast< double >( t_star2 ) - static_cast< double >( t_star3 ) ) <= 5. ) { beta1 = 3.; beta2 = 1.; @@ -194,7 +194,7 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> if( histogram->GetFrequency(ih, 0) != NumericTraits< AbsoluteFrequencyType >::Zero ) { double x = ( normHisto[ih] / P1[it] ); - ent_back -= x * vcl_log ( x ); + ent_back -= x * std::log ( x ); } } @@ -205,7 +205,7 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> if( histogram->GetFrequency(ih, 0) != NumericTraits< AbsoluteFrequencyType >::Zero ) { double x = ( normHisto[ih] / P2[it] ); - ent_obj -= x * vcl_log( x ); + ent_obj -= x * std::log( x ); } } @@ -243,14 +243,14 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> double ent_back = 0.0; for( InstanceIdentifier ih = 0; ih <= it; ih++ ) { - ent_back += vcl_sqrt( normHisto[ih] / P1[it] ); + ent_back += std::sqrt( normHisto[ih] / P1[it] ); } /* Entropy of the object pixels */ double ent_obj = 0.0; for( InstanceIdentifier ih = it + 1; ih < m_Size; ih++ ) { - ent_obj += vcl_sqrt( normHisto[ih] / P2[it] ); + ent_obj += std::sqrt( normHisto[ih] / P2[it] ); } /* Total entropy */ @@ -259,7 +259,7 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> if( product > 0.0 ) { - tot_ent = term * vcl_log( ent_back * ent_obj ); + tot_ent = term * std::log( ent_back * ent_obj ); } if( tot_ent > max_ent ) @@ -307,7 +307,7 @@ RenyiEntropyThresholdCalculator<THistogram, TOutput> double product = ent_back * ent_obj; if( product > 0.0 ) { - tot_ent = term * vcl_log( product ); + tot_ent = term * std::log( product ); } if( tot_ent > max_ent ) diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkShanbhagThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkShanbhagThresholdCalculator.hxx index f27a3ef1227ce423b15028171a56dea42d7bbd8c..e8ea6f927bc6aa9e7f256b60f1add84ba1ae9ee0 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkShanbhagThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkShanbhagThresholdCalculator.hxx @@ -78,7 +78,7 @@ ShanbhagThresholdCalculator<THistogram, TOutput> first_bin=0; for (ih = 0; (unsigned)ih < size; ih++ ) { - if ( !(vcl_abs(P1[ih])<tolerance)) + if ( !(std::abs(P1[ih])<tolerance)) { first_bin = ih; break; @@ -89,7 +89,7 @@ ShanbhagThresholdCalculator<THistogram, TOutput> last_bin=size - 1; for (ih = size - 1; ih >= first_bin; ih-- ) { - if ( !(vcl_abs(P2[ih])<tolerance)) + if ( !(std::abs(P2[ih])<tolerance)) { last_bin = ih; break; @@ -108,7 +108,7 @@ ShanbhagThresholdCalculator<THistogram, TOutput> term = 0.5 / P1[it]; for ( ih = 1; ih <= it; ih++ ) { //0+1? - ent_back -= norm_histo[ih] * vcl_log ( 1.0 - term * P1[ih - 1] ); + ent_back -= norm_histo[ih] * std::log ( 1.0 - term * P1[ih - 1] ); } ent_back *= term; @@ -117,12 +117,12 @@ ShanbhagThresholdCalculator<THistogram, TOutput> term = 0.5 / P2[it]; for ( ih = it + 1; (unsigned)ih < size; ih++ ) { - ent_obj -= norm_histo[ih] * vcl_log ( 1.0 - term * P2[ih] ); + ent_obj -= norm_histo[ih] * std::log ( 1.0 - term * P2[ih] ); } ent_obj *= term; /* Total entropy */ - tot_ent = vcl_abs ( ent_back - ent_obj ); + tot_ent = std::abs ( ent_back - ent_obj ); if ( tot_ent < min_ent ) { diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkThresholdImageFilter.h b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkThresholdImageFilter.h index be13b7f00de58556c2527b2e011363ba8fd9f2ab..09c0014c61f4a05911ed7ef64507535e94cca307 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkThresholdImageFilter.h +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkThresholdImageFilter.h @@ -42,6 +42,21 @@ namespace itk * value (by default, "black") if the image values are below, above, or * between simple threshold values. * + * The available methods are: + * + * ThresholdAbove(): + * The values greater than the threshold value are set to OutsideValue + * + * ThresholdBelow(): + * The values less than the threshold value are set to OutsideValue + * + * ThresholdOutside(): + * The values outside the threshold range (less than lower or greater + * than upper) are set to OutsideValue + * + * Note that these definitions indicate that pixels equal to the threshold + * value are not set to OutsideValue in any of these methods + * * The pixels must support the operators >= and <=. * * \ingroup IntensityImageFilters MultiThreaded diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkThresholdImageFilter.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkThresholdImageFilter.hxx index a0101c666f7d9e310ea8a42493d63af5576156f8..a920e86c7f26a935a6d138487394c02377fce603 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkThresholdImageFilter.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkThresholdImageFilter.hxx @@ -71,7 +71,7 @@ ThresholdImageFilter< TImage > } /** - * The values greater than or equal to the value are set to OutsideValue + * The values greater than the threshold value are set to OutsideValue */ template< typename TImage > void @@ -88,7 +88,7 @@ ThresholdImageFilter< TImage > } /** - * The values less than or equal to the value are set to OutsideValue + * The values less than the threshold value are set to OutsideValue */ template< typename TImage > void @@ -104,7 +104,7 @@ ThresholdImageFilter< TImage > } /** - * The values outside the range are set to OutsideValue + * The values outside the threshold range (less than lower or greater than upper) are set to OutsideValue */ template< typename TImage > void diff --git a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkYenThresholdCalculator.hxx b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkYenThresholdCalculator.hxx index 9781534664beb3688454c3b7b22c6316042d9c9a..6ff54998909aee25cb142fbeb2797995bc2fc75f 100644 --- a/Utilities/ITK/Modules/Filtering/Thresholding/include/itkYenThresholdCalculator.hxx +++ b/Utilities/ITK/Modules/Filtering/Thresholding/include/itkYenThresholdCalculator.hxx @@ -86,7 +86,7 @@ YenThresholdCalculator<THistogram, TOutput> max_crit = itk::NumericTraits<double>::NonpositiveMin(); for ( it = 0; (unsigned)it < size; it++ ) { - crit = -1.0 * (( P1_sq[it] * P2_sq[it] )> 0.0? vcl_log( P1_sq[it] * P2_sq[it]):0.0) + 2 * ( ( P1[it] * ( 1.0 - P1[it] ) )>0.0? vcl_log( P1[it] * ( 1.0 - P1[it] ) ): 0.0); + crit = -1.0 * (( P1_sq[it] * P2_sq[it] )> 0.0? std::log( P1_sq[it] * P2_sq[it]):0.0) + 2 * ( ( P1[it] * ( 1.0 - P1[it] ) )>0.0? std::log( P1[it] * ( 1.0 - P1[it] ) ): 0.0); if ( crit > max_crit ) { max_crit = crit; diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkArchetypeSeriesFileNames.h b/Utilities/ITK/Modules/IO/ImageBase/include/itkArchetypeSeriesFileNames.h index beea164dd6bea2e5da3465bdb47d821d59646312..8b948bcb5c510713d2fdb388d90cd4dee54b3673 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkArchetypeSeriesFileNames.h +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkArchetypeSeriesFileNames.h @@ -104,7 +104,7 @@ public: protected: ArchetypeSeriesFileNames(); ~ArchetypeSeriesFileNames() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Method that actually does the archetype matching/grouping */ void Scan(); diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileReader.hxx b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileReader.hxx index a4b4e241f49b1054cc815d379dde4438c3441644..f436c9bbda5838aea04bcc888bb41727fb81cc29 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileReader.hxx +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileReader.hxx @@ -34,7 +34,7 @@ template< typename TOutputImage, typename ConvertPixelTraits > ImageFileReader< TOutputImage, ConvertPixelTraits > ::ImageFileReader() { - m_ImageIO = 0; + m_ImageIO = ITK_NULLPTR; this->SetFileName(""); m_UserSpecifiedImageIO = false; m_UseStreaming = true; @@ -51,15 +51,7 @@ void ImageFileReader< TOutputImage, ConvertPixelTraits > { Superclass::PrintSelf(os, indent); - if ( m_ImageIO ) - { - os << indent << "ImageIO: \n"; - m_ImageIO->Print( os, indent.GetNextIndent() ); - } - else - { - os << indent << "ImageIO: (null)" << "\n"; - } + itkPrintSelfObjectMacro( ImageIO ); os << indent << "UserSpecifiedImageIO flag: " << m_UserSpecifiedImageIO << "\n"; os << indent << "m_UseStreaming: " << m_UseStreaming << "\n"; @@ -120,7 +112,7 @@ ImageFileReader< TOutputImage, ConvertPixelTraits > if ( m_ImageIO.IsNull() ) { std::ostringstream msg; - msg << " Could not create IO object for file " + msg << " Could not create IO object for reading file " << this->GetFileName().c_str() << std::endl; if ( m_ExceptionMessage.size() ) { @@ -128,17 +120,25 @@ ImageFileReader< TOutputImage, ConvertPixelTraits > } else { - msg << " Tried to create one of the following:" << std::endl; std::list< LightObject::Pointer > allobjects = ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); - for ( std::list< LightObject::Pointer >::iterator i = allobjects.begin(); - i != allobjects.end(); ++i ) + if (allobjects.size() > 0) + { + msg << " Tried to create one of the following:" << std::endl; + for ( std::list< LightObject::Pointer >::iterator i = allobjects.begin(); + i != allobjects.end(); ++i ) + { + ImageIOBase *io = dynamic_cast< ImageIOBase * >( i->GetPointer() ); + msg << " " << io->GetNameOfClass() << std::endl; + } + msg << " You probably failed to set a file suffix, or" << std::endl; + msg << " set the suffix to an unsupported type." << std::endl; + } + else { - ImageIOBase *io = dynamic_cast< ImageIOBase * >( i->GetPointer() ); - msg << " " << io->GetNameOfClass() << std::endl; + msg << " There are no registered IO factories." << std::endl; + msg << " Please visit http://www.itk.org/Wiki/ITK/FAQ#NoFactoryException to diagnose the problem." << std::endl; } - msg << " You probably failed to set a file suffix, or" << std::endl; - msg << " set the suffix to an unsupported type." << std::endl; } ImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; @@ -382,7 +382,7 @@ void ImageFileReader< TOutputImage, ConvertPixelTraits > itkDebugMacro (<< "Setting imageIO IORegion to: " << m_ActualIORegion); m_ImageIO->SetIORegion(m_ActualIORegion); - char *loadBuffer = 0; + char *loadBuffer = ITK_NULLPTR; // the size of the buffer is computed based on the actual number of // pixels to be read and the actual size of the pixels to be read // (as opposed to the sizes of the output) @@ -452,7 +452,7 @@ void ImageFileReader< TOutputImage, ConvertPixelTraits > // clean up delete[] loadBuffer; - loadBuffer = 0; + loadBuffer = ITK_NULLPTR; // then rethrow throw; @@ -460,7 +460,7 @@ void ImageFileReader< TOutputImage, ConvertPixelTraits > // clean up delete[] loadBuffer; - loadBuffer = 0; + loadBuffer = ITK_NULLPTR; } template< typename TOutputImage, typename ConvertPixelTraits > diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileWriter.h b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileWriter.h index 7e5663de059af25ec321aa48b8088c33e59280c2..20e89451181602c52d6008aa2eb1aedf670b2b85 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileWriter.h +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileWriter.h @@ -161,7 +161,7 @@ public: /** Aliased to the Write() method to be consistent with the rest of the * pipeline. */ - virtual void Update() + virtual void Update() ITK_OVERRIDE { this->Write(); } @@ -171,7 +171,7 @@ public: * Updates the pipeline, streaming it the NumberOfStreamDivisions times. * Existing PasteIORegion is reset. */ - virtual void UpdateLargestPossibleRegion() + virtual void UpdateLargestPossibleRegion() ITK_OVERRIDE { m_PasteIORegion = ImageIORegion(TInputImage::ImageDimension); m_UserSpecifiedIORegion = false; @@ -196,10 +196,10 @@ public: protected: ImageFileWriter(); ~ImageFileWriter(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Does the real work. */ - void GenerateData(void); + virtual void GenerateData(void) ITK_OVERRIDE; private: ImageFileWriter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileWriter.hxx b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileWriter.hxx index 325479b81c833402564d37be61cf7e2ebda053a1..c161c151ccfe33585623031801a26b6d2e41650e 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileWriter.hxx +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageFileWriter.hxx @@ -111,7 +111,7 @@ ImageFileWriter< TInputImage > itkDebugMacro(<< "Writing an image file"); // Make sure input is available - if ( input == 0 ) + if ( input == ITK_NULLPTR ) { itkExceptionMacro(<< "No input to writer!"); } @@ -150,21 +150,27 @@ ImageFileWriter< TInputImage > { ImageFileWriterException e(__FILE__, __LINE__); std::ostringstream msg; - msg << " Could not create IO object for file " + std::list< LightObject::Pointer > allobjects = + ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); + msg << " Could not create IO object for writing file " << m_FileName.c_str() << std::endl; - msg << " Tried to create one of the following:" << std::endl; + if (allobjects.size() > 0) { - std::list< LightObject::Pointer > allobjects = - ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); + msg << " Tried to create one of the following:" << std::endl; for ( std::list< LightObject::Pointer >::iterator i = allobjects.begin(); i != allobjects.end(); ++i ) { ImageIOBase *io = dynamic_cast< ImageIOBase * >( i->GetPointer() ); msg << " " << io->GetNameOfClass() << std::endl; } + msg << " You probably failed to set a file suffix, or" << std::endl; + msg << " set the suffix to an unsupported type." << std::endl; + } + else + { + msg << " There are no registered IO factories." << std::endl; + msg << " Please visit http://www.itk.org/Wiki/ITK/FAQ#NoFactoryException to diagnose the problem." << std::endl; } - msg << " You probably failed to set a file suffix, or" << std::endl; - msg << " set the suffix to an unsupported type." << std::endl; e.SetDescription( msg.str().c_str() ); e.SetLocation(ITK_LOCATION); throw e; @@ -237,14 +243,14 @@ ImageFileWriter< TInputImage > if ( strcmp(input->GetNameOfClass(), "VectorImage") == 0 ) { typedef typename InputImageType::InternalPixelType VectorImageScalarType; - m_ImageIO->SetPixelTypeInfo(static_cast<const VectorImageScalarType *>(0)); + m_ImageIO->SetPixelTypeInfo(static_cast<const VectorImageScalarType *>(ITK_NULLPTR)); typedef typename InputImageType::AccessorFunctorType AccessorFunctorType; m_ImageIO->SetNumberOfComponents( AccessorFunctorType::GetVectorLength(input) ); } else { // Set the pixel and component type; the number of components. - m_ImageIO->SetPixelTypeInfo(static_cast<const InputImagePixelType *>(0)); + m_ImageIO->SetPixelTypeInfo(static_cast<const InputImagePixelType *>(ITK_NULLPTR)); } // Setup the image IO for writing. diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageIOBase.h b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageIOBase.h index 3d38e08aa57170b2362ae596d9b01d50c049c494..c90355d9a3167c8152b48e914f6908e5c81deb38 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageIOBase.h +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageIOBase.h @@ -33,7 +33,9 @@ #include "itkImageRegionSplitterBase.h" #include "vnl/vnl_vector.h" +#include "vcl_compiler.h" +#include <fstream> #include <string> namespace itk @@ -523,7 +525,7 @@ public: protected: ImageIOBase(); ~ImageIOBase(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; virtual const ImageRegionSplitterBase* GetImageRegionSplitter(void) const; @@ -613,6 +615,38 @@ protected: * next slice. Returns m_Strides[3]. */ SizeType GetSliceStride() const; + /** \brief Opens a file for reading and random access + * + * \param[out] inputStream is an istream presumed to be opened for reading + * \param[in] filename is the name of the file + * \param[in] ascii optional (default is false); + * if true than the file will be opened in ASCII mode, + * which generally only applies to Windows + * + * The stream is closed if it's already opened. If an error is + * encountered than an exception will be thrown. + */ + virtual void OpenFileForReading(std::ifstream & inputStream, const std::string & filename, + bool ascii = false); + + /** \brief Opens a file for writing and random access + * + * \param[out] outputStream is an ostream presumed to be opened for writing + * \param[in] filename is the name of the file + * \param[in] truncate optional (default is true); + * if true than the file's existing content is truncated, + * if false than the file is opened for reading and + * writing with existing content intact + * \param[in] ascii optional (default is false); + * if true than the file will be opened in ASCII mode, + * which generally only applies to Windows + * + * The stream is closed if it's already opened. If an error is + * encountered than an exception will be thrown. + */ + virtual void OpenFileForWriting(std::ofstream & outputStream, const std::string & filename, + bool truncate = true, bool ascii = false); + /** Convenient method to write a buffer as ASCII text. */ virtual void WriteBufferAsASCII(std::ostream & os, const void *buffer, IOComponentType ctype, @@ -657,6 +691,10 @@ private: static const IOComponentType CType = ctype; \ } +// the following typemaps are not platform independent +#if VCL_CHAR_IS_SIGNED +IMAGEIOBASE_TYPEMAP(signed char, CHAR); +#endif // VCL_CHAR_IS_SIGNED IMAGEIOBASE_TYPEMAP(char, CHAR); IMAGEIOBASE_TYPEMAP(unsigned char, UCHAR); IMAGEIOBASE_TYPEMAP(short, SHORT); diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesReader.h b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesReader.h index 1ae22aafe54f8ae71be57752c0df95148d841195..c4d62f0d026dd632af19c012221982a3d5c4f985 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesReader.h +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesReader.h @@ -155,8 +155,13 @@ public: itkBooleanMacro(UseStreaming); protected: - ImageSeriesReader():m_ImageIO(0), m_ReverseOrder(false), - m_UseStreaming(true), m_MetaDataDictionaryArrayUpdate(true) {} + ImageSeriesReader() : + m_ImageIO(ITK_NULLPTR), + m_ReverseOrder(false), + m_NumberOfDimensionsInImage(0), + m_UseStreaming(true), + m_MetaDataDictionaryArrayUpdate(true) + {} ~ImageSeriesReader(); void PrintSelf(std::ostream & os, Indent indent) const; diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesReader.hxx b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesReader.hxx index 4d67169ea9d9ceb18f7ff8baed41eb906e39e7a9..991b717d6a138cfef14b4f1a51dc6e5d19e9e97a 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesReader.hxx +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesReader.hxx @@ -55,15 +55,7 @@ void ImageSeriesReader< TOutputImage > os << indent << "ReverseOrder: " << m_ReverseOrder << std::endl; os << indent << "UseStreaming: " << m_UseStreaming << std::endl; - if ( m_ImageIO ) - { - os << indent << "ImageIO: \n"; - m_ImageIO->Print( os, indent.GetNextIndent() ); - } - else - { - os << indent << "ImageIO: (null)" << "\n"; - } + itkPrintSelfObjectMacro( ImageIO ); os << indent << "MetaDataDictionaryArrayMTime: " << m_MetaDataDictionaryArrayMTime << std::endl; os << indent << "MetaDataDictionaryArrayUpdate: " << m_MetaDataDictionaryArrayUpdate << std::endl; @@ -231,7 +223,7 @@ void ImageSeriesReader< TOutputImage > { interSliceSpacing += vnl_math_sqr(position2[j] - position1[j]); } - interSliceSpacing = static_cast< float >( vcl_sqrt(interSliceSpacing) ); + interSliceSpacing = static_cast< float >( std::sqrt(interSliceSpacing) ); if ( interSliceSpacing == 0.0f ) { diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesWriter.h b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesWriter.h index 85bcaad07722140065fec4276e9a27bd69e56386..544e4f299274e515585a01310775df81c4d55ac9 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesWriter.h +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesWriter.h @@ -133,7 +133,7 @@ public: /** Aliased to the Write() method to be consistent with the rest of the * pipeline. */ - virtual void Update() + virtual void Update() ITK_OVERRIDE { this->Write(); } @@ -200,10 +200,10 @@ public: protected: ImageSeriesWriter(); ~ImageSeriesWriter(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Does the real work. */ - void GenerateData(void); + virtual void GenerateData(void) ITK_OVERRIDE; /** Transition method used for DEPRECATING old functionality. * This method should be removed after release ITK 1.8 */ diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesWriter.hxx b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesWriter.hxx index 5353669344cde0493029cd9b5e5004eacfb2a507..092ab0ab1c1a670eb6de79b479914092e0c89911 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesWriter.hxx +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkImageSeriesWriter.hxx @@ -34,9 +34,9 @@ namespace itk template< typename TInputImage, typename TOutputImage > ImageSeriesWriter< TInputImage, TOutputImage > ::ImageSeriesWriter(): - m_ImageIO(0), m_UserSpecifiedImageIO(false), + m_ImageIO(ITK_NULLPTR), m_UserSpecifiedImageIO(false), m_SeriesFormat("%d"), - m_StartIndex(1), m_IncrementIndex(1), m_MetaDataDictionaryArray(NULL) + m_StartIndex(1), m_IncrementIndex(1), m_MetaDataDictionaryArray(ITK_NULLPTR) { m_UseCompression = false; } @@ -87,7 +87,7 @@ ImageSeriesWriter< TInputImage, TOutputImage > itkDebugMacro(<< "Writing an image file"); // Make sure input is available - if ( inputImage == 0 ) + if ( inputImage == ITK_NULLPTR ) { itkExceptionMacro(<< "No input to writer!"); } diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkNumericSeriesFileNames.h b/Utilities/ITK/Modules/IO/ImageBase/include/itkNumericSeriesFileNames.h index f0c20aa247992409d2ae6e962259405a6b138691..a278beea9facedce10fe56250ad89b522bbe37cd 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkNumericSeriesFileNames.h +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkNumericSeriesFileNames.h @@ -96,7 +96,7 @@ public: protected: NumericSeriesFileNames(); ~NumericSeriesFileNames() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: NumericSeriesFileNames(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkRegularExpressionSeriesFileNames.h b/Utilities/ITK/Modules/IO/ImageBase/include/itkRegularExpressionSeriesFileNames.h index 8451d6e4b672c7b11859423e703657f386204005..00cb859848ed03de36b23998c08da2d7e3c693b9 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkRegularExpressionSeriesFileNames.h +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkRegularExpressionSeriesFileNames.h @@ -115,7 +115,7 @@ protected: m_RegularExpression(".*\\.([0-9]+)") {} ~RegularExpressionSeriesFileNames() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: RegularExpressionSeriesFileNames(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/IO/ImageBase/include/itkStreamingImageIOBase.h b/Utilities/ITK/Modules/IO/ImageBase/include/itkStreamingImageIOBase.h index ffab139180e932f3ade3823135ec6b2d49944b4a..601fc05d44f1b79d937fc3ccfbb749fe7ca2a407 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/include/itkStreamingImageIOBase.h +++ b/Utilities/ITK/Modules/IO/ImageBase/include/itkStreamingImageIOBase.h @@ -63,18 +63,18 @@ public: // see super class for documentation // // overidden to return true - virtual bool CanStreamWrite(void); + virtual bool CanStreamWrite(void) ITK_OVERRIDE; // see super class for documentation // // overidden to return true - virtual bool CanStreamRead(void); + virtual bool CanStreamRead(void) ITK_OVERRIDE; // see super class for documentation // // If UseStreamedReading is true, then returned region is the // requested region parameter. - virtual ImageIORegion GenerateStreamableReadRegionFromRequestedRegion(const ImageIORegion & requested) const; + virtual ImageIORegion GenerateStreamableReadRegionFromRequestedRegion(const ImageIORegion & requested) const ITK_OVERRIDE; // see super class for documentation // @@ -82,12 +82,12 @@ public: // GetActualNumberOfSplitsForWritingCanStreamWrite virtual unsigned int GetActualNumberOfSplitsForWriting(unsigned int numberOfRequestedSplits, const ImageIORegion & pasteRegion, - const ImageIORegion & largestPossibleRegion); + const ImageIORegion & largestPossibleRegion) ITK_OVERRIDE; protected: StreamingImageIOBase(); // virtual ~StreamingImageIOBase(); not needed - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** \brief Returns true if GetIORegion is not the same size as the * largest region give by GetNumberOfDimensions. @@ -152,24 +152,6 @@ protected: */ virtual SizeType GetDataPosition(void) const { return this->GetHeaderSize(); } - /** \brief Opens a file for reading and random access - * - * The stream is closed if it's already opened. If an error is - * encountered then an exception will be thrown. - */ - virtual void OpenFileForReading(std::ifstream & os, const char *filename); - - /** \brief Opens a file for writing and random access - * - * \param os is an ostream presumed to be opened for writing - * \param filename is the name of the file - * \param truncate if true then the file is truncated - * - * The stream is closed if it's already opened. If an error is - * encountered then an exception will be thrown. - */ - virtual void OpenFileForWriting(std::ofstream & os, const char *filename, bool truncate); - private: StreamingImageIOBase(const Self &); //purposely not implemented void operator=(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/IO/ImageBase/src/itkImageIOBase.cxx b/Utilities/ITK/Modules/IO/ImageBase/src/itkImageIOBase.cxx index b4c543f815944a980c045af2dd8cf1a246fc05f7..ae10e65dee1ecff0579d9ba43db9118c4466eec7 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/src/itkImageIOBase.cxx +++ b/Utilities/ITK/Modules/IO/ImageBase/src/itkImageIOBase.cxx @@ -21,6 +21,8 @@ #include "itkSimpleFastMutexLock.h" #include "itkMutexLockHolder.h" +#include "itksys/SystemTools.hxx" + namespace itk { ImageIOBase::ImageIOBase(): @@ -78,7 +80,7 @@ void ImageIOBase::Resize(const unsigned int numDimensions, const unsigned int *dimensions) { m_NumberOfDimensions = numDimensions; - if ( dimensions != NULL ) + if ( dimensions != ITK_NULLPTR ) { for ( unsigned int i = 0; i < m_NumberOfDimensions; i++ ) { @@ -162,7 +164,8 @@ void ImageIOBase::SetDirection(unsigned int i, const vnl_vector< double > & dire this->Modified(); std::vector< double > v; v.resize( m_Direction.size() ); - for ( unsigned int j = 0; j < v.size(); j++ ) + // Note: direction.size() <= v.size(). + for ( unsigned int j = 0; j < direction.size(); j++ ) { v[j] = direction[j]; } @@ -197,7 +200,6 @@ const std::type_info & ImageIOBase::GetComponentTypeInfo() const default: itkExceptionMacro ("Unknown component type: " << m_ComponentType); } - return typeid( ImageIOBase::UnknownType ); } void ImageIOBase::ComputeStrides() @@ -331,7 +333,6 @@ unsigned int ImageIOBase::GetPixelSize() const { itkExceptionMacro ("Unknown pixel or component type: (" << m_PixelType << ", " << m_ComponentType << ")"); - return 0; } return this->GetComponentSize() * this->GetNumberOfComponents(); @@ -365,8 +366,6 @@ unsigned int ImageIOBase::GetComponentSize() const default: itkExceptionMacro ("Unknown component type: " << m_ComponentType); } - - return 0; } std::string ImageIOBase::GetFileTypeAsString(FileType t) const @@ -556,6 +555,94 @@ ImageIOBase::IOPixelType ImageIOBase::GetPixelTypeFromString(const std::string & } } +void ImageIOBase::OpenFileForReading(std::ifstream & inputStream, const std::string & filename, + bool ascii) +{ + // Make sure that we have a file to + if ( filename.empty() ) + { + itkExceptionMacro( << "A FileName must be specified." ); + } + + // Close file from any previous image + if ( inputStream.is_open() ) + { + inputStream.close(); + } + + // Open the new file for reading + itkDebugMacro( << "Opening file for reading: " << filename ); + + std::ios::openmode mode = std::ios::in; + if ( !ascii ) + { + mode |= std::ios::binary; + } + + inputStream.open( filename.c_str(), mode ); + + if ( !inputStream.is_open() || inputStream.fail() ) + { + itkExceptionMacro( << "Could not open file: " + << filename << " for reading." + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError() ); + } +} + +void ImageIOBase::OpenFileForWriting(std::ofstream & outputStream, const std::string & filename, + bool truncate, bool ascii) +{ + // Make sure that we have a file to + if ( filename.empty() ) + { + itkExceptionMacro( << "A FileName must be specified." ); + } + + // Close file from any previous image + if ( outputStream.is_open() ) + { + outputStream.close(); + } + + // Open the new file for writing + itkDebugMacro( << "Opening file for writing: " << filename ); + + std::ios::openmode mode = std::ios::out; + if ( truncate ) + { + // typically, ios::out also implies ios::trunc, but being explicit is safer + mode |= std::ios::trunc; + } + else + { + mode |= std::ios::in; + // opening a nonexistent file for reading + writing is not allowed on some platforms + if ( !itksys::SystemTools::FileExists( filename.c_str() ) ) + { + itksys::SystemTools::Touch( filename.c_str(), true ); + // don't worry about failure here, errors should be detected later when the file + // is "actually" opened, unless there is a race condition + } + } + if ( !ascii ) + { + mode |= std::ios::binary; + } + + outputStream.open( filename.c_str(), mode ); + + if ( !outputStream.is_open() || outputStream.fail() ) + { + itkExceptionMacro( << "Could not open file: " + << filename << " for writing." + << std::endl + << "Reason: " + << itksys::SystemTools::GetLastSystemError() ); + } +} + namespace { template< typename TComponent > diff --git a/Utilities/ITK/Modules/IO/ImageBase/src/itkImageIOFactory.cxx b/Utilities/ITK/Modules/IO/ImageBase/src/itkImageIOFactory.cxx index 4f7a1014c329578ffe8a3efc46f7817ac8ea1fb7..638775873847ad8c4017a85f0992de9f4dee7161 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/src/itkImageIOFactory.cxx +++ b/Utilities/ITK/Modules/IO/ImageBase/src/itkImageIOFactory.cxx @@ -60,6 +60,6 @@ ImageIOFactory::CreateImageIO(const char *path, FileModeType mode) } } } - return 0; + return ITK_NULLPTR; } } // end namespace itk diff --git a/Utilities/ITK/Modules/IO/ImageBase/src/itkStreamingImageIOBase.cxx b/Utilities/ITK/Modules/IO/ImageBase/src/itkStreamingImageIOBase.cxx index 0e563cd6dfca3be8fcccb56c143ca50ba4c2f0ee..d7a358322a5f47d3523c214458d3e7d2c237286c 100644 --- a/Utilities/ITK/Modules/IO/ImageBase/src/itkStreamingImageIOBase.cxx +++ b/Utilities/ITK/Modules/IO/ImageBase/src/itkStreamingImageIOBase.cxx @@ -242,63 +242,6 @@ bool StreamingImageIOBase::StreamWriteBufferAsBinary(std::ostream & file, const return true; } -void StreamingImageIOBase::OpenFileForReading(std::ifstream & os, const char *filename) -{ - // Make sure that we have a file to - if ( *filename == 0 ) - { - itkExceptionMacro(<< "A FileName must be specified."); - } - - // Close file from any previous image - if ( os.is_open() ) - { - os.close(); - } - - // Open the new file for reading - itkDebugMacro(<< "Initialize: opening file " << filename); - - os.open(filename, std::ios::in | std::ios::binary); - if ( os.fail() ) - { - itkExceptionMacro(<< "Could not open file for reading: " << filename); - } -} - -void StreamingImageIOBase::OpenFileForWriting(std::ofstream & os, const char *filename, bool truncate) -{ - // Make sure that we have a file to - if ( *filename == 0 ) - { - itkExceptionMacro(<< "A FileName must be specified."); - } - - // Close file from any previous image - if ( os.is_open() ) - { - os.close(); - } - - // Open the new file for writing - itkDebugMacro(<< "Initialize: opening file " << filename); - - if ( truncate ) - { - // truncate - os.open(m_FileName.c_str(), std::ios::out | std::ios::binary | std::ios::trunc); - } - else - { - os.open(m_FileName.c_str(), std::ios::out | std::ios::binary | std::ios::in); - } - - if ( os.fail() ) - { - itkExceptionMacro(<< "Could not open file for writing: " << filename); - } -} - bool StreamingImageIOBase::CanStreamRead(void) { return true; diff --git a/Utilities/ITK/Modules/Numerics/Eigen/include/itkEigenAnalysis2DImageFilter.hxx b/Utilities/ITK/Modules/Numerics/Eigen/include/itkEigenAnalysis2DImageFilter.hxx index 01f3d42405ae646c884416ab82c6eb2345efbcb5..151893d86ab03d47174164d376f05e79dcfc0202 100644 --- a/Utilities/ITK/Modules/Numerics/Eigen/include/itkEigenAnalysis2DImageFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Eigen/include/itkEigenAnalysis2DImageFilter.hxx @@ -216,7 +216,7 @@ EigenAnalysis2DImageFilter< TInputImage, TEigenValueImage, TEigenVectorImage > const double dxy = xx - yy; const double sxy = xx + yy; - const double S = vcl_sqrt(dxy * dxy + 4.0 * xy * xy); + const double S = std::sqrt(dxy * dxy + 4.0 * xy * xy); const double pp = ( sxy + S ) / 2.0; const double qq = ( sxy - S ) / 2.0; diff --git a/Utilities/ITK/Modules/Numerics/Eigen/include/itkSymmetricEigenSystem.h b/Utilities/ITK/Modules/Numerics/Eigen/include/itkSymmetricEigenSystem.h index 46bfce5d692418b272e02ee8f996c96700a1b240..b58050a602ca5d60b484bf9190bfc97d832aab7b 100644 --- a/Utilities/ITK/Modules/Numerics/Eigen/include/itkSymmetricEigenSystem.h +++ b/Utilities/ITK/Modules/Numerics/Eigen/include/itkSymmetricEigenSystem.h @@ -107,7 +107,7 @@ public: protected: SymmetricEigenSystem(); virtual ~SymmetricEigenSystem(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Produces the eigen vectors and values. */ void GenerateData(); diff --git a/Utilities/ITK/Modules/Numerics/Eigen/include/itkSymmetricEigenSystem.hxx b/Utilities/ITK/Modules/Numerics/Eigen/include/itkSymmetricEigenSystem.hxx index 791e2cfdb5a53a4b0e530658cea6ac2eb9f3b798..37bcfe1e6a8e81a20340ee78628382785e397bf3 100644 --- a/Utilities/ITK/Modules/Numerics/Eigen/include/itkSymmetricEigenSystem.hxx +++ b/Utilities/ITK/Modules/Numerics/Eigen/include/itkSymmetricEigenSystem.hxx @@ -29,7 +29,7 @@ template< typename TMatrixElement, int VNumberOfRows > SymmetricEigenSystem< TMatrixElement, VNumberOfRows > ::SymmetricEigenSystem() { - m_Matrix = 0; + m_Matrix = ITK_NULLPTR; m_UseAbsoluteOrder = true; m_EigenValues.Fill(NumericTraits< TMatrixElement >::Zero); ArrayType temp; @@ -54,7 +54,7 @@ SymmetricEigenSystem< TMatrixElement, VNumberOfRows > os << indent << "Matrix:"; - if ( m_Matrix != 0 ) + if ( m_Matrix != ITK_NULLPTR ) { os << m_Matrix << std::endl; } diff --git a/Utilities/ITK/Modules/Numerics/NarrowBand/include/itkNarrowBand.h b/Utilities/ITK/Modules/Numerics/NarrowBand/include/itkNarrowBand.h index 533875d2d2dfcfff492111ff38faa9be19a9f828..bfcf22f186bebeef323d770b5a94c490f2d957e2 100644 --- a/Utilities/ITK/Modules/Numerics/NarrowBand/include/itkNarrowBand.h +++ b/Utilities/ITK/Modules/Numerics/NarrowBand/include/itkNarrowBand.h @@ -20,6 +20,7 @@ #include "itkLightObject.h" #include "itkObjectFactory.h" +#include "itkNumericTraits.h" #include <vector> namespace itk @@ -37,7 +38,9 @@ public: TDataType m_Data; TIndexType m_Index; signed char m_NodeState; - BandNode() : m_NodeState( 0 ) {} + BandNode() : + m_Data(NumericTraits<TDataType>::ZeroValue()), m_NodeState(0) + {} }; /** \class NarrowBand diff --git a/Utilities/ITK/Modules/Numerics/NarrowBand/include/itkNarrowBand.hxx b/Utilities/ITK/Modules/Numerics/NarrowBand/include/itkNarrowBand.hxx index 23d4633bd75ee2206d180f6545dfa45c685b1fc0..2478f7cac2bdd79f9fea439b3f3411365181ec5c 100644 --- a/Utilities/ITK/Modules/Numerics/NarrowBand/include/itkNarrowBand.hxx +++ b/Utilities/ITK/Modules/Numerics/NarrowBand/include/itkNarrowBand.hxx @@ -28,7 +28,6 @@ #ifndef __itkNarrowBand_hxx #define __itkNarrowBand_hxx #include "itkNarrowBand.h" -#include "vcl_cmath.h" #include <cmath> namespace itk @@ -50,7 +49,7 @@ NarrowBand< NodeType > SizeType regionsize = static_cast< SizeType >( - vcl_floor( static_cast< float >( t_size ) / static_cast< float >( t_n ) ) ); + std::floor( static_cast< float >( t_size ) / static_cast< float >( t_n ) ) ); if ( regionsize == 0 ) { diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkGaussianRadialBasisFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkGaussianRadialBasisFunction.hxx index 1be0f27784b94d8b318508d649f6f0cb567f46b5..c4be9ae4d442b27553629a9953c0630fb8751703 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkGaussianRadialBasisFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkGaussianRadialBasisFunction.hxx @@ -49,7 +49,7 @@ GaussianRadialBasisFunction< ScalarType> { ScalarType val; ScalarType radius = Superclass::GetRadius(); - val = vcl_exp(-0.5*vcl_pow(input,2)/vcl_pow(radius,2)); + val = std::exp(-0.5*std::pow(input,2)/std::pow(radius,2)); return val; } @@ -65,13 +65,13 @@ GaussianRadialBasisFunction< ScalarType> ArrayType center = Superclass::GetCenter(); if(mode=='u') //w.r.t centers { - ScalarType temp1= vcl_pow(radius,2); + ScalarType temp1= std::pow(radius,2); val=Evaluate(dist) *(input.GetElement(element_id)-center.GetElement(element_id))/temp1; } else if(mode=='s') // w.r.t radius { - val=Evaluate(dist)*vcl_pow(dist,2)/vcl_pow(radius,3); + val=Evaluate(dist)*std::pow(dist,2)/std::pow(radius,3); } return val; } diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkGaussianTransferFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkGaussianTransferFunction.hxx index 7eb74e7bb405ee7d04798fa80979f24bd6ee6daa..bf0a2734f5db62e8c9effd5e74dff6e6c44b177e 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkGaussianTransferFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkGaussianTransferFunction.hxx @@ -45,7 +45,7 @@ ScalarType GaussianTransferFunction<ScalarType> ::Evaluate(const ScalarType& input) const { - return static_cast<ScalarType>((vcl_exp(-1 * input * input))); + return static_cast<ScalarType>((std::exp(-1 * input * input))); } /** Evaluate derivatives function */ diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLayerBase.h b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLayerBase.h index 667a49a97f6afea921ec402d1563386403258888..61c6f4439655dadf097219b6a7b1c74b94e07ebe 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLayerBase.h +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLayerBase.h @@ -142,7 +142,7 @@ protected: ~LayerBase(); /** Method to print the object. */ - virtual void PrintSelf( std::ostream& os, Indent indent ) const; + virtual void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE; LayerTypeCode m_LayerTypeCode; //input, hidden, output unsigned int m_LayerId; diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLayerBase.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLayerBase.hxx index 1277dd0203ac7c05d415e942e3e50272dd782bed..57564dc193dfd376cb0af087da969bb2cea3a2af 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLayerBase.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLayerBase.hxx @@ -25,7 +25,7 @@ namespace itk { namespace Statistics { -#define INVALID_LAYER_ID vcl_numeric_limits<unsigned int>::max() +#define INVALID_LAYER_ID std::numeric_limits<unsigned int>::max() template<typename TMeasurementVector, typename TTargetVector> LayerBase<TMeasurementVector,TTargetVector> @@ -34,10 +34,10 @@ LayerBase<TMeasurementVector,TTargetVector> m_NumberOfNodes = 0; m_LayerId = INVALID_LAYER_ID; m_LayerTypeCode = INVALIDLAYER; - m_InputWeightSet = 0; - m_OutputWeightSet = 0; - m_ActivationFunction = 0; - m_NodeInputFunction = 0; + m_InputWeightSet = ITK_NULLPTR; + m_OutputWeightSet = ITK_NULLPTR; + m_ActivationFunction = ITK_NULLPTR; + m_NodeInputFunction = ITK_NULLPTR; } template<typename TMeasurementVector, typename TTargetVector> diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLearningFunctionBase.h b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLearningFunctionBase.h index 49bfffcff6a3e1f8314a047dbea51312cc967958..14560e9c254984889e07b80de679087c16700e2f 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLearningFunctionBase.h +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLearningFunctionBase.h @@ -58,7 +58,7 @@ protected: ~LearningFunctionBase() {}; /** Method to print the object. */ - virtual void PrintSelf( std::ostream& os, Indent indent ) const + virtual void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE { Superclass::PrintSelf( os, indent ); os << indent << "LearningFunctionBase(" << this << ")" << std::endl; diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLogSigmoidTransferFunction.h b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLogSigmoidTransferFunction.h index 928ac8a0e18aa86b911f2cf997edb8fe97548bf2..77ae71397bca79415bb2a20942325533daa81748 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLogSigmoidTransferFunction.h +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLogSigmoidTransferFunction.h @@ -30,17 +30,20 @@ namespace Statistics * \ingroup ITKNeuralNetworks */ -template<typename ScalarType> -class LogSigmoidTransferFunction : public TransferFunctionBase<ScalarType> +template<typename TScalar> +class LogSigmoidTransferFunction : public TransferFunctionBase<TScalar> { public: /** Standard class typedefs. */ typedef LogSigmoidTransferFunction Self; - typedef TransferFunctionBase<ScalarType> Superclass; + typedef TransferFunctionBase<TScalar> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; + typedef TScalar ScalarType; + typedef typename NumericTraits< ScalarType >::RealType RealType; + /** Run-time type information (and related methods). */ itkTypeMacro(LogSigmoidTransferFunction, TransferFunctionBase); @@ -48,10 +51,10 @@ public: itkNewMacro(Self); /** Evaluate at the specified input position */ - virtual ScalarType Evaluate(const ScalarType& input) const; + virtual TScalar Evaluate(const ScalarType& input) const; /** Evaluate the derivative at the specified input position */ - virtual ScalarType EvaluateDerivative(const ScalarType& input) const; + virtual TScalar EvaluateDerivative(const ScalarType& input) const; protected: diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLogSigmoidTransferFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLogSigmoidTransferFunction.hxx index ba23a9f3e5a30c037b4bdc504fc93c401e5656cb..a852912aa543df6cc98d698e359f2ae20a9176ff 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLogSigmoidTransferFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkLogSigmoidTransferFunction.hxx @@ -25,34 +25,31 @@ namespace itk namespace Statistics { -/** Constructor */ -template<typename ScalarType> -LogSigmoidTransferFunction<ScalarType> +template<typename TScalar> +LogSigmoidTransferFunction<TScalar> ::LogSigmoidTransferFunction() { } -/** Destructor */ -template<typename ScalarType> -LogSigmoidTransferFunction<ScalarType> +template<typename TScalar> +LogSigmoidTransferFunction<TScalar> ::~LogSigmoidTransferFunction() { } -/** Evaluate */ -template<typename ScalarType> -ScalarType -LogSigmoidTransferFunction<ScalarType> +template<typename TScalar> +TScalar +LogSigmoidTransferFunction<TScalar> ::Evaluate(const ScalarType& input) const { - const ScalarType v = 1.0 / (1.0 + vcl_exp(-input)); + const ScalarType v = static_cast< ScalarType >( 1.0 / + ( 1.0 + std::exp( static_cast< typename NumericTraits< ScalarType >::RealType >(-input)) ) ); return v; } -/** Evaluate derivatives */ -template<typename ScalarType> -ScalarType -LogSigmoidTransferFunction<ScalarType> +template<typename TScalar> +TScalar +LogSigmoidTransferFunction<TScalar> ::EvaluateDerivative(const ScalarType& input) const { ScalarType f = Evaluate(input); @@ -60,9 +57,9 @@ LogSigmoidTransferFunction<ScalarType> } /** Print the object */ -template<typename ScalarType> +template<typename TScalar> void -LogSigmoidTransferFunction<ScalarType> +LogSigmoidTransferFunction<TScalar> ::PrintSelf( std::ostream& os, Indent indent ) const { os << indent << "LogSigmoidTransferFunction(" << this << ")" << std::endl; diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkMultiquadricRadialBasisFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkMultiquadricRadialBasisFunction.hxx index 6b3cafc7484c19244d0b7c04ee6828246b8afaeb..8dd137f50564bfb20708c2eac0d9c130abdda264 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkMultiquadricRadialBasisFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkMultiquadricRadialBasisFunction.hxx @@ -45,7 +45,7 @@ ScalarType MultiquadricRadialBasisFunction<ScalarType> ::Evaluate(const ScalarType& input) const { - const ScalarType val = vcl_pow((input*input)+(m_Radius*m_Radius),0.5); + const ScalarType val = std::pow((input*input)+(m_Radius*m_Radius),0.5); return val; } diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkNeuralNetworkObject.h b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkNeuralNetworkObject.h index 64fe7f2c148e824c94701f3d631483cbfd5a02a2..121427361a074a8a37aab0bc27c16645dde69b7d 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkNeuralNetworkObject.h +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkNeuralNetworkObject.h @@ -62,7 +62,7 @@ protected: virtual ~NeuralNetworkObject(); /** Method to print the object. */ - virtual void PrintSelf( std::ostream& os, Indent indent ) const; + virtual void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE; ValueType m_LearningRate; diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkRBFBackPropagationLearningFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkRBFBackPropagationLearningFunction.hxx index 12ff7758ab275160f7c1dd71faa21cd6aa232ad3..81f6e9263dc26b80cc7a651efac0e8f2343d4e43 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkRBFBackPropagationLearningFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkRBFBackPropagationLearningFunction.hxx @@ -42,11 +42,6 @@ RBFBackPropagationLearningFunction<LayerType,TTargetVector> typename LayerType::WeightSetType::Pointer outputweightset = layer->GetModifiableOutputWeightSet(); typename LayerType::WeightSetType::Pointer inputweightset = layer->GetModifiableInputWeightSet(); - typedef typename LayerType::InputVectorType InputVectorType; - typedef typename LayerType::OutputVectorType OutputVectorType; - - typedef RBFLayer<InputVectorType,OutputVectorType> RbfLayerType; - typedef typename RbfLayerType::InternalVectorType ArrayType; typename LayerType::ValuePointer currentdeltavalues = inputweightset->GetTotalDeltaValues(); vnl_matrix<ValueType> DW_temp(currentdeltavalues,inputweightset->GetNumberOfOutputNodes(), inputweightset->GetNumberOfInputNodes()); diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSigmoidTransferFunction.h b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSigmoidTransferFunction.h index 40d96c1aae09a3132d6818a053f6329762ffbc4d..93aa7056efddc0f86a3293097e16db662494b4d7 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSigmoidTransferFunction.h +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSigmoidTransferFunction.h @@ -24,23 +24,26 @@ namespace itk { namespace Statistics { + /** \class SigmoidTransferFunction * \brief This is the itkSigmoidTransferFunction class. * * \ingroup ITKNeuralNetworks */ - -template<typename ScalarType> -class SigmoidTransferFunction : public TransferFunctionBase<ScalarType> +template<typename TScalar> +class SigmoidTransferFunction : public TransferFunctionBase<TScalar> { public: /** Standard class typedefs. */ typedef SigmoidTransferFunction Self; - typedef TransferFunctionBase<ScalarType> Superclass; + typedef TransferFunctionBase<TScalar> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; + typedef TScalar ScalarType; + typedef typename NumericTraits< ScalarType >::RealType RealType; + /** Run-time type information (and related methods). */ itkTypeMacro(SigmoidTransferFunction, TransferFunctionBase); @@ -48,10 +51,10 @@ public: itkNewMacro(Self); /** Set/Get macros */ - itkSetMacro(Alpha,ScalarType); - itkGetMacro(Alpha,ScalarType); - itkSetMacro(Beta,ScalarType); - itkGetMacro(Beta,ScalarType); + itkSetMacro(Alpha,RealType); + itkGetMacro(Alpha,RealType); + itkSetMacro(Beta,RealType); + itkGetMacro(Beta,RealType); itkSetMacro(OutputMinimum,ScalarType); itkGetMacro(OutputMinimum,ScalarType); itkSetMacro(OutputMaximum,ScalarType); @@ -73,8 +76,8 @@ protected: private: - ScalarType m_Alpha; - ScalarType m_Beta; + RealType m_Alpha; + RealType m_Beta; ScalarType m_OutputMinimum; ScalarType m_OutputMaximum; }; diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSigmoidTransferFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSigmoidTransferFunction.hxx index 5d8ab9d759d5a605e22b7bfbc03499348a90c823..1f71e28b7200d63ddd9ea4b27eb0b0fa284ee1d2 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSigmoidTransferFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSigmoidTransferFunction.hxx @@ -25,9 +25,9 @@ namespace itk namespace Statistics { -/** Constructor */ -template<typename ScalarType> -SigmoidTransferFunction< ScalarType> + +template<typename TScalar> +SigmoidTransferFunction<TScalar> ::SigmoidTransferFunction() { m_Alpha = 1.0; @@ -36,40 +36,40 @@ SigmoidTransferFunction< ScalarType> m_OutputMaximum = NumericTraits<ScalarType>::max(); } -/** Destructor */ -template<typename ScalarType> -SigmoidTransferFunction<ScalarType> + +template<typename TScalar> +SigmoidTransferFunction<TScalar> ::~SigmoidTransferFunction() { } -/** Evaluate */ -template<typename ScalarType> -ScalarType -SigmoidTransferFunction<ScalarType> + +template<typename TScalar> +TScalar +SigmoidTransferFunction<TScalar> ::Evaluate(const ScalarType& input) const { - const ScalarType x = (static_cast<ScalarType>(input) - m_Beta) / m_Alpha; - const ScalarType e = 1.0 / (1.0 + vcl_exp(-x)); - const ScalarType v = (m_OutputMaximum - m_OutputMinimum) * e + const RealType x = static_cast< RealType >( input - m_Beta ) / m_Alpha; + const RealType e = 1.0 / (1.0 + std::exp( static_cast< typename NumericTraits< ScalarType >::RealType >(-x))); + const ScalarType v = static_cast< ScalarType >( (m_OutputMaximum - m_OutputMinimum) * e ) + m_OutputMinimum; return v; } -/** Evaluate Derivatives */ -template<typename ScalarType> -ScalarType -SigmoidTransferFunction< ScalarType> + +template<typename TScalar> +TScalar +SigmoidTransferFunction<TScalar> ::EvaluateDerivative(const ScalarType& input) const { ScalarType f = Evaluate(input); return f * (1 - f); } -/** Print the object */ -template<typename ScalarType> + +template<typename TScalar> void -SigmoidTransferFunction<ScalarType> +SigmoidTransferFunction<TScalar> ::PrintSelf( std::ostream& os, Indent indent ) const { os << indent << "SigmoidTransferFunction(" << this << ")" << std::endl; diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSymmetricSigmoidTransferFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSymmetricSigmoidTransferFunction.hxx index a7e14aedbb25b10ca9dc77c3bd8448c1a8b01d3f..0b71399b1eb051c150ea823465013958b46b157e 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSymmetricSigmoidTransferFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkSymmetricSigmoidTransferFunction.hxx @@ -55,7 +55,7 @@ SymmetricSigmoidTransferFunction<ScalarType> } else { - val= (ScalarType)1.0/(1.0+vcl_exp(-input))-0.5; + val= (ScalarType)1.0/(1.0+std::exp(-input))-0.5; } return val; } diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTanHTransferFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTanHTransferFunction.hxx index 51019baf2382e7c5ff6b752fbf5ebb2596a54117..2962225804204f4101189c87ed4d9994e0fdd362 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTanHTransferFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTanHTransferFunction.hxx @@ -45,8 +45,8 @@ ScalarType TanHTransferFunction<ScalarType> ::Evaluate(const ScalarType& input) const { - ScalarType x = vcl_exp(input); - ScalarType y = vcl_exp(-input); + ScalarType x = std::exp(input); + ScalarType y = std::exp(-input); return static_cast<ScalarType>((float) (x - y) / (x + y)); } @@ -57,7 +57,7 @@ TanHTransferFunction<ScalarType> ::EvaluateDerivative(const ScalarType& input) const { ScalarType f = Evaluate(input); - return 1 - vcl_pow(f, 2); + return 1 - std::pow(f, 2); } /** Print the object */ diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTanSigmoidTransferFunction.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTanSigmoidTransferFunction.hxx index 1f78f60517e796172237a9d876ce69023ccdc9ee..6af6ca7b84d525397b44ef0dec0ec7e3ddf34511 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTanSigmoidTransferFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTanSigmoidTransferFunction.hxx @@ -46,7 +46,7 @@ TanSigmoidTransferFunction<ScalarType> ::Evaluate(const ScalarType& input) const { return static_cast<ScalarType>((2 - / (1 + vcl_exp(-2 * static_cast<ScalarType>(input)))) + / (1 + std::exp(-2 * static_cast<ScalarType>(input)))) - 1); } diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTrainingFunctionBase.h b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTrainingFunctionBase.h index a610e56e6914fa735cc5f5308a9991f5c02354f4..d7b02da300b65d9bc7e2394983274dcd0f224dd7 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTrainingFunctionBase.h +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTrainingFunctionBase.h @@ -105,7 +105,7 @@ protected: ~TrainingFunctionBase(){}; /** Method to print the object. */ - virtual void PrintSelf( std::ostream& os, Indent indent ) const; + virtual void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE; TSample* m_TrainingSamples;// original samples TTargetVector* m_SampleTargets; // original samples diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTrainingFunctionBase.hxx b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTrainingFunctionBase.hxx index 2b13f8c94ce1f94573d1197061d0f0eb914bab36..82da78bada5a1f2f1e47b203cbc1fdf7ebe1262d 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTrainingFunctionBase.hxx +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkTrainingFunctionBase.hxx @@ -31,8 +31,8 @@ TrainingFunctionBase<TSample,TTargetVector,ScalarType> { m_PerformanceFunction = DefaultPerformanceType::New(); m_Iterations = 0; - m_TrainingSamples = NULL; - m_SampleTargets = NULL; + m_TrainingSamples = ITK_NULLPTR; + m_SampleTargets = ITK_NULLPTR; m_LearningRate = 1.0; } diff --git a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkWeightSetBase.h b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkWeightSetBase.h index 5607b163d1df8d596d9c7abd7db8f33415d2fc74..8b9fa8037fcdc9d4a958dd8c008fc12d1cd5a357 100644 --- a/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkWeightSetBase.h +++ b/Utilities/ITK/Modules/Numerics/NeuralNetworks/include/itkWeightSetBase.h @@ -125,7 +125,7 @@ protected: ~WeightSetBase(); /** Method to print the object. */ - virtual void PrintSelf( std::ostream& os, Indent indent ) const; + virtual void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE; typename RandomVariateGeneratorType::Pointer m_RandomGenerator; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkAmoebaOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkAmoebaOptimizer.h index 757565ddf9fccba93d2b68df4ad115868348352c..11f515b01acfdffb570942b6ebbcbb92b274f0d9 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkAmoebaOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkAmoebaOptimizer.h @@ -83,10 +83,10 @@ public: typedef vnl_vector< double > InternalParametersType; /** Start optimization with an initial value. */ - void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; /** Plug in a Cost Function into the optimizer */ - virtual void SetCostFunction(SingleValuedCostFunction *costFunction); + virtual void SetCostFunction(SingleValuedCostFunction *costFunction) ITK_OVERRIDE; /** Set/Get the maximum number of iterations. The optimization algorithm will * terminate after the maximum number of iterations has been reached. @@ -137,7 +137,7 @@ public: itkGetConstMacro(FunctionConvergenceTolerance, double); /** Report the reason for stopping. */ - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; /** Return Current Value */ MeasureType GetValue() const; @@ -148,7 +148,7 @@ public: protected: AmoebaOptimizer(); virtual ~AmoebaOptimizer(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; typedef Superclass::CostFunctionAdaptorType CostFunctionAdaptorType; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkConjugateGradientOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkConjugateGradientOptimizer.h index 3dfc6d00237042971bbbf9469ecbd4da5d42219b..5ea080f9575c5c0ad6b06a4c314ffca133f4bb61 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkConjugateGradientOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkConjugateGradientOptimizer.h @@ -57,10 +57,10 @@ public: vnl_conjugate_gradient * GetOptimizer(void); /** Start optimization with an initial value. */ - void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; /** Plug in a Cost Function into the optimizer */ - virtual void SetCostFunction(SingleValuedCostFunction *costFunction); + virtual void SetCostFunction(SingleValuedCostFunction *costFunction) ITK_OVERRIDE; /** Return the number of iterations performed so far */ SizeValueType GetNumberOfIterations(void) const; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCostFunction.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCostFunction.h index 8b41eed387b0c1047973af78ab4eaf3dd0e579b7..7e6a770b8999ce107b50d6ae80990b0a2ad0e76a 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCostFunction.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCostFunction.h @@ -58,7 +58,7 @@ public: protected: CostFunctionTemplate() {} virtual ~CostFunctionTemplate() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: CostFunctionTemplate(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCumulativeGaussianCostFunction.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCumulativeGaussianCostFunction.h index 4ea0b0210e21bbafc0e9b7b69049b27f66a8b0c7..3b904f8b81677c8f4d2ccdc6fb9ead1d201a6e08 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCumulativeGaussianCostFunction.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCumulativeGaussianCostFunction.h @@ -74,10 +74,10 @@ public: /** Not necessary for this optimizer. */ void GetDerivative( const ParametersType & itkNotUsed(parameters), - DerivativeType & itkNotUsed(derivative) ) const {} + DerivativeType & itkNotUsed(derivative) ) const ITK_OVERRIDE {} /** Return the values evaluated for the given parameters. */ - MeasureType GetValue(const ParametersType & parameters) const; + virtual MeasureType GetValue(const ParametersType & parameters) const ITK_OVERRIDE; /** Return a pointer of values evaluated for the given parameters. */ MeasureType * GetValuePointer(ParametersType & parameters); @@ -89,10 +89,10 @@ public: double EvaluateCumulativeGaussian(double argument) const; /** Get the SpaceDimension. */ - unsigned int GetNumberOfParameters() const; + virtual unsigned int GetNumberOfParameters() const ITK_OVERRIDE; /** Get the number Range Dimension. */ - unsigned int GetNumberOfValues() const; + virtual unsigned int GetNumberOfValues() const ITK_OVERRIDE; /** Initialize the arrays. */ void Initialize(unsigned int rangeDimension); @@ -104,7 +104,7 @@ protected: CumulativeGaussianCostFunction(); virtual ~CumulativeGaussianCostFunction(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCumulativeGaussianOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCumulativeGaussianOptimizer.h index 03aa29ba5135c42e3eacec2c591be1a73796232e..144cbb121b31f9a9d11222974beae8d1bf35650e 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCumulativeGaussianOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkCumulativeGaussianOptimizer.h @@ -83,18 +83,18 @@ public: void SetDataArray(MeasureType *dataArray); /** Start the optimizer. */ - void StartOptimization(); + virtual void StartOptimization() ITK_OVERRIDE; /** Print an array. */ void PrintArray(MeasureType *array); /** Report the reason for stopping. */ - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: CumulativeGaussianOptimizer(); virtual ~CumulativeGaussianOptimizer(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkExhaustiveOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkExhaustiveOptimizer.h index f09f66156f42243997b921e4a7584c188126b576..8c187bf80bb6e46ebecf2a0a469d54b594342f4b 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkExhaustiveOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkExhaustiveOptimizer.h @@ -96,7 +96,7 @@ public: /** Run-time type information (and related methods). */ itkTypeMacro(ExhaustiveOptimizer, SingleValuedNonLinearOptimizer); - virtual void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; void StartWalking(void); @@ -117,12 +117,12 @@ public: itkGetConstReferenceMacro(MaximumNumberOfIterations, SizeValueType); /** Get the reason for termination */ - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: ExhaustiveOptimizer(); virtual ~ExhaustiveOptimizer() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Advance to the next grid position. */ void AdvanceOneStep(void); diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkFRPROptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkFRPROptimizer.h index fa0f03201f92bce31a031fd3c5a5b2aca070fe49..051a1f7975949b5adefe89b3c6018da8be5054a9 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkFRPROptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkFRPROptimizer.h @@ -73,7 +73,7 @@ public: itkGetConstMacro(UseUnitLengthGradient, bool); /** Start optimization. */ - void StartOptimization(); + virtual void StartOptimization() ITK_OVERRIDE; /** Set it to the Fletch-Reeves optimizer */ void SetToFletchReeves(); @@ -85,7 +85,7 @@ protected: FRPROptimizer(); virtual ~FRPROptimizer(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Get the value of the n-dimensional cost function at this scalar step * distance along the current line direction from the current line origin. diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkGradientDescentOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkGradientDescentOptimizer.h index ef43511da565f690dc9237243fb00cb9d7802738..3d11b4d6e5aa3db3db7735fd7b1e3cd3c0d058ab 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkGradientDescentOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkGradientDescentOptimizer.h @@ -87,7 +87,7 @@ public: virtual void AdvanceOneStep(void); /** Start optimization. */ - void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; /** Resume previously stopped optimization with current parameters * \sa StopOptimization. */ @@ -117,7 +117,7 @@ public: /** Get Stop condition. */ itkGetConstReferenceMacro(StopCondition, StopConditionType); - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; /** Get Gradient condition. */ itkGetConstReferenceMacro(Gradient, DerivativeType); @@ -125,7 +125,7 @@ public: protected: GradientDescentOptimizer(); virtual ~GradientDescentOptimizer() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; // made protected so subclass can access DerivativeType m_Gradient; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkInitializationBiasedParticleSwarmOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkInitializationBiasedParticleSwarmOptimizer.h index 07749d31761dba0ecf772a77c40fcff0e42d5983..22bbf7635bcb5e20da10ba5c1e0b8ec29baa795b 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkInitializationBiasedParticleSwarmOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkInitializationBiasedParticleSwarmOptimizer.h @@ -115,8 +115,8 @@ public: protected: InitializationBiasedParticleSwarmOptimizer(); virtual ~InitializationBiasedParticleSwarmOptimizer() {}; - void PrintSelf(std::ostream& os, Indent indent) const; - virtual void UpdateSwarm(); + virtual void PrintSelf(std::ostream& os, Indent indent) const ITK_OVERRIDE; + virtual void UpdateSwarm() ITK_OVERRIDE; private: //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLBFGSBOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLBFGSBOptimizer.h index 79e46d12c23230bb23952c15e0b3c740c3ceccab..81e2ae6867d065a753283847c47d08e9c40845e4 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLBFGSBOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLBFGSBOptimizer.h @@ -95,10 +95,10 @@ public: typedef LBFGSBOptimizerHelper InternalOptimizerType; /** Start optimization with an initial value. */ - void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; /** Plug in a Cost Function into the optimizer */ - virtual void SetCostFunction(SingleValuedCostFunction *costFunction); + virtual void SetCostFunction(SingleValuedCostFunction *costFunction) ITK_OVERRIDE; /** Set/Get the optimizer trace flag. If set to true, the optimizer * prints out information every iteration. @@ -175,12 +175,12 @@ public: itkGetConstReferenceMacro(InfinityNormOfProjectedGradient, double); /** Get the reason for termination */ - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: LBFGSBOptimizer(); virtual ~LBFGSBOptimizer(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; typedef Superclass::CostFunctionAdaptorType CostFunctionAdaptorType; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLBFGSOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLBFGSOptimizer.h index a32978118b31fdea4bbc11c6cea584ef5032cc66..4743cdee1268b6db198669798cdf0a2cae7b4c5b 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLBFGSOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLBFGSOptimizer.h @@ -55,10 +55,10 @@ public: vnl_lbfgs * GetOptimizer(void); /** Start optimization with an initial value. */ - void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; /** Plug in a Cost Function into the optimizer */ - virtual void SetCostFunction(SingleValuedCostFunction *costFunction); + virtual void SetCostFunction(SingleValuedCostFunction *costFunction) ITK_OVERRIDE; /** Set/Get the optimizer trace flag. If set to true, the optimizer * prints out information every iteration. @@ -104,12 +104,12 @@ public: MeasureType GetValue() const; /** Get the reason for termination */ - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: LBFGSOptimizer(); virtual ~LBFGSOptimizer(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; typedef Superclass::CostFunctionAdaptorType CostFunctionAdaptorType; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLevenbergMarquardtOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLevenbergMarquardtOptimizer.h index 130359657ee7e8a3813d0fec624b7055a510d7de..fac25d3e0ff679baf675f73edec1711424e0da5e 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLevenbergMarquardtOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkLevenbergMarquardtOptimizer.h @@ -55,10 +55,10 @@ public: vnl_levenberg_marquardt * GetOptimizer(void) const; /** Start optimization with an initial value. */ - void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; /** Plug in a Cost Function into the optimizer */ - virtual void SetCostFunction(MultipleValuedCostFunction *costFunction); + virtual void SetCostFunction(MultipleValuedCostFunction *costFunction) ITK_OVERRIDE; void SetNumberOfIterations(unsigned int iterations); @@ -71,7 +71,7 @@ public: /** Get the current value */ MeasureType GetValue() const; - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: LevenbergMarquardtOptimizer(); diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedNonLinearOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedNonLinearOptimizer.h index 3ea6327d4047bbe0221f3ac78be9bbc7ee012898..3d336c7e292f4dc44a33f11c6cee61fc249b821d 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedNonLinearOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedNonLinearOptimizer.h @@ -70,7 +70,7 @@ public: protected: MultipleValuedNonLinearOptimizer(); virtual ~MultipleValuedNonLinearOptimizer() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; CostFunctionPointer m_CostFunction; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedNonLinearVnlOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedNonLinearVnlOptimizer.h index bf4bba0b9d7919cb18bd81f889f551bce5d6bd0c..cc8e9a81aaf1104b9b522cbb1e6c7a1e3499788a 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedNonLinearVnlOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedNonLinearVnlOptimizer.h @@ -90,7 +90,7 @@ protected: MultipleValuedNonLinearVnlOptimizer(); virtual ~MultipleValuedNonLinearVnlOptimizer(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; typedef MultipleValuedVnlCostFunctionAdaptor CostFunctionAdaptorType; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedVnlCostFunctionAdaptor.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedVnlCostFunctionAdaptor.h index c53f8ba24fa95b9e3bec2a03111b87d8e84544c8..33a66fb7dc002104cb39c8bddc41e6a30dcf283f 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedVnlCostFunctionAdaptor.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkMultipleValuedVnlCostFunctionAdaptor.h @@ -73,11 +73,11 @@ public: /** Delegate computation of the value to the CostFunction. */ virtual void f(const InternalParametersType & inparameters, - InternalMeasureType & measures); + InternalMeasureType & measures) ITK_OVERRIDE; /** Delegate computation of the gradient to the costFunction. */ virtual void gradf(const InternalParametersType & inparameters, - InternalDerivativeType & gradient); + InternalDerivativeType & gradient) ITK_OVERRIDE; /** Delegate computation of value and gradient to the costFunction. */ virtual void compute(const InternalParametersType & x, diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkOnePlusOneEvolutionaryOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkOnePlusOneEvolutionaryOptimizer.h index bb4d31e319675e8654e2b7802dc1faa3200319b2..303efff16453ab90e5c028517a2b5142b0330c44 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkOnePlusOneEvolutionaryOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkOnePlusOneEvolutionaryOptimizer.h @@ -151,7 +151,7 @@ public: /** Start optimization. * Optimization will stop when it meets either of two termination conditions, * the maximum iteration limit or epsilon (minimal search radius) */ - void StartOptimization(); + virtual void StartOptimization() ITK_OVERRIDE; /** when users call StartOptimization, this value will be set false. * By calling StopOptimization, this flag will be set true, and @@ -165,13 +165,13 @@ public: itkGetConstReferenceMacro(MetricWorstPossibleValue, double); itkSetMacro(MetricWorstPossibleValue, double); - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: OnePlusOneEvolutionaryOptimizer(); OnePlusOneEvolutionaryOptimizer(const OnePlusOneEvolutionaryOptimizer &); virtual ~OnePlusOneEvolutionaryOptimizer(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkOptimizer.h index cf66537bfcbec0ae4596b4d9344ae44a85264738..ecc05b881c98563bc1ef359fb59fd66ead727d2c 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkOptimizer.h @@ -86,7 +86,7 @@ public: protected: Optimizer(); virtual ~Optimizer() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Set the current position. */ virtual void SetCurrentPosition(const ParametersType & param); diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkParticleSwarmOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkParticleSwarmOptimizer.h index a058b9c85e242c469c81c29974d9785c16024723..232ead53a42dfb3607a563d2f0317f4ab78dd5b6 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkParticleSwarmOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkParticleSwarmOptimizer.h @@ -94,8 +94,8 @@ public: protected: ParticleSwarmOptimizer(); virtual ~ParticleSwarmOptimizer(); - void PrintSelf(std::ostream& os, Indent indent) const; - virtual void UpdateSwarm(); + virtual void PrintSelf(std::ostream& os, Indent indent) const ITK_OVERRIDE; + virtual void UpdateSwarm() ITK_OVERRIDE; private: ParticleSwarmOptimizer(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkParticleSwarmOptimizerBase.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkParticleSwarmOptimizerBase.h index ff072982d1b67ec6da1e32e54a840da87eacffbe..3011a69d85e1cab97602e137962a765ceea41aea 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkParticleSwarmOptimizerBase.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkParticleSwarmOptimizerBase.h @@ -113,7 +113,7 @@ public: itkBooleanMacro( PrintSwarm ) /** Start optimization. */ - void StartOptimization( void ); + virtual void StartOptimization( void ) ITK_OVERRIDE; /** Set/Get number of particles in the swarm - the maximal number of function @@ -187,7 +187,7 @@ public: MeasureType GetValue() const; /** Get the reason for termination */ - virtual const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; /** Print the swarm information to the given output stream. Each line * (particle data) is of the form: @@ -198,7 +198,7 @@ public: protected: ParticleSwarmOptimizerBase(); virtual ~ParticleSwarmOptimizerBase(); - void PrintSelf( std::ostream& os, Indent indent ) const; + virtual void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE; void PrintParamtersType( const ParametersType& x, std::ostream& os ) const; /** diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkPowellOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkPowellOptimizer.h index 4ae97748cbe27cf80276516ba3de6859ebafe6c2..6d083d9f9f6f6e4bbb901e072ed45b589f8f4582 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkPowellOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkPowellOptimizer.h @@ -121,7 +121,7 @@ public: itkGetConstReferenceMacro(CurrentLineIteration, unsigned int); /** Start optimization. */ - void StartOptimization(); + virtual void StartOptimization() ITK_OVERRIDE; /** When users call StartOptimization, this value will be set false. * By calling StopOptimization, this flag will be set true, and @@ -135,13 +135,13 @@ public: itkGetConstReferenceMacro(MetricWorstPossibleValue, double); itkSetMacro(MetricWorstPossibleValue, double); - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: PowellOptimizer(); PowellOptimizer(const PowellOptimizer &); virtual ~PowellOptimizer(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; itkSetMacro(CurrentCost, double); diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkQuaternionRigidTransformGradientDescentOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkQuaternionRigidTransformGradientDescentOptimizer.h index eeed60af936b39353f5fda571cca7d64242ce658..601e1ed996585e9acd5ae9e34b66b26b8b85d09b 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkQuaternionRigidTransformGradientDescentOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkQuaternionRigidTransformGradientDescentOptimizer.h @@ -70,7 +70,7 @@ public: typedef Superclass::ParametersType ParametersType; /** Advance one step following the gradient direction. */ - virtual void AdvanceOneStep(void); + virtual void AdvanceOneStep(void) ITK_OVERRIDE; protected: QuaternionRigidTransformGradientDescentOptimizer() {} diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkRegularStepGradientDescentBaseOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkRegularStepGradientDescentBaseOptimizer.h index e67ab70ca4facc3f1913c22f73a38106797a9b93..7087491d4135118be5e484af3862fc5943b681c1 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkRegularStepGradientDescentBaseOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkRegularStepGradientDescentBaseOptimizer.h @@ -70,7 +70,7 @@ public: { SetMaximize(true); } /** Start optimization. */ - void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; /** Resume previously stopped optimization with current parameters. * \sa StopOptimization */ @@ -98,12 +98,12 @@ public: itkGetConstReferenceMacro(Gradient, DerivativeType); /** Get the reason for termination */ - virtual const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: RegularStepGradientDescentBaseOptimizer(); virtual ~RegularStepGradientDescentBaseOptimizer() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Advance one step following the gradient direction * This method verifies if a change in direction is required diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkRegularStepGradientDescentOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkRegularStepGradientDescentOptimizer.h index 197e9514e64809663a0770861f6e35687f86890b..54bf2a7cdc95e696c6e7070c9bd23a3e5f39b08c 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkRegularStepGradientDescentOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkRegularStepGradientDescentOptimizer.h @@ -61,7 +61,7 @@ protected: * \sa AdvanceOneStep */ virtual void StepAlongGradient( double factor, - const DerivativeType & transformedGradient); + const DerivativeType & transformedGradient) ITK_OVERRIDE; private: RegularStepGradientDescentOptimizer(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSPSAOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSPSAOptimizer.h index 344f5e47939dd2ec232161f53eb4ce59e131e7f4..5d59d4a50c0c4306055f67f866115f8a185b3d0c 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSPSAOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSPSAOptimizer.h @@ -69,7 +69,7 @@ public: virtual void AdvanceOneStep(void); /** Start optimization. */ - void StartOptimization(void); + virtual void StartOptimization(void) ITK_OVERRIDE; /** Resume previously stopped optimization with current parameters * \sa StopOptimization. */ @@ -194,7 +194,7 @@ public: itkGetConstMacro(Tolerance, double); /** Get the reason for termination */ - const std::string GetStopConditionDescription() const; + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; protected: @@ -202,7 +202,7 @@ protected: virtual ~SPSAOptimizer() {} /** PrintSelf method. */ - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Variables updated during optimization */ DerivativeType m_Gradient; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedNonLinearOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedNonLinearOptimizer.h index fa565ffba6a30b2d6f1c6504092684b1ee60b783..464f5974c4797b6ee967538eee5b9e6ad7b41e1c 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedNonLinearOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedNonLinearOptimizer.h @@ -76,7 +76,7 @@ public: protected: SingleValuedNonLinearOptimizer(); virtual ~SingleValuedNonLinearOptimizer() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; CostFunctionPointer m_CostFunction; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedNonLinearVnlOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedNonLinearVnlOptimizer.h index f2815ed40c7a57c873bd256daf010ef058422cc4..fe3aae0540754a2afceb60c7732e2ecaca98d18a 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedNonLinearVnlOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedNonLinearVnlOptimizer.h @@ -104,7 +104,7 @@ protected: CostFunctionAdaptorType * GetNonConstCostFunctionAdaptor(void) const; /** Print out internal state */ - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: /** Callback function for the Command Observer */ diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedVnlCostFunctionAdaptor.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedVnlCostFunctionAdaptor.h index 20f7400d2a1dc5515877ff5b6c4289ba834a5d6c..e16c1bdf8fd86f52eb7593e65b22295ee29f8b7b 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedVnlCostFunctionAdaptor.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkSingleValuedVnlCostFunctionAdaptor.h @@ -71,16 +71,16 @@ public: { return m_CostFunction; } /** Delegate computation of the value to the CostFunction. */ - virtual InternalMeasureType f(const InternalParametersType & inparameters); + virtual InternalMeasureType f(const InternalParametersType & inparameters) ITK_OVERRIDE; /** Delegate computation of the gradient to the costFunction. */ virtual void gradf(const InternalParametersType & inparameters, - InternalDerivativeType & gradient); + InternalDerivativeType & gradient) ITK_OVERRIDE; /** Delegate computation of value and gradient to the costFunction. */ virtual void compute(const InternalParametersType & x, InternalMeasureType *f, - InternalDerivativeType *g); + InternalDerivativeType *g) ITK_OVERRIDE; /** Convert external derviative measures into internal type */ void ConvertExternalToInternalGradient( diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkVersorRigid3DTransformOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkVersorRigid3DTransformOptimizer.h index ef64e50682e1c8ca2dea3aff5f1c2748b234a5c6..09c42617a5d68e25627dc95761ff7fdf824db102 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkVersorRigid3DTransformOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkVersorRigid3DTransformOptimizer.h @@ -73,7 +73,7 @@ public: /** Advance one step following the gradient direction. */ virtual void StepAlongGradient(double factor, - const DerivativeType & transformedGradient); + const DerivativeType & transformedGradient) ITK_OVERRIDE; protected: VersorRigid3DTransformOptimizer() {} diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkVersorTransformOptimizer.h b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkVersorTransformOptimizer.h index 4359bd25f5d60edd164c8a7cc038c01431cc56b3..27ceb7a7e14374c86339488d1e621431edb5a3e9 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/include/itkVersorTransformOptimizer.h +++ b/Utilities/ITK/Modules/Numerics/Optimizers/include/itkVersorTransformOptimizer.h @@ -71,7 +71,7 @@ public: /** Advance one step following the gradient direction. */ virtual void StepAlongGradient(double factor, - const DerivativeType & transformedGradient); + const DerivativeType & transformedGradient) ITK_OVERRIDE; protected: VersorTransformOptimizer() {} diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkAmoebaOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkAmoebaOptimizer.cxx index 358edd7525c062f5f4d15dee96867fe03dcbe451..a5613d254a14cb3d62cace80e92597e882897967 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkAmoebaOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkAmoebaOptimizer.cxx @@ -32,7 +32,7 @@ AmoebaOptimizer this->m_AutomaticInitialSimplex = true; this->m_InitialSimplexDelta.Fill( NumericTraits< ParametersType::ValueType >::One ); this->m_OptimizeWithRestarts = false; - this->m_VnlOptimizer = NULL; + this->m_VnlOptimizer = ITK_NULLPTR; } @@ -78,7 +78,7 @@ AmoebaOptimizer SingleValuedNonLinearVnlOptimizer::CostFunctionAdaptorType *costFunction = this->GetNonConstCostFunctionAdaptor(); - if( costFunction != NULL ) + if( costFunction != ITK_NULLPTR ) { if( static_cast<unsigned int>(costFunction->get_number_of_unknowns()) != numberOfParameters ) @@ -310,7 +310,7 @@ AmoebaOptimizer ::ValidateSettings() { //we have to have a cost function - if( GetCostFunctionAdaptor() == NULL ) + if( GetCostFunctionAdaptor() == ITK_NULLPTR ) { itkExceptionMacro(<<"NULL cost function") } diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkConjugateGradientOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkConjugateGradientOptimizer.cxx index be4207fb2c4d4fae32e5580f0587cc94ba3ac379..da1da76400389c2863a4061aff7a6f85a6fb5575 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkConjugateGradientOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkConjugateGradientOptimizer.cxx @@ -29,7 +29,7 @@ ConjugateGradientOptimizer ::ConjugateGradientOptimizer() { m_OptimizerInitialized = false; - m_VnlOptimizer = 0; + m_VnlOptimizer = ITK_NULLPTR; } /** diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkCumulativeGaussianCostFunction.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkCumulativeGaussianCostFunction.cxx index 9af141a0a48036745e870fb9d1dd0371642f006a..1ed9615f53e7b825e96726267cb1aec86451e415 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkCumulativeGaussianCostFunction.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkCumulativeGaussianCostFunction.cxx @@ -65,9 +65,9 @@ CumulativeGaussianCostFunction double fitError = 0.0; for ( int i = 0; i < (int)( numberOfElements ); i++ ) { - fitError += vcl_pow( ( setTestArray->get(i) - m_OriginalDataArray->get(i) ), 2 ); + fitError += std::pow( ( setTestArray->get(i) - m_OriginalDataArray->get(i) ), 2 ); } - return ( vcl_sqrt( ( 1 / numberOfElements ) * fitError ) ); + return ( std::sqrt( ( 1 / numberOfElements ) * fitError ) ); } double @@ -192,7 +192,7 @@ CumulativeGaussianCostFunction - parameters.get(2) ) * ( EvaluateCumulativeGaussian( ( i - parameters.get(0) ) - / ( parameters.get(1) * vcl_sqrt(2.0) ) ) + 1 ) / 2 ); + / ( parameters.get(1) * std::sqrt(2.0) ) ) + 1 ) / 2 ); } return m_Measure; @@ -211,7 +211,7 @@ CumulativeGaussianCostFunction - parameters.get(2) ) * ( EvaluateCumulativeGaussian( ( i - parameters.get(0) ) - / ( parameters.get(1) * vcl_sqrt(2.0) ) ) + 1 ) / 2 ) ); + / ( parameters.get(1) * std::sqrt(2.0) ) ) + 1 ) / 2 ) ); } return m_MeasurePointer; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkCumulativeGaussianOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkCumulativeGaussianOptimizer.cxx index 319f31ac2417f523183473bf3d0421e2d461cbf0..5f843a273c07517095123626427cc88c12fa8553 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkCumulativeGaussianOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkCumulativeGaussianOptimizer.cxx @@ -36,8 +36,8 @@ CumulativeGaussianOptimizer::CumulativeGaussianOptimizer() m_DifferenceTolerance = 1e-10; m_Verbose = 0; m_FitError = 0; - m_FinalSampledArray = NULL; - m_CumulativeGaussianArray = NULL; + m_FinalSampledArray = ITK_NULLPTR; + m_CumulativeGaussianArray = ITK_NULLPTR; m_StopConditionDescription << this->GetNameOfClass() << ": Constructed"; } @@ -61,7 +61,7 @@ CumulativeGaussianOptimizer for ( int i = 0; i < (int)( extendedArray->GetNumberOfElements() ); i++ ) { - extendedArray->put( i, amplitude * vcl_exp( -( vcl_pow( ( i - mean ), 2 ) / ( 2 * vcl_pow(sd, 2) ) ) ) ); + extendedArray->put( i, amplitude * std::exp( -( std::pow( ( i - mean ), 2 ) / ( 2 * std::pow(sd, 2) ) ) ) ); } // Then insert the originalArray over the middle section of extendedArray. for ( int i = 0; i < (int)( originalArray->GetNumberOfElements() ); i++ ) @@ -141,12 +141,12 @@ CumulativeGaussianOptimizer averageSumOfSquaredDifferences = FindAverageSumOfSquaredDifferences(extendedArray, extendedArrayCopy); // Stop if there is a very very very small change between iterations. - if ( vcl_fabs(temp - averageSumOfSquaredDifferences) <= m_DifferenceTolerance ) + if ( std::fabs(temp - averageSumOfSquaredDifferences) <= m_DifferenceTolerance ) { m_StopConditionDescription.str(""); m_StopConditionDescription << this->GetNameOfClass() << ": " << "Change between iterations (" - << vcl_fabs(temp - averageSumOfSquaredDifferences) + << std::fabs(temp - averageSumOfSquaredDifferences) << ") is less than DifferenceTolerance (" << m_DifferenceTolerance << ")."; @@ -197,15 +197,15 @@ void CumulativeGaussianOptimizer // Calculate the standard deviation for ( int i = 0; i < (int)( array->GetNumberOfElements() ); i++ ) { - m_ComputedStandardDeviation += array->get(i) * vcl_pow( ( i - m_ComputedMean ), 2 ); + m_ComputedStandardDeviation += array->get(i) * std::pow( ( i - m_ComputedMean ), 2 ); } - m_ComputedStandardDeviation = vcl_sqrt(m_ComputedStandardDeviation / sum); + m_ComputedStandardDeviation = std::sqrt(m_ComputedStandardDeviation / sum); // For the ERF, sum is the difference between the lower and upper intensities. m_ComputedTransitionHeight = sum; // Calculate the amplitude. - m_ComputedAmplitude = sum / ( m_ComputedStandardDeviation * vcl_sqrt(2 * vnl_math::pi) ); + m_ComputedAmplitude = sum / ( m_ComputedStandardDeviation * std::sqrt(2 * vnl_math::pi) ); } void @@ -244,7 +244,7 @@ CumulativeGaussianOptimizer if ( i < startingPointForInsertion || i >= startingPointForInsertion + (int)( originalArray->GetNumberOfElements() ) ) { - extendedArray->put( i, amplitude * vcl_exp( -( vcl_pow( ( i - mean ), 2 ) / ( 2 * vcl_pow(sd, 2) ) ) ) ); + extendedArray->put( i, amplitude * std::exp( -( std::pow( ( i - mean ), 2 ) / ( 2 * std::pow(sd, 2) ) ) ) ); } } return extendedArray; @@ -298,8 +298,8 @@ CumulativeGaussianOptimizer for ( int i = 0; i < sampledGaussianArraySize; i++ ) { sampledGaussianArray->put( i, m_ComputedAmplitude - * vcl_exp( -( vcl_pow( ( i - m_ComputedMean ), - 2 ) / ( 2 * vcl_pow(m_ComputedStandardDeviation, 2) ) ) ) ); + * std::exp( -( std::pow( ( i - m_ComputedMean ), + 2 ) / ( 2 * std::pow(m_ComputedStandardDeviation, 2) ) ) ) ); } // Add 0.5 to the mean of the sampled Gaussian curve to make up for the 0.5 // shift during derivation, then take the integral of the Gaussian sample diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkFRPROptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkFRPROptimizer.cxx index 96ffd265da5130f29be637115c321d15ec826f87..c446ca2de1d1795a58a163d251bf3acc45e2a87e 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkFRPROptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkFRPROptimizer.cxx @@ -56,7 +56,7 @@ FRPROptimizer { len += ( *xi )[i] * ( *xi )[i]; } - len = vcl_sqrt( len / this->GetSpaceDimension() ); + len = std::sqrt( len / this->GetSpaceDimension() ); for ( unsigned int i = 0; i < this->GetSpaceDimension(); i++ ) { ( *xi )[i] /= len; @@ -150,8 +150,8 @@ FRPROptimizer fret = fp; this->LineOptimize(&p, xi, &fret, tempCoord); - if ( 2.0 * vcl_abs(fret - fp) <= - this->GetValueTolerance() * ( vcl_abs(fret) + vcl_abs(fp) + FRPR_TINY ) ) + if ( 2.0 * std::abs(fret - fp) <= + this->GetValueTolerance() * ( std::abs(fret) + std::abs(fp) + FRPR_TINY ) ) { if ( limitCount < this->GetSpaceDimension() ) { diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkGradientDescentOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkGradientDescentOptimizer.cxx index 111d41953314ec7f1c844b97350d479f830f1f94..945f8fe2e1deee9afdee1d327031d1cd11fee7de 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkGradientDescentOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkGradientDescentOptimizer.cxx @@ -26,16 +26,17 @@ namespace itk * Constructor */ GradientDescentOptimizer -::GradientDescentOptimizer() +::GradientDescentOptimizer() : + m_Maximize(false), + m_LearningRate(1.0), + m_Stop(false), + m_Value(0.0), + m_StopCondition(MaximumNumberOfIterations), + m_NumberOfIterations(100), + m_CurrentIteration(0) { itkDebugMacro("Constructor"); - m_LearningRate = 1.0; - m_NumberOfIterations = 100; - m_CurrentIteration = 0; - m_Maximize = false; - m_Value = 0.0; - m_StopCondition = MaximumNumberOfIterations; m_StopConditionDescription << this->GetNameOfClass() << ": "; } diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLBFGSBOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLBFGSBOptimizer.cxx index e767cb81b9a865dd41f424d9c33dcc19b9dba19a..3c4da8017165d9a682a2a91f621eff91fc734e14 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLBFGSBOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLBFGSBOptimizer.cxx @@ -45,7 +45,7 @@ public: LBFGSBOptimizer * const itkObj); /** Handle new iteration event */ - virtual bool report_iter(); + virtual bool report_iter() ITK_OVERRIDE; private: LBFGSBOptimizer * const m_ItkObj; @@ -65,7 +65,7 @@ LBFGSBOptimizer m_MaximumNumberOfCorrections(5), m_CurrentIteration(0), m_InfinityNormOfProjectedGradient(0.0), - m_VnlOptimizer(0) + m_VnlOptimizer(ITK_NULLPTR) { m_LowerBound = InternalBoundValueType(0); m_UpperBound = InternalBoundValueType(0); diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLBFGSOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLBFGSOptimizer.cxx index a448de70b4893e738c9860bb1bc2e9a1f62376cc..11df5ce0f4381cf785ef8616438c856b262780c8 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLBFGSOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLBFGSOptimizer.cxx @@ -29,7 +29,7 @@ LBFGSOptimizer ::LBFGSOptimizer() { m_OptimizerInitialized = false; - m_VnlOptimizer = 0; + m_VnlOptimizer = ITK_NULLPTR; m_Trace = false; m_MaximumNumberOfFunctionEvaluations = 2000; m_GradientConvergenceTolerance = 1e-5; @@ -221,6 +221,8 @@ LBFGSOptimizer m_VnlOptimizer->default_step_length = m_DefaultStepLength; m_OptimizerInitialized = true; + + this->Modified(); } /** diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLevenbergMarquardtOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLevenbergMarquardtOptimizer.cxx index c326ae3010a0e5a50141836d4fc0f2d5611e5d45..3e361a14ffa9d31854f3a74fb92bb7a2937359eb 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLevenbergMarquardtOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkLevenbergMarquardtOptimizer.cxx @@ -29,7 +29,7 @@ LevenbergMarquardtOptimizer ::LevenbergMarquardtOptimizer() { m_OptimizerInitialized = false; - m_VnlOptimizer = 0; + m_VnlOptimizer = ITK_NULLPTR; m_NumberOfIterations = 2000; m_ValueTolerance = 1e-8; m_GradientTolerance = 1e-5; diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkMultipleValuedNonLinearOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkMultipleValuedNonLinearOptimizer.cxx index 19ac71acc6a60195c49e744425e94cf59b89a3e1..af257b61311b3241cd6ee2a06f609c737d0ab090 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkMultipleValuedNonLinearOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkMultipleValuedNonLinearOptimizer.cxx @@ -25,7 +25,7 @@ namespace itk MultipleValuedNonLinearOptimizer ::MultipleValuedNonLinearOptimizer() { - m_CostFunction = 0; + m_CostFunction = ITK_NULLPTR; } /** diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkMultipleValuedNonLinearVnlOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkMultipleValuedNonLinearVnlOptimizer.cxx index 7e98661e7664aac3f5c73789ebede031ce68c46c..fcd83f6f6235ff7cd52886acaf4c22e0435876fc 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkMultipleValuedNonLinearVnlOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkMultipleValuedNonLinearVnlOptimizer.cxx @@ -28,7 +28,7 @@ namespace itk MultipleValuedNonLinearVnlOptimizer ::MultipleValuedNonLinearVnlOptimizer() { - m_CostFunctionAdaptor = 0; + m_CostFunctionAdaptor = ITK_NULLPTR; m_UseGradient = true; m_Command = CommandType::New(); m_Command->SetCallbackFunction(this, @@ -45,7 +45,7 @@ MultipleValuedNonLinearVnlOptimizer ::~MultipleValuedNonLinearVnlOptimizer() { delete m_CostFunctionAdaptor; - m_CostFunctionAdaptor = 0; + m_CostFunctionAdaptor = ITK_NULLPTR; } void diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkOnePlusOneEvolutionaryOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkOnePlusOneEvolutionaryOptimizer.cxx index 28407cee0c9bedd639d565a87abf1d7377a1c3cc..7d2b2e9e488a313c91903e2c96ceb702c6673551 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkOnePlusOneEvolutionaryOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkOnePlusOneEvolutionaryOptimizer.cxx @@ -30,11 +30,11 @@ OnePlusOneEvolutionaryOptimizer m_Maximize = false; m_Epsilon = (double)1.5e-4; - m_RandomGenerator = 0; + m_RandomGenerator = ITK_NULLPTR; m_Initialized = false; m_GrowthFactor = 1.05; - m_ShrinkFactor = vcl_pow(m_GrowthFactor, -0.25); + m_ShrinkFactor = std::pow(m_GrowthFactor, -0.25); m_InitialRadius = 1.01; m_MaximumIteration = 100; m_Stop = false; @@ -75,7 +75,7 @@ OnePlusOneEvolutionaryOptimizer } if ( shrink == -1 ) { - m_ShrinkFactor = vcl_pow(m_GrowthFactor, -0.25); + m_ShrinkFactor = std::pow(m_GrowthFactor, -0.25); } else { diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkParticleSwarmOptimizerBase.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkParticleSwarmOptimizerBase.cxx index 08f714a0e09bdf158b35faa49aae612e9604661c..55742f3a9bec5a645f3a0f3d7383426922559b3c 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkParticleSwarmOptimizerBase.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkParticleSwarmOptimizerBase.cxx @@ -23,7 +23,9 @@ namespace itk ParticleSwarmOptimizerBase -::ParticleSwarmOptimizerBase(void) +::ParticleSwarmOptimizerBase(void): + m_FunctionBestValue(0), + m_IterationIndex(0) { this->m_PrintSwarm = false; this->m_InitializeNormalDistribution = false; @@ -323,7 +325,7 @@ ParticleSwarmOptimizerBase unsigned int i,n; //we have to have a cost function - if( GetCostFunction() == NULL ) + if( GetCostFunction() == ITK_NULLPTR ) { itkExceptionMacro(<<"NULL cost function") } diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkPowellOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkPowellOptimizer.cxx index 4d34f07152aedc3246844c83245f07e51e40c120..c0f0a8e22df0456fb0bfd9d216ef6ae9a58ffa22 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkPowellOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkPowellOptimizer.cxx @@ -184,7 +184,7 @@ PowellOptimizer // Compute the golden ratio as a constant to be // used when extrapolating the bracket // - const double goldenRatio = ( 1.0 + vcl_sqrt(5.0) ) / 2.0; + const double goldenRatio = ( 1.0 + std::sqrt(5.0) ) / 2.0; // // Get the value of the function for point x2 @@ -254,7 +254,7 @@ PowellOptimizer x = bx; w = bx; - const double goldenSectionRatio = ( 3.0 - vcl_sqrt(5.0) ) / 2; /* Gold + const double goldenSectionRatio = ( 3.0 - std::sqrt(5.0) ) / 2; /* Gold section ratio */ const double POWELL_TINY = 1.0e-20; @@ -278,10 +278,10 @@ PowellOptimizer double tolerance1; double tolerance2; - tolerance1 = m_StepTolerance * vcl_fabs(x) + POWELL_TINY; + tolerance1 = m_StepTolerance * std::fabs(x) + POWELL_TINY; tolerance2 = 2.0 * tolerance1; - if ( vcl_fabs(x - middle_range) <= ( tolerance2 - 0.5 * ( b - a ) ) + if ( std::fabs(x - middle_range) <= ( tolerance2 - 0.5 * ( b - a ) ) || 0.5 * ( b - a ) < m_StepTolerance ) { *extX = x; @@ -297,7 +297,7 @@ PowellOptimizer new_step = goldenSectionRatio * ( x < middle_range ? b - x : a - x ); /* Decide if the interpolation can be tried */ - if ( vcl_fabs(x - w) >= tolerance1 ) /* If x and w are distinct */ + if ( std::fabs(x - w) >= tolerance1 ) /* If x and w are distinct */ { double t; t = ( x - w ) * ( functionValueOfX - functionValueOfV ); @@ -321,7 +321,7 @@ PowellOptimizer /* Chec if x+p/q falls in [a,b] and not too close to a and b and isn't too large */ - if ( vcl_fabs(p) < vcl_fabs(new_step * q) + if ( std::fabs(p) < std::fabs(new_step * q) && p > q * ( a - x + 2 * tolerance1 ) && p < q * ( b - x - 2 * tolerance1 ) ) { @@ -333,7 +333,7 @@ PowellOptimizer } /* Adjust the step to be not less than tolerance*/ - if ( vcl_fabs(new_step) < tolerance1 ) + if ( std::fabs(new_step) < tolerance1 ) { if ( new_step > 0.0 ) { @@ -477,15 +477,15 @@ PowellOptimizer this->SetCurrentLinePoint(xx, fx); p = this->GetCurrentPosition(); - if ( vcl_fabs(fptt - fx) > del ) + if ( std::fabs(fptt - fx) > del ) { - del = vcl_fabs(fptt - fx); + del = std::fabs(fptt - fx); ibig = i; } } - if ( 2.0 * vcl_fabs(fp - fx) - <= m_ValueTolerance * ( vcl_fabs(fp) + vcl_fabs(fx) ) ) + if ( 2.0 * std::fabs(fp - fx) + <= m_ValueTolerance * ( std::fabs(fp) + std::fabs(fx) ) ) { m_StopConditionDescription << "Cost function values at the current parameter (" << fx diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkRegularStepGradientDescentBaseOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkRegularStepGradientDescentBaseOptimizer.cxx index 35f8a08dee5ac61a36df8b57694080a56b471670..23908cc47006b9e3281b57a55ed171418900a555 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkRegularStepGradientDescentBaseOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkRegularStepGradientDescentBaseOptimizer.cxx @@ -26,7 +26,8 @@ namespace itk * Constructor */ RegularStepGradientDescentBaseOptimizer -::RegularStepGradientDescentBaseOptimizer() +::RegularStepGradientDescentBaseOptimizer(): + m_Stop(false) { itkDebugMacro("Constructor"); @@ -37,7 +38,7 @@ RegularStepGradientDescentBaseOptimizer m_CurrentIteration = 0; m_Value = 0; m_Maximize = false; - m_CostFunction = 0; + m_CostFunction = ITK_NULLPTR; m_CurrentStepLength = 0; m_StopCondition = Unknown; m_Gradient.Fill(0.0f); @@ -165,13 +166,11 @@ RegularStepGradientDescentBaseOptimizer if ( m_RelaxationFactor < 0.0 ) { itkExceptionMacro(<< "Relaxation factor must be positive. Current value is " << m_RelaxationFactor); - return; } if ( m_RelaxationFactor >= 1.0 ) { itkExceptionMacro(<< "Relaxation factor must less than 1.0. Current value is " << m_RelaxationFactor); - return; } // Make sure the scales have been set properly @@ -198,7 +197,7 @@ RegularStepGradientDescentBaseOptimizer magnitudeSquare += weighted * weighted; } - const double gradientMagnitude = vcl_sqrt(magnitudeSquare); + const double gradientMagnitude = std::sqrt(magnitudeSquare); if ( gradientMagnitude < m_GradientMagnitudeTolerance ) { diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSPSAOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSPSAOptimizer.cxx index d3235e84f57c21c34171842675e1a48a4e1a0eed..6b8e39777087547c6e78f65efd08c1124e200553 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSPSAOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSPSAOptimizer.cxx @@ -28,7 +28,8 @@ namespace itk * ************************* Constructor ************************ */ SPSAOptimizer -::SPSAOptimizer() +::SPSAOptimizer(): + m_Stop(false) { itkDebugMacro("Constructor"); @@ -289,7 +290,7 @@ double SPSAOptimizer ::Compute_a(SizeValueType k) const { return static_cast< double >( - m_Sa / vcl_pow(m_A + k + 1, m_Alpha) ); + m_Sa / std::pow(m_A + k + 1, m_Alpha) ); } // end Compute_a /** @@ -303,7 +304,7 @@ double SPSAOptimizer ::Compute_c(SizeValueType k) const { return static_cast< double >( - m_Sc / vcl_pow(k + 1, m_Gamma) ); + m_Sc / std::pow(k + 1, m_Gamma) ); } // end Compute_c /** @@ -482,14 +483,14 @@ SPSAOptimizer::GuessParameters( this->ComputeGradient(initialPosition, m_Gradient); for ( unsigned int j = 0; j < spaceDimension; j++ ) { - averageAbsoluteGradient[j] += vcl_fabs(m_Gradient[j]); + averageAbsoluteGradient[j] += std::fabs(m_Gradient[j]); } } // end for ++n averageAbsoluteGradient /= static_cast< double >( numberOfGradientEstimates ); /** Set a in order to make the first steps approximately have an initialStepSize */ - this->SetSa( initialStepSize * vcl_pow(m_A + 1.0, m_Alpha) + this->SetSa( initialStepSize * std::pow(m_A + 1.0, m_Alpha) / averageAbsoluteGradient.max_value() ); } //end GuessParameters diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSingleValuedNonLinearOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSingleValuedNonLinearOptimizer.cxx index 2f53d42f67fcad110e70fdf525356ce9a184cd96..c25eedb143ceec99cd6de3302c8313c9f283e6ae 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSingleValuedNonLinearOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSingleValuedNonLinearOptimizer.cxx @@ -25,7 +25,7 @@ namespace itk SingleValuedNonLinearOptimizer ::SingleValuedNonLinearOptimizer() { - m_CostFunction = 0; + m_CostFunction = ITK_NULLPTR; } /** diff --git a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSingleValuedNonLinearVnlOptimizer.cxx b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSingleValuedNonLinearVnlOptimizer.cxx index 9b2f38dab82265efc9353e8200ecd00290ac0daa..4c74649179bbef02378ce7f0e7cdb0a6cc77e802 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSingleValuedNonLinearVnlOptimizer.cxx +++ b/Utilities/ITK/Modules/Numerics/Optimizers/src/itkSingleValuedNonLinearVnlOptimizer.cxx @@ -26,7 +26,7 @@ namespace itk SingleValuedNonLinearVnlOptimizer ::SingleValuedNonLinearVnlOptimizer() { - m_CostFunctionAdaptor = 0; + m_CostFunctionAdaptor = ITK_NULLPTR; m_Maximize = false; m_Command = CommandType::New(); m_Command->SetCallbackFunction(this, @@ -41,7 +41,7 @@ SingleValuedNonLinearVnlOptimizer ::~SingleValuedNonLinearVnlOptimizer() { delete m_CostFunctionAdaptor; - m_CostFunctionAdaptor = 0; + m_CostFunctionAdaptor = ITK_NULLPTR; } void diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/CMakeLists.txt b/Utilities/ITK/Modules/Numerics/Optimizersv4/CMakeLists.txt index d6d34f85266eb731ec0f5e7705e84eacc814ebf1..cf81a731339a0ca8237d989119e1ce8721446675 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/CMakeLists.txt +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/CMakeLists.txt @@ -1,2 +1,3 @@ project(ITKOptimizersv4) +set(ITKOptimizersv4_LIBRARIES ITKOptimizersv4) itk_module_impl() diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkAmoebaOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkAmoebaOptimizerv4.h new file mode 100644 index 0000000000000000000000000000000000000000..8a18b2d6fcd987213c7067d6362de44f15450cef --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkAmoebaOptimizerv4.h @@ -0,0 +1,162 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkAmoebaOptimizerv4_h +#define __itkAmoebaOptimizerv4_h + +#include "itkSingleValuedNonLinearVnlOptimizerv4.h" +#include "vnl/algo/vnl_amoeba.h" + +namespace itk +{ +/** \class AmoebaOptimizerv4 + * \brief Wrap of the vnl_amoeba algorithm + * + * AmoebaOptimizerv4 is a wrapper around the vnl_amoeba algorithm which + * is an implementation of the Nelder-Meade downhill simplex + * problem. For most problems, it is a few times slower than a + * Levenberg-Marquardt algorithm but does not require derivatives of + * its cost function. It works by creating a simplex (n+1 points in + * ND space). The cost function is evaluated at each corner of the + * simplex. The simplex is then modified (by reflecting a corner + * about the opposite edge, by shrinking the entire simplex, by + * contracting one edge of the simplex, or by expanding the simplex) + * in searching for the minimum of the cost function. + * + * The methods AutomaticInitialSimplex() and SetInitialSimplexDelta() + * control whether the optimizer defines the initial simplex + * automatically (by constructing a very small simplex around the + * initial position) or uses a user supplied simplex size. + * + * The method SetOptimizeWithRestarts() indicates that the amoeabe algorithm + * should be rerun after if converges. This heuristic increases the chances + * of escaping from a local optimum. Each time the simplex is initialized with + * the best solution obtained by the previous runs. The edge length is half of + * that from the previous iteration. The heuristic is terminated if the total + * number of iterations is greater-equal than the maximal number of iterations + * (SetNumberOfIterations) or the difference between the current function + * value and the best function value is less than a threshold + * (SetFunctionConvergenceTolerance) and + * max(|best_parameters_i - current_parameters_i|) is less than a threshold + * (SetParametersConvergenceTolerance). + * + * \ingroup ITKOptimizersv4 + */ +class AmoebaOptimizerv4: + public SingleValuedNonLinearVnlOptimizerv4 +{ +public: + /** Standard "Self" typedef. */ + typedef AmoebaOptimizerv4 Self; + typedef SingleValuedNonLinearVnlOptimizerv4 Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(AmoebaOptimizerv4, SingleValuedNonLinearVnlOptimizerv4); + + /** Parameters type. + * It defines a position in the optimization search space. */ + typedef Superclass::ParametersType ParametersType; + + /** InternalParameters typedef. */ + typedef vnl_vector< double > InternalParametersType; + + /** Start optimization with an initial value. */ + virtual void StartOptimization(bool doOnlyInitialization = false) ITK_OVERRIDE; + + /** Plug in a Cost Function into the optimizer */ + virtual void SetMetric(MetricType *metric) ITK_OVERRIDE; + + /** Set/Get the mode which determines how the amoeba algorithm + * defines the initial simplex. Default is + * AutomaticInitialSimplexOn. If AutomaticInitialSimplex is on, the + * initial simplex is created with a default size. If + * AutomaticInitialSimplex is off, then InitialSimplexDelta will be + * used to define the initial simplex, setting the ith corner of the + * simplex as [x0[0], x0[1], ..., x0[i]+InitialSimplexDelta[i], ..., + * x0[d-1]]. */ + itkSetMacro(AutomaticInitialSimplex, bool); + itkBooleanMacro(AutomaticInitialSimplex); + itkGetConstMacro(AutomaticInitialSimplex, bool); + + /** Set/Get the mode that determines if we want to use multiple runs of the + * Amoeba optimizer. If true, then the optimizer is rerun after it converges. + * The additional runs are performed using a simplex initialized with the + * best solution obtained by the previous runs. The edge length is half of + * that from the previous iteration. + */ + itkSetMacro(OptimizeWithRestarts, bool); + itkBooleanMacro(OptimizeWithRestarts); + itkGetConstMacro(OptimizeWithRestarts, bool); + + /** Set/Get the deltas that are used to define the initial simplex + * when AutomaticInitialSimplex is off. */ + void SetInitialSimplexDelta(ParametersType initialSimplexDelta, + bool automaticInitialSimplex = false); + itkGetConstMacro(InitialSimplexDelta, ParametersType); + + /** The optimization algorithm will terminate when the simplex + * diameter and the difference in cost function values at the corners of + * the simplex falls below user specified thresholds. The simplex + * diameter threshold is set via SetParametersConvergenceTolerance().*/ + itkSetMacro(ParametersConvergenceTolerance, double); + itkGetConstMacro(ParametersConvergenceTolerance, double); + + /** The optimization algorithm will terminate when the simplex + * diameter and the difference in cost function values at the corners of + * the simplex falls below user specified thresholds. The cost function + * convergence threshold is set via SetFunctionConvergenceTolerance().*/ + itkSetMacro(FunctionConvergenceTolerance, double); + itkGetConstMacro(FunctionConvergenceTolerance, double); + + /** Report the reason for stopping. */ + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; + + /** Method for getting access to the internal optimizer. */ + vnl_amoeba * GetOptimizer(void) const; + +protected: + AmoebaOptimizerv4(); + virtual ~AmoebaOptimizerv4(); + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + + typedef Superclass::CostFunctionAdaptorType CostFunctionAdaptorType; + +private: + /**Check that the settings are valid. If not throw an exception.*/ + void ValidateSettings(); + //purposely not implemented + AmoebaOptimizerv4(const Self &); + //purposely not implemented + void operator=(const Self &); + + ParametersType::ValueType m_ParametersConvergenceTolerance; + MeasureType m_FunctionConvergenceTolerance; + bool m_AutomaticInitialSimplex; + ParametersType m_InitialSimplexDelta; + bool m_OptimizeWithRestarts; + vnl_amoeba * m_VnlOptimizer; + + std::ostringstream m_StopConditionDescription; +}; +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkConvergenceMonitoringFunction.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkConvergenceMonitoringFunction.h index cb83284c88996a78b171396cf92304c8458555a9..6d537e50ebac4471cdd45634bb1be79f097e24d3 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkConvergenceMonitoringFunction.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkConvergenceMonitoringFunction.h @@ -98,7 +98,7 @@ protected: ~ConvergenceMonitoringFunction() {} - void PrintSelf( std::ostream & os, Indent indent ) const + virtual void PrintSelf( std::ostream & os, Indent indent ) const ITK_OVERRIDE { Superclass::PrintSelf( os, indent ); diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkExhaustiveOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkExhaustiveOptimizerv4.h new file mode 100644 index 0000000000000000000000000000000000000000..0d2defcd9c3bf9213015ddef1d1e4259d35191c6 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkExhaustiveOptimizerv4.h @@ -0,0 +1,180 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkExhaustiveOptimizerv4_h +#define __itkExhaustiveOptimizerv4_h + +#include "itkIntTypes.h" +#include "itkObjectToObjectOptimizerBase.h" + +namespace itk +{ +/** \class ExhaustiveOptimizerv4 + * \brief Optimizer that fully samples a grid on the parametric space. + * + * This optimizer is equivalent to an exahaustive search in a discrete grid + * defined over the parametric space. The grid is centered on the initial + * position. The subdivisions of the grid along each one of the dimensions + * of the parametric space is defined by an array of number of steps. + * + * A typical use is to plot the metric space to get an idea of how noisy it + * is. An example is given below, where it is desired to plot the metric + * space with respect to translations along x, y and z in a 3D registration + * application: + * Here it is assumed that the transform is Euler3DTransform. + * + * \code + * + * OptimizerType::StepsType steps( m_Transform->GetNumberOfParameters() ); + * steps[1] = 10; + * steps[2] = 10; + * steps[3] = 10; + * m_Optimizer->SetNumberOfSteps( steps ); + * m_Optimizer->SetStepLength( 2 ); + * + * \endcode + * + * The optimizer throws IterationEvents after every iteration. We use this to plot + * the metric space in an image as follows: + * + * \code + * + * if( itk::IterationEvent().CheckEvent(& event ) ) + * { + * IndexType index; + * index[0] = m_Optimizer->GetCurrentIndex()[0]; + * index[1] = m_Optimizer->GetCurrentIndex()[1]; + * index[2] = m_Optimizer->GetCurrentIndex()[2]; + * image->SetPixel( index, m_Optimizer->GetCurrentValue() ); + * } + * + * \endcode + * + * The image size is expected to be 11 x 11 x 11. + * + * If you wish to use different step lengths along each parametric axis, + * you can use the SetScales() method. This accepts an array, each element + * represents the number of subdivisions per step length. For instance scales + * of [0.5 1 4] along with a step length of 2 will cause the optimizer + * to search the metric space on a grid with x,y,z spacing of [1 2 8]. + * + * Physical dimensions of the grid are influenced by both the scales and + * the number of steps along each dimension, a side of the region is + * stepLength*(2*numberOfSteps[d]+1)*scaling[d]. + * + * \ingroup ITKOptimizersv4 + */ +template<typename TInternalComputationValueType> +class ExhaustiveOptimizerv4: + public ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> +{ +public: + /** Standard "Self" typedef. */ + typedef ExhaustiveOptimizerv4 Self; + typedef ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(ExhaustiveOptimizerv4, Superclass); + + /** Steps type */ + typedef Array< SizeValueType > StepsType; + + /** Measure type */ + typedef typename Superclass::MeasureType MeasureType; + + /** Parameters type */ + typedef typename Superclass::ParametersType ParametersType; + + /** Scales type */ + typedef typename Superclass::ScalesType ScalesType; + + virtual void StartOptimization(bool doOnlyInitialization = false) ITK_OVERRIDE; + + /** Start optimization */ + void StartWalking(void); + + /** Resume the optimization */ + void ResumeWalking(void); + + /** Stop optimization */ + void StopWalking(void); + + itkSetMacro(StepLength, double); + itkSetMacro(NumberOfSteps, StepsType); + itkGetConstReferenceMacro(StepLength, double); + itkGetConstReferenceMacro(NumberOfSteps, StepsType); + itkGetConstReferenceMacro(CurrentValue, MeasureType); + itkGetConstReferenceMacro(MaximumMetricValue, MeasureType); + itkGetConstReferenceMacro(MinimumMetricValue, MeasureType); + itkGetConstReferenceMacro(MinimumMetricValuePosition, ParametersType); + itkGetConstReferenceMacro(MaximumMetricValuePosition, ParametersType); + itkGetConstReferenceMacro(CurrentIndex, ParametersType); + + /** Get the reason for termination */ + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; + + /** Set the position to initialize the optimization. */ + void SetInitialPosition(const ParametersType & param); + + /** Get the position to initialize the optimization. */ + ParametersType & GetInitialPosition(void) + { + return m_InitialPosition; + } + +protected: + ExhaustiveOptimizerv4(); + virtual ~ExhaustiveOptimizerv4() {} + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + + /** Advance to the next grid position. */ + void AdvanceOneStep(void); + + void IncrementIndex(ParametersType & param); + +protected: + ParametersType m_InitialPosition; + MeasureType m_CurrentValue; + StepsType m_NumberOfSteps; + bool m_Stop; + unsigned int m_CurrentParameter; + double m_StepLength; + ParametersType m_CurrentIndex; + MeasureType m_MaximumMetricValue; + MeasureType m_MinimumMetricValue; + ParametersType m_MinimumMetricValuePosition; + ParametersType m_MaximumMetricValuePosition; + +private: + //purposely not implemented + ExhaustiveOptimizerv4(const Self &); + void operator=(const Self &); + + std::ostringstream m_StopConditionDescription; +}; +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkExhaustiveOptimizerv4.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkExhaustiveOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkExhaustiveOptimizerv4.hxx new file mode 100644 index 0000000000000000000000000000000000000000..64e1b38ac5d298c101cf6aabed069096eeb97090 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkExhaustiveOptimizerv4.hxx @@ -0,0 +1,260 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkExhaustiveOptimizerv4_hxx +#define __itkExhaustiveOptimizerv4_hxx + +#include "itkExhaustiveOptimizerv4.h" + +namespace itk +{ + +template<typename TInternalComputationValueType> +ExhaustiveOptimizerv4<TInternalComputationValueType> +::ExhaustiveOptimizerv4() : + m_CurrentValue(0), + m_NumberOfSteps(0), + m_Stop(false), + m_CurrentParameter(0), + m_StepLength(1.0), + m_CurrentIndex(0), + m_MaximumMetricValue(0.0), + m_MinimumMetricValue(0.0), + m_StopConditionDescription("") +{ + this->m_NumberOfIterations = 0; +} + +template<typename TInternalComputationValueType> +void +ExhaustiveOptimizerv4<TInternalComputationValueType> +::StartOptimization(bool /* doOnlyInitialization */) +{ + this->StartWalking(); +} + +template<typename TInternalComputationValueType> +void +ExhaustiveOptimizerv4<TInternalComputationValueType> +::StartWalking(void) +{ + itkDebugMacro("StartWalking"); + this->InvokeEvent( StartEvent() ); + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": Running"; + + ParametersType initialPos = this->m_Metric->GetParameters(); + m_MinimumMetricValuePosition = initialPos; + m_MaximumMetricValuePosition = initialPos; + + this->SetInitialPosition( initialPos ); // store the initial position + + MeasureType initialValue = this->m_Metric->GetValue(); + m_MaximumMetricValue = initialValue; + m_MinimumMetricValue = initialValue; + + this->m_CurrentIteration = 0; + this->m_NumberOfIterations = 1; + + const unsigned int spaceDimension = this->m_Metric->GetParameters().GetSize(); + + for ( unsigned int i = 0; i < spaceDimension; i++ ) + { + this->m_NumberOfIterations *= ( 2 * m_NumberOfSteps[i] + 1 ); + } + + m_CurrentIndex.SetSize(spaceDimension); + m_CurrentIndex.Fill(0); + + const ScalesType & scales = this->GetScales(); + // Make sure the scales have been set properly + if ( scales.size() != spaceDimension ) + { + itkExceptionMacro(<< "The size of Scales is " + << scales.size() + << ", but the NumberOfParameters is " + << spaceDimension + << "."); + } + + // Setup first grid position. + ParametersType position(spaceDimension); + for ( unsigned int i = 0; i < spaceDimension; i++ ) + { + position[i] = this->GetCurrentPosition()[i] - m_NumberOfSteps[i] * m_StepLength * scales[i]; + } + this->m_Metric->SetParameters(position); + + itkDebugMacro("Calling ResumeWalking"); + + this->ResumeWalking(); +} + +template<typename TInternalComputationValueType> +void +ExhaustiveOptimizerv4<TInternalComputationValueType> +::ResumeWalking(void) +{ + itkDebugMacro("ResumeWalk"); + m_Stop = false; + + while ( !m_Stop ) + { + ParametersType currentPosition = this->GetCurrentPosition(); + + if ( m_Stop ) + { + StopWalking(); + break; + } + + m_CurrentValue = this->m_Metric->GetValue(); + + if ( m_CurrentValue > m_MaximumMetricValue ) + { + m_MaximumMetricValue = m_CurrentValue; + m_MaximumMetricValuePosition = currentPosition; + } + if ( m_CurrentValue < m_MinimumMetricValue ) + { + m_MinimumMetricValue = m_CurrentValue; + m_MinimumMetricValuePosition = currentPosition; + } + + if ( m_Stop ) + { + this->StopWalking(); + break; + } + + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": Running. "; + m_StopConditionDescription << "@ index " << this->GetCurrentIndex() << " value is " << m_CurrentValue; + + this->InvokeEvent( IterationEvent() ); + this->AdvanceOneStep(); + this->m_CurrentIteration++; + } +} + +template<typename TInternalComputationValueType> +void +ExhaustiveOptimizerv4<TInternalComputationValueType> +::StopWalking(void) +{ + itkDebugMacro("StopWalking"); + + m_Stop = true; + this->InvokeEvent( EndEvent() ); +} + +template<typename TInternalComputationValueType> +void +ExhaustiveOptimizerv4<TInternalComputationValueType> +::AdvanceOneStep(void) +{ + itkDebugMacro("AdvanceOneStep"); + + const unsigned int spaceDimension = this->m_Metric->GetParameters().GetSize(); + + ParametersType newPosition(spaceDimension); + this->IncrementIndex(newPosition); + + itkDebugMacro(<< "new position = " << newPosition); + + this->m_Metric->SetParameters(newPosition); +} + +template<typename TInternalComputationValueType> +void +ExhaustiveOptimizerv4<TInternalComputationValueType> +::IncrementIndex(ParametersType & newPosition) +{ + unsigned int idx = 0; + const unsigned int spaceDimension = this->m_Metric->GetParameters().GetSize(); + + while ( idx < spaceDimension ) + { + m_CurrentIndex[idx]++; + + if ( m_CurrentIndex[idx] > ( 2 * m_NumberOfSteps[idx] ) ) + { + m_CurrentIndex[idx] = 0; + idx++; + } + else + { + break; + } + } + + if ( idx == spaceDimension ) + { + m_Stop = true; + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + m_StopConditionDescription << "Completed sampling of parametric space of size " << spaceDimension; + } + + const ScalesType & scales = this->GetScales(); + for ( unsigned int i = 0; i < spaceDimension; i++ ) + { + newPosition[i] = ( m_CurrentIndex[i] - m_NumberOfSteps[i] ) + * m_StepLength * scales[i] + + this->GetInitialPosition()[i]; + } +} + +template<typename TInternalComputationValueType> +const std::string +ExhaustiveOptimizerv4<TInternalComputationValueType> +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); +} + +template<typename TInternalComputationValueType> +void +ExhaustiveOptimizerv4<TInternalComputationValueType> +::SetInitialPosition(const ParametersType & param) +{ + m_InitialPosition = param; + this->Modified(); +} + +template<typename TInternalComputationValueType> +void +ExhaustiveOptimizerv4<TInternalComputationValueType> +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "InitialPosition = " << m_InitialPosition << std::endl; + os << indent << "CurrentValue = " << m_CurrentValue << std::endl; + os << indent << "NumberOfSteps = " << m_NumberOfSteps << std::endl; + os << indent << "Stop = " << m_Stop << std::endl; + os << indent << "CurrentParameter = " << m_CurrentParameter << std::endl; + os << indent << "StepLength = " << m_StepLength << std::endl; + os << indent << "CurrentIndex = " << m_CurrentIndex << std::endl; + os << indent << "MaximumMetricValue = " << m_MaximumMetricValue << std::endl; + os << indent << "MinimumMetricValue = " << m_MinimumMetricValue << std::endl; + os << indent << "MinimumMetricValuePosition = " << m_MinimumMetricValuePosition << std::endl; + os << indent << "MaximumMetricValuePosition = " << m_MaximumMetricValuePosition << std::endl; +} +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentLineSearchOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentLineSearchOptimizerv4.hxx index 185d4bab5da0acae08734eb3b0f74b9e0745804a..f45a36906d529bc3bf088f9e39a27e9cb7de1fb1 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentLineSearchOptimizerv4.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentLineSearchOptimizerv4.hxx @@ -131,7 +131,7 @@ GradientDescentLineSearchOptimizerv4Template<TInternalComputationValueType> { x = b - this->m_Resphi * ( b - a ); } - if ( vcl_abs( c - a ) < this->m_Epsilon * ( vcl_abs( b ) + vcl_abs( x ) ) ) + if ( std::abs( c - a ) < this->m_Epsilon * ( std::abs( b ) + std::abs( x ) ) ) { return ( c + a ) / 2; } diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerBasev4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerBasev4.h index 16996d3f6aad47a5a7c01e721e3355a9e453ff81..c979cf819229f5081c9b0115a30bd3acc71507da 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerBasev4.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerBasev4.h @@ -19,8 +19,7 @@ #define __itkGradientDescentOptimizerBasev4_h #include "itkObjectToObjectOptimizerBase.h" - -#include "itkObjectToObjectOptimizerBase.h" +#include "itkWindowConvergenceMonitoringFunction.h" #include "itkThreadedIndexedContainerPartitioner.h" #include "itkDomainThreader.h" @@ -57,14 +56,15 @@ public: UPDATE_PARAMETERS_ERROR, STEP_TOO_SMALL, CONVERGENCE_CHECKER_PASSED, + GRADIENT_MAGNITUDE_TOLEARANCE, OTHER_ERROR } StopConditionType; /** Stop condition return string type */ - typedef std::string StopConditionReturnStringType; + typedef typename Superclass::StopConditionReturnStringType StopConditionReturnStringType; /** Stop condition internal string type */ - typedef std::ostringstream StopConditionDescriptionType; + typedef typename Superclass::StopConditionDescriptionType StopConditionDescriptionType; /** It should be possible to derive the internal computation type from the class object. */ typedef TInternalComputationValueType InternalComputationValueType; @@ -74,7 +74,7 @@ public: typedef typename MetricType::Pointer MetricTypePointer; /** Derivative type */ - typedef typename MetricType::DerivativeType DerivativeType; + typedef typename Superclass::DerivativeType DerivativeType; /** Measure type */ typedef typename Superclass::MeasureType MeasureType; @@ -83,6 +83,10 @@ public: typedef typename Superclass::ParametersType ParametersType; + /** Type for the convergence checker */ + typedef itk::Function::WindowConvergenceMonitoringFunction<TInternalComputationValueType> + ConvergenceMonitoringType; + /** Get the most recent gradient values. */ itkGetConstReferenceMacro( Gradient, DerivativeType ); @@ -93,11 +97,14 @@ public: itkSetMacro(NumberOfIterations, SizeValueType); /** Get the number of iterations. */ - itkGetConstReferenceMacro(NumberOfIterations, SizeValueType); + itkGetConstMacro(NumberOfIterations, SizeValueType); /** Get the current iteration number. */ itkGetConstMacro(CurrentIteration, SizeValueType); + /** Start and run the optimization */ + virtual void StartOptimization( bool doOnlyInitialization = false ) ITK_OVERRIDE; + /** Resume optimization. * This runs the optimization loop, and allows continuation * of stopped optimization */ @@ -108,7 +115,7 @@ public: virtual void StopOptimization(void); /** Get the reason for termination */ - virtual const StopConditionReturnStringType GetStopConditionDescription() const; + virtual const StopConditionReturnStringType GetStopConditionDescription() const ITK_OVERRIDE; /** Modify the gradient in place, to advance the optimization. * This call performs a threaded modification for transforms with @@ -150,6 +157,39 @@ protected: GradientDescentOptimizerBasev4Template(); virtual ~GradientDescentOptimizerBasev4Template(); + /** Flag to control use of the ScalesEstimator (if set) for + * automatic learning step estimation at *each* iteration. + */ + bool m_DoEstimateLearningRateAtEachIteration; + + /** Flag to control use of the ScalesEstimator (if set) for + * automatic learning step estimation only *once*, during first iteration. + */ + bool m_DoEstimateLearningRateOnce; + + /** The maximum step size in physical units, to restrict learning rates. + * Only used with automatic learning rate estimation. + * It may be initialized either by calling SetMaximumStepSizeInPhysicalUnits + * manually or by using m_ScalesEstimator automatically, and the former has + * higher priority than the latter. See main documentation. + */ + TInternalComputationValueType m_MaximumStepSizeInPhysicalUnits; + + /** Flag to control using the convergence monitoring for stop condition. + * This flag should be always set to true except for regular step gradient + * descent optimizer that uses minimum step length to check the convergence. + */ + bool m_UseConvergenceMonitoring; + + /** Window size for the convergence checker. + * The convergence checker calculates convergence value by fitting to + * a window of the energy (metric value) profile. + */ + SizeValueType m_ConvergenceWindowSize; + + /** The convergence checker. */ + typename ConvergenceMonitoringType::Pointer m_ConvergenceMonitoring; + typename DomainThreader<ThreadedIndexedContainerPartitioner, Self>::Pointer m_ModifyGradientByScalesThreader; typename DomainThreader<ThreadedIndexedContainerPartitioner, Self>::Pointer m_ModifyGradientByLearningRateThreader; @@ -157,14 +197,13 @@ protected: bool m_Stop; StopConditionType m_StopCondition; StopConditionDescriptionType m_StopConditionDescription; - SizeValueType m_NumberOfIterations; - SizeValueType m_CurrentIteration; /** Current gradient */ DerivativeType m_Gradient; virtual void PrintSelf(std::ostream & os, Indent indent) const; private: + GradientDescentOptimizerBasev4Template( const Self & ); //purposely not implemented void operator=( const Self& ); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerBasev4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerBasev4.hxx index 8834159eb7f652ca3f477b1d24ae86fd92c4f57e..9a7cc222dc4af054ea231a57f20b5f2136e1ee1f 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerBasev4.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerBasev4.hxx @@ -28,7 +28,8 @@ namespace itk //------------------------------------------------------------------- template<typename TInternalComputationValueType> GradientDescentOptimizerBasev4Template<TInternalComputationValueType> -::GradientDescentOptimizerBasev4Template() +::GradientDescentOptimizerBasev4Template(): + m_Stop(false) { /** Threader for apply scales to gradient */ typename GradientDescentOptimizerBasev4ModifyGradientByScalesThreaderTemplate<TInternalComputationValueType>::Pointer modifyGradientByScalesThreader = @@ -40,10 +41,16 @@ GradientDescentOptimizerBasev4Template<TInternalComputationValueType> GradientDescentOptimizerBasev4ModifyGradientByLearningRateThreaderTemplate<TInternalComputationValueType>::New(); this->m_ModifyGradientByLearningRateThreader = modifyGradientByLearningRateThreader; - this->m_NumberOfIterations = 100; - this->m_CurrentIteration = 0; this->m_StopCondition = MAXIMUM_NUMBER_OF_ITERATIONS; this->m_StopConditionDescription << this->GetNameOfClass() << ": "; + + this->m_MaximumStepSizeInPhysicalUnits = NumericTraits<TInternalComputationValueType>::Zero; + + this->m_UseConvergenceMonitoring = true; + this->m_ConvergenceWindowSize = 50; + + this->m_DoEstimateLearningRateAtEachIteration = false; + this->m_DoEstimateLearningRateOnce = true; } //------------------------------------------------------------------- @@ -59,8 +66,6 @@ GradientDescentOptimizerBasev4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - os << indent << "Number of iterations: " << this->m_NumberOfIterations << std::endl; - os << indent << "Current iteration: " << this->m_CurrentIteration << std::endl; os << indent << "Stop condition:"<< this->m_StopCondition << std::endl; os << indent << "Stop condition description: " << this->m_StopConditionDescription.str() << std::endl; } @@ -118,6 +123,47 @@ GradientDescentOptimizerBasev4Template<TInternalComputationValueType> } } +template<typename TInternalComputationValueType> +void +GradientDescentOptimizerBasev4Template<TInternalComputationValueType> +::StartOptimization( bool doOnlyInitialization ) +{ + itkDebugMacro("StartOptimization"); + + /* Validate some settings */ + if ( this->m_ScalesEstimator.IsNotNull() && + this->m_DoEstimateLearningRateOnce && + this->m_DoEstimateLearningRateAtEachIteration ) + { + itkExceptionMacro("Both m_DoEstimateLearningRateOnce and " + "m_DoEstimateLearningRateAtEachIteration " + "are enabled. Not allowed. "); + } + + /* Estimate the parameter scales if requested. */ + if ( this->m_ScalesEstimator.IsNotNull() && this->m_DoEstimateScales ) + { + this->m_ScalesEstimator->EstimateScales(this->m_Scales); + itkDebugMacro( "Estimated scales = " << this->m_Scales ); + + /* If user hasn't set this, assign the default. */ + if ( this->m_MaximumStepSizeInPhysicalUnits <= NumericTraits<TInternalComputationValueType>::epsilon()) + { + this->m_MaximumStepSizeInPhysicalUnits = this->m_ScalesEstimator->EstimateMaximumStepSize(); + } + } + + if ( this->m_UseConvergenceMonitoring ) + { + // Initialize the convergence checker + this->m_ConvergenceMonitoring = ConvergenceMonitoringType::New(); + this->m_ConvergenceMonitoring->SetWindowSize( this->m_ConvergenceWindowSize ); + } + + /* Must call the superclass version for basic validation and setup */ + Superclass::StartOptimization( doOnlyInitialization ); +} + //------------------------------------------------------------------- template<typename TInternalComputationValueType> void diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerv4.h index 069475bee7f6eb85c813c2467bbf36ce85abad21..b85909a22d94165894be45274634b03cd91fe11b 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerv4.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerv4.h @@ -19,8 +19,6 @@ #define __itkGradientDescentOptimizerv4_h #include "itkGradientDescentOptimizerBasev4.h" -#include "itkOptimizerParameterScalesEstimator.h" -#include "itkWindowConvergenceMonitoringFunction.h" namespace itk { @@ -40,15 +38,8 @@ namespace itk * can be stored and retried via GetValue() and GetCurrentPosition(). * See SetReturnBestParametersAndValue(). * - * The user can scale each component of the df / dp in two ways: - * 1) manually, by setting a scaling vector using method SetScales(). - * Or, - * 2) automatically, by assigning a ScalesEstimator using SetScalesEstimator(). - * When ScalesEstimator is assigned, the optimizer is enabled by default to - * estimate scales, and can be changed via SetDoEstimateScales(). The scales - * are estimated and assigned once, during the call to StartOptimization(). - * This option will override any manually-assigned scales. - * + * Gradient scales can be manually set or automatically estimated, + * as documented in the base class. * The learing rate defaults to 1.0, and can be set in two ways: * 1) manually, via \c SetLearningRate(). * Or, @@ -62,9 +53,11 @@ namespace itk * SetDoEstimateLearningRateOnce(false). When enabled, the optimizer computes learning * rate(s) such that at each step, each voxel's change in physical space will be less * than m_MaximumStepSizeInPhysicalUnits. + * * m_LearningRate = * m_MaximumStepSizeInPhysicalUnits / * m_ScalesEstimator->EstimateStepScale(scaledGradient) + * * where m_MaximumStepSizeInPhysicalUnits defaults to the voxel spacing returned by * m_ScalesEstimator->EstimateMaximumStepSize() (which is typically 1 voxel), * and can be set by the user via SetMaximumStepSizeInPhysicalUnits(). @@ -111,10 +104,6 @@ public: typedef typename Superclass::ParametersType ParametersType; typedef typename Superclass::StopConditionType StopConditionType; - /** Type for the convergence checker */ - typedef itk::Function::WindowConvergenceMonitoringFunction<TInternalComputationValueType> - ConvergenceMonitoringType; - /** Set the learning rate. */ itkSetMacro(LearningRate, TInternalComputationValueType); @@ -132,25 +121,6 @@ public: /** Get the maximum step size, in physical space units. */ itkGetConstReferenceMacro(MaximumStepSizeInPhysicalUnits, TInternalComputationValueType); - /** Set the scales estimator. - * - * A ScalesEstimator is required for the scales and learning rate estimation - * options to work. See the main documentation. - * - * \sa SetDoEstimateScales() - * \sa SetDoEstimateLearningRateAtEachIteration() - * \sa SetDoEstimateLearningOnce() - */ - itkSetObjectMacro(ScalesEstimator, OptimizerParameterScalesEstimatorTemplate<TInternalComputationValueType>); - - /** Option to use ScalesEstimator for scales estimation. - * The estimation is performed once at begin of - * optimization, and overrides any scales set using SetScales(). - * Default is true. */ - itkSetMacro(DoEstimateScales, bool); - itkGetConstReferenceMacro(DoEstimateScales, bool); - itkBooleanMacro(DoEstimateScales); - /** Option to use ScalesEstimator for learning rate estimation at * *each* iteration. The estimation overrides the learning rate * set by SetLearningRate(). Default is false. @@ -213,11 +183,11 @@ public: itkBooleanMacro(ReturnBestParametersAndValue); /** Start and run the optimization */ - virtual void StartOptimization( bool doOnlyInitialization = false ); + virtual void StartOptimization( bool doOnlyInitialization = false ) ITK_OVERRIDE; - virtual void StopOptimization(void); + virtual void StopOptimization(void) ITK_OVERRIDE; - virtual void ResumeOptimization(); + virtual void ResumeOptimization() ITK_OVERRIDE; /** Estimate the learning rate based on the current gradient. */ virtual void EstimateLearningRate(); @@ -229,19 +199,14 @@ protected: virtual void AdvanceOneStep(void); /** Modify the gradient over a given index range. */ - virtual void ModifyGradientByScalesOverSubRange( const IndexRangeType& subrange ); - virtual void ModifyGradientByLearningRateOverSubRange( const IndexRangeType& subrange ); + virtual void ModifyGradientByScalesOverSubRange( const IndexRangeType& subrange ) ITK_OVERRIDE; + virtual void ModifyGradientByLearningRateOverSubRange( const IndexRangeType& subrange ) ITK_OVERRIDE; /** Manual learning rate to apply. It is overridden by * automatic learning rate estimation if enabled. See main documentation. */ TInternalComputationValueType m_LearningRate; - /** The maximum step size in physical units, to restrict learning rates. - * Only used with automatic learning rate estimation. See main documentation. - */ - TInternalComputationValueType m_MaximumStepSizeInPhysicalUnits; - /** Default constructor */ GradientDescentOptimizerv4Template(); @@ -250,8 +215,6 @@ protected: virtual void PrintSelf( std::ostream & os, Indent indent ) const; - typename OptimizerParameterScalesEstimatorTemplate<TInternalComputationValueType>::Pointer m_ScalesEstimator; - /** Minimum convergence value for convergence checking. * The convergence checker calculates convergence value by fitting to * a window of the energy profile. When the convergence value reaches @@ -259,19 +222,10 @@ protected: */ TInternalComputationValueType m_MinimumConvergenceValue; - /** Window size for the convergence checker. - * The convergence checker calculates convergence value by fitting to - * a window of the energy (metric value) profile. - */ - SizeValueType m_ConvergenceWindowSize; - /** Current convergence value. */ /* WindowConvergenceMonitoringFunction always returns output convergence value in 'TInternalComputationValueType' precision */ TInternalComputationValueType m_ConvergenceValue; - /** The convergence checker. */ - typename ConvergenceMonitoringType::Pointer m_ConvergenceMonitoring; - /** Store the best value and related paramters */ MeasureType m_CurrentBestValue; ParametersType m_BestParameters; @@ -279,21 +233,14 @@ protected: /** Flag to control returning of best value and parameters. */ bool m_ReturnBestParametersAndValue; -private: - /** Flag to control use of the ScalesEstimator (if set) for - * automatic scale estimation during StartOptimization() - */ - bool m_DoEstimateScales; - - /** Flag to control use of the ScalesEstimator (if set) for - * automatic learning step estimation at *each* iteration. + /** Store the previous gradient value at each iteration, + * so we can detect the changes in geradient direction. + * This is needed by the regular step gradient descent and + * Quasi newton optimizers. */ - bool m_DoEstimateLearningRateAtEachIteration; + DerivativeType m_PreviousGradient; - /** Flag to control use of the ScalesEstimator (if set) for - * automatic learning step estimation only *once*, during first iteration. - */ - bool m_DoEstimateLearningRateOnce; +private: GradientDescentOptimizerv4Template( const Self & ); //purposely not implemented void operator=( const Self& ); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerv4.hxx index 08132b905795a021ee6cb8e82ae68de42cdd429e..1c44c6931253f3c1f8c63b7e30a536acee625df1 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerv4.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkGradientDescentOptimizerv4.hxx @@ -31,21 +31,9 @@ GradientDescentOptimizerv4Template<TInternalComputationValueType> ::GradientDescentOptimizerv4Template() { this->m_LearningRate = NumericTraits<TInternalComputationValueType>::One; - - // m_MaximumStepSizeInPhysicalUnits is used for automatic learning - // rate estimation. it may be initialized either by calling - // SetMaximumStepSizeInPhysicalUnits manually or by using m_ScalesEstimator - // automatically. and the former has higher priority than the latter. - this->m_MaximumStepSizeInPhysicalUnits = NumericTraits<TInternalComputationValueType>::Zero; - - // Initialize parameters for the convergence checker - this->m_MinimumConvergenceValue = 1e-8;//NumericTraits<TInternalComputationValueType>::epsilon();//1e-30; - this->m_ConvergenceWindowSize = 50; - - this->m_DoEstimateScales = true; - this->m_DoEstimateLearningRateAtEachIteration = false; - this->m_DoEstimateLearningRateOnce = true; + this->m_MinimumConvergenceValue = 1e-8; this->m_ReturnBestParametersAndValue = false; + this->m_PreviousGradient.Fill( NumericTraits<TInternalComputationValueType>::Zero ); } /** @@ -69,16 +57,6 @@ GradientDescentOptimizerv4Template<TInternalComputationValueType> os << indent << "Learning rate:" << this->m_LearningRate << std::endl; os << indent << "MaximumStepSizeInPhysicalUnits: " << this->m_MaximumStepSizeInPhysicalUnits << std::endl; - if( this->m_ScalesEstimator.IsNull() ) - { - os << indent << "No ScalesEstimator set." << std::endl; - } - else - { - os << indent << "ScalesEstimator: " << std::endl; - this->m_ScalesEstimator->Print( os, indent.GetNextIndent() ); - } - os << indent << "DoEstimateScales: " << this->m_DoEstimateScales << std::endl; os << indent << "DoEstimateLearningRateAtEachIteration: " << this->m_DoEstimateLearningRateAtEachIteration << std::endl; os << indent << "DoEstimateLearningRateOnce: " @@ -93,34 +71,6 @@ void GradientDescentOptimizerv4Template<TInternalComputationValueType> ::StartOptimization( bool doOnlyInitialization ) { - itkDebugMacro("StartOptimization"); - - /* Validate some settings */ - if ( this->m_ScalesEstimator.IsNotNull() && - this->m_DoEstimateLearningRateOnce && - this->m_DoEstimateLearningRateAtEachIteration ) - { - itkExceptionMacro("Both m_DoEstimateLearningRateOnce and m_DoEstimateLearningRateAtEachIteration are enabled. Not allowed. "); - } - - /* Estimate the parameter scales if requested. */ - if ( this->m_DoEstimateScales && this->m_ScalesEstimator.IsNotNull() ) - { - this->m_ScalesEstimator->EstimateScales(this->m_Scales); - itkDebugMacro( "Estimated scales = " << this->m_Scales ); - - /* If user hasn't set this, assign the default. */ - if ( this->m_MaximumStepSizeInPhysicalUnits <= - NumericTraits<TInternalComputationValueType>::epsilon()) - { - this->m_MaximumStepSizeInPhysicalUnits = this->m_ScalesEstimator->EstimateMaximumStepSize(); - } - } - - // Initialize the convergence checker - this->m_ConvergenceMonitoring = ConvergenceMonitoringType::New(); - this->m_ConvergenceMonitoring->SetWindowSize( this->m_ConvergenceWindowSize ); - /* Must call the superclass version for basic validation and setup */ Superclass::StartOptimization( doOnlyInitialization ); @@ -169,6 +119,18 @@ GradientDescentOptimizerv4Template<TInternalComputationValueType> this->m_Stop = false; while( ! this->m_Stop ) { + // Do not run the loop if the maximum number of iterations is reached or its value is zero. + if ( this->m_CurrentIteration >= this->m_NumberOfIterations ) + { + this->m_StopConditionDescription << "Maximum number of iterations (" << this->m_NumberOfIterations << ") exceeded."; + this->m_StopCondition = Superclass::MAXIMUM_NUMBER_OF_ITERATIONS; + this->StopOptimization(); + break; + } + + // Save previous value with shallow swap that will be used by child optimizer. + swap( this->m_PreviousGradient, this->m_Gradient ); + /* Compute metric value/derivative. */ try { @@ -196,21 +158,24 @@ GradientDescentOptimizerv4Template<TInternalComputationValueType> /* Check the convergence by WindowConvergenceMonitoringFunction. */ - this->m_ConvergenceMonitoring->AddEnergyValue( this->m_CurrentMetricValue ); - try + if ( this->m_UseConvergenceMonitoring ) { - this->m_ConvergenceValue = this->m_ConvergenceMonitoring->GetConvergenceValue(); - if (this->m_ConvergenceValue <= this->m_MinimumConvergenceValue) + this->m_ConvergenceMonitoring->AddEnergyValue( this->m_CurrentMetricValue ); + try { - this->m_StopConditionDescription << "Convergence checker passed at iteration " << this->m_CurrentIteration << "."; - this->m_StopCondition = Superclass::CONVERGENCE_CHECKER_PASSED; - this->StopOptimization(); - break; + this->m_ConvergenceValue = this->m_ConvergenceMonitoring->GetConvergenceValue(); + if (this->m_ConvergenceValue <= this->m_MinimumConvergenceValue) + { + this->m_StopConditionDescription << "Convergence checker passed at iteration " << this->m_CurrentIteration << "."; + this->m_StopCondition = Superclass::CONVERGENCE_CHECKER_PASSED; + this->StopOptimization(); + break; + } + } + catch(std::exception & e) + { + std::cerr << "GetConvergenceValue() failed with exception: " << e.what() << std::endl; } - } - catch(std::exception & e) - { - std::cerr << "GetConvergenceValue() failed with exception: " << e.what() << std::endl; } /* Advance one step along the gradient. @@ -227,13 +192,6 @@ GradientDescentOptimizerv4Template<TInternalComputationValueType> /* Update and check iteration count */ this->m_CurrentIteration++; - if ( this->m_CurrentIteration >= this->m_NumberOfIterations ) - { - this->m_StopConditionDescription << "Maximum number of iterations (" << this->m_NumberOfIterations << ") exceeded."; - this->m_StopCondition = Superclass::MAXIMUM_NUMBER_OF_ITERATIONS; - this->StopOptimization(); - break; - } } //while (!m_Stop) } diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSBOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSBOptimizerv4.h new file mode 100644 index 0000000000000000000000000000000000000000..9d5b9a57e48de4643c1a0801ba9d7b0fce7e9164 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSBOptimizerv4.h @@ -0,0 +1,181 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkLBFGSBOptimizerv4_h +#define __itkLBFGSBOptimizerv4_h + +#include "itkLBFGSOptimizerBasev4.h" +#include "vnl/algo/vnl_lbfgsb.h" + +namespace itk +{ +/* Necessary forward declaration */ +/** \class LBFGSBOptimizerHelperv4 + * \brief Wrapper helper around vnl_lbfgsb. + * + * This class is used to translate iteration events, etc, from + * vnl_lbfgsb into iteration events in ITK. + * + * \ingroup ITKOptimizersv4 + */ +class LBFGSBOptimizerHelperv4; + +/** \class LBFGSBOptimizerv4 + * \brief Limited memory Broyden Fletcher Goldfarb Shannon minimization with simple bounds. + * + * This class is a wrapper for converted fortan code for performing limited + * memory Broyden Fletcher Goldfarb Shannon minimization with simple bounds. + * The algorithm miminizes a nonlinear function f(x) of n variables subject to + * simple bound constraints of l <= x <= u. + * + * See also the documentation in Numerics/lbfgsb.c + * + * References: + * + * [1] R. H. Byrd, P. Lu and J. Nocedal. + * A Limited Memory Algorithm for Bound Constrained Optimization, (1995), + * SIAM Journal on Scientific and Statistical Computing , + * 16, 5, pp. 1190-1208. + * + * [2] C. Zhu, R. H. Byrd and J. Nocedal. + * L-BFGS-B: Algorithm 778: L-BFGS-B, FORTRAN routines for large scale + * bound constrained optimization (1997), + * ACM Transactions on Mathematical Software, + * Vol 23, Num. 4, pp. 550 - 560. + * + * \ingroup Numerics Optimizersv4 + * \ingroup ITKOptimizersv4 + */ +class LBFGSBOptimizerv4: + public LBFGSOptimizerBasev4< vnl_lbfgsb > +{ +public: + /** Standard "Self" typedef. */ + typedef LBFGSBOptimizerv4 Self; + typedef LBFGSOptimizerBasev4<vnl_lbfgsb> Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + typedef Superclass::MetricType MetricType; + typedef Superclass::ParametersType ParametersType; + typedef Superclass::ScalesType ScalesType; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(LBFGSBOptimizerv4, Superclass); + + enum BoundSelectionValues { + UNBOUNDED = 0, + LOWERBOUNDED = 1, + BOTHBOUNDED = 2, + UPPERBOUNDED = 3 + }; + + /** BoundValue type. + * Use for defining the lower and upper bounds on the variables. + */ + typedef Array< double > BoundValueType; + + /** BoundSelection type + * Use for defining the boundary condition for each variables. + */ + typedef Array< long > BoundSelectionType; + + /** Set the position to initialize the optimization. */ + void SetInitialPosition(const ParametersType & param); + + /** Get the position to initialize the optimization. */ + ParametersType & GetInitialPosition(void) + { + return m_InitialPosition; + } + + /** Start optimization with an initial value. */ + virtual void StartOptimization(bool doOnlyInitialization = false) ITK_OVERRIDE; + + /** Plug in a Cost Function into the optimizer */ + virtual void SetMetric(MetricType *metric) ITK_OVERRIDE; + + /** Set the lower bound value for each variable. */ + void SetLowerBound(const BoundValueType & value); + + itkGetConstReferenceMacro(LowerBound,BoundValueType); + + /** Set the upper bound value for each variable. */ + void SetUpperBound(const BoundValueType & value); + + itkGetConstReferenceMacro(UpperBound,BoundValueType); + + /** Set the boundary condition for each variable, where + * select[i] = 0 if x[i] is unbounded, + * = 1 if x[i] has only a lower bound, + * = 2 if x[i] has both lower and upper bounds, and + * = 3 if x[1] has only an upper bound + */ + void SetBoundSelection(const BoundSelectionType & select); + + itkGetConstReferenceMacro(BoundSelection,BoundSelectionType); + + /** Set/Get the CostFunctionConvergenceFactor. Algorithm terminates + * when the reduction in cost function is less than factor * epsmcj + * where epsmch is the machine precision. + * Typical values for factor: 1e+12 for low accuracy; + * 1e+7 for moderate accuracy and 1e+1 for extremely high accuracy. + */ + virtual void SetCostFunctionConvergenceFactor(double); + + itkGetConstMacro(CostFunctionConvergenceFactor, double); + + /** Set/Get the MaximumNumberOfCorrections. Default is 5 */ + virtual void SetMaximumNumberOfCorrections(unsigned int); + + itkGetConstMacro(MaximumNumberOfCorrections, unsigned int); + + /** This optimizer does not support scaling of the derivatives. */ + virtual void SetScales(const ScalesType &) ITK_OVERRIDE; + + /** Get the current infinity norm of the project gradient of the cost + * function. */ + itkGetConstReferenceMacro(InfinityNormOfProjectedGradient, double); + +protected: + LBFGSBOptimizerv4(); + virtual ~LBFGSBOptimizerv4(); + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + + typedef Superclass::CostFunctionAdaptorType CostFunctionAdaptorType; + + /** Internal optimizer type. */ + typedef LBFGSBOptimizerHelperv4 InternalOptimizerType; + + friend class LBFGSBOptimizerHelperv4; + +private: + LBFGSBOptimizerv4(const Self &); //purposely not implemented + void operator=(const Self &); //purposely not implemented + + unsigned int m_MaximumNumberOfCorrections; + + ParametersType m_InitialPosition; + BoundValueType m_LowerBound; + BoundValueType m_UpperBound; + BoundSelectionType m_BoundSelection; +}; +} // end namespace itk +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerBasev4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerBasev4.h new file mode 100644 index 0000000000000000000000000000000000000000..87a63ecac054c8f9dbbe948e1932cfdd95b2d983 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerBasev4.h @@ -0,0 +1,169 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkLBFGSOptimizerBasev4_h +#define __itkLBFGSOptimizerBasev4_h + +#include "itkSingleValuedNonLinearVnlOptimizerv4.h" +#include "vnl/algo/vnl_lbfgs.h" +#include "vnl/algo/vnl_lbfgsb.h" +#include "itkAutoPointer.h" + +namespace itk +{ +/* Necessary forward declaration see below for definition */ +/** \class LBFGSOptimizerBaseHelperv4 + * \brief Wrapper helper around vnl optimizer. + * + * This class is used to translate iteration events, etc, from + * vnl_lbfgsb into iteration events in ITK. + * + * \ingroup ITKOptimizersv4 + */ +template< typename TInternalVnlOptimizerType > +class LBFGSOptimizerBaseHelperv4; + +/** \class LBFGSOptimizerBasev4 + * \brief Abstract base for vnl lbfgs algorithm optimizers in ITKv4 registration framework. + * + * \note The StopConditionDescription returned by this class is directly from the vnl + * optimizer by calling <tt> m_VnlOptimizer->get_failure_code() </tt>. This seems to + * return "Failure" even when no error has occured. The same behavior is observed + * in the ITKv3 version of this optimizer. + * + * \note Local-support (high-density) transforms. + * Local-support transforms are not supported. To add support for these, + * the class must be modified thusly: + * + * \note 1) Parameter updates: + * In SingleValuedNonLinearCostFunctionAdaptor, the handling of the gradient + * must be changed to accomodate the fact that local-support transforms expect + * a gradient to be added to the transform parameters using the + * UpdateTransformParameters method of the local support transform. Other optimizers + * in the v4 framework use this method, but the use of the vnl optimizers here + * complicates it. + * + * \note 2) Efficiency + * To work efficiently with local-support transforms, this class should be + * modified to use a single parameter object to avoid the multiple + * parameter copies that are currently performed. It should work to use + * the transform parameters pointer. + * + * This code has been adapted for the ITKv4 registration framework from the + * v3 version, itkLBFGSOptimizer. + * + * \ingroup ITKOptimizersv4 + */ +template< typename TInternalVnlOptimizerType > +class LBFGSOptimizerBasev4: + public SingleValuedNonLinearVnlOptimizerv4 +{ +public: + /** Standard "Self" typedef. */ + typedef LBFGSOptimizerBasev4 Self; + typedef SingleValuedNonLinearVnlOptimizerv4 Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(LBFGSOptimizerBasev4, SingleValuedNonLinearVnlOptimizerv4); + + typedef Superclass::MetricType MetricType; + typedef Superclass::ParametersType ParametersType; + typedef Superclass::ScalesType ScalesType; + + /** Stop condition return string type */ + typedef Superclass::StopConditionReturnStringType StopConditionReturnStringType; + + /** Stop condition internal string type */ + typedef Superclass::StopConditionDescriptionType StopConditionDescriptionType; + + /** The vnl optimizer */ + typedef LBFGSOptimizerBaseHelperv4<TInternalVnlOptimizerType> InternalOptimizerType; + + /** Method for getting access to the internal optimizer. */ + InternalOptimizerType * GetOptimizer(void); + + /** Start optimization with an initial value. */ + virtual void StartOptimization(bool doOnlyInitialization = false) ITK_OVERRIDE; + + /** Plug in a Cost Function into the optimizer */ + virtual void SetMetric(MetricType *metric) ITK_OVERRIDE; + + /** Set/Get the optimizer trace flag. If set to true, the optimizer + * prints out information every iteration. + */ + virtual void SetTrace(bool flag); + + itkGetConstMacro(Trace, bool); + itkBooleanMacro(Trace); + + /** Set/Get the maximum number of function evaluations allowed. */ + virtual void SetMaximumNumberOfFunctionEvaluations(unsigned int n); + + itkGetConstMacro(MaximumNumberOfFunctionEvaluations, unsigned int); + + /** Set/Get the gradient convergence tolerance. This is a positive + * real number that determines the accuracy with which the solution is to + * be found. The optimization terminates when: + * ||G|| < gtol max(1,||X||) where ||.|| denotes the Euclidean norm. + */ + virtual void SetGradientConvergenceTolerance(double gtol); + + itkGetConstMacro(GradientConvergenceTolerance, double); + + /** Get the reason for termination */ + virtual const StopConditionReturnStringType GetStopConditionDescription() const ITK_OVERRIDE; + +protected: + LBFGSOptimizerBasev4(); + virtual ~LBFGSOptimizerBasev4(); + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + + typedef Superclass::CostFunctionAdaptorType CostFunctionAdaptorType; + + bool m_OptimizerInitialized; + + typedef AutoPointer<InternalOptimizerType> InternalOptimizerAutoPointer; + InternalOptimizerAutoPointer m_VnlOptimizer; + + mutable std::ostringstream m_StopConditionDescription; + + bool m_Trace; + unsigned int m_MaximumNumberOfFunctionEvaluations; + double m_GradientConvergenceTolerance; + double m_InfinityNormOfProjectedGradient; + unsigned int m_MaximumNumberOfIterations; + double m_CostFunctionConvergenceFactor; + + // give the helper access to member variables, to update iteration + // counts, etc. + friend class LBFGSOptimizerBaseHelperv4<TInternalVnlOptimizerType>; + friend class LBFGSBOptimizerHelperv4; + +private: + LBFGSOptimizerBasev4(const Self &); //purposely not implemented + void operator=(const Self &); //purposely not implemented + +}; +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkLBFGSOptimizerBasev4.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerBasev4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerBasev4.hxx new file mode 100644 index 0000000000000000000000000000000000000000..4c47e69b4eb9fbc6212e74afb113eaad70bd3902 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerBasev4.hxx @@ -0,0 +1,258 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkLBFGSOptimizerBasev4_hxx +#define __itkLBFGSOptimizerBasev4_hxx + +#include "itkLBFGSOptimizerBasev4.h" + +extern "C" { + extern double v3p_netlib_dpmeps_(); +} + +namespace itk +{ + +template< typename TInternalVnlOptimizerType > +class LBFGSOptimizerBaseHelperv4: public TInternalVnlOptimizerType +{ + public: + typedef LBFGSOptimizerBaseHelperv4 Self; + typedef TInternalVnlOptimizerType Superclass; + + LBFGSOptimizerBaseHelperv4(vnl_cost_function & f, + LBFGSOptimizerBasev4<TInternalVnlOptimizerType> * itkObj): + TInternalVnlOptimizerType(f), + m_ItkObj(itkObj) + { + } + + protected: + LBFGSOptimizerBasev4<TInternalVnlOptimizerType> * m_ItkObj; +}; + +template<typename TInternalVnlOptimizerType> +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::LBFGSOptimizerBasev4(): + m_OptimizerInitialized(false), + m_Trace(false), + m_MaximumNumberOfFunctionEvaluations(2000), + m_GradientConvergenceTolerance(1e-5), + m_InfinityNormOfProjectedGradient(0.0), + m_MaximumNumberOfIterations(500), + m_CostFunctionConvergenceFactor(1e+7) +{ +} + +template<typename TInternalVnlOptimizerType> +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::~LBFGSOptimizerBasev4() +{ +} + +template<typename TInternalVnlOptimizerType> +void +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Trace: "; + if ( m_Trace ) + { + os << "On"; + } + else + { + os << "Off"; + } + os << std::endl; + os << indent << "MaximumNumberOfFunctionEvaluations: " + << m_MaximumNumberOfFunctionEvaluations << std::endl; + os << indent << "GradientConvergenceTolerance: " + << m_GradientConvergenceTolerance << std::endl; +} + +template<typename TInternalVnlOptimizerType> +void +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::SetTrace(bool flag) +{ + if ( flag == m_Trace ) + { + return; + } + + m_Trace = flag; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_trace(m_Trace); + } + + this->Modified(); +} + +template<typename TInternalVnlOptimizerType> +void +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::SetMaximumNumberOfFunctionEvaluations(unsigned int n) +{ + if ( n == m_MaximumNumberOfFunctionEvaluations ) + { + return; + } + + m_MaximumNumberOfFunctionEvaluations = n; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_max_function_evals( + static_cast< int >( m_MaximumNumberOfFunctionEvaluations ) ); + } + + this->Modified(); +} + +template<typename TInternalVnlOptimizerType> +void +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::SetGradientConvergenceTolerance(double f) +{ + if ( f == m_GradientConvergenceTolerance ) + { + return; + } + + m_GradientConvergenceTolerance = f; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_g_tolerance(m_GradientConvergenceTolerance); + } + + this->Modified(); +} + +template<typename TInternalVnlOptimizerType> +void +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::SetMetric(MetricType *metric) +{ + // assign to base class + this->m_Metric = metric; + + // assign to vnl cost-function adaptor + const unsigned int numberOfParameters = metric->GetNumberOfParameters(); + + CostFunctionAdaptorType *adaptor = new CostFunctionAdaptorType( numberOfParameters ); + + adaptor->SetCostFunction( metric ); + + this->SetCostFunctionAdaptor( adaptor ); + + m_VnlOptimizer.TakeOwnership( new InternalOptimizerType( *adaptor, this ) ); +} + +template<typename TInternalVnlOptimizerType> +void +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::StartOptimization(bool /* doOnlyInitialization */) +{ + // Check for a local-support transform. + // These aren't currently supported, see main class documentation. + if( this->GetMetric()->HasLocalSupport() ) + { + itkExceptionMacro("The assigned transform has local-support. This is not supported for this optimizer. See the optimizer documentation."); + } + + // Perform some verification, check scales, + // pass settings to cost-function adaptor. + Superclass::StartOptimization(); +} + +template<typename TInternalVnlOptimizerType> +typename LBFGSOptimizerBasev4<TInternalVnlOptimizerType>::InternalOptimizerType * +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::GetOptimizer() +{ + return m_VnlOptimizer.GetPointer(); +} + +template<typename TInternalVnlOptimizerType> +const std::string +LBFGSOptimizerBasev4<TInternalVnlOptimizerType> +::GetStopConditionDescription() const +{ + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + if ( m_VnlOptimizer ) + { + switch ( m_VnlOptimizer->get_failure_code() ) + { + case vnl_nonlinear_minimizer::ERROR_FAILURE: + m_StopConditionDescription << "Failure"; + break; + case vnl_nonlinear_minimizer::ERROR_DODGY_INPUT: + m_StopConditionDescription << "Dodgy input"; + break; + case vnl_nonlinear_minimizer::CONVERGED_FTOL: + m_StopConditionDescription << "Function tolerance reached after " + << m_CurrentIteration + << " iterations. " + << "The relative reduction of the cost function <= " + << m_CostFunctionConvergenceFactor * v3p_netlib_dpmeps_() + << " = CostFunctionConvergenceFactor (" + << m_CostFunctionConvergenceFactor + << ") * machine precision (" + << v3p_netlib_dpmeps_() + << ")."; + break; + case vnl_nonlinear_minimizer::CONVERGED_XTOL: + m_StopConditionDescription << "Solution tolerance reached"; + break; + case vnl_nonlinear_minimizer::CONVERGED_XFTOL: + m_StopConditionDescription << "Solution and Function tolerance both reached"; + break; + case vnl_nonlinear_minimizer::CONVERGED_GTOL: + m_StopConditionDescription << "Gradient tolerance reached. " + << "Gradient tolerance is " + << m_GradientConvergenceTolerance; + break; + case vnl_nonlinear_minimizer::FAILED_TOO_MANY_ITERATIONS: + m_StopConditionDescription << "Too many function evaluations. Function evaluations = " + << m_MaximumNumberOfFunctionEvaluations; + break; + case vnl_nonlinear_minimizer::FAILED_FTOL_TOO_SMALL: + m_StopConditionDescription << "Function tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_XTOL_TOO_SMALL: + m_StopConditionDescription << "Solution tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_GTOL_TOO_SMALL: + m_StopConditionDescription << "Gradient tolerance too small"; + break; + case vnl_nonlinear_minimizer::FAILED_USER_REQUEST: + m_StopConditionDescription << "User requested"; + break; + } + return m_StopConditionDescription.str(); + } + else + { + return std::string(""); + } +} +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerv4.h new file mode 100644 index 0000000000000000000000000000000000000000..4fbffd2c739cdc17fdd347797a2d1c79fae7d035 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkLBFGSOptimizerv4.h @@ -0,0 +1,99 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkLBFGSOptimizerv4_h +#define __itkLBFGSOptimizerv4_h + +#include "itkLBFGSOptimizerBasev4.h" +#include "vnl/algo/vnl_lbfgs.h" + +namespace itk +{ +/** \class LBFGSOptimizerv4 + * \brief Wrap of the vnl_lbfgs algorithm for use in ITKv4 registration framework. + * + * \ingroup ITKOptimizersv4 + */ + +class LBFGSOptimizerv4: + public LBFGSOptimizerBasev4< vnl_lbfgs > +{ +public: + /** Standard "Self" typedef. */ + typedef LBFGSOptimizerv4 Self; + typedef LBFGSOptimizerBasev4<vnl_lbfgs> Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + typedef Superclass::MetricType MetricType; + typedef Superclass::ParametersType ParametersType; + typedef Superclass::ScalesType ScalesType; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(LBFGSOptimizerv4, Superclass); + + /** Start optimization with an initial value. */ + virtual void StartOptimization(bool doOnlyInitialization = false) ITK_OVERRIDE; + + /** Plug in a Cost Function into the optimizer */ + virtual void SetMetric(MetricType *metric) ITK_OVERRIDE; + + void VerboseOn(void); + void VerboseOff(void); + + /** Set/Get the line search accuracy. This is a positive real number + * with a default value of 0.9, which controls the accuracy of the line + * search. If the function and gradient evalutions are inexpensive with + * respect to the cost of the iterations it may be advantageous to set + * the value to a small value (say 0.1). + */ + void SetLineSearchAccuracy(double tol); + + itkGetConstMacro(LineSearchAccuracy, double); + + /** Set/Get the default step size. This is a positive real number + * with a default value of 1.0 which determines the step size in the line + * search. + */ + void SetDefaultStepLength(double stp); + + itkGetConstMacro(DefaultStepLength, double); + +protected: + LBFGSOptimizerv4(); + virtual ~LBFGSOptimizerv4(); + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + + /** InternalParameters typedef. */ + typedef vnl_vector< double > InternalParametersType; + + /** Internal optimizer type. */ + typedef vnl_lbfgs InternalOptimizerType; + +private: + LBFGSOptimizerv4(const Self &); //purposely not implemented + void operator=(const Self &); //purposely not implemented + + bool m_Verbose; + double m_LineSearchAccuracy; + double m_DefaultStepLength; +}; +} // end namespace itk +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiGradientOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiGradientOptimizerv4.h index 9459fc5b7aafadeebdb9d0a7fd7ab67db134f915..729c47a578368cda243261d971fba7d9103b16fe 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiGradientOptimizerv4.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiGradientOptimizerv4.h @@ -70,10 +70,10 @@ public: typedef typename Superclass::StopConditionType StopConditionType; /** Stop condition return string type */ - typedef std::string StopConditionReturnStringType; + typedef typename Superclass::StopConditionReturnStringType StopConditionReturnStringType; /** Stop condition internal string type */ - typedef std::ostringstream StopConditionDescriptionType; + typedef typename Superclass::StopConditionDescriptionType StopConditionDescriptionType; /** It should be possible to derive the internal computation type from the class object. */ typedef TInternalComputationValueType InternalComputationValueType; @@ -92,15 +92,6 @@ public: /** Get stop condition enum */ itkGetConstReferenceMacro(StopCondition, StopConditionType); - /** Set the number of iterations. */ - itkSetMacro(NumberOfIterations, SizeValueType); - - /** Get the number of iterations. */ - itkGetConstReferenceMacro(NumberOfIterations, SizeValueType); - - /** Get the current iteration number. */ - itkGetConstMacro(CurrentIteration, SizeValueType); - /** Begin the optimization */ virtual void StartOptimization( bool doOnlyInitialization = false ); @@ -113,7 +104,7 @@ public: virtual void ResumeOptimization(); /** Get the reason for termination */ - virtual const StopConditionReturnStringType GetStopConditionDescription() const; + virtual const StopConditionReturnStringType GetStopConditionDescription() const ITK_OVERRIDE; /** Get the list of optimizers currently held. */ OptimizersListType & GetOptimizersList(); @@ -136,8 +127,6 @@ public: bool m_Stop; StopConditionType m_StopCondition; StopConditionDescriptionType m_StopConditionDescription; - SizeValueType m_NumberOfIterations; - SizeValueType m_CurrentIteration; OptimizersListType m_OptimizersList; MetricValuesListType m_MetricValuesList; MeasureType m_MinimumMetricValue; diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiGradientOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiGradientOptimizerv4.hxx index bfab8bdea00cb62032503a8fc641112f30c77198..da9df41172a0d2bd7da90534bc1fcd2cc08c9673 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiGradientOptimizerv4.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiGradientOptimizerv4.hxx @@ -26,10 +26,10 @@ namespace itk //------------------------------------------------------------------- template<typename TInternalComputationValueType> MultiGradientOptimizerv4Template<TInternalComputationValueType> -::MultiGradientOptimizerv4Template() +::MultiGradientOptimizerv4Template(): + m_Stop(false) { this->m_NumberOfIterations = static_cast<SizeValueType>(0); - this->m_CurrentIteration = static_cast<SizeValueType>(0); this->m_StopCondition = Superclass::MAXIMUM_NUMBER_OF_ITERATIONS; this->m_StopConditionDescription << this->GetNameOfClass() << ": "; @@ -51,8 +51,6 @@ MultiGradientOptimizerv4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - os << indent << "Number of iterations: " << this->m_NumberOfIterations << std::endl; - os << indent << "Current iteration: " << this->m_CurrentIteration << std::endl; os << indent << "Stop condition:"<< this->m_StopCondition << std::endl; os << indent << "Stop condition description: " << this->m_StopConditionDescription.str() << std::endl; } diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiStartOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiStartOptimizerv4.h index 583ae058397053a6559a8bd41372a3cd3adf6d74..0a929eb92e17ad571ca9101c7fc55e157270c6aa 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiStartOptimizerv4.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiStartOptimizerv4.h @@ -73,10 +73,11 @@ public: } StopConditionType; /** Stop condition return string type */ - typedef std::string StopConditionReturnStringType; + typedef typename Superclass::StopConditionReturnStringType StopConditionReturnStringType; /** Stop condition internal string type */ - typedef std::ostringstream StopConditionDescriptionType; + typedef typename Superclass::StopConditionDescriptionType StopConditionDescriptionType; + /** Stop condition return string type */ /** It should be possible to derive the internal computation type from the class object. */ typedef TInternalComputationValueType InternalComputationValueType; @@ -95,15 +96,6 @@ public: /** Get stop condition enum */ itkGetConstReferenceMacro(StopCondition, StopConditionType); - /** Set the number of iterations. */ - itkSetMacro(NumberOfIterations, SizeValueType); - - /** Get the number of iterations. */ - itkGetConstReferenceMacro(NumberOfIterations, SizeValueType); - - /** Get the current iteration number. */ - itkGetConstMacro(CurrentIteration, SizeValueType); - /** Create an instance of the local optimizer */ void InstantiateLocalOptimizer(void); @@ -119,7 +111,7 @@ public: virtual void ResumeOptimization(); /** Get the reason for termination */ - virtual const StopConditionReturnStringType GetStopConditionDescription() const; + virtual const StopConditionReturnStringType GetStopConditionDescription() const ITK_OVERRIDE; /** Get the list of parameters over which to search. */ ParametersListType & GetParametersList(); @@ -150,8 +142,6 @@ protected: bool m_Stop; StopConditionType m_StopCondition; StopConditionDescriptionType m_StopConditionDescription; - SizeValueType m_NumberOfIterations; - SizeValueType m_CurrentIteration; ParametersListType m_ParametersList; MetricValuesListType m_MetricValuesList; MeasureType m_MinimumMetricValue; diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiStartOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiStartOptimizerv4.hxx index a6e1a0e273cc4601d361798e18c842b10b7d31bc..2de014d80077d40847af27424fd13253eed44051 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiStartOptimizerv4.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkMultiStartOptimizerv4.hxx @@ -26,17 +26,17 @@ namespace itk //------------------------------------------------------------------- template<typename TInternalComputationValueType> MultiStartOptimizerv4Template<TInternalComputationValueType> -::MultiStartOptimizerv4Template() +::MultiStartOptimizerv4Template(): + m_Stop(false) { this->m_NumberOfIterations = static_cast<SizeValueType>(0); - this->m_CurrentIteration = static_cast<SizeValueType>(0); this->m_StopCondition = MAXIMUM_NUMBER_OF_ITERATIONS; this->m_StopConditionDescription << this->GetNameOfClass() << ": "; this->m_BestParametersIndex= static_cast<ParameterListSizeType>(0); this->m_MaximumMetricValue=NumericTraits<MeasureType>::max(); this->m_MinimumMetricValue = this->m_MaximumMetricValue; - m_LocalOptimizer = NULL; + m_LocalOptimizer = ITK_NULLPTR; } //------------------------------------------------------------------- @@ -52,8 +52,6 @@ MultiStartOptimizerv4Template<TInternalComputationValueType> ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - os << indent << "Number of iterations: " << this->m_NumberOfIterations << std::endl; - os << indent << "Current iteration: " << this->m_CurrentIteration << std::endl; os << indent << "Stop condition:"<< this->m_StopCondition << std::endl; os << indent << "Stop condition description: " << this->m_StopConditionDescription.str() << std::endl; } diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectMetric.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectMetric.hxx index 0a8459b76163a394dc35eda6aeeb6040fc49c620..cf285e152c59f31b6c399283239f8442fc762a59 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectMetric.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectMetric.hxx @@ -31,7 +31,8 @@ namespace itk */ template<unsigned int TFixedDimension, unsigned int TMovingDimension, typename TVirtualImage, typename TInternalComputationValueType> ObjectToObjectMetric<TFixedDimension, TMovingDimension, TVirtualImage, TInternalComputationValueType> -::ObjectToObjectMetric() +::ObjectToObjectMetric(): + m_NumberOfValidPoints(0) { /* Both transforms default to an identity transform */ typedef IdentityTransform<TInternalComputationValueType, itkGetStaticConstMacro( MovingDimension ) > MovingIdentityTransformType; @@ -238,7 +239,7 @@ ObjectToObjectMetric<TFixedDimension, TMovingDimension, TVirtualImage, TInternal { this->m_VirtualImage = virtualImage; this->Modified(); - this->m_UserHasSetVirtualDomain = virtualImage != NULL; + this->m_UserHasSetVirtualDomain = virtualImage != ITK_NULLPTR; } } @@ -415,7 +416,7 @@ ObjectToObjectMetric<TFixedDimension, TMovingDimension, TVirtualImage, TInternal const MovingTransformType* transform = this->m_MovingTransform.GetPointer(); // If it's a CompositeTransform, get the last transform (1st applied). const MovingCompositeTransformType* comptx = dynamic_cast< const MovingCompositeTransformType * > ( transform ); - if( comptx != NULL ) + if( comptx != ITK_NULLPTR ) { transform = comptx->GetBackTransform(); } @@ -441,7 +442,7 @@ ObjectToObjectMetric<TFixedDimension, TMovingDimension, TVirtualImage, TInternal * Eventually we'll want a method in Transform something like a * GetInputDomainSize to check this cleanly. */ const MovingDisplacementFieldTransformType * displacementTransform = this->GetMovingDisplacementFieldTransform(); - if( displacementTransform == NULL ) + if( displacementTransform == ITK_NULLPTR ) { itkExceptionMacro("Expected the moving transform to be of type DisplacementFieldTransform or derived, " "or a CompositeTransform with DisplacementFieldTransform as the last to have been added." ); @@ -514,20 +515,12 @@ ObjectToObjectMetric<TFixedDimension, TMovingDimension, TVirtualImage, TInternal { Superclass::PrintSelf(os, indent); - os << indent << "ObjectToObjectMetric: " << std::endl - << indent << "Fixed Transform: " << std::endl - << indent << this->m_FixedTransform << std::endl - << indent << "Moving Transform: " << std::endl - << indent << this->m_MovingTransform << std::endl; - if( this->m_VirtualImage.IsNull() ) - { - os << indent << "Virtual Image: NULL " << std::endl; - } - else - { - os << indent << "Virtual Image: " << std::endl - << indent << this->m_VirtualImage << std::endl; - } + os << indent << "ObjectToObjectMetric: " << std::endl; + + itkPrintSelfObjectMacro( FixedTransform ); + itkPrintSelfObjectMacro( MovingTransform ); + itkPrintSelfObjectMacro( VirtualImage ); + os << indent << "m_UserHasSetVirtualDomain: " << this->m_UserHasSetVirtualDomain << std::endl << indent << "m_NumberOfValidPoints: " << this->m_NumberOfValidPoints << std::endl; } diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectMetricBase.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectMetricBase.h index f63090d2cfd98a4e26aacff86d5705f621e8c16e..edcb1454d4cf0adb1a2cb5b6e3442c60c0047c6e 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectMetricBase.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectMetricBase.h @@ -133,7 +133,7 @@ public: virtual NumberOfParametersType GetNumberOfParameters() const = 0; virtual NumberOfParametersType GetNumberOfLocalParameters() const = 0; - /** Set the active transform's parameters */ + /** Set the active transform's parameters by value*/ virtual void SetParameters( ParametersType & params ) = 0; /** Get a const reference to the active transform's parameters */ diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectOptimizerBase.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectOptimizerBase.h index 475a0bc1970485b4a33f339c40b3181d847640e3..d6b909f9792165da56ef5f9e580db7813a0d9a7d 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectOptimizerBase.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectOptimizerBase.h @@ -19,6 +19,7 @@ #define __itkObjectToObjectOptimizerBase_h #include "itkOptimizerParameters.h" +#include "itkOptimizerParameterScalesEstimator.h" #include "itkObjectToObjectMetricBase.h" #include "itkIntTypes.h" @@ -38,9 +39,12 @@ namespace itk * appropriate, typically by passing it to its transform that is * being optimized. * - * SetScales() allows setting of a per-local-parameter scaling array. - * The gradient of each local parameter is divided by the corresponding - * scale. If unset, the \c m_Scales array will be initialized to all 1's. + * The user can scale each component of the gradient (derivative) + * at each iteration in one of two ways: + * + * 1) manually, by setting a scaling vector using method SetScales(). + * SetScales() allows setting of a per-local-parameter scaling array. If + * unset, the \c m_Scales array will be initialized to all 1's. * Note that when used with transforms with local support, these scales * correspond to each _local_ parameter, and not to each parameter. For * example, in a DisplacementFieldTransform of dimensionality N, the Scales @@ -48,6 +52,15 @@ namespace itk * transform's displacement field, and is applied to each vector in the * displacement field. * + * or, + * + * 2) automatically, by assigning a ScalesEstimator using SetScalesEstimator(). + * When ScalesEstimator is assigned, the optimizer is enabled by default to + * estimate scales, and can be changed via SetDoEstimateScales(). The scales + * are estimated and assigned once, during the call to StartOptimization(). + * This option will override any manually-assigned scales. + * + * * SetWeights() allows setting of a per-local-parameter weighting array. * If unset, the weights are treated as identity. Weights are multiplied * by the gradient at the same time scaling is applied. Weights are @@ -63,7 +76,7 @@ namespace itk * * \ingroup ITKOptimizersv4 */ -template< typename TInternalComputationValueType> +template< typename TInternalComputationValueType = double> class ObjectToObjectOptimizerBaseTemplate : public Object { public: @@ -77,7 +90,8 @@ public: itkTypeMacro(ObjectToObjectOptimizerBaseTemplate, Object); /** Scale type. */ - typedef OptimizerParameters< TInternalComputationValueType > ScalesType; + typedef OptimizerParameters< TInternalComputationValueType > ScalesType; + typedef OptimizerParameterScalesEstimatorTemplate<TInternalComputationValueType> ScalesEstimatorType; /** Parameters type. */ typedef OptimizerParameters< TInternalComputationValueType > ParametersType; @@ -86,12 +100,21 @@ public: typedef ObjectToObjectMetricBaseTemplate< TInternalComputationValueType > MetricType; typedef typename MetricType::Pointer MetricTypePointer; + /** Derivative type */ + typedef typename MetricType::DerivativeType DerivativeType; + /** Number of parameters type */ typedef typename MetricType::NumberOfParametersType NumberOfParametersType; /** Measure type */ typedef typename MetricType::MeasureType MeasureType; + /** Stop condition return string type */ + typedef std::string StopConditionReturnStringType; + + /** Stop condition internal string type */ + typedef std::ostringstream StopConditionDescriptionType; + /** Accessors for Metric */ itkSetObjectMacro( Metric, MetricType ); itkGetModifiableObjectMacro(Metric, MetricType ); @@ -109,7 +132,11 @@ public: virtual const MeasureType & GetValue() const; /** Set current parameters scaling. */ - itkSetMacro( Scales, ScalesType ); + //itkSetMacro( Scales, ScalesType ); + virtual void SetScales(const ScalesType & scales) + { + this->m_Scales = scales; + } /** Get current parameters scaling. */ itkGetConstReferenceMacro( Scales, ScalesType ); @@ -127,6 +154,30 @@ public: /** Get whether weights are identity. Cannot be set */ itkGetConstReferenceMacro( WeightsAreIdentity, bool ); + /** Get whether the scales have been set. Returns + * true if <tt> m_Scales.Size() > 0 </tt> */ + bool GetScalesInitialized( void ) const; + + /** Set the scales estimator. + * + * A ScalesEstimator is required for the scales estimation + * options to work. See the main documentation. + * Derived classes may also provide learning-rate estimation, + * in which case a scales estimator is also required. + * + * \sa SetDoEstimateScales() + */ + itkSetObjectMacro(ScalesEstimator, ScalesEstimatorType); + + /** Option to use ScalesEstimator for scales estimation. + * The estimation is performed once at begin of + * optimization, and overrides any scales set using SetScales(). + * Default is true. + */ + itkSetMacro(DoEstimateScales, bool); + itkGetConstReferenceMacro(DoEstimateScales, bool); + itkBooleanMacro(DoEstimateScales); + /** Set the number of threads to use when threading. * The default is the global default number of threads * returned from itkMultiThreader. */ @@ -135,6 +186,15 @@ public: /** Get the number of threads set to be used. */ itkGetConstReferenceMacro( NumberOfThreads, ThreadIdType ); + /** Return current number of iterations. */ + itkGetConstMacro(CurrentIteration, SizeValueType); + + /** Set the number of iterations. */ + itkSetMacro(NumberOfIterations, SizeValueType); + + /** Get the number of iterations. */ + itkGetConstMacro(NumberOfIterations, SizeValueType); + /** Get a reference to the current position of the optimization. * This returns the parameters from the assigned metric, since the optimizer * itself does not store a position. */ @@ -149,6 +209,9 @@ public: * perform any additional initialization before performing optimization. */ virtual void StartOptimization( bool doOnlyInitialization = false ); + /** Stop condition return string type */ + virtual const StopConditionReturnStringType GetStopConditionDescription() const = 0; + protected: /** Default constructor */ @@ -157,6 +220,8 @@ protected: MetricTypePointer m_Metric; ThreadIdType m_NumberOfThreads; + SizeValueType m_CurrentIteration; + SizeValueType m_NumberOfIterations; /** Metric measure value at a given iteration, as most recently evaluated. */ MeasureType m_CurrentMetricValue; @@ -174,10 +239,18 @@ protected: /** Flag to avoid unnecessary arithmetic when scales are identity. */ bool m_ScalesAreIdentity; + /** Scales estimator. Optionally provided by user. */ + typename ScalesEstimatorType::Pointer m_ScalesEstimator; + /** Flag to avoid unnecessary arithmetic when weights are identity. */ bool m_WeightsAreIdentity; - virtual void PrintSelf(std::ostream & os, Indent indent) const; + /** Flag to control use of the ScalesEstimator (if set) for + * automatic scale estimation during StartOptimization() + */ + bool m_DoEstimateScales; + + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectOptimizerBase.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectOptimizerBase.hxx index dfe3453151087d356887d7bcd17baaf0212a8dbd..e730b9304f3ec5bf5fe871bf1a3c78e7e10f52fd 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectOptimizerBase.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkObjectToObjectOptimizerBase.hxx @@ -29,13 +29,16 @@ template<typename TInternalComputationValueType> ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> ::ObjectToObjectOptimizerBaseTemplate() { - this->m_Metric = NULL; + this->m_Metric = ITK_NULLPTR; + this->m_CurrentIteration = 0; + this->m_NumberOfIterations = 100; this->m_CurrentMetricValue = 0; // Initialize, but w/out calling SetNumberOfThreads, to avoid // valgrind warning. this->m_NumberOfThreads = MultiThreader::GetGlobalDefaultNumberOfThreads(); this->m_ScalesAreIdentity = false; this->m_WeightsAreIdentity = true; + this->m_DoEstimateScales = true; } //------------------------------------------------------------------- @@ -54,13 +57,13 @@ ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> os << indent << "Number of threads: " << this->m_NumberOfThreads << std::endl; os << indent << "Number of scales: " << this->m_Scales.Size() << std::endl; - if( this->m_Scales.Size() > 0 ) + if( this->GetScalesInitialized() ) { os << indent << "m_Scales: " << this->m_Scales << std::endl; } else { - os << indent << "m_Scales is unset." << std::endl; + os << indent << "m_Scales: uninitialized." << std::endl; } os << indent << "m_ScalesAreIdentity: " << this->GetScalesAreIdentity() << std::endl; if( this->m_Weights.Size() > 0 ) @@ -72,8 +75,14 @@ ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> os << indent << "m_Weights is unset. Treated as identity." << std::endl; } os << indent << "m_WeightsAreIdentity: " << this->GetWeightsAreIdentity() << std::endl; - os << indent << "Metric: " << std::endl; - m_Metric->Print( os, indent.GetNextIndent() ); + itkPrintSelfObjectMacro( Metric ); + itkPrintSelfObjectMacro( ScalesEstimator ); + if ( this->m_CurrentIteration > 0 ) + { + os << indent << "CurrentIteration: " << this->m_CurrentIteration << std::endl; + } + os << indent << "Number of iterations: " << this->m_NumberOfIterations << std::endl; + os << indent << "DoEstimateScales: " << this->m_DoEstimateScales << std::endl; } //------------------------------------------------------------------- @@ -106,9 +115,18 @@ ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> return; } + /* Estimate the parameter scales if requested. */ + if ( this->m_DoEstimateScales && this->m_ScalesEstimator.IsNotNull() ) + { + ScalesType scales; + this->m_ScalesEstimator->EstimateScales( scales ); + this->SetScales( scales ); + itkDebugMacro( "Estimated scales = " << this->m_Scales ); + } + /* Verify m_Scales. If m_Scales hasn't been set, initialize to all 1's. */ typedef typename ScalesType::ValueType SValueType; - if( this->m_Scales.Size() > 0 ) + if( this->GetScalesInitialized() ) { if( this->m_Scales.Size() != this->m_Metric->GetNumberOfLocalParameters() ) { @@ -125,12 +143,12 @@ ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> { if( this->m_Scales[i] <= NumericTraits<SValueType>::epsilon() ) { - itkExceptionMacro("m_Scales values must be > epsilon."); + itkExceptionMacro("m_Scales values must be > epsilon." << this->m_Scales); } /* Check if the scales are identity. Consider to be identity if * within a tolerance, to allow for automatically estimated scales * that may not be exactly 1.0 when in priciniple they should be. */ - SValueType difference = vcl_fabs( NumericTraits<SValueType>::OneValue() - this->m_Scales[i] ); + SValueType difference = std::fabs( NumericTraits<SValueType>::OneValue() - this->m_Scales[i] ); SValueType tolerance = static_cast<SValueType>( 0.01 ); if( difference > tolerance ) { @@ -161,7 +179,7 @@ ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> this->m_WeightsAreIdentity = true; for( SizeType i=0; i < this->m_Weights.Size(); i++ ) { - SValueType difference = vcl_fabs( NumericTraits<SValueType>::OneValue() - this->m_Weights[i] ); + SValueType difference = std::fabs( NumericTraits<SValueType>::OneValue() - this->m_Weights[i] ); SValueType tolerance = static_cast<SValueType>( 1e-4 ); if( difference > tolerance ) { @@ -199,6 +217,13 @@ ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> return this->GetCurrentMetricValue(); } +template<typename TInternalComputationValueType> +bool +ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> +::GetScalesInitialized( void ) const +{ + return m_Scales.Size() > 0; +} }//namespace itk #endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOnePlusOneEvolutionaryOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOnePlusOneEvolutionaryOptimizerv4.h new file mode 100644 index 0000000000000000000000000000000000000000..0f622834d3e0cd69fcb66d94a52b9ebc9a7beaa2 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOnePlusOneEvolutionaryOptimizerv4.h @@ -0,0 +1,216 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkOnePlusOneEvolutionaryOptimizerv4_h +#define __itkOnePlusOneEvolutionaryOptimizerv4_h + +#include "itkObjectToObjectOptimizerBase.h" +#include "itkRandomVariateGeneratorBase.h" +#include <string> + +namespace itk +{ +/** \class OnePlusOneEvolutionaryOptimizerv4 + * \brief 1+1 evolutionary strategy optimizer + * + * This optimizer searches for the optimal parameters. It changes its search + * radius and position using the grow factor ,shrink factor, and isotropic + * probability function (which is a random unit normal variate generator). + * + * This optimizer needs a cost function and a random unit normal + * variate generator. + * The cost function should return cost with new position in parameter space + * which will be generated by 1+1 evolutionary strategy. + * Users should plug-in the random unit normal variate generator using + * SetNormalVariateGenerator method. + * + * The SetEpsilon method is the minimum value for the frobenius_norm of + * the covariance matrix. If the fnorm is smaller than this value, + * the optimization process will stop even before it hits the maximum + * iteration. + * + * Another way to stop the optimization process is calling the + * StopOptimization method. At next iteration after calling it, the + * optimization process will stop. + * + * This optimizing scheme was initially developed and implemented + * by Martin Styner, Univ. of North Carolina at Chapel Hill, and his + * colleagues. + * + * For more details. refer to the following articles. + * "Parametric estimate of intensity inhomogeneities applied to MRI" + * Martin Styner, G. Gerig, Christian Brechbuehler, Gabor Szekely, + * IEEE TRANSACTIONS ON MEDICAL IMAGING; 19(3), pp. 153-165, 2000, + * (http://www.cs.unc.edu/~styner/docs/tmi00.pdf) + * + * "Evaluation of 2D/3D bias correction with 1+1ES-optimization" + * Martin Styner, Prof. Dr. G. Gerig (IKT, BIWI, ETH Zuerich), TR-197 + * (http://www.cs.unc.edu/~styner/docs/StynerTR97.pdf) + * + * \sa NormalVariateGenerator + * \ingroup ITKOptimizersv4 + */ + +template<typename TInternalComputationValueType> +class OnePlusOneEvolutionaryOptimizerv4: + public ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> +{ +public: + /** Standard "Self" typedef. */ + typedef OnePlusOneEvolutionaryOptimizerv4 Self; + typedef ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(OnePlusOneEvolutionaryOptimizerv4, Superclass); + + /** Type of the Cost Function */ + typedef SingleValuedCostFunctionv4 CostFunctionType; + typedef CostFunctionType::Pointer CostFunctionPointer; + + /** Normal random variate generator type. */ + typedef Statistics::RandomVariateGeneratorBase NormalVariateGeneratorType; + + /** Measure type */ + typedef typename Superclass::MeasureType MeasureType; + + /** Parameters type */ + typedef typename Superclass::ParametersType ParametersType; + + /** Scales type */ + typedef typename Superclass::ScalesType ScalesType; + + /** Set/Get maximum iteration limit. */ + itkSetMacro(MaximumIteration, unsigned int); + itkGetConstReferenceMacro(MaximumIteration, unsigned int); + + /** Set/Get the search radius grow factor in parameter space. */ + itkSetMacro(GrowthFactor, double); + itkGetConstReferenceMacro(GrowthFactor, double); + + /** Set/Get the search radius shrink factor. */ + itkSetMacro(ShrinkFactor, double); + itkGetConstReferenceMacro(ShrinkFactor, double); + + /** Set/Get initial search radius in parameter space */ + itkSetMacro(InitialRadius, double); + itkGetConstReferenceMacro(InitialRadius, double); + + /** Set/Get the minimal size of search radius + * (frobenius_norm of covariance matrix). */ + itkSetMacro(Epsilon, double); + itkGetConstReferenceMacro(Epsilon, double); + + /** Get the current Frobenius norm of covariance matrix */ + itkGetConstReferenceMacro(FrobeniusNorm, double); + + void SetNormalVariateGenerator(NormalVariateGeneratorType *generator); + + /** Initializes the optimizer. + * Before running this optimizer, this function should have been called. + * + * initialRadius: search radius in parameter space + * grow: search radius grow factor + * shrink: searhc radius shrink factor */ + void Initialize(double initialRadius, double grow = -1, double shrink = -1); + + /** Return Current Value */ + itkGetConstReferenceMacro(CurrentCost, MeasureType); + virtual const MeasureType & GetValue() const ITK_OVERRIDE; + + /** Return if optimizer has been initialized */ + itkGetConstReferenceMacro(Initialized, bool); + + /** Start optimization. + * Optimization will stop when it meets either of two termination conditions, + * the maximum iteration limit or epsilon (minimal search radius) */ + virtual void StartOptimization(bool doOnlyInitialization = false) ITK_OVERRIDE; + + /** when users call StartOptimization, this value will be set false. + * By calling StopOptimization, this flag will be set true, and + * optimization will stop at the next iteration. */ + void StopOptimization() + { m_Stop = true; } + + itkGetConstReferenceMacro(CatchGetValueException, bool); + itkSetMacro(CatchGetValueException, bool); + + itkGetConstReferenceMacro(MetricWorstPossibleValue, double); + itkSetMacro(MetricWorstPossibleValue, double); + + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; + +protected: + OnePlusOneEvolutionaryOptimizerv4(); + OnePlusOneEvolutionaryOptimizerv4(const OnePlusOneEvolutionaryOptimizerv4 &); + virtual ~OnePlusOneEvolutionaryOptimizerv4(); + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + +private: + + /** Smart pointer to the normal random variate generator. */ + NormalVariateGeneratorType::Pointer m_RandomGenerator; + + /** Maximum iteration limit. */ + unsigned int m_MaximumIteration; + + bool m_CatchGetValueException; + double m_MetricWorstPossibleValue; + + /** The minimal size of search radius + * (frobenius_norm of covariance matrix). */ + double m_Epsilon; + + /** Initial search radius in parameter space. */ + double m_InitialRadius; + + /** Search radius growth factor in parameter space. */ + double m_GrowthFactor; + + /** Search radius shrink factor in parameter space, */ + double m_ShrinkFactor; + + /** Flag tells if the optimizer was initialized using Initialize function. */ + bool m_Initialized; + + /** Internal storage for the value type / used as a cache */ + MeasureType m_CurrentCost; + + /** This is user-settable flag to stop optimization. + * when users call StartOptimization, this value will be set false. + * By calling StopOptimization, this flag will be set true, and + * optimization will stop at the next iteration. */ + bool m_Stop; + + /** Stop description */ + std::ostringstream m_StopConditionDescription; + + /** Cache variable for reporting the Frobenius Norm + */ + double m_FrobeniusNorm; +}; // end of class +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkOnePlusOneEvolutionaryOptimizerv4.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOnePlusOneEvolutionaryOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOnePlusOneEvolutionaryOptimizerv4.hxx new file mode 100644 index 0000000000000000000000000000000000000000..0e3425ce4ed56fdd8afc982b44d0aa98e3484e5d --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOnePlusOneEvolutionaryOptimizerv4.hxx @@ -0,0 +1,337 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkOnePlusOneEvolutionaryOptimizerv4_hxx +#define __itkOnePlusOneEvolutionaryOptimizerv4_hxx + +#include "itkOnePlusOneEvolutionaryOptimizerv4.h" +#include "vnl/vnl_matrix.h" +namespace itk +{ +template<typename TInternalComputationValueType> +OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType> +::OnePlusOneEvolutionaryOptimizerv4() +{ + m_CatchGetValueException = false; + m_MetricWorstPossibleValue = 0; + + m_Epsilon = (double)1.5e-4; + m_RandomGenerator = ITK_NULLPTR; + + m_Initialized = false; + m_GrowthFactor = 1.05; + m_ShrinkFactor = std::pow(m_GrowthFactor, -0.25); + m_InitialRadius = 1.01; + m_MaximumIteration = 100; + m_Stop = false; + m_StopConditionDescription.str(""); + m_CurrentCost = 0; + m_FrobeniusNorm = 0.0; +} + +template<typename TInternalComputationValueType> +OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType> +::~OnePlusOneEvolutionaryOptimizerv4() +{} + +template<typename TInternalComputationValueType> +void +OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType> +::SetNormalVariateGenerator(NormalVariateGeneratorType *generator) +{ + if ( m_RandomGenerator != generator ) + { + m_RandomGenerator = generator; + this->Modified(); + } +} + +template<typename TInternalComputationValueType> +void +OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType> +::Initialize(double initialRadius, double grow, double shrink) +{ + m_InitialRadius = initialRadius; + + if ( grow == -1 ) + { + m_GrowthFactor = 1.05; + } + else + { + m_GrowthFactor = grow; + } + if ( shrink == -1 ) + { + m_ShrinkFactor = std::pow(m_GrowthFactor, -0.25); + } + else + { + m_ShrinkFactor = shrink; + } +} + +template<typename TInternalComputationValueType> +void +OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType> +::StartOptimization(bool /* doOnlyInitialization */) +{ + if ( this->m_Metric.IsNull() ) + { + return; + } + + Superclass::StartOptimization(); + + this->InvokeEvent( StartEvent() ); + m_Stop = false; + + unsigned int spaceDimension = this->m_Metric->GetNumberOfParameters(); + vnl_matrix< double > A(spaceDimension, spaceDimension); + vnl_vector< double > parent( this->m_Metric->GetParameters() ); + vnl_vector< double > f_norm(spaceDimension); + vnl_vector< double > child(spaceDimension); + vnl_vector< double > delta(spaceDimension); + + ParametersType parentPosition(spaceDimension); + ParametersType childPosition(spaceDimension); + + for ( unsigned int i = 0; i < spaceDimension; i++ ) + { + parentPosition[i] = parent[i]; + } + this->m_Metric->SetParameters( parentPosition ); + + double pvalue = m_MetricWorstPossibleValue; + try + { + pvalue = this->m_Metric->GetValue(); + } + catch ( ... ) + { + if ( m_CatchGetValueException ) + { + pvalue = m_MetricWorstPossibleValue; + } + else + { + throw; + } + } + + itkDebugMacro(<< ": initial position: " << parentPosition); + itkDebugMacro(<< ": initial fitness: " << pvalue); + + this->m_Metric->SetParameters(parentPosition); + const ScalesType & scales = this->GetScales(); + + // Make sure the scales have been set properly + if ( scales.size() != spaceDimension ) + { + itkExceptionMacro(<< "The size of Scales is " + << scales.size() + << ", but the NumberOfParameters for the CostFunction is " + << spaceDimension + << "."); + } + + A.set_identity(); + for ( unsigned int i = 0; i < spaceDimension; i++ ) + { + A(i, i) = m_InitialRadius / scales[i]; + } + this->m_CurrentIteration = 0; + + for ( unsigned int iter = 0; iter < m_MaximumIteration; iter++ ) + { + if ( m_Stop ) + { + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + m_StopConditionDescription << "StopOptimization() called"; + break; + } + + ++this->m_CurrentIteration; + + for ( unsigned int i = 0; i < spaceDimension; i++ ) + { + if ( !m_RandomGenerator ) + { + itkExceptionMacro(<< "Random Generator is not set!"); + } + f_norm[i] = m_RandomGenerator->GetVariate(); + } + + delta = A * f_norm; + child = parent + delta; + + for ( unsigned int i = 0; i < spaceDimension; i++ ) + { + childPosition[i] = child[i]; + } + // Update the metric so we can check the metric value in childPosition + this->m_Metric->SetParameters( childPosition ); + + double cvalue = m_MetricWorstPossibleValue; + try + { + cvalue = this->m_Metric->GetValue(); + // While we got the metric value in childPosition, + // the metric paramteres are set back to parentPosition + this->m_Metric->SetParameters( parentPosition ); + } + catch ( ... ) + { + if ( m_CatchGetValueException ) + { + cvalue = m_MetricWorstPossibleValue; + } + else + { + throw; + } + } + + itkDebugMacro(<< "iter: " << iter << ": parent position: " + << parentPosition); + itkDebugMacro(<< "iter: " << iter << ": parent fitness: " + << pvalue); + itkDebugMacro(<< "iter: " << iter << ": random vector: " << f_norm); + itkDebugMacro(<< "iter: " << iter << ": A: " << std::endl << A); + itkDebugMacro(<< "iter: " << iter << ": delta: " << delta); + itkDebugMacro(<< "iter: " << iter << ": child position: " + << childPosition); + itkDebugMacro(<< "iter: " << iter << ": child fitness: " + << cvalue); + + double adjust = m_ShrinkFactor; + + if ( cvalue < pvalue ) + { + itkDebugMacro(<< "iter: " << iter << ": increasing search radius"); + pvalue = cvalue; + parent.swap(child); + adjust = m_GrowthFactor; + for ( unsigned int i = 0; i < spaceDimension; i++ ) + { + parentPosition[i] = parent[i]; + } + this->m_Metric->SetParameters(parentPosition); + } + else + { + itkDebugMacro(<< "iter: " << iter << ": decreasing search radius"); + } + + m_CurrentCost = pvalue; + // convergence criterion: f-norm of A < epsilon_A + // Compute double precision sum of absolute values of + // a single precision vector + m_FrobeniusNorm = A.fro_norm(); + itkDebugMacro(<< "A f-norm:" << m_FrobeniusNorm); + if ( m_FrobeniusNorm <= m_Epsilon ) + { + itkDebugMacro(<< "converges at iteration = " << iter); + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + m_StopConditionDescription << "Fnorm (" << m_FrobeniusNorm + << ") is less than Epsilon (" << m_Epsilon + << " at iteration #" << iter; + this->InvokeEvent( EndEvent() ); + return; + } + + // A += (adjust - 1)/ (f_norm * f_norm) * A * f_norm * f_norm; + // Blas_R1_Update(A, A * f_norm, f_norm, + // ((adjust - 1) / Blas_Dot_Prod(f_norm, f_norm))); + // = DGER(Fortran) + // performs the rank 1 operation + // A := alpha*x*y' + A, + // where y' = transpose(y) + // where alpha is a scalar, x is an m element vector, y is an n element + // vector and A is an m by n matrix. + // x = A * f_norm , y = f_norm, alpha = (adjust - 1) / Blas_Dot_Prod( + // f_norm, f_norm) + + //A = A + (adjust - 1.0) * A; + double alpha = ( ( adjust - 1.0 ) / dot_product(f_norm, f_norm) ); + for ( unsigned int c = 0; c < spaceDimension; c++ ) + { + for ( unsigned int r = 0; r < spaceDimension; r++ ) + { + A(r, c) += alpha * delta[r] * f_norm[c]; + } + } + + this->InvokeEvent( IterationEvent() ); + itkDebugMacro( << "Current position: " << this->GetCurrentPosition() ); + } + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + m_StopConditionDescription << "Maximum number of iterations (" + << m_MaximumIteration + << ") exceeded. "; + this->InvokeEvent( EndEvent() ); +} + +template<typename TInternalComputationValueType> +const std::string +OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType> +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); +} + +template<typename TInternalComputationValueType> +const typename OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>::MeasureType & +OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType> +::GetValue() const +{ + return this->GetCurrentCost(); +} + +template<typename TInternalComputationValueType> +void +OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType> +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + if ( m_RandomGenerator ) + { + os << indent << "Random Generator " << m_RandomGenerator.GetPointer() << std::endl; + } + else + { + os << indent << "Random Generator " << "(none)" << std::endl; + } + os << indent << "Maximum Iteration " << GetMaximumIteration() << std::endl; + os << indent << "Epsilon " << GetEpsilon() << std::endl; + os << indent << "Initial Radius " << GetInitialRadius() << std::endl; + os << indent << "Growth Fractor " << GetGrowthFactor() << std::endl; + os << indent << "Shrink Fractor " << GetShrinkFactor() << std::endl; + os << indent << "Initialized " << GetInitialized() << std::endl; + os << indent << "Current Cost " << GetCurrentCost() << std::endl; + os << indent << "Frobenius Norm " << GetFrobeniusNorm() << std::endl; + os << indent << "CatchGetValueException " << GetCatchGetValueException() + << std::endl; + os << indent << "MetricWorstPossibleValue " << GetMetricWorstPossibleValue() + << std::endl; +} +} // end of namespace itk +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOptimizerParameterScalesEstimator.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOptimizerParameterScalesEstimator.h index 11a35522f982cda1e5ae35c13cfe769a8c274a58..3bc34c93c1d15409080ec77feba2029d5711b514 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOptimizerParameterScalesEstimator.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkOptimizerParameterScalesEstimator.h @@ -20,7 +20,7 @@ #include "itkObject.h" #include "itkObjectFactory.h" -#include "itkObjectToObjectOptimizerBase.h" +#include "itkOptimizerParameters.h" namespace itk { @@ -48,11 +48,12 @@ public: itkTypeMacro( OptimizerParameterScalesEstimatorTemplate, Object ); /** Type of scales */ - typedef typename ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType>::ScalesType ScalesType; + typedef OptimizerParameters<TInternalComputationValueType> ScalesType; /** Type of parameters of the optimizer */ - typedef typename ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType>::ParametersType ParametersType; + typedef OptimizerParameters<TInternalComputationValueType> ParametersType; + /** Type of float */ - typedef TInternalComputationValueType FloatType; + typedef TInternalComputationValueType FloatType; /** Estimate parameter scales. */ virtual void EstimateScales(ScalesType &scales) = 0; @@ -71,7 +72,7 @@ protected: OptimizerParameterScalesEstimatorTemplate(){}; ~OptimizerParameterScalesEstimatorTemplate(){}; - void PrintSelf(std::ostream &os, Indent indent) const + virtual void PrintSelf(std::ostream &os, Indent indent) const ITK_OVERRIDE { Superclass::PrintSelf(os,indent); } diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkPowellOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkPowellOptimizerv4.h new file mode 100644 index 0000000000000000000000000000000000000000..408ef734895ebecdf8e0cc771efd466a1c59cde6 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkPowellOptimizerv4.h @@ -0,0 +1,245 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkPowellOptimizerv4_h +#define __itkPowellOptimizerv4_h + +#include "itkVector.h" +#include "itkMatrix.h" +#include "itkObjectToObjectOptimizerBase.h" + +namespace itk +{ +/** \class PowellOptimizerv4 + * \brief Implements Powell optimization using Brent line search. + * + * The code in this class was adapted from the Wikipedia and the + * netlib.org zeroin function. + * + * http://www.netlib.org/go/zeroin.f + * http://en.wikipedia.org/wiki/Brent_method + * http://en.wikipedia.org/wiki/Golden_section_search + * + * This optimizer needs a cost function. + * Partial derivatives of that function are not required. + * + * For an N-dimensional parameter space, each iteration minimizes + * the function in N (initially orthogonal) directions. Typically only 2-5 + * iterations are required. If gradients are available, consider a conjugate + * gradient line search strategy. + * + * The SetStepLength determines the initial distance to step in a line direction + * when bounding the minimum (using bracketing triple spaced using a golden + * search strategy). + * + * The StepTolerance terminates optimization when the parameter values are + * known to be within this (scaled) distance of the local extreme. + * + * The ValueTolerance terminates optimization when the cost function values at + * the current parameters and at the local extreme are likely (within a second + * order approximation) to be within this is tolerance. + * + * \ingroup ITKOptimizersv4 + */ +template<typename TInternalComputationValueType> +class PowellOptimizerv4: + public ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> +{ +public: + /** Standard "Self" typedef. */ + typedef PowellOptimizerv4 Self; + typedef ObjectToObjectOptimizerBaseTemplate<TInternalComputationValueType> Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Method for creation through the object factory. */ + itkNewMacro(Self); + + /** Run-time type information (and related methods). */ + itkTypeMacro(PowellOptimizerv4, Superclass); + + typedef typename Superclass::ParametersType ParametersType; + typedef typename Superclass::MeasureType MeasureType; + typedef typename Superclass::ScalesType ScalesType; + + /** Set/Get maximum iteration limit. */ + itkSetMacro(MaximumIteration, unsigned int); + itkGetConstReferenceMacro(MaximumIteration, unsigned int); + + /** Set/Get the maximum number of line search iterations */ + itkSetMacro(MaximumLineIteration, unsigned int); + itkGetConstMacro(MaximumLineIteration, unsigned int); + + /** Set/Get StepLength for the (scaled) spacing of the sampling of + * parameter space while bracketing the extremum */ + itkSetMacro(StepLength, double); + itkGetConstReferenceMacro(StepLength, double); + + /** Set/Get StepTolerance. Once the local extreme is known to be within this + * distance of the current parameter values, optimization terminates */ + itkSetMacro(StepTolerance, double); + itkGetConstReferenceMacro(StepTolerance, double); + + /** Set/Get ValueTolerance. Once this current cost function value is known + * to be within this tolerance of the cost function value at the local + * extreme, optimization terminates */ + itkSetMacro(ValueTolerance, double); + itkGetConstReferenceMacro(ValueTolerance, double); + + /** Return Current Value */ + itkGetConstReferenceMacro(CurrentCost, MeasureType); + virtual const MeasureType & GetValue() const { return this->GetCurrentCost(); } + + /** Get the current line search iteration */ + itkGetConstReferenceMacro(CurrentLineIteration, unsigned int); + + /** Start optimization. */ + virtual void StartOptimization(bool doOnlyInitialization = false) ITK_OVERRIDE; + + /** When users call StartOptimization, this value will be set false. + * By calling StopOptimization, this flag will be set true, and + * optimization will stop at the next iteration. */ + void StopOptimization() + { m_Stop = true; } + + itkGetConstReferenceMacro(CatchGetValueException, bool); + itkSetMacro(CatchGetValueException, bool); + + itkGetConstReferenceMacro(MetricWorstPossibleValue, double); + itkSetMacro(MetricWorstPossibleValue, double); + + virtual const std::string GetStopConditionDescription() const ITK_OVERRIDE; + +protected: + PowellOptimizerv4(); + PowellOptimizerv4(const PowellOptimizerv4 &); + virtual ~PowellOptimizerv4(); + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + + itkSetMacro(CurrentCost, double); + + /** Used to specify the line direction through the n-dimensional parameter + * space the is currently being bracketed and optimized. */ + void SetLine(const ParametersType & origin, + const vnl_vector< double > & direction); + + /** Get the value of the n-dimensional cost function at this scalar step + * distance along the current line direction from the current line origin. + * Line origin and distances are set via SetLine */ + double GetLineValue(double x) const; + + double GetLineValue(double x, ParametersType & tempCoord) const; + + /** Set the given scalar step distance (x) and function value (fx) as the + * "best-so-far" optimizer values. */ + void SetCurrentLinePoint(double x, double fx); + + /** Used in bracketing the extreme along the current line. + * Adapted from NRC */ + void Swap(double *a, double *b) const; + + /** Used in bracketing the extreme along the current line. + * Adapted from NRC */ + void Shift(double *a, double *b, double *c, double d) const; + + /** The LineBracket routine from NRC. Later reimplemented from the description + * of the method available in the Wikipedia. + * + * Uses current origin and line direction (from SetLine) to find a triple of + * points (ax, bx, cx) that bracket the extreme "near" the origin. Search + * first considers the point StepLength distance from ax. + * + * IMPORTANT: The value of ax and the value of the function at ax (i.e., fa), + * must both be provided to this function. */ + virtual void LineBracket(double *ax, double *bx, double *cx, + double *fa, double *fb, double *fc); + + virtual void LineBracket(double *ax, double *bx, double *cx, + double *fa, double *fb, double *fc, + ParametersType & tempCoord); + + /** Given a bracketing triple of points and their function values, returns + * a bounded extreme. These values are in parameter space, along the + * current line and wrt the current origin set via SetLine. Optimization + * terminates based on MaximumIteration, StepTolerance, or ValueTolerance. + * Implemented as Brent line optimers from NRC. */ + virtual void BracketedLineOptimize(double ax, double bx, double cx, + double fa, double fb, double fc, + double *extX, double *extVal); + + virtual void BracketedLineOptimize(double ax, double bx, double cx, + double fa, double fb, double fc, + double *extX, double *extVal, + ParametersType & tempCoord); + + itkGetMacro(SpaceDimension, unsigned int); + void SetSpaceDimension(unsigned int dim) + { + this->m_SpaceDimension = dim; + this->m_LineDirection.set_size(dim); + this->m_LineOrigin.set_size(dim); + this->m_CurrentPosition.set_size(dim); + this->Modified(); + } + + itkSetMacro(CurrentIteration, unsigned int); + + itkGetMacro(Stop, bool); + itkSetMacro(Stop, bool); + +private: + unsigned int m_SpaceDimension; + + /** Current iteration */ + unsigned int m_CurrentLineIteration; + + /** Maximum iteration limit. */ + unsigned int m_MaximumIteration; + unsigned int m_MaximumLineIteration; + + bool m_CatchGetValueException; + double m_MetricWorstPossibleValue; + + /** The minimal size of search */ + double m_StepLength; + double m_StepTolerance; + + ParametersType m_LineOrigin; + vnl_vector< double > m_LineDirection; + + double m_ValueTolerance; + + /** Internal storage for the value type / used as a cache */ + MeasureType m_CurrentCost; + + /** this is user-settable flag to stop optimization. + * when users call StartOptimization, this value will be set false. + * By calling StopOptimization, this flag will be set true, and + * optimization will stop at the next iteration. */ + bool m_Stop; + + ParametersType m_CurrentPosition; + + std::ostringstream m_StopConditionDescription; +}; // end of class +} // end of namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkPowellOptimizerv4.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkPowellOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkPowellOptimizerv4.hxx new file mode 100644 index 0000000000000000000000000000000000000000..190361517d6efdcb3af321bc7569f88ef6cc4942 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkPowellOptimizerv4.hxx @@ -0,0 +1,582 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkPowellOptimizerv4_hxx +#define __itkPowellOptimizerv4_hxx + +#include "itkPowellOptimizerv4.h" + +namespace itk +{ +template<typename TInternalComputationValueType> +PowellOptimizerv4<TInternalComputationValueType> +::PowellOptimizerv4(): + m_SpaceDimension(0), + m_CurrentLineIteration(0), + m_MaximumIteration(100), + m_MaximumLineIteration(100), + m_CatchGetValueException(false), + m_MetricWorstPossibleValue(0), + m_StepLength(0), + m_StepTolerance(0), + m_ValueTolerance(0), + m_CurrentCost(0), + m_Stop(false) +{ + m_StopConditionDescription << this->GetNameOfClass() << ": "; +} + +template<typename TInternalComputationValueType> +PowellOptimizerv4<TInternalComputationValueType> +::~PowellOptimizerv4() +{} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::SetLine(const ParametersType & origin, + const vnl_vector< double > & direction) +{ + const ScalesType & scales = this->GetScales(); + for ( unsigned int i = 0; i < m_SpaceDimension; ++i ) + { + m_LineOrigin[i] = origin[i]; + if( this->GetScalesAreIdentity() ) + { + m_LineDirection[i] = direction[i]; + } + else + { + m_LineDirection[i] = direction[i] / scales[i]; + } + } +} + +template<typename TInternalComputationValueType> +double +PowellOptimizerv4<TInternalComputationValueType> +::GetLineValue(double x) const +{ + ParametersType tempCoord(m_SpaceDimension); + + return this->GetLineValue(x, tempCoord); +} + +template<typename TInternalComputationValueType> +double +PowellOptimizerv4<TInternalComputationValueType> +::GetLineValue(double x, ParametersType & tempCoord) const +{ + for ( unsigned int i = 0; i < m_SpaceDimension; i++ ) + { + tempCoord[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i]; + } + this->m_Metric->SetParameters(tempCoord); + itkDebugMacro(<< "x = " << x); + double val; + try + { + val = ( this->m_Metric->GetValue() ); + } + catch ( ... ) + { + if ( m_CatchGetValueException ) + { + val = m_MetricWorstPossibleValue; + } + else + { + throw; + } + } + itkDebugMacro(<< "val = " << val); + return val; +} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::SetCurrentLinePoint(double x, double fx) +{ + for ( unsigned int i = 0; i < m_SpaceDimension; i++ ) + { + this->m_CurrentPosition[i] = this->m_LineOrigin[i] + x * this->m_LineDirection[i]; + } + this->m_Metric->SetParameters(m_CurrentPosition); + this->SetCurrentCost(fx); + this->Modified(); +} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::Swap(double *a, double *b) const +{ + double tf; + + tf = *a; + *a = *b; + *b = tf; +} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::Shift(double *a, double *b, double *c, double d) const +{ + *a = *b; + *b = *c; + *c = d; +} + +// +// This code was implemented from the description of +// the Golden section search available in the Wikipedia +// +// http://en.wikipedia.org/wiki/Golden_section_search +// +// +// The inputs to this function are +// +// x1 and its function value f1 +// x2 +// +// (f2 is not yet evaluated, it will be computed inside) +// (x2 and its function value f3 are also computed inside) +// +// The outputs are the values of x2 and f2 at +// the end of the iterations. +// +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::LineBracket(double *x1, double *x2, double *x3, + double *f1, double *f2, double *f3) +{ + ParametersType tempCoord(m_SpaceDimension); + + this->LineBracket(x1, x2, x3, f1, f2, f3, tempCoord); +} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::LineBracket(double *x1, double *x2, double *x3, + double *f1, double *f2, double *f3, + ParametersType & tempCoord) +{ + // + // Compute the golden ratio as a constant to be + // used when extrapolating the bracket + // + const double goldenRatio = ( 1.0 + std::sqrt(5.0) ) / 2.0; + + // + // Get the value of the function for point x2 + // + *f2 = this->GetLineValue(*x2, tempCoord); + + // + // Compute extrapolated point using the golden ratio + // + if ( *f2 >= *f1 ) + { + this->Swap(x1, x2); + this->Swap(f1, f2); + } + + // compute x3 on the side of x2 + *x3 = *x1 + goldenRatio * ( *x2 - *x1 ); + *f3 = this->GetLineValue(*x3, tempCoord); + + // If the new point is a minimum + // then continue extrapolating in + // that direction until we find a + // value of f3 that makes f2 to be + // a minimum. + while ( *f3 < *f2 ) + { + *x2 = *x3; + *f2 = *f3; + *x3 = *x1 + goldenRatio * ( *x2 - *x1 ); + *f3 = this->GetLineValue(*x3, tempCoord); + } + + itkDebugMacro(<< "Initial: " << *x1 << ", " << *x2 << ", " << *x3); + // + // Report the central point as the minimum + // + this->SetCurrentLinePoint(*x2, *f2); +} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::BracketedLineOptimize(double ax, double bx, double cx, + double fa, double functionValueOfb, double fc, + double *extX, double *extVal) +{ + ParametersType tempCoord(m_SpaceDimension); + + this->BracketedLineOptimize(ax, bx, cx, fa, functionValueOfb, fc, extX, extVal, tempCoord); +} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::BracketedLineOptimize(double ax, double bx, double cx, + double itkNotUsed(fa), double functionValueOfb, double itkNotUsed(fc), + double *extX, double *extVal, + ParametersType & tempCoord) +{ + double x; + double v = 0.0; + double w; /* Abscissae, descr. see above */ + double a; + double b; + + a = ( ax < cx ? ax : cx ); + b = ( ax > cx ? ax : cx ); + + x = bx; + w = bx; + + const double goldenSectionRatio = ( 3.0 - std::sqrt(5.0) ) / 2; /* Gold + section + ratio */ + const double POWELL_TINY = 1.0e-20; + + double functionValueOfX; /* f(x) */ + double functionValueOfV; /* f(v) */ + double functionValueOfW; /* f(w) */ + + functionValueOfV = functionValueOfb; + functionValueOfX = functionValueOfV; + functionValueOfW = functionValueOfV; + + for ( m_CurrentLineIteration = 0; + m_CurrentLineIteration < m_MaximumLineIteration; + m_CurrentLineIteration++ ) + { + double middle_range = ( a + b ) / 2; + + double new_step; /* Step at this iteration */ + + double tolerance1; + double tolerance2; + + tolerance1 = m_StepTolerance * std::fabs(x) + POWELL_TINY; + tolerance2 = 2.0 * tolerance1; + + if ( std::fabs(x - middle_range) <= ( tolerance2 - 0.5 * ( b - a ) ) + || 0.5 * ( b - a ) < m_StepTolerance ) + { + *extX = x; + *extVal = functionValueOfX; + this->SetCurrentLinePoint(x, functionValueOfX); + itkDebugMacro(<< "x = " << *extX); + itkDebugMacro(<< "val = " << *extVal); + itkDebugMacro(<< "return 1"); + return; /* Acceptable approx. is found */ + } + + /* Obtain the gold section step */ + new_step = goldenSectionRatio * ( x < middle_range ? b - x : a - x ); + + /* Decide if the interpolation can be tried */ + if ( std::fabs(x - w) >= tolerance1 ) /* If x and w are distinct */ + { + double t; + t = ( x - w ) * ( functionValueOfX - functionValueOfV ); + + double q; /* ted as p/q; division operation*/ + q = ( x - v ) * ( functionValueOfX - functionValueOfW ); + + double p; /* Interpolation step is calcula-*/ + p = ( x - v ) * q - ( x - w ) * t; + + q = 2 * ( q - t ); + + if ( q > (double)0 ) /* q was calculated with the op-*/ + { + p = -p; /* posite sign; make q positive */ + } + else /* and assign possible minus to */ + { + q = -q; /* p */ + } + + /* Chec if x+p/q falls in [a,b] and not too close to a and b + and isn't too large */ + if ( std::fabs(p) < std::fabs(new_step * q) + && p > q * ( a - x + 2 * tolerance1 ) + && p < q * ( b - x - 2 * tolerance1 ) ) + { + new_step = p / q; /* it is accepted */ + } + + /* If p/q is too large then the gold section procedure can + reduce [a,b] range to more extent */ + } + + /* Adjust the step to be not less than tolerance*/ + if ( std::fabs(new_step) < tolerance1 ) + { + if ( new_step > 0.0 ) + { + new_step = tolerance1; + } + else + { + new_step = -tolerance1; + } + } + + /* Obtain the next approximation to min */ + /* and reduce the enveloping range */ + double t = x + new_step; /* Tentative point for the min */ + + double functionValueOft; + + functionValueOft = this->GetLineValue(t, tempCoord); + + if ( functionValueOft <= functionValueOfX ) + { + if ( t < x ) /* Reduce the range so that */ + { + b = x; /* t would fall within it */ + } + else + { + a = x; + } + + /* assing the best approximation to x */ + v = w; + w = x; + x = t; + + functionValueOfV = functionValueOfW; + functionValueOfW = functionValueOfX; + functionValueOfX = functionValueOft; + } + else /* x remains the better approx */ + { + if ( t < x ) /* Reduce the range enclosing x */ + { + a = t; + } + else + { + b = t; + } + + if ( functionValueOft <= functionValueOfW || w == x ) + { + v = w; + w = t; + functionValueOfV = functionValueOfW; + functionValueOfW = functionValueOft; + } + else if ( functionValueOft <= functionValueOfV || v == x || v == w ) + { + v = t; + functionValueOfV = functionValueOft; + } + } + } + + *extX = x; + *extVal = functionValueOfX; + itkDebugMacro(<< "x = " << *extX); + itkDebugMacro(<< "val = " << *extVal); + itkDebugMacro(<< "return 2"); + + this->SetCurrentLinePoint(x, functionValueOfX); +} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::StartOptimization(bool /* doOnlyInitialization */) +{ + if ( this->m_Metric.IsNull() ) + { + return; + } + + Superclass::StartOptimization(); + + m_StopConditionDescription.str(""); + m_StopConditionDescription << this->GetNameOfClass() << ": "; + + this->InvokeEvent( StartEvent() ); + m_Stop = false; + + this->SetSpaceDimension( this->m_Metric->GetNumberOfParameters() ); + + vnl_matrix< double > xi(m_SpaceDimension, m_SpaceDimension); + vnl_vector< double > xit(m_SpaceDimension); + xi.set_identity(); + xit.fill(0); + xit[0] = 1; + + ParametersType tempCoord(m_SpaceDimension); + ParametersType p(m_SpaceDimension); + ParametersType pt(m_SpaceDimension); + ParametersType ptt(m_SpaceDimension); + p = this->m_Metric->GetParameters(); + pt = p; + + unsigned int ibig; + double fp, del, fptt; + double ax, xx, bx; + double fa, fx, fb; + + xx = 0; + this->SetLine(p, xit); + fx = this->GetLineValue(0, tempCoord); + + for ( this->m_CurrentIteration = 0; + this->m_CurrentIteration <= m_MaximumIteration; + this->m_CurrentIteration++ ) + { + fp = fx; + ibig = 0; + del = 0.0; + + for ( unsigned int i = 0; i < m_SpaceDimension; i++ ) + { + for ( unsigned int j = 0; j < m_SpaceDimension; ++j ) + { + xit[j] = xi[j][i]; + } + fptt = fx; + + this->SetLine(p, xit); + + ax = 0.0; + fa = fx; + xx = m_StepLength; + this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb, tempCoord); + this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx, tempCoord); + this->SetCurrentLinePoint(xx, fx); + p = this->GetCurrentPosition(); + + if ( std::fabs(fptt - fx) > del ) + { + del = std::fabs(fptt - fx); + ibig = i; + } + } + + if ( 2.0 * std::fabs(fp - fx) + <= m_ValueTolerance * ( std::fabs(fp) + std::fabs(fx) ) ) + { + m_StopConditionDescription << "Cost function values at the current parameter (" + << fx + << ") and at the local extrema (" + << fp + << ") are within Value Tolerance (" + << m_ValueTolerance << ")"; + this->InvokeEvent( EndEvent() ); + return; + } + + const ScalesType & scales = this->GetScales(); + for ( unsigned int j = 0; j < m_SpaceDimension; ++j ) + { + ptt[j] = 2.0 * p[j] - pt[j]; + + if( this->GetScalesAreIdentity() ) + { + xit[j] = p[j] - pt[j]; + } + else + { + xit[j] = ( p[j] - pt[j] ) * scales[j]; + } + + pt[j] = p[j]; + } + + this->SetLine(ptt, xit); + fptt = this->GetLineValue(0, tempCoord); + if ( fptt < fp ) + { + double t = 2.0 * ( fp - 2.0 * fx + fptt ) + * vnl_math_sqr(fp - fx - del) + - del *vnl_math_sqr(fp - fptt); + if ( t < 0.0 ) + { + this->SetLine(p, xit); + + ax = 0.0; + fa = fx; + xx = 1; + this->LineBracket(&ax, &xx, &bx, &fa, &fx, &fb, tempCoord); + this->BracketedLineOptimize(ax, xx, bx, fa, fx, fb, &xx, &fx, tempCoord); + this->SetCurrentLinePoint(xx, fx); + p = this->GetCurrentPosition(); + + for ( unsigned int j = 0; j < m_SpaceDimension; j++ ) + { + xi[j][ibig] = xx * xit[j]; + } + } + } + + this->InvokeEvent( IterationEvent() ); + } + + m_StopConditionDescription << "Maximum number of iterations exceeded. " + << "Number of iterations is " + << m_MaximumIteration; + this->InvokeEvent( EndEvent() ); +} + +template<typename TInternalComputationValueType> +const std::string +PowellOptimizerv4<TInternalComputationValueType> +::GetStopConditionDescription() const +{ + return m_StopConditionDescription.str(); +} + +template<typename TInternalComputationValueType> +void +PowellOptimizerv4<TInternalComputationValueType> +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "Metric Worst Possible Value " << m_MetricWorstPossibleValue << std::endl; + os << indent << "Catch GetValue Exception " << m_CatchGetValueException << std::endl; + os << indent << "Space Dimension " << m_SpaceDimension << std::endl; + os << indent << "Maximum Iteration " << m_MaximumIteration << std::endl; + os << indent << "StepLength " << m_StepLength << std::endl; + os << indent << "StepTolerance " << m_StepTolerance << std::endl; + os << indent << "ValueTolerance " << m_ValueTolerance << std::endl; + os << indent << "LineOrigin " << m_LineOrigin << std::endl; + os << indent << "LineDirection " << m_LineDirection << std::endl; + os << indent << "Current Cost " << m_CurrentCost << std::endl; + os << indent << "Maximum Line Iteration " << m_MaximumLineIteration << std::endl; + os << indent << "Current Line Iteration " << m_CurrentLineIteration << std::endl; + os << indent << "Stop " << m_Stop << std::endl; +} +} // end of namespace itk +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkQuasiNewtonOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkQuasiNewtonOptimizerv4.h index 13ef00b1a5bcc5311dd25dc2d4c2488931ef9fc4..90cb5bb33f124af15b7e2557b4f9b6fc44aef490 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkQuasiNewtonOptimizerv4.h +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkQuasiNewtonOptimizerv4.h @@ -130,7 +130,6 @@ protected: /** The information about the previous step */ MeasureType m_PreviousValue; ParametersType m_PreviousPosition; - DerivativeType m_PreviousGradient; /** The best value so far and relevant information */ MeasureType m_BestValue; diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkQuasiNewtonOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkQuasiNewtonOptimizerv4.hxx index ed6f477c03101e661471a27542989df48b49c0e1..419e81706f458a6611f88ffe43560dcf2e8a9ba8 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkQuasiNewtonOptimizerv4.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkQuasiNewtonOptimizerv4.hxx @@ -26,9 +26,13 @@ namespace itk template<typename TInternalComputationValueType> QuasiNewtonOptimizerv4Template<TInternalComputationValueType> -::QuasiNewtonOptimizerv4Template() +::QuasiNewtonOptimizerv4Template(): + m_MaximumIterationsWithoutProgress(30), + m_PreviousValue(0.0), + m_BestValue(0.0), + m_BestPosition(0), + m_BestIteration(0) { - this->m_MaximumIterationsWithoutProgress = 30; this->m_LearningRate = NumericTraits<TInternalComputationValueType>::One; // m_MaximumNewtonStepSizeInPhysicalUnits is used for automatic learning @@ -38,9 +42,10 @@ QuasiNewtonOptimizerv4Template<TInternalComputationValueType> this->m_MaximumNewtonStepSizeInPhysicalUnits = NumericTraits<TInternalComputationValueType>::Zero; /** Threader for Quasi-Newton method */ - typedef QuasiNewtonOptimizerv4EstimateNewtonStepThreaderTemplate<TInternalComputationValueType> OptimizerType; - typedef typename OptimizerType::Pointer OptimizerPointer; - + typedef QuasiNewtonOptimizerv4EstimateNewtonStepThreaderTemplate<TInternalComputationValueType> + OptimizerType; + typedef typename OptimizerType::Pointer + OptimizerPointer; OptimizerPointer estimateNewtonStepThreader = OptimizerType::New(); this->m_EstimateNewtonStepThreader = estimateNewtonStepThreader; @@ -111,20 +116,20 @@ QuasiNewtonOptimizerv4Template<TInternalComputationValueType> if (this->GetCurrentIteration() == 0) { // initialize some information - m_PreviousValue = this->GetCurrentMetricValue(); - m_PreviousPosition = this->GetCurrentPosition(); - m_PreviousGradient = this->GetGradient(); + this->m_PreviousValue = this->GetCurrentMetricValue(); + this->m_PreviousPosition = this->GetCurrentPosition(); + this->m_PreviousGradient = this->GetGradient(); - m_BestValue = this->m_CurrentMetricValue; - m_BestPosition = this->m_CurrentPosition; - m_BestIteration = this->GetCurrentIteration(); + this->m_BestValue = this->m_CurrentMetricValue; + this->m_BestPosition = this->m_CurrentPosition; + this->m_BestIteration = this->GetCurrentIteration(); } else if (m_BestValue > this->m_CurrentMetricValue) { // store the best value and related information - m_BestValue = this->m_CurrentMetricValue; - m_BestPosition = this->m_CurrentPosition; - m_BestIteration = this->GetCurrentIteration(); + this->m_BestValue = this->m_CurrentMetricValue; + this->m_BestPosition = this->m_CurrentPosition; + this->m_BestIteration = this->GetCurrentIteration(); } if ( this->GetCurrentIteration() - m_BestIteration @@ -170,9 +175,9 @@ QuasiNewtonOptimizerv4Template<TInternalComputationValueType> this->EstimateNewtonStep(); /** Save for the next iteration */ - m_PreviousValue = this->GetCurrentMetricValue(); - m_PreviousPosition = this->GetCurrentPosition(); - m_PreviousGradient = this->GetGradient(); + this->m_PreviousValue = this->GetCurrentMetricValue(); + this->m_PreviousPosition = this->GetCurrentPosition(); + this->m_PreviousGradient = this->GetGradient(); this->CombineGradientNewtonStep(); this->ModifyCombinedNewtonStep(); @@ -268,7 +273,7 @@ QuasiNewtonOptimizerv4Template<TInternalComputationValueType> } } - if (vcl_abs(this->m_LearningRate - NumericTraits<TInternalComputationValueType>::One) + if (std::abs(this->m_LearningRate - NumericTraits<TInternalComputationValueType>::One) > 0.01) { this->m_NewtonStep *= this->m_LearningRate; @@ -389,8 +394,8 @@ QuasiNewtonOptimizerv4Template<TInternalComputationValueType> TInternalComputationValueType dot_dg_dx = inner_product(dg, dx); TInternalComputationValueType dot_edg_dx = inner_product(edg, dx); - if (vcl_abs(dot_dg_dx) <= NumericTraits<TInternalComputationValueType>::epsilon() - || vcl_abs(dot_edg_dx) <= NumericTraits<TInternalComputationValueType>::epsilon()) + if (std::abs(dot_dg_dx) <= NumericTraits<TInternalComputationValueType>::epsilon() + || std::abs(dot_edg_dx) <= NumericTraits<TInternalComputationValueType>::epsilon()) { return false; } @@ -412,7 +417,7 @@ QuasiNewtonOptimizerv4Template<TInternalComputationValueType> TInternalComputationValueType threshold = NumericTraits<TInternalComputationValueType>::epsilon(); - if ( vcl_abs(vnl_determinant(newHessian)) <= threshold ) + if ( std::abs(vnl_determinant(newHessian)) <= threshold ) { return false; } diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesEstimator.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesEstimator.hxx index 667b43de9b655a7bfb65cec250e6d6825f0720ad..ee79065bab91f2647916f1022d5e9e55bdf21d48 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesEstimator.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesEstimator.hxx @@ -82,11 +82,11 @@ if (m_Metric.IsNull()) itkExceptionMacro("RegistrationParameterScalesEstimator: the metric is NULL"); } - if (this->m_Metric->GetMovingTransform() == NULL) + if (this->m_Metric->GetMovingTransform() == ITK_NULLPTR) { itkExceptionMacro("RegistrationParameterScalesEstimator: this->m_MovingTransform in the metric is NULL."); } - if (this->m_Metric->GetFixedTransform() == NULL) + if (this->m_Metric->GetFixedTransform() == ITK_NULLPTR) { itkExceptionMacro("RegistrationParameterScalesEstimator: this->m_FixedTransform in the metric is NULL."); } @@ -290,9 +290,9 @@ void RegistrationParameterScalesEstimator< TMetric > ::ComputeSquaredJacobianNorms( const VirtualPointType & point, ParametersType & squareNorms ) { - JacobianType jacobian; const SizeValueType numPara = this->GetNumberOfLocalParameters(); const SizeValueType dim = this->GetDimension(); + JacobianType jacobian(dim,numPara); if (this->GetTransformForward()) { @@ -475,10 +475,10 @@ RegistrationParameterScalesEstimator< TMetric > const TransformBaseTemplate<typename TMetric::MeasureType> *transform = this->GetTransform(); - if ( dynamic_cast< const MatrixOffsetTransformBaseType * >( transform ) != NULL - || dynamic_cast< const TranslationTransformType * >( transform ) != NULL - || dynamic_cast< const IdentityTransformType * >( transform ) != NULL - || dynamic_cast< const Rigid3DPerspectiveTransformType * >( transform ) != NULL + if ( dynamic_cast< const MatrixOffsetTransformBaseType * >( transform ) != ITK_NULLPTR + || dynamic_cast< const TranslationTransformType * >( transform ) != ITK_NULLPTR + || dynamic_cast< const IdentityTransformType * >( transform ) != ITK_NULLPTR + || dynamic_cast< const Rigid3DPerspectiveTransformType * >( transform ) != ITK_NULLPTR ) { return true; @@ -642,7 +642,7 @@ RegistrationParameterScalesEstimator< TMetric > } else { - FloatType ratio = 1 + vcl_log((FloatType)total/SizeOfSmallDomain); + FloatType ratio = 1 + std::log((FloatType)total/SizeOfSmallDomain); //ratio >= 1 since total/SizeOfSmallDomain > 1 this->m_NumberOfRandomSamples = static_cast<int>(SizeOfSmallDomain * ratio); diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromJacobian.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromJacobian.hxx index 76859dbb869276e489f8766541f0a1c35dc75d61..36ef8c0c7325bc613c1e4b2d0b4b1634bb488c69 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromJacobian.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromJacobian.hxx @@ -159,19 +159,31 @@ RegistrationParameterScalesFromJacobian< TMetric > itk::Array<FloatType> dTdt(dim); + JacobianType jacobianCache(dim,dim); + JacobianType jacobian(dim, + (this->GetTransformForward() ? + this->m_Metric->GetMovingTransform()->GetNumberOfParameters() + : this->m_Metric->GetFixedTransform()->GetNumberOfParameters())); + + // checking each sample point for (SizeValueType c=0; c<numSamples; c++) { const VirtualPointType &point = this->m_SamplePoints[c]; - JacobianType jacobian; if (this->GetTransformForward()) { - this->m_Metric->GetMovingTransform()->ComputeJacobianWithRespectToParameters(point, jacobian); + this->m_Metric->GetMovingTransform()-> + ComputeJacobianWithRespectToParametersCachedTemporaries(point, + jacobian, + jacobianCache); } else { - this->m_Metric->GetFixedTransform()->ComputeJacobianWithRespectToParameters(point, jacobian); + this->m_Metric->GetFixedTransform()-> + ComputeJacobianWithRespectToParametersCachedTemporaries(point, + jacobian, + jacobianCache); } if( !this->IsDisplacementFieldTransform() ) diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromShiftBase.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromShiftBase.hxx index 119e9cafc601bffa18aaec72bc137232dc0e994a..fbdc5b919f6103dd7771ebb5d967a9840ffdce79 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromShiftBase.hxx +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegistrationParameterScalesFromShiftBase.hxx @@ -142,9 +142,9 @@ RegistrationParameterScalesFromShiftBase< TMetric > FloatType maxStep = NumericTraits<FloatType>::Zero; for (typename ParametersType::SizeValueType p = 0; p < step.GetSize(); p++) { - if (maxStep < vcl_abs(step[p])) + if (maxStep < std::abs(step[p])) { - maxStep = vcl_abs(step[p]); + maxStep = std::abs(step[p]); } } if (maxStep <= NumericTraits<FloatType>::epsilon()) diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegularStepGradientDescentOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegularStepGradientDescentOptimizerv4.h new file mode 100644 index 0000000000000000000000000000000000000000..399e3d2c9a15ed72db3ccc7670d5a381e807ee39 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegularStepGradientDescentOptimizerv4.h @@ -0,0 +1,150 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkRegularStepGradientDescentOptimizerv4_h +#define __itkRegularStepGradientDescentOptimizerv4_h + +#include "itkGradientDescentOptimizerv4.h" +#include <itkCompensatedSummation.h> + +namespace itk +{ + /** \class RegularStepGradientDescentOptimizerv4 + * \brief Regular Step Gradient descent optimizer. + * + * This optimizer is a variant of gradient descent that attempts to prevent it + * from taking steps that are too large. At each iteration, this optimizer + * will take a step along the direction of the metric derivative. Each time the + * direction of the derivative abruptly changes, the optimizer assumes that a + * local extrema has been passed and reacts by reducing the step length by a + * relaxation factor that is set to 0.5 by default. + * The default value for the initial step length is 1, and this value can only + * be changed manually via SetLearningRate() since this optimizer does not use + * the ScaleEstimator to automatically estimate the learning rate. + * Also note that unlike the previous version of ReuglarStepGradientDescentOptimizer, + * ITKv4 does not have a "maximize/minimize" option to modify the effect of + * the metric derivative. The assigned metric is assumed to return a parameter + * derivative result that "improves" the optimization. + * + * \ingroup ITKOptimizersv4 + */ +template<typename TInternalComputationValueType> +class RegularStepGradientDescentOptimizerv4 +: public GradientDescentOptimizerv4Template<TInternalComputationValueType> +{ +public: + /** Standard class typedefs. */ + typedef RegularStepGradientDescentOptimizerv4 Self; + typedef GradientDescentOptimizerv4Template<TInternalComputationValueType> Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(RegularStepGradientDescentOptimizerv4, Superclass); + + /** New macro for creation of through a Smart Pointer */ + itkNewMacro(Self); + + + /** It should be possible to derive the internal computation type from the class object. */ + typedef TInternalComputationValueType InternalComputationValueType; + + /** Derivative type */ + typedef typename Superclass::DerivativeType DerivativeType; + + /** Metric type over which this class is templated */ + typedef typename Superclass::MeasureType MeasureType; + typedef typename Superclass::IndexRangeType IndexRangeType; + typedef typename Superclass::ScalesType ScalesType; + typedef typename Superclass::ParametersType ParametersType; + typedef typename Superclass::StopConditionType StopConditionType; + + /** Compensated summation type */ + typedef CompensatedSummation< InternalComputationValueType > CompensatedSummationType; + + /** Minimum step length (learning rate) value for convergence checking. + * The step length is decreased by relaxation factor if the step is too + * long, and the algorithm passes the local minimum. + * When the step length value reaches a small value, it would be treated + * as converged. + * + * The default m_MinimumStepLength is set to 1e-4 to pass all + * tests. + */ + itkSetMacro(MinimumStepLength, TInternalComputationValueType); + itkGetConstReferenceMacro(MinimumStepLength, TInternalComputationValueType); + + /** Set/Get relaxation factor value */ + itkSetMacro(RelaxationFactor, TInternalComputationValueType); + itkGetConstReferenceMacro(RelaxationFactor, TInternalComputationValueType); + + /** Set/Get gradient magnitude tolerance value */ + itkSetMacro(GradientMagnitudeTolerance, TInternalComputationValueType); + itkGetConstReferenceMacro(GradientMagnitudeTolerance, TInternalComputationValueType); + + /** Start and run the optimization */ + virtual void StartOptimization( bool doOnlyInitialization = false ) ITK_OVERRIDE; + + /** Estimate the learning rate based on the current gradient. */ + virtual void EstimateLearningRate(); + +protected: + + /** Advance one Step following the gradient direction. + * Includes transform update. */ + virtual void AdvanceOneStep(void) ITK_OVERRIDE; + + /** Modify the input gradient over a given index range. */ + virtual void ModifyGradientByScalesOverSubRange( const IndexRangeType& subrange ) ITK_OVERRIDE; + virtual void ModifyGradientByLearningRateOverSubRange( const IndexRangeType& subrange ) ITK_OVERRIDE; + + /** + * When the local minima is passed by taking a large step, + * the step size is adjusted by the relaxation factor, so we + * can take smaller steps toward the minimum point. + */ + TInternalComputationValueType m_RelaxationFactor; + + /** Default constructor */ + RegularStepGradientDescentOptimizerv4(); + + /** Destructor */ + virtual ~RegularStepGradientDescentOptimizerv4(); + + virtual void PrintSelf( std::ostream & os, Indent indent ) const; + + /** Minimum gradient step value for convergence checking */ + TInternalComputationValueType m_MinimumStepLength; + + /** Minimum gradient magnitude value for convergence checking */ + TInternalComputationValueType m_GradientMagnitudeTolerance; + + /** Current scale for learning rate */ + MeasureType m_CurrentLearningRateRelaxation; + +private: + RegularStepGradientDescentOptimizerv4( const Self & ); //purposely not implemented + void operator=( const Self& ); //purposely not implemented +}; + +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +#include "itkRegularStepGradientDescentOptimizerv4.hxx" +#endif + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegularStepGradientDescentOptimizerv4.hxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegularStepGradientDescentOptimizerv4.hxx new file mode 100644 index 0000000000000000000000000000000000000000..99c57affef7983c1e9eb8222881c9b9aaeaf2f59 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkRegularStepGradientDescentOptimizerv4.hxx @@ -0,0 +1,299 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkRegularStepGradientDescentOptimizerv4_hxx +#define __itkRegularStepGradientDescentOptimizerv4_hxx + +#include "itkRegularStepGradientDescentOptimizerv4.h" + +namespace itk +{ + +template<typename TInternalComputationValueType> +RegularStepGradientDescentOptimizerv4<TInternalComputationValueType> +::RegularStepGradientDescentOptimizerv4(): + m_RelaxationFactor( 0.5 ), + m_MinimumStepLength( 1e-4 ), // Initialize parameter for the convergence checker + m_GradientMagnitudeTolerance( 1e-4 ), + m_CurrentLearningRateRelaxation( 0 ) +{ + this->m_DoEstimateLearningRateAtEachIteration = false; + this->m_DoEstimateLearningRateOnce = false; +} + +template<typename TInternalComputationValueType> +RegularStepGradientDescentOptimizerv4<TInternalComputationValueType> +::~RegularStepGradientDescentOptimizerv4() +{} + +template<typename TInternalComputationValueType> +void +RegularStepGradientDescentOptimizerv4<TInternalComputationValueType> +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Current learning rate relaxation: " << m_CurrentLearningRateRelaxation << std::endl; + os << indent << "Relaxation factor: " << this->m_RelaxationFactor << std::endl; + os << indent << "Minimum step length: " << this->m_MinimumStepLength << std::endl; + os << indent << "Gradient magnitude tolerance: " << this->m_GradientMagnitudeTolerance << std::endl; +} + +template<typename TInternalComputationValueType> +void +RegularStepGradientDescentOptimizerv4<TInternalComputationValueType> +::StartOptimization( bool doOnlyInitialization ) +{ + this->m_UseConvergenceMonitoring = false; + + /* Must call the grandparent version for basic validation and setup */ + GradientDescentOptimizerBasev4Template<TInternalComputationValueType>::StartOptimization( doOnlyInitialization ); + + if( this->m_ReturnBestParametersAndValue ) + { + this->m_BestParameters = this->GetCurrentPosition( ); + this->m_CurrentBestValue = NumericTraits< MeasureType >::max(); + } + + const SizeValueType spaceDimension = this->m_Metric->GetNumberOfParameters(); + + this->m_Gradient = DerivativeType(spaceDimension); + this->m_PreviousGradient = DerivativeType(spaceDimension); + this->m_Gradient.Fill(0.0f); + this->m_PreviousGradient.Fill(0.0f); + + // Reset the iterations and learning rate scale when the optimizer is started again. + this->m_CurrentLearningRateRelaxation = 1.0; + this->m_CurrentIteration = 0; + + // validity check for the value of GradientMagnitudeTolerance + if ( m_GradientMagnitudeTolerance < 0.0 ) + { + itkExceptionMacro(<< "Gradient magnitude tolerance must be" + "greater or equal 0.0. Current value is " << m_GradientMagnitudeTolerance); + } + + if( ! doOnlyInitialization ) + { + this->ResumeOptimization(); + } +} + +template<typename TInternalComputationValueType> +void +RegularStepGradientDescentOptimizerv4<TInternalComputationValueType> +::AdvanceOneStep() +{ + itkDebugMacro("AdvanceOneStep"); + + // Make sure the scales have been set properly + if ( this->m_Scales.size() != this->m_Gradient.Size() ) + { + itkExceptionMacro(<< "The size of Scales is " + << this->m_Scales.size() + << ", but the NumberOfParameters for the CostFunction is " + << this->m_Gradient.Size() + << "."); + } + + if ( this->m_RelaxationFactor < 0.0 ) + { + itkExceptionMacro(<< "Relaxation factor must be positive. Current value is " << this->m_RelaxationFactor); + } + + if ( this->m_RelaxationFactor >= 1.0 ) + { + itkExceptionMacro(<< "Relaxation factor must less than 1.0. Current value is " << this->m_RelaxationFactor); + } + + /* Begin threaded gradient modification. + * Scale gradient and previous gradient by scales. + * The m_Gradient and m_PreviousGradient variables are modified in-place. */ + this->ModifyGradientByScales(); + + CompensatedSummationType compensatedSummation; + for( SizeValueType dim = 0; dim < this->m_Gradient.Size(); ++dim ) + { + const double weighted = this->m_Gradient[dim]; + compensatedSummation += weighted * weighted; + } + const double gradientMagnitude = vcl_sqrt( compensatedSummation.GetSum() ); + + if( gradientMagnitude < this->m_GradientMagnitudeTolerance ) + { + this->m_StopCondition = Superclass::GRADIENT_MAGNITUDE_TOLEARANCE; + this->m_StopConditionDescription << "Gradient magnitude tolerance met after " + << this->m_CurrentIteration + << " iterations. Gradient magnitude (" + << gradientMagnitude + << ") is less than gradient magnitude tolerance (" + << this->m_GradientMagnitudeTolerance + << ")."; + this->StopOptimization(); + return; + } + + compensatedSummation.ResetToZero(); + for ( SizeValueType i = 0; i < this->m_Gradient.Size(); i++ ) + { + const double weight1 = this->m_Gradient[i]; + const double weight2 = this->m_PreviousGradient[i]; + compensatedSummation += weight1 * weight2; + } + const double scalarProduct = compensatedSummation.GetSum(); + + // If there is a direction change + if ( scalarProduct < 0 ) + { + this->m_CurrentLearningRateRelaxation *= this->m_RelaxationFactor; + } + + const double stepLength = this->m_CurrentLearningRateRelaxation*this->m_LearningRate; + + if ( stepLength < this->m_MinimumStepLength ) + { + this->m_StopCondition = Superclass::STEP_TOO_SMALL; + this->m_StopConditionDescription << "Step too small after " + << this->m_CurrentIteration + << " iterations. Current step (" + << stepLength + << ") is less than minimum step (" + << this->m_MinimumStepLength + << ")."; + this->StopOptimization(); + return; + } + + this->EstimateLearningRate(); + this->ModifyGradientByLearningRate(); + const double factor = NumericTraits<typename ScalesType::ValueType>::OneValue() / gradientMagnitude; + + try + { + /* Pass graident to transform and let it do its own updating */ + this->m_Metric->UpdateTransformParameters( this->m_Gradient, factor ); + } + catch ( ExceptionObject & err ) + { + this->m_StopCondition = Superclass::UPDATE_PARAMETERS_ERROR; + this->m_StopConditionDescription << "UpdateTransformParameters error"; + this->StopOptimization(); + + // Pass exception to caller + throw err; + } + + this->InvokeEvent( IterationEvent() ); +} + +template<typename TInternalComputationValueType> +void +RegularStepGradientDescentOptimizerv4<TInternalComputationValueType> +::ModifyGradientByScalesOverSubRange( const IndexRangeType& subrange ) +{ + const ScalesType& scales = this->GetScales(); + const ScalesType& weights = this->GetWeights(); + + ScalesType factor( scales.Size() ); + + if( this->GetWeightsAreIdentity() ) + { + for( SizeValueType i=0; i < factor.Size(); i++ ) + { + factor[i] = NumericTraits<typename ScalesType::ValueType>::OneValue() / scales[i]; + } + } + else + { + for( SizeValueType i=0; i < factor.Size(); i++ ) + { + factor[i] = weights[i] / scales[i]; + } + } + + /* Loop over the range. It is inclusive. */ + for ( IndexValueType j = subrange[0]; j <= subrange[1]; j++ ) + { + // scales is checked during StartOptmization for values <= + // machine epsilon. + // Take the modulo of the index to handle gradients from transforms + // with local support. The gradient array stores the gradient of local + // parameters at each local index with linear packing. + IndexValueType index = j % scales.Size(); + this->m_Gradient[j] = this->m_Gradient[j] * factor[index]; + this->m_PreviousGradient[j] = this->m_PreviousGradient[j] * factor[index]; + } +} + +template<typename TInternalComputationValueType> +void +RegularStepGradientDescentOptimizerv4<TInternalComputationValueType> +::ModifyGradientByLearningRateOverSubRange( const IndexRangeType& subrange ) +{ + /* Loop over the range. It is inclusive. */ + for ( IndexValueType j = subrange[0]; j <= subrange[1]; j++ ) + { + this->m_Gradient[j] = this->m_Gradient[j] * this->m_CurrentLearningRateRelaxation*this->m_LearningRate; + } +} + +/** +* Estimate the learning rate. +*/ +template<typename TInternalComputationValueType> +void +RegularStepGradientDescentOptimizerv4<TInternalComputationValueType> +::EstimateLearningRate() +{ + if ( this->m_ScalesEstimator.IsNull() ) + { + return; + } + if ( this->m_DoEstimateLearningRateAtEachIteration || + (this->m_DoEstimateLearningRateOnce && this->m_CurrentIteration == 0) ) + { + TInternalComputationValueType stepScale + = this->m_ScalesEstimator->EstimateStepScale(this->m_Gradient); + + if (stepScale <= NumericTraits<TInternalComputationValueType>::epsilon()) + { + this->m_LearningRate = NumericTraits<TInternalComputationValueType>::One; + } + else + { + this->m_LearningRate = this->m_MaximumStepSizeInPhysicalUnits / stepScale; + } + CompensatedSummationType compensatedSummation; + for( SizeValueType dim = 0; dim < this->m_Gradient.Size(); ++dim ) + { + const double weighted = this->m_Gradient[dim]; + compensatedSummation += weighted * weighted; + } + const double gradientMagnitude = std::sqrt( compensatedSummation.GetSum() ); + + // + // Specialized to keep the step size regularized this additional + // scale is needed to make the learning rate independent on the + // gradient magnitude. + // + this->m_LearningRate *= gradientMagnitude; + + } +} + +}//namespace itk + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkSingleValuedNonLinearVnlOptimizerv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkSingleValuedNonLinearVnlOptimizerv4.h new file mode 100644 index 0000000000000000000000000000000000000000..e32fb6c5646d1bfdd2eee93fc279563ed05671c9 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkSingleValuedNonLinearVnlOptimizerv4.h @@ -0,0 +1,126 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkSingleValuedNonLinearVnlOptimizerv4_h +#define __itkSingleValuedNonLinearVnlOptimizerv4_h + +#include "itkObjectToObjectOptimizerBase.h" +#include "itkSingleValuedVnlCostFunctionAdaptorv4.h" +#include "itkCommand.h" + +namespace itk +{ +/** \class SingleValuedNonLinearVnlOptimizerv4 + * \brief This is a base for the ITKv4 Optimization methods using + * the vnl library. + * + * It is an Adaptor class for optimizers provided by the vnl library. + * + * \ingroup ITKOptimizersv4 + */ +class SingleValuedNonLinearVnlOptimizerv4 : + public ObjectToObjectOptimizerBaseTemplate<double> +{ +public: + /** Standard class typedefs. */ + typedef SingleValuedNonLinearVnlOptimizerv4 Self; + typedef ObjectToObjectOptimizerBase Superclass; + typedef SmartPointer< Self > Pointer; + typedef SmartPointer< const Self > ConstPointer; + + /** Run-time type information (and related methods). */ + itkTypeMacro(SingleValuedNonLinearVnlOptimizerv4, ObjectToObjectOptimizerBase) + + /** Command observer that will interact with the ITKVNL cost-function + * adaptor in order to generate iteration events. This will allow to overcome + * the limitation of VNL optimizers not offering callbacks for every + * iteration */ + typedef ReceptorMemberCommand< Self > CommandType; + + typedef Superclass::MetricType MetricType; + typedef Superclass::DerivativeType DerivativeType; + typedef Superclass::ParametersType ParametersType; + typedef Superclass::ScalesType ScalesType; + + /** Stop condition return string type */ + typedef Superclass::StopConditionReturnStringType StopConditionReturnStringType; + + /** Stop condition internal string type */ + typedef Superclass::StopConditionDescriptionType StopConditionDescriptionType; + + virtual void StartOptimization(bool doOnlyInitialization = false) ITK_OVERRIDE; + + /** Set the metric (cost function). This method has to be overloaded + * by derived classes because the CostFunctionAdaptor requires + * to know the number of parameters at construction time. This + * number of parameters is obtained at run-time from the itkObjectToObjectMetric. + * As a consequence each derived optimizer should construct its own + * CostFunctionAdaptor when overloading this method */ + virtual void SetMetric(MetricType *metric) = 0; + + /** Return Cached Values. These method have the advantage of not triggering a + * recomputation of the metric value, but it has the disadvantage of returning + * a value that may not be the one corresponding to the current parameters. For + * GUI update purposes, this method is a good option. + * \note The metric value is cached in the base class, retrieved via GetValue(). */ + itkGetConstReferenceMacro(CachedDerivative, DerivativeType); + itkGetConstReferenceMacro(CachedCurrentPosition, ParametersType); + + /** Get the reason for termination */ + virtual const StopConditionReturnStringType GetStopConditionDescription() const = 0; + +protected: + SingleValuedNonLinearVnlOptimizerv4(); + virtual ~SingleValuedNonLinearVnlOptimizerv4(); + + typedef SingleValuedVnlCostFunctionAdaptorv4 CostFunctionAdaptorType; + + void SetCostFunctionAdaptor(CostFunctionAdaptorType *adaptor); + + const CostFunctionAdaptorType * GetCostFunctionAdaptor(void) const; + + CostFunctionAdaptorType * GetCostFunctionAdaptor(void); + + /** The purpose of this method is to get around the lack of + * const-correctness in VNL cost-functions and optimizers */ + CostFunctionAdaptorType * GetNonConstCostFunctionAdaptor(void) const; + + /** Print out internal state */ + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; + +private: + /** The purpose of this method is to get around the lack of iteration reporting + * in VNL optimizers. By interfacing directly with the ITK cost function + * adaptor we are generating here Iteration Events. Note the iteration events + * here are produce PER EVALUATION of the metric, not per real iteration of the + * vnl optimizer. Optimizers that evaluate the metric multiple times at each + * iteration will generate a lot more of Iteration events here. */ + void IterationReport(const EventObject & event); + + SingleValuedNonLinearVnlOptimizerv4(const Self &); //purposely not implemented + void operator=(const Self &); //purposely not implemented + + CostFunctionAdaptorType *m_CostFunctionAdaptor; + + CommandType::Pointer m_Command; + + mutable ParametersType m_CachedCurrentPosition; + mutable DerivativeType m_CachedDerivative; +}; +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkSingleValuedVnlCostFunctionAdaptorv4.h b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkSingleValuedVnlCostFunctionAdaptorv4.h new file mode 100644 index 0000000000000000000000000000000000000000..3b9dfef726dfed46c71c8b300cac2c30f0c921d8 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/include/itkSingleValuedVnlCostFunctionAdaptorv4.h @@ -0,0 +1,129 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#ifndef __itkSingleValuedVnlCostFunctionAdaptorv4_h +#define __itkSingleValuedVnlCostFunctionAdaptorv4_h + +#include "itkOptimizerParameters.h" +#include "itkObjectToObjectMetricBase.h" +#include "vnl/vnl_cost_function.h" + +namespace itk +{ +/** \class SingleValuedVnlCostFunctionAdaptorv4 + * \brief This class is an Adaptor that allows to pass + * itk::ObjectToObjectMetricBase objects to vnl_optimizers expecting + * a vnl_cost_function. For use in the ITKv4 registration framework. + * + * This class returns a single value. + * + * \ingroup ITKOptimizersv4 + */ +class SingleValuedVnlCostFunctionAdaptorv4: + public vnl_cost_function +{ +public: + + /** InternalMeasureType typedef. */ + typedef double InternalMeasureType; + + /** InternalParametersType typedef. */ + typedef vnl_vector< InternalMeasureType > InternalParametersType; + + /** InternalGradientType typedef. */ + typedef vnl_vector< InternalMeasureType > InternalDerivativeType; + + /** Parameters of the SingleValuedCostFunction */ + typedef ObjectToObjectMetricBase::ParametersType ParametersType; + + /** Derivatives of the SingleValuedCostFunction */ + typedef ObjectToObjectMetricBase::DerivativeType DerivativeType; + + /** Type of the SingleValuedCostFunction value */ + typedef ObjectToObjectMetricBase::MeasureType MeasureType; + + /** Scales typedef */ + typedef OptimizerParameters< InternalMeasureType > ScalesType; + + /** Constructor with size */ + SingleValuedVnlCostFunctionAdaptorv4(unsigned int spaceDimension); + + /** Set the CostFunction deriving from SingleValuedCostFunction */ + void SetCostFunction(ObjectToObjectMetricBase *costFunction) + { + m_ObjectMetric = costFunction; + } + + /** Get the CostFunction deriving from SingleValuedCostFunction */ + const ObjectToObjectMetricBase * GetCostFunction(void) const + { + return m_ObjectMetric; + } + + /** Delegate computation of the value to the CostFunction. */ + virtual InternalMeasureType f(const InternalParametersType & inparameters) ITK_OVERRIDE; + + /** Delegate computation of the gradient to the costFunction. */ + virtual void gradf(const InternalParametersType & inparameters, InternalDerivativeType & gradient) ITK_OVERRIDE; + + /** Delegate computation of value and gradient to the costFunction. */ + virtual void compute(const InternalParametersType & x, InternalMeasureType *f, InternalDerivativeType *g) ITK_OVERRIDE; + + /** Convert external derviative measures into internal type */ + void ConvertExternalToInternalGradient( const DerivativeType & input, InternalDerivativeType & output) const; + + /** Set current parameters scaling. */ + void SetScales(const ScalesType & scales); + + /** This AddObserver method allows to simulate that this class derives from + * an itkObject for the purpose of reporting iteration events. The goal of + * this method is to allow ITK-vnl optimizer adaptors to get iteration events + * despite the fact that VNL does not provide callbacks. */ + unsigned long AddObserver(const EventObject & event, Command *) const; + + /** Return the value of the last evaluation to the value of the cost function. + * Note that this method DOES NOT triggers a computation of the function or + * the derivatives, it only returns previous values. Therefore the values here + * are only valid after you invoke the f() or gradf() methods. */ + itkGetConstReferenceMacro(CachedValue, MeasureType); + + itkGetConstReferenceMacro(CachedDerivative, DerivativeType); + + /** Return the parameters directly from the assigned metric. */ + const ParametersType & GetCachedCurrentParameters() const; + +protected: + + /** This method is intended to be called by the derived classes in order to + * notify of an iteration event to any Command/Observers */ + void ReportIteration(const EventObject & event) const; + +private: + + ObjectToObjectMetricBase::Pointer m_ObjectMetric; + bool m_ScalesInitialized; + ScalesType m_Scales; + Object::Pointer m_Reporter; + + mutable MeasureType m_CachedValue; + mutable DerivativeType m_CachedDerivative; + +}; // end of Class CostFunction + +} // end namespace itk + +#endif diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/src/CMakeLists.txt b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7329f7a02c013737b5e424659e89865a29e4478c --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/CMakeLists.txt @@ -0,0 +1,14 @@ +set(ITKOptimizersv4_SRC + itkSingleValuedNonLinearVnlOptimizerv4.cxx + itkSingleValuedVnlCostFunctionAdaptorv4.cxx + itkLBFGSOptimizerv4.cxx + itkLBFGSBOptimizerv4.cxx + itkAmoebaOptimizerv4.cxx + ) + +add_library(ITKOptimizersv4 ${ITKOptimizersv4_SRC}) +target_link_libraries(ITKOptimizersv4 + ${ITKMetricsv4_LIBRARIES} + ${ITKOptimizers_LIBRARIES} + ) +itk_module_target(ITKOptimizersv4) diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkAmoebaOptimizerv4.cxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkAmoebaOptimizerv4.cxx new file mode 100644 index 0000000000000000000000000000000000000000..48bf958867945c8757d46e2a34ec747dd8fd0d55 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkAmoebaOptimizerv4.cxx @@ -0,0 +1,298 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ + +#include "itkAmoebaOptimizerv4.h" + +namespace itk +{ + + +AmoebaOptimizerv4 +::AmoebaOptimizerv4() : + m_InitialSimplexDelta(1) +{ + this->m_NumberOfIterations = 500; + this->m_ParametersConvergenceTolerance = 1e-8; + this->m_FunctionConvergenceTolerance = 1e-4; + this->m_AutomaticInitialSimplex = true; + this->m_InitialSimplexDelta.Fill( NumericTraits< ParametersType::ValueType >::One ); + this->m_OptimizeWithRestarts = false; + this->m_VnlOptimizer = ITK_NULLPTR; +} + + +AmoebaOptimizerv4 +::~AmoebaOptimizerv4() +{ + delete m_VnlOptimizer; +} + + +const std::string +AmoebaOptimizerv4 +::GetStopConditionDescription() const +{ + return this->m_StopConditionDescription.str(); +} + + +void +AmoebaOptimizerv4 +::PrintSelf( std::ostream & os, Indent indent ) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "ParametersConvergenceTolerance: " + << this->m_ParametersConvergenceTolerance << std::endl; + os << indent << "FunctionConvergenceTolerance: " + << this->m_FunctionConvergenceTolerance << std::endl; + os << indent << "AutomaticInitialSimplex: " + << ( this->m_AutomaticInitialSimplex ? "On" : "Off" ) << std::endl; + os << indent << "InitialSimplexDelta: " + << this->m_InitialSimplexDelta << std::endl; +} + + +vnl_amoeba * +AmoebaOptimizerv4 +::GetOptimizer() const +{ + return this->m_VnlOptimizer; +} + +void +AmoebaOptimizerv4:: +SetInitialSimplexDelta( ParametersType initialSimplexDelta, + bool automaticInitialSimplex ) +{ + this->m_InitialSimplexDelta = initialSimplexDelta; + this->m_AutomaticInitialSimplex = automaticInitialSimplex; + this->Modified(); +} + + +void +AmoebaOptimizerv4 +::SetMetric(MetricType *metric) +{ + this->m_Metric = metric; + + //if cost function is NULL this will throw an exception when the pointer is dereferenced + const unsigned int numberOfParameters = metric->GetNumberOfParameters(); + + // assign to vnl cost-function adaptor + CostFunctionAdaptorType *adaptor = new CostFunctionAdaptorType( numberOfParameters ); + adaptor->SetCostFunction( metric ); + this->SetCostFunctionAdaptor( adaptor ); + this->Modified(); +} + + +void +AmoebaOptimizerv4 +::StartOptimization(bool /* doOnlyInitialization */) +{ + // Perform some verification, check scales, + // pass settings to cost-function adaptor. + Superclass::StartOptimization(); + + //validate the settings (cost function is initialized, the size of its + //expected parameter vector matches the one we have etc...) + this->ValidateSettings(); + + ParametersType parameters = this->m_Metric->GetParameters(); + unsigned int n = parameters.GetSize(); + if( n == 0 ) + { + itkExceptionMacro(<<"Optimizer parameters are not initialized."); + } + + InternalParametersType delta( m_InitialSimplexDelta ); + + //start the actual work + this->InvokeEvent( StartEvent() ); + + //configure the vnl optimizer + CostFunctionAdaptorType *adaptor = GetNonConstCostFunctionAdaptor(); + //get rid of previous instance of the internal optimizer and create a + //new one + delete m_VnlOptimizer; + m_VnlOptimizer = new vnl_amoeba( *adaptor ); + m_VnlOptimizer->set_max_iterations( static_cast< int >( m_NumberOfIterations ) ); + m_VnlOptimizer->set_x_tolerance(m_ParametersConvergenceTolerance); + m_VnlOptimizer->set_f_tolerance(m_FunctionConvergenceTolerance); + + m_StopConditionDescription.str( "" ); + m_StopConditionDescription << this->GetNameOfClass() << ": Running"; + + ParametersType bestPosition = parameters; + + // Scale the initial parameters up if scales are defined. + // This compensates for later scaling them down in the cost function adaptor + // and at the end of this function. + const ScalesType & scales = GetScales(); + if ( !this->GetScalesAreIdentity() ) + { + for ( unsigned int i = 0; i < n; i++ ) + { + parameters[i] *= scales[i]; + } + } + //copy the automated initialization from vnl so that we have + //the same control as when the user provides the initial simplex. + //this also exposes the fact that there is an interaction between + //the parameter scaling and the initial simplex when using + //automated initialization - previously hidden inside vnl + if ( this->m_AutomaticInitialSimplex ) + { + const double relativeDiameter = 0.05; + const double zeroTermDelta = 0.00025; + InternalParametersType automaticDelta(n); + for( unsigned int i = 0; i < n; i++ ) + { + if( fabs( parameters[i] ) > zeroTermDelta ) + { + automaticDelta[i] = relativeDiameter*parameters[i]; + } + else + { + automaticDelta[i] = zeroTermDelta; + } + } + delta = automaticDelta; + } + + this->m_VnlOptimizer->minimize( parameters, delta ); + bestPosition = parameters; + double bestValue = adaptor->f( bestPosition ); + //multiple restart heuristic + if( this->m_OptimizeWithRestarts ) + { + this->m_CurrentIteration = static_cast<unsigned int>( m_VnlOptimizer->get_num_evaluations() ); + bool converged = false; + unsigned int i=1; + while( !converged && ( this->m_CurrentIteration < m_NumberOfIterations ) ) + { + this->m_VnlOptimizer->set_max_iterations( + static_cast< int >( this->m_NumberOfIterations - this->m_CurrentIteration ) ); + parameters = bestPosition; + delta = delta*( 1.0/pow( 2.0, static_cast<double>(i) ) * + (rand() > RAND_MAX/2 ? 1 : -1) ); + m_VnlOptimizer->minimize( parameters, delta ); + this->m_CurrentIteration += static_cast<unsigned int> + (m_VnlOptimizer->get_num_evaluations()); + double currentValue = adaptor->f( parameters ); + // be consistent with the underlying vnl amoeba implementation + double maxAbs = 0.0; + for( unsigned j=0; j<n; j++ ) + { + if( maxAbs< fabs( bestPosition[j] - parameters[j] ) ) + { + maxAbs = fabs( bestPosition[j] - parameters[j] ); + } + } + converged = fabs( bestValue - currentValue ) < + this->m_FunctionConvergenceTolerance && + maxAbs < this->m_ParametersConvergenceTolerance; + //this comparison is valid because the + //adaptor is set to always return the function value + //corresponding to minimization + if( currentValue < bestValue ) + { + bestValue = currentValue; + bestPosition = parameters; + } + i++; + } + } + // get the results, we scale the parameters down if scales are defined + if ( !this->GetScalesAreIdentity() ) + { + for ( unsigned int i = 0; i < n; ++i ) + { + bestPosition[i] /= scales[i]; + } + } + + this->m_Metric->SetParameters( bestPosition ); + + this->m_StopConditionDescription.str( "" ); + this->m_StopConditionDescription << this->GetNameOfClass() << ": "; + if ( static_cast< unsigned int >( this->m_VnlOptimizer->get_num_evaluations() ) + < this->m_NumberOfIterations ) + { + this->m_StopConditionDescription << "Both parameters convergence tolerance (" + << this->m_ParametersConvergenceTolerance + << ") and function convergence tolerance (" + << this->m_FunctionConvergenceTolerance + << ") have been met in " + << this->m_VnlOptimizer->get_num_evaluations() + << " iterations."; + } + else + { + this->m_StopConditionDescription << "Maximum number of iterations exceeded." + << " Number of iterations is " + << this->m_NumberOfIterations; + } + this->InvokeEvent( EndEvent() ); +} + + +void +AmoebaOptimizerv4 +::ValidateSettings() +{ + //if we got here it is safe to get the number of parameters the cost + //function expects + ParametersType parameters = this->m_Metric->GetParameters(); + unsigned int n = parameters.GetSize(); + + //the user gave us data to use for the initial simplex, check that it + //matches the number of parameters (simplex dimension is n+1 - the initial + //position and n vertices defined by adding m_InitialSimplexDelta[i] to + //the initial position + if( !m_AutomaticInitialSimplex ) + { + if( m_InitialSimplexDelta.size() != n ) + { + itkExceptionMacro(<<"cost function and simplex delta dimensions mismatch") + } + } + + //check that the number of scale factors matches + if ( this->GetScalesInitialized() ) + { + if( this->GetScales().Size() != n ) + { + itkExceptionMacro(<<"cost function and scaling information dimensions mismatch") + } + } + + //parameters' convergence tolerance has to be positive + if ( this->m_ParametersConvergenceTolerance < 0 ) + { + itkExceptionMacro(<<"negative parameters convergence tolerance") + } + //function convergence tolerance has to be positive + if ( this->m_FunctionConvergenceTolerance < 0 ) + { + itkExceptionMacro(<<"negative function convergence tolerance") + } +} + +} // end namespace itk diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkLBFGSBOptimizerv4.cxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkLBFGSBOptimizerv4.cxx new file mode 100644 index 0000000000000000000000000000000000000000..9ab0061981f24e1108bc7da5a0ffabfb79ec2a7a --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkLBFGSBOptimizerv4.cxx @@ -0,0 +1,296 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#include "itkLBFGSBOptimizerv4.h" + +namespace itk +{ +/** \class LBFGSBOptimizerHelperv4 + * \brief Wrapper helper around vnl_lbfgsb. + * + * This class is used to translate iteration events, etc, from + * vnl_lbfgsb into iteration events in ITK. + */ +class LBFGSBOptimizerHelperv4: +public LBFGSOptimizerBaseHelperv4<vnl_lbfgsb> +{ + public: + typedef LBFGSBOptimizerHelperv4 Self; + typedef LBFGSOptimizerBaseHelperv4<vnl_lbfgsb> Superclass; + + /** Create with a reference to the ITK object */ + LBFGSBOptimizerHelperv4(vnl_cost_function & f, + LBFGSBOptimizerv4 * const itkObj); + + protected: + /** Handle new iteration event */ + virtual bool report_iter(); +}; + +/** Create with a reference to the ITK object */ +LBFGSBOptimizerHelperv4 +::LBFGSBOptimizerHelperv4(vnl_cost_function & f, LBFGSBOptimizerv4 * const itkObj): + Superclass::LBFGSOptimizerBaseHelperv4(f, itkObj) +{ +} + +/** Handle new iteration event */ +bool +LBFGSBOptimizerHelperv4 +::report_iter() +{ + Superclass::report_iter(); + + m_ItkObj->m_InfinityNormOfProjectedGradient = this->get_inf_norm_projected_gradient(); + m_ItkObj->InvokeEvent( IterationEvent() ); + m_ItkObj->m_CurrentIteration = this->num_iterations_; + + // Return true to terminate the optimization loop. + if ( this->num_iterations_ > m_ItkObj->m_MaximumNumberOfIterations ) + { + return true; + } + else + { + return false; + } +} +//------------------------------------------------------------------------- + +LBFGSBOptimizerv4 + ::LBFGSBOptimizerv4(): + m_MaximumNumberOfCorrections(5), + m_InitialPosition(0), + m_LowerBound(0), + m_UpperBound(0), + m_BoundSelection(0) +{ +} + +LBFGSBOptimizerv4 +::~LBFGSBOptimizerv4() +{ +} + +void +LBFGSBOptimizerv4 +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + + os << indent << "InitialPosition: " << m_InitialPosition << std::endl; + os << indent << "CurrentPosition: " << this->GetCurrentPosition() << std::endl; + + os << indent << "LowerBound: " << m_LowerBound << std::endl; + os << indent << "UpperBound: " << m_UpperBound << std::endl; + os << indent << "BoundSelection: " << m_BoundSelection << std::endl; + + os << indent << "CostFunctionConvergenceFactor: " + << m_CostFunctionConvergenceFactor << std::endl; + + os << indent << "MaximumNumberOfEvaluations: " + << m_MaximumNumberOfFunctionEvaluations << std::endl; + + os << indent << "MaximumNumberOfCorrections: " + << m_MaximumNumberOfCorrections << std::endl; + + os << indent << "Value: " + << this->GetValue() << std::endl; + + os << indent << "InfinityNormOfProjectedGradient: " + << this->m_InfinityNormOfProjectedGradient << std::endl; + + if ( this->m_VnlOptimizer ) + { + os << indent << "Vnl LBFGSB Failure Code: " + << this->m_VnlOptimizer->get_failure_code() << std::endl; + } +} + +void +LBFGSBOptimizerv4 +::SetScales(const ScalesType &) +{ + std::cout << "WARNING: LBFGSB optimizer does not support scaling. All scales are set to one." << std::endl; + m_Scales.SetSize( this->m_Metric->GetNumberOfLocalParameters() ); + m_Scales.Fill( NumericTraits<ScalesType::ValueType>::OneValue() ); + this->m_ScalesAreIdentity = true; +} + +void +LBFGSBOptimizerv4 +::SetInitialPosition(const ParametersType & param) +{ + m_InitialPosition = param; + this->Modified(); +} + +void +LBFGSBOptimizerv4 +::SetLowerBound( + const BoundValueType & value) +{ + this->m_LowerBound = value; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_lower_bound(m_LowerBound); + } + this->Modified(); +} + +void +LBFGSBOptimizerv4 +::SetUpperBound( + const BoundValueType & value) +{ + this->m_UpperBound = value; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_upper_bound(m_UpperBound); + } + this->Modified(); +} + +void +LBFGSBOptimizerv4 +::SetBoundSelection( + const BoundSelectionType & value) +{ + m_BoundSelection = value; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_bound_selection( m_BoundSelection ); + } + this->Modified(); +} + +void +LBFGSBOptimizerv4 +::SetCostFunctionConvergenceFactor(double value) +{ + if ( value < 0.0 ) + { + itkExceptionMacro("Value " << value + << " is too small for SetCostFunctionConvergenceFactor()" + << "a typical range would be from 0.0 to 1e+12"); + } + m_CostFunctionConvergenceFactor = value; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_cost_function_convergence_factor( m_CostFunctionConvergenceFactor ); + } + this->Modified(); +} + +void +LBFGSBOptimizerv4 +::SetMaximumNumberOfCorrections(unsigned int value) +{ + m_MaximumNumberOfCorrections = value; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_max_variable_metric_corrections( m_MaximumNumberOfCorrections ); + } + this->Modified(); +} + +void +LBFGSBOptimizerv4 +::SetMetric(MetricType *metric) +{ + Superclass::SetMetric( metric ); + + CostFunctionAdaptorType *adaptor = this->GetCostFunctionAdaptor(); + + m_VnlOptimizer.Reset(); + m_VnlOptimizer.TakeOwnership( new InternalOptimizerType( *adaptor, this ) ); + + // set the optimizer parameters + m_VnlOptimizer->set_trace( m_Trace ); + m_VnlOptimizer->set_lower_bound( m_LowerBound ); + m_VnlOptimizer->set_upper_bound( m_UpperBound ); + m_VnlOptimizer->set_bound_selection( m_BoundSelection ); + m_VnlOptimizer->set_cost_function_convergence_factor( m_CostFunctionConvergenceFactor ); + m_VnlOptimizer->set_projected_gradient_tolerance( m_GradientConvergenceTolerance ); + m_VnlOptimizer->set_max_function_evals( static_cast< int >( m_MaximumNumberOfFunctionEvaluations ) ); + m_VnlOptimizer->set_max_variable_metric_corrections( m_MaximumNumberOfCorrections ); + + m_OptimizerInitialized = true; + + this->Modified(); +} + +void +LBFGSBOptimizerv4 +::StartOptimization(bool /*doOnlyInitialization*/ ) +{ + // Perform some verification, check scales, + // pass settings to cost-function adaptor. + Superclass::StartOptimization(); + + // Check if all the bounds parameters are the same size as the initial + // parameters. + unsigned int numberOfParameters = m_Metric->GetNumberOfParameters(); + + if ( this->GetInitialPosition().Size() < numberOfParameters ) + { + std::cout << "Set the initial position of the optimizer:" << std::endl; + this->SetInitialPosition( m_Metric->GetParameters() ); + } + + if ( m_LowerBound.size() < numberOfParameters && !m_BoundSelection.is_zero() ) + { + itkExceptionMacro(<< "LowerBound array does not have sufficient number of elements"); + } + + if ( m_UpperBound.size() < numberOfParameters && !m_BoundSelection.is_zero() ) + { + itkExceptionMacro(<< "UppperBound array does not have sufficient number of elements"); + } + + if ( m_BoundSelection.size() < numberOfParameters ) + { + itkExceptionMacro(<< "BoundSelection array does not have sufficient number of elements"); + } + + if(this->m_CostFunctionConvergenceFactor == 0.0 && this->m_GradientConvergenceTolerance == 0.0) + { + itkExceptionMacro("LBFGSB Optimizer cannot function if both CostFunctionConvergenceFactor" + " and ProjectedGradienctTolerance are zero."); + } + + ParametersType parameters( this->GetInitialPosition() ); + + this->InvokeEvent( StartEvent() ); + + // vnl optimizers return the solution by reference + // in the variable provided as initial position + m_VnlOptimizer->minimize(parameters); + + if ( parameters.GetSize() != this->GetInitialPosition().Size() ) + { + // set current position to initial position and throw an exception + this->m_Metric->SetParameters( this->GetInitialPosition() ); + itkExceptionMacro(<< "Error occurred in optimization"); + } + + this->m_Metric->SetParameters( parameters ); + + this->InvokeEvent( EndEvent() ); +} + +} // end namespace itk diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkLBFGSOptimizerv4.cxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkLBFGSOptimizerv4.cxx new file mode 100644 index 0000000000000000000000000000000000000000..90b1acc3d1ec745cda97dfaaa7238c9d5030a921 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkLBFGSOptimizerv4.cxx @@ -0,0 +1,207 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#include "itkLBFGSOptimizerv4.h" + +namespace itk +{ +LBFGSOptimizerv4 + ::LBFGSOptimizerv4(): + m_Verbose(false), + m_LineSearchAccuracy(0.9), + m_DefaultStepLength(1.0) +{ +} + +LBFGSOptimizerv4 +::~LBFGSOptimizerv4() +{ +} + +void +LBFGSOptimizerv4 +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "LineSearchAccuracy: " + << m_LineSearchAccuracy << std::endl; + os << indent << "DefaultStepLength: " + << m_DefaultStepLength << std::endl; + + if ( this->m_VnlOptimizer ) + { + os << indent << "Vnl LBFGS Failure Code: " + << this->m_VnlOptimizer->get_failure_code() << std::endl; + } +} + +void +LBFGSOptimizerv4 +::VerboseOn() +{ + if ( m_Verbose == true ) + { + return; + } + + m_Verbose = true; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_verbose(true); + } + + this->Modified(); +} + +void +LBFGSOptimizerv4 +::VerboseOff() +{ + if ( m_Verbose == false ) + { + return; + } + + m_Verbose = false; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->set_verbose(false); + } + + this->Modified(); +} + +void +LBFGSOptimizerv4 +::SetLineSearchAccuracy(double f) +{ + if ( f == m_LineSearchAccuracy ) + { + return; + } + + m_LineSearchAccuracy = f; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->line_search_accuracy = m_LineSearchAccuracy; + } + + this->Modified(); +} + +void +LBFGSOptimizerv4 +::SetDefaultStepLength(double f) +{ + if ( f == m_DefaultStepLength ) + { + return; + } + + m_DefaultStepLength = f; + if ( m_OptimizerInitialized ) + { + m_VnlOptimizer->default_step_length = m_DefaultStepLength; + } + + this->Modified(); +} + +void +LBFGSOptimizerv4 +::SetMetric(MetricType *metric) +{ + Superclass::SetMetric( metric ); + + // set the optimizer parameters + m_VnlOptimizer->set_trace( m_Trace ); + m_VnlOptimizer->set_verbose( m_Verbose ); + m_VnlOptimizer->set_max_function_evals( static_cast< int >( m_MaximumNumberOfFunctionEvaluations ) ); + m_VnlOptimizer->set_g_tolerance( m_GradientConvergenceTolerance ); + m_VnlOptimizer->line_search_accuracy = m_LineSearchAccuracy; + m_VnlOptimizer->default_step_length = m_DefaultStepLength; + // set for debugging + //m_VnlOptimizer->set_check_derivatives( true ); + + m_OptimizerInitialized = true; + + this->Modified(); +} + +void +LBFGSOptimizerv4 +::StartOptimization(bool /* doOnlyInitialization */) +{ + // Perform some verification, check scales, + // pass settings to cost-function adaptor. + Superclass::StartOptimization(); + + // Note that it's tempting to use a reference to the parameters stored + // in the metric for efficiency. + ParametersType parameters = this->m_Metric->GetParameters(); + + if( parameters.GetSize() == 0 ) + { + itkExceptionMacro(<<"Optimizer parameters are not initialized."); + } + + // Scale the initial parameters up if scales are defined. + // This compensates for later scaling them down in "compute" function of + // the cost function adaptor and at the end of this function. + InternalParametersType vnlCompatibleParameters(parameters.GetSize()); + const ScalesType & scales = this->GetScales(); + for ( SizeValueType i = 0; i < parameters.GetSize(); ++i ) + { + if( this->GetScalesAreIdentity() ) + { + vnlCompatibleParameters[i] = parameters[i]; + } + else + { + vnlCompatibleParameters[i] = parameters[i] * scales[i]; + } + } + + // vnl optimizers return the solution by reference + // in the variable provided as initial position. + // Also note that v4 registration always minimizes because v4 metrics return the negate value + // if the cost function should be maximized. + m_VnlOptimizer->minimize( vnlCompatibleParameters ); + + // Check if the output parameters are not null. + if ( vnlCompatibleParameters.size() != parameters.GetSize() ) + { + itkExceptionMacro(<< "Error occurred in optimization. Optimized parameters and initial parameters are not the same size: " + << vnlCompatibleParameters.size() << " vs. " << parameters.GetSize() ); + } + + // we scale the parameters down if scales are defined + for ( SizeValueType i = 0; i < vnlCompatibleParameters.size(); ++i ) + { + if( this->GetScalesAreIdentity() ) + { + parameters[i] = vnlCompatibleParameters[i]; + } + else + { + parameters[i] = vnlCompatibleParameters[i] / scales[i]; + } + } + + this->m_Metric->SetParameters( parameters ); +} +} // end namespace itk diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkSingleValuedNonLinearVnlOptimizerv4.cxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkSingleValuedNonLinearVnlOptimizerv4.cxx new file mode 100644 index 0000000000000000000000000000000000000000..2fca3dfcc546c2c55285ab339ffc668a68b14451 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkSingleValuedNonLinearVnlOptimizerv4.cxx @@ -0,0 +1,130 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#include "itkSingleValuedNonLinearVnlOptimizerv4.h" + +namespace itk +{ +SingleValuedNonLinearVnlOptimizerv4 +::SingleValuedNonLinearVnlOptimizerv4() +{ + this->m_CostFunctionAdaptor = ITK_NULLPTR; + this->m_Command = CommandType::New(); + this->m_Command->SetCallbackFunction(this, &SingleValuedNonLinearVnlOptimizerv4::IterationReport); + + this->m_CachedCurrentPosition.Fill( NumericTraits<DerivativeType::ValueType>::Zero ); + this->m_CachedDerivative.Fill( NumericTraits<DerivativeType::ValueType>::Zero ); +} + +SingleValuedNonLinearVnlOptimizerv4 +::~SingleValuedNonLinearVnlOptimizerv4() +{ + if ( this->m_CostFunctionAdaptor ) + { + delete this->m_CostFunctionAdaptor; + this->m_CostFunctionAdaptor = ITK_NULLPTR; + } +} + +void +SingleValuedNonLinearVnlOptimizerv4 +::StartOptimization(bool /* doOnlyInitialization */ ) +{ + // Perform some verification, check scales. + Superclass::StartOptimization(); + + // Verify adaptor + if( this->m_CostFunctionAdaptor == ITK_NULLPTR ) + { + itkExceptionMacro("CostFunctionAdaptor has not been set."); + } + + // If the user provides the scales and they're not identity, then we set. + // Otherwise we don't set them for computation speed. + // These are managed at the optimizer level, but + // applied at the cost-function adaptor level because that's + // where the per-iteration results of the vnl optimizer are accessible. + if ( ! this->GetScalesAreIdentity() ) + { + ScalesType scales = this->GetScales(); + this->GetNonConstCostFunctionAdaptor()->SetScales(scales); + } +} + +void +SingleValuedNonLinearVnlOptimizerv4 +::SetCostFunctionAdaptor(CostFunctionAdaptorType *adaptor) +{ + if ( this->m_CostFunctionAdaptor == adaptor ) + { + return; + } + + if ( this->m_CostFunctionAdaptor ) + { + delete this->m_CostFunctionAdaptor; + } + + this->m_CostFunctionAdaptor = adaptor; + + this->m_CostFunctionAdaptor->AddObserver(IterationEvent(), this->m_Command); +} + +const SingleValuedNonLinearVnlOptimizerv4::CostFunctionAdaptorType * +SingleValuedNonLinearVnlOptimizerv4 +::GetCostFunctionAdaptor(void) const +{ + return this->m_CostFunctionAdaptor; +} + +SingleValuedNonLinearVnlOptimizerv4::CostFunctionAdaptorType * +SingleValuedNonLinearVnlOptimizerv4 +::GetCostFunctionAdaptor(void) +{ + return this->m_CostFunctionAdaptor; +} + +SingleValuedNonLinearVnlOptimizerv4::CostFunctionAdaptorType * +SingleValuedNonLinearVnlOptimizerv4 +::GetNonConstCostFunctionAdaptor(void) const +{ + return this->m_CostFunctionAdaptor; +} + +void +SingleValuedNonLinearVnlOptimizerv4 +::IterationReport(const EventObject & event) +{ + const CostFunctionAdaptorType *adaptor = this->GetCostFunctionAdaptor(); + + this->m_CurrentMetricValue = adaptor->GetCachedValue(); + this->m_CachedDerivative = adaptor->GetCachedDerivative(); + this->m_CachedCurrentPosition = adaptor->GetCachedCurrentParameters(); + this->InvokeEvent(event); +} + +void +SingleValuedNonLinearVnlOptimizerv4 +::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Cached Derivative: " << this->m_CachedDerivative << std::endl; + os << indent << "Cached current positiion: " << this->m_CachedCurrentPosition << std::endl; + os << "Command observer " << this->m_Command.GetPointer() << std::endl; + os << "Cost Function adaptor" << this->m_CostFunctionAdaptor << std::endl; +} +} // end namespace itk diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkSingleValuedVnlCostFunctionAdaptorv4.cxx b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkSingleValuedVnlCostFunctionAdaptorv4.cxx new file mode 100644 index 0000000000000000000000000000000000000000..6ffa93987c5d207315c895a1bd3d45e01aad57b0 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/src/itkSingleValuedVnlCostFunctionAdaptorv4.cxx @@ -0,0 +1,194 @@ +/*========================================================================= + * + * Copyright Insight Software Consortium + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + *=========================================================================*/ +#include "itkSingleValuedVnlCostFunctionAdaptorv4.h" + +namespace itk +{ +SingleValuedVnlCostFunctionAdaptorv4 +::SingleValuedVnlCostFunctionAdaptorv4(unsigned int spaceDimension): + vnl_cost_function(spaceDimension) +{ + m_ScalesInitialized = false; + m_Reporter = Object::New(); + m_CachedValue = NumericTraits< MeasureType >::Zero; + m_CachedDerivative.Fill(0); +} + +void +SingleValuedVnlCostFunctionAdaptorv4 +::SetScales(const ScalesType & scales) +{ + m_Scales = scales; + m_ScalesInitialized = true; +} + +SingleValuedVnlCostFunctionAdaptorv4::InternalMeasureType +SingleValuedVnlCostFunctionAdaptorv4 +::f(const InternalParametersType & inparameters) +{ + if ( !m_ObjectMetric ) + { + itkGenericExceptionMacro( + << "Attempt to use a SingleValuedVnlCostFunctionAdaptorv4 without any Metric plugge d in"); + } + + // Use scales if they are provided + ParametersType parameters( inparameters.size() ); + if ( m_ScalesInitialized ) + { + for ( SizeValueType i = 0; i < parameters.GetSize(); ++i ) + { + parameters[i] = inparameters[i] / m_Scales[i]; + } + } + else + { + parameters.SetData( const_cast< double * >( inparameters.data_block() ) ); + } + + this->m_ObjectMetric->SetParameters( parameters ); + InternalMeasureType value = static_cast< InternalMeasureType >( m_ObjectMetric->GetValue() ); + + // Notify observers. This is used for overcoming the limitaion of VNL + // optimizers of not providing callbacks per iteration. + m_CachedValue = value; + this->ReportIteration( FunctionEvaluationIterationEvent() ); + + return value; +} + +void +SingleValuedVnlCostFunctionAdaptorv4 +::gradf(const InternalParametersType & inparameters, InternalDerivativeType & gradient) +{ + if ( !m_ObjectMetric ) + { + itkGenericExceptionMacro("Attempt to use a SingleValuedVnlCostFunctionAdaptorv4 without any Metric plugged in"); + } + + // Use scales if they are provided + ParametersType parameters( inparameters.size() ); + if ( m_ScalesInitialized ) + { + for ( SizeValueType i = 0; i < parameters.GetSize(); ++i ) + { + parameters[i] = inparameters[i] / m_Scales[i]; + } + } + else + { + parameters.SetData( const_cast< double * >( inparameters.data_block() ) ); + } + + // Delegate computation of the gradient to the ObjectMetric + this->m_ObjectMetric->SetParameters( parameters ); + this->m_ObjectMetric->GetDerivative( m_CachedDerivative ); + // This will also scale gradient by user scales + this->ConvertExternalToInternalGradient( m_CachedDerivative, gradient ); + + // Notify observers. This is used for overcoming the limitaion of VNL + // optimizers of not providing callbacks per iteration. + // Note that m_CachedDerivative is already loaded in the GetDerivative() + // above. + this->ReportIteration( GradientEvaluationIterationEvent() ); +} + +void +SingleValuedVnlCostFunctionAdaptorv4 +::compute(const InternalParametersType & x, InternalMeasureType *fun, InternalDerivativeType *g) +{ + // delegate the computation to the ObjectMetric + ParametersType parameters( x.size() ); + double measure; + + if ( m_ScalesInitialized ) + { + for ( SizeValueType i = 0; i < parameters.GetSize(); ++i ) + { + parameters[i] = x[i] / m_Scales[i]; + } + } + else + { + parameters.SetData( const_cast< double * >( x.data_block() ) ); + } + + this->m_ObjectMetric->SetParameters( parameters ); + this->m_ObjectMetric->GetValueAndDerivative( measure, m_CachedDerivative ); + if ( g ) // sometimes Vnl doesn't pass a valid pointer + { + this->ConvertExternalToInternalGradient(m_CachedDerivative, *g); + } + if ( fun ) // paranoids have longer lives... + { + *fun = static_cast< InternalMeasureType >( measure ); + // Notify observers. This is used for overcoming the limitaion of VNL + // optimizers of not providing callbacks per iteration. + // Note that m_CachedDerivative is already loaded in the GetDerivative() + // above. + m_CachedValue = *fun; + } + this->ReportIteration( FunctionAndGradientEvaluationIterationEvent() ); +} + +void +SingleValuedVnlCostFunctionAdaptorv4 +::ConvertExternalToInternalGradient(const DerivativeType & input, InternalDerivativeType & output) const +{ + // Convert external derviative measures into internal type + const unsigned int size = input.GetSize(); + + output = InternalDerivativeType(size); + for ( SizeValueType i = 0; i < size; ++i ) + { + output[i] = -input[i]; // because v4 metrics return the negate of gradient + + if ( m_ScalesInitialized ) + { + output[i] /= m_Scales[i]; + } + } +} + +void +SingleValuedVnlCostFunctionAdaptorv4 +::ReportIteration(const EventObject & event) const +{ + // This method reports iterations events. It is intended to + // help monitoring the progress of the optimization process. + this->m_Reporter->InvokeEvent(event); +} + +unsigned long +SingleValuedVnlCostFunctionAdaptorv4 +::AddObserver(const EventObject & event, Command *command) const +{ + // Connects a Command/Observer to the internal reporter class. + // This is useful for reporting iteration event to potential observers. + return m_Reporter->AddObserver(event, command); +} + +const SingleValuedVnlCostFunctionAdaptorv4::ParametersType & +SingleValuedVnlCostFunctionAdaptorv4 +::GetCachedCurrentParameters() const +{ + // Return the cached value of the parameters used for computing the function. + return this->m_ObjectMetric->GetParameters(); +} + +} // end namespace itk diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkGradientDescentOptimizerBasev4.wrap b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkGradientDescentOptimizerBasev4.wrap new file mode 100644 index 0000000000000000000000000000000000000000..74f5a6c9f3ed60595846955c482d2e985931d2e0 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkGradientDescentOptimizerBasev4.wrap @@ -0,0 +1,7 @@ +set(WRAPPER_AUTO_INCLUDE_HEADERS OFF) +itk_wrap_include("itkGradientDescentOptimizerBasev4.h") +itk_wrap_class("itk::GradientDescentOptimizerBasev4Template" POINTER) + foreach(t ${WRAP_ITK_REAL}) + itk_wrap_template("${ITKM_${t}}" "${ITKT_${t}}") + endforeach(t) +itk_end_wrap_class() diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkGradientDescentOptimizerv4.wrap b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkGradientDescentOptimizerv4.wrap index d53a176bfc6c8d0aaff4e999a59d40bacd74fdbd..3236448506e472deb908968d8fbd47776d1fcf2e 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkGradientDescentOptimizerv4.wrap +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkGradientDescentOptimizerv4.wrap @@ -1,3 +1,7 @@ -itk_wrap_simple_class("itk::ObjectToObjectOptimizerBase" POINTER) -itk_wrap_simple_class("itk::GradientDescentOptimizerBasev4" POINTER) -itk_wrap_simple_class("itk::GradientDescentOptimizerv4" POINTER) +set(WRAPPER_AUTO_INCLUDE_HEADERS OFF) +itk_wrap_include("itkGradientDescentOptimizerv4.h") +itk_wrap_class("itk::GradientDescentOptimizerv4Template" POINTER) + foreach(t ${WRAP_ITK_REAL}) + itk_wrap_template("${ITKM_${t}}" "${ITKT_${t}}") + endforeach(t) +itk_end_wrap_class() diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkObjectToObjectOptimizerBase.wrap b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkObjectToObjectOptimizerBase.wrap new file mode 100644 index 0000000000000000000000000000000000000000..61b2c448aeed5ff819afba5a116a292e29f4a340 --- /dev/null +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkObjectToObjectOptimizerBase.wrap @@ -0,0 +1,7 @@ +set(WRAPPER_AUTO_INCLUDE_HEADERS OFF) +itk_wrap_include("itkObjectToObjectOptimizerBase.h") +itk_wrap_class("itk::ObjectToObjectOptimizerBaseTemplate" POINTER) + foreach(t ${WRAP_ITK_REAL}) + itk_wrap_template("${ITKM_${t}}" "${ITKT_${t}}") + endforeach(t) +itk_end_wrap_class() diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkOptimizerParameterScalesEstimator.wrap b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkOptimizerParameterScalesEstimator.wrap index efd6a8c6ce933cc4929d71978146358ae6bb9184..a647ee41f928f622983669db770a6e560b5bdc08 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkOptimizerParameterScalesEstimator.wrap +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkOptimizerParameterScalesEstimator.wrap @@ -1 +1,7 @@ -itk_wrap_simple_class("itk::OptimizerParameterScalesEstimator" POINTER) +set(WRAPPER_AUTO_INCLUDE_HEADERS OFF) +itk_wrap_include("itkOptimizerParameterScalesEstimator.h") +itk_wrap_class("itk::OptimizerParameterScalesEstimatorTemplate" POINTER) + foreach(t ${WRAP_ITK_REAL}) + itk_wrap_template("${ITKM_${t}}" "${ITKT_${t}}") + endforeach(t) +itk_end_wrap_class() diff --git a/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkQuasiNewtonOptimizerv4.wrap b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkQuasiNewtonOptimizerv4.wrap index 4a43dd4fe409fb7b1990eab04bcc644f512d81fe..7eed11c5fcc75e32c1ded8389182fe70cf16c31d 100644 --- a/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkQuasiNewtonOptimizerv4.wrap +++ b/Utilities/ITK/Modules/Numerics/Optimizersv4/wrapping/itkQuasiNewtonOptimizerv4.wrap @@ -1 +1,7 @@ -itk_wrap_simple_class("itk::QuasiNewtonOptimizerv4" POINTER) +set(WRAPPER_AUTO_INCLUDE_HEADERS OFF) +itk_wrap_include("itkQuasiNewtonOptimizerv4.h") +itk_wrap_class("itk::QuasiNewtonOptimizerv4Template" POINTER) + foreach(t ${WRAP_ITK_REAL}) + itk_wrap_template("${ITKM_${t}}" "${ITKT_${t}}") + endforeach(t) +itk_end_wrap_class() diff --git a/Utilities/ITK/Modules/Numerics/Polynomials/include/itkMultivariateLegendrePolynomial.h b/Utilities/ITK/Modules/Numerics/Polynomials/include/itkMultivariateLegendrePolynomial.h index 9b654f958e6ab0c2a4c288556690ad71097bed5c..bdda18679613db4e212b18c9a03d61648edc1012 100644 --- a/Utilities/ITK/Modules/Numerics/Polynomials/include/itkMultivariateLegendrePolynomial.h +++ b/Utilities/ITK/Modules/Numerics/Polynomials/include/itkMultivariateLegendrePolynomial.h @@ -213,11 +213,12 @@ public: class SimpleForwardIterator { public: - SimpleForwardIterator (MultivariateLegendrePolynomial *polynomial) + SimpleForwardIterator (MultivariateLegendrePolynomial *polynomial) : + m_MultivariateLegendrePolynomial(polynomial), + m_Dimension (m_MultivariateLegendrePolynomial->GetDimension()), + m_DomainSize (m_MultivariateLegendrePolynomial->GetDomainSize()), + m_IsAtEnd(false) { - m_MultivariateLegendrePolynomial = polynomial; - m_Dimension = m_MultivariateLegendrePolynomial->GetDimension(); - m_DomainSize = m_MultivariateLegendrePolynomial->GetDomainSize(); m_Index.resize(m_Dimension); std::fill(m_Index.begin(), m_Index.end(), 0); } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkChiSquareDistribution.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkChiSquareDistribution.h index d587bc09abcbeeba220848e537bcd94228e2ca19..a3e9ffd6d899de7aa53b856ae1c144a42df806ff 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkChiSquareDistribution.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkChiSquareDistribution.h @@ -72,16 +72,16 @@ public: /** Return the number of parameters. For a Chi-Square * distribution, the number of parameters is 1 (degrees of freedom) */ - virtual SizeValueType GetNumberOfParameters() const { return 1; } + virtual SizeValueType GetNumberOfParameters() const ITK_OVERRIDE { return 1; } /** Evaluate the probability density function (pdf). The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluatePDF(double x) const; + virtual double EvaluatePDF(double x) const ITK_OVERRIDE; /** Evaluate the probability density function (pdf). The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (degrees of freedom). */ - virtual double EvaluatePDF(double x, const ParametersType &) const; + virtual double EvaluatePDF(double x, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the probability density function (pdf). The parameters * of the distribution are passed as separate parameters. */ @@ -89,12 +89,12 @@ public: /** Evaluate the cumulative distribution function (cdf). The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluateCDF(double x) const; + virtual double EvaluateCDF(double x) const ITK_OVERRIDE; /** Evaluate the cumulative distribution function (cdf). The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (degreesOfFreedom). */ - virtual double EvaluateCDF(double x, const ParametersType &) const; + virtual double EvaluateCDF(double x, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the cumulative distribution function (cdf). The parameters * of the distribution are passed as separate parameters. */ @@ -103,13 +103,13 @@ public: /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluateInverseCDF(double p) const; + virtual double EvaluateInverseCDF(double p) const ITK_OVERRIDE; /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (degrees of freedom). */ - virtual double EvaluateInverseCDF(double p, const ParametersType &) const; + virtual double EvaluateInverseCDF(double p, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters @@ -125,16 +125,16 @@ public: virtual SizeValueType GetDegreesOfFreedom() const; /** Does the Chi-Square distribution have a mean? */ - virtual bool HasMean() const { return true; } + virtual bool HasMean() const ITK_OVERRIDE { return true; } /** Get the mean of the distribution. */ - virtual double GetMean() const; + virtual double GetMean() const ITK_OVERRIDE; /** Does the Chi-Square distribution have a variance? */ - virtual bool HasVariance() const { return true; } + virtual bool HasVariance() const ITK_OVERRIDE { return true; } /** Get the variance of the distribution. */ - virtual double GetVariance() const; + virtual double GetVariance() const ITK_OVERRIDE; /** Static method to evaluate the probability density function (pdf) * of a Chi-Square with a specified number of degrees of freedom. The @@ -198,7 +198,7 @@ protected: ChiSquareDistribution(void); virtual ~ChiSquareDistribution(void) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: ChiSquareDistribution(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.h index 127618c1f66027c4f88b1b76a4265b6e13e27438..d9aac11a183dafbad8205922a373100ddb36410c 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.h @@ -64,63 +64,67 @@ public: itkTypeMacro(CovarianceSampleFilter, ProcessObject); itkNewMacro(Self); - /** Length of a measurement vector */ - typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; + /** Type of each measurement vector in sample */ + typedef typename SampleType::MeasurementVectorType MeasurementVectorType; - /** Measurement vector type */ - typedef typename TSample::MeasurementVectorType MeasurementVectorType; + /** Type of the length of each measurement vector */ + typedef typename SampleType::MeasurementVectorSizeType MeasurementVectorSizeType; - /** Type of vector elements */ - typedef typename TSample::MeasurementType MeasurementType; - typedef typename NumericTraits< MeasurementType >::RealType MeasurementRealType; + /** Type of measurement vector component value */ + typedef typename SampleType::MeasurementType MeasurementType; - /** Type of the measurement vector type */ + /** Type of a measurement vector, holding floating point values */ typedef typename NumericTraits< MeasurementVectorType >::RealType MeasurementVectorRealType; - /** Typedef for Covariance output */ - typedef VariableSizeMatrix< double > MatrixType; + /** Type of a floating point measurement component value */ + typedef typename NumericTraits< MeasurementType >::RealType MeasurementRealType; + - /** Method to set/get the sample */ + /** Method to set the sample */ using Superclass::SetInput; void SetInput(const SampleType *sample); + /** Method to get the sample */ const SampleType * GetInput() const; - /** VariableSizeMatrix is not a DataObject, we need to decorate it to push it down - * a ProcessObject's pipeline */ - typedef SimpleDataObjectDecorator< MatrixType > MatrixDecoratedType; - - /** MeasurementVector is not a DataObject, we need to decorate it to push it down - * a ProcessObject's pipeline */ - typedef SimpleDataObjectDecorator< MeasurementVectorRealType > MeasurementVectorDecoratedType; - typedef MeasurementVectorDecoratedType OutputType; + /** Type of covariance matrix output */ + typedef VariableSizeMatrix< MeasurementRealType > MatrixType; /** Return the covariance matrix */ const MatrixType GetCovarianceMatrix() const; + /** VariableSizeMatrix is not a DataObject, we need to decorate it to push it down + * a ProcessObject's pipeline */ + typedef SimpleDataObjectDecorator< MatrixType > MatrixDecoratedType; const MatrixDecoratedType * GetCovarianceMatrixOutput() const; + /** Return the mean vector */ const MeasurementVectorRealType GetMean() const; + /** MeasurementVector is not a DataObject, we need to decorate it to push it down + * a ProcessObject's pipeline */ + typedef SimpleDataObjectDecorator< MeasurementVectorRealType > MeasurementVectorDecoratedType; const MeasurementVectorDecoratedType * GetMeanOutput() const; + typedef MeasurementVectorDecoratedType OutputType; + MeasurementVectorSizeType GetMeasurementVectorSize() const; protected: CovarianceSampleFilter(); virtual ~CovarianceSampleFilter(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** DataObject pointer */ typedef DataObject::Pointer DataObjectPointer; typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: CovarianceSampleFilter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.hxx index 20f6fadc89cda6716d3813cc782f94c4e2825e9f..d6dc0aadfd75466dfd1dd908067b14fd63eb23e7 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkCovarianceSampleFilter.hxx @@ -76,7 +76,7 @@ CovarianceSampleFilter< TSample > { MatrixType covarianceMatrix(measurementVectorSize, measurementVectorSize); covarianceMatrix.SetIdentity(); - MatrixDecoratedType::Pointer decoratedCovarianceMatrix = MatrixDecoratedType::New(); + typename MatrixDecoratedType::Pointer decoratedCovarianceMatrix = MatrixDecoratedType::New(); decoratedCovarianceMatrix->Set(covarianceMatrix); return decoratedCovarianceMatrix.GetPointer(); } @@ -86,7 +86,7 @@ CovarianceSampleFilter< TSample > MeasurementVectorRealType mean; (void)mean; // for complainty pants : valgrind NumericTraits<MeasurementVectorRealType>::SetLength(mean, this->GetMeasurementVectorSize()); - mean.Fill( NumericTraits< MeasurementRealType >::Zero ); + // NumericTraits::SetLength also initializes array to zero typename MeasurementVectorDecoratedType::Pointer decoratedMean = MeasurementVectorDecoratedType::New(); decoratedMean->Set( mean ); return decoratedMean.GetPointer(); @@ -125,6 +125,7 @@ inline void CovarianceSampleFilter< TSample > ::GenerateData() { + // set up input / output const SampleType *input = this->GetInput(); MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); @@ -133,47 +134,46 @@ CovarianceSampleFilter< TSample > itkDynamicCastInDebugMode< MatrixDecoratedType * >( this->ProcessObject::GetOutput(0) ); MatrixType output = decoratedOutput->Get(); + output.SetSize( measurementVectorSize, measurementVectorSize ); + output.Fill( NumericTraits< typename MatrixType::ValueType >::Zero ); MeasurementVectorDecoratedType *decoratedMeanOutput = - itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >(this->ProcessObject::GetOutput(1)); + itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(1) ); - output.SetSize(measurementVectorSize, measurementVectorSize); - output.Fill(0.0); - - double totalFrequency = 0.0; - - typename TSample::ConstIterator iter = input->Begin(); - typename TSample::ConstIterator end = input->End(); - - MeasurementVectorRealType diff; - MeasurementVectorType measurements; - - NumericTraits<MeasurementVectorRealType>::SetLength(diff, measurementVectorSize); - NumericTraits<MeasurementVectorType>::SetLength(measurements, measurementVectorSize); - - typedef MeanSampleFilter< TSample > MeanFilterType; + // calculate mean + typedef MeanSampleFilter< SampleType > MeanFilterType; typename MeanFilterType::Pointer meanFilter = MeanFilterType::New(); meanFilter->SetInput( input ); meanFilter->Update(); - const typename MeanFilterType::MeasurementVectorDecoratedType * decorator = meanFilter->GetOutput(); - const typename MeanFilterType::MeasurementVectorRealType mean = decorator->Get(); - + const typename MeanFilterType::MeasurementVectorRealType mean = meanFilter->GetMean(); decoratedMeanOutput->Set( mean ); - iter = input->Begin(); + // covariance algorithm + MeasurementVectorRealType diff; + NumericTraits<MeasurementVectorRealType>::SetLength( diff, measurementVectorSize ); + + typedef typename SampleType::TotalAbsoluteFrequencyType TotalFrequencyType; + TotalFrequencyType totalFrequency = NumericTraits< TotalFrequencyType >::Zero; + + typename SampleType::ConstIterator iter = input->Begin(); + const typename SampleType::ConstIterator end = input->End(); // fills the lower triangle and the diagonal cells in the covariance matrix - while ( iter != end ) + for (; iter != end; ++iter ) { - const double frequency = iter.GetFrequency(); + const MeasurementVectorType & measurement = iter.GetMeasurementVector(); + + const typename SampleType::AbsoluteFrequencyType frequency = iter.GetFrequency(); totalFrequency += frequency; - measurements = iter.GetMeasurementVector(); - for ( unsigned int i = 0; i < measurementVectorSize; ++i ) + for ( unsigned int dim = 0; dim < measurementVectorSize; ++dim ) { - diff[i] = static_cast< MeasurementRealType >( measurements[i] ) - mean[i]; + const MeasurementRealType component = + static_cast< MeasurementRealType >( measurement[dim] ); + + diff[dim] = ( component - mean[dim] ); } // updates the covariance matrix @@ -181,10 +181,10 @@ CovarianceSampleFilter< TSample > { for ( unsigned int col = 0; col < row + 1; ++col ) { - output(row, col) += frequency * diff[row] * diff[col]; + output(row, col) += + ( static_cast< MeasurementRealType >( frequency ) * diff[row] * diff[col] ); } } - ++iter; } // fills the upper triangle using the lower triangle @@ -196,23 +196,21 @@ CovarianceSampleFilter< TSample > } } - if( totalFrequency - 1.0 > vnl_math::eps ) + const double normalizationFactor = + ( static_cast< MeasurementRealType >( totalFrequency ) - 1.0 ); + + if( normalizationFactor > vnl_math::eps ) { - const double factor = 1.0 / ( totalFrequency - 1.0 ); + const double inverseNormalizationFactor = 1.0 / normalizationFactor; - for ( unsigned int col = 0; col < measurementVectorSize; ++col ) - { - for ( unsigned int row = 0; row < measurementVectorSize; ++row ) - { - output(col, row) *= factor; - } - } - decoratedOutput->Set(output); + output *= inverseNormalizationFactor; } else { itkExceptionMacro("Total Frequency was too close to 1.0. Value = " << totalFrequency ); } + + decoratedOutput->Set( output ); } template< typename TSample > diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkDenseFrequencyContainer2.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkDenseFrequencyContainer2.h index 42b1d1cc0e4b53c009b6141698995be728c5c626..9820dcdd4dd39fbec674420a5dc7b9e5d57c05a4 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkDenseFrequencyContainer2.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkDenseFrequencyContainer2.h @@ -106,7 +106,7 @@ public: protected: DenseFrequencyContainer2(); virtual ~DenseFrequencyContainer2() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: DenseFrequencyContainer2(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkEuclideanDistanceMetric.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkEuclideanDistanceMetric.hxx index a214d48cb935aaba335b2eac17c3d0299c066465..7f2c8ce9c2703db235867582721f720c229aa9e2 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkEuclideanDistanceMetric.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkEuclideanDistanceMetric.hxx @@ -47,7 +47,7 @@ EuclideanDistanceMetric< TVector > sumOfSquares += temp * temp; } - const double distance = vcl_sqrt(sumOfSquares); + const double distance = std::sqrt(sumOfSquares); return distance; } @@ -74,7 +74,7 @@ EuclideanDistanceMetric< TVector > sumOfSquares += temp * temp; } - const double distance = vcl_sqrt(sumOfSquares); + const double distance = std::sqrt(sumOfSquares); return distance; } @@ -86,7 +86,7 @@ EuclideanDistanceMetric< TVector > { const double temp = a - b; - return vcl_abs(temp); + return std::abs(temp); } } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkExpectationMaximizationMixtureModelEstimator.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkExpectationMaximizationMixtureModelEstimator.h index e1d6a2c6570ba7e13dfa27ec89e01783ce1f0516..667700f91a1b5d9047a1523448007baa8476d254 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkExpectationMaximizationMixtureModelEstimator.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkExpectationMaximizationMixtureModelEstimator.h @@ -170,7 +170,7 @@ public: protected: ExpectationMaximizationMixtureModelEstimator(); virtual ~ExpectationMaximizationMixtureModelEstimator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; bool CalculateDensities(); diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkExpectationMaximizationMixtureModelEstimator.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkExpectationMaximizationMixtureModelEstimator.hxx index 422746c2ef556b9aa11b776bafbdfebaf4cac651..912e7d54b633c81df69db37abdbd5bb8f88ae130 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkExpectationMaximizationMixtureModelEstimator.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkExpectationMaximizationMixtureModelEstimator.hxx @@ -27,15 +27,14 @@ namespace Statistics { template< typename TSample > ExpectationMaximizationMixtureModelEstimator< TSample > -::ExpectationMaximizationMixtureModelEstimator() +::ExpectationMaximizationMixtureModelEstimator() : + m_Sample(ITK_NULLPTR), + m_MaxIteration(100), + m_CurrentIteration(0), + m_TerminationCode(NOT_CONVERGED), + m_MembershipFunctionsObject (MembershipFunctionVectorObjectType::New()), + m_MembershipFunctionsWeightArrayObject(MembershipFunctionsWeightsArrayObjectType::New()) { - m_TerminationCode = NOT_CONVERGED; - - m_MembershipFunctionsObject = MembershipFunctionVectorObjectType::New(); - m_MembershipFunctionsWeightArrayObject = - MembershipFunctionsWeightsArrayObjectType::New(); - m_Sample = 0; - m_MaxIteration = 100; } template< typename TSample > @@ -264,7 +263,7 @@ ExpectationMaximizationMixtureModelEstimator< TSample > // the log may blow up if( temp > NumericTraits<double>::epsilon() ) { - logProportion = vcl_log( temp ); + logProportion = std::log( temp ); } else { @@ -277,7 +276,7 @@ ExpectationMaximizationMixtureModelEstimator< TSample > GetWeight(measurementVectorIndex); if( temp > NumericTraits<double>::epsilon() ) { - sum += temp * ( logProportion + vcl_log( temp ) ); + sum += temp * ( logProportion + std::log( temp ) ); } else { @@ -306,7 +305,7 @@ ExpectationMaximizationMixtureModelEstimator< TSample > component->Update(); if ( component->AreParametersModified() ) { - return true; + updated = true; } } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianDistribution.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianDistribution.h index 7fc5d57a0eef18e29abc83322a2b0abbc0553339..73769d71b5946291b60a260fae827961825061d3 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianDistribution.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianDistribution.h @@ -75,16 +75,16 @@ public: /** Return the number of parameters. For a univariate Gaussian, * this is 2 (mean, variance). */ - virtual SizeValueType GetNumberOfParameters() const { return 2; } + virtual SizeValueType GetNumberOfParameters() const ITK_OVERRIDE { return 2; } /** Evaluate the probability density function (pdf). The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluatePDF(double x) const; + virtual double EvaluatePDF(double x) const ITK_OVERRIDE; /** Evaluate the probability density function (pdf). The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (mean, variance). */ - virtual double EvaluatePDF(double x, const ParametersType &) const; + virtual double EvaluatePDF(double x, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the probability density function (pdf). The parameters * of the distribution are passed as separate parameters. */ @@ -92,12 +92,12 @@ public: /** Evaluate the cumulative distribution function (cdf). The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluateCDF(double x) const; + virtual double EvaluateCDF(double x) const ITK_OVERRIDE; /** Evaluate the cumulative distribution function (cdf). The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (mean, variance). */ - virtual double EvaluateCDF(double x, const ParametersType &) const; + virtual double EvaluateCDF(double x, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the cumulative distribution function (cdf). The parameters * of the distribution are passed as separate parameters. */ @@ -106,13 +106,13 @@ public: /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluateInverseCDF(double p) const; + virtual double EvaluateInverseCDF(double p) const ITK_OVERRIDE; /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (mean, variance). */ - virtual double EvaluateInverseCDF(double p, const ParametersType &) const; + virtual double EvaluateInverseCDF(double p, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters @@ -127,10 +127,10 @@ public: /** Get the mean of the Gaussian distribution. Defaults to 0.0. The * mean is stored in position 0 of the parameters vector. */ - virtual double GetMean() const; + virtual double GetMean() const ITK_OVERRIDE; /** Does this distribution have a mean? */ - virtual bool HasMean() const { return true; } + virtual bool HasMean() const ITK_OVERRIDE { return true; } /** Set the variance of the Gaussian distribution. Defaults * to 1.0. The variance is stored in position 1 of the parameters @@ -139,10 +139,10 @@ public: /** Get the variance of the Gaussian distribution. Defaults to * 1.0. The variance is stored in position 1 of the parameters vector. */ - virtual double GetVariance() const; + virtual double GetVariance() const ITK_OVERRIDE; /** Does this distribution have a variance? */ - virtual bool HasVariance() const { return true; } + virtual bool HasVariance() const ITK_OVERRIDE { return true; } /** Static method to evaluate the probability density function (pdf) * of a standardized (mean zero, unit variance) Gaussian. The static @@ -233,7 +233,7 @@ protected: GaussianDistribution(void); virtual ~GaussianDistribution(void) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: GaussianDistribution(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianMembershipFunction.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianMembershipFunction.hxx index b2c67e104891c5e250f90210e19f0643a6dd96ee..70e30ed4f6a6575b29da93d994c1a65508b33fc3 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianMembershipFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianMembershipFunction.hxx @@ -31,7 +31,7 @@ GaussianMembershipFunction< TMeasurementVector > NumericTraits<MeanVectorType>::SetLength(m_Mean, this->GetMeasurementVectorSize()); m_Mean.Fill( 0.0 ); - m_PreFactor = 1.0 / vcl_sqrt(2.0 * vnl_math::pi); // default univariate + m_PreFactor = 1.0 / std::sqrt(2.0 * vnl_math::pi); // default univariate m_Covariance.SetSize(this->GetMeasurementVectorSize(), this->GetMeasurementVectorSize()); m_Covariance.SetIdentity(); @@ -136,13 +136,13 @@ GaussianMembershipFunction< TMeasurementVector > // calculate coefficient C of multivariate gaussian m_PreFactor = - 1.0 / ( vcl_sqrt(det) * - vcl_pow( vcl_sqrt(2.0 * vnl_math::pi), + 1.0 / ( std::sqrt(det) * + std::pow( std::sqrt(2.0 * vnl_math::pi), static_cast< double >( this->GetMeasurementVectorSize() ) ) ); } else { - const double aLargeDouble = vcl_pow(NumericTraits<double>::max(), 1.0/3.0) + const double aLargeDouble = std::pow(NumericTraits<double>::max(), 1.0/3.0) / (double) this->GetMeasurementVectorSize(); m_InverseCovariance.SetIdentity(); m_InverseCovariance *= aLargeDouble; @@ -173,7 +173,7 @@ GaussianMembershipFunction< TMeasurementVector > double temp = dot_product( tempVector, m_InverseCovariance.GetVnlMatrix() * tempVector ); - temp = vcl_exp(-0.5 * temp); + temp = std::exp(-0.5 * temp); return m_PreFactor * temp; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianMixtureModelComponent.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianMixtureModelComponent.hxx index 8e691e5471598751f1dcb472d661fa0ecc1026eb..6bcd3e928c87b78efc5040fcef04c0e748e0d55e 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianMixtureModelComponent.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianMixtureModelComponent.hxx @@ -177,7 +177,7 @@ GaussianMixtureModelComponent< TSample > } } - changes = vcl_sqrt(changes); + changes = std::sqrt(changes); return changes; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianRandomSpatialNeighborSubsampler.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianRandomSpatialNeighborSubsampler.hxx index ed9670353b3b66d499be2183d8187f506d47cdf4..ced22e112b1a1dca9c1a531b76617efbe772c220 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianRandomSpatialNeighborSubsampler.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkGaussianRandomSpatialNeighborSubsampler.hxx @@ -69,7 +69,7 @@ GaussianRandomSpatialNeighborSubsampler<TSample, TRegion> { RealType randVar = this->m_RandomNumberGenerator->GetNormalVariate(mean, m_Variance); - randInt = static_cast<RandomIntType>(vcl_floor(randVar)); + randInt = static_cast<RandomIntType>(std::floor(randVar)); } while ((randInt < lowerBound) || (randInt > upperBound)); return randInt; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogram.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogram.h index 5647eaeb6d95eace6402fc4fe38c51211ce120f9..3c7cd04051356b3c5a278e9615c9aa3569ea6fb9 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogram.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogram.h @@ -264,7 +264,11 @@ public: /** Increase the frequency of a measurement. Frequency is * increased by the specified value. Returns false if the - * measurement is outside the bounds of the histogram. */ + * measurement is outside the bounds of the histogram. + * + * \warning This function performs a dynamic allocation for the + * index length, and should not be used in tight per-pixel loops. + */ bool IncreaseFrequencyOfMeasurement( const MeasurementVectorType & measurement, AbsoluteFrequencyType value); diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogram.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogram.hxx index b06728498a98257798bdb082f7e1fcf3cfff4e71..18bb97f0d93fc1e74634851b8dca8de56f1d7a26 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogram.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogram.hxx @@ -27,11 +27,13 @@ namespace Statistics { template< typename TMeasurement, typename TFrequencyContainer > Histogram< TMeasurement, TFrequencyContainer > -::Histogram() +::Histogram() : + m_Size(0), + m_OffsetTable(OffsetTableType(Superclass::GetMeasurementVectorSize() + 1)), + m_FrequencyContainer(FrequencyContainerType::New()), + m_NumberOfInstances(0), + m_ClipBinsAtEnds(true) { - this->m_ClipBinsAtEnds = true; - this->m_FrequencyContainer = FrequencyContainerType::New(); - this->m_OffsetTable = OffsetTableType(this->GetMeasurementVectorSize() + 1); for ( unsigned int i = 0; i < this->GetMeasurementVectorSize() + 1; i++ ) { this->m_OffsetTable[i] = itk::NumericTraits< InstanceIdentifier >::Zero; @@ -741,8 +743,7 @@ Histogram< TMeasurement, TFrequencyContainer > os << this->m_OffsetTable[i] << " "; } os << std::endl; - os << indent << "FrequencyContainerPointer: " << std::endl; - m_FrequencyContainer->Print( os, indent.GetNextIndent() ); + itkPrintSelfObjectMacro( FrequencyContainer ); } template< typename TMeasurement, typename TFrequencyContainer > diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToEntropyImageFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToEntropyImageFilter.h index e4dac1df5d468053041cc118ddef4acb137365bb..f94888ba8491a45010dcd2874c4454a5078a31b8 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToEntropyImageFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToEntropyImageFilter.h @@ -73,13 +73,13 @@ public: { const double p = static_cast< OutputPixelType >( A ) / static_cast< OutputPixelType >( m_TotalFrequency ); - return static_cast< OutputPixelType >( ( -1 ) * p * vcl_log(p) / vcl_log(2.0) ); + return static_cast< OutputPixelType >( ( -1 ) * p * std::log(p) / std::log(2.0) ); } else { const double p = static_cast< OutputPixelType >( A + 1 ) / static_cast< OutputPixelType >( m_TotalFrequency ); - return static_cast< OutputPixelType >( ( -1 ) * p * vcl_log(p) / vcl_log(2.0) ); + return static_cast< OutputPixelType >( ( -1 ) * p * std::log(p) / std::log(2.0) ); } } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToLogProbabilityImageFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToLogProbabilityImageFilter.h index 0e25cf87ee75b5196f471bae944c2e1126309034..faa3944978b6ea6c54cc7039adee90ceecc66b4d 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToLogProbabilityImageFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToLogProbabilityImageFilter.h @@ -66,15 +66,15 @@ public: { if ( A ) { - return static_cast< OutputPixelType >( vcl_log( static_cast< OutputPixelType >( A ) + return static_cast< OutputPixelType >( std::log( static_cast< OutputPixelType >( A ) / static_cast< OutputPixelType >( m_TotalFrequency ) ) - / vcl_log(2.0) ); + / std::log(2.0) ); } else { // Check for Log 0. Always assume that the frequency is atleast 1. - return static_cast< OutputPixelType >( vcl_log( static_cast< OutputPixelType >( A + 1 ) + return static_cast< OutputPixelType >( std::log( static_cast< OutputPixelType >( A + 1 ) / static_cast< OutputPixelType >( m_TotalFrequency ) ) - / vcl_log(2.0) ); + / std::log(2.0) ); } } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToRunLengthFeaturesFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToRunLengthFeaturesFilter.h index d733a6cd751b96ef9ff543c9f187d665b4237c40..a5cc63c00aaf976f7f857b024a0eb4eefbeaa73a 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToRunLengthFeaturesFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToRunLengthFeaturesFilter.h @@ -161,14 +161,14 @@ public: protected: HistogramToRunLengthFeaturesFilter(); ~HistogramToRunLengthFeaturesFilter() {}; - void PrintSelf(std::ostream& os, Indent indent) const; + virtual void PrintSelf(std::ostream& os, Indent indent) const ITK_OVERRIDE; /** Make a DataObject to be used for output output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput( DataObjectPointerArraySizeType ); + virtual DataObjectPointer MakeOutput( DataObjectPointerArraySizeType ) ITK_OVERRIDE; - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: HistogramToRunLengthFeaturesFilter(const Self&); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToRunLengthFeaturesFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToRunLengthFeaturesFilter.hxx index 903ae1a3be8cce04e88b22d0aa3bd0b8cc3c00a8..1004f00f9d21a04a306d66cb872bcfa7fe418b7f 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToRunLengthFeaturesFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToRunLengthFeaturesFilter.hxx @@ -57,7 +57,7 @@ HistogramToRunLengthFeaturesFilter< THistogram> { if ( this->GetNumberOfInputs() < 1 ) { - return 0; + return ITK_NULLPTR; } return itkDynamicCastInDebugMode<const HistogramType *>(this->ProcessObject::GetInput( 0 ) ); } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToTextureFeaturesFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToTextureFeaturesFilter.h index 97a35078acfc6ba32343ad96e4c7c76b51b54d4c..2f47a98ed645a113fdae4d85e48d57f19a678311 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToTextureFeaturesFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToTextureFeaturesFilter.h @@ -204,14 +204,14 @@ public: protected: HistogramToTextureFeaturesFilter(); ~HistogramToTextureFeaturesFilter() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Make a DataObject to be used for output output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType) ITK_OVERRIDE; - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: HistogramToTextureFeaturesFilter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToTextureFeaturesFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToTextureFeaturesFilter.hxx index f1781fd6d9f49490cc561739e82eb47439f54a7c..c1689bde475e219bddc70a00e8076b5794bb1915 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToTextureFeaturesFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkHistogramToTextureFeaturesFilter.hxx @@ -114,7 +114,7 @@ HistogramToTextureFeaturesFilter< THistogram >::GenerateData(void) MeasurementType haralickCorrelation = NumericTraits< MeasurementType >::Zero; double pixelVarianceSquared = pixelVariance * pixelVariance; - double log2 = vcl_log(2.0); + double log2 = std::log(2.0); typename RelativeFrequencyContainerType::const_iterator rFreqIterator = m_RelativeFrequencyContainer.begin(); @@ -132,15 +132,15 @@ HistogramToTextureFeaturesFilter< THistogram >::GenerateData(void) IndexType index = inputHistogram->GetIndex( hit.GetInstanceIdentifier() ); energy += frequency * frequency; - entropy -= ( frequency > 0.0001 ) ? frequency *vcl_log(frequency) / log2:0; + entropy -= ( frequency > 0.0001 ) ? frequency *std::log(frequency) / log2:0; correlation += ( ( index[0] - pixelMean ) * ( index[1] - pixelMean ) * frequency ) / pixelVarianceSquared; inverseDifferenceMoment += frequency / ( 1.0 + ( index[0] - index[1] ) * ( index[0] - index[1] ) ); inertia += ( index[0] - index[1] ) * ( index[0] - index[1] ) * frequency; - clusterShade += vcl_pow( ( index[0] - pixelMean ) + ( index[1] - pixelMean ), 3 ) + clusterShade += std::pow( ( index[0] - pixelMean ) + ( index[1] - pixelMean ), 3 ) * frequency; - clusterProminence += vcl_pow( ( index[0] - pixelMean ) + ( index[1] - pixelMean ), 4 ) + clusterProminence += std::pow( ( index[0] - pixelMean ) + ( index[1] - pixelMean ), 4 ) * frequency; haralickCorrelation += index[0] * index[1] * frequency; } @@ -229,7 +229,7 @@ HistogramToTextureFeaturesFilter< THistogram >::ComputeMeansAndVariances(double M(1) = x(1), M(k) = M(k-1) + (x(k) - M(k-1) ) / k S(1) = 0, S(k) = S(k-1) + (x(k) - M(k-1)) * (x(k) - M(k)) for 2 <= k <= n, then - sigma = vcl_sqrt(S(n) / n) (or divide by n-1 for sample SD instead of + sigma = std::sqrt(S(n) / n) (or divide by n-1 for sample SD instead of population SD). */ marginalMean = marginalSums[0]; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageClassifierFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageClassifierFilter.hxx index eeb66500fcc4cfe5039d2c2046e6fdcb1ed10b4d..f87d3a252312ca8ae0608ca07351dd0f1e59be8c 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageClassifierFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageClassifierFilter.hxx @@ -34,7 +34,7 @@ ImageClassifierFilter< TSample, TInputImage, TOutputImage > this->SetNumberOfRequiredOutputs(1); /** Initialize decision rule */ - m_DecisionRule = NULL; + m_DecisionRule = ITK_NULLPTR; m_NumberOfClasses = 0; } @@ -143,7 +143,7 @@ ImageClassifierFilter< TSample, TInputImage, TOutputImage > } MembershipFunctionsWeightsArrayType membershipFunctionsWeightsArray; - if ( membershipFunctionsWeightsArrayDecorated == NULL ) + if ( membershipFunctionsWeightsArrayDecorated == ITK_NULLPTR ) { // no weights array is set and hence all membership functions will have // equal diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToHistogramFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToHistogramFilter.hxx index 82d16f5803dfa1017a0575ede1af8dcd850f1337..bb56efe4eb3f1e2a93a90b599a4a7ccb04a051ab 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToHistogramFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToHistogramFilter.hxx @@ -235,16 +235,17 @@ ImageToHistogramFilter< TImage > { // group the results in the output histogram HistogramType * hist = m_Histograms[0]; + typename HistogramType::IndexType index; for( unsigned int i=1; i<m_Histograms.size(); i++ ) { typedef typename HistogramType::ConstIterator HistogramIterator; - typedef typename HistogramType::AbsoluteFrequencyType AbsoluteFrequencyType; HistogramIterator hit = m_Histograms[i]->Begin(); HistogramIterator end = m_Histograms[i]->End(); while ( hit != end ) { - hist->IncreaseFrequencyOfMeasurement( hit.GetMeasurementVector(), hit.GetFrequency() ); + hist->GetIndex( hit.GetMeasurementVector(), index); + hist->IncreaseFrequencyOfIndex( index, hit.GetFrequency() ); ++hit; } } @@ -253,7 +254,7 @@ ImageToHistogramFilter< TImage > m_Histograms.clear(); m_Minimums.clear(); m_Maximums.clear(); - m_Barrier = NULL; + m_Barrier = ITK_NULLPTR; } @@ -298,11 +299,13 @@ ImageToHistogramFilter< TImage > inputIt.GoToBegin(); HistogramMeasurementVectorType m( nbOfComponents ); + typename HistogramType::IndexType index; while ( !inputIt.IsAtEnd() ) { const PixelType & p = inputIt.Get(); NumericTraits<PixelType>::AssignToArray( p, m ); - m_Histograms[threadId]->IncreaseFrequencyOfMeasurement( m, 1 ); + m_Histograms[threadId]->GetIndex( m, index ); + m_Histograms[threadId]->IncreaseFrequencyOfIndex( index, 1 ); ++inputIt; progress.CompletedPixel(); // potential exception thrown here } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleAdaptor.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleAdaptor.h index 7d9808db5eb112f71e8084e938c043b41c854824..cce79d51503a7d46942003260697a3984bb49bc2 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleAdaptor.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleAdaptor.h @@ -140,18 +140,17 @@ public: { friend class ImageToListSampleAdaptor; -public: + public: ConstIterator(const ImageToListSampleAdaptor *adaptor) { *this = adaptor->Begin(); } - ConstIterator(const ConstIterator & iter) - { - m_Iter = iter.m_Iter; - m_InstanceIdentifier = iter.m_InstanceIdentifier; - } + ConstIterator(const ConstIterator & iter) : + m_Iter(iter.m_Iter), + m_InstanceIdentifier(iter.m_InstanceIdentifier) + {} ConstIterator & operator=(const ConstIterator & iter) { @@ -193,20 +192,17 @@ public: return ( m_Iter == it.m_Iter ); } -protected: + protected: // This method should only be available to the ListSample class - ConstIterator( - ImageConstIteratorType iter, - InstanceIdentifier iid) - { - m_Iter = iter; - m_InstanceIdentifier = iid; - } + ConstIterator(const ImageConstIteratorType & iter, InstanceIdentifier iid) : + m_Iter(iter), + m_InstanceIdentifier(iid) + {} // This method is purposely not implemented ConstIterator(); -private: + private: ImageConstIteratorType m_Iter; mutable MeasurementVectorType m_MeasurementVectorCache; InstanceIdentifier m_InstanceIdentifier; @@ -216,16 +212,19 @@ private: * \brief Iterator * \ingroup ITKStatistics */ - class Iterator:public ConstIterator + class Iterator: + public ConstIterator { friend class ImageToListSampleAdaptor; -public: + public: - Iterator(Self *adaptor):ConstIterator(adaptor) + Iterator(Self *adaptor) : + ConstIterator(adaptor) {} - Iterator(const Iterator & iter):ConstIterator(iter) + Iterator(const Iterator & iter): + ConstIterator(iter) {} Iterator & operator=(const Iterator & iter) @@ -234,19 +233,20 @@ public: return *this; } -protected: + protected: // To ensure const-correctness these method must not be in the public API. // The are purposly not implemented, since they should never be called. Iterator(); Iterator(const Self *adaptor); - Iterator(ImageConstIteratorType iter, InstanceIdentifier iid); + Iterator(const ImageConstIteratorType & iter, InstanceIdentifier iid); Iterator(const ConstIterator & it); ConstIterator & operator=(const ConstIterator & it); - Iterator( ImageIteratorType iter, InstanceIdentifier iid):ConstIterator(iter, iid) + Iterator(const ImageIteratorType & iter, InstanceIdentifier iid) : + ConstIterator(iter, iid) {} -private: + private: }; /** returns an iterator that points to the beginning of the container */ diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleAdaptor.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleAdaptor.hxx index 8a61b5810c6956d82c477dbb328e19b64ac6dfcd..d9390cdee363f1b6a8726813375a836a036d7257 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleAdaptor.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleAdaptor.hxx @@ -28,7 +28,7 @@ template< typename TImage > ImageToListSampleAdaptor< TImage > ::ImageToListSampleAdaptor() { - m_Image = 0; + m_Image = ITK_NULLPTR; } template< typename TImage > diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleFilter.h index 1f95b1283f63581d11c272290a9a2f02bbb317b6..f2b2c923091cd5b4114e94b9e9e9f17a895e4134 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleFilter.h @@ -114,23 +114,22 @@ public: protected: ImageToListSampleFilter(); virtual ~ImageToListSampleFilter() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Standard itk::ProcessObject subclass method. */ typedef DataObject::Pointer DataObjectPointer; typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** This method causes the filter to generate its output. */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** This method ensures that a mask image if specified has requested regions * that at least contain the input image's buffered region. */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; - virtual void GenerateOutputInformation(); + virtual void GenerateOutputInformation() ITK_OVERRIDE; private: ImageToListSampleFilter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleFilter.hxx index b94c53e793eeced030747c8f1db827274f36fdf8..7119054999d3657c39e4698effe5b3a961ec37c7 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToListSampleFilter.hxx @@ -99,7 +99,7 @@ ImageToListSampleFilter< TImage, TMaskImage > { const ImageType *input = this->GetInput(); - if ( input == NULL ) + if ( input == ITK_NULLPTR ) { itkExceptionMacro("Input image has not been set yet"); } @@ -128,7 +128,7 @@ ImageToListSampleFilter< TImage, TMaskImage > static_cast< ListSampleType * >( this->ProcessObject::GetOutput(0) ); const ImageType * input = this->GetInput(); - const MaskImageType *maskImage = NULL; + const MaskImageType *maskImage = ITK_NULLPTR; // Verify whether the image and the mask have the same LargestPossibleRegion. // Otherwise, throw an exception. @@ -194,7 +194,6 @@ template< typename TImage, typename TMaskImage > void ImageToListSampleFilter< TImage, TMaskImage > ::GenerateInputRequestedRegion() -throw( InvalidRequestedRegionError ) { // call the superclass' implementation of this method. this should // copy the output requested region to the input requested region diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToNeighborhoodSampleAdaptor.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToNeighborhoodSampleAdaptor.hxx index 86a6f87fb4aa052a18f8e11ea0490dfa4ce17b93..819477a9a61577bde41996bfe736242d4baa1e09 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToNeighborhoodSampleAdaptor.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkImageToNeighborhoodSampleAdaptor.hxx @@ -25,19 +25,21 @@ namespace Statistics { template < typename TImage, typename TBoundaryCondition> ImageToNeighborhoodSampleAdaptor< TImage, TBoundaryCondition> -::ImageToNeighborhoodSampleAdaptor() + ::ImageToNeighborhoodSampleAdaptor() : + m_Image(ITK_NULLPTR), + m_InstanceIdentifierInternal(0), + m_UseImageRegion(true) { - m_Image = 0; m_Radius.Fill(0); + m_NeighborIndexInternal.Fill(0); + NeighborhoodIndexType start; NeighborhoodSizeType sz; start.Fill(0); sz.Fill(0); m_Region.SetIndex(start); m_Region.SetSize(sz); - m_UseImageRegion = true; this->SetMeasurementVectorSize(1); - m_NeighborIndexInternal.Fill(0); } template < typename TImage, typename TBoundaryCondition> diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkJointDomainImageToListSampleAdaptor.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkJointDomainImageToListSampleAdaptor.hxx index 8a88c21f98d4de4a9ca8284f9a0e5593fc4c9654..8020174fd75f0c5e994ea61be0b369debc001b15 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkJointDomainImageToListSampleAdaptor.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkJointDomainImageToListSampleAdaptor.hxx @@ -29,7 +29,7 @@ JointDomainImageToListSampleAdaptor< TImage > ::JointDomainImageToListSampleAdaptor() { m_NormalizationFactors.Fill(1.0f); - m_Image = 0; + m_Image = ITK_NULLPTR; m_UsePixelContainer = true; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTree.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTree.h index ac93787b4846446c2e669b144fdcea2ae96e47d1..eb6d9f36e8960ac00a45df4e531388784a84d5d3 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTree.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTree.h @@ -385,25 +385,25 @@ struct KdTreeTerminalNode:public KdTreeNode<TSample> /** Return the left tree pointer. Null for terminal nodes. */ Superclass * Left() { - return 0; + return ITK_NULLPTR; } /** Return the right tree pointer. Null for terminal nodes. */ Superclass * Right() { - return 0; + return ITK_NULLPTR; } /** Return the left tree const pointer. Null for terminal nodes. */ const Superclass * Left() const { - return 0; + return ITK_NULLPTR; } /** Return the right tree const pointer. Null for terminal nodes. */ const Superclass * Right() const { - return 0; + return ITK_NULLPTR; } /** Return the size of the node. */ @@ -535,7 +535,7 @@ public: { public: /** Constructor */ - NearestNeighbors() {} + NearestNeighbors() : m_FarthestNeighborIndex(0) {} /** Destructor */ ~NearestNeighbors() {} @@ -674,7 +674,13 @@ public: /** Searches the k-nearest neighbors */ void Search( const MeasurementVectorType &, unsigned int, - InstanceIdentifierVectorType & ) const; + InstanceIdentifierVectorType & ) const; + + /** Searches the k-nearest neighbors and returns + * the distance vector along with the distance measures. + */ + void Search( const MeasurementVectorType &, unsigned int, + InstanceIdentifierVectorType &, std::vector<double> & ) const; /** Searches the neighbors fallen into a hypersphere */ void Search( const MeasurementVectorType &, double, @@ -721,7 +727,7 @@ protected: /** Destructor: deletes the root node and the empty terminal node. */ virtual ~KdTree(); - void PrintSelf( std::ostream & os, Indent indent ) const; + virtual void PrintSelf( std::ostream & os, Indent indent ) const ITK_OVERRIDE; /** search loop */ int NearestNeighborSearchLoop( const KdTreeNodeType *, diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTree.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTree.hxx index 875f467bae68343c4fb118b7978284de7cb27b39..f4415348a263eba0570c3aba986961fdaa85a0f7 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTree.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTree.hxx @@ -27,12 +27,13 @@ namespace Statistics template<typename TSample> KdTreeNonterminalNode<TSample> ::KdTreeNonterminalNode( unsigned int partitionDimension, - MeasurementType partitionValue, Superclass *left, Superclass *right ) + MeasurementType partitionValue, Superclass *left, Superclass *right ) : + m_PartitionDimension(partitionDimension), + m_PartitionValue(partitionValue), + m_InstanceIdentifier(0), + m_Left(left), + m_Right(right) { - this->m_PartitionDimension = partitionDimension; - this->m_PartitionValue = partitionValue; - this->m_Left = left; - this->m_Right = right; } template<typename TSample> @@ -81,8 +82,8 @@ KdTree<TSample> this->m_EmptyTerminalNode = new KdTreeTerminalNode<TSample>(); this->m_DistanceMetric = DistanceMetricType::New(); - this->m_Sample = 0; - this->m_Root = 0; + this->m_Sample = ITK_NULLPTR; + this->m_Root = ITK_NULLPTR; this->m_BucketSize = 16; this->m_MeasurementVectorSize = 0; } @@ -91,7 +92,7 @@ template<typename TSample> KdTree<TSample> ::~KdTree() { - if( this->m_Root != 0 ) + if( this->m_Root != ITK_NULLPTR ) { this->DeleteNode( this->m_Root ); } @@ -106,7 +107,7 @@ KdTree<TSample> Superclass::PrintSelf( os, indent ); os << indent << "Input Sample: "; - if( this->m_Sample != 0 ) + if( this->m_Sample != ITK_NULLPTR ) { os << this->m_Sample << std::endl; } @@ -116,7 +117,7 @@ KdTree<TSample> } os << indent << "Bucket Size: " << this->m_BucketSize << std::endl; os << indent << "Root Node: "; - if( this->m_Root != 0 ) + if( this->m_Root != ITK_NULLPTR ) { os << this->m_Root << std::endl; } @@ -146,12 +147,12 @@ KdTree<TSample> } // non-terminal node - if( node->Left() != 0 ) + if( node->Left() != ITK_NULLPTR ) { this->DeleteNode( node->Left() ); } - if( node->Right() != 0 ) + if( node->Right() != ITK_NULLPTR ) { this->DeleteNode( node->Right() ); } @@ -183,7 +184,19 @@ template<typename TSample> void KdTree<TSample> ::Search( const MeasurementVectorType & query, - unsigned int numberOfNeighborsRequested, InstanceIdentifierVectorType &result ) const + unsigned int numberOfNeighborsRequested, InstanceIdentifierVectorType &result ) const +{ + // This function has two different signatures. The other signature, that returns the distances vector too, + // is called here; however, its distances vector is discarded. + std::vector<double> not_used_distances; + this->Search(query, numberOfNeighborsRequested, result, not_used_distances); +} + +template<typename TSample> +void +KdTree<TSample> +::Search( const MeasurementVectorType & query, + unsigned int numberOfNeighborsRequested, InstanceIdentifierVectorType &result, std::vector<double> &distances ) const { if( numberOfNeighborsRequested > this->Size() ) { @@ -204,16 +217,17 @@ KdTree<TSample> for( unsigned int d = 0; d < this->m_MeasurementVectorSize; ++d ) { - lowerBound[d] = static_cast< MeasurementType >( -vcl_sqrt( + lowerBound[d] = static_cast< MeasurementType >( -std::sqrt( -static_cast< double >( NumericTraits< MeasurementType >:: NonpositiveMin() ) ) / 2.0 ); - upperBound[d] = static_cast< MeasurementType >( vcl_sqrt( + upperBound[d] = static_cast< MeasurementType >( std::sqrt( static_cast<double >( NumericTraits< MeasurementType >::max() ) / 2.0 ) ); } this->NearestNeighborSearchLoop( this->m_Root, query, lowerBound, upperBound, nearestNeighbors ); result = nearestNeighbors.GetNeighbors(); + distances = nearestNeighbors.GetDistances(); } template<typename TSample> @@ -349,10 +363,10 @@ KdTree<TSample> for( unsigned int d = 0; d < this->m_MeasurementVectorSize; ++d ) { - lowerBound[d] = static_cast<MeasurementType>( -vcl_sqrt( + lowerBound[d] = static_cast<MeasurementType>( -std::sqrt( -static_cast<double>( NumericTraits<MeasurementType>:: NonpositiveMin() ) ) / 2.0 ); - upperBound[d] = static_cast< MeasurementType >( vcl_sqrt( + upperBound[d] = static_cast< MeasurementType >( std::sqrt( static_cast<double>( NumericTraits< MeasurementType >::max() ) / 2.0 ) ); } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeBasedKmeansEstimator.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeBasedKmeansEstimator.h index e1a42dc652feb9154078b9a97f0119ea7ef5b05e..98ee1c531fd2de020d131c735fe3af16f06bd822 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeBasedKmeansEstimator.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeBasedKmeansEstimator.h @@ -165,7 +165,7 @@ protected: KdTreeBasedKmeansEstimator(); virtual ~KdTreeBasedKmeansEstimator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void FillClusterLabels(KdTreeNodeType *node, int closestIndex); @@ -176,7 +176,7 @@ protected: class CandidateVector { public: - CandidateVector() {} + CandidateVector() : m_MeasurementVectorSize(0) {} struct Candidate { CentroidType Centroid; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeBasedKmeansEstimator.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeBasedKmeansEstimator.hxx index d2e8b9c424fcff6f554809d95bf120ea2af1b2a2..15695f154b5e94f042123e783026782d22d4660d 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeBasedKmeansEstimator.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeBasedKmeansEstimator.hxx @@ -27,20 +27,19 @@ namespace Statistics { template< typename TKdTree > KdTreeBasedKmeansEstimator< TKdTree > -::KdTreeBasedKmeansEstimator() +::KdTreeBasedKmeansEstimator() : + m_CurrentIteration(0), + m_MaximumIteration(100), + m_CentroidPositionChanges(0.0), + m_CentroidPositionChangesThreshold(0.0), + m_KdTree(ITK_NULLPTR), + m_DistanceMetric(EuclideanDistanceMetric< ParameterType >::New()), + m_UseClusterLabels(false), + m_GenerateClusterLabels(false), + m_MeasurementVectorSize(0), + m_MembershipFunctionsObject(MembershipFunctionVectorObjectType::New()) { - m_CentroidPositionChangesThreshold = 0.0; - m_KdTree = 0; - m_UseClusterLabels = false; - m_MaximumIteration = 100; - m_DistanceMetric = EuclideanDistanceMetric< ParameterType >::New(); - - m_MembershipFunctionsObject = MembershipFunctionVectorObjectType::New(); - - m_CentroidPositionChanges = 0.0; m_TempVertex.Fill(0.0); - m_CurrentIteration = 0; - m_MeasurementVectorSize = 0; } template< typename TKdTree > diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeGenerator.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeGenerator.h index 69efb0f0042e674559ae621034054669d0939acc..b413d91f67617096f1304cc7a87d5623d0f24bd7 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeGenerator.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeGenerator.h @@ -140,7 +140,7 @@ protected: /** Destructor */ virtual ~KdTreeGenerator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Returns the smart pointer to the internal Subsample object. */ SubsamplePointer GetSubsample() diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeGenerator.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeGenerator.hxx index 1c6f8c86dffefa6a8f1a50a0b0a60cd3d5b534ec..5dcbc586937c2dcee68711809fccdffa26c8dbc6 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeGenerator.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkKdTreeGenerator.hxx @@ -28,7 +28,7 @@ template< typename TSample > KdTreeGenerator< TSample > ::KdTreeGenerator() { - m_SourceSample = 0; + m_SourceSample = ITK_NULLPTR; m_BucketSize = 16; m_Subsample = SubsampleType::New(); m_MeasurementVectorSize = 0; @@ -42,7 +42,7 @@ KdTreeGenerator< TSample > Superclass::PrintSelf(os, indent); os << indent << "Source Sample: "; - if ( m_SourceSample != 0 ) + if ( m_SourceSample != ITK_NULLPTR ) { os << m_SourceSample << std::endl; } @@ -83,7 +83,7 @@ void KdTreeGenerator< TSample > ::GenerateData() { - if ( m_SourceSample == 0 ) + if ( m_SourceSample == ITK_NULLPTR ) { return; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMahalanobisDistanceMembershipFunction.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMahalanobisDistanceMembershipFunction.hxx index 06f91a3e105107d4711e153db5921d26c317c836..f5fd03405a4004d920d0b2895021610b321b8084 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMahalanobisDistanceMembershipFunction.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMahalanobisDistanceMembershipFunction.hxx @@ -124,7 +124,7 @@ MahalanobisDistanceMembershipFunction< TVector > // define the inverse to be diagonal with large values along the // diagonal. value chosen so (X-M)'inv(C)*(X-M) will usually stay // below NumericTraits<double>::max() - const double aLargeDouble = vcl_pow(NumericTraits<double>::max(), 1.0/3.0) + const double aLargeDouble = std::pow(NumericTraits<double>::max(), 1.0/3.0) / (double) this->GetMeasurementVectorSize(); m_InverseCovariance.SetSize(this->GetMeasurementVectorSize(), this->GetMeasurementVectorSize()); m_InverseCovariance.SetIdentity(); @@ -145,18 +145,22 @@ MahalanobisDistanceMembershipFunction< TVector > // Our inverse covariance is always well formed. When the covariance // is singular, we use a diagonal inverse covariance with a large diagnonal - // Compute ( y - mean ) - vnl_vector< double > tempVector( measurementVectorSize ); - - for ( MeasurementVectorSizeType i = 0; i < measurementVectorSize; ++i ) + // temp = ( y - mean )^t * InverseCovariance * ( y - mean ) + // + // This is manually done to remove dynamic memory allocation: + // double temp = dot_product( tempVector, m_InverseCovariance.GetVnlMatrix() * tempVector ); + // + double temp = 0.0; + for (unsigned int r = 0; r < measurementVectorSize; ++r) { - tempVector[i] = measurement[i] - m_Mean[i]; + double rowdot = 0.0; + for(unsigned int c = 0; c < measurementVectorSize; ++c) + { + rowdot += m_InverseCovariance(r, c) * ( measurement[c] - m_Mean[c] ); + } + temp += rowdot * ( measurement[r] - m_Mean[r] ); } - // temp = ( y - mean )^t * InverseCovariance * ( y - mean ) - double temp = dot_product( tempVector, - m_InverseCovariance.GetVnlMatrix() * tempVector ); - return temp; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMahalanobisDistanceMetric.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMahalanobisDistanceMetric.hxx index d462e0a3885faf3c5c1ba71008ce5591d5870730..ece5358ae1708952f567b38d0f237f96e8d7633b 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMahalanobisDistanceMetric.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMahalanobisDistanceMetric.hxx @@ -174,7 +174,7 @@ MahalanobisDistanceMetric< TVector > // Compute |y - mean | * inverse(cov) * |y - mean|^T double temp; - temp = vcl_sqrt( dot_product( tempMat.as_ref(), tempVec.as_ref() ) ); + temp = std::sqrt( dot_product( tempMat.as_ref(), tempVec.as_ref() ) ); return temp; } @@ -208,7 +208,7 @@ MahalanobisDistanceMetric< TVector > // Compute |x1 - x2 | * inverse(cov) * |x1 - x2|^T double temp; - temp = vcl_sqrt( dot_product( tempMat.as_ref(), tempVec.as_ref() ) ); + temp = std::sqrt( dot_product( tempMat.as_ref(), tempVec.as_ref() ) ); return temp; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkManhattanDistanceMetric.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkManhattanDistanceMetric.hxx index 8f9b0f16c22e851bd0799c8e002795bcebce2ed4..4c380315dd0705ab3e4578ba75635f9f7ebc42fd 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkManhattanDistanceMetric.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkManhattanDistanceMetric.hxx @@ -43,7 +43,7 @@ ManhattanDistanceMetric< TVector > for ( unsigned int i = 0; i < measurementVectorSize; i++ ) { - temp = vcl_abs(this->GetOrigin()[i] - x[i]); + temp = std::abs(this->GetOrigin()[i] - x[i]); distance += temp; } return distance; @@ -65,7 +65,7 @@ ManhattanDistanceMetric< TVector > double temp, distance = NumericTraits< double >::Zero; for ( unsigned int i = 0; i < measurementVectorSize; i++ ) { - temp = vcl_abs(x1[i] - x2[i]); + temp = std::abs(x1[i] - x2[i]); distance += temp; } return distance; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaskedImageToHistogramFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaskedImageToHistogramFilter.hxx index ff040de1586bababdc5932eab8b7056b89283421..2452b50158e41c744f5925328f0e7a9cbd80e91d 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaskedImageToHistogramFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaskedImageToHistogramFilter.hxx @@ -86,13 +86,15 @@ MaskedImageToHistogramFilter< TImage, TMaskImage > HistogramMeasurementVectorType m( nbOfComponents ); MaskPixelType maskValue = this->GetMaskValue(); + typename HistogramType::IndexType index; while ( !inputIt.IsAtEnd() ) { if( maskIt.Get() == maskValue ) { const PixelType & p = inputIt.Get(); NumericTraits<PixelType>::AssignToArray( p, m ); - this->m_Histograms[threadId]->IncreaseFrequencyOfMeasurement( m, 1 ); + this->m_Histograms[threadId]->GetIndex( m, index ); + this->m_Histograms[threadId]->IncreaseFrequencyOfIndex( index, 1 ); } ++inputIt; ++maskIt; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaximumDecisionRule.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaximumDecisionRule.h index e5743fda9dc0f129db16d13810819acfe4be2606..da36f3e621f8d5254700cc76355abca048d2542f 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaximumDecisionRule.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaximumDecisionRule.h @@ -62,7 +62,7 @@ public: * Evaluate the decision rule, returning the class label associated * with the largest discriminant score. */ - virtual ClassIdentifierType Evaluate(const MembershipVectorType & discriminantScores) const; + virtual ClassIdentifierType Evaluate(const MembershipVectorType & discriminantScores) const ITK_OVERRIDE; protected: MaximumDecisionRule() {} diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaximumRatioDecisionRule.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaximumRatioDecisionRule.h index 1af9524eb05457135f7877d399d12a3a8a878be1..d6eed361c8073a09098f40e0453cdf4472cc0281 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaximumRatioDecisionRule.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMaximumRatioDecisionRule.h @@ -87,7 +87,7 @@ public: * assumed). Parameter to Evaluate() is the discriminant score in * the form of a likelihood \f$p(x|i)\f$. */ - virtual ClassIdentifierType Evaluate(const MembershipVectorType & discriminantScores) const; + virtual ClassIdentifierType Evaluate(const MembershipVectorType & discriminantScores) const ITK_OVERRIDE; /** Set the prior probabilities used in evaluating * \f$p(x|i) p(i) > p(x|j) p(j)\f$. The likelihoods are set using @@ -101,7 +101,7 @@ public: protected: MaximumRatioDecisionRule(); virtual ~MaximumRatioDecisionRule() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: MaximumRatioDecisionRule(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeanSampleFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeanSampleFilter.h index 935126f6f8b3574b07d313aa74f089cb68eeb44a..c1efc8d753fb54b6dec8cb02b03e114d46e54a7a 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeanSampleFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeanSampleFilter.h @@ -45,7 +45,7 @@ namespace Statistics */ template< typename TSample > -class MeanSampleFilter:public ProcessObject +class MeanSampleFilter : public ProcessObject { public: /**Standard class typedefs. */ @@ -59,45 +59,55 @@ public: itkTypeMacro(MeanSampleFilter, ProcessObject); itkNewMacro(Self); - /** Length of a measurement vector */ - typedef unsigned int MeasurementVectorSizeType; - typedef typename TSample::MeasurementVectorType MeasurementVectorType; - typedef typename TSample::MeasurementType MeasurementType; - typedef typename NumericTraits< MeasurementType >::RealType MeasurementRealType; + /** Type of each measurement vector in sample */ + typedef typename SampleType::MeasurementVectorType MeasurementVectorType; + + /** Type of the length of each measurement vector */ + typedef typename SampleType::MeasurementVectorSizeType MeasurementVectorSizeType; + + /** Type of measurement vector component value */ + typedef typename SampleType::MeasurementType MeasurementType; + + /** Type of a measurement vector, holding floating point values */ typedef typename NumericTraits< MeasurementVectorType >::RealType MeasurementVectorRealType; - /** Method to set/get the sample */ + /** Type of a floating point measurement component value */ + typedef typename NumericTraits< MeasurementType >::RealType MeasurementRealType; + + + /** Method to set the sample */ using Superclass::SetInput; void SetInput(const SampleType *sample); - const SampleType * GetInput() const; + /** Method to get the sample */ + const SampleType * GetInput() const; - /** MeasurementVector is not a DataObject, we need to decorate it to push it down - * a ProcessObject's pipeline */ - typedef SimpleDataObjectDecorator< MeasurementVectorRealType > MeasurementVectorDecoratedType; - - typedef MeasurementVectorDecoratedType OutputType; /** Get the mean measurement vector */ + const MeasurementVectorRealType GetMean() const; + + /** MeasurementVector is not a DataObject, we need to decorate it to push it down + * a ProcessObject's pipeline */ + typedef SimpleDataObjectDecorator< MeasurementVectorRealType > MeasurementVectorDecoratedType; const MeasurementVectorDecoratedType * GetOutput() const; + typedef MeasurementVectorDecoratedType OutputType; - const MeasurementVectorRealType GetMean() const; MeasurementVectorSizeType GetMeasurementVectorSize() const; protected: MeanSampleFilter(); virtual ~MeanSampleFilter(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** DataObject pointer */ typedef DataObject::Pointer DataObjectPointer; typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: MeanSampleFilter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeanSampleFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeanSampleFilter.hxx index b18e2ed98b785c71c403b77960e7b2fb3398c745..887437b64ad81c6e0b1a7b6a0aa73029b10fc7be 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeanSampleFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeanSampleFilter.hxx @@ -18,9 +18,12 @@ #ifndef __itkMeanSampleFilter_hxx #define __itkMeanSampleFilter_hxx -#include "itkMeasurementVectorTraits.h" #include "itkMeanSampleFilter.h" +#include <vector> +#include "itkCompensatedSummation.h" +#include "itkMeasurementVectorTraits.h" + namespace itk { namespace Statistics @@ -72,7 +75,7 @@ MeanSampleFilter< TSample > MeasurementVectorRealType mean; (void)mean; // for complainty pants : valgrind NumericTraits<MeasurementVectorRealType>::SetLength( mean, this->GetMeasurementVectorSize() ); - mean.Fill( NumericTraits< MeasurementRealType >::Zero ); + // NumericTraits::SetLength also initializes array to zero typename MeasurementVectorDecoratedType::Pointer decoratedMean = MeasurementVectorDecoratedType::New(); decoratedMean->Set( mean ); return decoratedMean.GetPointer(); @@ -127,44 +130,43 @@ void MeanSampleFilter< TSample > ::GenerateData() { + // set up input / output const SampleType *input = this->GetInput(); - MeasurementVectorSizeType measurementVectorSize = + const MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); MeasurementVectorDecoratedType *decoratedOutput = - itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >(this->ProcessObject::GetOutput(0) ); + itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(0) ); MeasurementVectorRealType output = decoratedOutput->Get(); NumericTraits<MeasurementVectorRealType>::SetLength( output, this->GetMeasurementVectorSize() ); - typename TSample::ConstIterator iter = input->Begin(); - typename TSample::ConstIterator end = input->End(); - double totalFrequency = 0.0; + // algorithm start + typedef CompensatedSummation< MeasurementRealType > MeasurementRealAccumulateType; + std::vector< MeasurementRealAccumulateType > sum( measurementVectorSize ); - typedef typename NumericTraits< - MeasurementRealType >::AccumulateType MeasurementRealAccumulateType; + typedef typename SampleType::TotalAbsoluteFrequencyType TotalFrequencyType; + TotalFrequencyType totalFrequency = NumericTraits< TotalFrequencyType >::Zero; - Array< MeasurementRealAccumulateType > sum( measurementVectorSize ); - sum.Fill( NumericTraits< MeasurementRealAccumulateType >::Zero ); + typename SampleType::ConstIterator iter = input->Begin(); + const typename SampleType::ConstIterator end = input->End(); - while ( iter != end ) + for (; iter != end; ++iter ) { - double frequency = iter.GetFrequency(); - totalFrequency += frequency; - const MeasurementVectorType & measurement = iter.GetMeasurementVector(); + const typename SampleType::AbsoluteFrequencyType frequency = iter.GetFrequency(); + totalFrequency += frequency; + for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) { const MeasurementRealType component = static_cast< MeasurementRealType >( measurement[dim] ); - sum[dim] += static_cast< MeasurementRealAccumulateType >( component * frequency ); + sum[dim] += ( component * static_cast< MeasurementRealType >( frequency ) ); } - - ++iter; } // compute the mean if the total frequency is different from zero @@ -172,7 +174,7 @@ MeanSampleFilter< TSample > { for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) { - output[dim] = static_cast< MeasurementRealType >( sum[dim] / totalFrequency ); + output[dim] = ( sum[dim].GetSum() / static_cast< MeasurementRealType >( totalFrequency ) ); } } else diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeasurementVectorTraits.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeasurementVectorTraits.h index 980520e927f7f89741734392176e9abf3c05cb5b..c05ee1b097ccd058c0695c2561d47e3532f04e85 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeasurementVectorTraits.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMeasurementVectorTraits.h @@ -72,9 +72,9 @@ public: return ( len == 0 ); } - template< typename TValueType1, unsigned int VLength, typename TValueType2, unsigned int VLength2 > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > &, - const FixedArray< TValueType2, VLength2 > &, + template< typename TValue1, unsigned int VLength, typename TValue2, unsigned int VLength2 > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > &, + const FixedArray< TValue2, VLength2 > &, const char *errMsg = "Length Mismatch") { if ( VLength != VLength2 ) @@ -84,9 +84,9 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength, typename TValueType2, unsigned int VLength2 > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > *, - const FixedArray< TValueType2, VLength2 > *, + template< typename TValue1, unsigned int VLength, typename TValue2, unsigned int VLength2 > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > *, + const FixedArray< TValue2, VLength2 > *, const char *errMsg = "Length Mismatch") { if ( VLength != VLength2 ) @@ -96,9 +96,9 @@ public: return 0; } - template< typename TValueType1, typename TValueType2 > - static MeasurementVectorLength Assert(const Array< TValueType1 > & a, - const Array< TValueType2 > & b, const char *errMsg = "Length Mismatch") + template< typename TValue1, typename TValue2 > + static MeasurementVectorLength Assert(const Array< TValue1 > & a, + const Array< TValue2 > & b, const char *errMsg = "Length Mismatch") { if ( b.Size() != a.Size() ) { @@ -107,9 +107,9 @@ public: return 0; } - template< typename TValueType1, typename TValueType2 > - static MeasurementVectorLength Assert(const Array< TValueType1 > *a, - const Array< TValueType2 > *b, const char *errMsg = "Length Mismatch") + template< typename TValue1, typename TValue2 > + static MeasurementVectorLength Assert(const Array< TValue1 > *a, + const Array< TValue2 > *b, const char *errMsg = "Length Mismatch") { if ( b->Size() != a->Size() ) { @@ -118,9 +118,9 @@ public: return 0; } - template< typename TValueType1, typename TValueType2 > - static MeasurementVectorLength Assert(const VariableLengthVector< TValueType1 > & a, - const VariableLengthVector< TValueType2 > & b, + template< typename TValue1, typename TValue2 > + static MeasurementVectorLength Assert(const VariableLengthVector< TValue1 > & a, + const VariableLengthVector< TValue2 > & b, const char *errMsg = "Length Mismatch") { if ( b.Size() != a.Size() ) @@ -130,9 +130,9 @@ public: return 0; } - template< typename TValueType1, typename TValueType2 > - static MeasurementVectorLength Assert(const VariableLengthVector< TValueType1 > *a, - const VariableLengthVector< TValueType2 > *b, + template< typename TValue1, typename TValue2 > + static MeasurementVectorLength Assert(const VariableLengthVector< TValue1 > *a, + const VariableLengthVector< TValue2 > *b, const char *errMsg = "Length Mismatch") { if ( b->Size() != a->Size() ) @@ -142,9 +142,9 @@ public: return 0; } - template< typename TValueType1, typename TValueType2 > - static MeasurementVectorLength Assert(const std::vector< TValueType1 > & a, - const std::vector< TValueType2 > & b, const char *errMsg = "Length Mismatch") + template< typename TValue1, typename TValue2 > + static MeasurementVectorLength Assert(const std::vector< TValue1 > & a, + const std::vector< TValue2 > & b, const char *errMsg = "Length Mismatch") { if ( b.size() != a.size() ) { @@ -153,9 +153,9 @@ public: return 0; } - template< typename TValueType1, typename TValueType2 > - static MeasurementVectorLength Assert(const std::vector< TValueType1 > *a, - const std::vector< TValueType2 > *b, const char *errMsg = "Length Mismatch") + template< typename TValue1, typename TValue2 > + static MeasurementVectorLength Assert(const std::vector< TValue1 > *a, + const std::vector< TValue2 > *b, const char *errMsg = "Length Mismatch") { if ( b->size() != a->size() ) { @@ -164,9 +164,9 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength, typename TValueType2 > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > &, - const Array< TValueType2 > & b, const char *errMsg = "Length Mismatch") + template< typename TValue1, unsigned int VLength, typename TValue2 > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > &, + const Array< TValue2 > & b, const char *errMsg = "Length Mismatch") { if ( b.Size() == 0 ) { @@ -182,9 +182,9 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength, typename TValueType2 > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > *, - const Array< TValueType2 > *b, const char *errMsg = "Length Mismatch") + template< typename TValue1, unsigned int VLength, typename TValue2 > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > *, + const Array< TValue2 > *b, const char *errMsg = "Length Mismatch") { if ( b->Size() == 0 ) { @@ -197,9 +197,9 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength, typename TValueType2 > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > &, - const VariableLengthVector< TValueType2 > & b, + template< typename TValue1, unsigned int VLength, typename TValue2 > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > &, + const VariableLengthVector< TValue2 > & b, const char *errMsg = "Length Mismatch") { if ( b.Size() == 0 ) @@ -216,9 +216,9 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength, typename TValueType2 > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > *, - const VariableLengthVector< TValueType2 > *b, + template< typename TValue1, unsigned int VLength, typename TValue2 > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > *, + const VariableLengthVector< TValue2 > *b, const char *errMsg = "Length Mismatch") { if ( b->Size() == 0 ) @@ -232,9 +232,9 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength, typename TValueType2 > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > &, - const std::vector< TValueType2 > & b, const char *errMsg = "Length Mismatch") + template< typename TValue1, unsigned int VLength, typename TValue2 > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > &, + const std::vector< TValue2 > & b, const char *errMsg = "Length Mismatch") { if ( b.size() == 0 ) { @@ -250,9 +250,9 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength, typename TValueType2 > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > *, - const std::vector< TValueType2 > *b, const char *errMsg = "Length Mismatch") + template< typename TValue1, unsigned int VLength, typename TValue2 > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > *, + const std::vector< TValue2 > *b, const char *errMsg = "Length Mismatch") { if ( b->size() == 0 ) { @@ -265,8 +265,8 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > &, + template< typename TValue1, unsigned int VLength > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > &, const MeasurementVectorLength l, const char *errMsg = "Length Mismatch") { if ( l == 0 ) @@ -280,8 +280,8 @@ public: return 0; } - template< typename TValueType1, unsigned int VLength > - static MeasurementVectorLength Assert(const FixedArray< TValueType1, VLength > *, + template< typename TValue1, unsigned int VLength > + static MeasurementVectorLength Assert(const FixedArray< TValue1, VLength > *, const MeasurementVectorLength l, const char *errMsg = "Length Mismatch") { if ( l == 0 ) @@ -295,8 +295,8 @@ public: return 0; } - template< typename TValueType > - static MeasurementVectorLength Assert(const Array< TValueType > & a, + template< typename TValue > + static MeasurementVectorLength Assert(const Array< TValue > & a, const MeasurementVectorLength l, const char *errMsg = "Length Mismatch") { if ( ( ( l != 0 ) && ( a.Size() != l ) ) || ( a.Size() == 0 ) ) @@ -310,8 +310,8 @@ public: return 0; } - template< typename TValueType > - static MeasurementVectorLength Assert(const Array< TValueType > *a, + template< typename TValue > + static MeasurementVectorLength Assert(const Array< TValue > *a, const MeasurementVectorLength l, const char *errMsg = "Length Mismatch") { if ( ( ( l != 0 ) && ( a->Size() != l ) ) || ( a->Size() == 0 ) ) @@ -325,8 +325,8 @@ public: return 0; } - template< typename TValueType > - static MeasurementVectorLength Assert(const VariableLengthVector< TValueType > & a, + template< typename TValue > + static MeasurementVectorLength Assert(const VariableLengthVector< TValue > & a, const MeasurementVectorLength l, const char *errMsg = "Length Mismatch") { if ( ( ( l != 0 ) && ( a.Size() != l ) ) || ( a.Size() == 0 ) ) @@ -340,8 +340,8 @@ public: return 0; } - template< typename TValueType > - static MeasurementVectorLength Assert(const VariableLengthVector< TValueType > *a, + template< typename TValue > + static MeasurementVectorLength Assert(const VariableLengthVector< TValue > *a, const MeasurementVectorLength l, const char *errMsg = "Length Mismatch") { if ( ( ( l != 0 ) && ( a->Size() != l ) ) || ( a->Size() == 0 ) ) @@ -355,8 +355,8 @@ public: return 0; } - template< typename TValueType > - static MeasurementVectorLength Assert(const std::vector< TValueType > & a, + template< typename TValue > + static MeasurementVectorLength Assert(const std::vector< TValue > & a, const MeasurementVectorLength l, const char *errMsg = "Length Mismatch") { if ( ( ( l != 0 ) && ( a.size() != l ) ) || ( a.size() == 0 ) ) @@ -370,8 +370,8 @@ public: return 0; } - template< typename TValueType > - static MeasurementVectorLength Assert(const std::vector< TValueType > *a, + template< typename TValue > + static MeasurementVectorLength Assert(const std::vector< TValue > *a, const MeasurementVectorLength l, const char *errMsg = "Length Mismatch") { if ( ( ( l != 0 ) && ( a->size() != l ) ) || ( a->size() == 0 ) ) @@ -391,8 +391,8 @@ public: m = v; } - template< typename TValueType, unsigned int VLength > - static void Assign(FixedArray< TValueType, VLength > & m, const TValueType & v) + template< typename TValue, unsigned int VLength > + static void Assign(FixedArray< TValue, VLength > & m, const TValue & v) { m[0] = v; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMembershipSample.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMembershipSample.h index 7c177012d613ea21ce847a0fa6047b1309e49c3c..08d45af05659ffa5a065a86c2f290f5125cd65ae 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMembershipSample.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMembershipSample.h @@ -112,8 +112,8 @@ public: * identifier, id. */ unsigned int GetClassLabel(const InstanceIdentifier & id) const; - /** Gets the Subsample that includes only the instances that belongs - * to the classLabel */ + /** Gets the Subsample that includes only the instances that belong + * to the classLabel. If classLabel does not exist, NULL is returned. */ const ClassSampleType * GetClassSample(const ClassLabelType & classLabel) const; /** Gets the class labels that corresponding to the each instance in @@ -136,7 +136,7 @@ public: TotalAbsoluteFrequencyType GetTotalFrequency() const; /** Method to graft another sample */ - virtual void Graft(const DataObject *thatObject); + virtual void Graft(const DataObject *thatObject) ITK_OVERRIDE; // void PrintSelf(std::ostream& os, Indent indent) const; @@ -288,7 +288,7 @@ private: protected: MembershipSample(); virtual ~MembershipSample() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: MembershipSample(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMembershipSample.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMembershipSample.hxx index 0f00a5eed91d5a111dfd45f8f0a8b16877e30547..320caca7263ca924b334d8ba374ea2c039313941 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMembershipSample.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMembershipSample.hxx @@ -99,6 +99,10 @@ MembershipSample< TSample > ::GetClassSample(const ClassLabelType & classLabel) const { int classIndex = this->GetInternalClassLabel(classLabel); + if (classIndex < 0) + { + return NULL; + } return m_ClassSamples[classIndex]; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMinimumDecisionRule.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMinimumDecisionRule.h index 87fd65db67cfdcb161133c725669a5a7f03f265c..7bf5f6f12c9e54663ac55bd273ba8be4d8612006 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMinimumDecisionRule.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMinimumDecisionRule.h @@ -60,7 +60,7 @@ public: * Evaluate the decision rule, returning the class label associated * with the smallest discriminant score. */ - virtual ClassIdentifierType Evaluate(const MembershipVectorType & discriminantScores) const; + virtual ClassIdentifierType Evaluate(const MembershipVectorType & discriminantScores) const ITK_OVERRIDE; protected: MinimumDecisionRule() {} diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMixtureModelComponentBase.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMixtureModelComponentBase.h index c6b2213b7194b8dd7b15019e3708728d9ca06290..5e1c21d76e0507b57a8126faafc66a9ecc613659 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMixtureModelComponentBase.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMixtureModelComponentBase.h @@ -131,7 +131,7 @@ public: protected: MixtureModelComponentBase(); virtual ~MixtureModelComponentBase(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** stores the pointer to the membership function. * subclasses use this function to store their membership function diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMixtureModelComponentBase.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMixtureModelComponentBase.hxx index eeffa35e4f1c3f82fa79d8aaa71d7faffff8a418..16e652f877747ee89dae79d13e7bbf6ae7f75caa 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkMixtureModelComponentBase.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkMixtureModelComponentBase.hxx @@ -28,8 +28,8 @@ template< typename TSample > MixtureModelComponentBase< TSample > ::MixtureModelComponentBase() { - m_Sample = 0; - m_MembershipFunction = 0; + m_Sample = ITK_NULLPTR; + m_MembershipFunction = ITK_NULLPTR; m_MinimalParametersChange = 1.0e-06; m_ParametersModified = true; } @@ -47,7 +47,7 @@ MixtureModelComponentBase< TSample > Superclass::PrintSelf(os, indent); os << indent << "Sample: "; - if ( m_Sample != 0 ) + if ( m_Sample != ITK_NULLPTR ) { os << m_Sample << std::endl; } @@ -57,7 +57,7 @@ MixtureModelComponentBase< TSample > } os << indent << "Membership Function: "; - if ( m_MembershipFunction != 0 ) + if ( m_MembershipFunction != ITK_NULLPTR ) { os << m_MembershipFunction << std::endl; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkNeighborhoodSampler.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkNeighborhoodSampler.hxx index a7065c89563b31507be8ff0604c11a493760a279..b6e40ab4ffa6572d656bd8f5ab077beb0990abd8 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkNeighborhoodSampler.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkNeighborhoodSampler.hxx @@ -49,7 +49,7 @@ NeighborhoodSampler< TSample > const InputRadiusObjectType *radiusObject = this->GetRadiusInput(); - if ( radiusObject == NULL ) + if ( radiusObject == ITK_NULLPTR ) { itkExceptionMacro("Radius input is missing"); } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkNormalVariateGenerator.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkNormalVariateGenerator.h index d59e6cd5b05bb47ef778b50094cfacf62aeb1385..5e8c41feff5125e421d3992aed961c1c58406972 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkNormalVariateGenerator.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkNormalVariateGenerator.h @@ -115,12 +115,12 @@ public: void Initialize(int randomSeed); /** get a variate using FastNorm function */ - double GetVariate(); + virtual double GetVariate() ITK_OVERRIDE; protected: NormalVariateGenerator(); virtual ~NormalVariateGenerator(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** get a variate */ double FastNorm(void); diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkPointSetToListSampleAdaptor.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkPointSetToListSampleAdaptor.hxx index fe1e5c08c64cc0037d8a55f683174e0ea48a5869..910a1b064ab9e6802719468830aee2a83a92955a 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkPointSetToListSampleAdaptor.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkPointSetToListSampleAdaptor.hxx @@ -28,7 +28,7 @@ template< typename TPointSet > PointSetToListSampleAdaptor< TPointSet > ::PointSetToListSampleAdaptor() { - this->m_PointSet = 0; + this->m_PointSet = ITK_NULLPTR; this->SetMeasurementVectorSize( TPointSet::PointDimension ); } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkProbabilityDistribution.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkProbabilityDistribution.h index d0383af0cc25914f447b9104d7639e92c896011e..96a3e4a8b5f3631ed9747683312f39266edf7774 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkProbabilityDistribution.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkProbabilityDistribution.h @@ -155,7 +155,7 @@ public: protected: ProbabilityDistribution(void) {} virtual ~ProbabilityDistribution(void) {} - void PrintSelf(std::ostream & os, Indent indent) const + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE { Superclass::PrintSelf(os, indent); os << indent << "Parameters: " << m_Parameters << std::endl; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSample.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSample.h index a0762722995fa496d8e84647a5ffdcf5759aa009..93b74a29986f1852b7fcece0993deba3bb8c9f45 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSample.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSample.h @@ -88,7 +88,7 @@ public: * sequential id for each measurement vector in a Sample subclass. */ typedef typename MeasurementVectorTraits::InstanceIdentifier InstanceIdentifier; - /** Typedef for the length of each measurement vector */ + /** Type of the length of each measurement vector */ typedef unsigned int MeasurementVectorSizeType; /** Get the size of the sample (number of measurements) */ @@ -158,7 +158,7 @@ public: itkGetConstMacro(MeasurementVectorSize, MeasurementVectorSizeType); /** Method to graft another sample */ - virtual void Graft(const DataObject *thatObject) + virtual void Graft(const DataObject *thatObject) ITK_OVERRIDE { this->Superclass::Graft(thatObject); @@ -178,7 +178,7 @@ protected: virtual ~Sample() {} - void PrintSelf(std::ostream & os, Indent indent) const + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE { Superclass::PrintSelf(os, indent); os << indent << "Length of measurement vectors in the sample: " diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleClassifierFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleClassifierFilter.h index 1eeeb89bfa2ebeb7410f3d7c5dff0b0babb8b5fa..734eb7fd2f1742aec8cc6a04f47c153336c42add 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleClassifierFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleClassifierFilter.h @@ -128,13 +128,13 @@ public: protected: SampleClassifierFilter(); virtual ~SampleClassifierFilter() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; SampleClassifierFilter(const Self &); //purposely not implemented void operator=(const Self &); //purposely not implemented /** Starts the classification process */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Make a DataObject of the correct type to used as the specified * output. This method @@ -144,7 +144,7 @@ protected: */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleClassifierFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleClassifierFilter.hxx index d25aa19882f745cdd32367cdb9a82b6507c94fb8..cdc92bb42c8102efa82436260fa9434f0c903c0e 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleClassifierFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleClassifierFilter.hxx @@ -36,7 +36,7 @@ SampleClassifierFilter< TSample > this->ProcessObject::SetNthOutput( 0, this->MakeOutput(0) ); /** Initialize decision rule */ - m_DecisionRule = NULL; + m_DecisionRule = ITK_NULLPTR; } template< typename TSample > @@ -146,7 +146,7 @@ SampleClassifierFilter< TSample > } MembershipFunctionsWeightsArrayType membershipFunctionsWeightsArray; - if ( membershipFunctionsWeightsArrayDecorated == NULL ) + if ( membershipFunctionsWeightsArrayDecorated == ITK_NULLPTR ) { // no weights array is set and hence all membership functions will have // equal diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToHistogramFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToHistogramFilter.h index f5e2e5fb91c912dd0057551eac0a09e4ea3dba06..4d9ec37b00547b75f2eb6a4ee3f0028d3ad3730a 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToHistogramFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToHistogramFilter.h @@ -136,7 +136,7 @@ protected: SampleToHistogramFilter(); virtual ~SampleToHistogramFilter(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Make a DataObject of the correct type to used as the specified * output. This method @@ -146,10 +146,10 @@ protected: */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; // Where the histogram is actually computed - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: SampleToHistogramFilter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToHistogramFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToHistogramFilter.hxx index 7c9f72fa2ecc35bfea8c49dfb120e1a1f5380e5e..ef1241c763af31f51fd3abc243a17f3cd152f110 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToHistogramFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToHistogramFilter.hxx @@ -143,12 +143,12 @@ SampleToHistogramFilter< TSample, THistogram > const InputHistogramSizeObjectType *histogramSizeObject = this->GetHistogramSizeInput(); - if ( histogramSizeObject == NULL ) + if ( histogramSizeObject == ITK_NULLPTR ) { itkSpecializedExceptionMacro(MissingHistogramSizeInput); } - if ( marginalScaleObject == NULL ) + if ( marginalScaleObject == ITK_NULLPTR ) { itkSpecializedExceptionMacro(MissingHistogramMarginalScaleInput); } @@ -274,12 +274,12 @@ SampleToHistogramFilter< TSample, THistogram > } else { - if ( binMaximumObject == NULL ) + if ( binMaximumObject == ITK_NULLPTR ) { itkSpecializedExceptionMacro(MissingHistogramBinMaximumInput); } - if ( binMinimumObject == NULL ) + if ( binMinimumObject == ITK_NULLPTR ) { itkSpecializedExceptionMacro(MissingHistogramBinMinimumInput); } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToSubsampleFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToSubsampleFilter.h index 102a068e03ee2b209c151ddcc2e0c5481aacd2e9..8a674944eb6459ba61474b017cd50903927d2efe 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToSubsampleFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSampleToSubsampleFilter.h @@ -78,7 +78,7 @@ public: protected: SampleToSubsampleFilter(); virtual ~SampleToSubsampleFilter(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Make a DataObject of the correct type to used as the specified * output. This method @@ -88,7 +88,7 @@ protected: */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; private: SampleToSubsampleFilter(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceListSampleFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceListSampleFilter.h index 79f28c502b7f7d5d39cebc6bcd4771a071a8756c..f2c6005d03ccee2eb39ba5f8438eeb2d500534f8 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceListSampleFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceListSampleFilter.h @@ -102,15 +102,15 @@ public: protected: ScalarImageToCooccurrenceListSampleFilter(); virtual ~ScalarImageToCooccurrenceListSampleFilter() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; typedef DataObject::Pointer DataObjectPointer; typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** This method causes the filter to generate its output. */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: ScalarImageToCooccurrenceListSampleFilter(const Self &); //purposely not diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceMatrixFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceMatrixFilter.h index 4ef9744a4609db5c7cfaebe084f7c67d75d91193..1f8a0db37317749846143a439941dd609b4de493 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceMatrixFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceMatrixFilter.h @@ -172,7 +172,7 @@ public: protected: ScalarImageToCooccurrenceMatrixFilter(); virtual ~ScalarImageToCooccurrenceMatrixFilter() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; virtual void FillHistogram(RadiusType radius, RegionType region); @@ -183,10 +183,10 @@ protected: typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** This method causes the filter to generate its output. */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: ScalarImageToCooccurrenceMatrixFilter(const Self &); //purposely not diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceMatrixFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceMatrixFilter.hxx index 04843570d384ef8b6c0b2a8459b7d2e25f2d38fe..bf75ead85ff2e868900edfa518e713f35b905354 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceMatrixFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToCooccurrenceMatrixFilter.hxx @@ -173,7 +173,7 @@ ScalarImageToCooccurrenceMatrixFilter< TImageType, RadiusType radius; radius.Fill(minRadius); - const ImageType *maskImage = NULL; + const ImageType *maskImage = ITK_NULLPTR; // Check if a mask image has been provided // @@ -183,7 +183,7 @@ ScalarImageToCooccurrenceMatrixFilter< TImageType, } // Now fill in the histogram - if ( maskImage != NULL ) + if ( maskImage != ITK_NULLPTR ) { this->FillHistogramWithMask(radius, input->GetRequestedRegion(), maskImage); } @@ -230,6 +230,7 @@ ScalarImageToCooccurrenceMatrixFilter< TImageType, } typename OffsetVector::ConstIterator offsets; + typename HistogramType::IndexType index; for ( offsets = m_Offsets->Begin(); offsets != m_Offsets->End(); offsets++ ) { bool pixelInBounds; @@ -253,11 +254,13 @@ ScalarImageToCooccurrenceMatrixFilter< TImageType, cooccur[0] = centerPixelIntensity; cooccur[1] = pixelIntensity; - output->IncreaseFrequencyOfMeasurement(cooccur, 1); + output->GetIndex( cooccur, index ); + output->IncreaseFrequencyOfIndex( index, 1 ); cooccur[1] = centerPixelIntensity; cooccur[0] = pixelIntensity; - output->IncreaseFrequencyOfMeasurement(cooccur, 1); + output->GetIndex( cooccur, index ); + output->IncreaseFrequencyOfIndex( index, 1 ); } } } @@ -285,7 +288,7 @@ ScalarImageToCooccurrenceMatrixFilter< TImageType, maskNeighborIt = NeighborhoodIteratorType(radius, maskImage, region); MeasurementVectorType cooccur( output->GetMeasurementVectorSize() ); - + typename HistogramType::IndexType index; for ( neighborIt.GoToBegin(), maskNeighborIt.GoToBegin(); !neighborIt.IsAtEnd(); ++neighborIt, ++maskNeighborIt ) { @@ -332,11 +335,14 @@ ScalarImageToCooccurrenceMatrixFilter< TImageType, cooccur[0] = centerPixelIntensity; cooccur[1] = pixelIntensity; - output->IncreaseFrequencyOfMeasurement(cooccur, 1); + output->GetIndex( cooccur, index ); + output->IncreaseFrequencyOfIndex(index, 1); + cooccur[1] = centerPixelIntensity; cooccur[0] = pixelIntensity; - output->IncreaseFrequencyOfMeasurement(cooccur, 1); + output->GetIndex( cooccur, index ); + output->IncreaseFrequencyOfIndex(index, 1); } } } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToHistogramGenerator.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToHistogramGenerator.h index 66d311fff9ef364e28de4fe22961924ba9f0a6dd..1f5c76824fee162427e8480b5b0d6476a4269b7d 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToHistogramGenerator.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToHistogramGenerator.h @@ -91,7 +91,7 @@ public: protected: ScalarImageToHistogramGenerator(); virtual ~ScalarImageToHistogramGenerator() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthFeaturesFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthFeaturesFilter.h index 863aede45d21e39433c80ce1710acdeb4216d940..fb5ee0be2071b640ca05603a6dcce99f6baf6cdf 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthFeaturesFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthFeaturesFilter.h @@ -196,19 +196,19 @@ public: protected: ScalarImageToRunLengthFeaturesFilter(); virtual ~ScalarImageToRunLengthFeaturesFilter() {} - void PrintSelf( std::ostream & os, Indent indent ) const; + virtual void PrintSelf( std::ostream & os, Indent indent ) const ITK_OVERRIDE; void FastCompute(); void FullCompute(); /** This method causes the filter to generate its output. */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Make a DataObject to be used for output output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType) ITK_OVERRIDE; private: typename RunLengthMatrixFilterType::Pointer m_RunLengthMatrixGenerator; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthFeaturesFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthFeaturesFilter.hxx index 6df0a8cbecbfd7c7d6ea0671af4a52a189fa354b..51d127ec5c46b5855c720133a9ea53d08514e46c 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthFeaturesFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthFeaturesFilter.hxx @@ -168,7 +168,7 @@ ScalarImageToRunLengthFeaturesFilter<TImage, THistogramFrequencyContainer> M(1) = x(1), M(k) = M(k-1) + (x(k) - M(k-1) ) / k S(1) = 0, S(k) = S(k-1) + (x(k) - M(k-1)) * (x(k) - M(k)) for 2 <= k <= n, then - sigma = vcl_sqrt(S(n) / n) (or divide by n-1 for sample SD instead of + sigma = std::sqrt(S(n) / n) (or divide by n-1 for sample SD instead of population SD). */ @@ -197,7 +197,7 @@ ScalarImageToRunLengthFeaturesFilter<TImage, THistogramFrequencyContainer> } for( featureNum = 0; featureNum < numFeatures; featureNum++ ) { - tempFeatureDevs[featureNum] = vcl_sqrt( tempFeatureDevs[featureNum] / + tempFeatureDevs[featureNum] = std::sqrt( tempFeatureDevs[featureNum] / numOffsets ); this->m_FeatureMeans->push_back( tempFeatureMeans[featureNum] ); @@ -320,7 +320,7 @@ ScalarImageToRunLengthFeaturesFilter<TImage, THistogramFrequencyContainer> { if ( this->GetNumberOfInputs() < 1 ) { - return 0; + return ITK_NULLPTR; } return static_cast<const ImageType *>( this->ProcessObject::GetInput( 0 ) ); } @@ -354,7 +354,7 @@ ScalarImageToRunLengthFeaturesFilter<TImage, THistogramFrequencyContainer> { if ( this->GetNumberOfInputs() < 2 ) { - return 0; + return ITK_NULLPTR; } return static_cast< const ImageType *>( this->ProcessObject::GetInput( 1 ) ); } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.h index 88151c8d20d599e8f560914065df038d295ec242..4e646b3c8618860317c36ae7385d1ceeeff59910 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.h @@ -233,17 +233,17 @@ public: protected: ScalarImageToRunLengthMatrixFilter(); virtual ~ScalarImageToRunLengthMatrixFilter() {}; - void PrintSelf( std::ostream& os, Indent indent ) const; + virtual void PrintSelf( std::ostream& os, Indent indent ) const ITK_OVERRIDE; /** Standard itk::ProcessObject subclass method. */ typedef DataObject::Pointer DataObjectPointer; typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput( DataObjectPointerArraySizeType idx ); + virtual DataObjectPointer MakeOutput( DataObjectPointerArraySizeType idx ) ITK_OVERRIDE; /** This method causes the filter to generate its output. */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** * Normalize the direction of the offset before it is applied. diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.hxx index 00e0af40c6676c625cf0cbad72ded37b6d5cbb16..ae29ccf30cc00727b90aaaa298755ca2bac22f52 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToRunLengthMatrixFilter.hxx @@ -93,7 +93,7 @@ ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer> { if( this->GetNumberOfInputs() < 1 ) { - return 0; + return ITK_NULLPTR; } return static_cast<const ImageType *>( this->ProcessObject::GetInput( 0 ) ); } @@ -105,7 +105,7 @@ ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer> { if( this->GetNumberOfInputs() < 2 ) { - return 0; + return ITK_NULLPTR; } return static_cast<const ImageType *>( this->ProcessObject::GetInput( 1 ) ); } @@ -153,6 +153,7 @@ ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer> output->Initialize( size, this->m_LowerBound, this->m_UpperBound ); MeasurementVectorType run( output->GetMeasurementVectorSize() ); + typename HistogramType::IndexType hIndex; // Iterate over all of those pixels and offsets, adding each // distance/intensity pair to the histogram @@ -270,7 +271,8 @@ ScalarImageToRunLengthMatrixFilter<TImageType, THistogramFrequencyContainer> if( run[1] >= this->m_MinDistance && run[1] <= this->m_MaxDistance ) { - output->IncreaseFrequencyOfMeasurement( run, 1 ); + output->GetIndex( run, hIndex ); + output->IncreaseFrequencyOfIndex( hIndex, 1 ); itkDebugStatement(typename HistogramType::IndexType tempMeasurementIndex;) itkDebugStatement(output->GetIndex(run,tempMeasurementIndex);) diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToTextureFeaturesFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToTextureFeaturesFilter.h index ee9c2f29c9fab1bc23d1e1af7bdabe148dddaf62..fc1d321e43a8da738a3b284f60a33e5fcbef6deb 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToTextureFeaturesFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToTextureFeaturesFilter.h @@ -198,19 +198,19 @@ public: protected: ScalarImageToTextureFeaturesFilter(); virtual ~ScalarImageToTextureFeaturesFilter() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void FastCompute(); void FullCompute(); /** This method causes the filter to generate its output. */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Make a DataObject to be used for output output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType) ITK_OVERRIDE; private: typename CooccurrenceMatrixFilterType::Pointer m_GLCMGenerator; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToTextureFeaturesFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToTextureFeaturesFilter.hxx index 4cafebc7dceb1cf163e48bce94a7f89bf8feeb48..7304a82564c608fa3d37f8da88cfe11298bc4c31 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToTextureFeaturesFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkScalarImageToTextureFeaturesFilter.hxx @@ -145,7 +145,7 @@ ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >::Full M(1) = x(1), M(k) = M(k-1) + (x(k) - M(k-1) ) / k S(1) = 0, S(k) = S(k-1) + (x(k) - M(k-1)) * (x(k) - M(k)) for 2 <= k <= n, then - sigma = vcl_sqrt(S(n) / n) (or divide by n-1 for sample SD instead of + sigma = std::sqrt(S(n) / n) (or divide by n-1 for sample SD instead of population SD). */ @@ -174,7 +174,7 @@ ScalarImageToTextureFeaturesFilter< TImage, THistogramFrequencyContainer >::Full } for ( featureNum = 0; featureNum < numFeatures; featureNum++ ) { - tempFeatureDevs[featureNum] = vcl_sqrt(tempFeatureDevs[featureNum] / numOffsets); + tempFeatureDevs[featureNum] = std::sqrt(tempFeatureDevs[featureNum] / numOffsets); m_FeatureMeans->push_back(tempFeatureMeans[featureNum]); m_FeatureStandardDeviations->push_back(tempFeatureDevs[featureNum]); diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSparseFrequencyContainer2.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSparseFrequencyContainer2.h index 108cc1037dc65d4e08fa3b017ae93af038d06654..3f685c5f242314e2132f840f69ebf54c5248c186 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSparseFrequencyContainer2.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSparseFrequencyContainer2.h @@ -98,7 +98,7 @@ public: protected: SparseFrequencyContainer2(); virtual ~SparseFrequencyContainer2() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: SparseFrequencyContainer2(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.h index d6ff9c7b5b092a9f91e670ebac54834917bb1b56..a3af83d62931205655da96e0ea09a4e3bfa83038 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.h @@ -98,16 +98,16 @@ protected: StandardDeviationPerComponentSampleFilter(); virtual ~StandardDeviationPerComponentSampleFilter(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** DataObject pointer */ typedef DataObject::Pointer DataObjectPointer; typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; MeasurementVectorSizeType GetMeasurementVectorSize() const; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.hxx index b0cd43cc2fbdba36cc599441441a6b7fc6695ec2..6b0f0141aa2b80427648f6832a8b35880c9635d1 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.hxx @@ -195,7 +195,7 @@ StandardDeviationPerComponentSampleFilter< TSample > mean[i] = meanValue; const double variance = ( sumOfSquares[i] - meanValue * meanValue * totalFrequency ) / ( totalFrequency - 1.0 ); - standardDeviation[i] = vcl_sqrt(variance); + standardDeviation[i] = std::sqrt(variance); } decoratedStandardDeviationOutput->Set(standardDeviation); diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkStatisticsAlgorithm.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkStatisticsAlgorithm.h index 88d756b80916949a37a1465e53f0d79f2bb3488d..2a43fff7b3b66fe4aec77e80727da194eb94ce8e 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkStatisticsAlgorithm.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkStatisticsAlgorithm.h @@ -34,13 +34,29 @@ TSize FloorLog(TSize size); template< typename TValue > TValue MedianOfThree(const TValue a, const TValue b, const TValue c); +/** Finds the minimum and maximum of each measurement value, over an interval + * within a sample. + * + * Samples are considered independently of each other. + * + * \param[in] sample An instance of TSample. + * \param[in] begin An iterator to the first measurement vector in sample to be + * considered. + * \param[in] end An iterator to the last measurement vector in sample to be + * considered. + * \param[out] min A new measurement vector, with the minimum values. + * \param[out] max A new measurement vector, with the maximum values. + * + * \tparam TSample A subtype of Statistics::Sample. + */ template< typename TSample > void FindSampleBound(const TSample * sample, - typename TSample::ConstIterator begin, - typename TSample::ConstIterator end, + const typename TSample::ConstIterator & begin, + const typename TSample::ConstIterator & end, typename TSample::MeasurementVectorType & min, typename TSample::MeasurementVectorType & max); +/** The endIndex should points one point after the last elements. */ template< typename TSubsample > void FindSampleBoundAndMean(const TSubsample * sample, int beginIndex, @@ -49,9 +65,10 @@ void FindSampleBoundAndMean(const TSubsample * sample, typename TSubsample::MeasurementVectorType & max, typename TSubsample::MeasurementVectorType & mean); -/** The Partition algorithm performs partial sorting in a sample. Given a - * partitionValue, the algorithm moves to the beginning of the sample all - * MeasurementVectors whose component activeDimension is smaller than the +/** The Partition algorithm performs partial sorting in a sample. + * + * Given a partitionValue, the algorithm moves to the beginning of the sample + * all MeasurementVectors whose component activeDimension is smaller than the * partitionValue. In this way, the sample is partially sorted in two groups. * First the group with activeDimension component smaller than the * partitionValue, then the group of MeasurementVectors with activeDimension @@ -60,7 +77,15 @@ void FindSampleBoundAndMean(const TSubsample * sample, * Only the activeDimension components of the MeasurementVectors in the sample * will be considered by the algorithm. The Algorithm return an index in the * range of [beginIndex,endIndex] pointing to the element with activeDimension - * component closest to the partitionValue. */ + * component closest to the partitionValue. + * + * The endIndex should points one point after the last elements if multiple + * partitionValue exist in the sample the return index will points the middle + * of such values. Implemented following the description of the partition + * algorithm in the QuickSelect entry of the Wikipedia. + * + * \sa http://en.wikipedia.org/wiki/Selection_algorithm. + */ template< typename TSubsample > int Partition(TSubsample *sample, unsigned int activeDimension, @@ -68,13 +93,22 @@ int Partition(TSubsample *sample, const typename TSubsample::MeasurementType partitionValue); /** QuickSelect is an algorithm for finding the k-th largest element of a list. + * * In this case, only one of the components of the measurement vectors is * considered. This component is defined by the argument activeDimension. The * search is rectricted to the range between the index begin and end, also - * passed as arguments. In this version, a guess value for the median index is - * provided in the argument medianGuess. The algorithm returns the value of the - * activeDimension component in the MeasurementVector located in the kth position. - * http://en.wikipedia.org/wiki/Selection_algorithm */ + * passed as arguments. + * + * The endIndex should point one point after the last elements. Note that kth + * is an index in a different scale than [beginIndex,endIndex]. For example, + * it is possible to feed this function with beginIndex=15, endIndex=23, and + * kth=3, since we can ask for the element 3rd in the range [15,23]. + * In this version, a guess value for the median index is provided in the + * argument medianGuess. The algorithm returns the value of the activeDimension + * component in the MeasurementVector located in the kth position. + * + * \sa http://en.wikipedia.org/wiki/Selection_algorithm + */ template< typename TSubsample > typename TSubsample::MeasurementType QuickSelect(TSubsample * sample, @@ -84,11 +118,19 @@ QuickSelect(TSubsample * sample, typename TSubsample::MeasurementType medianGuess); /** QuickSelect is an algorithm for finding the k-th largest element of a list. + * * In this case, only one of the components of the measurement vectors is * considered. This component is defined by the argument activeDimension. The * search is rectricted to the range between the index begin and end, also * passed as arguments. - * http://en.wikipedia.org/wiki/Selection_algorithm. */ + * + * The endIndex should point one point after the last elements. Note that kth + * is an index in a different scale than [beginIndex,endIndex]. For example, + * it is possible to feed this function with beginIndex=15, endIndex=23, and + * kth=3, since we can ask for the element 3rd in the range [15,23]. + * + * \sa http://en.wikipedia.org/wiki/Selection_algorithm. + */ template< typename TSubsample > typename TSubsample::MeasurementType QuickSelect(TSubsample *sample, @@ -97,11 +139,13 @@ QuickSelect(TSubsample *sample, int kth); /** NthElement is an algorithm for finding the n-th largest element of a list. + * * In this case, only one of the components of the measurement vectors is * considered. This component is defined by the argument activeDimension. The * search is restricted to the range between the index begin and end, also * passed as arguments. This algorithm was based on the procedure used in the STL - * nth_element method. */ + * nth_element method. + */ template< typename TSubsample > typename TSubsample::MeasurementType NthElement(TSubsample *sample, diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkStatisticsAlgorithm.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkStatisticsAlgorithm.hxx index cfdcd866edf9e96495c6888715fb03e0258418c8..ca47e6a454e712b7cd2a8e618255e1b2595ae1c2 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkStatisticsAlgorithm.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkStatisticsAlgorithm.hxx @@ -40,11 +40,6 @@ inline TSize FloorLog(TSize size) return k; } -/** The endIndex should points one point after the last elements if multiple - * partitionValue exist in the sample the return index will points the middle - * of such values. Implemented following the description of the partition - * algorithm in the QuickSelect entry of the Wikipedia. - * http://en.wikipedia.org/wiki/Selection_algorithm. */ template< typename TSubsample > inline int Partition(TSubsample *sample, unsigned int activeDimension, @@ -245,23 +240,23 @@ inline TValue MedianOfThree(const TValue a, template< typename TSample > inline void FindSampleBound(const TSample *sample, - typename TSample::ConstIterator begin, - typename TSample::ConstIterator end, + const typename TSample::ConstIterator & begin, + const typename TSample::ConstIterator & end, typename TSample::MeasurementVectorType & min, typename TSample::MeasurementVectorType & max) { typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; - const MeasurementVectorSizeType Dimension = sample->GetMeasurementVectorSize(); - if ( Dimension == 0 ) + const MeasurementVectorSizeType measurementSize = sample->GetMeasurementVectorSize(); + if ( measurementSize == 0 ) { itkGenericExceptionMacro( << "Length of a sample's measurement vector hasn't been set."); } // Sanity check - MeasurementVectorTraits::Assert(max, Dimension, + MeasurementVectorTraits::Assert(max, measurementSize, "Length mismatch StatisticsAlgorithm::FindSampleBound"); - MeasurementVectorTraits::Assert(min, Dimension, + MeasurementVectorTraits::Assert(min, measurementSize, "Length mismatch StatisticsAlgorithm::FindSampleBound"); if ( sample->Size() == 0 ) @@ -271,33 +266,31 @@ inline void FindSampleBound(const TSample *sample, measurement vectors"); } - unsigned int dimension; - typename TSample::MeasurementVectorType temp; + min = begin.GetMeasurementVector(); + max = min; - min = max = temp = begin.GetMeasurementVector(); - while ( true ) + typename TSample::ConstIterator measurementItr = begin; + // increment measurementItr once, since min and max are already set to the 0th measurement + ++measurementItr; + for(; measurementItr != end; ++measurementItr ) { - for ( dimension = 0; dimension < Dimension; dimension++ ) + const typename TSample::MeasurementVectorType & currentMeasure = + measurementItr.GetMeasurementVector(); + + for ( MeasurementVectorSizeType dimension = 0; dimension < measurementSize; ++dimension ) { - if ( temp[dimension] < min[dimension] ) + if ( currentMeasure[dimension] < min[dimension] ) { - min[dimension] = temp[dimension]; + min[dimension] = currentMeasure[dimension]; } - else if ( temp[dimension] > max[dimension] ) + else if ( currentMeasure[dimension] > max[dimension] ) { - max[dimension] = temp[dimension]; + max[dimension] = currentMeasure[dimension]; } } - ++begin; - if ( begin == end ) - { - break; - } - temp = begin.GetMeasurementVector(); - } // end of while + } } -/** The endIndex should points one point after the last elements. */ template< typename TSubsample > inline void FindSampleBoundAndMean(const TSubsample *sample, @@ -358,11 +351,6 @@ FindSampleBoundAndMean(const TSubsample *sample, } } -/** The endIndex should point one point after the last elements. Note that kth - * is an index in a different scale than [beginIndex,endIndex]. For example, - * it is possible to feed this function with beginIndex=15, endIndex=23, and - * kth=3, since we can ask for the element 3rd in the range [15,23]. */ - template< typename TSubsample > inline typename TSubsample::MeasurementType QuickSelect(TSubsample *sample, diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsample.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsample.hxx index aa40075c85acf7acdb5ac1f3ae3fd567290bd8d9..c293b76e06584699b6d90278e6b2070948244916 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsample.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsample.hxx @@ -30,7 +30,7 @@ template< typename TSample > Subsample< TSample > ::Subsample() { - m_Sample = 0; + m_Sample = ITK_NULLPTR; m_TotalFrequency = NumericTraits< AbsoluteFrequencyType >::Zero; m_ActiveDimension = 0; } @@ -43,7 +43,7 @@ Subsample< TSample > Superclass::PrintSelf(os, indent); os << indent << "Sample: "; - if ( m_Sample != 0 ) + if ( m_Sample != ITK_NULLPTR ) { os << m_Sample << std::endl; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsamplerBase.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsamplerBase.h index 086e745e16b4eb13f7004a718c43a59ed69d45aa..0527439ec3a92b5f842f72ff351588f12ee9684b 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsamplerBase.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsamplerBase.h @@ -114,12 +114,12 @@ protected: * This does a complete copy of the subsampler state * to the new subsampler */ - virtual typename LightObject::Pointer InternalClone() const; + virtual typename LightObject::Pointer InternalClone() const ITK_OVERRIDE; SubsamplerBase(); virtual ~SubsamplerBase() {}; - virtual void PrintSelf(std::ostream& os, Indent indent) const; + virtual void PrintSelf(std::ostream& os, Indent indent) const ITK_OVERRIDE; SampleConstPointer m_Sample; bool m_RequestMaximumNumberOfResults; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsamplerBase.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsamplerBase.hxx index 96a96940abd41b485139010712efe18d76e8bd4f..c6e2a302df2f1394ab230887792ad610ba43cbc1 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsamplerBase.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkSubsamplerBase.hxx @@ -26,7 +26,7 @@ template <typename TSample> SubsamplerBase<TSample> ::SubsamplerBase() { - m_Sample = NULL; + m_Sample = ITK_NULLPTR; m_RequestMaximumNumberOfResults = true; m_CanSelectQuery = true; m_Seed = 0; diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkTDistribution.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkTDistribution.h index 619fefd27f402714ebd2a90dc15dd55084999715..9c4388d6683765b0a935f50bf7587547728193e6 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkTDistribution.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkTDistribution.h @@ -72,16 +72,16 @@ public: /** Return the number of parameters. For a univariate Student-t * distribution, the number of parameters is 1 (degrees of freedom) */ - virtual SizeValueType GetNumberOfParameters() const { return 1; } + virtual SizeValueType GetNumberOfParameters() const ITK_OVERRIDE { return 1; } /** Evaluate the probability density function (pdf). The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluatePDF(double x) const; + virtual double EvaluatePDF(double x) const ITK_OVERRIDE; /** Evaluate the probability density function (pdf). The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (degrees of freedom). */ - virtual double EvaluatePDF(double x, const ParametersType &) const; + virtual double EvaluatePDF(double x, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the probability density function (pdf). The parameters * of the distribution are passed as separate parameters. */ @@ -89,12 +89,12 @@ public: /** Evaluate the cumulative distribution function (cdf). The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluateCDF(double x) const; + virtual double EvaluateCDF(double x) const ITK_OVERRIDE; /** Evaluate the cumulative distribution function (cdf). The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (degreesOfFreedom). */ - virtual double EvaluateCDF(double x, const ParametersType &) const; + virtual double EvaluateCDF(double x, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the cumulative distribution function (cdf). The parameters * of the distribution are passed as separate parameters. */ @@ -103,13 +103,13 @@ public: /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters * of the distribution are assigned via SetParameters(). */ - virtual double EvaluateInverseCDF(double p) const; + virtual double EvaluateInverseCDF(double p) const ITK_OVERRIDE; /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters * for the distribution are passed as a parameters vector. The * ordering of the parameters is (degrees of freedom). */ - virtual double EvaluateInverseCDF(double p, const ParametersType &) const; + virtual double EvaluateInverseCDF(double p, const ParametersType &) const ITK_OVERRIDE; /** Evaluate the inverse cumulative distribution function (inverse * cdf). Parameter p must be between 0.0 and 1.0. The parameters @@ -125,18 +125,18 @@ public: virtual SizeValueType GetDegreesOfFreedom() const; /** Does the Student-t distribution have a mean? */ - virtual bool HasMean() const { return true; } + virtual bool HasMean() const ITK_OVERRIDE { return true; } /** Get the mean of the distribution. */ - virtual double GetMean() const; + virtual double GetMean() const ITK_OVERRIDE; /** Does the Student-t distribution have a variance? Variance is * only defined for degrees of freedom greater than 2 */ - virtual bool HasVariance() const; + virtual bool HasVariance() const ITK_OVERRIDE; /** Get the variance of the distribution. If the variance does not exist, * then quiet_NaN is returned. */ - virtual double GetVariance() const; + virtual double GetVariance() const ITK_OVERRIDE; /** Static method to evaluate the probability density function (pdf) * of a Student-t with a specified number of degrees of freedom. The @@ -200,7 +200,7 @@ protected: TDistribution(void); virtual ~TDistribution(void) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: TDistribution(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkVectorContainerToListSampleAdaptor.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkVectorContainerToListSampleAdaptor.hxx index f57ae7970665c79ccba788afb53ab4cd4c113e25..d94efd414eae492c840eed3fc6a3fd5309281018 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkVectorContainerToListSampleAdaptor.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkVectorContainerToListSampleAdaptor.hxx @@ -28,7 +28,7 @@ template<typename TVectorContainer> VectorContainerToListSampleAdaptor<TVectorContainer> ::VectorContainerToListSampleAdaptor() { - this->m_VectorContainer = 0; + this->m_VectorContainer = ITK_NULLPTR; } template<typename TVectorContainer> diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedCovarianceSampleFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedCovarianceSampleFilter.h index 542e70415e97bb3f504840c14161586312237206..4f2c588a13a02b6199e9b4640e64658cc330412a 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedCovarianceSampleFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedCovarianceSampleFilter.h @@ -54,27 +54,23 @@ public: itkTypeMacro(WeightedCovarianceSampleFilter, CovarianceSampleFilter); itkNewMacro(Self); - /** Traits derived from the base class */ + /** Types derived from the base class */ typedef typename Superclass::SampleType SampleType; typedef typename Superclass::MeasurementVectorType MeasurementVectorType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; - typedef typename Superclass::MeasurementVectorDecoratedType MeasurementVectorDecoratedType; - typedef typename Superclass::OutputType OutputType; - typedef typename Superclass::MeasurementRealType MeasurementRealType; + typedef typename Superclass::MeasurementType MeasurementType; + + /** Types derived from the base class */ typedef typename Superclass::MeasurementVectorRealType MeasurementVectorRealType; + typedef typename Superclass::MeasurementRealType MeasurementRealType; - /** Typedef for WeightedCovariance output */ - typedef VariableSizeMatrix< double > MatrixType; - /** Weight calculation function typedef */ - typedef FunctionBase< MeasurementVectorType, double > WeightingFunctionType; + /** Type of weight values */ + typedef double WeightValueType; - /** VariableSizeMatrix is not a DataObject, we need to decorate it to push it down - * a ProcessObject's pipeline */ - typedef SimpleDataObjectDecorator< MatrixType > MatrixDecoratedType; - /** Array typedef for weights */ - typedef Array< double > WeightArrayType; + /** Array type for weights */ + typedef Array< WeightValueType > WeightArrayType; /** Type of DataObjects to use for the weight array type */ typedef SimpleDataObjectDecorator< WeightArrayType > InputWeightArrayObjectType; @@ -82,12 +78,25 @@ public: /** Method to set the input value of the weight array */ itkSetGetDecoratedInputMacro(Weights, WeightArrayType); + + /** Weight calculation function type */ + typedef FunctionBase< MeasurementVectorType, WeightValueType > WeightingFunctionType; + /** Type of DataObjects to use for Weight function */ typedef DataObjectDecorator< WeightingFunctionType > InputWeightingFunctionObjectType; - /** Method to set the weighting function */ + /** Method to set/get the weighting function */ itkSetGetDecoratedObjectInputMacro(WeightingFunction, WeightingFunctionType); + + /** Types derived from the base class */ + typedef typename Superclass::MatrixType MatrixType; + typedef typename Superclass::MatrixDecoratedType MatrixDecoratedType; + + /** Types derived from the base class */ + typedef typename Superclass::MeasurementVectorDecoratedType MeasurementVectorDecoratedType; + typedef typename Superclass::OutputType OutputType; + protected: WeightedCovarianceSampleFilter(); virtual ~WeightedCovarianceSampleFilter(); diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedCovarianceSampleFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedCovarianceSampleFilter.hxx index d9be072f987f5333010b826bfcaa20e8c4535572..05f5c77fab4b5a777638feb0cdda7a4befb762f2 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedCovarianceSampleFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedCovarianceSampleFilter.hxx @@ -29,7 +29,7 @@ template< typename TSample > WeightedCovarianceSampleFilter< TSample > ::WeightedCovarianceSampleFilter() { - this->ProcessObject::SetNthInput(1, NULL); + this->ProcessObject::SetNthInput(1, ITK_NULLPTR); } template< typename TSample > @@ -58,7 +58,7 @@ WeightedCovarianceSampleFilter< TSample > const InputWeightingFunctionObjectType *functionObject = this->GetWeightingFunctionInput(); - if ( functionObject != NULL ) + if ( functionObject != ITK_NULLPTR ) { this->ComputeCovarianceMatrixWithWeightingFunction(); return; @@ -68,7 +68,7 @@ WeightedCovarianceSampleFilter< TSample > const InputWeightArrayObjectType *weightArrayObject = this->GetWeightsInput(); - if ( weightArrayObject != NULL ) + if ( weightArrayObject != ITK_NULLPTR ) { this->ComputeCovarianceMatrixWithWeights(); return; @@ -84,96 +84,100 @@ inline void WeightedCovarianceSampleFilter< TSample > ::ComputeCovarianceMatrixWithWeightingFunction() { + // set up input / output const SampleType *input = this->GetInput(); - MeasurementVectorSizeType measurementVectorSize = - input->GetMeasurementVectorSize(); + MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); MatrixDecoratedType *decoratedOutput = - itkDynamicCastInDebugMode< MatrixDecoratedType * >( - this->ProcessObject::GetOutput(0) ); + itkDynamicCastInDebugMode< MatrixDecoratedType * >( this->ProcessObject::GetOutput(0) ); MatrixType output = decoratedOutput->Get(); + output.SetSize( measurementVectorSize, measurementVectorSize ); + output.Fill( NumericTraits< typename MatrixType::ValueType >::Zero ); MeasurementVectorDecoratedType *decoratedMeanOutput = - itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( - this->ProcessObject::GetOutput(1) ); + itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(1) ); - output.SetSize(measurementVectorSize, measurementVectorSize); - output.Fill(0.0); + // calculate mean + const WeightingFunctionType * const weightingFunction = this->GetWeightingFunction(); - // if weighting function is specifed, use it to compute the mean - const InputWeightingFunctionObjectType *functionObject = this->GetWeightingFunctionInput(); - const WeightingFunctionType *weightFunction = functionObject->Get(); - - typedef WeightedMeanSampleFilter< TSample > WeightedMeanSampleFilterType; - typename WeightedMeanSampleFilterType::Pointer meanFilter = WeightedMeanSampleFilterType::New(); + typedef WeightedMeanSampleFilter< SampleType > WeightedMeanFilterType; + typename WeightedMeanFilterType::Pointer meanFilter = WeightedMeanFilterType::New(); meanFilter->SetInput( input ); - meanFilter->SetWeightingFunction( weightFunction ); + meanFilter->SetWeightingFunction( weightingFunction ); meanFilter->Update(); - const MeasurementVectorRealType mean = meanFilter->GetMean(); + const typename WeightedMeanFilterType::MeasurementVectorRealType mean = meanFilter->GetMean(); + decoratedMeanOutput->Set( mean ); + // covariance algorithm MeasurementVectorRealType diff; - NumericTraits<MeasurementVectorRealType>::SetLength(diff, measurementVectorSize); - MeasurementVectorType measurements; - NumericTraits<MeasurementVectorType>::SetLength(measurements, measurementVectorSize); + NumericTraits<MeasurementVectorRealType>::SetLength( diff, measurementVectorSize ); - double weight; - double totalWeight = 0.0; - double sumSquaredWeight = 0.0; + WeightValueType totalWeight = NumericTraits< WeightValueType >::Zero; + WeightValueType totalSquaredWeight = NumericTraits< WeightValueType >::Zero; - decoratedMeanOutput->Set( mean ); - - typename TSample::ConstIterator iter = input->Begin(); - typename TSample::ConstIterator end = input->End(); + typename SampleType::ConstIterator iter = input->Begin(); + const typename SampleType::ConstIterator end = input->End(); // fills the lower triangle and the diagonal cells in the covariance matrix - while ( iter != end ) + for (; iter != end; ++iter ) { - measurements = iter.GetMeasurementVector(); - weight = iter.GetFrequency() * weightFunction->Evaluate(measurements); + const MeasurementVectorType & measurement = iter.GetMeasurementVector(); + + const typename SampleType::AbsoluteFrequencyType frequency = iter.GetFrequency(); + + const WeightValueType rawWeight = weightingFunction->Evaluate( measurement ); + + const WeightValueType weight = ( rawWeight * static_cast< WeightValueType >( frequency ) ); totalWeight += weight; - sumSquaredWeight += weight * weight; - for ( unsigned int i = 0; i < measurementVectorSize; ++i ) + totalSquaredWeight += ( weight * weight ); + + for ( unsigned int dim = 0; dim < measurementVectorSize; ++dim ) { - diff[i] = static_cast< MeasurementRealType >( measurements[i] ) - mean[i]; + const MeasurementRealType component = + static_cast< MeasurementRealType >( measurement[dim] ); + + diff[dim] = ( component - mean[dim] ); } // updates the covariance matrix - for ( unsigned int row = 0; row < measurementVectorSize; row++ ) + for ( unsigned int row = 0; row < measurementVectorSize; ++row ) { - for ( unsigned int col = 0; col < row + 1; col++ ) + for ( unsigned int col = 0; col < row + 1; ++col ) { - output(row, col) += weight * diff[row] * diff[col]; + output(row, col) += + ( static_cast< MeasurementRealType >( weight ) * diff[row] * diff[col] ); } } - ++iter; } // fills the upper triangle using the lower triangle - for ( unsigned int row = 1; row < measurementVectorSize; row++ ) + for ( unsigned int row = 1; row < measurementVectorSize; ++row ) { - for ( unsigned int col = 0; col < row; col++ ) + for ( unsigned int col = 0; col < row; ++col ) { output(col, row) = output(row, col); } } - const double normalizationFactor = ( totalWeight - ( sumSquaredWeight / totalWeight ) ); + const double normalizationFactor = ( totalWeight - ( totalSquaredWeight / totalWeight ) ); if( normalizationFactor > vnl_math::eps ) { - output /= normalizationFactor; + const double inverseNormalizationFactor = 1.0 / normalizationFactor; + + output *= inverseNormalizationFactor; } else { itkExceptionMacro("Normalization factor was too close to zero. Value = " << normalizationFactor ); } - decoratedOutput->Set(output); + decoratedOutput->Set( output ); } template< typename TSample > @@ -181,64 +185,66 @@ inline void WeightedCovarianceSampleFilter< TSample > ::ComputeCovarianceMatrixWithWeights() { + // set up input / output const SampleType *input = this->GetInput(); - const MeasurementVectorSizeType measurementVectorSize = - input->GetMeasurementVectorSize(); + MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); - MatrixDecoratedType * const decoratedOutput = - itkDynamicCastInDebugMode< MatrixDecoratedType * >( - this->ProcessObject::GetOutput(0) ); + MatrixDecoratedType *decoratedOutput = + itkDynamicCastInDebugMode< MatrixDecoratedType * >( this->ProcessObject::GetOutput(0) ); MatrixType output = decoratedOutput->Get(); + output.SetSize( measurementVectorSize, measurementVectorSize ); + output.Fill( NumericTraits< typename MatrixType::ValueType >::Zero ); - MeasurementVectorDecoratedType * const decoratedMeanOutput = - itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( - this->ProcessObject::GetOutput(1) ); - - output.SetSize(measurementVectorSize, measurementVectorSize); - output.Fill(0.0); + MeasurementVectorDecoratedType *decoratedMeanOutput = + itkDynamicCastInDebugMode< MeasurementVectorDecoratedType * >( this->ProcessObject::GetOutput(1) ); - const InputWeightArrayObjectType *weightArrayObject = this->GetWeightsInput(); - const WeightArrayType weightArray = weightArrayObject->Get(); + // calculate mean + const WeightArrayType & weightsArray = this->GetWeights(); - typedef WeightedMeanSampleFilter< TSample > WeightedMeanSampleFilterType; - typename WeightedMeanSampleFilterType::Pointer meanFilter = WeightedMeanSampleFilterType::New(); + typedef WeightedMeanSampleFilter< SampleType > WeightedMeanFilterType; + typename WeightedMeanFilterType::Pointer meanFilter = WeightedMeanFilterType::New(); meanFilter->SetInput( input ); - meanFilter->SetWeights( weightArray ); + meanFilter->SetWeights( weightsArray ); meanFilter->Update(); - const MeasurementVectorRealType mean = meanFilter->GetMean(); - - decoratedMeanOutput->Set(mean); + const typename WeightedMeanFilterType::MeasurementVectorRealType mean = meanFilter->GetMean(); + decoratedMeanOutput->Set( mean ); + // covariance algorithm MeasurementVectorRealType diff; - NumericTraits<MeasurementVectorRealType>::SetLength(diff, measurementVectorSize); - MeasurementVectorType measurements; - NumericTraits<MeasurementVectorType>::SetLength(measurements, measurementVectorSize); + NumericTraits<MeasurementVectorRealType>::SetLength( diff, measurementVectorSize ); - double totalWeight = 0.0; - double sumSquaredWeight = 0.0; + WeightValueType totalWeight = NumericTraits< WeightValueType >::Zero; - unsigned int measurementVectorIndex = 0; + WeightValueType totalSquaredWeight = NumericTraits< WeightValueType >::Zero; - typename TSample::ConstIterator iter = input->Begin(); - typename TSample::ConstIterator end = input->End(); + typename SampleType::ConstIterator iter = input->Begin(); + const typename SampleType::ConstIterator end = input->End(); // fills the lower triangle and the diagonal cells in the covariance matrix - measurementVectorIndex = 0; - while ( iter != end ) + for ( unsigned int sampleVectorIndex = 0; + iter != end; + ++iter, ++sampleVectorIndex ) { - const double weight = iter.GetFrequency() * ( weightArray )[measurementVectorIndex]; - measurements = iter.GetMeasurementVector(); + const MeasurementVectorType & measurement = iter.GetMeasurementVector(); + + const typename SampleType::AbsoluteFrequencyType frequency = iter.GetFrequency(); + const WeightValueType rawWeight = weightsArray[sampleVectorIndex]; + + const WeightValueType weight = ( rawWeight * static_cast< WeightValueType >( frequency ) ); totalWeight += weight; - sumSquaredWeight += weight * weight; + totalSquaredWeight += ( weight * weight ); - for ( unsigned int i = 0; i < measurementVectorSize; ++i ) + for ( unsigned int dim = 0; dim < measurementVectorSize; ++dim ) { - diff[i] = static_cast< MeasurementRealType >( measurements[i] ) - mean[i]; + const MeasurementRealType component = + static_cast< MeasurementRealType >( measurement[dim] ); + + diff[dim] = ( component - mean[dim] ); } // updates the covariance matrix @@ -246,11 +252,10 @@ WeightedCovarianceSampleFilter< TSample > { for ( unsigned int col = 0; col < row + 1; ++col ) { - output(row, col) += weight * diff[row] * diff[col]; + output(row, col) += + ( static_cast< MeasurementRealType >( weight ) * diff[row] * diff[col] ); } } - ++iter; - ++measurementVectorIndex; } // fills the upper triangle using the lower triangle @@ -262,18 +267,20 @@ WeightedCovarianceSampleFilter< TSample > } } - const double normalizationFactor = ( totalWeight - ( sumSquaredWeight / totalWeight ) ); + const double normalizationFactor = ( totalWeight - ( totalSquaredWeight / totalWeight ) ); if( normalizationFactor > vnl_math::eps ) { - output /= normalizationFactor; + const double inverseNormalizationFactor = 1.0 / normalizationFactor; + + output *= inverseNormalizationFactor; } else { itkExceptionMacro("Normalization factor was too close to zero. Value = " << normalizationFactor ); } - decoratedOutput->Set(output); + decoratedOutput->Set( output ); } } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedMeanSampleFilter.h b/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedMeanSampleFilter.h index 3f16d9f634a3232abb7cdb7455bf9c4a1e482d84..efb230c7e1b27de8ddecafe4cb608c924e8af000 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedMeanSampleFilter.h +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedMeanSampleFilter.h @@ -52,34 +52,45 @@ public: itkTypeMacro(WeightedMeanSampleFilter, MeanSampleFilter); itkNewMacro(Self); - /** Traits derived from the base class */ + /** Types derived from the base class */ typedef typename Superclass::SampleType SampleType; - typedef typename Superclass::MeasurementType MeasurementType; typedef typename Superclass::MeasurementVectorType MeasurementVectorType; typedef typename Superclass::MeasurementVectorSizeType MeasurementVectorSizeType; - typedef typename Superclass::MeasurementVectorDecoratedType MeasurementVectorDecoratedType; - typedef typename Superclass::OutputType OutputType; - typedef typename Superclass::MeasurementRealType MeasurementRealType; + typedef typename Superclass::MeasurementType MeasurementType; + + /** Types derived from the base class */ typedef typename Superclass::MeasurementVectorRealType MeasurementVectorRealType; + typedef typename Superclass::MeasurementRealType MeasurementRealType; + - /** Array typedef for weights */ - typedef Array< double > WeightArrayType; + /** Type of weight values */ + typedef double WeightValueType; + + + /** Array type for weights */ + typedef Array< WeightValueType > WeightArrayType; /** Type of DataObjects to use for the weight array type */ typedef SimpleDataObjectDecorator< WeightArrayType > InputWeightArrayObjectType; - /** Method to set the input value of the weight array */ + /** Method to set/get the input value of the weight array */ itkSetGetDecoratedInputMacro(Weights, WeightArrayType); - /** Weight calculation function typedef */ - typedef FunctionBase< MeasurementVectorType, double > WeightingFunctionType; + + /** Weight calculation function type */ + typedef FunctionBase< MeasurementVectorType, WeightValueType > WeightingFunctionType; /** Type of DataObjects to use for Weight function */ typedef DataObjectDecorator< WeightingFunctionType > InputWeightingFunctionObjectType; - /** Method to set the weighting function */ + /** Method to set/get the weighting function */ itkSetGetDecoratedObjectInputMacro(WeightingFunction, WeightingFunctionType); + + /** Types derived from the base class */ + typedef typename Superclass::MeasurementVectorDecoratedType MeasurementVectorDecoratedType; + typedef typename Superclass::OutputType OutputType; + protected: WeightedMeanSampleFilter(); virtual ~WeightedMeanSampleFilter(); diff --git a/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedMeanSampleFilter.hxx b/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedMeanSampleFilter.hxx index 198702e5188c862be0fb67f7f6c747d84b3e1106..063155b9ad558eeb2d780127a34349524cd98394 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedMeanSampleFilter.hxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/include/itkWeightedMeanSampleFilter.hxx @@ -18,9 +18,12 @@ #ifndef __itkWeightedMeanSampleFilter_hxx #define __itkWeightedMeanSampleFilter_hxx -#include "itkMeasurementVectorTraits.h" #include "itkWeightedMeanSampleFilter.h" +#include <vector> +#include "itkCompensatedSummation.h" +#include "itkMeasurementVectorTraits.h" + namespace itk { namespace Statistics @@ -29,7 +32,7 @@ template< typename TSample > WeightedMeanSampleFilter< TSample > ::WeightedMeanSampleFilter() { - this->ProcessObject::SetNthInput(1, NULL); + this->ProcessObject::SetNthInput(1, ITK_NULLPTR); } template< typename TSample > @@ -58,7 +61,7 @@ WeightedMeanSampleFilter< TSample > const InputWeightingFunctionObjectType *functionObject = this->GetWeightingFunctionInput(); - if ( functionObject != NULL ) + if ( functionObject != ITK_NULLPTR ) { this->ComputeMeanWithWeightingFunction(); return; @@ -68,7 +71,7 @@ WeightedMeanSampleFilter< TSample > const InputWeightArrayObjectType *weightArrayObject = this->GetWeightsInput(); - if ( weightArrayObject != NULL ) + if ( weightArrayObject != ITK_NULLPTR ) { this->ComputeMeanWithWeights(); return; @@ -83,9 +86,10 @@ void WeightedMeanSampleFilter< TSample > ::ComputeMeanWithWeights() { + // set up input / output const SampleType *input = this->GetInput(); - MeasurementVectorSizeType measurementVectorSize = + const MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); MeasurementVectorDecoratedType *decoratedOutput = @@ -96,51 +100,44 @@ WeightedMeanSampleFilter< TSample > NumericTraits<MeasurementVectorRealType>::SetLength( output, this->GetMeasurementVectorSize() ); - //reset the output - for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) - { - output[dim] = NumericTraits< MeasurementRealType >::Zero; - } - - typedef typename NumericTraits< - MeasurementRealType >::AccumulateType MeasurementRealAccumulateType; + // algorithm start + typedef CompensatedSummation< MeasurementRealType > MeasurementRealAccumulateType; + std::vector< MeasurementRealAccumulateType > sum( measurementVectorSize ); - Array< MeasurementRealAccumulateType > sum( measurementVectorSize ); - sum.Fill( NumericTraits< MeasurementRealAccumulateType >::Zero ); + const WeightArrayType & weightsArray = this->GetWeights(); + WeightValueType totalWeight = NumericTraits< WeightValueType >::Zero; - typename TSample::ConstIterator iter = input->Begin(); - typename TSample::ConstIterator end = input->End(); - double totalWeight = 0.0; - double weight; + typename SampleType::ConstIterator iter = input->Begin(); + typename SampleType::ConstIterator end = input->End(); - typename TSample::MeasurementVectorType measurements; + for ( unsigned int sampleVectorIndex = 0; + iter != end; + ++iter, ++sampleVectorIndex ) + { + const MeasurementVectorType & measurement = iter.GetMeasurementVector(); - const InputWeightArrayObjectType *weightArrayObject = this->GetWeightsInput(); - const WeightArrayType weightArray = weightArrayObject->Get(); + const typename SampleType::AbsoluteFrequencyType frequency = iter.GetFrequency(); - int measurementVectorIndex = 0; + const WeightValueType rawWeight = weightsArray[sampleVectorIndex]; - while ( iter != end ) - { - measurements = iter.GetMeasurementVector(); - weight = iter.GetFrequency() * ( weightArray )[measurementVectorIndex]; + const WeightValueType weight = ( rawWeight * static_cast< WeightValueType >( frequency ) ); totalWeight += weight; for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) { - const MeasurementRealType component = static_cast< MeasurementRealType >( measurements[dim] ); - sum[dim] += static_cast< MeasurementRealAccumulateType >( component * weight ); + const MeasurementRealType component = + static_cast< MeasurementRealType >( measurement[dim] ); + + sum[dim] += ( component * weight ); } - ++measurementVectorIndex; - ++iter; } if ( totalWeight > vnl_math::eps ) { for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) { - output[dim] = static_cast< MeasurementRealType >( sum[dim] / totalWeight ); + output[dim] = ( sum[dim].GetSum() / static_cast< MeasurementRealType >( totalWeight ) ); } } else @@ -148,7 +145,7 @@ WeightedMeanSampleFilter< TSample > itkExceptionMacro("Total weight was too close to zero. Value = " << totalWeight ); } - decoratedOutput->Set(output); + decoratedOutput->Set( output ); } template< typename TSample > @@ -156,9 +153,10 @@ void WeightedMeanSampleFilter< TSample > ::ComputeMeanWithWeightingFunction() { + // set up input / output const SampleType *input = this->GetInput(); - MeasurementVectorSizeType measurementVectorSize = + const MeasurementVectorSizeType measurementVectorSize = input->GetMeasurementVectorSize(); MeasurementVectorDecoratedType *decoratedOutput = @@ -169,47 +167,50 @@ WeightedMeanSampleFilter< TSample > NumericTraits<MeasurementVectorRealType>::SetLength( output, this->GetMeasurementVectorSize() ); - //reset the output - for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) - { - output[dim] = NumericTraits< MeasurementRealType >::Zero; - } + // algorithm start + typedef CompensatedSummation< MeasurementRealType > MeasurementRealAccumulateType; + std::vector< MeasurementRealAccumulateType > sum( measurementVectorSize ); - typename TSample::ConstIterator iter = input->Begin(); - typename TSample::ConstIterator end = input->End(); - double totalWeight = 0.0; - double weight; + const WeightingFunctionType * const weightFunction = this->GetWeightingFunction(); - typename TSample::MeasurementVectorType measurements; + WeightValueType totalWeight = NumericTraits< WeightValueType >::Zero; - // if weighting function is specifed, use it to compute the mean - const InputWeightingFunctionObjectType *functionObject = - this->GetWeightingFunctionInput(); - - const WeightingFunctionType *weightFunction = functionObject->Get(); + typename SampleType::ConstIterator iter = input->Begin(); + const typename SampleType::ConstIterator end = input->End(); - while ( iter != end ) + for (; iter != end; ++iter ) { - measurements = iter.GetMeasurementVector(); - weight = - iter.GetFrequency() * weightFunction->Evaluate(measurements); + const MeasurementVectorType & measurement = iter.GetMeasurementVector(); + + const typename SampleType::AbsoluteFrequencyType frequency = iter.GetFrequency(); + + const WeightValueType rawWeight = weightFunction->Evaluate( measurement ); + + const WeightValueType weight = ( rawWeight * static_cast< WeightValueType >( frequency ) ); totalWeight += weight; + for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) { - output[dim] += measurements[dim] * weight; + const MeasurementRealType component = + static_cast< MeasurementRealType >( measurement[dim] ); + + sum[dim] += ( component * weight ); } - ++iter; } - if ( totalWeight != 0.0 ) + if ( totalWeight > vnl_math::eps ) { for ( unsigned int dim = 0; dim < measurementVectorSize; dim++ ) { - output[dim] /= totalWeight; + output[dim] = ( sum[dim].GetSum() / static_cast< MeasurementRealType >( totalWeight ) ); } } + else + { + itkExceptionMacro("Total weight was too close to zero. Value = " << totalWeight ); + } - decoratedOutput->Set(output); + decoratedOutput->Set( output ); } } // end of namespace Statistics } // end of namespace itk diff --git a/Utilities/ITK/Modules/Numerics/Statistics/src/itkChiSquareDistribution.cxx b/Utilities/ITK/Modules/Numerics/Statistics/src/itkChiSquareDistribution.cxx index e211c4586fd9060cab33c435627e1251eae00942..00acfad7e7055de9149668bc35e8bdefd16437be 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/src/itkChiSquareDistribution.cxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/src/itkChiSquareDistribution.cxx @@ -84,8 +84,8 @@ ChiSquareDistribution if ( x >= 0.0 ) { - pdf = vcl_exp(-0.5 * x) * vcl_pow(x, dofon2 - 1.0) - / ( vcl_pow(2.0, dofon2) * dgamma_(&dofon2) ); + pdf = std::exp(-0.5 * x) * std::pow(x, dofon2 - 1.0) + / ( std::pow(2.0, dofon2) * dgamma_(&dofon2) ); } return pdf; @@ -159,7 +159,7 @@ ChiSquareDistribution nx = GaussianDistribution::InverseCDF(p); double f = 2.0 / ( 9.0 * dof ); - x = dof * vcl_pow(1.0 - f + nx * vcl_sqrt(f), 3.0); + x = dof * std::pow(1.0 - f + nx * std::sqrt(f), 3.0); // The approximation above is only accurate for large degrees of // freedom. We'll improve the approximation by a few Newton iterations. diff --git a/Utilities/ITK/Modules/Numerics/Statistics/src/itkGaussianDistribution.cxx b/Utilities/ITK/Modules/Numerics/Statistics/src/itkGaussianDistribution.cxx index 957953f0ee338f00221323ff11ea856f1a50fa03..7ca0959d02ff76317af077dc1f5f9a6a62406a8b 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/src/itkGaussianDistribution.cxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/src/itkGaussianDistribution.cxx @@ -162,7 +162,7 @@ double GaussianDistribution ::PDF(double x) { - return vnl_math::one_over_sqrt2pi * vcl_exp(-0.5 * x * x); + return vnl_math::one_over_sqrt2pi * std::exp(-0.5 * x * x); } double @@ -171,8 +171,8 @@ GaussianDistribution { double xminusmean = x - mean; - return ( vnl_math::one_over_sqrt2pi / vcl_sqrt(variance) ) - * vcl_exp(-0.5 * xminusmean * xminusmean / variance); + return ( vnl_math::one_over_sqrt2pi / std::sqrt(variance) ) + * std::exp(-0.5 * xminusmean * xminusmean / variance); } double @@ -205,7 +205,7 @@ GaussianDistribution ::CDF(double x, double mean, double variance) { // convert to zero mean unit variance - double u = ( x - mean ) / vcl_sqrt(variance); + double u = ( x - mean ) / std::sqrt(variance); return 0.5 * ( vnl_erf(vnl_math::sqrt1_2 * u) + 1.0 ); } @@ -252,7 +252,7 @@ GaussianDistribution /** Step 1: use 26.2.23 from Abramowitz and Stegun */ - dt = vcl_sqrt( -2.0 * vcl_log(dp) ); + dt = std::sqrt( -2.0 * std::log(dp) ); dx = dt - ( ( .010328e+0 * dt + .802853e+0 ) * dt + 2.515517e+0 ) / ( ( ( .001308e+0 * dt + .189269e+0 ) * dt + 1.432788e+0 ) * dt + 1.e+0 ); @@ -262,7 +262,7 @@ GaussianDistribution for ( newt = 0; newt < 3; newt++ ) { dq = 0.5e+0 * vnl_erfc(dx * vnl_math::sqrt1_2) - dp; - ddq = vcl_exp(-0.5e+0 * dx * dx) / 2.506628274631000e+0; + ddq = std::exp(-0.5e+0 * dx * dx) / 2.506628274631000e+0; dx = dx + dq / ddq; } @@ -295,7 +295,7 @@ GaussianDistribution { // apply the mean and variance to provide the value for the // prescribed Gaussian - x = x * vcl_sqrt(variance) + mean; + x = x * std::sqrt(variance) + mean; return x; } } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/src/itkNormalVariateGenerator.cxx b/Utilities/ITK/Modules/Numerics/Statistics/src/itkNormalVariateGenerator.cxx index e6b24455d72fa9c58108893c1921b48d2ad266bb..6d6c96d693c9ac05f9781a1dbb7b78be2fd9f2f2 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/src/itkNormalVariateGenerator.cxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/src/itkNormalVariateGenerator.cxx @@ -34,7 +34,7 @@ NormalVariateGenerator::NormalVariateGenerator() m_TLEN = ( 8 * m_LEN ); m_Vec1 = new int[m_TLEN]; - m_Gausssave = 0; + m_Gausssave = ITK_NULLPTR; this->Initialize(0); } @@ -89,11 +89,11 @@ void NormalVariateGenerator::Initialize(int randomSeed) // Z = (sqrt (1/2TLEN)) * A * (B + n) // where: // B = C / A. -// We set m_Chic1 = A * vcl_sqrt(0.5 / TLEN), m_Chic2 = B +// We set m_Chic1 = A * std::sqrt(0.5 / TLEN), m_Chic2 = B fake = 1.0 + 0.125 / m_TLEN; // This is A - m_Chic2 = vcl_sqrt(2.0 * m_TLEN - fake * fake) / fake; - m_Chic1 = fake * vcl_sqrt(0.5 / m_TLEN); + m_Chic2 = std::sqrt(2.0 * m_TLEN - fake * fake) / fake; + m_Chic1 = fake * std::sqrt(0.5 / m_TLEN); m_ActualRSD = 0.0; } @@ -124,12 +124,12 @@ double NormalVariateGenerator::FastNorm(void) int r; int s; int t; - int * pa = 0; - int * pb = 0; - int * pc = 0; - int * pd = 0; + int * pa = ITK_NULLPTR; + int * pb = ITK_NULLPTR; + int * pc = ITK_NULLPTR; + int * pd = ITK_NULLPTR; int * pe; - int * p0 = 0; + int * p0 = ITK_NULLPTR; int mtype; int stype; double ts; @@ -333,16 +333,16 @@ nextpair: m_Irs = ( m_Irs <= 0 ) ? ( ( m_Irs << 1 ) ^ 333556017 ) : ( m_Irs << 1 ); r = m_Irs + m_Lseed; if ( r < 0 ) { r = ~r; } - tz = -2.0 * vcl_log( ( r + 0.5 ) * m_Rcons ); /* Sum of squares */ + tz = -2.0 * std::log( ( r + 0.5 ) * m_Rcons ); /* Sum of squares */ ts += tz; - tz = vcl_sqrt(tz / tr); + tz = std::sqrt(tz / tr); m_Vec1[p++] = (int)( m_Scale * tx * tz ); m_Vec1[p++] = (int)( m_Scale * ty * tz ); if ( p < m_TLEN ) { goto nextpair; } /* Horrid, but good enough */ /* Calc correction factor to make sum of squares = TLEN */ ts = m_TLEN / ts; /* Should be close to 1.0 */ - tr = vcl_sqrt(ts); + tr = std::sqrt(ts); for ( p = 0; p < m_TLEN; p++ ) { tx = m_Vec1[p] * tr; @@ -358,7 +358,7 @@ recalcsumsq: ts += ( tx * tx ); } /* Now ts should be Scale*Scale*TLEN or thereabouts */ - ts = vcl_sqrt( ts / ( m_Scale * m_Scale * m_TLEN ) ); + ts = std::sqrt( ts / ( m_Scale * m_Scale * m_TLEN ) ); m_ActualRSD = 1.0 / ts; /* Reciprocal of actual Standard Devtn */ goto startpass; } diff --git a/Utilities/ITK/Modules/Numerics/Statistics/src/itkTDistribution.cxx b/Utilities/ITK/Modules/Numerics/Statistics/src/itkTDistribution.cxx index 9b0e9813afaade533db41df357b00526b1e11dc4..fc3fa611c17e1bc5644abb547c218a3c2fb4a4ba 100644 --- a/Utilities/ITK/Modules/Numerics/Statistics/src/itkTDistribution.cxx +++ b/Utilities/ITK/Modules/Numerics/Statistics/src/itkTDistribution.cxx @@ -85,7 +85,7 @@ TDistribution double pdf; pdf = ( dgamma_(&dofplusoneon2) / dgamma_(&dofon2) ) - / ( vcl_sqrt(dof * vnl_math::pi) * vcl_pow(1.0 + ( ( x * x ) / dof ), dofplusoneon2) ); + / ( std::sqrt(dof * vnl_math::pi) * std::pow(1.0 + ( ( x * x ) / dof ), dofplusoneon2) ); return pdf; } @@ -189,10 +189,10 @@ TDistribution dof4 = dof * dof3; gaussX = GaussianDistribution::InverseCDF(p); - gaussX3 = vcl_pow(gaussX, 3.0); - gaussX5 = vcl_pow(gaussX, 5.0); - gaussX7 = vcl_pow(gaussX, 7.0); - gaussX9 = vcl_pow(gaussX, 9.0); + gaussX3 = std::pow(gaussX, 3.0); + gaussX5 = std::pow(gaussX, 5.0); + gaussX7 = std::pow(gaussX, 7.0); + gaussX9 = std::pow(gaussX, 9.0); x = gaussX + ( gaussX3 + gaussX ) / ( 4.0 * dof ) @@ -411,8 +411,6 @@ TDistribution << m_Parameters.size() << " parameters."); } - - return NumericTraits< double >::quiet_NaN(); } void diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkBlockMatchingImageFilter.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkBlockMatchingImageFilter.hxx index 5ee654550f00b1ed4d7a862511a0fc9f32715080..029f869d42e4eee5b0856593c01df27faae5f10a 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkBlockMatchingImageFilter.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkBlockMatchingImageFilter.hxx @@ -126,7 +126,7 @@ BlockMatchingImageFilter< TFixedImage, TMovingImage, TFeatures, TDisplacements, break; } itkExceptionMacro(<< "Bad output index " << idx ); - return 0; + return ITK_NULLPTR; } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkCenteredTransformInitializer.h b/Utilities/ITK/Modules/Registration/Common/include/itkCenteredTransformInitializer.h index c807884acbf714a90aa727370a019df1c2f581b9..b5ff8d389e16d98617fa5fa9cb1606ea778e8120 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkCenteredTransformInitializer.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkCenteredTransformInitializer.h @@ -135,7 +135,7 @@ protected: CenteredTransformInitializer(); ~CenteredTransformInitializer(){} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; itkGetModifiableObjectMacro(Transform, TransformType); diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkCommandIterationUpdate.h b/Utilities/ITK/Modules/Registration/Common/include/itkCommandIterationUpdate.h index 19ae7ea1a148cbf8102c89b07e3a799ea6b43c1c..785d6429681ab883ce260c3e66afbf73593bb8a9 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkCommandIterationUpdate.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkCommandIterationUpdate.h @@ -57,12 +57,12 @@ public: /** * Execute method will print data at each iteration */ - void Execute(itk::Object *caller, const itk::EventObject & event) + virtual void Execute(itk::Object *caller, const itk::EventObject & event) ITK_OVERRIDE { Execute( (const itk::Object *)caller, event); } - void Execute(const itk::Object *, const itk::EventObject & event) + virtual void Execute(const itk::Object *, const itk::EventObject & event) ITK_OVERRIDE { if( typeid( event ) == typeid( itk::StartEvent ) ) { diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkCommandVnlIterationUpdate.h b/Utilities/ITK/Modules/Registration/Common/include/itkCommandVnlIterationUpdate.h index 3740b5e3087965e88429d9f0935ee08ee691efd0..34863caf252a51d155b7bfdef06e61ff7d12901b 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkCommandVnlIterationUpdate.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkCommandVnlIterationUpdate.h @@ -57,12 +57,12 @@ public: /** * Execute method will print data at each iteration */ - void Execute(itk::Object *caller, const itk::EventObject & event) + virtual void Execute(itk::Object *caller, const itk::EventObject & event) ITK_OVERRIDE { Execute( (const itk::Object *)caller, event); } - void Execute(const itk::Object * itkNotUsed(caller), const itk::EventObject & event) + virtual void Execute(const itk::Object * itkNotUsed(caller), const itk::EventObject & event) ITK_OVERRIDE { if( typeid( event ) == typeid( itk::StartEvent ) ) { diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkCompareHistogramImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkCompareHistogramImageToImageMetric.hxx index 4ae26658bd22993993fd75859a5071e1bb9a1188..98526c1f7e16fcb0c2397be065dfc6f43e23a800 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkCompareHistogramImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkCompareHistogramImageToImageMetric.hxx @@ -26,11 +26,11 @@ namespace itk template< typename TFixedImage, typename TMovingImage > CompareHistogramImageToImageMetric< TFixedImage, TMovingImage >::CompareHistogramImageToImageMetric() { - m_TrainingFixedImage = 0; // has to be provided by the user. - m_TrainingMovingImage = 0; // has to be provided by the user. - m_TrainingTransform = 0; // has to be provided by the user. - m_TrainingInterpolator = 0; // has to be provided by the user. - m_TrainingHistogram = 0; // either provided by the user or created + m_TrainingFixedImage = ITK_NULLPTR; // has to be provided by the user. + m_TrainingMovingImage = ITK_NULLPTR; // has to be provided by the user. + m_TrainingTransform = ITK_NULLPTR; // has to be provided by the user. + m_TrainingInterpolator = ITK_NULLPTR; // has to be provided by the user. + m_TrainingHistogram = ITK_NULLPTR; // either provided by the user or created } template< typename TFixedImage, typename TMovingImage > @@ -111,6 +111,7 @@ throw ( ExceptionObject ) TrainingFixedIteratorType; typename FixedImageType::IndexType index; typename FixedImageType::RegionType fixedRegion; + typename HistogramType::IndexType hIndex; TrainingFixedIteratorType ti(this->m_TrainingFixedImage, this->m_TrainingFixedImageRegion); @@ -144,7 +145,9 @@ throw ( ExceptionObject ) sample.SetSize(2); sample[0] = TrainingFixedValue; sample[1] = TrainingMovingValue; - this->m_TrainingHistogram->IncreaseFrequencyOfMeasurement(sample, 1); + + this->m_TrainingHistogram->GetIndex( sample, hIndex ); + this->m_TrainingHistogram->IncreaseFrequencyOfIndex( hIndex, 1 ); } } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkCorrelationCoefficientHistogramImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkCorrelationCoefficientHistogramImageToImageMetric.hxx index 19419612a3af145638210c8b80ca2eb7cb957485..37ce2c9d52b7d009ce281cbc419c8987295490a0 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkCorrelationCoefficientHistogramImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkCorrelationCoefficientHistogramImageToImageMetric.hxx @@ -32,7 +32,7 @@ CorrelationCoefficientHistogramImageToImageMetric< TFixedImage, TMovingImage > const MeasureType varianceY = this->VarianceY(histogram); const MeasureType covariance = this->Covariance(histogram); - return vcl_fabs( covariance / ( vcl_sqrt(varianceX) * vcl_sqrt(varianceY) ) ); + return std::fabs( covariance / ( std::sqrt(varianceX) * std::sqrt(varianceY) ) ); } template< typename TFixedImage, typename TMovingImage > @@ -87,10 +87,10 @@ CorrelationCoefficientHistogramImageToImageMetric< TFixedImage, TMovingImage > { varX += static_cast< double >( histogram.GetFrequency(i, 0) ) / histogram.GetTotalFrequency() - * vcl_pow(histogram.GetMeasurement(i, 0), 2); + * std::pow(histogram.GetMeasurement(i, 0), 2); } - return varX - vcl_pow(MeanX(histogram), 2); + return varX - std::pow(MeanX(histogram), 2); } template< typename TFixedImage, typename TMovingImage > @@ -105,10 +105,10 @@ CorrelationCoefficientHistogramImageToImageMetric< TFixedImage, TMovingImage > { varY += static_cast< double >( histogram.GetFrequency(i, 1) ) / histogram.GetTotalFrequency() - * vcl_pow(histogram.GetMeasurement(i, 1), 2); + * std::pow(histogram.GetMeasurement(i, 1), 2); } - return varY - vcl_pow(MeanY(histogram), 2); + return varY - std::pow(MeanY(histogram), 2); } template< typename TFixedImage, typename TMovingImage > diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkDisplacementFieldTransformParametersAdaptor.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkDisplacementFieldTransformParametersAdaptor.hxx index 9da946b51f8b40a9c82ecc0ef4b8dad0eb6af571..9f90143b79ba4096dfc9a7ae0bfc4a4b89376bcb 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkDisplacementFieldTransformParametersAdaptor.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkDisplacementFieldTransformParametersAdaptor.hxx @@ -230,7 +230,7 @@ DisplacementFieldTransformParametersAdaptor<TTransform> newDisplacementField->Update(); newDisplacementField->DisconnectPipeline(); - typename DisplacementFieldType::Pointer newInverseDisplacementField = NULL; + typename DisplacementFieldType::Pointer newInverseDisplacementField = ITK_NULLPTR; if( this->m_Transform->GetInverseDisplacementField() ) { typename LinearInterpolatorType::Pointer inverseInterpolator = LinearInterpolatorType::New(); diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkEuclideanDistancePointMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkEuclideanDistancePointMetric.hxx index 0a65f1e65e61fa62c6c86c447cc200db9b7b8519..abe9d56173c5b1ee6bdcccb8f1f900be4517e7eb 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkEuclideanDistancePointMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkEuclideanDistancePointMetric.hxx @@ -28,7 +28,7 @@ template< typename TFixedPointSet, typename TMovingPointSet, typename TDistanceM EuclideanDistancePointMetric< TFixedPointSet, TMovingPointSet, TDistanceMap > ::EuclideanDistancePointMetric() { - m_DistanceMap = 0; + m_DistanceMap = ITK_NULLPTR; // when set to true it will be a bit faster, but it will result in minimizing // the sum of distances^4 instead of the sum of distances^2 @@ -121,7 +121,7 @@ EuclideanDistancePointMetric< TFixedPointSet, TMovingPointSet, TDistanceMap > if ( !m_ComputeSquaredDistance ) { - dist = vcl_sqrt(dist); + dist = std::sqrt(dist); } if ( dist < minimumDistance ) diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkGradientDifferenceImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkGradientDifferenceImageToImageMetric.hxx index 8e8a794daedf11c74b2b05ca97918ad56b938138..6bfb24eac80eb059939eec9414a69ec899942f84 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkGradientDifferenceImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkGradientDifferenceImageToImageMetric.hxx @@ -38,7 +38,7 @@ GradientDifferenceImageToImageMetric< TFixedImage, TMovingImage > { unsigned int iDimension; - m_TransformMovingImageFilter = 0; + m_TransformMovingImageFilter = ITK_NULLPTR; for ( iDimension = 0; iDimension < FixedImageDimension; iDimension++ ) { @@ -265,7 +265,10 @@ GradientDifferenceImageToImageMetric< TFixedImage, TMovingImage > ++iterate; } - m_Variance[iDimension] /= nPixels; + if (nPixels > 0) + { + m_Variance[iDimension] /= nPixels; + } } } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkHistogramImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkHistogramImageToImageMetric.hxx index 4f85a2805a34573261ac1f57cbac5be43b866552..2e02b9abca6382ef6ddced36787d1dc2e4ef0637 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkHistogramImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkHistogramImageToImageMetric.hxx @@ -277,6 +277,7 @@ HistogramImageToImageMetric< TFixedImage, TMovingImage > typename FixedImageType::IndexType index; typename FixedImageType::RegionType fixedRegion; + typename HistogramType::IndexType hIndex; fixedRegion = this->GetFixedImageRegion(); FixedIteratorType ti(fixedImage, fixedRegion); @@ -326,7 +327,9 @@ HistogramImageToImageMetric< TFixedImage, TMovingImage > sample.SetSize(2); sample[0] = fixedValue; sample[1] = movingValue; - histogram.IncreaseFrequencyOfMeasurement(sample, 1); + + histogram.GetIndex( sample, hIndex ); + histogram.IncreaseFrequencyOfIndex( hIndex, 1 ); } } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethod.h b/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethod.h index adc46bb87ae396b7fc6cf33f0ba0ecd19391a30d..d3a1738e1c0f39050285122ad8d5b29f1b767157 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethod.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethod.h @@ -186,11 +186,11 @@ public: * output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** Method to return the latest modified time of this object or * any of its cached ivars */ - ModifiedTimeType GetMTime() const; + virtual ModifiedTimeType GetMTime() const ITK_OVERRIDE; #ifdef ITKV3_COMPATIBILITY /** Method that initiates the registration. This will Initialize and ensure @@ -214,10 +214,10 @@ public: protected: ImageRegistrationMethod(); virtual ~ImageRegistrationMethod() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Method invoked by the pipeline in order to trigger the computation of * the registration. */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Provides derived classes with the ability to set this private var */ itkSetMacro(LastTransformParameters, ParametersType); diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethod.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethod.hxx index 4ff7b9ee1ebf47f91b263f6a7e4a2536f3a26f8d..112820f24f12d10454e798ff758b354ac681c222 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethod.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethod.hxx @@ -31,12 +31,12 @@ ImageRegistrationMethod< TFixedImage, TMovingImage > { this->SetNumberOfRequiredOutputs(1); // for the Transform - m_FixedImage = 0; // has to be provided by the user. - m_MovingImage = 0; // has to be provided by the user. - m_Transform = 0; // has to be provided by the user. - m_Interpolator = 0; // has to be provided by the user. - m_Metric = 0; // has to be provided by the user. - m_Optimizer = 0; // has to be provided by the user. + m_FixedImage = ITK_NULLPTR; // has to be provided by the user. + m_MovingImage = ITK_NULLPTR; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. + m_Interpolator = ITK_NULLPTR; // has to be provided by the user. + m_Metric = ITK_NULLPTR; // has to be provided by the user. + m_Optimizer = ITK_NULLPTR; // has to be provided by the user. m_InitialTransformParameters = ParametersType(1); m_LastTransformParameters = ParametersType(1); @@ -312,7 +312,7 @@ ImageRegistrationMethod< TFixedImage, TMovingImage > break; default: itkExceptionMacro("MakeOutput request for an output number larger than the expected number of outputs"); - return 0; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethodImageSource.h b/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethodImageSource.h index 4aee71a3be036ba1e20360b8c95ef239f604da0f..89aa96e6f0778d4fa0faa470d16e4489ee45a083 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethodImageSource.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageRegistrationMethodImageSource.h @@ -125,7 +125,7 @@ void GenerateImages( const typename MovingImageType::SizeType & size ) d += displacement; const double x = d[0]; const double y = d[1]; - const double value = 200.0 * vcl_exp( - ( x*x + y*y )/(s*s) ); + const double value = 200.0 * std::exp( - ( x*x + y*y )/(s*s) ); ri.Set( static_cast<typename MovingImageType::PixelType>(value) ); ++ri; } @@ -138,7 +138,7 @@ void GenerateImages( const typename MovingImageType::SizeType & size ) d = p-center; const double x = d[0]; const double y = d[1]; - const double value = 200.0 * vcl_exp( - ( x*x + y*y )/(s*s) ); + const double value = 200.0 * std::exp( - ( x*x + y*y )/(s*s) ); ti.Set( static_cast<typename FixedImageType::PixelType>(value) ); ++ti; } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageToImageMetric.h b/Utilities/ITK/Modules/Registration/Common/include/itkImageToImageMetric.h index 05ca62bf5ad7131ac6bb66a73198e43dbb51079c..92595897cc249dbbe3ce87a24305a861cefae506 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageToImageMetric.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageToImageMetric.h @@ -209,7 +209,7 @@ public: void SetTransformParameters(const ParametersType & parameters) const; /** Return the number of parameters required by the Transform */ - unsigned int GetNumberOfParameters(void) const + virtual unsigned int GetNumberOfParameters(void) const ITK_OVERRIDE { return m_Transform->GetNumberOfParameters(); } @@ -318,7 +318,7 @@ protected: ImageToImageMetric(); virtual ~ImageToImageMetric(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** \class FixedImageSamplePoint * A fixed image spatial sample consists of the fixed domain point @@ -469,14 +469,14 @@ public: MovingImagePointType & mappedPoint, bool & sampleWithinSupportRegion, double & movingImageValue, - ThreadIdType threadID) const; + ThreadIdType threadId) const; virtual void TransformPointWithDerivatives(unsigned int sampleNumber, MovingImagePointType & mappedPoint, bool & sampleWithinSupportRegion, double & movingImageValue, ImageDerivativesType & gradient, - ThreadIdType threadID) const; + ThreadIdType threadId) const; /** Boolean to indicate if the interpolator BSpline. */ bool m_InterpolatorIsBSpline; @@ -489,7 +489,7 @@ public: /** Compute image derivatives at a point. */ virtual void ComputeImageDerivatives(const MovingImagePointType & mappedPoint, ImageDerivativesType & gradient, - ThreadIdType threadID) const; + ThreadIdType threadId) const; /** * Types and variables related to multi-threading @@ -517,20 +517,20 @@ public: static ITK_THREAD_RETURN_TYPE GetValueMultiThreadedPostProcess(void *arg); - virtual inline void GetValueThread(ThreadIdType threadID) const; + virtual inline void GetValueThread(ThreadIdType threadId) const; virtual inline void GetValueThreadPreProcess( - ThreadIdType itkNotUsed(threadID), + ThreadIdType itkNotUsed(threadId), bool itkNotUsed(withinSampleThread) ) const {} virtual inline bool GetValueThreadProcessSample( - ThreadIdType itkNotUsed(threadID), + ThreadIdType itkNotUsed(threadId), SizeValueType itkNotUsed(fixedImageSample), const MovingImagePointType & itkNotUsed(mappedPoint), double itkNotUsed(movingImageValue) ) const { return false; } virtual inline void GetValueThreadPostProcess( - ThreadIdType itkNotUsed(threadID), + ThreadIdType itkNotUsed(threadId), bool itkNotUsed(withinSampleThread) ) const {} @@ -546,21 +546,21 @@ public: static ITK_THREAD_RETURN_TYPE GetValueAndDerivativeMultiThreadedPostProcess(void *arg); - virtual inline void GetValueAndDerivativeThread(ThreadIdType threadID) const; + virtual inline void GetValueAndDerivativeThread(ThreadIdType threadId) const; virtual inline void GetValueAndDerivativeThreadPreProcess( - ThreadIdType itkNotUsed(threadID), + ThreadIdType itkNotUsed(threadId), bool itkNotUsed(withinSampleThread) ) const {} virtual inline bool GetValueAndDerivativeThreadProcessSample( - ThreadIdType itkNotUsed(threadID), + ThreadIdType itkNotUsed(threadId), SizeValueType itkNotUsed(fixedImageSample), const MovingImagePointType & itkNotUsed(mappedPoint), double itkNotUsed(movingImageValue), const ImageDerivativesType & itkNotUsed(movingImageGradientValue) ) const { return false; } virtual inline void GetValueAndDerivativeThreadPostProcess( - ThreadIdType itkNotUsed(threadID), + ThreadIdType itkNotUsed(threadId), bool itkNotUsed(withinSampleThread) ) const {} diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkImageToImageMetric.hxx index ae0c80f24bae3379671ae6611f97c7d61353fe25..f436adbe0abc5e572811c6717b8845e0f459ecbf 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageToImageMetric.hxx @@ -42,19 +42,19 @@ ImageToImageMetric< TFixedImage, TMovingImage > m_NumberOfPixelsCounted(0), - m_FixedImage(0), // has to be provided by the user. - m_MovingImage(0), // has to be provided by the user. + m_FixedImage(ITK_NULLPTR), // has to be provided by the user. + m_MovingImage(ITK_NULLPTR), // has to be provided by the user. - m_Transform(NULL), // has to be provided by the user. - m_ThreaderTransform(NULL), // constructed at initialization. + m_Transform(ITK_NULLPTR), // has to be provided by the user. + m_ThreaderTransform(ITK_NULLPTR), // constructed at initialization. - m_Interpolator(0), // has to be provided by the user. + m_Interpolator(ITK_NULLPTR), // has to be provided by the user. m_ComputeGradient(true), // metric computes gradient by default - m_GradientImage(NULL), // computed at initialization + m_GradientImage(ITK_NULLPTR), // computed at initialization - m_FixedImageMask(0), - m_MovingImageMask(0), + m_FixedImageMask(ITK_NULLPTR), + m_MovingImageMask(ITK_NULLPTR), m_NumberOfThreads(1), @@ -66,7 +66,7 @@ ImageToImageMetric< TFixedImage, TMovingImage > m_TransformIsBSpline(false), m_NumBSplineWeights(0), - m_BSplineTransform(NULL), + m_BSplineTransform(ITK_NULLPTR), m_BSplineTransformWeightsArray(), m_BSplineTransformIndicesArray(), m_BSplinePreTransformPointsArray(0), @@ -76,15 +76,15 @@ ImageToImageMetric< TFixedImage, TMovingImage > m_UseCachingOfBSplineWeights(true), m_BSplineTransformWeights(), m_BSplineTransformIndices(), - m_ThreaderBSplineTransformWeights(NULL), - m_ThreaderBSplineTransformIndices(NULL), + m_ThreaderBSplineTransformWeights(ITK_NULLPTR), + m_ThreaderBSplineTransformIndices(ITK_NULLPTR), m_InterpolatorIsBSpline(false), - m_BSplineInterpolator(NULL), - m_DerivativeCalculator(NULL), + m_BSplineInterpolator(ITK_NULLPTR), + m_DerivativeCalculator(ITK_NULLPTR), m_Threader(MultiThreaderType::New()), - m_ThreaderNumberOfMovingImageSamples(NULL), + m_ThreaderNumberOfMovingImageSamples(ITK_NULLPTR), m_WithinThreadPreProcess(false), m_WithinThreadPostProcess(false) { @@ -107,16 +107,16 @@ ImageToImageMetric< TFixedImage, TMovingImage > ::~ImageToImageMetric() { delete[] m_ThreaderNumberOfMovingImageSamples; - m_ThreaderNumberOfMovingImageSamples = NULL; + m_ThreaderNumberOfMovingImageSamples = ITK_NULLPTR; delete[] m_ThreaderTransform; - m_ThreaderTransform = NULL; + m_ThreaderTransform = ITK_NULLPTR; delete[] this->m_ThreaderBSplineTransformWeights; - this->m_ThreaderBSplineTransformWeights = NULL; + this->m_ThreaderBSplineTransformWeights = ITK_NULLPTR; delete[] this->m_ThreaderBSplineTransformIndices; - this->m_ThreaderBSplineTransformIndices = NULL; + this->m_ThreaderBSplineTransformIndices = ITK_NULLPTR; } /** @@ -433,7 +433,7 @@ throw ( ExceptionObject ) m_DerivativeCalculator->SetInputImage(this->m_MovingImage); - m_BSplineInterpolator = NULL; + m_BSplineInterpolator = ITK_NULLPTR; itkDebugMacro("Interpolator is not BSpline"); } else @@ -442,7 +442,7 @@ throw ( ExceptionObject ) m_BSplineInterpolator->SetNumberOfThreads(m_NumberOfThreads); m_BSplineInterpolator->UseImageDirectionOn(); - m_DerivativeCalculator = NULL; + m_DerivativeCalculator = ITK_NULLPTR; itkDebugMacro("Interpolator is BSpline"); } @@ -463,7 +463,7 @@ throw ( ExceptionObject ) if ( !testPtr2 ) { m_TransformIsBSpline = false; - m_BSplineTransform = NULL; + m_BSplineTransform = ITK_NULLPTR; itkDebugMacro("Transform is not BSplineDeformable"); } else @@ -484,10 +484,10 @@ throw ( ExceptionObject ) this->m_BSplineTransformIndices.SetSize(1); delete[] this->m_ThreaderBSplineTransformWeights; - this->m_ThreaderBSplineTransformWeights = NULL; + this->m_ThreaderBSplineTransformWeights = ITK_NULLPTR; delete[] this->m_ThreaderBSplineTransformIndices; - this->m_ThreaderBSplineTransformIndices = NULL; + this->m_ThreaderBSplineTransformIndices = ITK_NULLPTR; if ( this->m_UseCachingOfBSplineWeights ) { @@ -893,14 +893,14 @@ ImageToImageMetric< TFixedImage, TMovingImage > MovingImagePointType & mappedPoint, bool & sampleOk, double & movingImageValue, - ThreadIdType threadID) const + ThreadIdType threadId) const { sampleOk = true; TransformType *transform; - if ( threadID > 0 ) + if ( threadId > 0 ) { - transform = this->m_ThreaderTransform[threadID - 1]; + transform = this->m_ThreaderTransform[threadId - 1]; } else { @@ -949,10 +949,10 @@ ImageToImageMetric< TFixedImage, TMovingImage > BSplineTransformWeightsType * weightsHelper; BSplineTransformIndexArrayType *indicesHelper; - if ( threadID > 0 ) + if ( threadId > 0 ) { - weightsHelper = &( this->m_ThreaderBSplineTransformWeights[threadID - 1] ); - indicesHelper = &( this->m_ThreaderBSplineTransformIndices[threadID - 1] ); + weightsHelper = &( this->m_ThreaderBSplineTransformWeights[threadId - 1] ); + indicesHelper = &( this->m_ThreaderBSplineTransformIndices[threadId - 1] ); } else { @@ -984,7 +984,7 @@ ImageToImageMetric< TFixedImage, TMovingImage > sampleOk = sampleOk && m_BSplineInterpolator->IsInsideBuffer(mappedPoint); if ( sampleOk ) { - movingImageValue = m_BSplineInterpolator->Evaluate(mappedPoint, threadID); + movingImageValue = m_BSplineInterpolator->Evaluate(mappedPoint, threadId); } } else @@ -1011,15 +1011,15 @@ ImageToImageMetric< TFixedImage, TMovingImage > bool & sampleOk, double & movingImageValue, ImageDerivativesType & movingImageGradient, - ThreadIdType threadID) const + ThreadIdType threadId) const { TransformType *transform; sampleOk = true; - if ( threadID > 0 ) + if ( threadId > 0 ) { - transform = this->m_ThreaderTransform[threadID - 1]; + transform = this->m_ThreaderTransform[threadId - 1]; } else { @@ -1068,10 +1068,10 @@ ImageToImageMetric< TFixedImage, TMovingImage > BSplineTransformWeightsType * weightsHelper; BSplineTransformIndexArrayType *indicesHelper; - if ( threadID > 0 ) + if ( threadId > 0 ) { - weightsHelper = &( this->m_ThreaderBSplineTransformWeights[threadID - 1] ); - indicesHelper = &( this->m_ThreaderBSplineTransformIndices[threadID - 1] ); + weightsHelper = &( this->m_ThreaderBSplineTransformWeights[threadId - 1] ); + indicesHelper = &( this->m_ThreaderBSplineTransformIndices[threadId - 1] ); } else { @@ -1106,7 +1106,7 @@ ImageToImageMetric< TFixedImage, TMovingImage > this->m_BSplineInterpolator->EvaluateValueAndDerivative(mappedPoint, movingImageValue, movingImageGradient, - threadID); + threadId); } } else @@ -1115,7 +1115,7 @@ ImageToImageMetric< TFixedImage, TMovingImage > sampleOk = sampleOk && m_Interpolator->IsInsideBuffer(mappedPoint); if ( sampleOk ) { - this->ComputeImageDerivatives(mappedPoint, movingImageGradient, threadID); + this->ComputeImageDerivatives(mappedPoint, movingImageGradient, threadId); movingImageValue = this->m_Interpolator->Evaluate(mappedPoint); } } @@ -1132,13 +1132,13 @@ void ImageToImageMetric< TFixedImage, TMovingImage > ::ComputeImageDerivatives(const MovingImagePointType & mappedPoint, ImageDerivativesType & gradient, - ThreadIdType threadID) const + ThreadIdType threadId) const { if ( m_InterpolatorIsBSpline ) { // Computed moving image gradient using derivative BSpline kernel. gradient = m_BSplineInterpolator->EvaluateDerivative(mappedPoint, - threadID); + threadId); } else { @@ -1182,9 +1182,9 @@ ImageToImageMetric< TFixedImage, TMovingImage > const_cast< void * >( static_cast< const void * >( &m_ThreaderParameter ) ) ); m_Threader->SingleMethodExecute(); - for ( ThreadIdType threadID = 0; threadID < m_NumberOfThreads - 1; threadID++ ) + for ( ThreadIdType threadId = 0; threadId < m_NumberOfThreads - 1; threadId++ ) { - this->m_NumberOfPixelsCounted += m_ThreaderNumberOfMovingImageSamples[threadID]; + this->m_NumberOfPixelsCounted += m_ThreaderNumberOfMovingImageSamples[threadId]; } } @@ -1206,15 +1206,15 @@ ITK_THREAD_RETURN_TYPE ImageToImageMetric< TFixedImage, TMovingImage > ::GetValueMultiThreadedPreProcess(void *arg) { - ThreadIdType threadID; + ThreadIdType threadId; MultiThreaderParameterType *mtParam; - threadID = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; + threadId = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; mtParam = (MultiThreaderParameterType *) ( ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->UserData ); - mtParam->metric->GetValueThreadPreProcess(threadID, false); + mtParam->metric->GetValueThreadPreProcess(threadId, false); return ITK_THREAD_RETURN_VALUE; } @@ -1227,15 +1227,15 @@ ITK_THREAD_RETURN_TYPE ImageToImageMetric< TFixedImage, TMovingImage > ::GetValueMultiThreaded(void *arg) { - ThreadIdType threadID; + ThreadIdType threadId; MultiThreaderParameterType *mtParam; - threadID = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; + threadId = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; mtParam = (MultiThreaderParameterType *) ( ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->UserData ); - mtParam->metric->GetValueThread(threadID); + mtParam->metric->GetValueThread(threadId); return ITK_THREAD_RETURN_VALUE; } @@ -1248,15 +1248,15 @@ ITK_THREAD_RETURN_TYPE ImageToImageMetric< TFixedImage, TMovingImage > ::GetValueMultiThreadedPostProcess(void *arg) { - ThreadIdType threadID; + ThreadIdType threadId; MultiThreaderParameterType *mtParam; - threadID = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; + threadId = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; mtParam = (MultiThreaderParameterType *) ( ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->UserData ); - mtParam->metric->GetValueThreadPostProcess(threadID, false); + mtParam->metric->GetValueThreadPostProcess(threadId, false); return ITK_THREAD_RETURN_VALUE; } @@ -1264,15 +1264,15 @@ ImageToImageMetric< TFixedImage, TMovingImage > template< typename TFixedImage, typename TMovingImage > void ImageToImageMetric< TFixedImage, TMovingImage > -::GetValueThread(ThreadIdType threadID) const +::GetValueThread(ThreadIdType threadId) const { // Figure out how many samples to process int chunkSize = m_NumberOfFixedImageSamples / m_NumberOfThreads; // Skip to this thread's samples to process - unsigned int fixedImageSample = threadID * chunkSize; + unsigned int fixedImageSample = threadId * chunkSize; - if ( threadID == m_NumberOfThreads - 1 ) + if ( threadId == m_NumberOfThreads - 1 ) { chunkSize = m_NumberOfFixedImageSamples - ( ( m_NumberOfThreads - 1 ) @@ -1282,7 +1282,7 @@ ImageToImageMetric< TFixedImage, TMovingImage > if ( m_WithinThreadPreProcess ) { - this->GetValueThreadPreProcess(threadID, true); + this->GetValueThreadPreProcess(threadId, true); } // Process the samples @@ -1294,12 +1294,12 @@ ImageToImageMetric< TFixedImage, TMovingImage > double movingImageValue; // Get moving image value this->TransformPoint(fixedImageSample, mappedPoint, sampleOk, movingImageValue, - threadID); + threadId); if ( sampleOk ) { // CALL USER FUNCTION - if ( GetValueThreadProcessSample(threadID, fixedImageSample, + if ( GetValueThreadProcessSample(threadId, fixedImageSample, mappedPoint, movingImageValue) ) { ++numSamples; @@ -1307,9 +1307,9 @@ ImageToImageMetric< TFixedImage, TMovingImage > } } - if ( threadID > 0 ) + if ( threadId > 0 ) { - m_ThreaderNumberOfMovingImageSamples[threadID - 1] = numSamples; + m_ThreaderNumberOfMovingImageSamples[threadId - 1] = numSamples; } else { @@ -1318,7 +1318,7 @@ ImageToImageMetric< TFixedImage, TMovingImage > if ( m_WithinThreadPostProcess ) { - this->GetValueThreadPostProcess(threadID, true); + this->GetValueThreadPostProcess(threadId, true); } } @@ -1345,9 +1345,9 @@ ImageToImageMetric< TFixedImage, TMovingImage > const_cast< void * >( static_cast< const void * >( &m_ThreaderParameter ) ) ); m_Threader->SingleMethodExecute(); - for ( ThreadIdType threadID = 0; threadID < m_NumberOfThreads - 1; threadID++ ) + for ( ThreadIdType threadId = 0; threadId < m_NumberOfThreads - 1; threadId++ ) { - this->m_NumberOfPixelsCounted += m_ThreaderNumberOfMovingImageSamples[threadID]; + this->m_NumberOfPixelsCounted += m_ThreaderNumberOfMovingImageSamples[threadId]; } } @@ -1369,15 +1369,15 @@ ITK_THREAD_RETURN_TYPE ImageToImageMetric< TFixedImage, TMovingImage > ::GetValueAndDerivativeMultiThreadedPreProcess(void *arg) { - ThreadIdType threadID; + ThreadIdType threadId; MultiThreaderParameterType *mtParam; - threadID = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; + threadId = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; mtParam = (MultiThreaderParameterType *) ( ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->UserData ); - mtParam->metric->GetValueAndDerivativeThreadPreProcess(threadID, false); + mtParam->metric->GetValueAndDerivativeThreadPreProcess(threadId, false); return ITK_THREAD_RETURN_VALUE; } @@ -1390,15 +1390,15 @@ ITK_THREAD_RETURN_TYPE ImageToImageMetric< TFixedImage, TMovingImage > ::GetValueAndDerivativeMultiThreaded(void *arg) { - ThreadIdType threadID; + ThreadIdType threadId; MultiThreaderParameterType *mtParam; - threadID = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; + threadId = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; mtParam = (MultiThreaderParameterType *) ( ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->UserData ); - mtParam->metric->GetValueAndDerivativeThread(threadID); + mtParam->metric->GetValueAndDerivativeThread(threadId); return ITK_THREAD_RETURN_VALUE; } @@ -1411,15 +1411,15 @@ ITK_THREAD_RETURN_TYPE ImageToImageMetric< TFixedImage, TMovingImage > ::GetValueAndDerivativeMultiThreadedPostProcess(void *arg) { - ThreadIdType threadID; + ThreadIdType threadId; MultiThreaderParameterType *mtParam; - threadID = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; + threadId = ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->ThreadID; mtParam = (MultiThreaderParameterType *) ( ( (MultiThreaderType::ThreadInfoStruct *)( arg ) )->UserData ); - mtParam->metric->GetValueAndDerivativeThreadPostProcess(threadID, false); + mtParam->metric->GetValueAndDerivativeThreadPostProcess(threadId, false); return ITK_THREAD_RETURN_VALUE; } @@ -1427,15 +1427,15 @@ ImageToImageMetric< TFixedImage, TMovingImage > template< typename TFixedImage, typename TMovingImage > void ImageToImageMetric< TFixedImage, TMovingImage > -::GetValueAndDerivativeThread(ThreadIdType threadID) const +::GetValueAndDerivativeThread(ThreadIdType threadId) const { // Figure out how many samples to process int chunkSize = m_NumberOfFixedImageSamples / m_NumberOfThreads; // Skip to this thread's samples to process - unsigned int fixedImageSample = threadID * chunkSize; + unsigned int fixedImageSample = threadId * chunkSize; - if ( threadID == m_NumberOfThreads - 1 ) + if ( threadId == m_NumberOfThreads - 1 ) { chunkSize = m_NumberOfFixedImageSamples - ( ( m_NumberOfThreads - 1 ) @@ -1446,7 +1446,7 @@ ImageToImageMetric< TFixedImage, TMovingImage > if ( m_WithinThreadPreProcess ) { - this->GetValueAndDerivativeThreadPreProcess(threadID, true); + this->GetValueAndDerivativeThreadPreProcess(threadId, true); } // Process the samples @@ -1459,12 +1459,12 @@ ImageToImageMetric< TFixedImage, TMovingImage > // Get moving image value TransformPointWithDerivatives(fixedImageSample, mappedPoint, sampleOk, movingImageValue, movingImageGradientValue, - threadID); + threadId); if ( sampleOk ) { // CALL USER FUNCTION - if ( this->GetValueAndDerivativeThreadProcessSample(threadID, + if ( this->GetValueAndDerivativeThreadProcessSample(threadId, fixedImageSample, mappedPoint, movingImageValue, @@ -1475,9 +1475,9 @@ ImageToImageMetric< TFixedImage, TMovingImage > } } - if ( threadID > 0 ) + if ( threadId > 0 ) { - m_ThreaderNumberOfMovingImageSamples[threadID - 1] = numSamples; + m_ThreaderNumberOfMovingImageSamples[threadId - 1] = numSamples; } else { @@ -1486,7 +1486,7 @@ ImageToImageMetric< TFixedImage, TMovingImage > if ( m_WithinThreadPostProcess ) { - this->GetValueAndDerivativeThreadPostProcess(threadID, true); + this->GetValueAndDerivativeThreadPostProcess(threadId, true); } } @@ -1575,13 +1575,13 @@ void ImageToImageMetric< TFixedImage, TMovingImage > ::SynchronizeTransforms() const { - for ( ThreadIdType threadID = 0; threadID < m_NumberOfThreads - 1; threadID++ ) + for ( ThreadIdType threadId = 0; threadId < m_NumberOfThreads - 1; threadId++ ) { /** Set the fixed parameters first. Some transforms have parameters which depend on the values of the fixed parameters. For instance, the BSplineTransform checks the grid size (part of the fixed parameters) before setting the parameters. */ - this->m_ThreaderTransform[threadID]->SetFixedParameters( this->m_Transform->GetFixedParameters() ); - this->m_ThreaderTransform[threadID]->SetParameters( this->m_Transform->GetParameters() ); + this->m_ThreaderTransform[threadId]->SetFixedParameters( this->m_Transform->GetFixedParameters() ); + this->m_ThreaderTransform[threadId]->SetParameters( this->m_Transform->GetParameters() ); } } } // end namespace itk diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectMetric.h b/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectMetric.h index 76798120dc86a22013e2b5417b5164f0f410921f..92fd892fa85ae319418b553fc723b0f5c999a397 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectMetric.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectMetric.h @@ -168,7 +168,7 @@ protected: virtual ~ImageToSpatialObjectMetric() {} ImageToSpatialObjectMetric(const Self &) {} void operator=(const Self &) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; MeasureType m_MatchMeasure; DerivativeType m_MatchMeasureDerivatives; diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectMetric.hxx index 18d83ed31912cfa94857a6d42f15ca6a844fd71e..6bbba44c02149b1ffd93c00534800b782eeaf01c 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectMetric.hxx @@ -25,12 +25,13 @@ namespace itk /** Constructor */ template< typename TFixedImage, typename TMovingSpatialObject > ImageToSpatialObjectMetric< TFixedImage, TMovingSpatialObject > -::ImageToSpatialObjectMetric() +::ImageToSpatialObjectMetric(): + m_MatchMeasure(0) { - m_FixedImage = 0; // has to be provided by the user. - m_MovingSpatialObject = 0; // has to be provided by the user. - m_Transform = 0; // has to be provided by the user. - m_Interpolator = 0; // has to be provided by the user. + m_FixedImage = ITK_NULLPTR; // has to be provided by the user. + m_MovingSpatialObject = ITK_NULLPTR; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. + m_Interpolator = ITK_NULLPTR; // has to be provided by the user. } /** diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.h b/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.h index 967eba2bc233a7e78f2ee581d1991796d96cb17a..82f2778dd7c0c116b1ac9609968ed9a932d99fb6 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.h @@ -174,11 +174,11 @@ public: * output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** Method to return the latest modified time of this object or * any of its cached ivars */ - ModifiedTimeType GetMTime() const; + virtual ModifiedTimeType GetMTime() const ITK_OVERRIDE; #ifdef ITKV3_COMPATIBILITY // StartRegistration is an old API from before @@ -198,11 +198,11 @@ public: protected: ImageToSpatialObjectRegistrationMethod(); virtual ~ImageToSpatialObjectRegistrationMethod() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Method invoked by the pipeline in order to trigger the computation of * the registration. */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Initialize by setting the interconnects between the components. */ void Initialize() diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.hxx index 09a3e5626d0fa019066ffad3b1ab9e7950fd32d6..5a64df1b72dfaa232ba1372383c86e7b21988ab3 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.hxx @@ -29,12 +29,12 @@ ImageToSpatialObjectRegistrationMethod< TFixedImage, TMovingSpatialObject > { this->SetNumberOfRequiredOutputs(1); // for the Transform - m_FixedImage = 0; // has to be provided by the user. - m_MovingSpatialObject = 0; // has to be provided by the user. - m_Transform = 0; // has to be provided by the user. - m_Interpolator = 0; // has to be provided by the user. - m_Metric = 0; // has to be provided by the user. - m_Optimizer = 0; // has to be provided by the user. + m_FixedImage = ITK_NULLPTR; // has to be provided by the user. + m_MovingSpatialObject = ITK_NULLPTR; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. + m_Interpolator = ITK_NULLPTR; // has to be provided by the user. + m_Metric = ITK_NULLPTR; // has to be provided by the user. + m_Optimizer = ITK_NULLPTR; // has to be provided by the user. m_InitialTransformParameters = ParametersType(1); m_LastTransformParameters = ParametersType(1); @@ -200,7 +200,7 @@ ImageToSpatialObjectRegistrationMethod< TFixedImage, TMovingSpatialObject > break; default: itkExceptionMacro("MakeOutput request for an output number larger than the expected number of outputs"); - return 0; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkKappaStatisticImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkKappaStatisticImageToImageMetric.hxx index 2287f74b6689147faaadfc4207f228bf49c18612..3583744d5a6837bc8e52fe0f8ccea74cd3df20fd 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkKappaStatisticImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkKappaStatisticImageToImageMetric.hxx @@ -211,7 +211,10 @@ KappaStatisticImageToImageMetric<TFixedImage, TMovingImage> int movingArea = 0; int intersection = 0; - TransformJacobianType jacobian; + TransformJacobianType jacobian(TFixedImage::ImageDimension, + this->m_Transform->GetNumberOfParameters()); + TransformJacobianType jacobianCache(TFixedImage::ImageDimension, + TFixedImage::ImageDimension); ti.GoToBegin(); while( !ti.IsAtEnd() ) @@ -255,8 +258,10 @@ KappaStatisticImageToImageMetric<TFixedImage, TMovingImage> intersection++; } - this->m_Transform->ComputeJacobianWithRespectToParameters( - inputPoint, jacobian); + this->m_Transform-> + ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); this->m_NumberOfPixelsCounted++; diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkKullbackLeiblerCompareHistogramImageToImageMetric.h b/Utilities/ITK/Modules/Registration/Common/include/itkKullbackLeiblerCompareHistogramImageToImageMetric.h index 4709ae0da691fa6e90fabc15271e316b2a6a0d55..e9a1314144ee727a162174214c5b4e150366602b 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkKullbackLeiblerCompareHistogramImageToImageMetric.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkKullbackLeiblerCompareHistogramImageToImageMetric.h @@ -41,7 +41,7 @@ namespace itk * pp. 525 - 532. * * The metric is given by KL(P_test||P_train) - * = Sum_{i1,i2} P_test(i1,i2) vcl_log(P_test(i1,i2)/P_train(i1,i2)) + * = Sum_{i1,i2} P_test(i1,i2) std::log(P_test(i1,i2)/P_train(i1,i2)) * where P_test and P_train are probabilities given my normalized * histograms, and i1 and i2 are the intensity bins in the histogram. * diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkKullbackLeiblerCompareHistogramImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkKullbackLeiblerCompareHistogramImageToImageMetric.hxx index 3553b47308e06be42f2fb3cd087d1f7d43446041..c8fbd4b378d1077f775d2974a6af9fd42dee7150 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkKullbackLeiblerCompareHistogramImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkKullbackLeiblerCompareHistogramImageToImageMetric.hxx @@ -68,7 +68,7 @@ KullbackLeiblerCompareHistogramImageToImageMetric< TFixedImage, \ double TrainingFreq = training_it.GetFrequency() + m_Epsilon; double MeasuredFreq = measured_it.GetFrequency() + m_Epsilon; - KullbackLeibler += MeasuredFreq * vcl_log(MeasuredFreq / TrainingFreq); + KullbackLeibler += MeasuredFreq * std::log(MeasuredFreq / TrainingFreq); ++measured_it; ++training_it; @@ -91,7 +91,7 @@ KullbackLeiblerCompareHistogramImageToImageMetric< TFixedImage, \ + this->GetHistogramSize()[0] * this->GetHistogramSize()[1] * m_Epsilon; KullbackLeibler = KullbackLeibler / static_cast< MeasureType >( AdjustedTotalMeasuredFreq ) - - vcl_log(AdjustedTotalMeasuredFreq / AdjustedTotalTrainingFreq); + - std::log(AdjustedTotalMeasuredFreq / AdjustedTotalTrainingFreq); return KullbackLeibler; } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.h b/Utilities/ITK/Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.h index 1dd1f238f2b274e66e212d37f9e15289c48dcc8e..fda323450d3dfde54a4ed27f610dd09e876b67fb 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.h @@ -91,8 +91,6 @@ namespace itk * * Notes: * 1. This class returns the negative mutual information value. - * 2. This class in not thread safe due the private data structures - * used to the store the sampled points and the marginal and joint pdfs. * * References: * [1] "Nonrigid multimodality image registration" @@ -227,9 +225,9 @@ public: */ const typename JointPDFType::Pointer GetJointPDF () const { - if( this->m_MMIMetricPerThreadVariables == NULL ) + if( this->m_MMIMetricPerThreadVariables == ITK_NULLPTR ) { - return JointPDFType::Pointer(NULL); + return JointPDFType::Pointer(ITK_NULLPTR); } return this->m_MMIMetricPerThreadVariables[0].JointPDF; } @@ -242,9 +240,9 @@ public: */ const typename JointPDFDerivativesType::Pointer GetJointPDFDerivatives () const { - if( this->m_MMIMetricPerThreadVariables == NULL ) + if( this->m_MMIMetricPerThreadVariables == ITK_NULLPTR ) { - return JointPDFDerivativesType::Pointer(NULL); + return JointPDFDerivativesType::Pointer(ITK_NULLPTR); } return this->m_MMIMetricPerThreadVariables[0].JointPDFDerivatives; } @@ -279,22 +277,22 @@ private: void ComputeFixedImageParzenWindowIndices( FixedImageSampleContainer & samples); /** Compute PDF derivative contribution for each parameter. */ - void ComputePDFDerivatives(ThreadIdType threadID, unsigned int sampleNumber, int movingImageParzenWindowIndex, + void ComputePDFDerivatives(ThreadIdType threadId, unsigned int sampleNumber, int movingImageParzenWindowIndex, const ImageDerivativesType & movingImageGradientValue, PDFValueType cubicBSplineDerivativeValue) const; - virtual void GetValueThreadPreProcess(ThreadIdType threadID, bool withinSampleThread) const; - virtual void GetValueThreadPostProcess(ThreadIdType threadID, bool withinSampleThread) const; + virtual void GetValueThreadPreProcess(ThreadIdType threadId, bool withinSampleThread) const; + virtual void GetValueThreadPostProcess(ThreadIdType threadId, bool withinSampleThread) const; //NOTE: The signature in base class requires that movingImageValue is of type double - virtual bool GetValueThreadProcessSample(ThreadIdType threadID, SizeValueType fixedImageSample, + virtual bool GetValueThreadProcessSample(ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & mappedPoint, double movingImageValue) const; - virtual void GetValueAndDerivativeThreadPreProcess( ThreadIdType threadID, bool withinSampleThread) const; - virtual void GetValueAndDerivativeThreadPostProcess( ThreadIdType threadID, bool withinSampleThread) const; + virtual void GetValueAndDerivativeThreadPreProcess( ThreadIdType threadId, bool withinSampleThread) const; + virtual void GetValueAndDerivativeThreadPostProcess( ThreadIdType threadId, bool withinSampleThread) const; //NOTE: The signature in base class requires that movingImageValue is of type double - virtual bool GetValueAndDerivativeThreadProcessSample(ThreadIdType threadID, SizeValueType fixedImageSample, + virtual bool GetValueAndDerivativeThreadProcessSample(ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & mappedPoint, double movingImageValue, const ImageDerivativesType & movingImageGradientValue) const; diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx index 27a8f7da380af5c619cff10f91f82d675334b553..d0f157d1145d01bfb39e47d30166c4a383f5fb4c 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMattesMutualInformationImageToImageMetric.hxx @@ -39,20 +39,22 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> m_NumberOfHistogramBins(50), m_MovingImageNormalizedMin(0.0), m_FixedImageNormalizedMin(0.0), + m_FixedImageTrueMin(0.0), + m_FixedImageTrueMax(0.0), m_MovingImageTrueMin(0.0), m_MovingImageTrueMax(0.0), m_FixedImageBinSize(0.0), m_MovingImageBinSize(0.0), - m_CubicBSplineKernel(NULL), - m_CubicBSplineDerivativeKernel(NULL), + m_CubicBSplineKernel(ITK_NULLPTR), + m_CubicBSplineDerivativeKernel(ITK_NULLPTR), m_PRatioArray(0,0), // Initialize memory m_MovingImageMarginalPDF(0), - m_MMIMetricPerThreadVariables(NULL), + m_MMIMetricPerThreadVariables(ITK_NULLPTR), m_UseExplicitPDFDerivatives(true), m_ImplicitDerivativesSecondPass(false) @@ -125,46 +127,70 @@ throw ( ExceptionObject ) * in computing the range of intensity values. */ - this->m_FixedImageTrueMin = vcl_numeric_limits<typename TFixedImage::PixelType>::max(); - this->m_FixedImageTrueMax = vcl_numeric_limits<typename TFixedImage::PixelType>::min(); - this->m_MovingImageTrueMin = vcl_numeric_limits<typename TMovingImage::PixelType>::max(); - this->m_MovingImageTrueMax = vcl_numeric_limits<typename TMovingImage::PixelType>::min(); + this->m_FixedImageTrueMin = std::numeric_limits<typename TFixedImage::PixelType>::max(); + this->m_FixedImageTrueMax = std::numeric_limits<typename TFixedImage::PixelType>::min(); + this->m_MovingImageTrueMin = std::numeric_limits<typename TMovingImage::PixelType>::max(); + this->m_MovingImageTrueMax = std::numeric_limits<typename TMovingImage::PixelType>::min(); // We need to make robust measures only over the requested mask region itk::ImageRegionConstIteratorWithIndex<TFixedImage> fi(this->m_FixedImage, this->m_FixedImage->GetBufferedRegion() ); - while( !fi.IsAtEnd() ) - { - typename TFixedImage::PointType fixedSpacePhysicalPoint; - this->m_FixedImage->TransformIndexToPhysicalPoint(fi.GetIndex(), fixedSpacePhysicalPoint); - // A null mask implies entire space is to be used. - if( this->m_FixedImageMask.IsNull() - || this->m_FixedImageMask->IsInside(fixedSpacePhysicalPoint) - ) + const bool fixedMaskIsPresent = !(this->m_FixedImageMask.IsNull()); + if( fixedMaskIsPresent ) { - const typename TFixedImage::PixelType currValue = fi.Get(); - this->m_FixedImageTrueMin = (m_FixedImageTrueMin < currValue) ? this->m_FixedImageTrueMin : currValue; - this->m_FixedImageTrueMax = (m_FixedImageTrueMax > currValue) ? this->m_FixedImageTrueMax : currValue; + typename TFixedImage::PointType fixedSpacePhysicalPoint; + while( !fi.IsAtEnd() ) + { + this->m_FixedImage->TransformIndexToPhysicalPoint(fi.GetIndex(), fixedSpacePhysicalPoint); + const bool shouldCheckPixelIntensity = this->m_FixedImageMask->IsInside( fixedSpacePhysicalPoint ); + if( shouldCheckPixelIntensity ) + { + const PDFValueType & currValue = fi.Get(); + this->m_FixedImageTrueMin = std::min(m_FixedImageTrueMin, currValue); + this->m_FixedImageTrueMax = std::max(m_FixedImageTrueMax, currValue); + } + ++fi; + } + } + else + { + while( !fi.IsAtEnd() ) + { + const PDFValueType & currValue = fi.Get(); + this->m_FixedImageTrueMin = std::min(m_FixedImageTrueMin, currValue); + this->m_FixedImageTrueMax = std::max(m_FixedImageTrueMax, currValue); + ++fi; + } } - ++fi; - } { itk::ImageRegionConstIteratorWithIndex<TMovingImage> mi(this->m_MovingImage, this->m_MovingImage->GetBufferedRegion() ); - while( !mi.IsAtEnd() ) + const bool movingMaskIsPresent = !(this->m_MovingImageMask.IsNull()); + if( movingMaskIsPresent ) { typename TMovingImage::PointType movingSpacePhysicalPoint; - this->m_MovingImage->TransformIndexToPhysicalPoint(mi.GetIndex(), movingSpacePhysicalPoint); - // A null mask implies entire space is to be used. - if( this->m_MovingImageMask.IsNull() - || this->m_MovingImageMask->IsInside(movingSpacePhysicalPoint) - ) + while( !mi.IsAtEnd() ) + { + this->m_MovingImage->TransformIndexToPhysicalPoint(mi.GetIndex(), movingSpacePhysicalPoint); + const bool shouldCheckPixelIntensity = this->m_MovingImageMask->IsInside(movingSpacePhysicalPoint); + if( shouldCheckPixelIntensity ) + { + const PDFValueType & currValue = mi.Get(); + this->m_MovingImageTrueMin = std::min(m_MovingImageTrueMin, currValue); + this->m_MovingImageTrueMax = std::max(m_MovingImageTrueMax, currValue); + } + ++mi; + } + } + else + { + while( !mi.IsAtEnd() ) { - const typename TMovingImage::PixelType currValue = mi.Get(); - this->m_MovingImageTrueMin = (m_MovingImageTrueMin < currValue) ? this->m_MovingImageTrueMin : currValue; - this->m_MovingImageTrueMax = (m_MovingImageTrueMax > currValue) ? this->m_MovingImageTrueMax : currValue; + const PDFValueType & currValue = mi.Get(); + this->m_MovingImageTrueMin = std::min(m_MovingImageTrueMin, currValue); + this->m_MovingImageTrueMax = std::max(m_MovingImageTrueMax, currValue); + ++mi; } - ++mi; } } @@ -218,10 +244,10 @@ throw ( ExceptionObject ) { const int binRange = this->m_NumberOfHistogramBins / this->m_NumberOfThreads; - for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads; threadID++ ) + for( ThreadIdType threadId = 0; threadId < this->m_NumberOfThreads; threadId++ ) { - this->m_MMIMetricPerThreadVariables[threadID].JointPDFStartBin = threadID * binRange; - this->m_MMIMetricPerThreadVariables[threadID].JointPDFEndBin = ( threadID + 1 ) * binRange - 1; + this->m_MMIMetricPerThreadVariables[threadId].JointPDFStartBin = threadId * binRange; + this->m_MMIMetricPerThreadVariables[threadId].JointPDFEndBin = ( threadId + 1 ) * binRange - 1; } // Ensure that the last EndBin range contains the last histogram bin @@ -259,13 +285,13 @@ throw ( ExceptionObject ) * Allocate memory for the joint PDF and joint PDF derivatives. * The joint PDF and joint PDF derivatives are store as itk::Image. */ - for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads; ++threadID ) + for( ThreadIdType threadId = 0; threadId < this->m_NumberOfThreads; ++threadId ) { - this->m_MMIMetricPerThreadVariables[threadID].JointPDF = JointPDFType::New(); - this->m_MMIMetricPerThreadVariables[threadID].JointPDF->SetRegions(jointPDFRegion); - this->m_MMIMetricPerThreadVariables[threadID].JointPDF->SetOrigin(origin); - this->m_MMIMetricPerThreadVariables[threadID].JointPDF->SetSpacing(spacing); - this->m_MMIMetricPerThreadVariables[threadID].JointPDF->Allocate(); + this->m_MMIMetricPerThreadVariables[threadId].JointPDF = JointPDFType::New(); + this->m_MMIMetricPerThreadVariables[threadId].JointPDF->SetRegions(jointPDFRegion); + this->m_MMIMetricPerThreadVariables[threadId].JointPDF->SetOrigin(origin); + this->m_MMIMetricPerThreadVariables[threadId].JointPDF->SetSpacing(spacing); + this->m_MMIMetricPerThreadVariables[threadId].JointPDF->Allocate(); } } @@ -301,11 +327,11 @@ throw ( ExceptionObject ) } // Set the regions and allocate - for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads; threadID++ ) + for( ThreadIdType threadId = 0; threadId < this->m_NumberOfThreads; threadId++ ) { - this->m_MMIMetricPerThreadVariables[threadID].JointPDFDerivatives = JointPDFDerivativesType::New(); - this->m_MMIMetricPerThreadVariables[threadID].JointPDFDerivatives->SetRegions( jointPDFDerivativesRegion); - this->m_MMIMetricPerThreadVariables[threadID].JointPDFDerivatives->Allocate(); + this->m_MMIMetricPerThreadVariables[threadId].JointPDFDerivatives = JointPDFDerivativesType::New(); + this->m_MMIMetricPerThreadVariables[threadId].JointPDFDerivatives->SetRegions( jointPDFDerivativesRegion); + this->m_MMIMetricPerThreadVariables[threadId].JointPDFDerivatives->Allocate(); } } } @@ -313,10 +339,10 @@ throw ( ExceptionObject ) { // Deallocate the memory that may have been allocated for // previous runs of the metric. - for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads; ++threadID ) + for( ThreadIdType threadId = 0; threadId < this->m_NumberOfThreads; ++threadId ) { // Not needed if this->m_UseExplicitPDFDerivatives=false - this->m_MMIMetricPerThreadVariables[threadID].JointPDFDerivatives = NULL; + this->m_MMIMetricPerThreadVariables[threadId].JointPDFDerivatives = ITK_NULLPTR; } /** Allocate memory for helper array that will contain the pRatios @@ -326,10 +352,10 @@ throw ( ExceptionObject ) this->m_PRatioArray.SetSize(this->m_NumberOfHistogramBins, this->m_NumberOfHistogramBins); this->m_PRatioArray.Fill(0.0); - for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads; threadID++ ) + for( ThreadIdType threadId = 0; threadId < this->m_NumberOfThreads; threadId++ ) { - this->m_MMIMetricPerThreadVariables[threadID].MetricDerivative.SetSize( this->GetNumberOfParameters() ); - this->m_MMIMetricPerThreadVariables[threadID].MetricDerivative.Fill(NumericTraits<MeasureType>::Zero); + this->m_MMIMetricPerThreadVariables[threadId].MetricDerivative.SetSize( this->GetNumberOfParameters() ); + this->m_MMIMetricPerThreadVariables[threadId].MetricDerivative.Fill(NumericTraits<MeasureType>::Zero); } } /** @@ -388,21 +414,21 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> template <typename TFixedImage, typename TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> -::GetValueThreadPreProcess(ThreadIdType threadID, +::GetValueThreadPreProcess(ThreadIdType threadId, bool withinSampleThread) const { - this->Superclass::GetValueThreadPreProcess(threadID, withinSampleThread); + this->Superclass::GetValueThreadPreProcess(threadId, withinSampleThread); - this->m_MMIMetricPerThreadVariables[threadID].JointPDF->FillBuffer(0.0F); + this->m_MMIMetricPerThreadVariables[threadId].JointPDF->FillBuffer(0.0F); - this->m_MMIMetricPerThreadVariables[threadID].FixedImageMarginalPDF = std::vector<PDFValueType>( + this->m_MMIMetricPerThreadVariables[threadId].FixedImageMarginalPDF = std::vector<PDFValueType>( m_NumberOfHistogramBins, 0.0F); } template <typename TFixedImage, typename TMovingImage> inline bool MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> -::GetValueThreadProcessSample(ThreadIdType threadID, +::GetValueThreadProcessSample(ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue) const @@ -445,11 +471,11 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> const unsigned int fixedImageParzenWindowIndex = this->m_FixedImageSamples[fixedImageSample].valueIndex; - this->m_MMIMetricPerThreadVariables[threadID].FixedImageMarginalPDF[fixedImageParzenWindowIndex] += 1; + this->m_MMIMetricPerThreadVariables[threadId].FixedImageMarginalPDF[fixedImageParzenWindowIndex] += 1; // Pointer to affected bin to be updated - JointPDFValueType *pdfPtr = this->m_MMIMetricPerThreadVariables[threadID].JointPDF->GetBufferPointer() - + ( fixedImageParzenWindowIndex * this->m_MMIMetricPerThreadVariables[threadID].JointPDF->GetOffsetTable()[1] ); + JointPDFValueType *pdfPtr = this->m_MMIMetricPerThreadVariables[threadId].JointPDF->GetBufferPointer() + + ( fixedImageParzenWindowIndex * this->m_MMIMetricPerThreadVariables[threadId].JointPDF->GetOffsetTable()[1] ); // Move the pointer to the first affected bin int pdfMovingIndex = static_cast<int>( movingImageParzenWindowIndex ) - 1; @@ -471,15 +497,15 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> template <typename TFixedImage, typename TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> -::GetValueThreadPostProcess( ThreadIdType threadID, +::GetValueThreadPostProcess( ThreadIdType threadId, bool itkNotUsed(withinSampleThread) ) const { const int maxI = this->m_NumberOfHistogramBins - * ( this->m_MMIMetricPerThreadVariables[threadID].JointPDFEndBin- - this->m_MMIMetricPerThreadVariables[threadID].JointPDFStartBin + 1 ); + * ( this->m_MMIMetricPerThreadVariables[threadId].JointPDFEndBin- + this->m_MMIMetricPerThreadVariables[threadId].JointPDFStartBin + 1 ); const unsigned int tPdfPtrOffset = - ( this->m_MMIMetricPerThreadVariables[threadID].JointPDFStartBin * + ( this->m_MMIMetricPerThreadVariables[threadId].JointPDFStartBin * this->m_MMIMetricPerThreadVariables[0].JointPDF->GetOffsetTable()[1] ); JointPDFValueType * const pdfPtrStart = this->m_MMIMetricPerThreadVariables[0].JointPDF->GetBufferPointer() + tPdfPtrOffset; @@ -499,8 +525,8 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> } } - for( int i = this->m_MMIMetricPerThreadVariables[threadID].JointPDFStartBin; - i <= this->m_MMIMetricPerThreadVariables[threadID].JointPDFEndBin; i++ ) + for( int i = this->m_MMIMetricPerThreadVariables[threadId].JointPDFStartBin; + i <= this->m_MMIMetricPerThreadVariables[threadId].JointPDFEndBin; i++ ) { PDFValueType PDFacc = this->m_MMIMetricPerThreadVariables[0].FixedImageMarginalPDF[i]; for( unsigned int t = 1; t < this->m_NumberOfThreads; t++ ) @@ -513,11 +539,11 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> // Sum of this threads domain into the // this->m_MMIMetricPerThreadVariables[].JointPDFSum // that covers that part of the domain. - this->m_MMIMetricPerThreadVariables[threadID].JointPDFSum = 0.0; + this->m_MMIMetricPerThreadVariables[threadId].JointPDFSum = 0.0; JointPDFValueType const * pdfPtr = pdfPtrStart; for( int i = 0; i < maxI; i++ ) { - this->m_MMIMetricPerThreadVariables[threadID].JointPDFSum += *( pdfPtr++ ); + this->m_MMIMetricPerThreadVariables[threadId].JointPDFSum += *( pdfPtr++ ); } } @@ -537,9 +563,9 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> // MUST BE CALLED TO INITIATE PROCESSING this->GetValueMultiThreadedPostProcessInitiate(); // Consolidate to the first element in the vector - for( ThreadIdType threadID = 1; threadID < this->m_NumberOfThreads; threadID++ ) + for( ThreadIdType threadId = 1; threadId < this->m_NumberOfThreads; threadId++ ) { - this->m_MMIMetricPerThreadVariables[0].JointPDFSum += this->m_MMIMetricPerThreadVariables[threadID].JointPDFSum; + this->m_MMIMetricPerThreadVariables[0].JointPDFSum += this->m_MMIMetricPerThreadVariables[threadId].JointPDFSum; } if( this->m_MMIMetricPerThreadVariables[0].JointPDFSum < itk::NumericTraits< PDFValueType >::epsilon() ) { @@ -612,13 +638,13 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> const PDFValueType jointPDFValue = *( jointPDFPtr ); // check for non-zero bin contribution - const PDFValueType closeToZero = vcl_numeric_limits<PDFValueType>::epsilon(); + const PDFValueType closeToZero = std::numeric_limits<PDFValueType>::epsilon(); if( jointPDFValue > closeToZero && movingImagePDFValue > closeToZero ) { - const PDFValueType pRatio = vcl_log(jointPDFValue / movingImagePDFValue); + const PDFValueType pRatio = std::log(jointPDFValue / movingImagePDFValue); if( fixedImagePDFValue > closeToZero ) { - sum += jointPDFValue * ( pRatio - vcl_log(fixedImagePDFValue) ); + sum += jointPDFValue * ( pRatio - std::log(fixedImagePDFValue) ); } } // end if-block to check non-zero bin contribution } // end for-loop over moving index @@ -630,22 +656,22 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> template <typename TFixedImage, typename TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> -::GetValueAndDerivativeThreadPreProcess( ThreadIdType threadID, +::GetValueAndDerivativeThreadPreProcess( ThreadIdType threadId, bool itkNotUsed(withinSampleThread) ) const { - this->m_MMIMetricPerThreadVariables[threadID].FixedImageMarginalPDF = std::vector<PDFValueType>( + this->m_MMIMetricPerThreadVariables[threadId].FixedImageMarginalPDF = std::vector<PDFValueType>( m_NumberOfHistogramBins, 0.0F); - this->m_MMIMetricPerThreadVariables[threadID].JointPDF->FillBuffer(0.0F); + this->m_MMIMetricPerThreadVariables[threadId].JointPDF->FillBuffer(0.0F); if( this->m_UseExplicitPDFDerivatives ) { - this->m_MMIMetricPerThreadVariables[threadID].JointPDFDerivatives->FillBuffer(0.0F); + this->m_MMIMetricPerThreadVariables[threadId].JointPDFDerivatives->FillBuffer(0.0F); } } template <typename TFixedImage, typename TMovingImage> inline bool MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> -::GetValueAndDerivativeThreadProcessSample(ThreadIdType threadID, +::GetValueAndDerivativeThreadProcessSample(ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue, @@ -694,7 +720,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> // Since a zero-order BSpline (box car) kernel is used for // the fixed image marginal pdf, we need only increment the // fixedImageParzenWindowIndex by value of 1.0. - this->m_MMIMetricPerThreadVariables[threadID].FixedImageMarginalPDF[fixedImageParzenWindowIndex] += 1; + this->m_MMIMetricPerThreadVariables[threadId].FixedImageMarginalPDF[fixedImageParzenWindowIndex] += 1; /** * The region of support of the parzen window determines which bins @@ -712,7 +738,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> static_cast<PDFValueType>( movingImageParzenWindowTerm ); // Pointer to affected bin to be updated - JointPDFValueType *pdfPtr = this->m_MMIMetricPerThreadVariables[threadID].JointPDF->GetBufferPointer() + JointPDFValueType *pdfPtr = this->m_MMIMetricPerThreadVariables[threadId].JointPDF->GetBufferPointer() + ( fixedImageParzenWindowIndex * this->m_NumberOfHistogramBins ) + pdfMovingIndex; @@ -727,7 +753,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> movingImageParzenWindowArg); // Compute PDF derivative contribution. - this->ComputePDFDerivatives(threadID, + this->ComputePDFDerivatives(threadId, fixedImageSample, pdfMovingIndex, movingImageGradientValue, @@ -744,23 +770,23 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> template <typename TFixedImage, typename TMovingImage> inline void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> -::GetValueAndDerivativeThreadPostProcess(ThreadIdType threadID, +::GetValueAndDerivativeThreadPostProcess(ThreadIdType threadId, bool withinSampleThread) const { - this->GetValueThreadPostProcess(threadID, withinSampleThread); + this->GetValueThreadPostProcess(threadId, withinSampleThread); if( this->m_UseExplicitPDFDerivatives ) { const unsigned int rowSize = this->m_NumberOfParameters * this->m_NumberOfHistogramBins; const unsigned int maxI = - rowSize * ( this->m_MMIMetricPerThreadVariables[threadID].JointPDFEndBin - - this->m_MMIMetricPerThreadVariables[threadID].JointPDFStartBin + 1 ); + rowSize * ( this->m_MMIMetricPerThreadVariables[threadId].JointPDFEndBin + - this->m_MMIMetricPerThreadVariables[threadId].JointPDFStartBin + 1 ); JointPDFDerivativesValueType *const pdfDPtrStart = this->m_MMIMetricPerThreadVariables[0].JointPDFDerivatives->GetBufferPointer() - + ( this->m_MMIMetricPerThreadVariables[threadID].JointPDFStartBin * rowSize ); - const unsigned int tPdfDPtrOffset = this->m_MMIMetricPerThreadVariables[threadID].JointPDFStartBin * rowSize; + + ( this->m_MMIMetricPerThreadVariables[threadId].JointPDFStartBin * rowSize ); + const unsigned int tPdfDPtrOffset = this->m_MMIMetricPerThreadVariables[threadId].JointPDFStartBin * rowSize; for( unsigned int t = 1; t < this->m_NumberOfThreads; t++ ) { JointPDFDerivativesValueType * pdfDPtr = pdfDPtrStart; @@ -813,9 +839,9 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> else { this->m_PRatioArray.Fill(0.0); - for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads; threadID++ ) + for( ThreadIdType threadId = 0; threadId < this->m_NumberOfThreads; threadId++ ) { - this->m_MMIMetricPerThreadVariables[threadID].MetricDerivative.Fill(NumericTraits<MeasureType>::Zero); + this->m_MMIMetricPerThreadVariables[threadId].MetricDerivative.Fill(NumericTraits<MeasureType>::Zero); } this->m_ImplicitDerivativesSecondPass = false; } @@ -828,9 +854,9 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> // CALL IF DOING THREADED POST PROCESSING this->GetValueAndDerivativeMultiThreadedPostProcessInitiate(); - for( ThreadIdType threadID = 1; threadID < this->m_NumberOfThreads; threadID++ ) + for( ThreadIdType threadId = 1; threadId < this->m_NumberOfThreads; threadId++ ) { - this->m_MMIMetricPerThreadVariables[0].JointPDFSum += this->m_MMIMetricPerThreadVariables[threadID].JointPDFSum; + this->m_MMIMetricPerThreadVariables[0].JointPDFSum += this->m_MMIMetricPerThreadVariables[threadId].JointPDFSum; } if( this->m_MMIMetricPerThreadVariables[0].JointPDFSum < itk::NumericTraits< PDFValueType >::epsilon() ) { @@ -900,14 +926,14 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> const PDFValueType jointPDFValue = *( jointPDFPtr ); // check for non-zero bin contribution - const PDFValueType closeToZero = vcl_numeric_limits<PDFValueType>::epsilon(); + const PDFValueType closeToZero = std::numeric_limits<PDFValueType>::epsilon(); if( jointPDFValue > closeToZero && movingImagePDFValue > closeToZero ) { - const PDFValueType pRatio = vcl_log(jointPDFValue / movingImagePDFValue); + const PDFValueType pRatio = std::log(jointPDFValue / movingImagePDFValue); if( fixedImagePDFValue > closeToZero ) { - sum += jointPDFValue * ( pRatio - vcl_log(fixedImagePDFValue) ); + sum += jointPDFValue * ( pRatio - std::log(fixedImagePDFValue) ); } if( this->m_UseExplicitPDFDerivatives ) @@ -981,7 +1007,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> template <typename TFixedImage, typename TMovingImage> void MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> -::ComputePDFDerivatives(ThreadIdType threadID, +::ComputePDFDerivatives(ThreadIdType threadId, unsigned int sampleNumber, int pdfMovingIndex, const ImageDerivativesType & movingImageGradientValue, @@ -994,13 +1020,13 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> const int pdfFixedIndex = this->m_FixedImageSamples[sampleNumber].valueIndex; - JointPDFDerivativesValueType *derivPtr=0; + JointPDFDerivativesValueType *derivPtr=ITK_NULLPTR; if( this->m_UseExplicitPDFDerivatives ) { - derivPtr = this->m_MMIMetricPerThreadVariables[threadID].JointPDFDerivatives->GetBufferPointer() - + ( pdfFixedIndex * this->m_MMIMetricPerThreadVariables[threadID].JointPDFDerivatives->GetOffsetTable()[2] ) - + ( pdfMovingIndex * this->m_MMIMetricPerThreadVariables[threadID].JointPDFDerivatives->GetOffsetTable()[1] ); + derivPtr = this->m_MMIMetricPerThreadVariables[threadId].JointPDFDerivatives->GetBufferPointer() + + ( pdfFixedIndex * this->m_MMIMetricPerThreadVariables[threadId].JointPDFDerivatives->GetOffsetTable()[2] ) + + ( pdfMovingIndex * this->m_MMIMetricPerThreadVariables[threadId].JointPDFDerivatives->GetOffsetTable()[1] ); } else { @@ -1021,9 +1047,9 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> // For instance, Register and UnRegister have mutex locks around // the reference counts. TransformType *transform; - if( threadID > 0 ) + if( threadId > 0 ) { - transform = this->m_ThreaderTransform[threadID - 1]; + transform = this->m_ThreaderTransform[threadId - 1]; } else { @@ -1032,7 +1058,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> // Compute the transform Jacobian. // Should pre-compute - typename TransformType::JacobianType &jacobian = this->m_MMIMetricPerThreadVariables[threadID].Jacobian; + typename TransformType::JacobianType &jacobian = this->m_MMIMetricPerThreadVariables[threadId].Jacobian; transform->ComputeJacobianWithRespectToParameters( this->m_FixedImageSamples[sampleNumber].point, jacobian); for( unsigned int mu = 0; mu < this->m_NumberOfParameters; mu++ ) { @@ -1051,18 +1077,18 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> } else { - this->m_MMIMetricPerThreadVariables[threadID].MetricDerivative[mu] += precomputedWeight * + this->m_MMIMetricPerThreadVariables[threadId].MetricDerivative[mu] += precomputedWeight * derivativeContribution; } } } else { - const WeightsValueType *weights = NULL; - const IndexValueType * indices = NULL; + const WeightsValueType *weights = ITK_NULLPTR; + const IndexValueType * indices = ITK_NULLPTR; - BSplineTransformWeightsType * weightsHelper = NULL; - BSplineTransformIndexArrayType *indicesHelper = NULL; + BSplineTransformWeightsType * weightsHelper = ITK_NULLPTR; + BSplineTransformIndexArrayType *indicesHelper = ITK_NULLPTR; if( this->m_UseCachingOfBSplineWeights ) { @@ -1077,10 +1103,10 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> } else { - if( threadID > 0 ) + if( threadId > 0 ) { - weightsHelper = &( this->m_ThreaderBSplineTransformWeights[threadID - 1] ); - indicesHelper = &( this->m_ThreaderBSplineTransformIndices[threadID - 1] ); + weightsHelper = &( this->m_ThreaderBSplineTransformWeights[threadId - 1] ); + indicesHelper = &( this->m_ThreaderBSplineTransformIndices[threadId - 1] ); } else { @@ -1122,7 +1148,7 @@ MattesMutualInformationImageToImageMetric<TFixedImage, TMovingImage> } else { - this->m_MMIMetricPerThreadVariables[threadID].MetricDerivative[parameterIndex] += precomputedWeight * + this->m_MMIMetricPerThreadVariables[threadId].MetricDerivative[parameterIndex] += precomputedWeight * derivativeContribution; } } // end mu for loop diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMeanReciprocalSquareDifferencePointSetToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMeanReciprocalSquareDifferencePointSetToImageMetric.hxx index 2c77e24d9e8ada9f415167ef768effa8922d42a1..cb8a3f9ab1d844abc713e2aaf53aa920faa1d071 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMeanReciprocalSquareDifferencePointSetToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMeanReciprocalSquareDifferencePointSetToImageMetric.hxx @@ -57,12 +57,10 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage MeasureType measure = NumericTraits<MeasureType>::Zero; this->m_NumberOfPixelsCounted = 0; - double lambdaSquared = vcl_pow(this->m_Lambda, 2); + double lambdaSquared = std::pow(this->m_Lambda, 2); this->SetTransformParameters(parameters); - typedef typename NumericTraits<MeasureType>::AccumulateType AccumulateType; - while( pointItr != pointEnd && pointDataItr != pointDataEnd ) { InputPointType inputPoint; @@ -119,12 +117,10 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage this->m_NumberOfPixelsCounted = 0; - double lambdaSquared = vcl_pow(this->m_Lambda, 2); + double lambdaSquared = std::pow(this->m_Lambda, 2); this->SetTransformParameters(parameters); - typedef typename NumericTraits<MeasureType>::AccumulateType AccumulateType; - const unsigned int ParametersDimension = this->GetNumberOfParameters(); derivative = DerivativeType(ParametersDimension); derivative.Fill(NumericTraits<typename DerivativeType::ValueType>::Zero); @@ -135,7 +131,8 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage PointDataIterator pointDataItr = fixedPointSet->GetPointData()->Begin(); PointDataIterator pointDataEnd = fixedPointSet->GetPointData()->End(); - TransformJacobianType jacobian; + TransformJacobianType jacobian(TMovingImage::ImageDimension,this->m_Transform->GetNumberOfParameters()); + TransformJacobianType jacobianCache(TMovingImage::ImageDimension, TMovingImage::ImageDimension); while( pointItr != pointEnd && pointDataItr != pointDataEnd ) { @@ -154,7 +151,9 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage const RealType diffSquared = diff * diff; // Now compute the derivatives - this->m_Transform->ComputeJacobianWithRespectToParameters(inputPoint, jacobian); + this->m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); // Get the gradient by NearestNeighboorInterpolation: // which is equivalent to round up the point components. @@ -178,7 +177,7 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage // Will it be computationally more efficient to instead calculate the // derivative using finite differences ? sum -= jacobian(dim, par) - * gradient[dim] / ( vcl_pow(lambdaSquared + diffSquared, 2) ); + * gradient[dim] / ( std::pow(lambdaSquared + diffSquared, 2) ); } derivative[par] += diff * sum; } @@ -226,9 +225,7 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage MeasureType measure = NumericTraits<MeasureType>::Zero; this->SetTransformParameters(parameters); - double lambdaSquared = vcl_pow(this->m_Lambda, 2); - - typedef typename NumericTraits<MeasureType>::AccumulateType AccumulateType; + double lambdaSquared = std::pow(this->m_Lambda, 2); const unsigned int ParametersDimension = this->GetNumberOfParameters(); derivative = DerivativeType(ParametersDimension); @@ -240,6 +237,10 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage PointDataIterator pointDataItr = fixedPointSet->GetPointData()->Begin(); PointDataIterator pointDataEnd = fixedPointSet->GetPointData()->End(); + TransformJacobianType jacobian(TMovingImage::ImageDimension, + this->m_Transform->GetNumberOfParameters()); + TransformJacobianType jacobianCache(TMovingImage::ImageDimension, + TMovingImage::ImageDimension); while( pointItr != pointEnd && pointDataItr != pointDataEnd ) { InputPointType inputPoint; @@ -255,8 +256,9 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage this->m_NumberOfPixelsCounted++; // Now compute the derivatives - TransformJacobianType jacobian; - this->m_Transform->ComputeJacobianWithRespectToParameters(inputPoint, jacobian); + this->m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); const RealType diff = movingValue - fixedValue; const RealType diffSquared = diff * diff; @@ -282,7 +284,7 @@ MeanReciprocalSquareDifferencePointSetToImageMetric<TFixedPointSet, TMovingImage for( unsigned int dim = 0; dim < Self::FixedPointSetDimension; dim++ ) { sum -= jacobian(dim, par) * gradient[dim] - * vcl_pow(lambdaSquared + diffSquared, 2); + * std::pow(lambdaSquared + diffSquared, 2); } derivative[par] += diff * sum; } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquareRegistrationFunction.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquareRegistrationFunction.hxx index 9c8f1e659d8ae18e2d0b1288150ab91df4812bf6..b684c8291daf2ae9fd195d8339c1454c48c73c7d 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquareRegistrationFunction.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquareRegistrationFunction.hxx @@ -44,8 +44,8 @@ MeanSquareRegistrationFunction< TFixedImage, TMovingImage, TDisplacementField > m_TimeStep = 1.0; m_DenominatorThreshold = 1e-9; m_IntensityDifferenceThreshold = 0.001; - this->SetMovingImage(NULL); - this->SetFixedImage(NULL); + this->SetMovingImage(ITK_NULLPTR); + this->SetFixedImage(ITK_NULLPTR); m_FixedImageGradientCalculator = GradientCalculatorType::New(); typename DefaultInterpolatorType::Pointer interp = @@ -146,7 +146,7 @@ MeanSquareRegistrationFunction< TFixedImage, TMovingImage, TDisplacementField > if ( normalizemetric ) { denominator = speedValue * speedValue * fixedGradientSquaredMagnitude; - denominator = vcl_sqrt(denominator); + denominator = std::sqrt(denominator); } if ( denominator == 0 ) { diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.h b/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.h index 9f4a63e5632a3b3f06ee7d1adfa276702f3ebbd1..b62bacb8347e6c5af33b3bef115144f682f68f99 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.h @@ -114,12 +114,12 @@ private: //purposely not implemented void operator=(const Self &); - inline bool GetValueThreadProcessSample(ThreadIdType threadID, + inline bool GetValueThreadProcessSample(ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & mappedPoint, double movingImageValue) const; - inline bool GetValueAndDerivativeThreadProcessSample(ThreadIdType threadID, + inline bool GetValueAndDerivativeThreadProcessSample(ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & mappedPoint, double movingImageValue, diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.hxx index da6e749eeca6279007ca3ee13e704b5fb02b5ff1..843e478cfed72b419c36bd87e001066d62089ddf 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresImageToImageMetric.hxx @@ -36,7 +36,7 @@ MeanSquaresImageToImageMetric<TFixedImage, TMovingImage> { this->SetComputeGradient(true); - m_PerThread = NULL; + m_PerThread = ITK_NULLPTR; this->m_WithinThreadPreProcess = false; this->m_WithinThreadPostProcess = false; @@ -51,7 +51,7 @@ MeanSquaresImageToImageMetric<TFixedImage, TMovingImage> ::~MeanSquaresImageToImageMetric() { delete[] m_PerThread; - m_PerThread = NULL; + m_PerThread = ITK_NULLPTR; } /** @@ -81,23 +81,23 @@ throw ( ExceptionObject ) m_PerThread = new AlignedPerThreadType[this->m_NumberOfThreads]; - for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads; threadID++ ) + for( ThreadIdType threadId = 0; threadId < this->m_NumberOfThreads; threadId++ ) { - m_PerThread[threadID].m_MSEDerivative.SetSize(this->m_NumberOfParameters); + m_PerThread[threadId].m_MSEDerivative.SetSize(this->m_NumberOfParameters); } } template <typename TFixedImage, typename TMovingImage> inline bool MeanSquaresImageToImageMetric<TFixedImage, TMovingImage> -::GetValueThreadProcessSample(ThreadIdType threadID, +::GetValueThreadProcessSample(ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue) const { double diff = movingImageValue - this->m_FixedImageSamples[fixedImageSample].value; - m_PerThread[threadID].m_MSE += diff * diff; + m_PerThread[threadId].m_MSE += diff * diff; return true; } @@ -153,7 +153,7 @@ MeanSquaresImageToImageMetric<TFixedImage, TMovingImage> template <typename TFixedImage, typename TMovingImage> inline bool MeanSquaresImageToImageMetric<TFixedImage, TMovingImage> -::GetValueAndDerivativeThreadProcessSample(ThreadIdType threadID, +::GetValueAndDerivativeThreadProcessSample(ThreadIdType threadId, SizeValueType fixedImageSample, const MovingImagePointType & itkNotUsed(mappedPoint), double movingImageValue, @@ -162,7 +162,7 @@ MeanSquaresImageToImageMetric<TFixedImage, TMovingImage> { double diff = movingImageValue - this->m_FixedImageSamples[fixedImageSample].value; - AlignedPerThreadType &threadS = m_PerThread[threadID]; + AlignedPerThreadType &threadS = m_PerThread[threadId]; threadS.m_MSE += diff * diff; @@ -176,9 +176,9 @@ MeanSquaresImageToImageMetric<TFixedImage, TMovingImage> // the reference counts. TransformType *transform; - if( threadID > 0 ) + if( threadId > 0 ) { - transform = this->m_ThreaderTransform[threadID - 1]; + transform = this->m_ThreaderTransform[threadId - 1]; } else { @@ -232,9 +232,9 @@ MeanSquaresImageToImageMetric<TFixedImage, TMovingImage> memset( derivative.data_block(), 0, this->m_NumberOfParameters * sizeof( double ) ); - for( ThreadIdType threadID = 0; threadID < this->m_NumberOfThreads; threadID++ ) + for( ThreadIdType threadId = 0; threadId < this->m_NumberOfThreads; threadId++ ) { - memset( m_PerThread[threadID].m_MSEDerivative.data_block(), + memset( m_PerThread[threadId].m_MSEDerivative.data_block(), 0, this->m_NumberOfParameters * sizeof( double ) ); } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresPointSetToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresPointSetToImageMetric.hxx index 5959ba693190a2717caf0ae54b50152a02761831..9d95c25001442915477feeaf740649ea937fa1df 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresPointSetToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMeanSquaresPointSetToImageMetric.hxx @@ -59,7 +59,6 @@ MeanSquaresPointSetToImageMetric<TFixedPointSet, TMovingImage> this->SetTransformParameters(parameters); - typedef typename NumericTraits<MeasureType>::AccumulateType AccumulateType; while( pointItr != pointEnd && pointDataItr != pointDataEnd ) { @@ -118,8 +117,6 @@ MeanSquaresPointSetToImageMetric<TFixedPointSet, TMovingImage> this->SetTransformParameters(parameters); - typedef typename NumericTraits<MeasureType>::AccumulateType AccumulateType; - const unsigned int ParametersDimension = this->GetNumberOfParameters(); derivative = DerivativeType(ParametersDimension); derivative.Fill(NumericTraits<typename DerivativeType::ValueType>::Zero); @@ -130,6 +127,10 @@ MeanSquaresPointSetToImageMetric<TFixedPointSet, TMovingImage> PointDataIterator pointDataItr = fixedPointSet->GetPointData()->Begin(); PointDataIterator pointDataEnd = fixedPointSet->GetPointData()->End(); + TransformJacobianType jacobian(TMovingImage::ImageDimension, + this->m_Transform->GetNumberOfParameters()); + TransformJacobianType jacobianCache(TMovingImage::ImageDimension,TMovingImage::ImageDimension); + while( pointItr != pointEnd && pointDataItr != pointDataEnd ) { InputPointType inputPoint; @@ -146,8 +147,9 @@ MeanSquaresPointSetToImageMetric<TFixedPointSet, TMovingImage> const RealType diff = movingValue - fixedValue; // Now compute the derivatives - TransformJacobianType jacobian; - this->m_Transform->ComputeJacobianWithRespectToParameters(inputPoint, jacobian); + this->m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); // Get the gradient by NearestNeighboorInterpolation: // which is equivalent to round up the point components. @@ -217,8 +219,6 @@ MeanSquaresPointSetToImageMetric<TFixedPointSet, TMovingImage> this->SetTransformParameters(parameters); - typedef typename NumericTraits<MeasureType>::AccumulateType AccumulateType; - const unsigned int ParametersDimension = this->GetNumberOfParameters(); derivative = DerivativeType(ParametersDimension); derivative.Fill(NumericTraits<typename DerivativeType::ValueType>::Zero); @@ -229,6 +229,10 @@ MeanSquaresPointSetToImageMetric<TFixedPointSet, TMovingImage> PointDataIterator pointDataItr = fixedPointSet->GetPointData()->Begin(); PointDataIterator pointDataEnd = fixedPointSet->GetPointData()->End(); + TransformJacobianType jacobian(TMovingImage::ImageDimension, + this->m_Transform->GetNumberOfParameters()); + TransformJacobianType jacobianCache(TMovingImage::ImageDimension,TMovingImage::ImageDimension); + while( pointItr != pointEnd && pointDataItr != pointDataEnd ) { InputPointType inputPoint; @@ -244,8 +248,9 @@ MeanSquaresPointSetToImageMetric<TFixedPointSet, TMovingImage> this->m_NumberOfPixelsCounted++; // Now compute the derivatives - TransformJacobianType jacobian; - this->m_Transform->ComputeJacobianWithRespectToParameters(inputPoint, jacobian); + this->m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); const RealType diff = movingValue - fixedValue; diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionImageRegistrationMethod.h b/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionImageRegistrationMethod.h index c155eb65f832b5254d162888c8f76a905f26e2f0..0b3d1ab7cdf2f5cd66c2394710be1727215d5427 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionImageRegistrationMethod.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionImageRegistrationMethod.h @@ -207,11 +207,11 @@ public: * output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** Method to return the latest modified time of this object or * any of its cached ivars */ - ModifiedTimeType GetMTime() const; + virtual ModifiedTimeType GetMTime() const ITK_OVERRIDE; #ifdef ITKV3_COMPATIBILITY // StartRegistration is an old API from before @@ -231,11 +231,11 @@ public: protected: MultiResolutionImageRegistrationMethod(); virtual ~MultiResolutionImageRegistrationMethod() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Method invoked by the pipeline in order to trigger the computation of * the registration. */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Initialize by setting the interconnects between the components. This method is executed at every level of the pyramid with the diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionImageRegistrationMethod.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionImageRegistrationMethod.hxx index 863eee76fb271c36fa0f52dc000109206038aacd..6193b1b5e21eb9617562268dca6765de2c89ca8a 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionImageRegistrationMethod.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionImageRegistrationMethod.hxx @@ -32,12 +32,12 @@ MultiResolutionImageRegistrationMethod< TFixedImage, TMovingImage > { this->SetNumberOfRequiredOutputs(1); // for the Transform - m_FixedImage = 0; // has to be provided by the user. - m_MovingImage = 0; // has to be provided by the user. - m_Transform = 0; // has to be provided by the user. - m_Interpolator = 0; // has to be provided by the user. - m_Metric = 0; // has to be provided by the user. - m_Optimizer = 0; // has to be provided by the user. + m_FixedImage = ITK_NULLPTR; // has to be provided by the user. + m_MovingImage = ITK_NULLPTR; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. + m_Interpolator = ITK_NULLPTR; // has to be provided by the user. + m_Metric = ITK_NULLPTR; // has to be provided by the user. + m_Optimizer = ITK_NULLPTR; // has to be provided by the user. // Use MultiResolutionPyramidImageFilter as the default // image pyramids. @@ -274,14 +274,14 @@ MultiResolutionImageRegistrationMethod< TFixedImage, TMovingImage > const float scaleFactor = static_cast< float >( schedule[level][dim] ); size[dim] = static_cast< typename SizeType::SizeValueType >( - vcl_floor(static_cast< float >( inputSize[dim] ) / scaleFactor) ); + std::floor(static_cast< float >( inputSize[dim] ) / scaleFactor) ); if ( size[dim] < 1 ) { size[dim] = 1; } start[dim] = static_cast< typename IndexType::IndexValueType >( - vcl_ceil(static_cast< float >( inputStart[dim] ) / scaleFactor) ); + std::ceil(static_cast< float >( inputStart[dim] ) / scaleFactor) ); } m_FixedImageRegionPyramid[level].SetSize(size); m_FixedImageRegionPyramid[level].SetIndex(start); @@ -351,7 +351,7 @@ MultiResolutionImageRegistrationMethod< TFixedImage, TMovingImage > // Invoke an iteration event. // This allows a UI to reset any of the components between // resolution level. - this->InvokeEvent( IterationEvent() ); + this->InvokeEvent( MultiResolutionIterationEvent() ); // Check if there has been a stop request if ( m_Stop ) @@ -474,7 +474,7 @@ MultiResolutionImageRegistrationMethod< TFixedImage, TMovingImage > break; default: itkExceptionMacro("MakeOutput request for an output number larger than the expected number of outputs"); - return 0; + return ITK_NULLPTR; } } } // end namespace itk diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionPyramidImageFilter.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionPyramidImageFilter.hxx index e07995068c6448fc7f9218ff2898f7d10a67056a..6845f7f044ccd3828c57a203f840776d0f60cad6 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionPyramidImageFilter.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMultiResolutionPyramidImageFilter.hxx @@ -407,11 +407,11 @@ MultiResolutionPyramidImageFilter< TInputImage, TOutputImage > outputSpacing[idim] = inputSpacing[idim] * shrinkFactor; outputSize[idim] = static_cast< SizeValueType >( - vcl_floor(static_cast< double >( inputSize[idim] ) / shrinkFactor) ); + std::floor(static_cast< double >( inputSize[idim] ) / shrinkFactor) ); if ( outputSize[idim] < 1 ) { outputSize[idim] = 1; } outputStartIndex[idim] = static_cast< IndexValueType >( - vcl_ceil(static_cast< double >( inputStartIndex[idim] ) / shrinkFactor) ); + std::ceil(static_cast< double >( inputStartIndex[idim] ) / shrinkFactor) ); } //Now compute the new shifted origin for the updated levels; const typename OutputImageType::PointType::VectorType outputOriginOffset = @@ -499,11 +499,11 @@ MultiResolutionPyramidImageFilter< TInputImage, TOutputImage > double factor = static_cast< double >( m_Schedule[ilevel][idim] ); outputSize[idim] = static_cast< SizeValueType >( - vcl_floor(static_cast< double >( baseSize[idim] ) / factor) ); + std::floor(static_cast< double >( baseSize[idim] ) / factor) ); if ( outputSize[idim] < 1 ) { outputSize[idim] = 1; } outputIndex[idim] = static_cast< IndexValueType >( - vcl_ceil(static_cast< double >( baseIndex[idim] ) / factor) ); + std::ceil(static_cast< double >( baseIndex[idim] ) / factor) ); } outputRegion.SetIndex(outputIndex); diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMutualInformationHistogramImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMutualInformationHistogramImageToImageMetric.hxx index c10ed9520209642bad51785ff14e9bbbe983bed1..2a05417d3d506100aa8e2bea79d41f38eb7766f7 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMutualInformationHistogramImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMutualInformationHistogramImageToImageMetric.hxx @@ -43,11 +43,11 @@ MutualInformationHistogramImageToImageMetric< TFixedImage, TMovingImage > static_cast< HistogramFrequencyRealType >( histogram.GetFrequency(i, 0) ); if ( freq > 0 ) { - entropyX += freq * vcl_log(freq); + entropyX += freq * std::log(freq); } } - entropyX = -entropyX / static_cast< MeasureType >( totalFreq ) + vcl_log(totalFreq); + entropyX = -entropyX / static_cast< MeasureType >( totalFreq ) + std::log(totalFreq); for ( unsigned int i = 0; i < this->GetHistogramSize()[1]; i++ ) { @@ -55,11 +55,11 @@ MutualInformationHistogramImageToImageMetric< TFixedImage, TMovingImage > static_cast< HistogramFrequencyRealType >( histogram.GetFrequency(i, 1) ); if ( freq > 0 ) { - entropyY += freq * vcl_log(freq); + entropyY += freq * std::log(freq); } } - entropyY = -entropyY / static_cast< MeasureType >( totalFreq ) + vcl_log(totalFreq); + entropyY = -entropyY / static_cast< MeasureType >( totalFreq ) + std::log(totalFreq); HistogramIteratorType it = histogram.Begin(); HistogramIteratorType end = histogram.End(); @@ -69,13 +69,13 @@ MutualInformationHistogramImageToImageMetric< TFixedImage, TMovingImage > static_cast< HistogramFrequencyRealType >( it.GetFrequency() ); if ( freq > 0 ) { - jointEntropy += freq * vcl_log(freq); + jointEntropy += freq * std::log(freq); } ++it; } jointEntropy = -jointEntropy - / static_cast< MeasureType >( totalFreq ) + vcl_log(totalFreq); + / static_cast< MeasureType >( totalFreq ) + std::log(totalFreq); return entropyX + entropyY - jointEntropy; } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkMutualInformationImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkMutualInformationImageToImageMetric.hxx index e4d68254f2278fb60fca9c9b1b27c565c2cad513..64f987f3b6e132753dd77f27b3f28439e5717d8b 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkMutualInformationImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkMutualInformationImageToImageMetric.hxx @@ -257,21 +257,21 @@ MutualInformationImageToImageMetric<TFixedImage, TMovingImage> if( dSumFixed.GetSum() > 0.0 ) { - dLogSumFixed -= vcl_log( dSumFixed.GetSum() ); + dLogSumFixed -= std::log( dSumFixed.GetSum() ); } if( dSumMoving.GetSum() > 0.0 ) { - dLogSumMoving -= vcl_log( dSumMoving.GetSum() ); + dLogSumMoving -= std::log( dSumMoving.GetSum() ); } if( dSumJoint.GetSum() > 0.0 ) { - dLogSumJoint -= vcl_log( dSumJoint.GetSum() ); + dLogSumJoint -= std::log( dSumJoint.GetSum() ); } } // end of sample B loop double nsamp = double(m_NumberOfSpatialSamples); - double threshold = -0.5 *nsamp *vcl_log(m_MinProbability); + double threshold = -0.5 *nsamp *std::log(m_MinProbability); if( dLogSumMoving.GetSum() > threshold || dLogSumFixed.GetSum() > threshold || dLogSumJoint.GetSum() > threshold ) { @@ -282,7 +282,7 @@ MutualInformationImageToImageMetric<TFixedImage, TMovingImage> MeasureType measure = dLogSumFixed.GetSum() + dLogSumMoving.GetSum() - dLogSumJoint.GetSum(); measure /= nsamp; - measure += vcl_log(nsamp); + measure += std::log(nsamp); return measure; } @@ -376,15 +376,15 @@ MutualInformationImageToImageMetric<TFixedImage, TMovingImage> if( dSumFixed.GetSum() > 0.0 ) { - dLogSumFixed -= vcl_log( dSumFixed.GetSum() ); + dLogSumFixed -= std::log( dSumFixed.GetSum() ); } if( dDenominatorMoving.GetSum() > 0.0 ) { - dLogSumMoving -= vcl_log( dDenominatorMoving.GetSum() ); + dLogSumMoving -= std::log( dDenominatorMoving.GetSum() ); } if( dDenominatorJoint.GetSum() > 0.0 ) { - dLogSumJoint -= vcl_log( dDenominatorJoint.GetSum() ); + dLogSumJoint -= std::log( dDenominatorJoint.GetSum() ); } /** get the image derivative for this B sample */ @@ -423,7 +423,7 @@ MutualInformationImageToImageMetric<TFixedImage, TMovingImage> double nsamp = double(m_NumberOfSpatialSamples); - double threshold = -0.5 *nsamp *vcl_log(m_MinProbability); + double threshold = -0.5 *nsamp *std::log(m_MinProbability); if( dLogSumMoving.GetSum() > threshold || dLogSumFixed.GetSum() > threshold || dLogSumJoint.GetSum() > threshold ) { @@ -434,7 +434,7 @@ MutualInformationImageToImageMetric<TFixedImage, TMovingImage> value = dLogSumFixed.GetSum() + dLogSumMoving.GetSum() - dLogSumJoint.GetSum(); value /= nsamp; - value += vcl_log(nsamp); + value += std::log(nsamp); derivative /= nsamp; derivative /= vnl_math_sqr(m_MovingImageStandardDeviation); @@ -486,7 +486,6 @@ MutualInformationImageToImageMetric<TFixedImage, TMovingImage> return; } - typedef typename TransformType::JacobianType JacobianType; this->m_Transform->ComputeJacobianWithRespectToParameters(point, jacobian); unsigned int numberOfParameters = this->m_Transform->GetNumberOfParameters(); diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedCorrelationImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedCorrelationImageToImageMetric.hxx index 3c7710ae20263cba8e3b12337dbe1ce24d49c2fc..41ba79cd23194d0054ef702232f463091ec749c6 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedCorrelationImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedCorrelationImageToImageMetric.hxx @@ -114,7 +114,7 @@ NormalizedCorrelationImageToImageMetric<TFixedImage, TMovingImage> sfm -= ( sf * sm / this->m_NumberOfPixelsCounted ); } - const RealType denom = -1.0 * vcl_sqrt(sff * smm); + const RealType denom = -1.0 * std::sqrt(sff * smm); if( this->m_NumberOfPixelsCounted > 0 && denom != 0.0 ) { @@ -220,7 +220,9 @@ NormalizedCorrelationImageToImageMetric<TFixedImage, TMovingImage> ++ti; } - TransformJacobianType jacobian; + TransformJacobianType jacobian(TFixedImage::ImageDimension, + this->m_Transform->GetNumberOfParameters()); + TransformJacobianType jacobianCache(TFixedImage::ImageDimension,TFixedImage::ImageDimension); // Compute contributions to derivatives ti.GoToBegin(); @@ -250,7 +252,9 @@ NormalizedCorrelationImageToImageMetric<TFixedImage, TMovingImage> const RealType movingValue = this->m_Interpolator->Evaluate(transformedPoint); const RealType fixedValue = ti.Get(); - this->m_Transform->ComputeJacobianWithRespectToParameters(inputPoint, jacobian); + this->m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); // Get the gradient by NearestNeighboorInterpolation: // which is equivalent to round up the point components. @@ -296,7 +300,7 @@ NormalizedCorrelationImageToImageMetric<TFixedImage, TMovingImage> sfm -= ( sf * sm / this->m_NumberOfPixelsCounted ); } - const RealType denom = -1.0 * vcl_sqrt(sff * smm); + const RealType denom = -1.0 * std::sqrt(sff * smm); if( this->m_NumberOfPixelsCounted > 0 && denom != 0.0 ) { @@ -409,6 +413,9 @@ NormalizedCorrelationImageToImageMetric<TFixedImage, TMovingImage> ++ti; } + TransformJacobianType jacobianCache(TFixedImage::ImageDimension,TFixedImage::ImageDimension); + TransformJacobianType jacobian(TFixedImage::ImageDimension, + this->m_Transform->GetNumberOfParameters()); // Compute contributions to derivatives ti.GoToBegin(); while( !ti.IsAtEnd() ) @@ -437,8 +444,9 @@ NormalizedCorrelationImageToImageMetric<TFixedImage, TMovingImage> const RealType movingValue = this->m_Interpolator->Evaluate(transformedPoint); const RealType fixedValue = ti.Get(); - TransformJacobianType jacobian; - this->m_Transform->ComputeJacobianWithRespectToParameters(inputPoint, jacobian); + this->m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); // Get the gradient by NearestNeighboorInterpolation: // which is equivalent to round up the point components. @@ -483,7 +491,7 @@ NormalizedCorrelationImageToImageMetric<TFixedImage, TMovingImage> sfm -= ( sf * sm / this->m_NumberOfPixelsCounted ); } - const RealType denom = -1.0 * vcl_sqrt(sff * smm); + const RealType denom = -1.0 * std::sqrt(sff * smm); if( this->m_NumberOfPixelsCounted > 0 && denom != 0.0 ) { diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedCorrelationPointSetToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedCorrelationPointSetToImageMetric.hxx index 4f6f29789ad95a633dd38d9558439a3619bffc4f..97114bf87540ee1277681e07f2179a0595dcf501 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedCorrelationPointSetToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedCorrelationPointSetToImageMetric.hxx @@ -101,7 +101,7 @@ NormalizedCorrelationPointSetToImageMetric<TFixedPointSet, TMovingImage> sfm -= ( sf * sm / this->m_NumberOfPixelsCounted ); } - const RealType denom = -1.0 * vcl_sqrt(sff * smm); + const RealType denom = -1.0 * std::sqrt(sff * smm); if( this->m_NumberOfPixelsCounted > 0 && denom != 0.0 ) { @@ -169,7 +169,9 @@ NormalizedCorrelationPointSetToImageMetric<TFixedPointSet, TMovingImage> PointDataIterator pointDataItr = fixedPointSet->GetPointData()->Begin(); PointDataIterator pointDataEnd = fixedPointSet->GetPointData()->End(); - TransformJacobianType jacobian; + TransformJacobianType jacobian(TMovingImage::ImageDimension, + this->m_Transform->GetNumberOfParameters()); + TransformJacobianType jacobianCache(TMovingImage::ImageDimension,TMovingImage::ImageDimension); while( pointItr != pointEnd && pointDataItr != pointDataEnd ) { @@ -195,7 +197,9 @@ NormalizedCorrelationPointSetToImageMetric<TFixedPointSet, TMovingImage> this->m_NumberOfPixelsCounted++; // Now compute the derivatives - this->m_Transform->ComputeJacobianWithRespectToParameters(inputPoint, jacobian); + this->m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); // Get the gradient by NearestNeighboorInterpolation: // which is equivalent to round up the point components. @@ -244,7 +248,7 @@ NormalizedCorrelationPointSetToImageMetric<TFixedPointSet, TMovingImage> } } - const RealType denom = -1.0 * vcl_sqrt(sff * smm); + const RealType denom = -1.0 * std::sqrt(sff * smm); if( this->m_NumberOfPixelsCounted > 0 && denom != 0.0 ) { @@ -316,6 +320,10 @@ NormalizedCorrelationPointSetToImageMetric<TFixedPointSet, TMovingImage> PointDataIterator pointDataItr = fixedPointSet->GetPointData()->Begin(); PointDataIterator pointDataEnd = fixedPointSet->GetPointData()->End(); + TransformJacobianType jacobian(TMovingImage::ImageDimension, + this->m_Transform->GetNumberOfParameters()); + TransformJacobianType jacobianCache(TMovingImage::ImageDimension,TMovingImage::ImageDimension); + while( pointItr != pointEnd && pointDataItr != pointDataEnd ) { InputPointType inputPoint; @@ -340,8 +348,9 @@ NormalizedCorrelationPointSetToImageMetric<TFixedPointSet, TMovingImage> this->m_NumberOfPixelsCounted++; // Now compute the derivatives - TransformJacobianType jacobian; - this->m_Transform->ComputeJacobianWithRespectToParameters(inputPoint, jacobian); + this->m_Transform->ComputeJacobianWithRespectToParametersCachedTemporaries(inputPoint, + jacobian, + jacobianCache); // Get the gradient by NearestNeighboorInterpolation: // which is equivalent to round up the point components. @@ -390,7 +399,7 @@ NormalizedCorrelationPointSetToImageMetric<TFixedPointSet, TMovingImage> } } - const RealType denom = -1.0 * vcl_sqrt(sff * smm); + const RealType denom = -1.0 * std::sqrt(sff * smm); if( this->m_NumberOfPixelsCounted > 0 && denom != 0.0 ) { diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedMutualInformationHistogramImageToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedMutualInformationHistogramImageToImageMetric.hxx index f5ef8726699f47d90dc1a703f7e73a8c72c96123..48957997dabaa0ed60a1fd1dfa6d62cbc0716017 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedMutualInformationHistogramImageToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkNormalizedMutualInformationHistogramImageToImageMetric.hxx @@ -46,11 +46,11 @@ NormalizedMutualInformationHistogramImageToImageMetric< TFixedImage, \ if ( freq > 0 ) { - entropyX += freq * vcl_log(freq); + entropyX += freq * std::log(freq); } } - entropyX = -entropyX / static_cast< MeasureType >( totalFreq ) + vcl_log(totalFreq); + entropyX = -entropyX / static_cast< MeasureType >( totalFreq ) + std::log(totalFreq); for ( unsigned int i = 0; i < this->GetHistogramSize()[1]; i++ ) { @@ -59,11 +59,11 @@ NormalizedMutualInformationHistogramImageToImageMetric< TFixedImage, \ if ( freq > 0 ) { - entropyY += freq * vcl_log(freq); + entropyY += freq * std::log(freq); } } - entropyY = -entropyY / static_cast< MeasureType >( totalFreq ) + vcl_log(totalFreq); + entropyY = -entropyY / static_cast< MeasureType >( totalFreq ) + std::log(totalFreq); HistogramIteratorType it = histogram.Begin(); HistogramIteratorType end = histogram.End(); @@ -74,13 +74,13 @@ NormalizedMutualInformationHistogramImageToImageMetric< TFixedImage, \ if ( freq > 0 ) { - jointEntropy += freq * vcl_log(freq); + jointEntropy += freq * std::log(freq); } ++it; } jointEntropy = -jointEntropy / static_cast< MeasureType >( totalFreq ) - + vcl_log(totalFreq); + + std::log(totalFreq); return ( entropyX + entropyY ) / jointEntropy; } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPDEDeformableRegistrationFunction.h b/Utilities/ITK/Modules/Registration/Common/include/itkPDEDeformableRegistrationFunction.h index d8c066ccc42ddd569d476da68e88fa96aa56aa5c..6bfa5c9dce2615fa211747e5987881049b3c14ed 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPDEDeformableRegistrationFunction.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPDEDeformableRegistrationFunction.h @@ -112,9 +112,9 @@ public: protected: PDEDeformableRegistrationFunction() { - m_MovingImage = NULL; - m_FixedImage = NULL; - m_DisplacementField = NULL; + m_MovingImage = ITK_NULLPTR; + m_FixedImage = ITK_NULLPTR; + m_DisplacementField = ITK_NULLPTR; m_Energy = 0.0; m_NormalizeGradient = true; m_GradientStep = 1.0; diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageMetric.h b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageMetric.h index 1e9368260613c6fde7e9898a3770fdeb7fa2b680..a0b4f1e1ef3d88af9749345a95c71cb7ef587561 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageMetric.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageMetric.h @@ -158,7 +158,7 @@ public: itkGetConstReferenceMacro(ComputeGradient, bool); /** Return the number of parameters required by the Transform */ - unsigned int GetNumberOfParameters(void) const + virtual unsigned int GetNumberOfParameters(void) const ITK_OVERRIDE { return m_Transform->GetNumberOfParameters(); } /** Initialize the Metric by making sure that all the components @@ -169,7 +169,7 @@ public: protected: PointSetToImageMetric(); virtual ~PointSetToImageMetric() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; mutable SizeValueType m_NumberOfPixelsCounted; diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageMetric.hxx index 969920eff5aa1d792c5a97e7f4b27c62b928787a..67096510df6c4ea52b25fadc92c2e9345ada8124 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageMetric.hxx @@ -29,13 +29,13 @@ template< typename TFixedPointSet, typename TMovingImage > PointSetToImageMetric< TFixedPointSet, TMovingImage > ::PointSetToImageMetric() { - m_FixedPointSet = 0; // has to be provided by the user. - m_MovingImage = 0; // has to be provided by the user. - m_Transform = 0; // has to be provided by the user. - m_Interpolator = 0; // has to be provided by the user. + m_FixedPointSet = ITK_NULLPTR; // has to be provided by the user. + m_MovingImage = ITK_NULLPTR; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. + m_Interpolator = ITK_NULLPTR; // has to be provided by the user. m_ComputeGradient = true; // metric computes gradient by default m_NumberOfPixelsCounted = 0; // initialize to zero - m_GradientImage = NULL; // computed at initialization + m_GradientImage = ITK_NULLPTR; // computed at initialization } /** diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageRegistrationMethod.h b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageRegistrationMethod.h index 0e8c59d1fab99e585e744d657ef76a8b8eef8d75..9f5f88074b03e45882c5aeb5993c1f222a644846 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageRegistrationMethod.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageRegistrationMethod.h @@ -156,11 +156,11 @@ public: * output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** Method to return the latest modified time of this object or * any of its cached ivars */ - ModifiedTimeType GetMTime() const; + virtual ModifiedTimeType GetMTime() const ITK_OVERRIDE; #ifdef ITKV3_COMPATIBILITY /** Method that initiates the registration. */ @@ -181,11 +181,11 @@ public: protected: PointSetToImageRegistrationMethod(); virtual ~PointSetToImageRegistrationMethod() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Method invoked by the pipeline in order to trigger the computation of * the registration. */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: PointSetToImageRegistrationMethod(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageRegistrationMethod.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageRegistrationMethod.hxx index 30e0950512c3e375f64b5ad0b163d36de8f94846..b2d4ae386dedc2466ee29f50fc72d496e7e53f56 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageRegistrationMethod.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToImageRegistrationMethod.hxx @@ -31,12 +31,12 @@ PointSetToImageRegistrationMethod< TFixedPointSet, TMovingImage > { this->SetNumberOfRequiredOutputs(1); // for the Transform - m_FixedPointSet = 0; // has to be provided by the user. - m_MovingImage = 0; // has to be provided by the user. - m_Transform = 0; // has to be provided by the user. - m_Interpolator = 0; // has to be provided by the user. - m_Metric = 0; // has to be provided by the user. - m_Optimizer = 0; // has to be provided by the user. + m_FixedPointSet = ITK_NULLPTR; // has to be provided by the user. + m_MovingImage = ITK_NULLPTR; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. + m_Interpolator = ITK_NULLPTR; // has to be provided by the user. + m_Metric = ITK_NULLPTR; // has to be provided by the user. + m_Optimizer = ITK_NULLPTR; // has to be provided by the user. m_InitialTransformParameters = ParametersType(1); m_LastTransformParameters = ParametersType(1); @@ -215,7 +215,7 @@ PointSetToImageRegistrationMethod< TFixedPointSet, TMovingImage > break; default: itkExceptionMacro("MakeOutput request for an output number larger than the expected number of outputs"); - return 0; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetMetric.h b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetMetric.h index 7419f04c9d5f3809c74a643a2ba7fe3075a96fc6..f4776a8729ec890a5bc650b008f5d82ee8299c99 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetMetric.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetMetric.h @@ -114,7 +114,7 @@ public: void SetTransformParameters(const ParametersType & parameters) const; /** Return the number of parameters required by the Transform */ - unsigned int GetNumberOfParameters(void) const + virtual unsigned int GetNumberOfParameters(void) const ITK_OVERRIDE { return m_Transform->GetNumberOfParameters(); } /** Initialize the Metric by making sure that all the components @@ -125,7 +125,7 @@ public: protected: PointSetToPointSetMetric(); virtual ~PointSetToPointSetMetric() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; FixedPointSetConstPointer m_FixedPointSet; diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetMetric.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetMetric.hxx index 8121c0c978ddb221bc039d2cb443a7d95cd494da..6786d76fbaa93ef07a038dd0c0b1af1180bf14a6 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetMetric.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetMetric.hxx @@ -27,9 +27,9 @@ template< typename TFixedPointSet, typename TMovingPointSet > PointSetToPointSetMetric< TFixedPointSet, TMovingPointSet > ::PointSetToPointSetMetric() { - m_FixedPointSet = 0; // has to be provided by the user. - m_MovingPointSet = 0; // has to be provided by the user. - m_Transform = 0; // has to be provided by the user. + m_FixedPointSet = ITK_NULLPTR; // has to be provided by the user. + m_MovingPointSet = ITK_NULLPTR; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. } /** Set the parameters that define a unique transform */ diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetRegistrationMethod.h b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetRegistrationMethod.h index 88c6d2b8fd547acc3651d19fb955abc4f9bff645..8def77a8c03f103e7e81606e3cfe96a5b204e84d 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetRegistrationMethod.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetRegistrationMethod.h @@ -146,11 +146,11 @@ public: * output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** Method to return the latest modified time of this object or * any of its cached ivars */ - ModifiedTimeType GetMTime() const; + virtual ModifiedTimeType GetMTime() const ITK_OVERRIDE; #ifdef ITKV3_COMPATIBILITY /** Method that initiates the registration. This will Initialize and ensure @@ -174,11 +174,11 @@ public: protected: PointSetToPointSetRegistrationMethod(); virtual ~PointSetToPointSetRegistrationMethod() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Method invoked by the pipeline in order to trigger the computation of * the registration. */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: PointSetToPointSetRegistrationMethod(const Self &); //purposely not diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetRegistrationMethod.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetRegistrationMethod.hxx index 8c6559356d4814149b5d460f361ea051bcbc094f..e5c5142a274b66e70df25a3d8ddf0aa511077a62 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetRegistrationMethod.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToPointSetRegistrationMethod.hxx @@ -31,11 +31,11 @@ PointSetToPointSetRegistrationMethod< TFixedPointSet, TMovingPointSet > { this->SetNumberOfRequiredOutputs(1); // for the Transform - m_FixedPointSet = 0; // has to be provided by the user. - m_MovingPointSet = 0; // has to be provided by the user. - m_Transform = 0; // has to be provided by the user. - m_Metric = 0; // has to be provided by the user. - m_Optimizer = 0; // has to be provided by the user. + m_FixedPointSet = ITK_NULLPTR; // has to be provided by the user. + m_MovingPointSet = ITK_NULLPTR; // has to be provided by the user. + m_Transform = ITK_NULLPTR; // has to be provided by the user. + m_Metric = ITK_NULLPTR; // has to be provided by the user. + m_Optimizer = ITK_NULLPTR; // has to be provided by the user. m_InitialTransformParameters = ParametersType(1); m_LastTransformParameters = ParametersType(1); @@ -204,7 +204,7 @@ PointSetToPointSetRegistrationMethod< TFixedPointSet, TMovingPointSet > break; default: itkExceptionMacro("MakeOutput request for an output number larger than the expected number of outputs"); - return 0; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToSpatialObjectDemonsRegistration.h b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToSpatialObjectDemonsRegistration.h index b1aba2b681f8d818f22bd879bdde8be2bca683d1..b30ed172552cf438751559f33d4d9fd2b7fce97f 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToSpatialObjectDemonsRegistration.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToSpatialObjectDemonsRegistration.h @@ -103,7 +103,7 @@ public: protected: PointSetToSpatialObjectDemonsRegistration(); virtual ~PointSetToSpatialObjectDemonsRegistration() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: PointSetToSpatialObjectDemonsRegistration(const Self &); //purposely not diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToSpatialObjectDemonsRegistration.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToSpatialObjectDemonsRegistration.hxx index 492c3b55cc2ced066d4b4f08ba86cd9b66914c4c..b38ad32f04e6a7a45dcdb66c2618e96368b7dff4 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToSpatialObjectDemonsRegistration.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointSetToSpatialObjectDemonsRegistration.hxx @@ -29,8 +29,8 @@ template< typename TFixedPointSet, typename TMovingSpatialObject > PointSetToSpatialObjectDemonsRegistration< TFixedPointSet, TMovingSpatialObject > ::PointSetToSpatialObjectDemonsRegistration() { - m_FixedPointSet = 0; // has to be provided by the user. - m_MovingSpatialObject = 0; // has to be provided by the user. + m_FixedPointSet = ITK_NULLPTR; // has to be provided by the user. + m_MovingSpatialObject = ITK_NULLPTR; // has to be provided by the user. } /** diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkPointsLocator.h b/Utilities/ITK/Modules/Registration/Common/include/itkPointsLocator.h index ad38c487954b89b8f857fcf18cb3d971864debd8..79b905b5e2ef4565c91d2fb18195c2e84c6550da 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkPointsLocator.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkPointsLocator.h @@ -112,7 +112,7 @@ public: protected: PointsLocator(); ~PointsLocator(); - virtual void PrintSelf(std::ostream& os, Indent indent) const; + virtual void PrintSelf(std::ostream& os, Indent indent) const ITK_OVERRIDE; private: PointsLocator( const Self& ); //purposely not implemented diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkRecursiveMultiResolutionPyramidImageFilter.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkRecursiveMultiResolutionPyramidImageFilter.hxx index b07ce34ee03638e9f28d41609be52fc07e65414c..c8b172319a719fe858964886cf933ccdd9273ce7 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkRecursiveMultiResolutionPyramidImageFilter.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkRecursiveMultiResolutionPyramidImageFilter.hxx @@ -347,14 +347,14 @@ RecursiveMultiResolutionPyramidImageFilter< TInputImage, TOutputImage > requestedIndex[idim] += radius[idim]; // take into account shrink component - requestedSize[idim] = static_cast< SizeValueType >( vcl_floor( + requestedSize[idim] = static_cast< SizeValueType >( std::floor( static_cast< double >( requestedSize[idim] ) / static_cast< double >( factors[idim] ) ) ); if ( requestedSize[idim] < 1 ) { requestedSize[idim] = 1; } - requestedIndex[idim] = static_cast< IndexValueType >( vcl_ceil( + requestedIndex[idim] = static_cast< IndexValueType >( std::ceil( static_cast< double >( requestedIndex[idim] ) / static_cast< double >( factors[idim] ) ) ); } diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkSimpleMultiResolutionImageRegistrationUI.h b/Utilities/ITK/Modules/Registration/Common/include/itkSimpleMultiResolutionImageRegistrationUI.h index f758926f4fbfe085d02f503029b48bf70c820c09..f12ad93d16f18a228fd40798db7164759728b08b 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkSimpleMultiResolutionImageRegistrationUI.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkSimpleMultiResolutionImageRegistrationUI.h @@ -30,7 +30,8 @@ template <typename TRegistrator> class SimpleMultiResolutionImageRegistrationUI { public: - SimpleMultiResolutionImageRegistrationUI( TRegistrator * ptr ) + SimpleMultiResolutionImageRegistrationUI( TRegistrator * ptr ): + m_Tag(0) { if ( !ptr ) return; diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkTimeVaryingBSplineVelocityFieldTransformParametersAdaptor.hxx b/Utilities/ITK/Modules/Registration/Common/include/itkTimeVaryingBSplineVelocityFieldTransformParametersAdaptor.hxx index e42e347119f5b0b8e7e0b400028afe0a0bc7b59e..86e32c9319e9a7c30e06e9db99cf8e5f79a1796c 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkTimeVaryingBSplineVelocityFieldTransformParametersAdaptor.hxx +++ b/Utilities/ITK/Modules/Registration/Common/include/itkTimeVaryingBSplineVelocityFieldTransformParametersAdaptor.hxx @@ -38,7 +38,7 @@ TimeVaryingBSplineVelocityFieldTransformParametersAdaptor<TTransform> this->m_RequiredTransformDomainOrigin.Fill( 0.0 ); this->m_RequiredTransformDomainDirection.SetIdentity(); - this->m_RequiredTransformDomainSize.Fill( 1.0 ); + this->m_RequiredTransformDomainSize.Fill( 1 ); this->m_RequiredTransformDomainSpacing.Fill( 0.0 ); this->m_RequiredTransformDomainMeshSize.Fill( 1 ); diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkTransformParametersAdaptor.h b/Utilities/ITK/Modules/Registration/Common/include/itkTransformParametersAdaptor.h index 8397734cbd5b3a3e0835034044d8a2efc7f1df00..9fb3e5c28e47be7e37992e5341f7ce747cee4a10 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkTransformParametersAdaptor.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkTransformParametersAdaptor.h @@ -19,6 +19,7 @@ #define __itkTransformParametersAdaptor_h #include "itkTransformParametersAdaptorBase.h" +#include "itkTransform.h" namespace itk { @@ -52,13 +53,13 @@ namespace itk */ template<typename TTransform> class TransformParametersAdaptor -: public TransformParametersAdaptorBase<TTransform> +: public TransformParametersAdaptorBase< Transform<typename TTransform::ScalarType, TTransform::InputSpaceDimension, TTransform::OutputSpaceDimension> > { public: /** Standard class typedefs. */ typedef TransformParametersAdaptor Self; - typedef TransformParametersAdaptorBase<TTransform> Superclass; + typedef TransformParametersAdaptorBase<Transform<typename TTransform::ScalarType, TTransform::InputSpaceDimension, TTransform::OutputSpaceDimension> > Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; @@ -66,14 +67,23 @@ public: itkTypeMacro( TransformParametersAdaptor, TransformParametersAdaptorBase ); /** Typedefs associated with the transform */ + + typedef typename Superclass::TransformBaseType TransformBaseType; typedef TTransform TransformType; - typedef typename Superclass::TransformPointer TransformPointer; - typedef typename Superclass::ParametersType ParametersType; + typedef typename TransformType::Pointer TransformPointer; + typedef typename TransformType::ParametersType ParametersType; typedef typename Superclass::ParametersValueType ParametersValueType; /** Set the transform to be adapted */ itkSetObjectMacro( Transform, TransformType ); + virtual void SetTransform( TransformBaseType * _arg, void * ) + { + TransformType *tx = dynamic_cast<TransformType *>(_arg); + itkAssertOrThrowMacro( tx != ITK_NULLPTR, "Unable to convert Transform to require concrete transform!" ); + this->SetTransform(tx); + } + /** New macro for creation of through the object factory. */ itkNewMacro( Self ); @@ -90,13 +100,13 @@ protected: TransformParametersAdaptor() {} ~TransformParametersAdaptor() {} - void PrintSelf( std::ostream & os, Indent itkNotUsed( indent ) ) const + void PrintSelf( std::ostream & os, Indent indent ) const { - os << "Fixed parameters: " << this->m_RequiredFixedParameters << std::endl; + Superclass::PrintSelf( os, indent ); + itkPrintSelfObjectMacro( Transform ); } TransformPointer m_Transform; - ParametersType m_RequiredFixedParameters; private: TransformParametersAdaptor( const Self & ); //purposely not implemented diff --git a/Utilities/ITK/Modules/Registration/Common/include/itkTransformParametersAdaptorBase.h b/Utilities/ITK/Modules/Registration/Common/include/itkTransformParametersAdaptorBase.h index 80e1445a392244dac2f2948083d95e21b5f0e81b..3e91099af2cef0865043d8fbe75e8759ef9cec93 100644 --- a/Utilities/ITK/Modules/Registration/Common/include/itkTransformParametersAdaptorBase.h +++ b/Utilities/ITK/Modules/Registration/Common/include/itkTransformParametersAdaptorBase.h @@ -67,13 +67,14 @@ public: itkTypeMacro( TransformParametersAdaptorBase, Object ); /** Typedefs associated with the transform */ - typedef TTransform TransformType; - typedef typename TransformType::Pointer TransformPointer; - typedef typename TransformType::ParametersType ParametersType; + typedef TTransform TransformBaseType; + typedef typename TransformBaseType::Pointer TransformBasePointer; + typedef typename TransformBaseType::ParametersType ParametersType; typedef typename ParametersType::ValueType ParametersValueType; - /** Set the transform to be adapted */ - itkSetObjectMacro( Transform, TransformType ); + // note: the void pointer is use to ensure this method has lower + // overloaded priority and avoid an ambiguous overloaded method + virtual void SetTransform( TransformBaseType *_arg, void * priorityLower = ITK_NULLPTR ) = 0; /** Set the fixed parameters */ itkSetMacro( RequiredFixedParameters, ParametersType ); @@ -88,13 +89,12 @@ protected: TransformParametersAdaptorBase() {} ~TransformParametersAdaptorBase() {} - void PrintSelf( std::ostream & os, Indent indent ) const + virtual void PrintSelf( std::ostream & os, Indent indent ) const ITK_OVERRIDE { - this->m_Transform->Print( os, indent ); + Superclass::PrintSelf( os, indent ); os << "Fixed parameters" << this->m_RequiredFixedParameters << std::endl; } - TransformPointer m_Transform; ParametersType m_RequiredFixedParameters; private: diff --git a/Utilities/ITK/Modules/Registration/Common/wrapping/itkBlockMatchingImageFilter.wrap b/Utilities/ITK/Modules/Registration/Common/wrapping/itkBlockMatchingImageFilter.wrap index 55eace4e10c5e87d8109f3bdfa30e396e52e7dcc..99589f62081687dd849474772c496a93d4704f1e 100644 --- a/Utilities/ITK/Modules/Registration/Common/wrapping/itkBlockMatchingImageFilter.wrap +++ b/Utilities/ITK/Modules/Registration/Common/wrapping/itkBlockMatchingImageFilter.wrap @@ -1,3 +1,7 @@ -itk_wrap_class("itk::BlockMatchingImageFilter" POINTER_WITH_2_SUPERCLASSES) - itk_wrap_image_filter("${WRAP_ITK_REAL}" 1 3) -itk_end_wrap_class() +itk_wrap_filter_dims(has_d_3 3) + +if(has_d_3) + itk_wrap_class("itk::BlockMatchingImageFilter" POINTER_WITH_2_SUPERCLASSES) + itk_wrap_image_filter("${WRAP_ITK_REAL}" 1 3) + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Registration/Common/wrapping/itkCenteredVersorTransformInitializer.wrap b/Utilities/ITK/Modules/Registration/Common/wrapping/itkCenteredVersorTransformInitializer.wrap index b9a0ba89d5f0985db365c578c42abb91a37fe6df..346f41d602f40c5598b24ed0dad706e46de3f997 100644 --- a/Utilities/ITK/Modules/Registration/Common/wrapping/itkCenteredVersorTransformInitializer.wrap +++ b/Utilities/ITK/Modules/Registration/Common/wrapping/itkCenteredVersorTransformInitializer.wrap @@ -1,4 +1,7 @@ -itk_wrap_class("itk::CenteredVersorTransformInitializer" POINTER) - # the superclass use a class which support only dim=3 - itk_wrap_image_filter("${WRAP_ITK_SCALAR}" 2 3) -itk_end_wrap_class() +itk_wrap_filter_dims(has_d_3 3) + +if(has_d_3) + itk_wrap_class("itk::CenteredVersorTransformInitializer" POINTER) + itk_wrap_image_filter("${WRAP_ITK_SCALAR}" 2 3) + itk_end_wrap_class() +endif(has_d_3) diff --git a/Utilities/ITK/Modules/Registration/GPUPDEDeformable/include/itkGPUDemonsRegistrationFunction.hxx b/Utilities/ITK/Modules/Registration/GPUPDEDeformable/include/itkGPUDemonsRegistrationFunction.hxx index 52e8893ea963266c458d2869d375df182360a97d..38808f6fdacb669b54282b748292d2fc709f3301 100644 --- a/Utilities/ITK/Modules/Registration/GPUPDEDeformable/include/itkGPUDemonsRegistrationFunction.hxx +++ b/Utilities/ITK/Modules/Registration/GPUPDEDeformable/include/itkGPUDemonsRegistrationFunction.hxx @@ -297,7 +297,7 @@ GPUDemonsRegistrationFunction< TFixedImage, TMovingImage, TDisplacementField > { m_Metric = m_SumOfSquaredDifference / static_cast<double>( m_NumberOfPixelsProcessed ); - m_RMSChange = vcl_sqrt( m_SumOfSquaredChange / + m_RMSChange = std::sqrt( m_SumOfSquaredChange / static_cast<double>( m_NumberOfPixelsProcessed ) ); } } @@ -415,7 +415,7 @@ GPUDemonsRegistrationFunction< TFixedImage, TMovingImage, TDisplacementField > { m_Metric = m_SumOfSquaredDifference / static_cast< double >( m_NumberOfPixelsProcessed ); - m_RMSChange = vcl_sqrt( m_SumOfSquaredChange + m_RMSChange = std::sqrt( m_SumOfSquaredChange / static_cast< double >( m_NumberOfPixelsProcessed ) ); } m_MetricCalculationLock.Unlock(); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.h index 7a5c52e0e87454b6a9c0e795c4f112af93188623..73c28b652261fc4d41034347ed703d80c7063d5d 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.h @@ -143,7 +143,9 @@ public: } ScanParametersType; protected: - ANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader() {} + ANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader() : + m_ANTSAssociate(ITK_NULLPTR) + {} /** * Dense threader and sparse threader invoke different in multi-threading. This class uses overloaded @@ -216,7 +218,7 @@ protected: const MovingImageGradientType & itkNotUsed(mappedMovingImageGradient), MeasureType & itkNotUsed(metricValueReturn), DerivativeType & itkNotUsed(localDerivativeReturn), - const ThreadIdType itkNotUsed(threadID) ) const + const ThreadIdType itkNotUsed(threadId) ) const { itkExceptionMacro("ProcessPoint should never be reached in ANTS CC metric threader class."); } @@ -250,12 +252,12 @@ protected: * UpdateQueuesAtBeginningOfLine or \c UpdateQueuesToNextScanWindow. */ void UpdateQueues(const ScanIteratorType &scanIt, ScanMemType &scanMem, const ScanParametersType &scanParameters, - const ThreadIdType threadID) const; + const ThreadIdType threadId) const; void UpdateQueuesAtBeginningOfLine( const ScanIteratorType &scanIt, ScanMemType &scanMem, const ScanParametersType &scanParameters, - const ThreadIdType threadID) const; + const ThreadIdType threadId) const; /** Increment the iterator and check to see if we're at the end of the * line. If so, go to the next line. Otherwise, add the @@ -263,19 +265,19 @@ protected: void UpdateQueuesToNextScanWindow( const ScanIteratorType &scanIt, ScanMemType &scanMem, const ScanParametersType &scanParameters, - const ThreadIdType threadID) const; + const ThreadIdType threadId) const; /** Test to see if there are any voxels we need to handle in the current * window. */ bool ComputeInformationFromQueues( const ScanIteratorType &scanIt, ScanMemType &scanMem, const ScanParametersType &scanParameters, - const ThreadIdType threadID) const; + const ThreadIdType threadId) const; void ComputeMovingTransformDerivative( const ScanIteratorType &scanIt, ScanMemType &scanMem, const ScanParametersType &scanParameters, DerivativeType &deriv, - MeasureType &local_cc, const ThreadIdType threadID) const; + MeasureType &local_cc, const ThreadIdType threadId) const; private: ANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader( const Self & ); // purposely not implemented diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.hxx index 09bd4a1cc2029f12e715528e719521ed9590ae58..1a02ff2a66f01c538dd29512dec7a7f517e4adf6 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.hxx @@ -33,7 +33,7 @@ ANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader< TD { /* Store the casted pointer to avoid dynamic casting in tight loops. */ this->m_ANTSAssociate = dynamic_cast< TNeighborhoodCorrelationMetric * >( this->m_Associate ); - if( this->m_ANTSAssociate == NULL ) + if( this->m_ANTSAssociate == ITK_NULLPTR ) { itkExceptionMacro("Dynamic casting of associate pointer failed."); } @@ -112,7 +112,7 @@ ANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader< TD /* call base method */ /* Store the casted pointer to avoid dynamic casting in tight loops. */ this->m_ANTSAssociate = dynamic_cast< TNeighborhoodCorrelationMetric * >( this->m_Associate ); - if( this->m_ANTSAssociate == NULL ) + if( this->m_ANTSAssociate == ITK_NULLPTR ) { itkExceptionMacro("Dynamic casting of associate pointer failed."); } @@ -503,10 +503,15 @@ ANTSNeighborhoodCorrelationImageToImageMetricv4GetValueAndDerivativeThreader< TD } /* Use a pre-allocated jacobian object for efficiency */ - JacobianType & jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobian; + typedef JacobianType & JacobianReferenceType; + JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobian; + JacobianReferenceType jacobianPositional = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobianPositional; /** For dense transforms, this returns identity */ - this->m_Associate->GetMovingTransform()->ComputeJacobianWithRespectToParameters( scanMem.virtualPoint, jacobian ); + this->m_Associate->GetMovingTransform()-> + ComputeJacobianWithRespectToParametersCachedTemporaries(scanMem.virtualPoint, + jacobian, + jacobianPositional); NumberOfParametersType numberOfLocalParameters = this->m_Associate->GetMovingTransform()->GetNumberOfLocalParameters(); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4.hxx index f8129d32368d8b2e39fe1dce1ba15cb77889736a..6c1f827e1d4bc06b0be2660d090e5926596be0d4 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4.hxx @@ -25,15 +25,17 @@ namespace itk template <typename TFixedImage, typename TMovingImage, typename TVirtualImage, typename TInternalComputationValueType, typename TMetricTraits> CorrelationImageToImageMetricv4<TFixedImage,TMovingImage,TVirtualImage, TInternalComputationValueType, TMetricTraits> -::CorrelationImageToImageMetricv4() +::CorrelationImageToImageMetricv4() : + m_AverageFix(0.0), + m_AverageMov(0.0) { - // We have our own GetValueAndDerivativeThreader's that we want - // ImageToImageMetricv4 to use. - this->m_DenseGetValueAndDerivativeThreader = CorrelationDenseGetValueAndDerivativeThreaderType::New(); - this->m_SparseGetValueAndDerivativeThreader = CorrelationSparseGetValueAndDerivativeThreaderType::New(); + this->m_DenseGetValueAndDerivativeThreader = + CorrelationDenseGetValueAndDerivativeThreaderType::New(); + this->m_SparseGetValueAndDerivativeThreader = + CorrelationSparseGetValueAndDerivativeThreaderType::New(); - this->m_HelperDenseThreader = CorrelationHelperDenseThreaderType::New(); - this->m_HelperSparseThreader = CorrelationHelperSparseThreaderType::New(); + m_HelperDenseThreader = CorrelationHelperDenseThreaderType::New(); + m_HelperSparseThreader = CorrelationHelperSparseThreaderType::New(); if( this->m_MovingTransform->GetTransformCategory() == MovingTransformType::DisplacementField ) { diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.h index 2801650bc67ea62b842e024adcbf2cfadafa5ff7..946045224ee4a55b3312ec5ad44b075af4bb12d5 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.h @@ -110,7 +110,7 @@ protected: const MovingImageGradientType & mappedMovingImageGradient, MeasureType & metricValueReturn, DerivativeType & localDerivativeReturn, - const ThreadIdType threadID ) const; + const ThreadIdType threadId ) const; private: CorrelationImageToImageMetricv4GetValueAndDerivativeThreader( const Self & ); // purposely not implemented diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.hxx index ff2f415587e83155f9f00854219a61945e1bfb65..ae22f4489dbc60706095e199395b3783233ad65e 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4GetValueAndDerivativeThreader.hxx @@ -25,10 +25,10 @@ namespace itk template<typename TDomainPartitioner, typename TImageToImageMetric, typename TCorrelationMetric> CorrelationImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TCorrelationMetric> -::CorrelationImageToImageMetricv4GetValueAndDerivativeThreader(): - m_CorrelationMetricValueDerivativePerThreadVariables( NULL ) -{ -} +::CorrelationImageToImageMetricv4GetValueAndDerivativeThreader() : + m_CorrelationMetricValueDerivativePerThreadVariables( ITK_NULLPTR ), + m_CorrelationAssociate( ITK_NULLPTR ) +{} template<typename TDomainPartitioner, typename TImageToImageMetric, typename TCorrelationMetric> @@ -48,7 +48,7 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner /* Store the casted pointer to avoid dynamic casting in tight loops. */ this->m_CorrelationAssociate = dynamic_cast<TCorrelationMetric *>(this->m_Associate); - if( this->m_CorrelationAssociate == NULL ) + if( this->m_CorrelationAssociate == ITK_NULLPTR ) { itkExceptionMacro("Dynamic casting of associate pointer failed."); } @@ -56,10 +56,11 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner /* This size always comes from the moving image */ const NumberOfParametersType globalDerivativeSize = this->GetCachedNumberOfParameters(); + const ThreadIdType numThreadsUsed = this->GetNumberOfThreadsUsed(); // set size delete[] m_CorrelationMetricValueDerivativePerThreadVariables; - m_CorrelationMetricValueDerivativePerThreadVariables = new AlignedCorrelationMetricValueDerivativePerThreadStruct[ this->GetNumberOfThreadsUsed() ]; - for (ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); i++) + m_CorrelationMetricValueDerivativePerThreadVariables = new AlignedCorrelationMetricValueDerivativePerThreadStruct[ numThreadsUsed ]; + for (ThreadIdType i = 0; i < numThreadsUsed; ++i) { this->m_CorrelationMetricValueDerivativePerThreadVariables[i].fdm.SetSize(globalDerivativeSize); this->m_CorrelationMetricValueDerivativePerThreadVariables[i].mdm.SetSize(globalDerivativeSize); @@ -67,7 +68,7 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner //--------------------------------------------------------------- // Set initial values. - for (ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); i++) + for (ThreadIdType i = 0; i < numThreadsUsed; ++i) { m_CorrelationMetricValueDerivativePerThreadVariables[i].fm = NumericTraits<InternalComputationValueType>::Zero; m_CorrelationMetricValueDerivativePerThreadVariables[i].f2 = NumericTraits<InternalComputationValueType>::Zero; @@ -89,11 +90,12 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader<TDomainPartitioner, /* This size always comes from the moving image */ const NumberOfParametersType globalDerivativeSize = this->GetCachedNumberOfParameters(); + const ThreadIdType numThreadsUsed = this->GetNumberOfThreadsUsed(); /* Store the number of valid points the enclosing class \c * m_NumberOfValidPoints by collecting the valid points per thread. */ this->m_CorrelationAssociate->m_NumberOfValidPoints = NumericTraits<SizeValueType>::Zero; - for (ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); i++) + for (ThreadIdType i = 0; i < numThreadsUsed; ++i) { this->m_CorrelationAssociate->m_NumberOfValidPoints += this->m_GetValueAndDerivativePerThreadVariables[i].NumberOfValidPoints; } @@ -112,7 +114,7 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader<TDomainPartitioner, InternalComputationValueType fm = NumericTraits<InternalComputationValueType>::Zero; InternalComputationValueType f2 = NumericTraits<InternalComputationValueType>::Zero; InternalComputationValueType m2 = NumericTraits<InternalComputationValueType>::Zero; - for (ThreadIdType threadId = 0; threadId < this->GetNumberOfThreadsUsed(); ++threadId) + for (ThreadIdType threadId = 0; threadId < numThreadsUsed; ++threadId) { fm += this->m_CorrelationMetricValueDerivativePerThreadVariables[threadId].fm; m2 += this->m_CorrelationMetricValueDerivativePerThreadVariables[threadId].m2; @@ -140,7 +142,7 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader<TDomainPartitioner, const InternalComputationValueType fc = static_cast<InternalComputationValueType>( 2.0 ); - for (ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); i++) + for (ThreadIdType i = 0; i < numThreadsUsed; ++i) { fdm += this->m_CorrelationMetricValueDerivativePerThreadVariables[i].fdm; mdm += this->m_CorrelationMetricValueDerivativePerThreadVariables[i].mdm; @@ -265,7 +267,7 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader<TDomainPartitioner, const MovingImageGradientType & movingImageGradient, MeasureType & itkNotUsed(metricValueReturn), DerivativeType & itkNotUsed(localDerivativeReturn), - const ThreadIdType threadID) const + const ThreadIdType threadId) const { /* @@ -278,7 +280,7 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader<TDomainPartitioner, const InternalComputationValueType & f1 = fixedImageValue - this->m_CorrelationAssociate->m_AverageFix; const InternalComputationValueType & m1 = movingImageValue - this->m_CorrelationAssociate->m_AverageMov; - AlignedCorrelationMetricValueDerivativePerThreadStruct & cumsum = this->m_CorrelationMetricValueDerivativePerThreadVariables[threadID]; + AlignedCorrelationMetricValueDerivativePerThreadStruct & cumsum = this->m_CorrelationMetricValueDerivativePerThreadVariables[threadId]; cumsum.f += f1; cumsum.m += m1; cumsum.f2 += f1 * f1; @@ -289,10 +291,14 @@ CorrelationImageToImageMetricv4GetValueAndDerivativeThreader<TDomainPartitioner, { /* Use a pre-allocated jacobian object for efficiency */ typedef typename TImageToImageMetric::JacobianType & JacobianReferenceType; - JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadID].MovingTransformJacobian; + JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobian; + JacobianReferenceType jacobianPositional = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobianPositional; /** For dense transforms, this returns identity */ - this->m_CorrelationAssociate->GetMovingTransform()->ComputeJacobianWithRespectToParameters(virtualPoint, jacobian); + this->m_CorrelationAssociate->GetMovingTransform()-> + ComputeJacobianWithRespectToParametersCachedTemporaries(virtualPoint, + jacobian, + jacobianPositional); for (unsigned int par = 0; par < this->m_CorrelationAssociate->GetNumberOfLocalParameters(); par++) { diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4HelperThreader.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4HelperThreader.hxx index c406321ac71c181b33be5ab4b9267c15da310013..1ce3d7e44d863fb1397c917e90d8a9b9153fba53 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4HelperThreader.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkCorrelationImageToImageMetricv4HelperThreader.hxx @@ -25,10 +25,10 @@ namespace itk template<typename TDomainPartitioner, typename TImageToImageMetric, typename TCorrelationMetric> CorrelationImageToImageMetricv4HelperThreader< TDomainPartitioner, TImageToImageMetric, TCorrelationMetric> -::CorrelationImageToImageMetricv4HelperThreader(): - m_CorrelationMetricPerThreadVariables( NULL ) -{ -} +::CorrelationImageToImageMetricv4HelperThreader() : + m_CorrelationMetricPerThreadVariables( ITK_NULLPTR ), + m_CorrelationAssociate( ITK_NULLPTR ) +{} template<typename TDomainPartitioner, typename TImageToImageMetric, typename TCorrelationMetric> @@ -49,12 +49,13 @@ CorrelationImageToImageMetricv4HelperThreader< TDomainPartitioner, TImageToImage /* Store the casted pointer to avoid dynamic casting in tight loops. */ this->m_CorrelationAssociate = dynamic_cast<TCorrelationMetric *>(this->m_Associate); + const ThreadIdType numThreadsUsed = this->GetNumberOfThreadsUsed(); delete[] this->m_CorrelationMetricPerThreadVariables; - this->m_CorrelationMetricPerThreadVariables = new AlignedCorrelationMetricPerThreadStruct[ this->GetNumberOfThreadsUsed() ]; + this->m_CorrelationMetricPerThreadVariables = new AlignedCorrelationMetricPerThreadStruct[ numThreadsUsed ]; //--------------------------------------------------------------- // Set initial values. - for (ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); i++) + for (ThreadIdType i = 0; i < numThreadsUsed; ++i) { this->m_CorrelationMetricPerThreadVariables[i].FixSum = NumericTraits<InternalComputationValueType>::Zero; this->m_CorrelationMetricPerThreadVariables[i].MovSum = NumericTraits<InternalComputationValueType>::Zero; @@ -72,7 +73,9 @@ CorrelationImageToImageMetricv4HelperThreader<TDomainPartitioner, * m_NumberOfValidPoints by collecting the valid points per thread. */ this->m_CorrelationAssociate->m_NumberOfValidPoints = NumericTraits<SizeValueType>::Zero; - for (ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); i++) + const ThreadIdType numThreadsUsed = this->GetNumberOfThreadsUsed(); + + for (ThreadIdType i = 0; i < numThreadsUsed; ++i) { this->m_CorrelationAssociate->m_NumberOfValidPoints += this->m_GetValueAndDerivativePerThreadVariables[i].NumberOfValidPoints; } @@ -86,7 +89,7 @@ CorrelationImageToImageMetricv4HelperThreader<TDomainPartitioner, InternalComputationValueType sumF = NumericTraits<InternalComputationValueType>::Zero; InternalComputationValueType sumM = NumericTraits<InternalComputationValueType>::Zero; - for (ThreadIdType threadId = 0; threadId < this->GetNumberOfThreadsUsed(); ++threadId) + for (ThreadIdType threadId = 0; threadId < numThreadsUsed; ++threadId) { sumF += this->m_CorrelationMetricPerThreadVariables[threadId].FixSum; sumM += this->m_CorrelationMetricPerThreadVariables[threadId].MovSum; @@ -100,7 +103,7 @@ template<typename TDomainPartitioner, typename TImageToImageMetric, typename TCo bool CorrelationImageToImageMetricv4HelperThreader<TDomainPartitioner, TImageToImageMetric, TCorrelationMetric> -::ProcessVirtualPoint( const VirtualIndexType & itkNotUsed(virtualIndex), const VirtualPointType & virtualPoint, const ThreadIdType threadID ) +::ProcessVirtualPoint( const VirtualIndexType & itkNotUsed(virtualIndex), const VirtualPointType & virtualPoint, const ThreadIdType threadId ) { FixedImagePointType mappedFixedPoint; FixedImagePixelType mappedFixedPixelValue; @@ -148,8 +151,8 @@ TImageToImageMetric, TCorrelationMetric> /* Do the specific calculations for values */ try { - this->m_CorrelationMetricPerThreadVariables[threadID].FixSum += mappedFixedPixelValue; - this->m_CorrelationMetricPerThreadVariables[threadID].MovSum += mappedMovingPixelValue; + this->m_CorrelationMetricPerThreadVariables[threadId].FixSum += mappedFixedPixelValue; + this->m_CorrelationMetricPerThreadVariables[threadId].MovSum += mappedMovingPixelValue; } catch( ExceptionObject & exc ) { @@ -160,7 +163,7 @@ TImageToImageMetric, TCorrelationMetric> } if( pointIsValid ) { - this->m_GetValueAndDerivativePerThreadVariables[threadID].NumberOfValidPoints++; + this->m_GetValueAndDerivativePerThreadVariables[threadId].NumberOfValidPoints++; } return pointIsValid; diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.h index 57e8ac6c02f497d4ff314abdd1924bbc000abca9..471b505859b135fd2baa1dadf3cc57475688828a 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.h @@ -64,7 +64,9 @@ public: typedef typename Superclass::ImageDimensionType ImageDimensionType; protected: - DemonsImageToImageMetricv4GetValueAndDerivativeThreader() {} + DemonsImageToImageMetricv4GetValueAndDerivativeThreader() : + m_DemonsAssociate(ITK_NULLPTR) + {} /** Overload. * Get pointer to metric object. @@ -85,7 +87,7 @@ protected: const MovingImageGradientType & mappedMovingImageGradient, MeasureType & metricValueReturn, DerivativeType & localDerivativeReturn, - const ThreadIdType threadID ) const; + const ThreadIdType threadId ) const; private: DemonsImageToImageMetricv4GetValueAndDerivativeThreader( const Self & ); // purposely not implemented diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.hxx index dcba9dcd658ff6c8c3b7b7ad858280f71ac2379c..8f0fab3d41110eab879bd77aa06c84d05c68e6e5 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkDemonsImageToImageMetricv4GetValueAndDerivativeThreader.hxx @@ -31,7 +31,7 @@ DemonsImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner, TIm /* Store the casted pointer to avoid dynamic casting in tight loops. */ this->m_DemonsAssociate = dynamic_cast<TDemonsMetric*>( this->m_Associate ); - if( this->m_DemonsAssociate == NULL ) + if( this->m_DemonsAssociate == ITK_NULLPTR ) { itkExceptionMacro("Dynamic casting of associate pointer failed."); } diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkEuclideanDistancePointSetToPointSetMetricv4.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkEuclideanDistancePointSetToPointSetMetricv4.h index db896198822350d8aa8cb68ce1189c7a0054e788..444cfd27ec51ac0e27fe7f5cfee81ab3b5c3f3f6 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkEuclideanDistancePointSetToPointSetMetricv4.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkEuclideanDistancePointSetToPointSetMetricv4.h @@ -38,15 +38,17 @@ namespace itk * * \ingroup ITKMetricsv4 */ -template<typename TFixedPointSet, typename TMovingPointSet = TFixedPointSet> +template<typename TFixedPointSet, typename TMovingPointSet = TFixedPointSet, + class TInternalComputationValueType = double> class EuclideanDistancePointSetToPointSetMetricv4: - public PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> + public PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> { public: /** Standard class typedefs. */ typedef EuclideanDistancePointSetToPointSetMetricv4 Self; - typedef PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> Superclass; + typedef PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, + TInternalComputationValueType> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkEuclideanDistancePointSetToPointSetMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkEuclideanDistancePointSetToPointSetMetricv4.hxx index cc19c99a7ad949b7f9d92858f3476987b191790e..0770f1647c1a8fc9d1140b2c19b7df502250f5d7 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkEuclideanDistancePointSetToPointSetMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkEuclideanDistancePointSetToPointSetMetricv4.hxx @@ -24,23 +24,23 @@ namespace itk { /** Constructor */ -template<typename TFixedPointSet, typename TMovingPointSet> -EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::EuclideanDistancePointSetToPointSetMetricv4() { } /** Destructor */ -template<typename TFixedPointSet, typename TMovingPointSet> -EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::~EuclideanDistancePointSetToPointSetMetricv4() { } -template<typename TFixedPointSet, typename TMovingPointSet> -typename EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +typename EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::MeasureType -EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodValue( const PointType & point, const PixelType & itkNotUsed( pixel ) ) const { PointType closestPoint; @@ -53,9 +53,9 @@ EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> return distance; } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodValueAndDerivative( const PointType & point, MeasureType &measure, LocalDerivativeType & localDerivative, const PixelType & itkNotUsed( pixel ) ) const { @@ -70,9 +70,9 @@ EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } /** PrintSelf method */ -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +EuclideanDistancePointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::PrintSelf( std::ostream & os, Indent indent ) const { Superclass::PrintSelf( os, indent ); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkExpectationBasedPointSetToPointSetMetricv4.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkExpectationBasedPointSetToPointSetMetricv4.h index 564067e5ae901f66f7061a7b8faebb37f716a5f1..d17d80071ca3ec92e96cd5e5d1f74ec595bdb724 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkExpectationBasedPointSetToPointSetMetricv4.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkExpectationBasedPointSetToPointSetMetricv4.h @@ -40,15 +40,17 @@ namespace itk * * \ingroup ITKMetricsv4 */ -template<typename TFixedPointSet, typename TMovingPointSet = TFixedPointSet> +template<typename TFixedPointSet, typename TMovingPointSet = TFixedPointSet, + class TInternalComputationValueType = double> class ExpectationBasedPointSetToPointSetMetricv4: - public PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> + public PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> { public: /** Standard class typedefs. */ typedef ExpectationBasedPointSetToPointSetMetricv4 Self; - typedef PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> Superclass; + typedef PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, + TInternalComputationValueType> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; @@ -105,7 +107,7 @@ public: /** Clone method will clone the existing instance of this type, * including its internal member variables. */ - virtual ::itk::LightObject::Pointer Clone( void ) const; + virtual typename LightObject::Pointer InternalClone() const; protected: ExpectationBasedPointSetToPointSetMetricv4(); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkExpectationBasedPointSetToPointSetMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkExpectationBasedPointSetToPointSetMetricv4.hxx index a7e84db962875bb714a90ea5a6bfae732cbda781..e1230121e47d6e0a4e41cf48f634b4b501beeb5f 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkExpectationBasedPointSetToPointSetMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkExpectationBasedPointSetToPointSetMetricv4.hxx @@ -24,24 +24,26 @@ namespace itk { /** Constructor */ -template<typename TFixedPointSet, typename TMovingPointSet> -ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::ExpectationBasedPointSetToPointSetMetricv4() : m_PointSetSigma( 1.0 ), + m_PreFactor( 0.0 ), + m_Denominator( 0.0 ), m_EvaluationKNeighborhood( 50 ) { } /** Destructor */ -template<typename TFixedPointSet, typename TMovingPointSet> -ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::~ExpectationBasedPointSetToPointSetMetricv4() { } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::Initialize( void ) throw ( ExceptionObject ) { Superclass::Initialize(); @@ -50,14 +52,14 @@ ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> { itkExceptionMacro("m_PointSetSigma is too small. <= epsilon"); } - this->m_PreFactor = 1.0 / ( vcl_sqrt( 2 * vnl_math::pi ) * this->m_PointSetSigma ); + this->m_PreFactor = 1.0 / ( std::sqrt( 2 * vnl_math::pi ) * this->m_PointSetSigma ); this->m_Denominator = 2.0 * vnl_math_sqr( this->m_PointSetSigma ); } -template<typename TFixedPointSet, typename TMovingPointSet> -typename ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +typename ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::MeasureType -ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodValue( const PointType & point, const PixelType & itkNotUsed( pixel ) ) const { MeasureType localValue = NumericTraits<MeasureType>::Zero; @@ -69,15 +71,15 @@ ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> { PointType neighbor = this->m_MovingTransformedPointSet->GetPoint( *it ); const MeasureType distance = point.SquaredEuclideanDistanceTo( neighbor ); - localValue -= this->m_PreFactor * vcl_exp( -distance / this->m_Denominator ); + localValue -= this->m_PreFactor * std::exp( -distance / this->m_Denominator ); } return localValue; } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodValueAndDerivative( const PointType & point, MeasureType &measure, LocalDerivativeType &localDerivative, const PixelType & itkNotUsed( pixel ) ) const { @@ -100,11 +102,11 @@ ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> { PointType neighbor = this->m_MovingTransformedPointSet->GetPoint( *it ); const MeasureType distance = point.SquaredEuclideanDistanceTo( neighbor ); - measureValues[it - neighborhood.begin()] = -this->m_PreFactor * vcl_exp( -distance / this->m_Denominator ); + measureValues[it - neighborhood.begin()] = -this->m_PreFactor * std::exp( -distance / this->m_Denominator ); measure += measureValues[it - neighborhood.begin()]; } - if ( vcl_fabs(measure) <= NumericTraits<MeasureType>::epsilon() ) + if ( std::fabs(measure) <= NumericTraits<MeasureType>::epsilon() ) { return; } @@ -118,7 +120,7 @@ ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> const MeasureType distance = point.SquaredEuclideanDistanceTo( weightedPoint ); - const MeasureType weight = this->m_PreFactor * vcl_exp( -distance / this->m_Denominator ) / -measure; + const MeasureType weight = this->m_PreFactor * std::exp( -distance / this->m_Denominator ) / -measure; VectorType force = ( weightedPoint - point ) * weight; @@ -128,27 +130,23 @@ ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } } -template<typename TFixedPointSet, typename TMovingPointSet> -::itk::LightObject::Pointer -ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> -::Clone( void ) const +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +typename LightObject::Pointer +ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> +::InternalClone( void ) const { - ::itk::LightObject::Pointer smartPtr; - Pointer copyPtr = Self::New(); + typename Self::Pointer rval = Self::New(); + rval->SetMovingPointSet( this->m_MovingPointSet ); + rval->SetFixedPointSet( this->m_FixedPointSet ); + rval->SetPointSetSigma( this->m_PointSetSigma ); + rval->SetEvaluationKNeighborhood( this->m_EvaluationKNeighborhood ); - copyPtr->m_MovingPointSet = this->m_MovingPointSet; - copyPtr->m_FixedPointSet = this->m_FixedPointSet; - copyPtr->m_PointSetSigma = this->m_PointSetSigma; - copyPtr->m_EvaluationKNeighborhood = this->m_EvaluationKNeighborhood; - - smartPtr = static_cast<Pointer>( copyPtr ); - - return smartPtr; + return rval.GetPointer(); } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +ExpectationBasedPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::PrintSelf( std::ostream& os, Indent indent ) const { Superclass::PrintSelf( os, indent ); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4.hxx index a18759f3bb51959c5b02b86eafa24f5b95136e41..8a6069dde32309a214229968294a14911c701dd0 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4.hxx @@ -74,7 +74,7 @@ ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputat this->m_NumberOfSkippedFixedSampledPoints = 0; this->m_Value = NumericTraits<MeasureType>::max(); - this->m_DerivativeResult = NULL; + this->m_DerivativeResult = ITK_NULLPTR; this->m_ComputeDerivative = false; } @@ -161,13 +161,13 @@ ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputat if( ! this->m_UseFixedImageGradientFilter ) { itkDebugMacro("Initialize FixedImageGradientCalculator"); - this->m_FixedImageGradientImage = NULL; + this->m_FixedImageGradientImage = ITK_NULLPTR; this->m_FixedImageGradientCalculator->SetInputImage(this->m_FixedImage); } if( ! this->m_UseMovingImageGradientFilter ) { itkDebugMacro("Initialize MovingImageGradientCalculator"); - this->m_MovingImageGradientImage = NULL; + this->m_MovingImageGradientImage = ITK_NULLPTR; this->m_MovingImageGradientCalculator->SetInputImage(this->m_MovingImage); } @@ -599,54 +599,13 @@ ImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualImage, TInternalComputat << indent << "UseFloatingPointCorrection: " << this->GetUseFloatingPointCorrection() << std::endl << indent << "FloatingPointCorrectionResolution: " << this->GetFloatingPointCorrectionResolution() << std::endl; - if( this->GetFixedImage() != NULL ) - { - os << indent << "FixedImage: " << this->GetFixedImage() << std::endl; - } - else - { - os << indent << "FixedImage is NULL." << std::endl; - } - if( this->GetMovingImage() != NULL ) - { - os << indent << "MovingImage: " << this->GetMovingImage() << std::endl; - } - else - { - os << indent << "MovingImage is NULL." << std::endl; - } - if( this->GetFixedTransform() != NULL ) - { - os << indent << "FixedTransform: " << this->GetFixedTransform() << std::endl; - } - else - { - os << indent << "FixedTransform is NULL." << std::endl; - } - if( this->GetMovingTransform() != NULL ) - { - os << indent << "MovingTransform: " << this->GetMovingTransform() << std::endl; - } - else - { - os << indent << "MovingTransform is NULL." << std::endl; - } - if( this->GetFixedImageMask() != NULL ) - { - os << indent << "FixedImageMask: " << this->GetFixedImageMask() << std::endl; - } - else - { - os << indent << "FixedImageMask is NULL." << std::endl; - } - if( this->GetMovingImageMask() != NULL ) - { - os << indent << "MovingImageMask: " << this->GetMovingImageMask() << std::endl; - } - else - { - os << indent << "MovingImageMask is NULL." << std::endl; - } + itkPrintSelfObjectMacro( FixedImage ); + itkPrintSelfObjectMacro( MovingImage ); + itkPrintSelfObjectMacro( FixedTransform ); + itkPrintSelfObjectMacro( MovingTransform ); + itkPrintSelfObjectMacro( FixedImageMask ); + itkPrintSelfObjectMacro( MovingImageMask ); + } }//namespace itk diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreader.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreader.hxx index bc6ad9d8b95a2891c0fee2c88450fc35a6220dab..3534e9fc183afa07ebe3618ea0b43e7e3b62421b 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreader.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreader.hxx @@ -30,14 +30,12 @@ ImageToImageMetricv4GetValueAndDerivativeThreader< ThreadedImageRegionPartitione ::ThreadedExecution ( const DomainType & imageSubRegion, const ThreadIdType threadId ) { - VirtualPointType virtualPoint; - VirtualIndexType virtualIndex; typename VirtualImageType::ConstPointer virtualImage = this->m_Associate->GetVirtualImage(); typedef ImageRegionConstIteratorWithIndex< VirtualImageType > IteratorType; - IteratorType it( virtualImage, imageSubRegion ); - for( it.GoToBegin(); !it.IsAtEnd(); ++it ) + VirtualPointType virtualPoint; + for( IteratorType it( virtualImage, imageSubRegion ); !it.IsAtEnd(); ++it ) { - virtualIndex = it.GetIndex(); + const VirtualIndexType & virtualIndex = it.GetIndex(); virtualImage->TransformIndexToPhysicalPoint( virtualIndex, virtualPoint ); this->ProcessVirtualPoint( virtualIndex, virtualPoint, threadId ); } @@ -49,16 +47,15 @@ ImageToImageMetricv4GetValueAndDerivativeThreader< ThreadedIndexedContainerParti ::ThreadedExecution ( const DomainType & indexSubRange, const ThreadIdType threadId ) { - VirtualPointType virtualPoint; - VirtualIndexType virtualIndex; - typename VirtualImageType::ConstPointer virtualImage = this->m_Associate->GetVirtualImage(); typename TImageToImageMetricv4::VirtualPointSetType::ConstPointer virtualSampledPointSet = this->m_Associate->GetVirtualSampledPointSet(); typedef typename TImageToImageMetricv4::VirtualPointSetType::MeshTraits::PointIdentifier ElementIdentifierType; const ElementIdentifierType begin = indexSubRange[0]; const ElementIdentifierType end = indexSubRange[1]; + VirtualIndexType virtualIndex; + typename VirtualImageType::ConstPointer virtualImage = this->m_Associate->GetVirtualImage(); for( ElementIdentifierType i = begin; i <= end; ++i ) { - virtualPoint = virtualSampledPointSet->GetPoint( i ); + const VirtualPointType & virtualPoint = virtualSampledPointSet->GetPoint( i ); virtualImage->TransformPhysicalPointToIndex( virtualPoint, virtualIndex ); this->ProcessVirtualPoint( virtualIndex, virtualPoint, threadId ); } diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.h index fbea2e673c5eb51defff954abb055cb2a6448cab..f5ce9093b0cc44a6d0e6a033162b7747337c1abb 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.h @@ -138,7 +138,7 @@ protected: * Results must be returned by derived classes in: * \param metricValueReturn * \param localDerivativeReturn - * \param threadID may be used as needed, for example to access any per-thread + * \param threadId may be used as needed, for example to access any per-thread * data cached during pre-processing by the derived class. * \warning This is called from the threader, and thus must be thread-safe. */ @@ -153,14 +153,14 @@ protected: const MovingImageGradientType & mappedMovingImageGradient, MeasureType & metricValueReturn, DerivativeType & localDerivativeReturn, - const ThreadIdType threadID ) const = 0; + const ThreadIdType threadId ) const = 0; /** Store derivative result from a single point calculation. * \warning If this method is overridden or otherwise not used * in a derived class, be sure to *accumulate* results. */ virtual void StorePointDerivativeResult( const VirtualIndexType & virtualIndex, - const ThreadIdType threadID ); + const ThreadIdType threadId ); struct GetValueAndDerivativePerThreadStruct { @@ -177,6 +177,7 @@ protected: /** Pre-allocated transform jacobian objects, for use as needed by dervied * classes for efficiency. */ JacobianType MovingTransformJacobian; + JacobianType MovingTransformJacobianPositional; }; itkPadStruct( ITK_CACHE_LINE_ALIGNMENT, GetValueAndDerivativePerThreadStruct, PaddedGetValueAndDerivativePerThreadStruct); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.hxx index beb4ea63a56860ce3f6ce57a6c642a01240f0e6b..eb15587a38200300baa862ed99be989adaeffd74 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkImageToImageMetricv4GetValueAndDerivativeThreaderBase.hxx @@ -27,7 +27,9 @@ namespace itk template< typename TDomainPartitioner, typename TImageToImageMetricv4 > ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 > ::ImageToImageMetricv4GetValueAndDerivativeThreaderBase(): - m_GetValueAndDerivativePerThreadVariables( NULL ) + m_GetValueAndDerivativePerThreadVariables( ITK_NULLPTR ), + m_CachedNumberOfParameters( 0 ), + m_CachedNumberOfLocalParameters( 0 ) { } @@ -45,19 +47,27 @@ ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImag { //--------------------------------------------------------------- // Resize the per thread memory objects. + //----------------------------------------------------------------- + // Cache some values + this->m_CachedNumberOfParameters = this->m_Associate->GetNumberOfParameters(); + this->m_CachedNumberOfLocalParameters = this->m_Associate->GetNumberOfLocalParameters(); /* Per-thread results */ + const ThreadIdType numThreadsUsed = this->GetNumberOfThreadsUsed(); delete[] m_GetValueAndDerivativePerThreadVariables; - this->m_GetValueAndDerivativePerThreadVariables = new AlignedGetValueAndDerivativePerThreadStruct[ this->GetNumberOfThreadsUsed() ]; + this->m_GetValueAndDerivativePerThreadVariables = new AlignedGetValueAndDerivativePerThreadStruct[ numThreadsUsed ]; if( this->m_Associate->GetComputeDerivative() ) { - for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); ++i) + for (ThreadIdType i = 0; i < numThreadsUsed; ++i) { /* Allocate intermediary per-thread storage used to get results from * derived classes */ - this->m_GetValueAndDerivativePerThreadVariables[i].LocalDerivatives.SetSize( this->m_Associate->GetNumberOfLocalParameters() ); - this->m_GetValueAndDerivativePerThreadVariables[i].MovingTransformJacobian.SetSize( this->m_Associate->VirtualImageDimension, this->m_Associate->GetNumberOfLocalParameters() ); + this->m_GetValueAndDerivativePerThreadVariables[i].LocalDerivatives.SetSize( this->m_CachedNumberOfLocalParameters ); + this->m_GetValueAndDerivativePerThreadVariables[i].MovingTransformJacobian.SetSize( + this->m_Associate->VirtualImageDimension, this->m_CachedNumberOfLocalParameters ); + this->m_GetValueAndDerivativePerThreadVariables[i].MovingTransformJacobianPositional.SetSize( + this->m_Associate->VirtualImageDimension, this->m_Associate->VirtualImageDimension ); if ( this->m_Associate->m_MovingTransform->GetTransformCategory() == MovingTransformType::DisplacementField ) { /* For transforms with local support, e.g. displacement field, @@ -73,7 +83,7 @@ ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImag { itkDebugMacro("ImageToImageMetricv4::Initialize: transform does NOT have local support\n"); /* This size always comes from the moving image */ - const NumberOfParametersType globalDerivativeSize = this->m_Associate->GetNumberOfParameters(); + const NumberOfParametersType globalDerivativeSize = this->m_CachedNumberOfParameters; /* Global transforms get a separate derivatives container for each thread * that holds the result over a particular image region. * Use a CompensatedSummation value to provide for better consistency between @@ -85,7 +95,7 @@ ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImag //--------------------------------------------------------------- // Set initial values. - for (ThreadIdType thread = 0; thread<this->GetNumberOfThreadsUsed(); thread++) + for (ThreadIdType thread = 0; thread < numThreadsUsed; ++thread) { this->m_GetValueAndDerivativePerThreadVariables[thread].NumberOfValidPoints = NumericTraits< SizeValueType >::Zero; this->m_GetValueAndDerivativePerThreadVariables[thread].Measure = NumericTraits< InternalComputationValueType >::Zero; @@ -96,18 +106,13 @@ ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImag /* Be sure to init to 0 here, because the threader may not use * all the threads if the region is better split into fewer * subregions. */ - for( NumberOfParametersType p = 0; p < this->m_Associate->GetNumberOfParameters(); p++ ) + for( NumberOfParametersType p = 0; p < this->m_CachedNumberOfParameters; p++ ) { this->m_GetValueAndDerivativePerThreadVariables[thread].CompensatedDerivatives[p].ResetToZero(); } } } } - - //----------------------------------------------------------------- - // Cache some values - this->m_CachedNumberOfParameters = this->m_Associate->GetNumberOfParameters(); - this->m_CachedNumberOfLocalParameters = this->m_Associate->GetNumberOfLocalParameters(); } template< typename TDomainPartitioner, typename TImageToImageMetricv4 > @@ -115,10 +120,11 @@ void ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImageToImageMetricv4 > ::AfterThreadedExecution() { + const ThreadIdType numThreadsUsed = this->GetNumberOfThreadsUsed(); /* Store the number of valid points the enclosing class \c * m_NumberOfValidPoints by collecting the valid points per thread. */ this->m_Associate->m_NumberOfValidPoints = NumericTraits< SizeValueType >::Zero; - for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++) + for (ThreadIdType i = 0; i < numThreadsUsed; ++i) { this->m_Associate->m_NumberOfValidPoints += this->m_GetValueAndDerivativePerThreadVariables[i].NumberOfValidPoints; } @@ -134,7 +140,7 @@ ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImag /* Use a compensated sum to be ready for when there is a very large number of threads */ CompensatedDerivativeValueType sum; sum.ResetToZero(); - for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++) + for (ThreadIdType i=0; i<numThreadsUsed; i++) { sum += this->m_GetValueAndDerivativePerThreadVariables[i].CompensatedDerivatives[p].GetSum(); } @@ -150,7 +156,7 @@ ImageToImageMetricv4GetValueAndDerivativeThreaderBase< TDomainPartitioner, TImag { this->m_Associate->m_Value = NumericTraits<MeasureType>::Zero; /* Accumulate the metric value from threads and store the average. */ - for(ThreadIdType threadId = 0; threadId < this->GetNumberOfThreadsUsed(); ++threadId ) + for(ThreadIdType threadId = 0; threadId < numThreadsUsed; ++threadId ) { this->m_Associate->m_Value += this->m_GetValueAndDerivativePerThreadVariables[threadId].Measure; } diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJensenHavrdaCharvatTsallisPointSetToPointSetMetricv4.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJensenHavrdaCharvatTsallisPointSetToPointSetMetricv4.h index ce96296b6abfebe493762ef6cc757b2cb459298f..f480723f6d443a65e0d0d2a0757eda3884360ff8 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJensenHavrdaCharvatTsallisPointSetToPointSetMetricv4.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJensenHavrdaCharvatTsallisPointSetToPointSetMetricv4.h @@ -67,14 +67,15 @@ namespace itk { * \ingroup ITKMetricsv4 */ -template<typename TPointSet> +template<typename TPointSet, class TInternalComputationValueType = double> class JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4 : - public PointSetToPointSetMetricv4<TPointSet, TPointSet> + public PointSetToPointSetMetricv4<TPointSet, TPointSet, TInternalComputationValueType> { public: /** Standard class typedefs. */ typedef JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4 Self; - typedef PointSetToPointSetMetricv4<TPointSet, TPointSet> Superclass; + typedef PointSetToPointSetMetricv4<TPointSet, TPointSet, + TInternalComputationValueType> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; @@ -202,21 +203,22 @@ public: /** Get the noise kernel sigma for the anistropic covariances. */ itkGetConstMacro( KernelSigma, RealType ); - virtual MeasureType GetLocalNeighborhoodValue( const PointType & point, const PixelType & pixel = 0 ) const; + virtual MeasureType GetLocalNeighborhoodValue( const PointType & point, + const PixelType & pixel = 0 ) const; - virtual void GetLocalNeighborhoodValueAndDerivative( const PointType &, MeasureType &, LocalDerivativeType &, const PixelType & pixel = 0 ) const; + virtual void GetLocalNeighborhoodValueAndDerivative( const PointType &, MeasureType &, + LocalDerivativeType &, const PixelType & pixel = 0 ) const; /** Clone method will clone the existing instance of this type, * including its internal member variables. */ - virtual ::itk::LightObject::Pointer Clone( void ) const; + virtual typename LightObject::Pointer InternalClone() const; protected: JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4(); ~JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4(); - virtual void InitializeForIteration( void ) const; - - void ComputeValueAndDerivative( const PointType & samplePoint, MeasureType &value, LocalDerivativeType &derivativeReturn, bool calcValue, bool calcDerivative ) const; + void ComputeValueAndDerivative( const PointType & samplePoint, MeasureType & value, + LocalDerivativeType &derivativeReturn, bool calcValue, bool calcDerivative ) const; void PrintSelf( std::ostream& os, Indent indent ) const; diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJensenHavrdaCharvatTsallisPointSetToPointSetMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJensenHavrdaCharvatTsallisPointSetToPointSetMetricv4.hxx index ce113459204030fc8f5b1b27107c0dd1b8a836e8..c45f1035f384717782016dc64c0aaaa1a3824851 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJensenHavrdaCharvatTsallisPointSetToPointSetMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJensenHavrdaCharvatTsallisPointSetToPointSetMetricv4.hxx @@ -23,29 +23,32 @@ namespace itk { /** Constructor */ -template<typename TPointSet> -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> +template<typename TPointSet, class TInternalComputationValueType> +JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> ::JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4() : m_UseAnisotropicCovariances( false ), m_PointSetSigma( static_cast<RealType>( 1.0 ) ), m_KernelSigma( static_cast<RealType>( 10.0 ) ), m_CovarianceKNeighborhood( static_cast<unsigned int>( 5 ) ), m_EvaluationKNeighborhood( static_cast<unsigned int>( 50 ) ), - m_Alpha( static_cast<RealType>(1.0) ) + m_Alpha( static_cast<RealType>(1.0) ), + m_TotalNumberOfPoints(0), + m_Prefactor0(0.0), + m_Prefactor1(0.0) { } /** Destructor */ -template<typename TPointSet> -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> +template<typename TPointSet, class TInternalComputationValueType> +JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> ::~JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4() { } /** Initialize the metric */ -template<typename TPointSet> +template<typename TPointSet, class TInternalComputationValueType> void -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> +JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> ::Initialize( void ) throw ( ExceptionObject ) { Superclass::Initialize(); @@ -55,41 +58,20 @@ JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> this->m_FixedDensityFunction->SetKernelSigma( this->m_KernelSigma ); this->m_FixedDensityFunction->SetRegularizationSigma( this->m_PointSetSigma ); this->m_FixedDensityFunction->SetNormalize( true ); - this->m_FixedDensityFunction->SetUseAnisotropicCovariances( this->m_UseAnisotropicCovariances ); - this->m_FixedDensityFunction->SetCovarianceKNeighborhood( this->m_CovarianceKNeighborhood ); - this->m_FixedDensityFunction->SetEvaluationKNeighborhood( this->m_EvaluationKNeighborhood ); - this->m_FixedDensityFunction->SetInputPointSet( this->m_FixedTransformedPointSet ); // Initialize the moving density function this->m_MovingDensityFunction = DensityFunctionType::New(); this->m_MovingDensityFunction->SetKernelSigma( this->m_KernelSigma ); this->m_MovingDensityFunction->SetRegularizationSigma( this->m_PointSetSigma ); - this->m_MovingDensityFunction->SetNormalize( true ); - this->m_MovingDensityFunction->SetUseAnisotropicCovariances( this->m_UseAnisotropicCovariances ); - this->m_MovingDensityFunction->SetCovarianceKNeighborhood( this->m_CovarianceKNeighborhood ); - this->m_MovingDensityFunction->SetEvaluationKNeighborhood( this->m_EvaluationKNeighborhood ); - this->m_MovingDensityFunction->SetInputPointSet( this->m_MovingTransformedPointSet ); -} - -template<typename TPointSet> -void -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> -::InitializeForIteration() const -{ - Superclass::InitializeForIteration(); - if( this->m_NumberOfValidPoints == 0 ) - { - itkExceptionMacro("There are no fixed points within the virtual domain."); - } // Pre-calc some values for efficiency this->m_TotalNumberOfPoints = static_cast<RealType>( this->m_NumberOfValidPoints + this->m_MovingDensityFunction->GetInputPointSet()->GetNumberOfPoints() ); @@ -101,10 +83,10 @@ JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> this->m_Prefactor1 = 1.0 / ( this->m_TotalNumberOfPoints * this->m_TotalNumberOfPoints ); } -template<typename TPointSet> -typename JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> +template<typename TPointSet, class TInternalComputationValueType> +typename JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> ::MeasureType -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> +JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodValue( const PointType & point, const PixelType & itkNotUsed( pixel ) ) const { MeasureType value; @@ -114,19 +96,21 @@ JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> } /** Get both the match Measure and the Derivative Measure */ -template<typename TPointSet> +template<typename TPointSet, class TInternalComputationValueType> void -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> +JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodValueAndDerivative( const PointType & point, MeasureType & value, LocalDerivativeType & derivative, const PixelType & itkNotUsed( pixel ) ) const { this->ComputeValueAndDerivative( point, value, derivative, true, true ); } -template<typename TPointSet> +template<typename TPointSet, class TInternalComputationValueType> void -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> +JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> ::ComputeValueAndDerivative( const PointType & samplePoint, MeasureType & value, LocalDerivativeType & derivativeReturn, bool calcValue, bool calcDerivative ) const { + + if( calcDerivative ) { derivativeReturn.Fill( NumericTraits<DerivativeValueType>::Zero ); @@ -151,18 +135,18 @@ JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> RealType realOne = NumericTraits<RealType>::One; if( this->m_Alpha == realOne ) { - value = ( vcl_log( probabilityStar ) ); + value = ( std::log( probabilityStar ) ); } else { - value = -realOne * ( vcl_pow( probabilityStar, static_cast<RealType>( this->m_Alpha - realOne ) ) ); + value = -realOne * ( std::pow( probabilityStar, static_cast<RealType>( this->m_Alpha - realOne ) ) ); } value *= this->m_Prefactor0; } if( calcDerivative ) { - RealType probabilityStarFactor = vcl_pow( probabilityStar, static_cast<RealType>( 2.0 - this->m_Alpha ) ); + RealType probabilityStarFactor = std::pow( probabilityStar, static_cast<RealType>( 2.0 - this->m_Alpha ) ); typename DensityFunctionType::NeighborsIdentifierType neighbors; this->m_MovingDensityFunction->GetPointsLocator()->FindClosestNPoints( samplePoint, this->m_EvaluationKNeighborhood, neighbors ); @@ -197,37 +181,33 @@ JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> DerivativeValueType factor = this->m_Prefactor1 * gaussian / probabilityStarFactor; for( unsigned int i = 0; i < PointDimension; i++ ) { - derivativeReturn[i] -= diffMean[i] * factor; + derivativeReturn[i] += diffMean[i] * factor; } } } } -template<typename TPointSet> -::itk::LightObject::Pointer -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> -::Clone() const +template<typename TPointSet, class TInternalComputationValueType> +typename LightObject::Pointer +JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> +::InternalClone( void ) const { - ::itk::LightObject::Pointer smartPtr; - Pointer copyPtr = Self::New(); - - copyPtr->m_MovingPointSet = this->m_MovingPointSet; - copyPtr->m_FixedPointSet = this->m_FixedPointSet; - copyPtr->m_Alpha = this->m_Alpha; - copyPtr->m_PointSetSigma = this->m_PointSetSigma; - copyPtr->m_KernelSigma = this->m_KernelSigma; - copyPtr->m_CovarianceKNeighborhood = this->m_CovarianceKNeighborhood; - copyPtr->m_EvaluationKNeighborhood = this->m_EvaluationKNeighborhood; - copyPtr->m_UseAnisotropicCovariances = this->m_UseAnisotropicCovariances; - - smartPtr = static_cast<Pointer>( copyPtr ); - - return smartPtr; + typename Self::Pointer rval = Self::New(); + rval->SetMovingPointSet( this->m_MovingPointSet ); + rval->SetFixedPointSet( this->m_FixedPointSet ); + rval->SetPointSetSigma( this->m_PointSetSigma ); + rval->SetEvaluationKNeighborhood( this->m_EvaluationKNeighborhood ); + rval->SetAlpha( this->m_Alpha ); + rval->SetKernelSigma( this->m_KernelSigma ); + rval->SetCovarianceKNeighborhood( this->m_CovarianceKNeighborhood ); + rval->SetUseAnisotropicCovariances( this->m_UseAnisotropicCovariances ); + + return rval.GetPointer(); } -template<typename TPointSet> +template<typename TPointSet, class TInternalComputationValueType> void -JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet> +JensenHavrdaCharvatTsallisPointSetToPointSetMetricv4<TPointSet, TInternalComputationValueType> ::PrintSelf( std::ostream& os, Indent indent ) const { Superclass::PrintSelf( os, indent ); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationComputeJointPDFThreaderBase.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationComputeJointPDFThreaderBase.hxx index 10c25e9540242388a066648fe71d709ef5ed6674..9d4543c9543f1e4b440703f7153fd858a2eac54f 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationComputeJointPDFThreaderBase.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationComputeJointPDFThreaderBase.hxx @@ -28,7 +28,7 @@ namespace itk template< typename TDomainPartitioner, typename TJointHistogramMetric > JointHistogramMutualInformationComputeJointPDFThreaderBase< TDomainPartitioner, TJointHistogramMetric > ::JointHistogramMutualInformationComputeJointPDFThreaderBase(): - m_JointHistogramMIPerThreadVariables( NULL ) + m_JointHistogramMIPerThreadVariables( ITK_NULLPTR ) { } @@ -44,9 +44,10 @@ void JointHistogramMutualInformationComputeJointPDFThreaderBase< TDomainPartitioner, TJointHistogramMetric > ::BeforeThreadedExecution() { + const ThreadIdType numThreadsUsed = this->GetNumberOfThreadsUsed(); delete[] this->m_JointHistogramMIPerThreadVariables; - this->m_JointHistogramMIPerThreadVariables = new AlignedJointHistogramMIPerThreadStruct[ this->GetNumberOfThreadsUsed() ]; - for( ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); ++i ) + this->m_JointHistogramMIPerThreadVariables = new AlignedJointHistogramMIPerThreadStruct[ numThreadsUsed ]; + for( ThreadIdType i = 0; i < numThreadsUsed; ++i ) { if( this->m_JointHistogramMIPerThreadVariables[i].JointHistogram.IsNull() ) { diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationGetValueAndDerivativeThreader.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationGetValueAndDerivativeThreader.h index 03714c84308745cd0a8af95ee9da6e94cc97d05c..ece59addc210926d9d473739656004a7159e26e4 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationGetValueAndDerivativeThreader.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationGetValueAndDerivativeThreader.h @@ -60,6 +60,7 @@ public: typedef typename Superclass::MeasureType MeasureType; typedef typename Superclass::DerivativeType DerivativeType; typedef typename Superclass::DerivativeValueType DerivativeValueType; + typedef typename Superclass::JacobianType JacobianType; typedef TJointHistogramMetric JointHistogramMetricType; typedef typename JointHistogramMetricType::InternalComputationValueType InternalComputationValueType; @@ -67,7 +68,6 @@ public: typedef typename JointHistogramMetricType::MarginalPDFInterpolatorType MarginalPDFInterpolatorType; typedef typename JointHistogramMetricType::JointPDFInterpolatorPointer JointPDFInterpolatorPointer; typedef typename JointHistogramMetricType::MarginalPDFInterpolatorPointer MarginalPDFInterpolatorPointer; - typedef typename JointHistogramMetricType::FixedTransformJacobianType FixedTransformJacobianType; typedef typename JointHistogramMetricType::NumberOfParametersType NumberOfParametersType; typedef typename JointHistogramMetricType::JointPDFType JointPDFType; typedef typename JointHistogramMetricType::MarginalPDFType MarginalPDFType; @@ -96,19 +96,19 @@ protected: const MovingImageGradientType & mappedMovingImageGradient, MeasureType & metricValueReturn, DerivativeType & localDerivativeReturn, - const ThreadIdType threadID ) const; + const ThreadIdType threadId ) const; inline InternalComputationValueType ComputeFixedImageMarginalPDFDerivative( const MarginalPDFPointType & margPDFpoint, - const ThreadIdType threadID ) const; + const ThreadIdType threadId ) const; inline InternalComputationValueType ComputeMovingImageMarginalPDFDerivative( const MarginalPDFPointType & margPDFpoint, - const ThreadIdType threadID ) const; + const ThreadIdType threadId ) const; inline InternalComputationValueType ComputeJointPDFDerivative( const JointPDFPointType & jointPDFpoint, - const ThreadIdType threadID, + const ThreadIdType threadId, const SizeValueType ind ) const; struct JointHistogramMIPerThreadStruct { diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationGetValueAndDerivativeThreader.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationGetValueAndDerivativeThreader.hxx index d6b73ae8002d7635b78bfe2a0763a64df029685d..b9e88e1c4dfbbf59d54c76e80baa008c676ffbe1 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationGetValueAndDerivativeThreader.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationGetValueAndDerivativeThreader.hxx @@ -25,10 +25,10 @@ namespace itk template< typename TDomainPartitioner, typename TImageToImageMetric, typename TJointHistogramMetric > JointHistogramMutualInformationGetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TJointHistogramMetric > -::JointHistogramMutualInformationGetValueAndDerivativeThreader(): - m_JointHistogramMIPerThreadVariables( NULL ) -{ -} +::JointHistogramMutualInformationGetValueAndDerivativeThreader() : + m_JointHistogramMIPerThreadVariables( ITK_NULLPTR ), + m_JointAssociate( ITK_NULLPTR ) +{} template< typename TDomainPartitioner, typename TImageToImageMetric, typename TJointHistogramMetric > @@ -48,15 +48,16 @@ JointHistogramMutualInformationGetValueAndDerivativeThreader< TDomainPartitioner /* Store the casted pointer to avoid dynamic casting in tight loops. */ this->m_JointAssociate = dynamic_cast< TJointHistogramMetric * >( this->m_Associate ); - if( this->m_JointAssociate == NULL ) + if( this->m_JointAssociate == ITK_NULLPTR ) { itkExceptionMacro("Dynamic casting of associate pointer failed."); } + const ThreadIdType numThreadsUsed = this->GetNumberOfThreadsUsed(); delete[] this->m_JointHistogramMIPerThreadVariables; - this->m_JointHistogramMIPerThreadVariables = new AlignedJointHistogramMIPerThreadStruct[ this->GetNumberOfThreadsUsed() ]; + this->m_JointHistogramMIPerThreadVariables = new AlignedJointHistogramMIPerThreadStruct[ numThreadsUsed ]; - for( ThreadIdType i = 0; i < this->GetNumberOfThreadsUsed(); ++i ) + for( ThreadIdType i = 0; i < numThreadsUsed; ++i ) { if( this->m_JointHistogramMIPerThreadVariables[i].JointPDFInterpolator.IsNull() ) { @@ -141,7 +142,7 @@ JointHistogramMutualInformationGetValueAndDerivativeThreader< TDomainPartitioner if( jointPDFValue > eps && movingImagePDFValue > eps ) { const InternalComputationValueType pRatio = - vcl_log(jointPDFValue)-vcl_log(movingImagePDFValue); + std::log(jointPDFValue)-std::log(movingImagePDFValue); const InternalComputationValueType & term1 = dJPDF*pRatio; const InternalComputationValueType & term2 = this->m_JointAssociate->m_Log2 * dMmPDF * jointPDFValue / movingImagePDFValue; scalingfactor = ( term2 - term1 ); @@ -152,11 +153,15 @@ JointHistogramMutualInformationGetValueAndDerivativeThreader< TDomainPartitioner } /* Use a pre-allocated jacobian object for efficiency */ - FixedTransformJacobianType & jacobian = - const_cast< FixedTransformJacobianType & >(this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobian); + typedef JacobianType & JacobianReferenceType; + JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobian; + JacobianReferenceType jacobianPositional = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobianPositional; /** For dense transforms, this returns identity */ - this->m_JointAssociate->m_MovingTransform->ComputeJacobianWithRespectToParameters( virtualPoint, jacobian ); + this->m_JointAssociate->GetMovingTransform()-> + ComputeJacobianWithRespectToParametersCachedTemporaries(virtualPoint, + jacobian, + jacobianPositional); for ( NumberOfParametersType par = 0; par < this->GetCachedNumberOfLocalParameters(); par++ ) { @@ -174,7 +179,7 @@ template< typename TDomainPartitioner, typename TImageToImageMetric, typename TJ typename JointHistogramMutualInformationGetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TJointHistogramMetric >::InternalComputationValueType JointHistogramMutualInformationGetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TJointHistogramMetric > ::ComputeFixedImageMarginalPDFDerivative( const MarginalPDFPointType & margPDFpoint, - const ThreadIdType threadID ) const + const ThreadIdType threadId ) const { InternalComputationValueType offset = 0.5*this->m_JointPDFSpacing[0]; InternalComputationValueType eps = this->m_JointPDFSpacing[0]; @@ -201,8 +206,8 @@ JointHistogramMutualInformationGetValueAndDerivativeThreader< TDomainPartitioner InternalComputationValueType delta = rightpoint[0]-leftpoint[0]; if ( delta > NumericTraits< InternalComputationValueType >::Zero ) { - InternalComputationValueType deriv = this->m_ThreaderFixedImageMarginalPDFInterpolator[threadID]->Evaluate(rightpoint) - - this->m_ThreaderFixedImageMarginalPDFInterpolator[threadID]->Evaluate(leftpoint); + InternalComputationValueType deriv = this->m_ThreaderFixedImageMarginalPDFInterpolator[threadId]->Evaluate(rightpoint) - + this->m_ThreaderFixedImageMarginalPDFInterpolator[threadId]->Evaluate(leftpoint); return deriv/delta; } else diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationImageToImageMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationImageToImageMetricv4.hxx index 33bd82da29dad1ed184c4e8abaf0d13e9099de02..29ed2f7877cf129a39e32456a23f2682168c5889 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationImageToImageMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkJointHistogramMutualInformationImageToImageMetricv4.hxx @@ -29,7 +29,8 @@ namespace itk template <typename TFixedImage, typename TMovingImage, typename TVirtualImage, typename TInternalComputationValueType, typename TMetricTraits> JointHistogramMutualInformationImageToImageMetricv4<TFixedImage,TMovingImage,TVirtualImage,TInternalComputationValueType, TMetricTraits> -::JointHistogramMutualInformationImageToImageMetricv4() +::JointHistogramMutualInformationImageToImageMetricv4(): + m_JointHistogramTotalCount(0) { // Initialize histogram properties this->m_NumberOfHistogramBins = 20; @@ -41,7 +42,7 @@ JointHistogramMutualInformationImageToImageMetricv4<TFixedImage,TMovingImage,TVi this->m_MovingImageBinSize = NumericTraits< TInternalComputationValueType >::Zero; this->m_Padding = 2; this->m_JointPDFSum = NumericTraits< TInternalComputationValueType >::Zero; - this->m_Log2 = vcl_log(2.0); + this->m_Log2 = std::log(2.0); this->m_VarianceForJointPDFSmoothing = 1.5; // We have our own GetValueAndDerivativeThreader's that we want @@ -70,13 +71,13 @@ JointHistogramMutualInformationImageToImageMetricv4<TFixedImage,TMovingImage,TVi /** Get the fixed and moving image true max's and mins. * Initialize them to the PixelType min and max. */ this->m_FixedImageTrueMin = - vcl_numeric_limits<typename TFixedImage::PixelType>::max(); + std::numeric_limits<typename TFixedImage::PixelType>::max(); this->m_FixedImageTrueMax = - vcl_numeric_limits<typename TFixedImage::PixelType>::min(); + std::numeric_limits<typename TFixedImage::PixelType>::min(); this->m_MovingImageTrueMin = - vcl_numeric_limits<typename TMovingImage::PixelType>::max(); + std::numeric_limits<typename TMovingImage::PixelType>::max(); this->m_MovingImageTrueMax = - vcl_numeric_limits<typename TMovingImage::PixelType>::min(); + std::numeric_limits<typename TMovingImage::PixelType>::min(); /** Iterate through the fixed image and set the true * max and min for the fixed image. */ @@ -350,7 +351,7 @@ JointHistogramMutualInformationImageToImageMetricv4<TFixedImage,TMovingImage,TVi if (pxy / denom > eps ) { //the classic mi calculation - local_mi = pxy * vcl_log( pxy / denom ); + local_mi = pxy * std::log( pxy / denom ); } } total_mi += local_mi; diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkLabeledPointSetToPointSetMetricv4.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkLabeledPointSetToPointSetMetricv4.h index 2eb3fd7ad41214ebb0682bf9eae487c318a8b5ba..1c3b040eec347c6da943b972bbc1ec34a718fb94 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkLabeledPointSetToPointSetMetricv4.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkLabeledPointSetToPointSetMetricv4.h @@ -49,15 +49,17 @@ namespace itk * * \ingroup ITKMetricsv4 */ -template<typename TFixedPointSet, typename TMovingPointSet = TFixedPointSet> +template<typename TFixedPointSet, typename TMovingPointSet = TFixedPointSet, + class TInternalComputationValueType = double> class LabeledPointSetToPointSetMetricv4: - public PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> + public PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> { public: /** Standard class typedefs. */ typedef LabeledPointSetToPointSetMetricv4 Self; - typedef PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> Superclass; + typedef PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, + TInternalComputationValueType> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkLabeledPointSetToPointSetMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkLabeledPointSetToPointSetMetricv4.hxx index 7d2dc0e1de41705665f472760e608ba0cd40f2c4..15164150d93a0d17a16daf9c6a4c56e25c1f5689 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkLabeledPointSetToPointSetMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkLabeledPointSetToPointSetMetricv4.hxx @@ -28,8 +28,8 @@ namespace itk { /** Constructor */ -template<typename TFixedPointSet, typename TMovingPointSet> -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::LabeledPointSetToPointSetMetricv4() { typedef EuclideanDistancePointSetToPointSetMetricv4<FixedPointSetType, MovingPointSetType> DefaultMetricType; @@ -40,15 +40,15 @@ LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } /** Destructor */ -template<typename TFixedPointSet, typename TMovingPointSet> -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::~LabeledPointSetToPointSetMetricv4() { } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::Initialize( void ) throw ( ExceptionObject ) { Superclass::Initialize(); @@ -67,6 +67,10 @@ LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> for( it = this->m_CommonPointSetLabels.begin(); it != this->m_CommonPointSetLabels.end(); ++it ) { typename PointSetMetricType::Pointer metricPtr = dynamic_cast<PointSetMetricType *>( this->m_PointSetMetric->Clone().GetPointer() ); + if( metricPtr.IsNull() ) + { + itkExceptionMacro( "The metric pointer clone is NULL." ); + } FixedPointSetPointer fixedPointSet = this->GetLabeledFixedPointSet( *it ); MovingPointSetPointer movingPointSet = this->GetLabeledMovingPointSet( *it ); @@ -79,10 +83,10 @@ LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } } -template<typename TFixedPointSet, typename TMovingPointSet> -typename LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +typename LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::MeasureType -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodValue( const PointType & point, const LabelType & label ) const { typename LabelSetType::const_iterator labelIt = std::find( this->m_CommonPointSetLabels.begin(), this->m_CommonPointSetLabels.end(), label ); @@ -98,9 +102,9 @@ LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodValueAndDerivative( const PointType & point, MeasureType &measure, LocalDerivativeType & localDerivative, const LabelType & label ) const { @@ -116,9 +120,9 @@ LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } } -template<typename TFixedPointSet, typename TMovingPointSet> -typename LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet>::FixedPointSetPointer -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +typename LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType>::FixedPointSetPointer +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLabeledFixedPointSet( const LabelType label ) const { typename FixedPointSetType::Pointer fixedPointSet = FixedPointSetType::New(); @@ -141,9 +145,9 @@ LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> return fixedPointSet; } -template<typename TFixedPointSet, typename TMovingPointSet> -typename LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet>::MovingPointSetPointer -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +typename LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType>::MovingPointSetPointer +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLabeledMovingPointSet( const LabelType label ) const { typename MovingPointSetType::Pointer movingPointSet = MovingPointSetType::New(); @@ -166,9 +170,9 @@ LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> return movingPointSet; } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::DetermineCommonPointSetLabels() { this->m_FixedPointSetLabels.clear(); @@ -225,9 +229,9 @@ LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } /** PrintSelf method */ -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +LabeledPointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::PrintSelf( std::ostream & os, Indent indent ) const { Superclass::PrintSelf( os, indent ); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkManifoldParzenWindowsPointSetFunction.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkManifoldParzenWindowsPointSetFunction.hxx index 1de3776417d51ed9d39c6be84d41d5e714bf4a1c..6f5c6f9373caa139d1d5199a31f450d6ea4073cc 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkManifoldParzenWindowsPointSetFunction.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkManifoldParzenWindowsPointSetFunction.hxx @@ -28,7 +28,7 @@ namespace itk template <typename TPointSet, typename TOutput, typename TCoordRep> ManifoldParzenWindowsPointSetFunction<TPointSet, TOutput, TCoordRep> ::ManifoldParzenWindowsPointSetFunction() : - m_PointsLocator( NULL ), + m_PointsLocator( ITK_NULLPTR ), m_CovarianceKNeighborhood( 5 ), m_EvaluationKNeighborhood( 50 ), m_RegularizationSigma( 1.0 ), @@ -167,7 +167,7 @@ TOutput ManifoldParzenWindowsPointSetFunction<TPointSet, TOutput, TCoordRep> ::Evaluate( const InputPointType &point ) const { - if( this->GetInputPointSet() == NULL ) + if( this->GetInputPointSet() == ITK_NULLPTR ) { itkExceptionMacro( "The input point set has not been specified." ); } @@ -212,7 +212,7 @@ ManifoldParzenWindowsPointSetFunction<TPointSet, TOutput, TCoordRep> } else { - return NULL; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4.h index 7019a59c2b4035d58d59008bbb86a7e5b9052bc1..8638b22cfda558cd9f1c023b7f98c6d0bcb12cad 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4.h @@ -170,7 +170,7 @@ public: { if( this->m_ThreaderJointPDF.size() == 0 ) { - return typename JointPDFType::Pointer(NULL); + return typename JointPDFType::Pointer(ITK_NULLPTR); } return this->m_ThreaderJointPDF[0]; } @@ -185,7 +185,7 @@ public: { if( this->m_ThreaderJointPDFDerivatives.size() == 0 ) { - return typename JointPDFDerivativesType::Pointer(NULL); + return typename JointPDFDerivativesType::Pointer(ITK_NULLPTR); } return this->m_ThreaderJointPDFDerivatives[0]; } diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4.hxx index 49a3456b3c6964c2cb878358b1ebef66f6cb592e..60cbf7c890f17964c29596491acca5fcb6a98f35 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4.hxx @@ -29,13 +29,15 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI m_NumberOfHistogramBins(50), m_MovingImageNormalizedMin(0.0), m_FixedImageNormalizedMin(0.0), + m_FixedImageTrueMin(0.0), + m_FixedImageTrueMax(0.0), m_MovingImageTrueMin(0.0), m_MovingImageTrueMax(0.0), m_FixedImageBinSize(0.0), m_MovingImageBinSize(0.0), - m_CubicBSplineKernel(NULL), - m_CubicBSplineDerivativeKernel(NULL), + m_CubicBSplineKernel(ITK_NULLPTR), + m_CubicBSplineDerivativeKernel(ITK_NULLPTR), m_PRatioArray(0), @@ -90,10 +92,10 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI * in computing the range of intensity values. */ - this->m_FixedImageTrueMin = vcl_numeric_limits<typename TFixedImage::PixelType>::max(); - this->m_FixedImageTrueMax = vcl_numeric_limits<typename TFixedImage::PixelType>::min(); - this->m_MovingImageTrueMin = vcl_numeric_limits<typename TMovingImage::PixelType>::max(); - this->m_MovingImageTrueMax = vcl_numeric_limits<typename TMovingImage::PixelType>::min(); + this->m_FixedImageTrueMin = std::numeric_limits<typename TFixedImage::PixelType>::max(); + this->m_FixedImageTrueMax = std::numeric_limits<typename TFixedImage::PixelType>::min(); + this->m_MovingImageTrueMin = std::numeric_limits<typename TMovingImage::PixelType>::max(); + this->m_MovingImageTrueMax = std::numeric_limits<typename TMovingImage::PixelType>::min(); // We need to make robust measures only over the requested mask region itk::ImageRegionConstIteratorWithIndex<TFixedImage> fi(this->m_FixedImage, this->m_FixedImage->GetBufferedRegion() ); @@ -184,9 +186,9 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI ::ComputeResults() const { // Collect some results - for( ThreadIdType threadID = 1; threadID < this->GetNumberOfThreadsUsed(); threadID++ ) + for( ThreadIdType threadId = 1, lastThread = this->GetNumberOfThreadsUsed(); threadId < lastThread; ++threadId ) { - this->m_ThreaderJointPDFSum[0] += this->m_ThreaderJointPDFSum[threadID]; + this->m_ThreaderJointPDFSum[0] += this->m_ThreaderJointPDFSum[threadId]; } if( this->m_ThreaderJointPDFSum[0] < itk::NumericTraits< PDFValueType >::epsilon() ) { @@ -196,14 +198,14 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI std::fill(this->m_MovingImageMarginalPDF.begin(), this->m_MovingImageMarginalPDF.end(), 0.0F); PDFValueType totalMassOfPDF = 0.0; - for( unsigned int i = 0; i < this->m_NumberOfHistogramBins; i++ ) + for( unsigned int i = 0; i < this->m_NumberOfHistogramBins; ++i ) { totalMassOfPDF += this->m_ThreaderFixedImageMarginalPDF[0][i]; } const PDFValueType normalizationFactor = 1.0 / this->m_ThreaderJointPDFSum[0]; JointPDFValueType *pdfPtr = this->m_ThreaderJointPDF[0]->GetBufferPointer(); - for( unsigned int i = 0; i < this->m_NumberOfHistogramBins; i++ ) + for( unsigned int i = 0; i < this->m_NumberOfHistogramBins; ++i ) { PDFValueType * movingMarginalPtr = &(m_MovingImageMarginalPDF[0]); for( unsigned int j = 0; j < this->m_NumberOfHistogramBins; j++ ) @@ -213,7 +215,7 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI } } - SizeValueType numberOfPoints = this->GetNumberOfDomainPoints(); + const SizeValueType numberOfPoints = this->GetNumberOfDomainPoints(); if( this->GetNumberOfValidPoints() < numberOfPoints / 16 ) { @@ -230,7 +232,7 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI { itkExceptionMacro("Fixed image marginal PDF summed to zero"); } - for( unsigned int bin = 0; bin < this->m_NumberOfHistogramBins; bin++ ) + for( unsigned int bin = 0; bin < this->m_NumberOfHistogramBins; ++bin ) { this->m_ThreaderFixedImageMarginalPDF[0][bin] /= totalMassOfPDF; } @@ -247,6 +249,7 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI const PDFValueType nFactor = 1.0 / ( this->m_MovingImageBinSize * this->GetNumberOfValidPoints() ); + static const PDFValueType closeToZero = std::numeric_limits<PDFValueType>::epsilon(); for( unsigned int fixedIndex = 0; fixedIndex < this->m_NumberOfHistogramBins; ++fixedIndex ) { const PDFValueType fixedImagePDFValue = this->m_ThreaderFixedImageMarginalPDF[0][fixedIndex]; @@ -256,16 +259,15 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI const PDFValueType jointPDFValue = *( jointPDFPtr ); // check for non-zero bin contribution - static const PDFValueType closeToZero = vcl_numeric_limits<PDFValueType>::epsilon(); if( ! (jointPDFValue > closeToZero && movingImagePDFValue > closeToZero) ) { continue; } - const PDFValueType pRatio = vcl_log(jointPDFValue / movingImagePDFValue); + const PDFValueType pRatio = std::log(jointPDFValue / movingImagePDFValue); if( fixedImagePDFValue > closeToZero ) { - sum += jointPDFValue * ( pRatio - vcl_log(fixedImagePDFValue) ); + sum += jointPDFValue * ( pRatio - std::log(fixedImagePDFValue) ); } if( this->GetComputeDerivative() ) @@ -278,7 +280,9 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI JointPDFValueType const * derivPtr = this->m_ThreaderJointPDFDerivatives[0]->GetBufferPointer() + ( fixedIndex * this->m_ThreaderJointPDFDerivatives[0]->GetOffsetTable()[2] ) + ( movingIndex * this->m_ThreaderJointPDFDerivatives[0]->GetOffsetTable()[1] ); - for( unsigned int parameter = 0; parameter < this->GetNumberOfLocalParameters(); ++parameter, derivPtr++ ) + for( unsigned int parameter = 0, lastParameter = this->GetNumberOfLocalParameters(); + parameter < lastParameter; + ++parameter, derivPtr++ ) { // Ref: eqn 23 of Thevenaz & Unser paper [3] (*(this->m_DerivativeResult))[parameter] += ( *derivPtr ) * pRatio; @@ -288,7 +292,7 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI { // Collect the pRatio per pdf indecies. // Will be applied subsequently to local-support derivative - OffsetValueType index = movingIndex + (fixedIndex * this->m_NumberOfHistogramBins); + const OffsetValueType index = movingIndex + (fixedIndex * this->m_NumberOfHistogramBins); this->m_PRatioArray[index] = pRatio * nFactor; } } @@ -301,15 +305,15 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI { if( this->HasLocalSupport() ) { - for( SizeValueType i = 0; i < this->m_DerivativeResult->Size(); i++ ) + for( SizeValueType i = 0, derivativeSize = this->m_DerivativeResult->Size(); i < derivativeSize; ++i ) { - for( SizeValueType bin = 0; bin < 4; bin++ ) + for( SizeValueType bin = 0; bin < 4; ++bin ) { // Increment the m_JointPdfIndex1DArray index by bin in order to recover // the pRatio at the moving indecies used for each portion of the derivative. // Note: in old v3 metric ComputeDerivatives, derivativeContribution is subtracted in global case, // but added in "local" (implicit) case. These operations have been switched to minimize the metric. - SizeValueType pRatioIndex = this->m_JointPdfIndex1DArray[i] + bin; + const SizeValueType pRatioIndex = this->m_JointPdfIndex1DArray[i] + bin; (*(this->m_DerivativeResult))[i] -= m_LocalDerivativeByParzenBin[bin][i] * this->m_PRatioArray[pRatioIndex]; } } @@ -332,25 +336,26 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI // code used by GetValue and GetValueAndDerivative. // Should be threaded. But if modified to do so, should probably not be threaded // separately, but rather as a part of all post-processing. - for( ThreadIdType threadID = 0; threadID < this->GetNumberOfThreadsUsed(); threadID++ ) + for( ThreadIdType threadId = 0, localNumberOfThreadsUsed = this->GetNumberOfThreadsUsed(); + threadId < localNumberOfThreadsUsed; ++threadId ) { - const int maxI = this->m_NumberOfHistogramBins * ( this->m_ThreaderJointPDFEndBin[threadID] - this->m_ThreaderJointPDFStartBin[threadID] + 1 ); + const int histogramBlockSize = this->m_NumberOfHistogramBins * ( this->m_ThreaderJointPDFEndBin[threadId] - this->m_ThreaderJointPDFStartBin[threadId] + 1 ); - const unsigned int tPdfPtrOffset = ( this->m_ThreaderJointPDFStartBin[threadID] * this->m_ThreaderJointPDF[0]->GetOffsetTable()[1] ); + const unsigned int tPdfPtrOffset = ( this->m_ThreaderJointPDFStartBin[threadId] * this->m_ThreaderJointPDF[0]->GetOffsetTable()[1] ); JointPDFValueType * const pdfPtrStart = this->m_ThreaderJointPDF[0]->GetBufferPointer() + tPdfPtrOffset; // The PDF domain is chunked based on thread. Each thread consolodates independent parts of the PDF. - for( unsigned int t = 1; t < this->GetNumberOfThreadsUsed(); t++ ) + for( unsigned int t = 1; t < localNumberOfThreadsUsed; ++t ) { JointPDFValueType * pdfPtr = pdfPtrStart; JointPDFValueType const * tPdfPtr = this->m_ThreaderJointPDF[t]->GetBufferPointer() + tPdfPtrOffset; - JointPDFValueType const * const tPdfPtrEnd = tPdfPtr + maxI; - // for(i=0; i < maxI; i++) + JointPDFValueType const * const tPdfPtrEnd = tPdfPtr + histogramBlockSize; + // for(i=0; i < histogramBlockSize; i++) while( tPdfPtr < tPdfPtrEnd ) { *( pdfPtr++ ) += *( tPdfPtr++ ); } - for( int i = this->m_ThreaderJointPDFStartBin[threadID]; i <= this->m_ThreaderJointPDFEndBin[threadID]; i++ ) + for( int i = this->m_ThreaderJointPDFStartBin[threadId], endBin= this->m_ThreaderJointPDFEndBin[threadId]; i <= endBin; ++i ) { this->m_ThreaderFixedImageMarginalPDF[0][i] += this->m_ThreaderFixedImageMarginalPDF[t][i]; } @@ -358,11 +363,11 @@ MattesMutualInformationImageToImageMetricv4<TFixedImage, TMovingImage, TVirtualI // Sum of this threads domain into the this->m_ThreaderJointPDFSum that covers that part of the domain. PDFValueType jointPDFSum = 0.0; JointPDFValueType const * pdfPtr = pdfPtrStart; - for( int i = 0; i < maxI; i++ ) + for( int i = 0; i < histogramBlockSize; i++ ) { jointPDFSum += *( pdfPtr++ ); } - this->m_ThreaderJointPDFSum[threadID] = jointPDFSum; + this->m_ThreaderJointPDFSum[threadId] = jointPDFSum; } } diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader.h index ed883377707c75323d93cf216061e6b8856e542d..071cf9ed3ee4429c52cc48d9b6cd254632c09c98 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader.h @@ -82,7 +82,9 @@ public: typedef typename TMattesMutualInformationMetric::JacobianType JacobianType; protected: - MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader() {} + MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader() : + m_MattesAssociate(ITK_NULLPTR) + {} virtual void BeforeThreadedExecution(); @@ -102,14 +104,20 @@ protected: const MovingImageGradientType & mappedMovingImageGradient, MeasureType & metricValueReturn, DerivativeType & localDerivativeReturn, - const ThreadIdType threadID ) const; + const ThreadIdType threadId ) const; - /** Compute PDF derivative contribution for each parameter. */ - virtual void ComputePDFDerivatives(const ThreadIdType & threadID, + /** Compute PDF derivative contribution for each parameter of a global support transform type. */ + virtual void ComputePDFDerivativesGlobalSupportTransform(const ThreadIdType & threadId, const OffsetValueType & fixedImageParzenWindowIndex, const JacobianType & jacobian, const OffsetValueType & pdfMovingIndex, const MovingImageGradientType & movingGradient, + const PDFValueType & cubicBSplineDerivativeValue) const; + + /** Compute PDF derivative contribution for each parameter of a displacement field. */ + virtual void ComputePDFDerivativesLocalSupportTransform( + const JacobianType & jacobian, + const MovingImageGradientType & movingGradient, const PDFValueType & cubicBSplineDerivativeValue, DerivativeValueType * localSupportDerivativeResultPtr) const; diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader.hxx index efb53fe4d18eca60d177ef836a7895449e57e2c4..7cf6f430bbbf190e04c499109c3baf5e49d63ea3 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader.hxx @@ -38,7 +38,7 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai /* Store the casted pointer to avoid dynamic casting in tight loops. */ this->m_MattesAssociate = dynamic_cast<TMattesMutualInformationMetric*>(this->m_Associate); - if( this->m_MattesAssociate == NULL ) + if( this->m_MattesAssociate == ITK_NULLPTR ) { itkExceptionMacro("Dynamic casting of associate pointer failed."); } @@ -49,23 +49,25 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai * Allocate memory for the marginal PDF and initialize values * to zero. The marginal PDFs are stored as std::vector. */ + const ThreadIdType mattesAssociateNumThreadsUsed = this->m_MattesAssociate->GetNumberOfThreadsUsed(); this->m_MattesAssociate->m_MovingImageMarginalPDF.resize(this->m_MattesAssociate->m_NumberOfHistogramBins, 0.0F); - this->m_MattesAssociate->m_ThreaderFixedImageMarginalPDF.resize(this->m_MattesAssociate->GetNumberOfThreadsUsed(), + this->m_MattesAssociate->m_ThreaderFixedImageMarginalPDF.resize(mattesAssociateNumThreadsUsed, std::vector<PDFValueType>(this->m_MattesAssociate->m_NumberOfHistogramBins, 0.0F) ); - this->m_MattesAssociate->m_ThreaderJointPDFStartBin.resize( this->GetNumberOfThreadsUsed() ); - this->m_MattesAssociate->m_ThreaderJointPDFEndBin.resize(this->GetNumberOfThreadsUsed() ); - const OffsetValueType binRange = this->m_MattesAssociate->m_NumberOfHistogramBins / this->GetNumberOfThreadsUsed(); - for( ThreadIdType threadID = 0; threadID < this->GetNumberOfThreadsUsed(); threadID++ ) + const ThreadIdType localNumberOfThreadsUsed = this->GetNumberOfThreadsUsed(); + this->m_MattesAssociate->m_ThreaderJointPDFStartBin.resize( localNumberOfThreadsUsed ); + this->m_MattesAssociate->m_ThreaderJointPDFEndBin.resize(localNumberOfThreadsUsed ); + const OffsetValueType binRange = this->m_MattesAssociate->m_NumberOfHistogramBins / localNumberOfThreadsUsed; + for( ThreadIdType threadId = 0; threadId < localNumberOfThreadsUsed; ++threadId ) { - this->m_MattesAssociate->m_ThreaderJointPDFStartBin[threadID] = threadID * binRange; - this->m_MattesAssociate->m_ThreaderJointPDFEndBin[threadID] = ( threadID + 1 ) * binRange - 1; + this->m_MattesAssociate->m_ThreaderJointPDFStartBin[threadId] = threadId * binRange; + this->m_MattesAssociate->m_ThreaderJointPDFEndBin[threadId] = ( threadId + 1 ) * binRange - 1; } // Ensure that the last EndBin range contains the last histogram bin - this->m_MattesAssociate->m_ThreaderJointPDFStartBin[this->GetNumberOfThreadsUsed() - 1] = ( this->GetNumberOfThreadsUsed() - 1 ) * binRange; - this->m_MattesAssociate->m_ThreaderJointPDFEndBin[this->GetNumberOfThreadsUsed() - 1] = this->m_MattesAssociate->m_NumberOfHistogramBins - 1; + this->m_MattesAssociate->m_ThreaderJointPDFStartBin[localNumberOfThreadsUsed - 1] = ( localNumberOfThreadsUsed - 1 ) * binRange; + this->m_MattesAssociate->m_ThreaderJointPDFEndBin[localNumberOfThreadsUsed - 1] = this->m_MattesAssociate->m_NumberOfHistogramBins - 1; - this->m_MattesAssociate->m_ThreaderJointPDFSum.resize(this->GetNumberOfThreadsUsed()); + this->m_MattesAssociate->m_ThreaderJointPDFSum.resize(localNumberOfThreadsUsed); JointPDFRegionType jointPDFRegion; // For the joint PDF define a region starting from {0,0} @@ -92,14 +94,14 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai * Allocate memory for the joint PDF and joint PDF derivatives. * The joint PDF and joint PDF derivatives are store as itk::Image. */ - this->m_MattesAssociate->m_ThreaderJointPDF.resize(this->GetNumberOfThreadsUsed()); - for( ThreadIdType threadID = 0; threadID < this->GetNumberOfThreadsUsed(); ++threadID ) + this->m_MattesAssociate->m_ThreaderJointPDF.resize(localNumberOfThreadsUsed); + for( ThreadIdType threadId = 0; threadId < localNumberOfThreadsUsed; ++threadId ) { - this->m_MattesAssociate->m_ThreaderJointPDF[threadID] = JointPDFType::New(); - this->m_MattesAssociate->m_ThreaderJointPDF[threadID]->SetRegions(jointPDFRegion); - this->m_MattesAssociate->m_ThreaderJointPDF[threadID]->SetOrigin(origin); - this->m_MattesAssociate->m_ThreaderJointPDF[threadID]->SetSpacing(spacing); - this->m_MattesAssociate->m_ThreaderJointPDF[threadID]->Allocate(); + this->m_MattesAssociate->m_ThreaderJointPDF[threadId] = JointPDFType::New(); + this->m_MattesAssociate->m_ThreaderJointPDF[threadId]->SetRegions(jointPDFRegion); + this->m_MattesAssociate->m_ThreaderJointPDF[threadId]->SetOrigin(origin); + this->m_MattesAssociate->m_ThreaderJointPDF[threadId]->SetSpacing(spacing); + this->m_MattesAssociate->m_ThreaderJointPDF[threadId]->Allocate(); } // @@ -125,7 +127,7 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai this->m_MattesAssociate->m_LocalDerivativeByParzenBin.resize(4); // The first container cannot point to the existing derivative result object // for efficiency, because of multi-variate metric. - for( SizeValueType n = 0; n<4; n++ ) + for( SizeValueType n = 0; n < 4; ++n ) { this->m_MattesAssociate->m_LocalDerivativeByParzenBin[n].SetSize( this->m_MattesAssociate->GetNumberOfParameters() ); // Initialize to zero because we accumulate, and so skipped points will behave properly @@ -157,13 +159,13 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai jointPDFDerivativesRegion.SetIndex(jointPDFDerivativesIndex); jointPDFDerivativesRegion.SetSize(jointPDFDerivativesSize); - this->m_MattesAssociate->m_ThreaderJointPDFDerivatives.resize(this->GetNumberOfThreadsUsed()); + this->m_MattesAssociate->m_ThreaderJointPDFDerivatives.resize(localNumberOfThreadsUsed); // Set the regions and allocate - for( ThreadIdType threadID = 0; threadID < this->GetNumberOfThreadsUsed(); threadID++ ) + for( ThreadIdType threadId = 0; threadId < localNumberOfThreadsUsed; ++threadId ) { - this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadID] = JointPDFDerivativesType::New(); - this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadID]->SetRegions( jointPDFDerivativesRegion); - this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadID]->Allocate(); + this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadId] = JointPDFDerivativesType::New(); + this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadId]->SetRegions( jointPDFDerivativesRegion); + this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadId]->Allocate(); } } } @@ -176,16 +178,15 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai /* This block of code is from MattesMutualImageToImageMetric::GetValueAndDerivativeThreadPreProcess */ - for( ThreadIdType threadID = 0; threadID < this->GetNumberOfThreadsUsed(); threadID++ ) + const bool createPerThreadDerivativesBuffers = this->m_MattesAssociate->GetComputeDerivative() + && ( ! this->m_MattesAssociate->HasLocalSupport() ); + for( ThreadIdType threadId = 0; threadId < localNumberOfThreadsUsed; ++threadId ) { - std::fill( this->m_MattesAssociate->m_ThreaderFixedImageMarginalPDF[threadID].begin(), this->m_MattesAssociate->m_ThreaderFixedImageMarginalPDF[threadID].end(), 0.0F); - this->m_MattesAssociate->m_ThreaderJointPDF[threadID]->FillBuffer(0.0F); - if( this->m_MattesAssociate->GetComputeDerivative() ) + std::fill( this->m_MattesAssociate->m_ThreaderFixedImageMarginalPDF[threadId].begin(), this->m_MattesAssociate->m_ThreaderFixedImageMarginalPDF[threadId].end(), 0.0F); + this->m_MattesAssociate->m_ThreaderJointPDF[threadId]->FillBuffer(0.0F); + if( createPerThreadDerivativesBuffers ) { - if( ! this->m_MattesAssociate->HasLocalSupport() ) - { - this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadID]->FillBuffer(0.0F); - } + this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadId]->FillBuffer(0.0F); } } } @@ -204,8 +205,9 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai const MovingImageGradientType & movingImageGradient, MeasureType &, DerivativeType &, - const ThreadIdType threadID) const + const ThreadIdType threadId) const { + const bool doComputeDerivative = this->m_MattesAssociate->GetComputeDerivative(); /** * Compute this sample's contribution to the marginal * and joint distributions. @@ -221,7 +223,7 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai } // Determine parzen window arguments (see eqn 6 of Mattes paper [2]). - PDFValueType movingImageParzenWindowTerm = movingImageValue / this->m_MattesAssociate->m_MovingImageBinSize - this->m_MattesAssociate->m_MovingImageNormalizedMin; + const PDFValueType movingImageParzenWindowTerm = movingImageValue / this->m_MattesAssociate->m_MovingImageBinSize - this->m_MattesAssociate->m_MovingImageNormalizedMin; OffsetValueType movingImageParzenWindowIndex = static_cast<OffsetValueType>( movingImageParzenWindowTerm ); // Make sure the extreme values are in valid bins @@ -237,7 +239,7 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai movingImageParzenWindowIndex = nindex; } } - // Move the pointer to the fist affected bin + // Move the pointer to the first affected bin OffsetValueType pdfMovingIndex = static_cast<OffsetValueType>( movingImageParzenWindowIndex ) - 1; const OffsetValueType pdfMovingIndexMax = static_cast<OffsetValueType>( movingImageParzenWindowIndex ) + 2; @@ -246,7 +248,7 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai // Since a zero-order BSpline (box car) kernel is used for // the fixed image marginal pdf, we need only increment the // fixedImageParzenWindowIndex by value of 1.0. - this->m_MattesAssociate->m_ThreaderFixedImageMarginalPDF[threadID][fixedImageParzenWindowIndex] += 1; + this->m_MattesAssociate->m_ThreaderFixedImageMarginalPDF[threadId][fixedImageParzenWindowIndex] += 1; /** * The region of support of the parzen window determines which bins @@ -262,64 +264,75 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai PDFValueType movingImageParzenWindowArg = static_cast<PDFValueType>( pdfMovingIndex ) - static_cast<PDFValueType>( movingImageParzenWindowTerm ); // Pointer to affected bin to be updated - JointPDFValueType *pdfPtr = this->m_MattesAssociate->m_ThreaderJointPDF[threadID]->GetBufferPointer() + JointPDFValueType *pdfPtr = this->m_MattesAssociate->m_ThreaderJointPDF[threadId]->GetBufferPointer() + ( fixedImageParzenWindowIndex * this->m_MattesAssociate->m_NumberOfHistogramBins ) + pdfMovingIndex; OffsetValueType localDerivativeOffset = 0; // Store the pdf indecies for this point. // Just store the starting pdfMovingIndex and we'll iterate later // over the next four to collect results. - if( this->m_MattesAssociate->GetComputeDerivative() ) + if( doComputeDerivative && ( this->m_MattesAssociate->HasLocalSupport() ) ) { - if( this->m_MattesAssociate->HasLocalSupport() ) + const OffsetValueType jointPdfIndex1D = pdfMovingIndex + (fixedImageParzenWindowIndex * this->m_MattesAssociate->m_NumberOfHistogramBins); + localDerivativeOffset = this->m_MattesAssociate->ComputeParameterOffsetFromVirtualIndex( virtualIndex, this->GetCachedNumberOfLocalParameters() ); + for (NumberOfParametersType i=0, numLocalParameters = this->GetCachedNumberOfLocalParameters(); + i < numLocalParameters; ++i) { - OffsetValueType jointPdfIndex1D = pdfMovingIndex + (fixedImageParzenWindowIndex * this->m_MattesAssociate->m_NumberOfHistogramBins); - localDerivativeOffset = this->m_MattesAssociate->ComputeParameterOffsetFromVirtualIndex( virtualIndex, this->GetCachedNumberOfLocalParameters() ); - for (NumberOfParametersType i=0; i < this->GetCachedNumberOfLocalParameters(); i++) - { - this->m_MattesAssociate->m_JointPdfIndex1DArray[localDerivativeOffset + i] = jointPdfIndex1D; - } + this->m_MattesAssociate->m_JointPdfIndex1DArray[localDerivativeOffset + i] = jointPdfIndex1D; } } // Compute the transform Jacobian. typedef JacobianType & JacobianReferenceType; - JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadID].MovingTransformJacobian; - if( this->m_MattesAssociate->GetComputeDerivative() ) + JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobian; + if( doComputeDerivative ) { - this->m_MattesAssociate->GetMovingTransform()->ComputeJacobianWithRespectToParameters( virtualPoint, jacobian); + JacobianReferenceType jacobianPositional = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobianPositional; + this->m_MattesAssociate->GetMovingTransform()-> + ComputeJacobianWithRespectToParametersCachedTemporaries(virtualPoint, + jacobian, + jacobianPositional); } SizeValueType movingParzenBin = 0; + const bool transformIsDisplacement = this->m_MattesAssociate->m_MovingTransform->GetTransformCategory() == MovingTransformType::DisplacementField; while( pdfMovingIndex <= pdfMovingIndexMax ) { - PDFValueType val = static_cast<PDFValueType>( this->m_MattesAssociate->m_CubicBSplineKernel ->Evaluate( movingImageParzenWindowArg) ); + const PDFValueType val = static_cast<PDFValueType>( this->m_MattesAssociate->m_CubicBSplineKernel ->Evaluate( movingImageParzenWindowArg) ); *( pdfPtr++ ) += val; - if( this->m_MattesAssociate->GetComputeDerivative() ) + if( doComputeDerivative ) { // Compute the cubicBSplineDerivative for later repeated use. const PDFValueType cubicBSplineDerivativeValue = this->m_MattesAssociate->m_CubicBSplineDerivativeKernel->Evaluate(movingImageParzenWindowArg); - // Pointer to local derivative partial result container. - // Not used with global support transforms. - DerivativeValueType * localSupportDerivativeResultPtr = NULL; - if( this->m_MattesAssociate->m_MovingTransform->GetTransformCategory() == MovingTransformType::DisplacementField ) - { - // ptr to where the derivative result should go, for efficiency - localSupportDerivativeResultPtr = &( this->m_MattesAssociate->m_LocalDerivativeByParzenBin[movingParzenBin][localDerivativeOffset] ); - } - - // Compute PDF derivative contribution. - this->ComputePDFDerivatives(threadID, - fixedImageParzenWindowIndex, - jacobian, - pdfMovingIndex, - movingImageGradient, - cubicBSplineDerivativeValue, - localSupportDerivativeResultPtr); + if( transformIsDisplacement ) + { + // Pointer to local derivative partial result container. + // Not used with global support transforms. + // ptr to where the derivative result should go, for efficiency + DerivativeValueType * localSupportDerivativeResultPtr = + &( this->m_MattesAssociate->m_LocalDerivativeByParzenBin[movingParzenBin][localDerivativeOffset] ); + // Compute PDF derivative contribution. + + this->ComputePDFDerivativesLocalSupportTransform( + jacobian, + movingImageGradient, + cubicBSplineDerivativeValue, + localSupportDerivativeResultPtr); + } + else + { + // Compute PDF derivative contribution. + this->ComputePDFDerivativesGlobalSupportTransform(threadId, + fixedImageParzenWindowIndex, + jacobian, + pdfMovingIndex, + movingImageGradient, + cubicBSplineDerivativeValue); + } } movingImageParzenWindowArg += 1.0; @@ -328,57 +341,63 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai } // have to do this here since we're returning false - this->m_GetValueAndDerivativePerThreadVariables[threadID].NumberOfValidPoints++; + this->m_GetValueAndDerivativePerThreadVariables[threadId].NumberOfValidPoints++; // Return false to avoid the storage of results in parent class. return false; } -/** - * ComputePDFDerivative - */ template< typename TDomainPartitioner, typename TImageToImageMetric, typename TMattesMutualInformationMetric > void MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TMattesMutualInformationMetric > -::ComputePDFDerivatives(const ThreadIdType & threadID, +::ComputePDFDerivativesGlobalSupportTransform(const ThreadIdType & threadId, const OffsetValueType & fixedImageParzenWindowIndex, const JacobianType & jacobian, const OffsetValueType & pdfMovingIndex, const MovingImageGradientType & movingImageGradient, - const PDFValueType & cubicBSplineDerivativeValue, - DerivativeValueType * localSupportDerivativeResultPtr) const + const PDFValueType & cubicBSplineDerivativeValue) const { // Update bins in the PDF derivatives for the current intensity pair - const OffsetValueType pdfFixedIndex = fixedImageParzenWindowIndex; - JointPDFDerivativesValueType *derivPtr=0; - if( this->m_MattesAssociate->m_MovingTransform->GetTransformCategory() != MovingTransformType::DisplacementField ) - { - derivPtr = this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadID]->GetBufferPointer() - + ( pdfFixedIndex * this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadID]->GetOffsetTable()[2] ) - + ( pdfMovingIndex * this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadID]->GetOffsetTable()[1] ); - } + JointPDFDerivativesValueType *derivPtr = this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadId]->GetBufferPointer() + + ( pdfFixedIndex * this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadId]->GetOffsetTable()[2] ) + + ( pdfMovingIndex * this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[threadId]->GetOffsetTable()[1] ); - for( NumberOfParametersType mu = 0; mu < this->GetCachedNumberOfLocalParameters(); mu++ ) + for( NumberOfParametersType mu = 0, maxElement=this->GetCachedNumberOfLocalParameters(); mu < maxElement; ++mu ) { PDFValueType innerProduct = 0.0; - for( SizeValueType dim = 0; dim < this->m_MattesAssociate->MovingImageDimension; dim++ ) + for( SizeValueType dim = 0, lastDim = this->m_MattesAssociate->MovingImageDimension; dim < lastDim; ++dim ) { innerProduct += jacobian[dim][mu] * movingImageGradient[dim]; } const PDFValueType derivativeContribution = innerProduct * cubicBSplineDerivativeValue; - if( this->m_MattesAssociate->m_MovingTransform->GetTransformCategory() == MovingTransformType::DisplacementField ) - { - *( localSupportDerivativeResultPtr ) += derivativeContribution; - localSupportDerivativeResultPtr++; - } - else + *( derivPtr ) -= derivativeContribution; + ++derivPtr; + } +} + +template< typename TDomainPartitioner, typename TImageToImageMetric, typename TMattesMutualInformationMetric > +void +MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TMattesMutualInformationMetric > +::ComputePDFDerivativesLocalSupportTransform( + const JacobianType & jacobian, + const MovingImageGradientType & movingImageGradient, + const PDFValueType & cubicBSplineDerivativeValue, + DerivativeValueType * localSupportDerivativeResultPtr) const +{ + for( NumberOfParametersType mu = 0, maxElement=this->GetCachedNumberOfLocalParameters(); mu < maxElement; ++mu ) + { + PDFValueType innerProduct = 0.0; + for( SizeValueType dim = 0, lastDim = this->m_MattesAssociate->MovingImageDimension; dim < lastDim; ++dim ) { - *( derivPtr ) -= derivativeContribution; - ++derivPtr; + innerProduct += jacobian[dim][mu] * movingImageGradient[dim]; } + + const PDFValueType derivativeContribution = innerProduct * cubicBSplineDerivativeValue; + *( localSupportDerivativeResultPtr ) += derivativeContribution; + localSupportDerivativeResultPtr++; } } @@ -387,6 +406,7 @@ void MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner, TImageToImageMetric, TMattesMutualInformationMetric > ::AfterThreadedExecution() { + const ThreadIdType localNumberOfThreadsUsed = this->GetNumberOfThreadsUsed(); /* NOTE: It is not worth threading this method. Profiling shows that post-processing * time of images with real-world sizes is too insignificant to register in * the profiler. */ @@ -395,9 +415,9 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai * m_NumberOfValidPoints by collecting the valid points per thread. * We do this here because we're skipping Superclass::AfterThreadedExecution*/ this->m_MattesAssociate->m_NumberOfValidPoints = NumericTraits< SizeValueType >::Zero; - for (ThreadIdType i=0; i<this->GetNumberOfThreadsUsed(); i++) + for (ThreadIdType threadId = 0; threadId < localNumberOfThreadsUsed; ++threadId) { - this->m_MattesAssociate->m_NumberOfValidPoints += this->m_GetValueAndDerivativePerThreadVariables[i].NumberOfValidPoints; + this->m_MattesAssociate->m_NumberOfValidPoints += this->m_GetValueAndDerivativePerThreadVariables[threadId].NumberOfValidPoints; } /* Porting: This code is from @@ -406,40 +426,41 @@ MattesMutualInformationImageToImageMetricv4GetValueAndDerivativeThreader< TDomai /* Post-processing that is common the GetValue and GetValueAndDerivative */ this->m_MattesAssociate->GetValueCommonAfterThreadedExecution(); - if( this->m_MattesAssociate->GetComputeDerivative() ) + if( this->m_MattesAssociate->GetComputeDerivative() && ( ! this->m_MattesAssociate->HasLocalSupport() ) ) { - if( ! this->m_MattesAssociate->HasLocalSupport() ) + const NumberOfParametersType rowSize = this->GetCachedNumberOfLocalParameters() * this->m_MattesAssociate->m_NumberOfHistogramBins; + /* See note above about threading. */ + + // This entire block of code is used to accumulate the per-thread buffers into 1 thread. + for( ThreadIdType threadId = 0; threadId < localNumberOfThreadsUsed; ++threadId ) { - /* See note above about threading. */ - for( ThreadIdType threadID = 0; threadID < this->GetNumberOfThreadsUsed(); threadID++ ) - { - const NumberOfParametersType rowSize = this->GetCachedNumberOfLocalParameters() * this->m_MattesAssociate->m_NumberOfHistogramBins; + // For this thread, how many histogram elements are there? + const SizeValueType histogramBlockSize = rowSize * ( this->m_MattesAssociate->m_ThreaderJointPDFEndBin[threadId] - this->m_MattesAssociate->m_ThreaderJointPDFStartBin[threadId] + 1 ); + + JointPDFDerivativesValueType *const accumulatorPdfDPtrStart = this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[0]->GetBufferPointer() + + ( this->m_MattesAssociate->m_ThreaderJointPDFStartBin[threadId] * rowSize ); - const SizeValueType maxI = rowSize * ( this->m_MattesAssociate->m_ThreaderJointPDFEndBin[threadID] - this->m_MattesAssociate->m_ThreaderJointPDFStartBin[threadID] + 1 ); + const SizeValueType tempThreadPdfDPtrOffset = this->m_MattesAssociate->m_ThreaderJointPDFStartBin[threadId] * rowSize; - JointPDFDerivativesValueType *const pdfDPtrStart = this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[0]->GetBufferPointer() - + ( this->m_MattesAssociate->m_ThreaderJointPDFStartBin[threadID] * rowSize ); - const SizeValueType tPdfDPtrOffset = this->m_MattesAssociate->m_ThreaderJointPDFStartBin[threadID] * rowSize; - for( SizeValueType t = 1; t < this->GetNumberOfThreadsUsed(); t++ ) + for( SizeValueType t = 1; t < localNumberOfThreadsUsed; ++t ) + { + JointPDFDerivativesValueType * accumulatorPdfDPtr = accumulatorPdfDPtrStart; + JointPDFDerivativesValueType const * tempThreadPdfDPtr = this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[t]->GetBufferPointer() + tempThreadPdfDPtrOffset; + JointPDFDerivativesValueType const * const tempThreadPdfDPtrEnd = tempThreadPdfDPtr + histogramBlockSize; + // for(i = 0; i < histogramBlockSize; i++) + while( tempThreadPdfDPtr < tempThreadPdfDPtrEnd ) { - JointPDFDerivativesValueType * pdfDPtr = pdfDPtrStart; - JointPDFDerivativesValueType const *tPdfDPtr = this->m_MattesAssociate->m_ThreaderJointPDFDerivatives[t]->GetBufferPointer() + tPdfDPtrOffset; - JointPDFDerivativesValueType const * const tPdfDPtrEnd = tPdfDPtr + maxI; - // for(i = 0; i < maxI; i++) - while( tPdfDPtr < tPdfDPtrEnd ) - { - *( pdfDPtr++ ) += *( tPdfDPtr++ ); - } + *( accumulatorPdfDPtr++ ) += *( tempThreadPdfDPtr++ ); } + } - const PDFValueType nFactor = 1.0 / ( this->m_MattesAssociate->m_MovingImageBinSize * this->m_MattesAssociate->GetNumberOfValidPoints() ); + const PDFValueType nFactor = 1.0 / ( this->m_MattesAssociate->m_MovingImageBinSize * this->m_MattesAssociate->GetNumberOfValidPoints() ); - JointPDFDerivativesValueType * pdfDPtr = pdfDPtrStart; - JointPDFDerivativesValueType const * const tPdfDPtrEnd = pdfDPtrStart + maxI; - while( pdfDPtr < tPdfDPtrEnd ) - { - *( pdfDPtr++ ) *= nFactor; - } + JointPDFDerivativesValueType * accumulatorPdfDPtr = accumulatorPdfDPtrStart; + JointPDFDerivativesValueType const * const tempThreadPdfDPtrEnd = accumulatorPdfDPtrStart + histogramBlockSize; + while( accumulatorPdfDPtr < tempThreadPdfDPtrEnd ) + { + *( accumulatorPdfDPtr++ ) *= nFactor; } } } diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.h index e003616946c3319792ae881bd632571586f9b622..b5813808477bb7e49cd0410a967fe0c9cf5f62fb 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.h @@ -78,7 +78,7 @@ protected: const MovingImageGradientType & mappedMovingImageGradient, MeasureType & metricValueReturn, DerivativeType & localDerivativeReturn, - const ThreadIdType threadID ) const; + const ThreadIdType threadId ) const; private: MeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader( const Self & ); // purposely not implemented diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.hxx index 903e0aef64a43453ec51eff4430152fea6bc23f8..9eeb68912ec7f588633043dd79dfa44e85813deb 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkMeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader.hxx @@ -37,7 +37,7 @@ MeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner const MovingImageGradientType & movingImageGradient, MeasureType & metricValueReturn, DerivativeType & localDerivativeReturn, - const ThreadIdType threadID) const + const ThreadIdType threadId) const { /** Only the voxelwise contribution given the point pairs. */ FixedImagePixelType diff = fixedImageValue - movingImageValue; @@ -57,10 +57,14 @@ MeanSquaresImageToImageMetricv4GetValueAndDerivativeThreader< TDomainPartitioner /* Use a pre-allocated jacobian object for efficiency */ typedef typename TImageToImageMetric::JacobianType & JacobianReferenceType; - JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadID].MovingTransformJacobian; + JacobianReferenceType jacobian = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobian; + JacobianReferenceType jacobianPositional = this->m_GetValueAndDerivativePerThreadVariables[threadId].MovingTransformJacobianPositional; /** For dense transforms, this returns identity */ - this->m_Associate->GetMovingTransform()->ComputeJacobianWithRespectToParameters( virtualPoint, jacobian ); + this->m_Associate->GetMovingTransform()-> + ComputeJacobianWithRespectToParametersCachedTemporaries(virtualPoint, + jacobian, + jacobianPositional); for ( unsigned int par = 0; par < this->GetCachedNumberOfLocalParameters(); par++ ) { diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkObjectToObjectMultiMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkObjectToObjectMultiMetricv4.hxx index 32ca8d7f3b5601a34a1ebc3fe3344431935113c8..7b0c57c9315108bbc2f8805f4b893e34b026d631 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkObjectToObjectMultiMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkObjectToObjectMultiMetricv4.hxx @@ -32,7 +32,7 @@ ObjectToObjectMultiMetricv4<TFixedDimension, TMovingDimension, TVirtualImage, TI this->m_MetricQueue.clear(); //We want the moving transform to be NULL by default - this->m_MovingTransform = NULL; + this->m_MovingTransform = ITK_NULLPTR; } /** Destructor */ @@ -146,7 +146,7 @@ ObjectToObjectMultiMetricv4<TFixedDimension, TMovingDimension, TVirtualImage, TI this->m_MetricValueArray.SetSize( this->GetNumberOfMetrics() ); /* Verify the same transform is in all metrics. */ - const MovingTransformType * firstTransform = NULL; + const MovingTransformType * firstTransform = ITK_NULLPTR; for (SizeValueType j = 0; j < this->GetNumberOfMetrics(); j++) { const MovingTransformType * transform = this->m_MetricQueue[j]->GetMovingTransform(); @@ -154,7 +154,7 @@ ObjectToObjectMultiMetricv4<TFixedDimension, TMovingDimension, TVirtualImage, TI // optimized, and it must be the same as in other metrics. typedef CompositeTransform<typename MovingTransformType::ScalarType, TFixedDimension> CompositeType; const CompositeType * composite = dynamic_cast<const CompositeType*>(transform); - if( composite != NULL ) + if( composite != ITK_NULLPTR ) { SizeValueType count = 0; for( size_t n = 0; n < composite->GetNumberOfTransforms(); n++ ) @@ -360,7 +360,7 @@ ObjectToObjectMultiMetricv4<TFixedDimension, TMovingDimension, TVirtualImage, TI for (SizeValueType i = 0; i < this->GetNumberOfMetrics(); i++) { os << indent << "~~~ Metric " << i << " ~~~" << std::endl; - this->m_MetricQueue[i]->Print(os, indent ); + this->m_MetricQueue[i]->Print(os, indent.GetNextIndent() ); } } diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetFunction.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetFunction.hxx index 97edd05f48bf9fbe77a6c6d2c7f26a60060cc1f6..c44e2787d67a9a99019c4a3c0e34d543efbbc328 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetFunction.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetFunction.hxx @@ -30,7 +30,7 @@ template <typename TInputPointSet, typename TOutput, typename TCoordRep> PointSetFunction<TInputPointSet, TOutput, TCoordRep> ::PointSetFunction() { - this->m_PointSet = NULL; + this->m_PointSet = ITK_NULLPTR; } /** diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetToPointSetMetricv4.h b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetToPointSetMetricv4.h index 5706bc18044ebc5454f6b5cf5fd6ee535d4215d0..bd8f04ced280560a78196b32976411aa1812a8df 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetToPointSetMetricv4.h +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetToPointSetMetricv4.h @@ -66,17 +66,22 @@ namespace itk * \ingroup ITKMetricsv4 */ -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, + class TInternalComputationValueType = double> class PointSetToPointSetMetricv4 -: public ObjectToObjectMetric<TFixedPointSet::PointDimension, TMovingPointSet::PointDimension> +: public ObjectToObjectMetric<TFixedPointSet::PointDimension, TMovingPointSet::PointDimension, + Image<TInternalComputationValueType, TFixedPointSet::PointDimension>, TInternalComputationValueType> { public: /** Standard class typedefs. */ - typedef PointSetToPointSetMetricv4 Self; - typedef ObjectToObjectMetric<TFixedPointSet::PointDimension, TMovingPointSet::PointDimension> Superclass; - typedef SmartPointer<Self> Pointer; - typedef SmartPointer<const Self> ConstPointer; + typedef PointSetToPointSetMetricv4 Self; + typedef ObjectToObjectMetric<TFixedPointSet::PointDimension, + TMovingPointSet::PointDimension, + Image<TInternalComputationValueType, TFixedPointSet::PointDimension>, + TInternalComputationValueType> Superclass; + typedef SmartPointer<Self> Pointer; + typedef SmartPointer<const Self> ConstPointer; /** Run-time type information (and related methods). */ itkTypeMacro( PointSetToPointSetMetricv4, ObjectToObjectMetric ); @@ -173,13 +178,14 @@ public: /** Get/Set the fixed pointset. */ itkSetConstObjectMacro( FixedPointSet, FixedPointSetType ); - itkGetConstObjectMacro(FixedPointSet, FixedPointSetType ); + itkGetConstObjectMacro( FixedPointSet, FixedPointSetType ); /** Get the moving transformed point set. */ - itkGetModifiableObjectMacro(FixedTransformedPointSet, FixedTransformedPointSetType ); + itkGetModifiableObjectMacro( FixedTransformedPointSet, FixedTransformedPointSetType ); /** Get/Set the moving point set. */ itkSetConstObjectMacro( MovingPointSet, MovingPointSetType ); + itkGetConstObjectMacro( MovingPointSet, MovingPointSetType ); /** Get the moving transformed point set. */ itkGetModifiableObjectMacro(MovingTransformedPointSet, MovingTransformedPointSetType ); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetToPointSetMetricv4.hxx b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetToPointSetMetricv4.hxx index 352c7e2506fc80f0495f0640e458f79187915146..bac203a4c3efd187cf1680cf89cb79a583ea2f31 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetToPointSetMetricv4.hxx +++ b/Utilities/ITK/Modules/Registration/Metricsv4/include/itkPointSetToPointSetMetricv4.hxx @@ -25,19 +25,19 @@ namespace itk { /** Constructor */ -template<typename TFixedPointSet, typename TMovingPointSet> -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::PointSetToPointSetMetricv4() { - this->m_FixedPointSet = NULL; // has to be provided by the user. - this->m_MovingPointSet = NULL; // has to be provided by the user. + this->m_FixedPointSet = ITK_NULLPTR; // has to be provided by the user. + this->m_MovingPointSet = ITK_NULLPTR; // has to be provided by the user. - this->m_FixedTransformedPointSet = NULL; - this->m_MovingTransformedPointSet = NULL; - this->m_VirtualTransformedPointSet = NULL; + this->m_FixedTransformedPointSet = ITK_NULLPTR; + this->m_MovingTransformedPointSet = ITK_NULLPTR; + this->m_VirtualTransformedPointSet = ITK_NULLPTR; - this->m_FixedTransformedPointsLocator = NULL; - this->m_MovingTransformedPointsLocator = NULL; + this->m_FixedTransformedPointsLocator = ITK_NULLPTR; + this->m_MovingTransformedPointsLocator = ITK_NULLPTR; this->m_MovingTransformPointLocatorsNeedInitialization = false; this->m_FixedTransformPointLocatorsNeedInitialization = false; @@ -54,16 +54,16 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } /** Destructor */ -template<typename TFixedPointSet, typename TMovingPointSet> -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::~PointSetToPointSetMetricv4() { } /** Initialize the metric */ -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::Initialize( void ) throw ( ExceptionObject ) { if ( !this->m_FixedPointSet ) @@ -124,9 +124,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> this->InitializePointSets(); } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::InitializePointSets() const { this->TransformMovingPointSet(); @@ -134,9 +134,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> this->InitializePointsLocators(); } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::InitializeForIteration() const { this->InitializePointSets(); @@ -148,17 +148,17 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> SizeValueType -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetNumberOfComponents() const { return this->m_FixedTransformedPointSet->GetNumberOfPoints(); } -template<typename TFixedPointSet, typename TMovingPointSet> -typename PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet>::MeasureType -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +typename PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType>::MeasureType +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetValue() const { this->InitializeForIteration(); @@ -207,26 +207,26 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> return value; } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetDerivative( DerivativeType & derivative ) const { MeasureType value = NumericTraits<MeasureType>::Zero; this->CalculateValueAndDerivative( value, derivative, false ); } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetValueAndDerivative( MeasureType & value, DerivativeType & derivative ) const { this->CalculateValueAndDerivative( value, derivative, true ); } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::CalculateValueAndDerivative( MeasureType & value, DerivativeType & derivative, bool calculateValue ) const { this->InitializeForIteration(); @@ -235,6 +235,7 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> value = NumericTraits<MeasureType>::Zero; MovingTransformJacobianType jacobian( MovingPointDimension, this->GetNumberOfLocalParameters() ); + MovingTransformJacobianType jacobianPositional( MovingPointDimension, MovingPointDimension ); DerivativeType localTransformDerivative( this->GetNumberOfLocalParameters() ); localTransformDerivative.Fill( NumericTraits<DerivativeValueType>::Zero ); @@ -286,7 +287,10 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> // Reset to zero since we're not accumulating in the local-support case. localTransformDerivative.Fill( NumericTraits<DerivativeValueType>::Zero ); } - this->GetMovingTransform()->ComputeJacobianWithRespectToParameters( virtualIt.Value(), jacobian ); + this->GetMovingTransform()-> + ComputeJacobianWithRespectToParametersCachedTemporaries(virtualIt.Value(), + jacobian, + jacobianPositional); for ( NumberOfParametersType par = 0; par < this->GetNumberOfLocalParameters(); par++ ) { for( DimensionType d = 0; d < PointDimension; ++d ) @@ -317,9 +321,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> this->m_Value = value; } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> SizeValueType -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::CalculateNumberOfValidFixedPoints() const { // Determine the number of valid fixed points, using @@ -337,9 +341,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> return numberOfValidPoints; } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::StorePointDerivative( const VirtualPointType & virtualPoint, const DerivativeType & pointDerivative, DerivativeType & field ) const { // Update derivative field at some index. @@ -365,10 +369,10 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } } -template<typename TFixedPointSet, typename TMovingPointSet> -typename PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +typename PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::LocalDerivativeType -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetLocalNeighborhoodDerivative( const PointType & point, const PixelType & pixel ) const { MeasureType measure; @@ -377,9 +381,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> return localDerivative; } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::TransformMovingPointSet() const { // Transform the moving point set with the moving transform. @@ -404,9 +408,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::TransformFixedAndCreateVirtualPointSet() const { // Transform the fixed point set through the virtual domain, and into the moving domain @@ -439,9 +443,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } } -template<typename TFixedPointSet, typename TMovingPointSet> -const typename PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet>::VirtualPointSetType * -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> +const typename PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType>::VirtualPointSetType * +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::GetVirtualTransformedPointSet( void ) const { // First make sure the virtual point set is current. @@ -449,9 +453,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> return this->m_VirtualTransformedPointSet.GetPointer(); } -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::InitializePointsLocators() const { if( this->m_FixedTransformPointLocatorsNeedInitialization ) @@ -484,9 +488,9 @@ PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> } /** PrintSelf */ -template<typename TFixedPointSet, typename TMovingPointSet> +template<typename TFixedPointSet, typename TMovingPointSet, class TInternalComputationValueType> void -PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet> +PointSetToPointSetMetricv4<TFixedPointSet, TMovingPointSet, TInternalComputationValueType> ::PrintSelf( std::ostream & os, Indent indent ) const { Superclass::PrintSelf( os, indent ); diff --git a/Utilities/ITK/Modules/Registration/Metricsv4/itk-module.cmake b/Utilities/ITK/Modules/Registration/Metricsv4/itk-module.cmake index 2da45b949985b3155933fbf4681b9d30e2e0ec98..5b52322e594cf069d1ed8d58066ab21c45213375 100644 --- a/Utilities/ITK/Modules/Registration/Metricsv4/itk-module.cmake +++ b/Utilities/ITK/Modules/Registration/Metricsv4/itk-module.cmake @@ -6,6 +6,7 @@ itk_module(ITKMetricsv4 ITKOptimizersv4 TEST_DEPENDS ITKTestKernel + ITKOptimizersv4 DESCRIPTION "${DOCUMENTATION}" ) diff --git a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkCurvatureRegistrationFilter.hxx b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkCurvatureRegistrationFilter.hxx index 2db11926d2fbb64562eb8005f5eac1a49c7a5760..275986892754e5e1f6b41ada1749ad4254e287b1 100644 --- a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkCurvatureRegistrationFilter.hxx +++ b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkCurvatureRegistrationFilter.hxx @@ -176,9 +176,9 @@ CurvatureRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField, TIma for ( unsigned int idx = 0; idx < m_FixedImageDimensions[dim]; ++idx ) { #ifdef SLOW_DCT - m_DiagonalElements[dim][idx] = -2 + 2 * vcl_cos(vnl_math::pi * idx / m_FixedImageDimensions[dim]); + m_DiagonalElements[dim][idx] = -2 + 2 * std::cos(vnl_math::pi * idx / m_FixedImageDimensions[dim]); #else - m_DiagonalElements[dim][idx] = -2 + 2 * vcl_cos(vnl_math::pi * ( idx + 1 ) / m_FixedImageDimensions[dim]); + m_DiagonalElements[dim][idx] = -2 + 2 * std::cos(vnl_math::pi * ( idx + 1 ) / m_FixedImageDimensions[dim]); #endif } } diff --git a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkDemonsRegistrationFunction.hxx b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkDemonsRegistrationFunction.hxx index bd8626166d7710f490a98b38ed13ce18b514543f..2ba6096cc439c2c5cfd09c20eafabf1cd8aca5dd 100644 --- a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkDemonsRegistrationFunction.hxx +++ b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkDemonsRegistrationFunction.hxx @@ -43,8 +43,8 @@ DemonsRegistrationFunction< TFixedImage, TMovingImage, TDisplacementField > m_TimeStep = 1.0; m_DenominatorThreshold = 1e-9; m_IntensityDifferenceThreshold = 0.001; - this->SetMovingImage(NULL); - this->SetFixedImage(NULL); + this->SetMovingImage(ITK_NULLPTR); + this->SetFixedImage(ITK_NULLPTR); //m_FixedImageSpacing.Fill( 1.0 ); //m_FixedImageOrigin.Fill( 0.0 ); m_Normalizer = 1.0; @@ -273,7 +273,7 @@ DemonsRegistrationFunction< TFixedImage, TMovingImage, TDisplacementField > { m_Metric = m_SumOfSquaredDifference / static_cast< double >( m_NumberOfPixelsProcessed ); - m_RMSChange = vcl_sqrt( m_SumOfSquaredChange + m_RMSChange = std::sqrt( m_SumOfSquaredChange / static_cast< double >( m_NumberOfPixelsProcessed ) ); } m_MetricCalculationLock.Unlock(); diff --git a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkFastSymmetricForcesDemonsRegistrationFunction.hxx b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkFastSymmetricForcesDemonsRegistrationFunction.hxx index 1a88293daa172f38551ab49fc9780d01227bb1b6..2056f534614ba6a1c4bd389c52ee75ac94630809 100644 --- a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkFastSymmetricForcesDemonsRegistrationFunction.hxx +++ b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkFastSymmetricForcesDemonsRegistrationFunction.hxx @@ -294,7 +294,7 @@ FastSymmetricForcesDemonsRegistrationFunction< TFixedImage, TMovingImage, TDispl { m_Metric = m_SumOfSquaredDifference / static_cast< double >( m_NumberOfPixelsProcessed ); - m_RMSChange = vcl_sqrt( m_SumOfSquaredChange + m_RMSChange = std::sqrt( m_SumOfSquaredChange / static_cast< double >( m_NumberOfPixelsProcessed ) ); } m_MetricCalculationLock.Unlock(); diff --git a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkLevelSetMotionRegistrationFunction.hxx b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkLevelSetMotionRegistrationFunction.hxx index efd08e462a98ec5f01229fe0bc0ef0703c46d356..e48d60775062455e2669abe0de3d46df2c8ea125 100644 --- a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkLevelSetMotionRegistrationFunction.hxx +++ b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkLevelSetMotionRegistrationFunction.hxx @@ -44,8 +44,8 @@ LevelSetMotionRegistrationFunction< TFixedImage, TMovingImage, TDisplacementFiel m_GradientMagnitudeThreshold = 1e-9; m_IntensityDifferenceThreshold = 0.001; m_GradientSmoothingStandardDeviations = 1.0; - this->SetMovingImage(NULL); - this->SetFixedImage(NULL); + this->SetMovingImage(ITK_NULLPTR); + this->SetFixedImage(ITK_NULLPTR); typename DefaultInterpolatorType::Pointer interp = DefaultInterpolatorType::New(); @@ -362,7 +362,7 @@ LevelSetMotionRegistrationFunction< TFixedImage, TMovingImage, TDisplacementFiel } gradientMagnitude += vnl_math_sqr(gradient[j]); } - gradientMagnitude = vcl_sqrt(gradientMagnitude); + gradientMagnitude = std::sqrt(gradientMagnitude); /** * Compute Update. @@ -451,7 +451,7 @@ LevelSetMotionRegistrationFunction< TFixedImage, TMovingImage, TDisplacementFiel { m_Metric = m_SumOfSquaredDifference / static_cast< double >( m_NumberOfPixelsProcessed ); - m_RMSChange = vcl_sqrt( m_SumOfSquaredChange + m_RMSChange = std::sqrt( m_SumOfSquaredChange / static_cast< double >( m_NumberOfPixelsProcessed ) ); } m_MetricCalculationLock.Unlock(); diff --git a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkMultiResolutionPDEDeformableRegistration.hxx b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkMultiResolutionPDEDeformableRegistration.hxx index 913c7890f76bf81cca470657cd54c0a8cc5757ac..735f5af8302cef2da903076b66fd9a4dc1d9055d 100644 --- a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkMultiResolutionPDEDeformableRegistration.hxx +++ b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkMultiResolutionPDEDeformableRegistration.hxx @@ -44,7 +44,7 @@ MultiResolutionPDEDeformableRegistration< TFixedImage, TMovingImage, TDisplaceme m_MovingImagePyramid = MovingImagePyramidType::New(); m_FixedImagePyramid = FixedImagePyramidType::New(); m_FieldExpander = FieldExpanderType::New(); - m_InitialDisplacementField = NULL; + m_InitialDisplacementField = ITK_NULLPTR; m_NumberOfLevels = 3; m_NumberOfIterations.SetSize(m_NumberOfLevels); @@ -262,7 +262,7 @@ MultiResolutionPDEDeformableRegistration< TFixedImage, TMovingImage, TDisplaceme unsigned int fixedLevel = vnl_math_min( (int)m_CurrentLevel, (int)m_FixedImagePyramid->GetNumberOfLevels() ); - DisplacementFieldPointer tempField = NULL; + DisplacementFieldPointer tempField = ITK_NULLPTR; DisplacementFieldPointer inputPtr = const_cast< DisplacementFieldType * >( this->GetInput(0) ); @@ -318,7 +318,7 @@ MultiResolutionPDEDeformableRegistration< TFixedImage, TMovingImage, TDisplaceme m_FieldExpander->SetOutputDirection( fi->GetDirection() ); m_FieldExpander->UpdateLargestPossibleRegion(); - m_FieldExpander->SetInput(NULL); + m_FieldExpander->SetInput(ITK_NULLPTR); tempField = m_FieldExpander->GetOutput(); tempField->DisconnectPipeline(); } @@ -329,7 +329,7 @@ MultiResolutionPDEDeformableRegistration< TFixedImage, TMovingImage, TDisplaceme { if ( tempField.IsNull() ) { - m_RegistrationFilter->SetInitialDisplacementField(NULL); + m_RegistrationFilter->SetInitialDisplacementField(ITK_NULLPTR); } else { @@ -348,7 +348,7 @@ MultiResolutionPDEDeformableRegistration< TFixedImage, TMovingImage, TDisplaceme m_FieldExpander->SetOutputDirection( fi->GetDirection() ); m_FieldExpander->UpdateLargestPossibleRegion(); - m_FieldExpander->SetInput(NULL); + m_FieldExpander->SetInput(ITK_NULLPTR); tempField = m_FieldExpander->GetOutput(); tempField->DisconnectPipeline(); @@ -386,7 +386,7 @@ MultiResolutionPDEDeformableRegistration< TFixedImage, TMovingImage, TDisplaceme (int)m_FixedImagePyramid->GetNumberOfLevels() ); // Invoke an iteration event. - this->InvokeEvent( IterationEvent() ); + this->InvokeEvent( MultiResolutionIterationEvent() ); // We can release data from pyramid which are no longer required. if ( movingLevel > 0 ) @@ -427,9 +427,9 @@ MultiResolutionPDEDeformableRegistration< TFixedImage, TMovingImage, TDisplaceme } // Release memory - m_FieldExpander->SetInput(NULL); + m_FieldExpander->SetInput(ITK_NULLPTR); m_FieldExpander->GetOutput()->ReleaseData(); - m_RegistrationFilter->SetInput(NULL); + m_RegistrationFilter->SetInput(ITK_NULLPTR); m_RegistrationFilter->GetOutput()->ReleaseData(); } diff --git a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkSymmetricForcesDemonsRegistrationFunction.hxx b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkSymmetricForcesDemonsRegistrationFunction.hxx index 32cca04b130cfa46b7f09095aa2b473f4cc3f1d3..92c6e0eb77300fd48e303640795b813f467da7ca 100644 --- a/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkSymmetricForcesDemonsRegistrationFunction.hxx +++ b/Utilities/ITK/Modules/Registration/PDEDeformable/include/itkSymmetricForcesDemonsRegistrationFunction.hxx @@ -39,8 +39,8 @@ SymmetricForcesDemonsRegistrationFunction< TFixedImage, TMovingImage, TDisplacem m_TimeStep = 1.0; m_DenominatorThreshold = 1e-9; m_IntensityDifferenceThreshold = 0.001; - this->SetMovingImage(NULL); - this->SetFixedImage(NULL); + this->SetMovingImage(ITK_NULLPTR); + this->SetFixedImage(ITK_NULLPTR); m_FixedImageSpacing.Fill(1.0); m_Normalizer = 0.0; m_FixedImageGradientCalculator = GradientCalculatorType::New(); @@ -317,7 +317,7 @@ SymmetricForcesDemonsRegistrationFunction< TFixedImage, TMovingImage, TDisplacem { m_Metric = m_SumOfSquaredDifference / static_cast< double >( m_NumberOfPixelsProcessed ); - m_RMSChange = vcl_sqrt( m_SumOfSquaredChange + m_RMSChange = std::sqrt( m_SumOfSquaredChange / static_cast< double >( m_NumberOfPixelsProcessed ) ); } m_MetricCalculationLock.Unlock(); diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkBSplineSyNImageRegistrationMethod.h b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkBSplineSyNImageRegistrationMethod.h index 8b510ba4f120271d80bd27ac07cf2a8a3d78a3f5..dbc1bafef69257ecfb5dbb6c59310b8d5f3b5300 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkBSplineSyNImageRegistrationMethod.h +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkBSplineSyNImageRegistrationMethod.h @@ -25,13 +25,6 @@ namespace itk { -//Forward-declare these because of module dependency conflict. -//They will soon be moved to a different module, at which -// time this can be removed. -template <unsigned int VDimension, typename TDataHolder> -class ImageToData; -template <typename TDataHolder> -class Array1DToData; /** \class BSplineSyNImageRegistrationMethod * \brief Interface method for the performing greedy B-spline SyN image registration. @@ -90,6 +83,7 @@ public: typedef typename Superclass::NumberOfIterationsArrayType NumberOfIterationsArrayType; + typedef typename Superclass::InitialTransformType InitialTransformType; typedef TOutputTransform OutputTransformType; typedef typename OutputTransformType::Pointer OutputTransformPointer; typedef typename OutputTransformType::ScalarType RealType; diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkBSplineSyNImageRegistrationMethod.hxx b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkBSplineSyNImageRegistrationMethod.hxx index 9084e7690ea09b8fc18af5f4e9392fc6a825d39a..1d435a23418dbdf61309e4076a3d70228b27c2c5 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkBSplineSyNImageRegistrationMethod.hxx +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkBSplineSyNImageRegistrationMethod.hxx @@ -79,7 +79,6 @@ BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> ::StartOptimization() { const DisplacementVectorType zeroVector( 0.0 ); - typedef ImageDuplicator<DisplacementFieldType> DisplacementFieldDuplicatorType; typename VirtualImageType::ConstPointer virtualDomainImage; typename MovingImageMaskType::ConstPointer movingImageMask; @@ -115,21 +114,22 @@ BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> } } + InitialTransformType* fixedInitialTransform = const_cast<InitialTransformType*>(this->GetFixedInitialTransform()); + // Monitor the convergence typedef itk::Function::WindowConvergenceMonitoringFunction<RealType> ConvergenceMonitoringType; typename ConvergenceMonitoringType::Pointer convergenceMonitoring = ConvergenceMonitoringType::New(); convergenceMonitoring->SetWindowSize( this->m_ConvergenceWindowSize ); - typedef IdentityTransform<RealType, ImageDimension> IdentityTransformType; - typename IdentityTransformType::Pointer identityTransform; - identityTransform = IdentityTransformType::New(); - IterationReporter reporter( this, 0, 1 ); while( this->m_CurrentIteration++ < this->m_NumberOfIterationsPerLevel[this->m_CurrentLevel] && !this->m_IsConverged ) { typename CompositeTransformType::Pointer fixedComposite = CompositeTransformType::New(); - fixedComposite->AddTransform( this->m_FixedInitialTransform ); + if ( fixedInitialTransform != ITK_NULLPTR ) + { + fixedComposite->AddTransform( fixedInitialTransform ); + } fixedComposite->AddTransform( this->m_FixedToMiddleTransform->GetInverseTransform() ); fixedComposite->FlattenTransformQueue(); fixedComposite->SetOnlyMostRecentTransformToOptimizeOn(); @@ -170,7 +170,7 @@ BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> fixedComposer->Update(); DisplacementFieldPointer fixedToMiddleSmoothTotalFieldTmp = this->BSplineSmoothDisplacementField( fixedComposer->GetOutput(), - this->m_FixedToMiddleTransform->GetNumberOfControlPointsForTheTotalField(), NULL ); + this->m_FixedToMiddleTransform->GetNumberOfControlPointsForTheTotalField(), ITK_NULLPTR ); typename ComposerType::Pointer movingComposer = ComposerType::New(); movingComposer->SetDisplacementField( movingToMiddleSmoothUpdateField ); @@ -178,7 +178,7 @@ BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> movingComposer->Update(); DisplacementFieldPointer movingToMiddleSmoothTotalFieldTmp = this->BSplineSmoothDisplacementField( movingComposer->GetOutput(), - this->m_MovingToMiddleTransform->GetNumberOfControlPointsForTheTotalField(), NULL ); + this->m_MovingToMiddleTransform->GetNumberOfControlPointsForTheTotalField(), ITK_NULLPTR ); // Iteratively estimate the inverse fields. @@ -384,7 +384,7 @@ BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> importer->SetDirection( virtualDomainImage->GetDirection() ); importer->Update(); - typename WeightedMaskImageType::Pointer weightedMask = NULL; + typename WeightedMaskImageType::Pointer weightedMask = ITK_NULLPTR; if( mask ) { @@ -424,7 +424,7 @@ BSplineSyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> { localNorm += vnl_math_sqr( vector[d] / spacing[d] ); } - localNorm = vcl_sqrt( localNorm ); + localNorm = std::sqrt( localNorm ); if( localNorm > maxNorm ) { diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkImageRegistrationMethodv4.h b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkImageRegistrationMethodv4.h index 2b1eda51b75f2adb55c90a42ce30f0da34e8af23..110bdf6a918a373094089c4e675f20b0f04e4e7c 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkImageRegistrationMethodv4.h +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkImageRegistrationMethodv4.h @@ -28,7 +28,7 @@ #include "itkImageToImageMetricv4.h" #include "itkShrinkImageFilter.h" #include "itkTransform.h" -#include "itkTransformParametersAdaptor.h" +#include "itkTransformParametersAdaptorBase.h" #include <vector> @@ -85,7 +85,10 @@ namespace itk * * \ingroup ITKRegistrationMethodsv4 */ -template<typename TFixedImage, typename TMovingImage, typename TOutputTransform, typename TVirtualImage = TFixedImage> +template<typename TFixedImage, + typename TMovingImage, + typename TOutputTransform=Transform<double, TFixedImage::ImageDimension, TFixedImage::ImageDimension >, + typename TVirtualImage = TFixedImage> class ImageRegistrationMethodv4 :public ProcessObject { @@ -140,6 +143,9 @@ public: */ typedef DataObjectDecorator<OutputTransformType> DecoratedOutputTransformType; typedef typename DecoratedOutputTransformType::Pointer DecoratedOutputTransformPointer; + typedef DataObjectDecorator<InitialTransformType> DecoratedInitialTransformType; + typedef typename DecoratedInitialTransformType::Pointer DecoratedInitialTransformPointer; + typedef ShrinkImageFilter<FixedImageType, VirtualImageType> ShrinkFilterType; typedef typename ShrinkFilterType::ShrinkFactorsType ShrinkFactorsPerDimensionContainerType; @@ -150,7 +156,7 @@ public: typedef Array<RealType> MetricSamplingPercentageArrayType; /** Transform adaptor typedefs */ - typedef TransformParametersAdaptor<OutputTransformType> TransformParametersAdaptorType; + typedef TransformParametersAdaptorBase<InitialTransformType> TransformParametersAdaptorType; typedef typename TransformParametersAdaptorType::Pointer TransformParametersAdaptorPointer; typedef std::vector<TransformParametersAdaptorPointer> TransformParametersAdaptorsContainerType; @@ -221,12 +227,27 @@ public: itkGetConstMacro( MetricSamplingPercentagePerLevel, MetricSamplingPercentageArrayType ); /** Set/Get the initial fixed transform. */ - itkSetObjectMacro( FixedInitialTransform, InitialTransformType ); - itkGetModifiableObjectMacro( FixedInitialTransform, InitialTransformType ); + itkSetGetDecoratedObjectInputMacro( FixedInitialTransform, InitialTransformType ); /** Set/Get the initial moving transform. */ - itkSetObjectMacro( MovingInitialTransform, InitialTransformType ); - itkGetModifiableObjectMacro( MovingInitialTransform, InitialTransformType ); + itkSetGetDecoratedObjectInputMacro( MovingInitialTransform, InitialTransformType ); + + /** Set/Get the initial transform to be optimized + * + * This transform is composed with the MovingInitialTransform to + * specify the initial transformation from the moving image to + * the virtual image. It is used for the default parameters, and can + * be use to specify the transform type. + * + * If the filter has "InPlace" set then this transform will be the + * output transform object or "grafted" to the output. Otherwise, + * this InitialTransform will be deep copied or "cloned" to the + * output. + * + * If this parameter is not set then a default constructed output + * transform is used. + */ + itkSetGetDecoratedObjectInputMacro(InitialTransform, InitialTransformType); /** Set/Get the transform adaptors. */ void SetTransformParametersAdaptorsPerLevel( TransformParametersAdaptorsContainerType & ); @@ -303,11 +324,18 @@ public: /** Make a DataObject of the correct type to be used as the specified output. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput( DataObjectPointerArraySizeType ); + virtual DataObjectPointer MakeOutput( DataObjectPointerArraySizeType ) ITK_OVERRIDE; /** Returns the transform resulting from the registration process */ + virtual DecoratedOutputTransformType * GetOutput(); virtual const DecoratedOutputTransformType * GetOutput() const; + virtual DecoratedOutputTransformType * GetTransformOutput() { return this->GetOutput(); } + virtual const DecoratedOutputTransformType * GetTransformOutput() const { return this->GetOutput(); } + + virtual OutputTransformType * GetModifiableTransform(); + virtual const OutputTransformType * GetTransform() const; + /** Get the current level. This is a helper function for reporting observations. */ itkGetConstMacro( CurrentLevel, SizeValueType ); @@ -323,6 +351,14 @@ public: /** Get the current convergence state per level. This is a helper function for reporting observations. */ itkGetConstReferenceMacro( IsConverged, bool ); + /** Request that the InitialTransform be grafted onto the output, + * there by not creating a copy. + */ + itkSetMacro(InPlace, bool); + itkGetConstMacro(InPlace, bool); + itkBooleanMacro(InPlace); + + #ifdef ITKV3_COMPATIBILITY /** Method that initiates the registration. This will Initialize and ensure * that all inputs the registration needs are in place, via a call to @@ -345,10 +381,12 @@ public: protected: ImageRegistrationMethodv4(); virtual ~ImageRegistrationMethodv4(); - virtual void PrintSelf( std::ostream & os, Indent indent ) const; + virtual void PrintSelf( std::ostream & os, Indent indent ) const ITK_OVERRIDE; /** Perform the registration. */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; + + virtual void AllocateOutputs(); /** Initialize by setting the interconnects between the components. */ virtual void InitializeRegistrationAtEachLevel( const SizeValueType ); @@ -380,18 +418,33 @@ protected: SmoothingSigmasArrayType m_SmoothingSigmasPerLevel; bool m_SmoothingSigmasAreSpecifiedInPhysicalUnits; - InitialTransformPointer m_MovingInitialTransform; - InitialTransformPointer m_FixedInitialTransform; - TransformParametersAdaptorsContainerType m_TransformParametersAdaptorsPerLevel; CompositeTransformPointer m_CompositeTransform; + //TODO: m_OutputTransform should be removed and replaced with a named input parameter for + // the pipeline --- Along with many other fixes OutputTransformPointer m_OutputTransform; + private: ImageRegistrationMethodv4( const Self & ); //purposely not implemented - void operator=( const Self & ); //purposely not implemented + void operator=( const Self & ); //purposely not implemented + + bool m_InPlace; + + // helper function to create the right kind of concrete transform + template<typename TTransform> + static void MakeOutputTransform(SmartPointer<TTransform> &ptr) + { + ptr = TTransform::New(); + } + + static void MakeOutputTransform(SmartPointer<InitialTransformType> &ptr) + { + ptr = itk::IdentityTransform<RealType, ImageDimension>::New().GetPointer(); + } + }; } // end namespace itk diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkImageRegistrationMethodv4.hxx b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkImageRegistrationMethodv4.hxx index bfd49358f3f367663ed3d4e9d89de7964ed1a88d..5e632c626d103861d46147a33976552710a22fef 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkImageRegistrationMethodv4.hxx +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkImageRegistrationMethodv4.hxx @@ -39,7 +39,21 @@ template<typename TFixedImage, typename TMovingImage, typename TTransform, typen ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> ::ImageRegistrationMethodv4() { - this->SetNumberOfRequiredOutputs( 1 ); + ProcessObject::SetNumberOfRequiredOutputs(1); + Self::SetPrimaryOutputName("Transform"); + + // indexed input are alternating fixed and moving images + Self::SetPrimaryInputName("Fixed"); + Self::AddRequiredInputName("Moving",1); + ProcessObject::SetNumberOfRequiredInputs(2); + + // optional named inputs + Self::SetInput("InitialTransform", ITK_NULLPTR); + Self::SetInput("FixedInitialTransform", ITK_NULLPTR); + Self::SetInput("MovingInitialTransform", ITK_NULLPTR); + + + Self::ReleaseDataBeforeUpdateFlagOff(); this->m_CurrentLevel = 0; this->m_CurrentIteration = 0; @@ -49,15 +63,11 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> this->m_NumberOfFixedImages = 0; this->m_NumberOfMovingImages = 0; - this->m_CompositeTransform = CompositeTransformType::New(); - - typedef IdentityTransform<RealType, ImageDimension> IdentityTransformType; + Self::ReleaseDataBeforeUpdateFlagOff(); - typename IdentityTransformType::Pointer defaultFixedInitialTransform = IdentityTransformType::New(); - this->m_FixedInitialTransform = defaultFixedInitialTransform; + this->m_InPlace = true; - typename IdentityTransformType::Pointer defaultMovingInitialTransform = IdentityTransformType::New(); - this->m_MovingInitialTransform = defaultMovingInitialTransform; + this->m_CompositeTransform = CompositeTransformType::New(); typedef MattesMutualInformationImageToImageMetricv4<FixedImageType, MovingImageType, VirtualImageType, RealType> DefaultMetricType; typename DefaultMetricType::Pointer mutualInformationMetric = DefaultMetricType::New(); @@ -82,11 +92,11 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> this->m_OptimizerWeights.SetSize( 0 ); this->m_OptimizerWeightsAreIdentity = true; - this->m_OutputTransform = OutputTransformType::New(); - DecoratedOutputTransformPointer transformDecorator = DecoratedOutputTransformType::New().GetPointer(); - transformDecorator->Set( this->m_OutputTransform ); + DecoratedOutputTransformPointer transformDecorator = + itkDynamicCastInDebugMode< DecoratedOutputTransformType * >( this->MakeOutput(0).GetPointer() ); this->ProcessObject::SetNthOutput( 0, transformDecorator ); + this->m_OutputTransform = transformDecorator->GetModifiable(); // By default we set up a 3-level image registration. @@ -200,7 +210,7 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> for( unsigned int i = 0; i < this->m_OptimizerWeights.Size(); i++ ) { OptimizerWeightsValueType difference = - vcl_fabs( NumericTraits<OptimizerWeightsValueType>::OneValue() - this->m_OptimizerWeights[i] ); + std::fabs( NumericTraits<OptimizerWeightsValueType>::OneValue() - this->m_OptimizerWeights[i] ); if( difference > tolerance ) { this->m_OptimizerWeightsAreIdentity = false; @@ -227,7 +237,7 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> itkExceptionMacro( "The number of fixed and moving images is not equal." ); } - SizeValueType numberOfImagePairs = static_cast<unsigned int>( 0.5 * this->GetNumberOfInputs() ); + SizeValueType numberOfImagePairs = static_cast<unsigned int>( 0.5 * this->GetNumberOfIndexedInputs() ); if( numberOfImagePairs == 0 ) { @@ -264,12 +274,15 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> itkExceptionMacro( "The image metric is not present." ); } + InitialTransformType* movingInitialTransform = const_cast<InitialTransformType*>(this->GetMovingInitialTransform()); + InitialTransformType* fixedInitialTransform = const_cast<InitialTransformType*>(this->GetFixedInitialTransform()); + this->m_CurrentIteration = 0; this->m_CurrentMetricValue = 0.0; this->m_CurrentConvergenceValue = 0.0; this->m_IsConverged = false; - this->InvokeEvent( InitializeEvent() ); + this->InvokeEvent( MultiResolutionIterationEvent() ); // For each level, we adapt the current transform. For many transforms, e.g. // affine, the base transform adaptor does not do anything. However, in the @@ -289,13 +302,22 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> { this->m_CompositeTransform->ClearTransformQueue(); - // If the moving initial transform is a composite transform, unroll - // it into m_CompositeTransform. This is a temporary fix to accommodate - // the lack of support for calculating the jacobian in the composite - // transform. + // Since we cannot instantiate a null object from an abstract class, we need to initialize the moving + // initial transform as an identity transform. + // Nevertheless, we do not need add this transform to the composite transform when it is only an + // identity transform. Simply by not setting that, we can save lots of time in jacobian computations + // of the composite transform since we can avoid some matrix multiplications. + + // Skip adding an IdentityTransform to the m_CompositeTransform + if( movingInitialTransform != ITK_NULLPTR && + std::string(movingInitialTransform->GetNameOfClass() ) != std::string("IdentityTransform") ) + { + this->m_CompositeTransform->AddTransform( movingInitialTransform ); + } - this->m_CompositeTransform->AddTransform( this->m_MovingInitialTransform ); this->m_CompositeTransform->AddTransform( this->m_OutputTransform ); + // If the moving initial transform is a composite transform, unroll + // it into m_CompositeTransform. this->m_CompositeTransform->FlattenTransformQueue(); if( this->m_OptimizerWeights.Size() > 0 ) @@ -317,7 +339,16 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> typename MultiMetricType::Pointer multiMetric2 = dynamic_cast<MultiMetricType *>( this->m_Metric.GetPointer() ); if( multiMetric2 ) { - multiMetric2->SetFixedTransform( this->m_FixedInitialTransform ); + if ( fixedInitialTransform ) + { + multiMetric2->SetFixedTransform( fixedInitialTransform ); + } + else + { + typedef IdentityTransform<RealType, ImageDimension> IdentityTransformType; + typename IdentityTransformType::Pointer defaultFixedInitialTransform = IdentityTransformType::New(); + multiMetric2->SetFixedTransform( defaultFixedInitialTransform ); + } multiMetric2->SetMovingTransform( this->m_CompositeTransform ); multiMetric2->SetVirtualDomainFromImage( shrinkFilter->GetOutput() ); for( unsigned int n = 0; n < multiMetric2->GetNumberOfMetrics(); n++ ) @@ -338,7 +369,16 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> typename ImageMetricType::Pointer imageMetric = dynamic_cast<ImageMetricType *>( this->m_Metric.GetPointer() ); if( imageMetric.IsNotNull() ) { - imageMetric->SetFixedTransform( this->m_FixedInitialTransform ); + if ( fixedInitialTransform ) + { + imageMetric->SetFixedTransform( fixedInitialTransform ); + } + else + { + typedef IdentityTransform<RealType, ImageDimension> IdentityTransformType; + typename IdentityTransformType::Pointer defaultFixedInitialTransform = IdentityTransformType::New(); + imageMetric->SetFixedTransform( defaultFixedInitialTransform ); + } imageMetric->SetMovingTransform( this->m_CompositeTransform ); imageMetric->SetVirtualDomainFromImage( shrinkFilter->GetOutput() ); } @@ -439,6 +479,80 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> } } + +template<typename TFixedImage, typename TMovingImage, typename TTransform, typename TVirtualImage> +void +ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> +::AllocateOutputs() +{ + const DecoratedInitialTransformType * decoratedInitialTransform = this->GetInitialTransformInput(); + DecoratedOutputTransformType *decoratedOutputTransform = this->GetOutput(); + + if ( decoratedInitialTransform ) + { + const InitialTransformType * initialTransform = decoratedInitialTransform->Get(); + + if ( initialTransform ) + { + if ( this->GetInPlace() ) + { + // graft the input to the output which may fail if the types + // aren't compatible. + decoratedOutputTransform->Graft( decoratedInitialTransform ); + + if ( decoratedOutputTransform->Get() ) + { + this->m_OutputTransform = decoratedOutputTransform->GetModifiable(); + + // This is generally done in the ReleaseInputs methods, + // however we do not need it again + const_cast<DecoratedInitialTransformType *>(decoratedInitialTransform)->ReleaseData(); + + // successful in-place grafting + itkDebugMacro("inplace allocation of output transform"); + return; + } + } + + const OutputTransformType * initialAsOutputTransform = dynamic_cast<const OutputTransformType*>( initialTransform ); + + if ( initialAsOutputTransform ) + { + // Clone performs a deep copy of the parameters and composition + this->m_OutputTransform = initialAsOutputTransform->Clone(); + decoratedOutputTransform->Set(this->m_OutputTransform); + + // successful deep copy from initial to output + itkDebugMacro("clone copy allocation of output transform"); + return; + } + else + { + itkExceptionMacro("Unable to convert InitialTransform input to the OutputTransform type"); + } + + } + } + + // fallback allocation and initialization + + + // initialize to identity? what happens if we re-run with optimized values? + itkDebugMacro("fallback allocation of output transform"); + + if ( !decoratedOutputTransform->Get() ) + { + // the output decorated component is null, allocate + OutputTransformPointer ptr; + Self::MakeOutputTransform(ptr); + decoratedOutputTransform->Set(ptr); + } + + this->m_OutputTransform = this->GetModifiableTransform(); + +} + + /* * Start the registration */ @@ -447,6 +561,7 @@ void ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> ::GenerateData() { + this->AllocateOutputs(); for( this->m_CurrentLevel = 0; this->m_CurrentLevel < this->m_NumberOfLevels; this->m_CurrentLevel++ ) { this->InitializeRegistrationAtEachLevel( this->m_CurrentLevel ); @@ -507,8 +622,7 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> this->m_TransformParametersAdaptorsPerLevel.clear(); for( SizeValueType level = 0; level < this->m_NumberOfLevels; level++ ) { - typename TransformParametersAdaptorType::Pointer transformParametersAdaptor = TransformParametersAdaptorType::New(); - this->m_TransformParametersAdaptorsPerLevel.push_back( transformParametersAdaptor.GetPointer() ); + this->m_TransformParametersAdaptorsPerLevel.push_back( ITK_NULLPTR ); } for( unsigned int level = 0; level < this->m_NumberOfLevels; ++level ) @@ -591,7 +705,7 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> { case REGULAR: { - const unsigned long sampleCount = static_cast<unsigned long>( vcl_ceil( 1.0 / this->m_MetricSamplingPercentagePerLevel[this->m_CurrentLevel] ) ); + const unsigned long sampleCount = static_cast<unsigned long>( std::ceil( 1.0 / this->m_MetricSamplingPercentagePerLevel[this->m_CurrentLevel] ) ); unsigned long count = sampleCount; //Start at sampleCount to keep behavior backwards identical, using first element. ImageRegionConstIteratorWithIndex<VirtualDomainImageType> It( virtualImage, virtualDomainRegion ); for( It.GoToBegin(); !It.IsAtEnd(); ++It ) @@ -663,8 +777,9 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> ::PrintSelf( std::ostream & os, Indent indent ) const { Superclass::PrintSelf( os, indent ); + Indent indent2 = indent.GetNextIndent(); - os << "Number of levels = " << this->m_NumberOfLevels << std::endl; + os << indent << "Number of levels = " << this->m_NumberOfLevels << std::endl; for( unsigned int level = 0; level < this->m_NumberOfLevels; ++level ) { @@ -675,11 +790,11 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> if( this->m_SmoothingSigmasAreSpecifiedInPhysicalUnits == true ) { - os << indent << indent << "Smoothing sigmas are specified in physical units." << std::endl; + os << indent2 << "Smoothing sigmas are specified in physical units." << std::endl; } else { - os << indent << indent << "Smoothing sigmas are specified in voxel units." << std::endl; + os << indent2 << "Smoothing sigmas are specified in voxel units." << std::endl; } if( this->m_OptimizerWeights.Size() > 0 ) @@ -695,11 +810,21 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> os << this->m_MetricSamplingPercentagePerLevel[i] << " "; } os << std::endl; + + os << indent << "InPlace: " << ( m_InPlace ? "On" : "Off" ) << std::endl; } /* * Get output transform */ +template<typename TFixedImage, typename TMovingImage, typename TTransform, typename TVirtualImage> +typename ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage>::DecoratedOutputTransformType * +ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> +::GetOutput() +{ + return static_cast<DecoratedOutputTransformType *>( this->ProcessObject::GetOutput( 0 ) ); +} + template<typename TFixedImage, typename TMovingImage, typename TTransform, typename TVirtualImage> const typename ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage>::DecoratedOutputTransformType * ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> @@ -708,6 +833,28 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> return static_cast<const DecoratedOutputTransformType *>( this->ProcessObject::GetOutput( 0 ) ); } +template<typename TFixedImage, typename TMovingImage, typename TTransform, typename TVirtualImage> +typename ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage>::OutputTransformType * +ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> +::GetModifiableTransform() +{ + DecoratedOutputTransformType * temp = this->GetOutput(); + // required outputs of process object should always exits + itkAssertInDebugAndIgnoreInReleaseMacro( temp != ITK_NULLPTR ); + return temp->GetModifiable(); +} + +template<typename TFixedImage, typename TMovingImage, typename TTransform, typename TVirtualImage> +const typename ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage>::OutputTransformType * +ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> +::GetTransform() const +{ + const DecoratedOutputTransformType * temp = this->GetOutput(); + // required outputs of process object should always exits + itkAssertInDebugAndIgnoreInReleaseMacro( temp != ITK_NULLPTR ); + return temp->Get(); +} + template<typename TFixedImage, typename TMovingImage, typename TTransform, typename TVirtualImage> DataObject::Pointer ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> @@ -716,11 +863,16 @@ ImageRegistrationMethodv4<TFixedImage, TMovingImage, TTransform, TVirtualImage> switch ( output ) { case 0: - return DecoratedOutputTransformType::New().GetPointer(); - break; + { + OutputTransformPointer ptr; + Self::MakeOutputTransform(ptr); + DecoratedOutputTransformPointer transformDecorator = DecoratedOutputTransformType::New(); + transformDecorator->Set( ptr ); + return transformDecorator.GetPointer(); + } default: itkExceptionMacro("MakeOutput request for an output number larger than the expected number of outputs"); - return 0; + return ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.h b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.h index dc430cdfdbd3d967ad9f364c250852fa6ee35ebd..64e86c3fc53c715939e3ee14c6b548e642d5ece4 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.h +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.h @@ -24,13 +24,6 @@ namespace itk { -//Forward-declare these because of module dependency conflict. -//They will soon be moved to a different module, at which -// time this can be removed. -template <unsigned int VDimension, typename TDataHolder> -class ImageToData; -template <typename TDataHolder> -class Array1DToData; /** \class SyNImageRegistrationMethod * \brief Interface method for the performing greedy SyN image registration. @@ -107,6 +100,7 @@ public: typedef typename ImageMetricType::FixedImageMaskType FixedImageMaskType; typedef typename ImageMetricType::MovingImageMaskType MovingImageMaskType; + typedef typename Superclass::InitialTransformType InitialTransformType; typedef TOutputTransform OutputTransformType; typedef typename OutputTransformType::Pointer OutputTransformPointer; typedef typename OutputTransformType::ScalarType RealType; diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.hxx b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.hxx index 1411eb67b6828eba343944ef7e5481359bc99154..99c8d221b1c93a68778d1d479d9895428dcae821 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.hxx +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkSyNImageRegistrationMethod.hxx @@ -130,7 +130,6 @@ SyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> ::StartOptimization() { const DisplacementVectorType zeroVector( 0.0 ); - typedef ImageDuplicator<DisplacementFieldType> DisplacementFieldDuplicatorType; typename VirtualImageType::ConstPointer virtualDomainImage; typename MultiMetricType::Pointer multiMetric = dynamic_cast<MultiMetricType *>( this->m_Metric.GetPointer() ); if( multiMetric ) @@ -142,21 +141,22 @@ SyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> virtualDomainImage = dynamic_cast<ImageMetricType *>( this->m_Metric.GetPointer() )->GetVirtualImage(); } + InitialTransformType* fixedInitialTransform = const_cast<InitialTransformType*>(this->GetFixedInitialTransform()); + // Monitor the convergence typedef itk::Function::WindowConvergenceMonitoringFunction<RealType> ConvergenceMonitoringType; typename ConvergenceMonitoringType::Pointer convergenceMonitoring = ConvergenceMonitoringType::New(); convergenceMonitoring->SetWindowSize( this->m_ConvergenceWindowSize ); - typedef IdentityTransform<RealType, ImageDimension> IdentityTransformType; - typename IdentityTransformType::Pointer identityTransform; - identityTransform = IdentityTransformType::New(); - IterationReporter reporter( this, 0, 1 ); while( this->m_CurrentIteration++ < this->m_NumberOfIterationsPerLevel[this->m_CurrentLevel] && !this->m_IsConverged ) { typename CompositeTransformType::Pointer fixedComposite = CompositeTransformType::New(); - fixedComposite->AddTransform( this->m_FixedInitialTransform ); + if ( fixedInitialTransform != ITK_NULLPTR ) + { + fixedComposite->AddTransform( fixedInitialTransform ); + } fixedComposite->AddTransform( this->m_FixedToMiddleTransform->GetInverseTransform() ); fixedComposite->FlattenTransformQueue(); fixedComposite->SetOnlyMostRecentTransformToOptimizeOn(); @@ -173,9 +173,9 @@ SyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> MeasureType movingMetricValue = 0.0; DisplacementFieldPointer fixedToMiddleSmoothUpdateField = this->ComputeUpdateField( - this->m_FixedSmoothImages, fixedComposite, this->m_MovingSmoothImages, movingComposite, NULL, movingMetricValue ); + this->m_FixedSmoothImages, fixedComposite, this->m_MovingSmoothImages, movingComposite, ITK_NULLPTR, movingMetricValue ); DisplacementFieldPointer movingToMiddleSmoothUpdateField = this->ComputeUpdateField( - this->m_MovingSmoothImages, movingComposite, this->m_FixedSmoothImages, fixedComposite, NULL, fixedMetricValue ); + this->m_MovingSmoothImages, movingComposite, this->m_FixedSmoothImages, fixedComposite, ITK_NULLPTR, fixedMetricValue ); if ( this->m_AverageMidPointGradients ) { @@ -406,7 +406,7 @@ SyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> { localNorm += vnl_math_sqr( vector[d] / spacing[d] ); } - localNorm = vcl_sqrt( localNorm ); + localNorm = std::sqrt( localNorm ); if( localNorm > maxNorm ) { @@ -550,6 +550,8 @@ void SyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> ::GenerateData() { + this->AllocateOutputs(); + for( this->m_CurrentLevel = 0; this->m_CurrentLevel < this->m_NumberOfLevels; this->m_CurrentLevel++ ) { this->InitializeRegistrationAtEachLevel( this->m_CurrentLevel ); @@ -580,9 +582,7 @@ SyNImageRegistrationMethod<TFixedImage, TMovingImage, TOutputTransform> this->m_OutputTransform->SetDisplacementField( composer->GetOutput() ); this->m_OutputTransform->SetInverseDisplacementField( inverseComposer->GetOutput() ); - DecoratedOutputTransformPointer transformDecorator = DecoratedOutputTransformType::New().GetPointer(); - transformDecorator->Set( this->m_OutputTransform ); - this->ProcessObject::SetNthOutput( 0, transformDecorator ); + this->GetTransformOutput()->Set(this->m_OutputTransform); } /* diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingBSplineVelocityFieldImageRegistrationMethod.h b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingBSplineVelocityFieldImageRegistrationMethod.h index b254cb1bf53d263cc11b1a02d41a05148cc06ffa..6bbd325de5f70f0fab82df6285ca4fd5c2b3cf03 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingBSplineVelocityFieldImageRegistrationMethod.h +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingBSplineVelocityFieldImageRegistrationMethod.h @@ -26,13 +26,6 @@ namespace itk { -//Forward-declare these because of module dependency conflict. -//They will soon be moved to a different module, at which -// time this can be removed. -template <unsigned int VDimension, typename TDataHolder> -class ImageToData; -template <typename TDataHolder> -class Array1DToData; /** \class TimeVaryingBSplineVelocityFieldImageRegistrationMethod * \brief Interface method for the current registration framework diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingBSplineVelocityFieldImageRegistrationMethod.hxx b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingBSplineVelocityFieldImageRegistrationMethod.hxx index 6d9d54dc09de117044c28754aa0067bad3981407..753ed95296527724571753c96d21a268b14fdce2 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingBSplineVelocityFieldImageRegistrationMethod.hxx +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingBSplineVelocityFieldImageRegistrationMethod.hxx @@ -153,7 +153,7 @@ TimeVaryingBSplineVelocityFieldImageRegistrationMethod<TFixedImage, TMovingImage this->m_OutputTransform->SetVelocityFieldSize( sampledVelocityFieldSize ); this->m_OutputTransform->IntegrateVelocityField(); - typename TimeVaryingWeightedMaskImageType::Pointer timeVaryingFixedWeightedMaskImage = NULL; + typename TimeVaryingWeightedMaskImageType::Pointer timeVaryingFixedWeightedMaskImage = ITK_NULLPTR; if( fixedImageMask ) { timeVaryingFixedWeightedMaskImage = TimeVaryingWeightedMaskImageType::New(); @@ -444,7 +444,7 @@ TimeVaryingBSplineVelocityFieldImageRegistrationMethod<TFixedImage, TMovingImage const typename VirtualImageType::IndexType virtualDomainIndex = virtualDomainImage->GetLargestPossibleRegion().GetIndex(); const typename VirtualImageType::SizeType virtualDomainSize = virtualDomainImage->GetLargestPossibleRegion().GetSize(); - typename MaskImageType::ConstPointer maskImage = NULL; + typename MaskImageType::ConstPointer maskImage = ITK_NULLPTR; if( fixedImageMask ) { typename ImageMaskSpatialObjectType::Pointer imageMask = dynamic_cast<ImageMaskSpatialObjectType *>( const_cast<FixedImageMaskType *>( fixedImageMask.GetPointer() ) ); @@ -559,7 +559,7 @@ TimeVaryingBSplineVelocityFieldImageRegistrationMethod<TFixedImage, TMovingImage TimeVaryingVelocityFieldControlPointLatticePointer updateControlPointLattice = bspliner->GetPhiLattice(); - TimeVaryingVelocityFieldPointer velocityField = NULL; + TimeVaryingVelocityFieldPointer velocityField = ITK_NULLPTR; if( this->GetDebug() ) { velocityField = bspliner->GetOutput(); @@ -581,6 +581,15 @@ TimeVaryingBSplineVelocityFieldImageRegistrationMethod<TFixedImage, TMovingImage if( this->m_CurrentConvergenceValue < this->m_ConvergenceThreshold ) { this->m_IsConverged = true; + } + + if( this->m_IsConverged || this->m_CurrentIteration >= this->m_NumberOfIterationsPerLevel[this->m_CurrentLevel] ) + { + + // Once we finish by convergence or exceeding number of iterations, + // we need to reset the transform by resetting the time bounds to the + // full range [0,1] and integrating the velocity field to get the + // forward and inverse displacement fields. this->m_OutputTransform->SetLowerTimeBound( 0 ); this->m_OutputTransform->SetUpperTimeBound( 1.0 ); @@ -637,6 +646,9 @@ void TimeVaryingBSplineVelocityFieldImageRegistrationMethod<TFixedImage, TMovingImage, TTransform> ::GenerateData() { + + this->AllocateOutputs(); + for( this->m_CurrentLevel = 0; this->m_CurrentLevel < this->m_NumberOfLevels; this->m_CurrentLevel++ ) { this->InitializeRegistrationAtEachLevel( this->m_CurrentLevel ); @@ -652,9 +664,7 @@ TimeVaryingBSplineVelocityFieldImageRegistrationMethod<TFixedImage, TMovingImage this->m_CompositeTransform->AddTransform( this->m_OutputTransform ); } - DecoratedOutputTransformPointer transformDecorator = DecoratedOutputTransformType::New().GetPointer(); - transformDecorator->Set( this->m_OutputTransform ); - this->ProcessObject::SetNthOutput( 0, transformDecorator ); + this->GetTransformOutput()->Set(this->m_OutputTransform); } /* diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingVelocityFieldImageRegistrationMethodv4.h b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingVelocityFieldImageRegistrationMethodv4.h index 1471e8be292163bbb2c564661f057a24b2fdbb7e..2c88a1c0de10de0607f032bb92c80b9f31bd0702 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingVelocityFieldImageRegistrationMethodv4.h +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingVelocityFieldImageRegistrationMethodv4.h @@ -25,14 +25,6 @@ namespace itk { -// Forward-declare these because of module dependency conflict. -// They will soon be moved to a different module, at which -// time this can be removed. -template <unsigned int VDimension, typename TDataHolder> -class ImageToData; -template <typename TDataHolder> -class Array1DToData; - /** \class TimeVaryingVelocityFieldImageRegistrationMethodv4 * \brief Interface method for the current registration framework * using the time varying velocity field transform. diff --git a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingVelocityFieldImageRegistrationMethodv4.hxx b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingVelocityFieldImageRegistrationMethodv4.hxx index 228d889eaaabd1c1b2492a5bbefb879f3867dbee..783cd8bb678ca1dfc2762beafdb92e68294ef6b9 100644 --- a/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingVelocityFieldImageRegistrationMethodv4.hxx +++ b/Utilities/ITK/Modules/Registration/RegistrationMethodsv4/include/itkTimeVaryingVelocityFieldImageRegistrationMethodv4.hxx @@ -334,6 +334,15 @@ TimeVaryingVelocityFieldImageRegistrationMethodv4<TFixedImage, TMovingImage, TOu if( this->m_CurrentConvergenceValue < this->m_ConvergenceThreshold ) { this->m_IsConverged = true; + } + + if( this->m_IsConverged || this->m_CurrentIteration >= this->m_NumberOfIterationsPerLevel[this->m_CurrentLevel] ) + { + + // Once we finish by convergence or exceeding number of iterations, + // we need to reset the transform by resetting the time bounds to the + // full range [0,1] and integrating the velocity field to get the + // forward and inverse displacement fields. this->m_OutputTransform->SetLowerTimeBound( 0 ); this->m_OutputTransform->SetUpperTimeBound( 1.0 ); @@ -390,6 +399,9 @@ void TimeVaryingVelocityFieldImageRegistrationMethodv4<TFixedImage, TMovingImage, TOutputTransform> ::GenerateData() { + + this->AllocateOutputs(); + for( this->m_CurrentLevel = 0; this->m_CurrentLevel < this->m_NumberOfLevels; this->m_CurrentLevel++ ) { this->InitializeRegistrationAtEachLevel( this->m_CurrentLevel ); @@ -405,9 +417,7 @@ TimeVaryingVelocityFieldImageRegistrationMethodv4<TFixedImage, TMovingImage, TOu this->m_CompositeTransform->AddTransform( this->m_OutputTransform ); } - DecoratedOutputTransformPointer transformDecorator = DecoratedOutputTransformType::New().GetPointer(); - transformDecorator->Set( this->m_OutputTransform ); - this->ProcessObject::SetNthOutput( 0, transformDecorator ); + this->GetTransformOutput()->Set(this->m_OutputTransform); } /* diff --git a/Utilities/ITK/Modules/Remote/AnalyzeObjectMapIO.remote.cmake b/Utilities/ITK/Modules/Remote/AnalyzeObjectMapIO.remote.cmake new file mode 100644 index 0000000000000000000000000000000000000000..372a4920de2b9f58ede73395a374f08597c871b0 --- /dev/null +++ b/Utilities/ITK/Modules/Remote/AnalyzeObjectMapIO.remote.cmake @@ -0,0 +1,5 @@ +itk_fetch_module(AnalyzeObjectMapIO + "AnalyzeObjectMapIO plugin for ITK. From Insight Journal article with handle: http://hdl.handle.net/1926/593" + GIT_REPOSITORY https://github.com/InsightSoftwareConsortium/itkAnalyzeObjectMap.git + GIT_TAG ea14a5547de995c3f2c7f10948a3df2091de3034 + ) diff --git a/Utilities/ITK/Modules/Remote/FDFImageIO.remote.cmake b/Utilities/ITK/Modules/Remote/FDFImageIO.remote.cmake new file mode 100644 index 0000000000000000000000000000000000000000..cb7f2badc514ab2e8c0d58abfb9571d4ef5eab04 --- /dev/null +++ b/Utilities/ITK/Modules/Remote/FDFImageIO.remote.cmake @@ -0,0 +1,5 @@ +itk_fetch_module(FDFImageIO + "FDFImageIO plugin for ITK. Authors Gleen Pierce/Nick Tustison/Kent Williams" + GIT_REPOSITORY http://github.com/InsightSoftwareConsortium/itkFDFImageIO.git + GIT_TAG df4888e4f843c18605da1229c28553933994ddbd + ) diff --git a/Utilities/ITK/Modules/Remote/IOSTL.remote.cmake b/Utilities/ITK/Modules/Remote/IOSTL.remote.cmake new file mode 100644 index 0000000000000000000000000000000000000000..aa4cc21c08a5befbf536b1dadc4484026d880de8 --- /dev/null +++ b/Utilities/ITK/Modules/Remote/IOSTL.remote.cmake @@ -0,0 +1,7 @@ +# Contact: Luis Ibanez <luis.ibanez@kitware.com> +itk_fetch_module(IOSTL + "This module contains classes for reading and writing QuadEdgeMeshes using + the STL (STereoLithography)file format. http://hdl.handle.net/10380/3452" + GIT_REPOSITORY https://github.com/InsightSoftwareConsortium/ITKSTLMeshIO.git + GIT_TAG 933359a5fd1bac792a3c0af5f4e05e291e153677 + ) diff --git a/Utilities/ITK/Modules/Remote/LesionSizingToolkit.remote.cmake b/Utilities/ITK/Modules/Remote/LesionSizingToolkit.remote.cmake index a3e431b74deb5199a94b1a58282a3052e78b33b3..0bbdc44842c6ecf1c05b9951a562ab7ef63f08a4 100644 --- a/Utilities/ITK/Modules/Remote/LesionSizingToolkit.remote.cmake +++ b/Utilities/ITK/Modules/Remote/LesionSizingToolkit.remote.cmake @@ -1,5 +1,5 @@ itk_fetch_module(LesionSizingToolkit "Framework for determining the sizes of lesions in medical images." GIT_REPOSITORY http://public.kitware.com/LesionSizingToolkit.git - GIT_TAG c03168c0ff69386d7f59b00b46875273852068c7 + GIT_TAG fd9cfcef3bb4f7678bc50ecbe6ad51c6998cc3db ) diff --git a/Utilities/ITK/Modules/Remote/MGHIO.remote.cmake b/Utilities/ITK/Modules/Remote/MGHIO.remote.cmake index fb52f58d982e9c8dcd57f1fd9b1791106d86baf7..e0a050cce5aeb6557b748db686552d2444a22dc6 100644 --- a/Utilities/ITK/Modules/Remote/MGHIO.remote.cmake +++ b/Utilities/ITK/Modules/Remote/MGHIO.remote.cmake @@ -1,5 +1,5 @@ itk_fetch_module(MGHIO "MGHIO ImageIO plugin for ITK" GIT_REPOSITORY https://github.com/Slicer/itkMGHImageIO.git - GIT_TAG d43fc18d3023a8eba2bdc50cae8adf1f77160c67 + GIT_TAG f4e475c47f5c246b1ebf0529e052f65b73c7d13d ) diff --git a/Utilities/ITK/Modules/Remote/SCIFIO.remote.cmake b/Utilities/ITK/Modules/Remote/SCIFIO.remote.cmake index 52fd2b606806a7eaf3b85374594952cf37960336..5dde18d49586a36afffa3beb078dd2b4f8cf95cd 100644 --- a/Utilities/ITK/Modules/Remote/SCIFIO.remote.cmake +++ b/Utilities/ITK/Modules/Remote/SCIFIO.remote.cmake @@ -1,5 +1,5 @@ itk_fetch_module(SCIFIO "SCIFIO (Bioformats) ImageIO plugin for ITK" GIT_REPOSITORY https://github.com/scifio/scifio-imageio.git - GIT_TAG 3e76055918e70c8e97730d1e321ec59f15007f4c + GIT_TAG da6edd6bcefd8f107a3ed34ed663bfc69b3dc167 ) diff --git a/Utilities/ITK/Modules/Remote/SkullStrip.remote.cmake b/Utilities/ITK/Modules/Remote/SkullStrip.remote.cmake new file mode 100644 index 0000000000000000000000000000000000000000..11ed169838dde00d26a9583213be86426233ebba --- /dev/null +++ b/Utilities/ITK/Modules/Remote/SkullStrip.remote.cmake @@ -0,0 +1,5 @@ +itk_fetch_module(SkullStrip + "A class to perform automatic skull-stripping for neuroimage analysis." + GIT_REPOSITORY https://github.com/lorensen/skullStrip.git + GIT_TAG master + ) diff --git a/Utilities/ITK/Modules/Remote/SmoothingRecursiveYvvGaussianFilter.remote.cmake b/Utilities/ITK/Modules/Remote/SmoothingRecursiveYvvGaussianFilter.remote.cmake index 36929416ff8200fabaef0f024f9385b336e49e35..957c71bc7b91f69ebfe9990bb7f63a895b4d2b12 100644 --- a/Utilities/ITK/Modules/Remote/SmoothingRecursiveYvvGaussianFilter.remote.cmake +++ b/Utilities/ITK/Modules/Remote/SmoothingRecursiveYvvGaussianFilter.remote.cmake @@ -2,5 +2,5 @@ itk_fetch_module(SmoothingRecursiveYvvGaussianFilter "GPU and CPU Young & Van Vliet Recursive Gaussian Smoothing Filter: http://hdl.handle.net/10380/3425" GIT_REPOSITORY https://github.com/Inria-Asclepios/SmoothingRecursiveYvvGaussianFilter - GIT_TAG d66cc15f97f98a6ecbf6e6ef8a5b52615ffb883e + GIT_TAG b3b6cab4848b4ad88b31384ada303ea2eeb663e4 ) diff --git a/Utilities/ITK/Modules/Remote/SphinxExamples.remote.cmake b/Utilities/ITK/Modules/Remote/SphinxExamples.remote.cmake new file mode 100644 index 0000000000000000000000000000000000000000..82e4839cb1f7032cb7bd8037e9eab4e49981595b --- /dev/null +++ b/Utilities/ITK/Modules/Remote/SphinxExamples.remote.cmake @@ -0,0 +1,7 @@ +# Contact: Matt McCormick <matt.mccormick@kitware.com> +itk_fetch_module(SphinxExamples + "This module builds the examples found at http://itk.org/ITKExamples/" + GIT_REPOSITORY http://itk.org/ITKExamples.git + # 2014-06-19 + GIT_TAG e256071ab7e813fc5c8c3875d591c8625e766fd1 + ) diff --git a/Utilities/ITK/Modules/Remote/SplitComponents.remote.cmake b/Utilities/ITK/Modules/Remote/SplitComponents.remote.cmake new file mode 100644 index 0000000000000000000000000000000000000000..d618b3199a3938ea8655ea45ecc281a4b09bba86 --- /dev/null +++ b/Utilities/ITK/Modules/Remote/SplitComponents.remote.cmake @@ -0,0 +1,9 @@ +# Contact: Matt McCormick <matt.mccormick@kitware.com> +itk_fetch_module(SplitComponents +"This module contains filter called +itk::SplitComponentsImageFilter. This filter generates component images from an +itk::Image of, for example, itk::Vector, itk::CovariantVector, or +itk::SymmetricSecondRankTensor. http://hdl.handle.net/10380/3230" + GIT_REPOSITORY https://github.com/thewtex/ITKSplitComponents/ + GIT_TAG 9747f758d63ba957923c268123b1124e4e2cb075 + ) diff --git a/Utilities/ITK/Modules/Remote/VariationalRegistration.remote.cmake b/Utilities/ITK/Modules/Remote/VariationalRegistration.remote.cmake new file mode 100644 index 0000000000000000000000000000000000000000..26b7eba790d35228fb851df8125ed7d6d687126f --- /dev/null +++ b/Utilities/ITK/Modules/Remote/VariationalRegistration.remote.cmake @@ -0,0 +1,9 @@ +# Insight Journal Handle: http://hdl.handle.net/10380/3460 +# Contact: Alexander Schmidt-Richberg <a.schmidt-richberg@imperial.ac.uk> +# Jan Ehrhardt <ehrhardt@imi.uni-luebeck.de> +# Rene Werner <r.werner@uke.de> +itk_fetch_module(VariationalRegistration + "A module to perform variational image registration. http://hdl.handle.net/10380/3460" + GIT_REPOSITORY https://github.com/VariationalRegistration/VariationalRegistration.git + GIT_TAG bd3ae2f8a37f76dc1700e7369e8edb03c31ff6dd + ) diff --git a/Utilities/ITK/Modules/Remote/WikiExamples.remote.cmake b/Utilities/ITK/Modules/Remote/WikiExamples.remote.cmake new file mode 100644 index 0000000000000000000000000000000000000000..ba1eed7686b5fb5d72c9e2b70ed336f7eb7ff059 --- /dev/null +++ b/Utilities/ITK/Modules/Remote/WikiExamples.remote.cmake @@ -0,0 +1,13 @@ +# +# ITK WikiExamples +# This remote module require a VTK build +# The following CMake variable must be set for the ITK build +# +# Check for requires cmake variables + +itk_fetch_module(WikiExamples + "A collection of examples that illustrate how to use ITK." + GIT_REPOSITORY https://github.com/InsightSoftwareConsortium/ITKWikiExamples.git +# June 17, 2014 + GIT_TAG 3d2213fb7475adbd1522f0e3a5e1747aa4dfe4f4 + ) diff --git a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCell.h b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCell.h index e33de4f3c7ab28cc7131283e24c54a32b0e0471e..b939079500e478709c708112242c22a5d7f869e5 100644 --- a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCell.h +++ b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCell.h @@ -56,7 +56,7 @@ public: virtual void Mitosis(void); - virtual void Apoptosis(void); + virtual void Apoptosis(void) ITK_OVERRIDE; virtual void ReceptorsReading(void); diff --git a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCell.hxx b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCell.hxx index e3693e13fc81ad8147ad641a25cf7b2186a93617..968655dc0049f0d7124ed6593657f759f173a633 100644 --- a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCell.hxx +++ b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCell.hxx @@ -32,7 +32,8 @@ namespace bio */ template< unsigned int NSpaceDimension > Cell< NSpaceDimension > -::Cell() +::Cell() : + m_Aggregate(ITK_NULLPTR) { m_Force.Fill(0.0f); @@ -64,8 +65,8 @@ Cell< NSpaceDimension > // Broad compensation for Volume distribution among daugthers. // The type of root should depend on the Dimension... - siblingA->m_Radius = m_Radius / vcl_sqrt(2.0f); - siblingB->m_Radius = m_Radius / vcl_sqrt(2.0f); + siblingA->m_Radius = m_Radius / std::sqrt(2.0f); + siblingB->m_Radius = m_Radius / std::sqrt(2.0f); // Update Teleomeres siblingA->m_Generation = m_Generation + 1; @@ -85,8 +86,8 @@ Cell< NSpaceDimension > siblingB->m_Genome = m_GenomeCopy; // Mark that the genome pointer is not owned by this cell anymore. - m_Genome = NULL; - m_GenomeCopy = NULL; + m_Genome = ITK_NULLPTR; + m_GenomeCopy = ITK_NULLPTR; // Register both daughter cells with the CellularAggregate. CellularAggregateBase *aggregate = this->GetCellularAggregate(); @@ -188,7 +189,7 @@ Cell< NSpaceDimension > if ( m_ChemoAttractantLevel > ChemoAttractantLowThreshold && m_ChemoAttractantLevel < ChemoAttractantHighThreshold ) { - double factor = 1.0 / vcl_pow( m_Radius, (double)( NSpaceDimension ) ); + double factor = 1.0 / std::pow( m_Radius, (double)( NSpaceDimension ) ); m_Force += force; m_Pressure += force.GetNorm() * factor; } diff --git a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregate.h b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregate.h index 63b67d04ffce29afb8bf3f3c901b66e704df5811..9b5b34cef9f48ec5472c135c1b3c64bf42b89cfc 100644 --- a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregate.h +++ b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregate.h @@ -128,9 +128,9 @@ public: virtual void Add(CellBase *cell, const VectorType & perturbation); - virtual void Add(CellBase *cellA, CellBase *cellB, double perturbationLength); + virtual void Add(CellBase *cellA, CellBase *cellB, double perturbationLength) ITK_OVERRIDE; - virtual void Remove(CellBase *cell); + virtual void Remove(CellBase *cell) ITK_OVERRIDE; virtual void GetVoronoi(IdentifierType cellId, VoronoiRegionAutoPointer &) const; @@ -141,7 +141,7 @@ public: virtual SubstratesVector & GetSubstrates(void); virtual SubstrateValueType GetSubstrateValue(IdentifierType cellId, - unsigned int substrateId) const; + unsigned int substrateId) const ITK_OVERRIDE; virtual void KillAll(void); @@ -151,7 +151,7 @@ protected: CellularAggregate(const Self &); void operator=(const Self &); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; virtual void ComputeForces(void); diff --git a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregate.hxx b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregate.hxx index 2b215e89503cd62c2d10400861acec7864c81e1f..feff31c9c8612914d7f15f4ef0e355d360cc4e32 100644 --- a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregate.hxx +++ b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregate.hxx @@ -453,7 +453,7 @@ CellularAggregate< NSpaceDimension > { const IdentifierType cell2Id = ( *neighbor ); - BioCellType *cell2 = 0; + BioCellType *cell2 = ITK_NULLPTR; PointType position2; if ( !m_Mesh->GetPoint(cell2Id, &position2) ) @@ -506,7 +506,7 @@ CellularAggregate< NSpaceDimension > PointsConstIterator point2It = beginPoints; - BioCellType *cell1 = 0; + BioCellType *cell1 = ITK_NULLPTR; IdentifierType cell1Id = point1It.Index(); m_Mesh->GetPointData(cell1Id, &cell1); @@ -627,7 +627,6 @@ CellularAggregate< NSpaceDimension > SubstratePointer substrate = m_Substrates[substrateId]; typename SubstrateType::IndexType index; - typedef typename SubstrateType::IndexType::IndexValueType IndexValueType; substrate->TransformPhysicalPointToIndex(cellPosition, index); diff --git a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregateBase.h b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregateBase.h index 9dcadafdb97a69704f07115fda45296b98195f27..bb09d23a329a2d67f16be7b1be58c2211ef82347 100644 --- a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregateBase.h +++ b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioCellularAggregateBase.h @@ -66,7 +66,7 @@ protected: CellularAggregateBase(); virtual ~CellularAggregateBase(); CellularAggregateBase(const Self &); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; }; } // end namespace bio } // end namespace itk diff --git a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioGenome.h b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioGenome.h index 58a838e94819fba303f8674d1f03e821b5784948..832b983e5d0b5e325619487715f12a5e770cb93c 100644 --- a/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioGenome.h +++ b/Utilities/ITK/Modules/Segmentation/BioCell/include/itkBioGenome.h @@ -26,7 +26,7 @@ #include <map> #include <string> -#include "vcl_cmath.h" +#include <cmath> namespace itk { @@ -65,7 +65,7 @@ public: * be used for gene network computations. */ static double Sigmoide(double threshold, double slant, double value) { - return vcl_atan( ( value - threshold ) / slant ) / 3.1416 + 0.5001; + return std::atan( ( value - threshold ) / slant ) / 3.1416 + 0.5001; } private: diff --git a/Utilities/ITK/Modules/Segmentation/BioCell/src/itkBioCellBase.cxx b/Utilities/ITK/Modules/Segmentation/BioCell/src/itkBioCellBase.cxx index d38fdfe6229087dbf73812301e85edb4edf57d65..9bffe94c4fa29ab7b2cf0248b62e317bf8c65c21 100644 --- a/Utilities/ITK/Modules/Segmentation/BioCell/src/itkBioCellBase.cxx +++ b/Utilities/ITK/Modules/Segmentation/BioCell/src/itkBioCellBase.cxx @@ -64,8 +64,8 @@ CellBase::ColorType CellBase:: StarvingColor; CellBase ::CellBase() { - m_Genome = NULL; - m_GenomeCopy = NULL; + m_Genome = ITK_NULLPTR; + m_GenomeCopy = ITK_NULLPTR; m_Radius = DefaultRadius; m_Color = DefaultColor; @@ -107,9 +107,9 @@ CellBase ::~CellBase() { delete m_Genome; - m_Genome = NULL; + m_Genome = ITK_NULLPTR; delete m_GenomeCopy; - m_GenomeCopy = NULL; + m_GenomeCopy = ITK_NULLPTR; } /** @@ -132,9 +132,9 @@ CellBase ::Apoptosis(void) { delete m_Genome; - m_Genome = NULL; + m_Genome = ITK_NULLPTR; delete m_GenomeCopy; - m_GenomeCopy = NULL; + m_GenomeCopy = ITK_NULLPTR; } /** diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkBayesianClassifierImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkBayesianClassifierImageFilter.hxx index 2a331954958dbcbc2f9b0b87d286b09c30547d24..4d96cdbf31541dd79ecf3bb6e53e4dff2bee001a 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkBayesianClassifierImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkBayesianClassifierImageFilter.hxx @@ -46,7 +46,7 @@ BayesianClassifierImageFilter< TInputVectorImage, TLabelsType, m_UserProvidedSmoothingFilter = false; this->SetNumberOfRequiredOutputs(2); m_NumberOfSmoothingIterations = 0; - m_SmoothingFilter = NULL; + m_SmoothingFilter = ITK_NULLPTR; PosteriorsImagePointer p = static_cast< PosteriorsImageType * >( this->MakeOutput(1).GetPointer() ); this->SetNthOutput( 1, p.GetPointer() ); @@ -174,7 +174,7 @@ BayesianClassifierImageFilter< TInputVectorImage, TLabelsType, const PriorsImageType *priorsImage = dynamic_cast< const PriorsImageType * >( this->GetInput(1) ); - if ( priorsImage == NULL ) + if ( priorsImage == ITK_NULLPTR ) { itkExceptionMacro("Second input type does not correspond to expected Priors Image Type"); } @@ -182,7 +182,7 @@ BayesianClassifierImageFilter< TInputVectorImage, TLabelsType, PosteriorsImageType *posteriorsImage = dynamic_cast< PosteriorsImageType * >( this->GetPosteriorImage() ); - if ( posteriorsImage == NULL ) + if ( posteriorsImage == ITK_NULLPTR ) { itkExceptionMacro("Second output type does not correspond to expected Posteriors Image Type"); } @@ -219,7 +219,7 @@ BayesianClassifierImageFilter< TInputVectorImage, TLabelsType, PosteriorsImageType *posteriorsImage = dynamic_cast< PosteriorsImageType * >( this->GetPosteriorImage() ); - if ( posteriorsImage == NULL ) + if ( posteriorsImage == ITK_NULLPTR ) { itkExceptionMacro("Second output type does not correspond to expected Posteriors Image Type"); } @@ -365,7 +365,7 @@ BayesianClassifierImageFilter< TInputVectorImage, TLabelsType, PosteriorsImageType *posteriorsImage = dynamic_cast< PosteriorsImageType * >( this->GetPosteriorImage() ); - if ( posteriorsImage == NULL ) + if ( posteriorsImage == ITK_NULLPTR ) { itkExceptionMacro("Second output type does not correspond to expected Posteriors Image Type"); } diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkBayesianClassifierInitializationImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkBayesianClassifierInitializationImageFilter.hxx index 922b180977f65d00caa3e3f2331f3557e0827308..89e6c5328776ce90c24a02a5adb328aa6e8fd50f 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkBayesianClassifierInitializationImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkBayesianClassifierInitializationImageFilter.hxx @@ -41,7 +41,7 @@ BayesianClassifierInitializationImageFilter< TInputImage, TProbabilityPrecisionT m_UserSuppliesMembershipFunctions(false), m_NumberOfClasses(0) { - m_MembershipFunctionContainer = NULL; + m_MembershipFunctionContainer = ITK_NULLPTR; } // GenerateOutputInformation method. Here we force update on the entire input diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkClassifierBase.h b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkClassifierBase.h index 6bdb8419bc8faf40fa15ff85dad418b18166dd4d..970e0e5c7710207f5469349ae8bc678dcbfa2947 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkClassifierBase.h +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkClassifierBase.h @@ -150,7 +150,7 @@ public: protected: ClassifierBase(); ~ClassifierBase(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** The real classification logic implementaion. All the subclasses * of this class should implement this method. */ diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkClassifierBase.hxx b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkClassifierBase.hxx index fc20a1cf1f026e335cc7547fe3696ec19fcdee3a..78552007f3e56555214df4bca8bbc11f8bc32527 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkClassifierBase.hxx +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkClassifierBase.hxx @@ -28,7 +28,7 @@ ClassifierBase< TDataContainer > ::ClassifierBase() { m_NumberOfClasses = 0; - m_DecisionRule = 0; + m_DecisionRule = ITK_NULLPTR; m_MembershipFunctions.resize(0); } diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageClassifierBase.hxx b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageClassifierBase.hxx index b3696c40ae40da80eac90bd7a6c3bb7623e374f2..a8e4ab3e799f0a35a09887a04dce9c8b0903fe29 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageClassifierBase.hxx +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageClassifierBase.hxx @@ -161,7 +161,6 @@ ImageClassifierBase< TInputImage, TClassifiedImage > this->SetClassifiedImage(classifiedImage); - typedef typename TClassifiedImage::IndexType myIndex; typename TClassifiedImage::IndexType classifiedImageIndex; classifiedImageIndex.Fill(0); diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageGaussianModelEstimator.hxx b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageGaussianModelEstimator.hxx index 00a4f87bb43fd43cfcc9473e6daccd03c7129004..fbbe2048a9fff214c897ae05dbb0134335183010 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageGaussianModelEstimator.hxx +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageGaussianModelEstimator.hxx @@ -26,7 +26,7 @@ template< typename TInputImage, typename TTrainingImage > ImageGaussianModelEstimator< TInputImage, TMembershipFunction, TTrainingImage > ::ImageGaussianModelEstimator(void): - m_Covariance(NULL) + m_Covariance(ITK_NULLPTR) {} template< typename TInputImage, diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageKmeansModelEstimator.hxx b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageKmeansModelEstimator.hxx index 87ff6a32c7b2c9442f7c57c5ec64d3e0161221a2..47f997ed1d843b678e470a8eed63941f44365e4b 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageKmeansModelEstimator.hxx +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageKmeansModelEstimator.hxx @@ -615,12 +615,12 @@ ImageKmeansModelEstimator< TInputImage, TMembershipFunction > double muloffset; double rand_num; - addoffset = m_OffsetAdd / vcl_pow(2.0, (double)scale); - muloffset = m_OffsetMultiply / vcl_pow(2.0, (double)scale); + addoffset = m_OffsetAdd / std::pow(2.0, (double)scale); + muloffset = m_OffsetMultiply / std::pow(2.0, (double)scale); for ( i = 0; i < m_VectorDimension; i++ ) { - srand( (unsigned)time(NULL) ); + srand( (unsigned)time(ITK_NULLPTR) ); rand_num = ( rand() ) / ( (double)RAND_MAX ); if ( oldCodeword[i] == 0.0 ) @@ -628,7 +628,7 @@ ImageKmeansModelEstimator< TInputImage, TMembershipFunction > newCodeword[i] = addoffset * rand_num; } - else if ( vcl_fabs(oldCodeword[i]) < 0.9 * addoffset ) + else if ( std::fabs(oldCodeword[i]) < 0.9 * addoffset ) { newCodeword[i] = oldCodeword[i]; diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageModelEstimatorBase.h b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageModelEstimatorBase.h index 279365064d125bd72af7fa2c468bf5671a45bc31..8a875df94b40b44ed82d1f86f220f2f34cdb935f 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageModelEstimatorBase.h +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkImageModelEstimatorBase.h @@ -131,9 +131,9 @@ public: protected: ImageModelEstimatorBase(); ~ImageModelEstimatorBase(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkScalarImageKmeansImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkScalarImageKmeansImageFilter.hxx index 448fffdb9ad1b631ba0fe1de135d60eb3be24d77..b62285d0e53b8f81097c1bcf00475ee7e3875434 100644 --- a/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkScalarImageKmeansImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/Classifiers/include/itkScalarImageKmeansImageFilter.hxx @@ -106,7 +106,6 @@ ScalarImageKmeansImageFilter< TInputImage, TOutputImage > this->m_FinalMeans = estimator->GetParameters(); typedef typename InputImageType::RegionType RegionType; - typedef typename InputImageType::SizeType SizeType; // Now classify the samples DecisionRuleType::Pointer decisionRule = DecisionRuleType::New(); diff --git a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkConnectedComponentFunctorImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkConnectedComponentFunctorImageFilter.hxx index a41965998d4a728dd6bbd41ff00e4812143c644b..053068ac0967cab82158b87471cad86fdb3e16e3 100644 --- a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkConnectedComponentFunctorImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkConnectedComponentFunctorImageFilter.hxx @@ -37,7 +37,7 @@ ConnectedComponentFunctorImageFilter< TInputImage, TOutputImage, TFunctor, TMask InputPixelType value, neighborValue; OutputPixelType label, originalLabel, neighborLabel; - OutputPixelType maxLabel = NumericTraits< OutputPixelType >::Zero; + OutputPixelType maxLabel = NumericTraits< OutputPixelType >::ZeroValue(); const OutputPixelType maxPossibleLabel = NumericTraits< OutputPixelType >::max(); typename TOutputImage::Pointer output = this->GetOutput(); @@ -49,7 +49,7 @@ ConnectedComponentFunctorImageFilter< TInputImage, TOutputImage, TFunctor, TMask // Set up the boundary condition to be zero padded (used on output image) ConstantBoundaryCondition< TOutputImage > BC; - BC.SetConstant(NumericTraits< OutputPixelType >::Zero); + BC.SetConstant(NumericTraits< OutputPixelType >::ZeroValue()); // Neighborhood iterators. Let's use a shaped neighborhood so we can // restrict the access to face connected neighbors. These iterators @@ -119,10 +119,10 @@ ConnectedComponentFunctorImageFilter< TInputImage, TOutputImage, TFunctor, TMask oit.GoToBegin(); while ( !mit.IsAtEnd() ) { - if ( mit.Get() == NumericTraits< MaskPixelType >::Zero ) + if ( mit.Get() == NumericTraits< MaskPixelType >::ZeroValue() ) { // mark pixel as unlabeled - oit.Set(NumericTraits< OutputPixelType >::Zero); + oit.Set(NumericTraits< OutputPixelType >::ZeroValue()); } ++mit; @@ -146,7 +146,7 @@ ConnectedComponentFunctorImageFilter< TInputImage, TOutputImage, TFunctor, TMask originalLabel = label; // If the pixel is not background - if ( label != NumericTraits< OutputPixelType >::Zero ) + if ( label != NumericTraits< OutputPixelType >::ZeroValue() ) { // loop over the "previous" neighbors to find labels. this loop // may establish one or more new equivalence classes @@ -160,7 +160,7 @@ ConnectedComponentFunctorImageFilter< TInputImage, TOutputImage, TFunctor, TMask // if the previous pixel has a label, verify equivalence or // establish a new equivalence - if ( neighborLabel != NumericTraits< OutputPixelType >::Zero ) + if ( neighborLabel != NumericTraits< OutputPixelType >::ZeroValue() ) { // see if current pixel is connected to its neighbor neighborValue = isIt.Get(); @@ -228,7 +228,7 @@ ConnectedComponentFunctorImageFilter< TInputImage, TOutputImage, TFunctor, TMask { label = oit.Get(); // if pixel has a label, write out the final equivalence - if ( label != NumericTraits< OutputPixelType >::Zero ) + if ( label != NumericTraits< OutputPixelType >::ZeroValue() ) { oit.Set( eqTable->Lookup(label) ); } diff --git a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkConnectedComponentImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkConnectedComponentImageFilter.hxx index ccfd4cee704563bbcfae4f89350c95dad45c45ab..a31c7ec174d0c386ab0eefa70550b50ae85c2079 100644 --- a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkConnectedComponentImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkConnectedComponentImageFilter.hxx @@ -407,9 +407,9 @@ ConnectedComponentImageFilter< TInputImage, TOutputImage, TMaskImage > ::AfterThreadedGenerateData() { m_NumberOfLabels.clear(); - m_Barrier = NULL; + m_Barrier = ITK_NULLPTR; m_LineMap.clear(); - m_Input = NULL; + m_Input = ITK_NULLPTR; } template< typename TInputImage, typename TOutputImage, typename TMaskImage > diff --git a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.h b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.h index 72176c60807d7979386e1cd31a7895a81905038a..3cc5e1d569c5275e085bf0a6c37761e16b585dba 100644 --- a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.h +++ b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.h @@ -89,7 +89,8 @@ public: ImageToImageFilter); /** Typedef to describe the type of pixel. */ - typedef typename TInputImage::PixelType PixelType; + typedef typename TInputImage::PixelType PixelType; + typedef typename TOutputImage::PixelType OutputPixelType; /** The pixel type must support comparison operators. */ itkConceptMacro( PixelTypeComparable, ( Concept::Comparable< PixelType > ) ); @@ -215,8 +216,9 @@ private: unsigned int m_MinimumObjectSizeInPixels; // Binary threshold variables - PixelType m_OutsideValue; - PixelType m_InsideValue; + OutputPixelType m_OutsideValue; + OutputPixelType m_InsideValue; + PixelType m_LowerBoundary; PixelType m_UpperBoundary; diff --git a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.hxx index 533b27efa47fa1ff49bbc1f1eba7e1c924fc1f89..d6ad090a288ae9505a825fc06c49d26729391f68 100644 --- a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkThresholdMaximumConnectedComponentsImageFilter.hxx @@ -59,10 +59,10 @@ ThresholdMaximumConnectedComponentsImageFilter< TInputImage, TOutputImage > // Initialize values for the theshold filters // Default. Use ITK set macro "SetOutsideValue" to change - m_OutsideValue = static_cast< PixelType >( minLabel ); + m_OutsideValue = static_cast< OutputPixelType >( minLabel ); // Default. Use ITK set macro "SetInsideValue" to change - m_InsideValue = static_cast< PixelType >( maxLabel ); + m_InsideValue = static_cast< OutputPixelType >( maxLabel ); m_LowerBoundary = m_ThresholdValue; @@ -212,10 +212,10 @@ ThresholdMaximumConnectedComponentsImageFilter< TInputImage, TOutputImage > Superclass::PrintSelf(os, indent); os << indent << "InsideValue: " - << static_cast< typename NumericTraits< PixelType >::PrintType >( + << static_cast< typename NumericTraits< OutputPixelType >::PrintType >( m_InsideValue ) << std::endl; os << indent << "OutsideValue: " - << static_cast< typename NumericTraits< PixelType >::PrintType >( + << static_cast< typename NumericTraits< OutputPixelType >::PrintType >( m_OutsideValue ) << std::endl; os << indent << "Lower: " << static_cast< typename NumericTraits< PixelType >::PrintType >( diff --git a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkVectorConnectedComponentImageFilter.h b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkVectorConnectedComponentImageFilter.h index de85cf5dc041da508d3d015d745b37ddcdfdbb5a..f45309f813b100a23a17720b59c46f96f41f5762 100644 --- a/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkVectorConnectedComponentImageFilter.h +++ b/Utilities/ITK/Modules/Segmentation/ConnectedComponents/include/itkVectorConnectedComponentImageFilter.h @@ -51,7 +51,7 @@ class SimilarVectorsFunctor { public: SimilarVectorsFunctor() - { m_Threshold = itk::NumericTraits< typename TInput::ValueType >::Zero; } + { m_Threshold = itk::NumericTraits< typename TInput::ValueType >::ZeroValue(); } ~SimilarVectorsFunctor() {} @@ -72,7 +72,7 @@ public: bool operator()(const TInput & a, const TInput & b) const { typedef typename NumericTraits<typename TInput::ValueType>::RealType RealValueType; - RealValueType dotProduct = NumericTraits<RealValueType>::Zero; + RealValueType dotProduct = NumericTraits<RealValueType>::ZeroValue(); for ( unsigned int i = 0; i < NumericTraits<TInput>::GetLength(a); ++i) { dotProduct += a[i]*b[i]; diff --git a/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DBalloonForceFilter.hxx b/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DBalloonForceFilter.hxx index ef3fda819b08994e3cd90945c651c054779db3ea..847870adcdb0d55e47c8fc4fb5df814c6088c619 100644 --- a/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DBalloonForceFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DBalloonForceFilter.hxx @@ -72,9 +72,9 @@ DeformableSimplexMesh3DBalloonForceFilter< TInputMesh, TOutputMesh > coord[1] = static_cast< GradientIndexValueType >( data->pos[1] ); coord[2] = static_cast< GradientIndexValueType >( data->pos[2] ); - coord2[0] = static_cast< GradientIndexValueType >( vcl_ceil(data->pos[0]) ); - coord2[1] = static_cast< GradientIndexValueType >( vcl_ceil(data->pos[1]) ); - coord2[2] = static_cast< GradientIndexValueType >( vcl_ceil(data->pos[2]) ); + coord2[0] = static_cast< GradientIndexValueType >( std::ceil(data->pos[0]) ); + coord2[1] = static_cast< GradientIndexValueType >( std::ceil(data->pos[1]) ); + coord2[2] = static_cast< GradientIndexValueType >( std::ceil(data->pos[2]) ); tmp_co_1[0] = coord2[0]; tmp_co_1[1] = coord[1]; diff --git a/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DFilter.hxx b/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DFilter.hxx index b4f6da8f044eb4bf67699197e89eee23bfec3d00..c64bace5d9b5fa70ad3a1875f2bd8be888b91082 100644 --- a/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DFilter.hxx @@ -66,7 +66,7 @@ DeformableSimplexMesh3DFilter< TInputMesh, TOutputMesh > this->ProcessObject::SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput( 0, output.GetPointer() ); - this->m_Data = NULL; + this->m_Data = ITK_NULLPTR; } template< typename TInputMesh, typename TOutputMesh > @@ -150,7 +150,7 @@ DeformableSimplexMesh3DFilter< TInputMesh, TOutputMesh > IdentifierType idx = pointItr.Index(); data = this->m_Data->GetElement(idx); delete data->neighborSet; - data->neighborSet = NULL; + data->neighborSet = ITK_NULLPTR; pointItr++; } @@ -294,10 +294,10 @@ DeformableSimplexMesh3DFilter< TInputMesh, TOutputMesh > double tmpNormalProd = dot_product( tmp.GetVnlVector(), data->normal.GetVnlVector() ); double sinphi = 2 *data->circleRadius *D *vnl_math_sgn(tmpNormalProd); - double phi = vcl_asin(sinphi); + double phi = std::asin(sinphi); data->phi = phi; - data->meanCurvature = vcl_abs(sinphi / data->circleRadius); + data->meanCurvature = std::abs(sinphi / data->circleRadius); tmp = data->pos - data->neighbors[0]; //compute the foot of p projection of p onto the triangle spanned by its @@ -374,7 +374,7 @@ DeformableSimplexMesh3DFilter< TInputMesh, TOutputMesh > eps1Diff = epsRef[0] - eps[0]; eps2Diff = epsRef[1] - eps[1]; eps3Diff = epsRef[2] - eps[2]; - // diffAbsSum = vcl_abs(eps1Diff)+vcl_abs(eps2Diff)+vcl_abs(eps3Diff); + // diffAbsSum = std::abs(eps1Diff)+std::abs(eps2Diff)+std::abs(eps3Diff); tangentForce.SetVnlVector(eps1Diff * ( data->neighbors[0] ).GetVnlVector() + eps2Diff * ( data->neighbors[1] ).GetVnlVector() @@ -423,9 +423,9 @@ DeformableSimplexMesh3DFilter< TInputMesh, TOutputMesh > coord[1] = static_cast< GradientIndexValueType >( data->pos[1] ); coord[2] = static_cast< GradientIndexValueType >( data->pos[2] ); - coord2[0] = static_cast< GradientIndexValueType >( vcl_ceil(data->pos[0]) ); - coord2[1] = static_cast< GradientIndexValueType >( vcl_ceil(data->pos[1]) ); - coord2[2] = static_cast< GradientIndexValueType >( vcl_ceil(data->pos[2]) ); + coord2[0] = static_cast< GradientIndexValueType >( std::ceil(data->pos[0]) ); + coord2[1] = static_cast< GradientIndexValueType >( std::ceil(data->pos[1]) ); + coord2[2] = static_cast< GradientIndexValueType >( std::ceil(data->pos[2]) ); tmp_co_1[0] = coord2[0]; tmp_co_1[1] = coord[1]; @@ -583,7 +583,7 @@ double DeformableSimplexMesh3DFilter< TInputMesh, TOutputMesh > double r2 = r * r; double d2 = d * d; double r2Minusd2 = r2 - d2; - double tanPhi = vcl_tan(phi); + double tanPhi = std::tan(phi); double eps = 1.0; @@ -595,7 +595,7 @@ double DeformableSimplexMesh3DFilter< TInputMesh, TOutputMesh > double tmpSqr = r2 + r2Minusd2 * tanPhi * tanPhi; if ( tmpSqr > 0 ) { - double denom = eps * ( vcl_sqrt(tmpSqr) + r ); + double denom = eps * ( std::sqrt(tmpSqr) + r ); if ( denom != 0 ) { L = ( r2Minusd2 * tanPhi ) / denom; diff --git a/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DGradientConstraintForceFilter.hxx b/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DGradientConstraintForceFilter.hxx index 643e4464dd632a99d0aa7a81ff9b371ad4c8d05b..0738701dec2fd4ea377694f307a61759167ed673 100644 --- a/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DGradientConstraintForceFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/DeformableMesh/include/itkDeformableSimplexMesh3DGradientConstraintForceFilter.hxx @@ -32,7 +32,7 @@ DeformableSimplexMesh3DGradientConstraintForceFilter< TInputMesh, TOutputMesh > ::DeformableSimplexMesh3DGradientConstraintForceFilter() { m_Range = 1; - m_StartVoxel = NULL; + m_StartVoxel = ITK_NULLPTR; } template< typename TInputMesh, typename TOutputMesh > @@ -58,7 +58,7 @@ DeformableSimplexMesh3DGradientConstraintForceFilter< TInputMesh, TOutputMesh > ::Clear() { delete m_StartVoxel; - m_StartVoxel = 0; + m_StartVoxel = ITK_NULLPTR; std::vector< ImageVoxel * >::iterator it; for ( it = m_Positive.begin(); it != m_Positive.end(); it++ ) { @@ -363,7 +363,7 @@ DeformableSimplexMesh3DGradientConstraintForceFilter< TInputMesh, TOutputMesh > } else { - m_StartVoxel = 0; + m_StartVoxel = ITK_NULLPTR; } // now fun begins try to use all the above @@ -384,7 +384,7 @@ DeformableSimplexMesh3DGradientConstraintForceFilter< TInputMesh, TOutputMesh > vec_for[2] = gradient3[2]; // check magnitude - mag = vcl_sqrt( dot_product( vec_for.GetVnlVector(), vec_for.GetVnlVector() ) ); + mag = std::sqrt( dot_product( vec_for.GetVnlVector(), vec_for.GetVnlVector() ) ); if ( mag > max ) { max = mag; diff --git a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMRegionGrowImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMRegionGrowImageFilter.hxx index a375870c4831b8b3c87d72737641cbce915a6a20..caff0b4498489c97232d6621a5feee62f309afbc 100644 --- a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMRegionGrowImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMRegionGrowImageFilter.hxx @@ -28,7 +28,8 @@ KLMRegionGrowImageFilter< TInputImage, TOutputImage > m_NumberOfRegions(0), m_InternalLambda(0), m_InitialNumberOfRegions(0), - m_BorderCandidate(NULL), + m_TotalBorderLength(0.0), + m_BorderCandidate(ITK_NULLPTR), m_InitialRegionArea(0) { m_InitialRegionMean.set_size(InputImageVectorDimension); @@ -702,8 +703,8 @@ KLMRegionGrowImageFilter< TInputImage, TOutputImage > // Remove any duplicate borders found during SpliceRegionBorders: // lambda = -1.0, pRegion1 and pRegion2 = NULL - while ( m_BorderCandidate->m_Pointer->GetRegion1() == NULL - || m_BorderCandidate->m_Pointer->GetRegion2() == NULL ) + while ( m_BorderCandidate->m_Pointer->GetRegion1() == ITK_NULLPTR + || m_BorderCandidate->m_Pointer->GetRegion2() == ITK_NULLPTR ) { m_BordersDynamicPointer.erase(m_BordersDynamicPointer.end() - 1); diff --git a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMSegmentationBorder.h b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMSegmentationBorder.h index 653752c42e527abf4661c9c004ed1dd8afd0f1be..df8ef1bbd67c398a0ce59ef322721e2906dcbe19 100644 --- a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMSegmentationBorder.h +++ b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMSegmentationBorder.h @@ -179,7 +179,7 @@ protected: ~KLMSegmentationBorder(); /** Print self identity */ - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: KLMSegmentationBorder(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMSegmentationRegion.h b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMSegmentationRegion.h index 2aa68d4828aeb32aaf42a3b47b61472ef587fb9b..6afc9442cd9bf76bf1028ebfd4d5163a947773bc 100644 --- a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMSegmentationRegion.h +++ b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkKLMSegmentationRegion.h @@ -215,7 +215,7 @@ public: protected: KLMSegmentationRegion(); ~KLMSegmentationRegion(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: KLMSegmentationRegion(const Self &); // purposely not implemented diff --git a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkSegmentationBorder.h b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkSegmentationBorder.h index e042d4c93627cd5bd144555dcdc3c33731e2da45..f162d6139b8d01751fb87c328e9e2dce8dea519f 100644 --- a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkSegmentationBorder.h +++ b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkSegmentationBorder.h @@ -70,7 +70,7 @@ public: protected: SegmentationBorder(); ~SegmentationBorder(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: SegmentationBorder(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkSegmentationRegion.h b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkSegmentationRegion.h index 9b984bf7b3a944830af9a5702cc8ed20a55e2281..d72de8fe66d407e60bb05217c8d4714b58c30ab3 100644 --- a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkSegmentationRegion.h +++ b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/include/itkSegmentationRegion.h @@ -78,7 +78,7 @@ public: protected: SegmentationRegion(); ~SegmentationRegion(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: SegmentationRegion(const Self &); //purposely not implemented diff --git a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/src/itkKLMSegmentationBorder.cxx b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/src/itkKLMSegmentationBorder.cxx index 28f78ccedba83876c8cddf64e06588c3d9912d92..e576c96e68b920f39e61c81f7491e7ddd1e9713e 100644 --- a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/src/itkKLMSegmentationBorder.cxx +++ b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/src/itkKLMSegmentationBorder.cxx @@ -23,8 +23,8 @@ KLMSegmentationBorder ::KLMSegmentationBorder(void) { m_Lambda = 0.0; - m_Region1 = 0; - m_Region2 = 0; + m_Region1 = ITK_NULLPTR; + m_Region2 = ITK_NULLPTR; } KLMSegmentationBorder diff --git a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/src/itkKLMSegmentationRegion.cxx b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/src/itkKLMSegmentationRegion.cxx index bbd2fd3967bb21af14c411fcd8e3dcb8290326e7..cc0b15dfcf6daefa15e2f4a118f2e1be46fe1036 100644 --- a/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/src/itkKLMSegmentationRegion.cxx +++ b/Utilities/ITK/Modules/Segmentation/KLMRegionGrowing/src/itkKLMSegmentationRegion.cxx @@ -97,7 +97,7 @@ void KLMSegmentationRegion ::DeleteRegionBorder(KLMSegmentationBorder *pBorderCandidate) { - if ( pBorderCandidate == NULL ) + if ( pBorderCandidate == ITK_NULLPTR ) { itkExceptionMacro(<< "Null pointer to segmentation region border"); } @@ -130,7 +130,7 @@ void KLMSegmentationRegion ::PushBackRegionBorder(KLMSegmentationBorder *pBorderCandidate) { - if ( pBorderCandidate == NULL ) + if ( pBorderCandidate == ITK_NULLPTR ) { itkExceptionMacro(<< "Null pointer to segmentation region border"); } @@ -141,7 +141,7 @@ void KLMSegmentationRegion ::PushFrontRegionBorder(KLMSegmentationBorder *pBorderCandidate) { - if ( pBorderCandidate == NULL ) + if ( pBorderCandidate == ITK_NULLPTR ) { itkExceptionMacro(<< "Null pointer to segmentation region border"); } @@ -153,7 +153,7 @@ KLMSegmentationRegion ::InsertRegionBorder(KLMSegmentationBorder *pBorderCandidate) { // Ensure that the border candidate is not a null pointer - if ( pBorderCandidate == NULL ) + if ( pBorderCandidate == ITK_NULLPTR ) { itkExceptionMacro(<< "Null pointer to segmentation region border"); } @@ -209,7 +209,7 @@ KLMSegmentationRegion KLMSegmentationBorder *pBorderCandidate) { // Ensure that the border candidate is not a null pointer - if ( pBorderCandidate == NULL ) + if ( pBorderCandidate == ITK_NULLPTR ) { itkExceptionMacro(<< "Null pointer to segmentation region border"); } @@ -379,8 +379,8 @@ KLMSegmentationRegion } // end else // Nullify the duplicate border so it can be identified and removed. - ( *thatRegionBordersIt )->SetRegion1(NULL); - ( *thatRegionBordersIt )->SetRegion2(NULL); + ( *thatRegionBordersIt )->SetRegion1(ITK_NULLPTR); + ( *thatRegionBordersIt )->SetRegion2(ITK_NULLPTR); ( *thatRegionBordersIt )->SetLambda(-1.0); thisRegionBordersIt++; diff --git a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkBinaryMedianImageFilter.h b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkBinaryMedianImageFilter.h index 0a5ac953b24501cefbf2d962781be5a5d0e27f1b..20736ebc60ee64361bc5624c297a04f791049d76 100644 --- a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkBinaryMedianImageFilter.h +++ b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkBinaryMedianImageFilter.h @@ -103,8 +103,7 @@ public: * in order to inform the pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkBinaryMedianImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkBinaryMedianImageFilter.hxx index 92338d1b18e3a440ef1bad950c649dcf71c05a26..5357687408f4e943e1d496918603b0454c1aeba4 100644 --- a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkBinaryMedianImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkBinaryMedianImageFilter.hxx @@ -44,7 +44,6 @@ template< typename TInputImage, typename TOutputImage > void BinaryMedianImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); diff --git a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkLabelVotingImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkLabelVotingImageFilter.hxx index cae9e9b8513878e369bebf8079f2e85ecd8465a3..aa73b6bfa46c9538163771300976f96cba51c355 100644 --- a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkLabelVotingImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkLabelVotingImageFilter.hxx @@ -21,6 +21,7 @@ #include "itkLabelVotingImageFilter.h" #include "itkImageRegionIterator.h" +#include "itkProgressReporter.h" #include "vnl/vnl_math.h" @@ -104,8 +105,10 @@ template< typename TInputImage, typename TOutputImage > void LabelVotingImageFilter< TInputImage, TOutputImage > ::ThreadedGenerateData( const OutputImageRegionType & outputRegionForThread, - ThreadIdType itkNotUsed(threadId) ) + ThreadIdType threadId ) { + ProgressReporter progress( this, threadId, outputRegionForThread.GetNumberOfPixels() ); + typedef ImageRegionConstIterator< TInputImage > IteratorType; typedef ImageRegionIterator< TOutputImage > OutIteratorType; @@ -159,6 +162,7 @@ LabelVotingImageFilter< TInputImage, TOutputImage > } } } + progress.CompletedPixel(); } delete[] it; diff --git a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkMultiLabelSTAPLEImageFilter.h b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkMultiLabelSTAPLEImageFilter.h index cf4d87ac0d117885420fa59969a6eacf364366b3..b6be982bdc79848d15ae7bb28a50b16751cc092f 100644 --- a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkMultiLabelSTAPLEImageFilter.h +++ b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkMultiLabelSTAPLEImageFilter.h @@ -27,6 +27,7 @@ #include "vector" #include "itkArray.h" #include "itkArray2D.h" +#include "itkNumericTraits.h" namespace itk { @@ -256,12 +257,15 @@ public: } protected: - MultiLabelSTAPLEImageFilter() + MultiLabelSTAPLEImageFilter() : + m_TotalLabelCount(0), + m_LabelForUndecidedPixels(NumericTraits<OutputPixelType>::Zero), + m_HasLabelForUndecidedPixels(false), + m_HasPriorProbabilities(false), + m_HasMaximumNumberOfIterations(false), + m_MaximumNumberOfIterations(0), + m_TerminationUpdateThreshold(1e-5) { - this->m_HasLabelForUndecidedPixels = false; - this->m_HasPriorProbabilities = false; - this->m_HasMaximumNumberOfIterations = false; - this->m_TerminationUpdateThreshold = 1e-5; } virtual ~MultiLabelSTAPLEImageFilter() {} diff --git a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkVotingBinaryImageFilter.h b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkVotingBinaryImageFilter.h index 4d5e6e90485f44308ce1bc63d109450c0e9e9261..82dd1946e36c5dbf045a91942ce3f375ef076f94 100644 --- a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkVotingBinaryImageFilter.h +++ b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkVotingBinaryImageFilter.h @@ -103,8 +103,7 @@ public: * in order to inform the pipeline execution model. * * \sa ImageToImageFilter::GenerateInputRequestedRegion() */ - virtual void GenerateInputRequestedRegion() - throw( InvalidRequestedRegionError ); + virtual void GenerateInputRequestedRegion(); #ifdef ITK_USE_CONCEPT_CHECKING // Begin concept checking diff --git a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkVotingBinaryImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkVotingBinaryImageFilter.hxx index e4ebb24896ed2e8585df4ceb36e60aedd09a4083..d7792e5cd7eb8033b8dffc16c7d37f8bf8967b48 100644 --- a/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkVotingBinaryImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LabelVoting/include/itkVotingBinaryImageFilter.hxx @@ -45,7 +45,6 @@ template< typename TInputImage, typename TOutputImage > void VotingBinaryImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() -throw ( InvalidRequestedRegionError ) { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkBinaryMaskToNarrowBandPointSetFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkBinaryMaskToNarrowBandPointSetFilter.hxx index 771cfd83ea01decdae0c1f6f90eb4d7c41045cbd..85892026d0f176dec1eeffa7b65303970f1b988c 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkBinaryMaskToNarrowBandPointSetFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkBinaryMaskToNarrowBandPointSetFilter.hxx @@ -130,7 +130,7 @@ BinaryMaskToNarrowBandPointSetFilter< TInputImage, TOutputMesh > { const NodeType & node = nodeItr.Value(); const float distance = node.GetValue(); - if ( vcl_fabs(distance) < m_BandWidth ) + if ( std::fabs(distance) < m_BandWidth ) { image->TransformIndexToPhysicalPoint(node.GetIndex(), point); points->push_back(point); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCollidingFrontsImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCollidingFrontsImageFilter.hxx index 8c5cef2e5a0f3a5dca448285fac1c7927363c285..0d07af010e6cb5b56963ea8d88da486b7f74abe6 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCollidingFrontsImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCollidingFrontsImageFilter.hxx @@ -29,8 +29,8 @@ template< typename TInputImage, typename TOutputImage > CollidingFrontsImageFilter< TInputImage, TOutputImage > ::CollidingFrontsImageFilter() { - m_SeedPoints1 = NULL; - m_SeedPoints2 = NULL; + m_SeedPoints1 = ITK_NULLPTR; + m_SeedPoints2 = ITK_NULLPTR; m_StopOnTargets = false; m_ApplyConnectivity = true; m_NegativeEpsilon = -1E-6; diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetFunction.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetFunction.h index 4dad6b4d93ae288b68a97766a98a1cc0e1f0e9d2..5f050968303f8776bd4fafbca1d9c37e6921b84f 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetFunction.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetFunction.h @@ -113,15 +113,15 @@ public: virtual void Initialize(const RadiusType & r); protected: - CurvesLevelSetFunction() + CurvesLevelSetFunction() : + m_Center(0), + m_DerivativeSigma(1.0) { //Curvature term is the minimal curvature. this->UseMinimalCurvatureOn(); this->SetAdvectionWeight(NumericTraits< ScalarValueType >::One); this->SetPropagationWeight(NumericTraits< ScalarValueType >::One); this->SetCurvatureWeight(NumericTraits< ScalarValueType >::One); - - m_DerivativeSigma = 1.0; } virtual ~CurvesLevelSetFunction() {} diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetImageFilter.hxx index 8f15298a60ba347031f0b0fb0261da70628c6dad..5c51173220910756dbd38b9b433b0e4ccfe247f7 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkCurvesLevelSetImageFilter.hxx @@ -45,8 +45,7 @@ CurvesLevelSetImageFilter< TInputImage, TFeatureImage, TOutputType > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - os << indent << "CurvesFunction: \n"; - m_CurvesFunction->Print( os, indent.GetNextIndent() ); + itkPrintSelfObjectMacro( CurvesFunction ); } template< typename TInputImage, typename TFeatureImage, typename TOutputType > diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkExtensionVelocitiesImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkExtensionVelocitiesImageFilter.hxx index 8f26b6152dc660315e8e74d0f5c886b6e2245902..1b48e961994afa84f1644a37abc124d77d60f7fa 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkExtensionVelocitiesImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkExtensionVelocitiesImageFilter.hxx @@ -74,7 +74,7 @@ ExtensionVelocitiesImageFilter< TLevelSet, TAuxValue, VAuxDimension > { if ( idx >= VAuxDimension || this->GetNumberOfIndexedInputs() < idx + 2 ) { - return NULL; + return ITK_NULLPTR; } return dynamic_cast< AuxImageType * >( @@ -92,7 +92,7 @@ ExtensionVelocitiesImageFilter< TLevelSet, TAuxValue, VAuxDimension > { if ( idx >= VAuxDimension || this->GetNumberOfIndexedOutputs() < idx + 2 ) { - return NULL; + return ITK_NULLPTR; } return itkDynamicCastInDebugMode< AuxImageType * >(this->ProcessObject::GetOutput(idx + 1) ); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourShapePriorLevelSetFunction.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourShapePriorLevelSetFunction.hxx index 6c6bb24f57f774b877f57cf26e6b639fec7a28f6..4139e0e301da62a31e8c9f9eeaf1df3d0bd314aa 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourShapePriorLevelSetFunction.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkGeodesicActiveContourShapePriorLevelSetFunction.hxx @@ -20,6 +20,7 @@ #include "itkGeodesicActiveContourShapePriorLevelSetFunction.h" #include "itkGradientRecursiveGaussianImageFilter.h" +#include "itkGradientImageFilter.h" #include "itkImageAlgorithm.h" namespace itk @@ -46,18 +47,44 @@ template< typename TImageType, typename TFeatureImageType > void GeodesicActiveContourShapePriorLevelSetFunction< TImageType, TFeatureImageType > ::CalculateAdvectionImage() { - /* compoute the gradient of the feature image. */ - typedef GradientRecursiveGaussianImageFilter< FeatureImageType, VectorImageType > - DerivativeFilterType; - typename DerivativeFilterType::Pointer derivative = DerivativeFilterType::New(); - derivative->SetInput( this->GetFeatureImage() ); - derivative->SetSigma(m_DerivativeSigma); - derivative->Update(); + typename VectorImageType::Pointer gradientImage; + + if ( m_DerivativeSigma != NumericTraits< float >::Zero ) + { + /* compute the gradient of the feature image. */ + typedef GradientRecursiveGaussianImageFilter< FeatureImageType, VectorImageType > + DerivativeFilterType; + + typename DerivativeFilterType::Pointer derivative = DerivativeFilterType::New(); + derivative->SetInput( this->GetFeatureImage() ); + derivative->SetSigma( m_DerivativeSigma ); + derivative->Update(); + + gradientImage = derivative->GetOutput(); + } + else + { + typedef GradientImageFilter< FeatureImageType > DerivativeFilterType; + + typename DerivativeFilterType::Pointer derivative = DerivativeFilterType::New(); + derivative->SetInput( this->GetFeatureImage() ); + derivative->SetUseImageSpacingOn(); + derivative->Update(); + + typedef typename DerivativeFilterType::OutputImageType DerivativeOutputImageType; + typedef VectorCastImageFilter< DerivativeOutputImageType, VectorImageType > GradientCasterType; + + typename GradientCasterType::Pointer caster = GradientCasterType::New(); + caster->SetInput( derivative->GetOutput() ); + caster->Update(); + + gradientImage = caster->GetOutput(); + } /* copy negative gradient into the advection image. */ ImageRegionIterator< VectorImageType > - dit( derivative->GetOutput(), this->GetFeatureImage()->GetRequestedRegion() ); + dit( gradientImage, this->GetFeatureImage()->GetRequestedRegion() ); ImageRegionIterator< VectorImageType > ait( this->GetAdvectionImage(), this->GetFeatureImage()->GetRequestedRegion() ); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkImplicitManifoldNormalVectorFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkImplicitManifoldNormalVectorFilter.hxx index 7e0efb2fcd0d01474879c26d4589f5da2e338344..a535a79252b239e7c6bd2c85d41072f0a1dfc70e 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkImplicitManifoldNormalVectorFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkImplicitManifoldNormalVectorFilter.hxx @@ -28,7 +28,7 @@ ImplicitManifoldNormalVectorFilter< TInputImage, TSparseOutputImage > ::ImplicitManifoldNormalVectorFilter() { this->SetPrecomputeFlag(true); - m_NormalFunction = 0; + m_NormalFunction = ITK_NULLPTR; // set defaults for parameters m_IsoLevelLow = NumericTraits< NodeValueType >::Zero; @@ -113,7 +113,7 @@ ImplicitManifoldNormalVectorFilter< TInputImage, TSparseOutputImage > } else { - output->SetPixel(index, 0); + output->SetPixel(index, ITK_NULLPTR); } ++it; } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunction.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunction.h index 328167349343a7b46198e981acf0ac46ae7490d0..8b6cded4dc11d7c87273d6d2eb5097267d51a785 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunction.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunction.h @@ -290,13 +290,15 @@ public: } protected: - LevelSetFunction() + LevelSetFunction() : + m_Center(0), + m_UseMinimalCurvature(false), + m_EpsilonMagnitude(static_cast< ScalarValueType >( 1.0e-5 )), + m_AdvectionWeight(NumericTraits< ScalarValueType >::Zero), + m_PropagationWeight(NumericTraits< ScalarValueType >::Zero), + m_CurvatureWeight(NumericTraits< ScalarValueType >::Zero), + m_LaplacianSmoothingWeight(NumericTraits< ScalarValueType >::Zero) { - m_EpsilonMagnitude = static_cast< ScalarValueType >( 1.0e-5 ); - m_AdvectionWeight = m_PropagationWeight = - m_CurvatureWeight = m_LaplacianSmoothingWeight = - NumericTraits< ScalarValueType >::Zero; - m_UseMinimalCurvature = false; } virtual ~LevelSetFunction() {} diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunction.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunction.hxx index 644b1698b922a5b18c256c51f837f36793dbfff5..2875ba58a0d8effa6ba6298db42880f6e3b38faf 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunction.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunction.hxx @@ -57,7 +57,7 @@ LevelSetFunction< TImageType > const FloatOffsetType & itkNotUsed(offset), GlobalDataStruct *gd) { unsigned int i, j, n; - ScalarValueType gradMag = vcl_sqrt(gd->m_GradMagSqr); + ScalarValueType gradMag = std::sqrt(gd->m_GradMagSqr); ScalarValueType Pgrad[ImageDimension][ImageDimension]; ScalarValueType tmp_matrix[ImageDimension][ImageDimension]; const ScalarValueType ZERO = NumericTraits< ScalarValueType >::Zero; @@ -150,7 +150,7 @@ LevelSetFunction< TImageType > { discriminant = 0.0; } - discriminant = vcl_sqrt(discriminant); + discriminant = std::sqrt(discriminant); return ( mean_curve - discriminant ); } @@ -434,7 +434,7 @@ LevelSetFunction< TImageType > vnl_math_max( gd->m_MaxPropagationChange, vnl_math_abs(propagation_term) ); - propagation_term *= vcl_sqrt(propagation_gradient); + propagation_term *= std::sqrt(propagation_gradient); } else { propagation_term = ZERO; } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunctionWithRefitTerm.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunctionWithRefitTerm.hxx index 1c2180fa054763944ad0a413270ead6c25a334ae..845a6926e9dd7f9cd08bde1c8e0a4cb11681edf9 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunctionWithRefitTerm.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetFunctionWithRefitTerm.hxx @@ -166,9 +166,9 @@ LevelSetFunctionWithRefitTerm< TImageType, TSparseImageType > NodeType * targetnode = m_SparseTargetImage->GetPixel (idx); ScalarValueType refitterm, cv, tcv; - if ( ( targetnode == 0 ) || ( targetnode->m_CurvatureFlag == false ) ) + if ( ( targetnode == ITK_NULLPTR ) || ( targetnode->m_CurvatureFlag == false ) ) { - if ( targetnode == 0 ) + if ( targetnode == ITK_NULLPTR ) { itkExceptionMacro(<< "required node has null pointer\n"); } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetNeighborhoodExtractor.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetNeighborhoodExtractor.h index 0de0ee2b7c2ad7a32e6b0ac0118ac48199444701..0279baedddbd0c73f21baba3f45b13023c2f280e 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetNeighborhoodExtractor.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetNeighborhoodExtractor.h @@ -133,7 +133,7 @@ public: protected: LevelSetNeighborhoodExtractor(); ~LevelSetNeighborhoodExtractor(){} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; typename LevelSetImageType::PixelType GetLargeValue() const { return m_LargeValue; } @@ -145,7 +145,7 @@ protected: virtual double CalculateDistance(IndexType & index); - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; bool GetLastPointIsInside() const { return m_LastPointIsInside; } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetNeighborhoodExtractor.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetNeighborhoodExtractor.hxx index 96143fc6c385aea597ec8e89a1a918060bbf5a21..d1aa98df7bd8cbc3742e74a8b7fdecda7b5aa576 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetNeighborhoodExtractor.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetNeighborhoodExtractor.hxx @@ -32,19 +32,19 @@ namespace itk */ template< typename TLevelSet > LevelSetNeighborhoodExtractor< TLevelSet > -::LevelSetNeighborhoodExtractor() +::LevelSetNeighborhoodExtractor() : + m_LevelSetValue(0.0), + m_InsidePoints(ITK_NULLPTR), + m_OutsidePoints(ITK_NULLPTR), + m_InputLevelSet(ITK_NULLPTR), + m_NarrowBanding(false), + m_NarrowBandwidth(12.0), + m_InputNarrowBand(ITK_NULLPTR), + m_LargeValue(NumericTraits< PixelType >::max()), + m_LastPointIsInside(false) { - m_LevelSetValue = 0.0; - m_InsidePoints = 0; - m_OutsidePoints = 0; - m_InputLevelSet = 0; - - m_LargeValue = NumericTraits< PixelType >::max(); m_NodesUsed.resize(SetDimension); - m_NarrowBanding = false; - m_NarrowBandwidth = 12.0; - m_InputNarrowBand = 0; for ( unsigned int i = 0; i < SetDimension; ++i ) { m_ImageSize[i] = 0; @@ -320,7 +320,7 @@ LevelSetNeighborhoodExtractor< TLevelSet > return m_LargeValue; } - distance = vcl_sqrt(1.0 / distance); + distance = std::sqrt(1.0 / distance); centerNode.SetValue(distance); if ( inside ) diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetVelocityNeighborhoodExtractor.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetVelocityNeighborhoodExtractor.h index 74d5053c85c5dd6fe2e5a6e3b712264294809d27..235c45a8bc2b42aaed51ef2a8c74a54c67dd75ed 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetVelocityNeighborhoodExtractor.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetVelocityNeighborhoodExtractor.h @@ -107,7 +107,7 @@ public: { if ( idx >= VAuxDimension ) { - return NULL; + return ITK_NULLPTR; } else { diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetVelocityNeighborhoodExtractor.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetVelocityNeighborhoodExtractor.hxx index bae2fd68eb370645fb26efd15dc2eaba29ceb822..566b3547d21ed24c0c83e4ec50cf11770a463801 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetVelocityNeighborhoodExtractor.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkLevelSetVelocityNeighborhoodExtractor.hxx @@ -31,11 +31,11 @@ template< typename TLevelSet, typename TAuxValue, LevelSetVelocityNeighborhoodExtractor< TLevelSet, TAuxValue, VAuxDimension > ::LevelSetVelocityNeighborhoodExtractor() { - m_AuxInsideValues = 0; - m_AuxOutsideValues = 0; + m_AuxInsideValues = ITK_NULLPTR; + m_AuxOutsideValues = ITK_NULLPTR; for ( unsigned int i = 0; i < VAuxDimension; ++i ) { - m_AuxImage[i] = 0; + m_AuxImage[i] = ITK_NULLPTR; } } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNarrowBandLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNarrowBandLevelSetImageFilter.hxx index 221956b95a5d6ff3fe829c2730082b92622882b3..d7015a01b4a0414c0d8e296c11c13be3a19b4ddf 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNarrowBandLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNarrowBandLevelSetImageFilter.hxx @@ -40,7 +40,7 @@ NarrowBandLevelSetImageFilter< TInputImage, TFeatureImage, TOutputPixelType, TOu this->SetNumberOfRequiredInputs(2); //this->SetNarrowBandInnerRadius(); //this->SetNarrowBandTotalRadius(); - m_SegmentationFunction = 0; + m_SegmentationFunction = ITK_NULLPTR; m_IsoFilter = IsoFilterType::New(); m_ChamferFilter = ChamferFilterType::New(); @@ -77,7 +77,7 @@ void NarrowBandLevelSetImageFilter< TInputImage, TFeatureImage, TOutputPixelType, TOutputImage > ::GenerateData() { - if ( m_SegmentationFunction == 0 ) + if ( m_SegmentationFunction == ITK_NULLPTR ) { itkExceptionMacro("No finite difference function was specified."); } // A positive speed value causes surface expansion, the opposite of the @@ -137,8 +137,8 @@ NarrowBandLevelSetImageFilter< TInputImage, TFeatureImage, TOutputPixelType, TOu m_ChamferFilter->Update(); this->GraftOutput( m_ChamferFilter->GetOutput() ); - m_IsoFilter->SetInput(NULL); - m_ChamferFilter->SetInput(NULL); + m_IsoFilter->SetInput(ITK_NULLPTR); + m_ChamferFilter->SetInput(ITK_NULLPTR); } } // end namespace itk diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorDiffusionFunction.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorDiffusionFunction.h index 9866f6640d2feef27b1fbffd7ca28fd49a931f96..6532fc13687c684b61401b98565a9d01578b56ef 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorDiffusionFunction.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorDiffusionFunction.h @@ -143,7 +143,7 @@ protected: { // the slow exp function could be replaced with a lookup table if ( v <= 0.0 ) { return NumericTraits< NodeValueType >::One; } - else { return static_cast< NodeValueType >( vcl_exp(m_FluxStopConstant * v) ); } + else { return static_cast< NodeValueType >( std::exp(m_FluxStopConstant * v) ); } } private: diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorDiffusionFunction.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorDiffusionFunction.hxx index dedaa7da6b3eab7603145a549e5c5144847ede79..54077dc1d0731e1610368a1448d755acca466248 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorDiffusionFunction.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorDiffusionFunction.hxx @@ -38,8 +38,8 @@ NormalVectorDiffusionFunction< TSparseImageType > this->SetRadius(r); this->SetTimeStep( static_cast< TimeStepType >( 0.5 / ImageDimension ) ); m_NormalProcessType = 0; - m_ConductanceParameter = NumericTraits< NodeValueType >::Zero; - m_FluxStopConstant = NumericTraits< NodeValueType >::Zero; + m_ConductanceParameter = NumericTraits< NodeValueType >::ZeroValue(); + m_FluxStopConstant = NumericTraits< NodeValueType >::ZeroValue(); } template< typename TSparseImageType > @@ -84,11 +84,11 @@ NormalVectorDiffusionFunction< TSparseImageType > for ( i = 0; i < ImageDimension; i++ ) // flux offset axis { PreviousNode = it.GetPrevious (i); - if ( PreviousNode == 0 ) + if ( PreviousNode == ITK_NULLPTR ) { for ( j = 0; j < ImageDimension; j++ ) { - CenterNode->m_Flux[i][j] = NumericTraits< NodeValueType >::Zero; + CenterNode->m_Flux[i][j] = NumericTraits< NodeValueType >::ZeroValue(); } } else @@ -100,7 +100,7 @@ NormalVectorDiffusionFunction< TSparseImageType > { // compute differences (j-axis) in line with center pixel OtherNode = it.GetPrevious (j); - if ( OtherNode == 0 ) + if ( OtherNode == ITK_NULLPTR ) { NegativeSidePixel[0] = CenterPixel; } @@ -109,7 +109,7 @@ NormalVectorDiffusionFunction< TSparseImageType > NegativeSidePixel[0] = OtherNode->m_Data; } OtherNode = it.GetNext (j); - if ( OtherNode == 0 ) + if ( OtherNode == ITK_NULLPTR ) { PositiveSidePixel[0] = CenterPixel; } @@ -120,7 +120,7 @@ NormalVectorDiffusionFunction< TSparseImageType > // compute derivative (j-axis) offset from center pixel on i-axis OtherNode = it.GetPixel (center - stride[i] - stride[j]); - if ( OtherNode == 0 ) + if ( OtherNode == ITK_NULLPTR ) { NegativeSidePixel[1] = PreviousPixel; } @@ -129,7 +129,7 @@ NormalVectorDiffusionFunction< TSparseImageType > NegativeSidePixel[1] = OtherNode->m_Data; } OtherNode = it.GetPixel (center - stride[i] + stride[j]); - if ( OtherNode == 0 ) + if ( OtherNode == ITK_NULLPTR ) { PositiveSidePixel[1] = PreviousPixel; } @@ -151,7 +151,7 @@ NormalVectorDiffusionFunction< TSparseImageType > // now compute the intrinsic derivative for ( j = 0; j < ImageDimension; j++ ) // component axis { - DotProduct = NumericTraits< NodeValueType >::Zero; + DotProduct = NumericTraits< NodeValueType >::ZeroValue(); for ( k = 0; k < ImageDimension; k++ ) // derivative axis { DotProduct += ( gradient[k][j] * CenterNode->m_ManifoldNormal[i][k] ); @@ -190,11 +190,11 @@ NormalVectorDiffusionFunction< TSparseImageType > const NeighborhoodScalesType neighborhoodScales = this->ComputeNeighborhoodScales(); - change = NumericTraits< NormalVectorType >::Zero; + change = NumericTraits< NormalVectorType >::ZeroValue(); for ( i = 0; i < ImageDimension; i++ ) // flux offset axis { NextNode = it.GetNext (i); - if ( NextNode == 0 ) + if ( NextNode == ITK_NULLPTR ) { change -= CenterNode->m_Flux[i] * neighborhoodScales[i]; } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorFunctionBase.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorFunctionBase.h index bf20c7463a36e17dbc1d5893a43e2feab76d0b7c..b0f5440c35bf162db8631e9c7efaadeb1f70ee4d 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorFunctionBase.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkNormalVectorFunctionBase.h @@ -83,7 +83,7 @@ public: typedef typename NodeType::NodeDataType NormalVectorType; /** Globaldata methods are not needed in this class. */ - virtual void * GetGlobalDataPointer() const { return 0; } + virtual void * GetGlobalDataPointer() const { return ITK_NULLPTR; } virtual void ReleaseGlobalDataPointer(void *) const {} /** For the global time step, we return the time step parameter. */ diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkParallelSparseFieldLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkParallelSparseFieldLevelSetImageFilter.hxx index a74cd8a03cb6fb856c9b10386a0ca26c1d90fedc..b87b60a653d06d1d309fa728887c8bd7be6dea0c 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkParallelSparseFieldLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkParallelSparseFieldLevelSetImageFilter.hxx @@ -128,19 +128,24 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > template< typename TInputImage, typename TOutputImage > ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > -::ParallelSparseFieldLevelSetImageFilter() +::ParallelSparseFieldLevelSetImageFilter() : + m_ConstantGradientValue(1.0), + m_NumberOfLayers(ImageDimension), + m_IsoSurfaceValue(m_ValueZero), + m_NumOfThreads(0), + m_SplitAxis(0), + m_ZSize(0), + m_BoundaryChanged(false), + m_Boundary(ITK_NULLPTR), + m_GlobalZHistogram(ITK_NULLPTR), + m_MapZToThreadNumber(ITK_NULLPTR), + m_ZCumulativeFrequency(ITK_NULLPTR), + m_Data(ITK_NULLPTR), + m_Stop(false), + m_InterpolateSurfaceLocation(true), + m_BoundsCheckingActive(false) { - m_IsoSurfaceValue = m_ValueZero; - m_NumberOfLayers = ImageDimension; this->SetRMSChange( static_cast< double >( m_ValueOne ) ); - m_InterpolateSurfaceLocation = true; - m_BoundsCheckingActive = false; - m_ConstantGradientValue = 1.0; - m_GlobalZHistogram = 0; - m_ZCumulativeFrequency = 0; - m_MapZToThreadNumber = 0; - m_Boundary = 0; - m_Data = 0; } template< typename TInputImage, typename TOutputImage > @@ -545,7 +550,7 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > length += dx_backward * dx_backward; } } - length = vcl_sqrt(length) + MIN_NORM; + length = std::sqrt(length) + MIN_NORM; distance = shiftedIt.GetCenterPixel() / length; m_OutputImage->SetPixel( activeIt->m_Index, @@ -716,7 +721,7 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > } // deallocate the shifted-image - m_ShiftedImage = 0; + m_ShiftedImage = ITK_NULLPTR; } template< typename TInputImage, typename TOutputImage > @@ -974,16 +979,16 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > // Delete data structures used for load distribution and balancing. delete[] m_GlobalZHistogram; - m_GlobalZHistogram = 0; + m_GlobalZHistogram = ITK_NULLPTR; delete[] m_ZCumulativeFrequency; - m_ZCumulativeFrequency = 0; + m_ZCumulativeFrequency = ITK_NULLPTR; delete[] m_MapZToThreadNumber; - m_MapZToThreadNumber = 0; + m_MapZToThreadNumber = ITK_NULLPTR; delete[] m_Boundary; - m_Boundary = 0; + m_Boundary = ITK_NULLPTR; // Deallocate the status image. - m_StatusImage = 0; + m_StatusImage = ITK_NULLPTR; // Remove the barrier from the system. // m_Barrier->Remove (); @@ -994,7 +999,7 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > for ( i = 0; i < 2 * static_cast< unsigned int >( m_NumberOfLayers ) + 1; i++ ) { // return all the nodes in layer i to the main node pool - LayerNodeType * nodePtr = 0; + LayerNodeType * nodePtr = ITK_NULLPTR; LayerPointerType layerPtr = m_Layers[i]; while ( !layerPtr->Empty() ) { @@ -1010,7 +1015,7 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > m_Layers.clear(); } - if ( m_Data != 0 ) + if ( m_Data != ITK_NULLPTR ) { // Deallocate the thread local data structures. for ( ThreadIdType ThreadId = 0; ThreadId < m_NumOfThreads; ThreadId++ ) @@ -1019,10 +1024,10 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > delete[] m_Data[ThreadId].m_ZHistogram; - if ( m_Data[ThreadId].globalData != 0 ) + if ( m_Data[ThreadId].globalData != ITK_NULLPTR ) { this->GetDifferenceFunction()->ReleaseGlobalDataPointer (m_Data[ThreadId].globalData); - m_Data[ThreadId].globalData = 0; + m_Data[ThreadId].globalData = ITK_NULLPTR; } // 1. delete nodes on the thread layers @@ -1102,7 +1107,7 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > delete[] m_Data; } // if m_data != 0 - m_Data = 0; + m_Data = ITK_NULLPTR; } template< typename TInputImage, typename TOutputImage > @@ -1197,13 +1202,13 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > if ( ThreadId == 0 ) { - str->Filter->m_StatusImage = 0; + str->Filter->m_StatusImage = ITK_NULLPTR; str->Filter->m_StatusImage = str->Filter->m_StatusImageTemp; - str->Filter->m_StatusImageTemp = 0; + str->Filter->m_StatusImageTemp = ITK_NULLPTR; - str->Filter->m_OutputImage = 0; + str->Filter->m_OutputImage = ITK_NULLPTR; str->Filter->m_OutputImage = str->Filter->m_OutputImageTemp; - str->Filter->m_OutputImageTemp = 0; + str->Filter->m_OutputImageTemp = ITK_NULLPTR; // str->Filter->GraftOutput(str->Filter->m_OutputImage); } @@ -1246,7 +1251,7 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > unsigned int count = str->Filter->m_Data[0].m_Count; if ( count != 0 ) { - str->Filter->SetRMSChange( static_cast< double >( vcl_sqrt( + str->Filter->SetRMSChange( static_cast< double >( std::sqrt( ( static_cast< float >( str->Filter->GetRMSChange() ) ) / count) ) ); } @@ -1276,7 +1281,7 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > } if ( count != 0 ) { - str->Filter->SetRMSChange( static_cast< double >( vcl_sqrt( ( static_cast< float >( str->Filter-> + str->Filter->SetRMSChange( static_cast< double >( std::sqrt( ( static_cast< float >( str->Filter-> m_RMSChange ) ) / count ) ) ); } @@ -2665,7 +2670,7 @@ ParallelSparseFieldLevelSetImageFilter< TInputImage, TOutputImage > for ( ThreadId = 0; ThreadId < m_NumOfThreads; ThreadId++ ) { os << indent << "ThreadId: " << ThreadId << std::endl; - if ( m_Data != 0 ) + if ( m_Data != ITK_NULLPTR ) { for ( i = 0; i < m_Data[ThreadId].m_Layers.size(); i++ ) { diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkReinitializeLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkReinitializeLevelSetImageFilter.hxx index 59fff4545ba4aeffb64355d338708cfe89a04739..ca56997a3ac32c41eaf85037c55ba59ce2a9a221 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkReinitializeLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkReinitializeLevelSetImageFilter.hxx @@ -39,8 +39,8 @@ ReinitializeLevelSetImageFilter< TLevelSet > m_NarrowBanding = false; m_InputNarrowBandwidth = 12.0; m_OutputNarrowBandwidth = 12.0; - m_InputNarrowBand = NULL; - m_OutputNarrowBand = NULL; + m_InputNarrowBand = ITK_NULLPTR; + m_OutputNarrowBand = ITK_NULLPTR; } /* diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSegmentationLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSegmentationLevelSetImageFilter.hxx index d2b5aaa60200a75020ae53b032e826b558f4074d..cb17025cb2d8a44c9610653b6d1e323211684159 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSegmentationLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSegmentationLevelSetImageFilter.hxx @@ -39,7 +39,7 @@ SegmentationLevelSetImageFilter< TInputImage, TFeatureImage, TOutputPixelType > { this->SetNumberOfRequiredInputs(2); this->SetNumberOfLayers(TInputImage::ImageDimension); - m_SegmentationFunction = 0; + m_SegmentationFunction = ITK_NULLPTR; m_AutoGenerateSpeedAdvection = true; this->SetIsoSurfaceValue(NumericTraits< ValueType >::Zero); @@ -73,7 +73,7 @@ void SegmentationLevelSetImageFilter< TInputImage, TFeatureImage, TOutputPixelType > ::GenerateData() { - if ( m_SegmentationFunction == 0 ) + if ( m_SegmentationFunction == ITK_NULLPTR ) { itkExceptionMacro("No finite difference function was specified."); } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapeDetectionLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapeDetectionLevelSetImageFilter.hxx index c33a3c0cdb3f209dc36836bb52af6e54d6e58756..fcd62a3e73a9c57cb264a7015df6ec2c25a282f4 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapeDetectionLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapeDetectionLevelSetImageFilter.hxx @@ -42,8 +42,7 @@ ShapeDetectionLevelSetImageFilter< TInputImage, TFeatureImage, TOutputType > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - os << indent << "ShapeDetectionFunction: " << std::endl; - m_ShapeDetectionFunction.GetPointer()->Print( os, indent.GetNextIndent() ); + itkPrintSelfObjectMacro( ShapeDetectionFunction ); } template< typename TInputImage, typename TFeatureImage, typename TOutputType > diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorMAPCostFunctionBase.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorMAPCostFunctionBase.h index 9f293336a6f69589f4e4b68479faec5c45dbb618..71f8972af0beb1183444ef40f4174e269a2cfca0 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorMAPCostFunctionBase.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorMAPCostFunctionBase.h @@ -106,15 +106,15 @@ public: /** This method returns the value of the cost function corresponding * to the specified parameters. */ - virtual MeasureType GetValue(const ParametersType & parameters) const; + virtual MeasureType GetValue(const ParametersType & parameters) const ITK_OVERRIDE; /** This method returns the derivative of the cost function corresponding * to the specified parameters. */ - virtual void GetDerivative(const ParametersType &, DerivativeType &) const + virtual void GetDerivative(const ParametersType &, DerivativeType &) const ITK_OVERRIDE { itkExceptionMacro(<< "This function is currently not supported."); } /** Return the number of parameters. */ - virtual unsigned int GetNumberOfParameters(void) const + virtual unsigned int GetNumberOfParameters(void) const ITK_OVERRIDE { return m_ShapeFunction->GetNumberOfParameters(); } /** Compute the inside term component of the MAP cost function. @@ -142,7 +142,7 @@ protected: ShapePriorMAPCostFunctionBase(); virtual ~ShapePriorMAPCostFunctionBase() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; ShapeFunctionPointer m_ShapeFunction; NodeContainerPointer m_ActiveRegion; diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorMAPCostFunctionBase.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorMAPCostFunctionBase.hxx index f588b8f9d89e6b37be2c29b5cbb33f32cef4c405..41ccd06fa7ec096fca64cec73c83428cd7f4ee48 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorMAPCostFunctionBase.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorMAPCostFunctionBase.hxx @@ -29,9 +29,9 @@ template< typename TFeatureImage, typename TOutputPixel > ShapePriorMAPCostFunctionBase< TFeatureImage, TOutputPixel > ::ShapePriorMAPCostFunctionBase() { - m_ShapeFunction = NULL; - m_ActiveRegion = NULL; - m_FeatureImage = NULL; + m_ShapeFunction = ITK_NULLPTR; + m_ActiveRegion = ITK_NULLPTR; + m_FeatureImage = ITK_NULLPTR; } /** diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorSegmentationLevelSetFunction.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorSegmentationLevelSetFunction.hxx index 55d5c8237ff63a41373ccef81445bde80148cea4..dd5ee246187fd08b36c78cd2308b83f2f02f541a 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorSegmentationLevelSetFunction.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorSegmentationLevelSetFunction.hxx @@ -29,7 +29,7 @@ template< typename TImageType, typename TFeatureImageType > ShapePriorSegmentationLevelSetFunction< TImageType, TFeatureImageType > ::ShapePriorSegmentationLevelSetFunction() { - m_ShapeFunction = NULL; + m_ShapeFunction = ITK_NULLPTR; m_ShapePriorWeight = NumericTraits< ScalarValueType >::Zero; } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorSegmentationLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorSegmentationLevelSetImageFilter.hxx index 91602f6b26bc90a36061bcba9e9ada9cdde51c4b..d0bac659b2856507426787240123f45b9661e0bd 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorSegmentationLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkShapePriorSegmentationLevelSetImageFilter.hxx @@ -40,10 +40,10 @@ template< typename TInputImage, typename TFeatureImage, typename TOutputPixelTyp ShapePriorSegmentationLevelSetImageFilter< TInputImage, TFeatureImage, TOutputPixelType > ::ShapePriorSegmentationLevelSetImageFilter() { - m_ShapeFunction = NULL; - m_Optimizer = NULL; - m_CostFunction = NULL; - m_ShapePriorSegmentationFunction = NULL; + m_ShapeFunction = ITK_NULLPTR; + m_Optimizer = ITK_NULLPTR; + m_CostFunction = ITK_NULLPTR; + m_ShapePriorSegmentationFunction = ITK_NULLPTR; } template< typename TInputImage, typename TFeatureImage, typename TOutputPixelType > diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldFourthOrderLevelSetImageFilter.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldFourthOrderLevelSetImageFilter.h index de8f0e95b2b994ac87070defa95bbc80f909fbce..d4ae03d7c96cbcaf07d004da65d406fe4c2e5511 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldFourthOrderLevelSetImageFilter.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldFourthOrderLevelSetImageFilter.h @@ -233,7 +233,7 @@ public: processing band. */ unsigned int GetMinimumNumberOfLayers() const { - return (int)vcl_ceil( m_CurvatureBandWidth + return (int)std::ceil( m_CurvatureBandWidth + itkGetStaticConstMacro(ImageDimension) ); } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldFourthOrderLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldFourthOrderLevelSetImageFilter.hxx index 01abeb25be4b0789c23543383b7fe1246e47528b..120becec18adbfc6bb5c6f1edeaabe208e3ad6bb 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldFourthOrderLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldFourthOrderLevelSetImageFilter.hxx @@ -41,7 +41,7 @@ SparseFieldFourthOrderLevelSetImageFilter< TInputImage, TOutputImage > ::SparseFieldFourthOrderLevelSetImageFilter() { m_RefitIteration = 0; - m_LevelSetFunction = 0; + m_LevelSetFunction = ITK_NULLPTR; m_ConvergenceFlag = false; this->SetIsoSurfaceValue(0); @@ -122,7 +122,7 @@ SparseFieldFourthOrderLevelSetImageFilter< TInputImage, TOutputImage > position -= stride[k]; } } - if ( it.GetPixel (position) == 0 ) + if ( it.GetPixel (position) == ITK_NULLPTR ) { flag = true; } @@ -186,7 +186,7 @@ SparseFieldFourthOrderLevelSetImageFilter< TInputImage, TOutputImage > } else { - if ( node != 0 ) + if ( node != ITK_NULLPTR ) { node->m_CurvatureFlag = false; } @@ -211,7 +211,7 @@ SparseFieldFourthOrderLevelSetImageFilter< TInputImage, TOutputImage > while ( layerIt != this->m_Layers[0]->End() ) { node = im->GetPixel(layerIt->m_Value); - if ( ( node == 0 ) + if ( ( node == ITK_NULLPTR ) || ( node->m_CurvatureFlag == false ) ) { //level set touching edge of normal band diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldLevelSetImageFilter.h b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldLevelSetImageFilter.h index f5d2852b4d99deed485063b4c15e53efcc82dc44..78a2b2996ab6080cbfede0e822b40d426b150063 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldLevelSetImageFilter.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldLevelSetImageFilter.h @@ -32,11 +32,11 @@ namespace itk * lists of indices and other values. * \ingroup ITKLevelSets */ -template< typename TValueType > +template< typename TValue > class SparseFieldLevelSetNode { public: - TValueType m_Value; + TValue m_Value; SparseFieldLevelSetNode *Next; SparseFieldLevelSetNode *Previous; }; diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldLevelSetImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldLevelSetImageFilter.hxx index 1041b24694d55ea4ee18501992315ce3b6fae77b..e42e2827275776005c0adb94634cbde3673a63ff 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldLevelSetImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkSparseFieldLevelSetImageFilter.hxx @@ -128,16 +128,18 @@ SparseFieldLevelSetImageFilter< TInputImage, TOutputImage > template< typename TInputImage, typename TOutputImage > SparseFieldLevelSetImageFilter< TInputImage, TOutputImage > -::SparseFieldLevelSetImageFilter() +::SparseFieldLevelSetImageFilter() : + m_ConstantGradientValue(1.0), + m_NumberOfLayers(2), + m_IsoSurfaceValue(m_ValueZero), + m_InterpolateSurfaceLocation(true), + m_InputImage(ITK_NULLPTR), + m_OutputImage(ITK_NULLPTR), + m_BoundsCheckingActive(false) { - m_IsoSurfaceValue = m_ValueZero; - m_NumberOfLayers = 2; m_LayerNodeStore = LayerNodeStorageType::New(); m_LayerNodeStore->SetGrowthStrategyToExponential(); this->SetRMSChange( static_cast< double >( m_ValueZero ) ); - m_InterpolateSurfaceLocation = true; - m_BoundsCheckingActive = false; - m_ConstantGradientValue = 1.0; } template< typename TInputImage, typename TOutputImage > @@ -482,7 +484,7 @@ SparseFieldLevelSetImageFilter< TInputImage, TOutputImage > } else { - this->SetRMSChange( static_cast< double >( vcl_sqrt( (double)( rms_change_accumulator + this->SetRMSChange( static_cast< double >( std::sqrt( (double)( rms_change_accumulator / static_cast< ValueType >( counter ) ) ) ) ); } } @@ -871,7 +873,7 @@ SparseFieldLevelSetImageFilter< TInputImage, TOutputImage > length += dx_backward * dx_backward; } } - length = vcl_sqrt( (double)length ) + MIN_NORM; + length = std::sqrt( (double)length ) + MIN_NORM; distance = shiftedIt.GetCenterPixel() / length; output->SetPixel( activeIt->m_Value, @@ -1192,8 +1194,7 @@ SparseFieldLevelSetImageFilter< TInputImage, TOutputImage > unsigned int i; os << indent << "m_IsoSurfaceValue: " << m_IsoSurfaceValue << std::endl; - os << indent << "m_LayerNodeStore: " << std::endl; - m_LayerNodeStore->Print( os, indent.GetNextIndent() ); + itkPrintSelfObjectMacro( LayerNodeStore ); os << indent << "m_BoundsCheckingActive: " << m_BoundsCheckingActive; for ( i = 0; i < m_Layers.size(); i++ ) { diff --git a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkVectorThresholdSegmentationLevelSetFunction.hxx b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkVectorThresholdSegmentationLevelSetFunction.hxx index 5713977caad5984cabca1db12563e5a914fa18b6..ec1df61e0c7b1a322b003de9b3118b69e87863d5 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkVectorThresholdSegmentationLevelSetFunction.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSets/include/itkVectorThresholdSegmentationLevelSetFunction.hxx @@ -38,7 +38,7 @@ void VectorThresholdSegmentationLevelSetFunction< TImageType, TFeatureImageType ScalarValueType threshold; for ( fit.GoToBegin(), sit.GoToBegin(); !fit.IsAtEnd(); ++sit, ++fit ) { - threshold = m_Threshold - vcl_sqrt( m_Mahalanobis->Evaluate( fit.Get() ) ); + threshold = m_Threshold - std::sqrt( m_Mahalanobis->Evaluate( fit.Get() ) ); sit.Set( static_cast< ScalarValueType >( threshold ) ); } } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkBinaryImageToLevelSetImageAdaptor.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkBinaryImageToLevelSetImageAdaptor.hxx index e94d8036c05002265214eb0efff4d3e2a8c2a0cd..23f91d520796987e74cde2a5d394e9bd916d3228 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkBinaryImageToLevelSetImageAdaptor.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkBinaryImageToLevelSetImageAdaptor.hxx @@ -139,7 +139,7 @@ BinaryImageToLevelSetImageAdaptor< this->m_LevelSet->SetLabelMap( this->m_LabelMap ); // release the memory - this->m_InternalImage = NULL; + this->m_InternalImage = ITK_NULLPTR; } template< typename TInput, typename TOutput > @@ -463,7 +463,7 @@ void BinaryImageToLevelSetImageAdaptor< TInput, ShiSparseLevelSetImage< TInput:: FindActiveLayer(); this->m_LevelSet->SetLabelMap( this->m_LabelMap ); - this->m_InternalImage = NULL; + this->m_InternalImage = ITK_NULLPTR; } @@ -622,7 +622,7 @@ void BinaryImageToLevelSetImageAdaptor< TInput,MalcolmSparseLevelSetImage< TInpu this->CreateMinimalInterface(); this->m_LevelSet->SetLabelMap( this->m_LabelMap ); - this->m_InternalImage = NULL; + this->m_InternalImage = ITK_NULLPTR; } template< typename TInput > diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkDiscreteLevelSetImage.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkDiscreteLevelSetImage.hxx index 9c8f5b5f84c2dfefc041aa5902828c7abfe53d4a..72062a291c23b7f028c2d70b746008c34fe2d7de 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkDiscreteLevelSetImage.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkDiscreteLevelSetImage.hxx @@ -710,20 +710,7 @@ DiscreteLevelSetImage< TOutput, VDimension > { Superclass::CopyInformation( data ); - const Self *LevelSet = NULL; - - try - { - LevelSet = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - // LevelSet could not be cast back down - itkExceptionMacro( << "itk::DiscreteLevelSetImage::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } - + const Self *LevelSet = dynamic_cast< const Self * >( data ); if ( !LevelSet ) { // pointer could not be cast back down @@ -740,19 +727,7 @@ DiscreteLevelSetImage< TOutput, VDimension > ::Graft( const DataObject* data ) { Superclass::Graft( data ); - const Self *LevelSet = NULL; - - try - { - LevelSet = dynamic_cast< const Self* >( data ); - } - catch( ... ) - { - // image could not be cast back down - itkExceptionMacro( << "itk::DiscreteLevelSetImage::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *LevelSet = dynamic_cast< const Self* >( data ); if ( !LevelSet ) { diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetBase.h b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetBase.h index 9d38798f7d15c499464d4a795d3265323a911c7a..ae05ecbd034492594a665879d0bad8ceec8024c0 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetBase.h +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetBase.h @@ -178,26 +178,26 @@ public: itkGetConstMacro(MaximumNumberOfRegions, RegionType); /** Initialize the level set function */ - virtual void Initialize(); + virtual void Initialize() ITK_OVERRIDE; /** Methods to manage streaming. */ - virtual void UpdateOutputInformation(); + virtual void UpdateOutputInformation() ITK_OVERRIDE; - virtual void SetRequestedRegionToLargestPossibleRegion(); + virtual void SetRequestedRegionToLargestPossibleRegion() ITK_OVERRIDE; - virtual void CopyInformation(const DataObject *data); + virtual void CopyInformation(const DataObject *data) ITK_OVERRIDE; - virtual void Graft(const DataObject *data); + virtual void Graft(const DataObject *data) ITK_OVERRIDE; - virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); + virtual bool RequestedRegionIsOutsideOfTheBufferedRegion() ITK_OVERRIDE; - virtual bool VerifyRequestedRegion(); + virtual bool VerifyRequestedRegion() ITK_OVERRIDE; /** Set the requested region from this data object to match the requested * region of the data object passed in as a parameter. This method * implements the API from DataObject. The data object parameter must be * castable to a PointSet. */ - virtual void SetRequestedRegion( const DataObject *data); + virtual void SetRequestedRegion( const DataObject *data) ITK_OVERRIDE; /** Set/Get the Requested region */ virtual void SetRequestedRegion(const RegionType & region); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetBase.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetBase.hxx index cb0ee71fd777ce00bf24742757af479541dae18d..df326a90d517f85344108742a8ac9d448fd70f01 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetBase.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetBase.hxx @@ -28,8 +28,13 @@ namespace itk template< typename TInput, unsigned int VDimension, typename TOutput, typename TDomain > LevelSetBase< TInput, VDimension, TOutput, TDomain > -::LevelSetBase() - {} +::LevelSetBase() : + m_MaximumNumberOfRegions(0), + m_NumberOfRegions(0), + m_RequestedNumberOfRegions(0), + m_BufferedRegion(0), + m_RequestedRegion(0) +{} // ---------------------------------------------------------------------------- template< typename TInput, unsigned int VDimension, typename TOutput, typename TDomain > @@ -208,19 +213,7 @@ void LevelSetBase< TInput, VDimension, TOutput, TDomain > ::CopyInformation(const DataObject *data) { - const LevelSetBase *levelSet = NULL; - - try - { - levelSet = dynamic_cast< const LevelSetBase * >( data ); - } - catch ( ... ) - { - // pointer could not be cast back down - itkExceptionMacro( << "itk::LevelSetBase::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( LevelSetBase * ).name() ); - } + const LevelSetBase *levelSet = dynamic_cast< const LevelSetBase * >( data ); if ( !levelSet ) { @@ -247,19 +240,7 @@ LevelSetBase< TInput, VDimension, TOutput, TDomain > // Copy Meta Data this->CopyInformation(data); - const Self * levelSet = NULL; - - try - { - levelSet = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - // pointer could not be cast back down - itkExceptionMacro( << "itk::LevelSetBase::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self * levelSet = dynamic_cast< const Self * >( data ); if ( !levelSet ) { diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetContainerBase.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetContainerBase.hxx index e36490579eda89d134a35095c79189b8b6a8b093..5436cea712723792db888037d61696ae70131db9 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetContainerBase.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetContainerBase.hxx @@ -100,7 +100,7 @@ LevelSetContainerBase< TIdentifier, TLevelSet > } else { - return NULL; + return ITK_NULLPTR; } } @@ -151,7 +151,7 @@ LevelSetContainerBase< TIdentifier, TLevelSet > if( it != m_Container.end() ) { - it->second = NULL; + it->second = ITK_NULLPTR; m_Container.erase( it ); this->Modified(); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDenseImage.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDenseImage.hxx index f69772459e75bd7c34b302494bf6cbdb3fe4b3a9..d08bfd9648dcda26cb8e636123bf064cb1d5b872 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDenseImage.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDenseImage.hxx @@ -77,7 +77,7 @@ LevelSetDenseImage< TImage > { Superclass::Initialize(); - this->m_Image = NULL; + this->m_Image = ITK_NULLPTR; } // ---------------------------------------------------------------------------- @@ -88,19 +88,7 @@ LevelSetDenseImage< TImage > { Superclass::CopyInformation( data ); - const Self *LevelSet = NULL; - - try - { - LevelSet = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - // LevelSet could not be cast back down - itkExceptionMacro( << "itk::LevelSetDenseImage::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *LevelSet = dynamic_cast< const Self * >( data ); if ( !LevelSet ) { @@ -118,19 +106,7 @@ LevelSetDenseImage< TImage > ::Graft( const DataObject* data ) { Superclass::Graft( data ); - const Self *LevelSet = NULL; - - try - { - LevelSet = dynamic_cast< const Self* >( data ); - } - catch( ... ) - { - // image could not be cast back down - itkExceptionMacro( << "itk::LevelSetDenseImage::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *LevelSet = dynamic_cast< const Self* >( data ); if ( !LevelSet ) { diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDomainMapImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDomainMapImageFilter.hxx index 0cae2a1aadb55911e7bce115499ca8ad470ae86a..96cd7ba66f3bb66f6cff456c1b3dfa9022e8c51a 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDomainMapImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDomainMapImageFilter.hxx @@ -29,8 +29,8 @@ LevelSetDomainMapImageFilter< TInputImage, TOutputImage > { this->Superclass::SetNumberOfRequiredInputs ( 1 ); this->Superclass::SetNumberOfRequiredOutputs ( 1 ); - this->m_InputImage = 0; - this->m_OutputImage = 0; + this->m_InputImage = ITK_NULLPTR; + this->m_OutputImage = ITK_NULLPTR; } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDomainPartitionImageWithKdTree.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDomainPartitionImageWithKdTree.hxx index d45c5c7e9863dc8211897def98d450a6f2500a3e..f2b47998b44daacc431298b36599147b9164a609 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDomainPartitionImageWithKdTree.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetDomainPartitionImageWithKdTree.hxx @@ -25,7 +25,7 @@ namespace itk template< typename TImage > LevelSetDomainPartitionImageWithKdTree< TImage > ::LevelSetDomainPartitionImageWithKdTree() : - m_KdTree(NULL), m_NumberOfNeighbors( 10 ) + m_KdTree(ITK_NULLPTR), m_NumberOfNeighbors( 10 ) { } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationChanAndVeseExternalTerm.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationChanAndVeseExternalTerm.hxx index a35a930411f29b99ba3f8a1e13b76ca7e2a0ab4d..5187e3df0b9f68b1dae22da23c70e738e5f44a26 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationChanAndVeseExternalTerm.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationChanAndVeseExternalTerm.hxx @@ -29,8 +29,8 @@ LevelSetEquationChanAndVeseExternalTerm< TInput, TLevelSetContainer > { this->m_TermName = "External Chan And Vese term"; this->m_RequiredData.insert( "Value" ); - this->m_DomainMapImageFilter = 0; - this->m_CacheImage = 0; + this->m_DomainMapImageFilter = ITK_NULLPTR; + this->m_CacheImage = ITK_NULLPTR; } template< typename TInput, typename TLevelSetContainer > @@ -58,7 +58,7 @@ void LevelSetEquationChanAndVeseExternalTerm< TInput, TLevelSetContainer > if( this->m_LevelSetContainer->HasDomainMap() ) { - if(this->m_DomainMapImageFilter == 0) + if(this->m_DomainMapImageFilter == ITK_NULLPTR) { this->m_DomainMapImageFilter = this->m_LevelSetContainer->GetModifiableDomainMapFilter(); this->m_CacheImage = this->m_DomainMapImageFilter->GetOutput(); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationOverlapPenaltyTerm.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationOverlapPenaltyTerm.hxx index a087881eb28e138bb6c64636ea705d365c4ddd7e..65c225e7a67077a4b451b0d424e76c49e4504574 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationOverlapPenaltyTerm.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEquationOverlapPenaltyTerm.hxx @@ -30,8 +30,8 @@ LevelSetEquationOverlapPenaltyTerm< TInput, TLevelSetContainer > { this->m_TermName = "Overlap term"; this->m_RequiredData.insert( "" ); - this->m_DomainMapImageFilter = 0; - this->m_CacheImage = 0; + this->m_DomainMapImageFilter = ITK_NULLPTR; + this->m_CacheImage = ITK_NULLPTR; } template< typename TInput, typename TLevelSetContainer > @@ -98,7 +98,7 @@ void LevelSetEquationOverlapPenaltyTerm< TInput, TLevelSetContainer > if( this->m_LevelSetContainer->HasDomainMap() ) { - if(this->m_DomainMapImageFilter == 0) + if(this->m_DomainMapImageFilter == ITK_NULLPTR) { this->m_DomainMapImageFilter = this->m_LevelSetContainer->GetModifiableDomainMapFilter(); this->m_CacheImage = this->m_DomainMapImageFilter->GetOutput(); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolution.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolution.hxx index 6a428bd50ab721d7eb5348836472088ac8bb3fda..27134314b0db3ad16345b398a4a28df4d76a7d58 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolution.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolution.hxx @@ -27,7 +27,8 @@ namespace itk template< typename TEquationContainer, typename TImage > LevelSetEvolution< TEquationContainer, LevelSetDenseImage< TImage > > -::LevelSetEvolution() +::LevelSetEvolution() : + m_IdListToProcessWhenThreading(ITK_NULLPTR) { this->m_SplitLevelSetComputeIterationThreader = SplitLevelSetComputeIterationThreaderType::New(); this->m_SplitDomainMapComputeIterationThreader = SplitDomainMapComputeIterationThreaderType::New(); diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolutionUpdateLevelSetsThreader.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolutionUpdateLevelSetsThreader.hxx index 16e306c41950d0ca1f88f4d9ce1a0ad90946167e..3b0df28ca93dbb05a2a22ebf91c2469e2690dcba 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolutionUpdateLevelSetsThreader.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetEvolutionUpdateLevelSetsThreader.hxx @@ -38,7 +38,7 @@ LevelSetEvolutionUpdateLevelSetsThreader< LevelSetDenseImage< TImage >, Threaded { this->m_RMSChangeAccumulatorPerThread.resize( this->GetNumberOfThreadsUsed() ); - for( ThreadIdType ii = 0; ii < this->GetNumberOfThreadsUsed(); ++ii ) + for( ThreadIdType ii = 0, maxThreads = this->GetNumberOfThreadsUsed(); ii < maxThreads; ++ii ) { this->m_RMSChangeAccumulatorPerThread[ii].ResetToZero(); } @@ -66,10 +66,9 @@ LevelSetEvolutionUpdateLevelSetsThreader< LevelSetDenseImage< TImage >, Threaded levelSetImageIt.GoToBegin(); levelSetUpdateImageIt.GoToBegin(); - LevelSetOutputRealType p; while( !levelSetImageIt.IsAtEnd() ) { - p = this->m_Associate->m_Dt * levelSetUpdateImageIt.Get(); + const LevelSetOutputRealType & p = this->m_Associate->m_Dt * levelSetUpdateImageIt.Get(); levelSetImageIt.Set( levelSetImageIt.Get() + p ); this->m_RMSChangeAccumulatorPerThread[threadId] += p*p; @@ -84,7 +83,7 @@ void LevelSetEvolutionUpdateLevelSetsThreader< LevelSetDenseImage< TImage >, ThreadedImageRegionPartitioner< TImage::ImageDimension >, TLevelSetEvolution > ::AfterThreadedExecution() { - for( ThreadIdType ii = 0; ii < this->GetNumberOfThreadsUsed(); ++ii ) + for( ThreadIdType ii = 0, maxThreads = this->GetNumberOfThreadsUsed(); ii < maxThreads; ++ii ) { this->m_Associate->m_RMSChangeAccumulator += this->m_RMSChangeAccumulatorPerThread[ii].GetSum(); } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetQuadEdgeMesh.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetQuadEdgeMesh.hxx index 471158fc9869e21e55d98aa2d02f649cc13998f9..078609799f3f4ef72e130c01ff89678cbfcf00eb 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetQuadEdgeMesh.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetQuadEdgeMesh.hxx @@ -113,19 +113,7 @@ LevelSetQuadEdgeMesh< TMesh >::CopyInformation(const DataObject *data) { Superclass::CopyInformation( data ); - const Self *levelSet = NULL; - - try - { - levelSet = dynamic_cast< const Self * >( data ); - } - catch ( ... ) - { - // levelSet could not be cast back down - itkExceptionMacro( << "itk::LevelSetQuadEdgeMesh::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *levelSet = dynamic_cast< const Self * >( data ); if ( !levelSet ) { @@ -141,19 +129,7 @@ void LevelSetQuadEdgeMesh< TMesh >::Graft( const DataObject* data ) { Superclass::Graft( data ); - const Self *levelSet = NULL; - - try - { - levelSet = dynamic_cast< const Self* >( data ); - } - catch( ... ) - { - // mesh could not be cast back down - itkExceptionMacro( << "itk::LevelSetQuadEdgeMesh::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *levelSet = dynamic_cast< const Self* >( data ); if ( !levelSet ) { diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetSparseImage.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetSparseImage.hxx index 4c4ca992a60ff96efbf780bf6439981d88e7cd4c..91751e43fd8027758bbca124da29ee661dc31264 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetSparseImage.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkLevelSetSparseImage.hxx @@ -81,19 +81,7 @@ LevelSetSparseImage< TOutput, VDimension > ::Graft( const DataObject* data ) { Superclass::Graft( data ); - const Self *LevelSet = 0; - - try - { - LevelSet = dynamic_cast< const Self* >( data ); - } - catch( ... ) - { - // mesh could not be cast back down - itkExceptionMacro( << "itk::MalcolmSparseLevelSet::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *LevelSet = dynamic_cast< const Self* >( data ); if ( !LevelSet ) { @@ -157,7 +145,7 @@ LevelSetSparseImage< TOutput, VDimension > { Superclass::Initialize(); - this->m_LabelMap = 0; + this->m_LabelMap = ITK_NULLPTR; this->InitializeLayers(); this->InitializeInternalLabelList(); } @@ -170,18 +158,7 @@ LevelSetSparseImage< TOutput, VDimension > { Superclass::CopyInformation( data ); - const Self *LevelSet = NULL; - try - { - LevelSet = dynamic_cast< const Self* >( data ); - } - catch( ... ) - { - // LevelSet could not be cast back down - itkExceptionMacro( << "itk::MalcolmSparseLevelSet::CopyInformation() cannot cast " - << typeid( data ).name() << " to " - << typeid( Self * ).name() ); - } + const Self *LevelSet = dynamic_cast< const Self* >( data ); if ( !LevelSet ) { diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkMalcolmSparseLevelSetImage.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkMalcolmSparseLevelSetImage.hxx index 11b8ada3c3896573fa244479c73208caf91486f5..afad4e87d90f6a9b97f2280fc79e68f50842a044 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkMalcolmSparseLevelSetImage.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkMalcolmSparseLevelSetImage.hxx @@ -76,7 +76,6 @@ MalcolmSparseLevelSetImage< VDimension >::Evaluate( const InputType& inputPixel itkGenericExceptionMacro( <<"status " << static_cast< int >( status ) << " should be 1 or -1" ); - return PlusOneLayer(); } } } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkShiSparseLevelSetImage.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkShiSparseLevelSetImage.hxx index a8e8f5aa958a3434f62f45e31f27b0e9d0f2e609..a2841f7ca5a7bcadbf9a93c1c2ce6b1992dda8d6 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkShiSparseLevelSetImage.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkShiSparseLevelSetImage.hxx @@ -76,7 +76,6 @@ ShiSparseLevelSetImage< VDimension > itkGenericExceptionMacro( <<"status " << static_cast< int >( status ) << " should be 3 or -3" ); - return static_cast<OutputType>( this->PlusThreeLayer() ); } } } diff --git a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkWhitakerSparseLevelSetImage.hxx b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkWhitakerSparseLevelSetImage.hxx index 2174b2a7d4adeed5d9ebb123f2e3c205e399032e..da06d08f8310f5ed6484ca1c4e8d7d3e9d84ce5a 100644 --- a/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkWhitakerSparseLevelSetImage.hxx +++ b/Utilities/ITK/Modules/Segmentation/LevelSetsv4/include/itkWhitakerSparseLevelSetImage.hxx @@ -77,7 +77,6 @@ WhitakerSparseLevelSetImage< TOutput, VDimension > itkGenericExceptionMacro( <<"status " << static_cast< int >( status ) << " should be 3 or -3" ); - return static_cast<OutputType>( this->PlusThreeLayer() ); } } } diff --git a/Utilities/ITK/Modules/Segmentation/MarkovRandomFieldsClassifiers/include/itkMRFImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/MarkovRandomFieldsClassifiers/include/itkMRFImageFilter.hxx index a35dd0675f016e719c657e380b02be8e309d8a0c..c464b0c5620d15e54d34362853fa3f4688751543 100644 --- a/Utilities/ITK/Modules/Segmentation/MarkovRandomFieldsClassifiers/include/itkMRFImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/MarkovRandomFieldsClassifiers/include/itkMRFImageFilter.hxx @@ -32,10 +32,10 @@ MRFImageFilter< TInputImage, TClassifiedImage > m_TotalNumberOfPixelsInInputImage(1), m_ErrorTolerance(0.2), m_SmoothingFactor(1), - m_ClassProbability(0), + m_ClassProbability(ITK_NULLPTR), m_NumberOfIterations(0), m_StopCondition(MaximumNumberOfIterations), - m_ClassifierPtr(0) + m_ClassifierPtr(ITK_NULLPTR) { if ( (int)InputImageDimension != (int)ClassifiedImageDimension ) { diff --git a/Utilities/ITK/Modules/Segmentation/MarkovRandomFieldsClassifiers/include/itkRGBGibbsPriorFilter.hxx b/Utilities/ITK/Modules/Segmentation/MarkovRandomFieldsClassifiers/include/itkRGBGibbsPriorFilter.hxx index 2d45e0a2947790005be38b61ee9b73048797c9f3..5e84f331cebb2293165b137bc9718056b3f48584 100644 --- a/Utilities/ITK/Modules/Segmentation/MarkovRandomFieldsClassifiers/include/itkRGBGibbsPriorFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/MarkovRandomFieldsClassifiers/include/itkRGBGibbsPriorFilter.hxx @@ -32,19 +32,19 @@ namespace itk template< typename TInputImage, typename TClassifiedImage > RGBGibbsPriorFilter< TInputImage, TClassifiedImage > ::RGBGibbsPriorFilter(void): - m_InputImage(0), - m_TrainingImage(0), - m_LabelledImage(0), + m_InputImage(ITK_NULLPTR), + m_TrainingImage(ITK_NULLPTR), + m_LabelledImage(ITK_NULLPTR), m_NumberOfClasses(0), m_MaximumNumberOfIterations(10), - m_ClassifierPtr(0), + m_ClassifierPtr(ITK_NULLPTR), m_BoundaryGradient(7), m_BoundaryWeight(1), m_GibbsPriorWeight(1), m_StartRadius(10), m_RecursiveNumber(0), - m_LabelStatus(0), - m_MediumImage(0), + m_LabelStatus(ITK_NULLPTR), + m_MediumImage(ITK_NULLPTR), m_Temp(0), m_ImageWidth(0), m_ImageHeight(0), @@ -53,8 +53,8 @@ RGBGibbsPriorFilter< TInputImage, TClassifiedImage > m_ObjectLabel(1), m_VecDim(0), m_LowPoint(), - m_Region(NULL), - m_RegionCount(NULL), + m_Region(ITK_NULLPTR), + m_RegionCount(ITK_NULLPTR), m_CliqueWeight_1(0.0), m_CliqueWeight_2(0.0), m_CliqueWeight_3(0.0), @@ -348,7 +348,7 @@ RGBGibbsPriorFilter< TInputImage, TClassifiedImage > { difenergy = energy[label] - energy[1 - label]; double rand_num = (double)( rand() / 32768.0 ); - double energy_num = (double)( vcl_exp( (double)( difenergy * 0.5 * size / ( 2 * size - m_Temp ) ) ) ); + double energy_num = (double)( std::exp( (double)( difenergy * 0.5 * size / ( 2 * size - m_Temp ) ) ) ); if ( rand_num < energy_num ) { m_LabelledImage->SetPixel(offsetIndex3D, 1 - label); diff --git a/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkConfidenceConnectedImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkConfidenceConnectedImageFilter.hxx index 9390822d139b6b9f452e76b17a661c6c592dfd16..df6850d21ef85dcc259d1064969c39def5406b29 100644 --- a/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkConfidenceConnectedImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkConfidenceConnectedImageFilter.hxx @@ -244,8 +244,8 @@ ConfidenceConnectedImageFilter< TInputImage, TOutputImage > m_Variance = ( sumOfSquares - ( sum * sum / double(num) ) ) / ( double(num) - 1.0 ); } - lower = m_Mean - m_Multiplier *vcl_sqrt(m_Variance); - upper = m_Mean + m_Multiplier *vcl_sqrt(m_Variance); + lower = m_Mean - m_Multiplier *std::sqrt(m_Variance); + upper = m_Mean + m_Multiplier *std::sqrt(m_Variance); // Find the highest and lowest seed intensity. InputRealType lowestSeedIntensity = itk::NumericTraits< InputImagePixelType >::max(); @@ -299,7 +299,7 @@ ConfidenceConnectedImageFilter< TInputImage, TOutputImage > itkDebugMacro( << "\nLower intensity = " << lower << ", Upper intensity = " << upper << "\nmean = " << m_Mean - << " , vcl_sqrt(variance) = " << vcl_sqrt(m_Variance) ); + << " , std::sqrt(variance) = " << std::sqrt(m_Variance) ); // Segment the image, the iterator walks the output image (so Set() // writes into the output image), starting at the seed point. As @@ -355,15 +355,15 @@ ConfidenceConnectedImageFilter< TInputImage, TOutputImage > << ", Upper intensity = " << upper << "\nmean = " << m_Mean << ", variance = " << m_Variance - << " , vcl_sqrt(variance) = " << vcl_sqrt(m_Variance) ); + << " , std::sqrt(variance) = " << std::sqrt(m_Variance) ); itkDebugMacro(<< "\nsum = " << sum << ", sumOfSquares = " << sumOfSquares << "\nnumberOfSamples = " << numberOfSamples); break; } - lower = m_Mean - m_Multiplier *vcl_sqrt(m_Variance); - upper = m_Mean + m_Multiplier *vcl_sqrt(m_Variance); + lower = m_Mean - m_Multiplier *std::sqrt(m_Variance); + upper = m_Mean + m_Multiplier *std::sqrt(m_Variance); // Adjust lower and upper to always contain the seed's intensity, otherwise, // no pixels will be @@ -394,7 +394,7 @@ ConfidenceConnectedImageFilter< TInputImage, TOutputImage > << ", Upper intensity = " << upper << "\nmean = " << m_Mean << ", variance = " << m_Variance - << " , vcl_sqrt(variance) = " << vcl_sqrt(m_Variance) ); + << " , std::sqrt(variance) = " << std::sqrt(m_Variance) ); itkDebugMacro(<< "\nsum = " << sum << ", sumOfSquares = " << sumOfSquares << "\nnum = " << numberOfSamples); // Rerun the segmentation, the iterator walks the output image, diff --git a/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkIsolatedConnectedImageFilter.h b/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkIsolatedConnectedImageFilter.h index 7bb5957571410b626bd199a0c3cf5f4c58c3eff7..cf66b632cc03ce1394d61e3ae15907447646f953 100644 --- a/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkIsolatedConnectedImageFilter.h +++ b/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkIsolatedConnectedImageFilter.h @@ -84,7 +84,6 @@ public: /** Run-time type information (and related methods). */ itkTypeMacro(IsolatedConnectedImageFilter, ImageToImageFilter); - typedef TInputImage InputImageType; typedef typename InputImageType::Pointer InputImagePointer; typedef typename InputImageType::ConstPointer InputImageConstPointer; @@ -105,27 +104,34 @@ public: void PrintSelf(std::ostream & os, Indent indent) const; - /** Set seed point 1. This seed will be isolated from Seed2 (if possible). + /** Add seed point 1. This seed will be isolated from Seed2 (if possible). + * All pixels connected to this seed will be replaced with ReplaceValue. */ + void AddSeed1(const IndexType & seed); + +#if ! defined ( ITK_FUTURE_LEGACY_REMOVE ) + /** \deprecated + * Set seed point 1. This seed will be isolated from Seed2 (if possible). * All pixels connected to this seed will be replaced with ReplaceValue. - * This method is deprecated, please use AddSeed() */ + * This method is deprecated, please use AddSeed1(). */ void SetSeed1(const IndexType & seed); +#endif /** Clear all the seeds1. */ void ClearSeeds1(); - /** Add seed point 1. */ - void AddSeed1(const IndexType & seed); + /** Add seed point 2. This seed will be isolated from Seed1 (if possible). */ + void AddSeed2(const IndexType & seed); - /** Set seed point 2. This seed will be isolated from Seed1 (if possible). - * This method is deprecated, please use AddSeed() */ +#if ! defined ( ITK_FUTURE_LEGACY_REMOVE ) + /** \deprecated + * Set seed point 2. This seed will be isolated from Seed1 (if possible). + * This method is deprecated, please use AddSeed2(). */ void SetSeed2(const IndexType & seed); +#endif /** Clear all the seeds2. */ void ClearSeeds2(); - /** Add seed point 2. */ - void AddSeed2(const IndexType & seed); - /** Method to access seed container */ virtual const SeedsContainerType &GetSeeds1() const; virtual const SeedsContainerType &GetSeeds2() const; @@ -140,7 +146,9 @@ public: itkSetMacro(Upper, InputImagePixelType); itkGetConstReferenceMacro(Upper, InputImagePixelType); - /** Set/Get the limit on the upper threshold value. The default is +#if ! defined ( ITK_FUTURE_LEGACY_REMOVE ) + /** \deprecated + * Set/Get the limit on the upper threshold value. The default is the max() for the InputPixelType. These methods have been deprecated. Please use Set/Get Upper instead. */ void SetUpperValueLimit(InputImagePixelType upperValue) @@ -152,6 +160,7 @@ public: { return this->GetUpper(); } +#endif /** Set/Get the precision required for the intensity threshold * value. The default is 1. */ diff --git a/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkIsolatedConnectedImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkIsolatedConnectedImageFilter.hxx index f5425b76986e9b558a3b4f4347892c2d1ef67b8d..b80e10b034a9035f5a51cfef3dcffcf4f64c3cde 100644 --- a/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkIsolatedConnectedImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/RegionGrowing/include/itkIsolatedConnectedImageFilter.hxx @@ -99,6 +99,20 @@ IsolatedConnectedImageFilter< TInputImage, TOutputImage > output->SetRequestedRegionToLargestPossibleRegion(); } +/** Add seed point 1. This seed will be isolated from Seed2 (if possible). */ +template< typename TInputImage, typename TOutputImage > +void +IsolatedConnectedImageFilter< TInputImage, TOutputImage > +::AddSeed1(const IndexType & seed) +{ + this->m_Seeds1.push_back(seed); + this->Modified(); +} + +#if ! defined ( ITK_FUTURE_LEGACY_REMOVE ) +/** \deprecated + * Set seed point 1. This seed will be isolated from Seed2 (if possible). + * This method is deprecated, please use AddSeed1() */ template< typename TInputImage, typename TOutputImage > void IsolatedConnectedImageFilter< TInputImage, TOutputImage > @@ -107,6 +121,7 @@ IsolatedConnectedImageFilter< TInputImage, TOutputImage > this->ClearSeeds1(); this->AddSeed1(seed); } +#endif /** Clear all the seeds1. */ template< typename TInputImage, typename TOutputImage > @@ -121,18 +136,20 @@ IsolatedConnectedImageFilter< TInputImage, TOutputImage > } } -/** Add seed point 1. */ +/** Add seed point 2. This seed will be isolated from Seed1 (if possible). */ template< typename TInputImage, typename TOutputImage > void IsolatedConnectedImageFilter< TInputImage, TOutputImage > -::AddSeed1(const IndexType & seed) +::AddSeed2(const IndexType & seed) { - this->m_Seeds1.push_back(seed); + this->m_Seeds2.push_back(seed); this->Modified(); } -/** Set seed point 2. This seed will be isolated from Seed1 (if possible). - * This method is deprecated, please use AddSeed() */ +#if ! defined ( ITK_FUTURE_LEGACY_REMOVE ) +/** \deprecated + * Set seed point 2. This seed will be isolated from Seed1 (if possible). + * This method is deprecated, please use AddSeed2() */ template< typename TInputImage, typename TOutputImage > void IsolatedConnectedImageFilter< TInputImage, TOutputImage > @@ -141,6 +158,7 @@ IsolatedConnectedImageFilter< TInputImage, TOutputImage > this->ClearSeeds2(); this->AddSeed2(seed); } +#endif /** Clear all the seeds2. */ template< typename TInputImage, typename TOutputImage > @@ -173,16 +191,6 @@ IsolatedConnectedImageFilter< TInputImage, TOutputImage > return this->m_Seeds2; } -/** Add seed point 2. */ -template< typename TInputImage, typename TOutputImage > -void -IsolatedConnectedImageFilter< TInputImage, TOutputImage > -::AddSeed2(const IndexType & seed) -{ - this->m_Seeds2.push_back(seed); - this->Modified(); -} - template< typename TInputImage, typename TOutputImage > void IsolatedConnectedImageFilter< TInputImage, TOutputImage > @@ -231,8 +239,8 @@ IsolatedConnectedImageFilter< TInputImage, TOutputImage > // two sets of seeds. const unsigned int maximumIterationsInBinarySearch = static_cast< unsigned int >( - vcl_log( ( static_cast< float >( upper ) - static_cast< float >( lower ) ) - / static_cast< float >( m_IsolatedValueTolerance ) ) / vcl_log(2.0) ); + std::log( ( static_cast< float >( upper ) - static_cast< float >( lower ) ) + / static_cast< float >( m_IsolatedValueTolerance ) ) / std::log(2.0) ); progressWeight = 1.0f / static_cast< float >( maximumIterationsInBinarySearch + 2 ); cumulatedProgress = 0.0f; @@ -298,8 +306,8 @@ IsolatedConnectedImageFilter< TInputImage, TOutputImage > // two sets of seeds. const unsigned int maximumIterationsInBinarySearch = static_cast< unsigned int >( - vcl_log( ( static_cast< float >( upper ) - static_cast< float >( lower ) ) - / static_cast< float >( m_IsolatedValueTolerance ) ) / vcl_log(2.0) ); + std::log( ( static_cast< float >( upper ) - static_cast< float >( lower ) ) + / static_cast< float >( m_IsolatedValueTolerance ) ) / std::log(2.0) ); progressWeight = 1.0f / static_cast< float >( maximumIterationsInBinarySearch + 2 ); cumulatedProgress = 0.0f; diff --git a/Utilities/ITK/Modules/Segmentation/SignedDistanceFunction/include/itkPCAShapeSignedDistanceFunction.hxx b/Utilities/ITK/Modules/Segmentation/SignedDistanceFunction/include/itkPCAShapeSignedDistanceFunction.hxx index a528f47f51deb5fdfadcebadd91fa30ac9a14bc9..9555a3f5650432afcc1b33fbdf7ab1ff37fc236e 100644 --- a/Utilities/ITK/Modules/Segmentation/SignedDistanceFunction/include/itkPCAShapeSignedDistanceFunction.hxx +++ b/Utilities/ITK/Modules/Segmentation/SignedDistanceFunction/include/itkPCAShapeSignedDistanceFunction.hxx @@ -33,7 +33,7 @@ PCAShapeSignedDistanceFunction< TCoordRep, VSpaceDimension, TImage > m_NumberOfPrincipalComponents = 0; m_NumberOfTransformParameters = 0; - m_MeanImage = NULL; + m_MeanImage = ITK_NULLPTR; m_PrincipalComponentImages.resize(0); m_PrincipalComponentStandardDeviations.SetSize(0); @@ -55,7 +55,7 @@ PCAShapeSignedDistanceFunction< TCoordRep, VSpaceDimension, TImage > { m_NumberOfPrincipalComponents = n; - m_PrincipalComponentImages.resize(n, NULL); + m_PrincipalComponentImages.resize(n, ITK_NULLPTR); m_PrincipalComponentStandardDeviations.SetSize(n); m_PrincipalComponentStandardDeviations.Fill(1.0); diff --git a/Utilities/ITK/Modules/Segmentation/SignedDistanceFunction/include/itkSphereSignedDistanceFunction.hxx b/Utilities/ITK/Modules/Segmentation/SignedDistanceFunction/include/itkSphereSignedDistanceFunction.hxx index 0dbba2bf3a05280d7ef242b8a8e2a35456de15d2..3dd4c0cc1a50983f1fea2d06751e4af9d5a65046 100644 --- a/Utilities/ITK/Modules/Segmentation/SignedDistanceFunction/include/itkSphereSignedDistanceFunction.hxx +++ b/Utilities/ITK/Modules/Segmentation/SignedDistanceFunction/include/itkSphereSignedDistanceFunction.hxx @@ -83,7 +83,7 @@ SphereSignedDistanceFunction< TCoordRep, VSpaceDimension > output += vnl_math_sqr( ( point[j] - m_Translation[j] ) ); } - output = vcl_sqrt(output) - m_Radius; + output = std::sqrt(output) - m_Radius; return output; } diff --git a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiDiagram2DGenerator.h b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiDiagram2DGenerator.h index d9f2e0aca524d136f3127277de12eef68f06ca98..12c95089ad5abe8ce2b65978c79a813482e47f7e 100644 --- a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiDiagram2DGenerator.h +++ b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiDiagram2DGenerator.h @@ -33,7 +33,7 @@ namespace itk * \brief Implement the Sweep Line Algorithm for the construction of the * 2D Voronoi Diagram. * - * Detailed informations of this method can be found in: + * Detailed information on this method can be found in: * "A sweepline algorithm for Voronoi diagrams." * S. Fortune, Algorithmica 2, 153-174, 1987. * @@ -41,10 +41,9 @@ namespace itk * (1) Size of the region. * (2) Seed points coordinates. These coordinates can also be randomly set. * - * Template parameters for VoronoiDiagram2DGenerator: + * \tparam TCoordType The type associated with the coordination of the seeds + * and the resulting vertices. * - * TCoordType: the type associated with the coordination of the seeds and the - * resulting vertices. * \ingroup ITKVoronoi */ template< typename TCoordType > @@ -77,16 +76,20 @@ public: /** Get the number of seed points. */ itkGetConstMacro(NumberOfSeeds, unsigned int); - /** Input the seeds information, will overwrite if seeds already - * exists. */ + /** Set the seed points. + * + * Specify the number of seeds as "num". Will overwrite if seeds already + * exists. + */ void SetSeeds(int num, SeedsIterator begin); - /** Add more seeds at one time. */ + /** Add more seeds. Specify the number of seeds to be added as "num". */ void AddSeeds(int num, SeedsIterator begin); + /** Add one seed. */ void AddOneSeed(PointType); - /** Sort the seeds by ____. */ + /** Sort the seeds with their y, then x, coordinates. */ void SortSeeds(void); /** Produce the output information. */ @@ -95,12 +98,15 @@ public: /** Update the Voronoi Diagram after adding seed(s). */ void UpdateDiagram(void); - /** The boundary that enclose the whole voronoi diagram. */ + /** Set the rectangle that encloses the whole Voronoi Diagram. */ void SetBoundary(PointType vorsize); void SetOrigin(PointType vorsize); - /** Set the seeds points randomly. */ + /** Set the seeds points randomly. + * + * Specify the number of seeds as "num". + */ void SetRandomSeeds(int num); /** Return the given indexed seed. */ @@ -123,46 +129,64 @@ private: OutputType m_OutputVD; SeedsType m_Seeds; + /** Compare point coordinates in the y direction. */ static bool comp(PointType arg1, PointType arg2); /** \class FortuneSite - * Small data structures for Fortune's Method - * and some public variables/methods not for external access. + * \brief Small data structures for Fortune's Method and some public + * variables/methods not for external access. + * * \ingroup ITKVoronoi */ class FortuneSite; class FortuneEdge; class FortuneHalfEdge; - /** All private nested classes must be friend classes to work with SunOS-CC compiler. - * If not, the private nested classes will not be able to access each other. */ + // All private nested classes must be friend classes to work with SunOS-CC + // compiler. If not, the private nested classes will not be able to access + // each other. friend class FortuneSite; friend class FortuneEdge; friend class FortuneHalfEdge; class FortuneSite { -public: + public: PointType m_Coord; int m_Sitenbr; - FortuneSite():m_Sitenbr( NumericTraits< int >::max() ) { m_Coord.Fill( NumericTraits< CoordRepType >::max() ); } + + FortuneSite() : + m_Sitenbr( NumericTraits< int >::max() ) + { + m_Coord.Fill( NumericTraits< CoordRepType >::max() ); + } + ~FortuneSite(){} }; class FortuneEdge { -public: + public: float m_A, m_B, m_C; // explicit line function: Ax + By = C; FortuneSite *m_Ep[2]; FortuneSite *m_Reg[2]; int m_Edgenbr; - FortuneEdge():m_A(0.0), m_B(0.0), m_C(0.0) { m_Ep[0] = m_Ep[1] = m_Reg[0] = m_Reg[1] = 0; } + + FortuneEdge() : + m_A(0.0), + m_B(0.0), + m_C(0.0), + m_Edgenbr(0) + { + m_Ep[0] = m_Ep[1] = m_Reg[0] = m_Reg[1] = ITK_NULLPTR; + } + ~FortuneEdge(){} }; class FortuneHalfEdge { -public: + public: FortuneHalfEdge *m_Left; FortuneHalfEdge *m_Right; FortuneEdge * m_Edge; @@ -170,15 +194,28 @@ public: FortuneSite * m_Vert; double m_Ystar; FortuneHalfEdge *m_Next; - FortuneHalfEdge():m_Left(0), m_Right(0), m_Edge(0), m_RorL(false), m_Vert(0), m_Ystar(0.0), m_Next(0) {} - FortuneHalfEdge(const FortuneHalfEdge & edge):m_Left(edge.m_Left), + + FortuneHalfEdge() : + m_Left(ITK_NULLPTR), + m_Right(ITK_NULLPTR), + m_Edge(ITK_NULLPTR), + m_RorL(false), + m_Vert(ITK_NULLPTR), + m_Ystar(0.0), + m_Next(ITK_NULLPTR) + {} + + FortuneHalfEdge(const FortuneHalfEdge & edge) : + m_Left(edge.m_Left), m_Right(edge.m_Right), m_Edge(edge.m_Edge), m_RorL(edge.m_RorL), m_Vert(edge.m_Vert), m_Ystar(edge.m_Ystar), - m_Next(edge.m_Next) {} - ~FortuneHalfEdge(){} + m_Next(edge.m_Next) + {} + + ~FortuneHalfEdge() {} }; double m_Pxmin; @@ -205,6 +242,9 @@ public: FortuneEdge m_DELETED; std::vector< FortuneSite > m_SeedSites; + /** Methods to convert the result from Fortune Algorithm into itkMesh + * structure. + */ bool differentPoint(PointType p1, PointType p2); bool almostsame(CoordRepType p1, CoordRepType p2); @@ -223,6 +263,10 @@ public: FortuneHalfEdge * ELgethash(int b); + /** Generate Voronoi Diagram using Fortune's Method. (Sweep Line) + * + * Information is stored in m_VertexList, m_EdgeList and m_LineList. + */ bool right_of(FortuneHalfEdge *el, PointType *p); FortuneSite * getRightReg(FortuneHalfEdge *he); diff --git a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiDiagram2DGenerator.hxx b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiDiagram2DGenerator.hxx index 27ae0caf59eef501dc9688e8768e6216f9eaa6a5..9dcb5fa74606e4c9b78b9d33c8cd1cffd50fbf9c 100644 --- a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiDiagram2DGenerator.hxx +++ b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiDiagram2DGenerator.hxx @@ -29,13 +29,24 @@ const double NUMERIC_TOLERENCE = 1.0e-10; const double DIFF_TOLERENCE = 0.001; template< typename TCoordRepType > -VoronoiDiagram2DGenerator< TCoordRepType >::VoronoiDiagram2DGenerator() -{ - m_NumberOfSeeds = 0; - m_Pxmin = 0; - m_Pymin = 0; - m_OutputVD = this->GetOutput(); -} +VoronoiDiagram2DGenerator< TCoordRepType >::VoronoiDiagram2DGenerator() : + m_NumberOfSeeds( 0 ), + m_OutputVD( this->GetOutput() ), + m_Pxmin( 0.0 ), + m_Pxmax( 0.0 ), + m_Pymin( 0.0 ), + m_Pymax( 0.0 ), + m_Deltax( 0.0 ), + m_Deltay( 0.0 ), + m_SqrtNSites( 0.0 ), + m_PQcount( 0 ), + m_PQmin( 0 ), + m_PQhashsize( 0 ), + m_Nedges( 0 ), + m_Nvert( 0 ), + m_BottomSite( ITK_NULLPTR ), + m_ELhashsize( 0 ) +{} template< typename TCoordRepType > VoronoiDiagram2DGenerator< TCoordRepType >:: @@ -51,7 +62,6 @@ VoronoiDiagram2DGenerator< TCoordRepType >::PrintSelf(std::ostream & os, Indent << m_NumberOfSeeds << std::endl; } -/* Set random seed points. Specify the number of seeds as "num". */ template< typename TCoordRepType > void VoronoiDiagram2DGenerator< TCoordRepType >::SetRandomSeeds(int num) @@ -70,7 +80,6 @@ VoronoiDiagram2DGenerator< TCoordRepType >::SetRandomSeeds(int num) m_NumberOfSeeds = num; } -/* Set the seed points. Specify the number of seeds as "num". */ template< typename TCoordRepType > void VoronoiDiagram2DGenerator< TCoordRepType >::SetSeeds(int num, SeedsIterator begin) @@ -84,7 +93,6 @@ VoronoiDiagram2DGenerator< TCoordRepType >::SetSeeds(int num, SeedsIterator beg m_NumberOfSeeds = num; } -/* Set the rectangle that encloses the Voronoi Diagram. */ template< typename TCoordRepType > void VoronoiDiagram2DGenerator< TCoordRepType >::SetBoundary(PointType vorsize) @@ -103,16 +111,19 @@ VoronoiDiagram2DGenerator< TCoordRepType >::SetOrigin(PointType vorsize) m_OutputVD->SetOrigin(vorsize); } -/* Compare point coordinates in the y direction. */ template< typename TCoordRepType > bool VoronoiDiagram2DGenerator< TCoordRepType >::comp(PointType arg1, PointType arg2) { - if ( arg1[1] < arg2[1] ) { return 1; } + if ( arg1[1] < arg2[1] ) + { + return 1; + } else if ( arg1[1] > arg2[1] ) { return 0; } + // arg1[1] == arg2[1] else if ( arg1[0] < arg2[0] ) { return 1; @@ -121,10 +132,13 @@ VoronoiDiagram2DGenerator< TCoordRepType >::comp(PointType arg1, PointType arg2) { return 0; } - else { return 1; } + // arg1[0] == arg2[0] + else + { + return 0; + } } -/* Sort the seeds with their y coordinates. */ template< typename TCoordRepType > void VoronoiDiagram2DGenerator< TCoordRepType >::SortSeeds(void) @@ -132,10 +146,9 @@ VoronoiDiagram2DGenerator< TCoordRepType >::SortSeeds(void) std::sort(m_Seeds.begin(), m_Seeds.end(), comp); } -/* Add seeds. Specify the number of seeds to be added as "num". */ template< typename TCoordRepType > void -VoronoiDiagram2DGenerator< TCoordRepType >::AddSeeds(int num, SeedsIterator begin) +VoronoiDiagram2DGenerator< TCoordRepType >::AddSeeds(int num, SeedsIterator begin) { SeedsIterator ii(begin); @@ -146,7 +159,6 @@ VoronoiDiagram2DGenerator< TCoordRepType >::AddSeeds(int num, SeedsIterator beg m_NumberOfSeeds += num; } -/* Add one seed. */ template< typename TCoordRepType > void VoronoiDiagram2DGenerator< TCoordRepType >::AddOneSeed(PointType inputSeed) @@ -183,9 +195,6 @@ VoronoiDiagram2DGenerator< TCoordRepType >::UpdateDiagram(void) this->GenerateData(); } -/** Methods to convert the result from Fortune Algorithm into - * itkMesh structure. */ - template< typename TCoordRepType > bool VoronoiDiagram2DGenerator< TCoordRepType >::differentPoint(PointType p1, PointType p2) @@ -437,10 +446,6 @@ VoronoiDiagram2DGenerator< TCoordRepType >::ConstructDiagram(void) delete[] rawEdges; } -/** - * Generate Voronoi Diagram using Fortune's Method. (Sweep Line) - * Infomations are stored in m_VertexList, m_EdgeList and m_LineList. */ - template< typename TCoordRepType > bool VoronoiDiagram2DGenerator< TCoordRepType >::right_of(FortuneHalfEdge *el, PointType *p) @@ -496,15 +501,15 @@ VoronoiDiagram2DGenerator< TCoordRepType >::createHalfEdge(FortuneHalfEdge *task { task->m_Edge = e; task->m_RorL = pm; - task->m_Next = NULL; - task->m_Vert = NULL; + task->m_Next = ITK_NULLPTR; + task->m_Vert = ITK_NULLPTR; } template< typename TCoordRepType > void VoronoiDiagram2DGenerator< TCoordRepType >::PQshowMin(PointType *answer) { - while ( ( m_PQHash[m_PQmin].m_Next ) == NULL ) + while ( ( m_PQHash[m_PQmin].m_Next ) == ITK_NULLPTR ) { m_PQmin += 1; } @@ -518,7 +523,7 @@ VoronoiDiagram2DGenerator< TCoordRepType >::deletePQ(FortuneHalfEdge *task) { FortuneHalfEdge *last; - if ( ( task->m_Vert ) != NULL ) + if ( ( task->m_Vert ) != ITK_NULLPTR ) { last = &( m_PQHash[PQbucket(task)] ); while ( ( last->m_Next ) != task ) @@ -527,7 +532,7 @@ VoronoiDiagram2DGenerator< TCoordRepType >::deletePQ(FortuneHalfEdge *task) } last->m_Next = ( task->m_Next ); m_PQcount--; - task->m_Vert = NULL; + task->m_Vert = ITK_NULLPTR; } } @@ -571,7 +576,7 @@ VoronoiDiagram2DGenerator< TCoordRepType >::insertPQ(FortuneHalfEdge *he, Fortun FortuneHalfEdge *last = &( m_PQHash[PQbucket(he)] ); FortuneHalfEdge *enext; - while ( ( ( enext = ( last->m_Next ) ) != NULL ) + while ( ( ( enext = ( last->m_Next ) ) != ITK_NULLPTR ) && ( ( ( he->m_Ystar ) > ( enext->m_Ystar ) ) || ( ( ( he->m_Ystar ) == ( enext->m_Ystar ) ) && ( ( v->m_Coord[0] ) > ( enext->m_Vert->m_Coord[0] ) ) ) ) ) @@ -590,7 +595,7 @@ VoronoiDiagram2DGenerator< TCoordRepType >::dist(FortuneSite *s1, FortuneSite *s double dx = ( s1->m_Coord[0] ) - ( s2->m_Coord[0] ); double dy = ( s1->m_Coord[1] ) - ( s2->m_Coord[1] ); - return ( vcl_sqrt(dx * dx + dy * dy) ); + return ( std::sqrt(dx * dx + dy * dy) ); } template< typename TCoordRepType > @@ -599,14 +604,14 @@ VoronoiDiagram2DGenerator< TCoordRepType >::ELgethash(int b) { if ( ( b < 0 ) || ( b >= static_cast< int >( m_ELhashsize ) ) ) { - return ( NULL ); + return ( ITK_NULLPTR ); } FortuneHalfEdge *he = m_ELHash[b]; - if ( he == NULL ) + if ( he == ITK_NULLPTR ) { return ( he ); } - if ( he->m_Edge == NULL ) + if ( he->m_Edge == ITK_NULLPTR ) { return ( he ); } @@ -614,9 +619,9 @@ VoronoiDiagram2DGenerator< TCoordRepType >::ELgethash(int b) { return ( he ); } - m_ELHash[b] = NULL; + m_ELHash[b] = ITK_NULLPTR; - return ( NULL ); + return ( ITK_NULLPTR ); } template< typename TCoordRepType > @@ -635,12 +640,12 @@ VoronoiDiagram2DGenerator< TCoordRepType >::findLeftHE(PointType *p) bucket = static_cast< int >( m_ELhashsize ) - 1; } FortuneHalfEdge *he = ELgethash(bucket); - if ( he == NULL ) + if ( he == ITK_NULLPTR ) { for ( i = 1; 1; i++ ) { - if ( ( he = ELgethash(bucket - i) ) != NULL ) { break; } - if ( ( he = ELgethash(bucket + i) ) != NULL ) { break; } + if ( ( he = ELgethash(bucket - i) ) != ITK_NULLPTR ) { break; } + if ( ( he = ELgethash(bucket + i) ) != ITK_NULLPTR ) { break; } } } @@ -673,7 +678,7 @@ template< typename TCoordRepType > typename VoronoiDiagram2DGenerator< TCoordRepType >::FortuneSite * VoronoiDiagram2DGenerator< TCoordRepType >::getRightReg(FortuneHalfEdge *he) { - if ( ( he->m_Edge ) == NULL ) + if ( ( he->m_Edge ) == ITK_NULLPTR ) { return ( m_BottomSite ); } @@ -691,7 +696,7 @@ template< typename TCoordRepType > typename VoronoiDiagram2DGenerator< TCoordRepType >::FortuneSite * VoronoiDiagram2DGenerator< TCoordRepType >::getLeftReg(FortuneHalfEdge *he) { - if ( ( he->m_Edge ) == NULL ) + if ( ( he->m_Edge ) == ITK_NULLPTR ) { return ( m_BottomSite ); } @@ -721,8 +726,8 @@ VoronoiDiagram2DGenerator< TCoordRepType >::bisect(FortuneEdge *answer, FortuneS { answer->m_Reg[0] = s1; answer->m_Reg[1] = s2; - answer->m_Ep[0] = NULL; - answer->m_Ep[1] = NULL; + answer->m_Ep[0] = ITK_NULLPTR; + answer->m_Ep[1] = ITK_NULLPTR; double dx = ( s2->m_Coord[0] ) - ( s1->m_Coord[0] ); double dy = ( s2->m_Coord[1] ) - ( s1->m_Coord[1] ); @@ -759,12 +764,12 @@ VoronoiDiagram2DGenerator< TCoordRepType >::intersect(FortuneSite *newV, Fortune FortuneHalfEdge *saveHE; FortuneEdge * saveE; - if ( e1 == NULL ) + if ( e1 == ITK_NULLPTR ) { newV->m_Sitenbr = -1; return; } - if ( e2 == NULL ) + if ( e2 == ITK_NULLPTR ) { newV->m_Sitenbr = -2; return; @@ -825,7 +830,7 @@ template< typename TCoordRepType > void VoronoiDiagram2DGenerator< TCoordRepType >::clip_line(FortuneEdge *task) { -/* clip line */ + /* clip line */ FortuneSite *s1; FortuneSite *s2; double x1, y1, x2, y2; @@ -845,7 +850,7 @@ VoronoiDiagram2DGenerator< TCoordRepType >::clip_line(FortuneEdge *task) int id2; if ( ( task->m_A ) == 1.0 ) { - if ( ( s1 != NULL ) && ( ( s1->m_Coord[1] ) > m_Pymin ) ) + if ( ( s1 != ITK_NULLPTR ) && ( ( s1->m_Coord[1] ) > m_Pymin ) ) { y1 = s1->m_Coord[1]; if ( y1 > m_Pymax ) @@ -862,7 +867,7 @@ VoronoiDiagram2DGenerator< TCoordRepType >::clip_line(FortuneEdge *task) id1 = -1; } - if ( ( s2 != NULL ) && ( ( s2->m_Coord[1] ) < m_Pymax ) ) + if ( ( s2 != ITK_NULLPTR ) && ( ( s2->m_Coord[1] ) < m_Pymax ) ) { y2 = s2->m_Coord[1]; if ( y2 < m_Pymin ) @@ -914,7 +919,7 @@ VoronoiDiagram2DGenerator< TCoordRepType >::clip_line(FortuneEdge *task) } else { - if ( ( s1 != NULL ) && ( ( s1->m_Coord[0] ) > m_Pxmin ) ) + if ( ( s1 != ITK_NULLPTR ) && ( ( s1->m_Coord[0] ) > m_Pxmin ) ) { x1 = s1->m_Coord[0]; if ( x1 > m_Pxmax ) @@ -930,7 +935,7 @@ VoronoiDiagram2DGenerator< TCoordRepType >::clip_line(FortuneEdge *task) y1 = ( task->m_C ) - ( task->m_A ) * x1; id1 = -1; } - if ( ( s2 != NULL ) && ( ( s2->m_Coord[0] ) < m_Pxmax ) ) + if ( ( s2 != ITK_NULLPTR ) && ( ( s2->m_Coord[0] ) < m_Pxmax ) ) { x2 = s2->m_Coord[0]; if ( x2 < m_Pxmin ) @@ -1022,7 +1027,7 @@ void VoronoiDiagram2DGenerator< TCoordRepType >::makeEndPoint(FortuneEdge *task, bool lr, FortuneSite *ends) { task->m_Ep[lr] = ends; - if ( ( task->m_Ep[1 - lr] ) == NULL ) + if ( ( task->m_Ep[1 - lr] ) == ITK_NULLPTR ) { return; } @@ -1043,13 +1048,13 @@ VoronoiDiagram2DGenerator< TCoordRepType >::GenerateVDFortune(void) m_SeedSites[i].m_Coord = m_Seeds[i]; m_SeedSites[i].m_Sitenbr = i; } -/* Initialize Boundary. */ + /* Initialize Boundary. */ m_Pxmax = m_VorBoundary[0]; m_Pymax = m_VorBoundary[1]; m_Deltay = m_Pymax - m_Pymin; m_Deltax = m_Pxmax - m_Pxmin; - m_SqrtNSites = vcl_sqrt( (float)( m_NumberOfSeeds + 4 ) ); + m_SqrtNSites = std::sqrt( (float)( m_NumberOfSeeds + 4 ) ); /* Initialize outputLists. */ m_Nedges = 0; @@ -1065,20 +1070,20 @@ VoronoiDiagram2DGenerator< TCoordRepType >::GenerateVDFortune(void) m_PQHash.resize(m_PQhashsize); for ( i = 0; i < m_PQhashsize; i++ ) { - m_PQHash[i].m_Next = NULL; + m_PQHash[i].m_Next = ITK_NULLPTR; } m_ELhashsize = (int)( 2 * m_SqrtNSites ); m_ELHash.resize(m_ELhashsize); for ( i = 0; i < m_ELhashsize; i++ ) { - m_ELHash[i] = NULL; + m_ELHash[i] = ITK_NULLPTR; } - createHalfEdge(&( m_ELleftend ), NULL, 0); - createHalfEdge(&( m_ELrightend ), NULL, 0); - m_ELleftend.m_Left = NULL; + createHalfEdge(&( m_ELleftend ), ITK_NULLPTR, 0); + createHalfEdge(&( m_ELrightend ), ITK_NULLPTR, 0); + m_ELleftend.m_Left = ITK_NULLPTR; m_ELleftend.m_Right = &( m_ELrightend ); m_ELrightend.m_Left = &( m_ELleftend ); - m_ELrightend.m_Right = NULL; + m_ELrightend.m_Right = ITK_NULLPTR; m_ELHash[0] = &( m_ELleftend ); m_ELHash[m_ELhashsize - 1] = &( m_ELrightend ); diff --git a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiPartitioningImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiPartitioningImageFilter.hxx index 936598ae26cf7ed79d4125a02736e83fa78b3f75..23fbd653609ab4a9975c1aa604edc41438185603 100644 --- a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiPartitioningImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiPartitioningImageFilter.hxx @@ -187,7 +187,7 @@ VoronoiPartitioningImageFilter< TInputImage, TOutputImage > double savevar; if ( num > 1 ) { - savevar = vcl_sqrt( ( addpp - ( addp * addp ) / static_cast< double >( num ) ) + savevar = std::sqrt( ( addpp - ( addp * addp ) / static_cast< double >( num ) ) / ( static_cast< double >( num ) - 1.0 ) ); } else @@ -195,7 +195,7 @@ VoronoiPartitioningImageFilter< TInputImage, TOutputImage > savevar = -1; } - return ( savevar >= 0 && vcl_sqrt(savevar) < m_SigmaThreshold ); + return ( savevar >= 0 && std::sqrt(savevar) < m_SigmaThreshold ); } template< typename TInputImage, typename TOutputImage > diff --git a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationImageFilter.hxx index 61f93ba00530ff1b1c1e040b8c58a7e74f3a5844..30be6bfbad238ba702cdbcb3647b3d0553a343ff 100644 --- a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationImageFilter.hxx @@ -81,7 +81,7 @@ VoronoiSegmentationImageFilter< TInputImage, TOutputImage, TBinaryPriorImage > if ( num > 1 ) { savemean = addp / num; - saveSTD = vcl_sqrt( ( addpp - ( addp * addp ) / ( num ) ) / ( num - 1 ) ); + saveSTD = std::sqrt( ( addpp - ( addp * addp ) / ( num ) ) / ( num - 1 ) ); } else { @@ -90,7 +90,7 @@ VoronoiSegmentationImageFilter< TInputImage, TOutputImage, TBinaryPriorImage > } // // jvm - Mahalanobis distance - // if (savevar > 0 && vcl_fabs(savemean - m_Mean) / m_Var < 2.5) + // if (savevar > 0 && std::fabs(savemean - m_Mean) / m_Var < 2.5) // return true; // else // return false; @@ -197,12 +197,12 @@ VoronoiSegmentationImageFilter< TInputImage, TOutputImage, TBinaryPriorImage > } m_Mean = addp / num; - m_STD = vcl_sqrt( ( addpp - ( addp * addp ) / num ) / ( num - 1 ) ); + m_STD = std::sqrt( ( addpp - ( addp * addp ) / num ) / ( num - 1 ) ); float b_Mean = addb / numb; if ( this->GetUseBackgroundInAPrior() ) { - m_MeanTolerance = vcl_fabs(m_Mean - b_Mean) * this->GetMeanDeviation(); + m_MeanTolerance = std::fabs(m_Mean - b_Mean) * this->GetMeanDeviation(); } else { diff --git a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationImageFilterBase.hxx b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationImageFilterBase.hxx index f03882b75f5257d5892d0e16af4d73b8515af666..42fa02d9f3694df7f04e23364546e07fd4f2b4b2 100644 --- a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationImageFilterBase.hxx +++ b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationImageFilterBase.hxx @@ -29,20 +29,21 @@ namespace itk /* Constructor: setting the default parameter values. */ template< typename TInputImage, typename TOutputImage, typename TBinaryPriorImage > VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage > -::VoronoiSegmentationImageFilterBase() +::VoronoiSegmentationImageFilterBase() : + m_NumberOfSeeds(200), + m_MinRegion(20), + m_Steps(0), + m_LastStepSeeds(0), + m_NumberOfSeedsToAdded(0), + m_NumberOfBoundary(0), + m_MeanDeviation(0.8), + m_UseBackgroundInAPrior(false), + m_OutputBoundary(false), + m_InteractiveSegmentation(false), + m_WorkingVD(VoronoiDiagram::New()), + m_VDGenerator(VoronoiDiagramGenerator::New()) { m_Size.Fill(0); - m_MinRegion = 20; - m_Steps = 0; - m_LastStepSeeds = 0; - m_NumberOfSeeds = 200; - m_NumberOfSeedsToAdded = 0; - m_MeanDeviation = 0.8; - m_UseBackgroundInAPrior = false; - m_OutputBoundary = false; - m_InteractiveSegmentation = false; - m_WorkingVD = VoronoiDiagram::New(); - m_VDGenerator = VoronoiDiagramGenerator::New(); } /* Destructor. */ @@ -125,7 +126,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage rightP = vertlist.back(); double beginy = currP[1]; - int intbeginy = (int)vcl_ceil(beginy); + int intbeginy = (int)std::ceil(beginy); idx[1] = intbeginy; double leftendy = leftP[1]; double rightendy = rightP[1]; @@ -169,7 +170,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage rightDx = ( rightP[0] - endx ) / ( rightP[1] - beginy ); } - int intendy = (int)vcl_floor(endy); + int intendy = (int)std::floor(endy); if ( intbeginy > intendy ) { //no scanline if ( RorL ) @@ -191,7 +192,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage { beginx = leftP[0]; } - for ( i = static_cast< int >( vcl_ceil(beginx) ); i <= static_cast< int >( vcl_floor(endx) ); i++ ) + for ( i = static_cast< int >( std::ceil(beginx) ); i <= static_cast< int >( std::floor(endx) ); i++ ) { idx[0] = i; ( *PixelPool ).push_back(idx); @@ -205,7 +206,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage beginx += offset * leftDx; while ( idx[1] <= intendy ) { - for ( i = static_cast< int >( vcl_ceil(beginx) ); i <= static_cast< int >( vcl_floor(endx) ); i++ ) + for ( i = static_cast< int >( std::ceil(beginx) ); i <= static_cast< int >( std::floor(endx) ); i++ ) { idx[0] = i; ( *PixelPool ).push_back(idx); @@ -271,8 +272,8 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage endy = leftendy; } - intendy = (int)vcl_floor(endy); - intbeginy = (int)vcl_ceil(beginy); + intendy = (int)std::floor(endy); + intbeginy = (int)std::ceil(beginy); if ( intbeginy > intendy ) { //no scanline @@ -292,7 +293,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage beginx += offset * leftDx; while ( idx[1] <= intendy ) { - for ( i = static_cast< int >( vcl_ceil(beginx) ); i <= static_cast< int >( vcl_floor(endx) ); i++ ) + for ( i = static_cast< int >( std::ceil(beginx) ); i <= static_cast< int >( std::floor(endx) ); i++ ) { idx[0] = i; ( *PixelPool ).push_back(idx); @@ -315,8 +316,8 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage beginy = leftP[1]; endy = rightP[1]; } - intbeginy = (int)vcl_ceil(beginy); - intendy = (int)vcl_floor(endy); + intbeginy = (int)std::ceil(beginy); + intendy = (int)std::floor(endy); if ( intbeginy <= intendy ) { if ( RorL ) @@ -350,7 +351,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage endx += offset * rightDx; while ( idx[1] <= intendy ) { - for ( i = static_cast< int >( vcl_ceil(beginx) ); i <= static_cast< int >( vcl_floor(endx) ); i++ ) + for ( i = static_cast< int >( std::ceil(beginx) ); i <= static_cast< int >( std::floor(endx) ); i++ ) { idx[0] = i; ( *PixelPool ).push_back(idx); @@ -689,7 +690,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage rightP = vertlist.back(); double beginy = currP[1]; - int intbeginy = (int)vcl_ceil(beginy); + int intbeginy = (int)std::ceil(beginy); idx[1] = intbeginy; double leftendy = leftP[1]; double rightendy = rightP[1]; @@ -731,7 +732,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage { rightDx = ( rightP[0] - endx ) / ( rightP[1] - beginy ); } - int intendy = (int)vcl_floor(endy); + int intendy = (int)std::floor(endy); if ( intbeginy > intendy ) { //no scanline if ( RorL ) @@ -753,7 +754,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage { beginx = leftP[0]; } - for ( i = static_cast< int >( vcl_ceil(beginx) ); i <= static_cast< int >( vcl_floor(endx) ); i++ ) + for ( i = static_cast< int >( std::ceil(beginx) ); i <= static_cast< int >( std::floor(endx) ); i++ ) { idx[0] = i; output->SetPixel(idx, color); @@ -767,7 +768,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage beginx += offset * leftDx; while ( idx[1] <= intendy ) { - for ( i = static_cast< int >( vcl_ceil(beginx) ); i <= static_cast< int >( vcl_floor(endx) ); i++ ) + for ( i = static_cast< int >( std::ceil(beginx) ); i <= static_cast< int >( std::floor(endx) ); i++ ) { idx[0] = i; output->SetPixel(idx, color); @@ -833,8 +834,8 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage endy = leftendy; } - intendy = (int)vcl_floor(endy); - intbeginy = (int)vcl_ceil(beginy); + intendy = (int)std::floor(endy); + intbeginy = (int)std::ceil(beginy); if ( intbeginy > intendy ) { //no scanline @@ -854,7 +855,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage beginx += offset * leftDx; while ( idx[1] <= intendy ) { - for ( i = static_cast< int >( vcl_ceil(beginx) ); i <= static_cast< int >( vcl_floor(endx) ); i++ ) + for ( i = static_cast< int >( std::ceil(beginx) ); i <= static_cast< int >( std::floor(endx) ); i++ ) { idx[0] = i; output->SetPixel(idx, color); @@ -877,8 +878,8 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage beginy = leftP[1]; endy = rightP[1]; } - intbeginy = (int)vcl_ceil(beginy); - intendy = (int)vcl_floor(endy); + intbeginy = (int)std::ceil(beginy); + intendy = (int)std::floor(endy); if ( intbeginy <= intendy ) { if ( RorL ) @@ -912,7 +913,7 @@ VoronoiSegmentationImageFilterBase< TInputImage, TOutputImage, TBinaryPriorImage endx += offset * rightDx; while ( idx[1] <= intendy ) { - for ( i = static_cast< int >( vcl_ceil(beginx) ); i <= static_cast< int >( vcl_floor(endx) ); i++ ) + for ( i = static_cast< int >( std::ceil(beginx) ); i <= static_cast< int >( std::floor(endx) ); i++ ) { idx[0] = i; output->SetPixel(idx, color); diff --git a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationRGBImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationRGBImageFilter.hxx index 10884712eb18a26953fb3d65d0e5276d1582e6e5..16014fe2a5aec4451ca416badea89dce9ab44bff 100644 --- a/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationRGBImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/Voronoi/include/itkVoronoiSegmentationRGBImageFilter.hxx @@ -62,7 +62,7 @@ VoronoiSegmentationRGBImageFilter< TInputImage, TOutputImage >::SetMeanPercentEr for ( unsigned int i = 0; i < 6; i++ ) { m_MeanPercentError[i] = x[i]; - m_MeanTolerance[i] = vcl_fabs(x[i] * m_Mean[i]); + m_MeanTolerance[i] = std::fabs(x[i] * m_Mean[i]); } } @@ -132,22 +132,22 @@ VoronoiSegmentationRGBImageFilter< TInputImage, TOutputImage > X = 0.607 * ipixel[0] + 0.174 * ipixel[1] + 0.201 * ipixel[2]; Y = 0.299 * ipixel[0] + 0.587 * ipixel[1] + 0.114 * ipixel[2]; Z = 0.066 * ipixel[1] + 1.117 * ipixel[2]; - X = vcl_pow( ( X / X0 ), 0.3333 ); - Y = vcl_pow( ( Y / Y0 ), 0.3333 ); - Z = vcl_pow( ( Z / Z0 ), 0.3333 ); + X = std::pow( ( X / X0 ), 0.3333 ); + Y = std::pow( ( Y / Y0 ), 0.3333 ); + Z = std::pow( ( Z / Z0 ), 0.3333 ); L = 116 * Y - 16; a = 500 * ( X - Y ); b = 200 * ( Y - Z ); if ( b != 0.0 ) { - wpixel[3] = vcl_atan2(b, a); //H + wpixel[3] = std::atan2(b, a); //H } else { wpixel[3] = 0; } - wpixel[4] = vcl_sqrt(a * a + b * b); //C + wpixel[4] = std::sqrt(a * a + b * b); //C wpixel[5] = L; //V wit.Set(wpixel); ++wit; @@ -181,7 +181,7 @@ VoronoiSegmentationRGBImageFilter< TInputImage, TOutputImage >::TestHomogeneity( for ( i = 0; i < 6; i++ ) { savemean[i] = addp[i] / num; - saveSTD[i] = vcl_sqrt( ( addpp[i] - ( addp[i] * addp[i] ) / ( num ) ) / ( num - 1 ) ); + saveSTD[i] = std::sqrt( ( addpp[i] - ( addp[i] * addp[i] ) / ( num ) ) / ( num - 1 ) ); } } else @@ -320,21 +320,57 @@ VoronoiSegmentationRGBImageFilter< TInputImage, TOutputImage >::TakeAPrior(const for ( unsigned int i = 0; i < 6; i++ ) { m_Mean[i] = objaddp[i] / objnum; - m_STD[i] = vcl_sqrt( ( objaddpp[i] - ( objaddp[i] * objaddp[i] ) / objnum ) / ( objnum - 1 ) ); + m_STD[i] = std::sqrt( ( objaddpp[i] - ( objaddp[i] * objaddp[i] ) / objnum ) / ( objnum - 1 ) ); m_STDTolerance[i] = m_STD[i] * m_STDPercentError[i]; - b_Mean[i] = bkgaddp[i] / bkgnum; - b_STD[i] = vcl_sqrt( ( bkgaddpp[i] - ( bkgaddp[i] * bkgaddp[i] ) / bkgnum ) / ( bkgnum - 1 ) ); - diffMean[i] = ( b_Mean[i] - m_Mean[i] ) / m_Mean[i]; - if ( diffMean[i] < 0 ) { diffMean[i] = -diffMean[i]; } - diffSTD[i] = ( b_STD[i] - m_STD[i] ) / m_STD[i]; - if ( diffSTD[i] < 0 ) { diffSTD[i] = -diffSTD[i]; } + if (bkgnum > 0) + { + b_Mean[i] = bkgaddp[i] / bkgnum; + } + else + { + b_Mean[i] = 0.0; + } + if (bkgnum > 1) + { + b_STD[i] = + std::sqrt( ( bkgaddpp[i] - ( bkgaddp[i] * bkgaddp[i] ) / bkgnum ) + / ( bkgnum - 1 ) ); + } + else + { + b_STD[i] = 0.0; + } + if (m_Mean[i] != 0.0) + { + diffMean[i] = ( b_Mean[i] - m_Mean[i] ) / m_Mean[i]; + } + else + { + diffMean[i] = 0.0; + } + if ( diffMean[i] < 0 ) + { + diffMean[i] = -diffMean[i]; + } + if (m_STD[i] != 0.0) + { + diffSTD[i] = ( b_STD[i] - m_STD[i] ) / m_STD[i]; + } + else + { + diffSTD[i] = 0.0; + } + if ( diffSTD[i] < 0 ) + { + diffSTD[i] = -diffSTD[i]; + } if ( this->GetUseBackgroundInAPrior() ) { m_MeanTolerance[i] = diffMean[i] * m_Mean[i] * this->GetMeanDeviation(); } else { - m_MeanTolerance[i] = vcl_fabs(m_Mean[i] * m_MeanPercentError[i]); + m_MeanTolerance[i] = std::fabs(m_Mean[i] * m_MeanPercentError[i]); } } diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkIsolatedWatershedImageFilter.hxx b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkIsolatedWatershedImageFilter.hxx index 453f5e45bd87619ecf838d303d7e3f85e1efea2c..9753044cb412a0c7e625c3844105244ca3fe9b28 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkIsolatedWatershedImageFilter.hxx +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkIsolatedWatershedImageFilter.hxx @@ -123,8 +123,8 @@ IsolatedWatershedImageFilter< TInputImage, TOutputImage > const unsigned int maximumIterationsInBinarySearch = static_cast< unsigned int >( - vcl_log( ( static_cast< float >( upper ) - static_cast< float >( lower ) ) - / static_cast< float >( m_IsolatedValueTolerance ) ) / vcl_log(2.0) ); + std::log( ( static_cast< float >( upper ) - static_cast< float >( lower ) ) + / static_cast< float >( m_IsolatedValueTolerance ) ) / std::log(2.0) ); const float progressWeight = 1.0f / static_cast< float >( maximumIterationsInBinarySearch + 2 ); float cumulatedProgress = 0.0f; diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkOneWayEquivalencyTable.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkOneWayEquivalencyTable.h index a2cc406c43c3ac079c9f26ee9432c9a8c27277f3..461e96f874dcf7c1131b5e7c2b06ee3efa119708 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkOneWayEquivalencyTable.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkOneWayEquivalencyTable.h @@ -129,7 +129,7 @@ protected: OneWayEquivalencyTable(const Self &); // purposely not implemented void operator=(const Self &); // purposely not implemented - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; HashTableType m_HashMap; }; diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedBoundary.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedBoundary.h index 8f525fd0cd2d71d8d46a7640a2b0c83e98beeb65..e931e304c9050021502b3a0214f19799e389335e 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedBoundary.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedBoundary.h @@ -200,7 +200,7 @@ protected: virtual ~Boundary() {} Boundary(const Self &) {} void operator=(const Self &) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** The Nx2 matrix of faces of this boundary. */ std::vector< std::pair< FacePointer, FacePointer > > m_Faces; diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedBoundaryResolver.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedBoundaryResolver.h index 9c641b0c366d2f3887a236c0778295a0d2ab84e0..b541ff244e09fefccb0a11375c50581cb31a73f3 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedBoundaryResolver.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedBoundaryResolver.h @@ -111,12 +111,12 @@ public: } /** Standard non-threaded pipeline method */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Standard itk::ProcessObject subclass method. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; protected: BoundaryResolver():m_Face(0) @@ -131,10 +131,10 @@ protected: virtual ~BoundaryResolver() {} BoundaryResolver(const Self &) {} void operator=(const Self &) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; unsigned short m_Face; - void GenerateOutputRequestedRegion(DataObject *output); + virtual void GenerateOutputRequestedRegion(DataObject *output) ITK_OVERRIDE; }; } // end namespace watershed } // end namespace itk diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedEquivalenceRelabeler.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedEquivalenceRelabeler.h index 6ee1936590e0444a6cd79122b8bad8dde524ce11..3439482a9f34c44cc20c232104c63af167446b43 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedEquivalenceRelabeler.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedEquivalenceRelabeler.h @@ -106,12 +106,12 @@ public: } /** Standard non-threaded pipeline method */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Standard itk::ProcessObject subclass method. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; protected: EquivalenceRelabeler() @@ -125,11 +125,11 @@ protected: virtual ~EquivalenceRelabeler() {} EquivalenceRelabeler(const Self &) {} void operator=(const Self &) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; - void GenerateOutputRequestedRegion(DataObject *output); + virtual void GenerateOutputRequestedRegion(DataObject *output) ITK_OVERRIDE; - void GenerateInputRequestedRegion(); + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; }; } // end namespace watershed } // end namespace itk diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedMiniPipelineProgressCommand.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedMiniPipelineProgressCommand.h index e41365ad156bb7f36664b27271a9f2893334c387..ab49fd379bf4a8c08eab992caa027c17f7ae28b5 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedMiniPipelineProgressCommand.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedMiniPipelineProgressCommand.h @@ -42,9 +42,9 @@ public: itkNewMacro(Self); /** Standard Command virtual methods */ - void Execute(Object *caller, const EventObject & event); + virtual void Execute(Object *caller, const EventObject & event) ITK_OVERRIDE; - void Execute(const Object *caller, const EventObject & event); + virtual void Execute(const Object *caller, const EventObject & event) ITK_OVERRIDE; /** Set/Get the filter whose UpdateProgress will be set by this * command object */ @@ -63,10 +63,10 @@ public: itkGetConstMacro(NumberOfFilters, double); protected: - WatershedMiniPipelineProgressCommand():m_Count(0.0), m_Filter(NULL), + WatershedMiniPipelineProgressCommand():m_Count(0.0), m_Filter(ITK_NULLPTR), m_NumberOfFilters(1.0) {} virtual ~WatershedMiniPipelineProgressCommand() {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: double m_Count; diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedRelabeler.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedRelabeler.h index ed0d2844b7e77f79e0d892e68271cdc03ea10b31..d0f9efc122b8ea3df5c7052fad42918a9b36feb4 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedRelabeler.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedRelabeler.h @@ -88,7 +88,7 @@ public: /** Standard itk::ProcessObject subclass method. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** Set/Get the input image */ void SetInputImage(ImageType *img) @@ -127,7 +127,7 @@ public: } /** Standard non-threaded pipeline method */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Set/Get the percentage of the maximum saliency level * to merge to. */ @@ -144,12 +144,12 @@ protected: virtual ~Relabeler() {} Relabeler(const Self &) {} void operator=(const Self &) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; double m_FloodLevel; - void GenerateOutputRequestedRegion(DataObject *output); + virtual void GenerateOutputRequestedRegion(DataObject *output) ITK_OVERRIDE; - void GenerateInputRequestedRegion(); + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; }; } // end namespace watershed } // end namespace itk diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTable.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTable.h index 615c06ee14bac4e4d06d527053f02b7d32cfb8f6..4425bb8bb498835207bd4242805f33eec52e2343 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTable.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTable.h @@ -112,7 +112,7 @@ public: { Iterator result = m_HashMap.find(a); - if ( result == m_HashMap.end() ) { return 0; } + if ( result == m_HashMap.end() ) { return ITK_NULLPTR; } else { return &( ( *result ).second ); } } @@ -203,7 +203,9 @@ public: } protected: - SegmentTable() {} + SegmentTable() : + m_MaximumDepth(0) + {} virtual ~SegmentTable() {} HashMapType m_HashMap; diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTree.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTree.h index cad29a22ce7cd901ca9d4d624a9d504203970e6e..f3fe9986b70c3a4c2afcf140221bf9ea477d3d1d 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTree.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTree.h @@ -157,14 +157,14 @@ public: /** Standard DataObject routine to initialize. Returns the segment * tree to a default state, deallocating memory. */ - void Initialize(); + virtual void Initialize() ITK_OVERRIDE; protected: SegmentTree() {} virtual ~SegmentTree() {} SegmentTree(const Self &) {} void operator=(const Self &) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; DequeType m_Deque; }; diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTreeGenerator.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTreeGenerator.h index e91234db703de34a6a1e7f0d128fdb2db19462d1..55681ef82e791fde4f3ba404ab12bea317617872 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTreeGenerator.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTreeGenerator.h @@ -140,7 +140,7 @@ public: } /** Standard non-threaded itk pipeline method */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** Get/Set a boolean flag indicating whether or not to pre-merge the segments marked as equivalent in the EquivalencyTable. This is only @@ -190,14 +190,14 @@ public: /** Standard itk::ProcessObject subclass method. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; protected: SegmentTreeGenerator(); virtual ~SegmentTreeGenerator() {} SegmentTreeGenerator(const Self &) {} void operator=(const Self &) {} - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Generates an initial list of all potentential merges in * the segment table. */ @@ -210,9 +210,9 @@ protected: void MergeEquivalencies(); /** Methods required by the itk pipeline */ - void GenerateOutputRequestedRegion(DataObject *output); + virtual void GenerateOutputRequestedRegion(DataObject *output) ITK_OVERRIDE; - void GenerateInputRequestedRegion(); + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; private: bool m_Merge; diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTreeGenerator.hxx b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTreeGenerator.hxx index 80e2eabc9bb23c0aaf3f6061f753bb613baeea61..df8ca709134a01e09f5ae3e750aa7eadb0098764 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTreeGenerator.hxx +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmentTreeGenerator.hxx @@ -430,7 +430,7 @@ void SegmentTreeGenerator< TScalar > typename SegmentTableType::segment_t * from_seg = segments->Lookup(FROM); typename SegmentTableType::segment_t * to_seg = segments->Lookup(TO); - if ( from_seg == 0 || to_seg == 0 ) + if ( from_seg == ITK_NULLPTR || to_seg == ITK_NULLPTR ) { itkGenericExceptionMacro ( << diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmenter.h b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmenter.h index da99754b74524a556d5137c0f8d76669783f553a..887584cb4193d41f541abd447f6875e5c36c7314 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmenter.h +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmenter.h @@ -172,7 +172,7 @@ public: { this->ProcessObject::SetNthOutput(2, b); } /** Standard non-threaded pipeline execution method. */ - void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** This method is necessary until the streaming mechanisms of the Itk * pipeline are full fleshed out. It is only used for streaming @@ -199,7 +199,7 @@ public: /** Standard itk::ProcessObject subclass method. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; /** Gets/Sets the initial label (IdentifierType integer value) used * by the labeling algorithm. Only necessary for streaming applications. */ @@ -267,7 +267,7 @@ protected: Segmenter(); Segmenter(const Self &) {} virtual ~Segmenter(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; void operator=(const Self &) {} @@ -278,11 +278,11 @@ protected: /** This method asks for an image region that is one pixel larger * at each boundary than the region being processed. This single pixel * expansion represents an overlap with adjacent image chunks */ - void GenerateInputRequestedRegion(); + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; - void GenerateOutputRequestedRegion(DataObject *output); + virtual void GenerateOutputRequestedRegion(DataObject *output) ITK_OVERRIDE; - void UpdateOutputInformation(); + virtual void UpdateOutputInformation() ITK_OVERRIDE; /** Allocates boundary structure information and sets the * boundary data to null values. */ diff --git a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmenter.hxx b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmenter.hxx index 3ecc961a30e7f9bbce89edb5936c0df0e5bdfb82..7c823cc96822c2786aaccd233695270561632818 100644 --- a/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmenter.hxx +++ b/Utilities/ITK/Modules/Segmentation/Watersheds/include/itkWatershedSegmenter.hxx @@ -325,7 +325,6 @@ void Segmenter< TInputImage > ImageRegionIterator< OutputImageType > labelIt; typename BoundaryType::face_t::Pointer face; - typedef typename BoundaryType::flat_hash_t flats_t; typename BoundaryType::flat_hash_t * flats; typename BoundaryType::flat_hash_t::iterator flats_it; typename BoundaryType::flat_region_t flr; @@ -953,7 +952,7 @@ void Segmenter< TInputImage > // and update its minimum value if necessary. segment_ptr = segments->Lookup(segment_label); edge_table_entry_ptr = edgeHash.find(segment_label); - if ( segment_ptr == 0 ) // This segment not yet identified. + if ( segment_ptr == ITK_NULLPTR ) // This segment not yet identified. { // So add it to the table. temp_segment.min = searchIt.GetPixel(hoodCenter); segments->Add(segment_label, temp_segment); @@ -1016,7 +1015,7 @@ void Segmenter< TInputImage > { // Lookup the corresponding segment entry segment_ptr = segments->Lookup( ( *edge_table_entry_ptr ).first ); - if ( segment_ptr == 0 ) + if ( segment_ptr == ITK_NULLPTR ) { itkGenericExceptionMacro (<< "UpdateSegmentTable:: An unexpected and fatal error has occurred."); } @@ -1252,7 +1251,7 @@ Segmenter< TInputImage > { return BoundaryType::New().GetPointer(); } - else { return 0; } + else { return ITK_NULLPTR; } } template< typename TInputImage > @@ -1354,8 +1353,8 @@ Segmenter< TInputImage > m_CurrentLabel = 1; m_DoBoundaryAnalysis = false; m_SortEdgeLists = true; - m_Connectivity.direction = 0; - m_Connectivity.index = 0; + m_Connectivity.direction = ITK_NULLPTR; + m_Connectivity.index = ITK_NULLPTR; typename OutputImageType::Pointer img = static_cast< OutputImageType * >( this->MakeOutput(0).GetPointer() ); typename SegmentTableType::Pointer st = diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/UpdateDoubleConversionFromGoogle.sh b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/UpdateDoubleConversionFromGoogle.sh old mode 100644 new mode 100755 index b3daaad35251946f741bc981a37e30a1d15ca022..64db70b406ac15121a763c9e3d94e22d1e99c573 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/UpdateDoubleConversionFromGoogle.sh +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/UpdateDoubleConversionFromGoogle.sh @@ -25,8 +25,8 @@ fi # EDIT THIS SCRIPT to change the hash tag at which to begin the # next update... # -# This merge done April 30 2013 -git branch DoubleConversion-upstream 0447797f4afab5c5 +# This merge done April 28, 2014 +git branch DoubleConversion-upstream 1feae55e5af21e36 # # Make a temp directory to handle the import of the upstream source @@ -53,13 +53,16 @@ git clone https://code.google.com/p/double-conversion/ # recover the upstream commit date. cd double-conversion upstream_date="$(git log -n 1 --format='%cd')" +upstream_sha="$(git rev-parse HEAD)" cd .. # # Check to see if LICENSE file changed -- if changed, fix in a separate # commit. -if [ ! diff double-conversion/LICENSE ../Modules/ThirdParty/DoubleConversion/LICENSE ] +if diff double-conversion/LICENSE ../Modules/ThirdParty/DoubleConversion/src/LICENSE then + echo LICENSE file unchanged +else echo The double-conversion LICENSE file has changed. Please echo add the change in a separate commit by hand and run this script again. exit 1 @@ -77,7 +80,12 @@ git add --all GIT_AUTHOR_NAME='Google double-conversion Maintainers' \ GIT_AUTHOR_EMAIL='floitsch@google.com' \ GIT_AUTHOR_DATE="${upstream_date}" \ -git commit -q -m "Google double-conversion (reduced)" +git commit -q -m "Google double-conversion (reduced) + +This corresponds to commit hash + ${upstream_sha} +from Google repository + http://code.google.com/p/double-conversion" # # push to the DoubleConversion-upstream branch in the diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/CMakeLists.txt index fe0936fe8843ce823a1bf81112cbe650f75ca103..697026d37065cdc484cf182e5243040a7a78e592 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/CMakeLists.txt @@ -29,22 +29,15 @@ endif() itk_module_target(itkdouble-conversion NO_INSTALL) -# -# associates the list of headers with the library -# for the purposes of installation/import into other projects # # install command to set up library install # given the above PUBLIC_HEADER property set, this # pulls along all the header files with the library. -if(NOT ITK_INSTALL_NO_LIBRARIES) - install(TARGETS itkdouble-conversion - EXPORT ${ITKDoubleConversion-targets} - RUNTIME DESTINATION "${ITKDoubleConversion_INSTALL_RUNTIME_DIR}" COMPONENT Applications - LIBRARY DESTINATION "${ITKDoubleConversion_INSTALL_LIBRARY_DIR}" COMPONENT Libraries - ARCHIVE DESTINATION "${ITKDoubleConversion_INSTALL_LIBRARY_DIR}" COMPONENT Development) -endif() +install(TARGETS itkdouble-conversion + EXPORT ${ITKDoubleConversion-targets} + RUNTIME DESTINATION "${ITKDoubleConversion_INSTALL_RUNTIME_DIR}" COMPONENT Applications + LIBRARY DESTINATION "${ITKDoubleConversion_INSTALL_LIBRARY_DIR}" COMPONENT Libraries + ARCHIVE DESTINATION "${ITKDoubleConversion_INSTALL_LIBRARY_DIR}" COMPONENT Development) -if(NOT ITK_INSTALL_NO_DEVELOPMENT) - install(FILES ${headers} - DESTINATION "${ITKDoubleConversion_INSTALL_INCLUDE_DIR}" COMPONENT Development) -endif() +install(FILES ${headers} + DESTINATION "${ITKDoubleConversion_INSTALL_INCLUDE_DIR}" COMPONENT Development) diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/bignum-dtoa.cc b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/bignum-dtoa.cc index b6c2e85d17cc51fb28d52e012f248fc7a15d1997..f1ad7a5ae8dd027d53e2786d3f6c459aed04e397 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/bignum-dtoa.cc +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/bignum-dtoa.cc @@ -192,13 +192,13 @@ static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator, delta_plus = delta_minus; } *length = 0; - while (true) { + for (;;) { uint16_t digit; digit = numerator->DivideModuloIntBignum(*denominator); ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive. // digit = numerator / denominator (integer division). // numerator = numerator % denominator. - buffer[(*length)++] = digit + '0'; + buffer[(*length)++] = static_cast<char>(digit + '0'); // Can we stop already? // If the remainder of the division is less than the distance to the lower @@ -282,7 +282,7 @@ static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator, // exponent (decimal_point), when rounding upwards. static void GenerateCountedDigits(int count, int* decimal_point, Bignum* numerator, Bignum* denominator, - Vector<char>(buffer), int* length) { + Vector<char> buffer, int* length) { ASSERT(count >= 0); for (int i = 0; i < count - 1; ++i) { uint16_t digit; @@ -290,7 +290,7 @@ static void GenerateCountedDigits(int count, int* decimal_point, ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive. // digit = numerator / denominator (integer division). // numerator = numerator % denominator. - buffer[i] = digit + '0'; + buffer[i] = static_cast<char>(digit + '0'); // Prepare for next iteration. numerator->Times10(); } @@ -300,7 +300,8 @@ static void GenerateCountedDigits(int count, int* decimal_point, if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) { digit++; } - buffer[count - 1] = digit + '0'; + ASSERT(digit <= 10); + buffer[count - 1] = static_cast<char>(digit + '0'); // Correct bad digits (in case we had a sequence of '9's). Propagate the // carry until we hat a non-'9' or til we reach the first digit. for (int i = count - 1; i > 0; --i) { diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/bignum.cc b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/bignum.cc index dc8a2a63e777e62261eebac592632f58e2cca211..2743d67e8d922aaab3283a586dcd7c97ad7a78a9 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/bignum.cc +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/bignum.cc @@ -40,6 +40,7 @@ Bignum::Bignum() template<typename S> static int BitSize(S value) { + (void) value; // Mark variable as used. return 8 * sizeof(value); } @@ -122,9 +123,8 @@ void Bignum::AssignDecimalString(Vector<const char> value) { static int HexCharValue(char c) { if ('0' <= c && c <= '9') return c - '0'; if ('a' <= c && c <= 'f') return 10 + c - 'a'; - if ('A' <= c && c <= 'F') return 10 + c - 'A'; - UNREACHABLE(); - return 0; // To make compiler happy. + ASSERT('A' <= c && c <= 'F'); + return 10 + c - 'A'; } @@ -505,9 +505,10 @@ uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) { // is big. This function is implemented for doubleToString where // the result should be small (less than 10). ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16)); + ASSERT(bigits_[used_digits_ - 1] < 0x10000); // Remove the multiples of the first digit. // Example this = 23 and other equals 9. -> Remove 2 multiples. - result += bigits_[used_digits_ - 1]; + result += static_cast<uint16_t>(bigits_[used_digits_ - 1]); SubtractTimes(other, bigits_[used_digits_ - 1]); } @@ -523,13 +524,15 @@ uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) { // Shortcut for easy (and common) case. int quotient = this_bigit / other_bigit; bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient; - result += quotient; + ASSERT(quotient < 0x10000); + result += static_cast<uint16_t>(quotient); Clamp(); return result; } int division_estimate = this_bigit / (other_bigit + 1); - result += division_estimate; + ASSERT(division_estimate < 0x10000); + result += static_cast<uint16_t>(division_estimate); SubtractTimes(other, division_estimate); if (other_bigit * (division_estimate + 1) > this_bigit) { @@ -560,8 +563,8 @@ static int SizeInHexChars(S number) { static char HexCharOfValue(int value) { ASSERT(0 <= value && value <= 16); - if (value < 10) return value + '0'; - return value - 10 + 'A'; + if (value < 10) return static_cast<char>(value + '0'); + return static_cast<char>(value - 10 + 'A'); } diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/cached-powers.cc b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/cached-powers.cc index c676429194e85498b764d9f00d77b5a6eb7479b1..d1359ffe43e9935fcd18ed3b7df7d60f04fdac7e 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/cached-powers.cc +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/cached-powers.cc @@ -152,6 +152,7 @@ void PowersOfTenCache::GetCachedPowerForBinaryExponentRange( ASSERT(0 <= index && index < kCachedPowersLength); CachedPower cached_power = kCachedPowers[index]; ASSERT(min_exponent <= cached_power.binary_exponent); + (void) max_exponent; // Mark variable as used. ASSERT(cached_power.binary_exponent <= max_exponent); *decimal_exponent = cached_power.decimal_exponent; *power = DiyFp(cached_power.significand, cached_power.binary_exponent); diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/double-conversion.cc b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/double-conversion.cc index 5f2738ab14160d8a429419ea1d17c08693efbd78..addb3622a9ccc81136d4a5875eb7156e53780548 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/double-conversion.cc +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/double-conversion.cc @@ -348,7 +348,6 @@ static BignumDtoaMode DtoaToBignumDtoaMode( case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION; default: UNREACHABLE(); - return BIGNUM_DTOA_SHORTEST; // To silence compiler. } } @@ -403,8 +402,8 @@ void DoubleToStringConverter::DoubleToAscii(double v, vector, length, point); break; default: - UNREACHABLE(); fast_worked = false; + UNREACHABLE(); } if (fast_worked) return; @@ -417,8 +416,9 @@ void DoubleToStringConverter::DoubleToAscii(double v, // Consumes the given substring from the iterator. // Returns false, if the substring does not match. -static bool ConsumeSubString(const char** current, - const char* end, +template <class Iterator> +static bool ConsumeSubString(Iterator* current, + Iterator end, const char* substring) { ASSERT(**current == *substring); for (substring++; *substring != '\0'; substring++) { @@ -440,10 +440,36 @@ static bool ConsumeSubString(const char** current, const int kMaxSignificantDigits = 772; +static const char kWhitespaceTable7[] = { 32, 13, 10, 9, 11, 12 }; +static const int kWhitespaceTable7Length = ARRAY_SIZE(kWhitespaceTable7); + + +static const uc16 kWhitespaceTable16[] = { + 160, 8232, 8233, 5760, 6158, 8192, 8193, 8194, 8195, + 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279 +}; +static const int kWhitespaceTable16Length = ARRAY_SIZE(kWhitespaceTable16); + + +static bool isWhitespace(int x) { + if (x < 128) { + for (int i = 0; i < kWhitespaceTable7Length; i++) { + if (kWhitespaceTable7[i] == x) return true; + } + } else { + for (int i = 0; i < kWhitespaceTable16Length; i++) { + if (kWhitespaceTable16[i] == x) return true; + } + } + return false; +} + + // Returns true if a nonspace found and false if the end has reached. -static inline bool AdvanceToNonspace(const char** current, const char* end) { +template <class Iterator> +static inline bool AdvanceToNonspace(Iterator* current, Iterator end) { while (*current != end) { - if (**current != ' ') return true; + if (!isWhitespace(**current)) return true; ++*current; } return false; @@ -462,26 +488,50 @@ static double SignedZero(bool sign) { } +// Returns true if 'c' is a decimal digit that is valid for the given radix. +// +// The function is small and could be inlined, but VS2012 emitted a warning +// because it constant-propagated the radix and concluded that the last +// condition was always true. By moving it into a separate function the +// compiler wouldn't warn anymore. +static bool IsDecimalDigitForRadix(int c, int radix) { + return '0' <= c && c <= '9' && (c - '0') < radix; +} + +// Returns true if 'c' is a character digit that is valid for the given radix. +// The 'a_character' should be 'a' or 'A'. +// +// The function is small and could be inlined, but VS2012 emitted a warning +// because it constant-propagated the radix and concluded that the first +// condition was always false. By moving it into a separate function the +// compiler wouldn't warn anymore. +static bool IsCharacterDigitForRadix(int c, int radix, char a_character) { + return radix > 10 && c >= a_character && c < a_character + radix - 10; +} + + // Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end. -template <int radix_log_2> -static double RadixStringToIeee(const char* current, - const char* end, +template <int radix_log_2, class Iterator> +static double RadixStringToIeee(Iterator* current, + Iterator end, bool sign, bool allow_trailing_junk, double junk_string_value, bool read_as_double, - const char** trailing_pointer) { - ASSERT(current != end); + bool* result_is_junk) { + ASSERT(*current != end); const int kDoubleSize = Double::kSignificandSize; const int kSingleSize = Single::kSignificandSize; const int kSignificandSize = read_as_double? kDoubleSize: kSingleSize; + *result_is_junk = true; + // Skip leading 0s. - while (*current == '0') { - ++current; - if (current == end) { - *trailing_pointer = end; + while (**current == '0') { + ++(*current); + if (*current == end) { + *result_is_junk = false; return SignedZero(sign); } } @@ -492,14 +542,14 @@ static double RadixStringToIeee(const char* current, do { int digit; - if (*current >= '0' && *current <= '9' && *current < '0' + radix) { - digit = static_cast<char>(*current) - '0'; - } else if (radix > 10 && *current >= 'a' && *current < 'a' + radix - 10) { - digit = static_cast<char>(*current) - 'a' + 10; - } else if (radix > 10 && *current >= 'A' && *current < 'A' + radix - 10) { - digit = static_cast<char>(*current) - 'A' + 10; + if (IsDecimalDigitForRadix(**current, radix)) { + digit = static_cast<char>(**current) - '0'; + } else if (IsCharacterDigitForRadix(**current, radix, 'a')) { + digit = static_cast<char>(**current) - 'a' + 10; + } else if (IsCharacterDigitForRadix(**current, radix, 'A')) { + digit = static_cast<char>(**current) - 'A' + 10; } else { - if (allow_trailing_junk || !AdvanceToNonspace(¤t, end)) { + if (allow_trailing_junk || !AdvanceToNonspace(current, end)) { break; } else { return junk_string_value; @@ -523,14 +573,14 @@ static double RadixStringToIeee(const char* current, exponent = overflow_bits_count; bool zero_tail = true; - while (true) { - ++current; - if (current == end || !isDigit(*current, radix)) break; - zero_tail = zero_tail && *current == '0'; + for (;;) { + ++(*current); + if (*current == end || !isDigit(**current, radix)) break; + zero_tail = zero_tail && **current == '0'; exponent += radix_log_2; } - if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) { + if (!allow_trailing_junk && AdvanceToNonspace(current, end)) { return junk_string_value; } @@ -552,13 +602,13 @@ static double RadixStringToIeee(const char* current, } break; } - ++current; - } while (current != end); + ++(*current); + } while (*current != end); ASSERT(number < ((int64_t)1 << kSignificandSize)); ASSERT(static_cast<int64_t>(static_cast<double>(number)) == number); - *trailing_pointer = current; + *result_is_junk = false; if (exponent == 0) { if (sign) { @@ -573,13 +623,14 @@ static double RadixStringToIeee(const char* current, } +template <class Iterator> double StringToDoubleConverter::StringToIeee( - const char* input, + Iterator input, int length, - int* processed_characters_count, - bool read_as_double) const { - const char* current = input; - const char* end = input + length; + bool read_as_double, + int* processed_characters_count) const { + Iterator current = input; + Iterator end = input + length; *processed_characters_count = 0; @@ -600,7 +651,7 @@ double StringToDoubleConverter::StringToIeee( if (allow_leading_spaces || allow_trailing_spaces) { if (!AdvanceToNonspace(¤t, end)) { - *processed_characters_count = current - input; + *processed_characters_count = static_cast<int>(current - input); return empty_string_value_; } if (!allow_leading_spaces && (input != current)) { @@ -626,7 +677,7 @@ double StringToDoubleConverter::StringToIeee( if (*current == '+' || *current == '-') { sign = (*current == '-'); ++current; - const char* next_non_space = current; + Iterator next_non_space = current; // Skip following spaces (if allowed). if (!AdvanceToNonspace(&next_non_space, end)) return junk_string_value_; if (!allow_spaces_after_sign && (current != next_non_space)) { @@ -649,7 +700,7 @@ double StringToDoubleConverter::StringToIeee( } ASSERT(buffer_pos == 0); - *processed_characters_count = current - input; + *processed_characters_count = static_cast<int>(current - input); return sign ? -Double::Infinity() : Double::Infinity(); } } @@ -668,7 +719,7 @@ double StringToDoubleConverter::StringToIeee( } ASSERT(buffer_pos == 0); - *processed_characters_count = current - input; + *processed_characters_count = static_cast<int>(current - input); return sign ? -Double::NaN() : Double::NaN(); } } @@ -677,7 +728,7 @@ double StringToDoubleConverter::StringToIeee( if (*current == '0') { ++current; if (current == end) { - *processed_characters_count = current - input; + *processed_characters_count = static_cast<int>(current - input); return SignedZero(sign); } @@ -690,17 +741,17 @@ double StringToDoubleConverter::StringToIeee( return junk_string_value_; // "0x". } - const char* tail_pointer = NULL; - double result = RadixStringToIeee<4>(current, + bool result_is_junk; + double result = RadixStringToIeee<4>(¤t, end, sign, allow_trailing_junk, junk_string_value_, read_as_double, - &tail_pointer); - if (tail_pointer != NULL) { - if (allow_trailing_spaces) AdvanceToNonspace(&tail_pointer, end); - *processed_characters_count = tail_pointer - input; + &result_is_junk); + if (!result_is_junk) { + if (allow_trailing_spaces) AdvanceToNonspace(¤t, end); + *processed_characters_count = static_cast<int>(current - input); } return result; } @@ -709,7 +760,7 @@ double StringToDoubleConverter::StringToIeee( while (*current == '0') { ++current; if (current == end) { - *processed_characters_count = current - input; + *processed_characters_count = static_cast<int>(current - input); return SignedZero(sign); } } @@ -757,7 +808,7 @@ double StringToDoubleConverter::StringToIeee( while (*current == '0') { ++current; if (current == end) { - *processed_characters_count = current - input; + *processed_characters_count = static_cast<int>(current - input); return SignedZero(sign); } exponent--; // Move this 0 into the exponent. @@ -855,16 +906,17 @@ double StringToDoubleConverter::StringToIeee( if (octal) { double result; - const char* tail_pointer = NULL; - result = RadixStringToIeee<3>(buffer, + bool result_is_junk; + char* start = buffer; + result = RadixStringToIeee<3>(&start, buffer + buffer_pos, sign, allow_trailing_junk, junk_string_value_, read_as_double, - &tail_pointer); - ASSERT(tail_pointer != NULL); - *processed_characters_count = current - input; + &result_is_junk); + ASSERT(!result_is_junk); + *processed_characters_count = static_cast<int>(current - input); return result; } @@ -882,8 +934,42 @@ double StringToDoubleConverter::StringToIeee( } else { converted = Strtof(Vector<const char>(buffer, buffer_pos), exponent); } - *processed_characters_count = current - input; + *processed_characters_count = static_cast<int>(current - input); return sign? -converted: converted; } + +double StringToDoubleConverter::StringToDouble( + const char* buffer, + int length, + int* processed_characters_count) const { + return StringToIeee(buffer, length, true, processed_characters_count); +} + + +double StringToDoubleConverter::StringToDouble( + const uc16* buffer, + int length, + int* processed_characters_count) const { + return StringToIeee(buffer, length, true, processed_characters_count); +} + + +float StringToDoubleConverter::StringToFloat( + const char* buffer, + int length, + int* processed_characters_count) const { + return static_cast<float>(StringToIeee(buffer, length, false, + processed_characters_count)); +} + + +float StringToDoubleConverter::StringToFloat( + const uc16* buffer, + int length, + int* processed_characters_count) const { + return static_cast<float>(StringToIeee(buffer, length, false, + processed_characters_count)); +} + } // namespace double_conversion diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/double-conversion.h b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/double-conversion.h index 1c3387d4f842c60a2eac65c7c27a7abb28608467..6bdfa8d25d768a640ac460ec1283f2ceae1098aa 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/double-conversion.h +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/double-conversion.h @@ -415,9 +415,10 @@ class StringToDoubleConverter { // junk, too. // - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of // a double literal. - // - ALLOW_LEADING_SPACES: skip over leading spaces. - // - ALLOW_TRAILING_SPACES: ignore trailing spaces. - // - ALLOW_SPACES_AFTER_SIGN: ignore spaces after the sign. + // - ALLOW_LEADING_SPACES: skip over leading whitespace, including spaces, + // new-lines, and tabs. + // - ALLOW_TRAILING_SPACES: ignore trailing whitespace. + // - ALLOW_SPACES_AFTER_SIGN: ignore whitespace after the sign. // Ex: StringToDouble("- 123.2") -> -123.2. // StringToDouble("+ 123.2") -> 123.2 // @@ -502,19 +503,24 @@ class StringToDoubleConverter { // in the 'processed_characters_count'. Trailing junk is never included. double StringToDouble(const char* buffer, int length, - int* processed_characters_count) const { - return StringToIeee(buffer, length, processed_characters_count, true); - } + int* processed_characters_count) const; + + // Same as StringToDouble above but for 16 bit characters. + double StringToDouble(const uc16* buffer, + int length, + int* processed_characters_count) const; // Same as StringToDouble but reads a float. // Note that this is not equivalent to static_cast<float>(StringToDouble(...)) // due to potential double-rounding. float StringToFloat(const char* buffer, int length, - int* processed_characters_count) const { - return static_cast<float>(StringToIeee(buffer, length, - processed_characters_count, false)); - } + int* processed_characters_count) const; + + // Same as StringToFloat above but for 16 bit characters. + float StringToFloat(const uc16* buffer, + int length, + int* processed_characters_count) const; private: const int flags_; @@ -523,10 +529,11 @@ class StringToDoubleConverter { const char* const infinity_symbol_; const char* const nan_symbol_; - double StringToIeee(const char* buffer, + template <class Iterator> + double StringToIeee(Iterator start_pointer, int length, - int* processed_characters_count, - bool read_as_double) const; + bool read_as_double, + int* processed_characters_count) const; DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter); }; diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/fast-dtoa.cc b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/fast-dtoa.cc index 1a0f8235092f36d6c4a264f0ad3a4b184e000443..61350383a95ea69e73604bd692ae2037ff4b7b14 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/fast-dtoa.cc +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/fast-dtoa.cc @@ -248,10 +248,7 @@ static void BiggestPowerTen(uint32_t number, // Note: kPowersOf10[i] == 10^(i-1). exponent_plus_one_guess++; // We don't have any guarantees that 2^number_bits <= number. - // TODO(floitsch): can we change the 'while' into an 'if'? We definitely see - // number < (2^number_bits - 1), but I haven't encountered - // number < (2^number_bits - 2) yet. - while (number < kSmallPowersOfTen[exponent_plus_one_guess]) { + if (number < kSmallPowersOfTen[exponent_plus_one_guess]) { exponent_plus_one_guess--; } *power = kSmallPowersOfTen[exponent_plus_one_guess]; @@ -350,7 +347,8 @@ static bool DigitGen(DiyFp low, // that is smaller than integrals. while (*kappa > 0) { int digit = integrals / divisor; - buffer[*length] = '0' + digit; + ASSERT(digit <= 9); + buffer[*length] = static_cast<char>('0' + digit); (*length)++; integrals %= divisor; (*kappa)--; @@ -379,13 +377,14 @@ static bool DigitGen(DiyFp low, ASSERT(one.e() >= -60); ASSERT(fractionals < one.f()); ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f()); - while (true) { + for (;;) { fractionals *= 10; unit *= 10; unsafe_interval.set_f(unsafe_interval.f() * 10); // Integer division by one. int digit = static_cast<int>(fractionals >> -one.e()); - buffer[*length] = '0' + digit; + ASSERT(digit <= 9); + buffer[*length] = static_cast<char>('0' + digit); (*length)++; fractionals &= one.f() - 1; // Modulo by one. (*kappa)--; @@ -459,7 +458,8 @@ static bool DigitGenCounted(DiyFp w, // that is smaller than 'integrals'. while (*kappa > 0) { int digit = integrals / divisor; - buffer[*length] = '0' + digit; + ASSERT(digit <= 9); + buffer[*length] = static_cast<char>('0' + digit); (*length)++; requested_digits--; integrals %= divisor; @@ -492,7 +492,8 @@ static bool DigitGenCounted(DiyFp w, w_error *= 10; // Integer division by one. int digit = static_cast<int>(fractionals >> -one.e()); - buffer[*length] = '0' + digit; + ASSERT(digit <= 9); + buffer[*length] = static_cast<char>('0' + digit); (*length)++; requested_digits--; fractionals &= one.f() - 1; // Modulo by one. diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/fixed-dtoa.cc b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/fixed-dtoa.cc index 45f910c63265135e69928f2d9f43c3223cd08185..aef65fdc21168f7b2dee2b21b4391a767bd8e877 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/fixed-dtoa.cc +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/fixed-dtoa.cc @@ -133,7 +133,7 @@ static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) { while (number != 0) { int digit = number % 10; number /= 10; - buffer[(*length) + number_length] = '0' + digit; + buffer[(*length) + number_length] = static_cast<char>('0' + digit); number_length++; } // Exchange the digits. @@ -150,7 +150,7 @@ static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) { } -static void FillDigits64FixedLength(uint64_t number, int /* requested_length */, +static void FillDigits64FixedLength(uint64_t number, Vector<char> buffer, int* length) { const uint32_t kTen7 = 10000000; // For efficiency cut the number into 3 uint32_t parts, and print those. @@ -253,7 +253,8 @@ static void FillFractionals(uint64_t fractionals, int exponent, fractionals *= 5; point--; int digit = static_cast<int>(fractionals >> point); - buffer[*length] = '0' + digit; + ASSERT(digit <= 9); + buffer[*length] = static_cast<char>('0' + digit); (*length)++; fractionals -= static_cast<uint64_t>(digit) << point; } @@ -274,7 +275,8 @@ static void FillFractionals(uint64_t fractionals, int exponent, fractionals128.Multiply(5); point--; int digit = fractionals128.DivModPowerOf2(point); - buffer[*length] = '0' + digit; + ASSERT(digit <= 9); + buffer[*length] = static_cast<char>('0' + digit); (*length)++; } if (fractionals128.BitAt(point - 1) == 1) { @@ -358,7 +360,7 @@ bool FastFixedDtoa(double v, remainder = (dividend % divisor) << exponent; } FillDigits32(quotient, buffer, length); - FillDigits64FixedLength(remainder, divisor_power, buffer, length); + FillDigits64FixedLength(remainder, buffer, length); *decimal_point = *length; } else if (exponent >= 0) { // 0 <= exponent <= 11 diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/ieee.h b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/ieee.h index 839dc47d455a8703da0674f51bc32bf1b6c697e6..661141d1a8de2dc7f65127888c347c12512dced2 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/ieee.h +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/ieee.h @@ -256,6 +256,8 @@ class Double { return (significand & kSignificandMask) | (biased_exponent << kPhysicalSignificandSize); } + + DISALLOW_COPY_AND_ASSIGN(Double); }; class Single { @@ -391,6 +393,8 @@ class Single { static const uint32_t kNaN = 0x7FC00000; const uint32_t d32_; + + DISALLOW_COPY_AND_ASSIGN(Single); }; } // namespace double_conversion diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/strtod.cc b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/strtod.cc index 9758989f71dbfc02c105ff6090d5281f63fbbb40..34717562bd4d492b2d2b81b47f8631809d452d71 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/strtod.cc +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/strtod.cc @@ -137,6 +137,7 @@ static void TrimAndCut(Vector<const char> buffer, int exponent, Vector<const char> right_trimmed = TrimTrailingZeros(left_trimmed); exponent += left_trimmed.length() - right_trimmed.length(); if (right_trimmed.length() > kMaxSignificantDecimalDigits) { + (void) space_size; // Mark variable as used. ASSERT(space_size >= kMaxSignificantDecimalDigits); CutToMaxSignificantDigits(right_trimmed, exponent, buffer_copy_space, updated_exponent); @@ -263,7 +264,6 @@ static DiyFp AdjustmentPowerOfTen(int exponent) { case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40); default: UNREACHABLE(); - return DiyFp(0, 0); } } @@ -515,6 +515,7 @@ float Strtof(Vector<const char> buffer, int exponent) { double double_next2 = Double(double_next).NextDouble(); f4 = static_cast<float>(double_next2); } + (void) f2; // Mark variable as used. ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4); // If the guess doesn't lie near a single-precision boundary we can simply diff --git a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/utils.h b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/utils.h index e3a3a372bda55d350fcb0160a99523af577a6098..b0938ef0865be2535aa9e3e52e9a9138dcddc235 100644 --- a/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/utils.h +++ b/Utilities/ITK/Modules/ThirdParty/DoubleConversion/src/double-conversion/utils.h @@ -33,7 +33,8 @@ #include <assert.h> #ifndef ASSERT -#define ASSERT(condition) (assert(condition)) +#define ASSERT(condition) \ + assert(condition); #endif #ifndef UNIMPLEMENTED #define UNIMPLEMENTED() (abort()) @@ -60,7 +61,7 @@ defined(__sparc__) || defined(__sparc) || defined(__s390__) || \ defined(__SH4__) || defined(__alpha__) || \ defined(_MIPS_ARCH_MIPS32R2) || \ - defined(_AARCH64EL_) + defined(__AARCH64EL__) #define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1 #elif defined(_M_IX86) || defined(__i386__) || defined(__i386) #if defined(_WIN32) @@ -73,6 +74,11 @@ #error Target architecture was not detected as supported by Double-Conversion. #endif +#if defined(__GNUC__) +#define DOUBLE_CONVERSION_UNUSED __attribute__((unused)) +#else +#define DOUBLE_CONVERSION_UNUSED +#endif #if defined(_WIN32) && !defined(__MINGW32__) @@ -92,6 +98,8 @@ typedef unsigned __int64 uint64_t; #endif +typedef uint16_t uc16; + // The following macro works on both 32 and 64-bit platforms. // Usage: instead of writing 0x1234567890123456 // write UINT64_2PART_C(0x12345678,90123456); @@ -298,7 +306,8 @@ template <class Dest, class Source> inline Dest BitCast(const Source& source) { // Compile time assertion: sizeof(Dest) == sizeof(Source) // A compile error here means your Dest and Source have different sizes. - typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1]; + DOUBLE_CONVERSION_UNUSED + typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1]; Dest dest; memmove(&dest, &source, sizeof(dest)); diff --git a/Utilities/ITK/Modules/ThirdParty/Expat/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/Expat/CMakeLists.txt index 8791cc40cffe4ec42271e388a5d70c86618e59f8..61f694edcd2887b53cb27b41bf646f24f7d77b1f 100644 --- a/Utilities/ITK/Modules/ThirdParty/Expat/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/Expat/CMakeLists.txt @@ -1,10 +1,22 @@ project(ITKExpat) set(ITKExpat_THIRD_PARTY 1) -set(ITKExpat_INCLUDE_DIRS +option(ITK_USE_SYSTEM_EXPAT "Use system-installed expat" OFF) +mark_as_advanced(ITK_USE_SYSTEM_EXPAT) + +if(ITK_USE_SYSTEM_EXPAT) + find_package(EXPAT REQUIRED) + set(ITKExpat_INCLUDE_DIRS ${ITKExpat_BINARY_DIR}/src ) + set(ITKExpat_SYSTEM_INCLUDE_DIRS "${EXPAT_INCLUDE_DIR}") + set(ITKExpat_LIBRARIES "${EXPAT_LIBRARY}") + set(ITKExpat_NO_SRC 1) +else() + set(ITKExpat_INCLUDE_DIRS ${ITKExpat_BINARY_DIR}/src/expat ${ITKExpat_SOURCE_DIR}/src/expat ) set(ITKExpat_LIBRARIES ITKEXPAT) +endif() + itk_module_impl() diff --git a/Utilities/ITK/Modules/ThirdParty/Expat/src/expat/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/Expat/src/expat/CMakeLists.txt index 167d05120404eda38fe4b194f7dc26956b961d72..14329c5cc36c6b19559933518953630ec34ccead 100644 --- a/Utilities/ITK/Modules/ThirdParty/Expat/src/expat/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/Expat/src/expat/CMakeLists.txt @@ -28,19 +28,15 @@ IF(ITK_LIBRARY_PROPERTIES) SET_TARGET_PROPERTIES(ITKEXPAT PROPERTIES ${ITK_LIBRARY_PROPERTIES}) ENDIF(ITK_LIBRARY_PROPERTIES) -IF(NOT ITK_INSTALL_NO_LIBRARIES) - INSTALL(TARGETS ITKEXPAT - EXPORT ${ITK3P_INSTALL_EXPORT_NAME} - RUNTIME DESTINATION ${ITK3P_INSTALL_RUNTIME_DIR} COMPONENT RuntimeLibraries - LIBRARY DESTINATION ${ITK3P_INSTALL_LIBRARY_DIR} COMPONENT RuntimeLibraries - ARCHIVE DESTINATION ${ITK3P_INSTALL_ARCHIVE_DIR} COMPONENT Development - ) -ENDIF(NOT ITK_INSTALL_NO_LIBRARIES) - -IF(NOT ITK_INSTALL_NO_DEVELOPMENT) - INSTALL(FILES - ${ITK3P_EXPAT_BINARY_DIR}/expatDllConfig.h - ${ITK3P_EXPAT_SOURCE_DIR}/expat.h - DESTINATION ${ITK3P_INSTALL_INCLUDE_DIR} # TODO: itk_expat.h #include "itkexpat/expat.h" - COMPONENT Development) -ENDIF(NOT ITK_INSTALL_NO_DEVELOPMENT) +INSTALL(TARGETS ITKEXPAT + EXPORT ${ITK3P_INSTALL_EXPORT_NAME} + RUNTIME DESTINATION ${ITK3P_INSTALL_RUNTIME_DIR} COMPONENT RuntimeLibraries + LIBRARY DESTINATION ${ITK3P_INSTALL_LIBRARY_DIR} COMPONENT RuntimeLibraries + ARCHIVE DESTINATION ${ITK3P_INSTALL_ARCHIVE_DIR} COMPONENT Development + ) + +INSTALL(FILES + ${ITK3P_EXPAT_BINARY_DIR}/expatDllConfig.h + ${ITK3P_EXPAT_SOURCE_DIR}/expat.h + DESTINATION ${ITK3P_INSTALL_INCLUDE_DIR} # TODO: itk_expat.h #include "itkexpat/expat.h" + COMPONENT Development) diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/KWSys/src/CMakeLists.txt index b1128155239b2f404e38d45122a0d8c001bf62ad..75b8ccd52bfa6f65902a5eba881e1a6cd3ec4f8d 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/CMakeLists.txt @@ -18,6 +18,7 @@ set(KWSYS_INSTALL_DOC_DIR ${ITK_INSTALL_DOC_DIR}) set(KWSYS_INSTALL_EXPORT_NAME ${ITKKWSys-targets}) set(KWSYS_INSTALL_COMPONENT_NAME_RUNTIME RuntimeLibraries) set(KWSYS_INSTALL_COMPONENT_NAME_DEVELOPMENT Development) +set(KWSYS_PROPERTIES_CXX MACOSX_RPATH 1) add_subdirectory(KWSys) itk_module_target(${KWSYS_NAMESPACE} NO_INSTALL) diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/CMakeLists.txt index c2b377df1d37a568531b1bc45840397f4d744bb5..5e6a2263a5b8ca4897cf1f32628bb949a0cfd0ac 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/CMakeLists.txt @@ -85,6 +85,9 @@ # written. CMAKE_MINIMUM_REQUIRED(VERSION 2.6.3 FATAL_ERROR) +IF(POLICY CMP0025) + CMAKE_POLICY(SET CMP0025 NEW) +ENDIF() #----------------------------------------------------------------------------- # If a namespace is not specified, use "kwsys" and enable testing. @@ -296,6 +299,13 @@ IF(NOT CMAKE_COMPILER_IS_GNUCXX) ENDIF(CMAKE_SYSTEM MATCHES "OSF1-V.*") IF(CMAKE_SYSTEM MATCHES "HP-UX") SET(KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS "+p") + IF(CMAKE_CXX_COMPILER_ID MATCHES "HP") + # it is known that version 3.85 fails and 6.25 works without these flags + IF(CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4) + # use new C++ library and improved template support + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -AA +hpxstd98") + ENDIF() + ENDIF() ENDIF(CMAKE_SYSTEM MATCHES "HP-UX") ENDIF(NOT CMAKE_COMPILER_IS_GNUCXX) @@ -682,6 +692,7 @@ IF(KWSYS_USE_SystemInformation) # usually it's in libc but on FreeBSD # it's in libexecinfo FIND_LIBRARY(EXECINFO_LIB "execinfo") + MARK_AS_ADVANCED(EXECINFO_LIB) IF (NOT EXECINFO_LIB) SET(EXECINFO_LIB "") ENDIF() @@ -1073,6 +1084,11 @@ IF(MSVC OR (WIN32 AND "${CMAKE_C_COMPILER_ID}" MATCHES "^(Intel)$")) ) ENDIF() +IF(WIN32) + # Help enforce the use of wide Windows apis. + ADD_DEFINITIONS(-DUNICODE -D_UNICODE) +ENDIF() + IF(KWSYS_USE_String) # Activate code in "String.c". See the comment in the source. SET_SOURCE_FILES_PROPERTIES(String.c PROPERTIES @@ -1133,6 +1149,11 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) testEncoding ) ENDIF(KWSYS_STL_HAS_WSTRING) + IF(KWSYS_USE_FStream) + SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} + testFStream + ) + ENDIF(KWSYS_USE_FStream) IF(KWSYS_USE_SystemInformation) SET(KWSYS_CXX_TESTS ${KWSYS_CXX_TESTS} testSystemInformation) ENDIF(KWSYS_USE_SystemInformation) @@ -1214,6 +1235,9 @@ IF(KWSYS_STANDALONE OR CMake_SOURCE_DIR) # Some Apple compilers produce bad optimizations in this source. IF(APPLE AND "${CMAKE_C_COMPILER_ID}" MATCHES "^(GNU|LLVM)$") SET_SOURCE_FILES_PROPERTIES(testProcess.c PROPERTIES COMPILE_FLAGS -O0) + ELSEIF(CMAKE_C_COMPILER_ID STREQUAL "XL") + # Tell IBM XL not to warn about our test infinite loop + SET_PROPERTY(SOURCE testProcess.c PROPERTY COMPILE_FLAGS -qsuppress=1500-010) ENDIF() # Test SharedForward diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/Encoding.hxx.in b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/Encoding.hxx.in index 60a4a8e053612cd0d25375340c27e250fa558045..aba4175545f68982095b6bc2d3d3ba965f1fc92b 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/Encoding.hxx.in +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/Encoding.hxx.in @@ -14,6 +14,7 @@ #include <@KWSYS_NAMESPACE@/Configure.hxx> #include <@KWSYS_NAMESPACE@/stl/string> +#include <@KWSYS_NAMESPACE@/stl/vector> /* Define these macros temporarily to keep the code readable. */ #if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS @@ -25,6 +26,36 @@ namespace @KWSYS_NAMESPACE@ class @KWSYS_NAMESPACE@_EXPORT Encoding { public: + + // Container class for argc/argv. + class CommandLineArguments + { + public: + // On Windows, get the program command line arguments + // in this Encoding module's 8 bit encoding. + // On other platforms the given argc/argv is used, and + // to be consistent, should be the argc/argv from main(). + static CommandLineArguments Main(int argc, char const* const* argv); + + // Construct CommandLineArguments with the given + // argc/argv. It is assumed that the string is already + // in the encoding used by this module. + CommandLineArguments(int argc, char const* const* argv); + + // Construct CommandLineArguments with the given + // argc and wide argv. This is useful if wmain() is used. + CommandLineArguments(int argc, wchar_t const* const* argv); + ~CommandLineArguments(); + CommandLineArguments(const CommandLineArguments&); + CommandLineArguments& operator=(const CommandLineArguments&); + + int argc() const; + char const* const* argv() const; + + protected: + std::vector<char*> argv_; + }; + /** * Convert between char and wchar_t */ diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/EncodingC.c b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/EncodingC.c index a36eeccbf756ae2a6bb03216a07a05d48c697057..cda78e2896c45b3470ed8f61237ffcf28e0fe3de 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/EncodingC.c +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/EncodingC.c @@ -68,7 +68,7 @@ size_t kwsysEncoding_wcstombs(char* dest, const wchar_t* str, size_t n) char* kwsysEncoding_DupToNarrow(const wchar_t* str) { char* ret = NULL; - size_t length = kwsysEncoding_wcstombs(0, str, 0); + size_t length = kwsysEncoding_wcstombs(0, str, 0) + 1; if(length > 0) { ret = malloc(length); diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/EncodingCXX.cxx b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/EncodingCXX.cxx index aebc14869cc0086c8b458cbb8058056abc5733d2..251a56ddc94cf77fbc255e90102aaca0bc58b041 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/EncodingCXX.cxx +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/EncodingCXX.cxx @@ -29,6 +29,7 @@ #endif #include <stdlib.h> +#include <string.h> #ifdef _MSC_VER # pragma warning (disable: 4786) @@ -42,6 +43,101 @@ namespace KWSYS_NAMESPACE { +Encoding::CommandLineArguments +Encoding::CommandLineArguments::Main(int argc, char const* const* argv) +{ +#ifdef _WIN32 + (void) argc; + (void) argv; + + int ac; + LPWSTR* w_av = CommandLineToArgvW(GetCommandLineW(), &ac); + + std::vector<std::string> av1(ac); + std::vector<char const*> av2(ac); + for(int i=0; i<ac; i++) + { + av1[i] = ToNarrow(w_av[i]); + av2[i] = av1[i].c_str(); + } + LocalFree(w_av); + return CommandLineArguments(ac, &av2[0]); +#else + return CommandLineArguments(argc, argv); +#endif +} + +Encoding::CommandLineArguments::CommandLineArguments(int ac, + char const* const* av) +{ + this->argv_.resize(ac+1); + for(int i=0; i<ac; i++) + { + this->argv_[i] = strdup(av[i]); + } + this->argv_[ac] = 0; +} + +Encoding::CommandLineArguments::CommandLineArguments(int ac, + wchar_t const* const* av) +{ + this->argv_.resize(ac+1); + for(int i=0; i<ac; i++) + { + this->argv_[i] = kwsysEncoding_DupToNarrow(av[i]); + } + this->argv_[ac] = 0; +} + +Encoding::CommandLineArguments::~CommandLineArguments() +{ + for(size_t i=0; i<this->argv_.size(); i++) + { + free(argv_[i]); + } +} + +Encoding::CommandLineArguments:: + CommandLineArguments(const CommandLineArguments& other) +{ + this->argv_.resize(other.argv_.size()); + for(size_t i=0; i<this->argv_.size(); i++) + { + this->argv_[i] = other.argv_[i] ? strdup(other.argv_[i]) : 0; + } +} + +Encoding::CommandLineArguments& +Encoding::CommandLineArguments::operator=(const CommandLineArguments& other) +{ + if(this != &other) + { + size_t i; + for(i=0; i<this->argv_.size(); i++) + { + free(this->argv_[i]); + } + + this->argv_.resize(other.argv_.size()); + for(i=0; i<this->argv_.size(); i++) + { + this->argv_[i] = other.argv_[i] ? strdup(other.argv_[i]) : 0; + } + } + + return *this; +} + +int Encoding::CommandLineArguments::argc() const +{ + return static_cast<int>(this->argv_.size() - 1); +} + +char const* const* Encoding::CommandLineArguments::argv() const +{ + return &this->argv_[0]; +} + #if KWSYS_STL_HAS_WSTRING kwsys_stl::wstring Encoding::ToWide(const kwsys_stl::string& str) diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/FStream.cxx b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/FStream.cxx new file mode 100644 index 0000000000000000000000000000000000000000..018652c84e7aba8c99eb52d987b4277dc89e5b99 --- /dev/null +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/FStream.cxx @@ -0,0 +1,76 @@ +/*============================================================================ + KWSys - Kitware System Library + Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#include "kwsysPrivate.h" +#include KWSYS_HEADER(FStream.hxx) + +// Work-around CMake dependency scanning limitation. This must +// duplicate the above list of headers. +#if 0 +# include "FStream.hxx.in" +#endif + +namespace KWSYS_NAMESPACE +{ +namespace FStream +{ + +BOM ReadBOM(std::istream& in) +{ + if(!in.good()) + { + return BOM_None; + } + unsigned long orig = in.tellg(); + unsigned char bom[4]; + in.read(reinterpret_cast<char*>(bom), 2); + if(!in.good()) + { + in.seekg(orig); + return BOM_None; + } + if(bom[0] == 0xEF && bom[1] == 0xBB) + { + in.read(reinterpret_cast<char*>(bom+2), 1); + if(in.good() && bom[2] == 0xBF) + { + return BOM_UTF8; + } + } + else if(bom[0] == 0xFE && bom[1] == 0xFF) + { + return BOM_UTF16BE; + } + else if(bom[0] == 0x00 && bom[1] == 0x00) + { + in.read(reinterpret_cast<char*>(bom+2), 2); + if(in.good() && bom[2] == 0xFE && bom[3] == 0xFF) + { + return BOM_UTF32BE; + } + } + else if(bom[0] == 0xFF && bom[1] == 0xFE) + { + unsigned long p = in.tellg(); + in.read(reinterpret_cast<char*>(bom+2), 2); + if(in.good() && bom[2] == 0x00 && bom[3] == 0x00) + { + return BOM_UTF32LE; + } + in.seekg(p); + return BOM_UTF16LE; + } + in.seekg(orig); + return BOM_None; +} + +} // FStream namespace +} //KWSYS_NAMESPACE diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/FStream.hxx.in b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/FStream.hxx.in index 8170fb37b58543dd1f6dc8f946de9056b9758bfc..45425ffd6d14a700f9026cc3bbe5884b2f5d4de6 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/FStream.hxx.in +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/FStream.hxx.in @@ -25,8 +25,9 @@ namespace @KWSYS_NAMESPACE@ typedef std::basic_filebuf<CharType,Traits> my_base_type; basic_filebuf *open(char const *s,std::ios_base::openmode mode) { - my_base_type::open(Encoding::ToWide(s).c_str(), mode); - return this; + return static_cast<basic_filebuf*>( + my_base_type::open(Encoding::ToWide(s).c_str(), mode) + ); } }; @@ -81,7 +82,7 @@ namespace @KWSYS_NAMESPACE@ internal_buffer_type *rdbuf() const { - return buf_.get(); + return buf_; } ~basic_ifstream() @@ -160,13 +161,28 @@ class basic_ofstream : public std::basic_ostream<CharType,Traits> typedef basic_ofstream<char> ofstream; #else - using @KWSYS_NAMESPACE@_ios_namespace::basic_filebuf; using @KWSYS_NAMESPACE@_ios_namespace::ofstream; using @KWSYS_NAMESPACE@_ios_namespace::ifstream; #endif + namespace FStream + { + enum BOM + { + BOM_None, + BOM_UTF8, + BOM_UTF16BE, + BOM_UTF16LE, + BOM_UTF32BE, + BOM_UTF32LE + }; + + // Read a BOM, if one exists. + // If a BOM exists, the stream is advanced to after the BOM. + // This function requires a seekable stream (but not a relative + // seekable stream). + BOM ReadBOM(std::istream& in); + } } - - #endif diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/MD5.c b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/MD5.c index 56776a3249a2ac30d66a9175ae7fbb58673420d2..a1470572d7ab4b6e9e23735cda4ae8752bac97d3 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/MD5.c +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/MD5.c @@ -478,11 +478,16 @@ void kwsysMD5_Initialize(kwsysMD5* md5) /*--------------------------------------------------------------------------*/ void kwsysMD5_Append(kwsysMD5* md5, unsigned char const* data, int length) { + size_t dlen; if(length < 0) { - length = (int)strlen((char const*)data); + dlen = strlen((char const*)data); } - md5_append(&md5->md5_state, (md5_byte_t const*)data, (size_t)length); + else + { + dlen = (size_t)length; + } + md5_append(&md5->md5_state, (md5_byte_t const*)data, dlen); } /*--------------------------------------------------------------------------*/ diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/ProcessUNIX.c b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/ProcessUNIX.c index b9af2f1f5e76533f28aadc71437405edcf1fe122..faeb9679366acc3ce7fe5affc1fc6f28981007ad 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/ProcessUNIX.c +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/ProcessUNIX.c @@ -2449,6 +2449,7 @@ static void kwsysProcessKill(pid_t process_id) if(f) { size_t nread = fread(buffer, 1, KWSYSPE_PIPE_BUFFER_SIZE, f); + fclose(f); buffer[nread] = '\0'; if(nread > 0) { @@ -2463,7 +2464,6 @@ static void kwsysProcessKill(pid_t process_id) } } } - fclose(f); } } } diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SharedForward.h.in b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SharedForward.h.in index 8bbc74ac2696c49ca13cda03985d07cd391a5ede..dd4d462a5f8a8c7a841cbd2a25422f417bdefac0 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SharedForward.h.in +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SharedForward.h.in @@ -415,7 +415,7 @@ static int kwsys_shared_forward_realpath(const char* in_path, char* out_path) { #if defined(_WIN32) && !defined(__CYGWIN__) /* Implementation for Windows. */ - DWORD n = GetFullPathName(in_path, KWSYS_SHARED_FORWARD_MAXPATH, + DWORD n = GetFullPathNameA(in_path, KWSYS_SHARED_FORWARD_MAXPATH, out_path, 0); return n > 0 && n <= KWSYS_SHARED_FORWARD_MAXPATH; #else @@ -429,9 +429,9 @@ static int kwsys_shared_forward_samepath(const char* file1, const char* file2) { #if defined(_WIN32) int result = 0; - HANDLE h1 = CreateFile(file1, GENERIC_READ, FILE_SHARE_READ, NULL, + HANDLE h1 = CreateFileA(file1, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - HANDLE h2 = CreateFile(file2, GENERIC_READ, FILE_SHARE_READ, NULL, + HANDLE h2 = CreateFileA(file2, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if(h1 != INVALID_HANDLE_VALUE && h2 != INVALID_HANDLE_VALUE) { @@ -462,7 +462,7 @@ static void kwsys_shared_forward_strerror(char* message) #if defined(_WIN32) && !defined(__CYGWIN__) /* Implementation for Windows. */ DWORD original = GetLastError(); - DWORD length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | + DWORD length = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, original, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), message, KWSYS_SHARED_FORWARD_MAXPATH, 0); diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/System.c b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/System.c index 5d178bfa27b98f562fd4e126849a0db5b451af63..1ee26fac584aeba93a5ff8e11ccc871aa3e1292d 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/System.c +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/System.c @@ -353,6 +353,10 @@ static int kwsysSystem_Shell__GetArgumentSize(const char* in, if(kwsysSystem_Shell__ArgumentNeedsQuotes(in, isUnix, flags)) { /* Surrounding quotes are needed. Allocate space for them. */ + if((flags & kwsysSystem_Shell_Flag_WatcomQuote) && (isUnix)) + { + size += 2; + } size += 2; /* We must escape all ending backslashes when quoting on windows. */ @@ -377,7 +381,18 @@ static char* kwsysSystem_Shell__GetArgument(const char* in, char* out, if(needQuotes) { /* Add the opening quote for this argument. */ - *out++ = '"'; + if(flags & kwsysSystem_Shell_Flag_WatcomQuote) + { + if(isUnix) + { + *out++ = '"'; + } + *out++ = '\''; + } + else + { + *out++ = '"'; + } } /* Scan the string for characters that require escaping or quoting. */ @@ -549,7 +564,18 @@ static char* kwsysSystem_Shell__GetArgument(const char* in, char* out, } /* Add the closing quote for this argument. */ - *out++ = '"'; + if(flags & kwsysSystem_Shell_Flag_WatcomQuote) + { + *out++ = '\''; + if(isUnix) + { + *out++ = '"'; + } + } + else + { + *out++ = '"'; + } } /* Store a terminating null without incrementing. */ diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/System.h.in b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/System.h.in index 549db900cc6590a84865c16b8d4f5f26916dd30c..f21bf0dcaa4b02e59b0d50bc9645de15b8b3d997 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/System.h.in +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/System.h.in @@ -36,6 +36,7 @@ # define kwsysSystem_Shell_Flag_MinGWMake kwsys_ns(System_Shell_Flag_MinGWMake) # define kwsysSystem_Shell_Flag_NMake kwsys_ns(System_Shell_Flag_NMake) # define kwsysSystem_Shell_Flag_AllowMakeVariables kwsys_ns(System_Shell_Flag_AllowMakeVariables) +# define kwsysSystem_Shell_Flag_WatcomQuote kwsys_ns(System_Shell_Flag_WatcomQuote) #endif #ifdef __VMS @@ -102,14 +103,17 @@ enum kwsysSystem_Shell_Flag_e kwsysSystem_Shell_Flag_MinGWMake = (1<<4), /** The target shell is in a NMake makefile. */ - kwsysSystem_Shell_Flag_NMake = (1<<6), + kwsysSystem_Shell_Flag_NMake = (1<<5), /** Make variable reference syntax $(MAKEVAR) should not be escaped to allow a build tool to replace it. Replacement values containing spaces, quotes, backslashes, or other non-alphanumeric characters that have significance to some makes or shells produce undefined behavior. */ - kwsysSystem_Shell_Flag_AllowMakeVariables = (1<<5) + kwsysSystem_Shell_Flag_AllowMakeVariables = (1<<6), + + /** The target shell quoting uses extra single Quotes for Watcom tools. */ + kwsysSystem_Shell_Flag_WatcomQuote = (1<<7) }; /** @@ -156,6 +160,7 @@ kwsysEXPORT char** kwsysSystem_Parse_CommandForUnix(const char* command, # undef kwsysSystem_Shell_Flag_MinGWMake # undef kwsysSystem_Shell_Flag_NMake # undef kwsysSystem_Shell_Flag_AllowMakeVariables +# undef kwsysSystem_Shell_Flag_WatcomQuote # endif #endif diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SystemInformation.cxx b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SystemInformation.cxx index 2f6c949cd2c8a9c7679e9b7116f023bfbb572b9a..720a7c3b0dfe14d168cfc1a564a8d507680291ef 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SystemInformation.cxx +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SystemInformation.cxx @@ -3162,8 +3162,17 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() kwsys_stl::string cores = this->ExtractValueFromCpuInfoFile(buffer,"cpu cores"); int numberOfCoresPerCPU=atoi(cores.c_str()); - this->NumberOfPhysicalCPU=static_cast<unsigned int>( - numberOfCoresPerCPU*(maxId+1)); + if (maxId > 0) + { + this->NumberOfPhysicalCPU=static_cast<unsigned int>( + numberOfCoresPerCPU*(maxId+1)); + } + else + { + // Linux Sparc: get cpu count + this->NumberOfPhysicalCPU= + atoi(this->ExtractValueFromCpuInfoFile(buffer,"ncpus active").c_str()); + } #else // __CYGWIN__ // does not have "physical id" entries, neither "cpu cores" @@ -3185,7 +3194,19 @@ bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile() // CPU speed (checking only the first processor) kwsys_stl::string CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"cpu MHz"); - this->CPUSpeedInMHz = static_cast<float>(atof(CPUSpeed.c_str())); + if(!CPUSpeed.empty()) + { + this->CPUSpeedInMHz = static_cast<float>(atof(CPUSpeed.c_str())); + } +#ifdef __linux + else + { + // Linux Sparc: CPU speed is in Hz and encoded in hexadecimal + CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"Cpu0ClkTck"); + this->CPUSpeedInMHz = static_cast<float>( + strtoull(CPUSpeed.c_str(),0,16))/1000000.0f; + } +#endif // Chip family kwsys_stl::string familyStr = @@ -4677,11 +4698,28 @@ bool SystemInformationImplementation::QueryHaikuInfo() { #if defined(__HAIKU__) + // CPU count system_info info; get_system_info(&info); - this->NumberOfPhysicalCPU = info.cpu_count; - this->CPUSpeedInMHz = info.cpu_clock_speed / 1000000.0F; + + // CPU speed + uint32 topologyNodeCount = 0; + cpu_topology_node_info* topology = 0; + get_cpu_topology_info(0, &topologyNodeCount); + if (topologyNodeCount != 0) + topology = new cpu_topology_node_info[topologyNodeCount]; + get_cpu_topology_info(topology, &topologyNodeCount); + + for (uint32 i = 0; i < topologyNodeCount; i++) { + if (topology[i].type == B_TOPOLOGY_CORE) { + this->CPUSpeedInMHz = topology[i].data.core.default_frequency / + 1000000.0f; + break; + } + } + + delete[] topology; // Physical Memory this->TotalPhysicalMemory = (info.max_pages * B_PAGE_SIZE) / (1024 * 1024) ; @@ -4985,16 +5023,26 @@ bool SystemInformationImplementation::QueryHPUXProcessor() case CPU_PA_RISC1_0: this->ChipID.Vendor = "Hewlett-Packard"; this->ChipID.Family = 0x100; + break; case CPU_PA_RISC1_1: this->ChipID.Vendor = "Hewlett-Packard"; this->ChipID.Family = 0x110; + break; case CPU_PA_RISC2_0: this->ChipID.Vendor = "Hewlett-Packard"; this->ChipID.Family = 0x200; + break; +# if defined(CPU_HP_INTEL_EM_1_0) || defined(CPU_IA64_ARCHREV_0) +# ifdef CPU_HP_INTEL_EM_1_0 + case CPU_HP_INTEL_EM_1_0: +# endif +# ifdef CPU_IA64_ARCHREV_0 case CPU_IA64_ARCHREV_0: +# endif this->ChipID.Vendor = "GenuineIntel"; this->Features.HasIA64 = true; break; +# endif default: return false; } diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SystemTools.cxx b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SystemTools.cxx index 4649f3b23451b5d0237b783cd2748f5c904acdb6..32e79e62f36df419f904a4ac58ed450b87ded414 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SystemTools.cxx +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/SystemTools.cxx @@ -188,6 +188,9 @@ static inline char *realpath(const char *path, char *resolved_path) #endif #if defined(_WIN32) && (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__) || defined(__MINGW32__)) + +#include <wctype.h> + inline int Mkdir(const char* dir) { return _wmkdir(KWSYS_NAMESPACE::Encoding::ToWide(dir).c_str()); @@ -2115,10 +2118,10 @@ bool SystemTools::CopyFileAlways(const char* source, const char* destination) SystemTools::RemoveFile(destination); #if defined(_WIN32) || defined(__CYGWIN__) - kwsys_ios::ofstream fout(destination, + kwsys::ofstream fout(destination, kwsys_ios::ios::binary | kwsys_ios::ios::out | kwsys_ios::ios::trunc); #else - kwsys_ios::ofstream fout(destination, + kwsys::ofstream fout(destination, kwsys_ios::ios::out | kwsys_ios::ios::trunc); #endif if(!fout) @@ -4915,8 +4918,8 @@ void SystemTools::ClassInitialize() // Strip off one directory level and see if the logical // mapping still works. - pwd_str = SystemTools::GetFilenamePath(pwd_str.c_str()); - cwd_str = SystemTools::GetFilenamePath(cwd_str.c_str()); + pwd_str = SystemTools::GetFilenamePath(pwd_str); + cwd_str = SystemTools::GetFilenamePath(cwd_str); Realpath(pwd_str.c_str(), pwd_path); } diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/Terminal.c b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/Terminal.c index 25832c2b1f58a71992b2f63825e3abdf29e1ebd5..6d7ec413959082f7fb32b1b0dc78af41a76e6f65 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/Terminal.c +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/Terminal.c @@ -155,6 +155,7 @@ static const char* kwsysTerminalVT100Names[] = "mach-color", "mlterm", "putty", + "putty-256color", "rxvt", "rxvt-256color", "rxvt-cygwin", diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/hashtable.hxx.in b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/hashtable.hxx.in index 62aa3f3237b2014cee13490686d580cf0c00ef74..b93e9be6be8a0ab94546074de717b1ae4ac22bb8 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/hashtable.hxx.in +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/hashtable.hxx.in @@ -310,6 +310,9 @@ struct _Hashtable_node { _Hashtable_node* _M_next; _Val _M_val; + void public_method_to_quiet_warning_about_all_methods_private(); +private: + void operator=(_Hashtable_node<_Val> const&); // poison node assignment }; template <class _Val, class _Key, class _HashFcn, diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/kwsysHeaderDump.pl b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/kwsysHeaderDump.pl old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/testEncoding.cxx b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/testEncoding.cxx index 8e74a504764d2d8e00e947ce61a1443c4383face..094588c1e3e13b6732b088fc74e534ce908ae75f 100644 --- a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/testEncoding.cxx +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/testEncoding.cxx @@ -16,14 +16,18 @@ #endif #include KWSYS_HEADER(Encoding.hxx) +#include KWSYS_HEADER(Encoding.h) #include KWSYS_HEADER(ios/iostream) #include <locale.h> +#include <string.h> +#include <stdlib.h> // Work-around CMake dependency scanning limitation. This must // duplicate the above list of headers. #if 0 # include "Encoding.hxx.in" +# include "Encoding.h.in" # include "kwsys_ios_iostream.h.in" #endif @@ -68,11 +72,16 @@ static int testHelloWorldEncoding() std::cout << str << std::endl; std::wstring wstr = kwsys::Encoding::ToWide(str); std::string str2 = kwsys::Encoding::ToNarrow(wstr); - if(!wstr.empty() && str != str2) + wchar_t* c_wstr = kwsysEncoding_DupToWide(str.c_str()); + char* c_str2 = kwsysEncoding_DupToNarrow(c_wstr); + if(!wstr.empty() && (str != str2 || strcmp(c_str2, str.c_str()))) { std::cout << "converted string was different: " << str2 << std::endl; + std::cout << "converted string was different: " << c_str2 << std::endl; ret++; } + free(c_wstr); + free(c_str2); } return ret; } @@ -136,6 +145,36 @@ static int testRobustEncoding() return ret; } +static int testCommandLineArguments() +{ + int status = 0; + + char const* argv[2] = { + "./app.exe", + (char const*)helloWorldStrings[1] + }; + + kwsys::Encoding::CommandLineArguments args(2, argv); + kwsys::Encoding::CommandLineArguments arg2 = + kwsys::Encoding::CommandLineArguments(args); + + char const* const* u8_argv = args.argv(); + for(int i=0; i<args.argc(); i++) + { + char const* u8_arg = u8_argv[i]; + if(strcmp(argv[i], u8_arg) != 0) + { + std::cout << "argv[" << i << "] " << argv[i] << " != " + << u8_arg << std::endl; + status++; + } + } + + kwsys::Encoding::CommandLineArguments args3 = + kwsys::Encoding::CommandLineArguments::Main(2, argv); + + return status; +} //---------------------------------------------------------------------------- int testEncoding(int, char*[]) @@ -154,6 +193,7 @@ int testEncoding(int, char*[]) ret |= testHelloWorldEncoding(); ret |= testRobustEncoding(); + ret |= testCommandLineArguments(); return ret; } diff --git a/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/testFStream.cxx b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/testFStream.cxx new file mode 100644 index 0000000000000000000000000000000000000000..9abfd4caa74ac1d335a171cc66615f31dfddc69b --- /dev/null +++ b/Utilities/ITK/Modules/ThirdParty/KWSys/src/KWSys/testFStream.cxx @@ -0,0 +1,190 @@ +/*============================================================================ + KWSys - Kitware System Library + Copyright 2000-2009 Kitware, Inc., Insight Software Consortium + + Distributed under the OSI-approved BSD License (the "License"); + see accompanying file Copyright.txt for details. + + This software is distributed WITHOUT ANY WARRANTY; without even the + implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + See the License for more information. +============================================================================*/ +#include "kwsysPrivate.h" + +#if defined(_MSC_VER) +# pragma warning (disable:4786) +#endif + +#include KWSYS_HEADER(FStream.hxx) +#include KWSYS_HEADER(ios/iostream) +#include <string.h> +#ifdef __BORLANDC__ +# include <mem.h> /* memcmp */ +#endif + +// Work-around CMake dependency scanning limitation. This must +// duplicate the above list of headers. +#if 0 +# include "FStream.hxx.in" +# include "kwsys_ios_iostream.h.in" +#endif + + +//---------------------------------------------------------------------------- +static int testNoFile() +{ + kwsys::ifstream in_file("NoSuchFile.txt"); + if(in_file) + { + return 1; + } + + return 0; +} + +static kwsys::FStream::BOM expected_bom[5] = +{ + kwsys::FStream::BOM_UTF8, + kwsys::FStream::BOM_UTF16LE, + kwsys::FStream::BOM_UTF16BE, + kwsys::FStream::BOM_UTF32LE, + kwsys::FStream::BOM_UTF32BE +}; + +static unsigned char expected_bom_data[5][5] = +{ + {3, 0xEF, 0xBB, 0xBF}, + {2, 0xFF, 0xFE}, + {2, 0xFE, 0xFF}, + {4, 0xFF, 0xFE, 0x00, 0x00}, + {4, 0x00, 0x00, 0xFE, 0xFF}, +}; + +static unsigned char file_data[5][45] = +{ + {11, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}, + {22, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20, 0x00, + 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64, 0x00}, + {22, 0x00, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20, + 0x00, 0x57, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x6C, 0x00, 0x64}, + {44, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, + 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00, 0x00, + 0x6C, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00}, + {44, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x6C, + 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x20, + 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x6F, 0x00, 0x00, 0x00, 0x72, + 0x00, 0x00, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x64}, +}; + +//---------------------------------------------------------------------------- +static int testBOM() +{ + // test various encodings in binary mode + for(int i=0; i<5; i++) + { + { + kwsys::ofstream out("bom.txt", kwsys::ofstream::binary); + out.write(reinterpret_cast<const char*>(expected_bom_data[i]+1), + *expected_bom_data[i]); + out.write(reinterpret_cast<const char*>(file_data[i]+1), + file_data[i][0]); + } + + kwsys::ifstream in("bom.txt", kwsys::ofstream::binary); + kwsys::FStream::BOM bom = kwsys::FStream::ReadBOM(in); + if(bom != expected_bom[i]) + { + kwsys_ios::cout << "Unexpected BOM " << i << std::endl; + return 1; + } + char data[45]; + in.read(data, file_data[i][0]); + if(!in.good()) + { + kwsys_ios::cout << "Unable to read data " << i << std::endl; + return 1; + } + + if(memcmp(data, file_data[i]+1, file_data[i][0]) != 0) + { + kwsys_ios::cout << "Incorrect read data " << i << std::endl; + return 1; + } + + } + + // test text file without bom + { + { + kwsys::ofstream out("bom.txt"); + out << "Hello World"; + } + + kwsys::ifstream in("bom.txt"); + kwsys::FStream::BOM bom = kwsys::FStream::ReadBOM(in); + if(bom != kwsys::FStream::BOM_None) + { + kwsys_ios::cout << "Unexpected BOM for none case" << std::endl; + return 1; + } + char data[45]; + in.read(data, file_data[0][0]); + if(!in.good()) + { + kwsys_ios::cout << "Unable to read data for none case" << std::endl; + return 1; + } + + if(memcmp(data, file_data[0]+1, file_data[0][0]) != 0) + { + kwsys_ios::cout << "Incorrect read data for none case" << std::endl; + return 1; + } + } + + // test text file with utf-8 bom + { + { + kwsys::ofstream out("bom.txt"); + out.write(reinterpret_cast<const char*>(expected_bom_data[0]+1), + *expected_bom_data[0]); + out << "Hello World"; + } + + kwsys::ifstream in("bom.txt"); + kwsys::FStream::BOM bom = kwsys::FStream::ReadBOM(in); + if(bom != kwsys::FStream::BOM_UTF8) + { + kwsys_ios::cout << "Unexpected BOM for utf-8 case" << std::endl; + return 1; + } + char data[45]; + in.read(data, file_data[0][0]); + if(!in.good()) + { + kwsys_ios::cout << "Unable to read data for utf-8 case" << std::endl; + return 1; + } + + if(memcmp(data, file_data[0]+1, file_data[0][0]) != 0) + { + kwsys_ios::cout << "Incorrect read data for utf-8 case" << std::endl; + return 1; + } + } + + return 0; +} + + +//---------------------------------------------------------------------------- +int testFStream(int, char*[]) +{ + int ret = 0; + + ret |= testNoFile(); + ret |= testBOM(); + + return ret; +} diff --git a/Utilities/ITK/Modules/ThirdParty/Netlib/src/netlib/slatec/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/Netlib/src/netlib/slatec/CMakeLists.txt index 4e3cb408e098001dc3641be7422c626ccedfc1d9..522662a2448fe6704395edb99e05f81e8d754435 100644 --- a/Utilities/ITK/Modules/ThirdParty/Netlib/src/netlib/slatec/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/Netlib/src/netlib/slatec/CMakeLists.txt @@ -19,7 +19,7 @@ ADD_LIBRARY( itkNetlibSlatec initds.c xermsg.c d_int.c - d_mod.c + d_mod.c ) IF(ITK_USE_SYSTEM_VXL) @@ -32,13 +32,11 @@ IF(ITK_LIBRARY_PROPERTIES) SET_TARGET_PROPERTIES(itkNetlibSlatec PROPERTIES ${ITK_LIBRARY_PROPERTIES}) ENDIF(ITK_LIBRARY_PROPERTIES) -IF(NOT ITK_INSTALL_NO_LIBRARIES) - INSTALL(TARGETS itkNetlibSlatec - EXPORT ${ITK3P_INSTALL_EXPORT_NAME} - RUNTIME DESTINATION ${ITK3P_INSTALL_RUNTIME_DIR} COMPONENT RuntimeLibraries - LIBRARY DESTINATION ${ITK3P_INSTALL_LIBRARY_DIR} COMPONENT RuntimeLibraries - ARCHIVE DESTINATION ${ITK3P_INSTALL_ARCHIVE_DIR} COMPONENT Development) -ENDIF(NOT ITK_INSTALL_NO_LIBRARIES) +INSTALL(TARGETS itkNetlibSlatec + EXPORT ${ITK3P_INSTALL_EXPORT_NAME} + RUNTIME DESTINATION ${ITK3P_INSTALL_RUNTIME_DIR} COMPONENT RuntimeLibraries + LIBRARY DESTINATION ${ITK3P_INSTALL_LIBRARY_DIR} COMPONENT RuntimeLibraries + ARCHIVE DESTINATION ${ITK3P_INSTALL_ARCHIVE_DIR} COMPONENT Development) IF (BORLAND) SET (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -w-8004 -w-8057") diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/DSPTemplates/mex/configure b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/DSPTemplates/mex/configure old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/DSPTemplates/mex/install-sh b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/DSPTemplates/mex/install-sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/config/vxl_shared_link_test/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/config/vxl_shared_link_test/CMakeLists.txt index 25f26b1629ffcf4a8cb512f4b1b5a561e2b5f3d6..47050277e164e31037d0650769b3e32642cc9b5f 100644 --- a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/config/vxl_shared_link_test/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/config/vxl_shared_link_test/CMakeLists.txt @@ -1,8 +1,14 @@ # vxl/config/cmake/config/vxl_shared_link_test/CMakeLists.txt # - +cmake_minimum_required(VERSION 2.8.6 FATAL_ERROR) +IF(POLICY CMP0025) + CMAKE_POLICY(SET CMP0025 NEW) +ENDIF() +IF(POLICY CMP0042) + CMAKE_POLICY(SET CMP0042 NEW) +ENDIF() PROJECT(vxl_pic_compatible) ADD_LIBRARY(cmTryCompileStaticLib STATIC static_src.cxx) ADD_LIBRARY(cmTryCompileSharedLib SHARED shared_src.cxx) -TARGET_LINK_LIBRARIES(cmTryCompileSharedLib cmTryCompileStaticLib ${LINK_LIBRARIES}) \ No newline at end of file +TARGET_LINK_LIBRARIES(cmTryCompileSharedLib cmTryCompileStaticLib ${LINK_LIBRARIES}) diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/doxygen/vxl_doxy.pl b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/config/cmake/doxygen/vxl_doxy.pl old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/tests/test_sparse_lm.cxx b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/tests/test_sparse_lm.cxx index b7cd225c38d8b506486a9266a4a24106ffbcd14a..fda2c7c9a0c7f8065a7e0ef912ba24a38812d145 100644 --- a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/tests/test_sparse_lm.cxx +++ b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/tests/test_sparse_lm.cxx @@ -630,7 +630,7 @@ void test_prob3() // initial perturbed parameters, add random gaussian noise vnl_vector<double> init_a(a_data,12), init_b(b_data,50); double sigma_pos = 1.0, sigma_ang = 0.1; - vnl_random rnd; + vnl_random rnd(1234); for (unsigned i=0; i<init_a.size()/3; ++i) { init_a[3*i] += rnd.normal()*sigma_ang; diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/vnl_lbfgsb.cxx b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/vnl_lbfgsb.cxx index 345160a4eebbdf75d0460210bd21f41d1f60039f..e6166e3198e963dd0871e995fd1b4540bc8c242b 100644 --- a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/vnl_lbfgsb.cxx +++ b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/vnl_lbfgsb.cxx @@ -160,7 +160,7 @@ bool vnl_lbfgsb::minimize(vnl_vector<double>& x) // function tolerance reached this->failure_code_ = CONVERGED_FTOL; } - else if (vcl_strncmp("CONVERGENCE: NORM OF PROJECTED GRADIENT <= PGTOL", + else if (vcl_strncmp("CONVERGENCE:_NORM_OF_PROJECTED_GRADIENT_<=_PGTOL", task, 48) == 0) { // gradient tolerance reached diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/vnl_diag_matrix.h b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/vnl_diag_matrix.h index 77dabedd37c5342e22a67ae515f1600e4ea9ba0a..d432f1696e14bb021ae0fd4eb41bfabcce99a65d 100644 --- a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/vnl_diag_matrix.h +++ b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/core/vnl/vnl_diag_matrix.h @@ -79,15 +79,8 @@ class vnl_diag_matrix return (i != j) ? T(0) : diagonal_[i]; } - inline T& operator () (unsigned i, -//Need to avoid compiler bug by not supplying the value of j unless checking the assert. -#ifdef NDEBUG -unsigned -#else -unsigned j -#endif -) { - assert(i == j); + inline T& operator () (unsigned i, unsigned j) { + assert(i == j); (void)j; return diagonal_[i]; } inline T& operator() (unsigned i) { return diagonal_[i]; } diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/v3p/netlib/libf2c/comptry.bat b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/v3p/netlib/libf2c/comptry.bat old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/v3p/netlib/libf2c/scomptry.bat b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/v3p/netlib/libf2c/scomptry.bat old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/vcl/generic/zap.pl b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/vcl/generic/zap.pl old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/vcl/iso/generate.sh b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/vcl/iso/generate.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/vcl/tr1/generate.sh b/Utilities/ITK/Modules/ThirdParty/VNL/src/vxl/vcl/tr1/generate.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Modules/ThirdParty/ZLIB/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/ZLIB/CMakeLists.txt index 939735f7c9287507378cf5d3895a8b6eda6ff257..b00c05150a0e3d825367a41f71079ab63347cf92 100644 --- a/Utilities/ITK/Modules/ThirdParty/ZLIB/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/ZLIB/CMakeLists.txt @@ -26,7 +26,7 @@ configure_file(src/itk_zlib.h.in src/itk_zlib.h) itk_module_impl() -if(NOT ITK_INSTALL_NO_DEVELOPMENT) - install(FILES ${ITKZLIB_BINARY_DIR}/src/itk_zlib.h - DESTINATION ${ITKZLIB_INSTALL_INCLUDE_DIR}) -endif(NOT ITK_INSTALL_NO_DEVELOPMENT) +install(FILES ${ITKZLIB_BINARY_DIR}/src/itk_zlib.h + DESTINATION ${ITKZLIB_INSTALL_INCLUDE_DIR} + COMPONENT Development + ) diff --git a/Utilities/ITK/Modules/ThirdParty/ZLIB/src/itkzlib/CMakeLists.txt b/Utilities/ITK/Modules/ThirdParty/ZLIB/src/itkzlib/CMakeLists.txt index 3528c4f6a449e28b0b76c4223e77030dd4b5db65..968742d3008e0b6797e172dbef8244dfb77a1900 100644 --- a/Utilities/ITK/Modules/ThirdParty/ZLIB/src/itkzlib/CMakeLists.txt +++ b/Utilities/ITK/Modules/ThirdParty/ZLIB/src/itkzlib/CMakeLists.txt @@ -34,21 +34,17 @@ if(ITK_LIBRARY_PROPERTIES) set_target_properties(itkzlib PROPERTIES ${ITK_LIBRARY_PROPERTIES}) endif(ITK_LIBRARY_PROPERTIES) -if(NOT ITK_INSTALL_NO_LIBRARIES) - install(TARGETS itkzlib - EXPORT ${ITK3P_INSTALL_EXPORT_NAME} - RUNTIME DESTINATION ${ITK3P_INSTALL_RUNTIME_DIR} COMPONENT RuntimeLibraries - LIBRARY DESTINATION ${ITK3P_INSTALL_LIBRARY_DIR} COMPONENT RuntimeLibraries - ARCHIVE DESTINATION ${ITK3P_INSTALL_ARCHIVE_DIR} COMPONENT Development - ) -endif(NOT ITK_INSTALL_NO_LIBRARIES) - -if(NOT ITK_INSTALL_NO_DEVELOPMENT) - install(FILES - ${ITK3P_ZLIB_SOURCE_DIR}/zlib.h - ${ITK3P_ZLIB_SOURCE_DIR}/zconf.h - ${ITK3P_ZLIB_SOURCE_DIR}/itk_zlib_mangle.h - ${ITK3P_ZLIB_BINARY_DIR}/zlibDllConfig.h - DESTINATION ${ITK3P_INSTALL_INCLUDE_DIR}/itkzlib # itk_zlib.h #include "itkzlib/zlib.h" - COMPONENT Development) -endif(NOT ITK_INSTALL_NO_DEVELOPMENT) +install(TARGETS itkzlib + EXPORT ${ITK3P_INSTALL_EXPORT_NAME} + RUNTIME DESTINATION ${ITK3P_INSTALL_RUNTIME_DIR} COMPONENT RuntimeLibraries + LIBRARY DESTINATION ${ITK3P_INSTALL_LIBRARY_DIR} COMPONENT RuntimeLibraries + ARCHIVE DESTINATION ${ITK3P_INSTALL_ARCHIVE_DIR} COMPONENT Development + ) + +install(FILES + ${ITK3P_ZLIB_SOURCE_DIR}/zlib.h + ${ITK3P_ZLIB_SOURCE_DIR}/zconf.h + ${ITK3P_ZLIB_SOURCE_DIR}/itk_zlib_mangle.h + ${ITK3P_ZLIB_BINARY_DIR}/zlibDllConfig.h + DESTINATION ${ITK3P_INSTALL_INCLUDE_DIR}/itkzlib # itk_zlib.h #include "itkzlib/zlib.h" + COMPONENT Development) diff --git a/Utilities/ITK/Modules/ThirdParty/pygccxml/src/README-ITK.txt b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/README-ITK.txt new file mode 100644 index 0000000000000000000000000000000000000000..3e1b559d2e015979580939f3de57df8a3daf6d06 --- /dev/null +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/README-ITK.txt @@ -0,0 +1,15 @@ +The Modules/ThirdParty/pygccxml/src/ +subdirectory contains a reduced distribution of the pygccxml source tree with +just the library source. + +This module is used by WrapITK to build the wrappings. We distribute our own +version so that the user does not have to install this dependency. +This module does not need to be compiled as it is a pure python module. +We do not allow (for the moment) the usage the systems pygccxml and rely +on the one shipped here. + +See Modules/ThirdParty/VNL/src/README-ITK.txt for update procedure of the +snapshot using a subtree merge. + +The last merged upstream snapshot commit hash is: +9f6f8dfecd74fdec274c1dbc273f785b529b5909 diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/__init__.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/__init__.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/__init__.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/__init__.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/__init__.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/__init__.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/__init__.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/__init__.py index 0daa07bdcbbc4b94fec0182d40bcafc96bd4cee5..e24850ccdd4644931bdf19c732de4f701d95a846 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/__init__.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/__init__.py @@ -335,3 +335,11 @@ __impl_decl_types[ namespace_t.free_function ] = free_function_t __impl_matchers[ namespace_t.free_operator ] = operator_matcher_t __impl_decl_types[ namespace_t.free_operator ] = free_operator_t + + + + + + + + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/algorithm.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/algorithm.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/algorithm.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/algorithm.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/algorithms_cache.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/algorithms_cache.py similarity index 93% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/algorithms_cache.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/algorithms_cache.py index 4471eae56ae253c51f0ce9f384ef3923f8a6b9df..6a85fd40400b533bb8f601ba33a8c4e113868e28 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/algorithms_cache.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/algorithms_cache.py @@ -17,8 +17,8 @@ class declaration_algs_cache_t( object ): self._access_type = None self._demangled_name = None self._declaration_path = None - self._partial_declaration_path = None - self._container_key_type = None + self._partial_declaration_path = None + self._container_key_type = None self._container_element_type = None def disable( self ): @@ -36,7 +36,7 @@ class declaration_algs_cache_t( object ): def _set_full_name( self, fname ): if not self.enabled: fname = None - self._full_name = fname + self._full_name = fname full_name = property( _get_full_name, _set_full_name ) def _get_full_partial_name( self ): @@ -44,7 +44,7 @@ class declaration_algs_cache_t( object ): def _set_full_partial_name( self, fname ): if not self.enabled: fname = None - self._full_partial_name = fname + self._full_partial_name = fname full_partial_name = property( _get_full_partial_name, _set_full_partial_name ) def _get_access_type( self ): @@ -59,8 +59,8 @@ class declaration_algs_cache_t( object ): return self._demangled_name def _set_demangled_name( self, demangled_name ): if not self.enabled: - demangled_name = None - self._demangled_name = demangled_name + demangled_name = None + self._demangled_name = demangled_name demangled_name = property( _get_demangled_name, _set_demangled_name ) def _get_declaration_path( self ): @@ -87,14 +87,14 @@ class declaration_algs_cache_t( object ): etype = None self._container_element_type = etype container_element_type = property( _get_container_element_type, _set_container_element_type ) - + def _get_container_key_type( self ): return self._container_key_type def _set_container_key_type( self, ktype ): if not self.enabled: ktype = None self._container_key_type = ktype - container_key_type = property( _get_container_key_type, _set_container_key_type ) + container_key_type = property( _get_container_key_type, _set_container_key_type ) def reset( self ): self.full_name = None @@ -120,7 +120,7 @@ class declaration_algs_cache_t( object ): class type_algs_cache_t( object ): enabled = True - + @staticmethod def disable(): type_algs_cache_t.enabled = False @@ -139,8 +139,9 @@ class type_algs_cache_t( object ): if not type_algs_cache_t.enabled: remove_alias = None self._remove_alias = remove_alias - + remove_alias = property( _get_remove_alias, _set_remove_alias ) def reset(self): self.remove_alias = None + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/call_invocation.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/call_invocation.py similarity index 96% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/call_invocation.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/call_invocation.py index 1858df4198827c7716162e0309b9bd8e0bb5d246..058242c9cf3207dcebd6bb03180ce578dc054fc2 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/call_invocation.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/call_invocation.py @@ -3,11 +3,11 @@ # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) -""" +""" free function call parser -This module implements all functionality necessary to parse C++ free function -invocation. In other words this module is able to extract next information from +This module implements all functionality necessary to parse C++ free function +invocation. In other words this module is able to extract next information from the string like this C{ print_message( message ) }. - name ( print_message ) - list of arguments ( message ) @@ -22,10 +22,10 @@ __THE_PARSER = pattern_parser.parser_t( '(', ')', ',' ) def is_call_invocation( decl_string ): """ returns True if decl_string is function invocation and False otherwise - + @param decl_string: string that should be checked for pattern presence @type decl_string: str - + @return: bool """ global __THE_PARSER @@ -34,7 +34,7 @@ def is_call_invocation( decl_string ): def name( decl_string ): """ returns name of function - + @type decl_string: str @return: str """ @@ -44,7 +44,7 @@ def name( decl_string ): def args( decl_string ): """ returns list of function arguments - + @type decl_string: str @return: [str] """ @@ -55,7 +55,7 @@ NOT_FOUND = __THE_PARSER.NOT_FOUND def find_args( text, start=None ): """ finds arguments within function invocation. - + @type text: str @return: [ arguments ] or L{NOT_FOUND} if arguments could not be found """ @@ -66,7 +66,7 @@ def split( decl_string ): """returns (name, [arguments] )""" global __THE_PARSER return __THE_PARSER.split( decl_string ) - + def split_recursive( decl_string ): """returns [(name, [arguments])]""" global __THE_PARSER diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/calldef.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/calldef.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py index ab95463a5f19c432d04b54a592bad5fca4fe3694..8fcd8813cb0c8cc7025aecea0e4b160264715e4c 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/calldef.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/calldef.py @@ -44,11 +44,11 @@ class argument_t(object): self._name = name self._default_value = default_value self._type = type - self._attributes = attributes + self._attributes = attributes def clone( self, **keywd ): """constructs new argument_t instance - + return argument_t( name=keywd.get( 'name', self.name ) , type=keywd.get( 'type', self.type ) , default_value=keywd.get( 'default_value', self.default_value ) @@ -59,7 +59,7 @@ class argument_t(object): , type=keywd.get( 'type', self.type ) , default_value=keywd.get( 'default_value', self.default_value ) , attributes=keywd.get( 'attributes', self.attributes ) ) - + def __str__(self): if self.ellipsis: return "..." @@ -114,7 +114,7 @@ class argument_t(object): type = property( _get_type, _set_type , doc="""The type of the argument. @type: L{type_t}""") - + def _get_attributes( self ): return self._attributes def _set_attributes( self, attributes ): @@ -203,7 +203,7 @@ class calldef_t( declaration.declaration_t ): self._does_throw = does_throw does_throw = property( _get_does_throw, _set_does_throw, doc="""If False, than function does not throw any exception. - In this case, function was declared with empty throw + In this case, function was declared with empty throw statement. """) @@ -226,9 +226,9 @@ class calldef_t( declaration.declaration_t ): @property def overloads(self): """A list of overloaded "callables" (i.e. other callables with the same name within the same scope. - + @type: list of L{calldef_t} - """ + """ if not self.parent: return [] # finding all functions with the same name @@ -313,7 +313,7 @@ class calldef_t( declaration.declaration_t ): report_dependency = lambda *args, **keywd: dependencies.dependency_info_t( self, *args, **keywd ) answer = [] if self.return_type: - answer.append( report_dependency( self.return_type, hint="return type" ) ) + answer.append( report_dependency( self.return_type, hint="return type" ) ) map( lambda arg: answer.append( report_dependency( arg.type ) ) , self.arguments ) map( lambda exception: answer.append( report_dependency( exception, hint="exception" ) ) @@ -506,11 +506,11 @@ class constructor_t( member_calldef_t ): if not isinstance( unaliased.base, cpptypes.declarated_t ): return False return id(unaliased.base.declaration) == id(self.parent) - + @property def is_trivial_constructor(self): return not bool( self.arguments ) - + class destructor_t( member_calldef_t ): """describes deconstructor declaration""" @@ -541,7 +541,7 @@ class free_operator_t( free_calldef_t, operator_t ): free_calldef_t.__init__( self, *args, **keywords ) operator_t.__init__( self, *args, **keywords ) self.__class_types = None - + @property def class_types( self ): """list of class/class declaration types, extracted from the operator arguments""" diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/class_declaration.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/class_declaration.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py index fd9c7967ec1b27a27c52b9d60b0cdd9c5b915904..ef6ba6dcf4d881d943b3a975f3cb275d19271222 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/class_declaration.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py @@ -457,7 +457,7 @@ class class_t( scopedef.scopedef_t ): def i_depend_on_them( self, recursive=True ): report_dependency = lambda *args: dependencies.dependency_info_t( self, *args ) - + answer = [] map( lambda base: answer.append( report_dependency( base.related_class, base.access_type, "base class" ) ) @@ -500,8 +500,8 @@ class class_t( scopedef.scopedef_t ): return 'wstring' else: return get_partial_name( self.name ) - - def find_noncopyable_vars( self ): + + def find_noncopyable_vars( self ): """returns list of all noncopyable variables""" import type_traits as tt#prevent cyclic dependencies logger = utils.loggers.cxx_parser @@ -524,7 +524,7 @@ class class_t( scopedef.scopedef_t ): cls = tt.class_traits.get_declaration( type_ ) if tt.is_noncopyable( cls ): logger.debug( "__contains_noncopyable_mem_var - %s - TRUE - containes member variable - class that is not copyable" % self.decl_string ) - noncopyable_vars.append( mvar ) + noncopyable_vars.append( mvar ) logger.debug( "__contains_noncopyable_mem_var - %s - false - doesn't contains noncopyable members" % self.decl_string ) return noncopyable_vars diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/compilers.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/compilers.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/compilers.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/compilers.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/container_traits.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/container_traits.py similarity index 97% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/container_traits.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/container_traits.py index 53061a9350ff09927954195081e5df04e1f6fe13..8c3a883a78bbb21bb25829166347e59ff3faab57 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/container_traits.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/container_traits.py @@ -258,7 +258,7 @@ class container_traits_impl_t: , container_name , element_type_index , element_type_typedef - , defaults_remover + , defaults_remover , key_type_index=None , key_type_typedef=None ): """ @@ -267,7 +267,7 @@ class container_traits_impl_t: arguments list element_type_typedef - class typedef to the value\\mapped type key_type_index - position of key type within template arguments list - key_type_typedef - class typedef to the key type + key_type_typedef - class typedef to the key type """ self._name = container_name self.remove_defaults_impl = defaults_remover @@ -314,16 +314,16 @@ class container_traits_impl_t: def is_sequence( self, type ): #raise exception if type is not container - unused = self.class_declaration( type ) + unused = self.class_declaration( type ) return self.key_type_index is None - + def is_mapping( self, type ): return not self.is_sequence( type ) def __find_xxx_type( self, type, xxx_index, xxx_typedef, cache_property_name ): cls = self.class_declaration( type ) result = getattr( cls.cache, cache_property_name ) - if not result: + if not result: if isinstance( cls, class_declaration.class_t ): xxx_type = cls.typedef( xxx_typedef, recursive=False ).type result = type_traits.remove_declarated( xxx_type ) @@ -344,7 +344,7 @@ class container_traits_impl_t: , 'container_element_type') def key_type( self, type ): - """returns reference to the class key type declaration""" + """returns reference to the class key type declaration""" if not self.is_mapping( type ): raise TypeError( 'Type "%s" is not "mapping" container' % str( type ) ) return self.__find_xxx_type( type @@ -354,11 +354,11 @@ class container_traits_impl_t: def remove_defaults( self, type_or_string ): """remove template defaults from a template class instantiation - + For example: - std::vector< int, std::allocator< int > > + std::vector< int, std::allocator< int > > will become - std::vector< int > + std::vector< int > """ name = type_or_string if not isinstance( type_or_string, types.StringTypes ): @@ -408,11 +408,11 @@ map_traits = create_traits( 'map' , defaults_eraser.erase_map_compare_allocator , key_type_index=0 , key_type_typedef='key_type') - + multimap_traits = create_traits( 'multimap' , 1 , 'mapped_type' - , defaults_eraser.erase_map_compare_allocator + , defaults_eraser.erase_map_compare_allocator , key_type_index=0 , key_type_typedef='key_type') @@ -420,15 +420,15 @@ multimap_traits = create_traits( 'multimap' hash_map_traits = create_traits( 'hash_map' , 1 , 'mapped_type' - , defaults_eraser.erase_hashmap_compare_allocator + , defaults_eraser.erase_hashmap_compare_allocator , key_type_index=0 , key_type_typedef='key_type') - - + + hash_multimap_traits = create_traits( 'hash_multimap' , 1 , 'mapped_type' - , defaults_eraser.erase_hashmap_compare_allocator + , defaults_eraser.erase_hashmap_compare_allocator , key_type_index=0 , key_type_typedef='key_type') @@ -436,7 +436,7 @@ set_traits = create_traits( 'set' , 0 , 'value_type' , defaults_eraser.erase_compare_allocator) - + multiset_traits = create_traits( 'multiset' , 0 , 'value_type' @@ -446,7 +446,7 @@ hash_set_traits = create_traits( 'hash_set' , 0 , 'value_type' , defaults_eraser.erase_hash_allocator ) - + hash_multiset_traits = create_traits( 'hash_multiset' , 0 , 'value_type' @@ -483,3 +483,5 @@ def find_container_traits( cls_or_string ): for cls_traits in container_traits: if cls_traits.is_my_case( cls_or_string ): return cls_traits + + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/cpptypes.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/cpptypes.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/cpptypes.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/cpptypes.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/decl_factory.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_factory.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/decl_factory.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_factory.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/decl_printer.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_printer.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/decl_printer.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_printer.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/decl_visitor.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_visitor.py similarity index 93% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/decl_visitor.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_visitor.py index db148e7f1011556ae9230974e3481ef753d19b45..896fb193226c60af23ada7d1a830b57cb3ecf98b 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/decl_visitor.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/decl_visitor.py @@ -10,47 +10,47 @@ defines declarations visitor class interface class decl_visitor_t(object): """ declarations visitor interface - + All functions within this class should be redefined in derived classes. """ def __init__(self): object.__init__(self) - + def visit_member_function( self ): raise NotImplementedError() - + def visit_constructor( self ): raise NotImplementedError() - + def visit_destructor( self ): raise NotImplementedError() - + def visit_member_operator( self ): raise NotImplementedError() - + def visit_casting_operator( self ): raise NotImplementedError() - + def visit_free_function( self ): raise NotImplementedError() - + def visit_free_operator( self ): raise NotImplementedError() def visit_class_declaration(self ): raise NotImplementedError() - + def visit_class(self ): raise NotImplementedError() - + def visit_enumeration(self ): raise NotImplementedError() - + def visit_namespace(self ): raise NotImplementedError() - + def visit_typedef(self ): raise NotImplementedError() - + def visit_variable(self ): raise NotImplementedError() \ No newline at end of file diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/declaration.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py similarity index 98% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/declaration.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py index 6850dcfed02908de64e155344fa8928464f1a84e..e61fd4878bcf690a574e1b688339e8d7b40b1e5c 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/declaration.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/declaration.py @@ -63,12 +63,12 @@ class declaration_t( object ): self._is_artificial = is_artificial self._mangled = mangled self._demangled = demangled - self._attributes = attributes + self._attributes = attributes self._parent = None self._cache = algorithms_cache.declaration_algs_cache_t() self._compiler = None self._partial_name = None - + def __str__(self): """Default __str__ method. @@ -163,10 +163,10 @@ class declaration_t( object ): def _get_partial_name_impl( self ): return self.name - + @property def partial_name( self ): - """declaration name, without template default arguments + """declaration name, without template default arguments Right now std containers is the only classes that support this functionality""" if None is self._partial_name: self._partial_name = self._get_partial_name_impl() diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/dependencies.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/dependencies.py similarity index 96% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/dependencies.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/dependencies.py index e811dba29957ab09109babe3a5b3a6e14a6372fb..6abe4ddcb4759a94718c6f0bb8a37b13e5d2e55e 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/dependencies.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/dependencies.py @@ -19,21 +19,21 @@ class dependency_info_t( object ): self._depend_on_it = depend_on_it self._access_type = access_type self._hint = hint - + @property def declaration( self ): return self._declaration #short name decl = declaration - @property + @property def depend_on_it( self ): return self._depend_on_it - + def _get_access_type( self ): return self._access_type def _set_access_type( self, access_type ): - self._access_type = access_type + self._access_type = access_type access_type = property( _get_access_type, _set_access_type ) def __str__( self ): @@ -52,7 +52,7 @@ class dependency_info_t( object ): """ #prevent recursive import from pygccxml import declarations - + if isinstance( self.depend_on_it, declarations.declaration_t ): return self.depend_on_it base_type = declarations.base_type( declarations.remove_alias( self.depend_on_it ) ) diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/enumeration.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/enumeration.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/enumeration.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/enumeration.py index e5b90e3dd75201a6e6f0370e84ba712c4872bd90..a77e51bcec91403569381a592071dc9361035fef 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/enumeration.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/enumeration.py @@ -135,3 +135,4 @@ class enumeration_t( declaration.declaration_t ): self._byte_align = new_byte_align byte_align = property( _get_byte_align, _set_byte_align , doc="Alignment of this class in bytes @type: int") + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/filtering.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/filtering.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/filtering.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/filtering.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/function_traits.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/function_traits.py similarity index 95% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/function_traits.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/function_traits.py index 56bdb50de22571f25d7103a6baccce7bfe68ec01..25b3f7cd0ef331dfb6218d0e46bcb963fb22a9f6 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/function_traits.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/function_traits.py @@ -13,17 +13,17 @@ import class_declaration def is_same_return_type( f1, f2 ): #covariant returns - #The return type of an overriding function shall be either identical to the - #return type of the overridden function or covariant with the classes of the - #functions. If a function D::f overrides a function B::f, the return types + #The return type of an overriding function shall be either identical to the + #return type of the overridden function or covariant with the classes of the + #functions. If a function D::f overrides a function B::f, the return types #of the functions are covariant if they satisfy the following criteria: #* both are pointers to classes or references to classes - #* the class in the return type of B::f is the same class as the class in - # the return type of D::f or, is an unambiguous direct or indirect base + #* the class in the return type of B::f is the same class as the class in + # the return type of D::f or, is an unambiguous direct or indirect base # class of the class in the return type of D::f and is accessible in D - #* both pointers or references have the same cv-qualification and the class - # type in the return type of D::f has the same cv-qualification as or less + #* both pointers or references have the same cv-qualification and the class + # type in the return type of D::f has the same cv-qualification as or less # cv-qualification than the class type in the return type of B::f. if not f1.__class__ is f2.__class__: @@ -43,7 +43,7 @@ def is_same_return_type( f1, f2 ): rt2 = type_traits.remove_pointer( rt2 ) elif type_traits.is_reference( rt1 ) and type_traits.is_reference( rt2 ): rt1 = type_traits.remove_reference( rt1 ) - rt2 = type_traits.remove_reference( rt2 ) + rt2 = type_traits.remove_reference( rt2 ) else: return type_traits.is_same( f1.return_type, f2.return_type) if ( type_traits.is_const( rt1 ) and type_traits.is_const( rt2 ) ) \ @@ -62,7 +62,7 @@ def is_same_return_type( f1, f2 ): return type_traits.is_same( c1, c2 ) \ or type_traits.is_base_and_derived( c1, c2 ) \ or type_traits.is_base_and_derived( c2, c1 ) - + def is_same_function( f1, f2 ): """returns true if f1 and f2 is same function @@ -87,3 +87,6 @@ def is_same_function( f1, f2 ): if not type_traits.is_same( f1_arg.type, f2_arg.type ): return False return True + + + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/matcher.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/matcher.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/matcher.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/matcher.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/matchers.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/matchers.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/matchers.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/matchers.py index 9fac068c69c4e814c5cefddb1241094c7a00c9ac..512b50577b4199e3a6120eb7da7517927703e98c 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/matchers.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/matchers.py @@ -177,7 +177,7 @@ class declaration_matcher_t( matcher_base_t ): else: self.__opt_is_full_name = False self.__decl_name_only = self.__opt_tmpl_name - self.__name = templates.normalize( name ) + self.__name = templates.normalize( name ) else: if '::' in self.__name: self.__opt_is_full_name = True @@ -229,7 +229,7 @@ class declaration_matcher_t( matcher_base_t ): if self.name != templates.normalize( decl.name ) \ and self.name != templates.normalize( decl.partial_name ): return False - else: + else: if self.name != templates.normalize( algorithm.full_name( decl, with_defaults=True ) ) \ and self.name != templates.normalize( algorithm.full_name( decl, with_defaults=False ) ): return False diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/mdecl_wrapper.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/mdecl_wrapper.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/mdecl_wrapper.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/mdecl_wrapper.py index 9c6a7ba110ef9c360a543344b7ea3f68e5a9f1c4..3ccd897e596f5429f559581b3b110854c8462cf8 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/mdecl_wrapper.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/mdecl_wrapper.py @@ -69,7 +69,7 @@ class mdecl_wrapper_t( object ): invalid_decls = filter( lambda d: not hasattr( d, name ), self.declarations ) sep = os.linesep + ' ' if invalid_decls: - raise RuntimeError( "Next declarations don't have '%s' attribute: %s" + raise RuntimeError( "Next declarations don't have '%s' attribute: %s" % ( name, sep.join( map( str, invalid_decls ) ) ) ) def __setattr__( self, name, value ): diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/namespace.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/namespace.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/namespace.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/namespace.py index d29c58796e25a88707813effbb618e8ac44b3be9..ae7178eb17d09c26348199f6e931751abd023310 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/namespace.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/namespace.py @@ -50,9 +50,9 @@ class namespace_t( scopedef.scopedef_t ): def adopt_declaration( self, decl ): self.declarations.append( decl ) - decl.parent = self + decl.parent = self decl.cache.reset() - + def remove_declaration( self, decl ): """ removes decl from members list @@ -73,7 +73,7 @@ class namespace_t( scopedef.scopedef_t ): , function=function , recursive=recursive ) ns = namespace - + def namespaces( self, name=None, function=None, recursive=None, allow_empty=None ): """returns a set of namespace declarations, that are matched defined criterias""" return self._find_multiple( scopedef.scopedef_t._impl_matchers[ namespace_t.namespace ] @@ -82,7 +82,7 @@ class namespace_t( scopedef.scopedef_t ): , recursive=recursive , allow_empty=allow_empty) nss = namespaces - + def free_function( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None ): """returns reference to free function declaration, that is matched defined criterias""" return self._find_single( scopedef.scopedef_t._impl_matchers[ namespace_t.free_function ] @@ -95,7 +95,7 @@ class namespace_t( scopedef.scopedef_t ): , header_file=header_file , recursive=recursive ) free_fun = free_function - + def free_functions( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None ): """returns a set of free function declarations, that are matched defined criterias""" return self._find_multiple( scopedef.scopedef_t._impl_matchers[ namespace_t.free_function ] diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/pattern_parser.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/pattern_parser.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/pattern_parser.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/pattern_parser.py index 858cdca04a346fe27e581517acc740970f0ce767..7b173022ba5316aead840120767a7d601c68964e 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/pattern_parser.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/pattern_parser.py @@ -135,3 +135,6 @@ class parser_t( object ): for i, arg in enumerate( args ): args[i] = self.normalize( arg ) return self.join( name, args, arg_separator ) + + + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/scopedef.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/scopedef.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/scopedef.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/scopedef.py index 956406559ad12fb00d6734ef6bff98cf61c0872e..a23571e7ce77ac7b6d45374c564fc91b47878922 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/scopedef.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/scopedef.py @@ -310,7 +310,7 @@ class scopedef_t( declaration.declaration_t ): #templates has tricky mode to compare them, so lets check the whole #range name = None - + if name and decl_type: matcher = scopedef_t._impl_matchers[ scopedef_t.decl ]( name=name ) if matcher.is_full_name(): @@ -648,3 +648,8 @@ class scopedef_t( declaration.declaration_t ): @param name_or_function Name of decl to lookup or finder function. """ return self.decls(name_or_function) + + + + + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/templates.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/templates.py similarity index 97% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/templates.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/templates.py index 3997d85d41e95236de5e6c34ff56bba92fc024d8..e2c10dfdf7e4f4b6b8a275140c136c1e0b09efd6 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/templates.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/templates.py @@ -3,11 +3,11 @@ # accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) -""" +""" template instantiation parser This module implements all functionality necessary to parse C++ template -instantiations.In other words this module is able to extract next information from +instantiations.In other words this module is able to extract next information from the string like this C{ std::vector<int> }. - name ( std::vector ) - list of arguments ( int ) @@ -22,10 +22,10 @@ __THE_PARSER = pattern_parser.parser_t( '<', '>', ',' ) def is_instantiation( decl_string ): """ returns True if decl_string is template instantiation and False otherwise - + @param decl_string: string that should be checked for pattern presence @type decl_string: str - + @return: bool """ global __THE_PARSER @@ -34,7 +34,7 @@ def is_instantiation( decl_string ): def name( decl_string ): """ returns name of instantiated template - + @type decl_string: str @return: str """ @@ -44,18 +44,18 @@ def name( decl_string ): def args( decl_string ): """ returns list of template arguments - + @type decl_string: str @return: [str] """ global __THE_PARSER return __THE_PARSER.args( decl_string ) - + def split( decl_string ): """returns (name, [arguments] )""" global __THE_PARSER return __THE_PARSER.split( decl_string ) - + def split_recursive( decl_string ): """returns [(name, [arguments])]""" global __THE_PARSER @@ -68,7 +68,7 @@ def join( name, args ): def normalize( decl_string ): """returns decl_string, which contains "normalized" spaces - + this functionality allows to implement comparison of 2 different string which are actually same: x::y< z > and x::y<z> """ diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/type_traits.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/type_traits.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py index 11e8bd1e51a68f9f825a5c806f68c5afd7862a71..98f5799b12c7c4d04e97d2503aa9fd52efb402f2 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/type_traits.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_traits.py @@ -1091,3 +1091,11 @@ def is_std_wostream( type ): else: type = remove_alias( type ) return remove_cv( type ).decl_string in decl_strings + + + + + + + + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/type_visitor.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_visitor.py similarity index 92% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/type_visitor.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_visitor.py index 619149fe086429c7444a65374034822d18cc1f4d..e2e474c76c5dc13035dc797a13c43935ae739d66 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/type_visitor.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/type_visitor.py @@ -10,7 +10,7 @@ defines types visitor class interface class type_visitor_t(object): """ types visitor interface - + All functions within this class should be redefined in derived classes. """ def __init__(self): @@ -18,55 +18,55 @@ class type_visitor_t(object): def visit_void( self ): raise NotImplementedError() - + def visit_char( self ): raise NotImplementedError() - + def visit_unsigned_char( self ): raise NotImplementedError() def visit_signed_char( self ): raise NotImplementedError() - + def visit_wchar( self ): raise NotImplementedError() - + def visit_short_int( self ): raise NotImplementedError() - + def visit_short_unsigned_int( self ): raise NotImplementedError() - + def visit_bool( self ): raise NotImplementedError() - + def visit_int( self ): raise NotImplementedError() - + def visit_unsigned_int( self ): raise NotImplementedError() - + def visit_long_int( self ): raise NotImplementedError() - + def visit_long_unsigned_int( self ): raise NotImplementedError() - + def visit_long_long_int( self ): raise NotImplementedError() - + def visit_long_long_unsigned_int( self ): raise NotImplementedError() - + def visit_float( self ): raise NotImplementedError() - + def visit_double( self ): raise NotImplementedError() - + def visit_long_double( self ): raise NotImplementedError() - + def visit_complex_long_double(self): raise NotImplementedError() @@ -75,57 +75,58 @@ class type_visitor_t(object): def visit_complex_float(self): raise NotImplementedError() - + def visit_jbyte(self): raise NotImplementedError() - + def visit_jshort(self): raise NotImplementedError() - + def visit_jint(self): raise NotImplementedError() - + def visit_jlong(self): raise NotImplementedError() - + def visit_jfloat(self): raise NotImplementedError() - + def visit_jdouble(self): raise NotImplementedError() - + def visit_jchar(self): raise NotImplementedError() - + def visit_jboolean(self): raise NotImplementedError() - + def visit_volatile( self ): raise NotImplementedError() - + def visit_const( self ): raise NotImplementedError() - + def visit_pointer( self ): raise NotImplementedError() - + def visit_reference( self ): raise NotImplementedError() - + def visit_array( self ): raise NotImplementedError() - + def visit_free_function_type( self ): raise NotImplementedError() - + def visit_member_function_type( self ): raise NotImplementedError() - + def visit_member_variable_type( self ): raise NotImplementedError() - + def visit_declarated( self ): raise NotImplementedError() def visit_restrict( self ): raise NotImplementedError() + \ No newline at end of file diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/typedef.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/typedef.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/typedef.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/typedef.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/variable.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/variable.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/variable.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/variable.py index 3b32b9bcee5353434c82ec85e056fdd6dc88f12a..cd5f99c47f89d904d435c137e13a0e692f26eef7 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/declarations/variable.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/variable.py @@ -22,7 +22,7 @@ class variable_t( declaration.declaration_t ): self._value = value self._bits = bits self._byte_offset = 0 - + def _get__cmp__items( self ): """implementation details""" return [ self.type, self.type_qualifiers, self.value ] diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/__init__.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/__init__.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/__init__.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/__init__.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/bsc/__init__.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/bsc/__init__.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/bsc/__init__.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/bsc/__init__.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/bsc/c_wrapper.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/bsc/c_wrapper.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/bsc/c_wrapper.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/bsc/c_wrapper.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/common_utils.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/common_utils.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/common_utils.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/common_utils.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/config.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/config.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/config.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/config.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/__init__.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/__init__.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/__init__.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/__init__.py index 2d09ad7f9a087c2edaba437a3fd6e5b54720c6fe..30626107d19f040e08ec397f455d068d06dd2bc7 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/__init__.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/__init__.py @@ -22,3 +22,4 @@ msdia = comtypes.client.GetModule( msvc_cfg.msdia_path ) #~ comtypes.client.gen_dir = comtypes_client_gen_dir from loader import decl_loader_t + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/enums.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/enums.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/enums.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/enums.py index 5c0cfa11afc8db0273bec4c5dcf108d4d79112e2..cb33e5f3e4e33dbdef6cd53c78734535064e1a34 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/enums.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/enums.py @@ -57,3 +57,4 @@ class DataKind( utils.enum ): DataIsMember = 7 DataIsStaticMember = 8 DataIsConstant = 9 + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/impl_details.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/impl_details.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/impl_details.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/impl_details.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/kb.txt b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/kb.txt similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/kb.txt rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/kb.txt index 601fe0486add4444df67d687f903d457e2ac69d8..e72ddf2b3e4698597c975ab228f85bb73e163256 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/kb.txt +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/kb.txt @@ -14,3 +14,4 @@ If the location is LocIsThisRel, use IDiaSymbol::get_offset to obtain the offset If the location is LocIsStatic, use IDiaSymbol::get_addressSection and IDiaSymbol::get_addressOffset, or IDiaSymbol::get_relativeVirtualAddress, or IDiaSymbol::get_virtualAddress to obtain the address of the static member. + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/loader.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/loader.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/pdb/loader.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/msvc/pdb/loader.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/__init__.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/__init__.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/__init__.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/__init__.py index af104c1d84ad6c10669996bef98c04266f584377..695e9c6a856dc22117acfe35de905696b42a3032 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/__init__.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/__init__.py @@ -43,7 +43,7 @@ def parse( files @type cache: L{cache_base_t} or str @returns: Declarations """ - + if not config: config = config_t() parser = project_reader_t( config=config, cache=cache ) diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/config.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/config.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/config.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/config.py index 896b924479f29294199a5518e1df44a7f0381ca4..3f528a2170cefcdad5027b0095dfde4ecdbefa41 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/config.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/config.py @@ -163,7 +163,6 @@ class gccxml_configuration_t(parser_configuration_t): def raise_on_wrong_settings( self ): - return super( gccxml_configuration_t, self ).raise_on_wrong_settings() if os.path.isfile( self.gccxml_path ): return diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/declarations_cache.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/declarations_cache.py similarity index 91% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/declarations_cache.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/declarations_cache.py index 4323888ddc3dfef729fe665ef16df552d8a8cb6c..2156e0ad63d3247f3cc336fdc36aefd92f4025ec 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/declarations_cache.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/declarations_cache.py @@ -5,12 +5,9 @@ # http://www.boost.org/LICENSE_1_0.txt) import os -try: - import hashlib as md5 -except: - import md5 +import md5 import time -import cPickle +import cPickle from pygccxml import utils import config as cxx_parsers_cfg @@ -25,7 +22,7 @@ def file_signature( filename ): sig = md5.new() f = file(filename,'r') sig.update(f.read()) - f.close() + f.close() return sig.hexdigest() def configuration_signature( config ): @@ -46,19 +43,19 @@ def configuration_signature( config ): for s in config.define_symbols: sig.update(str(s)) for u in config.undefine_symbols: - sig.update(str(u)) + sig.update(str(u)) return sig.hexdigest() class cache_base_t( object ): logger = utils.loggers.declarations_cache - + def __init__( self ): object.__init__(self) - + def flush(self): """ Flush (write out) the cache to disk if needed. """ raise NotImplementedError() - + def update(self, source_file, configuration, declarations, included_files): """ Update cache entry. @param source_file: path to the C++ source file being parsed @@ -66,14 +63,14 @@ class cache_base_t( object ): @param declarations: declaration tree found when parsing @param included_files: files included by parsing. """ - raise NotImplementedError() - + raise NotImplementedError() + def cached_value(self, source_file, configuration): """ Return declarations we have cached for the source_file and configuration given. @param source_file: path to the C++ source file being parsed. @param configuration: configuration to use for parsing (config_t) - """ + """ raise NotImplementedError() class record_t( object ): @@ -89,60 +86,60 @@ class record_t( object ): self.__included_files_signature = included_files_signature self.__declarations = declarations self.__was_hit = True # Track if there was a cache hit - + def _get_was_hit(self): return self.__was_hit def _set_was_hit(self, was_hit): self.__was_hit = was_hit was_hit = property( _get_was_hit, _set_was_hit ) - + def key(self): return ( self.__source_signature, self.__config_signature) - + @staticmethod def create_key( source_file, configuration ): return ( file_signature(source_file) - , configuration_signature(configuration)) - + , configuration_signature(configuration)) + def __source_signature(self): return self.__source_signature source_signature = property( __source_signature ) - + def __config_signature(self): return self.__config_signature config_signature = property( __config_signature ) - + def __included_files(self): return self.__included_files included_files = property( __included_files ) - + def __included_files_signature(self): return self.__included_files_signature included_files_signature = property( __included_files_signature ) - + def __declarations(self): return self.__declarations - declarations = property( __declarations ) + declarations = property( __declarations ) -class file_cache_t( cache_base_t ): - """ Cache implementation to store data in a pickled form in a file. +class file_cache_t( cache_base_t ): + """ Cache implementation to store data in a pickled form in a file. This class contains some cache logic that keeps track of which entries have been 'hit' in the cache and if an entry has not been hit then it is deleted at the time of the flush(). This keeps the cache from - growing larger when files change and are not used again. + growing larger when files change and are not used again. """ def __init__( self, name ): """ @param name: name of the cache file. """ - cache_base_t.__init__( self ) + cache_base_t.__init__( self ) self.__name = name # Name of cache file self.__cache = self.__load( self.__name ) # Map record_key to record_t - self.__needs_flushed = not bool( self.__cache ) # If empty then we need to flush + self.__needs_flushed = not bool( self.__cache ) # If empty then we need to flush for entry in self.__cache.itervalues(): # Clear hit flags entry.was_hit = False - + @staticmethod def __load( file_name ): " Load pickled cache from file and return the object. " @@ -156,7 +153,7 @@ class file_cache_t( cache_base_t ): try: file_cache_t.logger.info( 'Loading cache file "%s".' % file_name ) start_time = time.clock() - cache = cPickle.load( cache_file_obj ) + cache = cPickle.load( cache_file_obj ) file_cache_t.logger.debug( "Cache file has been loaded in %.1f secs"%( time.clock() - start_time ) ) file_cache_t.logger.debug( "Found cache in file: [%s] entries: %s" % ( file_name, len( cache.keys() ) ) ) @@ -165,15 +162,15 @@ class file_cache_t( cache_base_t ): cache_file_obj.close() file_cache_t.logger.info( "Invalid cache file: [%s] Regenerating." % file_name ) file(file_name, 'w+b').close() # Create empty file - cache = {} # Empty cache + cache = {} # Empty cache return cache - + def flush(self): # If not marked as needing flushed, then return immediately if not self.__needs_flushed: self.logger.debug("Cache did not change, ignoring flush.") return - + # Remove entries that did not get a cache hit num_removed = 0 for key in self.__cache.keys(): @@ -193,14 +190,14 @@ class file_cache_t( cache_base_t ): , config_signature=configuration_signature(configuration) , included_files=included_files , included_files_signature=map( file_signature, included_files) - , declarations=declarations + , declarations=declarations ) # Switched over to holding full record in cache so we don't have # to keep creating records in the next method. self.__cache[ record.key() ] = record self.__cache[ record.key() ].was_hit = True self.__needs_flushed = True - + def cached_value(self, source_file, configuration): """ Attempt to lookup the cached decls for the given file and configuration. If not found or signature check fails, returns None. @@ -212,10 +209,10 @@ class file_cache_t( cache_base_t ): if self.__is_valid_signature( record ): record.was_hit = True # Record cache hit return record.declarations - else: #some file has been changed + else: #some file has been changed del self.__cache[key] return None - + def __is_valid_signature( self, record ): # This is now part of key #if self.__signature( record.source_file ) != record.source_file_signature: @@ -224,17 +221,17 @@ class file_cache_t( cache_base_t ): if file_signature( included_file ) != record.included_files_signature[index]: return False return True - + class dummy_cache_t( cache_base_t ): def __init__( self ): cache_base_t.__init__(self) - + def flush(self): pass - + def update(self, source_file, configuration, declarations, included_files): pass - + def cached_value(self, source_file, configuration): - return None + return None \ No newline at end of file diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/directory_cache.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/directory_cache.py similarity index 98% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/directory_cache.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/directory_cache.py index f2fa5b897a2c40ed2ff4d2bf0957a5c6b20d2cc7..03b9e68094904db58617d9aa6f28f8a1c1c70b6b 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/directory_cache.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/directory_cache.py @@ -14,11 +14,7 @@ The cache class is L{directory_cache_t} which can be passed to the C{cache} argument of the L{parse()} function. """ -import os, os.path, gzip -try: - import hashlib as md5 -except: - import md5 +import os, os.path, gzip, md5 import cPickle import declarations_cache @@ -31,7 +27,7 @@ class index_entry_t: This class is a helper class for the directory_cache_t class. """ - + def __init__( self, filesigs, configsig ): """Constructor. @@ -46,7 +42,7 @@ class index_entry_t: def __setstate__(self, state): self.filesigs, self.configsig = state - + class directory_cache_t ( declarations_cache.cache_base_t ): """Cache class that stores its data as multiple files inside a directory. @@ -107,7 +103,7 @@ class directory_cache_t ( declarations_cache.cache_base_t ): def flush(self): """Save the index table to disk.""" - self._save() + self._save() # self.__filename_rep._dump() def update(self, source_file, configuration, declarations, included_files): @@ -156,7 +152,7 @@ class directory_cache_t ( declarations_cache.cache_base_t ): cachefilename = self._create_cache_filename(source_file) self._write_file(cachefilename, declarations) - + def cached_value(self, source_file, configuration): """Return the cached declarations or None. @@ -171,7 +167,7 @@ class directory_cache_t ( declarations_cache.cache_base_t ): key = self._create_cache_key(source_file) entry = self.__index.get(key) if entry==None: -# print "CACHE: %s: Not cached"%source_file +# print "CACHE: %s: Not cached"%source_file return None # Check if the entry is still valid. It is not valid if: @@ -224,7 +220,7 @@ class directory_cache_t ( declarations_cache.cache_base_t ): else: self.__index = {} self.__filename_rep = filename_repository_t(self.__md5_sigs) - + self.__modified_flag = False def _save(self): @@ -271,8 +267,8 @@ class directory_cache_t ( declarations_cache.cache_base_t ): else: f = file(filename, "wb") cPickle.dump(data, f, cPickle.HIGHEST_PROTOCOL) - f.close() - + f.close() + def _remove_entry(self, source_file, key): """Remove an entry from the cache. @@ -289,7 +285,7 @@ class directory_cache_t ( declarations_cache.cache_base_t ): @param key: Key value for the specified header file @type key: hashable object """ - + entry = self.__index.get(key) if entry==None: return @@ -353,7 +349,7 @@ class directory_cache_t ( declarations_cache.cache_base_t ): return m.digest() - + class filename_entry_t: """This is a record stored in the filename_repository_t class. @@ -372,7 +368,7 @@ class filename_entry_t: self.filename = filename # Reference count self.refcount = 0 - + # Cached signature value for the file. # If sig_valid flag is False, the signature still has to be computed, # otherwise the cached value can be used. @@ -414,7 +410,7 @@ class filename_repository_t: def __init__( self, md5_sigs ): """Constructor. """ - + # Flag that determines whether the signature is a md5 digest or # the modification time # (this flag is passed to the filename_repository_t class) @@ -437,7 +433,7 @@ class filename_repository_t: """Acquire a file name and return its id and its signature. """ id_ = self.__id_lut.get(name) - # Is this a new entry? + # Is this a new entry? if id_==None: # then create one... id_ = self.__next_id @@ -451,7 +447,7 @@ class filename_repository_t: entry.inc_ref_count() return id_, self._get_signature(entry) - + def release_filename(self, id_): """Release a file name. """ @@ -471,7 +467,7 @@ class filename_repository_t: if entry==None: raise ValueError, "Invalid filename id_ (%d)"%id_ - # Is the signature already known? + # Is the signature already known? if entry.sig_valid: # use the cached signature filesig = entry.signature @@ -529,3 +525,4 @@ class filename_repository_t: for id_ in self.__entries: entry = self.__entries[id_] print "%04d %-60s %d"%(id_, entry.filename, entry.refcount) + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/etree_scanner.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/etree_scanner.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/etree_scanner.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/etree_scanner.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/linker.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/linker.py similarity index 96% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/linker.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/linker.py index 61fd46d9530420e5e74f2ac53d08b750cb11dd17..b7053a4c6aa9159b687cc4996f59de0e92930743 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/linker.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/linker.py @@ -18,13 +18,13 @@ class linker_t( decl_visitor_t, type_visitor_t, object ): self.__membership = membership self.__files = files self.__inst = None - - self.__compiler = None + + self.__compiler = None if self.__decls: for d in self.__decls.itervalues(): self.__compiler = d.compiler break - + def _get_inst(self): return self.__inst def _set_inst(self, inst): @@ -48,12 +48,12 @@ class linker_t( decl_visitor_t, type_visitor_t, object ): else: return unknown_t() - def __link_compound_type(self): + def __link_compound_type(self): self.__inst.base = self.__link_type( self.__inst.base ) def __link_members(self): if not self.__membership.has_key( id(self.__inst) ): - return + return for member in self.__membership[ id(self.__inst) ]: if not self.__access.has_key( member ): continue @@ -85,7 +85,7 @@ class linker_t( decl_visitor_t, type_visitor_t, object ): def visit_constructor( self ): self.__link_calldef() - + def visit_destructor( self ): self.__link_calldef() @@ -109,13 +109,13 @@ class linker_t( decl_visitor_t, type_visitor_t, object ): def visit_class(self ): self.__link_members() #GCC-XML sometimes generates constructors with names that does not match - #class name. I think this is because those constructors are compiler - #generated. I need to find out more about this and to talk with Brad + #class name. I think this is because those constructors are compiler + #generated. I need to find out more about this and to talk with Brad new_name = self.__inst._name if templates.is_instantiation( new_name ): new_name = templates.name( new_name ) - + for decl in self.__inst.declarations: if not isinstance( decl, constructor_t ): continue @@ -133,7 +133,7 @@ class linker_t( decl_visitor_t, type_visitor_t, object ): access = data[0] self.__inst.bases.append( hierarchy_info_t( base_decl, access ) ) base_decl.derived.append( hierarchy_info_t( self.__inst, access ) ) - + def visit_enumeration(self ): pass @@ -208,25 +208,25 @@ class linker_t( decl_visitor_t, type_visitor_t, object ): def visit_jbyte(self): pass - + def visit_jshort(self): pass - + def visit_jint(self): pass - + def visit_jlong(self): pass - + def visit_jfloat(self): pass - + def visit_jdouble(self): pass - + def visit_jchar(self): pass - + def visit_jboolean(self): pass @@ -239,7 +239,7 @@ class linker_t( decl_visitor_t, type_visitor_t, object ): def visit_pointer( self ): if '0.9' in self.__compiler and isinstance( self.__inst.base, member_variable_type_t ): original_inst = self.__inst - self.__inst = self.__inst.base + self.__inst = self.__inst.base self.visit_member_variable_type() self.__inst = original_inst else: @@ -269,3 +269,4 @@ class linker_t( decl_visitor_t, type_visitor_t, object ): def visit_restrict( self ): self.__link_compound_type() + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/patcher.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/patcher.py similarity index 97% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/patcher.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/patcher.py index 46a842ec832f0cc6c2a150438052b139444973f2..119584b832444159bb90c2f875ce4616fec96326 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/patcher.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/patcher.py @@ -11,7 +11,7 @@ class default_argument_patcher_t( object ): def __init__( self, enums ): object.__init__( self ) self.__enums = enums - + def __call__(self, decl): for arg in decl.arguments: if not arg.default_value: @@ -26,7 +26,7 @@ class default_argument_patcher_t( object ): elif self.__is_unqualified_enum( func, arg ): return self.__fix_unqualified_enum elif self.__is_double_call( func, arg ): - return self.__fix_double_call + return self.__fix_double_call elif self.__is_invalid_integral( func, arg ): return self.__fix_invalid_integral elif self.__is_constructor_call( func, arg ): @@ -39,9 +39,9 @@ class default_argument_patcher_t( object ): return '::' + suffix else: return prefix + '::' + suffix - + def __is_unqualified_enum(self, func, arg): - type_ = declarations.remove_reference( declarations.remove_cv( arg.type ) ) + type_ = declarations.remove_reference( declarations.remove_cv( arg.type ) ) if not declarations.is_enum( type_ ): return False enum_type = declarations.enum_declaration( type_ ) @@ -53,7 +53,7 @@ class default_argument_patcher_t( object ): return self.__join_names( enum_type.parent.decl_string, arg.default_value ) def __is_invalid_integral(self, func, arg): - type_ = declarations.remove_reference( declarations.remove_cv( arg.type ) ) + type_ = declarations.remove_reference( declarations.remove_cv( arg.type ) ) if not declarations.is_integral( type_ ): return False try: @@ -68,7 +68,7 @@ class default_argument_patcher_t( object ): return arg.default_value except: pass - + try: int( arg.default_value, 16 ) if 64 == utils.get_architecture(): @@ -83,7 +83,7 @@ class default_argument_patcher_t( object ): return '0x' + default_value except: pass - + #may be we deal with enum parent = func.parent while parent: @@ -103,7 +103,7 @@ class default_argument_patcher_t( object ): #this algorithm could be improved: it could take into account #1. unnamed namespaced #2. location within files - + for enum in self.__enums: if enum.parent is scope and enum.has_value_name( default_value ): return enum @@ -121,7 +121,7 @@ class default_argument_patcher_t( object ): args1 = call_invocation.args( dv[ found1[0] : found1[1] + 1 ] ) args2 = call_invocation.args( dv[ found2[0] : found2[1] + 1 ] ) return len(args1) == len(args2) - + def __fix_double_call( self, func, arg ): call_invocation = declarations.call_invocation dv = arg.default_value @@ -167,7 +167,7 @@ class default_argument_patcher_t( object ): , decl.name ) else: f_q_name = self.__join_names( declarations.full_name( decl.parent ), name ) - + return call_invocation.join( f_q_name, args ) class casting_operator_patcher_t( object ): @@ -186,3 +186,4 @@ def fix_calldef_decls(decls, enums): default_arg_patcher( decl ) if isinstance( decl, declarations.casting_operator_t): _casting_oper_patcher_( decl ) + \ No newline at end of file diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/project_reader.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/project_reader.py similarity index 100% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/project_reader.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/project_reader.py diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/scanner.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/scanner.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/scanner.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/scanner.py index ee00a3bfc244bc0b010ae2dfd0343a6d73bcb6ae..563d3e28177a2a91031f6aff92cb87b87e5ea815 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/scanner.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/scanner.py @@ -334,8 +334,7 @@ class scanner_t( xml.sax.handler.ContentHandler ): if size is None: size = array_t.SIZE_UNKNOWN msg = 'unable to find out array size from expression "%s"' % attrs[ XML_AN_MAX ] - # warning is absolutely useless without much clue - # warnings.warn( msg ) + warnings.warn( msg ) return array_t( type_, size + 1 ) def __read_cv_qualified_type( self, attrs ): @@ -537,3 +536,4 @@ class scanner_t( xml.sax.handler.ContentHandler ): else: logger.info ( 'GCCXML version - 0.9' ) self.__compiler = compilers.GCC_XML_09 + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/source_reader.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/source_reader.py similarity index 99% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/source_reader.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/source_reader.py index 129c34b08f639426485cabe9822224d5ee9fa2b7..da20ef6ed1b0143a124bf4a388a34af60cc26ed1 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/parser/source_reader.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/parser/source_reader.py @@ -343,3 +343,4 @@ class source_reader_t: declarations = [scanner.global_ns] self.__dcache.update( ffname, self.__config, declarations, [] ) return declarations + diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/utils/__init__.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/utils/__init__.py similarity index 95% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/utils/__init__.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/utils/__init__.py index 92d93c74c878a7e2c1456cec2ecf8fbbc07db074..cb51ec1c2581954ccc47b9bccf13f14d5ccc387f 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/utils/__init__.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/utils/__init__.py @@ -22,7 +22,7 @@ def _create_logger_( name ): #handler.setFormatter( logging.Formatter( os.linesep + '%(levelname)s %(message)s' ) ) handler.setFormatter( logging.Formatter( '%(levelname)s %(message)s' ) ) logger.addHandler(handler) - logger.setLevel(logging.WARNING) + logger.setLevel(logging.INFO) return logger class loggers: @@ -119,36 +119,36 @@ class cached(property): def fdel(s): del s.__dict__[private] super(cached, self).__init__(fget, fdel=fdel) - + @staticmethod def reset(self): cls = self.__class__ for name in dir(cls): attr = getattr(cls, name) if isinstance(attr, cached): - delattr(self, name) + delattr(self, name) class enum( object ): """Usage example: class fruits(enum): apple = 0 orange = 1 - + fruits.has_value( 1 ) fruits.name_of( 1 ) """ - + @classmethod def has_value( cls, enum_numeric_value ): - for name, value in cls.__dict__.iteritems(): + for name, value in cls.__dict__.iteritems(): if enum_numeric_value == value: return True else: return False - + @classmethod def name_of( cls, enum_numeric_value ): - for name, value in cls.__dict__.iteritems(): + for name, value in cls.__dict__.iteritems(): if enum_numeric_value == value: return name else: diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/utils/fs_utils.py b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/utils/fs_utils.py similarity index 97% rename from Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/utils/fs_utils.py rename to Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/utils/fs_utils.py index 3d01e311bf7217823ee7438eac81fb744667fe31..0f5996e97a4cc45c96babc3a572eca288593b4cd 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/utils/fs_utils.py +++ b/Utilities/ITK/Modules/ThirdParty/pygccxml/src/pygccxml/utils/fs_utils.py @@ -18,19 +18,19 @@ def _make_list( argument ): return argument else: raise TypeError( 'Argument "%s" must be or list of strings or string.' % argument ) - + class base_files_iterator: def __init__(self, file_exts, is_include_exts = True): self.__file_exts = _make_list( file_exts ) self.__is_include_exts = is_include_exts - def _is_to_skip(self, file_path): + def _is_to_skip(self, file_path): if not self.__file_exts: return 0 file_ext = os.path.splitext( file_path )[1] if not file_ext: file_ext = '.' + file_ext - file_ext = '*' + file_ext + file_ext = '*' + file_ext if file_ext.lower() in self.__file_exts: return not self.__is_include_exts else: @@ -93,7 +93,7 @@ class directories_walker: self.__directories.extend( self.__sub_directories( root ) ) self.__is_recursive = is_recursive self.__directory_generator = None - + def __sub_directories(self, directory_path): sub_directories = [] directory_contains = os.listdir(directory_path) @@ -110,7 +110,7 @@ class directories_walker: if self.__is_recursive: for f in directories_walker( [curr_directory], True ): yield f - + def __iter__(self): self.__directory_generator = self.__walk() return self diff --git a/Utilities/ITK/Modules/Video/Core/include/itkRingBuffer.h b/Utilities/ITK/Modules/Video/Core/include/itkRingBuffer.h index eb4d93d20ec030a5e6e26fa364bff9d8e3c8397f..fd085a93613d3e15c389dd09275559a3ef1715f0 100644 --- a/Utilities/ITK/Modules/Video/Core/include/itkRingBuffer.h +++ b/Utilities/ITK/Modules/Video/Core/include/itkRingBuffer.h @@ -95,7 +95,7 @@ protected: /**-PROTECTED METHODS------------------------------------------------------*/ RingBuffer(); virtual ~RingBuffer(); - void PrintSelf(std::ostream &os, Indent indent) const; + virtual void PrintSelf(std::ostream &os, Indent indent) const ITK_OVERRIDE; /** Get the proper buffer index from an offset */ OffsetValueType GetOffsetBufferIndex(OffsetValueType offset); diff --git a/Utilities/ITK/Modules/Video/Core/include/itkRingBuffer.hxx b/Utilities/ITK/Modules/Video/Core/include/itkRingBuffer.hxx index 307fb72374221767018626a65468712a13003628..c61b74809c0c6306eae645fe73cbdac0d531c614 100644 --- a/Utilities/ITK/Modules/Video/Core/include/itkRingBuffer.hxx +++ b/Utilities/ITK/Modules/Video/Core/include/itkRingBuffer.hxx @@ -183,7 +183,7 @@ RingBuffer< TElement > { for (size_t i = 0; i < n - currentSize; ++i) { - ElementPointer newPointer = NULL; + ElementPointer newPointer = ITK_NULLPTR; this->m_PointerVector.insert( this->m_PointerVector.begin() + this->m_HeadIndex, newPointer ); diff --git a/Utilities/ITK/Modules/Video/Core/include/itkTemporalDataObject.h b/Utilities/ITK/Modules/Video/Core/include/itkTemporalDataObject.h index aff2935d554a57c72c3947ab8a22d2777d2b41a9..d5939dddafce978267f67738b19f7672c7f74c82 100644 --- a/Utilities/ITK/Modules/Video/Core/include/itkTemporalDataObject.h +++ b/Utilities/ITK/Modules/Video/Core/include/itkTemporalDataObject.h @@ -85,23 +85,23 @@ public: * buffered region */ virtual const TemporalRegionType GetUnbufferedRequestedTemporalRegion(); - virtual void SetRequestedRegionToLargestPossibleRegion(); + virtual void SetRequestedRegionToLargestPossibleRegion() ITK_OVERRIDE; - virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); + virtual bool RequestedRegionIsOutsideOfTheBufferedRegion() ITK_OVERRIDE; - virtual bool VerifyRequestedRegion(); + virtual bool VerifyRequestedRegion() ITK_OVERRIDE; - virtual void CopyInformation(const DataObject *); + virtual void CopyInformation(const DataObject *) ITK_OVERRIDE; - virtual void SetRequestedRegion(const DataObject *); + virtual void SetRequestedRegion(const DataObject *) ITK_OVERRIDE; - virtual void Graft(const DataObject *); + virtual void Graft(const DataObject *) ITK_OVERRIDE; protected: TemporalDataObject(); virtual ~TemporalDataObject(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Buffer for holding component data objects */ BufferType::Pointer m_DataObjectBuffer; diff --git a/Utilities/ITK/Modules/Video/Core/include/itkTemporalProcessObject.h b/Utilities/ITK/Modules/Video/Core/include/itkTemporalProcessObject.h index 6b2661170ee7c523c7b3b3d52e6d0c2cc2a90dab..050b95c7e1f35ece5695a6f24ca782531d437ef8 100644 --- a/Utilities/ITK/Modules/Video/Core/include/itkTemporalProcessObject.h +++ b/Utilities/ITK/Modules/Video/Core/include/itkTemporalProcessObject.h @@ -81,11 +81,11 @@ public: /** Override EnlargeOutputRequestedRegion, GenerateOutputRequestedRegion, and * GenerateInputRequestedRegion to handle temporal regions */ - virtual void EnlargeOutputRequestedRegion(DataObject* output); + virtual void EnlargeOutputRequestedRegion(DataObject* output) ITK_OVERRIDE; - virtual void GenerateOutputRequestedRegion(DataObject* output); + virtual void GenerateOutputRequestedRegion(DataObject* output) ITK_OVERRIDE; - virtual void GenerateInputRequestedRegion(); + virtual void GenerateInputRequestedRegion() ITK_OVERRIDE; /** Get the number of frames of input required to produce output. We don't * provide a Set method because we want some filters to be able to hold this @@ -102,7 +102,7 @@ public: * temporal region based on the largest possible temporal region of the input, * the unit input/output sizes for the process, and the number of frames * skipped per output*/ - virtual void UpdateOutputInformation(); + virtual void UpdateOutputInformation() ITK_OVERRIDE; /** Override ProcessObject's implementation of UpdateOutputData. This is * necessary because by default ProcessObject propagates the call to its @@ -115,7 +115,7 @@ public: * * Code: this->ProcessObject::UpdateOutputData( output ) */ - virtual void UpdateOutputData(DataObject* output); + virtual void UpdateOutputData(DataObject* output) ITK_OVERRIDE; /** Override GenerateData to do temporal region streaming. This is analogous * to the ThreadedGenerateData system implemented in ImageSource, but it @@ -127,7 +127,7 @@ public: * the requested temporal region of the input to each input requested * temporal sub-region (in sequence) and re-propagate the temporal region * request up the pipeline. */ - virtual void GenerateData(); + virtual void GenerateData() ITK_OVERRIDE; /** TemporalStreamingGenerateData is in charge of producing output for a * single portion of the output requested temporal region. This is where @@ -149,7 +149,7 @@ protected: } /** ITK print mechanism */ - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Explicitly handle temporal regions in EnlargeRequestedRegion. The default * implementation makes sure that the output requested temporal region is diff --git a/Utilities/ITK/Modules/Video/Core/include/itkTemporalRegion.h b/Utilities/ITK/Modules/Video/Core/include/itkTemporalRegion.h index a70392d52ddb679fd56d1e402e690cb731009ec2..6f1ee573062a3489fb85b2144b3f8c7a72422b6e 100644 --- a/Utilities/ITK/Modules/Video/Core/include/itkTemporalRegion.h +++ b/Utilities/ITK/Modules/Video/Core/include/itkTemporalRegion.h @@ -68,7 +68,7 @@ public: FrameOffsetType GetFrameDuration() const; /** Return RegionType (SRUCTURED_REGION) */ - virtual RegionType GetRegionType() const; + virtual RegionType GetRegionType() const ITK_OVERRIDE; /** Constructor */ TemporalRegion(); @@ -89,7 +89,7 @@ public: protected: - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Time boundaries */ RealTimeStamp m_RealStart; diff --git a/Utilities/ITK/Modules/Video/Core/include/itkVideoSource.h b/Utilities/ITK/Modules/Video/Core/include/itkVideoSource.h index 6802dc82ee2d8ff49c0ae2788dc103d7c67ec1d4..a49b4de211c1cf9ea203313028a0631841ff805c 100644 --- a/Utilities/ITK/Modules/Video/Core/include/itkVideoSource.h +++ b/Utilities/ITK/Modules/Video/Core/include/itkVideoSource.h @@ -99,7 +99,7 @@ public: * multiple types of output must override this to return the proper type. */ typedef ProcessObject::DataObjectPointerArraySizeType DataObjectPointerArraySizeType; using Superclass::MakeOutput; - virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx); + virtual DataObjectPointer MakeOutput(DataObjectPointerArraySizeType idx) ITK_OVERRIDE; protected: @@ -114,14 +114,14 @@ protected: * mid-pipeline filters will always have their outputs' requested spatial * regions set by the GenerateInputRequestedRegion call from the filter one * further down the pipeline. */ - virtual void GenerateOutputRequestedTemporalRegion(TemporalDataObject* output); + virtual void GenerateOutputRequestedTemporalRegion(TemporalDataObject* output) ITK_OVERRIDE; /** We override the default implementation of TemporalStreamingGenerateData * from TemporalProcessObject to provide functionality for spatial streaming. * This implementation works exactly the same way as the implementation of * GenerateData in ImageSource. The filter-specific implementation of * ThreadedGenerateData will be responsible of accessing the correct frames. */ - virtual void TemporalStreamingGenerateData(); + virtual void TemporalStreamingGenerateData() ITK_OVERRIDE; /** ThreadedGenerateData here serves the same symnatic purpose as * ThreadedGenerateData in ProcessObjects that handle Images. This is to say @@ -173,7 +173,7 @@ protected: VideoSource(); virtual ~VideoSource(); - virtual void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; private: diff --git a/Utilities/ITK/Modules/Video/Core/include/itkVideoSource.hxx b/Utilities/ITK/Modules/Video/Core/include/itkVideoSource.hxx index e6c86a9e6435b8d70ff23861ec9355f254e5b108..05b8e3176b7af35d3d98cdddc1daa63b8d19ce4d 100644 --- a/Utilities/ITK/Modules/Video/Core/include/itkVideoSource.hxx +++ b/Utilities/ITK/Modules/Video/Core/include/itkVideoSource.hxx @@ -69,7 +69,7 @@ VideoSource<TOutputVideoStream>::GetOutput() if (this->GetNumberOfOutputs() < 1) { itkWarningMacro("No outputs set"); - return NULL; + return ITK_NULLPTR; } // Return the output @@ -87,7 +87,7 @@ VideoSource<TOutputVideoStream>::GetOutput(unsigned int idx) (this->TemporalProcessObject::GetOutput(idx) ); // Make sure there is at least 1 output - if (out == NULL) + if (out == ITK_NULLPTR) { itkWarningMacro("dynamic_cast to output type failed"); } diff --git a/Utilities/ITK/Modules/Video/Core/include/itkVideoStream.h b/Utilities/ITK/Modules/Video/Core/include/itkVideoStream.h index 52b5f9f392bd02797d43025631e73b1be76bc407..39d60dd772c4a5e02b449fcbdc1a1a074bf64c7c 100644 --- a/Utilities/ITK/Modules/Video/Core/include/itkVideoStream.h +++ b/Utilities/ITK/Modules/Video/Core/include/itkVideoStream.h @@ -273,7 +273,7 @@ public: * just copies the meta information using TemporalProcessObject's Graft then * sets the internal RingBuffer pointer to point to the same buffer used by * the other VideoStream. */ - virtual void Graft(const DataObject* data); + virtual void Graft(const DataObject* data) ITK_OVERRIDE; protected: @@ -281,7 +281,7 @@ protected: } virtual ~VideoStream() { } - virtual void PrintSelf(std::ostream & os, Indent indent) const + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE { Superclass::Print(os, indent); } diff --git a/Utilities/ITK/Modules/Video/Core/src/itkTemporalDataObject.cxx b/Utilities/ITK/Modules/Video/Core/src/itkTemporalDataObject.cxx index 0bdc42f11c01049efeaa440aceab90767f233de3..40fe5666e9a6583042f221efa493c99223b91912 100644 --- a/Utilities/ITK/Modules/Video/Core/src/itkTemporalDataObject.cxx +++ b/Utilities/ITK/Modules/Video/Core/src/itkTemporalDataObject.cxx @@ -249,7 +249,6 @@ TemporalDataObject itkExceptionMacro( << "itk::TemporalDataObject::" << "RequestedRegionIsOutsideOfTheBufferedRegion() " << "Invalid Temporal Unit" ); - return true; } } @@ -283,7 +282,6 @@ TemporalDataObject default: itkExceptionMacro( << "itk::TemporalDataObject::VerifyRequestedRegion() " << "Invalid Temporal Unit" ); - return false; } } diff --git a/Utilities/ITK/Modules/Video/Filtering/include/itkImageFilterToVideoFilterWrapper.hxx b/Utilities/ITK/Modules/Video/Filtering/include/itkImageFilterToVideoFilterWrapper.hxx index fa31c9771e41b7709c4afe090e1b3b9f0c13d647..3ebc3b451ace57857770d50e42988031af06080f 100644 --- a/Utilities/ITK/Modules/Video/Filtering/include/itkImageFilterToVideoFilterWrapper.hxx +++ b/Utilities/ITK/Modules/Video/Filtering/include/itkImageFilterToVideoFilterWrapper.hxx @@ -37,7 +37,7 @@ ImageFilterToVideoFilterWrapper() this->TemporalProcessObject::m_FrameSkipPerOutput = 1; // Initialize image filter to NULL - m_ImageFilter = NULL; + m_ImageFilter = ITK_NULLPTR; } // diff --git a/Utilities/ITK/Modules/Video/IO/include/itkFileListVideoIO.h b/Utilities/ITK/Modules/Video/IO/include/itkFileListVideoIO.h index d8184e359eadf79e7979441ba78c524d5adfd7d3..b70dbf3b2aa19230dc5e78bb526cc38272b5f3d9 100644 --- a/Utilities/ITK/Modules/Video/IO/include/itkFileListVideoIO.h +++ b/Utilities/ITK/Modules/Video/IO/include/itkFileListVideoIO.h @@ -50,7 +50,7 @@ public: itkTypeMacro(FileListVideoIO, Superclass); /** Close the reader and writer and reset members */ - virtual void FinishReadingOrWriting(); + virtual void FinishReadingOrWriting() ITK_OVERRIDE; /** Split up the input file names -- This is public so that places where * FileListVideoIO is used can access the individual file names. This is @@ -60,27 +60,27 @@ public: /*-------- This part of the interface deals with reading data. ------ */ /** Set to reading from file */ - virtual void SetReadFromFile(); + virtual void SetReadFromFile() ITK_OVERRIDE; /** Set to reading from a camera */ - virtual void SetReadFromCamera(); + virtual void SetReadFromCamera() ITK_OVERRIDE; /** Determine the file type. Returns true if this ImageIO can read the * file specified. */ - virtual bool CanReadFile(const char *); + virtual bool CanReadFile(const char *) ITK_OVERRIDE; /** Return whether or not the VideoIO can read from a camera */ - virtual bool CanReadCamera( CameraIDType cameraID )const; + virtual bool CanReadCamera( CameraIDType cameraID )const ITK_OVERRIDE; /** Set the spacing and dimension information for the set filename. */ - virtual void ReadImageInformation(); + virtual void ReadImageInformation() ITK_OVERRIDE; /** Reads the data from disk into the memory buffer provided. */ - virtual void Read(void *buffer); + virtual void Read(void *buffer) ITK_OVERRIDE; /** Set the next frame that should be read. Return true if you operation * successful */ - virtual bool SetNextFrameToRead(FrameOffsetType frameNumber); + virtual bool SetNextFrameToRead(FrameOffsetType frameNumber) ITK_OVERRIDE; /** Accessor functions for video specific information */ itkGetConstMacro(PositionInMSec,TemporalOffsetType); @@ -92,42 +92,42 @@ public: itkGetConstMacro(LastIFrame,FrameOffsetType); /** Override SetFileName to do parsing */ - virtual void SetFileName(const std::string& fileList); - virtual void SetFileName(const char* fileList); + virtual void SetFileName(const std::string& fileList) ITK_OVERRIDE; + virtual void SetFileName(const char* fileList) ITK_OVERRIDE; /** Override Accessors to pass through to internal image reader */ - virtual double GetSpacing(unsigned int i) const; + virtual double GetSpacing(unsigned int i) const ITK_OVERRIDE; - virtual double GetOrigin(unsigned int i) const; + virtual double GetOrigin(unsigned int i) const ITK_OVERRIDE; - virtual std::vector< double > GetDirection(unsigned int i) const; + virtual std::vector< double > GetDirection(unsigned int i) const ITK_OVERRIDE; /*-------- This part of the interfaces deals with writing data. ----- */ /** Determine the file type. Returns true if this ImageIO can write the * file specified. */ - virtual bool CanWriteFile(const char *); + virtual bool CanWriteFile(const char *) ITK_OVERRIDE; /** Writes the spacing and dimensions of the image. * Assumes SetFileName has been called with a valid file name. */ - virtual void WriteImageInformation(); + virtual void WriteImageInformation() ITK_OVERRIDE; /** Writes the data to disk from the memory buffer provided. Make sure * that the IORegion has been set properly. */ - virtual void Write(const void *buffer); + virtual void Write(const void *buffer) ITK_OVERRIDE; /** Set Writer Parameters */ virtual void SetWriterParameters( TemporalRatioType framesPerSecond, const std::vector<SizeValueType>& dim, const char* fourCC, unsigned int nChannels, - IOComponentType componentType ); + IOComponentType componentType ) ITK_OVERRIDE; protected: FileListVideoIO(); ~FileListVideoIO(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Reset member variables to empty state closed */ void ResetMembers(); diff --git a/Utilities/ITK/Modules/Video/IO/include/itkFileListVideoIOFactory.h b/Utilities/ITK/Modules/Video/IO/include/itkFileListVideoIOFactory.h index 85925a6d3dd93c4e9f969f0978992d374a882b12..97e1efdeccc3a714947fad8aacb5d412f83bcecd 100644 --- a/Utilities/ITK/Modules/Video/IO/include/itkFileListVideoIOFactory.h +++ b/Utilities/ITK/Modules/Video/IO/include/itkFileListVideoIOFactory.h @@ -38,9 +38,9 @@ public: typedef SmartPointer< const Self > ConstPointer; /** Class methods used to interface with the registered factories. */ - virtual const char * GetITKSourceVersion(void) const; + virtual const char * GetITKSourceVersion(void) const ITK_OVERRIDE; - virtual const char * GetDescription(void) const; + virtual const char * GetDescription(void) const ITK_OVERRIDE; /** Method for class instantiation. */ itkFactorylessNewMacro(Self); diff --git a/Utilities/ITK/Modules/Video/IO/include/itkVideoFileReader.hxx b/Utilities/ITK/Modules/Video/IO/include/itkVideoFileReader.hxx index 0bf46f4e71c3b9cb5d7db4ef09d4a1f2e0d30d1d..531f15d418a7c3e544df2020601f5aea4bb41bdb 100644 --- a/Utilities/ITK/Modules/Video/IO/include/itkVideoFileReader.hxx +++ b/Utilities/ITK/Modules/Video/IO/include/itkVideoFileReader.hxx @@ -37,7 +37,7 @@ VideoFileReader< TOutputVideoStream > { // Initialize members m_FileName = ""; - m_VideoIO = NULL; + m_VideoIO = ITK_NULLPTR; m_PixelConversionNeeded = false; m_IFrameSafe = true; diff --git a/Utilities/ITK/Modules/Video/IO/include/itkVideoFileWriter.h b/Utilities/ITK/Modules/Video/IO/include/itkVideoFileWriter.h index cf3c76fe83cdecc686722df32480917f097d704c..019a26ede13934111cb90e5723734557ec273e21 100644 --- a/Utilities/ITK/Modules/Video/IO/include/itkVideoFileWriter.h +++ b/Utilities/ITK/Modules/Video/IO/include/itkVideoFileWriter.h @@ -100,11 +100,11 @@ public: /** Aliased to the Write() method to be consistent with the rest of the * pipeline. */ - virtual void Update(); + virtual void Update() ITK_OVERRIDE; /** Write the entire video to a file, if possible. This is the same as * calling write or update without setting an output temporal region. */ - virtual void UpdateLargestPossibleRegion(); + virtual void UpdateLargestPossibleRegion() ITK_OVERRIDE; protected: @@ -112,7 +112,7 @@ protected: VideoFileWriter(); virtual ~VideoFileWriter(); - void PrintSelf(std::ostream &os, Indent indent) const; + virtual void PrintSelf(std::ostream &os, Indent indent) const ITK_OVERRIDE; /** Initialize output parameters */ bool InitializeOutputParameters(); @@ -123,7 +123,7 @@ protected: bool InitializeVideoIO(); /** Override TemporalStreamingGenerateData to do the actual writing. */ - virtual void TemporalStreamingGenerateData(); + virtual void TemporalStreamingGenerateData() ITK_OVERRIDE; /**-PROTECTED MEMBERS------------------------------------------------------*/ diff --git a/Utilities/ITK/Modules/Video/IO/include/itkVideoFileWriter.hxx b/Utilities/ITK/Modules/Video/IO/include/itkVideoFileWriter.hxx index 52a618652c7d77f70abc5bf7c80e0b067ac2cc41..ea639b8d5fb711e4a6aa53a3921d6e8f5774c432 100644 --- a/Utilities/ITK/Modules/Video/IO/include/itkVideoFileWriter.hxx +++ b/Utilities/ITK/Modules/Video/IO/include/itkVideoFileWriter.hxx @@ -34,14 +34,13 @@ namespace itk // template< typename TInputVideoStream > VideoFileWriter< TInputVideoStream > -::VideoFileWriter() +::VideoFileWriter() : + m_FileName(""), + m_VideoIO(ITK_NULLPTR), + m_FramesPerSecond(24), + m_FourCC("MP42"), + m_NumberOfComponents(0) { - // Initialize members - m_FileName = ""; - m_VideoIO = NULL; - m_FramesPerSecond = 24; // Default to 24 fps - m_FourCC = "MP42"; // Default to Mpeg 4 v2 - // TemporalProcessObject inherited members this->TemporalProcessObject::m_UnitInputNumberOfFrames = 1; this->TemporalProcessObject::m_UnitOutputNumberOfFrames = 1; @@ -102,7 +101,7 @@ VideoFileWriter< TInputVideoStream > { if (this->GetNumberOfInputs() < 1) { - return NULL; + return ITK_NULLPTR; } return static_cast<VideoStreamType*>(this->ProcessObject::GetInput(0)); @@ -135,7 +134,7 @@ VideoFileWriter< TInputVideoStream > // Make sure input is available const VideoStreamType* input = this->GetInput(); - if (input == NULL) + if (input == ITK_NULLPTR) { itkExceptionMacro("No input to writer"); } @@ -272,7 +271,7 @@ VideoFileWriter< TInputVideoStream > ::UpdateLargestPossibleRegion() { const VideoStreamType* input = this->GetInput(); - if (input == NULL) + if (input == ITK_NULLPTR) { itkExceptionMacro("No input to writer"); } @@ -320,7 +319,7 @@ VideoFileWriter< TInputVideoStream > ::InitializeOutputParameters() { // InputImage and VideoIO must be valid - if (this->GetInput() == NULL) + if (this->GetInput() == ITK_NULLPTR) { return false; } diff --git a/Utilities/ITK/Modules/Video/IO/include/itkVideoIOBase.h b/Utilities/ITK/Modules/Video/IO/include/itkVideoIOBase.h index f1c64e539ad66d1e20a53f96a5cc60030c3e07a3..4eb0c062b8ffa9307f85ba7ad590cbff18801958 100644 --- a/Utilities/ITK/Modules/Video/IO/include/itkVideoIOBase.h +++ b/Utilities/ITK/Modules/Video/IO/include/itkVideoIOBase.h @@ -114,7 +114,7 @@ protected: VideoIOBase(); virtual ~VideoIOBase(); - void PrintSelf(std::ostream & os, Indent indent) const; + virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE; /** Member Variables */ ReadType m_ReadType; diff --git a/Utilities/ITK/Modules/Video/IO/src/itkFileListVideoIO.cxx b/Utilities/ITK/Modules/Video/IO/src/itkFileListVideoIO.cxx index 52a71c167fa730665aed970a6161f7e959ed44d4..12b253a3cd6811dcfcedf043622056c2bd819d62 100644 --- a/Utilities/ITK/Modules/Video/IO/src/itkFileListVideoIO.cxx +++ b/Utilities/ITK/Modules/Video/IO/src/itkFileListVideoIO.cxx @@ -526,7 +526,7 @@ void FileListVideoIO::OpenWriter() // void FileListVideoIO::ResetMembers() { - m_ImageIO = NULL; + m_ImageIO = ITK_NULLPTR; m_FileNames.clear(); m_WriterOpen = false; m_ReaderOpen = false; diff --git a/Utilities/ITK/Modules/Video/IO/src/itkVideoIOBase.cxx b/Utilities/ITK/Modules/Video/IO/src/itkVideoIOBase.cxx index 21dd988cc7dee1c9104ad210a58ed2d7c4ad52ac..618e34b3510c858d86a0b7cfbd63b2c2ca574f92 100644 --- a/Utilities/ITK/Modules/Video/IO/src/itkVideoIOBase.cxx +++ b/Utilities/ITK/Modules/Video/IO/src/itkVideoIOBase.cxx @@ -24,7 +24,17 @@ namespace itk { -VideoIOBase::VideoIOBase() +VideoIOBase::VideoIOBase() : + m_ReadType(ReadFromFile), + m_FramesPerSecond(0.0), + m_FrameTotal(NumericTraits<SizeValueType>::Zero), + m_CurrentFrame(NumericTraits<SizeValueType>::Zero), + m_IFrameInterval(NumericTraits<SizeValueType>::Zero), + m_LastIFrame(NumericTraits<SizeValueType>::Zero), + m_Ratio(0.0), + m_PositionInMSec(0.0), + m_WriterOpen(false), + m_ReaderOpen(false) { } diff --git a/Utilities/ITK/Modules/Video/IO/src/itkVideoIOFactory.cxx b/Utilities/ITK/Modules/Video/IO/src/itkVideoIOFactory.cxx index 8315bbf04527bb0d579e09831cce1263f1c8e74c..6f98007a1b878d7aac22a7840129617ef0556b33 100644 --- a/Utilities/ITK/Modules/Video/IO/src/itkVideoIOFactory.cxx +++ b/Utilities/ITK/Modules/Video/IO/src/itkVideoIOFactory.cxx @@ -83,7 +83,7 @@ VideoIOBase::Pointer VideoIOFactory::CreateVideoIO( IOModeType mode, const char* } // Didn't find a usable VideoIO - return NULL; + return ITK_NULLPTR; } diff --git a/Utilities/ITK/Utilities/Doxygen/CMakeLists.txt b/Utilities/ITK/Utilities/Doxygen/CMakeLists.txt index 97bd7ea4feb53aa50650bc9e109d0b95283a7cea..31876f009a858da8b7c112f91a6d6166a58b8645 100644 --- a/Utilities/ITK/Utilities/Doxygen/CMakeLists.txt +++ b/Utilities/ITK/Utilities/Doxygen/CMakeLists.txt @@ -135,25 +135,24 @@ if (BUILD_DOCUMENTATION) DEPENDS "${ITK_SOURCE_DIR}/Examples" "${ITK_SOURCE_DIR}/Utilities/Doxygen/GenerateExamplesDox.cmake" ) + add_custom_target(Documentation ALL + COMMAND ${DOXYGEN_EXECUTABLE} ${ITK_BINARY_DIR}/Utilities/Doxygen/doxygen.config + MAIN_DEPENDENCY ${ITK_BINARY_DIR}/Utilities/Doxygen/doxygen.config + DEPENDS ${ITK_BINARY_DIR}/Utilities/Doxygen/itkdoxygen.pl + DEPENDS ${ITK_BINARY_DIR}/Documentation/Doxygen/Examples.dox + WORKING_DIRECTORY ${ITK_BINARY_DIR}/Utilities/Doxygen + ) # Somehow the logo image is not copied into the html folder. # Here we ensure that the logo image ends up in the right directory # where html pages could find it. add_custom_command(TARGET Documentation + POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${ITK_SOURCE_DIR}/Documentation/Art/itkLogoSmall.jpg # logo ${ITK_DOXYGEN_OUTPUT_DIR}/html # output doxygen directory ) - add_custom_target(Documentation ALL - COMMAND ${DOXYGEN_EXECUTABLE} ${ITK_BINARY_DIR}/Utilities/Doxygen/doxygen.config - MAIN_DEPENDENCY ${ITK_BINARY_DIR}/Utilities/Doxygen/doxygen.config - DEPENDS ${ITK_BINARY_DIR}/Utilities/Doxygen/itkdoxygen.pl - DEPENDS ${ITK_BINARY_DIR}/Documentation/Doxygen/Examples.dox - WORKING_DIRECTORY ${ITK_BINARY_DIR}/Utilities/Doxygen - ) - - message( STATUS "To generate Doxygen's documentation, you need to build the Documentation target" ) diff --git a/Utilities/ITK/Utilities/Doxygen/doxygen.config.in b/Utilities/ITK/Utilities/Doxygen/doxygen.config.in index 1bfb75a996ac1302f42eb38e7b56469a528e4297..07996591c6f01b73741a2e2cedee7931dafc871b 100644 --- a/Utilities/ITK/Utilities/Doxygen/doxygen.config.in +++ b/Utilities/ITK/Utilities/Doxygen/doxygen.config.in @@ -1972,11 +1972,12 @@ PREDEFINED = "itkNotUsed(x)=" \ "itkSetConstObjectMacro(name,type)= virtual void Set##name ( const type* _arg);" \ "itkGetConstObjectMacro(name,type)= virtual const type* Get##name () const;" \ "itkGetModifiableObjectMacro(name,type)= virtual type* GetModifiable##name (); virtual const type* Get##name () const;" \ - "itkGetConstReferenceMacro(name,type)= virtual const type& Get##name ();" \ + "itkGetConstReferenceMacro(name,type)= virtual const type& Get##name () const;" \ "itkSetEnumMacro(name,type)= virtual void Set##name (const type _arg);" \ "itkGetEnumMacro(name,type)= virtual type Get##name () const;" \ "itkGetConstReferenceObjectMacro(name,type)= virtual const type::Pointer& Get##name () const;" \ "itkSetDecoratedInputMacro(name, type, number)= virtual void Set##name##Input(const SimpleDataObjectDecorator<type> *_arg); virtual void SetInput##number(const SimpleDataObjectDecorator<type> *_arg); virtual const SimpleDataObjectDecorator<type> * Get##name##Input() const; virtual const SimpleDataObjectDecorator<type> * GetInput##number() const; virtual void Set##name(const type &_arg);" \ + "itkSetGetDecoratedInputMacro(name, type, number)= virtual void Set##name##Input(const SimpleDataObjectDecorator< type > *_arg); virtual void Set##name(const type &_arg); virtual const SimpleDataObjectDecorator< type > * Get##name##Input() const; virtual const type & Get##name() const; " \ "itkSetDecoratedObjectInputMacro(name, type, number)= virtual void Set##name##Input(const DataObjectDecorator<type> *_arg); virtual void SetInput##number(const DataObjectDecorator<type> *_arg); virtual const DataObjectDecorator<type> * Get##name##Input() const; virtual const DataObjectDecorator<type> * GetInput##number() const; virtual void Set##name(const type *_arg);" \ "itkBooleanMacro(name)= virtual void name##On (); virtual void name##Off ();" \ "itkSetVector2Macro(name,type)= virtual void Set##name (type _arg1, type _arg2) virtual void Set##name (type _arg[2]);" \ @@ -1999,7 +2000,7 @@ PREDEFINED = "itkNotUsed(x)=" \ "itkEventMacro(thisClass,superclass)= class thisClass : public superclass {};" \ "itkDeclareExceptionMacro(newexcp,parentexcp,whatmessage)= namespace itk { class newexcp : public parentexcp { public: newexcp( const char *file, unsigned int lineNumber ) : parentexcp( file, lineNumber ) { this->SetDescription( whatmessage ); } newexcp( const std::string & file, unsigned int lineNumber ) : parentexcp( file, lineNumber ) { this->SetDescription( whatmessage ); } itkTypeMacro( newexcp, , parentexcp); }; }" \ "itkConceptMacro(thisName,thisConcept)= /** This class requires thisName in the form of thisConcept */ typedef thisConcept thisName;" \ - "vcl_numeric_limits= std::numeric_limits" \ + "std::numeric_limits= std::numeric_limits" \ "ITK_TYPENAME= typename" \ "itkTemplateFloatingToIntegerMacro(name)= template <TReturn, typename TInput> name( TInput x )" \ "FEM_ABSTRACT_CLASS(thisClass,parentClass)= public: /** Standard Self typedef.*/ typedef thisClass Self; /** Standard Superclass typedef. */ typedef parentClass Superclass; /** Pointer or SmartPointer to an object. */ typedef Self* Pointer; /** Const pointer or SmartPointer to an object. */ typedef const Self* ConstPointer; private:" \ @@ -2016,7 +2017,8 @@ PREDEFINED = "itkNotUsed(x)=" \ "ITK_USE_FFTWF" \ "ITK_USE_CONCEPT_CHECKING" \ "__itkMacro_h" \ - "ITK_LEGACY_REMOVE" + "ITK_LEGACY_REMOVE" \ + "ITKCommon_EXPORT_EXPLICIT" # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this # tag can be used to specify a list of macro names that should be expanded. The diff --git a/Utilities/ITK/Utilities/Doxygen/mcdoc.py b/Utilities/ITK/Utilities/Doxygen/mcdoc.py old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Doxygen/vxl_doxy.pl b/Utilities/ITK/Utilities/Doxygen/vxl_doxy.pl old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/KWStyle/KWStyle.cmake b/Utilities/ITK/Utilities/KWStyle/KWStyle.cmake index a755337f16b52a927b7a52a6f5a3e6ed6f4d43c6..4d6335e0bdba02d92e12b654b9e3bfa4924e838a 100644 --- a/Utilities/ITK/Utilities/KWStyle/KWStyle.cmake +++ b/Utilities/ITK/Utilities/KWStyle/KWStyle.cmake @@ -1,12 +1,13 @@ - -find_package(KWStyle 1.0.1 - QUIET - ) -option(ITK_USE_KWSTYLE - "Enable the use of KWStyle for checking coding style." - ${KWSTYLE_FOUND} # default - ) -mark_as_advanced(ITK_USE_KWSTYLE) +if(NOT DEFINED ITK_USE_KWSTYLE) + find_package(KWStyle 1.0.1 + QUIET + ) + option(ITK_USE_KWSTYLE + "Enable the use of KWStyle for checking coding style." + ${KWSTYLE_FOUND} # default + ) + mark_as_advanced(ITK_USE_KWSTYLE) +endif(NOT DEFINED ITK_USE_KWSTYLE) if(ITK_USE_KWSTYLE) find_package(KWStyle 1.0.1 @@ -15,24 +16,24 @@ if(ITK_USE_KWSTYLE) ) # Define and configure configuration files - set(KWSTYLE_ITK_CONFIGURATION_FILE + set(kwstyle_itk_configuration_file ${ITK_SOURCE_DIR}/Utilities/KWStyle/ITK.kws.xml ) - set(KWSTYLE_ITK_CODE_FILES_LIST_FILE + set(kwstyle_itk_code_files_list_file ${ITK_BINARY_DIR}/Utilities/KWStyle/ITKCodeFiles.txt ) configure_file( # KWStyle requires that the files list be absolute paths ${ITK_SOURCE_DIR}/Utilities/KWStyle/ITKCodeFiles.txt.in - ${KWSTYLE_ITK_CODE_FILES_LIST_FILE} + ${kwstyle_itk_code_files_list_file} ) - set(KWSTYLE_ITK_EXAMPLES_FILES_LIST_FILE + set(kwstyle_itk_examples_files_list_file ${ITK_BINARY_DIR}/Utilities/KWStyle/ITKExamplesFiles.txt ) configure_file( # KWStyle requires that the files list be absolute paths ${ITK_SOURCE_DIR}/Utilities/KWStyle/ITKExamplesFiles.txt.in - ${KWSTYLE_ITK_EXAMPLES_FILES_LIST_FILE} + ${kwstyle_itk_examples_files_list_file} ) - set(KWSTYLE_ITK_OVERWRITE_FILE + set(kwstyle_itk_overwrite_file ${ITK_SOURCE_DIR}/Utilities/KWStyle/ITKOverwrite.txt ) @@ -54,61 +55,61 @@ if(ITK_USE_KWSTYLE) mark_as_advanced(KWSTYLE_USE_GCC_FORMAT) mark_as_advanced(KWSTYLE_USE_MSVC_FORMAT) - set(KWSTYLE_EDITOR_FORMAT "") + set(kwstyle_editor_format "") if(KWSTYLE_USE_VIM_FORMAT) - list(APPEND KWSTYLE_EDITOR_FORMAT -vim) + list(APPEND kwstyle_editor_format -vim) endif() if(KWSTYLE_USE_GCC_FORMAT) - list(APPEND KWSTYLE_EDITOR_FORMAT -gcc) + list(APPEND kwstyle_editor_format -gcc) endif() if(KWSTYLE_USE_MSVC_FORMAT) - list(APPEND KWSTYLE_EDITOR_FORMAT -msvc) + list(APPEND kwstyle_editor_format -msvc) endif() list(LENGTH - KWSTYLE_EDITOR_FORMAT - KWSTYLE_EDITOR_FORMAT_LENGTH + kwstyle_editor_format + kwstyle_editor_format_length ) - if(KWSTYLE_EDITOR_FORMAT_LENGTH GREATER 1) + if(kwstyle_editor_format_length GREATER 1) message(FATAL_ERROR "At most, only one of KWSTYLE_USE_*_FORMAT can be set to TRUE.") endif() # Add build target and CTest test - set(KWSTYLE_COMMON_ARGUMENTS - -xml ${KWSTYLE_ITK_CONFIGURATION_FILE} + set(kwstyle_common_arguments + -xml ${kwstyle_itk_configuration_file} -v - -o ${KWSTYLE_ITK_OVERWRITE_FILE} + -o ${kwstyle_itk_overwrite_file} ) add_custom_target(StyleCheckCode COMMAND ${KWSTYLE_EXECUTABLE} - ${KWSTYLE_COMMON_ARGUMENTS} - -D ${KWSTYLE_ITK_CODE_FILES_LIST_FILE} - ${KWSTYLE_EDITOR_FORMAT} + ${kwstyle_common_arguments} + -D ${kwstyle_itk_code_files_list_file} + ${kwstyle_editor_format} COMMENT "Coding Style Checker" - WORKING_DIRECTORY ${ITK_SOURCE_DIR} # the paths in KWSTYLE_CONFIGURATION_FILE are relative + WORKING_DIRECTORY ${ITK_SOURCE_DIR} # the paths in kwstyle_itk_configuration_file are relative ) add_custom_target(StyleCheckExamples COMMAND ${KWSTYLE_EXECUTABLE} - ${KWSTYLE_COMMON_ARGUMENTS} - -D ${KWSTYLE_ITK_EXAMPLES_FILES_LIST_FILE} - ${KWSTYLE_EDITOR_FORMAT} + ${kwstyle_common_arguments} + -D ${kwstyle_itk_examples_files_list_file} + ${kwstyle_editor_format} COMMENT "Examples Style Checker" - WORKING_DIRECTORY ${ITK_SOURCE_DIR} # the paths in KWSTYLE_CONFIGURATION_FILE are relative + WORKING_DIRECTORY ${ITK_SOURCE_DIR} # the paths in kwstyle_itk_configuration_file are relative ) if(BUILD_TESTING) set(itk-module KWStyle) # for uniformity and brevity, test will always output GCC-style itk_add_test(NAME KWStyleCodeTest COMMAND ${KWSTYLE_EXECUTABLE} - ${KWSTYLE_COMMON_ARGUMENTS} - -D ${KWSTYLE_ITK_CODE_FILES_LIST_FILE} + ${kwstyle_common_arguments} + -D ${kwstyle_itk_code_files_list_file} -gcc WORKING_DIRECTORY ${ITK_SOURCE_DIR} ) itk_add_test(NAME KWStyleExamplesTest COMMAND ${KWSTYLE_EXECUTABLE} - ${KWSTYLE_COMMON_ARGUMENTS} - -D ${KWSTYLE_ITK_EXAMPLES_FILES_LIST_FILE} + ${kwstyle_common_arguments} + -D ${kwstyle_itk_examples_files_list_file} -gcc WORKING_DIRECTORY ${ITK_SOURCE_DIR} ) diff --git a/Utilities/ITK/Utilities/Maintenance/ArchiveTestingData.py b/Utilities/ITK/Utilities/Maintenance/ArchiveTestingData.py old mode 100644 new mode 100755 index ed4ca73761c3ac780dcf28fa7d033d9a7763361e..e55d8f095e8ce8846cf4c6ef9ae17e021fa85eaf --- a/Utilities/ITK/Utilities/Maintenance/ArchiveTestingData.py +++ b/Utilities/ITK/Utilities/Maintenance/ArchiveTestingData.py @@ -10,6 +10,8 @@ local ExternalData object store. Requires pydas: https://github.com/midasplatform/pydas """ +from __future__ import print_function + import argparse import fnmatch import os diff --git a/Utilities/ITK/Utilities/Maintenance/BuildHeaderTest.py b/Utilities/ITK/Utilities/Maintenance/BuildHeaderTest.py old mode 100644 new mode 100755 index be66437b64c07a4d1aaf160f35218d0462dad418..cdf54efc0465bad7c203b7e8a296974e60868928 --- a/Utilities/ITK/Utilities/Maintenance/BuildHeaderTest.py +++ b/Utilities/ITK/Utilities/Maintenance/BuildHeaderTest.py @@ -18,6 +18,8 @@ # #==========================================================================*/ +from __future__ import print_function + usage = """usage: BuildHeaderTest.py <module_name> <module_source_path> <module_binary_path> <maximum_number_of_headers> This script generates a a source file designed to check the headers in each diff --git a/Utilities/ITK/Utilities/Maintenance/BuildKWStyle/BuildKWStyle.sh b/Utilities/ITK/Utilities/Maintenance/BuildKWStyle/BuildKWStyle.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/BuildKWStyle/CMakeLists.txt b/Utilities/ITK/Utilities/Maintenance/BuildKWStyle/CMakeLists.txt index 724bc978feabef15cb6f129caba027a75362b272..fc71790689bb007e54fecbe6a920b7ab024bcec4 100644 --- a/Utilities/ITK/Utilities/Maintenance/BuildKWStyle/CMakeLists.txt +++ b/Utilities/ITK/Utilities/Maintenance/BuildKWStyle/CMakeLists.txt @@ -3,6 +3,7 @@ project(BuildKWStyle) include(ExternalProject) +itk_download_attempt_check(KWStyle) ExternalProject_add(KWStyle GIT_REPOSITORY "http://public.kitware.com/KWStyle.git" # GIT_TAG -- shouldn't there be a release tag? the GIT repo just diff --git a/Utilities/ITK/Utilities/Maintenance/CodeSwarmWithGource.sh b/Utilities/ITK/Utilities/Maintenance/CodeSwarmWithGource.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/FindMissingCopyrightStatementsInITK.sh b/Utilities/ITK/Utilities/Maintenance/FindMissingCopyrightStatementsInITK.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/FindRedundantHeaderIncludes.py b/Utilities/ITK/Utilities/Maintenance/FindRedundantHeaderIncludes.py old mode 100644 new mode 100755 index 16ad8d727e0b4e4d00943d06e53fbfbad8ad2f16..b4427d3d357ba9b1b46870db054ee2c10ccca665 --- a/Utilities/ITK/Utilities/Maintenance/FindRedundantHeaderIncludes.py +++ b/Utilities/ITK/Utilities/Maintenance/FindRedundantHeaderIncludes.py @@ -25,6 +25,8 @@ ## you can remove the sibling include. ## in the ITK/Code directory issue the following command +from __future__ import print_function + import os import sys import re @@ -47,7 +49,7 @@ class FileToPathMapping: curr_dir=os.path.dirname(testfile) if not os.path.isfile(testfile): continue - #print testfile + #print(testfile) ff=open(testfile) search_string=r'^#include *([<"])(itk[^<"]*h)([>"])' myregexp=re.compile(search_string) @@ -79,14 +81,14 @@ class FileToPathMapping: ## Pocess all children isdone=donenode.get((starting_child,dupcandidate),None) if isdone != None: - #print "found {0} {1}".format(starting_child,dupcandidate) + #print("found {0} {1}".format(starting_child,dupcandidate)) return False else: - #print "adding {0} {1}".format(starting_child,dupcandidate) + #print("adding {0} {1}".format(starting_child,dupcandidate)) donenode[(starting_child,dupcandidate)]=True nodeEdges=myDependTree[node] - #print nodeEdges + #print(nodeEdges) if ( dupcandidate not in nodeEdges): # Nothing to do print("-") return False @@ -125,7 +127,7 @@ myDependTree=mymapper.FillFromWalkingTree(basedir) # print(parentFiles) # for childFiles in myDependTree[parentFiles]: # print(" "*3+childFiles) -#print mymapper.filePathBaseDirs +#print(mymapper.filePathBaseDirs) donenode=dict() diff --git a/Utilities/ITK/Utilities/Maintenance/JREUpdate.py b/Utilities/ITK/Utilities/Maintenance/JREUpdate.py old mode 100644 new mode 100755 index c80655ec8e8522fc533a7a7db559f831f16268a1..09bb5d37f2c94cfb2436c6ca733bce2baa4402f0 --- a/Utilities/ITK/Utilities/Maintenance/JREUpdate.py +++ b/Utilities/ITK/Utilities/Maintenance/JREUpdate.py @@ -14,6 +14,8 @@ Currently, the tarball needs to be uploaded manually to midas3.kitware.com. In the future, pydas can be used for automatic upload. """ +from __future__ import print_function + import os import subprocess import tarfile diff --git a/Utilities/ITK/Utilities/Maintenance/ParallelStripIncludes.py b/Utilities/ITK/Utilities/Maintenance/ParallelStripIncludes.py old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/SourceTarball.bash b/Utilities/ITK/Utilities/Maintenance/SourceTarball.bash old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/StripIncludes.py b/Utilities/ITK/Utilities/Maintenance/StripIncludes.py old mode 100644 new mode 100755 index 58cd4bcf7ed1015b6943a213c7e19467292c83f1..920233de3a04b6edb8dd8edb96c83cb83bda9c7f --- a/Utilities/ITK/Utilities/Maintenance/StripIncludes.py +++ b/Utilities/ITK/Utilities/Maintenance/StripIncludes.py @@ -35,6 +35,7 @@ relativeFileList = "filelist.txt" # files to process includesToSkip = ["itkVersion.h","<cstring>", "<iostream>", "<fstream>","vnl/vnl_math.h","<string>","itkConfigure.h","<stdlib>","<time.h>"] #keep those headers ####################################################################### +from __future__ import print_function import os @@ -81,7 +82,7 @@ def processFile(directory, fileName): if line.startswith('#include'): if shouldSkipInclude(line): continue - print "Try remove:", line + print("Try remove:", line) lines[i] = "" writeFile(lines, absFileName) @@ -89,7 +90,7 @@ def processFile(directory, fileName): if returnCode == 0: removedLines.append(i) else: - print "Restoring:", line + print("Restoring:", line) lines[i] = line # Write final changes to file diff --git a/Utilities/ITK/Utilities/Maintenance/UpdateCopyrightStatementsInITK.py b/Utilities/ITK/Utilities/Maintenance/UpdateCopyrightStatementsInITK.py old mode 100644 new mode 100755 index 940bf8dd4a0625f60a4ddea0aa6eb446c61ef334..a384ba85f80a7d6bafd7feafc0c99e9b192118cc --- a/Utilities/ITK/Utilities/Maintenance/UpdateCopyrightStatementsInITK.py +++ b/Utilities/ITK/Utilities/Maintenance/UpdateCopyrightStatementsInITK.py @@ -22,6 +22,9 @@ # # This script is designed to help change the copyright notices in all ITK files to a common format. # For files that are .h, .cxx, .hxx, .c, if there is no other copyright information, add the itkCopyright. + +from __future__ import print_function + import re import sys import os @@ -108,10 +111,10 @@ for top,directory,files in os.walk(HeadOfITKTree): continue if ff[0] == '.': #Skip all files that begin with '.' files.remove(ff) - #print "@@@@@@@",ff + #print("@@@@@@@",ff) continue currFile=os.path.join(top,ff) - print currFile + print(currFile) infile=open(currFile,'r') file_text=infile.read() diff --git a/Utilities/ITK/Utilities/Maintenance/VerifyURLs.py b/Utilities/ITK/Utilities/Maintenance/VerifyURLs.py old mode 100644 new mode 100755 index 6af9abaccc9a5de8b90b48264418db0d36efaeaf..eec6d34436f3988a6bd91174722a675866bdd78e --- a/Utilities/ITK/Utilities/Maintenance/VerifyURLs.py +++ b/Utilities/ITK/Utilities/Maintenance/VerifyURLs.py @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import print_function + import sys import re import httplib @@ -22,7 +24,7 @@ for arg in sys.argv[1:]: f.close() if len( http_dict ) > 1: - print "Found ", len( http_dict ), " unique URLS." + print("Found ", len( http_dict ), " unique URLS.") # compile regular expression to pull out the server address and path server_re = re.compile( "http://([^/]+)(/?[^\s]*)" ) @@ -33,7 +35,7 @@ for url,filename in http_dict.items(): path = mo.group( 2 ) try: - #print "Verifying URL: ", url, + #print("Verifying URL: ", url,) # connect to server and get the path conn = httplib.HTTPConnection( server ) @@ -43,31 +45,31 @@ for url,filename in http_dict.items(): if r1.status == httplib.OK: # URL is OK do nothing - #print " URL: ", url, r1.status, r1.reason + #print(" URL: ", url, r1.status, r1.reason) pass elif r1.status == httplib.MOVED_PERMANENTLY: - print filename,": ERROR (URL needs update): ", url, - print r1.status, r1.reason, " to: ", r1.getheader("location") + print(filename,": ERROR (URL needs update): ", url) + print(r1.status, r1.reason, " to: ", r1.getheader("location")) elif r1.status == httplib.FOUND: - print filename,": INFO URL: ", url, r1.status, r1.reason, " to: ", r1.getheader("location") + print(filename,": INFO URL: ", url, r1.status, r1.reason, " to: ", r1.getheader("location")) pass elif r1.status == httplib.FORBIDDEN: - print filename,": INFO URL: ", url, r1.status, r1.reason + print(filename,": INFO URL: ", url, r1.status, r1.reason) pass elif r1.status == httplib.NOT_FOUND: - print filename,": ERROR URL: ", url, r1.status, r1.reason + print(filename,": ERROR URL: ", url, r1.status, r1.reason) else: - print filename, ": UNKNOWN URL: ", url, "\"", r1.status, "\"", r1.reason + print(filename, ": UNKNOWN URL: ", url, "\"", r1.status, "\"", r1.reason) pass except Exception as e: - print - print filename,": ERROR (exception): ", url, - print e + print() + print(filename,": ERROR (exception): ", url) + print(e) except: - print filename,": ERROR (exception): ", url, - print "Unexpected error:", sys.exc_info()[0] + print(filename,": ERROR (exception): ", url) + print("Unexpected error:", sys.exc_info()[0]) raise finally: conn.close() diff --git a/Utilities/ITK/Utilities/Maintenance/VisualizeTestTimes.py b/Utilities/ITK/Utilities/Maintenance/VisualizeTestTimes.py old mode 100644 new mode 100755 index 514f19ef4a73f211b698d5a78173f5e87ff6c2f8..9fc6b91e8838f85808c3bc3cb01bd10b25b28a88 --- a/Utilities/ITK/Utilities/Maintenance/VisualizeTestTimes.py +++ b/Utilities/ITK/Utilities/Maintenance/VisualizeTestTimes.py @@ -8,6 +8,8 @@ Run from the top of the build tree after the ctest has been run at least once. Pass the --modular-grouping flag to group by module.""" +from __future__ import print_function + import os import pprint import subprocess diff --git a/Utilities/ITK/Utilities/Maintenance/WhatModulesITK.py b/Utilities/ITK/Utilities/Maintenance/WhatModulesITK.py old mode 100644 new mode 100755 index 10e1c55a92c10d936e53958d672891980843cb11..4b0419f19b80e7bf6b016830f64e1640d2d111ed --- a/Utilities/ITK/Utilities/Maintenance/WhatModulesITK.py +++ b/Utilities/ITK/Utilities/Maintenance/WhatModulesITK.py @@ -1,10 +1,13 @@ #!/usr/bin/env python + +from __future__ import print_function + import os, sys import re program = sys.argv[0] if len(sys.argv) < 3: - print """ + print(""" Usage: WhatModulesITK.py itkSourceTree applicationFiles... Generate a FindPackage(ITK COMPONENTS) that lists all modules referenced by a set of files @@ -32,7 +35,7 @@ NOTE: IO modules, other than ITKIOImageBase, are not discovered unless their include file is present in the application code. If ITKIOImageBase is present, a cmake variable ITK_IO_MODULES_USED is created and added to the module list. -""" +""") exit(0) # Build a dict that maps include files to paths @@ -85,7 +88,7 @@ pathsToModules = FindModules(sys.argv[1] + "/Modules") # Test to see if ITK source is provided if len(pathsToModules) == 0: - print program + ": " + sys.argv[1] + " is not an ITK source directory. It does not contain any itk-module.cmake files." + print(program + ": " + sys.argv[1] + " is not an ITK source directory. It does not contain any itk-module.cmake files.") exit(1) # Build a set of includes for all command line files @@ -97,7 +100,7 @@ for f in sys.argv: if os.path.isfile(f): allIncludes.update(FindIncludes(f)) else: - print program + ": " + f + " is a directory and is ignored" + print(program + ": " + f + " is a directory and is ignored") # Build a set that contains all modules referenced in command line files allModules = set() @@ -107,12 +110,12 @@ for inc in allIncludes: allModules.add(pathsToModules[includesToPaths[inc]]) # Print a useful cmake command -print r'set(ITK_IO_MODULES_USED "")' -print "find_package(ITK COMPONENTS" +print(r'set(ITK_IO_MODULES_USED "")') +print("find_package(ITK COMPONENTS") for module in sorted(allModules): - print " " + module + print(" " + module) if "ITKIOImageBase" in allModules: - print r" ${ITK_IO_MODULES_USED}" -print ")" + print(r" ${ITK_IO_MODULES_USED}") +print(")") -print "Your application code includes " + str(len(allModules)) + " of " + str(len(pathsToModules)) + " itk modules." +print("Your application code includes " + str(len(allModules)) + " of " + str(len(pathsToModules)) + " itk modules.") diff --git a/Utilities/ITK/Utilities/Maintenance/computeCodeCoverageLocally.sh b/Utilities/ITK/Utilities/Maintenance/computeCodeCoverageLocally.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/computeCodeCoverageLocallyForOneTest.sh b/Utilities/ITK/Utilities/Maintenance/computeCodeCoverageLocallyForOneTest.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/computeGitStatistics.sh b/Utilities/ITK/Utilities/Maintenance/computeGitStatistics.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/doSingleKWStyleUncrustifyFix.sh.in b/Utilities/ITK/Utilities/Maintenance/doSingleKWStyleUncrustifyFix.sh.in old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/runValgrind.sh b/Utilities/ITK/Utilities/Maintenance/runValgrind.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/single-doxygen.sh b/Utilities/ITK/Utilities/Maintenance/single-doxygen.sh old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Utilities/Maintenance/strip-trailing-whitespace b/Utilities/ITK/Utilities/Maintenance/strip-trailing-whitespace old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Wrapping/CMakeLists.txt b/Utilities/ITK/Wrapping/CMakeLists.txt index 19f5b2a820de94babd53972a4d310dd3a1fb4c26..cbbaacdaa7dbab476e2ad83e72a4f8a04af85fa8 100644 --- a/Utilities/ITK/Wrapping/CMakeLists.txt +++ b/Utilities/ITK/Wrapping/CMakeLists.txt @@ -16,29 +16,21 @@ # #==========================================================================*/ +cmake_minimum_required(VERSION 2.8.6 FATAL_ERROR) +if(POLICY CMP0025) + cmake_policy(SET CMP0025 NEW) +endif() +if(POLICY CMP0042) + cmake_policy(SET CMP0042 NEW) +endif() + project(WrapITK) # set an internal cache to mark when this file is parsed set(ITK_WRAPPING_REACHED ON CACHE INTERNAL "Wrapping folder has been reached") -# check cmake version -# Require 2.4.2 for MATH and LIST commands (REMOVE_ITEM is not the same in -# 2.4.1) -# 2.4.5 is required to parse the if(POLICY) command. -cmake_minimum_required(VERSION 2.8 FATAL_ERROR) -if(COMMAND CMAKE_POLICY) - cmake_policy(SET CMP0003 NEW) - if(POLICY CMP0011) - cmake_policy(SET CMP0011 NEW) - endif() -endif() include("CMakeUtilityFunctions.cmake") -set(ITK_VERSION "${ITK_VERSION_MAJOR}.${ITK_VERSION_MINOR}.${ITK_VERSION_PATCH}") -if(NOT "${CMAKE_VERSION}" STRLESS "2.6.3") - cmake_policy(SET CMP0011 OLD) -endif() - enable_testing() ############################################################################### @@ -47,12 +39,6 @@ enable_testing() # Set up options needed for ConfigureWrapping -# set WrapITK version -set(WrapITK_VERSION_MAJOR 0) -set(WrapITK_VERSION_MINOR 4) -set(WrapITK_VERSION_PATCH 0) - - option(ITK_WRAP_unsigned_char "Wrap unsigned char type" ON) option(ITK_WRAP_unsigned_short "Wrap unsigned short type" OFF) option(ITK_WRAP_unsigned_long "Wrap unsigned long type" OFF) diff --git a/Utilities/ITK/Wrapping/ConfigureWrapping.cmake b/Utilities/ITK/Wrapping/ConfigureWrapping.cmake index cdcf4137bf50aef0d1f60fc2bebd8f6ad92eb593..556523ff18fa77ad22b1d85e63559072ba886698 100644 --- a/Utilities/ITK/Wrapping/ConfigureWrapping.cmake +++ b/Utilities/ITK/Wrapping/ConfigureWrapping.cmake @@ -38,8 +38,6 @@ # only used by the macros defined in a given cmake file. ############################################################################### -cmake_minimum_required(VERSION 2.8 FATAL_ERROR) - ############################################################################### # Find Required Packages @@ -50,16 +48,6 @@ cmake_minimum_required(VERSION 2.8 FATAL_ERROR) #----------------------------------------------------------------------------- find_package(ITK REQUIRED) include(${ITK_USE_FILE}) -# we must be sure we have the right ITK version; WrapITK can't build with -# an old version of ITK because some classes will not be there. -# newer version should only cause some warnings -set(ITK_REQUIRED_VERSION "4.0.0") -set(ITK_VERSION "${ITK_VERSION_MAJOR}.${ITK_VERSION_MINOR}.${ITK_VERSION_PATCH}") -if("${ITK_VERSION}" VERSION_LESS "${ITK_REQUIRED_VERSION}") - message(FATAL_ERROR "ITK ${ITK_REQUIRED_VERSION} is required to build this version of WrapITK, and you are trying to use version ${ITK_VERSION}. Set ITK_DIR to point to the directory of ITK ${ITK_REQUIRED_VERSION}.") -endif() - -cmake_policy(SET CMP0003 NEW) ############################################################################### # Set various variables in order @@ -114,10 +102,6 @@ else() set(WRAP_ITK_LIBNAME_PREFIX "") endif() -# 467 is for warnings caused by typemap on overloaded methods -set(CSWIG_IGNORE_WARNINGS -w362 -w389 -w467 -w503 -w508 -w509 -w516) -add_definitions(-DSWIG_GLOBAL) - # generators dir set(GENERATORS_SRC_DIR "${WRAP_ITK_CMAKE_DIR}/Generators" CACHE INTERNAL "generators source directory") diff --git a/Utilities/ITK/Wrapping/Generators/Doc/doxy2swig.py b/Utilities/ITK/Wrapping/Generators/Doc/doxy2swig.py old mode 100644 new mode 100755 index 3e08303cec1df1f1f20570a08db9b3d6a2c43f15..63bf07fcf722f2fdd15e737c3e165f85e074ab5a --- a/Utilities/ITK/Wrapping/Generators/Doc/doxy2swig.py +++ b/Utilities/ITK/Wrapping/Generators/Doc/doxy2swig.py @@ -21,6 +21,7 @@ output will be written (the file will be clobbered). # Author: Prabhu Ramachandran # License: BSD style +from __future__ import print_function from xml.dom import minidom import re @@ -309,7 +310,7 @@ class Doxy2SWIG: fname = refid + '.xml' if not os.path.exists(fname): fname = os.path.join(self.my_dir, fname) - print "parsing file: %s"%fname + print("parsing file: %s"%fname) p = Doxy2SWIG(fname) p.generate() self.pieces.extend(self.clean_pieces(p.pieces)) @@ -366,6 +367,6 @@ def main(input, output): if __name__ == '__main__': if len(sys.argv) != 3: - print __doc__ + print(__doc__) sys.exit(1) main(sys.argv[1], sys.argv[2]) diff --git a/Utilities/ITK/Wrapping/Generators/Doc/doxygen.config.in b/Utilities/ITK/Wrapping/Generators/Doc/doxygen.config.in index e856e64ada02fcac9fa742245e5879ea5d8f38ae..e1892373d34cc7a82d796d285bd59116a8463282 100644 --- a/Utilities/ITK/Wrapping/Generators/Doc/doxygen.config.in +++ b/Utilities/ITK/Wrapping/Generators/Doc/doxygen.config.in @@ -420,7 +420,7 @@ PREDEFINED = "itkNotUsed(x)="\ class thisClass : public superclass {};" \ "itkConceptMacro(name,concept)= \ enum { name = 0 };" \ - "vcl_numeric_limits= \ + "std::numeric_limits= \ std::numeric_limits" \ "ITK_TYPENAME= \ typename" \ diff --git a/Utilities/ITK/Wrapping/Generators/Doc/itk_doxy2swig.py b/Utilities/ITK/Wrapping/Generators/Doc/itk_doxy2swig.py old mode 100644 new mode 100755 index 859d54fee3b98f630d7c1f15ecbb3f4c12702eaa..cab3fd91a9791d8c8539576fc61041328f379840 --- a/Utilities/ITK/Wrapping/Generators/Doc/itk_doxy2swig.py +++ b/Utilities/ITK/Wrapping/Generators/Doc/itk_doxy2swig.py @@ -7,12 +7,7 @@ Usage: """ -# silently import psyco -try: - import psyco - psyco.full() -except ImportError: - pass +from __future__ import print_function import sys import os @@ -40,7 +35,7 @@ class itkDoxy2SWIG(Doxy2SWIG): def do_compoundname(self, node): self.add_text('\n\n') data = self.cpp_to_swig_name(node.firstChild.data) - # print "=================", data + # print("=================", data) self.add_text('%%feature("docstring") %s "\n'%data) def do_memberdef(self, node): @@ -80,7 +75,7 @@ class itkDoxy2SWIG(Doxy2SWIG): cname = self.cpp_to_swig_name(anc_node[0].firstChild.data) # self.add_text(' %s::%s "\n%s'%(cname, name, defn)) self.add_text(' %s::%s "'%(cname, name)) - # print "***", name, defn + # print("***", name, defn) # make sure that the docstring won't be empty before writing any text current_length = len(self.pieces) @@ -118,7 +113,7 @@ def d2s_dir(in_dir_name, out_swig_i): for swig_name in ls[2:]: output.write(tpl.replace("@[{(]})@", swig_name)) else: - print >> sys.stderr, "Warning: %s does not exist. Ignore it." % xfn + print("Warning: %s does not exist. Ignore it." % xfn, file=sys.stderr) f = open(out_swig_i, 'w') f.write(output.getvalue()) f.close() @@ -128,6 +123,6 @@ def main(in_dir_name, out_swig_i): if __name__ == '__main__': if len(sys.argv) != 3: - print __doc__ + print(__doc__) sys.exit(1) main(sys.argv[1], sys.argv[2]) diff --git a/Utilities/ITK/Wrapping/Generators/GccXML/CMakeLists.txt b/Utilities/ITK/Wrapping/Generators/GccXML/CMakeLists.txt index cd5967795722be0dbca75deedadf62a5f9e55abd..33c44b85fbfd098016ffa4af4b4ac7b7cfae4d73 100644 --- a/Utilities/ITK/Wrapping/Generators/GccXML/CMakeLists.txt +++ b/Utilities/ITK/Wrapping/Generators/GccXML/CMakeLists.txt @@ -2,6 +2,9 @@ option(ITK_USE_SYSTEM_GCCXML "Use system gccxml. If OFF, gccxml is built as an external project." OFF) mark_as_advanced(ITK_USE_SYSTEM_GCCXML) +set(gccxml_url http://itk.org/files/gccxml/gccxml-2014-06-10.tar.gz) +set(gccxml_md5 3ca85731d1d95a9d433eed865d2079c0) + set(gccxml_ep ${CMAKE_CURRENT_BINARY_DIR}/gccxml/bin/gccxml) if(WIN32) set(gccxml_ep "${gccxml_ep}.exe") @@ -25,9 +28,10 @@ else() else() set(test ) endif() - ExternalProject_add(GCC_XML - URL http://itk.org/files/gccxml/gccxml-2013-11-18.tar.bz2 - URL_MD5 3b8f72ae76c6946a954bddf3222c201b + itk_download_attempt_check(GCC_XML) + ExternalProject_Add(GCC_XML + URL ${gccxml_url} + URL_MD5 ${gccxml_md5} PREFIX gccxml CMAKE_ARGS -DCMAKE_CXX_COMPILER:STRING=${CMAKE_CXX_COMPILER} @@ -129,7 +133,6 @@ macro(itk_end_wrap_submodule_gccxml module) -fxml-start=_cable_ -o ${xml_file} ${CONFIG_GCCXML_INC_CONTENTS} - -DCSWIG -DCABLE_CONFIGURATION -DITK_MANUAL_INSTANTIATION ${cxx_file} @@ -142,7 +145,6 @@ macro(itk_end_wrap_submodule_gccxml module) -fxml-start=_cable_ -fxml=${xml_file} --gccxml-gcc-options ${gccxml_inc_file} - -DCSWIG -DCABLE_CONFIGURATION -DITK_MANUAL_INSTANTIATION ${ADDITIONAL_GCC_XML_FLAGS} diff --git a/Utilities/ITK/Wrapping/Generators/Java/itkCommand.i b/Utilities/ITK/Wrapping/Generators/Java/itkCommand.i index 752a84e88707553bc20884a876f1b61eef1c64c7..eb84cd457065b3fca481d494e38ad36f4c10821a 100644 --- a/Utilities/ITK/Wrapping/Generators/Java/itkCommand.i +++ b/Utilities/ITK/Wrapping/Generators/Java/itkCommand.i @@ -1,6 +1,6 @@ // This is needed for a reference in SwigExtras.i // The actuall itkCommand wrapping is done in wrap_ITKCommonBase.cxx by -// CableSwig +// Swig class itkCommand { public: diff --git a/Utilities/ITK/Wrapping/Generators/Java/itkJavaCommand.i b/Utilities/ITK/Wrapping/Generators/Java/itkJavaCommand.i index ad846700124863b74e19954ddce48c31bb67abe2..800a3b8ea3ccefd83a6ec5ae851fe187f7921b16 100644 --- a/Utilities/ITK/Wrapping/Generators/Java/itkJavaCommand.i +++ b/Utilities/ITK/Wrapping/Generators/Java/itkJavaCommand.i @@ -77,7 +77,7 @@ namespace std { %} // import fake itk command -// because itkCommand will be wrapped elsewhere by cableswig +// because itkCommand will be wrapped elsewhere by Swig %import "itkCommand.i" // create an itkJavaCommand that has an Execute method that diff --git a/Utilities/ITK/Wrapping/Generators/Python/CMakeLists.txt b/Utilities/ITK/Wrapping/Generators/Python/CMakeLists.txt index a0c13a4637d9cdb39ed8c62eb9af20c1a2dd343e..0e81d025fb6d1fd3120b75377e13483ecc4a180e 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/CMakeLists.txt +++ b/Utilities/ITK/Wrapping/Generators/Python/CMakeLists.txt @@ -1,8 +1,19 @@ - ############################################################################### -# configure python -find_package(PythonLibs) +# configure python (find PythonInterp first, as of cmake 3.1) find_package(PythonInterp) +find_package(PythonLibs) + +# require at least python 2.6 +if(PYTHON_VERSION_STRING VERSION_LESS 2.6) + message(WARNING "Python version less than 2.6: \"${PYTHON_VERSION_STRING}\".") +endif() + +# check for version mismatch. +if(PYTHONLIBS_FOUND AND PYTHONINTERP_FOUND + AND NOT(PYTHON_VERSION_STRING VERSION_EQUAL PYTHONLIBS_VERSION_STRING)) + message(WARNING "Python executable (\"${PYTHON_VERSION_STRING}\") and library (\"${PYTHONLIBS_VERSION_STRING}\") version mismatch.") +endif() + mark_as_advanced(PYTHON_EXECUTABLE) include_directories(${PYTHON_INCLUDE_PATH}) @@ -17,15 +28,6 @@ set(ITK_WRAP_PYTHON_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}" CACHE INTERNAL "pyt # create the python directory in the classindex dir file(MAKE_DIRECTORY ${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python) -############################################################################### -# should we use autodoc? swig 1.3.37 produce invalid code with autodoc. -# see https://sourceforge.net/tracker/index.php?func=detail&aid=2552048&group_id=1645&atid=101645 -if("${SWIG_VERSION}" STREQUAL "1.3.37") - set(ITK_WRAP_PYTHON_AUTODOC "" CACHE INTERNAL "python autodoc option") -else() - set(ITK_WRAP_PYTHON_AUTODOC -features autodoc=1 CACHE INTERNAL "python autodoc option") -endif() - ############################################################################### # python 2.6 search for the modules in a "64" subdirectory, and don't provide # any obvious way to find that. Create a link 64 -> . to make it find its @@ -120,21 +122,6 @@ if(NOT EXTERNAL_WRAP_ITK_PROJECT) endif() -############################################################################### -# Configure the old style module - -if(NOT EXTERNAL_WRAP_ITK_PROJECT) - set(ITK_WRAP_PYTHON_OLD_STYLE_IMPORTS ) - foreach(lib ${WRAP_ITK_MODULES}) - set(ITK_WRAP_PYTHON_OLD_STYLE_IMPORTS "${ITK_WRAP_PYTHON_OLD_STYLE_IMPORTS}from ${lib}Python import *\n") - endforeach() - configure_file("${ITK_WRAP_PYTHON_SOURCE_DIR}/InsightToolkit.py.in" - "${ITK_WRAP_PYTHON_BINARY_DIR}/InsightToolkit.py" - @ONLY) - WRAP_ITK_BINDINGS_INSTALL(/Python "${ITK_WRAP_PYTHON_BINARY_DIR}/InsightToolkit.py") -endif() - - ############################################################################### # Copy python files for out-of-source builds, and set up install of same. @@ -147,7 +134,7 @@ if(NOT EXTERNAL_WRAP_ITK_PROJECT) itkBase itkTemplate itkTypes - # itkExtras/__init__ + itkExtras itkLazy ) # Done listing files. @@ -162,7 +149,6 @@ if(NOT EXTERNAL_WRAP_ITK_PROJECT) endforeach() else() set(ITK_WRAP_PYTHON_FILES) - add_custom_target(copy_python_files ALL) foreach(file ${ITK_PYTHON_FILES}) set(src "${CMAKE_CURRENT_SOURCE_DIR}/${file}.py") # recall that WRAP_ITK_BUILD_INTDIR expands to nothing if no config types are set, @@ -176,19 +162,13 @@ if(NOT EXTERNAL_WRAP_ITK_PROJECT) # create the directory to avoid loosing case on windows file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${WRAP_ITK_INSTALL_INTDIR}${path}) - add_custom_command(SOURCE ${src} - COMMAND ${CMAKE_COMMAND} - ARGS -E copy ${src} ${copy_tgt} - OUTPUTS ${copy_tgt} - TARGET copy_python_files + add_custom_command(OUTPUT ${copy_tgt} + COMMAND ${CMAKE_COMMAND} -E copy ${src} ${copy_tgt} + DEPENDS ${src} COMMENT "Copying ${file}.py to build dir.") endforeach() + add_custom_target(copy_python_files ALL DEPENDS ${ITK_WRAP_PYTHON_FILES}) - # driver command to make the copy happen. - add_custom_command( - SOURCE copy_python_files - DEPENDS ${ITK_WRAP_PYTHON_FILES} - TARGET copy_python_files) endif() # Install the package python files. @@ -204,6 +184,7 @@ if(CMAKE_CONFIGURATION_TYPES) foreach(config ${CMAKE_CONFIGURATION_TYPES}) set(CONFIG_ITK_WRAP_PYTHON_DIR "${CMAKE_CURRENT_BINARY_DIR}/${config}") + set(CONFIG_ITK_WRAP_LIBRARY_DIR "${ITK_BINARY_DIR}/${ITK_INSTALL_LIBRARY_DIR}/${config}") # SWIG-generated libs and *.py files are sent to ${config} subdir # This assumes that CMAKE_LIBRARY_OUTPUT_DIRECTORY is WrapITK_BINARY_DIR/bin (bad!) @@ -214,6 +195,7 @@ if(CMAKE_CONFIGURATION_TYPES) endforeach() else() set(CONFIG_ITK_WRAP_PYTHON_DIR "${CMAKE_CURRENT_BINARY_DIR}") + set(CONFIG_ITK_WRAP_LIBRARY_DIR "${ITK_BINARY_DIR}/${ITK_INSTALL_LIBRARY_DIR}") configure_file("${CMAKE_CURRENT_SOURCE_DIR}/WrapITK.pth.in" "${CMAKE_CURRENT_BINARY_DIR}/WrapITK.pth" @@ -222,48 +204,28 @@ else() endif() set(CONFIG_ITK_WRAP_PYTHON_DIR "${CMAKE_INSTALL_PREFIX}/lib/ITK-${ITK_VERSION_MAJOR}.${ITK_VERSION_MINOR}/Python") +set(CONFIG_ITK_WRAP_LIBRARY_DIR "${CMAKE_INSTALL_PREFIX}/${ITK_INSTALL_LIBRARY_DIR}") configure_file("${CMAKE_CURRENT_SOURCE_DIR}/WrapITK.pth.in" "${CMAKE_CURRENT_BINARY_DIR}/InstallOnly/WrapITK.pth" @ONLY) if(PYTHON_EXECUTABLE) - file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/det_spp.py "try:\n import distutils.sysconfig; print distutils.sysconfig.get_python_lib(1)\nexcept: pass") + set(python_check "from __future__ import print_function\ntry:\n import distutils.sysconfig\n print(distutils.sysconfig.get_python_lib(1))\nexcept:\n pass") + file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/det_spp.py ${python_check}) execute_process(COMMAND "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_BINARY_DIR}/det_spp.py" OUTPUT_VARIABLE py_spp ERROR_VARIABLE py_spp ) endif() -string(REGEX REPLACE "\\\\" "/" py_spp_nobackslashes "${py_spp}") +string(REGEX REPLACE "\n" "" py_spp_no_newline "${py_spp}") +string(REGEX REPLACE "\\\\" "/" py_spp_nobackslashes "${py_spp_no_newline}") set(PY_SITE_PACKAGES_PATH "${py_spp_nobackslashes}" CACHE PATH "Python site-packages directory to install a .pth file pointing at WrapITK Python modules.") mark_as_advanced(PY_SITE_PACKAGES_PATH) if(PY_SITE_PACKAGES_PATH) INSTALL_AT_ABSOLUTE_PATH(install_wrapitk_compatibility "${PY_SITE_PACKAGES_PATH}" "${CMAKE_CURRENT_BINARY_DIR}/InstallOnly/WrapITK.pth") endif() - - -# # compile python files -# set(PYTHON_MODULES "") -# foreach(m ${WRAP_ITK_MODULES}) -# set(PYTHON_MODULES ${PYTHON_MODULES} _${m}Python) -# endforeach() -# -# add_custom_target(PythonCompile ALL -# ${PYTHON_EXECUTABLE} -# ${PY_SITE_PACKAGES_PATH}/../compileall.py -l -# -d "${CMAKE_INSTALL_PREFIX}/${WRAP_ITK_INSTALL_PREFIX}/lib" -# ${WrapITK_BINARY_DIR}/lib -# -# COMMAND ${PYTHON_EXECUTABLE} -# ${PY_SITE_PACKAGES_PATH}/../compileall.py -l -# -d "${CMAKE_INSTALL_PREFIX}/${WRAP_ITK_INSTALL_PREFIX}/Python" -# ${WrapITK_BINARY_DIR}/Python -# -# DEPENDS SwigRuntimePython ${PYTHON_MODULES} -# ) - - ############################################################################### # Install python stuff for external projects if(NOT EXTERNAL_WRAP_ITK_PROJECT) @@ -280,9 +242,8 @@ if(NOT EXTERNAL_WRAP_ITK_PROJECT) ) endif() - - - +############################################################################### +# Define the wrapping macros macro(itk_wrap_module_python library_name) set(ITK_WRAP_PYTHON_CONFIGURATION_TEMPLATES "") @@ -294,6 +255,77 @@ macro(itk_wrap_module_python library_name) endmacro() +macro(itk_setup_swig_python type base_name interface_file python_file cpp_file doc_file) + + ############################################################################# + # Runs swig to produce the .so and the .py file + # Called by itk_end_wrap_module_python and by itk_end_wrap_submodule_python + # Type will then be either "module" or "submodule" + ############################################################################# + + set(swig_command ${SWIG_EXECUTABLE}) + if(ITK_USE_CCACHE) + set(swig_command ${CCACHE_EXECUTABLE} ${swig_command}) + endif() + + set(_swig_depend) + if(NOT ITK_USE_SYSTEM_SWIG) + # The ExternalProject SWIG install. + set(_swig_depend swig) + endif() + + set(dependencies + "${DEPS}" + "${interface_file}" + "${WRAP_ITK_TYPEDEFS_DIRECTORY}/pyBase.i" + "${_swig_depend}") + + if("${type}" STREQUAL "module") + # Module + set(dependencies ${dependencies} + "${ITK_WRAP_PYTHON_LIBRARY_DEPS}" + "${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python/${WRAPPER_LIBRARY_NAME}_ext.i") + else() + # Submodule + set(dependencies ${dependencies} + "${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python/${base_name}_ext.i" + "${doc_file}") + endif() + + add_custom_command( + OUTPUT ${cpp_file} ${python_file} + COMMAND ${swig_command} -c++ -python -O -features autodoc=1 + -Werror + -w302 # Identifier 'name' redefined (ignored) + -w303 # %extend defined for an undeclared class 'name' (to avoid warning about customization in pyBase.i) + -w312 # Unnamed nested class not currently supported (ignored) + -w314 # 'identifier' is a lang keyword + -w361 # operator! ignored + -w362 # operator= ignored + -w350 # operator new ignored + -w383 # operator++ ignored + -w384 # operator-- ignored + -w389 # operator[] ignored + -w394 # operator new[] ignored + -w395 # operator delete[] ignored + -w467 # Overloaded declaration not supported (no type checking rule for 'type') + -w508 # Declaration of 'name' shadows declaration accessible via operator->(), previous declaration of'declaration' + -w509 # Overloaded method declaration effectively ignored, as it is shadowed by declaration + -o ${cpp_file} + -I${GENERATORS_SRC_DIR} + -I${WRAP_ITK_TYPEDEFS_DIRECTORY}/python + -I${WRAP_ITK_TYPEDEFS_DIRECTORY} + ${WRAP_ITK_SWIG_ARGS_PYTHON} + -outdir ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} + ${interface_file} + WORKING_DIRECTORY ${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python + DEPENDS ${dependencies} + ) + WRAP_ITK_BINDINGS_INSTALL("/Python" "${python_file}") + +endmacro() + + macro(itk_end_wrap_module_python) # Loop over the extra swig input files and add them to the generated files @@ -333,7 +365,6 @@ macro(itk_end_wrap_module_python) "${ITK_WRAP_PYTHON_BINARY_DIR}/Configuration/${WRAPPER_LIBRARY_NAME}Config.py" ) - # create the advanced lib module python file # this file let the final user _not_ use the itk module, but rather # something like "import Base" @@ -343,9 +374,6 @@ macro(itk_end_wrap_module_python) @ONLY) WRAP_ITK_BINDINGS_INSTALL("/Python" "${ITK_WRAP_PYTHON_BINARY_DIR}/${WRAPPER_LIBRARY_NAME}.py") -# add_custom_target(${WRAPPER_LIBRARY_NAME}SwigPython DEPENDS ${cpp_files} ${python_files}) -# add_custom_target(${WRAPPER_LIBRARY_NAME}Python DEPENDS ${modules}) - # create the python customization stuff in the main module # it allow to group the pythons module in a single shared lib, by loading the int # functions of the module. I also import the objects from the submodules in the @@ -360,7 +388,6 @@ macro(itk_end_wrap_module_python) "${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python/${WRAPPER_LIBRARY_NAME}_ext.i" ) - # set some var reused later set(interface_file "${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/${WRAPPER_LIBRARY_NAME}.i") set(lib ${WRAPPER_LIBRARY_NAME}Python) @@ -372,44 +399,10 @@ macro(itk_end_wrap_module_python) set(WRAP_ITK_SWIG_ARGS_PYTHON "" CACHE STRING "Extra user-defined swig arguments to be to the swig executable.") endif() - # and generate c++ code from the main module swig interface. - set(swig_command ${SWIG_EXECUTABLE}) - if(ITK_USE_CCACHE) - set(swig_command ${CCACHE_EXECUTABLE} ${swig_command}) - endif() - - set(_swig_depend) - if(NOT ITK_USE_SYSTEM_SWIG) - # The ExternalProject SWIG install. - set(_swig_depend swig) - endif() - add_custom_command( - OUTPUT ${cpp_file} ${python_file} - COMMAND ${swig_command} -c++ -python -O ${ITK_WRAP_PYTHON_AUTODOC} -Werror -# -fcompact - -w508 -w312 -w314 -w509 -w302 -w362 - -w389 # operator[], to be suppressed later... - -w384 -w383 # operator++ ane operator-- - -w361 # operator! - -w467 # overloaded functions (with typemaps) - -w350 -w394 -w395 # operator new/new[]/delete[] ignored - -w303 # to avoid warning about customization in pyBase.i - -o ${cpp_file} - -I${GENERATORS_SRC_DIR} - -I${WRAP_ITK_TYPEDEFS_DIRECTORY}/python - -I${WRAP_ITK_TYPEDEFS_DIRECTORY} - ${WRAP_ITK_SWIG_ARGS_PYTHON} - -outdir ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} - ${interface_file} - WORKING_DIRECTORY ${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python - DEPENDS ${DEPS} ${ITK_WRAP_PYTHON_LIBRARY_DEPS} ${interface_file} - ${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python/${WRAPPER_LIBRARY_NAME}_ext.i - ${WRAP_ITK_TYPEDEFS_DIRECTORY}/pyBase.i ${_swig_depend} - ) - WRAP_ITK_BINDINGS_INSTALL("/Python" "${python_file}") + # Run swig to produce the .so and the .py file + itk_setup_swig_python("module" ${base_name} ${interface_file} ${python_file} ${cpp_file} "") # build all the c++ files from this module in a common lib - set(lib ${WRAPPER_LIBRARY_NAME}Python) add_library(${lib} MODULE ${cpp_file} ${ITK_WRAP_PYTHON_CXX_FILES} ${WRAPPER_LIBRARY_CXX_SOURCES}) set_target_properties(${lib} PROPERTIES PREFIX "_") # gcc 4.4 complains a lot without this flag when building in release mode @@ -489,7 +482,6 @@ macro(itk_end_wrap_submodule_python group_name) set(ITK_WRAP_PYTHON_SWIG_EXT "%import pyBase.i\n\n${ITK_WRAP_PYTHON_SWIG_EXT}") # create the swig interface for all the groups in the module - # set(interface_file "${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/${base_name}.i") set(lib ${group_name}Python) set(python_file "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/${lib}.py") @@ -508,48 +500,8 @@ macro(itk_end_wrap_submodule_python group_name) set(DEPS ${DEPS} ${${dep}SwigFiles}) endforeach() - # and run swig to produce the c++ file and the .py file - set(swig_command ${SWIG_EXECUTABLE}) - if(ITK_USE_CCACHE) - set(swig_command ${CCACHE_EXECUTABLE} ${swig_command}) - endif() - - if(NOT ITK_USE_SYSTEM_SWIG) - # The ExternalProject SWIG install. - set(_swig_depend swig) - endif() - add_custom_command( - OUTPUT ${cpp_file} ${python_file} - COMMAND ${swig_command} -c++ -python -O ${ITK_WRAP_PYTHON_AUTODOC} -Werror -# -fcompact - -w508 -w312 -w314 -w509 -w302 -w362 - -w389 # operator[], to be suppressed later... - -w384 -w383 # operator++ ane operator-- - -w361 # operator! - -w467 # overloaded functions (with typemaps) - -w350 -w394 -w395 # operator new/new[]/delete[] ignored - -w303 # to avoid warning about customization in pyBase.i - -o ${cpp_file} - -I${GENERATORS_SRC_DIR} - -I${WRAP_ITK_TYPEDEFS_DIRECTORY}/python - -I${WRAP_ITK_TYPEDEFS_DIRECTORY} - ${WRAP_ITK_SWIG_ARGS_PYTHON} - -outdir ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} - ${interface_file} - WORKING_DIRECTORY ${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python - DEPENDS ${DEPS} ${interface_file} - ${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/python/${base_name}_ext.i - ${WRAP_ITK_TYPEDEFS_DIRECTORY}/pyBase.i ${doc_file} ${_swig_depend} - # ${ITK_WRAP_PYTHON_LIBRARY_DEPS} - ) - WRAP_ITK_BINDINGS_INSTALL("/Python" "${python_file}") - -# gcc visibility can't be used without getting errors when passing objects -# from one module to an other -# -# if(CMAKE_COMPILER_IS_GNUCC) -# set_target_properties(${lib} PROPERTIES COMPILE_FLAGS "-fvisibility=hidden") -# endif() + # Run swig to produce the .so and the .py file + itk_setup_swig_python("submodule" ${base_name} ${interface_file} ${python_file} ${cpp_file} "${doc_file}") # add the c++ files which will be generated by the swig command to the # list of python related c++ files, so they can be built at the end @@ -675,8 +627,6 @@ macro(itk_wrap_simple_type_python wrap_class swig_name) set(ext_def "") endif() string(REGEX REPLACE ".*::" "" simple_name "${cpp_name}") -# message("${wrap_class} -- ${swig_name}") -# message("${cpp_name} -- ${template_params} -- ${ext_def}") # must be done first so the typemap are used in the %template commands if("${swig_name}" MATCHES "_Pointer$") @@ -897,7 +847,6 @@ endmacro() if(NOT EXTERNAL_WRAP_ITK_PROJECT) add_subdirectory(Tests) - add_subdirectory(itkExtras) macro(itk_end_wrap_modules_python) add_subdirectory(${ITK_WRAP_PYTHON_SOURCE_DIR}/PyUtils) diff --git a/Utilities/ITK/Wrapping/Generators/Python/InsightToolkit.py.in b/Utilities/ITK/Wrapping/Generators/Python/InsightToolkit.py.in deleted file mode 100644 index ddcabd0a280cd5e164111779df51b5c75e85049d..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Python/InsightToolkit.py.in +++ /dev/null @@ -1,6 +0,0 @@ -import sys, os -sys.path.append(__file__+os.sep+"../lib") -del sys, os - -from ITKPyBase import * -@ITK_WRAP_PYTHON_OLD_STYLE_IMPORTS@ diff --git a/Utilities/ITK/Wrapping/Generators/Python/PyUtils/itkPyCommand.cxx b/Utilities/ITK/Wrapping/Generators/Python/PyUtils/itkPyCommand.cxx index b9bd6bcb6c2a427582aaba4ecddd3927241e6455..254d650d48e9f0ce1f708cec43cb081790b3912c 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/PyUtils/itkPyCommand.cxx +++ b/Utilities/ITK/Wrapping/Generators/Python/PyUtils/itkPyCommand.cxx @@ -80,7 +80,7 @@ void PyCommand::PyExecute() if (!PyCallable_Check(this->m_Object)) { // we throw a standard ITK exception: this makes it possible for - // our standard CableSwig exception handling logic to take this + // our standard Swig exception handling logic to take this // through to the invoking Python process itkExceptionMacro(<<"CommandCallable is not a callable Python object, " <<"or it has not been set."); diff --git a/Utilities/ITK/Wrapping/Generators/Python/PyUtils/itkPyImageFilter.hxx b/Utilities/ITK/Wrapping/Generators/Python/PyUtils/itkPyImageFilter.hxx index 9dafa3ed85618222411a62d634a6ce656157c7bc..b0e63877c67ee85ea4b36982f84d887a5d19b914 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/PyUtils/itkPyImageFilter.hxx +++ b/Utilities/ITK/Wrapping/Generators/Python/PyUtils/itkPyImageFilter.hxx @@ -77,7 +77,7 @@ PyImageFilter<TInputImage,TOutputImage> if (!PyCallable_Check(this->m_Object)) { // we throw a standard ITK exception: this makes it possible for - // our standard CableSwig exception handling logic to take this + // our standard Swig exception handling logic to take this // through to the invoking Python process itkExceptionMacro(<<"CommandCallable is not a callable Python object, " <<"or it has not been set."); diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/AntiAliasBinaryImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/AntiAliasBinaryImageFilter.py index 0b7421be11979dc056892cdcaf8ed35acfae5c17..1090c8cac059d6734e0f73f76c70b63640de44ae 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/AntiAliasBinaryImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/AntiAliasBinaryImageFilter.py @@ -16,26 +16,29 @@ # #==========================================================================*/ +from __future__ import print_function + import itk from sys import argv, stderr, exit itk.auto_progress(2) -if len(argv) < 3 : - print >> stderr, """Missing Parameters -Usage: AntiAliasBinaryImageFilter inputImage outputImage [RMS] [numberOfIterations]""" - exit(1) +if len(argv) < 3: + print(( + "Missing Parameters \n Usage: AntiAliasBinaryImageFilter" + " inputImage outputImage [RMS] [numberOfIterations]"), file=stderr) + exit(1) -inputFilename = argv[1] +inputFilename = argv[1] outputFilename = argv[2] maximumRMSError = 0.01 numberOfIterations = 50 -if len(argv) > 3 : - maximumRMSError = float( argv[3] ) +if len(argv) > 3: + maximumRMSError = float(argv[3]) -if len(argv) > 4 : - numberOfIterations = int( argv[4] ) +if len(argv) > 4: + numberOfIterations = int(argv[4]) CharPixelType = itk.UC @@ -45,18 +48,16 @@ Dimension = 3 CharImageType = itk.Image[CharPixelType, Dimension] RealImageType = itk.Image[RealPixelType, Dimension] -ReaderType = itk.ImageFileReader[ CharImageType ] -WriterType = itk.ImageFileWriter[ CharImageType ] - - +ReaderType = itk.ImageFileReader[CharImageType] +WriterType = itk.ImageFileWriter[CharImageType] -CastToRealFilterType = itk.CastImageFilter[ CharImageType, RealImageType] +CastToRealFilterType = itk.CastImageFilter[CharImageType, RealImageType] -RescaleFilter = itk.RescaleIntensityImageFilter[RealImageType, CharImageType ] +RescaleFilter = itk.RescaleIntensityImageFilter[RealImageType, CharImageType] - -AntiAliasFilterType = itk.AntiAliasBinaryImageFilter[RealImageType, RealImageType] +antiAliasFilter = itk.AntiAliasBinaryImageFilter[RealImageType, RealImageType] +antiAliasFilter = antiAliasFilter.New() reader = ReaderType.New() writer = WriterType.New() @@ -64,23 +65,21 @@ writer = WriterType.New() toReal = CastToRealFilterType.New() rescale = RescaleFilter.New() -antiAliasFilter = AntiAliasFilterType.New() - -reader.SetFileName( inputFilename ) -writer.SetFileName( outputFilename ) +reader.SetFileName(inputFilename) +writer.SetFileName(outputFilename) -rescale.SetOutputMinimum( 0 ) -rescale.SetOutputMaximum( 255 ) +rescale.SetOutputMinimum(0) +rescale.SetOutputMaximum(255) -toReal.SetInput( reader.GetOutput() ) +toReal.SetInput(reader.GetOutput()) -antiAliasFilter.SetInput( toReal.GetOutput() ) +antiAliasFilter.SetInput(toReal.GetOutput()) -antiAliasFilter.SetMaximumRMSError( maximumRMSError ) -antiAliasFilter.SetNumberOfIterations( numberOfIterations ) -antiAliasFilter.SetNumberOfLayers( 2 ) +antiAliasFilter.SetMaximumRMSError(maximumRMSError) +antiAliasFilter.SetNumberOfIterations(numberOfIterations) +antiAliasFilter.SetNumberOfLayers(2) -rescale.SetInput( antiAliasFilter.GetOutput() ) -writer.SetInput( rescale.GetOutput() ) +rescale.SetInput(antiAliasFilter.GetOutput()) +writer.SetInput(rescale.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryDilateImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryDilateImageFilter.py index 6a7f1581320f5f1cdfa4b9ec664e6ed5da5f0e27..3b2c5fade1098ee2efbaaec9ac087f3a908c0330 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryDilateImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryDilateImageFilter.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python + #========================================================================== # # Copyright Insight Software Consortium @@ -17,21 +19,39 @@ #==========================================================================*/ # -# Example on the use of the BinaryDilateImageFilter +# Test BinaryDilateImageFilter # +import sys import itk -from sys import argv itk.auto_progress(2) -dim = 2 -IType = itk.Image[itk.UC, dim] +inputImage = sys.argv[1] +outputImage = sys.argv[2] +radiusValue = int(sys.argv[3]) + +PixelType = itk.UC +Dimension = 2 + +ImageType = itk.Image[PixelType, Dimension] + +ReaderType = itk.ImageFileReader[ImageType] +reader = ReaderType.New() +reader.SetFileName(inputImage) + +StructuringElementType = itk.FlatStructuringElement[Dimension] +structuringElement = StructuringElementType.Ball(radiusValue) + +DilateFilterType = itk.BinaryDilateImageFilter[ + ImageType, ImageType, StructuringElementType] +dilateFilter = DilateFilterType.New() +dilateFilter.SetInput(reader.GetOutput()) +dilateFilter.SetKernel(structuringElement) +dilateFilter.SetDilateValue(200) -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -kernel = itk.strel(dim, 5) -filter = itk.BinaryDilateImageFilter[IType, IType, kernel].New( reader, - DilateValue=200, - Kernel=kernel ) -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +WriterType = itk.ImageFileWriter[ImageType] +writer = WriterType.New() +writer.SetFileName(outputImage) +writer.SetInput(dilateFilter.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryErodeImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryErodeImageFilter.py index 49fdc029008d31075fcabfef85ce5de22bdf57a2..17a36e8ee51f2f9ea7162a7f1cc7419bff1a6425 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryErodeImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryErodeImageFilter.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python + #========================================================================== # # Copyright Insight Software Consortium @@ -17,21 +19,39 @@ #==========================================================================*/ # -# Example on the use of the BinaryErodeImageFilter +# Test BinaryDilateImageFilter # +import sys import itk -from sys import argv itk.auto_progress(2) -dim = 2 -IType = itk.Image[itk.UC, dim] +inputImage = sys.argv[1] +outputImage = sys.argv[2] +radiusValue = int(sys.argv[3]) + +PixelType = itk.UC +Dimension = 2 + +ImageType = itk.Image[PixelType, Dimension] + +ReaderType = itk.ImageFileReader[ImageType] +reader = ReaderType.New() +reader.SetFileName(inputImage) + +StructuringElementType = itk.FlatStructuringElement[Dimension] +structuringElement = StructuringElementType.Ball(radiusValue) + +ErodeFilterType = itk.BinaryErodeImageFilter[ + ImageType, ImageType, StructuringElementType] +erodeFilter = ErodeFilterType.New() +erodeFilter.SetInput(reader.GetOutput()) +erodeFilter.SetKernel(structuringElement) +erodeFilter.SetErodeValue(200) -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -kernel = itk.strel(dim, 5) -filter = itk.BinaryErodeImageFilter[IType, IType, kernel].New( reader, - ErodeValue=200, - Kernel=kernel ) -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +WriterType = itk.ImageFileWriter[ImageType] +writer = WriterType.New() +writer.SetFileName(outputImage) +writer.SetInput(erodeFilter.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryThresholdImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryThresholdImageFilter.py index 22adc12dabefe613ab460ebd8ee80a783e32e212..ef7f5fa322c8ef70bbbdc8fb1311fd964cca6900 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryThresholdImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/BinaryThresholdImageFilter.py @@ -17,22 +17,42 @@ #==========================================================================*/ # -# Example on the use of the BinaryThresholdImageFilter +# Test BinaryThresholdImageFilter # +import sys import itk -from sys import argv itk.auto_progress(2) -dim = 2 -IType = itk.Image[itk.UC, dim] +inputImage = sys.argv[1] +outputImage = sys.argv[2] +lowerThreshold = int(sys.argv[3]) +upperThreshold = int(sys.argv[4]) +outsideValue = int(sys.argv[5]) +insideValue = int(sys.argv[6]) -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -filter = itk.BinaryThresholdImageFilter[IType, IType].New( reader, - LowerThreshold=eval( argv[3] ), - UpperThreshold=eval( argv[4] ), - OutsideValue=eval( argv[5] ), - InsideValue=eval( argv[6] )) -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +PixelType = itk.UC +Dimension = 2 + +ImageType = itk.Image[PixelType, Dimension] + +ReaderType = itk.ImageFileReader[ImageType] +reader = ReaderType.New() +reader.SetFileName(inputImage) + +FilterType = itk.BinaryThresholdImageFilter[ImageType, ImageType] +thresholdFilter = FilterType.New() + +thresholdFilter.SetInput(reader.GetOutput()) + +thresholdFilter.SetLowerThreshold(lowerThreshold) +thresholdFilter.SetUpperThreshold(upperThreshold) +thresholdFilter.SetOutsideValue(outsideValue) +thresholdFilter.SetInsideValue(insideValue) + +WriterType = itk.ImageFileWriter[ImageType] +writer = WriterType.New() +writer.SetFileName(outputImage) +writer.SetInput(thresholdFilter.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/BoxGrayscaleDilateImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/BoxGrayscaleDilateImageFilter.py index 58ed5f7f4c2534897d8519de8543693b2afc93a4..c96a560fa83758df95187b8b25e3168bd113ac80 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/BoxGrayscaleDilateImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/BoxGrayscaleDilateImageFilter.py @@ -28,10 +28,10 @@ itk.auto_progress(2) dim = 2 IType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) kernel = itk.FlatStructuringElement[dim].Box(5) -filter = itk.GrayscaleDilateImageFilter[IType, IType, kernel].New( reader, - Kernel=kernel ) -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +grayscaleFilter = itk.GrayscaleDilateImageFilter[IType, IType, kernel] +grayscaleFilter = grayscaleFilter.New(reader, Kernel=kernel) +writer = itk.ImageFileWriter[IType].New(grayscaleFilter, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/CMakeLists.txt b/Utilities/ITK/Wrapping/Generators/Python/Tests/CMakeLists.txt index 2dbf0912fde5e1ceb330f803110e3a458b4249ed..051220778884cd0de665dc8cf65340d3344b7dd4 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/CMakeLists.txt +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/CMakeLists.txt @@ -77,12 +77,14 @@ if(ITK_WRAP_unsigned_char AND WRAP_2) add_python_test(PythonModuleToModule ${CMAKE_CURRENT_SOURCE_DIR}/module2module.py DATA{${WrapITK_SOURCE_DIR}/images/cthead1.png} + 5 ) add_python_test(PythonBinaryDilateImageFilter ${CMAKE_CURRENT_SOURCE_DIR}/BinaryDilateImageFilter.py DATA{${WrapITK_SOURCE_DIR}/images/2th_cthead1.png} BinaryDilateImageFilter.png + 5 --compare BinaryDilateImageFilter.png DATA{${WrapITK_SOURCE_DIR}/images/BinaryDilateImageFilter.png} ) @@ -90,6 +92,7 @@ if(ITK_WRAP_unsigned_char AND WRAP_2) ${CMAKE_CURRENT_SOURCE_DIR}/BinaryErodeImageFilter.py DATA{${WrapITK_SOURCE_DIR}/images/2th_cthead1.png} BinaryErodeImageFilter.png + 5 --compare BinaryErodeImageFilter.png DATA{${WrapITK_SOURCE_DIR}/images/BinaryErodeImageFilter.png} ) @@ -113,6 +116,7 @@ if(ITK_WRAP_unsigned_char AND WRAP_2) ${CMAKE_CURRENT_SOURCE_DIR}/GrayscaleDilateImageFilter.py DATA{${WrapITK_SOURCE_DIR}/images/cthead1.png} GrayscaleDilateImageFilter.png + 5 --compare GrayscaleDilateImageFilter.png DATA{${WrapITK_SOURCE_DIR}/images/GrayscaleDilateImageFilter.png} ) @@ -135,6 +139,7 @@ if(ITK_WRAP_unsigned_char AND WRAP_2) ${CMAKE_CURRENT_SOURCE_DIR}/GrayscaleErodeImageFilter.py DATA{${WrapITK_SOURCE_DIR}/images/cthead1.png} GrayscaleErodeImageFilter.png + 5 --compare GrayscaleErodeImageFilter.png DATA{${WrapITK_SOURCE_DIR}/images/GrayscaleErodeImageFilter.png} ) @@ -417,6 +422,11 @@ if(ITK_WRAP_float AND WRAP_2) SpatialObject.png ) + add_python_test(PythonReadDicomAndReadTag + ${CMAKE_CURRENT_SOURCE_DIR}/ReadDicomAndReadTag.py + DATA{${ITK_DATA_ROOT}/Input/DicomSeries/,REGEX:Image[0-9]+.dcm} + ) + endif() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/CannyEdgeDetectionImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/CannyEdgeDetectionImageFilter.py index 36d2f7bff2700ff508ddcd138ae4ff597ca19b07..1913e6758a6852f651a214803ccea5f8364dd88b 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/CannyEdgeDetectionImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/CannyEdgeDetectionImageFilter.py @@ -20,20 +20,29 @@ # Example on the use of the CannyEdgeDetectionImageFilter # +from __future__ import print_function + import itk from sys import argv, stderr, exit itk.auto_progress(2) if len(argv) < 3: - print >> stderr, "Usage: CannyEdgeDetectionImageFilter.py inputImage outputImage [variance]" - exit(1) + print(( + "Usage: CannyEdgeDetectionImageFilter.py inputImage outputImage " + "[variance]"), file=stderr) + exit(1) variance = 2.0 if len(argv) > 3: - variance = float( argv[3] ) - print variance + variance = float(argv[3]) + print(variance) -reader = itk.ImageFileReader.IF2.New( FileName=argv[1] ) -filter = itk.CannyEdgeDetectionImageFilter.IF2IF2.New( reader, Variance=variance ) -outputCast = itk.RescaleIntensityImageFilter.IF2IUC2.New( filter, OutputMinimum=0, OutputMaximum=255 ) -itk.write( outputCast, argv[2] ) +reader = itk.ImageFileReader.IF2.New(FileName=argv[1]) +filter = itk.CannyEdgeDetectionImageFilter.IF2IF2.New( + reader, + Variance=variance) +outputCast = itk.RescaleIntensityImageFilter.IF2IUC2.New( + filter, + OutputMinimum=0, + OutputMaximum=255) +itk.write(outputCast, argv[2]) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/CastImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/CastImageFilter.py index 0a2d146d53bf96f1d97c0d153f6ad1b99dc67fa4..6a12b73065e2e25f71e769dc2bfc2a01620e551c 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/CastImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/CastImageFilter.py @@ -28,8 +28,8 @@ dim = 2 IType = itk.Image[itk.F, dim] OIType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -filter = itk.CastImageFilter[IType, OIType].New( reader ) -writer = itk.ImageFileWriter[OIType].New( filter, FileName=argv[2] ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +filter = itk.CastImageFilter[IType, OIType].New(reader) +writer = itk.ImageFileWriter[OIType].New(filter, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/CurvatureAnisotropicDiffusionImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/CurvatureAnisotropicDiffusionImageFilter.py index 8a88ae6aec080ebb846cb876338f1d276207e5b2..11b7097aa7477d62c88b82e6df7540adec9484b8 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/CurvatureAnisotropicDiffusionImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/CurvatureAnisotropicDiffusionImageFilter.py @@ -29,14 +29,17 @@ dim = 2 IType = itk.Image[itk.F, dim] OIType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -filter = itk.CurvatureAnisotropicDiffusionImageFilter[IType, IType].New( reader, - NumberOfIterations=eval( argv[3] ), - TimeStep=eval( argv[4] ), - ConductanceParameter=eval( argv[5] ) ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +filter = itk.CurvatureAnisotropicDiffusionImageFilter[IType, IType].New( + reader, + NumberOfIterations=eval( + argv[ + 3]), + TimeStep=eval(argv[4]), + ConductanceParameter=eval(argv[5])) cast = itk.RescaleIntensityImageFilter[IType, OIType].New(filter, - OutputMinimum=0, - OutputMaximum=255) -writer = itk.ImageFileWriter[OIType].New( cast, FileName=argv[2] ) + OutputMinimum=0, + OutputMaximum=255) +writer = itk.ImageFileWriter[OIType].New(cast, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/CurvatureFlowImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/CurvatureFlowImageFilter.py index beafb7df79a52521b16702be805b239158ae2a35..52f03f1a17880fb8c2c5eb29ec8c5986cb7121e2 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/CurvatureFlowImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/CurvatureFlowImageFilter.py @@ -21,7 +21,6 @@ # - import itk from sys import argv itk.auto_progress(2) @@ -30,13 +29,11 @@ dim = 2 IType = itk.Image[itk.F, dim] OIType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -filter = itk.CurvatureFlowImageFilter[IType, IType].New( reader, - NumberOfIterations=eval( argv[3] ), - TimeStep=eval( argv[4] ) ) -cast = itk.RescaleIntensityImageFilter[IType, OIType].New(filter, - OutputMinimum=0, - OutputMaximum=255) -writer = itk.ImageFileWriter[OIType].New( cast, FileName=argv[2] ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +filt = itk.CurvatureFlowImageFilter[IType, IType].New( + reader, NumberOfIterations=eval(argv[3]), TimeStep=eval(argv[4])) +cast = itk.RescaleIntensityImageFilter[IType, OIType].New( + filt, OutputMinimum=0, OutputMaximum=255) +writer = itk.ImageFileWriter[OIType].New(cast, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/FFTImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/FFTImageFilter.py index a3abe64f9adbacc281ad95b48f1ac370d64f60ff..8611802250d2066b2ad212a3c4e6c262bc34d8ae 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/FFTImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/FFTImageFilter.py @@ -27,26 +27,37 @@ itk.auto_progress(2) dim = 2 PixelType = itk.F ImageType = itk.Image[PixelType, dim] -ComplexImageType = itk.Image[itk.complex[PixelType], dim] +ComplexImageType = itk.Image[itk.complex[PixelType], dim] -reader = itk.ImageFileReader[ImageType].New( FileName=argv[1] ) +reader = itk.ImageFileReader[ImageType].New(FileName=argv[1]) fftFilter = itk.ForwardFFTImageFilter[ImageType, ComplexImageType].New(reader) # why this Update() ? fftFilter.Update() -complexWriter = itk.ImageFileWriter[ComplexImageType].New( fftFilter, FileName="complexImage.mhd" ) +complexWriter = itk.ImageFileWriter[ComplexImageType].New( + fftFilter, + FileName="complexImage.mhd") complexWriter.Update() -realFilter = itk.ComplexToRealImageFilter[ComplexImageType, ImageType].New( fftFilter ) +realFilter = itk.ComplexToRealImageFilter[ + ComplexImageType, ImageType].New(fftFilter) WritePixelType = itk.UC WriteImageType = itk.Image[WritePixelType, dim] -intensityRescaler = itk.RescaleIntensityImageFilter[ImageType, WriteImageType].New( realFilter, OutputMinimum=0, OutputMaximum=255 ) -writer = itk.ImageFileWriter[WriteImageType].New( intensityRescaler, FileName=argv[2] ) +intensityRescaler = itk.RescaleIntensityImageFilter[ + ImageType, + WriteImageType].New( + realFilter, + OutputMinimum=0, + OutputMaximum=255) +writer = itk.ImageFileWriter[WriteImageType].New( + intensityRescaler, + FileName=argv[2]) writer.Update() -imaginaryFilter = itk.ComplexToImaginaryImageFilter[ComplexImageType, ImageType].New( fftFilter ) -intensityRescaler.SetInput( imaginaryFilter.GetOutput() ) -writer.SetFileName( argv[3] ) +imaginaryFilter = itk.ComplexToImaginaryImageFilter[ + ComplexImageType, ImageType].New(fftFilter) +intensityRescaler.SetInput(imaginaryFilter.GetOutput()) +writer.SetFileName(argv[3]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/FastMarchingImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/FastMarchingImageFilter.py index f131b010fc98b4d709efe2290cb0cf7f8b52db57..59aeea6f246a08da3bdcb5443a9c5151c471b01d 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/FastMarchingImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/FastMarchingImageFilter.py @@ -35,111 +35,116 @@ # OUTPUTS: {FastMarchingFilterOutput3.png} # ARGUMENTS: 40 90 0.5 -0.3 2.0 200 100 +from __future__ import print_function + import itk from sys import argv, stderr, exit -if( len(argv) < 10 ): - print >> stderr, """Missing Parameters -Usage: FastMarchingImageFilter.py inputImage outputImage seedX seedY Sigma SigmoidAlpha SigmoidBeta TimeThreshold StoppingValue""" - exit(1) +if(len(argv) < 10): + print(( + "Missing Parameters \n Usage: FastMarchingImageFilter.py inputImage " + "outputImage seedX seedY Sigma SigmoidAlpha SigmoidBeta TimeThreshold " + "StoppingValue"), file=stderr) + exit(1) itk.auto_progress(2) InternalPixelType = itk.F Dimension = 2 -InternalImageType = itk.Image[ InternalPixelType, Dimension ] +InternalImageType = itk.Image[InternalPixelType, Dimension] OutputPixelType = itk.UC -OutputImageType = itk.Image[ OutputPixelType, Dimension ] +OutputImageType = itk.Image[OutputPixelType, Dimension] -thresholder = itk.BinaryThresholdImageFilter[ InternalImageType, OutputImageType ].New(); +thresholder = itk.BinaryThresholdImageFilter[ + InternalImageType, OutputImageType].New() -timeThreshold = float( argv[8] ) -thresholder.SetLowerThreshold( 0.0 ) -thresholder.SetUpperThreshold( timeThreshold ) +timeThreshold = float(argv[8]) +thresholder.SetLowerThreshold(0.0) +thresholder.SetUpperThreshold(timeThreshold) -thresholder.SetOutsideValue( 0 ) -thresholder.SetInsideValue( 255 ) +thresholder.SetOutsideValue(0) +thresholder.SetInsideValue(255) -ReaderType = itk.ImageFileReader[ InternalImageType ] -WriterType = itk.ImageFileWriter[ OutputImageType ] +ReaderType = itk.ImageFileReader[InternalImageType] +WriterType = itk.ImageFileWriter[OutputImageType] reader = ReaderType.New() writer = WriterType.New() -reader.SetFileName( argv[1] ) -writer.SetFileName( argv[2] ) +reader.SetFileName(argv[1]) +writer.SetFileName(argv[2]) CastFilterType = itk.RescaleIntensityImageFilter[ - InternalImageType, - OutputImageType ] + InternalImageType, + OutputImageType] SmoothingFilterType = itk.CurvatureAnisotropicDiffusionImageFilter[ - InternalImageType, - InternalImageType ] + InternalImageType, + InternalImageType] smoothing = SmoothingFilterType.New() GradientFilterType = itk.GradientMagnitudeRecursiveGaussianImageFilter[ - InternalImageType, - InternalImageType ] + InternalImageType, + InternalImageType] SigmoidFilterType = itk.SigmoidImageFilter[ - InternalImageType, - InternalImageType ] + InternalImageType, + InternalImageType] -gradientMagnitude = GradientFilterType.New(); +gradientMagnitude = GradientFilterType.New() sigmoid = SigmoidFilterType.New() -sigmoid.SetOutputMinimum( 0.0 ) -sigmoid.SetOutputMaximum( 1.0 ) +sigmoid.SetOutputMinimum(0.0) +sigmoid.SetOutputMaximum(1.0) -FastMarchingFilterType = itk.FastMarchingImageFilter[ InternalImageType, - InternalImageType ] +FastMarchingFilterType = itk.FastMarchingImageFilter[InternalImageType, + InternalImageType] fastMarching = FastMarchingFilterType.New() -smoothing.SetInput( reader.GetOutput() ) -gradientMagnitude.SetInput( smoothing.GetOutput() ) -sigmoid.SetInput( gradientMagnitude.GetOutput() ) -fastMarching.SetInput( sigmoid.GetOutput() ) -thresholder.SetInput( fastMarching.GetOutput() ) -writer.SetInput( thresholder.GetOutput() ) +smoothing.SetInput(reader.GetOutput()) +gradientMagnitude.SetInput(smoothing.GetOutput()) +sigmoid.SetInput(gradientMagnitude.GetOutput()) +fastMarching.SetInput(sigmoid.GetOutput()) +thresholder.SetInput(fastMarching.GetOutput()) +writer.SetInput(thresholder.GetOutput()) -smoothing.SetTimeStep( 0.125 ) -smoothing.SetNumberOfIterations( 5 ) -smoothing.SetConductanceParameter( 9.0 ) +smoothing.SetTimeStep(0.125) +smoothing.SetNumberOfIterations(5) +smoothing.SetConductanceParameter(9.0) -sigma = float( argv[5] ) +sigma = float(argv[5]) -gradientMagnitude.SetSigma( sigma ) +gradientMagnitude.SetSigma(sigma) -alpha = float( argv[6] ) -beta = float( argv[7] ) +alpha = float(argv[6]) +beta = float(argv[7]) -sigmoid.SetAlpha( alpha ) -sigmoid.SetBeta( beta ) +sigmoid.SetAlpha(alpha) +sigmoid.SetBeta(beta) NodeType = itk.LevelSetNode[InternalPixelType, Dimension] NodeContainer = itk.VectorContainer[itk.UI, NodeType] seeds = NodeContainer.New() -seedPosition = [int( argv[3] ), int( argv[4] )] +seedPosition = [int(argv[3]), int(argv[4])] node = NodeType() seedValue = 0.0 -node.SetValue( seedValue ) -node.SetIndex( seedPosition ) +node.SetValue(seedValue) +node.SetIndex(seedPosition) -seeds.Initialize(); -seeds.InsertElement( 0, node ) +seeds.Initialize() +seeds.InsertElement(0, node) -fastMarching.SetTrialPoints( seeds ); +fastMarching.SetTrialPoints(seeds) caster1 = CastFilterType.New() caster2 = CastFilterType.New() @@ -151,40 +156,40 @@ writer2 = WriterType.New() writer3 = WriterType.New() writer4 = WriterType.New() -caster1.SetInput( smoothing.GetOutput() ) -writer1.SetInput( caster1.GetOutput() ) +caster1.SetInput(smoothing.GetOutput()) +writer1.SetInput(caster1.GetOutput()) writer1.SetFileName("FastMarchingFilterOutput1.png") -caster1.SetOutputMinimum( 0 ) -caster1.SetOutputMaximum( 255 ) +caster1.SetOutputMinimum(0) +caster1.SetOutputMaximum(255) writer1.Update() -caster2.SetInput( gradientMagnitude.GetOutput() ) -writer2.SetInput( caster2.GetOutput() ) +caster2.SetInput(gradientMagnitude.GetOutput()) +writer2.SetInput(caster2.GetOutput()) writer2.SetFileName("FastMarchingFilterOutput2.png") -caster2.SetOutputMinimum( 0 ) -caster2.SetOutputMaximum( 255 ) +caster2.SetOutputMinimum(0) +caster2.SetOutputMaximum(255) writer2.Update() -caster3.SetInput( sigmoid.GetOutput() ) -writer3.SetInput( caster3.GetOutput() ) +caster3.SetInput(sigmoid.GetOutput()) +writer3.SetInput(caster3.GetOutput()) writer3.SetFileName("FastMarchingFilterOutput3.png") -caster3.SetOutputMinimum( 0 ) -caster3.SetOutputMaximum( 255 ) +caster3.SetOutputMinimum(0) +caster3.SetOutputMaximum(255) writer3.Update() -caster4.SetInput( fastMarching.GetOutput() ) -writer4.SetInput( caster4.GetOutput() ) +caster4.SetInput(fastMarching.GetOutput()) +writer4.SetInput(caster4.GetOutput()) writer4.SetFileName("FastMarchingFilterOutput4.png") -caster4.SetOutputMinimum( 0 ) -caster4.SetOutputMaximum( 255 ) +caster4.SetOutputMinimum(0) +caster4.SetOutputMaximum(255) fastMarching.SetOutputSize( - reader.GetOutput().GetBufferedRegion().GetSize() ) + reader.GetOutput().GetBufferedRegion().GetSize()) -stoppingTime = float( argv[9] ) +stoppingTime = float(argv[9]) -fastMarching.SetStoppingValue( stoppingTime ) +fastMarching.SetStoppingValue(stoppingTime) writer.Update() @@ -192,19 +197,19 @@ writer.Update() writer4.Update() -InternalWriterType = itk.ImageFileWriter[ InternalImageType ] +InternalWriterType = itk.ImageFileWriter[InternalImageType] mapWriter = InternalWriterType.New() -mapWriter.SetInput( fastMarching.GetOutput() ) +mapWriter.SetInput(fastMarching.GetOutput()) mapWriter.SetFileName("FastMarchingFilterOutput4.mha") mapWriter.Update() speedWriter = InternalWriterType.New() -speedWriter.SetInput( sigmoid.GetOutput() ) +speedWriter.SetInput(sigmoid.GetOutput()) speedWriter.SetFileName("FastMarchingFilterOutput3.mha") speedWriter.Update() gradientWriter = InternalWriterType.New() -gradientWriter.SetInput( gradientMagnitude.GetOutput() ) +gradientWriter.SetInput(gradientMagnitude.GetOutput()) gradientWriter.SetFileName("FastMarchingFilterOutput2.mha") gradientWriter.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/FlatStructuringElement.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/FlatStructuringElement.py index 7369f037084a3962ddf0eee3df3221a505a6fe8d..26b6c46b810f47c97f797ab06251d3a40d42a0e2 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/FlatStructuringElement.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/FlatStructuringElement.py @@ -16,35 +16,37 @@ # #==========================================================================*/ +from __future__ import print_function + import itk from sys import argv, exit itk.auto_progress(2) if argv[2] == "Ball": - print "Ball" - strel = itk.FlatStructuringElement[2].Ball( int( argv[3] ) ) + print("Ball") + strel = itk.FlatStructuringElement[2].Ball(int(argv[3])) elif argv[2] == "Box": - print "Box" - strel = itk.FlatStructuringElement[2].Box( int( argv[3] ) ) + print("Box") + strel = itk.FlatStructuringElement[2].Box(int(argv[3])) elif argv[2] == "FromImage": - print "FromImage" - reader = itk.ImageFileReader.IUC2.New( FileName=argv[3] ) - strel = itk.FlatStructuringElement[2].FromImageUC( reader.GetOutput() ) + print("FromImage") + reader = itk.ImageFileReader.IUC2.New(FileName=argv[3]) + strel = itk.FlatStructuringElement[2].FromImageUC(reader.GetOutput()) else: - print "invalid arguement: " + argv[2] - exit(1) + print("invalid arguement: " + argv[2]) + exit(1) img = strel.GetImageUC() -size = itk.size( img ) +size = itk.size(img) for y in range(0, size.GetElement(1)): - for x in range(0, size.GetElement(0)): - if img.GetPixel( [x, y] ): - print "X", - else: - print " ", - print "\n", + for x in range(0, size.GetElement(0)): + if img.GetPixel([x, y]): + print("X") + else: + print(" ") + print("\n") -itk.write( img, argv[1] ) +itk.write(img, argv[1]) # writer = itk.ImageFileWriter.IUC2.New(FileName=argv[1], Input=img ) # itk.echo(writer) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/GeodesicActiveContourImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/GeodesicActiveContourImageFilter.py index e34bbacc8446efce7c3790f7edd53f1be2da069e..f310a6ea2641e40e5e86afcc5e33fe3abfe96f8a 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/GeodesicActiveContourImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/GeodesicActiveContourImageFilter.py @@ -18,7 +18,8 @@ # GeodesicActiveContourImageFilter.py # Translated by Charl P. Botha <http://cpbotha.net/> from the cxx original. -# $Id: GeodesicActiveContourImageFilter.py,v 1.1 2006/09/06 20:58:42 glehmann Exp $ +# $Id: GeodesicActiveContourImageFilter.py,v 1.1 2006/09/06 20:58:42 glehmann +# Exp $ # example runs: # ------------ @@ -35,10 +36,13 @@ # See the ITK Software Guide, section 9.3.3 "Geodesic Active Contours # Segmentation" as well as the CXX example for more comments. +from __future__ import print_function + import itk from sys import argv, stderr itk.auto_progress(2) + def main(): if len(argv) < 10: errMsg = "Missing parameters\n" \ @@ -48,7 +52,7 @@ def main(): " Sigma SigmoidAlpha SigmoidBeta\n" \ " PropagationScaling\n" - print >> stderr, errMsg + print(errMsg, file=stderr) return # We're going to build the following pipelines: @@ -72,19 +76,26 @@ def main(): # needed to give the size to the fastmarching filter reader.Update() - smoothing = itk.CurvatureAnisotropicDiffusionImageFilter[InternalImageType, InternalImageType].New(reader, - TimeStep=0.125, - NumberOfIterations=5, - ConductanceParameter=9.0) - - gradientMagnitude = itk.GradientMagnitudeRecursiveGaussianImageFilter[InternalImageType, InternalImageType].New(smoothing, - Sigma=float(argv[6])) - - sigmoid = itk.SigmoidImageFilter[InternalImageType, InternalImageType].New(gradientMagnitude, - OutputMinimum=0.0, - OutputMaximum=1.1, - Alpha=float(argv[7]), - Beta=float(argv[8])) + smoothing = itk.CurvatureAnisotropicDiffusionImageFilter[ + InternalImageType, + InternalImageType].New( + reader, + TimeStep=0.125, + NumberOfIterations=5, + ConductanceParameter=9.0) + + gradientMagnitude = itk.GradientMagnitudeRecursiveGaussianImageFilter[ + InternalImageType, + InternalImageType].New( + smoothing, + Sigma=float(argv[6])) + + sigmoid = itk.SigmoidImageFilter[InternalImageType, InternalImageType].New( + gradientMagnitude, + OutputMinimum=0.0, + OutputMaximum=1.1, + Alpha=float(argv[7]), + Beta=float(argv[8])) seedPosition = itk.Index[2]() seedPosition.SetElement(0, int(argv[3])) @@ -94,67 +105,83 @@ def main(): node.SetValue(-float(argv[5])) node.SetIndex(seedPosition) - seeds = itk.VectorContainer[itk.UI, itk.LevelSetNode[InternalPixelType, Dimension]].New() + seeds = itk.VectorContainer[ + itk.UI, itk.LevelSetNode[InternalPixelType, Dimension]].New() seeds.Initialize() seeds.InsertElement(0, node) - fastMarching = itk.FastMarchingImageFilter[InternalImageType, InternalImageType].New(sigmoid, - TrialPoints=seeds, - SpeedConstant=1.0, - OutputSize=reader.GetOutput().GetBufferedRegion().GetSize() ) - - - geodesicActiveContour = itk.GeodesicActiveContourLevelSetImageFilter[InternalImageType, InternalImageType, InternalPixelType].New(fastMarching, - FeatureImage=sigmoid.GetOutput(), # it is required to use the explicitly the FeatureImage - itk segfault without that :-( - PropagationScaling=float(argv[9]), - CurvatureScaling=1.0, - AdvectionScaling=1.0, - MaximumRMSError=0.02, - NumberOfIterations=800 - ) - - thresholder = itk.BinaryThresholdImageFilter[InternalImageType, OutputImageType].New(geodesicActiveContour, - LowerThreshold=-1000, - UpperThreshold=0, - OutsideValue=0, - InsideValue=255) - - writer = itk.ImageFileWriter[OutputImageType].New(thresholder, FileName=argv[2]) - - - + fastMarching = itk.FastMarchingImageFilter[ + InternalImageType, + InternalImageType].New( + sigmoid, + TrialPoints=seeds, + SpeedConstant=1.0, + OutputSize=reader.GetOutput().GetBufferedRegion().GetSize()) + + geodesicActiveContour = itk.GeodesicActiveContourLevelSetImageFilter[ + InternalImageType, + InternalImageType, + InternalPixelType].New( + fastMarching, + # it is required to use the explicitly the FeatureImage + # - itk segfault without that :-( + FeatureImage=sigmoid.GetOutput(), + PropagationScaling=float(argv[9]), + CurvatureScaling=1.0, + AdvectionScaling=1.0, + MaximumRMSError=0.02, + NumberOfIterations=800) + + thresholder = itk.BinaryThresholdImageFilter[ + InternalImageType, + OutputImageType].New( + geodesicActiveContour, + LowerThreshold=-1000, + UpperThreshold=0, + OutsideValue=0, + InsideValue=255) + + writer = itk.ImageFileWriter[OutputImageType].New( + thresholder, + FileName=argv[2]) def rescaleAndWrite(filter, fileName): - caster = itk.RescaleIntensityImageFilter[InternalImageType, OutputImageType].New(filter, - OutputMinimum=0, - OutputMaximum=255) + caster = itk.RescaleIntensityImageFilter[ + InternalImageType, + OutputImageType].New( + filter, + OutputMinimum=0, + OutputMaximum=255) itk.write(caster, fileName) - rescaleAndWrite(smoothing, "GeodesicActiveContourImageFilterOutput1.png") - rescaleAndWrite(gradientMagnitude, "GeodesicActiveContourImageFilterOutput2.png") + rescaleAndWrite( + gradientMagnitude, + "GeodesicActiveContourImageFilterOutput2.png") rescaleAndWrite(sigmoid, "GeodesicActiveContourImageFilterOutput3.png") - rescaleAndWrite(fastMarching, "GeodesicActiveContourImageFilterOutput4.png") + rescaleAndWrite( + fastMarching, + "GeodesicActiveContourImageFilterOutput4.png") writer.Update() - - print - print "Max. no. iterations: %d" % (geodesicActiveContour.GetNumberOfIterations()) - print "Max. RMS error: %.3f" % (geodesicActiveContour.GetMaximumRMSError()) - print - print "No. elapsed iterations: %d" % (geodesicActiveContour.GetElapsedIterations()) - print "RMS change: %.3f" % (geodesicActiveContour.GetRMSChange()) - + print("") + print( + "Max. no. iterations: %d" % + (geodesicActiveContour.GetNumberOfIterations())) + print( + "Max. RMS error: %.3f" % + (geodesicActiveContour.GetMaximumRMSError())) + print("") + print( + "No. elapsed iterations: %d" + % (geodesicActiveContour.GetElapsedIterations())) + print("RMS change: %.3f" % (geodesicActiveContour.GetRMSChange())) itk.write(fastMarching, "GeodesicActiveContourImageFilterOutput4.mha") itk.write(sigmoid, "GeodesicActiveContourImageFilterOutput3.mha") itk.write(gradientMagnitude, "GeodesicActiveContourImageFilterOutput2.mha") - - - - if __name__ == "__main__": main() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/GradientAnisotropicDiffusionImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/GradientAnisotropicDiffusionImageFilter.py index 75e6d1fdb4728925ec35bb09cef34472fb3df021..29abfce37803d442caa4dbe985f8dfa0e937acd2 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/GradientAnisotropicDiffusionImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/GradientAnisotropicDiffusionImageFilter.py @@ -26,17 +26,24 @@ OutputPixelType = itk.F InputImageType = itk.Image[InputPixelType, 2] OutputImageType = itk.Image[OutputPixelType, 2] -reader = itk.ImageFileReader[InputImageType].New( FileName=argv[1] ) +reader = itk.ImageFileReader[InputImageType].New(FileName=argv[1]) -filter = itk.GradientAnisotropicDiffusionImageFilter[InputImageType, OutputImageType].New( reader, - NumberOfIterations=int(argv[3]), - TimeStep=float(argv[4]), - ConductanceParameter=float(argv[5])) -filter.Update(); +filter = itk.GradientAnisotropicDiffusionImageFilter[ + InputImageType, OutputImageType].New( + reader, + NumberOfIterations=int(argv[3]), + TimeStep=float(argv[4]), + ConductanceParameter=float(argv[5])) +filter.Update() WritePixelType = itk.UC WriteImageType = itk.Image[WritePixelType, 2] -rescaler = itk.RescaleIntensityImageFilter[OutputImageType, WriteImageType].New( filter, OutputMinimum=0, OutputMaximum=255 ) -writer = itk.ImageFileWriter[WriteImageType].New( rescaler, FileName=argv[2] ) -writer.Update(); +rescaler = itk.RescaleIntensityImageFilter[ + OutputImageType, + WriteImageType].New( + filter, + OutputMinimum=0, + OutputMaximum=255) +writer = itk.ImageFileWriter[WriteImageType].New(rescaler, FileName=argv[2]) +writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/GradientMagnitudeRecursiveGaussianImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/GradientMagnitudeRecursiveGaussianImageFilter.py index 83ea0b93d64dad53ecb29095b33ddeeff3769e7b..3aba8c4434a2358e89cc9faed8cddcc295a98b7e 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/GradientMagnitudeRecursiveGaussianImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/GradientMagnitudeRecursiveGaussianImageFilter.py @@ -26,14 +26,20 @@ OutputPixelType = itk.F InputImageType = itk.Image[InputPixelType, 2] OutputImageType = itk.Image[OutputPixelType, 2] -reader = itk.ImageFileReader[InputImageType].New( FileName=argv[1] ) +reader = itk.ImageFileReader[InputImageType].New(FileName=argv[1]) -filter = itk.GradientMagnitudeRecursiveGaussianImageFilter[InputImageType, OutputImageType].New( reader, Sigma=float(argv[3]) ) -filter.Update(); +filter = itk.GradientMagnitudeRecursiveGaussianImageFilter[ + InputImageType, OutputImageType].New(reader, Sigma=float(argv[3])) +filter.Update() WritePixelType = itk.UC WriteImageType = itk.Image[WritePixelType, 2] -rescaler = itk.RescaleIntensityImageFilter[OutputImageType, WriteImageType].New( filter, OutputMinimum=0, OutputMaximum=255 ) -writer = itk.ImageFileWriter[WriteImageType].New( rescaler, FileName=argv[2] ) -writer.Update(); +rescaler = itk.RescaleIntensityImageFilter[ + OutputImageType, + WriteImageType].New( + filter, + OutputMinimum=0, + OutputMaximum=255) +writer = itk.ImageFileWriter[WriteImageType].New(rescaler, FileName=argv[2]) +writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/GrayscaleDilateImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/GrayscaleDilateImageFilter.py index 785ee853dd1584dc37f9cddaee85b394381c7bef..653008519b0ca760f000ff1fdbd6cf8b92a8a1e8 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/GrayscaleDilateImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/GrayscaleDilateImageFilter.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python + #========================================================================== # # Copyright Insight Software Consortium @@ -17,20 +19,38 @@ #==========================================================================*/ # -# Example on the use of the GrayscaleDilateImageFilter +# Test GrayscaleDilateImageFilter # +import sys import itk -from sys import argv itk.auto_progress(2) -dim = 2 -IType = itk.Image[itk.UC, dim] +inputImage = sys.argv[1] +outputImage = sys.argv[2] +radiusValue = int(sys.argv[3]) + +PixelType = itk.UC +Dimension = 2 + +ImageType = itk.Image[PixelType, Dimension] + +ReaderType = itk.ImageFileReader[ImageType] +reader = ReaderType.New() +reader.SetFileName(inputImage) + +StructuringElementType = itk.FlatStructuringElement[Dimension] +structuringElement = StructuringElementType.Ball(radiusValue) + +GrayscaleFilterType = itk.GrayscaleDilateImageFilter[ + ImageType, ImageType, StructuringElementType] +grayscaleFilter = GrayscaleFilterType.New() +grayscaleFilter.SetInput(reader.GetOutput()) +grayscaleFilter.SetKernel(structuringElement) -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -kernel = itk.strel(dim, 5) -filter = itk.GrayscaleDilateImageFilter[IType, IType, kernel].New( reader, - Kernel=kernel ) -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +WriterType = itk.ImageFileWriter[ImageType] +writer = WriterType.New() +writer.SetFileName(outputImage) +writer.SetInput(grayscaleFilter.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/GrayscaleErodeImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/GrayscaleErodeImageFilter.py index aaff2b1fa543679d2c023f8f3d231d51a900c605..74c92dbb44897db2b7a904b6f953c7ace046ce5e 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/GrayscaleErodeImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/GrayscaleErodeImageFilter.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python + #========================================================================== # # Copyright Insight Software Consortium @@ -17,20 +19,38 @@ #==========================================================================*/ # -# Example on the use of the GrayscaleErodeImageFilter +# Test GrayscaleErodeImageFilter # +import sys import itk -from sys import argv itk.auto_progress(2) -dim = 2 -IType = itk.Image[itk.UC, dim] +inputImage = sys.argv[1] +outputImage = sys.argv[2] +radiusValue = int(sys.argv[3]) + +PixelType = itk.UC +Dimension = 2 + +ImageType = itk.Image[PixelType, Dimension] + +ReaderType = itk.ImageFileReader[ImageType] +reader = ReaderType.New() +reader.SetFileName(inputImage) + +StructuringElementType = itk.FlatStructuringElement[Dimension] +structuringElement = StructuringElementType.Ball(radiusValue) + +GrayscaleFilterType = itk.GrayscaleErodeImageFilter[ + ImageType, ImageType, StructuringElementType] +grayscaleFilter = GrayscaleFilterType.New() +grayscaleFilter.SetInput(reader.GetOutput()) +grayscaleFilter.SetKernel(structuringElement) -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -kernel = itk.strel(dim, 5) -filter = itk.GrayscaleErodeImageFilter[IType, IType, kernel].New( reader, - Kernel=kernel ) -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +WriterType = itk.ImageFileWriter[ImageType] +writer = WriterType.New() +writer.SetFileName(outputImage) +writer.SetInput(grayscaleFilter.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/LaplacianImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/LaplacianImageFilter.py index d27faf67036bc9fb9c7da481ccc94e69b0693f07..32be49617717100bfdc895854d02ccac8f6b5363 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/LaplacianImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/LaplacianImageFilter.py @@ -28,11 +28,11 @@ dim = 2 IType = itk.Image[itk.F, dim] OIType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -filter = itk.LaplacianImageFilter[IType, IType].New( reader ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +filter = itk.LaplacianImageFilter[IType, IType].New(reader) cast = itk.RescaleIntensityImageFilter[IType, OIType].New(filter, - OutputMinimum=0, - OutputMaximum=255) -writer = itk.ImageFileWriter[OIType].New( cast, FileName=argv[2] ) + OutputMinimum=0, + OutputMaximum=255) +writer = itk.ImageFileWriter[OIType].New(cast, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/MeanImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/MeanImageFilter.py index 35dfbbde55719cfa53fb4fc7a8536ec14c8482df..e0e30cfd6556d45e69a832f731d5e48c5ca66b50 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/MeanImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/MeanImageFilter.py @@ -1,3 +1,20 @@ +#========================================================================== +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#==========================================================================*/ # # Example on the use of the MeanImageFilter @@ -9,11 +26,11 @@ from sys import argv dim = 2 IType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -filter = itk.MeanImageFilter[IType, IType].New( reader, Radius=eval( argv[3] ) ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +filter = itk.MeanImageFilter[IType, IType].New(reader, Radius=eval(argv[3])) -watcher = itk.SimpleFilterWatcher( filter, "filter" ) +watcher = itk.SimpleFilterWatcher(filter, "filter") -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +writer = itk.ImageFileWriter[IType].New(filter, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/MedianImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/MedianImageFilter.py index 455190ceefc7d13f18f77e906ae019f781fdb65f..ebbc5eeee2892eef4e35d20b2a90b3e1a9deb509 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/MedianImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/MedianImageFilter.py @@ -23,15 +23,15 @@ import itk from sys import argv -reader = itk.ImageFileReader.IUC2.New( FileName=argv[1] ) +reader = itk.ImageFileReader.IUC2.New(FileName=argv[1]) # test the deduction of the template parameter from the input -filter = itk.MedianImageFilter.New( reader ) -watcher = itk.XMLFilterWatcher( filter, "filter" ) +filter = itk.MedianImageFilter.New(reader) +watcher = itk.XMLFilterWatcher(filter, "filter") # test the update of the filter with the __call__ operator # and the setting of parameter inside it -filter( Radius=eval(argv[3]) ) +filter(Radius=eval(argv[3])) # test the write method -itk.write( filter, argv[2] ) +itk.write(filter, argv[2]) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/OldStyleBinaryDilateImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/OldStyleBinaryDilateImageFilter.py index ad091b6d02968b480f71b606dcab34e1d0b34189..bb01f4ffea9e6027485b2ec01775dad7c725ed51 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/OldStyleBinaryDilateImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/OldStyleBinaryDilateImageFilter.py @@ -1,3 +1,21 @@ +#========================================================================== +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#==========================================================================*/ + # # Example on the use of the BinaryDilateImageFilter # @@ -6,14 +24,14 @@ from InsightToolkit import * from sys import argv reader = itkImageFileReaderIUC2.New() -reader.SetFileName( argv[1] ) -kernel = itkFlatStructuringElement2.Ball( 5 ) -filter = itkBinaryDilateImageFilterIUC2IUC2SE2.New() -filter.SetInput( reader.GetOutput() ) -filter.SetDilateValue( 200 ) -filter.SetKernel( kernel ) +reader.SetFileName(argv[1]) +kernel = itkFlatStructuringElement2.Ball(5) +filter = itkBinaryDilateImageFilterIUC2IUC2SE2.New() +filter.SetInput(reader.GetOutput()) +filter.SetDilateValue(200) +filter.SetKernel(kernel) writer = itkImageFileWriterIUC2.New() writer.SetInput(filter.GetOutput()) -writer.SetFileName( argv[2] ) +writer.SetFileName(argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/ReadDicomAndReadTag.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/ReadDicomAndReadTag.py new file mode 100644 index 0000000000000000000000000000000000000000..df1edd012dce9b3486a193fc942b61b88d4ed4ff --- /dev/null +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/ReadDicomAndReadTag.py @@ -0,0 +1,68 @@ +#========================================================================== +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#==========================================================================*/ + +# Tests: +# - Reading dicom files from a directory +# - Read a tag (patient's name) through the MetaDataDictionary +# - Read a tag (patient's name) directly with the GetValueFromTag() method +# - Compare the two tags if they are the same + +from __future__ import print_function + +import itk +import sys + +imdir = sys.argv[1] +image_t = itk.Image[itk.F, 3] + +# Set up reader +reader = itk.ImageSeriesReader[image_t].New() +dicomIO = itk.GDCMImageIO.New() +dicomFN = itk.GDCMSeriesFileNames.New() +reader.SetImageIO(dicomIO) + +# Get file names +dicomFN.SetUseSeriesDetails(True) +dicomFN.SetDirectory(imdir) + +# Get the first image series +uids = dicomFN.GetSeriesUIDs() +fnames = dicomFN.GetFileNames(uids[0]) + +# Read in the files +reader.SetFileNames(fnames) +reader.Update() +image = reader.GetOutput() + +# Now access the meta data dictionary +metad = dicomIO.GetMetaDataDictionary() + +# Get the patient's name +name1 = metad["0010|0010"] + +# Other way to get the tag +# GetValueFromTag(tagkey, tagvalue) +# tagvalue is an empty string, in C++ it is passed by +# reference. Here we pass an empty string, and the +# actual value is returned as the second variable. +found, name2 = dicomIO.GetValueFromTag("0010|0010", "") +assert(name1 == name2) + +# Check also if we returned the right tag +found, name3 = dicomIO.GetLabelFromTag("0010|0010", "") +assert(name3 == "Patient's Name") diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/ResampleImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/ResampleImageFilter.py index 74fe6eddbad290b561c417ee98e44ee319d47f31..1d1e6531d0a02c684c6bcdf4bac88de833ad41dd 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/ResampleImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/ResampleImageFilter.py @@ -33,89 +33,91 @@ # OUTPUTS: {ResampleImageFilterOutput4.png} # 3 +from __future__ import print_function + import itk from sys import argv, stderr, exit itk.auto_progress(2) -if( len(argv) < 3 ): - print >> stderr, """Missing Parameters -Usage: ResampleImageFilter.py inputImageFile outputImageFile [exampleAction={0,1,2,3}]""" - exit(1) +if(len(argv) < 3): + print(( + "Missing Parameters \n Usage: ResampleImageFilter.py inputImageFile " + "outputImageFile [exampleAction={0,1,2,3}]"), file=stderr) + exit(1) exampleAction = 0 -if( len(argv) >= 4 ): - exampleAction = int( argv[3] ) +if(len(argv) >= 4): + exampleAction = int(argv[3]) Dimension = 2 InputPixelType = itk.UC OutputPixelType = itk.UC -InputImageType = itk.Image[ InputPixelType, Dimension ] -OutputImageType = itk.Image[ OutputPixelType, Dimension ] +InputImageType = itk.Image[InputPixelType, Dimension] +OutputImageType = itk.Image[OutputPixelType, Dimension] -ReaderType = itk.ImageFileReader[ InputImageType ] -CastType = itk.CastImageFilter[ InputImageType, OutputImageType ] -WriterType = itk.ImageFileWriter[ OutputImageType ] +ReaderType = itk.ImageFileReader[InputImageType] +CastType = itk.CastImageFilter[InputImageType, OutputImageType] +WriterType = itk.ImageFileWriter[OutputImageType] reader = ReaderType.New() cast = CastType.New() writer = WriterType.New() -reader.SetFileName( argv[1] ) -writer.SetFileName( argv[2] ) +reader.SetFileName(argv[1]) +writer.SetFileName(argv[2]) -FilterType = itk.ResampleImageFilter[InputImageType,InputImageType] +FilterType = itk.ResampleImageFilter[InputImageType, InputImageType] filter = FilterType.New() -TransformType = itk.AffineTransform[ itk.D, Dimension ] +TransformType = itk.AffineTransform[itk.D, Dimension] transform = TransformType.New() -filter.SetTransform( transform ) +filter.SetTransform(transform) InterpolatorType = itk.NearestNeighborInterpolateImageFunction[ - InputImageType, itk.D ] + InputImageType, itk.D] interpolator = InterpolatorType.New() -filter.SetInterpolator( interpolator ) +filter.SetInterpolator(interpolator) -filter.SetDefaultPixelValue( 0 ) +filter.SetDefaultPixelValue(0) # spacing = itk.Vector[itk.D, Dimension]() # spacing.SetElement(0, 1.0) # spacing.SetElement(1, 1.0) # filter.SetOutputSpacing( spacing ) -filter.SetOutputSpacing( 1.0 ) +filter.SetOutputSpacing(1.0) # origin = itk.Point[itk.D, Dimension]() # origin.SetElement(0, 0.0) # origin.SetElement(1, 0.0) # filter.SetOutputOrigin( origin ) -filter.SetOutputOrigin( [0.0, 0.0] ) +filter.SetOutputOrigin([0.0, 0.0]) # size = itk.Size[Dimension]() # size.SetElement(0, 300) # size.SetElement(1, 300) # filter.SetSize( size ) -filter.SetSize( 300 ) +filter.SetSize(300) -filter.SetInput( reader.GetOutput() ) -cast.SetInput( filter.GetOutput() ) -writer.SetInput( cast.GetOutput() ) +filter.SetInput(reader.GetOutput()) +cast.SetInput(filter.GetOutput()) +writer.SetInput(cast.GetOutput()) writer.Update() # translation = itk.Vector[itk.D, Dimension]() # translation.SetElement(0, -30) # translation.SetElement(1, -50) # transform.Translate( translation, 0 ) -transform.Translate( [-30, -50], 0 ) - -if( exampleAction == 1 ): - writer.Update() +transform.Translate([-30, -50], False) +if(exampleAction == 1): + writer.Update() -filter.SetDefaultPixelValue( 100 ) +filter.SetDefaultPixelValue(100) -if( exampleAction == 2 ): - writer.Update() +if(exampleAction == 2): + writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/SigmoidImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/SigmoidImageFilter.py index 0cc76496414e14ec5ef330ae0dcf826ab11cdc38..f03467272f2152b1d35b8fe921d6e3eb01d3ad53 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/SigmoidImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/SigmoidImageFilter.py @@ -27,13 +27,13 @@ itk.auto_progress(2) dim = 2 IType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -filter = itk.SigmoidImageFilter[IType, IType].New( reader, - OutputMinimum=eval( argv[3] ), - OutputMaximum=eval( argv[4] ), - Alpha=eval( argv[5] ), - Beta=eval( argv[6] ), - ) -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +filter = itk.SigmoidImageFilter[IType, IType].New(reader, + OutputMinimum=eval(argv[3]), + OutputMaximum=eval(argv[4]), + Alpha=eval(argv[5]), + Beta=eval(argv[6]), + ) +writer = itk.ImageFileWriter[IType].New(filter, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/SmoothingRecursiveGaussianImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/SmoothingRecursiveGaussianImageFilter.py index 95aee112c1af7a785a0ccdae1f3ae009f0aacbae..12d1d7e370cc1157191c9dd8937c006faa401a51 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/SmoothingRecursiveGaussianImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/SmoothingRecursiveGaussianImageFilter.py @@ -24,6 +24,8 @@ import itk from sys import argv itk.auto_progress(2) -reader = itk.ImageFileReader.IUC2.New( FileName=argv[1] ) -filter = itk.SmoothingRecursiveGaussianImageFilter.New( reader, Sigma=eval( argv[3] ) ) -itk.write( filter, argv[2] ) +reader = itk.ImageFileReader.IUC2.New(FileName=argv[1]) +filter = itk.SmoothingRecursiveGaussianImageFilter.New( + reader, + Sigma=eval(argv[3])) +itk.write(filter, argv[2]) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/SpatialObjectTest.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/SpatialObjectTest.py index 58c7d56305bad4bab7142ebf05f126e767eec289..78c19320d1b70be31a3225b741f137b2bb66acae 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/SpatialObjectTest.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/SpatialObjectTest.py @@ -32,14 +32,17 @@ # OUTPUTS: {ResampleImageFilterOutput4.png} # 3 +from __future__ import print_function + import itk from sys import argv, stderr, exit itk.auto_progress(2) # if( len(argv) < 3 ): -# print >> stderr, """Missing Parameters -# Usage: ResampleImageFilter.py inputImageFile outputImageFile [exampleAction={0,1,2,3}]""" +# print("""Missing Parameters +# Usage: ResampleImageFilter.py inputImageFile outputImageFile +# [exampleAction={0,1,2,3}]""", file=stderr) # exit(1) dim = 2 @@ -48,27 +51,33 @@ InternalImageType = itk.Image[itk.F, dim] OutputPixelType = itk.UC OutputImageType = itk.Image[OutputPixelType, dim] -ellipse = itk.EllipseSpatialObject[dim].New( Radius=[10,5] ) -ellipse.GetObjectToParentTransform().SetOffset( [20,20] ) +ellipse = itk.EllipseSpatialObject[dim].New(Radius=[10, 5]) +ellipse.GetObjectToParentTransform().SetOffset([20, 20]) ellipse.ComputeObjectToWorldTransform() -box = itk.BoxSpatialObject[dim].New( Size=20 ) -box.GetObjectToParentTransform().SetOffset( [20,40] ) +box = itk.BoxSpatialObject[dim].New(Size=20) +box.GetObjectToParentTransform().SetOffset([20, 40]) box.ComputeObjectToWorldTransform() -gaussian = itk.GaussianSpatialObject[dim].New( Radius=100 ) -gaussian.GetObjectToParentTransform().SetOffset( [60,60] ) -gaussian.GetObjectToParentTransform().SetScale( 10 ) +gaussian = itk.GaussianSpatialObject[dim].New(Radius=100) +gaussian.GetObjectToParentTransform().SetOffset([60, 60]) +gaussian.GetObjectToParentTransform().SetScale(10) gaussian.ComputeObjectToWorldTransform() group = itk.GroupSpatialObject[dim].New() -group.AddSpatialObject( ellipse ) -group.AddSpatialObject( box ) -group.AddSpatialObject( gaussian ) +group.AddSpatialObject(ellipse) +group.AddSpatialObject(box) +group.AddSpatialObject(gaussian) -filter = itk.SpatialObjectToImageFilter[SOType, InternalImageType].New( group, Size=[100,100], UseObjectValue=True ) -filter.Update() # required ?! +filter = itk.SpatialObjectToImageFilter[SOType, InternalImageType].New( + group, Size=[100, 100], UseObjectValue=True) +filter.Update() # required ?! -rescale = itk.RescaleIntensityImageFilter[InternalImageType, OutputImageType].New( filter, OutputMinimum=itk.NumericTraits[OutputPixelType].NonpositiveMin(), OutputMaximum=itk.NumericTraits[OutputPixelType].max() ) +rescale = itk.RescaleIntensityImageFilter[ + InternalImageType, + OutputImageType].New( + filter, + OutputMinimum=itk.NumericTraits[OutputPixelType].NonpositiveMin(), + OutputMaximum=itk.NumericTraits[OutputPixelType].max()) itk.write(rescale, argv[1]) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/StrelFromImageGrayscaleDilateImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/StrelFromImageGrayscaleDilateImageFilter.py index d3e89dd83225d2ee38cfa0b3b3da319b9ece0592..758828e8336ea9102ee5f556e3469ec49acceb97 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/StrelFromImageGrayscaleDilateImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/StrelFromImageGrayscaleDilateImageFilter.py @@ -29,12 +29,12 @@ dim = 2 IType = itk.Image[itk.US, dim] OIType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -reader2 = itk.ImageFileReader[OIType].New( FileName=argv[3] ) -kernel = itk.FlatStructuringElement[dim].FromImageUC( reader2.GetOutput() ) -filter = itk.GrayscaleDilateImageFilter[IType, IType, kernel].New( reader, - Kernel=kernel ) -cast = itk.CastImageFilter[IType, OIType].New(filter) -writer = itk.ImageFileWriter[OIType].New( cast, FileName=argv[2] ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +reader2 = itk.ImageFileReader[OIType].New(FileName=argv[3]) +kernel = itk.FlatStructuringElement[dim].FromImageUC(reader2.GetOutput()) +grayscaleFilter = itk.GrayscaleDilateImageFilter[IType, IType, kernel] +grayscaleFilter = grayscaleFilter.New(reader, Kernel=kernel) +cast = itk.CastImageFilter[IType, OIType].New(grayscaleFilter) +writer = itk.ImageFileWriter[OIType].New(cast, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/TestDirectory.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/TestDirectory.py index 636254b00e18d13ef76842bcf81b37bdee202867..c5940aeb4d99e477a5dbf18fcfb8618efd94cac4 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/TestDirectory.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/TestDirectory.py @@ -16,6 +16,8 @@ # #==========================================================================*/ +from __future__ import print_function + import itk itk.auto_progress(2) @@ -24,5 +26,5 @@ d.Load(".") n = d.GetNumberOfFiles() i = 0 while i < n: - print d.GetFile(i) - i = i +1 + print(d.GetFile(i)) + i = i + 1 diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/TestMetaDataDictionary.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/TestMetaDataDictionary.py index d2c93562aec3d71a732d8e86fc38f6a09cb2b620..4a80ad09413316ccffcc746d73fb57368d6f8995 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/TestMetaDataDictionary.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/TestMetaDataDictionary.py @@ -15,6 +15,9 @@ # limitations under the License. # #==========================================================================*/ + +from __future__ import print_function + import itk from sys import argv @@ -23,7 +26,8 @@ md = itk.MetaDataDictionary() dv = itk.MetaDataObject.D.New() dv.SetMetaDataObjectValue(10.0) md.Set("double", dv) -print md.Get("double") -# other way of setting and retrieving double value (levereges on Python's weak type system) +print(md.Get("double")) +# other way of setting and retrieving double value (levereges on Python's +# weak type system) md['double'] = 10.0 -print md['double'] +print(md['double']) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/ThresholdImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/ThresholdImageFilter.py index ab3cb48b883e1f267cd5f2409cf337daf4576547..1e49caebd794ef45224bcd63b8f084e47e8deba8 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/ThresholdImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/ThresholdImageFilter.py @@ -27,13 +27,13 @@ itk.auto_progress(2) dim = 2 IType = itk.Image[itk.UC, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -filter = itk.ThresholdImageFilter[IType].New( reader, - OutsideValue=eval( argv[3] ) ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +filter = itk.ThresholdImageFilter[IType].New(reader, + OutsideValue=eval(argv[3])) # this method can't be called in the New() method because it doesn't # use the Set notation -filter.ThresholdAbove( eval( argv[4] ) ) +filter.ThresholdAbove(eval(argv[4])) -writer = itk.ImageFileWriter[IType].New( filter, FileName=argv[2] ) +writer = itk.ImageFileWriter[IType].New(filter, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/ThresholdSegmentationLevelSetImageFilter.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/ThresholdSegmentationLevelSetImageFilter.py index 5ff9dc3daa7bf408876f5414f75bc14ad0c8768b..33b12c845948ebdfeec3d6226ee0b862abd7e0de 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/ThresholdSegmentationLevelSetImageFilter.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/ThresholdSegmentationLevelSetImageFilter.py @@ -28,103 +28,114 @@ # OUTPUTS: {ThresholdSegmentationLevelSetImageFilterGrayMatter.png} # 107 69 5 180 210 +from __future__ import print_function + import itk from sys import argv, stderr, exit itk.auto_progress(2) # itk.auto_progress(1) -if len(argv) < 8 : - print >> stderr, """Missing Parameters -Usage: ThresholdSegmentationLevelSetImageFilter.py inputImage outputImage seedX seedY InitialDistance LowerThreshold UpperThreshold [CurvatureScaling == 1.0]""" - exit(1) +if len(argv) < 8: + print(( + "Missing Parameters \n Usage: " + "ThresholdSegmentationLevelSetImageFilter.py inputImage outputImage " + "seedX seedY InitialDistance LowerThreshold UpperThreshold " + "[CurvatureScaling == 1.0]"), file=stderr) + exit(1) InternalPixelType = itk.F Dimension = 2 -InternalImageType = itk.Image[ InternalPixelType, Dimension ] +InternalImageType = itk.Image[InternalPixelType, Dimension] OutputPixelType = itk.UC -OutputImageType = itk.Image[ OutputPixelType, Dimension ] +OutputImageType = itk.Image[OutputPixelType, Dimension] -thresholder = itk.BinaryThresholdImageFilter[ InternalImageType, OutputImageType ].New() +thresholder = itk.BinaryThresholdImageFilter[ + InternalImageType, OutputImageType].New() -thresholder.SetLowerThreshold( -1000.0 ) -thresholder.SetUpperThreshold( 0.0 ) +thresholder.SetLowerThreshold(-1000.0) +thresholder.SetUpperThreshold(0.0) -thresholder.SetOutsideValue( 0 ) -thresholder.SetInsideValue( 255 ) +thresholder.SetOutsideValue(0) +thresholder.SetInsideValue(255) -ReaderType = itk.ImageFileReader[ InternalImageType ] -WriterType = itk.ImageFileWriter[ OutputImageType ] +ReaderType = itk.ImageFileReader[InternalImageType] +WriterType = itk.ImageFileWriter[OutputImageType] reader = ReaderType.New() writer = WriterType.New() -reader.SetFileName( argv[1] ) -writer.SetFileName( argv[2] ) +reader.SetFileName(argv[1]) +writer.SetFileName(argv[2]) -FastMarchingFilterType = itk.FastMarchingImageFilter[ InternalImageType, InternalImageType ] +FastMarchingFilterType = itk.FastMarchingImageFilter[ + InternalImageType, + InternalImageType] fastMarching = FastMarchingFilterType.New() -ThresholdSegmentationLevelSetImageFilterType = itk.ThresholdSegmentationLevelSetImageFilter[ InternalImageType, InternalImageType, InternalPixelType ] -thresholdSegmentation = ThresholdSegmentationLevelSetImageFilterType.New() -thresholdSegmentation.SetPropagationScaling( 1.0 ) -if len(argv) > 8 : - thresholdSegmentation.SetCurvatureScaling( float(argv[8]) ) +ThresholdSegLvlSetImgFilterType = itk.ThresholdSegmentationLevelSetImageFilter[ + InternalImageType, + InternalImageType, + InternalPixelType] +thresholdSegmentation = ThresholdSegLvlSetImgFilterType.New() +thresholdSegmentation.SetPropagationScaling(1.0) +if len(argv) > 8: + thresholdSegmentation.SetCurvatureScaling(float(argv[8])) else: - thresholdSegmentation.SetCurvatureScaling( 1.0 ) + thresholdSegmentation.SetCurvatureScaling(1.0) -thresholdSegmentation.SetMaximumRMSError( 0.02 ) -thresholdSegmentation.SetNumberOfIterations( 1200 ) +thresholdSegmentation.SetMaximumRMSError(0.02) +thresholdSegmentation.SetNumberOfIterations(1200) -thresholdSegmentation.SetUpperThreshold( float(argv[7]) ) -thresholdSegmentation.SetLowerThreshold( float(argv[6]) ) +thresholdSegmentation.SetUpperThreshold(float(argv[7])) +thresholdSegmentation.SetLowerThreshold(float(argv[6])) thresholdSegmentation.SetIsoSurfaceValue(0.0) -thresholdSegmentation.SetInput( fastMarching.GetOutput() ) -thresholdSegmentation.SetFeatureImage( reader.GetOutput() ) -thresholder.SetInput( thresholdSegmentation.GetOutput() ) -writer.SetInput( thresholder.GetOutput() ) +thresholdSegmentation.SetInput(fastMarching.GetOutput()) +thresholdSegmentation.SetFeatureImage(reader.GetOutput()) +thresholder.SetInput(thresholdSegmentation.GetOutput()) +writer.SetInput(thresholder.GetOutput()) NodeType = itk.LevelSetNode[InternalPixelType, Dimension] NodeContainer = itk.VectorContainer[itk.UI, NodeType] seeds = NodeContainer.New() -seedPosition = [int( argv[3] ), int( argv[4] )] +seedPosition = [int(argv[3]), int(argv[4])] -initialDistance = float( argv[5] ) +initialDistance = float(argv[5]) node = NodeType() seedValue = - initialDistance -node.SetValue( seedValue ) -node.SetIndex( seedPosition ) +node.SetValue(seedValue) +node.SetIndex(seedPosition) seeds.Initialize() -seeds.InsertElement( 0, node ) +seeds.InsertElement(0, node) -fastMarching.SetTrialPoints( seeds ) +fastMarching.SetTrialPoints(seeds) -fastMarching.SetSpeedConstant( 1.0 ) +fastMarching.SetSpeedConstant(1.0) reader.Update() fastMarching.SetOutputSize( - reader.GetOutput().GetBufferedRegion().GetSize() ) + reader.GetOutput().GetBufferedRegion().GetSize()) writer.Update() itk.echo(thresholdSegmentation) -InternalWriterType = itk.ImageFileWriter[ InternalImageType ] +InternalWriterType = itk.ImageFileWriter[InternalImageType] mapWriter = InternalWriterType.New() -mapWriter.SetInput( fastMarching.GetOutput() ) +mapWriter.SetInput(fastMarching.GetOutput()) mapWriter.SetFileName("fastMarchingImage.mha") mapWriter.Update() speedWriter = InternalWriterType.New() -speedWriter.SetInput( thresholdSegmentation.GetSpeedImage() ) +speedWriter.SetInput(thresholdSegmentation.GetSpeedImage()) speedWriter.SetFileName("speedTermImage.mha") speedWriter.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/WatershedSegmentation1.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/WatershedSegmentation1.py index d8c59601c02ddca7fcba4ed9b789ec543a22d501..441ff57df273ef3961494dc24e16d62ae9e4eb43 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/WatershedSegmentation1.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/WatershedSegmentation1.py @@ -21,13 +21,13 @@ import sys itk.auto_progress(2) reader = itk.ImageFileReader.IF2.New() -reader.SetFileName( sys.argv[1] ) +reader.SetFileName(sys.argv[1]) diffusion = itk.GradientAnisotropicDiffusionImageFilter.IF2IF2.New() diffusion.SetInput(reader.GetOutput()) diffusion.SetTimeStep(0.0625) diffusion.SetConductanceParameter(9.0) -diffusion.SetNumberOfIterations( 5 ); +diffusion.SetNumberOfIterations(5) gradient = itk.GradientMagnitudeImageFilter.IF2IF2.New() gradient.SetInput(diffusion.GetOutput()) @@ -38,12 +38,12 @@ watershed.SetThreshold(0.01) watershed.SetLevel(0.2) relabel = itk.RelabelComponentImageFilter.IUL2ISS2.New() -relabel.SetInput( watershed.GetOutput() ) +relabel.SetInput(watershed.GetOutput()) cast = itk.CastImageFilter.ISS2IUC2.New() -cast.SetInput( relabel.GetOutput() ) +cast.SetInput(relabel.GetOutput()) writer = itk.ImageFileWriter.IUC2.New() -writer.SetFileName( sys.argv[2] ) -writer.SetInput( cast.GetOutput() ) +writer.SetFileName(sys.argv[2]) +writer.SetInput(cast.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/auto_pipeline.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/auto_pipeline.py index b6569519766493460df47646ad362feb447cd221..e9f4274be0a53a9e7545972ffa58643e52b45471 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/auto_pipeline.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/auto_pipeline.py @@ -1,14 +1,32 @@ +#========================================================================== +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#==========================================================================*/ + import itk from sys import argv # instantiate an auto pipeline p = itk.auto_pipeline() -# from now, and until we call p.Stop(), all the new objects will be connected to -# the pipeline p, without having to give a name to any filter +# from now, and until we call p.Stop(), all the new objects will be connected +# to the pipeline p, without having to give a name to any filter -itk.ImageFileReader.IUC2.New( FileName=argv[1] ) -itk.MedianImageFilter.IUC2IUC2.New( Radius=eval( argv[3] ) ) +itk.ImageFileReader.IUC2.New(FileName=argv[1]) +itk.MedianImageFilter.IUC2IUC2.New(Radius=eval(argv[3])) itk.CastImageFilter.IUC2IUC2.New() # stop the auto_pipeline and test that the next (imcompatible) filter is not @@ -17,5 +35,5 @@ p.Stop() itk.CastImageFilter.IF2IF2.New() p.Start() -itk.ImageFileWriter.IUC2.New( FileName=argv[2] ) +itk.ImageFileWriter.IUC2.New(FileName=argv[2]) p.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/extras.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/extras.py index 1598b87912fa01c505c80dc0cd0459f672ba7ef6..eef3bbcba67bd835bab3691dccdcda7ec82ff390 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/extras.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/extras.py @@ -17,15 +17,20 @@ #==========================================================================*/ # also test the import callback feature + +from __future__ import print_function + + def custom_callback(name, progress): - if progress == 0: - print >> sys.stderr, "Loading %s..." % name, - if progress == 1: - print >> sys.stderr, "done" + if progress == 0: + print("Loading %s..." % name, file=sys.stderr) + if progress == 1: + print("done", file=sys.stderr) import itkConfig itkConfig.ImportCallback = custom_callback -import itk, sys +import itk +import sys # test the force load function itk.force_load() @@ -51,19 +56,19 @@ assert itk.class_("dummy") == str assert itk.template(ReaderType) == (itk.ImageFileReader, (IType,)) assert itk.template(reader) == (itk.ImageFileReader, (IType,)) try: - itk.template(str) - raise Exception("unknown class should send an exception") + itk.template(str) + raise Exception("unknown class should send an exception") except KeyError: - pass + pass # test ctype assert itk.ctype("unsigned short") == itk.US assert itk.ctype(" unsigned \n short \t ") == itk.US try: - itk.ctype("dummy") - raise Exception("unknown C type should send an exception") + itk.ctype("dummy") + raise Exception("unknown C type should send an exception") except KeyError: - pass + pass # test output @@ -73,18 +78,6 @@ assert itk.output(1) == 1 assert itk.image(reader) == reader.GetOutput() assert itk.image(1) == 1 - -# test strel -# should work with the image type, an image instance or a filter -# and should work with a list, a tuple, an int or an itk.Size -for s in [2, (2, 2), [2, 2], itk.Size[2](2)] : - st = itk.strel(dim, s) - - (tpl, param) = itk.template(st) - assert tpl == itk.FlatStructuringElement - assert param[0] == dim - assert st.GetRadius()[0] == st.GetRadius()[1] == 2 - # test size s = itk.size(reader) assert s[0] == s[1] == 256 @@ -145,7 +138,8 @@ assert "Index" not in res # test down_cast obj = itk.Object.cast(reader) -assert obj.__class__ == itk.Object # be sure that the reader is casted to itk::Object +# be sure that the reader is casted to itk::Object +assert obj.__class__ == itk.Object down_casted = itk.down_cast(obj) assert down_casted == reader assert down_casted.__class__ == ReaderType diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/findEmptyClasses.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/findEmptyClasses.py index d1593de5534d5112ac5481f1eb97cf5b9351742d..93b3d67703039b9ba083dbe7b57eb8e296a2b4b8 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/findEmptyClasses.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/findEmptyClasses.py @@ -16,7 +16,11 @@ # #==========================================================================*/ -import itk, re, sys +from __future__ import print_function + +import itk +import re +import sys # itk.auto_progress(True) from itkTemplate import itkTemplate @@ -28,93 +32,97 @@ set = sets.Set # dirty but easier: a global var to count the empty classes empty = set() + def exploreTpl(tpl): for cl in tpl.itervalues(): - print cl + print(cl) exploreMethods(cl) # try to instanciate the class - try : + try: obj = cl.New() exploreMethods(obj) except: pass - try : + try: exploreMethods(cl()) except: pass + def exploreMethods(obj): global count excludeList = ['this', 'thisown'] - attrNameList = [i for i in dir(obj) if isinstance(i, str) and i[0].isupper() and i not in excludeList] - if attrNameList == [] : - empty.add(obj) + attrNameList = [i for i in dir( + obj) if isinstance(i, str) and i[0].isupper() and i not in excludeList] + if attrNameList == []: + empty.add(obj) excluded = set([ - "PeriodicBoundaryCondition", - "BandNode", - "DefaultDynamicMeshTraits", - "DefaultStaticMeshTraits", - "NormalBandNode", - "ZeroFluxNeumannBoundaryCondition", - "SparseFieldLevelSetNode", - "ParallelSparseFieldLevelSetNode", - "PySwigIterator", - "SwigPyIterator", - "COLORS", - "VECTOR_REALS", - "SCALARS", - "ALL_TYPES", - "COMPLEX_REALS", - "RGBS", - "RGBAS", - "REALS", - "USIGN_INTS", - "DIMS", - "SIGN_INTS", - "VECTORS", - "INTS", - "COV_VECTOR_REALS", - "FFTComplexToComplexImageFilter", - "QuadEdgeMeshCellTraitsInfo", - "QuadEdgeMeshTraits", - "OnesMatrixCoefficients", - "ConformalMatrixCoefficients", - "InverseEuclideanDistanceMatrixCoefficients", - "AuthalicMatrixCoefficients", - "IntrinsicMatrixCoefficients", - "InverseEuclideanDistanceMatrixCoefficients", - "OnesMatrixCoefficients", - "ConformalMatrixCoefficients", - "AuthalicMatrixCoefficients", - "MatrixCoefficients", - ]) - - -attrNameList = set([i for i in dir(itk) if i[0].isupper() and len(i) > 2]) - excluded + "PeriodicBoundaryCondition", + "BandNode", + "DefaultDynamicMeshTraits", + "DefaultStaticMeshTraits", + "NormalBandNode", + "ZeroFluxNeumannBoundaryCondition", + "SparseFieldLevelSetNode", + "ParallelSparseFieldLevelSetNode", + "PySwigIterator", + "SwigPyIterator", + "COLORS", + "VECTOR_REALS", + "SCALARS", + "ALL_TYPES", + "COMPLEX_REALS", + "RGBS", + "RGBAS", + "REALS", + "USIGN_INTS", + "DIMS", + "SIGN_INTS", + "VECTORS", + "INTS", + "COV_VECTOR_REALS", + "FFTComplexToComplexImageFilter", + "QuadEdgeMeshCellTraitsInfo", + "QuadEdgeMeshTraits", + "OnesMatrixCoefficients", + "ConformalMatrixCoefficients", + "InverseEuclideanDistanceMatrixCoefficients", + "AuthalicMatrixCoefficients", + "IntrinsicMatrixCoefficients", + "InverseEuclideanDistanceMatrixCoefficients", + "OnesMatrixCoefficients", + "ConformalMatrixCoefficients", + "AuthalicMatrixCoefficients", + "MatrixCoefficients", +]) + + +attrNameList = set( + [i for i in dir(itk) if i[0].isupper() and len(i) > 2]) - excluded for name in attrNameList: # use it because of lazy loading - exec "attr = itk."+name - print "-----------", name, "-----------" - if isinstance(attr, itkTemplate) : + exec "attr = itk." + name + print("-----------", name, "-----------") + if isinstance(attr, itkTemplate): exploreTpl(attr) - else : + else: exploreMethods(attr) - try : + try: exploreMethods(cl.New()) except: pass - try : + try: exploreMethods(cl()) except: pass -print -print -print len(empty), "empty classes found" +print() +print() +print(len(empty), "empty classes found") for c in empty: - print c + print(c) sys.exit(len(empty)) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/findSegfaults.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/findSegfaults.py index e6309b4b05d82ecb94b16b638acaa2763351fa36..377bd73624e5baf97747b126a770efb591307707 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/findSegfaults.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/findSegfaults.py @@ -16,20 +16,40 @@ # #==========================================================================*/ +from __future__ import print_function -import sys, commands, tempfile +import sys +import commands +import tempfile from optparse import OptionParser parser = OptionParser(usage="usage: %prog") -parser.add_option("--start-from", dest="startFrom", default=None, metavar="CLASS", help="") -parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="") -parser.add_option("-k", "--keep", action="store_true", dest="keep", default=False, help="") +parser.add_option( + "--start-from", + dest="startFrom", + default=None, + metavar="CLASS", + help="") +parser.add_option( + "-v", + "--verbose", + action="store_true", + dest="verbose", + default=False, + help="") +parser.add_option( + "-k", + "--keep", + action="store_true", + dest="keep", + default=False, + help="") (options, args) = parser.parse_args() -if options.keep : - mode = "a" +if options.keep: + mode = "a" else: - mode = "w" + mode = "w" segfaultFile = file(args[0], mode) logs = tempfile.NamedTemporaryFile() @@ -37,25 +57,26 @@ logs = tempfile.NamedTemporaryFile() lastClass = options.startFrom ret = 1 while ret != 0: - command = "python returnedTypeCoverage.py -v5 --exclude "+sys.argv[1]+" --log-file '"+logs.name+"'" - if lastClass: - command += " --start-from "+lastClass - if options.verbose: - print command - (ret, output) = commands.getstatusoutput( command ) - if ret != 0: - # find last args (the ones which caused the segfault) - faultyArgs = None - logs.file.seek(0) - for l in reversed(logs.file.readlines()): - l = l.strip() - if faultyArgs == None and l.startswith('('): - faultyArgs = l - if faultyArgs != None : - # find the last class - if len(l) != 0 and l[0].isupper(): - lastClass = l - break - print repr(faultyArgs) - segfaultFile.write(faultyArgs+"\n") - segfaultFile.flush() + command = "python returnedTypeCoverage.py -v5 --exclude " + \ + sys.argv[1] + " --log-file '" + logs.name + "'" + if lastClass: + command += " --start-from " + lastClass + if options.verbose: + print(command) + (ret, output) = commands.getstatusoutput(command) + if ret != 0: + # find last args (the ones which caused the segfault) + faultyArgs = None + logs.file.seek(0) + for l in reversed(logs.file.readlines()): + l = l.strip() + if faultyArgs is None and l.startswith('('): + faultyArgs = l + if faultyArgs is not None: + # find the last class + if len(l) != 0 and l[0].isupper(): + lastClass = l + break + print(repr(faultyArgs)) + segfaultFile.write(faultyArgs + "\n") + segfaultFile.flush() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/getNameOfClass.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/getNameOfClass.py index 698835c8ce0668ca26d4cf829c3335c4d598ea9a..71ecd1af9bdf758544d2619a132b8abb3ef2d030 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/getNameOfClass.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/getNameOfClass.py @@ -18,51 +18,63 @@ # a short program to check the value returned by the GetNameOfClass() methods -import itk, sys +from __future__ import print_function + +import itk +import sys itk.auto_progress(2) # must force the load to return all the names with dir(itk) itk.force_load() # itk.ImageToImageFilter -# a list of classes to exclude. Typically, the classes with a custom New() method, which return a subclass -# of the current class -exclude = ["ForwardFFTImageFilter", "InverseFFTImageFilter", "OutputWindow", "FFTComplexToComplexImageFilter", "templated_class", "HalfHermitianToRealInverseFFTImageFilter", "RealToHalfHermitianForwardFFTImageFilter"] +# a list of classes to exclude. Typically, the classes with a custom New() +# method, which return a subclass of the current class +exclude = ["ForwardFFTImageFilter", + "InverseFFTImageFilter", + "OutputWindow", + "FFTComplexToComplexImageFilter", + "templated_class", + "HalfHermitianToRealInverseFFTImageFilter", + "RealToHalfHermitianForwardFFTImageFilter"] wrongName = False for t in dir(itk): - if t not in exclude: - T = itk.__dict__[t] - # first case - that's a templated class - if isinstance(T, itk.Vector.__class__) and len(T)>0: - # use only the first specialization - all of them return the same name - i = T.values()[0] - # GetNameOfClass() is a virtual method of the LightObject class, so we must - # instantiate an object with the New() method - if 'New' in dir(i): - I = i.New() - # be sure that the type of the instantiated object is the same than the - # one of the class. It can be different if the class is an "abstract" one - # and don't provide any New() method. In that case, the one of the superclass - # is used. - if 'GetNameOfClass' in dir(I): - # print "Checking", t - n = I.GetNameOfClass() - if n != t and itk.class_(I) == i: - print >> sys.stderr, t, "doesn't provide the right name." - wrongName = True - else: - if 'New' in dir(T): - I = T.New() - if 'GetNameOfClass' in dir(I): - # print "Checking", t - n = I.GetNameOfClass() - if n != t and itk.class_(I) == T: - print >> sys.stderr, t, "doesn't provide the right name." - wrongName = True + if t not in exclude: + T = itk.__dict__[t] + # first case - that's a templated class + if isinstance(T, itk.Vector.__class__) and len(T) > 0: + # use only the first specialization - all of them return the same + # name + i = T.values()[0] + # GetNameOfClass() is a virtual method of the LightObject class, + # so we must instantiate an object with the New() method + if 'New' in dir(i): + I = i.New() + # be sure that the type of the instantiated object is the same + # than the one of the class. It can be different if the class + # is an "abstract" one and don't provide any New() method. + # In that case, the one of the superclass is used. + if 'GetNameOfClass' in dir(I): + # print("Checking", t) + n = I.GetNameOfClass() + if n != t and itk.class_(I) == i: + msg = "doesn't provide the right name." + print(t, msg, file=sys.stderr) + wrongName = True + else: + if 'New' in dir(T): + I = T.New() + if 'GetNameOfClass' in dir(I): + # print("Checking", t) + n = I.GetNameOfClass() + if n != t and itk.class_(I) == T: + msg = "doesn't provide the right name." + print(t, msg, file=sys.stderr) + wrongName = True if wrongName: - print >> sys.stderr, "Some classes are not providing the correct name." - sys.exit(1) + print("Some classes are not providing the correct name.", file=sys.stderr) + sys.exit(1) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/module2module.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/module2module.py index d577fcff79bf3e1698910839e596178c9aa5fe82..d1ef6d5765a233dc298294ed8d4ca0b3a0acde5b 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/module2module.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/module2module.py @@ -16,12 +16,10 @@ # #==========================================================================*/ -# def custom_callback(name): -# print "loading %s submodule..." % name -# import itkConfig -# itkConfig.ImportCallback = custom_callback +from __future__ import print_function -import itk, sys +import itk +import sys import ITKCommon import ITKBinaryMathematicalMorphology @@ -29,112 +27,109 @@ import ITKImageStatistics import ITKSmoothing import ITKDistanceMap import ITKImageIntensity -import ITKIOImageBase import ITKThresholding import ITKImageGrid -PType = itk.UC -dim = 2 -IType = itk.Image[PType, dim] +inputImage = sys.argv[1] +radiusValue = int(sys.argv[2]) -kernel = itk.strel(2, 1) +PixelType = itk.UC +Dimension = 2 +ImageType = itk.Image[PixelType, Dimension] + +StructuringElementType = itk.FlatStructuringElement[Dimension] +radius = (radiusValue, radiusValue) +structuringElement = StructuringElementType.Ball(radius) # create the reader -reader = itk.ImageFileReader[IType].New(FileName=sys.argv[1]) +reader = itk.ImageFileReader[ImageType].New(FileName=inputImage) sources = [] -image = ITKCommon.Image[PType, dim].New() -r = itk.ImageRegion._2() -r.SetSize((10, 10)) -image.SetRegions(r) +image = ITKCommon.Image[PixelType, Dimension].New() +region = itk.ImageRegion._2() +region.SetSize((10, 10)) +image.SetRegions(region) image.Allocate() sources.append(("ITKCommon", image)) sources.append(("ITKIOImageBase", reader.GetOutput())) -otsu = ITKThresholding.OtsuThresholdImageFilter[IType, IType].New(reader) +OtsuType = ITKThresholding.OtsuThresholdImageFilter[ImageType, ImageType] +otsu = OtsuType.New(reader) sources.append(("ITKThresholding", otsu.GetOutput())) -flip = ITKImageGrid.FlipImageFilter[IType].New(reader) +flip = ITKImageGrid.FlipImageFilter[ImageType].New(reader) sources.append(("ITKImageGrid", flip.GetOutput())) -abs = ITKImageIntensity.AbsImageFilter[IType, IType].New(reader) -sources.append(("ITKImageIntensity", abs.GetOutput())) +absFilter = ITKImageIntensity.AbsImageFilter[ImageType, ImageType].New(reader) +sources.append(("ITKImageIntensity", absFilter.GetOutput())) +absFilter.InPlaceOff() + +BinaryDilateType = ITKBinaryMathematicalMorphology.BinaryDilateImageFilter[ + ImageType, ImageType, StructuringElementType] +binaryDilateFilter = BinaryDilateType.New() +binaryDilateFilter.SetInput(reader.GetOutput()) +binaryDilateFilter.SetKernel(structuringElement) -bdilate = ITKBinaryMathematicalMorphology.BinaryDilateImageFilter[IType, IType, kernel].New(reader, Kernel=kernel) -sources.append(("ITKBinaryMathematicalMorphology", bdilate.GetOutput())) +output = binaryDilateFilter.GetOutput() +sources.append(("ITKBinaryMathematicalMorphology", output)) -minmax = ITKImageStatistics.MinimumMaximumImageFilter[IType].New(reader) +minmax = ITKImageStatistics.MinimumMaximumImageFilter[ImageType].New(reader) sources.append(("ITKImageStatistics", minmax.GetOutput())) -median = ITKSmoothing.MedianImageFilter[IType, IType].New(reader) +median = ITKSmoothing.MedianImageFilter[ImageType, ImageType].New(reader) sources.append(("ITKSmoothing", median.GetOutput())) -distance = ITKDistanceMap.DanielssonDistanceMapImageFilter[IType, IType].New(reader) +distance = ITKDistanceMap.DanielssonDistanceMapImageFilter[ + ImageType, ImageType].New(reader) sources.append(("ITKDistanceMap", distance.GetOutput())) -# sobel = EdgesAndContours.SobelEdgeDetectionImageFilter[IType, IType].New(reader) -# sources.append(("EdgesAndContours", sobel.GetOutput())) - -# laplacian = Filtering.LaplacianImageFilter[IType, IType].New(reader) -# sources.append(("Filtering", laplacian.GetOutput())) - - - - - - dests = [] -dotsu = ITKThresholding.OtsuThresholdImageFilter[IType, IType].New(reader) +dotsu = OtsuType.New() dests.append(("ITKThresholding", dotsu)) -dflip = ITKImageGrid.FlipImageFilter[IType].New() +dflip = ITKImageGrid.FlipImageFilter[ImageType].New() dests.append(("ITKImageGrid", dflip)) -dabs = ITKImageIntensity.AbsImageFilter[IType, IType].New() +dabs = ITKImageIntensity.AbsImageFilter[ImageType, ImageType].New() dests.append(("ITKImageIntensity", dabs)) -dbdilate = ITKBinaryMathematicalMorphology.BinaryDilateImageFilter[IType, IType, kernel].New(Kernel=kernel) -dests.append(("ITKBinaryMathematicalMorphology", dbdilate)) +dbinaryDilateFilter = BinaryDilateType.New() +dbinaryDilateFilter.SetKernel(structuringElement) +dests.append(("ITKBinaryMathematicalMorphology", dbinaryDilateFilter)) -dminmax = ITKImageStatistics.MinimumMaximumImageFilter[IType].New() +dminmax = ITKImageStatistics.MinimumMaximumImageFilter[ImageType].New() dests.append(("ITKImageStatistics", dminmax)) -dmedian = ITKSmoothing.MedianImageFilter[IType, IType].New() +dmedian = ITKSmoothing.MedianImageFilter[ImageType, ImageType].New() dests.append(("ITKSmoothing", dmedian)) -ddistance = ITKDistanceMap.DanielssonDistanceMapImageFilter[IType, IType].New() +DistanceMapType = ITKDistanceMap.DanielssonDistanceMapImageFilter[ImageType, + ImageType] +ddistance = DistanceMapType.New() dests.append(("ITKDistanceMap", ddistance)) -# dsobel = EdgesAndContours.SobelEdgeDetectionImageFilter[IType, IType].New() -# dests.append(("EdgesAndContours", dsobel)) - -# dlaplacian = Filtering.LaplacianImageFilter[IType, IType].New() -# dests.append(("Filtering", dlaplacian)) - -writer = ITKIOImageBase.ImageFileWriter[IType].New(FileName='out.png') -dests.append(("ITKIOImageBase", writer)) - nb = 0 failList = [] -for sname, s in sources: - for dname, d in dests: - nb += 1 - d.SetInput( s ) - try: - d.Update() - print "%s -> %s pass" % (sname, dname) - except RuntimeError, e: - print "%s -> %s fail" % (sname, dname) - failList.append((sname, dname)) - - -print -print "%i tests succeed" % (nb - len(failList)) -print "%i tests failed" % len(failList) +for sourceName, source in sources: + for destinationName, destination in dests: + nb += 1 + destination.SetInput(source) + try: + destination.UpdateLargestPossibleRegion() + print("%s -> %s pass" % (sourceName, destinationName)) + except RuntimeError as e: + print("%s -> %s fail" % (sourceName, destinationName)) + print(e) + failList.append((sourceName, destinationName)) + + +print() +print("%i tests succeed" % (nb - len(failList))) +print("%i tests failed" % len(failList)) sys.exit(len(failList)) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/DicomSliceRead.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/DicomSliceRead.py index e5901fe0478073c935a45bfa99fe03378a200d96..48a8d35194464f0c5b989b3f6be316d8ad3b3bc0 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/DicomSliceRead.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/DicomSliceRead.py @@ -34,17 +34,17 @@ writer = itkImageFileWriterUC2_New() dicomIO = itkDicomImageIO_New() -reader.SetImageIO( dicomIO.GetPointer() ) +reader.SetImageIO(dicomIO.GetPointer()) -filter = itkRescaleIntensityImageFilterUS2UC2_New() +filter = itkRescaleIntensityImageFilterUS2UC2_New() -filter.SetOutputMinimum( 0 ) +filter.SetOutputMinimum(0) filter.SetOutputMaximum(255) -filter.SetInput( reader.GetOutput() ) -writer.SetInput( filter.GetOutput() ) +filter.SetInput(reader.GetOutput()) +writer.SetInput(filter.GetOutput()) -reader.SetFileName( argv[1] ) -writer.SetFileName( argv[2] ) +reader.SetFileName(argv[1]) +writer.SetFileName(argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration3.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration3.py index aa780d87789ddddd2e6430e0270e9d69b455f2d0..98c52843c37af1f348143f501ecc47df7e99110a 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration3.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration3.py @@ -21,71 +21,69 @@ from InsightToolkit import * from sys import argv - # # Read the fixed and moving images using filenames # from the command line arguments # -fixedImageReader = itkImageFileReaderF2_New() +fixedImageReader = itkImageFileReaderF2_New() movingImageReader = itkImageFileReaderF2_New() -fixedImageReader.SetFileName( argv[1] ) -movingImageReader.SetFileName( argv[2] ) +fixedImageReader.SetFileName(argv[1]) +movingImageReader.SetFileName(argv[2]) fixedImageReader.Update() movingImageReader.Update() -fixedImage = fixedImageReader.GetOutput() +fixedImage = fixedImageReader.GetOutput() movingImage = movingImageReader.GetOutput() - - # # Instantiate the classes for the registration framework # registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMeanSquaresImageToImageMetricF2F2_New() -transform = itkTranslationTransform2_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() +imageMetric = itkMeanSquaresImageToImageMetricF2F2_New() +transform = itkTranslationTransform2_New() +optimizer = itkRegularStepGradientDescentOptimizer_New() interpolator = itkLinearInterpolateImageFunctionF2D_New() -registration.SetOptimizer( optimizer.GetPointer() ) -registration.SetTransform( transform.GetPointer() ) -registration.SetInterpolator( interpolator.GetPointer() ) -registration.SetMetric( imageMetric.GetPointer() ) -registration.SetFixedImage( fixedImage ) -registration.SetMovingImage( movingImage ) +registration.SetOptimizer(optimizer.GetPointer()) +registration.SetTransform(transform.GetPointer()) +registration.SetInterpolator(interpolator.GetPointer()) +registration.SetMetric(imageMetric.GetPointer()) +registration.SetFixedImage(fixedImage) +registration.SetMovingImage(movingImage) -registration.SetFixedImageRegion( fixedImage.GetBufferedRegion() ) +registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) transform.SetIdentity() initialParameters = transform.GetParameters() -registration.SetInitialTransformParameters( initialParameters ) +registration.SetInitialTransformParameters(initialParameters) # # Iteration Observer # + + def iterationUpdate(): currentParameter = transform.GetParameters() - print "M: %f P: %f %f " % ( optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1) ) + print "M: %f P: %f %f " % (optimizer.GetValue(), + currentParameter.GetElement(0), + currentParameter.GetElement(1)) iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable( iterationUpdate ) -optimizer.AddObserver( itkIterationEvent(), iterationCommand.GetPointer() ) - +iterationCommand.SetCommandCallable(iterationUpdate) +optimizer.AddObserver(itkIterationEvent(), iterationCommand.GetPointer()) # # Define optimizer parameters # -optimizer.SetMaximumStepLength( 4.00 ) -optimizer.SetMinimumStepLength( 0.01 ) -optimizer.SetNumberOfIterations( 200 ) +optimizer.SetMaximumStepLength(4.00) +optimizer.SetMinimumStepLength(0.01) +optimizer.SetNumberOfIterations(200) print "Starting registration" @@ -107,27 +105,25 @@ print "Translation X = %f" % (finalParameters.GetElement(0),) print "Translation Y = %f" % (finalParameters.GetElement(1),) - - # # Now, we use the final transform for resampling the # moving image. # resampler = itkResampleImageFilterF2F2_New() -resampler.SetTransform( transform.GetPointer() ) -resampler.SetInput( movingImage ) +resampler.SetTransform(transform.GetPointer()) +resampler.SetInput(movingImage) region = fixedImage.GetLargestPossibleRegion() -resampler.SetSize( region.GetSize() ) +resampler.SetSize(region.GetSize()) -resampler.SetOutputSpacing( fixedImage.GetSpacing() ) -resampler.SetOutputOrigin( fixedImage.GetOrigin() ) -resampler.SetDefaultPixelValue( 100 ) +resampler.SetOutputSpacing(fixedImage.GetSpacing()) +resampler.SetOutputOrigin(fixedImage.GetOrigin()) +resampler.SetDefaultPixelValue(100) outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetOutputMinimum( 0 ) -outputCast.SetOutputMaximum( 65535 ) +outputCast.SetOutputMinimum(0) +outputCast.SetOutputMaximum(65535) outputCast.SetInput(resampler.GetOutput()) # @@ -135,6 +131,6 @@ outputCast.SetInput(resampler.GetOutput()) # writer = itkImageFileWriterUS2_New() -writer.SetFileName( argv[3] ) -writer.SetInput( outputCast.GetOutput() ) +writer.SetFileName(argv[3]) +writer.SetInput(outputCast.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration4.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration4.py index fcc5a8a4021854b82e223f5a70e920af90ce2530..eabcab742f578ea247852f19a35f924253174fa4 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration4.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration4.py @@ -21,74 +21,72 @@ from InsightToolkit import * from sys import argv - # # Read the fixed and moving images using filenames # from the command line arguments # -fixedImageReader = itkImageFileReaderF2_New() +fixedImageReader = itkImageFileReaderF2_New() movingImageReader = itkImageFileReaderF2_New() -fixedImageReader.SetFileName( argv[1] ) -movingImageReader.SetFileName( argv[2] ) +fixedImageReader.SetFileName(argv[1]) +movingImageReader.SetFileName(argv[2]) fixedImageReader.Update() movingImageReader.Update() -fixedImage = fixedImageReader.GetOutput() +fixedImage = fixedImageReader.GetOutput() movingImage = movingImageReader.GetOutput() - - # # Instantiate the classes for the registration framework # registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMattesMutualInformationImageToImageMetricF2F2_New() -transform = itkTranslationTransform2_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() +imageMetric = itkMattesMutualInformationImageToImageMetricF2F2_New() +transform = itkTranslationTransform2_New() +optimizer = itkRegularStepGradientDescentOptimizer_New() interpolator = itkLinearInterpolateImageFunctionF2D_New() -imageMetric.SetNumberOfHistogramBins( 20 ); -imageMetric.SetNumberOfSpatialSamples( 10000 ); +imageMetric.SetNumberOfHistogramBins(20) +imageMetric.SetNumberOfSpatialSamples(10000) -registration.SetOptimizer( optimizer.GetPointer() ) -registration.SetTransform( transform.GetPointer() ) -registration.SetInterpolator( interpolator.GetPointer() ) -registration.SetMetric( imageMetric.GetPointer() ) -registration.SetFixedImage( fixedImage ) -registration.SetMovingImage( movingImage ) +registration.SetOptimizer(optimizer.GetPointer()) +registration.SetTransform(transform.GetPointer()) +registration.SetInterpolator(interpolator.GetPointer()) +registration.SetMetric(imageMetric.GetPointer()) +registration.SetFixedImage(fixedImage) +registration.SetMovingImage(movingImage) -registration.SetFixedImageRegion( fixedImage.GetBufferedRegion() ) +registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) transform.SetIdentity() initialParameters = transform.GetParameters() -registration.SetInitialTransformParameters( initialParameters ) +registration.SetInitialTransformParameters(initialParameters) # # Iteration Observer # + + def iterationUpdate(): currentParameter = transform.GetParameters() - print "M: %f P: %f %f " % ( optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1) ) + print "M: %f P: %f %f " % (optimizer.GetValue(), + currentParameter.GetElement(0), + currentParameter.GetElement(1)) iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable( iterationUpdate ) -optimizer.AddObserver( itkIterationEvent(), iterationCommand.GetPointer() ) - +iterationCommand.SetCommandCallable(iterationUpdate) +optimizer.AddObserver(itkIterationEvent(), iterationCommand.GetPointer()) # # Define optimizer parameters # -optimizer.SetMaximumStepLength( 4.00 ) -optimizer.SetMinimumStepLength( 0.01 ) -optimizer.SetNumberOfIterations( 200 ) +optimizer.SetMaximumStepLength(4.00) +optimizer.SetMinimumStepLength(0.01) +optimizer.SetNumberOfIterations(200) print "Starting registration" @@ -110,27 +108,25 @@ print "Translation X = %f" % (finalParameters.GetElement(0),) print "Translation Y = %f" % (finalParameters.GetElement(1),) - - # # Now, we use the final transform for resampling the # moving image. # resampler = itkResampleImageFilterF2F2_New() -resampler.SetTransform( transform.GetPointer() ) -resampler.SetInput( movingImage ) +resampler.SetTransform(transform.GetPointer()) +resampler.SetInput(movingImage) region = fixedImage.GetLargestPossibleRegion() -resampler.SetSize( region.GetSize() ) +resampler.SetSize(region.GetSize()) -resampler.SetOutputSpacing( fixedImage.GetSpacing() ) -resampler.SetOutputOrigin( fixedImage.GetOrigin() ) -resampler.SetDefaultPixelValue( 100 ) +resampler.SetOutputSpacing(fixedImage.GetSpacing()) +resampler.SetOutputOrigin(fixedImage.GetOrigin()) +resampler.SetDefaultPixelValue(100) outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetOutputMinimum( 0 ) -outputCast.SetOutputMaximum( 65535 ) +outputCast.SetOutputMinimum(0) +outputCast.SetOutputMaximum(65535) outputCast.SetInput(resampler.GetOutput()) # @@ -138,6 +134,6 @@ outputCast.SetInput(resampler.GetOutput()) # writer = itkImageFileWriterUS2_New() -writer.SetFileName( argv[3] ) -writer.SetInput( outputCast.GetOutput() ) +writer.SetFileName(argv[3]) +writer.SetInput(outputCast.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration5.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration5.py index 6a3e4dd15976bdcf55220b211c00a6a51a683b6e..a90c5ae642d273b0a66f311bea7c20c325d546c5 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration5.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageRegistration5.py @@ -29,8 +29,8 @@ from sys import argv fixedImageReader = itkImageFileReaderF2_New() movingImageReader = itkImageFileReaderF2_New() -fixedImageReader.SetFileName( argv[1] ) -movingImageReader.SetFileName( argv[2] ) +fixedImageReader.SetFileName(argv[1]) +movingImageReader.SetFileName(argv[2]) fixedImageReader.Update() movingImageReader.Update() @@ -41,60 +41,68 @@ movingImage = movingImageReader.GetOutput() # # Instantiate the classes for the registration framework # -registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMeanSquaresImageToImageMetricF2F2_New() -transform = itkCenteredRigid2DTransform_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() -interpolator = itkLinearInterpolateImageFunctionF2D_New() +registration = itkImageRegistrationMethodF2F2_New() +imageMetric = itkMeanSquaresImageToImageMetricF2F2_New() +transform = itkCenteredRigid2DTransform_New() +optimizer = itkRegularStepGradientDescentOptimizer_New() +interpolator = itkLinearInterpolateImageFunctionF2D_New() -registration.SetOptimizer( optimizer.GetPointer() ) -registration.SetTransform( transform.GetPointer() ) -registration.SetInterpolator( interpolator.GetPointer() ) -registration.SetMetric( imageMetric.GetPointer() ) -registration.SetFixedImage( fixedImage ) -registration.SetMovingImage( movingImage ) -registration.SetFixedImageRegion( fixedImage.GetBufferedRegion() ) +registration.SetOptimizer(optimizer.GetPointer()) +registration.SetTransform(transform.GetPointer()) +registration.SetInterpolator(interpolator.GetPointer()) +registration.SetMetric(imageMetric.GetPointer()) +registration.SetFixedImage(fixedImage) +registration.SetMovingImage(movingImage) +registration.SetFixedImageRegion(fixedImage.GetBufferedRegion()) # # Initial transform parameters # -transform.SetAngle( 0.0 ); +transform.SetAngle(0.0) # center of the fixed image fixedSpacing = fixedImage.GetSpacing() fixedOrigin = fixedImage.GetOrigin() fixedSize = fixedImage.GetLargestPossibleRegion().GetSize() -centerFixed = ( fixedOrigin.GetElement(0) + fixedSpacing.GetElement(0) * fixedSize.GetElement(0) / 2.0, - fixedOrigin.GetElement(1) + fixedSpacing.GetElement(1) * fixedSize.GetElement(1) / 2.0 ) +centerFixed = ( + fixedOrigin.GetElement(0) + fixedSpacing.GetElement(0) * + fixedSize.GetElement(0) / 2.0, + fixedOrigin.GetElement(1) + fixedSpacing.GetElement(1) * + fixedSize.GetElement(1) / 2.0) # center of the moving image movingSpacing = movingImage.GetSpacing() movingOrigin = movingImage.GetOrigin() movingSize = movingImage.GetLargestPossibleRegion().GetSize() -centerMoving = ( movingOrigin.GetElement(0) + movingSpacing.GetElement(0) * movingSize.GetElement(0) / 2.0, - movingOrigin.GetElement(1) + movingSpacing.GetElement(1) * movingSize.GetElement(1) / 2.0 ) +centerMoving = ( + movingOrigin.GetElement(0) + movingSpacing.GetElement(0) * + movingSize.GetElement(0) / 2.0, + movingOrigin.GetElement(1) + movingSpacing.GetElement(1) * + movingSize.GetElement(1) / 2.0) # transform center center = transform.GetCenter() -center.SetElement( 0, centerFixed[0] ) -center.SetElement( 1, centerFixed[1] ) +center.SetElement(0, centerFixed[0]) +center.SetElement(1, centerFixed[1]) # transform translation translation = transform.GetTranslation() -translation.SetElement( 0, centerMoving[0] - centerFixed[0] ) -translation.SetElement( 1, centerMoving[1] - centerFixed[1] ) +translation.SetElement(0, centerMoving[0] - centerFixed[0]) +translation.SetElement(1, centerMoving[1] - centerFixed[1]) initialParameters = transform.GetParameters() print "Initial Parameters: " print "Angle: %f" % (initialParameters.GetElement(0), ) -print "Center: %f, %f" % ( initialParameters.GetElement(1), initialParameters.GetElement(2) ) -print "Translation: %f, %f" % (initialParameters.GetElement(3), initialParameters.GetElement(4)) +print "Center: %f, %f" % (initialParameters.GetElement(1), + initialParameters.GetElement(2)) +print "Translation: %f, %f" % (initialParameters.GetElement(3), + initialParameters.GetElement(4)) -registration.SetInitialTransformParameters( initialParameters ) +registration.SetInitialTransformParameters(initialParameters) # # Define optimizer parameters @@ -103,33 +111,35 @@ registration.SetInitialTransformParameters( initialParameters ) # optimizer scale translationScale = 1.0 / 1000.0 -optimizerScales = itkArrayD( transform.GetNumberOfParameters() ) +optimizerScales = itkArrayD(transform.GetNumberOfParameters()) optimizerScales.SetElement(0, 1.0) optimizerScales.SetElement(1, translationScale) optimizerScales.SetElement(2, translationScale) optimizerScales.SetElement(3, translationScale) optimizerScales.SetElement(4, translationScale) -optimizer.SetScales( optimizerScales ) -optimizer.SetMaximumStepLength( 0.1 ) -optimizer.SetMinimumStepLength( 0.001 ) -optimizer.SetNumberOfIterations( 200 ) +optimizer.SetScales(optimizerScales) +optimizer.SetMaximumStepLength(0.1) +optimizer.SetMinimumStepLength(0.001) +optimizer.SetNumberOfIterations(200) # # Iteration Observer # + + def iterationUpdate(): currentParameter = transform.GetParameters() - print "M: %f P: %f %f %f %f %f " % ( optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1), - currentParameter.GetElement(2), - currentParameter.GetElement(3), - currentParameter.GetElement(4) ) + print "M: %f P: %f %f %f %f %f " % (optimizer.GetValue(), + currentParameter.GetElement(0), + currentParameter.GetElement(1), + currentParameter.GetElement(2), + currentParameter.GetElement(3), + currentParameter.GetElement(4)) iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable( iterationUpdate ) -optimizer.AddObserver( itkIterationEvent(), iterationCommand.GetPointer() ) +iterationCommand.SetCommandCallable(iterationUpdate) +optimizer.AddObserver(itkIterationEvent(), iterationCommand.GetPointer()) print "Starting registration" @@ -154,26 +164,26 @@ print "Translation in Y = %f" % finalParameters.GetElement(4) # Now, we use the final transform for resampling the moving image. resampler = itkResampleImageFilterF2F2_New() -resampler.SetTransform( transform.GetPointer() ) -resampler.SetInput( movingImage ) +resampler.SetTransform(transform.GetPointer()) +resampler.SetInput(movingImage) region = fixedImage.GetLargestPossibleRegion() -resampler.SetSize( region.GetSize() ) -resampler.SetOutputSpacing( fixedImage.GetSpacing() ) -resampler.SetOutputOrigin( fixedImage.GetOrigin() ) -resampler.SetDefaultPixelValue( 100 ) +resampler.SetSize(region.GetSize()) +resampler.SetOutputSpacing(fixedImage.GetSpacing()) +resampler.SetOutputOrigin(fixedImage.GetOrigin()) +resampler.SetDefaultPixelValue(100) # # Cast for output # outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetInput( resampler.GetOutput() ) -outputCast.SetOutputMinimum( 0 ) -outputCast.SetOutputMaximum( 65535 ) +outputCast.SetInput(resampler.GetOutput()) +outputCast.SetOutputMinimum(0) +outputCast.SetOutputMaximum(65535) writer = itkImageFileWriterUS2_New() -writer.SetFileName( argv[3] ) -writer.SetInput( outputCast.GetOutput() ) +writer.SetFileName(argv[3]) +writer.SetInput(outputCast.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageToArray.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageToArray.py index 5bbbb43a25f3232ff6d98811c7e45c6fb3a5a3ae..66ef5aa2a3b7621fe5442e78d62ad4421febcdcd 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageToArray.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/ImageToArray.py @@ -24,20 +24,20 @@ reader = itkImageFileReaderUC2_New() connector = itkPyBufferUC2_New() -reader.SetFileName( argv[1] ) +reader.SetFileName(argv[1]) reader.Update() print "ready to convert image into array" -buffer = connector.GetArrayFromImage( reader.GetOutput() ) +buffer = connector.GetArrayFromImage(reader.GetOutput()) writer = itkImageFileWriterUC2_New() -writer.SetFileName( argv[2] ) +writer.SetFileName(argv[2]) print "ready to convert array into image" -writer.SetInput( connector.GetImageFromArray( buffer ) ) +writer.SetInput(connector.GetImageFromArray(buffer)) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/VoronoiSegmentation.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/VoronoiSegmentation.py index f5b3cd7def87c985928fde295c47c71bc7193d0c..4b8f655c9c9ab811cb5254e4bb559f6cdcad2911 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/VoronoiSegmentation.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/VoronoiSegmentation.py @@ -28,22 +28,22 @@ from sys import argv readerInput = itkImageFileReaderUC2_New() readerPrior = itkImageFileReaderUC2_New() -readerInput.SetFileName( argv[1] ) -readerPrior.SetFileName( argv[2] ) +readerInput.SetFileName(argv[1]) +readerPrior.SetFileName(argv[2]) readerInput.Update() readerPrior.Update() -filter = itkVoronoiSegmentationImageFilterUC2UC2UC2_New() +filter = itkVoronoiSegmentationImageFilterUC2UC2UC2_New() -filter.SetInput( readerInput.GetOutput() ) -filter.TakeAPrior( readerPrior.GetOutput() ) +filter.SetInput(readerInput.GetOutput()) +filter.TakeAPrior(readerPrior.GetOutput()) -filter.SetMeanPercentError( eval( argv[4] ) ) -filter.SetSTDPercentError( eval( argv[5] ) ) +filter.SetMeanPercentError(eval(argv[4])) +filter.SetSTDPercentError(eval(argv[5])) writer = itkImageFileWriterUC2_New() -writer.SetFileName( argv[3] ) -writer.SetInput( filter.GetOutput() ) +writer.SetFileName(argv[3]) +writer.SetInput(filter.GetOutput()) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/itkCurvatureFlowTestPython2.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/itkCurvatureFlowTestPython2.py index 71904b24e9b5cd46d53e36fb3f0d954f5bd61515..453e2ec99a2dd57fe7dab3ea96d58f3ee5406334 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/itkCurvatureFlowTestPython2.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/notYetUsable/itkCurvatureFlowTestPython2.py @@ -17,95 +17,112 @@ #==========================================================================*/ from InsightToolkit import * -import itktesting +import itkTesting import sys import os import shutil -basename = os.path.basename( sys.argv[0] ) -name = os.path.splitext( basename )[0] -dir = "Algorithms" +basename = os.path.basename(sys.argv[0]) +name = os.path.splitext(basename)[0] +dir = "Algorithms" -testInput = itktesting.ITK_TEST_INPUT -testOutput = itktesting.ITK_TEST_OUTPUT -baseLine = itktesting.ITK_TEST_BASELINE +testInput = itkTesting.ITK_TEST_INPUT +testOutput = itkTesting.ITK_TEST_OUTPUT +baseLine = itkTesting.ITK_TEST_BASELINE reader = itkImageFileReaderF2_New() -reader.SetFileName( testInput+"/cthead1.png") +reader.SetFileName(testInput + "/cthead1.png") -cf = itkCurvatureFlowImageFilterF2F2_New() -cf.SetInput( reader.GetOutput() ) -cf.SetTimeStep( 0.25 ) -cf.SetNumberOfIterations( 10 ) +cf = itkCurvatureFlowImageFilterF2F2_New() +cf.SetInput(reader.GetOutput()) +cf.SetTimeStep(0.25) +cf.SetNumberOfIterations(10) -cfss = itkShiftScaleImageFilterF2US2_New() -cfss.SetInput( cf.GetOutput() ) -cfss.SetShift( 0.7 ) -cfss.SetScale( 0.9 ) +cfss = itkShiftScaleImageFilterF2US2_New() +cfss.SetInput(cf.GetOutput()) +cfss.SetShift(0.7) +cfss.SetScale(0.9) -valid = itkImageFileReaderUS2_New() -valid.SetFileName( baseLine+"/"+dir+"/"+name+".png") +valid = itkImageFileReaderUS2_New() +valid.SetFileName(baseLine + "/" + dir + "/" + name + ".png") -diff = itkDifferenceImageFilterUS2_New() -diff.SetValidInput( valid.GetOutput() ) -diff.SetTestInput( cfss.GetOutput() ) -diff.SetToleranceRadius( 1 ) -diff.SetDifferenceThreshold( 0 ) +diff = itkDifferenceImageFilterUS2_New() +diff.SetValidInput(valid.GetOutput()) +diff.SetTestInput(cfss.GetOutput()) +diff.SetToleranceRadius(1) +diff.SetDifferenceThreshold(0) diff.Update() -meanDiff = diff.GetMeanDifference() +meanDiff = diff.GetMeanDifference() totalDiff = diff.GetTotalDifference() -print "MeanDifference = ", meanDiff -print "TotalDifference = ", totalDiff - - -print "<DartMeasurement name=\"MeanDifference\" type=\"numeric/double\">",meanDiff,"</DartMeasurement>" -print "<DartMeasurement name=\"TotalDifference\" type=\"numeric/double\">",totalDiff,"</DartMeasurement>" - -if ( meanDiff > 0.1 ) : - convert = itkCastImageFilterUS2UC2_New() - rescale = itkRescaleIntensityImageFilterUS2UC2_New() - rescale.SetInput( diff.GetOutput() ) - rescale.SetOutputMinimum( 0 ) - rescale.SetOutputMaximum( 255 ) - - io = itkPNGImageIO_New() - io.SetUseCompression( 1 ) - io.SetCompressionLevel( 9 ) - - writer = itkImageFileWriterUC2_New() - writer.SetImageIO( io.GetPointer() ) - writer.SetInput( convert.GetOutput() ) - - writer.SetFileName( testOutput+"/"+name+".test.png" ) - convert.SetInput( cfss.GetOutput() ) - writer.Write() - - writer.SetFileName( testOutput+"/"+name+".diff.png" ) - writer.SetInput( rescale.GetOutput() ) - writer.Write() - - shutil.copyfile( baseLine+"/"+dir+"/"+name+".png", testOutput+"/"+name+".valid.png" ) - - print "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">"+testOutput+"/"+name+".test.png</DartMeasurementFile>" - print "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">"+testOutput+"/"+name+".diff.png</DartMeasurementFile>" - print "<DartMeasurementFile name=\"ValidImage\" type=\"image/png\">"+testOutput+"/"+name+".valid.png</DartMeasurementFile>" - print "<DartMeasurement name=\"DifferenceShift\" type=\"numeric/double\">",rescale.GetShift(),"</DartMeasurement>" - print "<DartMeasurement name=\"DifferenceScale\" type=\"numeric/double\">",rescale.GetScale(),"</DartMeasurement>" +print("MeanDifference = ", meanDiff) +print("TotalDifference = ", totalDiff) + + +print ("<DartMeasurement name=\"MeanDifference\" type=\"numeric/double\">", + meanDiff, "</DartMeasurement>") +print ("<DartMeasurement name=\"TotalDifference\" type=\"numeric/double\">", + totalDiff, "</DartMeasurement>") + +if (meanDiff > 0.1): + convert = itkCastImageFilterUS2UC2_New() + rescale = itkRescaleIntensityImageFilterUS2UC2_New() + rescale.SetInput(diff.GetOutput()) + rescale.SetOutputMinimum(0) + rescale.SetOutputMaximum(255) + + io = itkPNGImageIO_New() + io.SetUseCompression(1) + io.SetCompressionLevel(9) + + writer = itkImageFileWriterUC2_New() + writer.SetImageIO(io.GetPointer()) + writer.SetInput(convert.GetOutput()) + + writer.SetFileName(testOutput + "/" + name + ".test.png") + convert.SetInput(cfss.GetOutput()) + writer.Write() + + writer.SetFileName(testOutput + "/" + name + ".diff.png") + writer.SetInput(rescale.GetOutput()) + writer.Write() + + shutil.copyfile( + baseLine + + "/" + + dir + + "/" + + name + + ".png", + testOutput + + "/" + + name + + ".valid.png") + + print ("<DartMeasurementFile name=\"TestImage\" type=\"image/png\">" + + testOutput + "/" + name + ".test.png</DartMeasurementFile>") + print ("<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">" + + testOutput + "/" + name + ".diff.png</DartMeasurementFile>") + print ("<DartMeasurementFile name=\"ValidImage\" type=\"image/png\">" + + testOutput + "/" + name + ".valid.png</DartMeasurementFile>") + pr = "<DartMeasurement name=\"DifferenceShift\" type=\"numeric/double\">" + print (pr, rescale.GetShift(), "</DartMeasurement>") + pr = "<DartMeasurement name=\"DifferenceScale\" type=\"numeric/double\">" + print (pr, rescale.GetScale(), "</DartMeasurement>") # return 1 -#return 0 +# return 0 diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/pythonTestDriver.py.in b/Utilities/ITK/Wrapping/Generators/Python/Tests/pythonTestDriver.py.in index 408ece648655113218bda57bfab019f8cc743c6e..4cfb6e137aa513d41839c57986671c4b85a92673 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/pythonTestDriver.py.in +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/pythonTestDriver.py.in @@ -2,6 +2,8 @@ # set environment variables +from __future__ import print_function + import os, subprocess, sys from optparse import OptionParser @@ -57,7 +59,7 @@ if len(args) < 1: command = ["@PYTHON_EXECUTABLE@"] + args if options.verbose: - print >> sys.stderr, "+", " ".join(command) + print(sys.stderr, "+", " ".join(command)) returnValue = subprocess.call( command ) if returnValue != 0 : sys.exit( returnValue ) @@ -66,7 +68,7 @@ if returnValue != 0 : for imageFile1, imageFile2 in options.compare : command = ["@IMAGE_COMPARE@", imageFile1, imageFile2] if options.verbose: - print >> sys.stderr, "+", " ".join(command) + print(sys.stderr, "+", " ".join(command)) returnValue = subprocess.call( command ) if returnValue != 0 : sys.exit( returnValue ) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/returnedTypeCoverage.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/returnedTypeCoverage.py index 82733145e3b58c6412a2de02b7aeaf1e89737059..604709083bc8a53e34d1a6c26f7ba71598ded6ad 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/returnedTypeCoverage.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/returnedTypeCoverage.py @@ -16,7 +16,11 @@ # #==========================================================================*/ -import itk, re, sys +from __future__ import print_function + +import itk +import re +import sys try: import itkvtk except: @@ -26,241 +30,264 @@ from optparse import OptionParser ctypes = [ - 'double', - 'float', - 'signed_char', - 'signed_short', - 'signed_long', - 'unsigned_char', - 'unsigned_short', - 'unsigned_long', - 'char', - 'short', - 'long', - 'bool', - 'int', - 'unsigned_int', - 'void' + 'double', + 'float', + 'signed_char', + 'signed_short', + 'signed_long', + 'unsigned_char', + 'unsigned_short', + 'unsigned_long', + 'char', + 'short', + 'long', + 'bool', + 'int', + 'unsigned_int', + 'void' ] excludedMethodsList = [ - 'Delete', - 'Unregister', - 'SetReferenceCount', - - # the method broken for all filters - 'PushBackInput', - 'PushFrontInput', - 'GraftOutput', - 'SetInput', - 'UpdateOutputData', - 'PropagateRequestedRegion', - 'EnlargeOutputRequestedRegion', - - # functor are not wrapped so exclude GetFunctor - 'GetFunctor', - - #'UnCreateAllInstanceRegister', - #'Update', - #'UpdateLargestPossibleRegion', - #'GenerateInputRequestedRegion', - #'GenerateOutputInformation', - #'GenerateData', - #'GetImageIO', - #'UpdateOutputData', - #'UpdateOutputInformation', - #'GraftOutput', - #'AddSeed', - #'GetInputs', - #'GetOutputs', - #'CreateAllInstance' + 'Delete', + 'Unregister', + 'SetReferenceCount', + + # the method broken for all filters + 'PushBackInput', + 'PushFrontInput', + 'GraftOutput', + 'SetInput', + 'UpdateOutputData', + 'PropagateRequestedRegion', + 'EnlargeOutputRequestedRegion', + + # functor are not wrapped so exclude GetFunctor + 'GetFunctor', + + #'UnCreateAllInstanceRegister', + #'Update', + #'UpdateLargestPossibleRegion', + #'GenerateInputRequestedRegion', + #'GenerateOutputInformation', + #'GenerateData', + #'GetImageIO', + #'UpdateOutputData', + #'UpdateOutputInformation', + #'GraftOutput', + #'AddSeed', + #'GetInputs', + #'GetOutputs', + #'CreateAllInstance' ] excludedMethodsWithParamList = [ - #'GetElement', - #'RegisterFactory', - #'UnRegisterFactory', - #'PropagateRequestedRegion', - #'Resize', - #'PadByRadius' + #'GetElement', + #'RegisterFactory', + #'UnRegisterFactory', + #'PropagateRequestedRegion', + #'Resize', + #'PadByRadius' ] excludedClasses = [ - #'BinaryBallStructuringElement', - #'Neighborhood', - #'BSplineDecompositionImageFilter', - #'AtanImageFilter', - #'Atan2ImageFilter', - #'ChangeInformationImageFilter', - #'GeodesicActiveContourLevelSetImageFilter', - #'Image', - #'ImageBase', - #'ImageFileReader', - #'ImageFileWriter', - #'ImageRegistrationMethod', - #'BSplineDownsampleImageFilter', - #'BSplineUpsampleImageFilter', - #'CropImageFilter', - #'LevelSetFunction', - #'MattesMutualInformationImageToImageMetric', - #'MeanReciprocalSquareDifferenceImageToImageMetric', - #'MeanSquaresImageToImageMetric', - #'MultiResolutionImageRegistrationMethod', - #'MultiResolutionPyramidImageFilter', - #'MutualInformationImageToImageMetric', - #'NormalizedCorrelationImageToImageMetric', - #'ParallelSparseFieldLevelSetImageFilter', - #'PyBuffer', - #'RawImageIO', - #'RecursiveMultiResolutionPyramidImageFilter', - #'ResampleImageFilter', - #'RescaleIntensityImageFilter', - #'SegmentationLevelSetImageFilter', - #'ShapeDetectionLevelSetImageFilter', - #'SparseFieldFourthOrderLevelSetImageFilter', - #'SparseFieldLevelSetImageFilter', - #'SpatialObject', - #'SpatialObjectTreeNode', - #'WatershedImageFilter', - #'TreeNode', - #'ThresholdSegmentationLevelSetImageFilter', - #'PointSet', - #'ImageConstIterator', - #'ImageConstIteratorWithIndex', - #'ImageIterator', - #'ImageIteratorWithIndex', - #'ImageLinearConstIteratorWithIndex', - #'ImageLinearIteratorWithIndex', - #'ImageRandomConstIteratorWithIndex', - #'ImageRandomIteratorWithIndex', - #'ImageRandomNonRepeatingConstIteratorWithIndex', - #'ImageRandomNonRepeatingIteratorWithIndex', - #'ImageRegionConstIterator', - #'ImageRegionIterator', - #'ImageRegionConstIteratorWithIndex', - #'ImageRegionIteratorWithIndex', - #'InterpolateImageFilter', - #'IsolatedConnectedImageFilter', - 'SmartPointer', - 'BMPImageIO', + #'BinaryBallStructuringElement', + #'Neighborhood', + #'BSplineDecompositionImageFilter', + #'AtanImageFilter', + #'Atan2ImageFilter', + #'ChangeInformationImageFilter', + #'GeodesicActiveContourLevelSetImageFilter', + #'Image', + #'ImageBase', + #'ImageFileReader', + #'ImageFileWriter', + #'ImageRegistrationMethod', + #'BSplineDownsampleImageFilter', + #'BSplineUpsampleImageFilter', + #'CropImageFilter', + #'LevelSetFunction', + #'MattesMutualInformationImageToImageMetric', + #'MeanReciprocalSquareDifferenceImageToImageMetric', + #'MeanSquaresImageToImageMetric', + #'MultiResolutionImageRegistrationMethod', + #'MultiResolutionPyramidImageFilter', + #'MutualInformationImageToImageMetric', + #'NormalizedCorrelationImageToImageMetric', + #'ParallelSparseFieldLevelSetImageFilter', + #'PyBuffer', + #'RawImageIO', + #'RecursiveMultiResolutionPyramidImageFilter', + #'ResampleImageFilter', + #'RescaleIntensityImageFilter', + #'SegmentationLevelSetImageFilter', + #'ShapeDetectionLevelSetImageFilter', + #'SparseFieldFourthOrderLevelSetImageFilter', + #'SparseFieldLevelSetImageFilter', + #'SpatialObject', + #'SpatialObjectTreeNode', + #'WatershedImageFilter', + #'TreeNode', + #'ThresholdSegmentationLevelSetImageFilter', + #'PointSet', + #'ImageConstIterator', + #'ImageConstIteratorWithIndex', + #'ImageIterator', + #'ImageIteratorWithIndex', + #'ImageLinearConstIteratorWithIndex', + #'ImageLinearIteratorWithIndex', + #'ImageRandomConstIteratorWithIndex', + #'ImageRandomIteratorWithIndex', + #'ImageRandomNonRepeatingConstIteratorWithIndex', + #'ImageRandomNonRepeatingIteratorWithIndex', + #'ImageRegionConstIterator', + #'ImageRegionIterator', + #'ImageRegionConstIteratorWithIndex', + #'ImageRegionIteratorWithIndex', + #'InterpolateImageFilter', + #'IsolatedConnectedImageFilter', + 'SmartPointer', + 'BMPImageIO', ] + def log(s, level): - if level <= options.verbose: - print >> logFile, s - logFile.flush() + if level <= options.verbose: + print(logFile, s) + logFile.flush() def cleanType(s): - i = s.index('_', 1) - return s[i+1:] + i = s.index('_', 1) + return s[i + 1:] def addUnwrappedType(s): - s = cleanType(s) - if not s in unwrappedTypes: - unwrappedTypes.add(s) - log(s, 0) + s = cleanType(s) + if not s in unwrappedTypes: + unwrappedTypes.add(s) + log(s, 0) def exploreTpl(tpl): for cl in tpl.itervalues(): exploreMethods(cl, cl) # try to instanciate the class - try : + try: obj = cl.New() exploreMethods(obj, cl) except: pass - try : + try: exploreMethods(cl(), cl) except: pass + def exploreMethods(obj, cl): - attrNameList = [i for i in dir(obj) if isinstance(i, str) and i[0].isupper() and i not in excludedMethodsList] - attrNameList.sort() + isin = isinstance(i, str) + ls = excludedMethodsList + attrNameList = sorted( + [i for i in dir(obj) if isin and i[0].isupper() and i not in ls]) for attrName in attrNameList: log(" + " + attrName, 2) - try : + try: parameters = repr((cl.__name__, attrName)) - if parameters not in exclude : - log(parameters, 4) - exec "s = obj.%s()" % attrName - if isUnwrappedTypeString(s): - addUnwrappedType(s) - log(" - " + cleanType(s), 5) - except : + if parameters not in exclude: + log(parameters, 4) + exec "s = obj.%s()" % attrName + if isUnwrappedTypeString(s): + addUnwrappedType(s) + log(" - " + cleanType(s), 5) + except: # try with some parameters - if attrName not in excludedMethodsWithParamList : - for param in [0, '', False, None] : - parameters = repr((cl.__name__, attrName, param)) - if parameters not in exclude : - log(' * ' + repr(param), 3) - log(parameters, 4) - try : - exec "s = obj.%s(param)" % attrName - if isUnwrappedTypeString(s): - addUnwrappedType(s) - log(" - " + cleanType(s), 5) - except : - pass + if attrName not in excludedMethodsWithParamList: + for param in [0, '', False, None]: + parameters = repr((cl.__name__, attrName, param)) + if parameters not in exclude: + log(' * ' + repr(param), 3) + log(parameters, 4) + try: + exec "s = obj.%s(param)" % attrName + if isUnwrappedTypeString(s): + addUnwrappedType(s) + log(" - " + cleanType(s), 5) + except: + pass + def isUnwrappedTypeString(s): if not isinstance(s, str): return False if not s[0] == "_": return False - for t in ctypes : - if re.match('^_[0-9a-z]+_p_%s$' % t, s) : + for t in ctypes: + if re.match('^_[0-9a-z]+_p_%s$' % t, s): return False return True - - parser = OptionParser(usage="usage: %prog") -parser.add_option("--exclude", dest="exclude", default=None, metavar="FILE", help="") -parser.add_option("--log-file", dest="logFile", default="-", metavar="FILE", help="") -parser.add_option("--start-from", dest="startFrom", default=None, metavar="CLASS", help="") -parser.add_option("-v", "--verbose", dest="verbose", default=0, type="int", help="") +parser.add_option( + "--exclude", + dest="exclude", + default=None, + metavar="FILE", + help="") +parser.add_option( + "--log-file", + dest="logFile", + default="-", + metavar="FILE", + help="") +parser.add_option( + "--start-from", + dest="startFrom", + default=None, + metavar="CLASS", + help="") +parser.add_option( + "-v", + "--verbose", + dest="verbose", + default=0, + type="int", + help="") (options, args) = parser.parse_args() if options.logFile == "-": - logFile = sys.stdout + logFile = sys.stdout else: - logFile = file(options.logFile, "w") + logFile = file(options.logFile, "w") exclude = set() -if options.exclude : - exclude = set(file(options.exclude).read().splitlines()) - - +if options.exclude: + exclude = set(file(options.exclude).read().splitlines()) -attrNameList = sorted(set([i for i in dir(itk) if i[0].isupper() and len(i) > 2]) - set(excludedClasses)) +val = [i for i in dir(itk) if i[0].isupper() and len(i) > 2] +attrNameList = sorted(set(val) - set(excludedClasses)) -if options.startFrom : +if options.startFrom: attrNameList = attrNameList[attrNameList.index(options.startFrom):] unwrappedTypes = set() for name in attrNameList: - exec "attr = itk."+name + exec "attr = itk." + name # attr = itk.__dict__[name] log(name, 1) - if isinstance(attr, itkTemplate) : + if isinstance(attr, itkTemplate): exploreTpl(attr) - else : + else: exploreMethods(attr, attr) - try : + try: exploreMethods(attr.New(), attr) except: pass - try : + try: exploreMethods(attr(), attr) except: pass diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/simple_pipeline.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/simple_pipeline.py index ba718b0050be2ed2f87f427f57b897adfaef2d70..e20d062940136c0a2a1bac4cb307d0ba6e8213c1 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/simple_pipeline.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/simple_pipeline.py @@ -16,7 +16,8 @@ # #==========================================================================*/ -import itk, sys +import itk +import sys itk.auto_progress(2) # first argument is the pixel type diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/template.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/template.py index 146d62f428b154dfe4054dc71d5f6d3c6cdb8bda..10e4b84a76538333890397855b7061b17bff2723 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/template.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/template.py @@ -42,17 +42,17 @@ readerType3 = itk.ImageFileReader.IUC2 assert readerType == readerType2 == readerType3 # we should be able to get the template and its parameters from the class -(tpl, parameters) = itk.template( IType ) +(tpl, parameters) = itk.template(IType) assert tpl == itk.Image assert parameters == (PType, dim) # the template must raise a KeyError exception if the template parameter # is unknown -try : - itk.ImageFileReader['unknown parameter'] - raise Exception('no exception sent for unknown parameter') +try: + itk.ImageFileReader['unknown parameter'] + raise Exception('no exception sent for unknown parameter') except KeyError: - pass + pass # TODO: test the rest of the dict interface # TODO: test __eq__, __ne__ and __hash__ @@ -60,10 +60,7 @@ except KeyError: # something else ? - - # now test the New method - # without parameter reader = readerType.New() reader2 = readerType.New() @@ -73,18 +70,18 @@ reader = readerType.New(FileName='test.png') assert reader.GetFileName() == 'test.png' # wwith a wrong attribute name -try : - reader = readerType.New(WrongName='test.png') - raise Exception('no exception sent for wrong attribute name') +try: + reader = readerType.New(WrongName='test.png') + raise Exception('no exception sent for wrong attribute name') except AttributeError: - pass + pass # wwith a wrong attribute type -try : - reader = readerType.New(FileName=1) - raise Exception('no exception sent for wrong attribute type') -except : - pass +try: + reader = readerType.New(FileName=1) + raise Exception('no exception sent for wrong attribute type') +except: + pass # pass filter as argument for input # to a filter with SetInput method @@ -118,31 +115,32 @@ assert im2 == sub.GetInput(1) # pass invalid input try: - itk.MedianImageFilter[IType, IType].New(1) - raise Exception('no exception sent for wrong input type') + itk.MedianImageFilter[IType, IType].New(1) + raise Exception('no exception sent for wrong input type') except: - pass + pass try: - itk.SubtractImageFilter[IType, IType, IType].New(im, "wrong") - raise Exception('no exception sent for wrong 2nd input type') + itk.SubtractImageFilter[IType, IType, IType].New(im, "wrong") + raise Exception('no exception sent for wrong 2nd input type') except TypeError: - pass + pass # pass both input and attribute -recons = itk.ReconstructionByDilationImageFilter[IType, IType].New(reader.GetOutput(), im, FullyConnected=True) +recons = itk.ReconstructionByDilationImageFilter[ + IType, IType].New(reader.GetOutput(), im, FullyConnected=True) assert reader.GetOutput() == recons.GetInput(0) assert im == recons.GetInput(1) -assert recons.GetFullyConnected() == True +assert recons.GetFullyConnected() # pass input to object which do not take one try: - IType.New(im) - raise Exception('no exception sent for object without input') + IType.New(im) + raise Exception('no exception sent for object without input') except AttributeError: - pass + pass # TODO: test auto_progress # but how ? diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/templated_pipeline.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/templated_pipeline.py index 47bc7e0db3438c639b00c5a99d6430afaecd43b5..850e77aef58afa00e385cb5ae8e1d4985a4ebd19 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/templated_pipeline.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/templated_pipeline.py @@ -1,41 +1,73 @@ +#========================================================================== +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#==========================================================================*/ + import itk from sys import argv itk.auto_progress(2) # define a custom templated pipeline + class LabelDilateImageFilter(itk.pipeline): - def __init__(self, *args, **kargs): - # call the constructor of the superclass but without args and kargs, because the attributes - # are not all already there! - # Set/GetRadius() is created in the constructor for example, with the expose() method - itk.pipeline.__init__(self) - - # get the template parameters - template_parameters = kargs["template_parameters"] - # check the template parameters validity. Not really useful in that case, because we do the same - # here, but a good habit - LabelDilateImageFilter.check_template_parameters(template_parameters) - - # and store them in an easier way - ImageType, DistanceMapType = template_parameters - - # build the minipipeline - self.connect(itk.DanielssonDistanceMapImageFilter[ImageType, DistanceMapType].New(UseImageSpacing=True, SquaredDistance=False)) - self.connect(itk.BinaryThresholdImageFilter[DistanceMapType, ImageType].New()) - self.expose("UpperThreshold", "Radius") - self.append(itk.MaskImageFilter[ImageType, ImageType, ImageType].New(self.filters[0].GetVoronoiMap(), Input2=self.filters[1])) - - # now we can parse the inputs - itk.set_inputs(self, args, kargs) - - def check_template_parameters(template_parameters): - ImageType, DistanceMapType = template_parameters - itk.DanielssonDistanceMapImageFilter[ImageType, DistanceMapType] - itk.BinaryThresholdImageFilter[DistanceMapType, ImageType] - itk.CastImageFilter[DistanceMapType, ImageType] - itk.MaskImageFilter[ImageType, ImageType, ImageType] - check_template_parameters = staticmethod(check_template_parameters) + + def __init__(self, *args, **kargs): + # call the constructor of the superclass but without args and kargs, + # because the attributes are not all already there! + # Set/GetRadius() is created in the constructor for example, with the + # expose() method + itk.pipeline.__init__(self) + + # get the template parameters + template_parameters = kargs["template_parameters"] + # check the template parameters validity. Not really useful in that + # case, because we do the same here, but a good habit + LabelDilateImageFilter.check_template_parameters(template_parameters) + + # and store them in an easier way + ImageType, DistanceMapType = template_parameters + + # build the minipipeline + self.connect( + itk.DanielssonDistanceMapImageFilter[ + ImageType, + DistanceMapType].New( + UseImageSpacing=True, + SquaredDistance=False)) + self.connect( + itk.BinaryThresholdImageFilter[DistanceMapType, + ImageType].New()) + self.expose("UpperThreshold", "Radius") + self.append( + itk.MaskImageFilter[ImageType, + ImageType, + ImageType].New(self.filters[0].GetVoronoiMap(), + Input2=self.filters[1])) + + # now we can parse the inputs + itk.set_inputs(self, args, kargs) + + def check_template_parameters(template_parameters): + ImageType, DistanceMapType = template_parameters + itk.DanielssonDistanceMapImageFilter[ImageType, DistanceMapType] + itk.BinaryThresholdImageFilter[DistanceMapType, ImageType] + itk.CastImageFilter[DistanceMapType, ImageType] + itk.MaskImageFilter[ImageType, ImageType, ImageType] + check_template_parameters = staticmethod(check_template_parameters) LabelDilateImageFilter = itk.templated_class(LabelDilateImageFilter) @@ -46,8 +78,9 @@ IType = itk.Image[itk.UC, dim] OIType = itk.Image[itk.UC, dim] DIType = itk.Image[itk.F, dim] -reader = itk.ImageFileReader[IType].New( FileName=argv[1] ) -dilate = LabelDilateImageFilter[IType, DIType].New(reader, Radius=eval(argv[3])) -writer = itk.ImageFileWriter[OIType].New( dilate, FileName=argv[2] ) +reader = itk.ImageFileReader[IType].New(FileName=argv[1]) +val = argv[3] +dilate = LabelDilateImageFilter[IType, DIType].New(reader, Radius=eval(val)) +writer = itk.ImageFileWriter[OIType].New(dilate, FileName=argv[2]) writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/timing.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/timing.py index 31bc119c225ac64ef380554f5f38e17da875e29e..08818b6565db2937b5b2acffacc383ac0d0216a5 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/timing.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/timing.py @@ -1,59 +1,86 @@ +#========================================================================== +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#==========================================================================*/ + +from __future__ import print_function + import time start = time.time() import itk itk.force_load() -print "load:", time.time() - start +print("load:", time.time() - start) -img = itk.Image.UC2.New(Regions=(10,20)) +img = itk.Image.UC2.New(Regions=(10, 20)) img.Allocate() + def index(it): - idx = itk.Index[2]() - for dummy in range(0, it): - img.GetPixel(idx) + idx = itk.Index[2]() + for dummy in range(0, it): + img.GetPixel(idx) + def index2(it): - idx = itk.Index[2]() - for dummy in range(0, it): - idx[0] = 0 - idx[1] = 0 - img.GetPixel(idx) + idx = itk.Index[2]() + for dummy in range(0, it): + idx[0] = 0 + idx[1] = 0 + img.GetPixel(idx) + def integer(it): - for dummy in range(0, it): - img.GetPixel(0) + for dummy in range(0, it): + img.GetPixel(0) + def pylist(it): - l = [0, 0] - for dummy in range(0, it): - img.GetPixel(l) + l = [0, 0] + for dummy in range(0, it): + img.GetPixel(l) + def pytuple(it): - l = (0, 0) - for dummy in range(0, it): - img.GetPixel(l) + l = (0, 0) + for dummy in range(0, it): + img.GetPixel(l) + def new(it): - for dummy in range(0, it): - lo = itk.Image.UC2.__New_orig__() + for dummy in range(0, it): + lo = itk.Image.UC2.__New_orig__() + def extended_new(it): - for dummy in range(0, it): - lo = itk.Image.UC2.New() + for dummy in range(0, it): + lo = itk.Image.UC2.New() def run(f, it): - start = time.time() - f(it) - return time.time() - start + start = time.time() + f(it) + return time.time() - start it = 1000000 -print "index:", run(index, it) -print "index2:", run(index2, it) -print "integer:", run(integer, it) -print "list:", run(pylist, it) -print "tuple:", run(pytuple, it) -print "new:", run(new, 100000) -print "extended_new:", run(extended_new, 100000) +print("index:", run(index, it)) +print("index2:", run(index2, it)) +print("integer:", run(integer, it)) +print("list:", run(pylist, it)) +print("tuple:", run(pytuple, it)) +print("new:", run(new, 100000)) +print("extended_new:", run(extended_new, 100000)) diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/typemaps.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/typemaps.py index 9b9a2c032c5e8e39eba1bbf4cc0a01e78d3f56f1..6dfacedde8a7046c9e3390e1360bd5a5a2a81f5d 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/typemaps.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/typemaps.py @@ -16,7 +16,11 @@ # #==========================================================================*/ -import itk, sys, gc +from __future__ import print_function + +import itk +import sys +import gc # create some vars used later @@ -37,15 +41,31 @@ idx1 = itk.Index[2](idx) idx2 = itk.Index[2](t) idx3 = itk.Index[2](l) idx4 = itk.Index[2](i) -assert idx1.GetElement(0) == idx2.GetElement(0) == idx3.GetElement(0) == idx4.GetElement(0) == i -assert idx1.GetElement(1) == idx2.GetElement(1) == idx3.GetElement(1) == idx4.GetElement(1) == i +assert idx1.GetElement( + 0) == idx2.GetElement( + 0) == idx3.GetElement( + 0) == idx4.GetElement( + 0) == i +assert idx1.GetElement( + 1) == idx2.GetElement( + 1) == idx3.GetElement( + 1) == idx4.GetElement( + 1) == i size1 = itk.Size[2](size) size2 = itk.Size[2](t) size3 = itk.Size[2](l) size4 = itk.Size[2](i) -assert size1.GetElement(0) == size2.GetElement(0) == size3.GetElement(0) == size4.GetElement(0) == i -assert size1.GetElement(1) == size2.GetElement(1) == size3.GetElement(1) == size4.GetElement(1) == i +assert size1.GetElement( + 0) == size2.GetElement( + 0) == size3.GetElement( + 0) == size4.GetElement( + 0) == i +assert size1.GetElement( + 1) == size2.GetElement( + 1) == size3.GetElement( + 1) == size4.GetElement( + 1) == i median = itk.MedianImageFilter.IUC2IUC2.New() median.SetRadius(size) @@ -56,36 +76,44 @@ median.SetRadius(l) size3 = median.GetRadius() median.SetRadius(i) size4 = median.GetRadius() -assert size1.GetElement(0) == size2.GetElement(0) == size3.GetElement(0) == size4.GetElement(0) == i -assert size1.GetElement(1) == size2.GetElement(1) == size3.GetElement(1) == size4.GetElement(1) == i +assert size1.GetElement( + 0) == size2.GetElement( + 0) == size3.GetElement( + 0) == size4.GetElement( + 0) == i +assert size1.GetElement( + 1) == size2.GetElement( + 1) == size3.GetElement( + 1) == size4.GetElement( + 1) == i # smart pointers im = itk.Image.UC2.New() -assert im != None +assert im is not None -median.SetInput( im ) +median.SetInput(im) assert median.GetInput() == im assert median.GetInput() != median.GetOutput() -median.SetInput( None ) -assert median.GetInput() == None +median.SetInput(None) +assert median.GetInput() is None # ImageSource median2 = itk.MedianImageFilter.IUC2IUC2.New() -median.SetInput( median2 ) +median.SetInput(median2) assert median.GetInput() == median2.GetOutput() # catching exception try: - median.Update() - print >> sys.stderr, "Exception not throwed!" - sys.exit(1) -except RuntimeError, e: - print "Exception catched as expected", e + median.Update() + print("Exception not throwed!", file=sys.stderr) + sys.exit(1) +except RuntimeError as e: + print("Exception catched as expected", e) # ----- keep that at the end! ----- diff --git a/Utilities/ITK/Wrapping/Generators/Python/Tests/wrappingCoverage.py b/Utilities/ITK/Wrapping/Generators/Python/Tests/wrappingCoverage.py index 4edd1ce6404989c13fcc84795477b79e90047ecd..c819c63add6d69c9cca41ea6a82d74ad48f74e01 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/Tests/wrappingCoverage.py +++ b/Utilities/ITK/Wrapping/Generators/Python/Tests/wrappingCoverage.py @@ -1,71 +1,88 @@ -# -*- coding: utf-8 -*- +#========================================================================== +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#==========================================================================*/ -import sys, re, itk, os -from optparse import OptionParser - -# python 2.3 compatibility -if sys.version < '2.4' : - # set compatibility - import sets - set = sets.Set +from __future__ import print_function - def sorted(iterable, cmp=None, key=None, reverse=False) : - i = list(iterable) - if key : - d = {} - for v in iterable : - k = key(v) - if not d.has_key(k) : - d[k] = [] - d[k].append(v) - keys = d.keys() - keys.sort(cmp) - i = [] - for k in keys : - i += d[k] - else : - i.sort(cmp) - if reverse : - i.reverse() - return i +import sys +import re +import itk +import os +from optparse import OptionParser -parser = OptionParser(usage = 'wrappingCoverage.py paths') +parser = OptionParser(usage='wrappingCoverage.py paths') -parser.add_option("-b", "--base", dest="base", default="Filter", help="Base string used to search for the classes (default: Filter).") -parser.add_option("-e", "--exclude", dest="exclude", default=None, help="Path of a file with one class to exclude per line (default: None).") -parser.add_option("-E", "--no-error", action="store_true", dest="noError", help="Don't generate an error code if all the classes are not wrapped.") +parser.add_option( + "-b", + "--base", + dest="base", + default="Filter", + help="Base string used to search for the classes (default: Filter).") +parser.add_option( + "-e", + "--exclude", + dest="exclude", + default=None, + help="Path of a file with one class to exclude per line (default: None).") +parser.add_option( + "-E", + "--no-error", + action="store_true", + dest="noError", + help="Don't generate an error code if all the classes are not wrapped.") opts, args = parser.parse_args() # declares classes which will not be wrapped excluded = set([]) if opts.exclude: - map(excluded.add, [c.strip() for c in file(opts.exclude).readlines()]) + map(excluded.add, [c.strip() for c in file(opts.exclude).readlines()]) # get classes from sources headers = [] for d in args: - headers += sum([ f for p,d,f in os.walk(d) if "Deprecated" not in p and "TestKernel" not in p ], []) -classes = set([f[len('itk'):-len('.h')] for f in headers if f.startswith("itk") and not f.startswith("itkv3") and f.endswith(opts.base+".h")]) - excluded + headers += sum([f for p, d, f in os.walk(d) + if "Deprecated" not in p and "TestKernel" not in p], []) +classes = set([f[len('itk'):-len('.h')] for f in headers if f.startswith("itk") + and not f.startswith("itkv3") and + f.endswith(opts.base + ".h")]) - excluded # get filter from wrapper files -# remove classes which are not in the toolkit (external projects, PyImageFilter, ...) -wrapped = set([a for a in dir(itk) if a.endswith(opts.base)]).intersection(classes) +# remove classes which are not in the toolkit (external projects, +# PyImageFilter, ...) +wrapped = set([a for a in dir(itk) if a.endswith(opts.base)] + ).intersection(classes) nonWrapped = classes - wrapped -# print non wrapped classes without much text to stdout, so they can be easily reused -for f in sorted(nonWrapped) : - print f +# print non wrapped classes without much text to stdout, so they can be +# easily reused +for f in sorted(nonWrapped): + print(f) # and print stats in stderr to avoid poluting the list above -print >>sys.stderr -print >>sys.stderr, '%i %s' % (len(classes), opts.base) -print >>sys.stderr, '%i wrapped %s' % (len(wrapped), opts.base) -print >>sys.stderr, '%i non wrapped %s' % (len(nonWrapped), opts.base) -print >>sys.stderr, '%f%% covered' % (len(wrapped) / float(len(classes)) * 100) -print >>sys.stderr +print("", file=sys.stderr) +print('%i %s' % (len(classes), opts.base), file=sys.stderr) +print('%i wrapped %s' % (len(wrapped), opts.base), file=sys.stderr) +print('%i non wrapped %s' % (len(nonWrapped), opts.base), file=sys.stderr) +covered = len(wrapped) / float(len(classes)) +print('%f%% covered' % (covered * 100), file=sys.stderr) +print("", file=sys.stderr) if not opts.noError: - sys.exit(len(nonWrapped)) + sys.exit(len(nonWrapped)) diff --git a/Utilities/ITK/Wrapping/Generators/Python/WrapITK.pth.in b/Utilities/ITK/Wrapping/Generators/Python/WrapITK.pth.in index 2eadcd191790197901f06d295c10311e1d2fdf86..7e2dc5a4b96b67b7455c7b27f3477fad1e9e663c 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/WrapITK.pth.in +++ b/Utilities/ITK/Wrapping/Generators/Python/WrapITK.pth.in @@ -1,2 +1,3 @@ # Python pth file to add WrapITK's path to sys.path. @CONFIG_ITK_WRAP_PYTHON_DIR@ +@CONFIG_ITK_WRAP_LIBRARY_DIR@ diff --git a/Utilities/ITK/Wrapping/Generators/Python/WrapITKBuildOptionsConfig.py b/Utilities/ITK/Wrapping/Generators/Python/WrapITKBuildOptionsConfig.py index dc80b81c6bead5a7dd9af3dfe1f824a462447bd6..a0094a1a0a7f5e7af2268e56c38d56d9ce43af4d 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/WrapITKBuildOptionsConfig.py +++ b/Utilities/ITK/Wrapping/Generators/Python/WrapITKBuildOptionsConfig.py @@ -1,17 +1,17 @@ depends = ('ITKCommon',) templates = ( - ('DIMS', 'ITK_WRAP_DIMS', 'DIMS'), - ('USIGN_INTS', 'WRAP_ITK_USIGN_INT', 'USIGN_INTS'), - ('SIGN_INTS', 'WRAP_ITK_SIGN_INT', 'SIGN_INTS'), - ('REALS', 'WRAP_ITK_REAL', 'REALS'), - ('VECTOR_REALS', 'WRAP_ITK_VECTOR_REAL', 'VECTOR_REALS'), - ('COV_VECTOR_REALS', 'WRAP_ITK_COV_VECTOR_REAL', 'COV_VECTOR_REALS'), - ('RGBS', 'WRAP_ITK_RGB', 'RGBS'), - ('RGBAS', 'WRAP_ITK_RGBA', 'RGBAS'), - ('COMPLEX_REALS', 'WRAP_ITK_COMPLEX_REAL', 'COMPLEX_REALS'), - ('INTS', 'WRAP_ITK_INT', 'INTS'), - ('SCALARS', 'WRAP_ITK_SCALAR', 'SCALARS'), - ('VECTORS', 'WRAP_ITK_VECTOR', 'VECTORS'), - ('COLORS', 'WRAP_ITK_COLOR', 'COLORS'), - ('ALL_TYPES', 'WRAP_ITK_ALL_TYPE', 'ALL_TYPES'), + ('DIMS', 'ITK_WRAP_DIMS', 'DIMS'), + ('USIGN_INTS', 'WRAP_ITK_USIGN_INT', 'USIGN_INTS'), + ('SIGN_INTS', 'WRAP_ITK_SIGN_INT', 'SIGN_INTS'), + ('REALS', 'WRAP_ITK_REAL', 'REALS'), + ('VECTOR_REALS', 'WRAP_ITK_VECTOR_REAL', 'VECTOR_REALS'), + ('COV_VECTOR_REALS', 'WRAP_ITK_COV_VECTOR_REAL', 'COV_VECTOR_REALS'), + ('RGBS', 'WRAP_ITK_RGB', 'RGBS'), + ('RGBAS', 'WRAP_ITK_RGBA', 'RGBAS'), + ('COMPLEX_REALS', 'WRAP_ITK_COMPLEX_REAL', 'COMPLEX_REALS'), + ('INTS', 'WRAP_ITK_INT', 'INTS'), + ('SCALARS', 'WRAP_ITK_SCALAR', 'SCALARS'), + ('VECTORS', 'WRAP_ITK_VECTOR', 'VECTORS'), + ('COLORS', 'WRAP_ITK_COLOR', 'COLORS'), + ('ALL_TYPES', 'WRAP_ITK_ALL_TYPE', 'ALL_TYPES'), ) diff --git a/Utilities/ITK/Wrapping/Generators/Python/itk.py b/Utilities/ITK/Wrapping/Generators/Python/itk.py index e26198aed8f79991bcb055505a94643df98b41e4..1e1cec0cdfd4061b1825ec42fa87edc717bccf29 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/itk.py +++ b/Utilities/ITK/Wrapping/Generators/Python/itk.py @@ -17,56 +17,56 @@ #==========================================================================*/ """itk.py : Top-level container module for ITK wrappers.""" -import itkBase, itkConfig, itkLazy, itkTypes, itkExtras, os, sys - -# silently import psyco -try: - import psyco - psyco.profile() -except ImportError: - pass +import itkBase +import itkConfig +import itkLazy +import itkTypes +import itkExtras +import os +import sys thisModule = sys.modules[__name__] if itkConfig.LazyLoading: - # If we are loading lazily (on-demand), make a dict mapping the available - # classes/functions/etc. (read from the configuration modules) to the - # modules they are declared in. Then pass that dict to a LazyITKModule - # instance and (later) do some surgery on sys.modules so that the 'itk' - # module becomes that new instance instead of what is executed from this file. - lazyAttributes = {} - for module, data in itkBase.module_data.items(): - templateNames = [ t[0] for t in data['templates'] ] - attributes = dict( [(n, module) for n in templateNames] ) - lazyAttributes.update(attributes) - if isinstance(thisModule, itkLazy.LazyITKModule): - # Handle reload case where we've already done this once. - # If we made a new module every time, multiple reload()s would fail - # because the identity of sys.modules['itk'] would always be changing. - thisModule.__init__(__name__, lazyAttributes) - del lazyAttributes - else: - thisModule = itkLazy.LazyITKModule(__name__, lazyAttributes) + # If we are loading lazily (on-demand), make a dict mapping the available + # classes/functions/etc. (read from the configuration modules) to the + # modules they are declared in. Then pass that dict to a LazyITKModule + # instance and (later) do some surgery on sys.modules so that the 'itk' + # module becomes that new instance instead of what is executed from this + # file. + lazyAttributes = {} + for module, data in itkBase.module_data.items(): + templateNames = [t[0] for t in data['templates']] + attributes = dict([(n, module) for n in templateNames]) + lazyAttributes.update(attributes) + if isinstance(thisModule, itkLazy.LazyITKModule): + # Handle reload case where we've already done this once. + # If we made a new module every time, multiple reload()s would fail + # because the identity of sys.modules['itk'] would always be changing. + thisModule.__init__(__name__, lazyAttributes) + del lazyAttributes + else: + thisModule = itkLazy.LazyITKModule(__name__, lazyAttributes) else: - # We're not lazy-loading. Just load the modules in the order specified in - # the known_modules list for consistency. - for module in itkBase.known_modules: - itkBase.LoadModule(module, thisModule.__dict__) + # We're not lazy-loading. Just load the modules in the order specified in + # the known_modules list for consistency. + for module in itkBase.known_modules: + itkBase.LoadModule(module, thisModule.__dict__) # Regardless of how it was loaded, fill up the itk module with the ITK types # and extras. for k, v in itkTypes.__dict__.items(): - if k != 'itkCType' and not k.startswith('_'): - setattr(thisModule, k, v) + if k != 'itkCType' and not k.startswith('_'): + setattr(thisModule, k, v) for k, v in itkExtras.__dict__.items(): - if not k.startswith('_'): - setattr(thisModule, k, v) + if not k.startswith('_'): + setattr(thisModule, k, v) if itkConfig.LazyLoading: - # this has to be the last step, else python gets confused about itkTypes - # and itkExtras above. I'm not sure why... - sys.modules[__name__] = thisModule + # this has to be the last step, else python gets confused about itkTypes + # and itkExtras above. I'm not sure why... + sys.modules[__name__] = thisModule else: - # do some cleanup - del module, thisModule - del itkBase, itkConfig, itkLazy, itkTypes, itkExtras, os, sys + # do some cleanup + del module, thisModule + del itkBase, itkConfig, itkLazy, itkTypes, itkExtras, os, sys diff --git a/Utilities/ITK/Wrapping/Generators/Python/itkBase.py b/Utilities/ITK/Wrapping/Generators/Python/itkBase.py index f8fe00943221514e00eb638dd2d86c50c959c5cc..502329748bc035a2067a0bcbe0f9fcab5b510c5d 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/itkBase.py +++ b/Utilities/ITK/Wrapping/Generators/Python/itkBase.py @@ -16,213 +16,221 @@ # #==========================================================================*/ -import os, os.path, sys, imp, inspect, itkConfig, itkTemplate - -def LoadModule(name, namespace = None): - """This function causes a SWIG module to be loaded into memory after its dependencies - are satisfied. Information about the templates defined therein is looked up from - a config file, and PyTemplate instances for each are created. These template - instances are placed in a module with the given name that is either looked up - from sys.modules or created and placed there if it does not already exist. - Optionally, a 'namespace' parameter can be provided. If it is provided, this - namespace will be updated with the new template instantiations. - The raw classes loaded from the named module's SWIG interface are placed in a - 'swig' sub-module. If the namespace parameter is provided, this information will - be placed in a sub-module named 'swig' therein as well. This latter submodule - will be created if it does not already exist.""" - - # find the module's name in sys.modules, or create a new module so named - this_module = sys.modules.setdefault(name, imp.new_module(name)) - - # if this library and it's template instantiations have already been loaded - # into sys.modules, bail out after loading the defined symbols into 'namespace' - if hasattr(this_module, '__templates_loaded'): - if namespace is not None: - swig = namespace.setdefault('swig', imp.new_module('swig')) - swig.__dict__.update(this_module.swig.__dict__) - - # don't worry about overwriting the symbols in namespace -- any common - # symbols should be of type itkTemplate, which is a singleton type. That - # is, they are all identical, so replacing one with the other isn't a - # problem. - for k, v in this_module.__dict__.items(): - if not (k.startswith('_') or k == 'swig'): namespace[k] = v - return - - # We're definitely going to load the templates. We set templates_loaded here - # instead of at the end of the file to protect against cyclical dependencies - # that could kill the recursive lookup below. - this_module.__templates_loaded = True - - # For external projects : - # If this_module name (variable name) is in the module_data dictionnary, then - # this_module is an installed module (or a previously loaded module). - # Otherwise, it may come from an external project. In this case, we must - # search the Configuration/<name>Config.py file of this project. - try: - module_data[name] - except: - file = inspect.getfile(this_module) - path = os.path.dirname(file) - - data = {} +from __future__ import print_function + +import os +import os.path +import sys +import imp +import inspect +import itkConfig +import itkTemplate + + +def LoadModule(name, namespace=None): + """This function causes a SWIG module to be loaded into memory after its + dependencies are satisfied. Information about the templates defined therein + is looked up from a config file, and PyTemplate instances for each are + created. These template instances are placed in a module with the given + name that is either looked up from sys.modules or created and placed there + if it does not already exist. + Optionally, a 'namespace' parameter can be provided. If it is provided, + this namespace will be updated with the new template instantiations. + The raw classes loaded from the named module's SWIG interface are placed in + a 'swig' sub-module. If the namespace parameter is provided, this + information will be placed in a sub-module named 'swig' therein as well. + This later submodule will be created if it does not already exist.""" + + # find the module's name in sys.modules, or create a new module so named + this_module = sys.modules.setdefault(name, imp.new_module(name)) + + # if this library and it's template instantiations have already been loaded + # into sys.modules, bail out after loading the defined symbols into + # 'namespace' + if hasattr(this_module, '__templates_loaded'): + if namespace is not None: + swig = namespace.setdefault('swig', imp.new_module('swig')) + swig.__dict__.update(this_module.swig.__dict__) + + # don't worry about overwriting the symbols in namespace -- any + # common symbols should be of type itkTemplate, which is a + # singleton type. That is, they are all identical, so replacing one + # with the other isn't a problem. + for k, v in this_module.__dict__.items(): + if not (k.startswith('_') or k == 'swig'): + namespace[k] = v + return + + # We're definitely going to load the templates. We set templates_loaded + # here instead of at the end of the file to protect against cyclical + # dependencies that could kill the recursive lookup below. + this_module.__templates_loaded = True + + # For external projects : + # If this_module name (variable name) is in the module_data dictionnary, + # then this_module is an installed module (or a previously loaded module). + # Otherwise, it may come from an external project. In this case, we must + # search the Configuration/<name>Config.py file of this project. try: - # for a linux tree - execfile(os.path.join(path, 'Configuration', name + 'Config.py'), data) + module_data[name] except: - try: - # for a windows tree - execfile(os.path.join(path, '..', 'Configuration', name + 'Config.py'), data) - except: - data=None - if(data): - module_data[name] = data - - # Now, we we definitely need to load the template instantiations from the - # named module, and possibly also load the underlying SWIG module. Before we - # can load the template instantiations of this module, we need to load those - # of the modules on which this one depends. Ditto for the SWIG modules. - # So, we recursively satisfy the dependencies of named module and create the - # template instantiations. - # Dependencies are looked up from the auto-generated configuration files, via - # the module_data instance defined at the bottom of this file, which knows how - # to find those configuration files. - data = module_data[name] - if data: - deps = list(data['depends']) - deps.sort() - for dep in deps: - LoadModule(dep, namespace) - - if itkConfig.ImportCallback: itkConfig.ImportCallback(name, 0) - - # SWIG-generated modules have 'Python' appended. Only load the SWIG module if - # we haven't already. - swigModuleName = name + "Python" - loader = LibraryLoader() - if not swigModuleName in sys.modules: module = loader.load(swigModuleName) - - # OK, now the modules on which this one depends are loaded and template-instantiated, - # and the SWIG module for this one is also loaded. - # We're going to put the things we load and create in two places: the optional - # 'namespace' parameter, and the this_module variable's namespace. - - # make a new 'swig' sub-module for this_module. Also look up or create a - # different 'swig' module for 'namespace'. Since 'namespace' may be used to - # collect symbols from multiple different ITK modules, we don't want to - # stomp on an existing 'swig' module, nor do we want to share 'swig' modules - # between this_module and namespace. - - this_module.swig = imp.new_module('swig') - if namespace is not None: swig = namespace.setdefault('swig', imp.new_module('swig')) - for k, v in module.__dict__.items(): - if not k.startswith('__'): setattr(this_module.swig, k, v) - if namespace is not None and not k.startswith('__'): setattr(swig, k, v) - - data = module_data[name] - if data: - for template in data['templates']: - if len(template) == 4: - # this is a template description - pyClassName, cppClassName, swigClassName, templateParams = template - # It doesn't matter if an itkTemplate for this class name already exists - # since every instance of itkTemplate with the same name shares the same - # state. So we just make a new instance and add the new templates. - templateContainer = itkTemplate.itkTemplate(cppClassName) - try: - templateContainer.__add__(templateParams, getattr(module, swigClassName)) - setattr(this_module, pyClassName, templateContainer) - if namespace is not None: - current_value = namespace.get(pyClassName) - if current_value != None and current_value != templateContainer: - DebugPrintError("Namespace already has a value for %s, which is not an itkTemplate instance for class %s. Overwriting old value." %(pyClassName, cppClassName)) - namespace[pyClassName] = templateContainer - except Exception, e: - DebugPrintError("%s not loaded from module %s because of exception:\n %s" %(swigClassName, name, e)) - - else: - # this is a description of a non-templated class - pyClassName, cppClassName, swigClassName = template + file = inspect.getfile(this_module) + path = os.path.dirname(file) + + data = {} + conf = name + 'Config.py' try: - swigClass = getattr(module, swigClassName) - itkTemplate.registerNoTpl(cppClassName, swigClass) - setattr(this_module, pyClassName, swigClass) - if namespace is not None: - current_value = namespace.get(pyClassName) - if current_value != None and current_value != swigClass: - DebugPrintError("Namespace already has a value for %s, which is not class %s. Overwriting old value." %(pyClassName, cppClassName)) - namespace[pyClassName] = swigClass - except Exception, e: - DebugPrintError("%s not found in module %s because of exception:\n %s" %(swigClassName, name, e)) - - if itkConfig.ImportCallback: itkConfig.ImportCallback(name, 1) + # for a linux tree + execfile(os.path.join(path, 'Configuration', conf), data) + except: + try: + # for a windows tree + execfile(os.path.join(path, '..', 'Configuration', conf), data) + except: + data = None + if(data): + module_data[name] = data + + # Now, we definitely need to load the template instantiations from the + # named module, and possibly also load the underlying SWIG module. Before + # we can load the template instantiations of this module, we need to load + # those of the modules on which this one depends. Ditto for the SWIG + # modules. + # So, we recursively satisfy the dependencies of named module and create + # the template instantiations. + # Dependencies are looked up from the auto-generated configuration files, + # via the module_data instance defined at the bottom of this file, which + # knows how to find those configuration files. + data = module_data[name] + if data: + deps = sorted(data['depends']) + for dep in deps: + LoadModule(dep, namespace) + + if itkConfig.ImportCallback: + itkConfig.ImportCallback(name, 0) + + # SWIG-generated modules have 'Python' appended. Only load the SWIG module + # if we haven't already. + swigModuleName = name + "Python" + loader = LibraryLoader() + if not swigModuleName in sys.modules: + module = loader.load(swigModuleName) + + # OK, now the modules on which this one depends are loaded and + # template-instantiated, and the SWIG module for this one is also loaded. + # We're going to put the things we load and create in two places: the + # optional 'namespace' parameter, and the this_module variable's namespace. + + # make a new 'swig' sub-module for this_module. Also look up or create a + # different 'swig' module for 'namespace'. Since 'namespace' may be used to + # collect symbols from multiple different ITK modules, we don't want to + # stomp on an existing 'swig' module, nor do we want to share 'swig' + # modules between this_module and namespace. + + this_module.swig = imp.new_module('swig') + if namespace is not None: + swig = namespace.setdefault('swig', imp.new_module('swig')) + for k, v in module.__dict__.items(): + if not k.startswith('__'): + setattr(this_module.swig, k, v) + if namespace is not None and not k.startswith('__'): + setattr(swig, k, v) + + data = module_data[name] + if data: + for template in data['templates']: + if len(template) == 4: + # This is a template description + pyClassName, cppClassName, swigClassName, templateParams = \ + template + # It doesn't matter if an itkTemplate for this class name + # already exists since every instance of itkTemplate with the + # same name shares the same state. So we just make a new + # instance and add the new templates. + templateContainer = itkTemplate.itkTemplate(cppClassName) + try: + templateContainer.__add__( + templateParams, getattr(module, swigClassName)) + setattr(this_module, pyClassName, templateContainer) + if namespace is not None: + curval = namespace.get(pyClassName) + if curval is not None and curval != templateContainer: + DebugPrintError("Namespace already has a value for" + " %s, which is not an itkTemplate" + "instance for class %s. " + "Overwriting old value." + % (pyClassName, cppClassName)) + namespace[pyClassName] = templateContainer + except Exception as e: + DebugPrintError("%s not loaded from module %s because of " + "exception:\n %s" + % (swigClassName, name, e)) + + else: + # this is a description of a non-templated class + pyClassName, cppClassName, swigClassName = template + try: + swigClass = getattr(module, swigClassName) + itkTemplate.registerNoTpl(cppClassName, swigClass) + setattr(this_module, pyClassName, swigClass) + if namespace is not None: + curval = namespace.get(pyClassName) + if curval is not None and curval != swigClass: + DebugPrintError("Namespace already has a value for" + " %s, which is not class %s. " + "Overwriting old value." + % (pyClassName, cppClassName)) + namespace[pyClassName] = swigClass + except Exception as e: + DebugPrintError("%s not found in module %s because of " + "exception:\n %s" + % (swigClassName, name, e)) + + if itkConfig.ImportCallback: + itkConfig.ImportCallback(name, 1) + def DebugPrintError(error): - if itkConfig.DebugLevel == itkConfig.WARN: - print >> sys.stderr, error - elif itkConfig.DebugLevel == itkConfig.ERROR: - raise RuntimeError(error) + if itkConfig.DebugLevel == itkConfig.WARN: + print(error, file=sys.stderr) + elif itkConfig.DebugLevel == itkConfig.ERROR: + raise RuntimeError(error) + class LibraryLoader(object): - """Do all the work to set up the environment so that a SWIG-generated library - can be properly loaded. This invloves setting paths, etc., defined in itkConfig.""" - - # To share symbols across extension modules, we must set - # sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL) - # - # Since RTLD_NOW==0x002 and RTLD_GLOBAL==0x100 very commonly - # we will just guess that the proper flags are 0x102 when there - # is no dl module. On darwin (where there is not yet a dl module) - # we need different flags because RTLD_GLOBAL = 0x008. - darwin_dlopenflags = 0xA - generic_dlopenflags = 0x102 - - if sys.platform.startswith('darwin'): - dlopenflags = darwin_dlopenflags - elif sys.platform.startswith('win'): - dlopenflags = None - else: - dlopenflags = generic_dlopenflags - # now try to refine the dlopenflags if we have a dl module. - try: - import dl - dlopenflags = dl.RTLD_NOW|dl.RTLD_GLOBAL - except: - pass - - - def setup(self): - self.old_cwd = os.getcwd() - try: - os.chdir(itkConfig.swig_lib) - except OSError: - # silently pass to avoid the case where the dir is not there - pass - self.old_path = sys.path - sys.path = [itkConfig.swig_lib, itkConfig.swig_py] + sys.path - try: - self.old_dlopenflags = sys.getdlopenflags() - sys.setdlopenflags(self.dlopenflags) - except: - self.old_dlopenflags = None - def load(self, name): - self.setup() - try: - fp = None # needed in case next line raises exception, so that finally block works - fp, pathname, description = imp.find_module(name) - return imp.load_module(name, fp, pathname, description) - finally: - # Since we may exit via an exception, close fp explicitly. - if fp: fp.close() - self.cleanup() - - def cleanup(self): - os.chdir(self.old_cwd) - sys.path = self.old_path - if self.old_dlopenflags: - try: sys.setdlopenflags(self.old_dlopenflags) - except: pass + """Do all the work to set up the environment so that a SWIG-generated + library can be properly loaded. This invloves setting paths defined in + itkConfig.""" + + def setup(self): + self.old_cwd = os.getcwd() + try: + os.chdir(itkConfig.swig_lib) + except OSError: + # silently pass to avoid the case where the dir is not there + pass + self.old_path = sys.path + sys.path = [itkConfig.swig_lib, itkConfig.swig_py] + sys.path + + def load(self, name): + self.setup() + try: + # needed in case next line raises exception, so that finally block + # works + fp = None + fp, pathname, description = imp.find_module(name) + return imp.load_module(name, fp, pathname, description) + finally: + # Since we may exit via an exception, close fp explicitly. + if fp: + fp.close() + self.cleanup() + + def cleanup(self): + os.chdir(self.old_cwd) + sys.path = self.old_path # Make a list of all know modules (described in *Config.py files in the @@ -231,12 +239,13 @@ class LibraryLoader(object): dirs = [p for p in itkConfig.path if os.path.isdir(p)] module_data = {} for d in dirs: - known_modules = [f[:-9] for f in os.listdir(d+os.sep+"Configuration") if f.endswith('Config.py')] - known_modules.sort() - sys.path.append(d) - sys.path.append(d+os.sep+".."+os.sep+"lib") - - for module in known_modules: - data = {} - execfile(os.path.join(d+os.sep+"Configuration", module + 'Config.py'), data) - module_data[module] = data + files = os.listdir(d + os.sep + "Configuration") + known_modules = sorted([f[:-9] for f in files if f.endswith('Config.py')]) + sys.path.append(d) + sys.path.append(d + os.sep + ".." + os.sep + "lib") + + for module in known_modules: + data = {} + conf = module + 'Config.py' + execfile(os.path.join(d + os.sep + "Configuration", conf), data) + module_data[module] = data diff --git a/Utilities/ITK/Wrapping/Generators/Python/itkdata.py b/Utilities/ITK/Wrapping/Generators/Python/itkData.py similarity index 77% rename from Utilities/ITK/Wrapping/Generators/Python/itkdata.py rename to Utilities/ITK/Wrapping/Generators/Python/itkData.py index 9e5c2320d8b3e8d0023a81f24d11151f95d9b6f0..ff543aacfab9c041cbe3824c092de2ac704e3c93 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/itkdata.py +++ b/Utilities/ITK/Wrapping/Generators/Python/itkData.py @@ -16,7 +16,7 @@ # #==========================================================================*/ -import itkbase +import itkBase import sys import os @@ -27,16 +27,16 @@ ITK_DATA_ROOT = "" # Look for the -D command line option. if not ITK_DATA_ROOT: - for a in range(len(sys.argv)): - if sys.argv[a] == "-D" and a < len(sys.argv): - ITK_DATA_ROOT = sys.argv[a+1] - break + for a in range(len(sys.argv)): + if sys.argv[a] == "-D" and a < len(sys.argv): + ITK_DATA_ROOT = sys.argv[a + 1] + break # Check for the environment variable ::ITK_DATA_ROOT. -if not ITK_DATA_ROOT and os.environ.has_key('ITK_DATA_ROOT'): - ITK_DATA_ROOT = os.environ['ITK_DATA_ROOT'] +if not ITK_DATA_ROOT and 'ITK_DATA_ROOT' in os.environ: + ITK_DATA_ROOT = os.environ['ITK_DATA_ROOT'] # Use the default output directory. if not ITK_DATA_ROOT: - ITK_DATA_ROOT = itkbase.defaultDataRoot + ITK_DATA_ROOT = itkBase.defaultDataRoot diff --git a/Utilities/ITK/Wrapping/Generators/Python/itkExtras.py b/Utilities/ITK/Wrapping/Generators/Python/itkExtras.py new file mode 100644 index 0000000000000000000000000000000000000000..8b2c58556cdf3492ece293a77865b604566df8b1 --- /dev/null +++ b/Utilities/ITK/Wrapping/Generators/Python/itkExtras.py @@ -0,0 +1,1035 @@ +#========================================================================== +# +# Copyright Insight Software Consortium +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0.txt +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +#==========================================================================*/ + +from __future__ import print_function + +# The following line defines an ascii string used for dynamically refreshing +# the import and progress callbacks on the same terminal line. +# See http://www.termsys.demon.co.uk/vtansi.htm +# \033 is the C-style octal code for an escape character +# [2000D moves the cursor back 2000 columns, this is a brute force way of +# getting to the start of the line. +# [K erases the end of the line +clrLine = "\033[2000D\033[K" + + +def auto_not_in_place(v=True): + """Force it to not run in place + """ + import itkConfig + itkConfig.NotInPlace = v + + +def auto_progress(progressType=1): + """Set up auto progress report + + progressType: + 1 or True -> auto progress be used in a terminal + 2 -> simple auto progress (without special characters) + 0 or False -> disable auto progress + """ + import itkConfig + + if progressType is True or progressType == 1: + itkConfig.ImportCallback = terminal_import_callback + itkConfig.ProgressCallback = terminal_progress_callback + + elif progressType == 2: + itkConfig.ImportCallback = simple_import_callback + itkConfig.ProgressCallback = simple_progress_callback + + elif progressType is False or progressType == 0: + itkConfig.ImportCallback = None + itkConfig.ProgressCallback = None + + else: + raise ValueError("Invalid auto progress type: " + repr(progressType)) + + +def terminal_progress_callback(name, p): + """Display the progress of an object and clean the display once complete + + This function can be used with itkConfig.ProgressCallback + """ + import sys + print(clrLine + "%s: %f" % (name, p), file=sys.stderr) + if p == 1: + print(clrLine, file=sys.stderr) + + +def terminal_import_callback(name, p): + """Display the loading of a module and clean the display once complete + + This function can be used with itkConfig.ImportCallback + """ + import sys + print(clrLine + "Loading %s..." % name, file=sys.stderr) + if p == 1: + print(clrLine, file=sys.stderr) + + +def simple_import_callback(name, p): + """Print a message when a module is loading + + This function can be used with itkConfig.ImportCallback + """ + import sys + if p == 0: + print("Loading %s..." % name, file=sys.stderr) + elif p == 1: + print("done", file=sys.stderr) + + +def simple_progress_callback(name, p): + """Print a message when an object is running + + This function can be used with itkConfig.ProgressCallback + """ + import sys + if p == 0: + print("Running %s..." % name, file=sys.stderr) + elif p == 1: + print("done", file=sys.stderr) + + +def force_load(): + """force itk to load all the submodules""" + import itk + for k in dir(itk): + getattr(itk, k) + + +import sys + + +def echo(object, f=sys.stderr): + """Print an object is f + + If the object has a method Print(), this method is used. + repr(object) is used otherwise + """ + print(f, object) +del sys + + +def size(imageOrFilter): + """Return the size of an image, or of the output image of a filter + + This method take care of updating the needed informations + """ + # we don't need the entire output, only its size + imageOrFilter.UpdateOutputInformation() + img = output(imageOrFilter) + return img.GetLargestPossibleRegion().GetSize() + + +def physical_size(imageOrFilter): + """Return the physical size of an image, or of the output image of a filter + + This method take care of updating the needed informations + """ + # required because range is overladed in this module + from __builtin__ import range + spacing_ = spacing(imageOrFilter) + size_ = size(imageOrFilter) + result = [] + for i in range(0, spacing_.Size()): + result.append(spacing_.GetElement(i) * size_.GetElement(i)) + return result + + +def spacing(imageOrFilter): + """Return the spacing of an image, or of the output image of a filter + + This method take care of updating the needed informations + """ + # we don't need the entire output, only its size + imageOrFilter.UpdateOutputInformation() + img = output(imageOrFilter) + return img.GetSpacing() + + +def origin(imageOrFilter): + """Return the origin of an image, or of the output image of a filter + + This method take care of updating the needed informations + """ + # we don't need the entire output, only its size + imageOrFilter.UpdateOutputInformation() + img = output(imageOrFilter) + return img.GetOrigin() + + +def index(imageOrFilter): + """Return the index of an image, or of the output image of a filter + + This method take care of updating the needed informations + """ + # we don't need the entire output, only its size + imageOrFilter.UpdateOutputInformation() + img = output(imageOrFilter) + return img.GetLargestPossibleRegion().GetIndex() + + +def region(imageOrFilter): + """Return the region of an image, or of the output image of a filter + + This method take care of updating the needed informations + """ + # we don't need the entire output, only its size + imageOrFilter.UpdateOutputInformation() + img = output(imageOrFilter) + return img.GetLargestPossibleRegion() + + +# return an image +from itkTemplate import image, output + + +def template(cl): + """Return the template of a class (or of the class of an object) and + its parameters + + template() returns a tuple with 2 elements: + - the first one is the itkTemplate object + - the second is a tuple containing the template parameters + """ + from itkTemplate import itkTemplate + return itkTemplate.__class_to_template__[class_(cl)] + + +def ctype(s): + """Return the c type corresponding to the string passed in parameter + + The string can contain some extra spaces. + see also itkCType + """ + from itkTypes import itkCType + ret = itkCType.GetCType(" ".join(s.split())) + if ret is None: + raise KeyError("Unrecognized C type '%s'" % s) + return ret + + +def class_(obj): + """Return a class from an object + + Often in itk, the __class__ is not what the user is expecting. + class_() should do a better job + """ + import inspect + if inspect.isclass(obj): + # obj is already a class ! + return obj + else: + return obj.__class__ + + +def range(imageOrFilter): + """Return the range of values in a image of in the output image of a filter + + The minimum and maximum values are returned in a tuple: (min, max) + range() take care of updating the pipeline + """ + import itk + img = output(imageOrFilter) + img.UpdateOutputInformation() + img.Update() + # don't put that calculator in the automatic pipeline + tmp_auto_pipeline = auto_pipeline.current + auto_pipeline.current = None + comp = itk.MinimumMaximumImageCalculator[img].New(Image=img) + auto_pipeline.current = tmp_auto_pipeline + comp.Compute() + return (comp.GetMinimum(), comp.GetMaximum()) + + +def write(imageOrFilter, fileName, compression=False): + """Write a image or the output image of a filter to filename + + The writer is instantiated with the image type of the image in + parameter (or, again, with the output image of the filter in parameter) + """ + import itk + img = output(imageOrFilter) + img.UpdateOutputInformation() + # don't put that writer in the automatic pipeline + tmp_auto_pipeline = auto_pipeline.current + auto_pipeline.current = None + writer = itk.ImageFileWriter[img].New( + Input=img, + FileName=fileName, + UseCompression=compression) + auto_pipeline.current = tmp_auto_pipeline + writer.Update() + + +def search(s, case_sensitive=False): # , fuzzy=True): + """Search for a class name in the itk module. + """ + s = s.replace(" ", "") + if not case_sensitive: + s = s.lower() + import itk + names = sorted(dir(itk)) + # exact match first + if case_sensitive: + res = [n for n in names if s == n] + else: + res = [n for n in names if s == n.lower()] + # then exact match inside the name + if case_sensitive: + res += [n for n in names if s in n and s != n] + else: + res += [n for n in names if s in n.lower() and s != n.lower()] +# if fuzzy: +# try: +# everything now requires editdist +# import editdist +# if case_sensitive: +# res.sort(key=lambda x: editdist.distance(x, s)) +# else: +# res.sort(key=lambda x: (editdist.distance(x.lower(), s), x)) +# except: +# pass + return res + + +def set_inputs(newItkObject, args=[], kargs={}): + """Set the inputs of the given objects, according to the non named or the + named parameters in args and kargs + + This function tries to assign all the non named parameters in the input of + the newItkObject + - the first non named parameter in the first input, etc. + + The named parameters are used by calling the method with the same name + prefixed by 'Set'. + set_inputs( obj, kargs={'Threshold': 10} ) calls obj.SetThreshold(10) + + This is the function use in the enhanced New() method to manage the inputs. + It can be used to produce a similar behavior: + + def SetInputs(self, *args, **kargs): + import itk + itk.set_inputs(self, *args, **kargs) + """ + # try to get the images from the filters in args + args = [output(arg) for arg in args] + + # args without name are filter used to set input image + # + # count SetInput calls to call SetInput, SetInput2, SetInput3, ... + # usefull with filter which take 2 input (or more) like SubstractImageFiler + # Ex: substract image2.png to image1.png and save the result in result.png + # r1 = itk.ImageFileReader.US2.New(FileName='image1.png') + # r2 = itk.ImageFileReader.US2.New(FileName='image2.png') + # s = itk.SubtractImageFilter.US2US2US2.New(r1, r2) + # itk.ImageFileWriter.US2.New(s, FileName='result.png').Update() + try: + for setInputNb, arg in enumerate(args): + methodName = 'SetInput%i' % (setInputNb + 1) + if methodName in dir(newItkObject): + # first try to use methods called SetInput1, SetInput2, ... + # those method should have more chances to work in case of + # multiple input types + getattr(newItkObject, methodName)(arg) + else: + # no method called SetInput? + # try with the standard SetInput(nb, input) + newItkObject.SetInput(setInputNb, arg) + except TypeError as e: + # the exception have (at least) to possible reasons: + # + the filter don't take the input number as first argument + # + arg is an object of wrong type + # + # if it's not the first input, re-raise the exception + if setInputNb != 0: + raise e + # it's the first input, try to use the SetInput() method without input + # number + newItkObject.SetInput(args[0]) + # but raise an exception if there is more than 1 argument + if len(args) > 1: + raise TypeError('Object accept only 1 input.') + except AttributeError: + # There is no SetInput() method, try SetImage + # but before, check the number of inputs + if len(args) > 1: + raise TypeError('Object accept only 1 input.') + methodList = ['SetImage', 'SetInputImage'] + methodName = None + for m in methodList: + if m in dir(newItkObject): + methodName = m + if methodName: + getattr(newItkObject, methodName)(args[0]) + else: + raise AttributeError('No method found to set the input.') + + # named args : name is the function name, value is argument(s) + for attribName, value in kargs.iteritems(): + # use Set as prefix. It allow to use a shorter and more intuitive + # call (Ex: itk.ImageFileReader.UC2.New(FileName='image.png')) than + # with the full name + # (Ex: itk.ImageFileReader.UC2.New(SetFileName='image.png')) + if attribName not in ["auto_progress", "template_parameters"]: + attrib = getattr(newItkObject, 'Set' + attribName) + attrib(value) + + +def show(input, **kargs): + """display an image + """ + import itk + img = output(input) + if img.GetImageDimension() == 3 and "show3D" in dir(itk): + return itk.show3D(input, **kargs) + else: + # print("2D not supported yet, use the 3D viewer.") + return show2D(input, **kargs) + + +class show2D: + + """Display a 2D image + """ + + def __init__(self, imageOrFilter, Label=False, Title=None): + import tempfile + import itk + import os + import platform + # get some data from the environment + command = os.environ.get("WRAPITK_SHOW2D_COMMAND") + if command is None: + if platform.system() == "Darwin": + command = ( + "open -a ImageJ -n --args -eval 'open(\"%(image)s\"); " + "run (\"View 100%%\"); rename(\"%(title)s\");'") + else: + command = ( + "imagej %(image)s -run 'View 100%%' -eval " + "'rename(\"%(title)s\")' &") + + label_command = os.environ.get("WRAPITK_SHOW2D_LABEL_COMMAND") + if label_command is None: + if platform.system() == "Darwin": + label_command = ( + "open -a ImageJ -n --args -eval 'open(\"%(image)s\"); " + "run (\"View 100%%\"); rename(\"%(title)s\"); " + "run(\"3-3-2 RGB\");'") + else: + label_command = ( + "imagej %(image)s -run 'View 100%%' -eval " + "'rename(\"%(title)s\")' -run '3-3-2 RGB' &") + + compress = os.environ.get( + "WRAPITK_SHOW2D_COMPRESS", + "true").lower() in ["on", "true", "yes", "1"] + extension = os.environ.get("WRAPITK_SHOW2D_EXTENSION", ".tif") + + # use the tempfile module to get a non used file name and to put + # the file at the rignt place + self.__tmpFile__ = tempfile.NamedTemporaryFile(suffix=extension) + # get an updated image + img = output(imageOrFilter) + img.UpdateOutputInformation() + img.Update() + if Title is None: + # try to generate a title + s = img.GetSource() + if s: + s = itk.down_cast(s) + if hasattr(img, "GetSourceOutputIndex"): + o = '[%s]' % img.GetSourceOutputIndex() + elif hasattr(img, "GetSourceOutputName"): + o = '[%s]' % img.GetSourceOutputName() + else: + o = "" + Title = "%s%s" % (s.__class__.__name__, o) + else: + Title = img.__class__.__name__ + try: + import IPython.ipapi + ip = IPython.ipapi.get() + if ip is not None: + names = [] + ref = imageOrFilter + if s: + ref = s + for n, v in ip.user_ns.iteritems(): + if isinstance(v, itk.LightObject) and v == ref: + names.append(n) + if names != []: + Title = ", ".join(names) + " - " + Title + except ImportError: + # just do nothing + pass + # change the LabelMaps to an Image, so we can look at them easily + if 'LabelMap' in dir(itk) and img.GetNameOfClass() == 'LabelMap': + # retreive the biggest label in the label map + maxLabel = img.GetNthLabelObject( + img.GetNumberOfLabelObjects() - 1).GetLabel() + # search for a filter to convert the label map + lab = itk.LabelMapToLabelImageFilter.keys() + maxVal = itk.NumericTraits[itk.template(params[1])[1][0]].max() + cond = params[0] == class_(img) and maxVal >= maxLabel + label_image_type = sorted([params[1] for params in lab if cond])[0] + convert = itk.LabelMapToLabelImageFilter[ + img, label_image_type].New(img) + convert.Update() + img = convert.GetOutput() + # this is a label image - force the parameter + Label = True + write(img, self.__tmpFile__.name, compress) + # now run imview + import os + if Label: + os.system( + label_command % + {"image": self.__tmpFile__.name, "title": Title}) + else: + os.system( + command % + {"image": self.__tmpFile__.name, "title": Title}) + + +class templated_class: + + """This class is used to mimic the behavior of the templated C++ classes. + + It is used that way: + + class CustomClass: + # class definition here + CustomClass = templated_class(CustomClass) + + customObject = CustomClass[template, parameters].New() + + The template parameters are passed to the custom class constructor as a + named parameter 'template_parameters' in a tuple. + + The custom class may implement a static method + check_template_parameters(parameters) which should raise an exception if + the template parameters provided are not suitable to instantiate the custom + class. + """ + + def __init__(self, cls): + """cls is the custom class + """ + self.__cls__ = cls + self.__templates__ = {} + + def New(self, *args, **kargs): + """Use the parameters to infer the types of the template parameters. + """ + # extract the types from the arguments to instantiate the class + import itk + types = tuple(itk.class_(o) for o in args) + return self[types].New(*args, **kargs) + + def __getitem__(self, template_parameters): + """Return a pair class-template parameters ready to be instantiated. + + The template parameters may be validated if the custom class provide + the static method check_template_parameters(parameters). + """ + if not isinstance(template_parameters, tuple): + template_parameters = (template_parameters,) + return ( + templated_class.__templated_class_and_parameters__( + self, + template_parameters) + ) + + def check_template_parameters(self, template_parameters): + """Check the template parameters passed in parameter. + """ + # this method is there mainly to make possible to reuse it in the + # custom class constructor after having used templated_class(). + # Without that, the following example doesn't work: + # + # class CustomClass: + # def __init__(self, *args, **kargs): + # template_parameters = kargs["template_parameters"] + # CustomClass.check_template_parameters(template_parameters) + # other init stuff + # def check_template_parameters(template_parameters): + # check, really + # pass + # CustomClass = templated_class(CustomClass) + # + self.__cls__.check_template_parameters(template_parameters) + + def add_template(self, name, params): + if not isinstance(params, list) and not isinstance(params, tuple): + params = (params,) + params = tuple(params) + val = self[params] + self.__templates__[params] = val + setattr(self, name, val) + + def add_image_templates(self, *args): + import itk + if args == []: + return + combinations = [[t] for t in args[0]] + for types in args[1:]: + temp = [] + for t in types: + for c in combinations: + temp.append(c + [t]) + combinations = temp + for d in itk.DIMS: + for c in combinations: + parameters = [] + name = "" + for t in c: + parameters.append(itk.Image[t, d]) + name += "I" + t.short_name + str(d) + self.add_template(name, tuple(parameters)) + + class __templated_class_and_parameters__: + + """Inner class used to store the pair class-template parameters ready + to instantiate. + """ + + def __init__(self, templated_class, template_parameters): + self.__templated_class__ = templated_class + self.__template_parameters__ = template_parameters + if "check_template_parameters" in dir(templated_class.__cls__): + templated_class.__cls__.check_template_parameters( + template_parameters) + + def New(self, *args, **kargs): + """A New() method to mimic the ITK default behavior, even if the + class doesn't provide any New() method. + """ + kargs["template_parameters"] = self.__template_parameters__ + if "New" in dir(self.__templated_class__.__cls__): + obj = self.__templated_class__.__cls__.New(*args, **kargs) + else: + obj = self.__templated_class__.__cls__(*args, **kargs) + setattr( + obj, + "__template_parameters__", + self.__template_parameters__) + setattr(obj, "__templated_class__", self.__templated_class__) + return obj + + def __call__(self, *args, **kargs): + return self.New(*args, **kargs) + + def keys(self): + return self.__templates__.keys() + + # everything after this comment is for dict interface + # and is a copy/paste from DictMixin + # only methods to edit dictionary are not there + def __iter__(self): + for k in self.keys(): + yield k + + def has_key(self, key): + try: + value = self[key] + except KeyError: + return False + return True + + def __contains__(self, key): + return key in self + + # third level takes advantage of second level definitions + def iteritems(self): + for k in self: + yield (k, self[k]) + + def iterkeys(self): + return self.__iter__() + + # fourth level uses definitions from lower levels + def itervalues(self): + for _, v in self.iteritems(): + yield v + + def values(self): + return [v for _, v in self.iteritems()] + + def items(self): + return list(self.iteritems()) + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def __len__(self): + return len(self.keys()) + + +class pipeline: + + """A convenient class to store the reference to the filters of a pipeline + + With this class, a method can create a pipeline of several filters and + return it without losing the references to the filters in this pipeline. + The pipeline object act almost like a filter (it has a GetOutput() method) + and thus can be simply integrated in another pipeline. + """ + + def __init__(self, *args, **kargs): + self.clear() + self.input = None + set_inputs(self, args, kargs) + + def connect(self, filter): + """Connect a new filter to the pipeline + + The output of the first filter will be used as the input of this + one and the filter passed as parameter will be added to the list + """ + if self.GetOutput() is not None: + set_inputs(filter, [self.GetOutput()]) + self.append(filter) + + def append(self, filter): + """Add a new filter to the pipeline + + The new filter will not be connected. The user must connect it. + """ + self.filters.append(filter) + + def clear(self): + """Clear the filter list + """ + self.filters = [] + + def GetOutput(self, index=0): + """Return the output of the pipeline + + If another output is needed, use + pipeline.filters[-1].GetAnotherOutput() instead of this method, + subclass pipeline to implement another GetOutput() method, or use + expose() + """ + if len(self.filters) == 0: + return self.GetInput() + else: + filter = self.filters[-1] + if hasattr(filter, "__getitem__"): + return filter[index] + try: + return filter.GetOutput(index) + except: + if index == 0: + return filter.GetOutput() + else: + raise ValueError("Index can only be 0 on that object") + + def SetInput(self, input): + """Set the input of the pipeline + """ + if len(self.filters) != 0: + set_inputs(self.filters[0], [input]) + self.input = input + + def GetInput(self): + """Get the input of the pipeline + """ + return self.input + + def Update(self): + """Update the pipeline + """ + if len(self.filters) > 0: + return self.filters[-1].Update() + + def UpdateLargestPossibleRegion(self): + """Update the pipeline + """ + if len(self.filters) > 0: + return self.filters[-1].UpdateLargestPossibleRegion() + + def UpdateOutputInformation(self): + if "UpdateOutputInformation" in dir(self.filters[-1]): + self.filters[-1].UpdateOutputInformation() + else: + self.Update() + + def __len__(self): + if len(self.filters) == 0: + return 1 + else: + return self.filters[-1].GetNumberOfOutputs() + + def __getitem__(self, item): + return self.GetOutput(item) + + def __call__(self, *args, **kargs): + set_inputs(self, args, kargs) + self.UpdateLargestPossibleRegion() + return self + + def expose(self, name, new_name=None, position=-1): + """Expose an attribute from a filter of the minipeline. + + Once called, the pipeline instance has a new Set/Get set of methods to + access directly the corresponding method of one of the filter of the + pipeline. + Ex: p.expose( "Radius" ) + p.SetRadius( 5 ) + p.GetRadius( 5 ) + By default, the attribute usable on the pipeline instance has the same + name than the one of the filter, but it can be changed by providing a + value to new_name. + The last filter of the pipeline is used by default, but another one may + be used by giving its position. + Ex: p.expose("Radius", "SmoothingNeighborhood", 2) + p.GetSmoothingNeighborhood() + """ + if new_name is None: + new_name = name + src = self.filters[position] + ok = False + set_name = "Set" + name + if set_name in dir(src): + setattr(self, "Set" + new_name, getattr(src, set_name)) + ok = True + get_name = "Get" + name + if get_name in dir(src): + setattr(self, "Get" + new_name, getattr(src, get_name)) + ok = True + if not ok: + raise RuntimeError( + "No attribute %s at position %s." % + (name, position)) + + +class auto_pipeline(pipeline): + current = None + + def __init__(self, *args, **kargs): + pipeline.__init__(self, *args, **kargs) + self.Start() + + def Start(self): + auto_pipeline.current = self + + def Stop(self): + auto_pipeline.current = None + + +def down_cast(obj): + """Down cast an itkLightObject (or a object of a subclass) to its most + specialized type. + """ + import itk + import itkTemplate + className = obj.GetNameOfClass() + t = getattr(itk, className) + if isinstance(t, itkTemplate.itkTemplate): + for c in t.values(): + try: + return c.cast(obj) + except: + # fail silently for now + pass + raise RuntimeError( + "Can't downcast to a specialization of %s" % + className) + else: + return t.cast(obj) + + +def attribute_list(i, name): + """Returns a list of the specified attributes for the objects in the image. + + i: the input LabelImage + name: the attribute name + """ + import itk + i = itk.output(i) + relabel = itk.StatisticsRelabelLabelMapFilter[i].New( + i, + Attribute=name, + ReverseOrdering=True, + InPlace=False) + relabel.UpdateLargestPossibleRegion() + r = relabel.GetOutput() + l = [] + for i in range(1, r.GetNumberOfLabelObjects() + 1): + l.append(r.GetLabelObject(i).__getattribute__("Get" + name)()) + return l + + +def attributes_list(i, names): + """Returns a list of the specified attributes for the objects in the image. + + i: the input LabelImage + name: the attribute name + """ + import itk + i = itk.output(i) + relabel = itk.StatisticsRelabelLabelMapFilter[i].New( + i, + Attribute=names[0], + ReverseOrdering=True, + InPlace=False) + relabel.UpdateLargestPossibleRegion() + r = relabel.GetOutput() + l = [] + for i in range(1, r.GetNumberOfLabelObjects() + 1): + attrs = [] + for name in names: + attrs.append(r.GetLabelObject(i).__getattribute__("Get" + name)()) + l.append(tuple(attrs)) + return l + + +def attribute_dict(i, name): + """Returns a dict with the attribute values in keys and a list of the + corresponding objects in value + + i: the input LabelImage + name: the name of the attribute + """ + import itk + i = itk.output(i) + relabel = itk.StatisticsRelabelLabelMapFilter[i].New( + i, + Attribute=name, + ReverseOrdering=True, + InPlace=False) + relabel.UpdateLargestPossibleRegion() + r = relabel.GetOutput() + d = {} + for i in range(1, r.GetNumberOfLabelObjects() + 1): + lo = r.GetLabelObject(i) + v = lo.__getattribute__("Get" + name)() + l = d.get(v, []) + l.append(lo) + d[v] = l + return d + + +def number_of_objects(i): + """Returns the number of objets in the image. + + i: the input LabelImage + """ + import itk + i.UpdateLargestPossibleRegion() + i = itk.output(i) + return i.GetNumberOfLabelObjects() + + +def ipython_kw_matches(text): + """Match named ITK object's named parameters""" + import IPython.ipapi + import itk + import re + import inspect + import itkTemplate + regexp = re.compile(r''' + '.*?' | # single quoted strings or + ".*?" | # double quoted strings or + \w+ | # identifier + \S # other characters + ''', re.VERBOSE | re.DOTALL) + ip = IPython.ipapi.get() + if "." in text: # a parameter cannot be dotted + return [] + # 1. find the nearest identifier that comes before an unclosed + # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo". + # Use get_endidx() to find the indentifier at the cursor position + tokens = regexp.findall( + ip.IP.Completer.get_line_buffer()[:ip.IP.Completer.get_endidx()]) + tokens.reverse() + iterTokens = iter(tokens) + openPar = 0 + for token in iterTokens: + if token == ')': + openPar -= 1 + elif token == '(': + openPar += 1 + if openPar > 0: + # found the last unclosed parenthesis + break + else: + return [] + # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) + ids = [] + isId = re.compile(r'\w+$').match + while True: + try: + ids.append(iterTokens.next()) + if not isId(ids[-1]): + ids.pop() + break + if not iterTokens.next() == '.': + break + except StopIteration: + break + # lookup the candidate callable matches either using global_matches + # or attr_matches for dotted names + if len(ids) == 1: + callableMatches = ip.IP.Completer.global_matches(ids[0]) + else: + callableMatches = ip.IP.Completer.attr_matches('.'.join(ids[::-1])) + argMatches = [] + for callableMatch in callableMatches: + # drop the .New at this end, so we can search in the class members + if callableMatch.endswith(".New"): + callableMatch = callableMatch[:-4] + try: + object = eval(callableMatch, ip.IP.Completer.namespace) + if isinstance(object, itkTemplate.itkTemplate): + # this is a template - lets grab the first entry to search for + # the methods + object = object.values()[0] + namedArgs = [] + isin = isinstance(object, itk.LightObject) + issub = issubclass(object, itk.LightObject) + if isin or (inspect.isclass(object) and issub): + namedArgs = [n[3:] for n in dir(object) if n.startswith("Set")] + except Exception as e: + print(e) + continue + for namedArg in namedArgs: + if namedArg.startswith(text): + argMatches.append("%s=" % namedArg) + return argMatches + +# install progress callback and custom completer if we are in ipython +# interpreter +try: + import itkConfig + import IPython.ipapi + if IPython.ipapi.get(): + IPython.ipapi.get().IP.Completer.matchers.insert(0, ipython_kw_matches) + itkConfig.ProgressCallback = terminal_progress_callback + # some cleanup + del itkConfig, IPython +except ImportError: + # fail silently + pass diff --git a/Utilities/ITK/Wrapping/Generators/Python/itkExtras/CMakeLists.txt b/Utilities/ITK/Wrapping/Generators/Python/itkExtras/CMakeLists.txt deleted file mode 100644 index 878e7accad850dc786d43e29294956a03f56a472..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Python/itkExtras/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -# Copy python files for out-of-source builds, and set up install of same. - -# Create a list of Python files. -# WrapITK/Python/itkExtras/*.py -set(ITK_PYTHON_EXTRAS_FILES - __init__ - ) -# Done listing files. - -# Now copy these files if necessary. -set(ITK_WRAP_PYTHON_EXTRAS_INSTALL_FILES "") -if("${WrapITK_BINARY_DIR}" MATCHES "^${WrapITK_SOURCE_DIR}$") - # In source build -- no need to copy Python file. Do need to set up the install. - foreach(file ${ITK_PYTHON_EXTRAS_FILES}) - set(install_tgt "${CMAKE_CURRENT_SOURCE_DIR}/${file}.py") - set(ITK_WRAP_PYTHON_EXTRAS_INSTALL_FILES ${ITK_WRAP_PYTHON_EXTRAS_FILES} "${install_tgt}") - endforeach() -else() - set(ITK_WRAP_PYTHON_EXTRAS_FILES) - add_custom_target(copy_python_extras_files ALL) - foreach(file ${ITK_PYTHON_EXTRAS_FILES}) - set(src "${CMAKE_CURRENT_SOURCE_DIR}/${file}.py") - # recall that WRAP_ITK_BUILD_INTDIR expands to nothing if no config types are set, - # or to "CMAKE_CONFIG_INTDIR/" if there are such. Likewise, WRAP_ITK_INSTALL_INTDIR - # expands to ${BUILD_TYPE}/ or nothing. - set(copy_tgt "${CMAKE_CURRENT_BINARY_DIR}/${file}.py") - set(ITK_WRAP_PYTHON_EXTRAS_FILES ${ITK_WRAP_PYTHON_EXTRAS_FILES} "${copy_tgt}") - set(install_tgt "${CMAKE_CURRENT_BINARY_DIR}/${file}.py") - set(ITK_WRAP_PYTHON_EXTRAS_INSTALL_FILES ${ITK_WRAP_PYTHON_EXTRAS_INSTALL_FILES} "${install_tgt}") - - # create the directory to avoid loosing case on windows - file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${WRAP_ITK_INSTALL_INTDIR}${path}) - - add_custom_command(SOURCE ${src} - COMMAND ${CMAKE_COMMAND} - ARGS -E copy ${src} ${copy_tgt} - OUTPUTS ${copy_tgt} - TARGET copy_python_extras_files - COMMENT "source copy") - endforeach() - - # driver command to make the copy happen. - add_custom_command( - SOURCE copy_python_extras_files - DEPENDS ${ITK_WRAP_PYTHON_EXTRAS_FILES} - TARGET copy_python_extras_files) -endif() - -# Install the package python files. -WRAP_ITK_BINDINGS_INSTALL(/Python/itkExtras ${ITK_WRAP_PYTHON_EXTRAS_INSTALL_FILES}) diff --git a/Utilities/ITK/Wrapping/Generators/Python/itkExtras/__init__.py b/Utilities/ITK/Wrapping/Generators/Python/itkExtras/__init__.py deleted file mode 100644 index cea1b2f20e7fabde58e610abf765478c9636b45d..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Python/itkExtras/__init__.py +++ /dev/null @@ -1,1029 +0,0 @@ -#========================================================================== -# -# Copyright Insight Software Consortium -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0.txt -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -#==========================================================================*/ - -# new features introduced by itk module -# each new feature use a name in lower case -clrLine = "\033[2000D\033[K" - -def auto_not_in_place( v=True ) : - """Force it to not run in place - """ - import itkConfig - itkConfig.NotInPlace = v - -def auto_progress( progressType = 1 ): - """Set up auto progress report - - progressType: - 1 or True -> auto progress be used in a terminal - 2 -> simple auto progress (without special characters) - 0 or False -> disable auto progress - """ - import itkConfig - - if progressType == True or progressType == 1 : - itkConfig.ImportCallback = terminal_import_callback - itkConfig.ProgressCallback = terminal_progress_callback - - elif progressType == 2 : - itkConfig.ImportCallback = simple_import_callback - itkConfig.ProgressCallback = simple_progress_callback - - elif progressType == False or progressType == 0 : - itkConfig.ImportCallback = None - itkConfig.ProgressCallback = None - - else: - raise ValueError("Invalid auto progress type: "+repr(progressType)) - -def terminal_progress_callback(name, p): - """Display the progress of an object and clean the display once complete - - This function can be used with itkConfig.ProgressCallback - """ - import sys - print >> sys.stderr, clrLine+"%s: %f" % (name, p), - if p == 1 : - print >> sys.stderr, clrLine, - -def terminal_import_callback(name, p): - """Display the loading of a module and clean the display once complete - - This function can be used with itkConfig.ImportCallback - """ - import sys - print >> sys.stderr, clrLine+"Loading %s..." % name, - if p == 1 : - print >> sys.stderr, clrLine, - -def simple_import_callback(name, p): - """Print a message when a module is loading - - This function can be used with itkConfig.ImportCallback - """ - import sys - if p == 0: - print >> sys.stderr, "Loading %s..." % name, - elif p == 1 : - print >> sys.stderr, "done" - -def simple_progress_callback(name, p): - """Print a message when an object is running - - This function can be used with itkConfig.ProgressCallback - """ - import sys - if p == 0 : - print >> sys.stderr, "Running %s..." % name, - elif p == 1 : - print >> sys.stderr, "done" - - -def force_load(): - """force itk to load all the submodules""" - import itk - for k in dir(itk): - getattr(itk, k) - - -import sys -def echo(object, f=sys.stderr) : - """Print an object is f - - If the object has a method Print(), this method is used. - repr(object) is used otherwise - """ - print >> f, object -del sys - - -def size(imageOrFilter) : - """Return the size of an image, or of the output image of a filter - - This method take care of updating the needed informations - """ - # we don't need the entire output, only its size - imageOrFilter.UpdateOutputInformation() - img = output(imageOrFilter) - return img.GetLargestPossibleRegion().GetSize() - - -def physical_size(imageOrFilter) : - """Return the physical size of an image, or of the output image of a filter - - This method take care of updating the needed informations - """ - from __builtin__ import range # required because range is overladed in this module - spacing_ = spacing(imageOrFilter) - size_ = size(imageOrFilter) - result = [] - for i in range(0, spacing_.Size()): - result.append( spacing_.GetElement(i) * size_.GetElement(i) ) - return result - - -def spacing(imageOrFilter) : - """Return the spacing of an image, or of the output image of a filter - - This method take care of updating the needed informations - """ - # we don't need the entire output, only its size - imageOrFilter.UpdateOutputInformation() - img = output(imageOrFilter) - return img.GetSpacing() - - -def origin(imageOrFilter) : - """Return the origin of an image, or of the output image of a filter - - This method take care of updating the needed informations - """ - # we don't need the entire output, only its size - imageOrFilter.UpdateOutputInformation() - img = output(imageOrFilter) - return img.GetOrigin() - - -def index(imageOrFilter) : - """Return the index of an image, or of the output image of a filter - - This method take care of updating the needed informations - """ - # we don't need the entire output, only its size - imageOrFilter.UpdateOutputInformation() - img = output(imageOrFilter) - return img.GetLargestPossibleRegion().GetIndex() - - -def region(imageOrFilter) : - """Return the region of an image, or of the output image of a filter - - This method take care of updating the needed informations - """ - # we don't need the entire output, only its size - imageOrFilter.UpdateOutputInformation() - img = output(imageOrFilter) - return img.GetLargestPossibleRegion() - - -def strel(dim, radius=1) : - """A method to create a ball structuring element - """ - import itk - import sys - # print >> sys.stderr, "strel() is deprecated and will be removed in the next release" - return itk.FlatStructuringElement[dim].Ball(radius) - -# return an image -from itkTemplate import image, output - - -def template(cl) : - """Return the template of a class (or of the class of an object) and its parameters - - template() returns a tuple with 2 elements: - - the first one is the itkTemplate object - - the second is a tuple containing the template parameters - """ - from itkTemplate import itkTemplate - return itkTemplate.__class_to_template__[class_(cl)] - - -def ctype(s) : - """Return the c type corresponding to the string passed in parameter - - The string can contain some extra spaces. - see also itkCType - """ - from itkTypes import itkCType - ret = itkCType.GetCType(" ".join(s.split())) - if ret == None : - raise KeyError("Unrecognized C type '%s'" % s) - return ret - - -def class_(obj) : - """Return a class from an object - - Often in itk, the __class__ is not what the user is expecting. - class_() should do a better job - """ - import inspect - if inspect.isclass(obj) : - # obj is already a class ! - return obj - else : - return obj.__class__ - - -def range(imageOrFilter) : - """Return the range of values in a image of in the output image of a filter - - The minimum and maximum values are returned in a tuple: (min, max) - range() take care of updating the pipeline - """ - import itk - img = output(imageOrFilter) - img.UpdateOutputInformation() - img.Update() - # don't put that calculator in the automatic pipeline - tmp_auto_pipeline = auto_pipeline.current - auto_pipeline.current = None - comp = itk.MinimumMaximumImageCalculator[img].New(Image=img) - auto_pipeline.current = tmp_auto_pipeline - comp.Compute() - return (comp.GetMinimum(), comp.GetMaximum()) - - -def write(imageOrFilter, fileName, compression=False): - """Write a image or the output image of a filter to filename - - The writer is instantiated with the image type of the image in - parameter (or, again, with the output image of the filter in parameter) - """ - import itk - img = output(imageOrFilter) - img.UpdateOutputInformation() - # don't put that writer in the automatic pipeline - tmp_auto_pipeline = auto_pipeline.current - auto_pipeline.current = None - writer = itk.ImageFileWriter[img].New(Input=img, FileName=fileName, UseCompression=compression) - auto_pipeline.current = tmp_auto_pipeline - writer.Update() - - -def index_to_physical_point( imageOrFilter, idx ): - """Get the pysical point in an image from an index - - imageOrFilter is the image where the physical point must be computed - idx is the index used to compute the physical point. It can be a continuous index. - """ - import sys - print >> sys.stderr, "WrapITK warning: itk.index_to_physical_point() is deprecated. The coresponding templated method is now available in itk::ImageBase." - from __builtin__ import range # required because range is overladed in this module - # get the image if needed - img = output( imageOrFilter ) - dim = img.GetImageDimension() - o = origin( img ) - s = spacing( img ) - - # use the typemaps to really get a continuous index - import itk - idx = itk.ContinuousIndex[ itk.D, dim ]( idx ) - - # create the output object - p = itk.Point[ itk.D, dim ]() - for i in range( 0, dim ): - p[i] = s[i] * idx[i] + o[i] - return p - - -def physical_point_to_continuous_index( imageOrFilter, p ): - """Get the continuous index in an image from the physical point - - imageOrFilter is the image where the physical point must be computed - p is the point used to compute the index - """ - import sys - print >> sys.stderr, "WrapITK warning: itk.index_to_physical_point() is deprecated. The coresponding templated method is now available in itk::ImageBase." - from __builtin__ import range # required because range is overladed in this module - # get the image if needed - img = output( imageOrFilter ) - dim = img.GetImageDimension() - o = origin( img ) - s = spacing( img ) - - # use the typemaps to really get a point - import itk - p = itk.Point[ itk.D, dim ]( p ) - - # create the output object - idx = itk.ContinuousIndex[ itk.D, dim ]() - for i in range( 0, dim ): - idx.SetElement( i, ( p[i] - o[i] ) / s[i] ) - return idx - - -def physical_point_to_index( imageOrFilter, p ): - """Get the index in an image from the physical point - - image is the image where the physical point must be computed - p is the point used to compute the index - """ - import sys - print >> sys.stderr, "WrapITK warning: itk.physical_point_to_index() is deprecated. The coresponding templated method is now available in itk::ImageBase." - from __builtin__ import range # required because range is overladed in this module - # get the image if needed - img = output( imageOrFilter ) - dim = img.GetImageDimension() - o = origin( img ) - s = spacing( img ) - - # use the typemaps to really get a point - import itk - p = itk.Point[ itk.D, dim ]( p ) - - # create the output object - idx = itk.Index[ dim ]() - for i in range( 0, dim ): - idx.SetElement( i, int( round( ( p[i] - o[i] ) / s[i] ) ) ) - return idx - - -def search( s, case_sensitive=False): #, fuzzy=True): - """Search for a class name in the itk module. - """ - s = s.replace(" ", "") - if not case_sensitive: - s = s.lower() - import itk - names = dir(itk) - names.sort() - # exact match first - if case_sensitive: - res = [n for n in names if s == n] - else: - res = [n for n in names if s == n.lower()] - # then exact match inside the name - if case_sensitive: - res += [n for n in names if s in n and s != n] - else: - res += [n for n in names if s in n.lower() and s != n.lower()] -# if fuzzy: -# try: -# # everything now requires editdist -# import editdist -# if case_sensitive: -# res.sort(key=lambda x: editdist.distance(x, s)) -# else: -# res.sort(key=lambda x: (editdist.distance(x.lower(), s), x)) -# except: -# pass - return res - - -def set_inputs( newItkObject, args=[], kargs={} ): - """Set the inputs of the given objects, according to the non named or the named parameters in args and kargs - - This function tries to assign all the non named parameters in the input of the newItkObject - - the first non named parameter in the first input, etc. - - The named parameters are used by calling the method with the same name prefixed by 'Set'. - set_inputs( obj, kargs={'Threshold': 10} ) calls obj.SetThreshold(10) - - This is the function use in the enhanced New() method to manage the inputs. - It can be used to produce a similar behavior: - - def SetInputs(self, *args, **kargs): - import itk - itk.set_inputs(self, *args, **kargs) - """ - # try to get the images from the filters in args - args = [output(arg) for arg in args] - - # args without name are filter used to set input image - # - # count SetInput calls to call SetInput, SetInput2, SetInput3, ... - # usefull with filter which take 2 input (or more) like SubstractImageFiler - # Ex: substract image2.png to image1.png and save the result in result.png - # r1 = itk.ImageFileReader.US2.New(FileName='image1.png') - # r2 = itk.ImageFileReader.US2.New(FileName='image2.png') - # s = itk.SubtractImageFilter.US2US2US2.New(r1, r2) - # itk.ImageFileWriter.US2.New(s, FileName='result.png').Update() - try : - for setInputNb, arg in enumerate(args) : - methodName = 'SetInput%i' % (setInputNb+1) - if methodName in dir(newItkObject) : - # first try to use methods called SetInput1, SetInput2, ... - # those method should have more chances to work in case of multiple - # input types - getattr(newItkObject, methodName)(arg) - else : - # no method called SetInput? - # try with the standard SetInput(nb, input) - newItkObject.SetInput(setInputNb, arg) - except TypeError, e : - # the exception have (at least) to possible reasons: - # + the filter don't take the input number as first argument - # + arg is an object of wrong type - # - # if it's not the first input, re-raise the exception - if setInputNb != 0 : - raise e - # it's the first input, try to use the SetInput() method without input number - newItkObject.SetInput(args[0]) - # but raise an exception if there is more than 1 argument - if len(args) > 1 : - raise TypeError('Object accept only 1 input.') - except AttributeError : - # There is no SetInput() method, try SetImage - # but before, check the number of inputs - if len(args) > 1 : - raise TypeError('Object accept only 1 input.') - methodList = ['SetImage', 'SetInputImage'] - methodName = None - for m in methodList: - if m in dir(newItkObject): - methodName = m - if methodName : - getattr(newItkObject, methodName)(args[0]) - else: - raise AttributeError('No method found to set the input.') - - # named args : name is the function name, value is argument(s) - for attribName, value in kargs.iteritems() : - # use Set as prefix. It allow to use a shorter and more intuitive - # call (Ex: itk.ImageFileReader.UC2.New(FileName='image.png')) than with the - # full name (Ex: itk.ImageFileReader.UC2.New(SetFileName='image.png')) - if attribName not in ["auto_progress", "template_parameters"] : - attrib = getattr(newItkObject, 'Set' + attribName) - attrib(value) - - -def show(input, **kargs) : - """display an image - """ - import itk - img = output(input) - if img.GetImageDimension() == 3 and "show3D" in dir(itk): - return itk.show3D(input, **kargs) - else : - # print "2D not supported yet, use the 3D viewer." - return show2D(input, **kargs) - -class show2D : - """Display a 2D image - """ - def __init__(self, imageOrFilter, Label=False, Title=None) : - import tempfile, itk, os, platform - # get some data from the environment - command = os.environ.get("WRAPITK_SHOW2D_COMMAND") - if command==None: - if platform.system() == "Darwin": - command = "open -a ImageJ -n --args -eval 'open(\"%(image)s\"); run (\"View 100%%\"); rename(\"%(title)s\");'" - else: - command = "imagej %(image)s -run 'View 100%%' -eval 'rename(\"%(title)s\")' &" - - label_command = os.environ.get("WRAPITK_SHOW2D_LABEL_COMMAND") - if label_command==None: - if platform.system() == "Darwin": - label_command = "open -a ImageJ -n --args -eval 'open(\"%(image)s\"); run (\"View 100%%\"); rename(\"%(title)s\"); run(\"3-3-2 RGB\");'" - else: - label_command = "imagej %(image)s -run 'View 100%%' -eval 'rename(\"%(title)s\")' -run '3-3-2 RGB' &" - - compress = os.environ.get("WRAPITK_SHOW2D_COMPRESS", "true").lower() in ["on", "true", "yes", "1"] - extension = os.environ.get("WRAPITK_SHOW2D_EXTENSION", ".tif") - - # use the tempfile module to get a non used file name and to put - # the file at the rignt place - self.__tmpFile__ = tempfile.NamedTemporaryFile(suffix=extension) - # get an updated image - img = output(imageOrFilter) - img.UpdateOutputInformation() - img.Update() - if Title == None: - # try to generate a title - s = img.GetSource() - if s: - s = itk.down_cast(s) - if hasattr(img, "GetSourceOutputIndex"): - o = '[%s]' % img.GetSourceOutputIndex() - elif hasattr(img, "GetSourceOutputName"): - o = '[%s]' % img.GetSourceOutputName() - else: - o = "" - Title = "%s%s" % (s.__class__.__name__, o) - else: - Title = img.__class__.__name__ - try: - import IPython.ipapi - ip = IPython.ipapi.get() - if ip != None: - names = [] - ref = imageOrFilter - if s: - ref = s - for n, v in ip.user_ns.iteritems(): - if isinstance(v, itk.LightObject) and v == ref: - names.append(n) - if names != []: - Title = ", ".join(names)+" - "+Title - except ImportError: - # just do nothing - pass - # change the LabelMaps to an Image, so we can look at them easily - if 'LabelMap' in dir(itk) and img.GetNameOfClass() == 'LabelMap': - # retreive the biggest label in the label map - maxLabel = img.GetNthLabelObject( img.GetNumberOfLabelObjects() - 1 ).GetLabel() - # search for a filter to convert the label map - label_image_type = sorted( [params[1] for params in itk.LabelMapToLabelImageFilter.keys() if params[0] == class_(img) and itk.NumericTraits[itk.template(params[1])[1][0]].max() >= maxLabel ] )[0] - convert = itk.LabelMapToLabelImageFilter[ img, label_image_type ].New( img ) - convert.Update() - img = convert.GetOutput() - # this is a label image - force the parameter - Label = True - write(img, self.__tmpFile__.name, compress) - # now run imview - import os - if Label: - os.system( label_command % {"image":self.__tmpFile__.name, "title": Title} ) - else: - os.system( command % {"image":self.__tmpFile__.name, "title": Title} ) - #tmpFile.close() - - -class templated_class: - """This class is used to mimic the behavior of the templated C++ classes. - - It is used that way: - - class CustomClass: - # class definition here - CustomClass = templated_class(CustomClass) - - customObject = CustomClass[template, parameters].New() - - The template parameters are passed to the custom class constructor as a named parameter - 'template_parameters' in a tuple. - - The custom class may implement a static method check_template_parameters(parameters) - which should raise an exception if the template parameters provided are not suitable - to instantiate the custom class. - """ - def __init__(self, cls): - """cls is the custom class - """ - self.__cls__ = cls - self.__templates__ = {} - - def New(self, *args, **kargs): - """Use the parameters to infer the types of the template parameters. - """ - # extract the types from the arguments to instantiate the class - import itk - types = tuple(itk.class_(o) for o in args) - return self[types].New(*args, **kargs) - - def __getitem__(self, template_parameters): - """Return a pair class-template parameters ready to be instantiated. - - The template parameters may be validated if the custom class provide the static - method check_template_parameters(parameters). - """ - if not isinstance(template_parameters, tuple): - template_parameters = (template_parameters,) - return templated_class.__templated_class_and_parameters__(self, template_parameters) - - def check_template_parameters(self, template_parameters): - """Check the template parameters passed in parameter. - """ - # this method is there mainly to make possible to reuse it in the custom class - # constructor after having used templated_class(). Without that, the following - # example doesn't work: - # - # class CustomClass: - # def __init__(self, *args, **kargs): - # template_parameters = kargs["template_parameters"] - # CustomClass.check_template_parameters(template_parameters) - # # other init stuff - # def check_template_parameters(template_parameters): - # # check, really - # pass - # CustomClass = templated_class(CustomClass) - # - self.__cls__.check_template_parameters(template_parameters) - - def add_template(self, name, params): - if not isinstance(params, list) and not isinstance(params, tuple): - params = (params,) - params = tuple(params) - val = self[params] - self.__templates__[params] = val - setattr(self, name, val) - - def add_image_templates(self, *args): - import itk - if args == []: - return - combinations = [[t] for t in args[0]] - for types in args[1:]: - temp = [] - for t in types: - for c in combinations: - temp.append(c+[t]) - combinations = temp - for d in itk.DIMS: - for c in combinations: - parameters = [] - name = "" - for t in c: - parameters.append( itk.Image[t, d] ) - name += "I"+t.short_name+str(d) - self.add_template(name, tuple(parameters)) - - class __templated_class_and_parameters__: - """Inner class used to store the pair class-template parameters ready to instantiate. - """ - def __init__(self, templated_class, template_parameters): - self.__templated_class__ = templated_class - self.__template_parameters__ = template_parameters - if "check_template_parameters" in dir(templated_class.__cls__): - templated_class.__cls__.check_template_parameters(template_parameters) - - def New(self, *args, **kargs): - """A New() method to mimic the ITK default behavior, even if the class doesn't provide any New() method. - """ - kargs["template_parameters"] = self.__template_parameters__ - if "New" in dir(self.__templated_class__.__cls__): - obj = self.__templated_class__.__cls__.New(*args, **kargs) - else: - obj = self.__templated_class__.__cls__(*args, **kargs) - setattr(obj, "__template_parameters__", self.__template_parameters__) - setattr(obj, "__templated_class__", self.__templated_class__) - return obj - - def __call__(self, *args, **kargs): - return self.New(*args, **kargs) - - def keys(self): - return self.__templates__.keys() - - # everything after this comment is for dict interface - # and is a copy/paste from DictMixin - # only methods to edit dictionary are not there - def __iter__(self): - for k in self.keys(): - yield k - - def has_key(self,key): - try: - value=self[key] - except KeyError: - return False - return True - - def __contains__(self,key): - return self.has_key(key) - - # third level takes advantage of second level definitions - def iteritems(self): - for k in self: - yield (k,self[k]) - - def iterkeys(self): - return self.__iter__() - - # fourth level uses definitions from lower levels - def itervalues(self): - for _,v in self.iteritems(): - yield v - - def values(self): - return [v for _,v in self.iteritems()] - - def items(self): - return list(self.iteritems()) - - def get(self,key,default=None): - try: - return self[key] - except KeyError: - return default - - def __len__(self): - return len(self.keys()) - - -class pipeline: - """A convenient class to store the reference to the filters of a pipeline - - With this class, a method can create a pipeline of several filters and return - it without losing the references to the filters in this pipeline. The pipeline - object act almost like a filter (it has a GetOutput() method) and thus can - be simply integrated in another pipeline. - """ - def __init__( self, *args, **kargs ): - self.clear() - self.input = None - set_inputs( self, args, kargs ) - - def connect( self, filter ): - """Connect a new filter to the pipeline - - The output of the first filter will be used as the input of this - one and the filter passed as parameter will be added to the list - """ - if self.GetOutput() != None: - set_inputs(filter, [self.GetOutput()] ) - self.append( filter ) - - def append( self, filter ): - """Add a new filter to the pipeline - - The new filter will not be connected. The user must connect it. - """ - self.filters.append( filter ) - - def clear( self ): - """Clear the filter list - """ - self.filters = [] - - def GetOutput( self, index=0 ): - """Return the output of the pipeline - - If another output is needed, use - pipeline.filters[-1].GetAnotherOutput() instead of this method, subclass - pipeline to implement another GetOutput() method, or use expose() - """ - if len(self.filters) == 0: - return self.GetInput() - else : - filter = self.filters[-1] - if hasattr(filter, "__getitem__"): - return filter[index] - try: - return filter.GetOutput(index) - except: - if index == 0: - return filter.GetOutput() - else: - raise ValueError("Index can only be 0 on that object") - - def SetInput( self, input ): - """Set the input of the pipeline - """ - if len(self.filters) != 0: - set_inputs(self.filters[0], [input]) - self.input = input - - def GetInput( self ): - """Get the input of the pipeline - """ - return self.input - - def Update( self ): - """Update the pipeline - """ - if len(self.filters) > 0: - return self.filters[-1].Update() - - def UpdateLargestPossibleRegion( self ): - """Update the pipeline - """ - if len(self.filters) > 0: - return self.filters[-1].UpdateLargestPossibleRegion() - - def UpdateOutputInformation( self ): - if "UpdateOutputInformation" in dir(self.filters[-1]): - self.filters[-1].UpdateOutputInformation() - else: - self.Update() - - def __len__(self): - if len(self.filters) == 0: - return 1 - else: - return self.filters[-1].GetNumberOfOutputs() - - def __getitem__(self, item): - return self.GetOutput( item ) - - def __call__(self, *args, **kargs): - set_inputs( self, args, kargs ) - self.UpdateLargestPossibleRegion() - return self - - def expose(self, name, new_name=None, position=-1): - """Expose an attribute from a filter of the minipeline. - - Once called, the pipeline instance has a new Set/Get set of methods to access - directly the corresponding method of one of the filter of the pipeline. - Ex: p.expose( "Radius" ) - p.SetRadius( 5 ) - p.GetRadius( 5 ) - By default, the attribute usable on the pipeline instance has the same name than - the one of the filter, but it can be changed by providing a value to new_name. - The last filter of the pipeline is used by default, but another one may be used - by giving its position. - Ex: p.expose("Radius", "SmoothingNeighborhood", 2) - p.GetSmoothingNeighborhood() - """ - if new_name == None: - new_name = name - src = self.filters[position] - ok = False - set_name = "Set" + name - if set_name in dir(src): - setattr(self, "Set" + new_name, getattr(src, set_name)) - ok = True - get_name = "Get" + name - if get_name in dir(src): - setattr(self, "Get" + new_name, getattr(src, get_name)) - ok = True - if not ok: - raise RuntimeError("No attribute %s at position %s." % (name, position)) - - -class auto_pipeline(pipeline): - current = None - - def __init__(self, *args, **kargs): - pipeline.__init__(self, *args, **kargs) - self.Start() - - def Start(self): - auto_pipeline.current = self - - def Stop(self): - auto_pipeline.current = None - - -def down_cast(obj): - """Down cast an itkLightObject (or a object of a subclass) to its most specialized type. - """ - import itk, itkTemplate - className = obj.GetNameOfClass() - t = getattr(itk, className) - if isinstance(t, itkTemplate.itkTemplate): - for c in t.values(): - try: - return c.cast(obj) - except: - # fail silently for now - pass - raise RuntimeError("Can't downcast to a specialization of %s" % className) - else: - return t.cast(obj) - -def attribute_list( i, name ): - """Returns a list of the specified attributes for the objects in the image. - - i: the input LabelImage - name: the attribute name - """ - import itk - i = itk.output(i) - relabel = itk.StatisticsRelabelLabelMapFilter[i].New(i, Attribute=name, ReverseOrdering=True, InPlace=False) - relabel.UpdateLargestPossibleRegion() - r = relabel.GetOutput() - l = [] - for i in range(1, r.GetNumberOfLabelObjects()+1): - l.append( r.GetLabelObject(i).__getattribute__("Get"+name)() ) - return l - - -def attributes_list( i, names ): - """Returns a list of the specified attributes for the objects in the image. - - i: the input LabelImage - name: the attribute name - """ - import itk - i = itk.output(i) - relabel = itk.StatisticsRelabelLabelMapFilter[i].New(i, Attribute=names[0], ReverseOrdering=True, InPlace=False) - relabel.UpdateLargestPossibleRegion() - r = relabel.GetOutput() - l = [] - for i in range(1, r.GetNumberOfLabelObjects()+1): - attrs = [] - for name in names : - attrs.append( r.GetLabelObject(i).__getattribute__("Get"+name)() ) - l.append( tuple( attrs ) ) - return l - - -def attribute_dict( i, name ): - """Returns a dict with the attribute values in keys and a list of the corresponding objects in value - - i: the input LabelImage - name: the name of the attribute - """ - import itk - i = itk.output(i) - relabel = itk.StatisticsRelabelLabelMapFilter[i].New(i, Attribute=name, ReverseOrdering=True, InPlace=False) - relabel.UpdateLargestPossibleRegion() - r = relabel.GetOutput() - d = {} - for i in range(1, r.GetNumberOfLabelObjects()+1): - lo = r.GetLabelObject(i) - v = lo.__getattribute__("Get"+name)() - l = d.get( v, [] ) - l.append( lo ) - d[v] = l - return d - - -def number_of_objects( i ): - """Returns the number of objets in the image. - - i: the input LabelImage - """ - import itk - i.UpdateLargestPossibleRegion() - i = itk.output(i) - return i.GetNumberOfLabelObjects() - -def ipython_kw_matches(text): - """Match named ITK object's named parameters""" - import IPython.ipapi, itk, re, inspect, itkTemplate - regexp = re.compile(r''' - '.*?' | # single quoted strings or - ".*?" | # double quoted strings or - \w+ | # identifier - \S # other characters - ''', re.VERBOSE | re.DOTALL) - ip = IPython.ipapi.get() - if "." in text: # a parameter cannot be dotted - return [] - # 1. find the nearest identifier that comes before an unclosed - # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo". - # Use get_endidx() to find the indentifier at the cursor position - tokens = regexp.findall(ip.IP.Completer.get_line_buffer()[:ip.IP.Completer.get_endidx()]) - tokens.reverse() - iterTokens = iter(tokens); openPar = 0 - for token in iterTokens: - if token == ')': - openPar -= 1 - elif token == '(': - openPar += 1 - if openPar > 0: - # found the last unclosed parenthesis - break - else: - return [] - # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) - ids = [] - isId = re.compile(r'\w+$').match - while True: - try: - ids.append(iterTokens.next()) - if not isId(ids[-1]): - ids.pop(); break - if not iterTokens.next() == '.': - break - except StopIteration: - break - # lookup the candidate callable matches either using global_matches - # or attr_matches for dotted names - if len(ids) == 1: - callableMatches = ip.IP.Completer.global_matches(ids[0]) - else: - callableMatches = ip.IP.Completer.attr_matches('.'.join(ids[::-1])) - argMatches = [] - for callableMatch in callableMatches: - # drop the .New at this end, so we can search in the class members - if callableMatch.endswith(".New"): - callableMatch = callableMatch[:-4] - try: - object = eval(callableMatch, ip.IP.Completer.namespace) - if isinstance(object, itkTemplate.itkTemplate): - # this is a template - lets grab the first entry to search for the methods - object = object.values()[0] - namedArgs = [] - if isinstance(object, itk.LightObject) or (inspect.isclass(object) and issubclass(object, itk.LightObject)): - namedArgs = [n[3:] for n in dir(object) if n.startswith("Set")] - except Exception, e: - print e - continue - for namedArg in namedArgs: - if namedArg.startswith(text): - argMatches.append("%s=" %namedArg) - return argMatches - -# install progress callback and custom completer if we are in ipython interpreter -try: - import itkConfig, IPython.ipapi - if IPython.ipapi.get(): - IPython.ipapi.get().IP.Completer.matchers.insert(0, ipython_kw_matches) - itkConfig.ProgressCallback = terminal_progress_callback - # some cleanup - del itkConfig, IPython -except ImportError: - # fail silently - pass - -# now loads the other modules we may found in the same directory -import os.path, sys -directory = os.path.dirname(__file__) -moduleNames = [name[:-len('.py')] for name in os.listdir(directory) if name.endswith('.py') and name != '__init__.py'] -for name in moduleNames: - # there should be another way - I don't like to much exec -, but the which one ?? - exec "from %s import *" % name -# some cleaning -del directory, os, sys, moduleNames, name diff --git a/Utilities/ITK/Wrapping/Generators/Python/itkLazy.py b/Utilities/ITK/Wrapping/Generators/Python/itkLazy.py index 4facba413f1a03bd85588b1fe95543e9eabcd604..cfc7ebafb823bf26b0b02ea6e2ab56a0063dd02e 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/itkLazy.py +++ b/Utilities/ITK/Wrapping/Generators/Python/itkLazy.py @@ -17,29 +17,34 @@ #==========================================================================*/ -import types, itkBase +import types +import itkBase not_loaded = 'not loaded' + class LazyITKModule(types.ModuleType): - """Subclass of ModuleType that implements a custom __getattribute__ method - to allow lazy-loading of attributes from ITK sub-modules.""" - def __init__(self, name, lazy_attributes): - types.ModuleType.__init__(self, name) - self.__lazy_attributes = lazy_attributes - for k in lazy_attributes: - setattr(self, k, not_loaded) - def __getattribute__(self, attr): - value = types.ModuleType.__getattribute__(self, attr) - if value is not_loaded: - module = self.__lazy_attributes[attr] - namespace = {} - itkBase.LoadModule(module, namespace) - # Load into 'namespace' first, then self.__dict__ (via setattr) to - # prevent the warnings about overwriting the 'NotLoaded' values already - # in in self.__dict__ we would get if we just passed self.__dict__ to - # itkBase.LoadModule. - for k, v in namespace.items(): - setattr(self, k, v) - value = namespace[attr] - return value + + """Subclass of ModuleType that implements a custom __getattribute__ method + to allow lazy-loading of attributes from ITK sub-modules.""" + + def __init__(self, name, lazy_attributes): + types.ModuleType.__init__(self, name) + self.__lazy_attributes = lazy_attributes + for k in lazy_attributes: + setattr(self, k, not_loaded) + + def __getattribute__(self, attr): + value = types.ModuleType.__getattribute__(self, attr) + if value is not_loaded: + module = self.__lazy_attributes[attr] + namespace = {} + itkBase.LoadModule(module, namespace) + # Load into 'namespace' first, then self.__dict__ (via setattr) to + # prevent the warnings about overwriting the 'NotLoaded' values + # already in self.__dict__ we would get if we just passed + # self.__dict__ to itkBase.LoadModule. + for k, v in namespace.items(): + setattr(self, k, v) + value = namespace[attr] + return value diff --git a/Utilities/ITK/Wrapping/Generators/Python/itkTemplate.py b/Utilities/ITK/Wrapping/Generators/Python/itkTemplate.py index d8d3c38845d436e87103abbb8f854d6408758cb0..c72929484858dd6cae18df5471f0f2e17d59172e 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/itkTemplate.py +++ b/Utilities/ITK/Wrapping/Generators/Python/itkTemplate.py @@ -16,364 +16,411 @@ # #==========================================================================*/ +from __future__ import print_function + import types import inspect import sys import os +import warnings import itkConfig from itkTypes import itkCType -def registerNoTpl(name, cl): - """Register a class without template - - It can seem not useful to register classes without template (and it wasn't - useful until the SmartPointer template was generated), but those classes - can be used as template argument of classes with template. - """ - itkTemplate.__templates__[normalizeName(name)] = cl - +def itkFormatWarning(msg, *a): + """"Format the warnings issued by itk to display only the message. -def normalizeName(name): - """Normalize the class name to remove ambiguity + This will ignore the filename and the linenumber where the warning was + triggered. The message is returned to the warnings module. + """ - This function removes the white spaces in the name, and also - remove the pointer declaration "*" (it have no sense in python) """ + return str(msg) + '\n' - name = name.replace(" ","") - name = name.replace("*","") +# Redefine the format of the warnings +warnings.formatwarning = itkFormatWarning - return name +def registerNoTpl(name, cl): + """Register a class without template -class itkTemplate(object): - """This class manage access to avaible template arguments of C++ class - - There is 2 ways to access types: - - with a dict interface. The user can manipulate template parameters nearly - as it do in c++, excepted that the available parameters sets are choosed at - build time. It is also possible, with the dict interface, to explore the - available parameters sets. - - with object attributes. The user can easily find the available parameters - sets by pressing tab in interperter like ipython - """ - __templates__ = {} - __class_to_template__ = {} - __named_templates__ = {} - __doxygen_root__ = itkConfig.doxygen_root - - def __new__(cls, name): - # Singleton pattern: we only make a single instance of any Template of a - # given name. If we have already made the instance, just return it as-is. - if not cls.__named_templates__.has_key(name): - new_instance = object.__new__(cls) - new_instance.__name__ = name - new_instance.__template__ = {} - cls.__named_templates__[name] = new_instance - return cls.__named_templates__[name] - - def __add__(self, paramSetString, cl): - """add a new argument set and the resulting class to the template - - paramSetString is the c++ string which define the parameters set - cl is the class which correspond to the couple template-argument set + It can seem not useful to register classes without template (and it wasn't + useful until the SmartPointer template was generated), but those classes + can be used as template argument of classes with template. """ - # recreate the full name and normalize it to avoid ambiguity - normalizedFullName = normalizeName(self.__name__+"<"+paramSetString+">") - - # the full class should not be already registered. If it is, there is a problem - # somewhere so warn the user so he can fix the problem - if itkTemplate.__templates__.has_key( normalizedFullName ) : - print >>sys.stderr,"Warning: template %s\n already defined as %s\n is redefined as %s" % (normalizedFullName, self.__templates__[normalizedFullName], cl) - # register the class - itkTemplate.__templates__[normalizedFullName] = cl - - # __find_param__ will parse the paramSetString and produce a list of the same - # parameters transformed in corresponding python classes. - # we transform this list in tuple to make it usable as key of the dict - param = tuple( self.__find_param__( paramSetString ) ) - - # once again, warn the user if the tuple of parameter is already defined - # so he can fix the problem - if self.__template__.has_key( param ) : - print >>sys.stderr,"Warning: template already defined '%s'" % normalizedFullName - # and register the parameter tuple - self.__template__[param] = cl - - # add in __class_to_template__ dictionary - itkTemplate.__class_to_template__[cl] = (self, param) - - # now populate the template - # 2 cases: - # - the template is a SmartPointer. In that case, the attribute name will be the - # full real name of the class without the itk prefix and _Pointer suffix - # - the template is not a SmartPointer. In that case, we keep only the end of the - # real class name which is a short string discribing the template arguments - # (for example IUC2) - if cl.__name__.startswith("itk"): - if cl.__name__.endswith("_Pointer") : - # it's a SmartPointer - attributeName = cl.__name__[len("itk"):-len("_Pointer")] - else : - # it's not a SmartPointer - # we need to now the size of the name to keep only the suffix - # short name does not contain :: and nested namespace - # itk::Numerics::Sample -> itkSample - import re - shortNameSize = len(re.sub(r':.*:', '', self.__name__)) - attributeName = cl.__name__[shortNameSize:] - elif cl.__name__.startswith("vcl_complex"): - # C++ name is likely to be std::complex here, instead of the expected vcl_complex - attributeName = cl.__name__[len("vcl_complex"):] - else: - import re - shortNameSize = len(re.sub(r'.*::', '', self.__name__)) - attributeName = cl.__name__[shortNameSize:] + itkTemplate.__templates__[normalizeName(name)] = cl + +def normalizeName(name): + """Normalize the class name to remove ambiguity - if attributeName.isdigit() : - # the attribute name can't be a number - # add a single undescore before it to build a valid name - attributeName = "_" + attributeName + This function removes the white spaces in the name, and also + remove the pointer declaration "*" (it have no sense in python) """ - # add the attribute to this object - self.__dict__[attributeName] = cl + name = name.replace(" ", "") + name = name.replace("*", "") + return name - def __find_param__(self, paramSetString): - """find the parameters of the template - paramSetString is the c++ string which define the parameters set +class itkTemplate(object): - __find_param__ returns a list of itk classes, itkCType, and/or numbers - which correspond to the parameters described in paramSetString. - The parameters MUST have been registered before calling this method, - or __find_param__ will return a string and not the wanted object, and - will display a warning. Registration order is important. + """This class manage access to avaible template arguments of C++ class - This method is not static only to be able to display the template name - in the warning - """ - # split the string in a list of parameters - paramStrings = [] - inner = 0 - part = paramSetString.split(",") - for elt in part : - if inner == 0 : - paramStrings.append( elt ) - else: - paramStrings[-1] += "," + elt - inner += elt.count("<") - elt.count(">") - - # convert all string parameters into classes (if possible) - parameters = [] - for param in paramStrings: - # the parameter need to be normalized several time below - # do it once here - param = param.strip() - paramNorm = normalizeName(param) - - if itkTemplate.__templates__.has_key( paramNorm ) : - # the parameter is registered. - # just get the really class form the dictionary - param = itkTemplate.__templates__[paramNorm] - - elif itkCType.GetCType( param ) : - # the parameter is a c type - # just get the itkCtype instance - param = itkCType.GetCType( param ) - - elif paramNorm.isdigit() : - # the parameter is a number - # convert the string to a number ! - param = int(param) - - elif paramNorm == "true": - param = True - elif paramNorm == "false": - param = False - - else : - # unable to convert the parameter - # use it without changes, but display a warning message, to incite - # developer to fix the problem - print >>sys.stderr,"Warning: Unknown parameter '%s' in template '%s'" % (param, self.__name__) - - parameters.append( param ) - - return parameters - - - def __getitem__(self, parameters): - """return the class which correspond to the given template parameters - - parameters can be: - - a single parameter (Ex: itk.Index[2]) - - a list of element (Ex: itk.Image[itk.UC, 2]) + There is 2 ways to access types: + - with a dict interface. The user can manipulate template parameters nearly + as it do in c++, excepted that the available parameters sets are choosed at + build time. It is also possible, with the dict interface, to explore the + available parameters sets. + - with object attributes. The user can easily find the available parameters + sets by pressing tab in interperter like ipython """ + __templates__ = {} + __class_to_template__ = {} + __named_templates__ = {} + __doxygen_root__ = itkConfig.doxygen_root + + def __new__(cls, name): + # Singleton pattern: we only make a single instance of any Template of + # a given name. If we have already made the instance, just return it + # as-is. + if name not in cls.__named_templates__: + new_instance = object.__new__(cls) + new_instance.__name__ = name + new_instance.__template__ = {} + cls.__named_templates__[name] = new_instance + return cls.__named_templates__[name] + + def __add__(self, paramSetString, cl): + """add a new argument set and the resulting class to the template + + paramSetString is the c++ string which define the parameters set + cl is the class which correspond to the couple template-argument set + """ + # recreate the full name and normalize it to avoid ambiguity + normFullName = normalizeName( + self.__name__ + "<" + paramSetString + ">") + + # the full class should not be already registered. If it is, there is a + # problem somewhere so warn the user so he can fix the problem + if normFullName in itkTemplate.__templates__: + message = ( + "Template %s\n already defined as %s\n is redefined " + "as %s") % (normFullName, self.__templates__[normFullName], cl) + warnings.warn(message) + # register the class + itkTemplate.__templates__[normFullName] = cl + + # __find_param__ will parse the paramSetString and produce a list of + # the same parameters transformed in corresponding python classes. + # we transform this list in tuple to make it usable as key of the dict + param = tuple(self.__find_param__(paramSetString)) + + # once again, warn the user if the tuple of parameter is already + # defined so he can fix the problem + if param in self.__template__: + message = "Warning: template already defined '%s'" % normFullName + warnings.warn(message) + # and register the parameter tuple + self.__template__[param] = cl + + # add in __class_to_template__ dictionary + itkTemplate.__class_to_template__[cl] = (self, param) + + # now populate the template + # 2 cases: + # - the template is a SmartPointer. In that case, the attribute name + # will be the full real name of the class without the itk prefix and + # _Pointer suffix + # - the template is not a SmartPointer. In that case, we keep only the + # end of the real class name which is a short string discribing the + # template arguments (for example IUC2) + if cl.__name__.startswith("itk"): + if cl.__name__.endswith("_Pointer"): + # it's a SmartPointer + attributeName = cl.__name__[len("itk"):-len("_Pointer")] + else: + # it's not a SmartPointer + # we need to now the size of the name to keep only the suffix + # short name does not contain :: and nested namespace + # itk::Numerics::Sample -> itkSample + import re + shortNameSize = len(re.sub(r':.*:', '', self.__name__)) + attributeName = cl.__name__[shortNameSize:] + elif cl.__name__.startswith("vcl_complex"): + # C++ name is likely to be std::complex here, instead of the + # expected vcl_complex + attributeName = cl.__name__[len("vcl_complex"):] + else: + import re + shortNameSize = len(re.sub(r'.*::', '', self.__name__)) + attributeName = cl.__name__[shortNameSize:] + + if attributeName.isdigit(): + # the attribute name can't be a number + # add a single undescore before it to build a valid name + attributeName = "_" + attributeName + + # add the attribute to this object + self.__dict__[attributeName] = cl + + def __find_param__(self, paramSetString): + """find the parameters of the template + + paramSetString is the c++ string which define the parameters set + + __find_param__ returns a list of itk classes, itkCType, and/or numbers + which correspond to the parameters described in paramSetString. + The parameters MUST have been registered before calling this method, + or __find_param__ will return a string and not the wanted object, and + will display a warning. Registration order is important. + + This method is not static only to be able to display the template name + in the warning + """ + # split the string in a list of parameters + paramStrings = [] + inner = 0 + part = paramSetString.split(",") + for elt in part: + if inner == 0: + paramStrings.append(elt) + else: + paramStrings[-1] += "," + elt + inner += elt.count("<") - elt.count(">") + + # convert all string parameters into classes (if possible) + parameters = [] + for param in paramStrings: + # the parameter need to be normalized several time below + # do it once here + param = param.strip() + paramNorm = normalizeName(param) + + if paramNorm in itkTemplate.__templates__: + # the parameter is registered. + # just get the really class form the dictionary + param = itkTemplate.__templates__[paramNorm] + + elif itkCType.GetCType(param): + # the parameter is a c type + # just get the itkCtype instance + param = itkCType.GetCType(param) + + elif paramNorm.isdigit(): + # the parameter is a number + # convert the string to a number ! + param = int(param) + + elif paramNorm == "true": + param = True + elif paramNorm == "false": + param = False + + else: + # unable to convert the parameter + # use it without changes, but display a warning message, to + # incite developer to fix the problem + message = ( + "Warning: Unknown parameter '%s' in " + "template '%s'" % (param, self.__name__)) + warnings.warn(message) + + parameters.append(param) + + return parameters + + def __getitem__(self, parameters): + """return the class which correspond to the given template parameters + + parameters can be: + - a single parameter (Ex: itk.Index[2]) + - a list of element (Ex: itk.Image[itk.UC, 2]) + """ + + isin = isinstance(parameters, types.TupleType) + if not isin and not isinstance(parameters, types.ListType): + # parameters is a single element. + # include it in a list to manage the 2 cases in the same way + parameters = [parameters] + + cleanParameters = [] + for param in parameters: + # In the case of itk class instance, get the class + name = param.__class__.__name__ + isclass = inspect.isclass(param) + if not isclass and name[:3] == 'itk' and name != "itkCType": + param = param.__class__ + + # append the parameter to the list. If it's not a supported type, + # it is not in the dictionary and we will raise an exception below + cleanParameters.append(param) + + try: + return(self.__template__[tuple(cleanParameters)]) + except: + raise KeyError( + 'itkTemplate : No template %s for the %s class' % + (str(parameters), self.__name__)) + + def __repr__(self): + return '<itkTemplate %s>' % self.__name__ + + def __getattribute__(self, attr): + """Support for reading doxygen man pages to produce __doc__ strings""" + root = itkTemplate.__doxygen_root__ + indoc = (attr == '__doc__') + if indoc and root != "" and self.__name__.startswith('itk'): + try: + import commands + doxyname = self.__name__.replace("::", "_") + man_path = "%s/man3/%s.3" % (root, doxyname) + bzman_path = "%s/man3/%s.3.bz2" % (root, doxyname) + if os.path.exists(bzman_path): + return ( + commands.getoutput( + "bunzip2 --stdout '" + bzman_path + + "' | groff -mandoc -Tascii -c")) + elif os.path.exists(man_path): + # Use groff here instead of man because man dies when it is + # passed paths with spaces (!) groff does not. + return ( + commands.getoutput( + "groff -mandoc -Tascii -c '" + + man_path + "'")) + else: + return ( + "Cannot find man page for %s: %s" + % (self.__name__, man_path + "[.bz2]")) + except Exception as e: + return ( + "Cannot display man page for %s due to exception: %s." + % (self.__name__, e)) + else: + return object.__getattribute__(self, attr) + + def New(self, *args, **kargs): + """TODO: some doc! Don't call it __call__ as it break the __doc__ + attribute feature in ipython""" + import itk + keys = self.keys() + if len(args) != 0: + # try to find a type suitable for the input provided + input_types = [output(f).__class__ for f in args] + keys = [k for k in self.keys() if k[0] == input_types[0]] + cur = itk.auto_pipeline.current + if cur is not None and len(cur) != 0: + # try to find a type suitable for the input provided + input_type = output(cur).__class__ + keys = [k for k in self.keys() if k[0] == input_type] + if len(keys) == 0: + raise RuntimeError("No suitable template parameter can be found.") + return self[keys[0]].New(*args, **kargs) + + def keys(self): + return self.__template__.keys() + + # everything after this comment is for dict interface + # and is a copy/paste from DictMixin + # only methods to edit dictionary are not there + def __iter__(self): + for k in self.keys(): + yield k + + def has_key(self, key): + try: + value = self[key] + except KeyError: + return False + return True + + def __contains__(self, key): + return key in self + + # third level takes advantage of second level definitions + def iteritems(self): + for k in self: + yield (k, self[k]) + + def iterkeys(self): + return self.__iter__() + + # fourth level uses definitions from lower levels + def itervalues(self): + for _, v in self.iteritems(): + yield v + + def values(self): + return [v for _, v in self.iteritems()] + + def items(self): + return list(self.iteritems()) + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def __len__(self): + return len(self.keys()) - if type(parameters) != types.TupleType and type(parameters) != types.ListType : - # parameters is a single element. - # include it in a list to manage the 2 cases in the same way - parameters = [parameters] - cleanParameters = [] - for param in parameters: - # In the case of itk class instance, get the class - if not inspect.isclass( param ) and param.__class__.__name__[:3] == 'itk' and param.__class__.__name__!= "itkCType" : - param = param.__class__ +# create a new New function which accepts parameters +def New(self, *args, **kargs): + import sys + import itk - # append the parameter to the list. If it's not a supported type, it is - # not in the dictionary and we will raise an exception below - cleanParameters.append( param ) + itk.set_inputs(self, args, kargs) - try: - return(self.__template__[tuple(cleanParameters)]) - except: - raise KeyError, 'itkTemplate : No template %s for the %s class' % (str(parameters), self.__name__) - - - def __repr__(self): - return '<itkTemplate %s>' % self.__name__ - - # support for reading doxygen man pages to produce __doc__ strings - def __getattribute__(self, attr): - if attr == '__doc__' and itkTemplate.__doxygen_root__ != "" and self.__name__.startswith('itk'): - try: - import commands - doxyname = self.__name__.replace("::", "_") - man_path = "%s/man3/%s.3" %(itkTemplate.__doxygen_root__, doxyname) - bzman_path = "%s/man3/%s.3.bz2" %(itkTemplate.__doxygen_root__, doxyname) - if os.path.exists(bzman_path): - return commands.getoutput("bunzip2 --stdout '"+bzman_path+"' | groff -mandoc -Tascii -c") - elif os.path.exists(man_path): - # Use groff here instead of man because man dies when it is passed paths with spaces (!) - # groff does not. - return commands.getoutput("groff -mandoc -Tascii -c '" + man_path +"'") + # now, try to add observer to display progress + if "auto_progress" in kargs.keys(): + if kargs["auto_progress"] in [True, 1]: + callback = itk.terminal_progress_callback + elif kargs["auto_progress"] == 2: + callback = itk.simple_progress_callback else: - return "Cannot find man page for %s: %s" %(self.__name__, man_path+"[.bz2]") - except Exception, e: - return "Cannot display man page for %s due to exception: %s." %(self.__name__, e) + callback = None + elif itkConfig.ProgressCallback: + callback = itkConfig.ProgressCallback else: - return object.__getattribute__(self, attr) + callback = None - def New(self, *args, **kargs): - """TODO: some doc! Don't call it __call__ as it break the __doc__ attribute feature in - ipython""" - import itk - keys = self.keys() - if len(args) != 0: - # try to find a type suitable for the input provided - input_types = [output(f).__class__ for f in args] - keys = [k for k in self.keys() if k[0] == input_types[0]] - if itk.auto_pipeline.current != None and len(itk.auto_pipeline.current) != 0: - # try to find a type suitable for the input provided - input_type = output(itk.auto_pipeline.current).__class__ - keys = [k for k in self.keys() if k[0] == input_type] - if len(keys) == 0: - raise RuntimeError("No suitable template parameter can be found.") - return self[keys[0]].New(*args, **kargs) - - def keys(self): - return self.__template__.keys() - - # everything after this comment is for dict interface - # and is a copy/paste from DictMixin - # only methods to edit dictionary are not there - def __iter__(self): - for k in self.keys(): - yield k - - def has_key(self,key): - try: - value=self[key] - except KeyError: - return False - return True + if callback: + try: + name = self.__class__.__name__ - def __contains__(self,key): - return self.has_key(key) + def progress(): + # self and callback are kept referenced with a closure + callback(name, self.GetProgress()) - # third level takes advantage of second level definitions - def iteritems(self): - for k in self: - yield (k,self[k]) + self.AddObserver(itk.ProgressEvent(), progress) + except: + # it seems that something goes wrong... + # as this feature is designed for prototyping, it's not really a + # problem if an object doesn't have progress reporter, so adding + # reporter can silently fail + pass - def iterkeys(self): - return self.__iter__() + if itkConfig.NotInPlace and "SetInPlace" in dir(self): + self.SetInPlace(False) - # fourth level uses definitions from lower levels - def itervalues(self): - for _,v in self.iteritems(): - yield v + if itk.auto_pipeline.current is not None: + itk.auto_pipeline.current.connect(self) - def values(self): - return [v for _,v in self.iteritems()] + return self - def items(self): - return list(self.iteritems()) - def get(self,key,default=None): +def output(input): try: - return self[key] - except KeyError: - return default - - def __len__(self): - return len(self.keys()) - - - -# create a new New function which accepts parameters -def New(self, *args, **kargs) : - import sys, itk - - itk.set_inputs( self, args, kargs ) - - # now, try to add observer to display progress - if "auto_progress" in kargs.keys() : - if kargs["auto_progress"] in [True, 1] : - callback = itk.terminal_progress_callback - elif kargs["auto_progress"] == 2 : - callback = itk.simple_progress_callback - else : - callback = None - elif itkConfig.ProgressCallback : - callback = itkConfig.ProgressCallback - else : - callback = None - - if callback : - try : - name = self.__class__.__name__ - def progress() : - # self and callback are kept referenced with a closure - callback(name, self.GetProgress()) - - self.AddObserver(itk.ProgressEvent(), progress) - except : - # it seems that something goes wrong... - # as this feature is designed for prototyping, it's not really a problem - # if an object don't have progress reporter, so adding reporter can silently fail - pass - - if itkConfig.NotInPlace and "SetInPlace" in dir(self) : - self.SetInPlace( False ) - - if itk.auto_pipeline.current != None: - itk.auto_pipeline.current.connect(self) - - return self - - -def output(input) : - try : - img = input.GetOutput() - except AttributeError : - img = input - return img - -def image(input) : - import sys - print >> sys.stderr, "WrapITK warning: itk.image() is deprecated. Use itk.output() instead." - return output(input) + img = input.GetOutput() + except AttributeError: + img = input + return img + + +def image(input): + import sys + print( + ("WrapITK warning: itk.image() is deprecated. " + "Use itk.output() instead."), file=sys.stderr) + return output(input) diff --git a/Utilities/ITK/Wrapping/Generators/Python/itktesting.py b/Utilities/ITK/Wrapping/Generators/Python/itkTesting.py similarity index 57% rename from Utilities/ITK/Wrapping/Generators/Python/itktesting.py rename to Utilities/ITK/Wrapping/Generators/Python/itkTesting.py index c8dc2f72b7042df043c6676caa4a23edd973da1e..75ff5838651d7db34dc92074ed1729a17a45ce55 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/itktesting.py +++ b/Utilities/ITK/Wrapping/Generators/Python/itkTesting.py @@ -16,12 +16,12 @@ # #==========================================================================*/ -import itkbase +import itkBase import sys import os import stat -import itkdata +import itkData # Put the ITK_TEST_ROOT setting in the global namespace. This # package is only used for testing, so this is okay. @@ -30,32 +30,34 @@ ITK_TEST_ROOT = "" # Look for the -T command line option. if not ITK_TEST_ROOT: - for a in range(len(sys.argv)): - if sys.argv[a] == "-T" and a < len(sys.argv): - ITK_TEST_ROOT = sys.argv[a+1] - break + for a in range(len(sys.argv)): + if sys.argv[a] == "-T" and a < len(sys.argv): + ITK_TEST_ROOT = sys.argv[a + 1] + break # Check for the environment variable ::ITK_TEST_ROOT. -if not ITK_TEST_ROOT and os.environ.has_key('ITK_TEST_ROOT'): - ITK_TEST_ROOT = os.environ['ITK_TEST_ROOT'] +if not ITK_TEST_ROOT and 'ITK_TEST_ROOT' in os.environ: + ITK_TEST_ROOT = os.environ['ITK_TEST_ROOT'] # Use the default output directory. if not ITK_TEST_ROOT: - ITK_TEST_ROOT = itkbase.defaultTestRoot - if ITK_TEST_ROOT == "<NO_DEFAULT>": - sys.stderr.write("Set ITK_TEST_ROOT or use -T option to specify.\n") - sys.exit(1) + ITK_TEST_ROOT = itkBase.defaultTestRoot + if ITK_TEST_ROOT == "<NO_DEFAULT>": + sys.stderr.write("Set ITK_TEST_ROOT or use -T option to specify.\n") + sys.exit(1) # Setup testing directories. -ITK_TEST_BASELINE = "%s/Baseline" % itkdata.ITK_DATA_ROOT -ITK_TEST_INPUT = "%s/Input" % itkdata.ITK_DATA_ROOT -ITK_TEST_OUTPUT = "%s/Output" % ITK_TEST_ROOT +ITK_TEST_BASELINE = "%s/Baseline" % itkData.ITK_DATA_ROOT +ITK_TEST_INPUT = "%s/Input" % itkData.ITK_DATA_ROOT +ITK_TEST_OUTPUT = "%s/Output" % ITK_TEST_ROOT try: - if not os.path.exists(ITK_TEST_ROOT): - os.mkdir(ITK_TEST_OUTPUT) + if not os.path.exists(ITK_TEST_ROOT): + os.mkdir(ITK_TEST_OUTPUT) except: - sys.stderr.write("Bla: %s\n" % `sys.exc_info()[0]`) - sys.stderr.write("Unable to create testing output directory with name: %s\n" % ITK_TEST_OUTPUT) - sys.exit(1) + sys.stderr.write("Bla: %s\n" % repr(sys.exc_info()[0])) + sys.stderr.write( + "Unable to create testing output directory with name: %s\n" % + ITK_TEST_OUTPUT) + sys.exit(1) diff --git a/Utilities/ITK/Wrapping/Generators/Python/itkTypes.py b/Utilities/ITK/Wrapping/Generators/Python/itkTypes.py index a507f5c06de28d1e301dc00ed215210081606c10..1b08ab53d5ac8a9c24737ad2aad09d01c91d1efe 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/itkTypes.py +++ b/Utilities/ITK/Wrapping/Generators/Python/itkTypes.py @@ -16,41 +16,42 @@ # #==========================================================================*/ -class itkCType : - __cTypes__ = {} - def __init__(self,name,shortName): - self.name=name - self.short_name=shortName +class itkCType: + __cTypes__ = {} - itkCType.__cTypes__[self.name]=self + def __init__(self, name, shortName): + self.name = name + self.short_name = shortName - def __del__(self): - try: - del itkCType.__cTypes__[self.name] - except: - pass + itkCType.__cTypes__[self.name] = self - def __repr__(self): - return "<itkCType %s>" % self.name + def __del__(self): + try: + del itkCType.__cTypes__[self.name] + except: + pass - def GetCType(name): - try: - return(itkCType.__cTypes__[name]) - except KeyError: - return(None) - GetCType=staticmethod(GetCType) + def __repr__(self): + return "<itkCType %s>" % self.name + def GetCType(name): + try: + return(itkCType.__cTypes__[name]) + except KeyError: + return(None) + GetCType = staticmethod(GetCType) -F = itkCType("float", "F") -D = itkCType("double", "D") -LD = itkCType("long double", "LD") + +F = itkCType("float", "F") +D = itkCType("double", "D") +LD = itkCType("long double", "LD") UC = itkCType("unsigned char", "UC") -US = itkCType("unsigned short","US") -UI = itkCType("unsigned int", "UI") +US = itkCType("unsigned short", "US") +UI = itkCType("unsigned int", "UI") UL = itkCType("unsigned long", "UL") -SC = itkCType("signed char", "SC") -SS = itkCType("signed short", "SS") -SI = itkCType("signed int", "SI") -SL = itkCType("signed long", "SL") -B = itkCType("bool", "B") +SC = itkCType("signed char", "SC") +SS = itkCType("signed short", "SS") +SI = itkCType("signed int", "SI") +SL = itkCType("signed long", "SL") +B = itkCType("bool", "B") diff --git a/Utilities/ITK/Wrapping/Generators/Python/module_ext.i.in b/Utilities/ITK/Wrapping/Generators/Python/module_ext.i.in index f576d7f68bd3ad70ae7e198af49c20a291a2ae93..53f05530135a0a4a23de940ad56054204fcd3fc8 100644 --- a/Utilities/ITK/Wrapping/Generators/Python/module_ext.i.in +++ b/Utilities/ITK/Wrapping/Generators/Python/module_ext.i.in @@ -1,8 +1,7 @@ %{ -// workaround for undefined ptrdiff_t with swig 1.3.40 -#include <cstddef> - -// workaround for undefined SWIGPY_SLICE_ARG with swig 2.0.3 and 2.0.4 +// Workaround for undefined SWIGPY_SLICE_ARG with swig 2.0.3 and 2.0.4 +// If removed, fails also with swig 3.0, so this has not been fixed ? +// Needs to be investigated #include <iostream> #if PY_VERSION_HEX >= 0x03020000 diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/CMakeLists.txt b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/CMakeLists.txt deleted file mode 100644 index 868975852b597b513aba594be4c4c655cc00c0ca..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ - -# configure the test driver -find_program(ITK_TEST_DRIVER itkTestDriver) diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/DicomSliceRead.py b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/DicomSliceRead.py deleted file mode 100644 index 678925649719c40efa0f1df193bf99af62db0eff..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/DicomSliceRead.py +++ /dev/null @@ -1,32 +0,0 @@ -# -# Example on the use of DicomImageIO for reading a single DICOM slice, rescale -# the intensities and save it in a different file format. -# - -from InsightToolkit import * - -from sys import argv - -# -# Reads an image in 16bits/pixel -# and save it as 8bits/pixel -# -reader = itkImageFileReaderUS2_New() -writer = itkImageFileWriterUC2_New() - -dicomIO = itkDicomImageIO_New() - -reader.SetImageIO( dicomIO.GetPointer() ) - -filter = itkRescaleIntensityImageFilterUS2UC2_New() - -filter.SetOutputMinimum( 0 ) -filter.SetOutputMaximum(255) - -filter.SetInput( reader.GetOutput() ) -writer.SetInput( filter.GetOutput() ) - -reader.SetFileName( argv[1] ) -writer.SetFileName( argv[2] ) - -writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration3.py b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration3.py deleted file mode 100644 index e7ced3d5117cdc17f045bdc12ec169658c6f68d0..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration3.py +++ /dev/null @@ -1,139 +0,0 @@ -#========================================================================= -# -# Program: Insight Segmentation & Registration Toolkit -# Module: $RCSfile: ImageRegistration3.py,v $ -# Language: C++ -# Date: $Date: 2006/09/06 20:58:42 $ -# Version: $Revision: 1.1 $ -# -# Copyright (c) Insight Software Consortium. All rights reserved. -# See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. -# -# This software is distributed WITHOUT ANY WARRANTY; without even -# the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -# PURPOSE. See the above copyright notices for more information. -# -#========================================================================= - -from InsightToolkit import * - -from sys import argv - - - -# -# Read the fixed and moving images using filenames -# from the command line arguments -# -fixedImageReader = itkImageFileReaderF2_New() -movingImageReader = itkImageFileReaderF2_New() - -fixedImageReader.SetFileName( argv[1] ) -movingImageReader.SetFileName( argv[2] ) - -fixedImageReader.Update() -movingImageReader.Update() - -fixedImage = fixedImageReader.GetOutput() -movingImage = movingImageReader.GetOutput() - - - - -# -# Instantiate the classes for the registration framework -# -registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMeanSquaresImageToImageMetricF2F2_New() -transform = itkTranslationTransform2_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() -interpolator = itkLinearInterpolateImageFunctionF2D_New() - - -registration.SetOptimizer( optimizer.GetPointer() ) -registration.SetTransform( transform.GetPointer() ) -registration.SetInterpolator( interpolator.GetPointer() ) -registration.SetMetric( imageMetric.GetPointer() ) -registration.SetFixedImage( fixedImage ) -registration.SetMovingImage( movingImage ) - -registration.SetFixedImageRegion( fixedImage.GetBufferedRegion() ) - -transform.SetIdentity() -initialParameters = transform.GetParameters() - -registration.SetInitialTransformParameters( initialParameters ) - -# -# Iteration Observer -# -def iterationUpdate(): - currentParameter = transform.GetParameters() - print "M: %f P: %f %f " % ( optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1) ) - -iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable( iterationUpdate ) -optimizer.AddObserver( itkIterationEvent(), iterationCommand.GetPointer() ) - - - -# -# Define optimizer parameters -# -optimizer.SetMaximumStepLength( 4.00 ) -optimizer.SetMinimumStepLength( 0.01 ) -optimizer.SetNumberOfIterations( 200 ) - - -print "Starting registration" - -# -# Start the registration process -# - -registration.Update() - - -# -# Get the final parameters of the transformation -# -finalParameters = registration.GetLastTransformParameters() - -print "Final Registration Parameters " -print "Translation X = %f" % (finalParameters.GetElement(0),) -print "Translation Y = %f" % (finalParameters.GetElement(1),) - - - - -# -# Now, we use the final transform for resampling the -# moving image. -# -resampler = itkResampleImageFilterF2F2_New() -resampler.SetTransform( transform.GetPointer() ) -resampler.SetInput( movingImage ) - -region = fixedImage.GetLargestPossibleRegion() - -resampler.SetSize( region.GetSize() ) - -resampler.SetOutputSpacing( fixedImage.GetSpacing() ) -resampler.SetOutputOrigin( fixedImage.GetOrigin() ) -resampler.SetDefaultPixelValue( 100 ) - -outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetOutputMinimum( 0 ) -outputCast.SetOutputMaximum( 65535 ) -outputCast.SetInput(resampler.GetOutput()) - -# -# Write the resampled image -# -writer = itkImageFileWriterUS2_New() - -writer.SetFileName( argv[3] ) -writer.SetInput( outputCast.GetOutput() ) -writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration4.py b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration4.py deleted file mode 100644 index e552b24f0168be8c4a683b36a70b78093ddbee4c..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration4.py +++ /dev/null @@ -1,142 +0,0 @@ -#========================================================================= -# -# Program: Insight Segmentation & Registration Toolkit -# Module: $RCSfile: ImageRegistration4.py,v $ -# Language: C++ -# Date: $Date: 2006/09/06 20:58:42 $ -# Version: $Revision: 1.1 $ -# -# Copyright (c) Insight Software Consortium. All rights reserved. -# See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. -# -# This software is distributed WITHOUT ANY WARRANTY; without even -# the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR -# PURPOSE. See the above copyright notices for more information. -# -#========================================================================= - -from InsightToolkit import * - -from sys import argv - - - -# -# Read the fixed and moving images using filenames -# from the command line arguments -# -fixedImageReader = itkImageFileReaderF2_New() -movingImageReader = itkImageFileReaderF2_New() - -fixedImageReader.SetFileName( argv[1] ) -movingImageReader.SetFileName( argv[2] ) - -fixedImageReader.Update() -movingImageReader.Update() - -fixedImage = fixedImageReader.GetOutput() -movingImage = movingImageReader.GetOutput() - - - - -# -# Instantiate the classes for the registration framework -# -registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMattesMutualInformationImageToImageMetricF2F2_New() -transform = itkTranslationTransform2_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() -interpolator = itkLinearInterpolateImageFunctionF2D_New() - - -imageMetric.SetNumberOfHistogramBins( 20 ); -imageMetric.SetNumberOfSpatialSamples( 10000 ); - -registration.SetOptimizer( optimizer.GetPointer() ) -registration.SetTransform( transform.GetPointer() ) -registration.SetInterpolator( interpolator.GetPointer() ) -registration.SetMetric( imageMetric.GetPointer() ) -registration.SetFixedImage( fixedImage ) -registration.SetMovingImage( movingImage ) - -registration.SetFixedImageRegion( fixedImage.GetBufferedRegion() ) - -transform.SetIdentity() -initialParameters = transform.GetParameters() - -registration.SetInitialTransformParameters( initialParameters ) - -# -# Iteration Observer -# -def iterationUpdate(): - currentParameter = transform.GetParameters() - print "M: %f P: %f %f " % ( optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1) ) - -iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable( iterationUpdate ) -optimizer.AddObserver( itkIterationEvent(), iterationCommand.GetPointer() ) - - - -# -# Define optimizer parameters -# -optimizer.SetMaximumStepLength( 4.00 ) -optimizer.SetMinimumStepLength( 0.01 ) -optimizer.SetNumberOfIterations( 200 ) - - -print "Starting registration" - -# -# Start the registration process -# - -registration.Update() - - -# -# Get the final parameters of the transformation -# -finalParameters = registration.GetLastTransformParameters() - -print "Final Registration Parameters " -print "Translation X = %f" % (finalParameters.GetElement(0),) -print "Translation Y = %f" % (finalParameters.GetElement(1),) - - - - -# -# Now, we use the final transform for resampling the -# moving image. -# -resampler = itkResampleImageFilterF2F2_New() -resampler.SetTransform( transform.GetPointer() ) -resampler.SetInput( movingImage ) - -region = fixedImage.GetLargestPossibleRegion() - -resampler.SetSize( region.GetSize() ) - -resampler.SetOutputSpacing( fixedImage.GetSpacing() ) -resampler.SetOutputOrigin( fixedImage.GetOrigin() ) -resampler.SetDefaultPixelValue( 100 ) - -outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetOutputMinimum( 0 ) -outputCast.SetOutputMaximum( 65535 ) -outputCast.SetInput(resampler.GetOutput()) - -# -# Write the resampled image -# -writer = itkImageFileWriterUS2_New() - -writer.SetFileName( argv[3] ) -writer.SetInput( outputCast.GetOutput() ) -writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration5.py b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration5.py deleted file mode 100644 index 7ba18862ede5d65111d08cf97e1456fdc7656a87..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageRegistration5.py +++ /dev/null @@ -1,161 +0,0 @@ -# - -from InsightToolkit import * - -from sys import argv - -# -# Read the fixed and moving images using filenames -# from the command line arguments -# -fixedImageReader = itkImageFileReaderF2_New() -movingImageReader = itkImageFileReaderF2_New() - -fixedImageReader.SetFileName( argv[1] ) -movingImageReader.SetFileName( argv[2] ) - -fixedImageReader.Update() -movingImageReader.Update() - -fixedImage = fixedImageReader.GetOutput() -movingImage = movingImageReader.GetOutput() - -# -# Instantiate the classes for the registration framework -# -registration = itkImageRegistrationMethodF2F2_New() -imageMetric = itkMeanSquaresImageToImageMetricF2F2_New() -transform = itkCenteredRigid2DTransform_New() -optimizer = itkRegularStepGradientDescentOptimizer_New() -interpolator = itkLinearInterpolateImageFunctionF2D_New() - -registration.SetOptimizer( optimizer.GetPointer() ) -registration.SetTransform( transform.GetPointer() ) -registration.SetInterpolator( interpolator.GetPointer() ) -registration.SetMetric( imageMetric.GetPointer() ) -registration.SetFixedImage( fixedImage ) -registration.SetMovingImage( movingImage ) -registration.SetFixedImageRegion( fixedImage.GetBufferedRegion() ) - - -# -# Initial transform parameters -# -transform.SetAngle( 0.0 ); - -# center of the fixed image -fixedSpacing = fixedImage.GetSpacing() -fixedOrigin = fixedImage.GetOrigin() -fixedSize = fixedImage.GetLargestPossibleRegion().GetSize() - -centerFixed = ( fixedOrigin.GetElement(0) + fixedSpacing.GetElement(0) * fixedSize.GetElement(0) / 2.0, - fixedOrigin.GetElement(1) + fixedSpacing.GetElement(1) * fixedSize.GetElement(1) / 2.0 ) - -# center of the moving image -movingSpacing = movingImage.GetSpacing() -movingOrigin = movingImage.GetOrigin() -movingSize = movingImage.GetLargestPossibleRegion().GetSize() - -centerMoving = ( movingOrigin.GetElement(0) + movingSpacing.GetElement(0) * movingSize.GetElement(0) / 2.0, - movingOrigin.GetElement(1) + movingSpacing.GetElement(1) * movingSize.GetElement(1) / 2.0 ) - -# transform center -center = transform.GetCenter() -center.SetElement( 0, centerFixed[0] ) -center.SetElement( 1, centerFixed[1] ) - -# transform translation -translation = transform.GetTranslation() -translation.SetElement( 0, centerMoving[0] - centerFixed[0] ) -translation.SetElement( 1, centerMoving[1] - centerFixed[1] ) - -initialParameters = transform.GetParameters() - -print "Initial Parameters: " -print "Angle: %f" % (initialParameters.GetElement(0), ) -print "Center: %f, %f" % ( initialParameters.GetElement(1), initialParameters.GetElement(2) ) -print "Translation: %f, %f" % (initialParameters.GetElement(3), initialParameters.GetElement(4)) - -registration.SetInitialTransformParameters( initialParameters ) - -# -# Define optimizer parameters -# - -# optimizer scale -translationScale = 1.0 / 1000.0 - -optimizerScales = itkArrayD( transform.GetNumberOfParameters() ) -optimizerScales.SetElement(0, 1.0) -optimizerScales.SetElement(1, translationScale) -optimizerScales.SetElement(2, translationScale) -optimizerScales.SetElement(3, translationScale) -optimizerScales.SetElement(4, translationScale) - -optimizer.SetScales( optimizerScales ) -optimizer.SetMaximumStepLength( 0.1 ) -optimizer.SetMinimumStepLength( 0.001 ) -optimizer.SetNumberOfIterations( 200 ) - -# -# Iteration Observer -# -def iterationUpdate(): - currentParameter = transform.GetParameters() - print "M: %f P: %f %f %f %f %f " % ( optimizer.GetValue(), - currentParameter.GetElement(0), - currentParameter.GetElement(1), - currentParameter.GetElement(2), - currentParameter.GetElement(3), - currentParameter.GetElement(4) ) - -iterationCommand = itkPyCommand_New() -iterationCommand.SetCommandCallable( iterationUpdate ) -optimizer.AddObserver( itkIterationEvent(), iterationCommand.GetPointer() ) - -print "Starting registration" - -# -# Start the registration process -# - -registration.Update() - -# -# Get the final parameters of the transformation -# -finalParameters = registration.GetLastTransformParameters() - -print "Final Registration Parameters " -print "Angle in radians = %f" % finalParameters.GetElement(0) -print "Rotation Center X = %f" % finalParameters.GetElement(1) -print "Rotation Center Y = %f" % finalParameters.GetElement(2) -print "Translation in X = %f" % finalParameters.GetElement(3) -print "Translation in Y = %f" % finalParameters.GetElement(4) - -# Now, we use the final transform for resampling the moving image. -resampler = itkResampleImageFilterF2F2_New() - -resampler.SetTransform( transform.GetPointer() ) -resampler.SetInput( movingImage ) - -region = fixedImage.GetLargestPossibleRegion() - -resampler.SetSize( region.GetSize() ) -resampler.SetOutputSpacing( fixedImage.GetSpacing() ) -resampler.SetOutputOrigin( fixedImage.GetOrigin() ) -resampler.SetDefaultPixelValue( 100 ) - -# -# Cast for output -# -outputCast = itkRescaleIntensityImageFilterF2US2_New() -outputCast.SetInput( resampler.GetOutput() ) -outputCast.SetOutputMinimum( 0 ) -outputCast.SetOutputMaximum( 65535 ) - -writer = itkImageFileWriterUS2_New() - -writer.SetFileName( argv[3] ) -writer.SetInput( outputCast.GetOutput() ) -writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageToArray.py b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageToArray.py deleted file mode 100644 index 975c146f8bf345c66e6bfb3dc52817eb26df720c..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/ImageToArray.py +++ /dev/null @@ -1,25 +0,0 @@ -from InsightToolkit import * -from numarray import * -from sys import argv - -reader = itkImageFileReaderUC2_New() - -connector = itkPyBufferUC2_New() - -reader.SetFileName( argv[1] ) - -reader.Update() - -print "ready to convert image into array" - -buffer = connector.GetArrayFromImage( reader.GetOutput() ) - -writer = itkImageFileWriterUC2_New() - -writer.SetFileName( argv[2] ) - -print "ready to convert array into image" - -writer.SetInput( connector.GetImageFromArray( buffer ) ) - -writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/VoronoiSegmentation.py b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/VoronoiSegmentation.py deleted file mode 100644 index 202ebf7cc4e25bb4a07ecf5ce0a499e460d538b9..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/VoronoiSegmentation.py +++ /dev/null @@ -1,31 +0,0 @@ -# -# Example on the use of the VoronoiSegmentationImageFilter. -# - -from InsightToolkit import * - -from sys import argv - - -readerInput = itkImageFileReaderUC2_New() -readerPrior = itkImageFileReaderUC2_New() - -readerInput.SetFileName( argv[1] ) -readerPrior.SetFileName( argv[2] ) - -readerInput.Update() -readerPrior.Update() - -filter = itkVoronoiSegmentationImageFilterUC2UC2UC2_New() - -filter.SetInput( readerInput.GetOutput() ) -filter.TakeAPrior( readerPrior.GetOutput() ) - -filter.SetMeanPercentError( eval( argv[4] ) ) -filter.SetSTDPercentError( eval( argv[5] ) ) - -writer = itkImageFileWriterUC2_New() -writer.SetFileName( argv[3] ) -writer.SetInput( filter.GetOutput() ) - -writer.Update() diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/itkCurvatureFlowTestPython2.py b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/itkCurvatureFlowTestPython2.py deleted file mode 100644 index eaa167509bed2c4de9d71752b7f9a1f6c22a582c..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/notYetUsable/itkCurvatureFlowTestPython2.py +++ /dev/null @@ -1,93 +0,0 @@ -from InsightToolkit import * -import itktesting - -import sys -import os -import shutil - -basename = os.path.basename( sys.argv[0] ) -name = os.path.splitext( basename )[0] -dir = "Algorithms" - - -testInput = itktesting.ITK_TEST_INPUT -testOutput = itktesting.ITK_TEST_OUTPUT -baseLine = itktesting.ITK_TEST_BASELINE - - -reader = itkImageFileReaderF2_New() -reader.SetFileName( testInput+"/cthead1.png") - - -cf = itkCurvatureFlowImageFilterF2F2_New() -cf.SetInput( reader.GetOutput() ) -cf.SetTimeStep( 0.25 ) -cf.SetNumberOfIterations( 10 ) - - -cfss = itkShiftScaleImageFilterF2US2_New() -cfss.SetInput( cf.GetOutput() ) -cfss.SetShift( 0.7 ) -cfss.SetScale( 0.9 ) - - -valid = itkImageFileReaderUS2_New() -valid.SetFileName( baseLine+"/"+dir+"/"+name+".png") - - -diff = itkDifferenceImageFilterUS2_New() -diff.SetValidInput( valid.GetOutput() ) -diff.SetTestInput( cfss.GetOutput() ) -diff.SetToleranceRadius( 1 ) -diff.SetDifferenceThreshold( 0 ) - -diff.Update() - - -meanDiff = diff.GetMeanDifference() -totalDiff = diff.GetTotalDifference() - - -print "MeanDifference = ", meanDiff -print "TotalDifference = ", totalDiff - - -print "<DartMeasurement name=\"MeanDifference\" type=\"numeric/double\">",meanDiff,"</DartMeasurement>" -print "<DartMeasurement name=\"TotalDifference\" type=\"numeric/double\">",totalDiff,"</DartMeasurement>" - -if ( meanDiff > 0.1 ) : - convert = itkCastImageFilterUS2UC2_New() - rescale = itkRescaleIntensityImageFilterUS2UC2_New() - rescale.SetInput( diff.GetOutput() ) - rescale.SetOutputMinimum( 0 ) - rescale.SetOutputMaximum( 255 ) - - io = itkPNGImageIO_New() - io.SetUseCompression( 1 ) - io.SetCompressionLevel( 9 ) - - writer = itkImageFileWriterUC2_New() - writer.SetImageIO( io.GetPointer() ) - writer.SetInput( convert.GetOutput() ) - - writer.SetFileName( testOutput+"/"+name+".test.png" ) - convert.SetInput( cfss.GetOutput() ) - writer.Write() - - writer.SetFileName( testOutput+"/"+name+".diff.png" ) - writer.SetInput( rescale.GetOutput() ) - writer.Write() - - shutil.copyfile( baseLine+"/"+dir+"/"+name+".png", testOutput+"/"+name+".valid.png" ) - - print "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">"+testOutput+"/"+name+".test.png</DartMeasurementFile>" - print "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">"+testOutput+"/"+name+".diff.png</DartMeasurementFile>" - print "<DartMeasurementFile name=\"ValidImage\" type=\"image/png\">"+testOutput+"/"+name+".valid.png</DartMeasurementFile>" - print "<DartMeasurement name=\"DifferenceShift\" type=\"numeric/double\">",rescale.GetShift(),"</DartMeasurement>" - print "<DartMeasurement name=\"DifferenceScale\" type=\"numeric/double\">",rescale.GetScale(),"</DartMeasurement>" - -# return 1 - - - -#return 0 diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/pythonTestDriver.py.in b/Utilities/ITK/Wrapping/Generators/Ruby/Tests/pythonTestDriver.py.in deleted file mode 100644 index 408ece648655113218bda57bfab019f8cc743c6e..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/Ruby/Tests/pythonTestDriver.py.in +++ /dev/null @@ -1,76 +0,0 @@ -#!@PYTHON_EXECUTABLE@ - -# set environment variables - -import os, subprocess, sys -from optparse import OptionParser - -# the environment needed to find the lib depend on the system -# I'm really not sure that's needed on all the systems... -# TODO: can we replace os.name by os.uname()[0] for all systems ? -env_lib_path = {"posix": "LD_LIBRARY_PATH", "mac": "DYLD_LIBRARY_PATH", "nt": "PATH"}[os.name] -# the environment needed to find the lib depend on the system -if os.name == "posix": - if os.uname()[0] == "Darwin" : - env_lib_path = "DYLD_LIBRARY_PATH" - else : - env_lib_path = "LD_LIBRARY_PATH" -elif os.name == "nt": - env_lib_path = "PATH" -else: - raise "Please add the library path for your system." -lib_path_list = "@PYTHON_TEST_LIB_PATH@".split(';') -if os.environ.has_key(env_lib_path) : - os.environ[env_lib_path] = os.pathsep.join(lib_path_list + [os.environ[env_lib_path]]) -else: - os.environ[env_lib_path] = os.pathsep.join(lib_path_list) - -env_python_path = "PYTHONPATH" -python_path_list = "@PYTHON_TEST_PYTHON_PATH@".split(';') -if os.environ.has_key(env_python_path) : - os.environ[env_python_path] = os.pathsep.join(python_path_list + [os.environ[env_python_path]]) -else: - os.environ[env_python_path] = os.pathsep.join(python_path_list) - -env_wrapitk_python_path = "WRAPITK_PYTHON_PATH" -wrapitk_python_path_list = "@PYTHON_TEST_WRAPITK_PYTHON_PATH@".split(';') -if os.environ.has_key(env_wrapitk_python_path) : - os.environ[env_wrapitk_python_path] = os.pathsep.join(wrapitk_python_path_list + [os.environ[env_wrapitk_python_path]]) -else: - os.environ[env_wrapitk_python_path] = os.pathsep.join(wrapitk_python_path_list) - - - -# setup the option manager to be able to compare the resulting images in the same test - -optionParser = OptionParser(usage="usage: %prog [--compare image1 image2] test.py [arg1 [arg2 [...]]]") -optionParser.add_option("-c", "--compare", action="append", dest="compare", default=[], metavar="IMAGE1 IMAGE2", nargs=2, help="compare IMAGE1 and IMAGE2 and exit with an error if the images are different. This options can appear several times to compare several images.") -optionParser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="display the command line before running the programs.") - -(options, args) = optionParser.parse_args() - -if len(args) < 1: - optionParser.print_usage(sys.stderr) - sys.exit(1) - -# call the program, and exit if it fail - -command = ["@PYTHON_EXECUTABLE@"] + args -if options.verbose: - print >> sys.stderr, "+", " ".join(command) -returnValue = subprocess.call( command ) -if returnValue != 0 : - sys.exit( returnValue ) - -# compare the images if needed -for imageFile1, imageFile2 in options.compare : - command = ["@IMAGE_COMPARE@", imageFile1, imageFile2] - if options.verbose: - print >> sys.stderr, "+", " ".join(command) - returnValue = subprocess.call( command ) - if returnValue != 0 : - sys.exit( returnValue ) - - -# everything suceed - just exit -sys.exit(0) diff --git a/Utilities/ITK/Wrapping/Generators/Ruby/fix_require.rb b/Utilities/ITK/Wrapping/Generators/Ruby/fix_require.rb old mode 100644 new mode 100755 diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/CMakeLists.txt b/Utilities/ITK/Wrapping/Generators/SwigInterface/CMakeLists.txt index dec2cfe31aaf5ff50d87731a4257b7527923d052..6e77848e1c2c3986740dd28d6cfabbcd6f36276d 100644 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/CMakeLists.txt +++ b/Utilities/ITK/Wrapping/Generators/SwigInterface/CMakeLists.txt @@ -1,16 +1,22 @@ ############################################################################### -# find swig -#find_package(SWIG REQUIRED) -#include(${SWIG_USE_FILE}) +# Find python +find_package(PythonInterp REQUIRED) ############################################################################### # Build swig option(ITK_USE_SYSTEM_SWIG "Use system swig. If OFF, swig is built as an external project." OFF) -set(swig_version 2.0.4) -set(swig_md5 4319c503ee3a13d2a53be9d828c3adc0) -set(swigwin_md5 4ab8064b1a8894c8577ef9d0fb2523c8) +# Require at least SWIG 3.0.0 +if(ITK_USE_SYSTEM_SWIG) + if(${SWIG_VERSION} VERSION_LESS 3.0.0) + message(WARNING "Swig version less than 3.0.0: \"${SWIG_VERSION}\".") + endif() +endif() + +set(swig_version 3.0.2) +set(swig_md5 62f9b0d010cef36a13a010dc530d0d41) +set(swigwin_md5 3f18de4fc09ab9abb0d3be37c11fbc8f) if(WIN32) set(swig_ep "${CMAKE_CURRENT_BINARY_DIR}/swigwin-${swig_version}/swig.exe") @@ -35,6 +41,7 @@ if(ITK_USE_SYSTEM_SWIG) else() include(ExternalProject) if(WIN32) + itk_download_attempt_check(SWIG) ExternalProject_Add(swig URL http://prdownloads.sourceforge.net/swig/swigwin-${swig_version}.zip URL_MD5 ${swigwin_md5} @@ -61,9 +68,10 @@ else() # CXXCPP C++ preprocessor # build swig as an external project - ExternalProject_add(PCRE - URL http://downloads.sourceforge.net/project/pcre/pcre/8.12/pcre-8.12.tar.gz - URL_MD5 fa69e4c5d8971544acd71d1f10d59193 + itk_download_attempt_check(PCRE) + ExternalProject_Add(PCRE + URL http://downloads.sourceforge.net/project/pcre/pcre/8.35/pcre-8.35.tar.gz + URL_MD5 ed58bcbe54d3b1d59e9f5415ef45ce1c CONFIGURE_COMMAND env "CC=${CMAKE_C_COMPILER} ${CMAKE_C_COMPILER_ARG1}" @@ -107,7 +115,8 @@ else() # This script will default YFLAGS to the empty string to avoid a # default value of `-d' given by some make applications. - ExternalProject_add(swig + itk_download_attempt_check(SWIG) + ExternalProject_Add(swig URL http://prdownloads.sourceforge.net/swig/swig-${swig_version}.tar.gz URL_MD5 ${swig_md5} CONFIGURE_COMMAND @@ -133,12 +142,10 @@ else() set(SWIG_EXECUTABLE ${swig_ep} CACHE FILEPATH "swig executable." FORCE) endif() - ############################################################################### -# find python -find_package(PythonInterp REQUIRED) -set(CABLE_INDEX ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/idx.py CACHE INTERNAL "cableidx path") +set(IDX_GENERATOR ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/idx.py CACHE INTERNAL "idx generator path") +set(PYGCCXML_DIR ${CMAKE_SOURCE_DIR}/Modules/ThirdParty/pygccxml/src CACHE INTERNAL "pygccxml path") ############################################################################### # install the files requires for swiginterface @@ -149,12 +156,9 @@ if(NOT EXTERNAL_WRAP_ITK_PROJECT) WRAP_ITK_INSTALL(/Configuration/Generators/SwigInterface module.i.in) WRAP_ITK_INSTALL(/Configuration/Generators/SwigInterface module.includes.in) - install(DIRECTORY pygccxml-1.0.0 + install(DIRECTORY ${PYGCCXML_DIR} DESTINATION "${WRAP_ITK_INSTALL_PREFIX}/Configuration/Generators/SwigInterface" - PATTERN ".svn" EXCLUDE - PATTERN "CVS" EXCLUDE - PATTERN "docs" EXCLUDE - PATTERN "unittests" EXCLUDE + PATTERN ".git" EXCLUDE ) install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/idx.py" @@ -244,15 +248,6 @@ macro(itk_end_wrap_module_swig_interface) # set(opts ${opts} --import "${bi}") # endforeach() - # message("${opts}") - - # configure the test driver, to set the python path to the pygccxml dir - # find_program(ITK_TEST_DRIVER itkTestDriver) - # set(PYTHON_PYGCCXML_DRIVER "${ITK_TEST_DRIVER}" - # --add-before-env PYTHONPATH "${WRAP_ITK_CMAKE_DIR}/pygccxml-1.0.0/" - # "${PYTHON_EXECUTABLE}" - # ) - if(ITK_WRAP_EXPLICIT) set(opts ${opts} --include "${WRAPPER_LIBRARY_NAME}Explicit.h") endif() @@ -267,12 +262,13 @@ macro(itk_end_wrap_module_swig_interface) # --include ${WRAPPER_LIBRARY_NAME}.includes # --import ${module_interface_file} --swig-include ${module}_ext.i - -w1 -w3 -w51 -w52 -w53 -w54 #--warning-error + -w1 -w3 -w51 -w52 -w53 -w54 -A protected -A private + -p ${PYGCCXML_DIR} + -g ${GCCXML} --typedef-input ${typedef_in_file} --typedef-output ${typedef_file} --include ${module}SwigInterface.h - # --verbose ${xml_file} ${interface_file} DEPENDS ${DEPS} ${idx_files} ${IGENERATOR} # ${SWIG_INTERFACE_IDX_FILES} ${SWIG_INTERFACE_FILES} ${typedef_in_file} # ${includes_file} @@ -350,7 +346,6 @@ macro(itk_end_wrap_submodule_swig_interface module) # variables used: # WRAPPER_LIBRARY_NAME # WRAPPER_LIBRARY_OUTPUT_DIR - # WRAPPER_LIBRARY_CABLESWIG_INPUTS # WRAPPER_LIBRARY_DEPENDS # WRAPPER_MASTER_INDEX_OUTPUT_DIR # MODULE_INCLUDES @@ -384,9 +379,9 @@ macro(itk_end_wrap_submodule_swig_interface module) set(idx_file "${WRAPPER_MASTER_INDEX_OUTPUT_DIR}/${module}.idx") add_custom_command( OUTPUT ${idx_file} - COMMAND ${CABLE_INDEX} - ${xml_file} ${idx_file} - DEPENDS ${CABLE_INDEX} ${xml_file} + COMMAND ${IDX_GENERATOR} + ${PYGCCXML_DIR} ${GCCXML} ${xml_file} ${idx_file} + DEPENDS ${IDX_GENERATOR} ${xml_file} ) WRAP_ITK_INSTALL("/Configuration/Typedefs/" "${idx_file}") # add_custom_target(${module}Idx DEPENDS ${idx_file}) diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/idx.py b/Utilities/ITK/Wrapping/Generators/SwigInterface/idx.py old mode 100644 new mode 100755 index 3a75b171e907025398ba1905e2030e587422904d..1d5eb26b55cafbe7427505192d89b0771bb7f9a6 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/idx.py +++ b/Utilities/ITK/Wrapping/Generators/SwigInterface/idx.py @@ -1,41 +1,64 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -import sys, os -sys.path.append(sys.path[0]+os.sep+'pygccxml-1.0.0') +# Import unicode literals so that StringIO works on both Python 2 and 3 +from __future__ import unicode_literals +from __future__ import print_function -import pygccxml, sys, cStringIO +import sys +import os + +try: + # Python 3 + from io import StringIO +except ImportError: + # Python 2 + from cStringIO import StringIO + +pygccxmlPath = sys.argv[1] +gccxmlPath = sys.argv[2] +xmlFilePath = sys.argv[3] +idxFilePath = sys.argv[4] + +sys.path.append(pygccxmlPath) +import warnings +# Temporarly hide pygccxml warnings +# Import normally once pygccxml 1.6.0 is out +warnings.filterwarnings("ignore", category=UserWarning) +warnings.filterwarnings("ignore", category=DeprecationWarning) +import pygccxml # the output file -outputFile = cStringIO.StringIO() +outputFile = StringIO() # init the pygccxml stuff pygccxml.declarations.scopedef_t.RECURSIVE_DEFAULT = False pygccxml.declarations.scopedef_t.ALLOW_EMPTY_MDECL_WRAPPER = True -pygccxml_config = pygccxml.parser.config.config_t() -pygccxml_reader = pygccxml.parser.source_reader.source_reader_t(pygccxml_config) +pygccxml_config = pygccxml.parser.config.gccxml_configuration_t( + gccxml_path=gccxmlPath) +pygccxml_reader = pygccxml.parser.source_reader.source_reader_t( + pygccxml_config) # and read a xml file -res = pygccxml_reader.read_xml_file(sys.argv[1]) +res = pygccxml_reader.read_xml_file(xmlFilePath) -global_ns = pygccxml.declarations.get_global_namespace( res ) +global_ns = pygccxml.declarations.get_global_namespace(res) cable_ns = global_ns.namespace('_cable_') wrappers_ns = cable_ns.namespace('wrappers') -module = os.path.splitext(os.path.basename(sys.argv[1]))[0] +module = os.path.splitext(os.path.basename(xmlFilePath))[0] # iterate over all the typedefs in the _cable_::wrappers namespace for typedef in wrappers_ns.typedefs(): - n = typedef.name - s = typedef.type.decl_string - # drop the :: prefix - it make swig produce invalid code - if s.startswith("::"): - s = s[2:] - print >> outputFile, "{%s} {%s} {%s}" % (s, n, module) + n = typedef.name + s = typedef.type.decl_string + # drop the :: prefix - it make swig produce invalid code + if s.startswith("::"): + s = s[2:] + outputFile.write("{%s} {%s} {%s}\n" % (s, n, module)) content = outputFile.getvalue() -if sys.argv[2] != '-': - f = file( sys.argv[2], "w" ) - f.write( content ) - f.close() +if idxFilePath != '-': + with open(idxFilePath, "w") as f: + f.write(content) else: - sys.stdout.write( content ) + sys.stdout.write(content) diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/igenerator.py b/Utilities/ITK/Wrapping/Generators/SwigInterface/igenerator.py old mode 100644 new mode 100755 index ec4fb798bd1692928b1ae1246a14dd842e68ad25..5b672c79f6a18fb5fde8ea25a7015581ae825401 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/igenerator.py +++ b/Utilities/ITK/Wrapping/Generators/SwigInterface/igenerator.py @@ -1,33 +1,146 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -import sys, os -sys.path.append(sys.path[0]+os.sep+'pygccxml-1.0.0') - -import pygccxml, sys, re, cStringIO, time, os +# Import unicode literals so that StringIO works on both Python 2 and 3 +from __future__ import unicode_literals +from __future__ import print_function + +import sys +import os +import re +import time from optparse import OptionParser +try: + # Python 3 + from io import StringIO +except ImportError: + # Python 2 + from cStringIO import StringIO + # Start process time measurement t0 = time.clock() optionParser = OptionParser() -optionParser.add_option("--idx", action="append", dest="idx", default=[], metavar="FILE", help="idx file to be used.") -optionParser.add_option("--mdx", action="append", dest="mdx", default=[], metavar="FILE", help="master idx file to be used.") -optionParser.add_option("--include", action="append", dest="includes", default=[], metavar="FILE", help="File to be included in the generated interface file.") -optionParser.add_option("--take-includes", action="append", dest="take_includes", default=[], metavar="FILE", help="File which contains the include to take, and include in the generated interface file.") -optionParser.add_option("--swig-include", action="append", dest="swig_includes", default=[], metavar="FILE", help="File to be included by swig (%include) in the generated interface file.") -optionParser.add_option("--import", action="append", dest="imports", default=[], metavar="FILE", help="File to be imported in the generated interface file.") -optionParser.add_option("--typedef-input", action="store", type="string", dest="typedef_input") -optionParser.add_option("--typedef-output", action="store", type="string", dest="typedef_output") -optionParser.add_option("-w", "--disable-warning", action="append", dest="warnings", default=[], metavar="WARNING", help="Warning to be disabled.") -optionParser.add_option("-A", "--disable-access-warning", action="append", dest="access_warnings", default=[], metavar="LEVEL", help="Access level where warnings are disabled (public, protected, private).") -optionParser.add_option("-W", "--warning-error", action="store_true", dest="warningError", help="Treat warnings as errors.") -optionParser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Log what is currently done.") -optionParser.add_option("-k", "--keep", action="store_true", dest="keep", help="Don't rewrite the output file if the content is unchanged.") +optionParser.add_option( + "--idx", + action="append", + dest="idx", + default=[], + metavar="FILE", + help="idx file to be used.") +optionParser.add_option( + "--mdx", + action="append", + dest="mdx", + default=[], + metavar="FILE", + help="master idx file to be used.") +optionParser.add_option( + "--include", + action="append", + dest="includes", + default=[], + metavar="FILE", + help="File to be included in the generated interface file.") +optionParser.add_option( + "--take-includes", + action="append", + dest="take_includes", + default=[], + metavar="FILE", + help=( + "File which contains the include to take, and include in the " + "generated interface file.")) +optionParser.add_option( + "--swig-include", + action="append", + dest="swig_includes", + default=[], + metavar="FILE", + help=( + "File to be included by swig (%include) in the generated " + "interface file.")) +optionParser.add_option( + "--import", + action="append", + dest="imports", + default=[], + metavar="FILE", + help="File to be imported in the generated interface file.") +optionParser.add_option( + "--typedef-input", + action="store", + type="string", + dest="typedef_input") +optionParser.add_option( + "--typedef-output", + action="store", + type="string", + dest="typedef_output") +optionParser.add_option( + "-w", + "--disable-warning", + action="append", + dest="igenerator_warnings", + default=[], + metavar="WARNING", + help="Warning to be disabled.") +optionParser.add_option( + "-A", + "--disable-access-warning", + action="append", + dest="access_warnings", + default=[], + metavar="LEVEL", + help=( + "Access level where warnings are disabled " + "(public, protected, private).")) +optionParser.add_option( + "-W", + "--warning-error", + action="store_true", + dest="warningError", + help="Treat warnings as errors.") +optionParser.add_option( + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="Log what is currently done.") +optionParser.add_option( + "-k", + "--keep", + action="store_true", + dest="keep", + help="Don't rewrite the output file if the content is unchanged.") +optionParser.add_option( + "-p", + "--pygccxml-path", + action="store", + dest="pygccxml_path", + help="Path to pygccxml") +optionParser.add_option( + "-g", + "--gccxml-path", + action="store", + dest="gccxml_path", + help="Path to gccxml") options, args = optionParser.parse_args() +sys.path.append(options.pygccxml_path) +import warnings +# Temporarly hide pygccxml warnings +# Import normally once pygccxml 1.6.0 is out +warnings.filterwarnings("ignore", category=UserWarning) +warnings.filterwarnings("ignore", category=DeprecationWarning) +import pygccxml + +# Apply file, for passing std::string as reference in methods +applyFile = StringIO() +applyFileNames = [] # the output file -outputFile = cStringIO.StringIO() +outputFile = StringIO() # a dict to let us use the alias name instead of the full c++ name. Without # that, in many cases, swig don't know that's the same type @@ -41,60 +154,71 @@ usedTypes = set() typedefSource = {} -warnings = set() - -def warn( id, msg, doWarn=True ): - if not doWarn: - # don't warn for anything - return - if str(id) not in options.warnings: - if not options.verbose and (id, msg) in warnings: - # just do nothing - return - warnings.add((id, msg)) +igenerator_warnings = set() + + +def igenerator_warn(id, msg, doWarn=True): + if not doWarn: + # don't warn for anything + return + if str(id) not in options.igenerator_warnings: + if not options.verbose and (id, msg) in igenerator_warnings: + # just do nothing + return + igenerator_warnings.add((id, msg)) + if options.verbose: + if options.warningError: + print("error(%s): %s" % (str(id), msg), file=sys.stderr) + else: + print("warning(%s): %s" % (str(id), msg), file=sys.stderr) + else: + if options.warningError: + print( + "%s: error(%s): %s" % + (args[0], str(id), msg), file=sys.stderr) + else: + print( + "%s: warning(%s): %s" % + (args[0], str(id), msg), file=sys.stderr) + + +def info(msg): if options.verbose: - if options.warningError: - print >> sys.stderr, "error(%s): %s" % (str(id), msg) - else: - print >> sys.stderr, "warning(%s): %s" % (str(id), msg) - else: - if options.warningError: - print >> sys.stderr, "%s: error(%s): %s" % (args[0], str(id), msg) - else: - print >> sys.stderr, "%s: warning(%s): %s" % (args[0], str(id), msg) - -def info( msg ): - if options.verbose: - print >> sys.stderr, "info: %s" % msg + print("info: %s" % msg, file=sys.stderr) notWrapped = [ - "itk::SmartPointerForwardReference<.+>", - "itk::LibHandle", - "itk::NeighborhoodAllocator<.+>", - "itk::ImageRegion<.+>", # to avoid wrapping all the region for all the dims - "itk::ImportImageContainer<.+>", - "itk::DefaultPixelAccessor<.+>", - "itk::NeighborhoodAccessorFunctor<.+>", - "itk::DefaultVectorPixelAccessor<.+>", - "itk::VectorImageNeighborhoodAccessorFunctor<.+>", - "itk::.*Iterator.*", # TODO: remove this one ? - "itk::Neighborhood<.+>", # TODO: remove this one - "itk::ThreadFunctionType", - "itk::Functor::.+", - "itk::SmartPointer< itk::Functor::.+", - "itk::Function::.+", - "itk::.+Function.*", # Level set functions - "itk::InterpolateImageFunction<.+>", # use one more dimension than the wrapped one - "itk::watershed::.+", # ignore the internal classes of the watershed - "itk::SmartPointer< itk::VoronoiDiagram2D<.+> >", # require to wrap too more type - "itk::Image< itk::CovariantVector< double, \d+u >, \d+u >", # used internally in ImageToImageMetric + "itk::SmartPointerForwardReference<.+>", + "itk::LibHandle", + "itk::NeighborhoodAllocator<.+>", + # to avoid wrapping all the region for all the dims + "itk::ImageRegion<.+>", + "itk::ImportImageContainer<.+>", + "itk::DefaultPixelAccessor<.+>", + "itk::NeighborhoodAccessorFunctor<.+>", + "itk::DefaultVectorPixelAccessor<.+>", + "itk::VectorImageNeighborhoodAccessorFunctor<.+>", + "itk::.*Iterator.*", # TODO: remove this one ? + "itk::Neighborhood<.+>", # TODO: remove this one + "itk::ThreadFunctionType", + "itk::Functor::.+", + "itk::SmartPointer< itk::Functor::.+", + "itk::Function::.+", + "itk::.+Function.*", # Level set functions + # use one more dimension than the wrapped one + "itk::InterpolateImageFunction<.+>", + "itk::watershed::.+", # ignore the internal classes of the watershed + # require to wrap too more type + "itk::SmartPointer< itk::VoronoiDiagram2D<.+> >", + # used internally in ImageToImageMetric + "itk::Image< itk::CovariantVector< double, \d+u >, \d+u >", ] -notWrappedRegExp = re.compile( "|".join( [ "^"+s+"$" for s in notWrapped] ) ) +notWrappedRegExp = re.compile("|".join(["^" + s + "$" for s in notWrapped])) # vcl_complex code -vcl_complex_headers = {"D": """ class vcl_complexD { +vcl_complex_headers = { + "D": """ class vcl_complexD { public: ~vcl_complexD(); vcl_complexD & operator=(vcl_complexD const & arg0); @@ -118,7 +242,7 @@ vcl_complex_headers = {"D": """ class vcl_complexD { }; """, -"F": """class vcl_complexF { + "F": """class vcl_complexF { public: ~vcl_complexF(); vcl_complexF & operator=(vcl_complexF const & arg0); @@ -142,7 +266,7 @@ vcl_complex_headers = {"D": """ class vcl_complexD { }; """, -"LD" : """ class vcl_complexLD { + "LD": """ class vcl_complexLD { public: ~vcl_complexLD(); vcl_complexLD & operator=(vcl_complexLD const & arg0); @@ -164,430 +288,535 @@ vcl_complex_headers = {"D": """ class vcl_complexD { private: protected: }; -""" -} +"""} -def getType(v): - if hasattr(v, "type"): - return getType(v.type) - if hasattr(v, "declaration"): - return getType(v.declaration) - return v -def getDeclarationString(t): - t = getType(t) - if t.decl_string == "::PyObject *": - # don't go further - we want to keep that one as is - return "::PyObject *" - if isinstance(t, pygccxml.declarations.cpptypes.pointer_t): - return getDeclarationString(getType(t.base)) + " *" - elif isinstance(t, pygccxml.declarations.cpptypes.const_t): - return getDeclarationString(getType(t.base)) + " const" - elif isinstance(t, pygccxml.declarations.cpptypes.reference_t): - return getDeclarationString(getType(t.base)) + " &" - return t.decl_string - -def renameTypesInSTL( s ): - if s.startswith( "std::" ) and pygccxml.declarations.templates.is_instantiation(s): - args = [] - for arg in pygccxml.declarations.templates.args(s): - t, d = typeAndDecorators( arg ); - args.append( renameTypesInSTL( get_alias( t ) ) + d ) - return pygccxml.declarations.templates.join( pygccxml.declarations.templates.name(s), args ) + typeAndDecorators( s )[1] - return s +def getType(v): + if hasattr(v, "type"): + return getType(v.type) + if hasattr(v, "declaration"): + return getType(v.declaration) + return v -def removeStdAllocator( s ): - if pygccxml.declarations.templates.is_instantiation(s): - args = [] - for arg in pygccxml.declarations.templates.args(s): - if not arg.startswith("std::allocator"): - t, d = typeAndDecorators( arg ); - args.append( removeStdAllocator( t ) + d ) - return pygccxml.declarations.templates.join( pygccxml.declarations.templates.name(s), args ) + typeAndDecorators( s )[1] - return s - - -def typeAndDecorators( s ): - end = "" - s = s.strip() - ends = [" ", "*", "&", "const"] - needToContinue = True - while needToContinue: - needToContinue = False - for e in ends: - if s.endswith( e ): - end = e + end - s = s[:-len(e)] - needToContinue = True - return (s, end) - - -def get_alias( decl_string, w=True ): - s = str(decl_string) - - # drop the :: prefix - it make swig produce invalid code - if s.startswith("::"): - s = s[2:] - - # normalize string - s = normalize( s ) - - # workaround a bug - or is it a feature ? - somewhere - s = s.replace("complex float", "std::complex<float>") - s = s.replace("complex double", "std::complex<double>") - s = s.replace("complex long double", "std::complex<long double>") - - (s, end) = typeAndDecorators( s ) - - if aliases.has_key( s ): -# print >> sys.stderr, s, end, " ", aliases[s] - usedTypes.add( aliases[s] ) - return aliases[s] + end - - if s.startswith("itk::Templates::"): - # that's a explicitly instantiated type. The name is the same than the WraITK - # one, so lets use it as a base for WrapITK - # Ex: itk::Templates::RGBPixelUC - # don't store the new string in s, because we need it unchanged if the type is - # explicitly instantiated, but not wrapped - new_s = s.replace("::Templates::", "") - if new_s.split("::")[0] in aliases.values(): - usedTypes.add( new_s ) - return new_s + end - - if s[:s.rfind("::")] in aliases: - # take care of subtypes/enum/... - alias = aliases[ s[:s.rfind("::")] ] + s[s.rfind("::"):] - usedTypes.add( alias ) - return alias + end - - # replace the types defined in this type, to support std::vector<itkDataObject> for example - s = renameTypesInSTL( s ) - - # drop the allocator part of the type, because it is not supported by the %template directive with some generators (like tcl) - s = removeStdAllocator( s ) - - # rename basic_string to std::string to make name shorter - s = s.replace("std::basic_string< char, std::char_traits< char > >", "std::string") - - # rename some types not renamed by gccxml (why ?) - s = s.replace( "itk::SerieUIDContainer", "std::vector< std::string >") - s = s.replace( "itk::FilenamesContainer", "std::vector< std::string >") - - if s.startswith( "itk::") and not notWrappedRegExp.match( s ): - warn( 4, "ITK type not wrapped, or currently not known: %s" % s, w ) - - usedTypes.add( s ) - return s + end +def getDeclarationString(t): + t = getType(t) + if t.decl_string == "::PyObject *": + # don't go further - we want to keep that one as is + return "::PyObject *" + if isinstance(t, pygccxml.declarations.cpptypes.pointer_t): + return getDeclarationString(getType(t.base)) + " *" + elif isinstance(t, pygccxml.declarations.cpptypes.const_t): + return getDeclarationString(getType(t.base)) + " const" + elif isinstance(t, pygccxml.declarations.cpptypes.reference_t): + return getDeclarationString(getType(t.base)) + " &" + return t.decl_string + + +def renameTypesInSTL(s): + if s.startswith("std::") and \ + pygccxml.declarations.templates.is_instantiation(s): + args = [] + for arg in pygccxml.declarations.templates.args(s): + t, d = typeAndDecorators(arg) + args.append(renameTypesInSTL(get_alias(t)) + d) + return pygccxml.declarations.templates.join( + pygccxml.declarations.templates.name(s), + args) + typeAndDecorators(s)[1] + return s + + +def removeStdAllocator(s): + if pygccxml.declarations.templates.is_instantiation(s): + args = [] + for arg in pygccxml.declarations.templates.args(s): + if not arg.startswith("std::allocator"): + t, d = typeAndDecorators(arg) + args.append(removeStdAllocator(t) + d) + return pygccxml.declarations.templates.join( + pygccxml.declarations.templates.name(s), + args) + typeAndDecorators(s)[1] + return s + + +def typeAndDecorators(s): + end = "" + s = s.strip() + ends = [" ", "*", "&", "const"] + needToContinue = True + while needToContinue: + needToContinue = False + for e in ends: + if s.endswith(e): + end = e + end + s = s[:-len(e)] + needToContinue = True + return (s, end) + + +def get_alias(decl_string, w=True): + s = str(decl_string) + + # drop the :: prefix - it make swig produce invalid code + if s.startswith("::"): + s = s[2:] + + # normalize string + s = normalize(s) + + # workaround a bug - or is it a feature ? - somewhere + s = s.replace("complex float", "std::complex<float>") + s = s.replace("complex double", "std::complex<double>") + s = s.replace("complex long double", "std::complex<long double>") + + (s, end) = typeAndDecorators(s) + + if s in aliases: + # print(s, end, " ", aliases[s], file=sys.stderr) + usedTypes.add(aliases[s]) + return aliases[s] + end + + if s.startswith("itk::Templates::"): + # that's a explicitly instantiated type. The name is the same than + # the WraITK one, so lets use it as a base for WrapITK + # Ex: itk::Templates::RGBPixelUC + # don't store the new string in s, because we need it unchanged if + # the type is explicitly instantiated, but not wrapped + new_s = s.replace("::Templates::", "") + if new_s.split("::")[0] in aliases.values(): + usedTypes.add(new_s) + return new_s + end + + if s[:s.rfind("::")] in aliases: + # take care of subtypes/enum/... + alias = aliases[s[:s.rfind("::")]] + s[s.rfind("::"):] + usedTypes.add(alias) + return alias + end + + # replace the types defined in this type, to support + # std::vector<itkDataObject> for example + s = renameTypesInSTL(s) + + # drop the allocator part of the type, because it is not supported by the + # %template directive with some generators (like tcl) + s = removeStdAllocator(s) + + # rename basic_string to std::string to make name shorter + s = s.replace( + "std::basic_string< char, std::char_traits< char > >", + "std::string") + + # rename some types not renamed by gccxml (why ?) + s = s.replace("itk::SerieUIDContainer", "std::vector< std::string >") + s = s.replace("itk::FilenamesContainer", "std::vector< std::string >") + + if s.startswith("itk::") and not notWrappedRegExp.match(s): + igenerator_warn( + 4, + "ITK type not wrapped, or currently not known: %s" % + s, + w) + + usedTypes.add(s) + return s + end def load_idx(file_name): - f = file(file_name) - for l in f: - (full_name, alias, module) = re.findall(r'{(.*)} {(.*)} {(.*)}', l)[0] - # workaround lack of :: prefix in idx files - # TODO: would it be better to remove the :: prefix in the output of pygccxml ? - # full_name = "::"+full_name - # normalize some basic type names - full_name = normalize( full_name ) - # TODO: add a warning if the type is defined several times - aliases[ full_name ] = alias - # store the source of the def - if typedefSource.has_key( alias ) and file_name != typedefSource[ alias ]: - warn( 7, "%s in %s is already defined in %s." % (alias, file_name, typedefSource[ alias ]) ) - else: - typedefSource[ alias ] = file_name - # don't declare the typedef - they are included from .include files - # print >> outputFile, "typedef %s %s;" % (full_name, alias) - f.close() + with open(file_name, "r") as f: + for l in f: + (full_name, alias, module) = \ + re.findall(r'{(.*)} {(.*)} {(.*)}', l)[0] + # workaround lack of :: prefix in idx files + # TODO: would it be better to remove the :: prefix in the output of + # pygccxml ? + # full_name = "::"+full_name + # normalize some basic type names + full_name = normalize(full_name) + # TODO: add a warning if the type is defined several times + aliases[full_name] = alias + # store the source of the def + if alias in typedefSource and file_name != typedefSource[alias]: + igenerator_warn( + 7, "%s in %s is already defined in %s." % + (alias, file_name, typedefSource[alias])) + else: + typedefSource[alias] = file_name + # don't declare the typedef - they are included from .include files + # outputFile.write("typedef %s %s;\n" % (full_name, alias)) mdx_loaded = set() + + def load_mdx(file_name): - if file_name in mdx_loaded: - # already loaded - no need to do it again - return - mdx_loaded.add( file_name ) - f = file( file_name ) - ls = f.readlines() - f.close() - for l in ls : - if l.startswith( '%' ) or l.isspace(): - # exclude the lines which are starting with % - that's not the idx files - pass - elif l.strip().endswith(".mdx"): - load_mdx(os.path.dirname(file_name)+os.sep+l.strip()) - else: - load_idx(os.path.dirname(file_name)+os.sep+l.strip()) + if file_name in mdx_loaded: + # already loaded - no need to do it again + return + mdx_loaded.add(file_name) + with open(file_name, "r") as f: + ls = f.readlines() + for l in ls: + if l.startswith('%') or l.isspace(): + # exclude the lines which are starting with % - that's not the idx + # files + pass + elif l.strip().endswith(".mdx"): + load_mdx(os.path.dirname(file_name) + os.sep + l.strip()) + else: + load_idx(os.path.dirname(file_name) + os.sep + l.strip()) def normalize(name): - name = name.replace("short unsigned int", "unsigned short") - name = name.replace("long unsigned int", "unsigned long") - name = name.replace("short int", "short") - name = name.replace("long int", "long") + name = name.replace("short unsigned int", "unsigned short") + name = name.replace("long unsigned int", "unsigned long") + name = name.replace("short int", "short") + name = name.replace("long int", "long") # name = name.replace("unsigned int", "unsigned") - # normalize spaces - name = " ".join(name.replace(',', ', ').split()) - return name - - -def generate_class( typedef, indent=0 ): - info("Generating interface for %s." % typedef.name) - - if not typedef.name.startswith("vcl_complex"): - super_classes = [] - for super_class in typedef.type.declaration.bases: - super_classes.append( "%s %s" % ( super_class.access, get_alias(super_class.related_class.decl_string) ) ) - s = "" - if super_classes: - s = " : " + ", ".join( super_classes ) - print >> outputFile, " "*indent, "class %s%s {" % ( typedef.name, s ) - - # iterate over access - for access in pygccxml.declarations.ACCESS_TYPES.ALL: - - # print the access type - print >> outputFile, " "*indent, " %s:" % access - - # warnings or no warning? - w = access not in options.access_warnings - - # iterate over the members - for member in typedef.type.declaration.get_members( access=access ): - if isinstance( member, pygccxml.declarations.typedef.typedef_t ): - warn( 51, "Member typedef are not supported: %s" % member.name, w ) - elif isinstance( member, pygccxml.declarations.calldef.member_function_t ): - generate_method( typedef, member, indent, w ) - elif isinstance( member, pygccxml.declarations.calldef.constructor_t ): - generate_constructor( typedef, member, indent, w ) - elif isinstance( member, pygccxml.declarations.calldef.member_operator_t ): - generate_method( typedef, member, indent, w ) - elif isinstance( member, pygccxml.declarations.calldef.destructor_t ): - generate_destructor( typedef, member, indent, w ) - elif isinstance( member, pygccxml.declarations.enumeration.enumeration_t ): - generate_nested_enum( typedef, member, indent, w ) - elif isinstance( member, pygccxml.declarations.variable.variable_t ): - warn( 52, "Member variables are not supported: %s" % member.name, w ) - elif isinstance( member, pygccxml.declarations.class_declaration.class_t ): - warn( 53, "Member classes are not supported: %s" % member.name, w ) - elif isinstance( member, pygccxml.declarations.class_declaration.class_declaration_t ): - warn( 53, "Member classes are not supported: %s" % member.name, w ) - elif isinstance( member, pygccxml.declarations.calldef.casting_operator_t ): - warn( 54, "Member casting operators are not supported: %s" % member.name, w ) - else : - warn( 50, "Unknown member type: %s" % repr(member), w ) - - # finally, close the class - print >> outputFile, " "*indent, "};" - print >> outputFile - print >> outputFile - - elif typedef.name == "vcl_complexD": - print >> outputFile, vcl_complex_headers["D"] - elif typedef.name == "vcl_complexF": - print >> outputFile, vcl_complex_headers["F"] - elif typedef.name == "vcl_complexLD": - print >> outputFile, vcl_complex_headers["LD"] - else: - # vcl_complex is too difficult to wrap in some cases. Only wrap the constructor. - print >> outputFile, " "*indent, "class %s%s {" % ( typedef.name, s ) - - # iterate over access - for access in pygccxml.declarations.ACCESS_TYPES.ALL: - - # print the access type - print >> outputFile, " "*indent, " %s:" % access - - # warnings or no warning? - w = access not in options.access_warnings - for member in typedef.type.declaration.get_members( access=access ): - if isinstance( member, pygccxml.declarations.calldef.constructor_t ): - generate_constructor( typedef, member, indent, w ) - elif isinstance( member, pygccxml.declarations.calldef.destructor_t ): - generate_destructor( typedef, member, indent, w ) - # finally, close the class - print >> outputFile, " "*indent, "};" - print >> outputFile - print >> outputFile - - -def generate_constructor( typedef, constructor, indent, w ): - # iterate over the arguments - args = [] - for arg in constructor.arguments: - s = "%s %s" % (get_alias(getDeclarationString(arg), w), arg.name) - # append the default value if it exists - if arg.default_value: - s += " = %s" % arg.default_value - # and add the string to the arg list - args.append( s ) - print >> outputFile, " "*indent, " %s(%s);" % (typedef.name, ", ".join( args) ) - - -def generate_destructor( typedef, destructor, indent, w ): - print >> outputFile, " "*indent, " ~%s();" % typedef.name - - -def generate_enum( typedef ): - name = typedef.name - enum = typedef.type.declaration - decl_string = typedef.type.decl_string - # extract the namespace to put it in c++ code. Without that, the code generated by swig - # is wrong because it doesn't include the namespace - ns = "::".join( decl_string.split("::")[:-1]) - print >> outputFile, "%{" - print >> outputFile, "using namespace %s;" % ns - print >> outputFile, "%}" - content = [" %s = %i" % (key, value) for key, value in enum.values] - print >> outputFile, "enum %s { %s };" % ( name, ", ".join( content ) ) - - -def generate_nested_enum( typedef, enum, indent, w ): - content = [" %s = %i" % (key, value) for key, value in enum.values] - print >> outputFile, " "*indent, " enum %s { %s };" % ( enum.name, ", ".join( content ) ) - - -def generate_method( typedef, method, indent, w ): - info("Generating interface for method '%s::%s'." % (typedef.name, method.name) ) - # avoid the apply method for the class vnl_c_vector: the signature is quite strange - # and currently confuse swig :-/ - if "(" in method.return_type.decl_string : - warn( 1, "ignoring method not supported by swig '%s::%s'." % (typedef.name, method.name), w ) - return - - if ( (typedef.name.startswith('vnl_') and method.name in ["as_ref"]) - or (typedef.name.startswith('itk') and method.name in ["rBegin", "rEnd", "GetSpacingCallback", "GetOriginCallback", "Begin", "End"]) ) : - warn( 3, "ignoring black listed method '%s::%s'." % (typedef.name, method.name), w ) - return - - # iterate over the arguments - args = [] - for arg in method.arguments: - s = "%s %s" % (get_alias(getDeclarationString(arg), w), arg.name) - if "(" in s: - warn( 1, "ignoring method not supported by swig '%s::%s'." % (typedef.name, method.name), w ) - return - # append the default value if it exists - if arg.default_value: - s += " = %s" % arg.default_value - # and add the string to the arg list - args.append( s ) - - # find the method decorators - static = "" - const = "" - if method.has_static: - static = "static " - if method.has_const: - const = " const" - if method.virtuality != "not virtual": - static += "virtual " - if method.virtuality == "pure virtual": - const += " = 0" - - print >> outputFile, " "*indent, " %s%s %s(%s)%s;" % (static, get_alias(getDeclarationString(method.return_type), w), method.name, ", ".join( args), const ) - - + # normalize spaces + name = " ".join(name.replace(',', ', ').split()) + return name + + +def generate_class(typedef, indent=0): + info("Generating interface for %s." % typedef.name) + + decls = pygccxml.declarations + + if not typedef.name.startswith("vcl_complex"): + super_classes = [] + for super_class in typedef.type.declaration.bases: + super_classes.append( + "%s %s" % + (super_class.access, + get_alias( + super_class.related_class.decl_string))) + s = "" + if super_classes: + s = " : " + ", ".join(super_classes) + outputFile.write(" " * indent) + outputFile.write("class %s%s {\n" % (typedef.name, s)) + + # iterate over access + for access in decls.ACCESS_TYPES.ALL: + + # the access type + outputFile.write(" " * indent) + outputFile.write(" %s:" % access) + + # warnings or no warning? + w = access not in options.access_warnings + + # iterate over the members + for member in typedef.type.declaration.get_members(access=access): + if isinstance(member, decls.typedef.typedef_t): + igenerator_warn( + 51, + "Member typedef are not supported: %s" % + member.name, + w) + elif isinstance(member, decls.calldef.member_function_t): + generate_method(typedef, member, indent, w) + elif isinstance(member, decls.calldef.constructor_t): + generate_constructor(typedef, member, indent, w) + elif isinstance(member, decls.calldef.member_operator_t): + generate_method(typedef, member, indent, w) + elif isinstance(member, decls.calldef.destructor_t): + generate_destructor(typedef, member, indent, w) + elif isinstance(member, decls.enumeration.enumeration_t): + generate_nested_enum(typedef, member, indent, w) + elif isinstance(member, decls.variable.variable_t): + igenerator_warn( + 52, + "Member variables are not supported: %s" % + member.name, + w) + elif isinstance(member, decls.class_declaration.class_t): + igenerator_warn( + 53, + "Member classes are not supported: %s" % + member.name, + w) + elif isinstance( + member, decls.class_declaration.class_declaration_t): + igenerator_warn( + 53, + "Member classes are not supported: %s" % + member.name, + w) + elif isinstance(member, decls.calldef.casting_operator_t): + igenerator_warn( + 54, + "Member casting operators are not supported: %s" % + member.name, + w) + else: + igenerator_warn( + 50, + "Unknown member type: %s" % + repr(member), + w) + + # finally, close the class + outputFile.write(" " * indent) + outputFile.write("};\n\n\n") + + elif typedef.name == "vcl_complexD": + outputFile.write(vcl_complex_headers["D"] + '\n') + elif typedef.name == "vcl_complexF": + outputFile.write(vcl_complex_headers["F"] + '\n') + elif typedef.name == "vcl_complexLD": + outputFile.write(vcl_complex_headers["LD"] + '\n') + else: + # vcl_complex is too difficult to wrap in some cases. Only wrap the + # constructor. + outputFile.write(" " * indent) + outputFile.write("class %s%s {\n" % (typedef.name, s)) + + # iterate over access + for access in pygccxml.declarations.ACCESS_TYPES.ALL: + + # the access type + outputFile.write(" " * indent) + outputFile.write(" %s:\n" % access) + + # warnings or no warning? + w = access not in options.access_warnings + for member in typedef.type.declaration.get_members(access=access): + if isinstance(member, decls.calldef.constructor_t): + generate_constructor(typedef, member, indent, w) + elif isinstance(member, decls.calldef.destructor_t): + generate_destructor(typedef, member, indent, w) + # finally, close the class + outputFile.write(" " * indent) + outputFile.write("};\n\n\n") + + +def generate_constructor(typedef, constructor, indent, w): + # iterate over the arguments + args = [] + for arg in constructor.arguments: + s = "%s %s" % (get_alias(getDeclarationString(arg), w), arg.name) + # append the default value if it exists + if arg.default_value: + s += " = %s" % arg.default_value + # and add the string to the arg list + args.append(s) + outputFile.write(" " * indent) + outputFile.write(" %s(%s);\n" % (typedef.name, ", ".join(args))) + + +def generate_destructor(typedef, destructor, indent, w): + outputFile.write(" " * indent) + outputFile.write(" ~%s();\n" % typedef.name) + + +def generate_enum(typedef): + name = typedef.name + enum = typedef.type.declaration + decl_string = typedef.type.decl_string + # extract the namespace to put it in c++ code. Without that, the code + # generated by swig + # is wrong because it doesn't include the namespace + ns = "::".join(decl_string.split("::")[:-1]) + outputFile.write("%{\n") + outputFile.write("using namespace %s;\n" % ns) + outputFile.write("%}\n") + content = [" %s = %i" % (key, value) for key, value in enum.values] + outputFile.write("enum %s { %s };\n" % (name, ", ".join(content))) + + +def generate_nested_enum(typedef, enum, indent, w): + content = [" %s = %i" % (key, value) for key, value in enum.values] + outputFile.write(" " * indent) + outputFile.write(" enum %s { %s };\n" % (enum.name, ", ".join(content))) + + +def generate_method(typedef, method, indent, w): + info( + "Generating interface for method '%s::%s'." % + (typedef.name, method.name)) + # avoid the apply method for the class vnl_c_vector: the signature is + # quite strange and currently confuse swig :-/ + if "(" in method.return_type.decl_string: + igenerator_warn( + 1, "ignoring method not supported by swig '%s::%s'." % + (typedef.name, method.name), w) + return + + names = [ + "rBegin", + "rEnd", + "GetSpacingCallback", + "GetOriginCallback", + "Begin", + "End"] + + if ((typedef.name.startswith('vnl_') and method.name in ["as_ref"]) + or (typedef.name.startswith('itk') and method.name in names)): + igenerator_warn( + 3, "ignoring black listed method '%s::%s'." % + (typedef.name, method.name), w) + return + + # iterate over the arguments + args = [] + for arg in method.arguments: + s = "%s %s" % (get_alias(getDeclarationString(arg), w), arg.name) + if "(" in s: + igenerator_warn( + 1, "ignoring method not supported by swig '%s::%s'." % + (typedef.name, method.name), w) + return + # append the default value if it exists + if arg.default_value: + s += " = %s" % arg.default_value + # and add the string to the arg list + args.append(s) + + # find the method decorators + static = "" + const = "" + if method.has_static: + static = "static " + if method.has_const: + const = " const" + if method.virtuality != "not virtual": + static += "virtual " + if method.virtuality == "pure virtual": + const += " = 0" + + outputFile.write(" " * indent) + outputFile.write( + " %s%s %s(%s)%s;\n" % + (static, + get_alias( + getDeclarationString( + method.return_type), + w), + method.name, + ", ".join(args), + const)) + + # Check the method arguments for std::string passed by reference. + # In this case, save the name of the argument in the applyFileNames list + # for further usage. + for arg in method.arguments: + # arg.type is an instance, there is no clean API in pygccxml to get the + # name of the type as a string. This functionnality needs to be added + # to pygccxml. Meanwhile, we can use the __str__() method. + if arg.type.__str__() == "std::string &": + applyFileNames.append(arg.name) # init the pygccxml stuff pygccxml.declarations.scopedef_t.RECURSIVE_DEFAULT = False pygccxml.declarations.scopedef_t.ALLOW_EMPTY_MDECL_WRAPPER = True -# pass a fake gccxml path: it is not used here, but is required by -# pygccxml -pygccxml_config = pygccxml.parser.config.config_t() -#pygccxml_config = pygccxml.parser.config.config_t("gccxml") +pygccxml_config = pygccxml.parser.config.gccxml_configuration_t( + gccxml_path=options.gccxml_path) # create a reader -pygccxml_reader = pygccxml.parser.source_reader.source_reader_t(pygccxml_config) +pygccxml_reader = pygccxml.parser.source_reader.source_reader_t( + pygccxml_config) # and read a xml file info("Processing %s." % args[0]) res = pygccxml_reader.read_xml_file(args[0]) -global_ns = pygccxml.declarations.get_global_namespace( res ) +global_ns = pygccxml.declarations.get_global_namespace(res) cable_ns = global_ns.namespace('_cable_') wrappers_ns = cable_ns.namespace('wrappers') -# pygccxml.declarations.print_declarations( global_ns ) moduleName = cable_ns.variable('group').value[len('(const char*)"'):-1] # and begin to write the output -headerFile = cStringIO.StringIO() +headerFile = StringIO() info("Generating %s header." % args[1]) -print >> headerFile, "// This file is automatically generated." -print >> headerFile, "// Do not modify this file manually." -print >> headerFile -print >> headerFile +headerFile.write("// This file is automatically generated.\n") +headerFile.write("// Do not modify this file manually.\n\n\n") + +langs = [ + "CHICKEN", + "CSHARP", + "GUILE", + "JAVA", + "LUA", + "MODULA3", + "MZSCHEME", + "OCAML", + "PERL", + "PERL5", + "PHP", + "PHP4", + "PHP5", + "PIKE", + "PYTHON", + "R", + "RUBY", + "SEXP", + "TCL", + "XML"] # first, define the module # [1:-1] is there to drop the quotes -for lang in ["CHICKEN", "CSHARP", "GUILE", "JAVA", "LUA", "MODULA3", "MZSCHEME", "OCAML", "PERL", "PERL5", "PHP", "PHP4", "PHP5", "PIKE", "PYTHON", "R", "RUBY", "SEXP", "TCL", "XML"]: - print >> headerFile, "#ifdef SWIG%s" % lang - print >> headerFile, "%%module %s%s" % ( moduleName, lang.title() ) - print >> headerFile, "#endif" -print >> headerFile +for lang in langs: + headerFile.write("#ifdef SWIG%s\n" % lang) + headerFile.write("%%module %s%s\n" % (moduleName, lang.title())) + headerFile.write("#endif\n") +headerFile.write('\n') # add the includes # use a set to avoid putting many times the same include s = set() -print >> headerFile, "%{" +headerFile.write("%{\n") # the include files passed in option for f in options.includes: - i = '#include "%s"' % f - if not i in s: - print >> headerFile, i - s.add( i ) + i = '#include "%s"' % f + if i not in s: + headerFile.write(i + '\n') + s.add(i) # and the includes files from other files for file_name in options.take_includes: - f = file( file_name ) - for l in f : - if l.startswith( '#include' ): - i = " ".join(l.strip().split()) - if not i in s: - print >> headerFile, i - s.add( i ) - f.close() -print >> headerFile, "%}" -print >> headerFile -print >> headerFile + with open(file_name, "r") as f: + for l in f: + if l.startswith('#include'): + i = " ".join(l.strip().split()) + if i not in s: + headerFile.write(i + '\n') + s.add(i) +headerFile.write("%}\n\n\n") # load the aliases files -print >> headerFile, "%{" +headerFile.write("%{\n") # the idx files passed in option for f in options.idx: - load_idx(f) + load_idx(f) # and the idx files in the mdx ones for f in options.mdx: - load_mdx(f) + load_mdx(f) # iterate over all the typedefs in the _cable_::wrappers namespace # to fill the alias dict -for typedef in wrappers_ns.typedefs(): #allow_empty=True): - s = str(typedef.type.decl_string) - # drop the :: prefix - it make swig produce invalid code - if s.startswith("::"): - s = s[2:] - if not aliases.has_key( s ) : - warn( 2, "%s (%s) should be already defined in the idx files." % (s, typedef.name) ) - aliases[s] = typedef.name - # declare the typedef - print >> headerFile, "typedef %s %s;" % (s, typedef.name) - -print >> headerFile, "%}" -print >> headerFile -print >> headerFile +for typedef in wrappers_ns.typedefs(): # allow_empty=True): + s = str(typedef.type.decl_string) + # drop the :: prefix - it make swig produce invalid code + if s.startswith("::"): + s = s[2:] + if s not in aliases: + igenerator_warn( + 2, "%s (%s) should be already defined in the idx files." % + (s, typedef.name)) + aliases[s] = typedef.name + # declare the typedef + headerFile.write("typedef %s %s;\n" % (s, typedef.name)) + +headerFile.write("%}\n\n\n") # add the imports -importFile = cStringIO.StringIO() +importFile = StringIO() for f in options.imports: - print >> importFile, "%%import %s" % f -print >> importFile -print >> importFile + importFile.write("%%import %s\n" % f) +importFile.write("\n\n") # add the swig includes -includeFile = cStringIO.StringIO() +includeFile = StringIO() for f in options.swig_includes: - print >> includeFile, "%%include %s" % f -print >> includeFile -print >> includeFile + includeFile.write("%%include %s\n" % f) +includeFile.write('\n\n') # iterate over all the typedefs in the _cable_::wrappers namespace @@ -596,16 +825,26 @@ print >> includeFile classes = [] for typedef in wrappers_ns.typedefs(): - # begin a new class - if isinstance( typedef.type.declaration, pygccxml.declarations.class_declaration.class_t ): - classes.append( (typedef.name, [get_alias(super_class.related_class.decl_string) for super_class in typedef.type.declaration.bases], typedef) ) + # begin a new class + if isinstance( + typedef.type.declaration, + pygccxml.declarations.class_declaration.class_t): - elif isinstance( typedef.type.declaration, pygccxml.declarations.enumeration.enumeration_t ): - # warn( 6, "Enum are currently supported only nested in a class." ) - generate_enum( typedef ) + classes.append(( + typedef.name, + [get_alias(super_class.related_class.decl_string) for + super_class in typedef.type.declaration.bases], typedef)) - else: - warn( 5, "Unknown type type: %s" % str(typedef.type.declaration) ) + elif isinstance( + typedef.type.declaration, + pygccxml.declarations.enumeration.enumeration_t): + # igenerator_warn( 6, "Enum are currently supported only nested in a + # class." ) + generate_enum(typedef) + + else: + igenerator_warn( + 5, "Unknown type type: %s" % str(typedef.type.declaration)) # copy the classes in a new ordered list, according to the dependencies @@ -615,77 +854,89 @@ classes = sorted(classes) name_already_in_typedefs = [] typedefs = [] while len(classes) != 0: - nclasses = [] - for name, deps, typedef in classes: - ok = True - for d in deps: - if d in name_local_classes and d not in name_already_in_typedefs: - ok = False - if ok: - name_already_in_typedefs.append(name) - typedefs.append(typedef) - else: - nclasses.append( (name, deps, typedef) ) - classes = nclasses + nclasses = [] + for name, deps, typedef in classes: + ok = True + for d in deps: + if d in name_local_classes and d not in name_already_in_typedefs: + ok = False + if ok: + name_already_in_typedefs.append(name) + typedefs.append(typedef) + else: + nclasses.append((name, deps, typedef)) + classes = nclasses # now really generate the swig interface for typedef in typedefs: - # begin a new class - generate_class( typedef ) + # begin a new class + generate_class(typedef) -if len(warnings) > 0 and options.warningError: - sys.exit(1) +if len(igenerator_warnings) > 0 and options.warningError: + sys.exit(1) # search the files to import usedSources = set() for alias in usedTypes: - if typedefSource.has_key( alias ): - idxName = os.path.basename( typedefSource[ alias ] ) - iName = idxName[:-len(".idx")] - usedSources.add( iName ) -outputFileName = os.path.basename( args[1] ) + if alias in typedefSource: + idxName = os.path.basename(typedefSource[alias]) + iName = idxName[:-len(".idx")] + usedSources.add(iName) +outputFileName = os.path.basename(args[1]) if outputFileName in usedSources: - usedSources.remove( outputFileName ) -# print usedSources + usedSources.remove(outputFileName) for src in usedSources: - print >> importFile, "%%import %s.i" % src -print >> importFile -print >> importFile + importFile.write("%%import %s.i\n" % src) +importFile.write('\n\n') # create the typedef header if options.typedef_output: - typedefFile = cStringIO.StringIO() - print >> typedefFile, "#ifndef __%sSwigInterface_h" % moduleName - print >> typedefFile, "#define __%sSwigInterface_h" % moduleName - if options.typedef_input: - f = file(options.typedef_input) - print >> typedefFile, f.read() - f.close() - for src in usedSources: - print >> typedefFile, '#include "%sSwigInterface.h"' % src - print >> typedefFile, "#endif" - f = file(options.typedef_output, "w") - f.write( typedefFile.getvalue() ) - f.close() - + typedefFile = StringIO() + typedefFile.write("#ifndef __%sSwigInterface_h\n" % moduleName) + typedefFile.write("#define __%sSwigInterface_h\n" % moduleName) + if options.typedef_input: + with open(options.typedef_input, "r") as f: + typedefFile.write(f.read() + '\n') + for src in usedSources: + typedefFile.write('#include "%sSwigInterface.h"\n' % src) + typedefFile.write("#endif\n") + with open(options.typedef_output, "w") as f: + f.write(typedefFile.getvalue()) + +# When a std::string is passed by reference, we need to add the %apply +# line with the argument name, and the INOUT command. +# Use a set() to have remove duplicates, this will work event if we got +# multiple functions with the same argument name in the same .i file +# (swig should take care of it). +applyFileNames = set(applyFileNames) +for name in applyFileNames: + applyFile.write( + "%apply (std::string& INOUT) { std::string & " + name + "};\n") +applyFile.write("\n\n") # finally, really write the output -content = headerFile.getvalue()+ importFile.getvalue() + includeFile.getvalue() + outputFile.getvalue() +content = headerFile.getvalue() + importFile.getvalue() + \ + includeFile.getvalue() + applyFile.getvalue() + outputFile.getvalue() if args[1] != '-': - if options.keep and os.path.exists( args[1] ) and file( args[1] ).read() == content: - info("%s unchanged." % args[1]) - else: - info("Writing %s." % args[1]) - f = file(args[1], "w") - f.write( content ) - f.close() + + if options.keep and os.path.exists(args[1]): + with open(args[1], "r") as f: + filecontent = f.read() + + if options.keep and os.path.exists(args[1]) and \ + filecontent == content: + info("%s unchanged." % args[1]) + else: + info("Writing %s." % args[1]) + with open(args[1], "w") as f: + f.write(content) else: - sys.stdout.write( content ) + sys.stdout.write(content) # Stop process time measurement info("%s seconds i-generation time." % (time.clock() - t0)) diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/LICENSE_1_0.txt b/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/LICENSE_1_0.txt deleted file mode 100644 index 36b7cd93cdfbac762f5be4c6ce276df2ea6305c2..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/LICENSE_1_0.txt +++ /dev/null @@ -1,23 +0,0 @@ -Boost Software License - Version 1.0 - August 17th, 2003 - -Permission is hereby granted, free of charge, to any person or organization -obtaining a copy of the software and accompanying documentation covered by -this license (the "Software") to use, reproduce, display, distribute, -execute, and transmit the Software, and to prepare derivative works of the -Software, and to permit third-parties to whom the Software is furnished to -do so, all subject to the following: - -The copyright notices in the Software and this entire statement, including -the above license grant, this restriction and the following disclaimer, -must be included in all copies of the Software, in whole or in part, and -all derivative works of the Software, unless such copies or derivative -works are solely in the form of machine-executable object code generated by -a source language processor. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT -SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE -FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, -ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/MANIFEST b/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/MANIFEST deleted file mode 100644 index f8dc7f9bc0524471619782d4ea466bd905d4e524..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/MANIFEST +++ /dev/null @@ -1,553 +0,0 @@ -announcement.txt -LICENSE_1_0.txt -MANIFEST -README.txt -setup.py -docs\declarations_uml.png -docs\definition.rest -docs\design.rest -docs\download.rest -docs\links.rest -docs\parser_uml.png -docs\pkg-info.txt -docs\pygccxml.rest -docs\pygccxml_uml.vsd -docs\query_interface.rest -docs\upgrade_issues.rest -docs\users.rest -docs\apidocs\api-objects.txt -docs\apidocs\class-tree.html -docs\apidocs\crarr.png -docs\apidocs\epydoc.css -docs\apidocs\epydoc.js -docs\apidocs\help.html -docs\apidocs\identifier-index.html -docs\apidocs\index.html -docs\apidocs\module-tree.html -docs\apidocs\pygccxml-module.html -docs\apidocs\pygccxml-pysrc.html -docs\apidocs\pygccxml.declarations-module.html -docs\apidocs\pygccxml.declarations-pysrc.html -docs\apidocs\pygccxml.declarations.algorithm-module.html -docs\apidocs\pygccxml.declarations.algorithm-pysrc.html -docs\apidocs\pygccxml.declarations.algorithm.match_declaration_t-class.html -docs\apidocs\pygccxml.declarations.algorithm.visit_function_has_not_been_found_t-class.html -docs\apidocs\pygccxml.declarations.algorithms_cache-module.html -docs\apidocs\pygccxml.declarations.algorithms_cache-pysrc.html -docs\apidocs\pygccxml.declarations.algorithms_cache.declaration_algs_cache_t-class.html -docs\apidocs\pygccxml.declarations.algorithms_cache.type_algs_cache_t-class.html -docs\apidocs\pygccxml.declarations.calldef-module.html -docs\apidocs\pygccxml.declarations.calldef-pysrc.html -docs\apidocs\pygccxml.declarations.calldef.argument_t-class.html -docs\apidocs\pygccxml.declarations.calldef.calldef_t-class.html -docs\apidocs\pygccxml.declarations.calldef.casting_operator_t-class.html -docs\apidocs\pygccxml.declarations.calldef.constructor_t-class.html -docs\apidocs\pygccxml.declarations.calldef.destructor_t-class.html -docs\apidocs\pygccxml.declarations.calldef.free_calldef_t-class.html -docs\apidocs\pygccxml.declarations.calldef.free_function_t-class.html -docs\apidocs\pygccxml.declarations.calldef.free_operator_t-class.html -docs\apidocs\pygccxml.declarations.calldef.member_calldef_t-class.html -docs\apidocs\pygccxml.declarations.calldef.member_function_t-class.html -docs\apidocs\pygccxml.declarations.calldef.member_operator_t-class.html -docs\apidocs\pygccxml.declarations.calldef.operator_t-class.html -docs\apidocs\pygccxml.declarations.calldef.VIRTUALITY_TYPES-class.html -docs\apidocs\pygccxml.declarations.call_invocation-module.html -docs\apidocs\pygccxml.declarations.call_invocation-pysrc.html -docs\apidocs\pygccxml.declarations.class_declaration-module.html -docs\apidocs\pygccxml.declarations.class_declaration-pysrc.html -docs\apidocs\pygccxml.declarations.class_declaration.ACCESS_TYPES-class.html -docs\apidocs\pygccxml.declarations.class_declaration.class_declaration_t-class.html -docs\apidocs\pygccxml.declarations.class_declaration.class_t-class.html -docs\apidocs\pygccxml.declarations.class_declaration.CLASS_TYPES-class.html -docs\apidocs\pygccxml.declarations.class_declaration.hierarchy_info_t-class.html -docs\apidocs\pygccxml.declarations.compilers-module.html -docs\apidocs\pygccxml.declarations.compilers-pysrc.html -docs\apidocs\pygccxml.declarations.container_traits-module.html -docs\apidocs\pygccxml.declarations.container_traits-pysrc.html -docs\apidocs\pygccxml.declarations.container_traits.container_traits_impl_t-class.html -docs\apidocs\pygccxml.declarations.container_traits.defaults_eraser-class.html -docs\apidocs\pygccxml.declarations.container_traits.defaults_eraser.recursive_impl-class.html -docs\apidocs\pygccxml.declarations.cpptypes-module.html -docs\apidocs\pygccxml.declarations.cpptypes-pysrc.html -docs\apidocs\pygccxml.declarations.cpptypes.array_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.bool_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.calldef_type_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.char_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.complex_double_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.complex_float_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.complex_long_double_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.compound_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.const_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.declarated_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.double_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.dummy_type_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.ellipsis_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.float_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.free_function_type_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.fundamental_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.int_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.java_fundamental_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.jboolean_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.jbyte_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.jchar_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.jdouble_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.jfloat_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.jint_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.jlong_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.jshort_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.long_double_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.long_int_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.long_long_int_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.long_long_unsigned_int_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.long_unsigned_int_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.member_function_type_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.member_variable_type_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.pointer_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.reference_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.restrict_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.short_int_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.short_unsigned_int_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.signed_char_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.type_qualifiers_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.type_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.unknown_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.unsigned_char_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.unsigned_int_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.void_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.volatile_t-class.html -docs\apidocs\pygccxml.declarations.cpptypes.wchar_t-class.html -docs\apidocs\pygccxml.declarations.declaration-module.html -docs\apidocs\pygccxml.declarations.declaration-pysrc.html -docs\apidocs\pygccxml.declarations.declaration.declaration_t-class.html -docs\apidocs\pygccxml.declarations.declaration.location_t-class.html -docs\apidocs\pygccxml.declarations.decl_factory-module.html -docs\apidocs\pygccxml.declarations.decl_factory-pysrc.html -docs\apidocs\pygccxml.declarations.decl_factory.decl_factory_t-class.html -docs\apidocs\pygccxml.declarations.decl_printer-module.html -docs\apidocs\pygccxml.declarations.decl_printer-pysrc.html -docs\apidocs\pygccxml.declarations.decl_printer.decl_printer_t-class.html -docs\apidocs\pygccxml.declarations.decl_visitor-module.html -docs\apidocs\pygccxml.declarations.decl_visitor-pysrc.html -docs\apidocs\pygccxml.declarations.decl_visitor.decl_visitor_t-class.html -docs\apidocs\pygccxml.declarations.dependencies-module.html -docs\apidocs\pygccxml.declarations.dependencies-pysrc.html -docs\apidocs\pygccxml.declarations.dependencies.dependency_info_t-class.html -docs\apidocs\pygccxml.declarations.enumeration-module.html -docs\apidocs\pygccxml.declarations.enumeration-pysrc.html -docs\apidocs\pygccxml.declarations.enumeration.enumeration_t-class.html -docs\apidocs\pygccxml.declarations.filtering'-module.html -docs\apidocs\pygccxml.declarations.filtering'-pysrc.html -docs\apidocs\pygccxml.declarations.filtering'.filtering-class.html -docs\apidocs\pygccxml.declarations.function_traits-module.html -docs\apidocs\pygccxml.declarations.function_traits-pysrc.html -docs\apidocs\pygccxml.declarations.matcher'-module.html -docs\apidocs\pygccxml.declarations.matcher'-pysrc.html -docs\apidocs\pygccxml.declarations.matcher'.matcher-class.html -docs\apidocs\pygccxml.declarations.matcher.declaration_not_found_t-class.html -docs\apidocs\pygccxml.declarations.matcher.multiple_declarations_found_t-class.html -docs\apidocs\pygccxml.declarations.matchers-module.html -docs\apidocs\pygccxml.declarations.matchers-pysrc.html -docs\apidocs\pygccxml.declarations.matchers.access_type_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.and_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.calldef_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.custom_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.declaration_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.matcher_base_t-class.html -docs\apidocs\pygccxml.declarations.matchers.namespace_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.not_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.operator_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.or_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.regex_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.variable_matcher_t-class.html -docs\apidocs\pygccxml.declarations.matchers.virtuality_type_matcher_t-class.html -docs\apidocs\pygccxml.declarations.mdecl_wrapper-module.html -docs\apidocs\pygccxml.declarations.mdecl_wrapper-pysrc.html -docs\apidocs\pygccxml.declarations.mdecl_wrapper.call_redirector_t-class.html -docs\apidocs\pygccxml.declarations.mdecl_wrapper.mdecl_wrapper_t-class.html -docs\apidocs\pygccxml.declarations.namespace-module.html -docs\apidocs\pygccxml.declarations.namespace-pysrc.html -docs\apidocs\pygccxml.declarations.namespace.namespace_t-class.html -docs\apidocs\pygccxml.declarations.pattern_parser-module.html -docs\apidocs\pygccxml.declarations.pattern_parser-pysrc.html -docs\apidocs\pygccxml.declarations.pattern_parser.parser_t-class.html -docs\apidocs\pygccxml.declarations.scopedef-module.html -docs\apidocs\pygccxml.declarations.scopedef-pysrc.html -docs\apidocs\pygccxml.declarations.scopedef.scopedef_t-class.html -docs\apidocs\pygccxml.declarations.templates-module.html -docs\apidocs\pygccxml.declarations.templates-pysrc.html -docs\apidocs\pygccxml.declarations.typedef-module.html -docs\apidocs\pygccxml.declarations.typedef-pysrc.html -docs\apidocs\pygccxml.declarations.typedef.typedef_t-class.html -docs\apidocs\pygccxml.declarations.type_traits-module.html -docs\apidocs\pygccxml.declarations.type_traits-pysrc.html -docs\apidocs\pygccxml.declarations.type_traits.auto_ptr_traits-class.html -docs\apidocs\pygccxml.declarations.type_traits.declaration_xxx_traits-class.html -docs\apidocs\pygccxml.declarations.type_traits.impl_details-class.html -docs\apidocs\pygccxml.declarations.type_traits.smart_pointer_traits-class.html -docs\apidocs\pygccxml.declarations.type_visitor-module.html -docs\apidocs\pygccxml.declarations.type_visitor-pysrc.html -docs\apidocs\pygccxml.declarations.type_visitor.type_visitor_t-class.html -docs\apidocs\pygccxml.declarations.variable-module.html -docs\apidocs\pygccxml.declarations.variable-pysrc.html -docs\apidocs\pygccxml.declarations.variable.variable_t-class.html -docs\apidocs\pygccxml.msvc-module.html -docs\apidocs\pygccxml.msvc-pysrc.html -docs\apidocs\pygccxml.msvc.bsc-module.html -docs\apidocs\pygccxml.msvc.bsc-pysrc.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper-module.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper-pysrc.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper.Bsc-class.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper.BSC_STAT-class.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper.enums-class.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper.enums.ATTRIBUTES-class.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper.enums.MBF-class.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper.enums.TYPES-class.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper.IinstInfo-class.html -docs\apidocs\pygccxml.msvc.bsc.c_wrapper.NiQ-class.html -docs\apidocs\pygccxml.msvc.bsc.definition_t-class.html -docs\apidocs\pygccxml.msvc.bsc.instance_t-class.html -docs\apidocs\pygccxml.msvc.bsc.module_t-class.html -docs\apidocs\pygccxml.msvc.bsc.reader_t-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details-module.html -docs\apidocs\pygccxml.msvc.bsc_impl_details-pysrc.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.Bsc-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.bsc_reader_t-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.BSC_STAT-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.definition_t-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.enums-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.enums.ATTRIBUTES-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.enums.MBF-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.enums.TYPES-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.IinstInfo-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.instance_t-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.module_t-class.html -docs\apidocs\pygccxml.msvc.bsc_impl_details.NiQ-class.html -docs\apidocs\pygccxml.msvc.common_utils-module.html -docs\apidocs\pygccxml.msvc.common_utils-pysrc.html -docs\apidocs\pygccxml.msvc.common_utils.UNDECORATE_NAME_OPTIONS-class.html -docs\apidocs\pygccxml.msvc.config-module.html -docs\apidocs\pygccxml.msvc.config-pysrc.html -docs\apidocs\pygccxml.msvc.config.binaries_searcher_t-class.html -docs\apidocs\pygccxml.msvc.pdb-module.html -docs\apidocs\pygccxml.msvc.pdb-pysrc.html -docs\apidocs\pygccxml.msvc.pdb.enums-module.html -docs\apidocs\pygccxml.msvc.pdb.enums-pysrc.html -docs\apidocs\pygccxml.msvc.pdb.enums.BasicType-class.html -docs\apidocs\pygccxml.msvc.pdb.enums.CV_access_e-class.html -docs\apidocs\pygccxml.msvc.pdb.enums.DataKind-class.html -docs\apidocs\pygccxml.msvc.pdb.enums.NameSearchOptions-class.html -docs\apidocs\pygccxml.msvc.pdb.enums.UdtKind-class.html -docs\apidocs\pygccxml.msvc.pdb.impl_details-module.html -docs\apidocs\pygccxml.msvc.pdb.impl_details-pysrc.html -docs\apidocs\pygccxml.msvc.pdb.impl_details.full_name_splitter_t-class.html -docs\apidocs\pygccxml.msvc.pdb.loader-module.html -docs\apidocs\pygccxml.msvc.pdb.loader-pysrc.html -docs\apidocs\pygccxml.msvc.pdb.loader.decl_loader_t-class.html -docs\apidocs\pygccxml.msvc.pdb.loader.decl_loader_t.parent_exists_t-class.html -docs\apidocs\pygccxml.parser-module.html -docs\apidocs\pygccxml.parser-pysrc.html -docs\apidocs\pygccxml.parser.config-module.html -docs\apidocs\pygccxml.parser.config-pysrc.html -docs\apidocs\pygccxml.parser.config.gccxml_configuration_t-class.html -docs\apidocs\pygccxml.parser.config.parser_configuration_t-class.html -docs\apidocs\pygccxml.parser.declarations_cache-module.html -docs\apidocs\pygccxml.parser.declarations_cache-pysrc.html -docs\apidocs\pygccxml.parser.declarations_cache.cache_base_t-class.html -docs\apidocs\pygccxml.parser.declarations_cache.dummy_cache_t-class.html -docs\apidocs\pygccxml.parser.declarations_cache.file_cache_t-class.html -docs\apidocs\pygccxml.parser.declarations_cache.record_t-class.html -docs\apidocs\pygccxml.parser.directory_cache-module.html -docs\apidocs\pygccxml.parser.directory_cache-pysrc.html -docs\apidocs\pygccxml.parser.directory_cache.directory_cache_t-class.html -docs\apidocs\pygccxml.parser.directory_cache.filename_entry_t-class.html -docs\apidocs\pygccxml.parser.directory_cache.filename_repository_t-class.html -docs\apidocs\pygccxml.parser.directory_cache.index_entry_t-class.html -docs\apidocs\pygccxml.parser.etree_scanner-module.html -docs\apidocs\pygccxml.parser.etree_scanner-pysrc.html -docs\apidocs\pygccxml.parser.etree_scanner.etree_saxifier_t-class.html -docs\apidocs\pygccxml.parser.etree_scanner.ietree_scanner_t-class.html -docs\apidocs\pygccxml.parser.linker-module.html -docs\apidocs\pygccxml.parser.linker-pysrc.html -docs\apidocs\pygccxml.parser.linker.linker_t-class.html -docs\apidocs\pygccxml.parser.patcher-module.html -docs\apidocs\pygccxml.parser.patcher-pysrc.html -docs\apidocs\pygccxml.parser.patcher.casting_operator_patcher_t-class.html -docs\apidocs\pygccxml.parser.patcher.default_argument_patcher_t-class.html -docs\apidocs\pygccxml.parser.project_reader-module.html -docs\apidocs\pygccxml.parser.project_reader-pysrc.html -docs\apidocs\pygccxml.parser.project_reader.COMPILATION_MODE-class.html -docs\apidocs\pygccxml.parser.project_reader.file_configuration_t-class.html -docs\apidocs\pygccxml.parser.project_reader.file_configuration_t.CONTENT_TYPE-class.html -docs\apidocs\pygccxml.parser.project_reader.project_reader_t-class.html -docs\apidocs\pygccxml.parser.scanner-module.html -docs\apidocs\pygccxml.parser.scanner-pysrc.html -docs\apidocs\pygccxml.parser.scanner.scanner_t-class.html -docs\apidocs\pygccxml.parser.source_reader-module.html -docs\apidocs\pygccxml.parser.source_reader-pysrc.html -docs\apidocs\pygccxml.parser.source_reader.gccxml_runtime_error_t-class.html -docs\apidocs\pygccxml.parser.source_reader.source_reader_t-class.html -docs\apidocs\pygccxml.utils-module.html -docs\apidocs\pygccxml.utils-pysrc.html -docs\apidocs\pygccxml.utils.cached-class.html -docs\apidocs\pygccxml.utils.enum-class.html -docs\apidocs\pygccxml.utils.fs_utils-module.html -docs\apidocs\pygccxml.utils.fs_utils-pysrc.html -docs\apidocs\pygccxml.utils.fs_utils.base_files_iterator-class.html -docs\apidocs\pygccxml.utils.fs_utils.directories_walker-class.html -docs\apidocs\pygccxml.utils.fs_utils.files_walker-class.html -docs\apidocs\pygccxml.utils.loggers-class.html -docs\apidocs\redirect.html -docs\example\example.hpp -docs\example\example.hpp.rest -docs\example\example.hpp.xml -docs\example\example.hpp.xml.rest -docs\example\example.py -docs\example\example.py.rest -docs\example\example.rest -docs\example\output.txt -docs\example\output.txt.rest -docs\history\history.rest -docs\msvc\msvc.rest -gccxml-0.9-upgrade\const_variables.7.xml -gccxml-0.9-upgrade\const_variables.9.xml -gccxml-0.9-upgrade\const_variables.h -gccxml-0.9-upgrade\const_variables.h.diff -gccxml-0.9-upgrade\default_args.7.xml -gccxml-0.9-upgrade\default_args.9.xml -gccxml-0.9-upgrade\default_args.h -gccxml-0.9-upgrade\default_args.h.diff -gccxml-0.9-upgrade\demangled.7.xml -gccxml-0.9-upgrade\demangled.9.xml -gccxml-0.9-upgrade\demangled.h -gccxml-0.9-upgrade\demangled.h.diff -gccxml-0.9-upgrade\offset.7.xml -gccxml-0.9-upgrade\offset.9.xml -gccxml-0.9-upgrade\offset.h -gccxml-0.9-upgrade\offset.h.diff -gccxml-0.9-upgrade\union_and_struct.7.xml -gccxml-0.9-upgrade\union_and_struct.9.xml -gccxml-0.9-upgrade\union_and_struct.h -gccxml-0.9-upgrade\union_and_struct.h.diff -pygccxml\__init__.py -pygccxml\__init__.pyc -pygccxml\declarations\algorithm.py -pygccxml\declarations\algorithm.pyc -pygccxml\declarations\algorithms_cache.py -pygccxml\declarations\algorithms_cache.pyc -pygccxml\declarations\calldef.py -pygccxml\declarations\calldef.pyc -pygccxml\declarations\call_invocation.py -pygccxml\declarations\call_invocation.pyc -pygccxml\declarations\class_declaration.py -pygccxml\declarations\class_declaration.pyc -pygccxml\declarations\compilers.py -pygccxml\declarations\compilers.pyc -pygccxml\declarations\container_traits.py -pygccxml\declarations\container_traits.pyc -pygccxml\declarations\cpptypes.py -pygccxml\declarations\cpptypes.pyc -pygccxml\declarations\declaration.py -pygccxml\declarations\declaration.pyc -pygccxml\declarations\decl_factory.py -pygccxml\declarations\decl_factory.pyc -pygccxml\declarations\decl_printer.py -pygccxml\declarations\decl_printer.pyc -pygccxml\declarations\decl_visitor.py -pygccxml\declarations\decl_visitor.pyc -pygccxml\declarations\dependencies.py -pygccxml\declarations\dependencies.pyc -pygccxml\declarations\enumeration.py -pygccxml\declarations\enumeration.pyc -pygccxml\declarations\filtering.py -pygccxml\declarations\filtering.pyc -pygccxml\declarations\function_traits.py -pygccxml\declarations\function_traits.pyc -pygccxml\declarations\matcher.py -pygccxml\declarations\matcher.pyc -pygccxml\declarations\matchers.py -pygccxml\declarations\matchers.pyc -pygccxml\declarations\mdecl_wrapper.py -pygccxml\declarations\mdecl_wrapper.pyc -pygccxml\declarations\namespace.py -pygccxml\declarations\namespace.pyc -pygccxml\declarations\pattern_parser.py -pygccxml\declarations\pattern_parser.pyc -pygccxml\declarations\scopedef.py -pygccxml\declarations\scopedef.pyc -pygccxml\declarations\templates.py -pygccxml\declarations\templates.pyc -pygccxml\declarations\typedef.py -pygccxml\declarations\typedef.pyc -pygccxml\declarations\type_traits.py -pygccxml\declarations\type_traits.pyc -pygccxml\declarations\type_visitor.py -pygccxml\declarations\type_visitor.pyc -pygccxml\declarations\variable.py -pygccxml\declarations\variable.pyc -pygccxml\declarations\__init__.py -pygccxml\declarations\__init__.pyc -pygccxml\msvc\bsc_impl_details.py -pygccxml\msvc\bsc_impl_details.pyc -pygccxml\msvc\common_utils.py -pygccxml\msvc\common_utils.pyc -pygccxml\msvc\config.py -pygccxml\msvc\config.pyc -pygccxml\msvc\__init__.py -pygccxml\msvc\__init__.pyc -pygccxml\msvc\bsc\c_wrapper.py -pygccxml\msvc\bsc\c_wrapper.pyc -pygccxml\msvc\bsc\__init__.py -pygccxml\msvc\bsc\__init__.pyc -pygccxml\msvc\pdb\enums.py -pygccxml\msvc\pdb\enums.pyc -pygccxml\msvc\pdb\impl_details.py -pygccxml\msvc\pdb\impl_details.pyc -pygccxml\msvc\pdb\kb.txt -pygccxml\msvc\pdb\loader.py -pygccxml\msvc\pdb\loader.pyc -pygccxml\msvc\pdb\__init__.py -pygccxml\msvc\pdb\__init__.pyc -pygccxml\parser\config.py -pygccxml\parser\config.pyc -pygccxml\parser\declarations_cache.py -pygccxml\parser\declarations_cache.pyc -pygccxml\parser\directory_cache.py -pygccxml\parser\directory_cache.pyc -pygccxml\parser\etree_scanner.py -pygccxml\parser\etree_scanner.pyc -pygccxml\parser\linker.py -pygccxml\parser\linker.pyc -pygccxml\parser\patcher.py -pygccxml\parser\patcher.pyc -pygccxml\parser\project_reader.py -pygccxml\parser\project_reader.pyc -pygccxml\parser\scanner.py -pygccxml\parser\scanner.pyc -pygccxml\parser\source_reader.py -pygccxml\parser\source_reader.pyc -pygccxml\parser\__init__.py -pygccxml\parser\__init__.pyc -pygccxml\utils\fs_utils.py -pygccxml\utils\fs_utils.pyc -pygccxml\utils\__init__.py -pygccxml\utils\__init__.pyc -unittests\algorithms_cache_tester.py -unittests\attributes_tester.py -unittests\autoconfig.py -unittests\better_templates_matcher_tester.py -unittests\bit_fields_tester.py -unittests\bsc_tester.py -unittests\cached_source_file_tester.py -unittests\cache_enums_tester.py -unittests\calldef_matcher_tester.py -unittests\call_invocation_tester.py -unittests\complex_types_tester.py -unittests\copy_constructor_tester.py -unittests\core_tester.py -unittests\declarations_cache_tester.py -unittests\declarations_comparison_tester.py -unittests\declarations_tester.py -unittests\declaration_files_tester.py -unittests\decl_printer_tester.py -unittests\decl_string_tester.py -unittests\demangled_tester.py -unittests\dependencies_tester.py -unittests\file_cache_tester.py -unittests\filtering_tester.py -unittests\filters_tester.py -unittests\find_container_traits_tester.py -unittests\free_operators_tester.py -unittests\function_traits_tester.py -unittests\gccxml_runner_tester.py -unittests\has_binary_operator_traits_tester.py -unittests\hierarchy_traveling.py -unittests\namespace_matcher_tester.py -unittests\parser_test_case.py -unittests\patcher_tester.py -unittests\pdb_tester.py -unittests\plain_c_tester.py -unittests\profile_parser.py -unittests\project_reader_correctness_tester.py -unittests\remove_template_defaults_tester.py -unittests\results.txt -unittests\source_reader_tester.py -unittests\start_with_declarations_tester.py -unittests\string_traits_tester.py -unittests\templates_tester.py -unittests\test_all.py -unittests\test_performance.py -unittests\text_reader_tester.py -unittests\timeit_test_parser.py -unittests\typedefs_tester.py -unittests\type_as_exception_bug_tester.py -unittests\type_traits_tester.py -unittests\unnamed_classes_tester.py -unittests\unnamed_enums_bug_tester.py -unittests\variable_matcher_tester.py -unittests\vector_traits_tester.py -unittests\xmlfile_reader_tester.py -unittests\data\abstract_classes.hpp -unittests\data\attributes.hpp -unittests\data\better_templates_matcher_tester.hpp -unittests\data\big.xml.bz2 -unittests\data\big2-new.xml -unittests\data\big2.xml -unittests\data\big2.xml.bz2 -unittests\data\bit_fields.hpp -unittests\data\complex_types.hpp -unittests\data\core_cache.hpp -unittests\data\core_class_hierarchy.hpp -unittests\data\core_class_hierarchy.hpp.xml -unittests\data\core_diamand_hierarchy_base.hpp -unittests\data\core_diamand_hierarchy_derived1.hpp -unittests\data\core_diamand_hierarchy_derived2.hpp -unittests\data\core_diamand_hierarchy_final_derived.hpp -unittests\data\core_membership.hpp -unittests\data\core_ns_join_1.hpp -unittests\data\core_ns_join_2.hpp -unittests\data\core_ns_join_3.hpp -unittests\data\core_overloads_1.hpp -unittests\data\core_overloads_2.hpp -unittests\data\core_types.hpp -unittests\data\covariant_returns.hpp -unittests\data\declarations_calldef.hpp -unittests\data\declarations_comparison.hpp -unittests\data\declarations_enums.hpp -unittests\data\declarations_for_filtering.hpp -unittests\data\declarations_variables.hpp -unittests\data\decl_cache_file1.txt -unittests\data\decl_cache_file1_duplicate.txt -unittests\data\decl_cache_file2.txt -unittests\data\demangled.hpp -unittests\data\demangled_tester_64bit.xml -unittests\data\free_operators.hpp -unittests\data\has_public_binary_operator_traits.hpp -unittests\data\include_all.hpp -unittests\data\include_std.hpp -unittests\data\indexing_suites2.hpp -unittests\data\noncopyable.hpp -unittests\data\ogre.1.7.xml -unittests\data\ogre.1.7.xml.bz2 -unittests\data\ogre1.4.xml -unittests\data\patcher.hpp -unittests\data\patcher_tester_64bit.xml -unittests\data\plain_c.c -unittests\data\pygccxml.cache -unittests\data\remove_template_defaults.hpp -unittests\data\string_traits.hpp -unittests\data\typedefs1.hpp -unittests\data\typedefs2.hpp -unittests\data\typedefs_base.hpp -unittests\data\type_as_exception_bug.h -unittests\data\type_traits.hpp -unittests\data\unnamed_classes.hpp -unittests\data\unnamed_enums_bug1.hpp -unittests\data\unnamed_enums_bug2.hpp -unittests\data\unnamed_ns_bug.hpp -unittests\data\vector_traits.hpp -unittests\data\xxx.bsc -unittests\data\xxx.bsc.bz2 -unittests\data\xxx.pdb.bz2 -unittests\data\msvc_build\all.cpp -unittests\data\msvc_build\msvc_build.sln -unittests\data\msvc_build\msvc_build.vcproj diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/PKG-INFO b/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/PKG-INFO deleted file mode 100644 index d0c83ea4550338c81b5e1324e4a0a5e6c6a8dd0a..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/PKG-INFO +++ /dev/null @@ -1,10 +0,0 @@ -Metadata-Version: 1.0 -Name: pygccxml -Version: 1.0.0 -Summary: GCC-XML generated file reader -Home-page: http://www.language-binding.net/pygccxml/pygccxml.html -Author: Roman Yakovenko -Author-email: roman.yakovenko@gmail.com -License: UNKNOWN -Description: UNKNOWN -Platform: UNKNOWN diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/README.txt b/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/README.txt deleted file mode 100644 index 74031ee3d0e14486137db953fb3cf92346ff7554..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/README.txt +++ /dev/null @@ -1,39 +0,0 @@ -pygccxml - Reading GCCXML output -================================ - -pygccxml is a specialized XML reader that reads the output from GCCXML. - -Homepage: http://www.language-binding.net/pygccxml/pygccxml.html - - -Install -------- - -The package uses the Python distutils so you can do the usual procedure: - - python setup.py install - -For more information about using the distutils see the Python manual -"Installing Python Modules". - - -Documentation -------------- - -For examples and tutorials see the pygccxml web site. An API reference -is available in the directory docs/apidocs in the source archive. - -If you obtained the source code from the subversion repository you -have to build the API reference yourself. This can be done using the -setup script: - - python setup.py doc - -In order for this to work you need epydoc (http://epydoc.sourceforge.net). - - --------------------------------------------------------------------------- -Copyright 2004-2008 Roman Yakovenko. -Distributed under the Boost Software License, Version 1.0. (See -accompanying file LICENSE_1_0.txt or copy at -http://www.boost.org/LICENSE_1_0.txt) diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/announcement.txt b/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/announcement.txt deleted file mode 100644 index 7fa14fdad6a3c53b6d983ba462ca6c61099909da..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/announcement.txt +++ /dev/null @@ -1,43 +0,0 @@ -Hello! - -I'm pleased to announce the 1.0 release of pygccxml. - -What is pygccxml? -================= - -"...The purpose of the GCC-XML extension is to generate an XML description of a -C++ program from GCC's internal representation. " - --- Introduction to GCC-XML - -The purpose of pygccxml is to read a generated file and provide a simple -framework to navigate C++ declarations, using Python classes. - -Where is pygccxml? -================== - -Site: http://language-binding.net/pygccxml/pygccxml.html - -Download: http://language-binding.net/pygccxml/download.html - -What's new? -=========== - -Features ---------- - -* Support for ellipsis was added. - -* New experimental back-end, based on ``.pdb`` (progam database file), was added. - -* New high-level API wrapper for ``.bsc`` (browse source code file) was added. - - -Bug fixes ---------- - -* Search algorithm, for template instantiated classes, was improved. - - -For a more complete list, please see the news: -http://language-binding.net/pygccxml/history/history.html diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/bsc_impl_details.py b/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/bsc_impl_details.py deleted file mode 100644 index a92779da4bb58716f1cdecdb8a967de231d17eae..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/pygccxml/msvc/bsc_impl_details.py +++ /dev/null @@ -1,568 +0,0 @@ -import os -import sys -import ctypes -import logging -import msvc_details -from ctypes import * -from ctypes.wintypes import ULONG -from ctypes.wintypes import DWORD -from ctypes.wintypes import BOOL -from ctypes.wintypes import BYTE -from ctypes.wintypes import WORD -from ctypes.wintypes import UINT - -sys.path.append( r'../..' ) - -from pygccxml import utils -from pygccxml import declarations - - -STRING = c_char_p -_libraries = {} -_libraries['msvcr70.dll'] = CDLL(msvc_details.msvcr_path, mode=RTLD_GLOBAL) -_libraries['msbsc70.dll'] = CDLL(msvc_details.msbsc_path, mode=RTLD_GLOBAL) - - -qyMac = 9 -refreshAllOp = 4 -qyDervOf = 7 -delOp = 1 -qyImpMembers = 8 -changeOp = 2 -qyRefs = 4 -qyCalls = 2 -changeIinstOp = 3 -qyContains = 1 -qyCalledBy = 3 -noOp = 5 -qyBaseOf = 6 -qyNil = 0 -addOp = 0 -qyDefs = 5 -PULONG = POINTER(ULONG) -USHORT = c_ushort -PUSHORT = POINTER(USHORT) -UCHAR = c_ubyte -PUCHAR = POINTER(UCHAR) -PSZ = STRING -FLOAT = c_float -PFLOAT = POINTER(FLOAT) -PBOOL = POINTER(BOOL) -LPBOOL = POINTER(BOOL) -PBYTE = POINTER(BYTE) -LPBYTE = POINTER(BYTE) -PINT = POINTER(c_int) -LPINT = POINTER(c_int) -PWORD = POINTER(WORD) -LPWORD = POINTER(WORD) -LPLONG = POINTER(c_long) -PDWORD = POINTER(DWORD) -LPDWORD = POINTER(DWORD) -LPVOID = c_void_p -LPCVOID = c_void_p -INT = c_int -PUINT = POINTER(c_uint) -ULONG_PTR = POINTER(ULONG) -NI = ULONG -IINST = ULONG -IREF = ULONG -IDEF = ULONG -IMOD = USHORT -LINE = USHORT -TYP = BYTE -ATR = USHORT -ATR32 = ULONG -MBF = ULONG -SZ = STRING -SZ_CONST = STRING - -class Bsc(Structure): - pass - -# values for enumeration 'OPERATION' -OPERATION = c_int # enum -class IinstInfo(Structure): - pass -IinstInfo._fields_ = [ - ('m_iinst', IINST), - ('m_szName', SZ_CONST), - ('m_ni', NI), -] -class BSC_STAT(Structure): - pass -BSC_STAT._fields_ = [ - ('cDef', ULONG), - ('cRef', ULONG), - ('cInst', ULONG), - ('cMod', ULONG), - ('cUseLink', ULONG), - ('cBaseLink', ULONG), -] -class NiQ(Structure): - pass -NiQ._fields_ = [ - ('m_iinstOld', IINST), - ('m_iInfoNew', IinstInfo), - ('m_op', OPERATION), - ('m_typ', TYP), -] -pfnNotifyChange = CFUNCTYPE(BOOL, POINTER(NiQ), ULONG, ULONG_PTR) - -# values for enumeration '_qy_' -_qy_ = c_int # enum -QY = _qy_ -Bsc._fields_ = [ -] -BSCOpen = _libraries['msbsc70.dll'].BSCOpen -BSCOpen.restype = BOOL -BSCOpen.argtypes = [SZ_CONST, POINTER(POINTER(Bsc))] -BSCClose = _libraries['msbsc70.dll'].BSCClose -BSCClose.restype = BOOL -BSCClose.argtypes = [POINTER(Bsc)] -BSCIinstInfo = _libraries['msbsc70.dll'].BSCIinstInfo -BSCIinstInfo.restype = BOOL -BSCIinstInfo.argtypes = [POINTER(Bsc), IINST, POINTER(SZ), POINTER(TYP), POINTER(ATR)] -BSCIrefInfo = _libraries['msbsc70.dll'].BSCIrefInfo -BSCIrefInfo.restype = BOOL -BSCIrefInfo.argtypes = [POINTER(Bsc), IREF, POINTER(SZ), POINTER(LINE)] -BSCIdefInfo = _libraries['msbsc70.dll'].BSCIdefInfo -BSCIdefInfo.restype = BOOL -BSCIdefInfo.argtypes = [POINTER(Bsc), IDEF, POINTER(SZ), POINTER(LINE)] -BSCImodInfo = _libraries['msbsc70.dll'].BSCImodInfo -BSCImodInfo.restype = BOOL -BSCImodInfo.argtypes = [POINTER(Bsc), IMOD, POINTER(SZ)] -BSCSzFrTyp = _libraries['msbsc70.dll'].BSCSzFrTyp -BSCSzFrTyp.restype = SZ -BSCSzFrTyp.argtypes = [POINTER(Bsc), TYP] -BSCSzFrAtr = _libraries['msbsc70.dll'].BSCSzFrAtr -BSCSzFrAtr.restype = SZ -BSCSzFrAtr.argtypes = [POINTER(Bsc), ATR] -BSCGetIinstByvalue = _libraries['msbsc70.dll'].BSCGetIinstByvalue -BSCGetIinstByvalue.restype = BOOL -BSCGetIinstByvalue.argtypes = [POINTER(Bsc), SZ, TYP, ATR, POINTER(IINST)] -BSCGetOverloadArray = _libraries['msbsc70.dll'].BSCGetOverloadArray -BSCGetOverloadArray.restype = BOOL -BSCGetOverloadArray.argtypes = [POINTER(Bsc), SZ, MBF, POINTER(POINTER(IINST)), POINTER(ULONG)] -BSCGetUsedByArray = _libraries['msbsc70.dll'].BSCGetUsedByArray -BSCGetUsedByArray.restype = BOOL -BSCGetUsedByArray.argtypes = [POINTER(Bsc), IINST, MBF, POINTER(POINTER(IINST)), POINTER(ULONG)] -BSCGetUsesArray = _libraries['msbsc70.dll'].BSCGetUsesArray -BSCGetUsesArray.restype = BOOL -BSCGetUsesArray.argtypes = [POINTER(Bsc), IINST, MBF, POINTER(POINTER(IINST)), POINTER(ULONG)] -BSCGetBaseArray = _libraries['msbsc70.dll'].BSCGetBaseArray -BSCGetBaseArray.restype = BOOL -BSCGetBaseArray.argtypes = [POINTER(Bsc), IINST, POINTER(POINTER(IINST)), POINTER(ULONG)] -BSCGetDervArray = _libraries['msbsc70.dll'].BSCGetDervArray -BSCGetDervArray.restype = BOOL -BSCGetDervArray.argtypes = [POINTER(Bsc), IINST, POINTER(POINTER(IINST)), POINTER(ULONG)] -BSCGetMembersArray = _libraries['msbsc70.dll'].BSCGetMembersArray -BSCGetMembersArray.restype = BOOL -BSCGetMembersArray.argtypes = [POINTER(Bsc), IINST, MBF, POINTER(POINTER(IINST)), POINTER(ULONG)] -BSCGetDefArray = _libraries['msbsc70.dll'].BSCGetDefArray -BSCGetDefArray.restype = BOOL -BSCGetDefArray.argtypes = [POINTER(Bsc), IINST, POINTER(POINTER(IREF)), POINTER(ULONG)] -BSCGetRefArray = _libraries['msbsc70.dll'].BSCGetRefArray -BSCGetRefArray.restype = BOOL -BSCGetRefArray.argtypes = [POINTER(Bsc), IINST, POINTER(POINTER(IREF)), POINTER(ULONG)] -BSCGetModuleContents = _libraries['msbsc70.dll'].BSCGetModuleContents -BSCGetModuleContents.restype = BOOL -BSCGetModuleContents.argtypes = [POINTER(Bsc), IMOD, MBF, POINTER(POINTER(IINST)), POINTER(ULONG)] -BSCGetModuleByName = _libraries['msbsc70.dll'].BSCGetModuleByName -BSCGetModuleByName.restype = BOOL -BSCGetModuleByName.argtypes = [POINTER(Bsc), SZ, POINTER(IMOD)] -BSCGetAllModulesArray = _libraries['msbsc70.dll'].BSCGetAllModulesArray -BSCGetAllModulesArray.restype = BOOL -BSCGetAllModulesArray.argtypes = [POINTER(Bsc), POINTER(POINTER(IMOD)), POINTER(ULONG)] -BSCDisposeArray = _libraries['msbsc70.dll'].BSCDisposeArray -BSCDisposeArray.restype = None -BSCDisposeArray.argtypes = [POINTER(Bsc), c_void_p] -BSCFormatDname = _libraries['msbsc70.dll'].BSCFormatDname -BSCFormatDname.restype = SZ -BSCFormatDname.argtypes = [POINTER(Bsc), SZ] -BSCFInstFilter = _libraries['msbsc70.dll'].BSCFInstFilter -BSCFInstFilter.restype = BOOL -BSCFInstFilter.argtypes = [POINTER(Bsc), IINST, MBF] -BSCIinstFrIref = _libraries['msbsc70.dll'].BSCIinstFrIref -BSCIinstFrIref.restype = IINST -BSCIinstFrIref.argtypes = [POINTER(Bsc), IREF] -BSCIinstFrIdef = _libraries['msbsc70.dll'].BSCIinstFrIdef -BSCIinstFrIdef.restype = IINST -BSCIinstFrIdef.argtypes = [POINTER(Bsc), IDEF] -BSCIinstContextIref = _libraries['msbsc70.dll'].BSCIinstContextIref -BSCIinstContextIref.restype = IINST -BSCIinstContextIref.argtypes = [POINTER(Bsc), IREF] -BSCGetStatistics = _libraries['msbsc70.dll'].BSCGetStatistics -BSCGetStatistics.restype = BOOL -BSCGetStatistics.argtypes = [POINTER(Bsc), POINTER(BSC_STAT)] -BSCGetModuleStatistics = _libraries['msbsc70.dll'].BSCGetModuleStatistics -BSCGetModuleStatistics.restype = BOOL -BSCGetModuleStatistics.argtypes = [POINTER(Bsc), IMOD, POINTER(BSC_STAT)] -BSCFCaseSensitive = _libraries['msbsc70.dll'].BSCFCaseSensitive -BSCFCaseSensitive.restype = BOOL -BSCFCaseSensitive.argtypes = [POINTER(Bsc)] -BSCSetCaseSensitivity = _libraries['msbsc70.dll'].BSCSetCaseSensitivity -BSCSetCaseSensitivity.restype = BOOL -BSCSetCaseSensitivity.argtypes = [POINTER(Bsc), BOOL] -BSCGetAllGlobalsArray = _libraries['msbsc70.dll'].BSCGetAllGlobalsArray -BSCGetAllGlobalsArray.restype = BOOL -BSCGetAllGlobalsArray.argtypes = [POINTER(Bsc), MBF, POINTER(POINTER(IINST)), POINTER(ULONG)] -BSCSzFrAtr2 = _libraries['msbsc70.dll'].BSCSzFrAtr2 -BSCSzFrAtr2.restype = SZ -BSCSzFrAtr2.argtypes = [POINTER(Bsc), ATR32] -BSCIinstInfo2 = _libraries['msbsc70.dll'].BSCIinstInfo2 -BSCIinstInfo2.restype = BOOL -BSCIinstInfo2.argtypes = [POINTER(Bsc), IINST, POINTER(SZ), POINTER(TYP), POINTER(ATR32)] -BSCGetIinstByvalue2 = _libraries['msbsc70.dll'].BSCGetIinstByvalue2 -BSCGetIinstByvalue2.restype = BOOL -BSCGetIinstByvalue2.argtypes = [POINTER(Bsc), SZ, TYP, ATR32, POINTER(IINST)] -OpenBSCQuery = _libraries['msbsc70.dll'].OpenBSCQuery -OpenBSCQuery.restype = BOOL -OpenBSCQuery.argtypes = [POINTER(Bsc)] -CloseBSCQuery = _libraries['msbsc70.dll'].CloseBSCQuery -CloseBSCQuery.restype = BOOL -CloseBSCQuery.argtypes = [] -BOB = ULONG -InitBSCQuery = _libraries['msbsc70.dll'].InitBSCQuery -InitBSCQuery.restype = BOOL -InitBSCQuery.argtypes = [QY, BOB] -BobNext = _libraries['msbsc70.dll'].BobNext -BobNext.restype = BOB -BobNext.argtypes = [] -BobFrName = _libraries['msbsc70.dll'].BobFrName -BobFrName.restype = BOB -BobFrName.argtypes = [SZ] -LszNameFrBob = _libraries['msbsc70.dll'].LszNameFrBob -LszNameFrBob.restype = SZ -LszNameFrBob.argtypes = [BOB] -CLS = USHORT - -class enums: - class MBF(utils.enum): - NIL = 0x000 - VARS = 0x001 - FUNCS = 0x002 - MACROS = 0x004 - TYPES = 0x008 - CLASS = 0x010 - INCL = 0x020 - MSGMAP = 0x040 - DIALOGID = 0x080 - LIBRARY = 0x100 - IMPORT = 0x200 - TEMPLATE = 0x400 - NAMESPACE = 0x800 - ALL = 0xFFF - - class TYPES(utils.enum): - FUNCTION = 0x01 - LABEL = 0x02 - PARAMETER = 0x03 - VARIABLE = 0x04 - CONSTANT = 0x05 - MACRO = 0x06 - TYPEDEF = 0x07 - STRUCNAM = 0x08 - ENUMNAM = 0x09 - ENUMMEM = 0x0A - UNIONNAM = 0x0B - SEGMENT = 0x0C - GROUP = 0x0D - PROGRAM = 0x0E - CLASSNAM = 0x0F - MEMFUNC = 0x10 - MEMVAR = 0x11 - - class ATTRIBUTES(utils.enum): - LOCAL = 0x001 - STATIC = 0x002 - SHARED = 0x004 - NEAR = 0x008 - COMMON = 0x010 - DECL_ONLY = 0x020 - PUBLIC = 0x040 - NAMED = 0x080 - MODULE = 0x100 - VIRTUAL = 0x200 - PRIVATE = 0x400 - PROTECT = 0x800 - -class definition_t(object): - #represents some other symbol - def __init__( self, def_id, bsc ): - self.__bsc = bsc - self.__def_id = def_id - - @property - def def_id(self): - return self.__def_id - - @utils.cached - def location( self ): - module = STRING() - line = LINE() - if not BSCIdefInfo( self.__bsc, self.def_id, byref( module ), byref( line ) ): - raise RuntimeError( "Unable to load information about instance(%s)" % str( self.__def_id ) ) - return (module, line) - - @utils.cached - def file_name(self): - return self.location[0].value - - @utils.cached - def line(self): - return self.location[1].value - - def __str__( self ): - return self.file_name + ': %d' % self.line + ' name: %s' % self.as_instance.name - - @utils.cached - def as_instance(self): - return self.__bsc.create_instance( BSCIinstFrIdef( self.__bsc, self.def_id) ) - -class instance_t(object): - #represents some symbol - def __init__( self, inst_id, bsc ): - self.__bsc = bsc - self.__inst_id = inst_id - - @property - def inst_id(self): - return self.__inst_id - - @utils.cached - def name_type_attribute_mangled_name( self ): - name = STRING() - typ = TYP() - attribute = ATR() - if not BSCIinstInfo( self.__bsc, self.inst_id, byref( name ), byref( typ ), byref( attribute ) ): - raise RuntimeError( "Unable to load information about instance(%s)" % str( self.__inst_id ) ) - undecorated_name = BSCFormatDname( self.__bsc, name ) - return undecorated_name, typ, attribute, name.value - - - @utils.cached - def mangled_name(self): - return self.name_type_attribute_mangled_name[3] - - @utils.cached - def name(self): - return self.name_type_attribute_mangled_name[0] - - @utils.cached - def type(self): - return self.name_type_attribute_mangled_name[1].value - - @utils.cached - def attribute(self): - return self.name_type_attribute_mangled_name[2].value - - def __str__( self ): - tmp = [] - if enums.TYPES.has_value( self.type ): - tmp.append( 'type( "%s" )' % enums.TYPES.name_of( self.type ) ) - if enums.ATTRIBUTES.has_value( self.attribute ): - tmp.append( 'attribute( "%s" )' % enums.ATTRIBUTES.name_of( self.attribute ) ) - tmp.append( 'name( "%s" )' % self.name ) - tmp.append( 'mangled name( "%s" )' % self.mangled_name ) - return ', '.join( tmp ) - - - @utils.cached - def definitions( self ): - definitions_len = ULONG(0) - definitions_ids = pointer( IDEF() ) - - if not BSCGetDefArray( self.__bsc, self.inst_id, byref( definitions_ids ), byref( definitions_len ) ): - raise RuntimeError( "Unable to call BSCGetDefArray" ) - - definitions = map( lambda i: definition_t( definitions_ids[i], self.__bsc ) - , range( definitions_len.value ) ) - - BSCDisposeArray( self.__bsc, definitions_ids ) - return definitions - - @utils.cached - def members( self ): - instances_len = ULONG(0) - instances_ids = pointer( IINST() ) - - if not BSCGetMembersArray( self.__bsc, self.inst_id, enums.MBF.ALL, byref( instances_ids ), byref( instances_len ) ): - raise RuntimeError( "Unable to call BSCGetMembersArray" ) - - instances = map( lambda i: self.__bsc.create_instance( instances_ids[i] ) - , range( instances_len.value ) ) - - BSCDisposeArray( self.__bsc, instances_ids ) - return instances - - @utils.cached - def used_symbols(self): - instances_len = ULONG(0) - instances_ids = pointer( IINST() ) - - if not BSCGetUsesArray( self.__bsc, self.inst_id, enums.MBF.ALL, byref( instances_ids ), byref( instances_len ) ): - raise RuntimeError( "Unable to call BSCGetUsesArray" ) - - instances = map( lambda i: self.__bsc.create_instance( instances_ids[i] ) - , range( instances_len.value ) ) - - BSCDisposeArray( self.__bsc, instances_ids ) - return instances - - @utils.cached - def base_classes(self): - instances_len = ULONG(0) - instances_ids = pointer( IINST() ) - - if not BSCGetBaseArray( self.__bsc, self.inst_id, byref( instances_ids ), byref( instances_len ) ): - raise RuntimeError( "Unable to call BSCGetBaseArray" ) - - instances = map( lambda i: self.__bsc.create_instance( instances_ids[i] ) - , range( instances_len.value ) ) - - BSCDisposeArray( self.__bsc, instances_ids ) - return instances - - @utils.cached - def derived_classes(self): - instances_len = ULONG(0) - instances_ids = pointer( IINST() ) - - if not BSCGetDervArray( self.__bsc, self.inst_id, byref( instances_ids ), byref( instances_len ) ): - raise RuntimeError( "Unable to call BSCGetDervArray" ) - - instances = map( lambda i: self.__bsc.create_instance( instances_ids[i] ) - , range( instances_len.value ) ) - - BSCDisposeArray( self.__bsc, instances_ids ) - return instances - -class module_t(object): - #represents file - def __init__( self, mod_id, bsc ): - self.__bsc = bsc - self.__mod_id = mod_id - - @property - def mod_id( self ): - return self.__mod_id - - @utils.cached - def path( self ): - name = STRING() - BSCImodInfo(self.__bsc, self.__mod_id, byref(name)) - return name.value - - @utils.cached - def instances( self ): - instances_len = ULONG(0) - instances_ids = pointer( IINST() ) - - if not BSCGetModuleContents( self.__bsc, self.mod_id, enums.MBF.ALL, byref( instances_ids ), byref( instances_len ) ): - raise RuntimeError( "Unable to call BSCGetModuleContents" ) - - instances = map( lambda i: self.__bsc.create_instance( instances_ids[i] ) - , range( instances_len.value ) ) - - BSCDisposeArray( self.__bsc, instances_ids ) - return instances - -class bsc_reader_t( object ): - def __init__( self, bsc_file ): - self.logger = utils.loggers.pdb_reader - self.logger.setLevel(logging.INFO) - - self.__bsc_file = bsc_file - self.__bsc = pointer( Bsc() ) - if not BSCOpen( self.__bsc_file, byref( self.__bsc ) ): - raise RuntimeError( "Unable to open bsc file '%s'" % self.__bsc_file ) - - self.__instances_cache = {} #inst id : instance_t - self.__bsc.create_instance = lambda inst_id: self.__create_instance( inst_id ) - - def __create_instance( self, inst_id ): - try: - return self.__instances_cache[ inst_id ] - except KeyError: - inst = instance_t( inst_id, self.__bsc ) - self.__instances_cache[ inst_id ] = inst - return inst - - def query_all_instances( self ): - instances_len = ULONG(0) - instances = pointer( IINST() ) - - if not BSCGetAllGlobalsArray( self.__bsc, enums.MBF.ALL, byref( instances ), byref( instances_len ) ): - raise RuntimeError( "Unable to load all globals symbols" ) - for i in range( instances_len.value ): - self.__instances.append( instances[i] ) - BSCDisposeArray( self.__bsc, instances ) - - @utils.cached - def is_case_sensitive( self ): - return bool( BSCFCaseSensitive( self.__bsc ) ) - - @utils.cached - def files(self): - module_ids = pointer( IMOD() ) - module_len = ULONG() - bs = BSC_STAT() - - if not BSCGetAllModulesArray( self.__bsc, module_ids, byref(module_len) ): - raise RuntimeError( "Unable to load all modules" ) - - modules = map( lambda i: module_t( module_ids[i], self.__bsc ) - , range( module_len.value ) ) - - BSCDisposeArray( self.__bsc, module_ids ) - - return modules - - def print_stat( self ): - stat = BSC_STAT() - BSCGetStatistics( self.__bsc, byref( stat ) ) - for f, t in stat._fields_: - print '%s: %s' % ( f, str( getattr( stat, f) ) ) - - def print_classes(self, file_name=None): - for m in self.files: - if file_name and m.path != file_name: - continue - print 'File: ', m.path - if m.instances: - print '\tInstances:' - for inst in m.instances: - print '\t\t', str(inst) - if inst.definitions: - print '\t\t\tDefinitions:' - for definition in inst.definitions: - print '\t\t\t\t', str( definition ) - if inst.members: - print '\t\t\tMembers:' - for member in inst.members: - print '\t\t\t\t', str( member ) - if inst.used_symbols: - print '\t\t\tUsed symbols:' - for used_symbol in inst.used_symbols: - print '\t\t\t\t', str( used_symbol ) - if inst.base_classes: - print '\t\t\tBase classes:' - for base_class in inst.base_classes: - print '\t\t\t\t', str( base_class ) - if inst.derived_classes: - print '\t\t\tDerived classes:' - for derived_class in inst.derived_classes: - print '\t\t\t\t', str( derived_class ) - - def __del__( self ): - if self.__bsc: - BSCClose( self.__bsc ) - -if __name__ == '__main__': - control_bsc = r'xxx.bsc' - reader = bsc_reader_t( control_bsc ) - reader.print_stat() - print 'is_case_sensitive', reader.is_case_sensitive - #~ reader.query_all_instances() - #reader.files - reader.print_classes( )#r'c:\dev\produce_pdb\produce_pdb.cpp') diff --git a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/setup.py b/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/setup.py deleted file mode 100644 index b435aa767f38493923d1cffe101955c123c32d6d..0000000000000000000000000000000000000000 --- a/Utilities/ITK/Wrapping/Generators/SwigInterface/pygccxml-1.0.0/setup.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/bin/env python -# Copyright 2004-2008 Roman Yakovenko. -# Distributed under the Boost Software License, Version 1.0. (See -# accompanying file LICENSE_1_0.txt or copy at -# http://www.boost.org/LICENSE_1_0.txt) - -import sys, os, os.path -from distutils import sysconfig -from distutils.core import setup -from distutils.cmd import Command - -def generate_doc(): - """Generate the epydoc reference manual. - """ - print "Generating epydoc files..." - - from epydoc.docbuilder import build_doc_index - from epydoc.docwriter.html import HTMLWriter - - docindex = build_doc_index(['pygccxml']) - html_writer = HTMLWriter( docindex - , prj_name='pygccxml' - , prj_url='http://www.language-binding.net' - , show_private=False - , show_frames=False) - - html_writer.write( os.path.join('docs', 'apidocs') ) - -class doc_cmd(Command): - """This is a new distutils command 'doc' to build the epydoc manual. - """ - - description = 'build the API reference using epydoc' - user_options = [('no-doc', None, "don't run epydoc")] - boolean_options = ['no-doc'] - - def initialize_options (self): - self.no_doc = 0 - - def finalize_options (self): - pass - - def run(self): - if self.no_doc: - return - generate_doc() - - -# Generate the doc when a source distribution is created -if sys.argv[-1]=="sdist": - generate_doc() - - -setup( name = "pygccxml", - version = "1.0.0", - description = "GCC-XML generated file reader", - author = "Roman Yakovenko", - author_email = "roman.yakovenko@gmail.com", - url = 'http://www.language-binding.net/pygccxml/pygccxml.html', - packages = [ 'pygccxml', - 'pygccxml.declarations', - 'pygccxml.parser', - 'pygccxml.msvc', - 'pygccxml.msvc.bsc', - 'pygccxml.msvc.pdb', - 'pygccxml.utils' ], - cmdclass = {"doc" : doc_cmd} -) diff --git a/Utilities/ITK/Wrapping/Generators/Tcl/CreateLanguageSupport.cmake b/Utilities/ITK/Wrapping/Generators/Tcl/CreateLanguageSupport.cmake index d2cf89903003f7d4d4e196ce60c2961e7ce1e25a..990af7ef69b116c9f378dfe7bc36e3074f4455f3 100644 --- a/Utilities/ITK/Wrapping/Generators/Tcl/CreateLanguageSupport.cmake +++ b/Utilities/ITK/Wrapping/Generators/Tcl/CreateLanguageSupport.cmake @@ -12,7 +12,7 @@ macro(END_WRAPPER_LIBRARY_TCL) set(modules ) - foreach(source ${WRAPPER_LIBRARY_CABLESWIG_INPUTS}) + foreach(source ${WRAPPER_LIBRARY_SWIG_INPUTS}) get_filename_component(base_name ${source} NAME_WE) string(REGEX REPLACE "^wrap_" "" group_name "${base_name}") diff --git a/Utilities/ITK/Wrapping/Generators/Tcl/TCLGetInterp.i b/Utilities/ITK/Wrapping/Generators/Tcl/TCLGetInterp.i index ad846700124863b74e19954ddce48c31bb67abe2..d1c7daaea70f3f3e1bda3e1caba2c818af6bcdc4 100644 --- a/Utilities/ITK/Wrapping/Generators/Tcl/TCLGetInterp.i +++ b/Utilities/ITK/Wrapping/Generators/Tcl/TCLGetInterp.i @@ -77,7 +77,7 @@ namespace std { %} // import fake itk command -// because itkCommand will be wrapped elsewhere by cableswig +// because itkCommand will be wrapped elsewhere by swig %import "itkCommand.i" // create an itkJavaCommand that has an Execute method that diff --git a/Utilities/ITK/Wrapping/TypedefMacros.cmake b/Utilities/ITK/Wrapping/TypedefMacros.cmake index 27b818bcf2d6cd41655dac6457c33abf59fe7f12..c844415ced6891434d178ae66856b6a7fed1e0d0 100644 --- a/Utilities/ITK/Wrapping/TypedefMacros.cmake +++ b/Utilities/ITK/Wrapping/TypedefMacros.cmake @@ -1,5 +1,5 @@ ################################################################################ -# Macro definitions for creating proper CableSwig input files from wrap_*.cmake +# Macro definitions for creating proper Swig input files from wrap_*.cmake # files. # This file includes definitions for the macros to call from a CMakeList file # to cause wrap_*.cmake files to be turned into CXX files, and definitions for @@ -69,20 +69,16 @@ macro(itk_wrap_module library_name) # not the full path or file name. set(WRAPPER_LIBRARY_GROUPS ) - # WRAPPER_LIBRARY_CABLESWIG_INPUTS. List of C++ source files to be used - # as input for CableSwig. This list is then appended to by + # WRAPPER_LIBRARY_SWIG_INPUTS. List of C++ source files to be used + # as input for Swig. This list is then appended to by # WRAPPER_LIBRARY_AUTO_INCLUDE_WRAP_FILES. A full path to each input is required. - set(WRAPPER_LIBRARY_CABLESWIG_INPUTS ) + set(WRAPPER_LIBRARY_SWIG_INPUTS ) # WRAPPER_SWIG_LIBRARY_FILES. List of swig .swg files to pass to cswig to control # type handling and so forth. A full path to each include is required. # The itk.swg file and the library file for the current library are implicitly added. set(WRAPPER_SWIG_LIBRARY_FILES ) - # WRAPPER_LIBRARY_SWIG_INPUTS. SWIG input files to be fed to swig (not - # CableSwig). A full path to each input is required. - set(WRAPPER_LIBRARY_SWIG_INPUTS ) - # WRAPPER_LIBRARY_CXX_SOURCES. C++ sources to be compiled and linked in # to the wrapper library (with no prior processing by swig, etc.) # A full path to each input is required. @@ -153,7 +149,7 @@ macro(itk_auto_load_submodules) # Include the wrap_*.cmake files in WRAPPER_LIBRARY_SOURCE_DIR. This causes # corresponding wrap_*.cxx files to be generated WRAPPER_LIBRARY_OUTPUT_DIR, - # and added to the WRAPPER_LIBRARY_CABLESWIG_INPUTS list. + # and added to the WRAPPER_LIBRARY_SWIG_INPUTS list. # In addition, this causes the other required wrap_*.cxx files for the entire # library and each wrapper language to be created. # Finally, this macro causes the language support files for the templates and @@ -284,7 +280,7 @@ macro(itk_end_wrap_submodule) # Write the file, inless the included cmake file told us not to. # A file might declare WRAPPER_DO_NOT_CREATE_CXX if that cmake file # provides a custom wrap_*.cxx file and manually appends it to the - # WRAPPER_LIBRARY_CABLESWIG_INPUTS list; thus that file would not + # WRAPPER_LIBRARY_SWIG_INPUTS list; thus that file would not # need or want any cxx file generated. # if(NOT WRAPPER_DO_NOT_CREATE_CXX) # WRITE_WRAP_CXX("wrap_${module}.cxx") @@ -405,7 +401,7 @@ macro(itk_wrap_named_class class swig_name) endmacro() macro(itk_wrap_simple_class class) - # Similar to itk_wrap_class in that it generates typedefs for CableSwig input. + # Similar to itk_wrap_class in that it generates typedefs for Swig input. # However, since no templates need to be declared, there's no need for # itk_wrap_class ... (declare templates) .. itk_end_wrap_class. Instead # itk_wrap_simple_class takes care of it all. @@ -425,7 +421,7 @@ endmacro() macro(itk_wrap_named_simple_class class swig_name) - # Similar to itk_wrap_named_class in that it generates typedefs for CableSwig input. + # Similar to itk_wrap_named_class in that it generates typedefs for Swig input. # However, since no templates need to be declared, there's no need for # itk_wrap_class ... (declare templates) .. itk_end_wrap_class. Instead # itk_wrap_named_simple_class takes care of it all. @@ -469,7 +465,7 @@ endmacro() macro(itk_end_wrap_class) # Parse through the list of WRAPPER_TEMPLATES set up by the macros at the bottom # of this file, turning them into proper C++ type definitions suitable for - # input to CableSwig. The C++ definitions are stored in WRAPPER_TYPEDEFS. + # input to Swig. The C++ definitions are stored in WRAPPER_TYPEDEFS. # # Global vars used: WRAPPER_CLASS WRAPPER_WRAP_METHOD WRAPPER_TEMPLATES WRAPPER_SWIG_NAME # Global vars modified: WRAPPER_TYPEDEFS @@ -560,7 +556,7 @@ endmacro() # Macros which cause one or more template instantiations to be added to the # WRAPPER_TEMPLATES list. This list is initialized by the macro itk_wrap_class above, # and used by the macro itk_end_wrap_class to produce the wrap_xxx.cxx files with -# the correct templates. These cxx files serve as the CableSwig inputs. +# the correct templates. These cxx files serve as the Swig inputs. ################################################################################ macro(itk_wrap_template name types) @@ -798,182 +794,3 @@ macro(itk_wrap_filter_dims var_name dimension_condition) INTERSECTION(${var_name} "${dimension_condition}" "${ITK_WRAP_DIMS}") endif() endmacro() - - -# deprecated macros -macro(WRAP_LIBRARIES) - message("Deprecation warning: WRAP_LIBRARIES is replaced by itk_wrap_modules.") - itk_wrap_modules() -endmacro() - -macro(END_WRAP_LIBRARIES) - message("Deprecation warning: END_WRAP_LIBRARIES is replaced by itk_end_wrap_modules.") - itk_end_wrap_modules() -endmacro() - -macro(WRAP_LIBRARY library_name) - message("Deprecation warning: WRAP_LIBRARY is replaced by itk_wrap_module.") - itk_wrap_module("${library_name}") -endmacro() - -macro(END_WRAP_LIBRARY ) - message("Deprecation warning: END_WRAP_LIBRARY is replaced by itk_end_wrap_module.") - itk_end_wrap_module("${library_name}") -endmacro() - -macro(AUTO_INCLUDE_MODULES) - message("Deprecation warning: AUTO_INCLUDE_MODULES is replaced by itk_auto_load_submodules.") - itk_auto_load_submodules() -endmacro() - -macro(WRAP_MODULE module) - message("Deprecation warning: WRAP_MODULE is replaced by itk_wrap_submodule.") - itk_wrap_submodule("${module}") -endmacro() - -macro(END_WRAP_MODULE) - message("Deprecation warning: END_WRAP_MODULE is replaced by itk_end_wrap_submodule.") - itk_end_wrap_submodule() -endmacro() - -macro(WRAP_CLASS class) - message("Deprecation warning: WRAP_CLASS is replaced by itk_wrap_class.") - itk_wrap_class("${class}" "${ARGN}") -endmacro() - -macro(WRAP_NAMED_CLASS class swig_name) - message("Deprecation warning: WRAP_NAMED_CLASS is replaced by itk_wrap_named_class.") - itk_wrap_named_class("${class}" "${swig_name}" "${ARGN}") -endmacro() - -macro(WRAP_NON_TEMPLATE_CLASS class) - message("Deprecation warning: WRAP_NON_TEMPLATE_CLASS is replaced by itk_wrap_simple_class.") - itk_wrap_simple_class("${class}" "${ARGN}") -endmacro() - -macro(WRAP_NAMED_NON_TEMPLATE_CLASS class swig_name) - message("Deprecation warning: WRAP_NAMED_NON_TEMPLATE_CLASS is replaced by itk_wrap_named_simple_class.") - itk_wrap_named_simple_class("${class}" "${swig_name}" "${ARGN}") -endmacro() - -macro(WRAP_INCLUDE include_file) - message("Deprecation warning: WRAP_INCLUDE is replaced by itk_wrap_include.") - itk_wrap_include("${include_file}") -endmacro() - -macro(END_WRAP_CLASS) - message("Deprecation warning: END_WRAP_CLASS is replaced by itk_end_wrap_class.") - itk_end_wrap_class() -endmacro() - -macro(ADD_ONE_TYPEDEF wrap_method wrap_class swig_name) - message("Deprecation warning: ADD_ONE_TYPEDEF is replaced by itk_wrap_one_type.") - itk_wrap_one_type("${wrap_method}" "${wrap_class}" "${swig_name}") -endmacro() - -macro(WRAP_TEMPLATE name type) - message("Deprecation warning: WRAP_TEMPLATE is replaced by itk_wrap_template.") - itk_wrap_template("${name}" "${type}") -endmacro() - -macro(WRAP_IMAGE_FILTER param_type param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER is replaced by itk_wrap_template.") - itk_wrap_image_filter("${param_type}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_ALL_TYPES param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_ALL_TYPES() is replaced by itk_wrap_template(\"\${WRAP_ITK_ALL_TYPES}\").") - itk_wrap_image_filter("${WRAP_ITK_ALL_TYPES}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_SCALAR param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_SCALAR() is replaced by itk_wrap_template(\"\${WRAP_ITK_SCALAR}\").") - itk_wrap_image_filter("${WRAP_ITK_SCALAR}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_VECTOR param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_VECTOR() is replaced by itk_wrap_template(\"\${WRAP_ITK_VECTOR}\").") - itk_wrap_image_filter("${WRAP_ITK_VECTOR}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_USIGN_INT param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_USIGN_INT() is replaced by itk_wrap_template(\"\${WRAP_ITK_USIGN_INT}\").") - itk_wrap_image_filter("${WRAP_ITK_USIGN_INT}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_SIGN_INT param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_SIGN_INT() is replaced by itk_wrap_template(\"\${WRAP_ITK_SIGN_INT}\").") - itk_wrap_image_filter("${WRAP_ITK_SIGN_INT}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_INT param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_INT() is replaced by itk_wrap_template(\"\${WRAP_ITK_INT}\").") - itk_wrap_image_filter("${WRAP_ITK_INT}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_REAL param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_REAL() is replaced by itk_wrap_template(\"\${WRAP_ITK_REAL}\").") - itk_wrap_image_filter("${WRAP_ITK_REAL}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_RGB param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_RGB() is replaced by itk_wrap_template(\"\${WRAP_ITK_RGB}\").") - itk_wrap_image_filter("${WRAP_ITK_RGB}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_RGBA param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_RGBA() is replaced by itk_wrap_template(\"\${WRAP_ITK_RGBA}\").") - itk_wrap_image_filter("${WRAP_ITK_RGBA}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_VECTOR_REAL param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_VECTOR_REAL() is replaced by itk_wrap_template(\"\${WRAP_ITK_VECTOR_REAL}\").") - itk_wrap_image_filter("${WRAP_ITK_VECTOR_REAL}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_COV_VECTOR_REAL param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_COV_VECTOR_REAL() is replaced by itk_wrap_template(\"\${WRAP_ITK_COV_VECTOR_REAL}\").") - itk_wrap_image_filter("${WRAP_ITK_COV_VECTOR_REAL}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_COMPLEX_REAL param_count) - message("Deprecation warning: WRAP_IMAGE_FILTER_COMPLEX_REAL() is replaced by itk_wrap_template(\"\${WRAP_ITK_COMPLEX_REAL}\").") - itk_wrap_image_filter("${WRAP_ITK_COMPLEX_REAL}" ${param_count} "${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_COMBINATIONS) - message("Deprecation warning: WRAP_IMAGE_FILTER_COMBINATIONS is replaced by itk_wrap_image_filter_combinations.") - itk_wrap_image_filter_combinations("${ARGN}") -endmacro() - -macro(WRAP_IMAGE_FILTER_TYPES) - message("Deprecation warning: WRAP_IMAGE_FILTER_TYPES is replaced by itk_wrap_image_filter_types.") - itk_wrap_image_filter_types("${ARGN}") -endmacro() - -macro(FILTER_DIMS) - message("Deprecation warning: FILTER_DIMS is replaced by itk_wrap_filter_dims.") - itk_wrap_filter_dims("${ARGN}") -endmacro() - -macro(BEGIN_WRAPPER_LIBRARY library_name) - message("Deprecation warning: BEGIN_WRAPPER_LIBRARY is replaced by itk_wrap_module.") - itk_wrap_module("${library_name}") -endmacro() - -macro(WRAPPER_LIBRARY_CREATE_LIBRARY) - message("Deprecation warning: WRAPPER_LIBRARY_CREATE_LIBRARY is replaced by itk_end_wrap_module.") - itk_end_wrap_module() -endmacro() - -macro(WRAPPER_LIBRARY_CREATE_WRAP_FILES) - message("Deprecation warning: WRAPPER_LIBRARY_CREATE_WRAP_FILES is replaced by itk_auto_load_submodules.") - itk_auto_load_submodules() -endmacro() - -macro(INCLUDE_WRAP_CMAKE module) - message("Deprecation warning: INCLUDE_WRAP_CMAKE is replaced by itk_load_submodule.") - itk_load_submodule("${module}") -endmacro() - -set(WRAP_ITK_DIMS "${ITK_WRAP_DIMS}" CACHE INTERNAL "deprecated - do not use" FORCE) diff --git a/Utilities/ITK/Wrapping/WrapITKConfig.cmake.in b/Utilities/ITK/Wrapping/WrapITKConfig.cmake.in index b8995adf108f6e246c2d680d47b1e0e711945945..4ff8a18fb859879f32c0a057ecb4a53eab669993 100644 --- a/Utilities/ITK/Wrapping/WrapITKConfig.cmake.in +++ b/Utilities/ITK/Wrapping/WrapITKConfig.cmake.in @@ -22,11 +22,6 @@ if(EXISTS "${possible_swig_dir}") set(SWIG_DIR "${possible_swig_dir}" CACHE PATH "Path to Swig build or install") endif() -# set WrapITK version -set(WrapITK_VERSION_MAJOR @WrapITK_VERSION_MAJOR@) -set(WrapITK_VERSION_MINOR @WrapITK_VERSION_MINOR@) -set(WrapITK_VERSION_PATCH @WrapITK_VERSION_PATCH@) - # Set up the rest of the variables that WrapITK was built with. set(ITK_WRAP_unsigned_char @ITK_WRAP_unsigned_char@ CACHE BOOL "Wrap unsigned char type") set(ITK_WRAP_unsigned_short @ITK_WRAP_unsigned_short@ CACHE BOOL "Wrap unsigned short type") diff --git a/Utilities/ITK/Wrapping/WrapITKTypes.cmake b/Utilities/ITK/Wrapping/WrapITKTypes.cmake index cc0a896cdab3c842be117a486e0457ccfdfb5343..13ec599fafb527c7648e51d049269a106855dfad 100644 --- a/Utilities/ITK/Wrapping/WrapITKTypes.cmake +++ b/Utilities/ITK/Wrapping/WrapITKTypes.cmake @@ -4,7 +4,6 @@ # itk::Command has to be available in all ITK wrapped files set(WRAPPER_DEFAULT_INCLUDE itkCommand.h - itkStatisticsLabelObject.h ) # define some macro to help creation of types vars @@ -243,22 +242,28 @@ WRAP_TYPE("itk::Point" "P") END_WRAP_TYPE() set(itk_Wrap_Point ${WRAPPER_TEMPLATES}) -WRAP_TYPE("itk::LevelSetNode" "LSN") - # Only make level set nodes for the selected image pixel types - foreach(d ${ITK_WRAP_DIMS}) - foreach(type ${WRAP_ITK_SCALAR}) - ADD_TEMPLATE("${ITKM_${type}}${d}" "${ITKT_${type}},${d}") +if(ITK_BUILD_DEFAULT_MODULES OR ITKGroup_Filtering) + # Needed by Modules/Filtering/FastMarching/wrapping/itkLevelSetNode.wrap + WRAP_TYPE("itk::LevelSetNode" "LSN") + # Only make level set nodes for the selected image pixel types + foreach(d ${ITK_WRAP_DIMS}) + foreach(type ${WRAP_ITK_SCALAR}) + ADD_TEMPLATE("${ITKM_${type}}${d}" "${ITKT_${type}},${d}") + endforeach() endforeach() - endforeach() -END_WRAP_TYPE() -set(itk_Wrap_LevelSetNode ${WRAPPER_TEMPLATES}) - -WRAP_TYPE("itk::FlatStructuringElement" "SE") - foreach(d ${ITK_WRAP_DIMS}) - ADD_TEMPLATE("${d}" "${d}") - endforeach() -END_WRAP_TYPE() -set(itk_Wrap_StructuringElement ${WRAPPER_TEMPLATES}) + END_WRAP_TYPE() + set(itk_Wrap_LevelSetNode ${WRAPPER_TEMPLATES}) +endif() + +if(ITK_BUILD_DEFAULT_MODULES OR ITKGroup_Filtering) + # Needed by Modules/Filtering/MathematicalMorphology/wrapping/itkFlatStructuringElement.wrap + WRAP_TYPE("itk::FlatStructuringElement" "SE") + foreach(d ${ITK_WRAP_DIMS}) + ADD_TEMPLATE("${d}" "${d}") + endforeach() + END_WRAP_TYPE() + set(itk_Wrap_StructuringElement ${WRAPPER_TEMPLATES}) +endif() WRAP_TYPE("itk::SpatialObject" "SO") foreach(d ${ITK_WRAP_DIMS}) @@ -273,11 +278,14 @@ WRAP_TYPE("itk::Statistics::Histogram" "H") END_WRAP_TYPE() set(itk_Wrap_Histogram ${WRAPPER_TEMPLATES}) -WRAP_TYPE("itk::LabelMap" "LM") - foreach(d ${ITK_WRAP_DIMS}) - ADD_TEMPLATE("${d}" "itk::StatisticsLabelObject< ${ITKT_UL}, ${d} >") -endforeach() -END_WRAP_TYPE() -set(itk_Wrap_LabelMap ${WRAPPER_TEMPLATES}) +if(ITK_BUILD_DEFAULT_MODULES OR ITKGroup_Filtering) + # Needed by Modules/Filtering/LabelMap/wrapping/ITKLabelMapBase.wrap + WRAP_TYPE("itk::LabelMap" "LM") + foreach(d ${ITK_WRAP_DIMS}) + ADD_TEMPLATE("${d}" "itk::StatisticsLabelObject< ${ITKT_UL}, ${d} >") + endforeach() + END_WRAP_TYPE() + set(itk_Wrap_LabelMap ${WRAPPER_TEMPLATES}) +endif() #------------------------------------------------------------------------------ diff --git a/Utilities/ITK/Wrapping/itkWrapSetup.cmake b/Utilities/ITK/Wrapping/itkWrapSetup.cmake index b6c9126680d0b3a3e914e0b0aefc2567a0db9add..8251027b4ce05449e792875c6f1afebeb15aadaf 100644 --- a/Utilities/ITK/Wrapping/itkWrapSetup.cmake +++ b/Utilities/ITK/Wrapping/itkWrapSetup.cmake @@ -1,23 +1,21 @@ - -# Make it easier to enable the main supported languages, by providing the option even when -# the Wrapping directory has not yet been included -option(ITK_WRAP_PYTHON "Build python support" OFF) - -option(ITK_WRAPPING "Build external languages support" OFF) -mark_as_advanced(ITK_WRAPPING) - # check whether we should go in the wrapping folder, even with ITK_WRAPPING is OFF +# ITK_WRAPPING is an internal variable that indicates wrapping for any +# language will be attempted. if(NOT ITK_WRAPPING_REACHED) if(ITK_WRAP_PYTHON OR ITK_WRAP_JAVA) # force ITK_WRAPPING to ON - unset(ITK_WRAPPING CACHE) - option(ITK_WRAPPING "Build external languages support" ON) - mark_as_advanced(ITK_WRAPPING) + set(ITK_WRAPPING ON CACHE INTERNAL "Build external languages support" FORCE) endif() endif() if(ITK_WRAPPING) if(NOT ITK_BUILD_SHARED_LIBS) - message(FATAL_ERROR "Wrapping requires a shared build, change BUILD_SHARED_LIBS to ON") + message(WARNING "Wrapping requires a shared build, changing BUILD_SHARED_LIBS to ON") + set(BUILD_SHARED_LIBS ON CACHE BOOL "Build ITK with shared libraries." FORCE ) + endif() + + if(ITK_USE_64BITS_IDS AND WIN32) + message(FATAL_ERROR "Wrapping with ITK_USE_64BITS_IDS is not supported on Windows. + Please turn OFF ITK_USE_64BITS_IDS.") endif() endif() diff --git a/Utilities/ITK/Wrapping/testModules.sh b/Utilities/ITK/Wrapping/testModules.sh old mode 100644 new mode 100755