diff --git a/.clang-format b/.clang-format index 69950423abc..7252d3eee3f 100644 --- a/.clang-format +++ b/.clang-format @@ -1,4 +1,4 @@ -## This config file is only relevant for clang-format version 8.0.0 +## This config file is only relevant for clang-format version 19.1.7 ## ## Examples of each format style can be found on the in the clang-format documentation ## See: https://clang.llvm.org/docs/ClangFormatStyleOptions.html for details of each option @@ -10,139 +10,282 @@ ## maintaining a consistent code style. ## ## EXAMPLE apply code style enforcement before commit: -# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_8.0.0} --modified +# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_19.1.7} --modified ## EXAMPLE apply code style enforcement after commit: -# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_8.0.0} --last +# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_19.1.7} --last --- -# This configuration requires clang-format version 8.0.0 exactly. -BasedOnStyle: Mozilla +# This configuration requires clang-format version 19.1.7 exactly. Language: Cpp AccessModifierOffset: -2 AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: true +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false AlignEscapedNewlines: Left -AlignOperands: true -AlignTrailingComments: true -# clang 9.0 AllowAllArgumentsOnNextLine: true -# clang 9.0 AllowAllConstructorInitializersOnNextLine: true +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: false +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Never +AllowShortCaseExpressionOnASingleLine: true AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: Inline -# clang 9.0 AllowShortLambdasOnASingleLine: All -# clang 9.0 features AllowShortIfStatementsOnASingleLine: Never -AllowShortIfStatementsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +#AllowShortFunctionsOnASingleLine: Inline Only merge functions defined inside a class. Implies empty. +#AllowShortFunctionsOnASingleLine: None (in configuration: None) Never merge functions into a single line. +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: All AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: + - __capability BinPackArguments: false BinPackParameters: false -BreakBeforeBraces: Custom +BitFieldColonSpacing: Both BraceWrapping: - # clang 9.0 feature AfterCaseLabel: false + AfterCaseLabel: true AfterClass: true - AfterControlStatement: true + AfterControlStatement: Always AfterEnum: true + AfterExternBlock: true AfterFunction: true AfterNamespace: true AfterObjCDeclaration: true AfterStruct: true AfterUnion: true - AfterExternBlock: true BeforeCatch: true BeforeElse: true -## This is the big change from historical ITK formatting! -# Historically ITK used a style similar to https://en.wikipedia.org/wiki/Indentation_style#Whitesmiths_style -# with indented braces, and not indented code. This style is very difficult to automatically -# maintain with code beautification tools. Not indenting braces is more common among -# formatting tools. + BeforeLambdaBody: false + BeforeWhile: false IndentBraces: false SplitEmptyFunction: false SplitEmptyRecord: false SplitEmptyNamespace: false +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterReturnType: All +BreakArrays: true BreakBeforeBinaryOperators: None -#clang 6.0 BreakBeforeInheritanceComma: true -BreakInheritanceList: BeforeComma +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Custom +BreakBeforeInlineASMColon: OnlyMultiline BreakBeforeTernaryOperators: true -#clang 6.0 BreakConstructorInitializersBeforeComma: true BreakConstructorInitializers: BeforeComma -BreakAfterJavaFieldAnnotations: false +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeComma BreakStringLiterals: true +BreakTemplateDeclarations: Yes ## The following line allows larger lines in non-documentation code ColumnLimit: 120 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 2 ContinuationIndentWidth: 2 Cpp11BracedListStyle: false DerivePointerAlignment: false DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE IncludeBlocks: Preserve IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 + SortPriority: 0 + CaseSensitive: false - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 + SortPriority: 0 + CaseSensitive: false - Regex: '.*' Priority: 1 + SortPriority: 0 + CaseSensitive: false IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false IndentCaseLabels: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true IndentPPDirectives: AfterHash +IndentRequiresClause: true IndentWidth: 2 IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 JavaScriptQuotes: Leave JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: true + AtStartOfFile: true +LambdaBodyIndentation: Signature +LineEnding: DeriveLF MacroBlockBegin: '' MacroBlockEnd: '' +MainIncludeChar: Quote MaxEmptyLinesToKeep: 2 NamespaceIndentation: None ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: true ObjCSpaceBeforeProtocolList: false +PackConstructorInitializers: BinPack PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 ## The following line allows larger lines in non-documentation code PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 PenaltyReturnTypeOnItsOwnLine: 200 PointerAlignment: Middle +PPIndentWidth: -1 +QualifierAlignment: Custom +QualifierOrder: + - friend + - static + - inline + - constexpr + - const + - type +ReferenceAlignment: Pointer ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false # We may want to sort the includes as a separate pass -SortIncludes: false +SortIncludes: Never +SortJavaStaticImport: Before # We may want to revisit this later -SortUsingDeclarations: false +SortUsingDeclarations: Never SpaceAfterCStyleCast: false -# SpaceAfterLogicalNot: false +SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false SpaceBeforeRangeBasedForLoopColon: true -SpaceInEmptyParentheses: false +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false SpacesBeforeTrailingComments: 1 -SpacesInAngles: false +SpacesInAngles: Never SpacesInContainerLiterals: false -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false SpacesInSquareBrackets: false -Standard: Cpp11 +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION @@ -150,11 +293,26 @@ StatementMacros: - ITK_GCC_PRAGMA_POP - ITK_GCC_SUPPRESS_Wfloat_equal - ITK_GCC_SUPPRESS_Wformat_nonliteral + - ITK_GCC_SUPPRESS_Warray_bounds + - ITK_CLANG_PRAGMA_PUSH + - ITK_CLANG_PRAGMA_POP + - ITK_CLANG_SUPPRESS_Wzero_as_null_pointer_constant - CLANG_PRAGMA_PUSH - CLANG_PRAGMA_POP + - CLANG_SUPPRESS_Wfloat_equal - INTEL_PRAGMA_WARN_PUSH - INTEL_PRAGMA_WARN_POP - INTEL_SUPPRESS_warning_1292 + - itkTemplateFloatingToIntegerMacro + - itkLegacyMacro +TableGenBreakInsideDAGArg: DontBreak TabWidth: 2 UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE ... diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index d6d72e5f7db..4cd7523301d 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -96,3 +96,35 @@ fbbc7aa38cf23d0966b1dbd0f9825797e84c2502 f3899ce8c6d53fc077c4e0bfa2c6f1fe56166b57 # STYLE: Initial run of cmake-format efa749515db840b54f7329b261d3ec4c3a575f83 +# STYLE: Prefer explicit const designation +375ee8c47a03792d0d3d5447c6b4c4be6b9f2fb4 +# STYLE: Replace itkTypeMacro calls with `itkOverrideGetNameOfClassMacro` +2c264ea2ef62e916c6ef947599ce659cc8fce5fe +# STYLE: Remove recursive inclusion of .h files +f84720ee0823964bd135de8eb973acc40c1e70e1 +# STYLE: Use `auto` for declaration of variables initialized by `New()` +828453d1bf61c487310d2d8c9570093e08798a40 +# STYLE: Replace postfix by prefix increment in `for` loops in ITK/Modules +971aef211cad336ba75cb2da114fc86e873444e5 +# STYLE: Call ITK_DISALLOW_COPY_AND_MOVE, not ITK_DISALLOW_COPY_AND_ASSIGN +4c0982ddec474b1701d695839c78c7e888659ef4 +# STYLE: Pefer = default to explicitly trivial implementations +5142ed7bb5e4e5042734fc47bf556a2342be6cec +# STYLE: Prefer constexpr for const numeric literals +605cea4735634acdc3222d1e0f1d3fcb2db05e26 +# STYLE: Prefer C++11 type alias over typedef +66e5d6b3bcc28f1a85b702086b6cedc8cab6723b +# STYLE: Provide a well documented macro for repeated code +4a3257e293a9682b2d8b9063f72bddcae98d70dc +# STYLE: Use "typename" for template parameters +86bbb9d092d21bb309b0260c0b4082d9af966b67 +# STYLE: ITK_EXPORT had no use +b788601abbeebd72e5504b10a75a9f417f666c35 +# STYLE: Removed the MSVS6 compiler pragma 4786 +f1bc82756aaf853c50b6c2b5cfb4dfd88bc4824f +# STYLE: Converted module names to use camel case +540228ef42fb667b3255f8610baa5cd9d7b6760d +# STYLE: Change for development tool compliance +13f99f81510fd76b0409b98dac6a4670436e007a +# STYLE: Change to hxx extension for dev tools +2fccd272862ab7cc408d643c8db2e1cb5d098fcf diff --git a/.github/workflows/apply-clang-format.yml b/.github/workflows/apply-clang-format.yml deleted file mode 100644 index bbd0f6f9344..00000000000 --- a/.github/workflows/apply-clang-format.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Apply clang-format to PR - -on: - pull_request: - types: [labeled] - -jobs: - clang-format: - runs-on: ubuntu-latest - permissions: - pull-requests: write - - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - uses: InsightSoftwareConsortium/ITKApplyClangFormatAction@master - with: - github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/clang-format-linter.yml b/.github/workflows/clang-format-linter.yml deleted file mode 100644 index 4a9d9058f93..00000000000 --- a/.github/workflows/clang-format-linter.yml +++ /dev/null @@ -1,17 +0,0 @@ -name: clang-format linter - -on: [push,pull_request] - -permissions: - contents: read - -jobs: - lint: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v4 - - uses: InsightSoftwareConsortium/ITKClangFormatLinterAction@master - with: - error-message: 'Code is inconsistent with ITK Coding Style. Add the *action:ApplyClangFormat* PR label to correct.' - itk-branch: release-5.4 diff --git a/.github/workflows/itk_dict.txt b/.github/workflows/itk_dict.txt index 0fb96f47a34..06b4ee63775 100644 --- a/.github/workflows/itk_dict.txt +++ b/.github/workflows/itk_dict.txt @@ -226,12 +226,12 @@ Wachowiak Wanlin Wdeprecated Wi +Wmaybe Wtautological Xu Y'CbCr Yager's Yixun -Yhis Yuanting Zeiss Zosso @@ -277,6 +277,7 @@ btw buf bugfix bw +byteswap byu bzip calc @@ -617,6 +618,7 @@ memcpy memmove memset merchantability +mersenne meshpixperelt metacharacters metricb @@ -652,6 +654,7 @@ mv myhistogram myreferenceimage mx +natively nbOfDirections nbOfPixels ncodewords diff --git a/.github/workflows/macos-arm.yml b/.github/workflows/macos-arm.yml index 0ea6a336a92..36e84884618 100644 --- a/.github/workflows/macos-arm.yml +++ b/.github/workflows/macos-arm.yml @@ -23,11 +23,15 @@ on: - 'Utilities/ITKv5Preparation/**' - 'Utilities/Maintenance/**' +concurrency: + group: '${{ github.workflow }}@${{ github.head_ref || github.ref }}' + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + env: - ExternalDataVersion: 5.3.0 + ExternalDataVersion: 5.4.0 jobs: - macOS: + macOS-Python: runs-on: macos-14 timeout-minutes: 0 steps: @@ -45,63 +49,13 @@ jobs: - name: Install dependencies run: | set -x - python3 -m pip install ninja - - - name: Download dashboard script and testing data - run: | - set -x - git clone -b dashboard --single-branch https://github.com/InsightSoftwareConsortium/ITK.git ITK-dashboard + python3 -m pip install --upgrade --pre numpy - curl -L https://github.com/InsightSoftwareConsortium/ITK/releases/download/v${{ env.ExternalDataVersion }}/InsightData-${{ env.ExternalDataVersion }}.tar.gz -O - cmake -E tar xfz InsightData-${{ env.ExternalDataVersion }}.tar.gz - cmake -E rename InsightToolkit-${{ env.ExternalDataVersion }}/.ExternalData/MD5 ${{ github.workspace }}/.ExternalData/MD5 - - - name: Configure CTest script - run: | - cat > ITK-dashboard/dashboard.cmake << EOF - set(CTEST_BUILD_CONFIGURATION "Release") - set(CTEST_CMAKE_GENERATOR "Ninja") - set(dashboard_cache " - BUILD_SHARED_LIBS:BOOL=ON - BUILD_EXAMPLES:BOOL=ON - ITK_WRAP_PYTHON:BOOL=OFF - ITK_USE_CLANG_FORMAT:BOOL=OFF - ") - include(${{ github.workspace }}/ITK-dashboard/github_actions_dashboard.cmake) - EOF - cat ITK-dashboard/dashboard.cmake - - - name: Build and test - run: | - set -x - - c++ --version - cmake --version - - ctest -S ${{ github.workspace }}/ITK-dashboard/dashboard.cmake -VV -j 4 - env: - CTEST_OUTPUT_ON_FAILURE: 1 - - macOS-Python: - runs-on: macos-14 - timeout-minutes: 0 - steps: - - name: Checkout - uses: actions/checkout@v4 - with: - fetch-depth: 5 - clean: true - - - name: Set up Python - uses: actions/setup-python@v5 + - name: Get specific version of CMake, latest Ninja + uses: lukka/get-cmake@v4.0.1 with: - python-version: '3.11' - - - name: Install dependencies - run: | - set -x - python3 -m pip install ninja - python3 -m pip install numpy + cmakeVersion: "~4.0.1" + ninjaVersion: latest - name: Download dashboard script and testing data run: | @@ -110,7 +64,7 @@ jobs: curl -L https://github.com/InsightSoftwareConsortium/ITK/releases/download/v${{ env.ExternalDataVersion }}/InsightData-${{ env.ExternalDataVersion }}.tar.gz -O cmake -E tar xfz InsightData-${{ env.ExternalDataVersion }}.tar.gz - cmake -E rename InsightToolkit-${{ env.ExternalDataVersion }}/.ExternalData/MD5 ${{ github.workspace }}/.ExternalData/MD5 + cmake -E rename InsightToolkit-${{ env.ExternalDataVersion }}/.ExternalData/CID ${{ github.workspace }}/.ExternalData/CID - name: Configure CTest script run: | diff --git a/.github/workflows/pixi.yml b/.github/workflows/pixi.yml index abf3930c794..6caa5abb047 100644 --- a/.github/workflows/pixi.yml +++ b/.github/workflows/pixi.yml @@ -23,8 +23,12 @@ on: - 'Utilities/ITKv5Preparation/**' - 'Utilities/Maintenance/**' +concurrency: + group: '${{ github.workflow }}@${{ github.head_ref || github.ref }}' + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + env: - ExternalDataVersion: 5.3.0 + ExternalDataVersion: 5.4.0 jobs: Pixi-Cxx: @@ -32,7 +36,7 @@ jobs: timeout-minutes: 0 strategy: matrix: - os: [ubuntu-22.04, windows-2022, macos-13, macos-14] + os: [ubuntu-22.04, windows-2022, macos-14] steps: - name: Checkout uses: actions/checkout@v4 @@ -48,7 +52,7 @@ jobs: run: | curl -L https://github.com/InsightSoftwareConsortium/ITK/releases/download/v${{ env.ExternalDataVersion }}/InsightData-${{ env.ExternalDataVersion }}.tar.gz -O cmake -E tar xfz InsightData-${{ env.ExternalDataVersion }}.tar.gz - cmake -E rename InsightToolkit-${{ env.ExternalDataVersion }}/.ExternalData/MD5 ${{ github.workspace }}/.ExternalData/MD5 + cmake -E rename InsightToolkit-${{ env.ExternalDataVersion }}/.ExternalData/CID ${{ github.workspace }}/.ExternalData/CID - name: Set up Pixi uses: prefix-dev/setup-pixi@v0.8.1 diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml new file mode 100644 index 00000000000..dabebc4a162 --- /dev/null +++ b/.github/workflows/pre-commit.yml @@ -0,0 +1,20 @@ +name: pre-commit + +on: + pull_request: + +jobs: + pre-commit: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Check install of Python, pre-commit + run: | + ./Utilities/GitSetup/setup-precommit + git config hooks.SetupForDevelopment 99 + git config user.email "you@example.com" + git config user.name "Your Name" + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - uses: pre-commit/action@v3.0.1 diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml new file mode 100644 index 00000000000..2dd280ab66e --- /dev/null +++ b/.github/workflows/scorecard.yml @@ -0,0 +1,70 @@ +name: Scorecard analysis workflow +on: + # For Branch-Protection check. Only the default branch is supported. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection + branch_protection_rule: + # To guarantee Maintained check is occasionally updated. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained + schedule: + - cron: '42 23 * * 6' + push: + branches: [ "master" ] + +# Declare default permissions as read only. +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-latest + permissions: + # Needed to upload the results to code-scanning dashboard. + security-events: write + # Needed to publish results and get a badge (see publish_results below). + id-token: write + # Uncomment the permissions below if installing in a private repository. + # contents: read + # actions: read + + steps: + - name: "Checkout code" + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false + + - name: "Run analysis" + uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1 + with: + results_file: results.sarif + results_format: sarif + # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: + # - you want to enable the Branch-Protection check on a *public* repository, or + # - you are installing Scorecard on a *private* repository + # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action?tab=readme-ov-file#authentication-with-fine-grained-pat-optional. + # repo_token: ${{ secrets.SCORECARD_TOKEN }} + + # Public repositories: + # - Publish results to OpenSSF REST API for easy access by consumers + # - Allows the repository to include the Scorecard badge. + # - See https://github.com/ossf/scorecard-action#publishing-results. + # For private repositories: + # - `publish_results` will always be set to `false`, regardless + # of the value entered here. + publish_results: true + + # Upload the results as artifacts (optional). Commenting out will disable + # uploads of run results in SARIF format to the repository Actions tab. + # https://docs.github.com/en/actions/advanced-guides/storing-workflow-data-as-artifacts + - name: "Upload artifact" + uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # v4.6.1 + with: + name: SARIF file + path: results.sarif + retention-days: 5 + + # Upload the results to GitHub's code scanning dashboard (optional). + # Commenting out will disable upload of results to your repo's Code Scanning dashboard + - name: "Upload to code-scanning" + uses: github/codeql-action/upload-sarif@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 + with: + sarif_file: results.sarif diff --git a/.github/workflows/spell-check-comments.yml b/.github/workflows/spell-check-comments.yml index a36b27fbe0b..7d7704dcc51 100644 --- a/.github/workflows/spell-check-comments.yml +++ b/.github/workflows/spell-check-comments.yml @@ -20,7 +20,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - python -m pip install comment-spell-check~=0.2.2 + python -m pip install comment-spell-check~=0.3.0 curl -O https://raw.githubusercontent.com/SimpleITK/SimpleITK/master/.github/workflows/additional_dictionary.txt - name: Spell check Modules directory @@ -29,6 +29,7 @@ jobs: --miss \ --prefix "gdcm" --exclude ThirdParty \ --dict additional_dictionary.txt \ + --bibtex Documentation/Doxygen/doxygen.bib \ --dict .github/workflows/itk_dict.txt \ --suffix ".h" \ --suffix ".hxx" \ diff --git a/.hooks-config.bash b/.hooks-config.bash deleted file mode 100644 index d7c0368a62f..00000000000 --- a/.hooks-config.bash +++ /dev/null @@ -1,25 +0,0 @@ -#========================================================================== -# -# Copyright NumFOCUS -# -# 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 -# -# https://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. -# -#==========================================================================*/ - -# Loaded by .git/hooks/(pre-commit|commit-msg|prepare-commit-msg) -# during git commit after local hooks have been installed. - -hooks_chain_pre_commit="Utilities/Hooks/pre-commit" -hooks_chain_commit_msg="Utilities/Hooks/commit-msg" -hooks_chain_prepare_commit_msg="Utilities/Hooks/prepare-commit-msg" -hooks_chain_post_commit="Utilities/Hooks/post-commit" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000000..0ad7fd88626 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,105 @@ +# .pre-commit-config.yaml +# for details see https://pre-commit.com +# for list of available hooks see https://pre-commit.com/hooks.html +# +# Preclude commits that do not conform to various criteria. +# +# If a pre-commit check must be skipped then use: `SKIP=check_id git commit` Where `check_id` is the id of the check to +# be skipped such as `black`. + +fail_fast: true +default_stages: [pre-commit] +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: check-added-large-files + args: ['--maxkb=200'] + exclude: | + ( + Source/DataDictionary/gdcmPrivateDefaultDicts.cxx| + Documentation/watershed.ps + ) + - id: check-ast + exclude: "\\/ThirdParty\\/" + - id: check-case-conflict + - id: check-illegal-windows-names + - id: check-json + exclude: "\\/ThirdParty\\/" + - id: check-merge-conflict + exclude: "\\/ThirdParty\\/" + args: ['--assume-in-merge'] + - id: check-toml + exclude: "\\/ThirdParty\\/" + - id: check-vcs-permalinks + exclude: "\\/ThirdParty\\/" + - id: check-xml + exclude: "\\/ThirdParty\\/" + - id: check-yaml + exclude: "\\/ThirdParty\\/" + - id: check-shebang-scripts-are-executable + exclude: "\\/ThirdParty\\/" + - id: debug-statements + exclude: "\\/ThirdParty\\/" + - id: destroyed-symlinks + - id: detect-private-key + - id: end-of-file-fixer + exclude: "\\.(md5|sha|sha512|svg|vtk|vtp)$|^Resources\\/[^\\/]+\\.h$|\\/ColorFiles\\/.+\\.txt$|Data\\/Input\\/.+$|\\/ThirdParty\\/|\\/Data\\/" + - id: forbid-new-submodules + - id: forbid-submodules + - id: mixed-line-ending + exclude: "\\.(sha|sha512|svg|vtk|vtp)$|\\/ThirdParty\\/|\\/Data\\/" + - id: name-tests-test + exclude: "\\/ThirdParty\\/" + args: ['--pytest-test-first'] + - id: no-commit-to-branch + args: ['--branch','dashboard','--branch','python-builds','--branch','release','--branch','hooks','--branch', 'main','--branch','master','--pattern','release-*'] + - id: trailing-whitespace + exclude: "\\.(sha|sha512|svg|vtk|vtp)$|\\/ThirdParty\\/|\\/Data\\/" +- repo: https://github.com/pre-commit/mirrors-clang-format + rev: v19.1.7 + hooks: + - id: clang-format + args: ['--style=file'] + files: '\.(c|cc|h|cxx|hxx)$' + exclude: "\\/ThirdParty\\/|\\/Data\\/" +- repo: https://github.com/psf/black + rev: 24.2.0 + hooks: # check conformance to black formatting + - id: black + #args: ['--diff', '-v', '--target-version', 'py39' ] # if run without arguments, will fail and will format the files + args: ['--target-version', 'py39' ] # Allow black to fail and provide auto-formatting to files that need it for compliance + exclude: ".*build.*|\\/ThirdParty\\/|\\/Data\\/" +- repo: https://github.com/asottile/pyupgrade + rev: v3.19.0 + hooks: + - id: pyupgrade + exclude: ".*build.*|\\/ThirdParty\\/|\\/Data\\/" + args: [--py39-plus] +- repo: local + hooks: + - id: local-prepare-commit-msg + name: 'local prepare-commit-msg' + entry: 'Utilities/Hooks/prepare-commit-msg' + language: system + stages: [prepare-commit-msg] + - id: check-setup-for-development + name: 'Check version of SetupForDevelopment' + entry: 'Utilities/Hooks/check-setup-for-development' + language: system + stages: [pre-commit] + - id: local-pre-commit + name: 'local pre-commit' + entry: 'Utilities/Hooks/pre-commit' + language: system + stages: [pre-commit] + - id: kw-commit-msg + name: 'kw commit-msg' + entry: 'Utilities/Hooks/kw-commit-msg' + language: system + stages: [commit-msg] + - id: kw-pre-commit + name: 'kw-pre-commit' + entry: 'Utilities/Hooks/kw-pre-commit' + language: system + stages: [pre-commit] diff --git a/CMake/Findcppcheck.cpp b/CMake/Findcppcheck.cpp index 5f2eaecda52..7b3f2871fbb 100644 --- a/CMake/Findcppcheck.cpp +++ b/CMake/Findcppcheck.cpp @@ -1,17 +1,17 @@ /** -* \file Findcppcheck.cpp -* \brief Dummy C++ source file used by CMake module Findcppcheck.cmake -* -* \author -* Ryan Pavlik, 2009-2010 -* -* http://academic.cleardefinition.com/ -* -*/ + * \file Findcppcheck.cpp + * \brief Dummy C++ source file used by CMake module Findcppcheck.cmake + * + * \author + * Ryan Pavlik, 2009-2010 + * + * http://academic.cleardefinition.com/ + * + */ - -int main(int argc, char* argv[]) +int +main(int argc, char * argv[]) { return 0; } diff --git a/CMake/ITKClangFormatConfig.cmake.in b/CMake/ITKClangFormatConfig.cmake.in deleted file mode 100644 index a44b02adc33..00000000000 --- a/CMake/ITKClangFormatConfig.cmake.in +++ /dev/null @@ -1,17 +0,0 @@ -set(ITK_SOURCE_DIR "@ITK_SOURCE_DIR@") -set(CMAKE_SOURCE_DIR "@CMAKE_SOURCE_DIR@") -set(CLANG_FORMAT_EXECUTABLE "@CLANG_FORMAT_EXECUTABLE@") - -set(WORKING_DIR "") -if(ITK_SOURCE_DIR) - set(WORKING_DIR "${ITK_SOURCE_DIR}") -else() - set(WORKING_DIR "${CMAKE_SOURCE_DIR}") -endif() - -find_package(Git) -if(GIT_FOUND AND EXISTS "${WORKING_DIR}/.git/config") - execute_process(COMMAND ${GIT_EXECUTABLE} config clangFormat.binary - "${CLANG_FORMAT_EXECUTABLE}" - WORKING_DIRECTORY ${WORKING_DIR}) -endif() diff --git a/CMake/ITKClangFormatSetup.cmake b/CMake/ITKClangFormatSetup.cmake deleted file mode 100644 index 9ded94935e0..00000000000 --- a/CMake/ITKClangFormatSetup.cmake +++ /dev/null @@ -1,61 +0,0 @@ -# Provides itk_clangformat_setup to assist with maintaining consistent -# style across the ITK toolkit -# -# Globally the ${ITK_SOURCE_DIR}/.clang-format file is used to configure the enforced style. -# -# Clang version 8.0 is required -# -# The ITK style guidelines are represented by clang-format version 8.0.0 -# rules defined in ${ITK_SOURCE_DIR}/.clang-format -# -option(ITK_USE_CLANG_FORMAT "Enable the use of clang-format enforce ITK coding style." ${BUILD_TESTING}) -mark_as_advanced(ITK_USE_CLANG_FORMAT) - -find_program(CLANG_FORMAT_EXECUTABLE NAMES clang-format-8.0 clang-format8 clang-format) -mark_as_advanced(CLANG_FORMAT_EXECUTABLE) -if(ITK_USE_CLANG_FORMAT AND NOT CLANG_FORMAT_EXECUTABLE) - # Download pre-built binaries (about 2M) of clang-format extracted from - # https://releases.llvm.org/download.html and cached on data.kitware.com - # - # Darwin - macOS/OS X (Clang, GCC) https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-x86_64-apple-darwin.tar.xz - # Windows - Windows (Visual Studio, MinGW GCC) https://releases.llvm.org/8.0.0/LLVM-8.0.0-win64.exe - # https://releases.llvm.org/8.0.0/LLVM-8.0.0-win32.exe - # Linux - Linux (GCC, Intel, PGI) https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-x86_64-linux-gnu-ubuntu-14.04.tar.xz - # https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-x86_64-linux-gnu-ubuntu-16.04.tar.xz - # https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-x86_64-linux-gnu-ubuntu-18.04.tar.xz - # https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-x86_64-linux-sles11.3.tar.xz - # https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-armv7a-linux-gnueabihf.tar.xz - # https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-aarch64-linux-gnu.tar.xz - # - # FreeBSD - FreeBSD https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-amd64-unknown-freebsd11.tar.xz - # https://releases.llvm.org/8.0.0/clang+llvm-8.0.0-i386-unknown-freebsd11.tar.xz - # - # Android - Android NDK (GCC, Clang) - # CrayLinuxEnvironment - Cray supercomputers (Cray compiler) - # MSYS - Windows (MSYS2 shell native GCC) - if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin") - set(CLANG_FORMAT_DOWNLOAD_URL "https://data.kitware.com/api/v1/file/5d274e88877dfcc902effc47/download") - elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") - set(CLANG_FORMAT_DOWNLOAD_URL "https://data.kitware.com/api/v1/file/5d2b8775877dfcc902fd8236/download") - elseif (CMAKE_HOST_SYSTEM_NAME MATCHES "Linux" AND CMAKE_HOST_SYSTEM_PROCESSOR STREQUAL "x86_64") - set(CLANG_FORMAT_DOWNLOAD_URL "https://data.kitware.com/api/v1/file/5d2b8c87877dfcc902fda594/download") - else() - message(FATAL_ERROR "System binaries not available: set CLANG_FORMAT_EXECUTABLE to clang-format 8 or disable ITK_USE_CLANG_FORMAT.") - endif() - file(MAKE_DIRECTORY "${ITK_BINARY_DIR}/temp") - if(WIN32) - set(exe .exe) - endif() - set(CLANG_FORMAT_EXECUTABLE_NAME "clang-format-${CMAKE_SYSTEM_NAME}${exe}") - file(DOWNLOAD "${CLANG_FORMAT_DOWNLOAD_URL}" "${ITK_BINARY_DIR}/temp/${CLANG_FORMAT_EXECUTABLE_NAME}") - file( - COPY "${ITK_BINARY_DIR}/temp/${CLANG_FORMAT_EXECUTABLE_NAME}" - DESTINATION "${ITK_BINARY_DIR}" - FILE_PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ) - unset(CLANG_FORMAT_DOWNLOAD_URL) - set(CLANG_FORMAT_EXECUTABLE - "${ITK_BINARY_DIR}/${CLANG_FORMAT_EXECUTABLE_NAME}" - CACHE FILEPATH "The binary for clang-format" FORCE) -elseif(ITK_USE_CLANG_FORMAT AND NOT CLANG_FORMAT_EXECUTABLE) - message(FATAL_ERROR "Missing suitable clang-format executable, set CLANG_FORMAT_EXECUTABLE to clang-format 8 or disable ITK_USE_CLANG_FORMAT.") -endif() diff --git a/CMake/ITKConfig.cmake.in b/CMake/ITKConfig.cmake.in index 7a77ae3c07a..facc51c6572 100644 --- a/CMake/ITKConfig.cmake.in +++ b/CMake/ITKConfig.cmake.in @@ -26,9 +26,6 @@ set(ITK_VERSION_MAJOR "@ITK_VERSION_MAJOR@") set(ITK_VERSION_MINOR "@ITK_VERSION_MINOR@") set(ITK_VERSION_PATCH "@ITK_VERSION_PATCH@") -# If ITK was built with version 4 compatibility features. -set(ITKV4_COMPATIBILITY "@ITKV4_COMPATIBILITY@") - # Remove all legacy code completely. set(ITK_LEGACY_REMOVE "@ITK_LEGACY_REMOVE@") @@ -51,7 +48,7 @@ set(ITK_BUILD_SHARED "@ITK_BUILD_SHARED_LIBS@") set(ITK_LIBRARY_BUILD_TYPE "@ITK_LIBRARY_BUILD_TYPE@") # Whether ITK links to MSVC's static CRT (/MT and /MTd). -set(ITK_MSVC_STATIC_CRT "@ITK_MSVC_STATIC_RUNTIME_LIBRARY_value@") +set(ITK_MSVC_STATIC_CRT "@ITK_MSVC_STATIC_CRT@") # Whether ITK examples were built. set(ITK_BUILD_EXAMPLES "@BUILD_EXAMPLES@") diff --git a/CMake/ITKModuleClangFormat.cmake b/CMake/ITKModuleClangFormat.cmake deleted file mode 100644 index a4cc0c4b342..00000000000 --- a/CMake/ITKModuleClangFormat.cmake +++ /dev/null @@ -1,18 +0,0 @@ -# Download and configure clang-format for style uniformity during development. -# -# This code helps download a version of clang-format binaries consistent with -# ITK's clang-format configuration. Git configuration is added during -# development to help automatically apply the formatting. -# -# Globally, the ITK/.clang-format file provides the base style configuration. -# For more information on ITK coding style, see the ITK Coding Style Guide in -# the ITK Software Guide. -option(ITK_USE_CLANG_FORMAT "Enable the use of clang-format for coding style formatting." ${BUILD_TESTING}) -mark_as_advanced(ITK_USE_CLANG_FORMAT) - -if(BUILD_TESTING - AND ITK_USE_CLANG_FORMAT - AND NOT CMAKE_CROSSCOMPILING - AND NOT ITK_FORBID_DOWNLOADS) - include(${ITK_CMAKE_DIR}/../Utilities/ClangFormat/DownloadClangFormat.cmake) -endif() diff --git a/CMake/ITKModuleDoxygen.cmake b/CMake/ITKModuleDoxygen.cmake index 87697d8821f..20d843b4abd 100644 --- a/CMake/ITKModuleDoxygen.cmake +++ b/CMake/ITKModuleDoxygen.cmake @@ -10,23 +10,30 @@ macro(itk_module_doxygen _name) set(_content "${_content} \\defgroup ${_name} Module ${_name} \n") set(_content "${_content} ${ITK_MODULE_${_name}_DESCRIPTION} \n") - set(_content "${_content} \\par Dependencies:\n") - - # _dotcontent defines the content of the ${_name}.dot - set(_dotcontent "graph \"${_name}\" { \n") - + set(non_empty_loop "OFF") foreach(d ${ITK_MODULE_${_name}_DEPENDS}) - set(_content "${_content} \\li \\ref ${d} \n") - set(_dotcontent "${_dotcontent} \"${_name}\" -- \"${d}\"; \n") + set(non_empty_loop "ON") endforeach() - set(_dotcontent "${_dotcontent} }") + if (${non_empty_loop}) + set(_content "${_content} \\par Dependencies:\n") + + # _dotcontent defines the content of the ${_name}.dot + set(_dotcontent "graph \"${_name}\" { \n") - # add the image that will be generated by dot based on the defined graph - # here - set(_content "${_content} \\dot \n") - set(_content "${_content} ${_dotcontent} \n") - set(_content "${_content} \\enddot \n") + foreach(d ${ITK_MODULE_${_name}_DEPENDS}) + set(_content "${_content} \\li \\ref ${d} \n") + set(_dotcontent "${_dotcontent} \"${_name}\" -- \"${d}\"; \n") + endforeach() + + set(_dotcontent "${_dotcontent} }") + + # add the image that will be generated by dot based on the defined graph + # here + set(_content "${_content} \\dot \n") + set(_content "${_content} ${_dotcontent} \n") + set(_content "${_content} \\enddot \n") + endif() set(_content "${_content} */\n") if(ITK_SOURCE_DIR) diff --git a/CMake/ITKModuleMacros.cmake b/CMake/ITKModuleMacros.cmake index 2dcf9a264fa..412bfe4c4bc 100644 --- a/CMake/ITKModuleMacros.cmake +++ b/CMake/ITKModuleMacros.cmake @@ -6,7 +6,6 @@ include(${_ITKModuleMacros_DIR}/ITKModuleAPI.cmake) include(${_ITKModuleMacros_DIR}/ITKModuleDoxygen.cmake) include(${_ITKModuleMacros_DIR}/ITKModuleHeaderTest.cmake) include(${_ITKModuleMacros_DIR}/ITKModuleKWStyleTest.cmake) -include(${_ITKModuleMacros_DIR}/ITKModuleClangFormat.cmake) include(${_ITKModuleMacros_DIR}/CppcheckTargets.cmake) include(${_ITKModuleMacros_DIR}/ITKModuleCPPCheckTest.cmake) include(${_ITKModuleMacros_DIR}/ITKFactoryRegistration.cmake) diff --git a/CMake/ITKSetPython3Vars.cmake b/CMake/ITKSetPython3Vars.cmake index 97d2762f6d5..37f6bf9242c 100644 --- a/CMake/ITKSetPython3Vars.cmake +++ b/CMake/ITKSetPython3Vars.cmake @@ -8,26 +8,22 @@ # implementation gives preference to active virtualenvs. cmake_policy(SET CMP0094 NEW) # makes FindPython3 prefer activated virtualenv Python to latest version -set(PYTHON_REQUIRED_VERSION 3.8) -set(Python_ADDITIONAL_VERSIONS - 3.12 - 3.11 - 3.10 - 3.9 - 3.8) +set(PYTHON_VERSION_MIN 3.9) +set(PYTHON_VERSION_MAX 3.999) + if(PYTHON_DEVELOPMENT_REQUIRED) if(DEFINED Python3_EXECUTABLE) # if already specified set(_specified_Python3_EXECUTABLE ${Python3_EXECUTABLE}) endif() # set(Python3_FIND_REGISTRY LAST) # default is FIRST. Do we need/want this? - find_package(Python3 ${PYTHON_REQUIRED_VERSION} COMPONENTS Interpreter Development.Module ${SKBUILD_SABI_COMPONENT}) + find_package(Python3 ${PYTHON_VERSION_MIN}...${PYTHON_VERSION_MAX} COMPONENTS Interpreter Development.Module ${SKBUILD_SABI_COMPONENT}) if(DEFINED _specified_Python3_EXECUTABLE) set(Python3_EXECUTABLE ${_specified_Python3_EXECUTABLE} CACHE INTERNAL "Path to the Python interpreter" FORCE) endif() else() # if not PYTHON_DEVELOPMENT_REQUIRED, just find some version of Python (don't need to be as specific) - find_package(Python3 ${PYTHON_REQUIRED_VERSION} COMPONENTS Interpreter) + find_package(Python3 ${PYTHON_VERSION_MIN}...${PYTHON_VERSION_MAX} COMPONENTS Interpreter) endif() if(ITK_WRAP_PYTHON) set(ITK_WRAP_PYTHON_VERSION "${Python3_VERSION}") diff --git a/CMake/ITKSetStandardCompilerFlags.cmake b/CMake/ITKSetStandardCompilerFlags.cmake index 1ec759839e9..8f366f33a6f 100644 --- a/CMake/ITKSetStandardCompilerFlags.cmake +++ b/CMake/ITKSetStandardCompilerFlags.cmake @@ -229,7 +229,7 @@ function(check_avx_flags avx_flags_var) endfunction() # Check for the presence of SSE2. -# Adapted from the AVX check and https://github.com/InsightSoftwareConsortium/ITK/blob/master/Modules/ThirdParty/VNL/src/vxl/config/cmake/config/vxl_platform_tests.cxx#L164-L178 +# Adapted from the AVX check and https://github.com/InsightSoftwareConsortium/ITK/blob/4cbe24cb4a45d689cadd56d554b8ccf3584a5ca6/Modules/ThirdParty/VNL/src/vxl/config/cmake/config/vxl_platform_tests.cxx#L164-L178 function(check_sse2_flags sse2_flags_var) # set flags to be used in check_cxx_source_runs below diff --git a/CMake/ITKcppcheckSuppressions.txt b/CMake/ITKcppcheckSuppressions.txt new file mode 100644 index 00000000000..4d3cf8f19f3 --- /dev/null +++ b/CMake/ITKcppcheckSuppressions.txt @@ -0,0 +1,160 @@ +// This file contains enough suppressions to result in no cppcheck warnings, +// at least on macOS with cppcheck 2.16 with the flags below. + +// To run: +// cd /path/to/ITK/ +// cppcheck --platform=unspecified --enable=style -q --library=qt --library=posix --library=gnu --library=bsd --library=windows --check-level=exhaustive --suppressions-list=CMake/ITKcppcheckSuppressions.txt --template='{id},{file}:{line},{severity},{message}' -j8 -I Common/Core . +// or +// cd /path/to/ITK-bin/ +// cppcheck --project=compile_commands.json --platform=unspecified --enable=style -q --library=qt --library=posix --library=gnu --library=bsd --library=windows --check-level=exhaustive --suppressions-list=../ITK/CMake/ITKcppcheckSuppressions.txt --template='{id},{file}:{line},{severity},{message}' -j8 + +// Suppress everything from ThirdParty. +*:*/ThirdParty/* +*:*H5* + +// If cppcheck itself crashes, well, that's its problem, ignore that. +cppcheckError +internalAstError +syntaxError + +// When analyzing different define possibilities, it will sometimes hit a #error line +preprocessorErrorDirective + +// Using reallocf() would be a good solution, but it's not available on all platforms. +memleakOnRealloc + +// Using strtok_r() would be a good solution, but it's not available on all platforms. +strtokCalled + +// ITK assumes IEEE 754 floats, so this warning isn't useful. +memsetClassFloat + +// These are too stylistic +useStlAlgorithm + +// Gives too many false positives. +assertWithSideEffect +argumentSize + +// There are many, could probably be changed automatically, with clang-tidy? +cstyleCast + +// There are many, easily fixable, but possibly backwards incompatible. +passedByValue + +// Deliberate +duplicateExpression:*/itkFloatingPointExceptionsTest.cxx +knownConditionTrueFalse:*/itkAggregateTypesGTest.cxx +knownConditionTrueFalse:*/itkExceptionObjectTest.cxx +knownConditionTrueFalse:*/itkGoogleTest.cxx +knownConditionTrueFalse:*/itkImageIteratorTest.cxx +knownConditionTrueFalse:*/itkJointDomainImageToListSampleAdaptorTest.cxx +knownConditionTrueFalse:*/itkListSampleTest.cxx +knownConditionTrueFalse:*/itkMembershipSampleTest1.cxx +knownConditionTrueFalse:*/itkMembershipSampleTest2.cxx +knownConditionTrueFalse:*/itkMembershipSampleTest3.cxx +knownConditionTrueFalse:*/itkMembershipSampleTest4.cxx +knownConditionTrueFalse:*/itkPointSetToListSampleAdaptorTest.cxx +knownConditionTrueFalse:*/itkSmartPointerGTest.cxx +knownConditionTrueFalse:*/itkSubsampleTest2.cxx +knownConditionTrueFalse:*/itkVectorGeometryTest.cxx +knownConditionTrueFalse:*/itkVectorTest.cxx +oppositeInnerCondition:*/itkExhaustiveOptimizerv4.hxx +postfixOperator:*itkLabelObjectTest.cxx +redundantCondition:*/itkMINCTransformAdapter.h +unusedPrivateFunction:*/itkMaskNegatedImageFilter.h +unusedScopedObject:*/itkConceptChecking.h +unusedStructMember:*/itkBasicFiltersPrintTest.cxx +unusedStructMember:*/itkBioRadImageIO.cxx +unusedStructMember:*/itkCommonPrintTest.cxx +unusedStructMember:*/itkJPEG2000ImageIO.cxx +unusedStructMember:*/itkObjectStoreTest.cxx +unusedStructMember:*/itkTemporalProcessObjectTest.cxx + +// False positives. +CastIntegerToAddressAtReturn:*/itkCellInterface.h +duplicateExpression:*/itkVectorIndexSelectionCastImageFilter.h +ignoredReturnValue:*/itkConnectedThresholdImageFilterTest.cxx +knownArgument:*/itkMeanImageFilterGTest.cxx +knownConditionTrueFalse:*/itkFixedArrayTest.cxx +knownConditionTrueFalse:*/itkMeasurementVectorTraits.h +knownConditionTrueFalse:*/itkNeighborhood.hxx +knownConditionTrueFalse:*/itkQuadEdgeMeshCellInterfaceTest.cxx +knownConditionTrueFalse:*/itkResourceProbe.hxx +legacyUninitvar:*/itkDiscreteGaussianDerivativeImageFunctionTest.cxx +legacyUninitvar:*/itkDiscreteGradientMagnitudeGaussianImageFunctionTest.cxx +legacyUninitvar:*/itkDiscreteHessianGaussianImageFunctionTest.cxx +legacyUninitvar:*/itkVectorImageTest.cxx +mismatchingContainers:*/itkRangeGTestUtilities.h +missingOverride:*/itkImage.h +missingOverride:*/itkImageAdaptor.h +missingOverride:*/itkLabelMap.h +missingOverride:*/itkLevelSetQuadEdgeMesh.h +missingOverride:*/itkVectorImage.h +missingReturn:*/itkBSplineKernelFunction.h +nullPointerRedundantCheck:*/itkQuadEdgeTest1.cxx +nullPointerRedundantCheck:*/itkSpatialObject.hxx +nullPointerRedundantCheck:*/itkTernaryGeneratorImageFilter.hxx +postfixOperator:*/itkTriangleMeshToSimplexMeshFilter.hxx +unusedPrivateFunction:*/itkMaskNegatedImageFilter.h +unusedStructMember:*/ImageRegistrationHistogramPlotter.cxx +unusedStructMember:*/itkGoogleTestFixture.cxx +unusedStructMember:*/itkMinimumMaximumImageFilterGTest.cxx +containerOutOfBounds:*/itkMINCTransformIO.cxx + +// Not false positives exactly, but essentially. +duplicateExpression:*/IterativeClosestPoint2.cxx +duplicateExpression:*/ResampleImageFilter3.cxx +incrementboolean:*/itkMovingHistogramMorphologicalGradientImageFilter.h +moduloofone:*/itkMeshConvertPixelTraits.h +oppositeInnerCondition:*/itkExhaustiveOptimizer.cxx + +// Only a few to investigate, but non-trivial +invalidIterator1 +invalidPointerCast +objectIndex +accessMoved + +// To investigate... +constParameter +constParameterCallback +constParameterPointer +constParameterReference +constVariable +constVariablePointer +constVariableReference +derefInvalidIteratorRedundantCheck +duplInheritedMember +duplicateAssignExpression +duplicateCondition +duplicateConditionalAssign +knownConditionTrueFalse +memleak +noCopyConstructor +noDestructor +noExplicitConstructor +noOperatorEq +operatorEqToSelf +operatorEqVarError +redundantAssignment +redundantInitialization +rethrowNoCurrentException +returnByReference +shadowFunction +throwInNoexceptFunction +truncLongCastAssignment +uninitMemberVar +uninitdata +uninitvar +unpreciseMathCall +unreadVariable +unsafeClassCanLeak +unsignedLessThanZero +unsignedPositive +unusedVariable +useInitializationList +uselessAssignmentArg +uselessCallsRemove +uselessOverride +variableScope +virtualCallInConstructor diff --git a/CMake/InsightValgrind-Ubuntu2204.supp b/CMake/InsightValgrind-Ubuntu2204.supp new file mode 100644 index 00000000000..e40d4ff7a3c --- /dev/null +++ b/CMake/InsightValgrind-Ubuntu2204.supp @@ -0,0 +1,12 @@ +{ + Internal DLL exceptions + Memcheck:Leak + match-leak-kinds: definite + fun:malloc + ... + fun:_dl_catch_exception + fun:_dl_catch_error + fun:_dlerror_run + fun:dlopen_implementation + fun:dlopen@@GLIBC_2.* +} diff --git a/CMake/itkVersion.cmake b/CMake/itkVersion.cmake index e4ac96f6597..e9509ab406a 100644 --- a/CMake/itkVersion.cmake +++ b/CMake/itkVersion.cmake @@ -1,4 +1,4 @@ # ITK version number components. -set(ITK_VERSION_MAJOR "5") -set(ITK_VERSION_MINOR "4") -set(ITK_VERSION_PATCH "3") +set(ITK_VERSION_MAJOR "6") +set(ITK_VERSION_MINOR "0") +set(ITK_VERSION_PATCH "0") diff --git a/CMakeLists.txt b/CMakeLists.txt index 1267b1aae95..02c05c71cd2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -10,7 +10,7 @@ # CMake versions greater than the ITK_NEWEST_VALIDATED_POLICIES_VERSION policies will # continue to generate policy warnings "CMake Warning (dev)...Policy CMP0XXX is not set:" # -set(ITK_OLDEST_VALIDATED_POLICIES_VERSION "3.16.3") +set(ITK_OLDEST_VALIDATED_POLICIES_VERSION "3.22.1") set(ITK_NEWEST_VALIDATED_POLICIES_VERSION "3.29.0") cmake_minimum_required(VERSION ${ITK_OLDEST_VALIDATED_POLICIES_VERSION}...${ITK_NEWEST_VALIDATED_POLICIES_VERSION} FATAL_ERROR) @@ -130,7 +130,7 @@ if(MSVC) #-- Configure MSVC_STATIC_RUNTIME only if using MSVC environment option(ITK_MSVC_STATIC_RUNTIME_LIBRARY "Link to MSVC's static CRT (/MT and /MTd). OFF (default) means link to regular, dynamic CRT (/MD and /MDd)." OFF) mark_as_advanced(ITK_MSVC_STATIC_RUNTIME_LIBRARY) - set(ITK_MSVC_STATIC_RUNTIME_LIBRARY_value ${ITK_MSVC_STATIC_RUNTIME_LIBRARY}) + set(ITK_MSVC_STATIC_CRT ${ITK_MSVC_STATIC_RUNTIME_LIBRARY}) if(ITK_MSVC_STATIC_RUNTIME_LIBRARY) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") message(STATUS "Using MSVC's static CRT (/MT and /MTd)") @@ -325,20 +325,16 @@ cmake_dependent_option( OFF "NOT ITK_LEGACY_REMOVE" OFF) -# The disabling of legacy code, and the ITKv4 compatibility option can not both be -# requested. If removal of legacy code is requested, then ITKV4_COMPATIBILITY must -# be off. -cmake_dependent_option( - ITKV4_COMPATIBILITY - "Enable LEGACY compatibility with ITK4.x when possible." - OFF - "NOT ITK_LEGACY_REMOVE" - OFF) + mark_as_advanced( ITK_LEGACY_SILENT ITK_LEGACY_REMOVE ITK_FUTURE_LEGACY_REMOVE - ITKV4_COMPATIBILITY) + ) + +if(ITKV4_COMPATIBILITY) + message(FATAL_ERROR "ITKV4_COMPATIBILITY is removed starting in ITK version 6.0, this option is no longer valid.") +endif() if(ITKV3_COMPATIBILITY) message(FATAL_ERROR "ITKV3_COMPATIBILITY is removed starting in ITK version 5.0, this option is no longer valid.") @@ -498,11 +494,11 @@ option( mark_as_advanced(ITK_USE_64BITS_IDS) # ITK turn on concept checking -option( - ITK_USE_CONCEPT_CHECKING - "Turn on concept checking to give helpful errors at compile time if a type cannot be used as a template parameter." - ON) -mark_as_advanced(ITK_USE_CONCEPT_CHECKING) +if(ITK_USE_CONCEPT_CHECKING) + message( + WARNING + "Ignoring ITK_USE_CONCEPT_CHECKING, as concept checking is performed unconditionally. This variable is no longer used") +endif() if(ITK_USE_STRICT_CONCEPT_CHECKING) message( WARNING @@ -545,6 +541,9 @@ mark_as_advanced(ITK_COMPUTER_MEMORY_SIZE) # spacing/direction/origin to single precision option(ITK_USE_FLOAT_SPACE_PRECISION "Use single precision for origin/spacing/directions in itk::Image" OFF) mark_as_advanced(ITK_USE_FLOAT_SPACE_PRECISION) +if( ITK_USE_FLOAT_SPACE_PRECISION AND ITK_WRAP_PYTHON) + message(FATAL_ERROR "ITK_USE_FLOAT_SPACE_PRECISION=ON not supported with ITK_WRAP_PYTHON=ON") +endif() # This flag allows to not build itkTestDrivers while still configuring all the tests and disable all # tests that are implemented in the `test` folder in each ITK module. It does not disable tests @@ -582,8 +581,6 @@ add_subdirectory(Modules/Remote) # Enable modules according to user inputs and the module dependency DAG. include(ITKModuleEnablement) -# Setup clang-format for code style enforcement -include(ITKClangFormatSetup) # Setup clang-tidy for code best-practices enforcement for C++11 include(ITKClangTidySetup) #---------------------------------------------------------------------- diff --git a/Documentation/Doxygen/DoxygenFooter.html b/Documentation/Doxygen/DoxygenFooter.html index c64ddf09376..60d9cd86d8f 100644 --- a/Documentation/Doxygen/DoxygenFooter.html +++ b/Documentation/Doxygen/DoxygenFooter.html @@ -1,38 +1,36 @@ - + + diff --git a/Documentation/Doxygen/DoxygenHeader.html b/Documentation/Doxygen/DoxygenHeader.html index 72de89c82e0..28ea2c3e0d0 100644 --- a/Documentation/Doxygen/DoxygenHeader.html +++ b/Documentation/Doxygen/DoxygenHeader.html @@ -1,55 +1,79 @@ - + - + - + $projectname: $title $title + + + + + + + + + + + $treeview $search $mathjax +$darkmode $extrastylesheet + + +
+ + +
- + - + - - - + + + + + + + +
-
$projectname -  $projectnumber +
+
$projectname $projectnumber
$projectbrief
+
$projectbrief
$searchbox$searchbox
$searchbox
diff --git a/Documentation/Doxygen/DoxygenLayout.xml b/Documentation/Doxygen/DoxygenLayout.xml index 0bdc7516234..7dc7f2d470b 100644 --- a/Documentation/Doxygen/DoxygenLayout.xml +++ b/Documentation/Doxygen/DoxygenLayout.xml @@ -4,6 +4,7 @@ + diff --git a/Documentation/Doxygen/ITKDoxygenStyle.css b/Documentation/Doxygen/ITKDoxygenStyle.css deleted file mode 100644 index b70051e3995..00000000000 --- a/Documentation/Doxygen/ITKDoxygenStyle.css +++ /dev/null @@ -1,1763 +0,0 @@ -/* The standard CSS for doxygen 1.8.15 */ - -body, table, div, p, dl { - font: 400 14px/22px Roboto,sans-serif; -} - -p.reference, p.definition { - font: 400 14px/22px Roboto,sans-serif; -} - -/* @group Heading Levels */ - -h1.groupheader { - font-size: 150%; -} - -.title { - font: 400 14px/28px Roboto,sans-serif; - font-size: 150%; - font-weight: bold; - margin: 10px 2px; -} - -h2.groupheader { - border-bottom: 1px solid #879ECB; - color: #354C7B; - font-size: 150%; - font-weight: normal; - margin-top: 1.75em; - padding-top: 8px; - padding-bottom: 4px; - width: 100%; -} - -h3.groupheader { - font-size: 100%; -} - -h1, h2, h3, h4, h5, h6 { - -webkit-transition: text-shadow 0.5s linear; - -moz-transition: text-shadow 0.5s linear; - -ms-transition: text-shadow 0.5s linear; - -o-transition: text-shadow 0.5s linear; - transition: text-shadow 0.5s linear; - margin-right: 15px; -} - -h1.glow, h2.glow, h3.glow, h4.glow, h5.glow, h6.glow { - text-shadow: 0 0 15px cyan; -} - -dt { - font-weight: bold; -} - -div.multicol { - -moz-column-gap: 1em; - -webkit-column-gap: 1em; - -moz-column-count: 3; - -webkit-column-count: 3; -} - -p.startli, p.startdd { - margin-top: 2px; -} - -p.starttd { - margin-top: 0px; -} - -p.endli { - margin-bottom: 0px; -} - -p.enddd { - margin-bottom: 4px; -} - -p.endtd { - margin-bottom: 2px; -} - -p.interli { -} - -p.interdd { -} - -p.intertd { -} - -/* @end */ - -caption { - font-weight: bold; -} - -span.legend { - font-size: 70%; - text-align: center; -} - -h3.version { - font-size: 90%; - text-align: center; -} - -div.qindex, div.navtab{ - background-color: #EBEFF6; - border: 1px solid #A3B4D7; - text-align: center; -} - -div.qindex, div.navpath { - width: 100%; - line-height: 140%; -} - -div.navtab { - margin-right: 15px; -} - -/* @group Link Styling */ - -a { - color: #3D578C; - font-weight: normal; - text-decoration: none; -} - -.contents a:visited { - color: #4665A2; -} - -a:hover { - text-decoration: underline; -} - -a.qindex { - font-weight: bold; -} - -a.qindexHL { - font-weight: bold; - background-color: #9CAFD4; - color: #FFFFFF; - border: 1px double #869DCA; -} - -.contents a.qindexHL:visited { - color: #FFFFFF; -} - -a.el { - font-weight: bold; -} - -a.elRef { -} - -a.code, a.code:visited, a.line, a.line:visited { - color: #4665A2; -} - -a.codeRef, a.codeRef:visited, a.lineRef, a.lineRef:visited { - color: #4665A2; -} - -/* @end */ - -dl.el { - margin-left: -1cm; -} - -ul { - overflow: hidden; /*Fixed: list item bullets overlap floating elements*/ -} - -#side-nav ul { - overflow: visible; /* reset ul rule for scroll bar in GENERATE_TREEVIEW window */ -} - -#main-nav ul { - overflow: visible; /* reset ul rule for the navigation bar drop down lists */ -} - -.fragment { - text-align: left; - direction: ltr; - overflow-x: auto; /*Fixed: fragment lines overlap floating elements*/ - overflow-y: hidden; -} - -pre.fragment { - border: 1px solid #C4CFE5; - background-color: #FBFCFD; - padding: 4px 6px; - margin: 4px 8px 4px 2px; - overflow: auto; - word-wrap: break-word; - font-size: 9pt; - line-height: 125%; - font-family: monospace, fixed; - font-size: 105%; -} - -div.fragment { - padding: 0 0 1px 0; /*Fixed: last line underline overlap border*/ - margin: 4px 8px 4px 2px; - background-color: #FBFCFD; - border: 1px solid #C4CFE5; -} - -div.line { - font-family: monospace, fixed; - font-size: 13px; - min-height: 13px; - line-height: 1.0; - text-wrap: unrestricted; - white-space: -moz-pre-wrap; /* Moz */ - white-space: -pre-wrap; /* Opera 4-6 */ - white-space: -o-pre-wrap; /* Opera 7 */ - white-space: pre-wrap; /* CSS3 */ - word-wrap: break-word; /* IE 5.5+ */ - text-indent: -53px; - padding-left: 53px; - padding-bottom: 0px; - margin: 0px; - -webkit-transition-property: background-color, box-shadow; - -webkit-transition-duration: 0.5s; - -moz-transition-property: background-color, box-shadow; - -moz-transition-duration: 0.5s; - -ms-transition-property: background-color, box-shadow; - -ms-transition-duration: 0.5s; - -o-transition-property: background-color, box-shadow; - -o-transition-duration: 0.5s; - transition-property: background-color, box-shadow; - transition-duration: 0.5s; -} - -div.line:after { - content:"\000A"; - white-space: pre; -} - -div.line.glow { - background-color: cyan; - box-shadow: 0 0 10px cyan; -} - - -span.lineno { - padding-right: 4px; - text-align: right; - border-right: 2px solid #0F0; - background-color: #E8E8E8; - white-space: pre; -} -span.lineno a { - background-color: #D8D8D8; -} - -span.lineno a:hover { - background-color: #C8C8C8; -} - -.lineno { - -webkit-touch-callout: none; - -webkit-user-select: none; - -khtml-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -div.ah, span.ah { - background-color: black; - font-weight: bold; - color: #FFFFFF; - margin-bottom: 3px; - margin-top: 3px; - padding: 0.2em; - border: solid thin #333; - border-radius: 0.5em; - -webkit-border-radius: .5em; - -moz-border-radius: .5em; - box-shadow: 2px 2px 3px #999; - -webkit-box-shadow: 2px 2px 3px #999; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; - background-image: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#000),color-stop(0.3, #444)); - background-image: -moz-linear-gradient(center top, #eee 0%, #444 40%, #000 110%); -} - -div.classindex ul { - list-style: none; - padding-left: 0; -} - -div.classindex span.ai { - display: inline-block; -} - -div.groupHeader { - margin-left: 16px; - margin-top: 12px; - font-weight: bold; -} - -div.groupText { - margin-left: 16px; - font-style: italic; -} - -body { - background-color: white; - color: black; - margin: 0; -} - -div.contents { - margin-top: 10px; - margin-left: 12px; - margin-right: 8px; -} - -td.indexkey { - background-color: #EBEFF6; - font-weight: bold; - border: 1px solid #C4CFE5; - margin: 2px 0px 2px 0; - padding: 2px 10px; - white-space: nowrap; - vertical-align: top; -} - -td.indexvalue { - background-color: #EBEFF6; - border: 1px solid #C4CFE5; - padding: 2px 10px; - margin: 2px 0px; -} - -tr.memlist { - background-color: #EEF1F7; -} - -p.formulaDsp { - text-align: center; -} - -img.formulaDsp { - -} - -img.formulaInl, img.inline { - vertical-align: middle; -} - -div.center { - text-align: center; - margin-top: 0px; - margin-bottom: 0px; - padding: 0px; -} - -div.center img { - border: 0px; -} - -address.footer { - text-align: right; - padding-right: 12px; -} - -img.footer { - border: 0px; - vertical-align: middle; -} - -/* @group Code Colorization */ - -span.keyword { - color: #008000 -} - -span.keywordtype { - color: #604020 -} - -span.keywordflow { - color: #e08000 -} - -span.comment { - color: #800000 -} - -span.preprocessor { - color: #806020 -} - -span.stringliteral { - color: #002080 -} - -span.charliteral { - color: #008080 -} - -span.vhdldigit { - color: #ff00ff -} - -span.vhdlchar { - color: #000000 -} - -span.vhdlkeyword { - color: #700070 -} - -span.vhdllogic { - color: #ff0000 -} - -blockquote { - background-color: #F7F8FB; - border-left: 2px solid #9CAFD4; - margin: 0 24px 0 4px; - padding: 0 12px 0 16px; -} - -blockquote.DocNodeRTL { - border-left: 0; - border-right: 2px solid #9CAFD4; - margin: 0 4px 0 24px; - padding: 0 16px 0 12px; -} - -/* @end */ - -/* -.search { - color: #003399; - font-weight: bold; -} - -form.search { - margin-bottom: 0px; - margin-top: 0px; -} - -input.search { - font-size: 75%; - color: #000080; - font-weight: normal; - background-color: #e8eef2; -} -*/ - -td.tiny { - font-size: 75%; -} - -.dirtab { - padding: 4px; - border-collapse: collapse; - border: 1px solid #A3B4D7; -} - -th.dirtab { - background: #EBEFF6; - font-weight: bold; -} - -hr { - height: 0px; - border: none; - border-top: 1px solid #4A6AAA; -} - -hr.footer { - height: 1px; -} - -/* @group Member Descriptions */ - -table.memberdecls { - border-spacing: 0px; - padding: 0px; -} - -.memberdecls td, .fieldtable tr { - -webkit-transition-property: background-color, box-shadow; - -webkit-transition-duration: 0.5s; - -moz-transition-property: background-color, box-shadow; - -moz-transition-duration: 0.5s; - -ms-transition-property: background-color, box-shadow; - -ms-transition-duration: 0.5s; - -o-transition-property: background-color, box-shadow; - -o-transition-duration: 0.5s; - transition-property: background-color, box-shadow; - transition-duration: 0.5s; -} - -.memberdecls td.glow, .fieldtable tr.glow { - background-color: cyan; - box-shadow: 0 0 15px cyan; -} - -.mdescLeft, .mdescRight, -.memItemLeft, .memItemRight, -.memTemplItemLeft, .memTemplItemRight, .memTemplParams { - background-color: #F9FAFC; - border: none; - margin: 4px; - padding: 1px 0 0 8px; -} - -.mdescLeft, .mdescRight { - padding: 0px 8px 4px 8px; - color: #555; -} - -.memSeparator { - border-bottom: 1px solid #DEE4F0; - line-height: 1px; - margin: 0px; - padding: 0px; -} - -.memItemLeft, .memTemplItemLeft { - white-space: nowrap; -} - -.memItemRight { - width: 100%; -} - -.memTemplParams { - color: #4665A2; - white-space: nowrap; - font-size: 80%; -} - -/* @end */ - -/* @group Member Details */ - -/* Styles for detailed member documentation */ - -.memtitle { - padding: 8px; - border-top: 1px solid #A8B8D9; - border-left: 1px solid #A8B8D9; - border-right: 1px solid #A8B8D9; - border-top-right-radius: 4px; - border-top-left-radius: 4px; - margin-bottom: -1px; - background-image: url('nav_f.png'); - background-repeat: repeat-x; - background-color: #E2E8F2; - line-height: 1.25; - font-weight: 300; - float:left; -} - -.permalink -{ - font-size: 65%; - display: inline-block; - vertical-align: middle; -} - -.memtemplate { - font-size: 80%; - color: #4665A2; - font-weight: normal; - margin-left: 9px; -} - -.memnav { - background-color: #EBEFF6; - border: 1px solid #A3B4D7; - text-align: center; - margin: 2px; - margin-right: 15px; - padding: 2px; -} - -.mempage { - width: 100%; -} - -.memitem { - padding: 0; - margin-bottom: 10px; - margin-right: 5px; - -webkit-transition: box-shadow 0.5s linear; - -moz-transition: box-shadow 0.5s linear; - -ms-transition: box-shadow 0.5s linear; - -o-transition: box-shadow 0.5s linear; - transition: box-shadow 0.5s linear; - display: table !important; - width: 100%; -} - -.memitem.glow { - box-shadow: 0 0 15px cyan; -} - -.memname { - font-weight: 400; - margin-left: 6px; -} - -.memname td { - vertical-align: bottom; -} - -.memproto, dl.reflist dt { - border-top: 1px solid #A8B8D9; - border-left: 1px solid #A8B8D9; - border-right: 1px solid #A8B8D9; - padding: 6px 0px 6px 0px; - color: #253555; - font-weight: bold; - text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); - background-color: #DFE5F1; - /* opera specific markup */ - box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - border-top-right-radius: 4px; - /* firefox specific markup */ - -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; - -moz-border-radius-topright: 4px; - /* webkit specific markup */ - -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - -webkit-border-top-right-radius: 4px; - -} - -.overload { - font-family: "courier new",courier,monospace; - font-size: 65%; -} - -.memdoc, dl.reflist dd { - border-bottom: 1px solid #A8B8D9; - border-left: 1px solid #A8B8D9; - border-right: 1px solid #A8B8D9; - padding: 6px 10px 2px 10px; - background-color: #FBFCFD; - border-top-width: 0; - background-image:url('nav_g.png'); - background-repeat:repeat-x; - background-color: #FFFFFF; - /* opera specific markup */ - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; - box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - /* firefox specific markup */ - -moz-border-radius-bottomleft: 4px; - -moz-border-radius-bottomright: 4px; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px; - /* webkit specific markup */ - -webkit-border-bottom-left-radius: 4px; - -webkit-border-bottom-right-radius: 4px; - -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); -} - -dl.reflist dt { - padding: 5px; -} - -dl.reflist dd { - margin: 0px 0px 10px 0px; - padding: 5px; -} - -.paramkey { - text-align: right; -} - -.paramtype { - white-space: nowrap; -} - -.paramname { - color: #602020; - white-space: nowrap; -} -.paramname em { - font-style: normal; -} -.paramname code { - line-height: 14px; -} - -.params, .retval, .exception, .tparams { - margin-left: 0px; - padding-left: 0px; -} - -.params .paramname, .retval .paramname, .tparams .paramname { - font-weight: bold; - vertical-align: top; -} - -.params .paramtype, .tparams .paramtype { - font-style: italic; - vertical-align: top; -} - -.params .paramdir, .tparams .paramdir { - font-family: "courier new",courier,monospace; - vertical-align: top; -} - -table.mlabels { - border-spacing: 0px; -} - -td.mlabels-left { - width: 100%; - padding: 0px; -} - -td.mlabels-right { - vertical-align: bottom; - padding: 0px; - white-space: nowrap; -} - -span.mlabels { - margin-left: 8px; -} - -span.mlabel { - background-color: #728DC1; - border-top:1px solid #5373B4; - border-left:1px solid #5373B4; - border-right:1px solid #C4CFE5; - border-bottom:1px solid #C4CFE5; - text-shadow: none; - color: white; - margin-right: 4px; - padding: 2px 3px; - border-radius: 3px; - font-size: 7pt; - white-space: nowrap; - vertical-align: middle; -} - - - -/* @end */ - -/* these are for tree view inside a (index) page */ - -div.directory { - margin: 10px 0px; - border-top: 1px solid #9CAFD4; - border-bottom: 1px solid #9CAFD4; - width: 100%; -} - -.directory table { - border-collapse:collapse; -} - -.directory td { - margin: 0px; - padding: 0px; - vertical-align: top; -} - -.directory td.entry { - white-space: nowrap; - padding-right: 6px; - padding-top: 3px; -} - -.directory td.entry a { - outline:none; -} - -.directory td.entry a img { - border: none; -} - -.directory td.desc { - width: 100%; - padding-left: 6px; - padding-right: 6px; - padding-top: 3px; - border-left: 1px solid rgba(0,0,0,0.05); -} - -.directory tr.even { - padding-left: 6px; - background-color: #F7F8FB; -} - -.directory img { - vertical-align: -30%; -} - -.directory .levels { - white-space: nowrap; - width: 100%; - text-align: right; - font-size: 9pt; -} - -.directory .levels span { - cursor: pointer; - padding-left: 2px; - padding-right: 2px; - color: #3D578C; -} - -.arrow { - color: #9CAFD4; - -webkit-user-select: none; - -khtml-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; - cursor: pointer; - font-size: 80%; - display: inline-block; - width: 16px; - height: 22px; -} - -.icon { - font-family: Arial, Helvetica; - font-weight: bold; - font-size: 12px; - height: 14px; - width: 16px; - display: inline-block; - background-color: #728DC1; - color: white; - text-align: center; - border-radius: 4px; - margin-left: 2px; - margin-right: 2px; -} - -.icona { - width: 24px; - height: 22px; - display: inline-block; -} - -.iconfopen { - width: 24px; - height: 18px; - margin-bottom: 4px; - background-image:url('folderopen.png'); - background-position: 0px -4px; - background-repeat: repeat-y; - vertical-align:top; - display: inline-block; -} - -.iconfclosed { - width: 24px; - height: 18px; - margin-bottom: 4px; - background-image:url('folderclosed.png'); - background-position: 0px -4px; - background-repeat: repeat-y; - vertical-align:top; - display: inline-block; -} - -.icondoc { - width: 24px; - height: 18px; - margin-bottom: 4px; - background-image:url('doc.png'); - background-position: 0px -4px; - background-repeat: repeat-y; - vertical-align:top; - display: inline-block; -} - -table.directory { - font: 400 14px Roboto,sans-serif; -} - -/* @end */ - -div.dynheader { - margin-top: 8px; - -webkit-touch-callout: none; - -webkit-user-select: none; - -khtml-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -address { - font-style: normal; - color: #2A3D61; -} - -table.doxtable caption { - caption-side: top; -} - -table.doxtable { - border-collapse:collapse; - margin-top: 4px; - margin-bottom: 4px; -} - -table.doxtable td, table.doxtable th { - border: 1px solid #2D4068; - padding: 3px 7px 2px; -} - -table.doxtable th { - background-color: #374F7F; - color: #FFFFFF; - font-size: 110%; - padding-bottom: 4px; - padding-top: 5px; -} - -table.fieldtable { - /*width: 100%;*/ - margin-bottom: 10px; - border: 1px solid #A8B8D9; - border-spacing: 0px; - -moz-border-radius: 4px; - -webkit-border-radius: 4px; - border-radius: 4px; - -moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px; - -webkit-box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15); - box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15); -} - -.fieldtable td, .fieldtable th { - padding: 3px 7px 2px; -} - -.fieldtable td.fieldtype, .fieldtable td.fieldname { - white-space: nowrap; - border-right: 1px solid #A8B8D9; - border-bottom: 1px solid #A8B8D9; - vertical-align: top; -} - -.fieldtable td.fieldname { - padding-top: 3px; -} - -.fieldtable td.fielddoc { - border-bottom: 1px solid #A8B8D9; - /*width: 100%;*/ -} - -.fieldtable td.fielddoc p:first-child { - margin-top: 0px; -} - -.fieldtable td.fielddoc p:last-child { - margin-bottom: 2px; -} - -.fieldtable tr:last-child td { - border-bottom: none; -} - -.fieldtable th { - background-image:url('nav_f.png'); - background-repeat:repeat-x; - background-color: #E2E8F2; - font-size: 90%; - color: #253555; - padding-bottom: 4px; - padding-top: 5px; - text-align:left; - font-weight: 400; - -moz-border-radius-topleft: 4px; - -moz-border-radius-topright: 4px; - -webkit-border-top-left-radius: 4px; - -webkit-border-top-right-radius: 4px; - border-top-left-radius: 4px; - border-top-right-radius: 4px; - border-bottom: 1px solid #A8B8D9; -} - - -.tabsearch { - top: 0px; - left: 10px; - height: 36px; - background-image: url('tab_b.png'); - z-index: 101; - overflow: hidden; - font-size: 13px; -} - -.navpath ul -{ - font-size: 11px; - background-image:url('tab_b.png'); - background-repeat:repeat-x; - background-position: 0 -5px; - height:30px; - line-height:30px; - color:#8AA0CC; - border:solid 1px #C2CDE4; - overflow:hidden; - margin:0px; - padding:0px; -} - -.navpath li -{ - list-style-type:none; - float:left; - padding-left:10px; - padding-right:15px; - background-image:url('bc_s.png'); - background-repeat:no-repeat; - background-position:right; - color:#364D7C; -} - -.navpath li.navelem a -{ - height:32px; - display:block; - text-decoration: none; - outline: none; - color: #283A5D; - font-family: 'Lucida Grande',Geneva,Helvetica,Arial,sans-serif; - text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9); - text-decoration: none; -} - -.navpath li.navelem a:hover -{ - color:#6884BD; -} - -.navpath li.footer -{ - list-style-type:none; - float:right; - padding-left:10px; - padding-right:15px; - background-image:none; - background-repeat:no-repeat; - background-position:right; - color:#364D7C; - font-size: 8pt; -} - - -div.summary -{ - float: right; - font-size: 8pt; - padding-right: 5px; - width: 50%; - text-align: right; -} - -div.summary a -{ - white-space: nowrap; -} - -table.classindex -{ - margin: 10px; - white-space: nowrap; - margin-left: 3%; - margin-right: 3%; - width: 94%; - border: 0; - border-spacing: 0; - padding: 0; -} - -div.ingroups -{ - font-size: 8pt; - width: 50%; - text-align: left; -} - -div.ingroups a -{ - white-space: nowrap; -} - -div.header -{ - background-image:url('nav_h.png'); - background-repeat:repeat-x; - background-color: #F9FAFC; - margin: 0px; - border-bottom: 1px solid #C4CFE5; -} - -div.headertitle -{ - padding: 5px 5px 5px 10px; -} - -.PageDocRTL-title div.headertitle { - text-align: right; - direction: rtl; -} - -dl { - padding: 0 0 0 0; -} - -/* dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug, dl.examples */ -dl.section { - margin-left: 0px; - padding-left: 0px; -} - -dl.section.DocNodeRTL { - margin-right: 0px; - padding-right: 0px; -} - -dl.note { - margin-left: -7px; - padding-left: 3px; - border-left: 4px solid; - border-color: #D0C000; -} - -dl.note.DocNodeRTL { - margin-left: 0; - padding-left: 0; - border-left: 0; - margin-right: -7px; - padding-right: 3px; - border-right: 4px solid; - border-color: #D0C000; -} - -dl.warning, dl.attention { - margin-left: -7px; - padding-left: 3px; - border-left: 4px solid; - border-color: #FF0000; -} - -dl.warning.DocNodeRTL, dl.attention.DocNodeRTL { - margin-left: 0; - padding-left: 0; - border-left: 0; - margin-right: -7px; - padding-right: 3px; - border-right: 4px solid; - border-color: #FF0000; -} - -dl.pre, dl.post, dl.invariant { - margin-left: -7px; - padding-left: 3px; - border-left: 4px solid; - border-color: #00D000; -} - -dl.pre.DocNodeRTL, dl.post.DocNodeRTL, dl.invariant.DocNodeRTL { - margin-left: 0; - padding-left: 0; - border-left: 0; - margin-right: -7px; - padding-right: 3px; - border-right: 4px solid; - border-color: #00D000; -} - -dl.deprecated { - margin-left: -7px; - padding-left: 3px; - border-left: 4px solid; - border-color: #505050; -} - -dl.deprecated.DocNodeRTL { - margin-left: 0; - padding-left: 0; - border-left: 0; - margin-right: -7px; - padding-right: 3px; - border-right: 4px solid; - border-color: #505050; -} - -dl.todo { - margin-left: -7px; - padding-left: 3px; - border-left: 4px solid; - border-color: #00C0E0; -} - -dl.todo.DocNodeRTL { - margin-left: 0; - padding-left: 0; - border-left: 0; - margin-right: -7px; - padding-right: 3px; - border-right: 4px solid; - border-color: #00C0E0; -} - -dl.test { - margin-left: -7px; - padding-left: 3px; - border-left: 4px solid; - border-color: #3030E0; -} - -dl.test.DocNodeRTL { - margin-left: 0; - padding-left: 0; - border-left: 0; - margin-right: -7px; - padding-right: 3px; - border-right: 4px solid; - border-color: #3030E0; -} - -dl.bug { - margin-left: -7px; - padding-left: 3px; - border-left: 4px solid; - border-color: #C08050; -} - -dl.bug.DocNodeRTL { - margin-left: 0; - padding-left: 0; - border-left: 0; - margin-right: -7px; - padding-right: 3px; - border-right: 4px solid; - border-color: #C08050; -} - -dl.section dd { - margin-bottom: 6px; -} - - -#projectlogo -{ - text-align: center; - vertical-align: bottom; - border-collapse: separate; -} - -#projectlogo img -{ - border: 0px none; -} - -#projectalign -{ - vertical-align: middle; -} - -#projectname -{ - font: 300% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 2px 0px; -} - -#projectbrief -{ - font: 120% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#projectnumber -{ - font: 50% Tahoma, Arial,sans-serif; - margin: 0px; - padding: 0px; -} - -#titlearea -{ - padding: 0px; - margin: 0px; - width: 100%; - border-bottom: 1px solid #5373B4; -} - -.image -{ - text-align: center; -} - -.dotgraph -{ - text-align: center; -} - -.mscgraph -{ - text-align: center; -} - -.plantumlgraph -{ - text-align: center; -} - -.diagraph -{ - text-align: center; -} - -.caption -{ - font-weight: bold; -} - -div.zoom -{ - border: 1px solid #90A5CE; -} - -dl.citelist { - margin-bottom:50px; -} - -dl.citelist dt { - color:#334975; - float:left; - font-weight:bold; - margin-right:10px; - padding:5px; -} - -dl.citelist dd { - margin:2px 0; - padding:5px 0; -} - -div.toc { - padding: 14px 25px; - background-color: #F4F6FA; - border: 1px solid #D8DFEE; - border-radius: 7px 7px 7px 7px; - float: right; - height: auto; - margin: 0 8px 10px 10px; - width: 200px; -} - -.PageDocRTL-title div.toc { - float: left !important; - text-align: right; -} - -div.toc li { - background: url("bdwn.png") no-repeat scroll 0 5px transparent; - font: 10px/1.2 Verdana,DejaVu Sans,Geneva,sans-serif; - margin-top: 5px; - padding-left: 10px; - padding-top: 2px; -} - -.PageDocRTL-title div.toc li { - background-position-x: right !important; - padding-left: 0 !important; - padding-right: 10px; -} - -div.toc h3 { - font: bold 12px/1.2 Arial,FreeSans,sans-serif; - color: #4665A2; - border-bottom: 0 none; - margin: 0; -} - -div.toc ul { - list-style: none outside none; - border: medium none; - padding: 0px; -} - -div.toc li.level1 { - margin-left: 0px; -} - -div.toc li.level2 { - margin-left: 15px; -} - -div.toc li.level3 { - margin-left: 30px; -} - -div.toc li.level4 { - margin-left: 45px; -} - -.PageDocRTL-title div.toc li.level1 { - margin-left: 0 !important; - margin-right: 0; -} - -.PageDocRTL-title div.toc li.level2 { - margin-left: 0 !important; - margin-right: 15px; -} - -.PageDocRTL-title div.toc li.level3 { - margin-left: 0 !important; - margin-right: 30px; -} - -.PageDocRTL-title div.toc li.level4 { - margin-left: 0 !important; - margin-right: 45px; -} - -.inherit_header { - font-weight: bold; - color: gray; - cursor: pointer; - -webkit-touch-callout: none; - -webkit-user-select: none; - -khtml-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; -} - -.inherit_header td { - padding: 6px 0px 2px 5px; -} - -.inherit { - display: none; -} - -tr.heading h2 { - margin-top: 12px; - margin-bottom: 4px; -} - -/* tooltip related style info */ - -.ttc { - position: absolute; - display: none; -} - -#powerTip { - cursor: default; - white-space: nowrap; - background-color: white; - border: 1px solid gray; - border-radius: 4px 4px 4px 4px; - box-shadow: 1px 1px 7px gray; - display: none; - font-size: smaller; - max-width: 80%; - opacity: 0.9; - padding: 1ex 1em 1em; - position: absolute; - z-index: 2147483647; -} - -#powerTip div.ttdoc { - color: grey; - font-style: italic; -} - -#powerTip div.ttname a { - font-weight: bold; -} - -#powerTip div.ttname { - font-weight: bold; -} - -#powerTip div.ttdeci { - color: #006318; -} - -#powerTip div { - margin: 0px; - padding: 0px; - font: 12px/16px Roboto,sans-serif; -} - -#powerTip:before, #powerTip:after { - content: ""; - position: absolute; - margin: 0px; -} - -#powerTip.n:after, #powerTip.n:before, -#powerTip.s:after, #powerTip.s:before, -#powerTip.w:after, #powerTip.w:before, -#powerTip.e:after, #powerTip.e:before, -#powerTip.ne:after, #powerTip.ne:before, -#powerTip.se:after, #powerTip.se:before, -#powerTip.nw:after, #powerTip.nw:before, -#powerTip.sw:after, #powerTip.sw:before { - border: solid transparent; - content: " "; - height: 0; - width: 0; - position: absolute; -} - -#powerTip.n:after, #powerTip.s:after, -#powerTip.w:after, #powerTip.e:after, -#powerTip.nw:after, #powerTip.ne:after, -#powerTip.sw:after, #powerTip.se:after { - border-color: rgba(255, 255, 255, 0); -} - -#powerTip.n:before, #powerTip.s:before, -#powerTip.w:before, #powerTip.e:before, -#powerTip.nw:before, #powerTip.ne:before, -#powerTip.sw:before, #powerTip.se:before { - border-color: rgba(128, 128, 128, 0); -} - -#powerTip.n:after, #powerTip.n:before, -#powerTip.ne:after, #powerTip.ne:before, -#powerTip.nw:after, #powerTip.nw:before { - top: 100%; -} - -#powerTip.n:after, #powerTip.ne:after, #powerTip.nw:after { - border-top-color: #FFFFFF; - border-width: 10px; - margin: 0px -10px; -} -#powerTip.n:before { - border-top-color: #808080; - border-width: 11px; - margin: 0px -11px; -} -#powerTip.n:after, #powerTip.n:before { - left: 50%; -} - -#powerTip.nw:after, #powerTip.nw:before { - right: 14px; -} - -#powerTip.ne:after, #powerTip.ne:before { - left: 14px; -} - -#powerTip.s:after, #powerTip.s:before, -#powerTip.se:after, #powerTip.se:before, -#powerTip.sw:after, #powerTip.sw:before { - bottom: 100%; -} - -#powerTip.s:after, #powerTip.se:after, #powerTip.sw:after { - border-bottom-color: #FFFFFF; - border-width: 10px; - margin: 0px -10px; -} - -#powerTip.s:before, #powerTip.se:before, #powerTip.sw:before { - border-bottom-color: #808080; - border-width: 11px; - margin: 0px -11px; -} - -#powerTip.s:after, #powerTip.s:before { - left: 50%; -} - -#powerTip.sw:after, #powerTip.sw:before { - right: 14px; -} - -#powerTip.se:after, #powerTip.se:before { - left: 14px; -} - -#powerTip.e:after, #powerTip.e:before { - left: 100%; -} -#powerTip.e:after { - border-left-color: #FFFFFF; - border-width: 10px; - top: 50%; - margin-top: -10px; -} -#powerTip.e:before { - border-left-color: #808080; - border-width: 11px; - top: 50%; - margin-top: -11px; -} - -#powerTip.w:after, #powerTip.w:before { - right: 100%; -} -#powerTip.w:after { - border-right-color: #FFFFFF; - border-width: 10px; - top: 50%; - margin-top: -10px; -} -#powerTip.w:before { - border-right-color: #808080; - border-width: 11px; - top: 50%; - margin-top: -11px; -} - -@media print -{ - #top { display: none; } - #side-nav { display: none; } - #nav-path { display: none; } - body { overflow:visible; } - h1, h2, h3, h4, h5, h6 { page-break-after: avoid; } - .summary { display: none; } - .memitem { page-break-inside: avoid; } - #doc-content - { - margin-left:0 !important; - height:auto !important; - width:auto !important; - overflow:inherit; - display:inline; - } -} - -/* @group Markdown */ - -/* -table.markdownTable { - border-collapse:collapse; - margin-top: 4px; - margin-bottom: 4px; -} - -table.markdownTable td, table.markdownTable th { - border: 1px solid #2D4068; - padding: 3px 7px 2px; -} - -table.markdownTableHead tr { -} - -table.markdownTableBodyLeft td, table.markdownTable th { - border: 1px solid #2D4068; - padding: 3px 7px 2px; -} - -th.markdownTableHeadLeft th.markdownTableHeadRight th.markdownTableHeadCenter th.markdownTableHeadNone { - background-color: #374F7F; - color: #FFFFFF; - font-size: 110%; - padding-bottom: 4px; - padding-top: 5px; -} - -th.markdownTableHeadLeft { - text-align: left -} - -th.markdownTableHeadRight { - text-align: right -} - -th.markdownTableHeadCenter { - text-align: center -} -*/ - -table.markdownTable { - border-collapse:collapse; - margin-top: 4px; - margin-bottom: 4px; -} - -table.markdownTable td, table.markdownTable th { - border: 1px solid #2D4068; - padding: 3px 7px 2px; -} - -table.markdownTable tr { -} - -th.markdownTableHeadLeft, th.markdownTableHeadRight, th.markdownTableHeadCenter, th.markdownTableHeadNone { - background-color: #374F7F; - color: #FFFFFF; - font-size: 110%; - padding-bottom: 4px; - padding-top: 5px; -} - -th.markdownTableHeadLeft, td.markdownTableBodyLeft { - text-align: left -} - -th.markdownTableHeadRight, td.markdownTableBodyRight { - text-align: right -} - -th.markdownTableHeadCenter, td.markdownTableBodyCenter { - text-align: center -} - -.DocNodeRTL { - text-align: right; - direction: rtl; -} - -.DocNodeLTR { - text-align: left; - direction: ltr; -} - -table.DocNodeRTL { - width: auto; - margin-right: 0; - margin-left: auto; -} - -table.DocNodeLTR { - width: auto; - margin-right: auto; - margin-left: 0; -} - -tt, code, kbd, samp -{ - display: inline-block; - direction:ltr; -} -/* @end */ - -u { - text-decoration: underline; -} diff --git a/Documentation/Doxygen/ImageSimilarityMetrics.dox b/Documentation/Doxygen/ImageSimilarityMetrics.dox index fdbe93e9b26..8a7ccaaabcf 100644 --- a/Documentation/Doxygen/ImageSimilarityMetrics.dox +++ b/Documentation/Doxygen/ImageSimilarityMetrics.dox @@ -1,8 +1,8 @@ /** \page ImageSimilarityMetricsPage Image Similarity Metrics - -\section MetricsIntroduction Introduction + +\section MetricsIntroduction Introduction It is a common task in image analysis to require to compare how similar two image might be. This comparison may be limited to a @@ -23,7 +23,7 @@ in a toolkit. You need a set of them because none is able to perform the same job as the other. The following table presents a comparison between image similarity -metrics. This is by no means an exhaustive comparison but will at +metrics. This is by no means an exhaustive comparison but will at least provide some guidance as to what metric can be appropiated for particular problems. diff --git a/Documentation/Doxygen/Iterators.dox b/Documentation/Doxygen/Iterators.dox index 247509ad542..55ac56effb4 100644 --- a/Documentation/Doxygen/Iterators.dox +++ b/Documentation/Doxygen/Iterators.dox @@ -33,7 +33,7 @@ \code - ForAllThePixels p in image Do p = 100 + ForAllThePixels p in image Do p = 10 \endcode @@ -140,7 +140,7 @@ Another group of iterators support a moving neighborhood. Here the neighborhood can "iterate" over an image and a calculation can iterate over the neighborhood. This allows N-dimensional implementations of - convolution and finite differences to be implemented succintly. + convolution and finite differences to be implemented succinctly. This class of iterators is described in detail on the page \ref NeighborhoodIteratorsPage. @@ -198,19 +198,19 @@ iterators that can walk a region defined by a spatial function.) The region for an iterator is defined at constructor time. Regions are not validated, so the programmer is responsible for assigning a - region that is within the image. Iterator methods Begin() and End() + region that is within the image. Iterator methods `Begin()` and `End()` are defined relative to the region. See below. \section IteratorAPI Iterator API \subsection IteratorsPositioning Position - \subsection IteratorsIntervals Half Open Intervals - Begin/End + \subsection IteratorsIntervals Half Open Intervals - `Begin`/`End` Like most iterator implementations, ImageIterators walk a half-open - interval. Begin is defined as the first pixel in the region. End is + interval. `Begin` is defined as the first pixel in the region. `End` is defined as one pixel past the last pixel in the region (one pixel - past in the same row). So Begin points a valid pixel in the region - and End points to a pixel that is outside the region. + past in the same row). So `Begin` points a valid pixel in the region + and `End` points to a pixel that is outside the region. \subsection IteratorsDereferencing Dereferencing @@ -220,51 +220,51 @@ \code PixelType * p; // creation of the pointer - *p = 100; // write access to a data + *p = 10; // write access to a data PixelType a = *p; // read access to data \endcode Iterators dereference data using Set() and Get() \code - imageIterator.Set( 100 ); + imageIterator.Set( 10 ); PixelType a = imageIterator.Get(); \endcode - \subsection IteratorsOperatorPlusPlus operator++ + \subsection IteratorsOperatorPlusPlus `operator++` - The ++ operator will move the image iterator to the next pixel, + The `++ operator` will move the image iterator to the next pixel, according to the particular order in which this iterator walks - the imaage. + the image. - \subsection IteratorsOperatorMinusMinus operator-- + \subsection IteratorsOperatorMinusMinus `operator--` - The -- operator will move the image iterator to the previous pixel, + The `-- operator` will move the image iterator to the previous pixel, according to the particular order in which this iterator walks - the imaage. + the image. - \subsection IteratorsIteratorsBegin Begin() - Begin() returns an iterator for the same image and region as the current + \subsection IteratorsIteratorsBegin `Begin()` + `Begin()` returns an iterator for the same image and region as the current iterator but positioned at the first pixel in the region. The current iterator is not modified. - \subsection IteratorsIteratorsEnd End() - End() returns an iterator for the same image and region as the current + \subsection IteratorsIteratorsEnd `End()` + `End()` returns an iterator for the same image and region as the current iterator but positioned one pixel past the last pixel in the region. The current iterator is not modified. - \subsection IteratorsIteratorsGotoBegin GotoBegin() - GotoBegin() repositions the iterator to the first pixel in the region. + \subsection IteratorsIteratorsGotoBegin `GotoBegin()` + `GotoBegin()` repositions the iterator to the first pixel in the region. - \subsection IteratorsGotoEnd GotoEnd() - GotoEnd() repositions the iterator to one pixel past (in the same + \subsection IteratorsGotoEnd `GotoEnd()` + `GotoEnd()` repositions the iterator to one pixel past (in the same row) the last pixel in the region. - \subsection IteratorsIsAtBegin IsAtBegin() - IsAtBegin() returns true if the iterator is positioned at the first - pixel in the region, returns false otherwise. IsAtBegin() is faster than - comparing an iterator for equivalence to the iterator returned by Begion(). + \subsection IteratorsIsAtBegin `IsAtBegin()` + `IsAtBegin()` returns true if the iterator is positioned at the first + pixel in the region, returns false otherwise. `IsAtBegin()` is faster than + comparing an iterator for equivalence to the iterator returned by `Begin()`. \code if (it.IsAtBegin()) {} // Fast @@ -272,11 +272,11 @@ if (it == it.Begin()) {} // Slow \endcode - \subsection IteratorsIsAtEnd IsAtEnd() - IsAtEnd() returns true if the iterator is positioned one pixel past - the last pixel in the region, returns false otherwise. IsAtEnd() + \subsection IteratorsIsAtEnd `IsAtEnd()` + `IsAtEnd()` returns true if the iterator is positioned one pixel past + the last pixel in the region, returns false otherwise. `IsAtEnd()` is faster than comparing an iterator for equivalence to the iterator - returned by End(). + returned by `End()`. \code if (it.IsAtEnd()) {} // Fast @@ -298,4 +298,3 @@ */ - diff --git a/Documentation/Doxygen/MainPage.dox b/Documentation/Doxygen/MainPage.dox index bbf7951c038..2d0c889abc7 100644 --- a/Documentation/Doxygen/MainPage.dox +++ b/Documentation/Doxygen/MainPage.dox @@ -2,7 +2,7 @@ * * \mainpage Insight Toolkit * - * \image html itkLogo.png + * \image html itkLogo.png width=50% height=50% * * \section intro Introduction * @@ -37,4 +37,3 @@ * iterators. * */ - diff --git a/Documentation/Doxygen/Modules.dox b/Documentation/Doxygen/Modules.dox index b5ed15b5366..32863e2c796 100644 --- a/Documentation/Doxygen/Modules.dox +++ b/Documentation/Doxygen/Modules.dox @@ -139,7 +139,7 @@ /** - \ defgroup ImageEnhancement Image Enhancement Filters + \defgroup ImageEnhancement Image Enhancement Filters \ingroup ImageFilters Image enhancement filters process an image to enhance the appearance @@ -609,7 +609,7 @@ \defgroup Deprecated Deprecated Classes Classes that are scheduled to be removed from the toolkit. Their - funcionality is now provided by other classes or changes in the toolkit have + functionality is now provided by other classes or changes in the toolkit have made them useless. Please report to their documentation and look in to their "Deprecated" section. This section should indicate what to do to replace this class in any affected code. diff --git a/Documentation/Doxygen/NeighborhoodIterators.dox b/Documentation/Doxygen/NeighborhoodIterators.dox index 9e1394e0d8e..82a46ea056f 100644 --- a/Documentation/Doxygen/NeighborhoodIterators.dox +++ b/Documentation/Doxygen/NeighborhoodIterators.dox @@ -5,7 +5,7 @@ This document provides a general overview of the intended use of the NeighborhoodIterator classes and their associated objects for low-level image processing in Itk. For a more detailed description of the API, please refer to -the inline Itk documentation and manual. +the inline Itk documentation and manual. \par Neighborhood iterators are the abstraction of the concept of \em locality in @@ -25,16 +25,16 @@ This code in classical \em texbook notation can look like: int nx = 512; int ny = 512; ImageType image(nx,ny); - for(int x=1; xGetRequestedRegion()); 15 ImageIterator out(output_image, output_image->GetRequestedRegion()); 16 @@ -86,32 +86,32 @@ have been omitted for clarity. ) 19 { 20 float accum = 0.0; 21 for (unsigned int i = 0; i < it.Size(); ++i) -22 { -23 accum += it.GetPixel(i); +22 { +23 accum += it.GetPixel(i); 24 } 25 out.Set(accum/(float)(it.Size())); 26 } \endcode -\par +\par Note that the computational work is confined to lines 18-26. The code is also completely generalized for multiple dimensions. For example, changing line 1 to: \code 1 using ImageType = itk::Image; \endcode -produces an averaging filter for five-dimensional images. +produces an averaging filter for five-dimensional images. \par The values in the neighborhood are dereferenced through the GetPixel(n) method -of the iterator. Think of the iterator as a C array, storing neighborhood +of the iterator. Think of the iterator as a C array, storing neighborhood values in the same order that they are stored in the image, with the lowest dimension as the fastest increasing dimension. \section OperatorsOperationsSection Neighborhood operators and operations NeighborhoodOperators are container classes for generating and storing computational kernels such as LaPlacian, Gaussian, derivative, and -morphological operators. They provide a generalized interface for creation and +morphological operators. They provide a generalized interface for creation and access of the operator coefficients. \par @@ -129,7 +129,7 @@ demonstrates this concept. 4 NeighborhoodInnerProduct IP; 5 6 out = out.Begin(); -7 for (it.SetToBegin(); it != it.End(); ++it, ++out) +7 for (it.SetToBegin(); it != it.End(); ++it, ++out) 8 { 9 out.Set( IP( it, OP) ); 10 } @@ -144,7 +144,7 @@ operator/operation model. The mean calculation above is one example. A 1 NeighborhoodIterator::RadiusType radius = {1, 0, 0}; 2 NeighborhoodIterator it(radius, inputImage, regionToProcess) 3 ImageRegionIterator out( outputImage, regionToProcess ); -4 for (it.SetToBegin(); it != it.End(); ++it, ++out) +4 for (it.SetToBegin(); it != it.End(); ++it, ++out) 5 { 6 out.Set( it.GetPixel(3) - it.GetPixel(2) ); 7 } @@ -155,7 +155,7 @@ In this example the neighborhood is defined as a three pixel strip with width along only the first axis. Mapping the spatial orientation of neighborhood pixels to the array location is the responsibility of the code writer. Some methods such as GetStride(n), which -returns the stride length in pixels along an axis n, have been provided to help +returns the stride length in pixels along an axis n, have been provided to help in coding algorithms for arbitrary dimensionality. The index of the center pixel in a neighborhood is always Size()/2. @@ -171,17 +171,17 @@ is appropriate for their algorithm. \par A SmartNeighborhoodIterator can be used in place of NeighborhoodIterator to iterate over an entire image region, but it will incur a penalty on -performance. For this reason, it is desirable to process the image differently +performance. For this reason, it is desirable to process the image differently over distinct boundary and non-boundary regions. Itk's definition of image regions makes this easy to manage. The process is as follows: first apply the algorithm over all neighborhoods not on the image boundary using the fast NeighborhoodIterator, then process each region on the boundary using the -SmartNeighborhoodIterator. The size of the boundary regions are defined by the +SmartNeighborhoodIterator. The size of the boundary regions are defined by the radius of the neighborhood that you are using. \par Rewriting the inner product code using this approach looks like the following. -(Here we are using the default SmartNeighborhoodIterator boundary condition and +(Here we are using the default SmartNeighborhoodIterator boundary condition and omitting some template parameters for simplicity.) \code @@ -205,7 +205,7 @@ out = ImageIterator(outputImage, *regions_iterator); NeighborhoodIterator it (OP.GetRadius(), inputImage, *regions_iterator); NeighborhoodInnerProduct IP; out = out.Begin(); -for (it.SetToBegin(); it != it.End(); ++it, ++out) +for (it.SetToBegin(); it != it.End(); ++it, ++out) { out.Set( IP( it, OP) ); } @@ -219,7 +219,7 @@ for (regions_iterator++ ; regions_iterator != regions.end(); regions_iterator++) { out = ImageIterator(outputImage, *regions_iterator); sit = SmartNeighborhoodIterator(OP.GetRadius(), inputImage, *regions_iterator); - for (sit.SetToBegin(); sit != sit.End(); ++sit, ++out) + for (sit.SetToBegin(); sit != sit.End(); ++sit, ++out) { out.Set( SIP( sit, OP) ); } @@ -242,7 +242,7 @@ AnisotropicDiffusionFunctions and the morphological image filters. itk::WatershedSegmenter also makes extensive use of the neighborhood iterators. -\par +\par The best documentation of the API for these objects is are the class definitions themselves, since the API is subject to change as the toolkit matures and is refined. diff --git a/Documentation/Doxygen/Registration.dox b/Documentation/Doxygen/Registration.dox index 53f8028fac7..0a7d1b735c7 100644 --- a/Documentation/Doxygen/Registration.dox +++ b/Documentation/Doxygen/Registration.dox @@ -1,10 +1,10 @@ /** \page RegistrationPage Registration Techniques - -\section RegistrationIntroduction Introduction -\b Registration is a technique aimed to align two objects using a +\section RegistrationIntroduction Introduction + +\b Registration is a technique aimed to align two objects using a particular transformation. A typical example of registration is to have two medical images @@ -15,7 +15,7 @@ a spatial transformation to find the corresponding pixel from one image into the other. Another typical example of registration is to have a geometrical model -of an organ, let's say a bone. This model can be used to find the +of an organ, let's say a bone. This model can be used to find the corresponding structure in a medical image. In this case, a spatial transformation is needed to find the correct location of the structure in the image. @@ -23,7 +23,7 @@ in the image. \section RegistrationFramework ITK Registration Framework -The Insight Toolkit takes full advantage of the power provided by +The Insight Toolkit takes full advantage of the power provided by generic programming. Thanks to that, it have been possible to create an abstraction of the particular problems that the toolkit is intended to solve. @@ -58,7 +58,7 @@ This is a rapid description of the transforms implemented in the toolkit \li \b Rigid3D: This transform is specific for 3D, it supports only rotations and translations. Rotations are represented using \e Quaternions. -\li \b Rigid3DPerspective: A composition of a \e Rigid3D transform followed by a perpective projection. This transformation is intended to be used in applications like X-Rays projections. +\li \b Rigid3DPerspective: A composition of a \e Rigid3D transform followed by a perspective projection. This transformation is intended to be used in applications like X-Rays projections. \li \b Translation: A N-Dimensional translation internally represented as a vector. @@ -95,7 +95,7 @@ The following optimization methods are available: \li Amoeba : Nelder Meade Downhill Simplex. -\li One Plus One Evolutionary : Stategy that simulates the biological evolution of a set of samples in the search space. +\li One Plus One Evolutionary : Strategy that simulates the biological evolution of a set of samples in the search space. @@ -105,6 +105,6 @@ The evaluation of a metric can be very expensive in computing time. An approach It is usual to create first a sequence of reduced resolution version of the objects, this set of objects is called a pryramid representation . A Multiresolution method is basically a set of consecutive registration process, each one performed at a particular level of the pyramid, and using as initial transform the resulting transform of the previous process. -Multiresolution offers the double advantage of increasing performance and at the same time improving the stability of the optimization by smoothing out local minima and increasing the capture region of the process. +Multiresolution offers the double advantage of increasing performance and at the same time improving the stability of the optimization by smoothing out local minima and increasing the capture region of the process. */ diff --git a/Documentation/Doxygen/Streaming.dox b/Documentation/Doxygen/Streaming.dox index 4c13a1cf3ed..4d29de4100b 100644 --- a/Documentation/Doxygen/Streaming.dox +++ b/Documentation/Doxygen/Streaming.dox @@ -2,7 +2,7 @@ \page StreamingPage Streaming \section StreamingIntroduction Introduction - + \image html Streaming.gif "Pipelines can be set up to stream data through filters in small pieces." diff --git a/Documentation/Doxygen/Threading.dox b/Documentation/Doxygen/Threading.dox index 113a16dcbe1..6b60ec32511 100644 --- a/Documentation/Doxygen/Threading.dox +++ b/Documentation/Doxygen/Threading.dox @@ -2,7 +2,7 @@ \page ThreadingPage Threading \section ThreadingIntroduction Introduction - + ITK is designed to run in multiprocessor environments. Many of ITK's filters are multithreaded. When a multithreading filter executes, it automatically divides the work amongst multiprocessors @@ -15,7 +15,7 @@ \image html Threading.gif "Filters may process their data in multiple threads in a shared memory configuration." \section FilterThreadSafety Filter Level Multithreading - + A multithreaded filter provides an implementation of the ThreadedGenerateData() method (see itk::ImageSource::ThreadedGenerateData()) as opposed to the @@ -41,7 +41,7 @@ the threads write to this same block of memory but a given thread is only allowed to set specific pixels. - \subsection FilterMemoryAllocation Memory Management + \subsection FilterMemoryAllocation Memory Management The GenerateData() method is responsible for allocation the output bulk data. For an image processing filter, this corresponds to @@ -76,10 +76,10 @@ ITK is designed so that different instances of the same class can be accessed in different execution threads. But multiple threads should - not attempt to modify a single instance. This granularity of thread + not attempt to modify a single instance. This granularity of thread safety was chosen as a compromise between performance and flexibility. If we allow ITK objects to be modified in multiple threads then ITK - would have to mutex every access to every instance variable of a + would have to mutex every access to every instance variable of a class. This would severely affect performance. \section NumericsThreadSafety Thread Safety in the Numerics Library diff --git a/Documentation/Doxygen/doxygen.bib b/Documentation/Doxygen/doxygen.bib new file mode 100644 index 00000000000..3ed8000b62e --- /dev/null +++ b/Documentation/Doxygen/doxygen.bib @@ -0,0 +1,2351 @@ +@book{abramowitz1972, + title = {Handbook of Mathematical Functions: with Formulas, Graphs, and Mathematical Tables}, + author = {Milton Abramowitz and Irene A. Stegun}, + year = 1972, + publisher = {John Wiley & Sons, New York.} +} +@article{alyassin1994, + title = {Evaluation of new algorithms for the interactive measurement of surface area and volume}, + author = {Alyassin, Abdalmajeid M. and Lancaster, Jack L. and Downs III, J. Hunter and Fox, Peter T.}, + year = 1994, + journal = {Med Phys}, + volume = 21, + number = 6, + pages = {741--752}, + doi = {10.1118/1.597333}, + url = {https://doi.org/10.1118/1.597333} +} +@article{ashburner2007, + title = {A fast diffeomorphic image registration algorithm}, + author = {John Ashburner}, + year = 2007, + journal = {NeuroImage}, + volume = 38, + number = 1, + pages = {95--113}, + doi = {10.1016/j.neuroimage.2007.07.007}, + issn = {1053-8119}, + url = {https://doi.org/10.1016/j.neuroimage.2007.07.007} +} +@article{avants2008, + title = {Symmetric diffeomorphic image registration with cross-correlation: Evaluating automated labeling of elderly and neurodegenerative brain}, + author = {B.B. Avants and C.L. Epstein and M. Grossman and J.C. Gee}, + year = 2008, + journal = {Medical Image Analysis}, + volume = 12, + number = 1, + pages = {26--41}, + doi = {10.1016/j.media.2007.06.004}, + url = {https://doi.org/10.1016/j.media.2007.06.004} +} +@article{avants2011, + title = {A reproducible evaluation of {ANTs} similarity metric performance in brain image registration}, + author = {Brian B. Avants and Nicholas J. Tustison and Gang Song and Philip A. Cook and Arno Klein and James C. Gee}, + year = 2011, + journal = {NeuroImage}, + volume = 54, + number = 3, + pages = {2033--2044}, + doi = {10.1016/j.neuroimage.2010.09.025}, + url = {https://doi.org/10.1016/j.neuroimage.2010.09.025} +} +@inproceedings{awate2005, + title = {Higher-order image statistics for unsupervised, information-theoretic, adaptive, image filtering}, + author = {Suyash P. Awate and Ross T. Whitaker}, + year = 2005, + booktitle = {IEEE Computer Society Conference on Computer Vision and Pattern Recognition {(CVPR)}}, + volume = 2, + pages = {44--51}, + doi = {10.1109/CVPR.2005.176}, + url = {https://doi.org/10.1109/CVPR.2005.176} +} +@article{awate2006, + title = {Unsupervised, information-theoretic, adaptive image filtering for image restoration}, + author = {Suyash P. Awate and Ross T. Whitaker}, + year = 2006, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = 28, + number = 3, + pages = {364--376}, + doi = {10.1109/TPAMI.2006.64}, + url = {https://doi.org/10.1109/TPAMI.2006.64} +} +@book{bertero1998, + title = {Introduction to Inverse Problems in Imaging}, + author = {Mario Bertero and Patrizia Boccacci}, + year = 1998, + publisher = {CRC Press} +} +@article{besag1986, + title = {On the Statistical Analysis of Dirty Pictures}, + author = {Julian Besag}, + year = 1986, + journal = {Journal of the Royal Statistical Society: Series B (Methodological)}, + volume = 48, + number = 3, + pages = {259--279}, + doi = {10.1111/j.2517-6161.1986.tb01412.x}, + url = {https://doi.org/10.1111/j.2517-6161.1986.tb01412.x} +} +@article{besl1992, + title = {A method for registration of {3-D} shapes}, + author = {Besl, P.J. and McKay, Neil D.}, + year = 1992, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = 14, + number = 2, + pages = {239--256}, + doi = {10.1109/34.121791}, + url = {https://doi.org/10.1109/34.121791} +} +@inproceedings{bierling1988, + title = {{Displacement Estimation By Hierarchical Blockmatching}}, + author = {M. Bierling}, + year = 1988, + booktitle = {Visual Communications and Image Processing}, + publisher = {SPIE}, + volume = 1001, + pages = {942 -- 953}, + doi = {10.1117/12.969046}, + url = {https://doi.org/10.1117/12.969046} +} +@article{bowdler1968, + title = {The {QR} and {QL} algorithms for symmetric matrices}, + author = {Bowdler, Hilary and Martin, R. S. and Reinsch, C. and Wilkinson, J. H.}, + year = 1968, + journal = {Numerische Mathematik}, + volume = 11, + number = 4, + pages = {293--306}, + doi = {10.1007/BF02166681}, + url = {https://doi.org/10.1007/BF02166681} +} +@inbook{bowdler1971, + title = {The {QR} and {QL} Algorithms for Symmetric Matrices}, + author = {Bowdler, H. and Martin, R. S. and Reinsch, C. and Wilkinson, J. H.}, + year = 1971, + booktitle = {Handbook for Automatic Computation: Volume II: Linear Algebra}, + publisher = {Springer Berlin Heidelberg}, + address = {Berlin, Heidelberg}, + pages = {227--240}, + doi = {10.1007/978-3-642-86940-2_14}, + url = {https://doi.org/10.1007/978-3-642-86940-2_14} +} +@article{brigger1999, + title = {Centered pyramids}, + author = {Brigger, P. and Muller, F. and Illgner, K. and Unser, M.}, + year = 1999, + journal = {IEEE Transactions on Image Processing}, + volume = 8, + number = 9, + pages = {1254--1264}, + doi = {10.1109/83.784437}, + url = {https://doi.org/10.1109/83.784437} +} +@inproceedings{buades2005, + title = {A non-local algorithm for image denoising}, + author = {Antoni Buades and Bartomeu Coll and Jean-Michel Morel}, + year = 2005, + booktitle = {IEEE Computer Society Conference on Computer Vision and Pattern Recognition {(CVPR)}}, + volume = 2, + pages = {60--65}, + doi = {10.1109/CVPR.2005.38}, + url = {https://doi.org/10.1109/CVPR.2005.38} +} +@article{buades2008, + title = {Nonlocal Image and Movie Denoising}, + author = {Buades, Antoni and Coll, Bartomeu and Morel, Jean-Michel}, + year = 2008, + journal = {International Journal of Computer Vision}, + volume = 76, + number = 2, + pages = {123--139}, + doi = {10.1007/s11263-007-0052-1}, + url = {https://doi.org/10.1007/s11263-007-0052-1} +} +@article{byrd1995, + title = {A Limited Memory Algorithm for Bound Constrained Optimization}, + author = {Byrd, Richard H. and Lu, Peihuang and Nocedal, Jorge and Zhu, Ciyou}, + year = 1995, + journal = {SIAM Journal on Scientific Computing}, + volume = 16, + number = 5, + pages = {1190--1208}, + doi = {10.1137/0916069}, + url = {https://doi.org/10.1137/0916069} +} +@article{canny1986, + title = {A Computational Approach to Edge Detection}, + author = {John Canny}, + year = 1986, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = 8, + number = 6, + pages = {679–698}, + doi = {10.1109/TPAMI.1986.4767851}, + url = {https://doi.org/10.1109/TPAMI.1986.4767851} +} +@article{caselles1997, + title = {Geodesic Active Contours}, + author = {Caselles, Vicent and Kimmel, Ron and Sapiro, Guillermo}, + year = 1997, + journal = {International Journal of Computer Vision}, + volume = 22, + number = 1, + pages = {61--79}, + doi = {10.1023/A:1007979827043}, + url = {https://doi.org/10.1023/A:1007979827043} +} +@book{castleman1995, + title = {Digital Signal Processing}, + author = {Kenneth R. Castleman}, + year = 1995, + publisher = {Prentice Hall} +} +@inproceedings{chan1999, + title = {An Active Contour Model without Edges}, + author = {Chan, Tony and Vese, Luminita}, + year = 1999, + booktitle = {Scale-Space Theories in Computer Vision}, + publisher = {Springer Berlin Heidelberg}, + pages = {141--151}, + doi = {10.1007/3-540-48236-9_13}, + url = {https://doi.org/10.1007/3-540-48236-9_13} +} +@article{chan2001, + title = {Active contours without edges}, + author = {Chan, Tony F. and Vese, Luminita A.}, + year = 2001, + journal = {IEEE Transactions on Image Processing}, + volume = 10, + number = 2, + pages = {266--277}, + doi = {10.1109/83.902291}, + url = {https://doi.org/10.1109/83.902291} +} +@article{chu1990, + title = {Use of gray value distribution of run lengths for texture analysis}, + author = {A. Chu and C.M. Sehgal and J.F. Greenleaf}, + year = 1990, + journal = {Pattern Recognition Letters}, + volume = 11, + number = 6, + pages = {415--419}, + doi = {10.1016/0167-8655(90)90112-F}, + url = {https://doi.org/10.1016/0167-8655(90)90112-F} +} +@inproceedings{chung2002, + title = {Multi-modal Image Registration by Minimising Kullback-Leibler Distance}, + author = {Chung, Albert C. S. and Wells, William M. and Norbash, Alexander and Grimson, W. Eric L.}, + year = 2002, + booktitle = {Medical Image Computing and Computer-Assisted Intervention {(MICCAI)}}, + pages = {525--532}, + doi = {10.1007/3-540-45787-9_66}, + url = {https://doi.org/10.1007/3-540-45787-9_66} +} +@article{clatz2005, + title = {Robust nonrigid registration to capture brain shift from intraoperative MRI}, + author = {Clatz, O. and Delingette, H. and Talos, I.-F. and Golby, A.J. and Kikinis, R. and Jolesz, F.A. and Ayache, N. and Warfield, S.K.}, + year = 2005, + journal = {IEEE Transactions on Medical Imaging}, + volume = 24, + number = 11, + pages = {1417--1427}, + doi = {10.1109/TMI.2005.856734}, + url = {https://doi.org/10.1109/TMI.2005.856734} +} +@article{conners1980, + title = {A Theoretical Comparison of Texture Algorithms}, + author = {Conners, Richard W. and Harlow, Charles A.}, + year = 1980, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = {PAMI-2}, + number = 3, + pages = {204--222}, + doi = {10.1109/TPAMI.1980.4767008}, + url = {https://doi.org/10.1109/TPAMI.1980.4767008} +} +@article{conners1984, + title = {Segmentation of a high-resolution urban scene using texture operators}, + author = {Richard W. Conners and Mohan M. Trivedi and Charles A. Harlow}, + year = 1984, + journal = {Computer Vision, Graphics, and Image Processing}, + volume = 25, + number = 3, + pages = {273--310}, + doi = {10.1016/0734-189X(84)90197-X}, + url = {https://doi.org/10.1016/0734-189X(84)90197-X} +} +@article{danielsson1980, + title = {Euclidean distance mapping}, + author = {Per-Erik Danielsson}, + year = 1980, + journal = {Computer Graphics and Image Processing}, + volume = 14, + number = 3, + pages = {227--248}, + doi = {10.1016/0146-664X(80)90054-4}, + url = {https://doi.org/10.1016/0146-664X(80)90054-4} +} +@article{dasarathy1991, + title = {Image characterizations based on joint gray level—run length distributions}, + author = {Belur V. Dasarathy and Edwin B. Holder}, + year = 1991, + journal = {Pattern Recognition Letters}, + volume = 12, + number = 8, + pages = {497--502}, + doi = {10.1016/0167-8655(91)80014-2}, + url = {https://doi.org/10.1016/0167-8655(91)80014-2} +} +@article{davis1997, + title = {A physics-based coordinate transformation for {3-D} image matching}, + author = {Davis, M.H. and Khotanzad, A. and Flamig, D.P. and Harms, S.E.}, + year = 1997, + journal = {IEEE Transactions on Medical Imaging}, + volume = 16, + number = 3, + pages = {317--328}, + doi = {10.1109/42.585766}, + url = {https://doi.org/10.1109/42.585766} +} +@article{delingette1999, + title = {General Object Reconstruction Based on Simplex Meshes}, + author = {Delingette, Herv{\'e}}, + year = 1999, + journal = {International Journal of Computer Vision}, + volume = 32, + number = 2, + pages = {111--146}, + doi = {10.1023/A:1008157432188}, + url = {https://doi.org/10.1023/A:1008157432188} +} +@book{dennis1983, + title = {Numerical Methods for Unconstrained Optimization and Nonlinear Equations}, + author = {Dennis, Jr. John E. and Schnabel, Robert B.}, + year = 1983, + publisher = {Society for Industrial and Applied Mathematics (SIAM)}, + doi = {10.1137/1.9781611971200}, + url = {https://doi.org/10.1137/1.9781611971200} +} +@article{deriche1990, + title = {Fast algorithms for low-level vision}, + author = {Rachid Deriche}, + year = 1990, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = 12, + number = 1, + pages = {78--87}, + doi = {10.1109/34.41386}, + url = {https://doi.org/10.1109/34.41386} +} +@article{dufour2005, + title = {Segmenting and tracking fluorescent cells in dynamic 3-D microscopy with coupled active surfaces}, + author = {Dufour, A. and Shinin, V. and Tajbakhsh, S. and Guillen-Aghion, N. and Olivo-Marin, J.-C. and Zimmer, C.}, + year = 2005, + journal = {IEEE Transactions on Image Processing}, + volume = 14, + number = 9, + pages = {1396--1410}, + doi = {10.1109/TIP.2005.852790}, + url = {https://doi.org/10.1109/TIP.2005.852790} +} +@article{farneback2006, + title = {Improving Deriche-style Recursive Gaussian Filters}, + author = {Farneb{\"a}ck, Gunnar and Westin, Carl-Fredrik}, + year = 2006, + journal = {Journal of Mathematical Imaging and Vision}, + volume = 26, + number = 3, + pages = {293--299}, + doi = {10.1007/s10851-006-8464-z}, + url = {https://doi.org/10.1007/s10851-006-8464-z} +} +@article{fischer2004, + title = {A unified approach to fast image registration and a new curvature based registration technique}, + author = {Bernd Fischer and Jan Modersitzki}, + year = 2004, + journal = {Linear Algebra and its Applications}, + volume = 380, + pages = {107--124}, + doi = {10.1016/j.laa.2003.10.021}, + url = {https://doi.org/10.1016/j.laa.2003.10.021} +} +@article{fortune1987, + title = {A sweepline algorithm for {Voronoi} diagrams}, + author = {Fortune, Steven}, + year = 1987, + journal = {Algorithmica}, + volume = 2, + number = 1, + pages = {153--174}, + doi = {10.1007/BF01840357}, + url = {https://doi.org/10.1007/BF01840357} +} +@inproceedings{frangi1998, + title = {Multiscale vessel enhancement filtering}, + author = {Frangi, Alejandro F. and Niessen, Wiro J. and Vincken, Koen L. and Viergever, Max A.}, + year = 1998, + booktitle = {Medical Image Computing and Computer-Assisted Intervention (MICCAI)}, + pages = {130--137}, + doi = {10.1007/BFb0056195}, + url = {https://doi.org/10.1007/BFb0056195} +} +@inproceedings{galen2007, + title = {Scalable training of L1-regularized log-linear models}, + author = {Andrew, Galen and Gao, Jianfeng}, + year = 2007, + booktitle = {International Conference on Machine Learning (ICML)}, + pages = {33–40}, + doi = {10.1145/1273496.1273501}, + url = {https://doi.org/10.1145/1273496.1273501}, + numpages = 8 +} +@article{galloway1975, + title = {Texture analysis using gray level run lengths}, + author = {Mary M. Galloway}, + year = 1975, + journal = {Computer Graphics and Image Processing}, + volume = 4, + number = 2, + pages = {172--179}, + doi = {10.1016/S0146-664X(75)80008-6}, + url = {https://doi.org/10.1016/S0146-664X(75)80008-6} +} +@book{gamma1994, + title = {Design Patterns: Elements of Reusable Object-Oriented Software}, + author = {Erich Gamma and Richard Helm and Ralph Johnson and John Vlissides}, + year = 1994, + publisher = {Addison-Wesley} +} +@book{gersho1992, + title = {Vector Quantization and Signal Compression}, + author = {Allen Gersho and Robert M. Gray}, + year = 1992, + publisher = {Springer New York, NY}, + doi = {10.1007/978-1-4615-3626-0}, + url = {https://doi.org/10.1007/978-1-4615-3626-0} +} +@article{glasbey1993, + title = {An Analysis of Histogram-Based Thresholding Algorithms}, + author = {C.A. Glasbey}, + year = 1993, + journal = {CVGIP: Graphical Models and Image Processing}, + volume = 55, + number = 6, + pages = {532--537}, + doi = {10.1006/cgip.1993.1040}, + url = {https://doi.org/10.1006/cgip.1993.1040} +} +@book{gonzales1993, + title = {Digital Image Processing}, + author = {Rafael C. Gonzales and Richard E. Woods}, + year = 1993, + publisher = {Addison Wesley} +} +@article{gouraud1971, + title = {Continuous Shading of Curved Surfaces}, + author = {Gouraud, Henri}, + year = 1971, + journal = {IEEE Transactions on Computers}, + volume = {C-20}, + number = 6, + pages = {623--629}, + doi = {10.1109/T-C.1971.223313}, + url = {https://doi.org/10.1109/T-C.1971.223313} +} +@article{guibas1985, + title = {Primitives for the manipulation of general subdivisions and the computation of Voronoi}, + author = {Guibas, Leonidas and Stolfi, Jorge}, + year = 1985, + journal = {ACM Transactions on Graphics}, + volume = 4, + number = 2, + pages = {74–123}, + doi = {10.1145/282918.282923}, + url = {https://doi.org/10.1145/282918.282923} +} +@techreport{hamilton2006, + title = {Compact Hilbert Indices}, + author = {Chris Hamilton}, + year = 2006, + number = {CS-2006-07}, + institution = {Dalhousie University} +} +@article{haralick1973, + title = {Textural Features for Image Classification}, + author = {Haralick, Robert M. and Shanmugam, K. and Dinstein, Its'Hak}, + year = 1973, + journal = {IEEE Transactions on Systems, Man, and Cybernetics}, + volume = {SMC-3}, + number = 6, + pages = {610--621}, + doi = {10.1109/TSMC.1973.4309314}, + url = {https://doi.org/10.1109/TSMC.1973.4309314} +} +@article{haralick1979, + title = {Statistical and structural approaches to texture}, + author = {Haralick, R.M.}, + year = 1979, + journal = {Proceedings of the IEEE}, + volume = 67, + number = 5, + pages = {786--804}, + doi = {10.1109/PROC.1979.11328}, + url = {https://doi.org/10.1109/PROC.1979.11328} +} +@article{hasan2001, + title = {Analytical Computation of the Eigenvalues and Eigenvectors in {DT-MRI}}, + author = {Khader M. Hasan and Peter J. Basser and Dennis L. Parker and Andrew L. Alexander}, + year = 2001, + journal = {Journal of Magnetic Resonance}, + volume = 152, + number = 1, + pages = {41--47}, + doi = {10.1006/jmre.2001.2400}, + url = {https://doi.org/10.1006/jmre.2001.2400} +} +@article{hipwell2003, + title = {Intensity-based {2-D - 3-D} registration of cerebral angiograms}, + author = {Hipwell, J.H. and Penney, G.P. and McLaughlin, R.A. and Rhode, K. and Summers, P. and Cox, T.C. and Byrne, J.V. and Noble, J.A. and Hawkes, D.J.}, + year = 2003, + journal = {IEEE Transactions on Medical Imaging}, + volume = 22, + number = 11, + pages = {1417--1426}, + doi = {10.1109/TMI.2003.819283}, + url = {https://doi.org/10.1109/TMI.2003.819283} +} +@article{horn1987, + title = {Closed-form solution of absolute orientation using unit quaternions}, + author = {Berthold K. P. Horn}, + year = 1987, + journal = {Journal of the Optical Society of America A}, + publisher = {Optica Publishing Group}, + volume = 4, + number = 4, + pages = {629--642}, + doi = {10.1364/JOSAA.4.000629}, + url = {https://doi.org/10.1364/JOSAA.4.000629} +} +@article{huang1979, + title = {A fast two-dimensional median filtering algorithm}, + author = {Huang, T. and Yang, G. and Tang, G.}, + year = 1979, + journal = {IEEE Transactions on Acoustics, Speech, and Signal Processing}, + volume = 27, + number = 1, + pages = {13--18}, + doi = {10.1109/TASSP.1979.1163188}, + url = {https://doi.org/10.1109/TASSP.1979.1163188} +} +@article{huang1995, + title = {Image thresholding by minimizing the measures of fuzziness}, + author = {Liang-Kai Huang and Mao-Jiun J. Wang}, + year = 1995, + journal = {Pattern Recognition}, + volume = 28, + number = 1, + pages = {41--51}, + doi = {10.1016/0031-3203(94)E0043-K}, + url = {https://doi.org/10.1016/0031-3203(94)E0043-K} +} +@article{imelinska2000, + title = {Semi-automated color segmentation of anatomical tissue}, + author = {C. Imeli{\'n}ska and M.S. Downes and W. Yuan}, + year = 2000, + journal = {Computerized Medical Imaging and Graphics}, + volume = 24, + number = 3, + pages = {173--180}, + doi = {10.1016/S0895-6111(00)00017-3}, + url = {https://doi.org/10.1016/S0895-6111(00)00017-3} +} +@article{jin2005, + title = {A comparison of algorithms for vertex normal computation}, + author = {Jin, Shuangshuang and Lewis, Robert R. and West, David}, + year = 2005, + journal = {The Visual Computer}, + volume = 21, + number = 1, + pages = {71--82}, + doi = {10.1007/s00371-004-0271-1}, + url = {https://doi.org/10.1007/s00371-004-0271-1} +} +@article{kapur1985, + title = {A new method for gray-level picture thresholding using the entropy of the histogram}, + author = {J.N. Kapur and P.K. Sahoo and A.K.C. Wong}, + year = 1985, + journal = {Computer Vision, Graphics, and Image Processing}, + volume = 29, + number = 3, + pages = {273--285}, + doi = {10.1016/0734-189X(85)90125-2}, + url = {https://doi.org/10.1016/0734-189X(85)90125-2} +} +@inproceedings{kennedy1995, + title = {Particle swarm optimization}, + author = {Kennedy, J. and Eberhart, R.}, + year = 1995, + booktitle = {International Conference on Neural Networks}, + volume = 4, + pages = {1942--1948}, + doi = {10.1109/ICNN.1995.488968}, + url = {https://doi.org/10.1109/ICNN.1995.488968} +} +@article{kim2011, + title = {Affine Transformation for Landmark Based Registration Initializer in ITK}, + author = {Eun Young Kim and Hans Johnson and Norman Williams}, + year = 2011, + journal = {The MIDAS Journal}, + doi = {10.54294/fge470}, + url = {https://doi.org/10.54294/fge470} +} +@article{kimmel1998, + title = {Computing geodesic paths on manifolds}, + author = {R. Kimmel and J. A. Sethian}, + year = 1998, + journal = {Proceedings of the National Academy of Sciences}, + volume = 95, + number = 15, + pages = {8431--8435}, + doi = {10.1073/pnas.95.15.8431}, + url = {https://doi.org/10.1073/pnas.95.15.8431} +} +@article{kittler1986, + title = {Minimum error thresholding}, + author = {J. Kittler and J. Illingworth}, + year = 1986, + journal = {Pattern Recognition}, + volume = 19, + number = 1, + pages = {41--47}, + doi = {10.1016/0031-3203(86)90030-0}, + url = {https://doi.org/10.1016/0031-3203(86)90030-0} +} +@article{klein1997, + title = {Quantitative coronary angiography with deformable spline models}, + author = {Andreas Klein and Forester Lee and Amir A. Amini}, + year = 1997, + journal = {IEEE Transactions on Medical Imaging}, + volume = 16, + number = 5, + pages = {468--482}, + doi = {10.1109/42.640737}, + url = {https://doi.org/10.1109/42.640737} +} +@article{koepfler1994, + title = {A Multiscale Algorithm for Image Segmentation by Variational Method}, + author = {Koepfler, G. and Lopez, C. and Morel, J. M.}, + year = 1994, + journal = {SIAM Journal on Numerical Analysis}, + volume = 31, + number = 1, + pages = {282--299}, + doi = {10.1137/0731015}, + url = {https://doi.org/10.1137/0731015} +} +@article{lee1997, + title = {Scattered data interpolation with multilevel B-splines}, + author = {Lee, S. and Wolberg, G. and Shin, S.Y.}, + year = 1997, + journal = {IEEE Transactions on Visualization and Computer Graphics}, + volume = 3, + number = 3, + pages = {228--244}, + doi = {10.1109/2945.620490}, + url = {https://doi.org/10.1109/2945.620490} +} +@inproceedings{leventon2000, + title = {Statistical shape influence in geodesic active contours}, + author = {Leventon, M.E. and Grimson, W.E.L. and Faugeras, O.}, + year = 2000, + booktitle = {IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, + volume = 1, + pages = {316--323 vol.1}, + doi = {10.1109/CVPR.2000.855835}, + url = {https://doi.org/10.1109/CVPR.2000.855835} +} +@article{li1993, + title = {Minimum cross entropy thresholding}, + author = {C.H. Li and C.K. Lee}, + year = 1993, + journal = {Pattern Recognition}, + volume = 26, + number = 4, + pages = {617--625}, + doi = {10.1016/0031-3203(93)90115-D}, + url = {https://doi.org/10.1016/0031-3203(93)90115-D} +} +@article{li1998, + title = {An iterative algorithm for minimum cross entropy thresholding}, + author = {C.H. Li and P.K.S. Tam}, + year = 1998, + journal = {Pattern Recognition Letters}, + volume = 19, + number = 8, + pages = {771--776}, + doi = {10.1016/S0167-8655(98)00057-9}, + url = {https://doi.org/10.1016/S0167-8655(98)00057-9} +} +@inproceedings{li2005, + title = {Level set evolution without re-initialization: a new variational formulation}, + author = {Chunming Li and Chenyang Xu and Changfeng Gui and Fox, M.D.}, + year = 2005, + booktitle = {IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR)}, + volume = 1, + pages = {430--436}, + doi = {10.1109/CVPR.2005.213}, + url = {https://doi.org/10.1109/CVPR.2005.213} +} +@phdthesis{lindeberg1991, + title = {Discrete Scale-Space Theory and the Scale-Space Primal Sketch}, + author = {Tony Lindeberg}, + year = 1991, + school = {Royal Institute of Technology, Stockholm, Sweden} +} +@article{liu1989, + title = {On the limited memory BFGS method for large scale optimization}, + author = {Liu, Dong C. and Nocedal, Jorge}, + year = 1989, + journal = {Mathematical Programming}, + volume = 45, + number = 1, + pages = {503--528}, + doi = {10.1007/BF01589116}, + url = {https://doi.org/10.1007/BF01589116} +} +@inproceedings{liu2009, + title = {Real-Time Non-rigid Registration of Medical Images on a Cooperative Parallel Architecture}, + author = {Liu, Yixun and Fedorov, Andriy and Kikinis, Ron and Chrisochoides, Nikos}, + year = 2009, + booktitle = {IEEE International Conference on Bioinformatics and Biomedicine}, + pages = {401--404}, + doi = {10.1109/BIBM.2009.10}, + url = {https://doi.org/10.1109/BIBM.2009.10} +} +@article{lorensen1987, + title = {Marching cubes: {A} high resolution {3D} surface construction algorithm}, + author = {William E. Lorensen and Harvey E. Cline}, + year = 1987, + journal = {Computer Graphics}, + volume = 21, + number = 4, + pages = {163--169}, + doi = {10.1145/37402.37422}, + url = {https://doi.org/10.1145/37402.37422} +} +@article{lorigo2001, + title = {{CURVES:} Curve evolution for vessel segmentation}, + author = {L.M. Lorigo and O.D. Faugeras and W.E.L. Grimson and R. Keriven and R. Kikinis and A. Nabavi and C.-F. Westin}, + year = 2001, + journal = {Medical Image Analysis}, + volume = 5, + number = 3, + pages = {195--206}, + doi = {10.1016/S1361-8415(01)00040-8}, + issn = {1361-8415}, + url = {https://doi.org/10.1016/S1361-8415(01)00040-8} +} +@article{malladi1995, + title = {Shape modeling with front propagation: a level set approach}, + author = {Malladi, Ravikanth and Sethian, James A. and Vemuri, Baba C.}, + year = 1995, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = 17, + number = 2, + pages = {158--175}, + doi = {10.1109/34.368173}, + url = {https://doi.org/10.1109/34.368173} +} +@article{martin1968, + title = {Householder's tridiagonalization of a symmetric matrix}, + author = {Martin, R. S. and Reinsch, C. and Wilkinson, J. H.}, + year = 1968, + journal = {Numerische Mathematik}, + volume = 11, + number = 3, + pages = {181--195}, + doi = {10.1007/BF02161841}, + url = {https://doi.org/10.1007/BF02161841} +} +@inbook{martin1971, + title = {Householder's Tridiagonalization of a Symmetric Matrix}, + author = {Martin, R. S. and Reinsch, C. and Wilkinson, J. H.}, + year = 1971, + booktitle = {Handbook for Automatic Computation: Volume II: Linear Algebra}, + publisher = {Springer Berlin Heidelberg}, + address = {Berlin, Heidelberg}, + pages = {212--226}, + doi = {10.1007/978-3-642-86940-2_13}, + url = {https://doi.org/10.1007/978-3-642-86940-2_13} +} +@article{matsumoto1998, + title = {Mersenne twister: a 623-dimensionally equidistributed uniform pseudo-random number generator}, + author = {Matsumoto, Makoto and Nishimura, Takuji}, + year = 1998, + journal = {ACM Transactions on Modeling and Computer Simulation}, + volume = 8, + number = 1, + pages = {3–30}, + doi = {10.1145/272991.272995}, + url = {https://doi.org/10.1145/272991.272995} +} +@inproceedings{mattes2001, + title = {{Nonrigid multimodality image registration}}, + author = {David Mattes and David R. Haynor and Hubert Vesselle and Thomas K. Lewellyn and William Eubank}, + year = 2001, + booktitle = {Medical Imaging 2001: Image Processing}, + publisher = {SPIE}, + volume = 4322, + pages = {1609 -- 1620}, + doi = {10.1117/12.431046}, + url = {https://doi.org/10.1117/12.431046}, + editor = {Milan Sonka and Kenneth M. Hanson}, + organization = {International Society for Optics and Photonics} +} +@article{mattes2003, + title = {PET-CT image registration in the chest using free-form deformations}, + author = {Mattes, D. and Haynor, D.R. and Vesselle, H. and Lewellen, T.K. and Eubank, W.}, + year = 2003, + journal = {IEEE Transactions on Medical Imaging}, + volume = 22, + number = 1, + pages = {120--128}, + doi = {10.1109/TMI.2003.809072}, + url = {https://doi.org/10.1109/TMI.2003.809072} +} +@article{maurer2003, + title = {A linear time algorithm for computing exact Euclidean distance transforms of binary images in arbitrary dimensions}, + author = {Maurer, C.R. and Rensheng Qi and Raghavan, V.}, + year = 2003, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = 25, + number = 2, + pages = {265--270}, + doi = {10.1109/TPAMI.2003.1177156}, + url = {https://doi.org/10.1109/TPAMI.2003.1177156} +} +@inproceedings{meijering1999, + title = {Quantitative Comparison of Sinc-Approximating Kernels for Medical Image Interpolation}, + author = {Meijering, Erik H. W. and Niessen, Wiro J. and Pluim, Josien P. W. and Viergever, Max A.}, + year = 1999, + booktitle = {Medical Image Computing and Computer-Assisted Intervention {(MICCAI)}}, + pages = {210--217}, + doi = {10.1007/10704282_23}, + url = {https://doi.org/10.1007/10704282_23} +} +@article{meijster2002, + title = {A comparison of algorithms for connected set openings and closings}, + author = {Meijster, A. and Wilkinson, M.H.F.}, + year = 2002, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = 24, + number = 4, + pages = {484--494}, + doi = {10.1109/34.993556}, + url = {https://doi.org/10.1109/34.993556} +} +@article{melhem2002, + title = {Diffusion Tensor {MR} Imaging of the Brain and White Matter Tractography}, + author = {Melhem, Elias R. and Mori, Susumu and Mukundan, Govind and Kraut, Michael A. and Pomper, Martin G. and van Zijl, Peter C. M.}, + year = 2002, + journal = {American Journal of Roentgenology}, + volume = 178, + number = 1, + pages = {3--16}, + doi = {10.2214/ajr.178.1.1780003}, + url = {https://doi.org/10.2214/ajr.178.1.1780003} +} +@article{more1994, + title = {Line search algorithms with guaranteed sufficient decrease}, + author = {Mor\'{e}, Jorge J. and Thuente, David J.}, + year = 1994, + journal = {ACM Transactions on Mathematical Software}, + volume = 20, + number = 3, + pages = {286–307}, + doi = {10.1145/192115.192132}, + url = {https://doi.org/10.1145/192115.192132} +} +@article{ng2006, + title = {Automatic thresholding for defect detection}, + author = {Hui-Fuang Ng}, + year = 2006, + journal = {Pattern Recognition Letters}, + volume = 27, + number = 14, + pages = {1644--1649}, + doi = {10.1016/j.patrec.2006.03.009}, + issn = {0167-8655}, + url = {https://doi.org/10.1016/j.patrec.2006.03.009} +} +@inproceedings{nikopoulos1997, + title = {An Efficient Algorithm for {3D} Binary Morphological Transformations with {3D} Structuring Elements of Arbitrary Size and Shape}, + author = {Nikos Nikopoulos and Ioannis Pitas}, + year = 1997, + booktitle = {IEEE Workshop on Nonlinear Signal and Image Processing} +} +@article{nocedal1980, + title = {Updating Quasi-Newton Matrices with Limited Storage}, + author = {Jorge Nocedal}, + year = 1980, + journal = {Mathematics of Computation}, + volume = 35, + number = 151, + pages = {773--782}, + doi = {10.1090/S0025-5718-1980-0572855-7}, + url = {http://www.jstor.org/stable/2006193}, + url = {https://doi.org/10.1090/S0025-5718-1980-0572855-7} +} +@article{nyul2000, + title = {New variants of a method of {MRI} scale standardization}, + author = {Nyul, L.G. and Udupa, J.K. and Xuan Zhang}, + year = 2000, + journal = {IEEE Transactions on Medical Imaging}, + volume = 19, + number = 2, + pages = {143--150}, + doi = {10.1109/42.836373}, + url = {https://doi.org/10.1109/42.836373} +} +@inproceedings{padfield2010, + title = {Masked {FFT} registration}, + author = {Padfield, Dirk}, + year = 2010, + booktitle = {IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR)}, + pages = {2918--2925}, + doi = {10.1109/CVPR.2010.5540032}, + url = {https://doi.org/10.1109/CVPR.2010.5540032} +} +@article{padfield2012, + title = {Masked Object Registration in the Fourier Domain}, + author = {Padfield, Dirk}, + year = 2012, + journal = {IEEE Transactions on Image Processing}, + volume = 21, + number = 5, + pages = {2706--2718}, + doi = {10.1109/TIP.2011.2181402}, + url = {https://doi.org/10.1109/TIP.2011.2181402} +} +@article{perona1990, + title = {Scale-space and edge detection using anisotropic diffusion}, + author = {Pietro Perona and Jitendra Malik}, + year = 1990, + journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence}, + volume = 12, + number = 7, + pages = {629--639}, + doi = {10.1109/34.56205}, + url = {https://doi.org/10.1109/34.56205} +} +@book{piegl1997, + title = {The NURBS Book}, + author = {Les Piegl and Wayne Tiller}, + year = 1997, + publisher = {Springer Berlin}, + doi = {10.1007/978-3-642-59223-2}, + url = {https://doi.org/10.1007/978-3-642-59223-2} +} +@article{pikaz1996, + title = {Digital image thresholding, based on topological stable-state}, + author = {Arie Pikaz and Amir Averbuch}, + year = 1996, + journal = {Pattern Recognition}, + volume = 29, + number = 5, + pages = {829--843}, + doi = {10.1016/0031-3203(95)00126-3}, + url = {https://doi.org/10.1016/0031-3203(95)00126-3} +} +@article{pluta2009, + title = {Appearance and incomplete label matching for diffeomorphic template based hippocampus segmentation}, + author = {John Pluta and Brian B. Avants and Simon Glynn and Suyash Awate and James C. Gee and John A. Detre}, + year = 2009, + journal = {Hippocampus}, + volume = 19, + number = 6, + pages = {565--571}, + doi = {10.1002/hipo.20619}, + url = {https://doi.org/10.1002/hipo.20619} +} +@article{prewitt1966, + title = {The analysis of cell images}, + author = {Prewitt, Judith M. S. and Mendelsohn, Mortimer L.}, + year = 1966, + journal = {Annals of the New York Academy of Sciences}, + volume = 128, + number = 3, + pages = {1035--1053}, + doi = {10.1111/j.1749-6632.1965.tb11715.x}, + url = {https://doi.org/10.1111/j.1749-6632.1965.tb11715.x} +} +@article{ridler1978, + title = {Picture Thresholding Using an Iterative Selection Method}, + author = {T.W. Ridler, S. Calvard, Picture}, + year = 1978, + journal = {IEEE Transactions on Systems, Man, and Cybernetics}, + volume = 8, + number = 8, + pages = {630--632}, + doi = {10.1109/TSMC.1978.4310039}, + url = {https://doi.org/10.1109/TSMC.1978.4310039} +} +@article{robinson2004, + title = {Efficient morphological reconstruction: a downhill filter}, + author = {Kevin Robinson and Paul F. Whelan}, + year = 2004, + journal = {Pattern Recognition Letters}, + volume = 25, + number = 15, + pages = {1759--1767}, + doi = {10.1016/j.patrec.2004.07.002}, + url = {https://doi.org/10.1016/j.patrec.2004.07.002} +} +@article{rohlfing2004, + title = {Performance-based classifier combination in atlas-based image segmentation using expectation-maximization parameter estimation}, + author = {Rohlfing, T. and Russakoff, D.B. and Maurer, C.R.}, + year = 2004, + journal = {IEEE Transactions on Medical Imaging}, + volume = 23, + number = 8, + pages = {983--994}, + doi = {10.1109/TMI.2004.830803}, + url = {https://doi.org/10.1109/TMI.2004.830803} +} +@article{rohlfing2005, + title = {Multi-classifier framework for atlas-based image segmentation}, + author = {Torsten Rohlfing and Calvin R. Maurer}, + year = 2005, + journal = {Pattern Recognition Letters}, + volume = 26, + number = 13, + pages = {2070--2079}, + doi = {10.1016/j.patrec.2005.03.017}, + url = {https://doi.org/10.1016/j.patrec.2005.03.017} +} +@article{sapiro1996, + title = {Anisotropic diffusion of multivalued images with applications to color filtering}, + author = {Sapiro, G. and Ringach, D.L.}, + year = 1996, + journal = {IEEE Transactions on Image Processing}, + volume = 5, + number = 11, + pages = {1582--1586}, + doi = {10.1109/83.541429}, + url = {https://doi.org/10.1109/83.541429} +} +@book{sethian1996, + title = {Level Set Methods Evolving Interfaces in Geometry, Fluid Mechanics, Computer Vision, and Materials Science}, + author = {James A. Sethian}, + year = 1996, + publisher = {Cambridge University Press} +} +@inbook{sethian1999, + title = {Image Enhancement and Noise Removal}, + author = {J. A. Sethian}, + year = 1999, + booktitle = {Level Set Methods and Fast Marching Methods}, + publisher = {Cambridge Press}, + pages = {200--213} +} +@inbook{sethian1999a, + title = {Efficient Schemes: Fast Marching Methods}, + author = {J. A. Sethian}, + year = 1999, + booktitle = {Level Set Methods and Fast Marching Methods}, + publisher = {Cambridge Press}, + pages = {86--101} +} +@inbook{sethian1999b, + title = {Constructing Extension Velocities}, + author = {J. A. Sethian}, + year = 1999, + booktitle = {Level Set Methods and Fast Marching Methods}, + publisher = {Cambridge Press}, + pages = {127--141} +} +@article{sezgin2004, + title = {{Survey over image thresholding techniques and quantitative performance evaluation}}, + author = {Mehmet Sezgin and B{\"u}lent Sankur}, + year = 2004, + journal = {Journal of Electronic Imaging}, + volume = 13, + number = 1, + pages = {146 -- 165}, + doi = {10.1117/1.1631315}, + url = {https://doi.org/10.1117/1.1631315} +} +@article{shanbhag1994, + title = {Utilization of Information Measure as a Means of Image Thresholding}, + author = {A.G. Shanbhag}, + year = 1994, + journal = {CVGIP: Graphical Models and Image Processing}, + volume = 56, + number = 5, + pages = {414--419}, + doi = {10.1006/cgip.1994.1037}, + issn = {1049-9652}, + url = {https://doi.org/10.1006/cgip.1994.1037} +} +@book{silverman1986, + title = {Density Estimation for Statistics and Data Analysis}, + author = {B. W. Silverman}, + year = 1986, + publisher = {Chapman and Hall} +} +@article{sled1998, + title = {A nonparametric method for automatic correction of intensity nonuniformity in MRI data}, + author = {Sled, J.G. and Zijdenbos, A.P. and Evans, A.C.}, + year = 1998, + journal = {IEEE Transactions on Medical Imaging}, + volume = 17, + number = 1, + pages = {87--97}, + doi = {10.1109/42.668698}, + url = {https://doi.org/10.1109/42.668698} +} +@techreport{sobel1995, + title = {An Isotropic 3x3x3 Volume Gradient Operator}, + author = {Irwin Sobel}, + year = 1995, + institution = {Hewlett-Packard Laboratories} +} +@inbook{soille2004, + title = {Geodesic Transformations}, + author = {Soille, Pierre}, + year = 2004, + booktitle = {Morphological Image Analysis: Principles and Applications}, + publisher = {Springer Berlin Heidelberg}, + address = {Berlin, Heidelberg}, + pages = {183--218}, + doi = {10.1007/978-3-662-05088-0_6}, + url = {https://doi.org/10.1007/978-3-662-05088-0_6} +} +@inbook{soille2004a, + title = {Erosion and Dilation}, + author = {Soille, Pierre}, + year = 2004, + booktitle = {Morphological Image Analysis: Principles and Applications}, + publisher = {Springer Berlin Heidelberg}, + address = {Berlin, Heidelberg}, + pages = {63--103}, + doi = {10.1007/978-3-662-05088-0_3}, + url = {https://doi.org/10.1007/978-3-662-05088-0_3} +} +@inbook{soille2004b, + title = {Opening and Closing}, + author = {Soille, Pierre}, + year = 2004, + booktitle = {Morphological Image Analysis: Principles and Applications}, + publisher = {Springer Berlin Heidelberg}, + address = {Berlin, Heidelberg}, + pages = {105--137}, + doi = {10.1007/978-3-662-05088-0_4}, + url = {https://doi.org/10.1007/978-3-662-05088-0_4} +} +@inbook{soille2004c, + title = {Segmentation}, + author = {Soille, Pierre}, + year = 2004, + booktitle = {Morphological Image Analysis: Principles and Applications}, + publisher = {Springer Berlin Heidelberg}, + address = {Berlin, Heidelberg}, + pages = {267--292}, + doi = {10.1007/978-3-662-05088-0_9}, + url = {https://doi.org/10.1007/978-3-662-05088-0_9} +} +@techreport{spall1998, + title = {An Overview of the Simultaneous Perturbation Method for Efficient Optimization}, + author = {James C. Spall}, + year = 1998, + number = {19(4)}, + url = {https://secwww.jhuapl.edu/techdigest/Content/techdigest/pdf/V19-N04/19-04-Spall.pdf}, + institution = {Johns Hopkins APL} +} +@article{spall1998a, + title = {Implementation of the simultaneous perturbation algorithm for stochastic optimization}, + author = {Spall, James C.}, + year = 1998, + journal = {IEEE Transactions on Aerospace and Electronic Systems}, + volume = 34, + number = 3, + pages = {817--823}, + doi = {10.1109/7.705889}, + url = {https://doi.org/10.1109/7.705889} +} +@inproceedings{sprengel1996, + title = {Thin-plate spline approximation for image registration}, + author = {Sprengel, R. and Rohr, K. and Stiehl, H.S.}, + year = 1996, + booktitle = {Proceedings of 18th Annual International Conference of the IEEE Engineering in Medicine and Biology Society}, + volume = 3, + pages = {1190--1191}, + doi = {10.1109/IEMBS.1996.652767}, + url = {https://doi.org/10.1109/IEMBS.1996.652767} +} +@article{stark2000, + title = {Adaptive image contrast enhancement using generalizations of histogram equalization}, + author = {Stark, J. Alex}, + year = 2000, + journal = {IEEE Transactions on Image Processing}, + volume = 9, + number = 5, + pages = {889--896}, + doi = {10.1109/83.841534}, + url = {https://doi.org/10.1109/83.841534} +} +@book{stroustrup1997, + title = {The C++ Programming Language}, + author = {Bjarne Stroustrup}, + year = 1997, + publisher = {Addison Wesley} +} +@techreport{styner1997, + title = {Evaluation of {2D/3D} bias correction with {1+1ES-optimization}}, + author = {Martin Styner and Guido Gerig}, + year = 1997, + number = {TR-197}, + institution = {ETH Zurich} +} +@article{styner2000, + title = {Parametric estimate of intensity inhomogeneities applied to {MRI}}, + author = {Styner, M. and Brechbuhler, C. and Szckely, G. and Gerig, G.}, + year = 2000, + journal = {IEEE Transactions on Medical Imaging}, + volume = 19, + number = 3, + pages = {153--165}, + doi = {10.1109/42.845174}, + url = {https://doi.org/10.1109/42.845174} +} +@article{thevenaz2000, + title = {Optimization of mutual information for multiresolution image registration}, + author = {Thevenaz, P. and Unser, M.}, + year = 2000, + journal = {IEEE Transactions on Image Processing}, + volume = 9, + number = 12, + pages = {2083--2099}, + doi = {10.1109/83.887976}, + url = {https://doi.org/10.1109/83.887976} +} +@techreport{thirion1995, + title = {Fast Non-Rigid Matching of {3D} Medical Images}, + author = {Jean-Philippe Thirion}, + year = 1995, + number = {RR-2547}, + institution = {INRIA} +} +@article{thirion1998, + title = {Image matching as a diffusion process: an analogy with Maxwell's demons}, + author = {Jean-Philippe Thirion}, + year = 1998, + journal = {Medical Image Analysis}, + volume = 2, + number = 3, + pages = {243--260}, + doi = {10.1016/S1361-8415(98)80022-4}, + url = {https://doi.org/10.1016/S1361-8415(98)80022-4} +} +@article{thurmer1998, + title = {Computing Vertex Normals from Polygonal Facets}, + author = {Grit Th{\:u}rmer and Charles A. W{\:u}thrich}, + year = 1998, + journal = {Journal of Graphics Tools}, + volume = 3, + number = 1, + pages = {43--46}, + doi = {10.1080/10867651.1998.10487487}, + url = {https://doi.org/10.1080/10867651.1998.10487487} +} +@inproceedings{tomasi1998, + title = {Bilateral filtering for gray and color images}, + author = {Tomasi, C. and Manduchi, R.}, + year = 1998, + booktitle = {International Conference on Computer Vision (ICCV)}, + pages = {839--846}, + doi = {10.1109/ICCV.1998.710815}, + url = {https://doi.org/10.1109/ICCV.1998.710815} +} +@article{tsai1985, + title = {Moment-preserving thresolding: A new approach}, + author = {Wen-Hsiang Tsai}, + year = 1985, + journal = {Computer Vision, Graphics, and Image Processing}, + volume = 29, + number = 3, + pages = {377--393}, + doi = {10.1016/0734-189X(85)90133-1}, + issn = {0734-189X}, + url = {https://doi.org/10.1016/0734-189X(85)90133-1} +} +@inproceedings{tustison2006, + title = {Generalized {n-D} C$^k$B-Spline Scattered Data Approximation with Confidence Values}, + author = {Tustison, Nicholas J. and Gee, James C.}, + year = 2006, + booktitle = {Medical Imaging and Augmented Reality}, + pages = {76--83}, + doi = {10.1007/11812715_10}, + url = {https://doi.org/10.1007/11812715_10} +} +@article{tustison2009, + title = {Directly Manipulated Free-Form Deformation Image Registration}, + author = {Tustison, Nicholas J. and Avants, Brian B. and Gee, James C.}, + year = 2009, + journal = {IEEE Transactions on Image Processing}, + volume = 18, + number = 3, + pages = {624--635}, + doi = {10.1109/TIP.2008.2010072}, + url = {https://doi.org/10.1109/TIP.2008.2010072} +} +@article{tustison2010, + title = {{N4ITK}: Improved {N3} Bias Correction}, + author = {Tustison, Nicholas J. and Avants, Brian B. and Cook, Philip A. and Zheng, Yuanjie and Egan, Alexander and Yushkevich, Paul A. and Gee, James C.}, + year = 2010, + journal = {IEEE Transactions on Medical Imaging}, + volume = 29, + number = 6, + pages = {1310--1320}, + doi = {10.1109/TMI.2010.2046908}, + url = {https://doi.org/10.1109/TMI.2010.2046908} +} +@article{tustison2010a, + title = {Information-Theoretic Directly Manipulated Free-Form Deformation Labeled Point-Set Registration}, + author = {N. Tustison and S. Awate and J. Gee}, + year = 2010, + journal = {The Insight Journal}, + doi = {10.54294/791z7t}, + url = {https://doi.org/10.54294/791z7t} +} +@article{tustison2011, + title = {Point Set Registration Using Havrda–Charvat–Tsallis Entropy Measures}, + author = {Tustison, Nicholas J. and Awate, Suyash P. and Song, Gang and Cook, Tessa S. and Gee, James C.}, + year = 2011, + journal = {IEEE Transactions on Medical Imaging}, + volume = 30, + number = 2, + pages = {451--460}, + doi = {10.1109/TMI.2010.2086065}, + url = {https://doi.org/10.1109/TMI.2010.2086065} +} +@article{tustison2011a, + title = {Topological Well-Composedness and Glamorous Glue: A Digital Gluing Algorithm for Topologically Constrained Front Propagation}, + author = {Tustison, Nicholas J. and Avants, Brian B. and Siqueira, Marcelo and Gee, James C.}, + year = 2011, + journal = {IEEE Transactions on Image Processing}, + volume = 20, + number = 6, + pages = {1756--1761}, + doi = {10.1109/TIP.2010.2095021}, + url = {https://doi.org/10.1109/TIP.2010.2095021} +} +@article{unser1993, + title = {B-spline signal processing. {I. Theory}}, + author = {Unser, M. and Aldroubi, A. and Eden, M.}, + year = 1993, + journal = {IEEE Transactions on Signal Processing}, + volume = 41, + number = 2, + pages = {821--833}, + doi = {10.1109/78.193220}, + url = {https://doi.org/10.1109/78.193220} +} +@article{unser1993a, + title = {B-spline signal processing. {II. Efficiency} design and applications}, + author = {Unser, M. and Aldroubi, A. and Eden, M.}, + year = 1993, + journal = {IEEE Transactions on Signal Processing}, + volume = 41, + number = 2, + pages = {834--848}, + doi = {10.1109/78.193221}, + url = {https://doi.org/10.1109/78.193221} +} +@article{unser1999, + title = {Splines: a perfect fit for signal and image processing}, + author = {Michael Unser}, + year = 1999, + journal = {IEEE Signal Processing Magazine}, + volume = 16, + number = 6, + pages = {22--38}, + doi = {10.1109/79.799930}, + url = {https://doi.org/10.1109/79.799930} +} +@article{urish2005, + title = {Unsupervised Segmentation for Myofiber Counting in Immunofluorescent Microscopy Images}, + author = {Urish, Kenneth and August, Jonas and Huard, Johnny}, + year = 2005, + doi = {10.54294/h1vbsl}, + url = {https://doi.org/10.54294/h1vbsl}, + journal = {The Insight Journal} +} +@article{vemuri2003, + title = {Image registration via level-set motion: Applications to atlas-based segmentation}, + author = {B.C. Vemuri and J. Ye and Y. Chen and C.M. Leonard}, + year = 2003, + journal = {Medical Image Analysis}, + volume = 7, + number = 1, + pages = {1--20}, + doi = {10.1016/S1361-8415(02)00063-4}, + issn = {1361-8415}, + url = {https://doi.org/10.1016/S1361-8415(02)00063-4} +} +@inproceedings{vercauteren2007, + title = {Non-parametric Diffeomorphic Image Registration with the Demons Algorithm}, + author = {Vercauteren, Tom and Pennec, Xavier and Perchant, Aymeric and Ayache, Nicholas}, + year = 2007, + booktitle = {Medical Image Computing and Computer-Assisted Intervention {(MICCAI)}}, + pages = {319--326}, + doi = {10.1007/978-3-540-75759-7_39}, + url = {https://doi.org/10.1007/978-3-540-75759-7_39} +} +@article{vincent1991, + title = {Morphological transformations of binary images with arbitrary structuring elements}, + author = {Luc Vincent}, + year = 1991, + journal = {Signal Processing}, + volume = 22, + number = 1, + pages = {3--23}, + doi = {10.1016/0165-1684(91)90025-E}, + url = {https://doi.org/10.1016/0165-1684(91)90025-E} +} +@article{vincent1993, + title = {Morphological grayscale reconstruction in image analysis: applications and efficient algorithms}, + author = {Luc Vincent}, + year = 1993, + journal = {IEEE Transactions on Image Processing}, + volume = 2, + number = 2, + pages = {176--201}, + doi = {10.1109/83.217222}, + url = {https://doi.org/10.1109/83.217222} +} +@article{viola1997, + title = {Alignment by Maximization of Mutual Information}, + author = {Viola, Paul and Wells III, William M.}, + year = 1997, + journal = {International Journal of Computer Vision}, + volume = 24, + number = 2, + pages = {137--154}, + doi = {10.1023/A:1007958904918}, + url = {https://doi.org/10.1023/A:1007958904918} +} +@article{wachowiak2004, + title = {An approach to multimodal biomedical image registration utilizing particle swarm optimization}, + author = {Wachowiak, M.P. and Smolikova, R. and Yufeng Zheng and Zurada, J.M. and Elmaghraby, A.S.}, + year = 2004, + journal = {IEEE Transactions on Evolutionary Computation}, + volume = 8, + number = 3, + pages = {289--301}, + doi = {10.1109/TEVC.2004.826068}, + url = {https://doi.org/10.1109/TEVC.2004.826068} +} +@article{wallace1996, + title = {Fast pseudorandom generators for normal and exponential variates}, + author = {Wallace, C. S.}, + year = 1996, + journal = {ACM Transactions on Mathematical Software}, + volume = 22, + number = 1, + pages = {119–127}, + doi = {10.1145/225545.225554}, + url = {https://doi.org/10.1145/225545.225554} +} +@inproceedings{warfield2002, + title = {Validation of Image Segmentation and Expert Quality with an Expectation-Maximization Algorithm}, + author = {Warfield, Simon K. and Zou, Kelly H. and Wells, William M.}, + year = 2002, + booktitle = {Medical Image Computing and Computer-Assisted Intervention {(MICCAI)}}, + pages = {298--306}, + doi = {10.1007/3-540-45786-0_37}, + url = {https://doi.org/10.1007/3-540-45786-0_37} +} +@article{westin2002, + title = {Processing and visualization for diffusion tensor {MRI}}, + year = 2002, + journal = {Medical Image Analysis}, + volume = 6, + number = 2, + pages = {93--108}, + doi = {10.1016/S1361-8415(02)00053-1}, + issn = {1361-8415}, + url = {https://doi.org/10.1016/S1361-8415(02)00053-1} +} +@inproceedings{westin2002a, + title = {A Dual Tensor Basis Solution to the Stejskal-Tanner Equations for {DT-MRI}}, + author = {Westin, C. F. and Maier, S. E.}, + year = 2002, + booktitle = {International Society for Magnetic Resonance in Medicine (ISMRM)}, + url = {https://cds.ismrm.org/ismrm-2002/PDF4/1166.PDF} +} +@article{whitaker1998, + title = {A Level-Set Approach to {3D} Reconstruction from Range Data}, + author = {Whitaker, Ross T.}, + year = 1998, + journal = {International Journal of Computer Vision}, + volume = 29, + number = 3, + pages = {203--231}, + doi = {10.1023/A:1008036829907}, + url = {https://doi.org/10.1023/A:1008036829907} +} +@inproceedings{whitaker2000, + title = {Reducing Aliasing Artifacts in Iso-Surfaces of Binary Volumes}, + author = {Whitaker, Ross T.}, + year = 2000, + booktitle = {IEEE Symposium on Volume Visualization (VV 2000)}, + pages = {23--32}, + doi = {10.1109/VV.2000.10004}, + url = {https://doi.org/10.1109/VV.2000.10004} +} +@inproceedings{whitaker2001, + title = {Variable-conductance, level-set curvature for image denoising}, + author = {Ross T. Whitaker and Xinwei Xue}, + year = 2001, + booktitle = {International Conference on Image Processing}, + volume = 3, + pages = {142--145}, + doi = {10.1109/ICIP.2001.958071}, + url = {https://doi.org/10.1109/ICIP.2001.958071} +} +@article{yen1995, + title = {A new criterion for automatic multilevel thresholding}, + author = {Jui-Cheng Yen and Fu-Juay Chang and Shyang Chang}, + year = 1995, + journal = {IEEE Transactions on Image Processing}, + volume = 4, + number = 3, + pages = {370--378}, + doi = {10.1109/83.366472}, + url = {https://doi.org/10.1109/83.366472} +} +@article{zhu1997, + title = {Algorithm 778: {L-BFGS-B}: Fortran subroutines for large-scale bound-constrained optimization}, + author = {Zhu, Ciyou and Byrd, Richard H. and Lu, Peihuang and Nocedal, Jorge}, + year = 1997, + journal = {ACM Transactions on Mathematical Software}, + volume = 23, + number = 4, + pages = {550–560}, + doi = {10.1145/279232.279236}, + url = {https://doi.org/10.1145/279232.279236} +} +@article{zijdenbos1994, + title = {Morphometric analysis of white matter lesions in {MR} images: method and validation}, + author = {Zijdenbos, A.P. and Dawant, B.M. and Margolin, R.A. and Palmer, A.C.}, + year = 1994, + journal = {IEEE Transactions on Medical Imaging}, + volume = 13, + number = 4, + pages = {716--724}, + doi = {10.1109/42.363096}, + url = {https://doi.org/10.1109/42.363096} +} + +@article{Tustison_2005, + title={N-D $C^k$ B-Spline Scattered Data Approximation}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/0d55to}, + DOI={10.54294/0d55to}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Gee, James}, + year={2005}, + month=nov } +@article{Lehmann_2010_b, + title={FFT based convolution}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/0iky0u}, + DOI={10.54294/0iky0u}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2010}, + month=jul } +@article{Lehmann_2006_a, + title={Image projections along an axis}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/0pjyho}, + DOI={10.54294/0pjyho}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2006}, + month=jan } +@article{Tustison_2009_d, + title={Introducing Dice, Jaccard, and Other Label Overlap Measures To ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/1vixgg}, + DOI={10.54294/1vixgg}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Gee, James}, + year={2009}, + month=dec } +@article{Mosaliganti_2009_a, + title={Level set segmentation using coupled active surfaces}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/23ugmy}, + DOI={10.54294/23ugmy}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mosaliganti, Kishore and Smith, Benjamin and Gelas, Arnaud and Gouaillard, Alexandre and megason, sean}, + year={2009}, + month=apr } +@article{Lehmann_2006_b, + title={Kappa Sigma Clipping}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/39qekn}, + DOI={10.54294/39qekn}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2006}, + month=nov } +@article{Lehmann_2006_c, + title={Slice by slice filtering with ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/47329s}, + DOI={10.54294/47329s}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2006}, + month=nov } +@article{Mccormick_2012, + title={An ITK Class that Splits Multi-Component Images}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/4c92vb}, + DOI={10.54294/4c92vb}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mccormick, Matthew}, + year={2012}, + month=jul } +@article{Staring_2008, + title={Generating a Deformation Field from a Transform}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/4ids6q}, + DOI={10.54294/4ids6q}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Staring, Marius}, + year={2008}, + month=jun } +@article{Gouaillard_2006, + title={ItkQuadEdgeMesh: A Discrete Orientable 2-Manifold Data Structure for Image Processing}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/4mx7kk}, + DOI={10.54294/4mx7kk}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Gouaillard, Alexandre and Florez-Valencia, Leonardo and Boix, Eric}, + year={2006}, + month=sep } +@article{Wu_2010, + title={ITK-Based Implementation of Two-Projection 2D/3D Registration Method with an Application in Patient Setup for External Beam Radiotherapy}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/6f280b}, + DOI={10.54294/6f280b}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Wu, Jian}, + year={2010}, + month=dec } +@article{Ibanez_2014, + title={STL file format MeshIO class for ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/7rr2te}, + DOI={10.54294/7rr2te}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Ibanez, Luis}, + year={2014}, + month=jan } +@article{Lehmann_2006_d, + title={Robust Automatic Threshold Selection}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/7w23qz}, + DOI={10.54294/7w23qz}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2006}, + month=nov } +@article{Gelas_2007, + title={Parameterization of discrete surfaces}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/8ga88z}, + DOI={10.54294/8ga88z}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Gelas, Arnaud and Gouaillard, Alexandre}, + year={2007}, + month=nov } +@article{Lowekamp_2018, + title={Scalable Simple Linear Iterative Clustering (SSLIC) Using a Generic and Parallel Approach}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/8hic7f}, + DOI={10.54294/8hic7f}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lowekamp, Bradley and Chen, David and Yaniv, Ziv and Yoo, Terry}, + year={2018}, + month=jul } +@article{Mosaliganti_2009_b, + title={Level Set Segmentation: Active Contours without edge}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/8jk6oy}, + DOI={10.54294/8jk6oy}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mosaliganti, Kishore and Smith, Benjamin and Gelas, Arnaud and Gouaillard, Alexandre and megason, sean}, + year={2009}, + month=mar } +@article{Tustison_2016, + title={Two Luis Miguel fans walk into a bar in Nagoya ---> (yada, yada, yada) ---> an ITK-implementation of a popular patch-based denoising filter}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/9f5wt3}, + DOI={10.54294/9f5wt3}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Manjon, Jose}, + year={2016}, + month=aug } +@article{Mccormick_2016, + title={Performance Benchmarking the Insight Toolkit}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/9feae9}, + DOI={10.54294/9feae9}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mccormick, Matthew and Kang, Hyun-jae and BARRE, Sebastien}, + year={2016}, + month=jul } +@article{Zuki__2016_b, + title={ND morphological contour interpolation}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/achtrg}, + DOI={10.54294/achtrg}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Zukić, Dženan and Vicory, Jared and Mccormick, Matthew and Wisse, Laura and Gerig, Guido and Yushkevich, Paul and Aylward, Stephen}, + year={2016}, + month=aug } +@article{Beare_2008, + title={Morphology with parabolic structuring elements}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/aq68pt}, + DOI={10.54294/aq68pt}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Beare, Richard}, + year={2008}, + month=dec } +@article{Lehmann_2005, + title={Binary morphological closing and opening image filters}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/bcwtvq}, + DOI={10.54294/bcwtvq}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2005}, + month=nov } +@article{Mosaliganti_2010, + title={Support for Streaming the JPEG2000 File Format}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/bo53br}, + DOI={10.54294/bo53br}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mosaliganti, Kishore and Ibanez, Luis and Megason, Sean}, + year={2010}, + month=aug } +@article{Lehmann_2008, + title={Efficient contour detection in binary and label images}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/c7d3gv}, + DOI={10.54294/c7d3gv}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2008}, + month=apr } +@article{Vidal_Migallon_2013, + title={GPU and CPU implementation of Young - Van Vliet’s Recursive Gaussian Smoothing Filter}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/cpyaig}, + DOI={10.54294/cpyaig}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Vidal-Migallon, Irina and Commowick, Olivier and Pennec, Xavier and Dauguet, Julien and Vercauteren, Tom}, + year={2013}, + month=jul } +@article{Mueller_2010, + title={Cuberille Implicit Surface Polygonization for ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/df9mgw}, + DOI={10.54294/df9mgw}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mueller, Dan}, + year={2010}, + month=jul } +@article{Tustison_2007_b, + title={Go-Go Gabor Gadgetry}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/dhogdz}, + DOI={10.54294/dhogdz}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Gee, James}, + year={2007}, + month=apr } +@article{Tustison_2009_a, + title={Image Kernel Convolution}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/e292kx}, + DOI={10.54294/e292kx}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Gee, James}, + year={2009}, + month=jan } +@article{Schaerer_2014, + title={A MultipleImageIterator for iterating over multiple images simultaneously}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/e5lmyz}, + DOI={10.54294/e5lmyz}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Schaerer, Joël}, + year={2014}, + month=feb } +@article{Beare_2011, + title={Histogram-based thresholding - some missing methods}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/efycla}, + DOI={10.54294/efycla}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Beare, Richard}, + year={2011}, + month=jun } +@article{Mirebeau_2014, + title={Anisotropic Diffusion in ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/en3833}, + DOI={10.54294/en3833}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mirebeau, Jean-marie and Fehrenbach, Jérôme and Risser, Laurent and Tobji, Shaza}, + year={2014}, + month=dec } +@article{Vigneault_2016, + title={Perturbing Mesh Vertices with Additive Gaussian Noise}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/evr01z}, + DOI={10.54294/evr01z}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Vigneault, Davis}, + year={2016}, + month=nov } +@article{Tustison_2011, + title={Run-Length Matrices For Texture Analysis}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/ex0itu}, + DOI={10.54294/ex0itu}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Gee, James}, + year={2011}, + month=may } +@article{Kim_2011, + title={Affine Transformation for Landmark Based Registration Initializer in ITK}, + url={https//dx.doi.org/10.54294/fge470}, + DOI={10.54294/fge470}, + journal={The MIDAS Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Kim, Eun young and Johnson, Hans and Williams, Norman}, + year={2011}, + month=jul } +@article{Hatt_2012, + title={Multi-scale Steerable Phase-Symmetry Filters for ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/gcb82u}, + DOI={10.54294/gcb82u}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Hatt, Charles}, + year={2012}, + month=mar } +@article{Urish_2005, + title={Unsupervised Segmentation for Myofiber Counting in Immunofluorescent Microscopy Images}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/h1vbsl}, + DOI={10.54294/h1vbsl}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Urish, Kenneth and August, Jonas and Huard, Johnny}, + year={2005}, + month=aug } +@article{Warfield_2006, + title={FFT Complex to Complex filters and helper classes}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/h4j7t7}, + DOI={10.54294/h4j7t7}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Warfield, Simon}, + year={2006}, + month=oct } +@article{Johnson_2007, + title={BRAINSFit: Mutual Information Registrations of Whole-Brain 3D Images, Using the Insight Toolkit}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/hmb052}, + DOI={10.54294/hmb052}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Johnson, Hans and Harris, Greg and Williams, Kent}, + year={2007}, + month=oct } +@article{Beare_2005, + title={Finding regional extrema - methods and performance}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/hva3gz}, + DOI={10.54294/hva3gz}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Beare, Richard and Lehmann, Gaetan}, + year={2005}, + month=dec } +@article{Heibel_2007, + title={Shaped Neighborhood based Flood Filled Conditional Iterators}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/iei8xt}, + DOI={10.54294/iei8xt}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Heibel, Hauke and Groher, Martin}, + year={2007}, + month=nov } +@article{Beare_2007_a, + title={Grayscale morphological attribute operations}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/ifvjls}, + DOI={10.54294/ifvjls}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Beare, Richard}, + year={2007}, + month=nov } +@article{Beare_2007_b, + title={Efficient implementation of kernel filtering}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/igq8fn}, + DOI={10.54294/igq8fn}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Beare, Richard and Lehmann, Gaetan}, + year={2007}, + month=jul } +@article{Shamonin_2012, + title={An OpenCL implementation of the Gaussian pyramid and the resampler}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/j5h811}, + DOI={10.54294/j5h811}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Shamonin, Denis and Staring, Marius}, + year={2012}, + month=dec } +@article{Baghdadi_2006, + title={MINC2.0 IO Support for ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/j8lsa6}, + DOI={10.54294/j8lsa6}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Baghdadi, Leila}, + year={2006}, + month=apr } +@article{Tustison_2010, + title={N4ITK: Nick’s N3 ITK Implementation For MRI Bias Field Correction}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/jculxw}, + DOI={10.54294/jculxw}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Gee, James}, + year={2010}, + month=dec } +@article{Burstein_2006, + title={Support for “cub†image format}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/k9nj7c}, + DOI={10.54294/k9nj7c}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Burstein, Pablo and Yushkevich, Paul and Gee, James}, + year={2006}, + month=aug } +@article{Beare_2006, + title={The watershed transform in ITK - discussion and new developments}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/lf8u75}, + DOI={10.54294/lf8u75}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Beare, Richard and Lehmann, Gaetan}, + year={2006}, + month=jun } +@article{Bowers_2013, + title={Principal Components Analysis of Scalar, Vector, and Mesh Vertex Data}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/loekqj}, + DOI={10.54294/loekqj}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Bowers, Michael and Younes, Laurent}, + year={2013}, + month=aug } +@article{Macia_2007, + title={Generalized Computation of Gaussian Derivatives Using ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/mrg5is}, + DOI={10.54294/mrg5is}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Macia, Ivan}, + year={2007}, + month=oct } +@article{Gao_2006, + title={Conformal Flattening ITK Filter}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/msr7a5}, + DOI={10.54294/msr7a5}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Gao, Yi and Melonakos, John and Melonakos, John and Tannenbaum, Allen}, + year={2006}, + month=jul } +@article{Yushkevich_2009, + title={Gaussian Interpolation}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/n8k79e}, + DOI={10.54294/n8k79e}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Yushkevich, Paul and Tustison, Nicholas J. and Gee, James}, + year={2009}, + month=nov } +@article{Tustison_2009_b, + title={Stochastic Fractal Dimension Image}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/ne109t}, + DOI={10.54294/ne109t}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Gee, James}, + year={2009}, + month=apr } +@article{Woehr_2009, + title={A Fast Approximation to the Bilateral Filter for ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/noo5vc}, + DOI={10.54294/noo5vc}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Woehr, Jordan}, + year={2009}, + month=aug } +@article{Bigler_2008, + title={MR Parameter Map Suite: ITK Classes for Calculating Magnetic Resonance T2 and T1 Parameter Maps}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/o8w4c0}, + DOI={10.54294/o8w4c0}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Bigler, Don and Meadowcroft, Mark and Sun, Xiaoyan and Vesek, Jeffrey and Dresner, Alex and Smith, Michael and Yang, Qing}, + year={2008}, + month=jun } +@article{Pincus_2006, + title={ContourExtractor2DImageFilter: A subpixel-precision image isocontour extraction filter.}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/olkmog}, + DOI={10.54294/olkmog}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Pincus, Zachary}, + year={2006}, + month=feb } +@article{Lowekamp_2013, + title={BinShrink: A multi-resolution filter with cache efficient averaging.}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/p39qox}, + DOI={10.54294/p39qox}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lowekamp, Bradley and Chen, David}, + year={2013}, + month=nov } +@article{Lehmann_2007, + title={Label object representation and manipulation with ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/q6auw4}, + DOI={10.54294/q6auw4}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2007}, + month=aug } +@article{Vimort_2017_b, + title={Computing Textural Feature Maps for N-Dimensional images}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/qy48ty}, + DOI={10.54294/qy48ty}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Vimort, Jean-baptiste and Mccormick, Matthew and Budin, Francois and Paniagua, Beatriz}, + year={2017}, + month=jul } +@article{Gelas_2013, + title={Laplacian Mesh Deformation}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/s91axg}, + DOI={10.54294/s91axg}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Gelas, Arnaud}, + year={2013}, + month=jun } +@article{Padfield_2013, + title={A Label Geometry Image Filter for Multiple Object Measurement}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/saa3nn}, + DOI={10.54294/saa3nn}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Padfield, Dirk and Miller, James}, + year={2013}, + month=mar } +@article{Zuki__2016_a, + title={RLEImage: run-length encoded memory compression scheme for an itk::Image}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/t82x76}, + DOI={10.54294/t82x76}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Zukić, Dženan and Mccormick, Matthew and Gerig, Guido and Yushkevich, Paul}, + year={2016}, + month=aug } +@article{Bican_2006, + title={Polar Transforms for ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/t8t3j2}, + DOI={10.54294/t8t3j2}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Bican, Jakub}, + year={2006}, + month=oct } +@article{Tustison_2009_c, + title={Meeting Andy Warhol Somewhere Over the Rainbow: RGB Colormapping and ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/tmojbk}, + DOI={10.54294/tmojbk}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Zhang, Hui and Lehmann, Gaetan and Yushkevich, Paul and Gee, James}, + year={2009}, + month=jan } +@article{Schmidt_Richberg_2014, + title={A Flexible Variational Registration Framework}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/ts6kgm}, + DOI={10.54294/ts6kgm}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Schmidt-Richberg, Alexander and Werner, René and Handels, Heinz and Ehrhardt, Jan}, + year={2014}, + month=may } +@article{Lehmann_2010_c, + title={Deconvolution: infrastructure and reference algorithms}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/tvgfv1}, + DOI={10.54294/tvgfv1}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaëtan}, + year={2010}, + month=aug } +@article{Antiga_2007, + title={Generalizing vesselness with respect to dimensionality and shape}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/urgadx}, + DOI={10.54294/urgadx}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Antiga, Luca}, + year={2007}, + month=aug } +@article{Vercauteren_2008, + title={Diffeomorphic Demons Using ITK’s Finite Difference Solver Hierarchy}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/ux2obj}, + DOI={10.54294/ux2obj}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Vercauteren, Tom and Pennec, Xavier and Perchant, Aymeric and Ayache, Nicholas}, + year={2008}, + month=nov } +@article{Vimort_2017_a, + title={Computing Bone Morphometric Feature Maps from 3-Dimensional Images}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/vctqy4}, + DOI={10.54294/vctqy4}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Vimort, Jean-baptiste and Mccormick, Matthew and Paniagua, Beatriz}, + year={2017}, + month=nov } +@article{Lehmann_2010_a, + title={Noise simulation}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/vh6vbw}, + DOI={10.54294/vh6vbw}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2010}, + month=jul } +@article{Zhu_2011, + title={Triangle Mesh Subdivision}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/vw0ke0}, + DOI={10.54294/vw0ke0}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Zhu, Wanlin}, + year={2011}, + month=jul } +@article{Hawley_2009, + title={Reader/Writer for Analyze Object Maps for ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/w2jytv}, + DOI={10.54294/w2jytv}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Hawley, Jeffrey and Johnson, Hans}, + year={2009}, + month=mar } +@article{Mosaliganti_2009_c, + title={Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/wvwmf8}, + DOI={10.54294/wvwmf8}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mosaliganti, Kishore and Smith, Benjamin and Gelas, Arnaud and Gouaillard, Alexandre and Megason, Sean}, + year={2009}, + month=may } +@article{Lehmann_2006_e, + title={FFT Shift}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/xd0lzg}, + DOI={10.54294/xd0lzg}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2006}, + month=oct } +@article{Lehmann_2006_f, + title={Label overlay}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/xr1bvx}, + DOI={10.54294/xr1bvx}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lehmann, Gaetan}, + year={2006}, + month=feb } +@article{Tustison_2017, + title={A patch-based framework for new ITK functionality: Joint fusion, denoising, and non-local super-resolution}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/ywuouh}, + DOI={10.54294/ywuouh}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Avants, Brian and Wang, Hongzhi and Xie, Long and Coupe, Pierrick and Yushkevich, Paul and Manjon, Jose}, + year={2017}, + month=mar } +@article{Mueller_2008, + title={Fast Marching Minimal Path Extraction in ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/z5zwhh}, + DOI={10.54294/z5zwhh}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mueller, Dan}, + year={2008}, + month=mar } +@article{Zosso_2007, + title={Direct Fourier Tomographic Reconstruction Image-To-Image Filter}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/z83ly1}, + DOI={10.54294/z83ly1}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Zosso, Dominique and Bach Cuadra, Meritxell and Thiran, Jean-Philippe}, + year={2007}, + month=aug } +@article{Tustison_2007_a, + title={Gridding Graphic Graticules}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/ze1ssz}, + DOI={10.54294/ze1ssz}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Tustison, Nicholas J. and Avants, Brian and Gee, James}, + year={2007}, + month=jan } +@article{Mccormick_2010_a, + title={Higher Order Accurate Derivative and Gradient Calculation in ITK}, + ISSN={2327-770X}, + url={https//dx.doi.org/10.54294/zv7979}, + DOI={10.54294/zv7979}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mccormick, Matthew}, + year={2010}, + month=nov } +@article{Mccormick_2010_b, + title={An Open Source, Fast Ultrasound B-Mode Implementation for Commodity Hardware}, + ISSN={2327-770X}, + url={http://dx.doi.org/10.54294/yjowe4}, + DOI={10.54294/yjowe4}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Mccormick, Matthew}, + year={2010}, + month=may } +@article{Lowekamp_2010, + title={A Streaming IO Base Class and Support for Streaming the MRC and VTK File Format}, + ISSN={2327-770X}, + url={http://dx.doi.org/10.54294/ufs19w}, + DOI={10.54294/ufs19w}, + journal={The Insight Journal}, + publisher={NumFOCUS - Insight Software Consortium (ITK)}, + author={Lowekamp, Bradley and Chen, David}, + year={2010}, + month=jun } diff --git a/Documentation/Maintenance/Release.md b/Documentation/Maintenance/Release.md index 030d90000cb..f3c672b0d79 100644 --- a/Documentation/Maintenance/Release.md +++ b/Documentation/Maintenance/Release.md @@ -9,7 +9,7 @@ Current Maintainers The current ITK maintainers with a trusted GPG key are: - * Matt McCormick (@thewtex) + * Matt McCormick (@thewtex) * Pablo Hernandez-Cerdan * Brad King (@bradking) * Jean-Christophe Fillion-Robin (@jcfr) @@ -37,8 +37,8 @@ When releasing a new ITK version, the following steps are be taken: * Tarballs are tested locally. * Generate Python packages and ITKPythonBuilds. * Tarballs are posted to [ITK GitHub Releases]. - * Tarballs are archived on the [ITK data.kitware.com Releases]. - * Tarballs are linked from the ITK [download page]. + * Tarballs are archived on the [ITKReleases NumFOCUS GDrive]. + * Tarballs are linked from the [ITK Documentation]. * Python packages are uploaded to PyPI * conda-forge libitk and itk Packages are updated * Announcement @@ -75,7 +75,7 @@ When releasing a new ITK version, the following steps are be taken: * **Updating documentation, guides and websites**. * **Generate tarballs** * Tarballs are posted to [ITK GitHub Releases]. - * Tarballs are linked from the ITK [download page]. + * Tarballs are linked from the [ITK Documentation]. * Announcement Initial steps @@ -204,7 +204,7 @@ Archive ExternalData -------------------- More background on the testing data can be found in the -[Contributing Upload Binary Data][../docs/contributing/upload_binary_data.md) documentation. +[Contributing Upload Binary Data](../docs/contributing/upload_binary_data.md) documentation. The following steps archive data for release on various resources. Both [datalad] and [@web3-storage/w3cli] should be installed locally. And the [kubo] @@ -254,8 +254,9 @@ datalad save -m "ENH: Pre-updates for ITK-v" Upload the tree to archival storage with: ```bash +rm -rf ~/data/pre-archive && rm -f ~/data/pre-archive.tar.gz datalad export-archive ~/data/pre-archive -rm -rf ~/data/pre-archive && mkdir -p ~/data/pre-archive && tar -xf ~/data/pre-archive.tar.gz -C ~/data/ +tar -xf ~/data/pre-archive.tar.gz -C ~/data/ cd ~/data/pre-archive w3 put . --no-wrap -n ITKData-pre-verify -H cd - @@ -282,8 +283,9 @@ add your DID, obtained with `w3 whoami`, to the shared space. Upload the repository update to web3.storage: ```bash +rm -rf ~/data/itk-archive && rm -f ~/data/itk-archive.tar.gz +tar -xf ~/data/itk-archive.tar.gz -C ~/data/ datalad export-archive ~/data/itk-archive -rm -rf ~/data/itk-archive && mkdir -p ~/data/itk-archive && tar -xf ~/data/itk-archive.tar.gz -C ~/data/ cd ~/data/itk-archive w3 put . --no-wrap -n ITKData-v -H cd - @@ -303,11 +305,13 @@ If the [pinata] pinning service is not already available, create it: ```bash ipfs pin remote service add pinata https://api.pinata.cloud/psa/ PINATA_JWT ``` +Where `PINATA_JWT` is the secret key associated to an API key at the +InsightSoftwareConsortium workspace in pinata. Then pin the root CID locally and on Pinata: ```bash -ipfs pin add /ipfs/bafy +ipfs pin add /ipfs/bafy --progress ipfs pin remote add --service=pinata --name=ITKData-ITK-v /ipfs/bafy ``` @@ -403,6 +407,14 @@ git push upstream $major_minor Add any new remote modules to nightly builds. Some builds may be difficult to add due to third-party dependencies. +When a new ITK version is released, experience has shown that the remote +module packages are not binary compatible across ITK major or minor releases. +While we attempt to maintain API compatibility between ITK minor releases, the +ABI generally changes. This can be due to features and bug fixes in the ITK +source code, but there are also usually build system changes that cause ABI +changes. Thus, remote module versions should be bumped into a new major +version when requiring a new ITK major or minor version. The process described +below ensures appropriate versioning and compatibility of the remotes with ITK. Update Remote Modules --------------------- @@ -486,6 +498,14 @@ md5sum ./Insight* > MD5SUMS sha512sum ./Insight* > SHA512SUMS ``` +Sign the source and data tarballs. + +``` +for ff in Insight*; do gpg --armor --detach-sign $ff; done +``` + +The `*.asc` files provide a [signed release]. + Generate Python Packages ------------------------ @@ -702,33 +722,19 @@ Generate Doxygen Documentation Note: links to the nightly generated Doxygen can be found in the footer of the Doxygen HTML pages. Use the files to upload and create: - * `InsightDoxygenDocTag-MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION.gz` - * `InsightDoxygenXml-MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION.tar.gz` - * `InsightDoxygenDocHtml-MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION.tar.gz.` + * `InsightDoxygenDocTag-$MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION.gz` + * `InsightDoxygenXml-$MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION.tar.gz` + * `InsightDoxygenDocHtml-$MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION.tar.gz.` Prior to the release, new `Remote` modules should be enabled in the Doxygen build's configuration. -Run CMake in the binary build and enable `BUILD_DOXYGEN`, configure and -generate, then: - -```bash -cd Binaries/ITK -make Documentation -cd Utilities -mv old_doxygen_directory DoxygenInsightToolkit-$MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION -tar -cf DoxygenInsightToolkit-$MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION.tar DoxygenInsightToolkit-$MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION -gzip -9 DoxygenInsightToolkit-$MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION.tar -``` - -Historical note: Before ITK 3.8, the documentation used to be generated in a -directory called `Documentation/Doxygen`. +Download the tarballs from the `latest` [ITKDoxygen Release] and rename the files to use +the current version. Create a new [ITKDoxygen Release] with the files on a +`v$MAJOR_VERSION.$MINOR_VERSION.$PATCH_VERSION` tag. -Unpackage the Doxygen tarball, then upload to the Kitware web server to serve -at "https://itk.org/Doxygen$MAJOR_VERSION$MINOR_VERSION/html/". Contact -Kitware Sys-admin to setup a new rsync target. After the upload is complete, -verify that routing is set up so the path is not clobbered by the website / -blog. +ReadTheDocs will automatically generate a new rendered version based on this +tagged release. Update the ITK Software Guide ----------------------------- @@ -808,6 +814,33 @@ gzip -9 ${prefix}.tar git archive --format=zip -9 --prefix=${prefix}/ --output=${prefix}.zip ${tag} ``` +Release Notes Posts +------------------- + +To get started with the release notes, first use the download link +cookiecutter to generate [download page](https://github.com/InsightSoftwareConsortium/ITK/blob/master/Documentation/docs/download.md) markdown: + +```bash +pip install cookiecutter +cookiecutter ~/src/ITK/Utilities/Maintenance/DownloadLinksCookieCutter/ +``` + +Start with the previous GitHub Release markdown content to produce the +release notes. + +To generate the changelog by running + +```bash +cd ITK +./Utilities/Maintenance/AuthorsChangesSince.py $old_version +``` + +The log is generated at */tmp/AuthorsChangesSince/Changelog.md*. + +The count of recent authors is found in the script output, and a list of new authors +are found at */tmp/AuthorsChangesSince/NewAuthors.txt*. + + Upload the release artifacts to GitHub -------------------------------------- @@ -837,6 +870,10 @@ Upload the release artifacts. These include: - InsightToolkit-$version.zip - InsightData-$version.tar.gz - InsightData-$version.zip +- InsightToolkit-$version.tar.gz.asc +- InsightToolkit-$version.zip.asc +- InsightData-$version.tar.gz.asc +- InsightData-$version.zip.asc - MD5SUMS - SHA512SUMS - InsightDoxygenDocHtml-$version.tar.gz @@ -855,12 +892,10 @@ pre-release* box. Click *Update release*. -Upload the release artifacts to data.kitware.com +Upload the release artifacts to GDrive ------------------------------------------------ -Backup and archive the release artifacts in the [data.kitware.com ITK -Collection Releases -folder](https://data.kitware.com/#collection/57b5c9e58d777f126827f5a1/folder/5b1ec0378d777f2e622561e9). +Backup and archive the release artifacts in the [ITKReleases NumFOCUS GDrive]. This should include @@ -879,18 +914,19 @@ a PR. Update the Website ------------------ -The website is managed by Kitware folks. Access is currently granted to the ITK +Update the [download]. + +Access is currently granted to the ITK maintainer group. * Add or modify the `Current Release` entries on the - [download page](https://itk.org/ITK/resources/software.html). - * Update the [documentation page](https://itk.org/ITK/help/documentation.html) with a - link to the Doxygen files for the new release. - * Update the API documentation with a new link. See [PR 3804](https://github.com/InsightSoftwareConsortium/ITK/pull/3804/commits/fb00e5b22ad0e5e838779965bfe7254edaae18d1) for an example change. + [download page] * Verify that the links work ! -Contact Communications at in order to update the above pages -and to produce a press release. +The itk.org website is managed by Kitware folks. Contact Dženan Zukić +in order to create a WordPress blog post for the release with the release +notes. This will generate a new entry on the https://itk.org landing page for +the release. Update Issue Tracker -------------------- @@ -912,33 +948,6 @@ This means that a number of ITK developers should download the tarballs or do Git checkouts with the release tag, and build the toolkit in as many configurations as possible. -Release Notes Posts -------------------- - -To get started with the release notes, first use the download link -cookiecutter to generate [Download page](https://github.com/InsightSoftwareConsortium/ITK/blob/master/Documentation/docs/download.md) markdown: - -```bash -pip install cookiecutter -cookiecutter ~/src/ITK/Utilities/Maintenance/DownloadLinksCookieCutter/ -``` - -Start with the previous GitHub Release markdown content to produce the -release notes. - -To generate the changelog by running - -```bash -cd ITK -./Utilities/Maintenance/AuthorsChangesSince.py $old_version -``` - -The log is generated at */tmp/AuthorsChangesSince/Changelog.md*. - -The count of recent authors is found in the script output, and a list of new authors -are found at */tmp/AuthorsChangesSince/NewAuthors.txt*. - - Announcements ------------- @@ -973,11 +982,12 @@ excellent packaging. [Dashboard]: https://open.cdash.org/index.php?project=Insight [datalad]: https://www.datalad.org/ [community]: https://discourse.itk.org/ -[documentation page]: https://www.itk.org/ITK/help/documentation.html -[download page]: https://itk.org/ITK/resources/software.html +[documentation page]: https://docs.itk.org/ +[download page]: https://docs.itk.org/en/latest/download.html [GitHub]: https://github.com/InsightSoftwareConsortium/ITK [IPFS]: https://ipfs.tech/ [ipfs-desktop]: https://github.com/ipfs/ipfs-desktop/releases +[ITKDoxygen Release]: https://github.com/InsightSoftwareConsortium/ITKDoxygen/releases [ITKPythonPackage]: https://itkpythonpackage.readthedocs.io/en/latest/index.html [ITKTestingData]: https://github.com/InsightSoftwareConsortium/ITKTestingData [ITK discussion]: https://discourse.itk.org/ @@ -985,12 +995,14 @@ excellent packaging. [ITK Open Collective page]: https://opencollective.org/itk [ITK issue tracking]: https://issues.itk.org/ [ITK Software Guide]: https://itk.org/ItkSoftwareGuide.pdf -[ITK wiki]: https://itk.org/Wiki/ITK -[ITK Sphinx examples]: https://itk.org/ITKExamples/ +[ITK wiki]: https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK +[ITK Sphinx examples]: https://examples.itk.org/ +[ITKReleases NumFOCUS GDrive]: https://drive.google.com/drive/folders/1-uE7lKAZN4PT52vJJuDqr6KT656r6Dn_?usp=drive_link [kubo]: https://github.com/ipfs/kubo [pinata]: https://pinata.cloud -[releases page]: https://itk.org/Wiki/ITK/Releases -[release schedule]: https://itk.org/Wiki/ITK/Release_Schedule +[releases page]: https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK/Releases +[release schedule]: https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK/Release_Schedule +[signed release]: https://github.com/ossf/scorecard/blob/49c0eed3a423f00c872b5c3c9f1bbca9e8aae799/docs/checks.md#signed-releases [Software Guide]: https://itk.org/ItkSoftwareGuide.pdf [@web3-storage/w3cli]: https://www.npmjs.com/package/@web3-storage/w3cli [install the w3cli]: https://web3.storage/docs/w3cli/ @@ -1003,6 +1015,5 @@ excellent packaging. [ResearchGate]: https://www.researchgate.net/project/Insight-Toolkit-ITK [SourceForge]: https://sourceforge.net/downloads/itk/itk/ [ITK GitHub Releases]: https://github.com/InsightSoftwareConsortium/ITK/releases -[ITK data.kitware.com Releases]: https://data.kitware.com/#item/5b22a47f8d777f2e622564d8 [ITK GitHub Milestones]: https://github.com/InsightSoftwareConsortium/ITK/milestones [macos-14 GitHub Action Runner]: https://github.com/actions/runner-images/blob/main/images/macos/macos-14-Readme.md diff --git a/Documentation/docs/_static/icon/html_head_content.txt b/Documentation/docs/_static/icon/html_head_content.txt index 63b9f2077dc..f847964afda 100644 --- a/Documentation/docs/_static/icon/html_head_content.txt +++ b/Documentation/docs/_static/icon/html_head_content.txt @@ -6,4 +6,4 @@ - \ No newline at end of file + diff --git a/Documentation/docs/conf.py b/Documentation/docs/conf.py index e7c98d4b9d7..0a92ba0365a 100644 --- a/Documentation/docs/conf.py +++ b/Documentation/docs/conf.py @@ -6,31 +6,40 @@ # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information +import os from datetime import date -project = 'ITK' -copyright = f'{date.today().year}, NumFOCUS' -author = 'Insight Software Consortium' +project = "ITK" +copyright = f"{date.today().year}, NumFOCUS" +author = "Insight Software Consortium" + +# Define the canonical URL if you are using a custom domain on Read the Docs +html_baseurl = os.environ.get("READTHEDOCS_CANONICAL_URL", "docs.itk.org") + +html_context = {} +# Tell Jinja2 templates the build is running on Read the Docs +if os.environ.get("READTHEDOCS", "") == "True": + html_context["READTHEDOCS"] = True extensions = [ - 'sphinx.ext.napoleon', - 'myst_parser', - 'sphinx.ext.intersphinx', - 'sphinx_copybutton', - 'sphinxext.opengraph', - 'sphinx_design', + "sphinx.ext.napoleon", + "myst_parser", + "sphinx.ext.intersphinx", + "sphinx_copybutton", + "sphinxext.opengraph", + "sphinx_design", ] myst_enable_extensions = [ "colon_fence", "dollarmath", # Support syntax for inline and block math using `$...$` and `$$...$$` - # (see https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#dollar-delimited-math) + # (see https://myst-parser.readthedocs.io/en/latest/syntax/optional.html#dollar-delimited-math) "fieldlist", "linkify", # convert bare links to hyperlinks ] -templates_path = ['_templates'] -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] +templates_path = ["_templates"] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] intersphinx_mapping = { @@ -38,8 +47,8 @@ "numpy": ("https://numpy.org/doc/stable", None), } -html_theme = 'furo' -html_static_path = ['_static'] +html_theme = "furo" +html_static_path = ["_static"] # html_logo = "_static/itk-logo.svg" html_logo = "_static/itk-logo-low-res.png" html_favicon = "_static/icon/favicon.ico" diff --git a/Documentation/docs/contributing/dashboard.md b/Documentation/docs/contributing/dashboard.md index f4dd58233ad..3489ff9a550 100644 --- a/Documentation/docs/contributing/dashboard.md +++ b/Documentation/docs/contributing/dashboard.md @@ -14,7 +14,7 @@ commands to track it: mkdir -p ~/Dashboards/ITKScripts cd ~/Dashboards/ITKScripts git init -git remote add -t dashboard origin https://itk.org/ITK.git +git remote add -t dashboard origin https://github.com/InsightSoftwareConsortium/ITK.git git pull origin ``` diff --git a/Documentation/docs/contributing/documenting_itk.md b/Documentation/docs/contributing/document_itk.md similarity index 99% rename from Documentation/docs/contributing/documenting_itk.md rename to Documentation/docs/contributing/document_itk.md index aa5c459a3b0..562783d3320 100644 --- a/Documentation/docs/contributing/documenting_itk.md +++ b/Documentation/docs/contributing/document_itk.md @@ -1,4 +1,4 @@ -# Documenting ITK +# Document ITK The ITK code documentation is available online at https://docs.itk.org/projects/doxygen/. @@ -149,5 +149,5 @@ and the second one being the title of the example in the #### Maintaining the documentation The documentation is built nightly on the latest ITK commit, and deployed to GitHub pages -at https://insightsoftwareconsortium.github.io/ITKDoxygen/, whose code is maintaned at +at https://insightsoftwareconsortium.github.io/ITKDoxygen/, whose code is maintained at https://github.com/InsightSoftwareConsortium/ITKDoxygen. diff --git a/Documentation/docs/contributing/index.md b/Documentation/docs/contributing/index.md index 5bb7f06aa3d..388b66e7b8a 100644 --- a/Documentation/docs/contributing/index.md +++ b/Documentation/docs/contributing/index.md @@ -1,9 +1,9 @@ -Contributing to ITK -=================== +Contribute to ITK +================= Welcome to the Insight Toolkit (ITK) ! We are excited that you are here! Join us as a contributing member of the community. -![Contributor graph](https://contributor-graph-api.apiseven.com/contributors-svg?chart=contributorOverTime&repo=InsightSoftwareConsortium/ITK) +[![Alt](https://repobeats.axiom.co/api/embed/e2194d411e086b1a9a9db4336692fdb302612295.svg "Repobeats analytics image")](https://github.com/InsightSoftwareConsortium/ITK/pulse/monthly) This article documents how to contribute improvements to ITK. @@ -17,7 +17,7 @@ Setup Before you begin, perform initial setup: 1. [Register for a GitHub](https://github.com/join) account. - 2. Optionally download our [one page PDF desk reference](https://raw.githubusercontent.com/InsightSoftwareConsortium/ITK/master/Documentation/GitCheatSheet.pdf). + 2. Optionally download our [one page PDF desk reference](https://raw.githubusercontent.com/InsightSoftwareConsortium/ITK/master/Documentation/docs/contributing/GitCheatSheet.pdf). 3. Follow the [download instructions] to create a local ITK clone: ```bash @@ -313,25 +313,42 @@ After a feature topic has been reviewed and approved in GitHub, ITK maintainers will merge it into the upstream repository via the GitHub user interface. -(*If the merge conflicts follow the printed instructions to resolve them.*) +If the merge conflicts follow the printed instructions to resolve them. + +If a new contributor has not learned how to amend and force-push updates to +their branch into logical commits (preferred), maintainers should use the +*Squash and merge* button on the pull request to consolidate patches into +logical commits. For bug fixes that are ready to be included in the next patch release, make a comment on the pull request which states the topic should be merged to the -`release` branch. +`release` and `release-X.X` maintenance branch, where `X.X` are the current +maintenance version, e.g. `5.4`. Here are the recommended steps to merge a topic to both `release` and `master` branches, assuming the topic branch is forked off the `release` branch: ```bash -git checkout release +git checkout release-X.X +git pull --ff-only upstream release-X.X git merge --no-ff my-topic +git push upstream release-X.X +``` + +then: + +```bash +git checkout release +git pull --ff-only upstream release +git merge --no-ff release-X.X git push upstream release ``` -and do: +then: ```bash git checkout master +git pull --ff-only upstream master git merge --no-ff release git push upstream master ``` @@ -392,6 +409,10 @@ Actual releases have tags named by the release version number. :caption: 📖 More Information build_test_itk.md +document_itk.md +upload_binary_data.md +data.md +module_workflows.md ITK Software Guide, Book 1, Part III: Development Guidelines git_help.md GitHub flow guide @@ -399,10 +420,6 @@ ITK Git Cheatsheet dashboard.md updating_third_party.md -data.md -documenting_itk.md -upload_binary_data.md -module_workflows.md python_packaging.md ../README.md ``` diff --git a/Documentation/docs/contributing/python_packaging.md b/Documentation/docs/contributing/python_packaging.md index 679e37a0e30..65f4f539322 100644 --- a/Documentation/docs/contributing/python_packaging.md +++ b/Documentation/docs/contributing/python_packaging.md @@ -20,7 +20,7 @@ Building ITK Python wheels requires the following: - CMake >= 3.16 - Git - C++ Compiler (see [scikit-build platform specific requirements](https://scikit-build.readthedocs.io/en/latest/generators.html)) -- Python >= 3.8 +- Python >= 3.9 ## Automated Platform Scripts diff --git a/Documentation/docs/contributing/updating_third_party.md b/Documentation/docs/contributing/updating_third_party.md index df8d08e4d1c..f88e99a5f09 100644 --- a/Documentation/docs/contributing/updating_third_party.md +++ b/Documentation/docs/contributing/updating_third_party.md @@ -3,7 +3,7 @@ Updating Third Party Projects When updating a third party project, any changes to the imported project itself (e.g., the `ThirdParty/VNL` directory for VNL), should go through the -[UpdateThirdPartyFromUpstream.sh] framework. This framework ensures that all +[update-third-party.bash] framework. This framework ensures that all patches to the third party projects are tracked externally and available for (preferably) upstream or other projects also embedding the library. @@ -78,12 +78,12 @@ git push --set-upstream insight for/itk Making the initial import involves filling out the project's `UpdateFromUpstream.sh` script in its directory. The -[UpdateThirdPartyFromUpstream.sh] script describes what is +[update-third-party.bash] script describes what is necessary, but in a nutshell, it is basically metadata such as the name of the project and where it goes in the importing project. Use the instructions in the comments at the top of the -[UpdateThirdPartyFromUpstream] script to know the essential parts each third +[update-third-party.bash] script to know the essential parts each third party module's `UpdateFromUpstream.sh` script should have. Make sure `UpdateFromUpstream.sh` is executable before commit. On Unix, run: @@ -116,4 +116,4 @@ if necessary. -[UpdateThirdPartyFromUpstream.sh]: https://github.com/InsightSoftwareConsortium/ITK/blob/master/Utilities/Maintenance/UpdateThirdPartyFromUpstream.sh +[update-third-party.bash]: https://github.com/InsightSoftwareConsortium/ITK/blob/master/Utilities/Maintenance/update-third-party.bash diff --git a/Documentation/docs/index.md b/Documentation/docs/index.md index c7ee2e934ab..102fff14845 100644 --- a/Documentation/docs/index.md +++ b/Documentation/docs/index.md @@ -35,6 +35,7 @@ Tutorial learn/faq.md learn/dicom.md +learn/metaio.md learn/courses.md learn/third_party_applications.md learn/fda_off_the_shelf_sw_guidelines.md diff --git a/Documentation/docs/learn/dicom.md b/Documentation/docs/learn/dicom.md index ea5e8abf5ed..89d26ac3959 100644 --- a/Documentation/docs/learn/dicom.md +++ b/Documentation/docs/learn/dicom.md @@ -6,7 +6,7 @@ A question that is often asked is: I am trying to read/write a DICOM image, but the pixel data has changed (the scalar range has changed from input file). This surely comes from the fact that you did not used the proper -pixel type to instanciate your reader. You have to consider: +pixel type to instantiate your reader. You have to consider: - `Bits Allocated` - `Bits Stored` @@ -114,7 +114,7 @@ is however allowed that both files uses different transfer syntax uid (implicit/explicit, little/big endian). When a DICOM file is sent to a PACS, it is up to the implementor to decide what to do in case of duplicate `SOP Instance UID`. In most case you should expect that the -image is not resent, as standard garantee this is already the same +image is not resent, as standard guarantee this is already the same object. > âš ï¸ **Warning** diff --git a/Documentation/docs/learn/faq.md b/Documentation/docs/learn/faq.md index f4f072ec7f5..656f2f56fac 100644 --- a/Documentation/docs/learn/faq.md +++ b/Documentation/docs/learn/faq.md @@ -43,7 +43,7 @@ images. | [ITK HDF5](https://support.hdfgroup.org/HDF5/) | | | | [JPEG](https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format) † | [`itk::JPEGImageIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1JPEGImageIO.html) | | | [LSM](https://www.openwetware.org/wiki/Dissecting_LSM_files) | [`itk::LSMImageIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1LSMImageIO.html) | | -| [MetaImage](https://itk.org/Wiki/ITK/MetaIO/Documentation) (.mha/.mhd) | [`itk::MetaImageIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1MetaImageIO.html) | | +| [MetaImage](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK/MetaIO/Documentation) (.mha/.mhd) | [`itk::MetaImageIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1MetaImageIO.html) | | | [MINC 2.0](https://en.wikibooks.org/wiki/MINC/SoftwareDevelopment/MINC2.0_File_Format_Reference) (Medical Image NetCDF) | [`itk::MINCImagIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1MINCImageIO.html) | | | [MGH](https://surfer.nmr.mgh.harvard.edu/fswiki/FsTutorial/MghFormat) | [`itk:MGHImageIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1MGHImageIO.html) | | | [MRC](http://www.ccpem.ac.uk/mrc_format/mrc_format.php) | [`itk::MRCImageIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1MRCImageIO.html) | | @@ -66,7 +66,7 @@ possible to read/write 3D datasets as collections of 2D slices each one in an independent BMP, PNG or JPEG file by using the [`ImageSeriesReader`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1ImageSeriesReader.html) and [`itk::ImageSeriesWriter`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1ImageSeriesWriter.html). -‡ It is higly recommended not using this format. RAW is not a format, it +‡ It is highly recommended not using this format. RAW is not a format, it is insufficient, inconsistent and simply dangerous. A RAW file without a header is useless, and once you add a header, it is not RAW anymore. @@ -92,8 +92,7 @@ formats: | File Format | Read/Write | Import | | ----------- | ---------- | ------ | -| [BYU](http://www.eg-models.de/formats/Format_Byu.html) | - [`itk::BYUMeshIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1BYUMeshIO.html) | | +| [BYU](http://www.eg-models.de/formats/Format_Byu.html) | [`itk::BYUMeshIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1BYUMeshIO.html) | | | [FreeSurfer surface, binary and ASCII](http://www.grahamwideman.com/gw/brain/fs/surfacefileformats.htm) | [`itk::FreeSurferBinaryMeshIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1FreeSurferBinaryMeshIO.html), [`itk::FreeSurferAsciiMeshIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1FreeSurferAsciiMeshIO.html) | | | [OFF](https://en.wikipedia.org/wiki/OFF_%28file_format%29) | [`ìtk::OFFMeshIO`](https://docs.itk.org/projects/doxygen/en/stable/classitk_1_1OFFMeshIO.html) | | | [STL](https://en.wikipedia.org/wiki/STL_%28file_format%29) | | | @@ -132,7 +131,7 @@ in case of desperation. please look at the [`DicomSeriesReadImageWrite2.cxx`](https://github.com/InsightSoftwareConsortium/ITK/blob/master/Examples/IO/DicomSeriesReadImageWrite2.cxx) code. 1. Write a MetaImage header. This is a small text file holding - information about the image: spacing, dimensions, pixelt type, etc. + information about the image: spacing, dimensions, pixel type, etc. This header can hold the list of DICOM files you want to read. The only restriction is that the files must be uncompressed. You can take an existing MetaImage header and modify it in order to fit @@ -158,7 +157,7 @@ GDCM is an open source package developed by the Creatis team at INSA-Lyon. It is distributed under a license similar to ITK: http://gdcm.sourceforge.net/Copyright.html. GCDM uses CMake in order to configure its build process, so you will -find a familiar setup. Once you download, configure and buid GDCM, you +find a familiar setup. Once you download, configure and build GDCM, you can reconfigure ITK by running CMake in your ITK build, going into the advanced options and enabling `USE_GDCM`. @@ -367,7 +366,7 @@ Please see the [Contribute to ITK page](https://docs.itk.org/en/latest/contribut ### Is ITK tested? -Please see this page: [ITK/Testing](https://itk.org/Wiki/ITK/Testing). +Please see this page: [ITK/Testing](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK/Testing). ## Working with image data @@ -415,9 +414,9 @@ More details can be found in the Wikipedia article [Houndfield Units](https://en MRI images measure two types of relaxation times, T1 and T2. -The units are millisecons and the two relaxation concepts relate to how +The units are milliseconds and the two relaxation concepts relate to how long it takes for the molecules in the tissue to realign themselves with -a magentic field after being perturbed. +a magnetic field after being perturbed. Details on the MRI units are available on the [Relaxation (NMR)](https://en.wikipedia.org/wiki/Relaxation_%28NMR%29) Wikipedia article. @@ -459,9 +458,9 @@ High Bit = 15 Since DICOM V3, you **cannot** store any overlay in the unused bits of the `Pixel Data` (`0x7fe0,0x0010`), thus it imply that the unused bits are **zeros**. In ITK, there is no such thing as 12-bit pixel type, thus -when instanciating your reader you declare a 16-bit pixel type. This +when instantiating your reader you declare a 16-bit pixel type. This buffer is then passed back to GDCM which sees an array of 16bits values -and then simply used the simpliest way to store this buffer back on +and then simply used the simplest way to store this buffer back on disk: `Bits Stored = 16` and `High Bit = 15`. In case you have not made any change to your pixel buffer, implicitly the first 4 bits will be zero again. The only difference being that they are not as clearly declared diff --git a/Documentation/docs/learn/fda_sw_development_guidelines.md b/Documentation/docs/learn/fda_sw_development_guidelines.md index ad7fa2c7169..226e14e3fb3 100644 --- a/Documentation/docs/learn/fda_sw_development_guidelines.md +++ b/Documentation/docs/learn/fda_sw_development_guidelines.md @@ -37,11 +37,11 @@ development of your application. That will included things like: It is worth to point out that the software development process using in ITK and VTK are already following many of the FDA Guidelines for -software developement. In particular +software development. In particular - Continuous Testing via Dashboard ([CTest](https://cmake.org/cmake/help/latest/manual/ctest.1.html)) - Version control ([git](https://git-scm.com/)) -- Configuration standarization ([CMake](https://cmake.org/)) +- Configuration standardization ([CMake](https://cmake.org/)) - Bug tracking ([GitHub](https://github.com/features/issues)/[GitLab issues](https://docs.gitlab.com/ee/user/project/issues/)) ## General guidelines @@ -57,5 +57,5 @@ medical devices you must look at the following documents: - [Guidance for the Submission of Premarket Notifications For Radionuclide Dose Calibrators - Guidance for Industry](https://www.fda.gov/regulatory-information/search-fda-guidance-documents/guidance-submission-premarket-notifications-radionuclide-dose-calibrators-guidance-industry) - [Content of Premarket Submissions for Device Software Functions](https://www.fda.gov/regulatory-information/search-fda-guidance-documents/content-premarket-submissions-device-software-functions) -These and other relevant documents can be found at the [FDA Guidance Doument search](https://www.fda.gov/regulatory-information/search-fda-guidance-documents) +These and other relevant documents can be found at the [FDA Guidance Document search](https://www.fda.gov/regulatory-information/search-fda-guidance-documents) and the [Medical Devices and Radiation-Emitting Products Guidance Documents](https://www.fda.gov/medical-devices/device-advice-comprehensive-regulatory-assistance/guidance-documents-medical-devices-and-radiation-emitting-products) sites. diff --git a/Documentation/docs/learn/metaio.md b/Documentation/docs/learn/metaio.md new file mode 100644 index 00000000000..4a564820179 --- /dev/null +++ b/Documentation/docs/learn/metaio.md @@ -0,0 +1,1145 @@ +# MetaIO + +## Abstract + +MetaImage is the text-based tagged file format for medical images that resulted. +We have now extended that file format to support a variety of objects that occur +in medicine such a tubes (for vessels, needles, etc.), blobs (for arbitrary +shaped objects), cubes, spheres, etc. The complete library is known at MetaIO. + +The central code of MetaImage/MetaIO is quite stable. MetaImage has been in use +for several years by a wide range of research at UNC, Chapel Hill. New features +are occasionally added, but backward compatibility will always be maintained. + +## Introduction and Installation + +### Obtaining MetaIO + +1. The [upstream MetaIO Git repository](https://github.com/Kitware/MetaIO) is + available on GitHub. + +MetaIO is being distributed with the following packages: + +- National Library of Medicine’s Insight Toolkit (ITK) for medical image + segmentation and registration. +- Kitware's Visualization Toolkit (VTK). + +### Installing The MetaIO Package + +MetaIO is a hierarchy of C++ classes and functions. We have yet to find a modern +C++ compiler that does not compile MetaIO. Supported compilers include +[ITK's supported compilers](../supported_compilers.md). + +MetaIO is built as part of the standard ITK and VTK installations. It is +also quite easy to use MetaIO from within these toolkits without using the rest +of the toolkit. + +#### ITK MetaIO + +The hierarchy of the software in the stand-alone MetaIO package is as follows: + +- MetaIO/ + - doc/ + - tests/ + +The top level contains the source files, the header files, and the +`CMakeLists.txt` file that is used by the CMake program to compile MetaIO. This +document and the MetaObjects www pages are in the `doc` directory. A sequence of +simple tests is available in the `tests` directory. + +The hierarchy of the software in the Insight and InsightApplications +distributions is as follows: + +- ITK + - Modules/ThirdParty/MetaIO/src/MetaIO/src + - doc/ + - tests/ + +Routines that wrap MetaIO for ITK's image IO object factory are in: + +- ITK/Modules/IO/Meta + - `itkMetaImageIO` + +Routines that wrap MetaIO for reading and writing ITKS's Spatial Objects (tubes, +blobs, ellipses, meshes, etc.) are in: + +- ITK/Modules/Core/SpatialObjects + +#### Stand Alone MetaIO + +MetaIO can also be compiled outside of these toolkits. This is left as an +exercise to the user (hint: requires the kwsys and zlib libraries). Instead of a +stand-alone installation, we highly recommend using the distribution in ITK - if +you build ITK, you get MetaIO for free! + +## Quick Start + +### Data conversion via MetaHeaders + +This section assumes that you have data that you wish to process using an +application that reads MetaImages. This section gives examples on how “convert†+your data to the MetaImage format. + +For uncompressed data, “conversion†to MetaImage is actually just a matter of +specifying a MetaImage Headerfile (a “MetaHeaderâ€) that describes and points to +the file(s) containing your data. + +- Uncompressed data is data stored in a raw format, possibly with a header, as + is often the case for DICOM, BMP, and PNG formatted images. + +For compressed data, you must first convert your data to a non-compressed +format. One of the most robust image conversion software packages is +ImageMagick. It has an application called “convert†that handles most of the +popular 2D image formats. + +- Compressed data is includes JPEG or GIF formats as well as select PNG and + TIFF images. + +### Using MetaImageImporter + +`MetaImageImporter` asks a series of questions about your data and then produces +a MetaImage header file that points to your data and allows the MetaIO library +to read your data. + +`MetaImageImporter` is part of the InsightApplications repository. See the ITK +website for information on downloading and installing InsightApplications - the +companion to the Insight repository. + +`MetaImageImporter` now has a QT graphical user interface. Please see the +documentation. + +Otherwise, the following two sub-sections will step you through the conversion +process. The first sub-section applies if all of your data is in one file, i.e., +is a "brick-of-bytes". The second sub-section applies if your data is spread +across files, e.g., is dicom or a tiff sequence. + +### Reading a Brick-of-Bytes (an N-Dimensional volume in a single file) + +A “brick of bytes†is a volume of image data stored in a single file possibly +with preceding and trailing non-image data. A volume can be of any dimension (1 +dimensional to N dimensional). + +To correctly load these images, the minimal information that you need to know +is: + +- Number of dimensions +- Size of each dimension +- Data type +- Name of the data file + +For example, let’s say the data was 3 dimensional, had 256 x 256 x 64 voxels, +used an unsigned short to represent the value at each voxel, and was stored in +the file “image.rawâ€. The resulting MetaHeader (our naming convention would call +this file “image.mhdâ€) file would read: + +``` + +ObjectType = Image +NDims = 3 +DimSize = 256 256 64 +ElementType = MET_USHORT +ElementDataFile = image.raw + +``` +(this tag must be last in a MetaImageHeader) + +That’s it, but this assumes quite a bit about the image data. Specifically, it +assumes: + +- There are not any non-image data bytes (header data) at the beginning of the + image data file “image.rawâ€. +- The voxels are cubes – the distance spanned by and between a voxel in each + coordinate direction is 1 “unitâ€, e.g., 1x1x1mm voxel size and voxel + spacing. +- The byte-order of the data in `image.raw` matches the byte ordering native + to the machine the application is running on (e.g., PC’s use LSB ordering + and Suns/Macs use MSB ordering). + +If these assumptions are false, the data will not be loaded correctly by the +application. To fix these problems, MetaIO allows you to specify additional +tag/value pairs in the header: + +- To skip the header bytes in the image data file, use: + ``` + HeaderSize = X + ``` + where `X` is the number of bytes to skip at the beginning of the file before + reading image data. If you know there are no trailing bytes (extra bytes at + the end of the file) you can specify: + ``` + HeaderSize = -1 + ``` + and MetaImage will automatically calculate the number of extra bytes in the + data file, assume those bytes are at the head of the data file, and + automatically skip them before beginning to read the image data. + +- To specify the spacing of the voxels, use: + ``` + ElementSpacing = X Y Z + ``` + where `X` is the distance between the centers of the voxels along the + x-dimension, `Y` is the spacing in the y-dimension, and `Z` is the spacing + in the z-dimension. Therefore, to specify a 1x1x3mm voxel spacing, use: + ``` + ElementSpacing = 1 1 3 + ``` + NOTE: If `ElementSpacing` is not specified, it is assumed to be equal to + `ElementSize`. If neither is specified, both are assumed to be 1. + +- To specify a voxel size, use: + ``` + ElementSize = X Y Z + ``` + where `X Y Z` represent the size in the x, y, and z-dimensions respectively. + NOTE: If `ElementSize` is not specified, it is assumed to be equal to + `ElementSpacing`. If neither is specified, both are assumed to be 1. + +- To specify a particular byte ordering, use: + ``` + ElementByteOrderMSB = True + ``` + or + ``` + ElementByteOrderMSB = False + ``` + MSB (aka big-endian) ordering is common to SPARC and Motorola processors + (e.g., Macintoshes). LSB (aka little-endian) ordering is common to Intel + processors (e.g., PC compatibles). + +Putting it all together, to “convert†a file containing the image data in a +continuous block at the end of the file, specify the header: + +``` + +ObjectType = Image +NDims = 3 +DimSize = 256 256 64 +ElementType = MET_USHORT +HeaderSize = -1 +ElementSize = 1 1 3 +ElementSpacing = 1 1 1 +ElementByteOrderMSB = False +ElementDataFile = image.raw + +``` + +### Reading DICOM and Other One-Slice-Per-File Data Formats + +If the data is split into one slice per file, as is done with most DICOM object +files, only the `ElementDataFile` tag’s option needs to change. Note that 3D +DICOM object files are becoming popular, and some such DICOM files can be read +using the above, volume, technique. + +Since the MetaLibrary cannot directly parse DICOM headers, those headers must be +skipped and the user must specify the image dimensions and other essential image +information. For DICOM files, the MetaLibrary must automatically calculate the +header size of each file (luckily for almost every DICOM object the image data +is stored at the end of the file). For this reason, this method only works for +uncompressed files. + +To specify which files comprise the volume, they can be specified as an ordered +list in the MetaHeader using the `ElementDataFile=LIST` option. The filenames +should be listed at the end of the MetaHeader, after the `ElementDataFile` +option, and the filenames should be separated by whitespace: + +``` + +ObjectType = Image +NDims = 3 +DimSize = 512 512 100 +ElementType = MET_USHORT +HeaderSize = -1 +ElementSize = 1 1 3 +ElementSpacing = 1 1 1 +ElementByteOrderMSB = False +ElementDataFile = LIST +filenameOfSlice1 +filenameOfSlice2 +filenameOfSlice3 +filenameOfSlice4 +. +. (one hundred filenames must be specified to specify the 100 slices in the volume) +. + +``` + +This method works even if there are spaces in the file paths and file names. + +Notice that this method can become tedious if a large number of files need to be +read. To alleviate this, a second way of specifying a series of files can be +used if the filenames are numerically distinguished. That is, the file names +should be able to be specified using a numeric substitution into a c-style +printf-string, for a range of values. In pseudo-code: + +``` + +for i=numBegin to numEnd step numStep +sprintf(sliceName, “baseName.%03dâ€, i); +end + +``` + +The parameters of this system are `numBegin`, `numEnd`, `numStep`, and the +c-style printf string (e.g., `“baseName.%03dâ€`). The begin, end, and step +parameters appear in order after the c-style printf string: + +``` + +ObjectType = Image +NDims = 3 +DimSize = 512 512 100 +ElementType = MET_USHORT +HeaderSize = -1 +ElementSize = 1 1 3 +ElementSpacing = 1 1 1 +ElementByteOrderMSB = False +ElementDataFile = baseName.%03d 1 100 1 + +``` + +The above MetaImage header will cause the files “baseName.001†to “baseName.100†+to be read to create a 100-slice volume. This method works even if there are +spaces in the file paths and file names. However, when spaces are present in the +file path and/or file name, all three parameters (begin, end, and step) need to +be specified as the last parameters. The remaining parameters (initially parsed +based on spaces) are then joined back together (including spaces) to generate +the file name. + +In some cases, it may be helpful to skip slices in the volume. Changing the +slice spacing and the `ElementDataFileNumStep` enacts this… + +``` + +ObjectType = Image +NDims = 3 +DimSize = 512 512 50 +ElementType = MET_USHORT +HeaderSize = -1 +ElementSize = 1 1 3 +ElementSpacing = 1 1 2 +ElementByteOrderMSB = False +ElementDataFile = baseName.%03d 1 100 2 + +``` + +The complete set of MetaImage Tags are given in the Reference section of this +document. The next section discusses how to use the MetaImage Library for image +reading and writing in your own programs. + +## MetaIO Library Architecture + +The base class of the MetaIO library is the `MetaObject` class. It defines a +base set of tags that are common to all metaObjects such as `MetaImages`, +`MetaTubes`, etc. + +The tags are defined using the protected member functions `SetupReadFields` and +`SetupWriteFields`. These functions create a list of `MetaFieldRecords` to +define the name, type, interdependence, and necessity of each tag. Helper +functions for defining the fields are in `MetaUtils.cxx`. The types are defined +via enums in `MetaTypes.h`. + +The derived classes add tags to the list via their own `SetupReadFields` and +`SetupWriteFields` member functions. The `MetaImage` subclass also re-implements +the `Read` and `Write` methods since non tag data (i.e., the pixel values) must +also be read. Compare the derived classes for `MetaCube` and `MetaImage`. + +### MetaObjects + +In this section we describe the metaObjects which have been implemented already. +If you want to implement other objects, you can easily derive these classes. +`metaObject` is the base class for metaIO. `metaScene` and `metaGroup` are also +a useful objects that support multiple metaObjects. All these objects are +described in details next. + +**Constructors** + +- Simple constructor: `MetaObject(void);` +- Read a metafile and store the result in the current object: + `MetaObject(const char * _fileName);` +- Define the dimension of the object at construction time: + `MetaObject(unsigned int dim);` + +**Member functions** + +- Specify the filename to read (Optional): + - `void FileName(const char *_fileName);` + - `const char * FileName(void) const;` +- Read a MetaFile: `bool Read(const char * _fileName=NULL);` +- Write a MetaFile: + - `bool Write(const char * _fileName=NULL);` + - `virtual bool Append(const char *_headName=NULL);` +- Print the info about the metaObject: `virtual void PrintInfo(void) const;` +- Clear the information as well as the data of the metObject: `virtual void + Clear(void);` + +**Field descriptions** + +- Name: + - `void Name(const char *_Name);` + - `const char * Name(void) const;` +- Color: + - `const float * Color(void) const;` + - `void Color(float _r, float _g, float _b, float _a);` + - `void Color(const float * _color);` +- ID: ID number of the current metaObject + - `void ID(int _id);` + - `int ID(void) const;` +- Parent ID: ID number of the parent metaObject + - `void ParentID(int _parentId);` + - `int ParentID(void) const;` +- Binary Data: Specify if the data is binary or not + - `void BinaryData(bool _binaryData);` + - `bool BinaryData(void) const;` +- Binary Data Byte Order: + - `void BinaryDataByteOrderMSB(bool _binaryDataByteOrderMSB);` + - `bool BinaryDataByteOrderMSB(void) const;` +- Comments: + - `const char * Comment(void) const;` + - `void Comment(const char * _comment);` +- Object Typename and optional subtype (i.e. the type of the object) + - `const char * ObjectTypeName(void) const;` + - `void ObjectTypeName(const char * _objectTypeName);` + - `const char * ObjectSubTypeName(void) const;` + - `void ObjectSubTypeName(const char * _objectSubTypeName);` + +**Associated transformations** + +Physical location (in millimeters and with respect to machine coordinate system +or the patient) of the first element in the image. Physical orientation of the +object is defined as an NDims x NDims matrix that is serialized in a +column-major format in MetaIO files. + +- Offset: (equiv. to position and origin) + - `const float * Offset(void) const;` + - `float Offset(int _i) const;` + - `void Offset(const float * _position);` + - `void Offset(int _i, float _value);` +- Position: (equiv. to offset and origin) + - `const float * Position(void) const;` + - `float Position(int _i) const;` + - `void Position(const float * _position);` + - `void Position(int _i, float _value);` +- Origin: (equiv. to offset and position) + - `const float * Origin(void) const;` + - `float Origin(int _i) const;` + - `void Origin(const float * _position);` + - `void Origin(int _i, float _value);` +- Rotation: (equiv. to orientation and transformMatrix) + - `const float * Rotation(void) const;` + - `float Rotation(int _i, int _j) const;` + - `void Rotation(const float * _orientation);` + - `void Rotation(int _i, int _j, float _value);` +- Orientation: (equiv. to rotation and transformMatrix) + - `const float * Orientation(void) const;` + - `float Orientation(int _i, int _j) const;` + - `void Orientation(const float * _orientation);` + - `void Orientation(int _i, int _j, float _value);` +- TransformMatrix: (equiv. to rotation and orientation) + - `const float * TransformMatrix(void) const;` + - `float TransformMatrix(int _i, int _j) const;` + - `void TransformMatrix(const float * _transformMatrix);` + - `void TransformMatrix(int _i, int _j, float _value);` +- Center of rotation of the object: + - `const float * CenterOfRotation(void) const;` + - `float CenterOfRotation(int _i) const;` + - `void CenterOfRotation(const float * _position);` + - `void CenterOfRotation(int _i, float _value);` +- Anatomical Orientation: + - `const char * AnatomicalOrientationAcronym(void) const;` + - `const MET_OrientationEnumType * AnatomicalOrientation(void) const;` + - `MET_OrientationEnumType AnatomicalOrientation(int _dim) const;` + - `void AnatomicalOrientation(const char *_ao);` + - `void AnatomicalOrientation(const MET_OrientationEnumType *_ao);` + - `void AnatomicalOrientation(int _dim, MET_OrientationEnumType _ao);` + - `void AnatomicalOrientation(int _dim, char ao);` +- Element Spacing: Physical Spacing (in same units as position) + - `const float * ElementSpacing(void) const;` + - `float ElementSpacing(int _i) const;` + - `void ElementSpacing(const float * _elementSpacing);` + - `void ElementSpacing(int _i, float _value);` + +For simplicity, some dynamic functions have been recently added. They allow the +user to add fields dynamically. + +The function `AddUserField` is defined by: +``` + +template +bool AddUserField(const char* _fieldName, MET_ValueEnumType _type, int _length, T *_v, bool _required=true, int _dependsOn=-1 ) + +``` + +The user may also want to clear the fields created by using `ClearUserFields()`. + +To determine the value of a field: `void* GetUserField(const char* _name);` + +Note: When using `GetUserField()` function, the user is responsible for the +deletion of the pointer created. See the following example for details. + +**Example** + +``` + +/** We create a simple 3D metaObject with some properties */ +MetaObject tObj(3); // Create a 3D metaObject +tObj.FileName("testObject.txt"); // Define the name of the file +tObj.Comment("TestObject"); // Add some comments +tObj.ObjectTypeName("Object"); // Define the type of the object +tObj.ObjectSubTypeName("MinorObject"); // and the subtype as well + +/** We now define the position and the orientation as well as the spacing of the created object */ +// The position part +tObj.Position(0, 1); +tObj.Position(1, 2); +tObj.Position(2, 3); + +// The orientation part +float orient; +int i; +for(i=0; i<9; i++) +{ +orient[i] = 0; +} +orient = 1; +orient = 1; +orient = 1; +tObj.Orientation(orient); + +// The element spacing part +tObj.ElementSpacing(0, 1); +tObj.ElementSpacing(1, 2); +tObj.ElementSpacing(2, 1); + +/** Add user's defined fields */ +tObj.AddUserField("MyName", MET_STRING, strlen("JulienAndStephen"), "JulienAndStephen"); + +/** Write the object */ +tObj.Write(); + +/** Clear completely the object */ +tObj.Clear(); +tObj.ClearUserFields(); + +/** Specify that we want to read the field ‘MyName’ */ +tObj.AddUserField("MyName", MET_STRING); + +/** Read the object */ +tObj.Read("testObject.txt"); + +/** Print the object */ +tObj.PrintInfo(); + +/** Get the name in the file */ +char* name = static_cast(tObj.GetUserField("MyName")); +std::cout << name << std::endl; + +/** delete the allocated pointer */ +delete [] name; + +``` + +## Types of MetaObjects + +All of the following objects derive from `metaObject`. + +### MetaBlob + +A blob is defined by a list of points that describe the object. The points can +be inside the object (if obtained by connected-component for instance) or only +on the surface. Note that a color (RGBA) can be associated which each point. + +The required fields are: + +- The number of points defining the object: `NPoints(int npnt);` +- How the position of the points is stored in the file. By default the + configuration is x y z red green blue alpha: `PointDim(const char* + pointDim);` + +To access the internal list of points user should use the `GetPoints()` function +which returns the internal list by reference. Note that the list is a list of +pointers to point and is deleted automatically by the object itself so the user +does not need to free the allocated memory. + +**Example** + +``` + +/** Create a 3D blob */ +MetaBlob blob(3); +blob.ID(0); // define the ID of the blob + +/** Add 10 points to the blob */ +BlobPnt* pnt; +unsigned int i; +for(i=0;i<10;i++) +{ +pnt = new BlobPnt(3); +pnt->m_X=(float)0.2; +pnt->m_X[^1]=i; +pnt->m_X=i; +blob.GetPoints().push_back(pnt); // push the created point into the list of points +} + +/** Write the blob in binary format */ +blob.BinaryData(true); +blob.ElementType(MET_FLOAT); +blob.Write("myBlob.meta"); + +/** Read the file */ +blob.Read("myBlob.meta"); +blob.PrintInfo(); + +/** Access the list of points */ +std::cout << "Accessing pointlist..." << std::endl; +MetaBlob::PointListType plist = blob.GetPoints(); +MetaBlob::PointListType::const_iterator it = plist.begin(); +while(it != plist.end()) +{ +for(unsigned int d = 0; d < 3; d++) +{ +std::cout << (*it)->m_X[d] << " "; +} +std::cout << std::endl; +it++; +} + +``` + +### MetaEllipse + +`MetaEllipse` is an N-Dimensional object to define ellipsoids like circles, +spheres or even hyper-ellipsoids. + +The only field you need to provide is the Radius. + +There are several ways to input the radius: + +- As an array of floats: `void Radius(const float* radius);` +- As a single value which means that we are defining an hyper-sphere: `void + Radius(float radius);` +- A convenient way to define a 2D ellipse: `void Radius(float r1,float r2);` +- A convenient way to define a 3D ellipse: `void Radius(float r1,float r2, + float r3);` + +**Example** + +``` + +/** Create a sphere */ +MetaEllipse myEllipse (3); +myEllipse ->Radius(3); // radius of 3 + +``` + +### MetaGroup + +`MetaGroup` does not have added functionalities compared to `metaObject`. It +allows to group object in a metafile. + +### MetaImage + +**Constructors** + +- Simple constructor by specifying the filename: `MetaImage(const char + *_headerName);` +- Constructor by shared memory: `MetaImage(MetaImage *_im);` +- Other constructors: + - `MetaImage(int _nDims, const int * _dimSize, const float + *_elementSpacing, MET_ValueEnumType _elementType, int + _elementNumberOfChannels=1, void *_elementData=NULL);` + - `MetaImage(int _x, int _y, float _elementSpacingX, float + _elementSpacingY, MET_ValueEnumType _elementType, int + _elementNumberOfChannels=1, void *_elementData=NULL);` + - `MetaImage(int _x, int _y, int _z, float _elementSpacingX, float + _elementSpacingY, float _elementSpacingZ, MET_ValueEnumType + _elementType, int _elementNumberOfChannels=1, void *_elementData=NULL);` + +**Member functions** + +- HeaderSize: Return the size of the header: `int HeaderSize(void) const;` +- Quantity: Total number of elements in the image: `int Quantity(void) const;` +- SubQuantity: Number of elements in image spanning sub-dimensions. E.g., + elements per line, 2D sub-image, 3D sub-volume. + - `const int * SubQuantity(void) const;` + - `int SubQuantity(int _i) const;` +- ElementMin/Max: The default max returned is the largest allowed by + ElemNBytes (12 bit uint16_t will give 4096 max). This may not represent the + true max. Use `_reCalc=true` to force a calcuation of the actual max element + value. + - `bool ElementMinMaxValid(void) const;` + - `void ElementMinMaxValid(bool _elementMinMaxValid);` + - `void ElementMinMaxRecalc(void);` + - `double ElementMin(void) const;` + - `void ElementMin(double _elementMin);` + - `double ElementMax(void) const;` + - `void ElementMax(double _elementMax);` +- ElementByteOrderSwap: These functions are available only after + `ReadImageData()` or if `_read_and_close=TRUE` when read. + - `void ElementByteOrderSwap(void);` + - `bool ElementByteOrderFix(void);` +- ConverTo: Converts to a new data type. Rescales using Min and Max. + - `bool ConvertElementDataTo(MET_ValueEnumType _elementType=MET_UCHAR, + double _toMin=0, double _toMax=0);` + +**Field descriptions** + +- Modality: Specify the modality of the image + - `MET_ImageModalityEnumType Modality(void) const;` + - `void Modality(MET_ImageModalityEnumType _modality);` +- Dimension size: Specify the size of the image in each dimension + - `void DimSize(const int * _dimSize);` + - `void DimSize(int _i, int _value);` +- SequenceID: DICOM designation of this image relative to other images + acquired at the same time + - `const float * SequenceID(void) const;` + - `float SequenceID(int _i) const;` + - `void SequenceID(const float * _sequenceID);` + - `void SequenceID(int _i, float _value);` +- ElementSize: Optional Field. Physical size (in MM) of each element in the + image (0 = xSize, 1 = ySize, 2 = zSize) + - `const float * ElementSize(void) const;` + - `float ElementSize(int i) const;` + - `void ElementSize(const float * _pointSize);` + - `void ElementSize(int _i, float _value);` +- ElementType: Pixel type + - `MET_ValueEnumType ElementType(void) const;` + - `void ElementType(MET_ValueEnumType _elementType);` +- ElementNumberOfChannels: Number of channels + - `int ElementNumberOfChannels(void) const;` + - `void ElementNumberOfChannels(int _elementNumberOfChannels);` +- ElementData: Returns a pointer to the data. + - `void * ElementData(void);` + - `double ElementData(int _i) const;` + - `void ElementData(void * _data);` + - `bool ElementData(int _i, double _v);` +- ElementDataFileName: Set/Get the filename + - `const char * ElementDataFileName(void) const;` + - `void ElementDataFileName(const char * _dataFileName);` + +**Example** + +``` + +ObjectType = Image +NDims = 2 +BinaryData = True +BinaryDataByteOrderMSB = False +ElementSpacing = 1 2 +DimSize = 8 8 +ElementType = MET_CHAR +ElementDataFile = LOCAL +[Pixel Data] + +``` + +### MetaLandmark + +`MetaLandmark` is a simple list of landmarks. + +The number of landmarks defining the object is set using the function +`NPoints(int npnt);` + +How the position of the points is stored in the file: By default the +configuration is x y z red green blue alpha: `PointDim(const char* pointDim);` + +To access the internal list of points user should use the `GetPoints()` function +which returns the internal list by reference. Note that the list is a list of +pointers to point and is deleted automatically by the object itself so the user +does not need to free the allocated memory. + +**Example** + +``` + +/** Create a 3D Landmark */ +MetaLandmark Landmark(3); +Landmark.ID(0); +LandmarkPnt* pnt; + +/** Add some landmarks to the list of landmark points*/ +for(unsigned int i=0;i<10;i++) +{ +pnt = new LandmarkPnt(3); +pnt->m_X=(float)0.2; +pnt->m_X[^1]=i; +pnt->m_X=i; +Landmark.GetPoints().push_back(pnt); +} + +``` + +### MetaLine + +A `metaLine` is actually a polyline defined by a list of connected points. A +point on the line has a given position, a normal and a color. + +To set the position the local variable `m_X` should be filled in the point +structure. The variable `m_V` which is a double pointer to a float is used to +assess the normal. The normal has the dimension of the object minus one since a +metaLine in a 3D space will have two normals (a plane). + +Note that the user does not need to allocate the memory for those variables, +this is done automatically in the constructor of the point. + +To access the internal list of points user should use the `GetPoints()` function +which returns the internal list by reference. Note that the list is a list of +pointers to point and is deleted automatically by the object itself so the user +does not need to free the allocated memory. + +**Example** + +``` + +/** Create a 3D MetaLine */ +MetaLine Line(3); +LinePnt* pnt; +for(unsigned int i=0;i<10;i++) +{ +pnt = new LinePnt(3); +/** Define the position */ +pnt->m_X=(float)0.2; +pnt->m_X[^1]=i; +pnt->m_X=i; + +/** Define the normals */ +pnt->m_V=(float)0.3; +pnt->m_V[^1]=i; +pnt->m_V=i; +pnt->m_V[^1]=(float)0.4; +pnt->m_V[^1][^1]=i+1; +pnt->m_V[^1]=i+1; +Line.GetPoints().push_back(pnt); // Corrected: Line, not Line-> +} +/** Write the result */ +Line.BinaryData(true); +Line.Write("myLine.meta"); + +``` + +### MetaSurface + +The definition of a `metaSurface` is quite similar to the `metaLine`’s, except +for the normal which is only a NDim vector (i.e. an array of floats) where NDim +is the dimension of the metaObject. + +To access the internal list of points user should use the `GetPoints()` function +which returns the internal list by reference. Note that the list is a list of +pointers to point and is deleted automatically by the object itself so the user +does not need to free the allocated memory. + +**Example** + +``` + +MetaSurface surface(3); +SurfacePnt* pnt; +for(unsigned int i=0;i<10;i++) +{ +pnt = new SurfacePnt(3); +/** Position */ +pnt->m_X=(float)0.2; +pnt->m_X[^1]=i; +pnt->m_X=i; +/* Normal */ +pnt->m_V=(float)0.8; +pnt->m_V[^1]=i; +pnt->m_V=i; +surface.GetPoints().push_back(pnt); // Corrected: surface, not surface-> +} + +``` + +### MetaTube + +A `metaTube` is a tubular structure defined by a list of connected points (like +a `metaLine`) but more fields have been added for a complete representation, +especially the one of blood vessels. To specify a point that belongs to the +tube, the user can define: the position, the radius at that point, the +normal(s), the tangent, the color, the Identification number, the medialness, +the branchness, the ridgeness, and three alpha values that represents the ratio +of the eigen values at that points. + +Note that `metaTube` supports only 2D and 3D tubes. + +Also for a `metaTube`, the ID of the root can be specified by the command +`Root(int rootID)` and the ID of the parent point can also be assessed using +`ParentPoint(int parentpoint)`. + +To access the internal list of points user should use the `GetPoints()` function +which returns the internal list by reference. Note that the list is a list of +pointers to point and is deleted automatically by the object itself so the user +does not need to free the allocated memory. + +**Example** + +``` + +/** Create a 3D tube*/ +MetaTube* tube1 = new MetaTube(3); +tube1->ID(0); +/** Add 10 points to the list of tubePoints */ +TubePnt* pnt; +for(unsigned int i=0;i<10;i++) +{ +pnt = new TubePnt(3); +pnt->m_X=i; // position +pnt->m_X[^1]=i; +pnt->m_X=i; +pnt->m_R=i; // radius +tube1->GetPoints().push_back(pnt); +} + +``` + +### MetaScene + +A `metaScene` is a metaObject that contains a flat list of metaObjects. + +**Member functions** + +- Add an object to the scene: `void AddObject(MetaObject* object);` +- Return the number of objects in the scene: `int NObjects(void) const;` +- Get a list of objects present in the scene: `ObjectListType * + GetObjectList(void) {return & m_ObjectList;}` + +**Example** + +``` + +/** Define a 3D Scene */ +MetaScene scene(3); // Corrected: was s-> +MetaEllipse * e1 = new MetaEllipse(3); +e1->ID(0); +e1->Radius(3); +// MetaGroup g0; // Removed, appears unused/conflicting with g1 definition +MetaGroup * g1 = new MetaGroup(3); +g1->ID(2); +scene.AddObject(g1); // Corrected: scene, not s +scene.AddObject(e1); // Corrected: scene, not s +scene.Write("scene.scn"); // Corrected: scene, not s +scene.Clear(); +scene.Read("scene.scn"); // Corrected: scene, not s + +``` + +**Output File Example** + +Here is the example of a metafile with a scene that contains metaObjects: + +``` + +ObjectType = Scene +NDims = 3 +NObjects = 3 + +ObjectType = Group +NDims = 3 +ID = 2 +EndGroup = + +ObjectType = Ellipse +NDims = 3 +ID = 0 +ParentID = 2 +Radius = 1 2 3 + +ObjectType = Line +NDims = 3 +ID = 0 +BinaryData = False +BinaryDataByteOrderMSB = False +ElementType = MET_FLOAT +PointDim = x y z v1x v1y v1z +NPoints = 3 +Points = +1 2 3 0 0 0 +1 2 3 0 0 0 +1 2 3 0 0 0 + +ObjectType = Landmark +NDims = 3 +ID = 0 +BinaryData = True +BinaryDataByteOrderMSB = False +ElementType = MET_FLOAT +PointDim = x y z red green blue alpha +NPoints = 2 +Points = +1 2 3 1.0 0.0 0.0 1.0 +1 2 3 1.0 0.0 0.0 1.0 +1 2 3 1.0 0.0 0.0 1.0 + +``` + +## Spatial Objects + +MetaIO has also been chosen to support Spatial Objects IO. To obtain a complete +documentation of Spatial Objects and how to read/write them out please see the +Insight user’s manual available at the ITK website. + +## Reference: Tags of MetaImage + +### MetaObject Tags + +The tags of `MetaObject` are: + +- `Comment` + - Type: `MET_STRING` + - Description: User defined - arbitrary +- `ObjectType` + - Type: `MET_STRING` + - Description: Defined by derived objects – e.g., `Tube`, `Image` +- `ObjectSubType` + - Type: `MET_STRING` + - Description: Defined by derived objects – currently not used +- `TransformType` + - Type: `MET_STRING` + - Description: Defined by derived objects – e.g., `Rigid` +- `NDims` + - Type: `MET_INT` + - Description: Defined at object instantiation +- `Name` + - Type: `MET_STRING` + - Description: User defined +- `ID` + - Type: `MET_INT` + - Description: User defined else -1 +- `ParentID` + - Type: `MET_INT` + - Description: User defined else -1 +- `BinaryData` + - Type: `MET_STRING` (`True`/`False`) + - Description: Are the data associated with this object stored as Binary + or ASCII. Defined by derived objects. +- `ElementByteOrderMSB` / `BinaryDataByteOrderMSB` + - Type: `MET_STRING` (`True`/`False`) + - Description: Specifies byte order for binary data (MSB=True, LSB=False). +- `Color` + - Type: `MET_FLOAT_ARRAY[^4]` + - Description: R, G, B, alpha (opacity) +- `Position` (also `Offset`, `Origin`) + - Type: `MET_FLOAT_ARRAY[NDims]` + - Description: X, Y, Z,… of real-world coordinate of 0,0,0 index of object +- `Orientation` (also `Rotation`, `TransformMatrix`) + - Type: `MET_FLOAT_MATRIX[NDims][NDims]` + - Description: + - [^0][^0],[^0][^1],[^0][^2]... specify X, Y, Z… direction in + real-world of X-axis of object + - [^1][^0],[^1][^1],[^1][^2]... specify X, Y, Z… direction in + real-world of Y-axis of object, etc. + - Serialized column-major. +- `AnatomicalOrientation` + - Type: `MET_STRING` + - Description: This is a convenience tag, to be used and maintained by + applications. Changing this tag in a MetaIO file or via the MetaIO API + will not cause the MetaIO library to resample or change the direction + matrix of an image. It is up to an application to correctly read, write, + and maintain this tag. + - History: Labels ("from" vs "to"), LPS/RAI conventions. DICOM and ITK + use "to" labels (e.g., LPS). The direction matrix maps index space + (i,j,k) to physical space (x,y,z). `AnatomicalOrientation` + originally specified space (LPS/RAS), but later implementation + (early 2000s, coinciding with ITK direction matrix) changed it to + describe patient orientation in index space (assuming LPS), making + it somewhat redundant with the direction matrix. + - Recommendation: Use the definition currently implemented by ITK, + which represents the most common usage (a 3-letter code derived from + the direction matrix, assuming an LPS space). +- `ElementSpacing` + - Type: `MET_FLOAT_ARRAY[NDims]` + - Description: The distance between voxel centers (or equivalent element + centers). + +### Tags Added by MetaImage + +In addition to the above tags, `MetaImage` provides the following tags: + +- `DimSize` + - Type: `MET_INT_ARRAY[NDims]` + - Description: Number of elements per axis in data. +- `HeaderSize` + - Type: `MET_INT` + - Description: Number of Bytes to skip at the head of each data file. + - Specify –1 to have MetaImage calculate the header size based on the + assumption that the data occurs at the end of the file. + - Specify 0 if the data occurs at the beginning of the file. +- `Modality` + - Type: `MET_STRING` + - Description: One of enum type: `MET_MOD_CT`, `MET_MOD_MR`, `MET_MOD_US`… + See `metaImageTypes.h`. +- `SequenceID` + - Type: `MET_INT_ARRAY[^4]` (Note: Original doc says `MET_FLOAT_ARRAY`, + but context suggests `INT`) + - Description: Four values comprising a DICOM sequence: Study, Series, + Image numbers. +- `ElementMin` + - Type: `MET_FLOAT` + - Description: Minimum value in the data. +- `ElementMax` + - Type: `MET_FLOAT` + - Description: Maximum value in the data. +- `ElementNumberOfChannels` + - Type: `MET_INT` + - Description: Number of values (of type `ElementType`) per voxel. +- `ElementSize` + - Type: `MET_FLOAT_ARRAY[NDims]` + - Description: Physical size of each voxel. +- `ElementType` + - Type: `MET_STRING` + - Description: One of enum type: `MET_UCHAR`, `MET_CHAR`… as described in the following table: + + | ElementType tag | Description | + | -------------------- | ----------- | + | MET_NONE | none | + | MET_ASCII_CHAR | ASCII character | + | MET_CHAR | 8-bit signed integer | + | MET_UCHAR | 8-bit unsigned integer | + | MET_SHORT | 16-bit signed integer | + | MET_USHORT | 16-bit unsigned integer | + | MET_INT | 32-bit signed integer | + | MET_UINT | 32-bit unsigned integer | + | MET_LONG | 32-bit signed integer | + | MET_ULONG | 32-bit unsigned integer | + | MET_LONG_LONG | 64-bit signed integer | + | MET_ULONG_LONG | 64-bit unsigned integer | + | MET_FLOAT | 32-bit single precision floating point | + | MET_DOUBLE | 64-bit double precision floating point | + | MET_STRING | string of 8-bit characters | + | MET_CHAR_ARRAY | array of 8-bit signed integers | + | MET_UCHAR_ARRAY | array of 8-bit unsigned integers | + | MET_SHORT_ARRAY | array of 16-bit signed integers | + | MET_USHORT_ARRAY | array of 16-bit unsigned integers | + | MET_INT_ARRAY | array of 32-bit signed integers | + | MET_UINT_ARRAY | array of 32-bit unsigned integers | + | MET_LONG_ARRAY | array of 32-bit signed integers | + | MET_ULONG_ARRAY | array of 32-bit unsigned integers | + | MET_LONG_LONG_ARRAY | array of 64-bit signed integers | + | MET_ULONG_LONG_ARRAY | array of 64-bit unsigned integers | + | MET_FLOAT_ARRAY | array of 32-bit single precision floating points | + | MET_DOUBLE_ARRAY | array of 64-bit double precision floating points | + | MET_FLOAT_MATRIX | matrix of 32-bit single precision floating points | + | MET_OTHER | other | + + Note: this description (including the specified number of bits) applies + to all supported platforms, independent of platform specific sizes of + built-in C++ types (like `sizeof(long)`). + +- `ElementDataFile` + - Type: `MET_STRING` + - Description: Specifies the location of the pixel/voxel data. One of the + following formats: + - `filename.raw`: Name of the single file containing the data (for + "brick-of-bytes"). + - `printf_format min max [step]`: A C-style printf format string + followed by the minimum, maximum, and optional step integer values. + Used to generate a list of filenames for data split across multiple + files (e.g., slices). Each file must contain an (N-1)D block of + data. Example: `slice.%03d.raw 1 100 1`. + - `LIST [Dims]`: Indicates that a list of filenames follows on + subsequent lines (one filename per line). Each file contains a block + of data. By default, each file is assumed to contain an (N-1)D + block. An optional dimension specifier (e.g., `2D`) can be provided + to indicate the dimensionality of data within each file. Example: + `LIST 2D`. + - `LOCAL`: Indicates that the binary data begins immediately on the + next line within the same `.mhd` file. diff --git a/Documentation/docs/migration_guides/index.md b/Documentation/docs/migration_guides/index.md index e841f12a150..b8af3118227 100644 --- a/Documentation/docs/migration_guides/index.md +++ b/Documentation/docs/migration_guides/index.md @@ -6,5 +6,6 @@ These migration guides explain how to update major versions of ITK, whic may con :hidden: :maxdepth: 3 +itk_6_migration_guide itk_5_migration_guide ``` diff --git a/Documentation/docs/migration_guides/itk_5_migration_guide.md b/Documentation/docs/migration_guides/itk_5_migration_guide.md index 2adb64817ad..37716bfd41e 100644 --- a/Documentation/docs/migration_guides/itk_5_migration_guide.md +++ b/Documentation/docs/migration_guides/itk_5_migration_guide.md @@ -312,7 +312,7 @@ and intuitive. SpatialObjects now only have two spaces and two transforms directly associated with them: * ObjectSpace is the space that is "local" to each object. It is the physical space in which its data/parameters are defined. For example, for an ImageSpatialObject it is the "PhysicalSpace" (see Image Class definition) of the Image. For an Line/Tube/DTI and other -point-based SpatialObjects, it is the inherent space in which the Point coordinates are specififed. Typically, when a SpatialObject is +point-based SpatialObjects, it is the inherent space in which the Point coordinates are specified. Typically, when a SpatialObject is extracted from an Image, the parameters/coordinates of the SpatialObject are the space as the physical space of the source Image. Any children of a SpatialObject are defined within the ObjectSpace of that parent SpatialObject. diff --git a/Documentation/docs/migration_guides/itk_6_migration_guide.md b/Documentation/docs/migration_guides/itk_6_migration_guide.md new file mode 100644 index 00000000000..7b51b1d82f9 --- /dev/null +++ b/Documentation/docs/migration_guides/itk_6_migration_guide.md @@ -0,0 +1,125 @@ +ITK v6 Migration Guide +====================== + +This guide documents the changes required to migrate a code base +which uses ITK v5 to use ITK v6. The migration guide for transition +from v4 to v5 can be found [here](./itk_5_migration_guide.md). + +Require modern C++ language feature use +--------------------------------------- +Many backward compatible/ forward enabling compiler features are now required to be used. + +Replace `ITKv5_CONST` with `const` + +Remove support for ITKv4 interfaces +----------------------------------- + +`ITKV4_COMPATIBILITY` is no longer a supported option. Previously this option +was off by default. Previously when enabled, the ITK API was modified to +provide support for ITKV4 functions. + +Remove support for ITKv5 +----------------------------------- + +All contents of the Deprecated module were removed. This includes TreeContainer +and related classes; atomic primitives, mutexes and related classes which are +now part of C++ standard; specialized Vector filters - specialized versions are +no longer needed, as regular filters can work with vector images. For details, see +[ITKv5 Migration Guide](https://github.com/InsightSoftwareConsortium/ITK/blob/master/Documentation/docs/migration_guides/itk_5_migration_guide.md). + +Prefer standard CXX language features rather than ITK macros +------------------------------------------------------------- + +Replace ITK aliases (left column) with CXX standard feature (right column) + +```txt +ITK_FALLTHROUGH [[fallthrough]] +ITK_DELETE_FUNCTION = delete +ITK_CONSTEXPR_FUNC constexpr +ITK_CONSTEXPR_VAR constexpr + +ITK_ALIGNAS(X) alignas(X) +ITK_ALIGNOF(X) alignof(X) +ITK_DEPRECATED [[deprecated]] +ITK_DEPRECATED_MSG(MSG) [[deprecated(MSG)]] +ITK_CONSTEXPR constexpr +ITK_DELETED_FUNCTION = delete +ITK_EXTERN_TEMPLATE extern +ITK_FINAL final +ITK_NOEXCEPT noexcept +ITK_NOEXCEPT_EXPR(X) noexcept(X) +ITK_NULLPTR nullptr +ITK_OVERRIDE override +ITK_STATIC_ASSERT(X) static_assert(X, #X) +ITK_STATIC_ASSERT_MSG(X, MSG) static_assert(X, MSG) +ITK_THREAD_LOCAL thread_local +``` + +Removed ITKv5 migration/maintenance scripts +----------------------- + +The following scripts used for migrating to ITKv5 were removed from the ITKv6. + +```sh + CheckForOutdatedDefines.sh + EnumPrintFunction.py + Move_DISALLOW_COPY_to_public_section.cpp + ReplaceITK_NULLPTRMacroNames.sh + ReplaceITK_OVERRIDEMacroNames.sh + ReplaceitkGetObjectMacro.sh + UpdateAllC++Headers.sh + UseNativeC++Syntax.sh + misc-unused-parameters.sh + modernize-loop-convert.sh + modernize-pass-by-value.sh + modernize-return-braced-init-list.sh + modernize-use-auto.sh + modernize-use-bool-literals.sh + modernize-use-default-member-init.sh + modernize-use-emplace.sh + modernize-use-equals-default.sh + modernize-use-equals-delete.sh + modernize-use-nullptr.sh + modernize-use-override.sh + performance-general.sh + prefer-type-alias-over-typedef.sh + prefer_constexpr_for_const_literals.sh + readability-container-size-empty.sh + replaceClassWithTypename.py + replace_itkStaticConstMacro.sh + replace_vnl_math_XXX.sh +``` + +Accessing outdated ITKv5 migration scripts +------------------------------------------ + +``` +git worktree add .../ITKv5.4 v5.4.0 +ls ../ITKv5/Utilities/ITKv5Preparation +``` + +Class changes +------------- + +The `Clone()` member function of `itk::PointSet` now does a "deep copy" of its +data, creating a new instance that has a copy of the points, the point data and +the region information properties of the original PointSet object. With previous +ITK versions, `PointSet::Clone()` did not copy any data. (It previously just +created a default-constructed PointSet object, like `PointSet::CreateAnother()` +does.) + +For the sake of code readability, a new `CoordinateType` alias is added for +each nested `CoordRepType` alias. The old `CoordRepType` aliases will still be +available with ITK 6.0, but it is recommended to use `CoordinateType` instead. +The `CoordRepType` aliases will be removed when `ITK_FUTURE_LEGACY_REMOVE` is +enabled. Similarly, `InputCoordinateType`, `OutputCoordinateType`, and +`ImagePointCoordinateType` replace `InputCoordRepType`, `OutputCoordRepType`, +and `ImagePointCoordRepType`, respectively. + + +ITKVNLInstantiation library is removed +-------------------------------------- + +The usage of ITKVNLInstantiation library should be replaced directly with the +ITKVNL module. The ITKVNLInstantiation library was an empty libray used for +compatibility and provided transitive linking to ITKVNL. diff --git a/Documentation/docs/releases/4.0.md b/Documentation/docs/releases/4.0.md index 62a0bc93ce6..18e374ccd59 100644 --- a/Documentation/docs/releases/4.0.md +++ b/Documentation/docs/releases/4.0.md @@ -8,12 +8,12 @@ will continue to be contributed to the ITK version 3 code. ## Download -- [Download](https://itk.org/Wiki/ITK_Release_4/Download) +- [Download](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Download) ## Release Notes - [Release - Notes](https://itk.org/Wiki/ITK_Release_4/Migration_Plan/Release_Notes) + Notes](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Migration_Plan/Migration_Plan) ## LICENSE Change @@ -22,14 +22,14 @@ Apache 2.0 License. More details here: -- [Licensing](https://itk.org/Wiki/ITK_Release_4/Licensing) +- [Licensing](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Licensing) ## Revision Control - Adopt a modern revision control system - Move from cvs to [git](https://git-scm.com) for distributed source code management - - [ITK Git Instructions](https://itk.org/Wiki/ITK/Git) + - [ITK Git Instructions](https://docs.itk.org/en/latest/contributing/index.html) ## Code Review @@ -40,7 +40,7 @@ More details here: ## Modern C++ -- [Modern C++](https://itk.org/Wiki/ITK_Release_4/Modern_C++) +- [Modern C++](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Modern_C\%2B\%2B) @@ -57,22 +57,22 @@ More details here: ## Wrapping - Improved ITK Wrapping at the class level (WrapITK) - - [Wrapping](https://itk.org/Wiki/ITK_Release_4/Wrapping) + - [Wrapping](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Wrapping/Wrapping) - Particularly for Python 2.x, Python 3, Java and C\# ## Simplify -- Addition of [Simple ITK Layer](https://itk.org/Wiki/ITK_Release_4/SimpleITK) +- Addition of [Simple ITK Layer](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/SimpleITK/SimpleITK) ## Modularize -- Refactor for [Modularity](https://itk.org/Wiki/ITK_Release_4/Modularization) +- Refactor for [Modularity](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Modularization/Modularization) - ITKCore, ITKRegistrationModule, and Optional Modules ## Testing Crowdsourcing - [Testing - Crowdsourcing](https://itk.org/Wiki/ITK_Release_4/Testing_Crowdsourcing) + Crowdsourcing](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Testing_Crowdsourcing) ## Improve Software Process @@ -82,23 +82,23 @@ More details here: - Better management for Testing Data -- Data Collection [MIDAS](https://itk.org/Wiki/ITK_Release_4/Data_Collection) +- Data Collection [MIDAS](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Data_Collection) ### Distributed Testing (cdash@home) - Testing On Demand - [cdash@home](https://itk.org/Wiki/ITK_Release_4/Testing_On_Demand) + [cdash@home](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Testing_On_Demand/Testing_On_Demand) ### Testing Framework -- [New unit testing framework](https://itk.org/Wiki/ITK_Release_4/UnitTesting) +- [New unit testing framework](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/UnitTesting) based on [Google Test](https://code.google.com/p/googletest/) - Particularly to support module development, testing, and maintenance ### Coding Style -- [Coding Style](https://itk.org/Wiki/ITK_Release_4/Coding_Style) +- [Coding Style](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Coding_Style/Coding_Style) ## Revise @@ -124,22 +124,22 @@ More details here: ### Image Registration Framework - [Enhancing Image Registration - Framework](https://itk.org/Wiki/ITK_Release_4/Enhancing_Image_Registration_Framework) + Framework](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Enhancing_Image_Registration_Framework/Enhancing_Image_Registration_Framework) ### Spatial Objects - [ Spatial Object Refactoring project - page](https://itk.org/Wiki/ITK_Release_4/SpatialObjects) + page](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/SpatialObjects/SpatialObjects) ### Global Code Review -- [ Global Code Review](https://itk.org/Wiki/ITK_Release_4/Global_Code_Review) +- [ Global Code Review](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Global_Code_Review/Global_Code_Review) ## Accelerate ### GPU -- [GPU Acceleration - V4](https://itk.org/Wiki/ITK_Release_4/GPU_Acceleration) +- [GPU Acceleration - V4](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/GPU_Acceleration/GPU_Acceleration) - With support for distributed computing in the future @@ -150,53 +150,53 @@ More details here: ### Numerical Libraries - [Refactor Numerical - Libraries](https://itk.org/Wiki/ITK_Release_4/Refactor_Numerical_Libraries) + Libraries](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Refactor_Numerical_Libraries/Refactor_Numerical_Libraries/) ## Release schedules -- [Release Schedules](https://itk.org/Wiki/ITK_Release_4/ReleaseSchedules) +- [Release Schedules](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/ReleaseSchedules) ## The Team -[The Team](https://itk.org/Wiki/ITK_Release_4/The_Team) +[The Team](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/The_Team/The_Team/) ## Wish List -[Wish List](https://itk.org/Wiki/ITK_Release_4/Wish_List) +[Wish List](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Wish_List) ## Migration Plan (Developers) -[Migration Plan](https://itk.org/Wiki/ITK_Release_4/Migration_Plan) +[Migration Plan](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Migration_Plan/Migration_Plan/) ## Migration Guide (for Users) -[Users Migration Guide](https://itk.org/Wiki/ITK_Release_4/Users_Migration_Guide) +[Users Migration Guide](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Users_Migration_Guide/Users_Migration_Guide/) ## Software Guide (Update) -[Software Guide Update](https://itk.org/Wiki/ITK_Release_4/Software_Guide_Update) +[Software Guide Update](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Software_Guide_Update) ## A2D2 Projects -[A2D2 Projects](https://itk.org/Wiki/ITK_Release_4/A2D2_Projects) +[A2D2 Projects](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/A2D2_Projects/A2D2_Projects/) ## New Fields ITKv4 will provide improved support for -- [Video](https://itk.org/Wiki/ITK_Release_4/Video) -- [Microscopy](https://itk.org/Wiki/ITK_Release_4/Microscopy) -- [Remote Sensing](https://itk.org/Wiki/ITK_Release_4/Remote_Sensing) +- [Video](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Video/Video) +- [Microscopy](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Microscopy/Microscopy/) +- [Remote Sensing](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Remote_Sensing) ## Discussion Points -[Discussion Points](https://itk.org/Wiki/ITK_Release_4/Discussion_Points) +[Discussion Points](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Discussion_Points) ## Outreach -[Outreach](https://itk.org/Wiki/ITK_Release_4/Outreach) +[Outreach](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/Outreach/Outreach/) ## New Code Contribution Process [New Code Contribution -Process](https://itk.org/Wiki/ITK_Release_4/New_Code_Contribution_Process) +Process](https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK_Release_4/New_Code_Contribution_Process) diff --git a/Documentation/docs/releases/4.5.md b/Documentation/docs/releases/4.5.md index daf34ea803b..86ac8c39c31 100644 --- a/Documentation/docs/releases/4.5.md +++ b/Documentation/docs/releases/4.5.md @@ -17,13 +17,13 @@ New Documentation - ITK Wiki examples tarball.  A buildable archive of the outstanding - examples indexed at is available + examples indexed at is available to download, build against the current release, and learn from. - ITK Sphinx examples downloads.  Examples available online at - are stored in Git version control but + are stored in Git version control but rendered in HTML, PDF, and EPUB output formats with the Sphinx documentation system.  They have CTest unit tests, inline Doxygen class descriptions and links to full Doxygen class documentation, diff --git a/Documentation/docs/releases/5.1.md b/Documentation/docs/releases/5.1.md index d8e1d38e3da..b056298edd1 100644 --- a/Documentation/docs/releases/5.1.md +++ b/Documentation/docs/releases/5.1.md @@ -138,7 +138,7 @@ In addition to the many other pixel types supported, the `itk` binary Python pac ITK has adopted a [*.clang-format*](https://github.com/InsightSoftwareConsortium/ITK/blob/master/.clang-format) coding style configuration file so a consistent coding style can automatically be applied to C++ code with the [`clang-format`](https://releases.llvm.org/download.html) binary. A consistent coding style is critical for readability and collaborative development. -`clang-format` has been applied to the entire codebase. The Whitesmiths style of brace indentation, previously part of the [ITK Coding Style Guidelines](https://itk.org/ItkSoftwareGuide.pdf), is not supported by clang-format, so it has been replaced by a brace style consistent with VTK's current style. +`clang-format` has been applied to the entire code base. The Whitesmiths style of brace indentation, previously part of the [ITK Coding Style Guidelines](https://itk.org/ItkSoftwareGuide.pdf), is not supported by clang-format, so it has been replaced by a brace style consistent with VTK's current style. A Git commit hook will automatically apply `clang-format` to changed C++ code. diff --git a/Documentation/docs/releases/5.2.md b/Documentation/docs/releases/5.2.md index 3f635879660..1228d0fd3df 100644 --- a/Documentation/docs/releases/5.2.md +++ b/Documentation/docs/releases/5.2.md @@ -1801,4 +1801,3 @@ Remote Module Changes Since v5.2rc03 #### Style Changes - Move notebooks into examples/ directory directly ([d8ebede](https://github.com/KitwareMedical/ITKUltrasound/commit/d8ebede)) - diff --git a/Documentation/docs/releases/5.4.0.md b/Documentation/docs/releases/5.4.0.md index 1ec9b091b88..27d7e7bf485 100644 --- a/Documentation/docs/releases/5.4.0.md +++ b/Documentation/docs/releases/5.4.0.md @@ -136,7 +136,7 @@ Unpack optional testing data in the same directory where the Library Source is u - Add `itk::Copy(const T & original)`, which simply returns a copy - Make `itk::ImageRegion` trivially copyable, remove inheritance (FUTURE) - `itk::VTKPolyDataMeshIO` support for reading VTK 5.1 format -- Add `ITK_DEFAULT_COPY_AND_MOVE(TypeName)` macro definition +- Add `ITK_DEFAULT_COPY_AND_MOVE(TypeName)` macro definition - Replace `(const std::string)` casts with C++17 `std::string_view` - Replace SetSize/Index calls in tests with `region{ index, size }` - Optionally limit an `ImageMask` to a specific pixel value @@ -229,7 +229,7 @@ We extend our gratitude to all the ITK community members who have contributed to ðŸ—£ï¸ What's Next --------------- -ITK 5.4.0 represents a transformative milestone in our documentation journey. The finalization of 5.4.0 was delayed due to dependency issues in the example documentation's infrastructure. While these are addressed, we'll continue to refine the 5.4 series through patch releases. We're excited to eventually migrate the examples to a similar robust foundation in future innovations. +ITK 5.4.0 represents a transformative milestone in our documentation journey. The finalization of 5.4.0 was delayed due to dependency issues in the example documentation's infrastructure. While these are addressed, we'll continue to refine the 5.4 series through patch releases. We're excited to eventually migrate the examples to a similar robust foundation in future innovations. Looking ahead, we're thrilled to announce that ITK 6, our next major release, will showcase a substantial array of modernizations. The community has been hard at work implementing significant improvements that will elevate development with and on the toolkit. Watch for upcoming alpha and beta releases of ITK 6, which will run parallel to our 5.4 maintenance efforts. diff --git a/Documentation/docs/releases/5.4.2.md b/Documentation/docs/releases/5.4.2.md index 64cb36cf358..78f58642ae8 100644 --- a/Documentation/docs/releases/5.4.2.md +++ b/Documentation/docs/releases/5.4.2.md @@ -272,4 +272,3 @@ Remote Module Changes Since v5.4.0 #### Bug Fixes - Bump Python package version for re-deploy ([9f6654d](https://github.com/InsightSoftwareConsortium/ITKTotalVariation/commit/9f6654d)) - diff --git a/Documentation/docs/scientific_ecosystem/itk_ecosystem.md b/Documentation/docs/scientific_ecosystem/itk_ecosystem.md index 132a4925e96..6834f57bec2 100644 --- a/Documentation/docs/scientific_ecosystem/itk_ecosystem.md +++ b/Documentation/docs/scientific_ecosystem/itk_ecosystem.md @@ -1,6 +1,6 @@ # ITK ecosystem -Together with the core ITK codebase, a number of other projects and +Together with the core ITK code base, a number of other projects and frameworks are maintained allowing to leverage the power of ITK beyond its natural boundaries: @@ -31,7 +31,7 @@ or sets of pipelines were: - [Praxix](https://code.google.com/archive/p/praxix/) was a collection of command line programs for image processing using ITK. - [ITK One Shot](https://github.com/daviddoria/ITK_OneShot) was a - collecion of short programs to perform specific operations on images. + collection of short programs to perform specific operations on images. - [ITKApps](https://github.com/InsightSoftwareConsortium/ITKApps) were a variety of applications written with ITK, ranging from simple uses of the toolkit to complex and GUI-based applications. diff --git a/Examples/.clang-format b/Examples/.clang-format index 9c28e44cb35..aee28847baa 100644 --- a/Examples/.clang-format +++ b/Examples/.clang-format @@ -1,4 +1,4 @@ -## This config file is only relevant for clang-format version 8.0.0 +## This config file is only relevant for clang-format version 19.1.7 ## ## Examples of each format style can be found on the in the clang-format documentation ## See: https://clang.llvm.org/docs/ClangFormatStyleOptions.html for details of each option @@ -10,142 +10,309 @@ ## maintaining a consistent code style. ## ## EXAMPLE apply code style enforcement before commit: -# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_8.0.0} --modified +# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_19.1.7} --modified ## EXAMPLE apply code style enforcement after commit: -# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_8.0.0} --last +# Utilities/Maintenance/clang-format.bash --clang ${PATH_TO_CLANG_FORMAT_19.1.7} --last --- -# This configuration requires clang-format version 8.0.0 exactly. -BasedOnStyle: Mozilla +# This configuration requires clang-format version 19.1.7 exactly. Language: Cpp AccessModifierOffset: -2 AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: true -AlignEscapedNewlines: Right -AlignOperands: true -AlignTrailingComments: true -# clang 9.0 AllowAllArgumentsOnNextLine: true -# clang 9.0 AllowAllConstructorInitializersOnNextLine: true +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: false +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Never +AllowShortCaseExpressionOnASingleLine: true AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: Inline -# clang 9.0 AllowShortLambdasOnASingleLine: All -# clang 9.0 features AllowShortIfStatementsOnASingleLine: Never -AllowShortIfStatementsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +#AllowShortFunctionsOnASingleLine: Inline Only merge functions defined inside a class. Implies empty. +#AllowShortFunctionsOnASingleLine: None (in configuration: None) Never merge functions into a single line. +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: All AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: Yes +AttributeMacros: + - __capability BinPackArguments: false BinPackParameters: false -BreakBeforeBraces: Custom +BitFieldColonSpacing: Both BraceWrapping: - # clang 9.0 feature AfterCaseLabel: false + AfterCaseLabel: true AfterClass: true - AfterControlStatement: true + AfterControlStatement: Always AfterEnum: true + AfterExternBlock: true AfterFunction: true AfterNamespace: true AfterObjCDeclaration: true AfterStruct: true AfterUnion: true - AfterExternBlock: true BeforeCatch: true BeforeElse: true -## This is the big change from historical ITK formatting! -# Historically ITK used a style similar to https://en.wikipedia.org/wiki/Indentation_style#Whitesmiths_style -# with indented braces, and not indented code. This style is very difficult to automatically -# maintain with code beautification tools. Not indenting braces is more common among -# formatting tools. + BeforeLambdaBody: false + BeforeWhile: false IndentBraces: false SplitEmptyFunction: false SplitEmptyRecord: false SplitEmptyNamespace: false +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterReturnType: All +BreakArrays: true BreakBeforeBinaryOperators: None -#clang 6.0 BreakBeforeInheritanceComma: true -BreakInheritanceList: BeforeComma +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Custom +BreakBeforeInlineASMColon: OnlyMultiline BreakBeforeTernaryOperators: true -#clang 6.0 BreakConstructorInitializersBeforeComma: true BreakConstructorInitializers: BeforeComma -BreakAfterJavaFieldAnnotations: false +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeComma BreakStringLiterals: true -## The following line uses shorter lines in documentation code +BreakTemplateDeclarations: Yes +## The following line allows larger lines in non-documentation code ColumnLimit: 78 CommentPragmas: '^ IWYU pragma:' CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 2 ContinuationIndentWidth: 2 Cpp11BracedListStyle: false DerivePointerAlignment: false DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock ExperimentalAutoDetectBinPacking: false FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE IncludeBlocks: Preserve IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 + SortPriority: 0 + CaseSensitive: false - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 + SortPriority: 0 + CaseSensitive: false - Regex: '.*' Priority: 1 + SortPriority: 0 + CaseSensitive: false IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false IndentCaseLabels: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true IndentPPDirectives: AfterHash +IndentRequiresClause: true IndentWidth: 2 IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 JavaScriptQuotes: Leave JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: true + AtStartOfFile: true +LambdaBodyIndentation: Signature +LineEnding: DeriveLF MacroBlockBegin: '' MacroBlockEnd: '' +MainIncludeChar: Quote MaxEmptyLinesToKeep: 2 NamespaceIndentation: None ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true ObjCSpaceAfterProperty: true ObjCSpaceBeforeProtocolList: false +PackConstructorInitializers: BinPack PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 -## The following line uses shorter lines in documentation code +## The following line allows larger lines in non-documentation code PenaltyBreakFirstLessLess: 88 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 PenaltyReturnTypeOnItsOwnLine: 200 PointerAlignment: Middle +PPIndentWidth: -1 +QualifierAlignment: Custom +QualifierOrder: + - friend + - static + - inline + - constexpr + - const + - type +ReferenceAlignment: Pointer ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false # We may want to sort the includes as a separate pass -SortIncludes: false +SortIncludes: Never +SortJavaStaticImport: Before # We may want to revisit this later -SortUsingDeclarations: false +SortUsingDeclarations: Never SpaceAfterCStyleCast: false -# SpaceAfterLogicalNot: false +SpaceAfterLogicalNot: false SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false SpaceBeforeRangeBasedForLoopColon: true -SpaceInEmptyParentheses: false +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false SpacesBeforeTrailingComments: 1 -SpacesInAngles: false +SpacesInAngles: Never SpacesInContainerLiterals: false -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false SpacesInSquareBrackets: false -Standard: Cpp11 +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION + - ITK_GCC_PRAGMA_PUSH + - ITK_GCC_PRAGMA_POP + - ITK_GCC_SUPPRESS_Wfloat_equal + - ITK_GCC_SUPPRESS_Wformat_nonliteral + - ITK_GCC_SUPPRESS_Warray_bounds + - ITK_CLANG_PRAGMA_PUSH + - ITK_CLANG_PRAGMA_POP + - ITK_CLANG_SUPPRESS_Wzero_as_null_pointer_constant + - CLANG_PRAGMA_PUSH + - CLANG_PRAGMA_POP + - CLANG_SUPPRESS_Wfloat_equal + - INTEL_PRAGMA_WARN_PUSH + - INTEL_PRAGMA_WARN_POP + - INTEL_SUPPRESS_warning_1292 + - itkTemplateFloatingToIntegerMacro + - itkLegacyMacro +TableGenBreakInsideDAGArg: DontBreak TabWidth: 2 UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE ... diff --git a/Examples/DataRepresentation/Image/Image2.cxx b/Examples/DataRepresentation/Image/Image2.cxx index ea64432a95d..05ea94fadd6 100644 --- a/Examples/DataRepresentation/Image/Image2.cxx +++ b/Examples/DataRepresentation/Image/Image2.cxx @@ -137,7 +137,7 @@ main(int, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ImageType::Pointer image = reader->GetOutput(); + const ImageType::Pointer image = reader->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex diff --git a/Examples/DataRepresentation/Image/Image3.cxx b/Examples/DataRepresentation/Image/Image3.cxx index c79828d138e..45c78e3250b 100644 --- a/Examples/DataRepresentation/Image/Image3.cxx +++ b/Examples/DataRepresentation/Image/Image3.cxx @@ -43,10 +43,10 @@ main(int, char *[]) auto image = ImageType::New(); // The image region should be initialized - const ImageType::SizeType size = { + constexpr ImageType::SizeType size = { { 200, 200, 200 } }; // Size along {X,Y,Z} - const ImageType::IndexType start = { + constexpr ImageType::IndexType start = { { 0, 0, 0 } }; // First index on {X,Y,Z} @@ -82,7 +82,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const ImageType::IndexType pixelIndex = { + constexpr ImageType::IndexType pixelIndex = { { 27, 29, 37 } }; // Position of {X,Y,Z} // Software Guide : EndCodeSnippet @@ -99,7 +99,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ImageType::PixelType pixelValue = image->GetPixel(pixelIndex); + const ImageType::PixelType pixelValue = image->GetPixel(pixelIndex); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex diff --git a/Examples/DataRepresentation/Image/Image4.cxx b/Examples/DataRepresentation/Image/Image4.cxx index cdf0bdf8506..ceb4c49a2d0 100644 --- a/Examples/DataRepresentation/Image/Image4.cxx +++ b/Examples/DataRepresentation/Image/Image4.cxx @@ -81,10 +81,10 @@ main(int, char *[]) using ImageType = itk::Image; auto image = ImageType::New(); - const ImageType::SizeType size = { + constexpr ImageType::SizeType size = { { 200, 200, 200 } }; // Size along {X,Y,Z} - const ImageType::IndexType start = { + constexpr ImageType::IndexType start = { { 0, 0, 0 } }; // First index on {X,Y,Z} @@ -170,8 +170,7 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet // coordinates of the center of the first pixel in N-D - ImageType::PointType newOrigin; - newOrigin.Fill(0.0); + constexpr ImageType::PointType newOrigin{}; image->SetOrigin(newOrigin); // Software Guide : EndCodeSnippet @@ -443,8 +442,7 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using MatrixType = itk::Matrix; - MatrixType SpacingMatrix; - SpacingMatrix.Fill(0.0F); + auto SpacingMatrix = itk::MakeFilled(0.0F); const ImageType::SpacingType & ImageSpacing = image->GetSpacing(); SpacingMatrix(0, 0) = ImageSpacing[0]; @@ -455,13 +453,14 @@ main(int, char *[]) image->GetDirection(); const ImageType::PointType & ImageOrigin = image->GetOrigin(); - using VectorType = itk::Vector; + using VectorType = + itk::Vector; VectorType LeftEyeIndexVector; LeftEyeIndexVector[0] = LeftEyeIndex[0]; LeftEyeIndexVector[1] = LeftEyeIndex[1]; LeftEyeIndexVector[2] = LeftEyeIndex[2]; - ImageType::PointType LeftEyePointByHand = + const ImageType::PointType LeftEyePointByHand = ImageOrigin + ImageDirectionCosines * SpacingMatrix * LeftEyeIndexVector; // Software Guide : EndCodeSnippet diff --git a/Examples/DataRepresentation/Image/Image5.cxx b/Examples/DataRepresentation/Image/Image5.cxx index 0ee2c62931b..ab9ae0b1a4a 100644 --- a/Examples/DataRepresentation/Image/Image5.cxx +++ b/Examples/DataRepresentation/Image/Image5.cxx @@ -117,8 +117,7 @@ main(int argc, char * argv[]) size[1] = 200; // size along Y size[2] = 200; // size along Z - ImportFilterType::IndexType start; - start.Fill(0); + constexpr ImportFilterType::IndexType start{}; ImportFilterType::RegionType region; region.SetIndex(start); @@ -135,7 +134,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const itk::SpacePrecisionType origin[Dimension] = { 0.0, 0.0, 0.0 }; + constexpr itk::SpacePrecisionType origin[Dimension] = { 0.0, 0.0, 0.0 }; importFilter->SetOrigin(origin); // Software Guide : EndCodeSnippet @@ -147,7 +146,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet // spacing isotropic volumes to 1.0 - const itk::SpacePrecisionType spacing[Dimension] = { 1.0, 1.0, 1.0 }; + constexpr itk::SpacePrecisionType spacing[Dimension] = { 1.0, 1.0, 1.0 }; importFilter->SetSpacing(spacing); // Software Guide : EndCodeSnippet @@ -226,7 +225,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const bool importImageFilterWillOwnTheBuffer = true; + constexpr bool importImageFilterWillOwnTheBuffer = true; importFilter->SetImportPointer( localBuffer, numberOfPixels, importImageFilterWillOwnTheBuffer); // Software Guide : EndCodeSnippet diff --git a/Examples/DataRepresentation/Image/ImageAdaptor1.cxx b/Examples/DataRepresentation/Image/ImageAdaptor1.cxx index e282fde854b..a1f6bd76ad5 100644 --- a/Examples/DataRepresentation/Image/ImageAdaptor1.cxx +++ b/Examples/DataRepresentation/Image/ImageAdaptor1.cxx @@ -162,7 +162,7 @@ main(int argc, char * argv[]) it.GoToBegin(); while (!it.IsAtEnd()) { - float value = it.Get(); + const float value = it.Get(); sum += value; ++it; } diff --git a/Examples/DataRepresentation/Image/RGBImage.cxx b/Examples/DataRepresentation/Image/RGBImage.cxx index 8950eec44fb..325eb0f71cc 100644 --- a/Examples/DataRepresentation/Image/RGBImage.cxx +++ b/Examples/DataRepresentation/Image/RGBImage.cxx @@ -88,8 +88,8 @@ main(int, char * argv[]) reader->SetFileName(filename); reader->Update(); - ImageType::Pointer image = reader->GetOutput(); - const ImageType::IndexType pixelIndex = { { 25, 35, 0 } }; + const ImageType::Pointer image = reader->GetOutput(); + constexpr ImageType::IndexType pixelIndex = { { 25, 35, 0 } }; // Software Guide : BeginLatex // diff --git a/Examples/DataRepresentation/Image/VectorImage.cxx b/Examples/DataRepresentation/Image/VectorImage.cxx index d4fc1965f25..82c37ddfd1e 100644 --- a/Examples/DataRepresentation/Image/VectorImage.cxx +++ b/Examples/DataRepresentation/Image/VectorImage.cxx @@ -71,10 +71,12 @@ main(int, char *[]) auto image = ImageType::New(); // The image region should be initialized - const ImageType::IndexType start = { + constexpr ImageType::IndexType start = { { 0, 0, 0 } }; // First index at {X,Y,Z} - const ImageType::SizeType size = { { 200, 200, 200 } }; // Size of {X,Y,Z} + constexpr ImageType::SizeType size = { + { 200, 200, 200 } + }; // Size of {X,Y,Z} ImageType::RegionType region; region.SetSize(size); @@ -95,7 +97,7 @@ main(int, char *[]) // vector value. image->FillBuffer(initialValue); - const ImageType::IndexType pixelIndex = { + constexpr ImageType::IndexType pixelIndex = { { 27, 29, 37 } }; // Position {X,Y,Z} @@ -127,7 +129,7 @@ main(int, char *[]) // The GetPixel method can also be used to read Vectors // pixels from the image - ImageType::PixelType value = image->GetPixel(pixelIndex); + const ImageType::PixelType value = image->GetPixel(pixelIndex); std::cout << value << std::endl; diff --git a/Examples/DataRepresentation/Mesh/AutomaticMesh.cxx b/Examples/DataRepresentation/Mesh/AutomaticMesh.cxx index 085a460d3df..a2a5db34364 100644 --- a/Examples/DataRepresentation/Mesh/AutomaticMesh.cxx +++ b/Examples/DataRepresentation/Mesh/AutomaticMesh.cxx @@ -85,9 +85,7 @@ main(int, char *[]) using MeshSourceType = itk::AutomaticTopologyMeshSource; using IdentifierArrayType = MeshSourceType::IdentifierArrayType; - MeshSourceType::Pointer meshSource; - - meshSource = MeshSourceType::New(); + auto meshSource = MeshSourceType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -202,7 +200,7 @@ main(int, char *[]) // // Software Guide : EndLatex - MeshType::Pointer mesh = meshSource->GetOutput(); + const MeshType::Pointer mesh = meshSource->GetOutput(); std::cout << mesh << std::endl; // Software Guide : BeginLatex diff --git a/Examples/DataRepresentation/Mesh/Mesh1.cxx b/Examples/DataRepresentation/Mesh/Mesh1.cxx index a5243ee040a..d08211f6f90 100644 --- a/Examples/DataRepresentation/Mesh/Mesh1.cxx +++ b/Examples/DataRepresentation/Mesh/Mesh1.cxx @@ -218,12 +218,12 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - PointsIterator end = mesh->GetPoints()->End(); + const PointsIterator end = mesh->GetPoints()->End(); while (pointIterator != end) { - MeshType::PointType p = pointIterator.Value(); // access the point - std::cout << p << std::endl; // print the point - ++pointIterator; // advance to next point + const MeshType::PointType p = pointIterator.Value(); // access the point + std::cout << p << std::endl; // print the point + ++pointIterator; // advance to next point } // Software Guide : EndCodeSnippet diff --git a/Examples/DataRepresentation/Mesh/Mesh2.cxx b/Examples/DataRepresentation/Mesh/Mesh2.cxx index 80f041b67f4..d12ea68f75d 100644 --- a/Examples/DataRepresentation/Mesh/Mesh2.cxx +++ b/Examples/DataRepresentation/Mesh/Mesh2.cxx @@ -294,8 +294,8 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - CellIterator cellIterator = mesh->GetCells()->Begin(); - CellIterator end = mesh->GetCells()->End(); + CellIterator cellIterator = mesh->GetCells()->Begin(); + const CellIterator end = mesh->GetCells()->End(); // Software Guide : EndCodeSnippet diff --git a/Examples/DataRepresentation/Mesh/Mesh3.cxx b/Examples/DataRepresentation/Mesh/Mesh3.cxx index 6243a128e09..9a0ac50fe86 100644 --- a/Examples/DataRepresentation/Mesh/Mesh3.cxx +++ b/Examples/DataRepresentation/Mesh/Mesh3.cxx @@ -128,7 +128,7 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet CellType::CellAutoPointer line; - const unsigned int numberOfCells = numberOfPoints - 1; + constexpr unsigned int numberOfCells = numberOfPoints - 1; for (unsigned int cellId = 0; cellId < numberOfCells; ++cellId) { line.TakeOwnership(new LineType); @@ -218,8 +218,8 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - CellDataIterator cellDataIterator = mesh->GetCellData()->Begin(); - CellDataIterator end = mesh->GetCellData()->End(); + CellDataIterator cellDataIterator = mesh->GetCellData()->Begin(); + const CellDataIterator end = mesh->GetCellData()->End(); // Software Guide : EndCodeSnippet @@ -238,7 +238,7 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet while (cellDataIterator != end) { - PixelType cellValue = cellDataIterator.Value(); + const PixelType cellValue = cellDataIterator.Value(); std::cout << cellValue << std::endl; ++cellDataIterator; } diff --git a/Examples/DataRepresentation/Mesh/MeshKComplex.cxx b/Examples/DataRepresentation/Mesh/MeshKComplex.cxx index 797c7f73b4b..11cd1a8f8fe 100644 --- a/Examples/DataRepresentation/Mesh/MeshKComplex.cxx +++ b/Examples/DataRepresentation/Mesh/MeshKComplex.cxx @@ -331,8 +331,8 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using PointIterator = MeshType::PointsContainer::ConstIterator; - PointIterator pointIterator = mesh->GetPoints()->Begin(); - PointIterator pointEnd = mesh->GetPoints()->End(); + PointIterator pointIterator = mesh->GetPoints()->Begin(); + const PointIterator pointEnd = mesh->GetPoints()->End(); while (pointIterator != pointEnd) { @@ -602,7 +602,8 @@ main(int, char *[]) for (unsigned int b0 = 0; b0 < n0; ++b0) { MeshType::CellIdentifier id; - bool found = mesh->GetBoundaryAssignment(dimension, cellId, b0, &id); + const bool found = + mesh->GetBoundaryAssignment(dimension, cellId, b0, &id); if (found) std::cout << id << std::endl; } @@ -613,7 +614,8 @@ main(int, char *[]) for (unsigned int b1 = 0; b1 < n1; ++b1) { MeshType::CellIdentifier id; - bool found = mesh->GetBoundaryAssignment(dimension, cellId, b1, &id); + const bool found = + mesh->GetBoundaryAssignment(dimension, cellId, b1, &id); if (found) { std::cout << id << std::endl; @@ -625,7 +627,8 @@ main(int, char *[]) for (unsigned int b2 = 0; b2 < n2; ++b2) { MeshType::CellIdentifier id; - bool found = mesh->GetBoundaryAssignment(dimension, cellId, b2, &id); + const bool found = + mesh->GetBoundaryAssignment(dimension, cellId, b2, &id); if (found) { std::cout << id << std::endl; @@ -657,7 +660,8 @@ main(int, char *[]) for (unsigned int b1 = 0; b1 < n1; ++b1) { MeshType::CellIdentifier id; - bool found = mesh->GetBoundaryAssignment(dimension, cellId, b1, &id); + const bool found = + mesh->GetBoundaryAssignment(dimension, cellId, b1, &id); if (found) { std::cout << id << std::endl; diff --git a/Examples/DataRepresentation/Mesh/MeshPolyLine.cxx b/Examples/DataRepresentation/Mesh/MeshPolyLine.cxx index 39251baf36d..385e93c9491 100644 --- a/Examples/DataRepresentation/Mesh/MeshPolyLine.cxx +++ b/Examples/DataRepresentation/Mesh/MeshPolyLine.cxx @@ -207,8 +207,8 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using PointIterator = MeshType::PointsContainer::ConstIterator; - PointIterator pointIterator = mesh->GetPoints()->Begin(); - PointIterator pointEnd = mesh->GetPoints()->End(); + PointIterator pointIterator = mesh->GetPoints()->Begin(); + const PointIterator pointEnd = mesh->GetPoints()->End(); while (pointIterator != pointEnd) { diff --git a/Examples/DataRepresentation/Mesh/MeshTraits.cxx b/Examples/DataRepresentation/Mesh/MeshTraits.cxx index 57fb1bd43d7..bce06ddb39a 100644 --- a/Examples/DataRepresentation/Mesh/MeshTraits.cxx +++ b/Examples/DataRepresentation/Mesh/MeshTraits.cxx @@ -83,7 +83,7 @@ main(int, char *[]) // \item[PixelType.] The value type associated with every point. // \item[PointDimension.] The dimension of the space in which the mesh is // embedded. \item[MaxTopologicalDimension.] The highest dimension of the - // mesh cells. \item[CoordRepType.] The type used to represent spacial + // mesh cells. \item[CoordinateType.] The type used to represent spacial // coordinates. \item[InterpolationWeightType.] The type used to represent // interpolation weights. \item[CellPixelType.] The value type associated // with every cell. \end{description} @@ -189,7 +189,7 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet CellType::CellAutoPointer line; - const unsigned int numberOfCells = numberOfPoints - 1; + constexpr unsigned int numberOfCells = numberOfPoints - 1; for (unsigned int cellId = 0; cellId < numberOfCells; ++cellId) { line.TakeOwnership(new LineType); @@ -278,8 +278,8 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - CellDataIterator cellDataIterator = mesh->GetCellData()->Begin(); - CellDataIterator end = mesh->GetCellData()->End(); + CellDataIterator cellDataIterator = mesh->GetCellData()->Begin(); + const CellDataIterator end = mesh->GetCellData()->End(); // Software Guide : EndCodeSnippet @@ -299,7 +299,7 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet while (cellDataIterator != end) { - CellDataType cellValue = cellDataIterator.Value(); + const CellDataType cellValue = cellDataIterator.Value(); std::cout << cellValue << std::endl; ++cellDataIterator; } diff --git a/Examples/DataRepresentation/Mesh/PointSet1.cxx b/Examples/DataRepresentation/Mesh/PointSet1.cxx index 9e934e2e668..b5cb0b51616 100644 --- a/Examples/DataRepresentation/Mesh/PointSet1.cxx +++ b/Examples/DataRepresentation/Mesh/PointSet1.cxx @@ -195,8 +195,8 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - PointType pp; - bool pointExists = pointsSet->GetPoint(1, &pp); + PointType pp; + const bool pointExists = pointsSet->GetPoint(1, &pp); if (pointExists) { diff --git a/Examples/DataRepresentation/Mesh/PointSet2.cxx b/Examples/DataRepresentation/Mesh/PointSet2.cxx index a31998be04b..77beb867d9a 100644 --- a/Examples/DataRepresentation/Mesh/PointSet2.cxx +++ b/Examples/DataRepresentation/Mesh/PointSet2.cxx @@ -149,7 +149,7 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet - PointsContainer::Pointer points2 = pointSet->GetPoints(); + const PointsContainer::Pointer points2 = pointSet->GetPoints(); // Software Guide : EndCodeSnippet @@ -204,12 +204,12 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - PointsIterator end = points->End(); + const PointsIterator end = points->End(); while (pointIterator != end) { - PointType p = pointIterator.Value(); // access the point - std::cout << p << std::endl; // print the point - ++pointIterator; // advance to next point + const PointType p = pointIterator.Value(); // access the point + std::cout << p << std::endl; // print the point + ++pointIterator; // advance to next point } // Software Guide : EndCodeSnippet diff --git a/Examples/DataRepresentation/Mesh/PointSet3.cxx b/Examples/DataRepresentation/Mesh/PointSet3.cxx index c47f02d1737..1e39a6545e7 100644 --- a/Examples/DataRepresentation/Mesh/PointSet3.cxx +++ b/Examples/DataRepresentation/Mesh/PointSet3.cxx @@ -156,8 +156,8 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet unsigned int pointId = 0; - PixelType value0 = 34; - PixelType value1 = 67; + constexpr PixelType value0 = 34; + constexpr PixelType value1 = 67; pointData->InsertElement(pointId++, value0); pointData->InsertElement(pointId++, value1); @@ -190,7 +190,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - PointDataContainer::Pointer pointData2 = pointSet->GetPointData(); + const PointDataContainer::Pointer pointData2 = pointSet->GetPointData(); // Software Guide : EndCodeSnippet @@ -243,12 +243,12 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - PointDataIterator end = pointData2->End(); + const PointDataIterator end = pointData2->End(); while (pointDataIterator != end) { - PixelType p = pointDataIterator.Value(); // access the pixel data - std::cout << p << std::endl; // print the pixel data - ++pointDataIterator; // advance to next pixel/point + const PixelType p = pointDataIterator.Value(); // access the pixel data + std::cout << p << std::endl; // print the pixel data + ++pointDataIterator; // advance to next pixel/point } // Software Guide : EndCodeSnippet diff --git a/Examples/DataRepresentation/Mesh/PointSetWithCovariantVectors.cxx b/Examples/DataRepresentation/Mesh/PointSetWithCovariantVectors.cxx index df2a592e02f..a25e60b8f88 100644 --- a/Examples/DataRepresentation/Mesh/PointSetWithCovariantVectors.cxx +++ b/Examples/DataRepresentation/Mesh/PointSetWithCovariantVectors.cxx @@ -139,8 +139,8 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using PointDataIterator = PointSetType::PointDataContainer::ConstIterator; - PointDataIterator pixelIterator = pointSet->GetPointData()->Begin(); - PointDataIterator pixelEnd = pointSet->GetPointData()->End(); + PointDataIterator pixelIterator = pointSet->GetPointData()->Begin(); + const PointDataIterator pixelEnd = pointSet->GetPointData()->End(); using PointIterator = PointSetType::PointsContainer::Iterator; PointIterator pointIterator = pointSet->GetPoints()->Begin(); diff --git a/Examples/DataRepresentation/Mesh/PointSetWithVectors.cxx b/Examples/DataRepresentation/Mesh/PointSetWithVectors.cxx index f6f94858c34..1556c4ca9b3 100644 --- a/Examples/DataRepresentation/Mesh/PointSetWithVectors.cxx +++ b/Examples/DataRepresentation/Mesh/PointSetWithVectors.cxx @@ -133,8 +133,8 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using PointDataIterator = PointSetType::PointDataContainer::ConstIterator; - PointDataIterator pixelIterator = pointSet->GetPointData()->Begin(); - PointDataIterator pixelEnd = pointSet->GetPointData()->End(); + PointDataIterator pixelIterator = pointSet->GetPointData()->Begin(); + const PointDataIterator pixelEnd = pointSet->GetPointData()->End(); using PointIterator = PointSetType::PointsContainer::Iterator; PointIterator pointIterator = pointSet->GetPoints()->Begin(); diff --git a/Examples/DataRepresentation/Mesh/RGBPointSet.cxx b/Examples/DataRepresentation/Mesh/RGBPointSet.cxx index a4bb67ec51d..90d012e4bbb 100644 --- a/Examples/DataRepresentation/Mesh/RGBPointSet.cxx +++ b/Examples/DataRepresentation/Mesh/RGBPointSet.cxx @@ -108,8 +108,8 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using PointIterator = PointSetType::PointsContainer::ConstIterator; - PointIterator pointIterator = pointSet->GetPoints()->Begin(); - PointIterator pointEnd = pointSet->GetPoints()->End(); + PointIterator pointIterator = pointSet->GetPoints()->Begin(); + const PointIterator pointEnd = pointSet->GetPoints()->End(); while (pointIterator != pointEnd) { point = pointIterator.Value(); @@ -142,8 +142,8 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using PointDataIterator = PointSetType::PointDataContainer::ConstIterator; - PointDataIterator pixelIterator = pointSet->GetPointData()->Begin(); - PointDataIterator pixelEnd = pointSet->GetPointData()->End(); + PointDataIterator pixelIterator = pointSet->GetPointData()->Begin(); + const PointDataIterator pixelEnd = pointSet->GetPointData()->End(); while (pixelIterator != pixelEnd) { pixel = pixelIterator.Value(); diff --git a/Examples/DataRepresentation/Path/PolyLineParametricPath1.cxx b/Examples/DataRepresentation/Path/PolyLineParametricPath1.cxx index da6332dde76..64b58f10eff 100644 --- a/Examples/DataRepresentation/Path/PolyLineParametricPath1.cxx +++ b/Examples/DataRepresentation/Path/PolyLineParametricPath1.cxx @@ -84,9 +84,8 @@ main(int argc, char * argv[]) } // Software Guide : BeginCodeSnippet - ImageType::ConstPointer image = reader->GetOutput(); - auto path = PathType::New(); - path->Initialize(); + const ImageType::ConstPointer image = reader->GetOutput(); + auto path = PathType::New(); using ContinuousIndexType = PathType::ContinuousIndexType; ContinuousIndexType cindex; diff --git a/Examples/Filtering/BilateralImageFilter.cxx b/Examples/Filtering/BilateralImageFilter.cxx index 8ce01130112..9de6bbc879c 100644 --- a/Examples/Filtering/BilateralImageFilter.cxx +++ b/Examples/Filtering/BilateralImageFilter.cxx @@ -184,8 +184,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const unsigned int Dimension = InputImageType::ImageDimension; - double domainSigmas[Dimension]; + constexpr unsigned int Dimension = InputImageType::ImageDimension; + double domainSigmas[Dimension]; for (double & domainSigma : domainSigmas) { domainSigma = std::stod(argv[3]); diff --git a/Examples/Filtering/CMakeLists.txt b/Examples/Filtering/CMakeLists.txt index 0fabad39d80..1f52a2c04dd 100644 --- a/Examples/Filtering/CMakeLists.txt +++ b/Examples/Filtering/CMakeLists.txt @@ -22,6 +22,8 @@ add_executable(BinaryThresholdImageFilter BinaryThresholdImageFilter.cxx) target_link_libraries(BinaryThresholdImageFilter ${ITK_LIBRARIES}) add_executable(BinaryMedianImageFilter BinaryMedianImageFilter.cxx) target_link_libraries(BinaryMedianImageFilter ${ITK_LIBRARIES}) +add_executable(OrientImageFilter OrientImageFilter.cxx) +target_link_libraries(OrientImageFilter ${ITK_LIBRARIES}) add_executable(OtsuThresholdImageFilter OtsuThresholdImageFilter.cxx) target_link_libraries(OtsuThresholdImageFilter ${ITK_LIBRARIES}) add_executable(OtsuMultipleThresholdImageFilter OtsuMultipleThresholdImageFilter.cxx) @@ -62,8 +64,6 @@ add_executable(RGBToGrayscale RGBToGrayscale.cxx) target_link_libraries(RGBToGrayscale ${ITK_LIBRARIES}) add_executable(BilateralImageFilter BilateralImageFilter.cxx) target_link_libraries(BilateralImageFilter ${ITK_LIBRARIES}) -add_executable(ResampleOrientedImageFilter ResampleOrientedImageFilter.cxx) -target_link_libraries(ResampleOrientedImageFilter ${ITK_LIBRARIES}) add_executable(ResampleImageFilter2 ResampleImageFilter2.cxx) target_link_libraries(ResampleImageFilter2 ${ITK_LIBRARIES}) add_executable(GradientAnisotropicDiffusionImageFilter GradientAnisotropicDiffusionImageFilter.cxx) diff --git a/Examples/Filtering/DiffusionTensor3DReconstructionImageFilter.cxx b/Examples/Filtering/DiffusionTensor3DReconstructionImageFilter.cxx index ed7f63afdc8..db6783e2d74 100644 --- a/Examples/Filtering/DiffusionTensor3DReconstructionImageFilter.cxx +++ b/Examples/Filtering/DiffusionTensor3DReconstructionImageFilter.cxx @@ -87,8 +87,7 @@ main(int argc, char * argv[]) using PixelType = unsigned short; using ImageType = itk::VectorImage; - itk::ImageFileReader::Pointer reader = - itk::ImageFileReader::New(); + auto reader = itk::ImageFileReader::New(); ImageType::Pointer img; @@ -135,29 +134,30 @@ main(int argc, char * argv[]) // DWMRI_gradient_0003:=0.110000 0.664000 0.740000 // ... // - itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary(); + const itk::MetaDataDictionary imgMetaDictionary = + img->GetMetaDataDictionary(); std::vector imgMetaKeys = imgMetaDictionary.GetKeys(); std::vector::const_iterator itKey = imgMetaKeys.begin(); std::string metaString; TensorReconstructionImageFilterType::GradientDirectionType vect3d; - TensorReconstructionImageFilterType::GradientDirectionContainerType::Pointer - DiffusionVectors = TensorReconstructionImageFilterType:: + const TensorReconstructionImageFilterType::GradientDirectionContainerType:: + Pointer DiffusionVectors = TensorReconstructionImageFilterType:: GradientDirectionContainerType::New(); for (; itKey != imgMetaKeys.end(); ++itKey) { - double x, y, z; itk::ExposeMetaData(imgMetaDictionary, *itKey, metaString); if (itKey->find("DWMRI_gradient") != std::string::npos) { std::cout << *itKey << " ---> " << metaString << std::endl; - sscanf(metaString.c_str(), "%lf %lf %lf\n", &x, &y, &z); - vect3d[0] = x; - vect3d[1] = y; - vect3d[2] = z; + sscanf(metaString.c_str(), + "%lf %lf %lf\n", + &(vect3d[0]), + &(vect3d[1]), + &(vect3d[2])); DiffusionVectors->InsertElement(numberOfImages, vect3d); ++numberOfImages; // If the direction is 0.0, this is a reference image @@ -252,13 +252,13 @@ main(int argc, char * argv[]) { snprintf(filename, sizeof(filename), - "ReferenceImage%d.mhd", + "ReferenceImage%u.mhd", referenceImageIndex); ++referenceImageIndex; } else { - snprintf(filename, sizeof(filename), "Gradient%d.mhd", i); + snprintf(filename, sizeof(filename), "Gradient%u.mhd", i); } gradientWriter->SetFileName(filename); gradientWriter->Update(); diff --git a/Examples/Filtering/DigitallyReconstructedRadiograph1.cxx b/Examples/Filtering/DigitallyReconstructedRadiograph1.cxx index 54d91069eeb..559afad1dd0 100644 --- a/Examples/Filtering/DigitallyReconstructedRadiograph1.cxx +++ b/Examples/Filtering/DigitallyReconstructedRadiograph1.cxx @@ -46,7 +46,7 @@ #include "itkRayCastInterpolateImageFunction.h" // Software Guide : EndCodeSnippet -//#define WRITE_CUBE_IMAGE_TO_FILE +// #define WRITE_CUBE_IMAGE_TO_FILE void @@ -465,7 +465,7 @@ main(int argc, char * argv[]) const InputImageType::SpacingType spacing = image->GetSpacing(); std::cout << std::endl << "Input "; - InputImageType::RegionType region = image->GetBufferedRegion(); + const InputImageType::RegionType region = image->GetBufferedRegion(); region.Print(std::cout); std::cout << " Resolution: ["; @@ -540,8 +540,8 @@ main(int argc, char * argv[]) using InputImageRegionType = InputImageType::RegionType; using InputImageSizeType = InputImageRegionType::SizeType; - InputImageRegionType imRegion = image->GetBufferedRegion(); - InputImageSizeType imSize = imRegion.GetSize(); + const InputImageRegionType imRegion = image->GetBufferedRegion(); + InputImageSizeType imSize = imRegion.GetSize(); imOrigin[0] += imRes[0] * static_cast(imSize[0]) / 2.0; imOrigin[1] += imRes[1] * static_cast(imSize[1]) / 2.0; diff --git a/Examples/Filtering/FFTDirectInverse2.cxx b/Examples/Filtering/FFTDirectInverse2.cxx index e98aba62085..3731e168207 100644 --- a/Examples/Filtering/FFTDirectInverse2.cxx +++ b/Examples/Filtering/FFTDirectInverse2.cxx @@ -43,9 +43,9 @@ #include "itkFlipImageFilter.h" #if !defined(ITK_USE_FFTWF) -//#error "This example only works when single precision FFTW is used -// Changing WorkPixeltype to double and changing this conditional to -// ITK_USE_FFTWD will also work. +// #error "This example only works when single precision FFTW is used +// Changing WorkPixeltype to double and changing this conditional to +// ITK_USE_FFTWD will also work. #endif int diff --git a/Examples/Filtering/GaussianBlurImageFunction.cxx b/Examples/Filtering/GaussianBlurImageFunction.cxx index c908901b1af..d9edf099e4d 100644 --- a/Examples/Filtering/GaussianBlurImageFunction.cxx +++ b/Examples/Filtering/GaussianBlurImageFunction.cxx @@ -45,7 +45,7 @@ main(int argc, char * argv[]) const ImageType * inputImage = reader->GetOutput(); - ImageType::RegionType region = inputImage->GetBufferedRegion(); + const ImageType::RegionType region = inputImage->GetBufferedRegion(); ConstIteratorType it(inputImage, region); @@ -62,8 +62,7 @@ main(int argc, char * argv[]) auto gaussianFunction = GFunctionType::New(); gaussianFunction->SetInputImage(inputImage); - GFunctionType::ErrorArrayType setError; - setError.Fill(0.01); + auto setError = itk::MakeFilled(0.01); gaussianFunction->SetMaximumError(setError); gaussianFunction->SetSigma(std::stod(argv[3])); gaussianFunction->SetMaximumKernelWidth(std::stoi(argv[4])); diff --git a/Examples/Filtering/LaplacianRecursiveGaussianImageFilter1.cxx b/Examples/Filtering/LaplacianRecursiveGaussianImageFilter1.cxx index efc07544670..436e9753541 100644 --- a/Examples/Filtering/LaplacianRecursiveGaussianImageFilter1.cxx +++ b/Examples/Filtering/LaplacianRecursiveGaussianImageFilter1.cxx @@ -221,7 +221,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const bool normalizeAcrossScale = false; + constexpr bool normalizeAcrossScale = false; filterX1->SetNormalizeAcrossScale(normalizeAcrossScale); filterY1->SetNormalizeAcrossScale(normalizeAcrossScale); filterX2->SetNormalizeAcrossScale(normalizeAcrossScale); diff --git a/Examples/Filtering/MathematicalMorphologyBinaryFilters.cxx b/Examples/Filtering/MathematicalMorphologyBinaryFilters.cxx index 3b43e8e3cd7..dd1bc5f26ac 100644 --- a/Examples/Filtering/MathematicalMorphologyBinaryFilters.cxx +++ b/Examples/Filtering/MathematicalMorphologyBinaryFilters.cxx @@ -211,8 +211,8 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet thresholder->SetInput(reader->GetOutput()); - InputPixelType background = 0; - InputPixelType foreground = 255; + constexpr InputPixelType background = 0; + constexpr InputPixelType foreground = 255; thresholder->SetOutsideValue(background); thresholder->SetInsideValue(foreground); diff --git a/Examples/Filtering/OrientImageFilter.cxx b/Examples/Filtering/OrientImageFilter.cxx new file mode 100644 index 00000000000..5fabb7e54bd --- /dev/null +++ b/Examples/Filtering/OrientImageFilter.cxx @@ -0,0 +1,109 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * 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 + * + * https://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 "itkImage.h" +#include "itkImageFileReader.h" +#include "itkImageFileWriter.h" + +#include "itkOrientImageFilter.h" + +int +main(int argc, char * argv[]) +{ + if (argc < 4) + { + std::cerr << "Usage: " << std::endl; + std::cerr << argv[0] + << " inputImageFile outputImageFile " + "desiredPositiveCoordinateOrientation" + << std::endl; + return EXIT_FAILURE; + } + + // Get the inputs from the command line in C++ style + const std::string inputImageFile = argv[1]; + const std::string outputImageFile = argv[2]; + + const itk::AnatomicalOrientation desiredCoordinateOrientation{ + itk::AnatomicalOrientation::CreateFromPositiveStringEncoding(argv[3]) + }; + + if (desiredCoordinateOrientation == + itk::AnatomicalOrientation::PositiveEnum::INVALID) + { + std::cerr << "Invalid desiredPositiveCoordinateOrientation: " << argv[3] + << std::endl; + std::cerr << "Valid values are of the form LPS, RIP, etc."; + std::cerr << "Where each letter is either L or R, P or A, I or S." + << std::endl; + return EXIT_FAILURE; + } + + // Define the image and reader types + using PixelType = unsigned short; + using ImageType = itk::Image; + using ReaderType = itk::ImageFileReader; + + // Create and set up a reader + auto reader = ReaderType::New(); + reader->SetFileName(inputImageFile); + + reader->UpdateOutputInformation(); + + auto pixelType = reader->GetImageIO()->GetPixelType(); + auto componentType = reader->GetImageIO()->GetComponentType(); + + if (pixelType != itk::IOPixelEnum::SCALAR || + componentType != itk::IOComponentEnum::USHORT) + { + itkGenericOutputMacro( + "The input image is being converted to scalar unsigned short."); + } + + auto inputDirection = reader->GetOutput()->GetDirection(); + + std::cout << "Input image direction: " << std::endl; + inputDirection.PrintSelf(std::cout, itk::Indent(2)); + + std::cout << "The input image has the following orientation: " << std::endl; + std::cout << '\t' << itk::AnatomicalOrientation(inputDirection) + << std::endl; + + std::cout << "The re-orienting to approximately the desired orientation: " + << std::endl; + std::cout << '\t' << desiredCoordinateOrientation << std::endl; + + + // Create and set up an OrientImageFilter + using OrientImageFilterType = itk::OrientImageFilter; + auto orienter = OrientImageFilterType::New(); + orienter->SetInput(reader->GetOutput()); + orienter->UseImageDirectionOn(); + orienter->SetDesiredCoordinateOrientation(desiredCoordinateOrientation); + + + // Create and set up a writer + using WriterType = itk::ImageFileWriter; + auto writer = WriterType::New(); + writer->SetFileName(outputImageFile); + writer->SetInput(orienter->GetOutput()); + + writer->Update(); + + return EXIT_SUCCESS; +} diff --git a/Examples/Filtering/OtsuMultipleThresholdImageFilter.cxx b/Examples/Filtering/OtsuMultipleThresholdImageFilter.cxx index 859892084f2..8b696fbd921 100644 --- a/Examples/Filtering/OtsuMultipleThresholdImageFilter.cxx +++ b/Examples/Filtering/OtsuMultipleThresholdImageFilter.cxx @@ -103,7 +103,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ScalarImageToHistogramGeneratorType::Pointer + const ScalarImageToHistogramGeneratorType::Pointer scalarImageToHistogramGenerator = ScalarImageToHistogramGeneratorType::New(); @@ -196,7 +196,7 @@ main(int argc, char * argv[]) // // Software Guide : EndLatex - std::string outputFileBase = argv[2]; + const std::string outputFileBase = argv[2]; InputPixelType lowerThreshold = itk::NumericTraits::min(); InputPixelType upperThreshold; diff --git a/Examples/Filtering/OtsuThresholdImageFilter.cxx b/Examples/Filtering/OtsuThresholdImageFilter.cxx index 1b6f59f7cff..03cfc6ed30d 100644 --- a/Examples/Filtering/OtsuThresholdImageFilter.cxx +++ b/Examples/Filtering/OtsuThresholdImageFilter.cxx @@ -201,7 +201,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - int threshold = filter->GetThreshold(); + const int threshold = filter->GetThreshold(); std::cout << "Threshold = " << threshold << std::endl; // Software Guide : EndCodeSnippet diff --git a/Examples/Filtering/ResampleImageFilter.cxx b/Examples/Filtering/ResampleImageFilter.cxx index 487a641e148..8d8cc7dd596 100644 --- a/Examples/Filtering/ResampleImageFilter.cxx +++ b/Examples/Filtering/ResampleImageFilter.cxx @@ -246,11 +246,11 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet // pixel spacing in millimeters along X and Y - const double spacing[Dimension] = { 1.0, 1.0 }; + constexpr double spacing[Dimension] = { 1.0, 1.0 }; filter->SetOutputSpacing(spacing); // Physical space coordinate of origin for X and Y - const double origin[Dimension] = { 0.0, 0.0 }; + constexpr double origin[Dimension] = { 0.0, 0.0 }; filter->SetOutputOrigin(origin); // Software Guide : EndCodeSnippet diff --git a/Examples/Filtering/ResampleImageFilter2.cxx b/Examples/Filtering/ResampleImageFilter2.cxx index f567bdf3707..cecd2859b08 100644 --- a/Examples/Filtering/ResampleImageFilter2.cxx +++ b/Examples/Filtering/ResampleImageFilter2.cxx @@ -68,12 +68,7 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - int exampleAction = 0; - - if (argc >= 4) - { - exampleAction = std::stoi(argv[3]); - } + int exampleAction = std::stoi(argv[3]); constexpr unsigned int Dimension = 2; using InputPixelType = unsigned char; @@ -131,7 +126,7 @@ main(int argc, char * argv[]) { // Software Guide : BeginCodeSnippet // pixel spacing in millimeters along X & Y - const double spacing[Dimension] = { 1.0, 1.0 }; + constexpr double spacing[Dimension] = { 1.0, 1.0 }; filter->SetOutputSpacing(spacing); // Software Guide : EndCodeSnippet } @@ -163,7 +158,7 @@ main(int argc, char * argv[]) { // Software Guide : BeginCodeSnippet // space coordinate of origin - const double origin[Dimension] = { 30.0, 40.0 }; + constexpr double origin[Dimension] = { 30.0, 40.0 }; filter->SetOutputOrigin(origin); // Software Guide : EndCodeSnippet } @@ -248,7 +243,7 @@ main(int argc, char * argv[]) { // Software Guide : BeginCodeSnippet // space coordinate of origin - const double origin[Dimension] = { 60.0, 30.0 }; + constexpr double origin[Dimension] = { 60.0, 30.0 }; filter->SetOutputOrigin(origin); // Software Guide : EndCodeSnippet } @@ -325,7 +320,7 @@ main(int argc, char * argv[]) { // Software Guide : BeginCodeSnippet // space coordinate of origin - const double origin[Dimension] = { 0.0, 0.0 }; + constexpr double origin[Dimension] = { 0.0, 0.0 }; filter->SetOutputOrigin(origin); // Software Guide : EndCodeSnippet } @@ -341,7 +336,7 @@ main(int argc, char * argv[]) { // Software Guide : BeginCodeSnippet // pixel spacing in millimeters - const double spacing[Dimension] = { 2.0, 3.0 }; + constexpr double spacing[Dimension] = { 2.0, 3.0 }; filter->SetOutputSpacing(spacing); // Software Guide : EndCodeSnippet } @@ -462,7 +457,7 @@ main(int argc, char * argv[]) { // Software Guide : BeginCodeSnippet // space coordinate of origin - const double origin[Dimension] = { 25.0, 35.0 }; + constexpr double origin[Dimension] = { 25.0, 35.0 }; filter->SetOutputOrigin(origin); // Software Guide : EndCodeSnippet } @@ -491,7 +486,7 @@ main(int argc, char * argv[]) { // Software Guide : BeginCodeSnippet - const double spacing[Dimension] = { 4.0, 4.5 }; + constexpr double spacing[Dimension] = { 4.0, 4.5 }; filter->SetOutputSpacing(spacing); // Software Guide : EndCodeSnippet } diff --git a/Examples/Filtering/ResampleImageFilter3.cxx b/Examples/Filtering/ResampleImageFilter3.cxx index b7455d42dfd..bf867bf5a12 100644 --- a/Examples/Filtering/ResampleImageFilter3.cxx +++ b/Examples/Filtering/ResampleImageFilter3.cxx @@ -93,12 +93,7 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - int exampleAction = 0; - - if (argc >= 4) - { - exampleAction = std::stoi(argv[3]); - } + int exampleAction = std::stoi(argv[3]); constexpr unsigned int Dimension = 2; using InputPixelType = unsigned char; diff --git a/Examples/Filtering/ResampleImageFilter6.cxx b/Examples/Filtering/ResampleImageFilter6.cxx index 3ab133fd462..02e144f495c 100644 --- a/Examples/Filtering/ResampleImageFilter6.cxx +++ b/Examples/Filtering/ResampleImageFilter6.cxx @@ -69,8 +69,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet - PixelType defaultValue; - defaultValue.Fill(50); + auto defaultValue = itk::MakeFilled(50); filter->SetDefaultPixelValue(defaultValue); // Software Guide : EndCodeSnippet diff --git a/Examples/Filtering/ResampleImageFilter9.cxx b/Examples/Filtering/ResampleImageFilter9.cxx index a966d596c5e..7bbbe76786b 100644 --- a/Examples/Filtering/ResampleImageFilter9.cxx +++ b/Examples/Filtering/ResampleImageFilter9.cxx @@ -95,8 +95,7 @@ main(int argc, char * argv[]) linearFilter->SetTransform(transform); // Software Guide : BeginCodeSnippet - PixelType defaultValue; - defaultValue.Fill(50); + auto defaultValue = itk::MakeFilled(50); nearestFilter->SetDefaultPixelValue(defaultValue); linearFilter->SetDefaultPixelValue(defaultValue); // Software Guide : EndCodeSnippet diff --git a/Examples/Filtering/ResampleOrientedImageFilter.cxx b/Examples/Filtering/ResampleOrientedImageFilter.cxx deleted file mode 100644 index afe48bf362b..00000000000 --- a/Examples/Filtering/ResampleOrientedImageFilter.cxx +++ /dev/null @@ -1,88 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 "itkImage.h" -#include "itkImageFileReader.h" -#include "itkImageFileWriter.h" -#include "itkMatrix.h" - -#include "itkResampleImageFilter.h" - -int -main(int argc, char * argv[]) -{ - if (argc < 7) - { - std::cerr << "Usage: " << std::endl; - std::cerr << argv[0] << " inputImageFile outputImageFile"; - std::cerr << " direction cosines" << std::endl; - return EXIT_FAILURE; - } - - constexpr unsigned int Dimension = 2; - using InputPixelType = unsigned char; - using OutputPixelType = unsigned char; - using InputImageType = itk::Image; - using OutputImageType = itk::Image; - - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - - - using FilterType = - itk::ResampleImageFilter; - auto filter = FilterType::New(); - - filter->SetDefaultPixelValue(0); - - { - // pixel spacing in millimeters - const double spacing[Dimension] = { 1.0, 1.0 }; - filter->SetOutputSpacing(spacing); - } - - { - // space coordinate of origin - const double origin[Dimension] = { 0.0, 0.0 }; - filter->SetOutputOrigin(origin); - } - - OutputImageType::DirectionType direction; - direction(0, 0) = std::stoi(argv[3]); - direction(1, 0) = std::stoi(argv[4]); - direction(0, 1) = std::stoi(argv[5]); - direction(1, 1) = std::stoi(argv[6]); - filter->SetOutputDirection(direction); - - InputImageType::SizeType size; - size[0] = 300; // number of pixels along X - size[1] = 300; // number of pixels along Y - - filter->SetSize(size); - filter->SetInput(reader->GetOutput()); - writer->SetInput(filter->GetOutput()); - writer->Update(); - - return EXIT_SUCCESS; -} diff --git a/Examples/Filtering/ResampleVolumesToBeIsotropic.cxx b/Examples/Filtering/ResampleVolumesToBeIsotropic.cxx index 2ddd995df77..77341b0cc2c 100644 --- a/Examples/Filtering/ResampleVolumesToBeIsotropic.cxx +++ b/Examples/Filtering/ResampleVolumesToBeIsotropic.cxx @@ -275,7 +275,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - InputImageType::ConstPointer inputImage = reader->GetOutput(); + const InputImageType::ConstPointer inputImage = reader->GetOutput(); const InputImageType::SpacingType & inputSpacing = inputImage->GetSpacing(); // Software Guide : EndCodeSnippet diff --git a/Examples/Filtering/ScaleSpaceGenerator2D.cxx b/Examples/Filtering/ScaleSpaceGenerator2D.cxx index c751bc34b19..9603f40fe6b 100644 --- a/Examples/Filtering/ScaleSpaceGenerator2D.cxx +++ b/Examples/Filtering/ScaleSpaceGenerator2D.cxx @@ -85,7 +85,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet - int numberOfSlices = std::stoi(argv[3]); + const int numberOfSlices = std::stoi(argv[3]); for (int slice = 0; slice < numberOfSlices; ++slice) { std::ostringstream filename; diff --git a/Examples/Filtering/SecondDerivativeRecursiveGaussianImageFilter.cxx b/Examples/Filtering/SecondDerivativeRecursiveGaussianImageFilter.cxx index 7d67616ce16..7eae5aa5de5 100644 --- a/Examples/Filtering/SecondDerivativeRecursiveGaussianImageFilter.cxx +++ b/Examples/Filtering/SecondDerivativeRecursiveGaussianImageFilter.cxx @@ -104,8 +104,8 @@ main(int argc, char * argv[]) reader->SetFileName(argv[1]); - std::string outputPrefix = argv[2]; - std::string outputFileName; + const std::string outputPrefix = argv[2]; + std::string outputFileName; try { @@ -162,7 +162,7 @@ main(int argc, char * argv[]) gb->SetZeroOrder(); gc->SetSecondOrder(); - ImageType::Pointer inputImage = reader->GetOutput(); + const ImageType::Pointer inputImage = reader->GetOutput(); ga->SetInput(inputImage); gb->SetInput(ga->GetOutput()); @@ -173,7 +173,7 @@ main(int argc, char * argv[]) gc->Update(); duplicator->Update(); - ImageType::Pointer Izz = duplicator->GetOutput(); + const ImageType::Pointer Izz = duplicator->GetOutput(); // Software Guide: EndCodeSnippet writer->SetInput(Izz); @@ -200,7 +200,7 @@ main(int argc, char * argv[]) gc->Update(); duplicator->Update(); - ImageType::Pointer Iyy = duplicator->GetOutput(); + const ImageType::Pointer Iyy = duplicator->GetOutput(); // Software Guide : EndCodeSnippet writer->SetInput(Iyy); @@ -223,7 +223,7 @@ main(int argc, char * argv[]) gc->Update(); duplicator->Update(); - ImageType::Pointer Ixx = duplicator->GetOutput(); + const ImageType::Pointer Ixx = duplicator->GetOutput(); // Software Guide : EndCodeSnippet writer->SetInput(Ixx); @@ -252,7 +252,7 @@ main(int argc, char * argv[]) gc->Update(); duplicator->Update(); - ImageType::Pointer Iyz = duplicator->GetOutput(); + const ImageType::Pointer Iyz = duplicator->GetOutput(); // Software Guide : EndCodeSnippet writer->SetInput(Iyz); @@ -278,7 +278,7 @@ main(int argc, char * argv[]) gc->Update(); duplicator->Update(); - ImageType::Pointer Ixz = duplicator->GetOutput(); + const ImageType::Pointer Ixz = duplicator->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -305,7 +305,7 @@ main(int argc, char * argv[]) gc->Update(); duplicator->Update(); - ImageType::Pointer Ixy = duplicator->GetOutput(); + const ImageType::Pointer Ixy = duplicator->GetOutput(); writer->SetInput(Ixy); outputFileName = outputPrefix + "-Ixy.mhd"; diff --git a/Examples/Filtering/SpatialObjectToImage1.cxx b/Examples/Filtering/SpatialObjectToImage1.cxx index 3120e484b59..6fccf268ebb 100644 --- a/Examples/Filtering/SpatialObjectToImage1.cxx +++ b/Examples/Filtering/SpatialObjectToImage1.cxx @@ -311,7 +311,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const PixelType airHounsfieldUnits = -1000; + constexpr PixelType airHounsfieldUnits = -1000; constexpr PixelType boneHounsfieldUnits = 800; ellipse->SetDefaultInsideValue(boneHounsfieldUnits); diff --git a/Examples/Filtering/SpatialObjectToImage2.cxx b/Examples/Filtering/SpatialObjectToImage2.cxx index 2f4434db7ed..9562fd743d9 100644 --- a/Examples/Filtering/SpatialObjectToImage2.cxx +++ b/Examples/Filtering/SpatialObjectToImage2.cxx @@ -274,7 +274,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const PixelType airHounsfieldUnits = -1000; + constexpr PixelType airHounsfieldUnits = -1000; imageFilter->SetUseObjectValue(true); imageFilter->SetOutsideValue(airHounsfieldUnits); diff --git a/Examples/Filtering/SubsampleVolume.cxx b/Examples/Filtering/SubsampleVolume.cxx index fa5541f54fc..860b2bfb30f 100644 --- a/Examples/Filtering/SubsampleVolume.cxx +++ b/Examples/Filtering/SubsampleVolume.cxx @@ -119,7 +119,7 @@ main(int argc, char * argv[]) } - InputImageType::ConstPointer inputImage = reader->GetOutput(); + const InputImageType::ConstPointer inputImage = reader->GetOutput(); // Software Guide : BeginLatex diff --git a/Examples/Filtering/WarpImageFilter1.cxx b/Examples/Filtering/WarpImageFilter1.cxx index f21c77d4cf3..fa18eb06126 100644 --- a/Examples/Filtering/WarpImageFilter1.cxx +++ b/Examples/Filtering/WarpImageFilter1.cxx @@ -97,7 +97,7 @@ main(int argc, char * argv[]) fieldReader->SetFileName(argv[2]); fieldReader->Update(); - DisplacementFieldType::ConstPointer deformationField = + const DisplacementFieldType::ConstPointer deformationField = fieldReader->GetOutput(); // Software Guide : EndCodeSnippet diff --git a/Examples/Filtering/test/CMakeLists.txt b/Examples/Filtering/test/CMakeLists.txt index 2d09db0f6a6..2c492468fdb 100644 --- a/Examples/Filtering/test/CMakeLists.txt +++ b/Examples/Filtering/test/CMakeLists.txt @@ -397,21 +397,6 @@ itk_add_test( ${ITK_SOURCE_DIR}/Examples/Data/BrainProtonDensitySlice.png ${TEMP}/ResampleImageFilterTest1.png 0) -itk_add_test( - NAME - ResampleOrientedImageFilterTest - COMMAND - ${ITK_TEST_DRIVER} - --compare - DATA{${BASELINE}/ResampleOrientedImageFilterTest.png} - ${TEMP}/ResampleOrientedImageFilterTest.png - $ - ${ITK_SOURCE_DIR}/Examples/Data/VisibleWomanHeadSlice.png - ${TEMP}/ResampleOrientedImageFilterTest.png - 0 - 1 - 1 - 0) itk_add_test( NAME ResampleImageFilterTest2 diff --git a/Examples/IO/DicomImageReadChangeHeaderWrite.cxx b/Examples/IO/DicomImageReadChangeHeaderWrite.cxx index c9bcfa2ee18..207dc94a3b5 100644 --- a/Examples/IO/DicomImageReadChangeHeaderWrite.cxx +++ b/Examples/IO/DicomImageReadChangeHeaderWrite.cxx @@ -141,7 +141,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet - InputImageType::Pointer inputImage = reader->GetOutput(); + const InputImageType::Pointer inputImage = reader->GetOutput(); using DictionaryType = itk::MetaDataDictionary; DictionaryType & dictionary = inputImage->GetMetaDataDictionary(); // Software Guide : EndCodeSnippet @@ -162,8 +162,8 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet for (int i = 3; i < argc; i += 2) { - std::string entryId(argv[i]); - std::string value(argv[i + 1]); + const std::string entryId(argv[i]); + const std::string value(argv[i + 1]); itk::EncapsulateMetaData(dictionary, entryId, value); } // Software Guide : EndCodeSnippet diff --git a/Examples/IO/DicomImageReadPrintTags.cxx b/Examples/IO/DicomImageReadPrintTags.cxx index 8a9ef18af2f..f9095e528ab 100644 --- a/Examples/IO/DicomImageReadPrintTags.cxx +++ b/Examples/IO/DicomImageReadPrintTags.cxx @@ -198,9 +198,9 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet while (itr != end) { - itk::MetaDataObjectBase::Pointer entry = itr->second; + const itk::MetaDataObjectBase::Pointer entry = itr->second; - MetaDataStringType::Pointer entryvalue = + const MetaDataStringType::Pointer entryvalue = dynamic_cast(entry.GetPointer()); // Software Guide : EndCodeSnippet @@ -221,9 +221,9 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet if (entryvalue) { - std::string tagkey = itr->first; - std::string labelId; - bool found = itk::GDCMImageIO::GetLabelFromTag(tagkey, labelId); + const std::string tagkey = itr->first; + std::string labelId; + const bool found = itk::GDCMImageIO::GetLabelFromTag(tagkey, labelId); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -236,7 +236,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - std::string tagvalue = entryvalue->GetMetaDataObjectValue(); + const std::string tagvalue = entryvalue->GetMetaDataObjectValue(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -281,8 +281,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - std::string entryId = "0010|0010"; - auto tagItr = dictionary.Find(entryId); + const std::string entryId = "0010|0010"; + auto tagItr = dictionary.Find(entryId); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // @@ -294,7 +294,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet if (tagItr != end) { - MetaDataStringType::ConstPointer entryvalue = + const MetaDataStringType::ConstPointer entryvalue = dynamic_cast(tagItr->second.GetPointer()); // Software Guide : EndCodeSnippet @@ -309,7 +309,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet if (entryvalue) { - std::string tagvalue = entryvalue->GetMetaDataObjectValue(); + const std::string tagvalue = entryvalue->GetMetaDataObjectValue(); std::cout << "Patient's Name (" << entryId << ") "; std::cout << " is: " << tagvalue.c_str() << std::endl; } @@ -325,8 +325,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - std::string tagkey = "0008|1050"; - std::string labelId; + const std::string tagkey = "0008|1050"; + std::string labelId; if (itk::GDCMImageIO::GetLabelFromTag(tagkey, labelId)) { std::string value; @@ -365,8 +365,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - itk::IOPixelEnum pixelType = reader->GetImageIO()->GetPixelType(); - itk::IOComponentEnum componentType = + const itk::IOPixelEnum pixelType = reader->GetImageIO()->GetPixelType(); + const itk::IOComponentEnum componentType = reader->GetImageIO()->GetComponentType(); std::cout << "PixelType: " << reader->GetImageIO()->GetPixelTypeAsString(pixelType) diff --git a/Examples/IO/DicomPrintPatientInformation.cxx b/Examples/IO/DicomPrintPatientInformation.cxx index bf1b7d10d77..430ba09d7ee 100644 --- a/Examples/IO/DicomPrintPatientInformation.cxx +++ b/Examples/IO/DicomPrintPatientInformation.cxx @@ -32,7 +32,7 @@ FindDicomTag(const std::string & entryId, const itk::GDCMImageIO::Pointer dicomIO) { std::string tagvalue; - bool found = dicomIO->GetValueFromTag(entryId, tagvalue); + const bool found = dicomIO->GetValueFromTag(entryId, tagvalue); if (!found) { tagvalue = "NOT FOUND"; @@ -58,7 +58,7 @@ main(int argc, char * argv[]) auto reader = ReaderType::New(); - itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New(); + auto dicomIO = itk::GDCMImageIO::New(); reader->SetFileName(argv[1]); reader->SetImageIO(dicomIO); @@ -74,15 +74,15 @@ main(int argc, char * argv[]) } - std::string patientName = FindDicomTag("0010|0010", dicomIO); - std::string patientID = FindDicomTag("0010|0020", dicomIO); - std::string patientSex = FindDicomTag("0010|0040", dicomIO); - std::string patientAge = FindDicomTag("0010|1010", dicomIO); - std::string studyDate = FindDicomTag("0008|0020", dicomIO); - std::string modality = FindDicomTag("0008|0060", dicomIO); - std::string manufacturer = FindDicomTag("0008|0070", dicomIO); - std::string institution = FindDicomTag("0008|0080", dicomIO); - std::string model = FindDicomTag("0008|1090", dicomIO); + const std::string patientName = FindDicomTag("0010|0010", dicomIO); + const std::string patientID = FindDicomTag("0010|0020", dicomIO); + const std::string patientSex = FindDicomTag("0010|0040", dicomIO); + const std::string patientAge = FindDicomTag("0010|1010", dicomIO); + const std::string studyDate = FindDicomTag("0008|0020", dicomIO); + const std::string modality = FindDicomTag("0008|0060", dicomIO); + const std::string manufacturer = FindDicomTag("0008|0070", dicomIO); + const std::string institution = FindDicomTag("0008|0080", dicomIO); + const std::string model = FindDicomTag("0008|1090", dicomIO); std::cout << "Patient Name : " << patientName << std::endl; diff --git a/Examples/IO/DicomSeriesReadImageWrite.cxx b/Examples/IO/DicomSeriesReadImageWrite.cxx index b40857df933..0885a72460f 100644 --- a/Examples/IO/DicomSeriesReadImageWrite.cxx +++ b/Examples/IO/DicomSeriesReadImageWrite.cxx @@ -74,11 +74,10 @@ main(int argc, char * argv[]) using ImageType = itk::Image; using ReaderType = itk::ImageSeriesReader; - itk::DICOMImageIO2::Pointer dicomIO = itk::DICOMImageIO2::New(); + auto dicomIO = itk::DICOMImageIO2::New(); // Get the DICOM filenames from the directory - itk::DICOMSeriesFileNames::Pointer nameGenerator = - itk::DICOMSeriesFileNames::New(); + auto nameGenerator = itk::DICOMSeriesFileNames::New(); nameGenerator->SetDirectory(argv[1]); diff --git a/Examples/IO/DicomSeriesReadPrintTags.cxx b/Examples/IO/DicomSeriesReadPrintTags.cxx index 9f496f1be9e..88c32387440 100644 --- a/Examples/IO/DicomSeriesReadPrintTags.cxx +++ b/Examples/IO/DicomSeriesReadPrintTags.cxx @@ -119,7 +119,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet using FileNamesContainer = std::vector; - FileNamesContainer fileNames = nameGenerator->GetInputFileNames(); + const FileNamesContainer fileNames = nameGenerator->GetInputFileNames(); reader->SetFileNames(fileNames); // Software Guide : EndCodeSnippet @@ -212,15 +212,15 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet while (itr != end) { - itk::MetaDataObjectBase::Pointer entry = itr->second; + const itk::MetaDataObjectBase::Pointer entry = itr->second; - MetaDataStringType::Pointer entryvalue = + const MetaDataStringType::Pointer entryvalue = dynamic_cast(entry.GetPointer()); if (entryvalue) { - std::string tagkey = itr->first; - std::string tagvalue = entryvalue->GetMetaDataObjectValue(); + const std::string tagkey = itr->first; + const std::string tagvalue = entryvalue->GetMetaDataObjectValue(); std::cout << tagkey << " = " << tagvalue << std::endl; } @@ -238,7 +238,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - std::string entryId = "0010|0010"; + const std::string entryId = "0010|0010"; auto tagItr = dictionary.Find(entryId); @@ -260,12 +260,12 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - MetaDataStringType::ConstPointer entryvalue = + const MetaDataStringType::ConstPointer entryvalue = dynamic_cast(tagItr->second.GetPointer()); if (entryvalue) { - std::string tagvalue = entryvalue->GetMetaDataObjectValue(); + const std::string tagvalue = entryvalue->GetMetaDataObjectValue(); std::cout << "Patient's Name (" << entryId << ") "; std::cout << " is: " << tagvalue << std::endl; } diff --git a/Examples/IO/DicomSeriesReadSeriesWrite.cxx b/Examples/IO/DicomSeriesReadSeriesWrite.cxx index e8f983a020f..900e76bf98d 100644 --- a/Examples/IO/DicomSeriesReadSeriesWrite.cxx +++ b/Examples/IO/DicomSeriesReadSeriesWrite.cxx @@ -143,7 +143,7 @@ main(int argc, char * argv[]) namesGenerator->GetInputFileNames(); // Software Guide : EndCodeSnippet - size_t numberOfFileNames = filenames.size(); + const size_t numberOfFileNames = filenames.size(); std::cout << numberOfFileNames << std::endl; for (unsigned int fni = 0; fni < numberOfFileNames; ++fni) { diff --git a/Examples/IO/IOPlugin.cxx b/Examples/IO/IOPlugin.cxx index 2f70c8f17b9..7803596f48c 100644 --- a/Examples/IO/IOPlugin.cxx +++ b/Examples/IO/IOPlugin.cxx @@ -48,7 +48,7 @@ main(int argc, char * argv[]) #endif } myenv += std::string(argv[3]); - itksys::SystemTools::PutEnv(myenv.c_str()); + itksys::SystemTools::PutEnv(myenv); itk::ObjectFactoryBase::ReHash(); } @@ -83,7 +83,7 @@ main(int argc, char * argv[]) std::list::const_iterator e = enableflags.begin(); for (std::list::const_iterator o = overrides.begin(); o != overrides.end(); - ++o, ++n, ++d, e++) + ++o, ++n, ++d, ++e) { std::cout << " Override " << *o << " with " << *n << std::endl << " described as \"" << *d << "\"" << std::endl diff --git a/Examples/IO/ImageReadDicomSeriesWrite.cxx b/Examples/IO/ImageReadDicomSeriesWrite.cxx index 575e6b80c60..cc91e531d5f 100644 --- a/Examples/IO/ImageReadDicomSeriesWrite.cxx +++ b/Examples/IO/ImageReadDicomSeriesWrite.cxx @@ -97,9 +97,9 @@ main(int argc, char * argv[]) auto namesGenerator = NamesGeneratorType::New(); itk::MetaDataDictionary & dict = gdcmIO->GetMetaDataDictionary(); - std::string tagkey, value; - tagkey = "0008|0060"; // Modality - value = "MR"; + + std::string tagkey = "0008|0060"; // Modality + std::string value = "MR"; itk::EncapsulateMetaData(dict, tagkey, value); tagkey = "0008|0008"; // Image Type value = "DERIVED\\SECONDARY"; @@ -115,7 +115,7 @@ main(int argc, char * argv[]) seriesWriter->SetImageIO(gdcmIO); - ImageType::RegionType region = + const ImageType::RegionType region = reader->GetOutput()->GetLargestPossibleRegion(); ImageType::IndexType start = region.GetIndex(); diff --git a/Examples/IO/ImageReadExtractFilterInsertWrite.cxx b/Examples/IO/ImageReadExtractFilterInsertWrite.cxx index 077225a39ab..540b76c6623 100644 --- a/Examples/IO/ImageReadExtractFilterInsertWrite.cxx +++ b/Examples/IO/ImageReadExtractFilterInsertWrite.cxx @@ -165,8 +165,9 @@ main(int argc, char ** argv) // Software Guide : BeginCodeSnippet reader->Update(); - const InputImageType * inputImage = reader->GetOutput(); - InputImageType::RegionType inputRegion = inputImage->GetBufferedRegion(); + const InputImageType * inputImage = reader->GetOutput(); + const InputImageType::RegionType inputRegion = + inputImage->GetBufferedRegion(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex diff --git a/Examples/IO/ImageReadExtractWrite.cxx b/Examples/IO/ImageReadExtractWrite.cxx index d89e87bb8e6..edae8cd341e 100644 --- a/Examples/IO/ImageReadExtractWrite.cxx +++ b/Examples/IO/ImageReadExtractWrite.cxx @@ -175,7 +175,7 @@ main(int argc, char ** argv) // Software Guide : BeginCodeSnippet reader->UpdateOutputInformation(); - InputImageType::RegionType inputRegion = + const InputImageType::RegionType inputRegion = reader->GetOutput()->GetLargestPossibleRegion(); // Software Guide : EndCodeSnippet diff --git a/Examples/IO/ImageReadImageSeriesWrite.cxx b/Examples/IO/ImageReadImageSeriesWrite.cxx index 3067f9d4439..e8d36a4dcd1 100644 --- a/Examples/IO/ImageReadImageSeriesWrite.cxx +++ b/Examples/IO/ImageReadImageSeriesWrite.cxx @@ -153,10 +153,10 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ImageType::ConstPointer inputImage = reader->GetOutput(); - ImageType::RegionType region = inputImage->GetLargestPossibleRegion(); - ImageType::IndexType start = region.GetIndex(); - ImageType::SizeType size = region.GetSize(); + const ImageType::ConstPointer inputImage = reader->GetOutput(); + const ImageType::RegionType region = inputImage->GetLargestPossibleRegion(); + ImageType::IndexType start = region.GetIndex(); + ImageType::SizeType size = region.GetSize(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex diff --git a/Examples/IO/ImageSeriesReadWrite2.cxx b/Examples/IO/ImageSeriesReadWrite2.cxx index 214a69f3fe5..cc1331342ea 100644 --- a/Examples/IO/ImageSeriesReadWrite2.cxx +++ b/Examples/IO/ImageSeriesReadWrite2.cxx @@ -124,12 +124,12 @@ main(int argc, char ** argv) // Software Guide : EndCodeSnippet - std::string directory = argv[1]; - std::string regularExpression = argv[2]; + const std::string directory = argv[1]; + const std::string regularExpression = argv[2]; const unsigned int subMatch = std::stoi(argv[3]); - std::string outputFilename = argv[4]; + const std::string outputFilename = argv[4]; // Software Guide : BeginLatex diff --git a/Examples/IO/RGBImageReadWrite.cxx b/Examples/IO/RGBImageReadWrite.cxx index 40426cb5c8f..5d27670ff0c 100644 --- a/Examples/IO/RGBImageReadWrite.cxx +++ b/Examples/IO/RGBImageReadWrite.cxx @@ -102,7 +102,7 @@ main(int argc, char ** argv) // Software Guide : EndCodeSnippet - ImageType::Pointer image = reader->GetOutput(); + const ImageType::Pointer image = reader->GetOutput(); writer->SetInput(image); diff --git a/Examples/IO/TransformReadWrite.cxx b/Examples/IO/TransformReadWrite.cxx index 32668e6796a..0550398448a 100644 --- a/Examples/IO/TransformReadWrite.cxx +++ b/Examples/IO/TransformReadWrite.cxx @@ -55,9 +55,8 @@ main(int argc, char * argv[]) auto composite = CompositeTransformType::New(); using AffineTransformType = itk::AffineTransform; - auto affine = AffineTransformType::New(); - AffineTransformType::InputPointType cor; - cor.Fill(12); + auto affine = AffineTransformType::New(); + auto cor = itk::MakeFilled(12); affine->SetCenter(cor); composite->AddTransform(affine); @@ -76,15 +75,14 @@ main(int argc, char * argv[]) auto bspline = BSplineTransformType::New(); - BSplineTransformType::OriginType origin; - origin.Fill(100); - BSplineTransformType::PhysicalDimensionsType dimensions; - dimensions.Fill(1.5 * 9.0); + auto origin = itk::MakeFilled(100); + auto dimensions = + itk::MakeFilled(1.5 * 9.0); bspline->SetTransformDomainOrigin(origin); bspline->SetTransformDomainPhysicalDimensions(dimensions); - BSplineTransformType::ParametersType parameters( + const BSplineTransformType::ParametersType parameters( bspline->GetNumberOfParameters()); bspline->SetParameters(parameters); bspline->SetIdentity(); @@ -205,7 +203,7 @@ main(int argc, char * argv[]) auto it = transforms->begin(); if (!strcmp((*it)->GetNameOfClass(), "CompositeTransform")) { - ReadCompositeTransformType::Pointer compositeRead = + const ReadCompositeTransformType::Pointer compositeRead = static_cast((*it).GetPointer()); compositeRead->Print(std::cout); } diff --git a/Examples/IO/VisibleHumanPasteWrite.cxx b/Examples/IO/VisibleHumanPasteWrite.cxx index fc7b13abadf..1bcffc71413 100644 --- a/Examples/IO/VisibleHumanPasteWrite.cxx +++ b/Examples/IO/VisibleHumanPasteWrite.cxx @@ -47,8 +47,8 @@ main(int argc, char * argv[]) } - std::string inputImageFile = argv[1]; - std::string outputImageFile = argv[2]; + const std::string inputImageFile = argv[1]; + const std::string outputImageFile = argv[2]; using RGBPixelType = itk::RGBPixel; using RGB2DImageType = itk::Image; @@ -87,7 +87,7 @@ main(int argc, char * argv[]) // except that it is not templated over the image dimension, because // of the runtime nature of IO. composeRGB->UpdateOutputInformation(); - RGB2DImageType::RegionType largest = + const RGB2DImageType::RegionType largest = composeRGB->GetOutput()->GetLargestPossibleRegion(); itk::ImageIORegion halfIO(2); halfIO.SetIndex(0, @@ -118,9 +118,9 @@ main(int argc, char * argv[]) writer->SetIORegion(halfIO); writer->SetInput(adaptor); - itk::SimpleFilterWatcher watcher1(writer, "stream pasting writing"); + const itk::SimpleFilterWatcher watcher1(writer, "stream pasting writing"); - itk::SimpleFilterWatcher watcher(grad, "stream gradient magnitude"); + const itk::SimpleFilterWatcher watcher(grad, "stream gradient magnitude"); try diff --git a/Examples/IO/VisibleHumanStreamReadWrite.cxx b/Examples/IO/VisibleHumanStreamReadWrite.cxx index 353aa979bcb..2527fd1ed9a 100644 --- a/Examples/IO/VisibleHumanStreamReadWrite.cxx +++ b/Examples/IO/VisibleHumanStreamReadWrite.cxx @@ -55,8 +55,8 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - std::string visibleHumanPath = argv[1]; - std::string outputImageFile = argv[2]; + const std::string visibleHumanPath = argv[1]; + const std::string outputImageFile = argv[2]; using RGBPixelType = itk::RGBPixel; using PixelType = unsigned char; @@ -121,7 +121,7 @@ main(int argc, char * argv[]) composeRGB->SetInput3(breader->GetOutput()); // this filter is needed if square pixels are needed - // const int xyShrinkFactor = 3; + // constexpr int xyShrinkFactor = 3; // using ShrinkImageFilterType = itk::ShrinkImageFilter< RGB3DImageType, // RGB3DImageType >; auto shrinker = // ShrinkImageFilterType::New(); shrinker->SetInput( @@ -162,7 +162,7 @@ main(int argc, char * argv[]) writer->SetNumberOfStreamDivisions(200); writer->SetInput(extract->GetOutput()); - itk::SimpleFilterWatcher watcher1(writer, "stream writing"); + const itk::SimpleFilterWatcher watcher1(writer, "stream writing"); try diff --git a/Examples/IO/XML/DOMFindDemo.cxx b/Examples/IO/XML/DOMFindDemo.cxx index dffa0f89bb2..49982407864 100644 --- a/Examples/IO/XML/DOMFindDemo.cxx +++ b/Examples/IO/XML/DOMFindDemo.cxx @@ -60,10 +60,10 @@ main(int argc, char * argv[]) try { // read a DOM object from an XML file - itk::DOMNodeXMLReader::Pointer reader = itk::DOMNodeXMLReader::New(); + auto reader = itk::DOMNodeXMLReader::New(); reader->SetFileName(argv[1]); reader->Update(); - itk::DOMNode::Pointer dom = reader->GetOutput(); + const itk::DOMNode::Pointer dom = reader->GetOutput(); // the following code demonstrates the DOM function Find("QueryString"); // it navigates through the loaded XML document by typing a query string @@ -73,7 +73,7 @@ main(int argc, char * argv[]) do { std::cout << "query = \"" << query << "\"" << std::endl; - itk::DOMNode::Pointer dom2 = dom1->Find(query); + const itk::DOMNode::Pointer dom2 = dom1->Find(query); if ((itk::DOMNode *)dom2 == nullptr) { std::cout << "invalid query!" << std::endl; @@ -90,7 +90,7 @@ main(int argc, char * argv[]) } while (query != "..."); // write the sliced child DOM object to an XML file - itk::DOMNodeXMLWriter::Pointer writer = itk::DOMNodeXMLWriter::New(); + auto writer = itk::DOMNodeXMLWriter::New(); writer->SetInput(dom1); writer->SetFileName(argv[2]); writer->Update(); diff --git a/Examples/IO/XML/itkParticleSwarmOptimizerSAXReader.cxx b/Examples/IO/XML/itkParticleSwarmOptimizerSAXReader.cxx index f5264354659..628c0d4989c 100644 --- a/Examples/IO/XML/itkParticleSwarmOptimizerSAXReader.cxx +++ b/Examples/IO/XML/itkParticleSwarmOptimizerSAXReader.cxx @@ -31,7 +31,7 @@ int ParticleSwarmOptimizerSAXReader::CanReadFile(const char * name) { std::ifstream ifs(name); - int yes = ifs.is_open(); + const int yes = ifs.is_open(); if (yes) { ifs.close(); @@ -135,7 +135,7 @@ ParticleSwarmOptimizerSAXReader::CharacterDataHandler(const char * inData, { std::vector data; - std::string s(inData, inLength); + const std::string s(inData, inLength); std::istringstream iss(s); while (iss.good()) { @@ -282,7 +282,7 @@ ParticleSwarmOptimizerSAXReader::ProcessBoundAttributes( } } } // end if - } // end for + } // end for } /** Search for and return a particular attribute from the attribute list. */ diff --git a/Examples/IO/XML/itkParticleSwarmOptimizerSAXWriter.cxx b/Examples/IO/XML/itkParticleSwarmOptimizerSAXWriter.cxx index 39dd7f5bc25..53da4ee2f60 100644 --- a/Examples/IO/XML/itkParticleSwarmOptimizerSAXWriter.cxx +++ b/Examples/IO/XML/itkParticleSwarmOptimizerSAXWriter.cxx @@ -30,7 +30,7 @@ int ParticleSwarmOptimizerSAXWriter::CanWriteFile(const char * name) { std::ofstream ofs(name); - int yes = ofs.is_open(); + const int yes = ofs.is_open(); if (yes) { ofs.close(); diff --git a/Examples/Iterators/ImageLinearIteratorWithIndex2.cxx b/Examples/Iterators/ImageLinearIteratorWithIndex2.cxx index b31c2d44e05..519e77f6651 100644 --- a/Examples/Iterators/ImageLinearIteratorWithIndex2.cxx +++ b/Examples/Iterators/ImageLinearIteratorWithIndex2.cxx @@ -79,7 +79,7 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - Image4DType::ConstPointer image4D = reader4D->GetOutput(); + const Image4DType::ConstPointer image4D = reader4D->GetOutput(); // Software Guide : BeginLatex // @@ -106,7 +106,7 @@ main(int argc, char * argv[]) Spacing3DType spacing3D; Origin3DType origin3D; - Image4DType::RegionType region4D = image4D->GetBufferedRegion(); + const Image4DType::RegionType region4D = image4D->GetBufferedRegion(); Index4DType index4D = region4D.GetIndex(); Size4DType size4D = region4D.GetSize(); @@ -168,7 +168,7 @@ main(int argc, char * argv[]) sum += it.Get(); ++it; } - MeanType mean = + const MeanType mean = static_cast(sum) / static_cast(timeLength); index3D[0] = index4D[0]; diff --git a/Examples/Iterators/ImageSliceIteratorWithIndex.cxx b/Examples/Iterators/ImageSliceIteratorWithIndex.cxx index 95c4227a75e..8541b70bfa7 100644 --- a/Examples/Iterators/ImageSliceIteratorWithIndex.cxx +++ b/Examples/Iterators/ImageSliceIteratorWithIndex.cxx @@ -169,9 +169,8 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet auto projectionDirection = static_cast(std::stoi(argv[3])); - unsigned int i, j; unsigned int direction[2]; - for (i = 0, j = 0; i < 3; ++i) + for (unsigned int i = 0, j = 0; i < 3; ++i) { if (i != projectionDirection) { @@ -198,7 +197,8 @@ main(int argc, char * argv[]) ImageType2D::RegionType::SizeType size; ImageType2D::RegionType::IndexType index; - ImageType3D::RegionType requestedRegion = inputImage->GetRequestedRegion(); + const ImageType3D::RegionType requestedRegion = + inputImage->GetRequestedRegion(); index[direction[0]] = requestedRegion.GetIndex()[direction[0]]; index[1 - direction[0]] = requestedRegion.GetIndex()[direction[1]]; diff --git a/Examples/Iterators/NeighborhoodIterators1.cxx b/Examples/Iterators/NeighborhoodIterators1.cxx index 3eeffa186df..8a72a703f80 100644 --- a/Examples/Iterators/NeighborhoodIterators1.cxx +++ b/Examples/Iterators/NeighborhoodIterators1.cxx @@ -118,8 +118,7 @@ main(int argc, char ** argv) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - NeighborhoodIteratorType::RadiusType radius; - radius.Fill(1); + auto radius = itk::MakeFilled(1); NeighborhoodIteratorType it( radius, reader->GetOutput(), reader->GetOutput()->GetRequestedRegion()); // Software Guide : EndCodeSnippet @@ -160,12 +159,12 @@ main(int argc, char ** argv) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - NeighborhoodIteratorType::OffsetType offset1 = { { -1, -1 } }; - NeighborhoodIteratorType::OffsetType offset2 = { { 1, -1 } }; - NeighborhoodIteratorType::OffsetType offset3 = { { -1, 0 } }; - NeighborhoodIteratorType::OffsetType offset4 = { { 1, 0 } }; - NeighborhoodIteratorType::OffsetType offset5 = { { -1, 1 } }; - NeighborhoodIteratorType::OffsetType offset6 = { { 1, 1 } }; + constexpr NeighborhoodIteratorType::OffsetType offset1 = { { -1, -1 } }; + constexpr NeighborhoodIteratorType::OffsetType offset2 = { { 1, -1 } }; + constexpr NeighborhoodIteratorType::OffsetType offset3 = { { -1, 0 } }; + constexpr NeighborhoodIteratorType::OffsetType offset4 = { { 1, 0 } }; + constexpr NeighborhoodIteratorType::OffsetType offset5 = { { -1, 1 } }; + constexpr NeighborhoodIteratorType::OffsetType offset6 = { { 1, 1 } }; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex diff --git a/Examples/Iterators/NeighborhoodIterators2.cxx b/Examples/Iterators/NeighborhoodIterators2.cxx index de5d989de0b..fb0acea4eb6 100644 --- a/Examples/Iterators/NeighborhoodIterators2.cxx +++ b/Examples/Iterators/NeighborhoodIterators2.cxx @@ -124,11 +124,12 @@ main(int argc, char ** argv) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - NeighborhoodIteratorType::RadiusType radius = sobelOperator.GetRadius(); - NeighborhoodIteratorType it( + const NeighborhoodIteratorType::RadiusType radius = + sobelOperator.GetRadius(); + NeighborhoodIteratorType it( radius, reader->GetOutput(), reader->GetOutput()->GetRequestedRegion()); - itk::NeighborhoodInnerProduct innerProduct; + const itk::NeighborhoodInnerProduct innerProduct; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex diff --git a/Examples/Iterators/NeighborhoodIterators3.cxx b/Examples/Iterators/NeighborhoodIterators3.cxx index b960ac1d5ac..241dc332d8d 100644 --- a/Examples/Iterators/NeighborhoodIterators3.cxx +++ b/Examples/Iterators/NeighborhoodIterators3.cxx @@ -98,7 +98,7 @@ main(int argc, char ** argv) sobelOperator.SetDirection(std::stoi(argv[3])); sobelOperator.CreateDirectional(); - itk::NeighborhoodInnerProduct innerProduct; + const itk::NeighborhoodInnerProduct innerProduct; // Software Guide : BeginLatex // diff --git a/Examples/Iterators/NeighborhoodIterators4.cxx b/Examples/Iterators/NeighborhoodIterators4.cxx index d6fefe4dd88..1d178f15299 100644 --- a/Examples/Iterators/NeighborhoodIterators4.cxx +++ b/Examples/Iterators/NeighborhoodIterators4.cxx @@ -100,7 +100,7 @@ main(int argc, char ** argv) output->SetRegions(reader->GetOutput()->GetRequestedRegion()); output->Allocate(); - itk::NeighborhoodInnerProduct innerProduct; + const itk::NeighborhoodInnerProduct innerProduct; using FaceCalculatorType = itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator; @@ -170,7 +170,7 @@ main(int argc, char ** argv) // Swap the input and output buffers if (i != ImageType::ImageDimension - 1) { - ImageType::Pointer tmp = input; + const ImageType::Pointer tmp = input; input = output; output = tmp; } diff --git a/Examples/Iterators/NeighborhoodIterators5.cxx b/Examples/Iterators/NeighborhoodIterators5.cxx index c67171ca4a8..df0af750479 100644 --- a/Examples/Iterators/NeighborhoodIterators5.cxx +++ b/Examples/Iterators/NeighborhoodIterators5.cxx @@ -92,7 +92,7 @@ main(int argc, char ** argv) output->SetRegions(reader->GetOutput()->GetRequestedRegion()); output->Allocate(); - itk::NeighborhoodInnerProduct innerProduct; + const itk::NeighborhoodInnerProduct innerProduct; using FaceCalculatorType = itk::NeighborhoodAlgorithm::ImageBoundaryFacesCalculator; @@ -128,8 +128,8 @@ main(int argc, char ** argv) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - NeighborhoodIteratorType::RadiusType radius; - radius.Fill(gaussianOperator.GetRadius()[0]); + auto radius = itk::MakeFilled( + gaussianOperator.GetRadius()[0]); // Software Guide EndCodeSnippet // Software Guide : BeginLatex @@ -164,7 +164,7 @@ main(int argc, char ** argv) // Swap the input and output buffers if (i != ImageType::ImageDimension - 1) { - ImageType::Pointer tmp = input; + const ImageType::Pointer tmp = input; input = output; output = tmp; } diff --git a/Examples/Iterators/NeighborhoodIterators6.cxx b/Examples/Iterators/NeighborhoodIterators6.cxx index b192bc240b7..a8279bdc195 100644 --- a/Examples/Iterators/NeighborhoodIterators6.cxx +++ b/Examples/Iterators/NeighborhoodIterators6.cxx @@ -82,7 +82,7 @@ main(int argc, char ** argv) NodeType node; - const double seedValue = -initialDistance; + constexpr double seedValue = -initialDistance; ImageType::SizeType size = { { 256, 256 } }; @@ -94,10 +94,8 @@ main(int argc, char ** argv) fastMarching->SetTrialPoints(seeds); fastMarching->SetSpeedConstant(1.0); - itk::AddImageFilter::Pointer adder = - itk::AddImageFilter::New(); - itk::RandomImageSource::Pointer noise = - itk::RandomImageSource::New(); + auto adder = itk::AddImageFilter::New(); + auto noise = itk::RandomImageSource::New(); noise->SetSize(size.m_InternalArray); noise->SetMin(-.7); @@ -119,7 +117,7 @@ main(int argc, char ** argv) return EXIT_FAILURE; } - ImageType::Pointer input = adder->GetOutput(); + const ImageType::Pointer input = adder->GetOutput(); // Software Guide : BeginLatex // @@ -143,8 +141,7 @@ main(int argc, char ** argv) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - NeighborhoodIteratorType::RadiusType radius; - radius.Fill(1); + auto radius = itk::MakeFilled(1); NeighborhoodIteratorType it(radius, input, input->GetRequestedRegion()); it.SetLocation(index); @@ -166,8 +163,7 @@ main(int argc, char ** argv) bool flag = true; while (flag == true) { - NeighborhoodIteratorType::OffsetType nextMove; - nextMove.Fill(0); + NeighborhoodIteratorType::OffsetType nextMove{}; flag = false; diff --git a/Examples/Iterators/ShapedNeighborhoodIterators1.cxx b/Examples/Iterators/ShapedNeighborhoodIterators1.cxx index a39dcc4c3f6..6fa85350060 100644 --- a/Examples/Iterators/ShapedNeighborhoodIterators1.cxx +++ b/Examples/Iterators/ShapedNeighborhoodIterators1.cxx @@ -110,9 +110,9 @@ main(int argc, char ** argv) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - unsigned int element_radius = std::stoi(argv[3]); - ShapedNeighborhoodIteratorType::RadiusType radius; - radius.Fill(element_radius); + const unsigned int element_radius = std::stoi(argv[3]); + auto radius = itk::MakeFilled( + element_radius); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -180,7 +180,7 @@ main(int argc, char ** argv) { ShapedNeighborhoodIteratorType::OffsetType off; - float dis = std::sqrt(x * x + y * y); + const float dis = std::sqrt(x * x + y * y); if (dis <= rad) { off[0] = static_cast(x); diff --git a/Examples/Iterators/ShapedNeighborhoodIterators2.cxx b/Examples/Iterators/ShapedNeighborhoodIterators2.cxx index 00d23c039e7..2c8a00086be 100644 --- a/Examples/Iterators/ShapedNeighborhoodIterators2.cxx +++ b/Examples/Iterators/ShapedNeighborhoodIterators2.cxx @@ -52,7 +52,7 @@ main(int argc, char ** argv) auto reader = ReaderType::New(); reader->SetFileName(argv[1]); - unsigned int element_radius = std::stoi(argv[3]); + const unsigned int element_radius = std::stoi(argv[3]); try { @@ -76,8 +76,8 @@ main(int argc, char ** argv) FaceCalculatorType::FaceListType faceList; FaceCalculatorType::FaceListType::iterator fit; - ShapedNeighborhoodIteratorType::RadiusType radius; - radius.Fill(element_radius); + auto radius = itk::MakeFilled( + element_radius); faceList = faceCalculator(reader->GetOutput(), output->GetRequestedRegion(), radius); @@ -101,7 +101,7 @@ main(int argc, char ** argv) { ShapedNeighborhoodIteratorType::OffsetType off; - float dis = std::sqrt(x * x + y * y); + const float dis = std::sqrt(x * x + y * y); if (dis <= rad) { off[0] = static_cast(x); diff --git a/Examples/RegistrationITKv4/BSplineWarping1.cxx b/Examples/RegistrationITKv4/BSplineWarping1.cxx index 3502fe55a3b..bf6db1cf6fc 100644 --- a/Examples/RegistrationITKv4/BSplineWarping1.cxx +++ b/Examples/RegistrationITKv4/BSplineWarping1.cxx @@ -130,7 +130,7 @@ main(int argc, char * argv[]) movingWriter->SetFileName(argv[4]); - FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput(); using FilterType = @@ -153,17 +153,19 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - FixedImageType::SpacingType fixedSpacing = fixedImage->GetSpacing(); - FixedImageType::PointType fixedOrigin = fixedImage->GetOrigin(); - FixedImageType::DirectionType fixedDirection = fixedImage->GetDirection(); + FixedImageType::SpacingType fixedSpacing = fixedImage->GetSpacing(); + const FixedImageType::PointType fixedOrigin = fixedImage->GetOrigin(); + const FixedImageType::DirectionType fixedDirection = + fixedImage->GetDirection(); resampler->SetOutputSpacing(fixedSpacing); resampler->SetOutputOrigin(fixedOrigin); resampler->SetOutputDirection(fixedDirection); - FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion(); - FixedImageType::SizeType fixedSize = fixedRegion.GetSize(); + const FixedImageType::RegionType fixedRegion = + fixedImage->GetBufferedRegion(); + FixedImageType::SizeType fixedSize = fixedRegion.GetSize(); resampler->SetSize(fixedSize); resampler->SetOutputStartIndex(fixedRegion.GetIndex()); @@ -187,7 +189,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; diff --git a/Examples/RegistrationITKv4/BSplineWarping2.cxx b/Examples/RegistrationITKv4/BSplineWarping2.cxx index f7f49df58e0..d53826196b8 100644 --- a/Examples/RegistrationITKv4/BSplineWarping2.cxx +++ b/Examples/RegistrationITKv4/BSplineWarping2.cxx @@ -135,7 +135,7 @@ main(int argc, char * argv[]) movingWriter->SetFileName(argv[4]); // Software Guide : EndCodeSnippet - FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput(); using FilterType = @@ -150,9 +150,10 @@ main(int argc, char * argv[]) resampler->SetInterpolator(interpolator); - FixedImageType::SpacingType fixedSpacing = fixedImage->GetSpacing(); - FixedImageType::PointType fixedOrigin = fixedImage->GetOrigin(); - FixedImageType::DirectionType fixedDirection = fixedImage->GetDirection(); + FixedImageType::SpacingType fixedSpacing = fixedImage->GetSpacing(); + const FixedImageType::PointType fixedOrigin = fixedImage->GetOrigin(); + const FixedImageType::DirectionType fixedDirection = + fixedImage->GetDirection(); // Software Guide : BeginLatex // @@ -166,8 +167,9 @@ main(int argc, char * argv[]) resampler->SetOutputOrigin(fixedOrigin); resampler->SetOutputDirection(fixedDirection); - FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion(); - FixedImageType::SizeType fixedSize = fixedRegion.GetSize(); + const FixedImageType::RegionType fixedRegion = + fixedImage->GetBufferedRegion(); + FixedImageType::SizeType fixedSize = fixedRegion.GetSize(); resampler->SetSize(fixedSize); resampler->SetOutputStartIndex(fixedRegion.GetIndex()); // Software Guide : EndCodeSnippet @@ -191,7 +193,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; diff --git a/Examples/RegistrationITKv4/ChangeInformationImageFilter.cxx b/Examples/RegistrationITKv4/ChangeInformationImageFilter.cxx index cf7189942f0..b8c750b8cf6 100644 --- a/Examples/RegistrationITKv4/ChangeInformationImageFilter.cxx +++ b/Examples/RegistrationITKv4/ChangeInformationImageFilter.cxx @@ -117,15 +117,15 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - ImageType::ConstPointer inputImage = reader->GetOutput(); + const ImageType::ConstPointer inputImage = reader->GetOutput(); - ImageType::PointType origin = inputImage->GetOrigin(); - ImageType::SpacingType spacing = inputImage->GetSpacing(); - ImageType::DirectionType direction = inputImage->GetDirection(); + ImageType::PointType origin = inputImage->GetOrigin(); + ImageType::SpacingType spacing = inputImage->GetSpacing(); + const ImageType::DirectionType direction = inputImage->GetDirection(); if (argc > 3) { - double scale = std::stod(argv[3]); + const double scale = std::stod(argv[3]); for (unsigned int i = 0; i < Dimension; ++i) { spacing[i] *= scale; @@ -151,13 +151,14 @@ main(int argc, char * argv[]) if (argc > 7) { - double additionalAngle = std::stod(argv[7]); + const double additionalAngle = std::stod(argv[7]); itk::Versor rotation; - double angleInRadians = additionalAngle * itk::Math::pi / 180.0; + const double angleInRadians = additionalAngle * itk::Math::pi / 180.0; rotation.SetRotationAroundZ(angleInRadians); - ImageType::DirectionType newDirection = direction * rotation.GetMatrix(); + const ImageType::DirectionType newDirection = + direction * rotation.GetMatrix(); filter->SetOutputDirection(newDirection); filter->ChangeDirectionOn(); diff --git a/Examples/RegistrationITKv4/DeformableRegistration1.cxx b/Examples/RegistrationITKv4/DeformableRegistration1.cxx index 5eefcf04b06..6bbf3697e74 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration1.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration1.cxx @@ -214,8 +214,7 @@ main(int argc, char * argv[]) registrationFilter->SetMovingImage(IntensityEqualizeFilter->GetOutput()); - itk::ImageFileWriter::Pointer writer; - writer = itk::ImageFileWriter::New(); + auto writer = itk::ImageFileWriter::New(); std::string ofn = "fixed.mha"; writer->SetFileName(ofn.c_str()); writer->SetInput(registrationFilter->GetFixedImage()); @@ -231,8 +230,7 @@ main(int argc, char * argv[]) } ofn = "moving.mha"; - itk::ImageFileWriter::Pointer writer2; - writer2 = itk::ImageFileWriter::New(); + auto writer2 = itk::ImageFileWriter::New(); writer2->SetFileName(ofn.c_str()); writer2->SetInput(registrationFilter->GetMovingImage()); @@ -261,8 +259,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet // Create the material properties - itk::fem::MaterialLinearElasticity::Pointer m; - m = itk::fem::MaterialLinearElasticity::New(); + auto m = itk::fem::MaterialLinearElasticity::New(); m->SetGlobalNumber(0); // Young's modulus of the membrane m->SetYoungsModulus(registrationFilter->GetElasticity()); @@ -300,8 +297,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - itk::ImageFileWriter::Pointer warpedImageWriter; - warpedImageWriter = itk::ImageFileWriter::New(); + auto warpedImageWriter = itk::ImageFileWriter::New(); warpedImageWriter->SetInput(registrationFilter->GetWarpedImage()); warpedImageWriter->SetFileName("warpedMovingImage.mha"); try diff --git a/Examples/RegistrationITKv4/DeformableRegistration10.cxx b/Examples/RegistrationITKv4/DeformableRegistration10.cxx index 04ee58a8c62..8a95ba5cb5e 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration10.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration10.cxx @@ -175,9 +175,9 @@ main(int argc, char * argv[]) InternalPixelType>; using InterpolatorType = itk::LinearInterpolateImageFunction; - auto warper = WarperType::New(); - auto interpolator = InterpolatorType::New(); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + auto warper = WarperType::New(); + auto interpolator = InterpolatorType::New(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); warper->SetInput(movingImageReader->GetOutput()); warper->SetInterpolator(interpolator); diff --git a/Examples/RegistrationITKv4/DeformableRegistration11.cxx b/Examples/RegistrationITKv4/DeformableRegistration11.cxx index 5b97aa9b838..7ece605a9c9 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration11.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration11.cxx @@ -152,23 +152,20 @@ main(int argc, char * argv[]) registrationFilter->SetMovingImage(IntensityEqualizeFilter->GetOutput()); - itk::ImageFileWriter::Pointer writer; - writer = itk::ImageFileWriter::New(); + auto writer = itk::ImageFileWriter::New(); writer->SetFileName("fixed.mhd"); writer->SetInput(registrationFilter->GetFixedImage()); writer->Write(); - itk::ImageFileWriter::Pointer writer2; - writer2 = itk::ImageFileWriter::New(); + auto writer2 = itk::ImageFileWriter::New(); writer2->SetFileName("moving.mhd"); writer2->SetInput(registrationFilter->GetMovingImage()); writer2->Write(); // Create the material properties - itk::fem::MaterialLinearElasticity::Pointer m; - m = itk::fem::MaterialLinearElasticity::New(); + auto m = itk::fem::MaterialLinearElasticity::New(); m->SetGlobalNumber(0); m->SetYoungsModulus( registrationFilter diff --git a/Examples/RegistrationITKv4/DeformableRegistration12.cxx b/Examples/RegistrationITKv4/DeformableRegistration12.cxx index fb5401b3946..8edb123ae24 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration12.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration12.cxx @@ -149,17 +149,20 @@ main(int argc, char * argv[]) auto fixedImageReader = FixedImageReaderType::New(); fixedImageReader->SetFileName(argv[1]); fixedImageReader->Update(); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); - FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); + const FixedImageType::RegionType fixedRegion = + fixedImage->GetBufferedRegion(); using MovingImageReaderType = itk::ImageFileReader; auto movingImageReader = MovingImageReaderType::New(); movingImageReader->SetFileName(argv[2]); movingImageReader->Update(); - MovingImageType::ConstPointer movingImage = movingImageReader->GetOutput(); + const MovingImageType::ConstPointer movingImage = + movingImageReader->GetOutput(); // Software Guide : BeginCodeSnippet - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; @@ -321,7 +324,8 @@ main(int argc, char * argv[]) // While the registration filter is run, it updates the output transform // parameters with the final registration parameters - OptimizerType::ParametersType finalParameters = transform->GetParameters(); + const OptimizerType::ParametersType finalParameters = + transform->GetParameters(); // Report the time and memory taken by the registration chronometer.Report(std::cout); diff --git a/Examples/RegistrationITKv4/DeformableRegistration13.cxx b/Examples/RegistrationITKv4/DeformableRegistration13.cxx index e6a56dfee00..a8711d5596e 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration13.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration13.cxx @@ -142,7 +142,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; @@ -186,18 +186,20 @@ main(int argc, char * argv[]) fixedImageReader->SetFileName(argv[1]); movingImageReader->SetFileName(argv[2]); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImageReader->GetOutput()); fixedImageReader->Update(); - FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion(); + const FixedImageType::RegionType fixedRegion = + fixedImage->GetBufferedRegion(); registration->SetFixedImageRegion(fixedRegion); - unsigned int numberOfGridNodesInOneDimension = 7; + constexpr unsigned int numberOfGridNodesInOneDimension = 7; // Software Guide : BeginCodeSnippet @@ -307,7 +309,7 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - OptimizerType::ParametersType finalParameters = + const OptimizerType::ParametersType finalParameters = registration->GetLastTransformParameters(); diff --git a/Examples/RegistrationITKv4/DeformableRegistration14.cxx b/Examples/RegistrationITKv4/DeformableRegistration14.cxx index da7afc1177b..93beaab2a73 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration14.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration14.cxx @@ -121,7 +121,7 @@ main(int argc, char * argv[]) using FixedImageType = itk::Image; using MovingImageType = itk::Image; - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; @@ -161,18 +161,20 @@ main(int argc, char * argv[]) fixedImageReader->SetFileName(argv[1]); movingImageReader->SetFileName(argv[2]); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImageReader->GetOutput()); fixedImageReader->Update(); - FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion(); + const FixedImageType::RegionType fixedRegion = + fixedImage->GetBufferedRegion(); registration->SetFixedImageRegion(fixedRegion); - unsigned int numberOfGridNodesInOneDimension = 5; + constexpr unsigned int numberOfGridNodesInOneDimension = 5; // Software Guide : BeginCodeSnippet @@ -301,7 +303,7 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - OptimizerType::ParametersType finalParameters = + const OptimizerType::ParametersType finalParameters = registration->GetLastTransformParameters(); // Report the time and memory taken by the registration diff --git a/Examples/RegistrationITKv4/DeformableRegistration15.cxx b/Examples/RegistrationITKv4/DeformableRegistration15.cxx index 8ca1f7bca74..78ff03d9af8 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration15.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration15.cxx @@ -133,7 +133,7 @@ main(int argc, char * argv[]) using MovingImageType = itk::Image; - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; @@ -202,7 +202,8 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImageReader->GetOutput()); @@ -216,7 +217,8 @@ main(int argc, char * argv[]) // Setup the metric parameters metric->SetNumberOfHistogramBins(50); - FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion(); + const FixedImageType::RegionType fixedRegion = + fixedImage->GetBufferedRegion(); const unsigned int numberOfPixels = fixedRegion.GetNumberOfPixels(); @@ -278,7 +280,7 @@ main(int argc, char * argv[]) using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales( rigidTransform->GetNumberOfParameters()); - const double translationScale = 1.0 / 1000.0; + constexpr double translationScale = 1.0 / 1000.0; optimizerScales[0] = 1.0; optimizerScales[1] = 1.0; @@ -409,7 +411,7 @@ main(int argc, char * argv[]) // Perform Deformable Registration auto bsplineTransformCoarse = DeformableTransformType::New(); - unsigned int numberOfGridNodesInOneDimensionCoarse = 5; + constexpr unsigned int numberOfGridNodesInOneDimensionCoarse = 5; DeformableTransformType::PhysicalDimensionsType fixedPhysicalDimensions; DeformableTransformType::MeshSizeType meshSize; @@ -540,7 +542,7 @@ main(int argc, char * argv[]) auto bsplineTransformFine = DeformableTransformType::New(); - unsigned int numberOfGridNodesInOneDimensionFine = 20; + constexpr unsigned int numberOfGridNodesInOneDimensionFine = 20; meshSize.Fill(numberOfGridNodesInOneDimensionFine - SplineOrder); @@ -599,7 +601,8 @@ main(int argc, char * argv[]) decomposition->SetInput(upsampler->GetOutput()); decomposition->Update(); - ParametersImageType::Pointer newCoefficients = decomposition->GetOutput(); + const ParametersImageType::Pointer newCoefficients = + decomposition->GetOutput(); // copy the coefficients into the parameter array using Iterator = itk::ImageRegionIterator; diff --git a/Examples/RegistrationITKv4/DeformableRegistration16.cxx b/Examples/RegistrationITKv4/DeformableRegistration16.cxx index e8fa558f00e..3a4fe7d7923 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration16.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration16.cxx @@ -316,7 +316,7 @@ main(int argc, char * argv[]) auto interpolator = InterpolatorType::New(); - ImageType::Pointer targetImage = targetReader->GetOutput(); + const ImageType::Pointer targetImage = targetReader->GetOutput(); warper->SetInput(sourceReader->GetOutput()); warper->SetInterpolator(interpolator); warper->SetOutputSpacing(targetImage->GetSpacing()); diff --git a/Examples/RegistrationITKv4/DeformableRegistration17.cxx b/Examples/RegistrationITKv4/DeformableRegistration17.cxx index 06ac44cf333..dd07d2b68d9 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration17.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration17.cxx @@ -101,9 +101,11 @@ POSSIBILITY OF SUCH DAMAGE. #include "itkResampleImageFilter.h" #include "itkDisplacementFieldTransform.h" - +namespace +{ unsigned int RmsCounter = 0; double MaxRmsE[4] = { 0.8, 0.75, 0.4, 0.2 }; +} // namespace // The following section of code implements a Command observer // that will monitor the evolution of the registration process. @@ -317,7 +319,7 @@ main(int argc, char * argv[]) auto interpolator = InterpolatorType::New(); - ImageType::Pointer targetImage = targetReader->GetOutput(); + const ImageType::Pointer targetImage = targetReader->GetOutput(); warper->SetInput(sourceReader->GetOutput()); warper->SetInterpolator(interpolator); warper->SetOutputSpacing(targetImage->GetSpacing()); diff --git a/Examples/RegistrationITKv4/DeformableRegistration2.cxx b/Examples/RegistrationITKv4/DeformableRegistration2.cxx index 414ba7cc2eb..35a1235554f 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration2.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration2.cxx @@ -420,9 +420,9 @@ main(int argc, char * argv[]) using VectorImage2DType = DisplacementFieldType; using Vector2DType = DisplacementFieldType::PixelType; - VectorImage2DType::ConstPointer vectorImage2D = filter->GetOutput(); + const VectorImage2DType::ConstPointer vectorImage2D = filter->GetOutput(); - VectorImage2DType::RegionType region2D = + const VectorImage2DType::RegionType region2D = vectorImage2D->GetBufferedRegion(); VectorImage2DType::IndexType index2D = region2D.GetIndex(); VectorImage2DType::SizeType size2D = region2D.GetSize(); diff --git a/Examples/RegistrationITKv4/DeformableRegistration3.cxx b/Examples/RegistrationITKv4/DeformableRegistration3.cxx index 240a0505eec..dd38638c7da 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration3.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration3.cxx @@ -316,9 +316,9 @@ main(int argc, char * argv[]) using InterpolatorType = itk::LinearInterpolateImageFunction; - auto warper = WarperType::New(); - auto interpolator = InterpolatorType::New(); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + auto warper = WarperType::New(); + auto interpolator = InterpolatorType::New(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); warper->SetInput(movingImageReader->GetOutput()); warper->SetInterpolator(interpolator); diff --git a/Examples/RegistrationITKv4/DeformableRegistration4.cxx b/Examples/RegistrationITKv4/DeformableRegistration4.cxx index 4f302775f56..805b54dc1d9 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration4.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration4.cxx @@ -110,7 +110,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; @@ -145,7 +145,8 @@ main(int argc, char * argv[]) movingImageReader->SetFileName(argv[2]); fixedImageReader->Update(); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); // Software Guide : BeginLatex @@ -175,10 +176,10 @@ main(int argc, char * argv[]) auto transformInitializer = InitializerType::New(); - unsigned int numberOfGridNodesInOneDimension = 8; + constexpr unsigned int numberOfGridNodesInOneDimension = 8; - TransformType::MeshSizeType meshSize; - meshSize.Fill(numberOfGridNodesInOneDimension - SplineOrder); + auto meshSize = itk::MakeFilled( + numberOfGridNodesInOneDimension - SplineOrder); transformInitializer->SetTransform(transform); transformInitializer->SetImage(fixedImage); @@ -322,7 +323,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - OptimizerType::ParametersType finalParameters = transform->GetParameters(); + const OptimizerType::ParametersType finalParameters = + transform->GetParameters(); // Software Guide : EndCodeSnippet std::cout << "Last Transform Parameters" << std::endl; diff --git a/Examples/RegistrationITKv4/DeformableRegistration5.cxx b/Examples/RegistrationITKv4/DeformableRegistration5.cxx index 039b7707ca8..0474001be8f 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration5.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration5.cxx @@ -314,9 +314,9 @@ main(int argc, char * argv[]) using InterpolatorType = itk::LinearInterpolateImageFunction; - auto warper = WarperType::New(); - auto interpolator = InterpolatorType::New(); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + auto warper = WarperType::New(); + auto interpolator = InterpolatorType::New(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); warper->SetInput(movingImageReader->GetOutput()); warper->SetInterpolator(interpolator); @@ -422,9 +422,9 @@ main(int argc, char * argv[]) using VectorImage2DType = DisplacementFieldType; using Vector2DType = DisplacementFieldType::PixelType; - VectorImage2DType::ConstPointer vectorImage2D = filter->GetOutput(); + const VectorImage2DType::ConstPointer vectorImage2D = filter->GetOutput(); - VectorImage2DType::RegionType region2D = + const VectorImage2DType::RegionType region2D = vectorImage2D->GetBufferedRegion(); VectorImage2DType::IndexType index2D = region2D.GetIndex(); VectorImage2DType::SizeType size2D = region2D.GetSize(); diff --git a/Examples/RegistrationITKv4/DeformableRegistration6.cxx b/Examples/RegistrationITKv4/DeformableRegistration6.cxx index 93df4be33ac..f302e39b8f4 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration6.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration6.cxx @@ -160,7 +160,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; @@ -195,7 +195,8 @@ main(int argc, char * argv[]) fixedImageReader->SetFileName(argv[1]); movingImageReader->SetFileName(argv[2]); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImageReader->GetOutput()); @@ -221,10 +222,10 @@ main(int argc, char * argv[]) auto transformInitializer = InitializerType::New(); - unsigned int numberOfGridNodesInOneDimension = 8; + constexpr unsigned int numberOfGridNodesInOneDimension = 8; - TransformType::MeshSizeType meshSize; - meshSize.Fill(numberOfGridNodesInOneDimension - SplineOrder); + auto meshSize = itk::MakeFilled( + numberOfGridNodesInOneDimension - SplineOrder); transformInitializer->SetTransform(outputBSplineTransform); transformInitializer->SetImage(fixedImage); @@ -323,7 +324,7 @@ main(int argc, char * argv[]) bsplineAdaptor->SetRequiredTransformDomainPhysicalDimensions( fixedPhysicalDimensions); - adaptors.push_back(bsplineAdaptor); + adaptors.emplace_back(bsplineAdaptor); } registration->SetTransformParametersAdaptorsPerLevel(adaptors); diff --git a/Examples/RegistrationITKv4/DeformableRegistration7.cxx b/Examples/RegistrationITKv4/DeformableRegistration7.cxx index 453acd387c2..d7c7a095e80 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration7.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration7.cxx @@ -149,7 +149,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; @@ -185,7 +185,8 @@ main(int argc, char * argv[]) fixedImageReader->SetFileName(argv[1]); movingImageReader->SetFileName(argv[2]); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImageReader->GetOutput()); @@ -212,10 +213,10 @@ main(int argc, char * argv[]) auto transformInitializer = InitializerType::New(); - unsigned int numberOfGridNodesInOneDimension = 8; + constexpr unsigned int numberOfGridNodesInOneDimension = 8; - TransformType::MeshSizeType meshSize; - meshSize.Fill(numberOfGridNodesInOneDimension - SplineOrder); + auto meshSize = itk::MakeFilled( + numberOfGridNodesInOneDimension - SplineOrder); transformInitializer->SetTransform(outputBSplineTransform); transformInitializer->SetImage(fixedImage); @@ -306,7 +307,7 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - OptimizerType::ParametersType finalParameters = + const OptimizerType::ParametersType finalParameters = outputBSplineTransform->GetParameters(); std::cout << "Last Transform Parameters" << std::endl; diff --git a/Examples/RegistrationITKv4/DeformableRegistration8.cxx b/Examples/RegistrationITKv4/DeformableRegistration8.cxx index 4952cd61626..c7b17145200 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration8.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration8.cxx @@ -137,7 +137,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - const unsigned int SpaceDimension = ImageDimension; + constexpr unsigned int SpaceDimension = ImageDimension; constexpr unsigned int SplineOrder = 3; using CoordinateRepType = double; @@ -173,7 +173,8 @@ main(int argc, char * argv[]) fixedImageReader->SetFileName(argv[1]); movingImageReader->SetFileName(argv[2]); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImage(fixedImage); registration->SetMovingImage(movingImageReader->GetOutput()); @@ -207,8 +208,8 @@ main(int argc, char * argv[]) auto transformInitializer = InitializerType::New(); - TransformType::MeshSizeType meshSize; - meshSize.Fill(numberOfGridNodesInOneDimension - SplineOrder); + auto meshSize = itk::MakeFilled( + numberOfGridNodesInOneDimension - SplineOrder); transformInitializer->SetTransform(transform); transformInitializer->SetImage(fixedImage); @@ -314,7 +315,8 @@ main(int argc, char * argv[]) chronometer.Report(std::cout); memorymeter.Report(std::cout); - OptimizerType::ParametersType finalParameters = transform->GetParameters(); + const OptimizerType::ParametersType finalParameters = + transform->GetParameters(); std::cout << "Last Transform Parameters" << std::endl; std::cout << finalParameters << std::endl; diff --git a/Examples/RegistrationITKv4/DeformableRegistration9.cxx b/Examples/RegistrationITKv4/DeformableRegistration9.cxx index 45216847406..b906cc6c8f6 100644 --- a/Examples/RegistrationITKv4/DeformableRegistration9.cxx +++ b/Examples/RegistrationITKv4/DeformableRegistration9.cxx @@ -166,9 +166,9 @@ main(int argc, char * argv[]) using InterpolatorType = itk::LinearInterpolateImageFunction; - auto warper = WarperType::New(); - auto interpolator = InterpolatorType::New(); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + auto warper = WarperType::New(); + auto interpolator = InterpolatorType::New(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); warper->SetInput(movingImageReader->GetOutput()); warper->SetInterpolator(interpolator); diff --git a/Examples/RegistrationITKv4/DisplacementFieldInitialization.cxx b/Examples/RegistrationITKv4/DisplacementFieldInitialization.cxx index 1b89d0c64df..e3827cfe0b9 100644 --- a/Examples/RegistrationITKv4/DisplacementFieldInitialization.cxx +++ b/Examples/RegistrationITKv4/DisplacementFieldInitialization.cxx @@ -88,7 +88,7 @@ main(int argc, char * argv[]) } - FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput(); using FilterType = itk::LandmarkDisplacementFieldSource; diff --git a/Examples/RegistrationITKv4/ImageRegistration1.cxx b/Examples/RegistrationITKv4/ImageRegistration1.cxx index 1fe4770f8bf..0184edc2e93 100644 --- a/Examples/RegistrationITKv4/ImageRegistration1.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration1.cxx @@ -550,7 +550,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - TransformType::ConstPointer transform = registration->GetTransform(); + const TransformType::ConstPointer transform = registration->GetTransform(); // Software Guide : EndCodeSnippet @@ -728,7 +728,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resampler->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resampler->SetOutputOrigin(fixedImage->GetOrigin()); resampler->SetOutputSpacing(fixedImage->GetSpacing()); diff --git a/Examples/RegistrationITKv4/ImageRegistration10.cxx b/Examples/RegistrationITKv4/ImageRegistration10.cxx index c0ed286e5c6..18234d4aa52 100644 --- a/Examples/RegistrationITKv4/ImageRegistration10.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration10.cxx @@ -97,7 +97,7 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); + auto fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); // The types of each one of the components in the registration methods @@ -511,7 +511,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); resample->SetOutputSpacing(fixedImage->GetSpacing()); diff --git a/Examples/RegistrationITKv4/ImageRegistration11.cxx b/Examples/RegistrationITKv4/ImageRegistration11.cxx index 3c7059dbb61..25458e16a1a 100644 --- a/Examples/RegistrationITKv4/ImageRegistration11.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration11.cxx @@ -63,7 +63,7 @@ class CommandIterationUpdate : public itk::Command itkNewMacro(Self); protected: - CommandIterationUpdate() { m_LastMetricValue = 0.0; }; + CommandIterationUpdate() { m_LastMetricValue = 0.0; } public: using OptimizerType = itk::OnePlusOneEvolutionaryOptimizerv4; @@ -83,7 +83,7 @@ class CommandIterationUpdate : public itk::Command { return; } - double currentValue = optimizer->GetValue(); + const double currentValue = optimizer->GetValue(); // Only print out when the Metric value changes if (itk::Math::abs(m_LastMetricValue - currentValue) > 1e-7) { @@ -179,7 +179,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet registration->SetMetricSamplingPercentage(samplingPercentage); - RegistrationType::MetricSamplingStrategyEnum samplingStrategy = + constexpr RegistrationType::MetricSamplingStrategyEnum samplingStrategy = RegistrationType::MetricSamplingStrategyEnum::RANDOM; registration->SetMetricSamplingStrategy(samplingStrategy); // Software Guide : EndCodeSnippet @@ -295,12 +295,12 @@ main(int argc, char * argv[]) ParametersType finalParameters = transform->GetParameters(); - double TranslationAlongX = finalParameters[0]; - double TranslationAlongY = finalParameters[1]; + const double TranslationAlongX = finalParameters[0]; + const double TranslationAlongY = finalParameters[1]; - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results @@ -336,7 +336,7 @@ main(int argc, char * argv[]) resample->SetTransform(transform); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration12.cxx b/Examples/RegistrationITKv4/ImageRegistration12.cxx index 9f2043f8474..6215e888e74 100644 --- a/Examples/RegistrationITKv4/ImageRegistration12.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration12.cxx @@ -162,7 +162,7 @@ main(int argc, char * argv[]) using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales(transform->GetNumberOfParameters()); - const double translationScale = 1.0 / 1000.0; + constexpr double translationScale = 1.0 / 1000.0; optimizerScales[0] = 1.0; optimizerScales[1] = translationScale; @@ -375,8 +375,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - TransformType::MatrixType matrix = transform->GetMatrix(); - TransformType::OffsetType offset = transform->GetOffset(); + const TransformType::MatrixType matrix = transform->GetMatrix(); + const TransformType::OffsetType offset = transform->GetOffset(); std::cout << "Matrix = " << std::endl << matrix << std::endl; std::cout << "Offset = " << std::endl << offset << std::endl; @@ -394,7 +394,7 @@ main(int argc, char * argv[]) resample->SetTransform(finalTransform); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration13.cxx b/Examples/RegistrationITKv4/ImageRegistration13.cxx index d7a11674a82..0dda502249c 100644 --- a/Examples/RegistrationITKv4/ImageRegistration13.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration13.cxx @@ -139,10 +139,10 @@ main(int argc, char * argv[]) metric->SetNumberOfHistogramBins(20); - double samplingPercentage = 0.20; + constexpr double samplingPercentage = 0.20; registration->SetMetricSamplingPercentage(samplingPercentage); - RegistrationType::MetricSamplingStrategyEnum samplingStrategy = + constexpr RegistrationType::MetricSamplingStrategyEnum samplingStrategy = RegistrationType::MetricSamplingStrategyEnum::RANDOM; registration->SetMetricSamplingStrategy(samplingStrategy); // Software Guide : EndCodeSnippet @@ -214,7 +214,7 @@ main(int argc, char * argv[]) using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales(transform->GetNumberOfParameters()); - const double translationScale = 1.0 / 128.0; + constexpr double translationScale = 1.0 / 128.0; optimizerScales[0] = 1.0; optimizerScales[1] = translationScale; @@ -275,9 +275,9 @@ main(int argc, char * argv[]) const double rotationCenterY = registration->GetOutput()->Get()->GetFixedParameters()[1]; - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results // @@ -303,7 +303,7 @@ main(int argc, char * argv[]) resample->SetTransform(transform); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration14.cxx b/Examples/RegistrationITKv4/ImageRegistration14.cxx index 241e85f797e..fef1f1e42ca 100644 --- a/Examples/RegistrationITKv4/ImageRegistration14.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration14.cxx @@ -74,7 +74,7 @@ class CommandIterationUpdate : public itk::Command { return; } - double currentValue = optimizer->GetValue(); + const double currentValue = optimizer->GetValue(); // Only print out when the Metric value changes if (itk::Math::abs(m_LastMetricValue - currentValue) > 1e-7) { @@ -178,7 +178,8 @@ main(int argc, char * argv[]) fixedImageReader->Update(); movingImageReader->Update(); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImageRegion(fixedImage->GetBufferedRegion()); using TransformInitializerType = @@ -208,7 +209,7 @@ main(int argc, char * argv[]) transform->SetTranslation(initialTranslation); using ParametersType = RegistrationType::ParametersType; - ParametersType initialParameters = transform->GetParameters(); + const ParametersType initialParameters = transform->GetParameters(); registration->SetInitialTransformParameters(initialParameters); std::cout << "Initial transform parameters = "; std::cout << initialParameters << std::endl; @@ -216,7 +217,8 @@ main(int argc, char * argv[]) using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales(transform->GetNumberOfParameters()); - FixedImageType::RegionType region = fixedImage->GetLargestPossibleRegion(); + const FixedImageType::RegionType region = + fixedImage->GetLargestPossibleRegion(); FixedImageType::SizeType size = region.GetSize(); FixedImageType::SpacingType spacing = fixedImage->GetSpacing(); diff --git a/Examples/RegistrationITKv4/ImageRegistration15.cxx b/Examples/RegistrationITKv4/ImageRegistration15.cxx index 0e14741cc02..37d063ca145 100644 --- a/Examples/RegistrationITKv4/ImageRegistration15.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration15.cxx @@ -73,7 +73,7 @@ class CommandIterationUpdate : public itk::Command { return; } - double currentValue = optimizer->GetValue(); + const double currentValue = optimizer->GetValue(); // Only print out when the Metric value changes if (itk::Math::abs(m_LastMetricValue - currentValue) > 1e-7) { @@ -176,7 +176,8 @@ main(int argc, char * argv[]) fixedImageReader->Update(); movingImageReader->Update(); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImageRegion(fixedImage->GetBufferedRegion()); transform->SetIdentity(); @@ -198,7 +199,8 @@ main(int argc, char * argv[]) using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales(transform->GetNumberOfParameters()); - FixedImageType::RegionType region = fixedImage->GetLargestPossibleRegion(); + const FixedImageType::RegionType region = + fixedImage->GetLargestPossibleRegion(); FixedImageType::SizeType size = region.GetSize(); FixedImageType::SpacingType spacing = fixedImage->GetSpacing(); @@ -249,8 +251,8 @@ main(int argc, char * argv[]) ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalTranslationX = finalParameters[0]; const double finalTranslationY = finalParameters[1]; - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - const double bestValue = optimizer->GetValue(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const double bestValue = optimizer->GetValue(); // Print out results std::cout << "Result = " << std::endl; diff --git a/Examples/RegistrationITKv4/ImageRegistration16.cxx b/Examples/RegistrationITKv4/ImageRegistration16.cxx index 6f3dc8e0d32..3c20872365b 100644 --- a/Examples/RegistrationITKv4/ImageRegistration16.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration16.cxx @@ -184,7 +184,8 @@ main(int argc, char * argv[]) fixedImageReader->Update(); movingImageReader->Update(); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImageRegion(fixedImage->GetBufferedRegion()); @@ -286,7 +287,7 @@ main(int argc, char * argv[]) const double finalTranslationX = finalParameters[0]; const double finalTranslationY = finalParameters[1]; - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results diff --git a/Examples/RegistrationITKv4/ImageRegistration17.cxx b/Examples/RegistrationITKv4/ImageRegistration17.cxx index 2f0a0512db6..83f5ba795d3 100644 --- a/Examples/RegistrationITKv4/ImageRegistration17.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration17.cxx @@ -164,7 +164,8 @@ main(int argc, char * argv[]) fixedImageReader->Update(); movingImageReader->Update(); - FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = + fixedImageReader->GetOutput(); registration->SetFixedImageRegion(fixedImage->GetBufferedRegion()); @@ -279,7 +280,7 @@ main(int argc, char * argv[]) const double finalTranslationX = finalParameters[0]; const double finalTranslationY = finalParameters[1]; - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results diff --git a/Examples/RegistrationITKv4/ImageRegistration18.cxx b/Examples/RegistrationITKv4/ImageRegistration18.cxx index 75491488a66..b5054e282c1 100644 --- a/Examples/RegistrationITKv4/ImageRegistration18.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration18.cxx @@ -223,7 +223,7 @@ main(int argc, char * argv[]) resample->SetTransform(finalTransform); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration19.cxx b/Examples/RegistrationITKv4/ImageRegistration19.cxx index 22d1713b162..05a479287ce 100644 --- a/Examples/RegistrationITKv4/ImageRegistration19.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration19.cxx @@ -89,7 +89,7 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); + auto fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); // The types of each one of the components in the registration methods @@ -261,7 +261,7 @@ main(int argc, char * argv[]) // This parameter is tightly coupled to the stepInParametricSpace above. - double translationScale = 1.0 / 1000.0; + constexpr double translationScale = 1.0 / 1000.0; using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales(numberOfParameters); @@ -393,7 +393,7 @@ main(int argc, char * argv[]) // interpolator to be the same type of interpolator as the // registration method used (nearest neighbor). // - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); resample->SetOutputSpacing(fixedImage->GetSpacing()); diff --git a/Examples/RegistrationITKv4/ImageRegistration2.cxx b/Examples/RegistrationITKv4/ImageRegistration2.cxx index 76b0c7df097..4667d099492 100644 --- a/Examples/RegistrationITKv4/ImageRegistration2.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration2.cxx @@ -319,7 +319,7 @@ main(int argc, char * argv[]) fixedNormalizer->Update(); - FixedImageType::RegionType fixedImageRegion = + const FixedImageType::RegionType fixedImageRegion = fixedNormalizer->GetOutput()->GetBufferedRegion(); registration->SetFixedImageRegion(fixedImageRegion); @@ -444,12 +444,12 @@ main(int argc, char * argv[]) ParametersType finalParameters = registration->GetLastTransformParameters(); - double TranslationAlongX = finalParameters[0]; - double TranslationAlongY = finalParameters[1]; + const double TranslationAlongX = finalParameters[0]; + const double TranslationAlongY = finalParameters[1]; - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results @@ -510,7 +510,7 @@ main(int argc, char * argv[]) resample->SetTransform(finalTransform); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration20.cxx b/Examples/RegistrationITKv4/ImageRegistration20.cxx index ba8ff831c7b..fbfb367d009 100644 --- a/Examples/RegistrationITKv4/ImageRegistration20.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration20.cxx @@ -351,7 +351,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - OptimizerType::ParametersType finalParameters = + const OptimizerType::ParametersType finalParameters = registration->GetLastTransformParameters(); const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); @@ -384,7 +384,7 @@ main(int argc, char * argv[]) resampler->SetTransform(finalTransform); resampler->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resampler->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resampler->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration3.cxx b/Examples/RegistrationITKv4/ImageRegistration3.cxx index 619aef2114a..4f312f91419 100644 --- a/Examples/RegistrationITKv4/ImageRegistration3.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration3.cxx @@ -488,7 +488,7 @@ main(int argc, char * argv[]) resample->SetTransform(registration->GetTransform()); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration3.py b/Examples/RegistrationITKv4/ImageRegistration3.py index d0d408087f7..558a53d338c 100644 --- a/Examples/RegistrationITKv4/ImageRegistration3.py +++ b/Examples/RegistrationITKv4/ImageRegistration3.py @@ -68,6 +68,8 @@ optimizer.SetMinimumStepLength(0.001) optimizer.SetRelaxationFactor(0.5) optimizer.SetNumberOfIterations(100) + + # # Iteration Observer # diff --git a/Examples/RegistrationITKv4/ImageRegistration4.cxx b/Examples/RegistrationITKv4/ImageRegistration4.cxx index c70dd6c1b8a..af0041249b1 100644 --- a/Examples/RegistrationITKv4/ImageRegistration4.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration4.cxx @@ -306,7 +306,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - RegistrationType::MetricSamplingStrategyEnum samplingStrategy = + constexpr RegistrationType::MetricSamplingStrategyEnum samplingStrategy = RegistrationType::MetricSamplingStrategyEnum::RANDOM; // Software Guide : EndCodeSnippet @@ -349,7 +349,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - double samplingPercentage = 0.20; + constexpr double samplingPercentage = 0.20; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -388,15 +388,15 @@ main(int argc, char * argv[]) TransformType::ParametersType finalParameters = registration->GetOutput()->Get()->GetParameters(); - double TranslationAlongX = finalParameters[0]; - double TranslationAlongY = finalParameters[1]; + const double TranslationAlongX = finalParameters[0]; + const double TranslationAlongY = finalParameters[1]; // For stability reasons it may be desirable to round up the values of // translation // - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results @@ -453,7 +453,7 @@ main(int argc, char * argv[]) resample->SetTransform(registration->GetTransform()); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); PixelType defaultPixelValue = 100; diff --git a/Examples/RegistrationITKv4/ImageRegistration5.cxx b/Examples/RegistrationITKv4/ImageRegistration5.cxx index bdaae1b4e38..26571e15d9f 100644 --- a/Examples/RegistrationITKv4/ImageRegistration5.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration5.cxx @@ -293,7 +293,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); const SpacingType fixedSpacing = fixedImage->GetSpacing(); const OriginType fixedOrigin = fixedImage->GetOrigin(); @@ -314,7 +314,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - MovingImageType::Pointer movingImage = movingImageReader->GetOutput(); + const MovingImageType::Pointer movingImage = movingImageReader->GetOutput(); const SpacingType movingSpacing = movingImage->GetSpacing(); const OriginType movingOrigin = movingImage->GetOrigin(); @@ -396,7 +396,7 @@ main(int argc, char * argv[]) using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales( initialTransform->GetNumberOfParameters()); - const double translationScale = 1.0 / 1000.0; + constexpr double translationScale = 1.0 / 1000.0; optimizerScales[0] = 1.0; optimizerScales[1] = translationScale; diff --git a/Examples/RegistrationITKv4/ImageRegistration6.cxx b/Examples/RegistrationITKv4/ImageRegistration6.cxx index 24d81f620f8..5d9f30ee25d 100644 --- a/Examples/RegistrationITKv4/ImageRegistration6.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration6.cxx @@ -316,7 +316,7 @@ main(int argc, char * argv[]) using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales(transform->GetNumberOfParameters()); - const double translationScale = 1.0 / 1000.0; + constexpr double translationScale = 1.0 / 1000.0; optimizerScales[0] = 1.0; optimizerScales[1] = translationScale; @@ -443,8 +443,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - TransformType::MatrixType matrix = transform->GetMatrix(); - TransformType::OffsetType offset = transform->GetOffset(); + const TransformType::MatrixType matrix = transform->GetMatrix(); + const TransformType::OffsetType offset = transform->GetOffset(); std::cout << "Matrix = " << std::endl << matrix << std::endl; std::cout << "Offset = " << std::endl << offset << std::endl; @@ -577,7 +577,7 @@ main(int argc, char * argv[]) resample->SetTransform(transform); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration7.cxx b/Examples/RegistrationITKv4/ImageRegistration7.cxx index e1c3c70a633..6cf8f56b572 100644 --- a/Examples/RegistrationITKv4/ImageRegistration7.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration7.cxx @@ -295,7 +295,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales(transform->GetNumberOfParameters()); - const double translationScale = 1.0 / 100.0; + constexpr double translationScale = 1.0 / 100.0; optimizerScales[0] = 10.0; optimizerScales[1] = 1.0; @@ -490,7 +490,7 @@ main(int argc, char * argv[]) resampler->SetTransform(transform); resampler->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resampler->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resampler->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistration8.cxx b/Examples/RegistrationITKv4/ImageRegistration8.cxx index 00f7d959972..482ea3a0534 100644 --- a/Examples/RegistrationITKv4/ImageRegistration8.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration8.cxx @@ -315,7 +315,7 @@ main(int argc, char * argv[]) using OptimizerScalesType = OptimizerType::ScalesType; OptimizerScalesType optimizerScales( initialTransform->GetNumberOfParameters()); - const double translationScale = 1.0 / 1000.0; + constexpr double translationScale = 1.0 / 1000.0; optimizerScales[0] = 1.0; optimizerScales[1] = 1.0; optimizerScales[2] = 1.0; @@ -451,8 +451,8 @@ main(int argc, char * argv[]) finalTransform->SetParameters(finalParameters); // Software Guide : BeginCodeSnippet - TransformType::MatrixType matrix = finalTransform->GetMatrix(); - TransformType::OffsetType offset = finalTransform->GetOffset(); + const TransformType::MatrixType matrix = finalTransform->GetMatrix(); + const TransformType::OffsetType offset = finalTransform->GetOffset(); std::cout << "Matrix = " << std::endl << matrix << std::endl; std::cout << "Offset = " << std::endl << offset << std::endl; // Software Guide : EndCodeSnippet @@ -562,7 +562,7 @@ main(int argc, char * argv[]) resampler->SetTransform(finalTransform); resampler->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resampler->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resampler->SetOutputOrigin(fixedImage->GetOrigin()); @@ -636,7 +636,7 @@ main(int argc, char * argv[]) extractor->SetDirectionCollapseToSubmatrix(); extractor->InPlaceOn(); - FixedImageType::RegionType inputRegion = + const FixedImageType::RegionType inputRegion = fixedImage->GetLargestPossibleRegion(); FixedImageType::SizeType size = inputRegion.GetSize(); FixedImageType::IndexType start = inputRegion.GetIndex(); diff --git a/Examples/RegistrationITKv4/ImageRegistration9.cxx b/Examples/RegistrationITKv4/ImageRegistration9.cxx index 67b2bd072c3..703229d0c4b 100644 --- a/Examples/RegistrationITKv4/ImageRegistration9.cxx +++ b/Examples/RegistrationITKv4/ImageRegistration9.cxx @@ -115,7 +115,7 @@ class CommandIterationUpdate : public itk::Command vnl_svd svd(p); vnl_matrix r(2, 2); r = svd.U() * vnl_transpose(svd.V()); - double angle = std::asin(r[1][0]); + const double angle = std::asin(r[1][0]); std::cout << " AffineAngle: " << angle * 180.0 / itk::Math::pi << std::endl; } @@ -414,7 +414,7 @@ main(int argc, char * argv[]) vnl_svd svd(p); vnl_matrix r(2, 2); r = svd.U() * vnl_transpose(svd.V()); - double angle = std::asin(r[1][0]); + const double angle = std::asin(r[1][0]); const double angleInDegrees = angle * 180.0 / itk::Math::pi; @@ -523,7 +523,7 @@ main(int argc, char * argv[]) resampler->SetTransform(transform); resampler->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resampler->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resampler->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/ImageRegistrationHistogramPlotter.cxx b/Examples/RegistrationITKv4/ImageRegistrationHistogramPlotter.cxx index b1bd826c4d3..053b2618177 100644 --- a/Examples/RegistrationITKv4/ImageRegistrationHistogramPlotter.cxx +++ b/Examples/RegistrationITKv4/ImageRegistrationHistogramPlotter.cxx @@ -147,10 +147,7 @@ class RescaleDynamicRangeFunctor { return static_cast(255); } - else - { - return itk::Math::Round(-(30.0 * std::log(A))); - } + return itk::Math::Round(-(30.0 * std::log(A))); } else { @@ -249,7 +246,7 @@ class HistogramWriter void WriteHistogramFile(unsigned int iterationNumber) { - std::string outputFileBase = "JointHistogram"; + const std::string outputFileBase = "JointHistogram"; std::ostringstream outputFilename; outputFilename << outputFileBase << "." << std::setfill('0') << std::setw(3) << iterationNumber << "." @@ -380,7 +377,6 @@ class HistogramWriter HistogramToImageFilterPointer m_Filter; HistogramFileWriterPointer m_HistogramFileWriter; // Software Guide : EndCodeSnippet - std::string m_OutputFile; }; // Command - observer invoked after every iteration of the optimizer @@ -535,7 +531,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - unsigned int numberOfHistogramBins = std::stoi(argv[7]); + const unsigned int numberOfHistogramBins = std::stoi(argv[7]); MetricType::HistogramType::SizeType histogramSize; histogramSize.SetSize(2); histogramSize[0] = numberOfHistogramBins; @@ -649,12 +645,12 @@ main(int argc, char * argv[]) ParametersType finalParameters = registration->GetLastTransformParameters(); - double TranslationAlongX = finalParameters[0]; - double TranslationAlongY = finalParameters[1]; + const double TranslationAlongX = finalParameters[0]; + const double TranslationAlongY = finalParameters[1]; - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); std::cout << "Result = " << std::endl; @@ -689,7 +685,7 @@ main(int argc, char * argv[]) resample->SetTransform(finalTransform); resample->SetInput(movingImageReader->GetOutput()); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + const FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); diff --git a/Examples/RegistrationITKv4/IterativeClosestPoint1.cxx b/Examples/RegistrationITKv4/IterativeClosestPoint1.cxx index f71c1cbeeaa..5aeac385753 100644 --- a/Examples/RegistrationITKv4/IterativeClosestPoint1.cxx +++ b/Examples/RegistrationITKv4/IterativeClosestPoint1.cxx @@ -216,10 +216,10 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - unsigned long numberOfIterations = 100; - double gradientTolerance = 1e-5; // convergence criterion - double valueTolerance = 1e-5; // convergence criterion - double epsilonFunction = 1e-6; // convergence criterion + constexpr unsigned long numberOfIterations = 100; + constexpr double gradientTolerance = 1e-5; // convergence criterion + constexpr double valueTolerance = 1e-5; // convergence criterion + constexpr double epsilonFunction = 1e-6; // convergence criterion optimizer->SetScales(scales); diff --git a/Examples/RegistrationITKv4/IterativeClosestPoint2.cxx b/Examples/RegistrationITKv4/IterativeClosestPoint2.cxx index b4c979b29e2..57266063f57 100644 --- a/Examples/RegistrationITKv4/IterativeClosestPoint2.cxx +++ b/Examples/RegistrationITKv4/IterativeClosestPoint2.cxx @@ -232,10 +232,10 @@ main(int argc, char * argv[]) scales[4] = 1.0 / translationScale; scales[5] = 1.0 / translationScale; - unsigned long numberOfIterations = 2000; - double gradientTolerance = 1e-4; // convergence criterion - double valueTolerance = 1e-4; // convergence criterion - double epsilonFunction = 1e-5; // convergence criterion + constexpr unsigned long numberOfIterations = 2000; + constexpr double gradientTolerance = 1e-4; // convergence criterion + constexpr double valueTolerance = 1e-4; // convergence criterion + constexpr double epsilonFunction = 1e-5; // convergence criterion optimizer->SetScales(scales); diff --git a/Examples/RegistrationITKv4/IterativeClosestPoint3.cxx b/Examples/RegistrationITKv4/IterativeClosestPoint3.cxx index 8525698dd2b..50d62a8c35b 100644 --- a/Examples/RegistrationITKv4/IterativeClosestPoint3.cxx +++ b/Examples/RegistrationITKv4/IterativeClosestPoint3.cxx @@ -165,9 +165,9 @@ main(int argc, char * argv[]) scales.Fill(0.01); constexpr unsigned long numberOfIterations = 100; - const double gradientTolerance = 1e-5; // convergence criterion - const double valueTolerance = 1e-5; // convergence criterion - const double epsilonFunction = 1e-6; // convergence criterion + constexpr double gradientTolerance = 1e-5; // convergence criterion + constexpr double valueTolerance = 1e-5; // convergence criterion + constexpr double epsilonFunction = 1e-6; // convergence criterion optimizer->SetScales(scales); optimizer->SetNumberOfIterations(numberOfIterations); @@ -216,12 +216,6 @@ main(int argc, char * argv[]) auto pointsToImageFilter = PointsToImageFilterType::New(); pointsToImageFilter->SetInput(fixedPointSet); - - BinaryImageType::SpacingType spacing; - spacing.Fill(1.0); - - BinaryImageType::PointType origin; - origin.Fill(0.0); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -232,10 +226,9 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - pointsToImageFilter->SetSpacing(spacing); - pointsToImageFilter->SetOrigin(origin); pointsToImageFilter->Update(); - BinaryImageType::Pointer binaryImage = pointsToImageFilter->GetOutput(); + const BinaryImageType::Pointer binaryImage = + pointsToImageFilter->GetOutput(); using DistanceImageType = itk::Image; using DistanceFilterType = diff --git a/Examples/RegistrationITKv4/LandmarkWarping2.cxx b/Examples/RegistrationITKv4/LandmarkWarping2.cxx index ca816857067..9a1261b40f3 100644 --- a/Examples/RegistrationITKv4/LandmarkWarping2.cxx +++ b/Examples/RegistrationITKv4/LandmarkWarping2.cxx @@ -92,7 +92,7 @@ main(int argc, char * argv[]) movingWriter->SetFileName(argv[4]); - FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput(); + const FixedImageType::ConstPointer fixedImage = fixedReader->GetOutput(); // Software Guide : BeginLatex // @@ -189,7 +189,8 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - DisplacementFieldType::Pointer displacementField = deformer->GetOutput(); + const DisplacementFieldType::Pointer displacementField = + deformer->GetOutput(); using InterpolatorPrecisionType = double; using TransformPrecisionType = float; diff --git a/Examples/RegistrationITKv4/MeanSquaresImageMetric1.cxx b/Examples/RegistrationITKv4/MeanSquaresImageMetric1.cxx index 1bb1c8dab9b..1158b7f6aa1 100644 --- a/Examples/RegistrationITKv4/MeanSquaresImageMetric1.cxx +++ b/Examples/RegistrationITKv4/MeanSquaresImageMetric1.cxx @@ -132,8 +132,8 @@ main(int argc, char * argv[]) transform->SetIdentity(); - ImageType::ConstPointer fixedImage = fixedReader->GetOutput(); - ImageType::ConstPointer movingImage = movingReader->GetOutput(); + const ImageType::ConstPointer fixedImage = fixedReader->GetOutput(); + const ImageType::ConstPointer movingImage = movingReader->GetOutput(); // Software Guide : BeginLatex diff --git a/Examples/RegistrationITKv4/ModelToImageRegistration1.cxx b/Examples/RegistrationITKv4/ModelToImageRegistration1.cxx index 6a0cd9c8bf9..1c000a35315 100644 --- a/Examples/RegistrationITKv4/ModelToImageRegistration1.cxx +++ b/Examples/RegistrationITKv4/ModelToImageRegistration1.cxx @@ -337,9 +337,10 @@ class SimpleImageToSpatialObjectMetric this->m_Transform->SetParameters(parameters); value = 0; - for (auto it : m_PointList) + for (auto point : m_PointList) { - PointType transformedPoint = this->m_Transform->TransformPoint(it); + const PointType transformedPoint = + this->m_Transform->TransformPoint(point); if (this->m_Interpolator->IsInsideBuffer(transformedPoint)) { value += this->m_Interpolator->Evaluate(transformedPoint); @@ -917,7 +918,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - RegistrationType::ParametersType finalParameters = + const RegistrationType::ParametersType finalParameters = registration->GetLastTransformParameters(); std::cout << "Final Solution is : " << finalParameters << std::endl; diff --git a/Examples/RegistrationITKv4/ModelToImageRegistration2.cxx b/Examples/RegistrationITKv4/ModelToImageRegistration2.cxx index efee258fd17..1a7e3fff348 100644 --- a/Examples/RegistrationITKv4/ModelToImageRegistration2.cxx +++ b/Examples/RegistrationITKv4/ModelToImageRegistration2.cxx @@ -261,7 +261,8 @@ main(int argc, char * argv[]) // spatialObject->SetSizeInObjectSpace(boxSize); - ImageType::RegionType region = movingImage->GetLargestPossibleRegion(); + const ImageType::RegionType region = + movingImage->GetLargestPossibleRegion(); ImageType::SizeType imageSize = region.GetSize(); @@ -336,7 +337,7 @@ main(int argc, char * argv[]) OptimizerScalesType optimizerScales(transform->GetNumberOfParameters()); - const double translationScale = 1.0 / 1000.0; + constexpr double translationScale = 1.0 / 1000.0; optimizerScales[0] = 1.0; optimizerScales[1] = translationScale; @@ -360,11 +361,11 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - ParametersType transformParameters = + const ParametersType transformParameters = registrationMethod->GetLastTransformParameters(); - TransformType::OutputPointType center = transform->GetCenter(); + const TransformType::OutputPointType center = transform->GetCenter(); std::cout << "Registration parameter = " << std::endl; std::cout << "Rotation center = " << center << std::endl; diff --git a/Examples/RegistrationITKv4/MultiResImageRegistration1.cxx b/Examples/RegistrationITKv4/MultiResImageRegistration1.cxx index a777749be00..fc8246719a6 100644 --- a/Examples/RegistrationITKv4/MultiResImageRegistration1.cxx +++ b/Examples/RegistrationITKv4/MultiResImageRegistration1.cxx @@ -209,8 +209,8 @@ class RegistrationInterfaceCommand : public itk::Command static_cast(registration->GetModifiableOptimizer()); // Software Guide : EndCodeSnippet - unsigned int currentLevel = registration->GetCurrentLevel(); - typename RegistrationType::ShrinkFactorsPerDimensionContainerType + const unsigned int currentLevel = registration->GetCurrentLevel(); + const typename RegistrationType::ShrinkFactorsPerDimensionContainerType shrinkFactors = registration->GetShrinkFactorsPerDimension(currentLevel); typename RegistrationType::SmoothingSigmasArrayType smoothingSigmas = @@ -313,10 +313,10 @@ class CommandIterationUpdate : public itk::Command private: unsigned int m_CumulativeIterationIndex{ 0 }; }; - - +namespace +{ int -main(int argc, const char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 4) { @@ -377,17 +377,11 @@ main(int argc, const char * argv[]) registration->SetOptimizer(optimizer); registration->SetMetric(metric); - using FixedImageReaderType = itk::ImageFileReader; - using MovingImageReaderType = itk::ImageFileReader; - - auto fixedImageReader = FixedImageReaderType::New(); - auto movingImageReader = MovingImageReaderType::New(); - - fixedImageReader->SetFileName(fixedImageFile); - movingImageReader->SetFileName(movingImageFile); + const auto fixedImage = itk::ReadImage(fixedImageFile); + const auto movingImage = itk::ReadImage(movingImageFile); - registration->SetFixedImage(fixedImageReader->GetOutput()); - registration->SetMovingImage(movingImageReader->GetOutput()); + registration->SetFixedImage(fixedImage); + registration->SetMovingImage(movingImage); using ParametersType = OptimizerType::ParametersType; @@ -487,28 +481,21 @@ main(int argc, const char * argv[]) // // Software Guide : EndLatex - try - { - registration->Update(); - std::cout << "Optimizer stop condition: " - << registration->GetOptimizer()->GetStopConditionDescription() - << std::endl; - } - catch (const itk::ExceptionObject & err) - { - std::cout << "ExceptionObject caught !" << std::endl; - std::cout << err << std::endl; - return EXIT_FAILURE; - } + + registration->Update(); + std::cout << "Optimizer stop condition: " + << registration->GetOptimizer()->GetStopConditionDescription() + << std::endl; + ParametersType finalParameters = transform->GetParameters(); - double TranslationAlongX = finalParameters[0]; - double TranslationAlongY = finalParameters[1]; + const double TranslationAlongX = finalParameters[0]; + const double TranslationAlongY = finalParameters[1]; - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results @@ -568,10 +555,7 @@ main(int argc, const char * argv[]) auto resample = ResampleFilterType::New(); resample->SetTransform(transform); - resample->SetInput(movingImageReader->GetOutput()); - - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); - + resample->SetInput(movingImage); resample->SetSize(fixedImage->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fixedImage->GetOrigin()); @@ -586,20 +570,10 @@ main(int argc, const char * argv[]) using CastFilterType = itk::CastImageFilter; - - using WriterType = itk::ImageFileWriter; - - - auto writer = WriterType::New(); auto caster = CastFilterType::New(); - - - writer->SetFileName(outImagefile); - - caster->SetInput(resample->GetOutput()); - writer->SetInput(caster->GetOutput()); - writer->Update(); + + itk::WriteImage(caster->GetOutput(), outImagefile); // // Generate checkerboards before and after registration @@ -612,7 +586,6 @@ main(int argc, const char * argv[]) checker->SetInput2(resample->GetOutput()); caster->SetInput(checker->GetOutput()); - writer->SetInput(caster->GetOutput()); resample->SetDefaultPixelValue(0); @@ -627,8 +600,7 @@ main(int argc, const char * argv[]) } if (checkerBoardBefore != std::string("")) { - writer->SetFileName(checkerBoardBefore); - writer->Update(); + itk::WriteImage(caster->GetOutput(), checkerBoardBefore); } @@ -636,8 +608,7 @@ main(int argc, const char * argv[]) resample->SetTransform(transform); if (checkerBoardAfter != std::string("")) { - writer->SetFileName(checkerBoardAfter); - writer->Update(); + itk::WriteImage(caster->GetOutput(), checkerBoardAfter); } // Software Guide : BeginLatex @@ -688,3 +659,25 @@ main(int argc, const char * argv[]) return EXIT_SUCCESS; } +} // namespace +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/RegistrationITKv4/MultiResImageRegistration2.cxx b/Examples/RegistrationITKv4/MultiResImageRegistration2.cxx index 84373205fdd..27964711dc9 100644 --- a/Examples/RegistrationITKv4/MultiResImageRegistration2.cxx +++ b/Examples/RegistrationITKv4/MultiResImageRegistration2.cxx @@ -166,8 +166,11 @@ class RegistrationInterfaceCommand : public itk::Command } }; +namespace +{ + int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 4) { @@ -244,14 +247,8 @@ main(int argc, char * argv[]) registration->SetTransform(transform); // Software Guide : EndCodeSnippet - using FixedImageReaderType = itk::ImageFileReader; - using MovingImageReaderType = itk::ImageFileReader; - - auto fixedImageReader = FixedImageReaderType::New(); - auto movingImageReader = MovingImageReaderType::New(); - - fixedImageReader->SetFileName(argv[1]); - movingImageReader->SetFileName(argv[2]); + const auto fixedImage = itk::ReadImage(argv[1]); + const auto movingImage = itk::ReadImage(argv[2]); using FixedCastFilterType = itk::CastImageFilter; @@ -260,8 +257,8 @@ main(int argc, char * argv[]) auto fixedCaster = FixedCastFilterType::New(); auto movingCaster = MovingCastFilterType::New(); - fixedCaster->SetInput(fixedImageReader->GetOutput()); - movingCaster->SetInput(movingImageReader->GetOutput()); + fixedCaster->SetInput(fixedImage); + movingCaster->SetInput(movingImage); registration->SetFixedImage(fixedCaster->GetOutput()); registration->SetMovingImage(movingCaster->GetOutput()); @@ -289,8 +286,8 @@ main(int argc, char * argv[]) MovingImageType>; auto initializer = TransformInitializerType::New(); initializer->SetTransform(transform); - initializer->SetFixedImage(fixedImageReader->GetOutput()); - initializer->SetMovingImage(movingImageReader->GetOutput()); + initializer->SetFixedImage(fixedImage); + initializer->SetMovingImage(movingImage); initializer->MomentsOn(); initializer->InitializeTransform(); registration->SetInitialTransformParameters(transform->GetParameters()); @@ -444,19 +441,12 @@ main(int argc, char * argv[]) registration->AddObserver(itk::IterationEvent(), command); registration->SetNumberOfLevels(3); - try - { - registration->Update(); - std::cout << "Optimizer stop condition: " - << registration->GetOptimizer()->GetStopConditionDescription() - << std::endl; - } - catch (const itk::ExceptionObject & err) - { - std::cout << "ExceptionObject caught !" << std::endl; - std::cout << err << std::endl; - return EXIT_FAILURE; - } + + registration->Update(); + std::cout << "Optimizer stop condition: " + << registration->GetOptimizer()->GetStopConditionDescription() + << std::endl; + std::cout << "Optimizer Stopping Condition = " << optimizer->GetStopCondition() << std::endl; @@ -464,12 +454,12 @@ main(int argc, char * argv[]) using ParametersType = RegistrationType::ParametersType; ParametersType finalParameters = registration->GetLastTransformParameters(); - double TranslationAlongX = finalParameters[4]; - double TranslationAlongY = finalParameters[5]; + const double TranslationAlongX = finalParameters[4]; + const double TranslationAlongY = finalParameters[5]; - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results // @@ -533,9 +523,8 @@ main(int argc, char * argv[]) auto resample = ResampleFilterType::New(); resample->SetTransform(finalTransform); - resample->SetInput(movingImageReader->GetOutput()); + resample->SetInput(movingImage); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); PixelType backgroundGrayLevel = 100; if (argc > 4) @@ -553,16 +542,10 @@ main(int argc, char * argv[]) using OutputImageType = itk::Image; using CastFilterType = itk::CastImageFilter; - using WriterType = itk::ImageFileWriter; - - auto writer = WriterType::New(); auto caster = CastFilterType::New(); - writer->SetFileName(argv[3]); - caster->SetInput(resample->GetOutput()); - writer->SetInput(caster->GetOutput()); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[3]); // Software Guide : BeginLatex // @@ -613,7 +596,6 @@ main(int argc, char * argv[]) checker->SetInput2(resample->GetOutput()); caster->SetInput(checker->GetOutput()); - writer->SetInput(caster->GetOutput()); resample->SetDefaultPixelValue(0); @@ -625,17 +607,38 @@ main(int argc, char * argv[]) if (argc > 5) { - writer->SetFileName(argv[5]); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[5]); } // After registration resample->SetTransform(finalTransform); if (argc > 6) { - writer->SetFileName(argv[6]); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[6]); } return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/RegistrationITKv4/MultiResImageRegistration3.cxx b/Examples/RegistrationITKv4/MultiResImageRegistration3.cxx index 7a00431fee8..c3edf7fd34c 100644 --- a/Examples/RegistrationITKv4/MultiResImageRegistration3.cxx +++ b/Examples/RegistrationITKv4/MultiResImageRegistration3.cxx @@ -134,9 +134,10 @@ class CommandIterationUpdate : public itk::Command } }; - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 4) { @@ -197,16 +198,10 @@ main(int argc, char * argv[]) registration->SetFixedImagePyramid(fixedImagePyramid); registration->SetMovingImagePyramid(movingImagePyramid); - - using FixedImageReaderType = itk::ImageFileReader; - using MovingImageReaderType = itk::ImageFileReader; - - auto fixedImageReader = FixedImageReaderType::New(); - auto movingImageReader = MovingImageReaderType::New(); - - fixedImageReader->SetFileName(argv[1]); - movingImageReader->SetFileName(argv[2]); - + const FixedImageType::Pointer fixedImage = + itk::ReadImage(argv[1]); + const MovingImageType::Pointer movingImage = + itk::ReadImage(argv[2]); using FixedCastFilterType = itk::CastImageFilter; @@ -216,8 +211,8 @@ main(int argc, char * argv[]) auto fixedCaster = FixedCastFilterType::New(); auto movingCaster = MovingCastFilterType::New(); - fixedCaster->SetInput(fixedImageReader->GetOutput()); - movingCaster->SetInput(movingImageReader->GetOutput()); + fixedCaster->SetInput(fixedImage); + movingCaster->SetInput(movingImage); registration->SetFixedImage(fixedCaster->GetOutput()); registration->SetMovingImage(movingCaster->GetOutput()); @@ -284,29 +279,22 @@ main(int argc, char * argv[]) registration->SetNumberOfLevels(3); - try - { - registration->Update(); - std::cout << "Optimizer stop condition: " - << registration->GetOptimizer()->GetStopConditionDescription() - << std::endl; - } - catch (const itk::ExceptionObject & err) - { - std::cout << "ExceptionObject caught !" << std::endl; - std::cout << err << std::endl; - return EXIT_FAILURE; - } + + registration->Update(); + std::cout << "Optimizer stop condition: " + << registration->GetOptimizer()->GetStopConditionDescription() + << std::endl; + ParametersType finalParameters = registration->GetLastTransformParameters(); - double TranslationAlongX = finalParameters[0]; - double TranslationAlongY = finalParameters[1]; - double TranslationAlongZ = finalParameters[2]; + const double TranslationAlongX = finalParameters[0]; + const double TranslationAlongY = finalParameters[1]; + const double TranslationAlongZ = finalParameters[2]; - unsigned int numberOfIterations = optimizer->GetCurrentIteration(); + const unsigned int numberOfIterations = optimizer->GetCurrentIteration(); - double bestValue = optimizer->GetValue(); + const double bestValue = optimizer->GetValue(); // Print out results @@ -329,9 +317,7 @@ main(int argc, char * argv[]) auto resample = ResampleFilterType::New(); resample->SetTransform(finalTransform); - resample->SetInput(movingImageReader->GetOutput()); - - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); + resample->SetInput(movingImage); PixelType backgroundGrayLevel = 100; if (argc > 4) @@ -352,20 +338,9 @@ main(int argc, char * argv[]) using CastFilterType = itk::CastImageFilter; - - using WriterType = itk::ImageFileWriter; - - - auto writer = WriterType::New(); auto caster = CastFilterType::New(); - - - writer->SetFileName(argv[3]); - - caster->SetInput(resample->GetOutput()); - writer->SetInput(caster->GetOutput()); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[3]); // // Generate checkerboards before and after registration @@ -378,7 +353,6 @@ main(int argc, char * argv[]) checker->SetInput2(resample->GetOutput()); caster->SetInput(checker->GetOutput()); - writer->SetInput(caster->GetOutput()); resample->SetDefaultPixelValue(0); @@ -389,8 +363,7 @@ main(int argc, char * argv[]) if (argc > 5) { - writer->SetFileName(argv[5]); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[5]); } @@ -398,9 +371,31 @@ main(int argc, char * argv[]) resample->SetTransform(finalTransform); if (argc > 6) { - writer->SetFileName(argv[6]); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[6]); } return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/RegistrationITKv4/MultiStageImageRegistration1.cxx b/Examples/RegistrationITKv4/MultiStageImageRegistration1.cxx index a197a5b1d9e..f53913b423c 100644 --- a/Examples/RegistrationITKv4/MultiStageImageRegistration1.cxx +++ b/Examples/RegistrationITKv4/MultiStageImageRegistration1.cxx @@ -113,8 +113,8 @@ class RegistrationInterfaceCommand : public itk::Command const auto * registration = static_cast(object); - unsigned int currentLevel = registration->GetCurrentLevel(); - typename RegistrationType::ShrinkFactorsPerDimensionContainerType + const unsigned int currentLevel = registration->GetCurrentLevel(); + const typename RegistrationType::ShrinkFactorsPerDimensionContainerType shrinkFactors = registration->GetShrinkFactorsPerDimension(currentLevel); typename RegistrationType::SmoothingSigmasArrayType smoothingSigmas = @@ -170,9 +170,10 @@ class CommandIterationUpdate : public itk::Command private: unsigned int m_CumulativeIterationIndex{ 0 }; }; - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 4) { @@ -314,17 +315,11 @@ main(int argc, char * argv[]) compositeTransform->AddTransform(movingInitTx); // Software Guide : EndCodeSnippet - using FixedImageReaderType = itk::ImageFileReader; - using MovingImageReaderType = itk::ImageFileReader; + const auto fixedImage = itk::ReadImage(argv[1]); + const auto movingImage = itk::ReadImage(argv[2]); - auto fixedImageReader = FixedImageReaderType::New(); - auto movingImageReader = MovingImageReaderType::New(); - - fixedImageReader->SetFileName(argv[1]); - movingImageReader->SetFileName(argv[2]); - - transRegistration->SetFixedImage(fixedImageReader->GetOutput()); - transRegistration->SetMovingImage(movingImageReader->GetOutput()); + transRegistration->SetFixedImage(fixedImage); + transRegistration->SetMovingImage(movingImage); transRegistration->SetObjectName("TranslationRegistration"); // Software Guide : BeginLatex @@ -399,20 +394,13 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - try - { - transRegistration->Update(); - std::cout - << "Optimizer stop condition: " - << transRegistration->GetOptimizer()->GetStopConditionDescription() - << std::endl; - } - catch (const itk::ExceptionObject & err) - { - std::cout << "ExceptionObject caught !" << std::endl; - std::cout << err << std::endl; - return EXIT_FAILURE; - } + + transRegistration->Update(); + std::cout + << "Optimizer stop condition: " + << transRegistration->GetOptimizer()->GetStopConditionDescription() + << std::endl; + compositeTransform->AddTransform( transRegistration->GetModifiableTransform()); @@ -478,8 +466,8 @@ main(int argc, char * argv[]) affineRegistration->SetMovingInitialTransform(compositeTransform); // Software Guide : EndCodeSnippet - affineRegistration->SetFixedImage(fixedImageReader->GetOutput()); - affineRegistration->SetMovingImage(movingImageReader->GetOutput()); + affineRegistration->SetFixedImage(fixedImage); + affineRegistration->SetMovingImage(movingImage); affineRegistration->SetObjectName("AffineRegistration"); affineMetric->SetNumberOfHistogramBins(24); @@ -533,8 +521,6 @@ main(int argc, char * argv[]) using RegionType = FixedImageType::RegionType; using SizeType = FixedImageType::SizeType; - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); - const SpacingType fixedSpacing = fixedImage->GetSpacing(); const OriginType fixedOrigin = fixedImage->GetOrigin(); const RegionType fixedRegion = fixedImage->GetLargestPossibleRegion(); @@ -749,20 +735,12 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - try - { - affineRegistration->Update(); - std::cout - << "Optimizer stop condition: " - << affineRegistration->GetOptimizer()->GetStopConditionDescription() - << std::endl; - } - catch (const itk::ExceptionObject & err) - { - std::cout << "ExceptionObject caught !" << std::endl; - std::cout << err << std::endl; - return EXIT_FAILURE; - } + + affineRegistration->Update(); + std::cout + << "Optimizer stop condition: " + << affineRegistration->GetOptimizer()->GetStopConditionDescription() + << std::endl; compositeTransform->AddTransform( affineRegistration->GetModifiableTransform()); @@ -881,7 +859,7 @@ main(int argc, char * argv[]) auto resample = ResampleFilterType::New(); resample->SetTransform(compositeTransform); - resample->SetInput(movingImageReader->GetOutput()); + resample->SetInput(movingImage); PixelType backgroundGrayLevel = 100; if (argc > 4) @@ -899,16 +877,10 @@ main(int argc, char * argv[]) using OutputImageType = itk::Image; using CastFilterType = itk::CastImageFilter; - using WriterType = itk::ImageFileWriter; - - auto writer = WriterType::New(); auto caster = CastFilterType::New(); - writer->SetFileName(argv[3]); - caster->SetInput(resample->GetOutput()); - writer->SetInput(caster->GetOutput()); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[3]); // Software Guide : BeginLatex // @@ -937,9 +909,7 @@ main(int argc, char * argv[]) checker->SetInput1(fixedImage); checker->SetInput2(resample->GetOutput()); - caster->SetInput(checker->GetOutput()); - writer->SetInput(caster->GetOutput()); resample->SetDefaultPixelValue(0); @@ -947,31 +917,47 @@ main(int argc, char * argv[]) // Before registration using TransformType = itk::IdentityTransform; TransformType::Pointer identityTransform; - try - { - identityTransform = TransformType::New(); - } - catch (const itk::ExceptionObject & err) - { - err.Print(std::cerr); - return EXIT_FAILURE; - } + + identityTransform = TransformType::New(); + identityTransform->SetIdentity(); resample->SetTransform(identityTransform); if (argc > 5) { - writer->SetFileName(argv[5]); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[5]); } // After registration resample->SetTransform(compositeTransform); if (argc > 6) { - writer->SetFileName(argv[6]); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[6]); } return EXIT_SUCCESS; } +} // namespace + + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/RegistrationITKv4/MultiStageImageRegistration2.cxx b/Examples/RegistrationITKv4/MultiStageImageRegistration2.cxx index 97087a11623..0e9cd602f42 100644 --- a/Examples/RegistrationITKv4/MultiStageImageRegistration2.cxx +++ b/Examples/RegistrationITKv4/MultiStageImageRegistration2.cxx @@ -111,8 +111,8 @@ class RegistrationInterfaceCommand : public itk::Command << object->GetNameOfClass()); } - unsigned int currentLevel = registration->GetCurrentLevel(); - typename RegistrationType::ShrinkFactorsPerDimensionContainerType + const unsigned int currentLevel = registration->GetCurrentLevel(); + const typename RegistrationType::ShrinkFactorsPerDimensionContainerType shrinkFactors = registration->GetShrinkFactorsPerDimension(currentLevel); typename RegistrationType::SmoothingSigmasArrayType smoothingSigmas = @@ -174,8 +174,10 @@ class CommandIterationUpdate : public itk::Command unsigned int m_CumulativeIterationIndex{ 0 }; }; +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 4) { @@ -254,17 +256,11 @@ main(int argc, char * argv[]) // // Software Guide : EndLatex - using FixedImageReaderType = itk::ImageFileReader; - using MovingImageReaderType = itk::ImageFileReader; - - auto fixedImageReader = FixedImageReaderType::New(); - auto movingImageReader = MovingImageReaderType::New(); + const auto fixedImage = itk::ReadImage(argv[1]); + const auto movingImage = itk::ReadImage(argv[2]); - fixedImageReader->SetFileName(argv[1]); - movingImageReader->SetFileName(argv[2]); - - transRegistration->SetFixedImage(fixedImageReader->GetOutput()); - transRegistration->SetMovingImage(movingImageReader->GetOutput()); + transRegistration->SetFixedImage(fixedImage); + transRegistration->SetMovingImage(movingImage); transRegistration->SetObjectName("TranslationRegistration"); // Software Guide : BeginLatex @@ -368,8 +364,6 @@ main(int argc, char * argv[]) affineMetric->SetNumberOfHistogramBins(std::stoi(argv[7])); } - fixedImageReader->Update(); - FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); // Software Guide : BeginCodeSnippet using FixedImageCalculatorType = @@ -406,8 +400,8 @@ main(int argc, char * argv[]) affineRegistration->InPlaceOn(); // Software Guide : EndCodeSnippet - affineRegistration->SetFixedImage(fixedImageReader->GetOutput()); - affineRegistration->SetMovingImage(movingImageReader->GetOutput()); + affineRegistration->SetFixedImage(fixedImage); + affineRegistration->SetMovingImage(movingImage); affineRegistration->SetObjectName("AffineRegistration"); // Software Guide : BeginLatex @@ -492,20 +486,14 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - try - { - affineRegistration->Update(); - std::cout - << "Optimizer stop condition: " - << affineRegistration->GetOptimizer()->GetStopConditionDescription() - << std::endl; - } - catch (const itk::ExceptionObject & err) - { - std::cout << "ExceptionObject caught !" << std::endl; - std::cout << err << std::endl; - return EXIT_FAILURE; - } + + affineRegistration->Update(); + std::cout + << "Optimizer stop condition: " + << affineRegistration->GetOptimizer()->GetStopConditionDescription() + << std::endl; + + // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -597,7 +585,7 @@ main(int argc, char * argv[]) auto resample = ResampleFilterType::New(); resample->SetTransform(compositeTransform); - resample->SetInput(movingImageReader->GetOutput()); + resample->SetInput(movingImage); PixelType backgroundGrayLevel = 100; if (argc > 4) @@ -615,16 +603,10 @@ main(int argc, char * argv[]) using OutputImageType = itk::Image; using CastFilterType = itk::CastImageFilter; - using WriterType = itk::ImageFileWriter; - - auto writer = WriterType::New(); auto caster = CastFilterType::New(); - writer->SetFileName(argv[3]); - caster->SetInput(resample->GetOutput()); - writer->SetInput(caster->GetOutput()); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[3]); // Software Guide : BeginLatex // @@ -657,7 +639,6 @@ main(int argc, char * argv[]) checker->SetInput2(resample->GetOutput()); caster->SetInput(checker->GetOutput()); - writer->SetInput(caster->GetOutput()); resample->SetDefaultPixelValue(0); @@ -665,31 +646,45 @@ main(int argc, char * argv[]) // Before registration using TransformType = itk::IdentityTransform; TransformType::Pointer identityTransform; - try - { - identityTransform = TransformType::New(); - } - catch (const itk::ExceptionObject & err) - { - err.Print(std::cerr); - return EXIT_FAILURE; - } + + identityTransform = TransformType::New(); + identityTransform->SetIdentity(); resample->SetTransform(identityTransform); if (argc > 5) { - writer->SetFileName(argv[5]); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[5]); } // After registration resample->SetTransform(compositeTransform); if (argc > 6) { - writer->SetFileName(argv[6]); - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[6]); } return EXIT_SUCCESS; } +} // namespace +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/RegistrationITKv4/ThinPlateSplineWarp.cxx b/Examples/RegistrationITKv4/ThinPlateSplineWarp.cxx index 20f555e9a8c..92b9373919e 100644 --- a/Examples/RegistrationITKv4/ThinPlateSplineWarp.cxx +++ b/Examples/RegistrationITKv4/ThinPlateSplineWarp.cxx @@ -40,9 +40,10 @@ #include "itkPointSet.h" #include - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 4) { @@ -58,11 +59,8 @@ main(int argc, char * argv[]) using PixelType = unsigned char; using InputImageType = itk::Image; - using ReaderType = itk::ImageFileReader; - using DeformedImageWriterType = itk::ImageFileWriter; using FieldVectorType = itk::Vector; using DisplacementFieldType = itk::Image; - using FieldWriterType = itk::ImageFileWriter; using CoordinateRepType = double; using TransformType = itk::ThinPlateSplineKernelTransform; @@ -74,19 +72,9 @@ main(int argc, char * argv[]) using InterpolatorType = itk::LinearInterpolateImageFunction; - auto reader = ReaderType::New(); - reader->SetFileName(argv[2]); + InputImageType::ConstPointer inputImage; - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Exception thrown " << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + inputImage = itk::ReadImage(argv[2]); // Software Guide : BeginLatex @@ -104,9 +92,9 @@ main(int argc, char * argv[]) auto targetLandMarks = PointSetType::New(); PointType p1; PointType p2; - PointSetType::PointsContainer::Pointer sourceLandMarkContainer = + const PointSetType::PointsContainer::Pointer sourceLandMarkContainer = sourceLandMarks->GetPoints(); - PointSetType::PointsContainer::Pointer targetLandMarkContainer = + const PointSetType::PointsContainer::Pointer targetLandMarkContainer = targetLandMarks->GetPoints(); // Software Guide : EndCodeSnippet @@ -141,15 +129,14 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Set the resampler params - InputImageType::ConstPointer inputImage = reader->GetOutput(); - auto resampler = ResamplerType::New(); - auto interpolator = InterpolatorType::New(); + auto resampler = ResamplerType::New(); + auto interpolator = InterpolatorType::New(); resampler->SetInterpolator(interpolator); - InputImageType::SpacingType spacing = inputImage->GetSpacing(); - InputImageType::PointType origin = inputImage->GetOrigin(); - InputImageType::DirectionType direction = inputImage->GetDirection(); - InputImageType::RegionType region = inputImage->GetBufferedRegion(); - InputImageType::SizeType size = region.GetSize(); + const InputImageType::SpacingType spacing = inputImage->GetSpacing(); + const InputImageType::PointType origin = inputImage->GetOrigin(); + const InputImageType::DirectionType direction = inputImage->GetDirection(); + const InputImageType::RegionType region = inputImage->GetBufferedRegion(); + const InputImageType::SizeType size = region.GetSize(); // Software Guide : BeginCodeSnippet resampler->SetOutputSpacing(spacing); @@ -160,23 +147,11 @@ main(int argc, char * argv[]) // Software Guide : EndCodeSnippet resampler->SetOutputStartIndex(region.GetIndex()); - resampler->SetInput(reader->GetOutput()); + resampler->SetInput(inputImage); // Set and write deformed image - auto deformedImageWriter = DeformedImageWriterType::New(); - deformedImageWriter->SetInput(resampler->GetOutput()); - deformedImageWriter->SetFileName(argv[3]); - try - { - deformedImageWriter->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Exception thrown " << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + itk::WriteImage(resampler->GetOutput(), argv[3]); // Software Guide : BeginLatex @@ -216,18 +191,31 @@ main(int argc, char * argv[]) } // Write computed deformation field - auto fieldWriter = FieldWriterType::New(); - fieldWriter->SetFileName(argv[4]); - fieldWriter->SetInput(field); + + itk::WriteImage(field, argv[4]); + + + return EXIT_SUCCESS; +} +} // namespace +int +main(int argc, char * argv[]) +{ try { - fieldWriter->Update(); + return ExampleMain(argc, argv); } - catch (const itk::ExceptionObject & excp) + catch (const itk::ExceptionObject & exceptionObject) { - std::cerr << "Exception thrown " << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; } - return EXIT_SUCCESS; + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; } diff --git a/Examples/Segmentation/CannySegmentationLevelSetImageFilter.cxx b/Examples/Segmentation/CannySegmentationLevelSetImageFilter.cxx index 991f26ea347..5b476f3cf66 100644 --- a/Examples/Segmentation/CannySegmentationLevelSetImageFilter.cxx +++ b/Examples/Segmentation/CannySegmentationLevelSetImageFilter.cxx @@ -134,16 +134,8 @@ main(int argc, char * argv[]) thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader1 = ReaderType::New(); - auto reader2 = ReaderType::New(); - auto writer = WriterType::New(); - - reader1->SetFileName(argv[1]); - reader2->SetFileName(argv[2]); - writer->SetFileName(argv[3]); + const auto input1 = itk::ReadImage(argv[1]); + const auto input2 = itk::ReadImage(argv[2]); // Software Guide : BeginLatex // @@ -249,18 +241,16 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - diffusion->SetInput(reader1->GetOutput()); - cannySegmentation->SetInput(reader2->GetOutput()); + diffusion->SetInput(input1); + cannySegmentation->SetInput(input2); cannySegmentation->SetFeatureImage(diffusion->GetOutput()); thresholder->SetInput(cannySegmentation->GetOutput()); - writer->SetInput(thresholder->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // - // Invoking the \code{Update()} method on the writer triggers the - // execution of the pipeline. As usual, the call is placed in a + // As usual, the write image call is placed in a // \code{try/catch} block to handle any exceptions that may be thrown. // // Software Guide : EndLatex @@ -268,7 +258,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), argv[3]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/ConfidenceConnected.cxx b/Examples/Segmentation/ConfidenceConnected.cxx index db69c98e5d9..b65753018af 100644 --- a/Examples/Segmentation/ConfidenceConnected.cxx +++ b/Examples/Segmentation/ConfidenceConnected.cxx @@ -134,18 +134,8 @@ main(int argc, char * argv[]) itk::CastImageFilter; auto caster = CastingFilterType::New(); - - // We instantiate reader and writer types - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - + // Read the input image + const auto input = itk::ReadImage(argv[1]); // Software Guide : BeginLatex // @@ -199,7 +189,7 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // // Now it is time to create a simple, linear pipeline. A file reader is - // added at the beginning of the pipeline and a cast filter and writer are + // added at the beginning of the pipeline and a cast filter is // added at the end. The cast filter is required here to convert // \code{float} pixel types to integer types since only a few image file // formats support \code{float} types. @@ -207,10 +197,9 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); confidenceConnected->SetInput(smoothing->GetOutput()); caster->SetInput(confidenceConnected->GetOutput()); - writer->SetInput(caster->GetOutput()); // Software Guide : EndCodeSnippet @@ -330,8 +319,8 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // - // The invocation of the \code{Update()} method on the writer triggers the - // execution of the pipeline. It is recommended to place update calls in a + // The invocation of \code{WriteImage} triggers the + // execution of the pipeline. It is recommended to place write calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex @@ -339,7 +328,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/ConfidenceConnected3D.cxx b/Examples/Segmentation/ConfidenceConnected3D.cxx index a286289ac24..6a91e0e7e0d 100644 --- a/Examples/Segmentation/ConfidenceConnected3D.cxx +++ b/Examples/Segmentation/ConfidenceConnected3D.cxx @@ -60,15 +60,7 @@ main(int argc, char * argv[]) itk::CastImageFilter; auto caster = CastingFilterType::New(); - - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); + const auto input = itk::ReadImage(argv[1]); using CurvatureFlowImageFilterType = itk::CurvatureFlowImageFilter; @@ -78,10 +70,9 @@ main(int argc, char * argv[]) itk::ConfidenceConnectedImageFilter; auto confidenceConnected = ConnectedFilterType::New(); - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); confidenceConnected->SetInput(smoothing->GetOutput()); caster->SetInput(confidenceConnected->GetOutput()); - writer->SetInput(caster->GetOutput()); smoothing->SetNumberOfIterations(2); smoothing->SetTimeStep(0.05); @@ -123,7 +114,7 @@ main(int argc, char * argv[]) try { - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/ConnectedThresholdImageFilter.cxx b/Examples/Segmentation/ConnectedThresholdImageFilter.cxx index bdbac9226d1..efc9e16d077 100644 --- a/Examples/Segmentation/ConnectedThresholdImageFilter.cxx +++ b/Examples/Segmentation/ConnectedThresholdImageFilter.cxx @@ -130,15 +130,7 @@ main(int argc, char * argv[]) // We instantiate reader and writer types // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - + const auto input = itk::ReadImage(argv[1]); // Software Guide : BeginLatex // @@ -201,10 +193,9 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); connectedThreshold->SetInput(smoothing->GetOutput()); caster->SetInput(connectedThreshold->GetOutput()); - writer->SetInput(caster->GetOutput()); // Software Guide : EndCodeSnippet @@ -294,7 +285,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/CurvesLevelSetImageFilter.cxx b/Examples/Segmentation/CurvesLevelSetImageFilter.cxx index 9a8d6deeb46..128cc63f5e9 100644 --- a/Examples/Segmentation/CurvesLevelSetImageFilter.cxx +++ b/Examples/Segmentation/CurvesLevelSetImageFilter.cxx @@ -140,18 +140,7 @@ main(int argc, char * argv[]) thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); - - // We instantiate reader and writer types in the following lines. - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - + const auto input = itk::ReadImage(argv[1]); // The RescaleIntensityImageFilter type is declared below. This filter will // renormalize image before sending them to writers. @@ -278,7 +267,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); gradientMagnitude->SetInput(smoothing->GetOutput()); sigmoid->SetInput(gradientMagnitude->GetOutput()); @@ -286,7 +275,6 @@ main(int argc, char * argv[]) geodesicActiveContour->SetFeatureImage(sigmoid->GetOutput()); thresholder->SetInput(geodesicActiveContour->GetOutput()); - writer->SetInput(thresholder->GetOutput()); // Software Guide : EndCodeSnippet @@ -400,35 +388,22 @@ main(int argc, char * argv[]) auto caster3 = CastFilterType::New(); auto caster4 = CastFilterType::New(); - auto writer1 = WriterType::New(); - auto writer2 = WriterType::New(); - auto writer3 = WriterType::New(); - auto writer4 = WriterType::New(); - caster1->SetInput(smoothing->GetOutput()); - writer1->SetInput(caster1->GetOutput()); - writer1->SetFileName("CurvesImageFilterOutput1.png"); caster1->SetOutputMinimum(0); caster1->SetOutputMaximum(255); - writer1->Update(); + itk::WriteImage(caster1->GetOutput(), "CurvesImageFilterOutput1.png"); caster2->SetInput(gradientMagnitude->GetOutput()); - writer2->SetInput(caster2->GetOutput()); - writer2->SetFileName("CurvesImageFilterOutput2.png"); caster2->SetOutputMinimum(0); caster2->SetOutputMaximum(255); - writer2->Update(); + itk::WriteImage(caster2->GetOutput(), "CurvesImageFilterOutput2.png"); caster3->SetInput(sigmoid->GetOutput()); - writer3->SetInput(caster3->GetOutput()); - writer3->SetFileName("CurvesImageFilterOutput3.png"); caster3->SetOutputMinimum(0); caster3->SetOutputMaximum(255); - writer3->Update(); + itk::WriteImage(caster3->GetOutput(), "CurvesImageFilterOutput3.png"); caster4->SetInput(fastMarching->GetOutput()); - writer4->SetInput(caster4->GetOutput()); - writer4->SetFileName("CurvesImageFilterOutput4.png"); caster4->SetOutputMinimum(0); caster4->SetOutputMaximum(255); @@ -440,8 +415,7 @@ main(int argc, char * argv[]) // only after the \code{Update()} methods of this filter has been called // directly or indirectly. // - fastMarching->SetOutputSize( - reader->GetOutput()->GetBufferedRegion().GetSize()); + fastMarching->SetOutputSize(input->GetBufferedRegion().GetSize()); // Software Guide : BeginLatex @@ -455,7 +429,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { @@ -477,8 +451,7 @@ main(int argc, char * argv[]) std::cout << "RMS change: " << geodesicActiveContour->GetRMSChange() << std::endl; - writer4->Update(); - + itk::WriteImage(caster4->GetOutput(), "CurvesImageFilterOutput4.png"); // The following writer type is used to save the output of the time-crossing // map in a file with appropriate pixel representation. The advantage of diff --git a/Examples/Segmentation/FastMarchingImageFilter.cxx b/Examples/Segmentation/FastMarchingImageFilter.cxx index 99fa95b9505..eadf41ad8bb 100644 --- a/Examples/Segmentation/FastMarchingImageFilter.cxx +++ b/Examples/Segmentation/FastMarchingImageFilter.cxx @@ -267,23 +267,14 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // - // We instantiate reader and writer types in the following lines. + // Read the input image // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; + const auto input = itk::ReadImage(argv[1]); // Software Guide : EndCodeSnippet - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - - // The RescaleIntensityImageFilter type is declared below. This filter will // renormalize image before sending them to writers. // @@ -398,12 +389,11 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); gradientMagnitude->SetInput(smoothing->GetOutput()); sigmoid->SetInput(gradientMagnitude->GetOutput()); fastMarching->SetInput(sigmoid->GetOutput()); thresholder->SetInput(fastMarching->GetOutput()); - writer->SetInput(thresholder->GetOutput()); // Software Guide : EndCodeSnippet @@ -583,13 +573,10 @@ main(int argc, char * argv[]) try { auto caster1 = CastFilterType::New(); - auto writer1 = WriterType::New(); caster1->SetInput(smoothing->GetOutput()); - writer1->SetInput(caster1->GetOutput()); - writer1->SetFileName(argv[10]); caster1->SetOutputMinimum(0); caster1->SetOutputMaximum(255); - writer1->Update(); + itk::WriteImage(caster1->GetOutput(), argv[10]); } catch (const itk::ExceptionObject & err) { @@ -601,13 +588,10 @@ main(int argc, char * argv[]) try { auto caster2 = CastFilterType::New(); - auto writer2 = WriterType::New(); caster2->SetInput(gradientMagnitude->GetOutput()); - writer2->SetInput(caster2->GetOutput()); - writer2->SetFileName(argv[11]); caster2->SetOutputMinimum(0); caster2->SetOutputMaximum(255); - writer2->Update(); + itk::WriteImage(caster2->GetOutput(), argv[11]); } catch (const itk::ExceptionObject & err) { @@ -619,13 +603,10 @@ main(int argc, char * argv[]) try { auto caster3 = CastFilterType::New(); - auto writer3 = WriterType::New(); caster3->SetInput(sigmoid->GetOutput()); - writer3->SetInput(caster3->GetOutput()); - writer3->SetFileName(argv[12]); caster3->SetOutputMinimum(0); caster3->SetOutputMaximum(255); - writer3->Update(); + itk::WriteImage(caster3->GetOutput(), argv[12]); } catch (const itk::ExceptionObject & err) { @@ -646,8 +627,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - fastMarching->SetOutputSize( - reader->GetOutput()->GetBufferedRegion().GetSize()); + fastMarching->SetOutputSize(input->GetBufferedRegion().GetSize()); // Software Guide : EndCodeSnippet @@ -683,7 +663,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { @@ -696,13 +676,10 @@ main(int argc, char * argv[]) try { auto caster4 = CastFilterType::New(); - auto writer4 = WriterType::New(); caster4->SetInput(fastMarching->GetOutput()); - writer4->SetInput(caster4->GetOutput()); - writer4->SetFileName("FastMarchingFilterOutput4.png"); caster4->SetOutputMinimum(0); caster4->SetOutputMaximum(255); - writer4->Update(); + itk::WriteImage(caster4->GetOutput(), "FastMarchingFilterOutput4.png"); } catch (const itk::ExceptionObject & err) { diff --git a/Examples/Segmentation/GeodesicActiveContourImageFilter.cxx b/Examples/Segmentation/GeodesicActiveContourImageFilter.cxx index b42f3cffc7e..29b0afc6312 100644 --- a/Examples/Segmentation/GeodesicActiveContourImageFilter.cxx +++ b/Examples/Segmentation/GeodesicActiveContourImageFilter.cxx @@ -163,18 +163,7 @@ main(int argc, char * argv[]) thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); - - // We instantiate reader and writer types in the following lines. - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - + const auto input = itk::ReadImage(argv[1]); // The RescaleIntensityImageFilter type is declared below. This filter will // renormalize image before sending them to writers. @@ -301,7 +290,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); gradientMagnitude->SetInput(smoothing->GetOutput()); sigmoid->SetInput(gradientMagnitude->GetOutput()); @@ -309,7 +298,6 @@ main(int argc, char * argv[]) geodesicActiveContour->SetFeatureImage(sigmoid->GetOutput()); thresholder->SetInput(geodesicActiveContour->GetOutput()); - writer->SetInput(thresholder->GetOutput()); // Software Guide : EndCodeSnippet @@ -423,39 +411,28 @@ main(int argc, char * argv[]) auto caster3 = CastFilterType::New(); auto caster4 = CastFilterType::New(); - auto writer1 = WriterType::New(); - auto writer2 = WriterType::New(); - auto writer3 = WriterType::New(); - auto writer4 = WriterType::New(); - caster1->SetInput(smoothing->GetOutput()); - writer1->SetInput(caster1->GetOutput()); - writer1->SetFileName("GeodesicActiveContourImageFilterOutput1.png"); caster1->SetOutputMinimum(0); caster1->SetOutputMaximum(255); - writer1->Update(); + itk::WriteImage(caster1->GetOutput(), + "GeodesicActiveContourImageFilterOutput1.png"); caster2->SetInput(gradientMagnitude->GetOutput()); - writer2->SetInput(caster2->GetOutput()); - writer2->SetFileName("GeodesicActiveContourImageFilterOutput2.png"); caster2->SetOutputMinimum(0); caster2->SetOutputMaximum(255); - writer2->Update(); + itk::WriteImage(caster2->GetOutput(), + "GeodesicActiveContourImageFilterOutput2.png"); caster3->SetInput(sigmoid->GetOutput()); - writer3->SetInput(caster3->GetOutput()); - writer3->SetFileName("GeodesicActiveContourImageFilterOutput3.png"); caster3->SetOutputMinimum(0); caster3->SetOutputMaximum(255); - writer3->Update(); + itk::WriteImage(caster3->GetOutput(), + "GeodesicActiveContourImageFilterOutput3.png"); caster4->SetInput(fastMarching->GetOutput()); - writer4->SetInput(caster4->GetOutput()); - writer4->SetFileName("GeodesicActiveContourImageFilterOutput4.png"); caster4->SetOutputMinimum(0); caster4->SetOutputMaximum(255); - // The FastMarchingImageFilter requires the user to specify the // size of the image to be produced as output. This is done using the // \code{SetOutputSize()}. Note that the size is obtained here from the @@ -463,8 +440,7 @@ main(int argc, char * argv[]) // only after the \code{Update()} methods of this filter has been called // directly or indirectly. // - fastMarching->SetOutputSize( - reader->GetOutput()->GetBufferedRegion().GetSize()); + fastMarching->SetOutputSize(input->GetBufferedRegion().GetSize()); // Software Guide : BeginLatex @@ -478,7 +454,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { @@ -500,8 +476,8 @@ main(int argc, char * argv[]) std::cout << "RMS change: " << geodesicActiveContour->GetRMSChange() << std::endl; - writer4->Update(); - + itk::WriteImage(caster4->GetOutput(), + "GeodesicActiveContourImageFilterOutput4.png"); // The following writer type is used to save the output of the time-crossing // map in a file with appropriate pixel representation. The advantage of diff --git a/Examples/Segmentation/GeodesicActiveContourShapePriorLevelSetImageFilter.cxx b/Examples/Segmentation/GeodesicActiveContourShapePriorLevelSetImageFilter.cxx index 841e97b3f91..c07c6776f34 100644 --- a/Examples/Segmentation/GeodesicActiveContourShapePriorLevelSetImageFilter.cxx +++ b/Examples/Segmentation/GeodesicActiveContourShapePriorLevelSetImageFilter.cxx @@ -244,18 +244,7 @@ main(int argc, char * argv[]) thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); - - // We instantiate reader and writer types in the following lines. - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - + const auto input = itk::ReadImage(argv[1]); // The RescaleIntensityImageFilter type is declared below. This filter will // renormalize image before sending them to writers. @@ -418,7 +407,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - center->SetInput(reader->GetOutput()); + center->SetInput(input); smoothing->SetInput(center->GetOutput()); gradientMagnitude->SetInput(smoothing->GetOutput()); reciprocal->SetInput(gradientMagnitude->GetOutput()); @@ -427,7 +416,6 @@ main(int argc, char * argv[]) geodesicActiveContour->SetFeatureImage(reciprocal->GetOutput()); thresholder->SetInput(geodesicActiveContour->GetOutput()); - writer->SetInput(thresholder->GetOutput()); // Software Guide : EndCodeSnippet @@ -539,39 +527,25 @@ main(int argc, char * argv[]) auto caster3 = CastFilterType::New(); auto caster4 = CastFilterType::New(); - auto writer1 = WriterType::New(); - auto writer2 = WriterType::New(); - auto writer3 = WriterType::New(); - auto writer4 = WriterType::New(); - caster1->SetInput(smoothing->GetOutput()); - writer1->SetInput(caster1->GetOutput()); - writer1->SetFileName( - "GeodesicActiveContourShapePriorImageFilterOutput1.png"); caster1->SetOutputMinimum(0); caster1->SetOutputMaximum(255); - writer1->Update(); + itk::WriteImage(caster1->GetOutput(), + "GeodesicActiveContourShapePriorImageFilterOutput1.png"); caster2->SetInput(gradientMagnitude->GetOutput()); - writer2->SetInput(caster2->GetOutput()); - writer2->SetFileName( - "GeodesicActiveContourShapePriorImageFilterOutput2.png"); caster2->SetOutputMinimum(0); caster2->SetOutputMaximum(255); - writer2->Update(); + itk::WriteImage(caster2->GetOutput(), + "GeodesicActiveContourShapePriorImageFilterOutput2.png"); caster3->SetInput(reciprocal->GetOutput()); - writer3->SetInput(caster3->GetOutput()); - writer3->SetFileName( - "GeodesicActiveContourShapePriorImageFilterOutput3.png"); caster3->SetOutputMinimum(0); caster3->SetOutputMaximum(255); - writer3->Update(); + itk::WriteImage(caster3->GetOutput(), + "GeodesicActiveContourShapePriorImageFilterOutput3.png"); caster4->SetInput(fastMarching->GetOutput()); - writer4->SetInput(caster4->GetOutput()); - writer4->SetFileName( - "GeodesicActiveContourShapePriorImageFilterOutput4.png"); caster4->SetOutputMinimum(0); caster4->SetOutputMaximum(255); @@ -638,9 +612,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - auto meanShapeReader = ReaderType::New(); - meanShapeReader->SetFileName(argv[13]); - meanShapeReader->Update(); + const auto meanShapeImage = itk::ReadImage(argv[13]); std::vector shapeModeImages(numberOfPCAModes); @@ -654,13 +626,11 @@ main(int argc, char * argv[]) for (unsigned int k = 0; k < numberOfPCAModes; ++k) { - auto shapeModeReader = ReaderType::New(); - shapeModeReader->SetFileName(shapeModeFileNames[k].c_str()); - shapeModeReader->Update(); - shapeModeImages[k] = shapeModeReader->GetOutput(); + shapeModeImages[k] = + itk::ReadImage(shapeModeFileNames[k].c_str()); } - shape->SetMeanImage(meanShapeReader->GetOutput()); + shape->SetMeanImage(meanShapeImage); shape->SetPrincipalComponentImages(shapeModeImages); // Software Guide : EndCodeSnippet @@ -847,9 +817,9 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - double initRadius = 1.05; - double grow = 1.1; - double shrink = pow(grow, -0.25); + constexpr double initRadius = 1.05; + constexpr double grow = 1.1; + const double shrink = pow(grow, -0.25); optimizer->Initialize(initRadius, grow, shrink); optimizer->SetEpsilon(1.0e-6); // minimal search radius @@ -904,7 +874,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { @@ -928,7 +898,8 @@ main(int argc, char * argv[]) std::cout << "Parameters: " << geodesicActiveContour->GetCurrentParameters() << std::endl; - writer4->Update(); + itk::WriteImage(caster4->GetOutput(), + "GeodesicActiveContourShapePriorImageFilterOutput4.png"); // The following writer type is used to save the output of the time-crossing @@ -969,20 +940,19 @@ main(int argc, char * argv[]) shape->SetParameters(geodesicActiveContour->GetInitialParameters()); thresholder->SetInput(evaluator->GetOutput()); - writer->SetFileName( - "GeodesicActiveContourShapePriorImageFilterOutput5.png"); - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), + "GeodesicActiveContourShapePriorImageFilterOutput5.png"); shape->SetParameters(geodesicActiveContour->GetCurrentParameters()); evaluator->Modified(); - writer->SetFileName( - "GeodesicActiveContourShapePriorImageFilterOutput6.png"); - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), + "GeodesicActiveContourShapePriorImageFilterOutput6.png"); // Software Guide : BeginLatex // - // Deviating from previous examples, we will demonstrate this example using + // Deviating from previous examples, we will demonstrate this example + // using // \code{BrainMidSagittalSlice.png} // (Figure~\ref{fig:GeodesicActiveContourShapePriorImageFilterOutput}, // left) from the \code{Examples/Data} directory. The aim here is to @@ -991,10 +961,10 @@ main(int argc, char * argv[]) // components \code{CorpusCallosumMode0.mha}, // \code{CorpusCallosumMode1.mha} and \code{CorpusCallosumMode12.mha}. As // shown in Figure~\ref{fig:CorpusCallosumPCAModes}, the first mode - // captures scaling, the second mode captures the shifting of mass between - // the rostrum and the splenium and the third mode captures the degree of - // curvature. Segmentation results with and without shape guidance are - // shown in + // captures scaling, the second mode captures the shifting of mass + // between the rostrum and the splenium and the third mode captures the + // degree of curvature. Segmentation results with and without shape + // guidance are shown in // Figure~\ref{fig:GeodesicActiveContourShapePriorImageFilterOutput2}. // // @@ -1019,11 +989,13 @@ main(int argc, char * argv[]) // & $-3\sigma$ & mean & $+3\sigma$ \\ mode 0: & // \includegraphics[width=0.10\textwidth]{CorpusCallosumModeMinus0} & // \includegraphics[width=0.10\textwidth]{CorpusCallosumMeanShape} & - // \includegraphics[width=0.10\textwidth]{CorpusCallosumModePlus0} \\ mode - // 1: & \includegraphics[width=0.10\textwidth]{CorpusCallosumModeMinus1} & + // \includegraphics[width=0.10\textwidth]{CorpusCallosumModePlus0} + // \\ mode 1: & + // \includegraphics[width=0.10\textwidth]{CorpusCallosumModeMinus1} & // \includegraphics[width=0.10\textwidth]{CorpusCallosumMeanShape} & - // \includegraphics[width=0.10\textwidth]{CorpusCallosumModePlus1} \\ mode - // 2: & \includegraphics[width=0.10\textwidth]{CorpusCallosumModeMinus2} & + // \includegraphics[width=0.10\textwidth]{CorpusCallosumModePlus1} + // \\ mode 2: & + // \includegraphics[width=0.10\textwidth]{CorpusCallosumModeMinus2} & // \includegraphics[width=0.10\textwidth]{CorpusCallosumMeanShape} & // \includegraphics[width=0.10\textwidth]{CorpusCallosumModePlus2} // \\ \end{tabular} @@ -1047,17 +1019,19 @@ main(int argc, char * argv[]) // Figure~\ref{fig:GeodesicActiveContourShapePriorImageFilterOutput} // (right). // - // From Figure~\ref{fig:GeodesicActiveContourShapePriorImageFilterOutput2} - // it can be observed that without shape guidance (left), segmentation - // using geodesic active contour leaks in the regions where the corpus - // callosum blends into the surrounding brain tissues. With shape guidance + // From + // Figure~\ref{fig:GeodesicActiveContourShapePriorImageFilterOutput2} it + // can be observed that without shape guidance (left), segmentation using + // geodesic active contour leaks in the regions where the corpus callosum + // blends into the surrounding brain tissues. With shape guidance // (center), the segmentation is constrained by the global shape model to // prevent leaking. // // The final best-fit shape parameters after the segmentation process is: // // \begin{verbatim} - // Parameters: [-0.384988, -0.578738, 0.557793, 0.275202, 16.9992, 4.73473] + // Parameters: [-0.384988, -0.578738, 0.557793, + // 0.275202, 16.9992, 4.73473] // \end{verbatim} // // and is shown in @@ -1065,12 +1039,13 @@ main(int argc, char * argv[]) // (right). Note that a $0.28$ radian ($15.8$ degree) rotation has been // introduced to match the model to the corpus callosum in the image. // Additionally, a negative weight for the first mode shrinks the size - // relative to the mean shape. A negative weight for the second mode shifts - // the mass to splenium, and a positive weight for the third mode increases - // the curvature. It can also be observed that the final segmentation is a - // combination of the best-fit shape with additional local deformation. The - // combination of both global and local shape allows the segmentation to - // capture fine details not represented in the shape model. + // relative to the mean shape. A negative weight for the second mode + // shifts the mass to splenium, and a positive weight for the third mode + // increases the curvature. It can also be observed that the final + // segmentation is a combination of the best-fit shape with additional + // local deformation. The combination of both global and local shape + // allows the segmentation to capture fine details not represented in the + // shape model. // // // \begin{figure} \center diff --git a/Examples/Segmentation/GibbsPriorImageFilter1.cxx b/Examples/Segmentation/GibbsPriorImageFilter1.cxx index 4cb22167679..4a3d4e29a29 100644 --- a/Examples/Segmentation/GibbsPriorImageFilter1.cxx +++ b/Examples/Segmentation/GibbsPriorImageFilter1.cxx @@ -92,29 +92,16 @@ main(int argc, char * argv[]) using ClassImageType = itk::Image; // Software Guide : EndCodeSnippet - - // We instantiate reader and writer types - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto inputimagereader = ReaderType::New(); - auto trainingimagereader = ReaderType::New(); - auto writer = WriterType::New(); - - inputimagereader->SetFileName(argv[1]); - trainingimagereader->SetFileName(argv[2]); - writer->SetFileName(argv[3]); - + const auto input_image = itk::ReadImage(argv[1]); + const auto training_image = itk::ReadImage(argv[2]); // We convert the input into vector images // auto vecImage = VecImageType::New(); using VecImagePixelType = VecImageType::PixelType; - VecImageType::SizeType vecImgSize = { { 181, 217, 1 } }; + constexpr VecImageType::SizeType vecImgSize = { { 181, 217, 1 } }; - VecImageType::IndexType index; - index.Fill(0); + constexpr VecImageType::IndexType index{}; VecImageType::RegionType region; @@ -134,13 +121,9 @@ main(int argc, char * argv[]) VecIterator vecIt(vecImage, vecImage->GetBufferedRegion()); vecIt.GoToBegin(); - inputimagereader->Update(); - trainingimagereader->Update(); - using ClassIterator = itk::ImageRegionIterator; - ClassIterator inputIt(inputimagereader->GetOutput(), - inputimagereader->GetOutput()->GetBufferedRegion()); + ClassIterator inputIt(input_image, input_image->GetBufferedRegion()); inputIt.GoToBegin(); // Set up the vector to store the image data @@ -182,7 +165,7 @@ main(int argc, char * argv[]) applyEstimateModel->SetNumberOfModels(NUM_CLASSES); applyEstimateModel->SetInputImage(vecImage); - applyEstimateModel->SetTrainingImage(trainingimagereader->GetOutput()); + applyEstimateModel->SetTrainingImage(training_image); // Run the gaussian classifier algorithm @@ -225,7 +208,7 @@ main(int argc, char * argv[]) using ClassifierType = itk::ImageClassifierBase; using ClassifierPointer = ClassifierType::Pointer; - ClassifierPointer myClassifier = ClassifierType::New(); + const ClassifierPointer myClassifier = ClassifierType::New(); // Software Guide : EndCodeSnippet // Set the Classifier parameters @@ -285,7 +268,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet applyGibbsImageFilter->SetInput(vecImage); applyGibbsImageFilter->SetClassifier(myClassifier); - applyGibbsImageFilter->SetTrainingImage(trainingimagereader->GetOutput()); + applyGibbsImageFilter->SetTrainingImage(training_image); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -300,8 +283,7 @@ main(int argc, char * argv[]) std::cout << "applyGibbsImageFilter: " << applyGibbsImageFilter; - writer->SetInput(applyGibbsImageFilter->GetOutput()); - writer->Update(); + itk::WriteImage(applyGibbsImageFilter->GetOutput(), argv[3]); // Software Guide : BeginLatex // diff --git a/Examples/Segmentation/HoughTransform2DCirclesImageFilter.cxx b/Examples/Segmentation/HoughTransform2DCirclesImageFilter.cxx index e8049817c1e..d3d20a5cfee 100644 --- a/Examples/Segmentation/HoughTransform2DCirclesImageFilter.cxx +++ b/Examples/Segmentation/HoughTransform2DCirclesImageFilter.cxx @@ -88,12 +88,10 @@ main(int argc, char * argv[]) // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - using ReaderType = itk::ImageFileReader; - auto reader = ReaderType::New(); - reader->SetFileName(argv[1]); + ImageType::Pointer localImage; try { - reader->Update(); + localImage = itk::ReadImage(argv[1]); } catch (const itk::ExceptionObject & excep) { @@ -101,7 +99,6 @@ main(int argc, char * argv[]) std::cerr << excep << std::endl; return EXIT_FAILURE; } - ImageType::Pointer localImage = reader->GetOutput(); // Software Guide : EndCodeSnippet @@ -146,7 +143,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - houghFilter->SetInput(reader->GetOutput()); + houghFilter->SetInput(localImage); houghFilter->SetNumberOfCircles(std::stoi(argv[3])); houghFilter->SetMinimumRadius(std::stod(argv[4])); @@ -170,7 +167,8 @@ main(int argc, char * argv[]) } houghFilter->Update(); - AccumulatorImageType::Pointer localAccumulator = houghFilter->GetOutput(); + const AccumulatorImageType::Pointer localAccumulator = + houghFilter->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -245,7 +243,7 @@ main(int argc, char * argv[]) localIndex[1] = itk::Math::Round( centerPoint[1] + (*itCircles)->GetRadiusInObjectSpace()[0] * std::sin(angle)); - OutputImageType::RegionType outputRegion = + const OutputImageType::RegionType outputRegion = localOutputImage->GetLargestPossibleRegion(); if (outputRegion.IsInside(localIndex)) @@ -253,7 +251,7 @@ main(int argc, char * argv[]) localOutputImage->SetPixel(localIndex, 255); } } - itCircles++; + ++itCircles; } // Software Guide : EndCodeSnippet @@ -264,15 +262,10 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - using WriterType = itk::ImageFileWriter; - auto writer = WriterType::New(); - - writer->SetFileName(argv[2]); - writer->SetInput(localOutputImage); try { - writer->Update(); + itk::WriteImage(localOutputImage, argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/HoughTransform2DLinesImageFilter.cxx b/Examples/Segmentation/HoughTransform2DLinesImageFilter.cxx index 60b79086059..54ebd06a480 100644 --- a/Examples/Segmentation/HoughTransform2DLinesImageFilter.cxx +++ b/Examples/Segmentation/HoughTransform2DLinesImageFilter.cxx @@ -82,13 +82,10 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - using ReaderType = itk::ImageFileReader; - auto reader = ReaderType::New(); - - reader->SetFileName(argv[1]); + ImageType::Pointer localImage; try { - reader->Update(); + localImage = itk::ReadImage(argv[1]); } catch (const itk::ExceptionObject & excep) { @@ -96,7 +93,6 @@ main(int argc, char * argv[]) std::cerr << excep << std::endl; return EXIT_FAILURE; } - ImageType::Pointer localImage = reader->GetOutput(); // Software Guide : EndCodeSnippet @@ -141,8 +137,8 @@ main(int argc, char * argv[]) threshFilter->SetInput(gradFilter->GetOutput()); threshFilter->SetOutsideValue(0); - unsigned char threshBelow = 0; - unsigned char threshAbove = 255; + constexpr unsigned char threshBelow = 0; + constexpr unsigned char threshAbove = 255; threshFilter->ThresholdOutside(threshBelow, threshAbove); threshFilter->Update(); // Software Guide : EndCodeSnippet @@ -189,7 +185,8 @@ main(int argc, char * argv[]) houghFilter->SetDiscRadius(std::stod(argv[5])); } houghFilter->Update(); - AccumulatorImageType::Pointer localAccumulator = houghFilter->GetOutput(); + const AccumulatorImageType::Pointer localAccumulator = + houghFilter->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -218,7 +215,8 @@ main(int argc, char * argv[]) auto localOutputImage = OutputImageType::New(); - OutputImageType::RegionType region(localImage->GetLargestPossibleRegion()); + const OutputImageType::RegionType region( + localImage->GetLargestPossibleRegion()); localOutputImage->SetRegions(region); localOutputImage->CopyInformation(localImage); localOutputImage->Allocate(true); // initialize buffer to zero @@ -257,12 +255,12 @@ main(int argc, char * argv[]) double u[2]; u[0] = (*itPoints).GetPositionInObjectSpace()[0]; u[1] = (*itPoints).GetPositionInObjectSpace()[1]; - itPoints++; + ++itPoints; double v[2]; v[0] = u[0] - (*itPoints).GetPositionInObjectSpace()[0]; v[1] = u[1] - (*itPoints).GetPositionInObjectSpace()[1]; - double norm = std::sqrt(v[0] * v[0] + v[1] * v[1]); + const double norm = std::sqrt(v[0] * v[0] + v[1] * v[1]); v[0] /= norm; v[1] /= norm; // Software Guide : EndCodeSnippet @@ -277,7 +275,7 @@ main(int argc, char * argv[]) ImageType::IndexType localIndex; itk::Size<2> size = localOutputImage->GetLargestPossibleRegion().GetSize(); - float diag = + const float diag = std::sqrt(static_cast(size[0] * size[0] + size[1] * size[1])); for (auto i = static_cast(-diag); i < static_cast(diag); ++i) @@ -285,7 +283,7 @@ main(int argc, char * argv[]) localIndex[0] = static_cast(u[0] + i * v[0]); localIndex[1] = static_cast(u[1] + i * v[1]); - OutputImageType::RegionType outputRegion = + const OutputImageType::RegionType outputRegion = localOutputImage->GetLargestPossibleRegion(); if (outputRegion.IsInside(localIndex)) @@ -293,7 +291,7 @@ main(int argc, char * argv[]) localOutputImage->SetPixel(localIndex, 255); } } - itLines++; + ++itLines; } // Software Guide : EndCodeSnippet @@ -304,14 +302,10 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - using WriterType = itk::ImageFileWriter; - auto writer = WriterType::New(); - writer->SetFileName(argv[2]); - writer->SetInput(localOutputImage); try { - writer->Update(); + itk::WriteImage(localOutputImage, argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/IsolatedConnectedImageFilter.cxx b/Examples/Segmentation/IsolatedConnectedImageFilter.cxx index 39031d765b8..aa78cc972f8 100644 --- a/Examples/Segmentation/IsolatedConnectedImageFilter.cxx +++ b/Examples/Segmentation/IsolatedConnectedImageFilter.cxx @@ -92,18 +92,7 @@ main(int argc, char * argv[]) auto caster = CastingFilterType::New(); - - // We instantiate reader and writer types - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - + const auto input = itk::ReadImage(argv[1]); using CurvatureFlowImageFilterType = itk::CurvatureFlowImageFilter; @@ -141,10 +130,9 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); isolatedConnected->SetInput(smoothing->GetOutput()); caster->SetInput(isolatedConnected->GetOutput()); - writer->SetInput(caster->GetOutput()); // Software Guide : EndCodeSnippet @@ -211,7 +199,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/LaplacianSegmentationLevelSetImageFilter.cxx b/Examples/Segmentation/LaplacianSegmentationLevelSetImageFilter.cxx index 5f02be25f59..423fc474c5a 100644 --- a/Examples/Segmentation/LaplacianSegmentationLevelSetImageFilter.cxx +++ b/Examples/Segmentation/LaplacianSegmentationLevelSetImageFilter.cxx @@ -125,16 +125,8 @@ main(int argc, char * argv[]) thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader1 = ReaderType::New(); - auto reader2 = ReaderType::New(); - auto writer = WriterType::New(); - - reader1->SetFileName(argv[1]); - reader2->SetFileName(argv[2]); - writer->SetFileName(argv[3]); + const auto input1 = itk::ReadImage(argv[1]); + const auto input2 = itk::ReadImage(argv[2]); // Software Guide : BeginLatex // @@ -166,7 +158,7 @@ main(int argc, char * argv[]) using LaplacianSegmentationLevelSetImageFilterType = itk::LaplacianSegmentationLevelSetImageFilter; - LaplacianSegmentationLevelSetImageFilterType::Pointer + const LaplacianSegmentationLevelSetImageFilterType::Pointer laplacianSegmentation = LaplacianSegmentationLevelSetImageFilterType::New(); // Software Guide : EndCodeSnippet @@ -223,11 +215,10 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - diffusion->SetInput(reader1->GetOutput()); - laplacianSegmentation->SetInput(reader2->GetOutput()); + diffusion->SetInput(input1); + laplacianSegmentation->SetInput(input2); laplacianSegmentation->SetFeatureImage(diffusion->GetOutput()); thresholder->SetInput(laplacianSegmentation->GetOutput()); - writer->SetInput(thresholder->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -241,7 +232,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), argv[3]); } catch (const itk::ExceptionObject & excep) { @@ -264,8 +255,7 @@ main(int argc, char * argv[]) << std::endl; // Write out the speed (propagation) image for parameter tuning purposes. - itk::ImageFileWriter::Pointer speedWriter = - itk::ImageFileWriter::New(); + auto speedWriter = itk::ImageFileWriter::New(); speedWriter->SetInput(laplacianSegmentation->GetSpeedImage()); speedWriter->SetFileName("speedImage.mha"); speedWriter->Update(); diff --git a/Examples/Segmentation/NeighborhoodConnectedImageFilter.cxx b/Examples/Segmentation/NeighborhoodConnectedImageFilter.cxx index f3dfd7b9863..c26049fff24 100644 --- a/Examples/Segmentation/NeighborhoodConnectedImageFilter.cxx +++ b/Examples/Segmentation/NeighborhoodConnectedImageFilter.cxx @@ -101,15 +101,8 @@ main(int argc, char * argv[]) // We instantiate reader and writer types // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); + const auto input = itk::ReadImage(argv[1]); // Software Guide : BeginLatex // @@ -171,10 +164,9 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); neighborhoodConnected->SetInput(smoothing->GetOutput()); caster->SetInput(neighborhoodConnected->GetOutput()); - writer->SetInput(caster->GetOutput()); // Software Guide : EndCodeSnippet @@ -270,7 +262,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(caster->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/RelabelComponentImageFilter.cxx b/Examples/Segmentation/RelabelComponentImageFilter.cxx index c3d44d4506c..e4225484bbc 100644 --- a/Examples/Segmentation/RelabelComponentImageFilter.cxx +++ b/Examples/Segmentation/RelabelComponentImageFilter.cxx @@ -71,15 +71,7 @@ main(int argc, char * argv[]) using OutputImageType = itk::Image; // Software Guide : EndCodeSnippet - - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); + const auto input = itk::ReadImage(argv[1]); // Software Guide : BeginLatex // @@ -114,9 +106,8 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet - relabeler->SetInput(reader->GetOutput()); - writer->SetInput(relabeler->GetOutput()); - writer->Update(); + relabeler->SetInput(input); + itk::WriteImage(relabeler->GetOutput(), argv[2]); // Software Guide : EndCodeSnippet diff --git a/Examples/Segmentation/ShapeDetectionLevelSetFilter.cxx b/Examples/Segmentation/ShapeDetectionLevelSetFilter.cxx index 1d184396bc9..a0710fc87be 100644 --- a/Examples/Segmentation/ShapeDetectionLevelSetFilter.cxx +++ b/Examples/Segmentation/ShapeDetectionLevelSetFilter.cxx @@ -245,17 +245,7 @@ main(int argc, char * argv[]) // Software Guide : EndCodeSnippet - // We instantiate reader and writer types in the following lines. - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(inputImageFile); - writer->SetFileName(outputImageFile); - + const auto input = itk::ReadImage(inputImageFile); // The RescaleIntensityImageFilter type is declared below. This filter will // renormalize image before sending them to writers. @@ -389,7 +379,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - smoothing->SetInput(reader->GetOutput()); + smoothing->SetInput(input); gradientMagnitude->SetInput(smoothing->GetOutput()); sigmoid->SetInput(gradientMagnitude->GetOutput()); @@ -397,8 +387,6 @@ main(int argc, char * argv[]) shapeDetection->SetFeatureImage(sigmoid->GetOutput()); thresholder->SetInput(shapeDetection->GetOutput()); - - writer->SetInput(thresholder->GetOutput()); // Software Guide : EndCodeSnippet @@ -572,37 +560,27 @@ main(int argc, char * argv[]) auto caster3 = CastFilterType::New(); auto caster4 = CastFilterType::New(); - auto writer1 = WriterType::New(); - auto writer2 = WriterType::New(); - auto writer3 = WriterType::New(); - auto writer4 = WriterType::New(); - const std::string outputImageFilePrefix = itksys::SystemTools::GetFilenameWithoutExtension(outputImageFile); caster1->SetInput(smoothing->GetOutput()); - writer1->SetInput(caster1->GetOutput()); - writer1->SetFileName(outputImageFilePrefix + "Smoothing.png"); caster1->SetOutputMinimum(0); caster1->SetOutputMaximum(255); - writer1->Update(); + itk::WriteImage(caster1->GetOutput(), + outputImageFilePrefix + "Smoothing.png"); caster2->SetInput(gradientMagnitude->GetOutput()); - writer2->SetInput(caster2->GetOutput()); - writer2->SetFileName(outputImageFilePrefix + "GradientMagnitude.png"); caster2->SetOutputMinimum(0); caster2->SetOutputMaximum(255); - writer2->Update(); + itk::WriteImage(caster2->GetOutput(), + outputImageFilePrefix + "GradientMagnitude.png"); caster3->SetInput(sigmoid->GetOutput()); - writer3->SetInput(caster3->GetOutput()); - writer3->SetFileName(outputImageFilePrefix + "Sigmoid.png"); caster3->SetOutputMinimum(0); caster3->SetOutputMaximum(255); - writer3->Update(); + itk::WriteImage(caster3->GetOutput(), + outputImageFilePrefix + "Sigmoid.png"); caster4->SetInput(fastMarching->GetOutput()); - writer4->SetInput(caster4->GetOutput()); - writer4->SetFileName(outputImageFilePrefix + "FastMarching.png"); caster4->SetOutputMinimum(0); caster4->SetOutputMaximum(255); @@ -619,8 +597,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - fastMarching->SetOutputSize( - reader->GetOutput()->GetBufferedRegion().GetSize()); + fastMarching->SetOutputSize(input->GetBufferedRegion().GetSize()); // Software Guide : EndCodeSnippet @@ -691,7 +668,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), outputImageFile); } catch (const itk::ExceptionObject & excep) { @@ -712,14 +689,15 @@ main(int argc, char * argv[]) << shapeDetection->GetElapsedIterations() << std::endl; std::cout << "RMS change: " << shapeDetection->GetRMSChange() << std::endl; - writer4->Update(); + itk::WriteImage(caster4->GetOutput(), + outputImageFilePrefix + "FastMarching.png"); - // The following writer type is used to save the output of the time-crossing - // map in a file with appropriate pixel representation. The advantage of - // saving this image in native format is that it can be used with a viewer - // to help determine an appropriate threshold to be used on the output of - // the fastmarching filter. + // The following writer type is used to save the output of the + // time-crossing map in a file with appropriate pixel representation. The + // advantage of saving this image in native format is that it can be used + // with a viewer to help determine an appropriate threshold to be used on + // the output of the fastmarching filter. // using InternalWriterType = itk::ImageFileWriter; diff --git a/Examples/Segmentation/ThresholdSegmentationLevelSetImageFilter.cxx b/Examples/Segmentation/ThresholdSegmentationLevelSetImageFilter.cxx index 132e5287047..28228af19d5 100644 --- a/Examples/Segmentation/ThresholdSegmentationLevelSetImageFilter.cxx +++ b/Examples/Segmentation/ThresholdSegmentationLevelSetImageFilter.cxx @@ -146,15 +146,7 @@ main(int argc, char * argv[]) thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); - + const auto input = itk::ReadImage(argv[1]); // We now declare the type of the \doxygen{FastMarchingImageFilter} that // will be used to generate the initial level set in the form of a distance @@ -176,7 +168,7 @@ main(int argc, char * argv[]) using ThresholdSegmentationLevelSetImageFilterType = itk::ThresholdSegmentationLevelSetImageFilter; - ThresholdSegmentationLevelSetImageFilterType::Pointer + const ThresholdSegmentationLevelSetImageFilterType::Pointer thresholdSegmentation = ThresholdSegmentationLevelSetImageFilterType::New(); // Software Guide : EndCodeSnippet @@ -252,9 +244,8 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet thresholdSegmentation->SetInput(fastMarching->GetOutput()); - thresholdSegmentation->SetFeatureImage(reader->GetOutput()); + thresholdSegmentation->SetFeatureImage(input); thresholder->SetInput(thresholdSegmentation->GetOutput()); - writer->SetInput(thresholder->GetOutput()); // Software Guide : EndCodeSnippet // @@ -340,13 +331,12 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - reader->Update(); - const InternalImageType * inputImage = reader->GetOutput(); + const auto inputImage = itk::ReadImage(argv[1]); fastMarching->SetOutputRegion(inputImage->GetBufferedRegion()); fastMarching->SetOutputSpacing(inputImage->GetSpacing()); fastMarching->SetOutputOrigin(inputImage->GetOrigin()); fastMarching->SetOutputDirection(inputImage->GetDirection()); - writer->Update(); + itk::WriteImage(thresholder->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { @@ -372,17 +362,10 @@ main(int argc, char * argv[]) // We write out some intermediate images for debugging. These images can // help tune parameters. // - using InternalWriterType = itk::ImageFileWriter; - - auto mapWriter = InternalWriterType::New(); - mapWriter->SetInput(fastMarching->GetOutput()); - mapWriter->SetFileName("fastMarchingImage.mha"); - mapWriter->Update(); - auto speedWriter = InternalWriterType::New(); - speedWriter->SetInput(thresholdSegmentation->GetSpeedImage()); - speedWriter->SetFileName("speedTermImage.mha"); - speedWriter->Update(); + itk::WriteImage(fastMarching->GetOutput(), "fastMarchingImage.mha"); + itk::WriteImage(thresholdSegmentation->GetSpeedImage(), + "speedTermImage.mha"); // Software Guide : BeginLatex // diff --git a/Examples/Segmentation/VectorConfidenceConnected.cxx b/Examples/Segmentation/VectorConfidenceConnected.cxx index ad450cdbec1..e105ef38bf8 100644 --- a/Examples/Segmentation/VectorConfidenceConnected.cxx +++ b/Examples/Segmentation/VectorConfidenceConnected.cxx @@ -91,16 +91,8 @@ main(int argc, char * argv[]) using OutputImageType = itk::Image; - // We instantiate reader and writer types - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); + const auto input = itk::ReadImage(argv[1]); - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); // Software Guide : BeginLatex // @@ -134,8 +126,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - confidenceConnected->SetInput(reader->GetOutput()); - writer->SetInput(confidenceConnected->GetOutput()); + confidenceConnected->SetInput(input); // Software Guide : EndCodeSnippet @@ -252,7 +243,7 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet try { - writer->Update(); + itk::WriteImage(confidenceConnected->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/Segmentation/WatershedSegmentation1.cxx b/Examples/Segmentation/WatershedSegmentation1.cxx index 88f187f45d0..542ede91c86 100644 --- a/Examples/Segmentation/WatershedSegmentation1.cxx +++ b/Examples/Segmentation/WatershedSegmentation1.cxx @@ -105,7 +105,6 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - using FileReaderType = itk::ImageFileReader; using CastFilterType = itk::CastImageFilter; using DiffusionFilterType = itk::VectorGradientAnisotropicDiffusionImageFilter; // Software Guide : EndCodeSnippet - using FileWriterType = itk::ImageFileWriter; - - auto reader = FileReaderType::New(); - reader->SetFileName(argv[1]); + const auto input = itk::ReadImage(argv[1]); auto caster = CastFilterType::New(); @@ -199,9 +195,6 @@ main(int argc, char * argv[]) // Software Guide : EndCodeSnippet - auto writer = FileWriterType::New(); - writer->SetFileName(argv[2]); - // Software Guide : BeginLatex // // The filters are connected into a single pipeline, with readers and @@ -210,17 +203,16 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - caster->SetInput(reader->GetOutput()); + caster->SetInput(input); diffusion->SetInput(caster->GetOutput()); gradient->SetInput(diffusion->GetOutput()); watershed->SetInput(gradient->GetOutput()); colormapper->SetInput(watershed->GetOutput()); - writer->SetInput(colormapper->GetOutput()); // Software Guide : EndCodeSnippet try { - writer->Update(); + itk::WriteImage(colormapper->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & e) { diff --git a/Examples/Segmentation/WatershedSegmentation2.cxx b/Examples/Segmentation/WatershedSegmentation2.cxx index 9bc96270382..c1583a27863 100644 --- a/Examples/Segmentation/WatershedSegmentation2.cxx +++ b/Examples/Segmentation/WatershedSegmentation2.cxx @@ -55,17 +55,7 @@ main(int argc, char * argv[]) using RGBImageType = itk::Image; - // - // We instantiate reader and writer types - // - using ReaderType = itk::ImageFileReader; - using WriterType = itk::ImageFileWriter; - - auto reader = ReaderType::New(); - auto writer = WriterType::New(); - - reader->SetFileName(argv[1]); - writer->SetFileName(argv[2]); + const auto input = itk::ReadImage(argv[1]); // @@ -77,7 +67,7 @@ main(int argc, char * argv[]) auto gradienMagnitudeFilter = GradientMagnitudeFilterType::New(); - gradienMagnitudeFilter->SetInput(reader->GetOutput()); + gradienMagnitudeFilter->SetInput(input); gradienMagnitudeFilter->SetSigma(1.0); @@ -114,11 +104,9 @@ main(int argc, char * argv[]) colorMapFilter->SetInput(watershedFilter->GetOutput()); - writer->SetInput(colorMapFilter->GetOutput()); - try { - writer->Update(); + itk::WriteImage(colorMapFilter->GetOutput(), argv[2]); } catch (const itk::ExceptionObject & excep) { diff --git a/Examples/SpatialObjects/ArrowSpatialObject.cxx b/Examples/SpatialObjects/ArrowSpatialObject.cxx index 074c05658f5..eb4824238ab 100644 --- a/Examples/SpatialObjects/ArrowSpatialObject.cxx +++ b/Examples/SpatialObjects/ArrowSpatialObject.cxx @@ -54,8 +54,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ArrowType::PointType pos; - pos.Fill(1); + auto pos = itk::MakeFilled(1); myArrow->SetPositionInObjectSpace(pos); // Software Guide : EndCodeSnippet @@ -83,8 +82,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ArrowType::VectorType direction; - direction.Fill(0); + ArrowType::VectorType direction{}; direction[1] = 1.0; myArrow->SetDirectionInObjectSpace(direction); // Software Guide : EndCodeSnippet diff --git a/Examples/SpatialObjects/BlobSpatialObject.cxx b/Examples/SpatialObjects/BlobSpatialObject.cxx index b0de29ebc88..2e5ba9ffec7 100644 --- a/Examples/SpatialObjects/BlobSpatialObject.cxx +++ b/Examples/SpatialObjects/BlobSpatialObject.cxx @@ -106,7 +106,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - BlobPointer blob = BlobType::New(); + const BlobPointer blob = BlobType::New(); blob->GetProperty().SetName("My Blob"); blob->SetId(1); blob->SetPoints(list); @@ -121,7 +121,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - BlobType::BlobPointListType pointList = blob->GetPoints(); + const BlobType::BlobPointListType pointList = blob->GetPoints(); std::cout << "The blob contains " << pointList.size(); std::cout << " points" << std::endl; // Software Guide : EndCodeSnippet diff --git a/Examples/SpatialObjects/BoundingBoxFromImageMaskSpatialObject.cxx b/Examples/SpatialObjects/BoundingBoxFromImageMaskSpatialObject.cxx index 68936a4f591..37eef2b991d 100644 --- a/Examples/SpatialObjects/BoundingBoxFromImageMaskSpatialObject.cxx +++ b/Examples/SpatialObjects/BoundingBoxFromImageMaskSpatialObject.cxx @@ -36,8 +36,10 @@ #include "itkImageFileReader.h" +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 2) @@ -51,25 +53,13 @@ main(int argc, char * argv[]) using ImageMaskSpatialObject = itk::ImageMaskSpatialObject<3>; using ImageType = ImageMaskSpatialObject::ImageType; - using ReaderType = itk::ImageFileReader; - - auto reader = ReaderType::New(); + ImageType::Pointer input; + input = itk::ReadImage(argv[1]); - reader->SetFileName(argv[1]); - - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } auto maskSO = ImageMaskSpatialObject::New(); - maskSO->SetImage(reader->GetOutput()); + maskSO->SetImage(input); maskSO->Update(); std::cout << "Bounding Box Region: " @@ -78,3 +68,26 @@ main(int argc, char * argv[]) return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/SpatialObjects/DTITubeSpatialObject.cxx b/Examples/SpatialObjects/DTITubeSpatialObject.cxx index fb4d923099f..8eb559f349d 100644 --- a/Examples/SpatialObjects/DTITubeSpatialObject.cxx +++ b/Examples/SpatialObjects/DTITubeSpatialObject.cxx @@ -133,7 +133,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - DTITubeType::DTITubePointListType pointList = dtiTube->GetPoints(); + const DTITubeType::DTITubePointListType pointList = dtiTube->GetPoints(); std::cout << "Number of points representing the fiber tract: "; std::cout << pointList.size() << std::endl; // Software Guide : EndCodeSnippet diff --git a/Examples/SpatialObjects/EllipseSpatialObject.cxx b/Examples/SpatialObjects/EllipseSpatialObject.cxx index 858377b1c91..999db901d40 100644 --- a/Examples/SpatialObjects/EllipseSpatialObject.cxx +++ b/Examples/SpatialObjects/EllipseSpatialObject.cxx @@ -83,7 +83,7 @@ main(int, char *[]) // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - EllipseType::ArrayType myCurrentRadius = + const EllipseType::ArrayType myCurrentRadius = myEllipse->GetRadiusInObjectSpace(); std::cout << "Current radius is " << myCurrentRadius << std::endl; // Software Guide : EndCodeSnippet @@ -97,16 +97,14 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - itk::Point insidePoint; - insidePoint.Fill(1.0); + auto insidePoint = itk::MakeFilled>(1.0); if (myEllipse->IsInsideInWorldSpace(insidePoint)) { std::cout << "The point " << insidePoint; std::cout << " is really inside the ellipse" << std::endl; } - itk::Point outsidePoint; - outsidePoint.Fill(3.0); + auto outsidePoint = itk::MakeFilled>(3.0); if (!myEllipse->IsInsideInWorldSpace(outsidePoint)) { std::cout << "The point " << outsidePoint; diff --git a/Examples/SpatialObjects/GroupSpatialObject.cxx b/Examples/SpatialObjects/GroupSpatialObject.cxx index 636ca5dc899..a909c8904e9 100644 --- a/Examples/SpatialObjects/GroupSpatialObject.cxx +++ b/Examples/SpatialObjects/GroupSpatialObject.cxx @@ -72,8 +72,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - GroupType::VectorType offset; - offset.Fill(10); + auto offset = itk::MakeFilled(10); myGroup->GetModifiableObjectToParentTransform()->SetOffset(offset); myGroup->Update(); // Software Guide : EndCodeSnippet @@ -88,8 +87,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - GroupType::PointType point; - point.Fill(10); + auto point = itk::MakeFilled(10); std::cout << "Is my point " << point << " inside?: " << myGroup->IsInsideInWorldSpace(point, 2) << std::endl; diff --git a/Examples/SpatialObjects/ImageMaskSpatialObject.cxx b/Examples/SpatialObjects/ImageMaskSpatialObject.cxx index fc1f919976d..ec8b8ba5c94 100644 --- a/Examples/SpatialObjects/ImageMaskSpatialObject.cxx +++ b/Examples/SpatialObjects/ImageMaskSpatialObject.cxx @@ -67,10 +67,10 @@ main(int, char *[]) using ImageType = ImageMaskSpatialObject::ImageType; using Iterator = itk::ImageRegionIterator; - auto image = ImageType::New(); - ImageType::SizeType size = { { 50, 50, 50 } }; - ImageType::IndexType index = { { 0, 0, 0 } }; - ImageType::RegionType region; + auto image = ImageType::New(); + constexpr ImageType::SizeType size = { { 50, 50, 50 } }; + constexpr ImageType::IndexType index = { { 0, 0, 0 } }; + ImageType::RegionType region; region.SetSize(size); region.SetIndex(index); @@ -78,9 +78,9 @@ main(int, char *[]) image->SetRegions(region); image->Allocate(true); // initialize buffer to zero - ImageType::RegionType insideRegion; - ImageType::SizeType insideSize = { { 30, 30, 30 } }; - ImageType::IndexType insideIndex = { { 10, 10, 10 } }; + ImageType::RegionType insideRegion; + constexpr ImageType::SizeType insideSize = { { 30, 30, 30 } }; + constexpr ImageType::IndexType insideIndex = { { 10, 10, 10 } }; insideRegion.SetSize(insideSize); insideRegion.SetIndex(insideIndex); @@ -124,12 +124,10 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ImageMaskSpatialObject::PointType inside; - inside.Fill(20); + auto inside = itk::MakeFilled(20); std::cout << "Is my point " << inside << " inside my mask? " << maskSO->IsInsideInWorldSpace(inside) << std::endl; - ImageMaskSpatialObject::PointType outside; - outside.Fill(45); + auto outside = itk::MakeFilled(45); std::cout << "Is my point " << outside << " outside my mask? " << !maskSO->IsInsideInWorldSpace(outside) << std::endl; // Software Guide : EndCodeSnippet diff --git a/Examples/SpatialObjects/ImageSpatialObject.cxx b/Examples/SpatialObjects/ImageSpatialObject.cxx index 3efbc223dca..76c03680e38 100644 --- a/Examples/SpatialObjects/ImageSpatialObject.cxx +++ b/Examples/SpatialObjects/ImageSpatialObject.cxx @@ -43,9 +43,9 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using Image = itk::Image; - auto image = Image::New(); - Image::SizeType size = { { 10, 10 } }; - Image::RegionType region; + auto image = Image::New(); + constexpr Image::SizeType size = { { 10, 10 } }; + Image::RegionType region; region.SetSize(size); image->SetRegions(region); image->Allocate(); @@ -105,8 +105,7 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet using Point = itk::Point; - Point insidePoint; - insidePoint.Fill(9); + auto insidePoint = itk::MakeFilled(9); if (imageSO->IsInsideInWorldSpace(insidePoint)) { diff --git a/Examples/SpatialObjects/LandmarkSpatialObject.cxx b/Examples/SpatialObjects/LandmarkSpatialObject.cxx index 7d83cedd76d..243e86409f0 100644 --- a/Examples/SpatialObjects/LandmarkSpatialObject.cxx +++ b/Examples/SpatialObjects/LandmarkSpatialObject.cxx @@ -47,7 +47,7 @@ main(int, char *[]) using LandmarkPointType = LandmarkType::LandmarkPointType; using PointType = LandmarkType::PointType; - LandmarkPointer landmark = LandmarkType::New(); + const LandmarkPointer landmark = LandmarkType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // @@ -104,7 +104,7 @@ main(int, char *[]) // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - size_t nPoints = landmark->GetPoints().size(); + const size_t nPoints = landmark->GetPoints().size(); std::cout << "Number of Points in the landmark: " << nPoints << std::endl; LandmarkType::LandmarkPointListType::const_iterator it = diff --git a/Examples/SpatialObjects/LineSpatialObject.cxx b/Examples/SpatialObjects/LineSpatialObject.cxx index 1b877d3a9f9..d2a07363569 100644 --- a/Examples/SpatialObjects/LineSpatialObject.cxx +++ b/Examples/SpatialObjects/LineSpatialObject.cxx @@ -53,7 +53,7 @@ main(int, char *[]) using PointType = LineType::PointType; using CovariantVectorType = LineType::CovariantVectorType; - LinePointer Line = LineType::New(); + const LinePointer Line = LineType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -119,7 +119,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - LineType::LinePointListType pointList = Line->GetPoints(); + const LineType::LinePointListType pointList = Line->GetPoints(); std::cout << "Number of points representing the line: "; std::cout << pointList.size() << std::endl; // Software Guide : EndCodeSnippet diff --git a/Examples/SpatialObjects/MeshSpatialObject.cxx b/Examples/SpatialObjects/MeshSpatialObject.cxx index d1289838942..4dcc43ba58b 100644 --- a/Examples/SpatialObjects/MeshSpatialObject.cxx +++ b/Examples/SpatialObjects/MeshSpatialObject.cxx @@ -63,14 +63,12 @@ main(int, char *[]) // Software Guide : BeginCodeSnippet auto myMesh = MeshType::New(); - MeshType::CoordRepType testPointCoords[4][3] = { + constexpr MeshType::CoordinateType testPointCoords[4][3] = { { 0, 0, 0 }, { 9, 0, 0 }, { 9, 9, 0 }, { 0, 0, 9 } }; MeshType::PointIdentifier tetraPoints[4] = { 0, 1, 2, 4 }; - - int i; - for (i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { myMesh->SetPoint(i, PointType(testPointCoords[i])); } @@ -134,8 +132,7 @@ main(int, char *[]) << "Mesh bounds : " << myMeshSpatialObject->GetMyBoundingBoxInWorldSpace()->GetBounds() << std::endl; - MeshSpatialObjectType::PointType myPhysicalPoint; - myPhysicalPoint.Fill(1); + auto myPhysicalPoint = itk::MakeFilled(1); std::cout << "Is my physical point inside? : " << myMeshSpatialObject->IsInsideInWorldSpace(myPhysicalPoint) << std::endl; @@ -239,7 +236,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - ImageType::Pointer myBinaryMeshImage = imageFilter->GetOutput(); + const ImageType::Pointer myBinaryMeshImage = imageFilter->GetOutput(); // Software Guide : EndCodeSnippet return EXIT_SUCCESS; diff --git a/Examples/SpatialObjects/SpatialObjectToImageStatisticsCalculator.cxx b/Examples/SpatialObjects/SpatialObjectToImageStatisticsCalculator.cxx index 02b42c32621..2eace034dd2 100644 --- a/Examples/SpatialObjects/SpatialObjectToImageStatisticsCalculator.cxx +++ b/Examples/SpatialObjects/SpatialObjectToImageStatisticsCalculator.cxx @@ -52,7 +52,7 @@ main(int, char *[]) size[1] = 10; randomImageSource->SetSize(size); randomImageSource->Update(); - ImageType::Pointer image = randomImageSource->GetOutput(); + const ImageType::Pointer image = randomImageSource->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -66,8 +66,7 @@ main(int, char *[]) using EllipseType = itk::EllipseSpatialObject<2>; auto ellipse = EllipseType::New(); ellipse->SetRadiusInObjectSpace(2); - EllipseType::PointType offset; - offset.Fill(5); + auto offset = itk::MakeFilled(5); ellipse->SetCenterInObjectSpace(offset); ellipse->Update(); // Software Guide : EndCodeSnippet diff --git a/Examples/SpatialObjects/SurfaceSpatialObject.cxx b/Examples/SpatialObjects/SurfaceSpatialObject.cxx index 0f7c11af822..f20b7a0dcbe 100644 --- a/Examples/SpatialObjects/SurfaceSpatialObject.cxx +++ b/Examples/SpatialObjects/SurfaceSpatialObject.cxx @@ -53,7 +53,7 @@ main(int, char *[]) using CovariantVectorType = SurfaceType::CovariantVectorType; using PointType = SurfaceType::PointType; - SurfacePointer surface = SurfaceType::New(); + const SurfacePointer surface = SurfaceType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -109,7 +109,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - SurfaceType::SurfacePointListType pointList = surface->GetPoints(); + const SurfaceType::SurfacePointListType pointList = surface->GetPoints(); std::cout << "Number of points representing the surface: "; std::cout << pointList.size() << std::endl; // Software Guide : EndCodeSnippet @@ -136,7 +136,7 @@ main(int, char *[]) std::cout << "Normal = " << (*it).GetNormalInObjectSpace() << std::endl; std::cout << "Color = " << (*it).GetColor() << std::endl; std::cout << std::endl; - it++; + ++it; } // Software Guide : EndCodeSnippet diff --git a/Examples/SpatialObjects/TubeSpatialObject.cxx b/Examples/SpatialObjects/TubeSpatialObject.cxx index d0d45277680..cd47b43e96a 100644 --- a/Examples/SpatialObjects/TubeSpatialObject.cxx +++ b/Examples/SpatialObjects/TubeSpatialObject.cxx @@ -54,7 +54,7 @@ main(int, char *[]) using PointType = TubeType::PointType; using CovariantVectorType = TubePointType::CovariantVectorType; - TubePointer tube = TubeType::New(); + const TubePointer tube = TubeType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -123,7 +123,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - TubeType::TubePointListType pointList = tube->GetPoints(); + const TubeType::TubePointListType pointList = tube->GetPoints(); std::cout << "Number of points representing the tube: "; std::cout << pointList.size() << std::endl; // Software Guide : EndCodeSnippet @@ -167,8 +167,8 @@ main(int, char *[]) std::cout << "Second Normal: " << (*it).GetNormal2InObjectSpace() << std::endl; std::cout << "Color = " << (*it).GetColor() << std::endl; - it++; - i++; + ++it; + ++i; } // Software Guide : EndCodeSnippet diff --git a/Examples/SpatialObjects/VesselTubeSpatialObject.cxx b/Examples/SpatialObjects/VesselTubeSpatialObject.cxx index 720e02b9517..fb2bfb187f2 100644 --- a/Examples/SpatialObjects/VesselTubeSpatialObject.cxx +++ b/Examples/SpatialObjects/VesselTubeSpatialObject.cxx @@ -123,7 +123,7 @@ main(int, char *[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - VesselTubeType::TubePointListType pointList = vesselTube->GetPoints(); + const VesselTubeType::TubePointListType pointList = vesselTube->GetPoints(); std::cout << "Number of points representing the blood vessel: "; std::cout << pointList.size() << std::endl; // Software Guide : EndCodeSnippet diff --git a/Examples/Statistics/BayesianClassifier.cxx b/Examples/Statistics/BayesianClassifier.cxx index cc64de6c9e2..68f0ff81584 100644 --- a/Examples/Statistics/BayesianClassifier.cxx +++ b/Examples/Statistics/BayesianClassifier.cxx @@ -54,8 +54,10 @@ #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkRescaleIntensityImageFilter.h" +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 3) @@ -67,24 +69,16 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - // input parameters - const char * membershipImageFileName = argv[1]; - const char * labelMapImageFileName = argv[2]; - - // setup reader constexpr unsigned int Dimension = 2; using InputPixelType = float; using InputImageType = itk::VectorImage; - using ReaderType = itk::ImageFileReader; - auto reader = ReaderType::New(); - reader->SetFileName(membershipImageFileName); + auto input = itk::ReadImage(argv[1]); using LabelType = unsigned char; using PriorType = float; using PosteriorType = float; - using ClassifierFilterType = itk::BayesianClassifierImageFilterSetInput(input); - filter->SetInput(reader->GetOutput()); - - if (argv[3]) + if (argc > 3) { filter->SetNumberOfSmoothingIterations(std::stoi(argv[3])); using ExtractedComponentImageType = @@ -111,15 +104,11 @@ main(int argc, char * argv[]) filter->SetSmoothingFilter(smoother); } - // SET FILTER'S PRIOR PARAMETERS // do nothing here to default to uniform priors // otherwise set the priors to some user provided values - // - // Setup writer.. Rescale the label map to the dynamic range of the - // datatype and write it - // + // Rescale the label map to the dynamic range of the datatype and write it using ClassifierOutputImageType = ClassifierFilterType::OutputImageType; using OutputImageType = itk::Image; using RescalerType = @@ -130,30 +119,35 @@ main(int argc, char * argv[]) rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); - using WriterType = itk::ImageFileWriter; + // Write labelmap to file + itk::WriteImage(rescaler->GetOutput(), argv[2]); - auto writer = WriterType::New(); - writer->SetFileName(labelMapImageFileName); + // Testing print + filter->Print(std::cout); + std::cout << "Test passed." << std::endl; - // - // Write labelmap to file - // - writer->SetInput(rescaler->GetOutput()); + return EXIT_SUCCESS; +} +} // namespace +int +main(int argc, char * argv[]) +{ try { - writer->Update(); + return ExampleMain(argc, argv); } - catch (const itk::ExceptionObject & excp) + catch (const itk::ExceptionObject & exceptionObject) { - std::cerr << "Exception caught: " << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; } - - // Testing print - filter->Print(std::cout); - std::cout << "Test passed." << std::endl; - - return EXIT_SUCCESS; + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; } diff --git a/Examples/Statistics/BayesianClassifierInitializer.cxx b/Examples/Statistics/BayesianClassifierInitializer.cxx index 043f3cf5ac4..0a07a8bf10a 100644 --- a/Examples/Statistics/BayesianClassifierInitializer.cxx +++ b/Examples/Statistics/BayesianClassifierInitializer.cxx @@ -58,9 +58,10 @@ #include "itkImageFileWriter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkImageRegionConstIterator.h" - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { constexpr unsigned int Dimension = 2; @@ -80,58 +81,22 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } + using ImageType = itk::Image; using BayesianInitializerType = itk::BayesianClassifierInitializationImageFilter; auto bayesianInitializer = BayesianInitializerType::New(); - using ReaderType = itk::ImageFileReader; - auto reader = ReaderType::New(); - reader->SetFileName(argv[1]); + auto input = itk::ReadImage(argv[1]); - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Exception thrown " << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } - - bayesianInitializer->SetInput(reader->GetOutput()); + bayesianInitializer->SetInput(input); bayesianInitializer->SetNumberOfClasses(std::stoi(argv[3])); // TODO add test where we specify membership functions - using WriterType = - itk::ImageFileWriter; - auto writer = WriterType::New(); - writer->SetInput(bayesianInitializer->GetOutput()); - writer->SetFileName(argv[2]); + bayesianInitializer->Update(); - try - { - bayesianInitializer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Exception thrown " << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } - - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Exception thrown " << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + itk::WriteImage(bayesianInitializer->GetOutput(), argv[2]); if (argv[4] && argv[5]) { @@ -175,13 +140,31 @@ main(int argc, char * argv[]) rescaler->SetInput(extractedComponentImage); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); - using ExtractedComponentWriterType = - itk::ImageFileWriter; - auto rescaledImageWriter = ExtractedComponentWriterType::New(); - rescaledImageWriter->SetInput(rescaler->GetOutput()); - rescaledImageWriter->SetFileName(argv[5]); - rescaledImageWriter->Update(); + itk::WriteImage(rescaler->GetOutput(), argv[5]); } return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/Statistics/BayesianPluginClassifier.cxx b/Examples/Statistics/BayesianPluginClassifier.cxx index 0efab9deb5a..a20fd44962f 100644 --- a/Examples/Statistics/BayesianPluginClassifier.cxx +++ b/Examples/Statistics/BayesianPluginClassifier.cxx @@ -278,9 +278,9 @@ main(int, char *[]) auto classLabelVectorObject = ClassLabelVectorObjectType::New(); ClassLabelVectorType classLabelVector = classLabelVectorObject->Get(); - ClassifierType::ClassLabelType class1 = 100; + constexpr ClassifierType::ClassLabelType class1 = 100; classLabelVector.push_back(class1); - ClassifierType::ClassLabelType class2 = 200; + constexpr ClassifierType::ClassLabelType class2 = 200; classLabelVector.push_back(class2); classLabelVectorObject->Set(classLabelVector); @@ -327,7 +327,7 @@ main(int, char *[]) membershipFunction->SetMean(covarianceEstimators[i]->GetMean()); membershipFunction->SetCovariance( covarianceEstimators[i]->GetCovarianceMatrix()); - membershipFunctionVector.push_back(membershipFunction); + membershipFunctionVector.emplace_back(membershipFunction); } membershipFunctionVectorObject->Set(membershipFunctionVector); classifier->SetMembershipFunctions(membershipFunctionVectorObject); diff --git a/Examples/Statistics/ExpectationMaximizationMixtureModelEstimator.cxx b/Examples/Statistics/ExpectationMaximizationMixtureModelEstimator.cxx index bde5b6344a5..8f4e30b8515 100644 --- a/Examples/Statistics/ExpectationMaximizationMixtureModelEstimator.cxx +++ b/Examples/Statistics/ExpectationMaximizationMixtureModelEstimator.cxx @@ -122,7 +122,7 @@ main() // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - unsigned int numberOfClasses = 2; + constexpr unsigned int numberOfClasses = 2; using MeasurementVectorType = itk::Vector; using SampleType = itk::Statistics::ListSample; auto sample = SampleType::New(); diff --git a/Examples/Statistics/GaussianMembershipFunction.cxx b/Examples/Statistics/GaussianMembershipFunction.cxx index 3209abab016..8a180327a42 100644 --- a/Examples/Statistics/GaussianMembershipFunction.cxx +++ b/Examples/Statistics/GaussianMembershipFunction.cxx @@ -99,8 +99,7 @@ main(int, char *[]) densityFunction->SetMean(mean); densityFunction->SetCovariance(cov); - MeasurementVectorType mv; - mv.Fill(0); + constexpr MeasurementVectorType mv{}; std::cout << densityFunction->Evaluate(mv) << std::endl; // Software Guide : EndCodeSnippet diff --git a/Examples/Statistics/ImageEntropy1.cxx b/Examples/Statistics/ImageEntropy1.cxx index de718b28cd3..7295912eab7 100644 --- a/Examples/Statistics/ImageEntropy1.cxx +++ b/Examples/Statistics/ImageEntropy1.cxx @@ -57,9 +57,10 @@ // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 3) @@ -84,23 +85,8 @@ main(int argc, char * argv[]) using ImageType = itk::Image; // Software Guide : EndCodeSnippet - using ReaderType = itk::ImageFileReader; - - auto reader = ReaderType::New(); - - reader->SetFileName(argv[1]); - - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem encountered while reading image file : " << argv[1] - << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + ImageType::Pointer input; + input = itk::ReadImage(argv[1]); // Software Guide : BeginLatex // @@ -144,7 +130,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - histogramGenerator->SetInput(reader->GetOutput()); + histogramGenerator->SetInput(input); histogramGenerator->Compute(); // Software Guide : EndCodeSnippet @@ -194,10 +180,10 @@ main(int argc, char * argv[]) // Software Guide : BeginCodeSnippet - HistogramType::ConstIterator itr = histogram->Begin(); - HistogramType::ConstIterator end = histogram->End(); + HistogramType::ConstIterator itr = histogram->Begin(); + const HistogramType::ConstIterator end = histogram->End(); - double Sum = histogram->GetTotalFrequency(); + const double Sum = histogram->GetTotalFrequency(); double Entropy = 0.0; // Software Guide : EndCodeSnippet @@ -279,3 +265,26 @@ main(int argc, char * argv[]) return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/Statistics/ImageHistogram1.cxx b/Examples/Statistics/ImageHistogram1.cxx index f82f705dfee..1e8e998304f 100644 --- a/Examples/Statistics/ImageHistogram1.cxx +++ b/Examples/Statistics/ImageHistogram1.cxx @@ -56,9 +56,10 @@ #include "itkHistogram.h" #include "itkSampleToHistogramFilter.h" // Software Guide : EndCodeSnippet - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 2) @@ -84,17 +85,18 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // - // Using the same image type we instantiate the type of the image reader + // Using the same image type we read the image file // that will provide the image source for our example. + // As usual, this must be done inside a try/catch block because the read + // operation can potentially throw exceptions. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - using ReaderType = itk::ImageFileReader; + ImageType::Pointer input; - auto reader = ReaderType::New(); + input = itk::ReadImage(argv[1]); - reader->SetFileName(argv[1]); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -104,7 +106,7 @@ main(int argc, char * argv[]) // samples. We instantiate the type of the adaptor by using the actual image // type. Then construct the adaptor by invoking its \code{New()} method and // assigning the result to the corresponding smart pointer. Finally we - // connect the output of the image reader to the input of the adaptor. + // specify the input to the adaptor. // // \index{itk::Statistics::Scalar\-Image\-To\-List\-Adaptor!instantiation} // @@ -115,31 +117,7 @@ main(int argc, char * argv[]) auto adaptor = AdaptorType::New(); - adaptor->SetImage(reader->GetOutput()); - // Software Guide : EndCodeSnippet - - // Software Guide : BeginLatex - // - // You must keep in mind that adaptors are not pipeline objects. This means - // that they do not propagate update calls. It is therefore your - // responsibility to make sure that you invoke the \code{Update()} method of - // the reader before you attempt to use the output of the adaptor. As usual, - // this must be done inside a try/catch block because the read operation can - // potentially throw exceptions. - // - // Software Guide : EndLatex - - // Software Guide : BeginCodeSnippet - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem reading image file : " << argv[1] << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + adaptor->SetImage(input); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -206,7 +184,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - HistogramType::ConstPointer histogram = filter->GetOutput(); + const HistogramType::ConstPointer histogram = filter->GetOutput(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -230,3 +208,26 @@ main(int argc, char * argv[]) return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/Statistics/ImageHistogram2.cxx b/Examples/Statistics/ImageHistogram2.cxx index 3779056ebb2..bb17e04bc86 100644 --- a/Examples/Statistics/ImageHistogram2.cxx +++ b/Examples/Statistics/ImageHistogram2.cxx @@ -46,9 +46,10 @@ // Software Guide : EndCodeSnippet #include "itkImageFileReader.h" - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 2) @@ -74,23 +75,9 @@ main(int argc, char * argv[]) using ImageType = itk::Image; // Software Guide : EndCodeSnippet + ImageType::Pointer input; - using ReaderType = itk::ImageFileReader; - - auto reader = ReaderType::New(); - - reader->SetFileName(argv[1]); - - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem reading image file : " << argv[1] << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + input = itk::ReadImage(argv[1]); // Software Guide : BeginLatex @@ -119,7 +106,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - histogramGenerator->SetInput(reader->GetOutput()); + histogramGenerator->SetInput(input); // Software Guide : EndCodeSnippet @@ -193,8 +180,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - HistogramType::ConstIterator itr = histogram->Begin(); - HistogramType::ConstIterator end = histogram->End(); + HistogramType::ConstIterator itr = histogram->Begin(); + const HistogramType::ConstIterator end = histogram->End(); unsigned int binNumber = 0; while (itr != end) @@ -209,3 +196,26 @@ main(int argc, char * argv[]) return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/Statistics/ImageHistogram3.cxx b/Examples/Statistics/ImageHistogram3.cxx index 970d8c016d6..8d97d1923c0 100644 --- a/Examples/Statistics/ImageHistogram3.cxx +++ b/Examples/Statistics/ImageHistogram3.cxx @@ -47,9 +47,10 @@ #include "itkImageFileReader.h" - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 2) @@ -80,24 +81,9 @@ main(int argc, char * argv[]) using RGBImageType = itk::Image; // Software Guide : EndCodeSnippet + RGBImageType::Pointer input; - using ReaderType = itk::ImageFileReader; - - auto reader = ReaderType::New(); - - reader->SetFileName(argv[1]); - - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem encountered while reading image file : " << argv[1] - << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + input = itk::ReadImage(argv[1]); // Software Guide : BeginLatex @@ -192,7 +178,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - histogramFilter->SetInput(reader->GetOutput()); + histogramFilter->SetInput(input); histogramFilter->Update(); // Software Guide : EndCodeSnippet @@ -348,3 +334,25 @@ main(int argc, char * argv[]) return EXIT_SUCCESS; } +} // namespace +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/Statistics/ImageHistogram4.cxx b/Examples/Statistics/ImageHistogram4.cxx index e506363303a..486aa8e7818 100644 --- a/Examples/Statistics/ImageHistogram4.cxx +++ b/Examples/Statistics/ImageHistogram4.cxx @@ -59,8 +59,10 @@ #include "itkImageFileReader.h" +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 3) @@ -89,23 +91,9 @@ main(int argc, char * argv[]) using RGBImageType = itk::Image; // Software Guide : EndCodeSnippet + RGBImageType::Pointer input; - using ReaderType = itk::ImageFileReader; - - auto reader = ReaderType::New(); - - reader->SetFileName(argv[1]); - - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem reading image file : " << argv[1] << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + input = itk::ReadImage(argv[1]); // Software Guide : BeginLatex @@ -187,7 +175,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - histogramFilter->SetInput(reader->GetOutput()); + histogramFilter->SetInput(input); // Software Guide : EndCodeSnippet @@ -257,8 +245,8 @@ main(int argc, char * argv[]) std::ofstream histogramFile; histogramFile.open(argv[2]); - HistogramType::ConstIterator itr = histogram->Begin(); - HistogramType::ConstIterator end = histogram->End(); + HistogramType::ConstIterator itr = histogram->Begin(); + const HistogramType::ConstIterator end = histogram->End(); using AbsoluteFrequencyType = HistogramType::AbsoluteFrequencyType; @@ -293,3 +281,26 @@ main(int argc, char * argv[]) return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/Statistics/ImageMutualInformation1.cxx b/Examples/Statistics/ImageMutualInformation1.cxx index 2cc8091db8b..0484e9e9ab7 100644 --- a/Examples/Statistics/ImageMutualInformation1.cxx +++ b/Examples/Statistics/ImageMutualInformation1.cxx @@ -84,9 +84,10 @@ #include "itkImageToHistogramFilter.h" // Software Guide : EndCodeSnippet - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 3) @@ -114,19 +115,14 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // - // Using the image type we proceed to instantiate the readers for both input - // images. Then, we take their filenames from the command line arguments. + // Using the image type we proceed to read in the input images + // taking their filenames from the command line arguments. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - using ReaderType = itk::ImageFileReader; - - auto reader1 = ReaderType::New(); - auto reader2 = ReaderType::New(); - - reader1->SetFileName(argv[1]); - reader2->SetFileName(argv[2]); + const auto input1 = itk::ReadImage(argv[1]); + const auto input2 = itk::ReadImage(argv[2]); // Software Guide : EndCodeSnippet @@ -142,8 +138,8 @@ main(int argc, char * argv[]) auto joinFilter = JoinFilterType::New(); - joinFilter->SetInput1(reader1->GetOutput()); - joinFilter->SetInput2(reader2->GetOutput()); + joinFilter->SetInput1(input1); + joinFilter->SetInput2(input2); // Software Guide : EndCodeSnippet @@ -157,15 +153,9 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - try - { - joinFilter->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + + joinFilter->Update(); + // Software Guide : EndCodeSnippet @@ -419,7 +409,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - double MutualInformation = Entropy1 + Entropy2 - JointEntropy; + const double MutualInformation = Entropy1 + Entropy2 - JointEntropy; // Software Guide : EndCodeSnippet std::cout << "Mutual Information = " << MutualInformation << " bits " @@ -434,7 +424,7 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - double NormalizedMutualInformation1 = + const double NormalizedMutualInformation1 = 2.0 * MutualInformation / (Entropy1 + Entropy2); // Software Guide : EndCodeSnippet @@ -450,7 +440,8 @@ main(int argc, char * argv[]) // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - double NormalizedMutualInformation2 = (Entropy1 + Entropy2) / JointEntropy; + const double NormalizedMutualInformation2 = + (Entropy1 + Entropy2) / JointEntropy; // Software Guide : EndCodeSnippet @@ -469,3 +460,26 @@ main(int argc, char * argv[]) return EXIT_SUCCESS; } +} // namespace + +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/Statistics/ImageToListSampleAdaptor.cxx b/Examples/Statistics/ImageToListSampleAdaptor.cxx index 05afbc4ff84..4ead9f585d3 100644 --- a/Examples/Statistics/ImageToListSampleAdaptor.cxx +++ b/Examples/Statistics/ImageToListSampleAdaptor.cxx @@ -76,8 +76,7 @@ main() // Software Guide : BeginCodeSnippet using FloatImage2DType = itk::Image; - itk::RandomImageSource::Pointer random; - random = itk::RandomImageSource::New(); + auto random = itk::RandomImageSource::New(); random->SetMin(0.0); random->SetMax(1000.0); diff --git a/Examples/Statistics/KdTree.cxx b/Examples/Statistics/KdTree.cxx index e335ec5b80c..f68c421a870 100644 --- a/Examples/Statistics/KdTree.cxx +++ b/Examples/Statistics/KdTree.cxx @@ -124,8 +124,8 @@ main() using TreeType = TreeGeneratorType::KdTreeType; using NodeType = TreeType::KdTreeNodeType; - TreeType::Pointer tree = treeGenerator->GetOutput(); - TreeType::Pointer centroidTree = centroidTreeGenerator->GetOutput(); + const TreeType::Pointer tree = treeGenerator->GetOutput(); + const TreeType::Pointer centroidTree = centroidTreeGenerator->GetOutput(); NodeType * root = tree->GetRoot(); @@ -212,7 +212,7 @@ main() // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - unsigned int numberOfNeighbors = 3; + constexpr unsigned int numberOfNeighbors = 3; TreeType::InstanceIdentifierVectorType neighbors; tree->Search(queryPoint, numberOfNeighbors, neighbors); @@ -308,7 +308,7 @@ main() // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - double radius = 437.0; + constexpr double radius = 437.0; tree->Search(queryPoint, radius, neighbors); diff --git a/Examples/Statistics/KdTreeBasedKMeansClustering.cxx b/Examples/Statistics/KdTreeBasedKMeansClustering.cxx index 1f4a49faddc..a41bd01b760 100644 --- a/Examples/Statistics/KdTreeBasedKMeansClustering.cxx +++ b/Examples/Statistics/KdTreeBasedKMeansClustering.cxx @@ -323,9 +323,9 @@ main() auto classLabelsObject = ClassLabelVectorObjectType::New(); ClassLabelVectorType & classLabelsVector = classLabelsObject->Get(); - ClassLabelType class1 = 200; + constexpr ClassLabelType class1 = 200; classLabelsVector.push_back(class1); - ClassLabelType class2 = 100; + constexpr ClassLabelType class2 = 100; classLabelsVector.push_back(class2); classifier->SetClassLabels(classLabelsObject); @@ -370,7 +370,7 @@ main() centroid[j] = estimatedMeans[index++]; } membershipFunction->SetCentroid(centroid); - membershipFunctionVector.push_back(membershipFunction); + membershipFunctionVector.emplace_back(membershipFunction); } classifier->SetMembershipFunctions(membershipFunctionVectorObject); diff --git a/Examples/Statistics/MembershipSample.cxx b/Examples/Statistics/MembershipSample.cxx index a1cc94c0edd..3850f4aa830 100644 --- a/Examples/Statistics/MembershipSample.cxx +++ b/Examples/Statistics/MembershipSample.cxx @@ -175,7 +175,7 @@ main() // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - MembershipSampleType::ClassSampleType::ConstPointer classSample = + const MembershipSampleType::ClassSampleType::ConstPointer classSample = membershipSample->GetClassSample(0); MembershipSampleType::ClassSampleType::ConstIterator c_iter = diff --git a/Examples/Statistics/PointSetToAdaptor.cxx b/Examples/Statistics/PointSetToAdaptor.cxx index 2aadab7dfb8..d255b012b8f 100644 --- a/Examples/Statistics/PointSetToAdaptor.cxx +++ b/Examples/Statistics/PointSetToAdaptor.cxx @@ -67,8 +67,7 @@ main() // Software Guide : BeginCodeSnippet using FloatPointSet2DType = itk::PointSet; - itk::RandomPointSetSource::Pointer random; - random = itk::RandomPointSetSource::New(); + auto random = itk::RandomPointSetSource::New(); random->SetMin(0.0); random->SetMax(1000.0); diff --git a/Examples/Statistics/PointSetToListSampleAdaptor.cxx b/Examples/Statistics/PointSetToListSampleAdaptor.cxx index a1b6bbcdc9c..a8196882eb2 100644 --- a/Examples/Statistics/PointSetToListSampleAdaptor.cxx +++ b/Examples/Statistics/PointSetToListSampleAdaptor.cxx @@ -80,7 +80,7 @@ main() // dimension, we have to modify the \code{TMeshTraits} (one of the optional // template arguments for the \code{PointSet} class). The easiest way of // creating a custom mesh traits instance is to specialize the existing - // \doxygen{DefaultStaticMeshTraits}. By specifying the \code{TCoordRep} + // \doxygen{DefaultStaticMeshTraits}. By specifying the \code{TCoordinate} // template argument, we can change the coordinate value type of a point. // By specifying the \code{VPointDimension} template argument, we can // change the dimension of the point. As mentioned earlier, a diff --git a/Examples/Statistics/SampleSorting.cxx b/Examples/Statistics/SampleSorting.cxx index c06047e3466..45760d3bc09 100644 --- a/Examples/Statistics/SampleSorting.cxx +++ b/Examples/Statistics/SampleSorting.cxx @@ -190,7 +190,7 @@ main() // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - int activeDimension = 0; + constexpr int activeDimension = 0; itk::Statistics::Algorithm::InsertSort( subsample, activeDimension, 0, subsample->Size()); printSubsample(subsample, "InsertSort"); @@ -243,7 +243,7 @@ main() // Software Guide : BeginCodeSnippet initializeSubsample(subsample, sample); - SubsampleType::MeasurementType median = + const SubsampleType::MeasurementType median = itk::Statistics::Algorithm::QuickSelect(subsample, activeDimension, 0, diff --git a/Examples/Statistics/ScalarImageKmeansClassifier.cxx b/Examples/Statistics/ScalarImageKmeansClassifier.cxx index 188344c7068..4076123dbe5 100644 --- a/Examples/Statistics/ScalarImageKmeansClassifier.cxx +++ b/Examples/Statistics/ScalarImageKmeansClassifier.cxx @@ -42,9 +42,10 @@ #include "itkImageFileWriter.h" #include "itkScalarImageKmeansImageFilter.h" // Software Guide : EndCodeSnippet - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 5) { @@ -55,30 +56,25 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - const char * inputImageFileName = argv[1]; - - // Software Guide : BeginLatex // // First we define the pixel type and dimension of the image that we intend - // to classify. With this image type we can also declare the - // \doxygen{ImageFileReader} needed for reading the input image, create one - // and set its input filename. + // to classify. With this image type we can also read the input image. + // We start a try-catch block which encloses most of the code in the + // example. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet + using PixelType = short; constexpr unsigned int Dimension = 2; using ImageType = itk::Image; - using ReaderType = itk::ImageFileReader; - auto reader = ReaderType::New(); - reader->SetFileName(inputImageFileName); + auto input = itk::ReadImage(argv[1]); // Software Guide : EndCodeSnippet - // Software Guide : BeginLatex // // With the \code{ImageType} we instantiate the type of the @@ -92,25 +88,25 @@ main(int argc, char * argv[]) auto kmeansFilter = KMeansFilterType::New(); - kmeansFilter->SetInput(reader->GetOutput()); + kmeansFilter->SetInput(input); const unsigned int numberOfInitialClasses = std::stoi(argv[4]); // Software Guide : EndCodeSnippet - // Software Guide : BeginLatex // - // In general the classification will produce as output an image whose pixel - // values are integers associated to the labels of the classes. Since - // typically these integers will be generated in order (0,1,2,...N), the - // output image will tend to look very dark when displayed with naive + // In general the classification will produce as output an image whose + // pixel values are integers associated to the labels of the classes. + // Since typically these integers will be generated in order (0,1,2,...N), + // the output image will tend to look very dark when displayed with naive // viewers. It is therefore convenient to have the option of spreading the - // label values over the dynamic range of the output image pixel type. When - // this is done, the dynamic range of the pixels is divided by the number of - // classes in order to define the increment between labels. For example, an - // output image of 8 bits will have a dynamic range of [0:256], and when it - // is used for holding four classes, the non-contiguous labels will be - // (0,64,128,192). The selection of the mode to use is done with the method + // label values over the dynamic range of the output image pixel type. + // When this is done, the dynamic range of the pixels is divided by the + // number of classes in order to define the increment between labels. For + // example, an output image of 8 bits will have a dynamic range of + // [0:256], and when it is used for holding four classes, the + // non-contiguous labels will be (0,64,128,192). The selection of the mode + // to use is done with the method // \code{SetUseNonContiguousLabels()}. // // Software Guide : EndLatex @@ -121,7 +117,6 @@ main(int argc, char * argv[]) kmeansFilter->SetUseNonContiguousLabels(useNonContiguousLabels); // Software Guide : EndCodeSnippet - constexpr unsigned int argoffset = 5; if (static_cast(argc) < numberOfInitialClasses + argoffset) @@ -133,18 +128,16 @@ main(int argc, char * argv[]) return EXIT_FAILURE; } - // Software Guide : BeginLatex // - // For each one of the classes we must provide a tentative initial value for - // the mean of the class. Given that this is a scalar image, each one of the - // means is simply a scalar value. Note however that in a general case of - // K-Means, the input image would be a vector image and therefore the means - // will be vectors of the same dimension as the image pixels. + // For each one of the classes we must provide a tentative initial value + // for the mean of the class. Given that this is a scalar image, each one + // of the means is simply a scalar value. Note however that in a general + // case of K-Means, the input image would be a vector image and therefore + // the means will be vectors of the same dimension as the image pixels. // // Software Guide : EndLatex - // Software Guide : BeginCodeSnippet for (unsigned int k = 0; k < numberOfInitialClasses; ++k) { @@ -153,64 +146,24 @@ main(int argc, char * argv[]) } // Software Guide : EndCodeSnippet - - const char * outputImageFileName = argv[2]; - - - // Software Guide : BeginLatex - // - // The \doxygen{ScalarImageKmeansImageFilter} is predefined for producing an - // 8 bits scalar image as output. This output image contains labels - // associated to each one of the classes in the K-Means algorithm. In the - // following lines we use the \code{OutputImageType} in order to instantiate - // the type of a \doxygen{ImageFileWriter}. Then create one, and connect it - // to the output of the classification filter. - // - // Software Guide : EndLatex - - // Software Guide : BeginCodeSnippet - using OutputImageType = KMeansFilterType::OutputImageType; - - using WriterType = itk::ImageFileWriter; - - auto writer = WriterType::New(); - - writer->SetInput(kmeansFilter->GetOutput()); - - writer->SetFileName(outputImageFileName); - // Software Guide : EndCodeSnippet - - // Software Guide : BeginLatex // - // We are now ready for triggering the execution of the pipeline. This is - // done by simply invoking the \code{Update()} method in the writer. This - // call will propagate the update request to the reader and then to the - // classifier. + // The \doxygen{ScalarImageKmeansImageFilter} is predefined for producing + // an 8 bits scalar image as output. This output image contains labels + // associated to each one of the classes in the K-Means algorithm. The + // following line writes the output of the classification filter to file. // // Software Guide : EndLatex - // Software Guide : BeginCodeSnippet - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem encountered while writing "; - std::cerr << " image file : " << argv[2] << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + itk::WriteImage(kmeansFilter->GetOutput(), argv[2]); // Software Guide : EndCodeSnippet - // Software Guide : BeginLatex // - // At this point the classification is done, the labeled image is saved in a - // file, and we can take a look at the means that were found as a result of - // the model estimation performed inside the classifier filter. + // At this point the classification is done, the labeled image is saved in + // a file, and we can take a look at the means that were found as a result + // of the model estimation performed inside the classifier filter. // // Software Guide : EndLatex @@ -226,6 +179,8 @@ main(int argc, char * argv[]) std::cout << " estimated mean : " << estimatedMeans[i] << std::endl; } + return EXIT_SUCCESS; + // Software Guide : EndCodeSnippet // Software Guide : BeginLatex @@ -242,6 +197,26 @@ main(int argc, char * argv[]) // The means were estimated by ScalarImageKmeansModelEstimator.cxx. // // Software Guide : EndLatex - - return EXIT_SUCCESS; +} +} // namespace +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; } diff --git a/Examples/Statistics/ScalarImageKmeansModelEstimator.cxx b/Examples/Statistics/ScalarImageKmeansModelEstimator.cxx index 61a7c2f1a50..945b59628b5 100644 --- a/Examples/Statistics/ScalarImageKmeansModelEstimator.cxx +++ b/Examples/Statistics/ScalarImageKmeansModelEstimator.cxx @@ -45,9 +45,10 @@ #include "itkImage.h" #include "itkImageFileReader.h" - +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 2) @@ -62,23 +63,9 @@ main(int argc, char * argv[]) using ImageType = itk::Image; - using ReaderType = itk::ImageFileReader; + ImageType::Pointer input; - auto reader = ReaderType::New(); - - reader->SetFileName(argv[1]); - - try - { - reader->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem encountered while reading image file : " << argv[1] - << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } + input = itk::ReadImage(argv[1]); // Software Guide : BeginCodeSnippet @@ -88,7 +75,7 @@ main(int argc, char * argv[]) auto adaptor = AdaptorType::New(); - adaptor->SetImage(reader->GetOutput()); + adaptor->SetImage(input); // Create the K-d tree structure using TreeGeneratorType = @@ -145,3 +132,25 @@ main(int argc, char * argv[]) return EXIT_SUCCESS; } +} // namespace +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; +} diff --git a/Examples/Statistics/ScalarImageMarkovRandomField1.cxx b/Examples/Statistics/ScalarImageMarkovRandomField1.cxx index aef51ff3fa5..079d45b9aab 100644 --- a/Examples/Statistics/ScalarImageMarkovRandomField1.cxx +++ b/Examples/Statistics/ScalarImageMarkovRandomField1.cxx @@ -66,9 +66,11 @@ #include "itkDistanceToCentroidMembershipFunction.h" #include "itkMinimumDecisionRule.h" // Software Guide : EndCodeSnippet +namespace +{ int -main(int argc, char * argv[]) +ExampleMain(int argc, const char * const argv[]) { if (argc < 7) { @@ -105,23 +107,19 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // // First we define the pixel type and dimension of the image that we intend - // to classify. With this image type we can also declare the - // \doxygen{ImageFileReader} needed for reading the input image, create one - // and set its input filename. In this particular case we choose to use - // \code{short} as pixel type, which is typical for MicroMRI and CT - // data sets. + // to classify and read the input image.In this particular case we choose to + // use \code{short} as pixel type, which is typical for MicroMRI and CT data + // sets. We open a try block to enclose most of the code in this example. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet + using PixelType = short; constexpr unsigned int Dimension = 2; using ImageType = itk::Image; - - using ReaderType = itk::ImageFileReader; - auto reader = ReaderType::New(); - reader->SetFileName(inputImageFileName); + auto input = itk::ReadImage(inputImageFileName); // Software Guide : EndCodeSnippet @@ -139,18 +137,17 @@ main(int argc, char * argv[]) using LabelImageType = itk::Image; - using LabelReaderType = itk::ImageFileReader; - auto labelReader = LabelReaderType::New(); - labelReader->SetFileName(inputLabelImageFileName); + const auto labelInput = + itk::ReadImage(inputLabelImageFileName); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // - // Since the Markov Random Field algorithm is defined in general for images - // whose pixels have multiple components, that is, images of vector type, we - // must adapt our scalar image in order to satisfy the interface expected by - // the \code{MRFImageFilter}. We do this by using the + // Since the Markov Random Field algorithm is defined in general for + // images whose pixels have multiple components, that is, images of vector + // type, we must adapt our scalar image in order to satisfy the interface + // expected by the \code{MRFImageFilter}. We do this by using the // \doxygen{ComposeImageFilter}. With this filter we will present our // scalar image as a vector image whose vector pixels contain a single // component. @@ -166,7 +163,7 @@ main(int argc, char * argv[]) itk::ComposeImageFilter; auto scalarToArrayFilter = ScalarToArrayFilterType::New(); - scalarToArrayFilter->SetInput(reader->GetOutput()); + scalarToArrayFilter->SetInput(input); // Software Guide : EndCodeSnippet @@ -190,8 +187,8 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // - // We set now some of the parameters for the MRF filter. In particular, the - // number of classes to be used during the classification, the maximum + // We set now some of the parameters for the MRF filter. In particular, + // the number of classes to be used during the classification, the maximum // number of iterations to be run in this filter and the error tolerance // that will be used as a criterion for convergence. // @@ -208,10 +205,10 @@ main(int argc, char * argv[]) // // The smoothing factor represents the tradeoff between fidelity to the // observed image and the smoothness of the segmented image. Typical - // smoothing factors have values between 1~5. This factor will multiply the - // weights that define the influence of neighbors on the classification of a - // given pixel. The higher the value, the more uniform will be the regions - // resulting from the classification refinement. + // smoothing factors have values between 1~5. This factor will multiply + // the weights that define the influence of neighbors on the + // classification of a given pixel. The higher the value, the more uniform + // will be the regions resulting from the classification refinement. // // Software Guide : EndLatex @@ -224,10 +221,10 @@ main(int argc, char * argv[]) // // Given that the MRF filter need to continually relabel the pixels, it // needs access to a set of membership functions that will measure to what - // degree every pixel belongs to a particular class. The classification is - // performed by the \doxygen{ImageClassifierBase} class, that is - // instantiated using the type of the input vector image and the type of the - // labeled image. + // degree every pixel belongs to a particular class. The classification + // is performed by the \doxygen{ImageClassifierBase} class, that is + // instantiated using the type of the input vector image and the type of + // the labeled image. // // Software Guide : EndLatex @@ -242,11 +239,11 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // // The classifier need a decision rule to be set by the user. Note that we - // must use \code{GetPointer()} in the call of the \code{SetDecisionRule()} - // method because we are passing a SmartPointer, and smart pointer cannot - // perform polymorphism, we must then extract the raw pointer that is - // associated to the smart pointer. This extraction is done with the - // GetPointer() method. + // must use \code{GetPointer()} in the call of the + // \code{SetDecisionRule()} method because we are passing a SmartPointer, + // and smart pointer cannot perform polymorphism, we must then extract the + // raw pointer that is associated to the smart pointer. This extraction is + // done with the GetPointer() method. // // Software Guide : EndLatex @@ -279,7 +276,7 @@ main(int argc, char * argv[]) MembershipFunctionType::CentroidType centroid(1); for (unsigned int i = 0; i < numberOfClasses; ++i) { - MembershipFunctionPointer membershipFunction = + const MembershipFunctionPointer membershipFunction = MembershipFunctionType::New(); centroid[0] = std::stod(argv[i + numberOfArgumentsBeforeMeans]); @@ -303,9 +300,9 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // // We set the Smoothing factor. This factor will multiply the weights that - // define the influence of neighbors on the classification of a given pixel. - // The higher the value, the more uniform will be the regions resulting from - // the classification refinement. + // define the influence of neighbors on the classification of a given + // pixel. The higher the value, the more uniform will be the regions + // resulting from the classification refinement. // // Software Guide : EndLatex @@ -321,9 +318,9 @@ main(int argc, char * argv[]) // classification of any given pixel. Note that despite the fact that we // call this a radius, it is actually the half size of an hypercube. That // is, the actual region of influence will not be circular but rather an - // n-dimensional box. For example, a neighborhood radius of 2 in a 3D image - // will result in a clique of size 5x5x5 pixels, and a radius of 1 will - // result in a clique of size 3x3x3 pixels. + // n-dimensional box. For example, a neighborhood radius of 2 in a 3D + // image will result in a clique of size 5x5x5 pixels, and a radius of 1 + // will result in a clique of size 3x3x3 pixels. // // Software Guide : EndLatex @@ -337,9 +334,9 @@ main(int argc, char * argv[]) // We should now set the weights used for the neighbors. This is done by // passing an array of values that contains the linear sequence of weights // for the neighbors. For example, in a neighborhood of size 3x3x3, we - // should provide a linear array of 9 weight values. The values are packaged - // in a \code{std::vector} and are supposed to be \code{double}. The - // following lines illustrate a typical set of values for a 3x3x3 + // should provide a linear array of 9 weight values. The values are + // packaged in a \code{std::vector} and are supposed to be \code{double}. + // The following lines illustrate a typical set of values for a 3x3x3 // neighborhood. The array is arranged and then passed to the filter by // using the method \code{SetMRFNeighborhoodWeight()}. // @@ -364,16 +361,16 @@ main(int argc, char * argv[]) // We now scale weights so that the smoothing function and the image // fidelity functions have comparable value. This is necessary since the // label image and the input image can have different dynamic ranges. The - // fidelity function is usually computed using a distance function, such as - // the \doxygen{DistanceToCentroidMembershipFunction} or one of the other - // membership functions. They tend to have values in the order of the means - // specified. + // fidelity function is usually computed using a distance function, such + // as the \doxygen{DistanceToCentroidMembershipFunction} or one of the + // other membership functions. They tend to have values in the order of + // the means specified. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet double totalWeight = 0; - for (double weight : weights) + for (const double weight : weights) { totalWeight += weight; } @@ -401,11 +398,12 @@ main(int argc, char * argv[]) // Software Guide : BeginLatex // // The output image produced by the \doxygen{MRFImageFilter} has the same - // pixel type as the labeled input image. In the following lines we use the + // pixel type as the labeled input image. In the following lines we use + // the // \code{OutputImageType} in order to instantiate the type of a - // \doxygen{ImageFileWriter}. Then create one, and connect it to the output - // of the classification filter after passing it through an intensity - // rescaler to rescale it to an 8 bit dynamic range + // \doxygen{ImageFileWriter}. Then create one, and connect it to the + // output of the classification filter after passing it through an + // intensity rescaler to rescale it to an 8 bit dynamic range // // Software Guide : EndLatex @@ -424,40 +422,20 @@ main(int argc, char * argv[]) intensityRescaler->SetOutputMaximum(255); intensityRescaler->SetInput(mrfFilter->GetOutput()); - // Software Guide : BeginCodeSnippet - using WriterType = itk::ImageFileWriter; - - auto writer = WriterType::New(); - - writer->SetInput(intensityRescaler->GetOutput()); - - writer->SetFileName(outputImageFileName); - // Software Guide : EndCodeSnippet - - // Software Guide : BeginLatex // // We are now ready for triggering the execution of the pipeline. This is - // done by simply invoking the \code{Update()} method in the writer. This - // call will propagate the update request to the reader and then to the MRF - // filter. + // done by simply invoking the \code{WriteImage()} function. This call + // will propagate the update request to the MRF filter and writes the + // processed image to the specified file. After the filter has been + // updated, we can get the number of iterations and the stop condition. At + // the end of the program, we close the try block with a catch statement. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet - try - { - writer->Update(); - } - catch (const itk::ExceptionObject & excp) - { - std::cerr << "Problem encountered while writing "; - std::cerr << " image file : " << argv[2] << std::endl; - std::cerr << excp << std::endl; - return EXIT_FAILURE; - } - // Software Guide : EndCodeSnippet + itk::WriteImage(intensityRescaler->GetOutput(), outputImageFileName); std::cout << "Number of Iterations : "; std::cout << mrfFilter->GetNumberOfIterations() << std::endl; @@ -466,6 +444,9 @@ main(int argc, char * argv[]) std::cout << " (2) Error tolerance: " << std::endl; std::cout << mrfFilter->GetStopCondition() << std::endl; + return EXIT_SUCCESS; + // Software Guide : EndCodeSnippet + // Software Guide : BeginLatex // // \begin{figure} \center @@ -482,6 +463,27 @@ main(int argc, char * argv[]) // and the means were estimated by ScalarImageKmeansModelEstimator.cxx. // // Software Guide : EndLatex +} +} // namespace - return EXIT_SUCCESS; +int +main(int argc, char * argv[]) +{ + try + { + return ExampleMain(argc, argv); + } + catch (const itk::ExceptionObject & exceptionObject) + { + std::cerr << "ITK exception caught:\n" << exceptionObject << '\n'; + } + catch (const std::exception & stdException) + { + std::cerr << "std exception caught:\n" << stdException.what() << '\n'; + } + catch (...) + { + std::cerr << "Unhandled exception!\n"; + } + return EXIT_FAILURE; } diff --git a/Examples/Statistics/WeightedSampleStatistics.cxx b/Examples/Statistics/WeightedSampleStatistics.cxx index ca9bd976f36..7539a235573 100644 --- a/Examples/Statistics/WeightedSampleStatistics.cxx +++ b/Examples/Statistics/WeightedSampleStatistics.cxx @@ -84,10 +84,8 @@ class ExampleWeightFunction { return 0.5; } - else - { - return 0.01; - } + + return 0.01; } protected: diff --git a/Examples/Visualization/CannyEdgeDetectionImageFilterConnectVTKITK.py b/Examples/Visualization/CannyEdgeDetectionImageFilterConnectVTKITK.py index 4a4455f8798..3e8d1aa657a 100644 --- a/Examples/Visualization/CannyEdgeDetectionImageFilterConnectVTKITK.py +++ b/Examples/Visualization/CannyEdgeDetectionImageFilterConnectVTKITK.py @@ -67,6 +67,7 @@ rescaler.SetOutputMinimum(0) rescaler.SetOutputMaximum(65535) + # this is to show off the new PyCommand functionality. :) def progressEvent(): print(f"{canny.GetProgress() * 100.0:.0f}{'%'} done...") diff --git a/Modules/Bridge/NumPy/include/itkPyBuffer.h b/Modules/Bridge/NumPy/include/itkPyBuffer.h index f075f3e7ac6..9f294ed4a55 100644 --- a/Modules/Bridge/NumPy/include/itkPyBuffer.h +++ b/Modules/Bridge/NumPy/include/itkPyBuffer.h @@ -73,10 +73,11 @@ class PyBuffer _GetArrayViewFromImage(ImageType * image); /** - * Get an ITK image from a Python array + * Get an ITK image from a contiguous Python array. Internal helper function for the implementation of + * `itkPyBuffer.GetImageViewFromArray`. */ - static const OutputImagePointer - _GetImageViewFromArray(PyObject * arr, PyObject * shape, PyObject * numOfComponent); + static OutputImagePointer + _get_image_view_from_contiguous_array(PyObject * arr, PyObject * shape, PyObject * numOfComponent); }; } // namespace itk diff --git a/Modules/Bridge/NumPy/include/itkPyBuffer.hxx b/Modules/Bridge/NumPy/include/itkPyBuffer.hxx index efd66a500ac..42f176d6361 100644 --- a/Modules/Bridge/NumPy/include/itkPyBuffer.hxx +++ b/Modules/Bridge/NumPy/include/itkPyBuffer.hxx @@ -20,6 +20,8 @@ #include "itkImportImageContainer.h" +#include // For reverse. +#include // For unique_ptr. namespace itk { @@ -28,13 +30,7 @@ template PyObject * PyBuffer::_GetArrayViewFromImage(ImageType * image) { - PyObject * memoryView = NULL; - Py_buffer pyBuffer; - memset(&pyBuffer, 0, sizeof(Py_buffer)); - - Py_ssize_t len = 1; - size_t pixelSize = sizeof(ComponentType); - int res = 0; + Py_buffer pyBuffer{}; if (!image) { @@ -43,134 +39,88 @@ PyBuffer::_GetArrayViewFromImage(ImageType * image) image->Update(); - ComponentType * buffer = - const_cast(reinterpret_cast(image->GetBufferPointer())); - - void * itkImageBuffer = (void *)(buffer); + void * const buffer = image->GetBufferPointer(); // Computing the length of data - const int numberOfComponents = image->GetNumberOfComponentsPerPixel(); - SizeType size = image->GetBufferedRegion().GetSize(); - - for (unsigned int dim = 0; dim < ImageDimension; ++dim) - { - len *= size[dim]; - } - - len *= numberOfComponents; - len *= pixelSize; + const unsigned int numberOfComponents = image->GetNumberOfComponentsPerPixel(); + const SizeValueType numberOfPixels = image->GetBufferedRegion().GetNumberOfPixels(); + const auto len = static_cast(numberOfPixels * numberOfComponents * sizeof(ComponentType)); - res = PyBuffer_FillInfo(&pyBuffer, NULL, (void *)itkImageBuffer, len, 0, PyBUF_CONTIG); - memoryView = PyMemoryView_FromBuffer(&pyBuffer); - - PyBuffer_Release(&pyBuffer); - - return memoryView; + PyBuffer_FillInfo(&pyBuffer, nullptr, buffer, len, 0, PyBUF_CONTIG); + return PyMemoryView_FromBuffer(&pyBuffer); } template auto -PyBuffer::_GetImageViewFromArray(PyObject * arr, PyObject * shape, PyObject * numOfComponent) - -> const OutputImagePointer +PyBuffer::_get_image_view_from_contiguous_array(PyObject * arr, PyObject * shape, PyObject * numOfComponent) + -> OutputImagePointer { - PyObject * shapeseq = NULL; - PyObject * item = NULL; - - Py_ssize_t bufferLength; - Py_buffer pyBuffer; - memset(&pyBuffer, 0, sizeof(Py_buffer)); - - SizeType size; - SizeType sizeFortran; - SizeValueType numberOfPixels = 1; - - const void * buffer; - - long numberOfComponents = 1; - unsigned int dimension = 0; + Py_buffer pyBuffer{}; + SizeType size; - size_t pixelSize = sizeof(ComponentType); - size_t len = 1; - - if (PyObject_GetBuffer(arr, &pyBuffer, PyBUF_ND | PyBUF_ANY_CONTIGUOUS) == -1) + if (PyObject_GetBuffer(arr, &pyBuffer, PyBUF_ANY_CONTIGUOUS) == -1) { - PyErr_SetString(PyExc_RuntimeError, "Cannot get an instance of NumPy array."); - PyBuffer_Release(&pyBuffer); + PyErr_SetString(PyExc_RuntimeError, "Cannot get a contiguous buffer from the specified NumPy array."); return nullptr; } - else - { - bufferLength = pyBuffer.len; - buffer = pyBuffer.buf; - } - PyBuffer_Release(&pyBuffer); - shapeseq = PySequence_Fast(shape, "expected sequence"); - dimension = PySequence_Size(shape); + [[maybe_unused]] const std::unique_ptr bufferScopeGuard(&pyBuffer, + &PyBuffer_Release); - numberOfComponents = PyInt_AsLong(numOfComponent); + const Py_ssize_t bufferLength = pyBuffer.len; + void * const buffer = pyBuffer.buf; + + PyObject * const shapeseq = PySequence_Fast(shape, "expected sequence"); + const unsigned int dimension = PySequence_Size(shape); + + const long numberOfComponents = PyInt_AsLong(numOfComponent); for (unsigned int i = 0; i < dimension; ++i) { - item = PySequence_Fast_GET_ITEM(shapeseq, i); - size[i] = (SizeValueType)PyInt_AsLong(item); - sizeFortran[dimension - 1 - i] = (SizeValueType)PyInt_AsLong(item); - numberOfPixels *= size[i]; + PyObject * const item = PySequence_Fast_GET_ITEM(shapeseq, i); + size[i] = static_cast(PyInt_AsLong(item)); } - bool isFortranContiguous = false; - if (pyBuffer.strides != NULL && pyBuffer.itemsize == pyBuffer.strides[0]) - { - isFortranContiguous = true; - } + const SizeValueType numberOfPixels = size.CalculateProductOfElements(); - len = numberOfPixels * numberOfComponents * pixelSize; - if (bufferLength != len) + const size_t len = numberOfPixels * numberOfComponents * sizeof(ComponentType); + if (bufferLength < 0 || static_cast(bufferLength) != len) { PyErr_SetString(PyExc_RuntimeError, "Size mismatch of image and Buffer."); - PyBuffer_Release(&pyBuffer); SWIG_Py_DECREF(shapeseq); return nullptr; } - IndexType start; - start.Fill(0); - - RegionType region; - region.SetIndex(start); - region.SetSize(size); - if (isFortranContiguous) - { - region.SetSize(sizeFortran); - } - else + if (PyBuffer_IsContiguous(&pyBuffer, 'C') == 0) { - region.SetSize(size); + if (PyBuffer_IsContiguous(&pyBuffer, 'F') == 1) + { + // The buffer is Fortran contiguous (and not C-contiguous), so reverse the size elements. + std::reverse(size.begin(), size.end()); + } + else + { + // The buffer is neither Fortran nor C-contiguous. This is unlikely to happen, because PyBUF_ANY_CONTIGUOUS was + // specified as argument, when retrieving the buffer. But if it _does_ happen, it's obviously an error. + PyErr_SetString(PyExc_RuntimeError, "The buffer should be contiguous, but it is not!"); + return nullptr; + } } - PointType origin; - origin.Fill(0.0); - - SpacingType spacing; - spacing.Fill(1.0); - using InternalPixelType = typename TImage::InternalPixelType; using ImporterType = ImportImageContainer; - auto importer = ImporterType::New(); - constexpr bool importImageFilterWillOwnTheBuffer = false; - InternalPixelType * data = (InternalPixelType *)buffer; + auto importer = ImporterType::New(); + constexpr bool importImageFilterWillOwnTheBuffer = false; + auto * const data = static_cast(buffer); importer->SetImportPointer(data, numberOfPixels, importImageFilterWillOwnTheBuffer); OutputImagePointer output = TImage::New(); - output->SetRegions(region); - output->SetOrigin(origin); - output->SetSpacing(spacing); + output->SetRegions(size); output->SetPixelContainer(importer); output->SetNumberOfComponentsPerPixel(numberOfComponents); SWIG_Py_DECREF(shapeseq); - PyBuffer_Release(&pyBuffer); return output; } diff --git a/Modules/Bridge/NumPy/include/itkPyVectorContainer.h b/Modules/Bridge/NumPy/include/itkPyVectorContainer.h index 3a3bec9a78b..2b8d389dfdf 100644 --- a/Modules/Bridge/NumPy/include/itkPyVectorContainer.h +++ b/Modules/Bridge/NumPy/include/itkPyVectorContainer.h @@ -61,7 +61,7 @@ class PyVectorContainer /** * Get a vnl vector from a Python array */ - static const typename VectorContainerType::Pointer + static typename VectorContainerType::Pointer _vector_container_from_array(PyObject * arr, PyObject * shape); }; diff --git a/Modules/Bridge/NumPy/include/itkPyVectorContainer.hxx b/Modules/Bridge/NumPy/include/itkPyVectorContainer.hxx index 517e854d2d7..cb3627521fb 100644 --- a/Modules/Bridge/NumPy/include/itkPyVectorContainer.hxx +++ b/Modules/Bridge/NumPy/include/itkPyVectorContainer.hxx @@ -18,6 +18,7 @@ #ifndef itkPyVectorContainer_hxx #define itkPyVectorContainer_hxx +#include // For unique_ptr. #include namespace itk @@ -27,12 +28,7 @@ template PyObject * PyVectorContainer::_array_view_from_vector_container(VectorContainerType * vector) { - PyObject * memoryView = NULL; - Py_buffer pyBuffer; - memset(&pyBuffer, 0, sizeof(Py_buffer)); - - size_t elementSize = sizeof(DataType); - int res = 0; + Py_buffer pyBuffer{}; if (!vector) { @@ -41,77 +37,47 @@ PyVectorContainer::_array_view_from_vector_contain DataType * buffer = vector->CastToSTLContainer().data(); - void * vectorBuffer = (void *)(buffer); - // Computing the length of data - Py_ssize_t len = vector->Size(); - len *= elementSize; - - res = PyBuffer_FillInfo(&pyBuffer, NULL, (void *)vectorBuffer, len, 0, PyBUF_CONTIG); - memoryView = PyMemoryView_FromBuffer(&pyBuffer); - - PyBuffer_Release(&pyBuffer); + const auto len = static_cast(vector->size() * sizeof(DataType)); - return memoryView; + PyBuffer_FillInfo(&pyBuffer, nullptr, buffer, len, 0, PyBUF_CONTIG); + return PyMemoryView_FromBuffer(&pyBuffer); } template auto -PyVectorContainer::_vector_container_from_array(PyObject * arr, PyObject * shape) -> const +PyVectorContainer::_vector_container_from_array(PyObject * arr, PyObject * const shape) -> typename VectorContainerType::Pointer { - PyObject * obj = NULL; - PyObject * shapeseq = NULL; - PyObject * item = NULL; - - Py_ssize_t bufferLength; - Py_buffer pyBuffer; - memset(&pyBuffer, 0, sizeof(Py_buffer)); - - size_t numberOfElements = 1; - - const void * buffer; - - unsigned int dimension = 0; - - - size_t elementSize = sizeof(DataType); - size_t len = 1; + Py_buffer pyBuffer{}; if (PyObject_GetBuffer(arr, &pyBuffer, PyBUF_CONTIG) == -1) { PyErr_SetString(PyExc_RuntimeError, "Cannot get an instance of NumPy array."); - PyBuffer_Release(&pyBuffer); return nullptr; } - else - { - bufferLength = pyBuffer.len; - buffer = pyBuffer.buf; - } - obj = shape; - shapeseq = PySequence_Fast(obj, "expected sequence"); - dimension = PySequence_Size(obj); + [[maybe_unused]] const std::unique_ptr bufferScopeGuard(&pyBuffer, + &PyBuffer_Release); - item = PySequence_Fast_GET_ITEM(shapeseq, 0); // Only one dimension - numberOfElements = (size_t)PyInt_AsLong(item); + const Py_ssize_t bufferLength = pyBuffer.len; + const void * const buffer = pyBuffer.buf; - len = numberOfElements * elementSize; - if (bufferLength != len) + PyObject * const shapeseq = PySequence_Fast(shape, "expected sequence"); + const unsigned int dimension = PySequence_Size(shape); + + PyObject * item = PySequence_Fast_GET_ITEM(shapeseq, 0); // Only one dimension + const size_t numberOfElements = static_cast(PyInt_AsLong(item)); + + const size_t len = numberOfElements * sizeof(DataType); + if (bufferLength < 0 || static_cast(bufferLength) != len) { PyErr_SetString(PyExc_RuntimeError, "Size mismatch of vector and Buffer."); - PyBuffer_Release(&pyBuffer); return nullptr; } - DataType * data = (DataType *)buffer; - auto output = VectorContainerType::New(); - output->resize(numberOfElements); - for (size_t ii = 0; ii < numberOfElements; ++ii) - { - output->SetElement(ii, data[ii]); - } - PyBuffer_Release(&pyBuffer); + const auto * const data = static_cast(buffer); + auto output = VectorContainerType::New(); + output->assign(data, data + numberOfElements); return output; } diff --git a/Modules/Bridge/NumPy/include/itkPyVnl.h b/Modules/Bridge/NumPy/include/itkPyVnl.h index 84d9370451e..419a70e0b7c 100644 --- a/Modules/Bridge/NumPy/include/itkPyVnl.h +++ b/Modules/Bridge/NumPy/include/itkPyVnl.h @@ -63,7 +63,7 @@ class PyVnl /** * Get a vnl vector from a Python array */ - static const VectorType + static VectorType _GetVnlVectorFromArray(PyObject * arr, PyObject * shape); /** @@ -75,7 +75,7 @@ class PyVnl /** * Get a vnl matrix from a Python array */ - static const MatrixType + static MatrixType _GetVnlMatrixFromArray(PyObject * arr, PyObject * shape); }; diff --git a/Modules/Bridge/NumPy/include/itkPyVnl.hxx b/Modules/Bridge/NumPy/include/itkPyVnl.hxx index 12e0f4ce68f..e61d9c1e0e2 100644 --- a/Modules/Bridge/NumPy/include/itkPyVnl.hxx +++ b/Modules/Bridge/NumPy/include/itkPyVnl.hxx @@ -18,6 +18,7 @@ #ifndef itkPyVnl_hxx #define itkPyVnl_hxx +#include // For unique_ptr. #include namespace itk @@ -27,12 +28,7 @@ template PyObject * PyVnl::_GetArrayViewFromVnlVector(VectorType * vector) { - PyObject * memoryView = NULL; - Py_buffer pyBuffer; - memset(&pyBuffer, 0, sizeof(Py_buffer)); - - size_t elementSize = sizeof(DataType); - int res = 0; + Py_buffer pyBuffer{}; if (!vector) { @@ -41,85 +37,52 @@ PyVnl::_GetArrayViewFromVnlVector(VectorType * vector) DataType * buffer = vector->data_block(); - void * vectorBuffer = (void *)(buffer); - // Computing the length of data - Py_ssize_t len = vector->size(); - len *= elementSize; - - res = PyBuffer_FillInfo(&pyBuffer, NULL, (void *)vectorBuffer, len, 0, PyBUF_CONTIG); - memoryView = PyMemoryView_FromBuffer(&pyBuffer); - - PyBuffer_Release(&pyBuffer); + const auto len = static_cast(vector->size() * sizeof(DataType)); - return memoryView; + PyBuffer_FillInfo(&pyBuffer, nullptr, buffer, len, 0, PyBUF_CONTIG); + return PyMemoryView_FromBuffer(&pyBuffer); } template auto -PyVnl::_GetVnlVectorFromArray(PyObject * arr, PyObject * shape) -> const VectorType +PyVnl::_GetVnlVectorFromArray(PyObject * arr, PyObject * const shape) -> VectorType { - PyObject * obj = NULL; - PyObject * shapeseq = NULL; - PyObject * item = NULL; - - Py_ssize_t bufferLength; - Py_buffer pyBuffer; - memset(&pyBuffer, 0, sizeof(Py_buffer)); - - size_t numberOfElements = 1; - - const void * buffer; - - unsigned int dimension = 0; - - - size_t elementSize = sizeof(DataType); - size_t len = 1; + Py_buffer pyBuffer{}; if (PyObject_GetBuffer(arr, &pyBuffer, PyBUF_CONTIG) == -1) { PyErr_SetString(PyExc_RuntimeError, "Cannot get an instance of NumPy array."); - PyBuffer_Release(&pyBuffer); return VectorType(); } - else - { - bufferLength = pyBuffer.len; - buffer = pyBuffer.buf; - } - obj = shape; - shapeseq = PySequence_Fast(obj, "expected sequence"); - dimension = PySequence_Size(obj); + [[maybe_unused]] const std::unique_ptr bufferScopeGuard(&pyBuffer, + &PyBuffer_Release); + + const Py_ssize_t bufferLength = pyBuffer.len; + const void * const buffer = pyBuffer.buf; - item = PySequence_Fast_GET_ITEM(shapeseq, 0); // Only one dimension - numberOfElements = (size_t)PyInt_AsLong(item); + PyObject * const shapeseq = PySequence_Fast(shape, "expected sequence"); + const unsigned int dimension = PySequence_Size(shape); - len = numberOfElements * elementSize; - if (bufferLength != len) + PyObject * const item = PySequence_Fast_GET_ITEM(shapeseq, 0); // Only one dimension + const size_t numberOfElements = static_cast(PyInt_AsLong(item)); + + const size_t len = numberOfElements * sizeof(DataType); + if (bufferLength < 0 || static_cast(bufferLength) != len) { PyErr_SetString(PyExc_RuntimeError, "Size mismatch of vector and Buffer."); - PyBuffer_Release(&pyBuffer); return VectorType(); } - DataType * data = (DataType *)buffer; - VectorType output(data, numberOfElements); - PyBuffer_Release(&pyBuffer); - - return output; + const auto * const data = static_cast(buffer); + return VectorType(data, numberOfElements); } template PyObject * PyVnl::_GetArrayViewFromVnlMatrix(MatrixType * matrix) { - PyObject * memoryView = NULL; - Py_buffer pyBuffer; - memset(&pyBuffer, 0, sizeof(Py_buffer)); - - size_t elementSize = sizeof(DataType); - int res = 0; + Py_buffer pyBuffer{}; if (!matrix) { @@ -128,78 +91,54 @@ PyVnl::_GetArrayViewFromVnlMatrix(MatrixType * matrix) DataType * buffer = matrix->data_block(); - void * matrixBuffer = (void *)(buffer); - // Computing the length of data - Py_ssize_t len = matrix->size(); - len *= elementSize; + const auto len = static_cast(matrix->size() * sizeof(DataType)); - res = PyBuffer_FillInfo(&pyBuffer, NULL, (void *)matrixBuffer, len, 0, PyBUF_CONTIG); - memoryView = PyMemoryView_FromBuffer(&pyBuffer); - - PyBuffer_Release(&pyBuffer); - - return memoryView; + PyBuffer_FillInfo(&pyBuffer, nullptr, buffer, len, 0, PyBUF_CONTIG); + return PyMemoryView_FromBuffer(&pyBuffer); } template auto -PyVnl::_GetVnlMatrixFromArray(PyObject * arr, PyObject * shape) -> const MatrixType +PyVnl::_GetVnlMatrixFromArray(PyObject * arr, PyObject * const shape) -> MatrixType { - PyObject * obj = NULL; - PyObject * shapeseq = NULL; - PyObject * item = NULL; - - Py_ssize_t bufferLength; - Py_buffer pyBuffer; - memset(&pyBuffer, 0, sizeof(Py_buffer)); + Py_buffer pyBuffer{}; size_t numberOfElements = 1; - const void * buffer; - - unsigned int dimension = 0; - - size_t elementSize = sizeof(DataType); - size_t len = 1; unsigned int size[2]; if (PyObject_GetBuffer(arr, &pyBuffer, PyBUF_CONTIG) == -1) { PyErr_SetString(PyExc_RuntimeError, "Cannot get an instance of NumPy array."); - PyBuffer_Release(&pyBuffer); return MatrixType(); } - else - { - bufferLength = pyBuffer.len; - buffer = pyBuffer.buf; - } - obj = shape; - shapeseq = PySequence_Fast(obj, "expected sequence"); - dimension = PySequence_Size(obj); + [[maybe_unused]] const std::unique_ptr bufferScopeGuard(&pyBuffer, + &PyBuffer_Release); + + const Py_ssize_t bufferLength = pyBuffer.len; + const void * const buffer = pyBuffer.buf; + + PyObject * const shapeseq = PySequence_Fast(shape, "expected sequence"); + const unsigned int dimension = PySequence_Size(shape); for (unsigned int i = 0; i < 2; ++i) { - item = PySequence_Fast_GET_ITEM(shapeseq, i); + PyObject * const item = PySequence_Fast_GET_ITEM(shapeseq, i); size[i] = static_cast(PyInt_AsLong(item)); numberOfElements *= size[i]; } - len = numberOfElements * elementSize; - if (bufferLength != len) + const size_t len = numberOfElements * sizeof(DataType); + if (bufferLength < 0 || static_cast(bufferLength) != len) { PyErr_SetString(PyExc_RuntimeError, "Size mismatch of matrix and Buffer."); - PyBuffer_Release(&pyBuffer); return MatrixType(); } - DataType * data = (DataType *)buffer; - MatrixType output(data, size[0], size[1]); - PyBuffer_Release(&pyBuffer); - - return output; + const auto * const data = static_cast(buffer); + return MatrixType(data, size[0], size[1]); } diff --git a/Modules/Bridge/NumPy/wrapping/PyBuffer.i.in b/Modules/Bridge/NumPy/wrapping/PyBuffer.i.in index 3257e06c252..22a95428726 100644 --- a/Modules/Bridge/NumPy/wrapping/PyBuffer.i.in +++ b/Modules/Bridge/NumPy/wrapping/PyBuffer.i.in @@ -99,11 +99,11 @@ if is_vector: if ndarr.flags['C_CONTIGUOUS']: - imgview = itkPyBuffer@PyBufferTypes@._GetImageViewFromArray(ndarr, ndarr.shape[-2::-1], ndarr.shape[-1]) + imgview = itkPyBuffer@PyBufferTypes@._get_image_view_from_contiguous_array(ndarr, ndarr.shape[-2::-1], ndarr.shape[-1]) else: - imgview = itkPyBuffer@PyBufferTypes@._GetImageViewFromArray(ndarr, ndarr.shape[-1:0:-1], ndarr.shape[0]) + imgview = itkPyBuffer@PyBufferTypes@._get_image_view_from_contiguous_array(ndarr, ndarr.shape[-1:0:-1], ndarr.shape[0]) else: - imgview = itkPyBuffer@PyBufferTypes@._GetImageViewFromArray(ndarr, ndarr.shape[::-1], 1) + imgview = itkPyBuffer@PyBufferTypes@._get_image_view_from_contiguous_array(ndarr, ndarr.shape[::-1], 1) # Keep a reference imgview._SetBase(ndarr) diff --git a/Modules/Bridge/NumPy/wrapping/test/itkPyBufferTest.py b/Modules/Bridge/NumPy/wrapping/test/itkPyBufferTest.py index e22418992c3..2f7bdc4685a 100644 --- a/Modules/Bridge/NumPy/wrapping/test/itkPyBufferTest.py +++ b/Modules/Bridge/NumPy/wrapping/test/itkPyBufferTest.py @@ -91,6 +91,7 @@ def test_EmptyImage_pickle(self): # scalarImage.Allocate(True) import pickle + pickled = pickle.dumps(image) reloaded = pickle.loads(pickled) reloaded_spacing = reloaded.GetSpacing() diff --git a/Modules/Bridge/VTK/include/itkVTKImageExport.h b/Modules/Bridge/VTK/include/itkVTKImageExport.h index 1c0747e6d3b..6984c12ffbb 100644 --- a/Modules/Bridge/VTK/include/itkVTKImageExport.h +++ b/Modules/Bridge/VTK/include/itkVTKImageExport.h @@ -73,16 +73,16 @@ class ITK_TEMPLATE_EXPORT VTKImageExport : public VTKImageExportBase /** The type of the input image. */ using InputImageType = TInputImage; -#ifdef ITK_USE_CONCEPT_CHECKING itkConceptMacro(ImageDimensionCheck, (Concept::SameDimensionOrMinusOneOrTwo<3, Self::InputImageDimension>)); -#endif + /** Set the input image of this image exporter. */ + /** @ITKStartGrouping */ using Superclass::SetInput; void SetInput(const InputImageType *); InputImageType * GetInput(); - + /** @ITKEndGrouping */ protected: VTKImageExport(); ~VTKImageExport() override = default; diff --git a/Modules/Bridge/VTK/include/itkVTKImageExport.hxx b/Modules/Bridge/VTK/include/itkVTKImageExport.hxx index c6fcc23a94f..23df337715e 100644 --- a/Modules/Bridge/VTK/include/itkVTKImageExport.hxx +++ b/Modules/Bridge/VTK/include/itkVTKImageExport.hxx @@ -137,16 +137,16 @@ template int * VTKImageExport::WholeExtentCallback() { - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); if (!input) { itkExceptionMacro("Need to set an input"); } - InputRegionType region = input->GetLargestPossibleRegion(); - InputSizeType size = region.GetSize(); - InputIndexType index = region.GetIndex(); + const InputRegionType region = input->GetLargestPossibleRegion(); + InputSizeType size = region.GetSize(); + InputIndexType index = region.GetIndex(); unsigned int i = 0; // Fill in the known portion of the extent. @@ -172,7 +172,7 @@ template double * VTKImageExport::SpacingCallback() { - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); if (!input) { @@ -203,7 +203,7 @@ template float * VTKImageExport::FloatSpacingCallback() { - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); const typename TInputImage::SpacingType & spacing = input->GetSpacing(); @@ -229,7 +229,7 @@ template double * VTKImageExport::OriginCallback() { - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); if (!input) { @@ -260,7 +260,7 @@ template float * VTKImageExport::FloatOriginCallback() { - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); const typename TInputImage::PointType & origin = input->GetOrigin(); @@ -286,7 +286,7 @@ template double * VTKImageExport::DirectionCallback() { - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); if (!input) { @@ -360,7 +360,7 @@ VTKImageExport::PropagateUpdateExtentCallback(int * extent) const InputRegionType region(index, size); - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); if (!input) { itkExceptionMacro("Need to set an input"); @@ -379,16 +379,16 @@ template int * VTKImageExport::DataExtentCallback() { - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); if (!input) { itkExceptionMacro("Need to set an input"); } - InputRegionType region = input->GetBufferedRegion(); - InputSizeType size = region.GetSize(); - InputIndexType index = region.GetIndex(); + const InputRegionType region = input->GetBufferedRegion(); + InputSizeType size = region.GetSize(); + InputIndexType index = region.GetIndex(); unsigned int i = 0; for (; i < InputImageDimension; ++i) @@ -412,7 +412,7 @@ template void * VTKImageExport::BufferPointerCallback() { - InputImagePointer input = this->GetInput(); + const InputImagePointer input = this->GetInput(); if (!input) { diff --git a/Modules/Bridge/VTK/include/itkVTKImageExportBase.h b/Modules/Bridge/VTK/include/itkVTKImageExportBase.h index 57b19095492..d130fe0304c 100644 --- a/Modules/Bridge/VTK/include/itkVTKImageExportBase.h +++ b/Modules/Bridge/VTK/include/itkVTKImageExportBase.h @@ -54,6 +54,7 @@ class ITKVTK_EXPORT VTKImageExportBase : public ProcessObject GetCallbackUserData(); /** The function pointer type expected for a callback. */ + /** @ITKStartGrouping */ using UpdateInformationCallbackType = void (*)(void *); using PipelineModifiedCallbackType = int (*)(void *); using WholeExtentCallbackType = int * (*)(void *); @@ -66,11 +67,12 @@ class ITKVTK_EXPORT VTKImageExportBase : public ProcessObject using UpdateDataCallbackType = void (*)(void *); using DataExtentCallbackType = int * (*)(void *); using BufferPointerCallbackType = void * (*)(void *); - + /** @ITKEndGrouping */ /** Compatibility for VTK older than 4.4. */ + /** @ITKStartGrouping */ using FloatSpacingCallbackType = float * (*)(void *); using FloatOriginCallbackType = float * (*)(void *); - + /** @ITKEndGrouping */ /** * \class CallbackTypeProxy * \brief Provide compatibility between VTK 4.4 and earlier versions. diff --git a/Modules/Bridge/VTK/include/itkVTKImageImport.h b/Modules/Bridge/VTK/include/itkVTKImageImport.h index 80eddabd1a8..99a9b869fad 100644 --- a/Modules/Bridge/VTK/include/itkVTKImageImport.h +++ b/Modules/Bridge/VTK/include/itkVTKImageImport.h @@ -83,6 +83,7 @@ class ITK_TEMPLATE_EXPORT VTKImageImport : public ImageSource /** These are function pointer types for the pipeline connection * callbacks. */ + /** @ITKStartGrouping */ using UpdateInformationCallbackType = void (*)(void *); using PipelineModifiedCallbackType = int (*)(void *); using WholeExtentCallbackType = int * (*)(void *); @@ -95,24 +96,29 @@ class ITK_TEMPLATE_EXPORT VTKImageImport : public ImageSource using UpdateDataCallbackType = void (*)(void *); using DataExtentCallbackType = int * (*)(void *); using BufferPointerCallbackType = void * (*)(void *); - + /** @ITKEndGrouping */ /** Compatibility for VTK older than 4.4. */ + /** @ITKStartGrouping */ using FloatSpacingCallbackType = float * (*)(void *); using FloatOriginCallbackType = float * (*)(void *); - + /** @ITKEndGrouping */ /** What to do when receiving UpdateInformation(). */ + /** @ITKStartGrouping */ itkSetMacro(UpdateInformationCallback, UpdateInformationCallbackType); itkGetConstMacro(UpdateInformationCallback, UpdateInformationCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving PipelineModified(). */ + /** @ITKStartGrouping */ itkSetMacro(PipelineModifiedCallback, PipelineModifiedCallbackType); itkGetConstMacro(PipelineModifiedCallback, PipelineModifiedCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving SetWholeExtent(). */ + /** @ITKStartGrouping */ itkSetMacro(WholeExtentCallback, WholeExtentCallbackType); itkGetConstMacro(WholeExtentCallback, WholeExtentCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving SetSpacing(). */ + /** @ITKStartGrouping */ itkSetMacro(SpacingCallback, SpacingCallbackType); itkGetConstMacro(SpacingCallback, SpacingCallbackType); itkSetMacro(FloatSpacingCallback, FloatSpacingCallbackType); @@ -122,8 +128,9 @@ class ITK_TEMPLATE_EXPORT VTKImageImport : public ImageSource { this->SetFloatSpacingCallback(f); } - + /** @ITKEndGrouping */ /** What to do when receiving SetOrigin(). */ + /** @ITKStartGrouping */ itkSetMacro(OriginCallback, OriginCallbackType); itkGetConstMacro(OriginCallback, OriginCallbackType); itkSetMacro(FloatOriginCallback, FloatOriginCallbackType); @@ -133,39 +140,47 @@ class ITK_TEMPLATE_EXPORT VTKImageImport : public ImageSource { this->SetFloatOriginCallback(f); } - + /** @ITKEndGrouping */ /** What to do when receiving SetDirection(). */ + /** @ITKStartGrouping */ itkSetMacro(DirectionCallback, DirectionCallbackType); itkGetConstMacro(DirectionCallback, DirectionCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving UpdateInformation(). */ + /** @ITKStartGrouping */ itkSetMacro(ScalarTypeCallback, ScalarTypeCallbackType); itkGetConstMacro(ScalarTypeCallback, ScalarTypeCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving SetNumberOfComponents(). */ + /** @ITKStartGrouping */ itkSetMacro(NumberOfComponentsCallback, NumberOfComponentsCallbackType); itkGetConstMacro(NumberOfComponentsCallback, NumberOfComponentsCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving PropagateUpdateExtent(). */ + /** @ITKStartGrouping */ itkSetMacro(PropagateUpdateExtentCallback, PropagateUpdateExtentCallbackType); itkGetConstMacro(PropagateUpdateExtentCallback, PropagateUpdateExtentCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving UpdateData(). */ + /** @ITKStartGrouping */ itkSetMacro(UpdateDataCallback, UpdateDataCallbackType); itkGetConstMacro(UpdateDataCallback, UpdateDataCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving DataExtent(). */ + /** @ITKStartGrouping */ itkSetMacro(DataExtentCallback, DataExtentCallbackType); itkGetConstMacro(DataExtentCallback, DataExtentCallbackType); - + /** @ITKEndGrouping */ /** What to do when receiving BufferPointer(). */ + /** @ITKStartGrouping */ itkSetMacro(BufferPointerCallback, BufferPointerCallbackType); itkGetConstMacro(BufferPointerCallback, BufferPointerCallbackType); - + /** @ITKEndGrouping */ /** Specify callback data. */ + /** @ITKStartGrouping */ itkSetMacro2(CallbackUserData, void *); itkGetConstMacro(CallbackUserData, void *); - + /** @ITKEndGrouping */ protected: VTKImageImport(); ~VTKImageImport() override = default; diff --git a/Modules/Bridge/VTK/include/itkVTKImageImport.hxx b/Modules/Bridge/VTK/include/itkVTKImageImport.hxx index 5e53427ecf3..f64aefc34e4 100644 --- a/Modules/Bridge/VTK/include/itkVTKImageImport.hxx +++ b/Modules/Bridge/VTK/include/itkVTKImageImport.hxx @@ -112,9 +112,9 @@ VTKImageImport::PropagateRequestedRegion(DataObject * outputPtr) Superclass::PropagateRequestedRegion(output); if (m_PropagateUpdateExtentCallback) { - OutputRegionType region = output->GetRequestedRegion(); - OutputSizeType size = region.GetSize(); - OutputIndexType index = region.GetIndex(); + const OutputRegionType region = output->GetRequestedRegion(); + OutputSizeType size = region.GetSize(); + OutputIndexType index = region.GetIndex(); int updateExtent[6]; unsigned int i = 0; @@ -163,7 +163,7 @@ VTKImageImport::GenerateOutputInformation() Superclass::GenerateOutputInformation(); // get pointer to the output - OutputImagePointer output = this->GetOutput(); + const OutputImagePointer output = this->GetOutput(); if (m_WholeExtentCallback) { @@ -293,7 +293,7 @@ VTKImageImport::GenerateData() if (m_DataExtentCallback && m_BufferPointerCallback) { // get pointer to the output - OutputImagePointer output = this->GetOutput(); + const OutputImagePointer output = this->GetOutput(); int * extent = (m_DataExtentCallback)(m_CallbackUserData); OutputIndexType index; diff --git a/Modules/Bridge/VTK/src/itkVTKImageExportBase.cxx b/Modules/Bridge/VTK/src/itkVTKImageExportBase.cxx index 87c103a3592..40e3ca9bf88 100644 --- a/Modules/Bridge/VTK/src/itkVTKImageExportBase.cxx +++ b/Modules/Bridge/VTK/src/itkVTKImageExportBase.cxx @@ -23,10 +23,7 @@ namespace itk * Constructor sets up information for the image-type indepenedent * callbacks implemented in this superclass. */ -VTKImageExportBase::VTKImageExportBase() -{ - m_LastPipelineMTime = 0; -} +VTKImageExportBase::VTKImageExportBase() { m_LastPipelineMTime = 0; } void VTKImageExportBase::PrintSelf(std::ostream & os, Indent indent) const @@ -136,7 +133,7 @@ VTKImageExportBase::UpdateInformationCallback() int VTKImageExportBase::PipelineModifiedCallback() { - DataObjectPointer input = this->GetInput(0); + const DataObjectPointer input = this->GetInput(0); if (!input) { @@ -162,10 +159,8 @@ VTKImageExportBase::PipelineModifiedCallback() m_LastPipelineMTime = pipelineMTime; return 1; } - else - { - return 0; - } + + return 0; } /** @@ -176,7 +171,7 @@ void VTKImageExportBase::UpdateDataCallback() { // Get the input. - DataObjectPointer input = this->GetInput(0); + const DataObjectPointer input = this->GetInput(0); if (!input) { diff --git a/Modules/Bridge/VtkGlue/include/itkViewImage.hxx b/Modules/Bridge/VtkGlue/include/itkViewImage.hxx index 55ec5984d49..c1846e93735 100644 --- a/Modules/Bridge/VtkGlue/include/itkViewImage.hxx +++ b/Modules/Bridge/VtkGlue/include/itkViewImage.hxx @@ -101,8 +101,8 @@ ViewImage::View(const ImageType * img, const std::string & winTitle, siz cam->GetViewUp(vup); for (unsigned int i = 0; i < 3; ++i) { - pos[i] = -pos[i]; - vup[i] = -vup[i]; + pos[i] *= -1; + vup[i] *= -1; } cam->SetPosition(pos); cam->SetViewUp(vup); diff --git a/Modules/Bridge/VtkGlue/src/QuickView.cxx b/Modules/Bridge/VtkGlue/src/QuickView.cxx index 287684053e4..ee7527236f9 100644 --- a/Modules/Bridge/VtkGlue/src/QuickView.cxx +++ b/Modules/Bridge/VtkGlue/src/QuickView.cxx @@ -58,27 +58,27 @@ using FloatImageType = itk::Image; using DoubleImageType = itk::Image; template void ITKVtkGlue_EXPORT - QuickView::AddImage(CharImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(CharImageType * image, bool FlipVertical, std::string Description); template void ITKVtkGlue_EXPORT - QuickView::AddImage(UnsignedShortImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(UnsignedShortImageType * image, bool FlipVertical, std::string Description); template void ITKVtkGlue_EXPORT - QuickView::AddImage(ShortImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(ShortImageType * image, bool FlipVertical, std::string Description); template void ITKVtkGlue_EXPORT - QuickView::AddImage(UnsignedIntImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(UnsignedIntImageType * image, bool FlipVertical, std::string Description); template void ITKVtkGlue_EXPORT - QuickView::AddImage(IntImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(IntImageType * image, bool FlipVertical, std::string Description); template void ITKVtkGlue_EXPORT - QuickView::AddImage(UnsignedLongImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(UnsignedLongImageType * image, bool FlipVertical, std::string Description); template void ITKVtkGlue_EXPORT - QuickView::AddImage(LongImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(LongImageType * image, bool FlipVertical, std::string Description); template void ITKVtkGlue_EXPORT - QuickView::AddImage(FloatImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(FloatImageType * image, bool FlipVertical, std::string Description); template void ITKVtkGlue_EXPORT - QuickView::AddImage(DoubleImageType * image, bool FlipVertical, std::string Description); +QuickView::AddImage(DoubleImageType * image, bool FlipVertical, std::string Description); template <> void ITKVtkGlue_EXPORT - QuickView::AddImage(UnsignedCharImageType * image, bool FlipVertical, std::string Description) +QuickView::AddImage(UnsignedCharImageType * image, bool FlipVertical, std::string Description) { if (FlipVertical) { @@ -101,7 +101,7 @@ void ITKVtkGlue_EXPORT template void ITK_TEMPLATE_EXPORT - QuickView::AddImage(TImage * image, bool FlipVertical, std::string Description) +QuickView::AddImage(TImage * image, bool FlipVertical, std::string Description) { using rescaleFilterType = itk::RescaleIntensityImageFilter; @@ -116,7 +116,7 @@ void ITK_TEMPLATE_EXPORT template <> void ITKVtkGlue_EXPORT - QuickView::AddImage(UnsignedCharRGBImageType * image, +QuickView::AddImage(UnsignedCharRGBImageType * image, bool FlipVertical, std::string Description) { @@ -141,7 +141,7 @@ void ITKVtkGlue_EXPORT template <> void ITKVtkGlue_EXPORT - QuickView::AddRGBImage(UnsignedCharRGBImageType * image, +QuickView::AddRGBImage(UnsignedCharRGBImageType * image, bool FlipVertical, std::string Description) { @@ -166,7 +166,7 @@ void ITKVtkGlue_EXPORT template <> void ITKVtkGlue_EXPORT - QuickView::AddRGBImage(FloatRGBImageType * image, bool FlipVertical, std::string Description) +QuickView::AddRGBImage(FloatRGBImageType * image, bool FlipVertical, std::string Description) { using AdaptorType = itk::RGBToVectorImageAdaptor; AdaptorType::Pointer adaptor = AdaptorType::New(); @@ -182,7 +182,7 @@ void ITKVtkGlue_EXPORT template <> void ITKVtkGlue_EXPORT - QuickView::AddImage(FloatRGBImageType * image, bool FlipVertical, std::string Description) +QuickView::AddImage(FloatRGBImageType * image, bool FlipVertical, std::string Description) { using AdaptorType = itk::RGBToVectorImageAdaptor; AdaptorType::Pointer adaptor = AdaptorType::New(); diff --git a/Modules/Bridge/VtkGlue/test/itkImageToVTKImageFilterTest.cxx b/Modules/Bridge/VtkGlue/test/itkImageToVTKImageFilterTest.cxx index cc78c0051a5..72556d2fc2f 100644 --- a/Modules/Bridge/VtkGlue/test/itkImageToVTKImageFilterTest.cxx +++ b/Modules/Bridge/VtkGlue/test/itkImageToVTKImageFilterTest.cxx @@ -25,7 +25,7 @@ int itkImageToVTKImageFilterTest(int, char *[]) { - const int dim = 3; + constexpr int dim = 3; using ImageType = itk::Image; using SourceType = itk::RandomImageSource; using SpacingType = SourceType::SpacingType; @@ -48,8 +48,7 @@ itkImageToVTKImageFilterTest(int, char *[]) origin[0] = -1.5; origin[1] = 0.222; origin[2] = 0; - DirectionType direction; - direction.Fill(0.0); + DirectionType direction{}; direction[0][1] = 1; direction[1][0] = -1; direction[2][2] = 0.7; diff --git a/Modules/Bridge/VtkGlue/test/itkVTKImageToImageFilterTest.cxx b/Modules/Bridge/VtkGlue/test/itkVTKImageToImageFilterTest.cxx index b09a918364e..5f1c3a4b49b 100644 --- a/Modules/Bridge/VtkGlue/test/itkVTKImageToImageFilterTest.cxx +++ b/Modules/Bridge/VtkGlue/test/itkVTKImageToImageFilterTest.cxx @@ -25,7 +25,7 @@ int itkVTKImageToImageFilterTest(int, char *[]) { - const int dim = 2; + constexpr int dim = 2; using ImageType = itk::Image; using VTKNoiseType = vtkSmartPointer; using ConnectorType = itk::VTKImageToImageFilter; diff --git a/Modules/Bridge/VtkGlue/test/itkVtkConnectedComponentImageFilterTest.cxx b/Modules/Bridge/VtkGlue/test/itkVtkConnectedComponentImageFilterTest.cxx index eaa51f664c1..ea849dca2c7 100644 --- a/Modules/Bridge/VtkGlue/test/itkVtkConnectedComponentImageFilterTest.cxx +++ b/Modules/Bridge/VtkGlue/test/itkVtkConnectedComponentImageFilterTest.cxx @@ -103,8 +103,7 @@ itkVtkConnectedComponentImageFilterTest(int argc, char * argv[]) filterContainer["Triangle"] = TriangleFilterType::New(); filterContainer["Yen"] = YenFilterType::New(); - auto it = filterContainer.begin(); - for (it = filterContainer.begin(); it != filterContainer.end(); ++it) + for (auto it = filterContainer.begin(); it != filterContainer.end(); ++it) { it->second->SetInsideValue(255); it->second->SetOutsideValue(0); diff --git a/Modules/Bridge/VtkGlue/test/itkVtkMedianFilterTest.cxx b/Modules/Bridge/VtkGlue/test/itkVtkMedianFilterTest.cxx index ff68e5619ee..0c53d92691a 100644 --- a/Modules/Bridge/VtkGlue/test/itkVtkMedianFilterTest.cxx +++ b/Modules/Bridge/VtkGlue/test/itkVtkMedianFilterTest.cxx @@ -50,9 +50,8 @@ itkVtkMedianFilterTest(int argc, char * argv[]) reader->SetFileName(inputFilename); // Create and setup a median filter - auto medianFilter = FilterType::New(); - FilterType::InputSizeType radius; - radius.Fill(2); + auto medianFilter = FilterType::New(); + auto radius = FilterType::InputSizeType::Filled(2); if (argc > 2) { radius.Fill(std::stoi(argv[2])); diff --git a/Modules/Bridge/VtkGlue/wrapping/VtkGlue.i b/Modules/Bridge/VtkGlue/wrapping/VtkGlue.i index b8482f2b27d..54d41993bd9 100644 --- a/Modules/Bridge/VtkGlue/wrapping/VtkGlue.i +++ b/Modules/Bridge/VtkGlue/wrapping/VtkGlue.i @@ -1,4 +1,4 @@ -/* This file declares various VTK datatype to SWIG so they can be refered as*/ +/* This file declares various VTK datatype to SWIG so they can be referred as*/ /* something else than SwigObject*/ /* Python bindings have been tested successfully.*/ /* TODO: Test TCL bindings*/ diff --git a/Modules/Compatibility/Deprecated/include/itkAtomicInt.h b/Modules/Compatibility/Deprecated/include/itkAtomicInt.h deleted file mode 100644 index 9af70976769..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkAtomicInt.h +++ /dev/null @@ -1,306 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Program: Visualization Toolkit - * Module: vtkAtomicInt.h - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * All rights reserved. - * See Copyright.txt or https://www.kitware.com/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 notice for more information. - * - *=========================================================================*/ - -#ifndef itkAtomicInt_h -#define itkAtomicInt_h - -#include "itkMacro.h" -#include "itkIntTypes.h" -#include "itkAtomicIntDetail.h" -#include "itkConceptChecking.h" - -#include -#include // For ptrdiff_t. - - -namespace itk -{ - -/** - * \class AtomicInt - * \brief Provides support for atomic integers - * - * - * Objects of atomic types are C++ objects that are free from data races; - * that is, if one thread writes to an atomic object while another thread - * reads from it, the behavior is well-defined. AtomicInt provides - * a subset of the std::atomic API and implementation, for 32 bit and 64 bit - * integers and pointer types. For these types, AtomicInt defines a - * number of operations that happen atomically - without interruption - * by another thread. Furthermore, these operations happen in a - * sequentially-consistent way and use full memory fences. This means - * that operations relating to atomic variables happen in the specified - * order and the results are made visible to other processing cores to - * guarantee proper sequential operation. Other memory access patterns - * supported by std::atomic are not currently supported. - * - * Note that when atomic operations are not available on a particular - * platform or compiler, mutexes, which are significantly slower, are used - * as a fallback. - * - * \ingroup ITKDeprecated - */ -template -class AtomicInt -{ -private: - using Impl = Detail::AtomicOps; - using ValueType = typename Impl::ValueType; - itkConceptMacro(SupportedInteger, (Detail::IsAtomicSupportedIntegralType)); - -public: - AtomicInt() - : m_Object(0) - {} - - AtomicInt(T val) - : m_Object(static_cast(val)) - {} - - AtomicInt(const AtomicInt & ai) - : m_Object(static_cast(ai.load())) - {} - - T - operator++() - { - return static_cast(++m_Object); - } - - T - operator++(int) - { - return static_cast(m_Object++); - } - - T - operator--() - { - return static_cast(--m_Object); - } - - T - operator--(int) - { - return static_cast(m_Object--); - } - - T - operator+=(T val) - { - return static_cast(m_Object += static_cast(val)); - } - - T - operator-=(T val) - { - return static_cast(m_Object -= static_cast(val)); - } - - operator T() const { return static_cast(m_Object.load()); } - - T - operator=(T val) - { - m_Object.store(static_cast(val)); - return val; - } - - AtomicInt & - operator=(const AtomicInt & ai) - { - this->store(ai.load()); - return *this; - } - - T - load() const - { - return static_cast(m_Object.load()); - } - - void - store(T val) - { - m_Object.store(static_cast(val)); - } - -private: - std::atomic::ValueType> m_Object; -}; - - -template -class AtomicInt -{ -private: - using Impl = Detail::AtomicOps; - using ValueType = typename Impl::ValueType; - -public: - AtomicInt() - : m_Object(0) - {} - - AtomicInt(T * val) - : m_Object(reinterpret_cast(val)) - {} - - AtomicInt(const AtomicInt & ai) - : m_Object(reinterpret_cast(ai.load())) - {} - - T * - operator++() - { - return reinterpret_cast(m_Object.fetch_add(sizeof(T)) + sizeof(T)); - } - - T * - operator++(int) - { - return reinterpret_cast(m_Object.fetch_add(sizeof(T))); - } - - T * - operator--() - { - return reinterpret_cast(m_Object.fetch_sub(sizeof(T)) - sizeof(T)); - } - - T * - operator--(int) - { - return reinterpret_cast(m_Object.fetch_sub(sizeof(T))); - } - - T * - operator+=(ptrdiff_t val) - { - return reinterpret_cast(m_Object += val * sizeof(T)); - } - - T * - operator-=(ptrdiff_t val) - { - return reinterpret_cast(m_Object -= val * sizeof(T)); - } - - operator T *() const { return reinterpret_cast(m_Object.load()); } - - T * - operator=(T * val) - { - m_Object.store(reinterpret_cast(val)); - return val; - } - - AtomicInt & - operator=(const AtomicInt & ai) - { - this->store(ai.load()); - return *this; - } - - T * - load() const - { - return reinterpret_cast(m_Object.load()); - } - - void - store(T * val) - { - m_Object.store(reinterpret_cast(val)); - } - -private: - std::atomic::ValueType> m_Object; -}; - - -template <> -class AtomicInt -{ -private: - using Impl = Detail::AtomicOps; - using ValueType = Impl::ValueType; - -public: - AtomicInt() - : m_Object(0) - {} - - AtomicInt(void * val) - : m_Object(reinterpret_cast(val)) - {} - - AtomicInt(const AtomicInt & ai) - : m_Object(reinterpret_cast(ai.load())) - {} - - operator void *() const { return reinterpret_cast(m_Object.load()); } - - void * - operator=(void * val) - { - m_Object.store(reinterpret_cast(val)); - return val; - } - - AtomicInt & - operator=(const AtomicInt & ai) - { - this->store(ai.load()); - return *this; - } - - void * - load() const - { - return reinterpret_cast(m_Object.load()); - } - - void - store(void * val) - { - m_Object.store(reinterpret_cast(val)); - } - -private: - std::atomic::ValueType> m_Object; -}; - - -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkAtomicIntDetail.h b/Modules/Compatibility/Deprecated/include/itkAtomicIntDetail.h deleted file mode 100644 index e8aeb7767e2..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkAtomicIntDetail.h +++ /dev/null @@ -1,101 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Program: Visualization Toolkit - * Module: vtkAtomicInt.h - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * All rights reserved. - * See Copyright.txt or https://www.kitware.com/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 notice for more information. - * - *=========================================================================*/ - -#ifndef itkAtomicIntDetail_h -#define itkAtomicIntDetail_h - -#include "itkMacro.h" -#include "itkConceptChecking.h" - -#include - -namespace itk -{ - -namespace Detail -{ - -template -struct BaseType; - -template -class AtomicOps -{ -public: - using AtomicType = typename BaseType::Type; - using ValueType = typename BaseType::Type; -}; - - -template <> -struct BaseType<8> -{ - itkAlignedTypedef(8, int64_t, Type); -}; - -template <> -struct BaseType<4> -{ - itkAlignedTypedef(4, int32_t, Type); -}; - -template -struct IsAtomicSupportedIntegralType -{ - using Self = IsAtomicSupportedIntegralType; - struct Constraints - { - using TrueT = Concept::Detail::UniqueType_bool; - using SpecializedT = Concept::Detail::UniqueType_bool::is_specialized>; - using IntegralT = Concept::Detail::UniqueType_bool::is_integer>; - using SizeT = Concept::Detail::UniqueType_bool; - void - constraints() - { - IntegralT a = TrueT(); - IntegralT b = TrueT(); - IntegralT c = TrueT(); - - IgnoreUnusedVariable(a); - IgnoreUnusedVariable(b); - IgnoreUnusedVariable(c); - } - }; - - - itkConceptConstraintsMacro(); -}; - -} // end namespace Detail -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkBarrier.h b/Modules/Compatibility/Deprecated/include/itkBarrier.h deleted file mode 100644 index cbc5c4ccbd6..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkBarrier.h +++ /dev/null @@ -1,87 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkBarrier_h -#define itkBarrier_h - -#include "itkLightObject.h" -#include "itkObjectFactory.h" -#include "ITKDeprecatedExport.h" -#include -#include - -namespace itk -{ -/** - * \class Barrier - * \brief Standard barrier class implementation for synchronizing the execution - * of threads. - * - * A barrier class is used to synchronize threaded execution by allowing - * threads to block until each has reached a desired state. As each thread - * enters the barrier it blocks. When all threads have entered the barrier, - * all released and continue to execute. - * - * A thread enters the barrier by calling Barrier::Wait() on the barrier - * class. To set up a barrier class, call Barrier::Initialize(unsigned int), - * specifying the number of waiting threads that will trigger a release of the - * barrier as the argument. - * - * NOTE: This class is only compatible with PlatformMultiThreader! - * - * \ingroup ITKDeprecated - */ -class ITKDeprecated_EXPORT Barrier : public LightObject -{ -public: - /** Standard class type aliases. */ - using Self = Barrier; - using Superclass = LightObject; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(Barrier); - - /** Creates a new system variable used to implement the barrier. The - argument to this method is the number of threads that must Wait() on the - barrier before it is cleared. */ - void - Initialize(unsigned int); - - /** A thread calling this method waits until m_NumberOfThreads have called - * Wait() on the barrier. When the final expected thread calls Wait(), all - * threads are released. */ - void - Wait(); - -private: - Barrier(); - ~Barrier() override; - - unsigned int m_NumberArrived{ 0 }; - unsigned int m_NumberExpected{ 0 }; - unsigned int m_Generation{ 0 }; // Allows successive waits - std::condition_variable m_ConditionVariable{}; - std::mutex m_Mutex{}; -}; -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkChildTreeIterator.h b/Modules/Compatibility/Deprecated/include/itkChildTreeIterator.h deleted file mode 100644 index 68166ac1263..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkChildTreeIterator.h +++ /dev/null @@ -1,94 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkChildTreeIterator_h -#define itkChildTreeIterator_h - -#include "itkTreeIteratorBase.h" - -namespace itk -{ -template -class ITK_TEMPLATE_EXPORT ChildTreeIterator : public TreeIteratorBase -{ -public: - /** Typedefs */ - using Self = ChildTreeIterator; - using Superclass = TreeIteratorBase; - using TreeType = TTreeType; - using ValueType = typename TTreeType::ValueType; - using typename Superclass::TreeNodeType; - using ChildIdentifier = typename TreeNodeType::ChildIdentifier; - using typename Superclass::NodeType; - - /** Constructor */ - ChildTreeIterator(TreeType * tree, const TreeNodeType * start = nullptr); - - /** Constructor */ - ChildTreeIterator(const TreeIteratorBase & iterator); - - /** Get the type of the iterator. */ - NodeType - GetType() const override; - - /** Go to a specific child node. */ - bool - GoToChild(ChildIdentifier number = 0) override; - - /** Go to the parent node. */ - bool - GoToParent() override; - - /** Clone function */ - TreeIteratorBase * - Clone() override; - - /** operator = */ - Self & - operator=(Superclass & iterator) - { - if (this != &iterator) - { - Superclass::operator=(iterator); - auto & it = static_cast &>(iterator); - m_ListPosition = it.m_ListPosition; - m_ParentNode = it.m_ParentNode; - } - return *this; - } - -protected: - /** Get the next node. */ - const ValueType & - Next() override; - - /** Return true if the next node exists. */ - bool - HasNext() const override; - -private: - mutable ChildIdentifier m_ListPosition{}; - TreeNodeType * m_ParentNode{}; -}; - -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -# include "itkChildTreeIterator.hxx" -#endif - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkChildTreeIterator.hxx b/Modules/Compatibility/Deprecated/include/itkChildTreeIterator.hxx deleted file mode 100644 index aa1d9bfa861..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkChildTreeIterator.hxx +++ /dev/null @@ -1,122 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkChildTreeIterator_hxx -#define itkChildTreeIterator_hxx - - -namespace itk -{ - -template -ChildTreeIterator::ChildTreeIterator(TTreeType * tree, const TreeNodeType * start) - : TreeIteratorBase(tree, start) -{ - m_ListPosition = 0; - m_ParentNode = this->m_Position; - this->m_Position = m_ParentNode->GetChild(m_ListPosition); - this->m_Begin = this->m_Position; -} - -template -ChildTreeIterator::ChildTreeIterator(const TreeIteratorBase & iterator) - : TreeIteratorBase(iterator.GetTree(), iterator.GetNode()) -{ - m_ListPosition = 0; - m_ParentNode = this->m_Position; - this->m_Position = m_ParentNode->GetChild(m_ListPosition); -} - -template -bool -ChildTreeIterator::GoToChild(ChildIdentifier number) -{ - if (m_ParentNode->GetChild(number) == nullptr) - { - return false; - } - - m_ListPosition = 0; - m_ParentNode = m_ParentNode->GetChild(number); - this->m_Position = m_ParentNode->GetChild(m_ListPosition); - this->m_Begin = this->m_Position; - return true; -} - -template -bool -ChildTreeIterator::GoToParent() -{ - TreeNodeType * parent = m_ParentNode->GetParent(); - - if (parent == nullptr) - { - return false; - } - - m_ListPosition = 0; - m_ParentNode = parent; - this->m_Position = m_ParentNode->GetChild(m_ListPosition); - this->m_Begin = this->m_Position; - return true; -} - -template -auto -ChildTreeIterator::GetType() const -> NodeType -{ - return TreeIteratorBaseEnums::TreeIteratorBaseNode::CHILD; -} - -template -bool -ChildTreeIterator::HasNext() const -{ - if (m_ListPosition < m_ParentNode->CountChildren() - 1) - { - return true; - } - else - { - return false; - } -} - -template -auto -ChildTreeIterator::Next() -> const ValueType & -{ - ++m_ListPosition; - this->m_Position = m_ParentNode->GetChild(m_ListPosition); - if (this->m_Position == nullptr) - { - return this->m_Root->Get(); // value irrelevant, but we have to return something - } - return this->m_Position->Get(); -} - -template -TreeIteratorBase * -ChildTreeIterator::Clone() -{ - auto * clone = new ChildTreeIterator(const_cast(this->m_Tree), this->m_Position); - *clone = *this; - return clone; -} -} // namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkConditionVariable.h b/Modules/Compatibility/Deprecated/include/itkConditionVariable.h deleted file mode 100644 index e510fec6e86..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkConditionVariable.h +++ /dev/null @@ -1,99 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkConditionVariable_h -#define itkConditionVariable_h - -#include "itkConfigure.h" -#include "itkMutexLock.h" -#include "itkLightObject.h" - -namespace itk -{ -/** - * \class ConditionVariable - * \brief A thread synchronization object used to suspend execution until some - * condition on shared data is met. - * - * A thread calls Wait() to suspend its execution until the condition is - * met. Each call to Signal() from an executing thread will then cause a single - * waiting thread to be released. A call to Signal() means, "signal - * that the condition is true." Broadcast() releases all threads waiting on - * the condition variable. - * - * The ITK ConditionVariable implementation is consistent with the standard - * definition and use of condition variables in pthreads and other common - * thread libraries. - * - * IMPORTANT: A condition variable always requires an associated SimpleMutexLock - * object. The mutex object is used to avoid a dangerous race condition when - * Wait() and Signal() are called simultaneously from two different - * threads. - * - * On systems using pthreads, this implementation abstract the - * standard calls to the pthread condition variable. On Win32 - * systems, there is no system provided condition variable. This - * class implements a condition variable using a critical section, a - * semaphore, an event and a number of counters. The implementation is - * almost an extract translation of the implementation presented by - * Douglas C Schmidt and Irfan Pyarali in "Strategies for Implementing - * POSIX Condition Variables on Win32". This article can be found at - * http://www.cs.wustl.edu/~schmidt/win32-cv-1.html - * - * \ingroup ITKDeprecated - */ -class ITKDeprecated_EXPORT ConditionVariable : public LightObject -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(ConditionVariable); - - /** Standard class type aliases. */ - using Self = ConditionVariable; - using Superclass = LightObject; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(ConditionVariable); - - /** Suspend execution of this thread until the condition is signaled. The - * argument is a SimpleMutex object that must be locked prior to calling - * this method. */ - void - Wait(SimpleMutexLock * mutex); - - /** Signal that the condition is true and release one waiting thread */ - void - Signal(); - - /** Signal that the condition is true and release all waiting threads */ - void - Broadcast(); - -protected: - ConditionVariable(); - ~ConditionVariable() override; - -private: - ConditionVariableType m_ConditionVariable{}; -}; -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/src/itkConditionVariable.cxx b/Modules/Compatibility/Deprecated/include/itkDeprecatedPlaceholder.h similarity index 75% rename from Modules/Compatibility/Deprecated/src/itkConditionVariable.cxx rename to Modules/Compatibility/Deprecated/include/itkDeprecatedPlaceholder.h index 9f49ed9b217..a69087b3846 100644 --- a/Modules/Compatibility/Deprecated/src/itkConditionVariable.cxx +++ b/Modules/Compatibility/Deprecated/include/itkDeprecatedPlaceholder.h @@ -15,12 +15,11 @@ * limitations under the License. * *=========================================================================*/ -#include "itkConditionVariable.h" +#ifndef itkDeprecatedPlaceholder_h +#define itkDeprecatedPlaceholder_h -#if defined(ITK_USE_PTHREADS) -# include "itkConditionVariablePThreads.cxx" -#elif defined(ITK_USE_WIN32_THREADS) -# include "itkConditionVariableWinThreads.cxx" -#else -# include "itkConditionVariableNoThreads.cxx" +#include + +extern std::string +dummy_deprecated_function_placeholder(); #endif diff --git a/Modules/Compatibility/Deprecated/include/itkFastMutexLock.h b/Modules/Compatibility/Deprecated/include/itkFastMutexLock.h deleted file mode 100644 index c231bda5a4f..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkFastMutexLock.h +++ /dev/null @@ -1,118 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#ifndef itkFastMutexLock_h -#define itkFastMutexLock_h - -#include "itkObject.h" -#include "itkSimpleFastMutexLock.h" -#include "itkObjectFactory.h" - -namespace itk -{ -/** - * \class FastMutexLock - * \brief Critical section locking class. - * - * FastMutexLock allows the locking of variables which are accessed - * through different threads. This header file also defines - * SimpleFastMutexLock which is not a subclass of Object. - * The API is identical to that of MutexLock, and the behavior is - * identical as well, except on Windows 9x/NT platforms. The only difference - * on these platforms is that MutexLock is more flexible, in that - * it works across processes as well as across threads, but also costs - * more, in that it evokes a 600-cycle x86 ring transition. The - * FastMutexLock provides a higher-performance equivalent (on - * Windows) but won't work across processes. Since it is unclear how, - * in itk, an object at the itk level can be shared across processes - * in the first place, one should use FastMutexLock unless one has - * a very good reason to use MutexLock. If higher-performance equivalents - * for non-Windows platforms (Irix, SunOS, etc) are discovered, they - * should replace the implementations in this class - * - * \ingroup OSSystemObjects - * \ingroup ITKDeprecated - */ -class ITKDeprecated_EXPORT FastMutexLock : public Object -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(FastMutexLock); - - /** Standard class type aliases. */ - using Self = FastMutexLock; - using Superclass = Object; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - /** Method for creation. */ - itkNewMacro(Self); - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(FastMutexLock); - - /** Lock the itkFastMutexLock. */ - void - Lock(); - - /** Non-blocking Lock access. - \return bool - true if lock is captured, false if it was already held by someone else. - */ - bool - TryLock(); - - /** Unlock the FastMutexLock. */ - void - Unlock(); - -protected: - FastMutexLock() = default; - ~FastMutexLock() override = default; - - SimpleFastMutexLock m_SimpleFastMutexLock{}; - void - PrintSelf(std::ostream & os, Indent indent) const override; -}; - -inline void -FastMutexLock::Lock() -{ - m_SimpleFastMutexLock.Lock(); -} - -inline bool -FastMutexLock::TryLock() -{ - return m_SimpleFastMutexLock.TryLock(); -} - -inline void -FastMutexLock::Unlock() -{ - m_SimpleFastMutexLock.Unlock(); -} -} // namespace itk -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkImageTransformer.h b/Modules/Compatibility/Deprecated/include/itkImageTransformer.h deleted file mode 100644 index 73e962ae561..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkImageTransformer.h +++ /dev/null @@ -1,271 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#ifndef itkImageTransformer_h -#define itkImageTransformer_h - -#include "itkProcessObject.h" -#include "itkImage.h" - -namespace itk -{ -/** - * \class ImageTransformer - * \brief Base class for all process objects that transform an image into something else. - * - * ImageTransformer is the base class for all process objects that transform an - * image data. Specifically, this class defines the SetInput() method - * that takes a pointer to the input image. The class also defines - * some internal private data members that are used to manage streaming - * of data. - * - * Memory management in an ImageTransformer is slightly different than a - * standard ProcessObject. ProcessObject's always release the bulk - * data associated with their output prior to GenerateData() being - * called. ImageTransformers default to not releasing the bulk data incase - * that particular memory block is large enough to hold the new output - * values. This avoids unnecessary deallocation/allocation - * sequences. ImageTransformer's can be forced to use a memory management - * model similar to the default ProcessObject behaviour by calling - * ProcessObject::ReleaseDataBeforeUpdateFlagOn(). A user may want to - * set this flag to limit peak memory usage during a pipeline update. - * - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT ImageTransformer : public ProcessObject -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(ImageTransformer); - - /** Standard class type aliases. */ - using Self = ImageTransformer; - using Superclass = ProcessObject; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - /** Smart Pointer type to a DataObject. */ - using DataObjectPointer = DataObject::Pointer; - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(ImageTransformer); - - /** Some convenient type alias. */ - using InputImageType = TInputImage; - using InputImagePointer = typename InputImageType::Pointer; - using InputImageRegionType = typename InputImageType::RegionType; - using InputImagePixelType = typename InputImageType::PixelType; - - /** ImageDimension constant */ - static constexpr unsigned int InputImageDimension = TInputImage::ImageDimension; - - /** Set/Get the image input of this process object. */ - using Superclass::SetInput; - virtual void - SetInput(const InputImageType * image); - virtual void - SetInput(unsigned int, const TInputImage * image); - const InputImageType * - GetInput() const; - InputImageType * - GetInput(); - const InputImageType * - GetInput(unsigned int idx) const; - - /** Push/Pop the input of this process object. These methods allow a - * filter to model its input vector as a queue or stack. These - * routines may not be appropriate for all filters, especially - * filters with different types of inputs. These routines follow - * the semantics of STL. - * - * The routines are useful for applications that need to process - * "rolling" sets of images. For instance, if an application has 10 - * images and they need to run a filter on images 1, 2, 3, 4, then - * run the filter on images 2, 3, 4, 5, then run the filter on - * images 3, 4, 5, 6, the application can accomplish this by popping - * an input off the front of the input list and push a new image - * onto the back of input list. Again, this only makes sense for - * filters that single type of input. - * - * Other uses are also possible. For a single input filter, pushing - * and popping inputs allow the application to temporarily replace - * an input to a filter. - */ - virtual void - PushBackInput(const InputImageType * image); - void - PopBackInput() override; - virtual void - PushFrontInput(const InputImageType * image); - void - PopFrontInput() override; - -protected: - ImageTransformer(); - ~ImageTransformer() override = default; - - /** The image transformer is assumed to need the whole input. - * - * This implementation of GenerateInputRequestedRegion() only - * processes the inputs that are a subclass of the - * ImageBase. If an input is another type of - * DataObject (including an Image of a different dimension), they - * are skipped by this method. The subclasses of ImageToImageFilter - * are responsible for providing an implementation of - * GenerateInputRequestedRegion() when there are multiple inputs of - * different types. - * - * \sa ProcessObject::GenerateInputRequestedRegion(), - * ImageSource::GenerateInputRequestedRegion() */ - void - GenerateInputRequestedRegion() override; - - /** A version of GenerateData() specific for image processing - * filters. This implementation will split the processing across - * multiple threads. The buffer is allocated by this method. Then - * the BeforeThreadedGenerateData() method is called (if - * provided). Then, a series of threads are spawned each calling - * ThreadedGenerateData(). After all the threads have completed - * processing, the AfterThreadedGenerateData() method is called (if - * provided). If an image processing filter cannot be threaded, the - * filter should provide an implementation of GenerateData(). That - * implementation is responsible for allocating the output buffer. - * If a filter can be threaded, it should NOT provide a - * GenerateData() method but should provide a ThreadedGenerateData() - * instead. - * - * \sa ThreadedGenerateData() */ - void - GenerateData() override; - - /** If an imaging filter can be implemented as a multithreaded - * algorithm, the filter will provide an implementation of - * ThreadedGenerateData(). This superclass will automatically split - * the output image into a number of pieces, spawn multiple threads, - * and call ThreadedGenerateData() in each thread. Prior to spawning - * threads, the BeforeThreadedGenerateData() method is called. After - * all the threads have completed, the AfterThreadedGenerateData() - * method is called. If an image processing filter cannot support - * threading, that filter should provide an implementation of the - * GenerateData() method instead of providing an implementation of - * ThreadedGenerateData(). If a filter provides a GenerateData() - * method as its implementation, then the filter is responsible for - * allocating the output data. If a filter provides a - * ThreadedGenerateData() method as its implementation, then the - * output memory will allocated automatically by this superclass. - * The ThreadedGenerateData() method should only produce the output - * specified by "inputThreadRegion" - * parameter. ThreadedGenerateData() cannot write to any other - * portion of the output image (as this is responsibility of a - * different thread). - * - * \sa GenerateData(), SplitRequestedRegion() */ - virtual void - ThreadedGenerateData(const InputImageRegionType & inputRegionForThread, ThreadIdType threadId); - - /** Many filters do special management of image buffer and threading, - * so this method provides just the multi-threaded invocation part - * of GenerateData() method. */ - void - ClassicMultiThread(ThreadFunctionType callbackFunction); - - /** The GenerateData method normally allocates the buffers for all of the - * outputs of a filter. Some filters may want to override this default - * behavior. For example, a filter may have multiple outputs with - * varying resolution. Or a filter may want to process data in place by - * grafting its input to its output. */ - virtual void - AllocateOutputs(); - - /** If an imaging filter needs to perform processing after the buffer - * has been allocated but before threads are spawned, the filter can - * can provide an implementation for BeforeThreadedGenerateData(). The - * execution flow in the default GenerateData() method will be: - * 1) Allocate the output buffer - * 2) Call BeforeThreadedGenerateData() - * 3) Spawn threads, calling ThreadedGenerateData() in each thread. - * 4) Call AfterThreadedGenerateData() - * Note that this flow of control is only available if a filter provides - * a ThreadedGenerateData() method and NOT a GenerateData() method. */ - virtual void - BeforeThreadedGenerateData() - {} - - /** If an imaging filter needs to perform processing after all - * processing threads have completed, the filter can can provide an - * implementation for AfterThreadedGenerateData(). The execution - * flow in the default GenerateData() method will be: - * 1) Allocate the output buffer - * 2) Call BeforeThreadedGenerateData() - * 3) Spawn threads, calling ThreadedGenerateData() in each thread. - * 4) Call AfterThreadedGenerateData() - * Note that this flow of control is only available if a filter provides - * a ThreadedGenerateData() method and NOT a GenerateData() method. */ - virtual void - AfterThreadedGenerateData() - {} - - /** Split the input's RequestedRegion into "num" pieces, returning - * region "i" as "splitRegion". This method is called "num" times. The - * regions must not overlap. The method returns the number of pieces that - * the routine is capable of splitting the input RequestedRegion, - * i.e. return value is less than or equal to "num". */ - virtual unsigned int - SplitRequestedRegion(unsigned int i, unsigned int num, InputImageRegionType & splitRegion); - - /** Static function used as a "callback" by the MultiThreader. The threading - * library will call this routine for each thread, which will delegate the - * control to ThreadedGenerateData(). */ - static ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION - ThreaderCallback(void * arg); - - /** - * PushBackInput(), PushFrontInput() in the public section force the - * input to be the type expected by an ImageTransformer. However, - * these methods end up "hiding" the versions from the superclass - * (ProcessObject) whose arguments are DataObjects. Here, we re-expose - * the versions from ProcessObject to avoid warnings about hiding - * methods from the superclass. - * NOTE: The same code resides in ImageToImageFilter - */ - using Superclass::PushBackInput; - using Superclass::PushFrontInput; - - /** Internal structure used for passing image data into the threading library - */ - struct ThreadStruct - { - Pointer Filter; - }; -}; -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -# include "itkImageTransformer.hxx" -#endif - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkImageTransformer.hxx b/Modules/Compatibility/Deprecated/include/itkImageTransformer.hxx deleted file mode 100644 index 1c57cee58f2..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkImageTransformer.hxx +++ /dev/null @@ -1,352 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#ifndef itkImageTransformer_hxx -#define itkImageTransformer_hxx - -#include "itkMath.h" - -namespace itk -{ -/** - * - */ -template -ImageTransformer::ImageTransformer() -{ - // Set the default behavior of an image source to NOT release its - // output bulk data prior to GenerateData() in case that bulk data - // can be reused (an thus avoid a costly deallocate/allocate cycle). - this->ReleaseDataBeforeUpdateFlagOff(); -} - -/** - * - */ -template -void -ImageTransformer::SetInput(const InputImageType * input) -{ - // Process object is not const-correct so the const_cast is required here - this->ProcessObject::SetNthInput(0, const_cast(input)); -} - -/** - * Connect one of the operands for pixel-wise addition - */ -template -void -ImageTransformer::SetInput(unsigned int index, const TInputImage * image) -{ - // Process object is not const-correct so the const_cast is required here - this->ProcessObject::SetNthInput(index, const_cast(image)); -} - -/** - * - */ -template -auto -ImageTransformer::GetInput() const -> const InputImageType * -{ - if (this->GetNumberOfInputs() < 1) - { - return 0; - } - - return itkDynamicCastInDebugMode(this->ProcessObject::GetInput(0)); -} - -/** - * - */ -template -auto -ImageTransformer::GetInput() -> InputImageType * -{ - if (this->GetNumberOfInputs() < 1) - { - return nullptr; - } - - return itkDynamicCastInDebugMode(this->ProcessObject::GetInput(0)); -} - -/** - * - */ -template -auto -ImageTransformer::GetInput(unsigned int idx) const -> const InputImageType * -{ - return itkDynamicCastInDebugMode(this->ProcessObject::GetInput(idx)); -} - -template -void -ImageTransformer::PushBackInput(const InputImageType * input) -{ - // Forward to the protected method in the superclass - this->ProcessObject::PushBackInput(input); -} - -template -void -ImageTransformer::PopBackInput() -{ - // Forward to the protected method in the superclass - this->ProcessObject::PopBackInput(); -} - -template -void -ImageTransformer::PushFrontInput(const InputImageType * input) -{ - // Forward to the protected method in the superclass - this->ProcessObject::PushFrontInput(input); -} - -template -void -ImageTransformer::PopFrontInput() -{ - // Forward to the protected method in the superclass - this->ProcessObject::PopFrontInput(); -} - -//----------------------------------------------------------------------- -// -template -void -ImageTransformer::GenerateInputRequestedRegion() -{ - Superclass::GenerateInputRequestedRegion(); - - for (unsigned int idx = 0; idx < this->GetNumberOfInputs(); ++idx) - { - if (this->GetInput(idx)) - { - // Check whether the input is an image of the appropriate - // dimension (use ProcessObject's version of the GetInput() - // method since it returns the input as a pointer to a - // DataObject as opposed to the subclass version which - // static_casts the input to an TInputImage). - using ImageBaseType = ImageBase; - typename ImageBaseType::ConstPointer constInput = - dynamic_cast(this->ProcessObject::GetInput(idx)); - - // If not an image, skip it, and let a subclass of - // ImageToImageFilter handle this input. - if (constInput.IsNull()) - { - continue; - } - - // Input is an image, cast away the constness so we can set - // the requested region. - InputImagePointer input = const_cast(this->GetInput(idx)); - - // transform is assumed to need the whole image - input->SetRequestedRegion(input->GetLargestPossibleRegion()); - } - } -} - -//---------------------------------------------------------------------------- -template -unsigned int -ImageTransformer::SplitRequestedRegion(unsigned int i, - unsigned int num, - InputImageRegionType & splitRegion) -{ - // Get the input pointer - InputImageType * inputPtr = this->GetInput(); - - const typename TInputImage::SizeType & requestedRegionSize = inputPtr->GetRequestedRegion().GetSize(); - - int splitAxis; - typename TInputImage::IndexType splitIndex; - typename TInputImage::SizeType splitSize; - - // Initialize the splitRegion to the input requested region - splitRegion = inputPtr->GetRequestedRegion(); - splitIndex = splitRegion.GetIndex(); - splitSize = splitRegion.GetSize(); - - // split on the outermost dimension available - splitAxis = inputPtr->GetImageDimension() - 1; - while (requestedRegionSize[splitAxis] == 1) - { - --splitAxis; - if (splitAxis < 0) - { // cannot split - itkDebugMacro(" Cannot Split"); - return 1; - } - } - - // determine the actual number of pieces that will be generated - typename TInputImage::SizeType::SizeValueType range = requestedRegionSize[splitAxis]; - if (num != 0 && range != 0) - { - auto valuesPerThread = Math::Ceil(range / static_cast(num)); - unsigned int maxThreadIdUsed = Math::Ceil(range / static_cast(valuesPerThread)) - 1; - // Split the region - if (i < maxThreadIdUsed) - { - splitIndex[splitAxis] += i * valuesPerThread; - splitSize[splitAxis] = valuesPerThread; - } - if (i == maxThreadIdUsed) - { - splitIndex[splitAxis] += i * valuesPerThread; - // last thread needs to process the "rest" dimension being split - splitSize[splitAxis] = splitSize[splitAxis] - i * valuesPerThread; - } - - // set the split region ivars - splitRegion.SetIndex(splitIndex); - splitRegion.SetSize(splitSize); - - itkDebugMacro(" Split Piece: " << splitRegion); - - return maxThreadIdUsed + 1; - } - else - { - itkDebugMacro("Division by zero: num/range = 0."); - return 1; - } -} - -//---------------------------------------------------------------------------- -template -void -ImageTransformer::AllocateOutputs() -{} - -//---------------------------------------------------------------------------- -template -void -ImageTransformer::ClassicMultiThread(ThreadFunctionType callbackFunction) -{ - ThreadStruct str; - str.Filter = this; - - this->GetMultiThreader()->SetNumberOfWorkUnits(this->GetNumberOfWorkUnits()); - this->GetMultiThreader()->SetSingleMethodAndExecute(callbackFunction, &str); -} - -//---------------------------------------------------------------------------- -template -void -ImageTransformer::GenerateData() -{ - // Call a method that can be overridden by a subclass to allocate - // memory for the filter's outputs - this->AllocateOutputs(); - - // Call a method that can be overridden by a subclass to perform - // some calculations prior to splitting the main computations into - // separate threads - this->BeforeThreadedGenerateData(); - - this->ClassicMultiThread(this->ThreaderCallback); - - // Call a method that can be overridden by a subclass to perform - // some calculations after all the threads have completed - this->AfterThreadedGenerateData(); -} - -//---------------------------------------------------------------------------- -// The execute method created by the subclass. -template -void -ImageTransformer::ThreadedGenerateData(const InputImageRegionType &, ThreadIdType) -{ - // The following code is equivalent to: - // itkExceptionMacro("subclass should override this method!!!"); - // The ExceptionMacro is not used because gcc warns that a - // 'noreturn' function does return - std::ostringstream message; - - message << "itk::ERROR: " << this->GetNameOfClass() << '(' << this << "): " - << "Subclass should override this method!!!"; - ExceptionObject e_(__FILE__, __LINE__, message.str().c_str(), ITK_LOCATION); - throw e_; -} - -// Callback routine used by the threading library. This routine just calls -// the ThreadedGenerateData method after setting the correct region for this -// thread. -template -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -ImageTransformer::ThreaderCallback(void * arg) -{ - ThreadStruct * str; - ThreadIdType total, threadId, threadCount; - - threadId = ((MultiThreaderBase::WorkUnitInfo *)(arg))->WorkUnitID; - threadCount = ((MultiThreaderBase::WorkUnitInfo *)(arg))->NumberOfWorkUnits; - - str = (ThreadStruct *)(((MultiThreaderBase::WorkUnitInfo *)(arg))->UserData); - - // execute the actual method with appropriate output region - // first find out how many pieces extent can be split into. - typename TInputImage::RegionType splitRegion; - total = str->Filter->SplitRequestedRegion(threadId, threadCount, splitRegion); - - if (threadId < total) - { - str->Filter->ThreadedGenerateData(splitRegion, threadId); -#if defined(ITKV4_COMPATIBILITY) - if (str->Filter->GetAbortGenerateData()) - { - std::string msg; - ProcessAborted e(__FILE__, __LINE__); - msg += "Object " + std::string(str->Filter->GetNameOfClass()) + ": AbortGenerateData was set!"; - e.SetDescription(msg); - throw e; - } - else if (str->Filter->GetProgress() == 0.0f) // progress was not set after at least the first chunk finished - { - str->Filter->UpdateProgress(static_cast(threadId + 1) / total); // this will be the only progress update - } -#endif - } - // else - // { - // otherwise don't use this thread. Sometimes the threads don't - // break up very well and it is just as efficient to leave a - // few threads idle. - // } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkInOrderTreeIterator.h b/Modules/Compatibility/Deprecated/include/itkInOrderTreeIterator.h deleted file mode 100644 index ee2bb872bdd..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkInOrderTreeIterator.h +++ /dev/null @@ -1,182 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkInOrderTreeIterator_h -#define itkInOrderTreeIterator_h - -#include "itkTreeIteratorBase.h" - -namespace itk -{ -template -class ITK_TEMPLATE_EXPORT InOrderTreeIterator : public TreeIteratorBase -{ -public: - /** Typedefs */ - using Self = InOrderTreeIterator; - using Superclass = TreeIteratorBase; - using TreeType = TTreeType; - using ValueType = typename TTreeType::ValueType; - using typename Superclass::TreeNodeType; - using typename Superclass::NodeType; - - /** Constructors */ - InOrderTreeIterator(TreeType & start); - InOrderTreeIterator(TreeType * tree, TreeNodeType * start = nullptr); - - /** Get the type of iterator */ - NodeType - GetType() const override; - - /** Clone function */ - TreeIteratorBase * - Clone() override; - -protected: - /** Return the next node */ - const ValueType & - Next() override; - - /** Return true if the next node exists */ - bool - HasNext() const override; - -private: - /** Find the next node */ - const TreeNodeType * - FindNextNode() const; -}; - -/** Constructor */ -template -InOrderTreeIterator::InOrderTreeIterator(TTreeType & start) - : TreeIteratorBase(start) -{} - -/** Constructor */ -template -InOrderTreeIterator::InOrderTreeIterator(TTreeType * tree, TreeNodeType * start) - : TreeIteratorBase(tree, start) -{} - -/** Get the type of the iterator */ -template -auto -InOrderTreeIterator::GetType() const -> NodeType -{ - return TreeIteratorBaseEnums::TreeIteratorBaseNode::INORDER; -} - -/** Return true if the next node exists */ -template -bool -InOrderTreeIterator::HasNext() const -{ - if (const_cast(FindNextNode()) != nullptr) - { - return true; - } - return false; -} - -/** Return the next node */ -template -const typename InOrderTreeIterator::ValueType & -InOrderTreeIterator::Next() -{ - this->m_Position = const_cast(FindNextNode()); - if (this->m_Position == nullptr) - { - return this->m_Root->Get(); // value irrelevant, but we have to return something - } - return this->m_Position->Get(); -} - -/** Find the next node */ -template -const typename InOrderTreeIterator::TreeNodeType * -InOrderTreeIterator::FindNextNode() const -{ - if (this->m_Position == nullptr) - { - return nullptr; - } - - if (this->m_Position->HasChildren()) - { - return this->m_Position->GetChild(0); - } - - if (!this->m_Position->HasParent()) - { - return nullptr; - } - - TreeNodeType * child = this->m_Position; - TreeNodeType * parent = this->m_Position->GetParent(); - - int childPosition = parent->ChildPosition(child); - int lastChildPosition = parent->CountChildren() - 1; - - while (childPosition < lastChildPosition) - { - TreeNodeType * help = parent->GetChild(childPosition + 1); - if (help != nullptr) - { - return help; - } - ++childPosition; - } - - while (parent->HasParent()) - { - child = parent; - parent = parent->GetParent(); - - // Subtree - if (parent->ChildPosition(this->m_Root) >= 0) - { - return nullptr; - } - childPosition = parent->ChildPosition(child); - lastChildPosition = parent->CountChildren() - 1; - - while (childPosition < lastChildPosition) - { - TreeNodeType * help = parent->GetChild(childPosition + 1); - if (help != nullptr) - { - return help; - } - } - } - return nullptr; -} - -/** Clone function */ -template -TreeIteratorBase * -InOrderTreeIterator::Clone() -{ - auto * clone = new InOrderTreeIterator(const_cast(this->m_Tree)); - - *clone = *this; - return clone; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkLeafTreeIterator.h b/Modules/Compatibility/Deprecated/include/itkLeafTreeIterator.h deleted file mode 100644 index 1ce97b49647..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkLeafTreeIterator.h +++ /dev/null @@ -1,185 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkLeafTreeIterator_h -#define itkLeafTreeIterator_h - -#include "itkPreOrderTreeIterator.h" - -namespace itk -{ -template -class ITK_TEMPLATE_EXPORT LeafTreeIterator : public TreeIteratorBase -{ -public: - /** Typedefs */ - using Self = LeafTreeIterator; - using Superclass = TreeIteratorBase; - using TreeType = TTreeType; - using ValueType = typename TreeType::ValueType; - using typename Superclass::TreeNodeType; - using typename Superclass::NodeType; - - /** Constructor */ - LeafTreeIterator(const TreeType * tree); - - /** Constructor */ - LeafTreeIterator(TreeType * tree); - - /** Destructor */ - ~LeafTreeIterator() override; - - /** Return the type of iterator */ - NodeType - GetType() const override; - - /** Clone function */ - TreeIteratorBase * - Clone() override; - -protected: - /** Return the next value */ - const ValueType & - Next() override; - - /** Return true if the next value exists */ - bool - HasNext() const override; - -private: - /** Find the next node */ - const TreeNodeType * - FindNextNode() const; -}; - -/** Constructor */ -template -LeafTreeIterator::LeafTreeIterator(const TTreeType * tree) - : TreeIteratorBase(tree, nullptr) -{ - this->m_Begin = const_cast(this->FindNextNode()); // - // - // Position - // the - // - // iterator - // to - // the - // first - // leaf; -} - -/** Constructor */ -template -LeafTreeIterator::LeafTreeIterator(TTreeType * tree) - : TreeIteratorBase(tree, nullptr) -{ - this->m_Begin = const_cast(this->FindNextNode()); // - // - // Position - // the - // - // iterator - // to - // the - // first - // leaf; -} - -/** Destructor */ -template -LeafTreeIterator::~LeafTreeIterator() = default; - -/** Return the type of iterator */ -template -auto -LeafTreeIterator::GetType() const -> NodeType -{ - return TreeIteratorBaseEnums::TreeIteratorBaseNode::LEAF; -} - -/** Return true if the next value exists */ -template -bool -LeafTreeIterator::HasNext() const -{ - if (this->m_Position == nullptr) - { - return false; - } - if (const_cast(FindNextNode()) != nullptr) - { - return true; - } - return false; -} - -/** Return the next node */ -template -const typename LeafTreeIterator::ValueType & -LeafTreeIterator::Next() -{ - this->m_Position = const_cast(FindNextNode()); - if (this->m_Position == nullptr) - { - return this->m_Root->Get(); // value irrelevant, but we have to return something - } - return this->m_Position->Get(); -} - -/** Find the next node given the position */ -template -const typename LeafTreeIterator::TreeNodeType * -LeafTreeIterator::FindNextNode() const -{ - PreOrderTreeIterator it(this->m_Tree, this->m_Position); - it.m_Root = this->m_Root; - ++it; // go next - if (it.IsAtEnd()) - { - return nullptr; - } - - if (!it.HasChild()) - { - return it.GetNode(); - } - - while (!it.IsAtEnd()) - { - if (!it.HasChild()) - { - return it.GetNode(); - } - ++it; - } - - return nullptr; -} - -/** Clone function */ -template -TreeIteratorBase * -LeafTreeIterator::Clone() -{ - auto * clone = new LeafTreeIterator(this->m_Tree); - *clone = *this; - return clone; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkLevelOrderTreeIterator.h b/Modules/Compatibility/Deprecated/include/itkLevelOrderTreeIterator.h deleted file mode 100644 index 360f5b14c94..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkLevelOrderTreeIterator.h +++ /dev/null @@ -1,120 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkLevelOrderTreeIterator_h -#define itkLevelOrderTreeIterator_h - -#include -#include -#include "itkTreeIteratorBase.h" - -namespace itk -{ -/** - * \class LevelOrderTreeIterator - * \brief Iterate over a tree in level order. - * - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT LevelOrderTreeIterator : public TreeIteratorBase -{ -public: - /** Typedefs */ - using Self = LevelOrderTreeIterator; - using Superclass = TreeIteratorBase; - using TreeType = TTreeType; - using ValueType = typename TTreeType::ValueType; - using typename Superclass::TreeNodeType; - using typename Superclass::NodeType; - - /** Constructor with end level specification */ - LevelOrderTreeIterator(TreeType * tree, int endLevel = INT_MAX, const TreeNodeType * start = nullptr); - - /** Constructor with end level specification. */ - LevelOrderTreeIterator(TreeType * tree, int startLevel, int endLevel, const TreeNodeType * start = nullptr); - - ~LevelOrderTreeIterator() override = default; - - /** Get the type of the iterator. */ - NodeType - GetType() const override; - - /** Get the start level. */ - int - GetStartLevel() const; - - /** Get the end level. */ - int - GetEndLevel() const; - - /** Get the current level. */ - int - GetLevel() const; - - /** Clone function. */ - TreeIteratorBase * - Clone() override; - - /** operator = */ - const Self & - operator=(const Self & iterator) - { - if (this != &iterator) - { - this->Superclass::operator=(iterator); - m_StartLevel = iterator.m_StartLevel; - m_EndLevel = iterator.m_EndLevel; - m_Queue = iterator.m_Queue; - } - return *this; - } - -protected: - /** Get the next node. */ - const ValueType & - Next() override; - - /** Return true if the next node exists. */ - bool - HasNext() const override; - -private: - /** Find the next available node. */ - const TreeNodeType * - FindNextNode() const; - - /** Helper function to find the next node. */ - const TreeNodeType * - FindNextNodeHelp() const; - - /** Get the level given a node. */ - int - GetLevel(const TreeNodeType * node) const; - - int m_StartLevel{}; - int m_EndLevel{}; - mutable std::queue m_Queue{}; -}; - -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -# include "itkLevelOrderTreeIterator.hxx" -#endif - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkLevelOrderTreeIterator.hxx b/Modules/Compatibility/Deprecated/include/itkLevelOrderTreeIterator.hxx deleted file mode 100644 index 33c2fda69a3..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkLevelOrderTreeIterator.hxx +++ /dev/null @@ -1,223 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkLevelOrderTreeIterator_hxx -#define itkLevelOrderTreeIterator_hxx - - -namespace itk -{ - -template -LevelOrderTreeIterator::LevelOrderTreeIterator(TTreeType * tree, int endLevel, const TreeNodeType * start) - : TreeIteratorBase(tree, start) -{ - m_StartLevel = -1; - m_EndLevel = endLevel; - if (start != nullptr) - { - m_Queue.push(start); - this->m_Position = const_cast(start); - } - else - { - if (tree->GetRoot()) - { - m_Queue.push(dynamic_cast(tree->GetRoot())); - this->m_Position = const_cast(dynamic_cast(tree->GetRoot())); - } - } - this->m_Begin = this->m_Position; -} - -template -LevelOrderTreeIterator::LevelOrderTreeIterator(TTreeType * tree, - int startLevel, - int endLevel, - const TreeNodeType * start) - : TreeIteratorBase(tree, start) -{ - m_StartLevel = startLevel; - m_EndLevel = endLevel; - if (start != nullptr) - { - m_Queue.push(start); - this->m_Position = const_cast(start); - } - else - { - if (tree->GetRoot()) - { - m_Queue.push(dynamic_cast(tree->GetRoot())); - this->m_Position = const_cast(dynamic_cast(tree->GetRoot())); - } - } - this->m_Begin = this->m_Position; -} - -template -auto -LevelOrderTreeIterator::GetType() const -> NodeType -{ - return TreeIteratorBaseEnums::TreeIteratorBaseNode::LEVELORDER; -} - -template -bool -LevelOrderTreeIterator::HasNext() const -{ - if (const_cast(FindNextNode())) - { - return true; - } - return false; -} - -template -auto -LevelOrderTreeIterator::Next() -> const ValueType & -{ - this->m_Position = const_cast(FindNextNode()); - if (this->m_Position == nullptr) - { - return this->m_Root->Get(); // value irrelevant, but we have to return something - } - return this->m_Position->Get(); -} - -template -int -LevelOrderTreeIterator::GetStartLevel() const -{ - return m_StartLevel; -} - -template -int -LevelOrderTreeIterator::GetEndLevel() const -{ - return m_EndLevel; -} - -template -auto -LevelOrderTreeIterator::FindNextNode() const -> const TreeNodeType * -{ - int level; - const TreeNodeType * node; - - do - { - node = FindNextNodeHelp(); - if (node == nullptr) - { - return nullptr; - } - level = GetLevel(node); - if (level > m_EndLevel) - { - return nullptr; - } - } while (level < m_StartLevel); - - return node; -} - -template -int -LevelOrderTreeIterator::GetLevel() const -{ - if (this->m_Position == nullptr) - { - return -1; - } - - int level = 0; - TreeNodeType * node = this->m_Position; - while (node->HasParent() && node != this->m_Root) - { - node = dynamic_cast(node->GetParent()); - ++level; - } - return level; -} - -template -int -LevelOrderTreeIterator::GetLevel(const TreeNodeType * node) const -{ - if (node == nullptr) - { - return -1; - } - int level = 0; - - while (node->HasParent() && node != this->m_Root) - { - node = dynamic_cast(node->GetParent()); - ++level; - } - return level; -} - -template -auto -LevelOrderTreeIterator::FindNextNodeHelp() const -> const TreeNodeType * -{ - if (m_Queue.empty()) - { - return nullptr; - } - - const TreeNodeType * currentNode = m_Queue.front(); - m_Queue.pop(); - - if (currentNode == nullptr) - { - return nullptr; - } - - int size = currentNode->CountChildren(); - - for (int i = 0; i < size; ++i) - { - auto * child = dynamic_cast(currentNode->GetChild(i)); - if (child != nullptr) - { - m_Queue.push(child); - } - } - - // If the current node is the root we try again - if (currentNode == this->m_Root) - { - currentNode = const_cast(FindNextNodeHelp()); - } - return currentNode; -} - -template -TreeIteratorBase * -LevelOrderTreeIterator::Clone() -{ - auto * clone = new LevelOrderTreeIterator(const_cast(this->m_Tree), m_StartLevel, m_EndLevel); - *clone = *this; - return clone; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkMultiThreader.h b/Modules/Compatibility/Deprecated/include/itkMultiThreader.h deleted file mode 100644 index 669fe30a76c..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkMultiThreader.h +++ /dev/null @@ -1,48 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkMultiThreader_h -#define itkMultiThreader_h - -#if !defined(ITK_LEGACY_REMOVE) -# include "itkMultiThreaderBase.h" -# include "itkPlatformMultiThreader.h" -namespace itk -{ -/** Since ITK 5.0 MultiThreader has been split into a class hierarchy. - * Most of the time you will want to replace it by MultiThreaderBase. - * - * Additionally, call this->DynamicMultiThreadingOff(); prior to Update() - * (for example in constructor) if any of the following is true: - * - Your filter needs a constant, in-advance known number of threads - * - Your filter uses threadId parameter in ThreadedGenerateData() - * - Your filter uses a custom region splitting method */ -using MultiThreader = MultiThreaderBase; - - -/** Replace it by PlatformMultiThreader if any of the following is true: - * - Your filter uses cross-thread synchronization e.g. itkBarrier - * - Your filter uses MultipleMethodExecute() - * - Your filter uses SpawnThread/TerminateThread. */ -// using MultiThreader = PlatformMultiThreader; -} // namespace itk -#else // ITK_LEGACY_REMOVE -# error itkMultiThreader.h is a legacy file since ITK 5.0 and will be removed in the future. -#endif // ITK_LEGACY_REMOVE - -#endif // itkMultiThreader_h diff --git a/Modules/Compatibility/Deprecated/include/itkMutexLock.h b/Modules/Compatibility/Deprecated/include/itkMutexLock.h deleted file mode 100644 index da8bcae3fa2..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkMutexLock.h +++ /dev/null @@ -1,177 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#ifndef itkMutexLock_h -#define itkMutexLock_h - -#include "itkObject.h" -#include "itkObjectFactory.h" -#include "itkThreadSupport.h" -#include "ITKDeprecatedExport.h" - -namespace itk -{ - -/** - * \class SimpleMutexLock - * \brief Simple mutual exclusion locking class. - - * SimpleMutexLock allows the locking of variables which are accessed - * through different threads. This header file also defines - * SimpleMutexLock which is not a subclass of Object. - * - * \ingroup OSSystemObjects - * \ingroup ITKDeprecated - */ -class ITKDeprecated_EXPORT SimpleMutexLock -{ -public: - /** Standard class type aliases. */ - using Self = SimpleMutexLock; - - /** Constructor and destructor left public purposely. */ - SimpleMutexLock(); - virtual ~SimpleMutexLock(); - - /** Methods for creation and destruction through the object factory. */ - static SimpleMutexLock * - New(); - - void - Delete() - { - delete this; - } - - /** Used for debugging and other run-time purposes. */ - virtual const char * - GetNameOfClass() - { - return "itkSimpleMutexLock"; - } - - /** Lock the MutexLock. */ - void - Lock(); - - /** Non-blocking Lock access. - \return bool - true if lock is captured, false if it was already held by someone else. - */ - bool - TryLock(); - - /** Unlock the MutexLock. */ - void - Unlock(); - - /** Access the MutexType member variable from outside this class */ - MutexType & - GetMutexLock() - { - return m_MutexLock; - } - - MutexType - GetMutexLock() const - { - return *(const_cast(&m_MutexLock)); - } - -protected: - MutexType m_MutexLock{}; -}; - -/** - * \class MutexLock - * \brief Mutual exclusion locking class. - * - * MutexLock allows the locking of variables which are accessed - * through different threads. This header file also defines - * SimpleMutexLock which is not a subclass of itkObject. - * - * \ingroup OSSystemObjects - * \ingroup ITKDeprecated - */ -class ITKDeprecated_EXPORT MutexLock : public Object -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(MutexLock); - - /** Standard class type aliases. */ - using Self = MutexLock; - using Superclass = Object; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - /** Method for creation. */ - itkNewMacro(Self); - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(MutexLock); - - /** Lock the itkMutexLock. */ - void - Lock(); - - /** Non-blocking Lock access. - \return bool - true if lock is captured, false if it was already held by someone else. - */ - bool - TryLock(); - - /** Unlock the MutexLock. */ - void - Unlock(); - -protected: - MutexLock() = default; - ~MutexLock() override = default; - - SimpleMutexLock m_SimpleMutexLock{}; - void - PrintSelf(std::ostream & os, Indent indent) const override; -}; - -inline void -MutexLock::Lock() -{ - m_SimpleMutexLock.Lock(); -} - -inline bool -MutexLock::TryLock() -{ - return m_SimpleMutexLock.TryLock(); -} - -inline void -MutexLock::Unlock() -{ - m_SimpleMutexLock.Unlock(); -} -} // namespace itk -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkMutexLockHolder.h b/Modules/Compatibility/Deprecated/include/itkMutexLockHolder.h deleted file mode 100644 index be0bd136c16..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkMutexLockHolder.h +++ /dev/null @@ -1,92 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#ifndef itkMutexLockHolder_h -#define itkMutexLockHolder_h - -#include "itkMacro.h" - -namespace itk -{ -/** - * \class MutexLockHolder - * \brief A container to store a Mutex. - * This holder class for ensuring that locks are released in - * the event of an exception being thrown after the lock was - * created. - * - * \ingroup ITKDeprecated - */ -template -class MutexLockHolder -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(MutexLockHolder); - - using Self = MutexLockHolder; - using MutexType = TMutex; - - MutexLockHolder(MutexType & mutex, const bool noblock = false) - : m_Mutex(mutex) - , m_LockCaptured(true) - { - if (noblock == false) - { - m_Mutex.Lock(); - } - else - { - m_LockCaptured = m_Mutex.TryLock(); - } - } - - /** True if the holder has acquired the lock, for no-blocking - + constructor this will always be true. - */ - inline bool - GetLockCaptured() const - { - return this->m_LockCaptured; - } - operator bool() const { return this->m_LockCaptured; } - - ~MutexLockHolder() - { - if (m_LockCaptured) - { - m_Mutex.Unlock(); - } - } - -protected: - MutexType & m_Mutex; - bool m_LockCaptured; -}; - -} // namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkPostOrderTreeIterator.h b/Modules/Compatibility/Deprecated/include/itkPostOrderTreeIterator.h deleted file mode 100644 index f79c269ae6e..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkPostOrderTreeIterator.h +++ /dev/null @@ -1,232 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkPostOrderTreeIterator_h -#define itkPostOrderTreeIterator_h - -#include "itkTreeIteratorBase.h" - -namespace itk -{ -template -class ITK_TEMPLATE_EXPORT PostOrderTreeIterator : public TreeIteratorBase -{ -public: - /** Typedefs */ - using Self = PostOrderTreeIterator; - using Superclass = TreeIteratorBase; - using TreeType = TTreeType; - using ValueType = typename TTreeType::ValueType; - using typename Superclass::TreeNodeType; - using typename Superclass::NodeType; - - /** Constructor */ - PostOrderTreeIterator(TreeType * tree); - - /** Get the type of the iterator */ - NodeType - GetType() const override; - - /** Clone function */ - TreeIteratorBase * - Clone() override; - -protected: - /** Return the next node */ - const ValueType & - Next() override; - - /** Return true if the next node exists */ - bool - HasNext() const override; - -protected: - const TreeNodeType * - FindNextNode() const; - - const TreeNodeType * - FindMostRightLeaf(TreeNodeType * node) const; - - const TreeNodeType * - FindSister(TreeNodeType * node) const; -}; - -/** Constructor */ -template -PostOrderTreeIterator::PostOrderTreeIterator(TTreeType * tree) - : TreeIteratorBase(tree, nullptr) -{ - if (tree->GetRoot() == nullptr) - { - this->m_Begin = nullptr; - } - else - { - const auto * root = dynamic_cast(tree->GetRoot()); - if (root == nullptr) - { - itkGenericExceptionMacro("Can't downcast root node to TreeNodeType *"); - } - this->m_Position = const_cast(root); - this->m_Position = const_cast(FindMostRightLeaf(this->m_Position)); - this->m_Begin = this->m_Position; - } -} - -/** Return the type of the iterator */ -template -auto -PostOrderTreeIterator::GetType() const -> NodeType -{ - return TreeIteratorBaseEnums::TreeIteratorBaseNode::POSTORDER; -} - -/** Return true if the next node exists */ -template -bool -PostOrderTreeIterator::HasNext() const -{ - if (const_cast(FindNextNode()) != nullptr) - { - return true; - } - return false; -} - -/** Go to the next node */ -template -const typename PostOrderTreeIterator::ValueType & -PostOrderTreeIterator::Next() -{ - this->m_Position = const_cast(FindNextNode()); - return this->m_Position->Get(); -} - -/** Find the next node */ -template -const typename PostOrderTreeIterator::TreeNodeType * -PostOrderTreeIterator::FindNextNode() const -{ - if (this->m_Position == nullptr || this->m_Position == this->m_Root) - { - return nullptr; - } - auto * sister = const_cast(FindSister(this->m_Position)); - - if (sister != nullptr) - { - return FindMostRightLeaf(sister); - } - if (this->m_Position->GetParent() == nullptr) - { - return nullptr; - } - auto * rval = dynamic_cast(this->m_Position->GetParent()); - if (rval == nullptr) - { - itkGenericExceptionMacro("Can't downcast to TreeNodeType *"); - } - return rval; -} - -/** Find the sister node */ -template -const typename PostOrderTreeIterator::TreeNodeType * -PostOrderTreeIterator::FindSister(TreeNodeType * node) const -{ - if (!node->HasParent()) - { - return nullptr; - } - - auto * parent = dynamic_cast(node->GetParent()); - if (parent == nullptr) - { - itkGenericExceptionMacro("Can't downcast to TreeNodeType *"); - } - - int childPosition = parent->ChildPosition(node); - int lastChildPosition = parent->CountChildren() - 1; - - while (childPosition < lastChildPosition) - { - if (parent->GetChild(childPosition + 1) == nullptr) - { - ++childPosition; - } - else - { - auto * sister = dynamic_cast(parent->GetChild(childPosition + 1)); - if (sister == nullptr) - { - itkGenericExceptionMacro("Can't downcast to TreeNodeType *"); - } - return sister; - } - } - return nullptr; -} - -/** Find the most right leaf */ -template -const typename PostOrderTreeIterator::TreeNodeType * -PostOrderTreeIterator::FindMostRightLeaf(TreeNodeType * node) const -{ - while (node->HasChildren()) - { - TreeNodeType * helpNode; - int childCount = node->CountChildren(); - int i = 0; - - do - { - if (node->GetChild(i) == nullptr) - { - helpNode = nullptr; - } - else - { - helpNode = dynamic_cast(node->GetChild(i)); - if (helpNode == nullptr) - { - itkGenericExceptionMacro("Can't downcast to TreeNodeType *"); - } - } - ++i; - } while (helpNode == nullptr && i < childCount); - - if (helpNode == nullptr) - { - return node; - } - node = helpNode; - } - return node; -} - -/** Clone function */ -template -TreeIteratorBase * -PostOrderTreeIterator::Clone() -{ - auto * clone = new PostOrderTreeIterator(const_cast(this->m_Tree)); - *clone = *this; - return clone; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkPreOrderTreeIterator.h b/Modules/Compatibility/Deprecated/include/itkPreOrderTreeIterator.h deleted file mode 100644 index 5de9ab18c96..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkPreOrderTreeIterator.h +++ /dev/null @@ -1,170 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkPreOrderTreeIterator_h -#define itkPreOrderTreeIterator_h - -#include "itkTreeIteratorBase.h" - -namespace itk -{ -// Forward reference because of circular dependencies -template -class ITK_TEMPLATE_EXPORT LeafTreeIterator; - -template -class ITK_TEMPLATE_EXPORT PreOrderTreeIterator : public TreeIteratorBase -{ -public: - /** Typedefs */ - using ValueType = typename TTreeType::ValueType; - using Superclass = TreeIteratorBase; - using typename Superclass::TreeNodeType; - using typename Superclass::NodeType; - - /** Constructor */ - PreOrderTreeIterator(const TTreeType * tree, const TreeNodeType * start = nullptr); - - /** Get the type of the iterator */ - NodeType - GetType() const override; - - /** Clone function */ - TreeIteratorBase * - Clone() override; - -protected: - /** Return the next node */ - const ValueType & - Next() override; - - /** Return true if the next node exists */ - bool - HasNext() const override; - -private: - /** Find the next node */ - const TreeNodeType * - FindNextNode() const; - - /** LeafTreeIterator uses PreOrderTreeIterator in its implementation, but it - * needs to adjust its root. A friend designation is added to correct - * behavior and retain backwards compatible behavior. */ - friend class LeafTreeIterator; -}; - -/** Constructor */ -template -PreOrderTreeIterator::PreOrderTreeIterator(const TTreeType * tree, const TreeNodeType * start) - : TreeIteratorBase(tree, start) -{} - -/** Return the type of the iterator */ -template -auto -PreOrderTreeIterator::GetType() const -> NodeType -{ - return TreeIteratorBaseEnums::TreeIteratorBaseNode::PREORDER; -} - -/** Return true if the next node exists */ -template -bool -PreOrderTreeIterator::HasNext() const -{ - if (const_cast(FindNextNode()) != nullptr) - { - return true; - } - return false; -} - -/** Return the next node */ -template -const typename PreOrderTreeIterator::ValueType & -PreOrderTreeIterator::Next() -{ - this->m_Position = const_cast(FindNextNode()); - if (this->m_Position == nullptr) - { - return this->m_Root->Get(); // value irrelevant, but we have to return something - } - return this->m_Position->Get(); -} - -/** Find the next node */ -template -const typename PreOrderTreeIterator::TreeNodeType * -PreOrderTreeIterator::FindNextNode() const -{ - if (this->m_Position == nullptr) - { - return nullptr; - } - if (this->m_Position->HasChildren()) - { - return dynamic_cast(this->m_Position->GetChild(0)); - } - - if (!this->m_Position->HasParent()) - { - return nullptr; - } - - TreeNodeType * child = this->m_Position; - TreeNodeType * parent = this->m_Position; - - while (parent->HasParent()) - { - child = parent; - parent = dynamic_cast(parent->GetParent()); - - // Subtree - if (parent->ChildPosition(this->m_Root) >= 0) - { - return nullptr; - } - - int childPosition = parent->ChildPosition(child); - int lastChildPosition = parent->CountChildren() - 1; - - while (childPosition < lastChildPosition) - { - auto * help = dynamic_cast(parent->GetChild(childPosition + 1)); - - if (help != nullptr) - { - return help; - } - ++childPosition; - } - } - return nullptr; -} - -/** Clone function */ -template -TreeIteratorBase * -PreOrderTreeIterator::Clone() -{ - auto * clone = new PreOrderTreeIterator(this->m_Tree, this->m_Position); - *clone = *this; - return clone; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkRootTreeIterator.h b/Modules/Compatibility/Deprecated/include/itkRootTreeIterator.h deleted file mode 100644 index 2276ef711c3..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkRootTreeIterator.h +++ /dev/null @@ -1,131 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkRootTreeIterator_h -#define itkRootTreeIterator_h - -#include "itkTreeIteratorBase.h" - -namespace itk -{ -template -class ITK_TEMPLATE_EXPORT RootTreeIterator : public TreeIteratorBase -{ -public: - /** Typedefs */ - using Superclass = TreeIteratorBase; - using TreeType = TTreeType; - using ValueType = typename TTreeType::ValueType; - using typename Superclass::TreeNodeType; - using typename Superclass::NodeType; - - /** Constructor */ - RootTreeIterator(TreeType * tree, const TreeNodeType * start = nullptr); - - /** Return the type of the iterator */ - NodeType - GetType() const override; - - /** Clone function */ - TreeIteratorBase * - Clone() override; - -protected: - /** Return the next node */ - const ValueType & - Next() override; - - /** Return true if the next node exists */ - bool - HasNext() const override; - -private: - /** Find the next node */ - const TreeNodeType * - FindNextNode() const; -}; - -/** Constructor */ -template -RootTreeIterator::RootTreeIterator(TTreeType * tree, const TreeNodeType * start) - : TreeIteratorBase(tree, start) -{ - if (start) - { - this->m_Begin = const_cast *>(start); - } - this->m_Root = tree->GetRoot(); - this->m_Position = this->m_Begin; -} - -/** Return the type of the iterator */ -template -auto -RootTreeIterator::GetType() const -> NodeType -{ - return TreeIteratorBaseEnums::TreeIteratorBaseNode::ROOT; -} - -/** Return true if the next node exists */ -template -bool -RootTreeIterator::HasNext() const -{ - if (const_cast(FindNextNode()) != nullptr) - { - return true; - } - return false; -} - -/** Go to the next node */ -template -const typename RootTreeIterator::ValueType & -RootTreeIterator::Next() -{ - this->m_Position = const_cast(FindNextNode()); - return this->m_Position->Get(); -} - -/** Find the next node */ -template -const typename RootTreeIterator::TreeNodeType * -RootTreeIterator::FindNextNode() const -{ - if (this->m_Position == nullptr) - { - return nullptr; - } - if (this->m_Position == this->m_Root) - { - return nullptr; - } - return this->m_Position->GetParent(); -} - -/** Clone function */ -template -TreeIteratorBase * -RootTreeIterator::Clone() -{ - auto * clone = new RootTreeIterator(const_cast(this->m_Tree), this->m_Position); - *clone = *this; - return clone; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkSimpleFastMutexLock.h b/Modules/Compatibility/Deprecated/include/itkSimpleFastMutexLock.h deleted file mode 100644 index 9a4679385d5..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkSimpleFastMutexLock.h +++ /dev/null @@ -1,80 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#ifndef itkSimpleFastMutexLock_h -#define itkSimpleFastMutexLock_h - -#include "itkMacro.h" -#include "itkThreadSupport.h" -#include "ITKDeprecatedExport.h" - -namespace itk -{ - -/** - * \class SimpleFastMutexLock - * \brief Critical section locking class that can be allocated on the stack. - * - * SimpleFastMutexLock is used by FastMutexLock to perform mutex locking. - * SimpleFastMutexLock is not a subclass of Object and is designed to be - * allocated on the stack. - * - * \ingroup OSSystemObjects - * \ingroup ITKDeprecated - */ - -// Critical Section object that is not a itkObject. -class ITKDeprecated_EXPORT SimpleFastMutexLock -{ -public: - /** Standard class type aliases. */ - using Self = SimpleFastMutexLock; - - /** Constructor and destructor left public purposely because of stack - allocation. */ - SimpleFastMutexLock(); - ~SimpleFastMutexLock(); - - /** Lock access. */ - void - Lock() const; - - /** Non-blocking Lock access. - \return bool - true if lock is captured, false if it was already held by someone else. - */ - bool - TryLock() const; - - /** Unlock access. */ - void - Unlock() const; - -protected: - mutable FastMutexType m_FastMutexLock; -}; -} // namespace itk -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeChangeEvent.h b/Modules/Compatibility/Deprecated/include/itkTreeChangeEvent.h deleted file mode 100644 index 6beb2385486..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeChangeEvent.h +++ /dev/null @@ -1,279 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeChangeEvent_h -#define itkTreeChangeEvent_h - -#include "itkMacro.h" -#include "itkEventObject.h" -#include "itkTreeIteratorBase.h" - -namespace itk -{ -/** \class TreeChangeEvent - * \brief Checks if the position of a node in the tree has been changed. - * - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT TreeChangeEvent : public ModifiedEvent -{ -public: - /** Typedefs */ - using Self = TreeChangeEvent; - using Superclass = ModifiedEvent; - - Self & - operator=(const Self &) = delete; - - /** Constructor */ - TreeChangeEvent() - : m_ChangePosition(nullptr) - {} - - /** Copy constructor */ - TreeChangeEvent(const TreeIteratorBase & position) { m_ChangePosition = &position; } - - /** Destructor */ - ~TreeChangeEvent() override = default; - - /** Get the event name */ - const char * - GetEventName() const override - { - return "TreeChangeEvent"; - } - - /** Check the event */ - bool - CheckEvent(const itk::EventObject * e) const override - { - return (dynamic_cast(e) != nullptr); - } - - /** Make the event object */ - itk::EventObject * - MakeObject() const override - { - return new Self(*m_ChangePosition); - } - - /** Get the change position */ - const TreeIteratorBase & - GetChangePosition() const - { - return *m_ChangePosition; - } - - // cppcheck-suppress uninitVar - TreeChangeEvent(const Self & s) - : itk::ModifiedEvent(s) - {} - -protected: - const TreeIteratorBase * m_ChangePosition{}; -}; - -/** \class TreeNodeChangeEvent - * \brief Signals that a node has been set to another value. The position of the - * changed node is provided. - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT TreeNodeChangeEvent : public TreeChangeEvent -{ -public: - using Self = TreeNodeChangeEvent; - using Superclass = TreeChangeEvent; - - TreeNodeChangeEvent() = default; - - TreeNodeChangeEvent(const TreeIteratorBase & position) - : TreeChangeEvent(position) - {} - - const char * - GetEventName() const override - { - return "TreeNodeChangeEvent"; - } - - bool - CheckEvent(const itk::EventObject * e) const override - { - auto eSelf = dynamic_cast(e); - return eSelf != nullptr; - } - - itk::EventObject * - MakeObject() const override - { - return new Self(*this->m_ChangePosition); - } - - TreeNodeChangeEvent(const Self & s) - : TreeChangeEvent(s) - {} - - void - operator=(const Self &) = delete; -}; - -/** \class TreeAddEvent - * \brief Checks if a node has been added to the tree. - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT TreeAddEvent : public TreeChangeEvent -{ -public: - /** Typedefs */ - using Self = TreeAddEvent; - using Superclass = TreeChangeEvent; - - /** Constructor */ - TreeAddEvent() = default; - - /** Copy constructor */ - TreeAddEvent(const TreeIteratorBase & position) - : TreeChangeEvent(position) - {} - - /** Get the name of the event */ - const char * - GetEventName() const override - { - return "TreeAddEvent"; - } - - /** Check event function */ - bool - CheckEvent(const itk::EventObject * e) const override - { - return (dynamic_cast(e) != nullptr); - } - - /** Make the event object */ - itk::EventObject * - MakeObject() const override - { - return new Self(*this->m_ChangePosition); - } - - TreeAddEvent(const Self & s) - : TreeChangeEvent(s) - {} - - void - operator=(const Self &) = delete; -}; - -/** \class TreeRemoveEvent - * \brief Checks if a node has been removed from the tree. - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT TreeRemoveEvent : public TreeChangeEvent -{ -public: - /** Typedefs */ - using Self = TreeRemoveEvent; - using Superclass = TreeChangeEvent; - - /** Constructor */ - TreeRemoveEvent() = default; - - /** Copy constructor */ - TreeRemoveEvent(const TreeIteratorBase & position) - : TreeChangeEvent(position) - {} - - /** Get the event name */ - const char * - GetEventName() const override - { - return "TreeRemoveEvent"; - } - - /** Check the event */ - bool - CheckEvent(const itk::EventObject * e) const override - { - return (dynamic_cast(e) != nullptr); - } - - /** Make the event object */ - itk::EventObject * - MakeObject() const override - { - return new Self(*this->m_ChangePosition); - } - - TreeRemoveEvent(const Self & s) - : TreeChangeEvent(s) - {} - - void - operator=(const Self &) = delete; -}; - -/** \class TreePruneEvent - * \brief Signals that a node and all its children will shortly be - * removed. The position of the top-level removed node is provided. - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT TreePruneEvent : public TreeRemoveEvent -{ -public: - using Self = TreePruneEvent; - using Superclass = TreeRemoveEvent; - - TreePruneEvent() = default; - - TreePruneEvent(const TreeIteratorBase & position) - : TreeRemoveEvent(position) - {} - - const char * - GetEventName() const override - { - return "TreePruneEvent"; - } - - bool - CheckEvent(const itk::EventObject * e) const override - { - return (dynamic_cast(e) != nullptr); - } - - itk::EventObject * - MakeObject() const override - { - return new Self(*this->m_ChangePosition); - } - - TreePruneEvent(const Self & s) - : TreeRemoveEvent(s) - {} - - void - operator=(const Self &) = delete; -}; -} // namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeContainer.h b/Modules/Compatibility/Deprecated/include/itkTreeContainer.h deleted file mode 100644 index 631071df4c4..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeContainer.h +++ /dev/null @@ -1,137 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeContainer_h -#define itkTreeContainer_h - -#include "itkTreeContainerBase.h" -#include "itkPreOrderTreeIterator.h" - -namespace itk -{ -/** \class TreeContainer - * \brief A tree container. - * - * This class derives from the TreeContainerBase class. - * The class is templated over the type of the elements. - * - * \tparam TValue Element type stored at each location in the Tree. - * - * \ingroup DataRepresentation - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT TreeContainer : public TreeContainerBase -{ -public: - /** Standard type alias */ - using Superclass = TreeContainerBase; - using Self = TreeContainer; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - using ValueType = TValue; - using TreeNodeType = TreeNode; - - /** Iterators type alias */ - using IteratorType = TreeIteratorBase; - using PreOrderIteratorType = PreOrderTreeIterator; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(TreeContainer); - - /** Constructor with default children count. */ - TreeContainer(int defaultChildrenCount); - - /** Constructor by adding a tree. */ - TreeContainer(TreeContainer & tree); - - /** Set the specified element as the root. */ - bool - SetRoot(const TValue element) override; - - /** Set the specified iterator position as the root. */ - bool - SetRoot(IteratorType & pos); - - /** Set the specified tree node as the root. */ - bool - SetRoot(TreeNode * node) override; - - /** Return true if the element is in the tree. */ - bool - Contains(const TValue element) override; - - /** Return the number of elements in the tree. */ - int - Count() const override; - - /** Return true if the node containing the given element is a leaf of the tree. */ - bool - IsLeaf(const TValue element) override; - - /** Return true if the node containing the given element is the root. */ - bool - IsRoot(const TValue element) override; - - /** Clear the tree. */ - bool - Clear() override; - - /** operator equal. */ - bool - operator==(TreeContainer & tree); - - /** Swap the iterators. */ - bool - Swap(IteratorType & v, IteratorType & w); - - /** Get the root. */ - const TreeNodeType * - GetRoot() const override - { - return m_Root.GetPointer(); - } - - /** Add a child to a given parent. */ - bool - Add(const TValue child, const TValue parent); - - /** Get the node corresponding to the given a value. */ - const TreeNodeType * - GetNode(TValue val) const; - -protected: - TreeContainer(); - ~TreeContainer() override = default; - - typename TreeNodeType::Pointer m_Root{}; - - int m_DefaultChildrenCount{}; - - void - PrintSelf(std::ostream & os, Indent indent) const override; -}; -} // namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -# include "itkTreeContainer.hxx" -#endif - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeContainer.hxx b/Modules/Compatibility/Deprecated/include/itkTreeContainer.hxx deleted file mode 100644 index 9fcdabef877..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeContainer.hxx +++ /dev/null @@ -1,331 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeContainer_hxx -#define itkTreeContainer_hxx - - -namespace itk -{ - -template -TreeContainer::TreeContainer() -{ - m_Root = nullptr; - this->SetSubtree(false); - m_DefaultChildrenCount = 2; -} - -template -TreeContainer::TreeContainer(int dcc) -{ - m_Root = nullptr; - this->SetSubtree(false); - m_DefaultChildrenCount = dcc; -} - -template -TreeContainer::TreeContainer(TreeContainer &) -{ - m_Root = nullptr; - this->SetSubtree(false); - m_DefaultChildrenCount = 3; -} - -template -bool -TreeContainer::SetRoot(const TValue element) -{ - m_Root = TreeNodeType::New(); - m_Root->Set(element); - m_Root->SetParent(nullptr); - return true; -} - -template -bool -TreeContainer::SetRoot(TreeNode * node) -{ - m_Root = node; - return true; -} - -template -int -TreeContainer::Count() const -{ - if (!m_Root) - { - return 0; - } - int size = 0; - PreOrderTreeIterator it(this, this->m_Root); - it.GoToBegin(); - while (!it.IsAtEnd()) - { - ++size; - ++it; - } - return size; -} - -template -bool -TreeContainer::Swap(IteratorType & v, IteratorType & w) -{ - TreeNode * nv = v.GetNode(); - TreeNode * nw = w.GetNode(); - - if (nv == nullptr || nw == nullptr) - { - return false; - } - TreeNode * pv = nv->GetParent(); - TreeNode * pw = nw->GetParent(); - - if (pv == nullptr && pw == nullptr) - { - return false; - } - else if (pv == nullptr) - { - pw->ReplaceChild(nw, nv); - m_Root = nw; - } - else if (pw == nullptr) - { - pv->ReplaceChild(nv, nw); - m_Root = nv; - } - else - { - pv->ReplaceChild(nv, nw); - pw->ReplaceChild(nw, nv); - } - - nv->SetParent(pw); - nw->SetParent(pv); - - return true; -} - -template -bool -TreeContainer::Contains(const TValue element) -{ - PreOrderTreeIterator it(this, m_Root); - it.GoToBegin(); - while (!it.IsAtEnd()) - { - if (it.Get() == element) - { - return true; - } - ++it; - } - return false; -} - -template -bool -TreeContainer::operator==(TreeContainer & tree) -{ - PreOrderTreeIterator it(this, m_Root); - it.GoToBegin(); - PreOrderTreeIterator it2(&tree, tree.GetRoot()); - it2.GoToBegin(); - - while ((!it.IsAtEnd()) && (!it2.IsAtEnd())) - { - if (it.Get() != it2.Get()) - { - return false; - } - ++it; - ++it2; - } - - return true; -} - -template -bool -TreeContainer::IsLeaf(TValue element) -{ - PreOrderTreeIterator it(this, m_Root); - it.GoToBegin(); - while (!it.IsAtEnd()) - { - if (it.Get() == element) - { - if (it.IsLeaf()) - { - return true; - } - else - { - return false; - } - } - } - return false; -} - -template -bool -TreeContainer::IsRoot(TValue element) -{ - PreOrderTreeIterator it(this, m_Root); - it.GoToBegin(); - while (!it.IsAtEnd()) - { - if (it.Get() == element) - { - if (!it.HasParent()) - { - return true; - } - else - { - return false; - } - } - ++it; - } - return false; -} - -template -bool -TreeContainer::Clear() -{ - PreOrderTreeIterator it(this, m_Root); - bool success = it.Remove(); - m_Root = nullptr; - return success; -} - -template -const TreeNode * -TreeContainer::GetNode(TValue val) const -{ - PreOrderTreeIterator it(this, m_Root); - it.GoToBegin(); - while (!it.IsAtEnd()) - { - if (it.Get() == val) - { - return it.GetNode(); - } - ++it; - } - return nullptr; -} - -template -bool -TreeContainer::SetRoot(IteratorType & pos) -{ - if (this->m_SubTree) - { - return false; - } - TreeNode * node = pos.GetNode(); - if (node == nullptr) - { - return false; - } - - TreeNode * parent = node->GetParent(); - TreeNode * help = nullptr; - - if (parent == nullptr) - { - return false; - } - - m_Root = node; - node->AddChild(parent); - parent->Remove(node); - node->SetParent(nullptr); - help = parent->GetParent(); - parent->SetParent(node); - node = parent; - - while (help != nullptr) - { - parent = help; - help = help->GetParent(); - node->AddChild(parent); - parent->Remove(node); - parent->SetParent(node); - node = parent; - } - return true; -} - -template -bool -TreeContainer::Add(const TValue child, const TValue parent) -{ - if (!m_Root) - { - std::cout << "TreeContainer::Add() : The tree is empty" << std::endl; - return false; - } - // Find the first node in the tree that has the parent value - PreOrderTreeIterator it(this, m_Root); - it.GoToBegin(); - while (!it.IsAtEnd()) - { - if (it.Get() == parent) - { - it.Add(child); - return true; - } - ++it; - } - return false; -} - -template -void -TreeContainer::PrintSelf(std::ostream & os, Indent indent) const -{ - Superclass::PrintSelf(os, indent); - os << indent << "Number of objects = " << this->Count() << std::endl; - - if (this->Count() > 0) - { - os << indent << "Tree:" << std::endl; - // Now prints the tree - PreOrderTreeIterator it(this, m_Root); - it.GoToBegin(); - while (!it.IsAtEnd()) - { - if (it.GetParent()) - { - std::cout << it.GetParent()->Get() << " <- "; - } - std::cout << it.Get() << std::endl; - ++it; - } - } -} -} // namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeContainerBase.h b/Modules/Compatibility/Deprecated/include/itkTreeContainerBase.h deleted file mode 100644 index 032a392fd79..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeContainerBase.h +++ /dev/null @@ -1,94 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeContainerBase_h -#define itkTreeContainerBase_h - -#include "itkMacro.h" -#include -#include "itkTreeNode.h" - -namespace itk -{ -/** \class TreeContainerBase - * \brief A base class for tree containers. - * - * \ingroup DataRepresentation - * \ingroup ITKDeprecated - */ -template -class TreeContainerBase : public Object -{ -public: - using Superclass = Object; - using Self = TreeContainerBase; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - using ValueType = TValue; - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(TreeContainerBase); - - /** Set the root element. - * A new node is created and the element is added to the node */ - virtual bool - SetRoot(const TValue element) = 0; - - /** Set the root has a node */ - virtual bool - SetRoot(TreeNode * node) = 0; - - /** Return true if the tree contains the element */ - 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 TValue element) = 0; - - /** Return if the element is root */ - virtual bool - IsRoot(const TValue element) = 0; - - /** Clear the tree */ - virtual bool - Clear() = 0; - - /** Get the root as a node */ - virtual const TreeNode * - GetRoot() const = 0; - - /** Set if the tree is a subtree */ - void - SetSubtree(bool val) - { - m_SubTree = val; - } - -protected: - TreeContainerBase() = default; - ~TreeContainerBase() override = default; - bool m_SubTree{ false }; -}; -} // namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeIteratorBase.h b/Modules/Compatibility/Deprecated/include/itkTreeIteratorBase.h deleted file mode 100644 index 464ab68fd1e..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeIteratorBase.h +++ /dev/null @@ -1,293 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeIteratorBase_h -#define itkTreeIteratorBase_h - -#include "itkTreeNode.h" - -namespace itk -{ -/** \class TreeIteratorBaseEnums - * \brief Enum classes used in the TreeIteratorBase class. - * \ingroup ITKDeprecated - */ -class TreeIteratorBaseEnums -{ -public: - /** \class TreeIteratorBaseNode - * \ingroup ITKDeprecated - * Enumerations for node type - */ - enum class TreeIteratorBaseNode : uint8_t - { - UNDEFIND = 0, - PREORDER = 1, - INORDER = 2, - POSTORDER = 3, - LEVELORDER = 4, - CHILD = 5, - ROOT = 6, - LEAF = 7 - }; -}; -// Define how to print enumeration -extern ITKCOMMON_DEPRECATED_EXPORT std::ostream & - operator<<(std::ostream & out, const TreeIteratorBaseEnums::TreeIteratorBaseNode value); -/** \class TreeIteratorBase - * \brief This class provides the base implementation for tree iterators. - * - * Events will notify interested observers about tree changes. These events all derive from TreeChangeEvent. They are: - * - * - TreeNodeChangeEvent: invoked when Set() is called, i.e. exactly one node changes - * - TreeAddEvent: invoked when Add() is called. - * - TreeRemoveEvent: when a single node has been removed, i.e. Disconnect() has been called. - * - TreePruneEvent: when a node and all its children were removed, i.e. Remove() has been called. - * - * All those events have a member GetChangePosition(), which returns an iterator to the position that has changed. - * Please note that this iterator may not be fully functional, but you should always be able to use its Get() method to - * retrieve the thing it points to. - * - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT TreeIteratorBase -{ -public: - /** Typedefs */ - using Self = TreeIteratorBase; - using ValueType = typename TTreeType::ValueType; - using TreeNodeType = typename TTreeType::TreeNodeType; - using ChildIdentifier = typename TreeNodeType::ChildIdentifier; - - /** Backwards compatibility for enum values */ - using NodeType = TreeIteratorBaseEnums::TreeIteratorBaseNode; -#if !defined(ITK_LEGACY_REMOVE) - // We need to expose the enum values at the class level - // for backwards compatibility - static constexpr NodeType UNDEFIND = NodeType::UNDEFIND; - static constexpr NodeType PREORDER = NodeType::PREORDER; - static constexpr NodeType INORDER = NodeType::INORDER; - static constexpr NodeType POSTORDER = NodeType::POSTORDER; - static constexpr NodeType LEVELORDER = NodeType::LEVELORDER; - static constexpr NodeType CHILD = NodeType::CHILD; - static constexpr NodeType ROOT = NodeType::ROOT; - static constexpr NodeType LEAF = NodeType::LEAF; -#endif - - /** Add an element to the tree at the current node. - * - * Creates a new child node. - */ - virtual bool - Add(ValueType element); - - /** Add an element to the tree at a given position. */ - virtual bool - Add(int position, ValueType element); - - /** Add a subtree. */ - virtual bool - Add(TTreeType & subTree); - - /** Get the value of the current node. */ - virtual const ValueType & - Get() const; - - /** Get the subtree. */ - virtual TTreeType * - GetSubTree() const; - - /** Return true if the current node is a leaf. */ - virtual bool - IsLeaf() const; - - /** Return true if the current node is a root */ - virtual bool - IsRoot() const; - - /** Get the type of iterator */ - virtual NodeType - GetType() const = 0; - - /** Go to the specified child. */ - virtual bool - GoToChild(ChildIdentifier number = 0); - - /** Go to the parent of the current node. */ - virtual bool - GoToParent(); - - /** Set the specified value to the current node. */ - void - Set(ValueType element); - - /** Return true if the current node has a child. */ - virtual bool - HasChild(int number = 0) const; - - /** Return the current child position of an element. */ - virtual int - ChildPosition(ValueType element) const; - - /** Remove a child. - * - * Removes its child nodes as well. - * / - virtual bool - RemoveChild(int number); - - /** Count the number of children. */ - virtual int - CountChildren() const; - - /** Return true if the current node has a parent. */ - virtual bool - HasParent() const; - - /** Disconnect the tree. */ - virtual bool - Disconnect(); - - /** Return a list of children. */ - virtual TreeIteratorBase * - Children(); - - /** Return the list of parents. */ - virtual TreeIteratorBase * - Parents(); - - /** Get the child corresponding to the given a number at the current node. */ - virtual TreeIteratorBase * - GetChild(int number) const; - - /** Count the number of nodes. */ - virtual int - Count(); - - /** Remove the current node from the tree. */ - bool - Remove(); - - /** Get the current node. */ - virtual TreeNodeType * - GetNode(); - - virtual const TreeNodeType * - GetNode() const; - - /** Get the root. */ - TreeNodeType * - GetRoot(); - - const TreeNodeType * - GetRoot() const; - - /** Get the tree. */ - TTreeType * - GetTree() const; - - /** Return the first parent found. */ - const TreeNodeType * - GetParent() const; - - /** Move an iterator to the beginning of the tree. */ - void - GoToBegin() - { - m_Position = m_Begin; - } - - /** Move an iterator to the end of the tree. */ - void - GoToEnd() - { - m_Position = nullptr; - } - - /** Is the iterator at the beginning of the tree? */ - bool - IsAtBegin() const - { - return (m_Position == m_Begin); - } - - /** Is the iterator at the end of the tree? */ - bool - IsAtEnd() const - { - return (m_Position == nullptr); - } - - /** Clone the iterator */ - virtual TreeIteratorBase * - Clone() = 0; - - /** operator++ */ - Self & - operator++() - { - this->Next(); - return *this; - } - - /** operator++ */ - void - operator++(int) - { - this->Next(); - } - - /** operator = */ - Self & - operator=(const Self & iterator) - { - if (this != &iterator) - { - m_Position = iterator.m_Position; - m_Begin = iterator.m_Begin; - m_Root = iterator.m_Root; - m_Tree = iterator.m_Tree; - } - return *this; - } - - virtual ~TreeIteratorBase() = default; - -protected: - /** Constructors */ - TreeIteratorBase(TTreeType * tree, const TreeNodeType * start); - TreeIteratorBase(const TTreeType * tree, const TreeNodeType * start); - - mutable TreeNodeType * m_Position{}; // Current position of the iterator - mutable TreeNodeType * m_Begin{}; - const TreeNodeType * m_Root{}; - TTreeType * m_Tree{}; - - virtual bool - HasNext() const = 0; - - virtual const ValueType & - Next() = 0; -}; -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -# include "itkTreeIteratorBase.hxx" -#endif - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeIteratorBase.hxx b/Modules/Compatibility/Deprecated/include/itkTreeIteratorBase.hxx deleted file mode 100644 index 5f4a77a4007..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeIteratorBase.hxx +++ /dev/null @@ -1,503 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeIteratorBase_hxx -#define itkTreeIteratorBase_hxx - -#include "itkTreeChangeEvent.h" - -/** There are some weird circular #include dependencies between TreeChangeEvent - * and TreeIteratorBase that cause the HeaderTest to fail without these forward - * declarations. */ -template -class ITK_TEMPLATE_EXPORT TreeNodeChangeEvent; - -template -class ITK_TEMPLATE_EXPORT TreeAddEvent; - -template -class ITK_TEMPLATE_EXPORT TreePruneEvent; - -template -class ITK_TEMPLATE_EXPORT TreeRemoveEvent; - -namespace itk -{ - -template -TreeIteratorBase::TreeIteratorBase(TTreeType * tree, const TreeNodeType * start) -{ - if (start) - { - m_Root = start; - } - else - { - m_Root = dynamic_cast(tree->GetRoot()); - } - - m_Position = const_cast(m_Root); - m_Tree = tree; - m_Begin = m_Position; -} - -template -TreeIteratorBase::TreeIteratorBase(const TTreeType * tree, const TreeNodeType * start) -{ - if (start) - { - m_Root = start; - } - else - { - m_Root = const_cast(dynamic_cast(tree->GetRoot())); - } - m_Position = const_cast(m_Root); - m_Tree = const_cast(tree); - m_Begin = m_Position; -} - -template -auto -TreeIteratorBase::Get() const -> const ValueType & -{ - return m_Position->Get(); -} - -template -void -TreeIteratorBase::Set(ValueType element) -{ - // itkAssertInDebugAndIgnoreInReleaseMacro(m_Position); - m_Position->Set(element); - m_Tree->Modified(); - m_Tree->InvokeEvent(TreeNodeChangeEvent(*this)); -} - -template -bool -TreeIteratorBase::Add(ValueType element) -{ - if (m_Position == nullptr && m_Root == nullptr) - { - bool returnValue = const_cast(m_Tree)->SetRoot(element); - // signal AddEvent for self - m_Root = dynamic_cast(const_cast(m_Tree)->GetRoot()); - m_Position = const_cast(m_Root); - m_Tree->Modified(); - m_Tree->InvokeEvent(TreeAddEvent(*this)); - return returnValue; - } - else if (m_Position == nullptr) - { - return false; - } - - auto node = TreeNodeType::New(); - node->Set(element); - m_Position->AddChild(node); - m_Tree->Modified(); - - // signal AddEvent for new child - TreeIteratorBase * childIterator = Clone(); - childIterator->m_Position = dynamic_cast(m_Position->GetChild(m_Position->ChildPosition(node))); - // signal "child has been added deleted" - m_Tree->InvokeEvent(TreeAddEvent(*childIterator)); - delete childIterator; - - return true; -} - -template -bool -TreeIteratorBase::Add(int itkNotUsed(childPosition), ValueType element) -{ - if (m_Position) - { - auto node = TreeNodeType::New(); - node->Set(element); - m_Position->AddChild(node); - m_Tree->Modified(); - - // signal AddEvent - TreeIteratorBase * childIterator = Clone(); - childIterator->m_Position = dynamic_cast(m_Position->GetChild(m_Position->ChildPosition(node))); - // signal "child has been added deleted" - m_Tree->InvokeEvent(TreeAddEvent(*childIterator)); - delete childIterator; - - return true; - } - return false; -} - -template -bool -TreeIteratorBase::IsLeaf() const -{ - return !(m_Position->HasChildren()); -} - -template -bool -TreeIteratorBase::IsRoot() const -{ - if (m_Root == nullptr) - { - return false; - } - - if (m_Position == m_Root) - { - return true; - } - return false; -} - -template -bool -TreeIteratorBase::Add(TTreeType & subTree) -{ - if (subTree.Count() == 0) - { - return false; - } - - if (!subTree.GetRoot()) - { - return false; - } - - if (m_Root == nullptr) - { - m_Root = static_cast(subTree.GetRoot()); - } - else - { - if (m_Position == nullptr) - { - return false; - } - m_Position->AddChild(const_cast(static_cast(subTree.GetRoot()))); - } - return true; -} - -template -TTreeType * -TreeIteratorBase::GetSubTree() const -{ - auto tree = TTreeType::New(); - tree->SetRoot(m_Position); - tree->SetSubtree(true); - return tree; -} - -template -bool -TreeIteratorBase::HasChild(int number) const -{ - if (m_Position == nullptr) - { - return false; - } - if (m_Position->GetChild(number) != nullptr) - { - return true; - } - return false; -} - -template -int -TreeIteratorBase::ChildPosition(ValueType element) const -{ - if (!m_Position) - { - return -1; - } - return m_Position->ChildPosition(element); -} - -template -bool -TreeIteratorBase::RemoveChild(int number) -{ - if (!HasChild(number)) - { - return false; - } - auto * child = dynamic_cast(m_Position->GetChild(number)); - - if (child != nullptr) - { - // signal PruneEvent (node plus all children are removed) - TreeIteratorBase * childIterator = Clone(); - childIterator->m_Position = child; - // signal "child has been added deleted" - m_Tree->InvokeEvent(TreePruneEvent(*childIterator)); - delete childIterator; - - // and really remove child (and subitems) - const_cast(m_Position)->Remove(child); - m_Tree->Modified(); - return true; - } - return false; -} - -template -int -TreeIteratorBase::CountChildren() const -{ - if (m_Position == nullptr) - { - return -1; - } - return m_Position->CountChildren(); -} - -template -bool -TreeIteratorBase::HasParent() const -{ - return (m_Position != nullptr && m_Position->GetParent() != nullptr); -} - -template -bool -TreeIteratorBase::Disconnect() -{ - if (m_Position == nullptr) - { - return false; - } - - if (m_Position->HasParent() == false) - { - return false; - } - - // keep node alive just a bit longer - typename TreeNodeType::Pointer position = m_Position; - - auto * parent = dynamic_cast(m_Position->GetParent()); - parent->Remove(const_cast(m_Position)); - m_Tree->Modified(); - - while (m_Position->CountChildren() > 0) - { - // always add first child in list, because AddChild() removes the added node - // from - // its former parent (== m_position) - auto * child = dynamic_cast(m_Position->GetChild(0)); - parent->AddChild(child); - } - - m_Tree->InvokeEvent(TreeRemoveEvent(*this)); - - m_Position = nullptr; - return true; -} - -template -TreeIteratorBase * -TreeIteratorBase::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 nullptr; -} - -template -auto -TreeIteratorBase::GetParent() const -> const TreeNodeType * -{ - if (m_Position == nullptr) - { - return nullptr; - } - - return m_Position->GetParent(); -} - -template -TreeIteratorBase * -TreeIteratorBase::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 nullptr; -} - -template -bool -TreeIteratorBase::GoToChild(ChildIdentifier number) -{ - if (m_Position == nullptr) - { - return false; - } - - auto * next = dynamic_cast(m_Position->GetChild(number)); - - if (next == nullptr) - { - return false; - } - m_Position = next; - return true; -} - -template -bool -TreeIteratorBase::GoToParent() -{ - if (m_Position == nullptr) - { - return false; - } - - if (!m_Position->HasParent()) - { - return false; - } - - m_Position = dynamic_cast(m_Position->GetParent()); - return true; -} - -template -TreeIteratorBase * -TreeIteratorBase::GetChild(int number) const -{ - if (!m_Position) - { - return nullptr; - } - - auto * child = dynamic_cast(m_Position->GetChild(number)); - - if (!child) - { - return nullptr; - } - // return new WalkTreeIterator( child, m_Root, m_Tree, getType() - // ); - return nullptr; -} - -template -int -TreeIteratorBase::Count() -{ - int size = 0; - - this->GoToBegin(); - if (!m_Position->HasChildren()) - { - return 0; - } - while (this->Next()) - { - ++size; - } - return size; -} - -template -auto -TreeIteratorBase::GetNode() -> TreeNodeType * -{ - return const_cast(m_Position); -} - -template -auto -TreeIteratorBase::GetNode() const -> const TreeNodeType * -{ - return m_Position; -} - -template -auto -TreeIteratorBase::GetRoot() -> TreeNodeType * -{ - return const_cast(m_Root); -} - -template -auto -TreeIteratorBase::GetRoot() const -> const TreeNodeType * -{ - return m_Root; -} - -template -bool -TreeIteratorBase::Remove() -{ - if (m_Position == nullptr) - { - return false; - } - - // keep node alive just a bit longer (for the notification) - typename TreeNodeType::Pointer position = m_Position; - - if (m_Position->HasParent()) - { - TreeNodeType * parent = m_Position->GetParent(); - // removes this node (and implicitly all children, too) - parent->Remove(m_Position); - } - else if (m_Root == m_Position) - { - m_Root = nullptr; - m_Tree->SetRoot((TreeNodeType *)nullptr); - // this won't do anything if root is already != nullptr ==> root cannot be - // removed - } - - m_Position->SetParent(nullptr); // we don't have a parent anymore - m_Tree->InvokeEvent(TreePruneEvent(*this)); - while (m_Position->CountChildren() > 0) // remove all children - { - // always remove first child (id 0) - auto * child = dynamic_cast(m_Position->GetChild(0)); - m_Position->Remove(child); - } - - position = nullptr; - m_Position = nullptr; // Smart pointer, deletes *m_Position - - m_Tree->Modified(); - - return true; -} - -template -TTreeType * -TreeIteratorBase::GetTree() const -{ - return m_Tree; -} -} // namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeIteratorClone.h b/Modules/Compatibility/Deprecated/include/itkTreeIteratorClone.h deleted file mode 100644 index 6c5b156cd87..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeIteratorClone.h +++ /dev/null @@ -1,211 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeIteratorClone_h -#define itkTreeIteratorClone_h - -#include "itkMacro.h" -#include - -namespace itk -{ -/** \class TreeIteratorClone - * \brief itkTreeIteratorClone class - * \ingroup DataRepresentation - * \ingroup ITKDeprecated - */ -template -class TreeIteratorClone -{ -public: - /** Typedefs */ - using Self = TreeIteratorClone; - using ObjectType = TObjectType; - - /** Constructor */ - TreeIteratorClone() { m_Pointer = 0; } - - /** Copy constructor */ - TreeIteratorClone(const TreeIteratorClone & p) - { - m_Pointer = nullptr; - if (p.m_Pointer != nullptr) - { - m_Pointer = p.m_Pointer->Clone(); - } - } - - /** Constructor to pointer p */ - TreeIteratorClone(ObjectType * p) - { - m_Pointer = 0; - if (p != nullptr) - { - m_Pointer = p->Clone(); - } - } - - /** Constructor to reference p */ - TreeIteratorClone(const ObjectType & p) - { - m_Pointer = nullptr; - m_Pointer = const_cast(&p)->Clone(); - } - - /** Destructor */ - ~TreeIteratorClone() - { - delete m_Pointer; - m_Pointer = nullptr; - } - - /** Overload operator -> */ - ObjectType * operator->() const { return m_Pointer; } - - /** Test if the pointer has been initialized */ - bool - IsNotNull() const - { - return m_Pointer != 0; - } - bool - IsNull() const - { - return m_Pointer == 0; - } - - /** Template comparison operators. */ - template - bool - operator==(TR r) const - { - return (m_Pointer == (ObjectType *)(r)); - } - -#ifndef ITK_EXPERIMENTAL_CXX20_REWRITTEN_UNEQUAL_OPERATOR - template - bool - operator!=(TR r) const - { - return (m_Pointer != (ObjectType *)(r)); - } -#endif - - /** Access function to pointer. */ - ObjectType * - GetPointer() const - { - return m_Pointer; - } - - /** Comparison of pointers. Less than comparison. */ - bool - operator<(const TreeIteratorClone & r) const - { - return (void *)m_Pointer < (void *)r.m_Pointer; - } - - /** Comparison of pointers. Greater than comparison. */ - bool - operator>(const TreeIteratorClone & r) const - { - return (void *)m_Pointer > (void *)r.m_Pointer; - } - - /** Comparison of pointers. Less than or equal to comparison. */ - bool - operator<=(const TreeIteratorClone & r) const - { - return (void *)m_Pointer <= (void *)r.m_Pointer; - } - - /** Comparison of pointers. Greater than or equal to comparison. */ - bool - operator>=(const TreeIteratorClone & r) const - { - return (void *)m_Pointer >= (void *)r.m_Pointer; - } - - /** Overload operator assignment. */ - TreeIteratorClone & - operator=(const TreeIteratorClone & r) - { - return this->operator=(r.GetPointer()); - } - - /** Overload operator assignment. */ - TreeIteratorClone & - operator=(const ObjectType * r) - { - if (m_Pointer != r) - { - delete m_Pointer; - m_Pointer = nullptr; - if (r != nullptr) - { - m_Pointer = const_cast(r)->Clone(); - } - } - return *this; - } - - Self & - operator++() - { - if (m_Pointer) - { - ++(*m_Pointer); - } - return *this; - } - - const Self - operator++(int) - { - if (m_Pointer) - { - const Self oldValue(m_Pointer); // create a copy of the iterator behind - // the pointer (Clone()) - ++(*m_Pointer); - return oldValue; - } - } - - /** Function to print object pointed to */ - ObjectType * - Print(std::ostream & os) const - { - // This prints the object pointed to by the pointer - m_Pointer->Print(os); - return m_Pointer; - } - -private: - /** The pointer to the object referred to by this smart pointer. */ - ObjectType * m_Pointer; -}; - -template -std::ostream & -operator<<(std::ostream & os, const TreeIteratorClone p) -{ - p.Print(os); - return os; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeNode.h b/Modules/Compatibility/Deprecated/include/itkTreeNode.h deleted file mode 100644 index a4326c6dcd6..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeNode.h +++ /dev/null @@ -1,156 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeNode_h -#define itkTreeNode_h - -#include -#include -#include -#include "itkObject.h" -#include "itkObjectFactory.h" -#include "itkIntTypes.h" - -namespace itk -{ -/** \class TreeNode - * \brief Represents a node in a tree. - * - * This class derives from the Object class. - * - * The class is templated over the type of the elements. - * - * \tparam TValue = Element type stored in the node - * - * \ingroup DataRepresentation - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT TreeNode : public Object -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(TreeNode); - - /** Standard type alias */ - using Superclass = Object; - using Self = TreeNode; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - using ChildrenListType = std::vector; - using ChildIdentifier = itk::OffsetValueType; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(TreeNode); - - /** Get the value of the node */ - const TValue & - Get() const; - - /** Set the current value of the node */ - TValue - Set(const TValue data); - - /** Get the child node */ - Self * - GetChild(ChildIdentifier number) const; - - /** Get the parent node */ - Self * - GetParent() const; - - /** Return true if the node has children */ - bool - HasChildren() const; - - /** Return true if the node has a parent */ - bool - HasParent() const; - - /** Set the parent of the node */ - void - SetParent(Self * n); - - /** Return the number of children */ - ChildIdentifier - CountChildren() const; - - /** Remove a node from the node */ - bool - Remove(Self * n); - - /** Get the number of children given a name and depth */ - ChildIdentifier - GetNumberOfChildren(unsigned int depth = 0, char * name = nullptr) const; - - /** Replace a given child by a new one */ - bool - ReplaceChild(Self * oldChild, Self * newChild); - - /** Return the child position given a node */ - ChildIdentifier - ChildPosition(const Self * node) const; - - /** Return the child position given a value */ - ChildIdentifier - ChildPosition(TValue node) const; - - /** Add a child to the node */ - void - AddChild(Self * node); - - /** Add a child to the node and specify the number in the children list */ - virtual void - AddChild(ChildIdentifier number, Self * node); - - /** Get the children list */ -#if !defined(ITK_WRAPPING_PARSER) - virtual ChildrenListType * - GetChildren(unsigned int depth = 0, char * name = nullptr) const; - -#endif - - /** Get the internal list of children */ -#if !defined(ITK_WRAPPING_PARSER) - virtual ChildrenListType & - GetChildrenList() - { - return m_Children; - } -#endif - - /** Set the data of the node */ - // virtual void SetData(TValue data) {m_Data = data;} - -protected: - TreeNode() = default; - ~TreeNode() override; - - TValue m_Data{}; - Self * m_Parent{ nullptr }; - - ChildrenListType m_Children{}; -}; -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -# include "itkTreeNode.hxx" -#endif - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkTreeNode.hxx b/Modules/Compatibility/Deprecated/include/itkTreeNode.hxx deleted file mode 100644 index 6c86145786b..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkTreeNode.hxx +++ /dev/null @@ -1,303 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkTreeNode_hxx -#define itkTreeNode_hxx - -#include "itkMacro.h" -#include - -namespace itk -{ - -/** Destructor */ -template -TreeNode::~TreeNode() -{ - if (m_Parent) - { - m_Parent->Remove(this); - } - - const auto numberOfChildren = static_cast(m_Children.size()); - - for (ChildIdentifier i = numberOfChildren; i > 0; i--) - { - m_Children[i - 1]->SetParent(nullptr); - } - m_Children.clear(); - m_Parent = nullptr; - m_Data = 0; -} - -/** Return the parent node */ -template -TreeNode * -TreeNode::GetParent() const -{ - return m_Parent; -} - -/** Get a child */ -template -TreeNode * -TreeNode::GetChild(ChildIdentifier number) const -{ - const auto numberOfChildren = static_cast(m_Children.size()); - - if (number < numberOfChildren) - { - return m_Children[number]; - } - else - { - return nullptr; - } -} - -/** Set the value of a node */ -template -TValue -TreeNode::Set(const TValue data) -{ - TValue help = m_Data; - - m_Data = data; - return help; -} - -/** Get the data of node */ -template -const TValue & -TreeNode::Get() const -{ - return m_Data; -} - -/** Return true if has a parent */ -template -bool -TreeNode::HasParent() const -{ - return (m_Parent) ? true : false; -} - -/** Set the parent node */ -template -void -TreeNode::SetParent(TreeNode * node) -{ - // keep ourself alive just a bit longer - Pointer ourself = this; - - if (m_Parent != nullptr) - { - m_Parent->Remove(this); - } - m_Parent = node; -} - -/** Return true if the node has children */ -template -bool -TreeNode::HasChildren() const -{ - return (!m_Children.empty()) ? true : false; -} - -/** Return the number of children */ -template -auto -TreeNode::CountChildren() const -> ChildIdentifier -{ - return static_cast(m_Children.size()); -} - -/** Remove a child node from the current node */ -template -bool -TreeNode::Remove(Self * n) -{ - typename std::vector::iterator pos; - pos = std::find(m_Children.begin(), m_Children.end(), n); - if (pos != m_Children.end()) - { - // keep node alive just a bit longer - Pointer position = n; - m_Children.erase(pos); - n->SetParent(nullptr); - return true; - } - return false; -} - -/** Replace a child by a new one */ -template -bool -TreeNode::ReplaceChild(Self * oldChild, Self * newChild) -{ - const auto numberOfChildren = static_cast(m_Children.size()); - - for (ChildIdentifier i = 0; i < numberOfChildren; ++i) - { - if (m_Children[i] == oldChild) - { - m_Children[i] = newChild; - return true; - } - } - return false; -} - -/** Return the child position given a node */ -template -OffsetValueType -TreeNode::ChildPosition(const Self * node) const -{ - const auto numberOfChildren = static_cast(m_Children.size()); - - for (ChildIdentifier i = 0; i < numberOfChildren; ++i) - { - if (m_Children[i] == node) - { - return i; - } - } - return -1; -} - -/** Return the child position given an element, the first child found. */ -template -auto -TreeNode::ChildPosition(TValue element) const -> ChildIdentifier -{ - const auto numberOfChildren = static_cast(m_Children.size()); - - for (ChildIdentifier i = 0; i < numberOfChildren; ++i) - { - if (m_Children[i]->Get() == element) - { - return i; - } - } - return -1; -} - -/** Add a child node */ -template -void -TreeNode::AddChild(Self * node) -{ - Pointer nodeKeepAlive = node; - - node->SetParent(this); - m_Children.push_back(node); -} - -/** Add a child at a specific position in the children list */ -template -void -TreeNode::AddChild(ChildIdentifier number, Self * node) -{ - const auto numberOfChildren = static_cast(m_Children.size()); - auto childId = static_cast(number); - - if (childId > numberOfChildren) - { - m_Children.resize(childId); - for (ChildIdentifier i = numberOfChildren; i <= childId; ++i) - { - m_Children[i] = nullptr; - } - m_Children[number] = node; - return; - } - - m_Children[number] = node; -} - -/** Get the number of children given a name and a depth */ -template -auto -TreeNode::GetNumberOfChildren(unsigned int depth, char * name) const -> ChildIdentifier -{ - auto it = m_Children.begin(); - auto itEnd = m_Children.end(); - - ChildIdentifier cnt = 0; - while (it != itEnd) - { - if (name == nullptr || strstr(typeid(**it).name(), name)) - { - ++cnt; - } - ++it; - } - - it = m_Children.begin(); - itEnd = m_Children.end(); - if (depth > 0) - { - while (it != itEnd) - { - cnt += (*it)->GetNumberOfChildren(depth - 1, name); - ++it; - } - } - - return cnt; -} - -/** Get children given a name and a depth */ -#if !defined(ITK_WRAPPING_PARSER) -template -auto -TreeNode::GetChildren(unsigned int depth, char * name) const -> ChildrenListType * -{ - auto * children = new ChildrenListType; - - auto childrenListIt = m_Children.begin(); - auto childrenListEnd = m_Children.end(); - - while (childrenListIt != childrenListEnd) - { - if (name == nullptr || strstr(typeid(**childrenListIt).name(), name)) - { - children->push_back(*childrenListIt); - } - if (depth > 0) - { - ChildrenListType * nextchildren = (**childrenListIt).GetChildren(depth - 1, name); - // Add the child to the current list - typename ChildrenListType::const_iterator nextIt = nextchildren->begin(); - while (nextIt != nextchildren->end()) - { - children->push_back(*nextIt); - ++nextIt; - } - delete nextchildren; - } - ++childrenListIt; - } - - return children; -} - -#endif -} // namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkVectorCastImageFilter.h b/Modules/Compatibility/Deprecated/include/itkVectorCastImageFilter.h deleted file mode 100644 index 2d17af244cd..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkVectorCastImageFilter.h +++ /dev/null @@ -1,119 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkVectorCastImageFilter_h -#define itkVectorCastImageFilter_h - -#include "itkUnaryFunctorImageFilter.h" -#include "itkNumericTraitsFixedArrayPixel.h" - -namespace itk -{ -/** - * \class VectorCastImageFilter - * - * \brief Casts input vector pixels to output vector pixel type. - * - * This filter is templated over the input image type and - * output image type. - * - * The filter expect both images to have the same number of dimensions, - * and that both the input and output have itk::Vector pixel types - * of the same VectorDimension. - * - * \sa Vector - * - * \ingroup IntensityImageFilters MultiThreaded - * \ingroup ITKDeprecated - */ -namespace Functor -{ -template -class VectorCast -{ -public: - bool - operator!=(const VectorCast &) const - { - return false; - } - - bool - operator==(const VectorCast & other) const - { - return !(*this != other); - } - - inline TOutput - operator()(const TInput & A) const - { - using OutputValueType = typename TOutput::ValueType; - - TOutput value; - for (unsigned int k = 0; k < TOutput::Dimension; ++k) - { - value[k] = static_cast(A[k]); - } - return value; - } -}; -} // namespace Functor - -template -class VectorCastImageFilter - : public UnaryFunctorImageFilter< - TInputImage, - TOutputImage, - Functor::VectorCast> -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(VectorCastImageFilter); - - /** Standard class type aliases. */ - using Self = VectorCastImageFilter; - using Superclass = - UnaryFunctorImageFilter>; - - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(VectorCastImageFilter); - -#ifdef ITK_USE_CONCEPT_CHECKING - // Begin concept checking - itkConceptMacro(InputHasNumericTraitsCheck, (Concept::HasNumericTraits)); - itkConceptMacro(OutputHasNumericTraitsCheck, - (Concept::HasNumericTraits)); - itkConceptMacro( - InputConvertibleToOutputCheck, - (Concept::Convertible)); - // End concept checking -#endif - -protected: - VectorCastImageFilter() = default; - ~VectorCastImageFilter() override = default; -}; -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkVectorCentralDifferenceImageFunction.h b/Modules/Compatibility/Deprecated/include/itkVectorCentralDifferenceImageFunction.h deleted file mode 100644 index 728c822de14..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkVectorCentralDifferenceImageFunction.h +++ /dev/null @@ -1,158 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkVectorCentralDifferenceImageFunction_h -#define itkVectorCentralDifferenceImageFunction_h - -#include "itkImageFunction.h" -#include "itkMatrix.h" - -namespace itk -{ - -/** - * \class VectorCentralDifferenceImageFunction - * \brief Calculate the derivative by central differencing. - * - * This class is templated over the input image type and - * the coordinate representation type (e.g. float or double). - * - * Possible improvements: - * - the use of Neighborhood operators may improve efficiency. - * - * \author Tom Vercauteren, INRIA & Mauna Kea Technologies - * - * This implementation was taken from the Insight Journal paper: - * https://www.insight-journal.org/browse/publication/154 - * - * \deprecated Please use CentralDifferenceImageFunction instead. - * - * \ingroup ImageFunctions - * \ingroup ITKDeprecated - */ -template -class ITK_TEMPLATE_EXPORT VectorCentralDifferenceImageFunction - : public ImageFunction, - TCoordRep> -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(VectorCentralDifferenceImageFunction); - - using InputPixelType = typename TInputImage::PixelType; - - /** Extract the vector dimension from the pixel template parameter. */ - static constexpr unsigned int Dimension = InputPixelType::Dimension; - - /** Dimension underlying input image. */ - static constexpr unsigned int ImageDimension = TInputImage::ImageDimension; - - /** Standard class type aliases. */ - using Self = VectorCentralDifferenceImageFunction; - using Superclass = ImageFunction, TCoordRep>; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(VectorCentralDifferenceImageFunction); - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** InputImageType type alias support */ - using InputImageType = TInputImage; - - /** OutputType typedef support. */ - using typename Superclass::OutputType; - - /** Index type alias support */ - using typename Superclass::IndexType; - - /** ContinuousIndex type alias support */ - using typename Superclass::ContinuousIndexType; - - /** Point type alias support */ - using typename Superclass::PointType; - - /** Evaluate the image derivative by central differencing at specified index. - * - * No bounds checking is done. - * The point is assume to lie within the image buffer. - * - * ImageFunction::IsInsideBuffer() can be used to check bounds before - * calling the method. */ - OutputType - EvaluateAtIndex(const IndexType & index) const override; - - /** Evaluate the image derivative by central differencing at non-integer - * positions. - * - * No bounds checking is done. - * The point is assumed to lie within the image buffer. - * - * ImageFunction::IsInsideBuffer() can be used to check bounds before - * calling the method. */ - OutputType - Evaluate(const PointType & point) const override - { - IndexType index; - - this->ConvertPointToNearestIndex(point, index); - return this->EvaluateAtIndex(index); - } - - OutputType - EvaluateAtContinuousIndex(const ContinuousIndexType & cindex) const override - { - IndexType index; - - this->ConvertContinuousIndexToNearestIndex(cindex, index); - return this->EvaluateAtIndex(index); - } - - /** The UseImageDirection flag determines whether image derivatives are - * computed with respect to the image grid or with respect to the physical - * space. When this flag is ON the derivatives are computed with respect to - * the coordinate system of physical space. The difference is whether we take - * into account the image Direction or not. The flag ON will take into - * account the image direction and will result in an extra matrix - * multiplication compared to the amount of computation performed when the - * flag is OFF. - * The default value of this flag is On. - */ - itkSetMacro(UseImageDirection, bool); - itkGetConstMacro(UseImageDirection, bool); - itkBooleanMacro(UseImageDirection); - -protected: - VectorCentralDifferenceImageFunction(); - ~VectorCentralDifferenceImageFunction() override = default; - void - PrintSelf(std::ostream & os, Indent indent) const override; - -private: - // flag to take or not the image direction into account - // when computing the derivatives. - bool m_UseImageDirection{ true }; -}; -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -# include "itkVectorCentralDifferenceImageFunction.hxx" -#endif - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkVectorCentralDifferenceImageFunction.hxx b/Modules/Compatibility/Deprecated/include/itkVectorCentralDifferenceImageFunction.hxx deleted file mode 100644 index 14ea29cce58..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkVectorCentralDifferenceImageFunction.hxx +++ /dev/null @@ -1,111 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkVectorCentralDifferenceImageFunction_hxx -#define itkVectorCentralDifferenceImageFunction_hxx - - -namespace itk -{ - -template -VectorCentralDifferenceImageFunction::VectorCentralDifferenceImageFunction() -{} - -template -void -VectorCentralDifferenceImageFunction::PrintSelf(std::ostream & os, Indent indent) const -{ - this->Superclass::PrintSelf(os, indent); - - os << indent << "UseImageDirection: " << m_UseImageDirection << std::endl; -} - -template -auto -VectorCentralDifferenceImageFunction::EvaluateAtIndex(const IndexType & index) const - -> OutputType -{ - OutputType derivative; - - derivative.Fill(0.0); - - IndexType neighIndex = index; - - const typename InputImageType::SizeType & size = this->GetInputImage()->GetBufferedRegion().GetSize(); - const typename InputImageType::IndexType & start = this->GetInputImage()->GetBufferedRegion().GetIndex(); - - for (unsigned int dim = 0; dim < TInputImage::ImageDimension; ++dim) - { - // bounds checking - if (index[dim] < start[dim] + 1 || index[dim] > (start[dim] + static_cast(size[dim]) - 2)) - { - for (unsigned int vdim = 0; vdim < Dimension; ++vdim) - { - derivative(vdim, dim) = 0.0; - } - continue; - } - - // compute derivative - const double deriv_weight = 0.5 / this->GetInputImage()->GetSpacing()[dim]; - - neighIndex[dim] += 1; - const InputPixelType & pixf = this->GetInputImage()->GetPixel(neighIndex); - for (unsigned int vdim = 0; vdim < Dimension; ++vdim) - { - derivative(vdim, dim) = pixf[vdim]; - } - - neighIndex[dim] -= 2; - const InputPixelType & pixb = this->GetInputImage()->GetPixel(neighIndex); - for (unsigned int vdim = 0; vdim < Dimension; ++vdim) - { - derivative(vdim, dim) -= pixb[vdim]; - derivative(vdim, dim) *= deriv_weight; - } - - neighIndex[dim] += 1; - } - - if (this->m_UseImageDirection) - { - OutputType orientedderivative; - const typename InputImageType::DirectionType & direction = this->GetInputImage()->GetDirection(); - for (unsigned int i = 0; i < TInputImage::ImageDimension; ++i) - { - std::vector sums(Dimension, 0.0); - for (unsigned int j = 0; j < TInputImage::ImageDimension; ++j) - { - for (unsigned int vdim = 0; vdim < Dimension; ++vdim) - { - sums[vdim] += direction[i][j] * derivative(vdim, j); - } - } - for (unsigned int vdim = 0; vdim < Dimension; ++vdim) - { - orientedderivative(vdim, i) = static_cast(sums[vdim]); - } - } - return orientedderivative; - } - - return (derivative); -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkVectorResampleImageFilter.h b/Modules/Compatibility/Deprecated/include/itkVectorResampleImageFilter.h deleted file mode 100644 index 688d5a45a64..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkVectorResampleImageFilter.h +++ /dev/null @@ -1,251 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkVectorResampleImageFilter_h -#define itkVectorResampleImageFilter_h - -#include "itkTransform.h" -#include "itkImageRegionIterator.h" -#include "itkImageToImageFilter.h" -#include "itkVectorInterpolateImageFunction.h" -#include "itkSize.h" - -namespace itk -{ -/** - * \class VectorResampleImageFilter - * \brief Resample an image via a coordinate transform - * - * VectorResampleImageFilter resamples an existing image through some coordinate - * transform, interpolating via some image function. The class is templated - * over the types of the input and output images. - * - * Note that the choice of interpolator function can be important. - * This function is set via SetInterpolator(). The default is - * itk::VectorLinearInterpolateImageFunction, which - * is reasonable for ordinary medical images. - * - * 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::GenerateInputRequestedRegion() and - * ProcessObject::GenerateOutputInformation(). - * - * This filter is implemented as a multithreaded filter. It provides a - * DynamicThreadedGenerateData() method for its implementation. - * - * \deprecated ResampleImageFilter can now resample vector images and should - * be used instead of the VectorResampleImageFilter. - * - * \ingroup GeometricTransform - * \ingroup ITKDeprecated - * - * \sphinx - * \sphinxexample{Compatibility/Deprecated/ResampleRGBImage,Resample RGB Image} - * \sphinxexample{Core/Transform/TranslateAVectorImage,Translate A Vector Image} - * \sphinxexample{Compatibility/Deprecated/ResampleITK::VectorImage,Resample A Vector Image} - * \endsphinx - */ -template -class ITK_TEMPLATE_EXPORT VectorResampleImageFilter : public ImageToImageFilter -{ -public: - ITK_DISALLOW_COPY_AND_MOVE(VectorResampleImageFilter); - - /** Standard class type aliases. */ - using Self = VectorResampleImageFilter; - using Superclass = ImageToImageFilter; - using Pointer = SmartPointer; - using ConstPointer = SmartPointer; - - using InputImageType = TInputImage; - using OutputImageType = TOutputImage; - using InputImagePointer = typename InputImageType::Pointer; - using InputImageConstPointer = typename InputImageType::ConstPointer; - using OutputImagePointer = typename OutputImageType::Pointer; - using InputImageRegionType = typename InputImageType::RegionType; - - /** Method for creation through the object factory. */ - itkNewMacro(Self); - - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(VectorResampleImageFilter); - - /** Number of dimensions. */ - static constexpr unsigned int ImageDimension = TOutputImage::ImageDimension; - - /** Transform type alias. - * - * \todo Check that input and output images have the same number of - * dimensions; this is required by the current implementation of - * AffineTransform. */ - using TransformType = Transform; - using TransformPointerType = typename TransformType::ConstPointer; - - /** Interpolator type alias. */ - using InterpolatorType = VectorInterpolateImageFunction; - using InterpolatorPointerType = typename InterpolatorType::Pointer; - - /** Image size type alias. */ - using SizeType = Size; - - /** Image index type alias. */ - using IndexType = typename TOutputImage::IndexType; - - /** Image point type alias. */ - using PointType = typename InterpolatorType::PointType; - - /** Image pixel value type alias. */ - using PixelType = typename TOutputImage::PixelType; - using PixelComponentType = typename PixelType::ValueType; - - /** Typedef to describe the output image region type. */ - using OutputImageRegionType = typename TOutputImage::RegionType; - - /** Image spacing, origin and direction type alias. */ - using SpacingType = typename TOutputImage::SpacingType; - using OriginPointType = typename TOutputImage::PointType; - using DirectionType = typename TOutputImage::DirectionType; - - /** Set/Get the coordinate transformation. - * Set the coordinate transform to use for resampling. Note that this - * must be in index coordinates and is the output-to-input transform, - * NOT the input-to-output transform that you might naively expect. - * The default is itk::AffineTransform. */ - itkSetConstObjectMacro(Transform, TransformType); - itkGetConstObjectMacro(Transform, TransformType); - - /** Set the interpolator function. The default is - * itk::VectorLinearInterpolateImageFunction. */ - itkSetObjectMacro(Interpolator, InterpolatorType); - - /** Get a pointer to the interpolator function. */ - itkGetModifiableObjectMacro(Interpolator, InterpolatorType); - - /** Set the size of the output image. */ - itkSetMacro(Size, SizeType); - - /** Get the size of the output image. */ - itkGetConstReferenceMacro(Size, SizeType); - - /** Set the pixel value when a transformed pixel is outside of the - * image. The default default pixel value is 0. */ - itkSetMacro(DefaultPixelValue, PixelType); - - /** Get the pixel value when a transformed pixel is outside of the image */ - itkGetConstMacro(DefaultPixelValue, PixelType); - - /** Set the output image spacing. */ - itkSetMacro(OutputSpacing, SpacingType); - virtual void - SetOutputSpacing(const double * values); - - /** Get the output image spacing. */ - itkGetConstReferenceMacro(OutputSpacing, SpacingType); - - /** Set the output image origin. */ - itkSetMacro(OutputOrigin, OriginPointType); - virtual void - SetOutputOrigin(const double * values); - - /** Get the output image origin. */ - itkGetConstReferenceMacro(OutputOrigin, OriginPointType); - - /** Set/Get the output direction cosine matrix. */ - itkSetMacro(OutputDirection, DirectionType); - itkGetConstReferenceMacro(OutputDirection, DirectionType); - - /** Set the start index of the output largest possible region. - * The default is an index of all zeros. */ - itkSetMacro(OutputStartIndex, IndexType); - - /** Get the start index of the output largest possible region. */ - itkGetConstReferenceMacro(OutputStartIndex, IndexType); - - /** VectorResampleImageFilter produces an image which is a different size - * than its input. As such, it needs to provide an implementation - * for GenerateOutputInformation() in order to inform the pipeline - * execution model. The original documentation of this method is - * below. \sa ProcessObject::GenerateOutputInformaton() */ - void - GenerateOutputInformation() override; - - /** VectorResampleImageFilter needs a different input requested region than - * the output requested region. As such, VectorResampleImageFilter needs - * to provide an implementation for GenerateInputRequestedRegion() - * in order to inform the pipeline execution model. - * \sa ProcessObject::GenerateInputRequestedRegion() */ - void - GenerateInputRequestedRegion() override; - - /** Set the state of the filter before multi-threading. - * Note that InterpolatorType::SetInputImage is not thread-safe and hence - * has to be set up before DynamicThreadedGenerateData. */ - void - BeforeThreadedGenerateData() override; - - /** Set the state of the filter after multi-threading. */ - void - AfterThreadedGenerateData() override; - - /** Compute the Modified Time based on changed to the components. */ - ModifiedTimeType - GetMTime() const override; - -#ifdef ITK_USE_CONCEPT_CHECKING - // Begin concept checking - itkConceptMacro(InputHasNumericTraitsCheck, (Concept::HasNumericTraits)); - itkConceptMacro(OutputHasNumericTraitsCheck, (Concept::HasNumericTraits)); - // End concept checking -#endif - -protected: - VectorResampleImageFilter(); - ~VectorResampleImageFilter() override = default; - void - PrintSelf(std::ostream & os, Indent indent) const override; - - /** VectorResampleImageFilter can be implemented as a multithreaded filter. Therefore, - * this implementation provides a DynamicThreadedGenerateData() routine which - * is called for each processing thread. The output image data is allocated - * automatically by the superclass prior to calling DynamicThreadedGenerateData(). - * DynamicThreadedGenerateData can only write to the portion of the output image - * specified by the parameter "outputRegionForThread" - * \sa ImageToImageFilter::ThreadedGenerateData(), - * ImageToImageFilter::GenerateData() */ - void - DynamicThreadedGenerateData(const OutputImageRegionType & outputRegionForThread) override; - - -private: - SizeType m_Size{}; - TransformPointerType m_Transform{}; - InterpolatorPointerType m_Interpolator{}; - PixelType m_DefaultPixelValue{}; - SpacingType m_OutputSpacing{}; - OriginPointType m_OutputOrigin{}; - DirectionType m_OutputDirection{}; - IndexType m_OutputStartIndex{}; -}; -} // end namespace itk - -#ifndef ITK_MANUAL_INSTANTIATION -# include "itkVectorResampleImageFilter.hxx" -#endif - -#endif diff --git a/Modules/Compatibility/Deprecated/include/itkVectorResampleImageFilter.hxx b/Modules/Compatibility/Deprecated/include/itkVectorResampleImageFilter.hxx deleted file mode 100644 index edc4f4ce5cf..00000000000 --- a/Modules/Compatibility/Deprecated/include/itkVectorResampleImageFilter.hxx +++ /dev/null @@ -1,250 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 itkVectorResampleImageFilter_hxx -#define itkVectorResampleImageFilter_hxx - -#include "itkIdentityTransform.h" -#include "itkVectorLinearInterpolateImageFunction.h" -#include "itkTotalProgressReporter.h" -#include "itkImageRegionIteratorWithIndex.h" -#include // For max. - -namespace itk -{ - -template -VectorResampleImageFilter::VectorResampleImageFilter() - : m_OutputSpacing(1.0) - , m_OutputOrigin(0.0) -{ - m_Size.Fill(0); - m_OutputStartIndex.Fill(0); - - m_OutputDirection.SetIdentity(); - - m_Transform = IdentityTransform::New(); - m_Interpolator = VectorLinearInterpolateImageFunction::New(); - - m_DefaultPixelValue = NumericTraits::ZeroValue(m_DefaultPixelValue); - this->DynamicMultiThreadingOn(); - this->ThreaderUpdateProgressOff(); -} - -template -void -VectorResampleImageFilter::SetOutputSpacing( - const double * spacing) -{ - SpacingType s; - for (unsigned int i = 0; i < TInputImage::ImageDimension; ++i) - { - s[i] = static_cast(spacing[i]); - } - this->SetOutputSpacing(s); -} - -template -void -VectorResampleImageFilter::SetOutputOrigin(const double * origin) -{ - OriginPointType p(origin); - - this->SetOutputOrigin(p); -} - -template -void -VectorResampleImageFilter::BeforeThreadedGenerateData() -{ - if (!m_Interpolator) - { - itkExceptionMacro("Interpolator not set"); - } - - // Connect input image to interpolator - m_Interpolator->SetInputImage(this->GetInput()); - - if (m_DefaultPixelValue.Size() == 0) - { - NumericTraits::SetLength(m_DefaultPixelValue, this->GetInput()->GetNumberOfComponentsPerPixel()); - m_DefaultPixelValue.Fill(0); - } -} - -template -void -VectorResampleImageFilter::AfterThreadedGenerateData() -{ - // Disconnect input image from the interpolator - m_Interpolator->SetInputImage(nullptr); -} - -template -void -VectorResampleImageFilter::DynamicThreadedGenerateData( - const OutputImageRegionType & outputRegionForThread) -{ - OutputImagePointer outputPtr = this->GetOutput(); - InputImageConstPointer inputPtr = this->GetInput(); - - TotalProgressReporter progress(this, outputPtr->GetRequestedRegion().GetNumberOfPixels()); - - // Create an iterator that will walk the output region for this thread. - using OutputIterator = ImageRegionIteratorWithIndex; - - OutputIterator outIt(outputPtr, outputRegionForThread); - - // 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 inputPoint; // Coordinates of current input pixel - - using ContinuousIndexType = ContinuousIndex; - - // Doc says this only works for VectorImage, but Image implementation says otherwise... - const unsigned int numberOfComponents = this->GetInput()->GetNumberOfComponentsPerPixel(); - - using OutputType = typename InterpolatorType::OutputType; - - // Walk the output region - outIt.GoToBegin(); - - while (!outIt.IsAtEnd()) - { - // Determine the index of the current output pixel - outputPtr->TransformIndexToPhysicalPoint(outIt.GetIndex(), outputPoint); - - // Compute corresponding input pixel position - inputPoint = m_Transform->TransformPoint(outputPoint); - const ContinuousIndexType inputIndex = - inputPtr->template TransformPhysicalPointToContinuousIndex(inputPoint); - - // Evaluate input at right position and copy to the output - if (m_Interpolator->IsInsideBuffer(inputIndex)) - { - PixelType pixval; - NumericTraits::SetLength(pixval, numberOfComponents); - - const OutputType value = m_Interpolator->EvaluateAtContinuousIndex(inputIndex); - for (unsigned int i = 0; i < numberOfComponents; ++i) - { - pixval[i] = static_cast(value[i]); - } - - outIt.Set(pixval); - } - else - { - outIt.Set(m_DefaultPixelValue); // default background value - } - - ++outIt; - progress.CompletedPixel(); - } -} - -template -void -VectorResampleImageFilter::GenerateInputRequestedRegion() -{ - // Call the superclass's implementation of this method - Superclass::GenerateInputRequestedRegion(); - - if (!this->GetInput()) - { - return; - } - - // Get the pointer to the input image - InputImagePointer inputPtr = const_cast(this->GetInput()); - - // Determining the actual input region is non-trivial, especially - // when we cannot assume anything about the transform being used. - // So we do the easy thing and request the entire input image. - // - InputImageRegionType inputRegion; - inputRegion = inputPtr->GetLargestPossibleRegion(); - inputPtr->SetRequestedRegion(inputRegion); -} - -template -void -VectorResampleImageFilter::GenerateOutputInformation() -{ - // Call the superclass' implementation of this method - Superclass::GenerateOutputInformation(); - - // Get the pointer to the output image - OutputImagePointer outputPtr = this->GetOutput(); - if (!outputPtr) - { - return; - } - - // Set the size of the output region - typename TOutputImage::RegionType outputLargestPossibleRegion; - outputLargestPossibleRegion.SetSize(m_Size); - outputLargestPossibleRegion.SetIndex(m_OutputStartIndex); - outputPtr->SetLargestPossibleRegion(outputLargestPossibleRegion); - - // Set spacing and origin - outputPtr->SetSpacing(m_OutputSpacing); - outputPtr->SetOrigin(m_OutputOrigin); - outputPtr->SetDirection(m_OutputDirection); -} - -template -ModifiedTimeType -VectorResampleImageFilter::GetMTime() const -{ - ModifiedTimeType latestTime = Object::GetMTime(); - - if (m_Transform) - { - latestTime = std::max(latestTime, m_Transform->GetMTime()); - } - - if (m_Interpolator) - { - latestTime = std::max(latestTime, m_Interpolator->GetMTime()); - } - - return latestTime; -} - -template -void -VectorResampleImageFilter::PrintSelf(std::ostream & os, - Indent indent) const -{ - Superclass::PrintSelf(os, indent); - - os << indent - << "DefaultPixelValue: " << static_cast::PrintType>(m_DefaultPixelValue) - << std::endl; - os << indent << "Size: " << m_Size << std::endl; - os << indent << "OutputStartIndex: " << m_OutputStartIndex << std::endl; - 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 << "Interpolator: " << m_Interpolator.GetPointer() << std::endl; -} -} // end namespace itk - -#endif diff --git a/Modules/Compatibility/Deprecated/itk-module.cmake b/Modules/Compatibility/Deprecated/itk-module.cmake index a04eee547b3..c4384784485 100644 --- a/Modules/Compatibility/Deprecated/itk-module.cmake +++ b/Modules/Compatibility/Deprecated/itk-module.cmake @@ -2,9 +2,6 @@ set(DOCUMENTATION "This is a collection of classes that are intended to be removed from the toolkit.") set(ITKDeprecatedOnByDefault EXCLUDE_FROM_DEFAULT) -if(ITKV4_COMPATIBILITY) - set(ITKDeprecatedOnByDefault "") -endif() itk_module( ITKDeprecated diff --git a/Modules/Compatibility/Deprecated/src/CMakeLists.txt b/Modules/Compatibility/Deprecated/src/CMakeLists.txt index 6c58174f062..349f4cc6c39 100644 --- a/Modules/Compatibility/Deprecated/src/CMakeLists.txt +++ b/Modules/Compatibility/Deprecated/src/CMakeLists.txt @@ -1,8 +1,4 @@ set(ITKDeprecated_SRCS - itkBarrier.cxx - itkConditionVariable.cxx - itkFastMutexLock.cxx - itkMutexLock.cxx - itkSimpleFastMutexLock.cxx) - + itkDeprecatedPlaceholder.cxx + ) itk_module_add_library(ITKDeprecated ${ITKDeprecated_SRCS}) diff --git a/Modules/Compatibility/Deprecated/src/itkConditionVariableWinThreads.cxx b/Modules/Compatibility/Deprecated/src/itkConditionVariableWinThreads.cxx deleted file mode 100644 index 5b8d44cbb3a..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkConditionVariableWinThreads.cxx +++ /dev/null @@ -1,134 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 "itkConditionVariable.h" - -namespace itk -{ -ConditionVariable::ConditionVariable() -{ - m_ConditionVariable.m_NumberOfWaiters = 0; - m_ConditionVariable.m_WasBroadcast = 0; - m_ConditionVariable.m_Semaphore = CreateSemaphore(nullptr, // no security - 0, // initial value - 0x7fffffff, // max count - nullptr); // unnamed - InitializeCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - m_ConditionVariable.m_WaitersAreDone = CreateEvent(nullptr, // no security - FALSE, // auto-reset - FALSE, // non-signaled initially - nullptr); // unnamed -} - -ConditionVariable::~ConditionVariable() -{ - CloseHandle(m_ConditionVariable.m_Semaphore); - CloseHandle(m_ConditionVariable.m_WaitersAreDone); - DeleteCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); -} - -void -ConditionVariable::Signal() -{ - EnterCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - bool haveWaiters = (m_ConditionVariable.m_NumberOfWaiters > 0); - LeaveCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - - // if there were not any waiters, then this is a no-op - if (haveWaiters) - { - ReleaseSemaphore(m_ConditionVariable.m_Semaphore, 1, 0); - } -} - -void -ConditionVariable::Broadcast() -{ - // This is needed to ensure that m_NumberOfWaiters and m_WasBroadcast are - // consistent - EnterCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - bool haveWaiters = false; - - if (m_ConditionVariable.m_NumberOfWaiters > 0) - { - // We are broadcasting, even if there is just one waiter... - // Record that we are broadcasting, which helps optimize Wait() - // for the non-broadcast case - m_ConditionVariable.m_WasBroadcast = 1; - haveWaiters = true; - } - - if (haveWaiters) - { - // Wake up all waiters atomically - ReleaseSemaphore(m_ConditionVariable.m_Semaphore, m_ConditionVariable.m_NumberOfWaiters, 0); - - LeaveCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - - // Wait for all the awakened threads to acquire the counting - // semaphore - WaitForSingleObject(m_ConditionVariable.m_WaitersAreDone, INFINITE); - // This assignment is ok, even without the m_NumberOfWaitersLock held - // because no other waiter threads can wake up to access it. - m_ConditionVariable.m_WasBroadcast = 0; - } - else - { - LeaveCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - } -} - -void -ConditionVariable::Wait(SimpleMutexLock * mutex) -{ - // Avoid race conditions - EnterCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - m_ConditionVariable.m_NumberOfWaiters++; - LeaveCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - - // This call atomically releases the mutex and waits on the - // semaphore until signaled - SignalObjectAndWait(mutex->GetMutexLock(), m_ConditionVariable.m_Semaphore, INFINITE, FALSE); - - // Reacquire lock to avoid race conditions - EnterCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - - // We're no longer waiting.... - m_ConditionVariable.m_NumberOfWaiters--; - - // Check to see if we're the last waiter after the broadcast - int lastWaiter = m_ConditionVariable.m_WasBroadcast && m_ConditionVariable.m_NumberOfWaiters == 0; - - LeaveCriticalSection(&m_ConditionVariable.m_NumberOfWaitersLock); - - // If we're the last waiter thread during this particular broadcast - // then let the other threads proceed - if (lastWaiter) - { - // This call atomically signals the m_WaitersAreDone event and waits - // until it can acquire the external mutex. This is required to - // ensure fairness - SignalObjectAndWait(m_ConditionVariable.m_WaitersAreDone, mutex->GetMutexLock(), INFINITE, FALSE); - } - else - { - // Always regain the external mutex since that's the guarantee we - // give to our callers - WaitForSingleObject(mutex->GetMutexLock(), INFINITE); - } -} -} // end of namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkConditionVariableNoThreads.cxx b/Modules/Compatibility/Deprecated/src/itkDeprecatedPlaceholder.cxx similarity index 72% rename from Modules/Compatibility/Deprecated/src/itkConditionVariableNoThreads.cxx rename to Modules/Compatibility/Deprecated/src/itkDeprecatedPlaceholder.cxx index 47b38546337..a5495d910de 100644 --- a/Modules/Compatibility/Deprecated/src/itkConditionVariableNoThreads.cxx +++ b/Modules/Compatibility/Deprecated/src/itkDeprecatedPlaceholder.cxx @@ -15,23 +15,14 @@ * limitations under the License. * *=========================================================================*/ -#include "itkConditionVariable.h" +#include +#include -namespace itk +// This small placeholder is needed to retain the +// infrastructure for future deprecated code +// in ITKv6 +std::string +dummy_deprecated_function_placeholder() { -ConditionVariable::ConditionVariable() {} - -ConditionVariable::~ConditionVariable() {} - -void -ConditionVariable::Signal() -{} - -void -ConditionVariable::Broadcast() -{} - -void -ConditionVariable::Wait(SimpleMutexLock *) -{} -} // end of namespace itk + return std::string(ITK_VERSION_STRING); +} diff --git a/Modules/Compatibility/Deprecated/src/itkMutexLock.cxx b/Modules/Compatibility/Deprecated/src/itkMutexLock.cxx deleted file mode 100644 index f219a2fe253..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkMutexLock.cxx +++ /dev/null @@ -1,52 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#include "itkMutexLock.h" - -#if defined(ITK_USE_PTHREADS) -# include "itkMutexLockPThreads.cxx" -#elif defined(ITK_USE_WIN32_THREADS) -# include "itkMutexLockWinThreads.cxx" -#else -# include "itkMutexLockNoThreads.cxx" -#endif - -namespace itk -{ -// New for the SimpleMutex -SimpleMutexLock * -SimpleMutexLock::New() -{ - return new SimpleMutexLock; -} - -void -MutexLock::PrintSelf(std::ostream & os, Indent indent) const -{ - Superclass::PrintSelf(os, indent); -} -} // end namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkMutexLockNoThreads.cxx b/Modules/Compatibility/Deprecated/src/itkMutexLockNoThreads.cxx deleted file mode 100644 index d927d199d4a..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkMutexLockNoThreads.cxx +++ /dev/null @@ -1,56 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#include "itkMutexLock.h" - -namespace itk -{ - -// Construct a new MutexLock -SimpleMutexLock::SimpleMutexLock() {} - -// Destruct the MutexVariable -SimpleMutexLock::~SimpleMutexLock() {} - -// Lock the MutexLock -void -SimpleMutexLock::Lock() -{} - -// Lock the MutexLock -bool -SimpleMutexLock::TryLock() -{ - return true; -} - -// Unlock the MutexLock -void -SimpleMutexLock::Unlock() -{} - -} // end namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkMutexLockPThreads.cxx b/Modules/Compatibility/Deprecated/src/itkMutexLockPThreads.cxx deleted file mode 100644 index c82acf7b2e0..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkMutexLockPThreads.cxx +++ /dev/null @@ -1,71 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#include "itkMutexLock.h" - -namespace itk -{ -// Construct a new MutexLock -SimpleMutexLock::SimpleMutexLock() -{ - pthread_mutex_init(&m_MutexLock, nullptr); -} - -// Destruct the MutexVariable -SimpleMutexLock::~SimpleMutexLock() -{ - pthread_mutex_destroy(&m_MutexLock); -} - -// Lock the MutexLock -void -SimpleMutexLock::Lock() -{ - pthread_mutex_lock(&m_MutexLock); -} -// -// Lock the MutexLock -bool -SimpleMutexLock::TryLock() -{ - const bool lockCaptured = (pthread_mutex_trylock(&m_MutexLock) == 0); - /* - * non-blocking lock of mutex - * - if mutex is not already locked, you will obtain the lock & own the mutex, and return 0 immediately - * - if mutex is already locked, pthread_mutex_trylock() will return immediately wth return value EBUSY - */ - return lockCaptured; -} - -// Unlock the MutexLock -void -SimpleMutexLock::Unlock() -{ - pthread_mutex_unlock(&m_MutexLock); -} - -} // end namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkMutexLockWinThreads.cxx b/Modules/Compatibility/Deprecated/src/itkMutexLockWinThreads.cxx deleted file mode 100644 index eda0ad98c4a..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkMutexLockWinThreads.cxx +++ /dev/null @@ -1,72 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#include "itkMutexLock.h" - -namespace itk -{ - -// Construct a new MutexLock -SimpleMutexLock::SimpleMutexLock() -{ - m_MutexLock = CreateMutex(nullptr, FALSE, nullptr); -} - -// Destruct the MutexVariable -SimpleMutexLock::~SimpleMutexLock() -{ - CloseHandle(m_MutexLock); -} - -// Lock the MutexLock -void -SimpleMutexLock::Lock() -{ - WaitForSingleObject(m_MutexLock, INFINITE); -} - -// Lock the MutexLock -bool -SimpleMutexLock::TryLock() -{ - const bool lockCaptured = (WaitForSingleObject(m_MutexLock, 1) == WAIT_OBJECT_0); - /* - * non-blocking lock of mutex - * - if mutex is not already locked, you will obtain the lock & own the mutex, and return 0 immediately - * - if mutex is already locked, pthread_mutex_trylock() will return immediately wth return value EBUSY - */ - return lockCaptured; -} - -// Unlock the MutexLock -void -SimpleMutexLock::Unlock() -{ - ReleaseMutex(m_MutexLock); -} - -} // end namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLock.cxx b/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLock.cxx deleted file mode 100644 index 20a124fde9d..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLock.cxx +++ /dev/null @@ -1,36 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#include "itkSimpleFastMutexLock.h" - -#if defined(ITK_USE_PTHREADS) -# include "itkSimpleFastMutexLockPThreads.cxx" -#elif defined(ITK_USE_WIN32_THREADS) -# include "itkSimpleFastMutexLockWinThreads.cxx" -#else -# include "itkSimpleFastMutexLockNoThreads.cxx" -#endif diff --git a/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockNoThreads.cxx b/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockNoThreads.cxx deleted file mode 100644 index 9738a0e3b0d..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockNoThreads.cxx +++ /dev/null @@ -1,54 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#include "itkSimpleFastMutexLock.h" - -namespace itk -{ -// Construct a new SimpleMutexLock -SimpleFastMutexLock::SimpleFastMutexLock() {} - -// Destruct the SimpleMutexVariable -SimpleFastMutexLock::~SimpleFastMutexLock() {} - -// Lock the FastMutexLock -void -SimpleFastMutexLock::Lock() const -{} - -// Non-blocking TryLock the FastMutexLock -bool -SimpleFastMutexLock::TryLock() const -{ - return true; -} - -// Unlock the FastMutexLock -void -SimpleFastMutexLock::Unlock() const -{} -} // end namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockPThreads.cxx b/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockPThreads.cxx deleted file mode 100644 index 63ab4144334..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockPThreads.cxx +++ /dev/null @@ -1,73 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#include "itkSimpleFastMutexLock.h" - -namespace itk -{ -// Construct a new SimpleMutexLock -SimpleFastMutexLock::SimpleFastMutexLock() -{ - pthread_mutexattr_t mta; - pthread_mutexattr_init(&mta); - pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&(m_FastMutexLock), &mta); -} - -// Destruct the SimpleMutexVariable -SimpleFastMutexLock::~SimpleFastMutexLock() -{ - pthread_mutex_destroy(&m_FastMutexLock); -} - -// Lock the FastMutexLock -void -SimpleFastMutexLock::Lock() const -{ - pthread_mutex_lock(&m_FastMutexLock); -} - -// Non-blocking TryLock the FastMutexLock -bool -SimpleFastMutexLock::TryLock() const -{ - const bool lockCaptured = (pthread_mutex_trylock(&m_FastMutexLock) == 0); - /* - * non-blocking lock of mutex - * - if mutex is not already locked, you will obtain the lock & own the mutex, and return 0 immediately - * - if mutex is already locked, pthread_mutex_trylock() will return immediately wth return value EBUSY - */ - return lockCaptured; -} - -// Unlock the FastMutexLock -void -SimpleFastMutexLock::Unlock() const -{ - pthread_mutex_unlock(&m_FastMutexLock); -} -} // end namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockWinThreads.cxx b/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockWinThreads.cxx deleted file mode 100644 index bc0031ba377..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkSimpleFastMutexLockWinThreads.cxx +++ /dev/null @@ -1,71 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - * - * Portions of this file are subject to the VTK Toolkit Version 3 copyright. - * - * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - * - * For complete copyright, license and disclaimer of warranty information - * please refer to the NOTICE file at the top of the ITK source tree. - * - *=========================================================================*/ -#include "itkSimpleFastMutexLock.h" - -namespace itk -{ -// Construct a new SimpleMutexLock -SimpleFastMutexLock::SimpleFastMutexLock() -{ - // this->MutexLock = CreateMutex( nullptr, FALSE, nullptr ); - InitializeCriticalSection(&m_FastMutexLock); -} - -// Destruct the SimpleMutexVariable -SimpleFastMutexLock::~SimpleFastMutexLock() -{ - DeleteCriticalSection(&m_FastMutexLock); -} - -// Lock the FastMutexLock -void -SimpleFastMutexLock::Lock() const -{ - EnterCriticalSection(&m_FastMutexLock); -} - -// Non-blocking TryLock the FastMutexLock -bool -SimpleFastMutexLock::TryLock() const -{ - const bool lockCaptured = TryEnterCriticalSection(&m_FastMutexLock); - /* - * non-blocking lock of mutex - * - if mutex is not already locked, you will obtain the lock & own the mutex, and return non-zero immediately - * - if mutex is already locked, TryEnterCriticalSection() will return immediately wth return value 0 - */ - return lockCaptured; -} - -// Unlock the FastMutexLock -void -SimpleFastMutexLock::Unlock() const -{ - LeaveCriticalSection(&m_FastMutexLock); -} -} // end namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkTreeIteratorBase.cxx b/Modules/Compatibility/Deprecated/src/itkTreeIteratorBase.cxx deleted file mode 100644 index 71cd66aec34..00000000000 --- a/Modules/Compatibility/Deprecated/src/itkTreeIteratorBase.cxx +++ /dev/null @@ -1,50 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 "itkTreeIteratorBase.h" - -namespace itk -{ -/** Print enum values */ -std::ostream & -operator<<(std::ostream & out, const TreeIteratorBaseEnums::TreeIteratorBaseNode value) -{ - return out << [value] { - switch (value) - { - case TreeIteratorBaseEnums::TreeIteratorBaseNode::UNDEFIND: - return "itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::UNDEFIND"; - case TreeIteratorBaseEnums::TreeIteratorBaseNode::PREORDER: - return "itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::PREORDER"; - case TreeIteratorBaseEnums::TreeIteratorBaseNode::INORDER: - return "itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::INORDER"; - case TreeIteratorBaseEnums::TreeIteratorBaseNode::POSTORDER: - return "itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::POSTORDER"; - case TreeIteratorBaseEnums::TreeIteratorBaseNode::LEVELORDER: - return "itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::LEVELORDER"; - case TreeIteratorBaseEnums::TreeIteratorBaseNode::CHILD: - return "itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::CHILD"; - case TreeIteratorBaseEnums::TreeIteratorBaseNode::ROOT: - return "itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::ROOT"; - case TreeIteratorBaseEnums::TreeIteratorBaseNode::LEAF: - return "itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::LEAF"; - default: - return "INVALID VALUE FOR itk::TreeIteratorBaseEnums::TreeIteratorBaseNode"; - } - }(); -} -} // end namespace itk diff --git a/Modules/Compatibility/Deprecated/test/CMakeLists.txt b/Modules/Compatibility/Deprecated/test/CMakeLists.txt index 955cc632658..63a371a36c1 100644 --- a/Modules/Compatibility/Deprecated/test/CMakeLists.txt +++ b/Modules/Compatibility/Deprecated/test/CMakeLists.txt @@ -1,98 +1,9 @@ -itk_module_test() -set(ITKDeprecatedTests - itkAtomicIntTest.cxx - itkBarrierTest.cxx - itkConditionVariableTest.cxx - itkSimpleFastMutexLockTest.cxx - itkVectorCentralDifferenceImageFunctionTest.cxx - itkVectorResampleImageFilterTest.cxx - itkTreeContainerTest.cxx - itkTreeContainerTest2.cxx) +#Placeholder for future deprecated tests +#itk_module_test() +#set(ITKDeprecatedTests +# ) -if(NOT ITK_LEGACY_REMOVE) - list(APPEND ITKDeprecatedTests itkSpawnThreadTest.cxx) -endif() +#createtestdriver(ITKDeprecated "${ITKDeprecated-Test_LIBRARIES}" "${ITKDeprecatedTests}") -createtestdriver(ITKDeprecated "${ITKDeprecated-Test_LIBRARIES}" "${ITKDeprecatedTests}") - -set(BASELINE "${ITK_DATA_ROOT}/Baseline/Common") -set(TEMP ${ITK_TEST_OUTPUT_DIR}) - -itk_add_test( - NAME - itkAtomicIntTest - COMMAND - ITKDeprecatedTestDriver - itkAtomicIntTest) - -if(NOT MINGW) - itk_add_test( - NAME - itkBarrierTest - COMMAND - ITKDeprecatedTestDriver - itkBarrierTest) - itk_add_test( - NAME - itkBarrierTest107 - COMMAND - ITKDeprecatedTestDriver - itkBarrierTest - 107) - itk_add_test( - NAME - itkConditionVariableTest - COMMAND - ITKDeprecatedTestDriver - itkConditionVariableTest) -endif() - -itk_add_test( - NAME - itkSimpleFastMutexLockTest - COMMAND - ITKDeprecatedTestDriver - itkSimpleFastMutexLockTest) -# short timeout because failing test will hang and test is quite small -set_tests_properties(itkSimpleFastMutexLockTest PROPERTIES TIMEOUT 60) - -if(NOT ITK_LEGACY_REMOVE) - itk_add_test( - NAME - itkSpawnThreadTest - COMMAND - ITKDeprecatedTestDriver - itkSpawnThreadTest - 100) -endif() - -itk_add_test( - NAME - itkVectorCentralDifferenceImageFunctionTest - COMMAND - ITKDeprecatedTestDriver - itkVectorCentralDifferenceImageFunctionTest) - -itk_add_test( - NAME - itkVectorResampleImageFilterTest - COMMAND - ITKDeprecatedTestDriver - --compare - DATA{${ITK_DATA_ROOT}/Baseline/BasicFilters/VectorResampleImageFilterTest.png} - ${ITK_TEST_OUTPUT_DIR}/VectorResampleImageFilterTest.png - itkVectorResampleImageFilterTest - ${ITK_TEST_OUTPUT_DIR}/VectorResampleImageFilterTest.png) - -itk_add_test( - NAME - itkTreeContainerTest - COMMAND - ITKDeprecatedTestDriver - itkTreeContainerTest) -itk_add_test( - NAME - itkTreeContainerTest2 - COMMAND - ITKDeprecatedTestDriver - itkTreeContainerTest2) +#set(BASELINE "${ITK_DATA_ROOT}/Baseline/Common") +#set(TEMP ${ITK_TEST_OUTPUT_DIR}) diff --git a/Modules/Compatibility/Deprecated/test/itkAtomicIntTest.cxx b/Modules/Compatibility/Deprecated/test/itkAtomicIntTest.cxx deleted file mode 100644 index 88f67e6d6a3..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkAtomicIntTest.cxx +++ /dev/null @@ -1,335 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ -/*========================================================================= - - Program: Visualization Toolkit - Module: TestAtomic.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or https://www.kitware.com/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 notice for more information. - -=========================================================================*/ -#include "itkAtomicInt.h" -#include "itkMultiThreaderBase.h" -#include "itkObject.h" -#include - -namespace -{ - -int Total = 0; -itk::uint64_t Total64 = 0; -itk::AtomicInt TotalAtomic(0); -itk::AtomicInt TotalAtomic64(0); -constexpr unsigned int Target = 1000000; -itk::int32_t Values32[Target + 2]; -itk::int64_t Values64[Target + 2]; -itk::AtomicInt AtomicPtr(Values32); -itk::AtomicInt Atomic64Ptr(Values64); - -int NumThreads = 5; - -itk::Object::Pointer AnObject; -} // namespace - - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -MyFunction(void *) -{ - for (unsigned int i = 0; i < Target / NumThreads; ++i) - { - Total++; - int idx = ++TotalAtomic; - Values32[idx] = 1; - - Total64++; - idx = ++TotalAtomic64; - Values64[idx] = 1; - - AnObject->Modified(); - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -MyFunction2(void *) -{ - for (unsigned int i = 0; i < Target / NumThreads; ++i) - { - --TotalAtomic; - - --TotalAtomic64; - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -MyFunction3(void *) -{ - for (unsigned int i = 0; i < Target / NumThreads; ++i) - { - int idx = TotalAtomic += 1; - Values32[idx]++; - - idx = TotalAtomic64 += 1; - Values64[idx]++; - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -MyFunction4(void *) -{ - for (unsigned int i = 0; i < Target / NumThreads; ++i) - { - TotalAtomic++; - TotalAtomic += 1; - TotalAtomic--; - TotalAtomic -= 1; - - TotalAtomic64++; - TotalAtomic64 += 1; - TotalAtomic64--; - TotalAtomic64 -= 1; - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -MyFunctionPtr(void *) -{ - for (unsigned int i = 0; i < Target / NumThreads; ++i) - { - itk::int32_t * ptr32 = ++AtomicPtr; - (*ptr32) = 1; - - itk::int64_t * ptr64 = ++Atomic64Ptr; - (*ptr64) = 1; - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -template -int -TestAtomicOperators(std::string name) -{ - itk::AtomicInt testAtomic(1); - if (testAtomic != 1) - { - std::cout << "Expecting testAtomic" << name << " value to be 1. Got " << testAtomic << std::endl; - return 1; - } - testAtomic = 2; - if (testAtomic != 2) - { - std::cout << "Expecting testAtomic" << name << " value to be 2. Got " << testAtomic << std::endl; - return 1; - } - itk::AtomicInt testAtomicCopy(3); - testAtomic = testAtomicCopy; - if (testAtomic != 3) - { - std::cout << "Expecting testAtomic" << name << " value to be 3. Got " << testAtomic << std::endl; - return 1; - } - if (testAtomic.load() != 3) - { - std::cout << "Expecting testAtomic" << name << ".load() value to be 3. Got " << testAtomic.load() << std::endl; - return 1; - } - testAtomic.store(0); - if (testAtomic != 0) - { - std::cout << "Expecting testAtomic" << name << " value to be 0. Got " << testAtomic << std::endl; - return 1; - } - T preinc_val = ++testAtomic; - if (preinc_val != 1) - { - std::cout << "Expecting PreIncrement (" << name << ") value to be 1. Got " << preinc_val << std::endl; - return 1; - } - T postinc_val = testAtomic++; - if (postinc_val != 1) - { - std::cout << "Expecting PostIncrement (" << name << ") value to be 1. Got " << postinc_val << std::endl; - return 1; - } - T predec_val = --testAtomic; - if (predec_val != 1) - { - std::cout << "Expecting PreDecrement (" << name << ") value to be 1. Got " << predec_val << std::endl; - return 1; - } - T postdec_val = testAtomic--; - if (postdec_val != 1) - { - std::cout << "Expecting PostDecrement (" << name << ") value to be 1. Got " << postdec_val << std::endl; - return 1; - } - testAtomic += 2; - T addAndFetch_val = testAtomic; - if (addAndFetch_val != 2) - { - std::cout << "Expecting AddAndFetch (" << name << ") value to be 2. Got " << addAndFetch_val << std::endl; - return 1; - } - testAtomic -= 1; - T subAndFetch_val = testAtomic; - if (subAndFetch_val != 1) - { - std::cout << "Expecting SubAndFetch (" << name << ") value to be 1. Got " << subAndFetch_val << std::endl; - return 1; - } - return 0; -} - -int -itkAtomicIntTest(int, char *[]) -{ - // Verify all atomic operators - if (TestAtomicOperators("32") || TestAtomicOperators("64")) - { - return 1; - } - // Verify atomic behavior - Total = 0; - TotalAtomic = 0; - Total64 = 0; - TotalAtomic64 = 0; - - for (unsigned int i = 0; i < Target; ++i) - { - Values32[i] = 0; - Values64[i] = 0; - } - - itk::MultiThreaderBase::Pointer mt = itk::MultiThreaderBase::New(); - // depending on which multi-threader is instantiated by default, - // there might be different number of object modification times - // so the "initial" Mtime is recorder afterwards - AnObject = itk::Object::New(); - itk::ModifiedTimeType beforeMTime = AnObject->GetMTime(); - - mt->SetSingleMethod(MyFunction, nullptr); - mt->SetNumberOfWorkUnits(NumThreads); - mt->SingleMethodExecute(); - - mt->SetSingleMethod(MyFunction2, nullptr); - mt->SingleMethodExecute(); - - mt->SetSingleMethod(MyFunction3, nullptr); - mt->SingleMethodExecute(); - - // Making sure that atomic incr returned unique - // values each time. We expect all numbers from - // 1 to Target-1 to be 2. - if (Values32[0] != 0) - { - std::cout << "Expecting Values32[0] to be 0. Got " << Values32[0] << std::endl; - return 1; - } - if (Values64[0] != 0) - { - std::cout << "Expecting Values64[0] to be 0. Got " << Values64[0] << std::endl; - return 1; - } - for (unsigned int i = 1; i < Target; ++i) - { - if (Values32[i] != 2) - { - std::cout << "Expecting Values32[" << i << "] to be 2. Got " << Values32[i] << std::endl; - return 1; - } - if (Values64[i] != 2) - { - std::cout << "Expecting Values64[" << i << "] to be 2. Got " << Values64[i] << std::endl; - return 1; - } - } - - mt->SetSingleMethod(MyFunction4, nullptr); - mt->SingleMethodExecute(); - - std::cout << Total << ' ' << TotalAtomic.load() << std::endl; - std::cout << Total64 << ' ' << TotalAtomic64.load() << std::endl; - - std::cout << "MTime: " << AnObject->GetMTime() << std::endl; - - mt->SetSingleMethod(MyFunctionPtr, nullptr); - mt->SingleMethodExecute(); - - // Making sure that pointer atomic incr returned unique - // values each time incremented by the size of the pointer. - // We expect all numbers from 1 to Target-1 to be 1. - if (Values32[0] != 0) - { - std::cout << "Expecting Values32[0] to be 0. Got " << Values32[0] << std::endl; - return 1; - } - if (Values64[0] != 0) - { - std::cout << "Expecting Values64[0] to be 0. Got " << Values64[0] << std::endl; - return 1; - } - for (unsigned int i = 1; i < Target; ++i) - { - if (Values32[i] != 1) - { - std::cout << "Expecting Values32[" << i << "] to be 1. Got " << Values32[i] << std::endl; - return 1; - } - if (Values64[i] != 1) - { - std::cout << "Expecting Values64[" << i << "] to be 1. Got " << Values64[i] << std::endl; - return 1; - } - } - - if (TotalAtomic.load() != static_cast(Target)) - { - return 1; - } - - if (TotalAtomic64.load() != static_cast(Target)) - { - return 1; - } - - if (AnObject->GetReferenceCount() != 1) - { - return 1; - } - - if (AnObject->GetMTime() != Target + beforeMTime) - { - return 1; - } - - return 0; -} diff --git a/Modules/Compatibility/Deprecated/test/itkBarrierTest.cxx b/Modules/Compatibility/Deprecated/test/itkBarrierTest.cxx deleted file mode 100644 index 4675a567e3e..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkBarrierTest.cxx +++ /dev/null @@ -1,178 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 "itkBarrier.h" -#include "itkMultiThreaderBase.h" -#include "itkTestingMacros.h" - - -class BarrierTestUserData -{ -public: - itk::Barrier::Pointer m_FirstBarrier; - itk::Barrier::Pointer m_SecondBarrier; - unsigned int m_Counter[itk::ITK_MAX_THREADS]; - unsigned int m_NumberOfIterations; - unsigned int m_NumberOfWorkUnits; - bool m_TestFailure; - - BarrierTestUserData(unsigned int number_of_threads) - { - m_TestFailure = false; - m_NumberOfWorkUnits = number_of_threads; - for (unsigned int i = 0; i < number_of_threads - 1; ++i) - { - m_Counter[i] = 0; - } - m_NumberOfIterations = 50; - m_FirstBarrier = itk::Barrier::New(); - m_SecondBarrier = itk::Barrier::New(); - m_FirstBarrier->Initialize(number_of_threads); - m_SecondBarrier->Initialize(number_of_threads); - } - ~BarrierTestUserData() = default; -}; - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -BarrierTestIncrement(void * ptr) -{ - itk::ThreadIdType threadId = ((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->WorkUnitID; - auto * data = static_cast(((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->UserData); - - for (unsigned int i = 0; i < data->m_NumberOfIterations; ++i) - { - // set the value for this iteration - data->m_Counter[threadId] = i; - - // wait for all the other threads - data->m_FirstBarrier->Wait(); - data->m_SecondBarrier->Wait(); - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -BarrierCheckIncrement(void * ptr) -{ - auto * data = static_cast(((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->UserData); - - for (unsigned int i = 0; i < data->m_NumberOfIterations; ++i) - { - // Wait for other threads to populate the m_Counter array - data->m_FirstBarrier->Wait(); - - // Check the values in the m_Counter array - for (unsigned int j = 0; j < data->m_NumberOfWorkUnits - 1; ++j) - { - if (data->m_Counter[j] != i) - { - data->m_TestFailure = true; - } - } - data->m_SecondBarrier->Wait(); - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -BarrierTestCallback(void * ptr) -{ - itk::ThreadIdType threadId = ((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->WorkUnitID; - auto * data = static_cast(((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->UserData); - - if (threadId == data->m_NumberOfWorkUnits - 1) - { - BarrierCheckIncrement(ptr); - } - else - { - BarrierTestIncrement(ptr); - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -BarrierSpecialTest(void * ptr) -{ - auto * data = static_cast(((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->UserData); - - for (unsigned int j = 0; j < 1000; ++j) - { - data->m_FirstBarrier->Wait(); - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -int -itkBarrierTest(int argc, char * argv[]) -{ - itk::Barrier::Pointer barrier = itk::Barrier::New(); - ITK_EXERCISE_BASIC_OBJECT_METHODS(barrier, Barrier, LightObject); - - itk::ThreadIdType number_of_threads = 4; - if (argc > 1) - { - number_of_threads = std::stoi(argv[1]); - } - - BarrierTestUserData data(number_of_threads); - - try - { - itk::MultiThreaderBase::Pointer multithreader = itk::MultiThreaderBase::New(); - multithreader->SetMaximumNumberOfThreads(number_of_threads); - if (multithreader->GetMaximumNumberOfThreads() < number_of_threads) - { - std::cerr << "Could not increase number of threads to " << number_of_threads << " in " - << multithreader->GetNameOfClass() << std::endl; - return EXIT_FAILURE; - } - - multithreader->SetNumberOfWorkUnits(number_of_threads); - multithreader->SetSingleMethod(BarrierTestCallback, &data); - - for (unsigned int i = 0; i < 5; ++i) // repeat test 5 times - { - multithreader->SingleMethodExecute(); - } - - // perform another test - multithreader->SetSingleMethod(BarrierSpecialTest, &data); - multithreader->SingleMethodExecute(); - } - catch (const itk::ExceptionObject & e) - { - std::cerr << e << std::endl; - return EXIT_FAILURE; - } - - if (data.m_TestFailure == false) - { - std::cout << "[TEST PASSED]" << std::endl; - return EXIT_SUCCESS; - } - else - { - std::cout << "[TEST FAILED]" << std::endl; - return 2; - } -} diff --git a/Modules/Compatibility/Deprecated/test/itkConditionVariableTest.cxx b/Modules/Compatibility/Deprecated/test/itkConditionVariableTest.cxx deleted file mode 100644 index f8acf6ad9c6..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkConditionVariableTest.cxx +++ /dev/null @@ -1,131 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 -#include "itkConditionVariable.h" -#include "itkPlatformMultiThreader.h" - -class ConditionVariableTestUserData -{ -public: - itk::SimpleMutexLock m_Mutex; - itk::ConditionVariable::Pointer m_ConditionVariable; - unsigned int m_Counter; - unsigned int m_CountLimit; - - ConditionVariableTestUserData() - { - m_ConditionVariable = itk::ConditionVariable::New(); - m_Counter = 0; - m_CountLimit = 12; - } - ~ConditionVariableTestUserData() = default; -}; - - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -ConditionVariableTestIncCount(void * ptr) -{ - auto * data = static_cast(((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->UserData); - - double v = 400.0; - - for (unsigned int i = 0; i < 10; ++i) - { - data->m_Mutex.Lock(); - data->m_Counter++; - // Check the value of count. If the condition has been reached, signal - // waiting threads. - if (data->m_Counter == data->m_CountLimit) - { - // data->m_ConditionVariable->Signal(); - // Tests both Broadcast and Signal - data->m_ConditionVariable->Broadcast(); - } - - data->m_Mutex.Unlock(); - - // Do some work here. - for (unsigned int j = 0; j < 1000; ++j) - { - v = v / 2.4; - v = v * 2.4; - } - } - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -ConditionVariableTestWatchCount(void * ptr) -{ - auto * data = static_cast(((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->UserData); - - // Lock the mutex and wait for the signal. - data->m_Mutex.Lock(); - while (data->m_Counter < data->m_CountLimit) - { - data->m_ConditionVariable->Wait(&data->m_Mutex); - } - data->m_Mutex.Unlock(); - - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION -ConditionVariableTestCallback(void * ptr) -{ - itk::ThreadIdType threadId = ((itk::MultiThreaderBase::WorkUnitInfo *)(ptr))->WorkUnitID; - - if (threadId == 0) - { - ConditionVariableTestWatchCount(ptr); - } - else - { - ConditionVariableTestIncCount(ptr); - } - return ITK_THREAD_RETURN_DEFAULT_VALUE; -} - -int -itkConditionVariableTest(int, char *[]) -{ - ConditionVariableTestUserData cond; - - try - { - itk::PlatformMultiThreader::Pointer multithreader = itk::PlatformMultiThreader::New(); - multithreader->SetNumberOfWorkUnits(3); - multithreader->SetSingleMethod(ConditionVariableTestCallback, &cond); - - for (unsigned int i = 0; i < 1000; ++i) - { - cond.m_Counter = 0; - multithreader->SingleMethodExecute(); - } - } - catch (const itk::ExceptionObject & e) - { - std::cerr << e << std::endl; - return 2; - } - - std::cout << "[TEST PASSED]" << std::endl; - return EXIT_SUCCESS; -} diff --git a/Modules/Compatibility/Deprecated/test/itkSimpleFastMutexLockTest.cxx b/Modules/Compatibility/Deprecated/test/itkSimpleFastMutexLockTest.cxx deleted file mode 100644 index c797b687b9b..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkSimpleFastMutexLockTest.cxx +++ /dev/null @@ -1,67 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 "itkSimpleFastMutexLock.h" - -#include // For cout. - - -int -itkSimpleFastMutexLockTest(int, char *[]) -{ - { - itk::SimpleFastMutexLock lock; - - // Acquire the lock - lock.Lock(); - - // Acquire the lock again; as this call happens within the same thread, - // it shouldn't block. - // If the lock isn't recursive, it will block forever and the CTest - // timeout will cause the test to fail. - lock.Lock(); - } - - - { // Test non-blocking version - itk::SimpleFastMutexLock nblock; - nblock.Lock(); - nblock.Unlock(); - const bool testTryLockWhenFree = nblock.TryLock(); - if (testTryLockWhenFree != true) - { - std::cout << "Failed to capture a free lock with TryLock()" << std::endl; - return EXIT_FAILURE; - } - - if (!nblock.TryLock()) - { - std::cout << "Failed to recursively capture a lock with TryLock()" << std::endl; - return EXIT_FAILURE; - } - nblock.Unlock(); - nblock.Lock(); - // Ensure the TryLock() does not cause a deadlock. - // If the lock isn't recursive, it will block forever and the CTest - // timeout will cause the test to fail. - nblock.Unlock(); - } - - return EXIT_SUCCESS; -} diff --git a/Modules/Compatibility/Deprecated/test/itkSpawnThreadTest.cxx b/Modules/Compatibility/Deprecated/test/itkSpawnThreadTest.cxx deleted file mode 100644 index 9fb8edc961e..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkSpawnThreadTest.cxx +++ /dev/null @@ -1,110 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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_LEGACY_TEST // so deprecation warnings are not triggered by this test -#include "itkPlatformMultiThreader.h" -#include "itkMutexLock.h" -#include "itkTimeProbe.h" -#include "itkConfigure.h" -#include "itksys/SystemTools.hxx" - -struct SharedThreadData -{ - int numberOfLoop; - itk::MutexLock::Pointer sharedMutex; -}; - -void * -ThreadFunction(void * ptr) -{ - // Retrieve shared thread data and user data - auto * workUnitInfo = static_cast(ptr); - itk::ThreadIdType localthreadId = workUnitInfo->WorkUnitID; - auto * localThreadData = static_cast(workUnitInfo->UserData); - int localnumberOfLoop = localThreadData->numberOfLoop; - itk::MutexLock::Pointer localMutex = localThreadData->sharedMutex; - - for (int i = 0; i < localnumberOfLoop; ++i) - { - localMutex->Lock(); - std::cerr << "Thread #" << localthreadId << ":: counter = " << i << std::endl; - localMutex->Unlock(); - } - - localMutex->Lock(); - std::cerr << "Thread #" << localthreadId << " is done." << std::endl; - localMutex->Unlock(); - - return nullptr; -} - -int -itkSpawnThreadTest(int argc, char * argv[]) -{ - int loop = 100; - if (argc > 1) - { - const int nt = std::stoi(argv[1]); - if (nt > 1) - { - loop = nt; - } - } - - itk::PlatformMultiThreader::Pointer threader = itk::PlatformMultiThreader::New(); - itk::MutexLock::Pointer mutexlock = itk::MutexLock::New(); - if (threader.IsNull() || mutexlock.IsNull()) - { - return EXIT_FAILURE; - } - - SharedThreadData threadData; - threadData.numberOfLoop = loop; - threadData.sharedMutex = mutexlock; - - int id1 = threader->SpawnThread((itk::ThreadFunctionType)&ThreadFunction, &threadData); - int id2 = threader->SpawnThread((itk::ThreadFunctionType)&ThreadFunction, &threadData); - int id3 = threader->SpawnThread((itk::ThreadFunctionType)&ThreadFunction, &threadData); - int id4 = threader->SpawnThread((itk::ThreadFunctionType)&ThreadFunction, &threadData); - int id5 = threader->SpawnThread((itk::ThreadFunctionType)&ThreadFunction, &threadData); - int id6 = threader->SpawnThread((itk::ThreadFunctionType)&ThreadFunction, &threadData); - int id7 = threader->SpawnThread((itk::ThreadFunctionType)&ThreadFunction, &threadData); - - for (int i = 0; i < threadData.numberOfLoop; ++i) - { - mutexlock->Lock(); - std::cerr << "Main Thread:: counter = " << i << std::endl; - mutexlock->Unlock(); - } - - mutexlock->Lock(); - std::cerr << "Main Thread is done." << std::endl; - mutexlock->Unlock(); - - // wait for the threads - threader->TerminateThread(id1); - threader->TerminateThread(id2); - threader->TerminateThread(id3); - threader->TerminateThread(id4); - threader->TerminateThread(id5); - threader->TerminateThread(id6); - threader->TerminateThread(id7); - - std::cerr << "All theads are stopped ...." << std::endl; - return EXIT_SUCCESS; -} diff --git a/Modules/Compatibility/Deprecated/test/itkTreeContainerTest.cxx b/Modules/Compatibility/Deprecated/test/itkTreeContainerTest.cxx deleted file mode 100644 index 5a74409c072..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkTreeContainerTest.cxx +++ /dev/null @@ -1,296 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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. - * - *=========================================================================*/ - -/** - * This is a test file for the itkTreeContainer class. - */ -#include "itkTreeContainer.h" -#include "itkChildTreeIterator.h" -#include "itkLeafTreeIterator.h" -#include "itkLevelOrderTreeIterator.h" -#include "itkInOrderTreeIterator.h" -#include "itkPostOrderTreeIterator.h" -#include "itkRootTreeIterator.h" -#include "itkTreeIteratorClone.h" -#include "itkTestingMacros.h" - -int -itkTreeContainerTest(int, char *[]) -{ - using NodeType = int; - using TreeType = itk::TreeContainer; - auto tree = TreeType::New(); - tree->SetRoot(0); - tree->Add(1, 0); - tree->Add(2, 0); - tree->Add(3, 0); - tree->Add(4, 2); - tree->Add(5, 2); - tree->Add(6, 5); - tree->Add(7, 1); - - unsigned int expectedIndex = 0; - - std::cout << "Testing PrintSelf: " << std::endl; - std::cout << tree << std::endl; - std::cout << "[SUCCESS]" << std::endl; - - // LevelOrderTreeIterator Test - std::cout << "Testing LevelOrderTreeIterator: " << std::endl; - itk::LevelOrderTreeIterator levelIt(tree, 10, tree->GetNode(2)); - levelIt.GoToBegin(); - while (!levelIt.IsAtEnd()) - { - std::cout << levelIt.Get() << " (" << levelIt.GetLevel() << ')' << std::endl; - ++levelIt; - } - - // Test some functionalities of TreeIteratorBase - // IsLeaf() - std::cout << "Testing IsLeaf(): "; - levelIt.GoToBegin(); - if (levelIt.IsLeaf()) - { - std::cout << "[FAILURE]" << std::endl; - return EXIT_FAILURE; - } - std::cout << "[SUCCESS]" << std::endl; - - // IsRoot() - std::cout << "Testing IsRoot(): "; - if (!levelIt.IsRoot()) - { - std::cout << "[FAILURE]" << std::endl; - return EXIT_FAILURE; - } - std::cout << "[SUCCESS]" << std::endl; - - // HasParent() - std::cout << "Testing HasParent(): "; - if (!levelIt.HasParent()) - { - std::cout << "[FAILURE]" << std::endl; - return EXIT_FAILURE; - } - std::cout << "[SUCCESS]" << std::endl; - - // CountChildren() - std::cout << "Testing CountChildren(): "; - if (levelIt.CountChildren() != 2) - { - std::cout << "[FAILURE]" << std::endl; - return EXIT_FAILURE; - } - std::cout << "[SUCCESS]" << std::endl; - - - // ChildTreeIterator Test - std::cout << "Testing ChildTreeIterator: " << std::endl; - NodeType expectedChild[] = { 1, 2, 3 }; - expectedIndex = 0; - itk::ChildTreeIterator childIt(tree); - childIt.GoToBegin(); - while (!childIt.IsAtEnd()) - { - std::cout << childIt.Get() << std::endl; - ITK_TEST_EXPECT_EQUAL(childIt.Get(), expectedChild[expectedIndex]); - ++expectedIndex; - ++childIt; - } - std::cout << std::endl; - - std::cout << "Starting to another branch: " << std::endl; - itk::ChildTreeIterator childIt2(tree, tree->GetNode(2)); - childIt2.GoToBegin(); - while (!childIt2.IsAtEnd()) - { - std::cout << childIt2.Get() << std::endl; - ++childIt2; - } - - childIt2.GoToBegin(); - - std::cout << "Testing other features : "; - - if (childIt2.GetType() != itk::TreeIteratorBaseEnums::TreeIteratorBaseNode::CHILD) - { - std::cout << "[FAILURE]" << std::endl; - return EXIT_FAILURE; - } - - if (!childIt2.GoToParent()) - { - std::cout << "[FAILURE]" << std::endl; - return EXIT_FAILURE; - } - - std::cout << "[SUCCESS]" << std::endl; - - std::cout << "Testing Clone() : "; - itk::TreeIteratorBase * childItClone = childIt2.Clone(); - if (!childItClone) - { - std::cout << "[FAILURE]" << std::endl; - return EXIT_FAILURE; - } - delete childItClone; - - std::cout << "[SUCCESS]" << std::endl; - - // LeafTreeIterator Test - std::cout << "Testing LeafTreeIterator: " << std::endl; - NodeType expectedLeaf[] = { 7, 4, 6, 3 }; - expectedIndex = 0; - itk::LeafTreeIterator leafIt(tree); - leafIt.GoToBegin(); - while (!leafIt.IsAtEnd()) - { - std::cout << leafIt.Get() << std::endl; - ITK_TEST_EXPECT_EQUAL(leafIt.Get(), expectedLeaf[expectedIndex]); - ++expectedIndex; - ++leafIt; - } - - std::cout << std::endl; - std::cout << "[SUCCESS]" << std::endl; - - - // InOrderTreeIterator Test - std::cout << "Testing InOrderTreeIterator: " << std::endl; - NodeType expectedInOrder[] = { 0, 1, 7, 2, 4, 5, 6, 3 }; - expectedIndex = 0; - itk::InOrderTreeIterator InOrderIt(tree); - InOrderIt.GoToBegin(); - while (!InOrderIt.IsAtEnd()) - { - std::cout << InOrderIt.Get() << std::endl; - ITK_TEST_EXPECT_EQUAL(InOrderIt.Get(), expectedInOrder[expectedIndex]); - ++expectedIndex; - ++InOrderIt; - } - std::cout << std::endl; - std::cout << "[SUCCESS]" << std::endl; - - - // PostOrderTreeIterator Test - std::cout << "Testing PostOrderTreeIterator: " << std::endl; - NodeType expectedPostOrder[] = { 7, 1, 4, 6, 5, 2, 3, 0 }; - expectedIndex = 0; - itk::PostOrderTreeIterator PostOrderIt(tree); - PostOrderIt.GoToBegin(); - while (!PostOrderIt.IsAtEnd()) - { - std::cout << PostOrderIt.Get() << std::endl; - ITK_TEST_EXPECT_EQUAL(PostOrderIt.Get(), expectedPostOrder[expectedIndex]); - ++expectedIndex; - ++PostOrderIt; - } - std::cout << std::endl; - std::cout << "[SUCCESS]" << std::endl; - - // RootTreeIterator Test - std::cout << "Testing RootTreeIterator: " << std::endl; - NodeType expectedRootTree[] = { 6, 5, 2, 0 }; - expectedIndex = 0; - itk::RootTreeIterator RootIt(tree, tree->GetNode(6)); - RootIt.GoToBegin(); - while (!RootIt.IsAtEnd()) - { - std::cout << RootIt.Get() << std::endl; - ITK_TEST_EXPECT_EQUAL(RootIt.Get(), expectedRootTree[expectedIndex]); - ++expectedIndex; - ++RootIt; - } - std::cout << std::endl; - std::cout << "[SUCCESS]" << std::endl; - - - // PreOrderTreeIterator Test - std::cout << "Testing PreOrderTreeIterator: " << std::endl; - NodeType expectedPreOrder[] = { 0, 1, 7, 2, 4, 5, 6, 3 }; - expectedIndex = 0; - itk::PreOrderTreeIterator PreOrderIt(tree); - PreOrderIt.GoToBegin(); - while (!PreOrderIt.IsAtEnd()) - { - std::cout << PreOrderIt.Get() << std::endl; - ITK_TEST_EXPECT_EQUAL(PreOrderIt.Get(), expectedPreOrder[expectedIndex]); - ++expectedIndex; - ++PreOrderIt; - } - std::cout << std::endl; - std::cout << "[SUCCESS]" << std::endl; - - - /** Now create the tree using iterators */ - std::cout << "Testing clear tree" << std::endl; - if (tree->Clear()) - { - std::cout << "[SUCCESS]" << std::endl; - } - else - { - std::cout << "[FAILURE]" << std::endl; - return EXIT_FAILURE; - } - - std::cout << tree << std::endl; - - // Testing the tree creation using iterators - itk::PreOrderTreeIterator PreOrderIt2(tree); - PreOrderIt2.Add(0); - PreOrderIt2.Add(1); - PreOrderIt2.Add(2); - PreOrderIt2.Add(3); - PreOrderIt2.GoToChild(2); - PreOrderIt2.Add(4); - PreOrderIt2.Add(5); - - std::cout << tree << std::endl; - std::cout << "[SUCCESS]" << std::endl; - // Try to add a bench of leaves - itk::LeafTreeIterator LeafIt2(tree); - LeafIt2.GoToBegin(); - int i = 6; - while (!LeafIt2.IsAtEnd()) - { - LeafIt2.Add(i); - i++; - ++LeafIt2; - if (!LeafIt2.IsAtEnd()) - { - ++LeafIt2; - } - } - std::cout << tree << std::endl; - std::cout << "[SUCCESS]" << std::endl; - - - // Test the TreeIteratorClone - using IteratorType = itk::TreeIteratorBase; - using MyIteratorClone = itk::TreeIteratorClone; - itk::PreOrderTreeIterator anIterator(tree); - MyIteratorClone aClone = anIterator; - ++aClone; // step forward in the cloned iterator, anIterator unchanged. - itk::PreOrderTreeIterator anotherIterator(tree); - aClone = anotherIterator; // the memory for the cloned version of "anIterator" is freed. - ++aClone; // step forward in the cloned iterator, but now in post-order! - - std::cout << "Test Done." << std::endl; - return EXIT_SUCCESS; -} diff --git a/Modules/Compatibility/Deprecated/test/itkTreeContainerTest2.cxx b/Modules/Compatibility/Deprecated/test/itkTreeContainerTest2.cxx deleted file mode 100644 index cdcafe15fe7..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkTreeContainerTest2.cxx +++ /dev/null @@ -1,430 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 -#include "itkCommand.h" -#include - - -/** - * This is a test file for the itkTreeContainer class. - */ - -#include "itkTreeContainer.h" -#include "itkChildTreeIterator.h" -#include "itkLevelOrderTreeIterator.h" -#include "itkInOrderTreeIterator.h" -#include "itkPostOrderTreeIterator.h" -#include "itkRootTreeIterator.h" - -class TestData -{ -public: - TestData() - { - m_Value = 0; - m_Counter++; - } - - TestData(const int valueIn) - { - m_Value = valueIn; - m_Counter++; - } - - TestData(const TestData & t) - { - m_Value = t.m_Value; - m_Counter++; - } - - ~TestData() - { - m_Value = 0; - m_Counter--; - - if (m_Counter == 0) - { - std::cout << "last Data destroyed" << std::endl; - } - } - - int - Get() const - { - return m_Value; - } - - void - Set(int v) - { - m_Value = v; - } - - TestData & - operator=(const TestData & t) - { - m_Value = t.m_Value; - std::cout << "assignation: " << m_Value << std::endl; - return *this; - } - - bool - operator==(const TestData & t) - { - if (&t == this) - { - return true; - } - return false; - } - - friend std::ostream & - operator<<(std::ostream & o, TestData & t); - friend std::istream & - operator>>(std::istream & i, TestData & t); - -private: - int m_Value; - static int m_Counter; -}; - -int TestData::m_Counter = 0; - -std::ostream & -operator<<(std::ostream & o, TestData & t) -{ - return o << "( TestData Nr. " << t.Get() << " )"; -} - -std::istream & -operator>>(std::istream & i, TestData & t) -{ - char s[10]; - int value; - - i >> s; // { - i >> s; // TestData - i >> s; // Nr. - i >> s; // } - i >> value; - - t.Set(value); - return i; -} - - -using NodePointerType = TestData *; -using NodeListType = std::list; -using TreeType = itk::TreeContainer; - -class TreeChangeListener : public itk::Command -{ -public: - using Self = TreeChangeListener; - using Pointer = itk::SmartPointer; - using ConstPointer = itk::SmartPointer; - itkNewMacro(Self); - - void - Execute(itk::Object *, const itk::EventObject & event) override - { - std::cout << event.GetEventName() << std::endl; - } - - void - Execute(const itk::Object *, const itk::EventObject & event) override - { - std::cout << event.GetEventName(); - - const auto * e = static_cast *>(&event); - - std::cout << *e->GetChangePosition().Get() << std::endl; - } - -protected: - TreeChangeListener() = default; -}; - -/* - CreateTree_1() - - [1] - - * * * - * * * * - * * * * - [11] [12] [13] [14] - * * * * * * - * * * * * * - * * * * * * - [111] [112] [113] [121] [122] [123] - * - * - * - [9] - * * - * * - * * - [91] [92] - * * * - * * * - * * * - [991] [912] [913] - */ -TreeType::Pointer -CreateTree_1(NodeListType & internalList) -{ - std::cout << "create tree" << std::endl; - - auto tree = TreeType::New(); - - - auto treeChangeListener = TreeChangeListener::New(); - itk::TreeAddEvent ev; - unsigned long tag = tree->AddObserver(ev, treeChangeListener); - - - itk::PostOrderTreeIterator it(tree); - - auto * newNode = new TestData(1); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(11); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(12); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(13); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(14); - internalList.push_back(newNode); - it.Add(newNode); - it.GoToChild(0); - newNode = new TestData(111); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(112); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(113); - internalList.push_back(newNode); - it.Add(newNode); - it.GoToParent(); - it.GoToChild(1); - newNode = new TestData(121); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(122); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(123); - internalList.push_back(newNode); - it.Add(newNode); - tree->RemoveObserver(tag); - - std::cout << "end create tree" << std::endl; - return tree; -} - -/* - CreateTree_2() - - * - * - * - [9] - * * - * * - * * - [91] [92] - * * * - * * * - * * * - [991] [912] [913] - */ -TreeType::Pointer -CreateTree_2(NodeListType & internalList) -{ - std::cout << "create tree 2" << std::endl; - - auto tree = TreeType::New(); - auto * newNode = new TestData(9); - internalList.push_back(newNode); - tree->SetRoot(newNode); - itk::PostOrderTreeIterator it(tree); - - newNode = new TestData(91); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(92); - internalList.push_back(newNode); - it.Add(newNode); - it.GoToChild(0); - newNode = new TestData(991); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(912); - internalList.push_back(newNode); - it.Add(newNode); - newNode = new TestData(913); - internalList.push_back(newNode); - it.Add(newNode); - - std::cout << "end create tree 2" << std::endl; - return tree; -} - -int -IteratorTest(itk::TreeIteratorBase & i) -{ - int sum = 0; - - // childIt.GoToBegin(); - while (!i.IsAtEnd()) - { - sum += i.Get()->Get(); - std::cout << i.Get()->Get() << std::endl; - ++i; - } - - return sum; -} - -/** Print the results */ -int -PrintResult(int result, int value) -{ - if (result == value) - { - std::cout << "[SUCCESS]" << std::endl; - return 1; - } - else - { - std::cout << "[FAILURE]" << std::endl; - return 0; - } -} - -/** - * Test - */ -int -itkTreeContainerTest2(int, char *[]) -{ - int result; - int testCounter = 0; - NodeListType internalList; // used to delete the pointer in the tree - - TreeType::Pointer tree = CreateTree_1(internalList); - - std::cout << "\nPreOrderTreeIterator:" << std::endl; - itk::PreOrderTreeIterator preOrderIt(tree); - result = IteratorTest(preOrderIt); - testCounter += PrintResult(result, 753); - - std::cout << "\nLevelOrderTreeIterator:" << std::endl; - itk::LevelOrderTreeIterator levelIt(tree); - result = IteratorTest(levelIt); - testCounter += PrintResult(result, 753); - - std::cout << "\nInOrderTreeIterator:" << std::endl; - itk::InOrderTreeIterator inOrderIt(tree); - result = IteratorTest(inOrderIt); - testCounter += PrintResult(result, 753); - - std::cout << "\nPostOrderTreeIterator:" << std::endl; - itk::PostOrderTreeIterator postOrderIt(tree); - result = IteratorTest(postOrderIt); - testCounter += PrintResult(result, 753); - - std::cout << "\nChildTreeIterator Test 1:" << std::endl; - itk::ChildTreeIterator childIt_1(tree); - result = IteratorTest(childIt_1); - testCounter += PrintResult(result, 50); - - std::cout << "\nChildTreeIterator Test 2:" << std::endl; - itk::ChildTreeIterator childIt_2(tree); - childIt_2.GoToChild(0); - result = IteratorTest(childIt_2); - testCounter += PrintResult(result, 336); - - std::cout << "\nChildTreeIterator Test 3:" << std::endl; - itk::ChildTreeIterator childIt_3(tree); - childIt_3.GoToChild(1); - result = IteratorTest(childIt_3); - testCounter += PrintResult(result, 366); - - std::cout << "\nChildTreeIterator Test 4:" << std::endl; - itk::ChildTreeIterator childIt_4(tree); - childIt_4.GoToChild(1); - childIt_4.GoToChild(2); - result = IteratorTest(childIt_4); - testCounter += PrintResult(result, 0); - - std::cout << "\nRootTreeIterator Test 1:" << std::endl; - itk::RootTreeIterator rootIt_1(tree); - rootIt_1.GoToChild(1); - rootIt_1.GoToChild(2); - result = IteratorTest(rootIt_1); - testCounter += PrintResult(result, 136); - - // creat tree 2 - itk::PreOrderTreeIterator iterator_123(tree); - iterator_123.GoToChild(1); - iterator_123.GoToChild(2); - TreeType::Pointer tree_2 = CreateTree_2(internalList); - iterator_123.Add(*tree_2.GetPointer()); - - std::cout << "\nTree1 + Tree2:" << std::endl; - itk::PreOrderTreeIterator preOrderIt_Tree_1_2(tree); - result = IteratorTest(preOrderIt_Tree_1_2); - testCounter += PrintResult(result, 3761); - - auto treeChangeListener = TreeChangeListener::New(); - itk::TreeChangeEvent ev; - unsigned long tag = tree->AddObserver(ev, treeChangeListener); - tree->Clear(); - tree->RemoveObserver(tag); - - // Delete the list of pointer to TestData - auto it = internalList.begin(); - - while (it != internalList.end()) - { - auto it2 = it; - ++it; - TestData * t = *it2; - internalList.erase(it2); - delete t; - } - - if (testCounter == 10) - { - std::cout << "TEST DONE" << std::endl; - return EXIT_SUCCESS; - } - else - { - std::cout << "TEST [FAILURE]" << std::endl; - return EXIT_FAILURE; - } -} diff --git a/Modules/Compatibility/Deprecated/test/itkVectorCentralDifferenceImageFunctionTest.cxx b/Modules/Compatibility/Deprecated/test/itkVectorCentralDifferenceImageFunctionTest.cxx deleted file mode 100644 index 2de86210067..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkVectorCentralDifferenceImageFunctionTest.cxx +++ /dev/null @@ -1,103 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 "itkVectorCentralDifferenceImageFunction.h" -#include "itkImageRegionIterator.h" - -int -itkVectorCentralDifferenceImageFunctionTest(int, char *[]) -{ - constexpr unsigned int ImageDimension = 2; - constexpr unsigned int VectorDimension = 3; - using PixelType = itk::Vector; - using ImageType = itk::Image; - - auto image = ImageType::New(); - ImageType::SizeType size; - size.Fill(16); - ImageType::RegionType region(size); - - image->SetRegions(region); - image->Allocate(); - - // make a test image - using Iterator = itk::ImageRegionIterator; - Iterator iter(image, region); - iter.GoToBegin(); - unsigned int counter = 0; - - while (!iter.IsAtEnd()) - { - iter.Set(counter++); - ++iter; - } - - // set up central difference calculator - using CoordRepType = float; - using FunctionType = itk::VectorCentralDifferenceImageFunction; - auto function = FunctionType::New(); - - function->SetInputImage(image); - - ImageType::IndexType index; - - // pick an index inside the image - index.Fill(8); - std::cout << "Index: " << index << " Derivative:" << std::endl; - std::cout << function->EvaluateAtIndex(index) << std::endl; - - if (function->IsInsideBuffer(index)) - { - std::cout << "Index: " << index << " is inside the BufferedRegion." << std::endl; - } - - FunctionType::ContinuousIndexType cindex; - cindex.Fill(8.0); - std::cout << "ContinuousIndex: " << cindex << " Derivative:" << std::endl; - std::cout << function->EvaluateAtContinuousIndex(cindex) << std::endl; - - FunctionType::PointType point; - point.Fill(8.0); - std::cout << "Point: " << cindex << " Derivative:" << std::endl; - std::cout << function->Evaluate(point) << std::endl; - - // pick an index on the image edge - index.Fill(8); - index[0] = 15; - std::cout << "Index: " << index << " Derivative:" << std::endl; - std::cout << function->EvaluateAtIndex(index) << std::endl; - - if (function->IsInsideBuffer(index)) - { - std::cout << "Index: " << index << " is inside the BufferedRegion." << std::endl; - } - - cindex.Fill(8.0); - cindex[0] = 15.0; - std::cout << "ContinuousIndex: " << cindex << " Derivative:" << std::endl; - std::cout << function->EvaluateAtContinuousIndex(cindex) << std::endl; - - point.Fill(8.0); - point[0] = 15.0; - std::cout << "Point: " << cindex << " Derivative:" << std::endl; - std::cout << function->Evaluate(point) << std::endl; - - - std::cout << "Test passed." << std::endl; - return EXIT_SUCCESS; -} diff --git a/Modules/Compatibility/Deprecated/test/itkVectorResampleImageFilterTest.cxx b/Modules/Compatibility/Deprecated/test/itkVectorResampleImageFilterTest.cxx deleted file mode 100644 index c74a9983645..00000000000 --- a/Modules/Compatibility/Deprecated/test/itkVectorResampleImageFilterTest.cxx +++ /dev/null @@ -1,155 +0,0 @@ -/*========================================================================= - * - * Copyright NumFOCUS - * - * 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 - * - * https://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 "itkVectorResampleImageFilter.h" -#include "itkImageFileWriter.h" -#include "itkSimpleFilterWatcher.h" -#include "itkTestingMacros.h" - -int -itkVectorResampleImageFilterTest(int argc, char * argv[]) -{ - - if (argc < 2) - { - std::cerr << "Missing parameters." << std::endl; - std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv); - std::cerr << " outputImage" << std::endl; - return EXIT_FAILURE; - } - - constexpr unsigned int Dimension = 2; - using PixelComponentType = unsigned char; - - using PixelType = itk::RGBPixel; - using ImageType = itk::Image; - - using FilterType = itk::VectorResampleImageFilter; - - auto filter = FilterType::New(); - - ITK_EXERCISE_BASIC_OBJECT_METHODS(filter, VectorResampleImageFilter, ImageToImageFilter); - - itk::SimpleFilterWatcher watcher(filter); - - using InterpolatorType = itk::VectorLinearInterpolateImageFunction; - - auto interpolator = InterpolatorType::New(); - - filter->SetInterpolator(interpolator); - ITK_TEST_SET_GET_VALUE(interpolator, filter->GetInterpolator()); - - using TransformType = itk::IdentityTransform; - auto transform = TransformType::New(); - - filter->SetTransform(transform); - ITK_TEST_SET_GET_VALUE(transform, filter->GetTransform()); - - ImageType::SpacingType spacing; - spacing.Fill(1.0); - - ImageType::PointType origin; - origin.Fill(0.0); - - ImageType::RegionType region; - ImageType::SizeType size; - ImageType::IndexType start; - - size[0] = 128; - size[1] = 128; - - start[0] = 0; - start[1] = 0; - - region.SetSize(size); - region.SetIndex(start); - - auto image = ImageType::New(); - - image->SetOrigin(origin); - image->SetSpacing(spacing); - image->SetRegions(region); - image->Allocate(); - - PixelType pixelValue; - - itk::ImageRegionIteratorWithIndex it(image, region); - - // Fill the image with some color pattern - it.GoToBegin(); - while (!it.IsAtEnd()) - { - ImageType::IndexType index = it.GetIndex(); - pixelValue.SetRed(index[0] * 2); - pixelValue.SetGreen(index[0] + index[1]); - pixelValue.SetBlue(index[1] * 2); - it.Set(pixelValue); - ++it; - } - - PixelType blackValue; - blackValue.Fill(0); - - filter->SetDefaultPixelValue(blackValue); - ITK_TEST_SET_GET_VALUE(blackValue, filter->GetDefaultPixelValue()); - - // Set the spacing for the resampling - spacing[0] *= 2.0; - spacing[1] *= 2.0; - - filter->SetOutputSpacing(spacing); - ITK_TEST_SET_GET_VALUE(spacing, filter->GetOutputSpacing()); - - // Keep the input image origin - filter->SetOutputOrigin(origin); - ITK_TEST_SET_GET_VALUE(origin, filter->GetOutputOrigin()); - - // Set the size - size[0] /= 2; - size[1] /= 2; - - filter->SetSize(size); - ITK_TEST_SET_GET_VALUE(size, filter->GetSize()); - - // Set the output direction - FilterType::DirectionType outputDirection = image->GetDirection(); - - filter->SetOutputDirection(outputDirection); - ITK_TEST_SET_GET_VALUE(outputDirection, filter->GetOutputDirection()); - - // Set the start index - FilterType::IndexType outputStartIndex = image->GetLargestPossibleRegion().GetIndex(); - - filter->SetOutputStartIndex(outputStartIndex); - ITK_TEST_SET_GET_VALUE(outputStartIndex, filter->GetOutputStartIndex()); - - - filter->SetInput(image); - - ITK_TRY_EXPECT_NO_EXCEPTION(filter->Update()); - - // Write an image for regression testing - using WriterType = itk::ImageFileWriter; - auto writer = WriterType::New(); - writer->SetInput(filter->GetOutput()); - writer->SetFileName(argv[1]); - - ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update()); - - return EXIT_SUCCESS; -} diff --git a/Modules/Compatibility/Deprecated/wrapping/itkImageTransformer.wrap b/Modules/Compatibility/Deprecated/wrapping/itkImageTransformer.wrap deleted file mode 100644 index e8f43819894..00000000000 --- a/Modules/Compatibility/Deprecated/wrapping/itkImageTransformer.wrap +++ /dev/null @@ -1,9 +0,0 @@ -itk_wrap_class("itk::ImageTransformer" POINTER) -itk_wrap_image_filter("${WRAP_ITK_ALL_TYPES}" 1) - -foreach(d ${ITK_WRAP_IMAGE_DIMS}) - foreach(type ${WRAP_ITK_SCALAR}) - itk_wrap_template("${ITKM_VI${type}${d}}" "${ITKT_VI${type}${d}}") - endforeach() -endforeach() -itk_end_wrap_class() diff --git a/Modules/Compatibility/Deprecated/wrapping/itkVectorCastImageFilter.wrap b/Modules/Compatibility/Deprecated/wrapping/itkVectorCastImageFilter.wrap deleted file mode 100644 index fff6d81d143..00000000000 --- a/Modules/Compatibility/Deprecated/wrapping/itkVectorCastImageFilter.wrap +++ /dev/null @@ -1,12 +0,0 @@ -itk_wrap_class("itk::VectorCastImageFilter" POINTER_WITH_SUPERCLASS) -# vector <-> vector -itk_wrap_image_filter_combinations("${WRAP_ITK_VECTOR}" "${WRAP_ITK_VECTOR}") - -# RGB <-> RGB -unique(rgb "RGBUC;${WRAP_ITK_RGB}") -itk_wrap_image_filter_combinations("${rgb}" "${rgb}") - -# vector <-> RGB -# itk_wrap_image_filter_combinations("${WRAP_ITK_VECTOR}" "${WRAP_ITK_RGB}" 3) -# itk_wrap_image_filter_combinations("${WRAP_ITK_RGB}" "${WRAP_ITK_VECTOR}" 3) -itk_end_wrap_class() diff --git a/Modules/Compatibility/Deprecated/wrapping/itkVectorResampleImageFilter.wrap b/Modules/Compatibility/Deprecated/wrapping/itkVectorResampleImageFilter.wrap deleted file mode 100644 index 7a136022d7e..00000000000 --- a/Modules/Compatibility/Deprecated/wrapping/itkVectorResampleImageFilter.wrap +++ /dev/null @@ -1,3 +0,0 @@ -itk_wrap_class("itk::VectorResampleImageFilter" POINTER) -itk_wrap_image_filter("${WRAP_ITK_VECTOR_REAL}" 2) -itk_end_wrap_class() diff --git a/Modules/Compatibility/README b/Modules/Compatibility/README index 68985cb0305..f3a58c20587 100644 --- a/Modules/Compatibility/README +++ b/Modules/Compatibility/README @@ -6,4 +6,4 @@ considered as Legacy code, and will be removed from the toolkit in future releases. Deprecated: Any code that provides a feature or function - that is no longer supported in ITKv5 + that is no longer supported in ITKv6 diff --git a/Modules/Core/Common/CMake/itkCheckHasFenvtStructMember.cxx b/Modules/Core/Common/CMake/itkCheckHasFenvtStructMember.cxx index 2c6d1c12984..ba052a42b47 100644 --- a/Modules/Core/Common/CMake/itkCheckHasFenvtStructMember.cxx +++ b/Modules/Core/Common/CMake/itkCheckHasFenvtStructMember.cxx @@ -21,15 +21,13 @@ int main() { - fenv_t fenv; #if defined(ITK_CHECK_FENV_T_CONTROL) - (void)sizeof(fenv.__control); + static_assert(sizeof(fenv_t().__control) > 0); #elif defined(ITK_CHECK_FENV_T_CONTROL_WORD) - (void)sizeof(fenv.__control_word); + static_assert(sizeof(fenv_t().__control_word) > 0); #elif defined(ITK_CHECK_FENV_T_CW) - (void)sizeof(fenv.__cw); + static_assert(sizeof(fenv_t().__cw) > 0); #else - (void)fenv; # error \ "Unknown fenv_t struct member test: Make sure to specify a compile definition of the form -DITK_CHECK_FENV_T_xxx" #endif diff --git a/Modules/Core/Common/CMake/itkCheckHasGNUAttributeAligned.cxx b/Modules/Core/Common/CMake/itkCheckHasGNUAttributeAligned.cxx index 3c79dbed09d..9b5ee3b8af6 100644 --- a/Modules/Core/Common/CMake/itkCheckHasGNUAttributeAligned.cxx +++ b/Modules/Core/Common/CMake/itkCheckHasGNUAttributeAligned.cxx @@ -77,7 +77,7 @@ main() using AlignedA = A __attribute__((aligned(64))); - return OnlyTrue<__alignof__(AlignedA) == 64>::Result && OnlyTrue<__alignof__(B) == 64>::Result; + return OnlyTrue < __alignof__(AlignedA) == 64 > ::Result && OnlyTrue < __alignof__(B) == 64 > ::Result; return 0; diff --git a/Modules/Core/Common/CMakeLists.txt b/Modules/Core/Common/CMakeLists.txt index 430fa57e88b..36c90a1a00b 100644 --- a/Modules/Core/Common/CMakeLists.txt +++ b/Modules/Core/Common/CMakeLists.txt @@ -11,13 +11,10 @@ test_big_endian(CMAKE_WORDS_BIGENDIAN) include(FindThreads) set(ITK_USE_WIN32_THREADS 0) set(ITK_USE_PTHREADS 0) -set(ITK_HP_PTHREADS 0) if(CMAKE_USE_WIN32_THREADS_INIT) set(ITK_USE_WIN32_THREADS 1) elseif(CMAKE_USE_PTHREADS_INIT AND NOT EMSCRIPTEN) set(ITK_USE_PTHREADS 1) -elseif(CMAKE_HP_PTHREADS_INIT) - set(ITK_HP_PTHREADS 1) endif() set(CMAKE_THREAD_LIBS "${CMAKE_THREAD_LIBS_INIT}" @@ -123,7 +120,7 @@ endif() # This is required on Mac OSX to avoid dynamic_cast failures across binaries. # See Change-Id: Ib4a6b8cafe8720c3a2a5b3e6ba833d11002978df for more information." option(ITK_TEMPLATE_VISIBILITY_DEFAULT - "Set symbol visibility to default for template class declarations. https://itk.org/Wiki/ITK/FAQ" + "Set symbol visibility to default for template class declarations. https://insightsoftwareconsortium.github.io/ITKWikiArchive/Wiki/ITK/FAQ" "${_template_visibility_init}") mark_as_advanced(ITK_TEMPLATE_VISIBILITY_DEFAULT) @@ -134,6 +131,10 @@ set(ITK_USE_TBB ${Module_ITKTBB}) configure_file(src/itkConfigure.h.in itkConfigure.h) configure_file(src/itkConfigurePrivate.h.in itkConfigurePrivate.h) +if(ITK_WRAP_PYTHON) + set(ITKCommon_SYSTEM_INCLUDE_DIRS "${Python3_INCLUDE_DIRS}") + set(ITKCommon_SYSTEM_LIBRARY_DIRS "${Python3_LIBRARY_DIRS}") +endif() set(ITKCommon_INCLUDE_DIRS ${ITKCommon_BINARY_DIR}) set(ITKCommon_LIBRARIES ITKCommon) diff --git a/Modules/Core/Common/ITKKWStyleOverwrite.txt b/Modules/Core/Common/ITKKWStyleOverwrite.txt index 3a32a99533e..927e6112ef0 100644 --- a/Modules/Core/Common/ITKKWStyleOverwrite.txt +++ b/Modules/Core/Common/ITKKWStyleOverwrite.txt @@ -1,3 +1,5 @@ +.*VNLSparseLUSolverTraits.* Namespace Disable +test/ClientTestLibrary.*\.h Namespace Disable test/.*\.cxx Namespace Disable test/.*\.cxx SemicolonSpace Disable itkAtomicIntDetail\.h InternalVariables Disable @@ -33,3 +35,15 @@ itkMultiThreaderBase.h Comments Disable itkSingleton\.cxx Namespace Disable itkExceptionObject\.h IfNDefDefine Disable itkConceptChecking\.h Template Disable +itkCommonEnums\.h Comments Disable +itkExtractImageFilter\.h Comments Disable +itkFloatingPointExceptions\.h Comments Disable +itkFrustumSpatialFunction\.h Comments Disable +itkGaussianDerivativeOperator\.h Comments Disable +itkLoggerBase\.h Comments Disable +itkLoggerThreadWrapper\.h Comments Disable +itkMultiThreaderBase\.h Comments Disable +itkObjectStore\.h Comments Disable +itkSpatialOrientation\.h Comments Disable +itkSymmetricEigenAnalysis\.h Comments Disable +itkPyCommand\.cxx Namespace Disable diff --git a/Modules/Core/Common/include/VNLIterativeSparseSolverTraits.h b/Modules/Core/Common/include/VNLIterativeSparseSolverTraits.h index b743c2ea95a..3f5d3ee5037 100644 --- a/Modules/Core/Common/include/VNLIterativeSparseSolverTraits.h +++ b/Modules/Core/Common/include/VNLIterativeSparseSolverTraits.h @@ -123,8 +123,8 @@ class VNLIterativeSparseSolverTraits static bool Solve(const MatrixType & iA, const VectorType & iBx, const VectorType & iBy, VectorType & oX, VectorType & oY) { - bool result1 = Solve(iA, iBx, oX); - bool result2 = Solve(iA, iBy, oY); + const bool result1 = Solve(iA, iBx, oX); + const bool result2 = Solve(iA, iBy, oY); return (result1 && result2); } diff --git a/Modules/Core/Common/include/itkAnatomicalOrientation.h b/Modules/Core/Common/include/itkAnatomicalOrientation.h new file mode 100644 index 00000000000..cf78b6cb4d6 --- /dev/null +++ b/Modules/Core/Common/include/itkAnatomicalOrientation.h @@ -0,0 +1,584 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * 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 + * + * https://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 itkAnatomicalOrientation_h +#define itkAnatomicalOrientation_h + +#include "ITKCommonExport.h" +#include "itkImageBase.h" +#ifndef ITK_FUTURE_LEGACY_REMOVE +# include "itkSpatialOrientation.h" +#endif +#include +#include + +namespace itk +{ + +/** \class AnatomicalOrientation + * \brief Representations of anatomical orientations and methods to convert between conventions. + * + * Defines patient specific anatomical names to the XYZ axes of a 3D image. + * + * A class instances holds the patient orientation stored as an enumerated type. Conversion to different representations + * such as strings and direction cosine matrices are supported. + * + * The use of unambiguous anatomical orientation names such as "RightToLeft" is preferred, where "Right" is the + * "from direction" and the negative direction of the coordinates, while "Left" is the "to direction" and the positive + * direction. The following is an unambiguous construction of an AnatomicalOrientation object: + * + * \code + * AnatomicalOrientation(AnatomicalOrientation::CoordinateEnum::RightToLeft, + * AnatomicalOrientation::CoordinateEnum::AnteriorToPosterior, + * AnatomicalOrientation::CoordinateEnum::InferiorToSuperior); + * \endcode + * + * + * \ingroup ITKCommon + */ +class ITKCommon_EXPORT AnatomicalOrientation +{ +public: + static constexpr unsigned int Dimension = 3; + using DirectionType = typename ImageBase::DirectionType; + static constexpr unsigned int ImageDimension = Dimension; + +#ifndef ITK_FUTURE_LEGACY_REMOVE + using LegacyOrientationType = SpatialOrientationEnums::ValidCoordinateOrientations; +#endif + + // Anatomical names for an axis. + // + enum class CoordinateEnum : uint8_t + { + UNKNOWN = 0, + RightToLeft = 2, ///< 0b0010 + LeftToRight = 3, + PosteriorToAnterior = 4, ///< to front - 0b0100 + AnteriorToPosterior = 5, ///< to back + InferiorToSuperior = 8, ///< to head - 0b1000 + SuperiorToInferior = 9, ///< to foot + }; + +protected: + enum class CoordinateMajornessTermsEnum : uint8_t + { + PrimaryMinor = 0, + SecondaryMinor = 8, + TertiaryMinor = 16 + }; + + template + static constexpr uint32_t m_OrientationValue = + (static_cast(VPrimary) << static_cast(CoordinateMajornessTermsEnum::PrimaryMinor)) + + (static_cast(VSecondary) << static_cast(CoordinateMajornessTermsEnum::SecondaryMinor)) + + (static_cast(VTertiary) << static_cast(CoordinateMajornessTermsEnum::TertiaryMinor)); + + CoordinateEnum + GetCoordinateTerm(CoordinateMajornessTermsEnum cmt) const; + +public: + // Enumerated acronyms based on the positive or "To" direction of the anatomical coordinates. + enum class PositiveEnum : uint32_t + + { + INVALID = 0, + + RIP = m_OrientationValue, + LIP = m_OrientationValue, + RSP = m_OrientationValue, + LSP = m_OrientationValue, + RIA = m_OrientationValue, + LIA = m_OrientationValue, + RSA = m_OrientationValue, + LSA = m_OrientationValue, + + IRP = m_OrientationValue, + ILP = m_OrientationValue, + SRP = m_OrientationValue, + SLP = m_OrientationValue, + IRA = m_OrientationValue, + ILA = m_OrientationValue, + SRA = m_OrientationValue, + SLA = m_OrientationValue, + + RPI = m_OrientationValue, + LPI = m_OrientationValue, + RAI = m_OrientationValue, + LAI = m_OrientationValue, + RPS = m_OrientationValue, + LPS = m_OrientationValue, + RAS = m_OrientationValue, + LAS = m_OrientationValue, + + PRI = m_OrientationValue, + PLI = m_OrientationValue, + ARI = m_OrientationValue, + ALI = m_OrientationValue, + PRS = m_OrientationValue, + PLS = m_OrientationValue, + ARS = m_OrientationValue, + ALS = m_OrientationValue, + + IPR = m_OrientationValue, + SPR = m_OrientationValue, + IAR = m_OrientationValue, + SAR = m_OrientationValue, + IPL = m_OrientationValue, + SPL = m_OrientationValue, + IAL = m_OrientationValue, + SAL = m_OrientationValue, + + PIR = m_OrientationValue, + PSR = m_OrientationValue, + AIR = m_OrientationValue, + ASR = m_OrientationValue, + PIL = m_OrientationValue, + PSL = m_OrientationValue, + AIL = m_OrientationValue, + ASL = m_OrientationValue + }; + + // Enumerated acronyms based on the negative or "From" direction of the anatomical coordinates. + enum class NegativeEnum : uint32_t + + { + INVALID = 0, + + RIP = m_OrientationValue, + LIP = m_OrientationValue, + RSP = m_OrientationValue, + LSP = m_OrientationValue, + RIA = m_OrientationValue, + LIA = m_OrientationValue, + RSA = m_OrientationValue, + LSA = m_OrientationValue, + + IRP = m_OrientationValue, + ILP = m_OrientationValue, + SRP = m_OrientationValue, + SLP = m_OrientationValue, + IRA = m_OrientationValue, + ILA = m_OrientationValue, + SRA = m_OrientationValue, + SLA = m_OrientationValue, + + RPI = m_OrientationValue, + LPI = m_OrientationValue, + RAI = m_OrientationValue, + LAI = m_OrientationValue, + RPS = m_OrientationValue, + LPS = m_OrientationValue, + RAS = m_OrientationValue, + LAS = m_OrientationValue, + + PRI = m_OrientationValue, + PLI = m_OrientationValue, + ARI = m_OrientationValue, + ALI = m_OrientationValue, + PRS = m_OrientationValue, + PLS = m_OrientationValue, + ARS = m_OrientationValue, + ALS = m_OrientationValue, + + IPR = m_OrientationValue, + SPR = m_OrientationValue, + IAR = m_OrientationValue, + SAR = m_OrientationValue, + IPL = m_OrientationValue, + SPL = m_OrientationValue, + IAL = m_OrientationValue, + SAL = m_OrientationValue, + + PIR = m_OrientationValue, + PSR = m_OrientationValue, + AIR = m_OrientationValue, + ASR = m_OrientationValue, + PIL = m_OrientationValue, + PSL = m_OrientationValue, + AIL = m_OrientationValue, + ASL = m_OrientationValue + + }; + + + /** \brief Initialize with CoordinateEnum's from separate axes. + * + * If multiple CoordinateEnums are from the same axes then the Orientation value is INVALID. + */ + constexpr AnatomicalOrientation(CoordinateEnum primary, CoordinateEnum secondary, CoordinateEnum tertiary) + : m_Value( + SameOrientationAxes(primary, secondary) || SameOrientationAxes(primary, tertiary) || + SameOrientationAxes(secondary, tertiary) + ? PositiveEnum::INVALID + : static_cast( + (static_cast(primary) << static_cast(CoordinateMajornessTermsEnum::PrimaryMinor)) + + (static_cast(secondary) << static_cast(CoordinateMajornessTermsEnum::SecondaryMinor)) + + (static_cast(tertiary) << static_cast(CoordinateMajornessTermsEnum::TertiaryMinor)))) + {} + + + constexpr AnatomicalOrientation(PositiveEnum toOrientation) + : m_Value(toOrientation) + {} + + + constexpr AnatomicalOrientation(NegativeEnum fromOrientation) + : m_Value(PositiveEnum(static_cast(fromOrientation))) + {} + +#ifndef ITK_FUTURE_LEGACY_REMOVE + /** \brief Conversion from Legacy SpatialOrientation + * + * @param legacyOrientation + */ +# if defined(ITK_LEGACY_REMOVE) && !defined(ITK_LEGACY_SILENT) && !defined(ITK_WRAPPING) + [[deprecated("Use the AnatomicalOrientation::FromEnum type instead.")]] +# endif + AnatomicalOrientation(LegacyOrientationType legacyOrientation); +#endif + + /** Conversion for a Direction Cosine Matrix to the closest anatomical orientation. Any partial axis rotations are + * rounded to the nearest axis, and lost in this conversion. + */ + explicit AnatomicalOrientation(const DirectionType & d) + : m_Value(ConvertDirectionToPositiveEnum(d)) + {} + + /** Creates a AnatomicalOrientation from a string with the PositiveEnum encoding. The string is case-insensitive. If + * the string is not a valid encoding then the orientation is set to INVALID. + */ + static AnatomicalOrientation + CreateFromPositiveStringEncoding(std::string str); + + // Same as CreateFromPositiveStringEncoding but for the NegativeEnum encoding. + static AnatomicalOrientation + CreateFromNegativeStringEncoding(std::string str); + + operator PositiveEnum() const { return m_Value; } + + /** Returns the PositiveEnum encoding as a string. The string is always upper case. */ + std::string + GetAsPositiveStringEncoding() const; + + /** Returns the NegativeEnum encoding as a string. The string is always upper case. */ + std::string + GetAsNegativeStringEncoding() const; + + /** An involution to convert between "positive" and "negative" single character encoding strings. + * + * For example the string "RAS" is converted to "LPI" and vice versa. + * + * The input maybe upper or lower case, while the output is always upper case. + * There is no check that the input is a valid encoding. + * + * */ + static std::string + ConvertStringEncoding(std::string str); + + /** \brief Return the direction cosine matrix for the orientation. */ + DirectionType + GetAsDirection() const + { + return ConvertPositiveEnumToDirection(m_Value); + } + + PositiveEnum + GetAsPositiveOrientation() const + { + return m_Value; + } + + NegativeEnum + GetAsNegativeOrientation() const + { + return NegativeEnum(uint32_t(this->m_Value)); + } + + CoordinateEnum + GetPrimaryTerm() const + { + return GetCoordinateTerm(CoordinateMajornessTermsEnum::PrimaryMinor); + } + + CoordinateEnum + GetSecondaryTerm() const + { + return GetCoordinateTerm(CoordinateMajornessTermsEnum::SecondaryMinor); + } + + CoordinateEnum + GetTertiaryTerm() const + { + return GetCoordinateTerm(CoordinateMajornessTermsEnum::TertiaryMinor); + } + + std::array + GetTerms() const + { + return { GetPrimaryTerm(), GetSecondaryTerm(), GetTertiaryTerm() }; + } + + static constexpr bool + SameOrientationAxes(CoordinateEnum a, CoordinateEnum b) + { + const uint8_t AxisField = ~1; // mask the lowest bit + return (static_cast(a) & AxisField) == (static_cast(b) & AxisField); + } + + + friend ITKCommon_EXPORT std::ostream & + operator<<(std::ostream & out, PositiveEnum value); + +protected: + /** \brief Return the direction cosine matrix for a orientation. */ + static DirectionType ConvertPositiveEnumToDirection(PositiveEnum); + + + /** \brief Return the closest orientation for a direction cosine matrix. */ + static PositiveEnum + ConvertDirectionToPositiveEnum(const DirectionType & dir); + + + /** \brief Return the global instance of the map from orientation enum to strings. + * + * The implementation uses a function static local variable so the global is created only if needed, only once. + */ + static const std::map & + GetCodeToString(); + + /** \brief Return the global instance of the map from string to orientation enum. + */ + static const std::map & + GetStringToCode(); + + PositiveEnum m_Value; +}; + +/** Outputs unambiguous anatomical orientation names such as "right-to-left". */ +ITKCommon_EXPORT std::ostream & + operator<<(std::ostream & out, typename AnatomicalOrientation::CoordinateEnum value); + +/** Outputs the PositiveEnum encoding as a string such as "LPS". */ +ITKCommon_EXPORT std::ostream & + operator<<(std::ostream & out, typename AnatomicalOrientation::PositiveEnum value); + + +/** Outputs the NegativeEnum encoding as a string such as "RAI" */ +ITKCommon_EXPORT std::ostream & + operator<<(std::ostream & out, typename AnatomicalOrientation::NegativeEnum value); + +ITKCommon_EXPORT std::ostream & + operator<<(std::ostream & out, const AnatomicalOrientation & orientation); + + +} // end namespace itk + + +#endif diff --git a/Modules/Core/Common/include/itkAnnulusOperator.h b/Modules/Core/Common/include/itkAnnulusOperator.h index 4c1888f7ab5..f4332ce7f01 100644 --- a/Modules/Core/Common/include/itkAnnulusOperator.h +++ b/Modules/Core/Common/include/itkAnnulusOperator.h @@ -91,6 +91,7 @@ class ITK_TEMPLATE_EXPORT AnnulusOperator : public NeighborhoodOperatorSetNormalize(false); } - + /** @ITKEndGrouping */ /** If Normalize is on, you define the annulus to have a bright * center or a dark center. */ + /** @ITKStartGrouping */ void SetBrightCenter(bool b) { @@ -174,11 +179,12 @@ class ITK_TEMPLATE_EXPORT AnnulusOperator : public NeighborhoodOperatorSetBrightCenter(false); } - + /** @ITKEndGrouping */ /** If Normalize is off, the interior to annulus, the * annulus (region between the two circles), and the region exterior to the * annulus to be defined manually. Defaults are 0, 1, 0 * respectively. */ + /** @ITKStartGrouping */ void SetInteriorValue(TPixel v) { @@ -209,7 +215,7 @@ class ITK_TEMPLATE_EXPORT AnnulusOperator : public NeighborhoodOperator void AnnulusOperator::CreateOperator() { - CoefficientVector coefficients; - - coefficients = this->GenerateCoefficients(); + const CoefficientVector coefficients = this->GenerateCoefficients(); this->Fill(coefficients); } @@ -61,11 +59,13 @@ auto AnnulusOperator::GenerateCoefficients() -> CoefficientVector { // Determine the initial kernel values... - double interiorV, annulusV, exteriorV; + double interiorV; + double annulusV; + double exteriorV; if (m_Normalize) { - double bright = (m_BrightCenter ? 1.0 : -1.0); + const double bright = (m_BrightCenter ? 1.0 : -1.0); // Initial values for a normalized kernel interiorV = bright; @@ -81,14 +81,16 @@ AnnulusOperator::GenerateCoefficients() -> Coeff } // Compute the size of the kernel in pixels - SizeType r; - unsigned int i, j; - double outerRadius = m_InnerRadius + m_Thickness; - for (i = 0; i < TDimension; ++i) { - r[i] = Math::Ceil(outerRadius / m_Spacing[i]); + SizeType r; + + const double outerRadius = m_InnerRadius + m_Thickness; + for (unsigned int i = 0; i < TDimension; ++i) + { + r[i] = Math::Ceil(outerRadius / m_Spacing[i]); + } + this->SetRadius(r); } - this->SetRadius(r); // Use a couple of sphere spatial functions... using SphereType = SphereSpatialFunction; @@ -111,13 +113,13 @@ AnnulusOperator::GenerateCoefficients() -> Coeff OffsetType offset; typename SphereType::InputType point; - for (i = 0; i < w; ++i) + for (unsigned int i = 0; i < w; ++i) { // get the offset from the center pixel offset = this->GetOffset(i); // convert to a position - for (j = 0; j < TDimension; ++j) + for (unsigned int j = 0; j < TDimension; ++j) { point[j] = m_Spacing[j] * offset[j]; } @@ -158,22 +160,22 @@ AnnulusOperator::GenerateCoefficients() -> Coeff { // Calculate the mean and standard deviation of kernel values NOT // the exterior - auto num = static_cast(countNotExterior); - double mean = sumNotExterior / num; - double var = (sumNotExteriorSq - (sumNotExterior * sumNotExterior / num)) / (num - 1.0); - double std = std::sqrt(var); + auto num = static_cast(countNotExterior); + const double mean = sumNotExterior / num; + const double var = (sumNotExteriorSq - (sumNotExterior * sumNotExterior / num)) / (num - 1.0); + const double std = std::sqrt(var); // convert std to a scaling factor k such that // // || (coeffP - mean) / k || = 1.0 // - double k = std * std::sqrt(num - 1.0); + const 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 // kernel to have mean zero and norm 1 AND forces the region // outside the annulus to have no influence. - for (i = 0; i < w; ++i) + for (unsigned int i = 0; i < w; ++i) { // normalize the coefficient if it is inside the outer circle // (exterior to outer circle is already zero) diff --git a/Modules/Core/Common/include/itkArray.h b/Modules/Core/Common/include/itkArray.h index 9a1d1f1da78..cb383aa4e00 100644 --- a/Modules/Core/Common/include/itkArray.h +++ b/Modules/Core/Common/include/itkArray.h @@ -78,22 +78,25 @@ class ITK_TEMPLATE_EXPORT Array : public vnl_vector * the array does not manage the memory of the buffer. It merely points to * that location and it is the user's responsibility to delete it. * If "LetArrayManageMemory" is true, then this class will free the - * memory when this object is destroyed. */ - Array(ValueType * datain, SizeValueType sz, bool LetArrayManageMemory = false); + * memory when this object is destroyed. + * \note This constructor supports class template argument deduction (CTAD). */ + Array(TValue * datain, SizeValueType sz, bool LetArrayManageMemory = false); #if defined(ITK_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); + * manages memory. + * \note This constructor supports class template argument deduction (CTAD). */ + Array(const TValue * datain, SizeValueType sz); #else // defined ( ITK_LEGACY_REMOVE ) /** Constructor that initializes array with contents from a user supplied * buffer. The pointer to the buffer and the length is specified. The array * does a deep copy of the const pointer data, so the array class also - * manages memory. The 3rd argument is only for backward compatibility. */ - Array(const ValueType * datain, SizeValueType sz, bool LetArrayManageMemory = false); + * manages memory. The 3rd argument is only for backward compatibility. + * \note This constructor supports class template argument deduction (CTAD). */ + Array(const TValue * datain, SizeValueType sz, bool LetArrayManageMemory = false); #endif /** Constructor to initialize an array from another of any data type */ @@ -109,7 +112,7 @@ class ITK_TEMPLATE_EXPORT Array : public vnl_vector /** Set all the elements of the array to the specified value */ void - Fill(TValue const & v) + Fill(const TValue & v) { this->fill(v); } @@ -122,6 +125,7 @@ class ITK_TEMPLATE_EXPORT Array : public vnl_vector operator=(const VnlVectorType & rhs); /** Return the number of elements in the Array */ + /** @ITKStartGrouping */ SizeValueType Size() const { @@ -132,7 +136,7 @@ class ITK_TEMPLATE_EXPORT Array : public vnl_vector { return static_cast(this->size()); } - + /** @ITKEndGrouping */ /** Get one element */ const TValue & GetElement(SizeValueType i) const @@ -196,7 +200,7 @@ class ITK_TEMPLATE_EXPORT Array : public vnl_vector #endif void - Swap(Array & other) + Swap(Array & other) noexcept { using std::swap; this->VnlVectorType::swap(other); @@ -208,6 +212,10 @@ class ITK_TEMPLATE_EXPORT Array : public vnl_vector bool m_LetArrayManageMemory{ true }; }; +// Deduction guide to avoid compiler warnings (-wctad-maybe-unsupported) when using class template argument deduction. +template +Array(TValue *, typename vnl_vector::size_type, bool) -> Array; + template std::ostream & operator<<(std::ostream & os, const Array & arr) @@ -229,14 +237,14 @@ operator<<(std::ostream & os, const Array & arr) // declaration of specialization template <> -ITKCommon_EXPORT std::ostream & operator<<(std::ostream & os, const Array & arr); +ITKCommon_EXPORT std::ostream & operator<< (std::ostream & os, const Array & arr); template <> -ITKCommon_EXPORT std::ostream & operator<<(std::ostream & os, const Array & arr); +ITKCommon_EXPORT std::ostream & operator<< (std::ostream & os, const Array & arr); template inline void -swap(Array & a, Array & b) +swap(Array & a, Array & b) noexcept { a.Swap(b); } diff --git a/Modules/Core/Common/include/itkArray2D.h b/Modules/Core/Common/include/itkArray2D.h index 44f0089bb6e..91adcc9cfce 100644 --- a/Modules/Core/Common/include/itkArray2D.h +++ b/Modules/Core/Common/include/itkArray2D.h @@ -58,21 +58,41 @@ class ITK_TEMPLATE_EXPORT Array2D : public vnl_matrix Array2D(unsigned int numberOfRows, unsigned int numberOfCols, const TValue & initialValue); /** Copy-constructor. */ - Array2D(const Self & array); + Array2D(const Self &) = default; + + /** Move-constructor. + * \note This move-constructor is `noexcept`, even while the move-constructor of its base class (`vnl_matrix`) is not + * `noexcept`, because unlike `vnl_matrix`, `Array2D` always manages its own memory. */ + Array2D(Self && array) noexcept + : vnl_matrix(std::move(array)) + { + // Note: GCC <= 9.5 does not yet support "defaulting" (`= default`) this `noexcept` move-constructor. + } /** Converting constructor. Implicitly converts the specified matrix to an Array2D. */ Array2D(const VnlMatrixType & matrix); /** Copy-assignment operator. */ Self & - operator=(const Self & array); + operator=(const Self &) = default; + + /** Move-assignment operator. + * \note This move-assignment operator is `noexcept`, even while the move-assignment operator of its base class + * (`vnl_matrix`) is not `noexcept`, because unlike `vnl_matrix`, `Array2D` always manages its own memory. */ + Self & + operator=(Self && array) noexcept + { + // Note: GCC <= 9.5 does not yet support "defaulting" (`= default`) this `noexcept` move-assignment operator. + this->VnlMatrixType::operator=(std::move(array)); + return *this; + } /** Assigns the specified matrix to an Array2D. */ Self & operator=(const VnlMatrixType & matrix); void - Fill(TValue const & v) + Fill(const TValue & v) { this->fill(v); } diff --git a/Modules/Core/Common/include/itkArray2D.hxx b/Modules/Core/Common/include/itkArray2D.hxx index 74e268f666f..77c9232ed30 100644 --- a/Modules/Core/Common/include/itkArray2D.hxx +++ b/Modules/Core/Common/include/itkArray2D.hxx @@ -37,19 +37,6 @@ Array2D::Array2D(const VnlMatrixType & matrix) : vnl_matrix(matrix) {} -template -Array2D::Array2D(const Self & array) - : vnl_matrix(array) -{} - -template -Array2D & -Array2D::operator=(const Self & array) -{ - this->VnlMatrixType::operator=(array); - return *this; -} - template Array2D & Array2D::operator=(const VnlMatrixType & matrix) diff --git a/Modules/Core/Common/include/itkAtanRegularizedHeavisideStepFunction.h b/Modules/Core/Common/include/itkAtanRegularizedHeavisideStepFunction.h index 24276fd8a52..7c52e1d8b6a 100644 --- a/Modules/Core/Common/include/itkAtanRegularizedHeavisideStepFunction.h +++ b/Modules/Core/Common/include/itkAtanRegularizedHeavisideStepFunction.h @@ -28,21 +28,9 @@ namespace itk * * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. * - * This code was taken from the Insight Journal paper: - * - * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" - * https://www.insight-journal.org/browse/publication/642 - * - * That is based on the papers: - * - * "Level Set Segmentation: Active Contours without edge" - * https://www.insight-journal.org/browse/publication/322 - * - * and - * - * "Level set segmentation using coupled active surfaces" - * https://www.insight-journal.org/browse/publication/323 - * + * This code was taken from the Insight Journal paper \cite Mosaliganti_2009_c + * that is based on the papers \cite Mosaliganti_2009_a and + * \cite Mosaliganti_2009_b. * * \ingroup ITKCommon */ diff --git a/Modules/Core/Common/include/itkAutoPointer.h b/Modules/Core/Common/include/itkAutoPointer.h index aa3abf945ee..36042339da4 100644 --- a/Modules/Core/Common/include/itkAutoPointer.h +++ b/Modules/Core/Common/include/itkAutoPointer.h @@ -73,7 +73,11 @@ class AutoPointer ~AutoPointer() { this->Reset(); } /** Overload operator ->. */ - ObjectType * operator->() const { return m_Pointer; } + ObjectType * + operator->() const + { + return m_Pointer; + } /** Clear the AutoPointer. If it had a pointer the object is deleted and the pointer is set to null. */ @@ -156,7 +160,7 @@ class AutoPointer bool operator==(const AutoPointer & r) const { - return (void *)m_Pointer == (void *)r.m_Pointer; + return m_Pointer == r.m_Pointer; } ITK_UNEQUAL_OPERATOR_MEMBER_FUNCTION(Self); @@ -165,28 +169,28 @@ class AutoPointer bool operator<(const AutoPointer & r) const { - return (void *)m_Pointer < (void *)r.m_Pointer; + return m_Pointer < r.m_Pointer; } /** Comparison of pointers. Greater than comparison. */ bool operator>(const AutoPointer & r) const { - return (void *)m_Pointer > (void *)r.m_Pointer; + return m_Pointer > r.m_Pointer; } /** Comparison of pointers. Less than or equal to comparison. */ bool operator<=(const AutoPointer & r) const { - return (void *)m_Pointer <= (void *)r.m_Pointer; + return m_Pointer <= r.m_Pointer; } /** Comparison of pointers. Greater than or equal to comparison. */ bool operator>=(const AutoPointer & r) const { - return (void *)m_Pointer >= (void *)r.m_Pointer; + return m_Pointer >= r.m_Pointer; } /** Overload operator assignment. */ @@ -250,6 +254,7 @@ TransferAutoPointer(TAutoPointerBase & pa, TAutoPointerDerived & pb) pb.ReleaseOwnership(); // pb Release Ownership and clears } } + } // end namespace itk #endif diff --git a/Modules/Core/Common/include/itkAutoPointerDataObjectDecorator.h b/Modules/Core/Common/include/itkAutoPointerDataObjectDecorator.h index e4d005687bc..ac1ab35bbe7 100644 --- a/Modules/Core/Common/include/itkAutoPointerDataObjectDecorator.h +++ b/Modules/Core/Common/include/itkAutoPointerDataObjectDecorator.h @@ -84,6 +84,7 @@ class ITK_TEMPLATE_EXPORT AutoPointerDataObjectDecorator : public DataObject Set(T * val); /** Get the contained object */ + /** @ITKStartGrouping */ virtual T * Get() { @@ -94,7 +95,7 @@ class ITK_TEMPLATE_EXPORT AutoPointerDataObjectDecorator : public DataObject { return m_Component.get(); } - + /** @ITKEndGrouping */ protected: AutoPointerDataObjectDecorator() = default; ~AutoPointerDataObjectDecorator() override = default; diff --git a/Modules/Core/Common/include/itkBSplineDerivativeKernelFunction.h b/Modules/Core/Common/include/itkBSplineDerivativeKernelFunction.h index 4da2b65cb10..91890fa63fb 100644 --- a/Modules/Core/Common/include/itkBSplineDerivativeKernelFunction.h +++ b/Modules/Core/Common/include/itkBSplineDerivativeKernelFunction.h @@ -95,21 +95,21 @@ class ITK_TEMPLATE_EXPORT BSplineDerivativeKernelFunction : public KernelFunctio {}; /** Evaluate the function: zeroth order spline. */ - inline static TRealValueType + static inline TRealValueType Evaluate(const Dispatch<0> &, const TRealValueType & itkNotUsed(u)) { return TRealValueType{ 0.0 }; } /** Evaluate the function: first order spline */ - inline static TRealValueType + static inline TRealValueType Evaluate(const Dispatch<1> &, const TRealValueType & u) { if (Math::ExactlyEquals(u, TRealValueType{ -1.0 })) { return TRealValueType{ 0.5 }; } - else if ((u > TRealValueType{ -1.0 }) && (u < TRealValueType{ 0.0 })) + if ((u > TRealValueType{ -1.0 }) && (u < TRealValueType{ 0.0 })) { return TRealValueType{ 1.0 }; } @@ -132,14 +132,14 @@ class ITK_TEMPLATE_EXPORT BSplineDerivativeKernelFunction : public KernelFunctio } /** Evaluate the function: second order spline. */ - inline static TRealValueType + static inline TRealValueType Evaluate(const Dispatch<2> &, const TRealValueType & u) { if ((u > TRealValueType{ -0.5 }) && (u < TRealValueType{ 0.5 })) { return (TRealValueType{ -2.0 } * u); } - else if ((u >= TRealValueType{ 0.5 }) && (u < TRealValueType{ 1.5 })) + if ((u >= TRealValueType{ 0.5 }) && (u < TRealValueType{ 1.5 })) { return (TRealValueType{ -1.5 } + u); } @@ -154,14 +154,14 @@ class ITK_TEMPLATE_EXPORT BSplineDerivativeKernelFunction : public KernelFunctio } /** Evaluate the function: third order spline. */ - inline static TRealValueType + static inline TRealValueType Evaluate(const Dispatch<3> &, const TRealValueType & u) { if ((u >= TRealValueType{ 0.0 }) && (u < TRealValueType{ 1.0 })) { return (TRealValueType{ -2.0 } * u + TRealValueType{ 1.5 } * u * u); } - else if ((u > TRealValueType{ -1.0 }) && (u < TRealValueType{ 0.0 })) + if ((u > TRealValueType{ -1.0 }) && (u < TRealValueType{ 0.0 })) { return (TRealValueType{ -2.0 } * u - TRealValueType{ 1.5 } * u * u); } @@ -180,12 +180,13 @@ class ITK_TEMPLATE_EXPORT BSplineDerivativeKernelFunction : public KernelFunctio } /** Evaluate the function: unimplemented spline order */ - inline static TRealValueType + static inline TRealValueType Evaluate(const DispatchBase &, const TRealValueType &) { itkGenericExceptionMacro("Evaluate not implemented for spline order " << SplineOrder); } }; + } // end namespace itk #endif diff --git a/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.h b/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.h index 6918027e4fd..7b4cff4571a 100644 --- a/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.h +++ b/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.h @@ -44,9 +44,9 @@ namespace itk * \ingroup Functions ImageInterpolators * \ingroup ITKCommon */ -template +template class ITK_TEMPLATE_EXPORT BSplineInterpolationWeightFunction - : public FunctionBase, + : public FunctionBase, FixedArray> { public: @@ -54,7 +54,7 @@ class ITK_TEMPLATE_EXPORT BSplineInterpolationWeightFunction /** Standard class type aliases. */ using Self = BSplineInterpolationWeightFunction; - using Superclass = FunctionBase, + using Superclass = FunctionBase, FixedArray>; using Pointer = SmartPointer; @@ -83,7 +83,7 @@ class ITK_TEMPLATE_EXPORT BSplineInterpolationWeightFunction using SizeType = Size; /** ContinuousIndex type alias support. */ - using ContinuousIndexType = ContinuousIndex; + using ContinuousIndexType = ContinuousIndex; /** The support region size: a hypercube of length SplineOrder + 1 */ static constexpr SizeType SupportSize{ SizeType::Filled(VSplineOrder + 1) }; @@ -106,31 +106,23 @@ class ITK_TEMPLATE_EXPORT BSplineInterpolationWeightFunction #if !defined(ITK_LEGACY_REMOVE) /** Get support region size. */ - itkLegacyMacro(SizeType GetSupportSize() const) { return Self::SupportSize; }; + itkLegacyMacro(SizeType GetSupportSize() const) + { + return Self::SupportSize; + } /** Get number of weights. */ - itkLegacyMacro(unsigned int GetNumberOfWeights() const) { return Self::NumberOfWeights; } + itkLegacyMacro(unsigned int GetNumberOfWeights() const) + { + return Self::NumberOfWeights; + } #endif protected: BSplineInterpolationWeightFunction() = default; ~BSplineInterpolationWeightFunction() override = default; - -private: - /** Lookup table type. */ - using TableType = FixedArray; - - /** Table mapping linear offset to indices. */ - const TableType m_OffsetToIndexTable{ [] { - TableType table; - // Note: Copied the constexpr value `SupportSize` to a local variable, to prevent a GCC - // (Ubuntu 7.5.0-3ubuntu1~18.04) link error, "undefined reference to `SupportSize`", and Clang - // (Mac10.13-AppleClang-dbg-x86_64-static) "Undefined symbols for architecture x86_64". - const auto supportSize = SupportSize; - std::copy_n(ZeroBasedIndexRange(supportSize).cbegin(), NumberOfWeights, table.begin()); - return table; - }() }; }; + } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.hxx b/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.hxx index 59fc3c8f480..03934806ea5 100644 --- a/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.hxx +++ b/Modules/Core/Common/include/itkBSplineInterpolationWeightFunction.hxx @@ -26,9 +26,9 @@ namespace itk { /** Compute weights for interpolation at continuous index position */ -template +template auto -BSplineInterpolationWeightFunction::Evaluate( +BSplineInterpolationWeightFunction::Evaluate( const ContinuousIndexType & index) const -> WeightsType { WeightsType weights; @@ -40,17 +40,27 @@ BSplineInterpolationWeightFunction::Ev } /** Compute weights for interpolation at continuous index position */ -template +template void -BSplineInterpolationWeightFunction::Evaluate( +BSplineInterpolationWeightFunction::Evaluate( const ContinuousIndexType & index, WeightsType & weights, IndexType & startIndex) const { - unsigned int j, k; + static constexpr auto offsetToIndexTable = [] { + FixedArray table{}; + auto indexIterator = ZeroBasedIndexRange(SupportSize).cbegin(); + + for (size_t i{}; i < NumberOfWeights; ++i) + { + table[i] = *indexIterator; + ++indexIterator; + } + return table; + }(); // Find the starting index of the support region - for (j = 0; j < SpaceDimension; ++j) + for (unsigned int j = 0; j < SpaceDimension; ++j) { // Note that the expression passed to Math::Floor is adapted to work around // a compiler bug which caused endless compilations (apparently), by @@ -60,24 +70,24 @@ BSplineInterpolationWeightFunction::Ev // Compute the weights Matrix weights1D; - for (j = 0; j < SpaceDimension; ++j) + for (unsigned int j = 0; j < SpaceDimension; ++j) { double x = index[j] - static_cast(startIndex[j]); - for (k = 0; k <= SplineOrder; ++k) + for (unsigned int k = 0; k <= SplineOrder; ++k) { weights1D[j][k] = BSplineKernelFunction::FastEvaluate(x); x -= 1.0; } } - for (k = 0; k < Self::NumberOfWeights; ++k) + for (unsigned int k = 0; k < Self::NumberOfWeights; ++k) { weights[k] = 1.0; - for (j = 0; j < SpaceDimension; ++j) + for (unsigned int j = 0; j < SpaceDimension; ++j) { - weights[k] *= weights1D[j][m_OffsetToIndexTable[k][j]]; + weights[k] *= weights1D[j][offsetToIndexTable[k][j]]; } } } diff --git a/Modules/Core/Common/include/itkBSplineKernelFunction.h b/Modules/Core/Common/include/itkBSplineKernelFunction.h index 63dbd17b2ae..094d5d85a8a 100644 --- a/Modules/Core/Common/include/itkBSplineKernelFunction.h +++ b/Modules/Core/Common/include/itkBSplineKernelFunction.h @@ -95,7 +95,7 @@ class ITK_TEMPLATE_EXPORT BSplineKernelFunction : public KernelFunctionBase &, const TRealValueType & u) { const TRealValueType absValue = itk::Math::abs(u); @@ -103,7 +103,7 @@ class ITK_TEMPLATE_EXPORT BSplineKernelFunction : public KernelFunctionBase &, const TRealValueType & u) { const TRealValueType absValue = itk::Math::abs(u); @@ -122,14 +122,12 @@ class ITK_TEMPLATE_EXPORT BSplineKernelFunction : public KernelFunctionBase &, const TRealValueType & u) { const TRealValueType absValue = itk::Math::abs(u); @@ -138,7 +136,7 @@ class ITK_TEMPLATE_EXPORT BSplineKernelFunction : public KernelFunctionBase &, const TRealValueType & u) { const TRealValueType absValue = itk::Math::abs(u); @@ -162,7 +160,7 @@ class ITK_TEMPLATE_EXPORT BSplineKernelFunction : public KernelFunctionBaseFillCenteredDirectional(coeff); } }; + } // namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.h b/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.h index 036b6b913bd..01b01a4e3f1 100644 --- a/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.h +++ b/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.h @@ -71,17 +71,20 @@ class ITK_TEMPLATE_EXPORT BinaryThresholdSpatialFunction using FunctionOutputType = typename TFunction::OutputType; /** Set/Get the lower threshold. */ + /** @ITKStartGrouping */ itkSetMacro(LowerThreshold, FunctionOutputType); itkGetConstReferenceMacro(LowerThreshold, FunctionOutputType); - + /** @ITKEndGrouping */ /** Set/Get the upper threshold. */ + /** @ITKStartGrouping */ itkSetMacro(UpperThreshold, FunctionOutputType); itkGetConstReferenceMacro(UpperThreshold, FunctionOutputType); - + /** @ITKEndGrouping */ /** Set/Get the underlying function. */ + /** @ITKStartGrouping */ itkSetObjectMacro(Function, FunctionType); itkGetModifiableObjectMacro(Function, FunctionType); - + /** @ITKEndGrouping */ /** Evaluate the function at a given position. */ OutputType Evaluate(const InputType & point) const override; diff --git a/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.hxx b/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.hxx index 5eef8a3a850..cdae77134ed 100644 --- a/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkBinaryThresholdSpatialFunction.hxx @@ -42,7 +42,7 @@ template auto BinaryThresholdSpatialFunction::Evaluate(const InputType & point) const -> OutputType { - FunctionOutputType value = m_Function->Evaluate(point); + const FunctionOutputType value = m_Function->Evaluate(point); if (m_LowerThreshold <= value && value <= m_UpperThreshold) { diff --git a/Modules/Core/Common/include/itkBoolean.h b/Modules/Core/Common/include/itkBoolean.h index 9fdb636a0ed..055efc9f19d 100644 --- a/Modules/Core/Common/include/itkBoolean.h +++ b/Modules/Core/Common/include/itkBoolean.h @@ -47,7 +47,11 @@ class Boolean {} /** Supports implicit conversion to `bool`. */ - constexpr operator bool() const { return m_Value; } + constexpr + operator bool() const + { + return m_Value; + } private: bool m_Value = false; diff --git a/Modules/Core/Common/include/itkBoundingBox.h b/Modules/Core/Common/include/itkBoundingBox.h index 4519ebf7a0e..ffcffc93200 100644 --- a/Modules/Core/Common/include/itkBoundingBox.h +++ b/Modules/Core/Common/include/itkBoundingBox.h @@ -55,7 +55,7 @@ namespace itk * Template parameters for BoundingBox: * * \tparam TPointIdentifier The type used to access a particular point (i.e., a point's id) - * \tparam TCoordRep Numerical type with which to represent each coordinate value. + * \tparam TCoordinate Numerical type with which to represent each coordinate value. * \tparam VPointDimension Geometric dimension of space. * * \ingroup DataRepresentation @@ -65,8 +65,8 @@ namespace itk */ template >> + typename TCoordinate = float, + typename TPointsContainer = VectorContainer>> class ITK_TEMPLATE_EXPORT BoundingBox : public Object { public: @@ -89,14 +89,17 @@ class ITK_TEMPLATE_EXPORT BoundingBox : public Object /** Hold on to the type information specified by the template parameters. */ using PointIdentifier = TPointIdentifier; - using CoordinateType = TCoordRep; - using CoordRepType = CoordinateType; + using CoordinateType = TCoordinate; +#ifndef ITK_FUTURE_LEGACY_REMOVE + using CoordRepType ITK_FUTURE_DEPRECATED( + "ITK 6 discourages using `CoordRepType`. Please use `CoordinateType` instead!") = CoordinateType; +#endif using PointsContainer = TPointsContainer; using PointsContainerPointer = typename PointsContainer::Pointer; using PointsContainerConstPointer = typename PointsContainer::ConstPointer; - using PointType = Point; - using BoundsArrayType = FixedArray; + using PointType = Point; + using BoundsArrayType = FixedArray; /** Hold on to the dimensions specified by the template parameters. */ static constexpr unsigned int PointDimension = VPointDimension; @@ -123,7 +126,7 @@ class ITK_TEMPLATE_EXPORT BoundingBox : public Object ComputeCorners() const; /** Compute and return the corners of the bounding box */ - itkLegacyMacro(const PointsContainer * GetCorners()); + itkLegacyMacro(const PointsContainer * GetCorners();) /** Method that actually computes bounding box. */ bool @@ -173,7 +176,7 @@ class ITK_TEMPLATE_EXPORT BoundingBox : public Object /** Get the length squared of the diagonal of the bounding box. * Returns zero if bounding box cannot be computed. Note that the * Accumulate type is used to represent the length. */ - using AccumulateType = typename NumericTraits::AccumulateType; + using AccumulateType = typename NumericTraits::AccumulateType; AccumulateType GetDiagonalLength2() const; diff --git a/Modules/Core/Common/include/itkBoundingBox.hxx b/Modules/Core/Common/include/itkBoundingBox.hxx index d14c95b3fcb..5766bf876d6 100644 --- a/Modules/Core/Common/include/itkBoundingBox.hxx +++ b/Modules/Core/Common/include/itkBoundingBox.hxx @@ -29,16 +29,17 @@ #define itkBoundingBox_hxx #include // For max. +#include namespace itk { /** * Print out the bounding box. */ -template +template void -BoundingBox::PrintSelf(std::ostream & os, - Indent indent) const +BoundingBox::PrintSelf(std::ostream & os, + Indent indent) const { Superclass::PrintSelf(os, indent); @@ -53,9 +54,9 @@ BoundingBox::Pri /** * Access routine to set the points container. */ -template +template void -BoundingBox::SetPoints(const PointsContainer * points) +BoundingBox::SetPoints(const PointsContainer * points) { itkDebugMacro("setting Points container to " << points); if (m_PointsContainer != points) @@ -66,9 +67,9 @@ BoundingBox::Set } /** Access routine to get the points container. */ -template +template auto -BoundingBox::GetPoints() const +BoundingBox::GetPoints() const -> const PointsContainer * { itkDebugMacro("returning Points container of " << m_PointsContainer); @@ -77,9 +78,9 @@ BoundingBox::Get } /** Compute and get the corners of the bounding box */ -template +template auto -BoundingBox::ComputeCorners() const +BoundingBox::ComputeCorners() const -> std::array { std::array result; @@ -94,12 +95,11 @@ BoundingBox::Com for (SizeValueType j = 0; j < NumberOfCorners; ++j) { - PointType pnt; + const std::bitset cornerBitset{ j }; + PointType pnt; for (unsigned int i = 0; i < PointDimension; ++i) { - pnt[i] = center[i] + - std::pow(-1.0, (static_cast(j / (static_cast(std::pow(2.0, static_cast(i))))))) * - radius[i]; + pnt[i] = center[i] + (cornerBitset[i] ? -1 : 1) * radius[i]; } result[j] = pnt; @@ -110,9 +110,9 @@ BoundingBox::Com #if !defined(ITK_LEGACY_REMOVE) /** Compute and get the corners of the bounding box */ -template +template auto -BoundingBox::GetCorners() -> const PointsContainer * +BoundingBox::GetCorners() -> const PointsContainer * { m_CornersContainer->clear(); m_CornersContainer->Reserve(NumberOfCorners); @@ -128,15 +128,15 @@ BoundingBox::Get #endif -template +template bool -BoundingBox::ComputeBoundingBox() const +BoundingBox::ComputeBoundingBox() const { if (!m_PointsContainer) { if (this->GetMTime() > m_BoundsMTime) { - m_Bounds.Fill(CoordRepType{}); + m_Bounds.Fill(CoordinateType{}); m_BoundsMTime.Modified(); } return false; @@ -148,13 +148,13 @@ BoundingBox::Com // start by initializing the values if (m_PointsContainer->Size() < 1) { - m_Bounds.Fill(CoordRepType{}); + m_Bounds.Fill(CoordinateType{}); m_BoundsMTime.Modified(); return false; } - PointsContainerConstIterator ci = m_PointsContainer->Begin(); - Point point = ci->Value(); // point value + PointsContainerConstIterator ci = m_PointsContainer->Begin(); + Point point = ci->Value(); // point value for (unsigned int i = 0; i < PointDimension; ++i) { m_Bounds[2 * i] = point[i]; @@ -187,9 +187,9 @@ BoundingBox::Com return true; } -template +template auto -BoundingBox::GetCenter() const -> PointType +BoundingBox::GetCenter() const -> PointType { this->ComputeBoundingBox(); @@ -202,9 +202,9 @@ BoundingBox::Get return center; } -template +template auto -BoundingBox::GetMinimum() const -> PointType +BoundingBox::GetMinimum() const -> PointType { this->ComputeBoundingBox(); @@ -217,9 +217,9 @@ BoundingBox::Get return minimum; } -template +template void -BoundingBox::SetMinimum(const PointType & point) +BoundingBox::SetMinimum(const PointType & point) { for (unsigned int i = 0; i < PointDimension; ++i) { @@ -229,9 +229,9 @@ BoundingBox::Set m_BoundsMTime.Modified(); } -template +template auto -BoundingBox::GetMaximum() const -> PointType +BoundingBox::GetMaximum() const -> PointType { this->ComputeBoundingBox(); @@ -244,9 +244,9 @@ BoundingBox::Get return maximum; } -template +template void -BoundingBox::SetMaximum(const PointType & point) +BoundingBox::SetMaximum(const PointType & point) { for (unsigned int i = 0; i < PointDimension; ++i) { @@ -256,9 +256,9 @@ BoundingBox::Set m_BoundsMTime.Modified(); } -template +template void -BoundingBox::ConsiderPoint(const PointType & point) +BoundingBox::ConsiderPoint(const PointType & point) { bool changed = false; @@ -282,12 +282,12 @@ BoundingBox::Con } } -template +template auto -BoundingBox::GetDiagonalLength2() const +BoundingBox::GetDiagonalLength2() const -> AccumulateType { - typename NumericTraits::AccumulateType dist2 = CoordRepType{}; + typename NumericTraits::AccumulateType dist2{}; if (this->ComputeBoundingBox()) { @@ -300,9 +300,9 @@ BoundingBox::Get return dist2; } -template +template bool -BoundingBox::IsInside(const PointType & point) const +BoundingBox::IsInside(const PointType & point) const { unsigned int j = 0; unsigned int i = 0; @@ -322,9 +322,9 @@ BoundingBox::IsI return true; } -template +template ModifiedTimeType -BoundingBox::GetMTime() const +BoundingBox::GetMTime() const { ModifiedTimeType latestTime = Object::GetMTime(); @@ -335,9 +335,9 @@ BoundingBox::Get return latestTime; } -template +template auto -BoundingBox::DeepCopy() const -> Pointer +BoundingBox::DeepCopy() const -> Pointer { Pointer clone = Self::New(); @@ -348,11 +348,11 @@ BoundingBox::Dee // Copy the corners into the clone. clone->m_CornersContainer->clear(); - PointsContainerConstIterator itr = this->m_CornersContainer->Begin(); - PointsContainerConstIterator end = this->m_CornersContainer->End(); + PointsContainerConstIterator itr = this->m_CornersContainer->Begin(); + const PointsContainerConstIterator end = this->m_CornersContainer->End(); clone->m_CornersContainer->Reserve(this->m_CornersContainer->Size()); - PointsContainerIterator dest = clone->m_CornersContainer->Begin(); + const PointsContainerIterator dest = clone->m_CornersContainer->Begin(); while (itr != end) { diff --git a/Modules/Core/Common/include/itkBresenhamLine.hxx b/Modules/Core/Common/include/itkBresenhamLine.hxx index 0aa6b1675ae..b6a4c847f86 100644 --- a/Modules/Core/Common/include/itkBresenhamLine.hxx +++ b/Modules/Core/Common/include/itkBresenhamLine.hxx @@ -29,35 +29,11 @@ BresenhamLine::BuildLine(LType Direction, IdentifierType length) -> { // copied from the line iterator /** Variables that drive the Bresenham-Algorithm */ - // The dimension with the largest difference between start and end - unsigned int m_MainDirection; - - // Accumulated error for the other dimensions - IndexType m_AccumulateError; - - // Increment for the error for each step. Two times the difference between - // start and end - IndexType m_IncrementError; - - // If enough is accumulated for a dimension, the index has to be - // incremented. Will be the number of pixels in the line - IndexType m_MaximalError; - - // Direction of increment. -1 or 1 - IndexType m_OverflowIncrement; - - // After an overflow, the accumulated error is reduced again. Will be - // two times the number of pixels in the line - IndexType m_ReduceErrorAfterIncrement; - - OffsetArray result(length); - - IndexType m_CurrentImageIndex, LastIndex; Direction.Normalize(); // we are going to start at 0 - m_CurrentImageIndex.Fill(0); constexpr IndexType StartIndex = { { 0 } }; + IndexType LastIndex; for (unsigned int i = 0; i < VDimension; ++i) { LastIndex[i] = (IndexValueType)(length * Direction[i]); @@ -65,6 +41,12 @@ BresenhamLine::BuildLine(LType Direction, IdentifierType length) -> // Find the dominant direction IndexValueType maxDistance = 0; unsigned int maxDistanceDimension = 0; + // Increment for the error for each step. Two times the difference between + // start and end + IndexType incrementError; + + // Direction of increment. -1 or 1 + IndexType overflowIncrement; for (unsigned int i = 0; i < VDimension; ++i) { auto distance = static_cast(itk::Math::abs(LastIndex[i])); @@ -73,37 +55,47 @@ BresenhamLine::BuildLine(LType Direction, IdentifierType length) -> maxDistance = distance; maxDistanceDimension = i; } - m_IncrementError[i] = 2 * distance; - m_OverflowIncrement[i] = (LastIndex[i] < 0 ? -1 : 1); + incrementError[i] = 2 * distance; + overflowIncrement[i] = (LastIndex[i] < 0 ? -1 : 1); } - m_MainDirection = maxDistanceDimension; - m_MaximalError.Fill(maxDistance); - m_ReduceErrorAfterIncrement.Fill(2 * maxDistance); - m_AccumulateError.Fill(0); + + // The dimension with the largest difference between start and end + const unsigned int mainDirection = maxDistanceDimension; + // If enough is accumulated for a dimension, the index has to be + // incremented. Will be the number of pixels in the line + auto maximalError = MakeFilled(maxDistance); + // After an overflow, the accumulated error is reduced again. Will be + // two times the number of pixels in the line + auto reduceErrorAfterIncrement = MakeFilled(2 * maxDistance); + // Accumulated error for the other dimensions + auto accumulateError = MakeFilled(0); + + OffsetArray result(length); + auto currentImageIndex = MakeFilled(0); + result[0] = currentImageIndex - StartIndex; unsigned int steps = 1; - result[0] = m_CurrentImageIndex - StartIndex; while (steps < length) { // This part is from ++ in LineConstIterator - // We need to modify m_AccumulateError, m_CurrentImageIndex, m_IsAtEnd + // We need to modify accumulateError, currentImageIndex, isAtEnd for (unsigned int i = 0; i < VDimension; ++i) { - if (i == m_MainDirection) + if (i == mainDirection) { - m_CurrentImageIndex[i] += m_OverflowIncrement[i]; + currentImageIndex[i] += overflowIncrement[i]; } else { - m_AccumulateError[i] += m_IncrementError[i]; - if (m_AccumulateError[i] >= m_MaximalError[i]) + accumulateError[i] += incrementError[i]; + if (accumulateError[i] >= maximalError[i]) { - m_CurrentImageIndex[i] += m_OverflowIncrement[i]; - m_AccumulateError[i] -= m_ReduceErrorAfterIncrement[i]; + currentImageIndex[i] += overflowIncrement[i]; + accumulateError[i] -= reduceErrorAfterIncrement[i]; } } } - result[steps] = m_CurrentImageIndex - StartIndex; // produce an offset + result[steps] = currentImageIndex - StartIndex; // produce an offset ++steps; } @@ -121,7 +113,7 @@ BresenhamLine::BuildLine(IndexType p0, IndexType p1) -> IndexArray { point0[i] = p0[i]; point1[i] = p1[i]; - IdentifierType distance = itk::Math::abs(p0[i] - p1[i]) + 1; + const IdentifierType distance = itk::Math::abs(p0[i] - p1[i]) + 1; if (distance > maxDistance) { maxDistance = distance; diff --git a/Modules/Core/Common/include/itkBuildInformation.h b/Modules/Core/Common/include/itkBuildInformation.h index acf21bc0c6b..87dfd4b7f77 100644 --- a/Modules/Core/Common/include/itkBuildInformation.h +++ b/Modules/Core/Common/include/itkBuildInformation.h @@ -85,6 +85,7 @@ class ITKCommon_EXPORT BuildInformation final : public Object New(); /** Returns the global singleton instance of the BuildInformation */ + /** @ITKStartGrouping */ static Pointer GetInstance(); static const MapType & @@ -95,7 +96,7 @@ class ITKCommon_EXPORT BuildInformation final : public Object GetDescription(const MapKeyType &); static const std::vector GetAllKeys(); - + /** @ITKEndGrouping */ private: BuildInformation(); diff --git a/Modules/Core/Common/include/itkByteSwapper.h b/Modules/Core/Common/include/itkByteSwapper.h index f76d6ba3250..2ac032f17b1 100644 --- a/Modules/Core/Common/include/itkByteSwapper.h +++ b/Modules/Core/Common/include/itkByteSwapper.h @@ -58,25 +58,36 @@ class ITK_TEMPLATE_EXPORT ByteSwapper : public Object using Pointer = SmartPointer; using ConstPointer = SmartPointer; - /** Work around MSVC bug (including ByteSwapper.h in a templated class). */ - using OStreamType = std::ostream; +#ifndef ITK_FUTURE_LEGACY_REMOVE + /** Work around old MSVC bug (including ByteSwapper.h in a templated class). */ + using OStreamType + [[deprecated("ByteSwapper::OStreamType is deprecated from ITK 6. Just use `std::ostream` instead!")]] = + std::ostream; +#endif /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(ByteSwapper); - /** Query the machine Endian-ness. */ - static bool - SystemIsBigEndian(); + /** Query the machine Endian-ness. + \note C++20 also allows querying the endianness, by using its enum class `std::endian`. */ + static constexpr bool + SystemIsBigEndian() + { + return m_SystemIsBigEndian; + } - static bool + static constexpr bool SystemIsBE() { return SystemIsBigEndian(); } - static bool - SystemIsLittleEndian(); + static constexpr bool + SystemIsLittleEndian() + { + return !m_SystemIsBigEndian; + } - static bool + static constexpr bool SystemIsLE() { return SystemIsLittleEndian(); @@ -110,7 +121,7 @@ class ITK_TEMPLATE_EXPORT ByteSwapper : public Object * others raise an exception. The method is used to * swap to and from Big Endian. */ static void - SwapWriteRangeFromSystemToBigEndian(const T * p, int num, OStreamType * fp); + SwapWriteRangeFromSystemToBigEndian(const T * p, int num, std::ostream * fp); /** Generic swap method handles type T. The swapping is * done in-place. 2, 4 and 8 byte swapping @@ -136,53 +147,29 @@ class ITK_TEMPLATE_EXPORT ByteSwapper : public Object * others raise an exception. The method is used to * swap to and from Little Endian. */ static void - SwapWriteRangeFromSystemToLittleEndian(const T * p, int num, OStreamType * fp); + SwapWriteRangeFromSystemToLittleEndian(const T * p, int num, std::ostream * fp); protected: ByteSwapper() = default; ~ByteSwapper() override = default; - /** Swap 2 bytes. */ +private: + /** Swaps the bytes of the specified argument in-place. Assumes that its number of bytes is either 2, 4, or 8. + * Otherwise, it throws an exception. */ static void - Swap2(void * pin); + SwapBytes(T &); - /** Swap a range of two-byte words. Num is the number of two-byte - * words to swap. */ + /** Swaps and writes the specified elements to the specified output stream. */ static void - Swap2Range(void * ptr, BufferSizeType num); + SwapWriteRange(const T * buffer, SizeValueType numberOfElements, std::ostream & outputStream); - /** Swap and write a range of two-byte words. Num is the number of two-byte - * words to swap and write. */ - static void - SwapWrite2Range(const void * ptr, BufferSizeType num, OStreamType * fp); - - /** Swap four bytes. */ - static void - Swap4(void * ptr); - - /** Swap a range of four-byte words. Num is the number of four-byte words - * to swap. */ - static void - Swap4Range(void * ptr, BufferSizeType num); - - /** Swap and write a range of four-byte words. Num is the number of four-byte - * words to swap and write. */ - static void - SwapWrite4Range(const void * ptr, BufferSizeType num, OStreamType * fp); - - /** Swap 8 bytes. */ - static void - Swap8(void * ptr); - - /** Swap a range of 8-byte words. Num is the number of four-byte words - * to swap. */ - static void - Swap8Range(void * ptr, BufferSizeType num); - - /** Swap and write a range of 8-byte words. Num is the number of four-byte - * words to swap and write. */ - static void - SwapWrite8Range(const void * ptr, BufferSizeType num, OStreamType * fp); + static constexpr bool m_SystemIsBigEndian{ +#ifdef CMAKE_WORDS_BIGENDIAN + true +#else + false +#endif + }; }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkByteSwapper.hxx b/Modules/Core/Common/include/itkByteSwapper.hxx index 81bdd6e54a9..203552f4e50 100644 --- a/Modules/Core/Common/include/itkByteSwapper.hxx +++ b/Modules/Core/Common/include/itkByteSwapper.hxx @@ -28,408 +28,139 @@ #ifndef itkByteSwapper_hxx #define itkByteSwapper_hxx #include "itkMakeUniqueForOverwrite.h" -#include // For swap. +#include // For for_each_n and swap. +#include // For byte. #include #include namespace itk { // The following are the public methods -------------------------------- -// -// Machine definitions -#ifdef CMAKE_WORDS_BIGENDIAN -template -bool -ByteSwapper::SystemIsBigEndian() -{ - return true; -} -template -bool -ByteSwapper::SystemIsLittleEndian() -{ - return false; -} -#else -template -bool -ByteSwapper::SystemIsBigEndian() -{ - return false; -} -template -bool -ByteSwapper::SystemIsLittleEndian() -{ - return true; -} -#endif //------Big Endian methods---------------------------------------------- // Use different swap methods based on type -#ifdef CMAKE_WORDS_BIGENDIAN -template -void -ByteSwapper::SwapFromSystemToBigEndian(T *) -{} -#else -template -void -ByteSwapper::SwapFromSystemToBigEndian(T * p) -{ - switch (sizeof(T)) - { - case 1: - return; - case 2: - Self::Swap2(p); - return; - case 4: - Self::Swap4(p); - return; - case 8: - Self::Swap8(p); - return; - default: - itkGenericExceptionMacro("Cannot swap number of bytes requested"); - } -} -#endif - -#ifdef CMAKE_WORDS_BIGENDIAN template void -ByteSwapper::SwapRangeFromSystemToBigEndian(T *, BufferSizeType) +ByteSwapper::SwapFromSystemToBigEndian([[maybe_unused]] T * p) { - // nothing needs to be done here... -} - -#else - -# ifdef __INTEL_COMPILER -# pragma warning disable 280 // remark #280: selector expression is constant -# endif -template -void -ByteSwapper::SwapRangeFromSystemToBigEndian(T * p, BufferSizeType num) -{ - switch (sizeof(T)) + if constexpr (!m_SystemIsBigEndian && sizeof(T) > 1) { - case 1: - return; - case 2: - Self::Swap2Range(p, num); - return; - case 4: - Self::Swap4Range(p, num); - return; - case 8: - Self::Swap8Range(p, num); - return; - default: - itkGenericExceptionMacro("Cannot swap number of bytes requested"); + SwapBytes(*p); } } -#endif - -#ifdef CMAKE_WORDS_BIGENDIAN -template -void -ByteSwapper::SwapWriteRangeFromSystemToBigEndian(const T * p, int num, OStreamType * fp) -{ - num *= sizeof(T); - fp->write(reinterpret_cast(p), num); -} - -#else template void -ByteSwapper::SwapWriteRangeFromSystemToBigEndian(const T * p, int num, OStreamType * fp) +ByteSwapper::SwapRangeFromSystemToBigEndian([[maybe_unused]] T * p, [[maybe_unused]] BufferSizeType num) { - switch (sizeof(T)) + if constexpr (!m_SystemIsBigEndian && sizeof(T) > 1) { - case 1: - return; - case 2: - Self::SwapWrite2Range(p, num, fp); - return; - case 4: - Self::SwapWrite4Range(p, num, fp); - return; - case 8: - Self::SwapWrite8Range(p, num, fp); - return; - default: - itkGenericExceptionMacro("Cannot swap number of bytes requested"); + std::for_each_n(p, num, [](T & element) { SwapBytes(element); }); } } -#endif - -//------Little Endian methods---------------------------------------------- - -#ifdef CMAKE_WORDS_BIGENDIAN template void -ByteSwapper::SwapFromSystemToLittleEndian(T * p) +ByteSwapper::SwapWriteRangeFromSystemToBigEndian(const T * p, int num, std::ostream * fp) { - switch (sizeof(T)) + if constexpr (m_SystemIsBigEndian || sizeof(T) == 1) { - case 1: - return; - case 2: - Self::Swap2(p); - return; - case 4: - Self::Swap4(p); - return; - case 8: - Self::Swap8(p); - return; - default: - itkGenericExceptionMacro("Cannot swap number of bytes requested"); + num *= sizeof(T); + fp->write(reinterpret_cast(p), num); } -} - -#else -template -void -ByteSwapper::SwapFromSystemToLittleEndian(T *) -{} -#endif - -#ifdef CMAKE_WORDS_BIGENDIAN -template -void -ByteSwapper::SwapRangeFromSystemToLittleEndian(T * p, BufferSizeType num) -{ - switch (sizeof(T)) + else { - case 1: - return; - case 2: - Self::Swap2Range(p, num); - return; - case 4: - Self::Swap4Range(p, num); - return; - case 8: - Self::Swap8Range(p, num); - return; - default: - itkGenericExceptionMacro("Cannot swap number of bytes requested"); + SwapWriteRange(p, num, *fp); } } -#else -template -void -ByteSwapper::SwapRangeFromSystemToLittleEndian(T *, BufferSizeType) -{} -#endif -#ifdef CMAKE_WORDS_BIGENDIAN +//------Little Endian methods---------------------------------------------- + template void -ByteSwapper::SwapWriteRangeFromSystemToLittleEndian(const T * p, int num, OStreamType * fp) +ByteSwapper::SwapFromSystemToLittleEndian([[maybe_unused]] T * p) { - switch (sizeof(T)) + if constexpr (m_SystemIsBigEndian && sizeof(T) > 1) { - case 1: - return; - case 2: - Self::SwapWrite2Range(p, num, fp); - return; - case 4: - Self::SwapWrite4Range(p, num, fp); - return; - case 8: - Self::SwapWrite8Range(p, num, fp); - return; - default: - itkGenericExceptionMacro("Cannot swap number of bytes requested"); + SwapBytes(*p); } } -#else template void -ByteSwapper::SwapWriteRangeFromSystemToLittleEndian(const T * p, int num, OStreamType * fp) +ByteSwapper::SwapRangeFromSystemToLittleEndian([[maybe_unused]] T * p, [[maybe_unused]] BufferSizeType num) { - num *= sizeof(T); - fp->write(reinterpret_cast(p), num); -} - -#endif - -// The following are the protected methods ------------------------- -// - -//------2-byte methods---------------------------------------------- - -// Swap 2 byte word. -template -void -ByteSwapper::Swap2(void * pin) -{ - auto * p = static_cast(pin); - std::swap(p[0], p[1]); -} - -// Swap bunch of bytes. Num is the number of two byte words to swap. -template -void -ByteSwapper::Swap2Range(void * ptr, BufferSizeType num) -{ - auto * pos = static_cast(ptr); - for (BufferSizeType i = 0; i < num; ++i) + if constexpr (m_SystemIsBigEndian && sizeof(T) > 1) { - Self::Swap2(pos); - pos = pos + 2; + std::for_each_n(p, num, [](T & element) { SwapBytes(element); }); } } -// Swap bunch of bytes. Num is the number of four byte words to swap. template void -ByteSwapper::SwapWrite2Range(const void * ptr, BufferSizeType num, OStreamType * fp) +ByteSwapper::SwapWriteRangeFromSystemToLittleEndian(const T * p, int num, std::ostream * fp) { - BufferSizeType chunkSize = 1000000; - if (num < chunkSize) + if constexpr (m_SystemIsBigEndian && sizeof(T) > 1) { - chunkSize = num; + SwapWriteRange(p, num, *fp); } - const auto cpy = make_unique_for_overwrite(chunkSize * 2); - while (num) + else { - memcpy(cpy.get(), ptr, chunkSize * 2); - - Self::Swap2Range(cpy.get(), num); - - fp->write(cpy.get(), static_cast(2 * chunkSize)); - ptr = static_cast(ptr) + chunkSize * 2; - num -= chunkSize; - if (num < chunkSize) - { - chunkSize = num; - } + num *= sizeof(T); + fp->write(reinterpret_cast(p), num); } } -//------4-byte methods---------------------------------------------- -// Swap four byte word. -template -void -ByteSwapper::Swap4(void * ptr) -{ - auto * p = static_cast(ptr); - std::swap(p[0], p[3]); - std::swap(p[1], p[2]); -} - -// Swap bunch of bytes. Num is the number of four byte words to swap. -template -void -ByteSwapper::Swap4Range(void * ptr, BufferSizeType num) -{ - auto * pos = static_cast(ptr); - - for (BufferSizeType i = 0; i < num; ++i) - { - Self::Swap4(pos); - pos = pos + 4; - } -} +// The following member functions are private: -// Swap bunch of bytes. Num is the number of four byte words to swap. template void -ByteSwapper::SwapWrite4Range(const void * ptr, BufferSizeType num, OStreamType * fp) +ByteSwapper::SwapBytes(T & value) { - BufferSizeType chunkSize = 1000000; + static constexpr size_t numberOfBytes = sizeof(T); - if (num < chunkSize) + // Historically (from ITK v1.2.0, March 2003) the following number of bytes are supported: + if constexpr (numberOfBytes == 2 || numberOfBytes == 4 || numberOfBytes == 8) { - chunkSize = num; - } - const auto cpy = make_unique_for_overwrite(chunkSize * 4); + // When the value is an integer, the following code is equivalent to `value = std::byteswap(value)`, in C++26: + auto * const bytes = reinterpret_cast(&value); - while (num) - { - memcpy(cpy.get(), ptr, chunkSize * 4); - - Self::Swap4Range(cpy.get(), num); - - fp->write(cpy.get(), static_cast(4 * chunkSize)); - ptr = static_cast(ptr) + chunkSize * 4; - num -= chunkSize; - if (num < chunkSize) + for (size_t i{}; i < (numberOfBytes / 2); ++i) { - chunkSize = num; + std::swap(bytes[i], bytes[(numberOfBytes - 1) - i]); } } -} - -//------8-byte methods---------------------------------------------- - -// Swap 8 byte double precision -template -void -ByteSwapper::Swap8(void * ptr) -{ - auto * p = static_cast(ptr); - - std::swap(p[0], p[7]); - std::swap(p[1], p[6]); - std::swap(p[2], p[5]); - std::swap(p[3], p[4]); -} - -// Swap bunch of bytes. Num is the number of eight byte words to swap. -template -void -ByteSwapper::Swap8Range(void * ptr, BufferSizeType num) -{ - auto * pos = static_cast(ptr); - - for (BufferSizeType i = 0; i < num; ++i) + else { - Self::Swap8(pos); - pos = pos + 8; + itkGenericExceptionMacro("Cannot swap number of bytes requested"); } } -// Swap bunch of bytes. Num is the number of four byte words to swap. template void -ByteSwapper::SwapWrite8Range(const void * ptr, BufferSizeType num, OStreamType * fp) +ByteSwapper::SwapWriteRange(const T * buffer, SizeValueType numberOfElements, std::ostream & outputStream) { - BufferSizeType chunkSize = 1000000; - if (num < chunkSize) - { - chunkSize = num; - } - const auto cpy = make_unique_for_overwrite(chunkSize * 8); + auto chunkSize = std::min(numberOfElements, SizeValueType{ 1000000 }); - while (num) - { - memcpy(cpy.get(), ptr, chunkSize * 8); - - Self::Swap8Range(cpy.get(), chunkSize); + const auto chunk = make_unique_for_overwrite(chunkSize); - fp->write(cpy.get(), static_cast(8 * chunkSize)); - ptr = static_cast(ptr) + chunkSize * 8; - num -= chunkSize; - if (num < chunkSize) - { - chunkSize = num; - } + while (numberOfElements > 0) + { + std::copy_n(buffer, chunkSize, chunk.get()); + std::for_each_n(chunk.get(), chunkSize, [](T & element) { SwapBytes(element); }); + + outputStream.write(reinterpret_cast(chunk.get()), + static_cast(chunkSize * sizeof(T))); + buffer += chunkSize; + numberOfElements -= chunkSize; + chunkSize = std::min(numberOfElements, chunkSize); } } + } // end namespace itk #endif diff --git a/Modules/Core/Common/include/itkCellInterface.h b/Modules/Core/Common/include/itkCellInterface.h index 148edd0929a..f5c20236d9b 100644 --- a/Modules/Core/Common/include/itkCellInterface.h +++ b/Modules/Core/Common/include/itkCellInterface.h @@ -39,7 +39,8 @@ { \ v->VisitFromCell(cellid, this); \ } \ - } + } \ + ITK_MACROEND_NOOP_STATEMENT // Define a macro for the common type alias required by the // classes deriving form CellInterface (included). @@ -61,7 +62,7 @@ using typename Superclass::CellRawPointer; \ using typename Superclass::CellConstRawPointer; \ using typename Superclass::CellTraits; \ - using typename Superclass::CoordRepType; \ + using typename Superclass::CoordinateType; \ using typename Superclass::InterpolationWeightType; \ using typename Superclass::PointIdentifier; \ using typename Superclass::PointIdIterator; \ @@ -108,8 +109,11 @@ class ITK_TEMPLATE_EXPORT CellInterface using CellTraits = TCellTraits; /** Save type information for this cell. */ - using CoordinateType = typename CellTraits::CoordRepType; - using CoordRepType = CoordinateType; + using CoordinateType = typename CellTraits::CoordinateType; +#ifndef ITK_FUTURE_LEGACY_REMOVE + using CoordRepType ITK_FUTURE_DEPRECATED( + "ITK 6 discourages using `CoordRepType`. Please use `CoordinateType` instead!") = CoordinateType; +#endif using InterpolationWeightType = typename CellTraits::InterpolationWeightType; using PointIdentifier = typename CellTraits::PointIdentifier; using PointIdIterator = typename CellTraits::PointIdIterator; @@ -140,7 +144,7 @@ class ITK_TEMPLATE_EXPORT CellInterface using CellFeatureCount = CellFeatureIdentifier; /** Types needed to contour the cells */ - using ParametricCoordArrayType = Array; + using ParametricCoordArrayType = Array; using ShapeFunctionsArrayType = Array; // static int GetNextUserCellId(); // never return > MAX_INTERFACE @@ -203,7 +207,7 @@ class ITK_TEMPLATE_EXPORT CellInterface void AddVisitor(VisitorType * v) { - CellGeometryEnum id = v->GetCellTopologyId(); + const CellGeometryEnum id = v->GetCellTopologyId(); if (id < CellGeometryEnum::LAST_ITK_CELL) { @@ -302,18 +306,19 @@ class ITK_TEMPLATE_EXPORT CellInterface PointIdsEnd() const = 0; /** Get/Set the point id list used by the cell */ + /** @ITKStartGrouping */ using PointIdentifierContainerType = itk::Array; PointIdentifierContainerType GetPointIdsContainer() const; void SetPointIdsContainer(const PointIdentifierContainerType &); - + /** @ITKEndGrouping */ /** Given the parametric coordinates of a point in the cell * (pCoords[CellDimension]), get the closest cell boundary feature of * topological dimension CellDimension-1. If the "inside" pointer is not * nullptr, the flag is set to indicate whether the point is inside the cell. */ virtual bool - GetClosestBoundary(CoordRepType[], bool *, CellAutoPointer &) + GetClosestBoundary(CoordinateType[], bool *, CellAutoPointer &) { return false; } @@ -335,10 +340,10 @@ class ITK_TEMPLATE_EXPORT CellInterface * - Get the interpolation weights for the cell * (Returns through pointer to array: weights[NumberOfPoints]). */ virtual bool - EvaluatePosition(CoordRepType *, + EvaluatePosition(CoordinateType *, PointsContainer *, - CoordRepType *, - CoordRepType[], + CoordinateType *, + CoordinateType[], double *, InterpolationWeightType *) { @@ -368,12 +373,12 @@ class ITK_TEMPLATE_EXPORT CellInterface * * Returns whether an intersection exists within the given tolerance. */ virtual bool - IntersectWithLine(CoordRepType[PointDimension], - CoordRepType[PointDimension], - CoordRepType, - CoordRepType[PointDimension], - CoordRepType *, - CoordRepType[]) + IntersectWithLine(CoordinateType[PointDimension], + CoordinateType[PointDimension], + CoordinateType, + CoordinateType[PointDimension], + CoordinateType *, + CoordinateType[]) { return bool(); } @@ -382,13 +387,17 @@ class ITK_TEMPLATE_EXPORT CellInterface * Array is ordered (xmin, xmax, ymin, ymax, ....). A pointer to the * array is returned for convenience. This allows code like: * "CoordRep* bounds = cell->GetBoundingBox(new CoordRep[6]);". */ - CoordRepType * GetBoundingBox(CoordRepType[PointDimension * 2]) { return nullptr; } + CoordinateType * + GetBoundingBox(CoordinateType[PointDimension * 2]) + { + return nullptr; + } /** Compute the square of the diagonal length of the bounding box. */ - CoordRepType + CoordinateType GetBoundingBoxDiagonalLength2() { - return CoordRepType{}; + return CoordinateType{}; } /** Intersect the given bounding box (bounds[PointDimension*2]) with a line @@ -403,11 +412,12 @@ class ITK_TEMPLATE_EXPORT CellInterface * (returned through "t" pointer). * * Returns whether an intersection exists. */ - virtual bool IntersectBoundingBoxWithLine(CoordRepType[PointDimension * 2], - CoordRepType[PointDimension], - CoordRepType[PointDimension], - CoordRepType[PointDimension], - CoordRepType *) + virtual bool + IntersectBoundingBoxWithLine(CoordinateType[PointDimension * 2], + CoordinateType[PointDimension], + CoordinateType[PointDimension], + CoordinateType[PointDimension], + CoordinateType *) { return bool(); } @@ -513,7 +523,7 @@ class ITK_TEMPLATE_EXPORT CellInterface * \ingroup ITKCommon */ template pixel, const char * name = "UserDefined"); - + /** @ITKEndGrouping */ /** Given the position in the table and the color * returns the value. */ diff --git a/Modules/Core/Common/include/itkColorTable.hxx b/Modules/Core/Common/include/itkColorTable.hxx index 94b08ed36dc..7f0591850fd 100644 --- a/Modules/Core/Common/include/itkColorTable.hxx +++ b/Modules/Core/Common/include/itkColorTable.hxx @@ -87,8 +87,8 @@ ColorTable::UseDiscreteColors() // max for TComponent. Exceptions were happening // on this assignment, even if realMax was // set to NumericTraits::max(). - typename NumericTraits::RealType realMax(1.0 * scale + shift); - TComponent pixelMax(NumericTraits::max()); + const typename NumericTraits::RealType realMax(1.0 * scale + shift); + TComponent pixelMax(NumericTraits::max()); // Converting from TComponent to RealType may introduce a rounding error, so do static_cast constexpr auto max_value_converted = static_cast::RealType>(NumericTraits::max()); @@ -104,8 +104,6 @@ template void ColorTable::UseGrayColors(unsigned int n) { - unsigned int i; - this->DeleteColors(); m_NumberOfColors = n; @@ -138,9 +136,9 @@ ColorTable::UseGrayColors(unsigned int n) // Converting from TComponent to RealType may introduce a rounding error, so do static_cast constexpr auto max_value_converted = static_cast::RealType>(NumericTraits::max()); - for (i = 0; i < m_NumberOfColors; ++i) + for (unsigned int i = 0; i < m_NumberOfColors; ++i) { - typename NumericTraits::RealType realGray(minimum + i * delta); + const typename NumericTraits::RealType realGray(minimum + i * delta); TComponent gray = NumericTraits::max(); if (realGray < max_value_converted) @@ -159,8 +157,6 @@ template void ColorTable::UseHeatColors(unsigned int n) { - unsigned int i; - this->DeleteColors(); m_NumberOfColors = n; @@ -183,12 +179,12 @@ ColorTable::UseHeatColors(unsigned int n) // Converting from TComponent to RealType may introduce a rounding error, so do static_cast constexpr auto max_value_converted = static_cast::RealType>(NumericTraits::max()); - for (i = 0; i < n / 2.0; ++i) + for (unsigned int i = 0; i < n / 2.0; ++i) { // // avoid overflow - typename NumericTraits::RealType realR(((i + 1) / (n / 2.0 + 1)) * scale + shift); - TComponent r(NumericTraits::max()); + const typename NumericTraits::RealType realR(((i + 1) / (n / 2.0 + 1)) * scale + shift); + TComponent r(NumericTraits::max()); if (realR < max_value_converted) { r = static_cast(realR); @@ -201,10 +197,10 @@ ColorTable::UseHeatColors(unsigned int n) m_ColorName[i] = name.str(); } - for (i = 0; i < n / 2; ++i) + for (unsigned int i = 0; i < n / 2; ++i) { - typename NumericTraits::RealType rdouble(1.0 * scale + shift); - TComponent r(NumericTraits::max()); + const typename NumericTraits::RealType rdouble(1.0 * scale + shift); + TComponent r(NumericTraits::max()); if (rdouble < max_value_converted) { r = static_cast(rdouble); @@ -222,15 +218,14 @@ template void ColorTable::UseRandomColors(unsigned int n) { - unsigned int i; - this->DeleteColors(); m_NumberOfColors = n; m_Color.resize(m_NumberOfColors); m_ColorName.resize(m_NumberOfColors); - TComponent r, g, b; - TComponent minimum, maximum; + + TComponent minimum; + TComponent maximum; if (NumericTraits::is_integer) { minimum = NumericTraits::NonpositiveMin(); @@ -241,13 +236,13 @@ ColorTable::UseRandomColors(unsigned int n) minimum = TComponent{}; maximum = NumericTraits::OneValue(); } - for (i = 0; i < n; ++i) + for (unsigned int i = 0; i < n; ++i) { - r = static_cast(vnl_sample_uniform(minimum, maximum)); + auto r = static_cast(vnl_sample_uniform(minimum, maximum)); m_Color[i][0] = r; - g = static_cast(vnl_sample_uniform(minimum, maximum)); + auto g = static_cast(vnl_sample_uniform(minimum, maximum)); m_Color[i][1] = g; - b = static_cast(vnl_sample_uniform(minimum, maximum)); + auto b = static_cast(vnl_sample_uniform(minimum, maximum)); m_Color[i][2] = b; std::ostringstream name; name << "Random(" << std::fixed << std::setprecision(2) << static_cast(r) << ',' << static_cast(g) @@ -286,12 +281,10 @@ ColorTable::GetColor(unsigned int c) { return m_Color[c]; } - else - { - RGBPixel pixel; - pixel.Set(0, 0, 0); - return pixel; - } + + RGBPixel pixel; + pixel.Set(0, 0, 0); + return pixel; } template @@ -334,10 +327,8 @@ ColorTable::GetColorName(unsigned int c) { return m_ColorName[c]; } - else - { - return ""; - } + + return ""; } template @@ -349,8 +340,7 @@ ColorTable::GetClosestColorTableId(TComponent r, TComponent g, TComp for (unsigned int i = 0; i < m_NumberOfColors; ++i) { - double match; - match = (r - static_cast(m_Color[i].GetRed())) * (r - static_cast(m_Color[i].GetRed())); + double match = (r - static_cast(m_Color[i].GetRed())) * (r - static_cast(m_Color[i].GetRed())); match += (g - static_cast(m_Color[i].GetGreen())) * (g - static_cast(m_Color[i].GetGreen())); match += (b - static_cast(m_Color[i].GetGreen())) * (b - static_cast(m_Color[i].GetBlue())); if (i == 0 || match < bestMatch) diff --git a/Modules/Core/Common/include/itkCommand.h b/Modules/Core/Common/include/itkCommand.h index 9fab6ba028d..573143f9254 100644 --- a/Modules/Core/Common/include/itkCommand.h +++ b/Modules/Core/Common/include/itkCommand.h @@ -89,9 +89,10 @@ class ITK_TEMPLATE_EXPORT MemberCommand : public Command ITK_DISALLOW_COPY_AND_MOVE(MemberCommand); /** pointer to a member function that takes a Object* and the event */ + /** @ITKStartGrouping */ using TMemberFunctionPointer = void (T::*)(Object *, const EventObject &); using TConstMemberFunctionPointer = void (T::*)(const Object *, const EventObject &); - + /** @ITKEndGrouping */ /** Standard class type aliases. */ using Self = MemberCommand; using Pointer = SmartPointer; @@ -358,10 +359,11 @@ class ITKCommon_EXPORT CStyleCommand : public Command { public: /** Typedefs for C-style callbacks. */ + /** @ITKStartGrouping */ using FunctionPointer = void (*)(Object *, const EventObject &, void *); using ConstFunctionPointer = void (*)(const Object *, const EventObject &, void *); using DeleteDataFunctionPointer = void (*)(void *); - + /** @ITKEndGrouping */ /** Standard class type aliases. */ using Self = CStyleCommand; using Pointer = SmartPointer; @@ -378,11 +380,12 @@ class ITKCommon_EXPORT CStyleCommand : public Command SetClientData(void * cd); /** Set the C callback function pointer to be called at Execute time. */ + /** @ITKStartGrouping */ void SetCallback(FunctionPointer f); void SetConstCallback(ConstFunctionPointer f); - + /** @ITKEndGrouping */ /** Set the callback to delete the client data. */ void SetClientDataDeleteCallback(DeleteDataFunctionPointer f); diff --git a/Modules/Core/Common/include/itkCommonEnums.h b/Modules/Core/Common/include/itkCommonEnums.h index c23f62bf776..44e51474159 100644 --- a/Modules/Core/Common/include/itkCommonEnums.h +++ b/Modules/Core/Common/include/itkCommonEnums.h @@ -40,7 +40,6 @@ class CommonEnums public: // Used in Input/Output for Images/Mesh/Transform types /** - * \class IOPixel * \ingroup ITKCommon * Enums used to manipulate the point/cell pixel type. The pixel type provides * context for automatic data conversions (for instance, RGB to @@ -67,7 +66,6 @@ class CommonEnums }; /** - * \class IOComponent * \ingroup ITKCommon * Enums used to manipulate the component type. The component type * refers to the actual storage class associated with either a @@ -92,7 +90,6 @@ class CommonEnums }; /** - * \class IOFile * \ingroup ITKCommon * Enums used to specify write style: whether binary or ASCII. Some * subclasses use this, some ignore it. @@ -108,7 +105,6 @@ class CommonEnums }; /** - * \class IOFileMode * \ingroup ITKCommon * Mode in which the files is intended to be used */ @@ -119,7 +115,6 @@ class CommonEnums }; /** - * \class IOByteOrder * \ingroup ITKCommon * Enums used to specify byte order; whether Big Endian or Little Endian. * Some subclasses use this, some ignore it. @@ -132,7 +127,6 @@ class CommonEnums }; /** - * \class CellGeometry * \ingroup ITKCommon * Enums used to specify cell type */ enum class CellGeometry : uint8_t @@ -170,6 +164,7 @@ using IOFileModeType = CommonEnums::IOFileMode; using IOByteOrderType = CommonEnums::IOByteOrder; using CellGeometryType = CommonEnums::CellGeometry; #endif + // Define how to print enumeration extern ITKCommon_EXPORT std::ostream & operator<<(std::ostream & out, IOPixelEnum value); @@ -190,7 +185,7 @@ extern ITKCommon_EXPORT std::ostream & class MeshEnums { public: - /** \class MeshClassCellsAllocationMethod + /** * \ingroup ITKCommon * Enum defining the possible methods used to allocate memory for * the Cells */ @@ -212,19 +207,20 @@ class OctreeEnums { public: /** - * \class Octree * \ingroup ITKCommon * The enumeration to define the planar orientation of the octree */ enum class Octree : uint8_t { - UNKNOWN_PLANE, ///< The plane is Unknown - SAGITAL_PLANE, ///< The plane is Sagittal + UNKNOWN_PLANE, ///< The plane is Unknown + SAGITTAL_PLANE, ///< The plane is Sagittal +#if !defined(ITK_LEGACY_REMOVE) + SAGITAL_PLANE [[deprecated("Use SAGITTAL_PLANE instead")]] = SAGITTAL_PLANE, ///< Support misspelling +#endif CORONAL_PLANE, ///< The plane is Coronal TRANSVERSE_PLANE ///< The plane is Transverse }; - /*** - * \class LeafIdentifier + /** * \ingroup ITKCommon */ enum class LeafIdentifier : uint8_t @@ -251,7 +247,7 @@ extern ITKCommon_EXPORT std::ostream & class ObjectEnums { public: - /** \class RegionEnum + /** * \ingroup ITKCommon * Enums used to describe the extent types. */ enum class RegionEnum : uint8_t @@ -270,10 +266,9 @@ extern ITKCommon_EXPORT std::ostream & class ObjectFactoryEnums { public: - /** \class InsertionPosition - * \ingroup ITKCommon - * Position at which the new factory will be registered in the - * internal factory container. + /** \ingroup ITKCommon + * Position at which the new factory will be registered in the + * internal factory container. */ enum class InsertionPosition : uint8_t { diff --git a/Modules/Core/Common/include/itkCompensatedSummation.h b/Modules/Core/Common/include/itkCompensatedSummation.h index 3cefc4ad1a3..9b3ac86f61e 100644 --- a/Modules/Core/Common/include/itkCompensatedSummation.h +++ b/Modules/Core/Common/include/itkCompensatedSummation.h @@ -76,34 +76,38 @@ class ITK_TEMPLATE_EXPORT CompensatedSummation using Self = CompensatedSummation; /** Constructors. */ + /** @ITKStartGrouping */ CompensatedSummation() = default; CompensatedSummation(FloatType value); - + /** @ITKEndGrouping */ /** Copy constructor. */ - CompensatedSummation(const Self & rhs); + CompensatedSummation(const Self &) = default; + /** Assignment operator. */ Self & - operator=(const Self & rhs); + operator=(const Self &) = default; /** Add an element to the sum. */ + /** @ITKStartGrouping */ void AddElement(const FloatType & element); Self & operator+=(const FloatType & rhs); Self & operator+=(const Self & rhs); - + /** @ITKEndGrouping */ /** Subtract an element from the sum. */ Self & operator-=(const FloatType & rhs); /** Division and multiplication. These do not provide any numerical advantages * relative to vanilla division and multiplication. */ + /** @ITKStartGrouping */ Self & operator*=(const FloatType & rhs); Self & operator/=(const FloatType & rhs); - + /** @ITKEndGrouping */ /** Reset the sum and compensation to zero. */ void ResetToZero(); @@ -117,22 +121,21 @@ class ITK_TEMPLATE_EXPORT CompensatedSummation GetSum() const; /** explicit conversion */ - explicit operator FloatType() const; + explicit + operator FloatType() const; private: AccumulateType m_Sum{}; AccumulateType m_Compensation{}; -// Maybe support more types in the future with template specialization. -#ifdef ITK_USE_CONCEPT_CHECKING + // Maybe support more types in the future with template specialization. itkConceptMacro(OnlyDefinedForFloatingPointTypes, (itk::Concept::IsFloatingPoint)); -#endif // ITK_USE_CONCEPT_CHECKING }; void ITKCommon_EXPORT - CompensatedSummationAddElement(float & compensation, float & sum, const float element); +CompensatedSummationAddElement(float & compensation, float & sum, const float element); void ITKCommon_EXPORT - CompensatedSummationAddElement(double & compensation, double & sum, const double element); +CompensatedSummationAddElement(double & compensation, double & sum, const double element); } // end namespace itk diff --git a/Modules/Core/Common/include/itkCompensatedSummation.hxx b/Modules/Core/Common/include/itkCompensatedSummation.hxx index c3a644772e1..66c924d55b9 100644 --- a/Modules/Core/Common/include/itkCompensatedSummation.hxx +++ b/Modules/Core/Common/include/itkCompensatedSummation.hxx @@ -23,9 +23,9 @@ namespace itk { void ITKCommon_EXPORT - CompensatedSummationAddElement(float & compensation, float & sum, const float element); +CompensatedSummationAddElement(float & compensation, float & sum, const float element); void ITKCommon_EXPORT - CompensatedSummationAddElement(double & compensation, double & sum, const double element); +CompensatedSummationAddElement(double & compensation, double & sum, const double element); #ifndef itkCompensatedSummation_cxx // We try the looser pragma guards if we don't have an explicit instantiation. @@ -64,25 +64,6 @@ CompensatedSummation::CompensatedSummation(const TFloat value) , m_Compensation(AccumulateType{}) {} -template -CompensatedSummation::CompensatedSummation(const Self & rhs) -{ - this->m_Sum = rhs.m_Sum; - this->m_Compensation = rhs.m_Compensation; -} - -template -auto -CompensatedSummation::operator=(const Self & rhs) -> Self & -{ - if (this != &rhs) - { - this->m_Sum = rhs.m_Sum; - this->m_Compensation = rhs.m_Compensation; - } - return *this; -} - template void CompensatedSummation::AddElement(const FloatType & element) diff --git a/Modules/Core/Common/include/itkConceptChecking.h b/Modules/Core/Common/include/itkConceptChecking.h index 6dd565f4435..44d00d6f640 100644 --- a/Modules/Core/Common/include/itkConceptChecking.h +++ b/Modules/Core/Common/include/itkConceptChecking.h @@ -76,6 +76,7 @@ * run-time overhead. The "vtable" approach was invented for this * project by Brad King at Kitware. */ +/** @ITKStartGrouping */ # define itkConceptConstraintsMacro() \ virtual void Enforcer() { &Constraints::constraints; } # define itkConceptMacro(name, concept) \ @@ -83,7 +84,7 @@ { \ name = sizeof concept \ } - +/** @ITKEndGrouping */ #elif defined(ITK_CONCEPT_IMPLEMENTATION_CALL) /** Not implemented. */ @@ -112,6 +113,7 @@ namespace itk namespace. */ namespace Concept { + /** * Some concept implementation details are adapted from the BOOST C++ * libraries (www.boost.org). These are marked with "(BOOST)" in the @@ -140,7 +142,8 @@ struct UniqueType_bool * warning. (BOOST) */ template -inline void IgnoreUnusedVariable(T) +inline void +IgnoreUnusedVariable(T) {} /** @@ -152,7 +155,7 @@ template void RequireBooleanExpression(const T & t) { - bool x = t; + const bool x = t; IgnoreUnusedVariable(x); } @@ -648,7 +651,7 @@ struct Signed void constraints() { - SignedT a = TrueT(); + const SignedT a = TrueT(); Detail::IgnoreUnusedVariable(a); } @@ -666,7 +669,7 @@ struct SameType void constraints() { - Detail::UniqueType a = Detail::UniqueType(); + const Detail::UniqueType a = Detail::UniqueType(); Detail::IgnoreUnusedVariable(a); } }; @@ -684,7 +687,7 @@ struct SameDimension void constraints() { - DT1 a = DT2(); + DT1 const a = DT2(); Detail::IgnoreUnusedVariable(a); } @@ -701,6 +704,7 @@ struct HasNumericTraits void constraints() { + // This is here to cause compile-time failures, if a provided custom type is missing some methods. Detail::UniqueType::ValueType>(); Detail::UniqueType::PrintType>(); Detail::UniqueType::AbsType>(); @@ -708,6 +712,7 @@ struct HasNumericTraits Detail::UniqueType::RealType>(); Detail::UniqueType::ScalarRealType>(); Detail::UniqueType::FloatType>(); + T a{}; // Test these methods that take an instance of T to @@ -738,7 +743,7 @@ struct HasPixelTraits constraints() { Detail::UniqueType::ValueType>(); - unsigned int a = PixelTraits::Dimension; + const unsigned int a = PixelTraits::Dimension; Detail::IgnoreUnusedVariable(a); } }; @@ -806,7 +811,9 @@ struct SameDimensionOrMinusOne using Type1 = Detail::UniqueType_unsigned_int; using Type2 = Detail::UniqueType_unsigned_int; - void f(Type1) {} + void + f(Type1) + {} void f(Type2, int = 0) {} @@ -814,7 +821,7 @@ struct SameDimensionOrMinusOne void constraints() { - Detail::UniqueType_unsigned_int tt; + const Detail::UniqueType_unsigned_int tt; this->f(tt); } }; @@ -831,7 +838,9 @@ struct SameDimensionOrMinusOneOrTwo using Type2 = Detail::UniqueType_unsigned_int; using Type3 = Detail::UniqueType_unsigned_int; - void f(Type1) {} + void + f(Type1) + {} void f(Type2, int = 0) {} @@ -842,7 +851,7 @@ struct SameDimensionOrMinusOneOrTwo void constraints() { - Detail::UniqueType_unsigned_int tt; + constexpr Detail::UniqueType_unsigned_int tt; this->f(tt); } }; @@ -862,7 +871,7 @@ struct IsInteger void constraints() { - IntegralT a = TrueT(); + const IntegralT a = TrueT(); Detail::IgnoreUnusedVariable(a); } @@ -885,7 +894,7 @@ struct IsUnsignedInteger void constraints() { - UnsignedT a = TrueT(); + const UnsignedT a = TrueT(); Detail::IgnoreUnusedVariable(a); } @@ -932,8 +941,8 @@ struct IsFloatingPoint void constraints() { - IntegralT a = FalseT(); - ExactT b = FalseT(); + const IntegralT a = FalseT(); + const ExactT b = FalseT(); Detail::IgnoreUnusedVariable(a); Detail::IgnoreUnusedVariable(b); diff --git a/Modules/Core/Common/include/itkConicShellInteriorExteriorSpatialFunction.h b/Modules/Core/Common/include/itkConicShellInteriorExteriorSpatialFunction.h index 07b79d5248b..ade439dac09 100644 --- a/Modules/Core/Common/include/itkConicShellInteriorExteriorSpatialFunction.h +++ b/Modules/Core/Common/include/itkConicShellInteriorExteriorSpatialFunction.h @@ -89,10 +89,12 @@ class ITK_TEMPLATE_EXPORT ConicShellInteriorExteriorSpatialFunction Evaluate(const InputType & position) const override; /** Set/Get the origin of the function. */ + /** @ITKStartGrouping */ itkGetConstMacro(Origin, InputType); itkSetMacro(Origin, InputType); - + /** @ITKEndGrouping */ /** Set/Get the gradient at the origin of the function. */ + /** @ITKStartGrouping */ GradientType GetOriginGradient() { @@ -100,26 +102,30 @@ class ITK_TEMPLATE_EXPORT ConicShellInteriorExteriorSpatialFunction } void SetOriginGradient(GradientType grad); - + /** @ITKEndGrouping */ /** Set/Get the minimum search distance. */ + /** @ITKStartGrouping */ itkGetConstMacro(DistanceMin, double); itkSetMacro(DistanceMin, double); - + /** @ITKEndGrouping */ /** Set/Get the maximum search distance. */ + /** @ITKStartGrouping */ itkGetConstMacro(DistanceMax, double); itkSetMacro(DistanceMax, double); - + /** @ITKEndGrouping */ /** Set/Get the tolerance of the in/out comparison. */ + /** @ITKStartGrouping */ itkGetConstMacro(Epsilon, double); itkSetMacro(Epsilon, double); - + /** @ITKEndGrouping */ /** Set/Get direction along the gradient to search. * Set to true to use the direction that the gradient is pointing; * set to false for the opposite direction. */ + /** @ITKStartGrouping */ itkGetConstMacro(Polarity, bool); itkSetMacro(Polarity, bool); itkBooleanMacro(Polarity); - + /** @ITKEndGrouping */ protected: ConicShellInteriorExteriorSpatialFunction() = default; ~ConicShellInteriorExteriorSpatialFunction() override = default; diff --git a/Modules/Core/Common/include/itkConicShellInteriorExteriorSpatialFunction.hxx b/Modules/Core/Common/include/itkConicShellInteriorExteriorSpatialFunction.hxx index 52676d0e03e..eaa9624119c 100644 --- a/Modules/Core/Common/include/itkConicShellInteriorExteriorSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkConicShellInteriorExteriorSpatialFunction.hxx @@ -41,8 +41,7 @@ ConicShellInteriorExteriorSpatialFunction::Evaluate(const In VectorType vecOriginToTest = position - m_Origin; // Compute the length of this vector - // double vecDistance = vecOriginToTest.GetVnlVector().magnitude(); - double vecDistance = vecOriginToTest.GetNorm(); + const double vecDistance = vecOriginToTest.GetNorm(); // Check to see if this an allowed distance if (!((vecDistance > m_DistanceMin) && (vecDistance < m_DistanceMax))) @@ -54,7 +53,7 @@ ConicShellInteriorExteriorSpatialFunction::Evaluate(const In vecOriginToTest.Normalize(); // Create a temp vector to get around const problems - GradientType originGradient = m_OriginGradient; + const GradientType originGradient = m_OriginGradient; // Now compute the dot product double dotprod = originGradient * vecOriginToTest; @@ -84,16 +83,15 @@ ConicShellInteriorExteriorSpatialFunction::PrintSelf(std::os { Superclass::PrintSelf(os, indent); - unsigned int i; os << indent << "Origin: ["; - for (i = 0; i < VDimension - 1; ++i) + for (unsigned int i = 0; i < VDimension - 1; ++i) { os << m_Origin[i] << ", "; } os << ']' << std::endl; os << indent << "Gradient at origin: ["; - for (i = 0; i < VDimension - 1; ++i) + for (unsigned int i = 0; i < VDimension - 1; ++i) { os << m_OriginGradient[i] << ", "; } diff --git a/Modules/Core/Common/include/itkConnectedComponentAlgorithm.h b/Modules/Core/Common/include/itkConnectedComponentAlgorithm.h index 176708f0de7..165787eef5c 100644 --- a/Modules/Core/Common/include/itkConnectedComponentAlgorithm.h +++ b/Modules/Core/Common/include/itkConnectedComponentAlgorithm.h @@ -27,13 +27,13 @@ template TIterator * setConnectivity(TIterator * it, bool fullyConnected = false) { - typename TIterator::OffsetType offset; + it->ClearActiveList(); if (!fullyConnected) { // only activate the neighbors that are face connected // to the current pixel. do not include the center pixel - offset.Fill(0); + typename TIterator::OffsetType offset{}; for (unsigned int d = 0; d < TIterator::Dimension; ++d) { offset[d] = -1; @@ -47,14 +47,14 @@ setConnectivity(TIterator * it, bool fullyConnected = false) { // activate all neighbors that are face+edge+vertex // connected to the current pixel. do not include the center pixel - unsigned int centerIndex = it->GetCenterNeighborhoodIndex(); + const unsigned int centerIndex = it->GetCenterNeighborhoodIndex(); for (unsigned int d = 0; d < centerIndex * 2 + 1; ++d) { - offset = it->GetOffset(d); + const typename TIterator::OffsetType offset = it->GetOffset(d); it->ActivateOffset(offset); } - offset.Fill(0); - it->DeactivateOffset(offset); + const typename TIterator::OffsetType offset_zeros{}; + it->DeactivateOffset(offset_zeros); } return it; } @@ -64,13 +64,12 @@ TIterator * setConnectivityPrevious(TIterator * it, bool fullyConnected = false) { // activate the "previous" neighbours - typename TIterator::OffsetType offset; it->ClearActiveList(); if (!fullyConnected) { // only activate the neighbors that are face connected // to the current pixel. do not include the center pixel - offset.Fill(0); + typename TIterator::OffsetType offset{}; for (unsigned int d = 0; d < TIterator::Dimension; ++d) { offset[d] = -1; @@ -82,14 +81,14 @@ setConnectivityPrevious(TIterator * it, bool fullyConnected = false) { // activate all neighbors that are face+edge+vertex // connected to the current pixel. do not include the center pixel - unsigned int centerIndex = it->GetCenterNeighborhoodIndex(); + const unsigned int centerIndex = it->GetCenterNeighborhoodIndex(); for (unsigned int d = 0; d < centerIndex; ++d) { - offset = it->GetOffset(d); + const typename TIterator::OffsetType offset = it->GetOffset(d); it->ActivateOffset(offset); } - offset.Fill(0); - it->DeactivateOffset(offset); + const typename TIterator::OffsetType offset_zeros{}; + it->DeactivateOffset(offset_zeros); } return it; } @@ -99,13 +98,13 @@ TIterator * setConnectivityLater(TIterator * it, bool fullyConnected = false) { // activate the "later" neighbours - typename TIterator::OffsetType offset; + it->ClearActiveList(); if (!fullyConnected) { // only activate the neighbors that are face connected // to the current pixel. do not include the center pixel - offset.Fill(0); + typename TIterator::OffsetType offset{}; for (unsigned int d = 0; d < TIterator::Dimension; ++d) { offset[d] = 1; @@ -117,14 +116,14 @@ setConnectivityLater(TIterator * it, bool fullyConnected = false) { // activate all neighbors that are face+edge+vertex // connected to the current pixel. do not include the center pixel - unsigned int centerIndex = it->GetCenterNeighborhoodIndex(); + const unsigned int centerIndex = it->GetCenterNeighborhoodIndex(); for (unsigned int d = centerIndex + 1; d < 2 * centerIndex + 1; ++d) { - offset = it->GetOffset(d); + const typename TIterator::OffsetType offset = it->GetOffset(d); it->ActivateOffset(offset); } - offset.Fill(0); - it->DeactivateOffset(offset); + const typename TIterator::OffsetType offset_zeros{}; + it->DeactivateOffset(offset_zeros); } return it; } diff --git a/Modules/Core/Common/include/itkConnectedImageNeighborhoodShape.h b/Modules/Core/Common/include/itkConnectedImageNeighborhoodShape.h index 19eb29a0a12..714631620a2 100644 --- a/Modules/Core/Common/include/itkConnectedImageNeighborhoodShape.h +++ b/Modules/Core/Common/include/itkConnectedImageNeighborhoodShape.h @@ -107,7 +107,6 @@ class ConnectedImageNeighborhoodShape , m_NumberOfOffsets{ CalculateNumberOfOffsets(maximumCityblockDistance, includeCenterPixel) } {} - /** Returns the number of offsets needed for this shape. */ constexpr size_t GetNumberOfOffsets() const noexcept @@ -196,8 +195,9 @@ class ConnectedImageNeighborhoodShape static constexpr uintmax_t CalculateBinomialCoefficient(const uintmax_t n, const uintmax_t k) noexcept { - return (k > n) ? (assert(!"Out of range!"), 0) - : (k == 0) ? 1 : Math::UnsignedProduct(n, CalculateBinomialCoefficient(n - 1, k - 1)) / k; + return (k > n) ? (assert(!"Out of range!"), 0) + : (k == 0) ? 1 + : Math::UnsignedProduct(n, CalculateBinomialCoefficient(n - 1, k - 1)) / k; } @@ -248,7 +248,6 @@ class ConnectedImageNeighborhoodShape } }; - /** Generates the offsets for a connected image neighborhood shape. */ template auto diff --git a/Modules/Core/Common/include/itkConstNeighborhoodIterator.h b/Modules/Core/Common/include/itkConstNeighborhoodIterator.h index ca856039f54..a873e185b16 100644 --- a/Modules/Core/Common/include/itkConstNeighborhoodIterator.h +++ b/Modules/Core/Common/include/itkConstNeighborhoodIterator.h @@ -172,8 +172,8 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator /** Returns the N-dimensional index of the iterator's position in * the image. */ - ITK_ITERATOR_VIRTUAL IndexType - GetIndex() const ITK_ITERATOR_FINAL + IndexType + GetIndex() const { return m_Loop; } @@ -186,12 +186,12 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator /** Function that "dereferences" a ConstNeighborhoodIterator, * returning a Neighborhood of pixel values. */ - ITK_ITERATOR_VIRTUAL NeighborhoodType - GetNeighborhood() const ITK_ITERATOR_FINAL; + NeighborhoodType + GetNeighborhood() const; /** Returns the pixel value located at a linear array location i. */ - ITK_ITERATOR_VIRTUAL PixelType - GetPixel(const NeighborIndexType i) const ITK_ITERATOR_FINAL + PixelType + GetPixel(const NeighborIndexType i) const { if (!m_NeedToUseBoundaryCondition || this->InBounds()) { @@ -211,13 +211,13 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator * image and the pixel value returned is an actual pixel in the * image. Sets "IsInBounds" to false if the location is outside the * image and the pixel value returned is a boundary condition. */ - ITK_ITERATOR_VIRTUAL PixelType - GetPixel(NeighborIndexType i, bool & IsInBounds) const ITK_ITERATOR_FINAL; + PixelType + GetPixel(NeighborIndexType n, bool & IsInBounds) const; /** Returns the pixel value located at the itk::Offset o from the center of the neighborhood. */ - ITK_ITERATOR_VIRTUAL PixelType - GetPixel(const OffsetType & o) const ITK_ITERATOR_FINAL + PixelType + GetPixel(const OffsetType & o) const { bool inbounds; @@ -229,8 +229,8 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator * image and the pixel value returned is an actual pixel in the * image. Sets "IsInBounds" to false if the offset is outside the * image and the pixel value returned is a boundary condition. */ - ITK_ITERATOR_VIRTUAL PixelType - GetPixel(const OffsetType & o, bool & IsInBounds) const ITK_ITERATOR_FINAL + PixelType + GetPixel(const OffsetType & o, bool & IsInBounds) const { return (this->GetPixel(this->GetNeighborhoodIndex(o), IsInBounds)); } @@ -238,8 +238,8 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator /** Returns the pixel value located i pixels distant from the neighborhood * center in the positive specified "axis" direction. No bounds checking * is done on the size of the neighborhood. */ - ITK_ITERATOR_VIRTUAL PixelType - GetNext(const unsigned int axis, NeighborIndexType i) const ITK_ITERATOR_FINAL + PixelType + GetNext(const unsigned int axis, NeighborIndexType i) const { return (this->GetPixel(this->GetCenterNeighborhoodIndex() + (i * this->GetStride(axis)))); } @@ -247,8 +247,8 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator /** Returns the pixel value located one pixel distant from the neighborhood * center in the specified positive axis direction. No bounds checking is * done on the size of the neighborhood. */ - ITK_ITERATOR_VIRTUAL PixelType - GetNext(const unsigned int axis) const ITK_ITERATOR_FINAL + PixelType + GetNext(const unsigned int axis) const { return (this->GetPixel(this->GetCenterNeighborhoodIndex() + this->GetStride(axis))); } @@ -256,8 +256,8 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator /** Returns the pixel value located i pixels distant from the neighborhood * center in the negative specified "axis" direction. No bounds checking * is done on the size of the neighborhood. */ - ITK_ITERATOR_VIRTUAL PixelType - GetPrevious(const unsigned int axis, NeighborIndexType i) const ITK_ITERATOR_FINAL + PixelType + GetPrevious(const unsigned int axis, NeighborIndexType i) const { return (this->GetPixel(this->GetCenterNeighborhoodIndex() - (i * this->GetStride(axis)))); } @@ -265,24 +265,24 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator /** Returns the pixel value located one pixel distant from the neighborhood * center in the specified negative axis direction. No bounds checking is * done on the size of the neighborhood. */ - ITK_ITERATOR_VIRTUAL PixelType - GetPrevious(const unsigned int axis) const ITK_ITERATOR_FINAL + PixelType + GetPrevious(const unsigned int axis) const { return (this->GetPixel(this->GetCenterNeighborhoodIndex() - this->GetStride(axis))); } /** Returns the image index for neighbor pixel at offset o from the center of the neighborhood. */ - ITK_ITERATOR_VIRTUAL IndexType - GetIndex(const OffsetType & o) const ITK_ITERATOR_FINAL + IndexType + GetIndex(const OffsetType & o) const { return (this->GetIndex() + o); } /** Returns the image index for neighbor pixel at index i in the neighborhood. */ - ITK_ITERATOR_VIRTUAL IndexType - GetIndex(NeighborIndexType i) const ITK_ITERATOR_FINAL + IndexType + GetIndex(NeighborIndexType i) const { return (this->GetIndex() + this->GetOffset(i)); } @@ -326,31 +326,31 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator } /** Method for rewinding the iterator to its beginning pixel. */ - ITK_ITERATOR_VIRTUAL void - GoToBegin() ITK_ITERATOR_FINAL; + void + GoToBegin(); /** Method for sending the iterator to one past the last pixel in its * region. */ - ITK_ITERATOR_VIRTUAL void - GoToEnd() ITK_ITERATOR_FINAL; + void + GoToEnd(); /** Initializes the iterator to walk a particular image and a particular * region of that image. */ - ITK_ITERATOR_VIRTUAL void - Initialize(const SizeType & radius, const ImageType * ptr, const RegionType & region) ITK_ITERATOR_FINAL; + void + Initialize(const SizeType & radius, const ImageType * ptr, const RegionType & region); /** Method for determining whether the iterator is at the * beginning of its iteration region. */ - ITK_ITERATOR_VIRTUAL bool - IsAtBegin() const ITK_ITERATOR_FINAL + bool + IsAtBegin() const { return (this->GetCenterPointer() == m_Begin); } /** Method for determining whether the iterator has reached the * end of its iteration region. */ - ITK_ITERATOR_VIRTUAL bool - IsAtEnd() const ITK_ITERATOR_FINAL + bool + IsAtEnd() const { if (this->GetCenterPointer() > m_End) { @@ -486,16 +486,16 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator * object during the time it is referenced. The overriding condition * can be of a different type than the default type as long as it is * a subclass of ImageBoundaryCondition. */ - ITK_ITERATOR_VIRTUAL void - OverrideBoundaryCondition(const ImageBoundaryConditionPointerType i) ITK_ITERATOR_FINAL + void + OverrideBoundaryCondition(const ImageBoundaryConditionPointerType i) { m_BoundaryCondition = i; } /** Resets the boundary condition to the internal, default conditions * specified by the template parameter. */ - ITK_ITERATOR_VIRTUAL void - ResetBoundaryCondition() ITK_ITERATOR_FINAL + void + ResetBoundaryCondition() { m_BoundaryCondition = &m_InternalBoundaryCondition; } @@ -540,14 +540,14 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator } /** Set the region to iterate over. */ - ITK_ITERATOR_VIRTUAL void - SetRegion(const RegionType & region) ITK_ITERATOR_FINAL; + void + SetRegion(const RegionType & region); protected: /** Default method for setting the coordinate location of the iterator. * Loop indices correspond to the actual Image region index. */ - ITK_ITERATOR_VIRTUAL void - SetLoop(const IndexType & p) ITK_ITERATOR_FINAL + void + SetLoop(const IndexType & p) { m_Loop = p; m_IsInBoundsValid = false; @@ -556,28 +556,28 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIterator /** Method for setting internal loop boundaries. This * method must be defined in each subclass because * each subclass may handle loop boundaries differently. */ - ITK_ITERATOR_VIRTUAL void - SetBound(const SizeType &) ITK_ITERATOR_FINAL; + void + SetBound(const SizeType &); /** Default method for setting the values of the internal pointers * to itk::Image memory buffer locations. This method should * generally only be called when the iterator is initialized. * \sa SetLocation */ - ITK_ITERATOR_VIRTUAL void - SetPixelPointers(const IndexType &) ITK_ITERATOR_FINAL; + void + SetPixelPointers(const IndexType &); /** Default method for setting the index of the first pixel in the * iteration region. */ - ITK_ITERATOR_VIRTUAL void - SetBeginIndex(const IndexType & start) ITK_ITERATOR_FINAL + void + SetBeginIndex(const IndexType & start) { m_BeginIndex = start; } /** Default method for setting the index of the first pixel in the * iteration region. */ - ITK_ITERATOR_VIRTUAL void - SetEndIndex() ITK_ITERATOR_FINAL; + void + SetEndIndex(); /** The starting index for iteration within the itk::Image region * on which this ConstNeighborhoodIterator is defined. */ diff --git a/Modules/Core/Common/include/itkConstNeighborhoodIterator.hxx b/Modules/Core/Common/include/itkConstNeighborhoodIterator.hxx index 5dc14d96364..6432b206480 100644 --- a/Modules/Core/Common/include/itkConstNeighborhoodIterator.hxx +++ b/Modules/Core/Common/include/itkConstNeighborhoodIterator.hxx @@ -55,7 +55,7 @@ ConstNeighborhoodIterator::IndexInBounds(const Neigh { return true; } - else if (this->InBounds()) // Is this whole neighborhood in bounds? + if (this->InBounds()) // Is this whole neighborhood in bounds? { return true; } @@ -108,7 +108,7 @@ ConstNeighborhoodIterator::IndexInBounds(const Neigh { return true; } - else if (this->InBounds()) // Is this whole neighborhood in bounds? + if (this->InBounds()) // Is this whole neighborhood in bounds? { return true; } @@ -162,22 +162,19 @@ ConstNeighborhoodIterator::GetPixel(NeighborIndexTyp IsInBounds = true; return (m_NeighborhoodAccessorFunctor.Get(this->operator[](n))); } + + OffsetType offset; + OffsetType internalIndex; + const bool flag = this->IndexInBounds(n, internalIndex, offset); + if (flag) + { + IsInBounds = true; + return (m_NeighborhoodAccessorFunctor.Get(this->operator[](n))); + } else { - bool flag; - OffsetType offset, internalIndex; - - flag = this->IndexInBounds(n, internalIndex, offset); - if (flag) - { - IsInBounds = true; - return (m_NeighborhoodAccessorFunctor.Get(this->operator[](n))); - } - else - { - IsInBounds = false; - return (m_NeighborhoodAccessorFunctor.BoundaryCondition(internalIndex, offset, this, this->m_BoundaryCondition)); - } + IsInBounds = false; + return (m_NeighborhoodAccessorFunctor.BoundaryCondition(internalIndex, offset, this, this->m_BoundaryCondition)); } } @@ -188,7 +185,7 @@ ConstNeighborhoodIterator::ComputeInternalIndex(cons { OffsetType ans; auto r = static_cast(n); - for (long i = static_cast(Dimension) - 1; i >= 0; --i) + for (long i = long{ Dimension } - 1; i >= 0; --i) { ans[i] = static_cast(r / this->GetStride(i)); r = r % this->GetStride(i); @@ -200,8 +197,8 @@ template auto ConstNeighborhoodIterator::GetBoundingBoxAsImageRegion() const -> RegionType { - const IndexValueType zero{}; - const RegionType ans(this->GetIndex(zero), this->GetSize()); + constexpr IndexValueType zero{}; + const RegionType ans(this->GetIndex(zero), this->GetSize()); return ans; } @@ -267,32 +264,31 @@ template auto ConstNeighborhoodIterator::GetNeighborhood() const -> NeighborhoodType { - OffsetType OverlapLow, OverlapHigh, temp, offset; - const ConstIterator _end = this->End(); - NeighborhoodType ans; - - typename NeighborhoodType::Iterator ansIt; - ConstIterator thisIt; + NeighborhoodType ans; ans.SetRadius(this->GetRadius()); - if (m_NeedToUseBoundaryCondition == false) { - for (ansIt = ans.Begin(), thisIt = this->Begin(); thisIt < _end; ++ansIt, ++thisIt) + ConstIterator thisIt = this->Begin(); + for (typename NeighborhoodType::Iterator ansIt = ans.Begin(); thisIt < _end; ++ansIt, ++thisIt) { *ansIt = m_NeighborhoodAccessorFunctor.Get(*thisIt); } } else if (InBounds()) { - for (ansIt = ans.Begin(), thisIt = this->Begin(); thisIt < _end; ++ansIt, ++thisIt) + ConstIterator thisIt = this->Begin(); + for (typename NeighborhoodType::Iterator ansIt = ans.Begin(); thisIt < _end; ++ansIt, ++thisIt) { *ansIt = m_NeighborhoodAccessorFunctor.Get(*thisIt); } } else { + OffsetType temp; + OffsetType OverlapHigh; + OffsetType OverlapLow; // Calculate overlap & initialize index for (DimensionValueType i = 0; i < Dimension; ++i) { @@ -302,11 +298,13 @@ ConstNeighborhoodIterator::GetNeighborhood() const - } // Iterate through neighborhood - for (ansIt = ans.Begin(), thisIt = this->Begin(); thisIt < _end; ++ansIt, ++thisIt) + ConstIterator thisIt = this->Begin(); + for (typename NeighborhoodType::Iterator ansIt = ans.Begin(); thisIt < _end; ++ansIt, ++thisIt) { bool flag = true; // Is this pixel in bounds? + OffsetType offset; for (DimensionValueType i = 0; i < Dimension; ++i) { if (m_InBounds[i]) @@ -486,7 +484,6 @@ template ConstNeighborhoodIterator & ConstNeighborhoodIterator::operator++() { - Iterator it; const Iterator _end = Superclass::End(); // Repositioning neighborhood, previous bounds check on neighborhood @@ -494,7 +491,7 @@ ConstNeighborhoodIterator::operator++() m_IsInBoundsValid = false; // Increment pointers. - for (it = Superclass::Begin(); it < _end; ++it) + for (Iterator it = Superclass::Begin(); it < _end; ++it) { (*it)++; } @@ -506,7 +503,7 @@ ConstNeighborhoodIterator::operator++() if (m_Loop[i] == m_Bound[i]) { m_Loop[i] = m_BeginIndex[i]; - for (it = Superclass::Begin(); it < _end; ++it) + for (Iterator it = Superclass::Begin(); it < _end; ++it) { (*it) += m_WrapOffset[i]; } @@ -523,7 +520,6 @@ template ConstNeighborhoodIterator & ConstNeighborhoodIterator::operator--() { - Iterator it; const Iterator _end = Superclass::End(); // Repositioning neighborhood, previous bounds check on neighborhood @@ -531,7 +527,7 @@ ConstNeighborhoodIterator::operator--() m_IsInBoundsValid = false; // Decrement pointers. - for (it = Superclass::Begin(); it < _end; ++it) + for (Iterator it = Superclass::Begin(); it < _end; ++it) { (*it)--; } @@ -542,7 +538,7 @@ ConstNeighborhoodIterator::operator--() if (m_Loop[i] == m_BeginIndex[i]) { m_Loop[i] = m_Bound[i] - 1; - for (it = Superclass::Begin(); it < _end; ++it) + for (Iterator it = Superclass::Begin(); it < _end; ++it) { (*it) -= m_WrapOffset[i]; } @@ -562,45 +558,43 @@ ConstNeighborhoodIterator::PrintSelf(std::ostream & { Superclass::PrintSelf(os, indent); - DimensionValueType i; - os << indent; os << "ConstNeighborhoodIterator {this= " << this; os << ", m_Region = { Start = {"; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_Region.GetIndex()[i] << ' '; } os << "}, Size = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_Region.GetSize()[i] << ' '; } os << "} }"; os << ", m_BeginIndex = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_BeginIndex[i] << ' '; } os << "} , m_EndIndex = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_EndIndex[i] << ' '; } os << "} , m_Loop = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_Loop[i] << ' '; } os << "}, m_Bound = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_Bound[i] << ' '; } os << "}, m_IsInBounds = {" << m_IsInBounds; os << "}, m_IsInBoundsValid = {" << m_IsInBoundsValid; os << "}, m_WrapOffset = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_WrapOffset[i] << ' '; } @@ -609,12 +603,12 @@ ConstNeighborhoodIterator::PrintSelf(std::ostream & os << '}' << std::endl; os << indent << ", m_InnerBoundsLow = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_InnerBoundsLow[i] << ' '; } os << "}, m_InnerBoundsHigh = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_InnerBoundsHigh[i] << ' '; } @@ -650,35 +644,27 @@ void ConstNeighborhoodIterator::SetPixelPointers(const IndexType & pos) { const Iterator _end = Superclass::End(); - InternalPixelType * Iit; auto * ptr = const_cast(m_ConstImage.GetPointer()); const SizeType size = this->GetSize(); const OffsetValueType * OffsetTable = m_ConstImage->GetOffsetTable(); const SizeType radius = this->GetRadius(); - DimensionValueType i; - Iterator Nit; - SizeType loop; - - for (i = 0; i < Dimension; ++i) - { - loop[i] = 0; - } + SizeType loop{}; // Find first "upper-left-corner" pixel address of neighborhood - Iit = ptr->GetBufferPointer() + ptr->ComputeOffset(pos); + InternalPixelType * Iit = ptr->GetBufferPointer() + ptr->ComputeOffset(pos); - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { Iit -= radius[i] * OffsetTable[i]; } // Compute the rest of the pixel addresses - for (Nit = Superclass::Begin(); Nit != _end; ++Nit) + for (Iterator Nit = Superclass::Begin(); Nit != _end; ++Nit) { *Nit = Iit; ++Iit; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { loop[i]++; if (loop[i] == size[i]) @@ -702,7 +688,6 @@ template ConstNeighborhoodIterator & ConstNeighborhoodIterator::operator+=(const OffsetType & idx) { - Iterator it; const Iterator _end = this->End(); OffsetValueType accumulator = 0; const OffsetValueType * stride = this->GetImagePointer()->GetOffsetTable(); @@ -725,7 +710,7 @@ ConstNeighborhoodIterator::operator+=(const OffsetTy } // Increment pointers. - for (it = this->Begin(); it < _end; ++it) + for (Iterator it = this->Begin(); it < _end; ++it) { (*it) += accumulator; } @@ -740,7 +725,6 @@ template ConstNeighborhoodIterator & ConstNeighborhoodIterator::operator-=(const OffsetType & idx) { - Iterator it; const Iterator _end = this->End(); OffsetValueType accumulator = 0; const OffsetValueType * stride = this->GetImagePointer()->GetOffsetTable(); @@ -763,7 +747,7 @@ ConstNeighborhoodIterator::operator-=(const OffsetTy } // Increment pointers. - for (it = this->Begin(); it < _end; ++it) + for (Iterator it = this->Begin(); it < _end; ++it) { (*it) -= accumulator; } diff --git a/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.h b/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.h index 2a88242f8a4..234b93a3dd6 100644 --- a/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.h +++ b/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.h @@ -60,6 +60,8 @@ template class ITK_TEMPLATE_EXPORT ConstNeighborhoodIteratorWithOnlyIndex : public Neighborhood { public: + ITK_DEFAULT_COPY_AND_MOVE(ConstNeighborhoodIteratorWithOnlyIndex); + /** Type used to refer to space dimensions */ using DimensionValueType = unsigned int; @@ -94,17 +96,10 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIteratorWithOnlyIndex : public Neighb /** Virtual destructor */ ~ConstNeighborhoodIteratorWithOnlyIndex() override = default; - /** Copy constructor */ - ConstNeighborhoodIteratorWithOnlyIndex(const ConstNeighborhoodIteratorWithOnlyIndex &); - /** Constructor which establishes the region size, neighborhood, and image * over which to walk. */ ConstNeighborhoodIteratorWithOnlyIndex(const SizeType & radius, const ImageType * ptr, const RegionType & region); - /** Assignment operator */ - Self & - operator=(const Self & orig); - /** Standard itk print method */ void PrintSelf(std::ostream &, Indent) const override; @@ -138,24 +133,24 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIteratorWithOnlyIndex : public Neighb /** Returns the N-dimensional index of the iterator's position in * the image. */ - ITK_ITERATOR_VIRTUAL IndexType - GetIndex() const ITK_ITERATOR_FINAL + IndexType + GetIndex() const { return m_Loop; } /** Returns the image index for neighbor pixel at offset o from the center of the neighborhood. */ - ITK_ITERATOR_VIRTUAL IndexType - GetIndex(const OffsetType & o) const ITK_ITERATOR_FINAL + IndexType + GetIndex(const OffsetType & o) const { return (this->GetIndex() + o); } /** Returns the image index for neighbor pixel at index i in the neighborhood. */ - ITK_ITERATOR_VIRTUAL IndexType - GetIndex(NeighborIndexType i) const ITK_ITERATOR_FINAL + IndexType + GetIndex(NeighborIndexType i) const { return (this->GetIndex() + this->GetOffset(i)); } @@ -181,31 +176,31 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIteratorWithOnlyIndex : public Neighb GetBoundingBoxAsImageRegion() const; /** Method for rewinding the iterator to its beginning image index. */ - ITK_ITERATOR_VIRTUAL void - GoToBegin() ITK_ITERATOR_FINAL; + void + GoToBegin(); /** Method for sending the iterator to one past the last index in its * region. */ - ITK_ITERATOR_VIRTUAL void - GoToEnd() ITK_ITERATOR_FINAL; + void + GoToEnd(); /** Initializes the iterator to walk a particular image and a particular * region of that image. */ - ITK_ITERATOR_VIRTUAL void - Initialize(const SizeType & radius, const ImageType * ptr, const RegionType & region) ITK_ITERATOR_FINAL; + void + Initialize(const SizeType & radius, const ImageType * ptr, const RegionType & region); /** Virtual method for determining whether the iterator is at the * beginning of its iteration region. */ - ITK_ITERATOR_VIRTUAL bool - IsAtBegin() const ITK_ITERATOR_FINAL + bool + IsAtBegin() const { return (this->GetIndex() == m_BeginIndex); } /** Virtual method for determining whether the iterator has reached the * end of its iteration region. */ - ITK_ITERATOR_VIRTUAL bool - IsAtEnd() const ITK_ITERATOR_FINAL; + bool + IsAtEnd() const; /** Increments the pointers in the ConstNeighborhoodIteratorWithOnlyIndex, * wraps across boundaries automatically, accounting for @@ -341,8 +336,8 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIteratorWithOnlyIndex : public Neighb protected: /** Default method for setting the coordinate location of the iterator. * Loop indices correspond to the actual Image region index. */ - ITK_ITERATOR_VIRTUAL void - SetLoop(const IndexType & p) ITK_ITERATOR_FINAL + void + SetLoop(const IndexType & p) { m_Loop = p; m_IsInBoundsValid = false; @@ -351,21 +346,21 @@ class ITK_TEMPLATE_EXPORT ConstNeighborhoodIteratorWithOnlyIndex : public Neighb /** Virtual method for setting internal loop boundaries. This * method must be defined in each subclass because * each subclass may handle loop boundaries differently. */ - ITK_ITERATOR_VIRTUAL void - SetBound(const SizeType &) ITK_ITERATOR_FINAL; + void + SetBound(const SizeType &); /** Default method for setting the first index of the * iteration region. */ - ITK_ITERATOR_VIRTUAL void - SetBeginIndex(const IndexType & start) ITK_ITERATOR_FINAL + void + SetBeginIndex(const IndexType & start) { m_BeginIndex = start; } /** Default method for setting the last index of the * iteration region. */ - ITK_ITERATOR_VIRTUAL void - SetEndIndex() ITK_ITERATOR_FINAL; + void + SetEndIndex(); /** The starting index for iteration within the itk::Image region * on which this ConstNeighborhoodIteratorWithOnlyIndex is defined. */ @@ -414,8 +409,7 @@ inline ConstNeighborhoodIteratorWithOnlyIndex operator+(const ConstNeighborhoodIteratorWithOnlyIndex & it, const typename ConstNeighborhoodIteratorWithOnlyIndex::OffsetType & ind) { - ConstNeighborhoodIteratorWithOnlyIndex ret; - ret = it; + ConstNeighborhoodIteratorWithOnlyIndex ret = it; ret += ind; return ret; } @@ -433,8 +427,7 @@ inline ConstNeighborhoodIteratorWithOnlyIndex operator-(const ConstNeighborhoodIteratorWithOnlyIndex & it, const typename ConstNeighborhoodIteratorWithOnlyIndex::OffsetType & ind) { - ConstNeighborhoodIteratorWithOnlyIndex ret; - ret = it; + ConstNeighborhoodIteratorWithOnlyIndex ret = it; ret -= ind; return ret; } diff --git a/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.hxx b/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.hxx index 2d87290e5aa..ede12d813ef 100644 --- a/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.hxx +++ b/Modules/Core/Common/include/itkConstNeighborhoodIteratorWithOnlyIndex.hxx @@ -57,7 +57,7 @@ ConstNeighborhoodIteratorWithOnlyIndex::IndexInBounds(const NeighborInde { return true; } - else if (this->InBounds()) // Is this whole neighborhood in bounds? + if (this->InBounds()) // Is this whole neighborhood in bounds? { return true; } @@ -108,7 +108,7 @@ ConstNeighborhoodIteratorWithOnlyIndex::ComputeInternalIndex(NeighborInd { OffsetType ans; auto r = static_cast(n); - for (long i = static_cast(Dimension) - 1; i >= 0; --i) + for (long i = long{ Dimension } - 1; i >= 0; --i) { ans[i] = static_cast(r / this->GetStride(i)); r = r % this->GetStride(i); @@ -120,36 +120,13 @@ template auto ConstNeighborhoodIteratorWithOnlyIndex::GetBoundingBoxAsImageRegion() const -> RegionType { - const IndexValueType zero{}; - const RegionType ans(this->GetIndex(zero), this->GetSize()); + constexpr IndexValueType zero{}; + const RegionType ans(this->GetIndex(zero), this->GetSize()); return ans; } -template -ConstNeighborhoodIteratorWithOnlyIndex::ConstNeighborhoodIteratorWithOnlyIndex(const Self & orig) - : Neighborhood(orig) -{ - m_Bound = orig.m_Bound; - m_BeginIndex = orig.m_BeginIndex; - m_ConstImage = orig.m_ConstImage; - m_EndIndex = orig.m_EndIndex; - m_Loop = orig.m_Loop; - m_Region = orig.m_Region; - - m_NeedToUseBoundaryCondition = orig.m_NeedToUseBoundaryCondition; - for (DimensionValueType i = 0; i < Dimension; ++i) - { - m_InBounds[i] = orig.m_InBounds[i]; - } - m_IsInBoundsValid = orig.m_IsInBoundsValid; - m_IsInBounds = orig.m_IsInBounds; - - m_InnerBoundsLow = orig.m_InnerBoundsLow; - m_InnerBoundsHigh = orig.m_InnerBoundsHigh; -} - template ConstNeighborhoodIteratorWithOnlyIndex::ConstNeighborhoodIteratorWithOnlyIndex(const SizeType & radius, const ImageType * ptr, @@ -235,36 +212,6 @@ ConstNeighborhoodIteratorWithOnlyIndex::Initialize(const SizeType & ra m_IsInBounds = false; } -template -ConstNeighborhoodIteratorWithOnlyIndex & -ConstNeighborhoodIteratorWithOnlyIndex::operator=(const Self & orig) -{ - if (this != &orig) - { - Superclass::operator=(orig); - - m_Bound = orig.m_Bound; - m_ConstImage = orig.m_ConstImage; - m_EndIndex = orig.m_EndIndex; - m_Loop = orig.m_Loop; - m_Region = orig.m_Region; - m_BeginIndex = orig.m_BeginIndex; - - m_NeedToUseBoundaryCondition = orig.m_NeedToUseBoundaryCondition; - - m_InnerBoundsLow = orig.m_InnerBoundsLow; - m_InnerBoundsHigh = orig.m_InnerBoundsHigh; - - for (DimensionValueType i = 0; i < Dimension; ++i) - { - m_InBounds[i] = orig.m_InBounds[i]; - } - m_IsInBoundsValid = orig.m_IsInBoundsValid; - m_IsInBounds = orig.m_IsInBounds; - } - return *this; -} - template bool ConstNeighborhoodIteratorWithOnlyIndex::operator<(const Self & it) const @@ -401,38 +348,36 @@ ConstNeighborhoodIteratorWithOnlyIndex::PrintSelf(std::ostream & os, Ind { Superclass::PrintSelf(os, indent); - DimensionValueType i; - os << indent; os << "ConstNeighborhoodIteratorWithOnlyIndex {this= " << this; os << ", m_Region = { Start = {"; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_Region.GetIndex()[i] << ' '; } os << "}, Size = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_Region.GetSize()[i] << ' '; } os << "} }"; os << ", m_BeginIndex = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_BeginIndex[i] << ' '; } os << "} , m_EndIndex = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_EndIndex[i] << ' '; } os << "} , m_Loop = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_Loop[i] << ' '; } os << "}, m_Bound = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_Bound[i] << ' '; } @@ -440,12 +385,12 @@ ConstNeighborhoodIteratorWithOnlyIndex::PrintSelf(std::ostream & os, Ind os << "}, m_IsInBoundsValid = {" << m_IsInBoundsValid; os << indent << ", m_InnerBoundsLow = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_InnerBoundsLow[i] << ' '; } os << "}, m_InnerBoundsHigh = { "; - for (i = 0; i < Dimension; ++i) + for (DimensionValueType i = 0; i < Dimension; ++i) { os << m_InnerBoundsHigh[i] << ' '; } diff --git a/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.h b/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.h index 5325e943a17..60313d23dbe 100644 --- a/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.h +++ b/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.h @@ -122,7 +122,7 @@ class ITK_TEMPLATE_EXPORT ConstShapedNeighborhoodIterator : private Neighborhood this->GoToBegin(); } - ITK_ITERATOR_VIRTUAL ~ConstIterator() = default; + ~ConstIterator() = default; ConstIterator & operator=(const ConstIterator & o) @@ -179,10 +179,8 @@ class ITK_TEMPLATE_EXPORT ConstShapedNeighborhoodIterator : private Neighborhood { return true; } - else - { - return false; - } + + return false; } void @@ -326,17 +324,18 @@ class ITK_TEMPLATE_EXPORT ConstShapedNeighborhoodIterator : private Neighborhood /** Add/Remove a neighborhood offset (from the center of the neighborhood) * to/from the active list. Active list offsets are the only locations * updated and accessible through the iterator. */ - ITK_ITERATOR_VIRTUAL void - ActivateOffset(const OffsetType & off) ITK_ITERATOR_FINAL + /** @ITKStartGrouping */ + void + ActivateOffset(const OffsetType & off) { this->ActivateIndex(Superclass::GetNeighborhoodIndex(off)); } - ITK_ITERATOR_VIRTUAL void - DeactivateOffset(const OffsetType & off) ITK_ITERATOR_FINAL + void + DeactivateOffset(const OffsetType & off) { this->DeactivateIndex(Superclass::GetNeighborhoodIndex(off)); } - + /** @ITKEndGrouping */ /** Activates a whole range of offsets, for example, an std::vector, * which could be from GenerateImageNeighborhoodOffsets(shape). */ template @@ -350,8 +349,8 @@ class ITK_TEMPLATE_EXPORT ConstShapedNeighborhoodIterator : private Neighborhood } /** Removes all active pixels from this neighborhood. */ - ITK_ITERATOR_VIRTUAL void - ClearActiveList() ITK_ITERATOR_FINAL + void + ClearActiveList() { m_ActiveIndexList.clear(); m_CenterIsActive = false; @@ -374,6 +373,7 @@ class ITK_TEMPLATE_EXPORT ConstShapedNeighborhoodIterator : private Neighborhood /** Add non-zero neighborhood offsets to the active list. The * radius of the neighborhood must match the radius of the shaped * iterator */ + /** @ITKStartGrouping */ template void CreateActiveListFromNeighborhood(const Neighborhood &); @@ -383,7 +383,7 @@ class ITK_TEMPLATE_EXPORT ConstShapedNeighborhoodIterator : private Neighborhood // just delegate to the templated version this->CreateActiveListFromNeighborhood(neighborhood); } - + /** @ITKEndGrouping */ /** Reimplements the operator++ method so that only active pixel locations * are updated. */ Self & @@ -422,9 +422,9 @@ class ITK_TEMPLATE_EXPORT ConstShapedNeighborhoodIterator : private Neighborhood argument is an index location calculated as an offset into a linear array which represents the image region defined by the radius of this iterator, with the smallest dimension as the fastest increasing index. */ - ITK_ITERATOR_VIRTUAL void ActivateIndex(NeighborIndexType) ITK_ITERATOR_FINAL; + void ActivateIndex(NeighborIndexType); - ITK_ITERATOR_VIRTUAL void DeactivateIndex(NeighborIndexType) ITK_ITERATOR_FINAL; + void DeactivateIndex(NeighborIndexType); bool m_CenterIsActive{ false }; diff --git a/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.hxx b/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.hxx index bc55ef181ff..d71ee9f0763 100644 --- a/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.hxx +++ b/Modules/Core/Common/include/itkConstShapedNeighborhoodIterator.hxx @@ -32,7 +32,7 @@ ConstShapedNeighborhoodIterator::PrintSelf(std::ostr } os << "] "; - os << indent << "CenterIsActive: " << (m_CenterIsActive ? "On" : "Off") << std::endl; + itkPrintSelfBooleanMacro(CenterIsActive); } template @@ -92,18 +92,17 @@ ConstShapedNeighborhoodIterator::DeactivateIndex(Nei { return; } - else + + while (n != *it) { - while (n != *it) + ++it; + if (it == m_ActiveIndexList.end()) { - ++it; - if (it == m_ActiveIndexList.end()) - { - return; - } + return; } - m_ActiveIndexList.erase(it); } + m_ActiveIndexList.erase(it); + // Did we just deactivate the index at the center of the neighborhood? if (n == this->GetCenterNeighborhoodIndex()) @@ -124,9 +123,9 @@ ConstShapedNeighborhoodIterator::CreateActiveListFro << ") does not equal radius of neighborhood(" << neighborhood.GetRadius() << ')'); } - typename Neighborhood::ConstIterator nit; - NeighborIndexType idx = 0; - for (nit = neighborhood.Begin(); nit != neighborhood.End(); ++nit, ++idx) + + NeighborIndexType idx = 0; + for (auto nit = neighborhood.Begin(); nit != neighborhood.End(); ++nit, ++idx) { if (*nit) { @@ -157,8 +156,6 @@ ConstShapedNeighborhoodIterator::operator++() } else { - IndexListConstIterator it; - // Center pointer must be updated whether or not it is active. if (!m_CenterIsActive) { @@ -166,7 +163,7 @@ ConstShapedNeighborhoodIterator::operator++() } // Increment pointers for only the active pixels. - for (it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) + for (auto it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) { (this->GetElement(*it))++; } @@ -182,7 +179,7 @@ ConstShapedNeighborhoodIterator::operator++() { this->GetElement(this->GetCenterNeighborhoodIndex()) += this->m_WrapOffset[ii]; } - for (it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) + for (auto it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) { (this->GetElement(*it)) += this->m_WrapOffset[ii]; } @@ -200,9 +197,6 @@ template ConstShapedNeighborhoodIterator & ConstShapedNeighborhoodIterator::operator--() { - unsigned int i; - IndexListConstIterator it; - // Repositioning neighborhood, previous bounds check on neighborhood // location is invalid. this->m_IsInBoundsValid = false; @@ -224,13 +218,13 @@ ConstShapedNeighborhoodIterator::operator--() } // Decrement pointers for only the active pixels. - for (it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) + for (auto it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) { (this->GetElement(*it))--; } // Check loop bounds, wrap & add pointer offsets if needed. - for (i = 0; i < Dimension; ++i) + for (unsigned int i = 0; i < Dimension; ++i) { if (this->m_Loop[i] == this->m_BeginIndex[i]) { @@ -239,7 +233,7 @@ ConstShapedNeighborhoodIterator::operator--() { this->GetElement(this->GetCenterNeighborhoodIndex()) -= this->m_WrapOffset[i]; } - for (it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) + for (auto it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) { (this->GetElement(*it)) -= this->m_WrapOffset[i]; } @@ -258,8 +252,6 @@ template ConstShapedNeighborhoodIterator & ConstShapedNeighborhoodIterator::operator+=(const OffsetType & idx) { - unsigned int i; - IndexListConstIterator it; OffsetValueType accumulator = 0; const OffsetValueType * stride = this->GetImagePointer()->GetOffsetTable(); @@ -285,7 +277,7 @@ ConstShapedNeighborhoodIterator::operator+=(const Of // Because the image offset table is based on its buffer size and // not its requested region size, we don't have to worry about // adding in the wrapping offsets. - for (i = 1; i < Dimension; ++i) + for (unsigned int i = 1; i < Dimension; ++i) { accumulator += idx[i] * stride[i]; } @@ -297,7 +289,7 @@ ConstShapedNeighborhoodIterator::operator+=(const Of } // Increment pointers only for those active pixels - for (it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) + for (auto it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) { (this->GetElement(*it)) += accumulator; } @@ -312,8 +304,6 @@ template ConstShapedNeighborhoodIterator & ConstShapedNeighborhoodIterator::operator-=(const OffsetType & idx) { - unsigned int i; - IndexListConstIterator it; OffsetValueType accumulator = 0; const OffsetValueType * stride = this->GetImagePointer()->GetOffsetTable(); @@ -339,7 +329,7 @@ ConstShapedNeighborhoodIterator::operator-=(const Of // Because the image offset table is based on its buffer size and // not its requested region size, we don't have to worry about // adding in the wrapping offsets. - for (i = 1; i < Dimension; ++i) + for (unsigned int i = 1; i < Dimension; ++i) { accumulator += idx[i] * stride[i]; } @@ -351,7 +341,7 @@ ConstShapedNeighborhoodIterator::operator-=(const Of } // Increment pointers only for those active pixels - for (it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) + for (auto it = m_ActiveIndexList.begin(); it != m_ActiveIndexList.end(); ++it) { (this->GetElement(*it)) -= accumulator; } diff --git a/Modules/Core/Common/include/itkConstSliceIterator.h b/Modules/Core/Common/include/itkConstSliceIterator.h index 28141401385..87d78f41245 100644 --- a/Modules/Core/Common/include/itkConstSliceIterator.h +++ b/Modules/Core/Common/include/itkConstSliceIterator.h @@ -40,8 +40,7 @@ namespace itk * * References: * Modeled after a slice iterator proposed by Bjarne Stroustrup - * in C++ Programming Language, Third Edition. Bjarne Stroustrup. Addison - * Wesley, Reading, MA. 1997. + * in \cite stroustrup1997. * * \ingroup Iterators * @@ -54,7 +53,6 @@ class ConstSliceIterator /** Constructor. */ ConstSliceIterator(const TContainer * n, std::slice s) : m_ContainerPointer(n) - , m_Pos(0) , m_Slice(s) {} @@ -99,11 +97,19 @@ class ConstSliceIterator /** Returns the element at position n of the slice. Sets the * iterator to point to position n. */ - const TPixel & operator[](SizeValueType n) { return this->Loc(m_Pos = n); } + const TPixel & + operator[](SizeValueType n) + { + return this->Loc(m_Pos = n); + } /** Dereferences the iterator, returning the value that it points * to. */ - const TPixel & operator*() { return Loc(m_Pos); } + const TPixel & + operator*() + { + return Loc(m_Pos); + } /** Returns the logical && of the boolean == of two slice iterator positions, * stride, and start locations. */ @@ -138,7 +144,7 @@ class ConstSliceIterator const TContainer * m_ContainerPointer; /** Current position within the slice. */ - SizeValueType m_Pos; + SizeValueType m_Pos{ 0 }; /** Slice structure information. */ std::slice m_Slice; diff --git a/Modules/Core/Common/include/itkConstantBoundaryCondition.hxx b/Modules/Core/Common/include/itkConstantBoundaryCondition.hxx index 1a7ab87a75a..fdbc90f4b5b 100644 --- a/Modules/Core/Common/include/itkConstantBoundaryCondition.hxx +++ b/Modules/Core/Common/include/itkConstantBoundaryCondition.hxx @@ -63,7 +63,7 @@ ConstantBoundaryCondition::GetInputRequestedRegion( const RegionType & outputRequestedRegion) const -> RegionType { RegionType inputRequestedRegion(inputLargestPossibleRegion); - bool cropped = inputRequestedRegion.Crop(outputRequestedRegion); + const bool cropped = inputRequestedRegion.Crop(outputRequestedRegion); if (!cropped) { @@ -79,7 +79,7 @@ auto ConstantBoundaryCondition::GetPixel(const IndexType & index, const TInputImage * image) const -> OutputPixelType { - RegionType imageRegion = image->GetLargestPossibleRegion(); + const RegionType imageRegion = image->GetLargestPossibleRegion(); if (imageRegion.IsInside(index)) { return static_cast(image->GetPixel(index)); diff --git a/Modules/Core/Common/include/itkConstantBoundaryImageNeighborhoodPixelAccessPolicy.h b/Modules/Core/Common/include/itkConstantBoundaryImageNeighborhoodPixelAccessPolicy.h index e455ecbf35e..ea1f7447566 100644 --- a/Modules/Core/Common/include/itkConstantBoundaryImageNeighborhoodPixelAccessPolicy.h +++ b/Modules/Core/Common/include/itkConstantBoundaryImageNeighborhoodPixelAccessPolicy.h @@ -124,7 +124,6 @@ class ConstantBoundaryImageNeighborhoodPixelAccessPolicy final , m_Constant{ constant } {} - /** Retrieves the pixel value from the image buffer, at the current * index. When the index is out of bounds, it returns the constant * value specified during construction. */ @@ -146,7 +145,6 @@ class ConstantBoundaryImageNeighborhoodPixelAccessPolicy final } }; - } // namespace itk #endif diff --git a/Modules/Core/Common/include/itkContinuousIndex.h b/Modules/Core/Common/include/itkContinuousIndex.h index 04043eee1ba..1028a9d8933 100644 --- a/Modules/Core/Common/include/itkContinuousIndex.h +++ b/Modules/Core/Common/include/itkContinuousIndex.h @@ -30,7 +30,7 @@ namespace itk * * ContinuousIndex is a templated class that holds a set of coordinates * (components). - * The template parameter TCoordRep can be any floating point type (float, double). + * The template parameter TCoordinate can be any floating point type (float, double). * The VIndexDimension defines the number of components in the continuous * index array. * @@ -42,22 +42,25 @@ namespace itk * * \ingroup ITKCommon */ -template -class ITK_TEMPLATE_EXPORT ContinuousIndex : public Point +template +class ITK_TEMPLATE_EXPORT ContinuousIndex : public Point { - static_assert(std::is_floating_point_v, + static_assert(std::is_floating_point_v, "The coordinates of a continuous index must be represented by floating point numbers."); public: /** Standard class type aliases. */ using Self = ContinuousIndex; - using Superclass = Point; + using Superclass = Point; /** ValueType can be used to declare a variable that is the same type * as a data element held in an Point. */ - using ValueType = TCoordRep; - using CoordinateType = TCoordRep; - using CoordRepType = CoordinateType; + using ValueType = TCoordinate; + using CoordinateType = TCoordinate; +#ifndef ITK_FUTURE_LEGACY_REMOVE + using CoordRepType ITK_FUTURE_DEPRECATED( + "ITK 6 discourages using `CoordRepType`. Please use `CoordinateType` instead!") = CoordinateType; +#endif /** Dimension of the Space */ static constexpr unsigned int IndexDimension = VIndexDimension; @@ -84,7 +87,7 @@ class ITK_TEMPLATE_EXPORT ContinuousIndex : public Point(index[i]); + (*this)[i] = static_cast(index[i]); } } }; diff --git a/Modules/Core/Common/include/itkCovariantVector.h b/Modules/Core/Common/include/itkCovariantVector.h index 05885d24ec3..9232aee5fef 100644 --- a/Modules/Core/Common/include/itkCovariantVector.h +++ b/Modules/Core/Common/include/itkCovariantVector.h @@ -64,7 +64,6 @@ namespace itk * \sphinxexample{Core/Common/CovariantVectorDotProduct, Covariant Vector Dot Product} * \endsphinx */ - template class ITK_TEMPLATE_EXPORT CovariantVector : public FixedArray { @@ -190,15 +189,18 @@ class ITK_TEMPLATE_EXPORT CovariantVector : public FixedArray & other) const; + ValueType + operator*(const Vector & other) const; /** Scalar operator*. Scale the elements of a vector by a scalar. * Return a new vector. */ - inline Self operator*(const ValueType & val) const + inline Self + operator*(const ValueType & val) const { Self result; @@ -245,9 +247,9 @@ class ITK_TEMPLATE_EXPORT CovariantVector : public FixedArray + template void - CastFrom(const CovariantVector & pa) + CastFrom(const CovariantVector & pa) { for (unsigned int i = 0; i < VVectorDimension; ++i) { @@ -259,7 +261,8 @@ class ITK_TEMPLATE_EXPORT CovariantVector : public FixedArray = T * CovariantVector< T,N > */ template -inline CovariantVector operator*(const T & scalar, const CovariantVector & v) +inline CovariantVector +operator*(const T & scalar, const CovariantVector & v) { return v.operator*(scalar); } @@ -267,8 +270,8 @@ inline CovariantVector operator*(const T & scalar, const Co /** Performs the scalar product of a covariant with a contravariant. * This scalar product is invariant under affine transformations */ template -inline T operator*(const Vector & contravariant, - const CovariantVector & covariant) +inline T +operator*(const Vector & contravariant, const CovariantVector & covariant) { return covariant.operator*(contravariant); } @@ -285,7 +288,7 @@ CrossProduct(CovariantVector, const Vector &, const Vector inline void -swap(CovariantVector & a, CovariantVector & b) +swap(CovariantVector & a, CovariantVector & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkCovariantVector.hxx b/Modules/Core/Common/include/itkCovariantVector.hxx index 41ee35cd288..4ee1cd23225 100644 --- a/Modules/Core/Common/include/itkCovariantVector.hxx +++ b/Modules/Core/Common/include/itkCovariantVector.hxx @@ -98,8 +98,8 @@ CovariantVector::operator-(const Self & vec) const -> Self } template -typename CovariantVector::ValueType CovariantVector::operator*( - const Self & other) const +typename CovariantVector::ValueType +CovariantVector::operator*(const Self & other) const { typename NumericTraits::AccumulateType value = T{}; for (unsigned int i = 0; i < VVectorDimension; ++i) @@ -110,10 +110,10 @@ typename CovariantVector::ValueType CovariantVector -typename CovariantVector::ValueType CovariantVector::operator*( - const Vector & other) const +typename CovariantVector::ValueType +CovariantVector::operator*(const Vector & other) const { - typename NumericTraits::AccumulateType value = T{}; + typename NumericTraits::AccumulateType value{}; for (unsigned int i = 0; i < VVectorDimension; ++i) { value += (*this)[i] * other[i]; diff --git a/Modules/Core/Common/include/itkCreateObjectFunction.h b/Modules/Core/Common/include/itkCreateObjectFunction.h index cfe5018d5c0..adf07d141da 100644 --- a/Modules/Core/Common/include/itkCreateObjectFunction.h +++ b/Modules/Core/Common/include/itkCreateObjectFunction.h @@ -67,13 +67,14 @@ class CreateObjectFunction : public CreateObjectFunctionBase using Pointer = SmartPointer; /** Methods from itk:LightObject. */ + /** @ITKStartGrouping */ itkFactorylessNewMacro(Self); LightObject::Pointer CreateObject() override { return T::New().GetPointer(); } - + /** @ITKEndGrouping */ protected: CreateObjectFunction() = default; ~CreateObjectFunction() override = default; diff --git a/Modules/Core/Common/include/itkCrossHelper.h b/Modules/Core/Common/include/itkCrossHelper.h index 1c235aa5508..1ff647fb417 100644 --- a/Modules/Core/Common/include/itkCrossHelper.h +++ b/Modules/Core/Common/include/itkCrossHelper.h @@ -49,27 +49,14 @@ class CrossHelper VectorType operator()(const VectorType & iU, const VectorType & iV) const { - VectorType oCross; + VectorType oCross{}; - if (Dimension > 2) + if constexpr (Dimension > 2) { oCross[0] = iU[1] * iV[2] - iV[1] * iU[2]; oCross[1] = iV[0] * iU[2] - iU[0] * iV[2]; oCross[2] = iU[0] * iV[1] - iV[0] * iU[1]; - - if (Dimension > 3) - { - for (unsigned int dim = 3; dim < Dimension; ++dim) - { - oCross[dim] = 0.0; - } - } - } - else - { - oCross.Fill(0.); } - return oCross; } }; diff --git a/Modules/Core/Common/include/itkDataObject.h b/Modules/Core/Common/include/itkDataObject.h index 6a2504c9196..a2bbfbabd04 100644 --- a/Modules/Core/Common/include/itkDataObject.h +++ b/Modules/Core/Common/include/itkDataObject.h @@ -59,10 +59,7 @@ class ITKCommon_EXPORT DataObjectError : public ExceptionObject ~DataObjectError() noexcept override = default; /** Constructor. Needed to ensure the exception object can be copied. */ - DataObjectError(const char * file, unsigned int lineNumber); - - /** Constructor. Needed to ensure the exception object can be copied. */ - DataObjectError(const std::string & file, unsigned int lineNumber); + DataObjectError(std::string file, unsigned int lineNumber); /** Copy constructor. Needed to ensure the exception object can be copied. */ DataObjectError(const DataObjectError & orig) noexcept; @@ -80,13 +77,14 @@ class ITKCommon_EXPORT DataObjectError : public ExceptionObject /** Get the data object that is throwing this exception. */ + /** @ITKStartGrouping */ const DataObject * GetDataObject() const noexcept; #if !defined(ITK_LEGACY_REMOVE) DataObject * GetDataObject() noexcept; #endif - + /** @ITKEndGrouping */ protected: /** Print exception information. This method can be overridden by * specific exception subtypes. The default is to print out the @@ -117,10 +115,7 @@ class ITKCommon_EXPORT InvalidRequestedRegionError : public DataObjectError ~InvalidRequestedRegionError() noexcept override = default; /** Constructor. Needed to ensure the exception object can be copied. */ - InvalidRequestedRegionError(const char * file, unsigned int lineNumber); - - /** Constructor. Needed to ensure the exception object can be copied. */ - InvalidRequestedRegionError(const std::string & file, unsigned int lineNumber); + InvalidRequestedRegionError(std::string file, unsigned int lineNumber); /** Copy constructor. Needed to ensure the exception object can be copied. */ InvalidRequestedRegionError(const InvalidRequestedRegionError & orig) noexcept; @@ -433,13 +428,14 @@ class ITK_FORCE_EXPORT_MACRO(ITKCommon) DataObject : public Object /** The maximum MTime of all upstream filters and data objects. * This does not include the MTime of this data object. */ + /** @ITKStartGrouping */ void SetPipelineMTime(ModifiedTimeType time) { m_PipelineMTime = time; } itkGetConstReferenceMacro(PipelineMTime, ModifiedTimeType); - + /** @ITKEndGrouping */ /** MTime for the last time this DataObject was generated. */ virtual ModifiedTimeType GetUpdateMTime() const; @@ -449,9 +445,10 @@ class ITK_FORCE_EXPORT_MACRO(ITKCommon) DataObject : public Object * the Unix epoch. That is the time 00:00:00 UTC on 1 January 1970 * (or 1970-01-01T00:00:00Z ISO 8601) */ + /** @ITKStartGrouping */ itkSetMacro(RealTimeStamp, RealTimeStamp); itkGetConstReferenceMacro(RealTimeStamp, RealTimeStamp); - + /** @ITKEndGrouping */ /** Setup a DataObject to receive new data. This method is called * by the pipeline mechanism on each output of filter that needs * to execute. The default implementation is to return a DataObject diff --git a/Modules/Core/Common/include/itkDataObjectConstIterator.h b/Modules/Core/Common/include/itkDataObjectConstIterator.h index 8ee96619099..0988926a8b1 100644 --- a/Modules/Core/Common/include/itkDataObjectConstIterator.h +++ b/Modules/Core/Common/include/itkDataObjectConstIterator.h @@ -68,7 +68,7 @@ class DataObjectConstIterator DataObjectConstIterator operator++(int) { - DataObjectConstIterator tmp = *this; + const DataObjectConstIterator tmp = *this; ++(*this); return tmp; } diff --git a/Modules/Core/Common/include/itkDataObjectDecorator.h b/Modules/Core/Common/include/itkDataObjectDecorator.h index 062596f6c8e..b36d51efc89 100644 --- a/Modules/Core/Common/include/itkDataObjectDecorator.h +++ b/Modules/Core/Common/include/itkDataObjectDecorator.h @@ -90,11 +90,12 @@ class ITK_TEMPLATE_EXPORT DataObjectDecorator : public DataObject Set(const ComponentType * val); /** Get the contained object */ + /** @ITKStartGrouping */ virtual const ComponentType * Get() const; virtual ComponentType * GetModifiable(); - + /** @ITKEndGrouping */ /** The most recent MTime of this object and the held component */ ModifiedTimeType GetMTime() const override; diff --git a/Modules/Core/Common/include/itkDataObjectIterator.h b/Modules/Core/Common/include/itkDataObjectIterator.h index e93d6225ed8..e70203cc73d 100644 --- a/Modules/Core/Common/include/itkDataObjectIterator.h +++ b/Modules/Core/Common/include/itkDataObjectIterator.h @@ -68,7 +68,7 @@ class DataObjectIterator DataObjectIterator operator++(int) { - DataObjectIterator tmp = *this; + const DataObjectIterator tmp = *this; ++(*this); return tmp; } diff --git a/Modules/Core/Common/include/itkDefaultDynamicMeshTraits.h b/Modules/Core/Common/include/itkDefaultDynamicMeshTraits.h index cf6cc00fb06..8fb978f9f2b 100644 --- a/Modules/Core/Common/include/itkDefaultDynamicMeshTraits.h +++ b/Modules/Core/Common/include/itkDefaultDynamicMeshTraits.h @@ -46,7 +46,7 @@ namespace itk * \tparam VMaxTopologicalDimension Max topological dimension of a cell * that can be inserted into this mesh. * - * \tparam TCoordRep Numerical type to store each coordinate value. + * \tparam TCoordinate Numerical type to store each coordinate value. * * \tparam TInterpolationWeight Numerical type to store interpolation * weights. @@ -57,7 +57,7 @@ namespace itk template class DefaultDynamicMeshTraits @@ -69,8 +69,11 @@ class DefaultDynamicMeshTraits /** Just save all the template parameters. */ using PixelType = TPixelType; using CellPixelType = TCellPixelType; - using CoordinateType = TCoordRep; - using CoordRepType = CoordinateType; + using CoordinateType = TCoordinate; +#ifndef ITK_FUTURE_LEGACY_REMOVE + using CoordRepType ITK_FUTURE_DEPRECATED( + "ITK 6 discourages using `CoordRepType`. Please use `CoordinateType` instead!") = CoordinateType; +#endif using InterpolationWeightType = TInterpolationWeight; /** Just save all the template parameters. */ @@ -91,11 +94,11 @@ class DefaultDynamicMeshTraits using CellFeatureIdentifier = IdentifierType; /** The type of point used by the mesh. */ - using PointType = Point; + using PointType = Point; /** The type of point used for hashing. This should never change from * this setting, regardless of the mesh type. */ - using PointHashType = Point; + using PointHashType = Point; /** The container type for use in storing points. It must conform to * the IndexedContainerInterface. */ diff --git a/Modules/Core/Common/include/itkDefaultStaticMeshTraits.h b/Modules/Core/Common/include/itkDefaultStaticMeshTraits.h index e4998f19cb9..ea424d2394c 100644 --- a/Modules/Core/Common/include/itkDefaultStaticMeshTraits.h +++ b/Modules/Core/Common/include/itkDefaultStaticMeshTraits.h @@ -43,7 +43,7 @@ namespace itk * VMaxTopologicalDimension = * Max topological dimension of a cell that can be inserted into this mesh. * - * TCoordRep = + * TCoordinate = * Numerical type with which to represent each coordinate value. * * TInterpolationWeight = @@ -55,7 +55,7 @@ namespace itk template class ITK_TEMPLATE_EXPORT DefaultStaticMeshTraits @@ -67,8 +67,11 @@ class ITK_TEMPLATE_EXPORT DefaultStaticMeshTraits /** Just save all the template parameters. */ using PixelType = TPixelType; using CellPixelType = TCellPixelType; - using CoordinateType = TCoordRep; - using CoordRepType = CoordinateType; + using CoordinateType = TCoordinate; +#ifndef ITK_FUTURE_LEGACY_REMOVE + using CoordRepType ITK_FUTURE_DEPRECATED( + "ITK 6 discourages using `CoordRepType`. Please use `CoordinateType` instead!") = CoordinateType; +#endif using InterpolationWeightType = TInterpolationWeight; /** Just save all the template parameters. */ @@ -89,15 +92,15 @@ class ITK_TEMPLATE_EXPORT DefaultStaticMeshTraits using CellFeatureIdentifier = IdentifierType; /** The type of point used by the mesh. */ - using PointType = Point; + using PointType = Point; /** The type of point used for hashing. This should never change from * this setting, regardless of the mesh type. */ - using PointHashType = Point; + using PointHashType = Point; /** The container type for use in storing points. It must conform to * the IndexedContainer interface. */ - using PointsContainer = VectorContainer; + using PointsContainer = VectorContainer; /** The container type that will be used to store boundary links * back to cells. This must conform to the STL "set" interface. */ @@ -115,7 +118,7 @@ class ITK_TEMPLATE_EXPORT DefaultStaticMeshTraits /** The container type for use in storing cells. It must conform to * the IndexedContainer interface. */ - using CellsContainer = VectorContainer; + using CellsContainer = VectorContainer; /** The CellLinks container should be a container of PointCellLinksContainer, * which should be a container conforming to the STL "set" interface. */ @@ -123,15 +126,15 @@ class ITK_TEMPLATE_EXPORT DefaultStaticMeshTraits /** The container type for use in storing point links back to cells. * It must conform to the IndexedContainer interface. */ - using CellLinksContainer = VectorContainer; + using CellLinksContainer = VectorContainer; /** The container type for use in storing point data. It must conform to * the IndexedContainer interface. */ - using PointDataContainer = VectorContainer; + using PointDataContainer = VectorContainer; /** The container type for use in storing cell data. It must conform to * the IndexedContainer interface. */ - using CellDataContainer = VectorContainer; + using CellDataContainer = VectorContainer; }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkDeref.h b/Modules/Core/Common/include/itkDeref.h index d9e98254c3f..bd2040b5aba 100644 --- a/Modules/Core/Common/include/itkDeref.h +++ b/Modules/Core/Common/include/itkDeref.h @@ -39,7 +39,6 @@ class DerefError : public ExceptionObject itkOverrideGetNameOfClassMacro(DerefError); }; - /** Dereferences the specified pointer, when the pointer is not null. Throws a `DerefError` exception when the pointer * is null. Aims to avoid undefined behavior from accidentally dereferencing a null pointer. */ diff --git a/Modules/Core/Common/include/itkDerivativeOperator.h b/Modules/Core/Common/include/itkDerivativeOperator.h index 1971387739a..8acda0274bc 100644 --- a/Modules/Core/Common/include/itkDerivativeOperator.h +++ b/Modules/Core/Common/include/itkDerivativeOperator.h @@ -39,8 +39,7 @@ namespace itk using DerivativeOperatorType = itk::DerivativeOperator; DerivativeOperatorType derivativeOperator; derivativeOperator.SetDirection(0); // X dimension - itk::Size<2> radius; - radius.Fill(1); // A radius of 1 in both dimensions is a 3x3 operator + constexpr auto radius = itk::Size<2>::Filled(1); // A radius of 1 in both dimensions is a 3x3 operator derivativeOperator.CreateToRadius(radius); \endcode * and creates a kernel that looks like: diff --git a/Modules/Core/Common/include/itkDerivativeOperator.hxx b/Modules/Core/Common/include/itkDerivativeOperator.hxx index 1aab4f718a3..882f9d8b283 100644 --- a/Modules/Core/Common/include/itkDerivativeOperator.hxx +++ b/Modules/Core/Common/include/itkDerivativeOperator.hxx @@ -26,37 +26,35 @@ template auto DerivativeOperator::GenerateCoefficients() -> CoefficientVector { - unsigned int i; - unsigned int j; - PixelRealType previous; - PixelRealType next; const unsigned int w = 2 * ((m_Order + 1) / 2) + 1; CoefficientVector coeff(w); coeff[w / 2] = 1.0; - for (i = 0; i < m_Order / 2; ++i) + for (unsigned int i = 0; i < m_Order / 2; ++i) { - previous = coeff[1] - 2 * coeff[0]; - for (j = 1; j < w - 1; ++j) + PixelRealType previous = coeff[1] - 2 * coeff[0]; + unsigned int j = 1; + for (; j < w - 1; ++j) { - next = coeff[j - 1] + coeff[j + 1] - 2 * coeff[j]; + const PixelRealType next = coeff[j - 1] + coeff[j + 1] - 2 * coeff[j]; coeff[j - 1] = previous; previous = next; } - next = coeff[j - 1] - 2 * coeff[j]; + const PixelRealType next = coeff[j - 1] - 2 * coeff[j]; coeff[j - 1] = previous; coeff[j] = next; } - for (i = 0; i < m_Order % 2; ++i) + for (unsigned int i = 0; i < m_Order % 2; ++i) { - previous = 0.5 * coeff[1]; - for (j = 1; j < w - 1; ++j) + PixelRealType previous = 0.5 * coeff[1]; + unsigned int j = 1; + for (; j < w - 1; ++j) { - next = -0.5 * coeff[j - 1] + 0.5 * coeff[j + 1]; + const PixelRealType next = -0.5 * coeff[j - 1] + 0.5 * coeff[j + 1]; coeff[j - 1] = previous; previous = next; } - next = -0.5 * coeff[j - 1]; + const PixelRealType next = -0.5 * coeff[j - 1]; coeff[j - 1] = previous; coeff[j] = next; } diff --git a/Modules/Core/Common/include/itkDiffusionTensor3D.h b/Modules/Core/Common/include/itkDiffusionTensor3D.h index bdbd3488184..b0693dee2a0 100644 --- a/Modules/Core/Common/include/itkDiffusionTensor3D.h +++ b/Modules/Core/Common/include/itkDiffusionTensor3D.h @@ -64,10 +64,7 @@ namespace itk * NIA AG 17919, PI: E.V. Sullivan. * * - * \par References - * E. R. Melhem, S. Mori, G. Mukundan, M. A. Kraut, M. G. Pomper, and - * P. C. M. van Zijl, "Diffusion tensor MR imaging of the brain and white - * matter tractography," Am. J. Roentgenol., vol. 178, pp. 3-16, 2002. + * For algorithmic details see \cite melhem2002. * * \sa SymmetricSecondRankTensor * @@ -98,13 +95,14 @@ class ITK_TEMPLATE_EXPORT DiffusionTensor3D : public SymmetricSecondRankTensor - DiffusionTensor3D(const DiffusionTensor3D & pa) + template + DiffusionTensor3D(const DiffusionTensor3D & pa) : SymmetricSecondRankTensor(pa) {} @@ -119,14 +117,14 @@ class ITK_TEMPLATE_EXPORT DiffusionTensor3D : public SymmetricSecondRankTensor + template Self & - operator=(const DiffusionTensor3D & pa) + operator=(const DiffusionTensor3D & pa) { // NOTE (this != &pa ) because they are different pointer types // if this templated function is called // ComponentType 'itk::DiffusionTensor3D *' - // TCoordRepB 'const DiffusionTensor3D *') + // TCoordinateB 'const DiffusionTensor3D *') SymmetricSecondRankTensor::operator=(pa); return *this; } @@ -164,7 +162,7 @@ class ITK_TEMPLATE_EXPORT DiffusionTensor3D : public SymmetricSecondRankTensor inline void -swap(DiffusionTensor3D & a, DiffusionTensor3D & b) +swap(DiffusionTensor3D & a, DiffusionTensor3D & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkDomainThreader.h b/Modules/Core/Common/include/itkDomainThreader.h index 13b9ea0a7e4..5d2b1f4b239 100644 --- a/Modules/Core/Common/include/itkDomainThreader.h +++ b/Modules/Core/Common/include/itkDomainThreader.h @@ -91,9 +91,10 @@ class ITK_TEMPLATE_EXPORT DomainThreader : public Object Execute(AssociateType * enclosingClass, const DomainType & completeDomain); /** Set/Get the DomainPartitioner. */ + /** @ITKStartGrouping */ itkSetObjectMacro(DomainPartitioner, DomainPartitionerType); itkGetModifiableObjectMacro(DomainPartitioner, DomainPartitionerType); - + /** @ITKEndGrouping */ /** Accessor for number of work units that were actually used in the last * ThreadedExecution. */ itkGetConstMacro(NumberOfWorkUnitsUsed, ThreadIdType); @@ -106,13 +107,15 @@ class ITK_TEMPLATE_EXPORT DomainThreader : public Object * \warning When setting the desired number of work units, it might be clamped by * itk::MultiThreaderBase::GetGlobalMaximumNumberOfThreads(). * */ + /** @ITKStartGrouping */ itkSetClampMacro(NumberOfWorkUnits, ThreadIdType, 1, ITK_MAX_THREADS); itkGetConstMacro(NumberOfWorkUnits, ThreadIdType); - + /** @ITKEndGrouping */ /** Convenience methods to set/get the maximum number of threads to use. * \warning When setting the maximum number of threads, it will be clamped by * itk::MultiThreaderBase::GetGlobalMaximumNumberOfThreads(). * */ + /** @ITKStartGrouping */ ThreadIdType GetMaximumNumberOfThreads() const { @@ -120,7 +123,7 @@ class ITK_TEMPLATE_EXPORT DomainThreader : public Object } void SetMaximumNumberOfThreads(const ThreadIdType threads); - + /** @ITKEndGrouping */ protected: DomainThreader(); ~DomainThreader() override = default; diff --git a/Modules/Core/Common/include/itkDomainThreader.hxx b/Modules/Core/Common/include/itkDomainThreader.hxx index 7b68c4f1d8d..cfd3e01fe50 100644 --- a/Modules/Core/Common/include/itkDomainThreader.hxx +++ b/Modules/Core/Common/include/itkDomainThreader.hxx @@ -71,7 +71,7 @@ template void DomainThreader::DetermineNumberOfWorkUnitsUsed() { - ThreadIdType numberOfWorkUnits = this->GetNumberOfWorkUnits(); + const ThreadIdType numberOfWorkUnits = this->GetNumberOfWorkUnits(); // Attempt a single dummy partition, just to get the number of subdomains actually created DomainType subdomain; diff --git a/Modules/Core/Common/include/itkDynamicLoader.h b/Modules/Core/Common/include/itkDynamicLoader.h index 6c4da07d567..9296bff665a 100644 --- a/Modules/Core/Common/include/itkDynamicLoader.h +++ b/Modules/Core/Common/include/itkDynamicLoader.h @@ -24,6 +24,13 @@ namespace itk { + +// BTX +using LibHandle = itksys::DynamicLoader::LibraryHandle; +// Cannot use this as this is a void (*)() but ITK old API used to be void* +using SymbolPointer = itksys::DynamicLoader::SymbolPointer; +// ETX + /** \class DynamicLoader * \brief Portable loading of dynamic libraries or dll's. * @@ -34,12 +41,6 @@ namespace itk * \ingroup ITKCommon */ -// BTX -using LibHandle = itksys::DynamicLoader::LibraryHandle; -// Cannot use this as this is a void (*)() but ITK old API used to be void* -using SymbolPointer = itksys::DynamicLoader::SymbolPointer; -// ETX - class ITKCommon_EXPORT DynamicLoader : public Object { public: diff --git a/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.h b/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.h index de5f9babf2e..bc8542f990d 100644 --- a/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.h +++ b/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.h @@ -64,13 +64,15 @@ class ITK_TEMPLATE_EXPORT EllipsoidInteriorExteriorSpatialFunction using OrientationType = vnl_matrix_fixed; /** Set/Get and set the center of the ellipsoid. */ + /** @ITKStartGrouping */ itkGetConstMacro(Center, InputType); itkSetMacro(Center, InputType); - + /** @ITKEndGrouping */ /** Get and set the axes lengths of the ellipsoid. */ + /** @ITKStartGrouping */ itkGetConstMacro(Axes, InputType); itkSetMacro(Axes, InputType); - + /** @ITKEndGrouping */ /** Set the orientation vectors (must be orthogonal) of the ellipsoid axes. * Must be normalized!!!!! */ void diff --git a/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.hxx b/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.hxx index b017422b21a..dbd5f14c78b 100644 --- a/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkEllipsoidInteriorExteriorSpatialFunction.hxx @@ -18,6 +18,7 @@ #ifndef itkEllipsoidInteriorExteriorSpatialFunction_hxx #define itkEllipsoidInteriorExteriorSpatialFunction_hxx +#include "itkMath.h" #include namespace itk @@ -26,27 +27,24 @@ template auto EllipsoidInteriorExteriorSpatialFunction::Evaluate(const InputType & position) const -> OutputType { - double distanceSquared = 0; - - Vector orientationVector; - Vector pointVector; - // Project the position onto each of the axes, normalize by axis length, // and determine whether position is inside ellipsoid. The length of axis0, // m_Axis[0] is orientated in the direction of m_Orientations[0]. + Vector pointVector; for (unsigned int i = 0; i < VDimension; ++i) { pointVector[i] = position[i] - m_Center[i]; } + double distanceSquared = 0; for (unsigned int i = 0; i < VDimension; ++i) { + Vector orientationVector; for (unsigned int j = 0; j < VDimension; ++j) { orientationVector[j] = m_Orientations[i][j]; } - distanceSquared += - std::pow(static_cast((orientationVector * pointVector) / (.5 * m_Axes[i])), static_cast(2)); + distanceSquared += Math::sqr(static_cast((orientationVector * pointVector) / (.5 * m_Axes[i]))); } if (distanceSquared <= 1) @@ -69,16 +67,14 @@ template void EllipsoidInteriorExteriorSpatialFunction::PrintSelf(std::ostream & os, Indent indent) const { - unsigned int i, j; - Superclass::PrintSelf(os, indent); os << indent << "Lengths of Ellipsoid Axes: " << m_Axes << std::endl; os << indent << "Origin of Ellipsoid: " << m_Center << std::endl; os << indent << "Orientations: " << std::endl; - for (i = 0; i < VDimension; ++i) + for (unsigned int i = 0; i < VDimension; ++i) { - for (j = 0; j < VDimension; ++j) + for (unsigned int j = 0; j < VDimension; ++j) { os << indent << indent << m_Orientations[i][j] << ' '; } diff --git a/Modules/Core/Common/include/itkEnableIf.h b/Modules/Core/Common/include/itkEnableIf.h index f90a66a9abb..d0226979a80 100644 --- a/Modules/Core/Common/include/itkEnableIf.h +++ b/Modules/Core/Common/include/itkEnableIf.h @@ -17,154 +17,7 @@ *=========================================================================*/ #ifndef itkEnableIf_h #define itkEnableIf_h - -#include "itkMacro.h" - -#if !defined(ITK_LEGACY_REMOVE) - -namespace itk -{ -/// \cond HIDE_META_PROGRAMMING -namespace mpl -{ - -/** \brief This is an implementation of the enable if idiom. - * \ingroup MetaProgrammingLibrary - * \ingroup ITKCommon - * - * Enable if is a common C++ meta-programming technique for example - * there is a boost implementation, for more information on its usage - * please see: - * https://www.boost.org/doc/libs/1_49_0/libs/utility/enable_if.html - * - * This template enables specialization of a templated function based - * on some traits or concepts. It is implemented with SFINAE. - * - * If the parameter V is true then the Type trait is the second - * template parameter, otherwise an implementation does not exist and - * with SFINAE another implementation may be chosen. - * - * Example: - \code - template< typename TType> - typename EnableIfC< - IsSame::ValueType>::Value, - TType >::Type - GetComponent(const TType pix, - unsigned int itkNotUsed( idx ) ) const - { - return pix; - } - \endcode - * - * \sa \c EnableIf - */ -template -struct EnableIfC -{}; -/// \cond SPECIALIZATION_IMPLEMENTATION -template -struct EnableIfC -{ - using Type = TType; -}; -/// \endcond - - -/** \brief An implementation of the negation of the enable if idiom. - * \ingroup MetaProgrammingLibrary - * \ingroup ITKCommon - * - * \sa \c EnableIfC - * \sa \c DisableIf - */ -template -struct DisableIfC -{}; -/// \cond SPECIALIZATION_IMPLEMENTATION -template -struct DisableIfC -{ - using Type = TType; -}; -/// \endcond - -/** \brief simplified way to dispose of \c enable_if. - * \ingroup MetaProgrammingLibrary - * \ingroup ITKCommon - * \tparam TCondition Condition type. It's expected to provide a boolean value - * through its \c Value member. - * \tparam TType Type to \em return when the \c TCondition is (a) true (type). - * - * This \em overload automatically fetches \c TCondition value. However, beware, it - * won't work with standard C++ traits or boost traits. Indeed, this \c - * enable_if overload expects the \em value to follow UpperCamelCase ITK naming - * policy instead of the standard snake_case policy. - * - * Example: - \code - template< typename TType> - typename EnableIf< - IsSame::ValueType>, - TType >::Type - GetComponent(const TType pix, - unsigned int itkNotUsed( idx ) ) const - { - return pix; - } - \endcode - * \sa \c EnableIfC - * \sa \c DisableIf - */ -template -struct EnableIf : public EnableIfC -{}; - -/** \brief simplified way to dispose of \c disable_if. - * \ingroup MetaProgrammingLibrary - * \ingroup ITKCommon - * \tparam TCondition Condition type. It's expected to provide a boolean value - * through its \c Value member. - * \tparam TType Type to \em return when the \c TCondition is (a) false (type). - * - * This \em overload automatically fetches \c TCondition value. However, beware, it - * won't work with standard C++ traits or boost traits. Indeed, this \c - * enable_if overload expects the \em value to follow UpperCamelCase ITK naming - * policy instead of the standard snake_case policy. - * - * Example: - \code - template< typename TType> - typename DisableIf< - mpl::Not_::ValueType>>, - TType >::Type - GetComponent(const TType pix, - unsigned int itkNotUsed( idx ) ) const - { - return pix; - } - \endcode - * \sa \c EnableIfC - * \sa \c DisableIf - */ -template -struct DisableIf : public DisableIfC -{}; - -} // namespace mpl - -// itk::EnableIf(C), DisableIf(C) have move to itk::mpl -// Expect them to be deprecated. -using mpl::EnableIf; -using mpl::DisableIf; -using mpl::EnableIfC; -using mpl::DisableIfC; - -/// \endcond -} // namespace itk - -#else // ITK_LEGACY_REMOVE -# error Use C++ 11 std::enable_if directly -#endif +// This file is no longer needed, features are natively available in C++11 +#error Use C++ 11 std::enable_if directly #endif // itkEnableIf_h diff --git a/Modules/Core/Common/include/itkEquivalencyTable.h b/Modules/Core/Common/include/itkEquivalencyTable.h index a3337c5c11f..118e8edbd23 100644 --- a/Modules/Core/Common/include/itkEquivalencyTable.h +++ b/Modules/Core/Common/include/itkEquivalencyTable.h @@ -47,13 +47,14 @@ class ITKCommon_EXPORT EquivalencyTable : public DataObject ITK_DISALLOW_COPY_AND_MOVE(EquivalencyTable); /** Standard smart pointer declarations */ + /** @ITKStartGrouping */ using Self = EquivalencyTable; using Superclass = DataObject; using Pointer = SmartPointer; using ConstPointer = SmartPointer; itkNewMacro(Self); itkOverrideGetNameOfClassMacro(EquivalencyTable); - + /** @ITKEndGrouping */ /** Define the container type for the table. */ using HashTableType = std::unordered_map>; @@ -98,10 +99,8 @@ class ITKCommon_EXPORT EquivalencyTable : public DataObject { return a; } - else - { - return result->second; - } + + return result->second; } /** Lookup an equivalency in the table by recursing through all @@ -120,10 +119,8 @@ class ITKCommon_EXPORT EquivalencyTable : public DataObject { return false; } - else - { - return true; - } + + return true; } /** Erases the entry with key a. */ diff --git a/Modules/Core/Common/include/itkEventObject.h b/Modules/Core/Common/include/itkEventObject.h index 0dddea3f561..64182c5ecc0 100644 --- a/Modules/Core/Common/include/itkEventObject.h +++ b/Modules/Core/Common/include/itkEventObject.h @@ -18,6 +18,7 @@ #ifndef itkEventObject_h #define itkEventObject_h +#include "itkMacro.h" #include "itkIndent.h" namespace itk @@ -139,11 +140,11 @@ operator<<(std::ostream & os, const EventObject & e) void \ operator=(const Self &); \ }; \ - static_assert(true, "Compile time eliminated. Used to require a semi-colon at end of macro.") + ITK_MACROEND_NOOP_STATEMENT #define itkEventMacroDefinition(classname, super) \ classname::classname(const classname & s) \ - : super(s){}; \ + : super(s) {}; \ classname::~classname() {} \ const char * classname::GetEventName() const { return #classname; } \ bool classname::CheckEvent(const itk::EventObject * e) const \ @@ -151,7 +152,7 @@ operator<<(std::ostream & os, const EventObject & e) return (dynamic_cast(e) != nullptr); \ } \ itk::EventObject * classname::MakeObject() const { return new classname; } \ - static_assert(true, "Compile time eliminated. Used to require a semi-colon at end of macro.") + ITK_MACROEND_NOOP_STATEMENT #if !defined(ITK_LEGACY_REMOVE) // Support Pre 2015 code bases @@ -189,7 +190,7 @@ operator<<(std::ostream & os, const EventObject & e) return new Self; \ } \ classname(const Self & s) \ - : super(s){}; \ + : super(s) {}; \ \ private: \ void \ @@ -199,6 +200,7 @@ operator<<(std::ostream & os, const EventObject & e) /** * Declare some common ITK events */ +/** @ITKStartGrouping */ itkEventMacroDeclaration(NoEvent, EventObject); itkEventMacroDeclaration(AnyEvent, EventObject); itkEventMacroDeclaration(DeleteEvent, AnyEvent); @@ -219,7 +221,7 @@ itkEventMacroDeclaration(FunctionEvaluationIterationEvent, IterationEvent); itkEventMacroDeclaration(GradientEvaluationIterationEvent, IterationEvent); itkEventMacroDeclaration(FunctionAndGradientEvaluationIterationEvent, IterationEvent); itkEventMacroDeclaration(UserEvent, AnyEvent); - +/** @ITKEndGrouping */ #undef ITKEvent_EXPORT #define ITKEvent_EXPORT ITK_ABI_EXPORT diff --git a/Modules/Core/Common/include/itkExceptionObject.h b/Modules/Core/Common/include/itkExceptionObject.h index 934e236cad6..1430c3c960e 100644 --- a/Modules/Core/Common/include/itkExceptionObject.h +++ b/Modules/Core/Common/include/itkExceptionObject.h @@ -16,14 +16,15 @@ * *=========================================================================*/ #ifndef itkExceptionObject_h -# error "Do not include itkExceptionObject.h directly, include itkMacro.h instead." -#else // itkExceptionObject_h +#define itkExceptionObject_h -# include "itkMacro.h" +// NOTE: This itkExceptionObject.h file is included by itkMacro.h, and should never be included directly. +#ifndef allow_inclusion_of_itkExceptionObject_h +# error "Do not include itkExceptionObject.h directly, include itkMacro.h instead." +#endif -# include // For shared_ptr. -# include -# include +#include // For shared_ptr. +#include namespace itk { @@ -55,14 +56,10 @@ class ITKCommon_EXPORT ExceptionObject : public std::exception /** Explicitly-defaulted default-constructor. Creates an empty exception object. */ ExceptionObject() noexcept = default; - explicit ExceptionObject(const char * file, - unsigned int lineNumber = 0, - const char * desc = "None", - const char * loc = "Unknown"); explicit ExceptionObject(std::string file, unsigned int lineNumber = 0, - std::string desc = "None", - std::string loc = "Unknown"); + std::string description = "None", + std::string location = {}); /** Copy-constructor. */ ExceptionObject(const ExceptionObject &) noexcept = default; @@ -132,7 +129,7 @@ class ITKCommon_EXPORT ExceptionObject : public std::exception private: class ExceptionData; - std::shared_ptr m_ExceptionData{}; + std::shared_ptr m_ExceptionData; }; /** Generic inserter operator for ExceptionObject and its subclasses. */ @@ -225,22 +222,35 @@ class ITKCommon_EXPORT ProcessAborted : public ExceptionObject } /** Constructor. Needed to ensure the exception object can be copied. */ - ProcessAborted(const char * file, unsigned int lineNumber) - : ExceptionObject(file, lineNumber) + ProcessAborted(std::string file, unsigned int lineNumber) + : ExceptionObject(std::move(file), lineNumber, "Filter execution was aborted by an external request") + {} + + /** \see LightObject::GetNameOfClass() */ + itkOverrideGetNameOfClassMacro(ProcessAborted); +}; + +// Forward declaration in Macro.h, implementation here to avoid circular dependency +template +TTarget +itkDynamicCastInDebugMode(TSource x) +{ +#ifndef NDEBUG + if (x == nullptr) { - this->SetDescription("Filter execution was aborted by an external request"); + return nullptr; } - - /** Constructor. Needed to ensure the exception object can be copied. */ - ProcessAborted(const std::string & file, unsigned int lineNumber) - : ExceptionObject(file, lineNumber) + TTarget rval = dynamic_cast(x); + if (rval == nullptr) { - this->SetDescription("Filter execution was aborted by an external request"); + itkGenericExceptionMacro("Failed dynamic cast to " << typeid(TTarget).name() + << " object type = " << x->GetNameOfClass()); } + return rval; +#else + return static_cast(x); +#endif +} - /** \see LightObject::GetNameOfClass() */ - itkOverrideGetNameOfClassMacro(ProcessAborted); -}; } // end namespace itk - #endif // itkExceptionObject_h diff --git a/Modules/Core/Common/include/itkExtractImageFilter.h b/Modules/Core/Common/include/itkExtractImageFilter.h index 17773d1e584..bf7d2c3fa44 100644 --- a/Modules/Core/Common/include/itkExtractImageFilter.h +++ b/Modules/Core/Common/include/itkExtractImageFilter.h @@ -35,7 +35,7 @@ namespace itk class ExtractImageFilterEnums { public: - /** \class DirectionCollapseStrategy + /** * \ingroup ITKCommon * Strategy to be used to collapse physical space dimensions */ @@ -47,6 +47,7 @@ class ExtractImageFilterEnums DIRECTIONCOLLAPSETOGUESS = 3 }; }; + /** Define how to print enumerations */ extern ITKCommon_EXPORT std::ostream & operator<<(std::ostream & out, const ExtractImageFilterEnums::DirectionCollapseStrategy value); @@ -256,15 +257,12 @@ class ITK_TEMPLATE_EXPORT ExtractImageFilter : public InPlaceImageFilter)); - // End concept checking -#endif + /** @ITKEndGrouping */ protected: ExtractImageFilter(); diff --git a/Modules/Core/Common/include/itkExtractImageFilter.hxx b/Modules/Core/Common/include/itkExtractImageFilter.hxx index 2b03120c2e2..3a9c1cfe27a 100644 --- a/Modules/Core/Common/include/itkExtractImageFilter.hxx +++ b/Modules/Core/Common/include/itkExtractImageFilter.hxx @@ -49,7 +49,7 @@ ExtractImageFilter::CallCopyOutputRegionToInputRegion InputImageRegionType & destRegion, const OutputImageRegionType & srcRegion) { - ExtractImageFilterRegionCopierType extractImageRegionCopier; + const ExtractImageFilterRegionCopierType extractImageRegionCopier; extractImageRegionCopier(destRegion, srcRegion, m_ExtractionRegion); } @@ -62,11 +62,9 @@ ExtractImageFilter::SetExtractionRegion(InputImageReg "InputImageDimension must be greater than OutputImageDimension"); m_ExtractionRegion = extractRegion; - InputImageSizeType inputSize = extractRegion.GetSize(); - OutputImageSizeType outputSize; - outputSize.Fill(0); - OutputImageIndexType outputIndex; - outputIndex.Fill(0); + InputImageSizeType inputSize = extractRegion.GetSize(); + OutputImageSizeType outputSize{}; + OutputImageIndexType outputIndex{}; /** * check to see if the number of non-zero entries in the extraction region @@ -107,8 +105,8 @@ ExtractImageFilter::GenerateOutputInformation() // this filter allows the input and the output to be of different dimensions // get pointers to the input and output - typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); - typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); + const typename Superclass::OutputImagePointer outputPtr = this->GetOutput(); + const typename Superclass::InputImageConstPointer inputPtr = this->GetInput(); if (!outputPtr || !inputPtr) { @@ -119,122 +117,113 @@ ExtractImageFilter::GenerateOutputInformation() outputPtr->SetLargestPossibleRegion(m_OutputImageRegion); // Set the output spacing and origin - if (this->GetInput()) - { - // Copy what we can from the image from spacing and origin of the input - // This logic needs to be augmented with logic that select which - // dimensions to copy - const typename InputImageType::SpacingType & inputSpacing = inputPtr->GetSpacing(); - const typename InputImageType::DirectionType & inputDirection = inputPtr->GetDirection(); - const typename InputImageType::PointType & inputOrigin = inputPtr->GetOrigin(); + // Copy what we can from the image from spacing and origin of the input + // This logic needs to be augmented with logic that select which + // dimensions to copy + + const typename InputImageType::SpacingType & inputSpacing = inputPtr->GetSpacing(); + const typename InputImageType::DirectionType & inputDirection = inputPtr->GetDirection(); + const typename InputImageType::PointType & inputOrigin = inputPtr->GetOrigin(); - typename OutputImageType::SpacingType outputSpacing; - typename OutputImageType::DirectionType outputDirection; - typename OutputImageType::PointType outputOrigin; - outputOrigin.Fill(0.0); + typename OutputImageType::SpacingType outputSpacing; + typename OutputImageType::DirectionType outputDirection; + typename OutputImageType::PointType outputOrigin{}; - if (static_cast(OutputImageDimension) > static_cast(InputImageDimension)) + if constexpr (OutputImageDimension > InputImageDimension) + { + // copy the input to the output and fill the rest of the + // output with zeros. + for (unsigned int i = 0; i < InputImageDimension; ++i) { - // copy the input to the output and fill the rest of the - // output with zeros. - for (unsigned int i = 0; i < InputImageDimension; ++i) + outputSpacing[i] = inputSpacing[i]; + outputOrigin[i] = inputOrigin[i]; + for (unsigned int dim = 0; dim < InputImageDimension; ++dim) { - outputSpacing[i] = inputSpacing[i]; - outputOrigin[i] = inputOrigin[i]; - for (unsigned int dim = 0; dim < InputImageDimension; ++dim) - { - outputDirection[i][dim] = inputDirection[i][dim]; - } + outputDirection[i][dim] = inputDirection[i][dim]; } - for (unsigned int i = InputImageDimension; i < OutputImageDimension; ++i) + } + for (unsigned int i = InputImageDimension; i < OutputImageDimension; ++i) + { + outputSpacing[i] = 1.0; + outputOrigin[i] = 0.0; + for (unsigned int dim = 0; dim < InputImageDimension; ++dim) { - outputSpacing[i] = 1.0; - outputOrigin[i] = 0.0; - for (unsigned int dim = 0; dim < InputImageDimension; ++dim) - { - outputDirection[i][dim] = 0.0; - } - outputDirection[i][i] = 1.0; + outputDirection[i][dim] = 0.0; } + outputDirection[i][i] = 1.0; } - else + } + else + { + // copy the non-collapsed part of the input spacing and origin to the + // output + outputDirection.SetIdentity(); + int nonZeroCount = 0; + for (unsigned int i = 0; i < InputImageDimension; ++i) { - // copy the non-collapsed part of the input spacing and origin to the - // output - outputDirection.SetIdentity(); - int nonZeroCount = 0; - for (unsigned int i = 0; i < InputImageDimension; ++i) + if (m_ExtractionRegion.GetSize()[i]) { - if (m_ExtractionRegion.GetSize()[i]) + outputSpacing[nonZeroCount] = inputSpacing[i]; + outputOrigin[nonZeroCount] = inputOrigin[i]; + int nonZeroCount2 = 0; + for (unsigned int dim = 0; dim < InputImageDimension; ++dim) { - outputSpacing[nonZeroCount] = inputSpacing[i]; - outputOrigin[nonZeroCount] = inputOrigin[i]; - int nonZeroCount2 = 0; - for (unsigned int dim = 0; dim < InputImageDimension; ++dim) + if (m_ExtractionRegion.GetSize()[dim]) { - if (m_ExtractionRegion.GetSize()[dim]) - { - outputDirection[nonZeroCount][nonZeroCount2] = inputDirection[i][dim]; - ++nonZeroCount2; - } + outputDirection[nonZeroCount][nonZeroCount2] = inputDirection[i][dim]; + ++nonZeroCount2; } - ++nonZeroCount; } + ++nonZeroCount; } } - // if the filter changes from a higher to a lower dimension, or - // if, after rebuilding the direction cosines, there's a zero - // length cosine vector, reset the directions to identity - // or throw an exception, depending on the collapse strategy. - if (static_cast(InputImageDimension) != static_cast(OutputImageDimension)) + } + // if the filter changes from a higher to a lower dimension, or + // if, after rebuilding the direction cosines, there's a zero + // length cosine vector, reset the directions to identity + // or throw an exception, depending on the collapse strategy. + if constexpr (InputImageDimension != OutputImageDimension) + { + switch (m_DirectionCollapseStrategy) { - switch (m_DirectionCollapseStrategy) + case DirectionCollapseStrategyEnum::DIRECTIONCOLLAPSETOIDENTITY: { - case DirectionCollapseStrategyEnum::DIRECTIONCOLLAPSETOIDENTITY: - { - outputDirection.SetIdentity(); - } - break; - case DirectionCollapseStrategyEnum::DIRECTIONCOLLAPSETOSUBMATRIX: - { - if (vnl_determinant(outputDirection.GetVnlMatrix()) == 0.0) - { - itkExceptionMacro("Invalid submatrix extracted for collapsed direction."); - } - } - break; - case DirectionCollapseStrategyEnum::DIRECTIONCOLLAPSETOGUESS: + outputDirection.SetIdentity(); + } + break; + case DirectionCollapseStrategyEnum::DIRECTIONCOLLAPSETOSUBMATRIX: + { + if (vnl_determinant(outputDirection.GetVnlMatrix()) == 0.0) { - if (vnl_determinant(outputDirection.GetVnlMatrix()) == 0.0) - { - outputDirection.SetIdentity(); - } + itkExceptionMacro("Invalid submatrix extracted for collapsed direction."); } - break; - case DirectionCollapseStrategyEnum::DIRECTIONCOLLAPSETOUNKOWN: - default: + } + break; + case DirectionCollapseStrategyEnum::DIRECTIONCOLLAPSETOGUESS: + { + if (vnl_determinant(outputDirection.GetVnlMatrix()) == 0.0) { - itkExceptionMacro( - << "It is required that the strategy for collapsing the direction matrix be explicitly specified. " - << "Set with either myfilter->SetDirectionCollapseToIdentity() or " - "myfilter->SetDirectionCollapseToSubmatrix() " - << typeid(ImageBase *).name()); + outputDirection.SetIdentity(); } } + break; + case DirectionCollapseStrategyEnum::DIRECTIONCOLLAPSETOUNKOWN: + default: + { + itkExceptionMacro( + << "It is required that the strategy for collapsing the direction matrix be explicitly specified. " + << "Set with either myfilter->SetDirectionCollapseToIdentity() or " + "myfilter->SetDirectionCollapseToSubmatrix() " + << typeid(ImageBase *).name()); + } } - // set the spacing and origin - outputPtr->SetSpacing(outputSpacing); - outputPtr->SetDirection(outputDirection); - outputPtr->SetOrigin(outputOrigin); - outputPtr->SetNumberOfComponentsPerPixel(inputPtr->GetNumberOfComponentsPerPixel()); - } - else - { - // pointer could not be cast back down - itkExceptionMacro("itk::ExtractImageFilter::GenerateOutputInformation " - << "cannot cast input to " << typeid(ImageBase *).name()); } + // set the spacing and origin + outputPtr->SetSpacing(outputSpacing); + outputPtr->SetDirection(outputDirection); + outputPtr->SetOrigin(outputOrigin); + outputPtr->SetNumberOfComponentsPerPixel(inputPtr->GetNumberOfComponentsPerPixel()); } template diff --git a/Modules/Core/Common/include/itkExtractImageFilterRegionCopier.h b/Modules/Core/Common/include/itkExtractImageFilterRegionCopier.h index 0dcf41b78eb..227986d5b4e 100644 --- a/Modules/Core/Common/include/itkExtractImageFilterRegionCopier.h +++ b/Modules/Core/Common/include/itkExtractImageFilterRegionCopier.h @@ -57,9 +57,8 @@ ExtractImageFilterCopyRegion( const typename BinaryUnsignedIntDispatch::FirstLessThanSecondType & firstLessThanSecond, ImageRegion & destRegion, const ImageRegion & srcRegion, - const ImageRegion & totalInputExtractionRegion) + const ImageRegion & itkNotUsed(totalInputExtractionRegion)) { - (void)totalInputExtractionRegion; ImageToImageFilterDefaultCopyRegion(firstLessThanSecond, destRegion, srcRegion); } @@ -89,14 +88,14 @@ ExtractImageFilterCopyRegion(const typename BinaryUnsignedIntDispatch::F // Source dimension is less than the destination dimension, so look // at the m_TotalExtractionRegion and see what values in size are 0. // With these values, lock the destRegion.Index to the corresponding index - unsigned int dim; + Index destIndex; Size destSize; const Index & srcIndex = srcRegion.GetIndex(); const Size & srcSize = srcRegion.GetSize(); int count = 0; - for (dim = 0; dim < T1; ++dim) + for (unsigned int dim = 0; dim < T1; ++dim) { // for dimensions to be removed if (!totalInputExtractionRegion.GetSize()[dim]) diff --git a/Modules/Core/Common/include/itkFileOutputWindow.h b/Modules/Core/Common/include/itkFileOutputWindow.h index f2e94506459..e10b80eee08 100644 --- a/Modules/Core/Common/include/itkFileOutputWindow.h +++ b/Modules/Core/Common/include/itkFileOutputWindow.h @@ -67,18 +67,20 @@ class ITKCommon_EXPORT FileOutputWindow : public OutputWindow itkGetStringMacro(FileName); /** Set/Get the buffer flushing mode */ + /** @ITKStartGrouping */ itkSetMacro(Flush, bool); itkGetConstMacro(Flush, bool); itkBooleanMacro(Flush); - + /** @ITKEndGrouping */ /** Setting append will cause the log file to be * opened in append mode. Otherwise, if the log file exists, * it will be overwritten each time the FileOutputWindow * is created. */ + /** @ITKStartGrouping */ itkSetMacro(Append, bool); itkGetConstMacro(Append, bool); itkBooleanMacro(Append); - + /** @ITKEndGrouping */ protected: FileOutputWindow(); ~FileOutputWindow() override; diff --git a/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.h b/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.h index b0f9bca4ac1..1f1386b0734 100644 --- a/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.h +++ b/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.h @@ -60,33 +60,33 @@ class ITK_TEMPLATE_EXPORT FiniteCylinderSpatialFunction : public InteriorExterio using typename Superclass::OutputType; /** Set/Get and set the center of the cylinder. */ + /** @ITKStartGrouping */ itkGetConstMacro(Center, InputType); itkSetMacro(Center, InputType); - + /** @ITKEndGrouping */ /** Get and set the medial axis length of the cylinder. */ + /** @ITKStartGrouping */ itkGetConstMacro(AxisLength, double); itkSetMacro(AxisLength, double); - + /** @ITKEndGrouping */ /** Get and set the radius length of the cylinder. */ + /** @ITKStartGrouping */ itkGetConstMacro(Radius, double); itkSetMacro(Radius, double); - + /** @ITKEndGrouping */ /** Set the orientation vectors (must be orthogonal) of the ellipsoid axes. * Must be normalized!!!!! */ + /** @ITKStartGrouping */ itkGetConstMacro(Orientation, InputType); virtual void SetOrientation(const InputType _Orientation); - + /** @ITKEndGrouping */ /** Evaluates the function at a given position. */ OutputType Evaluate(const InputType & position) const override; -#ifdef ITK_USE_CONCEPT_CHECKING - // Begin concept checking itkConceptMacro(DimensionShouldBe3, (Concept::SameDimension)); itkConceptMacro(PointDimensionShouldBe3, (Concept::SameDimension)); - // End concept checking -#endif protected: FiniteCylinderSpatialFunction(); diff --git a/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.hxx b/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.hxx index ae89bd63378..f7410bdfd67 100644 --- a/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkFiniteCylinderSpatialFunction.hxx @@ -19,6 +19,7 @@ #define itkFiniteCylinderSpatialFunction_hxx #include "itkFloatingPointExceptions.h" +#include "itkMath.h" #include namespace itk @@ -28,7 +29,7 @@ FiniteCylinderSpatialFunction::FiniteCylinderSpatialFunction { // a normalized {1,1,...1} vector is // { 1.0 / sqrt( VDim ), ... } - const double orientationVal = 1.0 / std::sqrt(static_cast(VDimension)); + const double orientationVal = 1.0 / std::sqrt(double{ VDimension }); m_Orientation.Fill(orientationVal); m_NormalizedOrientation.Fill(orientationVal); m_AxisLength = 1.0f; // Length of cylinder axis. @@ -102,35 +103,31 @@ FiniteCylinderSpatialFunction::Evaluate(const InputType & po } if (itk::Math::abs(distanceFromCenter) <= (halfAxisLength) && - m_Radius >= std::sqrt(std::pow(pointVector.GetVnlVector().magnitude(), 2.0) - std::pow(distanceFromCenter, 2.0))) + m_Radius >= std::sqrt(Math::sqr(pointVector.GetNorm()) - Math::sqr(distanceFromCenter))) { return 1; } - else - { - return 0; - } + + return 0; } template void FiniteCylinderSpatialFunction::PrintSelf(std::ostream & os, Indent indent) const { - unsigned int i; - Superclass::PrintSelf(os, indent); os << indent << "Lengths of Axis: " << m_AxisLength << std::endl; os << indent << "Radius: " << m_Radius << std::endl; os << indent << "Origin of Cylinder: " << m_Center << std::endl; os << indent << "Orientation: " << std::endl; - for (i = 0; i < VDimension; ++i) + for (unsigned int i = 0; i < VDimension; ++i) { os << indent << indent << m_Orientation[i] << ' '; } os << std::endl; os << indent << "Normalized Orientation: " << std::endl; - for (i = 0; i < VDimension; ++i) + for (unsigned int i = 0; i < VDimension; ++i) { os << indent << indent << m_NormalizedOrientation[i] << ' '; } diff --git a/Modules/Core/Common/include/itkFixedArray.h b/Modules/Core/Common/include/itkFixedArray.h index 92d4feef13d..e731e8690d9 100644 --- a/Modules/Core/Common/include/itkFixedArray.h +++ b/Modules/Core/Common/include/itkFixedArray.h @@ -103,8 +103,16 @@ class ITK_TEMPLATE_EXPORT FixedArray { return ReverseIterator(m_Iterator++); } - Iterator operator->() const { return (m_Iterator - 1); } - ValueType & operator*() const { return *(m_Iterator - 1); } + Iterator + operator->() const + { + return (m_Iterator - 1); + } + ValueType & + operator*() const + { + return *(m_Iterator - 1); + } bool operator==(const ReverseIterator & rit) const @@ -150,8 +158,16 @@ class ITK_TEMPLATE_EXPORT FixedArray { return ConstReverseIterator(m_Iterator++); } - ConstIterator operator->() const { return (m_Iterator - 1); } - const ValueType & operator*() const { return *(m_Iterator - 1); } + ConstIterator + operator->() const + { + return (m_Iterator - 1); + } + const ValueType & + operator*() const + { + return *(m_Iterator - 1); + } bool operator==(const ConstReverseIterator & rit) const @@ -165,6 +181,9 @@ class ITK_TEMPLATE_EXPORT FixedArray ConstIterator m_Iterator; }; + /** The type of an element. */ + using value_type = TValue; + /** A pointer to the ValueType. */ using pointer = ValueType *; @@ -200,9 +219,10 @@ class ITK_TEMPLATE_EXPORT FixedArray * Values are copied individually instead of with a binary copy. This * allows the ValueType's assignment operator to be executed. */ + /** @ITKStartGrouping */ FixedArray(const ValueType r[VLength]); FixedArray(const ValueType &); - + /** @ITKEndGrouping */ /** Explicit constructor for std::array. */ explicit FixedArray(const std::array & stdArray) { @@ -260,22 +280,24 @@ class ITK_TEMPLATE_EXPORT FixedArray /** Allow the FixedArray to be indexed normally. No bounds checking is done. */ -// false positive warnings with GCC -#if defined(__GNUC__) -# if (__GNUC__ >= 7) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Warray-bounds" -# endif -#endif - constexpr reference operator[](unsigned int index) { return m_InternalArray[index]; } - constexpr const_reference operator[](unsigned int index) const { return m_InternalArray[index]; } -#if defined(__GNUC__) -# if (__GNUC__ >= 7) -# pragma GCC diagnostic pop -# endif -#endif - + /** @ITKStartGrouping */ + // false positive warnings with GCC + ITK_GCC_PRAGMA_PUSH + ITK_GCC_SUPPRESS_Warray_bounds + constexpr reference + operator[](unsigned int index) + { + return m_InternalArray[index]; + } + constexpr const_reference + operator[](unsigned int index) const + { + return m_InternalArray[index]; + } + ITK_GCC_PRAGMA_POP + /** @ITKEndGrouping */ /** Set/Get element methods are more convenient in wrapping languages */ + /** @ITKStartGrouping */ void SetElement(unsigned int index, const_reference value) { @@ -286,7 +308,7 @@ class ITK_TEMPLATE_EXPORT FixedArray { return m_InternalArray[index]; } - + /** @ITKEndGrouping */ /** Return a pointer to the data. */ ValueType * GetDataPointer() @@ -329,16 +351,16 @@ class ITK_TEMPLATE_EXPORT FixedArray End() const; /** Get a begin ReverseIterator. */ - itkLegacyMacro(ReverseIterator rBegin()); + itkLegacyMacro(ReverseIterator rBegin();) /** Get a begin ConstReverseIterator. */ - itkLegacyMacro(ConstReverseIterator rBegin() const); + itkLegacyMacro(ConstReverseIterator rBegin() const;) /** Get an end ReverseIterator. */ - itkLegacyMacro(ReverseIterator rEnd()); + itkLegacyMacro(ReverseIterator rEnd();) /** Get an end ConstReverseIterator. */ - itkLegacyMacro(ConstReverseIterator rEnd() const); + itkLegacyMacro(ConstReverseIterator rEnd() const;) constexpr const_iterator cbegin() const noexcept @@ -427,7 +449,7 @@ class ITK_TEMPLATE_EXPORT FixedArray Fill(const ValueType &); void - swap(FixedArray & other) + swap(FixedArray & other) noexcept { std::swap(m_InternalArray, other.m_InternalArray); } @@ -452,7 +474,7 @@ operator<<(std::ostream & os, const FixedArray & arr); template inline void -swap(FixedArray & a, FixedArray & b) +swap(FixedArray & a, FixedArray & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkFloatingPointExceptions.h b/Modules/Core/Common/include/itkFloatingPointExceptions.h index d407803204b..fd2f0ce2564 100644 --- a/Modules/Core/Common/include/itkFloatingPointExceptions.h +++ b/Modules/Core/Common/include/itkFloatingPointExceptions.h @@ -30,7 +30,7 @@ namespace itk class FloatingPointExceptionsEnums { public: - /** \class ExceptionAction + /** * \ingroup ITKCommon * defines what should happen when exceptions occur */ enum class ExceptionAction : uint8_t diff --git a/Modules/Core/Common/include/itkFloodFilledFunctionConditionalConstIterator.hxx b/Modules/Core/Common/include/itkFloodFilledFunctionConditionalConstIterator.hxx index 73c8fa88be3..c535df4a143 100644 --- a/Modules/Core/Common/include/itkFloodFilledFunctionConditionalConstIterator.hxx +++ b/Modules/Core/Common/include/itkFloodFilledFunctionConditionalConstIterator.hxx @@ -44,8 +44,7 @@ FloodFilledFunctionConditionalConstIterator::FloodFilledFunct { this->m_Image = imagePtr; m_Function = fnPtr; - unsigned int i; - for (i = 0; i < startIndex.size(); ++i) + for (unsigned int i = 0; i < startIndex.size(); ++i) { m_Seeds.push_back(startIndex[i]); } @@ -80,7 +79,7 @@ FloodFilledFunctionConditionalConstIterator::InitializeIterat // Build a temporary image of chars for use in the flood algorithm m_TemporaryPointer = TTempImage::New(); - typename TTempImage::RegionType tempRegion = this->m_Image->GetBufferedRegion(); + const typename TTempImage::RegionType tempRegion = this->m_Image->GetBufferedRegion(); m_TemporaryPointer->SetRegions(tempRegion); m_TemporaryPointer->AllocateInitialized(); @@ -205,7 +204,7 @@ FloodFilledFunctionConditionalConstIterator::DoFloodStep() } } } // end left/right neighbor loop - } // end check all neighbors + } // end check all neighbors // Now that all the potential neighbors have been // inserted we can get rid of the pixel in the front diff --git a/Modules/Core/Common/include/itkFloodFilledSpatialFunctionConditionalConstIterator.hxx b/Modules/Core/Common/include/itkFloodFilledSpatialFunctionConditionalConstIterator.hxx index a6e0abbfdb2..78b8a971c66 100644 --- a/Modules/Core/Common/include/itkFloodFilledSpatialFunctionConditionalConstIterator.hxx +++ b/Modules/Core/Common/include/itkFloodFilledSpatialFunctionConditionalConstIterator.hxx @@ -109,21 +109,20 @@ FloodFilledSpatialFunctionConditionalConstIterator::IsPixelIn // means of determining index inclusion. // To reiterate... DO NOT use this on images higher than 16D - unsigned int counter; - unsigned int counterCopy; - unsigned int dim = TImage::ImageDimension; - auto numReps = static_cast(std::pow(2.0, static_cast(dim))); - IndexType tempIndex; + constexpr unsigned int dim = TImage::ImageDimension; + constexpr unsigned int numReps{ 1ULL << dim }; + // First we loop over the binary counter - for (counter = 0; counter < numReps; ++counter) + for (unsigned int counter = 0; counter < numReps; ++counter) { // Next we use the binary values in the counter to form // an index to look at + IndexType tempIndex; for (unsigned int i = 0; i < dim; ++i) { - counterCopy = counter; + const unsigned int counterCopy = counter; tempIndex[i] = index[i] + static_cast((counterCopy >> i) & 0x0001); } @@ -154,20 +153,19 @@ FloodFilledSpatialFunctionConditionalConstIterator::IsPixelIn // generated indices are true // To reiterate... DO NOT use this on images higher than 16D - unsigned int counter; - unsigned int counterCopy; - unsigned int dim = TImage::ImageDimension; - auto numReps = static_cast(std::pow(2.0, static_cast(dim))); - IndexType tempIndex; + + constexpr unsigned int dim = TImage::ImageDimension; + constexpr unsigned int numReps{ 1ULL << dim }; // First we loop over the binary counter - for (counter = 0; counter < numReps; ++counter) + for (unsigned int counter = 0; counter < numReps; ++counter) { // Next we use the binary values in the counter to form // an index to look at + IndexType tempIndex; for (unsigned int i = 0; i < dim; ++i) { - counterCopy = counter; + const unsigned int counterCopy = counter; tempIndex[i] = index[i] + static_cast((counterCopy >> i) & 0x0001); } diff --git a/Modules/Core/Common/include/itkFrustumSpatialFunction.h b/Modules/Core/Common/include/itkFrustumSpatialFunction.h index e9d12931a44..96dad496dde 100644 --- a/Modules/Core/Common/include/itkFrustumSpatialFunction.h +++ b/Modules/Core/Common/include/itkFrustumSpatialFunction.h @@ -32,7 +32,7 @@ namespace itk class FrustumSpatialFunctionEnums { public: - /** \class RotationPlane + /** * \ingroup ITKCommon */ enum class RotationPlane : uint8_t @@ -98,33 +98,40 @@ class ITK_TEMPLATE_EXPORT FrustumSpatialFunction : public InteriorExteriorSpatia Evaluate(const InputType & position) const override; /** Set/Get the apex of the pyramid. */ + /** @ITKStartGrouping */ itkGetConstMacro(Apex, InputType); itkSetMacro(Apex, InputType); - + /** @ITKEndGrouping */ /** Set/Get the angle of the pyramid axis with respect to the Z axis. */ + /** @ITKStartGrouping */ itkGetConstMacro(AngleZ, double); itkSetMacro(AngleZ, double); - + /** @ITKEndGrouping */ /** Set/Get the aperture angle in the X axis. */ + /** @ITKStartGrouping */ itkGetConstMacro(ApertureAngleX, double); itkSetMacro(ApertureAngleX, double); - + /** @ITKEndGrouping */ /** Set/Get the aperture angle in the Y axis. */ + /** @ITKStartGrouping */ itkGetConstMacro(ApertureAngleY, double); itkSetMacro(ApertureAngleY, double); - + /** @ITKEndGrouping */ /** Set/Get the top plane distance to the apex. */ + /** @ITKStartGrouping */ itkGetConstMacro(TopPlane, double); itkSetMacro(TopPlane, double); - + /** @ITKEndGrouping */ /** Set/Get the bottom plane distance to the apex. */ + /** @ITKStartGrouping */ itkGetConstMacro(BottomPlane, double); itkSetMacro(BottomPlane, double); - + /** @ITKEndGrouping */ /** Set/Get the plane in which the frustum should rotate. */ + /** @ITKStartGrouping */ itkGetConstMacro(RotationPlane, FrustumRotationPlaneType); itkSetMacro(RotationPlane, FrustumRotationPlaneType); - + /** @ITKEndGrouping */ protected: FrustumSpatialFunction() = default; ~FrustumSpatialFunction() override = default; diff --git a/Modules/Core/Common/include/itkFrustumSpatialFunction.hxx b/Modules/Core/Common/include/itkFrustumSpatialFunction.hxx index 3fb38055e52..cc4c00989de 100644 --- a/Modules/Core/Common/include/itkFrustumSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkFrustumSpatialFunction.hxx @@ -77,7 +77,7 @@ FrustumSpatialFunction::Evaluate(const InputType & position) return 1; } - else if (m_RotationPlane == RotationPlaneEnum::RotateInYZPlane) + if (m_RotationPlane == RotationPlaneEnum::RotateInYZPlane) { const double dx = relativePosition[0]; const double dy = relativePosition[1]; diff --git a/Modules/Core/Common/include/itkGaussianDerivativeOperator.h b/Modules/Core/Common/include/itkGaussianDerivativeOperator.h index aeb72cca467..b5ebde83b83 100644 --- a/Modules/Core/Common/include/itkGaussianDerivativeOperator.h +++ b/Modules/Core/Common/include/itkGaussianDerivativeOperator.h @@ -35,7 +35,6 @@ class GaussianDerivativeOperatorEnums { public: /** - * \class InterpolationMode * \ingroup ITKCommon * Interpolation modes */ @@ -76,15 +75,13 @@ extern ITKCommon_EXPORT std::ostream & * lest the operator size become unreasonably large. * * References: - * The Gaussian kernel contained in this operator was described - * by Tony Lindeberg (Discrete Scale-Space Theory and the Scale-Space - * Primal Sketch. Dissertation. Royal Institute of Technology, Stockholm, - * Sweden. May 1991.). + * The Gaussian kernel contained in this operator was described in + * \cite lindeberg1991. * * \author Ivan Macia, Vicomtech, Spain, https://www.vicomtech.org/en * * This implementation is derived from the Insight Journal paper: - * https://www.insight-journal.org/browse/publication/179 + * https://doi.org/10.54294/mrg5is * * \note GaussianDerivativeOperator does not have any user-declared "special member function", * following the C++ Rule of Zero: the compiler will generate them if necessary. @@ -126,6 +123,7 @@ class ITK_TEMPLATE_EXPORT GaussianDerivativeOperator : public NeighborhoodOperat * algorithms such as blob detection. The scaling results in the * value of the derivatives being independent of the size of an * object. */ + /** @ITKStartGrouping */ void SetNormalizeAcrossScale(bool flag) { @@ -137,10 +135,11 @@ class ITK_TEMPLATE_EXPORT GaussianDerivativeOperator : public NeighborhoodOperat return m_NormalizeAcrossScale; } itkBooleanMacro(NormalizeAcrossScale); - + /** @ITKEndGrouping */ /** Set/Get the variance of the Gaussian kernel. * */ + /** @ITKStartGrouping */ void SetVariance(const double variance) { @@ -151,8 +150,9 @@ class ITK_TEMPLATE_EXPORT GaussianDerivativeOperator : public NeighborhoodOperat { return m_Variance; } - + /** @ITKEndGrouping */ /** Set/Get the spacing for the direction of this kernel. */ + /** @ITKStartGrouping */ void SetSpacing(const double spacing) { @@ -163,7 +163,7 @@ class ITK_TEMPLATE_EXPORT GaussianDerivativeOperator : public NeighborhoodOperat { return m_Spacing; } - + /** @ITKEndGrouping */ /** Set/Get the desired maximum error of the gaussian approximation. Maximum * error is the difference between the area under the discrete Gaussian curve * and the area under the continuous Gaussian. Maximum error affects the @@ -186,14 +186,16 @@ class ITK_TEMPLATE_EXPORT GaussianDerivativeOperator : public NeighborhoodOperat * large variances will yield very large kernel sizes. This value can be * used to truncate a kernel in such instances. A warning will be given on * truncation of the kernel. */ + /** @ITKStartGrouping */ void SetMaximumKernelWidth(unsigned int n) { m_MaximumKernelWidth = n; } itkGetConstMacro(MaximumKernelWidth, unsigned int); - + /** @ITKEndGrouping */ /** Sets/Get the order of the derivative. */ + /** @ITKStartGrouping */ void SetOrder(const unsigned int order) { @@ -204,7 +206,7 @@ class ITK_TEMPLATE_EXPORT GaussianDerivativeOperator : public NeighborhoodOperat { return m_Order; } - + /** @ITKEndGrouping */ void PrintSelf(std::ostream & os, Indent indent) const override; diff --git a/Modules/Core/Common/include/itkGaussianDerivativeOperator.hxx b/Modules/Core/Common/include/itkGaussianDerivativeOperator.hxx index d5a2426cf08..0a5a26ba25f 100644 --- a/Modules/Core/Common/include/itkGaussianDerivativeOperator.hxx +++ b/Modules/Core/Common/include/itkGaussianDerivativeOperator.hxx @@ -42,7 +42,7 @@ GaussianDerivativeOperator::GenerateCoefficients // Calculate scale-space normalization factor for derivatives double norm; - if (m_NormalizeAcrossScale && m_Order) + if (m_NormalizeAcrossScale) { norm = std::pow(m_Variance, m_Order / 2.0); } @@ -64,7 +64,7 @@ GaussianDerivativeOperator::GenerateCoefficients // operator, then the output kernel needs to be padded by N-1. For // these values to be computed the input kernel needs to be padded // by 2N-1 on both sides. - unsigned int N = (derivOp.Size() - 1) / 2; + const unsigned int N = (derivOp.Size() - 1) / 2; // copy the gaussian operator adding clamped boundary condition CoefficientVector paddedCoeff(coeff.size() + 4 * N - 2); @@ -88,7 +88,7 @@ GaussianDerivativeOperator::GenerateCoefficients // current index in derivative op for (unsigned int j = 0; j < derivOp.Size(); ++j) { - unsigned int k = i + j - derivOp.Size() / 2; + const unsigned int k = i + j - derivOp.Size() / 2; conv += paddedCoeff[k] * derivOp[derivOp.Size() - 1 - j]; } @@ -103,20 +103,19 @@ template auto GaussianDerivativeOperator::GenerateGaussianCoefficients() const -> CoefficientVector { - - CoefficientVector coeff; - // Use image spacing to modify variance const double pixelVariance = m_Variance / (m_Spacing * m_Spacing); // Now create coefficients as if they were zero order coeffs - const double et = std::exp(-pixelVariance); - const double cap = 1.0 - m_MaximumError; - CompensatedSummation sum; + const double et = std::exp(-pixelVariance); + const double cap = 1.0 - m_MaximumError; + // Create the kernel coefficients as a std::vector + CoefficientVector coeff; coeff.push_back(et * ModifiedBesselI0(pixelVariance)); - sum += coeff[0]; + + CompensatedSummation sum = coeff[0]; coeff.push_back(et * ModifiedBesselI1(pixelVariance)); sum += coeff[1] * 2.0; @@ -156,7 +155,7 @@ GaussianDerivativeOperator::GenerateGaussianCoef } // Make symmetric - size_t s = coeff.size() - 1; + const size_t s = coeff.size() - 1; coeff.insert(coeff.begin(), s, 0); std::copy_n(coeff.rbegin(), s, coeff.begin()); @@ -167,19 +166,19 @@ template double GaussianDerivativeOperator::ModifiedBesselI0(double y) { - double d, accumulator; - double m; + double accumulator; - if ((d = itk::Math::abs(y)) < 3.75) + const double d = itk::Math::abs(y); + if (d < 3.75) { - m = y / 3.75; + double m = y / 3.75; m *= m; accumulator = 1.0 + m * (3.5156229 + m * (3.0899424 + m * (1.2067492 + m * (0.2659732 + m * (0.360768e-1 + m * 0.45813e-2))))); } else { - m = 3.75 / d; + const double m = 3.75 / d; accumulator = (std::exp(d) / std::sqrt(d)) * (0.39894228 + @@ -196,12 +195,11 @@ template double GaussianDerivativeOperator::ModifiedBesselI1(double y) { - double d, accumulator; - double m; - - if ((d = itk::Math::abs(y)) < 3.75) + double accumulator; + const double d = itk::Math::abs(y); + if (d < 3.75) { - m = y / 3.75; + double m = y / 3.75; m *= m; accumulator = d * (0.5 + m * (0.87890594 + @@ -209,7 +207,7 @@ GaussianDerivativeOperator::ModifiedBesselI1(dou } else { - m = 3.75 / d; + const double m = 3.75 / d; accumulator = 0.2282967e-1 + m * (-0.2895312e-1 + m * (0.1787654e-1 - m * 0.420059e-2)); accumulator = 0.39894228 + m * (-0.3988024e-1 + m * (-0.362018e-2 + m * (0.163801e-2 + m * (-0.1031555e-1 + m * accumulator)))); @@ -221,10 +219,8 @@ GaussianDerivativeOperator::ModifiedBesselI1(dou { return -accumulator; } - else - { - return accumulator; - } + + return accumulator; } template @@ -232,50 +228,47 @@ double GaussianDerivativeOperator::ModifiedBesselI(int n, double y) { constexpr double DIGITS = 10.0; - int j; - double qim, qi, qip, toy; - double accumulator; if (n < 2) { throw ExceptionObject(__FILE__, __LINE__, "Order of modified bessel is > 2.", ITK_LOCATION); // // placeholder } + + double accumulator; if (y == 0.0) { return 0.0; } - else + + const double toy = 2.0 / itk::Math::abs(y); + double qip = accumulator = 0.0; + double qi = 1.0; + for (int j = 2 * (n + static_cast(DIGITS * std::sqrt(static_cast(n)))); j > 0; j--) { - toy = 2.0 / itk::Math::abs(y); - qip = accumulator = 0.0; - qi = 1.0; - for (j = 2 * (n + static_cast(DIGITS * std::sqrt(static_cast(n)))); j > 0; j--) + const double qim = qip + j * toy * qi; + qip = qi; + qi = qim; + if (itk::Math::abs(qi) > 1.0e10) { - qim = qip + j * toy * qi; - qip = qi; - qi = qim; - if (itk::Math::abs(qi) > 1.0e10) - { - accumulator *= 1.0e-10; - qi *= 1.0e-10; - qip *= 1.0e-10; - } - if (j == n) - { - accumulator = qip; - } + accumulator *= 1.0e-10; + qi *= 1.0e-10; + qip *= 1.0e-10; } - accumulator *= ModifiedBesselI0(y) / qi; - if (y < 0.0 && (n & 1)) + if (j == n) { - return -accumulator; - } - else - { - return accumulator; + accumulator = qip; } } + accumulator *= ModifiedBesselI0(y) / qi; + if (y < 0.0 && (n & 1)) + { + return -accumulator; + } + else + { + return accumulator; + } } template diff --git a/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.h b/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.h index 059968be9df..1f9217389b9 100644 --- a/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.h +++ b/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.h @@ -79,6 +79,7 @@ class ITK_TEMPLATE_EXPORT GaussianDerivativeSpatialFunction : public SpatialFunc EvaluateVector(const TInput & position) const; /** Gets and sets for gaussian parameters */ + /** @ITKStartGrouping */ itkSetMacro(Scale, double); itkGetConstMacro(Scale, double); itkSetMacro(Normalized, bool); @@ -89,7 +90,7 @@ class ITK_TEMPLATE_EXPORT GaussianDerivativeSpatialFunction : public SpatialFunc itkGetConstMacro(Mean, ArrayType); itkSetMacro(Direction, unsigned int); itkGetConstMacro(Direction, unsigned int); - + /** @ITKEndGrouping */ protected: GaussianDerivativeSpatialFunction() = default; ~GaussianDerivativeSpatialFunction() override = default; diff --git a/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.hxx b/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.hxx index d50bddf26df..c1288db779f 100644 --- a/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkGaussianDerivativeSpatialFunction.hxx @@ -57,7 +57,7 @@ GaussianDerivativeSpatialFunction::Evaluate(co (2 * m_Sigma[m_Direction] * m_Sigma[m_Direction]); } - double value = + const double value = -2 * (position[m_Direction] - m_Mean[m_Direction]) * m_Scale * (1 / prefixDenom) * std::exp(-1 * suffixExp); return static_cast(value); @@ -88,7 +88,7 @@ GaussianDerivativeSpatialFunction::PrintSelf(s os << indent << "Sigma: " << m_Sigma << std::endl; os << indent << "Mean: " << m_Mean << std::endl; os << indent << "Scale: " << m_Scale << std::endl; - os << indent << "Normalized: " << (m_Normalized ? "On" : "Off") << std::endl; + itkPrintSelfBooleanMacro(Normalized); os << indent << "Direction: " << m_Direction << std::endl; } } // end namespace itk diff --git a/Modules/Core/Common/include/itkGaussianKernelFunction.h b/Modules/Core/Common/include/itkGaussianKernelFunction.h index 8aa3f5d1c23..d0d1829b188 100644 --- a/Modules/Core/Common/include/itkGaussianKernelFunction.h +++ b/Modules/Core/Common/include/itkGaussianKernelFunction.h @@ -59,21 +59,18 @@ class ITK_TEMPLATE_EXPORT GaussianKernelFunction : public KernelFunctionBase auto GaussianOperator::GenerateCoefficients() -> CoefficientVector { - CoefficientVector coeff; - double sum; - int i; - int j; - - typename CoefficientVector::iterator it; - const double et = std::exp(-m_Variance); - const double cap = 1.0 - m_MaximumError; // Create the kernel coefficients as a std::vector - sum = 0.0; + double sum = 0.0; + CoefficientVector coeff; coeff.push_back(et * ModifiedBesselI0(m_Variance)); sum += coeff[0]; coeff.push_back(et * ModifiedBesselI1(m_Variance)); sum += coeff[1] * 2.0; - for (i = 2; sum < cap; ++i) + const double cap = 1.0 - m_MaximumError; + for (int i = 2; sum < cap; ++i) { coeff.push_back(et * ModifiedBesselI(i, m_Variance)); sum += coeff[i] * 2.0; @@ -59,19 +53,21 @@ GaussianOperator::GenerateCoefficients() -> Coef } } // Normalize the coefficients so that their sum is one. - for (it = coeff.begin(); it < coeff.end(); ++it) + for (auto it = coeff.begin(); it < coeff.end(); ++it) { *it /= sum; } // Make symmetric - j = static_cast(coeff.size()) - 1; + const int j = static_cast(coeff.size()) - 1; coeff.insert(coeff.begin(), j, 0); - for (i = 0, it = coeff.end() - 1; i < j; --it, ++i) { - coeff[i] = *it; + int i = 0; + for (auto it = coeff.end() - 1; i < j; --it, ++i) + { + coeff[i] = *it; + } } - return coeff; } @@ -133,10 +129,8 @@ GaussianOperator::ModifiedBesselI1(double y) { return -accumulator; } - else - { - return accumulator; - } + + return accumulator; } template @@ -144,9 +138,6 @@ double GaussianOperator::ModifiedBesselI(int n, double y) { constexpr double ACCURACY = 40.0; - int j; - double qim, qi, qip, toy; - double accumulator; if (n < 2) { @@ -159,40 +150,39 @@ GaussianOperator::ModifiedBesselI(int n, double { return 0.0; } - else - { - toy = 2.0 / itk::Math::abs(y); - qip = accumulator = 0.0; - qi = 1.0; - - for (j = 2 * (n + static_cast(std::sqrt(ACCURACY * n))); j > 0; j--) - { - qim = qip + j * toy * qi; - qip = qi; - qi = qim; - if (itk::Math::abs(qi) > 1.0e10) - { - accumulator *= 1.0e-10; - qi *= 1.0e-10; - qip *= 1.0e-10; - } - if (j == n) - { - accumulator = qip; - } - } - accumulator *= ModifiedBesselI0(y) / qi; + const double toy = 2.0 / itk::Math::abs(y); + double qip = 0.0; + double accumulator = 0.0; + double qi = 1.0; - if (y < 0.0 && (n & 1)) + for (int j = 2 * (n + static_cast(std::sqrt(ACCURACY * n))); j > 0; j--) + { + const double qim = qip + j * toy * qi; + qip = qi; + qi = qim; + if (itk::Math::abs(qi) > 1.0e10) { - return -accumulator; + accumulator *= 1.0e-10; + qi *= 1.0e-10; + qip *= 1.0e-10; } - else + if (j == n) { - return accumulator; + accumulator = qip; } } + + accumulator *= ModifiedBesselI0(y) / qi; + + if (y < 0.0 && (n & 1)) + { + return -accumulator; + } + else + { + return accumulator; + } } } // end namespace itk diff --git a/Modules/Core/Common/include/itkGaussianSpatialFunction.h b/Modules/Core/Common/include/itkGaussianSpatialFunction.h index 94965a76413..8cac689a343 100644 --- a/Modules/Core/Common/include/itkGaussianSpatialFunction.h +++ b/Modules/Core/Common/include/itkGaussianSpatialFunction.h @@ -72,22 +72,26 @@ class ITK_TEMPLATE_EXPORT GaussianSpatialFunction : public SpatialFunction::PrintSelf(std::ostrea os << indent << "Sigma: " << m_Sigma << std::endl; os << indent << "Mean: " << m_Mean << std::endl; os << indent << "Scale: " << m_Scale << std::endl; - os << indent << "Normalized: " << (m_Normalized ? "On" : "Off") << std::endl; + itkPrintSelfBooleanMacro(Normalized); } } // end namespace itk diff --git a/Modules/Core/Common/include/itkHeavisideStepFunction.h b/Modules/Core/Common/include/itkHeavisideStepFunction.h index a649e826066..7435ebb2731 100644 --- a/Modules/Core/Common/include/itkHeavisideStepFunction.h +++ b/Modules/Core/Common/include/itkHeavisideStepFunction.h @@ -34,21 +34,9 @@ namespace itk * * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. * - * This code was taken from the Insight Journal paper: - * - * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" - * https://www.insight-journal.org/browse/publication/642 - * - * That is based on the papers: - * - * "Level Set Segmentation: Active Contours without edge" - * https://www.insight-journal.org/browse/publication/322 - * - * and - * - * "Level set segmentation using coupled active surfaces" - * https://www.insight-journal.org/browse/publication/323 - * + * This code was taken from the Insight Journal paper \cite Mosaliganti_2009_c + * that is based on the papers \cite Mosaliganti_2009_a and + * \cite Mosaliganti_2009_b. * * \ingroup ITKCommon */ diff --git a/Modules/Core/Common/include/itkHeavisideStepFunctionBase.h b/Modules/Core/Common/include/itkHeavisideStepFunctionBase.h index 00d8cc73093..4021974a0c0 100644 --- a/Modules/Core/Common/include/itkHeavisideStepFunctionBase.h +++ b/Modules/Core/Common/include/itkHeavisideStepFunctionBase.h @@ -29,21 +29,9 @@ namespace itk * * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. * - * This code was taken from the Insight Journal paper: - * - * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" - * https://www.insight-journal.org/browse/publication/642 - * - * That is based on the papers: - * - * "Level Set Segmentation: Active Contours without edge" - * https://www.insight-journal.org/browse/publication/322 - * - * and - * - * "Level set segmentation using coupled active surfaces" - * https://www.insight-journal.org/browse/publication/323 - * + * This code was taken from the Insight Journal paper \cite Mosaliganti_2009_c + * that is based on the papers \cite Mosaliganti_2009_a and + * \cite Mosaliganti_2009_b. * * \ingroup ITKCommon */ @@ -73,11 +61,9 @@ class ITK_TEMPLATE_EXPORT HeavisideStepFunctionBase : public FunctionBase)); itkConceptMacro(DoubleConvertibleToOutputCheck, (Concept::Convertible)); -#endif // ITK_USE_CONCEPT_CHECKING protected: HeavisideStepFunctionBase() diff --git a/Modules/Core/Common/include/itkHexahedronCell.h b/Modules/Core/Common/include/itkHexahedronCell.h index cb7fd3f61f0..810ec0c5b4d 100644 --- a/Modules/Core/Common/include/itkHexahedronCell.h +++ b/Modules/Core/Common/include/itkHexahedronCell.h @@ -31,11 +31,6 @@ namespace itk * * HexahedronCell represents a hexahedron, more precisely, a cuboid, for a Mesh. * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. - * * \todo When reviewing this class, the documentation of the template * parameters MUST be fixed. * @@ -55,9 +50,10 @@ class ITK_TEMPLATE_EXPORT HexahedronCell ITK_DISALLOW_COPY_AND_MOVE(HexahedronCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(HexahedronCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(HexahedronCell); @@ -87,7 +83,9 @@ class ITK_TEMPLATE_EXPORT HexahedronCell */ static constexpr unsigned int CellDimension3D = 3; static constexpr unsigned int PointDimension3D = 3; + /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -95,7 +93,7 @@ class ITK_TEMPLATE_EXPORT HexahedronCell } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ unsigned int GetDimension() const override; @@ -146,10 +144,10 @@ class ITK_TEMPLATE_EXPORT HexahedronCell /** Evaluate the position inside the cell */ bool - EvaluatePosition(CoordRepType *, + EvaluatePosition(CoordinateType *, PointsContainer *, - CoordRepType *, - CoordRepType[], + CoordinateType *, + CoordinateType[], double *, InterpolationWeightType *) override; @@ -162,15 +160,15 @@ class ITK_TEMPLATE_EXPORT HexahedronCell NumericTraits::max()) }; void - InterpolationDerivs(CoordRepType pcoords[Self::CellDimension], - CoordRepType derivs[Self::CellDimension * Self::NumberOfPoints]); + InterpolationDerivs(CoordinateType pcoords[Self::CellDimension], + CoordinateType derivs[Self::CellDimension * Self::NumberOfPoints]); void - InterpolationFunctions(CoordRepType pcoords[Self::CellDimension], InterpolationWeightType sf[Self::NumberOfPoints]); + InterpolationFunctions(CoordinateType pcoords[Self::CellDimension], InterpolationWeightType sf[Self::NumberOfPoints]); void EvaluateLocation(int & itkNotUsed(subId), PointsContainer * points, - CoordRepType pcoords[Self::CellDimension], - CoordRepType x[Self::CellDimension], + CoordinateType pcoords[Self::CellDimension], + CoordinateType x[Self::CellDimension], InterpolationWeightType * weights); public: diff --git a/Modules/Core/Common/include/itkHexahedronCell.hxx b/Modules/Core/Common/include/itkHexahedronCell.hxx index 1aca6755d7a..c202e964fbe 100644 --- a/Modules/Core/Common/include/itkHexahedronCell.hxx +++ b/Modules/Core/Common/include/itkHexahedronCell.hxx @@ -320,10 +320,10 @@ HexahedronCell::GetFace(CellFeatureIdentifier faceId, FaceAutoPo /** Evaluate the position inside the cell */ template bool -HexahedronCell::EvaluatePosition(CoordRepType * x, +HexahedronCell::EvaluatePosition(CoordinateType * x, PointsContainer * points, - CoordRepType * closestPoint, - CoordRepType pcoord[], + CoordinateType * closestPoint, + CoordinateType pcoord[], double * dist2, InterpolationWeightType * weight) { @@ -339,19 +339,12 @@ HexahedronCell::EvaluatePosition(CoordRepType * x, static constexpr double ITK_HEX_CONVERGED = 1.e-03; static constexpr double ITK_DIVERGED = 1.e6; - double params[Self::CellDimension3D]{ 0.5, 0.5, 0.5 }; - double fcol[Self::PointDimension3D]; - double rcol[Self::PointDimension3D]; - double scol[Self::PointDimension3D]; - double tcol[Self::PointDimension3D]; - double d; - PointType pt; - CoordRepType derivs[CellDimension3D * Self::NumberOfPoints]{ 0 }; + CoordinateType derivs[CellDimension3D * Self::NumberOfPoints]{ 0 }; InterpolationWeightType weights[Self::NumberOfPoints]; // set initial position for Newton's method - int subId{ 0 }; - CoordRepType pcoords[CellDimension3D]{ 0.5, 0.5, 0.5 }; + int subId{ 0 }; + CoordinateType pcoords[CellDimension3D]{ 0.5, 0.5, 0.5 }; // NOTE: Avoid compiler warning. The code below only runs if PointType::Dimension == Self::PointDimension3D constexpr unsigned int PREVENT_OVERRUN_OF_INVALID_INSTANTIATIONS = @@ -366,14 +359,18 @@ HexahedronCell::EvaluatePosition(CoordRepType * x, this->InterpolationDerivs(pcoords, derivs); // calculate newton functions + double fcol[Self::PointDimension3D]; + double rcol[Self::PointDimension3D]; + double scol[Self::PointDimension3D]; + double tcol[Self::PointDimension3D]; for (unsigned int i = 0; i < Self::PointDimension3D; ++i) { fcol[i] = rcol[i] = scol[i] = tcol[i] = 0.0; } + for (unsigned int i = 0; i < Self::NumberOfPoints; ++i) { - - pt = points->GetElement(m_PointIds[i]); + PointType pt = points->GetElement(m_PointIds[i]); for (unsigned int j = 0; j < PREVENT_OVERRUN_OF_INVALID_INSTANTIATIONS; ++j) { fcol[j] += pt[j] * weights[i]; @@ -392,7 +389,7 @@ HexahedronCell::EvaluatePosition(CoordRepType * x, static_assert(Self::PointDimension3D == HARD_CODED_POINT_DIM, "ERROR: Self::PointDimension3D does not equal HARD_CODED_POINT_DIM (i.e. 3)."); // compute determinants and generate improvements - vnl_matrix_fixed mat; + vnl_matrix_fixed mat; for (unsigned int i = 0; i < Self::PointDimension3D; ++i) { mat.put(0, i, rcol[i]); @@ -401,14 +398,14 @@ HexahedronCell::EvaluatePosition(CoordRepType * x, } // ONLY 3x3 determinants are supported. - d = vnl_determinant(mat); + const double d = vnl_determinant(mat); // d=vtkMath::Determinant3x3(rcol,scol,tcol); if (itk::Math::abs(d) < 1.e-20) { return false; } - vnl_matrix_fixed mat1; + vnl_matrix_fixed mat1; for (unsigned int i = 0; i < Self::PointDimension3D; ++i) { mat1.put(0, i, fcol[i]); @@ -416,7 +413,7 @@ HexahedronCell::EvaluatePosition(CoordRepType * x, mat1.put(2, i, tcol[i]); } - vnl_matrix_fixed mat2; + vnl_matrix_fixed mat2; for (unsigned int i = 0; i < Self::PointDimension3D; ++i) { mat2.put(0, i, rcol[i]); @@ -424,14 +421,14 @@ HexahedronCell::EvaluatePosition(CoordRepType * x, mat2.put(2, i, tcol[i]); } - vnl_matrix_fixed mat3; + vnl_matrix_fixed mat3; for (unsigned int i = 0; i < Self::PointDimension3D; ++i) { mat3.put(0, i, rcol[i]); mat3.put(1, i, scol[i]); mat3.put(2, i, fcol[i]); } - + double params[Self::CellDimension3D]{ 0.5, 0.5, 0.5 }; pcoords[0] = params[0] - vnl_determinant(mat1) / d; pcoords[1] = params[1] - vnl_determinant(mat2) / d; pcoords[2] = params[2] - vnl_determinant(mat3) / d; @@ -455,7 +452,7 @@ HexahedronCell::EvaluatePosition(CoordRepType * x, else if ((itk::Math::abs(pcoords[0]) > ITK_DIVERGED) || (itk::Math::abs(pcoords[1]) > ITK_DIVERGED) || (itk::Math::abs(pcoords[2]) > ITK_DIVERGED)) { - return -1; + return false; } // if not converged, repeat @@ -499,43 +496,42 @@ HexahedronCell::EvaluatePosition(CoordRepType * x, } return true; } - else + + CoordinateType pc[CellDimension3D]; + if (closestPoint) { - CoordRepType pc[CellDimension3D], w[Self::NumberOfPoints]; - if (closestPoint) + for (unsigned int i = 0; i < CellDimension3D; ++i) // only approximate, not really true + // for warped hexa { - for (unsigned int i = 0; i < CellDimension3D; ++i) // only approximate, not really true - // for warped hexa + if (pcoords[i] < 0.0) { - if (pcoords[i] < 0.0) - { - pc[i] = 0.0; - } - else if (pcoords[i] > 1.0) - { - pc[i] = 1.0; - } - else - { - pc[i] = pcoords[i]; - } + pc[i] = 0.0; } - this->EvaluateLocation(subId, points, pc, closestPoint, (InterpolationWeightType *)w); - - *dist2 = 0; - for (unsigned int i = 0; i < Self::PointDimension3D; ++i) + else if (pcoords[i] > 1.0) { - *dist2 += (closestPoint[i] - x[i]) * (closestPoint[i] - x[i]); + pc[i] = 1.0; + } + else + { + pc[i] = pcoords[i]; } } - return false; + CoordinateType w[Self::NumberOfPoints]; + this->EvaluateLocation(subId, points, pc, closestPoint, (InterpolationWeightType *)w); + + *dist2 = 0; + for (unsigned int i = 0; i < Self::PointDimension3D; ++i) + { + *dist2 += (closestPoint[i] - x[i]) * (closestPoint[i] - x[i]); + } } + return false; } /** Compute iso-parametric interpolation functions */ template void -HexahedronCell::InterpolationFunctions(CoordRepType pcoords[Self::CellDimension], +HexahedronCell::InterpolationFunctions(CoordinateType pcoords[Self::CellDimension], InterpolationWeightType sf[Self::NumberOfPoints]) { // Throw an exception if trying to EvaluatePosition for anything other than @@ -547,7 +543,7 @@ HexahedronCell::InterpolationFunctions(CoordRepType p } else { - CoordRepType pcoords3D[Self::CellDimension3D]{ 0 }; + CoordinateType pcoords3D[Self::CellDimension3D]{ 0 }; // NOTE: Avoid compiler warning. The code below only runs if PointType::Dimension == Self::PointDimension3D constexpr unsigned int PREVENT_OVERRUN_OF_INVALID_INSTANTIATIONS = hexahedron_constexpr_min(PointType::Dimension, Self::PointDimension3D); @@ -579,8 +575,8 @@ HexahedronCell::InterpolationFunctions(CoordRepType p /** Compute iso-parametric interpolation functions */ template void -HexahedronCell::InterpolationDerivs(CoordRepType pcoords[Self::CellDimension], - CoordRepType derivs[Self::CellDimension * Self::NumberOfPoints]) +HexahedronCell::InterpolationDerivs(CoordinateType pcoords[Self::CellDimension], + CoordinateType derivs[Self::CellDimension * Self::NumberOfPoints]) { // Throw an exception if trying to EvaluatePosition for anything other than // a 3D point or cell dimension. This implementation is hard-coded to 3D. @@ -592,8 +588,8 @@ HexahedronCell::InterpolationDerivs(CoordRepType pcoords[Self::C else { - CoordRepType pcoords3D[Self::CellDimension3D]{ 0 }; - CoordRepType derivs3D[Self::CellDimension3D * Self::NumberOfPoints]{ 0 }; + CoordinateType pcoords3D[Self::CellDimension3D]{ 0 }; + CoordinateType derivs3D[Self::CellDimension3D * Self::NumberOfPoints]{ 0 }; // NOTE: Avoid compiler warning. The code below only runs if PointType::Dimension == Self::PointDimension3D constexpr unsigned int PREVENT_OVERRUN_OF_INVALID_INSTANTIATIONS = hexahedron_constexpr_min(PointType::Dimension, Self::PointDimension3D); @@ -657,8 +653,8 @@ template void HexahedronCell::EvaluateLocation(int & itkNotUsed(subId), PointsContainer * points, - CoordRepType pcoords[Self::CellDimension], - CoordRepType x[Self::CellDimension], + CoordinateType pcoords[Self::CellDimension], + CoordinateType x[Self::CellDimension], InterpolationWeightType * weights) { // Throw an exception if trying to EvaluatePosition for anything other than @@ -683,7 +679,7 @@ HexahedronCell::EvaluateLocation(int & itkNo for (unsigned int j = 0; j < PREVENT_OVERRUN_OF_INVALID_INSTANTIATIONS; ++j) { - const CoordRepType t = pt[j] * weights[i]; + const CoordinateType t = pt[j] * weights[i]; x[j] += t; } } diff --git a/Modules/Core/Common/include/itkImage.h b/Modules/Core/Common/include/itkImage.h index 6613887be9a..adae393cf97 100644 --- a/Modules/Core/Common/include/itkImage.h +++ b/Modules/Core/Common/include/itkImage.h @@ -171,7 +171,7 @@ class ITK_TEMPLATE_EXPORT Image : public ImageBase * example usage: * using OutputImageType = typename ImageType::template Rebind< float >::Type; * - * \deprecated Use RebindImageType instead + * Deprecated: Use RebindImageType instead */ template struct Rebind @@ -207,7 +207,7 @@ class ITK_TEMPLATE_EXPORT Image : public ImageBase void SetPixel(const IndexType & index, const TPixel & value) { - OffsetValueType offset = this->FastComputeOffset(index); + const OffsetValueType offset = this->FastComputeOffset(index); (*m_Buffer)[offset] = value; } @@ -218,7 +218,7 @@ class ITK_TEMPLATE_EXPORT Image : public ImageBase const TPixel & GetPixel(const IndexType & index) const { - OffsetValueType offset = this->FastComputeOffset(index); + const OffsetValueType offset = this->FastComputeOffset(index); return ((*m_Buffer)[offset]); } @@ -229,7 +229,7 @@ class ITK_TEMPLATE_EXPORT Image : public ImageBase TPixel & GetPixel(const IndexType & index) { - OffsetValueType offset = this->FastComputeOffset(index); + const OffsetValueType offset = this->FastComputeOffset(index); return ((*m_Buffer)[offset]); } @@ -237,16 +237,25 @@ class ITK_TEMPLATE_EXPORT Image : public ImageBase * * For efficiency, this function does not check that the * image has actually been allocated yet. */ - TPixel & operator[](const IndexType & index) { return this->GetPixel(index); } + TPixel & + operator[](const IndexType & index) + { + return this->GetPixel(index); + } /** \brief Access a pixel. This version can only be an rvalue. * * For efficiency, this function does not check that the * image has actually been allocated yet. */ - const TPixel & operator[](const IndexType & index) const { return this->GetPixel(index); } + const TPixel & + operator[](const IndexType & index) const + { + return this->GetPixel(index); + } /** Return a pointer to the beginning of the buffer. This is used by * the image iterator class. */ + /** @ITKStartGrouping */ virtual TPixel * GetBufferPointer() { @@ -257,7 +266,7 @@ class ITK_TEMPLATE_EXPORT Image : public ImageBase { return m_Buffer ? m_Buffer->GetBufferPointer() : nullptr; } - + /** @ITKEndGrouping */ /** Return a pointer to the container. */ PixelContainer * GetPixelContainer() diff --git a/Modules/Core/Common/include/itkImageAlgorithm.h b/Modules/Core/Common/include/itkImageAlgorithm.h index 8f072948707..c05b6e14e11 100644 --- a/Modules/Core/Common/include/itkImageAlgorithm.h +++ b/Modules/Core/Common/include/itkImageAlgorithm.h @@ -193,7 +193,6 @@ struct ImageAlgorithm } }; - /** Function to dispatch to std::copy or std::transform. */ template static TType * diff --git a/Modules/Core/Common/include/itkImageAlgorithm.hxx b/Modules/Core/Common/include/itkImageAlgorithm.hxx index 8cead5f2ff6..5bf85f8564d 100644 --- a/Modules/Core/Common/include/itkImageAlgorithm.hxx +++ b/Modules/Core/Common/include/itkImageAlgorithm.hxx @@ -207,7 +207,7 @@ ImageAlgorithm::EnlargeRegionOverBox(const typename InputImageType::RegionType & { numberOfInputCorners *= 2; } - using ContinuousIndexValueType = double; + using ContinuousIndexValueType = ContinuousIndex::ValueType; using ContinuousInputIndexType = ContinuousIndex; using ContinuousOutputIndexType = ContinuousIndex; @@ -216,9 +216,8 @@ ImageAlgorithm::EnlargeRegionOverBox(const typename InputImageType::RegionType & for (unsigned int count = 0; count < numberOfInputCorners; ++count) { - ContinuousInputIndexType currentInputCornerIndex; - currentInputCornerIndex.Fill(0); - unsigned int localCount = count; + ContinuousInputIndexType currentInputCornerIndex{}; + unsigned int localCount = count; // For each dimension, set the current index to either // the highest or lowest index along this dimension. @@ -241,10 +240,11 @@ ImageAlgorithm::EnlargeRegionOverBox(const typename InputImageType::RegionType & } using InputPointType = Point; + const InputPointType inputPoint = + inputImage->template TransformContinuousIndexToPhysicalPoint( + currentInputCornerIndex); using OutputPointType = Point; - InputPointType inputPoint; - OutputPointType outputPoint; - inputImage->TransformContinuousIndexToPhysicalPoint(currentInputCornerIndex, inputPoint); + OutputPointType outputPoint{}; if (transform != nullptr) { outputPoint = transform->TransformPoint(inputPoint); @@ -254,7 +254,6 @@ ImageAlgorithm::EnlargeRegionOverBox(const typename InputImageType::RegionType & // if InputDimension < OutputDimension then embed point in Output space. // else if InputDimension == OutputDimension copy the points. // else if InputDimension > OutputDimension project the point to first N-Dimensions of Output space. - outputPoint.Fill(0.0); for (unsigned int d = 0; d < std::min(inputPoint.GetPointDimension(), outputPoint.GetPointDimension()); ++d) { outputPoint[d] = inputPoint[d]; diff --git a/Modules/Core/Common/include/itkImageBase.h b/Modules/Core/Common/include/itkImageBase.h index 579507352b2..9809f5db000 100644 --- a/Modules/Core/Common/include/itkImageBase.h +++ b/Modules/Core/Common/include/itkImageBase.h @@ -174,8 +174,8 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject void Initialize() override; - /** Image dimension. The dimension of an image is fixed at construction. */ - static unsigned int + /** Image dimension. The dimension of an image is fixed at compile-time. */ + static constexpr unsigned int GetImageDimension() { return VImageDimension; @@ -185,12 +185,13 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * coordinates of the image origin (pixel [0,0]). It is stored internally * as SpacePrecisionType but may be set from float or double. * \sa GetOrigin() */ + /** @ITKStartGrouping */ itkSetMacro(Origin, PointType); virtual void SetOrigin(const double origin[VImageDimension]); virtual void SetOrigin(const float origin[VImageDimension]); - + /** @ITKEndGrouping */ /** Set the direction cosines of the image. The direction cosines * are vectors that point from one pixel to the next. * @@ -249,7 +250,8 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * */ virtual void - Allocate(bool initialize = false); + Allocate(bool itkNotUsed(initialize) = false) + {} /** Allocates the pixel buffer of the image, zero-initializing its pixels. `AllocateInitialized()` is equivalent to * `Allocate(true)`. It is just intended to make the code more readable. */ @@ -328,6 +330,7 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject /** Convenience methods to set the LargestPossibleRegion, * BufferedRegion and RequestedRegion. Allocate must still be called. */ + /** @ITKStartGrouping */ virtual void SetRegions(const RegionType & region) { @@ -344,6 +347,7 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject this->Self::SetRegions(region); } + /** @ITKEndGrouping */ /** Get the offset table. The offset table gives increments for * moving from one pixel to next in the current row, column, slice, @@ -433,13 +437,14 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * float. These methods also pre-compute the Index to Physical point * transforms of the image. * \sa GetSpacing() */ + /** @ITKStartGrouping */ virtual void SetSpacing(const SpacingType & spacing); virtual void SetSpacing(const double spacing[VImageDimension]); virtual void SetSpacing(const float spacing[VImageDimension]); - + /** @ITKEndGrouping */ /** Returns the index (discrete) of a voxel from a physical point. * Floating point index results are rounded to integers * \note This specific overload does not figure out whether or not @@ -455,15 +460,15 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject if (image->TransformPhysicalPointToIndex(point, index)) // Et cetera... \endcode * \sa Transform */ - template + template [[nodiscard]] IndexType - TransformPhysicalPointToIndex(const Point & point) const + TransformPhysicalPointToIndex(const Point & point) const { IndexType index; for (unsigned int i = 0; i < VImageDimension; ++i) { - TCoordRep sum{}; + TCoordinate sum{}; for (unsigned int j = 0; j < VImageDimension; ++j) { sum += this->m_PhysicalPointToIndex[i][j] * (point[j] - this->m_Origin[j]); @@ -481,9 +486,9 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * overload instead, which has only one parameter (the point), and returns the index. * * \sa Transform */ - template + template ITK_NODISCARD("Call the overload which has the point as the only parameter and returns the index") - bool TransformPhysicalPointToIndex(const Point & point, IndexType & index) const + bool TransformPhysicalPointToIndex(const Point & point, IndexType & index) const { index = TransformPhysicalPointToIndex(point); @@ -507,9 +512,9 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject if (image->TransformPhysicalPointToContinuousIndex(point, index)) // Et cetera... \endcode * \sa Transform */ - template + template [[nodiscard]] ContinuousIndex - TransformPhysicalPointToContinuousIndex(const Point & point) const + TransformPhysicalPointToContinuousIndex(const Point & point) const { ContinuousIndex index; Vector cvector; @@ -534,9 +539,9 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * overload instead, which has only one parameter (the point), and returns the continuous index. * * \sa Transform */ - template + template ITK_NODISCARD("Call the overload which has the point as the only parameter and returns the index") - bool TransformPhysicalPointToContinuousIndex(const Point & point, + bool TransformPhysicalPointToContinuousIndex(const Point & point, ContinuousIndex & index) const { index = TransformPhysicalPointToContinuousIndex(point); @@ -550,14 +555,14 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * the origin and spacing information comes from) * from a continuous index (in the index space) * \sa Transform */ - template + template void TransformContinuousIndexToPhysicalPoint(const ContinuousIndex & index, - Point & point) const + Point & point) const { for (unsigned int r = 0; r < VImageDimension; ++r) { - TCoordRep sum{}; + TCoordinate sum{}; for (unsigned int c = 0; c < VImageDimension; ++c) { sum += this->m_IndexToPhysicalPoint(r, c) * index[c]; @@ -570,11 +575,11 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * the origin and spacing information comes from) * from a continuous index (in the index space) * \sa Transform */ - template - [[nodiscard]] Point + template + [[nodiscard]] Point TransformContinuousIndexToPhysicalPoint(const ContinuousIndex & index) const { - Point point; + Point point; TransformContinuousIndexToPhysicalPoint(index, point); return point; } @@ -584,9 +589,9 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * from a discrete index (in the index space) * * \sa Transform */ - template + template void - TransformIndexToPhysicalPoint(const IndexType & index, Point & point) const + TransformIndexToPhysicalPoint(const IndexType & index, Point & point) const { for (unsigned int i = 0; i < VImageDimension; ++i) { @@ -603,11 +608,11 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * from a discrete index (in the index space) * * \sa Transform */ - template - [[nodiscard]] Point + template + [[nodiscard]] Point TransformIndexToPhysicalPoint(const IndexType & index) const { - Point point; + Point point; TransformIndexToPhysicalPoint(index, point); return point; } @@ -626,10 +631,10 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * * \sa Image */ - template + template void - TransformLocalVectorToPhysicalVector(const FixedArray & inputGradient, - FixedArray & outputGradient) const + TransformLocalVectorToPhysicalVector(const FixedArray & inputGradient, + FixedArray & outputGradient) const { const DirectionType & direction = this->GetDirection(); @@ -637,13 +642,13 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject for (unsigned int i = 0; i < VImageDimension; ++i) { - using CoordSumType = typename NumericTraits::AccumulateType; + using CoordSumType = typename NumericTraits::AccumulateType; CoordSumType sum{}; for (unsigned int j = 0; j < VImageDimension; ++j) { sum += direction[i][j] * inputGradient[j]; } - outputGradient[i] = static_cast(sum); + outputGradient[i] = static_cast(sum); } } @@ -675,10 +680,10 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * same data. * */ - template + template void - TransformPhysicalVectorToLocalVector(const FixedArray & inputGradient, - FixedArray & outputGradient) const + TransformPhysicalVectorToLocalVector(const FixedArray & inputGradient, + FixedArray & outputGradient) const { const DirectionType & inverseDirection = this->GetInverseDirection(); @@ -686,13 +691,13 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject for (unsigned int i = 0; i < VImageDimension; ++i) { - using CoordSumType = typename NumericTraits::AccumulateType; + using CoordSumType = typename NumericTraits::AccumulateType; CoordSumType sum{}; for (unsigned int j = 0; j < VImageDimension; ++j) { sum += inverseDirection[i][j] * inputGradient[j]; } - outputGradient[i] = static_cast(sum); + outputGradient[i] = static_cast(sum); } } @@ -821,11 +826,12 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject * # returned from NumericTraits for the pixel type, and VectorImage * returns the vector length set by the user. */ + /** @ITKStartGrouping */ virtual unsigned int GetNumberOfComponentsPerPixel() const; virtual void SetNumberOfComponentsPerPixel(unsigned int); - + /** @ITKEndGrouping */ protected: ImageBase() = default; ~ImageBase() override = default; @@ -851,16 +857,18 @@ class ITK_TEMPLATE_EXPORT ImageBase : public DataObject /** Origin, spacing, and direction in physical coordinates. This variables are * protected for efficiency. They are referenced frequently by * inner loop calculations. */ + /** @ITKStartGrouping */ SpacingType m_Spacing{ MakeFilled(1.0) }; PointType m_Origin{}; DirectionType m_Direction{ DirectionType::GetIdentity() }; DirectionType m_InverseDirection{ DirectionType::GetIdentity() }; - + /** @ITKEndGrouping */ /** Matrices intended to help with the conversion of Index coordinates * to PhysicalPoint coordinates */ + /** @ITKStartGrouping */ DirectionType m_IndexToPhysicalPoint{ DirectionType::GetIdentity() }; DirectionType m_PhysicalPointToIndex{ DirectionType::GetIdentity() }; - + /** @ITKEndGrouping */ /** Restores the buffered region to its default state * This method does not call Modify because Initialization is * called by ReleaseData and can not modify the MTime diff --git a/Modules/Core/Common/include/itkImageBase.hxx b/Modules/Core/Common/include/itkImageBase.hxx index f67fd5f4193..9b6e92cf990 100644 --- a/Modules/Core/Common/include/itkImageBase.hxx +++ b/Modules/Core/Common/include/itkImageBase.hxx @@ -37,13 +37,6 @@ namespace itk { - -template -void -ImageBase::Allocate(bool) -{} - - template void ImageBase::Initialize() @@ -347,14 +340,13 @@ template bool ImageBase::RequestedRegionIsOutsideOfTheBufferedRegion() { - unsigned int i; const IndexType & requestedRegionIndex = this->GetRequestedRegion().GetIndex(); const IndexType & bufferedRegionIndex = this->GetBufferedRegion().GetIndex(); const SizeType & requestedRegionSize = this->GetRequestedRegion().GetSize(); const SizeType & bufferedRegionSize = this->GetBufferedRegion().GetSize(); - for (i = 0; i < VImageDimension; ++i) + for (unsigned int i = 0; i < VImageDimension; ++i) { if ((requestedRegionIndex[i] < bufferedRegionIndex[i]) || ((requestedRegionIndex[i] + static_cast(requestedRegionSize[i])) > @@ -372,9 +364,6 @@ template bool ImageBase::VerifyRequestedRegion() { - bool retval = true; - unsigned int i; - // Is the requested region within the LargestPossibleRegion? // Note that the test is indeed against the largest possible region // rather than the buffered region; see DataObject::VerifyRequestedRegion. @@ -384,17 +373,16 @@ ImageBase::VerifyRequestedRegion() const SizeType & requestedRegionSize = this->GetRequestedRegion().GetSize(); const SizeType & largestPossibleRegionSize = this->GetLargestPossibleRegion().GetSize(); - for (i = 0; i < VImageDimension; ++i) + for (unsigned int i = 0; i < VImageDimension; ++i) { if ((requestedRegionIndex[i] < largestPossibleRegionIndex[i]) || ((requestedRegionIndex[i] + static_cast(requestedRegionSize[i])) > (largestPossibleRegionIndex[i] + static_cast(largestPossibleRegionSize[i])))) { - retval = false; + return false; // Short circuit return on first dimension test failure. } } - - return retval; + return true; } @@ -528,16 +516,18 @@ ImageBase::PrintSelf(std::ostream & os, Indent indent) const os << indent << "Origin: " << this->GetOrigin() << std::endl; - os << indent << "Direction: " << std::endl << this->GetDirection() << std::endl; + + os << indent << "Direction: " << std::endl; + this->GetDirection().PrintSelf(os, indent.GetNextIndent()); os << indent << "IndexToPointMatrix: " << std::endl; - os << this->m_IndexToPhysicalPoint << std::endl; + this->m_IndexToPhysicalPoint.PrintSelf(os, indent.GetNextIndent()); os << indent << "PointToIndexMatrix: " << std::endl; - os << this->m_PhysicalPointToIndex << std::endl; + this->m_PhysicalPointToIndex.PrintSelf(os, indent.GetNextIndent()); os << indent << "Inverse Direction: " << std::endl; - os << this->GetInverseDirection() << std::endl; + this->m_InverseDirection.PrintSelf(os, indent.GetNextIndent()); } } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageBoundaryCondition.h b/Modules/Core/Common/include/itkImageBoundaryCondition.h index aa0ced6394e..b2957e4814f 100644 --- a/Modules/Core/Common/include/itkImageBoundaryCondition.h +++ b/Modules/Core/Common/include/itkImageBoundaryCondition.h @@ -129,9 +129,9 @@ class ITK_TEMPLATE_EXPORT ImageBoundaryCondition * pixel values in the outputRequestedRegion. */ virtual RegionType - GetInputRequestedRegion(const RegionType & inputLargestPossibleRegion, const RegionType & outputRequestedRegion) const + GetInputRequestedRegion(const RegionType & inputLargestPossibleRegion, + [[maybe_unused]] const RegionType & itkNotUsed(outputRequestedRegion)) const { - (void)outputRequestedRegion; return inputLargestPossibleRegion; } diff --git a/Modules/Core/Common/include/itkImageBufferRange.h b/Modules/Core/Common/include/itkImageBufferRange.h index 28134ad4482..25f06d61504 100644 --- a/Modules/Core/Common/include/itkImageBufferRange.h +++ b/Modules/Core/Common/include/itkImageBufferRange.h @@ -317,7 +317,8 @@ class ImageBufferRange final /** Returns a reference to the current pixel. */ - reference operator*() const noexcept + reference + operator*() const noexcept { assert(m_InternalPixelPointer != nullptr); @@ -472,7 +473,11 @@ class ImageBufferRange final /** Returns it[n] for iterator 'it' and integer value 'n'. */ - reference operator[](const difference_type n) const noexcept { return *(*this + n); } + reference + operator[](const difference_type n) const noexcept + { + return *(*this + n); + } }; static constexpr bool IsImageTypeConst = std::is_const_v; @@ -648,7 +653,8 @@ class ImageBufferRange final * \note The return type QualifiedIterator::reference is equivalent to * iterator::reference. */ - typename QualifiedIterator::reference operator[](const size_t n) const noexcept + typename QualifiedIterator::reference + operator[](const size_t n) const noexcept { assert(n < this->size()); assert(n <= static_cast(std::numeric_limits::max())); @@ -660,7 +666,7 @@ class ImageBufferRange final // Deduction guide to avoid compiler warnings (-wctad-maybe-unsupported) when using class template argument deduction. template -ImageBufferRange(TImage &)->ImageBufferRange; +ImageBufferRange(TImage &) -> ImageBufferRange; /** Creates a range to iterate over the pixels of the specified image. @@ -675,10 +681,8 @@ MakeImageBufferRange(TImage * const image) { return {}; } - else - { - return ImageBufferRange{ *image }; - } + + return ImageBufferRange{ *image }; } diff --git a/Modules/Core/Common/include/itkImageConstIterator.h b/Modules/Core/Common/include/itkImageConstIterator.h index ec5c9cca7dc..c801b312f89 100644 --- a/Modules/Core/Common/include/itkImageConstIterator.h +++ b/Modules/Core/Common/include/itkImageConstIterator.h @@ -163,8 +163,8 @@ class ITK_TEMPLATE_EXPORT ImageConstIterator m_PixelAccessorFunctor.SetBegin(m_Buffer); } - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageConstIterator(const ImageType * ptr, const RegionType & region) { m_Image = ptr; diff --git a/Modules/Core/Common/include/itkImageConstIteratorWithIndex.h b/Modules/Core/Common/include/itkImageConstIteratorWithIndex.h index 7ca135f4180..6658be14de9 100644 --- a/Modules/Core/Common/include/itkImageConstIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageConstIteratorWithIndex.h @@ -144,8 +144,8 @@ class ITK_TEMPLATE_EXPORT ImageConstIteratorWithIndex * handle to the image is properly reference counted. */ ImageConstIteratorWithIndex(const Self & it); - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageConstIteratorWithIndex(const TImage * ptr, const RegionType & region); /** Default Destructor. */ @@ -157,7 +157,7 @@ class ITK_TEMPLATE_EXPORT ImageConstIteratorWithIndex operator=(const Self & it); /** Get the dimension (size) of the index. */ - static unsigned int + static constexpr unsigned int GetImageDimension() { return ImageDimension; diff --git a/Modules/Core/Common/include/itkImageConstIteratorWithIndex.hxx b/Modules/Core/Common/include/itkImageConstIteratorWithIndex.hxx index 4a0f381d81e..96835d60db7 100644 --- a/Modules/Core/Common/include/itkImageConstIteratorWithIndex.hxx +++ b/Modules/Core/Common/include/itkImageConstIteratorWithIndex.hxx @@ -70,7 +70,7 @@ ImageConstIteratorWithIndex::ImageConstIteratorWithIndex(const TImage * std::copy_n(m_Image->GetOffsetTable(), ImageDimension + 1, m_OffsetTable); // Compute the start position - OffsetValueType offs = m_Image->ComputeOffset(m_BeginIndex); + const OffsetValueType offs = m_Image->ComputeOffset(m_BeginIndex); m_Begin = buffer + offs; m_Position = m_Begin; @@ -79,7 +79,7 @@ ImageConstIteratorWithIndex::ImageConstIteratorWithIndex(const TImage * IndexType pastEnd; for (unsigned int i = 0; i < ImageDimension; ++i) { - SizeValueType size = region.GetSize()[i]; + const SizeValueType size = region.GetSize()[i]; if (size > 0) { m_Remaining = true; diff --git a/Modules/Core/Common/include/itkImageConstIteratorWithOnlyIndex.h b/Modules/Core/Common/include/itkImageConstIteratorWithOnlyIndex.h index fd641e92ea2..415bca911cf 100644 --- a/Modules/Core/Common/include/itkImageConstIteratorWithOnlyIndex.h +++ b/Modules/Core/Common/include/itkImageConstIteratorWithOnlyIndex.h @@ -95,6 +95,8 @@ template class ITK_TEMPLATE_EXPORT ImageConstIteratorWithOnlyIndex { public: + ITK_DEFAULT_COPY_AND_MOVE(ImageConstIteratorWithOnlyIndex); + /** Standard class type aliases. */ using Self = ImageConstIteratorWithOnlyIndex; @@ -126,24 +128,15 @@ class ITK_TEMPLATE_EXPORT ImageConstIteratorWithOnlyIndex * provide a copy constructor. */ ImageConstIteratorWithOnlyIndex() = default; - /** Copy Constructor. The copy constructor is provided to make sure the - * handle to the image is properly reference counted. */ - ImageConstIteratorWithOnlyIndex(const Self & it); - - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageConstIteratorWithOnlyIndex(const TImage * ptr, const RegionType & region); /** Default Destructor. */ virtual ~ImageConstIteratorWithOnlyIndex() = default; - /** operator= is provided to make sure the handle to the image is properly - * reference counted. */ - Self & - operator=(const Self & it); - /** Get the dimension (size) of the index. */ - static unsigned int + static constexpr unsigned int GetImageDimension() { return ImageDimension; diff --git a/Modules/Core/Common/include/itkImageConstIteratorWithOnlyIndex.hxx b/Modules/Core/Common/include/itkImageConstIteratorWithOnlyIndex.hxx index 28f40bec2be..e3399bf881e 100644 --- a/Modules/Core/Common/include/itkImageConstIteratorWithOnlyIndex.hxx +++ b/Modules/Core/Common/include/itkImageConstIteratorWithOnlyIndex.hxx @@ -21,24 +21,6 @@ namespace itk { -//---------------------------------------------------------------------- -// Constructor -//---------------------------------------------------------------------- -template -ImageConstIteratorWithOnlyIndex::ImageConstIteratorWithOnlyIndex(const Self & it) -{ - m_Image = it.m_Image; // copy the smart pointer - - m_PositionIndex = it.m_PositionIndex; - m_BeginIndex = it.m_BeginIndex; - m_EndIndex = it.m_EndIndex; - m_Region = it.m_Region; - - std::copy_n(it.m_OffsetTable, ImageDimension + 1, m_OffsetTable); - - m_Remaining = it.m_Remaining; -} - //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- @@ -57,7 +39,7 @@ ImageConstIteratorWithOnlyIndex::ImageConstIteratorWithOnlyIndex(const T m_Remaining = false; for (unsigned int i = 0; i < ImageDimension; ++i) { - SizeValueType size = region.GetSize()[i]; + const SizeValueType size = region.GetSize()[i]; if (size > 0) { m_Remaining = true; @@ -68,29 +50,6 @@ ImageConstIteratorWithOnlyIndex::ImageConstIteratorWithOnlyIndex(const T GoToBegin(); } -//---------------------------------------------------------------------- -// Assignment Operator -//---------------------------------------------------------------------- -template -ImageConstIteratorWithOnlyIndex & -ImageConstIteratorWithOnlyIndex::operator=(const Self & it) -{ - if (this != *it) - { - m_Image = it.m_Image; // copy the smart pointer - - m_BeginIndex = it.m_BeginIndex; - m_EndIndex = it.m_EndIndex; - m_PositionIndex = it.m_PositionIndex; - m_Region = it.m_Region; - - std::copy_n(it.m_OffsetTable, ImageDimension + 1, m_OffsetTable); - - m_Remaining = it.m_Remaining; - } - return *this; -} - //---------------------------------------------------------------------------- // GoToBegin() is the first pixel in the region. //---------------------------------------------------------------------------- diff --git a/Modules/Core/Common/include/itkImageContainerInterface.h b/Modules/Core/Common/include/itkImageContainerInterface.h index 18a439549b6..18751da24b5 100644 --- a/Modules/Core/Common/include/itkImageContainerInterface.h +++ b/Modules/Core/Common/include/itkImageContainerInterface.h @@ -67,10 +67,12 @@ class ImageContainerInterface : public Object using Element = TElement; /** Index operator. This version can be an lvalue. */ - virtual TElement & operator[](const ElementIdentifier) = 0; + virtual TElement & + operator[](const ElementIdentifier) = 0; /** Index operator. This version can only be an rvalue */ - virtual const TElement & operator[](const ElementIdentifier) const = 0; + virtual const TElement & + operator[](const ElementIdentifier) const = 0; /** Return a pointer to the beginning of the buffer. This is used by * the image iterator class. */ diff --git a/Modules/Core/Common/include/itkImageDuplicator.h b/Modules/Core/Common/include/itkImageDuplicator.h index 63eeb657851..274b7e67736 100644 --- a/Modules/Core/Common/include/itkImageDuplicator.h +++ b/Modules/Core/Common/include/itkImageDuplicator.h @@ -86,6 +86,7 @@ class ITK_TEMPLATE_EXPORT ImageDuplicator : public Object * by returning a non-const pointer * for the generated Object. */ + /** @ITKStartGrouping */ // NOTE: The m_DuplicateImage is only // exposed via the Source generation interface // by the GetOutput() method that mimics @@ -100,7 +101,7 @@ class ITK_TEMPLATE_EXPORT ImageDuplicator : public Object { return this->m_DuplicateImage.GetPointer(); } - + /** @ITKEndGrouping */ #if !defined(ITK_LEGACY_REMOVE) // This interface was exposed in ITKv4 when the itkGetModifiableObjectMacro was used virtual ImageType * diff --git a/Modules/Core/Common/include/itkImageDuplicator.hxx b/Modules/Core/Common/include/itkImageDuplicator.hxx index d342a82ca65..a4a031cb9ef 100644 --- a/Modules/Core/Common/include/itkImageDuplicator.hxx +++ b/Modules/Core/Common/include/itkImageDuplicator.hxx @@ -51,7 +51,7 @@ ImageDuplicator::Update() m_DuplicateImage->SetRequestedRegion(m_InputImage->GetRequestedRegion()); m_DuplicateImage->SetBufferedRegion(m_InputImage->GetBufferedRegion()); m_DuplicateImage->Allocate(); - typename ImageType::RegionType region = m_InputImage->GetBufferedRegion(); + const typename ImageType::RegionType region = m_InputImage->GetBufferedRegion(); ImageAlgorithm::Copy(m_InputImage.GetPointer(), m_DuplicateImage.GetPointer(), region, region); } diff --git a/Modules/Core/Common/include/itkImageHelper.h b/Modules/Core/Common/include/itkImageHelper.h index da36dcee7cb..f940b9c4d2d 100644 --- a/Modules/Core/Common/include/itkImageHelper.h +++ b/Modules/Core/Common/include/itkImageHelper.h @@ -60,7 +60,7 @@ class ImageHelper using IndexValueType = typename ImageType::IndexValueType; /** ComputeIndex with recursive templates */ - inline static void + static inline void ComputeIndex(const IndexType & bufferedRegionIndex, OffsetValueType offset, [[maybe_unused]] const OffsetValueType offsetTable[], @@ -88,7 +88,7 @@ class ImageHelper // ComputeOffset // - inline static void + static inline void ComputeOffset(const IndexType & bufferedRegionIndex, const IndexType & index, [[maybe_unused]] const OffsetValueType offsetTable[], diff --git a/Modules/Core/Common/include/itkImageIORegion.h b/Modules/Core/Common/include/itkImageIORegion.h index 24b3f348552..041be6eebf2 100644 --- a/Modules/Core/Common/include/itkImageIORegion.h +++ b/Modules/Core/Common/include/itkImageIORegion.h @@ -121,36 +121,38 @@ class ITKCommon_EXPORT ImageIORegion : public Region SetIndex(const IndexType & index); /** Get index defining the corner of the region. */ + /** @ITKStartGrouping */ const IndexType & GetIndex() const; IndexType & GetModifiableIndex(); - + /** @ITKEndGrouping */ /** Set the size of the region. This plus the index determines the * rectangular shape, or extent, of the region. */ void SetSize(const SizeType & size); /** Get the size of the region. */ + /** @ITKStartGrouping */ const SizeType & GetSize() const; SizeType & GetModifiableSize(); - + /** @ITKEndGrouping */ /** Convenience methods to get the size of the image in a particular * coordinate direction i. Do not try to access image sizes beyond the * the ImageDimension. */ SizeValueType - GetSize(unsigned long i) const; + GetSize(unsigned int i) const; IndexValueType - GetIndex(unsigned long i) const; + GetIndex(unsigned int i) const; void - SetSize(const unsigned long i, SizeValueType size); + SetSize(const unsigned int i, SizeValueType size); void - SetIndex(const unsigned long i, IndexValueType idx); + SetIndex(const unsigned int i, IndexValueType idx); /** Compare two regions. */ bool @@ -164,7 +166,7 @@ class ITKCommon_EXPORT ImageIORegion : public Region /** Test if a region (the argument) is completely inside of this region */ bool - IsInside(const Self & region) const; + IsInside(const Self & otherRegion) const; /** Get the number of pixels contained in this region. This just * multiplies the size components. */ @@ -251,11 +253,8 @@ class ImageIORegionAdaptor ImageRegionType & outImageRegion, const ImageIndexType & largestRegionIndex) { - ImageSizeType size; - ImageIndexType index; - - size.Fill(1); // initialize with default values - index.Fill(0); + auto size = MakeFilled(1); // initialize with default values + ImageIndexType index{}; // // The ImageRegion and ImageIORegion objects may have different dimensions. diff --git a/Modules/Core/Common/include/itkImageIterator.h b/Modules/Core/Common/include/itkImageIterator.h index bcc3cb145cb..91bc506e0a9 100644 --- a/Modules/Core/Common/include/itkImageIterator.h +++ b/Modules/Core/Common/include/itkImageIterator.h @@ -65,6 +65,8 @@ template class ITK_TEMPLATE_EXPORT ImageIterator : public ImageConstIterator { public: + ITK_DEFAULT_COPY_AND_MOVE(ImageIterator); + /** Standard class type aliases. */ using Self = ImageIterator; @@ -96,19 +98,10 @@ class ITK_TEMPLATE_EXPORT ImageIterator : public ImageConstIterator /** Default Destructor */ ~ImageIterator() override = default; - /** Copy Constructor. The copy constructor is provided to make sure the - * handle to the image is properly reference counted. */ - ImageIterator(const Self & it); - - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageIterator(TImage * ptr, const RegionType & region); - /** operator= is provided to make sure the handle to the image is properly - * reference counted. */ - Self & - operator=(const Self & it); - /** Set the pixel value */ void Set(const PixelType & value) const @@ -141,9 +134,11 @@ class ITK_TEMPLATE_EXPORT ImageIterator : public ImageConstIterator protected: /** This constructor is declared protected in order to enforce const-correctness */ + /** @ITKStartGrouping */ ImageIterator(const ImageConstIterator & it); Self & operator=(const ImageConstIterator & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageIterator.hxx b/Modules/Core/Common/include/itkImageIterator.hxx index 5a64c9dada7..181512ae143 100644 --- a/Modules/Core/Common/include/itkImageIterator.hxx +++ b/Modules/Core/Common/include/itkImageIterator.hxx @@ -22,14 +22,6 @@ namespace itk { -//---------------------------------------------------------------------- -// Constructor -//---------------------------------------------------------------------- -template -ImageIterator::ImageIterator(const Self & it) - : ImageConstIterator(it) -{} - //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- @@ -57,17 +49,6 @@ ImageIterator::operator=(const ImageConstIterator & it) return *this; } -//---------------------------------------------------------------------- -// Assignment Operator -//---------------------------------------------------------------------- -template -ImageIterator & -ImageIterator::operator=(const Self & it) -{ - this->ImageConstIterator::operator=(it); - return *this; -} - } // end namespace itk #endif diff --git a/Modules/Core/Common/include/itkImageIteratorWithIndex.h b/Modules/Core/Common/include/itkImageIteratorWithIndex.h index 94ace5e96ee..38e7773857a 100644 --- a/Modules/Core/Common/include/itkImageIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageIteratorWithIndex.h @@ -68,6 +68,8 @@ template class ITK_TEMPLATE_EXPORT ImageIteratorWithIndex : public ImageConstIteratorWithIndex { public: + ITK_DEFAULT_COPY_AND_MOVE(ImageIteratorWithIndex); + /** Standard class type aliases. */ using Self = ImageIteratorWithIndex; @@ -99,19 +101,10 @@ class ITK_TEMPLATE_EXPORT ImageIteratorWithIndex : public ImageConstIteratorWith /** Default Destructor */ ~ImageIteratorWithIndex() override = default; - /** Copy Constructor. The copy constructor is provided to make sure the - * handle to the image is properly reference counted. */ - ImageIteratorWithIndex(const Self & it); - - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageIteratorWithIndex(TImage * ptr, const RegionType & region); - /** operator= is provided to make sure the handle to the image is properly - * reference counted. */ - Self & - operator=(const Self & it); - /** Set the pixel value */ void Set(const PixelType & value) const @@ -131,9 +124,11 @@ class ITK_TEMPLATE_EXPORT ImageIteratorWithIndex : public ImageConstIteratorWith protected: /** This constructor is declared protected in order to enforce const-correctness */ + /** @ITKStartGrouping */ ImageIteratorWithIndex(const ImageConstIteratorWithIndex & it); Self & operator=(const ImageConstIteratorWithIndex & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageIteratorWithIndex.hxx b/Modules/Core/Common/include/itkImageIteratorWithIndex.hxx index 5ca8aee3faa..7dfbbcb9cb3 100644 --- a/Modules/Core/Common/include/itkImageIteratorWithIndex.hxx +++ b/Modules/Core/Common/include/itkImageIteratorWithIndex.hxx @@ -22,14 +22,6 @@ namespace itk { -//---------------------------------------------------------------------- -// Constructor -//---------------------------------------------------------------------- -template -ImageIteratorWithIndex::ImageIteratorWithIndex(const Self & it) - : ImageConstIteratorWithIndex(it) -{} - //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- @@ -57,17 +49,6 @@ ImageIteratorWithIndex::operator=(const ImageConstIteratorWithIndex -ImageIteratorWithIndex & -ImageIteratorWithIndex::operator=(const Self & it) -{ - this->ImageConstIteratorWithIndex::operator=(it); - return *this; -} - } // end namespace itk #endif diff --git a/Modules/Core/Common/include/itkImageKernelOperator.h b/Modules/Core/Common/include/itkImageKernelOperator.h index b3ca7416a47..216acb006c2 100644 --- a/Modules/Core/Common/include/itkImageKernelOperator.h +++ b/Modules/Core/Common/include/itkImageKernelOperator.h @@ -32,7 +32,7 @@ namespace itk * * "Image Kernel Convolution" * by Tustison N., Gee J. - * https://www.insight-journal.org/browse/publication/208 + * https://doi.org/10.54294/e292kx * * * \note ImageKernelOperator does not have any user-declared "special member function", diff --git a/Modules/Core/Common/include/itkImageKernelOperator.hxx b/Modules/Core/Common/include/itkImageKernelOperator.hxx index 6bfc14901f1..69ec26fe8ef 100644 --- a/Modules/Core/Common/include/itkImageKernelOperator.hxx +++ b/Modules/Core/Common/include/itkImageKernelOperator.hxx @@ -28,7 +28,7 @@ * * "Image Kernel Convolution" * by Tustison N., Gee J. - * https://www.insight-journal.org/browse/publication/208 + * https://doi.org/10.54294/e292kx * */ diff --git a/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.h b/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.h index 3fa846507f1..eff14ad6b7e 100644 --- a/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.h @@ -135,8 +135,8 @@ class ITK_TEMPLATE_EXPORT ImageLinearConstIteratorWithIndex : public ImageConstI {} - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageLinearConstIteratorWithIndex(const ImageType * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageIterator to an @@ -262,11 +262,9 @@ ImageLinearConstIteratorWithIndex::NextLine() this->m_Remaining = true; break; } - else - { - this->m_Position -= this->m_OffsetTable[n] * (this->m_Region.GetSize()[n] - 1); - this->m_PositionIndex[n] = this->m_BeginIndex[n]; - } + + this->m_Position -= this->m_OffsetTable[n] * (this->m_Region.GetSize()[n] - 1); + this->m_PositionIndex[n] = this->m_BeginIndex[n]; } } @@ -298,11 +296,9 @@ ImageLinearConstIteratorWithIndex::PreviousLine() this->m_Remaining = true; break; } - else - { - this->m_Position += this->m_OffsetTable[n] * (this->m_Region.GetSize()[n] - 1); - this->m_PositionIndex[n] = this->m_EndIndex[n] - 1; - } + + this->m_Position += this->m_OffsetTable[n] * (this->m_Region.GetSize()[n] - 1); + this->m_PositionIndex[n] = this->m_EndIndex[n] - 1; } } } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.hxx b/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.hxx index 663c7eced1c..0a3a95f5a8c 100644 --- a/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.hxx +++ b/Modules/Core/Common/include/itkImageLinearConstIteratorWithIndex.hxx @@ -39,7 +39,7 @@ template void ImageLinearConstIteratorWithIndex::GoToReverseBeginOfLine() { - OffsetValueType distanceToEnd = this->m_EndIndex[m_Direction] - this->m_PositionIndex[m_Direction] - 1; + const OffsetValueType distanceToEnd = this->m_EndIndex[m_Direction] - this->m_PositionIndex[m_Direction] - 1; this->m_Position += m_Jump * distanceToEnd; this->m_PositionIndex[m_Direction] = this->m_EndIndex[m_Direction] - 1; @@ -52,7 +52,7 @@ template void ImageLinearConstIteratorWithIndex::GoToBeginOfLine() { - OffsetValueType distanceToBegin = this->m_PositionIndex[m_Direction] - this->m_BeginIndex[m_Direction]; + const OffsetValueType distanceToBegin = this->m_PositionIndex[m_Direction] - this->m_BeginIndex[m_Direction]; this->m_Position -= m_Jump * distanceToBegin; @@ -66,7 +66,7 @@ template void ImageLinearConstIteratorWithIndex::GoToEndOfLine() { - OffsetValueType distanceToEnd = this->m_EndIndex[m_Direction] - this->m_PositionIndex[m_Direction]; + const OffsetValueType distanceToEnd = this->m_EndIndex[m_Direction] - this->m_PositionIndex[m_Direction]; this->m_Position += m_Jump * distanceToEnd; diff --git a/Modules/Core/Common/include/itkImageLinearIteratorWithIndex.h b/Modules/Core/Common/include/itkImageLinearIteratorWithIndex.h index 3eb85da1121..3b80496fc71 100644 --- a/Modules/Core/Common/include/itkImageLinearIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageLinearIteratorWithIndex.h @@ -86,8 +86,8 @@ class ITK_TEMPLATE_EXPORT ImageLinearIteratorWithIndex : public ImageLinearConst /** Default constructor. Needed since we provide a cast constructor. */ ImageLinearIteratorWithIndex() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageLinearIteratorWithIndex(ImageType * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageIterator to an @@ -117,9 +117,11 @@ class ITK_TEMPLATE_EXPORT ImageLinearIteratorWithIndex : public ImageLinearConst protected: /** the construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageLinearIteratorWithIndex(const ImageLinearConstIteratorWithIndex & it); Self & operator=(const ImageLinearConstIteratorWithIndex & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageRandomConstIteratorWithIndex.h b/Modules/Core/Common/include/itkImageRandomConstIteratorWithIndex.h index 9d573b1d283..0e25a6f47b9 100644 --- a/Modules/Core/Common/include/itkImageRandomConstIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageRandomConstIteratorWithIndex.h @@ -137,6 +137,7 @@ class ITK_TEMPLATE_EXPORT ImageRandomConstIteratorWithIndex : public ImageConstI /** Default constructor. Needed since we provide a cast constructor. */ ImageRandomConstIteratorWithIndex() = default; + ~ImageRandomConstIteratorWithIndex() override = default; /** Constructor establishes an iterator to walk a particular image and a diff --git a/Modules/Core/Common/include/itkImageRandomConstIteratorWithOnlyIndex.h b/Modules/Core/Common/include/itkImageRandomConstIteratorWithOnlyIndex.h index 923abbf2b3b..693088d6a8d 100644 --- a/Modules/Core/Common/include/itkImageRandomConstIteratorWithOnlyIndex.h +++ b/Modules/Core/Common/include/itkImageRandomConstIteratorWithOnlyIndex.h @@ -139,6 +139,7 @@ class ITK_TEMPLATE_EXPORT ImageRandomConstIteratorWithOnlyIndex : public ImageCo /** Default constructor. Needed since we provide a cast constructor. */ ImageRandomConstIteratorWithOnlyIndex() = default; + ~ImageRandomConstIteratorWithOnlyIndex() override = default; /** Constructor establishes an iterator to walk a particular image and a diff --git a/Modules/Core/Common/include/itkImageRandomIteratorWithIndex.h b/Modules/Core/Common/include/itkImageRandomIteratorWithIndex.h index 6aaf414628e..a9219227013 100644 --- a/Modules/Core/Common/include/itkImageRandomIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageRandomIteratorWithIndex.h @@ -117,9 +117,11 @@ class ITK_TEMPLATE_EXPORT ImageRandomIteratorWithIndex : public ImageRandomConst protected: /** The construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageRandomIteratorWithIndex(const ImageRandomConstIteratorWithIndex & it); Self & operator=(const ImageRandomConstIteratorWithIndex & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageRandomNonRepeatingConstIteratorWithIndex.h b/Modules/Core/Common/include/itkImageRandomNonRepeatingConstIteratorWithIndex.h index b0defff6c42..41fc54cd18f 100644 --- a/Modules/Core/Common/include/itkImageRandomNonRepeatingConstIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageRandomNonRepeatingConstIteratorWithIndex.h @@ -58,10 +58,8 @@ class NodeOfPermutation { return m_Value < b.m_Value; } - else - { - return m_Priority < b.m_Priority; - } + + return m_Priority < b.m_Priority; } }; @@ -104,10 +102,8 @@ class RandomPermutation ostrm << "Error: RandomPermuation does not have " << i << " elements" << std::endl; throw std::runtime_error(ostrm.str()); } - else - { - m_Permutation[i].m_Priority = priority; - } + + m_Permutation[i].m_Priority = priority; } void @@ -121,7 +117,11 @@ class RandomPermutation std::sort(m_Permutation, m_Permutation + m_Size); } - SizeValueType operator[](SizeValueType i) const { return m_Permutation[i].m_Index; } + SizeValueType + operator[](SizeValueType i) const + { + return m_Permutation[i].m_Index; + } ~RandomPermutation() { delete[] m_Permutation; } @@ -129,7 +129,7 @@ class RandomPermutation void ReinitializeSeed() const { - m_Generator->Initialize(); + m_Generator->SetSeed(); } void @@ -235,6 +235,7 @@ class ITK_TEMPLATE_EXPORT ImageRandomNonRepeatingConstIteratorWithIndex : public /** Default constructor. Needed since we provide a cast constructor. */ ImageRandomNonRepeatingConstIteratorWithIndex() = default; + ~ImageRandomNonRepeatingConstIteratorWithIndex() override { delete m_Permutation; } /** Constructor establishes an iterator to walk a particular image and a @@ -323,6 +324,7 @@ class ITK_TEMPLATE_EXPORT ImageRandomNonRepeatingConstIteratorWithIndex : public } /** Set/Get number of random samples to extract from the image region. */ + /** @ITKStartGrouping */ void SetNumberOfSamples(SizeValueType number) { @@ -332,12 +334,12 @@ class ITK_TEMPLATE_EXPORT ImageRandomNonRepeatingConstIteratorWithIndex : public m_NumberOfSamplesRequested = m_NumberOfPixelsInRegion; } } - SizeValueType GetNumberOfSamples() const { return m_NumberOfSamplesRequested; } + /** @ITKEndGrouping */ /** Reinitialize the seed of the random number generator. */ void diff --git a/Modules/Core/Common/include/itkImageRandomNonRepeatingIteratorWithIndex.h b/Modules/Core/Common/include/itkImageRandomNonRepeatingIteratorWithIndex.h index e867a17a696..5a1ee63374a 100644 --- a/Modules/Core/Common/include/itkImageRandomNonRepeatingIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageRandomNonRepeatingIteratorWithIndex.h @@ -129,9 +129,11 @@ class ITK_TEMPLATE_EXPORT ImageRandomNonRepeatingIteratorWithIndex protected: /** The construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageRandomNonRepeatingIteratorWithIndex(const ImageRandomNonRepeatingConstIteratorWithIndex & it); Self & operator=(const ImageRandomNonRepeatingConstIteratorWithIndex & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageRegion.h b/Modules/Core/Common/include/itkImageRegion.h index 7fbb997a430..0f8d8765cf9 100644 --- a/Modules/Core/Common/include/itkImageRegion.h +++ b/Modules/Core/Common/include/itkImageRegion.h @@ -36,11 +36,11 @@ #include // For conditional and integral_constant. #include // For tuple_element and tuple_size. -// Macro added to each `ImageRegion` member function that overrides a virtual member function of `Region`. In the -// future, `ImageRegion` will no longer inherit from `Region`, so then those `ImageRegion` member functions will no -// longer override. -#ifdef ITK_FUTURE_LEGACY_REMOVE -# define itkRegionOverrideMacro // nothing (in the future) +// Macro added to each `ImageRegion` member function that overrides a virtual member function of `Region`, when legacy +// support is enabled. Without legacy support, `ImageRegion` will no longer inherit from `Region`, so then those +// `ImageRegion` member functions will no longer override. +#ifdef ITK_LEGACY_REMOVE +# define itkRegionOverrideMacro // nothing #else # define itkRegionOverrideMacro override #endif @@ -78,8 +78,8 @@ class ITK_TEMPLATE_EXPORT ImageBase; */ template class ITK_TEMPLATE_EXPORT ImageRegion final -#ifndef ITK_FUTURE_LEGACY_REMOVE - // This inheritance is to be removed in the future. +#ifndef ITK_LEGACY_REMOVE + // This inheritance is only there when legacy support is enabled. : public Region #endif { @@ -87,7 +87,7 @@ class ITK_TEMPLATE_EXPORT ImageRegion final /** Standard class type aliases. */ using Self = ImageRegion; -#ifndef ITK_FUTURE_LEGACY_REMOVE +#ifndef ITK_LEGACY_REMOVE using Superclass = Region; #endif @@ -105,8 +105,8 @@ class ITK_TEMPLATE_EXPORT ImageRegion final in which case the SliceDimension is also one dimensional. */ static constexpr unsigned int SliceDimension = ImageDimension - (ImageDimension > 1); - /** Dimension of the image available at run time. */ - static unsigned int + /** Dimension of the image available at compile-time and at run time. */ + static constexpr unsigned int GetImageDimension() { return ImageDimension; @@ -184,6 +184,7 @@ class ITK_TEMPLATE_EXPORT ImageRegion final } /** Get index defining the corner of the region. */ + /** @ITKStartGrouping */ const IndexType & GetIndex() const { @@ -194,7 +195,7 @@ class ITK_TEMPLATE_EXPORT ImageRegion final { return m_Index; } - + /** @ITKEndGrouping */ /** Set the size of the region. This plus the index determines the * rectangular shape, or extent, of the region. */ void @@ -204,6 +205,7 @@ class ITK_TEMPLATE_EXPORT ImageRegion final } /** Get the size of the region. */ + /** @ITKStartGrouping */ const SizeType & GetSize() const { @@ -214,9 +216,10 @@ class ITK_TEMPLATE_EXPORT ImageRegion final { return m_Size; } - + /** @ITKEndGrouping */ /** Convenience methods to get and set the size of the particular dimension i. */ + /** @ITKStartGrouping */ void SetSize(unsigned int i, SizeValueType sze) { @@ -227,9 +230,10 @@ class ITK_TEMPLATE_EXPORT ImageRegion final { return m_Size[i]; } - + /** @ITKEndGrouping */ /** Convenience methods to get and set the index of the particular dimension i. */ + /** @ITKStartGrouping */ void SetIndex(unsigned int i, IndexValueType sze) { @@ -240,7 +244,7 @@ class ITK_TEMPLATE_EXPORT ImageRegion final { return m_Index[i]; } - + /** @ITKEndGrouping */ /** Get index defining the upper corner of the region. */ IndexType GetUpperIndex() const; @@ -280,11 +284,11 @@ class ITK_TEMPLATE_EXPORT ImageRegion final * We take into account the fact that each voxel has its * center at the integer coordinate and extends half way * to the next integer coordinate, inclusive on all sides. */ - template + template bool - IsInside(const ContinuousIndex & index) const + IsInside(const ContinuousIndex & index) const { - constexpr TCoordRepType half = 0.5; + constexpr TCoordinate half = 0.5; for (unsigned int i = 0; i < ImageDimension; ++i) { // Use negation of tests so that index[i]==NaN leads to returning false. @@ -413,7 +417,7 @@ class ITK_TEMPLATE_EXPORT ImageRegion final // Deduction guide to avoid compiler warnings (-wctad-maybe-unsupported) when using class template argument deduction. template -ImageRegion(const Index &, const Size &)->ImageRegion; +ImageRegion(const Index &, const Size &) -> ImageRegion; template @@ -424,11 +428,11 @@ operator<<(std::ostream & os, const ImageRegion & region); namespace std { -#if defined(__clang__) -# pragma GCC diagnostic push -// Old Clang compiler versions (before Clang 7.0.0) produced some unimportant warnings, like: "warning: 'tuple_size' -// defined as a struct template here but previously declared as a class template" -# pragma GCC diagnostic ignored "-Wmismatched-tags" +#if defined(__clang__) && defined(__apple_build_version__) && (__clang_major__ <= 10) +# pragma clang diagnostic push +// Old AppleClang 10.0.0 (Xcode 10.1, newest on macOS 10.13) produced some unimportant warnings, like: +// "warning: 'tuple_size' defined as a struct template here but previously declared as a class template" +# pragma clang diagnostic ignored "-Wmismatched-tags" #endif // NOLINTBEGIN(cert-dcl58-cpp) @@ -456,8 +460,8 @@ struct tuple_element> // NOLINTEND(cert-dcl58-cpp) -#if defined(__clang__) -# pragma GCC diagnostic pop +#if defined(__clang__) && defined(__apple_build_version__) && (__clang_major__ <= 10) +# pragma clang diagnostic pop #endif } // namespace std diff --git a/Modules/Core/Common/include/itkImageRegion.hxx b/Modules/Core/Common/include/itkImageRegion.hxx index 3a95eb3cbbd..dcf0578a62f 100644 --- a/Modules/Core/Common/include/itkImageRegion.hxx +++ b/Modules/Core/Common/include/itkImageRegion.hxx @@ -231,12 +231,9 @@ ImageRegion::Slice(const unsigned int dim) const -> SliceRegion "The dimension to remove: " << dim << " is greater than the dimension of the image: " << VImageDimension); } - Index sliceIndex; - Size sliceSize; - - sliceIndex.Fill(0); - sliceSize.Fill(0); - unsigned int ii = 0; + Index sliceIndex{}; + Size sliceSize{}; + unsigned int ii = 0; for (unsigned int i = 0; i < VImageDimension; ++i) { if (i != dim) diff --git a/Modules/Core/Common/include/itkImageRegionConstIterator.h b/Modules/Core/Common/include/itkImageRegionConstIterator.h index b997fc8753b..a2cc2fab503 100644 --- a/Modules/Core/Common/include/itkImageRegionConstIterator.h +++ b/Modules/Core/Common/include/itkImageRegionConstIterator.h @@ -123,6 +123,7 @@ class ITK_TEMPLATE_EXPORT ImageRegionConstIterator : public ImageConstIterator(ptr, region) { diff --git a/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.h b/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.h index f09f2aad88a..e79e2742f00 100644 --- a/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.h @@ -138,6 +138,7 @@ class ITK_TEMPLATE_EXPORT ImageRegionConstIteratorWithIndex : public ImageConstI * Index type alias support While these were already typedef'ed in the superclass * they need to be redone here for this subclass to compile properly with gcc. */ + /** Types inherited from the Superclass */ using typename Superclass::IndexType; using typename Superclass::SizeType; @@ -155,8 +156,8 @@ class ITK_TEMPLATE_EXPORT ImageRegionConstIteratorWithIndex : public ImageConstI : ImageConstIteratorWithIndex() {} - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageRegionConstIteratorWithIndex(const TImage * ptr, const RegionType & region) : ImageConstIteratorWithIndex(ptr, region) {} diff --git a/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.hxx b/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.hxx index 90c2d1ada7f..119d8c8c6ff 100644 --- a/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.hxx +++ b/Modules/Core/Common/include/itkImageRegionConstIteratorWithIndex.hxx @@ -38,11 +38,9 @@ ImageRegionConstIteratorWithIndex::operator++() this->m_Remaining = true; break; } - else - { - this->m_Position -= this->m_OffsetTable[in] * (static_cast(this->m_Region.GetSize()[in]) - 1); - this->m_PositionIndex[in] = this->m_BeginIndex[in]; - } + + this->m_Position -= this->m_OffsetTable[in] * (static_cast(this->m_Region.GetSize()[in]) - 1); + this->m_PositionIndex[in] = this->m_BeginIndex[in]; } if (!this->m_Remaining) // It will not advance here otherwise @@ -70,11 +68,9 @@ ImageRegionConstIteratorWithIndex::operator--() this->m_Remaining = true; break; } - else - { - this->m_Position += this->m_OffsetTable[in] * (static_cast(this->m_Region.GetSize()[in]) - 1); - this->m_PositionIndex[in] = this->m_EndIndex[in] - 1; - } + + this->m_Position += this->m_OffsetTable[in] * (static_cast(this->m_Region.GetSize()[in]) - 1); + this->m_PositionIndex[in] = this->m_EndIndex[in] - 1; } if (!this->m_Remaining) // It will not advance here otherwise diff --git a/Modules/Core/Common/include/itkImageRegionConstIteratorWithOnlyIndex.h b/Modules/Core/Common/include/itkImageRegionConstIteratorWithOnlyIndex.h index d3fb5a28729..37ae1ce5374 100644 --- a/Modules/Core/Common/include/itkImageRegionConstIteratorWithOnlyIndex.h +++ b/Modules/Core/Common/include/itkImageRegionConstIteratorWithOnlyIndex.h @@ -139,6 +139,7 @@ class ITK_TEMPLATE_EXPORT ImageRegionConstIteratorWithOnlyIndex : public ImageCo * Index type alias support While these were already typedef'ed in the superclass * they need to be redone here for this subclass to compile properly with gcc. */ + /** Types inherited from the Superclass */ using typename Superclass::IndexType; using typename Superclass::SizeType; @@ -151,8 +152,8 @@ class ITK_TEMPLATE_EXPORT ImageRegionConstIteratorWithOnlyIndex : public ImageCo : ImageConstIteratorWithOnlyIndex() {} - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageRegionConstIteratorWithOnlyIndex(const TImage * ptr, const RegionType & region) : ImageConstIteratorWithOnlyIndex(ptr, region) {} diff --git a/Modules/Core/Common/include/itkImageRegionConstIteratorWithOnlyIndex.hxx b/Modules/Core/Common/include/itkImageRegionConstIteratorWithOnlyIndex.hxx index 9589e68616e..2963e88d3df 100644 --- a/Modules/Core/Common/include/itkImageRegionConstIteratorWithOnlyIndex.hxx +++ b/Modules/Core/Common/include/itkImageRegionConstIteratorWithOnlyIndex.hxx @@ -37,10 +37,8 @@ ImageRegionConstIteratorWithOnlyIndex::operator++() this->m_Remaining = true; break; } - else - { - this->m_PositionIndex[in] = this->m_BeginIndex[in]; - } + + this->m_PositionIndex[in] = this->m_BeginIndex[in]; } return *this; @@ -62,10 +60,8 @@ ImageRegionConstIteratorWithOnlyIndex::operator--() this->m_Remaining = true; break; } - else - { - this->m_PositionIndex[in] = this->m_EndIndex[in] - 1; - } + + this->m_PositionIndex[in] = this->m_EndIndex[in] - 1; } return *this; diff --git a/Modules/Core/Common/include/itkImageRegionExclusionConstIteratorWithIndex.h b/Modules/Core/Common/include/itkImageRegionExclusionConstIteratorWithIndex.h index 05f96873a3d..75ae9041d78 100644 --- a/Modules/Core/Common/include/itkImageRegionExclusionConstIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageRegionExclusionConstIteratorWithIndex.h @@ -150,8 +150,8 @@ class ITK_TEMPLATE_EXPORT ImageRegionExclusionConstIteratorWithIndex : public Im /** Default constructor. Needed since we provide a cast constructor. */ ImageRegionExclusionConstIteratorWithIndex() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageRegionExclusionConstIteratorWithIndex(const ImageType * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageRegionConstIteratorWithIndex diff --git a/Modules/Core/Common/include/itkImageRegionExclusionConstIteratorWithIndex.hxx b/Modules/Core/Common/include/itkImageRegionExclusionConstIteratorWithIndex.hxx index 14426890673..eddc78c49b8 100644 --- a/Modules/Core/Common/include/itkImageRegionExclusionConstIteratorWithIndex.hxx +++ b/Modules/Core/Common/include/itkImageRegionExclusionConstIteratorWithIndex.hxx @@ -63,9 +63,7 @@ template void ImageRegionExclusionConstIteratorWithIndex::SetExclusionRegionToInsetRegion() { - RegionType excludeRegion; - - excludeRegion = this->m_Region; + RegionType excludeRegion = this->m_Region; for (unsigned int i = 0; i < TImage::ImageDimension; ++i) { if (excludeRegion.GetSize()[i] >= 2) diff --git a/Modules/Core/Common/include/itkImageRegionExclusionIteratorWithIndex.h b/Modules/Core/Common/include/itkImageRegionExclusionIteratorWithIndex.h index 37bc0db072c..c71bf70742f 100644 --- a/Modules/Core/Common/include/itkImageRegionExclusionIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageRegionExclusionIteratorWithIndex.h @@ -87,8 +87,8 @@ class ITK_TEMPLATE_EXPORT ImageRegionExclusionIteratorWithIndex /** Default constructor. Needed since we provide a cast constructor. */ ImageRegionExclusionIteratorWithIndex() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageRegionExclusionIteratorWithIndex(ImageType * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageIterator to an @@ -118,9 +118,11 @@ class ITK_TEMPLATE_EXPORT ImageRegionExclusionIteratorWithIndex protected: /** The construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageRegionExclusionIteratorWithIndex(const ImageRegionExclusionConstIteratorWithIndex & it); Self & operator=(const ImageRegionExclusionConstIteratorWithIndex & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageRegionIterator.h b/Modules/Core/Common/include/itkImageRegionIterator.h index 72a420ab090..93babf4631e 100644 --- a/Modules/Core/Common/include/itkImageRegionIterator.h +++ b/Modules/Core/Common/include/itkImageRegionIterator.h @@ -99,8 +99,8 @@ class ITK_TEMPLATE_EXPORT ImageRegionIterator : public ImageRegionConstIterator< /** Default constructor. Needed since we provide a cast constructor. */ ImageRegionIterator() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageRegionIterator(ImageType * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageIterator to an @@ -130,9 +130,11 @@ class ITK_TEMPLATE_EXPORT ImageRegionIterator : public ImageRegionConstIterator< protected: /** the construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageRegionIterator(const ImageRegionConstIterator & it); Self & operator=(const ImageRegionConstIterator & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageRegionIteratorWithIndex.h b/Modules/Core/Common/include/itkImageRegionIteratorWithIndex.h index dddf36a837e..a0c7b813c12 100644 --- a/Modules/Core/Common/include/itkImageRegionIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageRegionIteratorWithIndex.h @@ -92,8 +92,8 @@ class ITK_TEMPLATE_EXPORT ImageRegionIteratorWithIndex : public ImageRegionConst /** Default constructor. Needed since we provide a cast constructor. */ ImageRegionIteratorWithIndex() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageRegionIteratorWithIndex(TImage * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageIterator to an @@ -123,9 +123,11 @@ class ITK_TEMPLATE_EXPORT ImageRegionIteratorWithIndex : public ImageRegionConst protected: /** The construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageRegionIteratorWithIndex(const ImageRegionConstIteratorWithIndex & it); Self & operator=(const ImageRegionConstIteratorWithIndex & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageRegionRange.h b/Modules/Core/Common/include/itkImageRegionRange.h index e203267d3c7..6a0a7a85fcf 100644 --- a/Modules/Core/Common/include/itkImageRegionRange.h +++ b/Modules/Core/Common/include/itkImageRegionRange.h @@ -225,7 +225,11 @@ class ImageRegionRange final /** Returns a reference to the current pixel. */ - reference operator*() const noexcept { return *m_BufferIterator; } + reference + operator*() const noexcept + { + return *m_BufferIterator; + } /** Prefix increment ('++it'). */ QualifiedIterator & @@ -458,7 +462,7 @@ class ImageRegionRange final // Deduction guide to avoid compiler warnings (-wctad-maybe-unsupported) when using class template argument deduction. template -ImageRegionRange(TImage &)->ImageRegionRange; +ImageRegionRange(TImage &) -> ImageRegionRange; } // namespace itk diff --git a/Modules/Core/Common/include/itkImageRegionReverseConstIterator.h b/Modules/Core/Common/include/itkImageRegionReverseConstIterator.h index d060cabed3b..6e9390ba41e 100644 --- a/Modules/Core/Common/include/itkImageRegionReverseConstIterator.h +++ b/Modules/Core/Common/include/itkImageRegionReverseConstIterator.h @@ -153,8 +153,8 @@ class ITK_TEMPLATE_EXPORT ImageRegionReverseConstIterator : public ImageReverseC m_SpanEndOffset = 0; } - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageRegionReverseConstIterator(const ImageType * ptr, const RegionType & region) : Superclass(ptr, region) { diff --git a/Modules/Core/Common/include/itkImageRegionReverseIterator.h b/Modules/Core/Common/include/itkImageRegionReverseIterator.h index c3da858580f..9896a3c33b4 100644 --- a/Modules/Core/Common/include/itkImageRegionReverseIterator.h +++ b/Modules/Core/Common/include/itkImageRegionReverseIterator.h @@ -88,8 +88,8 @@ class ITK_TEMPLATE_EXPORT ImageRegionReverseIterator : public ImageRegionReverse /** Default constructor. Needed since we provide a cast constructor. */ ImageRegionReverseIterator() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageRegionReverseIterator(ImageType * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageConstIterator to an @@ -119,9 +119,11 @@ class ITK_TEMPLATE_EXPORT ImageRegionReverseIterator : public ImageRegionReverse protected: /** the construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageRegionReverseIterator(const ImageRegionReverseConstIterator & it); Self & operator=(const ImageRegionReverseConstIterator & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageRegionSplitterBase.h b/Modules/Core/Common/include/itkImageRegionSplitterBase.h index f28ea7bdfe6..5852eb2c65f 100644 --- a/Modules/Core/Common/include/itkImageRegionSplitterBase.h +++ b/Modules/Core/Common/include/itkImageRegionSplitterBase.h @@ -75,6 +75,7 @@ class ITKCommon_EXPORT ImageRegionSplitterBase : public Object * a certain dimensions, then some splits will not be possible. This * method returns a number less than or equal to the requested number * of pieces. */ + /** @ITKStartGrouping */ template unsigned int GetNumberOfSplits(const ImageRegion & region, unsigned int requestedNumber) const @@ -88,7 +89,7 @@ class ITKCommon_EXPORT ImageRegionSplitterBase : public Object return this->GetNumberOfSplitsInternal( region.GetImageDimension(), ®ion.GetIndex()[0], ®ion.GetSize()[0], requestedNumber); } - + /** @ITKEndGrouping */ /** \brief Get a region definition that represents the ith piece a * specified region. diff --git a/Modules/Core/Common/include/itkImageRegionSplitterDirection.h b/Modules/Core/Common/include/itkImageRegionSplitterDirection.h index 9e94f78f073..3c276b7dafa 100644 --- a/Modules/Core/Common/include/itkImageRegionSplitterDirection.h +++ b/Modules/Core/Common/include/itkImageRegionSplitterDirection.h @@ -52,9 +52,10 @@ class ITKCommon_EXPORT ImageRegionSplitterDirection : public ImageRegionSplitter * * Defaults to 0. */ + /** @ITKStartGrouping */ itkGetConstMacro(Direction, unsigned int); itkSetMacro(Direction, unsigned int); - + /** @ITKEndGrouping */ protected: ImageRegionSplitterDirection(); diff --git a/Modules/Core/Common/include/itkImageReverseConstIterator.h b/Modules/Core/Common/include/itkImageReverseConstIterator.h index 9ca2f43187b..386e0a66292 100644 --- a/Modules/Core/Common/include/itkImageReverseConstIterator.h +++ b/Modules/Core/Common/include/itkImageReverseConstIterator.h @@ -166,8 +166,8 @@ class ITK_TEMPLATE_EXPORT ImageReverseConstIterator m_PixelAccessorFunctor.SetBegin(m_Buffer); } - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageReverseConstIterator(const ImageType * ptr, const RegionType & region) { SizeValueType offset; @@ -208,7 +208,7 @@ class ITK_TEMPLATE_EXPORT ImageReverseConstIterator m_Region = it.GetRegion(); m_Buffer = m_Image->GetBufferPointer(); - IndexType ind = it.GetIndex(); + const IndexType ind = it.GetIndex(); m_Offset = m_Image->ComputeOffset(ind); diff --git a/Modules/Core/Common/include/itkImageReverseIterator.h b/Modules/Core/Common/include/itkImageReverseIterator.h index 8b732558d6b..7f824b1b26e 100644 --- a/Modules/Core/Common/include/itkImageReverseIterator.h +++ b/Modules/Core/Common/include/itkImageReverseIterator.h @@ -84,8 +84,8 @@ class ITK_TEMPLATE_EXPORT ImageReverseIterator : public ImageRegionReverseConstI /** Default constructor. Needed since we provide a cast constructor. */ ImageReverseIterator() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageReverseIterator(ImageType * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageIterator to an @@ -115,9 +115,11 @@ class ITK_TEMPLATE_EXPORT ImageReverseIterator : public ImageRegionReverseConstI protected: /** the construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageReverseIterator(const ImageRegionReverseConstIterator & it); Self & operator=(const ImageRegionReverseConstIterator & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageScanlineConstIterator.h b/Modules/Core/Common/include/itkImageScanlineConstIterator.h index 393e5ecac17..5dde1cb09ff 100644 --- a/Modules/Core/Common/include/itkImageScanlineConstIterator.h +++ b/Modules/Core/Common/include/itkImageScanlineConstIterator.h @@ -78,6 +78,7 @@ class ITK_TEMPLATE_EXPORT ImageScanlineConstIterator : public ImageConstIterator * Index type alias support While these were already typedef'ed in the superclass, * they need to be redone here for this subclass to compile properly with gcc. */ + /** Types inherited from the Superclass */ using typename Superclass::IndexType; using typename Superclass::SizeType; @@ -101,8 +102,8 @@ class ITK_TEMPLATE_EXPORT ImageScanlineConstIterator : public ImageConstIterator m_SpanEndOffset = 0; } - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageScanlineConstIterator(const TImage * ptr, const RegionType & region) : ImageConstIterator(ptr, region) { @@ -256,7 +257,6 @@ class ITK_TEMPLATE_EXPORT ImageScanlineConstIterator : public ImageConstIterator return *this; } - protected: OffsetValueType m_SpanBeginOffset{}; // one pixel the beginning of the scanline OffsetValueType m_SpanEndOffset{}; // one pixel past the end of the scanline @@ -265,7 +265,7 @@ class ITK_TEMPLATE_EXPORT ImageScanlineConstIterator : public ImageConstIterator // Deduction guide for class template argument deduction (CTAD). template ImageScanlineConstIterator(SmartPointer, const typename TImage::RegionType &) - ->ImageScanlineConstIterator>; + -> ImageScanlineConstIterator>; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageScanlineIterator.h b/Modules/Core/Common/include/itkImageScanlineIterator.h index c2ea15dfc9a..d98a593165f 100644 --- a/Modules/Core/Common/include/itkImageScanlineIterator.h +++ b/Modules/Core/Common/include/itkImageScanlineIterator.h @@ -61,8 +61,8 @@ class ITK_TEMPLATE_EXPORT ImageScanlineIterator : public ImageScanlineConstItera /** Default constructor. Needed since we provide a cast constructor. */ ImageScanlineIterator() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageScanlineIterator(TImage * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageIterator to an @@ -92,14 +92,16 @@ class ITK_TEMPLATE_EXPORT ImageScanlineIterator : public ImageScanlineConstItera protected: /** the construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageScanlineIterator(const ImageScanlineConstIterator & it); Self & operator=(const ImageScanlineConstIterator & it); + /** @ITKEndGrouping */ }; // Deduction guide for class template argument deduction (CTAD). template -ImageScanlineIterator(SmartPointer, const typename TImage::RegionType &)->ImageScanlineIterator; +ImageScanlineIterator(SmartPointer, const typename TImage::RegionType &) -> ImageScanlineIterator; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageSink.h b/Modules/Core/Common/include/itkImageSink.h index d8c146c8b3d..ed9d9de7954 100644 --- a/Modules/Core/Common/include/itkImageSink.h +++ b/Modules/Core/Common/include/itkImageSink.h @@ -110,17 +110,19 @@ class ImageSink * by the input images. ITK has a requirement that multiple input * images be congruent in space by default. */ + /** @ITKStartGrouping */ itkSetMacro(CoordinateTolerance, double); itkGetConstMacro(CoordinateTolerance, double); - + /** @ITKEndGrouping */ /** get/set the direction tolerance * This tolerance is used to make sure that all input * images are oriented the same before performing the filter's * transformations. */ + /** @ITKStartGrouping */ itkSetMacro(DirectionTolerance, double); itkGetConstMacro(DirectionTolerance, double); - + /** @ITKEndGrouping */ /** get/set the global default direction tolerance * * This value is used to initialize the DirectionTolerance upon @@ -158,7 +160,7 @@ class ImageSink {} void - VerifyInputInformation() ITKv5_CONST override; + VerifyInputInformation() const override; void BeforeStreamedGenerateData() override @@ -183,9 +185,10 @@ class ImageSink /** Set/Get Helper class for dividing the input into regions for * streaming */ + /** @ITKStartGrouping */ itkSetObjectMacro(RegionSplitter, SplitterType); itkGetModifiableObjectMacro(RegionSplitter, SplitterType); - + /** @ITKEndGrouping */ private: unsigned int m_NumberOfStreamDivisions{ 1 }; @@ -196,8 +199,10 @@ class ImageSink * Tolerances for checking whether input images are defined to * occupy the same physical space. */ + /** @ITKStartGrouping */ double m_CoordinateTolerance{ Self::GetGlobalDefaultCoordinateTolerance() }; double m_DirectionTolerance{ Self::GetGlobalDefaultDirectionTolerance() }; + /** @ITKEndGrouping */ }; } // namespace itk diff --git a/Modules/Core/Common/include/itkImageSink.hxx b/Modules/Core/Common/include/itkImageSink.hxx index 7966797b669..0e062454195 100644 --- a/Modules/Core/Common/include/itkImageSink.hxx +++ b/Modules/Core/Common/include/itkImageSink.hxx @@ -116,8 +116,8 @@ template unsigned int ImageSink::GetNumberOfInputRequestedRegions() { - const InputImageType * inputPtr = const_cast(this->GetInput()); - InputImageRegionType inputImageRegion = inputPtr->GetLargestPossibleRegion(); + const InputImageType * inputPtr = const_cast(this->GetInput()); + const InputImageRegionType inputImageRegion = inputPtr->GetLargestPossibleRegion(); return this->GetRegionSplitter()->GetNumberOfSplits(inputImageRegion, this->m_NumberOfStreamDivisions); } @@ -167,7 +167,7 @@ ImageSink::GenerateNthInputRequestedRegion(unsigned int inputReques template void -ImageSink::VerifyInputInformation() ITKv5_CONST +ImageSink::VerifyInputInformation() const { using ImageBaseType = const ImageBase; @@ -210,29 +210,31 @@ ImageSink::VerifyInputInformation() ITKv5_CONST !inputPtr1->GetDirection().GetVnlMatrix().is_equal(inputPtrN->GetDirection().GetVnlMatrix(), this->m_DirectionTolerance)) { - std::ostringstream originString, spacingString, directionString; + std::ostringstream originString; if (!inputPtr1->GetOrigin().GetVnlVector().is_equal(inputPtrN->GetOrigin().GetVnlVector(), coordinateTol)) { originString.setf(std::ios::scientific); originString.precision(7); - originString << "InputImage Origin: " << inputPtr1->GetOrigin() << ", InputImage" << it.GetName() + originString << "InputImage Origin: " << inputPtr1->GetOrigin() << ", InputImage " << it.GetName() << " Origin: " << inputPtrN->GetOrigin() << std::endl; originString << "\tTolerance: " << coordinateTol << std::endl; } + std::ostringstream spacingString; if (!inputPtr1->GetSpacing().GetVnlVector().is_equal(inputPtrN->GetSpacing().GetVnlVector(), coordinateTol)) { spacingString.setf(std::ios::scientific); spacingString.precision(7); - spacingString << "InputImage Spacing: " << inputPtr1->GetSpacing() << ", InputImage" << it.GetName() + spacingString << "InputImage Spacing: " << inputPtr1->GetSpacing() << ", InputImage " << it.GetName() << " Spacing: " << inputPtrN->GetSpacing() << std::endl; spacingString << "\tTolerance: " << coordinateTol << std::endl; } + std::ostringstream directionString; if (!inputPtr1->GetDirection().GetVnlMatrix().is_equal(inputPtrN->GetDirection().GetVnlMatrix(), this->m_DirectionTolerance)) { directionString.setf(std::ios::scientific); directionString.precision(7); - directionString << "InputImage Direction: " << inputPtr1->GetDirection() << ", InputImage" << it.GetName() + directionString << "InputImage Direction: " << inputPtr1->GetDirection() << ", InputImage " << it.GetName() << " Direction: " << inputPtrN->GetDirection() << std::endl; directionString << "\tTolerance: " << this->m_DirectionTolerance << std::endl; } diff --git a/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.h b/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.h index a9da795e212..325b5210e3b 100644 --- a/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.h @@ -134,8 +134,8 @@ class ITK_TEMPLATE_EXPORT ImageSliceConstIteratorWithIndex : public ImageConstIt : ImageConstIteratorWithIndex() {} - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageSliceConstIteratorWithIndex(const ImageType * ptr, const RegionType & region) : ImageConstIteratorWithIndex(ptr, region) , m_PixelJump(0) diff --git a/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.hxx b/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.hxx index 866faaf549c..2e6cfd4442b 100644 --- a/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.hxx +++ b/Modules/Core/Common/include/itkImageSliceConstIteratorWithIndex.hxx @@ -92,11 +92,9 @@ ImageSliceConstIteratorWithIndex::NextSlice() this->m_Remaining = true; break; } - else - { - this->m_Position -= this->m_OffsetTable[n + 1] - this->m_OffsetTable[n]; - this->m_PositionIndex[n] = this->m_BeginIndex[n]; - } + + this->m_Position -= this->m_OffsetTable[n + 1] - this->m_OffsetTable[n]; + this->m_PositionIndex[n] = this->m_BeginIndex[n]; } } @@ -127,11 +125,9 @@ ImageSliceConstIteratorWithIndex::PreviousSlice() this->m_Remaining = true; break; } - else - { - this->m_Position += this->m_OffsetTable[n + 1] - this->m_OffsetTable[n]; - this->m_PositionIndex[n] = this->m_EndIndex[n] - 1; - } + + this->m_Position += this->m_OffsetTable[n + 1] - this->m_OffsetTable[n]; + this->m_PositionIndex[n] = this->m_EndIndex[n] - 1; } } diff --git a/Modules/Core/Common/include/itkImageSliceIteratorWithIndex.h b/Modules/Core/Common/include/itkImageSliceIteratorWithIndex.h index 56041825b9f..9b7e73021cf 100644 --- a/Modules/Core/Common/include/itkImageSliceIteratorWithIndex.h +++ b/Modules/Core/Common/include/itkImageSliceIteratorWithIndex.h @@ -88,8 +88,8 @@ class ITK_TEMPLATE_EXPORT ImageSliceIteratorWithIndex : public ImageSliceConstIt /** Default constructor. Needed since we provide a cast constructor. */ ImageSliceIteratorWithIndex() = default; - /** Constructor establishes an iterator to walk a particular image and a - * particular region of that image. */ + /** Constructor establishes an iterator to walk a particular image and a particular region of that image. Initializes + * the iterator at the begin of the region. */ ImageSliceIteratorWithIndex(ImageType * ptr, const RegionType & region); /** Constructor that can be used to cast from an ImageIterator to an @@ -119,9 +119,11 @@ class ITK_TEMPLATE_EXPORT ImageSliceIteratorWithIndex : public ImageSliceConstIt protected: /** The construction from a const iterator is declared protected in order to enforce const correctness. */ + /** @ITKStartGrouping */ ImageSliceIteratorWithIndex(const ImageSliceConstIteratorWithIndex & it); Self & operator=(const ImageSliceConstIteratorWithIndex & it); + /** @ITKEndGrouping */ }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageSource.h b/Modules/Core/Common/include/itkImageSource.h index d57631b0cf7..0757870b2da 100644 --- a/Modules/Core/Common/include/itkImageSource.h +++ b/Modules/Core/Common/include/itkImageSource.h @@ -142,11 +142,12 @@ class ITK_TEMPLATE_EXPORT ImageSource * types. Derived classes should have names get methods for these * outputs. */ + /** @ITKStartGrouping */ OutputImageType * GetOutput(); const OutputImageType * GetOutput() const; - + /** @ITKEndGrouping */ OutputImageType * GetOutput(unsigned int idx); @@ -221,11 +222,12 @@ class ITK_TEMPLATE_EXPORT ImageSource * SmartPointer to a DataObject. If a subclass of ImageSource has * multiple outputs of different types, then that class must provide * an implementation of MakeOutput(). */ + /** @ITKStartGrouping */ ProcessObject::DataObjectPointer MakeOutput(ProcessObject::DataObjectPointerArraySizeType idx) override; ProcessObject::DataObjectPointer MakeOutput(const ProcessObject::DataObjectIdentifierType &) override; - + /** @ITKEndGrouping */ protected: ImageSource(); ~ImageSource() override = default; @@ -295,11 +297,12 @@ class ITK_TEMPLATE_EXPORT ImageSource * in a single thread being reused to process multiple work units. * * \sa GenerateData(), SplitRequestedRegion() */ + /** @ITKStartGrouping */ virtual void ThreadedGenerateData(const OutputImageRegionType & region, ThreadIdType threadId); virtual void DynamicThreadedGenerateData(const OutputImageRegionType & outputRegionForThread); - + /** @ITKEndGrouping */ /** The GenerateData method normally allocates the buffers for all of the * outputs of a filter. Some filters may want to override this default * behavior. For example, a filter may have multiple outputs with @@ -395,11 +398,12 @@ class ITK_TEMPLATE_EXPORT ImageSource /** Whether to use classic multi-threading infrastructure (OFF by default). * Classic multi-threading uses derived class' ImageRegionSplitter, * thus enabling custom region splitting methods. */ + /** @ITKStartGrouping */ itkGetConstMacro(DynamicMultiThreading, bool); itkSetMacro(DynamicMultiThreading, bool); itkBooleanMacro(DynamicMultiThreading); - - bool m_DynamicMultiThreading{}; + /** @ITKEndGrouping */ + bool m_DynamicMultiThreading{ true }; }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageSource.hxx b/Modules/Core/Common/include/itkImageSource.hxx index 3103e4256eb..e0adfa55f8a 100644 --- a/Modules/Core/Common/include/itkImageSource.hxx +++ b/Modules/Core/Common/include/itkImageSource.hxx @@ -41,16 +41,10 @@ ImageSource::ImageSource() { // Create the output. We use static_cast<> here because we know the default // output must be of type TOutputImage - typename TOutputImage::Pointer output = static_cast(this->MakeOutput(0).GetPointer()); + const typename TOutputImage::Pointer output = static_cast(this->MakeOutput(0).GetPointer()); this->ProcessObject::SetNumberOfRequiredOutputs(1); this->ProcessObject::SetNthOutput(0, output.GetPointer()); -#if defined(ITKV4_COMPATIBILITY) - m_DynamicMultiThreading = false; -#else - m_DynamicMultiThreading = true; -#endif - // Set the default behavior of an image source to NOT release its // output bulk data prior to GenerateData() in case that bulk data // can be reused (an thus avoid a costly deallocate/allocate cycle). @@ -58,7 +52,8 @@ ImageSource::ImageSource() } template -ProcessObject::DataObjectPointer ImageSource::MakeOutput(ProcessObject::DataObjectPointerArraySizeType) +ProcessObject::DataObjectPointer +ImageSource::MakeOutput(ProcessObject::DataObjectPointerArraySizeType) { return TOutputImage::New().GetPointer(); } @@ -274,34 +269,19 @@ ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION ImageSource::ThreaderCallback(void * arg) { using WorkUnitInfo = MultiThreaderBase::WorkUnitInfo; - auto * workUnitInfo = static_cast(arg); - ThreadIdType workUnitID = workUnitInfo->WorkUnitID; - ThreadIdType workUnitCount = workUnitInfo->NumberOfWorkUnits; - auto * str = (ThreadStruct *)(workUnitInfo->UserData); + auto * workUnitInfo = static_cast(arg); + const ThreadIdType workUnitID = workUnitInfo->WorkUnitID; + const ThreadIdType workUnitCount = workUnitInfo->NumberOfWorkUnits; + auto * str = (ThreadStruct *)(workUnitInfo->UserData); // execute the actual method with appropriate output region // first find out how many pieces extent can be split into. typename TOutputImage::RegionType splitRegion; - ThreadIdType total = str->Filter->SplitRequestedRegion(workUnitID, workUnitCount, splitRegion); + const ThreadIdType total = str->Filter->SplitRequestedRegion(workUnitID, workUnitCount, splitRegion); if (workUnitID < total) { str->Filter->ThreadedGenerateData(splitRegion, workUnitID); -#if defined(ITKV4_COMPATIBILITY) - if (str->Filter->GetAbortGenerateData()) - { - std::string msg; - ProcessAborted e(__FILE__, __LINE__); - msg += "Object " + std::string(str->Filter->GetNameOfClass()) + ": AbortGenerateData was set!"; - e.SetDescription(msg); - throw e; - } - else if (!str->Filter->GetDynamicMultiThreading() // progress reporting is not done in MultiThreaders - && str->Filter->GetProgress() == 0.0f) // and progress was not set after at least the first chunk finished - { - str->Filter->UpdateProgress(static_cast(workUnitID + 1) / total); // this will be the only progress update - } -#endif } // else don't use this thread. Threads were not split conveniently. return ITK_THREAD_RETURN_DEFAULT_VALUE; @@ -312,7 +292,7 @@ void ImageSource::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - os << indent << "DynamicMultiThreading: " << (m_DynamicMultiThreading ? "On" : "Off") << std::endl; + itkPrintSelfBooleanMacro(DynamicMultiThreading); } } // end namespace itk diff --git a/Modules/Core/Common/include/itkImageToImageFilter.h b/Modules/Core/Common/include/itkImageToImageFilter.h index f294f6b066f..ddf00106642 100644 --- a/Modules/Core/Common/include/itkImageToImageFilter.h +++ b/Modules/Core/Common/include/itkImageToImageFilter.h @@ -186,17 +186,19 @@ class ITK_TEMPLATE_EXPORT ImageToImageFilter * by the input images. ITK has a requirement that multiple input * images be congruent in space by default. */ + /** @ITKStartGrouping */ itkSetMacro(CoordinateTolerance, double); itkGetConstMacro(CoordinateTolerance, double); - + /** @ITKEndGrouping */ /** get/set the direction tolerance * This tolerance is used to make sure that all input * images are oriented the same before performing the filter's * transformations. */ + /** @ITKStartGrouping */ itkSetMacro(DirectionTolerance, double); itkGetConstMacro(DirectionTolerance, double); - + /** @ITKEndGrouping */ /** get/set the global default direction tolerance * * This value is used to initialize the DirectionTolerance upon @@ -244,7 +246,7 @@ class ITK_TEMPLATE_EXPORT ImageToImageFilter * \sa ProcessObject::VerifyInputInformation */ void - VerifyInputInformation() ITKv5_CONST override; + VerifyInputInformation() const override; /** What is the input requested region that is required to produce * the output requested region? The base assumption for image @@ -362,9 +364,10 @@ class ITK_TEMPLATE_EXPORT ImageToImageFilter * the versions from ProcessObject to avoid warnings about hiding * methods from the superclass. */ + /** @ITKStartGrouping */ using Superclass::PushBackInput; using Superclass::PushFrontInput; - + /** @ITKEndGrouping */ private: /** * Tolerances for checking whether input images are defined to diff --git a/Modules/Core/Common/include/itkImageToImageFilter.hxx b/Modules/Core/Common/include/itkImageToImageFilter.hxx index c8ec806f39c..e6c6d6aeb4c 100644 --- a/Modules/Core/Common/include/itkImageToImageFilter.hxx +++ b/Modules/Core/Common/include/itkImageToImageFilter.hxx @@ -116,7 +116,7 @@ ImageToImageFilter::CallCopyOutputRegionToInputRegion InputImageRegionType & destRegion, const OutputImageRegionType & srcRegion) { - OutputToInputRegionCopierType regionCopier; + const OutputToInputRegionCopierType regionCopier; regionCopier(destRegion, srcRegion); } @@ -127,7 +127,7 @@ void ImageToImageFilter::CallCopyInputRegionToOutputRegion(OutputImageRegionType & destRegion, const InputImageRegionType & srcRegion) { - InputToOutputRegionCopierType regionCopier; + const InputToOutputRegionCopierType regionCopier; regionCopier(destRegion, srcRegion); } @@ -145,7 +145,7 @@ ImageToImageFilter::PrintSelf(std::ostream & os, Inde template void -ImageToImageFilter::VerifyInputInformation() ITKv5_CONST +ImageToImageFilter::VerifyInputInformation() const { using ImageBaseType = const ImageBase; @@ -186,29 +186,31 @@ ImageToImageFilter::VerifyInputInformation() ITKv5_CO if (!inputPtr1->IsCongruentImageGeometry(inputPtrN, m_CoordinateTolerance, m_DirectionTolerance)) { - std::ostringstream originString, spacingString, directionString; + std::ostringstream originString; if (!inputPtr1->GetOrigin().GetVnlVector().is_equal(inputPtrN->GetOrigin().GetVnlVector(), coordinateTol)) { originString.setf(std::ios::scientific); originString.precision(7); - originString << "InputImage Origin: " << inputPtr1->GetOrigin() << ", InputImage" << it.GetName() + originString << "InputImage Origin: " << inputPtr1->GetOrigin() << ", InputImage " << it.GetName() << " Origin: " << inputPtrN->GetOrigin() << std::endl; originString << "\tTolerance: " << coordinateTol << std::endl; } + std::ostringstream spacingString; if (!inputPtr1->GetSpacing().GetVnlVector().is_equal(inputPtrN->GetSpacing().GetVnlVector(), coordinateTol)) { spacingString.setf(std::ios::scientific); spacingString.precision(7); - spacingString << "InputImage Spacing: " << inputPtr1->GetSpacing() << ", InputImage" << it.GetName() + spacingString << "InputImage Spacing: " << inputPtr1->GetSpacing() << ", InputImage " << it.GetName() << " Spacing: " << inputPtrN->GetSpacing() << std::endl; spacingString << "\tTolerance: " << coordinateTol << std::endl; } + std::ostringstream directionString; if (!inputPtr1->GetDirection().GetVnlMatrix().is_equal(inputPtrN->GetDirection().GetVnlMatrix(), this->m_DirectionTolerance)) { directionString.setf(std::ios::scientific); directionString.precision(7); - directionString << "InputImage Direction: " << inputPtr1->GetDirection() << ", InputImage" << it.GetName() + directionString << "InputImage Direction: " << inputPtr1->GetDirection() << ", InputImage " << it.GetName() << " Direction: " << inputPtrN->GetDirection() << std::endl; directionString << "\tTolerance: " << this->m_DirectionTolerance << std::endl; } diff --git a/Modules/Core/Common/include/itkImageToImageFilterDetail.h b/Modules/Core/Common/include/itkImageToImageFilterDetail.h index 8d2f7c9180f..a722cf78d89 100644 --- a/Modules/Core/Common/include/itkImageToImageFilterDetail.h +++ b/Modules/Core/Common/include/itkImageToImageFilterDetail.h @@ -43,6 +43,7 @@ namespace itk */ namespace ImageToImageFilterDetail { + /** \struct DispatchBase * \brief Base class for a class used to dispatch to dimension specific implementations. * @@ -54,8 +55,7 @@ namespace ImageToImageFilterDetail struct DispatchBase {}; -/** \struct BooleanDispatch - * \brief Templated class to produce a unique type "true" and "false". +/** \brief Templated class to produce a unique type "true" and "false". * * BooleanDispatch is a templated class that produce a unique type for * for "true" and for "false". These types may be used to decide which @@ -65,8 +65,7 @@ template struct BooleanDispatch {}; -/** \struct IntDispatch - * \brief Templated class to produce a unique type for each integer +/** \brief Templated class to produce a unique type for each integer * * IntDispatch is a templated class that produces a unique * type for each integer. IntDispatch is typically @@ -77,8 +76,7 @@ template struct IntDispatch : public DispatchBase {}; -/** \struct UnsignedIntDispatch - * \brief Templated class to produce a unique type for each unsigned integer (usually a dimension). +/** \brief Templated class to produce a unique type for each unsigned integer (usually a dimension). * * UnsignedIntDispatch is a templated class that produces a unique * type for each unsigned integer. UnsignedIntDispatch is typically @@ -95,8 +93,7 @@ template struct UnsignedIntDispatch : public DispatchBase {}; -/** \struct BinaryBooleanDispatch - * \brief Templated class to produce a unique type for a pairing of booleans. +/** \brief Templated class to produce a unique type for a pairing of booleans. * * BinaryBooleanDispatch is a templated class that produces a unique type * for each pairing of two boolean values ((true, true), (true, false), @@ -111,8 +108,7 @@ struct BinaryBooleanDispatch using SecondType = BooleanDispatch; }; -/** \struct BinaryIntDispatch - * \brief Templated class to produce a unique type for a pairing of integers. +/** \brief Templated class to produce a unique type for a pairing of integers. * * IntBooleanDispatch is a templated class that produces a unique type * for each pairing of two integer values. @@ -126,8 +122,7 @@ struct BinaryIntDispatch using SecondType = IntDispatch; }; -/** \struct BinaryUnsignedIntDispatch - * \brief Templated class to produce a unique type for a pairing of unsigned integers (usually two dimensions). +/** \brief Templated class to produce a unique type for a pairing of unsigned integers (usually two dimensions). * * BinaryUnsignedIntDispatch is a templated class that produces a * unique type for a pairing of unsigned integers. @@ -215,7 +210,7 @@ ImageToImageFilterDefaultCopyRegion(const typename BinaryUnsignedIntDispatch destIndex; Size destSize; @@ -223,7 +218,7 @@ ImageToImageFilterDefaultCopyRegion(const typename BinaryUnsignedIntDispatch & srcSize = srcRegion.GetSize(); // copy what we can - for (dim = 0; dim < D1; ++dim) + for (unsigned int dim = 0; dim < D1; ++dim) { destIndex[dim] = srcIndex[dim]; destSize[dim] = srcSize[dim]; @@ -257,26 +252,26 @@ ImageToImageFilterDefaultCopyRegion(const typename BinaryUnsignedIntDispatch destIndex; Size destSize; const Index & srcIndex = srcRegion.GetIndex(); const Size & srcSize = srcRegion.GetSize(); // copy what we can - for (dim = 0; dim < D2; ++dim) - { - destIndex[dim] = srcIndex[dim]; - destSize[dim] = srcSize[dim]; - } - // fill in the rest of the dimensions with zero/one - for (; dim < D1; ++dim) { - destIndex[dim] = 0; - destSize[dim] = 1; + unsigned int dim = 0; + for (; dim < D2; ++dim) + { + destIndex[dim] = srcIndex[dim]; + destSize[dim] = srcSize[dim]; + } + // fill in the rest of the dimensions with zero/one + for (; dim < D1; ++dim) + { + destIndex[dim] = 0; + destSize[dim] = 1; + } } - destRegion.SetIndex(destIndex); destRegion.SetSize(destSize); } diff --git a/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.hxx b/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.hxx index 8fa6baa20e7..6001114af1d 100644 --- a/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.hxx +++ b/Modules/Core/Common/include/itkImageVectorOptimizerParametersHelper.hxx @@ -39,7 +39,7 @@ ImageVectorOptimizerParametersHelper: using vectorElement = typename ParameterImageType::PixelContainer::Element; auto * vectorPointer = reinterpret_cast(pointer); // We're expecting the new memory buffer t be of same size. - unsigned int sizeInVectors = m_ParameterImage->GetPixelContainer()->Size(); + const unsigned int sizeInVectors = m_ParameterImage->GetPixelContainer()->Size(); // After this call, PixelContainer will *not* manage its memory. this->m_ParameterImage->GetPixelContainer()->SetImportPointer(vectorPointer, sizeInVectors); Superclass::MoveDataPointer(container, pointer); @@ -57,25 +57,23 @@ ImageVectorOptimizerParametersHelper: m_ParameterImage = nullptr; return; } - else + + auto * image = dynamic_cast(object); + if (image == nullptr) { - auto * image = dynamic_cast(object); - if (image == nullptr) - { - itkGenericExceptionMacro("ImageVectorOptimizerParametersHelper::SetParametersObject: object is " - "not of proper image type. Expected VectorImage, received " - << object->GetNameOfClass()); - } - m_ParameterImage = image; - // The PixelContainer for Image points to type Vector, so we have - // 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. - typename CommonContainerType::SizeValueType sz = image->GetPixelContainer()->Size() * VVectorDimension; - auto * valuePointer = reinterpret_cast(image->GetPixelContainer()->GetBufferPointer()); - // Set the Array's pointer to the image data buffer. By default it will - // not manage the memory. - container->SetData(valuePointer, sz, false); + itkGenericExceptionMacro("ImageVectorOptimizerParametersHelper::SetParametersObject: object is " + "not of proper image type. Expected VectorImage, received " + << object->GetNameOfClass()); } + m_ParameterImage = image; + // The PixelContainer for Image points to type Vector, so we have + // 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. + const typename CommonContainerType::SizeValueType sz = image->GetPixelContainer()->Size() * VVectorDimension; + auto * valuePointer = reinterpret_cast(image->GetPixelContainer()->GetBufferPointer()); + // Set the Array's pointer to the image data buffer. By default it will + // not manage the memory. + container->SetData(valuePointer, sz, false); } } // namespace itk diff --git a/Modules/Core/Common/include/itkImportImageContainer.h b/Modules/Core/Common/include/itkImportImageContainer.h index 189dfcb6a5a..38894c6294c 100644 --- a/Modules/Core/Common/include/itkImportImageContainer.h +++ b/Modules/Core/Common/include/itkImportImageContainer.h @@ -80,10 +80,18 @@ class ITK_TEMPLATE_EXPORT ImportImageContainer : public Object SetImportPointer(TElement * ptr, TElementIdentifier num, bool LetContainerManageMemory = false); /** Index operator. This version can be an lvalue. */ - TElement & operator[](const ElementIdentifier id) { return m_ImportPointer[id]; } + TElement & + operator[](const ElementIdentifier id) + { + return m_ImportPointer[id]; + } /** Index operator. This version can only be an rvalue */ - const TElement & operator[](const ElementIdentifier id) const { return m_ImportPointer[id]; } + const TElement & + operator[](const ElementIdentifier id) const + { + return m_ImportPointer[id]; + } /** Return a pointer to the beginning of the buffer. This is used by * the image iterator class. */ @@ -147,10 +155,11 @@ class ITK_TEMPLATE_EXPORT ImportImageContainer : public Object * Note that the normal logic of this class set the value of the boolean * flag. This may override your setting if you call this methods prematurely. * \warning Improper use of these methods will result in memory leaks */ + /** @ITKStartGrouping */ itkSetMacro(ContainerManageMemory, bool); itkGetConstMacro(ContainerManageMemory, bool); itkBooleanMacro(ContainerManageMemory); - + /** @ITKEndGrouping */ protected: ImportImageContainer() = default; ~ImportImageContainer() override; diff --git a/Modules/Core/Common/include/itkImportImageFilter.h b/Modules/Core/Common/include/itkImportImageFilter.h index bd1c3135f33..c35c5251f74 100644 --- a/Modules/Core/Common/include/itkImportImageFilter.h +++ b/Modules/Core/Common/include/itkImportImageFilter.h @@ -117,16 +117,18 @@ class ITK_TEMPLATE_EXPORT ImportImageFilter : public ImageSource; /** Set the direction of the image diff --git a/Modules/Core/Common/include/itkImportImageFilter.hxx b/Modules/Core/Common/include/itkImportImageFilter.hxx index 7c3fdf35ced..31caf9827b1 100644 --- a/Modules/Core/Common/include/itkImportImageFilter.hxx +++ b/Modules/Core/Common/include/itkImportImageFilter.hxx @@ -38,14 +38,14 @@ ImportImageFilter::PrintSelf(std::ostream & os, Indent itkPrintSelfObjectMacro(ImportImageContainer); os << indent << "Import buffer size: " << m_Size << std::endl; os << indent << "Spacing: ["; - for (i = 0; i < static_cast(VImageDimension) - 1; ++i) + for (i = 0; i < int{ VImageDimension } - 1; ++i) { os << m_Spacing[i] << ", "; } os << m_Spacing[i] << ']' << std::endl; os << indent << "Origin: ["; - for (i = 0; i < static_cast(VImageDimension) - 1; ++i) + for (i = 0; i < int{ VImageDimension } - 1; ++i) { os << m_Origin[i] << ", "; } @@ -92,7 +92,7 @@ ImportImageFilter::EnlargeOutputRequestedRegion(DataObj Superclass::EnlargeOutputRequestedRegion(output); // get pointer to the output - OutputImagePointer outputPtr = this->GetOutput(); + const OutputImagePointer outputPtr = this->GetOutput(); // set the requested region to the largest possible region (in this case // the amount of data that we have) @@ -110,7 +110,7 @@ ImportImageFilter::GenerateOutputInformation() Superclass::GenerateOutputInformation(); // get pointer to the output - OutputImagePointer outputPtr = this->GetOutput(); + const OutputImagePointer outputPtr = this->GetOutput(); // we need to compute the output spacing, the output origin, the // output image size, and the output image start index @@ -132,7 +132,7 @@ ImportImageFilter::GenerateData() // Therefore, this filter does not call outputPtr->Allocate(). // get pointer to the output - OutputImagePointer outputPtr = this->GetOutput(); + const OutputImagePointer outputPtr = this->GetOutput(); // the output buffer size is set to the size specified by the user via the // SetRegion() method. diff --git a/Modules/Core/Common/include/itkInPlaceImageFilter.h b/Modules/Core/Common/include/itkInPlaceImageFilter.h index df1f8c1f27c..79d296c572e 100644 --- a/Modules/Core/Common/include/itkInPlaceImageFilter.h +++ b/Modules/Core/Common/include/itkInPlaceImageFilter.h @@ -110,10 +110,11 @@ class ITK_TEMPLATE_EXPORT InPlaceImageFilter : public ImageToImageFilter::PrintSelf(std::ostream & os, Inde { Superclass::PrintSelf(os, indent); - os << indent << "InPlace: " << (m_InPlace ? "On" : "Off") << std::endl; - os << indent << "RunningInPlace: " << (m_RunningInPlace ? "On" : "Off") << std::endl; + itkPrintSelfBooleanMacro(InPlace); + itkPrintSelfBooleanMacro(RunningInPlace); } template @@ -57,10 +57,9 @@ InPlaceImageFilter::InternalAllocateOutputs() // additionally the buffered and requested regions of the input and // output must match. bool rMatch = true; - if (inputPtr != nullptr && - static_cast(InputImageDimension) == static_cast(OutputImageDimension)) + if (inputPtr != nullptr && InputImageDimension == OutputImageDimension) { - for (unsigned int i = 0; i < static_cast(InputImageDimension); ++i) + for (unsigned int i = 0; i < InputImageDimension; ++i) { if (inputPtr->GetBufferedRegion().GetIndex(i) != outputPtr->GetRequestedRegion().GetIndex(i)) { @@ -98,7 +97,8 @@ InPlaceImageFilter::InternalAllocateOutputs() // method since it returns the input as a pointer to a // DataObject as opposed to the subclass version which // static_casts the input to an TInputImage). - typename ImageBaseType::Pointer nthOutputPtr = dynamic_cast(this->ProcessObject::GetOutput(i)); + const typename ImageBaseType::Pointer nthOutputPtr = + dynamic_cast(this->ProcessObject::GetOutput(i)); if (nthOutputPtr) { diff --git a/Modules/Core/Common/include/itkIndex.h b/Modules/Core/Common/include/itkIndex.h index 754bc27dbdb..706c699ae06 100644 --- a/Modules/Core/Common/include/itkIndex.h +++ b/Modules/Core/Common/include/itkIndex.h @@ -27,8 +27,7 @@ namespace itk { -/** \struct Index - * \brief Represent a n-dimensional index in a n-dimensional image. +/** \brief Represent a n-dimensional index in a n-dimensional image. * * Index is a templated class to represent a multi-dimensional index, * i.e. (i,j,k,...). Index is templated over the dimension of the index. @@ -210,7 +209,8 @@ struct ITK_TEMPLATE_EXPORT Index final /** * Multiply an index by a size (elementwise product). */ - const Self operator*(const SizeType & vec) const + const Self + operator*(const SizeType & vec) const { Self result; @@ -246,7 +246,7 @@ struct ITK_TEMPLATE_EXPORT Index final * \sa SetIndex() * \sa GetElement() */ void - SetElement(unsigned long element, IndexValueType val) + SetElement(unsigned int element, IndexValueType val) { m_InternalArray[element] = val; } @@ -258,7 +258,7 @@ struct ITK_TEMPLATE_EXPORT Index final * \sa GetIndex() * \sa SetElement() */ IndexValueType - GetElement(unsigned long element) const + GetElement(unsigned int element) const { return m_InternalArray[element]; } @@ -289,9 +289,9 @@ struct ITK_TEMPLATE_EXPORT Index final alignas(IndexValueType) IndexValueType m_InternalArray[VDimension]; /** Copy values from a FixedArray by rounding each one of the components */ - template + template inline void - CopyWithRound(const FixedArray & point) + CopyWithRound(const FixedArray & point) { for (unsigned int i = 0; i < VDimension; ++i) { @@ -300,9 +300,9 @@ struct ITK_TEMPLATE_EXPORT Index final } /** Copy values from a FixedArray by casting each one of the components */ - template + template inline void - CopyWithCast(const FixedArray & point) + CopyWithCast(const FixedArray & point) { for (unsigned int i = 0; i < VDimension; ++i) { @@ -344,7 +344,7 @@ struct ITK_TEMPLATE_EXPORT Index final } void - swap(Index & other) + swap(Index & other) noexcept { std::swap(m_InternalArray, other.m_InternalArray); } @@ -427,9 +427,17 @@ struct ITK_TEMPLATE_EXPORT Index final return false; } - constexpr reference operator[](size_type pos) { return m_InternalArray[pos]; } + constexpr reference + operator[](size_type pos) + { + return m_InternalArray[pos]; + } - constexpr const_reference operator[](size_type pos) const { return m_InternalArray[pos]; } + constexpr const_reference + operator[](size_type pos) const + { + return m_InternalArray[pos]; + } reference at(size_type pos) @@ -445,25 +453,25 @@ struct ITK_TEMPLATE_EXPORT Index final return m_InternalArray[pos]; } - reference + constexpr reference front() { return *begin(); } - const_reference + constexpr const_reference front() const { return *begin(); } - reference + constexpr reference back() { return VDimension ? *(end() - 1) : *end(); } - const_reference + constexpr const_reference back() const { return VDimension ? *(end() - 1) : *end(); @@ -522,7 +530,7 @@ operator<<(std::ostream & os, const Index & obj) { os << obj[i] << ", "; } - if (VDimension >= 1) + if constexpr (VDimension >= 1) { os << obj[VDimension - 1]; } @@ -577,7 +585,7 @@ operator>=(const Index & one, const Index & two) // Specialized algorithms [6.2.2.2]. template inline void -swap(Index & one, Index & two) +swap(Index & one, Index & two) noexcept { std::swap(one.m_InternalArray, two.m_InternalArray); } diff --git a/Modules/Core/Common/include/itkIndexRange.h b/Modules/Core/Common/include/itkIndexRange.h index 5306ef7785b..b0af309ac4a 100644 --- a/Modules/Core/Common/include/itkIndexRange.h +++ b/Modules/Core/Common/include/itkIndexRange.h @@ -101,15 +101,23 @@ class IndexRange final /** Returns a reference to the current index. */ - reference operator*() const noexcept { return m_Index; } + constexpr reference + operator*() const noexcept + { + return m_Index; + } /** Returns a pointer to the current index. */ - pointer operator->() const noexcept { return &(**this); } + constexpr pointer + operator->() const noexcept + { + return &(**this); + } /** Prefix increment ('++it'). */ - const_iterator & + constexpr const_iterator & operator++() noexcept { for (unsigned int i = 0; i < (VDimension - 1); ++i) @@ -132,7 +140,7 @@ class IndexRange final /** Postfix increment ('it++'). * \note Usually prefix increment ('++it') is preferable. */ - const_iterator + constexpr const_iterator operator++(int) noexcept { auto result = *this; @@ -142,7 +150,7 @@ class IndexRange final /** Prefix decrement ('--it'). */ - const_iterator & + constexpr const_iterator & operator--() noexcept { for (unsigned int i = 0; i < (VDimension - 1); ++i) @@ -164,7 +172,7 @@ class IndexRange final /** Postfix increment ('it--'). * \note Usually prefix increment ('--it') is preferable. */ - const_iterator + constexpr const_iterator operator--(int) noexcept { auto result = *this; @@ -195,7 +203,7 @@ class IndexRange final /** Returns (it1 < it2) for iterators it1 and it2. */ - friend bool + friend constexpr bool operator<(const const_iterator & lhs, const const_iterator & rhs) noexcept { for (unsigned int i = VDimension; i > 0; --i) @@ -216,7 +224,7 @@ class IndexRange final /** Returns (it1 > it2) for iterators it1 and it2. */ - friend bool + friend constexpr bool operator>(const const_iterator & lhs, const const_iterator & rhs) noexcept { // Implemented just like the corresponding std::rel_ops operator. @@ -225,7 +233,7 @@ class IndexRange final /** Returns (it1 <= it2) for iterators it1 and it2. */ - friend bool + friend constexpr bool operator<=(const const_iterator & lhs, const const_iterator & rhs) noexcept { // Implemented just like the corresponding std::rel_ops operator. @@ -234,7 +242,7 @@ class IndexRange final /** Returns (it1 >= it2) for iterators it1 and it2. */ - friend bool + friend constexpr bool operator>=(const const_iterator & lhs, const const_iterator & rhs) noexcept { // Implemented just like the corresponding std::rel_ops operator. @@ -250,10 +258,18 @@ class IndexRange final struct ZeroIndex { // The "index" operator. - constexpr IndexValueType operator[](unsigned int) const { return 0; } + constexpr IndexValueType + operator[](unsigned int) const + { + return 0; + } // Implicitly converts to a default-initialized itk::Index. - constexpr operator IndexType() const { return IndexType(); } + constexpr + operator IndexType() const + { + return IndexType(); + } }; @@ -261,7 +277,9 @@ class IndexRange final using MinIndexType = std::conditional_t; // Private constructor, only used by friend class IndexRange. - const_iterator(const IndexType & index, const MinIndexType & minIndex, const IndexType & maxIndex) noexcept + constexpr const_iterator(const IndexType & index, + const MinIndexType & minIndex, + const IndexType & maxIndex) noexcept : // Note: Use parentheses instead of curly braces to initialize data members, // to avoid AppleClang 6.0.0.6000056 compilation error, "no viable conversion..." m_Index(index) @@ -296,7 +314,7 @@ class IndexRange final /** Constructs a range of indices for the specified grid size. */ - explicit IndexRange(const SizeType & gridSize) + constexpr explicit IndexRange(const SizeType & gridSize) : // Note: Use parentheses instead of curly braces to initialize data members, // to avoid AppleClang 6.0.0.6000056 compile errors, "no viable conversion..." m_MinIndex() @@ -326,14 +344,14 @@ class IndexRange final /** Returns an iterator to the first index. */ - iterator + constexpr iterator begin() const noexcept { return iterator(m_MinIndex, m_MinIndex, m_MaxIndex); } /** Returns an 'end iterator' for this range. */ - iterator + constexpr iterator end() const noexcept { IndexType index = m_MinIndex; @@ -343,14 +361,14 @@ class IndexRange final /** Returns a const iterator to the first index. * Provides only read-only access to the index data. */ - const_iterator + constexpr const_iterator cbegin() const noexcept { return this->begin(); } /** Returns a const 'end iterator' for this range. */ - const_iterator + constexpr const_iterator cend() const noexcept { return this->end(); @@ -386,7 +404,7 @@ class IndexRange final /** Returns the size of the range, that is the number of indices. */ - size_t + constexpr size_t size() const noexcept { size_t result = 1; @@ -400,7 +418,7 @@ class IndexRange final /** Tells whether the range is empty. */ - bool + constexpr bool empty() const noexcept { // When an IndexRange is empty, each index value of m_MaxIndex is less than the corresponding @@ -414,7 +432,7 @@ class IndexRange final private: using MinIndexType = typename iterator::MinIndexType; - static IndexType + static constexpr IndexType CalculateMaxIndex(const MinIndexType & minIndex, const SizeType & size) { const bool sizeHasZeroValue = [&size] { @@ -431,7 +449,8 @@ class IndexRange final // Treat any size that has a zero value equally. const SizeType normalizedSize = sizeHasZeroValue ? SizeType{ { 0 } } : size; - IndexType index; + // The `index` is initialized (`{}`), just to support C++17 constexpr. + IndexType index{}; for (unsigned int i = 0; i < VDimension; ++i) { diff --git a/Modules/Core/Common/include/itkIntTypes.h b/Modules/Core/Common/include/itkIntTypes.h index 6bebb402ae5..0ec9cf3f9c1 100644 --- a/Modules/Core/Common/include/itkIntTypes.h +++ b/Modules/Core/Common/include/itkIntTypes.h @@ -58,6 +58,9 @@ using std::uintmax_t; using std::intptr_t; using std::uintptr_t; +using std::size_t; +using std::ptrdiff_t; + #if defined(ITK_USE_64BITS_IDS) && ((ULLONG_MAX != ULONG_MAX) || (LLONG_MAX != LONG_MAX)) diff --git a/Modules/Core/Common/include/itkIsBaseOf.h b/Modules/Core/Common/include/itkIsBaseOf.h index 34cc34b6129..6882791877b 100644 --- a/Modules/Core/Common/include/itkIsBaseOf.h +++ b/Modules/Core/Common/include/itkIsBaseOf.h @@ -18,39 +18,6 @@ #ifndef itkIsBaseOf_h #define itkIsBaseOf_h -#include - -#include "itkMacro.h" - -#if !defined(ITK_LEGACY_REMOVE) - -namespace itk -{ -/// \cond HIDE_META_PROGRAMMING -namespace mpl -{ -/** Traits that emulates \c std::is_base_of<>. - * \tparam TBase base type - * \tparam TDerived derived type - * \return (in \c Value) whether \c TDerived inherits (publicly) from \c TBase - * (directly, or indirectly) - * \author The definition provided follows the code snippet available in Andrei - * Alexandrescu's Modern C++ Design. - * \ingroup MetaProgrammingLibrary - * \ingroup ITKCommon - */ -template -struct IsBaseOf -{ - static constexpr bool Value = std::is_base_of_v; -}; -} // end namespace mpl - -/// \endcond -} // end namespace itk - -#else // ITK_LEGACY_REMOVE -# error Use C++ 11 std::is_base_of directly -#endif +#error Use C++ 11 std::is_base_of directly #endif // itkIsBaseOf_h diff --git a/Modules/Core/Common/include/itkIsConvertible.h b/Modules/Core/Common/include/itkIsConvertible.h index 12193fd05b9..66c6ecffa6d 100644 --- a/Modules/Core/Common/include/itkIsConvertible.h +++ b/Modules/Core/Common/include/itkIsConvertible.h @@ -17,75 +17,7 @@ *=========================================================================*/ #ifndef itkIsConvertible_h #define itkIsConvertible_h - -#include "itkMacro.h" - -#if !defined(ITK_LEGACY_REMOVE) - -# include "itkMetaProgrammingLibrary.h" - -namespace itk -{ - -/** \cond HIDE_META_PROGRAMMING */ - -namespace mpl -{ -namespace Details -{ - -/** Helper root class for Meta-programming purpose. - * This class provides two types that help build SFINAE based meta-programs. - * \ingroup MetaProgrammingLibrary - * \ingroup ITKCommon - */ -struct SfinaeTypes -{ - using TOne = char; - struct TTwo - { - char arr__[2]; - }; -}; -} // namespace Details - -/** Traits that emulates \c std::is_convertible<>. - * \tparam TFrom type to convert from - * \tparam TTo type to convert to - * \return (in \c Value) whether \c TFrom objects can be converted into \c TTo - * objects. - * \warning This version does not support \c void, function pointers, nor arrays. - * \author The definition provided follows the code snippet available in Andrei - * Alexandrescu's Modern C++ Design. - * \ingroup MetaProgrammingLibrary - * \ingroup ITKCommon - */ -template -struct IsConvertible : private Details::SfinaeTypes -{ -private: - static TOne Test(TTo); - static TTwo - Test(...); - static TFrom - MakeT(); - -public: - static constexpr bool Value = sizeof(Test(MakeT())) == sizeof(TOne); -}; - -} // end namespace mpl - -// itk::IsConvertible has moved to itk::mpl. -// Expect itk::IsConvertible to be deprecated. -using mpl::IsConvertible; - -/** \endcond */ - -} // end namespace itk - -#else // ITK_LEGACY_REMOVE -# error Use C++ 11 std::is_convertible directly -#endif +// This file is no longer needed, C++11 provides support directly +#error Use C++ 11 std::is_convertible directly #endif // itkIsConvertible_h diff --git a/Modules/Core/Common/include/itkIsNumber.h b/Modules/Core/Common/include/itkIsNumber.h index 2e020c662a3..ad569463968 100644 --- a/Modules/Core/Common/include/itkIsNumber.h +++ b/Modules/Core/Common/include/itkIsNumber.h @@ -28,7 +28,7 @@ namespace itk namespace mpl { /** Tells whether a type is a number. - * \return \c TrueType for all kinds of numbers from \c short to `long long`, + * \c TrueType for all kinds of numbers from \c short to `long long`, * and from \c float to `long double`. * \ingroup MetaProgrammingLibrary * \ingroup ITKCommon diff --git a/Modules/Core/Common/include/itkIsSame.h b/Modules/Core/Common/include/itkIsSame.h index 93cf498df08..fe195927b4d 100644 --- a/Modules/Core/Common/include/itkIsSame.h +++ b/Modules/Core/Common/include/itkIsSame.h @@ -18,44 +18,7 @@ #ifndef itkIsSame_h #define itkIsSame_h -#include "itkMacro.h" - -#if !defined(ITK_LEGACY_REMOVE) - -# include "itkMetaProgrammingLibrary.h" - -namespace itk -{ -/// \cond HIDE_META_PROGRAMMING -namespace mpl -{ - -/** Tells whether two types are identical. - * \ingroup MetaProgrammingLibrary - * \ingroup ITKCommon - */ -template -struct IsSame : public FalseType -{}; - -/// \cond SPECIALIZATION_IMPLEMENTATION -template -struct IsSame : public TrueType -{}; -/// \endcond - -} // end namespace mpl - -// itk::IsSame have move to itk::mpl -// Expect them to be deprecated. -using mpl::IsSame; - -/// \endcond - -} // end namespace itk - -#else // ITK_LEGACY_REMOVE -# error Use C++ 11 std::is_same directly -#endif +// This file is no longer needed, C++11 provides support directly +#error Use C++ 11 std::is_same directly #endif // itkIsSame_h diff --git a/Modules/Core/Common/include/itkKernelFunctionBase.h b/Modules/Core/Common/include/itkKernelFunctionBase.h index 7ea9fbc921e..87b91e2c736 100644 --- a/Modules/Core/Common/include/itkKernelFunctionBase.h +++ b/Modules/Core/Common/include/itkKernelFunctionBase.h @@ -31,10 +31,7 @@ namespace itk * This class encapsulates the smoothing kernel used for statistical density * estimation and nonparametric regression. The basic idea of the kernel * approach is to weight observations by a smooth function (the kernel) - * to created a smoothed approximation. - * - * Reference: - * Silverman, B. W. (1986) Density Estimation. London: Chapman and Hall. + * to create a smoothed approximation \cite silverman1986. * * \ingroup Functions * \ingroup ITKCommon @@ -58,11 +55,7 @@ class ITK_TEMPLATE_EXPORT KernelFunctionBase : public FunctionBase)); - // End concept checking -#endif protected: KernelFunctionBase() = default; diff --git a/Modules/Core/Common/include/itkLaplacianOperator.h b/Modules/Core/Common/include/itkLaplacianOperator.h index ab3746c8efa..343306331ce 100644 --- a/Modules/Core/Common/include/itkLaplacianOperator.h +++ b/Modules/Core/Common/include/itkLaplacianOperator.h @@ -99,10 +99,11 @@ class ITK_TEMPLATE_EXPORT LaplacianOperator : public NeighborhoodOperator void LaplacianOperator::CreateOperator() { - CoefficientVector coefficients; - - coefficients = this->GenerateCoefficients(); + const CoefficientVector coefficients = this->GenerateCoefficients(); this->Fill(coefficients); } @@ -47,13 +45,13 @@ template void LaplacianOperator::Fill(const CoefficientVector & coeff) { - typename Superclass::CoefficientVector::const_iterator it; + const std::slice temp_slice(0, coeff.size(), 1); typename Self::SliceIteratorType data(this, temp_slice); - it = coeff.begin(); + typename Superclass::CoefficientVector::const_iterator it = coeff.begin(); // Copy the coefficients into the neighborhood for (data = data.Begin(); data < data.End(); ++data, ++it) @@ -66,24 +64,20 @@ template auto LaplacianOperator::GenerateCoefficients() -> CoefficientVector { - unsigned int i, w; - // Here we set the radius to 1's, here the // operator is 3x3 for 2D, 3x3x3 for 3D. - SizeType r; - - r.Fill(1); + constexpr auto r = SizeType::Filled(1); this->SetRadius(r); // Create a vector of the correct size to hold the coefficients. - w = this->Size(); - CoefficientVector coeffP(w); + const unsigned int w = this->Size(); + CoefficientVector coeffP(w); // Set the coefficients double sum = 0.0; - for (i = 0; i < 2 * VDimension; i += 2) + for (unsigned int i = 0; i < 2 * VDimension; i += 2) { - OffsetValueType stride = this->GetStride(i / 2); + const OffsetValueType stride = this->GetStride(i / 2); const double hsq = m_DerivativeScalings[i / 2] * m_DerivativeScalings[i / 2]; coeffP[w / 2 - stride] = coeffP[w / 2 + stride] = hsq; diff --git a/Modules/Core/Common/include/itkLightObject.h b/Modules/Core/Common/include/itkLightObject.h index 6fc299eec69..a2a70dcd47f 100644 --- a/Modules/Core/Common/include/itkLightObject.h +++ b/Modules/Core/Common/include/itkLightObject.h @@ -94,9 +94,11 @@ class ITKCommon_EXPORT LightObject #ifdef _WIN32 /** Used to avoid dll boundary problems. */ - void * operator new(size_t); + void * + operator new(size_t); - void * operator new[](size_t); + void * + operator new[](size_t); void operator delete(void *); diff --git a/Modules/Core/Common/include/itkLightProcessObject.h b/Modules/Core/Common/include/itkLightProcessObject.h index cb4dd5969ef..e143fc848cf 100644 --- a/Modules/Core/Common/include/itkLightProcessObject.h +++ b/Modules/Core/Common/include/itkLightProcessObject.h @@ -100,13 +100,15 @@ class ITKCommon_EXPORT LightProcessObject : public Object /** Set the execution progress of a process object. The progress is * a floating number between (0,1), 0 meaning no progress; 1 meaning * the filter has completed execution. */ + /** @ITKStartGrouping */ itkSetClampMacro(Progress, float, 0.0f, 1.0f); - + /** @ITKEndGrouping */ /** Get the execution progress of a process object. The progress is * a floating number between (0,1), 0 meaning no progress; 1 meaning * the filter has completed execution. */ + /** @ITKStartGrouping */ itkGetConstReferenceMacro(Progress, float); - + /** @ITKEndGrouping */ /** Update the progress of the process object. If a ProgressMethod exists, * executes it. Then set the Progress ivar to amount. The parameter amount * should range between (0,1). */ diff --git a/Modules/Core/Common/include/itkLineCell.h b/Modules/Core/Common/include/itkLineCell.h index a3f160b3d38..f3d2ca3964b 100644 --- a/Modules/Core/Common/include/itkLineCell.h +++ b/Modules/Core/Common/include/itkLineCell.h @@ -32,11 +32,6 @@ namespace itk * * Template parameters for LineCell: * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. - * * \ingroup MeshObjects * \ingroup ITKCommon */ @@ -48,9 +43,10 @@ class ITK_TEMPLATE_EXPORT LineCell : public TCellInterface ITK_DISALLOW_COPY_AND_MOVE(LineCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(LineCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(LineCell); @@ -64,6 +60,7 @@ class ITK_TEMPLATE_EXPORT LineCell : public TCellInterface static constexpr unsigned int CellDimension = 1; /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -71,7 +68,7 @@ class ITK_TEMPLATE_EXPORT LineCell : public TCellInterface } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ unsigned int GetDimension() const override; diff --git a/Modules/Core/Common/include/itkLineConstIterator.hxx b/Modules/Core/Common/include/itkLineConstIterator.hxx index fbb72d89749..29e878d8660 100644 --- a/Modules/Core/Common/include/itkLineConstIterator.hxx +++ b/Modules/Core/Common/include/itkLineConstIterator.hxx @@ -42,7 +42,7 @@ LineConstIterator::LineConstIterator(const ImageType * imagePtr, unsigned int maxDistanceDimension = 0; for (unsigned int i = 0; i < TImage::ImageDimension; ++i) { - IndexValueType distance = itk::Math::abs(difference[i]); + const IndexValueType distance = itk::Math::abs(difference[i]); if (distance > maxDistance) { maxDistance = distance; diff --git a/Modules/Core/Common/include/itkLoggerBase.h b/Modules/Core/Common/include/itkLoggerBase.h index 2f3939b4b1e..ab11e2fec6d 100644 --- a/Modules/Core/Common/include/itkLoggerBase.h +++ b/Modules/Core/Common/include/itkLoggerBase.h @@ -35,7 +35,7 @@ namespace itk class LoggerBaseEnums { public: - /** \class PriorityLevel + /** * \ingroup ITKCommon * Definition of types of messages. These codes will be used to regulate * the level of detail of messages reported to the final outputs @@ -51,7 +51,7 @@ class LoggerBaseEnums NOTSET }; - /** \class TimeStampFormat + /** * \ingroup ITKCommon * Select the type of format for reporting time stamps */ enum class TimeStampFormat : uint8_t @@ -124,9 +124,10 @@ class ITKCommon_EXPORT LoggerBase : public Object * \sa SetHumanReadableFormat() * */ + /** @ITKStartGrouping */ itkSetEnumMacro(TimeStampFormat, TimeStampFormatEnum); itkGetConstReferenceMacro(TimeStampFormat, TimeStampFormatEnum); - + /** @ITKEndGrouping */ /** Set/Get the specific text format to use when the time stamp format type * is set to HUMANREADABLE. For a description of the acceptable formats * please look at the man page of the strftime() method. The default is set @@ -135,12 +136,13 @@ class ITKCommon_EXPORT LoggerBase : public Object * \sa SetTimeStampFormat * */ + /** @ITKStartGrouping */ itkSetStringMacro(HumanReadableFormat); itkGetStringMacro(HumanReadableFormat); - + /** @ITKEndGrouping */ /** Provides a default formatted log entry */ virtual std::string - BuildFormattedEntry(PriorityLevelEnum level, std::string const & content); + BuildFormattedEntry(PriorityLevelEnum level, const std::string & content); /** 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 @@ -177,41 +179,41 @@ class ITKCommon_EXPORT LoggerBase : public Object AddLogOutput(OutputType * output); virtual void - Write(PriorityLevelEnum level, std::string const & content); + Write(PriorityLevelEnum level, const std::string & content); /** Helper methods */ void - Debug(std::string const & message) + Debug(const std::string & message) { this->Write(LoggerBase::PriorityLevelEnum::DEBUG, message); } void - Info(std::string const & message) + Info(const std::string & message) { this->Write(LoggerBase::PriorityLevelEnum::INFO, message); } void - Warning(std::string const & message) + Warning(const std::string & message) { this->Write(LoggerBase::PriorityLevelEnum::WARNING, message); } void - Critical(std::string const & message) + Critical(const std::string & message) { this->Write(LoggerBase::PriorityLevelEnum::CRITICAL, message); } void - Error(std::string const & message) + Error(const std::string & message) { this->Write(LoggerBase::PriorityLevelEnum::CRITICAL, message); } void - Fatal(std::string const & message) + Fatal(const std::string & message) { this->Write(LoggerBase::PriorityLevelEnum::FATAL, message); } diff --git a/Modules/Core/Common/include/itkLoggerManager.h b/Modules/Core/Common/include/itkLoggerManager.h index ef4a32ee007..2fe1a3bc09b 100644 --- a/Modules/Core/Common/include/itkLoggerManager.h +++ b/Modules/Core/Common/include/itkLoggerManager.h @@ -91,7 +91,7 @@ class ITKCommon_EXPORT LoggerManager : public Object AddLogOutput(OutputType * output); void - Write(PriorityLevelEnum level, std::string const & content); + Write(PriorityLevelEnum level, const std::string & content); void Flush(); diff --git a/Modules/Core/Common/include/itkLoggerThreadWrapper.h b/Modules/Core/Common/include/itkLoggerThreadWrapper.h index ec95dbd7c4d..1e3ede5bfe9 100644 --- a/Modules/Core/Common/include/itkLoggerThreadWrapper.h +++ b/Modules/Core/Common/include/itkLoggerThreadWrapper.h @@ -37,7 +37,7 @@ namespace itk class LoggerThreadWrapperEnums { public: - /** \class Operation + /** * \ingroup ITKCommon * Definition of types of operations for LoggerThreadWrapper. */ @@ -129,7 +129,7 @@ class ITK_TEMPLATE_EXPORT LoggerThreadWrapper : public SimpleLoggerType AddLogOutput(OutputType * output) override; void - Write(PriorityLevelEnum level, std::string const & content) override; + Write(PriorityLevelEnum level, const std::string & content) override; void Flush() override; diff --git a/Modules/Core/Common/include/itkLoggerThreadWrapper.hxx b/Modules/Core/Common/include/itkLoggerThreadWrapper.hxx index 608f6a05f43..c534de7ec96 100644 --- a/Modules/Core/Common/include/itkLoggerThreadWrapper.hxx +++ b/Modules/Core/Common/include/itkLoggerThreadWrapper.hxx @@ -43,7 +43,7 @@ typename SimpleLoggerType::PriorityLevelEnum LoggerThreadWrapper::GetPriorityLevel() const { const std::lock_guard lockGuard(m_Mutex); - PriorityLevelEnum level = this->m_PriorityLevel; + const PriorityLevelEnum level = this->m_PriorityLevel; return level; } @@ -62,7 +62,7 @@ typename SimpleLoggerType::PriorityLevelEnum LoggerThreadWrapper::GetLevelForFlushing() const { const std::lock_guard lockGuard(m_Mutex); - PriorityLevelEnum level = this->m_LevelForFlushing; + const PriorityLevelEnum level = this->m_LevelForFlushing; return level; } @@ -79,7 +79,7 @@ auto LoggerThreadWrapper::GetDelay() const -> DelayType { const std::lock_guard lockGuard(m_Mutex); - DelayType delay = this->m_Delay; + const DelayType delay = this->m_Delay; return delay; } @@ -95,7 +95,7 @@ LoggerThreadWrapper::AddLogOutput(OutputType * output) template void -LoggerThreadWrapper::Write(PriorityLevelEnum level, std::string const & content) +LoggerThreadWrapper::Write(PriorityLevelEnum level, const std::string & content) { const std::lock_guard lockGuard(m_Mutex); if (this->m_PriorityLevel >= level) diff --git a/Modules/Core/Common/include/itkMacro.h b/Modules/Core/Common/include/itkMacro.h index d5e590248b3..4f1dc8702e3 100644 --- a/Modules/Core/Common/include/itkMacro.h +++ b/Modules/Core/Common/include/itkMacro.h @@ -68,29 +68,28 @@ namespace itk #define itkNotUsed(x) // clang-format off - /** The `static_assert(true, "")` idiom is commonly employed for * C++11 or greater to ensure that it is compile-time only * check that can not be part of the binary file. - * This allows a macro to be used anywhere that a statement - * is expected, and to enforce consistent use of ; after - * a macro. The static_assert is a constexpr that can be used - * in places where raw statements (i.e. 'do{} while(0)') are + * + * The ITK_NOOP_STATEMENT idiom allows a macro to be used anywhere + * that a statement is expected, and to enforce consistent use of + * ';' after a macro. The static_assert is a constexpr that can be + * used in places where raw statements (i.e. 'do{} while(0)') are * not allowed (i.e. after class member function definitions). * */ #define ITK_NOOP_STATEMENT static_assert(true, "") - -#if defined(ITK_FUTURE_LEGACY_REMOVE) - -# define ITK_MACROEND_NOOP_STATEMENT ITK_NOOP_STATEMENT -#else -/* NOTE: The ITK_MACROEND_NOOP_STATEMENT must be defined to nothing - * in order to maintain backwards compatibility with earlier macro - * uses that may or may not have ';' after the macro is used. */ -/* Purposefully empty */ -# define ITK_MACROEND_NOOP_STATEMENT -#endif +/* NOTE: The ITK_MACROEND_NOOP_STATEMENT is used at the end + * of ITK supported macros to ensure that when the macro + * is used in the code base that the line must have ';' after + * the macro is used. This makes formatting visually similar + * to functions, and greatly improves the clang-format + * behaviors for indentation. This also assists + * modern IDE's and removes 1000's of warnings about + * unused statements or unnecessary ';' when macros are + * used. */ +#define ITK_MACROEND_NOOP_STATEMENT ITK_NOOP_STATEMENT // clang-format on // Define ITK_PRAGMA macro. @@ -109,20 +108,25 @@ namespace itk # define ITK_GCC_PRAGMA_POP ITK_PRAGMA(GCC diagnostic pop) # define ITK_GCC_SUPPRESS_Wfloat_equal ITK_PRAGMA(GCC diagnostic ignored "-Wfloat-equal") # define ITK_GCC_SUPPRESS_Wformat_nonliteral ITK_PRAGMA(GCC diagnostic ignored "-Wformat-nonliteral") +# define ITK_GCC_SUPPRESS_Warray_bounds ITK_PRAGMA(GCC diagnostic ignored "-Warray-bounds") #else # define ITK_GCC_PRAGMA_PUSH # define ITK_GCC_PRAGMA_POP # define ITK_GCC_SUPPRESS_Wfloat_equal # define ITK_GCC_SUPPRESS_Wformat_nonliteral +# define ITK_GCC_SUPPRESS_Warray_bounds #endif // For Clang only (and not GCC): #if defined(__clang__) && defined(__has_warning) # define ITK_CLANG_PRAGMA_PUSH ITK_PRAGMA(clang diagnostic push) # define ITK_CLANG_PRAGMA_POP ITK_PRAGMA(clang diagnostic pop) +# define ITK_CLANG_SUPPRESS_Wzero_as_null_pointer_constant \ + ITK_PRAGMA(clang diagnostic ignored "-Wzero-as-null-pointer-constant") #else # define ITK_CLANG_PRAGMA_PUSH # define ITK_CLANG_PRAGMA_POP +# define ITK_CLANG_SUPPRESS_Wzero_as_null_pointer_constant #endif // These were not intended as public API, but some code was nevertheless using them. @@ -172,38 +176,38 @@ namespace itk * MSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 Version 16.0) */ #if defined(_MSC_VER) && (_MSC_VER < 1920) -# error "MSVC versions before Visual Studio 2019 are not supported under ITKv5.4" +# error "MSVC versions before Visual Studio 2019 are not supported" #endif #if defined(__SUNPRO_CC) && (__SUNPRO_CC < 0x5140) -# error "SUNPro C++ < 5.14.0 is not supported under ITKv5 and above" +# error "SUNPro C++ < 5.14.0 is not supported" #endif #if defined(__CYGWIN__) -# error "The Cygwin compiler is not supported in ITKv4 and above" +# error "The Cygwin compiler is not supported" #endif #if defined(__BORLANDC__) -# error "The Borland C compiler is not supported in ITKv4 and above" +# error "The Borland C compiler is not supported" #endif #if defined(__MWERKS__) -# error "The MetroWerks compiler is not supported in ITKv4 and above" +# error "The MetroWerks compiler is not supported" #endif #if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && (__GNUC__ < 7) -# error "GCC < 7 is not supported under ITKv5.4" +# error "GCC < 7 is not supported" #endif #if defined(__sgi) // This is true for IRIX 6.5.18m with MIPSPro 7.3.1.3m. // TODO: At some future point, it may be necessary to // define a minimum __sgi version that will work. -# error "The SGI compiler is not supported under ITKv4 and above" +# error "The SGI compiler is not supported" #endif #if defined(__APPLE__) # if defined(__clang__) && (__cplusplus < 201703L) -# error "Apple LLVM compiling with a standard less than C++17 is not supported under ITKv5.4" +# error "Apple LLVM compiling with a standard less than C++17 is not supported" # endif #elif defined(__clang__) && (__clang_major__ < 5) -# error "Clang < 5 is not supported under ITKv5.4" +# error "Clang < 5 is not supported" #endif #if defined(__INTEL_COMPILER) && (__INTEL_COMPILER < 1910) -# error "Intel C++ < 19.1 is not supported under ITKv5.4" +# error "Intel C++ < 19.1 is not supported4" #endif // Setup symbol exports @@ -250,41 +254,6 @@ namespace itk #endif -//-*-*-* -// The following deprecations should be removed in ITKV6 and later -// NOTE DEPRECATED should be ITK_NOEXCEPT -#define ITK_NOEXCEPT_OR_THROW error "Replace ITK_NOEXCEPT_OR_THROW with ITK_NOEXCEPT" -// NOTE DEPRECATED! should be ITK_COMPILER_CXX_STATIC_ASSERT -#if !defined(ITK_LEGACY_REMOVE) -# define ITK_DELETE_FUNCTION = delete -#else -# define ITK_DELETE_FUNCTION error "Replace ITK_DELETE_FUNCTION with = delete" -#endif -//-*-*-* - -// DEPRECATED: These macros are left here for compatibility with remote modules. -// Once they have been removed from all known remote modules, this code should -// be removed. -#if defined(ITK_FUTURE_LEGACY_REMOVE) -# define ITK_CONSTEXPR_FUNC "Replace ITK_CONSTEXPR_FUNC with constexpr" -# define ITK_CONSTEXPR_VAR "Replace ITK_CONSTEXPR_VAR with constexpr" -/** Exposes enum value as an int*/ -# define itkExposeEnumValue(name) static_cast(name) -// Future remove# define itkExposeEnumValue(name) "Replace type of " # name " with proper enumeration instead of -// integer." -#else -# define ITK_CONSTEXPR_FUNC constexpr -# define ITK_CONSTEXPR_VAR constexpr -/** Exposes enum value as an int*/ -# define itkExposeEnumValue(name) static_cast(name) -#endif - -#if !defined(ITK_FUTURE_LEGACY_REMOVE) -# define ITK_FALLTHROUGH [[fallthrough]] -#else -# define ITK_FALLTHROUGH static_assert(false, "ERROR: ITK_FALLTHROUGH must be replaced with [[fallthrough]]") -#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 @@ -305,12 +274,13 @@ namespace itk * Break the methods into itkSimpleNewMacro and itkCreateAnotherMacro * so we can selectively overload CreateAnother() without having to * provide a definition for New(). */ +/** @ITKStartGrouping */ #define itkNewMacro(x) \ itkSimpleNewMacro(x); \ itkCreateAnotherMacro(x); \ itkCloneMacro(x); \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ #define itkSimpleNewMacro(x) \ static Pointer New() \ { \ @@ -339,14 +309,15 @@ namespace itk /** Define an object creation method throwing an exception if the object * is not created through the object factory, for use in base classes that * do not fully implement a backend. */ +/** @ITKStartGrouping */ #define itkFactoryOnlyNewMacro(x) \ itkSimpleFactoryOnlyNewMacro(x); \ itkCreateAnotherMacro(x); \ itkCloneMacro(x); \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ #define itkSimpleFactoryOnlyNewMacro(x) \ - static auto New()->Pointer \ + static auto New() -> Pointer \ { \ Pointer smartPtr = ::itk::ObjectFactory::Create(); \ if (smartPtr == nullptr) \ @@ -371,17 +342,18 @@ namespace itk * UnRegister() on the rawPtr to compensate for LightObject's constructor * initializing an object's reference count to 1 (needed for proper * initialization of process objects and data objects cycles). */ +/** @ITKStartGrouping */ #define itkFactorylessNewMacro(x) \ static Pointer New() \ { \ - x * rawPtr = new x(); \ + auto * rawPtr = new x(); \ Pointer smartPtr = rawPtr; \ rawPtr->UnRegister(); \ return smartPtr; \ } \ itkCreateAnotherMacro(x); \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ // // A macro to disallow the copy constructor, copy assignment, // move constructor, and move assignment functions. @@ -397,7 +369,7 @@ namespace itk TypeName(TypeName &&) = delete; \ TypeName & operator=(TypeName &&) = delete -#if !defined(ITK_FUTURE_LEGACY_REMOVE) +#if !defined(ITK_LEGACY_REMOVE) # define ITK_DISALLOW_COPY_AND_ASSIGN(TypeName) ITK_DISALLOW_COPY_AND_MOVE(TypeName) #else # define ITK_DISALLOW_COPY_AND_ASSIGN(TypeName) \ @@ -412,12 +384,13 @@ user-declared destructor [-Wdeprecated]" (Mac10.13-AppleClang) - "warning C5267: definition of implicit copy constructor for '' is deprecated because it has a user-provided destructor." (Visual Studio 2022/MSVC) Intended to be used in the public section of a class. */ +/** @ITKStartGrouping */ #define ITK_DEFAULT_COPY_AND_MOVE(TypeName) \ TypeName(const TypeName &) = default; \ TypeName & operator=(const TypeName &) = default; \ TypeName(TypeName &&) = default; \ TypeName & operator=(TypeName &&) = default - +/** @ITKEndGrouping */ // When ITK_EXPERIMENTAL_CXX20_REWRITTEN_UNEQUAL_OPERATOR is defined, ITK uses // the ability for operator!= to be rewritten automatically in terms of @@ -490,6 +463,7 @@ namespace itk * OutputWindow::GetInstance()->DisplayText(); * This is to avoid Object \#include of OutputWindow * while OutputWindow \#includes Object. */ +/** @ITKStartGrouping */ extern ITKCommon_EXPORT void OutputWindowDisplayText(const char *); @@ -504,6 +478,7 @@ OutputWindowDisplayGenericOutputText(const char *); extern ITKCommon_EXPORT void OutputWindowDisplayDebugText(const char *); +/** @ITKEndGrouping */ } // end namespace itk @@ -512,12 +487,12 @@ OutputWindowDisplayDebugText(const char *); * also used to catch errors, etc. Requires that the caller implements * the GetDebug() method (see itk::Object). Example usage looks like: * itkDebugMacro("this is debug info" << this->SomeVariable); */ +/** @ITKStartGrouping */ #if defined(NDEBUG) # define itkDebugMacro(x) ITK_NOOP_STATEMENT # define itkDebugStatement(x) ITK_NOOP_STATEMENT #else # define itkDebugMacro(x) \ - do \ { \ using namespace ::itk::print_helper; /* for ostream << std::vector */ \ if (this->GetDebug() && ::itk::Object::GetGlobalWarningDisplay()) \ @@ -527,18 +502,17 @@ OutputWindowDisplayDebugText(const char *); << this->GetNameOfClass() << " (" << this << "): " x << "\n\n"; \ ::itk::OutputWindowDisplayDebugText(itkmsg.str().c_str()); \ } \ - } while (0) - + } \ + ITK_MACROEND_NOOP_STATEMENT // The itkDebugStatement is to be used to protect code that is only // used in the itkDebugMacro # define itkDebugStatement(x) x #endif - +/** @ITKEndGrouping */ /** This macro is used to print warning information (i.e., unusual circumstance * but not necessarily fatal.) Example usage looks like: * itkWarningMacro("this is warning info" << this->SomeVariable); */ #define itkWarningMacro(x) \ - do \ { \ if (::itk::Object::GetGlobalWarningDisplay()) \ { \ @@ -547,7 +521,9 @@ OutputWindowDisplayDebugText(const char *); << this->GetNameOfClass() << " (" << this << "): " x << "\n\n"; \ ::itk::OutputWindowDisplayWarningText(itkmsg.str().c_str()); \ } \ - } while (0) + } \ + ITK_MACROEND_NOOP_STATEMENT + #define itkWarningStatement(x) x @@ -657,7 +633,7 @@ OutputWindowDisplayDebugText(const char *); // declared in their class. Example usage: // // // \deprecated Replaced by MyOtherMethod() as of ITK 2.0. -// itkLegacyMacro(void MyMethod()); +// itkLegacyMacro(void MyMethod();) // // See below for what to do for the method definition. #if defined(ITK_LEGACY_REMOVE) @@ -665,10 +641,10 @@ OutputWindowDisplayDebugText(const char *); #else # if defined(ITK_LEGACY_SILENT) || defined(ITK_LEGACY_TEST) // Provide legacy methods with no warnings. -# define itkLegacyMacro(method) method +# define itkLegacyMacro(method) method /* no ';' */ # else // Request compile-time warnings for uses of deprecated methods. -# define itkLegacyMacro(method) [[deprecated]] method +# define itkLegacyMacro(method) [[deprecated]] method /* no ';' */ # endif #endif @@ -728,7 +704,7 @@ OutputWindowDisplayDebugText(const char *); struct newtype : public oldtype \ { \ char _StructPadding[mincachesize - (sizeof(oldtype) % mincachesize)]; \ - }; + } // // itkAlignedTypedef is a macro which creates a new type to make a @@ -788,7 +764,8 @@ compilers. for (unsigned int i = 0; i < NumberOfIterations; ++i) \ { \ DestinationArray[i] = static_cast(SourceArray[i]); \ - } + } \ + ITK_MACROEND_NOOP_STATEMENT //-------------------------------------------------------------------------------- // Macro that generates an unrolled for loop for rounding and assigning @@ -804,7 +781,8 @@ compilers. for (unsigned int i = 0; i < NumberOfIterations; ++i) \ { \ DestinationArray[i] = ::itk::Math::Round(SourceArray[i]); \ - } + } \ + ITK_MACROEND_NOOP_STATEMENT // end of Template Meta Programming helper macros @@ -867,6 +845,7 @@ compilers. #endif /** Set an input. This defines the Set"name"() method */ +/** @ITKStartGrouping */ #define itkSetInputMacro(name, type) \ virtual void Set##name(const type * _arg) \ { \ @@ -878,8 +857,9 @@ compilers. } \ } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Get an input. This defines the Get"name"() method */ +/** @ITKStartGrouping */ #define itkGetInputMacro(name, type) \ virtual const type * Get##name() const \ { \ @@ -887,11 +867,12 @@ compilers. return itkDynamicCastInDebugMode(this->ProcessObject::GetInput(#name)); \ } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ // clang-format off /** Set a decorated input. This defines the Set"name"() and a Set"name"Input() method */ +/** @ITKStartGrouping */ #define itkSetDecoratedInputMacro(name, type) \ - virtual void Set##name##Input(const SimpleDataObjectDecorator * _arg) \ + virtual void Set## name## Input(const SimpleDataObjectDecorator * _arg) \ { \ itkDebugMacro("setting input " #name " to " << _arg); \ if (_arg != itkDynamicCastInDebugMode *>(this->ProcessObject::GetInput(#name))) \ @@ -900,28 +881,29 @@ compilers. this->Modified(); \ } \ } \ - virtual void Set##name(const SimpleDataObjectDecorator * _arg) { this->Set##name##Input(_arg); } \ - virtual void Set##name(const type & _arg) \ + virtual void Set## name(const SimpleDataObjectDecorator * _arg) { this->Set## name## Input(_arg); } \ + virtual void Set## name(const type & _arg) \ { \ using DecoratorType = SimpleDataObjectDecorator; \ itkDebugMacro("setting input " #name " to " << _arg); \ const DecoratorType * oldInput = \ itkDynamicCastInDebugMode(this->ProcessObject::GetInput(#name)); \ - ITK_GCC_PRAGMA_PUSH \ - ITK_GCC_SUPPRESS_Wfloat_equal \ + ITK_GCC_PRAGMA_PUSH \ + ITK_GCC_SUPPRESS_Wfloat_equal \ if (oldInput && oldInput->Get() == _arg) \ { \ return; \ } \ - ITK_GCC_PRAGMA_POP \ + ITK_GCC_PRAGMA_POP \ auto newInput = DecoratorType::New(); \ newInput->Set(_arg); \ - this->Set##name##Input(newInput); \ + this->Set## name## Input(newInput); \ } \ ITK_MACROEND_NOOP_STATEMENT // clang-format on - +/** @ITKEndGrouping */ /** Set a decorated input. This defines the Set"name"() and Set"name"Input() method */ +/** @ITKStartGrouping */ #define itkGetDecoratedInputMacro(name, type) \ virtual const SimpleDataObjectDecorator * Get##name##Input() const \ { \ @@ -941,7 +923,7 @@ compilers. return input->Get(); \ } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Set a decorated input. This defines the Set"name"() and Set"name"Input() method * and Get"name" and Get"name"Input methods */ #define itkSetGetDecoratedInputMacro(name, type) \ @@ -952,6 +934,7 @@ compilers. * itk::DataObject. This defines the Set"name"() and Set"name"Input * methods. */ +/** @ITKStartGrouping */ #define itkSetDecoratedObjectInputMacro(name, type) \ virtual void Set##name##Input(const DataObjectDecorator * _arg) \ { \ @@ -977,11 +960,12 @@ compilers. this->Set##name##Input(newInput); \ } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Get a decorated input that derives from itk::Object, but not from * itk::DataObject. This defines the Get"name"() and Get"name"Input * methods. */ +/** @ITKStartGrouping */ #define itkGetDecoratedObjectInputMacro(name, type) \ virtual const DataObjectDecorator * Get##name##Input() const \ { \ @@ -1001,7 +985,7 @@ compilers. return input->Get(); \ } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Set a decorated input. This defines the Set"name"() and Set"name"Input() method * and Get"name" and Get"name"Input methods */ #define itkSetGetDecoratedObjectInputMacro(name, type) \ @@ -1011,44 +995,49 @@ compilers. /** Set built-in type or regular C++ type. Creates member Set"name"() (e.g., SetVisibility()); */ // clang-format off #define itkSetMacro(name, type) \ - virtual void Set##name(type _arg) \ + virtual void Set## name(type _arg) \ { \ itkDebugMacro("setting " #name " to " << _arg); \ - ITK_GCC_PRAGMA_PUSH \ - ITK_GCC_SUPPRESS_Wfloat_equal \ - if (this->m_##name != _arg) \ + ITK_GCC_PRAGMA_PUSH \ + ITK_GCC_SUPPRESS_Wfloat_equal \ + if (this->m_## name != _arg) \ { \ - this->m_##name = std::move(_arg); \ + this->m_## name = std::move(_arg); \ this->Modified(); \ } \ - ITK_GCC_PRAGMA_POP \ + ITK_GCC_PRAGMA_POP \ } \ ITK_MACROEND_NOOP_STATEMENT // clang-format on + /** Get built-in type. Creates member Get"name"() (e.g., GetVisibility()); */ +/** @ITKStartGrouping */ #define itkGetMacro(name, type) \ virtual type Get##name() { return this->m_##name; } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Get built-in type. Creates member Get"name"() (e.g., GetVisibility()); * This is the "const" form of the itkGetMacro. It should be used unless * the member can be changed through the "Get" access routine. */ +/** @ITKStartGrouping */ #define itkGetConstMacro(name, type) \ virtual type Get##name() const { return this->m_##name; } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Get built-in type. Creates member Get"name"() (e.g., GetVisibility()); * This is the "const" form of the itkGetMacro. It should be used unless * the member can be changed through the "Get" access routine. * This versions returns a const reference to the variable. */ +/** @ITKStartGrouping */ #define itkGetConstReferenceMacro(name, type) \ virtual const type & Get##name() const { return this->m_##name; } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Set built-in type. Creates member Set"name"() (e.g., SetVisibility()); * This should be used when the type is an enum. It is used to avoid warnings on * some compilers with non specified enum types passed to * itkDebugMacro. */ +/** @ITKStartGrouping */ #define itkSetEnumMacro(name, type) \ virtual void Set##name(const type _arg) \ { \ @@ -1060,18 +1049,20 @@ compilers. } \ } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Get built-in type. Creates member Get"name"() (e.g., GetVisibility()); * This should be use when the type is an enum. It is use to avoid warnings on * some compilers with non specified enum types passed to * itkDebugMacro. */ +/** @ITKStartGrouping */ #define itkGetEnumMacro(name, type) \ virtual type Get##name() const { return this->m_##name; } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Set character string. Creates member Set"name"() * (e.g., SetFilename(char *)). The macro assumes that * the class member (name) is declared a type std::string. */ +/** @ITKStartGrouping */ #define itkSetStringMacro(name) \ virtual void Set##name(const char * _arg) \ { \ @@ -1091,7 +1082,7 @@ compilers. } \ virtual void Set##name(const std::string & _arg) { this->Set##name(_arg.c_str()); } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Get character string. Creates member Get"name"() * (e.g., SetFilename(char *)). The macro assumes that @@ -1104,40 +1095,42 @@ compilers. /** Set built-in type where value is constrained between min/max limits. * Create member Set"name"() (e.q., SetRadius()). \#defines are * convenience for clamping open-ended values. */ +/** @ITKStartGrouping */ #define itkSetClampMacro(name, type, min, max) \ - virtual void Set##name(type _arg) \ + virtual void Set## name(type _arg) \ { \ const type temp_extrema = (_arg <= min ? min : (_arg >= max ? max : _arg)); \ itkDebugMacro("setting " << #name " to " << _arg); \ - ITK_GCC_PRAGMA_PUSH \ - ITK_GCC_SUPPRESS_Wfloat_equal \ - if (this->m_##name != temp_extrema) \ + ITK_GCC_PRAGMA_PUSH \ + ITK_GCC_SUPPRESS_Wfloat_equal \ + if (this->m_## name != temp_extrema) \ { \ - this->m_##name = temp_extrema; \ + this->m_## name = temp_extrema; \ this->Modified(); \ } \ - ITK_GCC_PRAGMA_POP \ + ITK_GCC_PRAGMA_POP \ } \ ITK_MACROEND_NOOP_STATEMENT // clang-format on - +/** @ITKEndGrouping */ // clang-format off /** Set pointer to object; uses Object reference counting methodology. * Creates method Set"name"() (e.g., SetPoints()). Note that using * smart pointers requires using raw pointers when setting input. */ +/** @ITKStartGrouping */ #define itkSetObjectMacro(name, type) \ - virtual void Set##name(type * _arg) \ + virtual void Set## name(type * _arg) \ { \ itkDebugMacro("setting " << #name " to " << _arg); \ - if (this->m_##name != _arg) \ + if (this->m_## name != _arg) \ { \ - this->m_##name = _arg; \ + this->m_## name = _arg; \ this->Modified(); \ } \ } \ ITK_MACROEND_NOOP_STATEMENT // clang-format on - +/** @ITKEndGrouping */ /** Get a raw pointer to an object. Creates the member * Get"name"() (e.g., GetPoints()). * NOTE: This function returns a non-const @@ -1178,7 +1171,8 @@ compilers. virtual type * Get##name() \ { \ purposeful_error("itkGetObjectMacro should be replaced with itkGetModifiableObjectMacro."); \ - } + } \ + ITK_MACROEND_NOOP_STATEMENT # define itkGetModifiableObjectMacro(name, type) \ virtual type * GetModifiable##name() { return this->m_##name.GetPointer(); } \ @@ -1187,6 +1181,7 @@ compilers. #else // defined ( ITK_FUTURE_LEGACY_REMOVE ) /** Get a raw pointer to an object. Creates the member * Get"name"() (e.g., GetPoints()). */ +/** @ITKStartGrouping */ # define itkGetObjectMacro(name, type) \ virtual type * Get##name() { return this->m_##name.GetPointer(); } \ ITK_MACROEND_NOOP_STATEMENT @@ -1194,6 +1189,7 @@ compilers. virtual type * GetModifiable##name() { return this->m_##name.GetPointer(); } \ itkGetConstObjectMacro(name, type); \ itkGetObjectMacro(name, type) +/** @ITKEndGrouping */ #endif // defined ( ITK_FUTURE_LEGACY_REMOVE ) // For backwards compatibility define ITK_EXPORT to nothing @@ -1209,6 +1205,7 @@ compilers. /** Set const pointer to object; uses Object reference counting methodology. * Creates method Set"name"() (e.g., SetPoints()). Note that using * smart pointers requires using raw pointers when setting input. */ +/** @ITKStartGrouping */ #define itkSetConstObjectMacro(name, type) \ virtual void Set##name(const type * _arg) \ { \ @@ -1220,43 +1217,86 @@ compilers. } \ } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Create members "name"On() and "name"Off() (e.g., DebugOn() DebugOff()). * Set method must be defined to use this macro. */ -#define itkBooleanMacro(name) \ - virtual void name##On() { this->Set##name(true); } \ - virtual void name##Off() { this->Set##name(false); } +/** @ITKStartGrouping */ +#define itkBooleanMacro(name) \ + virtual void name##On() { this->Set##name(true); } \ + virtual void name##Off() { this->Set##name(false); } \ + ITK_MACROEND_NOOP_STATEMENT +/** @ITKEndGrouping */ + +/** + * \brief A utility function to encapsulate a commonly used paradigm + * for filling one container with a value for Set##Name# Methods + * + * returns false if no values were changed. + * return true if any of the values are changed. + * \ingroup ITKCommon + */ +template +bool +ContainerFillWithCheck(MemberContainerType & m, const CopyFromValueType & c, const LoopEndType N) +{ + bool value_updated = false; + for (unsigned int i = 0; i < N; ++i) + { + ITK_GCC_PRAGMA_PUSH + ITK_GCC_SUPPRESS_Wfloat_equal + if (m[i] != c) + { + m[i] = c; + value_updated = true; + } + ITK_GCC_PRAGMA_POP + } + return value_updated; +} + +/** + * \brief A utility function to encapsulate a commonly used paradigm + * for copying one container to another inside of a "Set##Name# Methods + * + * returns false if no values were changed. + * return true if any of the values are changed. + * \ingroup ITKCommon + */ +template +bool +ContainerCopyWithCheck(MemberContainerType & m, const CopyFromContainerType & c, const LoopEndType N) +{ + bool value_updated = false; + for (LoopEndType i = 0; i < N; ++i) + { + ITK_GCC_PRAGMA_PUSH + ITK_GCC_SUPPRESS_Wfloat_equal + if (m[i] != c[i]) + { + m[i] = c[i]; + value_updated = true; + } + ITK_GCC_PRAGMA_POP + } + return value_updated; +} // clang-format off /** General set vector macro creates a single method that copies specified * number of values into object. * Examples: void SetColor(c,3) */ -#define itkSetVectorMacro(name, type, count) \ - virtual void Set##name(type data[]) \ - { \ - unsigned int i; \ - for (i = 0; i < count; ++i) \ - { \ - ITK_GCC_PRAGMA_PUSH \ - ITK_GCC_SUPPRESS_Wfloat_equal \ - if (data[i] != this->m_##name[i]) \ - { \ - break; \ - } \ - ITK_GCC_PRAGMA_POP \ - } \ - if (i < count) \ - { \ - this->Modified(); \ - for (i = 0; i < count; ++i) \ - { \ - this->m_##name[i] = data[i]; \ - } \ - } \ - } \ +/** @ITKStartGrouping */ +#define itkSetVectorMacro(name, type, count) \ + virtual void Set## name(type data[]) \ + { \ + if (ContainerCopyWithCheck( this->m_## name, data, count)) \ + { \ + this->Modified(); \ + } \ + } \ ITK_MACROEND_NOOP_STATEMENT // clang-format on - +/** @ITKEndGrouping */ /** Get vector macro. Returns pointer to type (i.e., array of type). * This is for efficiency. */ #define itkGetVectorMacro(name, type, count) \ @@ -1274,6 +1314,7 @@ compilers. * then without adding the `class` keyword. Useful when an export specifier * needs to be added between the `class` keyword and the class name. */ +/** @ITKStartGrouping */ #define itkGPUKernelMacro(kernel) \ kernel \ { \ @@ -1283,9 +1324,10 @@ compilers. ~kernel() = delete; \ static const char * GetOpenCLSource(); \ } - -#define itkGetOpenCLSourceFromKernelMacro(kernel) \ - static const char * GetOpenCLSource() { return kernel::GetOpenCLSource(); } +/** @ITKEndGrouping */ +#define itkGetOpenCLSourceFromKernelMacro(kernel) \ + static const char * GetOpenCLSource() { return kernel::GetOpenCLSource(); } \ + ITK_MACROEND_NOOP_STATEMENT // A useful macro in the PrintSelf method for printing member variables // which are pointers to object based on the LightObject class. @@ -1302,7 +1344,15 @@ compilers. ITK_MACROEND_NOOP_STATEMENT +// A useful macro in the PrintSelf method for printing boolean member +// variables. +#define itkPrintSelfBooleanMacro(name) \ + os << indent << #name << ": " << (this->m_##name ? "On" : "Off") << std::endl; \ + ITK_MACROEND_NOOP_STATEMENT + + /** Set a decorated output. This defines the Set"name"() and a Set"name"Output() method */ +/** @ITKStartGrouping */ #define itkSetDecoratedOutputMacro(name, type) \ virtual void Set##name##Output(const SimpleDataObjectDecorator * _arg) \ { \ @@ -1337,8 +1387,9 @@ compilers. } \ } \ ITK_MACROEND_NOOP_STATEMENT - +/** @ITKEndGrouping */ /** Set a decorated output. This defines the Get"name"() and Get"name"Output() method */ +/** @ITKStartGrouping */ #define itkGetDecoratedOutputMacro(name, type) \ virtual const SimpleDataObjectDecorator * Get##name##Output() const \ { \ @@ -1358,96 +1409,110 @@ compilers. return output->Get(); \ } \ ITK_MACROEND_NOOP_STATEMENT - - -/** Defines to provide compatibility with derived iterators. - * - * With ITKv5 several methods for Image Iterators have been - * devirtualized for performance reasons. These definitions may help - * provide legacy compatibility, or help detecting derived iterators - * relying on the virtual interface. Compatibility for derived - * classes can be achieved with defining ITKV4_COMPATIBILITY. Code - * should be migrated to no longer rely on the old virtual interface. - */ -#if defined(ITKV4_COMPATIBILITY) -# define ITK_ITERATOR_VIRTUAL virtual -# define ITK_ITERATOR_OVERRIDE override -# define ITK_ITERATOR_FINAL -#elif !defined(ITK_LEGACY_REMOVE) -# define ITK_ITERATOR_VIRTUAL virtual -# define ITK_ITERATOR_OVERRIDE override -# define ITK_ITERATOR_FINAL final +/** @ITKEndGrouping */ +// ITK_FUTURE_DEPRECATED is only for internal use, within the implementation of ITK. It allows triggering "deprecated" +// warnings when legacy support is removed, which warn that a specific feature may be removed in the future. +#if defined(ITK_LEGACY_REMOVE) && !defined(ITK_LEGACY_SILENT) +# define ITK_FUTURE_DEPRECATED(message) [[deprecated(message)]] #else -# define ITK_ITERATOR_VIRTUAL -# define ITK_ITERATOR_OVERRIDE -# define ITK_ITERATOR_FINAL +# define ITK_FUTURE_DEPRECATED(message) #endif -#if defined(ITKV4_COMPATIBILITY) -// A macro for methods which are const in ITKv5, but not in ITKv4 -# define ITKv5_CONST +#if __cplusplus >= 202002L +# define ITK_NODISCARD(message) [[nodiscard(message)]] #else -// A macro for methods which are const in ITKv5, but not in ITKv4 -# define ITKv5_CONST const +# define ITK_NODISCARD(message) [[nodiscard]] #endif -#define itkExceptionObject_h -#include "itkExceptionObject.h" -#undef itkExceptionObject_h +//-*-*-* -/** itkDynamicCastInDebugMode - * Use static_cast in Release builds, and dynamic_cast in Debug - * - * Note: this must come after: - * - * #include "itkExceptionObject.h" - */ -template -TTarget -itkDynamicCastInDebugMode(TSource x) -{ -#ifndef NDEBUG - if (x == nullptr) - { - return nullptr; - } - TTarget rval = dynamic_cast(x); - if (rval == nullptr) - { - itkGenericExceptionMacro("Failed dynamic cast to " << typeid(TTarget).name() - << " object type = " << x->GetNameOfClass()); - } - return rval; -#else - return static_cast(x); -#endif -} +#if defined(ITK_LEGACY_REMOVE) +# define itkExposeEnumValue(name) \ + static_assert(false, "ERROR: Replace static_cast(name) with with proper enumeration instead of integer") + +# define ITK_NOEXCEPT_OR_THROW static_assert(false, "Replace ITK_NOEXCEPT_OR_THROW with ITK_NOEXCEPT") + +# define ITK_DELETE_FUNCTION static_assert(false, "ERROR: ITK_DELETE_FUNCTION must be replaced with `= delete`" +# define ITK_CONSTEXPR_FUNC static_assert(false, "ERROR: ITK_CONSTEXPR_FUNC must be replaced with 'constexpr'") +# define ITK_CONSTEXPR_VAR static_assert(false, "ERROR: ITK_CONSTEXPR_VAR must be replaced with 'constexpr'") + +# define ITK_FALLTHROUGH static_assert(false, "ERROR: ITK_FALLTHROUGH must be replaced with '[[fallthrough]]'") + +// Defines which used to be in itk_compiler_detection.h +# define ITK_ALIGNAS static_assert(false, "ERROR: ITK_ALIGNAS must be replaced with 'alignas'") +# define ITK_ALIGNOF static_assert(false, "ERROR: ITK_ALIGNOF must be replaced with 'alignof'") +# define ITK_DEPRECATED static_assert(false, "ERROR: ITK_DEPRECATED must be replaced with '[[deprecated]]'") +# define ITK_DEPRECATED_MSG \ + static_assert(false, "ERROR: ITK_DEPRECATED_MSG must be replaced with '[[deprecated(MSG)]]'") +# define ITK_CONSTEXPR static_assert(false, "ERROR: ITK_CONSTEXPR must be replaced with 'constexpr'") +# define ITK_DELETED_FUNCTION static_assert(false, "ERROR: ITK_DELETED_FUNCTION must be replaced with '= delete'") +# define ITK_EXTERN_TEMPLATE static_assert(false, "ERROR: ITK_EXTERN_TEMPLATE must be replaced with 'extern'") +# define ITK_FINAL static_assert(false, "ERROR: ITK_FINAL must be replaced with 'final'") +# define ITK_NOEXCEPT static_assert(false, "ERROR: ITK_NOEXCEPT must be replaced with 'noexcept'") +# define ITK_NOEXCEPT_EXPR static_assert(false, "ERROR: ITK_NOEXCEPT_EXPR must be replaced with 'noexcept'") +# define ITK_NULLPTR static_assert(false, "ERROR: ITK_NULLPTR must be replaced with 'nullptr'") +# define ITK_OVERRIDE static_assert(false, "ERROR: ITK_OVERRIDE must be replaced with 'override'") +# define ITK_STATIC_ASSERT static_assert(false, "ERROR: ITK_STATIC_ASSERT must be replaced with 'static_assert'") +# define ITK_STATIC_ASSERT_MSG \ + static_assert(false, "ERROR: ITK_STATIC_ASSERT_MSG must be replaced with 'static_assert'") +# define ITK_THREAD_LOCAL static_assert(false, "ERROR: ITK_THREAD_LOCAL must be replaced with 'thread_local'") + +// A macro for methods which are const in ITKv5 and ITKv6 require const for functions +# define ITKv5_CONST static_assert(false, "ERROR: ITKv5_CONST must be replaced with 'const'") + +# define ITK_ITERATOR_VIRTUAL static_assert(false, "ERROR: ITK_ITERATOR_VIRTUAL must be removed'") +# define ITK_ITERATOR_OVERRIDE static_assert(false, "ERROR: ITK_ITERATOR_OVERRIDE must be removed") +# define ITK_ITERATOR_FINAL static_assert(false, "ERROR: ITK_ITERATOR_FINAL must be removed") -#ifdef ITK_LEGACY_REMOVE -# if __cplusplus >= 202002L -# define ITK_NODISCARD(message) [[nodiscard(message)]] -# else -# define ITK_NODISCARD(message) [[nodiscard]] -# endif #else -# define ITK_NODISCARD(message) -#endif +// DEPRECATED: These macros are left here for compatibility with remote modules. +// Once they have been removed from all known remote modules, this code should +// be removed. + +// Future remove `#define itkExposeEnumValue(name)` +// "Replace type of `name` with proper enumeration instead of integer. +# define itkExposeEnumValue(name) static_cast(name) + + +# define ITK_NOEXCEPT_OR_THROW ITK_NOEXCEPT + +# define ITK_FALLTHROUGH [[fallthrough]] + +# define ITK_DELETE_FUNCTION = delete + +# define ITK_CONSTEXPR_FUNC constexpr +# define ITK_CONSTEXPR_VAR constexpr // Defines which used to be in itk_compiler_detection.h -#define ITK_ALIGNAS(X) alignas(X) -#define ITK_ALIGNOF(X) alignof(X) -#define ITK_DEPRECATED [[deprecated]] -#define ITK_DEPRECATED_MSG(MSG) [[deprecated(MSG)]] -#define ITK_CONSTEXPR constexpr -#define ITK_DELETED_FUNCTION = delete -#define ITK_EXTERN_TEMPLATE extern -#define ITK_FINAL final -#define ITK_NOEXCEPT noexcept -#define ITK_NOEXCEPT_EXPR(X) noexcept(X) -#define ITK_NULLPTR nullptr -#define ITK_OVERRIDE override -#define ITK_STATIC_ASSERT(X) static_assert(X, #X) -#define ITK_STATIC_ASSERT_MSG(X, MSG) static_assert(X, MSG) -#define ITK_THREAD_LOCAL thread_local - -#endif // end of itkMacro.h +# define ITK_ALIGNAS(X) alignas(X) +# define ITK_ALIGNOF(X) alignof(X) +# define ITK_DEPRECATED [[deprecated]] +# define ITK_DEPRECATED_MSG(MSG) [[deprecated(MSG)]] +# define ITK_CONSTEXPR constexpr +# define ITK_DELETED_FUNCTION = delete +# define ITK_EXTERN_TEMPLATE extern +# define ITK_FINAL final +# define ITK_NOEXCEPT noexcept +# define ITK_NOEXCEPT_EXPR(X) noexcept(X) +# define ITK_NULLPTR nullptr +# define ITK_OVERRIDE override +# define ITK_STATIC_ASSERT(X) static_assert(X, #X) +# define ITK_STATIC_ASSERT_MSG(X, MSG) static_assert(X, MSG) +# define ITK_THREAD_LOCAL thread_local + +// A macro for methods which are const in after ITKv4 +# define ITKv5_CONST const + +# define ITK_ITERATOR_VIRTUAL /*purposefully empty for ITKv6, iterators are not virtual for performance reasons*/ +# define ITK_ITERATOR_OVERRIDE /*purposefully empty for ITKv6, iterators are not virtual for performance reasons*/ +# define ITK_ITERATOR_FINAL /*purposefully empty for ITKv6, iterators are not virtual for performance reasons*/ +#endif + +#define allow_inclusion_of_itkExceptionObject_h +// Must include itkExceptionObject.h at the end of the file +// because it depends on the macros defined above +#include "itkExceptionObject.h" + + +#undef allow_inclusion_of_itkExceptionObject_h +#endif // itkMacro_h diff --git a/Modules/Core/Common/include/itkMapContainer.h b/Modules/Core/Common/include/itkMapContainer.h index 9a522117bdc..1d550ef0ac6 100644 --- a/Modules/Core/Common/include/itkMapContainer.h +++ b/Modules/Core/Common/include/itkMapContainer.h @@ -73,6 +73,7 @@ class ITK_TEMPLATE_EXPORT MapContainer /** Provide pass-through constructors corresponding to all the STL * map constructors. These are for internal use only since this is also * an Object which must be constructed through the "New()" routine. */ + /** @ITKStartGrouping */ MapContainer() : MapType() {} @@ -88,7 +89,7 @@ class ITK_TEMPLATE_EXPORT MapContainer MapContainer(TInputIterator first, TInputIterator last, const MapKeyCompareType & comp) : MapType(first, last, comp) {} - + /** @ITKEndGrouping */ /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -181,8 +182,16 @@ class ITK_TEMPLATE_EXPORT MapContainer : m_Iter(i) {} - Iterator & operator*() { return *this; } - Iterator * operator->() { return this; } + Iterator & + operator*() + { + return *this; + } + Iterator * + operator->() + { + return this; + } Iterator & operator++() { @@ -266,8 +275,16 @@ class ITK_TEMPLATE_EXPORT MapContainer : m_Iter(r.m_Iter) {} - ConstIterator & operator*() { return *this; } - ConstIterator * operator->() { return this; } + ConstIterator & + operator*() + { + return *this; + } + ConstIterator * + operator->() + { + return this; + } ConstIterator & operator++() { @@ -445,7 +462,8 @@ class ITK_TEMPLATE_EXPORT MapContainer * memory usage. */ void - Squeeze(); + Squeeze() + {} /** * Tell the container to release any memory it may have allocated and diff --git a/Modules/Core/Common/include/itkMapContainer.hxx b/Modules/Core/Common/include/itkMapContainer.hxx index 1792e7555d8..e527e70e82e 100644 --- a/Modules/Core/Common/include/itkMapContainer.hxx +++ b/Modules/Core/Common/include/itkMapContainer.hxx @@ -226,16 +226,6 @@ MapContainer::Reserve(ElementIdentifier sz) } } -/** - * Tell the container to try to minimize its memory usage for storage of - * the current number of elements. This is NOT guaranteed to decrease - * memory usage. - */ -template -void -MapContainer::Squeeze() -{} - /** * Tell the container to release any memory it may have allocated and * return itself to its initial state. diff --git a/Modules/Core/Common/include/itkMath.h b/Modules/Core/Common/include/itkMath.h index c311597d815..7f396de8ef9 100644 --- a/Modules/Core/Common/include/itkMath.h +++ b/Modules/Core/Common/include/itkMath.h @@ -140,7 +140,7 @@ static constexpr float float_sqrteps = vnl_math::float_sqrteps; * \warning We assume that the rounding mode is not changed from the default * one (or at least that it is always restored to the default one). */ -itkTemplateFloatingToIntegerMacro(RoundHalfIntegerToEven); +itkTemplateFloatingToIntegerMacro(RoundHalfIntegerToEven) /** \brief Round towards nearest integer * @@ -164,7 +164,7 @@ itkTemplateFloatingToIntegerMacro(RoundHalfIntegerToEven); * the default one (or at least that it is always restored to the * default one). */ -itkTemplateFloatingToIntegerMacro(RoundHalfIntegerUp); +itkTemplateFloatingToIntegerMacro(RoundHalfIntegerUp) /** \brief Round towards nearest integer (This is a synonym for RoundHalfIntegerUp) * @@ -192,7 +192,7 @@ Round(TInput x) * the default one (or at least that it is always restored to the * default one). */ -itkTemplateFloatingToIntegerMacro(Floor); +itkTemplateFloatingToIntegerMacro(Floor) /** \brief Round towards plus infinity * @@ -204,7 +204,7 @@ itkTemplateFloatingToIntegerMacro(Floor); * the default one (or at least that it is always restored to the * default one). */ -itkTemplateFloatingToIntegerMacro(Ceil); +itkTemplateFloatingToIntegerMacro(Ceil) #undef itkTemplateFloatingToIntegerMacro @@ -212,10 +212,8 @@ template inline TReturn CastWithRangeCheck(TInput x) { -#ifdef ITK_USE_CONCEPT_CHECKING itkConceptMacro(OnlyDefinedForIntegerTypes1, (itk::Concept::IsInteger)); itkConceptMacro(OnlyDefinedForIntegerTypes2, (itk::Concept::IsInteger)); -#endif // ITK_USE_CONCEPT_CHECKING auto ret = static_cast(x); if constexpr (sizeof(TReturn) > sizeof(TInput) && @@ -253,8 +251,8 @@ template inline typename Detail::FloatIEEE::IntType FloatDifferenceULP(T x1, T x2) { - Detail::FloatIEEE x1f(x1); - Detail::FloatIEEE x2f(x2); + const Detail::FloatIEEE x1f(x1); + const Detail::FloatIEEE x2f(x2); return x1f.AsULP() - x2f.AsULP(); } @@ -269,8 +267,8 @@ template inline T FloatAddULP(T x, typename Detail::FloatIEEE::IntType ulps) { - Detail::FloatIEEE representInput(x); - Detail::FloatIEEE representOutput(representInput.asInt + ulps); + const Detail::FloatIEEE representInput(x); + const Detail::FloatIEEE representOutput(representInput.asInt + ulps); return representOutput.asFloat; } @@ -329,11 +327,7 @@ FloatAlmostEqual(T x1, return false; } - typename Detail::FloatIEEE::IntType ulps = FloatDifferenceULP(x1, x2); - if (ulps < 0) - { - ulps = -ulps; - } + const typename Detail::FloatIEEE::IntType ulps = std::abs(FloatDifferenceULP(x1, x2)); return ulps <= maxUlps; } @@ -743,6 +737,7 @@ NotExactlyEquals(const TInput1 & x1, const TInput2 & x2) * * \note Negative numbers cannot be prime. */ +/** @ITKStartGrouping */ ITKCommon_EXPORT bool IsPrime(unsigned short n); ITKCommon_EXPORT bool @@ -751,9 +746,10 @@ ITKCommon_EXPORT bool IsPrime(unsigned long n); ITKCommon_EXPORT bool IsPrime(unsigned long long n); - +/** @ITKEndGrouping */ /** Return the greatest factor of the decomposition in prime numbers. */ +/** @ITKStartGrouping */ ITKCommon_EXPORT unsigned short GreatestPrimeFactor(unsigned short n); ITKCommon_EXPORT unsigned int @@ -762,7 +758,7 @@ ITKCommon_EXPORT unsigned long GreatestPrimeFactor(unsigned long n); ITKCommon_EXPORT unsigned long long GreatestPrimeFactor(unsigned long long n); - +/** @ITKEndGrouping */ /** Returns `a * b`. Numeric overflow triggers a compilation error in * "constexpr context" and a debug assert failure at run-time. @@ -797,11 +793,10 @@ UnsignedPower(const uintmax_t base, const uintmax_t exponent) noexcept // Uses recursive function calls because C++11 does not support other ways of // iterations for a constexpr function. - return (exponent == 0) - ? (assert(base > 0), 1) - : (exponent == 1) ? base - : UnsignedProduct(UnsignedPower(base, exponent / 2), - UnsignedPower(base, (exponent + 1) / 2)); + return (exponent == 0) ? (assert(base > 0), 1) + : (exponent == 1) ? base + : UnsignedProduct(UnsignedPower(base, exponent / 2), + UnsignedPower(base, (exponent + 1) / 2)); } diff --git a/Modules/Core/Common/include/itkMatrix.h b/Modules/Core/Common/include/itkMatrix.h index 99bc070b2d0..5fc6ba34076 100644 --- a/Modules/Core/Common/include/itkMatrix.h +++ b/Modules/Core/Common/include/itkMatrix.h @@ -59,6 +59,24 @@ class ITK_TEMPLATE_EXPORT Matrix using ValueType = T; using ComponentType = T; + /** A pointer to the ValueType. */ + using pointer = ValueType *; + + /** A const pointer to the ValueType. */ + using const_pointer = const ValueType *; + + /** A reference to the ValueType. */ + using reference = ValueType &; + + /** A const reference to the ValueType. */ + using const_reference = const ValueType &; + + /** The return type of the non-const overloads of begin() and end(). */ + using iterator = ValueType *; + + /** The return type of cbegin() and cend(), and the const overloads of begin() and end(). */ + using const_iterator = const ValueType *; + /** Number Of Columns and Rows. */ static constexpr unsigned int RowDimensions = VRows; static constexpr unsigned int ColumnDimensions = VColumns; @@ -72,22 +90,28 @@ class ITK_TEMPLATE_EXPORT Matrix using CompatibleSquareMatrixType = Matrix; /** Matrix by Vector multiplication. */ - Vector operator*(const Vector & vect) const; + Vector + operator*(const Vector & vect) const; /** Matrix by Point multiplication. */ - Point operator*(const Point & pnt) const; + Point + operator*(const Point & pnt) const; /** Matrix by CovariantVector multiplication. */ - CovariantVector operator*(const CovariantVector & covect) const; + CovariantVector + operator*(const CovariantVector & covect) const; /** Matrix by vnl_vector_fixed multiplication. */ - vnl_vector_fixed operator*(const vnl_vector_fixed & inVNLvect) const; + vnl_vector_fixed + operator*(const vnl_vector_fixed & inVNLvect) const; /** Matrix by Matrix multiplication. */ - Self operator*(const CompatibleSquareMatrixType & matrix) const; + Self + operator*(const CompatibleSquareMatrixType & matrix) const; template - Matrix operator*(const vnl_matrix_fixed & matrix) const + Matrix + operator*(const vnl_matrix_fixed & matrix) const { const Matrix result(m_Matrix * matrix); return result; @@ -108,7 +132,8 @@ class ITK_TEMPLATE_EXPORT Matrix operator-=(const Self & matrix); /** Matrix by vnl_matrix multiplication. */ - vnl_matrix operator*(const vnl_matrix & matrix) const; + vnl_matrix + operator*(const vnl_matrix & matrix) const; /** Matrix by Matrix multiplication. */ void @@ -119,7 +144,8 @@ class ITK_TEMPLATE_EXPORT Matrix operator*=(const vnl_matrix & matrix); /** Matrix by vnl_vector multiplication. */ - vnl_vector operator*(const vnl_vector & vc) const; + vnl_vector + operator*(const vnl_vector & vc) const; /** Matrix by scalar multiplication. */ void @@ -129,7 +155,8 @@ class ITK_TEMPLATE_EXPORT Matrix } /** Matrix by scalar multiplication. */ - Self operator*(const T & value) const + Self + operator*(const T & value) const { Self result(*this); @@ -169,10 +196,18 @@ class ITK_TEMPLATE_EXPORT Matrix } /** Return a row of the matrix. */ - inline T * operator[](unsigned int i) { return m_Matrix[i]; } + inline T * + operator[](unsigned int i) + { + return m_Matrix[i]; + } /** Return a row of the matrix. */ - inline const T * operator[](unsigned int i) const { return m_Matrix[i]; } + inline const T * + operator[](unsigned int i) const + { + return m_Matrix[i]; + } /** Return the matrix. */ inline InternalMatrixType & @@ -280,7 +315,7 @@ class ITK_TEMPLATE_EXPORT Matrix { itkGenericExceptionMacro("Singular matrix. Determinant is 0."); } - vnl_matrix_inverse inverse(m_Matrix.as_ref()); + const vnl_matrix_inverse inverse(m_Matrix.as_ref()); return vnl_matrix_fixed{ inverse.as_matrix() }; } @@ -298,14 +333,78 @@ class ITK_TEMPLATE_EXPORT Matrix */ Matrix() = default; + /** Returns the number of elements. */ + constexpr unsigned int + size() const + { + return m_Matrix.size(); + } + + /** Returns an iterator to the first element. */ + iterator + begin() + { + return m_Matrix.begin(); + } + + /** Returns an iterator just beyond the last element. */ + iterator + end() + { + return m_Matrix.end(); + } + + /** Returns a const iterator to the first element. */ + const_iterator + begin() const + { + return m_Matrix.begin(); + } + + /** Returns a const iterator just beyond the last element. */ + const_iterator + end() const + { + return m_Matrix.end(); + } + + /** Returns a const iterator to the first element. */ + const_iterator + cbegin() const + { + return m_Matrix.begin(); + } + + /** Returns a const iterator just beyond the last element. */ + const_iterator + cend() const + { + return m_Matrix.end(); + } + void - swap(Self & other) + swap(Self & other) noexcept { // allow for augment dependent look up using std::swap; swap(this->m_Matrix, other.m_Matrix); } + inline void + PrintSelf(std::ostream & os, Indent indent) const + { + os << indent << "Matrix (" << VRows << "x" << VColumns << ")\n"; + for (unsigned int r = 0; r < VRows; ++r) + { + os << indent << " "; + for (unsigned int c = 0; c < VColumns; ++c) + { + os << m_Matrix(r, c) << " "; + } + os << "\n"; + } + } + private: InternalMatrixType m_Matrix{}; }; @@ -321,7 +420,7 @@ operator<<(std::ostream & os, const Matrix & v) template inline void -swap(const Matrix & a, const Matrix & b) +swap(const Matrix & a, const Matrix & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkMatrix.hxx b/Modules/Core/Common/include/itkMatrix.hxx index 28f1d8446c7..557dcef106e 100644 --- a/Modules/Core/Common/include/itkMatrix.hxx +++ b/Modules/Core/Common/include/itkMatrix.hxx @@ -26,7 +26,8 @@ namespace itk * Product by a Vector */ template -Vector Matrix::operator*(const Vector & vect) const +Vector +Matrix::operator*(const Vector & vect) const { Vector result; for (unsigned int r = 0; r < VRows; ++r) @@ -45,7 +46,8 @@ Vector Matrix::operator*(const Vector * Product by a Point */ template -Point Matrix::operator*(const Point & pnt) const +Point +Matrix::operator*(const Point & pnt) const { Point result; for (unsigned int r = 0; r < VRows; ++r) @@ -64,7 +66,8 @@ Point Matrix::operator*(const Point & * Product by a vnl_vector_fixed */ template -vnl_vector_fixed Matrix::operator*(const vnl_vector_fixed & inVNLvect) const +vnl_vector_fixed +Matrix::operator*(const vnl_vector_fixed & inVNLvect) const { vnl_vector_fixed result; for (unsigned int r = 0; r < VRows; ++r) @@ -83,7 +86,8 @@ vnl_vector_fixed Matrix::operator*(const vnl_vecto * Product by a CovariantVector */ template -CovariantVector Matrix::operator*(const CovariantVector & covect) const +CovariantVector +Matrix::operator*(const CovariantVector & covect) const { CovariantVector result; for (unsigned int r = 0; r < VRows; ++r) @@ -102,7 +106,8 @@ CovariantVector Matrix::operator*(const CovariantV * Product by a matrix */ template -Matrix Matrix::operator*(const CompatibleSquareMatrixType & matrix) const +Matrix +Matrix::operator*(const CompatibleSquareMatrixType & matrix) const { const Self result(m_Matrix * matrix.GetVnlMatrix()); return result; @@ -184,7 +189,8 @@ Matrix::operator-=(const Self & matrix) * Product by a vnl_matrix */ template -vnl_matrix Matrix::operator*(const vnl_matrix & matrix) const +vnl_matrix +Matrix::operator*(const vnl_matrix & matrix) const { return m_Matrix * matrix; } @@ -213,7 +219,8 @@ Matrix::operator*=(const vnl_matrix & matrix) * Product by a vnl_vector */ template -vnl_vector Matrix::operator*(const vnl_vector & vc) const +vnl_vector +Matrix::operator*(const vnl_vector & vc) const { return m_Matrix * vc; } diff --git a/Modules/Core/Common/include/itkMemoryUsageObserver.h b/Modules/Core/Common/include/itkMemoryUsageObserver.h index f1c7ca2b895..12793f5f053 100644 --- a/Modules/Core/Common/include/itkMemoryUsageObserver.h +++ b/Modules/Core/Common/include/itkMemoryUsageObserver.h @@ -87,6 +87,7 @@ class ITKCommon_EXPORT LinuxMemoryUsageObserver : public MemoryUsageObserverBase public: /** destructor */ ~LinuxMemoryUsageObserver() override; + MemoryLoadType GetMemoryUsage() override; }; @@ -98,6 +99,7 @@ class ITKCommon_EXPORT MacOSXMemoryUsageObserver : public MemoryUsageObserverBas public: /** destructor */ ~MacOSXMemoryUsageObserver() override; + MemoryLoadType GetMemoryUsage() override; }; @@ -109,6 +111,7 @@ class ITKCommon_EXPORT SunSolarisMemoryUsageObserver : public MemoryUsageObserve public: /** destructor */ virtual ~SunSolarisMemoryUsageObserver(); + virtual MemoryLoadType GetMemoryUsage(); }; @@ -120,6 +123,7 @@ class ITKCommon_EXPORT SysResourceMemoryUsageObserver : public MemoryUsageObserv public: /** destructor */ ~SysResourceMemoryUsageObserver() override; + MemoryLoadType GetMemoryUsage() override; }; @@ -134,9 +138,11 @@ class ITKCommon_EXPORT MallinfoMemoryUsageObserver : public MemoryUsageObserverB public: /** destructor */ ~MallinfoMemoryUsageObserver() override; + MemoryLoadType GetMemoryUsage() override; }; + # endif // Mallinfo #endif // !defined(WIN32) && !defined(_WIN32) diff --git a/Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h b/Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h index 8875d7f1f63..74ce9f84161 100644 --- a/Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h +++ b/Modules/Core/Common/include/itkMersenneTwisterRandomVariateGenerator.h @@ -29,6 +29,7 @@ #include #include #include +#include namespace itk { @@ -69,10 +70,7 @@ namespace Statistics * division, and it benefits from caches and pipelines. For more information * see the inventors' web page at http:*www.math.keio.ac.jp/~matumoto/emt.html * - * Reference - * M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally - * Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on - * Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. + * Algorithmic details can be found in \cite matsumoto1998. * * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, * Copyright (C) 2000 - 2003, Richard J. Wagner @@ -165,40 +163,71 @@ class ITKCommon_EXPORT MersenneTwisterRandomVariateGenerator : public RandomVari static void ResetNextSeed(); + /** The initial seed of a default-constructed generator. + * + * \note The global generator retrieved by `GetInstance()`, and local generators created by `New()` may all have a + * different (non-default) seeds. + * \note The Mersenne Twister random number engine of the Standard C++ Library `std::mersenne_twister_engine` + * (`std::mt19937`) has a different default seed, `default_seed == 5489`. + */ + static constexpr IntegerType DefaultSeed = 121212; + /** Length of state vector */ static constexpr IntegerType StateVectorLength = 624; - /** Initialize with a simple IntegerType */ - void - Initialize(const IntegerType seed); - - /* Initialize with clock time */ +#ifndef ITK_FUTURE_LEGACY_REMOVE + /** Sets the seed and initializes the internal state of this generator. + * \deprecated ITK 6 discourages using this member function. Please use `SetSeed` instead! + */ + ITK_FUTURE_DEPRECATED("ITK 6 discourages using this member function. Please use `SetSeed` instead!") void - Initialize(); + Initialize(const IntegerType seed = Self::CreateRandomSeed()) + { + this->SetSeed(seed); + } +#endif /** Get a random variate in the range [0, 1] */ double - GetVariateWithClosedRange(); + GetVariateWithClosedRange() + { + return static_cast(GetIntegerVariate()) * (1.0 / double{ std::numeric_limits::max() }); + } /** Get a random variate in the range [0, n] */ double - GetVariateWithClosedRange(const double n); + GetVariateWithClosedRange(const double n) + { + return GetVariateWithClosedRange() * n; + } /** Get a range variate in the range [0, 1) */ double - GetVariateWithOpenUpperRange(); + GetVariateWithOpenUpperRange() + { + return static_cast(GetIntegerVariate()) / double{ 1ULL << 32ULL }; + } /** Get a range variate in the range [0, n) */ double - GetVariateWithOpenUpperRange(const double n); + GetVariateWithOpenUpperRange(const double n) + { + return GetVariateWithOpenUpperRange() * n; + } /** Get a range variate in the range (0, 1) */ double - GetVariateWithOpenRange(); + GetVariateWithOpenRange() + { + return (static_cast(GetIntegerVariate()) + 0.5) / double{ 1ULL << 32ULL }; + } /** Get a range variate in the range (0, n) */ double - GetVariateWithOpenRange(const double n); + GetVariateWithOpenRange(const double n) + { + return GetVariateWithOpenRange() * n; + } /** Get an integer variate in [0, 2^32-1] */ IntegerType @@ -206,7 +235,7 @@ class ITKCommon_EXPORT MersenneTwisterRandomVariateGenerator : public RandomVari /** Get an integer variate in [0, n] for n < 2^32 */ IntegerType - GetIntegerVariate(const IntegerType & n); + GetIntegerVariate(const IntegerType n); /** Access to 53-bit random numbers (capacity of IEEE double precision) * in the range [0,1) */ @@ -229,27 +258,34 @@ class ITKCommon_EXPORT MersenneTwisterRandomVariateGenerator : public RandomVari * reading 624 consecutive values. */ double - GetVariate() override; + GetVariate() override + { + return GetVariateWithClosedRange(); + } /** Same as GetVariate() */ double - operator()(); + operator()() + { + return GetVariate(); + } - /** Re-seeding functions with same behavior as initializers + /** Re-seeding function with same behavior as Initialize. * * \note This method is thread-safe. */ - inline void - SetSeed(const IntegerType oneSeed); - inline void - SetSeed(); + void + SetSeed(const IntegerType seed = Self::CreateRandomSeed()); /** Return the current seed * * \note This method is thread-safe. */ IntegerType - GetSeed() const; + GetSeed() const + { + return m_Seed; + } /** Return the next seed, derived as a sequence from the seed of the * singleton instance. @@ -259,57 +295,40 @@ class ITKCommon_EXPORT MersenneTwisterRandomVariateGenerator : public RandomVari static IntegerType GetNextSeed(); - /* - // Saving and loading generator state - void save( IntegerType* saveArray ) const; // to array of size SAVE - void load( IntegerType *const loadArray ); // from such array - */ - protected: MersenneTwisterRandomVariateGenerator(); ~MersenneTwisterRandomVariateGenerator() override; void PrintSelf(std::ostream & os, Indent indent) const override; - /** Period parameter */ - static constexpr unsigned int M = 397; - /** Reload array with N new values. */ void reload(); - IntegerType - hiBit(const IntegerType & u) const - { - return u & 0x80000000; - } - IntegerType - loBit(const IntegerType & u) const - { - return u & 0x00000001; - } - IntegerType - loBits(const IntegerType & u) const - { - return u & 0x7fffffff; - } - IntegerType - mixBits(const IntegerType & u, const IntegerType & v) const - { - return hiBit(u) | loBits(v); - } + static IntegerType + hash(time_t t, clock_t c); - IntegerType - twist(const IntegerType & m, const IntegerType & s0, const IntegerType & s1) const +private: + /** Only used to synchronize the global variable across static libraries.*/ + itkGetGlobalDeclarationMacro(MersenneTwisterGlobals, PimplGlobals); + + /** Internal method to actually create a new object. */ + static Pointer + CreateInstance(); + + /** Uses time() and clock() to generate a unlikely-to-repeat seed. */ + static IntegerType + CreateRandomSeed() { - return m ^ (mixBits(s0, s1) >> 1) ^ (-static_cast(loBit(s1)) & 0x9908b0df); + return hash(time(nullptr), clock()); } - static IntegerType - hash(time_t t, clock_t c); + /** Internal method to initialize a generator object without mutex locking. */ + void + InitializeWithoutMutexLocking(const IntegerType seed); // Internal state - IntegerType state[StateVectorLength]; + IntegerType m_State[StateVectorLength]; // Next value to get from state IntegerType * m_PNext{}; @@ -320,14 +339,6 @@ class ITKCommon_EXPORT MersenneTwisterRandomVariateGenerator : public RandomVari // Seed value std::atomic m_Seed{}; -private: - /** Only used to synchronize the global variable across static libraries.*/ - itkGetGlobalDeclarationMacro(MersenneTwisterGlobals, PimplGlobals); - - /** Internal method to actually create a new object. */ - static Pointer - CreateInstance(); - // Local lock to enable concurrent access to singleton std::mutex m_InstanceMutex{}; @@ -339,168 +350,13 @@ class ITKCommon_EXPORT MersenneTwisterRandomVariateGenerator : public RandomVari // Declare inlined functions.... (must be declared in the header) -inline void -MersenneTwisterRandomVariateGenerator::Initialize(const IntegerType seed) -{ - const std::lock_guard lockGuard(m_InstanceMutex); - this->m_Seed = seed; - // Initialize generator state with 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. - IntegerType * s = state; - IntegerType * r = state; - IntegerType i = 1; - - *s++ = seed & 0xffffffffUL; - for (i = 1; i < MersenneTwisterRandomVariateGenerator::StateVectorLength; ++i) - { - *s++ = (1812433253UL * (*r ^ (*r >> 30)) + i) & 0xffffffffUL; - ++r; - } - reload(); -} - -inline void -MersenneTwisterRandomVariateGenerator::reload() -{ - // Generate N new values in state - // Made clearer and faster by Matthew Bellew - // matthew dot bellew at home dot com - - // get rid of VS warning - constexpr auto index = int{ M } - int{ MersenneTwisterRandomVariateGenerator::StateVectorLength }; - - IntegerType * p = state; - int i; - - for (i = MersenneTwisterRandomVariateGenerator::StateVectorLength - M; i--; ++p) - { - *p = twist(p[M], p[0], p[1]); - } - for (i = M; --i; ++p) - { - *p = twist(p[index], p[0], p[1]); - } - *p = twist(p[index], p[0], state[0]); - - m_Left = MersenneTwisterRandomVariateGenerator::StateVectorLength; - m_PNext = state; -} - -inline void -MersenneTwisterRandomVariateGenerator::Initialize() -{ - SetSeed(); -} - -inline void -MersenneTwisterRandomVariateGenerator::SetSeed(const IntegerType oneSeed) -{ - // Seed the generator with a simple IntegerType - Initialize(oneSeed); -} - -inline void -MersenneTwisterRandomVariateGenerator::SetSeed() -{ - // use time() and clock() to generate a unlikely-to-repeat seed. - SetSeed(hash(time(nullptr), clock())); -} - - -inline MersenneTwisterRandomVariateGenerator::IntegerType -MersenneTwisterRandomVariateGenerator::GetSeed() const -{ - return this->m_Seed; -} - -/** Get an integer variate in [0, 2^32-1] */ -inline MersenneTwisterRandomVariateGenerator::IntegerType -MersenneTwisterRandomVariateGenerator::GetIntegerVariate() -{ - if (m_Left == 0) - { - reload(); - } - --m_Left; - - IntegerType s1 = *m_PNext++; - s1 ^= (s1 >> 11); - s1 ^= (s1 << 7) & 0x9d2c5680; - s1 ^= (s1 << 15) & 0xefc60000; - return (s1 ^ (s1 >> 18)); -} - -inline double -MersenneTwisterRandomVariateGenerator::GetVariateWithClosedRange() -{ - return static_cast(GetIntegerVariate()) * (1.0 / 4294967295.0); -} - -/** Get a random variate in the range [0, n] */ -inline double -MersenneTwisterRandomVariateGenerator::GetVariateWithClosedRange(const double n) -{ - return GetVariateWithClosedRange() * n; -} - -/** Get a range variate in the range [0, 1) */ -inline double -MersenneTwisterRandomVariateGenerator::GetVariateWithOpenUpperRange() -{ - return static_cast(GetIntegerVariate()) * (1.0 / 4294967296.0); -} - -/** Get a range variate in the range [0, n) */ -inline double -MersenneTwisterRandomVariateGenerator::GetVariateWithOpenUpperRange(const double n) -{ - return GetVariateWithOpenUpperRange() * n; -} - -/** Get a range variate in the range (0, 1) */ -inline double -MersenneTwisterRandomVariateGenerator::GetVariateWithOpenRange() -{ - return (static_cast(GetIntegerVariate()) + 0.5) * (1.0 / 4294967296.0); -} - -/** Get a range variate in the range (0, n) */ -inline double -MersenneTwisterRandomVariateGenerator::GetVariateWithOpenRange(const double n) -{ - return GetVariateWithOpenRange() * n; -} - -inline MersenneTwisterRandomVariateGenerator::IntegerType -MersenneTwisterRandomVariateGenerator::GetIntegerVariate(const IntegerType & n) -{ - // Find which bits are used in n - IntegerType used = n; - - used |= used >> 1; - used |= used >> 2; - used |= used >> 4; - used |= used >> 8; - used |= used >> 16; - - // Draw numbers until one is found in [0,n] - IntegerType i; - do - { - i = GetIntegerVariate() & used; // toss unused bits to shorten search - } while (i > n); - - return i; -} - /** Access to 53-bit random numbers (capacity of IEEE double precision) * in the range [0,1) */ inline double MersenneTwisterRandomVariateGenerator::Get53BitVariate() { - IntegerType a = GetIntegerVariate() >> 5, b = GetIntegerVariate() >> 6; + const IntegerType a = GetIntegerVariate() >> 5; + const IntegerType b = GetIntegerVariate() >> 6; return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); // by Isaku // Wada @@ -513,8 +369,8 @@ MersenneTwisterRandomVariateGenerator::GetNormalVariate(const double mean, const { // Return a real number from a normal (Gaussian) distribution with given // mean and variance by Box-Muller method - double r = std::sqrt(-2.0 * std::log(1.0 - GetVariateWithOpenRange()) * variance); - double phi = 2.0 * itk::Math::pi * GetVariateWithOpenUpperRange(); + const double r = std::sqrt(-2.0 * std::log(1.0 - GetVariateWithOpenRange()) * variance); + const double phi = 2.0 * itk::Math::pi * GetVariateWithOpenUpperRange(); return mean + r * std::cos(phi); } @@ -524,23 +380,11 @@ MersenneTwisterRandomVariateGenerator::GetNormalVariate(const double mean, const inline double MersenneTwisterRandomVariateGenerator::GetUniformVariate(const double a, const double b) { - double u = GetVariateWithOpenUpperRange(); + const double u = GetVariateWithOpenUpperRange(); return ((1.0 - u) * a + u * b); } -inline double -MersenneTwisterRandomVariateGenerator::GetVariate() -{ - return GetVariateWithClosedRange(); -} - -inline double -MersenneTwisterRandomVariateGenerator::operator()() -{ - return GetVariate(); -} - /* Change log from MTRand.h */ // Change log: // diff --git a/Modules/Core/Common/include/itkMetaDataDictionary.h b/Modules/Core/Common/include/itkMetaDataDictionary.h index 9aad3891bf9..c0681ac72ae 100644 --- a/Modules/Core/Common/include/itkMetaDataDictionary.h +++ b/Modules/Core/Common/include/itkMetaDataDictionary.h @@ -121,12 +121,14 @@ class ITKCommon_EXPORT MetaDataDictionary // cannot be exported. This causes problems when building DLL's. // Here we inherit privately from std::map and provide a simple // API. The implementation will be in the DLL. - MetaDataObjectBase::Pointer & operator[](const std::string &); + MetaDataObjectBase::Pointer & + operator[](const std::string &); // \brief Get a constant point to a DataObject // // If the key does not exist then nullptr is returned. - const MetaDataObjectBase * operator[](const std::string &) const; + const MetaDataObjectBase * + operator[](const std::string &) const; const MetaDataObjectBase * Get(const std::string &) const; @@ -143,21 +145,23 @@ class ITKCommon_EXPORT MetaDataDictionary * context cannot be dereferenced safely */ /** Returns an iterator to the beginning of the map */ + /** @ITKStartGrouping */ // Blacklisted by igenerator.py Iterator Begin(); // Blacklisted by igenerator.py ConstIterator Begin() const; - + /** @ITKEndGrouping */ /** Returns an iterator to the end of the map */ + /** @ITKStartGrouping */ // Blacklisted by igenerator.py Iterator End(); // Blacklisted by igenerator.py ConstIterator End() const; - + /** @ITKEndGrouping */ /** Returns an iterator matching the string key */ Iterator Find(const std::string & key); @@ -180,7 +184,7 @@ class ITKCommon_EXPORT MetaDataDictionary }; inline void -swap(MetaDataDictionary & a, MetaDataDictionary & b) +swap(MetaDataDictionary & a, MetaDataDictionary & b) noexcept { a.Swap(b); } diff --git a/Modules/Core/Common/include/itkMetaDataObject.h b/Modules/Core/Common/include/itkMetaDataObject.h index bbf2f7bd8cf..f1ffa585d14 100644 --- a/Modules/Core/Common/include/itkMetaDataObject.h +++ b/Modules/Core/Common/include/itkMetaDataObject.h @@ -58,15 +58,8 @@ namespace itk * and redefining the copy constructor and initializing constructor and the Get/Set functions * to work around those deficiencies. * - * The behavior of the MetaDataObject::Print() function has many plausible - * application dependent implementations. The default implementation prints the - * string "[UNKNOWN PRINT CHARACTERISTICS]" that works for all possible - * MetaDataObject types. - * - * The application developer may overload the default implementation to provide - * a specialized Print() characteristics to produce results desirable for their application. - * A set of very crude Macros {NATIVE_TYPE_METADATAPRINT, ITK_OBJECT_TYPE_METADATAPRINT_1COMMA, - * ITK_IMAGE_TYPE_METADATAPRINT } are provided to facilitate a very simple implementation, and as an example. + * The default implementation prints uses the MetaDataObjectType's Print or operator<< if available. Otherwise, it + * prints string "[UNKNOWN PRINT CHARACTERISTICS]". * * \ingroup ITKCommon * @@ -221,7 +214,7 @@ template inline void EncapsulateMetaData(MetaDataDictionary & Dictionary, const std::string & key, const T & invalue) { - typename MetaDataObject::Pointer temp = MetaDataObject::New(); + auto temp = MetaDataObject::New(); temp->SetMetaDataObjectValue(invalue); Dictionary[key] = temp; } @@ -252,7 +245,7 @@ ExposeMetaData(const MetaDataDictionary & Dictionary, const std::string key, T & return false; } - auto const * const TempMetaDataObject = dynamic_cast const *>(keyIter->second.GetPointer()); + const auto * const TempMetaDataObject = dynamic_cast *>(keyIter->second.GetPointer()); if (TempMetaDataObject == nullptr) { return false; @@ -264,52 +257,6 @@ ExposeMetaData(const MetaDataDictionary & Dictionary, const std::string key, T & } // end namespace itk -/** - * \def ITK_NATIVE_TYPE_METADATAPRINT( TYPE_NAME ) - * \brief An ugly macro to facilitate creating a simple implementation of - * the MetaDataObject::Print() function for types that - * have operator<< defined. - * \param TYPE_NAME the native type parameter type - */ -#define ITK_NATIVE_TYPE_METADATAPRINT(TYPE_NAME) \ - template <> \ - void itk::MetaDataObject::Print(std::ostream & os) const \ - { \ - os << this->m_MetaDataObjectValue << std::endl; \ - } - -/** - * \def ITK_OBJECT_TYPE_METADATAPRINT_1COMMA( TYPE_NAME_PART1, TYPE_NAME_PART2 ) - * \brief An ugly macro to facilitate creating a simple implementation of - * the MetaDataObject< Type >::Print() function for - * itk::Objects that have 1 comma in their type definition - * \param TYPE_NAME_PART1 - * \param TYPE_NAME_PART2 - */ -#define ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(TYPE_NAME_PART1, TYPE_NAME_PART2) \ - template <> \ - void itk::MetaDataObject::Print(std::ostream & os) const \ - { \ - this->m_MetaDataObjectValue->Print(os); \ - } - -/** - * \def ITK_IMAGE_TYPE_METADATAPRINT( STORAGE_TYPE ) - * An ugly macro to facilitate creating a simple implementation of - * the MetaDataObject::Print() function for - * itk::Image\\::Pointer - * \param STORAGE_TYPE The storage type of the image type to print. - */ -#define ITK_IMAGE_TYPE_METADATAPRINT(STORAGE_TYPE) \ - ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(itk::Image::Pointer) \ - ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(itk::Image::Pointer) \ - ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(itk::Image::Pointer) \ - ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(itk::Image::Pointer) \ - ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(itk::Image::Pointer) \ - ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(itk::Image::Pointer) \ - ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(itk::Image::Pointer) \ - ITK_OBJECT_TYPE_METADATAPRINT_1COMMA(itk::Image::Pointer) - #ifndef ITK_MANUAL_INSTANTIATION # include "itkMetaDataObject.hxx" #endif diff --git a/Modules/Core/Common/include/itkMetaDataObject.hxx b/Modules/Core/Common/include/itkMetaDataObject.hxx index 23b92f234db..27ec13a373b 100644 --- a/Modules/Core/Common/include/itkMetaDataObject.hxx +++ b/Modules/Core/Common/include/itkMetaDataObject.hxx @@ -28,6 +28,7 @@ #ifndef itkMetaDataObject_hxx #define itkMetaDataObject_hxx +#include "itkMetaDataObjectDetail.h" namespace itk { @@ -63,7 +64,21 @@ template void MetaDataObject::Print(std::ostream & os) const { - Superclass::Print(os); + // future c++20 feature + // constexpr bool hasPrint = false; requires( const &MetaDataObjectType obj ) { obj.Print(os); }; + + if constexpr (MetaDataObjectDetail::has_Print::value) + { + m_MetaDataObjectValue.Print(os); + } + else if constexpr (MetaDataObjectDetail::has_output_operator::value) + { + os << m_MetaDataObjectValue; + } + else + { + Superclass::Print(os); + } } } // end namespace itk diff --git a/Modules/Compatibility/Deprecated/src/itkBarrier.cxx b/Modules/Core/Common/include/itkMetaDataObjectDetail.h similarity index 51% rename from Modules/Compatibility/Deprecated/src/itkBarrier.cxx rename to Modules/Core/Common/include/itkMetaDataObjectDetail.h index be060f518a4..26201bfc262 100644 --- a/Modules/Compatibility/Deprecated/src/itkBarrier.cxx +++ b/Modules/Core/Common/include/itkMetaDataObjectDetail.h @@ -15,38 +15,37 @@ * limitations under the License. * *=========================================================================*/ -#include "itkBarrier.h" -namespace itk -{ -Barrier::Barrier() = default; +#ifndef itkMetaDataObjectDetail_h +#define itkMetaDataObjectDetail_h -Barrier::~Barrier() = default; +#include +#include +#include -void -Barrier::Initialize(unsigned int n) +namespace itk { - m_NumberExpected = n; -} -void -Barrier::Wait() +// Implementation details for MetaDataObject meta programming +namespace MetaDataObjectDetail { - std::unique_lock lockHolder{ m_Mutex }; - unsigned int lGeneration = m_Generation; - ++m_NumberArrived; - if (m_NumberArrived == m_NumberExpected) - { - // Clear all blocked threads - ++m_Generation; - m_NumberArrived = 0; - m_ConditionVariable.notify_all(); - } - else - { - // Block this thread - m_ConditionVariable.wait(lockHolder, [this, lGeneration] { return lGeneration != m_Generation; }); - } -} - -} // end namespace itk +template +struct has_Print : std::false_type +{}; + +template +struct has_Print().Print(std::declval()))>> : std::true_type +{}; + +template +struct has_output_operator : std::false_type +{}; + +template +struct has_output_operator() << std::declval())>> + : std::true_type +{}; +} // namespace MetaDataObjectDetail +} // namespace itk + +#endif diff --git a/Modules/Core/Common/include/itkMetaProgrammingLibrary.h b/Modules/Core/Common/include/itkMetaProgrammingLibrary.h index 34323675a50..8bc605f8ceb 100644 --- a/Modules/Core/Common/include/itkMetaProgrammingLibrary.h +++ b/Modules/Core/Common/include/itkMetaProgrammingLibrary.h @@ -44,7 +44,7 @@ struct TrueType using Type = TrueType; static constexpr ValueType Value = true; - operator ValueType() { return Value; } + operator ValueType() { return Value; } }; /** borrowed from ``. @@ -56,7 +56,7 @@ struct FalseType using ValueType = bool; using Type = FalseType; static constexpr ValueType Value = false; - operator ValueType() { return Value; } + operator ValueType() { return Value; } }; /** MPL \c if control-statement. @@ -99,7 +99,7 @@ struct OrC : FalseType /** MPL \c OR operator on types. * \tparam TF1 First boolean type * \tparam TF2 Second boolean type - * \tparam VF3 Third (optional) boolean type + * \tparam TF3 Third (optional) boolean type * * This \em overload automatically fetches \c TF1, \c TF2 and \c TF3 values. * However, beware, it won't work with standard C++ traits or boost traits. diff --git a/Modules/Core/Common/include/itkMultiThreaderBase.h b/Modules/Core/Common/include/itkMultiThreaderBase.h index 5aa630aca60..6dd4908f02d 100644 --- a/Modules/Core/Common/include/itkMultiThreaderBase.h +++ b/Modules/Core/Common/include/itkMultiThreaderBase.h @@ -53,7 +53,7 @@ namespace itk class MultiThreaderBaseEnums { public: - /** \class Threader + /** * \ingroup ITKCommon * Currently supported types of multi-threader implementations. * Last will change with additional implementations. @@ -68,7 +68,7 @@ class MultiThreaderBaseEnums Unknown = -1 }; - /** \class ThreadExitCode + /** * \ingroup ITKCommon */ enum class ThreadExitCode : uint8_t @@ -124,17 +124,19 @@ class ITKCommon_EXPORT MultiThreaderBase : public Object /** Get/Set the number of threads to use. It will be clamped to the range * [ 1, m_GlobalMaximumNumberOfThreads ], so the caller of this method should * check that the requested number of threads was accepted. */ + /** @ITKStartGrouping */ virtual void SetMaximumNumberOfThreads(ThreadIdType numberOfThreads); itkGetConstMacro(MaximumNumberOfThreads, ThreadIdType); - + /** @ITKEndGrouping */ /** Get/Set the number of work units to create. It might be clamped to the range * [ 1, SomeMaximumNumber ], so the caller of this method should * check that the requested number of work units was accepted. */ + /** @ITKStartGrouping */ virtual void SetNumberOfWorkUnits(ThreadIdType numberOfWorkUnits); itkGetConstMacro(NumberOfWorkUnits, ThreadIdType); - + /** @ITKEndGrouping */ virtual void SetUpdateProgress(bool updates); itkGetConstMacro(UpdateProgress, bool); @@ -144,19 +146,21 @@ class ITKCommon_EXPORT MultiThreaderBase : public Object * are already statically allocated using the ITK_MAX_THREADS number. * Therefore the caller of this method should check that the requested number * of threads was accepted. */ + /** @ITKStartGrouping */ static void SetGlobalMaximumNumberOfThreads(ThreadIdType val); static ThreadIdType GetGlobalMaximumNumberOfThreads(); - + /** @ITKEndGrouping */ /** Set/Get whether to use the to use the thread pool * implementation or the spawning implementation of * starting threads. * * Deprecated: use Get/Set GlobalDefaultThreader. */ - itkLegacyMacro(static void SetGlobalDefaultUseThreadPool(const bool GlobalDefaultUseThreadPool)); - itkLegacyMacro(static bool GetGlobalDefaultUseThreadPool()); - + /** @ITKStartGrouping */ + itkLegacyMacro(static void SetGlobalDefaultUseThreadPool(const bool GlobalDefaultUseThreadPool);) + itkLegacyMacro(static bool GetGlobalDefaultUseThreadPool();) + /** @ITKEndGrouping */ using ThreaderEnum = MultiThreaderBaseEnums::Threader; #if !defined(ITK_LEGACY_REMOVE) using ThreaderType = ThreaderEnum; @@ -201,30 +205,36 @@ class ITKCommon_EXPORT MultiThreaderBase : public Object * * If the SetGlobalDefaultThreaderType API is ever used by the developer, * the developer's choice is respected over the environment variables. */ + /** @ITKStartGrouping */ static void SetGlobalDefaultThreader(ThreaderEnum threaderType); static ThreaderEnum GetGlobalDefaultThreader(); - + /** @ITKEndGrouping */ /** Set/Get the value which is used to initialize the NumberOfThreads in the * constructor. It will be clamped to the range [1, m_GlobalMaximumNumberOfThreads ]. * Therefore the caller of this method should check that the requested number * of threads was accepted. */ + /** @ITKStartGrouping */ static void SetGlobalDefaultNumberOfThreads(ThreadIdType val); static ThreadIdType GetGlobalDefaultNumberOfThreads(); - + /** @ITKEndGrouping */ #if !defined(ITK_LEGACY_REMOVE) /** Get/Set the number of threads to use. * DEPRECATED! Use WorkUnits and MaximumNumberOfThreads instead. */ + /** @ITKStartGrouping */ itkLegacyMacro(virtual void SetNumberOfThreads(ThreadIdType numberOfThreads)) { this->SetMaximumNumberOfThreads(numberOfThreads); this->SetNumberOfWorkUnits(this->GetMaximumNumberOfThreads()); // Might be clamped } - itkLegacyMacro(virtual ThreadIdType GetNumberOfThreads()) { return this->GetNumberOfWorkUnits(); } - + itkLegacyMacro(virtual ThreadIdType GetNumberOfThreads()) + { + return this->GetNumberOfWorkUnits(); + } + /** @ITKEndGrouping */ /** This is the structure that is passed to the thread that is * created from the SingleMethodExecute. It is passed in as a void *, * and it is up to the method to cast correctly and extract the information. @@ -233,6 +243,7 @@ class ITKCommon_EXPORT MultiThreaderBase : public Object * (void *)arg passed into the SetSingleMethod. * * DEPRECATED! Use WorkUnitInfo instead. */ + /** @ITKStartGrouping */ // clang-format off ITK_GCC_PRAGMA_DIAG_PUSH() ITK_GCC_PRAGMA_DIAG(ignored "-Wattributes") @@ -264,6 +275,7 @@ INTEL_PRAGMA_WARN_POP // clang-format off ITK_GCC_PRAGMA_DIAG_POP() // clang-format on + /** @ITKEndGrouping */ #endif // ITK_LEGACY_REMOVE /** This is the structure that is passed to the thread that is @@ -368,7 +380,7 @@ ITK_GCC_PRAGMA_DIAG_POP() if constexpr (VDimension <= 1) // Cannot split, no parallelization { - ProgressReporter progress(filter, 0, requestedRegion.GetNumberOfPixels()); + const ProgressReporter progress(filter, 0, requestedRegion.GetNumberOfPixels()); funcP(requestedRegion); } else // Can split, parallelize! diff --git a/Modules/Core/Common/include/itkNeighborhood.h b/Modules/Core/Common/include/itkNeighborhood.h index 6456ed81d84..2c75583de10 100644 --- a/Modules/Core/Common/include/itkNeighborhood.h +++ b/Modules/Core/Common/include/itkNeighborhood.h @@ -164,6 +164,7 @@ class ITK_TEMPLATE_EXPORT Neighborhood } /** STL-style iterator support. */ + /** @ITKStartGrouping */ Iterator End() { @@ -184,6 +185,7 @@ class ITK_TEMPLATE_EXPORT Neighborhood { return m_DataBuffer.begin(); } + /** @ITKEndGrouping */ /** More STL-style support. */ NeighborIndexType @@ -193,13 +195,23 @@ class ITK_TEMPLATE_EXPORT Neighborhood } /** Pass-through data access methods to the buffer. */ - TPixel & operator[](NeighborIndexType i) { return m_DataBuffer[i]; } - const TPixel & operator[](NeighborIndexType i) const { return m_DataBuffer[i]; } + /** @ITKStartGrouping */ + TPixel & + operator[](NeighborIndexType i) + { + return m_DataBuffer[i]; + } + const TPixel & + operator[](NeighborIndexType i) const + { + return m_DataBuffer[i]; + } TPixel & GetElement(NeighborIndexType i) { return m_DataBuffer[i]; } + /** @ITKEndGrouping */ /** Returns the element at the center of the neighborhood. */ TPixel @@ -237,6 +249,7 @@ class ITK_TEMPLATE_EXPORT Neighborhood } /** Returns a reference to the data buffer structure. */ + /** @ITKStartGrouping */ AllocatorType & GetBufferReference() { @@ -247,10 +260,21 @@ class ITK_TEMPLATE_EXPORT Neighborhood { return m_DataBuffer; } + /** @ITKEndGrouping */ /** Get pixel value by offset */ - TPixel & operator[](const OffsetType & o) { return this->operator[](this->GetNeighborhoodIndex(o)); } - const TPixel & operator[](const OffsetType & o) const { return this->operator[](this->GetNeighborhoodIndex(o)); } + /** @ITKStartGrouping */ + TPixel & + operator[](const OffsetType & o) + { + return this->operator[](this->GetNeighborhoodIndex(o)); + } + const TPixel & + operator[](const OffsetType & o) const + { + return this->operator[](this->GetNeighborhoodIndex(o)); + } + /** @ITKEndGrouping */ /** Returns the itk::Offset from the center of the Neighborhood to the requested neighbor index. */ diff --git a/Modules/Core/Common/include/itkNeighborhood.hxx b/Modules/Core/Common/include/itkNeighborhood.hxx index f4db3c812ed..5f9b70991ee 100644 --- a/Modules/Core/Common/include/itkNeighborhood.hxx +++ b/Modules/Core/Common/include/itkNeighborhood.hxx @@ -41,17 +41,17 @@ Neighborhood::ComputeNeighborhoodOffsetTable() { m_OffsetTable.clear(); m_OffsetTable.reserve(this->Size()); - OffsetType o; - DimensionValueType i, j; - for (j = 0; j < VDimension; ++j) + + OffsetType o; + for (DimensionValueType j = 0; j < VDimension; ++j) { o[j] = -(static_cast(this->GetRadius(j))); } - for (i = 0; i < this->Size(); ++i) + for (DimensionValueType i = 0; i < this->Size(); ++i) { m_OffsetTable.push_back(o); - for (j = 0; j < VDimension; ++j) + for (DimensionValueType j = 0; j < VDimension; ++j) { o[j] = o[j] + 1; if (o[j] > static_cast(this->GetRadius(j))) @@ -70,12 +70,7 @@ template void Neighborhood::SetRadius(const SizeValueType s) { - SizeType k; - - for (DimensionValueType i = 0; i < VDimension; ++i) - { - k[i] = s; - } + auto k = MakeFilled(s); this->SetRadius(k); } diff --git a/Modules/Core/Common/include/itkNeighborhoodAccessorFunctor.h b/Modules/Core/Common/include/itkNeighborhoodAccessorFunctor.h index e51bd9e147c..e0b1ee4faf8 100644 --- a/Modules/Core/Common/include/itkNeighborhoodAccessorFunctor.h +++ b/Modules/Core/Common/include/itkNeighborhoodAccessorFunctor.h @@ -88,7 +88,9 @@ class ITK_TEMPLATE_EXPORT NeighborhoodAccessorFunctor final return boundaryCondition->operator()(point_index, boundary_offset, data); } - void SetVectorLength(VectorLengthType) {} + void + SetVectorLength(VectorLengthType) + {} VectorLengthType SetVectorLength() { diff --git a/Modules/Core/Common/include/itkNeighborhoodAlgorithm.hxx b/Modules/Core/Common/include/itkNeighborhoodAlgorithm.hxx index 39e63b41c4a..8ee39307a36 100644 --- a/Modules/Core/Common/include/itkNeighborhoodAlgorithm.hxx +++ b/Modules/Core/Common/include/itkNeighborhoodAlgorithm.hxx @@ -173,12 +173,10 @@ ImageBoundaryFacesCalculator::operator()(const TImage * img, RegionType { return FaceListType{}; } - else - { - FaceListType faceList = std::move(result.m_BoundaryFaces); - faceList.push_front(result.m_NonBoundaryRegion); - return faceList; - } + + FaceListType faceList = std::move(result.m_BoundaryFaces); + faceList.push_front(result.m_NonBoundaryRegion); + return faceList; } diff --git a/Modules/Core/Common/include/itkNeighborhoodAllocator.h b/Modules/Core/Common/include/itkNeighborhoodAllocator.h index fb66cd8ddcd..c4d6f362fde 100644 --- a/Modules/Core/Common/include/itkNeighborhoodAllocator.h +++ b/Modules/Core/Common/include/itkNeighborhoodAllocator.h @@ -93,7 +93,6 @@ class NeighborhoodAllocator other.m_ElementCount = 0; } - /** Assignment operator. */ Self & operator=(const Self & other) @@ -106,7 +105,6 @@ class NeighborhoodAllocator return *this; } - /** Move-assignment. */ Self & operator=(Self && other) noexcept @@ -120,8 +118,8 @@ class NeighborhoodAllocator return *this; } - /** STL-style iterator support for the memory buffer. */ + /** @ITKStartGrouping */ iterator begin() { @@ -147,10 +145,21 @@ class NeighborhoodAllocator { return m_ElementCount; } + /** @ITKEndGrouping */ /** Data access methods */ - const TPixel & operator[](unsigned int i) const { return m_Data[i]; } - TPixel & operator[](unsigned int i) { return m_Data[i]; } + /** @ITKStartGrouping */ + const TPixel & + operator[](unsigned int i) const + { + return m_Data[i]; + } + TPixel & + operator[](unsigned int i) + { + return m_Data[i]; + } + /** @ITKEndGrouping */ /** Allocates a buffer of size n */ void diff --git a/Modules/Core/Common/include/itkNeighborhoodInnerProduct.h b/Modules/Core/Common/include/itkNeighborhoodInnerProduct.h index ce03840d54c..e2d63c17e17 100644 --- a/Modules/Core/Common/include/itkNeighborhoodInnerProduct.h +++ b/Modules/Core/Common/include/itkNeighborhoodInnerProduct.h @@ -76,7 +76,7 @@ class ITK_TEMPLATE_EXPORT NeighborhoodInnerProduct const unsigned int start = 0, const unsigned int stride = 1); - /** Reference oeprator. */ + /** Reference operator. */ OutputPixelType operator()(const std::slice & s, const ConstNeighborhoodIterator & it, const OperatorType & op) const { diff --git a/Modules/Core/Common/include/itkNeighborhoodIterator.h b/Modules/Core/Common/include/itkNeighborhoodIterator.h index a1d7f855bad..b29c13077b9 100644 --- a/Modules/Core/Common/include/itkNeighborhoodIterator.h +++ b/Modules/Core/Common/include/itkNeighborhoodIterator.h @@ -262,8 +262,8 @@ class ITK_TEMPLATE_EXPORT NeighborhoodIterator : public ConstNeighborhoodIterato } /** Returns the central pixel of the neighborhood. */ - ITK_ITERATOR_VIRTUAL void - SetCenterPixel(const PixelType & p) ITK_ITERATOR_FINAL + void + SetCenterPixel(const PixelType & p) { this->m_NeighborhoodAccessorFunctor.Set(this->operator[]((this->Size()) >> 1), p); } @@ -271,23 +271,23 @@ class ITK_TEMPLATE_EXPORT NeighborhoodIterator : public ConstNeighborhoodIterato /** Virtual function that replaces the pixel values in the image * neighborhood that are pointed to by this NeighborhoodIterator with * the pixel values contained in a Neighborhood. */ - ITK_ITERATOR_VIRTUAL void - SetNeighborhood(const NeighborhoodType &) ITK_ITERATOR_FINAL; + void + SetNeighborhood(const NeighborhoodType &); /** Special SetPixel method which quietly ignores out-of-bounds attempts. * Sets status TRUE if pixel has been set, FALSE otherwise. */ - ITK_ITERATOR_VIRTUAL void - SetPixel(const unsigned int i, const PixelType & v, bool & status) ITK_ITERATOR_FINAL; + void + SetPixel(const unsigned int n, const PixelType & v, bool & status); /** Set the pixel at the ith location. */ - ITK_ITERATOR_VIRTUAL void - SetPixel(const unsigned int i, const PixelType & v) ITK_ITERATOR_FINAL; + void + SetPixel(const unsigned int n, const PixelType & v); // { *(this->operator[](i)) = v; } /** Set the pixel at offset o from the neighborhood center */ - ITK_ITERATOR_VIRTUAL void - SetPixel(const OffsetType o, const PixelType & v) ITK_ITERATOR_FINAL + void + SetPixel(const OffsetType o, const PixelType & v) { this->SetPixel(this->GetNeighborhoodIndex(o), v); } @@ -296,8 +296,8 @@ class ITK_TEMPLATE_EXPORT NeighborhoodIterator : public ConstNeighborhoodIterato /** Sets the pixel value located i pixels distant from the neighborhood center in the positive specified "axis" direction. No bounds checking is done on the size of the neighborhood. */ - ITK_ITERATOR_VIRTUAL void - SetNext(const unsigned int axis, const unsigned int i, const PixelType & v) ITK_ITERATOR_FINAL + void + SetNext(const unsigned int axis, const unsigned int i, const PixelType & v) { this->SetPixel(this->GetCenterNeighborhoodIndex() + (i * this->GetStride(axis)), v); } @@ -305,8 +305,8 @@ class ITK_TEMPLATE_EXPORT NeighborhoodIterator : public ConstNeighborhoodIterato /** Sets the pixel value located one pixel distant from the neighborhood center in the specified positive axis direction. No bounds checking is done on the size of the neighborhood. */ - ITK_ITERATOR_VIRTUAL void - SetNext(const unsigned int axis, const PixelType & v) ITK_ITERATOR_FINAL + void + SetNext(const unsigned int axis, const PixelType & v) { this->SetPixel(this->GetCenterNeighborhoodIndex() + this->GetStride(axis), v); } @@ -314,8 +314,8 @@ class ITK_TEMPLATE_EXPORT NeighborhoodIterator : public ConstNeighborhoodIterato /** Sets the pixel value located i pixels distant from the neighborhood center in the negative specified "axis" direction. No bounds checking is done on the size of the neighborhood. */ - ITK_ITERATOR_VIRTUAL void - SetPrevious(const unsigned int axis, const unsigned int i, const PixelType & v) ITK_ITERATOR_FINAL + void + SetPrevious(const unsigned int axis, const unsigned int i, const PixelType & v) { this->SetPixel(this->GetCenterNeighborhoodIndex() - (i * this->GetStride(axis)), v); } @@ -323,8 +323,8 @@ class ITK_TEMPLATE_EXPORT NeighborhoodIterator : public ConstNeighborhoodIterato /** Sets the pixel value located one pixel distant from the neighborhood center in the specified negative axis direction. No bounds checking is done on the size of the neighborhood. */ - ITK_ITERATOR_VIRTUAL void - SetPrevious(const unsigned int axis, const PixelType & v) ITK_ITERATOR_FINAL + void + SetPrevious(const unsigned int axis, const PixelType & v) { this->SetPixel(this->GetCenterNeighborhoodIndex() - this->GetStride(axis), v); } diff --git a/Modules/Core/Common/include/itkNeighborhoodIterator.hxx b/Modules/Core/Common/include/itkNeighborhoodIterator.hxx index 14a9ab08d09..befdd2266f7 100644 --- a/Modules/Core/Common/include/itkNeighborhoodIterator.hxx +++ b/Modules/Core/Common/include/itkNeighborhoodIterator.hxx @@ -97,10 +97,7 @@ template void NeighborhoodIterator::SetPixel(const unsigned int n, const PixelType & v, bool & status) { - unsigned int i; - OffsetType temp; - typename OffsetType::OffsetValueType OverlapLow, OverlapHigh; if (this->m_NeedToUseBoundaryCondition == false) { @@ -117,18 +114,18 @@ NeighborhoodIterator::SetPixel(const unsigned int n, } else { - temp = this->ComputeInternalIndex(n); + OffsetType temp = this->ComputeInternalIndex(n); // Calculate overlap. // Here, we are checking whether the particular pixel in the // neighborhood is within the bounds (when the neighborhood is not // completely in bounds, it is usually partly in bounds) - for (i = 0; i < Superclass::Dimension; ++i) + for (unsigned int i = 0; i < Superclass::Dimension; ++i) { if (!this->m_InBounds[i]) // Part of dimension spills out of bounds { - OverlapLow = this->m_InnerBoundsLow[i] - this->m_Loop[i]; - OverlapHigh = + const typename OffsetType::OffsetValueType OverlapLow = this->m_InnerBoundsLow[i] - this->m_Loop[i]; + const auto OverlapHigh = static_cast(this->GetSize(i) - ((this->m_Loop[i] + 2) - this->m_InnerBoundsHigh[i])); if (temp[i] < OverlapLow || OverlapHigh < temp[i]) { @@ -147,25 +144,22 @@ template void NeighborhoodIterator::SetNeighborhood(const NeighborhoodType & N) { - unsigned int i; - OffsetType OverlapLow, OverlapHigh, temp; - bool flag; - const Iterator _end = this->End(); - Iterator this_it; typename NeighborhoodType::ConstIterator N_it; if (this->m_NeedToUseBoundaryCondition == false) { - for (N_it = N.Begin(), this_it = this->Begin(); this_it < _end; ++this_it, ++N_it) + Iterator this_it = this->Begin(); + for (N_it = N.Begin(); this_it < _end; ++this_it, ++N_it) { this->m_NeighborhoodAccessorFunctor.Set(*this_it, *N_it); } } else if (this->InBounds()) { - for (N_it = N.Begin(), this_it = this->Begin(); this_it < _end; ++this_it, ++N_it) + Iterator this_it = this->Begin(); + for (N_it = N.Begin(); this_it < _end; ++this_it, ++N_it) { this->m_NeighborhoodAccessorFunctor.Set(*this_it, *N_it); } @@ -173,19 +167,22 @@ NeighborhoodIterator::SetNeighborhood(const Neighbor else { // Calculate overlap & initialize index - for (i = 0; i < Superclass::Dimension; ++i) + OffsetType OverlapLow; + OffsetType OverlapHigh; + OffsetType temp{ 0 }; + for (unsigned int i = 0; i < Superclass::Dimension; ++i) { OverlapLow[i] = this->m_InnerBoundsLow[i] - this->m_Loop[i]; OverlapHigh[i] = static_cast(this->GetSize(i) - (this->m_Loop[i] - this->m_InnerBoundsHigh[i]) - 1); - temp[i] = 0; } // Iterate through neighborhood - for (N_it = N.Begin(), this_it = this->Begin(); this_it < _end; ++N_it, ++this_it) + Iterator this_it = this->Begin(); + for (N_it = N.Begin(); this_it < _end; ++N_it, ++this_it) { - flag = true; - for (i = 0; i < Superclass::Dimension; ++i) + bool flag = true; + for (unsigned int i = 0; i < Superclass::Dimension; ++i) { if (!this->m_InBounds[i] && ((temp[i] < OverlapLow[i]) || (temp[i] >= OverlapHigh[i]))) { @@ -199,7 +196,7 @@ NeighborhoodIterator::SetNeighborhood(const Neighbor this->m_NeighborhoodAccessorFunctor.Set(*this_it, *N_it); } - for (i = 0; i < Superclass::Dimension; ++i) // Update index + for (unsigned int i = 0; i < Superclass::Dimension; ++i) // Update index { temp[i]++; if (static_cast(temp[i]) == this->GetSize(i)) diff --git a/Modules/Core/Common/include/itkNeighborhoodIteratorTestCommon.hxx b/Modules/Core/Common/include/itkNeighborhoodIteratorTestCommon.hxx index ec1ff550488..f10f6685850 100644 --- a/Modules/Core/Common/include/itkNeighborhoodIteratorTestCommon.hxx +++ b/Modules/Core/Common/include/itkNeighborhoodIteratorTestCommon.hxx @@ -68,15 +68,13 @@ FillImage(itk::Image, VDimension> * img) using ImageType = itk::Image; const itk::Size size = img->GetRequestedRegion().GetSize(); - unsigned int i; - IndexType loop; - loop.Fill(0); + IndexType loop{}; itk::ImageRegionIterator it(img, img->GetRequestedRegion()); while (!it.IsAtEnd()) { it.Value() = loop; - for (i = 0; i < VDimension; ++i) + for (unsigned int i = 0; i < VDimension; ++i) { loop[i]++; if (static_cast(loop[i]) == size[i]) diff --git a/Modules/Core/Common/include/itkNeighborhoodOperator.h b/Modules/Core/Common/include/itkNeighborhoodOperator.h index 55232f9e845..3fb083e5a9c 100644 --- a/Modules/Core/Common/include/itkNeighborhoodOperator.h +++ b/Modules/Core/Common/include/itkNeighborhoodOperator.h @@ -91,7 +91,7 @@ class ITK_TEMPLATE_EXPORT NeighborhoodOperator : public Neighborhood= VDimension) { @@ -102,7 +102,7 @@ class ITK_TEMPLATE_EXPORT NeighborhoodOperator : public Neighborhood ITKCommon_EXPORT std::string -NumberToString::operator()(double val) const; + NumberToString::operator()(double val) const; template <> ITKCommon_EXPORT std::string -NumberToString::operator()(float val) const; + NumberToString::operator()(float val) const; template <> class NumberToString diff --git a/Modules/Core/Common/include/itkNumericTraits.h b/Modules/Core/Common/include/itkNumericTraits.h index ae4bd04fbb2..65dcdaf3f7a 100644 --- a/Modules/Core/Common/include/itkNumericTraits.h +++ b/Modules/Core/Common/include/itkNumericTraits.h @@ -27,7 +27,8 @@ static constexpr ValueType min(ValueType) { return std::numeric_limits::min(); } \ static constexpr ValueType max(ValueType) { return std::numeric_limits::max(); } \ static constexpr ValueType min() { return std::numeric_limits::min(); } \ - static constexpr ValueType max() { return std::numeric_limits::max(); } + static constexpr ValueType max() { return std::numeric_limits::max(); } \ + ITK_MACROEND_NOOP_STATEMENT #include // for std::numeric_limits #include @@ -307,14 +308,14 @@ class NumericTraits : public std::numeric_limits return !val; } static constexpr bool - IsNegative(bool val) + IsNegative(bool itkNotUsed(val)) { - return val ? false : false; + return false; } static constexpr bool - IsNonnegative(bool val) + IsNonnegative(bool itkNotUsed(val)) { - return val ? true : true; + return true; } static constexpr bool IsSigned = false; static constexpr bool IsInteger = true; @@ -639,14 +640,14 @@ class NumericTraits : public std::numeric_limits return val == Zero; } static constexpr bool - IsNegative(unsigned char val) + IsNegative(unsigned char itkNotUsed(val)) { - return val ? false : false; + return false; } static constexpr bool - IsNonnegative(unsigned char val) + IsNonnegative(unsigned char itkNotUsed(val)) { - return val ? true : true; + return true; } static constexpr bool IsSigned = false; static constexpr bool IsInteger = true; @@ -844,14 +845,14 @@ class NumericTraits : public std::numeric_limits return val == Zero; } static constexpr bool - IsNegative(unsigned short val) + IsNegative(unsigned short itkNotUsed(val)) { - return val ? false : false; + return false; } static constexpr bool - IsNonnegative(unsigned short val) + IsNonnegative(unsigned short itkNotUsed(val)) { - return val ? true : true; + return true; } static constexpr bool IsSigned = false; static constexpr bool IsInteger = true; @@ -1068,14 +1069,14 @@ class NumericTraits : public std::numeric_limits return val == Zero; } static constexpr bool - IsNegative(unsigned int val) + IsNegative(unsigned int itkNotUsed(val)) { - return val ? false : false; + return false; } static constexpr bool - IsNonnegative(unsigned int val) + IsNonnegative(unsigned int itkNotUsed(val)) { - return val ? true : true; + return true; } static constexpr bool IsSigned = false; static constexpr bool IsInteger = true; @@ -1798,8 +1799,16 @@ class NumericTraits : public std::numeric_limits> { return std::numeric_limits::max(); } - static constexpr Self min(Self) { return min(); } - static constexpr Self max(Self) { return max(); } + static constexpr Self + min(Self) + { + return min(); + } + static constexpr Self + max(Self) + { + return max(); + } static constexpr ValueType epsilon() { diff --git a/Modules/Core/Common/include/itkNumericTraitsFixedArrayPixel.h b/Modules/Core/Common/include/itkNumericTraitsFixedArrayPixel.h index e3ffb5483c7..3e5ec2590e1 100644 --- a/Modules/Core/Common/include/itkNumericTraitsFixedArrayPixel.h +++ b/Modules/Core/Common/include/itkNumericTraitsFixedArrayPixel.h @@ -204,7 +204,8 @@ class NumericTraits> MakeFilled>(NumericTraits::Zero); \ template <> \ ITKCommon_EXPORT const GENERIC_ARRAY NumericTraits>::One = \ - MakeFilled>(NumericTraits::One); + MakeFilled>(NumericTraits::One); \ + ITK_MACROEND_NOOP_STATEMENT // // List here the array dimension specializations of these static @@ -220,7 +221,8 @@ class NumericTraits> itkStaticNumericTraitsGenericArrayMacro(GENERIC_ARRAY, T, 7); \ itkStaticNumericTraitsGenericArrayMacro(GENERIC_ARRAY, T, 8); \ itkStaticNumericTraitsGenericArrayMacro(GENERIC_ARRAY, T, 9); \ - itkStaticNumericTraitsGenericArrayMacro(GENERIC_ARRAY, T, 10); + itkStaticNumericTraitsGenericArrayMacro(GENERIC_ARRAY, T, 10); \ + ITK_MACROEND_NOOP_STATEMENT } // end namespace itk #endif // itkNumericTraitsFixedArrayPixel_h diff --git a/Modules/Core/Common/include/itkNumericTraitsStdVector.h b/Modules/Core/Common/include/itkNumericTraitsStdVector.h index db00b3b6601..72226b2520b 100644 --- a/Modules/Core/Common/include/itkNumericTraitsStdVector.h +++ b/Modules/Core/Common/include/itkNumericTraitsStdVector.h @@ -96,6 +96,7 @@ class NumericTraits> * \note minimum value for floating pointer types is defined as * minimum positive normalize value. */ + /** @ITKStartGrouping */ static const Self max(const Self & a) { @@ -130,6 +131,7 @@ class NumericTraits> Self b(a.Size(), NumericTraits::NonpositiveMin()); return b; } + /** @ITKEndGrouping */ static constexpr bool IsSigned = std::is_signed_v; static constexpr bool IsInteger = std::is_integral_v; diff --git a/Modules/Core/Common/include/itkObject.h b/Modules/Core/Common/include/itkObject.h index 3f3047670f9..d5a1fb3852e 100644 --- a/Modules/Core/Common/include/itkObject.h +++ b/Modules/Core/Common/include/itkObject.h @@ -152,15 +152,11 @@ class ITKCommon_EXPORT Object : public LightObject * which can be used later to remove the event or retrieve the * command. * - * \note This member function is overloaded for const and non-const, - * just for backward compatibility. Removing the non-const overload - * appears to break the use of SWIG %pythonprepend in + * \note The parameter name `cmd` is part of the interface to SWIG! It is used by the %pythonprepend section in * ITK/Wrapping/Generators/Python/PyBase/pyBase.i */ unsigned long - AddObserver(const EventObject & event, Command *); - unsigned long - AddObserver(const EventObject & event, Command *) const; + AddObserver(const EventObject & event, Command * cmd) const; /** \brief A convenient method to add an C++ lambda function as an observer. * @@ -201,7 +197,7 @@ class ITKCommon_EXPORT Object : public LightObject /** Remove the observer with this tag value. */ void - RemoveObserver(unsigned long tag); + RemoveObserver(unsigned long tag) const; /** Remove all observers . */ void @@ -227,11 +223,12 @@ class ITKCommon_EXPORT Object : public LightObject /** * Set the MetaDataDictionary */ + /** @ITKStartGrouping */ void SetMetaDataDictionary(const MetaDataDictionary & rhs); void SetMetaDataDictionary(MetaDataDictionary && rrhs); - + /** @ITKEndGrouping */ /** * A facility to help application programmers set a * human identifiable name for a given object. @@ -239,9 +236,10 @@ class ITKCommon_EXPORT Object : public LightObject * convenience to allow developers to provide a * name for this object. */ + /** @ITKStartGrouping */ itkSetMacro(ObjectName, std::string); itkGetConstReferenceMacro(ObjectName, std::string); - + /** @ITKEndGrouping */ protected: Object(); ~Object() override; diff --git a/Modules/Core/Common/include/itkObjectFactory.h b/Modules/Core/Common/include/itkObjectFactory.h index 4cc86e928eb..12241cb1bee 100644 --- a/Modules/Core/Common/include/itkObjectFactory.h +++ b/Modules/Core/Common/include/itkObjectFactory.h @@ -58,7 +58,7 @@ class ObjectFactory : public ObjectFactoryBase static typename T::Pointer Create() { - LightObject::Pointer ret = CreateInstance(typeid(T).name()); + const LightObject::Pointer ret = CreateInstance(typeid(T).name()); return dynamic_cast(ret.GetPointer()); } diff --git a/Modules/Core/Common/include/itkObjectFactoryBase.h b/Modules/Core/Common/include/itkObjectFactoryBase.h index 208cf97a23a..f2f53a2bdaf 100644 --- a/Modules/Core/Common/include/itkObjectFactoryBase.h +++ b/Modules/Core/Common/include/itkObjectFactoryBase.h @@ -161,6 +161,7 @@ class ITKCommon_EXPORT ObjectFactoryBase : public Object * versions do not match, an exception will be thrown. When this is false, and * the versions do not match, only a warning message is printed out in the * console, and the factory is still registered. */ + /** @ITKStartGrouping */ static void SetStrictVersionChecking(bool); static void @@ -169,7 +170,7 @@ class ITKCommon_EXPORT ObjectFactoryBase : public Object StrictVersionCheckingOff(); static bool GetStrictVersionChecking(); - + /** @ITKEndGrouping */ /** Return a descriptive string describing the factory. */ virtual const char * GetDescription() const = 0; @@ -218,12 +219,10 @@ class ITKCommon_EXPORT ObjectFactoryBase : public Object {}; // Factory registration, made thread-safe by "magic statics" (as introduced with C++11). - static const FactoryRegistration staticFactoryRegistration = [] { + [[maybe_unused]] static const FactoryRegistration staticFactoryRegistration = [] { RegisterFactoryInternal(TFactory::New()); return FactoryRegistration{}; }(); - - (void)staticFactoryRegistration; } /** Initialize the static members of ObjectFactoryBase. */ @@ -264,10 +263,11 @@ class ITKCommon_EXPORT ObjectFactoryBase : public Object /** Set/Get the pointer to ObjectFactoryBasePrivate. * No concurrent thread safe. */ + /** @ITKStartGrouping */ static void SynchronizeObjectFactoryBase(void * objectFactoryBasePrivate); itkGetGlobalDeclarationMacro(ObjectFactoryBasePrivate, PimplGlobals); - + /** @ITKEndGrouping */ const std::unique_ptr m_OverrideMap; /** Load dynamic factories from the ITK_AUTOLOAD_PATH */ diff --git a/Modules/Core/Common/include/itkObjectStore.h b/Modules/Core/Common/include/itkObjectStore.h index 73d53b1d317..f2a084b8534 100644 --- a/Modules/Core/Common/include/itkObjectStore.h +++ b/Modules/Core/Common/include/itkObjectStore.h @@ -34,7 +34,7 @@ namespace itk class ObjectStoreEnums { public: - /** \class GrowthStrategy + /** * \ingroup ITKCommon * Type of memory allocation strategy */ enum class GrowthStrategy : uint8_t @@ -141,13 +141,15 @@ class ITK_TEMPLATE_EXPORT ObjectStore : public Object Clear(); /** Set/Get the linear growth size */ + /** @ITKStartGrouping */ itkSetMacro(LinearGrowthSize, SizeValueType); itkGetConstMacro(LinearGrowthSize, SizeValueType); - + /** @ITKEndGrouping */ /** Set/Get the growth strategy. */ + /** @ITKStartGrouping */ itkSetEnumMacro(GrowthStrategy, GrowthStrategyEnum); itkGetConstMacro(GrowthStrategy, GrowthStrategyEnum); - + /** @ITKEndGrouping */ /** Set growth strategy to exponential */ void SetGrowthStrategyToExponential() diff --git a/Modules/Core/Common/include/itkObjectStore.hxx b/Modules/Core/Common/include/itkObjectStore.hxx index 74e098f5a07..23481ca8bf2 100644 --- a/Modules/Core/Common/include/itkObjectStore.hxx +++ b/Modules/Core/Common/include/itkObjectStore.hxx @@ -42,7 +42,7 @@ ObjectStore::Reserve(SizeValueType n) // Need to grow. Allocate a new block of memory and copy that block's // pointers into the m_FreeList. Updates m_Size appropriately. - MemoryBlock new_block(n - m_Size); + const MemoryBlock new_block(n - m_Size); m_Store.push_back(new_block); m_FreeList.reserve(n); diff --git a/Modules/Core/Common/include/itkOctree.h b/Modules/Core/Common/include/itkOctree.h index 647468bf4cb..d47e918934e 100644 --- a/Modules/Core/Common/include/itkOctree.h +++ b/Modules/Core/Common/include/itkOctree.h @@ -49,9 +49,10 @@ class ITKCommon_EXPORT OctreeBase : public Object #if !defined(ITK_LEGACY_REMOVE) // We need to expose the enum values at the class level // for backwards compatibility - static constexpr OctreeEnum UNKNOWN_PLANE = OctreeEnum::UNKNOWN_PLANE; - static constexpr OctreeEnum SAGITAL_PLANE = OctreeEnum::SAGITAL_PLANE; - static constexpr OctreeEnum CORONAL_PLANE = OctreeEnum::CORONAL_PLANE; + static constexpr OctreeEnum UNKNOWN_PLANE = OctreeEnum::UNKNOWN_PLANE; + static constexpr OctreeEnum SAGITTAL_PLANE = OctreeEnum::SAGITTAL_PLANE; + [[deprecated("Use SAGITTAL_PLANE instead")]] static constexpr OctreeEnum SAGITAL_PLANE = OctreeEnum::SAGITTAL_PLANE; + static constexpr OctreeEnum CORONAL_PLANE = OctreeEnum::CORONAL_PLANE; static constexpr OctreeEnum TRANSVERSE_PLANE = OctreeEnum::TRANSVERSE_PLANE; #endif @@ -134,6 +135,7 @@ class ITK_TEMPLATE_EXPORT Octree : public OctreeBase using Pointer = SmartPointer; using ImageType = Image; using ImageTypePointer = typename ImageType::Pointer; + /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -149,7 +151,8 @@ class ITK_TEMPLATE_EXPORT Octree : public OctreeBase const unsigned int ysize, const unsigned int zsize) override; - void BuildFromImage(Image * fromImage); + void + BuildFromImage(Image * fromImage); Octree(); ~Octree() override; @@ -181,14 +184,17 @@ class ITK_TEMPLATE_EXPORT Octree : public OctreeBase unsigned int GetDepth() override; +#if !defined(ITK_LEGACY_REMOVE) /*** * Exposes enum values for backwards compatibility * */ -#if !defined(ITK_LEGACY_REMOVE) - static constexpr OctreeEnum UNKNOWN_PLANE = OctreeEnum::UNKNOWN_PLANE; - static constexpr OctreeEnum SAGITAL_PLANE = OctreeEnum::SAGITAL_PLANE; - static constexpr OctreeEnum CORONAL_PLANE = OctreeEnum::CORONAL_PLANE; + /** @ITKStartGrouping */ + static constexpr OctreeEnum UNKNOWN_PLANE = OctreeEnum::UNKNOWN_PLANE; + static constexpr OctreeEnum SAGITTAL_PLANE = OctreeEnum::SAGITTAL_PLANE; + [[deprecated("Use SAGITTAL_PLANE instead")]] static constexpr OctreeEnum SAGITAL_PLANE = OctreeEnum::SAGITTAL_PLANE; + static constexpr OctreeEnum CORONAL_PLANE = OctreeEnum::CORONAL_PLANE; static constexpr OctreeEnum TRANSVERSE_PLANE = OctreeEnum::TRANSVERSE_PLANE; + /** @ITKEndGrouping */ #endif OctreeNode * diff --git a/Modules/Core/Common/include/itkOctree.hxx b/Modules/Core/Common/include/itkOctree.hxx index ee246bdc8c6..dbab7a3854c 100644 --- a/Modules/Core/Common/include/itkOctree.hxx +++ b/Modules/Core/Common/include/itkOctree.hxx @@ -87,7 +87,7 @@ OCTREE_OCTANT(const unsigned int VoxX, * \defgroup Octant directional identifying functions * These functions determine if the directions are in the "lower" or * "upper" portion of the Octree in the given directions. - * @{ + * @ITKStartGrouping */ inline unsigned int XF(const unsigned int octantID) @@ -107,7 +107,7 @@ ZF(const unsigned int octantID) return (octantID >> 2) & 1; // Just return 1 if 2nd bit is a one } -/** @} */ // End of defgroup +/** @ITKEndGrouping */ // End of defgroup template int @@ -123,7 +123,9 @@ Octree::GetValue(const unsigned int // Define CurrentOctreeNode at the Octree head Node OctreeNode * CurrentOctreeNode = &m_Tree; // Define the origin of current OctreeNode - unsigned int ox = 0, oy = 0, oz = 0; + unsigned int ox = 0; + unsigned int oy = 0; + unsigned int oz = 0; // Define the halfwidth, this will be changed inside of while loop unsigned int halfwidth = this->m_Width; @@ -178,44 +180,42 @@ Octree::maskToOctree(const TPixel * { return nodeArray[0]; } - else - { - auto * q = new OctreeNodeBranch(this); - { - OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::ZERO); - newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::ZERO)]); - } - { - OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::ONE); - newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::ONE)]); - } - { - OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::TWO); - newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::TWO)]); - } - { - OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::THREE); - newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::THREE)]); - } - { - OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::FOUR); - newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::FOUR)]); - } - { - OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::FIVE); - newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::FIVE)]); - } - { - OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::SIX); - newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::SIX)]); - } - { - OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::SEVEN); - newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::SEVEN)]); - } - return (q); + auto * q = new OctreeNodeBranch(this); + + { + OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::ZERO); + newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::ZERO)]); + } + { + OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::ONE); + newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::ONE)]); + } + { + OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::TWO); + newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::TWO)]); + } + { + OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::THREE); + newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::THREE)]); + } + { + OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::FOUR); + newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::FOUR)]); + } + { + OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::FIVE); + newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::FIVE)]); + } + { + OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::SIX); + newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::SIX)]); + } + { + OctreeNode * newbranch = q->GetLeaf(OctreeNode::LeafIdentifierEnum::SEVEN); + newbranch->SetBranch(nodeArray[static_cast(OctreeNode::LeafIdentifierEnum::SEVEN)]); } + return (q); } template @@ -225,9 +225,9 @@ Octree::BuildFromBuffer(const void const unsigned int ysize, const unsigned int zsize) { - unsigned int maxSize = xsize >= ysize ? (xsize >= zsize ? xsize : zsize) : (ysize >= zsize ? ysize : zsize); - unsigned int width = 1; - unsigned int depth = 0; + const unsigned int maxSize = xsize >= ysize ? (xsize >= zsize ? xsize : zsize) : (ysize >= zsize ? ysize : zsize); + unsigned int width = 1; + unsigned int depth = 0; while (width < maxSize) { diff --git a/Modules/Core/Common/include/itkOctreeNode.h b/Modules/Core/Common/include/itkOctreeNode.h index 0202f1cbb1b..6cd6f328d56 100644 --- a/Modules/Core/Common/include/itkOctreeNode.h +++ b/Modules/Core/Common/include/itkOctreeNode.h @@ -77,15 +77,14 @@ class ITKCommon_EXPORT OctreeNode * \param ChildID The numerical identifier of the desired child. * \return A pointer to the Desired child. NOTE: This is always an * instance of an OctreeNode. - * @{ + * @ITKStartGrouping */ OctreeNode & GetChild(const LeafIdentifierEnum ChildID) const; OctreeNode & GetChild(const LeafIdentifierEnum ChildID); - /** @} - */ + /** @ITKEndGrouping */ /** * Determines the color value of the specified Child for this OctreeNode diff --git a/Modules/Core/Common/include/itkOffset.h b/Modules/Core/Common/include/itkOffset.h index 694bfff02a3..605fee89ee2 100644 --- a/Modules/Core/Common/include/itkOffset.h +++ b/Modules/Core/Common/include/itkOffset.h @@ -26,9 +26,7 @@ namespace itk { -/** - * \struct Offset - * \brief Represent a n-dimensional offset between two n-dimensional indexes of n-dimensional image. +/** \brief Represent a n-dimensional offset between two n-dimensional indexes of n-dimensional image. * * Offset is a templated class to represent a multi-dimensional offset, * i.e. (i,j,k,...). Offset is templated over the dimension of the space. @@ -172,7 +170,6 @@ struct ITK_TEMPLATE_EXPORT Offset final return *this; } - /** Get the offset. This provides a read only pointer to the offset. * \sa SetOffset() */ const OffsetValueType * @@ -241,9 +238,9 @@ struct ITK_TEMPLATE_EXPORT Offset final alignas(OffsetValueType) OffsetValueType m_InternalArray[VDimension]; /** Copy values from a FixedArray by rounding each one of the components */ - template + template inline void - CopyWithRound(const FixedArray & point) + CopyWithRound(const FixedArray & point) { for (unsigned int i = 0; i < VDimension; ++i) { @@ -252,9 +249,9 @@ struct ITK_TEMPLATE_EXPORT Offset final } /** Copy values from a FixedArray by casting each one of the components */ - template + template inline void - CopyWithCast(const FixedArray & point) + CopyWithCast(const FixedArray & point) { for (unsigned int i = 0; i < VDimension; ++i) { @@ -296,7 +293,7 @@ struct ITK_TEMPLATE_EXPORT Offset final } void - swap(Offset & other) + swap(Offset & other) noexcept { std::swap(m_InternalArray, other.m_InternalArray); } @@ -379,9 +376,17 @@ struct ITK_TEMPLATE_EXPORT Offset final return false; } - reference operator[](size_type pos) { return m_InternalArray[pos]; } + reference + operator[](size_type pos) + { + return m_InternalArray[pos]; + } - const_reference operator[](size_type pos) const { return m_InternalArray[pos]; } + const_reference + operator[](size_type pos) const + { + return m_InternalArray[pos]; + } reference at(size_type pos) @@ -397,25 +402,25 @@ struct ITK_TEMPLATE_EXPORT Offset final return m_InternalArray[pos]; } - reference + constexpr reference front() { return *begin(); } - const_reference + constexpr const_reference front() const { return *begin(); } - reference + constexpr reference back() { return VDimension ? *(end() - 1) : *end(); } - const_reference + constexpr const_reference back() const { return VDimension ? *(end() - 1) : *end(); @@ -449,9 +454,7 @@ template Offset Offset::GetBasisOffset(unsigned int dim) { - Self ind; - - memset(ind.m_InternalArray, 0, sizeof(OffsetValueType) * VDimension); + Self ind{}; ind.m_InternalArray[dim] = 1; return ind; } @@ -461,12 +464,12 @@ std::ostream & operator<<(std::ostream & os, const Offset & ind) { os << '['; - unsigned int dimlim = VDimension - 1; + const unsigned int dimlim = VDimension - 1; for (unsigned int i = 0; i < dimlim; ++i) { os << ind[i] << ", "; } - if (VDimension >= 1) + if constexpr (VDimension >= 1) { os << ind[VDimension - 1]; } @@ -521,7 +524,7 @@ operator>=(const Offset & one, const Offset & two) // Specialized algorithms [6.2.2.2]. template inline void -swap(Offset & one, Offset & two) +swap(Offset & one, Offset & two) noexcept { std::swap(one.m_InternalArray, two.m_InternalArray); } diff --git a/Modules/Core/Common/include/itkOptimizerParameters.h b/Modules/Core/Common/include/itkOptimizerParameters.h index 2139b9606cf..e285507f658 100644 --- a/Modules/Core/Common/include/itkOptimizerParameters.h +++ b/Modules/Core/Common/include/itkOptimizerParameters.h @@ -154,6 +154,7 @@ class ITK_TEMPLATE_EXPORT OptimizerParameters : public ArrayArrayType::operator=(rhs); return *this; } + /** @ITKEndGrouping */ ~OptimizerParameters() override = default; diff --git a/Modules/Core/Common/include/itkOrientationAdapterBase.h b/Modules/Core/Common/include/itkOrientationAdapterBase.h index 30f47b3b0b8..7e7ad026e82 100644 --- a/Modules/Core/Common/include/itkOrientationAdapterBase.h +++ b/Modules/Core/Common/include/itkOrientationAdapterBase.h @@ -53,15 +53,19 @@ class ITK_TEMPLATE_EXPORT [[deprecated("Since ITK 5.3 use SpatialOrientationAdap using DirectionType = typename ImageType::DirectionType; /** Convert direction cosines to the Orientation type */ - virtual OrientationType FromDirectionCosines(const DirectionType & Dir) = 0; + virtual OrientationType + FromDirectionCosines(const DirectionType & Dir) = 0; /** Convert Orientation type direction cosines */ - virtual DirectionType ToDirectionCosines(const OrientationType & Orient) = 0; + virtual DirectionType + ToDirectionCosines(const OrientationType & Orient) = 0; protected: /** destructor, to silence "virtual class has non-virtual destructor()" warnings */ + /** @ITKStartGrouping */ virtual ~OrientationAdapterBase() = default; + /** @ITKEndGrouping */ }; } // namespace itk #else // ITK_LEGACY_REMOVE diff --git a/Modules/Core/Common/include/itkOutputWindow.h b/Modules/Core/Common/include/itkOutputWindow.h index 8afd0ed7b11..22095c625fa 100644 --- a/Modules/Core/Common/include/itkOutputWindow.h +++ b/Modules/Core/Common/include/itkOutputWindow.h @@ -121,10 +121,11 @@ class ITKCommon_EXPORT OutputWindow : public Object /** If PromptUser is set to true then each time a line of text * is displayed, the user is asked if they want to keep getting * messages. */ + /** @ITKStartGrouping */ itkSetMacro(PromptUser, bool); itkGetConstMacro(PromptUser, bool); itkBooleanMacro(PromptUser); - + /** @ITKEndGrouping */ protected: OutputWindow(); ~OutputWindow() override; diff --git a/Modules/Core/Common/include/itkPeriodicBoundaryCondition.hxx b/Modules/Core/Common/include/itkPeriodicBoundaryCondition.hxx index caba00b5658..db0fb175623 100644 --- a/Modules/Core/Common/include/itkPeriodicBoundaryCondition.hxx +++ b/Modules/Core/Common/include/itkPeriodicBoundaryCondition.hxx @@ -31,21 +31,19 @@ PeriodicBoundaryCondition::operator()(const OffsetTyp // This is guaranteed to be called with an object that is using // PeriodicBoundaryCondition const auto * iterator = reinterpret_cast *>(data); - typename TInputImage::PixelType * ptr; - int linear_index = 0; - unsigned int i; + int linear_index = 0; // Find the pointer of the closest boundary pixel // Return the value of the pixel at the closest boundary point. - for (i = 0; i < ImageDimension; ++i) + for (unsigned int i = 0; i < ImageDimension; ++i) { linear_index += (point_index[i] + boundary_offset[i]) * data->GetStride(i); } // (data->operator[](linear_index)) is guaranteed to be a pointer to // TInputImage::PixelType except for VectorImage, in which case, it will be a // pointer to TInputImage::InternalPixelType. - ptr = reinterpret_cast((data->operator[](linear_index))); + typename TInputImage::PixelType * ptr = reinterpret_cast((data->operator[](linear_index))); // Wrap the pointer around the image in the necessary dimensions. If we have // reached this point, we can assume that we are on the edge of the BUFFERED @@ -55,7 +53,7 @@ PeriodicBoundaryCondition::operator()(const OffsetTyp // These are the step sizes for increments in each dimension of the image. const typename TInputImage::OffsetValueType * offset_table = iterator->GetImagePointer()->GetOffsetTable(); - for (i = 0; i < ImageDimension; ++i) + for (unsigned int i = 0; i < ImageDimension; ++i) { if (boundary_offset[i] != 0) { // If the neighborhood overlaps on the low edge, then wrap from the @@ -87,20 +85,18 @@ PeriodicBoundaryCondition::operator()( // This is guaranteed to be called with an object that is using // PeriodicBoundaryCondition const auto * iterator = reinterpret_cast *>(data); - typename TInputImage::InternalPixelType * ptr; - int linear_index = 0; - unsigned int i; + int linear_index = 0; // Find the pointer of the closest boundary pixel // std::cout << "Boundary offset = " << boundary_offset << std::endl; // std::cout << "point index = " << point_index << std::endl; // Return the value of the pixel at the closest boundary point. - for (i = 0; i < ImageDimension; ++i) + for (unsigned int i = 0; i < ImageDimension; ++i) { linear_index += (point_index[i] + boundary_offset[i]) * data->GetStride(i); } - ptr = data->operator[](linear_index); + typename TInputImage::InternalPixelType * ptr = data->operator[](linear_index); // Wrap the pointer around the image in the necessary dimensions. If we have // reached this point, we can assume that we are on the edge of the BUFFERED @@ -110,7 +106,7 @@ PeriodicBoundaryCondition::operator()( // These are the step sizes for increments in each dimension of the image. const typename TInputImage::OffsetValueType * offset_table = iterator->GetImagePointer()->GetOffsetTable(); - for (i = 0; i < ImageDimension; ++i) + for (unsigned int i = 0; i < ImageDimension; ++i) { if (boundary_offset[i] != 0) { // If the neighborhood overlaps on the low edge, then wrap from the @@ -155,9 +151,9 @@ PeriodicBoundaryCondition::GetInputRequestedRegion( { lowIndex += static_cast(imageSize[i]); } - IndexValueType highIndex = lowIndex + static_cast(outputSize[i]); + const IndexValueType highIndex = lowIndex + static_cast(outputSize[i]); - bool overlap = (highIndex >= static_cast(imageSize[i])); + const bool overlap = (highIndex >= static_cast(imageSize[i])); if (overlap) { @@ -172,7 +168,7 @@ PeriodicBoundaryCondition::GetInputRequestedRegion( inputRequestedSize[i] = outputSize[i]; } } - RegionType inputRequestedRegion(inputRequestedIndex, inputRequestedSize); + const RegionType inputRequestedRegion(inputRequestedIndex, inputRequestedSize); return inputRequestedRegion; } @@ -183,9 +179,9 @@ auto PeriodicBoundaryCondition::GetPixel(const IndexType & index, const TInputImage * image) const -> OutputPixelType { - RegionType imageRegion = image->GetLargestPossibleRegion(); - IndexType imageIndex = imageRegion.GetIndex(); - SizeType imageSize = imageRegion.GetSize(); + const RegionType imageRegion = image->GetLargestPossibleRegion(); + IndexType imageIndex = imageRegion.GetIndex(); + SizeType imageSize = imageRegion.GetSize(); IndexType lookupIndex; diff --git a/Modules/Core/Common/include/itkPhasedArray3DSpecialCoordinatesImage.h b/Modules/Core/Common/include/itkPhasedArray3DSpecialCoordinatesImage.h index df4a79eec02..97a8c970224 100644 --- a/Modules/Core/Common/include/itkPhasedArray3DSpecialCoordinatesImage.h +++ b/Modules/Core/Common/include/itkPhasedArray3DSpecialCoordinatesImage.h @@ -182,29 +182,29 @@ class ITK_TEMPLATE_EXPORT PhasedArray3DSpecialCoordinatesImage : public SpecialC using PixelContainerConstPointer = typename PixelContainer::ConstPointer; /** Returns the continuous index from a physical point */ - template + template [[nodiscard]] ContinuousIndex - TransformPhysicalPointToContinuousIndex(const Point & point) const + TransformPhysicalPointToContinuousIndex(const Point & point) const { const RegionType region = this->GetLargestPossibleRegion(); const double maxAzimuth = region.GetSize(0) - 1; const double maxElevation = region.GetSize(1) - 1; // Convert Cartesian coordinates into angular coordinates - TCoordRep azimuth = Math::pi_over_2; - TCoordRep elevation = Math::pi_over_2; + TCoordinate azimuth = Math::pi_over_2; + TCoordinate elevation = Math::pi_over_2; if (point[2] != 0.0) { azimuth = std::atan(point[0] / point[2]); elevation = std::atan(point[1] / point[2]); } - const TCoordRep radius = std::sqrt(point[0] * point[0] + point[1] * point[1] + point[2] * point[2]); + const TCoordinate radius = std::sqrt(point[0] * point[0] + point[1] * point[1] + point[2] * point[2]); // Convert the "proper" angular coordinates into index format ContinuousIndex index; - index[0] = static_cast((azimuth / m_AzimuthAngularSeparation) + (maxAzimuth / 2.0)); - index[1] = static_cast((elevation / m_ElevationAngularSeparation) + (maxElevation / 2.0)); - index[2] = static_cast(((radius - m_FirstSampleDistance) / m_RadiusSampleSize)); + index[0] = static_cast((azimuth / m_AzimuthAngularSeparation) + (maxAzimuth / 2.0)); + index[1] = static_cast((elevation / m_ElevationAngularSeparation) + (maxElevation / 2.0)); + index[2] = static_cast(((radius - m_FirstSampleDistance) / m_RadiusSampleSize)); return index; } @@ -216,9 +216,9 @@ class ITK_TEMPLATE_EXPORT PhasedArray3DSpecialCoordinatesImage : public SpecialC * overload instead, which has only one parameter (the point), and returns the continuous index. * * \sa Transform */ - template + template ITK_NODISCARD("Call the overload which has the point as the only parameter and returns the index") - bool TransformPhysicalPointToContinuousIndex(const Point & point, + bool TransformPhysicalPointToContinuousIndex(const Point & point, ContinuousIndex & index) const { index = this->TransformPhysicalPointToContinuousIndex(point); @@ -232,23 +232,23 @@ class ITK_TEMPLATE_EXPORT PhasedArray3DSpecialCoordinatesImage : public SpecialC /** Returns the index (discrete) from a physical point. * Floating point index results are truncated to integers. */ - template + template [[nodiscard]] IndexType - TransformPhysicalPointToIndex(const Point & point) const + TransformPhysicalPointToIndex(const Point & point) const { const RegionType region = this->GetLargestPossibleRegion(); const double maxAzimuth = region.GetSize(0) - 1; const double maxElevation = region.GetSize(1) - 1; // Convert Cartesian coordinates into angular coordinates - TCoordRep azimuth = Math::pi_over_2; - TCoordRep elevation = Math::pi_over_2; + TCoordinate azimuth = Math::pi_over_2; + TCoordinate elevation = Math::pi_over_2; if (point[2] != 0.0) { azimuth = std::atan(point[0] / point[2]); elevation = std::atan(point[1] / point[2]); } - const TCoordRep radius = std::sqrt(point[0] * point[0] + point[1] * point[1] + point[2] * point[2]); + const TCoordinate radius = std::sqrt(point[0] * point[0] + point[1] * point[1] + point[2] * point[2]); // Convert the "proper" angular coordinates into index format IndexType index; @@ -266,9 +266,9 @@ class ITK_TEMPLATE_EXPORT PhasedArray3DSpecialCoordinatesImage : public SpecialC * overload instead, which has only one parameter (the point), and returns the index. * * \sa Transform */ - template + template ITK_NODISCARD("Call the overload which has the point as the only parameter and returns the index") - bool TransformPhysicalPointToIndex(const Point & point, IndexType & index) const + bool TransformPhysicalPointToIndex(const Point & point, IndexType & index) const { index = this->TransformPhysicalPointToIndex(point); @@ -282,36 +282,36 @@ class ITK_TEMPLATE_EXPORT PhasedArray3DSpecialCoordinatesImage : public SpecialC * the origin and spacing information comes from) * from a continuous index (in the index space) * \sa Transform */ - template + template void TransformContinuousIndexToPhysicalPoint(const ContinuousIndex & index, - Point & point) const + Point & point) const { const RegionType region = this->GetLargestPossibleRegion(); const double maxAzimuth = region.GetSize(0) - 1; const double maxElevation = region.GetSize(1) - 1; // Convert the index into proper angular coordinates - const TCoordRep azimuth = (index[0] - (maxAzimuth / 2.0)) * m_AzimuthAngularSeparation; - const TCoordRep elevation = (index[1] - (maxElevation / 2.0)) * m_ElevationAngularSeparation; - const TCoordRep radius = (index[2] * m_RadiusSampleSize) + m_FirstSampleDistance; + const TCoordinate azimuth = (index[0] - (maxAzimuth / 2.0)) * m_AzimuthAngularSeparation; + const TCoordinate elevation = (index[1] - (maxElevation / 2.0)) * m_ElevationAngularSeparation; + const TCoordinate radius = (index[2] * m_RadiusSampleSize) + m_FirstSampleDistance; // Convert the angular coordinates into Cartesian coordinates - const TCoordRep tanOfAzimuth = std::tan(azimuth); - const TCoordRep tanOfElevation = std::tan(elevation); + const TCoordinate tanOfAzimuth = std::tan(azimuth); + const TCoordinate tanOfElevation = std::tan(elevation); point[2] = - static_cast(radius / std::sqrt(1 + tanOfAzimuth * tanOfAzimuth + tanOfElevation * tanOfElevation)); - point[1] = static_cast(point[2] * tanOfElevation); - point[0] = static_cast(point[2] * tanOfAzimuth); + static_cast(radius / std::sqrt(1 + tanOfAzimuth * tanOfAzimuth + tanOfElevation * tanOfElevation)); + point[1] = static_cast(point[2] * tanOfElevation); + point[0] = static_cast(point[2] * tanOfAzimuth); } /** Returns a physical point from a continuous index. */ - template - [[nodiscard]] Point + template + [[nodiscard]] Point TransformContinuousIndexToPhysicalPoint(const ContinuousIndex & index) const { - Point point; + Point point; this->TransformContinuousIndexToPhysicalPoint(index, point); return point; } @@ -321,35 +321,35 @@ class ITK_TEMPLATE_EXPORT PhasedArray3DSpecialCoordinatesImage : public SpecialC * from a discrete index (in the index space) * * \sa Transform */ - template + template void - TransformIndexToPhysicalPoint(const IndexType & index, Point & point) const + TransformIndexToPhysicalPoint(const IndexType & index, Point & point) const { const RegionType region = this->GetLargestPossibleRegion(); const double maxAzimuth = region.GetSize(0) - 1; const double maxElevation = region.GetSize(1) - 1; // Convert the index into proper angular coordinates - const TCoordRep azimuth = (static_cast(index[0]) - (maxAzimuth / 2.0)) * m_AzimuthAngularSeparation; - const TCoordRep elevation = (static_cast(index[1]) - (maxElevation / 2.0)) * m_ElevationAngularSeparation; - const TCoordRep radius = (static_cast(index[2]) * m_RadiusSampleSize) + m_FirstSampleDistance; + const TCoordinate azimuth = (static_cast(index[0]) - (maxAzimuth / 2.0)) * m_AzimuthAngularSeparation; + const TCoordinate elevation = (static_cast(index[1]) - (maxElevation / 2.0)) * m_ElevationAngularSeparation; + const TCoordinate radius = (static_cast(index[2]) * m_RadiusSampleSize) + m_FirstSampleDistance; // Convert the angular coordinates into Cartesian coordinates - const TCoordRep tanOfAzimuth = std::tan(azimuth); - const TCoordRep tanOfElevation = std::tan(elevation); + const TCoordinate tanOfAzimuth = std::tan(azimuth); + const TCoordinate tanOfElevation = std::tan(elevation); point[2] = - static_cast(radius / std::sqrt(1.0 + tanOfAzimuth * tanOfAzimuth + tanOfElevation * tanOfElevation)); - point[1] = static_cast(point[2] * tanOfElevation); - point[0] = static_cast(point[2] * tanOfAzimuth); + static_cast(radius / std::sqrt(1.0 + tanOfAzimuth * tanOfAzimuth + tanOfElevation * tanOfElevation)); + point[1] = static_cast(point[2] * tanOfElevation); + point[0] = static_cast(point[2] * tanOfAzimuth); } /** Returns a physical point from a discrete index. */ - template - [[nodiscard]] Point + template + [[nodiscard]] Point TransformIndexToPhysicalPoint(const IndexType & index) const { - Point point; + Point point; this->TransformIndexToPhysicalPoint(index, point); return point; } @@ -366,13 +366,14 @@ class ITK_TEMPLATE_EXPORT PhasedArray3DSpecialCoordinatesImage : public SpecialC /** Set the distance to add to the radius. */ itkSetMacro(FirstSampleDistance, double); - template - void TransformLocalVectorToPhysicalVector(FixedArray &) const + template + void + TransformLocalVectorToPhysicalVector(FixedArray &) const {} - template + template void - TransformPhysicalVectorToLocalVector(const FixedArray &, FixedArray &) const + TransformPhysicalVectorToLocalVector(const FixedArray &, FixedArray &) const {} /** Return the Pixel Accessor object */ diff --git a/Modules/Core/Common/include/itkPlatformMultiThreader.h b/Modules/Core/Common/include/itkPlatformMultiThreader.h index a03678e8f79..ee0f78f49e4 100644 --- a/Modules/Core/Common/include/itkPlatformMultiThreader.h +++ b/Modules/Core/Common/include/itkPlatformMultiThreader.h @@ -70,6 +70,7 @@ class ITKCommon_EXPORT PlatformMultiThreader : public MultiThreaderBase * are already statically allocated using the ITK_MAX_THREADS number. * Therefore the caller of this method should check that the requested number * of threads was accepted. Legacy: use MultiThreaderBase to invoke these. */ + /** @ITKStartGrouping */ itkLegacyMacro(static void SetGlobalMaximumNumberOfThreads(ThreadIdType val)) { itkGenericOutputMacro("Warning: SetGlobalMaximumNumberOfThreads should now be called on itk::MultiThreaderBase. It " @@ -82,11 +83,13 @@ class ITKCommon_EXPORT PlatformMultiThreader : public MultiThreaderBase "can affect all MultiThreaderBase's derived classes in ITK"); return Superclass::GetGlobalMaximumNumberOfThreads(); } + /** @ITKEndGrouping */ /** Set/Get the value which is used to initialize the NumberOfThreads in the * constructor. It will be clamped to the range [1, m_GlobalMaximumNumberOfThreads ]. * Therefore the caller of this method should check that the requested number * of threads was accepted. Legacy: use MultiThreaderBase to invoke these. */ + /** @ITKStartGrouping */ itkLegacyMacro(static void SetGlobalDefaultNumberOfThreads(ThreadIdType val)) { itkGenericOutputMacro("Warning: SetGlobalDefaultNumberOfThreads should now be called on itk::MultiThreaderBase. It " @@ -99,6 +102,7 @@ class ITKCommon_EXPORT PlatformMultiThreader : public MultiThreaderBase "can affect all MultiThreaderBase's derived classes in ITK"); return Superclass::GetGlobalDefaultNumberOfThreads(); } + /** @ITKEndGrouping */ #endif /** Execute the SingleMethod (as define by SetSingleMethod) using @@ -112,7 +116,7 @@ class ITKCommon_EXPORT PlatformMultiThreader : public MultiThreaderBase * each of the required m_NumberOfWorkUnits methods) using m_NumberOfWorkUnits * threads. As a side effect the m_NumberOfWorkUnits will be checked against the * current m_GlobalMaximumNumberOfThreads and clamped if necessary. */ - itkLegacyMacro(void MultipleMethodExecute()); + itkLegacyMacro(void MultipleMethodExecute();) /** Set the SingleMethod to f() and the UserData field of the * WorkUnitInfo that is passed to it will be data. @@ -124,17 +128,17 @@ class ITKCommon_EXPORT PlatformMultiThreader : public MultiThreaderBase /** Set the MultipleMethod at the given index to f() and the UserData * field of the WorkUnitInfo that is passed to it will be data. */ - itkLegacyMacro(void SetMultipleMethod(ThreadIdType index, ThreadFunctionType, void * data)); + itkLegacyMacro(void SetMultipleMethod(ThreadIdType index, ThreadFunctionType, void * data);) /** Create a new thread for the given function. Return a thread id * which is a number between 0 and ITK_MAX_THREADS - 1. This * id should be used to kill the thread at a later time. * Deprecated. Use C++11 thread support instead. */ - itkLegacyMacro(ThreadIdType SpawnThread(ThreadFunctionType, void * data)); + itkLegacyMacro(ThreadIdType SpawnThread(ThreadFunctionType, void * data);) /** Terminate the thread that was created with a SpawnThreadExecute() * Deprecated. Use C++11 thread support instead. */ - itkLegacyMacro(void TerminateThread(ThreadIdType thread_id)); + itkLegacyMacro(void TerminateThread(ThreadIdType thread_id);) void SetMaximumNumberOfThreads(ThreadIdType numberOfThreads) override; @@ -177,6 +181,7 @@ class ITKCommon_EXPORT PlatformMultiThreader : public MultiThreaderBase /** spawn a new thread for the SingleMethod */ ThreadProcessIdType SpawnDispatchSingleMethodThread(WorkUnitInfo *); + /** wait for a thread in the threadpool to finish work */ void SpawnWaitForSingleMethodThread(ThreadProcessIdType); diff --git a/Modules/Core/Common/include/itkPoint.h b/Modules/Core/Common/include/itkPoint.h index 02122438a7a..e6570b8ae94 100644 --- a/Modules/Core/Common/include/itkPoint.h +++ b/Modules/Core/Common/include/itkPoint.h @@ -49,19 +49,22 @@ namespace itk * \sphinxexample{Core/Common/DistanceBetweenIndices,Distance between two indices} * \endsphinx */ -template -class ITK_TEMPLATE_EXPORT Point : public FixedArray +template +class ITK_TEMPLATE_EXPORT Point : public FixedArray { public: /** Standard class type aliases. */ using Self = Point; - using Superclass = FixedArray; + using Superclass = FixedArray; /** ValueType can be used to declare a variable that is the same type * as a data element held in an Point. */ - using ValueType = TCoordRep; - using CoordinateType = TCoordRep; - using CoordRepType = CoordinateType; + using ValueType = TCoordinate; + using CoordinateType = TCoordinate; +#ifndef ITK_FUTURE_LEGACY_REMOVE + using CoordRepType ITK_FUTURE_DEPRECATED( + "ITK 6 discourages using `CoordRepType`. Please use `CoordinateType` instead!") = CoordinateType; +#endif using RealType = typename NumericTraits::RealType; @@ -69,7 +72,7 @@ class ITK_TEMPLATE_EXPORT Point : public FixedArray static constexpr unsigned int PointDimension = VPointDimension; /** The Array type from which this Vector is derived. */ - using BaseArray = FixedArray; + using BaseArray = FixedArray; using Iterator = typename BaseArray::Iterator; using ConstIterator = typename BaseArray::ConstIterator; @@ -92,7 +95,9 @@ class ITK_TEMPLATE_EXPORT Point : public FixedArray Point(const Point & r) : BaseArray(r) {} + /** Pass-through constructors for plain arrays. */ + /** @ITKStartGrouping */ template Point(const TPointValueType r[VPointDimension]) : BaseArray(r) @@ -100,7 +105,7 @@ class ITK_TEMPLATE_EXPORT Point : public FixedArray Point(const ValueType r[VPointDimension]) : BaseArray(r) {} - + /** @ITKEndGrouping */ #if defined(ITK_LEGACY_REMOVE) /** Prevents copy-initialization from `nullptr`, as well as from `0` (NULL). */ Point(std::nullptr_t) = delete; @@ -114,12 +119,14 @@ class ITK_TEMPLATE_EXPORT Point : public FixedArray : BaseArray(v) {} #else + /** Pass-through constructors for single values * \note ITK_LEGACY_REMOVE=ON will disallow implicit conversion from a single value. */ template Point(const TPointValueType & v) : BaseArray(v) {} + Point(const ValueType & v) : BaseArray(v) {} @@ -168,11 +175,11 @@ class ITK_TEMPLATE_EXPORT Point : public FixedArray GetVectorFromOrigin() const; /** Get a vnl_vector_ref referencing the same memory block */ - vnl_vector_ref + vnl_vector_ref GetVnlVector(); /** Get a vnl_vector with a copy of the internal memory block. */ - vnl_vector + vnl_vector GetVnlVector() const; /** Set to median point between the two points @@ -253,13 +260,13 @@ class ITK_TEMPLATE_EXPORT Point : public FixedArray /** Copy from another Point with a different representation type. * Casting is done with C-Like rules */ - template + template void - CastFrom(const Point & pa) + CastFrom(const Point & pa) { for (unsigned int i = 0; i < VPointDimension; ++i) { - (*this)[i] = static_cast(pa[i]); + (*this)[i] = static_cast(pa[i]); } } @@ -267,9 +274,9 @@ class ITK_TEMPLATE_EXPORT Point : public FixedArray * with a different representation type. Casting is done with * C-Like rules */ - template + template RealType - SquaredEuclideanDistanceTo(const Point & pa) const + SquaredEuclideanDistanceTo(const Point & pa) const { RealType sum{}; @@ -285,9 +292,9 @@ class ITK_TEMPLATE_EXPORT Point : public FixedArray /** Compute the Euclidean Distance from this point to another point * with a different representation type. Casting is done with * C-Like rules */ - template + template RealType - EuclideanDistanceTo(const Point & pa) const + EuclideanDistanceTo(const Point & pa) const { const double distance = std::sqrt(static_cast(this->SquaredEuclideanDistanceTo(pa))); @@ -344,9 +351,9 @@ class ITK_TEMPLATE_EXPORT BarycentricCombination }; -template +template inline void -swap(Point & a, Point & b) +swap(Point & a, Point & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkPoint.hxx b/Modules/Core/Common/include/itkPoint.hxx index 8542e4d6e2c..339d907ef3f 100644 --- a/Modules/Core/Common/include/itkPoint.hxx +++ b/Modules/Core/Common/include/itkPoint.hxx @@ -219,13 +219,11 @@ auto BarycentricCombination::Evaluate(const PointContainerPointer & points, const WeightContainerType & weights) -> PointType { - using ValueType = typename PointType::ValueType; - PointType barycentre; - barycentre.Fill(ValueType{}); // set to null + PointType barycentre{}; // set to null - typename TPointContainer::Iterator point = points->Begin(); - typename TPointContainer::Iterator final = points->End(); - typename TPointContainer::Iterator last = final; + typename TPointContainer::Iterator point = points->Begin(); + const typename TPointContainer::Iterator final = points->End(); + typename TPointContainer::Iterator last = final; --last; // move to the (N)th point double weightSum = 0.0; @@ -263,7 +261,7 @@ std::ostream & operator<<(std::ostream & os, const Point & vct) { os << '['; - if (TPointDimension == 1) + if constexpr (TPointDimension == 1) { os << vct[0]; } diff --git a/Modules/Core/Common/include/itkPointSet.h b/Modules/Core/Common/include/itkPointSet.h index 5fc164ef5d8..00ebff06184 100644 --- a/Modules/Core/Common/include/itkPointSet.h +++ b/Modules/Core/Common/include/itkPointSet.h @@ -28,9 +28,8 @@ #ifndef itkPointSet_h #define itkPointSet_h -#include "itkDataObject.h" +#include "itkPointSetBase.h" #include "itkDefaultStaticMeshTraits.h" -#include #include namespace itk @@ -79,14 +78,14 @@ namespace itk template > -class ITK_TEMPLATE_EXPORT PointSet : public DataObject +class ITK_TEMPLATE_EXPORT PointSet : public PointSetBase { public: ITK_DISALLOW_COPY_AND_MOVE(PointSet); /** Standard class type aliases. */ using Self = PointSet; - using Superclass = DataObject; + using Superclass = PointSetBase; using Pointer = SmartPointer; using ConstPointer = SmartPointer; @@ -101,43 +100,18 @@ class ITK_TEMPLATE_EXPORT PointSet : public DataObject using PixelType = typename MeshTraits::PixelType; /** Convenient type alias obtained from TMeshTraits template parameter. */ - using CoordinateType = typename MeshTraits::CoordRepType; - using CoordRepType = CoordinateType; using PointIdentifier = typename MeshTraits::PointIdentifier; using PointType = typename MeshTraits::PointType; - using PointsContainer = typename MeshTraits::PointsContainer; using PointDataContainer = typename MeshTraits::PointDataContainer; - /** For improving Python support for PointSet and Meshes **/ - using PointsVectorContainer = typename itk::VectorContainer; - using PointsVectorContainerPointer = typename PointsVectorContainer::Pointer; - - /** Convenient type alias obtained from TMeshTraits template parameter. */ - static constexpr unsigned int PointDimension = TMeshTraits::PointDimension; - /** Create types that are pointers to each of the container types. */ - using PointsContainerPointer = typename PointsContainer::Pointer; - using PointsContainerConstPointer = typename PointsContainer::ConstPointer; using PointDataContainerPointer = typename PointDataContainer::Pointer; using PointDataContainerConstPointer = typename PointDataContainer::ConstPointer; /** Create types that are iterators for each of the container types. */ - using PointsContainerConstIterator = typename PointsContainer::ConstIterator; - using PointsContainerIterator = typename PointsContainer::Iterator; using PointDataContainerIterator = typename PointDataContainer::ConstIterator; - /** Type used to define Regions */ - using RegionType = long; - - /** Get the maximum number of regions that this data can be - * separated into. */ - itkGetConstMacro(MaximumNumberOfRegions, RegionType); - protected: - /** An object containing points used by the mesh. Individual points are - * accessed through point identifiers. */ - PointsContainerPointer m_PointsContainer{}; - /** An object containing data associated with the mesh's points. * Optionally, this can be nullptr, indicating that no data are associated with * the points. The data for a point can be accessed through its point @@ -145,38 +119,12 @@ class ITK_TEMPLATE_EXPORT PointSet : public DataObject PointDataContainerPointer m_PointDataContainer{}; public: - /** Copy the geometric and topological structure of the given input pointSet. - * The copying is done via reference counting. - */ - void - PassStructure(Self * inputPointSet); - /** Restore the PointSet to its initial state. Useful for data pipeline updates * without memory re-allocation. */ void Initialize() override; - /** Get the number of points in the points container. */ - PointIdentifier - GetNumberOfPoints() const; - - /** Set the points container. */ - void - SetPoints(PointsContainer *); - - /** Set the points container using a 1D vector. */ - void - SetPoints(PointsVectorContainer *); - - /** Get the points container. */ - PointsContainer * - GetPoints(); - - /** Get the points container. */ - const PointsContainer * - GetPoints() const; - /** Set the point data container. */ void SetPointData(PointDataContainer *); @@ -189,23 +137,6 @@ class ITK_TEMPLATE_EXPORT PointSet : public DataObject const PointDataContainer * GetPointData() const; - /** Assign a point to a point identifier. If a spot for the point identifier - * does not exist, it will be created automatically. - */ - void SetPoint(PointIdentifier, PointType); - - /** Check if a point exists for a given point identifier. If a spot for - * the point identifier exists, the point is set, and true is returned. - * Otherwise, false is returned, and the point is not modified. - * If the point is nullptr, then it is never set, but the existence of the - * point is still returned. - */ - bool - GetPoint(PointIdentifier, PointType *) const; - - /** Get the point for the given point identifier. */ - PointType GetPoint(PointIdentifier) const; - /** Assign data to a point identifier. If a spot for the point identifier * does not exist, it will be created automatically. There is no check if * a point with the same identifier exists. @@ -221,66 +152,20 @@ class ITK_TEMPLATE_EXPORT PointSet : public DataObject bool GetPointData(PointIdentifier, PixelType *) const; - /** Methods to manage streaming. */ - void - UpdateOutputInformation() override; - - void - SetRequestedRegionToLargestPossibleRegion() override; - - void - CopyInformation(const DataObject * data) override; - void Graft(const DataObject * data) override; - bool - RequestedRegionIsOutsideOfTheBufferedRegion() override; - - bool - VerifyRequestedRegion() 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. */ - void - SetRequestedRegion(const DataObject * data) override; - - /** Set/Get the Requested region */ - virtual void - SetRequestedRegion(const RegionType & region); - - itkGetConstMacro(RequestedRegion, RegionType); - - /** Set/Get the Buffered region */ - virtual void - SetBufferedRegion(const RegionType & region); - - itkGetConstMacro(BufferedRegion, RegionType); - protected: /** Constructor for use by New() method. */ + /** @ITKStartGrouping */ PointSet() = default; ~PointSet() override = default; void PrintSelf(std::ostream & os, Indent indent) const override; + /** @ITKEndGrouping */ + LightObject::Pointer + InternalClone() const override; - // If the RegionType is ITK_UNSTRUCTURED_REGION, then the following - // variables represent the maximum number of region that the data - // object can be broken into, which region out of how many is - // currently in the buffered region, and the number of regions and - // the specific region requested for the update. Data objects that - // do not support any division of the data can simply leave the - // MaximumNumberOfRegions as 1. The RequestedNumberOfRegions and - // RequestedRegion are used to define the currently requested - // region. The LargestPossibleRegion is always requested region = 0 - // and number of regions = 1; - RegionType m_MaximumNumberOfRegions{ 1 }; - RegionType m_NumberOfRegions{ 1 }; - RegionType m_RequestedNumberOfRegions{}; - RegionType m_BufferedRegion{ -1 }; - RegionType m_RequestedRegion{ -1 }; }; // End Class: PointSet } // end namespace itk diff --git a/Modules/Core/Common/include/itkPointSet.hxx b/Modules/Core/Common/include/itkPointSet.hxx index 0aed6b93cae..bba950ade26 100644 --- a/Modules/Core/Common/include/itkPointSet.hxx +++ b/Modules/Core/Common/include/itkPointSet.hxx @@ -38,12 +38,6 @@ void PointSet::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - os << indent << "Number Of Points: " << this->GetNumberOfPoints() << std::endl; - - os << indent << "Requested Number Of Regions: " << m_RequestedNumberOfRegions << std::endl; - os << indent << "Requested Region: " << m_RequestedRegion << std::endl; - os << indent << "Buffered Region: " << m_BufferedRegion << std::endl; - os << indent << "Maximum Number Of Regions: " << m_MaximumNumberOfRegions << std::endl; os << indent << "Point Data Container pointer: " << ((this->m_PointDataContainer) ? this->m_PointDataContainer.GetPointer() : nullptr) << std::endl; os << indent @@ -51,55 +45,6 @@ PointSet::PrintSelf(std::ostream & os, Inde << std::endl; } -template -void -PointSet::SetPoints(PointsContainer * points) -{ - itkDebugMacro("setting Points container to " << points); - if (m_PointsContainer != points) - { - m_PointsContainer = points; - this->Modified(); - } -} - -template -void -PointSet::SetPoints(PointsVectorContainer * points) -{ - - itkDebugMacro("setting Points container to " << points); - if (points->Size() % PointDimension != 0) - { - itkExceptionMacro("Number of entries in given 1d array incompatible with the point dimension"); - } - auto * pointsPtr = reinterpret_cast(points); - - m_PointsContainer = pointsPtr; - this->Modified(); -} - -template -auto -PointSet::GetPoints() -> PointsContainer * -{ - itkDebugMacro("Starting GetPoints()"); - if (!m_PointsContainer) - { - this->SetPoints(PointsContainer::New()); - } - itkDebugMacro("returning Points container of " << m_PointsContainer); - return m_PointsContainer; -} - -template -auto -PointSet::GetPoints() const -> const PointsContainer * -{ - itkDebugMacro("returning Points container of " << m_PointsContainer); - return m_PointsContainer.GetPointer(); -} - template void PointSet::SetPointData(PointDataContainer * pointData) @@ -132,66 +77,6 @@ PointSet::GetPointData() const -> const Poi return m_PointDataContainer.GetPointer(); } -template -void -PointSet::SetPoint(PointIdentifier ptId, PointType point) -{ - /** - * Make sure a points container exists. - */ - if (!m_PointsContainer) - { - this->SetPoints(PointsContainer::New()); - } - - /** - * Insert the point into the container with the given identifier. - */ - m_PointsContainer->InsertElement(ptId, point); -} - -template -bool -PointSet::GetPoint(PointIdentifier ptId, PointType * point) const -{ - /** - * If the points container doesn't exist, then the point doesn't either. - */ - if (!m_PointsContainer) - { - return false; - } - - /** - * Ask the container if the point identifier exists. - */ - return m_PointsContainer->GetElementIfIndexExists(ptId, point); -} - -template -auto -PointSet::GetPoint(PointIdentifier ptId) const -> PointType -{ - /** - * If the points container doesn't exist, then the point doesn't either. - */ - if (!m_PointsContainer) - { - itkExceptionMacro("Point container doesn't exist."); - } - - /** - * Ask the container if the point identifier exists. - */ - PointType point; - bool exist = m_PointsContainer->GetElementIfIndexExists(ptId, &point); - if (!exist) - { - itkExceptionMacro("Point id doesn't exist: " << ptId); - } - return point; -} - template void PointSet::SetPointData(PointIdentifier ptId, PixelType data) @@ -229,80 +114,16 @@ PointSet::GetPointData(PointIdentifier ptId return m_PointDataContainer->GetElementIfIndexExists(ptId, data); } -template -void -PointSet::PassStructure(Self *) -{ - // IMPLEMENT ME -} - -template -auto -PointSet::GetNumberOfPoints() const -> PointIdentifier -{ - if (m_PointsContainer) - { - return m_PointsContainer->Size(); - } - return 0; -} - template void PointSet::Initialize() { Superclass::Initialize(); - m_PointsContainer = nullptr; m_PointDataContainer = nullptr; } -template -void -PointSet::UpdateOutputInformation() -{ - this->Superclass::UpdateOutputInformation(); - - // Now we should know what our largest possible region is. If our - // requested region was not set yet, (or has been set to something - // invalid - with no data in it ) then set it to the largest - // possible region. - if (m_RequestedRegion == -1 && m_RequestedNumberOfRegions == 0) - { - this->SetRequestedRegionToLargestPossibleRegion(); - } -} - -template -void -PointSet::SetRequestedRegionToLargestPossibleRegion() -{ - m_RequestedNumberOfRegions = 1; - m_RequestedRegion = 0; -} - -template -void -PointSet::CopyInformation(const DataObject * data) -{ - const auto * pointSet = dynamic_cast(data); - - if (!pointSet) - { - // pointer could not be cast back down - itkExceptionMacro("itk::PointSet::CopyInformation() cannot cast " << typeid(data).name() << " to " - << typeid(PointSet *).name()); - } - - m_MaximumNumberOfRegions = pointSet->GetMaximumNumberOfRegions(); - - m_NumberOfRegions = pointSet->m_NumberOfRegions; - m_RequestedNumberOfRegions = pointSet->m_RequestedNumberOfRegions; - m_BufferedRegion = pointSet->m_BufferedRegion; - m_RequestedRegion = pointSet->m_RequestedRegion; -} - template void PointSet::Graft(const DataObject * data) @@ -315,81 +136,29 @@ PointSet::Graft(const DataObject * data) if (!pointSet) { // pointer could not be cast back down - itkExceptionMacro("itk::PointSet::CopyInformation() cannot cast " << typeid(data).name() << " to " - << typeid(Self *).name()); + itkExceptionMacro("itk::PointSet::Graft() cannot cast " << typeid(data).name() << " to " << typeid(Self *).name()); } - this->SetPoints(pointSet->m_PointsContainer); + this->SetPoints(pointSet->Superclass::m_PointsContainer); this->SetPointData(pointSet->m_PointDataContainer); } template -void -PointSet::SetRequestedRegion(const DataObject * data) -{ - const auto * pointSet = dynamic_cast(data); - - if (pointSet) - { - // only copy the RequestedRegion if the parameter is another PointSet - m_RequestedRegion = pointSet->m_RequestedRegion; - m_RequestedNumberOfRegions = pointSet->m_RequestedNumberOfRegions; - } -} - -template -void -PointSet::SetRequestedRegion(const RegionType & region) -{ - if (m_RequestedRegion != region) - { - m_RequestedRegion = region; - } -} - -template -void -PointSet::SetBufferedRegion(const RegionType & region) -{ - if (m_BufferedRegion != region) - { - m_BufferedRegion = region; - this->Modified(); - } -} - -template -bool -PointSet::RequestedRegionIsOutsideOfTheBufferedRegion() -{ - if (m_RequestedRegion != m_BufferedRegion || m_RequestedNumberOfRegions != m_NumberOfRegions) - { - return true; - } - - return false; -} - -template -bool -PointSet::VerifyRequestedRegion() +LightObject::Pointer +PointSet::InternalClone() const { - bool retval = true; + LightObject::Pointer lightObject = Superclass::InternalClone(); - // Are we asking for more regions than we can get? - if (m_RequestedNumberOfRegions > m_MaximumNumberOfRegions) + if (auto * const clone = dynamic_cast(lightObject.GetPointer())) { - itkExceptionMacro("Cannot break object into " << m_RequestedNumberOfRegions << ". The limit is " - << m_MaximumNumberOfRegions); + if (m_PointDataContainer) + { + clone->m_PointDataContainer = PointDataContainer::New(); + clone->m_PointDataContainer->CastToSTLContainer() = m_PointDataContainer->CastToSTLConstContainer(); + } + return lightObject; } - - if (m_RequestedRegion >= m_RequestedNumberOfRegions || m_RequestedRegion < 0) - { - itkExceptionMacro("Invalid update region " << m_RequestedRegion << ". Must be between 0 and " - << m_RequestedNumberOfRegions - 1); - } - - return retval; + itkExceptionMacro("downcast to type " << this->GetNameOfClass() << " failed."); } } // end namespace itk diff --git a/Modules/Core/Common/include/itkPointSetBase.h b/Modules/Core/Common/include/itkPointSetBase.h new file mode 100644 index 00000000000..af13f71bc9c --- /dev/null +++ b/Modules/Core/Common/include/itkPointSetBase.h @@ -0,0 +1,241 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * 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 + * + * https://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. + * + *=========================================================================*/ +/*========================================================================= + * + * Portions of this file are subject to the VTK Toolkit Version 3 copyright. + * + * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + * + * For complete copyright, license and disclaimer of warranty information + * please refer to the NOTICE file at the top of the ITK source tree. + * + *=========================================================================*/ +#ifndef itkPointSetBase_h +#define itkPointSetBase_h + +#include "itkDataObject.h" +#include "itkVectorContainer.h" +#include + +namespace itk +{ + +/** \class PointSetBase + * \brief A superclass of PointSet + * supports point (geometric coordinate and attribute) definition. + * + * PointSetBase is a superclass of PointSet. + * It provides the portion of the point set definition for geometric coordinates + * (and region information). The defined API provides operations on points but + * does not tie down the underlying implementation and storage. + * + * \tparam TPointsContainer Type of the container of points. Typically either an `itk::VectorContainer` or an + * `itk::MapContainer`.). + * + * \ingroup MeshObjects + * \ingroup DataRepresentation + * \ingroup ITKCommon + */ + +template +class ITK_TEMPLATE_EXPORT PointSetBase : public DataObject +{ +public: + ITK_DISALLOW_COPY_AND_MOVE(PointSetBase); + + /** Standard class type aliases. */ + using Self = PointSetBase; + using Superclass = DataObject; + using Pointer = SmartPointer; + using ConstPointer = SmartPointer; + + /** \see LightObject::GetNameOfClass() */ + itkOverrideGetNameOfClassMacro(PointSetBase); + + itkCloneMacro(Self); + + /** Convenient type alias obtained from TPointsContainer template parameter. */ + using PointType = typename TPointsContainer::Element; + using CoordinateType = typename PointType::CoordinateType; +#ifndef ITK_FUTURE_LEGACY_REMOVE + using CoordRepType ITK_FUTURE_DEPRECATED( + "ITK 6 discourages using `CoordRepType`. Please use `CoordinateType` instead!") = CoordinateType; +#endif + using PointIdentifier = typename TPointsContainer::ElementIdentifier; + using PointsContainer = TPointsContainer; + + /** For improving Python support for PointSetBase and Meshes **/ + using PointsVectorContainer = typename itk::VectorContainer; + using PointsVectorContainerPointer = typename PointsVectorContainer::Pointer; + + /** Convenient constant, indirectly obtained from TPointsContainer template parameter. */ + static constexpr unsigned int PointDimension = PointType::PointDimension; + + /** Create types that are pointers to each of the container types. */ + using PointsContainerPointer = typename PointsContainer::Pointer; + using PointsContainerConstPointer = typename PointsContainer::ConstPointer; + + /** Create types that are iterators for each of the container types. */ + using PointsContainerConstIterator = typename PointsContainer::ConstIterator; + using PointsContainerIterator = typename PointsContainer::Iterator; + + /** Type used to define Regions */ + using RegionType = long; + + /** Get the maximum number of regions that this data can be + * separated into. */ + itkGetConstMacro(MaximumNumberOfRegions, RegionType); + +protected: + /** An object containing points used by the mesh. Individual points are + * accessed through point identifiers. */ + PointsContainerPointer m_PointsContainer{}; + +public: + /** Copy the geometric and topological structure of the given input pointSet. + * The copying is done via reference counting. + */ + void + PassStructure(Self * inputPointSet); + + /** Restore the PointSetBase to its initial state. Useful for data pipeline updates + * without memory re-allocation. + */ + void + Initialize() override; + + /** Point dimension. The dimension of a point is fixed at compile-time. */ + static constexpr unsigned int + GetPointDimension() + { + return PointDimension; + } + + /** Get the number of points in the points container. */ + PointIdentifier + GetNumberOfPoints() const; + + /** Set the points container. */ + void + SetPoints(PointsContainer *); + + /** Set the points container using a 1D vector. + \warning This member function is unsafe. It may just work, but it may also lead to undefined behavior. */ + void + SetPoints(PointsVectorContainer *); + + /** Sets the points by specifying its coordinates. */ + void + SetPointsByCoordinates(const std::vector & coordinates); + + /** Get the points container. */ + PointsContainer * + GetPoints(); + + /** Get the points container. */ + const PointsContainer * + GetPoints() const; + + /** Assign a point to a point identifier. If a spot for the point identifier + * does not exist, it will be created automatically. + */ + void SetPoint(PointIdentifier, PointType); + + /** Check if a point exists for a given point identifier. If a spot for + * the point identifier exists, the point is set, and true is returned. + * Otherwise, false is returned, and the point is not modified. + * If the point is nullptr, then it is never set, but the existence of the + * point is still returned. + */ + bool + GetPoint(PointIdentifier, PointType *) const; + + /** Get the point for the given point identifier. */ + PointType GetPoint(PointIdentifier) const; + + /** Methods to manage streaming. */ + void + UpdateOutputInformation() override; + + void + SetRequestedRegionToLargestPossibleRegion() override; + + void + CopyInformation(const DataObject * data) override; + + bool + RequestedRegionIsOutsideOfTheBufferedRegion() override; + + bool + VerifyRequestedRegion() 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 PointSetBase. */ + void + SetRequestedRegion(const DataObject * data) override; + + /** Set/Get the Requested region */ + virtual void + SetRequestedRegion(const RegionType & region); + + itkGetConstMacro(RequestedRegion, RegionType); + + /** Set/Get the Buffered region */ + virtual void + SetBufferedRegion(const RegionType & region); + + itkGetConstMacro(BufferedRegion, RegionType); + +protected: + /** Default-constructor, to be used by derived classes. */ + PointSetBase() = default; + + /** Pure virtual destructor, to be used by derived classes. */ + ~PointSetBase() override = 0; + + void + PrintSelf(std::ostream & os, Indent indent) const override; + + LightObject::Pointer + InternalClone() const override; + + // If the RegionType is ITK_UNSTRUCTURED_REGION, then the following + // variables represent the maximum number of region that the data + // object can be broken into, which region out of how many is + // currently in the buffered region, and the number of regions and + // the specific region requested for the update. Data objects that + // do not support any division of the data can simply leave the + // MaximumNumberOfRegions as 1. The RequestedNumberOfRegions and + // RequestedRegion are used to define the currently requested + // region. The LargestPossibleRegion is always requested region = 0 + // and number of regions = 1; + RegionType m_MaximumNumberOfRegions{ 1 }; + RegionType m_NumberOfRegions{ 1 }; + RegionType m_RequestedNumberOfRegions{}; + RegionType m_BufferedRegion{ -1 }; + RegionType m_RequestedRegion{ -1 }; +}; +} // end namespace itk + +#ifndef ITK_MANUAL_INSTANTIATION +# include "itkPointSetBase.hxx" +#endif + +#endif diff --git a/Modules/Core/Common/include/itkPointSetBase.hxx b/Modules/Core/Common/include/itkPointSetBase.hxx new file mode 100644 index 00000000000..43139311bc7 --- /dev/null +++ b/Modules/Core/Common/include/itkPointSetBase.hxx @@ -0,0 +1,384 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * 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 + * + * https://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. + * + *=========================================================================*/ +/*========================================================================= + * + * Portions of this file are subject to the VTK Toolkit Version 3 copyright. + * + * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen + * + * For complete copyright, license and disclaimer of warranty information + * please refer to the NOTICE file at the top of the ITK source tree. + * + *=========================================================================*/ +#ifndef itkPointSetBase_hxx +#define itkPointSetBase_hxx + +#include "itkProcessObject.h" +#include + +namespace itk +{ +template +void +PointSetBase::PrintSelf(std::ostream & os, Indent indent) const +{ + Superclass::PrintSelf(os, indent); + os << indent << "Number Of Points: " << this->GetNumberOfPoints() << std::endl; + + os << indent << "Requested Number Of Regions: " << m_RequestedNumberOfRegions << std::endl; + os << indent << "Requested Region: " << m_RequestedRegion << std::endl; + os << indent << "Buffered Region: " << m_BufferedRegion << std::endl; + os << indent << "Maximum Number Of Regions: " << m_MaximumNumberOfRegions << std::endl; +} + +template +void +PointSetBase::SetPoints(PointsContainer * points) +{ + itkDebugMacro("setting Points container to " << points); + if (m_PointsContainer != points) + { + m_PointsContainer = points; + this->Modified(); + } +} + +template +void +PointSetBase::SetPoints(PointsVectorContainer * points) +{ + + itkDebugMacro("setting Points container to " << points); + if (points->Size() % PointDimension != 0) + { + itkExceptionMacro("Number of entries in given 1d array incompatible with the point dimension"); + } + + // Note: this cast is unsafe. It may lead to undefined behavior. + auto * pointsPtr = reinterpret_cast(points); + + m_PointsContainer = pointsPtr; + this->Modified(); +} + + +template +void +PointSetBase::SetPointsByCoordinates(const std::vector & coordinates) +{ + itkDebugMacro("Setting the points to the specified coordinates"); + + const size_t numberOfCoordinates = coordinates.size(); + + if (numberOfCoordinates % PointDimension != 0) + { + itkExceptionMacro("Number of specified coordinates incompatible with the point dimension"); + } + + const size_t numberOfPoints = numberOfCoordinates / PointDimension; + + if (m_PointsContainer == nullptr) + { + m_PointsContainer = PointsContainer::New(); + } + + using STLContainerType = typename PointsContainer::STLContainerType; + + STLContainerType & points = m_PointsContainer->CastToSTLContainer(); + points.clear(); + + if constexpr (std::is_same_v>) + { + // STLContainerType is either an std::vector or an std::map. Only when it is an std::vector, it should be resized. + // std::map does not have a resize function. + points.resize(numberOfPoints); + } + else + { + static_assert(std::is_same_v>); + } + + auto coordinateIterator = coordinates.cbegin(); + + for (PointIdentifier pointIdentifier{}; pointIdentifier < numberOfPoints; ++pointIdentifier) + { + PointType & point = points[pointIdentifier]; + std::copy_n(coordinateIterator, PointDimension, point.begin()); + coordinateIterator += PointDimension; + } + + this->Modified(); +} + + +template +auto +PointSetBase::GetPoints() -> PointsContainer * +{ + itkDebugMacro("Starting GetPoints()"); + if (!m_PointsContainer) + { + this->SetPoints(PointsContainer::New()); + } + itkDebugMacro("returning Points container of " << m_PointsContainer); + return m_PointsContainer; +} + +template +auto +PointSetBase::GetPoints() const -> const PointsContainer * +{ + itkDebugMacro("returning Points container of " << m_PointsContainer); + return m_PointsContainer.GetPointer(); +} + +template +void +PointSetBase::SetPoint(PointIdentifier ptId, PointType point) +{ + /** + * Make sure a points container exists. + */ + if (!m_PointsContainer) + { + this->SetPoints(PointsContainer::New()); + } + + /** + * Insert the point into the container with the given identifier. + */ + m_PointsContainer->InsertElement(ptId, point); +} + +template +bool +PointSetBase::GetPoint(PointIdentifier ptId, PointType * point) const +{ + /** + * If the points container doesn't exist, then the point doesn't either. + */ + if (!m_PointsContainer) + { + return false; + } + + /** + * Ask the container if the point identifier exists. + */ + return m_PointsContainer->GetElementIfIndexExists(ptId, point); +} + +template +auto +PointSetBase::GetPoint(PointIdentifier ptId) const -> PointType +{ + /** + * If the points container doesn't exist, then the point doesn't either. + */ + if (!m_PointsContainer) + { + itkExceptionMacro("Point container doesn't exist."); + } + + /** + * Ask the container if the point identifier exists. + */ + PointType point; + const bool exist = m_PointsContainer->GetElementIfIndexExists(ptId, &point); + if (!exist) + { + itkExceptionMacro("Point id doesn't exist: " << ptId); + } + return point; +} + + +template +void +PointSetBase::PassStructure(Self *) +{ + // IMPLEMENT ME +} + +template +auto +PointSetBase::GetNumberOfPoints() const -> PointIdentifier +{ + if (m_PointsContainer) + { + return m_PointsContainer->Size(); + } + return 0; +} + +template +void +PointSetBase::Initialize() +{ + Superclass::Initialize(); + + m_PointsContainer = nullptr; +} + + +template +void +PointSetBase::UpdateOutputInformation() +{ + this->Superclass::UpdateOutputInformation(); + + // Now we should know what our largest possible region is. If our + // requested region was not set yet, (or has been set to something + // invalid - with no data in it ) then set it to the largest + // possible region. + if (m_RequestedRegion == -1 && m_RequestedNumberOfRegions == 0) + { + this->SetRequestedRegionToLargestPossibleRegion(); + } +} + +template +void +PointSetBase::SetRequestedRegionToLargestPossibleRegion() +{ + m_RequestedNumberOfRegions = 1; + m_RequestedRegion = 0; +} + +template +void +PointSetBase::CopyInformation(const DataObject * data) +{ + const auto * pointSet = dynamic_cast(data); + + if (!pointSet) + { + // pointer could not be cast back down + itkExceptionMacro("itk::PointSetBase::CopyInformation() cannot cast " << typeid(data).name() << " to " + << typeid(PointSetBase *).name()); + } + + m_MaximumNumberOfRegions = pointSet->GetMaximumNumberOfRegions(); + + m_NumberOfRegions = pointSet->m_NumberOfRegions; + m_RequestedNumberOfRegions = pointSet->m_RequestedNumberOfRegions; + m_BufferedRegion = pointSet->m_BufferedRegion; + m_RequestedRegion = pointSet->m_RequestedRegion; +} + +template +void +PointSetBase::SetRequestedRegion(const DataObject * data) +{ + const auto * pointSet = dynamic_cast(data); + + if (pointSet) + { + // only copy the RequestedRegion if the parameter is another PointSetBase + m_RequestedRegion = pointSet->m_RequestedRegion; + m_RequestedNumberOfRegions = pointSet->m_RequestedNumberOfRegions; + } +} + +template +void +PointSetBase::SetRequestedRegion(const RegionType & region) +{ + if (m_RequestedRegion != region) + { + m_RequestedRegion = region; + } +} + +template +void +PointSetBase::SetBufferedRegion(const RegionType & region) +{ + if (m_BufferedRegion != region) + { + m_BufferedRegion = region; + this->Modified(); + } +} + +template +bool +PointSetBase::RequestedRegionIsOutsideOfTheBufferedRegion() +{ + if (m_RequestedRegion != m_BufferedRegion || m_RequestedNumberOfRegions != m_NumberOfRegions) + { + return true; + } + + return false; +} + +template +bool +PointSetBase::VerifyRequestedRegion() +{ + const bool retval = true; + + // Are we asking for more regions than we can get? + if (m_RequestedNumberOfRegions > m_MaximumNumberOfRegions) + { + itkExceptionMacro("Cannot break object into " << m_RequestedNumberOfRegions << ". The limit is " + << m_MaximumNumberOfRegions); + } + + if (m_RequestedRegion >= m_RequestedNumberOfRegions || m_RequestedRegion < 0) + { + itkExceptionMacro("Invalid update region " << m_RequestedRegion << ". Must be between 0 and " + << m_RequestedNumberOfRegions - 1); + } + + return retval; +} + +template +LightObject::Pointer +PointSetBase::InternalClone() const +{ + LightObject::Pointer lightObject = Superclass::InternalClone(); + + if (auto * const clone = dynamic_cast(lightObject.GetPointer())) + { + if (m_PointsContainer) + { + clone->m_PointsContainer = TPointsContainer::New(); + clone->m_PointsContainer->CastToSTLContainer() = m_PointsContainer->CastToSTLConstContainer(); + } + + clone->m_MaximumNumberOfRegions = m_MaximumNumberOfRegions; + clone->m_NumberOfRegions = m_NumberOfRegions; + clone->m_RequestedNumberOfRegions = m_RequestedNumberOfRegions; + clone->m_BufferedRegion = m_BufferedRegion; + clone->m_RequestedRegion = m_RequestedRegion; + + return lightObject; + } + itkExceptionMacro("downcast to type " << this->GetNameOfClass() << " failed."); +} + +// Destructor. Must be defined here (rather than inside the class definition) because it is pure virtual. +template +PointSetBase::~PointSetBase() = default; + +} // end namespace itk + +#endif diff --git a/Modules/Core/Common/include/itkPointSetToImageFilter.h b/Modules/Core/Common/include/itkPointSetToImageFilter.h index bf2a3c7429c..797a9cb1be3 100644 --- a/Modules/Core/Common/include/itkPointSetToImageFilter.h +++ b/Modules/Core/Common/include/itkPointSetToImageFilter.h @@ -88,10 +88,11 @@ class ITK_TEMPLATE_EXPORT PointSetToImageFilter : public ImageSource void PointSetToImageFilter::GenerateData() { - unsigned int i; - itkDebugMacro("PointSetToImageFilter::Update() called"); // Get the input and output pointers const InputPointSetType * InputPointSet = this->GetInput(); - OutputImagePointer OutputImage = this->GetOutput(); - - // Generate the image - double origin[InputPointSetDimension]; - SizeType size; + const OutputImagePointer OutputImage = this->GetOutput(); using BoundingBoxType = BoundingBox; auto bb = BoundingBoxType::New(); bb->SetPoints(InputPointSet->GetPoints()); bb->ComputeBoundingBox(); - for (i = 0; i < InputPointSetDimension; ++i) + // Generate the image + double origin[InputPointSetDimension]; + SizeType size; + for (unsigned int i = 0; i < InputPointSetDimension; ++i) { size[i] = static_cast(bb->GetBounds()[2 * i + 1] - bb->GetBounds()[2 * i]); origin[i] = bb->GetBounds()[2 * i]; @@ -141,7 +138,7 @@ PointSetToImageFilter::GenerateData() // PointSet's bounding box will be used as default. bool specified = false; - for (i = 0; i < OutputImageDimension; ++i) + for (unsigned int i = 0; i < OutputImageDimension; ++i) { if (m_Size[i] != SizeValueType{}) { @@ -167,7 +164,7 @@ PointSetToImageFilter::GenerateData() // the point-set is used as default. specified = false; - for (i = 0; i < OutputImageDimension; ++i) + for (unsigned int i = 0; i < OutputImageDimension; ++i) { if (Math::NotExactlyEquals(m_Spacing[i], typename NumericTraits::ValueType{})) { @@ -182,7 +179,7 @@ PointSetToImageFilter::GenerateData() } specified = false; - for (i = 0; i < OutputImageDimension; ++i) + for (unsigned int i = 0; i < OutputImageDimension; ++i) { if (Math::NotExactlyEquals(m_Origin[i], typename NumericTraits::ValueType{})) { @@ -193,7 +190,7 @@ PointSetToImageFilter::GenerateData() if (specified) { - for (i = 0; i < OutputImageDimension; ++i) + for (unsigned int i = 0; i < OutputImageDimension; ++i) { origin[i] = m_Origin[i]; // set origin } @@ -205,8 +202,8 @@ PointSetToImageFilter::GenerateData() OutputImage->FillBuffer(m_OutsideValue); using PointIterator = typename InputPointSetType::PointsContainer::ConstIterator; - PointIterator pointItr = InputPointSet->GetPoints()->Begin(); - PointIterator pointEnd = InputPointSet->GetPoints()->End(); + PointIterator pointItr = InputPointSet->GetPoints()->Begin(); + const PointIterator pointEnd = InputPointSet->GetPoints()->End(); typename OutputImageType::IndexType index; diff --git a/Modules/Core/Common/include/itkPolyLineCell.h b/Modules/Core/Common/include/itkPolyLineCell.h index 5f51f9c9e57..be521775920 100644 --- a/Modules/Core/Common/include/itkPolyLineCell.h +++ b/Modules/Core/Common/include/itkPolyLineCell.h @@ -28,11 +28,6 @@ namespace itk * * Template parameters for PolyLineCell: * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. - * * \ingroup MeshObjects * \ingroup ITKCommon */ @@ -44,9 +39,10 @@ class ITK_TEMPLATE_EXPORT PolyLineCell : public TCellInterface ITK_DISALLOW_COPY_AND_MOVE(PolyLineCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(PolyLineCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(PolyLineCell); @@ -58,6 +54,7 @@ class ITK_TEMPLATE_EXPORT PolyLineCell : public TCellInterface static constexpr unsigned int CellDimension = 1; /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -65,7 +62,7 @@ class ITK_TEMPLATE_EXPORT PolyLineCell : public TCellInterface } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ unsigned int GetDimension() const override; diff --git a/Modules/Core/Common/include/itkPolyLineCell.hxx b/Modules/Core/Common/include/itkPolyLineCell.hxx index e7467e294a5..85fa0bf6bc6 100644 --- a/Modules/Core/Common/include/itkPolyLineCell.hxx +++ b/Modules/Core/Common/include/itkPolyLineCell.hxx @@ -207,10 +207,8 @@ PolyLineCell::PointIdsEnd() -> PointIdIterator { return &m_PointIds.back() + 1; } - else - { - return nullptr; - } + + return nullptr; } /** @@ -226,10 +224,8 @@ PolyLineCell::PointIdsEnd() const -> PointIdConstIterator { return &m_PointIds.back() + 1; } - else - { - return nullptr; - } + + return nullptr; } /** diff --git a/Modules/Core/Common/include/itkPolygonCell.h b/Modules/Core/Common/include/itkPolygonCell.h index 6dfadbb4455..6e15c072532 100644 --- a/Modules/Core/Common/include/itkPolygonCell.h +++ b/Modules/Core/Common/include/itkPolygonCell.h @@ -41,10 +41,6 @@ namespace itk * PolygonCell represents a polygon for a Mesh. * the points of the polygon can be dynamically changed. * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. * * \ingroup MeshObjects * \ingroup ITKCommon @@ -56,9 +52,10 @@ class ITK_TEMPLATE_EXPORT PolygonCell : public TCellInterface ITK_DISALLOW_COPY_AND_MOVE(PolygonCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(PolygonCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(PolygonCell); @@ -80,6 +77,7 @@ class ITK_TEMPLATE_EXPORT PolygonCell : public TCellInterface itkCellVisitMacro(CellGeometryEnum::POLYGON_CELL); /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -87,7 +85,7 @@ class ITK_TEMPLATE_EXPORT PolygonCell : public TCellInterface } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ unsigned int GetDimension() const override; @@ -144,6 +142,7 @@ class ITK_TEMPLATE_EXPORT PolygonCell : public TCellInterface GetEdge(CellFeatureIdentifier, EdgeAutoPointer &); /** Constructor and destructor */ + /** @ITKStartGrouping */ PolygonCell() = default; PolygonCell(PointIdentifier NumberOfPoints) { @@ -153,7 +152,7 @@ class ITK_TEMPLATE_EXPORT PolygonCell : public TCellInterface } this->BuildEdges(); } - + /** @ITKEndGrouping */ ~PolygonCell() override = default; protected: diff --git a/Modules/Core/Common/include/itkPolygonCell.hxx b/Modules/Core/Common/include/itkPolygonCell.hxx index d48fb8ef5c6..492fe17e8ba 100644 --- a/Modules/Core/Common/include/itkPolygonCell.hxx +++ b/Modules/Core/Common/include/itkPolygonCell.hxx @@ -278,10 +278,8 @@ PolygonCell::PointIdsBegin() -> PointIdIterator { return &m_PointIds.front(); } - else - { - return nullptr; - } + + return nullptr; } /** @@ -297,10 +295,8 @@ PolygonCell::PointIdsBegin() const -> PointIdConstIterator { return &m_PointIds.front(); } - else - { - return nullptr; - } + + return nullptr; } /** @@ -315,10 +311,8 @@ PolygonCell::PointIdsEnd() -> PointIdIterator { return &m_PointIds.back() + 1; } - else - { - return nullptr; - } + + return nullptr; } /** @@ -334,10 +328,8 @@ PolygonCell::PointIdsEnd() const -> PointIdConstIterator { return &m_PointIds.back() + 1; } - else - { - return nullptr; - } + + return nullptr; } /** @@ -387,8 +379,8 @@ template bool PolygonCell::GetEdge(CellFeatureIdentifier edgeId, EdgeAutoPointer & edgePointer) { - auto * edge = new EdgeType; - unsigned int max_pointId = this->GetNumberOfPoints() - 1; + auto * edge = new EdgeType; + const unsigned int max_pointId = this->GetNumberOfPoints() - 1; if (edgeId < max_pointId) { diff --git a/Modules/Core/Common/include/itkPriorityQueueContainer.hxx b/Modules/Core/Common/include/itkPriorityQueueContainer.hxx index 8fbda303a43..fadc47e77dd 100644 --- a/Modules/Core/Common/include/itkPriorityQueueContainer.hxx +++ b/Modules/Core/Common/include/itkPriorityQueueContainer.hxx @@ -337,7 +337,7 @@ bool PriorityQueueContainer::Update( const ElementWrapperType & element) { - ElementIdentifierType location = m_Interface.GetLocation(element); + const ElementIdentifierType location = m_Interface.GetLocation(element); if (location != m_ElementNotFound) { @@ -363,13 +363,13 @@ bool PriorityQueueContainer::DeleteElement( const ElementWrapperType & element) { - ElementIdentifierType location = m_Interface.GetLocation(element); + const ElementIdentifierType location = m_Interface.GetLocation(element); if (location != m_ElementNotFound) { // m_Interface.SetLocation(element, m_ElementNotFound); - ElementIdentifierType tsize = this->Size(); + const ElementIdentifierType tsize = this->Size(); if (location >= tsize) { @@ -438,7 +438,7 @@ PriorityQueueContainerSize(); + const ElementIdentifierType queueSize = this->Size(); while (id < queueSize) { diff --git a/Modules/Core/Common/include/itkProcessObject.h b/Modules/Core/Common/include/itkProcessObject.h index 80f6630b2f9..aa5a909a501 100644 --- a/Modules/Core/Common/include/itkProcessObject.h +++ b/Modules/Core/Common/include/itkProcessObject.h @@ -164,7 +164,7 @@ class ITKCommon_EXPORT ProcessObject : public Object /** STL array of data object names */ using NameArray = std::vector; - //** Type of general multi-threader interface */ + /** Type of general multi-threader interface */ using MultiThreaderType = MultiThreaderBase; /** \brief Return an array with the names of the inputs defined. @@ -459,6 +459,7 @@ class ITKCommon_EXPORT ProcessObject : public Object * used by a downstream ProcessObject. Default value is off. Another * options for controlling memory utilization is the * ReleaseDataBeforeUpdateFlag. */ + /** @ITKStartGrouping */ virtual void SetReleaseDataFlag(bool val); virtual bool @@ -473,6 +474,7 @@ class ITKCommon_EXPORT ProcessObject : public Object { this->SetReleaseDataFlag(false); } + /** @ITKEndGrouping */ /** Turn on/off the flags to control whether the bulk data belonging * to the outputs of this ProcessObject are released/reallocated @@ -486,19 +488,17 @@ class ITKCommon_EXPORT ProcessObject : public Object * ReleaseDataBeforeUpdateFlag manages the deallocation/reallocation * of bulk data during a pipeline update to control peak memory * utilization. Default value is on. */ + /** @ITKStartGrouping */ itkSetMacro(ReleaseDataBeforeUpdateFlag, bool); itkGetConstReferenceMacro(ReleaseDataBeforeUpdateFlag, bool); itkBooleanMacro(ReleaseDataBeforeUpdateFlag); + /** @ITKEndGrouping */ /** Get/Set the number of work units to create when executing. */ + /** @ITKStartGrouping */ itkSetClampMacro(NumberOfWorkUnits, ThreadIdType, 1, ITK_MAX_THREADS); itkGetConstReferenceMacro(NumberOfWorkUnits, ThreadIdType); - -#if !defined(ITK_LEGACY_REMOVE) || defined(ITKV4_COMPATIBILITY) - itkLegacyMacro(void SetNumberOfThreads(ThreadIdType count)) { this->SetNumberOfWorkUnits(count); } - - itkLegacyMacro(ThreadIdType GetNumberOfThreads() const) { return this->GetNumberOfWorkUnits(); } -#endif // !ITK_LEGACY_REMOVE + /** @ITKEndGrouping */ /** Return the multithreader used by this class. */ MultiThreaderType * @@ -542,6 +542,7 @@ class ITKCommon_EXPORT ProcessObject : public Object /** Method used internally for getting an indexed input. */ + /** @ITKStartGrouping */ DataObject * GetInput(DataObjectPointerArraySizeType idx) { @@ -552,6 +553,7 @@ class ITKCommon_EXPORT ProcessObject : public Object { return idx < m_IndexedInputs.size() ? m_IndexedInputs[idx]->second.GetPointer() : nullptr; } + /** @ITKEndGrouping */ /** \brief Protected method for setting indexed and named inputs. * @@ -596,6 +598,7 @@ class ITKCommon_EXPORT ProcessObject : public Object virtual void RemoveInput(DataObjectPointerArraySizeType); /** Return the main input */ + /** @ITKStartGrouping */ DataObject * GetPrimaryInput() { @@ -606,8 +609,10 @@ class ITKCommon_EXPORT ProcessObject : public Object { return m_IndexedInputs[0]->second; } + /** @ITKEndGrouping */ /** Set/Get the name associated with the Primary input. Defaults to "Primary". */ + /** @ITKStartGrouping */ virtual void SetPrimaryInputName(const DataObjectIdentifierType & key); virtual const char * @@ -615,6 +620,7 @@ class ITKCommon_EXPORT ProcessObject : public Object { return this->m_IndexedInputs[0]->first.c_str(); } + /** @ITKEndGrouping */ /** Set the main input */ virtual void @@ -696,12 +702,15 @@ class ITKCommon_EXPORT ProcessObject : public Object // /** Return an output */ + /** @ITKStartGrouping */ DataObject * GetOutput(const DataObjectIdentifierType & key); const DataObject * GetOutput(const DataObjectIdentifierType & key) const; + /** @ITKEndGrouping */ /** Set/Get the name associated with the Primary output. Defaults to "Primary". */ + /** @ITKStartGrouping */ virtual void SetPrimaryOutputName(const DataObjectIdentifierType & key); virtual const char * @@ -709,12 +718,15 @@ class ITKCommon_EXPORT ProcessObject : public Object { return this->m_IndexedOutputs[0]->first.c_str(); } + /** @ITKEndGrouping */ /** Method used internally for getting an indexed output. */ + /** @ITKStartGrouping */ DataObject * GetOutput(DataObjectPointerArraySizeType i); const DataObject * GetOutput(DataObjectPointerArraySizeType i) const; + /** @ITKEndGrouping */ /** Set an output */ virtual void @@ -725,6 +737,7 @@ class ITKCommon_EXPORT ProcessObject : public Object RemoveOutput(const DataObjectIdentifierType & key); /** Return the main output */ + /** @ITKStartGrouping */ DataObject * GetPrimaryOutput() { @@ -735,6 +748,7 @@ class ITKCommon_EXPORT ProcessObject : public Object { return m_IndexedOutputs[0]->second; } + /** @ITKEndGrouping */ /** Set the main output */ virtual void @@ -788,7 +802,7 @@ class ITKCommon_EXPORT ProcessObject : public Object * */ virtual void - VerifyPreconditions() ITKv5_CONST; + VerifyPreconditions() const; /** \brief Verifies that the inputs meta-data is consistent and valid * for continued execution of the pipeline, throws an exception if @@ -801,7 +815,7 @@ class ITKCommon_EXPORT ProcessObject : public Object * */ virtual void - VerifyInputInformation() ITKv5_CONST; + VerifyInputInformation() const; /** What is the input requested region that is required to produce the * output requested region? By default, the largest possible region is @@ -852,6 +866,7 @@ class ITKCommon_EXPORT ProcessObject : public Object {} /** Called to allocate the input array. Copies old inputs. */ + /** Propagate a call to ResetPipeline() up the pipeline. Called only from * DataObject. */ virtual void @@ -892,11 +907,12 @@ class ITKCommon_EXPORT ProcessObject : public Object * When true, the MultiThreader will report course grain progress. If set to false, a progress must be explicitly * updated in derived filters. */ + /** @ITKStartGrouping */ itkGetConstMacro(ThreaderUpdateProgress, bool); itkBooleanMacro(ThreaderUpdateProgress); virtual void SetThreaderUpdateProgress(bool arg); - + /** @ITKEndGrouping */ /** * Internal method to convert internal integer progress to float [0.0, 1.0] @@ -905,7 +921,7 @@ class ITKCommon_EXPORT ProcessObject : public Object progressFixedToFloat(uint32_t fixed) { return static_cast(fixed) / static_cast(std::numeric_limits::max()); - }; + } /** * Internal method convert floating point progress [0.0, 1.0] to internal integer representation. Values outside the @@ -922,9 +938,22 @@ class ITKCommon_EXPORT ProcessObject : public Object { return std::numeric_limits::max(); } - double temp = static_cast(f) * std::numeric_limits::max(); + const double temp = static_cast(f) * std::numeric_limits::max(); return static_cast(temp); - }; + } + + /** Sets the required number of outputs, and creates each of them by MakeOutput. */ + template + static void + MakeRequiredOutputs(TSourceObject & sourceObject, const DataObjectPointerArraySizeType numberOfRequiredOutputs) + { + sourceObject.ProcessObject::SetNumberOfRequiredOutputs(numberOfRequiredOutputs); + + for (unsigned int i{}; i < numberOfRequiredOutputs; ++i) + { + sourceObject.ProcessObject::SetNthOutput(i, sourceObject.TSourceObject::MakeOutput(i)); + } + } /** These ivars are made protected so filters like itkStreamingImageFilter * can access them directly. */ diff --git a/Modules/Core/Common/include/itkProgressReporter.h b/Modules/Core/Common/include/itkProgressReporter.h index f70346baa05..46901055f21 100644 --- a/Modules/Core/Common/include/itkProgressReporter.h +++ b/Modules/Core/Common/include/itkProgressReporter.h @@ -114,7 +114,7 @@ class ITKCommon_EXPORT ProgressReporter ProcessObject * m_Filter; ThreadIdType m_ThreadId; float m_InverseNumberOfPixels; - SizeValueType m_CurrentPixel; + SizeValueType m_CurrentPixel{ 0 }; SizeValueType m_PixelsPerUpdate; SizeValueType m_PixelsBeforeUpdate; float m_InitialProgress; diff --git a/Modules/Core/Common/include/itkProgressTransformer.h b/Modules/Core/Common/include/itkProgressTransformer.h index 2b33f0225b4..4104d9f0bea 100644 --- a/Modules/Core/Common/include/itkProgressTransformer.h +++ b/Modules/Core/Common/include/itkProgressTransformer.h @@ -67,7 +67,7 @@ class ITKCommon_EXPORT ProgressTransformer using CommandType = SimpleMemberCommand; CommandType::Pointer m_ProgressCommand; - unsigned long m_ProgressTag; + unsigned long m_ProgressTag{ 0 }; }; } // end namespace itk #endif // itkProgressTransformer_h diff --git a/Modules/Core/Common/include/itkPromoteType.h b/Modules/Core/Common/include/itkPromoteType.h index 7162ac1805c..75f0cea3b75 100644 --- a/Modules/Core/Common/include/itkPromoteType.h +++ b/Modules/Core/Common/include/itkPromoteType.h @@ -60,7 +60,7 @@ struct Identity struct SizeToType \ { \ using Type = Typed; \ - }; + } ITK_ASSOCIATE(1, TA); ITK_ASSOCIATE(2, TB); @@ -82,7 +82,8 @@ ITK_ASSOCIATE(13, long double); /** Helper class to deduce, in C++98, the resulting type of an operation between two input types. * \tparam TA Input type 1 * \tparam TB Input type 2 - * \return \c Type the resulting type compatible with \c TA and \c TB. + * + * \c Type the resulting type compatible with \c TA and \c TB. * * In order to support user defined type, specialize \c * itk::PromoteType<> in consequence. For instance, to support type promotion @@ -112,17 +113,28 @@ struct PromoteType static Details::Identity<2>::Type & Check(typename Details::SizeToType<2, TA, TB>::Type, T); // Common numeric types - static Details::Identity<3>::Type & Check(typename Details::SizeToType<3, TA, TB>::Type, int); - static Details::Identity<4>::Type & Check(typename Details::SizeToType<4, TA, TB>::Type, int); - static Details::Identity<5>::Type & Check(typename Details::SizeToType<5, TA, TB>::Type, int); - static Details::Identity<6>::Type & Check(typename Details::SizeToType<6, TA, TB>::Type, int); - static Details::Identity<7>::Type & Check(typename Details::SizeToType<7, TA, TB>::Type, int); - static Details::Identity<8>::Type & Check(typename Details::SizeToType<8, TA, TB>::Type, int); - static Details::Identity<9>::Type & Check(typename Details::SizeToType<9, TA, TB>::Type, int); - static Details::Identity<10>::Type & Check(typename Details::SizeToType<10, TA, TB>::Type, int); - static Details::Identity<11>::Type & Check(typename Details::SizeToType<11, TA, TB>::Type, int); - static Details::Identity<12>::Type & Check(typename Details::SizeToType<12, TA, TB>::Type, int); - static Details::Identity<13>::Type & Check(typename Details::SizeToType<13, TA, TB>::Type, int); + static Details::Identity<3>::Type & + Check(typename Details::SizeToType<3, TA, TB>::Type, int); + static Details::Identity<4>::Type & + Check(typename Details::SizeToType<4, TA, TB>::Type, int); + static Details::Identity<5>::Type & + Check(typename Details::SizeToType<5, TA, TB>::Type, int); + static Details::Identity<6>::Type & + Check(typename Details::SizeToType<6, TA, TB>::Type, int); + static Details::Identity<7>::Type & + Check(typename Details::SizeToType<7, TA, TB>::Type, int); + static Details::Identity<8>::Type & + Check(typename Details::SizeToType<8, TA, TB>::Type, int); + static Details::Identity<9>::Type & + Check(typename Details::SizeToType<9, TA, TB>::Type, int); + static Details::Identity<10>::Type & + Check(typename Details::SizeToType<10, TA, TB>::Type, int); + static Details::Identity<11>::Type & + Check(typename Details::SizeToType<11, TA, TB>::Type, int); + static Details::Identity<12>::Type & + Check(typename Details::SizeToType<12, TA, TB>::Type, int); + static Details::Identity<13>::Type & + Check(typename Details::SizeToType<13, TA, TB>::Type, int); public: /** Type result of operations between \c TA and \c TB. diff --git a/Wrapping/Generators/Python/PyUtils/itkPyCommand.h b/Modules/Core/Common/include/itkPyCommand.h similarity index 90% rename from Wrapping/Generators/Python/PyUtils/itkPyCommand.h rename to Modules/Core/Common/include/itkPyCommand.h index df637f0de89..d7dc0715a75 100644 --- a/Wrapping/Generators/Python/PyUtils/itkPyCommand.h +++ b/Modules/Core/Common/include/itkPyCommand.h @@ -38,8 +38,11 @@ namespace itk * This is analogous to itk::TclCommand, but then a tad more flexible.;) * * This class was contributed by Charl P. Botha + * + * \ingroup ITKSystemObjects + * \ingroup ITKCommon */ -class PyCommand : public Command +class ITKCommon_EXPORT PyCommand : public Command { public: ///! Standard "Self" typedef. @@ -66,13 +69,13 @@ class PyCommand : public Command GetCommandCallable(); void - Execute(Object *, const EventObject &); + Execute(Object *, const EventObject &) override; void - Execute(const Object *, const EventObject &); + Execute(const Object *, const EventObject &) override; protected: PyCommand(); - ~PyCommand(); + ~PyCommand() override; void PyExecute(); PyCommand(const Self &); // Not implemented. diff --git a/Wrapping/Generators/Python/PyUtils/itkPyImageFilter.h b/Modules/Core/Common/include/itkPyImageFilter.h similarity index 98% rename from Wrapping/Generators/Python/PyUtils/itkPyImageFilter.h rename to Modules/Core/Common/include/itkPyImageFilter.h index 318b26a09b4..9d8acb77e61 100644 --- a/Wrapping/Generators/Python/PyUtils/itkPyImageFilter.h +++ b/Modules/Core/Common/include/itkPyImageFilter.h @@ -35,6 +35,8 @@ namespace itk * * For more information on ITK filters, the GenerateData() method, and other filter pipeline methods, * see the ITK Software Guide. + * + * \ingroup ITKCommon */ template class ITK_TEMPLATE_EXPORT PyImageFilter : public ImageToImageFilter @@ -100,8 +102,8 @@ class ITK_TEMPLATE_EXPORT PyImageFilter : public ImageToImageFilter -PyImageFilter::PyImageFilter() -{} - template PyImageFilter::~PyImageFilter() { @@ -171,8 +167,7 @@ PyImageFilter::GenerateOutputInformation() PyErr_Print(); // make sure the invoking Python code knows there was a problem // by raising an exception - itkExceptionMacro("There was an error executing the " - << "CommandCallable."); + itkExceptionMacro("There was an error executing the CommandCallable."); } } } @@ -204,8 +199,7 @@ PyImageFilter::EnlargeOutputRequestedRegion(DataObjec PyErr_Print(); // make sure the invoking Python code knows there was a problem // by raising an exception - itkExceptionMacro("There was an error executing the " - << "CommandCallable."); + itkExceptionMacro("There was an error executing the CommandCallable."); } } } @@ -236,8 +230,7 @@ PyImageFilter::GenerateInputRequestedRegion() PyErr_Print(); // make sure the invoking Python code knows there was a problem // by raising an exception - itkExceptionMacro("There was an error executing the " - << "CommandCallable."); + itkExceptionMacro("There was an error executing the CommandCallable."); } } } @@ -252,8 +245,7 @@ PyImageFilter::GenerateData() // we throw a standard ITK exception: this makes it possible for // 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."); + itkExceptionMacro("CommandCallable is not a callable Python object, or it has not been set."); } else { @@ -273,8 +265,7 @@ PyImageFilter::GenerateData() PyErr_Print(); // make sure the invoking Python code knows there was a problem // by raising an exception - itkExceptionMacro("There was an error executing the " - << "CommandCallable."); + itkExceptionMacro("There was an error executing the CommandCallable."); } } } diff --git a/Modules/Core/Common/include/itkQuadraticEdgeCell.h b/Modules/Core/Common/include/itkQuadraticEdgeCell.h index 125275f3ada..70a11996406 100644 --- a/Modules/Core/Common/include/itkQuadraticEdgeCell.h +++ b/Modules/Core/Common/include/itkQuadraticEdgeCell.h @@ -28,11 +28,6 @@ namespace itk /** \class QuadraticEdgeCell * \brief Represents a second order line segment for a Mesh. * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. - * * \ingroup MeshObjects * \ingroup ITKCommon */ @@ -43,9 +38,10 @@ class ITK_TEMPLATE_EXPORT QuadraticEdgeCell : public TCellInterface ITK_DISALLOW_COPY_AND_MOVE(QuadraticEdgeCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(QuadraticEdgeCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(QuadraticEdgeCell); @@ -59,6 +55,7 @@ class ITK_TEMPLATE_EXPORT QuadraticEdgeCell : public TCellInterface static constexpr unsigned int CellDimension = 1; /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -66,7 +63,7 @@ class ITK_TEMPLATE_EXPORT QuadraticEdgeCell : public TCellInterface } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ unsigned int GetDimension() const override; diff --git a/Modules/Core/Common/include/itkQuadraticEdgeCell.hxx b/Modules/Core/Common/include/itkQuadraticEdgeCell.hxx index 88b81784125..39247255917 100644 --- a/Modules/Core/Common/include/itkQuadraticEdgeCell.hxx +++ b/Modules/Core/Common/include/itkQuadraticEdgeCell.hxx @@ -225,7 +225,7 @@ void QuadraticEdgeCell::EvaluateShapeFunctions(const ParametricCoordArrayType & parametricCoordinates, ShapeFunctionsArrayType & weights) const { - CoordRepType x = parametricCoordinates[0]; // one-dimensional cell + const CoordinateType x = parametricCoordinates[0]; // one-dimensional cell if (weights.Size() != this->GetNumberOfPoints()) { diff --git a/Modules/Core/Common/include/itkQuadraticTriangleCell.h b/Modules/Core/Common/include/itkQuadraticTriangleCell.h index 267ac243d35..a0f2d1836a7 100644 --- a/Modules/Core/Common/include/itkQuadraticTriangleCell.h +++ b/Modules/Core/Common/include/itkQuadraticTriangleCell.h @@ -29,11 +29,6 @@ namespace itk /** \class QuadraticTriangleCell * \brief Represents a second order triangular patch for a Mesh. * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. - * * \ingroup MeshObjects * \ingroup ITKCommon */ @@ -46,9 +41,10 @@ class ITK_TEMPLATE_EXPORT QuadraticTriangleCell ITK_DISALLOW_COPY_AND_MOVE(QuadraticTriangleCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(QuadraticTriangleCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(QuadraticTriangleCell); @@ -67,6 +63,7 @@ class ITK_TEMPLATE_EXPORT QuadraticTriangleCell static constexpr unsigned int CellDimension = 2; /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -74,7 +71,7 @@ class ITK_TEMPLATE_EXPORT QuadraticTriangleCell } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ unsigned int GetDimension() const override; diff --git a/Modules/Core/Common/include/itkQuadrilateralCell.h b/Modules/Core/Common/include/itkQuadrilateralCell.h index acf10441a73..236f2fcf8bf 100644 --- a/Modules/Core/Common/include/itkQuadrilateralCell.h +++ b/Modules/Core/Common/include/itkQuadrilateralCell.h @@ -29,11 +29,6 @@ namespace itk /** \class QuadrilateralCell * \brief Represents a quadrilateral for a Mesh. * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. - * * \ingroup MeshObjects * \ingroup ITKCommon */ @@ -47,9 +42,10 @@ class ITK_TEMPLATE_EXPORT QuadrilateralCell ITK_DISALLOW_COPY_AND_MOVE(QuadrilateralCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(QuadrilateralCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(QuadrilateralCell); @@ -69,6 +65,7 @@ class ITK_TEMPLATE_EXPORT QuadrilateralCell static constexpr unsigned int NumberOfDerivatives = 8; /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -76,7 +73,7 @@ class ITK_TEMPLATE_EXPORT QuadrilateralCell } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ unsigned int GetDimension() const override; @@ -122,10 +119,10 @@ class ITK_TEMPLATE_EXPORT QuadrilateralCell /** Evaluate the position inside the cell */ bool - EvaluatePosition(CoordRepType * x, + EvaluatePosition(CoordinateType * x, PointsContainer * points, - CoordRepType * closestPoint, - CoordRepType[CellDimension], + CoordinateType * closestPoint, + CoordinateType[CellDimension], double * dist2, InterpolationWeightType * weight) override; @@ -133,34 +130,25 @@ class ITK_TEMPLATE_EXPORT QuadrilateralCell itkCellVisitMacro(CellGeometryEnum::QUADRILATERAL_CELL); /** Constructor and destructor */ + /** @ITKStartGrouping */ QuadrilateralCell() = default; - -#if defined(__GNUC__) - // A bug in some versions of the GCC and Clang compilers - // result in an ICE or linker error when "= default" is requested. - // This was observed in at least gcc 4.8 and 5.4.0, and - // AppleClang 7.0.2 and 8.0.0. Probably others too. - // "= default" doesn't gain us much, so just don't use it here. - ~QuadrilateralCell() override{}; -#else ~QuadrilateralCell() override = default; -#endif - + /** @ITKEndGrouping */ protected: /** Store the number of points needed for a quadrilateral. */ std::array m_PointIds{ MakeFilled>( NumericTraits::max()) }; void - InterpolationDerivs(const CoordRepType pointCoords[CellDimension], CoordRepType derivs[NumberOfDerivatives]); + InterpolationDerivs(const CoordinateType pointCoords[CellDimension], CoordinateType derivs[NumberOfDerivatives]); void - InterpolationFunctions(const CoordRepType pointCoords[CellDimension], + InterpolationFunctions(const CoordinateType pointCoords[CellDimension], InterpolationWeightType weights[NumberOfPoints]); void EvaluateLocation(int & itkNotUsed(subId), const PointsContainer * points, - const CoordRepType pointCoords[PointDimension], - CoordRepType x[PointDimension], + const CoordinateType pointCoords[PointDimension], + CoordinateType x[PointDimension], InterpolationWeightType * weights); }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkQuadrilateralCell.hxx b/Modules/Core/Common/include/itkQuadrilateralCell.hxx index 36551042363..da44dcdbb9c 100644 --- a/Modules/Core/Common/include/itkQuadrilateralCell.hxx +++ b/Modules/Core/Common/include/itkQuadrilateralCell.hxx @@ -268,10 +268,10 @@ QuadrilateralCell::GetEdge(CellFeatureIdentifier edgeId, EdgeAut /** Evaluate the position inside the cell */ template bool -QuadrilateralCell::EvaluatePosition(CoordRepType * x, +QuadrilateralCell::EvaluatePosition(CoordinateType * x, PointsContainer * points, - CoordRepType * closestPoint, - CoordRepType pcoord[CellDimension], + CoordinateType * closestPoint, + CoordinateType pcoord[CellDimension], double * dist2, InterpolationWeightType * weight) { @@ -279,42 +279,36 @@ QuadrilateralCell::EvaluatePosition(CoordRepType * x, static constexpr double ITK_QUAD_CONVERGED = 1.e-03; static constexpr double ITK_DIVERGED = 1.e6; - int iteration, converged; - double params[CellDimension]; - double fcol[CellDimension]; - double rcol[CellDimension]; - double scol[CellDimension]; - double d; - PointType pt; - CoordRepType derivs[NumberOfDerivatives]; - InterpolationWeightType weights[NumberOfPoints]; - // set initial position for Newton's method - int subId = 0; - CoordRepType pcoords[CellDimension]; + int subId = 0; - pcoords[0] = pcoords[1] = params[0] = params[1] = 0.5; + double params[CellDimension] = { 0.5, 0.5 }; + CoordinateType pcoords[CellDimension] = { 0.5, 0.5 }; // NOTE: Point x is here assumed to lie on the plane of Quad. Otherwise, (FIXME) // - Get normal for quadrilateral, using its 3 corners // - Project point x onto Quad plane using this normal // See vtkQuad for this: ComputeNormal (this, pt1, pt2, pt3, n); vtkPlane::ProjectPoint(x,pt1,n,cp); + // enter iteration loop - for (iteration = converged = 0; !converged && (iteration < ITK_QUAD_MAX_ITERATION); ++iteration) + InterpolationWeightType weights[NumberOfPoints]; + int converged = 0; + for (int iteration = 0; !converged && (iteration < ITK_QUAD_MAX_ITERATION); ++iteration) { // calculate element interpolation functions and derivatives this->InterpolationFunctions(pcoords, weights); + CoordinateType derivs[NumberOfDerivatives]; this->InterpolationDerivs(pcoords, derivs); // calculate newton functions - for (unsigned int i = 0; i < CellDimension; ++i) - { - fcol[i] = rcol[i] = scol[i] = 0.0; - } + double fcol[CellDimension]{}; + double rcol[CellDimension]{}; + double scol[CellDimension]{}; + for (unsigned int i = 0; i < NumberOfPoints; ++i) { - pt = points->GetElement(m_PointIds[i]); + PointType pt = points->GetElement(m_PointIds[i]); // using the projection normal n, one can choose which 2 axes to use out of 3 // any 2 should work, so (not having n) we use [x,y] (also assuming 2D use of QuadCell) // if we compute n, one can use the closest two indices as in vtkQuad @@ -332,28 +326,28 @@ QuadrilateralCell::EvaluatePosition(CoordRepType * x, } // compute determinants and generate improvements - vnl_matrix_fixed mat; + vnl_matrix_fixed mat; for (unsigned int i = 0; i < CellDimension; ++i) { mat.put(0, i, rcol[i]); mat.put(1, i, scol[i]); } - d = vnl_determinant(mat); + const double d = vnl_determinant(mat); // d=vtkMath::Determinant2x2(rcol,scol); if (itk::Math::abs(d) < 1.e-20) { return false; } - vnl_matrix_fixed mat1; + vnl_matrix_fixed mat1; for (unsigned int i = 0; i < CellDimension; ++i) { mat1.put(0, i, fcol[i]); mat1.put(1, i, scol[i]); } - vnl_matrix_fixed mat2; + vnl_matrix_fixed mat2; for (unsigned int i = 0; i < CellDimension; ++i) { mat2.put(0, i, rcol[i]); @@ -379,7 +373,7 @@ QuadrilateralCell::EvaluatePosition(CoordRepType * x, // Test for bad divergence (S.Hirschberg 11.12.2001) else if ((itk::Math::abs(pcoords[0]) > ITK_DIVERGED) || (itk::Math::abs(pcoords[1]) > ITK_DIVERGED)) { - return -1; + return false; } // if not converged, repeat @@ -417,42 +411,41 @@ QuadrilateralCell::EvaluatePosition(CoordRepType * x, } return true; } - else + + CoordinateType pc[CellDimension]; + CoordinateType w[NumberOfPoints]; + if (closestPoint) { - CoordRepType pc[CellDimension], w[NumberOfPoints]; - if (closestPoint) + for (unsigned int i = 0; i < CellDimension; ++i) // only approximate ?? { - for (unsigned int i = 0; i < CellDimension; ++i) // only approximate ?? + if (pcoords[i] < 0.0) { - if (pcoords[i] < 0.0) - { - pc[i] = 0.0; - } - else if (pcoords[i] > 1.0) - { - pc[i] = 1.0; - } - else - { - pc[i] = pcoords[i]; - } + pc[i] = 0.0; } - this->EvaluateLocation(subId, points, pc, closestPoint, (InterpolationWeightType *)w); - - *dist2 = 0; - for (unsigned int i = 0; i < CellDimension; ++i) + else if (pcoords[i] > 1.0) { - *dist2 += (closestPoint[i] - x[i]) * (closestPoint[i] - x[i]); + pc[i] = 1.0; + } + else + { + pc[i] = pcoords[i]; } } - return false; + this->EvaluateLocation(subId, points, pc, closestPoint, (InterpolationWeightType *)w); + + *dist2 = 0; + for (unsigned int i = 0; i < CellDimension; ++i) + { + *dist2 += (closestPoint[i] - x[i]) * (closestPoint[i] - x[i]); + } } + return false; } /** Compute iso-parametric interpolation functions */ template void -QuadrilateralCell::InterpolationFunctions(const CoordRepType pointCoords[CellDimension], +QuadrilateralCell::InterpolationFunctions(const CoordinateType pointCoords[CellDimension], InterpolationWeightType weights[NumberOfPoints]) { const double rm = 1. - pointCoords[0]; @@ -467,8 +460,8 @@ QuadrilateralCell::InterpolationFunctions(const CoordRepType /** Compute iso-parametric interpolation functions */ template void -QuadrilateralCell::InterpolationDerivs(const CoordRepType pointCoords[CellDimension], - CoordRepType derivs[NumberOfDerivatives]) +QuadrilateralCell::InterpolationDerivs(const CoordinateType pointCoords[CellDimension], + CoordinateType derivs[NumberOfDerivatives]) { const double rm = 1. - pointCoords[0]; const double sm = 1. - pointCoords[1]; @@ -490,15 +483,15 @@ template void QuadrilateralCell::EvaluateLocation(int & itkNotUsed(subId), const PointsContainer * points, - const CoordRepType pointCoords[PointDimension], - CoordRepType x[PointDimension], + const CoordinateType pointCoords[PointDimension], + CoordinateType x[PointDimension], InterpolationWeightType * weights) { this->InterpolationFunctions(pointCoords, weights); for (unsigned int ii = 0; ii < PointDimension; ++ii) { - x[ii] = CoordRepType{}; + x[ii] = CoordinateType{}; } for (unsigned int ii = 0; ii < NumberOfPoints; ++ii) diff --git a/Modules/Core/Common/include/itkRGBAPixel.h b/Modules/Core/Common/include/itkRGBAPixel.h index 65205478704..a5498984318 100644 --- a/Modules/Core/Common/include/itkRGBAPixel.h +++ b/Modules/Core/Common/include/itkRGBAPixel.h @@ -81,10 +81,17 @@ class ITK_TEMPLATE_EXPORT RGBAPixel : public FixedArray #ifdef ITK_FUTURE_LEGACY_REMOVE RGBAPixel() = default; #else - RGBAPixel() { this->Fill(0); } + constexpr RGBAPixel() + : Superclass(Superclass()) + { + // `: Superclass(Superclass())` is a workaround for an old compiler bug. A simple `: Superclass()` triggered + // warnings from GCC 9.4.0 saying: "warning: '' may be used uninitialized in this function + // [-Wmaybe-uninitialized]". + } #endif /** Pass-through constructor for the Array base class. */ + /** @ITKStartGrouping */ template RGBAPixel(const RGBAPixel & r) : BaseArray(r) @@ -92,6 +99,7 @@ class ITK_TEMPLATE_EXPORT RGBAPixel : public FixedArray RGBAPixel(const ComponentType r[4]) : BaseArray(r) {} + /** @ITKEndGrouping */ #if defined(ITK_LEGACY_REMOVE) /** Prevents copy-initialization from `nullptr`, as well as from `0` (NULL). */ @@ -108,15 +116,19 @@ class ITK_TEMPLATE_EXPORT RGBAPixel : public FixedArray operator=(const ComponentType r[4]); /** Arithmetic operations between pixels. Return a new RGBAPixel. */ + /** @ITKStartGrouping */ Self operator+(const Self & r) const; Self - operator-(const Self & r) const; - Self operator*(const ComponentType & r) const; + operator-(const Self & r) const; + Self + operator*(const ComponentType & r) const; Self operator/(const ComponentType & r) const; + /** @ITKEndGrouping */ /** Arithmetic-assignment operators. */ + /** @ITKStartGrouping */ const Self & operator+=(const Self & r); const Self & @@ -125,6 +137,7 @@ class ITK_TEMPLATE_EXPORT RGBAPixel : public FixedArray operator*=(const ComponentType & r); const Self & operator/=(const ComponentType & r); + /** @ITKEndGrouping */ /** Implements strict weak ordering. For use in STL, e.g. std::map. */ bool @@ -245,7 +258,7 @@ operator>>(std::istream & is, RGBAPixel & c); template inline void -swap(RGBAPixel & a, RGBAPixel & b) +swap(RGBAPixel & a, RGBAPixel & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkRGBAPixel.hxx b/Modules/Core/Common/include/itkRGBAPixel.hxx index 65d5028ec28..ac2c91d1631 100644 --- a/Modules/Core/Common/include/itkRGBAPixel.hxx +++ b/Modules/Core/Common/include/itkRGBAPixel.hxx @@ -103,7 +103,8 @@ RGBAPixel::operator/=(const ComponentType & r) } template -RGBAPixel RGBAPixel::operator*(const ComponentType & r) const +RGBAPixel +RGBAPixel::operator*(const ComponentType & r) const { Self result; diff --git a/Modules/Core/Common/include/itkRGBPixel.h b/Modules/Core/Common/include/itkRGBPixel.h index 643024b15ad..11b97597e42 100644 --- a/Modules/Core/Common/include/itkRGBPixel.h +++ b/Modules/Core/Common/include/itkRGBPixel.h @@ -80,7 +80,13 @@ class ITK_TEMPLATE_EXPORT RGBPixel : public FixedArray #ifdef ITK_FUTURE_LEGACY_REMOVE RGBPixel() = default; #else - RGBPixel() { this->Fill(0); } + constexpr RGBPixel() + : Superclass(Superclass()) + { + // `: Superclass(Superclass())` is a workaround for an old compiler bug. A simple `: Superclass()` triggered + // warnings from GCC 9.4.0 saying: "warning: '' may be used uninitialized in this function + // [-Wmaybe-uninitialized]". + } #endif #if defined(ITK_LEGACY_REMOVE) @@ -90,12 +96,14 @@ class ITK_TEMPLATE_EXPORT RGBPixel : public FixedArray /** Prevents copy-initialization from `nullptr`, as well as from `0` (NULL). */ RGBPixel(std::nullptr_t) = delete; #else + /** Constructor to fill Red=Blue=Green= r. * \note ITK_LEGACY_REMOVE=ON will disallow implicit conversion from a component value. */ RGBPixel(const ComponentType & r) { this->Fill(r); } #endif /** Pass-through constructor for the Array base class. */ + /** @ITKStartGrouping */ template RGBPixel(const RGBPixel & r) : BaseArray(r) @@ -103,8 +111,10 @@ class ITK_TEMPLATE_EXPORT RGBPixel : public FixedArray RGBPixel(const ComponentType r[3]) : BaseArray(r) {} + /** @ITKEndGrouping */ /** Pass-through assignment operator for the Array base class. */ + /** @ITKStartGrouping */ template Self & operator=(const RGBPixel & r) @@ -112,20 +122,25 @@ class ITK_TEMPLATE_EXPORT RGBPixel : public FixedArray BaseArray::operator=(r); return *this; } + /** @ITKEndGrouping */ Self & operator=(const ComponentType r[3]); /** Arithmetic operations between pixels. Return a new RGBPixel. */ + /** @ITKStartGrouping */ Self operator+(const Self & r) const; Self - operator-(const Self & r) const; - Self operator*(const ComponentType & r) const; + operator-(const Self & r) const; + Self + operator*(const ComponentType & r) const; Self operator/(const ComponentType & r) const; + /** @ITKEndGrouping */ /** Arithmetic-assignment operators. */ + /** @ITKStartGrouping */ const Self & operator+=(const Self & r); const Self & @@ -134,6 +149,7 @@ class ITK_TEMPLATE_EXPORT RGBPixel : public FixedArray operator*=(const ComponentType & r); const Self & operator/=(const ComponentType & r); + /** @ITKEndGrouping */ /** Implements strict weak ordering. For use in STL, e.g. std::map. */ bool @@ -239,7 +255,7 @@ operator>>(std::istream & is, RGBPixel & c); template inline void -swap(RGBPixel & a, RGBPixel & b) +swap(RGBPixel & a, RGBPixel & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkRGBPixel.hxx b/Modules/Core/Common/include/itkRGBPixel.hxx index e89f6ba17e5..42fee507e94 100644 --- a/Modules/Core/Common/include/itkRGBPixel.hxx +++ b/Modules/Core/Common/include/itkRGBPixel.hxx @@ -103,7 +103,8 @@ RGBPixel::operator/=(const ComponentType & r) } template -RGBPixel RGBPixel::operator*(const ComponentType & r) const +RGBPixel +RGBPixel::operator*(const ComponentType & r) const { Self result; diff --git a/Modules/Core/Common/include/itkRealTimeInterval.h b/Modules/Core/Common/include/itkRealTimeInterval.h index 1ff0041649c..8fe97379dad 100644 --- a/Modules/Core/Common/include/itkRealTimeInterval.h +++ b/Modules/Core/Common/include/itkRealTimeInterval.h @@ -64,6 +64,7 @@ class ITKCommon_EXPORT RealTimeInterval using TimeRepresentationType = double; /** Return time in multiple units. */ + /** @ITKStartGrouping */ TimeRepresentationType GetTimeInMicroSeconds() const; TimeRepresentationType @@ -76,8 +77,9 @@ class ITKCommon_EXPORT RealTimeInterval GetTimeInHours() const; TimeRepresentationType GetTimeInDays() const; - + /** @ITKEndGrouping */ /** Arithmetic operations between RealTimeInterval and RealTimeInterval. */ + /** @ITKStartGrouping */ Self operator-(const Self &) const; Self @@ -86,8 +88,9 @@ class ITKCommon_EXPORT RealTimeInterval operator-=(const Self &); const Self & operator+=(const Self &); - + /** @ITKEndGrouping */ /** Comparison operations. */ + /** @ITKStartGrouping */ bool operator>(const Self &) const; bool @@ -99,7 +102,7 @@ class ITKCommon_EXPORT RealTimeInterval operator<=(const Self &) const; bool operator>=(const Self &) const; - + /** @ITKEndGrouping */ /** Set with values. The units and signs of the seconds and microseconds will * be harmonized internally. */ void Set(SecondsDifferenceType, MicroSecondsDifferenceType); diff --git a/Modules/Core/Common/include/itkRealTimeStamp.h b/Modules/Core/Common/include/itkRealTimeStamp.h index 2d67122e98f..c0d8b7a7893 100644 --- a/Modules/Core/Common/include/itkRealTimeStamp.h +++ b/Modules/Core/Common/include/itkRealTimeStamp.h @@ -61,6 +61,7 @@ class ITKCommon_EXPORT RealTimeStamp using TimeRepresentationType = RealTimeInterval::TimeRepresentationType; /** Return time in multiple units. */ + /** @ITKStartGrouping */ TimeRepresentationType GetTimeInMicroSeconds() const; TimeRepresentationType @@ -73,8 +74,9 @@ class ITKCommon_EXPORT RealTimeStamp GetTimeInHours() const; TimeRepresentationType GetTimeInDays() const; - + /** @ITKEndGrouping */ /** Arithmetic operations between RealTimeInterval and RealTimeStamp. */ + /** @ITKStartGrouping */ RealTimeInterval operator-(const Self &) const; Self @@ -85,8 +87,9 @@ class ITKCommon_EXPORT RealTimeStamp operator+=(const RealTimeInterval &); const Self & operator-=(const RealTimeInterval &); - + /** @ITKEndGrouping */ /** Comparison operations. */ + /** @ITKStartGrouping */ bool operator>(const Self &) const; bool @@ -98,7 +101,7 @@ class ITKCommon_EXPORT RealTimeStamp operator<=(const Self &) const; bool operator>=(const Self &) const; - + /** @ITKEndGrouping */ /** Default print out of a RealTimeStamp */ friend ITKCommon_EXPORT std::ostream & operator<<(std::ostream & os, const RealTimeStamp & v); diff --git a/Modules/Core/Common/include/itkRegularizedHeavisideStepFunction.h b/Modules/Core/Common/include/itkRegularizedHeavisideStepFunction.h index f3322c8270d..a1dbb9982ab 100644 --- a/Modules/Core/Common/include/itkRegularizedHeavisideStepFunction.h +++ b/Modules/Core/Common/include/itkRegularizedHeavisideStepFunction.h @@ -28,21 +28,9 @@ namespace itk * * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. * - * This code was taken from the Insight Journal paper: - * - * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" - * https://www.insight-journal.org/browse/publication/642 - * - * That is based on the papers: - * - * "Level Set Segmentation: Active Contours without edge" - * https://www.insight-journal.org/browse/publication/322 - * - * and - * - * "Level set segmentation using coupled active surfaces" - * https://www.insight-journal.org/browse/publication/323 - * + * This code was taken from the Insight Journal paper \cite Mosaliganti_2009_c + * that is based on the papers \cite Mosaliganti_2009_a and + * \cite Mosaliganti_2009_b. * * \ingroup ITKCommon */ diff --git a/Modules/Core/Common/include/itkResourceProbe.hxx b/Modules/Core/Common/include/itkResourceProbe.hxx index 9af6cff8aff..cae2dd06c0a 100644 --- a/Modules/Core/Common/include/itkResourceProbe.hxx +++ b/Modules/Core/Common/include/itkResourceProbe.hxx @@ -91,17 +91,17 @@ template void ResourceProbe::Reset() { - this->m_TotalValue = ValueType{}; - this->m_StartValue = ValueType{}; - this->m_MinimumValue = NumericTraits::max(); - this->m_MaximumValue = NumericTraits::NonpositiveMin(); - this->m_StandardDeviation = ValueType{}; + m_TotalValue = ValueType{}; + m_StartValue = ValueType{}; + m_MinimumValue = NumericTraits::max(); + m_MaximumValue = NumericTraits::NonpositiveMin(); + m_StandardDeviation = ValueType{}; - this->m_NumberOfStarts = CountType{}; - this->m_NumberOfStops = CountType{}; - this->m_NumberOfIteration = CountType{}; + m_NumberOfStarts = CountType{}; + m_NumberOfStops = CountType{}; + m_NumberOfIteration = CountType{}; - this->m_ProbeValueList.clear(); + m_ProbeValueList.clear(); } @@ -109,7 +109,7 @@ template std::string ResourceProbe::GetType() const { - return this->m_TypeString; + return m_TypeString; } @@ -117,7 +117,7 @@ template std::string ResourceProbe::GetUnit() const { - return this->m_UnitString; + return m_UnitString; } @@ -125,8 +125,8 @@ template void ResourceProbe::Start() { - this->m_NumberOfStarts++; - this->m_StartValue = this->GetInstantValue(); + ++m_NumberOfStarts; + m_StartValue = this->GetInstantValue(); } @@ -134,17 +134,17 @@ template void ResourceProbe::Stop() { - ValueType probevalue = this->GetInstantValue() - this->m_StartValue; - if (this->m_NumberOfStops == this->m_NumberOfStarts) + ValueType probevalue = this->GetInstantValue() - m_StartValue; + if (m_NumberOfStops == m_NumberOfStarts) { return; } this->UpdateMinimumMaximumMeasuredValue(probevalue); - this->m_TotalValue += probevalue; - this->m_ProbeValueList.push_back(probevalue); - this->m_NumberOfStops++; - this->m_NumberOfIteration = static_cast(this->m_ProbeValueList.size()); + m_TotalValue += probevalue; + m_ProbeValueList.push_back(probevalue); + ++m_NumberOfStops; + m_NumberOfIteration = static_cast(m_ProbeValueList.size()); } @@ -152,7 +152,7 @@ template auto ResourceProbe::GetNumberOfStarts() const -> CountType { - return this->m_NumberOfStarts; + return m_NumberOfStarts; } @@ -160,7 +160,7 @@ template auto ResourceProbe::GetNumberOfStops() const -> CountType { - return this->m_NumberOfStops; + return m_NumberOfStops; } @@ -168,7 +168,7 @@ template auto ResourceProbe::GetNumberOfIteration() const -> CountType { - return this->m_NumberOfIteration; + return m_NumberOfIteration; } @@ -176,7 +176,7 @@ template ValueType ResourceProbe::GetTotal() const { - return this->m_TotalValue; + return m_TotalValue; } @@ -186,9 +186,9 @@ ResourceProbe::GetMean() const { MeanType meanValue{}; - if (this->m_NumberOfStops) + if (m_NumberOfStops) { - meanValue = static_cast(this->m_TotalValue) / static_cast(this->m_NumberOfStops); + meanValue = static_cast(m_TotalValue) / static_cast(m_NumberOfStops); } return meanValue; @@ -199,7 +199,7 @@ template ValueType ResourceProbe::GetMinimum() const { - return this->m_MinimumValue; + return m_MinimumValue; } @@ -207,7 +207,7 @@ template ValueType ResourceProbe::GetMaximum() const { - return this->m_MaximumValue; + return m_MaximumValue; } @@ -217,24 +217,24 @@ ResourceProbe::GetStandardDeviation() { using InternalComputeType = typename NumericTraits::RealType; const auto realMean = static_cast(this->GetMean()); - std::vector diff(this->m_ProbeValueList.size()); - std::transform(this->m_ProbeValueList.begin(), - this->m_ProbeValueList.end(), + std::vector diff(m_ProbeValueList.size()); + std::transform(m_ProbeValueList.begin(), + m_ProbeValueList.end(), diff.begin(), // Subtract mean from every value; [realMean](const ValueType v) { return (static_cast(v) - realMean); }); const InternalComputeType sqsum = std::inner_product(diff.begin(), diff.end(), diff.begin(), InternalComputeType{}); - const InternalComputeType sz = static_cast(this->m_ProbeValueList.size()) - 1.0; + const InternalComputeType sz = static_cast(m_ProbeValueList.size()) - 1.0; if (sz <= 0.0) { - this->m_StandardDeviation = ValueType{}; + m_StandardDeviation = ValueType{}; } else { - this->m_StandardDeviation = static_cast(std::sqrt(sqsum / sz)); + m_StandardDeviation = static_cast(std::sqrt(sqsum / sz)); } - return this->m_StandardDeviation; + return m_StandardDeviation; } @@ -243,9 +243,8 @@ ValueType ResourceProbe::GetStandardError() { const ValueType standardDeviation = this->GetStandardDeviation(); - this->m_StandardError = - static_cast(standardDeviation / std::sqrt(static_cast(this->m_ProbeValueList.size()))); - return this->m_StandardError; + m_StandardError = static_cast(standardDeviation / std::sqrt(static_cast(m_ProbeValueList.size()))); + return m_StandardError; } @@ -253,7 +252,7 @@ template void ResourceProbe::SetNameOfProbe(const char * nameOfProbe) { - this->m_NameOfProbe = nameOfProbe; + m_NameOfProbe = nameOfProbe; } @@ -261,7 +260,7 @@ template std::string ResourceProbe::GetNameOfProbe() const { - return this->m_NameOfProbe; + return m_NameOfProbe; } template @@ -313,14 +312,14 @@ ResourceProbe::Report(std::ostream & os, bool printSystemIn std::stringstream ss; if (useTabs) { - ss << std::left << '\t' << this->m_NameOfProbe << std::left << '\t' << this->m_NumberOfIteration << std::left - << '\t' << this->GetTotal() << std::left << '\t' << this->GetMinimum() << std::left << '\t' << this->GetMean() + ss << std::left << '\t' << m_NameOfProbe << std::left << '\t' << m_NumberOfIteration << std::left << '\t' + << this->GetTotal() << std::left << '\t' << this->GetMinimum() << std::left << '\t' << this->GetMean() << std::left << '\t' << this->GetMaximum() << std::left << '\t' << this->GetStandardDeviation(); } else { - ss << std::left << std::setw(tabwidth * 2) << this->m_NameOfProbe << std::left << std::setw(tabwidth) - << this->m_NumberOfIteration << std::left << std::setw(tabwidth) << this->GetTotal() << std::left + ss << std::left << std::setw(tabwidth * 2) << m_NameOfProbe << std::left << std::setw(tabwidth) + << m_NumberOfIteration << std::left << std::setw(tabwidth) << this->GetTotal() << std::left << std::setw(tabwidth) << this->GetMinimum() << std::left << std::setw(tabwidth) << this->GetMean() << std::left << std::setw(tabwidth) << this->GetMaximum() << std::left << std::setw(tabwidth) << this->GetStandardDeviation(); } @@ -369,8 +368,8 @@ ResourceProbe::ExpandedReport(std::ostream & os, if (useTabs) { - ss << std::left << '\t' << this->m_NameOfProbe << std::left << '\t' << this->m_NumberOfIteration << std::left - << '\t' << this->GetTotal() << std::left << '\t' << this->GetMinimum() << std::left << '\t' + ss << std::left << '\t' << m_NameOfProbe << std::left << '\t' << m_NumberOfIteration << std::left << '\t' + << this->GetTotal() << std::left << '\t' << this->GetMinimum() << std::left << '\t' << this->GetMean() - this->GetMinimum() << std::left << '\t' << ratioOfMeanToMinimum * 100 << std::left << '\t' << this->GetMean() << std::left << '\t' << this->GetMaximum() - this->GetMean() << std::left << '\t' << ratioOfMaximumToMean * 100 << std::left << '\t' << this->GetMaximum() << std::left << '\t' @@ -379,8 +378,8 @@ ResourceProbe::ExpandedReport(std::ostream & os, } else { - ss << std::left << std::setw(tabwidth * 2) << this->m_NameOfProbe << std::left << std::setw(tabwidth) - << this->m_NumberOfIteration << std::left << std::setw(tabwidth) << this->GetTotal() << std::left + ss << std::left << std::setw(tabwidth * 2) << m_NameOfProbe << std::left << std::setw(tabwidth) + << m_NumberOfIteration << std::left << std::setw(tabwidth) << this->GetTotal() << std::left << std::setw(tabwidth) << this->GetMinimum() << std::left << std::setw(tabwidth) << this->GetMean() - this->GetMinimum() << std::left << std::setw(tabwidth) << ratioOfMeanToMinimum * 100 << std::left << std::setw(tabwidth) << this->GetMean() << std::left << std::setw(tabwidth) @@ -402,7 +401,7 @@ ResourceProbe::PrintJSONvar(std::ostream & os, unsigned int indent, bool comma) { - bool varIsNumber = mpl::IsNumber::Value; + const bool varIsNumber = mpl::IsNumber::Value; while (indent > 0) { os << ' '; @@ -427,8 +426,6 @@ template void ResourceProbe::JSONReport(std::ostream & os) { - std::stringstream ss; - ValueType ratioOfMeanToMinimum; if (Math::ExactlyEquals(this->GetMinimum(), 0.0)) { @@ -475,14 +472,14 @@ template void ResourceProbe::UpdateMinimumMaximumMeasuredValue(ValueType value) { - if (this->m_MinimumValue > value) + if (m_MinimumValue > value) { - this->m_MinimumValue = value; + m_MinimumValue = value; } - if (this->m_MaximumValue < value) + if (m_MaximumValue < value) { - this->m_MaximumValue = value; + m_MaximumValue = value; } } @@ -494,22 +491,22 @@ ResourceProbe::PrintReportHead(std::ostream & os, bool useT std::stringstream ss; if (useTabs) { - ss << std::left << '\t' << std::string("Name Of Probe (") + this->m_TypeString + std::string(")") << std::left - << '\t' << "Iterations" << std::left << '\t' << std::string("Total (") + this->m_UnitString + std::string(")") - << std::left << '\t' << std::string("Min (") + this->m_UnitString + std::string(")") << std::left << '\t' - << std::string("Mean (") + this->m_UnitString + std::string(")") << std::left << '\t' - << std::string("Max (") + this->m_UnitString + std::string(")") << std::left << '\t' - << std::string("StdDev (") + this->m_UnitString + std::string(")"); + ss << std::left << '\t' << std::string("Name Of Probe (") + m_TypeString + std::string(")") << std::left << '\t' + << "Iterations" << std::left << '\t' << std::string("Total (") + m_UnitString + std::string(")") << std::left + << '\t' << std::string("Min (") + m_UnitString + std::string(")") << std::left << '\t' + << std::string("Mean (") + m_UnitString + std::string(")") << std::left << '\t' + << std::string("Max (") + m_UnitString + std::string(")") << std::left << '\t' + << std::string("StdDev (") + m_UnitString + std::string(")"); } else { - ss << std::left << std::setw(tabwidth * 2) << std::string("Name Of Probe (") + this->m_TypeString + std::string(")") + ss << std::left << std::setw(tabwidth * 2) << std::string("Name Of Probe (") + m_TypeString + std::string(")") << std::left << std::setw(tabwidth) << "Iterations" << std::left << std::setw(tabwidth) - << std::string("Total (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) - << std::string("Min (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) - << std::string("Mean (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) - << std::string("Max (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) - << std::string("StdDev (") + this->m_UnitString + std::string(")"); + << std::string("Total (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("Min (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("Mean (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("Max (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("StdDev (") + m_UnitString + std::string(")"); } os << ss.str() << std::endl; @@ -523,30 +520,29 @@ ResourceProbe::PrintExpandedReportHead(std::ostream & os, b std::stringstream ss; if (useTabs) { - ss << std::left << '\t' << std::string("Name Of Probe (") + this->m_TypeString + std::string(")") << std::left - << '\t' << "Iterations" << std::left << '\t' << std::string("Total (") + this->m_UnitString + std::string(")") - << std::left << '\t' << std::string("Min (") + this->m_UnitString + std::string(")") << std::left << '\t' - << "Mean-Min (diff)" << std::left << '\t' << "Mean/Min (%)" << std::left << '\t' - << std::string("Mean (") + this->m_UnitString + std::string(")") << std::left << '\t' << "Max-Mean (diff)" - << std::left << '\t' << "Max/Mean (%)" << std::left << '\t' - << std::string("Max (") + this->m_UnitString + std::string(")") << std::left << '\t' - << std::string("Total Diff (") + this->m_UnitString + std::string(")") << std::left << '\t' - << std::string("StdDev (") + this->m_UnitString + std::string(")") << std::left << '\t' - << std::string("StdErr (") + this->m_UnitString + std::string(")"); + ss << std::left << '\t' << std::string("Name Of Probe (") + m_TypeString + std::string(")") << std::left << '\t' + << "Iterations" << std::left << '\t' << std::string("Total (") + m_UnitString + std::string(")") << std::left + << '\t' << std::string("Min (") + m_UnitString + std::string(")") << std::left << '\t' << "Mean-Min (diff)" + << std::left << '\t' << "Mean/Min (%)" << std::left << '\t' + << std::string("Mean (") + m_UnitString + std::string(")") << std::left << '\t' << "Max-Mean (diff)" << std::left + << '\t' << "Max/Mean (%)" << std::left << '\t' << std::string("Max (") + m_UnitString + std::string(")") + << std::left << '\t' << std::string("Total Diff (") + m_UnitString + std::string(")") << std::left << '\t' + << std::string("StdDev (") + m_UnitString + std::string(")") << std::left << '\t' + << std::string("StdErr (") + m_UnitString + std::string(")"); } else { - ss << std::left << std::setw(tabwidth * 2) << std::string("Name Of Probe (") + this->m_TypeString + std::string(")") + ss << std::left << std::setw(tabwidth * 2) << std::string("Name Of Probe (") + m_TypeString + std::string(")") << std::left << std::setw(tabwidth) << "Iterations" << std::left << std::setw(tabwidth) - << std::string("Total (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) - << std::string("Min (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("Total (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("Min (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) << "Mean-Min (diff)" << std::left << std::setw(tabwidth) << "Mean/Min (%)" << std::left << std::setw(tabwidth) - << std::string("Mean (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("Mean (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) << "Max-Mean (diff)" << std::left << std::setw(tabwidth) << "Max/Mean (%)" << std::left << std::setw(tabwidth) - << std::string("Max (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) - << std::string("Total Diff (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) - << std::string("StdDev (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth) - << std::string("StdErr (") + this->m_UnitString + std::string(")"); + << std::string("Max (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("Total Diff (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("StdDev (") + m_UnitString + std::string(")") << std::left << std::setw(tabwidth) + << std::string("StdErr (") + m_UnitString + std::string(")"); } os << ss.str() << std::endl; @@ -585,10 +581,9 @@ ResourceProbe::PrintJSONSystemInformation(std::ostream & os PrintJSONvar(os, "Bitness", (systeminfo.Is64Bits() ? "64 bit" : "32 bit"), 6, false); os << " },\n"; - std::ostringstream itkVersionStringStream; - itkVersionStringStream << ITK_VERSION_STRING << '.' << ITK_VERSION_PATCH; + const std::string itkVersionString = ITK_VERSION_STRING "." + std::to_string(ITK_VERSION_PATCH); - PrintJSONvar(os, "ITKVersion", itkVersionStringStream.str(), 4, false); + PrintJSONvar(os, "ITKVersion", itkVersionString, 4, false); os << " }"; } diff --git a/Modules/Core/Common/include/itkResourceProbesCollectorBase.hxx b/Modules/Core/Common/include/itkResourceProbesCollectorBase.hxx index d3c150d79f6..fe21dd46fb6 100644 --- a/Modules/Core/Common/include/itkResourceProbesCollectorBase.hxx +++ b/Modules/Core/Common/include/itkResourceProbesCollectorBase.hxx @@ -37,7 +37,7 @@ template void ResourceProbesCollectorBase::Stop(const char * id) { - IdType tid = id; + const IdType tid = id; auto pos = this->m_Probes.find(tid); if (pos == this->m_Probes.end()) @@ -52,7 +52,7 @@ template const TProbe & ResourceProbesCollectorBase::GetProbe(const char * id) const { - IdType tid = id; + const IdType tid = id; auto pos = this->m_Probes.find(tid); if (pos == this->m_Probes.end()) @@ -67,8 +67,8 @@ template void ResourceProbesCollectorBase::Report(std::ostream & os, bool printSystemInfo, bool printReportHead, bool useTabs) { - auto probe = this->m_Probes.begin(); - typename MapType::const_iterator end = this->m_Probes.end(); + auto probe = this->m_Probes.begin(); + const auto end = this->m_Probes.end(); if (probe == end) { @@ -122,8 +122,8 @@ ResourceProbesCollectorBase::ExpandedReport(std::ostream & os, bool printReportHead, bool useTabs) { - auto probe = this->m_Probes.begin(); - typename MapType::const_iterator end = this->m_Probes.end(); + auto probe = this->m_Probes.begin(); + const auto end = this->m_Probes.end(); if (probe == end) { @@ -174,8 +174,8 @@ template void ResourceProbesCollectorBase::JSONReport(std::ostream & os, bool printSystemInfo) { - auto probe = this->m_Probes.begin(); - typename MapType::const_iterator end = this->m_Probes.end(); + auto probe = this->m_Probes.begin(); + const auto end = this->m_Probes.end(); if (probe == end) { diff --git a/Modules/Core/Common/include/itkSTLConstContainerAdaptor.h b/Modules/Core/Common/include/itkSTLConstContainerAdaptor.h index 670c38e3f7c..b9ef269e1b2 100644 --- a/Modules/Core/Common/include/itkSTLConstContainerAdaptor.h +++ b/Modules/Core/Common/include/itkSTLConstContainerAdaptor.h @@ -36,7 +36,7 @@ namespace itk * Here's a usage example of STLContainerAdaptor * \code - itk::STLConstContainerAdaptor> vecAdaptor(aContainer); + itk::STLConstContainerAdaptor> vecAdaptor(aContainer); const std::vector & vec = vecAdaptor.GetSTLContainerRef(); // do things with vec ... \endcode diff --git a/Modules/Core/Common/include/itkSTLContainerAdaptor.h b/Modules/Core/Common/include/itkSTLContainerAdaptor.h index ce92df6a2bb..cc3ef0df6ab 100644 --- a/Modules/Core/Common/include/itkSTLContainerAdaptor.h +++ b/Modules/Core/Common/include/itkSTLContainerAdaptor.h @@ -32,7 +32,7 @@ namespace itk * Here's a usage example of STLContainerAdaptor: * \code - itk::STLContainerAdaptor> vecAdaptor(aContainer); + itk::STLContainerAdaptor> vecAdaptor(aContainer); std::vector & vec = vecAdaptor.GetSTLContainerRef(); // do things with vec ... // upon return from function, vecAdaptor is destroyed and aContainer is Modified() diff --git a/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.h b/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.h index 5d42b304544..82814dd62ab 100644 --- a/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.h +++ b/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.h @@ -33,7 +33,7 @@ namespace itk * to pixels. * * Contributed as a paper to the Insight Journal: - * https://www.insight-journal.org/browse/publication/204 + * https://doi.org/10.54294/iei8xt * * \ingroup ImageIterators * diff --git a/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.hxx b/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.hxx index 14fa816c52d..754e9f3d7b3 100644 --- a/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.hxx +++ b/Modules/Core/Common/include/itkShapedFloodFilledFunctionConditionalConstIterator.hxx @@ -27,7 +27,7 @@ ShapedFloodFilledFunctionConditionalConstIterator::ShapedFloo const ImageType * imagePtr, FunctionType * fnPtr, IndexType startIndex) - : m_FullyConnected(false) + { this->m_Image = imagePtr; m_Function = fnPtr; @@ -43,12 +43,10 @@ ShapedFloodFilledFunctionConditionalConstIterator::ShapedFloo FunctionType * fnPtr, std::vector & startIndex) : m_Function(fnPtr) - , m_FullyConnected(false) + { this->m_Image = imagePtr; // can not be done in the initialization list - - unsigned int i; - for (i = 0; i < startIndex.size(); ++i) + for (unsigned int i = 0; i < startIndex.size(); ++i) { m_Seeds.push_back(startIndex[i]); } @@ -61,7 +59,7 @@ template ShapedFloodFilledFunctionConditionalConstIterator::ShapedFloodFilledFunctionConditionalConstIterator( const ImageType * imagePtr, FunctionType * fnPtr) - : m_FullyConnected(false) + { this->m_Image = imagePtr; m_Function = fnPtr; @@ -80,17 +78,16 @@ ShapedFloodFilledFunctionConditionalConstIterator::Initialize m_ImageRegion = this->m_Image->GetBufferedRegion(); // Build and setup the neighborhood iterator - typename NeighborhoodIteratorType::RadiusType radius; - radius.Fill(1); + constexpr auto radius = MakeFilled(1); - NeighborhoodIteratorType tmp_iter(radius, this->m_Image, m_ImageRegion); + const NeighborhoodIteratorType tmp_iter(radius, this->m_Image, m_ImageRegion); m_NeighborhoodIterator = tmp_iter; setConnectivity(&m_NeighborhoodIterator, m_FullyConnected); // Build a temporary image of chars for use in the flood algorithm m_TempPtr = TTempImage::New(); - typename TTempImage::RegionType tempRegion = this->m_Image->GetBufferedRegion(); + const typename TTempImage::RegionType tempRegion = this->m_Image->GetBufferedRegion(); m_TempPtr->SetRegions(tempRegion); m_TempPtr->AllocateInitialized(); diff --git a/Modules/Core/Common/include/itkShapedFloodFilledImageFunctionConditionalConstIterator.h b/Modules/Core/Common/include/itkShapedFloodFilledImageFunctionConditionalConstIterator.h index 6d8963707a4..4c29c79f421 100644 --- a/Modules/Core/Common/include/itkShapedFloodFilledImageFunctionConditionalConstIterator.h +++ b/Modules/Core/Common/include/itkShapedFloodFilledImageFunctionConditionalConstIterator.h @@ -28,7 +28,7 @@ namespace itk * access to pixels. * * Contributed as a paper to the Insight Journal: - * https://www.insight-journal.org/browse/publication/204 + * https://doi.org/10.54294/iei8xt * * \ingroup ImageIterators * diff --git a/Modules/Core/Common/include/itkShapedFloodFilledImageFunctionConditionalIterator.h b/Modules/Core/Common/include/itkShapedFloodFilledImageFunctionConditionalIterator.h index a244b838de7..3832fac882b 100644 --- a/Modules/Core/Common/include/itkShapedFloodFilledImageFunctionConditionalIterator.h +++ b/Modules/Core/Common/include/itkShapedFloodFilledImageFunctionConditionalIterator.h @@ -28,7 +28,7 @@ namespace itk * to pixels. * * Contributed as a paper to the Insight Journal: - * https://www.insight-journal.org/browse/publication/204 + * https://doi.org/10.54294/iei8xt * * \ingroup ImageIterators * diff --git a/Modules/Core/Common/include/itkShapedImageNeighborhoodRange.h b/Modules/Core/Common/include/itkShapedImageNeighborhoodRange.h index a6594c22c9b..ec74b895a13 100644 --- a/Modules/Core/Common/include/itkShapedImageNeighborhoodRange.h +++ b/Modules/Core/Common/include/itkShapedImageNeighborhoodRange.h @@ -347,7 +347,8 @@ class ShapedImageNeighborhoodRange final {} - TImageNeighborhoodPixelAccessPolicy CreatePixelAccessPolicy(EmptyPixelAccessParameter) const + TImageNeighborhoodPixelAccessPolicy + CreatePixelAccessPolicy(EmptyPixelAccessParameter) const { return TImageNeighborhoodPixelAccessPolicy{ m_ImageSize, m_OffsetTable, m_NeighborhoodAccessor, m_RelativeLocation + *m_CurrentOffset @@ -403,7 +404,8 @@ class ShapedImageNeighborhoodRange final /** Returns a reference to the current pixel. */ - reference operator*() const noexcept + reference + operator*() const noexcept { return reference{ m_ImageBufferPointer, CreatePixelAccessPolicy(m_OptionalPixelAccessParameter) }; } @@ -566,7 +568,11 @@ class ShapedImageNeighborhoodRange final /** Returns it[n] for iterator 'it' and integer value 'n'. */ - reference operator[](const difference_type n) const noexcept { return *(*this + n); } + reference + operator[](const difference_type n) const noexcept + { + return *(*this + n); + } }; static constexpr bool IsImageTypeConst = std::is_const_v; @@ -777,7 +783,8 @@ class ShapedImageNeighborhoodRange final * iterator::reference. The return value is a proxy object that behaves like a * reference to the pixel. */ - typename QualifiedIterator::reference operator[](const size_t n) const noexcept + typename QualifiedIterator::reference + operator[](const size_t n) const noexcept { assert(n < this->size()); assert(n <= static_cast(std::numeric_limits::max())); diff --git a/Modules/Core/Common/include/itkShapedNeighborhoodIterator.h b/Modules/Core/Common/include/itkShapedNeighborhoodIterator.h index 9f24917141d..463170d239e 100644 --- a/Modules/Core/Common/include/itkShapedNeighborhoodIterator.h +++ b/Modules/Core/Common/include/itkShapedNeighborhoodIterator.h @@ -82,8 +82,7 @@ namespace itk it.ActivateOffset(offset3); // etc.. ... - ShapedNeighborhoodIterator::Iterator i; - for (i = it.Begin(); ! i.IsAtEnd(); ++i) + for (auto i = it.Begin(); ! i.IsAtEnd(); ++i) { i.Set(i.Get() + 1.0); } // you may also use i != i.End(), but IsAtEnd() may be slightly faster. \endcode @@ -186,7 +185,7 @@ class ITK_TEMPLATE_EXPORT ShapedNeighborhoodIterator : ConstIterator(s) {} - ~Iterator() ITK_ITERATOR_OVERRIDE = default; + ~Iterator() = default; Iterator & operator=(const Iterator & o) { @@ -240,6 +239,7 @@ class ITK_TEMPLATE_EXPORT ShapedNeighborhoodIterator /** Returns a const iterator for the neighborhood which points to the first * pixel in the neighborhood. */ + /** @ITKStartGrouping */ Iterator Begin() { @@ -250,6 +250,7 @@ class ITK_TEMPLATE_EXPORT ShapedNeighborhoodIterator { return Iterator(this, this->m_ActiveIndexList.end()); } + /** @ITKEndGrouping */ using Superclass::Begin; using Superclass::End; diff --git a/Modules/Core/Common/include/itkSimpleDataObjectDecorator.h b/Modules/Core/Common/include/itkSimpleDataObjectDecorator.h index 83aadf5dd05..152aefc79e7 100644 --- a/Modules/Core/Common/include/itkSimpleDataObjectDecorator.h +++ b/Modules/Core/Common/include/itkSimpleDataObjectDecorator.h @@ -88,6 +88,7 @@ class ITK_TEMPLATE_EXPORT SimpleDataObjectDecorator : public DataObject Set(const T & val); /** Get the contained object */ + /** @ITKStartGrouping */ virtual T & Get() { @@ -98,7 +99,7 @@ class ITK_TEMPLATE_EXPORT SimpleDataObjectDecorator : public DataObject { return m_Component; } - + /** @ITKEndGrouping */ protected: SimpleDataObjectDecorator() = default; ~SimpleDataObjectDecorator() override = default; diff --git a/Modules/Core/Common/include/itkSimpleFilterWatcher.h b/Modules/Core/Common/include/itkSimpleFilterWatcher.h index 6bfbaa87d06..43740fb6421 100644 --- a/Modules/Core/Common/include/itkSimpleFilterWatcher.h +++ b/Modules/Core/Common/include/itkSimpleFilterWatcher.h @@ -96,6 +96,7 @@ class ITKCommon_EXPORT SimpleFilterWatcher /** Methods to control the verbosity of the messages. Quiet * reporting limits the information emitted at a ProgressEvent. */ + /** @ITKStartGrouping */ void QuietOn() { @@ -106,10 +107,12 @@ class ITKCommon_EXPORT SimpleFilterWatcher { m_Quiet = false; } + /** @ITKEndGrouping */ /** Methods to use to test the AbortEvent of the a filter. If * TestAbort is on, the filter being watched will be aborted when * the progress reaches 30%. */ + /** @ITKStartGrouping */ void TestAbortOn() { @@ -120,8 +123,10 @@ class ITKCommon_EXPORT SimpleFilterWatcher { m_TestAbort = false; } + /** @ITKEndGrouping */ /** Methods to access member data */ + /** Get a pointer to the process object being watched. */ ProcessObject * GetProcess() @@ -130,6 +135,7 @@ class ITKCommon_EXPORT SimpleFilterWatcher } /** Set/Get the steps completed. */ + /** @ITKStartGrouping */ void SetSteps(int val) { @@ -140,8 +146,10 @@ class ITKCommon_EXPORT SimpleFilterWatcher { return m_Steps; } + /** @ITKEndGrouping */ /** Set/Get the number of iterations completed. */ + /** @ITKStartGrouping */ void SetIterations(int val) { @@ -152,9 +160,11 @@ class ITKCommon_EXPORT SimpleFilterWatcher { return m_Iterations; } + /** @ITKEndGrouping */ /** Set/Get the quiet mode boolean. If true, verbose progress is * reported. */ + /** @ITKStartGrouping */ void SetQuiet(bool val) { @@ -165,6 +175,7 @@ class ITKCommon_EXPORT SimpleFilterWatcher { return m_Quiet; } + /** @ITKEndGrouping */ /** Get the comment for the watcher. */ std::string diff --git a/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.h b/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.h index 1c71ddf4faa..92907313e34 100644 --- a/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.h +++ b/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.h @@ -28,21 +28,9 @@ namespace itk * * \author Mosaliganti K., Smith B., Gelas A., Gouaillard A., Megason S. * - * This code was taken from the Insight Journal paper: - * - * "Cell Tracking using Coupled Active Surfaces for Nuclei and Membranes" - * https://www.insight-journal.org/browse/publication/642 - * - * That is based on the papers: - * - * "Level Set Segmentation: Active Contours without edge" - * https://www.insight-journal.org/browse/publication/322 - * - * and - * - * "Level set segmentation using coupled active surfaces" - * https://www.insight-journal.org/browse/publication/323 - * + * This code was taken from the Insight Journal paper \cite Mosaliganti_2009_c + * that is based on the papers \cite Mosaliganti_2009_a and + * \cite Mosaliganti_2009_b. * * \ingroup ITKCommon */ diff --git a/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.hxx b/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.hxx index 060b113690b..3be2f12c4b8 100644 --- a/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.hxx +++ b/Modules/Core/Common/include/itkSinRegularizedHeavisideStepFunction.hxx @@ -30,19 +30,17 @@ SinRegularizedHeavisideStepFunction::Evaluate(const InputType & { return NumericTraits::OneValue(); } + + if (static_cast(input) <= -this->GetEpsilon()) + { + return OutputType{}; + } else { - if (static_cast(input) <= -this->GetEpsilon()) - { - return OutputType{}; - } - else - { - const RealType angleFactor = 0.5 * itk::Math::pi * this->GetOneOverEpsilon(); - const RealType angle = input * angleFactor; + const RealType angleFactor = 0.5 * itk::Math::pi * this->GetOneOverEpsilon(); + const RealType angle = input * angleFactor; - return static_cast(0.5 * (1.0 + std::sin(angle))); - } + return static_cast(0.5 * (1.0 + std::sin(angle))); } } @@ -54,13 +52,11 @@ SinRegularizedHeavisideStepFunction::EvaluateDerivative(const I { return OutputType{}; } - else - { - const RealType angleFactor = 0.5 * itk::Math::pi * this->GetOneOverEpsilon(); - const RealType angle = input * angleFactor; - return static_cast(0.5 * angleFactor * std::cos(angle)); - } + const RealType angleFactor = 0.5 * itk::Math::pi * this->GetOneOverEpsilon(); + const RealType angle = input * angleFactor; + + return static_cast(0.5 * angleFactor * std::cos(angle)); } } // namespace itk diff --git a/Modules/Core/Common/include/itkSingleton.h b/Modules/Core/Common/include/itkSingleton.h index a0847f87323..fc747dfb717 100644 --- a/Modules/Core/Common/include/itkSingleton.h +++ b/Modules/Core/Common/include/itkSingleton.h @@ -33,7 +33,8 @@ */ template [[deprecated("Preferably use the C++ `[[maybe_unused]]` attribute instead!")]] inline void -Unused(const T &){}; +Unused(const T &) +{} #endif namespace itk @@ -77,12 +78,12 @@ class ITKCommon_EXPORT SingletonIndex #ifndef ITK_FUTURE_LEGACY_REMOVE template - [[deprecated("Prefer calling the SetGlobalInstance(globalName, global, deleteFunc) overload (without the unused func " - "parameter)!")]] bool - SetGlobalInstance(const char * globalName, - T * global, - std::function itkNotUsed(func), - std::function deleteFunc) + ITK_FUTURE_DEPRECATED("Prefer calling the SetGlobalInstance(globalName, global, deleteFunc) overload (without the " + "unused func parameter)!") + bool SetGlobalInstance(const char * globalName, + T * global, + std::function itkNotUsed(func), + std::function deleteFunc) { this->SetGlobalInstance(globalName, global, std::move(deleteFunc)); // Just returns true for backward compatibility (legacy only). @@ -92,12 +93,13 @@ class ITKCommon_EXPORT SingletonIndex /** Set/Get the pointer to GlobalSingleton. * Note that SetGlobalSingleton is not concurrent thread safe. */ + /** @ITKStartGrouping */ static Self * GetInstance(); static void SetInstance(Self * instance); ~SingletonIndex(); - + /** @ITKEndGrouping */ private: // Internal struct to store the instance pointer and the delete function object of a global object. struct GlobalObject @@ -147,8 +149,9 @@ Singleton(const char * globalName, std::function deleteFunc) #ifndef ITK_FUTURE_LEGACY_REMOVE template -[[deprecated("Prefer calling the Singleton(globalName, deleteFunc) overload (without the unused func parameter)!")]] T * -Singleton(const char * globalName, std::function itkNotUsed(func), std::function deleteFunc) +ITK_FUTURE_DEPRECATED( + "Prefer calling the Singleton(globalName, deleteFunc) overload (without the unused func parameter)!") +T * Singleton(const char * globalName, std::function itkNotUsed(func), std::function deleteFunc) { return Singleton(globalName, std::move(deleteFunc)); } diff --git a/Modules/Core/Common/include/itkSingletonMacro.h b/Modules/Core/Common/include/itkSingletonMacro.h index 8796233e0ca..9286456f0e9 100644 --- a/Modules/Core/Common/include/itkSingletonMacro.h +++ b/Modules/Core/Common/include/itkSingletonMacro.h @@ -25,11 +25,10 @@ #ifndef itkSingletonMacro_h #define itkSingletonMacro_h -#define itkInitGlobalsMacro(VarName) \ - { \ - static auto * staticGlobals = Get##VarName##Pointer(); \ - (void)staticGlobals; \ - } \ +#define itkInitGlobalsMacro(VarName) \ + { \ + [[maybe_unused]] static auto * staticGlobals = Get##VarName##Pointer(); \ + } \ ITK_MACROEND_NOOP_STATEMENT #define itkGetGlobalDeclarationMacro(Type, VarName) static Type * Get##VarName##Pointer() diff --git a/Modules/Core/Common/include/itkSize.h b/Modules/Core/Common/include/itkSize.h index 2e6a60c8441..87d4192d505 100644 --- a/Modules/Core/Common/include/itkSize.h +++ b/Modules/Core/Common/include/itkSize.h @@ -29,8 +29,7 @@ namespace itk { -/** \struct Size - * \brief Represent a n-dimensional size (bounds) of a n-dimensional image. +/** \brief Represent a n-dimensional size (bounds) of a n-dimensional image. * * Size is a templated class to represent multi-dimensional array bounds, * i.e. (I,J,K,...). Size is templated over the dimension of the bounds. @@ -139,7 +138,8 @@ struct ITK_TEMPLATE_EXPORT Size final } /** Multiply two sizes (elementwise product). */ - const Self operator*(const Self & vec) const + const Self + operator*(const Self & vec) const { Self result; @@ -268,7 +268,7 @@ struct ITK_TEMPLATE_EXPORT Size final } void - swap(Size & other) + swap(Size & other) noexcept { std::swap(m_InternalArray, other.m_InternalArray); } @@ -351,9 +351,17 @@ struct ITK_TEMPLATE_EXPORT Size final return false; } - constexpr reference operator[](size_type pos) { return m_InternalArray[pos]; } + constexpr reference + operator[](size_type pos) + { + return m_InternalArray[pos]; + } - constexpr const_reference operator[](size_type pos) const { return m_InternalArray[pos]; } + constexpr const_reference + operator[](size_type pos) const + { + return m_InternalArray[pos]; + } reference at(size_type pos) @@ -369,25 +377,25 @@ struct ITK_TEMPLATE_EXPORT Size final return m_InternalArray[pos]; } - reference + constexpr reference front() { return *begin(); } - const_reference + constexpr const_reference front() const { return *begin(); } - reference + constexpr reference back() { return VDimension ? *(end() - 1) : *end(); } - const_reference + constexpr const_reference back() const { return VDimension ? *(end() - 1) : *end(); @@ -436,7 +444,7 @@ operator<<(std::ostream & os, const Size & obj) { os << obj[i] << ", "; } - if (VDimension >= 1) + if constexpr (VDimension >= 1) { os << obj[VDimension - 1]; } @@ -491,7 +499,7 @@ operator>=(const Size & one, const Size & two) // Specialized algorithms [6.2.2.2]. template inline void -swap(Size & one, Size & two) +swap(Size & one, Size & two) noexcept { std::swap(one.m_InternalArray, two.m_InternalArray); } diff --git a/Modules/Core/Common/include/itkSliceIterator.h b/Modules/Core/Common/include/itkSliceIterator.h index 13ab52ff284..f2cd257fffa 100644 --- a/Modules/Core/Common/include/itkSliceIterator.h +++ b/Modules/Core/Common/include/itkSliceIterator.h @@ -38,8 +38,7 @@ namespace itk * * References: * Modeled after a slice iterator proposed by Bjarne Stroustrup - * in C++ Programming Language, Third Edition. Bjarne Stroustrup. Addison - * Wesley, Reading, MA. 1997. + * in \cite stroustrup1997. * * \ingroup Iterators * \ingroup ITKCommon @@ -51,7 +50,6 @@ class SliceIterator /** Constructor. */ SliceIterator(TContainer * n, std::slice s) : m_ContainerPointer(n) - , m_Pos(0) , m_Slice(s) {} @@ -95,11 +93,19 @@ class SliceIterator /** Returns the element at position n of the slice. Sets the * iterator to point to position n. */ - TPixel & operator[](OffsetValueType n) { return this->Loc(m_Pos = n); } + TPixel & + operator[](OffsetValueType n) + { + return this->Loc(m_Pos = n); + } /** Dereferences the iterator, returning the value that it points * to. */ - TPixel & operator*() { return Loc(m_Pos); } + TPixel & + operator*() + { + return Loc(m_Pos); + } /** Returns the logical && of the boolean == of two slice iterator positions, * stride, and start locations. */ @@ -137,7 +143,7 @@ class SliceIterator TContainer * m_ContainerPointer; /** Current position within the slice. */ - OffsetValueType m_Pos; + OffsetValueType m_Pos{ 0 }; /** Slice structure information. */ std::slice m_Slice; diff --git a/Modules/Core/Common/include/itkSmapsFileParser.h b/Modules/Core/Common/include/itkSmapsFileParser.h index f6d9e140095..3a1a116c3de 100644 --- a/Modules/Core/Common/include/itkSmapsFileParser.h +++ b/Modules/Core/Common/include/itkSmapsFileParser.h @@ -277,8 +277,8 @@ class ITK_TEMPLATE_EXPORT MapFileParser GetMemoryUsage(const char * filter, const char * token = "Size"); protected: - std::string m_MapFilePath{}; //< location of the last loaded Map file - TMapData m_MapData{}; //< data of the loaded smap file + std::string m_MapFilePath{}; // location of the last loaded Map file + TMapData m_MapData{}; // data of the loaded smap file }; /** \class SmapsFileParser @@ -291,14 +291,14 @@ template class ITK_TEMPLATE_EXPORT SmapsFileParser : public MapFileParser { public: - virtual ~SmapsFileParser() = default; + ~SmapsFileParser() override = default; /** Load and parse the smaps file pointed by smapsFileLocation. * If smapsFileLocation is empty, load the file located at * "/proc/" + PID + "/smaps" * Throw an exception is the file can't be opened. */ - virtual void - ReadFile(const std::string & mapFileLocation = ""); + void + ReadFile(const std::string & mapFileLocation = "") override; }; /** \class VMMapFileParser @@ -310,12 +310,12 @@ template class ITK_TEMPLATE_EXPORT VMMapFileParser : public MapFileParser { public: - virtual ~VMMapFileParser() = default; + ~VMMapFileParser() override = default; /** If no vmmap file, create one using "vmmap pid" command * Throw an exception is the file can't be created/opened. */ - virtual void - ReadFile(const std::string & mapFileLocation = ""); + void + ReadFile(const std::string & mapFileLocation = "") override; }; } // end namespace itk diff --git a/Modules/Core/Common/include/itkSmapsFileParser.hxx b/Modules/Core/Common/include/itkSmapsFileParser.hxx index 7b61eb32050..cbf9d367046 100644 --- a/Modules/Core/Common/include/itkSmapsFileParser.hxx +++ b/Modules/Core/Common/include/itkSmapsFileParser.hxx @@ -104,7 +104,7 @@ SmapsFileParser::ReadFile(const std::string & mapFileLocation) #if defined(WIN32) || defined(_WIN32) itkGenericExceptionMacro("smaps files don't exist on Windows"); #else - int pid = getpid(); + int const pid = getpid(); filename << "/proc/" << pid << "/smaps"; #endif } diff --git a/Modules/Core/Common/include/itkSmartPointer.h b/Modules/Core/Common/include/itkSmartPointer.h index 6ed775ac68a..7971503e5d5 100644 --- a/Modules/Core/Common/include/itkSmartPointer.h +++ b/Modules/Core/Common/include/itkSmartPointer.h @@ -103,11 +103,23 @@ class SmartPointer ~SmartPointer() { this->UnRegister(); } /** Overload operator -> */ - ObjectType * operator->() const noexcept { return m_Pointer; } + ObjectType * + operator->() const noexcept + { + return m_Pointer; + } - ObjectType & operator*() const noexcept { return *m_Pointer; } + ObjectType & + operator*() const noexcept + { + return *m_Pointer; + } - explicit operator bool() const noexcept { return m_Pointer != nullptr; } + explicit + operator bool() const noexcept + { + return m_Pointer != nullptr; + } /** Return pointer to object. */ operator ObjectType *() const noexcept { return m_Pointer; } @@ -149,6 +161,7 @@ class SmartPointer * Additionally, it relies on constructors for additional conversion * for pointer types. */ + /** @ITKStartGrouping */ // cppcheck-suppress operatorEqVarError SmartPointer & operator=(SmartPointer r) noexcept @@ -160,12 +173,14 @@ class SmartPointer return *this; } - SmartPointer & operator=(std::nullptr_t) noexcept + SmartPointer & + operator=(std::nullptr_t) noexcept { this->UnRegister(); this->m_Pointer = nullptr; return *this; } + /** @ITKEndGrouping */ /** Function to print object pointed to */ ObjectType * @@ -227,6 +242,7 @@ class SmartPointer /** Comparison of pointers. Equality comparison. */ +/** @ITKStartGrouping */ template bool operator==(const SmartPointer & l, const SmartPointer & r) noexcept @@ -245,8 +261,9 @@ operator==(std::nullptr_t, const SmartPointer & r) noexcept { return (nullptr == r.GetPointer()); } - +/** @ITKEndGrouping */ /** Comparison of pointers. Not equal comparison. */ +/** @ITKStartGrouping */ template bool operator!=(const SmartPointer & l, const SmartPointer & r) noexcept @@ -265,7 +282,7 @@ operator!=(std::nullptr_t, const SmartPointer & r) noexcept { return (nullptr != r.GetPointer()); } - +/** @ITKEndGrouping */ /** Comparison of pointers. Less than comparison. */ template diff --git a/Modules/Core/Common/include/itkSmartPointerForwardReference.hxx b/Modules/Core/Common/include/itkSmartPointerForwardReference.hxx index 2e23865dcc9..e1cffae687a 100644 --- a/Modules/Core/Common/include/itkSmartPointerForwardReference.hxx +++ b/Modules/Core/Common/include/itkSmartPointerForwardReference.hxx @@ -54,7 +54,8 @@ SmartPointerForwardReference::~SmartPointerForwardReference() //---------------------------------------------------------------------------- template -T * SmartPointerForwardReference::operator->() const +T * +SmartPointerForwardReference::operator->() const { return m_Pointer; } diff --git a/Modules/Core/Common/include/itkSobelOperator.h b/Modules/Core/Common/include/itkSobelOperator.h index cae6bd10794..de359cb3472 100644 --- a/Modules/Core/Common/include/itkSobelOperator.h +++ b/Modules/Core/Common/include/itkSobelOperator.h @@ -35,8 +35,7 @@ namespace itk * 1) Set the direction by calling \code SetDirection \endcode * 2) call \code - itk::Size<2> radius; - radius.Fill(1); + constexpr auto radius = itk::Size<2>::Filled(1); sobelOperator.CreateToRadius(radius); \endcode * 3) You may optionally scale the coefficients of this operator using the @@ -62,9 +61,7 @@ namespace itk * The current implementation of the Sobel operator is for 2 and 3 dimensions only. * The ND version is planned for future releases. * - * The extension to 3D is from the publication - * "Irwin Sobel. An Isotropic 3x3x3 Volume Gradient Operator. - * Technical report, Hewlett-Packard Laboratories, April 1995." + * The extension to 3D was described in \cite sobel1995. * * The Sobel operator in 3D has the kernel * @@ -121,11 +118,7 @@ class ITK_TEMPLATE_EXPORT SobelOperator : public NeighborhoodOperator::ValueType>)); - // End concept checking -#endif /** Type alias support for coefficient vector type.*/ using typename Superclass::CoefficientVector; diff --git a/Modules/Core/Common/include/itkSobelOperator.hxx b/Modules/Core/Common/include/itkSobelOperator.hxx index a163ecc4a73..2e63ff5a6af 100644 --- a/Modules/Core/Common/include/itkSobelOperator.hxx +++ b/Modules/Core/Common/include/itkSobelOperator.hxx @@ -28,43 +28,46 @@ SobelOperator::Fill(const CoefficientVector & co { this->InitializeToZero(); - // Note that this code is only good for 2d and 3d operators. Places the - // coefficients in the exact center of the neighborhood - const unsigned int center = this->GetCenterNeighborhoodIndex(); - - if (VDimension == 3) + if constexpr (VDimension == 2 || VDimension == 3) { - unsigned int coeff_index = 0; - for (int z = -1; z <= 1; ++z) + // Note that this code is only good for 2d and 3d operators. Places the + // coefficients in the exact center of the neighborhood + const unsigned int center = this->GetCenterNeighborhoodIndex(); + + if constexpr (VDimension == 3) { - for (int y = -1; y <= 1; ++y) + unsigned int coeff_index = 0; + for (int z = -1; z <= 1; ++z) { - for (int x = -1; x <= 1; ++x) + for (int y = -1; y <= 1; ++y) { - const int pos = center + z * this->GetStride(2) + y * this->GetStride(1) + x * this->GetStride(0); + for (int x = -1; x <= 1; ++x) + { + const int pos = center + z * this->GetStride(2) + y * this->GetStride(1) + x * this->GetStride(0); - this->operator[](pos) = static_cast(coeff[coeff_index]); + this->operator[](pos) = static_cast(coeff[coeff_index]); - ++coeff_index; + ++coeff_index; + } } } } - } - else if (VDimension == 2) - { - unsigned int coeff_index = 0; - for (int y = -1; y <= 1; ++y) + else // So now VDimension == 2 { - for (int x = -1; x <= 1; ++x) + unsigned int coeff_index = 0; + for (int y = -1; y <= 1; ++y) { - const int pos = center + y * this->GetStride(1) + x * this->GetStride(0); - // Note, The following line copies the double precision - // coefficients of SobelOperator to the pixel type - // of the neighborhood operator which may not support - // negative numbers, or floating point numbers. - this->operator[](pos) = static_cast(coeff[coeff_index]); - - ++coeff_index; + for (int x = -1; x <= 1; ++x) + { + const int pos = center + y * this->GetStride(1) + x * this->GetStride(0); + // Note, The following line copies the double precision + // coefficients of SobelOperator to the pixel type + // of the neighborhood operator which may not support + // negative numbers, or floating point numbers. + this->operator[](pos) = static_cast(coeff[coeff_index]); + + ++coeff_index; + } } } } diff --git a/Modules/Core/Common/include/itkSparseFieldLayer.h b/Modules/Core/Common/include/itkSparseFieldLayer.h index f5fb3331a0b..2aca00b8414 100644 --- a/Modules/Core/Common/include/itkSparseFieldLayer.h +++ b/Modules/Core/Common/include/itkSparseFieldLayer.h @@ -37,9 +37,17 @@ template class ITK_TEMPLATE_EXPORT ConstSparseFieldLayerIterator { public: - const TNodeType & operator*() const { return *m_Pointer; } + const TNodeType & + operator*() const + { + return *m_Pointer; + } - const TNodeType * operator->() const { return m_Pointer; } + const TNodeType * + operator->() const + { + return m_Pointer; + } const TNodeType * GetPointer() const @@ -54,10 +62,8 @@ class ITK_TEMPLATE_EXPORT ConstSparseFieldLayerIterator { return true; } - else - { - return false; - } + + return false; } ITK_UNEQUAL_OPERATOR_MEMBER_FUNCTION(ConstSparseFieldLayerIterator); @@ -104,9 +110,17 @@ class ITK_TEMPLATE_EXPORT SparseFieldLayerIterator : public ConstSparseFieldLaye : Superclass(p) {} - TNodeType & operator*() { return *this->m_Pointer; } + TNodeType & + operator*() + { + return *this->m_Pointer; + } - TNodeType * operator->() { return this->m_Pointer; } + TNodeType * + operator->() + { + return this->m_Pointer; + } TNodeType * GetPointer() @@ -280,10 +294,8 @@ class ITK_TEMPLATE_EXPORT SparseFieldLayer : public Object { return true; } - else - { - return false; - } + + return false; } /** Returns the number of elements in the list. Size() executes in constant diff --git a/Modules/Core/Common/include/itkSparseFieldLayer.hxx b/Modules/Core/Common/include/itkSparseFieldLayer.hxx index d7c9bb7f291..2bc75322618 100644 --- a/Modules/Core/Common/include/itkSparseFieldLayer.hxx +++ b/Modules/Core/Common/include/itkSparseFieldLayer.hxx @@ -50,13 +50,13 @@ template auto SparseFieldLayer::SplitRegions(int num) const -> RegionListType { - std::vector regionlist; - unsigned int size, regionsize; - size = Size(); - regionsize = static_cast(std::ceil(static_cast(size) / static_cast(num))); + const unsigned int size = Size(); + const auto regionsize = static_cast(std::ceil(static_cast(size) / static_cast(num))); ConstIterator position = Begin(); - ConstIterator last = End(); + const ConstIterator last = End(); + std::vector regionlist; + regionlist.reserve(num); for (int i = 0; i < num; ++i) { unsigned int j = 0; diff --git a/Modules/Core/Common/include/itkSpatialOrientation.h b/Modules/Core/Common/include/itkSpatialOrientation.h index 50d345f491e..180389a47da 100644 --- a/Modules/Core/Common/include/itkSpatialOrientation.h +++ b/Modules/Core/Common/include/itkSpatialOrientation.h @@ -46,7 +46,7 @@ namespace itk class SpatialOrientationEnums { public: - /** \class CoordinateTerms + /** * * Coordinate orientation codes have a place-value organization such that * an ImageDimension-al sequence of subcodes says both which varies fastest @@ -70,7 +70,7 @@ class SpatialOrientationEnums // ITK_COORDINATE_Future=17 }; - /** \class CoordinateMajornessTerms + /** * * These code place values have to be far enough apart to * separate the CoordinateTerms above. @@ -92,7 +92,7 @@ class SpatialOrientationEnums ITK_COORDINATE_TertiaryMinor = 16 }; - /** \class CoordinateMajornessTerms + /** * * Adding time IN GENERAL would make these 8 x 6 = 48 triples into 16 * x 24 = 384 4-tuples. @@ -461,7 +461,7 @@ extern ITKCommon_EXPORT std::ostream & extern ITKCommon_EXPORT std::ostream & operator<<(std::ostream & out, const SpatialOrientationEnums::CoordinateMajornessTerms value); extern ITKCommon_EXPORT std::ostream & - operator<<(std::ostream & out, const SpatialOrientationEnums::ValidCoordinateOrientations value); +operator<<(std::ostream & out, const SpatialOrientationEnums::ValidCoordinateOrientations value); #ifndef ITK_LEGACY_REMOVE namespace SpatialOrientation diff --git a/Modules/Core/Common/include/itkSpatialOrientationAdapter.h b/Modules/Core/Common/include/itkSpatialOrientationAdapter.h index 2800ed37422..1b2bbbe07a7 100644 --- a/Modules/Core/Common/include/itkSpatialOrientationAdapter.h +++ b/Modules/Core/Common/include/itkSpatialOrientationAdapter.h @@ -43,15 +43,15 @@ Max3(double x, double y, double z) { constexpr double obliquityThresholdCosineValue = 0.001; - double absX = itk::Math::abs(x); - double absY = itk::Math::abs(y); - double absZ = itk::Math::abs(z); + const double absX = itk::Math::abs(x); + const double absY = itk::Math::abs(y); + const double absZ = itk::Math::abs(z); if ((absX > obliquityThresholdCosineValue) && (absX > absY) && (absX > absZ)) { return 0; } - else if ((absY > obliquityThresholdCosineValue) && (absY > absX) && (absY > absZ)) + if ((absY > obliquityThresholdCosineValue) && (absY > absX) && (absY > absZ)) { return 1; } diff --git a/Modules/Core/Common/include/itkSpecialCoordinatesImage.h b/Modules/Core/Common/include/itkSpecialCoordinatesImage.h index 90fce4143b0..257ce6fdf52 100644 --- a/Modules/Core/Common/include/itkSpecialCoordinatesImage.h +++ b/Modules/Core/Common/include/itkSpecialCoordinatesImage.h @@ -193,7 +193,7 @@ class ITK_TEMPLATE_EXPORT SpecialCoordinatesImage : public ImageBaseFastComputeOffset(index); + const OffsetValueType offset = this->FastComputeOffset(index); (*m_Buffer)[offset] = value; } @@ -204,7 +204,7 @@ class ITK_TEMPLATE_EXPORT SpecialCoordinatesImage : public ImageBaseFastComputeOffset(index); + const OffsetValueType offset = this->FastComputeOffset(index); return ((*m_Buffer)[offset]); } @@ -215,7 +215,7 @@ class ITK_TEMPLATE_EXPORT SpecialCoordinatesImage : public ImageBaseFastComputeOffset(index); + const OffsetValueType offset = this->FastComputeOffset(index); return ((*m_Buffer)[offset]); } @@ -223,16 +223,25 @@ class ITK_TEMPLATE_EXPORT SpecialCoordinatesImage : public ImageBaseGetPixel(index); } + TPixel & + operator[](const IndexType & index) + { + return this->GetPixel(index); + } /** \brief Access a pixel. This version can only be an rvalue. * * For efficiency, this function does not check that the * image has actually been allocated yet. */ - const TPixel & operator[](const IndexType & index) const { return this->GetPixel(index); } + const TPixel & + operator[](const IndexType & index) const + { + return this->GetPixel(index); + } /** Return a pointer to the beginning of the buffer. This is used by * the image iterator class. */ + /** @ITKStartGrouping */ TPixel * GetBufferPointer() { @@ -243,7 +252,7 @@ class ITK_TEMPLATE_EXPORT SpecialCoordinatesImage : public ImageBaseGetBufferPointer() : nullptr; } - + /** @ITKEndGrouping */ /** Return a pointer to the container. */ PixelContainer * GetPixelContainer() @@ -281,6 +290,7 @@ class ITK_TEMPLATE_EXPORT SpecialCoordinatesImage : public ImageBase + template virtual bool TransformPhysicalPointToContinuousIndex( - const Point& point, - ContinuousIndex& index ) const = 0; + const Point& point, + ContinuousIndex& index ) const = 0; - template + template virtual bool TransformPhysicalPointToIndex( - const Point&, + const Point&, IndexType & index ) const = 0; - template + template virtual void TransformContinuousIndexToPhysicalPoint( - const ContinuousIndex& index, - Point& point ) const = 0; + const ContinuousIndex& index, + Point& point ) const = 0; - template + template virtual void TransformIndexToPhysicalPoint( const IndexType & index, - Point& point ) const = 0; + Point& point ) const = 0; */ protected: diff --git a/Modules/Core/Common/include/itkSphereSpatialFunction.h b/Modules/Core/Common/include/itkSphereSpatialFunction.h index d9dad1725d3..06313635e8b 100644 --- a/Modules/Core/Common/include/itkSphereSpatialFunction.h +++ b/Modules/Core/Common/include/itkSphereSpatialFunction.h @@ -60,13 +60,15 @@ class ITK_TEMPLATE_EXPORT SphereSpatialFunction : public InteriorExteriorSpatial Evaluate(const InputType & position) const override; /** Get and set the center of the sphere. */ + /** @ITKStartGrouping */ itkGetConstMacro(Center, InputType); itkSetMacro(Center, InputType); - + /** @ITKEndGrouping */ /** Get and set the radius of the sphere */ + /** @ITKStartGrouping */ itkGetConstMacro(Radius, double); itkSetMacro(Radius, double); - + /** @ITKEndGrouping */ protected: SphereSpatialFunction() = default; ~SphereSpatialFunction() override = default; diff --git a/Modules/Core/Common/include/itkSphereSpatialFunction.hxx b/Modules/Core/Common/include/itkSphereSpatialFunction.hxx index 1d447f2463d..3fb5b026e42 100644 --- a/Modules/Core/Common/include/itkSphereSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkSphereSpatialFunction.hxx @@ -38,10 +38,8 @@ SphereSpatialFunction::Evaluate(const InputType & posit { return 1; } - else - { - return 0; // outside the sphere - } + + return 0; // outside the sphere } template @@ -50,9 +48,8 @@ SphereSpatialFunction::PrintSelf(std::ostream & os, Ind { Superclass::PrintSelf(os, indent); - unsigned int i; os << indent << "Center: ["; - for (i = 0; i < VImageDimension - 1; ++i) + for (unsigned int i = 0; i < VImageDimension - 1; ++i) { os << m_Center[i] << ", "; } diff --git a/Modules/Core/Common/include/itkStaticAssert.h b/Modules/Core/Common/include/itkStaticAssert.h index 83fbbda022c..f93c2b42db9 100644 --- a/Modules/Core/Common/include/itkStaticAssert.h +++ b/Modules/Core/Common/include/itkStaticAssert.h @@ -19,19 +19,8 @@ #ifndef itkStaticAssert_h #define itkStaticAssert_h -#include "itkMacro.h" - -#if !defined(ITK_LEGACY_REMOVE) -/** Static assertion. - * This macro will use C++11 \c static_assert() keyword. - * \param expr compile-time expression to check - * \param str string literal that will appear as compiler error if \c expr is \c false. - * \ingroup ITKCommon - */ -# define itkStaticAssert(expr, str) static_assert(expr, str) -#else -# define itkStaticAssert(expr, str) Use C++ 11 static_assert directly -#endif +// This is no longer needed as C++11 provides this support directly +#define itkStaticAssert(expr, str) static_assert(false, "Use C++ 11 static_assert directly") // TODO: remove this file entirely in the future (e.g. with ITKv6) diff --git a/Modules/Core/Common/include/itkStdStreamLogOutput.h b/Modules/Core/Common/include/itkStdStreamLogOutput.h index 072798ad34f..69b41dd5850 100644 --- a/Modules/Core/Common/include/itkStdStreamLogOutput.h +++ b/Modules/Core/Common/include/itkStdStreamLogOutput.h @@ -71,11 +71,11 @@ class ITKCommon_EXPORT StdStreamLogOutput : public LogOutput /** Write to a buffer */ void - Write(std::string const & content) override; + Write(const std::string & content) override; /** Write to a buffer */ void - Write(std::string const & content, double timestamp) override; + Write(const std::string & content, double timestamp) override; protected: /** Constructor */ diff --git a/Modules/Core/Common/include/itkStoppingCriterionBase.h b/Modules/Core/Common/include/itkStoppingCriterionBase.h index e460e2fa5f7..c74901608bd 100644 --- a/Modules/Core/Common/include/itkStoppingCriterionBase.h +++ b/Modules/Core/Common/include/itkStoppingCriterionBase.h @@ -50,11 +50,12 @@ class ITKCommon_EXPORT StoppingCriterionBase : public Object /** \return \c true if the stopping criterion is reached (and the algorithm must stop). \return \c false else. */ + /** @ITKStartGrouping */ virtual bool IsSatisfied() const = 0; virtual std::string GetDescription() const = 0; - + /** @ITKEndGrouping */ protected: /** \brief Constructor */ StoppingCriterionBase(); diff --git a/Modules/Core/Common/include/itkStreamingImageFilter.h b/Modules/Core/Common/include/itkStreamingImageFilter.h index 2b291a1c3ad..b8da3792a17 100644 --- a/Modules/Core/Common/include/itkStreamingImageFilter.h +++ b/Modules/Core/Common/include/itkStreamingImageFilter.h @@ -87,9 +87,10 @@ class ITK_TEMPLATE_EXPORT StreamingImageFilter : public ImageToImageFilter)); itkConceptMacro(InputConvertibleToOutputCheck, (Concept::Convertible)); - // End concept checking -#endif protected: StreamingImageFilter(); diff --git a/Modules/Core/Common/include/itkStreamingImageFilter.hxx b/Modules/Core/Common/include/itkStreamingImageFilter.hxx index 4db5e1c8131..c32b0e78182 100644 --- a/Modules/Core/Common/include/itkStreamingImageFilter.hxx +++ b/Modules/Core/Common/include/itkStreamingImageFilter.hxx @@ -151,10 +151,9 @@ StreamingImageFilter::UpdateOutputData(DataObject * i * minimum of what the user specified via SetNumberOfStreamDivisions() * and what the Splitter thinks is a reasonable value. */ - unsigned int numDivisions, numDivisionsFromSplitter; - - numDivisions = m_NumberOfStreamDivisions; - numDivisionsFromSplitter = m_RegionSplitter->GetNumberOfSplits(outputRegion, m_NumberOfStreamDivisions); + unsigned int numDivisions = m_NumberOfStreamDivisions; + const unsigned int numDivisionsFromSplitter = + m_RegionSplitter->GetNumberOfSplits(outputRegion, m_NumberOfStreamDivisions); if (numDivisionsFromSplitter < numDivisions) { numDivisions = numDivisionsFromSplitter; diff --git a/Modules/Core/Common/include/itkSymmetricEigenAnalysis.h b/Modules/Core/Common/include/itkSymmetricEigenAnalysis.h index ff6d65f46e8..ad6acf64d15 100644 --- a/Modules/Core/Common/include/itkSymmetricEigenAnalysis.h +++ b/Modules/Core/Common/include/itkSymmetricEigenAnalysis.h @@ -38,20 +38,20 @@ const TValueType * GetPointerToMatrixData(const vnl_matrix_fixed & inputMatrix) { return inputMatrix.data_block(); -}; +} template const TValueType * GetPointerToMatrixData(const vnl_matrix & inputMatrix) { return inputMatrix.data_block(); -}; +} template const TValueType * GetPointerToMatrixData(const itk::Matrix & inputMatrix) { return inputMatrix.GetVnlMatrix().data_block(); -}; +} /** Sort input to be ordered by magnitude, and returns container with the * permutations required for the sorting. @@ -110,6 +110,7 @@ permuteColumnsWithSortIndices(QMatrix & eigenVectors, const std::vector & i // Apply it eigenVectors = eigenVectors * perm; } + } // end namespace detail /** \class SymmetricEigenAnalysisEnums @@ -119,7 +120,7 @@ permuteColumnsWithSortIndices(QMatrix & eigenVectors, const std::vector & i class SymmetricEigenAnalysisEnums { public: - /** \class EigenValueOrder + /** * \ingroup ITKCommon * Order of eigen values * OrderByValue: lambda_1 < lambda_2 < .... @@ -191,10 +192,9 @@ static constexpr EigenValueOrderEnum DoNotOrder = EigenValueOrderEnum::DoNotOrde * netlib/tred1.c * netlib/tred2.c * - * Reference: - * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and - * wilkinson. - * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). + * For algorithmic descriptions see \cite bowdler1968 and + * \cite bowdler1971. + * * \ingroup ITKCommon */ @@ -280,6 +280,7 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis /** Set/Get methods to order the eigen values in ascending order. * This is the default. ie lambda_1 < lambda_2 < .... */ + /** @ITKStartGrouping */ void SetOrderEigenValues(const bool b) { @@ -298,10 +299,12 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis { return (m_OrderEigenValues == EigenValueOrderEnum::OrderByValue); } + /** @ITKEndGrouping */ /** Set/Get methods to order the eigen value magnitudes in ascending order. * In other words, |lambda_1| < |lambda_2| < ..... */ + /** @ITKStartGrouping */ void SetOrderEigenMagnitudes(const bool b) { @@ -320,6 +323,7 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis { return (m_OrderEigenValues == EigenValueOrderEnum::OrderByMagnitude); } + /** @ITKEndGrouping */ /** Set the dimension of the input matrix A. A is a square matrix of * size m_Dimension. */ @@ -342,6 +346,7 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis } /** Set/Get to use Eigen library instead of vnl/netlib. */ + /** @ITKStartGrouping */ void SetUseEigenLibrary(const bool input) { @@ -362,7 +367,7 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis { return m_UseEigenLibrary; } - + /** @ITKEndGrouping */ private: bool m_UseEigenLibrary{ false }; unsigned int m_Dimension{ 0 }; @@ -385,9 +390,8 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis * Function adapted from netlib/tred1.c. * [Changed: remove static vars, enforce const correctness. * Use vnl routines as necessary]. - * Reference: - * num. math. 11, 181-195(1968) by martin, reinsch, and wilkinson. - * handbook for auto. comp., vol.ii-linear algebra, 212-226(1971). */ + * For algorithmic descriptions see \cite martin1968 and + * \cite martin1971. */ void ReduceToTridiagonalMatrix(double * a, double * d, double * e, double * e2) const; @@ -409,9 +413,8 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis * Function adapted from netlib/tred2.c. * [Changed: remove static vars, enforce const correctness. * Use vnl routines as necessary]. - * Reference: - * num. math. 11, 181-195(1968) by martin, reinsch, and wilkinson. - * handbook for auto. comp., vol.ii-linear algebra, 212-226(1971). */ + * For algorithmic descriptions see \cite martin1968 and + * \cite martin1971. */ void ReduceToTridiagonalMatrixAndGetTransformation(const double * a, double * d, double * e, double * z) const; @@ -433,9 +436,7 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis * * Reference * This subroutine is a translation of the algol procedure tql1, - * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and - * wilkinson. - * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). + * \cite bowdler1968 and \cite bowdler1971. * * Questions and comments should be directed to Burton s. Garbow, * Mathematics and Computer Science Div., Argonne National Laboratory. @@ -472,9 +473,7 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis * * Reference * This subroutine is a translation of the algol procedure tql1, - * num. math. 11, 293-306(1968) by bowdler, martin, reinsch, and - * wilkinson. - * handbook for auto. comp., vol.ii-linear algebra, 227-240(1971). + * \cite bowdler1968 and \cite bowdler1971. * * Questions and comments should be directed to Burton s. Garbow, * Mathematics and Computer Science Div., Argonne National Laboratory. @@ -556,8 +555,8 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis } } using EigenSolverType = Eigen::SelfAdjointEigenSolver; - EigenSolverType solver(inputMatrix); // Computes EigenValues and EigenVectors - const auto & eigenValues = solver.eigenvalues(); + const EigenSolverType solver(inputMatrix); // Computes EigenValues and EigenVectors + const auto & eigenValues = solver.eigenvalues(); /* Column k of the returned matrix is an eigenvector corresponding to * eigenvalue number $ k $ as returned by eigenvalues(). * The eigenvectors are normalized to have (Euclidean) norm equal to one. */ @@ -683,8 +682,8 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysis } } using EigenSolverType = Eigen::SelfAdjointEigenSolver; - EigenSolverType solver(inputMatrix, Eigen::EigenvaluesOnly); - auto eigenValues = solver.eigenvalues(); + const EigenSolverType solver(inputMatrix, Eigen::EigenvaluesOnly); + auto eigenValues = solver.eigenvalues(); if (m_OrderEigenValues == EigenValueOrderEnum::OrderByMagnitude) { detail::sortEigenValuesByMagnitude(eigenValues, m_Dimension); @@ -971,8 +970,8 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysisFixedDimension } } using EigenSolverType = Eigen::SelfAdjointEigenSolver; - EigenSolverType solver(inputMatrix); // Computes EigenValues and EigenVectors - const auto & eigenValues = solver.eigenvalues(); + const EigenSolverType solver(inputMatrix); // Computes EigenValues and EigenVectors + const auto & eigenValues = solver.eigenvalues(); /* Column k of the returned matrix is an eigenvector corresponding to * eigenvalue number $ k $ as returned by eigenvalues(). * The eigenvectors are normalized to have (Euclidean) norm equal to one. */ @@ -1030,8 +1029,8 @@ class ITK_TEMPLATE_EXPORT SymmetricEigenAnalysisFixedDimension } } using EigenSolverType = Eigen::SelfAdjointEigenSolver; - EigenSolverType solver(inputMatrix, Eigen::EigenvaluesOnly); - auto eigenValues = solver.eigenvalues(); + const EigenSolverType solver(inputMatrix, Eigen::EigenvaluesOnly); + auto eigenValues = solver.eigenvalues(); if (m_OrderEigenValues == EigenValueOrderEnum::OrderByMagnitude) { detail::sortEigenValuesByMagnitude(eigenValues, VDimension); diff --git a/Modules/Core/Common/include/itkSymmetricEigenAnalysis.hxx b/Modules/Core/Common/include/itkSymmetricEigenAnalysis.hxx index 5abb8906f48..fc8a66aee2d 100644 --- a/Modules/Core/Common/include/itkSymmetricEigenAnalysis.hxx +++ b/Modules/Core/Common/include/itkSymmetricEigenAnalysis.hxx @@ -31,10 +31,8 @@ SymmetricEigenAnalysis::ComputeEigenValues(const { return ComputeEigenValuesWithEigenLibrary(A, D); } - else - { - return ComputeEigenValuesLegacy(A, D); - } + + return ComputeEigenValuesLegacy(A, D); } template @@ -47,10 +45,8 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec { return ComputeEigenValuesAndVectorsWithEigenLibrary(A, EigenValues, EigenVectors); } - else - { - return ComputeEigenValuesAndVectorsLegacy(A, EigenValues, EigenVectors); - } + + return ComputeEigenValuesAndVectorsLegacy(A, EigenValues, EigenVectors); } template @@ -139,34 +135,28 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri double * e, double * e2) const { - double d__1; - // Local variables - double f, g, h; - int i, j, k, l; - double scale; - - for (i = 0; i < static_cast(m_Order); ++i) + for (int i = 0; i < static_cast(m_Order); ++i) { d[i] = a[m_Order - 1 + i * m_Dimension]; a[m_Order - 1 + i * m_Dimension] = a[i + i * m_Dimension]; } - for (i = m_Order - 1; i >= 0; --i) + for (int i = m_Order - 1; i >= 0; --i) { - l = i - 1; - h = 0.; - scale = 0.; + const int l = i - 1; + double h = 0.; + double scale = 0.; // Scale row (algol tol then not needed) - for (k = 0; k <= l; ++k) + for (int k = 0; k <= l; ++k) { scale += itk::Math::abs(d[k]); } if (scale == 0.) { - for (j = 0; j <= l; ++j) + for (int j = 0; j <= l; ++j) { d[j] = a[l + j * m_Dimension]; a[l + j * m_Dimension] = a[i + j * m_Dimension]; @@ -176,33 +166,33 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri e2[i] = 0.; continue; } - for (k = 0; k <= l; ++k) + for (int k = 0; k <= l; ++k) { d[k] /= scale; h += d[k] * d[k]; } e2[i] = scale * scale * h; - f = d[l]; - d__1 = std::sqrt(h); - g = (-1.0) * itk::Math::sgn0(f) * itk::Math::abs(d__1); + double f = d[l]; + const double d__1 = std::sqrt(h); + double g = (-1.0) * itk::Math::sgn0(f) * itk::Math::abs(d__1); e[i] = scale * g; h -= f * g; d[l] = f - g; if (l != 0) { // Form a*u - for (j = 0; j <= l; ++j) + for (int j = 0; j <= l; ++j) { e[j] = 0.; } - for (j = 0; j <= l; ++j) + for (int j = 0; j <= l; ++j) { f = d[j]; g = e[j] + a[j + j * m_Dimension] * f; - for (k = j + 1; k <= l; ++k) + for (int k = j + 1; k <= l; ++k) { g += a[k + j * m_Dimension] * d[k]; e[k] += a[k + j * m_Dimension] * f; @@ -213,7 +203,7 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri // Form p f = 0.; - for (j = 0; j <= l; ++j) + for (int j = 0; j <= l; ++j) { e[j] /= h; f += e[j] * d[j]; @@ -221,25 +211,25 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri h = f / (h + h); // Form q - for (j = 0; j <= l; ++j) + for (int j = 0; j <= l; ++j) { e[j] -= h * d[j]; } // Form reduced a - for (j = 0; j <= l; ++j) + for (int j = 0; j <= l; ++j) { f = d[j]; g = e[j]; - for (k = j; k <= l; ++k) + for (int k = j; k <= l; ++k) { a[k + j * m_Dimension] = a[k + j * m_Dimension] - f * e[k] - g * d[k]; } } } - for (j = 0; j <= l; ++j) + for (int j = 0; j <= l; ++j) { f = d[j]; d[j] = a[l + j * m_Dimension]; @@ -256,30 +246,24 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri double * e, double * z) const { - double d__1; - // Local variables - double f, g, h; - unsigned int i, j, k, l; - double scale, hh; - - for (i = 0; i < m_Order; ++i) + for (unsigned int i = 0; i < m_Order; ++i) { - for (j = i; j < m_Order; ++j) + for (unsigned int j = i; j < m_Order; ++j) { z[j + i * m_Dimension] = a[j + i * m_Dimension]; } d[i] = a[m_Order - 1 + i * m_Dimension]; } - for (i = m_Order - 1; i > 0; --i) + for (unsigned int i = m_Order - 1; i > 0; --i) { - l = i - 1; - h = 0.0; - scale = 0.0; + const unsigned int l = i - 1; + double h = 0.0; + double scale = 0.0; // Scale row (algol tol then not needed) - for (k = 0; k <= l; ++k) + for (unsigned int k = 0; k <= l; ++k) { scale += itk::Math::abs(d[k]); } @@ -288,7 +272,7 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri { e[i] = d[l]; - for (j = 0; j <= l; ++j) + for (unsigned int j = 0; j <= l; ++j) { d[j] = z[l + j * m_Dimension]; z[i + j * m_Dimension] = 0.0; @@ -297,32 +281,32 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri } else { - for (k = 0; k <= l; ++k) + for (unsigned int k = 0; k <= l; ++k) { d[k] /= scale; h += d[k] * d[k]; } - f = d[l]; - d__1 = std::sqrt(h); - g = (-1.0) * itk::Math::sgn0(f) * itk::Math::abs(d__1); + double f = d[l]; + const double d__1 = std::sqrt(h); + double g = (-1.0) * itk::Math::sgn0(f) * itk::Math::abs(d__1); e[i] = scale * g; h -= f * g; d[l] = f - g; // Form a*u - for (j = 0; j <= l; ++j) + for (unsigned int j = 0; j <= l; ++j) { e[j] = 0.0; } - for (j = 0; j <= l; ++j) + for (unsigned int j = 0; j <= l; ++j) { f = d[j]; z[j + i * m_Dimension] = f; g = e[j] + z[j + j * m_Dimension] * f; - for (k = j + 1; k <= l; ++k) + for (unsigned int k = j + 1; k <= l; ++k) { g += z[k + j * m_Dimension] * d[k]; e[k] += z[k + j * m_Dimension] * f; @@ -334,27 +318,27 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri // Form p f = 0.0; - for (j = 0; j <= l; ++j) + for (unsigned int j = 0; j <= l; ++j) { e[j] /= h; f += e[j] * d[j]; } - hh = f / (h + h); + const double hh = f / (h + h); // Form q - for (j = 0; j <= l; ++j) + for (unsigned int j = 0; j <= l; ++j) { e[j] -= hh * d[j]; } // Form reduced a - for (j = 0; j <= l; ++j) + for (unsigned int j = 0; j <= l; ++j) { f = d[j]; g = e[j]; - for (k = j; k <= l; ++k) + for (unsigned int k = j; k <= l; ++k) { z[k + j * m_Dimension] = z[k + j * m_Dimension] - f * e[k] - g * d[k]; } @@ -368,42 +352,42 @@ SymmetricEigenAnalysis::ReduceToTridiagonalMatri } // Accumulation of transformation matrices - for (i = 1; i < m_Order; ++i) + for (unsigned int i = 1; i < m_Order; ++i) { - l = i - 1; + const unsigned int l = i - 1; z[m_Order - 1 + l * m_Dimension] = z[l + l * m_Dimension]; z[l + l * m_Dimension] = 1.0; - h = d[i]; + const double h = d[i]; if (h != 0.0) { - for (k = 0; k <= l; ++k) + for (unsigned int k = 0; k <= l; ++k) { d[k] = z[k + i * m_Dimension] / h; } - for (j = 0; j <= l; ++j) + for (unsigned int j = 0; j <= l; ++j) { - g = 0.0; + double g = 0.0; - for (k = 0; k <= l; ++k) + for (unsigned int k = 0; k <= l; ++k) { g += z[k + i * m_Dimension] * z[k + j * m_Dimension]; } - for (k = 0; k <= l; ++k) + for (unsigned int k = 0; k <= l; ++k) { z[k + j * m_Dimension] -= g * d[k]; } } } - for (k = 0; k <= l; ++k) + for (unsigned int k = 0; k <= l; ++k) { z[k + i * m_Dimension] = 0.0; } } - for (i = 0; i < m_Order; ++i) + for (unsigned int i = 0; i < m_Order; ++i) { d[i] = z[m_Order - 1 + i * m_Dimension]; z[m_Order - 1 + i * m_Dimension] = 0.0; @@ -420,33 +404,26 @@ SymmetricEigenAnalysis::ComputeEigenValuesUsingQ constexpr double c_b10 = 1.0; // Local variables - double c, f, g, h; - unsigned int i, j, l, m; - double p, r, s, c2, c3 = 0.0; - double s2 = 0.0; - double dl1, el1; - double tst1, tst2; - unsigned int ierr = 0; if (m_Order == 1) { return 1; } - - for (i = 1; i < m_Order; ++i) + unsigned int m; + for (unsigned int i = 1; i < m_Order; ++i) { e[i - 1] = e[i]; } - f = 0.; - tst1 = 0.; + double f = 0.; + double tst1 = 0.; e[m_Order - 1] = 0.; - for (l = 0; l < m_Order; ++l) + for (unsigned int l = 0; l < m_Order; ++l) { - j = 0; - h = itk::Math::abs(d[l]) + itk::Math::abs(e[l]); + unsigned int j = 0; + double h = itk::Math::abs(d[l]) + itk::Math::abs(e[l]); if (tst1 < h) { tst1 = h; @@ -454,7 +431,7 @@ SymmetricEigenAnalysis::ComputeEigenValuesUsingQ // Look for small sub-diagonal element for (m = l; m < m_Order - 1; ++m) { - tst2 = tst1 + itk::Math::abs(e[m]); + const double tst2 = tst1 + itk::Math::abs(e[m]); if (tst2 == tst1) { break; @@ -464,6 +441,7 @@ SymmetricEigenAnalysis::ComputeEigenValuesUsingQ if (m != l) { + double tst2; do { if (j == 30) @@ -474,15 +452,15 @@ SymmetricEigenAnalysis::ComputeEigenValuesUsingQ } ++j; // Form shift - g = d[l]; - p = (d[l + 1] - g) / (e[l] * 2.); - r = itk::Math::hypot(p, c_b10); + double g = d[l]; + double p = (d[l + 1] - g) / (e[l] * 2.); + double r = itk::Math::hypot(p, c_b10); d[l] = e[l] / (p + itk::Math::sgn0(p) * itk::Math::abs(r)); d[l + 1] = e[l] * (p + itk::Math::sgn0(p) * itk::Math::abs(r)); - dl1 = d[l + 1]; + const double dl1 = d[l + 1]; h = g - d[l]; - for (i = l + 2; i < m_Order; ++i) + for (unsigned int i = l + 2; i < m_Order; ++i) { d[i] -= h; } @@ -490,11 +468,13 @@ SymmetricEigenAnalysis::ComputeEigenValuesUsingQ f += h; // ql transformation p = d[m]; - c = 1.; - c2 = c; - el1 = e[l + 1]; - s = 0.; - for (i = m - 1; i >= l; --i) + double c = 1.; + double c2 = c; + const double el1 = e[l + 1]; + double s = 0.; + double s2 = 0; + double c3 = c2; + for (unsigned int i = m - 1; i >= l; --i) { c3 = c2; c2 = c; @@ -520,12 +500,13 @@ SymmetricEigenAnalysis::ComputeEigenValuesUsingQ } while (tst2 > tst1); } - p = d[l] + f; + const double p = d[l] + f; if (m_OrderEigenValues == EigenValueOrderEnum::OrderByValue) { // Order by value - for (i = l; i > 0; --i) + unsigned int i = l; + for (; i > 0; --i) { if (p >= d[i - 1]) { @@ -538,7 +519,8 @@ SymmetricEigenAnalysis::ComputeEigenValuesUsingQ else if (m_OrderEigenValues == EigenValueOrderEnum::OrderByMagnitude) { // Order by magnitude. Make eigenvalues positive - for (i = l; i > 0; --i) + unsigned int i = l; + for (; i > 0; --i) { if (itk::Math::abs(p) >= itk::Math::abs(d[i - 1])) { @@ -564,41 +546,36 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec double * z) const { constexpr double c_b10 = 1.0; - - // Local variables - double c, f, g, h; - unsigned int i, j, k, l, m; - double p, r, s, c2, c3 = 0.0; - double s2 = 0.0; - double dl1, el1; - double tst1, tst2; - - unsigned int ierr = 0; - if (m_Order == 1) { return 1; } - for (i = 1; i < m_Order; ++i) + unsigned int ierr = 0; + double c3 = 0.0; + double s2 = 0.0; + for (unsigned int i = 1; i < m_Order; ++i) { e[i - 1] = e[i]; } - f = 0.0; - tst1 = 0.; + + double f = 0.0; + double tst1 = 0.; e[m_Order - 1] = 0.; - for (l = 0; l < m_Order; ++l) + for (unsigned int l = 0; l < m_Order; ++l) { - j = 0; - h = itk::Math::abs(d[l]) + itk::Math::abs(e[l]); + unsigned int j = 0; + double h = itk::Math::abs(d[l]) + itk::Math::abs(e[l]); if (tst1 < h) { tst1 = h; } // Look for small sub-diagonal element + unsigned int m; + double tst2; for (m = l; m < m_Order - 1; ++m) { tst2 = tst1 + itk::Math::abs(e[m]); @@ -622,15 +599,15 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec } ++j; // Form shift - g = d[l]; - p = (d[l + 1] - g) / (e[l] * 2.); - r = itk::Math::hypot(p, c_b10); + double g = d[l]; + double p = (d[l + 1] - g) / (e[l] * 2.); + double r = itk::Math::hypot(p, c_b10); d[l] = e[l] / (p + itk::Math::sgn0(p) * itk::Math::abs(r)); d[l + 1] = e[l] * (p + itk::Math::sgn0(p) * itk::Math::abs(r)); - dl1 = d[l + 1]; + const double dl1 = d[l + 1]; h = g - d[l]; - for (i = l + 2; i < m_Order; ++i) + for (unsigned int i = l + 2; i < m_Order; ++i) { d[i] -= h; } @@ -638,12 +615,12 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec f += h; // ql transformation p = d[m]; - c = 1.0; - c2 = c; - el1 = e[l + 1]; - s = 0.; + double c = 1.0; + double c2 = c; + const double el1 = e[l + 1]; + double s = 0.; - for (i = m - 1; i >= l; --i) + for (unsigned int i = m - 1; i >= l; --i) { c3 = c2; c2 = c; @@ -658,7 +635,7 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec d[i + 1] = h + s * (c * g + s * d[i]); // Form vector - for (k = 0; k < m_Order; ++k) + for (unsigned int k = 0; k < m_Order; ++k) { h = z[k + (i + 1) * m_Dimension]; z[k + (i + 1) * m_Dimension] = s * z[k + i * m_Dimension] + c * h; @@ -684,12 +661,12 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec if (m_OrderEigenValues == EigenValueOrderEnum::OrderByValue) { // Order by value - for (i = 0; i < m_Order - 1; ++i) + for (unsigned int i = 0; i < m_Order - 1; ++i) { - k = i; - p = d[i]; + unsigned int k = i; + double p = d[i]; - for (j = i + 1; j < m_Order; ++j) + for (unsigned int j = i + 1; j < m_Order; ++j) { if (d[j] >= p) { @@ -706,7 +683,7 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec d[k] = d[i]; d[i] = p; - for (j = 0; j < m_Order; ++j) + for (unsigned int j = 0; j < m_Order; ++j) { p = z[j + i * m_Dimension]; z[j + i * m_Dimension] = z[j + k * m_Dimension]; @@ -717,12 +694,12 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec else if (m_OrderEigenValues == EigenValueOrderEnum::OrderByMagnitude) { // Order by magnitude - for (i = 0; i < m_Order - 1; ++i) + for (unsigned int i = 0; i < m_Order - 1; ++i) { - k = i; - p = d[i]; + unsigned int k = i; + double p = d[i]; - for (j = i + 1; j < m_Order; ++j) + for (unsigned int j = i + 1; j < m_Order; ++j) { if (itk::Math::abs(d[j]) >= itk::Math::abs(p)) { @@ -740,7 +717,7 @@ SymmetricEigenAnalysis::ComputeEigenValuesAndVec d[k] = d[i]; d[i] = p; - for (j = 0; j < m_Order; ++j) + for (unsigned int j = 0; j < m_Order; ++j) { p = z[j + i * m_Dimension]; z[j + i * m_Dimension] = z[j + k * m_Dimension]; diff --git a/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h b/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h index dd3770fc61a..95730252f55 100644 --- a/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h +++ b/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.h @@ -66,9 +66,10 @@ class ITK_TEMPLATE_EXPORT SymmetricEllipsoidInteriorExteriorSpatialFunction Evaluate(const InputType & position) const override; /** Get and set the center of the ellipsoid. */ + /** @ITKStartGrouping */ itkGetConstMacro(Center, InputType); itkSetMacro(Center, InputType); - + /** @ITKEndGrouping */ /** Set the orientation vector of the ellipsoid's unique axis and axes lengths. * Must be normalized!!!!! */ void diff --git a/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.hxx b/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.hxx index d173669ab46..112594d2e0c 100644 --- a/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkSymmetricEllipsoidInteriorExteriorSpatialFunction.hxx @@ -18,6 +18,7 @@ #ifndef itkSymmetricEllipsoidInteriorExteriorSpatialFunction_hxx #define itkSymmetricEllipsoidInteriorExteriorSpatialFunction_hxx +#include "itkMath.h" #include namespace itk @@ -48,11 +49,9 @@ SymmetricEllipsoidInteriorExteriorSpatialFunction::Evaluate( pointVector[i] = position[i] - m_Center[i]; } - uniqueTerm = - std::pow(static_cast(((pointVector * m_Orientation) / (.5 * m_UniqueAxis))), static_cast(2)); + uniqueTerm = Math::sqr(static_cast(((pointVector * m_Orientation) / (.5 * m_UniqueAxis)))); symmetricVector = pointVector - (m_Orientation * (pointVector * m_Orientation)); - symmetricTerm = - std::pow(static_cast(((symmetricVector.GetNorm()) / (.5 * m_SymmetricAxes))), static_cast(2)); + symmetricTerm = Math::sqr(static_cast(((symmetricVector.GetNorm()) / (.5 * m_SymmetricAxes)))); if ((uniqueTerm + symmetricTerm) >= 0 && (uniqueTerm + symmetricTerm) <= 1) { diff --git a/Modules/Core/Common/include/itkSymmetricSecondRankTensor.h b/Modules/Core/Common/include/itkSymmetricSecondRankTensor.h index 9a8de6111c6..116497151ae 100644 --- a/Modules/Core/Common/include/itkSymmetricSecondRankTensor.h +++ b/Modules/Core/Common/include/itkSymmetricSecondRankTensor.h @@ -113,8 +113,8 @@ class ITK_TEMPLATE_EXPORT SymmetricSecondRankTensor : public FixedArrayFill(r); } /** Constructor to enable casting... */ - template - SymmetricSecondRankTensor(const SymmetricSecondRankTensor & pa) + template + SymmetricSecondRankTensor(const SymmetricSecondRankTensor & pa) : BaseArray(pa) {} @@ -126,9 +126,9 @@ class ITK_TEMPLATE_EXPORT SymmetricSecondRankTensor : public FixedArray + template Self & - operator=(const SymmetricSecondRankTensor & pa) + operator=(const SymmetricSecondRankTensor & pa) { BaseArray::operator=(pa); return *this; @@ -156,7 +156,8 @@ class ITK_TEMPLATE_EXPORT SymmetricSecondRankTensor : public FixedArray Self Rotate(const Matrix & m) const; @@ -231,6 +233,7 @@ class ITK_TEMPLATE_EXPORT SymmetricSecondRankTensor : public FixedArrayRotate(static_cast>(m)); } + /** @ITKEndGrouping */ /** Pre-Multiply by a Matrix as ResultingMatrix = Matrix * ThisTensor. */ MatrixType @@ -258,7 +261,7 @@ operator>>(InputStreamType & is, SymmetricSecondRankTensor inline void -swap(SymmetricSecondRankTensor & a, SymmetricSecondRankTensor & b) +swap(SymmetricSecondRankTensor & a, SymmetricSecondRankTensor & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkSymmetricSecondRankTensor.hxx b/Modules/Core/Common/include/itkSymmetricSecondRankTensor.hxx index 1f14cc3ec18..c89cbd373d0 100644 --- a/Modules/Core/Common/include/itkSymmetricSecondRankTensor.hxx +++ b/Modules/Core/Common/include/itkSymmetricSecondRankTensor.hxx @@ -136,8 +136,8 @@ SymmetricSecondRankTensor::operator/=(const RealValueType & r) * Performs multiplication with a scalar */ template -SymmetricSecondRankTensor SymmetricSecondRankTensor::operator*( - const RealValueType & r) const +SymmetricSecondRankTensor +SymmetricSecondRankTensor::operator*(const RealValueType & r) const { Self result; @@ -256,7 +256,7 @@ template void SymmetricSecondRankTensor::ComputeEigenValues(EigenValuesArrayType & eigenValues) const { - SymmetricEigenAnalysisType symmetricEigenSystem; + const SymmetricEigenAnalysisType symmetricEigenSystem; MatrixType tensorMatrix; @@ -280,7 +280,7 @@ void SymmetricSecondRankTensor::ComputeEigenAnalysis(EigenValuesArrayType & eigenValues, EigenVectorsMatrixType & eigenVectors) const { - SymmetricEigenAnalysisType symmetricEigenSystem; + const SymmetricEigenAnalysisType symmetricEigenSystem; MatrixType tensorMatrix; diff --git a/Modules/Core/Common/include/itkTetrahedronCell.h b/Modules/Core/Common/include/itkTetrahedronCell.h index 9c62125ff12..c017d924595 100644 --- a/Modules/Core/Common/include/itkTetrahedronCell.h +++ b/Modules/Core/Common/include/itkTetrahedronCell.h @@ -29,10 +29,6 @@ namespace itk /** \class TetrahedronCell * \brief TetrahedronCell represents a tetrahedron for a Mesh. * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. * \ingroup MeshObjects * \ingroup ITKCommon */ @@ -45,9 +41,10 @@ class ITK_TEMPLATE_EXPORT TetrahedronCell ITK_DISALLOW_COPY_AND_MOVE(TetrahedronCell); /** Standard class type alias. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(TetrahedronCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(TetrahedronCell); @@ -73,6 +70,7 @@ class ITK_TEMPLATE_EXPORT TetrahedronCell // Standard CellInterface /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -80,7 +78,7 @@ class ITK_TEMPLATE_EXPORT TetrahedronCell } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ /** Get the topological dimension of this cell. */ unsigned int GetDimension() const override; @@ -168,10 +166,10 @@ class ITK_TEMPLATE_EXPORT TetrahedronCell itkCellVisitMacro(CellGeometryEnum::TETRAHEDRON_CELL); bool - EvaluatePosition(CoordRepType *, + EvaluatePosition(CoordinateType *, PointsContainer *, - CoordRepType *, - CoordRepType[], + CoordinateType *, + CoordinateType[], double *, InterpolationWeightType *) override; diff --git a/Modules/Core/Common/include/itkTetrahedronCell.hxx b/Modules/Core/Common/include/itkTetrahedronCell.hxx index 431617d6884..0057a6309d5 100644 --- a/Modules/Core/Common/include/itkTetrahedronCell.hxx +++ b/Modules/Core/Common/include/itkTetrahedronCell.hxx @@ -65,24 +65,15 @@ TetrahedronCell::GetNumberOfBoundaryFeatures(int dimension) cons template bool -TetrahedronCell::EvaluatePosition(CoordRepType * x, +TetrahedronCell::EvaluatePosition(CoordinateType * x, PointsContainer * points, - CoordRepType * closestPoint, - CoordRepType pcoord[], + CoordinateType * closestPoint, + CoordinateType pcoord[], double * minDist2, InterpolationWeightType * weights) { - unsigned int i; - double rhs[PointDimension]; - double c1[PointDimension]; - double c2[PointDimension]; - double c3[PointDimension]; - double det; - double p4; - CoordRepType pcoords[3]; - - pcoords[0] = pcoords[1] = pcoords[2] = 0.0; + CoordinateType pcoords[3] = { 0.0, 0.0, 0.0 }; if (!points) { @@ -94,7 +85,11 @@ TetrahedronCell::EvaluatePosition(CoordRepType * x, PointType pt3 = points->GetElement(m_PointIds[2]); PointType pt4 = points->GetElement(m_PointIds[3]); - for (i = 0; i < PointDimension; ++i) + double rhs[PointDimension]; + double c1[PointDimension]; + double c2[PointDimension]; + double c3[PointDimension]; + for (unsigned int i = 0; i < PointDimension; ++i) { rhs[i] = x[i] - pt4[i]; c1[i] = pt1[i] - pt4[i]; @@ -104,20 +99,20 @@ TetrahedronCell::EvaluatePosition(CoordRepType * x, // Create a vnl_matrix so that the determinant can be computed // for any PointDimension - vnl_matrix_fixed mat; - for (i = 0; i < PointDimension; ++i) + vnl_matrix_fixed mat; + for (unsigned int i = 0; i < PointDimension; ++i) { mat.put(0, i, c1[i]); mat.put(1, i, c2[i]); mat.put(2, i, c3[i]); } - - if ((det = vnl_determinant(mat)) == 0.0) + const double det = vnl_determinant(mat); + if (det == 0.0) { return false; } - for (i = 0; i < PointDimension; ++i) + for (unsigned int i = 0; i < PointDimension; ++i) { mat.put(0, i, rhs[i]); mat.put(1, i, c2[i]); @@ -126,7 +121,7 @@ TetrahedronCell::EvaluatePosition(CoordRepType * x, pcoords[0] = vnl_determinant(mat) / det; - for (i = 0; i < PointDimension; ++i) + for (unsigned int i = 0; i < PointDimension; ++i) { mat.put(0, i, c1[i]); mat.put(1, i, rhs[i]); @@ -135,7 +130,7 @@ TetrahedronCell::EvaluatePosition(CoordRepType * x, pcoords[1] = vnl_determinant(mat) / det; - for (i = 0; i < PointDimension; ++i) + for (unsigned int i = 0; i < PointDimension; ++i) { mat.put(0, i, c1[i]); mat.put(1, i, c2[i]); @@ -144,7 +139,7 @@ TetrahedronCell::EvaluatePosition(CoordRepType * x, pcoords[2] = vnl_determinant(mat) / det; - p4 = 1.0 - pcoords[0] - pcoords[1] - pcoords[2]; + const double p4 = 1.0 - pcoords[0] - pcoords[1] - pcoords[2]; if (weights) { @@ -179,16 +174,17 @@ TetrahedronCell::EvaluatePosition(CoordRepType * x, } else { // could easily be sped up using parametric localization - next release - double dist2; - CoordRepType closest[PointDimension], pc[3]; + CoordinateType closest[PointDimension]; + CoordinateType pc[3]; if (closestPoint) { FaceAutoPointer triangle; *minDist2 = NumericTraits::max(); - for (i = 0; i < 4; ++i) + for (int i = 0; i < 4; ++i) { this->GetFace(i, triangle); + double dist2; triangle->EvaluatePosition(x, points, closest, pc, &dist2, nullptr); if (dist2 < *minDist2) diff --git a/Modules/Core/Common/include/itkThreadLogger.h b/Modules/Core/Common/include/itkThreadLogger.h index 735c9d93c2d..27879301602 100644 --- a/Modules/Core/Common/include/itkThreadLogger.h +++ b/Modules/Core/Common/include/itkThreadLogger.h @@ -59,14 +59,14 @@ class ITKCommon_EXPORT ThreadLogger : public Logger using DelayType = unsigned int; /** Definition of types of operations for ThreadLogger. */ - typedef enum + enum OperationType { SET_PRIORITY_LEVEL, SET_LEVEL_FOR_FLUSHING, ADD_LOG_OUTPUT, WRITE, FLUSH - } OperationType; + }; /** 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 @@ -103,7 +103,7 @@ class ITKCommon_EXPORT ThreadLogger : public Logger AddLogOutput(OutputType * output) override; void - Write(PriorityLevelEnum level, std::string const & content) override; + Write(PriorityLevelEnum level, const std::string & content) override; void Flush() override; diff --git a/Modules/Core/Common/include/itkThreadPool.h b/Modules/Core/Common/include/itkThreadPool.h index 63946122651..1db0c19c45d 100644 --- a/Modules/Core/Common/include/itkThreadPool.h +++ b/Modules/Core/Common/include/itkThreadPool.h @@ -119,11 +119,12 @@ auto result = pool->AddWork([](int param) { return param; }, 7); This function should be used carefully, probably only during static initialization phase to disable waiting for threads when ITK is built as a static library and linked into a shared library (Windows only). */ + /** @ITKStartGrouping */ static bool GetDoNotWaitForThreads(); static void SetDoNotWaitForThreads(bool doNotWaitForThreads); - + /** @ITKEndGrouping */ protected: /** We need access to the mutex in AddWork, and the variable is only * visible in the .cxx file, so this method returns it. */ diff --git a/Modules/Core/Common/include/itkThreadSupport.h b/Modules/Core/Common/include/itkThreadSupport.h index 467ced7a418..57d01ff6357 100644 --- a/Modules/Core/Common/include/itkThreadSupport.h +++ b/Modules/Core/Common/include/itkThreadSupport.h @@ -22,16 +22,6 @@ #include "itkConfigure.h" // For ITK_USE_WIN32_THREADS, ITK_USE_PTHREADS, etc. -// This implementation uses a routine called SignalObjectAndWait() -// which is only defined on WinNT 4.0 or greater systems. We need to -// define this symbol in order to get the prototype for the -// routine. This needs to be done before we load any system headers. -#ifdef ITK_USE_WIN32_THREADS -# ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x0501 // TBB 4.4 requires WinXP (0x0501 or greater) -# endif -#endif - #if defined(ITK_USE_PTHREADS) # include #elif defined(ITK_USE_WIN32_THREADS) @@ -44,6 +34,7 @@ namespace itk { /** Platform specific type alias for simple types */ +/** @ITKStartGrouping */ #if defined(ITK_USE_PTHREADS) constexpr size_t ITK_MAX_THREADS = ITK_DEFAULT_MAX_THREADS; using MutexType = pthread_mutex_t; @@ -54,7 +45,7 @@ using ThreadProcessIdType = pthread_t; constexpr ThreadProcessIdType ITK_DEFAULT_THREAD_ID = 0; # endif using ITK_THREAD_RETURN_TYPE = void *; - +/** @ITKEndGrouping */ constexpr ITK_THREAD_RETURN_TYPE ITK_THREAD_RETURN_DEFAULT_VALUE = nullptr; using itk::ITK_THREAD_RETURN_DEFAULT_VALUE; // We need this out of the itk namespace for #define to work below using ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION = itk::ITK_THREAD_RETURN_TYPE; @@ -107,8 +98,8 @@ struct ConditionVariableType // threads to wake up and // release the semaphore - int m_WasBroadcast; // Used as boolean. Keeps track of whether - // we were broadcasting or signaling + int m_WasBroadcast; // Used as boolean. Keeps track of whether + // we were broadcasting or signaling #endif }; @@ -117,7 +108,7 @@ struct ConditionVariableType // Compile-time conditional code for different threading models // require that some items are #defines (always global scope) or // can sometimes be rigorously typed. When rigorously typed, -// we need to re-exposed to the global namespace to keep the +// we need to re-expose to the global namespace to keep the // use of these items consistent. #if defined(ITK_USE_PTHREADS) using itk::ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION; diff --git a/Modules/Core/Common/include/itkThreadedIteratorRangePartitioner.hxx b/Modules/Core/Common/include/itkThreadedIteratorRangePartitioner.hxx index 5f9478e6d87..785b0c4fa48 100644 --- a/Modules/Core/Common/include/itkThreadedIteratorRangePartitioner.hxx +++ b/Modules/Core/Common/include/itkThreadedIteratorRangePartitioner.hxx @@ -36,10 +36,10 @@ ThreadedIteratorRangePartitioner::PartitionDomain(const ThreadIdType // overallIndexRange is expected to be inclusive // determine the actual number of pieces that will be generated - ThreadIdType count = std::distance(completeDomain.Begin(), completeDomain.End()); + const ThreadIdType count = std::distance(completeDomain.Begin(), completeDomain.End()); auto valuesPerThread = Math::Ceil(static_cast(count) / static_cast(requestedTotal)); - ThreadIdType maxThreadIdUsed = + const ThreadIdType maxThreadIdUsed = Math::Ceil(static_cast(count) / static_cast(valuesPerThread)) - 1; if (threadId > maxThreadIdUsed) diff --git a/Modules/Core/Common/include/itkTimeStamp.h b/Modules/Core/Common/include/itkTimeStamp.h index 8509ffb7ef1..34467e89af7 100644 --- a/Modules/Core/Common/include/itkTimeStamp.h +++ b/Modules/Core/Common/include/itkTimeStamp.h @@ -102,6 +102,7 @@ class ITKCommon_EXPORT TimeStamp } /** Support comparisons of time stamp objects directly. */ + /** @ITKStartGrouping */ bool operator>(TimeStamp & ts) const { @@ -112,7 +113,7 @@ class ITKCommon_EXPORT TimeStamp { return (m_ModifiedTime < ts.m_ModifiedTime); } - + /** @ITKEndGrouping */ /** Allow for typecasting to unsigned long. */ operator ModifiedTimeType() const { return m_ModifiedTime; } diff --git a/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.h b/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.h index 85b39abc80b..9de5403353a 100644 --- a/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.h +++ b/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.h @@ -67,17 +67,20 @@ class ITK_TEMPLATE_EXPORT TorusInteriorExteriorSpatialFunction /** Set/Get the origin of the torus (the point from which the major * radius is measured). */ + /** @ITKStartGrouping */ itkGetConstMacro(Origin, InputType); itkSetMacro(Origin, InputType); - + /** @ITKEndGrouping */ /** Set/Get the major radius of the torus. */ + /** @ITKStartGrouping */ itkGetConstMacro(MajorRadius, double); itkSetMacro(MajorRadius, double); - + /** @ITKEndGrouping */ /** Set/Get the minor radius of the torus (radius of tube). */ + /** @ITKStartGrouping */ itkGetConstMacro(MinorRadius, double); itkSetMacro(MinorRadius, double); - + /** @ITKEndGrouping */ protected: TorusInteriorExteriorSpatialFunction() = default; ~TorusInteriorExteriorSpatialFunction() override = default; diff --git a/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx b/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx index 0aac93f944c..93e5b0d2edf 100644 --- a/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx +++ b/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx @@ -18,6 +18,8 @@ #ifndef itkTorusInteriorExteriorSpatialFunction_hxx #define itkTorusInteriorExteriorSpatialFunction_hxx +#include "itkMath.h" + namespace itk { @@ -25,20 +27,18 @@ template auto TorusInteriorExteriorSpatialFunction::Evaluate(const InputType & position) const -> OutputType { - double x = position[0] - m_Origin[0]; - double y = position[1] - m_Origin[1]; - double z = position[2] - m_Origin[2]; + const double x = position[0] - m_Origin[0]; + const double y = position[1] - m_Origin[1]; + const double z = position[2] - m_Origin[2]; - double k = std::pow(m_MajorRadius - std::sqrt(x * x + y * y), 2.0) + z * z; + const double k = Math::sqr(m_MajorRadius - std::sqrt(x * x + y * y)) + z * z; if (k <= (m_MinorRadius * m_MinorRadius)) { return true; } - else - { - return false; - } + + return false; } template @@ -47,10 +47,8 @@ TorusInteriorExteriorSpatialFunction::PrintSelf(std::ostream { Superclass::PrintSelf(os, indent); - unsigned int i; - os << indent << "Origin: ["; - for (i = 0; i < VDimension - 1; ++i) + for (unsigned int i = 0; i < VDimension - 1; ++i) { os << m_Origin[i] << ", "; } diff --git a/Modules/Core/Common/include/itkTotalProgressReporter.h b/Modules/Core/Common/include/itkTotalProgressReporter.h index bf46c6588f0..313fed0b983 100644 --- a/Modules/Core/Common/include/itkTotalProgressReporter.h +++ b/Modules/Core/Common/include/itkTotalProgressReporter.h @@ -102,8 +102,8 @@ class ITKCommon_EXPORT TotalProgressReporter if (count >= m_PixelsBeforeUpdate) { - SizeValueType total = static_cast(m_PixelsPerUpdate - m_PixelsBeforeUpdate) + count; - SizeValueType numberOfUpdates = total / m_PixelsPerUpdate; + const SizeValueType total = static_cast(m_PixelsPerUpdate - m_PixelsBeforeUpdate) + count; + const SizeValueType numberOfUpdates = total / m_PixelsPerUpdate; m_PixelsBeforeUpdate = m_PixelsPerUpdate - total % m_PixelsPerUpdate; m_CurrentPixel += numberOfUpdates * m_PixelsPerUpdate; @@ -124,7 +124,7 @@ class ITKCommon_EXPORT TotalProgressReporter protected: ProcessObject * m_Filter; float m_InverseNumberOfPixels; - SizeValueType m_CurrentPixel; + SizeValueType m_CurrentPixel{ 0 }; SizeValueType m_PixelsPerUpdate; SizeValueType m_PixelsBeforeUpdate; float m_ProgressWeight; diff --git a/Modules/Core/Common/include/itkTriangleCell.h b/Modules/Core/Common/include/itkTriangleCell.h index 24b6a787ddf..066c8e71978 100644 --- a/Modules/Core/Common/include/itkTriangleCell.h +++ b/Modules/Core/Common/include/itkTriangleCell.h @@ -51,9 +51,10 @@ class ITK_TEMPLATE_EXPORT TriangleCell ITK_DISALLOW_COPY_AND_MOVE(TriangleCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(TriangleCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(TriangleCell); @@ -74,6 +75,7 @@ class ITK_TEMPLATE_EXPORT TriangleCell // Standard CellInterface /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -81,7 +83,7 @@ class ITK_TEMPLATE_EXPORT TriangleCell } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ /** Get the topological dimension of this cell. */ unsigned int GetDimension() const override; @@ -157,10 +159,10 @@ class ITK_TEMPLATE_EXPORT TriangleCell /** Evaluate the position of a given point inside the cell */ bool - EvaluatePosition(CoordRepType *, + EvaluatePosition(CoordinateType *, PointsContainer *, - CoordRepType *, - CoordRepType[], + CoordinateType *, + CoordinateType[], double *, InterpolationWeightType *) override; @@ -168,11 +170,11 @@ class ITK_TEMPLATE_EXPORT TriangleCell itkCellVisitMacro(CellGeometryEnum::TRIANGLE_CELL); /** Compute Area to a TriangleCell given a PointsContainer. */ - CoordRepType + CoordinateType ComputeArea(PointsContainer *); PointType - ComputeBarycenter(CoordRepType *, PointsContainer *); + ComputeBarycenter(CoordinateType *, PointsContainer *); PointType ComputeCenterOfGravity(PointsContainer *); @@ -182,16 +184,7 @@ class ITK_TEMPLATE_EXPORT TriangleCell public: TriangleCell() = default; -#if defined(__GNUC__) - // A bug in some versions of the GCC and Clang compilers - // result in an ICE or linker error when "= default" is requested. - // This was observed in at least gcc 4.8 and 5.4.0, and - // AppleClang 7.0.2 and 8.0.0. Probably others too. - // "= default" doesn't gain us much, so just don't use it here. - ~TriangleCell() override{}; -#else ~TriangleCell() override = default; -#endif protected: /** Store the number of points needed for a triangle. */ @@ -202,7 +195,7 @@ class ITK_TEMPLATE_EXPORT TriangleCell /** Compute the squared distance between a point and a line segment defined by two other points. Returns the * parametric coordinate t and point location on line. */ double - DistanceToLine(PointType x, PointType p1, PointType p2, double & t, CoordRepType * closestPoint); + DistanceToLine(PointType x, PointType p1, PointType p2, double & t, CoordinateType * closestPoint); double DistanceToLine(PointType x, PointType p1, PointType p2, double & t, PointType & closestPoint); diff --git a/Modules/Core/Common/include/itkTriangleCell.hxx b/Modules/Core/Common/include/itkTriangleCell.hxx index 2f4a8fd0a4e..8672aa332ba 100644 --- a/Modules/Core/Common/include/itkTriangleCell.hxx +++ b/Modules/Core/Common/include/itkTriangleCell.hxx @@ -20,6 +20,7 @@ #include "vnl/algo/vnl_determinant.h" #include // For copy_n. +#include // For abs. namespace itk { @@ -192,13 +193,13 @@ TriangleCell::GetEdge(CellFeatureIdentifier edgeId, EdgeAutoPoin template double -TriangleCell::DistanceToLine(PointType x, - PointType p1, - PointType p2, - double & t, - CoordRepType * closestPoint) +TriangleCell::DistanceToLine(PointType x, + PointType p1, + PointType p2, + double & t, + CoordinateType * closestPoint) { - // convert from CoordRepType * to PointType: + // convert from CoordinateType * to PointType: PointType temp(closestPoint); // for (unsigned int i = 0; i < PointDimension; ++i) // { @@ -208,7 +209,7 @@ TriangleCell::DistanceToLine(PointType x, // Compute the squared distance to the line: const double distance2 = this->DistanceToLine(x, p1, p2, t, temp); - // convert from PointType to CoordRepType * : + // convert from PointType to CoordinateType * : for (unsigned int j = 0; j < PointDimension; ++j) { closestPoint[j] = temp[j]; @@ -237,12 +238,7 @@ TriangleCell::DistanceToLine(PointType x, denom += static_cast(v21[i] * v21[i]); } - // trying to avoid an expensive fabs - double tolerance = 1.e-05 * num; - if (tolerance < 0.0) - { - tolerance = -tolerance; - } + const double tolerance = std::abs(1.e-05 * num); if ((-tolerance < denom) && (denom < tolerance)) // numerically bad! { closestPoint = p1; // arbitrary, point is (numerically) far away @@ -268,7 +264,7 @@ TriangleCell::DistanceToLine(PointType x, template auto -TriangleCell::ComputeArea(PointsContainer * iPoints) -> CoordRepType +TriangleCell::ComputeArea(PointsContainer * iPoints) -> CoordinateType { PointType p[3]; @@ -277,34 +273,31 @@ TriangleCell::ComputeArea(PointsContainer * iPoints) -> CoordRep p[i] = iPoints->GetElement(m_PointIds[i]); } - CoordRepType a = p[1].EuclideanDistanceTo(p[2]); - CoordRepType b = p[0].EuclideanDistanceTo(p[2]); - CoordRepType c = p[1].EuclideanDistanceTo(p[0]); + CoordinateType a = p[1].EuclideanDistanceTo(p[2]); + CoordinateType b = p[0].EuclideanDistanceTo(p[2]); + CoordinateType c = p[1].EuclideanDistanceTo(p[0]); - CoordRepType s = 0.5 * (a + b + c); + CoordinateType s = 0.5 * (a + b + c); return std::sqrt(s * (s - a) * (s - b) * (s - c)); } template auto -TriangleCell::ComputeBarycenter(CoordRepType * iWeights, PointsContainer * iPoints) -> PointType +TriangleCell::ComputeBarycenter(CoordinateType * iWeights, PointsContainer * iPoints) -> PointType { - PointType p[3]; - CoordRepType sum_weights(0.); - unsigned int i(0); + PointType p[3]; + CoordinateType sum_weights(0.); - for (; i < 3; ++i) + for (unsigned int i = 0; i < 3; ++i) { sum_weights += iWeights[i]; p[i] = iPoints->GetElement(m_PointIds[i]); } - PointType oP; - + PointType oP{}; if (sum_weights != 0.) { - oP.Fill(0.); - for (i = 0; i < 3; ++i) + for (unsigned int i = 0; i < 3; ++i) { oP += p[i].GetVectorFromOrigin() * iWeights[i] / sum_weights; } @@ -320,7 +313,7 @@ template auto TriangleCell::ComputeCenterOfGravity(PointsContainer * iPoints) -> PointType { - std::vector weights(3, 1. / 3.); + std::vector weights(3, 1. / 3.); return ComputeBarycenter(&weights[0], iPoints); } @@ -328,61 +321,56 @@ template auto TriangleCell::ComputeCircumCenter(PointsContainer * iPoints) -> PointType { - std::vector weights(3, 0.); + std::vector weights(3, 0.); - PointType p[3]; - unsigned int i; + PointType p[3]; - for (i = 0; i < 3; ++i) + for (unsigned int i = 0; i < 3; ++i) { p[i] = iPoints->GetElement(m_PointIds[i]); } - CoordRepType a = p[1].SquaredEuclideanDistanceTo(p[2]); - CoordRepType b = p[0].SquaredEuclideanDistanceTo(p[2]); - CoordRepType c = p[1].SquaredEuclideanDistanceTo(p[0]); + CoordinateType a = p[1].SquaredEuclideanDistanceTo(p[2]); + CoordinateType b = p[0].SquaredEuclideanDistanceTo(p[2]); + CoordinateType c = p[1].SquaredEuclideanDistanceTo(p[0]); weights[0] = a * (b + c - a); weights[1] = b * (c + a - b); weights[2] = c * (a + b - c); - CoordRepType sum_weights = weights[0] + weights[1] + weights[2]; + CoordinateType sum_weights = weights[0] + weights[1] + weights[2]; if (sum_weights != 0.) { - PointType oP; - oP.Fill(0.); + PointType oP{}; - for (i = 0; i < 3; ++i) + for (unsigned i = 0; i < 3; ++i) { oP += p[i].GetVectorFromOrigin() * weights[i] / sum_weights; } return oP; } - else - { - return p[0]; - } + + return p[0]; } template bool -TriangleCell::EvaluatePosition(CoordRepType * x, +TriangleCell::EvaluatePosition(CoordinateType * x, PointsContainer * points, - CoordRepType * closestPoint, - CoordRepType pcoord[], + CoordinateType * closestPoint, + CoordinateType pcoord[], double * minDist2, InterpolationWeightType * weights) { - unsigned int i; - double dist2Point; - double dist2Line1; - double dist2Line2; - PointType closest; - PointType closestPoint1; - PointType closestPoint2; - PointType X(x); + double dist2Point; + double dist2Line1; + double dist2Line2; + PointType closest; + PointType closestPoint1; + PointType closestPoint2; + const PointType X(x); if (!points) { @@ -396,8 +384,8 @@ TriangleCell::EvaluatePosition(CoordRepType * x, // Compute Vectors along the edges. // These two vectors form a vector base for the 2D space of the triangle cell. - VectorType v12 = pt1 - pt2; - VectorType v32 = pt3 - pt2; + const VectorType v12 = pt1 - pt2; + const VectorType v32 = pt3 - pt2; // Compute Vectors in the dual vector base inside the 2D space of the triangle // cell. @@ -416,13 +404,13 @@ TriangleCell::EvaluatePosition(CoordRepType * x, // Compute components of the input point in the 2D // space defined by v12 and v32 - VectorType xo = X - pt2; + const VectorType xo = X - pt2; const double u12p = xo * u12; const double u32p = xo * u32; - VectorType x12 = v12 * u12p; - VectorType x32 = v32 * u32p; + const VectorType x12 = v12 * u12p; + const VectorType x32 = v32 * u32p; // The projection of point X in the plane is cp PointType cp = pt2 + x12 + x32; @@ -447,7 +435,7 @@ TriangleCell::EvaluatePosition(CoordRepType * x, if (closestPoint) { // Compute the Distance 2 Between Points *minDist2 = 0; - for (i = 0; i < PointDimension; ++i) + for (unsigned int i = 0; i < PointDimension; ++i) { const double val = cp[i] - x[i]; *minDist2 += val * val; @@ -471,131 +459,133 @@ TriangleCell::EvaluatePosition(CoordRepType * x, return true; } - else + + if (closestPoint) { - if (closestPoint) + double lt; // parameter along the line (not used) + if (b1 < 0.0 && b2 < 0.0) { - double lt; // parameter along the line (not used) - if (b1 < 0.0 && b2 < 0.0) + dist2Point = 0; + for (unsigned int i = 0; i < PointDimension; ++i) { - dist2Point = 0; - for (i = 0; i < PointDimension; ++i) - { - dist2Point += (x[i] - pt3[i]) * (x[i] - pt3[i]); - } - dist2Line1 = this->DistanceToLine(x, pt1, pt3, lt, closestPoint1); - dist2Line2 = this->DistanceToLine(x, pt3, pt2, lt, closestPoint2); - if (dist2Point < dist2Line1) - { - *minDist2 = dist2Point; - closest = pt3; - } - else - { - *minDist2 = dist2Line1; - closest = closestPoint1; - } - if (dist2Line2 < *minDist2) - { - *minDist2 = dist2Line2; - closest = closestPoint2; - } - for (i = 0; i < PointDimension; ++i) - { - closestPoint[i] = closest[i]; - } - for (; i < 3; ++i) - { - closestPoint[i] = 0.; - } + dist2Point += (x[i] - pt3[i]) * (x[i] - pt3[i]); } - else if (b2 < 0.0 && b3 < 0.0) + dist2Line1 = this->DistanceToLine(x, pt1, pt3, lt, closestPoint1); + dist2Line2 = this->DistanceToLine(x, pt3, pt2, lt, closestPoint2); + if (dist2Point < dist2Line1) { - dist2Point = 0; - for (i = 0; i < PointDimension; ++i) - { - dist2Point += (x[i] - pt1[i]) * (x[i] - pt1[i]); - } - dist2Line1 = this->DistanceToLine(x, pt1, pt3, lt, closestPoint1); - dist2Line2 = this->DistanceToLine(x, pt1, pt2, lt, closestPoint2); - if (dist2Point < dist2Line1) - { - *minDist2 = dist2Point; - closest = pt1; - } - else - { - *minDist2 = dist2Line1; - closest = closestPoint1; - } - if (dist2Line2 < *minDist2) - { - *minDist2 = dist2Line2; - closest = closestPoint2; - } - for (i = 0; i < PointDimension; ++i) - { - closestPoint[i] = closest[i]; - } - for (; i < 3; ++i) - { - closestPoint[i] = 0.; - } + *minDist2 = dist2Point; + closest = pt3; } - else if (b1 < 0.0 && b3 < 0.0) + else { - dist2Point = 0; - for (i = 0; i < PointDimension; ++i) - { - dist2Point += (x[i] - pt2[i]) * (x[i] - pt2[i]); - } - dist2Line1 = this->DistanceToLine(x, pt2, pt3, lt, closestPoint1); - dist2Line2 = this->DistanceToLine(x, pt1, pt2, lt, closestPoint2); - if (dist2Point < dist2Line1) - { - *minDist2 = dist2Point; - closest = pt2; - } - else - { - *minDist2 = dist2Line1; - closest = closestPoint1; - } - if (dist2Line2 < *minDist2) - { - *minDist2 = dist2Line2; - closest = closestPoint2; - } - for (i = 0; i < PointDimension; ++i) - { - closestPoint[i] = closest[i]; - } - for (; i < 3; ++i) - { - closestPoint[i] = 0.; - } + *minDist2 = dist2Line1; + closest = closestPoint1; } - else if (b1 < 0.0) + if (dist2Line2 < *minDist2) { - *minDist2 = this->DistanceToLine(x, pt2, pt3, lt, closestPoint); + *minDist2 = dist2Line2; + closest = closestPoint2; } - else if (b2 < 0.0) + unsigned int i = 0; + for (; i < PointDimension; ++i) { - *minDist2 = this->DistanceToLine(x, pt1, pt3, lt, closestPoint); + closestPoint[i] = closest[i]; } - else if (b3 < 0.0) + for (; i < 3; ++i) { - *minDist2 = this->DistanceToLine(x, pt1, pt2, lt, closestPoint); + closestPoint[i] = 0.; } } - if (pcoord) + else if (b2 < 0.0 && b3 < 0.0) { - pcoord[0] = b1; - pcoord[1] = b2; - pcoord[2] = b3; + dist2Point = 0; + for (unsigned int i = 0; i < PointDimension; ++i) + { + dist2Point += (x[i] - pt1[i]) * (x[i] - pt1[i]); + } + dist2Line1 = this->DistanceToLine(x, pt1, pt3, lt, closestPoint1); + dist2Line2 = this->DistanceToLine(x, pt1, pt2, lt, closestPoint2); + if (dist2Point < dist2Line1) + { + *minDist2 = dist2Point; + closest = pt1; + } + else + { + *minDist2 = dist2Line1; + closest = closestPoint1; + } + if (dist2Line2 < *minDist2) + { + *minDist2 = dist2Line2; + closest = closestPoint2; + } + unsigned int i = 0; + for (; i < PointDimension; ++i) + { + closestPoint[i] = closest[i]; + } + for (; i < 3; ++i) + { + closestPoint[i] = 0.; + } + } + else if (b1 < 0.0 && b3 < 0.0) + { + dist2Point = 0; + for (unsigned int i = 0; i < PointDimension; ++i) + { + dist2Point += (x[i] - pt2[i]) * (x[i] - pt2[i]); + } + dist2Line1 = this->DistanceToLine(x, pt2, pt3, lt, closestPoint1); + dist2Line2 = this->DistanceToLine(x, pt1, pt2, lt, closestPoint2); + if (dist2Point < dist2Line1) + { + *minDist2 = dist2Point; + closest = pt2; + } + else + { + *minDist2 = dist2Line1; + closest = closestPoint1; + } + if (dist2Line2 < *minDist2) + { + *minDist2 = dist2Line2; + closest = closestPoint2; + } + unsigned int i = 0; + for (; i < PointDimension; ++i) + { + closestPoint[i] = closest[i]; + } + for (; i < 3; ++i) + { + closestPoint[i] = 0.; + } + } + else if (b1 < 0.0) + { + *minDist2 = this->DistanceToLine(x, pt2, pt3, lt, closestPoint); + } + else if (b2 < 0.0) + { + *minDist2 = this->DistanceToLine(x, pt1, pt3, lt, closestPoint); + } + else if (b3 < 0.0) + { + *minDist2 = this->DistanceToLine(x, pt1, pt2, lt, closestPoint); } - // Just fall through to default return false; } + if (pcoord) + { + pcoord[0] = b1; + pcoord[1] = b2; + pcoord[2] = b3; + } + // Just fall through to default return false; + return false; // Default case that should never be reached. } } // end namespace itk diff --git a/Modules/Core/Common/include/itkTriangleHelper.h b/Modules/Core/Common/include/itkTriangleHelper.h index 56d8d915901..b2995424bdd 100644 --- a/Modules/Core/Common/include/itkTriangleHelper.h +++ b/Modules/Core/Common/include/itkTriangleHelper.h @@ -33,8 +33,11 @@ class ITK_TEMPLATE_EXPORT TriangleHelper public: using Self = TriangleHelper; using PointType = TPoint; - using CoordinateType = typename PointType::CoordRepType; - using CoordRepType = CoordinateType; + using CoordinateType = typename PointType::CoordinateType; +#ifndef ITK_FUTURE_LEGACY_REMOVE + using CoordRepType ITK_FUTURE_DEPRECATED( + "ITK 6 discourages using `CoordRepType`. Please use `CoordinateType` instead!") = CoordinateType; +#endif using VectorType = typename PointType::VectorType; using CrossVectorType = CrossHelper; @@ -50,20 +53,20 @@ class ITK_TEMPLATE_EXPORT TriangleHelper ComputeNormal(const PointType & iA, const PointType & iB, const PointType & iC); /** \brief Compute cotangent(iA,iB,iC)*/ - static CoordRepType + static CoordinateType Cotangent(const PointType & iA, const PointType & iB, const PointType & iC); /** \brief Compute barycenter, with given weights*/ static PointType - ComputeBarycenter(const CoordRepType & iA1, - const PointType & iP1, - const CoordRepType & iA2, - const PointType & iP2, - const CoordRepType & iA3, - const PointType & iP3); + ComputeBarycenter(const CoordinateType & iA1, + const PointType & iP1, + const CoordinateType & iA2, + const PointType & iP2, + const CoordinateType & iA3, + const PointType & iP3); /** \brief Compute angles (iA,iB,iC)*/ - static CoordRepType + static CoordinateType ComputeAngle(const PointType & iP1, const PointType & iP2, const PointType & iP3); /** \brief Compute center of mass*/ @@ -79,10 +82,10 @@ class ITK_TEMPLATE_EXPORT TriangleHelper ComputeConstrainedCircumCenter(const PointType & iP1, const PointType & iP2, const PointType & iP3); /** \brief Compute Area.*/ - static CoordRepType + static CoordinateType ComputeArea(const PointType & iP1, const PointType & iP2, const PointType & iP3); - static CoordRepType + static CoordinateType ComputeMixedArea(const PointType & iP1, const PointType & iP2, const PointType & iP3); }; } // namespace itk diff --git a/Modules/Core/Common/include/itkTriangleHelper.hxx b/Modules/Core/Common/include/itkTriangleHelper.hxx index 42bdd5de2ea..d2bdd49725d 100644 --- a/Modules/Core/Common/include/itkTriangleHelper.hxx +++ b/Modules/Core/Common/include/itkTriangleHelper.hxx @@ -26,30 +26,28 @@ template bool TriangleHelper::IsObtuse(const PointType & iA, const PointType & iB, const PointType & iC) { - VectorType v01 = iB - iA; - VectorType v02 = iC - iA; - VectorType v12 = iC - iB; + const VectorType v01 = iB - iA; + const VectorType v02 = iC - iA; + const VectorType v12 = iC - iB; if (v01 * v02 < 0.0) { return true; } + + if (v02 * v12 < 0.0) + { + return true; + } else { - if (v02 * v12 < 0.0) + if (v01 * -v12 < 0.0) { return true; } else { - if (v01 * -v12 < 0.0) - { - return true; - } - else - { - return false; - } + return false; } } } @@ -58,9 +56,9 @@ template auto TriangleHelper::ComputeNormal(const PointType & iA, const PointType & iB, const PointType & iC) -> VectorType { - CrossVectorType cross; - VectorType w = cross(iB - iA, iC - iA); - CoordRepType l2 = w.GetSquaredNorm(); + const CrossVectorType cross; + VectorType w = cross(iB - iA, iC - iA); + const CoordinateType l2 = w.GetSquaredNorm(); if (l2 != 0.0) { @@ -72,55 +70,52 @@ TriangleHelper::ComputeNormal(const PointType & iA, const PointType & iB template auto -TriangleHelper::Cotangent(const PointType & iA, const PointType & iB, const PointType & iC) -> CoordRepType +TriangleHelper::Cotangent(const PointType & iA, const PointType & iB, const PointType & iC) -> CoordinateType { VectorType v21 = iA - iB; - CoordRepType v21_l2 = v21.GetSquaredNorm(); + const CoordinateType v21_l2 = v21.GetSquaredNorm(); - if (Math::NotAlmostEquals(v21_l2, CoordRepType{})) + if (Math::NotAlmostEquals(v21_l2, CoordinateType{})) { v21 /= std::sqrt(v21_l2); } - VectorType v23 = iC - iB; - CoordRepType v23_l2 = v23.GetSquaredNorm(); - if (Math::NotAlmostEquals(v23_l2, CoordRepType{})) + VectorType v23 = iC - iB; + const CoordinateType v23_l2 = v23.GetSquaredNorm(); + if (Math::NotAlmostEquals(v23_l2, CoordinateType{})) { v23 /= std::sqrt(v23_l2); } - CoordRepType bound(0.999999); + const CoordinateType bound(0.999999); - CoordRepType cos_theta = std::clamp(v21 * v23, -bound, bound); + const CoordinateType cos_theta = std::clamp(v21 * v23, -bound, bound); return 1.0 / std::tan(std::acos(cos_theta)); } template auto -TriangleHelper::ComputeBarycenter(const CoordRepType & iA1, - const PointType & iP1, - const CoordRepType & iA2, - const PointType & iP2, - const CoordRepType & iA3, - const PointType & iP3) -> PointType +TriangleHelper::ComputeBarycenter(const CoordinateType & iA1, + const PointType & iP1, + const CoordinateType & iA2, + const PointType & iP2, + const CoordinateType & iA3, + const PointType & iP3) -> PointType { - PointType oPt; - - CoordRepType total = iA1 + iA2 + iA3; - - if (Math::AlmostEquals(total, CoordRepType{})) + const CoordinateType total = iA1 + iA2 + iA3; + PointType oPt{}; + if (Math::AlmostEquals(total, CoordinateType{})) { // in such case there is no barycenter; - oPt.Fill(0.); return oPt; } - CoordRepType inv_total = 1. / total; - CoordRepType a1 = iA1 * inv_total; - CoordRepType a2 = iA2 * inv_total; - CoordRepType a3 = iA3 * inv_total; + const CoordinateType inv_total = 1. / total; + const CoordinateType a1 = iA1 * inv_total; + const CoordinateType a2 = iA2 * inv_total; + const CoordinateType a3 = iA3 * inv_total; for (unsigned int dim = 0; dim < PointDimension; ++dim) { @@ -133,13 +128,13 @@ TriangleHelper::ComputeBarycenter(const CoordRepType & iA1, template auto TriangleHelper::ComputeAngle(const PointType & iP1, const PointType & iP2, const PointType & iP3) - -> CoordRepType + -> CoordinateType { VectorType v21 = iP1 - iP2; VectorType v23 = iP3 - iP2; - CoordRepType v21_l2 = v21.GetSquaredNorm(); - CoordRepType v23_l2 = v23.GetSquaredNorm(); + const CoordinateType v21_l2 = v21.GetSquaredNorm(); + const CoordinateType v23_l2 = v23.GetSquaredNorm(); if (v21_l2 != 0.0) { @@ -150,9 +145,9 @@ TriangleHelper::ComputeAngle(const PointType & iP1, const PointType & iP v23 /= std::sqrt(v23_l2); } - CoordRepType bound(0.999999); + const CoordinateType bound(0.999999); - CoordRepType cos_theta = std::clamp(v21 * v23, -bound, bound); + const CoordinateType cos_theta = std::clamp(v21 * v23, -bound, bound); return std::acos(cos_theta); } @@ -170,15 +165,13 @@ auto TriangleHelper::ComputeCircumCenter(const PointType & iP1, const PointType & iP2, const PointType & iP3) -> PointType { - PointType oPt; - - oPt.Fill(0.0); + const PointType oPt{}; - CoordRepType a = iP2.SquaredEuclideanDistanceTo(iP3); - CoordRepType b = iP1.SquaredEuclideanDistanceTo(iP3); - CoordRepType c = iP2.SquaredEuclideanDistanceTo(iP1); + const CoordinateType a = iP2.SquaredEuclideanDistanceTo(iP3); + const CoordinateType b = iP1.SquaredEuclideanDistanceTo(iP3); + const CoordinateType c = iP2.SquaredEuclideanDistanceTo(iP1); - CoordRepType Weight[3]; + CoordinateType Weight[3]; Weight[0] = a * (b + c - a); Weight[1] = b * (c + a - b); Weight[2] = c * (a + b - c); @@ -192,11 +185,11 @@ TriangleHelper::ComputeConstrainedCircumCenter(const PointType & iP1, const PointType & iP2, const PointType & iP3) -> PointType { - const CoordRepType a = iP2.SquaredEuclideanDistanceTo(iP3); - const CoordRepType b = iP1.SquaredEuclideanDistanceTo(iP3); - const CoordRepType c = iP2.SquaredEuclideanDistanceTo(iP1); + const CoordinateType a = iP2.SquaredEuclideanDistanceTo(iP3); + const CoordinateType b = iP1.SquaredEuclideanDistanceTo(iP3); + const CoordinateType c = iP2.SquaredEuclideanDistanceTo(iP1); - CoordRepType Weight[3] = { a * (b + c - a), b * (c + a - b), c * (a + b - c) }; + CoordinateType Weight[3] = { a * (b + c - a), b * (c + a - b), c * (a + b - c) }; for (auto & i : Weight) { @@ -211,46 +204,45 @@ TriangleHelper::ComputeConstrainedCircumCenter(const PointType & iP1, template auto -TriangleHelper::ComputeArea(const PointType & iP1, const PointType & iP2, const PointType & iP3) -> CoordRepType +TriangleHelper::ComputeArea(const PointType & iP1, const PointType & iP2, const PointType & iP3) + -> CoordinateType { - CoordRepType a = iP2.EuclideanDistanceTo(iP3); - CoordRepType b = iP1.EuclideanDistanceTo(iP3); - CoordRepType c = iP2.EuclideanDistanceTo(iP1); + const CoordinateType a = iP2.EuclideanDistanceTo(iP3); + const CoordinateType b = iP1.EuclideanDistanceTo(iP3); + const CoordinateType c = iP2.EuclideanDistanceTo(iP1); - CoordRepType s = 0.5 * (a + b + c); + const CoordinateType s = 0.5 * (a + b + c); - return static_cast(std::sqrt(s * (s - a) * (s - b) * (s - c))); + return static_cast(std::sqrt(s * (s - a) * (s - b) * (s - c))); } template auto TriangleHelper::ComputeMixedArea(const PointType & iP1, const PointType & iP2, const PointType & iP3) - -> CoordRepType + -> CoordinateType { using TriangleType = TriangleHelper; if (!TriangleType::IsObtuse(iP1, iP2, iP3)) { - auto sq_d01 = static_cast(iP1.SquaredEuclideanDistanceTo(iP2)); - auto sq_d02 = static_cast(iP1.SquaredEuclideanDistanceTo(iP3)); + auto sq_d01 = static_cast(iP1.SquaredEuclideanDistanceTo(iP2)); + auto sq_d02 = static_cast(iP1.SquaredEuclideanDistanceTo(iP3)); - CoordRepType cot_theta_210 = TriangleType::Cotangent(iP3, iP2, iP1); - CoordRepType cot_theta_021 = TriangleType::Cotangent(iP1, iP3, iP2); + const CoordinateType cot_theta_210 = TriangleType::Cotangent(iP3, iP2, iP1); + const CoordinateType cot_theta_021 = TriangleType::Cotangent(iP1, iP3, iP2); return 0.125 * (sq_d02 * cot_theta_210 + sq_d01 * cot_theta_021); } + + auto area = static_cast(TriangleType::ComputeArea(iP1, iP2, iP3)); + + if ((iP2 - iP1) * (iP3 - iP1) < CoordinateType{}) + { + return 0.5 * area; + } else { - auto area = static_cast(TriangleType::ComputeArea(iP1, iP2, iP3)); - - if ((iP2 - iP1) * (iP3 - iP1) < CoordRepType{}) - { - return 0.5 * area; - } - else - { - return 0.25 * area; - } + return 0.25 * area; } } } // namespace itk diff --git a/Modules/Core/Common/include/itkUnaryFunctorImageFilter.h b/Modules/Core/Common/include/itkUnaryFunctorImageFilter.h index 79f05dcbd9a..8dc4f41583f 100644 --- a/Modules/Core/Common/include/itkUnaryFunctorImageFilter.h +++ b/Modules/Core/Common/include/itkUnaryFunctorImageFilter.h @@ -81,6 +81,7 @@ class ITK_TEMPLATE_EXPORT UnaryFunctorImageFilter : public InPlaceImageFilter::GenerateOutputInf this->CallCopyInputRegionToOutputRegion(outputLargestPossibleRegion, inputPtr->GetLargestPossibleRegion()); outputPtr->SetLargestPossibleRegion(outputLargestPossibleRegion); - ImageToImageFilterDetail::ImageInformationCopier + const ImageToImageFilterDetail::ImageInformationCopier informationCopier; informationCopier(outputPtr, inputPtr); } @@ -88,8 +89,6 @@ UnaryFunctorImageFilter::DynamicThreadedGe ImageScanlineConstIterator inputIt(inputPtr, inputRegionForThread); ImageScanlineIterator outputIt(outputPtr, outputRegionForThread); - inputIt.GoToBegin(); - outputIt.GoToBegin(); while (!inputIt.IsAtEnd()) { while (!inputIt.IsAtEndOfLine()) diff --git a/Modules/Core/Common/include/itkValarrayImageContainer.h b/Modules/Core/Common/include/itkValarrayImageContainer.h index 7cf966d5ade..aed6e892656 100644 --- a/Modules/Core/Common/include/itkValarrayImageContainer.h +++ b/Modules/Core/Common/include/itkValarrayImageContainer.h @@ -69,6 +69,7 @@ class ITK_TEMPLATE_EXPORT ValarrayImageContainer * valarray constructors. These are for internal use only since * this is also an Object which must be constructed through the * "New()" routine. */ + /** @ITKStartGrouping */ ValarrayImageContainer() : ValarrayType() {} @@ -81,7 +82,7 @@ class ITK_TEMPLATE_EXPORT ValarrayImageContainer ValarrayImageContainer(const Self & r) : ValarrayType(r) {} - + /** @ITKEndGrouping */ public: /** Method for creation through the object factory. */ itkNewMacro(Self); @@ -90,10 +91,18 @@ class ITK_TEMPLATE_EXPORT ValarrayImageContainer itkOverrideGetNameOfClassMacro(ValarrayImageContainer); /** Index operator. This version can be an lvalue. */ - TElement & operator[](const ElementIdentifier id) { return this->ValarrayType::operator[](id); } + TElement & + operator[](const ElementIdentifier id) + { + return this->ValarrayType::operator[](id); + } /** Index operator. This version can only be an rvalue */ - const TElement & operator[](const ElementIdentifier id) const { return this->ValarrayType::operator[](id); } + const TElement & + operator[](const ElementIdentifier id) const + { + return this->ValarrayType::operator[](id); + } /** Return a pointer to the beginning of the buffer. This is used by * the image iterator class. */ @@ -104,10 +113,8 @@ class ITK_TEMPLATE_EXPORT ValarrayImageContainer { return &(this->ValarrayType::operator[](0)); } - else - { - return nullptr; - } + + return nullptr; } /** Get the number of elements currently stored in the container. */ diff --git a/Modules/Core/Common/include/itkVariableLengthVector.h b/Modules/Core/Common/include/itkVariableLengthVector.h index 6eece59fd6e..634441bf9f3 100644 --- a/Modules/Core/Common/include/itkVariableLengthVector.h +++ b/Modules/Core/Common/include/itkVariableLengthVector.h @@ -94,7 +94,8 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector /**\name Policies * The following Policies will be used by \c itk::VariableLengthVector::SetSize */ - //@{ + /** @ITKStartGrouping */ + /** \c VariableLengthVector empty base-class for allocation policies. * All Allocation Policies are expected to inherit from this empty base * class. @@ -113,7 +114,7 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector * This policy, when used from \c VariableLengthVector::SetSize(), always * implies that the previous internal buffer will be reallocated. Even if * enough memory was available. - * \return true (always) + * Returns true (always) * * \sa \c itk::VariableLengthVector::SetSize * \sa \c NeverReallocate @@ -138,8 +139,7 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector * * The typical use case of this policy is to make sure a \c * VariableLengthVector is not a proxy object. - * \return false (always) - * + * Returns false (always) * \pre oldSize == newSize, checked by assertion * * \sa \c itk::VariableLengthVector::SetSize @@ -152,10 +152,8 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector struct NeverReallocate : AllocateRootPolicy { bool - operator()(unsigned int newSize, unsigned int oldSize) const + operator()([[maybe_unused]] unsigned int newSize, [[maybe_unused]] unsigned int oldSize) const { - (void)newSize; - (void)oldSize; itkAssertInDebugAndIgnoreInReleaseMacro(newSize == oldSize && "SetSize is expected to never change the VariableLengthVector size..."); return true; @@ -304,7 +302,7 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector TValue2 * itkNotUsed(newBuffer)) const {} }; - //@} + /** @ITKEndGrouping */ /** The element type stored at each location in the Array. */ @@ -473,7 +471,8 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector * \post \c m_LetArrayManageMemory is true */ template - VariableLengthVector(VariableLengthVectorExpression const & rhs); + VariableLengthVector(const VariableLengthVectorExpression & rhs); + /** Assignment from an Expression Template vector. * \tparam TExpr1 Type of the left sub-expression * \tparam TExpr2 Type of the right sub-expression @@ -495,13 +494,13 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector */ template Self & - operator=(VariableLengthVectorExpression const & rhs); + operator=(const VariableLengthVectorExpression & rhs); /** Set all the elements of the array to the specified value. * \pre This function may be called on empty vectors, it's a no-op. */ void - Fill(TValue const & v); + Fill(const TValue & v); /** Converting assignment operator. * \note Ensures a String Exception Guarantee: resists to @@ -526,7 +525,7 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector // VLV vcref(v.GetDataPointer(), v.GetSize()); // ...; // v = vcref; - ElementIdentifier const N = v.Size(); + const ElementIdentifier N = v.Size(); this->SetSize(N, DontShrinkToFit(), DumpOldValues()); for (ElementIdentifier i = 0; i < N; ++i) { @@ -572,9 +571,10 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector * precision */ Self & - operator=(TValue const & v); + operator=(const TValue & v); /** Return the number of elements in the Array */ + /** @ITKStartGrouping */ unsigned int Size() const { @@ -590,11 +590,20 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector { return m_NumElements; } - + /** @ITKEndGrouping */ /** Return reference to the element at specified index. No range checking. */ - TValue & 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. */ - TValue const & operator[](unsigned int i) const { return this->m_Data[i]; } + const TValue & + operator[](unsigned int i) const + { + return this->m_Data[i]; + } /** Get one element */ const TValue & @@ -869,7 +878,7 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector */ template Self & - operator+=(VariableLengthVectorExpression const & rhs) + operator+=(const VariableLengthVectorExpression & rhs) { itkAssertInDebugAndIgnoreInReleaseMacro(rhs.Size() == Size()); for (ElementIdentifier i = 0; i < m_NumElements; ++i) @@ -890,7 +899,7 @@ class ITK_TEMPLATE_EXPORT VariableLengthVector */ template Self & - operator-=(VariableLengthVectorExpression const & rhs) + operator-=(const VariableLengthVectorExpression & rhs) { itkAssertInDebugAndIgnoreInReleaseMacro(rhs.Size() == Size()); for (ElementIdentifier i = 0; i < m_NumElements; ++i) @@ -1029,13 +1038,13 @@ template struct GetType { using Type = TExpr; + /** Fetches the i-th element from an array (expression). * \note the default unspecialized behaviour returns the input number \c v. */ static Type - Load(Type const & v, unsigned int idx) + Load(const Type & v, unsigned int itkNotUsed(idx)) { - (void)idx; return v; } }; @@ -1052,9 +1061,8 @@ struct GetType */ template inline std::enable_if_t, mpl::IsArray>::Value, unsigned int> -GetSize(TExpr1 const & lhs, TExpr2 const & rhs) +GetSize(const TExpr1 & lhs, [[maybe_unused]] const TExpr2 & rhs) { - (void)rhs; itkAssertInDebugAndIgnoreInReleaseMacro(lhs.Size() == rhs.Size()); return lhs.Size(); } @@ -1071,7 +1079,7 @@ GetSize(TExpr1 const & lhs, TExpr2 const & rhs) */ template inline std::enable_if_t, mpl::Not>>::Value, unsigned int> -GetSize(TExpr1 const & lhs, TExpr2 const & itkNotUsed(rhs)) +GetSize(const TExpr1 & lhs, const TExpr2 & itkNotUsed(rhs)) { return lhs.Size(); } @@ -1087,7 +1095,7 @@ GetSize(TExpr1 const & lhs, TExpr2 const & itkNotUsed(rhs)) */ template inline std::enable_if_t, mpl::Not>>::Value, unsigned int> -GetSize(TExpr1 const & itkNotUsed(lhs), TExpr2 const & rhs) +GetSize(const TExpr1 & itkNotUsed(lhs), const TExpr2 & rhs) { return rhs.Size(); } @@ -1097,7 +1105,7 @@ struct GetType> { using Type = T; static Type - Load(VariableLengthVector const & v, unsigned int idx) + Load(const VariableLengthVector & v, unsigned int idx) { return v[idx]; } @@ -1107,7 +1115,7 @@ struct GetType> { using Type = typename VariableLengthVectorExpression::ResType; static Type - Load(VariableLengthVectorExpression const & v, unsigned int idx) + Load(const VariableLengthVectorExpression & v, unsigned int idx) { return v[idx]; } @@ -1198,7 +1206,7 @@ struct CanBeDivided : mpl::And, mpl::IsNumber> template struct VariableLengthVectorExpression { - VariableLengthVectorExpression(TExpr1 const & lhs, TExpr2 const & rhs) + VariableLengthVectorExpression(const TExpr1 & lhs, const TExpr2 & rhs) : m_lhs(lhs) , m_rhs(rhs) { @@ -1231,7 +1239,8 @@ struct VariableLengthVectorExpression * * \c Load() is in charge of fetching the i-th element of the sub-expressions */ - ResType operator[](unsigned int idx) const + ResType + operator[](unsigned int idx) const { itkAssertInDebugAndIgnoreInReleaseMacro(idx < Size()); return TBinaryOp::Apply(Details::GetType::Load(m_lhs, idx), Details::GetType::Load(m_rhs, idx)); @@ -1246,8 +1255,8 @@ struct VariableLengthVectorExpression GetSquaredNorm() const; private: - TExpr1 const & m_lhs; - TExpr2 const & m_rhs; + const TExpr1 & m_lhs; + const TExpr2 & m_rhs; }; /** Addition involving a \c VariableLengthVector. @@ -1262,7 +1271,7 @@ struct VariableLengthVectorExpression template inline std::enable_if_t::Value, VariableLengthVectorExpression> -operator+(TExpr1 const & lhs, TExpr2 const & rhs) +operator+(const TExpr1 & lhs, const TExpr2 & rhs) { return VariableLengthVectorExpression(lhs, rhs); } @@ -1279,7 +1288,7 @@ operator+(TExpr1 const & lhs, TExpr2 const & rhs) template inline std::enable_if_t::Value, VariableLengthVectorExpression> -operator-(TExpr1 const & lhs, TExpr2 const & rhs) +operator-(const TExpr1 & lhs, const TExpr2 & rhs) { return VariableLengthVectorExpression(lhs, rhs); } @@ -1295,7 +1304,7 @@ operator-(TExpr1 const & lhs, TExpr2 const & rhs) template inline std::enable_if_t::Value, VariableLengthVectorExpression> -operator*(TExpr1 const & lhs, TExpr2 const & rhs) +operator*(const TExpr1 & lhs, const TExpr2 & rhs) { return VariableLengthVectorExpression(lhs, rhs); } @@ -1310,7 +1319,7 @@ operator*(TExpr1 const & lhs, TExpr2 const & rhs) template inline std::enable_if_t::Value, VariableLengthVectorExpression> -operator/(TExpr1 const & lhs, TExpr2 const & rhs) +operator/(const TExpr1 & lhs, const TExpr2 & rhs) { return VariableLengthVectorExpression(lhs, rhs); } @@ -1320,7 +1329,7 @@ operator/(TExpr1 const & lhs, TExpr2 const & rhs) */ template std::ostream & -operator<<(std::ostream & os, VariableLengthVectorExpression const & v) +operator<<(std::ostream & os, const VariableLengthVectorExpression & v) { os << '['; if (v.Size() != 0) @@ -1341,7 +1350,7 @@ operator<<(std::ostream & os, VariableLengthVectorExpression inline std::enable_if_t::Value, typename TExpr::RealValueType> -GetNorm(TExpr const & v) +GetNorm(const TExpr & v) { return static_cast(std::sqrt(static_cast(GetSquaredNorm(v)))); } @@ -1353,7 +1362,7 @@ GetNorm(TExpr const & v) */ template inline std::enable_if_t::Value, typename TExpr::RealValueType> -GetSquaredNorm(TExpr const & v) +GetSquaredNorm(const TExpr & v) { using RealValueType = typename TExpr::RealValueType; RealValueType sum = 0.0; @@ -1366,7 +1375,7 @@ GetSquaredNorm(TExpr const & v) } /**\name Serialization */ -//@{ + /** Serialization of \c VariableLengthVector * \relates itk::VariableLengthVector */ @@ -1389,10 +1398,9 @@ operator<<(std::ostream & os, const VariableLengthVector & arr) os << ']'; return os; } -//@} /**\name Standard compliance functions */ -//@{ + /** \c swap() overload for \c VariableLengthVector * \throw None * \relates itk::VariableLengthVector @@ -1416,7 +1424,6 @@ swap(VariableLengthVector & l_, VariableLengthVector & r_) noexcept { l_.Swap(r_); } -//@} } // namespace itk diff --git a/Modules/Core/Common/include/itkVariableLengthVector.hxx b/Modules/Core/Common/include/itkVariableLengthVector.hxx index 53af7c37327..7f5653ae36c 100644 --- a/Modules/Core/Common/include/itkVariableLengthVector.hxx +++ b/Modules/Core/Common/include/itkVariableLengthVector.hxx @@ -124,7 +124,7 @@ VariableLengthVector::operator=(Self && v) noexcept template template VariableLengthVector::VariableLengthVector( - VariableLengthVectorExpression const & + const VariableLengthVectorExpression & rhs) { m_NumElements = rhs.Size(); @@ -142,10 +142,10 @@ template template VariableLengthVector & VariableLengthVector::operator=( - VariableLengthVectorExpression const & + const VariableLengthVectorExpression & rhs) { - ElementIdentifier const N = rhs.Size(); + const ElementIdentifier N = rhs.Size(); this->SetSize(N, DontShrinkToFit(), DumpOldValues()); for (ElementIdentifier i = 0; i < N; ++i) { @@ -286,7 +286,7 @@ VariableLengthVector::SetSize(unsigned int sz, TReallocatePolicy realloc template void -VariableLengthVector::Fill(TValue const & v) +VariableLengthVector::Fill(const TValue & v) { itkAssertInDebugAndIgnoreInReleaseMacro(m_NumElements == 0 || (m_NumElements > 0 && m_Data != nullptr)); // VC++ version of std::fill_n() expects the output iterator to be valid @@ -302,7 +302,7 @@ VariableLengthVector::operator=(const Self & v) // - the operator already resists self assignment through a strong exception // guarantee // - the test becomes a pessimization as we never write "v = v;". - ElementIdentifier const N = v.Size(); + const ElementIdentifier N = v.Size(); this->SetSize(N, DontShrinkToFit(), DumpOldValues()); // VC++ version of std::copy expects the input range to be valid, and the @@ -324,7 +324,7 @@ inline VariableLengthVector & VariableLengthVector::FastAssign(const Self & v) { itkAssertInDebugAndIgnoreInReleaseMacro(this->m_LetArrayManageMemory); - ElementIdentifier const N = v.Size(); + const ElementIdentifier N = v.Size(); itkAssertInDebugAndIgnoreInReleaseMacro(N > 0); itkAssertInDebugAndIgnoreInReleaseMacro(N == this->Size()); // Redundant precondition checks @@ -338,7 +338,7 @@ VariableLengthVector::FastAssign(const Self & v) template VariableLengthVector & -VariableLengthVector::operator=(TValue const & v) +VariableLengthVector::operator=(const TValue & v) { this->Fill(v); return *this; @@ -350,7 +350,7 @@ VariableLengthVector::operator-() { for (ElementIdentifier i = 0; i < m_NumElements; ++i) { - m_Data[i] = -m_Data[i]; + m_Data[i] *= -1; } return *this; } diff --git a/Modules/Core/Common/include/itkVariableSizeMatrix.h b/Modules/Core/Common/include/itkVariableSizeMatrix.h index ef302d781cf..f3ee84e4e7d 100644 --- a/Modules/Core/Common/include/itkVariableSizeMatrix.h +++ b/Modules/Core/Common/include/itkVariableSizeMatrix.h @@ -56,10 +56,12 @@ class ITK_TEMPLATE_EXPORT VariableSizeMatrix using InternalMatrixType = vnl_matrix; /** Matrix by Vector multiplication. */ - Array operator*(const Array & vect) const; + Array + operator*(const Array & vect) const; /** Matrix by Matrix multiplication. */ - Self operator*(const Self & matrix) const; + Self + operator*(const Self & matrix) const; /** Matrix addition. */ Self @@ -80,7 +82,8 @@ class ITK_TEMPLATE_EXPORT VariableSizeMatrix operator-(); /** Matrix by vnl_matrix multiplication. */ - vnl_matrix operator*(const vnl_matrix & matrix) const; + vnl_matrix + operator*(const vnl_matrix & matrix) const; /** Matrix by Matrix multiplication. */ void @@ -91,7 +94,8 @@ class ITK_TEMPLATE_EXPORT VariableSizeMatrix operator*=(const vnl_matrix & matrix); /** Matrix by vnl_vector multiplication. */ - vnl_vector operator*(const vnl_vector & vc) const; + vnl_vector + operator*(const vnl_vector & vc) const; /** Matrix by scalar multiplication. */ void @@ -101,7 +105,8 @@ class ITK_TEMPLATE_EXPORT VariableSizeMatrix } /** Matrix by scalar multiplication. */ - Self operator*(const T & value) const + Self + operator*(const T & value) const { Self result(*this); @@ -141,10 +146,18 @@ class ITK_TEMPLATE_EXPORT VariableSizeMatrix } /** Return a row of the matrix. */ - inline T * operator[](unsigned int i) { return m_Matrix[i]; } + inline T * + operator[](unsigned int i) + { + return m_Matrix[i]; + } /** Return a row of the matrix. */ - inline const T * operator[](unsigned int i) const { return m_Matrix[i]; } + inline const T * + operator[](unsigned int i) const + { + return m_Matrix[i]; + } /** Return the matrix. */ inline InternalMatrixType & diff --git a/Modules/Core/Common/include/itkVariableSizeMatrix.hxx b/Modules/Core/Common/include/itkVariableSizeMatrix.hxx index d6ce69e35a9..d605a3f7b67 100644 --- a/Modules/Core/Common/include/itkVariableSizeMatrix.hxx +++ b/Modules/Core/Common/include/itkVariableSizeMatrix.hxx @@ -31,10 +31,11 @@ VariableSizeMatrix::VariableSizeMatrix(unsigned int rows, unsigned int cols) * Product by a Vector */ template -Array VariableSizeMatrix::operator*(const Array & vect) const +Array +VariableSizeMatrix::operator*(const Array & vect) const { - unsigned int rows = this->Rows(); - unsigned int cols = this->Cols(); + const unsigned int rows = this->Rows(); + const unsigned int cols = this->Cols(); if (vect.Size() != cols) { @@ -59,7 +60,8 @@ Array VariableSizeMatrix::operator*(const Array & vect) const * Product by a matrix */ template -VariableSizeMatrix VariableSizeMatrix::operator*(const Self & matrix) const +VariableSizeMatrix +VariableSizeMatrix::operator*(const Self & matrix) const { if (this->Cols() != matrix.Rows()) { @@ -178,7 +180,7 @@ VariableSizeMatrix::operator-() { for (unsigned int c = 0; c < this->Cols(); ++c) { - m_Matrix(r, c) = -m_Matrix(r, c); + m_Matrix(r, c) *= -1; } } return *this; @@ -188,7 +190,8 @@ VariableSizeMatrix::operator-() * Product by a vnl_matrix */ template -vnl_matrix VariableSizeMatrix::operator*(const vnl_matrix & matrix) const +vnl_matrix +VariableSizeMatrix::operator*(const vnl_matrix & matrix) const { return m_Matrix * matrix; } @@ -217,7 +220,8 @@ VariableSizeMatrix::operator*=(const vnl_matrix & matrix) * Product by a vnl_vector */ template -vnl_vector VariableSizeMatrix::operator*(const vnl_vector & vc) const +vnl_vector +VariableSizeMatrix::operator*(const vnl_vector & vc) const { return m_Matrix * vc; } diff --git a/Modules/Core/Common/include/itkVector.h b/Modules/Core/Common/include/itkVector.h index 8a5e1cdf8af..de7684d685b 100644 --- a/Modules/Core/Common/include/itkVector.h +++ b/Modules/Core/Common/include/itkVector.h @@ -111,9 +111,10 @@ class ITK_TEMPLATE_EXPORT Vector : public FixedArray /** Constructor to initialize entire vector to one value. * \warning Not intended to convert a scalar value into * a Vector filled with that value. - * \deprecated */ + * Deprecated */ Vector(const ValueType & r); #else + /** Constructor to initialize entire vector to one value, * if explicitly invoked. */ explicit Vector(const ValueType & r); @@ -123,6 +124,7 @@ class ITK_TEMPLATE_EXPORT Vector : public FixedArray #endif /** Pass-through constructor for the Array base class. */ + /** @ITKStartGrouping */ template Vector(const Vector & r) : BaseArray(r) @@ -134,6 +136,7 @@ class ITK_TEMPLATE_EXPORT Vector : public FixedArray Vector(const TVectorValueType r[Dimension]) : BaseArray(r) {} + /** @ITKEndGrouping */ /** Explicit constructor for std::array. */ explicit Vector(const std::array & stdArray) @@ -199,11 +202,13 @@ class ITK_TEMPLATE_EXPORT Vector : public FixedArray /** Vector operator*. Performs the inner product of two vectors. * this is also known as the scalar product. */ - ValueType operator*(const Self & other) const; + ValueType + operator*(const Self & other) const; /** Scalar operator*. Scale the elements of a vector by a scalar. * Return a new vector. */ - inline Self operator*(const ValueType & value) const + inline Self + operator*(const ValueType & value) const { Self result; @@ -241,7 +246,7 @@ class ITK_TEMPLATE_EXPORT Vector : public FixedArray ITK_UNEQUAL_OPERATOR_MEMBER_FUNCTION(Self); - /** Returns the Euclidean Norm of the vector */ + /** Returns the Euclidean Norm of the vector (also referred to as its "magnitude"). */ RealValueType GetNorm() const; @@ -269,9 +274,9 @@ class ITK_TEMPLATE_EXPORT Vector : public FixedArray /** Copy from another Vector with a different representation type. * Casting is done with C-Like rules */ - template + template void - CastFrom(const Vector & pa) + CastFrom(const Vector & pa) { for (unsigned int i = 0; i < VVectorDimension; ++i) { @@ -279,13 +284,13 @@ class ITK_TEMPLATE_EXPORT Vector : public FixedArray } } - template - operator Vector() + template + operator Vector() { - Vector r; + Vector r; for (unsigned int i = 0; i < VVectorDimension; ++i) { - r[i] = static_cast((*this)[i]); + r[i] = static_cast((*this)[i]); } return r; } @@ -294,7 +299,8 @@ class ITK_TEMPLATE_EXPORT Vector : public FixedArray /** Premultiply Operator for product of a vector and a scalar. * Vector< T, N > = T * Vector< T,N > */ template -inline Vector operator*(const T & scalar, const Vector & v) +inline Vector +operator*(const T & scalar, const Vector & v) { return v.operator*(scalar); } @@ -321,7 +327,7 @@ ITKCommon_EXPORT Vector template inline void -swap(Vector & a, Vector & b) +swap(Vector & a, Vector & b) noexcept { a.swap(b); } diff --git a/Modules/Core/Common/include/itkVector.hxx b/Modules/Core/Common/include/itkVector.hxx index 8d2fca35141..c7184fb778e 100644 --- a/Modules/Core/Common/include/itkVector.hxx +++ b/Modules/Core/Common/include/itkVector.hxx @@ -103,7 +103,7 @@ template auto Vector::GetSquaredNorm() const -> RealValueType { - typename NumericTraits::AccumulateType sum = T{}; + T sum{}; for (unsigned int i = 0; i < TVectorDimension; ++i) { const RealValueType value = (*this)[i]; @@ -167,7 +167,7 @@ std::ostream & operator<<(std::ostream & os, const Vector & vct) { os << '['; - if (TVectorDimension == 1) + if constexpr (TVectorDimension == 1) { os << vct[0]; } @@ -195,9 +195,10 @@ operator>>(std::istream & is, Vector & vct) } template -typename Vector::ValueType Vector::operator*(const Self & other) const +typename Vector::ValueType +Vector::operator*(const Self & other) const { - typename NumericTraits::AccumulateType value = T{}; + T value{}; for (unsigned int i = 0; i < TVectorDimension; ++i) { value += (*this)[i] * other[i]; diff --git a/Modules/Core/Common/include/itkVectorContainer.h b/Modules/Core/Common/include/itkVectorContainer.h index 5e217d16d17..5886bb7008c 100644 --- a/Modules/Core/Common/include/itkVectorContainer.h +++ b/Modules/Core/Common/include/itkVectorContainer.h @@ -21,11 +21,14 @@ #include "itkObject.h" #include "itkObjectFactory.h" +#include // For is_void_v. #include #include namespace itk { +namespace detail +{ /** \class VectorContainer * \brief Define a front-end to the STL "vector" container that conforms to the * IndexedContainerInterface. @@ -162,8 +165,16 @@ class ITK_TEMPLATE_EXPORT VectorContainer : m_Pos(d) , m_Iter(i) {} - Iterator & operator*() { return *this; } - Iterator * operator->() { return this; } + Iterator & + operator*() + { + return *this; + } + Iterator * + operator->() + { + return this; + } Iterator & operator++() { @@ -244,7 +255,7 @@ class ITK_TEMPLATE_EXPORT VectorContainer m_Pos += n; m_Iter += n; return *this; - }; + } /** Get the index into the VectorContainer associated with this iterator. */ @@ -290,8 +301,16 @@ class ITK_TEMPLATE_EXPORT VectorContainer : m_Pos(r.m_Pos) , m_Iter(r.m_Iter) {} - ConstIterator & operator*() { return *this; } - ConstIterator * operator->() { return this; } + ConstIterator & + operator*() + { + return *this; + } + ConstIterator * + operator->() + { + return this; + } ConstIterator & operator++() { @@ -335,7 +354,7 @@ class ITK_TEMPLATE_EXPORT VectorContainer m_Pos += n; m_Iter += n; return *this; - }; + } difference_type operator-(const ConstIterator & r) const @@ -388,6 +407,7 @@ class ITK_TEMPLATE_EXPORT VectorContainer { return static_cast(m_Pos); } + /** Get the value at this iterator's location in the VectorContainer. */ const_reference Value() const @@ -530,7 +550,8 @@ class ITK_TEMPLATE_EXPORT VectorContainer * with other containers in the toolkit. */ void - Squeeze(); + Squeeze() + {} /** * Clear the elements. The final size will be zero. @@ -542,6 +563,7 @@ class ITK_TEMPLATE_EXPORT VectorContainer /** Provide pass-through constructors corresponding to all the STL * vector constructors. These are for internal use only since this is also * an Object which must be constructed through the "New()" routine. */ + /** @ITKStartGrouping */ VectorContainer() = default; VectorContainer(size_type n) : Object() @@ -560,7 +582,35 @@ class ITK_TEMPLATE_EXPORT VectorContainer : Object() , VectorType(first, last) {} + /** @ITKEndGrouping */ }; +} // namespace detail + +/** Alias template, allowing to use `itk::VectorContainer` without having to explicitly specify its + * `ElementIdentifier` type. + * + * The template parameters `T1` and `T2` allow specifying the index type and the element type, as follows: + * + * \tparam T1 The index type OR (when `T2` is `void`) the element type. + * + * \tparam T2 The element type OR `void`. When `T2` is `void`, the element type is specified by the first template + * argument (T1), and the index type will be `SizeValueType`. + */ +template +using VectorContainer = detail::VectorContainer, SizeValueType, T1>, + std::conditional_t, T1, T2>>; + + +/** Makes a VectorContainer that has a copy of the specified `std::vector`. */ +template +auto +MakeVectorContainer(std::vector stdVector) +{ + auto vectorContainer = VectorContainer::New(); + vectorContainer->CastToSTLContainer() = std::move(stdVector); + return vectorContainer; +} + } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION diff --git a/Modules/Core/Common/include/itkVectorContainer.hxx b/Modules/Core/Common/include/itkVectorContainer.hxx index 6a658639036..570c47ef006 100644 --- a/Modules/Core/Common/include/itkVectorContainer.hxx +++ b/Modules/Core/Common/include/itkVectorContainer.hxx @@ -20,7 +20,7 @@ #include "itkNumericTraits.h" -namespace itk +namespace itk::detail { template @@ -178,11 +178,6 @@ VectorContainer::Reserve(ElementIdentifier sz) { this->CreateIndex(sz - 1); } - -template -void -VectorContainer::Squeeze() -{} -} // end namespace itk +} // namespace itk::detail #endif diff --git a/Modules/Core/Common/include/itkVectorImage.h b/Modules/Core/Common/include/itkVectorImage.h index 30a52652555..16cf9344679 100644 --- a/Modules/Core/Common/include/itkVectorImage.h +++ b/Modules/Core/Common/include/itkVectorImage.h @@ -181,7 +181,7 @@ class ITK_TEMPLATE_EXPORT VectorImage : public ImageBase \endcode * * \sa Image::Rebind - * \deprecated Use template alias RebindImageType instead + * Deprecated: Use template alias RebindImageType instead */ template struct Rebind @@ -223,7 +223,7 @@ class ITK_TEMPLATE_EXPORT VectorImage : public ImageBase void SetPixel(const IndexType & index, const PixelType & value) { - OffsetValueType offset = m_VectorLength * this->FastComputeOffset(index); + const OffsetValueType offset = m_VectorLength * this->FastComputeOffset(index); for (VectorLengthType i = 0; i < m_VectorLength; ++i) { @@ -239,7 +239,7 @@ class ITK_TEMPLATE_EXPORT VectorImage : public ImageBase const PixelType GetPixel(const IndexType & index) const { - OffsetValueType offset = m_VectorLength * this->FastComputeOffset(index); + const OffsetValueType offset = m_VectorLength * this->FastComputeOffset(index); // Do not create a local for this method, to use return value // optimization. @@ -258,7 +258,7 @@ class ITK_TEMPLATE_EXPORT VectorImage : public ImageBase PixelType GetPixel(const IndexType & index) { - OffsetValueType offset = m_VectorLength * this->FastComputeOffset(index); + const OffsetValueType offset = m_VectorLength * this->FastComputeOffset(index); // Correctness of this method relies of return value optimization, do // not create a local for the value. @@ -274,16 +274,25 @@ class ITK_TEMPLATE_EXPORT VectorImage : public ImageBase * * For efficiency, this function does not check that the * image has actually been allocated yet. */ - PixelType operator[](const IndexType & index) { return this->GetPixel(index); } + PixelType + operator[](const IndexType & index) + { + return this->GetPixel(index); + } /** \brief Access a pixel. * * For efficiency, this function does not check that the * image has actually been allocated yet. */ - const PixelType operator[](const IndexType & index) const { return this->GetPixel(index); } + const PixelType + operator[](const IndexType & index) const + { + return this->GetPixel(index); + } /** Return a pointer to the beginning of the buffer. This is used by * the image iterator class. */ + /** @ITKStartGrouping */ InternalPixelType * GetBufferPointer() { @@ -294,7 +303,7 @@ class ITK_TEMPLATE_EXPORT VectorImage : public ImageBase { return m_Buffer ? m_Buffer->GetBufferPointer() : nullptr; } - + /** @ITKEndGrouping */ /** Return a pointer to the container. */ PixelContainer * GetPixelContainer() @@ -356,9 +365,10 @@ class ITK_TEMPLATE_EXPORT VectorImage : public ImageBase } /** Set/Get macros for the length of each vector in the vector image */ + /** @ITKStartGrouping */ itkSetMacro(VectorLength, VectorLengthType); itkGetConstReferenceMacro(VectorLength, VectorLengthType); - + /** @ITKEndGrouping */ /** Get/Set the number of components each pixel has, ie the VectorLength */ unsigned int GetNumberOfComponentsPerPixel() const override; diff --git a/Modules/Core/Common/include/itkVersor.h b/Modules/Core/Common/include/itkVersor.h index 5763fcfdaf1..d07036eff73 100644 --- a/Modules/Core/Common/include/itkVersor.h +++ b/Modules/Core/Common/include/itkVersor.h @@ -37,6 +37,8 @@ namespace itk * versor. For this reason, addition is not defined in this class, even * though it is a valid operation between quaternions. * + * \note Its special member functions are implicitly defaulted, following the C++ "Rule of Zero". + * * \ingroup Geometry * \ingroup DataRepresentation * @@ -108,17 +110,6 @@ class ITK_TEMPLATE_EXPORT Versor void Set(T x, T y, T z, T w); - /** Default constructor creates a null versor - * (representing 0 degrees rotation). */ - Versor() = default; - - /** Copy constructor. */ - Versor(const Self & v); - - /** Assignment operator =. Copy the versor argument. */ - Self & - operator=(const Self & v); - /** Composition operator *=. Compose the current versor * with the operand and store the result in the current * versor. */ @@ -158,7 +149,8 @@ class ITK_TEMPLATE_EXPORT Versor /** Versor operator*. Performs the composition of two versors. * this operation is NOT commutative. */ - Self operator*(const Self & v) const; + Self + operator*(const Self & v) const; /** Versor operator/. Performs the division of two versors. */ Self @@ -309,6 +301,7 @@ class ITK_TEMPLATE_EXPORT Versor private: /** use different epsilon for float and double */ + /** @ITKStartGrouping */ static inline ValueType Epsilon(double *) { @@ -324,6 +317,7 @@ class ITK_TEMPLATE_EXPORT Versor { return Epsilon((ValueType *)nullptr); } + /** @ITKEndGrouping */ /** Component parallel to x axis. */ ValueType m_X{}; diff --git a/Modules/Core/Common/include/itkVersor.hxx b/Modules/Core/Common/include/itkVersor.hxx index ba4071aa3d5..d4c0cb7c821 100644 --- a/Modules/Core/Common/include/itkVersor.hxx +++ b/Modules/Core/Common/include/itkVersor.hxx @@ -24,26 +24,6 @@ namespace itk { -template -Versor::Versor(const Self & v) -{ - m_X = v.m_X; - m_Y = v.m_Y; - m_Z = v.m_Z; - m_W = v.m_W; -} - -template -Versor & -Versor::operator=(const Self & v) -{ - m_X = v.m_X; - m_Y = v.m_Y; - m_Z = v.m_Z; - m_W = v.m_W; - return *this; -} - template void Versor::SetIdentity() @@ -79,7 +59,8 @@ Versor::operator*=(const Self & v) } template -Versor Versor::operator*(const Self & v) const +Versor +Versor::operator*(const Self & v) const { Self result; @@ -127,11 +108,11 @@ bool Versor::operator==(const Self & v) const { // Evaluate the quaternion ratio between them - Self ratio = *this * v.GetReciprocal(); + const Self ratio = *this * v.GetReciprocal(); const typename itk::NumericTraits::AccumulateType square = ratio.m_W * ratio.m_W; - const double epsilon = 1e-300; + constexpr double epsilon = 1e-300; if (itk::Math::abs(1.0f - square) < epsilon) { @@ -319,7 +300,7 @@ template void Versor::Set(const MatrixType & mat) { - // const double epsilon = 1e-30; + // constexpr double epsilon = 1e-30; // 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 matrices for rotations diff --git a/Modules/Core/Common/include/itkVertexCell.h b/Modules/Core/Common/include/itkVertexCell.h index 9b5f1d7b10a..102b0812503 100644 --- a/Modules/Core/Common/include/itkVertexCell.h +++ b/Modules/Core/Common/include/itkVertexCell.h @@ -29,11 +29,6 @@ namespace itk /** \class VertexCell * \brief Represents a single vertex for a Mesh. * - * \tparam TPixelType The type associated with a point, cell, or boundary - * for use in storing its data. - * - * \tparam TCellTraits Type information of mesh containing cell. - * * \ingroup MeshObjects * \ingroup ITKCommon */ @@ -45,9 +40,10 @@ class ITK_TEMPLATE_EXPORT VertexCell : public TCellInterface ITK_DISALLOW_COPY_AND_MOVE(VertexCell); /** Standard class type aliases. */ + /** @ITKStartGrouping */ itkCellCommonTypedefs(VertexCell); itkCellInheritedTypedefs(TCellInterface); - + /** @ITKEndGrouping */ /** \see LightObject::GetNameOfClass() */ itkOverrideGetNameOfClassMacro(VertexCell); @@ -58,6 +54,7 @@ class ITK_TEMPLATE_EXPORT VertexCell : public TCellInterface // Standard CellInterface /** Implement the standard CellInterface. */ + /** @ITKStartGrouping */ CellGeometryEnum GetType() const override { @@ -65,7 +62,7 @@ class ITK_TEMPLATE_EXPORT VertexCell : public TCellInterface } void MakeCopy(CellAutoPointer &) const override; - + /** @ITKEndGrouping */ /** Get the topological dimension of this cell. */ unsigned int GetDimension() const override; @@ -129,10 +126,10 @@ class ITK_TEMPLATE_EXPORT VertexCell : public TCellInterface /** Evaluate the position of a given point */ bool - EvaluatePosition(CoordRepType *, + EvaluatePosition(CoordinateType *, PointsContainer *, - CoordRepType *, - CoordRepType[], + CoordinateType *, + CoordinateType[], double *, InterpolationWeightType *) override; diff --git a/Modules/Core/Common/include/itkVertexCell.hxx b/Modules/Core/Common/include/itkVertexCell.hxx index 544d5184755..b5bae4f2c09 100644 --- a/Modules/Core/Common/include/itkVertexCell.hxx +++ b/Modules/Core/Common/include/itkVertexCell.hxx @@ -131,10 +131,10 @@ VertexCell::GetPointId() -> PointIdentifier template bool -VertexCell::EvaluatePosition(CoordRepType * x, +VertexCell::EvaluatePosition(CoordinateType * x, PointsContainer * points, - CoordRepType * closestPoint, - CoordRepType pcoord[], + CoordinateType * closestPoint, + CoordinateType pcoord[], double * minDist2, InterpolationWeightType * weights) { @@ -174,14 +174,12 @@ VertexCell::EvaluatePosition(CoordRepType * x, } return true; } - else + + if (pcoord) { - if (pcoord) - { - pcoord[0] = -10.0; - } - return false; + pcoord[0] = -10.0; } + return false; } } // end namespace itk diff --git a/Modules/Core/Common/include/itkWeakPointer.h b/Modules/Core/Common/include/itkWeakPointer.h index ca9320c1836..45aa1a56b5b 100644 --- a/Modules/Core/Common/include/itkWeakPointer.h +++ b/Modules/Core/Common/include/itkWeakPointer.h @@ -63,7 +63,11 @@ class WeakPointer {} /** Overload operator ->. */ - ObjectType * operator->() const { return m_Pointer; } + ObjectType * + operator->() const + { + return m_Pointer; + } /** Return pointer to object. */ operator ObjectType *() const { return m_Pointer; } diff --git a/Modules/Core/Common/include/itkWin32OutputWindow.h b/Modules/Core/Common/include/itkWin32OutputWindow.h index 97fbd874667..aa880c7a346 100644 --- a/Modules/Core/Common/include/itkWin32OutputWindow.h +++ b/Modules/Core/Common/include/itkWin32OutputWindow.h @@ -73,7 +73,7 @@ class ITKCommon_EXPORT Win32OutputWindow : public OutputWindow DisplayText(const char *) override; static LRESULT APIENTRY - WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); + WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); protected: Win32OutputWindow() = default; diff --git a/Modules/Core/Common/include/itkZeroFluxNeumannBoundaryCondition.hxx b/Modules/Core/Common/include/itkZeroFluxNeumannBoundaryCondition.hxx index b2f07b1ed1d..d5f7e7f5cc3 100644 --- a/Modules/Core/Common/include/itkZeroFluxNeumannBoundaryCondition.hxx +++ b/Modules/Core/Common/include/itkZeroFluxNeumannBoundaryCondition.hxx @@ -123,7 +123,7 @@ ZeroFluxNeumannBoundaryCondition::GetInputRequestedRe if (requestIndex[i] < outputIndex[i]) { // How much do we need to adjust - OffsetValueType crop = outputIndex[i] - requestIndex[i]; + const OffsetValueType crop = outputIndex[i] - requestIndex[i]; // Adjust the start index and the size of the current region requestIndex[i] += crop; @@ -134,8 +134,8 @@ ZeroFluxNeumannBoundaryCondition::GetInputRequestedRe outputIndex[i] + static_cast(outputSize[i])) { // How much do we need to adjust - OffsetValueType crop = requestIndex[i] + static_cast(requestSize[i]) - outputIndex[i] - - static_cast(outputSize[i]); + const OffsetValueType crop = requestIndex[i] + static_cast(requestSize[i]) - outputIndex[i] - + static_cast(outputSize[i]); // Adjust the size requestSize[i] -= static_cast(crop); @@ -143,7 +143,7 @@ ZeroFluxNeumannBoundaryCondition::GetInputRequestedRe } } - RegionType inputRequestedRegion(requestIndex, requestSize); + const RegionType inputRequestedRegion(requestIndex, requestSize); return inputRequestedRegion; } @@ -155,16 +155,16 @@ ZeroFluxNeumannBoundaryCondition::GetPixel(const Inde const TInputImage * image) const -> OutputPixelType { - RegionType imageRegion = image->GetLargestPossibleRegion(); - IndexType imageIndex = imageRegion.GetIndex(); - SizeType imageSize = imageRegion.GetSize(); + const RegionType imageRegion = image->GetLargestPossibleRegion(); + IndexType imageIndex = imageRegion.GetIndex(); + SizeType imageSize = imageRegion.GetSize(); IndexType lookupIndex; for (unsigned int i = 0; i < ImageDimension; ++i) { - IndexValueType lowerIndex = imageIndex[i]; - IndexValueType upperIndex = imageIndex[i] + static_cast(imageSize[i]) - 1; + const IndexValueType lowerIndex = imageIndex[i]; + const IndexValueType upperIndex = imageIndex[i] + static_cast(imageSize[i]) - 1; if (index[i] < lowerIndex) { lookupIndex[i] = lowerIndex; diff --git a/Modules/Core/Common/include/itkZeroFluxNeumannImageNeighborhoodPixelAccessPolicy.h b/Modules/Core/Common/include/itkZeroFluxNeumannImageNeighborhoodPixelAccessPolicy.h index 4f1edf0ae9d..0237e55f302 100644 --- a/Modules/Core/Common/include/itkZeroFluxNeumannImageNeighborhoodPixelAccessPolicy.h +++ b/Modules/Core/Common/include/itkZeroFluxNeumannImageNeighborhoodPixelAccessPolicy.h @@ -67,9 +67,9 @@ class ZeroFluxNeumannImageNeighborhoodPixelAccessPolicy final GetClampedIndexValue(const IndexValueType indexValue, const ImageSizeValueType imageSizeValue) noexcept { return (indexValue <= 0) ? 0 - : (static_cast(indexValue) < imageSizeValue) - ? indexValue - : static_cast(imageSizeValue - 1); + : (static_cast(indexValue) < imageSizeValue) + ? indexValue + : static_cast(imageSizeValue - 1); } // Private helper function. Calculates and returns the index value of the diff --git a/Modules/Core/Common/itk-module.cmake b/Modules/Core/Common/itk-module.cmake index 499165bcc88..89bc7c93333 100644 --- a/Modules/Core/Common/itk-module.cmake +++ b/Modules/Core/Common/itk-module.cmake @@ -17,12 +17,12 @@ itk_module( ENABLE_SHARED DEPENDS ITKEigen3 + ITKVNL ${ITKCOMMON_TBB_DEPENDS} PRIVATE_DEPENDS ITKDoubleConversion COMPILE_DEPENDS ITKKWSys - ITKVNLInstantiation TEST_DEPENDS ITKTestKernel ITKMesh diff --git a/Modules/Core/Common/src/CMakeLists.txt b/Modules/Core/Common/src/CMakeLists.txt index 74f031b08d1..dd20f78a68b 100644 --- a/Modules/Core/Common/src/CMakeLists.txt +++ b/Modules/Core/Common/src/CMakeLists.txt @@ -145,7 +145,13 @@ set(ITKCommon_SRCS itkFrustumSpatialFunction.cxx itkObjectStore.cxx itkGaussianDerivativeOperator.cxx - itkSpatialOrientation.cxx) + itkSpatialOrientation.cxx + itkAnatomicalOrientation.cxx +) + +if(ITK_WRAP_PYTHON) + list(APPEND ITKCommon_SRCS itkPyCommand.cxx) +endif() if(WIN32) list(APPEND ITKCommon_SRCS itkWin32OutputWindow.cxx) @@ -192,8 +198,7 @@ itk_module_add_library(ITKCommon ${ITKCommon_SRCS}) target_link_libraries( ITKCommon LINK_PUBLIC - itksys - ITKVNLInstantiation) + itksys) if(UNIX) target_link_libraries( diff --git a/Modules/Core/Common/src/itkAnatomicalOrientation.cxx b/Modules/Core/Common/src/itkAnatomicalOrientation.cxx new file mode 100644 index 00000000000..104525ea032 --- /dev/null +++ b/Modules/Core/Common/src/itkAnatomicalOrientation.cxx @@ -0,0 +1,327 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * 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 + * + * https://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 "itkAnatomicalOrientation.h" +#ifndef ITK_FUTURE_LEGACY_REMOVE +# include "itkSpatialOrientationAdapter.h" +#endif + +namespace itk +{ + + +#ifndef ITK_FUTURE_LEGACY_REMOVE +AnatomicalOrientation::AnatomicalOrientation(LegacyOrientationType legacyOrientation) + : AnatomicalOrientation(SpatialOrientationAdapter().ToDirectionCosines(legacyOrientation)) +{ + assert(uint32_t(legacyOrientation) == uint32_t(m_Value)); +} +#endif + + +std::string +AnatomicalOrientation::GetAsPositiveStringEncoding() const +{ + + // a lambda function to convert a CoordinateEnum to a char + auto enumAsChar = [](CoordinateEnum coord) -> char { + switch (coord) + { + case CoordinateEnum::RightToLeft: + return 'L'; + case CoordinateEnum::LeftToRight: + return 'R'; + case CoordinateEnum::AnteriorToPosterior: + return 'P'; + case CoordinateEnum::PosteriorToAnterior: + return 'A'; + case CoordinateEnum::InferiorToSuperior: + return 'S'; + case CoordinateEnum::SuperiorToInferior: + return 'I'; + default: + return 'X'; + } + }; + + if (m_Value == PositiveEnum::INVALID) + { + return "INVALID"; + } + + return std::string({ enumAsChar(GetPrimaryTerm()), enumAsChar(GetSecondaryTerm()), enumAsChar(GetTertiaryTerm()) }); +} + + +std::string +AnatomicalOrientation::GetAsNegativeStringEncoding() const +{ + return ConvertStringEncoding(GetAsPositiveStringEncoding()); +} + + +AnatomicalOrientation +AnatomicalOrientation::CreateFromPositiveStringEncoding(std::string str) +{ + std::transform(str.begin(), str.end(), str.begin(), ::toupper); + + const std::map & stringToCode = GetStringToCode(); + auto iter = stringToCode.find(str); + if (iter == stringToCode.end()) + { + return { PositiveEnum::INVALID }; + } + return { iter->second }; +} + +AnatomicalOrientation +AnatomicalOrientation::CreateFromNegativeStringEncoding(std::string str) +{ + return AnatomicalOrientation::CreateFromPositiveStringEncoding(ConvertStringEncoding(str)); +} + + +std::string +AnatomicalOrientation::ConvertStringEncoding(std::string str) +{ + + auto flip = [](char c) -> char { + switch (::toupper(c)) + { + case 'R': + return 'L'; + case 'L': + return 'R'; + case 'A': + return 'P'; + case 'P': + return 'A'; + case 'S': + return 'I'; + case 'I': + return 'S'; + case 'X': + return 'X'; + default: + return c; + } + }; + + for (auto & c : str) + { + c = flip(c); + } + return str; +} + + +AnatomicalOrientation::CoordinateEnum +AnatomicalOrientation::GetCoordinateTerm(CoordinateMajornessTermsEnum cmt) const +{ + return static_cast(static_cast(m_Value) >> static_cast(cmt) & 0xff); +} + + +const std::map & +AnatomicalOrientation::GetCodeToString() +{ + auto createCodeToString = []() -> std::map { + std::map orientToString; + + for (auto code : { PositiveEnum::RIP, PositiveEnum::LIP, PositiveEnum::RSP, PositiveEnum::LSP, PositiveEnum::RIA, + PositiveEnum::LIA, PositiveEnum::RSA, PositiveEnum::LSA, PositiveEnum::IRP, PositiveEnum::ILP, + PositiveEnum::SRP, PositiveEnum::SLP, PositiveEnum::IRA, PositiveEnum::ILA, PositiveEnum::SRA, + PositiveEnum::SLA, PositiveEnum::RPI, PositiveEnum::LPI, PositiveEnum::RAI, PositiveEnum::LAI, + PositiveEnum::RPS, PositiveEnum::LPS, PositiveEnum::RAS, PositiveEnum::LAS, PositiveEnum::PRI, + PositiveEnum::PLI, PositiveEnum::ARI, PositiveEnum::ALI, PositiveEnum::PRS, PositiveEnum::PLS, + PositiveEnum::ARS, PositiveEnum::ALS, PositiveEnum::IPR, PositiveEnum::SPR, PositiveEnum::IAR, + PositiveEnum::SAR, PositiveEnum::IPL, PositiveEnum::SPL, PositiveEnum::IAL, PositiveEnum::SAL, + PositiveEnum::PIR, PositiveEnum::PSR, PositiveEnum::AIR, PositiveEnum::ASR, PositiveEnum::PIL, + PositiveEnum::PSL, PositiveEnum::AIL, PositiveEnum::ASL, PositiveEnum::INVALID }) + { + orientToString[code] = AnatomicalOrientation(code).GetAsPositiveStringEncoding(); + } + + return orientToString; + }; + static const std::map codeToString = createCodeToString(); + return codeToString; +} + +const std::map & +AnatomicalOrientation::GetStringToCode() +{ + + auto createStringToCode = []() -> std::map { + std::map stringToCode; + const std::map & codeToString = GetCodeToString(); + + for (const auto & kv : codeToString) + { + stringToCode[kv.second] = kv.first; + } + return stringToCode; + }; + + static const std::map stringToCode = createStringToCode(); + return stringToCode; +} + + +AnatomicalOrientation::PositiveEnum +AnatomicalOrientation::ConvertDirectionToPositiveEnum(const DirectionType & dir) +{ + // NOTE: This method was based off of itk::SpatialObjectAdaptor::FromDirectionCosines + // but it is DIFFERENT in the meaning of direction in terms of sign-ness. + CoordinateEnum terms[3] = { CoordinateEnum::UNKNOWN, CoordinateEnum::UNKNOWN, CoordinateEnum::UNKNOWN }; + + std::multimap> value_to_idx; + for (unsigned int c = 0; c < 3; ++c) + { + for (unsigned int r = 0; r < 3; ++r) + { + value_to_idx.emplace(std::abs(dir[c][r]), std::make_pair(c, r)); + } + } + + for (unsigned i = 0; i < 3; ++i) + { + + auto max_idx = value_to_idx.rbegin()->second; + const unsigned int max_c = max_idx.first; + const unsigned int max_r = max_idx.second; + + const int max_sgn = Math::sgn(dir[max_c][max_r]); + + for (auto it = value_to_idx.begin(); it != value_to_idx.end();) + { + if (it->second.first == max_c || it->second.second == max_r) + { + value_to_idx.erase(it++); + } + else + { + ++it; + } + } + + switch (max_c) + { + case 0: + { + // When the dominant axis sign is positive, assign the coordinate for the direction we are increasing towards. + // ITK is in LPS, so that is the positive direction + terms[max_r] = (max_sgn == 1) ? CoordinateEnum::RightToLeft : CoordinateEnum::LeftToRight; + break; + } + case 1: + { + terms[max_r] = (max_sgn == 1) ? CoordinateEnum::AnteriorToPosterior : CoordinateEnum::PosteriorToAnterior; + break; + } + case 2: + { + terms[max_r] = (max_sgn == 1) ? CoordinateEnum::InferiorToSuperior : CoordinateEnum::SuperiorToInferior; + break; + } + default: + itkGenericExceptionMacro("Unexpected Axis"); + } + } + + return AnatomicalOrientation(terms[0], terms[1], terms[2]); +} + + +typename AnatomicalOrientation::DirectionType +AnatomicalOrientation::ConvertPositiveEnumToDirection(PositiveEnum orientationEnum) +{ + const AnatomicalOrientation o(orientationEnum); + + const CoordinateEnum terms[Dimension] = { o.GetPrimaryTerm(), o.GetSecondaryTerm(), o.GetTertiaryTerm() }; + DirectionType direction{}; + + for (unsigned int i = 0; i < Dimension; ++i) + { + const int sign = (static_cast(terms[i]) & 0x1) ? 1 : -1; + + switch (terms[i]) + { + case CoordinateEnum::LeftToRight: + case CoordinateEnum::RightToLeft: + direction[0][i] = -1 * sign; + break; + case CoordinateEnum::AnteriorToPosterior: + case CoordinateEnum::PosteriorToAnterior: + direction[1][i] = 1 * sign; + break; + case CoordinateEnum::InferiorToSuperior: + case CoordinateEnum::SuperiorToInferior: + direction[2][i] = -1 * sign; + break; + case CoordinateEnum::UNKNOWN: + break; + } + } + return direction; +} + +std::ostream & +operator<<(std::ostream & out, typename AnatomicalOrientation::CoordinateEnum value) +{ + switch (value) + { + case AnatomicalOrientation::CoordinateEnum::RightToLeft: + return out << "right-to-left"; + case AnatomicalOrientation::CoordinateEnum::LeftToRight: + return out << "left-to-right"; + case AnatomicalOrientation::CoordinateEnum::AnteriorToPosterior: + return out << "anterior-to-posterior"; + case AnatomicalOrientation::CoordinateEnum::PosteriorToAnterior: + return out << "posterior-to-anterior"; + case AnatomicalOrientation::CoordinateEnum::InferiorToSuperior: + return out << "inferior-to-superior"; + case AnatomicalOrientation::CoordinateEnum::SuperiorToInferior: + return out << "superior-to-inferior"; + case AnatomicalOrientation::CoordinateEnum::UNKNOWN: + return out << "unknown"; + default: + return out << "invalid"; + } +} + +std::ostream & +operator<<(std::ostream & out, typename AnatomicalOrientation::PositiveEnum value) +{ + return (out << AnatomicalOrientation(value).GetAsPositiveStringEncoding()); +} + +std::ostream & +operator<<(std::ostream & out, typename AnatomicalOrientation::NegativeEnum value) +{ + return (out << AnatomicalOrientation(value).GetAsNegativeStringEncoding()); +} + +std::ostream & +operator<<(std::ostream & out, const AnatomicalOrientation & orientation) +{ + const auto terms = orientation.GetTerms(); + static_assert(std::tuple_size{} == 3); + return out << terms[0] << " " << terms[1] << " " << terms[2]; +} + +} // namespace itk diff --git a/Modules/Core/Common/src/itkArrayOutputSpecialization.cxx b/Modules/Core/Common/src/itkArrayOutputSpecialization.cxx index 5dd38fdaf24..d6802f9e270 100644 --- a/Modules/Core/Common/src/itkArrayOutputSpecialization.cxx +++ b/Modules/Core/Common/src/itkArrayOutputSpecialization.cxx @@ -22,7 +22,7 @@ namespace itk { template <> -std::ostream & operator<<(std::ostream & os, const Array & arr) +std::ostream & operator<< (std::ostream & os, const Array & arr) { os << '['; const size_t length = arr.size(); @@ -40,7 +40,7 @@ std::ostream & operator<<(std::ostream & os, const Array & arr) } template <> -std::ostream & operator<<(std::ostream & os, const Array & arr) +std::ostream & operator<< (std::ostream & os, const Array & arr) { os << '['; const size_t length = arr.size(); @@ -58,7 +58,7 @@ std::ostream & operator<<(std::ostream & os, const Array & arr) } template <> -std::ostream & operator<<(std::ostream & os, const Array2D & arr) +std::ostream & operator<< (std::ostream & os, const Array2D & arr) { const unsigned int numberOfRows = arr.rows(); const unsigned int numberOfColumns = arr.cols(); @@ -82,7 +82,7 @@ std::ostream & operator<<(std::ostream & os, const Array2D & arr } template <> -std::ostream & operator<<(std::ostream & os, const Array2D & arr) +std::ostream & operator<< (std::ostream & os, const Array2D & arr) { const unsigned int numberOfRows = arr.rows(); const unsigned int numberOfColumns = arr.cols(); diff --git a/Modules/Core/Common/src/itkBuildInformation.cxx.in b/Modules/Core/Common/src/itkBuildInformation.cxx.in index ad4cf9026df..2fed7cf4191 100644 --- a/Modules/Core/Common/src/itkBuildInformation.cxx.in +++ b/Modules/Core/Common/src/itkBuildInformation.cxx.in @@ -87,7 +87,7 @@ BuildInformation::GetValue(const MapKeyType & key) { return it->second.m_Value; } - return {""}; + return {}; } const BuildInformation::MapValueDescriptionType @@ -100,7 +100,7 @@ BuildInformation::GetDescription(const MapKeyType & key) { return it->second.m_Description; } - return {""}; + return {}; } const std::vector< BuildInformation::MapKeyType > diff --git a/Modules/Core/Common/src/itkCommonEnums.cxx b/Modules/Core/Common/src/itkCommonEnums.cxx index 1fd6d5a0030..da4fcb63fae 100644 --- a/Modules/Core/Common/src/itkCommonEnums.cxx +++ b/Modules/Core/Common/src/itkCommonEnums.cxx @@ -229,8 +229,8 @@ operator<<(std::ostream & out, const OctreeEnums::Octree value) { case OctreeEnums::Octree::UNKNOWN_PLANE: return "itk::OctreeEnums::Octree::UNKNOWN_PLANE"; - case OctreeEnums::Octree::SAGITAL_PLANE: - return "itk::OctreeEnums::Octree::SAGITAL_PLANE"; + case OctreeEnums::Octree::SAGITTAL_PLANE: + return "itk::OctreeEnums::Octree::SAGITTAL_PLANE"; case OctreeEnums::Octree::CORONAL_PLANE: return "itk::OctreeEnums::Octree::CORONAL_PLANE"; case OctreeEnums::Octree::TRANSVERSE_PLANE: diff --git a/Modules/Core/Common/src/itkCompensatedSummation.cxx b/Modules/Core/Common/src/itkCompensatedSummation.cxx index 26a32b14c5a..df1bd3bd95a 100644 --- a/Modules/Core/Common/src/itkCompensatedSummation.cxx +++ b/Modules/Core/Common/src/itkCompensatedSummation.cxx @@ -26,12 +26,12 @@ namespace itk { void ITKCommon_EXPORT - CompensatedSummationAddElement(float & compensation, float & sum, const float element) +CompensatedSummationAddElement(float & compensation, float & sum, const float element) { CompensatedSummationAddElement(compensation, sum, element, 1); } void ITKCommon_EXPORT - CompensatedSummationAddElement(double & compensation, double & sum, const double element) +CompensatedSummationAddElement(double & compensation, double & sum, const double element) { CompensatedSummationAddElement(compensation, sum, element, 1); } diff --git a/Modules/Core/Common/src/itkConfigure.h.in b/Modules/Core/Common/src/itkConfigure.h.in index 48118bb3e92..c2cb088ac42 100644 --- a/Modules/Core/Common/src/itkConfigure.h.in +++ b/Modules/Core/Common/src/itkConfigure.h.in @@ -59,7 +59,6 @@ /* what threading system are we using */ #cmakedefine ITK_USE_PTHREADS -#cmakedefine ITK_HP_PTHREADS #cmakedefine ITK_USE_WIN32_THREADS #cmakedefine ITK_WINDOWS_EXPORT_ALL_SYMBOLS @@ -71,11 +70,9 @@ #endif #cmakedefine ITK_DYNAMIC_LOADING -#cmakedefine ITKV4_COMPATIBILITY #cmakedefine ITK_LEGACY_REMOVE #cmakedefine ITK_LEGACY_SILENT #cmakedefine ITK_FUTURE_LEGACY_REMOVE -#cmakedefine ITK_USE_CONCEPT_CHECKING #cmakedefine ITK_USE_FFTWF #cmakedefine ITK_USE_FFTWD #cmakedefine ITK_USE_CUFFTW diff --git a/Modules/Core/Common/src/itkCovariantVector.cxx b/Modules/Core/Common/src/itkCovariantVector.cxx index 64e8ad75233..2f12b74d6c8 100644 --- a/Modules/Core/Common/src/itkCovariantVector.cxx +++ b/Modules/Core/Common/src/itkCovariantVector.cxx @@ -28,7 +28,7 @@ namespace itk */ void ITKCommon_EXPORT - CrossProduct(CovariantVector & c, const Vector & a, const Vector & b) +CrossProduct(CovariantVector & c, const Vector & a, const Vector & b) { c[0] = a[1] * b[2] - a[2] * b[1]; c[1] = a[2] * b[0] - a[0] * b[2]; @@ -36,7 +36,7 @@ void ITKCommon_EXPORT } void ITKCommon_EXPORT - CrossProduct(CovariantVector & c, const Vector & a, const Vector & b) +CrossProduct(CovariantVector & c, const Vector & a, const Vector & b) { c[0] = a[1] * b[2] - a[2] * b[1]; c[1] = a[2] * b[0] - a[0] * b[2]; @@ -44,7 +44,7 @@ void ITKCommon_EXPORT } void ITKCommon_EXPORT - CrossProduct(CovariantVector & c, const Vector & a, const Vector & b) +CrossProduct(CovariantVector & c, const Vector & a, const Vector & b) { c[0] = a[1] * b[2] - a[2] * b[1]; c[1] = a[2] * b[0] - a[0] * b[2]; diff --git a/Modules/Core/Common/src/itkDataObject.cxx b/Modules/Core/Common/src/itkDataObject.cxx index afa6cd87d42..a8741b53b31 100644 --- a/Modules/Core/Common/src/itkDataObject.cxx +++ b/Modules/Core/Common/src/itkDataObject.cxx @@ -39,12 +39,8 @@ DataObjectError::DataObjectError() noexcept : ExceptionObject() {} -DataObjectError::DataObjectError(const char * file, unsigned int lineNumber) - : ExceptionObject(file, lineNumber) -{} - -DataObjectError::DataObjectError(const std::string & file, unsigned int lineNumber) - : ExceptionObject(file, lineNumber) +DataObjectError::DataObjectError(std::string file, unsigned int lineNumber) + : ExceptionObject(std::move(file), lineNumber) {} DataObjectError::DataObjectError(const DataObjectError & orig) noexcept @@ -98,12 +94,8 @@ InvalidRequestedRegionError::InvalidRequestedRegionError() noexcept : DataObjectError() {} -InvalidRequestedRegionError::InvalidRequestedRegionError(const char * file, unsigned int lineNumber) - : DataObjectError(file, lineNumber) -{} - -InvalidRequestedRegionError::InvalidRequestedRegionError(const std::string & file, unsigned int lineNumber) - : DataObjectError(file, lineNumber) +InvalidRequestedRegionError::InvalidRequestedRegionError(std::string file, unsigned int lineNumber) + : DataObjectError(std::move(file), lineNumber) {} InvalidRequestedRegionError::InvalidRequestedRegionError(const InvalidRequestedRegionError &) noexcept = default; @@ -215,11 +207,9 @@ DataObject::DisconnectSource(ProcessObject * arg, const DataObjectIdentifierType this->Modified(); return true; } - else - { - itkDebugMacro("could not disconnect source " << arg << ", source output name " << name); - return false; - } + + itkDebugMacro("could not disconnect source " << arg << ", source output name " << name); + return false; } bool @@ -234,12 +224,10 @@ DataObject::ConnectSource(ProcessObject * arg, const DataObjectIdentifierType & this->Modified(); return true; } - else - { - itkDebugMacro("could not connect source " << arg << ", source output name " << name); - return false; - } + itkDebugMacro("could not connect source " << arg << ", source output name " << name); + + return false; } //---------------------------------------------------------------------------- diff --git a/Modules/Core/Common/src/itkDirectory.cxx b/Modules/Core/Common/src/itkDirectory.cxx index 81d528ead5b..59e32085b85 100644 --- a/Modules/Core/Common/src/itkDirectory.cxx +++ b/Modules/Core/Common/src/itkDirectory.cxx @@ -39,7 +39,7 @@ Directory::PrintSelf(std::ostream & os, Indent indent) const os << indent << "Directory for: " << m_Internal.GetPath() << '\n'; os << indent << "Contains the following files:\n"; indent = indent.GetNextIndent(); - unsigned long numFiles = m_Internal.GetNumberOfFiles(); + const unsigned long numFiles = m_Internal.GetNumberOfFiles(); for (unsigned long i = 0; i < numFiles; ++i) { os << indent << m_Internal.GetFile(i) << '\n'; diff --git a/Modules/Core/Common/src/itkEquivalencyTable.cxx b/Modules/Core/Common/src/itkEquivalencyTable.cxx index 0371a7312f6..bb686c54801 100644 --- a/Modules/Core/Common/src/itkEquivalencyTable.cxx +++ b/Modules/Core/Common/src/itkEquivalencyTable.cxx @@ -22,18 +22,17 @@ namespace itk bool EquivalencyTable::Add(unsigned long a, unsigned long b) { - std::pair result; if (a == b) { return false; } - else if (a < b) + if (a < b) { // swap a, b - unsigned long temp = a; + const unsigned long temp = a; a = b; b = temp; } - result = m_HashMap.insert(ValueType(a, b)); + const std::pair result = m_HashMap.insert(ValueType(a, b)); if (result.second == false) { // Stop endless loops. @@ -41,10 +40,8 @@ EquivalencyTable::Add(unsigned long a, unsigned long b) { return false; } - else - { - return (this->Add((*(result.first)).second, b)); - } + + return (this->Add((*(result.first)).second, b)); } else { @@ -55,20 +52,19 @@ EquivalencyTable::Add(unsigned long a, unsigned long b) bool EquivalencyTable::AddAndFlatten(unsigned long a, unsigned long b) { - std::pair result; if (a == b) { return false; } - else if (a < b) + if (a < b) { // swap a, b - unsigned long temp = a; + const unsigned long temp = a; a = b; b = temp; } - unsigned long bFlattened = this->RecursiveLookup(b); - result = m_HashMap.insert(ValueType(a, bFlattened)); + const unsigned long bFlattened = this->RecursiveLookup(b); + const std::pair result = m_HashMap.insert(ValueType(a, bFlattened)); if (result.second == false) { // Stop endless loops. @@ -76,10 +72,8 @@ EquivalencyTable::AddAndFlatten(unsigned long a, unsigned long b) { return false; } - else - { - return (this->Add((*(result.first)).second, bFlattened)); - } + + return (this->Add((*(result.first)).second, bFlattened)); } else { diff --git a/Modules/Core/Common/src/itkEventObject.cxx b/Modules/Core/Common/src/itkEventObject.cxx index 7c58cd93196..dee96f2236d 100644 --- a/Modules/Core/Common/src/itkEventObject.cxx +++ b/Modules/Core/Common/src/itkEventObject.cxx @@ -22,7 +22,7 @@ namespace itk void EventObject::Print(std::ostream & os) const { - Indent indent; + const Indent indent; this->PrintHeader(os, 0); this->PrintSelf(os, indent.GetNextIndent()); diff --git a/Modules/Core/Common/src/itkExceptionObject.cxx b/Modules/Core/Common/src/itkExceptionObject.cxx index c4e7374014d..1b0d3275e20 100644 --- a/Modules/Core/Common/src/itkExceptionObject.cxx +++ b/Modules/Core/Common/src/itkExceptionObject.cxx @@ -41,11 +41,13 @@ class ExceptionObject::ExceptionData , m_File(std::move(file)) , m_Line(line) { - std::ostringstream loc; - - loc << ':' << m_Line << ":\n"; m_What = m_File; - m_What += loc.str(); + m_What += ':' + std::to_string(m_Line) + ':'; + if (!m_Location.empty()) + { + m_What += " in '" + m_Location + "':"; + } + m_What += '\n'; m_What += m_Description; } @@ -63,15 +65,12 @@ class ExceptionObject::ExceptionData }; -ExceptionObject::ExceptionObject(const char * file, unsigned int lineNumber, const char * desc, const char * loc) - : m_ExceptionData(std::make_shared(file == nullptr ? "" : file, - lineNumber, - desc == nullptr ? "" : desc, - loc == nullptr ? "" : loc)) -{} - -ExceptionObject::ExceptionObject(std::string file, unsigned int lineNumber, std::string desc, std::string loc) - : m_ExceptionData(std::make_shared(std::move(file), lineNumber, std::move(desc), std::move(loc))) +ExceptionObject::ExceptionObject(std::string file, + unsigned int lineNumber, + std::string description, + std::string location) + : m_ExceptionData( + std::make_shared(std::move(file), lineNumber, std::move(description), std::move(location))) {} @@ -91,12 +90,10 @@ ExceptionObject::operator==(const ExceptionObject & orig) const { return true; } - else - { - return (thisData != nullptr) && (origData != nullptr) && thisData->m_Location == origData->m_Location && - thisData->m_Description == origData->m_Description && thisData->m_File == origData->m_File && - thisData->m_Line == origData->m_Line; - } + + return (thisData != nullptr) && (origData != nullptr) && thisData->m_Location == origData->m_Location && + thisData->m_Description == origData->m_Description && thisData->m_File == origData->m_File && + thisData->m_Line == origData->m_Line; } void @@ -178,7 +175,7 @@ ExceptionObject::what() const noexcept void ExceptionObject::Print(std::ostream & os) const { - Indent indent; + const Indent indent; // Print header os << std::endl; diff --git a/Modules/Core/Common/src/itkFileOutputWindow.cxx b/Modules/Core/Common/src/itkFileOutputWindow.cxx index 8254bf78965..43bc59069ac 100644 --- a/Modules/Core/Common/src/itkFileOutputWindow.cxx +++ b/Modules/Core/Common/src/itkFileOutputWindow.cxx @@ -30,11 +30,7 @@ FileOutputWindow::FileOutputWindow() m_FileName = ""; } -FileOutputWindow::~FileOutputWindow() -{ - delete m_Stream; - m_Stream = nullptr; -} +FileOutputWindow::~FileOutputWindow() { delete m_Stream; } void FileOutputWindow::PrintSelf(std::ostream & os, Indent indent) const diff --git a/Modules/Core/Common/src/itkFloatingPointExceptions.cxx b/Modules/Core/Common/src/itkFloatingPointExceptions.cxx index db61b61e224..2b1405db4e5 100644 --- a/Modules/Core/Common/src/itkFloatingPointExceptions.cxx +++ b/Modules/Core/Common/src/itkFloatingPointExceptions.cxx @@ -113,7 +113,7 @@ itkFloatingPointExceptionsAbortOrExit() } } -void +[[maybe_unused]] void itkFloatingPointExceptionsNotSupported() { std::cerr << "FloatingPointExceptions are not supported on this platform." << std::endl; diff --git a/Modules/Core/Common/src/itkFloatingPointExceptions_unix.cxx b/Modules/Core/Common/src/itkFloatingPointExceptions_unix.cxx index 4a9e0d22af8..a01d2fabfd5 100644 --- a/Modules/Core/Common/src/itkFloatingPointExceptions_unix.cxx +++ b/Modules/Core/Common/src/itkFloatingPointExceptions_unix.cxx @@ -157,15 +157,13 @@ FloatingPointExceptions::Enable() itk_feenableexcept(FE_DIVBYZERO); itk_feenableexcept(FE_INVALID); # if defined(ITK_FPE_USE_SIGNAL_HANDLER) - struct sigaction act; - memset(&act, 0, sizeof(struct sigaction)); + struct sigaction act{}; act.sa_sigaction = fhdl; sigemptyset(&act.sa_mask); act.sa_flags = SA_SIGINFO; sigaction(SIGFPE, &act, nullptr); # endif FloatingPointExceptions::m_PimplGlobals->m_Enabled = true; - (void)itkFloatingPointExceptionsNotSupported; // avoid unused-function warning #else itkFloatingPointExceptionsNotSupported(); #endif diff --git a/Modules/Core/Common/src/itkImageIORegion.cxx b/Modules/Core/Common/src/itkImageIORegion.cxx index 1495edd0ba9..d54f373898b 100644 --- a/Modules/Core/Common/src/itkImageIORegion.cxx +++ b/Modules/Core/Common/src/itkImageIORegion.cxx @@ -130,7 +130,7 @@ ImageIORegion::GetRegionDimension() const } ImageIORegion::SizeValueType -ImageIORegion::GetSize(unsigned long i) const +ImageIORegion::GetSize(unsigned int i) const { if (i >= m_Size.size()) { @@ -140,7 +140,7 @@ ImageIORegion::GetSize(unsigned long i) const } ImageIORegion::IndexValueType -ImageIORegion::GetIndex(unsigned long i) const +ImageIORegion::GetIndex(unsigned int i) const { if (i >= m_Index.size()) { @@ -150,7 +150,7 @@ ImageIORegion::GetIndex(unsigned long i) const } void -ImageIORegion::SetSize(const unsigned long i, SizeValueType size) +ImageIORegion::SetSize(const unsigned int i, SizeValueType size) { if (i >= m_Size.size()) { @@ -160,7 +160,7 @@ ImageIORegion::SetSize(const unsigned long i, SizeValueType size) } void -ImageIORegion::SetIndex(const unsigned long i, IndexValueType idx) +ImageIORegion::SetIndex(const unsigned int i, IndexValueType idx) { if (i >= m_Index.size()) { diff --git a/Modules/Core/Common/src/itkImageRegionSplitterDirection.cxx b/Modules/Core/Common/src/itkImageRegionSplitterDirection.cxx index 2c3812a9fdd..c8f621417cb 100644 --- a/Modules/Core/Common/src/itkImageRegionSplitterDirection.cxx +++ b/Modules/Core/Common/src/itkImageRegionSplitterDirection.cxx @@ -22,10 +22,7 @@ namespace itk { -ImageRegionSplitterDirection::ImageRegionSplitterDirection() -{ - this->m_Direction = 0; -} +ImageRegionSplitterDirection::ImageRegionSplitterDirection() { this->m_Direction = 0; } void ImageRegionSplitterDirection::PrintSelf(std::ostream & os, Indent indent) const diff --git a/Modules/Core/Common/src/itkImageRegionSplitterMultidimensional.cxx b/Modules/Core/Common/src/itkImageRegionSplitterMultidimensional.cxx index a6977240e62..683f0363eea 100644 --- a/Modules/Core/Common/src/itkImageRegionSplitterMultidimensional.cxx +++ b/Modules/Core/Common/src/itkImageRegionSplitterMultidimensional.cxx @@ -41,7 +41,7 @@ ImageRegionSplitterMultidimensional::GetNumberOfSplitsInternal(unsigned int // number of splits in each dimension std::vector splits(dim); // Note: stack allocation preferred - unsigned int numberOfPieces = this->ComputeSplits(dim, requestedNumber, regionIndex, regionSize, &splits[0]); + const unsigned int numberOfPieces = this->ComputeSplits(dim, requestedNumber, regionIndex, regionSize, &splits[0]); return numberOfPieces; } diff --git a/Modules/Core/Common/src/itkLightObject.cxx b/Modules/Core/Common/src/itkLightObject.cxx index 132e79caf8d..4e6677b7b3e 100644 --- a/Modules/Core/Common/src/itkLightObject.cxx +++ b/Modules/Core/Common/src/itkLightObject.cxx @@ -19,7 +19,7 @@ #include "itkObjectFactoryBase.h" #include -// Better name demanging for gcc +// Better name demangling for gcc #if defined(__GNUC__) && !defined(__EMSCRIPTEN__) # define GCC_USEDEMANGLE #endif @@ -40,14 +40,13 @@ LightObject::LightObject() LightObject::Pointer LightObject::New() { - Pointer smartPtr; LightObject * rawPtr = ObjectFactoryBase::CreateInstance(typeid(LightObject).name()); if (rawPtr == nullptr) { rawPtr = new LightObject; } - smartPtr = rawPtr; + Pointer smartPtr = rawPtr; rawPtr->UnRegister(); return smartPtr; } @@ -96,13 +95,13 @@ LightObject::operator new[](size_t n) void LightObject::operator delete(void * m) { - delete[](char *) m; + delete[] (char *)m; } void LightObject::operator delete[](void * m, size_t) { - delete[](char *) m; + delete[] (char *)m; } #endif @@ -191,7 +190,7 @@ void LightObject::PrintSelf(std::ostream & os, Indent indent) const { #ifdef GCC_USEDEMANGLE - char const * mangledName = typeid(*this).name(); + const char * mangledName = typeid(*this).name(); int status; char * unmangled = abi::__cxa_demangle(mangledName, nullptr, nullptr, &status); diff --git a/Modules/Core/Common/src/itkLoggerBase.cxx b/Modules/Core/Common/src/itkLoggerBase.cxx index 5f1a6ec1ee5..e1090cf026c 100644 --- a/Modules/Core/Common/src/itkLoggerBase.cxx +++ b/Modules/Core/Common/src/itkLoggerBase.cxx @@ -44,7 +44,7 @@ LoggerBase::AddLogOutput(OutputType * output) } void -LoggerBase::Write(PriorityLevelEnum level, std::string const & content) +LoggerBase::Write(PriorityLevelEnum level, const std::string & content) { if (this->m_PriorityLevel >= level) { @@ -69,11 +69,11 @@ LoggerBase::PrivateFlush() } std::string -LoggerBase::BuildFormattedEntry(PriorityLevelEnum level, std::string const & content) +LoggerBase::BuildFormattedEntry(PriorityLevelEnum level, const std::string & content) { - static std::string m_LevelString[] = { "(MUSTFLUSH) ", "(FATAL) ", "(CRITICAL) ", "(WARNING) ", - "(INFO) ", "(DEBUG) ", "(NOTSET) " }; - std::ostringstream s; + static const std::string levelString[] = { "(MUSTFLUSH) ", "(FATAL) ", "(CRITICAL) ", "(WARNING) ", + "(INFO) ", "(DEBUG) ", "(NOTSET) " }; + std::ostringstream s; switch (this->m_TimeStampFormat) { @@ -89,7 +89,7 @@ LoggerBase::BuildFormattedEntry(PriorityLevelEnum level, std::string const & con break; } } - s << " : " << this->GetName() << " " << m_LevelString[static_cast(level)] << content; + s << " : " << this->GetName() << " " << levelString[static_cast(level)] << content; return s.str(); } diff --git a/Modules/Core/Common/src/itkLoggerManager.cxx b/Modules/Core/Common/src/itkLoggerManager.cxx index 9433fc6985b..abc221a7150 100644 --- a/Modules/Core/Common/src/itkLoggerManager.cxx +++ b/Modules/Core/Common/src/itkLoggerManager.cxx @@ -93,7 +93,7 @@ LoggerManager::AddLogOutput(OutputType * output) } void -LoggerManager::Write(PriorityLevelEnum level, std::string const & content) +LoggerManager::Write(PriorityLevelEnum level, const std::string & content) { for (const auto & logger : m_LoggerSet) { diff --git a/Modules/Core/Common/src/itkMemoryUsageObserver.cxx b/Modules/Core/Common/src/itkMemoryUsageObserver.cxx index 61cbe7b657d..b8744c3d8ef 100644 --- a/Modules/Core/Common/src/itkMemoryUsageObserver.cxx +++ b/Modules/Core/Common/src/itkMemoryUsageObserver.cxx @@ -169,8 +169,8 @@ struct SYSTEM_PROCESSES ULONG pad4; ULONG pad5; # else - ULONG ProcessId; - ULONG InheritedFromProcessId; + ULONG ProcessId; + ULONG InheritedFromProcessId; # endif ULONG HandleCount; ULONG Reserved2[2]; @@ -211,8 +211,7 @@ WindowsMemoryUsageObserver::GetMemoryUsage() if (!m_hNTLib) { - itkGenericExceptionMacro("Can't find ntdll.dll. " - << "You should probably disable SUPPORT_TOOLHELP32"); + itkGenericExceptionMacro("Can't find ntdll.dll. You should probably disable SUPPORT_TOOLHELP32"); } // the ntdll.dll library could not have been opened (file not found?) if (!ZwQuerySystemInformation) @@ -316,10 +315,10 @@ MacOSXMemoryUsageObserver::GetMemoryUsage() // // this method comes from // https://stackoverflow.com/questions/5839626/how-is-top-able-to-see-memory-usage - task_t targetTask = mach_task_self(); + const task_t targetTask = mach_task_self(); struct task_basic_info ti; mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT; - kern_return_t kr = task_info(targetTask, TASK_BASIC_INFO_64, (task_info_t)&ti, &count); + const kern_return_t kr = task_info(targetTask, TASK_BASIC_INFO_64, (task_info_t)&ti, &count); if (kr != KERN_SUCCESS) { return 0; @@ -429,7 +428,7 @@ SysResourceMemoryUsageObserver::GetMemoryUsage() // Maybe use getrusage() ?? rusage resourceInfo; - const int who = RUSAGE_SELF; + constexpr int who = RUSAGE_SELF; if (getrusage(who, &resourceInfo) == 0) { return static_cast(resourceInfo.ru_ixrss); diff --git a/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx b/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx index c277e124947..288a564e7cf 100644 --- a/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx +++ b/Modules/Core/Common/src/itkMersenneTwisterRandomVariateGenerator.cxx @@ -25,6 +25,40 @@ namespace itk { namespace Statistics { +namespace +{ +using IntegerType = MersenneTwisterRandomVariateGenerator::IntegerType; + +IntegerType +hiBit(const IntegerType u) +{ + return u & 0x80000000; +} + +IntegerType +loBit(const IntegerType u) +{ + return u & 0x00000001; +} + +IntegerType +loBits(const IntegerType u) +{ + return u & 0x7fffffff; +} +IntegerType +mixBits(const IntegerType u, const IntegerType v) +{ + return hiBit(u) | loBits(v); +} + +IntegerType +twist(const IntegerType m, const IntegerType s0, const IntegerType s1) +{ + return m ^ (mixBits(s0, s1) >> 1) ^ (-static_cast(loBit(s1)) & 0x9908b0df); +} +} // namespace + /** Private nested class to easily synchronize global variables across static libraries.*/ struct MersenneTwisterGlobals @@ -34,9 +68,9 @@ struct MersenneTwisterGlobals MersenneTwisterGlobals() = default; ~MersenneTwisterGlobals() = default; - MersenneTwisterRandomVariateGenerator::Pointer m_StaticInstance{}; - std::mutex m_StaticInstanceMutex{}; - std::atomic m_StaticDiffer{}; + MersenneTwisterRandomVariateGenerator::Pointer m_StaticInstance{}; + std::mutex m_StaticInstanceMutex{}; + std::atomic m_StaticDiffer{}; }; itkGetGlobalSimpleMacro(MersenneTwisterRandomVariateGenerator, MersenneTwisterGlobals, PimplGlobals); @@ -47,7 +81,7 @@ MersenneTwisterRandomVariateGenerator::Pointer MersenneTwisterRandomVariateGenerator::CreateInstance() { // Try the factory first - MersenneTwisterRandomVariateGenerator::Pointer obj = ObjectFactory::Create(); + Pointer obj = ObjectFactory::Create(); // If the factory did not provide one, then create it here if (!obj) { @@ -62,9 +96,9 @@ MersenneTwisterRandomVariateGenerator::CreateInstance() MersenneTwisterRandomVariateGenerator::Pointer MersenneTwisterRandomVariateGenerator::New() { - MersenneTwisterRandomVariateGenerator::Pointer obj = MersenneTwisterRandomVariateGenerator::CreateInstance(); + Pointer obj = Self::CreateInstance(); - obj->SetSeed(MersenneTwisterRandomVariateGenerator::GetNextSeed()); + obj->InitializeWithoutMutexLocking(Self::GetNextSeed()); return obj; } @@ -76,8 +110,8 @@ MersenneTwisterRandomVariateGenerator::GetInstance() if (!m_PimplGlobals->m_StaticInstance) { - m_PimplGlobals->m_StaticInstance = MersenneTwisterRandomVariateGenerator::CreateInstance(); - m_PimplGlobals->m_StaticInstance->SetSeed(); + m_PimplGlobals->m_StaticInstance = Self::CreateInstance(); + m_PimplGlobals->m_StaticInstance->InitializeWithoutMutexLocking(Self::CreateRandomSeed()); } return m_PimplGlobals->m_StaticInstance; @@ -94,12 +128,12 @@ MersenneTwisterRandomVariateGenerator::ResetNextSeed() MersenneTwisterRandomVariateGenerator::MersenneTwisterRandomVariateGenerator() { - SetSeed(121212); + this->InitializeWithoutMutexLocking(DefaultSeed); } MersenneTwisterRandomVariateGenerator::~MersenneTwisterRandomVariateGenerator() = default; -MersenneTwisterRandomVariateGenerator::IntegerType +IntegerType MersenneTwisterRandomVariateGenerator::hash(const time_t t, const clock_t c) { itkInitGlobalsMacro(PimplGlobals); @@ -124,29 +158,124 @@ MersenneTwisterRandomVariateGenerator::hash(const time_t t, const clock_t c) return (h1 + m_PimplGlobals->m_StaticDiffer++) ^ h2; } -MersenneTwisterRandomVariateGenerator::IntegerType +IntegerType MersenneTwisterRandomVariateGenerator::GetNextSeed() { itkInitGlobalsMacro(PimplGlobals); - IntegerType newSeed = GetInstance()->GetSeed(); + return Self::GetInstance()->m_Seed + m_PimplGlobals->m_StaticDiffer++; +} + + +void +MersenneTwisterRandomVariateGenerator::SetSeed(const IntegerType seed) +{ + // This is a public member function, so it must lock the mutex of the instance. + const std::lock_guard lockGuard(m_InstanceMutex); + this->InitializeWithoutMutexLocking(seed); +} + +void +MersenneTwisterRandomVariateGenerator::InitializeWithoutMutexLocking(const IntegerType seed) +{ + m_Seed = seed; + // Initialize generator state with 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. + IntegerType * s = m_State; + const IntegerType * r = m_State; + + *s++ = seed; + for (IntegerType i = 1; i < StateVectorLength; ++i) { - newSeed += m_PimplGlobals->m_StaticDiffer++; + *s++ = uint32_t{ (uint32_t{ 1812433253 } * (*r ^ (*r >> 30)) + i) }; + ++r; } - return newSeed; + reload(); } +void +MersenneTwisterRandomVariateGenerator::reload() +{ + // Generate N new values in state + // Made clearer and faster by Matthew Bellew + // matthew dot bellew at home dot com + + // Period parameter + static constexpr unsigned int M = 397; + + // get rid of VS warning + constexpr auto index = int{ M } - int{ StateVectorLength }; + + IntegerType * p = m_State; + + for (int i = StateVectorLength - M; i--; ++p) + { + *p = twist(p[M], p[0], p[1]); + } + for (int i = M; --i; ++p) + { + *p = twist(p[index], p[0], p[1]); + } + *p = twist(p[index], p[0], m_State[0]); + + m_Left = StateVectorLength; + m_PNext = m_State; +} + + +/** Get an integer variate in [0, 2^32-1] */ +IntegerType +MersenneTwisterRandomVariateGenerator::GetIntegerVariate() +{ + if (m_Left == 0) + { + reload(); + } + --m_Left; + + IntegerType s1 = *m_PNext++; + s1 ^= (s1 >> 11); + s1 ^= (s1 << 7) & 0x9d2c5680; + s1 ^= (s1 << 15) & 0xefc60000; + return (s1 ^ (s1 >> 18)); +} + + +IntegerType +MersenneTwisterRandomVariateGenerator::GetIntegerVariate(const IntegerType n) +{ + // Find which bits are used in n + IntegerType used = n; + + used |= used >> 1; + used |= used >> 2; + used |= used >> 4; + used |= used >> 8; + used |= used >> 16; + + // Draw numbers until one is found in [0,n] + IntegerType i; + do + { + i = GetIntegerVariate() & used; // toss unused bits to shorten search + } while (i > n); + + return i; +} + + 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 << "State vector: " << m_State << std::endl; os << indent; - const IntegerType * s = state; - int i = StateVectorLength; - for (; i--; os << *s++ << '\t') + for (const IntegerType stateValue : m_State) { + os << stateValue << '\t'; } os << std::endl; diff --git a/Modules/Core/Common/src/itkMetaDataDictionary.cxx b/Modules/Core/Common/src/itkMetaDataDictionary.cxx index 8edd058fd05..9787c1e1d84 100644 --- a/Modules/Core/Common/src/itkMetaDataDictionary.cxx +++ b/Modules/Core/Common/src/itkMetaDataDictionary.cxx @@ -44,20 +44,22 @@ void MetaDataDictionary::Print(std::ostream & os) const { os << "Dictionary use_count: " << m_Dictionary.use_count() << std::endl; - for (MetaDataDictionaryMapType::const_iterator it = m_Dictionary->begin(); it != m_Dictionary->end(); ++it) + for (auto & it : *m_Dictionary) { - os << it->first << " "; - it->second->Print(os); + os << it.first << " "; + it.second->Print(os); } } -MetaDataObjectBase::Pointer & MetaDataDictionary::operator[](const std::string & key) +MetaDataObjectBase::Pointer & +MetaDataDictionary::operator[](const std::string & key) { MakeUnique(); return (*m_Dictionary)[key]; } -const MetaDataObjectBase * MetaDataDictionary::operator[](const std::string & key) const +const MetaDataObjectBase * +MetaDataDictionary::operator[](const std::string & key) const { auto iter = m_Dictionary->find(key); if (iter == m_Dictionary->end()) @@ -76,8 +78,8 @@ MetaDataDictionary::Get(const std::string & key) const { itkGenericExceptionMacro("Key '" << key << "' does not exist "); } - MetaDataObjectBase::Pointer entry = (*m_Dictionary)[key]; - const MetaDataObjectBase * constentry = entry.GetPointer(); + const MetaDataObjectBase::Pointer entry = (*m_Dictionary)[key]; + const MetaDataObjectBase * constentry = entry.GetPointer(); return constentry; } @@ -100,9 +102,9 @@ MetaDataDictionary::GetKeys() const using VectorType = std::vector; VectorType ans; - for (MetaDataDictionaryMapType::const_iterator it = m_Dictionary->begin(); it != m_Dictionary->end(); ++it) + for (auto & it : *m_Dictionary) { - ans.push_back(it->first); + ans.push_back(it.first); } return ans; @@ -177,8 +179,8 @@ MetaDataDictionary::MakeUnique() bool MetaDataDictionary::Erase(const std::string & key) { - auto it = m_Dictionary->find(key); - const MetaDataDictionaryMapType::iterator end = m_Dictionary->end(); + auto it = m_Dictionary->find(key); + const auto end = m_Dictionary->end(); if (it != end) { diff --git a/Modules/Core/Common/src/itkMultiThreaderBase.cxx b/Modules/Core/Common/src/itkMultiThreaderBase.cxx index 4b01f5ba80f..a0110210add 100644 --- a/Modules/Core/Common/src/itkMultiThreaderBase.cxx +++ b/Modules/Core/Common/src/itkMultiThreaderBase.cxx @@ -147,7 +147,7 @@ MultiThreaderBase::GetGlobalDefaultThreaderPrivate() if (itksys::SystemTools::GetEnv("ITK_GLOBAL_DEFAULT_THREADER", envVar)) { envVar = itksys::SystemTools::UpperCase(envVar); - ThreaderEnum threaderT = ThreaderTypeFromString(envVar); + const ThreaderEnum threaderT = ThreaderTypeFromString(envVar); if (threaderT != ThreaderEnum::Unknown) { MultiThreaderBase::SetGlobalDefaultThreaderPrivate(threaderT); @@ -199,7 +199,7 @@ MultiThreaderBase::ThreaderTypeFromString(std::string threaderString) { return ThreaderEnum::Platform; } - else if (threaderString == "POOL") + if (threaderString == "POOL") { return ThreaderEnum::Pool; } @@ -362,13 +362,10 @@ MultiThreaderBase::GetGlobalDefaultNumberOfThreadsByPlatform() # else num = 1; # endif -# if defined(__SVR4) && defined(sun) && defined(PTHREAD_MUTEX_NORMAL) - pthread_setconcurrency(num); -# endif itksys::SystemInformation mySys; mySys.RunCPUCheck(); - int result = mySys.GetNumberOfPhysicalCPU(); // Avoid using hyperthreading cores. + const int result = mySys.GetNumberOfPhysicalCPU(); // Avoid using hyperthreading cores. if (result == -1) { num = 1; @@ -391,7 +388,7 @@ MultiThreaderBase::New() Pointer smartPtr = itk::ObjectFactory::Create(); if (smartPtr == nullptr) { - ThreaderEnum threaderType = GetGlobalDefaultThreader(); + const ThreaderEnum threaderType = GetGlobalDefaultThreader(); switch (threaderType) { case ThreaderEnum::Platform: @@ -480,14 +477,11 @@ MultiThreaderBase::ParallelizeArray(SizeValueType firstIndex, filter = nullptr; } // Upon destruction, progress will be set to 1.0 - ProgressReporter progress(filter, 0, 1); + const ProgressReporter progress(filter, 0, 1); if (firstIndex + 1 < lastIndexPlus1) { - struct ArrayCallback acParams - { - aFunc, firstIndex, lastIndexPlus1, filter - }; + struct ArrayCallback acParams{ aFunc, firstIndex, lastIndexPlus1, filter }; this->SetSingleMethodAndExecute(&MultiThreaderBase::ParallelizeArrayHelper, &acParams); } else if (firstIndex + 1 == lastIndexPlus1) @@ -500,15 +494,15 @@ MultiThreaderBase::ParallelizeArray(SizeValueType firstIndex, ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION MultiThreaderBase::ParallelizeArrayHelper(void * arg) { - auto * workUnitInfo = static_cast(arg); - ThreadIdType workUnitID = workUnitInfo->WorkUnitID; - ThreadIdType workUnitCount = workUnitInfo->NumberOfWorkUnits; - auto * acParams = static_cast(workUnitInfo->UserData); - - SizeValueType range = acParams->lastIndexPlus1 - acParams->firstIndex; - double fraction = static_cast(range) / workUnitCount; - SizeValueType first = acParams->firstIndex + fraction * workUnitID; - SizeValueType afterLast = acParams->firstIndex + fraction * (workUnitID + 1); + auto * workUnitInfo = static_cast(arg); + const ThreadIdType workUnitID = workUnitInfo->WorkUnitID; + const ThreadIdType workUnitCount = workUnitInfo->NumberOfWorkUnits; + auto * acParams = static_cast(workUnitInfo->UserData); + + const SizeValueType range = acParams->lastIndexPlus1 - acParams->firstIndex; + const double fraction = static_cast(range) / workUnitCount; + const SizeValueType first = acParams->firstIndex + fraction * workUnitID; + SizeValueType afterLast = acParams->firstIndex + fraction * (workUnitID + 1); if (workUnitID == workUnitCount - 1) // last thread { // Avoid possible problems due to floating point arithmetic @@ -541,22 +535,19 @@ MultiThreaderBase::ParallelizeImageRegion(unsigned int { filter = nullptr; } - ProgressReporter progress(filter, 0, 1); + const ProgressReporter progress(filter, 0, 1); - struct RegionAndCallback rnc - { - funcP, dimension, index, size, filter - }; + struct RegionAndCallback rnc{ funcP, dimension, index, size, filter }; this->SetSingleMethodAndExecute(&MultiThreaderBase::ParallelizeImageRegionHelper, &rnc); } ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION MultiThreaderBase::ParallelizeImageRegionHelper(void * arg) { - auto * workUnitInfo = static_cast(arg); - ThreadIdType workUnitID = workUnitInfo->WorkUnitID; - ThreadIdType workUnitCount = workUnitInfo->NumberOfWorkUnits; - auto * rnc = static_cast(workUnitInfo->UserData); + auto * workUnitInfo = static_cast(arg); + const ThreadIdType workUnitID = workUnitInfo->WorkUnitID; + const ThreadIdType workUnitCount = workUnitInfo->NumberOfWorkUnits; + auto * rnc = static_cast(workUnitInfo->UserData); const ImageRegionSplitterBase * splitter = ImageSourceCommon::GetGlobalDefaultSplitter(); ImageIORegion region(rnc->dimension); @@ -565,7 +556,7 @@ MultiThreaderBase::ParallelizeImageRegionHelper(void * arg) region.SetIndex(d, rnc->index[d]); region.SetSize(d, rnc->size[d]); } - ThreadIdType total = splitter->GetSplit(workUnitID, workUnitCount, region); + const ThreadIdType total = splitter->GetSplit(workUnitID, workUnitCount, region); TotalProgressReporter reporter(rnc->filter, 0); diff --git a/Modules/Core/Common/src/itkNumberToString.cxx b/Modules/Core/Common/src/itkNumberToString.cxx index f9805da2b05..ca351a7880c 100644 --- a/Modules/Core/Common/src/itkNumberToString.cxx +++ b/Modules/Core/Common/src/itkNumberToString.cxx @@ -56,7 +56,7 @@ FloatingPointNumberToString(const TValue val) { itkGenericExceptionMacro("Conversion failed for " << val); } - return std::string(builder.Finalize()); + return { builder.Finalize() }; } } // namespace diff --git a/Modules/Core/Common/src/itkNumericTraits.cxx b/Modules/Core/Common/src/itkNumericTraits.cxx index 550dad4a85a..9d1d225629a 100644 --- a/Modules/Core/Common/src/itkNumericTraits.cxx +++ b/Modules/Core/Common/src/itkNumericTraits.cxx @@ -44,11 +44,11 @@ template <> const std::complex NumericTraits>::One = std::complex(1, 0); template <> -const std::complex NumericTraits>::Zero = std::complex(0, - 0); +const std::complex NumericTraits>::Zero = + std::complex(0, 0); template <> -const std::complex NumericTraits>::One = std::complex(1, - 0); +const std::complex NumericTraits>::One = + std::complex(1, 0); template <> const std::complex NumericTraits>::Zero = std::complex(0, 0); @@ -66,11 +66,11 @@ template <> const std::complex NumericTraits>::One = std::complex(1L, 0L); template <> -const std::complex NumericTraits>::Zero = std::complex(0UL, - 0UL); +const std::complex NumericTraits>::Zero = + std::complex(0UL, 0UL); template <> -const std::complex NumericTraits>::One = std::complex(1UL, - 0UL); +const std::complex NumericTraits>::One = + std::complex(1UL, 0UL); #endif // !defined(ITK_LEGACY_REMOVE) template <> diff --git a/Modules/Core/Common/src/itkNumericTraitsDiffusionTensor3DPixel.cxx b/Modules/Core/Common/src/itkNumericTraitsDiffusionTensor3DPixel.cxx index 935941a47ff..d48c4674748 100644 --- a/Modules/Core/Common/src/itkNumericTraitsDiffusionTensor3DPixel.cxx +++ b/Modules/Core/Common/src/itkNumericTraitsDiffusionTensor3DPixel.cxx @@ -31,7 +31,8 @@ namespace itk ITKCommon_EXPORT const DiffusionTensor3D NumericTraits>::Zero{}; \ template <> \ ITKCommon_EXPORT const DiffusionTensor3D NumericTraits>::One = \ - MakeFilled>(1); + MakeFilled>(1); \ + ITK_MACROEND_NOOP_STATEMENT // // List here the specializations of the Traits: diff --git a/Modules/Core/Common/src/itkNumericTraitsRGBAPixel.cxx b/Modules/Core/Common/src/itkNumericTraitsRGBAPixel.cxx index 526a161d96d..bf14e7dd142 100644 --- a/Modules/Core/Common/src/itkNumericTraitsRGBAPixel.cxx +++ b/Modules/Core/Common/src/itkNumericTraitsRGBAPixel.cxx @@ -27,11 +27,12 @@ namespace itk // Helper macro for initializing the Zero and One static member of the // NumericTraits<>. // -#define RGBAPIXELSTATICTRAITSMACRO(T) \ - template <> \ - ITKCommon_EXPORT const RGBAPixel NumericTraits>::Zero{}; \ - template <> \ - ITKCommon_EXPORT const RGBAPixel NumericTraits>::One = MakeFilled>(1); +#define RGBAPIXELSTATICTRAITSMACRO(T) \ + template <> \ + ITKCommon_EXPORT const RGBAPixel NumericTraits>::Zero{}; \ + template <> \ + ITKCommon_EXPORT const RGBAPixel NumericTraits>::One = MakeFilled>(1); \ + ITK_MACROEND_NOOP_STATEMENT // // List here the specializations of the Traits: diff --git a/Modules/Core/Common/src/itkNumericTraitsRGBPixel.cxx b/Modules/Core/Common/src/itkNumericTraitsRGBPixel.cxx index 121da6e5e3d..30013357117 100644 --- a/Modules/Core/Common/src/itkNumericTraitsRGBPixel.cxx +++ b/Modules/Core/Common/src/itkNumericTraitsRGBPixel.cxx @@ -27,11 +27,12 @@ namespace itk // Helper macro for initializing the Zero and One static member of the // NumericTraits<>. // -#define RGBPIXELSTATICTRAITSMACRO(T) \ - template <> \ - ITKCommon_EXPORT const RGBPixel NumericTraits>::Zero{}; \ - template <> \ - ITKCommon_EXPORT const RGBPixel NumericTraits>::One = MakeFilled>(1); +#define RGBPIXELSTATICTRAITSMACRO(T) \ + template <> \ + ITKCommon_EXPORT const RGBPixel NumericTraits>::Zero{}; \ + template <> \ + ITKCommon_EXPORT const RGBPixel NumericTraits>::One = MakeFilled>(1); \ + ITK_MACROEND_NOOP_STATEMENT // // List here the specializations of the Traits: diff --git a/Modules/Core/Common/src/itkObject.cxx b/Modules/Core/Common/src/itkObject.cxx index fcb49d00d31..ca5e7edb926 100644 --- a/Modules/Core/Common/src/itkObject.cxx +++ b/Modules/Core/Common/src/itkObject.cxx @@ -154,7 +154,7 @@ Object::SubjectImplementation::InvokeEvent(const EventObject & event, Object * s // m_ListModified flag. The modified flag is save to the stack and // marked false before recursively saving the current list. - SaveRestoreListModified save(this); + const SaveRestoreListModified save(this); auto i = m_Observers.crbegin(); InvokeEventRecursion(event, self, i); @@ -163,7 +163,7 @@ Object::SubjectImplementation::InvokeEvent(const EventObject & event, Object * s void Object::SubjectImplementation::InvokeEvent(const EventObject & event, const Object * self) { - SaveRestoreListModified save(this); + const SaveRestoreListModified save(this); auto i = m_Observers.crbegin(); InvokeEventRecursion(event, self, i); @@ -265,14 +265,13 @@ Object::SubjectImplementation::PrintObservers(std::ostream & os, Indent indent) Object::Pointer Object::New() { - Pointer smartPtr; Object * rawPtr = itk::ObjectFactory::Create(); if (rawPtr == nullptr) { rawPtr = new Object; } - smartPtr = rawPtr; + Pointer smartPtr = rawPtr; rawPtr->UnRegister(); return smartPtr; } @@ -361,8 +360,7 @@ Object::Modified() const void Object::Register() const { - itkDebugMacro("Registered, " - << "ReferenceCount = " << (m_ReferenceCount + 1)); + itkDebugMacro("Registered, ReferenceCount = " << (m_ReferenceCount + 1)); // call the parent Superclass::Register(); @@ -375,8 +373,7 @@ void Object::UnRegister() const noexcept { // call the parent - itkDebugMacro("UnRegistered, " - << "ReferenceCount = " << (m_ReferenceCount - 1)); + itkDebugMacro("UnRegistered, ReferenceCount = " << (m_ReferenceCount - 1)); if ((m_ReferenceCount - 1) <= 0) { @@ -456,13 +453,6 @@ Object::GetGlobalWarningDisplay() return *Object::GetGlobalWarningDisplayPointer(); } -unsigned long -Object::AddObserver(const EventObject & event, Command * cmd) -{ - const auto & thisAsConst = *this; - return thisAsConst.AddObserver(event, cmd); -} - unsigned long Object::AddObserver(const EventObject & event, Command * cmd) const { @@ -493,7 +483,7 @@ Object::GetCommand(unsigned long tag) } void -Object::RemoveObserver(unsigned long tag) +Object::RemoveObserver(unsigned long tag) const { if (this->m_SubjectImplementation) { @@ -559,10 +549,7 @@ Object::Object() this->Modified(); } -Object::~Object() -{ - itkDebugMacro("Destructing!"); -} +Object::~Object() { itkDebugMacro("Destructing!"); } /** * Chaining method to print an object's instance variables, as well as diff --git a/Modules/Core/Common/src/itkObjectFactoryBase.cxx b/Modules/Core/Common/src/itkObjectFactoryBase.cxx index cdf7f68de57..1d99d69f466 100644 --- a/Modules/Core/Common/src/itkObjectFactoryBase.cxx +++ b/Modules/Core/Common/src/itkObjectFactoryBase.cxx @@ -130,8 +130,8 @@ class ObjectFactoryBase::ObjectFactoryBasePrivate : public LightObject auto ObjectFactoryBase::GetPimplGlobalsPointer() -> ObjectFactoryBasePrivate * { - const auto deleteLambda = []() { m_PimplGlobals->UnRegister(); }; - ObjectFactoryBasePrivate * globalInstance = Singleton("ObjectFactoryBase", deleteLambda); + const auto deleteLambda = []() { m_PimplGlobals->UnRegister(); }; + auto * globalInstance = Singleton("ObjectFactoryBase", deleteLambda); if (globalInstance != m_PimplGlobals) { SynchronizeObjectFactoryBase(globalInstance); @@ -256,7 +256,7 @@ ObjectFactoryBase::LoadDynamicFactories() # ifdef _WIN32 char PathSeparator = ';'; # else - char PathSeparator = ':'; + const char PathSeparator = ':'; # endif const std::string itk_autoload_env{ "ITK_AUTOLOAD_PATH" }; @@ -286,7 +286,8 @@ ObjectFactoryBase::LoadDynamicFactories() EndSeparatorPosition = LoadPath.size() + 1; // Add 1 to simulate // having a separator } - std::string CurrentPath = LoadPath.substr(StartSeparatorPosition, EndSeparatorPosition - StartSeparatorPosition); + const std::string CurrentPath = + LoadPath.substr(StartSeparatorPosition, EndSeparatorPosition - StartSeparatorPosition); ObjectFactoryBase::LoadLibrariesInPath(CurrentPath.c_str()); @@ -320,7 +321,7 @@ CreateFullPath(const char * path, const char * file) # ifdef _WIN32 const char sep = '\\'; # else - const char sep = '/'; + constexpr char sep = '/'; # endif /** * make sure the end of path is a separator @@ -348,12 +349,12 @@ using ITK_LOAD_FUNCTION = ObjectFactoryBase * (*)(); * lower case for LibExtension values. */ inline bool -NameIsSharedLibrary(const char * name) +NameIsSharedLibrary([[maybe_unused]] const char * name) { #ifdef ITK_DYNAMIC_LOADING std::string extension = itksys::DynamicLoader::LibExtension(); - std::string sname = name; + const std::string sname = name; if (sname.rfind(extension) == sname.size() - extension.size()) { return true; @@ -368,7 +369,6 @@ NameIsSharedLibrary(const char * name) return true; } #else // ITK_DYNAMIC_LOADING - (void)name; itkGenericExceptionMacro("ITK was not built with support for dynamic loading."); #endif return false; @@ -400,8 +400,8 @@ ObjectFactoryBase::LoadLibrariesInPath(const char * path) */ if (NameIsSharedLibrary(file)) { - std::string fullpath = CreateFullPath(path, file); - LibHandle lib = DynamicLoader::OpenLibrary(fullpath.c_str()); + const std::string fullpath = CreateFullPath(path, file); + LibHandle lib = DynamicLoader::OpenLibrary(fullpath.c_str()); if (lib) { /** @@ -513,7 +513,7 @@ ObjectFactoryBase::RegisterFactory(ObjectFactoryBase * factory, InsertionPositio if (factory->m_LibraryHandle == nullptr) { - const char nonDynamicName[] = "Non-Dynamicaly loaded factory"; + constexpr char nonDynamicName[] = "Non-Dynamicaly loaded factory"; factory->m_LibraryPath = nonDynamicName; } else @@ -588,11 +588,9 @@ ObjectFactoryBase::RegisterFactory(ObjectFactoryBase * factory, InsertionPositio m_PimplGlobals->m_RegisteredFactories.insert(fitr, factory); break; } - else - { - itkGenericExceptionMacro("Position" << position << " is outside range. \ + + itkGenericExceptionMacro("Position" << position << " is outside range. \ Only " << numberOfFactories << " factories are registered"); - } } } factory->Register(); @@ -607,7 +605,7 @@ ObjectFactoryBase::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - os << indent << "Factory DLL path: " << m_LibraryPath.c_str() << '\n'; + os << indent << "Factory DLL path: " << m_LibraryPath << '\n'; os << indent << "Factory description: " << this->GetDescription() << std::endl; auto num = static_cast(m_OverrideMap->size()); @@ -616,8 +614,8 @@ ObjectFactoryBase::PrintSelf(std::ostream & os, Indent indent) const indent = indent.GetNextIndent(); for (auto & i : *m_OverrideMap) { - os << indent << "Class : " << i.first.c_str() << '\n'; - os << indent << "Overridden with: " << i.second.m_OverrideWithName.c_str() << std::endl; + os << indent << "Class : " << i.first << '\n'; + os << indent << "Overridden with: " << i.second.m_OverrideWithName << std::endl; os << indent << "Enable flag: " << i.second.m_EnabledFlag << std::endl; os << indent << "Create object: " << i.second.m_CreateObject << std::endl; os << std::endl; diff --git a/Modules/Core/Common/src/itkOctreeNode.cxx b/Modules/Core/Common/src/itkOctreeNode.cxx index 3a596913ba6..d8d4de4bdcf 100644 --- a/Modules/Core/Common/src/itkOctreeNode.cxx +++ b/Modules/Core/Common/src/itkOctreeNode.cxx @@ -31,10 +31,7 @@ OctreeNode::OctreeNode() m_Branch = nullptr; } -OctreeNode::~OctreeNode() -{ - this->RemoveChildren(); -} +OctreeNode::~OctreeNode() { this->RemoveChildren(); } OctreeNode & OctreeNode::GetChild(const LeafIdentifierEnum ChildID) const @@ -85,7 +82,6 @@ OctreeNode::SetBranch(OctreeNodeBranch * NewBranch) /** * \brief Determines if the current node is colored - * \param void * \return bool true if this node is colored */ bool @@ -99,10 +95,8 @@ OctreeNode::IsNodeColored() const return this->m_Branch >= first && this->m_Branch <= last; } - else - { - return false; - } + + return false; } void diff --git a/Modules/Core/Common/src/itkOutputWindow.cxx b/Modules/Core/Common/src/itkOutputWindow.cxx index b6890046905..d1bb319e6af 100644 --- a/Modules/Core/Common/src/itkOutputWindow.cxx +++ b/Modules/Core/Common/src/itkOutputWindow.cxx @@ -42,10 +42,7 @@ struct OutputWindowGlobals /** * Prompting off by default */ -OutputWindow::OutputWindow() -{ - m_PromptUser = false; -} +OutputWindow::OutputWindow() { m_PromptUser = false; } OutputWindow::~OutputWindow() = default; diff --git a/Modules/Core/Common/src/itkPlatformMultiThreaderPosix.cxx b/Modules/Core/Common/src/itkPlatformMultiThreaderPosix.cxx index b7199947ec6..eaf67615787 100644 --- a/Modules/Core/Common/src/itkPlatformMultiThreaderPosix.cxx +++ b/Modules/Core/Common/src/itkPlatformMultiThreaderPosix.cxx @@ -43,7 +43,6 @@ extern "C" void PlatformMultiThreader::MultipleMethodExecute() { - pthread_t process_id[ITK_MAX_THREADS]; // obey the global maximum number of threads limit @@ -65,23 +64,17 @@ PlatformMultiThreader::MultipleMethodExecute() // will call m_MultipleMethods[NumberOfWorkUnits-1](). When it is done, // it will wait for all the children to finish. // - // First, start up the m_NumberOfWorkUnits-1 processes. Keep track - // of their process ids for use later in the pthread_join call - - pthread_attr_t attr; + // First, start up the m_NumberOfWorkUnits-1 threads. Keep track + // of their thread ids for use later in the pthread_join call - pthread_attr_init(&attr); -# ifndef __CYGWIN__ - pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); -# endif for (ThreadIdType thread_loop = 1; thread_loop < m_NumberOfWorkUnits; ++thread_loop) { m_ThreadInfoArray[thread_loop].UserData = m_MultipleData[thread_loop]; m_ThreadInfoArray[thread_loop].NumberOfWorkUnits = m_NumberOfWorkUnits; - int threadError = pthread_create(&(process_id[thread_loop]), - &attr, - reinterpret_cast(m_MultipleMethod[thread_loop]), - ((void *)(&m_ThreadInfoArray[thread_loop]))); + const int threadError = pthread_create(&(process_id[thread_loop]), + nullptr, + reinterpret_cast(m_MultipleMethod[thread_loop]), + ((void *)(&m_ThreadInfoArray[thread_loop]))); if (threadError != 0) { itkExceptionMacro("Unable to create a thread. pthread_create() returned " << threadError); @@ -131,17 +124,10 @@ PlatformMultiThreader::SpawnThread(ThreadFunctionType f, void * UserData) m_SpawnedThreadInfoArray[id].ActiveFlag = &m_SpawnedThreadActiveFlag[id]; m_SpawnedThreadInfoArray[id].ActiveFlagLock = m_SpawnedThreadActiveFlagMutex[id]; - pthread_attr_t attr; - - pthread_attr_init(&attr); -# ifndef __CYGWIN__ - pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); -# endif - - int threadError = pthread_create(&(m_SpawnedThreadProcessID[id]), - &attr, - reinterpret_cast(f), - ((void *)(&m_SpawnedThreadInfoArray[id]))); + const int threadError = pthread_create(&(m_SpawnedThreadProcessID[id]), + nullptr, + reinterpret_cast(f), + ((void *)(&m_SpawnedThreadInfoArray[id]))); if (threadError != 0) { itkExceptionMacro("Unable to create a thread. pthread_create() returned " << threadError); @@ -183,17 +169,11 @@ ThreadProcessIdType PlatformMultiThreader::SpawnDispatchSingleMethodThread(PlatformMultiThreader::WorkUnitInfo * threadInfo) { // Using POSIX threads - pthread_attr_t attr; - pthread_t threadHandle; - - pthread_attr_init(&attr); -#if !defined(__CYGWIN__) - pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); -#endif - - int threadError; - threadError = pthread_create( - &threadHandle, &attr, reinterpret_cast(this->SingleMethodProxy), reinterpret_cast(threadInfo)); + pthread_t threadHandle; + const int threadError = pthread_create(&threadHandle, + nullptr, + reinterpret_cast(this->SingleMethodProxy), + reinterpret_cast(threadInfo)); if (threadError != 0) { itkExceptionMacro("Unable to create a thread. pthread_create() returned " << threadError); diff --git a/Modules/Core/Common/src/itkPlatformMultiThreaderWindows.cxx b/Modules/Core/Common/src/itkPlatformMultiThreaderWindows.cxx index dce7ba02036..e39a96e888e 100644 --- a/Modules/Core/Common/src/itkPlatformMultiThreaderWindows.cxx +++ b/Modules/Core/Common/src/itkPlatformMultiThreaderWindows.cxx @@ -40,13 +40,11 @@ namespace itk void PlatformMultiThreader::MultipleMethodExecute() { - ThreadIdType threadCount; - HANDLE processId[ITK_MAX_THREADS]; // obey the global maximum number of threads limit m_NumberOfWorkUnits = std::min(m_NumberOfWorkUnits, MultiThreaderBase::GetGlobalMaximumNumberOfThreads()); - for (threadCount = 0; threadCount < m_NumberOfWorkUnits; ++threadCount) + for (ThreadIdType threadCount = 0; threadCount < m_NumberOfWorkUnits; ++threadCount) { if (m_MultipleMethod[threadCount] == nullptr) { @@ -63,7 +61,7 @@ PlatformMultiThreader::MultipleMethodExecute() // // First, start up the m_NumberOfWorkUnits-1 processes. Keep track // of their process ids for use later in the waitid call - for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount) + for (ThreadIdType threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount) { m_ThreadInfoArray[threadCount].UserData = m_MultipleData[threadCount]; m_ThreadInfoArray[threadCount].NumberOfWorkUnits = m_NumberOfWorkUnits; @@ -84,12 +82,12 @@ PlatformMultiThreader::MultipleMethodExecute() // The parent thread has finished its method - so now it // waits for each of the other processes to // exit - for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount) + for (ThreadIdType threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount) { WaitForSingleObject(processId[threadCount], INFINITE); } // close the threads - for (threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount) + for (ThreadIdType threadCount = 1; threadCount < m_NumberOfWorkUnits; ++threadCount) { CloseHandle(processId[threadCount]); } diff --git a/Modules/Core/Common/src/itkPoolMultiThreader.cxx b/Modules/Core/Common/src/itkPoolMultiThreader.cxx index 5e829449859..27bd8277163 100644 --- a/Modules/Core/Common/src/itkPoolMultiThreader.cxx +++ b/Modules/Core/Common/src/itkPoolMultiThreader.cxx @@ -86,12 +86,10 @@ PoolMultiThreader::PoolMultiThreader() } ThreadIdType defaultThreads = std::max(1u, GetGlobalDefaultNumberOfThreads()); -#if !defined(ITKV4_COMPATIBILITY) if (defaultThreads > 1) // one work unit for only one thread { defaultThreads *= 4; } -#endif m_NumberOfWorkUnits = std::min(ITK_MAX_THREADS, defaultThreads); m_MaximumNumberOfThreads = m_ThreadPool->GetMaximumNumberOfThreads(); } @@ -109,7 +107,7 @@ void PoolMultiThreader::SetMaximumNumberOfThreads(ThreadIdType numberOfThreads) { Superclass::SetMaximumNumberOfThreads(numberOfThreads); - ThreadIdType threadCount = m_ThreadPool->GetMaximumNumberOfThreads(); + const ThreadIdType threadCount = m_ThreadPool->GetMaximumNumberOfThreads(); if (threadCount < m_MaximumNumberOfThreads) { m_ThreadPool->AddThreads(m_MaximumNumberOfThreads - threadCount); @@ -256,7 +254,7 @@ PoolMultiThreader::ParallelizeImageRegion(unsigned int dimension, else { const ImageRegionSplitterBase * splitter = ImageSourceCommon::GetGlobalDefaultSplitter(); - ThreadIdType splitCount = splitter->GetNumberOfSplits(region, m_NumberOfWorkUnits); + const ThreadIdType splitCount = splitter->GetNumberOfSplits(region, m_NumberOfWorkUnits); ProgressReporter reporter(filter, 0, splitCount); itkAssertOrThrowMacro(splitCount <= m_NumberOfWorkUnits, "Split count is greater than number of work units!"); ImageIORegion iRegion; diff --git a/Modules/Core/Common/src/itkProcessObject.cxx b/Modules/Core/Common/src/itkProcessObject.cxx index 27149b018a7..4bb4a307a8b 100644 --- a/Modules/Core/Common/src/itkProcessObject.cxx +++ b/Modules/Core/Common/src/itkProcessObject.cxx @@ -95,7 +95,8 @@ ProcessObject::MakeOutput(const DataObjectIdentifierType & name) } -DataObject::Pointer ProcessObject::MakeOutput(DataObjectPointerArraySizeType) +DataObject::Pointer +ProcessObject::MakeOutput(DataObjectPointerArraySizeType) { return static_cast(DataObject::New().GetPointer()); } @@ -344,7 +345,7 @@ ProcessObject::PushFrontInput(const DataObject * input) void ProcessObject::PopFrontInput() { - DataObjectPointerArraySizeType nb = this->GetNumberOfIndexedInputs(); + const DataObjectPointerArraySizeType nb = this->GetNumberOfIndexedInputs(); if (nb > 0) { for (DataObjectPointerArraySizeType i = 1; i < nb; ++i) @@ -425,7 +426,7 @@ ProcessObject::SetOutput(const DataObjectIdentifierType & name, DataObject * out // copy the key, because it might be destroyed in that method, so a reference // is not enough. - DataObjectIdentifierType key = name; + const DataObjectIdentifierType key = name; if (key.empty()) { @@ -433,7 +434,7 @@ ProcessObject::SetOutput(const DataObjectIdentifierType & name, DataObject * out } // does this change anything? - DataObjectPointerMap::const_iterator it = m_Outputs.find(key); + const auto it = m_Outputs.find(key); if (it != m_Outputs.end() && it->second.GetPointer() == output) { return; @@ -461,7 +462,7 @@ ProcessObject::SetOutput(const DataObjectIdentifierType & name, DataObject * out if (!m_Outputs[key]) { itkDebugMacro(" creating new output object."); - DataObjectPointer newOutput = this->MakeOutput(key); + const DataObjectPointer newOutput = this->MakeOutput(key); this->SetOutput(key, newOutput); // If we had an output object before, copy the requested region @@ -673,7 +674,7 @@ ProcessObject::GetOutputs() // only include the primary if it's required or set if (output.first != m_IndexedOutputs[0]->first || output.second.IsNotNull()) { - res.push_back(output.second.GetPointer()); + res.emplace_back(output.second.GetPointer()); } } return res; @@ -966,7 +967,7 @@ ProcessObject::GetInputs() // only include the primary if it's required or set if (input.first != m_IndexedInputs[0]->first || input.second.IsNotNull() || this->IsRequiredInputName(input.first)) { - res.push_back(input.second.GetPointer()); + res.emplace_back(input.second.GetPointer()); } } return res; @@ -1050,12 +1051,10 @@ ProcessObject::MakeNameFromIndex(DataObjectPointerArraySizeType idx) const { if (idx < ITK_GLOBAL_INDEX_NAMES_NUMBER) { - return ProcessObject::DataObjectIdentifierType(globalIndexNames[idx]); - } - else - { - return '_' + std::to_string(idx); + return { globalIndexNames[idx] }; } + + return '_' + std::to_string(idx); } @@ -1086,14 +1085,14 @@ ProcessObject::MakeIndexFromOutputName(const DataObjectIdentifierType & name) co ProcessObject::DataObjectPointerArraySizeType ProcessObject::MakeIndexFromName(const DataObjectIdentifierType & name) const { - DataObjectIdentifierType baseName = "_"; - DataObjectPointerArraySizeType baseSize = baseName.size(); + const DataObjectIdentifierType baseName = "_"; + const DataObjectPointerArraySizeType baseSize = baseName.size(); if (name.size() <= baseSize || name.substr(0, baseSize) != baseName) { itkDebugMacro("MakeIndexFromName(" << name << ") -> exception bad base name"); itkExceptionMacro("Not an indexed data object: " << name); } - DataObjectIdentifierType idxStr = name.substr(baseSize); + const DataObjectIdentifierType idxStr = name.substr(baseSize); DataObjectPointerArraySizeType idx; if (!(std::istringstream(idxStr) >> idx)) { @@ -1155,11 +1154,11 @@ void ProcessObject::IncrementProgress(float increment) { // Clamp the value to be between 0 and 1. - uint32_t integerIncrement = progressFloatToFixed(increment); + const uint32_t integerIncrement = progressFloatToFixed(increment); - uint32_t oldProgress = m_Progress.fetch_add(integerIncrement); + const uint32_t oldProgress = m_Progress.fetch_add(integerIncrement); - uint32_t updatedProgress = m_Progress; + const uint32_t updatedProgress = m_Progress; // check if progress overflowed if (oldProgress > updatedProgress) @@ -1203,7 +1202,7 @@ ProcessObject::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); - Indent indent2 = indent.GetNextIndent(); + const Indent indent2 = indent.GetNextIndent(); if (!m_Inputs.empty()) { os << indent << "Inputs: " << std::endl; @@ -1268,10 +1267,9 @@ ProcessObject::PrintSelf(std::ostream & os, Indent indent) const } os << indent << "NumberOfRequiredOutputs: " << m_NumberOfRequiredOutputs << std::endl; - os << indent << "Number Of Work Units: " << m_NumberOfWorkUnits << std::endl; - os << indent << "ReleaseDataFlag: " << (this->GetReleaseDataFlag() ? "On" : "Off") << std::endl; - os << indent << "ReleaseDataBeforeUpdateFlag: " << (m_ReleaseDataBeforeUpdateFlag ? "On" : "Off") << std::endl; - os << indent << "AbortGenerateData: " << (m_AbortGenerateData ? "On" : "Off") << std::endl; + os << indent << "NumberOfWorkUnits: " << m_NumberOfWorkUnits << std::endl; + itkPrintSelfBooleanMacro(ReleaseDataBeforeUpdateFlag); + itkPrintSelfBooleanMacro(AbortGenerateData); os << indent << "Progress: " << progressFixedToFloat(m_Progress) << std::endl; os << indent << "Multithreader: " << std::endl; m_MultiThreader->PrintSelf(os, indent.GetNextIndent()); @@ -1327,7 +1325,7 @@ ProcessObject::PropagateResetPipeline() void -ProcessObject::VerifyPreconditions() ITKv5_CONST +ProcessObject::VerifyPreconditions() const { /** * Make sure that all the required named inputs are there and non null @@ -1356,7 +1354,7 @@ ProcessObject::VerifyPreconditions() ITKv5_CONST void -ProcessObject::VerifyInputInformation() ITKv5_CONST +ProcessObject::VerifyInputInformation() const {} @@ -1573,9 +1571,9 @@ ProcessObject::SetMultiThreader(MultiThreaderType * threader) } else { - ThreadIdType oldDefaultNumber = m_MultiThreader->GetNumberOfWorkUnits(); + const ThreadIdType oldDefaultNumber = m_MultiThreader->GetNumberOfWorkUnits(); this->m_MultiThreader = threader; - ThreadIdType newDefaultNumber = m_MultiThreader->GetNumberOfWorkUnits(); + const ThreadIdType newDefaultNumber = m_MultiThreader->GetNumberOfWorkUnits(); if (m_NumberOfWorkUnits == oldDefaultNumber) { m_NumberOfWorkUnits = newDefaultNumber; diff --git a/Modules/Core/Common/src/itkProgressAccumulator.cxx b/Modules/Core/Common/src/itkProgressAccumulator.cxx index c1e40e1a8f2..d86565b2b3b 100644 --- a/Modules/Core/Common/src/itkProgressAccumulator.cxx +++ b/Modules/Core/Common/src/itkProgressAccumulator.cxx @@ -32,17 +32,14 @@ ProgressAccumulator::ProgressAccumulator() m_CallbackCommand->SetCallbackFunction(this, &Self::ReportProgress); } -ProgressAccumulator::~ProgressAccumulator() -{ - UnregisterAllFilters(); -} +ProgressAccumulator::~ProgressAccumulator() { UnregisterAllFilters(); } void ProgressAccumulator::RegisterInternalFilter(GenericFilterType * filter, float weight) { // Observe the filter - unsigned long progressTag = filter->AddObserver(ProgressEvent(), m_CallbackCommand); - unsigned long startTag = filter->AddObserver(StartEvent(), m_CallbackCommand); + const unsigned long progressTag = filter->AddObserver(ProgressEvent(), m_CallbackCommand); + const unsigned long startTag = filter->AddObserver(StartEvent(), m_CallbackCommand); // Create a record for the filter struct FilterRecord record; @@ -60,12 +57,11 @@ void ProgressAccumulator::UnregisterAllFilters() { // The filters should no longer be observing us - FilterRecordVector::iterator it; - for (it = m_FilterRecord.begin(); it != m_FilterRecord.end(); ++it) + for (auto & it : m_FilterRecord) { - it->Filter->RemoveObserver(it->ProgressObserverTag); - it->Filter->RemoveObserver(it->StartObserverTag); + it.Filter->RemoveObserver(it.ProgressObserverTag); + it.Filter->RemoveObserver(it.StartObserverTag); } // Clear the filter array @@ -85,8 +81,7 @@ ProgressAccumulator::ResetProgress() m_BaseAccumulatedProgress = 0.0f; // Reset each of the individual progress meters - FilterRecordVector::iterator it; - for (it = m_FilterRecord.begin(); it != m_FilterRecord.end(); ++it) + for (auto it = m_FilterRecord.begin(); it != m_FilterRecord.end(); ++it) { it->Filter->UpdateProgress(0.0f); } @@ -104,8 +99,8 @@ ProgressAccumulator::ResetFilterProgressAndKeepAccumulatedProgress() void ProgressAccumulator::ReportProgress(Object * who, const EventObject & event) { - ProgressEvent pe; - StartEvent se; + const ProgressEvent pe; + const StartEvent se; if (typeid(event) == typeid(pe)) { @@ -113,14 +108,13 @@ ProgressAccumulator::ReportProgress(Object * who, const EventObject & event) m_AccumulatedProgress = m_BaseAccumulatedProgress; // Add up the new progress from different filters. - FilterRecordVector::iterator it; - for (it = m_FilterRecord.begin(); it != m_FilterRecord.end(); ++it) + for (auto & it : m_FilterRecord) { - float progress = it->Filter->GetProgress(); - if (progress != it->AccumulatedProgress) + const float progress = it.Filter->GetProgress(); + if (progress != it.AccumulatedProgress) { - m_AccumulatedProgress += progress * it->Weight; - it->AccumulatedProgress = 0.0; // this filter is now active + m_AccumulatedProgress += progress * it.Weight; + it.AccumulatedProgress = 0.0; // this filter is now active } // else skip this filter, as it has finished } @@ -132,12 +126,11 @@ ProgressAccumulator::ReportProgress(Object * who, const EventObject & event) if (m_MiniPipelineFilter->GetAbortGenerateData()) { // Abort the filter that is reporting progress - FilterRecordVector::iterator fit; - for (fit = m_FilterRecord.begin(); fit != m_FilterRecord.end(); ++fit) + for (auto & fit : m_FilterRecord) { - if (who == fit->Filter) + if (who == fit.Filter) { - fit->Filter->AbortGenerateDataOn(); + fit.Filter->AbortGenerateDataOn(); } } } @@ -151,17 +144,16 @@ ProgressAccumulator::ReportProgress(Object * who, const EventObject & event) // By capturing the start event, it is no longer necessary for filters that use the ProgressAccumulator // to explicitly call ResetFilterProgressAndKeepAccumulatedProgress(). - FilterRecordVector::iterator it; - for (it = m_FilterRecord.begin(); it != m_FilterRecord.end(); ++it) + for (auto & it : m_FilterRecord) { - if (who == it->Filter) + if (who == it.Filter) { // On a start event, we need to capture the accumulated progress for this filter // and then reset this filter's progress. // It is not necessary to call UpdateProgress(0.0f) explicitly on the filter because this is done // automatically when the filter is restarted. - it->AccumulatedProgress = it->Filter->GetProgress(); - m_BaseAccumulatedProgress += it->AccumulatedProgress * it->Weight; + it.AccumulatedProgress = it.Filter->GetProgress(); + m_BaseAccumulatedProgress += it.AccumulatedProgress * it.Weight; } } } diff --git a/Modules/Core/Common/src/itkProgressReporter.cxx b/Modules/Core/Common/src/itkProgressReporter.cxx index e16be9d8934..30dc86a8e00 100644 --- a/Modules/Core/Common/src/itkProgressReporter.cxx +++ b/Modules/Core/Common/src/itkProgressReporter.cxx @@ -29,7 +29,6 @@ ProgressReporter::ProgressReporter(ProcessObject * filter, float progressWeight) : m_Filter(filter) , m_ThreadId(threadId) - , m_CurrentPixel(0) , m_InitialProgress(initialProgress) , m_ProgressWeight(progressWeight) { @@ -65,8 +64,8 @@ ProgressReporter::~ProgressReporter() // Set the progress to the end of its current range. // Make sure it increases the progress, in case multiple reporters // were used inside filter's GenerateData(). - float newProgress = m_InitialProgress + m_ProgressWeight; - float oldProgress = m_Filter->GetProgress(); + const float newProgress = m_InitialProgress + m_ProgressWeight; + const float oldProgress = m_Filter->GetProgress(); if (newProgress > oldProgress) { m_Filter->UpdateProgress(m_InitialProgress + m_ProgressWeight); diff --git a/Modules/Core/Common/src/itkProgressTransformer.cxx b/Modules/Core/Common/src/itkProgressTransformer.cxx index a87a069e517..098905722b4 100644 --- a/Modules/Core/Common/src/itkProgressTransformer.cxx +++ b/Modules/Core/Common/src/itkProgressTransformer.cxx @@ -39,7 +39,7 @@ class DummyProcess : public itk::ProcessObject ProgressTransformer::ProgressTransformer(float start, float end, ProcessObject * targetFilter) : m_TargetFilter(targetFilter) - , m_ProgressTag(0) + { m_Start = std::clamp(start, 0.0f, 1.0f); m_End = std::clamp(end, 0.0f, 1.0f); diff --git a/Wrapping/Generators/Python/PyUtils/itkPyCommand.cxx b/Modules/Core/Common/src/itkPyCommand.cxx similarity index 87% rename from Wrapping/Generators/Python/PyUtils/itkPyCommand.cxx rename to Modules/Core/Common/src/itkPyCommand.cxx index 74a51e1f428..9bf1480dbf4 100644 --- a/Wrapping/Generators/Python/PyUtils/itkPyCommand.cxx +++ b/Modules/Core/Common/src/itkPyCommand.cxx @@ -47,14 +47,14 @@ PyCommand::~PyCommand() { if (this->m_Object) { - PyGILStateEnsure gil; + const PyGILStateEnsure gil; Py_DECREF(this->m_Object); } this->m_Object = nullptr; if (this->m_EmptyArgumentList) { - PyGILStateEnsure gil; + const PyGILStateEnsure gil; Py_DECREF(this->m_EmptyArgumentList); } this->m_EmptyArgumentList = nullptr; @@ -66,7 +66,7 @@ PyCommand::SetCommandCallable(PyObject * o) { if (o != this->m_Object) { - PyGILStateEnsure gil; + const PyGILStateEnsure gil; if (this->m_Object) { // get rid of our reference @@ -116,13 +116,12 @@ PyCommand::PyExecute() // we throw a standard ITK exception: this makes it possible for // 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."); + itkExceptionMacro("CommandCallable is not a callable Python object, or it has not been set."); } else { - PyGILStateEnsure gil; - PyObject * result = PyObject_Call(this->m_Object, this->m_EmptyArgumentList, (PyObject *)nullptr); + const PyGILStateEnsure gil; + PyObject * result = PyObject_Call(this->m_Object, this->m_EmptyArgumentList, (PyObject *)nullptr); if (result) { @@ -134,8 +133,7 @@ PyCommand::PyExecute() PyErr_Print(); // make sure the invoking Python code knows there was a problem // by raising an exception - itkExceptionMacro("There was an error executing the " - << "CommandCallable."); + itkExceptionMacro("There was an error executing the CommandCallable."); } } } diff --git a/Modules/Core/Common/src/itkRealTimeClock.cxx b/Modules/Core/Common/src/itkRealTimeClock.cxx index 81b4793d43f..90a1fd03b22 100644 --- a/Modules/Core/Common/src/itkRealTimeClock.cxx +++ b/Modules/Core/Common/src/itkRealTimeClock.cxx @@ -85,7 +85,7 @@ RealTimeClock::GetTimeInSeconds() const struct timeval tval; ::gettimeofday(&tval, nullptr); - TimeStampType value = + const TimeStampType value = static_cast(tval.tv_sec) + static_cast(tval.tv_usec) / m_Frequency; return value; #endif // defined(WIN32) || defined(_WIN32) diff --git a/Modules/Core/Common/src/itkSimpleFilterWatcher.cxx b/Modules/Core/Common/src/itkSimpleFilterWatcher.cxx index d7a322759ba..d50fa5ccd35 100644 --- a/Modules/Core/Common/src/itkSimpleFilterWatcher.cxx +++ b/Modules/Core/Common/src/itkSimpleFilterWatcher.cxx @@ -52,10 +52,7 @@ SimpleFilterWatcher::SimpleFilterWatcher() {} -SimpleFilterWatcher::SimpleFilterWatcher(const SimpleFilterWatcher & watch) -{ - this->DeepCopy(watch); -} +SimpleFilterWatcher::SimpleFilterWatcher(const SimpleFilterWatcher & watch) { this->DeepCopy(watch); } SimpleFilterWatcher & SimpleFilterWatcher::operator=(const SimpleFilterWatcher & watch) diff --git a/Modules/Core/Common/src/itkSmapsFileParser.cxx b/Modules/Core/Common/src/itkSmapsFileParser.cxx index 9a2f2ce8d50..261c1d8cf1d 100644 --- a/Modules/Core/Common/src/itkSmapsFileParser.cxx +++ b/Modules/Core/Common/src/itkSmapsFileParser.cxx @@ -20,7 +20,7 @@ namespace itk { bool ITKCommon_EXPORT - ci_equal(char a, char b) +ci_equal(char a, char b) { return tolower(static_cast(a)) == tolower(static_cast(b)); } @@ -54,25 +54,30 @@ ITKCommon_EXPORT std::istream & // Get name std::istringstream stream(headerline); - std::string address, perms, offset, device; - int inode = -1; + + int inode = -1; // the header is defined with the following expression: "address permissions // offset device inode [name]" + std::string address; + stream >> address; if (!stream.good()) { itkGenericExceptionMacro("bad address: " << address); } + std::string perms; stream >> perms; if (!stream.good()) { itkGenericExceptionMacro("bad perms: " << perms); } + std::string offset; stream >> offset; if (!stream.good()) { itkGenericExceptionMacro("bad offset: " << offset); } + std::string device; stream >> device; if (!stream.good()) { @@ -343,10 +348,7 @@ struct MapRecordConditionalPlusor /** --- MapData --- **/ /** MadData destructor */ -MapData::~MapData() -{ - this->Reset(); -} +MapData::~MapData() { this->Reset(); } MapData::MemoryLoadType MapData::GetTotalMemoryUsage() diff --git a/Modules/Core/Common/src/itkSpatialOrientationAdapter.cxx b/Modules/Core/Common/src/itkSpatialOrientationAdapter.cxx index e7e19898d68..9e522f6835e 100644 --- a/Modules/Core/Common/src/itkSpatialOrientationAdapter.cxx +++ b/Modules/Core/Common/src/itkSpatialOrientationAdapter.cxx @@ -132,8 +132,7 @@ SpatialOrientationAdapter::ToDirectionCosines(const OrientationType & Or) (static_cast(Or) >> static_cast(SpatialOrientationEnums::CoordinateMajornessTerms::ITK_COORDINATE_TertiaryMinor)) & 0xff); - DirectionType direction; - direction.Fill(0.0); + DirectionType direction{}; for (unsigned int i = 0; i < DirectionType::ColumnDimensions; ++i) { switch (terms[i]) @@ -145,25 +144,25 @@ SpatialOrientationAdapter::ToDirectionCosines(const OrientationType & Or) direction[0][i] = -1; break; case CoordinateTerms::ITK_COORDINATE_Anterior: - if (DirectionType::RowDimensions > 1) + if constexpr (DirectionType::RowDimensions > 1) { direction[1][i] = 1; } break; case CoordinateTerms::ITK_COORDINATE_Posterior: - if (DirectionType::RowDimensions > 1) + if constexpr (DirectionType::RowDimensions > 1) { direction[1][i] = -1; } break; case CoordinateTerms::ITK_COORDINATE_Inferior: - if (DirectionType::RowDimensions > 2) + if constexpr (DirectionType::RowDimensions > 2) { direction[2][i] = 1; } break; case CoordinateTerms::ITK_COORDINATE_Superior: - if (DirectionType::RowDimensions > 2) + if constexpr (DirectionType::RowDimensions > 2) { direction[2][i] = -1; } diff --git a/Modules/Core/Common/src/itkStdStreamLogOutput.cxx b/Modules/Core/Common/src/itkStdStreamLogOutput.cxx index 5969058c27e..b5f83935f0d 100644 --- a/Modules/Core/Common/src/itkStdStreamLogOutput.cxx +++ b/Modules/Core/Common/src/itkStdStreamLogOutput.cxx @@ -21,10 +21,7 @@ namespace itk { /** Constructor */ -StdStreamLogOutput::StdStreamLogOutput() -{ - this->m_Stream = nullptr; -} +StdStreamLogOutput::StdStreamLogOutput() { this->m_Stream = nullptr; } /** Destructor */ StdStreamLogOutput::~StdStreamLogOutput() @@ -67,7 +64,7 @@ StdStreamLogOutput::Write(double timestamp) /** Write to a buffer */ void -StdStreamLogOutput::Write(std::string const & content) +StdStreamLogOutput::Write(const std::string & content) { const std::lock_guard lockGuard(m_Mutex); if (this->m_Stream) @@ -78,7 +75,7 @@ StdStreamLogOutput::Write(std::string const & content) /** Write to a buffer */ void -StdStreamLogOutput::Write(std::string const & content, double timestamp) +StdStreamLogOutput::Write(const std::string & content, double timestamp) { const std::lock_guard lockGuard(m_Mutex); if (this->m_Stream) diff --git a/Modules/Core/Common/src/itkStreamingProcessObject.cxx b/Modules/Core/Common/src/itkStreamingProcessObject.cxx index c70ab967ae8..141dadf2632 100644 --- a/Modules/Core/Common/src/itkStreamingProcessObject.cxx +++ b/Modules/Core/Common/src/itkStreamingProcessObject.cxx @@ -36,7 +36,7 @@ StreamingProcessObject::GenerateData() // minimum of what the user specified via SetNumberOfStreamDivisions() // and what the Splitter thinks is a reasonable value. // - unsigned int numberOfInputRequestRegion = this->GetNumberOfInputRequestedRegions(); + const unsigned int numberOfInputRequestRegion = this->GetNumberOfInputRequestedRegions(); // // Loop over the number of pieces, execute the upstream pipeline on each diff --git a/Modules/Core/Common/src/itkTBBMultiThreader.cxx b/Modules/Core/Common/src/itkTBBMultiThreader.cxx index 8fa18d81a56..03b844ea342 100644 --- a/Modules/Core/Common/src/itkTBBMultiThreader.cxx +++ b/Modules/Core/Common/src/itkTBBMultiThreader.cxx @@ -35,7 +35,7 @@ get_default_num_threads() #if __TBB_MIC_OFFLOAD # pragma offload target(mic) out(default_num_threads) #endif // __TBB_MIC_OFFLOAD - static const size_t default_num_threads = + const static size_t default_num_threads = tbb::global_control::active_value(tbb::global_control::max_allowed_parallelism); return static_cast(default_num_threads); } @@ -47,14 +47,10 @@ namespace itk TBBMultiThreader::TBBMultiThreader() { ThreadIdType defaultThreads = std::max(1u, GetGlobalDefaultNumberOfThreads()); -#if defined(ITKV4_COMPATIBILITY) - m_NumberOfWorkUnits = defaultThreads; -#else if (defaultThreads > 1) // one work unit for only one thread { m_NumberOfWorkUnits = 16 * defaultThreads; } -#endif } TBBMultiThreader::~TBBMultiThreader() = default; diff --git a/Modules/Core/Common/src/itkThreadLogger.cxx b/Modules/Core/Common/src/itkThreadLogger.cxx index dfc2d5d9135..eff0b6f7a4c 100644 --- a/Modules/Core/Common/src/itkThreadLogger.cxx +++ b/Modules/Core/Common/src/itkThreadLogger.cxx @@ -50,7 +50,7 @@ Logger::PriorityLevelEnum ThreadLogger::GetPriorityLevel() const { const std::lock_guard lockGuard(m_Mutex); - PriorityLevelEnum level = this->m_PriorityLevel; + const PriorityLevelEnum level = this->m_PriorityLevel; return level; } @@ -67,7 +67,7 @@ Logger::PriorityLevelEnum ThreadLogger::GetLevelForFlushing() const { const std::lock_guard lockGuard(m_Mutex); - PriorityLevelEnum level = this->m_LevelForFlushing; + const PriorityLevelEnum level = this->m_LevelForFlushing; return level; } @@ -82,7 +82,7 @@ ThreadLogger::DelayType ThreadLogger::GetDelay() const { const std::lock_guard lockGuard(m_Mutex); - DelayType delay = this->m_Delay; + const DelayType delay = this->m_Delay; return delay; } @@ -91,11 +91,11 @@ ThreadLogger::AddLogOutput(OutputType * output) { const std::lock_guard lockGuard(m_Mutex); this->m_OperationQ.push(ADD_LOG_OUTPUT); - this->m_OutputQ.push(output); + this->m_OutputQ.emplace(output); } void -ThreadLogger::Write(PriorityLevelEnum level, std::string const & content) +ThreadLogger::Write(PriorityLevelEnum level, const std::string & content) { const std::lock_guard lockGuard(m_Mutex); this->m_OperationQ.push(WRITE); diff --git a/Modules/Core/Common/src/itkThreadPool.cxx b/Modules/Core/Common/src/itkThreadPool.cxx index 57065659fa3..1b4dd517eb7 100644 --- a/Modules/Core/Common/src/itkThreadPool.cxx +++ b/Modules/Core/Common/src/itkThreadPool.cxx @@ -111,7 +111,7 @@ ThreadPool::ThreadPool() m_PimplGlobals->m_ThreadPoolInstance = this; // threads need this m_PimplGlobals->m_ThreadPoolInstance->UnRegister(); // Remove extra reference - ThreadIdType threadCount = MultiThreaderBase::GetGlobalDefaultNumberOfThreads(); + const ThreadIdType threadCount = MultiThreaderBase::GetGlobalDefaultNumberOfThreads(); m_Threads.reserve(threadCount); for (ThreadIdType i = 0; i < threadCount; ++i) { @@ -179,8 +179,8 @@ ThreadPool::PrepareForFork() void ThreadPool::ResumeFromFork() { - ThreadPool * instance = m_PimplGlobals->m_ThreadPoolInstance.GetPointer(); - ThreadIdType threadCount = instance->m_Threads.size(); + ThreadPool * instance = m_PimplGlobals->m_ThreadPoolInstance.GetPointer(); + const ThreadIdType threadCount = instance->m_Threads.size(); instance->m_Threads.clear(); instance->m_Stopping = false; instance->AddThreads(threadCount); diff --git a/Modules/Core/Common/src/itkThreadedIndexedContainerPartitioner.cxx b/Modules/Core/Common/src/itkThreadedIndexedContainerPartitioner.cxx index 679bf275436..b50e4f558ed 100644 --- a/Modules/Core/Common/src/itkThreadedIndexedContainerPartitioner.cxx +++ b/Modules/Core/Common/src/itkThreadedIndexedContainerPartitioner.cxx @@ -34,9 +34,9 @@ ThreadedIndexedContainerPartitioner::PartitionDomain(const ThreadIdType threadId // completeIndexRange and subIndexRange are inclusive // determine the actual number of pieces that will be generated - const auto count = static_cast(completeIndexRange[1] - completeIndexRange[0] + 1); - auto valuesPerThread = Math::Ceil(count / static_cast(requestedTotal)); - ThreadIdType maxThreadIdUsed = Math::Ceil(count / static_cast(valuesPerThread)) - 1; + const auto count = static_cast(completeIndexRange[1] - completeIndexRange[0] + 1); + auto valuesPerThread = Math::Ceil(count / static_cast(requestedTotal)); + const ThreadIdType maxThreadIdUsed = Math::Ceil(count / static_cast(valuesPerThread)) - 1; // Split the index range if (threadId < maxThreadIdUsed) diff --git a/Modules/Core/Common/src/itkTotalProgressReporter.cxx b/Modules/Core/Common/src/itkTotalProgressReporter.cxx index 4d318abd092..95424afe32a 100644 --- a/Modules/Core/Common/src/itkTotalProgressReporter.cxx +++ b/Modules/Core/Common/src/itkTotalProgressReporter.cxx @@ -26,7 +26,6 @@ TotalProgressReporter::TotalProgressReporter(ProcessObject * filter, SizeValueType numberOfUpdates, float progressWeight) : m_Filter(filter) - , m_CurrentPixel(0) , m_ProgressWeight(progressWeight) { // Make sure we have at least one pixel. @@ -51,7 +50,7 @@ TotalProgressReporter::TotalProgressReporter(ProcessObject * filter, //---------------------------------------------------------------------------- TotalProgressReporter::~TotalProgressReporter() { - SizeValueType pixelRemnants = m_PixelsPerUpdate - m_PixelsBeforeUpdate; + const SizeValueType pixelRemnants = m_PixelsPerUpdate - m_PixelsBeforeUpdate; if (pixelRemnants != 0 && m_Filter) { diff --git a/Modules/Core/Common/src/itkVector.cxx b/Modules/Core/Common/src/itkVector.cxx index 44259f07492..8481814507a 100644 --- a/Modules/Core/Common/src/itkVector.cxx +++ b/Modules/Core/Common/src/itkVector.cxx @@ -28,7 +28,7 @@ namespace itk */ Vector ITKCommon_EXPORT - CrossProduct(const Vector & a, const Vector & b) +CrossProduct(const Vector & a, const Vector & b) { Vector c; c[0] = a[1] * b[2] - a[2] * b[1]; @@ -38,7 +38,7 @@ Vector ITKCommon_EXPORT } Vector ITKCommon_EXPORT - CrossProduct(const Vector & a, const Vector & b) +CrossProduct(const Vector & a, const Vector & b) { Vector c; c[0] = a[1] * b[2] - a[2] * b[1]; @@ -48,7 +48,7 @@ Vector ITKCommon_EXPORT } Vector ITKCommon_EXPORT - CrossProduct(const Vector & a, const Vector & b) +CrossProduct(const Vector & a, const Vector & b) { Vector c; c[0] = a[1] * b[2] - a[2] * b[1]; diff --git a/Modules/Core/Common/src/itkWin32OutputWindow.cxx b/Modules/Core/Common/src/itkWin32OutputWindow.cxx index 4e2b4ceb7bf..9e151d3ffc6 100644 --- a/Modules/Core/Common/src/itkWin32OutputWindow.cxx +++ b/Modules/Core/Common/src/itkWin32OutputWindow.cxx @@ -44,7 +44,7 @@ Win32OutputWindow::~Win32OutputWindow() /** */ LRESULT APIENTRY - Win32OutputWindow::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) +Win32OutputWindow::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { diff --git a/Modules/Core/Common/test/CMakeLists.txt b/Modules/Core/Common/test/CMakeLists.txt index 78846a40f49..ecc27127c65 100644 --- a/Modules/Core/Common/test/CMakeLists.txt +++ b/Modules/Core/Common/test/CMakeLists.txt @@ -1714,6 +1714,7 @@ if(ITK_BUILD_SHARED_LIBS AND ITK_DYNAMIC_LOADING) endif() set(ITKCommonGTests + itkArrayGTest.cxx itkArray2DGTest.cxx itkAggregateTypesGTest.cxx itkBitCastGTest.cxx @@ -1735,6 +1736,7 @@ set(ITKCommonGTests itkImageIORegionGTest.cxx itkImageRandomConstIteratorWithIndexGTest.cxx itkImageRegionGTest.cxx + itkImageRegionIteratorGTest.cxx itkIndexGTest.cxx itkIndexRangeGTest.cxx itkLightObjectGTest.cxx @@ -1747,6 +1749,7 @@ set(ITKCommonGTests itkOffsetGTest.cxx itkOptimizerParametersGTest.cxx itkPointGTest.cxx + itkPointSetGTest.cxx itkRGBAPixelGTest.cxx itkRGBPixelGTest.cxx itkShapedImageNeighborhoodRangeGTest.cxx @@ -1758,7 +1761,9 @@ set(ITKCommonGTests itkWeakPointerGTest.cxx itkCommonTypeTraitsGTest.cxx itkMetaDataDictionaryGTest.cxx - itkSpatialOrientationAdaptorGTest.cxx) + itkSpatialOrientationAdaptorGTest.cxx + itkAnatomicalOrientationGTest.cxx +) creategoogletestdriver(ITKCommon "${ITKCommon-Test_LIBRARIES}" "${ITKCommonGTests}") # If `-static` was passed to CMAKE_EXE_LINKER_FLAGS, compilation fails. No need to # test this case. diff --git a/Modules/Core/Common/test/ClientTestLibraryA.cxx b/Modules/Core/Common/test/ClientTestLibraryA.cxx index dd74216e99b..d8c8be3d5b4 100644 --- a/Modules/Core/Common/test/ClientTestLibraryA.cxx +++ b/Modules/Core/Common/test/ClientTestLibraryA.cxx @@ -26,14 +26,14 @@ namespace template int -dynamic_castDownCast(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCast(const char * type, const char * instanceSource, const itk::Object * base) { using DerivedType = TDerived; static constexpr int passed = 0; static constexpr int failed = 1; - DerivedType const * derived = dynamic_cast(base); + const DerivedType * derived = dynamic_cast(base); if (derived != nullptr) { std::cout << type << " cast in library A for an instance from " << instanceSource << "\tsucceeded." @@ -49,7 +49,7 @@ dynamic_castDownCast(const char * type, const char * instanceSource, itk::Object namespace LibraryA { -ITKObjectProducer ::ITKObjectProducer() +ITKObjectProducer::ITKObjectProducer() { m_EquivalencyTable = itk::EquivalencyTable::New(); using ImageType = itk::Image; @@ -69,14 +69,14 @@ ITKObjectProducer::Image() } int -dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, const itk::Object * base) { using EquivalencyTableType = itk::EquivalencyTable; return dynamic_castDownCast(type, instanceSource, base); } int -dynamic_castDownCastImage(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCastImage(const char * type, const char * instanceSource, const itk::Object * base) { using ImageType = itk::Image; return dynamic_castDownCast(type, instanceSource, base); diff --git a/Modules/Core/Common/test/ClientTestLibraryA.h b/Modules/Core/Common/test/ClientTestLibraryA.h index 302280c2b19..3092c85ac5b 100644 --- a/Modules/Core/Common/test/ClientTestLibraryA.h +++ b/Modules/Core/Common/test/ClientTestLibraryA.h @@ -43,10 +43,10 @@ class ClientTestLibraryA_EXPORT ITKObjectProducer }; int ClientTestLibraryA_EXPORT - dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, itk::Object const * base); +dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, const itk::Object * base); int ClientTestLibraryA_EXPORT - dynamic_castDownCastImage(const char * type, const char * instanceSource, itk::Object const * base); +dynamic_castDownCastImage(const char * type, const char * instanceSource, const itk::Object * base); } // end namespace LibraryA diff --git a/Modules/Core/Common/test/ClientTestLibraryB.cxx b/Modules/Core/Common/test/ClientTestLibraryB.cxx index 1260bb1a361..c0282aec331 100644 --- a/Modules/Core/Common/test/ClientTestLibraryB.cxx +++ b/Modules/Core/Common/test/ClientTestLibraryB.cxx @@ -26,14 +26,14 @@ namespace template int -dynamic_castDownCast(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCast(const char * type, const char * instanceSource, const itk::Object * base) { using DerivedType = TDerived; static constexpr int passed = 0; static constexpr int failed = 1; - DerivedType const * derived = dynamic_cast(base); + const DerivedType * derived = dynamic_cast(base); if (derived != nullptr) { std::cout << type << " cast in library B for an instance from " << instanceSource << "\tsucceeded." @@ -49,7 +49,7 @@ dynamic_castDownCast(const char * type, const char * instanceSource, itk::Object namespace LibraryB { -ITKObjectProducer ::ITKObjectProducer() +ITKObjectProducer::ITKObjectProducer() { m_EquivalencyTable = itk::EquivalencyTable::New(); using ImageType = itk::Image; @@ -74,7 +74,7 @@ ITKObjectProducer::Image() int -dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, const itk::Object * base) { using EquivalencyTableType = itk::EquivalencyTable; return dynamic_castDownCast(type, instanceSource, base); @@ -82,7 +82,7 @@ dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSou int -dynamic_castDownCastImage(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCastImage(const char * type, const char * instanceSource, const itk::Object * base) { using ImageType = itk::Image; return dynamic_castDownCast(type, instanceSource, base); diff --git a/Modules/Core/Common/test/ClientTestLibraryB.h b/Modules/Core/Common/test/ClientTestLibraryB.h index 204d38ebeaf..36e792bf446 100644 --- a/Modules/Core/Common/test/ClientTestLibraryB.h +++ b/Modules/Core/Common/test/ClientTestLibraryB.h @@ -31,9 +31,9 @@ extern "C" Image(); ITK_ABI_EXPORT int - dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, itk::Object const * base); + dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, const itk::Object * base); ITK_ABI_EXPORT int - dynamic_castDownCastImage(const char * type, const char * instanceSource, itk::Object const * base); + dynamic_castDownCastImage(const char * type, const char * instanceSource, const itk::Object * base); } namespace LibraryB diff --git a/Modules/Core/Common/test/ClientTestLibraryC.cxx b/Modules/Core/Common/test/ClientTestLibraryC.cxx index d6441dea385..c87edf99139 100644 --- a/Modules/Core/Common/test/ClientTestLibraryC.cxx +++ b/Modules/Core/Common/test/ClientTestLibraryC.cxx @@ -26,14 +26,14 @@ namespace template int -dynamic_castDownCast(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCast(const char * type, const char * instanceSource, const itk::Object * base) { using DerivedType = TDerived; static constexpr int passed = 0; static constexpr int failed = 1; - DerivedType const * derived = dynamic_cast(base); + const DerivedType * derived = dynamic_cast(base); if (derived != nullptr) { std::cout << type << " cast in library C for an instance from " << instanceSource << "\tsucceeded." @@ -49,7 +49,7 @@ dynamic_castDownCast(const char * type, const char * instanceSource, itk::Object namespace LibraryC { -ITKObjectProducer ::ITKObjectProducer() +ITKObjectProducer::ITKObjectProducer() { m_EquivalencyTable = itk::EquivalencyTable::New(); using ImageType = itk::Image; @@ -69,14 +69,14 @@ ITKObjectProducer::Image() } int -dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, const itk::Object * base) { using EquivalencyTableType = itk::EquivalencyTable; return dynamic_castDownCast(type, instanceSource, base); } int -dynamic_castDownCastImage(const char * type, const char * instanceSource, itk::Object const * base) +dynamic_castDownCastImage(const char * type, const char * instanceSource, const itk::Object * base) { using ImageType = itk::Image; return dynamic_castDownCast(type, instanceSource, base); diff --git a/Modules/Core/Common/test/ClientTestLibraryC.h b/Modules/Core/Common/test/ClientTestLibraryC.h index a9a8a5be4fc..350bde3ce15 100644 --- a/Modules/Core/Common/test/ClientTestLibraryC.h +++ b/Modules/Core/Common/test/ClientTestLibraryC.h @@ -43,10 +43,10 @@ class ClientTestLibraryC_EXPORT ITKObjectProducer }; int ClientTestLibraryC_EXPORT - dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, itk::Object const * base); +dynamic_castDownCastEquivalencyTable(const char * type, const char * instanceSource, const itk::Object * base); int ClientTestLibraryC_EXPORT - dynamic_castDownCastImage(const char * type, const char * instanceSource, itk::Object const * base); +dynamic_castDownCastImage(const char * type, const char * instanceSource, const itk::Object * base); } // end namespace LibraryC diff --git a/Modules/Core/Common/test/SharedTestLibraryA.cxx b/Modules/Core/Common/test/SharedTestLibraryA.cxx index 81da43b5373..ae45ad0db1d 100644 --- a/Modules/Core/Common/test/SharedTestLibraryA.cxx +++ b/Modules/Core/Common/test/SharedTestLibraryA.cxx @@ -21,5 +21,5 @@ void bar() { using ImageType = itk::Image; - ImageType::Pointer image = ImageType::New(); + const ImageType::Pointer image = ImageType::New(); } diff --git a/Modules/Core/Common/test/SharedTestLibraryA.h b/Modules/Core/Common/test/SharedTestLibraryA.h index f8ebf69e00d..b823c17b2e2 100644 --- a/Modules/Core/Common/test/SharedTestLibraryA.h +++ b/Modules/Core/Common/test/SharedTestLibraryA.h @@ -23,6 +23,6 @@ #include void SharedTestLibraryA_EXPORT - bar(); +bar(); #endif diff --git a/Modules/Core/Common/test/SharedTestLibraryB.cxx b/Modules/Core/Common/test/SharedTestLibraryB.cxx index b939073cd99..b98bf044447 100644 --- a/Modules/Core/Common/test/SharedTestLibraryB.cxx +++ b/Modules/Core/Common/test/SharedTestLibraryB.cxx @@ -21,5 +21,5 @@ void foo() { using ImageType = itk::Image; - ImageType::Pointer image = ImageType::New(); + const ImageType::Pointer image = ImageType::New(); } diff --git a/Modules/Core/Common/test/SharedTestLibraryB.h b/Modules/Core/Common/test/SharedTestLibraryB.h index 9a00b166d75..add865bb3f7 100644 --- a/Modules/Core/Common/test/SharedTestLibraryB.h +++ b/Modules/Core/Common/test/SharedTestLibraryB.h @@ -23,6 +23,6 @@ #include void SharedTestLibraryB_EXPORT - foo(); +foo(); #endif diff --git a/Modules/Core/Common/test/VNLSparseLUSolverTraitsTest.cxx b/Modules/Core/Common/test/VNLSparseLUSolverTraitsTest.cxx index 17b975b59b2..7a3ba7537a9 100644 --- a/Modules/Core/Common/test/VNLSparseLUSolverTraitsTest.cxx +++ b/Modules/Core/Common/test/VNLSparseLUSolverTraitsTest.cxx @@ -59,8 +59,8 @@ VNLSparseLUSolverTraitsTest(int, char *[]) /** * Build the linear system to solve */ - unsigned int N = 3; - VectorType Bx = SolverTraits::InitializeVector(N); + constexpr unsigned int N = 3; + VectorType Bx = SolverTraits::InitializeVector(N); Bx.fill(0.); Bx[0] = 2.1; @@ -86,7 +86,7 @@ VNLSparseLUSolverTraitsTest(int, char *[]) /** * Define the tolerance and expected results */ - CoordinateType tolerance = 1e-9; + constexpr CoordinateType tolerance = 1e-9; VectorType Xexpected(N); Xexpected(0) = 1.575; diff --git a/Modules/Core/Common/test/itkAbortProcessObjectTest.cxx b/Modules/Core/Common/test/itkAbortProcessObjectTest.cxx index d0556dc8437..253c52d01c2 100644 --- a/Modules/Core/Common/test/itkAbortProcessObjectTest.cxx +++ b/Modules/Core/Common/test/itkAbortProcessObjectTest.cxx @@ -35,7 +35,7 @@ bool onAbortCalled = false; void onProgress(itk::Object * obj, const itk::EventObject &, void *) { - itk::ProcessObject::Pointer p(dynamic_cast(obj)); + const itk::ProcessObject::Pointer p(dynamic_cast(obj)); if (p.IsNull()) { return; @@ -64,9 +64,9 @@ itkAbortProcessObjectTest(int, char *[]) auto img = ShortImage::New(); // fill in an image - const ShortImage::IndexType index = { { 0, 0 } }; - const ShortImage::SizeType size = { { 100, 100 } }; - ShortImage::RegionType region{ index, size }; + constexpr ShortImage::IndexType index = { { 0, 0 } }; + constexpr ShortImage::SizeType size = { { 100, 100 } }; + const ShortImage::RegionType region{ index, size }; img->SetRegions(region); img->Allocate(); @@ -80,22 +80,22 @@ itkAbortProcessObjectTest(int, char *[]) } // Create a filter - itk::ExtractImageFilter::Pointer extract; - extract = itk::ExtractImageFilter::New(); + const itk::ExtractImageFilter::Pointer extract = + itk::ExtractImageFilter::New(); extract->SetInput(img); // fill in an image - ShortImage::IndexType extractIndex = { { 0, 0 } }; - ShortImage::SizeType extractSize = { { 99, 99 } }; - ShortImage::RegionType extractRegion{ extractIndex, extractSize }; + constexpr ShortImage::IndexType extractIndex = { { 0, 0 } }; + constexpr ShortImage::SizeType extractSize = { { 99, 99 } }; + const ShortImage::RegionType extractRegion{ extractIndex, extractSize }; extract->SetExtractionRegion(extractRegion); - itk::CStyleCommand::Pointer progressCmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer progressCmd = itk::CStyleCommand::New(); progressCmd->SetCallback(onProgress); progressCmd->SetObjectName("Progress Event"); extract->AddObserver(itk::ProgressEvent(), progressCmd); - itk::CStyleCommand::Pointer abortCmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer abortCmd = itk::CStyleCommand::New(); abortCmd->SetCallback(onAbort); abortCmd->SetObjectName("Abort Event"); extract->AddObserver(itk::AbortEvent(), abortCmd); diff --git a/Modules/Core/Common/test/itkAdaptorComparisonTest.cxx b/Modules/Core/Common/test/itkAdaptorComparisonTest.cxx index 95f9443ca10..fc477ef4a36 100644 --- a/Modules/Core/Common/test/itkAdaptorComparisonTest.cxx +++ b/Modules/Core/Common/test/itkAdaptorComparisonTest.cxx @@ -84,18 +84,15 @@ BypassAdaptorSupportModifyScalars(itk::Image * img) void AdaptorSupportedModifyVectors(itk::Image, 3> * img) { - using VectorType = itk::Vector; constexpr unsigned int N = 3; - unsigned int i; - VectorType temp_vector; + using VectorType = itk::Vector; itk::ImageRegionIteratorWithIndex> it(img, img->GetRequestedRegion()); while (!it.IsAtEnd()) { - temp_vector = it.Get(); - - for (i = 0; i < N; ++i) + VectorType temp_vector = it.Get(); + for (unsigned int i = 0; i < N; ++i) { temp_vector[i] += 3.435f; } @@ -108,42 +105,36 @@ AdaptorSupportedModifyVectors(itk::Image, 3> * img) void NoAdaptorSupportModifyVectors(itk::Image, 3> * img) { - using VectorType = itk::Vector; constexpr unsigned int N = 3; - unsigned int i; - VectorType temp_vector; + using VectorType = itk::Vector; itk::ImageRegionIterator> it(img, img->GetRequestedRegion()); while (!it.IsAtEnd()) { - temp_vector = it.Get(); + VectorType temp_vector = it.Get(); - for (i = 0; i < N; ++i) + for (unsigned int i = 0; i < N; ++i) { temp_vector[i] += 3.435f; } it.Set(temp_vector); ++it; - - // for (i = 0; i, 3> * img) { - using VectorType = itk::Vector; constexpr unsigned int N = 3; - unsigned int i; + using VectorType = itk::Vector; itk::ImageRegionIteratorWithIndex> it(img, img->GetRequestedRegion()); while (!it.IsAtEnd()) { - for (i = 0; i < N; ++i) + for (unsigned int i = 0; i < N; ++i) { (it.Value())[i] += 3.435f; } @@ -156,19 +147,17 @@ BypassAdaptorSupportModifyVectors(itk::Image, 3> * img) void BypassNoAdaptorSupportModifyVectors(itk::Image, 3> * img) { - using VectorType = itk::Vector; constexpr unsigned int N = 3; - unsigned int i; + using VectorType = itk::Vector; itk::ImageRegionIterator> it(img, img->GetRequestedRegion()); while (!it.IsAtEnd()) { - for (i = 0; i < N; ++i) + for (unsigned int i = 0; i < N; ++i) { (it.Value())[i] += 3.435f; } - ++it; } } @@ -180,8 +169,6 @@ itkAdaptorComparisonTest(int, char *[]) using ScalarImageType = itk::Image; using VectorImageType = itk::Image, 3>; - clock_t start, stop, no_adaptor_comp, adaptor_comp; - // Set up some images itk::ImageRegion<3> region; itk::Size<3> size; @@ -204,70 +191,80 @@ itkAdaptorComparisonTest(int, char *[]) vector_image->SetRegions(region); vector_image->Allocate(); - VectorImageType::PixelType initialVectorValue; - initialVectorValue.Fill(1.2345); // arbitrary value; + auto initialVectorValue = itk::MakeFilled(1.2345); // arbitrary value; vector_image->FillBuffer(initialVectorValue); // Time trials std::cout << "Speed of adaptor supporting iterator (for reference) \t"; - start = clock(); - AdaptorSupportedIteratorSpeed(scalar_image); - stop = clock(); - adaptor_comp = stop - start; - std::cout << adaptor_comp << std::endl; - - std::cout << "Speed of iterator that does not support adaptors (for reference) \t"; - start = clock(); - NoAdaptorSupportIteratorSpeed(scalar_image); - stop = clock(); - no_adaptor_comp = stop - start; - std::cout << no_adaptor_comp << std::endl; - std::cout << "Modifying scalar image using adaptor iterator...\t"; - start = clock(); - AdaptorSupportedModifyScalars(scalar_image); - stop = clock(); - std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; - - std::cout << "Modifying scalar image using non-adaptor iterator...\t"; - start = clock(); - NoAdaptorSupportModifyScalars(scalar_image); - stop = clock(); - std::cout << (stop - start) << "\t compensated = " << (stop - start) - no_adaptor_comp << std::endl; - - std::cout << "Modifying vector image using adaptor iterator...\t"; - start = clock(); - AdaptorSupportedModifyVectors(vector_image); - stop = clock(); - std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; - - std::cout << "Modifying vector image using non-adaptor iterator...\t"; - start = clock(); - NoAdaptorSupportModifyVectors(vector_image); - stop = clock(); - std::cout << (stop - start) << "\t compensated = " << (stop - start) - no_adaptor_comp << std::endl; - - std::cout << "Modifying scalar image bypassing adaptor api using" - << " adaptor iterator...\t"; - start = clock(); - BypassAdaptorSupportModifyScalars(scalar_image); - stop = clock(); - std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; - - std::cout << "Modifying vector image bypassing adaptor api using" - << " non-adaptor iterator...\t"; - start = clock(); - BypassNoAdaptorSupportModifyVectors(vector_image); - stop = clock(); - std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; - - std::cout << "Modifying vector image bypassing adaptor api using" - << " adaptor iterator...\t"; - start = clock(); - BypassAdaptorSupportModifyVectors(vector_image); - stop = clock(); - std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; + const clock_t adaptor_comp = [&]() -> auto { + const auto start = clock(); + AdaptorSupportedIteratorSpeed(scalar_image); + const auto stop = clock(); + return stop - start; + }(); + std::cout << adaptor_comp << std::endl; + const clock_t no_adaptor_comp = [=](auto scalarImage) { + std::cout << "Speed of iterator that does not support adaptors (for reference) \t"; + const auto start = clock(); + NoAdaptorSupportIteratorSpeed(scalarImage); + const auto stop = clock(); + return stop - start; + }(scalar_image); + std::cout << no_adaptor_comp << std::endl; + { + std::cout << "Modifying scalar image using adaptor iterator...\t"; + const auto start = clock(); + AdaptorSupportedModifyScalars(scalar_image); + const auto stop = clock(); + std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; + } + { + std::cout << "Modifying scalar image using non-adaptor iterator...\t"; + const auto start = clock(); + NoAdaptorSupportModifyScalars(scalar_image); + const auto stop = clock(); + std::cout << (stop - start) << "\t compensated = " << (stop - start) - no_adaptor_comp << std::endl; + } + { + std::cout << "Modifying vector image using adaptor iterator...\t"; + const auto start = clock(); + AdaptorSupportedModifyVectors(vector_image); + const auto stop = clock(); + std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; + } + { + std::cout << "Modifying vector image using non-adaptor iterator...\t"; + const auto start = clock(); + NoAdaptorSupportModifyVectors(vector_image); + const auto stop = clock(); + std::cout << (stop - start) << "\t compensated = " << (stop - start) - no_adaptor_comp << std::endl; + } + { + std::cout << "Modifying scalar image bypassing adaptor api using" + << " adaptor iterator...\t"; + const auto start = clock(); + BypassAdaptorSupportModifyScalars(scalar_image); + const auto stop = clock(); + std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; + } + { + std::cout << "Modifying vector image bypassing adaptor api using" + << " non-adaptor iterator...\t"; + const auto start = clock(); + BypassNoAdaptorSupportModifyVectors(vector_image); + const auto stop = clock(); + std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; + } + { + std::cout << "Modifying vector image bypassing adaptor api using" + << " adaptor iterator...\t"; + const auto start = clock(); + BypassAdaptorSupportModifyVectors(vector_image); + const auto stop = clock(); + std::cout << (stop - start) << "\t compensated = " << (stop - start) - adaptor_comp << std::endl; + } return EXIT_SUCCESS; } diff --git a/Modules/Core/Common/test/itkAggregateTypesGTest.cxx b/Modules/Core/Common/test/itkAggregateTypesGTest.cxx index 58d583ae2f9..299f44e71cd 100644 --- a/Modules/Core/Common/test/itkAggregateTypesGTest.cxx +++ b/Modules/Core/Common/test/itkAggregateTypesGTest.cxx @@ -85,8 +85,8 @@ IO const Self & operator-=(const OffsetType & offset) IO const Self operator-(const OffsetType & off) const IO const OffsetType operator-(const Self & vec) const -IO inline void CopyWithRound(const FixedArray & point) -IO inline void CopyWithCast(const FixedArray & point) +IO inline void CopyWithRound(const FixedArray & point) +IO inline void CopyWithCast(const FixedArray & point) Index I void SetIndex(const IndexValueType val[VDimension]) @@ -288,12 +288,9 @@ class CommonIndexOffsetMathOps //============ Test Copy with Round/Cast Type ==================================== { AggregateType known3s{ { 3, 3, 3, 3 } }; - AggregateType threes; - - threes.Fill(0); - AggregateType known4s{ { 4, 4, 4, 4 } }; - itk::Point p1; - p1.Fill(3.5); + AggregateType threes{}; + AggregateType known4s{ { 4, 4, 4, 4 } }; + auto p1 = itk::MakeFilled>(3.5); threes.CopyWithRound(p1); ITK_EXPECT_VECTOR_NEAR(threes, known4s, 0); @@ -332,16 +329,16 @@ TEST(Specialized, Index) using IndexType = itk::Index<4>; - const IndexType zeroBasis = { { 1, 0, 0, 0 } }; - const IndexType oneBasis = { { 0, 1, 0, 0 } }; - const IndexType twoBasis = { { 0, 0, 1, 0 } }; - const IndexType threeBasis = { { 0, 0, 0, 1 } }; + constexpr IndexType zeroBasis = { { 1, 0, 0, 0 } }; + constexpr IndexType oneBasis = { { 0, 1, 0, 0 } }; + constexpr IndexType twoBasis = { { 0, 0, 1, 0 } }; + constexpr IndexType threeBasis = { { 0, 0, 0, 1 } }; ITK_EXPECT_VECTOR_NEAR(IndexType::GetBasisIndex(0), zeroBasis, 0); ITK_EXPECT_VECTOR_NEAR(IndexType::GetBasisIndex(1), oneBasis, 0); ITK_EXPECT_VECTOR_NEAR(IndexType::GetBasisIndex(2), twoBasis, 0); ITK_EXPECT_VECTOR_NEAR(IndexType::GetBasisIndex(3), threeBasis, 0); - IndexType known3s{ { 3, 3, 3, 3 } }; + constexpr IndexType known3s{ { 3, 3, 3, 3 } }; IndexType threes; IndexType::IndexValueType raw3s[4] = { 3, 3, 3, 3 }; threes.SetIndex(raw3s); @@ -356,18 +353,18 @@ TEST(Specialized, Offset) using OffsetType = itk::Offset<4>; - const OffsetType zeroBasis = { { 1, 0, 0, 0 } }; - const OffsetType oneBasis = { { 0, 1, 0, 0 } }; - const OffsetType twoBasis = { { 0, 0, 1, 0 } }; - const OffsetType threeBasis = { { 0, 0, 0, 1 } }; + constexpr OffsetType zeroBasis = { { 1, 0, 0, 0 } }; + constexpr OffsetType oneBasis = { { 0, 1, 0, 0 } }; + constexpr OffsetType twoBasis = { { 0, 0, 1, 0 } }; + constexpr OffsetType threeBasis = { { 0, 0, 0, 1 } }; ITK_EXPECT_VECTOR_NEAR(OffsetType::GetBasisOffset(0), zeroBasis, 0); ITK_EXPECT_VECTOR_NEAR(OffsetType::GetBasisOffset(1), oneBasis, 0); ITK_EXPECT_VECTOR_NEAR(OffsetType::GetBasisOffset(2), twoBasis, 0); ITK_EXPECT_VECTOR_NEAR(OffsetType::GetBasisOffset(3), threeBasis, 0); - OffsetType known3s{ { 3, 3, 3, 3 } }; - OffsetType threes; - OffsetType::OffsetValueType raw3s[4] = { 3, 3, 3, 3 }; + constexpr OffsetType known3s{ { 3, 3, 3, 3 } }; + OffsetType threes; + constexpr OffsetType::OffsetValueType raw3s[4] = { 3, 3, 3, 3 }; threes.SetOffset(raw3s); ITK_EXPECT_VECTOR_NEAR(threes, known3s, 0); } @@ -378,9 +375,9 @@ TEST(Specialized, Size) EXPECT_EQ(itk::Size<7>::GetSizeDimension(), 7); using SizeType = itk::Size<4>; - SizeType known3s{ { 3, 3, 3, 3 } }; - SizeType threes; - SizeType::SizeValueType raw3s[4] = { 3, 3, 3, 3 }; + constexpr SizeType known3s{ { 3, 3, 3, 3 } }; + SizeType threes; + constexpr SizeType::SizeValueType raw3s[4] = { 3, 3, 3, 3 }; threes.SetSize(raw3s); ITK_EXPECT_VECTOR_NEAR(threes, known3s, 0); } diff --git a/Modules/Core/Common/test/itkAnatomicalOrientationGTest.cxx b/Modules/Core/Common/test/itkAnatomicalOrientationGTest.cxx new file mode 100644 index 00000000000..0460a39aff7 --- /dev/null +++ b/Modules/Core/Common/test/itkAnatomicalOrientationGTest.cxx @@ -0,0 +1,269 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * 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 + * + * https://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 + +#include "itkGTest.h" +#ifndef ITK_FUTURE_LEGACY_REMOVE +# define ITK_LEGACY_SILENT +#endif +#include "itkAnatomicalOrientation.h" +#include "itkImage.h" +#include + + +TEST(AnatomicalOrientation, ConstructionAndValues) +{ + using itk::AnatomicalOrientation; + using OE = AnatomicalOrientation::PositiveEnum; + using NOE = AnatomicalOrientation::NegativeEnum; + using CE = AnatomicalOrientation::CoordinateEnum; + using ImageType = itk::Image; + + ImageType::DirectionType d; + + AnatomicalOrientation do1(OE::LPS); + + EXPECT_EQ("LPS", do1.GetAsPositiveStringEncoding()); + EXPECT_EQ(CE::RightToLeft, do1.GetPrimaryTerm()); + EXPECT_EQ(CE::AnteriorToPosterior, do1.GetSecondaryTerm()); + EXPECT_EQ(CE::InferiorToSuperior, do1.GetTertiaryTerm()); + EXPECT_EQ(OE::LPS, do1.GetAsPositiveOrientation()); + EXPECT_EQ(NOE::RAI, do1.GetAsNegativeOrientation()); + + d.SetIdentity(); + EXPECT_EQ(d, do1.GetAsDirection()); + + + do1 = AnatomicalOrientation::CreateFromPositiveStringEncoding("RAS"); + + EXPECT_EQ("RAS", do1.GetAsPositiveStringEncoding()); + EXPECT_EQ(CE::LeftToRight, do1.GetPrimaryTerm()); + EXPECT_EQ(CE::PosteriorToAnterior, do1.GetSecondaryTerm()); + EXPECT_EQ(CE::InferiorToSuperior, do1.GetTertiaryTerm()); + EXPECT_EQ(OE::RAS, do1.GetAsPositiveOrientation()); + EXPECT_EQ(NOE::LPI, do1.GetAsNegativeOrientation()); + + d.Fill(0.0); + d(0, 0) = -1.0; + d(1, 1) = -1.0; + d(2, 2) = 1.0; + EXPECT_EQ(d, do1.GetAsDirection()); + + + do1 = AnatomicalOrientation::CreateFromPositiveStringEncoding("rai"); + + EXPECT_EQ("RAI", do1.GetAsPositiveStringEncoding()); + EXPECT_EQ(CE::LeftToRight, do1.GetPrimaryTerm()); + EXPECT_EQ(CE::PosteriorToAnterior, do1.GetSecondaryTerm()); + EXPECT_EQ(CE::SuperiorToInferior, do1.GetTertiaryTerm()); + EXPECT_EQ(OE::RAI, do1.GetAsPositiveOrientation()); + EXPECT_EQ(NOE::LPS, do1.GetAsNegativeOrientation()); + + + do1 = AnatomicalOrientation::CreateFromNegativeStringEncoding("LPI"); + + EXPECT_EQ("RAS", do1.GetAsPositiveStringEncoding()); + EXPECT_EQ("LPI", do1.GetAsNegativeStringEncoding()); + EXPECT_EQ(CE::LeftToRight, do1.GetPrimaryTerm()); + EXPECT_EQ(CE::PosteriorToAnterior, do1.GetSecondaryTerm()); + EXPECT_EQ(CE::InferiorToSuperior, do1.GetTertiaryTerm()); + EXPECT_EQ(OE::RAS, do1.GetAsPositiveOrientation()); + EXPECT_EQ(NOE::LPI, do1.GetAsNegativeOrientation()); + + do1 = AnatomicalOrientation(OE::PIR); + + EXPECT_EQ("PIR", do1.GetAsPositiveStringEncoding()); + EXPECT_EQ(CE::AnteriorToPosterior, do1.GetPrimaryTerm()); + EXPECT_EQ(CE::SuperiorToInferior, do1.GetSecondaryTerm()); + EXPECT_EQ(CE::LeftToRight, do1.GetTertiaryTerm()); + EXPECT_EQ(OE::PIR, do1.GetAsPositiveOrientation()); + EXPECT_EQ(NOE::ASL, do1.GetAsNegativeOrientation()); + + d.Fill(0.0); + d(1, 0) = 1.0; + d(2, 1) = -1.0; + d(0, 2) = -1.0; + EXPECT_EQ(d, do1.GetAsDirection()); + + const AnatomicalOrientation do2(d); + + EXPECT_EQ("PIR", do2.GetAsPositiveStringEncoding()); + EXPECT_EQ(CE::AnteriorToPosterior, do2.GetPrimaryTerm()); + EXPECT_EQ(CE::SuperiorToInferior, do2.GetSecondaryTerm()); + EXPECT_EQ(CE::LeftToRight, do2.GetTertiaryTerm()); + EXPECT_EQ(OE::PIR, do2.GetAsPositiveOrientation()); + EXPECT_EQ(NOE::ASL, do2.GetAsNegativeOrientation()); + + EXPECT_EQ(d, do2.GetAsDirection()); + + const AnatomicalOrientation do3 = AnatomicalOrientation::CreateFromPositiveStringEncoding("something invalid"); + EXPECT_EQ("INVALID", do3.GetAsPositiveStringEncoding()); + EXPECT_EQ(CE::UNKNOWN, do3.GetPrimaryTerm()); + EXPECT_EQ(CE::UNKNOWN, do3.GetSecondaryTerm()); + EXPECT_EQ(CE::UNKNOWN, do3.GetTertiaryTerm()); + EXPECT_EQ(OE::INVALID, do3.GetAsPositiveOrientation()); + EXPECT_EQ(NOE::INVALID, do3.GetAsNegativeOrientation()); +} + + +TEST(AnatomicalOrientation, ConvertDirectionToPositiveEnum) +{ + using itk::AnatomicalOrientation; + using OE = AnatomicalOrientation::PositiveEnum; + using ImageType = itk::Image; + ImageType::DirectionType d; + d.SetIdentity(); + + EXPECT_EQ(OE::LPS, AnatomicalOrientation(d)); + + d.Fill(0.0); + d(0, 0) = -1.0; + d(1, 1) = -1.0; + d(2, 2) = -1.0; + EXPECT_EQ(OE::RAI, AnatomicalOrientation(d)); + + d.Fill(0.0); + d(2, 0) = 1; + d(0, 1) = 1; + d(1, 2) = 1; + EXPECT_EQ(OE::SLP, AnatomicalOrientation(d)); + + d.Fill(0.0); + d(1, 0) = 1; + d(2, 1) = 1; + d(0, 2) = 1; + EXPECT_EQ(OE::PSL, AnatomicalOrientation(d)); + + d.Fill(0.0); + d(0, 0) = 1; + d(2, 1) = 1; + d(1, 2) = 1; + EXPECT_EQ(OE::LSP, AnatomicalOrientation(d)); + + d.Fill(0.0); + d(1, 0) = 1; + d(0, 1) = 1; + d(2, 2) = 1; + EXPECT_EQ(OE::PLS, AnatomicalOrientation(d)); + + d.Fill(0.0); + d(2, 0) = 1; + d(1, 1) = 1; + d(0, 2) = 1; + EXPECT_EQ(OE::SPL, AnatomicalOrientation(d)); + + constexpr itk::SpacePrecisionType data[] = { 0.5986634407395047, 0.22716302314740483, -0.768113953548866, + 0.5627936241740271, 0.563067040943212, 0.6051601804419384, + 0.5699696670095713, -0.794576911518317, 0.20924175102261847 }; + const ImageType::DirectionType::InternalMatrixType m{ data }; + d.GetVnlMatrix() = m; + EXPECT_EQ(OE::PIR, AnatomicalOrientation(d)); +} + +TEST(AnatomicalOrientation, ConvertPositiveEnumToDirection) +{ + using itk::AnatomicalOrientation; + using ImageType = itk::Image; + using OE = AnatomicalOrientation::PositiveEnum; + + ImageType::DirectionType d; + d.SetIdentity(); + + EXPECT_EQ(d, AnatomicalOrientation(OE::LPS).GetAsDirection()); + + d.Fill(0.0); + d(0, 0) = -1.0; + d(1, 1) = -1.0; + d(2, 2) = -1.0; + EXPECT_EQ(d, AnatomicalOrientation(OE::RAI).GetAsDirection()); + + d.Fill(0.0); + d(2, 0) = 1; + d(0, 1) = 1; + d(1, 2) = 1; + EXPECT_EQ(d, AnatomicalOrientation(OE::SLP).GetAsDirection()); + + d.Fill(0.0); + d(1, 0) = 1; + d(2, 1) = 1; + d(0, 2) = 1; + EXPECT_EQ(d, AnatomicalOrientation(OE::PSL).GetAsDirection()); + + d.Fill(0.0); + d(0, 0) = 1; + d(2, 1) = 1; + d(1, 2) = 1; + EXPECT_EQ(d, AnatomicalOrientation(OE::LSP).GetAsDirection()); + + d.Fill(0.0); + d(1, 0) = 1; + d(0, 1) = 1; + d(2, 2) = 1; + EXPECT_EQ(d, AnatomicalOrientation(OE::PLS).GetAsDirection()); + + d.Fill(0.0); + d(2, 0) = 1; + d(1, 1) = 1; + d(0, 2) = 1; + EXPECT_EQ(d, AnatomicalOrientation(OE::SPL).GetAsDirection()); +} + +TEST(AntomicalOrientation, ToFromEnumInteroperability) +{ + + using OE = itk::AnatomicalOrientation::PositiveEnum; + using FromOE = itk::AnatomicalOrientation::NegativeEnum; + using CE = itk::AnatomicalOrientation::CoordinateEnum; + + static_assert(int(OE::RAI) == int(FromOE::LPS)); + static_assert(int(OE::LPS) == int(FromOE::RAI)); + static_assert(int(OE::RAS) == int(FromOE::LPI)); + static_assert(int(OE::LPI) == int(FromOE::RAS)); + static_assert(int(OE::PIR) == int(FromOE::ASL)); + static_assert(int(OE::ASL) == int(FromOE::PIR)); + + constexpr itk::AnatomicalOrientation itk_rai(FromOE::RAI); + + EXPECT_EQ(itk_rai, itk::AnatomicalOrientation(OE::LPS)); + EXPECT_EQ(itk_rai.GetAsPositiveOrientation(), OE::LPS); + EXPECT_EQ(itk_rai.GetAsPositiveStringEncoding(), "LPS"); + constexpr std::array expected_terms = { { CE::RightToLeft, CE::AnteriorToPosterior, CE::InferiorToSuperior } }; + EXPECT_EQ(itk_rai.GetTerms(), expected_terms); +} + +#ifndef ITK_FUTURE_LEGACY_REMOVE +# include "itkSpatialOrientation.h" +TEST(AnatomicalOrientation, LegacyInteroperability) +{ + + using OE = itk::AnatomicalOrientation::PositiveEnum; + using SOE = itk::SpatialOrientationEnums::ValidCoordinateOrientations; + + // byte for byte compatibility, may assist with migration of bindings when types are not strictly enforced. + static_assert(int(SOE::ITK_COORDINATE_ORIENTATION_RAI) == int(OE::LPS)); + static_assert(int(SOE::ITK_COORDINATE_ORIENTATION_LPS) == int(OE::RAI)); + static_assert(int(SOE::ITK_COORDINATE_ORIENTATION_RSA) == int(OE::LIP)); + static_assert(int(SOE::ITK_COORDINATE_ORIENTATION_ASL) == int(OE::PIR)); + + const itk::AnatomicalOrientation itk_rai(SOE::ITK_COORDINATE_ORIENTATION_RAI); + EXPECT_EQ(itk_rai, OE::LPS); + EXPECT_EQ(itk_rai.GetAsPositiveOrientation(), OE::LPS); + EXPECT_EQ(itk_rai.GetAsPositiveStringEncoding(), "LPS"); +} +#endif diff --git a/Modules/Core/Common/test/itkAnnulusOperatorTest.cxx b/Modules/Core/Common/test/itkAnnulusOperatorTest.cxx index f217176e676..31155af9ca7 100644 --- a/Modules/Core/Common/test/itkAnnulusOperatorTest.cxx +++ b/Modules/Core/Common/test/itkAnnulusOperatorTest.cxx @@ -26,7 +26,7 @@ itkAnnulusOperatorTest(int, char *[]) // Save the format stream variables for std::cout // They will be restored when coutState goes out of scope // scope. - itk::StdStreamStateSave coutState(std::cout); + const itk::StdStreamStateSave coutState(std::cout); constexpr unsigned int Dimension = 2; using PixelType = float; @@ -41,7 +41,7 @@ itkAnnulusOperatorTest(int, char *[]) normalizedAnnulus.SetInnerRadius(3); normalizedAnnulus.SetThickness(2); - const bool brightCenter = false; + constexpr bool brightCenter = false; ITK_TEST_SET_GET_BOOLEAN((&normalizedAnnulus), BrightCenter, brightCenter); try @@ -70,11 +70,10 @@ itkAnnulusOperatorTest(int, char *[]) std::cout << std::endl; std::cout << "Annulus, N = " << normalizedAnnulusSize << ", r = " << normalizedAnnulus.GetInnerRadius() << ", t = " << normalizedAnnulus.GetThickness() << std::endl; - unsigned int i, j, k; - for (i = 0, k = 0; i < normalizedAnnulusSize[1]; ++i) + for (unsigned int i = 0, k = 0; i < normalizedAnnulusSize[1]; ++i) { - for (j = 0; j < normalizedAnnulusSize[0]; ++j, ++k) + for (unsigned int j = 0; j < normalizedAnnulusSize[0]; ++j, ++k) { std::cout.width(6); std::cout.precision(3); @@ -85,16 +84,16 @@ itkAnnulusOperatorTest(int, char *[]) // Compute again having the center bright std::cout << std::endl << std::endl; - std::cout << "Rebuiling annulus with a bright center"; + std::cout << "Rebuilding annulus with a bright center"; normalizedAnnulus.BrightCenterOn(); normalizedAnnulus.CreateOperator(); std::cout << ", N = " << normalizedAnnulusSize << ", r = " << normalizedAnnulus.GetInnerRadius() << ", t = " << normalizedAnnulus.GetThickness() << std::endl; - for (i = 0, k = 0; i < normalizedAnnulusSize[1]; ++i) + for (unsigned int i = 0, k = 0; i < normalizedAnnulusSize[1]; ++i) { - for (j = 0; j < normalizedAnnulusSize[0]; ++j, ++k) + for (unsigned int j = 0; j < normalizedAnnulusSize[0]; ++j, ++k) { std::cout.width(6); std::cout.precision(3); @@ -108,26 +107,26 @@ itkAnnulusOperatorTest(int, char *[]) std::cout << "Creating an annulus by specifying values"; OperatorType annulus; - const bool normalize = false; + constexpr bool normalize = false; ITK_TEST_SET_GET_BOOLEAN((&annulus), Normalize, normalize); - const double innerRadius = 2; + constexpr double innerRadius = 2; annulus.SetInnerRadius(innerRadius); ITK_TEST_SET_GET_VALUE(innerRadius, annulus.GetInnerRadius()); - const double thickness = 1; + constexpr double thickness = 1; annulus.SetThickness(thickness); ITK_TEST_SET_GET_VALUE(thickness, annulus.GetThickness()); - const typename OperatorType::PixelType exteriorValue = 1; + constexpr typename OperatorType::PixelType exteriorValue = 1; annulus.SetExteriorValue(exteriorValue); ITK_TEST_SET_GET_VALUE(exteriorValue, annulus.GetExteriorValue()); - const typename OperatorType::PixelType annulusValue = 8; + constexpr typename OperatorType::PixelType annulusValue = 8; annulus.SetAnnulusValue(annulusValue); ITK_TEST_SET_GET_VALUE(annulusValue, annulus.GetAnnulusValue()); - const typename OperatorType::PixelType interiorValue = 4; + constexpr typename OperatorType::PixelType interiorValue = 4; annulus.SetInteriorValue(interiorValue); ITK_TEST_SET_GET_VALUE(interiorValue, annulus.GetInteriorValue()); @@ -139,9 +138,9 @@ itkAnnulusOperatorTest(int, char *[]) << ", i = " << annulus.GetInteriorValue() << ", a = " << annulus.GetAnnulusValue() << ", e = " << annulus.GetExteriorValue() << std::endl; - for (i = 0, k = 0; i < annulusSize[1]; ++i) + for (unsigned int i = 0, k = 0; i < annulusSize[1]; ++i) { - for (j = 0; j < annulusSize[0]; ++j, ++k) + for (unsigned int j = 0; j < annulusSize[0]; ++j, ++k) { std::cout.width(3); std::cout.precision(3); @@ -161,9 +160,9 @@ itkAnnulusOperatorTest(int, char *[]) << ", i = " << annulus.GetInteriorValue() << ", a = " << annulus.GetAnnulusValue() << ", e = " << annulus.GetExteriorValue() << std::endl; - for (i = 0, k = 0; i < annulusSize[1]; ++i) + for (unsigned int i = 0, k = 0; i < annulusSize[1]; ++i) { - for (j = 0; j < annulusSize[0]; ++j, ++k) + for (unsigned int j = 0; j < annulusSize[0]; ++j, ++k) { std::cout.width(3); std::cout.precision(3); @@ -185,9 +184,9 @@ itkAnnulusOperatorTest(int, char *[]) << ", i = " << annulus.GetInteriorValue() << ", a = " << annulus.GetAnnulusValue() << ", e = " << annulus.GetExteriorValue() << std::endl; - for (i = 0, k = 0; i < annulusSize[1]; ++i) + for (unsigned int i = 0, k = 0; i < annulusSize[1]; ++i) { - for (j = 0; j < annulusSize[0]; ++j, ++k) + for (unsigned int j = 0; j < annulusSize[0]; ++j, ++k) { std::cout.width(3); std::cout.precision(3); @@ -217,9 +216,9 @@ itkAnnulusOperatorTest(int, char *[]) << ", s = " << annulus.GetSpacing() << ", i = " << annulus.GetInteriorValue() << ", a = " << annulus.GetAnnulusValue() << ", e = " << annulus.GetExteriorValue() << std::endl; - for (i = 0, k = 0; i < annulusSize[1]; ++i) + for (unsigned int i = 0, k = 0; i < annulusSize[1]; ++i) { - for (j = 0; j < annulusSize[0]; ++j, ++k) + for (unsigned int j = 0; j < annulusSize[0]; ++j, ++k) { std::cout.width(3); std::cout.precision(3); diff --git a/Modules/Core/Common/test/itkArray2DGTest.cxx b/Modules/Core/Common/test/itkArray2DGTest.cxx index 54f562bf4e8..f65af118d06 100644 --- a/Modules/Core/Common/test/itkArray2DGTest.cxx +++ b/Modules/Core/Common/test/itkArray2DGTest.cxx @@ -20,8 +20,16 @@ #include "itkArray2D.h" #include #include +#include // For is_nothrow_move_constructible_v and is_nothrow_move_assignable_v. +static_assert(std::is_nothrow_move_constructible_v> && + std::is_nothrow_move_constructible_v>, + "Array2D should have a `noexcept` move-constructor!"); +static_assert(std::is_nothrow_move_assignable_v> && + std::is_nothrow_move_assignable_v>, + "Array2D should have a `noexcept` move-assignment operator!"); + // Tests that Array2D may be constructed with an initial value for each element. TEST(Array2D, ConstructorSupportsInitialValue) { @@ -51,3 +59,54 @@ TEST(Array2D, ConstructorSupportsInitialValue) checkConstructor(1, 2, initialValue); } } + + +// Tests that when move-constructing an Array2D, the data is "taken" from the original, and "moved" to the newly +// constructed object. +TEST(Array2D, MoveConstruct) +{ + const auto checkMoveConstruct = [](auto && original) { + const auto * const * const originalDataArray{ original.data_array() }; + const unsigned int originalSize{ original.size() }; + + const auto moveConstructed = std::move(original); + + // After the "move", the move-constructed object has retrieved the original data. + EXPECT_EQ(moveConstructed.data_array(), originalDataArray); + EXPECT_EQ(moveConstructed.size(), originalSize); + + // After the "move", the original is left empty. + EXPECT_EQ(original.data_array(), nullptr); + EXPECT_EQ(original.size(), 0U); + }; + + checkMoveConstruct(itk::Array2D()); + checkMoveConstruct(itk::Array2D(1U, 1U)); + checkMoveConstruct(itk::Array2D(1U, 2U)); +} + + +// Tests that when move-assigning an Array2D, the data is "taken" from the original, and "moved" to the target of the +// move-assignment. +TEST(Array2D, MoveAssign) +{ + const auto checkMoveAssign = [](auto original) { + const auto * const * const originalDataArray{ original.data_array() }; + const unsigned int originalSize{ original.size() }; + + decltype(original) moveAssigmentTarget; + moveAssigmentTarget = std::move(original); + + // After the "move", the target of the move-assignment has retrieved the original data. + EXPECT_EQ(moveAssigmentTarget.data_array(), originalDataArray); + EXPECT_EQ(moveAssigmentTarget.size(), originalSize); + + // After the "move", the original is left empty. + EXPECT_EQ(original.data_array(), nullptr); + EXPECT_EQ(original.size(), 0U); + }; + + checkMoveAssign(itk::Array2D()); + checkMoveAssign(itk::Array2D(1U, 1U)); + checkMoveAssign(itk::Array2D(1U, 2U)); +} diff --git a/Modules/Core/Common/test/itkArray2DTest.cxx b/Modules/Core/Common/test/itkArray2DTest.cxx index daca446935c..4b1f531a5a8 100644 --- a/Modules/Core/Common/test/itkArray2DTest.cxx +++ b/Modules/Core/Common/test/itkArray2DTest.cxx @@ -44,7 +44,7 @@ itkArray2DTest(int, char *[]) } } - const double tolerance = 1e-6; + constexpr double tolerance = 1e-6; // test copy constructor ArrayType b(a); @@ -81,9 +81,8 @@ itkArray2DTest(int, char *[]) } // test for assignment from Array2D - ArrayType e; - e = a; + ArrayType e = a; for (unsigned int r = 0; r < rows; ++r) { @@ -100,9 +99,8 @@ itkArray2DTest(int, char *[]) } // test for assignment from vnl_matrix - ArrayType f; - f = vm; + ArrayType f = vm; for (unsigned int r = 0; r < rows; ++r) { diff --git a/Modules/Core/Common/test/itkArrayGTest.cxx b/Modules/Core/Common/test/itkArrayGTest.cxx new file mode 100644 index 00000000000..f8ad28e3497 --- /dev/null +++ b/Modules/Core/Common/test/itkArrayGTest.cxx @@ -0,0 +1,44 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * 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 + * + * https://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. + * + *=========================================================================*/ + +// First include the header file to be tested: +#include "itkArray.h" +#include + +namespace +{ +// Checks that `itk::Array` supports class template argument deduction (CTAD). +template +constexpr bool +CheckClassTemplateArgumentDeduction() +{ + using ExpectedType = itk::Array; + + const TValue constValue{}; + static_assert(std::is_same_v, + "The `Array(const ValueType *, ...)` constructor should support CTAD!"); + + TValue nonConstValue{}; + static_assert(std::is_same_v, + "The `Array(ValueType *, ...)` constructor should support CTAD!"); + return true; +} +} // namespace + + +static_assert(CheckClassTemplateArgumentDeduction() && CheckClassTemplateArgumentDeduction()); diff --git a/Modules/Core/Common/test/itkArrayTest.cxx b/Modules/Core/Common/test/itkArrayTest.cxx index 706e9ede389..4ad5b558949 100644 --- a/Modules/Core/Common/test/itkArrayTest.cxx +++ b/Modules/Core/Common/test/itkArrayTest.cxx @@ -28,8 +28,8 @@ itkArrayTest(int, char *[]) using FloatArrayType = itk::Array; using DoubleArrayType = itk::Array; - FloatArrayType fa(10); - DoubleArrayType da(10); + const FloatArrayType fa(10); + const DoubleArrayType da(10); /** * The following section tests the functionality of the Array's @@ -64,15 +64,13 @@ itkArrayTest(int, char *[]) // // Copy an itk::Array which manages its own memory // - FloatArrayType test1; - test1 = myOwnBoss; + const FloatArrayType test1 = myOwnBoss; std::cout << test1 << std::endl; // // Copy an itk::Array which does not manage its own memory // - FloatArrayType test2; - test2 = notMyOwnBoss; + FloatArrayType test2 = notMyOwnBoss; std::cout << test2 << std::endl; // @@ -109,7 +107,7 @@ itkArrayTest(int, char *[]) objectToCopy.SetDataSameSize(data); // This implicitly means LetArrayManageMemory=false // Make a copy of the array which is not managing its own memory. - FloatArrayType copy(objectToCopy); + const FloatArrayType copy(objectToCopy); // DO a double // diff --git a/Modules/Core/Common/test/itkAtanRegularizedHeavisideStepFunctionTest1.cxx b/Modules/Core/Common/test/itkAtanRegularizedHeavisideStepFunctionTest1.cxx index 7c21e46b6f0..2ce0e8a28f4 100644 --- a/Modules/Core/Common/test/itkAtanRegularizedHeavisideStepFunctionTest1.cxx +++ b/Modules/Core/Common/test/itkAtanRegularizedHeavisideStepFunctionTest1.cxx @@ -38,7 +38,7 @@ itkAtanRegularizedHeavisideStepFunctionTest1(int, char *[]) constexpr double epsilon0 = 1.0; - const double epsilon1 = 1e-4; + constexpr double epsilon1 = 1e-4; ITK_TEST_SET_GET_VALUE(epsilon0, functionBase0->GetEpsilon()); @@ -48,16 +48,16 @@ itkAtanRegularizedHeavisideStepFunctionTest1(int, char *[]) constexpr double epsilon2 = 0.5; functionBase0->SetEpsilon(epsilon2); - const int minValue = -20; + constexpr int minValue = -20; constexpr int maxValue = 20; constexpr InputType incValue = 0.1; for (int x = minValue; x < maxValue; ++x) { - const InputType ix = x * incValue; - OutputType f = functionBase0->Evaluate(ix); - OutputType df = functionBase0->EvaluateDerivative(ix); + const InputType ix = x * incValue; + const OutputType f = functionBase0->Evaluate(ix); + const OutputType df = functionBase0->EvaluateDerivative(ix); std::cout << ix << ' ' << f << ' ' << df << std::endl; } diff --git a/Modules/Core/Common/test/itkAutoPointerTest.cxx b/Modules/Core/Common/test/itkAutoPointerTest.cxx index ecfc906a79b..b6c0634bebe 100644 --- a/Modules/Core/Common/test/itkAutoPointerTest.cxx +++ b/Modules/Core/Common/test/itkAutoPointerTest.cxx @@ -83,7 +83,7 @@ itkAutoPointerTest(int, char *[]) cptr1.TakeOwnership(new TestObject); - TestObject::ConstAutoPointer cptr2(cptr1); + const TestObject::ConstAutoPointer cptr2(cptr1); return EXIT_SUCCESS; diff --git a/Modules/Core/Common/test/itkBSplineInterpolationWeightFunctionTest.cxx b/Modules/Core/Common/test/itkBSplineInterpolationWeightFunctionTest.cxx index 20f0d8d8934..afe9f8db6c7 100644 --- a/Modules/Core/Common/test/itkBSplineInterpolationWeightFunctionTest.cxx +++ b/Modules/Core/Common/test/itkBSplineInterpolationWeightFunctionTest.cxx @@ -20,7 +20,7 @@ #include "itkImageRegionConstIteratorWithIndex.h" #include "itkTestingMacros.h" -// Test template instantiation for TCoordRep = float and VSplineOrder = 1. +// Test template instantiation for TCoordinate = float and VSplineOrder = 1. // Note that this particular template instantiation would take forever to // compile on VS2015 Update 3 64-bit Release when using ITK 4.13, but // itkBSplineInterpolationWeightFunction.hxx can now handle this Visual C++ @@ -45,14 +45,14 @@ itkBSplineInterpolationWeightFunctionTest(int, char *[]) { { // Creating a local scope - using CoordRepType = double; + using CoordinateType = double; constexpr unsigned int SpaceDimension = 1; constexpr unsigned int SplineOrder = 2; std::cout << "Testing SpaceDimension= " << SpaceDimension; std::cout << " and SplineOrder= " << SplineOrder << std::endl; - using FunctionType = itk::BSplineInterpolationWeightFunction; + using FunctionType = itk::BSplineInterpolationWeightFunction; using ContinuousIndexType = FunctionType::ContinuousIndexType; using IndexType = FunctionType::IndexType; using WeightsType = FunctionType::WeightsType; @@ -92,13 +92,13 @@ itkBSplineInterpolationWeightFunctionTest(int, char *[]) function->Evaluate(position1, weights1, startIndex1); function->Evaluate(position2, weights2, startIndex2); - const unsigned int numberOfWeigts = weights1.size(); + constexpr unsigned int numberOfWeigts = weights1.size(); const int indexDifference = itk::Math::abs(startIndex2[0] + startIndex1[0]) & 1; - const double tolerance = 1e-6; - bool symmetryForXBroken = false; + constexpr double tolerance = 1e-6; + bool symmetryForXBroken = false; for (unsigned int nw = 0; nw < numberOfWeigts - indexDifference; ++nw) { @@ -145,14 +145,14 @@ itkBSplineInterpolationWeightFunctionTest(int, char *[]) std::cout << "Test passed. " << std::endl; } { // Creating a local scope - using CoordRepType = double; + using CoordinateType = double; constexpr unsigned int SpaceDimension = 1; constexpr unsigned int SplineOrder = 3; std::cout << "Testing SpaceDimension= " << SpaceDimension; std::cout << " and SplineOrder= " << SplineOrder << std::endl; - using FunctionType = itk::BSplineInterpolationWeightFunction; + using FunctionType = itk::BSplineInterpolationWeightFunction; using ContinuousIndexType = FunctionType::ContinuousIndexType; using IndexType = FunctionType::IndexType; using WeightsType = FunctionType::WeightsType; @@ -180,13 +180,13 @@ itkBSplineInterpolationWeightFunctionTest(int, char *[]) function->Evaluate(position1, weights1, startIndex1); function->Evaluate(position2, weights2, startIndex2); - const unsigned int numberOfWeigts = weights1.size(); + constexpr unsigned int numberOfWeigts = weights1.size(); const int indexDifference = itk::Math::abs(startIndex2[0] + startIndex1[0] + 1) & 1; - const double tolerance = 1e-6; - bool symmetryForXBroken = false; + constexpr double tolerance = 1e-6; + bool symmetryForXBroken = false; for (unsigned int nw = 0; nw < numberOfWeigts - indexDifference; ++nw) { @@ -234,13 +234,13 @@ itkBSplineInterpolationWeightFunctionTest(int, char *[]) } { // Creating a local scope - using CoordRepType = double; + using CoordinateType = double; constexpr unsigned int SpaceDimension = 3; constexpr unsigned int SplineOrder = 3; std::cout << "Testing SpaceDimension= " << SpaceDimension; std::cout << " and SplineOrder= " << SplineOrder << std::endl; - using FunctionType = itk::BSplineInterpolationWeightFunction; + using FunctionType = itk::BSplineInterpolationWeightFunction; using ContinuousIndexType = FunctionType::ContinuousIndexType; using IndexType = FunctionType::IndexType; using WeightsType = FunctionType::WeightsType; @@ -249,8 +249,8 @@ itkBSplineInterpolationWeightFunctionTest(int, char *[]) auto function = FunctionType::New(); function->Print(std::cout); - SizeType size = FunctionType::SupportSize; - unsigned long numberOfWeights = FunctionType::NumberOfWeights; + constexpr SizeType size = FunctionType::SupportSize; + constexpr unsigned long numberOfWeights = FunctionType::NumberOfWeights; std::cout << "Number Of Weights: " << numberOfWeights << std::endl; @@ -275,8 +275,8 @@ itkBSplineInterpolationWeightFunctionTest(int, char *[]) auto kernel = KernelType::New(); using ImageType = itk::Image; - auto image = ImageType::New(); - ImageType::RegionType region{ startIndex, size }; + auto image = ImageType::New(); + const ImageType::RegionType region{ startIndex, size }; image->SetRegions(region); image->AllocateInitialized(); diff --git a/Modules/Core/Common/test/itkBSplineKernelFunctionTest.cxx b/Modules/Core/Common/test/itkBSplineKernelFunctionTest.cxx index 9022ed05ba6..257756479f6 100644 --- a/Modules/Core/Common/test/itkBSplineKernelFunctionTest.cxx +++ b/Modules/Core/Common/test/itkBSplineKernelFunctionTest.cxx @@ -27,35 +27,35 @@ itkBSplineKernelFunctionTest(int, char *[]) // Externally generated results constexpr unsigned int npoints = 49; - const double x[npoints] = { -3, -2.875, -2.75, -2.625, -2.5, -2.375, -2.25, -2.125, -2, -1.875, - -1.75, -1.625, -1.5, -1.375, -1.25, -1.125, -1, -0.875, -0.75, -0.625, - -0.5, -0.375, -0.25, -0.125, 0, 0.125, 0.25, 0.375, 0.5, 0.625, - 0.75, 0.875, 1, 1.125, 1.25, 1.375, 1.5, 1.625, 1.75, 1.875, - 2, 2.125, 2.25, 2.375, 2.5, 2.625, 2.75, 2.875, 3 }; - - const double b0[npoints] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1, 1, 1, 1, - 1, 1, 1, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - - const double b1[npoints] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1, 0.875, - 0.75, 0.625, 0.5, 0.375, 0.25, 0.125, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - - const double b2[npoints] = { 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0.0078125, - 0.03125, 0.0703125, 0.125, 0.195313, 0.28125, 0.382813, 0.5, - 0.609375, 0.6875, 0.734375, 0.75, 0.734375, 0.6875, 0.609375, - 0.5, 0.382813, 0.28125, 0.195313, 0.125, 0.0703125, 0.03125, - 0.0078125, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0 }; - - const double b3[npoints] = { 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0.000325521, 0.00260417, 0.00878906, 0.0208333, 0.0406901, - 0.0703125, 0.111654, 0.166667, 0.236003, 0.315104, 0.398112, 0.479167, - 0.552409, 0.611979, 0.652018, 0.666667, 0.652018, 0.611979, 0.552409, - 0.479167, 0.398112, 0.315104, 0.236003, 0.166667, 0.111654, 0.0703125, - 0.0406901, 0.0208333, 0.00878906, 0.00260417, 0.000325521, 0, 0, - 0, 0, 0, 0, 0, 0, 0 }; + constexpr double x[npoints] = { -3, -2.875, -2.75, -2.625, -2.5, -2.375, -2.25, -2.125, -2, -1.875, + -1.75, -1.625, -1.5, -1.375, -1.25, -1.125, -1, -0.875, -0.75, -0.625, + -0.5, -0.375, -0.25, -0.125, 0, 0.125, 0.25, 0.375, 0.5, 0.625, + 0.75, 0.875, 1, 1.125, 1.25, 1.375, 1.5, 1.625, 1.75, 1.875, + 2, 2.125, 2.25, 2.375, 2.5, 2.625, 2.75, 2.875, 3 }; + + constexpr double b0[npoints] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1, 1, 1, 1, + 1, 1, 1, 0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + constexpr double b1[npoints] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1, 0.875, + 0.75, 0.625, 0.5, 0.375, 0.25, 0.125, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + constexpr double b2[npoints] = { 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0.0078125, + 0.03125, 0.0703125, 0.125, 0.195313, 0.28125, 0.382813, 0.5, + 0.609375, 0.6875, 0.734375, 0.75, 0.734375, 0.6875, 0.609375, + 0.5, 0.382813, 0.28125, 0.195313, 0.125, 0.0703125, 0.03125, + 0.0078125, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0 }; + + constexpr double b3[npoints] = { 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0.000325521, 0.00260417, 0.00878906, 0.0208333, 0.0406901, + 0.0703125, 0.111654, 0.166667, 0.236003, 0.315104, 0.398112, 0.479167, + 0.552409, 0.611979, 0.652018, 0.666667, 0.652018, 0.611979, 0.552409, + 0.479167, 0.398112, 0.315104, 0.236003, 0.166667, 0.111654, 0.0703125, + 0.0406901, 0.0208333, 0.00878906, 0.00260417, 0.000325521, 0, 0, + 0, 0, 0, 0, 0, 0, 0 }; // Testing the output of BSplineKernelFunction @@ -65,7 +65,7 @@ itkBSplineKernelFunctionTest(int, char *[]) auto function = FunctionType::New(); \ \ function->Print(std::cout); \ - const double epsilon = 1e-6; \ + constexpr double epsilon = 1e-6; \ for (unsigned int j = 0; j < npoints; ++j) \ { \ double results = function->Evaluate(x[j]); \ @@ -97,11 +97,11 @@ itkBSplineKernelFunctionTest(int, char *[]) auto derivFunction = DerivativeFunctionType::New(); derivFunction->Print(std::cout); - double xx = -0.25; - double expectedValue = 0.0; - double results = derivFunction->Evaluate(xx); + constexpr double xx = -0.25; + constexpr double expectedValue = 0.0; + const double results = derivFunction->Evaluate(xx); - const double epsilon = 1e-6; + constexpr double epsilon = 1e-6; if (itk::Math::abs(results - expectedValue) > epsilon) { std::cerr.precision(static_cast(itk::Math::abs(std::log10(epsilon)))); @@ -125,10 +125,10 @@ itkBSplineKernelFunctionTest(int, char *[]) for (double xx = -3.0; xx <= 3.0; xx += 0.1) { - double expectedValue = function->Evaluate(xx + 0.5) - function->Evaluate(xx - 0.5); - double results = derivFunction->Evaluate(xx); + const double expectedValue = function->Evaluate(xx + 0.5) - function->Evaluate(xx - 0.5); + const double results = derivFunction->Evaluate(xx); - const double epsilon = 1e-6; + constexpr double epsilon = 1e-6; if (itk::Math::abs(results - expectedValue) > epsilon) { std::cerr.precision(static_cast(itk::Math::abs(std::log10(epsilon)))); @@ -154,10 +154,10 @@ itkBSplineKernelFunctionTest(int, char *[]) for (double xx = -3.0; xx <= 3.0; xx += 0.1) { - double expectedValue = function->Evaluate(xx + 0.5) - function->Evaluate(xx - 0.5); - double results = derivFunction->Evaluate(xx); + const double expectedValue = function->Evaluate(xx + 0.5) - function->Evaluate(xx - 0.5); + const double results = derivFunction->Evaluate(xx); - const double epsilon = 1e-6; + constexpr double epsilon = 1e-6; if (itk::Math::abs(results - expectedValue) > epsilon) { std::cerr.precision(static_cast(itk::Math::abs(std::log10(epsilon)))); @@ -183,10 +183,10 @@ itkBSplineKernelFunctionTest(int, char *[]) for (double xx = -3.0; xx <= 3.0; xx += 0.1) { - double expectedValue = function->Evaluate(xx + 0.5) - function->Evaluate(xx - 0.5); - double results = derivFunction->Evaluate(xx); + const double expectedValue = function->Evaluate(xx + 0.5) - function->Evaluate(xx - 0.5); + const double results = derivFunction->Evaluate(xx); - const double epsilon = 1e-6; + constexpr double epsilon = 1e-6; if (itk::Math::abs(results - expectedValue) > epsilon) { std::cerr.precision(static_cast(itk::Math::abs(std::log10(epsilon)))); diff --git a/Modules/Core/Common/test/itkBitCastGTest.cxx b/Modules/Core/Common/test/itkBitCastGTest.cxx index bf35cae0532..4ffc2892a71 100644 --- a/Modules/Core/Common/test/itkBitCastGTest.cxx +++ b/Modules/Core/Common/test/itkBitCastGTest.cxx @@ -40,7 +40,6 @@ TEST(BitCast, ResultIsBitwiseEqualToArgument) Expect_return_value_is_bitwise_equal_to_function_argument(i); } - int value; - (void)value; + [[maybe_unused]] int value; Expect_return_value_is_bitwise_equal_to_function_argument(&value); } diff --git a/Modules/Core/Common/test/itkBoundaryConditionTest.cxx b/Modules/Core/Common/test/itkBoundaryConditionTest.cxx index c501dd7c542..b495d8868ff 100644 --- a/Modules/Core/Common/test/itkBoundaryConditionTest.cxx +++ b/Modules/Core/Common/test/itkBoundaryConditionTest.cxx @@ -32,11 +32,10 @@ template void printn(itk::NeighborhoodAllocator & n, const itk::Size<2> & sz) { - unsigned int i, j, k; - k = 0; - for (j = 0; j < sz[1]; ++j) + unsigned int k = 0; + for (unsigned int j = 0; j < sz[1]; ++j) { - for (i = 0; i < sz[0]; ++i, ++k) + for (unsigned int i = 0; i < sz[0]; ++i, ++k) { std::cout << n[k] << ' '; } @@ -47,8 +46,8 @@ printn(itk::NeighborhoodAllocator & n, const itk::Size<2> & sz) void filln(itk::Image * img) { - float i, j; - i = j = 0.0f; + float i = 0.0f; + float j = 0.0f; itk::ImageRegionIterator> it(img, img->GetRequestedRegion()); @@ -130,9 +129,9 @@ itkBoundaryConditionTest(int, char *[]) image3D->Allocate(); imageND->Allocate(); - itk::ImageRegionIterator it2D(image2D, image2D->GetRequestedRegion()); - itk::ImageRegionIterator it3D(image3D, image3D->GetRequestedRegion()); - itk::ImageRegionIterator itND(imageND, imageND->GetRequestedRegion()); + const itk::ImageRegionIterator it2D(image2D, image2D->GetRequestedRegion()); + itk::ImageRegionIterator it3D(image3D, image3D->GetRequestedRegion()); + itk::ImageRegionIterator itND(imageND, imageND->GetRequestedRegion()); println("Initializing some images"); diff --git a/Modules/Core/Common/test/itkBoundingBoxTest.cxx b/Modules/Core/Common/test/itkBoundingBoxTest.cxx index 184c9c2b9ce..b2abe8efc6c 100644 --- a/Modules/Core/Common/test/itkBoundingBoxTest.cxx +++ b/Modules/Core/Common/test/itkBoundingBoxTest.cxx @@ -16,7 +16,9 @@ * *=========================================================================*/ -#define ITK_LEGACY_TEST +#ifndef ITK_LEGACY_REMOVE +# define ITK_LEGACY_TEST +#endif #include #include "itkBoundingBox.h" #include "itkMath.h" @@ -29,7 +31,7 @@ itkBoundingBoxTest(int, char *[]) using BB = itk::BoundingBox; auto myBox = BB::New(); - BB::PointsContainerPointer Points = BB::PointsContainer::New(); + const BB::PointsContainerPointer Points = BB::PointsContainer::New(); itk::Point P; @@ -38,7 +40,7 @@ itkBoundingBoxTest(int, char *[]) const BB::BoundsArrayType & bounds = myBox->GetBounds(); for (unsigned int i = 0; i < bounds.Size(); ++i) { - if (itk::Math::NotExactlyEquals(bounds[i], BB::CoordRepType{})) + if (itk::Math::NotExactlyEquals(bounds[i], BB::CoordinateType{})) { std::cerr << "Bounding Box initialization test failed" << std::endl; std::cerr << bounds << std::endl; @@ -52,7 +54,7 @@ itkBoundingBoxTest(int, char *[]) BB::PointType center = myBox->GetCenter(); for (unsigned int i = 0; i < 1; ++i) { - if (itk::Math::NotExactlyEquals(center[i], BB::CoordRepType{})) + if (itk::Math::NotExactlyEquals(center[i], BB::CoordinateType{})) { std::cerr << "Empty Box GetCenter initialization test failed" << std::endl; return EXIT_FAILURE; @@ -115,15 +117,14 @@ itkBoundingBoxTest(int, char *[]) std::cout << "Null GetCenter test passed" << std::endl; } - itk::NumericTraits::AccumulateType diagonal; - diagonal = myBox->GetDiagonalLength2(); + const itk::NumericTraits::AccumulateType diagonal = myBox->GetDiagonalLength2(); if (diagonal != 81.0) { return EXIT_FAILURE; } std::cout << "GetDiagonalLength2 passed" << std::endl; - BB::PointsContainerConstPointer NewPoints = myBox->GetPoints(); + const BB::PointsContainerConstPointer NewPoints = myBox->GetPoints(); // End with a Print. myBox->Print(std::cout); @@ -135,10 +136,10 @@ itkBoundingBoxTest(int, char *[]) using CC = itk::BoundingBox; auto my3DBox = CC::New(); - CC::PointsContainerPointer Points3D = CC::PointsContainer::New(); + const CC::PointsContainerPointer Points3D = CC::PointsContainer::New(); - CC::PointType::ValueType qval1[3] = { -1.0f, -1.0f, -1.0f }; - CC::PointType Q = qval1; + constexpr CC::PointType::ValueType qval1[3] = { -1.0f, -1.0f, -1.0f }; + CC::PointType Q = qval1; Points3D->InsertElement(0, Q); CC::PointType::ValueType qval2[3] = { 1.0f, 1.0f, 1.0f }; @@ -157,7 +158,7 @@ itkBoundingBoxTest(int, char *[]) Q = qval3; if (!my3DBox->IsInside(Q)) { - std::cerr << "Point " << Q << " Should be repoted inside " << std::endl; + std::cerr << "Point " << Q << " Should be reported inside " << std::endl; return EXIT_FAILURE; } @@ -165,7 +166,7 @@ itkBoundingBoxTest(int, char *[]) Q = qval4; if (my3DBox->IsInside(Q)) { - std::cerr << "Point " << Q << " Should be repoted outside " << std::endl; + std::cerr << "Point " << Q << " Should be reported outside " << std::endl; return EXIT_FAILURE; } @@ -192,8 +193,8 @@ itkBoundingBoxTest(int, char *[]) // Testing the DeepCopy method { - const double tolerance = 1e-10; - CC::Pointer clone = my3DBox->DeepCopy(); + constexpr double tolerance = 1e-10; + const CC::Pointer clone = my3DBox->DeepCopy(); const CC::BoundsArrayType & originalBounds = my3DBox->GetBounds(); const CC::BoundsArrayType & clonedbounds = clone->GetBounds(); for (unsigned int i = 0; i < originalBounds.Size(); ++i) diff --git a/Modules/Core/Common/test/itkBuildInformationGTest.cxx b/Modules/Core/Common/test/itkBuildInformationGTest.cxx index 19aebcceeff..c87adbda7b3 100644 --- a/Modules/Core/Common/test/itkBuildInformationGTest.cxx +++ b/Modules/Core/Common/test/itkBuildInformationGTest.cxx @@ -32,7 +32,7 @@ TEST(ITKBuildInformation, InformationFeatures) { using MapType = itk::BuildInformation::MapType; - itk::BuildInformation::Pointer instance = itk::BuildInformation::GetInstance(); + const itk::BuildInformation::Pointer instance = itk::BuildInformation::GetInstance(); EXPECT_EQ(instance.IsNull(), false); @@ -47,7 +47,7 @@ TEST(ITKBuildInformation, InformationFeatures) EXPECT_EQ(it->second.m_Description, std::string{ "The URL of project." }); } - for (auto mapEntry : localMap) + for (const auto & mapEntry : localMap) { const auto & key = mapEntry.first; diff --git a/Modules/Core/Common/test/itkByteSwapTest.cxx b/Modules/Core/Common/test/itkByteSwapTest.cxx index 16b18cceada..4408b01fa56 100644 --- a/Modules/Core/Common/test/itkByteSwapTest.cxx +++ b/Modules/Core/Common/test/itkByteSwapTest.cxx @@ -27,27 +27,20 @@ itkByteSwapTest(int, char *[]) std::cout << "Starting test" << std::endl; - unsigned char uc = 'a', uc1 = 'a'; - unsigned short us = 1, us1 = 1; - unsigned int ui = 1, ui1 = 1; - unsigned long ul = 1, ul1 = 1; - unsigned long long ull = 1, ull1 = 1; - float f = 1.0, f1 = 1.0; - double d = 1.0, d1 = 1.0; - - // Try to swap a char - if (itk::ByteSwapper::SystemIsBigEndian() == itk::ByteSwapper::SystemIsLE()) + if constexpr (itk::ByteSwapper::SystemIsBigEndian() == itk::ByteSwapper::SystemIsLE()) { return EXIT_FAILURE; } - if (itk::ByteSwapper::SystemIsBE() == itk::ByteSwapper::SystemIsLittleEndian()) + if constexpr (itk::ByteSwapper::SystemIsBE() == itk::ByteSwapper::SystemIsLittleEndian()) { return EXIT_FAILURE; } - if (itk::ByteSwapper::SystemIsBigEndian()) + unsigned char uc = 'a'; + constexpr unsigned char uc1 = 'a'; + if constexpr (itk::ByteSwapper::SystemIsBigEndian()) { itk::ByteSwapper::SwapFromSystemToLittleEndian(&uc); itk::ByteSwapper::SwapFromSystemToLittleEndian(&uc); @@ -63,7 +56,9 @@ itkByteSwapTest(int, char *[]) } std::cout << "Passed unsigned char: " << uc << std::endl; - if (itk::ByteSwapper::SystemIsBE()) + unsigned short us = 1; + constexpr unsigned short us1 = 1; + if constexpr (itk::ByteSwapper::SystemIsBE()) { itk::ByteSwapper::SwapFromSystemToLittleEndian(&us); itk::ByteSwapper::SwapFromSystemToLittleEndian(&us); @@ -78,8 +73,9 @@ itkByteSwapTest(int, char *[]) return EXIT_FAILURE; } std::cout << "Passed unsigned short: " << us << std::endl; - - if (itk::ByteSwapper::SystemIsBigEndian()) + unsigned int ui = 1; + constexpr unsigned int ui1 = 1; + if constexpr (itk::ByteSwapper::SystemIsBigEndian()) { itk::ByteSwapper::SwapFromSystemToLittleEndian(&ui); itk::ByteSwapper::SwapFromSystemToLittleEndian(&ui); @@ -95,10 +91,11 @@ itkByteSwapTest(int, char *[]) } std::cout << "Passed unsigned int: " << ui << std::endl; - + unsigned long ul = 1; + constexpr unsigned long ul1 = 1; try { - if (itk::ByteSwapper::SystemIsBigEndian()) + if constexpr (itk::ByteSwapper::SystemIsBigEndian()) { itk::ByteSwapper::SwapFromSystemToLittleEndian(&ul); itk::ByteSwapper::SwapFromSystemToLittleEndian(&ul); @@ -120,10 +117,11 @@ itkByteSwapTest(int, char *[]) err.Print(std::cerr); } - + unsigned long long ull = 1; + constexpr unsigned long long ull1 = 1; try { - if (itk::ByteSwapper::SystemIsBigEndian()) + if constexpr (itk::ByteSwapper::SystemIsBigEndian()) { itk::ByteSwapper::SwapFromSystemToLittleEndian(&ull); itk::ByteSwapper::SwapFromSystemToLittleEndian(&ull); @@ -145,9 +143,11 @@ itkByteSwapTest(int, char *[]) err.Print(std::cerr); } + float f = 1.0; + constexpr float f1 = 1.0; try { - if (itk::ByteSwapper::SystemIsBigEndian()) + if constexpr (itk::ByteSwapper::SystemIsBigEndian()) { itk::ByteSwapper::SwapFromSystemToLittleEndian(&f); itk::ByteSwapper::SwapFromSystemToLittleEndian(&f); @@ -170,9 +170,11 @@ itkByteSwapTest(int, char *[]) return EXIT_FAILURE; } + double d = 1.0; + constexpr double d1 = 1.0; try { - if (itk::ByteSwapper::SystemIsBigEndian()) + if constexpr (itk::ByteSwapper::SystemIsBigEndian()) { itk::ByteSwapper::SwapFromSystemToLittleEndian(&d); itk::ByteSwapper::SwapFromSystemToLittleEndian(&d); diff --git a/Modules/Core/Common/test/itkCMakeConfigurationTest.cxx b/Modules/Core/Common/test/itkCMakeConfigurationTest.cxx index e7880829d58..d1b50a6aad6 100644 --- a/Modules/Core/Common/test/itkCMakeConfigurationTest.cxx +++ b/Modules/Core/Common/test/itkCMakeConfigurationTest.cxx @@ -49,12 +49,11 @@ itkCMakeInformationPrintFile(const char * name, std::ostream & os) os << " does not exist.\n"; return; } - else - { - os << " has " << fs.st_size << " bytes"; - } - std::ifstream fin(name); + os << " has " << fs.st_size << " bytes"; + + + const std::ifstream fin(name); if (fin) { const char * div = "======================================================================="; @@ -86,7 +85,7 @@ main(int argc, char * argv[]) for (const char ** f = files; *f; ++f) { - std::string fname = build_dir + *f; + const std::string fname = build_dir + *f; itkCMakeInformationPrintFile(fname.c_str(), std::cout); } return EXIT_SUCCESS; diff --git a/Modules/Core/Common/test/itkColorTableTest.cxx b/Modules/Core/Common/test/itkColorTableTest.cxx index baf713abdcd..525aec4116f 100644 --- a/Modules/Core/Common/test/itkColorTableTest.cxx +++ b/Modules/Core/Common/test/itkColorTableTest.cxx @@ -78,7 +78,7 @@ ColorTableTestSpecialConditionChecker(typename itk::ColorTable::Poin return EXIT_FAILURE; } - RGBPixelType pixel = colors->GetColor(numberOfColors); + const RGBPixelType pixel = colors->GetColor(numberOfColors); if (pixel != zeroPixel) { std::cerr << "Test failed!" << std::endl; @@ -87,7 +87,7 @@ ColorTableTestSpecialConditionChecker(typename itk::ColorTable::Poin return EXIT_FAILURE; } - bool tf = colors->SetColor(numberOfColors, 0, 0, 0, "NoMatterTheName"); + const bool tf = colors->SetColor(numberOfColors, 0, 0, 0, "NoMatterTheName"); if (tf != false) { std::cerr << "Test failed!" << std::endl; @@ -96,7 +96,7 @@ ColorTableTestSpecialConditionChecker(typename itk::ColorTable::Poin return EXIT_FAILURE; } - std::string name = colors->GetColorName(numberOfColors); + const std::string name = colors->GetColorName(numberOfColors); if (!name.empty()) { std::cerr << "Test failed!" << std::endl; @@ -174,6 +174,7 @@ itkColorTableTest(int argc, char * argv[]) { if (argc != 2) { + std::cerr << "Missing parameters." << std::endl; std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " numberOfColors" << std::endl; return EXIT_FAILURE; } @@ -204,12 +205,11 @@ itkColorTableTest(int argc, char * argv[]) testStatus |= ColorTableTestHelper("double", numberOfColors); // Find the closest color for a few colors - unsigned int id; using RGBPixelType = itk::RGBPixel; RGBPixelType pixel; colors->UseRandomColors(10000); pixel.Set(255, 0, 0); - id = colors->GetClosestColorTableId(pixel[0], pixel[1], pixel[2]); + unsigned int id = colors->GetClosestColorTableId(pixel[0], pixel[1], pixel[2]); std::cout << "Pixel : " << pixel << " is closest to id: " << id << " which has the color: " << colors->GetColor(id) << " and name " << colors->GetColorName(id) << std::endl; diff --git a/Modules/Core/Common/test/itkCommandObserverObjectTest.cxx b/Modules/Core/Common/test/itkCommandObserverObjectTest.cxx index 23bc60571f9..a757476d28f 100644 --- a/Modules/Core/Common/test/itkCommandObserverObjectTest.cxx +++ b/Modules/Core/Common/test/itkCommandObserverObjectTest.cxx @@ -67,23 +67,23 @@ onAnyThrow(itk::Object *, const itk::EventObject &, void *) void onUserRemove(itk::Object * o, const itk::EventObject &, void * data) { - unsigned long idToRemove = *static_cast(data); + const unsigned long idToRemove = *static_cast(data); o->RemoveObserver(idToRemove); } int testDeleteObserverDuringEvent() { - itk::Object::Pointer o = itk::Object::New(); + const itk::Object::Pointer o = itk::Object::New(); unsigned long idToRemove; - itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New(); removeCmd->SetCallback(onUserRemove); removeCmd->SetObjectName("Remove Command"); - itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New(); cmd->SetCallback(onAny); cmd->SetObjectName("Any Command 1"); @@ -180,14 +180,14 @@ int testCommandConstObject() { - itk::Object::Pointer o = itk::Object::New(); - itk::Object::ConstPointer co = o; + const itk::Object::Pointer o = itk::Object::New(); + const itk::Object::ConstPointer co = o; - itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New(); cmd->SetConstCallback(onAnyConst); cmd->SetObjectName("Any Command 1"); - itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New(); removeCmd->SetCallback(onUserRemove); removeCmd->SetObjectName("Remove Command"); @@ -215,20 +215,20 @@ testCommandRecursiveObject() // a Command. // This is a super-mean test that is not likely to really be used. - itk::Object::Pointer o = itk::Object::New(); - itk::Object::ConstPointer co = o; + const itk::Object::Pointer o = itk::Object::New(); + const itk::Object::ConstPointer co = o; unsigned long idToRemove; - itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New(); cmd->SetCallback(onAny); cmd->SetObjectName("Any Command 1"); - itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New(); removeCmd->SetCallback(onUserRemove); removeCmd->SetObjectName("Remove Command"); - itk::CStyleCommand::Pointer cmdInvoke = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer cmdInvoke = itk::CStyleCommand::New(); cmdInvoke->SetCallback(onAnyInvokeUser); cmdInvoke->SetObjectName("Any Invoke User"); @@ -274,9 +274,9 @@ bool testDeleteEventThrow() { // check the case where an exception in thrown in the DeleteEvent - itk::Object::Pointer o = itk::Object::New(); + const itk::Object::Pointer o = itk::Object::New(); - itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New(); + const itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New(); cmd->SetCallback(onAnyThrow); o->AddObserver(itk::DeleteEvent(), cmd); @@ -295,7 +295,7 @@ testLambdaCommand() { // check the case where an exception in thrown in the DeleteEvent - itk::Object::Pointer o = itk::Object::New(); + const itk::Object::Pointer o = itk::Object::New(); /*----- FIRST OBSERVER LAMBDA */ o->AddObserver(itk::AnyEvent(), [&cnt](const itk::EventObject &) { ++cnt; }); @@ -311,7 +311,7 @@ testLambdaCommand() ITK_TEST_EXPECT_EQUAL(1, cnt); ITK_TEST_EXPECT_EQUAL(1, name_of_class_cnt); - } // A DeleteEvent is called here! as object "o" is deleted + } // A DeleteEvent is called here! as object "o" is deleted ITK_TEST_EXPECT_EQUAL(2, cnt); // Verify that cnt really was incremented during DeleteEvent! ITK_TEST_EXPECT_EQUAL(2, name_of_class_cnt); return EXIT_SUCCESS; diff --git a/Modules/Core/Common/test/itkCompensatedSummationTest.cxx b/Modules/Core/Common/test/itkCompensatedSummationTest.cxx index 47dc02e0ab6..9887a3e37db 100644 --- a/Modules/Core/Common/test/itkCompensatedSummationTest.cxx +++ b/Modules/Core/Common/test/itkCompensatedSummationTest.cxx @@ -27,10 +27,10 @@ itkCompensatedSummationTest(int, char *[]) // Save the format stream variables for std::cout // They will be restored when coutState goes out of scope // scope. - itk::StdStreamStateSave coutState(std::cout); + const itk::StdStreamStateSave coutState(std::cout); using FloatType = float; - long seedValue = 17; + constexpr long seedValue = 17; constexpr FloatType expectedMean = 0.5; @@ -38,7 +38,7 @@ itkCompensatedSummationTest(int, char *[]) using GeneratorType = itk::Statistics::MersenneTwisterRandomVariateGenerator; auto generator = GeneratorType::New(); - generator->Initialize(seedValue); + generator->SetSeed(seedValue); FloatType vanillaSum = 0.0; using CompensatedSummationType = itk::CompensatedSummation; @@ -73,15 +73,14 @@ itkCompensatedSummationTest(int, char *[]) } // exercise other methods - CompensatedSummationType floatAccumulatorCopy = floatAccumulator; + const CompensatedSummationType floatAccumulatorCopy = floatAccumulator; if (itk::Math::NotExactlyEquals(floatAccumulatorCopy.GetSum(), floatAccumulator.GetSum())) { std::cerr << "The copy constructor failed." << std::endl; return EXIT_FAILURE; } - CompensatedSummationType floatAccumulatorCopy2; - floatAccumulatorCopy2 = floatAccumulator; + const CompensatedSummationType floatAccumulatorCopy2 = floatAccumulator; if (itk::Math::NotExactlyEquals(floatAccumulatorCopy2.GetSum(), floatAccumulator.GetSum())) { std::cerr << "The assignment operator failed." << std::endl; diff --git a/Modules/Core/Common/test/itkCompensatedSummationTest2.cxx b/Modules/Core/Common/test/itkCompensatedSummationTest2.cxx index 9e4a4d1d359..cd5c01bfb42 100644 --- a/Modules/Core/Common/test/itkCompensatedSummationTest2.cxx +++ b/Modules/Core/Common/test/itkCompensatedSummationTest2.cxx @@ -71,9 +71,9 @@ class CompensatedSummationTest2Associate void ThreadedExecution(const DomainType & subdomain, const itk::ThreadIdType threadId) override { + constexpr double value = 1.0 / 7; for (DomainType::IndexValueType i = subdomain[0]; i <= subdomain[1]; ++i) { - double value = 1.0 / 7; this->m_PerThreadCompensatedSum[threadId].AddElement(value); } } @@ -86,7 +86,7 @@ class CompensatedSummationTest2Associate for (itk::ThreadIdType i = 0, numWorkUnitsUsed = this->GetNumberOfWorkUnitsUsed(); i < numWorkUnitsUsed; ++i) { - double sum = this->m_PerThreadCompensatedSum[i].GetSum(); + const double sum = this->m_PerThreadCompensatedSum[i].GetSum(); std::cout << i << ": " << sum << std::endl; this->m_Associate->m_CompensatedSumOfThreads.AddElement(sum); this->m_Associate->m_UncompensatedSumOfThreads += sum; @@ -139,8 +139,9 @@ class CompensatedSummationTest2Associate int itkCompensatedSummationTest2(int, char *[]) { - CompensatedSummationTest2Associate enclosingClass; - CompensatedSummationTest2Associate::TestDomainThreader::Pointer domainThreader = enclosingClass.GetDomainThreader(); + CompensatedSummationTest2Associate enclosingClass; + const CompensatedSummationTest2Associate::TestDomainThreader::Pointer domainThreader = + enclosingClass.GetDomainThreader(); /* Check # of threads */ std::cout << "GetGlobalMaximumNumberOfThreads: " @@ -151,12 +152,12 @@ itkCompensatedSummationTest2(int, char *[]) using DomainType = CompensatedSummationTest2Associate::TestDomainThreader::DomainType; DomainType domain; - itk::ThreadIdType maxNumberOfThreads = domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads(); + const itk::ThreadIdType maxNumberOfThreads = domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads(); domain[0] = 0; domain[1] = maxNumberOfThreads * 10000; /* Test with single thread. We should get the same result. */ - itk::ThreadIdType numberOfThreads = 1; + constexpr itk::ThreadIdType numberOfThreads = 1; domainThreader->SetMaximumNumberOfThreads(numberOfThreads); domainThreader->SetNumberOfWorkUnits(numberOfThreads); std::cout << "Testing with " << numberOfThreads << " threads and domain " << domain << " ..." << std::endl; @@ -183,7 +184,7 @@ itkCompensatedSummationTest2(int, char *[]) } /* Store result as reference */ - double referenceSum = enclosingClass.GetCompensatedSumOfThreads(); + const double referenceSum = enclosingClass.GetCompensatedSumOfThreads(); /* Test with maximum threads. We need at least three threads to see a difference. */ if (domainThreader->GetMultiThreader()->GetGlobalMaximumNumberOfThreads() > 2) diff --git a/Modules/Core/Common/test/itkConicShellInteriorExteriorSpatialFunctionTest.cxx b/Modules/Core/Common/test/itkConicShellInteriorExteriorSpatialFunctionTest.cxx index 2d667fbc2d3..5c8b58acc6e 100644 --- a/Modules/Core/Common/test/itkConicShellInteriorExteriorSpatialFunctionTest.cxx +++ b/Modules/Core/Common/test/itkConicShellInteriorExteriorSpatialFunctionTest.cxx @@ -31,10 +31,10 @@ itkConicShellInteriorExteriorSpatialFunctionTest(int, char *[]) constexpr unsigned int PointDimension = 3; // Define the point coordinate representation type - using PointCoordRepType = float; + using PointCoordinateType = float; // Define the point type - using PointType = itk::Point; + using PointType = itk::Point; // Define the type for the conic spatial function using ConicShellInteriorExteriorSpatialFunctionType = @@ -42,7 +42,7 @@ itkConicShellInteriorExteriorSpatialFunctionTest(int, char *[]) // Create the conic shell function - ConicShellInteriorExteriorSpatialFunctionType::Pointer conicShellInteriorExteriorSpatialFunction = + const ConicShellInteriorExteriorSpatialFunctionType::Pointer conicShellInteriorExteriorSpatialFunction = ConicShellInteriorExteriorSpatialFunctionType::New(); ITK_EXERCISE_BASIC_OBJECT_METHODS(conicShellInteriorExteriorSpatialFunction, @@ -50,18 +50,16 @@ itkConicShellInteriorExteriorSpatialFunctionTest(int, char *[]) InteriorExteriorSpatialFunction); // Set the conic shell properties - ConicShellInteriorExteriorSpatialFunctionType::InputType origin; - origin.Fill(1.0); + auto origin = itk::MakeFilled(1.0); conicShellInteriorExteriorSpatialFunction->SetOrigin(origin); ITK_TEST_SET_GET_VALUE(origin, conicShellInteriorExteriorSpatialFunction->GetOrigin()); - ConicShellInteriorExteriorSpatialFunctionType::GradientType originGradient; - originGradient.Fill(1.6); + auto originGradient = itk::MakeFilled(1.6); originGradient.GetVnlVector().normalize(); conicShellInteriorExteriorSpatialFunction->SetOriginGradient(originGradient); - double tolerance = 10e-6; + constexpr double tolerance = 10e-6; std::cerr.precision(static_cast(itk::Math::abs(std::log10(tolerance)))); for (unsigned int i = 0; i < originGradient.Size(); ++i) { @@ -76,15 +74,15 @@ itkConicShellInteriorExteriorSpatialFunctionTest(int, char *[]) } } - double distanceMin = 10.0; + constexpr double distanceMin = 10.0; conicShellInteriorExteriorSpatialFunction->SetDistanceMin(distanceMin); ITK_TEST_SET_GET_VALUE(distanceMin, conicShellInteriorExteriorSpatialFunction->GetDistanceMin()); - double distanceMax = 50.0; + constexpr double distanceMax = 50.0; conicShellInteriorExteriorSpatialFunction->SetDistanceMax(distanceMax); ITK_TEST_SET_GET_VALUE(distanceMax, conicShellInteriorExteriorSpatialFunction->GetDistanceMax()); - double epsilon = 1e-3; + constexpr double epsilon = 1e-3; conicShellInteriorExteriorSpatialFunction->SetEpsilon(epsilon); ITK_TEST_SET_GET_VALUE(epsilon, conicShellInteriorExteriorSpatialFunction->GetEpsilon()); diff --git a/Modules/Core/Common/test/itkConnectedImageNeighborhoodShapeGTest.cxx b/Modules/Core/Common/test/itkConnectedImageNeighborhoodShapeGTest.cxx index 9a83f801b2c..2ca4311d425 100644 --- a/Modules/Core/Common/test/itkConnectedImageNeighborhoodShapeGTest.cxx +++ b/Modules/Core/Common/test/itkConnectedImageNeighborhoodShapeGTest.cxx @@ -49,7 +49,7 @@ Assert_GetNumberOfOffsets_returns_expected_number() "Checked ConnectedImageNeighborhoodShape::GetNumberOfOffsets()."); // Test GetNumberOfOffsets() on a non-const shape, at run-time: - ShapeType nonConstShape = constexprShape; + const ShapeType nonConstShape = constexprShape; ASSERT_EQ(nonConstShape.GetNumberOfOffsets(), VExpectedNumberOfOffsets); } @@ -82,7 +82,7 @@ Assert_GenerateImageNeighborhoodOffsets_returns_expected_offsets_excluding_cente { using ShapeType = itk::ConnectedImageNeighborhoodShape; - const bool includeCenterPixel = false; + constexpr bool includeCenterPixel = false; const ShapeType shape{ VMaximumCityblockDistance, includeCenterPixel }; ASSERT_EQ(GenerateImageNeighborhoodOffsets(shape), expectedOffsets); @@ -125,7 +125,7 @@ Assert_Offsets_are_unique_and_colexicographically_ordered() for (unsigned int maximumCityblockDistance = 0; maximumCityblockDistance < VImageDimension; ++maximumCityblockDistance) { - for (bool includeCenterPixel : { false, true }) + for (const bool includeCenterPixel : { false, true }) { const ShapeType shape{ maximumCityblockDistance, includeCenterPixel }; const std::vector offsets = GenerateImageNeighborhoodOffsets(shape); @@ -249,14 +249,12 @@ TEST(ConnectedImageNeighborhoodShape, SupportsConstShapedNeighborhoodIterator) // Create a "dummy" image. const auto image = ImageType::New(); - SizeType imageSize; - imageSize.Fill(1); + auto imageSize = SizeType::Filled(1); image->SetRegions(imageSize); image->AllocateInitialized(); // Create a radius, (just) large enough for all offsets activated below here. - SizeType radius; - radius.Fill(1); + auto radius = SizeType::Filled(1); itk::ConstShapedNeighborhoodIterator shapedNeighborhoodIterator{ radius, image, diff --git a/Modules/Core/Common/test/itkConstNeighborhoodIteratorTest.cxx b/Modules/Core/Common/test/itkConstNeighborhoodIteratorTest.cxx index 05beff7fa37..41b466d00cb 100644 --- a/Modules/Core/Common/test/itkConstNeighborhoodIteratorTest.cxx +++ b/Modules/Core/Common/test/itkConstNeighborhoodIteratorTest.cxx @@ -34,10 +34,9 @@ GetTestImage(int d1, int d2, int d3, int d4) sizeND[2] = d3; sizeND[3] = d4; - itk::Index<4> origND; - origND.Fill(0); + constexpr itk::Index<4> origND{}; - itk::ImageRegion<4> RegionND{ origND, sizeND }; + const itk::ImageRegion<4> RegionND{ origND, sizeND }; auto imageND = TestImageType::New(); imageND->SetRegions(RegionND); @@ -51,7 +50,7 @@ GetTestImage(int d1, int d2, int d3, int d4) int itkConstNeighborhoodIteratorTest(int, char *[]) { - TestImageType::Pointer img = GetTestImage(10, 10, 5, 3); + const TestImageType::Pointer img = GetTestImage(10, 10, 5, 3); itk::ConstNeighborhoodIterator::IndexType loc; loc[0] = 4; loc[1] = 4; @@ -177,7 +176,7 @@ itkConstNeighborhoodIteratorTest(int, char *[]) println("Testing random access iteration"); - TestImageType::Pointer ra_img = GetTestImage(10, 10, 5, 3); + const TestImageType::Pointer ra_img = GetTestImage(10, 10, 5, 3); loc[0] = 4; loc[1] = 4; loc[2] = 2; @@ -193,8 +192,7 @@ itkConstNeighborhoodIteratorTest(int, char *[]) printnb>(ra_it, false); println("Adding [1, 1, 1, 1]"); - OffsetType a_off; - a_off.Fill(1); + auto a_off = itk::MakeFilled(1); ra_it += a_off; printnb>(ra_it, false); @@ -226,8 +224,8 @@ itkConstNeighborhoodIteratorTest(int, char *[]) // Test IndexInBounds // println("Testing IndexInBounds"); - int dims[4] = { 13, 11, 9, 7 }; - TestImageType::Pointer iib_img = GetTestImage(dims[0], dims[1], dims[2], dims[3]); + constexpr int dims[4] = { 13, 11, 9, 7 }; + const TestImageType::Pointer iib_img = GetTestImage(dims[0], dims[1], dims[2], dims[3]); radius[0] = 4; radius[1] = 3; radius[2] = 2; @@ -318,13 +316,11 @@ itkConstNeighborhoodIteratorTest(int, char *[]) { // Create an image using ChangeRegionTestImageType = itk::Image; - ChangeRegionTestImageType::IndexType imageCorner; - imageCorner.Fill(0); + constexpr ChangeRegionTestImageType::IndexType imageCorner{}; - ChangeRegionTestImageType::SizeType imageSize; - imageSize.Fill(4); + auto imageSize = ChangeRegionTestImageType::SizeType::Filled(4); - ChangeRegionTestImageType::RegionType imageRegion(imageCorner, imageSize); + const ChangeRegionTestImageType::RegionType imageRegion(imageCorner, imageSize); auto image = ChangeRegionTestImageType::New(); image->SetRegions(imageRegion); @@ -348,17 +344,14 @@ itkConstNeighborhoodIteratorTest(int, char *[]) } // Setup and iterate over the first region - ChangeRegionTestImageType::IndexType region1Start; - region1Start.Fill(1); + auto region1Start = ChangeRegionTestImageType::IndexType::Filled(1); - ChangeRegionTestImageType::SizeType regionSize; - regionSize.Fill(1); + auto regionSize = ChangeRegionTestImageType::SizeType::Filled(1); - ChangeRegionTestImageType::RegionType region1(region1Start, regionSize); + const ChangeRegionTestImageType::RegionType region1(region1Start, regionSize); // Create the radius (a 3x3 region) - ChangeRegionTestImageType::SizeType neighborhoodRadius; - neighborhoodRadius.Fill(1); + auto neighborhoodRadius = ChangeRegionTestImageType::SizeType::Filled(1); using NeighborhoodIteratorType = itk::ConstNeighborhoodIterator; NeighborhoodIteratorType neighborhoodIterator(neighborhoodRadius, image, region1); @@ -387,10 +380,9 @@ itkConstNeighborhoodIteratorTest(int, char *[]) } // Change iteration region - ChangeRegionTestImageType::IndexType region2start; - region2start.Fill(2); + auto region2start = ChangeRegionTestImageType::IndexType::Filled(2); - ChangeRegionTestImageType::RegionType region2(region2start, regionSize); + const ChangeRegionTestImageType::RegionType region2(region2start, regionSize); neighborhoodIterator.SetRegion(region2); neighborhoodIterator.GoToBegin(); diff --git a/Modules/Core/Common/test/itkConstNeighborhoodIteratorWithOnlyIndexTest.cxx b/Modules/Core/Common/test/itkConstNeighborhoodIteratorWithOnlyIndexTest.cxx index a01c7f58640..1532af6cf4e 100644 --- a/Modules/Core/Common/test/itkConstNeighborhoodIteratorWithOnlyIndexTest.cxx +++ b/Modules/Core/Common/test/itkConstNeighborhoodIteratorWithOnlyIndexTest.cxx @@ -29,10 +29,9 @@ itkConstNeighborhoodIteratorWithOnlyIndexTestGetTestImage(int d1, int d2, int d3 sizeND[2] = d3; sizeND[3] = d4; - itk::Index<4> origND; - origND.Fill(0); + constexpr itk::Index<4> origND{}; - itk::ImageRegion<4> RegionND{ origND, sizeND }; + const itk::ImageRegion<4> RegionND{ origND, sizeND }; auto imageND = TImage::New(); imageND->SetRegions(RegionND); @@ -44,7 +43,7 @@ template int itkConstNeighborhoodIteratorWithOnlyIndexTestRun() { - typename TImage::Pointer img = itkConstNeighborhoodIteratorWithOnlyIndexTestGetTestImage(10, 10, 5, 3); + const typename TImage::Pointer img = itkConstNeighborhoodIteratorWithOnlyIndexTestGetTestImage(10, 10, 5, 3); using ImageType = TImage; using ConstNeighborhoodIteratorType = itk::ConstNeighborhoodIteratorWithOnlyIndex; @@ -213,7 +212,8 @@ itkConstNeighborhoodIteratorWithOnlyIndexTestRun() std::cout << "Testing random access iteration" << std::endl; - typename ImageType::Pointer ra_img = itkConstNeighborhoodIteratorWithOnlyIndexTestGetTestImage(10, 10, 5, 3); + const typename ImageType::Pointer ra_img = + itkConstNeighborhoodIteratorWithOnlyIndexTestGetTestImage(10, 10, 5, 3); loc[0] = 4; loc[1] = 4; loc[2] = 2; @@ -242,8 +242,7 @@ itkConstNeighborhoodIteratorWithOnlyIndexTestRun() ra_it.SetLocation(loc); std::cout << "Adding [1, 1, 1, 1]" << std::endl; - OffsetType a_off; - a_off.Fill(1); + auto a_off = itk::MakeFilled(1); ra_it += a_off; for (unsigned int i = 0; i < 4; ++i) { @@ -357,8 +356,8 @@ itkConstNeighborhoodIteratorWithOnlyIndexTestRun() // Test IndexInBounds // std::cout << "Testing IndexInBounds" << std::endl; - int dims[4] = { 13, 11, 9, 7 }; - typename ImageType::Pointer iib_img = + constexpr int dims[4] = { 13, 11, 9, 7 }; + const typename ImageType::Pointer iib_img = itkConstNeighborhoodIteratorWithOnlyIndexTestGetTestImage(dims[0], dims[1], dims[2], dims[3]); radius[0] = 4; radius[1] = 3; diff --git a/Modules/Core/Common/test/itkConstShapedNeighborhoodIteratorTest.cxx b/Modules/Core/Common/test/itkConstShapedNeighborhoodIteratorTest.cxx index 1c115a53d9c..409f2598200 100644 --- a/Modules/Core/Common/test/itkConstShapedNeighborhoodIteratorTest.cxx +++ b/Modules/Core/Common/test/itkConstShapedNeighborhoodIteratorTest.cxx @@ -22,9 +22,8 @@ void PrintShapedNeighborhood(const itk::ConstShapedNeighborhoodIterator & n) { - itk::ConstShapedNeighborhoodIterator::ConstIterator it; std::cout << n.GetIndex() << "->["; - for (it = n.Begin(); !it.IsAtEnd(); ++it) + for (itk::ConstShapedNeighborhoodIterator::ConstIterator it = n.Begin(); !it.IsAtEnd(); ++it) { std::cout << it.Get(); } @@ -34,7 +33,7 @@ PrintShapedNeighborhood(const itk::ConstShapedNeighborhoodIterator::IndexType loc; loc[0] = 4; loc[1] = 4; @@ -300,8 +299,8 @@ itkConstShapedNeighborhoodIteratorTest(int, char *[]) std::cout << "it.GetActiveIndexListSize()=" << it.GetActiveIndexListSize(); println("Testing GetActiveIndexList()"); - itk::ConstShapedNeighborhoodIterator::IndexListType l = it.GetActiveIndexList(); - itk::ConstShapedNeighborhoodIterator::IndexListType ::const_iterator ali = l.begin(); + itk::ConstShapedNeighborhoodIterator::IndexListType l = it.GetActiveIndexList(); + auto ali = l.begin(); while (ali != l.end()) { std::cout << *ali << ' '; @@ -310,29 +309,29 @@ itkConstShapedNeighborhoodIteratorTest(int, char *[]) std::cout << std::endl; println("Testing const iteration through the neighborhood."); - itk::ConstShapedNeighborhoodIterator::ConstIterator ci = it.Begin(); - - println("Testing using IsAtEnd()"); - while (!ci.IsAtEnd()) { - std::cout << ci.GetNeighborhoodIndex() << " -> " << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl; - ci++; + println("Testing using IsAtEnd()"); + itk::ConstShapedNeighborhoodIterator::ConstIterator ci = it.Begin(); + while (!ci.IsAtEnd()) + { + std::cout << ci.GetNeighborhoodIndex() << " -> " << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl; + ++ci; + } } - println("Testing using != it.End()"); - for (ci = it.Begin(); ci != it.End(); ++ci) + for (auto ci = it.Begin(); ci != it.End(); ++ci) { std::cout << ci.GetNeighborhoodIndex() << " -> " << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl; } println("Testing reverse iteration using != it.Begin()"); - ci = it.End(); + auto ci = it.End(); --ci; while (ci != it.Begin()) { std::cout << ci.GetNeighborhoodIndex() << " -> " << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl; - ci--; + --ci; } std::cout << ci.GetNeighborhoodIndex() << " -> " << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl; @@ -417,13 +416,11 @@ itkConstShapedNeighborhoodIteratorTest(int, char *[]) { // Create an image using ChangeRegionTestImageType = itk::Image; - ChangeRegionTestImageType::IndexType imageCorner; - imageCorner.Fill(0); + constexpr ChangeRegionTestImageType::IndexType imageCorner{}; - ChangeRegionTestImageType::SizeType imageSize; - imageSize.Fill(4); + auto imageSize = ChangeRegionTestImageType::SizeType::Filled(4); - ChangeRegionTestImageType::RegionType imageRegion(imageCorner, imageSize); + const ChangeRegionTestImageType::RegionType imageRegion(imageCorner, imageSize); auto image = ChangeRegionTestImageType::New(); image->SetRegions(imageRegion); @@ -447,17 +444,14 @@ itkConstShapedNeighborhoodIteratorTest(int, char *[]) } // Setup and iterate over the first region - ChangeRegionTestImageType::IndexType region1Start; - region1Start.Fill(1); + auto region1Start = ChangeRegionTestImageType::IndexType::Filled(1); - ChangeRegionTestImageType::SizeType regionSize; - regionSize.Fill(1); + auto regionSize = ChangeRegionTestImageType::SizeType::Filled(1); - ChangeRegionTestImageType::RegionType region1(region1Start, regionSize); + const ChangeRegionTestImageType::RegionType region1(region1Start, regionSize); // Create the radius (a 3x3 region) - ChangeRegionTestImageType::SizeType neighborhoodRadius; - neighborhoodRadius.Fill(1); + auto neighborhoodRadius = ChangeRegionTestImageType::SizeType::Filled(1); // Use the first two offsets std::vector> offsets; @@ -499,10 +493,9 @@ itkConstShapedNeighborhoodIteratorTest(int, char *[]) //} // Change iteration region - ChangeRegionTestImageType::IndexType region2start; - region2start.Fill(2); + auto region2start = ChangeRegionTestImageType::IndexType::Filled(2); - ChangeRegionTestImageType::RegionType region2(region2start, regionSize); + const ChangeRegionTestImageType::RegionType region2(region2start, regionSize); shapedNeighborhoodIterator.SetRegion(region2); shapedNeighborhoodIterator.GoToBegin(); diff --git a/Modules/Core/Common/test/itkConstShapedNeighborhoodIteratorTest2.cxx b/Modules/Core/Common/test/itkConstShapedNeighborhoodIteratorTest2.cxx index bcd5c1e2f7b..12d1e209095 100644 --- a/Modules/Core/Common/test/itkConstShapedNeighborhoodIteratorTest2.cxx +++ b/Modules/Core/Common/test/itkConstShapedNeighborhoodIteratorTest2.cxx @@ -44,7 +44,7 @@ template void MyDerivedCSNI::TestNewExposedProtectedMembers() { - bool needToUseBoundaryCondition(this->GetNeedToUseBoundaryCondition()); + const bool needToUseBoundaryCondition(this->GetNeedToUseBoundaryCondition()); this->NeedToUseBoundaryConditionOn(); this->NeedToUseBoundaryConditionOff(); this->SetNeedToUseBoundaryCondition(needToUseBoundaryCondition); @@ -53,7 +53,7 @@ MyDerivedCSNI::TestNewExposedProtectedMembers() int itkConstShapedNeighborhoodIteratorTest2(int, char *[]) { - TestImageType::Pointer img = GetTestImage(10, 10, 5, 3); + const TestImageType::Pointer img = GetTestImage(10, 10, 5, 3); MyDerivedCSNI::IndexType loc; loc[0] = 4; loc[1] = 4; diff --git a/Modules/Core/Common/test/itkConstantBoundaryConditionTest.cxx b/Modules/Core/Common/test/itkConstantBoundaryConditionTest.cxx index 13b15b92ecc..e14b90bb4d9 100644 --- a/Modules/Core/Common/test/itkConstantBoundaryConditionTest.cxx +++ b/Modules/Core/Common/test/itkConstantBoundaryConditionTest.cxx @@ -39,10 +39,10 @@ TestPrintNeighborhood(IteratorType & p, VectorIteratorType & v) std::cout << "Output from operator()(const OffsetType &, const OffsetType &, const NeighborhoodType *) const" << std::endl; - unsigned int x, y, i = 0; - for (y = 0; y < p.GetSize()[1]; ++y) + + for (unsigned int y = 0, i = 0; y < p.GetSize()[1]; ++y) { - for (x = 0; x < p.GetSize()[0]; ++x, ++i) + for (unsigned int x = 0; x < p.GetSize()[0]; ++x, ++i) { std::cout << p.GetPixel(i) << ' '; } @@ -52,10 +52,9 @@ TestPrintNeighborhood(IteratorType & p, VectorIteratorType & v) std::cout << "Output from operator()(const OffsetType &, const OffsetType &, const NeighborhoodType *, " << "const NeighborhoodAccessorFunctorType &) const" << std::endl; - i = 0; - for (y = 0; y < v.GetSize()[1]; ++y) + for (unsigned int y = 0, i = 0; y < v.GetSize()[1]; ++y) { - for (x = 0; x < v.GetSize()[0]; ++x, ++i) + for (unsigned int x = 0; x < v.GetSize()[0]; ++x, ++i) { std::cout << v.GetPixel(i)[0] << ' '; } @@ -64,20 +63,19 @@ TestPrintNeighborhood(IteratorType & p, VectorIteratorType & v) std::cout << "Output from GetPixel( const IndexType & index, const TImage * image ) const" << std::endl; - i = 0; - for (y = 0; y < p.GetSize()[1]; ++y) + for (unsigned int y = 0, i = 0; y < p.GetSize()[1]; ++y) { itk::Index<2> index; index[1] = p.GetIndex()[1] - p.GetRadius()[1] + y; - for (x = 0; x < p.GetSize()[0]; ++x, ++i) + for (unsigned int x = 0; x < p.GetSize()[0]; ++x, ++i) { index[0] = p.GetIndex()[0] - p.GetRadius()[0] + x; // Access the pixel value through three different methods in the // boundary condition. - int pixel1 = p.GetBoundaryCondition()->GetPixel(index, p.GetImagePointer()); - int pixel2 = p.GetPixel(i); - int pixel3 = v.GetPixel(i)[0]; + const int pixel1 = p.GetBoundaryCondition()->GetPixel(index, p.GetImagePointer()); + const int pixel2 = p.GetPixel(i); + const int pixel3 = v.GetPixel(i)[0]; std::cout << pixel1 << ' '; @@ -123,10 +121,10 @@ int itkConstantBoundaryConditionTest(int, char *[]) { // Test an image to cover one operator() method. - auto image = ImageType::New(); - RegionType imageRegion; - SizeType imageSize = { { 5, 5 } }; - IndexType imageIndex = { { 0, 0 } }; + auto image = ImageType::New(); + constexpr SizeType imageSize = { { 5, 5 } }; + constexpr IndexType imageIndex = { { 0, 0 } }; + RegionType imageRegion; imageRegion.SetSize(imageSize); imageRegion.SetIndex(imageIndex); image->SetRegions(imageRegion); @@ -161,7 +159,7 @@ itkConstantBoundaryConditionTest(int, char *[]) itk::ConstantBoundaryCondition bc; itk::ConstantBoundaryCondition vbc; - ImageType::PixelType constant = 3; + constexpr ImageType::PixelType constant = 3; bc.SetConstant(constant); if (bc.GetConstant() != constant) @@ -190,7 +188,7 @@ itkConstantBoundaryConditionTest(int, char *[]) for (it.GoToBegin(), vit.GoToBegin(); !it.IsAtEnd(); ++it, ++vit) { std::cout << "Index: " << it.GetIndex() << std::endl; - bool success = TestPrintNeighborhood(it, vit); + const bool success = TestPrintNeighborhood(it, vit); if (!success) { return EXIT_FAILURE; @@ -211,7 +209,7 @@ itkConstantBoundaryConditionTest(int, char *[]) for (it2.GoToBegin(), vit2.GoToBegin(); !it2.IsAtEnd(); ++it2, ++vit2) { std::cout << "Index: " << it2.GetIndex() << std::endl; - bool success = TestPrintNeighborhood(it2, vit2); + const bool success = TestPrintNeighborhood(it2, vit2); if (!success) { return EXIT_FAILURE; @@ -219,26 +217,18 @@ itkConstantBoundaryConditionTest(int, char *[]) } // Now test the input region calculation - IndexType requestIndex; - SizeType requestSize; - RegionType requestRegion; - - IndexType expectedIndex; - SizeType expectedSize; - RegionType expectedRegion; - - RegionType inputRegion; // Test 1 std::cout << "GetInputRequestedRegion() Test 1" << std::endl; - requestIndex.Fill(0); - requestSize.Fill(2); + IndexType requestIndex{}; + auto requestSize = SizeType::Filled(2); + RegionType requestRegion; requestRegion.SetIndex(requestIndex); requestRegion.SetSize(requestSize); - expectedRegion = requestRegion; + RegionType expectedRegion = requestRegion; - inputRegion = bc.GetInputRequestedRegion(imageRegion, requestRegion); + RegionType inputRegion = bc.GetInputRequestedRegion(imageRegion, requestRegion); if (!CheckInputRequestedRegion(imageRegion, inputRegion, expectedRegion)) { std::cerr << "[FAILED]" << std::endl; @@ -255,11 +245,11 @@ itkConstantBoundaryConditionTest(int, char *[]) requestRegion.SetIndex(requestIndex); requestRegion.SetSize(requestSize); - expectedIndex[0] = 0; - expectedIndex[1] = 0; + auto expectedIndex = itk::MakeFilled(0); + expectedRegion.SetIndex(expectedIndex); + SizeType expectedSize = { 1, 2 }; expectedSize[0] = 1; expectedSize[1] = 2; - expectedRegion.SetIndex(expectedIndex); expectedRegion.SetSize(expectedSize); inputRegion = bc.GetInputRequestedRegion(imageRegion, requestRegion); diff --git a/Modules/Core/Common/test/itkConstantBoundaryImageNeighborhoodPixelAccessPolicyGTest.cxx b/Modules/Core/Common/test/itkConstantBoundaryImageNeighborhoodPixelAccessPolicyGTest.cxx index 3ed8708de17..5cbad17f338 100644 --- a/Modules/Core/Common/test/itkConstantBoundaryImageNeighborhoodPixelAccessPolicyGTest.cxx +++ b/Modules/Core/Common/test/itkConstantBoundaryImageNeighborhoodPixelAccessPolicyGTest.cxx @@ -89,8 +89,8 @@ TEST(ConstantBoundaryImageNeighborhoodPixelAccessPolicy, YieldsZeroOutsideImageB const auto image = CreateImage(sizeX, sizeY); image->FillBuffer(42); - const ImageType::IndexType locationOutsideImage{ { -1, -1 } }; - const itk::Size radius = { {} }; + constexpr ImageType::IndexType locationOutsideImage{ { -1, -1 } }; + constexpr itk::Size radius = { {} }; const std::vector> offsets = itk::GenerateRectangularImageNeighborhoodOffsets(radius); const RangeType range{ *image, locationOutsideImage, offsets }; @@ -119,8 +119,8 @@ TEST(ConstantBoundaryImageNeighborhoodPixelAccessPolicy, YieldsSpecifiedConstant const auto image = CreateImage(sizeX, sizeY); image->FillBuffer(42); - const ImageType::IndexType locationOutsideImage{ { -1, -1 } }; - const itk::Size radius = { {} }; + constexpr ImageType::IndexType locationOutsideImage{ { -1, -1 } }; + constexpr itk::Size radius = { {} }; const std::vector> offsets = itk::GenerateRectangularImageNeighborhoodOffsets(radius); const auto numberOfExpectedNeighbors = offsets.size(); @@ -163,8 +163,8 @@ TEST(ConstantBoundaryImageNeighborhoodPixelAccessPolicy, YieldsSameValuesAsConst }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - const ImageType::IndexType location{ {} }; - const itk::Size radius = { { 1, 2 } }; + constexpr ImageType::IndexType location{ {} }; + constexpr itk::Size radius = { { 1, 2 } }; const std::vector> offsets = itk::GenerateRectangularImageNeighborhoodOffsets(radius); diff --git a/Modules/Core/Common/test/itkCopyGTest.cxx b/Modules/Core/Common/test/itkCopyGTest.cxx index d5be421afe7..b5e32c3550e 100644 --- a/Modules/Core/Common/test/itkCopyGTest.cxx +++ b/Modules/Core/Common/test/itkCopyGTest.cxx @@ -104,7 +104,7 @@ TEST(Copy, AllowsUsingAutoKeywordCopyingWithoutWarnings) // Sanity check: the copy of the vector and the copy of the array still have the same elements. EXPECT_TRUE(std::equal(copyOfVector.cbegin(), copyOfVector.cend(), copyOfArray.cbegin(), copyOfArray.cend())); - // The following demonstates an `itk::Copy` use case when having structured bindings: + // The following demonstrates an `itk::Copy` use case when having structured bindings: auto originalPair = std::make_pair(std::vector{ 1, 2, 3, 4 }, std::array{ 1, 2, 3, 4 }); const auto [first, second] = itk::Copy(GetReference(originalPair)); diff --git a/Modules/Core/Common/test/itkCovariantVectorGeometryTest.cxx b/Modules/Core/Common/test/itkCovariantVectorGeometryTest.cxx index ad5afb3e748..243e61c9a05 100644 --- a/Modules/Core/Common/test/itkCovariantVectorGeometryTest.cxx +++ b/Modules/Core/Common/test/itkCovariantVectorGeometryTest.cxx @@ -53,7 +53,7 @@ itkCovariantVectorGeometryTest(int, char *[]) std::cout << "vb = (1,3,5) = "; std::cout << vb << std::endl; - VectorType vc = vb - va; + const VectorType vc = vb - va; std::cout << "vc = vb - va = "; std::cout << vc << std::endl; @@ -73,7 +73,7 @@ itkCovariantVectorGeometryTest(int, char *[]) std::cout << "ve -= vb = "; std::cout << ve << std::endl; - VectorType vh = vb; + const VectorType vh = vb; std::cout << "vh = vb = "; std::cout << vh << std::endl; @@ -81,15 +81,15 @@ itkCovariantVectorGeometryTest(int, char *[]) std::cout << "vg( va ) = "; std::cout << vg << std::endl; - ValueType norm2 = vg.GetSquaredNorm(); + const ValueType norm2 = vg.GetSquaredNorm(); std::cout << "vg squared norm = "; std::cout << norm2 << std::endl; - ValueType norm = vg.GetNorm(); + const ValueType norm = vg.GetNorm(); std::cout << "vg norm = "; std::cout << norm << std::endl; - ValueType normX = vg.Normalize(); + const ValueType normX = vg.Normalize(); std::cout << "vg after normalizing: " << vg << std::endl; if (norm != normX) { @@ -137,7 +137,7 @@ itkCovariantVectorGeometryTest(int, char *[]) { std::cout << "Test for CastFrom() method... "; - const float tolerance = 1e-7; + constexpr float tolerance = 1e-7; // CovariantVector Classes using DoubleCovariantVectorType = itk::CovariantVector; @@ -190,7 +190,7 @@ itkCovariantVectorGeometryTest(int, char *[]) covariant[1] = 3.0; covariant[2] = 5.0; - const double expectedValue = -28.0; + constexpr double expectedValue = -28.0; if (!itk::Math::FloatAlmostEqual(expectedValue, covariant * contravariant) || !itk::Math::FloatAlmostEqual(expectedValue, contravariant * covariant)) @@ -240,7 +240,7 @@ itkCovariantVectorGeometryTest(int, char *[]) using CovariantVectorType = itk::CovariantVector; CovariantVectorType::ComponentType comp(1.0); double x(1.0); - if (sizeof(comp) != sizeof(double)) + if constexpr (sizeof(comp) != sizeof(double)) { std::cerr << "error -- CovariantVectorType::ComponentType size != sizeof(double)" << std::endl; return EXIT_FAILURE; diff --git a/Modules/Core/Common/test/itkCrossHelperTest.cxx b/Modules/Core/Common/test/itkCrossHelperTest.cxx index 0d7d6426470..7d4e4c2f882 100644 --- a/Modules/Core/Common/test/itkCrossHelperTest.cxx +++ b/Modules/Core/Common/test/itkCrossHelperTest.cxx @@ -22,29 +22,26 @@ int -itkCrossHelperTest(int argc, char * argv[]) +itkCrossHelperTest(int itkNotUsed(argc), char * itkNotUsed(argv)[]) { - (void)argc; - (void)argv; - constexpr unsigned int Dimension2D = 2; constexpr unsigned int Dimension3D = 3; constexpr unsigned int Dimension4D = 4; - using CoordRepType = double; + using CoordinateType = double; - using Vector2DType = itk::Vector; - using Vector3DType = itk::Vector; - using Vector4DType = itk::Vector; + using Vector2DType = itk::Vector; + using Vector3DType = itk::Vector; + using Vector4DType = itk::Vector; using Cross2DType = itk::CrossHelper; - Cross2DType cross2d; + constexpr Cross2DType cross2d; using Cross3DType = itk::CrossHelper; - Cross3DType cross3d; + constexpr Cross3DType cross3d; using Cross4DType = itk::CrossHelper; - Cross4DType cross4d; + constexpr Cross4DType cross4d; Vector2DType u2d; u2d[0] = 1.; diff --git a/Modules/Core/Common/test/itkDataObjectAndProcessObjectTest.cxx b/Modules/Core/Common/test/itkDataObjectAndProcessObjectTest.cxx index f244dbee231..b61caab1c65 100644 --- a/Modules/Core/Common/test/itkDataObjectAndProcessObjectTest.cxx +++ b/Modules/Core/Common/test/itkDataObjectAndProcessObjectTest.cxx @@ -228,8 +228,8 @@ itkDataObjectAndProcessObjectTest(int, char *[]) ITK_TEST_SET_GET_VALUE(true, process->GetReleaseDataBeforeUpdateFlag()); ITK_TEST_EXPECT_TRUE(itk::MultiThreaderBase::GetGlobalDefaultNumberOfThreads() <= process->GetNumberOfWorkUnits()); - process->SetNumberOfWorkUnits(11); - ITK_TEST_SET_GET_VALUE(11, process->GetNumberOfWorkUnits()); + process->SetNumberOfWorkUnits(itk::ITK_MAX_THREADS - 1); + ITK_TEST_SET_GET_VALUE(itk::ITK_MAX_THREADS - 1, process->GetNumberOfWorkUnits()); process->SetNumberOfWorkUnits(0); ITK_TEST_SET_GET_VALUE(1, process->GetNumberOfWorkUnits()); process->SetNumberOfWorkUnits(itk::NumericTraits::max()); @@ -238,14 +238,14 @@ itkDataObjectAndProcessObjectTest(int, char *[]) ITK_TEST_SET_GET_VALUE(itk::MultiThreaderBase::GetGlobalDefaultNumberOfThreads(), process->GetNumberOfWorkUnits()); // not sure what to test with that method - at least test that it exist - itk::MultiThreaderBase::Pointer multiThreader = process->GetMultiThreader(); + const itk::MultiThreaderBase::Pointer multiThreader = process->GetMultiThreader(); ITK_TEST_SET_GET_VALUE(true, multiThreader.IsNotNull()); // create some data object that will be used as input and output - itk::TestDataObject::Pointer input0 = itk::TestDataObject::New(); - itk::TestDataObject::Pointer input1 = itk::TestDataObject::New(); + const itk::TestDataObject::Pointer input0 = itk::TestDataObject::New(); + const itk::TestDataObject::Pointer input1 = itk::TestDataObject::New(); - itk::TestDataObject::Pointer output1 = itk::TestDataObject::New(); + const itk::TestDataObject::Pointer output1 = itk::TestDataObject::New(); // default input values ITK_TEST_SET_GET_NULL_VALUE(process->GetPrimaryInput()); @@ -297,7 +297,7 @@ itkDataObjectAndProcessObjectTest(int, char *[]) process->PopBackInput(); ITK_TEST_SET_GET_VALUE(1, process->GetNumberOfIndexedInputs()); - itk::TestDataObject::Pointer output = itk::TestDataObject::New(); + const itk::TestDataObject::Pointer output = itk::TestDataObject::New(); process->SetNthOutput(0, output); process->SetNumberOfRequiredInputs(1); diff --git a/Modules/Core/Common/test/itkDataObjectTest.cxx b/Modules/Core/Common/test/itkDataObjectTest.cxx index 8a51ee7d21e..877110c0acb 100644 --- a/Modules/Core/Common/test/itkDataObjectTest.cxx +++ b/Modules/Core/Common/test/itkDataObjectTest.cxx @@ -54,11 +54,11 @@ class DataObjectTestHelper : public DataObject int itkDataObjectTest(int, char *[]) { - itk::DataObjectTestHelper::Pointer dataObject = itk::DataObjectTestHelper::New(); + const itk::DataObjectTestHelper::Pointer dataObject = itk::DataObjectTestHelper::New(); - itk::RealTimeClock::Pointer clock = itk::RealTimeClock::New(); + const itk::RealTimeClock::Pointer clock = itk::RealTimeClock::New(); dataObject->SetRealTimeStamp(clock->GetRealTimeStamp()); - itk::RealTimeStamp timeStamp = dataObject->GetRealTimeStamp(); + const itk::RealTimeStamp timeStamp = dataObject->GetRealTimeStamp(); dataObject->DataHasBeenGenerated(); if (timeStamp != dataObject->GetRealTimeStamp()) { diff --git a/Modules/Core/Common/test/itkDecoratorTest.cxx b/Modules/Core/Common/test/itkDecoratorTest.cxx index 786413b64f4..12169d4ed83 100644 --- a/Modules/Core/Common/test/itkDecoratorTest.cxx +++ b/Modules/Core/Common/test/itkDecoratorTest.cxx @@ -102,7 +102,6 @@ itkDecoratorTest(int, char *[]) ITK_TEST_EXPECT_TRUE(decoratedTransform->Get() == nullptr); using VectorType = std::vector; - using VectorPointer = VectorType *; using VectorObjectType = itk::SimpleDataObjectDecorator; using VectorPointerObjectType = itk::AutoPointerDataObjectDecorator; @@ -117,8 +116,7 @@ itkDecoratorTest(int, char *[]) // ownership of the dynamically allocated memory is passed to the // AutoPointerDataObjectDecorator { - VectorPointer vp; - vp = new VectorType; + auto vp = new VectorType; vp->resize(3); std::cout << *vp << std::endl; diff --git a/Modules/Core/Common/test/itkDirectoryTest.cxx b/Modules/Core/Common/test/itkDirectoryTest.cxx index 537246fa998..27e3bb6f12c 100644 --- a/Modules/Core/Common/test/itkDirectoryTest.cxx +++ b/Modules/Core/Common/test/itkDirectoryTest.cxx @@ -22,7 +22,7 @@ int itkDirectoryTest(int argc, char * argv[]) { - itk::Directory::Pointer directory = itk::Directory::New(); + const itk::Directory::Pointer directory = itk::Directory::New(); if (argc < 2) { diff --git a/Modules/Core/Common/test/itkDownCastTest.cxx b/Modules/Core/Common/test/itkDownCastTest.cxx index 0224b8c3abf..e436eb762cb 100644 --- a/Modules/Core/Common/test/itkDownCastTest.cxx +++ b/Modules/Core/Common/test/itkDownCastTest.cxx @@ -27,7 +27,7 @@ #include "itkTestingMacros.h" using PRODUCER_FUNCTION = itk::Object * (*)(); -using DYNAMIC_DOWNCAST_FUNCTION = int (*)(const char * type, const char * instanceSource, itk::Object const * base); +using DYNAMIC_DOWNCAST_FUNCTION = int (*)(const char * type, const char * instanceSource, const itk::Object * base); int itkDownCastTest(int argc, char * argv[]) @@ -72,7 +72,7 @@ itkDownCastTest(int argc, char * argv[]) } - itk::Object const * equivalencyTableA = libraryAProducer.EquivalencyTable(); + const itk::Object * equivalencyTableA = libraryAProducer.EquivalencyTable(); dynamic_castFailures += LibraryA::dynamic_castDownCastEquivalencyTable("EquivalencyTable", "library A ", equivalencyTableA); dynamic_castFailures += @@ -87,7 +87,7 @@ itkDownCastTest(int argc, char * argv[]) std::cerr << "Could not get the EquivalencyTable function symbol." << std::endl; return EXIT_FAILURE; } - itk::Object const * equivalencyTableB = (*equivalencyTableFunction)(); + const itk::Object * equivalencyTableB = (*equivalencyTableFunction)(); dynamic_castFailures += LibraryA::dynamic_castDownCastEquivalencyTable("EquivalencyTable", "library B ", equivalencyTableB); dynamic_castFailures += @@ -95,7 +95,7 @@ itkDownCastTest(int argc, char * argv[]) dynamic_castFailures += LibraryC::dynamic_castDownCastEquivalencyTable("EquivalencyTable", "library B ", equivalencyTableB); - itk::Object const * equivalencyTableC = libraryCProducer.EquivalencyTable(); + const itk::Object * equivalencyTableC = libraryCProducer.EquivalencyTable(); dynamic_castFailures += LibraryA::dynamic_castDownCastEquivalencyTable("EquivalencyTable", "library C ", equivalencyTableC); dynamic_castFailures += @@ -103,7 +103,7 @@ itkDownCastTest(int argc, char * argv[]) dynamic_castFailures += LibraryC::dynamic_castDownCastEquivalencyTable("EquivalencyTable", "library C ", equivalencyTableC); - itk::Object const * imageA = libraryAProducer.Image(); + const itk::Object * imageA = libraryAProducer.Image(); dynamic_castFailures += LibraryA::dynamic_castDownCastImage("Image ", "library A ", imageA); dynamic_castFailures += libraryBdynamic_castDownCastImage("Image ", "library A ", imageA); dynamic_castFailures += LibraryC::dynamic_castDownCastImage("Image ", "library A ", imageA); @@ -114,12 +114,12 @@ itkDownCastTest(int argc, char * argv[]) std::cerr << "Could not get the Image function symbol." << std::endl; return EXIT_FAILURE; } - itk::Object const * imageB = (*imageFunction)(); + const itk::Object * imageB = (*imageFunction)(); dynamic_castFailures += LibraryA::dynamic_castDownCastImage("Image ", "library B ", imageB); dynamic_castFailures += libraryBdynamic_castDownCastImage("Image ", "library B ", imageB); dynamic_castFailures += LibraryC::dynamic_castDownCastImage("Image ", "library B ", imageB); - itk::Object const * imageC = libraryCProducer.Image(); + const itk::Object * imageC = libraryCProducer.Image(); dynamic_castFailures += LibraryA::dynamic_castDownCastImage("Image ", "library C ", imageC); dynamic_castFailures += libraryBdynamic_castDownCastImage("Image ", "library C ", imageC); dynamic_castFailures += LibraryC::dynamic_castDownCastImage("Image ", "library C ", imageC); diff --git a/Modules/Core/Common/test/itkEllipsoidInteriorExteriorSpatialFunctionTest.cxx b/Modules/Core/Common/test/itkEllipsoidInteriorExteriorSpatialFunctionTest.cxx index f8b05d38f63..956fe5d637a 100644 --- a/Modules/Core/Common/test/itkEllipsoidInteriorExteriorSpatialFunctionTest.cxx +++ b/Modules/Core/Common/test/itkEllipsoidInteriorExteriorSpatialFunctionTest.cxx @@ -42,9 +42,9 @@ itkEllipsoidInteriorExteriorSpatialFunctionTest(int, char *[]) spatialFunc->SetAxes(axes); // Define function doitkEllipsoidInteriorExteriorSpatialFunctionTest, which encapsulates ellipsoid. - int xExtent = 50; - int yExtent = 50; - int zExtent = 50; + constexpr int xExtent = 50; + constexpr int yExtent = 50; + constexpr int zExtent = 50; // Define and set the center of the ellipsoid in the center of // the function doitkEllipsoidInteriorExteriorSpatialFunctionTest @@ -58,8 +58,8 @@ itkEllipsoidInteriorExteriorSpatialFunctionTest(int, char *[]) // (0,1,0) corresponds to the axes of length axes[0] // (1,0,0) corresponds to the axes of length axes[1] // (0,0,1) corresponds to the axes of length axes[2] - double data[] = { 0, 1, 0, 1, 0, 0, 0, 0, 1 }; - vnl_matrix orientations(data, 3, 3); + double data[] = { 0, 1, 0, 1, 0, 0, 0, 0, 1 }; + const vnl_matrix orientations(data, 3, 3); // Set the orientations of the ellipsoids spatialFunc->SetOrientations(orientations); @@ -98,10 +98,10 @@ itkEllipsoidInteriorExteriorSpatialFunctionTest(int, char *[]) functionValue = spatialFunc->Evaluate(testPosition); // Volume of ellipsoid using V=(4/3)*pi*(a/2)*(b/2)*(c/2) - double volume = 4.18879013333 * (axes[0] / 2) * (axes[1] / 2) * (axes[2] / 2); + const double volume = 4.18879013333 * (axes[0] / 2) * (axes[1] / 2) * (axes[2] / 2); // Percent difference in volume measurement and calculation - double volumeError = (itk::Math::abs(volume - interiorPixelCounter) / volume) * 100; + const double volumeError = (itk::Math::abs(volume - interiorPixelCounter) / volume) * 100; std::cout << spatialFunc; diff --git a/Modules/Core/Common/test/itkEventObjectTest.cxx b/Modules/Core/Common/test/itkEventObjectTest.cxx index b00a436e2cf..1fec0aafcb4 100644 --- a/Modules/Core/Common/test/itkEventObjectTest.cxx +++ b/Modules/Core/Common/test/itkEventObjectTest.cxx @@ -35,7 +35,7 @@ itkEventObjectTest(int, char *[]) { // test constructor - itk::TestEvent event; + const itk::TestEvent event; itk::TestDerivedEvent derivedEvent; diff --git a/Modules/Core/Common/test/itkExceptionObjectGTest.cxx b/Modules/Core/Common/test/itkExceptionObjectGTest.cxx index 88173d271ae..0fa6ad68c44 100644 --- a/Modules/Core/Common/test/itkExceptionObjectGTest.cxx +++ b/Modules/Core/Common/test/itkExceptionObjectGTest.cxx @@ -84,18 +84,39 @@ TEST(ExceptionObject, TestDescriptionFromSpecializedExceptionMacro) // Tests that `ExceptionObject::what()` returns the expected concatenation of -// file name, line number, and description. +// file name, line number, location and description. TEST(ExceptionObject, TestWhat) { - const itk::ExceptionObject exceptionObject(__FILE__, __LINE__, "test description"); + { + // Test with empty location. + const itk::ExceptionObject exceptionObject(__FILE__, __LINE__, "test description", ""); + + const char * const what = exceptionObject.what(); + const char * const file = exceptionObject.GetFile(); + const char * const description = exceptionObject.GetDescription(); + + ASSERT_NE(what, nullptr); + ASSERT_NE(file, nullptr); + ASSERT_NE(description, nullptr); + + EXPECT_EQ(what, file + (":" + std::to_string(exceptionObject.GetLine()) + ":\n") + description); + } + { + // Test with location = ITK_LOCATION (as used by ITK's exception macro's). + const itk::ExceptionObject exceptionObject(__FILE__, __LINE__, "test description", ITK_LOCATION); + + const char * const what = exceptionObject.what(); + const char * const file = exceptionObject.GetFile(); + const char * const description = exceptionObject.GetDescription(); + const char * const location = exceptionObject.GetLocation(); - const char * const what = exceptionObject.what(); - const char * const file = exceptionObject.GetFile(); - const char * const description = exceptionObject.GetDescription(); + ASSERT_NE(what, nullptr); + ASSERT_NE(file, nullptr); + ASSERT_NE(description, nullptr); + ASSERT_NE(location, nullptr); - ASSERT_NE(what, nullptr); - ASSERT_NE(file, nullptr); - ASSERT_NE(description, nullptr); - EXPECT_EQ(what, file + (":" + std::to_string(exceptionObject.GetLine()) + ":\n") + description); + EXPECT_EQ(what, + file + (":" + std::to_string(exceptionObject.GetLine()) + ": in '" + location + "':\n") + description); + } } diff --git a/Modules/Core/Common/test/itkExceptionObjectTest.cxx b/Modules/Core/Common/test/itkExceptionObjectTest.cxx index 8dd1107e384..07e69b9a8c8 100644 --- a/Modules/Core/Common/test/itkExceptionObjectTest.cxx +++ b/Modules/Core/Common/test/itkExceptionObjectTest.cxx @@ -73,7 +73,7 @@ mammal::operator==(mammal & o) int lookup(const int i) { - static int table[5] = { 23, 42, 42, 32, 12 }; + static const int table[5] = { 23, 42, 42, 32, 12 }; if (!(0 <= i && i < 5)) { itk::RangeError e(__FILE__, __LINE__); @@ -133,13 +133,14 @@ itkExceptionObjectTest(int, char *[]) bool OneShouldFail = true; try { - human john, jane; - naked_mole_rat hal; + human john; OneShouldFail &= (john == john); // OK + human jane; OneShouldFail &= (jane == john); // OK // NOTE: (hal == john) throws an exception, and does not actually return false! // This means that the &= operator below is never executed, and // the OneShouldFail variable is never actually set to false! + naked_mole_rat hal; OneShouldFail &= (hal == john); // ERROR } catch (const itk::IncompatibleOperandsError & e) diff --git a/Modules/Core/Common/test/itkExtractImage3Dto2DTest.cxx b/Modules/Core/Common/test/itkExtractImage3Dto2DTest.cxx index a1ed39fa5c0..6d119438966 100644 --- a/Modules/Core/Common/test/itkExtractImage3Dto2DTest.cxx +++ b/Modules/Core/Common/test/itkExtractImage3Dto2DTest.cxx @@ -32,10 +32,10 @@ itkExtractImage3Dto2DTest(int, char *[]) auto src = RandomImageSourceType::New(); src->SetMin(0); src->SetMax(255); - Image3DType::SizeType size = { { 16, 16, 16 } }; + constexpr Image3DType::SizeType size = { { 16, 16, 16 } }; src->SetSize(size); src->Update(); - Image3DType::Pointer im3d(src->GetOutput()); + const Image3DType::Pointer im3d(src->GetOutput()); Image3DType::DirectionType dir = im3d->GetDirection(); dir[1][1] = 0.0; dir[1][2] = 1.0; @@ -63,7 +63,7 @@ itkExtractImage3Dto2DTest(int, char *[]) extract->SetExtractionRegion(extractRegion); extract->Update(); - Image2DType::Pointer extractedImage = extract->GetOutput(); + const Image2DType::Pointer extractedImage = extract->GetOutput(); Image2DType::DirectionType identity; identity.SetIdentity(); if (extractedImage->GetDirection() != identity) diff --git a/Modules/Core/Common/test/itkExtractImageTest.cxx b/Modules/Core/Common/test/itkExtractImageTest.cxx index f32ff1c7657..9cea4b747c2 100644 --- a/Modules/Core/Common/test/itkExtractImageTest.cxx +++ b/Modules/Core/Common/test/itkExtractImageTest.cxx @@ -34,16 +34,16 @@ ExtractImageInPlaceTest() using ImageType = itk::Image; using SourceType = itk::RandomImageSource; - auto source = SourceType::New(); - ImageType::SizeType size = { { 32, 32, 32 } }; + auto source = SourceType::New(); + constexpr ImageType::SizeType size = { { 32, 32, 32 } }; source->SetSize(size); source->UpdateLargestPossibleRegion(); - ImageType::IndexType extractIndex = { { 16, 16, 16 } }; - ImageType::SizeType extractSize = { { 8, 8, 8 } }; - ImageType::SizeType zeroSize = { { 0, 0, 0 } }; + constexpr ImageType::IndexType extractIndex = { { 16, 16, 16 } }; + constexpr ImageType::SizeType extractSize = { { 8, 8, 8 } }; + constexpr ImageType::SizeType zeroSize = { { 0, 0, 0 } }; using ExtractFilterType = itk::ExtractImageFilter; auto extract = ExtractFilterType::New(); @@ -89,7 +89,7 @@ ExtractImageInPlaceTest() int itkExtractImageTest(int, char *[]) { - itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); + const itk::FileOutputWindow::Pointer fow = itk::FileOutputWindow::New(); fow->SetInstance(fow); int nextVal; @@ -108,9 +108,9 @@ itkExtractImageTest(int, char *[]) auto if2 = ShortImage::New(); // fill in an image - ShortImage::IndexType index = { { 0, 0 } }; - ShortImage::SizeType size = { { 8, 12 } }; - ShortImage::RegionType region{ index, size }; + ShortImage::IndexType index = { { 0, 0 } }; + ShortImage::SizeType size = { { 8, 12 } }; + const ShortImage::RegionType region{ index, size }; if2->SetLargestPossibleRegion(region); if2->SetBufferedRegion(region); if2->Allocate(); @@ -229,7 +229,7 @@ itkExtractImageTest(int, char *[]) stream->SetInput(extract->GetOutput()); stream->SetNumberOfStreamDivisions(2); - ShortImage::RegionType setRegion = extract->GetExtractionRegion(); + const ShortImage::RegionType setRegion = extract->GetExtractionRegion(); size = setRegion.GetSize(); index = setRegion.GetIndex(); @@ -323,7 +323,7 @@ itkExtractImageTest(int, char *[]) ShortImage::IndexType testIndex; for (; !iteratorLineIn.IsAtEnd(); ++iteratorLineIn) { - LineImage::PixelType linePixelValue = iteratorLineIn.Get(); + const LineImage::PixelType linePixelValue = iteratorLineIn.Get(); testIndex[0] = extractIndex[0]; testIndex[1] = iteratorLineIn.GetIndex()[0]; if (linePixelValue != if2->GetPixel(testIndex)) diff --git a/Modules/Core/Common/test/itkFileOutputWindowTest.cxx b/Modules/Core/Common/test/itkFileOutputWindowTest.cxx index d53590bb7c3..145530135c6 100644 --- a/Modules/Core/Common/test/itkFileOutputWindowTest.cxx +++ b/Modules/Core/Common/test/itkFileOutputWindowTest.cxx @@ -40,15 +40,15 @@ itkFileOutputWindowTest(int, char *[]) std::cout << "window->GetFileName(): " << fileName2 << std::endl; // Test itkSetMacros - const bool flush = false; + constexpr bool flush = false; window->SetFlush(flush); - const bool append = false; + constexpr bool append = false; window->SetAppend(append); // Test itkGetMacros - bool flush2 = window->GetFlush(); + const bool flush2 = window->GetFlush(); std::cout << "window->GetFlush(): " << flush2 << std::endl; - bool append2 = window->GetAppend(); + const bool append2 = window->GetAppend(); std::cout << "window->GetAppend(): " << append2 << std::endl; // Test itkBooleanMacros diff --git a/Modules/Core/Common/test/itkFilterDispatchTest.cxx b/Modules/Core/Common/test/itkFilterDispatchTest.cxx index bcf3f3f26fe..10cdf88681b 100644 --- a/Modules/Core/Common/test/itkFilterDispatchTest.cxx +++ b/Modules/Core/Common/test/itkFilterDispatchTest.cxx @@ -150,7 +150,8 @@ ExampleImageFilter::Execute(const DispatchBase &) * instantiation. */ template -void ExampleImageFilter::Execute(Dispatch<2>) +void +ExampleImageFilter::Execute(Dispatch<2>) { std::cout << "2d-specific Execute() has been called." << std::endl; @@ -170,7 +171,8 @@ void ExampleImageFilter::Execute(Dispatch<2>) * instantiation. */ template -void ExampleImageFilter::Execute(Dispatch<3>) +void +ExampleImageFilter::Execute(Dispatch<3>) { std::cout << "3d-specific Execute() has been called." << std::endl; @@ -190,7 +192,8 @@ void ExampleImageFilter::Execute(Dispatch<3>) * fail to compile. */ template -void ExampleImageFilter::Execute(Dispatch<0>) +void +ExampleImageFilter::Execute(Dispatch<0>) { // this_should_not_have_been_instantiated(); throw std::string("The 0-Dispatch method should not have been called."); @@ -252,9 +255,7 @@ itkFilterDispatchTest(int, char *[]) std::cout << "The test has passed." << std::endl; return EXIT_SUCCESS; } - else - { - std::cout << "The test has failed." << std::endl; - return EXIT_FAILURE; - } + + std::cout << "The test has failed." << std::endl; + return EXIT_FAILURE; } diff --git a/Modules/Core/Common/test/itkFiniteCylinderSpatialFunctionTest.cxx b/Modules/Core/Common/test/itkFiniteCylinderSpatialFunctionTest.cxx index 4cacc8ae0fe..ac2ff4fe11e 100644 --- a/Modules/Core/Common/test/itkFiniteCylinderSpatialFunctionTest.cxx +++ b/Modules/Core/Common/test/itkFiniteCylinderSpatialFunctionTest.cxx @@ -44,14 +44,14 @@ itkFiniteCylinderSpatialFunctionTest(int, char *[]) orientation[2] = 0.0; ITK_TRY_EXPECT_EXCEPTION(spatialFunc->SetOrientation(orientation)); - double axis = 40.0; + constexpr double axis = 40.0; spatialFunc->SetAxisLength(axis); ITK_TEST_SET_GET_VALUE(axis, spatialFunc->GetAxisLength()); // Define function, which encapsulates cylinder. - int xExtent = 50; - int yExtent = 50; - int zExtent = 50; + constexpr int xExtent = 50; + constexpr int yExtent = 50; + constexpr int zExtent = 50; TCylinderFunctionVectorType center; center[0] = xExtent / 2; @@ -66,7 +66,7 @@ itkFiniteCylinderSpatialFunctionTest(int, char *[]) spatialFunc->SetOrientation(orientation); ITK_TEST_SET_GET_VALUE(orientation, spatialFunc->GetOrientation()); - double radius = 5.0; + constexpr double radius = 5.0; spatialFunc->SetRadius(radius); ITK_TEST_SET_GET_VALUE(radius, spatialFunc->GetRadius()); @@ -103,10 +103,10 @@ itkFiniteCylinderSpatialFunctionTest(int, char *[]) functionValue = spatialFunc->Evaluate(testPosition); // Volume of cylinder using V=pi*r^2*h - double volume = 3.14159 * pow(radius, 2) * axis; + const double volume = 3.14159 * pow(radius, 2) * axis; // Percent difference in volume measurement and calculation - double volumeError = (itk::Math::abs(volume - interiorPixelCounter) / volume) * 100; + const double volumeError = (itk::Math::abs(volume - interiorPixelCounter) / volume) * 100; std::cout << spatialFunc; diff --git a/Modules/Core/Common/test/itkFixedArrayGTest.cxx b/Modules/Core/Common/test/itkFixedArrayGTest.cxx index 0fbd7bb63c6..1f14a61c4c0 100644 --- a/Modules/Core/Common/test/itkFixedArrayGTest.cxx +++ b/Modules/Core/Common/test/itkFixedArrayGTest.cxx @@ -17,7 +17,9 @@ *=========================================================================*/ // Enable testing legacy member functions rBegin() and rEnd(). -#define ITK_LEGACY_TEST +#ifndef ITK_LEGACY_REMOVE +# define ITK_LEGACY_TEST +#endif // First include the header file to be tested: #include "itkFixedArray.h" @@ -56,7 +58,7 @@ Check_FixedArray_supports_retrieving_values_by_range_based_for_loop() EXPECT_EQ(stdArrayIterator, stdArray.cend()); // Now test retrieving the values from a non-const FixedArray: - itk::FixedArray nonConstFixedArray{ stdArray }; + const itk::FixedArray nonConstFixedArray{ stdArray }; stdArrayIterator = stdArray.cbegin(); @@ -243,6 +245,14 @@ Is_Filled_FixedArray_correctly_filled() } +template +constexpr bool +Check_FixedArray_value_type() +{ + static_assert(std::is_same_v::value_type, TValue>); + return true; +} + } // End of namespace static_assert(Is_Filled_FixedArray_correctly_filled<0>() && Is_Filled_FixedArray_correctly_filled<1>() && @@ -255,6 +265,9 @@ static_assert(itk::RangeGTestUtilities::CheckConstexprBeginAndEndOfContainer() && Check_FixedArray_value_type()); + + // Tests that the values of a FixedArray (either const or non-const) can be retrieved by a // range-based for-loop. TEST(FixedArray, SupportsRetrievingValuesByRangeBasedForLoop) diff --git a/Modules/Core/Common/test/itkFixedArrayTest.cxx b/Modules/Core/Common/test/itkFixedArrayTest.cxx index 0d0c538ed40..bd5d33ca247 100644 --- a/Modules/Core/Common/test/itkFixedArrayTest.cxx +++ b/Modules/Core/Common/test/itkFixedArrayTest.cxx @@ -31,7 +31,7 @@ Set_c_Array(int x[3]) } void -Print_Array(itk::FixedArray x, std::ostream & os) +Print_Array(const itk::FixedArray & x, std::ostream & os) { os << '{' << x[0] << ',' << x[1] << ',' << x[2] << '}' << std::endl; } @@ -43,7 +43,7 @@ Print_c_ArrayConst(const int x[3], std::ostream & os) } void -Print_Array5(itk::FixedArray x, std::ostream & os) +Print_Array5(const itk::FixedArray & x, std::ostream & os) { os << '{' << x[0] << ',' << x[1] << ',' << x[2] << ',' << x[3] << ',' << x[4] << '}' << std::endl; } @@ -70,8 +70,7 @@ itkFixedArrayTest(int, char *[]) Set_c_Array(array3.GetDataPointer()); Print_Array(array3, std::cout); - itk::FixedArray array4; - array4.Fill(0); + constexpr itk::FixedArray array4{}; Print_Array(array4, std::cout); // Test operator!= and operator== diff --git a/Modules/Core/Common/test/itkFixedArrayTest2.cxx b/Modules/Core/Common/test/itkFixedArrayTest2.cxx index af603bb7847..9687588a87d 100644 --- a/Modules/Core/Common/test/itkFixedArrayTest2.cxx +++ b/Modules/Core/Common/test/itkFixedArrayTest2.cxx @@ -25,31 +25,26 @@ int itkFixedArrayTest2(int, char *[]) { // Define the number of elements in the array - const unsigned int nelements = 10000000L; + constexpr unsigned int nelements = 10000000L; // Define the number of runs used for timing constexpr unsigned int nrun = 10; // Declare a simple timer - clock_t t; using ArrayType = itk::FixedArray; // Declare an array of nelements FixedArray // and add a small margin to play with pointers // but not map outside the allocated memory - auto * vec = new ArrayType[nelements + 8]; - - // Fill it up with zeros - memset(vec, 0, (nelements + 8) * sizeof(ArrayType)); - + auto * vec = new ArrayType[nelements + 8](); // Display the alignment of the array std::cout << "Initial alignment: " << (((size_t)vec) & 7) << '\n'; // Start a simple experiment - t = clock(); - double acc1 = 0.0; + clock_t t = clock(); + double acc1 = 0.0; for (unsigned int i = 0; i < nrun; ++i) { diff --git a/Modules/Core/Common/test/itkFloatingPointExceptionsTest.cxx b/Modules/Core/Common/test/itkFloatingPointExceptionsTest.cxx index 6696356597c..490980b3046 100644 --- a/Modules/Core/Common/test/itkFloatingPointExceptionsTest.cxx +++ b/Modules/Core/Common/test/itkFloatingPointExceptionsTest.cxx @@ -36,19 +36,19 @@ itkFloatingPointExceptionsTest(int argc, char * argv[]) std::cout << "No test specified" << std::endl; return 1; } - int error_return(0); - double double_zero = itkFloatingPointExceptionsTest_double_zero; - double double_max = itkFloatingPointExceptionsTest_double_max; - double test1 = itkFloatingPointExceptionsTest_double_zero; + int error_return(0); + const double double_zero = itkFloatingPointExceptionsTest_double_zero; + const double double_max = itkFloatingPointExceptionsTest_double_max; + const double test1 = itkFloatingPointExceptionsTest_double_zero; - std::string testName(argv[1]); + const std::string testName(argv[1]); if (testName == "DivByZero") { std::cout << "Testing floating point divide by zero" << std::endl; std::cout.flush(); try { - double s = 1.0 / double_zero; + const double s = 1.0 / double_zero; // // should never reach here std::cout << "Divide by Zero Exception not caught" @@ -68,7 +68,7 @@ itkFloatingPointExceptionsTest(int argc, char * argv[]) std::cout.flush(); try { - double s = test1 / double_zero; + const double s = test1 / double_zero; // // should never reach here std::cout << "Zero divide by Zero Exception not caught" diff --git a/Modules/Core/Common/test/itkFloodFillIteratorTest.cxx b/Modules/Core/Common/test/itkFloodFillIteratorTest.cxx index 5b4db9142aa..3efb543e715 100644 --- a/Modules/Core/Common/test/itkFloodFillIteratorTest.cxx +++ b/Modules/Core/Common/test/itkFloodFillIteratorTest.cxx @@ -91,8 +91,8 @@ itkFloodFillIteratorTest(int, char *[]) std::cout << "Sphere spatial function created" << std::endl; //---------Create and initialize a spatial function iterator----------- - TImageType::IndexType seedPos; - const TImageType::IndexValueType pos[] = { 10, 10, 10 }; + TImageType::IndexType seedPos; + constexpr TImageType::IndexValueType pos[] = { 10, 10, 10 }; seedPos.SetIndex(pos); using TItType = itk::FloodFilledSpatialFunctionConditionalIterator; diff --git a/Modules/Core/Common/test/itkFloodFilledSpatialFunctionTest.cxx b/Modules/Core/Common/test/itkFloodFilledSpatialFunctionTest.cxx index 21816b5811f..ffd894a8903 100644 --- a/Modules/Core/Common/test/itkFloodFilledSpatialFunctionTest.cxx +++ b/Modules/Core/Common/test/itkFloodFilledSpatialFunctionTest.cxx @@ -91,8 +91,8 @@ itkFloodFilledSpatialFunctionTest(int, char *[]) spatialFunc->SetCenter(center); // Create and initialize a spatial function iterator - ImageType::IndexType seedPos; - const ImageType::IndexValueType pos[] = { 2, 2 }; + ImageType::IndexType seedPos; + constexpr ImageType::IndexValueType pos[] = { 2, 2 }; seedPos.SetIndex(pos); using ItType = itk::FloodFilledSpatialFunctionConditionalIterator; diff --git a/Modules/Core/Common/test/itkFrustumSpatialFunctionTest.cxx b/Modules/Core/Common/test/itkFrustumSpatialFunctionTest.cxx index 97b2f9b0377..1c583d1a2b5 100644 --- a/Modules/Core/Common/test/itkFrustumSpatialFunctionTest.cxx +++ b/Modules/Core/Common/test/itkFrustumSpatialFunctionTest.cxx @@ -29,10 +29,10 @@ itkFrustumSpatialFunctionTest(int, char *[]) constexpr unsigned int PointDimension = 3; // Define the point coordinate representation type - using PointCoordRepType = float; + using PointCoordinateType = float; // Define the point type - using PointType = itk::Point; + using PointType = itk::Point; // Define the type for the frustum spatial function using FrustumSpatialFunctionType = itk::FrustumSpatialFunction; @@ -43,8 +43,7 @@ itkFrustumSpatialFunctionTest(int, char *[]) ITK_EXERCISE_BASIC_OBJECT_METHODS(frustrumSpatialFunction, FrustumSpatialFunction, InteriorExteriorSpatialFunction); // Set the frustum properties - FrustumSpatialFunctionType::InputType apex; - apex.Fill(1.1); + auto apex = itk::MakeFilled(1.1); frustrumSpatialFunction->SetApex(apex); ITK_TEST_SET_GET_VALUE(apex, frustrumSpatialFunction->GetApex()); @@ -57,15 +56,15 @@ itkFrustumSpatialFunctionTest(int, char *[]) frustrumSpatialFunction->SetBottomPlane(bottomPlane); ITK_TEST_SET_GET_VALUE(bottomPlane, frustrumSpatialFunction->GetBottomPlane()); - double angleZ = 36; + constexpr double angleZ = 36; frustrumSpatialFunction->SetAngleZ(angleZ); ITK_TEST_SET_GET_VALUE(angleZ, frustrumSpatialFunction->GetAngleZ()); - double apertureAngleX = 54; + constexpr double apertureAngleX = 54; frustrumSpatialFunction->SetApertureAngleX(apertureAngleX); ITK_TEST_SET_GET_VALUE(apertureAngleX, frustrumSpatialFunction->GetApertureAngleX()); - double apertureAngleY = 120; + constexpr double apertureAngleY = 120; frustrumSpatialFunction->SetApertureAngleY(apertureAngleY); ITK_TEST_SET_GET_VALUE(apertureAngleY, frustrumSpatialFunction->GetApertureAngleY()); diff --git a/Modules/Core/Common/test/itkGaussianDerivativeOperatorTest.cxx b/Modules/Core/Common/test/itkGaussianDerivativeOperatorTest.cxx index d5ffdf105cc..093cb0dcda4 100644 --- a/Modules/Core/Common/test/itkGaussianDerivativeOperatorTest.cxx +++ b/Modules/Core/Common/test/itkGaussianDerivativeOperatorTest.cxx @@ -34,7 +34,7 @@ TestGaussianOperator(double variance, double error, unsigned int width, unsigned GaussianOp op; - const bool normalizeAcrossScale = false; + constexpr bool normalizeAcrossScale = false; ITK_TEST_SET_GET_BOOLEAN((&op), NormalizeAcrossScale, normalizeAcrossScale); op.SetVariance(variance); @@ -54,12 +54,12 @@ TestGaussianOperator(double variance, double error, unsigned int width, unsigned op.CreateDirectional(); - double total = std::accumulate(op.Begin(), op.End(), 0.0); + const double total = std::accumulate(op.Begin(), op.End(), 0.0); std::cout << "total: " << total << std::endl; std::cout.precision(16); - const double epsilon = itk::NumericTraits::epsilon() * 32; + constexpr double epsilon = itk::NumericTraits::epsilon() * 32; if (order == 0 && itk::Math::abs(total - 1.0) > epsilon) { std::cerr << "Test failed!" << std::endl; @@ -103,22 +103,22 @@ itkGaussianDerivativeOperatorTest(int argc, char * argv[]) // Save the format stream variables for std::cout // They will be restored when coutState goes out of scope. - itk::StdStreamStateSave coutState(std::cout); + const itk::StdStreamStateSave coutState(std::cout); if (argc == 6) { - double variance = std::stod(argv[1]); - double error = std::stod(argv[2]); - unsigned int width = std::stoi(argv[3]); - unsigned int order = std::stoi(argv[4]); - double spacing = std::stod(argv[5]); + const double variance = std::stod(argv[1]); + const double error = std::stod(argv[2]); + const unsigned int width = std::stoi(argv[3]); + const unsigned int order = std::stoi(argv[4]); + const double spacing = std::stod(argv[5]); TestGaussianOperator(variance, error, width, order, spacing); std::cout << "Test finished." << std::endl; return EXIT_SUCCESS; } - else if (argc > 1) + if (argc > 1) { std::cerr << "Missing Parameters." << std::endl; std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " [variance error width order spacing]" @@ -140,12 +140,7 @@ itkGaussianDerivativeOperatorTest(int argc, char * argv[]) ITK_EXERCISE_BASIC_OBJECT_METHODS((&op1), GaussianDerivativeOperator, NeighborhoodOperator); - GaussianOp op2; - // Check assignment - op2 = op1; - - bool testStatus = true; testStatus &= TestGaussianOperator(.2, .001, 30, 0, 1.0); @@ -182,8 +177,6 @@ itkGaussianDerivativeOperatorTest(int argc, char * argv[]) { return EXIT_SUCCESS; } - else - { - return EXIT_FAILURE; - } + + return EXIT_FAILURE; } diff --git a/Modules/Core/Common/test/itkGaussianSpatialFunctionTest.cxx b/Modules/Core/Common/test/itkGaussianSpatialFunctionTest.cxx index 72f30ab7824..bb03f70127a 100644 --- a/Modules/Core/Common/test/itkGaussianSpatialFunctionTest.cxx +++ b/Modules/Core/Common/test/itkGaussianSpatialFunctionTest.cxx @@ -58,7 +58,7 @@ itkGaussianSpatialFunctionTest(int argc, char * argv[]) gaussianSpatialFunction->SetSigma(sigma); ITK_TEST_SET_GET_VALUE(sigma, gaussianSpatialFunction->GetSigma()); - double scale = std::stod(argv[1]); + const double scale = std::stod(argv[1]); gaussianSpatialFunction->SetScale(scale); ITK_TEST_SET_GET_VALUE(scale, gaussianSpatialFunction->GetScale()); @@ -87,7 +87,7 @@ itkGaussianSpatialFunctionTest(int argc, char * argv[]) point[1] = mean[1]; point[2] = mean[2]; - double computedValueAtMean = gaussianSpatialFunction->Evaluate(point); + const double computedValueAtMean = gaussianSpatialFunction->Evaluate(point); double expectedValueAtMean = 1.0; if (gaussianSpatialFunction->GetNormalized()) @@ -99,7 +99,7 @@ itkGaussianSpatialFunctionTest(int argc, char * argv[]) else { constexpr double oneDimensionalFactor = 1.0; - const double factor = oneDimensionalFactor * oneDimensionalFactor * oneDimensionalFactor; + constexpr double factor = oneDimensionalFactor * oneDimensionalFactor * oneDimensionalFactor; expectedValueAtMean = scale / factor; } diff --git a/Modules/Core/Common/test/itkHashTableTest.cxx b/Modules/Core/Common/test/itkHashTableTest.cxx index ddf71ca4c37..e373395bd17 100644 --- a/Modules/Core/Common/test/itkHashTableTest.cxx +++ b/Modules/Core/Common/test/itkHashTableTest.cxx @@ -55,13 +55,13 @@ int itkHashTableTest(int, char *[]) { println("Testing std::hash"); - std::hash H; + constexpr std::hash H; std::cout << "foo -> " << H("foo") << std::endl; std::cout << "bar -> " << H("bar") << std::endl; - std::hash H1; + constexpr std::hash H1; std::cout << "1 -> " << H1(1) << std::endl; std::cout << "234 -> " << H1(234) << std::endl; - std::hash H2; + constexpr std::hash H2; std::cout << "a -> " << H2('a') << std::endl; std::cout << "Z -> " << H2('Z') << std::endl; @@ -87,11 +87,8 @@ itkHashTableTest(int, char *[]) } Set.rehash(50); Set.insert("the horror"); - auto hsh_it = Set.begin(); - HashSetType::const_iterator hst_const_it; - hst_const_it = Set.end(); - HashSetType SetCopy; - SetCopy = Set; + auto hsh_it = Set.begin(); + const HashSetType SetCopy = Set; println("Testing std::unordered_map"); using HashMapType = std::unordered_map, eqstr>; @@ -122,13 +119,10 @@ itkHashTableTest(int, char *[]) std::cout << "Set is empty." << std::endl; } months.rehash(50); - HashMapType::value_type p("psychotic break", 2); + constexpr HashMapType::value_type p("psychotic break", 2); months.insert(p); - auto map_it = months.begin(); - HashMapType::const_iterator map_const_it; - map_const_it = months.end(); - HashMapType MapCopy; - MapCopy = months; + auto map_it = months.begin(); + const HashMapType MapCopy = months; IgnoreUnusedVariable(hsh_it); IgnoreUnusedVariable(map_it); diff --git a/Modules/Core/Common/test/itkHeavisideStepFunctionTest1.cxx b/Modules/Core/Common/test/itkHeavisideStepFunctionTest1.cxx index 4fdda9e00f2..9ec3622ed31 100644 --- a/Modules/Core/Common/test/itkHeavisideStepFunctionTest1.cxx +++ b/Modules/Core/Common/test/itkHeavisideStepFunctionTest1.cxx @@ -31,16 +31,16 @@ itkHeavisideStepFunctionTest1(int, char *[]) std::cout << "GetNameOfClass() = " << functionBase0->GetNameOfClass() << std::endl; functionBase0->Print(std::cout); - const int minValue = -20; + constexpr int minValue = -20; constexpr int maxValue = 20; constexpr InputType incValue = 0.1; for (int x = minValue; x < maxValue; ++x) { - const InputType ix = x * incValue; - OutputType f = functionBase0->Evaluate(ix); - OutputType df = functionBase0->EvaluateDerivative(ix); + const InputType ix = x * incValue; + const OutputType f = functionBase0->Evaluate(ix); + const OutputType df = functionBase0->EvaluateDerivative(ix); std::cout << ix << ' ' << f << ' ' << df << std::endl; } diff --git a/Modules/Core/Common/test/itkImageAdaptorPipeLineTest.cxx b/Modules/Core/Common/test/itkImageAdaptorPipeLineTest.cxx index 29555076a74..bc22a0841e0 100644 --- a/Modules/Core/Common/test/itkImageAdaptorPipeLineTest.cxx +++ b/Modules/Core/Common/test/itkImageAdaptorPipeLineTest.cxx @@ -37,7 +37,7 @@ itkImageAdaptorPipeLineTest(int, char *[]) // Save the format stream variables for std::cout // They will be restored when coutState goes out of scope // scope. - itk::StdStreamStateSave coutState(std::cout); + const itk::StdStreamStateSave coutState(std::cout); //------------------------------------------------------------- // Typedefs @@ -80,9 +80,9 @@ itkImageAdaptorPipeLineTest(int, char *[]) start[1] = 0; start[2] = 0; - myRegionType region{ start, size }; + const myRegionType region{ start, size }; - const float spacing[3] = { 1.0, 1.0, 1.0 }; + constexpr float spacing[3] = { 1.0, 1.0, 1.0 }; //------------------------------------------------------------- // Create and Initialize the RGBPixel image @@ -129,7 +129,7 @@ itkImageAdaptorPipeLineTest(int, char *[]) } - std::cout << "RGBPixel Image Initializaed" << std::endl; + std::cout << "RGBPixel Image Initialized" << std::endl; //------------------------------------------------------------- // Create and Initialize the Float image @@ -143,7 +143,7 @@ itkImageAdaptorPipeLineTest(int, char *[]) myFloatIteratorType itf(myFloatImage, myFloatImage->GetRequestedRegion()); - myFloatPixelType initialFloatValue = 5.0; + constexpr myFloatPixelType initialFloatValue = 5.0; while (!itf.IsAtEnd()) { @@ -168,7 +168,7 @@ itkImageAdaptorPipeLineTest(int, char *[]) ++itf; } - std::cout << "Float Image Initializaed" << std::endl; + std::cout << "Float Image Initialized" << std::endl; //------------------------------------------------------------- @@ -196,7 +196,7 @@ itkImageAdaptorPipeLineTest(int, char *[]) myFloatImageType::Pointer myFloatOutputImage = filter->GetOutput(); myFloatOutputImage->SetSpacing(spacing); - std::cout << "Float Output Image Initializaed" << std::endl; + std::cout << "Float Output Image Initialized" << std::endl; //------------------------------------------------------------- // Force the execution of the filter diff --git a/Modules/Core/Common/test/itkImageAlgorithmCopyTest.cxx b/Modules/Core/Common/test/itkImageAlgorithmCopyTest.cxx index 082161dbcb4..dd751be7e57 100644 --- a/Modules/Core/Common/test/itkImageAlgorithmCopyTest.cxx +++ b/Modules/Core/Common/test/itkImageAlgorithmCopyTest.cxx @@ -32,8 +32,7 @@ AverageTestCopy(typename TImage::SizeType & size) typename ImageType::RegionType region; - typename ImageType::IndexType index; - index.Fill(0); + const typename ImageType::IndexType index{}; region.SetSize(size); region.SetIndex(index); @@ -120,9 +119,7 @@ int itkImageAlgorithmCopyTest(int, char *[]) { using ImageType3D = itk::Image; - ImageType3D::SizeType size3d; - - size3d.Fill(16); + auto size3d = ImageType3D::SizeType::Filled(16); AverageTestCopy(size3d); size3d.Fill(32); @@ -135,9 +132,7 @@ itkImageAlgorithmCopyTest(int, char *[]) AverageTestCopy(size3d); using ImageType2D = itk::Image; - ImageType2D::SizeType size2d; - - size2d.Fill(16); + auto size2d = ImageType2D::SizeType::Filled(16); AverageTestCopy(size2d); size2d.Fill(32); diff --git a/Modules/Core/Common/test/itkImageAlgorithmCopyTest2.cxx b/Modules/Core/Common/test/itkImageAlgorithmCopyTest2.cxx index dd9b44cb3d5..bb509b7d007 100644 --- a/Modules/Core/Common/test/itkImageAlgorithmCopyTest2.cxx +++ b/Modules/Core/Common/test/itkImageAlgorithmCopyTest2.cxx @@ -64,12 +64,10 @@ itkImageAlgorithmCopyTest2(int, char *[]) using RegionType = itk::ImageRegion<3>; - RegionType::IndexType index; - index.Fill(0); - RegionType::SizeType size; - size.Fill(64); + constexpr RegionType::IndexType index{}; + auto size = RegionType::SizeType::Filled(64); - RegionType region{ index, size }; + const RegionType region{ index, size }; auto image1 = Short3DImageType::New(); diff --git a/Modules/Core/Common/test/itkImageBaseGTest.cxx b/Modules/Core/Common/test/itkImageBaseGTest.cxx index 470cc166e0c..f64a67ee15b 100644 --- a/Modules/Core/Common/test/itkImageBaseGTest.cxx +++ b/Modules/Core/Common/test/itkImageBaseGTest.cxx @@ -29,6 +29,14 @@ namespace { +// Tells whether GetImageDimension() returns ImageDimension, for all of the specified values of VImageDimension. +template +constexpr bool GetImageDimension_returns_ImageDimension{ ( + (itk::ImageBase::GetImageDimension() == VImageDimension) && ...) }; + +static_assert(GetImageDimension_returns_ImageDimension<2, 3, 4>, "GetImageDimension() should return ImageDimension."); + + template void Expect_same_type_and_equal_value(T1 && value1, T2 && value2) @@ -129,9 +137,9 @@ CheckInvalidSpacingExceptions() const auto imageBase = itk::ImageBase::New(); // Test exceptions - const SpacingType initialSpacing = imageBase->GetSpacing(); - const auto negativeSpacing = itk::MakeFilled(-1.0); - const SpacingType zeroSpacing{}; + const SpacingType initialSpacing = imageBase->GetSpacing(); + const auto negativeSpacing = itk::MakeFilled(-1.0); + constexpr SpacingType zeroSpacing{}; #if !defined(ITK_LEGACY_REMOVE) // Only a warning is displayed @@ -148,8 +156,8 @@ CheckInvalidSpacingExceptions() EXPECT_THROW(imageBase->SetSpacing(zeroSpacing), itk::ExceptionObject); EXPECT_EQ(imageBase->GetSpacing(), initialSpacing); - const DirectionType initialDirection = imageBase->GetDirection(); - const DirectionType zeroDirection{}; + const DirectionType initialDirection = imageBase->GetDirection(); + constexpr DirectionType zeroDirection{}; EXPECT_THROW(imageBase->SetDirection(zeroDirection), itk::ExceptionObject); diff --git a/Modules/Core/Common/test/itkImageBufferRangeGTest.cxx b/Modules/Core/Common/test/itkImageBufferRangeGTest.cxx index 2481e0594da..d11d541c5d4 100644 --- a/Modules/Core/Common/test/itkImageBufferRangeGTest.cxx +++ b/Modules/Core/Common/test/itkImageBufferRangeGTest.cxx @@ -139,9 +139,8 @@ template typename TImage::Pointer CreateSmallImage() { - const auto image = TImage::New(); - typename TImage::SizeType imageSize; - imageSize.Fill(0); + const auto image = TImage::New(); + const typename TImage::SizeType imageSize{}; image->SetRegions(imageSize); SetVectorLengthIfImageIsVectorImage(*image, 1); image->AllocateInitialized(); @@ -154,9 +153,8 @@ void ExpectRangeIsNotEmptyForNonEmptyImage() { // First create a non-empty image: - const auto image = TImage::New(); - typename TImage::SizeType imageSize; - imageSize.Fill(1); + const auto image = TImage::New(); + auto imageSize = TImage::SizeType::Filled(1); image->SetRegions(imageSize); SetVectorLengthIfImageIsVectorImage(*image, 1); image->Allocate(); @@ -179,9 +177,8 @@ void ExpectMakeImageBufferRangeReturnsCorrectRangeForNonEmptyImage() { // First create a non-empty image: - const auto image = TImage::New(); - typename TImage::SizeType imageSize; - imageSize.Fill(1); + const auto image = TImage::New(); + auto imageSize = TImage::SizeType::Filled(1); image->SetRegions(imageSize); SetVectorLengthIfImageIsVectorImage(*image, 1); image->Allocate(); @@ -249,7 +246,7 @@ TEST(ImageBufferRange, EquivalentBeginOrEndIteratorsCompareEqual) const auto image = CreateImage(2, 3); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; const ImageBufferRange::iterator begin = range.begin(); const ImageBufferRange::iterator end = range.end(); @@ -282,7 +279,7 @@ TEST(ImageBufferRange, BeginAndEndDoNotCompareEqual) const auto image = CreateImage(2, 3); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; EXPECT_FALSE(range.begin() == range.end()); EXPECT_NE(range.begin(), range.end()); @@ -296,7 +293,7 @@ TEST(ImageBufferRange, IteratorConvertsToConstIterator) const auto image = CreateImage(2, 3); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; const ImageBufferRange::iterator begin = range.begin(); const ImageBufferRange::const_iterator const_begin_from_begin = begin; @@ -320,7 +317,7 @@ TEST(ImageBufferRange, IteratorsCanBePassedToStdVectorConstructor) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; // Easily store all pixels of the ImageBufferRange in an std::vector: const std::vector stdVector(range.begin(), range.end()); @@ -342,9 +339,9 @@ TEST(ImageBufferRange, IteratorsCanBePassedToStdReverseCopy) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; - const unsigned int numberOfPixels = sizeX * sizeY; + constexpr unsigned int numberOfPixels = sizeX * sizeY; const std::vector stdVector(range.begin(), range.end()); std::vector reversedStdVector1(numberOfPixels); @@ -380,7 +377,7 @@ TEST(ImageBufferRange, IteratorsCanBePassedToStdInnerProduct) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; const double innerProduct = std::inner_product(range.begin(), range.end(), range.begin(), 0.0); @@ -401,7 +398,7 @@ TEST(ImageBufferRange, IteratorsCanBePassedToStdForEach) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; std::for_each(range.begin(), range.end(), [](const PixelType pixel) { EXPECT_TRUE(pixel > 0); }); } @@ -454,7 +451,7 @@ TEST(ImageBufferRange, DistanceBetweenIteratorsCanBeObtainedBySubtraction) }; const auto image = CreateImage(sizeX, sizeY); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; ImageBufferRange::iterator it1 = range.begin(); @@ -486,7 +483,7 @@ TEST(ImageBufferRange, IteratorReferenceActsLikeARealReference) const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); using RangeType = ImageBufferRange; - RangeType range{ *image }; + const RangeType range{ *image }; RangeType::iterator it = range.begin(); std::iterator_traits::reference reference1 = *it; @@ -534,8 +531,8 @@ TEST(ImageBufferRange, SupportsVectorImage) sizeY = 2, sizeZ = 2 }; - const auto image = ImageType::New(); - const typename ImageType::SizeType imageSize = { { sizeX, sizeY, sizeZ } }; + const auto image = ImageType::New(); + constexpr typename ImageType::SizeType imageSize = { { sizeX, sizeY, sizeZ } }; image->SetRegions(imageSize); image->SetVectorLength(vectorLength); image->AllocateInitialized(); @@ -544,9 +541,9 @@ TEST(ImageBufferRange, SupportsVectorImage) image->FillBuffer(fillPixelValue); using RangeType = ImageBufferRange; - RangeType range{ *image }; + const RangeType range{ *image }; - for (PixelType pixelValue : range) + for (const PixelType pixelValue : range) { EXPECT_EQ(pixelValue, fillPixelValue); } @@ -575,7 +572,7 @@ TEST(ImageBufferRange, IteratorsCanBePassedToStdSort) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; // Initial order: (1, 2, 3, ..., 9). const std::vector initiallyOrderedPixels(range.cbegin(), range.cend()); @@ -606,7 +603,7 @@ TEST(ImageBufferRange, IteratorsCanBePassedToStdNthElement) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - ImageBufferRange range{ *image }; + const ImageBufferRange range{ *image }; std::reverse(range.begin(), range.end()); @@ -646,7 +643,7 @@ TEST(ImageBufferRange, IteratorsSupportRandomAccess) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - RangeType range{ *image }; + const RangeType range{ *image }; // Testing expressions from Table 111 "Random access iterator requirements // (in addition to bidirectional iterator)", C++11 Standard, section 24.2.7 @@ -667,12 +664,12 @@ TEST(ImageBufferRange, IteratorsSupportRandomAccess) { // Expression to be tested: 'r += n' - difference_type n = 3; + constexpr difference_type n = 3; r = initialIterator; - const auto expectedResult = [&r, n] { + const auto expectedResult = [&r](const difference_type nn) { // Operational semantics, as specified by the C++11 Standard: - difference_type m = n; + difference_type m = nn; if (m >= 0) while (m--) ++r; @@ -680,7 +677,7 @@ TEST(ImageBufferRange, IteratorsSupportRandomAccess) while (m++) --r; return r; - }(); + }(n); r = initialIterator; auto && actualResult = r += n; EXPECT_EQ(actualResult, expectedResult); @@ -688,29 +685,29 @@ TEST(ImageBufferRange, IteratorsSupportRandomAccess) } { // Expressions to be tested: 'a + n' and 'n + a' - difference_type n = 3; + constexpr difference_type n = 3; static_assert(std::is_same_v, "Return type tested"); static_assert(std::is_same_v, "Return type tested"); - const auto expectedResult = [a, n] { + const auto expectedResult = [a](const difference_type nn) { // Operational semantics, as specified by the C++11 Standard: X tmp = a; - return tmp += n; - }(); + return tmp += nn; + }(n); EXPECT_EQ(a + n, expectedResult); EXPECT_TRUE(a + n == n + a); } { // Expression to be tested: 'r -= n' - difference_type n = 3; + constexpr difference_type n = 3; r = initialIterator; - const auto expectedResult = [&r, n] { + const auto expectedResult = [&r](const difference_type nn) { // Operational semantics, as specified by the C++11 Standard: - return r += -n; - }(); + return r += -nn; + }(n); r = initialIterator; auto && actualResult = r -= n; EXPECT_EQ(actualResult, expectedResult); @@ -718,15 +715,15 @@ TEST(ImageBufferRange, IteratorsSupportRandomAccess) } { // Expression to be tested: 'a - n' - difference_type n = -3; + constexpr difference_type n = -3; static_assert(std::is_same_v, "Return type tested"); - const auto expectedResult = [a, n] { + const auto expectedResult = [a](const difference_type nn) { // Operational semantics, as specified by the C++11 Standard: X tmp = a; - return tmp -= n; - }(); + return tmp -= nn; + }(n); EXPECT_EQ(a - n, expectedResult); } @@ -734,13 +731,13 @@ TEST(ImageBufferRange, IteratorsSupportRandomAccess) // Expression to be tested: 'b - a' static_assert(std::is_same_v, "Return type tested"); - difference_type n = b - a; + const difference_type n = b - a; EXPECT_TRUE(a + n == b); EXPECT_TRUE(b == a + (b - a)); } { // Expression to be tested: 'a[n]' - difference_type n = 3; + constexpr difference_type n = 3; static_assert(std::is_convertible_v, "Return type tested"); EXPECT_EQ(a[n], *(a + n)); } @@ -750,7 +747,7 @@ TEST(ImageBufferRange, IteratorsSupportRandomAccess) static_assert(std::is_convertible_v b), bool>, "Return type tested"); static_assert(std::is_convertible_v= b), bool>, "Return type tested"); static_assert(std::is_convertible_v, "Return type tested"); - EXPECT_EQ(a 0); + EXPECT_EQ(a < b, b - a > 0); EXPECT_EQ(a > b, b < a); EXPECT_EQ(a >= b, !(a < b)); EXPECT_EQ(a <= b, !(b < a)); @@ -771,7 +768,7 @@ TEST(ImageBufferRange, SupportsSubscript) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - RangeType range{ *image }; + const RangeType range{ *image }; const size_t numberOfNeighbors = range.size(); @@ -779,7 +776,7 @@ TEST(ImageBufferRange, SupportsSubscript) for (size_t i = 0; i < numberOfNeighbors; ++i) { - std::iterator_traits::reference neighbor = range[i]; + std::iterator_traits::reference neighbor = range[i]; // NOLINT EXPECT_EQ(neighbor, *it); ++it; } @@ -798,9 +795,9 @@ TEST(ImageBufferRange, ProvidesReverseIterators) }; const auto image = CreateImageFilledWithSequenceOfNaturalNumbers(sizeX, sizeY); - RangeType range{ *image }; + const RangeType range{ *image }; - const unsigned int numberOfPixels = sizeX * sizeY; + constexpr unsigned int numberOfPixels = sizeX * sizeY; const std::vector stdVector(range.begin(), range.end()); std::vector reversedStdVector1(numberOfPixels); diff --git a/Modules/Core/Common/test/itkImageComputeOffsetAndIndexTest.cxx b/Modules/Core/Common/test/itkImageComputeOffsetAndIndexTest.cxx index cc8e992a8f0..dfce9b0aa3d 100644 --- a/Modules/Core/Common/test/itkImageComputeOffsetAndIndexTest.cxx +++ b/Modules/Core/Common/test/itkImageComputeOffsetAndIndexTest.cxx @@ -40,8 +40,7 @@ template void ComputeFastIndex(TImage * image, unsigned int count, unsigned int repeat) { - typename TImage::IndexType index; - index.Fill(0); + typename TImage::IndexType index{}; const typename TImage::IndexType & bufferedRegionIndex = image->GetBufferedRegion().GetIndex(); const typename TImage::OffsetValueType * offsetTable = image->GetOffsetTable(); @@ -62,13 +61,12 @@ ComputeOffset(TImage * image, unsigned int count, unsigned int repeat) { typename TImage::OffsetValueType offset = 0; typename TImage::OffsetValueType accum = 0; - typename TImage::IndexType index; - typename TImage::OffsetType indexIncr; - indexIncr.Fill(1); + + auto indexIncr = itk::MakeFilled(1); for (unsigned int j = 0; j < repeat; ++j) { - index.Fill(0); + typename TImage::IndexType index{}; for (unsigned int i = 0; i < count; ++i) { @@ -86,15 +84,14 @@ ComputeFastOffset(TImage * image, unsigned int count, unsigned int repeat) { typename TImage::OffsetValueType offset = 0; typename TImage::OffsetValueType accum = 0; - typename TImage::IndexType index; - typename TImage::OffsetType indexIncr; - indexIncr.Fill(1); + + auto indexIncr = itk::MakeFilled(1); const typename TImage::OffsetValueType * offsetTable = image->GetOffsetTable(); for (unsigned int j = 0; j < repeat; ++j) { - index.Fill(0); + typename TImage::IndexType index{}; for (unsigned int i = 0; i < count; ++i) { offset = 0; @@ -113,115 +110,99 @@ itkImageComputeOffsetAndIndexTest(int, char *[]) itk::TimeProbesCollectorBase collector; -#define TRY_FAST_INDEX(dim) \ - { \ - using PixelType = char; \ - using ImageType = itk::Image; \ - auto myImage = ImageType::New(); \ - ImageType::SizeType size; \ - ImageType::IndexType index; \ - ImageType::RegionType region; \ - size.Fill(50); \ - index.Fill(0); \ - region.SetSize(size); \ - region.SetIndex(index); \ - myImage->SetRegions(region); \ - myImage->Allocate(); \ - collector.Start("ComputeIndexFast " #dim "D"); \ - unsigned int totalSize = 1; \ - for (unsigned int i = 0; i < dim; ++i) \ - totalSize *= size[i]; \ - unsigned int repeat = 1000; \ - if (dim > 2) \ - repeat = 100; \ - if (dim > 3) \ - repeat = 10; \ - if (dim > 4) \ - repeat = 1; \ - ComputeFastIndex(myImage, totalSize, repeat); \ - collector.Stop("ComputeIndexFast " #dim "D"); \ - } \ +#define TRY_FAST_INDEX(dim) \ + { \ + using PixelType = char; \ + using ImageType = itk::Image; \ + auto myImage = ImageType::New(); \ + const auto size = ImageType::SizeType::Filled(50); \ + constexpr ImageType::IndexType index{}; \ + const ImageType::RegionType region{ index, size }; \ + myImage->SetRegions(region); \ + myImage->Allocate(); \ + collector.Start("ComputeIndexFast " #dim "D"); \ + unsigned int totalSize = 1; \ + for (unsigned int i = 0; i < dim; ++i) \ + totalSize *= size[i]; \ + unsigned int repeat = 1000; \ + if (dim > 2) \ + repeat = 100; \ + if (dim > 3) \ + repeat = 10; \ + if (dim > 4) \ + repeat = 1; \ + ComputeFastIndex(myImage, totalSize, repeat); \ + collector.Stop("ComputeIndexFast " #dim "D"); \ + } \ ITK_MACROEND_NOOP_STATEMENT -#define TRY_INDEX(dim) \ - { \ - using PixelType = char; \ - using ImageType = itk::Image; \ - auto myImage = ImageType::New(); \ - ImageType::SizeType size; \ - ImageType::IndexType index; \ - ImageType::RegionType region; \ - size.Fill(50); \ - index.Fill(0); \ - region.SetSize(size); \ - region.SetIndex(index); \ - myImage->SetRegions(region); \ - myImage->Allocate(); \ - collector.Start("ComputeIndex " #dim "D"); \ - unsigned int totalSize = 1; \ - for (unsigned int i = 0; i < dim; ++i) \ - totalSize *= size[i]; \ - unsigned int repeat = 1000; \ - if (dim > 2) \ - repeat = 100; \ - if (dim > 3) \ - repeat = 10; \ - if (dim > 4) \ - repeat = 1; \ - ComputeIndex(myImage, totalSize, repeat); \ - collector.Stop("ComputeIndex " #dim "D"); \ - } \ +#define TRY_INDEX(dim) \ + { \ + using PixelType = char; \ + using ImageType = itk::Image; \ + auto myImage = ImageType::New(); \ + const auto size = ImageType::SizeType::Filled(50); \ + constexpr ImageType::IndexType index{}; \ + const ImageType::RegionType region{ index, size }; \ + myImage->SetRegions(region); \ + myImage->Allocate(); \ + collector.Start("ComputeIndex " #dim "D"); \ + unsigned int totalSize = 1; \ + for (unsigned int i = 0; i < dim; ++i) \ + totalSize *= size[i]; \ + unsigned int repeat = 1000; \ + if (dim > 2) \ + repeat = 100; \ + if (dim > 3) \ + repeat = 10; \ + if (dim > 4) \ + repeat = 1; \ + ComputeIndex(myImage, totalSize, repeat); \ + collector.Stop("ComputeIndex " #dim "D"); \ + } \ ITK_MACROEND_NOOP_STATEMENT -#define TRY_FAST_OFFSET(dim) \ - { \ - using PixelType = char; \ - using ImageType = itk::Image; \ - auto myImage = ImageType::New(); \ - ImageType::SizeType size; \ - ImageType::IndexType index; \ - ImageType::RegionType region; \ - size.Fill(50); \ - index.Fill(0); \ - region.SetSize(size); \ - region.SetIndex(index); \ - myImage->SetRegions(region); \ - myImage->Allocate(); \ - collector.Start("ComputeOffsetFast " #dim "D"); \ - unsigned int repeat = 1; \ - if (dim < 4) \ - repeat = 100; \ - unsigned int totalSize = 1; \ - for (unsigned int i = 0; i < dim; ++i) \ - totalSize *= size[i]; \ - ComputeFastOffset(myImage, size[0], totalSize * repeat); \ - collector.Stop("ComputeOffsetFast " #dim "D"); \ - } \ +#define TRY_FAST_OFFSET(dim) \ + { \ + using PixelType = char; \ + using ImageType = itk::Image; \ + auto myImage = ImageType::New(); \ + const auto size = ImageType::SizeType::Filled(50); \ + constexpr ImageType::IndexType index{}; \ + const ImageType::RegionType region{ index, size }; \ + myImage->SetRegions(region); \ + myImage->Allocate(); \ + collector.Start("ComputeOffsetFast " #dim "D"); \ + unsigned int repeat = 1; \ + if (dim < 4) \ + repeat = 100; \ + unsigned int totalSize = 1; \ + for (unsigned int i = 0; i < dim; ++i) \ + totalSize *= size[i]; \ + ComputeFastOffset(myImage, size[0], totalSize * repeat); \ + collector.Stop("ComputeOffsetFast " #dim "D"); \ + } \ ITK_MACROEND_NOOP_STATEMENT -#define TRY_OFFSET(dim) \ - { \ - using PixelType = char; \ - using ImageType = itk::Image; \ - auto myImage = ImageType::New(); \ - ImageType::SizeType size; \ - ImageType::IndexType index; \ - ImageType::RegionType region; \ - size.Fill(50); \ - index.Fill(0); \ - region.SetSize(size); \ - region.SetIndex(index); \ - myImage->SetRegions(region); \ - myImage->Allocate(); \ - collector.Start("ComputeOffset " #dim "D"); \ - unsigned int repeat = 1; \ - if (dim < 4) \ - repeat = 100; \ - unsigned int totalSize = 1; \ - for (unsigned int i = 0; i < dim; ++i) \ - totalSize *= size[i]; \ - ComputeOffset(myImage, size[0], totalSize * repeat); \ - collector.Stop("ComputeOffset " #dim "D"); \ - } \ +#define TRY_OFFSET(dim) \ + { \ + using PixelType = char; \ + using ImageType = itk::Image; \ + auto myImage = ImageType::New(); \ + const auto size = ImageType::SizeType::Filled(50); \ + constexpr ImageType::IndexType index{}; \ + const ImageType::RegionType region{ index, size }; \ + myImage->SetRegions(region); \ + myImage->Allocate(); \ + collector.Start("ComputeOffset " #dim "D"); \ + unsigned int repeat = 1; \ + if (dim < 4) \ + repeat = 100; \ + unsigned int totalSize = 1; \ + for (unsigned int i = 0; i < dim; ++i) \ + totalSize *= size[i]; \ + ComputeOffset(myImage, size[0], totalSize * repeat); \ + collector.Stop("ComputeOffset " #dim "D"); \ + } \ ITK_MACROEND_NOOP_STATEMENT TRY_INDEX(1); diff --git a/Modules/Core/Common/test/itkImageDuplicatorTest.cxx b/Modules/Core/Common/test/itkImageDuplicatorTest.cxx index 5ec3e11b37c..643eddef33d 100644 --- a/Modules/Core/Common/test/itkImageDuplicatorTest.cxx +++ b/Modules/Core/Common/test/itkImageDuplicatorTest.cxx @@ -33,8 +33,7 @@ itkImageDuplicatorTest(int, char *[]) size[0] = 10; size[1] = 20; size[2] = 30; - ImageType::IndexType index; - index.Fill(0); + constexpr ImageType::IndexType index{}; region.SetSize(size); region.SetIndex(index); @@ -192,7 +191,7 @@ itkImageDuplicatorTest(int, char *[]) RGBduplicator->SetInputImage(m_RGBImage); RGBduplicator->Update(); - RGBImageType::Pointer RGBImageCopy = RGBduplicator->GetOutput(); + const RGBImageType::Pointer RGBImageCopy = RGBduplicator->GetOutput(); itk::ImageRegionIterator it4(RGBImageCopy, RGBImageCopy->GetLargestPossibleRegion()); @@ -205,7 +204,7 @@ itkImageDuplicatorTest(int, char *[]) while (!it4.IsAtEnd()) { - itk::RGBPixel pixel = it4.Get(); + const itk::RGBPixel pixel = it4.Get(); if (pixel.GetRed() != r) { std::cout << "Error: Pixel R value mismatched: " << static_cast(pixel.GetRed()) << " vs. " @@ -248,7 +247,7 @@ itkImageDuplicatorTest(int, char *[]) { constexpr unsigned int Dimension = 3; - const unsigned int VectorLength = 2 * Dimension; + constexpr unsigned int VectorLength = 2 * Dimension; using PixelType = float; using VectorImageType = itk::VectorImage; @@ -270,7 +269,7 @@ itkImageDuplicatorTest(int, char *[]) Vectorduplicator->SetInputImage(vectorImage); Vectorduplicator->Update(); - VectorImageType::Pointer vectorImageCopy = Vectorduplicator->GetOutput(); + const VectorImageType::Pointer vectorImageCopy = Vectorduplicator->GetOutput(); itk::ImageRegionIterator it3(vectorImage, vectorImage->GetLargestPossibleRegion()); itk::ImageRegionIterator it4(vectorImageCopy, vectorImageCopy->GetLargestPossibleRegion()); @@ -279,8 +278,8 @@ itkImageDuplicatorTest(int, char *[]) while (!it4.IsAtEnd()) { - itk::VariableLengthVector pixel4 = it4.Get(); - itk::VariableLengthVector pixel3 = it3.Get(); + const itk::VariableLengthVector pixel4 = it4.Get(); + const itk::VariableLengthVector pixel3 = it3.Get(); if (pixel4 != pixel3) { return EXIT_FAILURE; diff --git a/Modules/Core/Common/test/itkImageDuplicatorTest2.cxx b/Modules/Core/Common/test/itkImageDuplicatorTest2.cxx index 85b5a982a4c..5217028e53e 100644 --- a/Modules/Core/Common/test/itkImageDuplicatorTest2.cxx +++ b/Modules/Core/Common/test/itkImageDuplicatorTest2.cxx @@ -47,11 +47,11 @@ itkImageDuplicatorTest2(int argc, char * argv[]) { const auto inImage = itk::ReadImage(argv[1]); - ImageType::RegionType lpr = inImage->GetLargestPossibleRegion(); - ImageType::RegionType region = lpr; + const ImageType::RegionType lpr = inImage->GetLargestPossibleRegion(); + ImageType::RegionType region = lpr; for (unsigned int d = 0; d < Dimension; ++d) { - itk::IndexValueType size = region.GetSize(d); + const itk::IndexValueType size = region.GetSize(d); region.SetIndex(d, size / 4); region.SetSize(d, size / 2); } @@ -59,11 +59,11 @@ itkImageDuplicatorTest2(int argc, char * argv[]) absF->SetInput(inImage); absF->GetOutput()->SetRequestedRegion(region); absF->Update(); - ImageType::Pointer absImage = absF->GetOutput(); // different buffered and largest regions + const ImageType::Pointer absImage = absF->GetOutput(); // different buffered and largest regions dup->SetInputImage(absF->GetOutput()); dup->Update(); - ImageType::ConstPointer dupImage = dup->GetOutput(); + const ImageType::ConstPointer dupImage = dup->GetOutput(); itk::WriteImage(dupImage, argv[2]); std::cout << "Test SUCCESS" << std::endl; diff --git a/Modules/Core/Common/test/itkImageGTest.cxx b/Modules/Core/Common/test/itkImageGTest.cxx index ab17349bdd5..4f0cd44d1f3 100644 --- a/Modules/Core/Common/test/itkImageGTest.cxx +++ b/Modules/Core/Common/test/itkImageGTest.cxx @@ -193,8 +193,8 @@ TEST(Image, UnequalWhenPixelValuesDiffer) // 'FillBuffer(const TPixel&)' defined but not used [-Wunused-function] TEST(Image, FillBufferOfNonEqualityComparableType) { - const auto ImageDimagion = 2U; - const auto image = itk::Image::New(); + constexpr auto ImageDimagion = 2U; + const auto image = itk::Image::New(); image->SetRegions(itk::Size::Filled(1)); image->Allocate(); @@ -221,7 +221,7 @@ TEST(Image, IsXImageGeometry) const auto image1 = generate_image({ 2, 2 }); - const double tol = 1e-8; + constexpr double tol = 1e-8; auto image2 = generate_image({ 2, 2 }); diff --git a/Modules/Core/Common/test/itkImageIORegionGTest.cxx b/Modules/Core/Common/test/itkImageIORegionGTest.cxx index fc1e8297d61..9b2b9ab97ea 100644 --- a/Modules/Core/Common/test/itkImageIORegionGTest.cxx +++ b/Modules/Core/Common/test/itkImageIORegionGTest.cxx @@ -173,7 +173,7 @@ TEST(ImageIORegion, IsTwoDimensionalByDefault) EXPECT_EQ(itk::ImageIORegion(), expectedTwoDimensionalRegion); - itk::ImageIORegion defaultInitializedRegion; + const itk::ImageIORegion defaultInitializedRegion; EXPECT_EQ(defaultInitializedRegion, expectedTwoDimensionalRegion); } diff --git a/Modules/Core/Common/test/itkImageIteratorTest.cxx b/Modules/Core/Common/test/itkImageIteratorTest.cxx index ee883ed7b96..4a8412a28f1 100644 --- a/Modules/Core/Common/test/itkImageIteratorTest.cxx +++ b/Modules/Core/Common/test/itkImageIteratorTest.cxx @@ -27,8 +27,8 @@ template void TestConstPixelAccess(const itk::Image & in, itk::Image & out) { - typename itk::Image::IndexType regionStartIndex3D = { { 5, 10, 15 } }; - typename itk::Image::IndexType regionEndIndex3D = { { 8, 15, 17 } }; + const typename itk::Image::IndexType regionStartIndex3D = { { 5, 10, 15 } }; + const typename itk::Image::IndexType regionEndIndex3D = { { 8, 15, 17 } }; T vec; @@ -49,27 +49,28 @@ itkImageIteratorTest(int, char *[]) constexpr unsigned int ImageDimension = 3; std::cout << "Creating an image" << std::endl; - itk::Image, ImageDimension>::Pointer o3 = + const itk::Image, ImageDimension>::Pointer o3 = itk::Image, ImageDimension>::New(); float origin3D[ImageDimension] = { 5.0f, 2.1f, 8.1f }; float spacing3D[ImageDimension] = { 1.5f, 2.1f, 1.0f }; - itk::Image, ImageDimension>::SizeType imageSize3D = { { 20, 40, 60 } }; + constexpr itk::Image, ImageDimension>::SizeType imageSize3D = { { 20, 40, 60 } }; - itk::Image, ImageDimension>::IndexType startIndex3D = { { 5, 4, 1 } }; - itk::Image, ImageDimension>::IndexType regionStartIndex3D = { { 5, 10, 12 } }; - itk::Image, ImageDimension>::IndexType regionEndIndex3D = { { 8, 15, 17 } }; + constexpr itk::Image, ImageDimension>::IndexType startIndex3D = { { 5, 4, 1 } }; + constexpr itk::Image, ImageDimension>::IndexType regionStartIndex3D = { + { 5, 10, 12 } + }; + constexpr itk::Image, ImageDimension>::IndexType regionEndIndex3D = { { 8, 15, 17 } }; - itk::Image, ImageDimension>::RegionType region{ startIndex3D, imageSize3D }; + const itk::Image, ImageDimension>::RegionType region{ startIndex3D, imageSize3D }; o3->SetRegions(region); o3->SetOrigin(origin3D); o3->SetSpacing(spacing3D); o3->Allocate(); - itk::Vector fillValue; - fillValue.Fill(itk::NumericTraits::max()); + auto fillValue = itk::MakeFilled>(itk::NumericTraits::max()); o3->FillBuffer(fillValue); std::cout << "Setting/Getting a pixel" << std::endl; @@ -91,11 +92,11 @@ itkImageIteratorTest(int, char *[]) using VectorImageIterator = itk::ImageIterator; using VectorImageConstIterator = itk::ImageConstIterator; - VectorImageIterator itr1(o3, region); - VectorImageConstIterator itr2(o3, region); + VectorImageIterator itr1(o3, region); + const VectorImageConstIterator itr2(o3, region); // Exercise copy constructor - VectorImageIterator itr3(itr1); + const VectorImageIterator itr3(itr1); // Exercise assignment operator VectorImageIterator itr4; @@ -151,7 +152,7 @@ itkImageIteratorTest(int, char *[]) } // Exercise GetIndex() - VectorImageType::IndexType index1 = itr1.GetIndex(); + const VectorImageType::IndexType index1 = itr1.GetIndex(); if (index1 != startIndex3D) { std::cerr << "Error in GetIndex()" << std::endl; @@ -176,7 +177,7 @@ itkImageIteratorTest(int, char *[]) } // Exercise GetRegion() - VectorImageType::RegionType region1 = itr1.GetRegion(); + const VectorImageType::RegionType region1 = itr1.GetRegion(); if (region1 != region) { std::cerr << "Error in GetRegion()" << std::endl; diff --git a/Modules/Core/Common/test/itkImageIteratorWithIndexTest.cxx b/Modules/Core/Common/test/itkImageIteratorWithIndexTest.cxx index 37da3c05a6f..87011877286 100644 --- a/Modules/Core/Common/test/itkImageIteratorWithIndexTest.cxx +++ b/Modules/Core/Common/test/itkImageIteratorWithIndexTest.cxx @@ -40,13 +40,11 @@ class itkImageIteratorWithIndexTestIteratorTester { m_Image = ImageType::New(); - typename ImageType::SizeType size; - size.Fill(100); + auto size = ImageType::SizeType::Filled(100); - typename ImageType::IndexType start; - start.Fill(0); + const typename ImageType::IndexType start{}; - typename ImageType::RegionType region{ start, size }; + const typename ImageType::RegionType region{ start, size }; m_Image->SetRegions(region); m_Image->Allocate(); @@ -62,8 +60,8 @@ class itkImageIteratorWithIndexTestIteratorTester it.GoToBegin(); while (!it.IsAtEnd()) { - PixelType value = it.Get(); - PixelType testValue = value * static_cast::ValueType>(2); + const PixelType value = it.Get(); + const PixelType testValue = value * static_cast::ValueType>(2); it.Set(testValue); if (itk::Math::NotExactlyEquals(it.Get(), testValue)) { @@ -89,7 +87,7 @@ class itkImageIteratorWithIndexTestIteratorTester it.GoToBegin(); while (!it.IsAtEnd()) { - PixelType value = it.Get(); + const PixelType value = it.Get(); if (itk::Math::NotExactlyEquals(value, it.Get())) // check repeatibility { std::cerr << "TestConstIterator failed!" << std::endl; @@ -114,7 +112,7 @@ class itkImageIteratorWithIndexTestIteratorTester it.GoToReverseBegin(); while (!it.IsAtReverseEnd()) { - PixelType value = it.Get(); + const PixelType value = it.Get(); if (itk::Math::NotExactlyEquals(value, it.Get())) // check repeatibility { std::cerr << "TestReverseIteration failed!" << std::endl; @@ -266,8 +264,7 @@ itkImageIteratorWithIndexTest(int, char *[]) std::cout << "Testing with Image< itk::Vector, 3 > " << std::endl; using VC = itk::Vector; - VC vc; - vc.Fill(127); + auto vc = itk::MakeFilled(127); itkImageIteratorWithIndexTestIteratorTester TesterVC(vc); if (TesterVC.TestIterator() == false) { @@ -284,8 +281,7 @@ itkImageIteratorWithIndexTest(int, char *[]) std::cout << "Testing with Image< itk::Vector, 3 > " << std::endl; using VUC = itk::Vector; - VUC vuc; - vuc.Fill(10); + auto vuc = itk::MakeFilled(10); itkImageIteratorWithIndexTestIteratorTester TesterVUC(vuc); if (TesterVUC.TestIterator() == false) { @@ -302,8 +298,7 @@ itkImageIteratorWithIndexTest(int, char *[]) std::cout << "Testing with Image< itk::Vector, 3 > " << std::endl; using VS = itk::Vector; - VS vs; - vs.Fill(10); + auto vs = itk::MakeFilled(10); itkImageIteratorWithIndexTestIteratorTester TesterVS(vs); if (TesterVS.TestIterator() == false) { @@ -320,8 +315,7 @@ itkImageIteratorWithIndexTest(int, char *[]) std::cout << "Testing with Image< itk::Vector, 3 > " << std::endl; using VUS = itk::Vector; - VUS vus; - vus.Fill(10); + auto vus = itk::MakeFilled(10); itkImageIteratorWithIndexTestIteratorTester TesterVUS(vus); if (TesterVUS.TestIterator() == false) { @@ -338,8 +332,7 @@ itkImageIteratorWithIndexTest(int, char *[]) std::cout << "Testing with Image< itk::Vector, 3 > " << std::endl; using VI = itk::Vector; - VI vi; - vi.Fill(10); + auto vi = itk::MakeFilled(10); itkImageIteratorWithIndexTestIteratorTester TesterVI(vi); if (TesterVI.TestIterator() == false) { @@ -356,8 +349,7 @@ itkImageIteratorWithIndexTest(int, char *[]) std::cout << "Testing with Image< itk::Vector, 3 > " << std::endl; using VUI = itk::Vector; - VUI vui; - vui.Fill(10); + auto vui = itk::MakeFilled(10); itkImageIteratorWithIndexTestIteratorTester TesterVUI(vui); if (TesterVUI.TestIterator() == false) { @@ -374,8 +366,7 @@ itkImageIteratorWithIndexTest(int, char *[]) std::cout << "Testing with Image< itk::Vector, 3 > " << std::endl; using VF = itk::Vector; - VF vf; - vf.Fill(10); + auto vf = itk::MakeFilled(10); itkImageIteratorWithIndexTestIteratorTester TesterVF(vf); if (TesterVF.TestIterator() == false) { @@ -392,8 +383,7 @@ itkImageIteratorWithIndexTest(int, char *[]) std::cout << "Testing with Image< itk::Vector, 3 > " << std::endl; using VD = itk::Vector; - VD vd; - vd.Fill(10); + auto vd = itk::MakeFilled(10); itkImageIteratorWithIndexTestIteratorTester TesterVD(vd); if (TesterVD.TestIterator() == false) { diff --git a/Modules/Core/Common/test/itkImageIteratorsForwardBackwardTest.cxx b/Modules/Core/Common/test/itkImageIteratorsForwardBackwardTest.cxx index 5c9844ec1a4..90610279a1b 100644 --- a/Modules/Core/Common/test/itkImageIteratorsForwardBackwardTest.cxx +++ b/Modules/Core/Common/test/itkImageIteratorsForwardBackwardTest.cxx @@ -35,10 +35,9 @@ itkImageIteratorsForwardBackwardTest(int, char *[]) size[1] = 4; size[2] = 4; - ImageType::IndexType start; - start.Fill(0); + constexpr ImageType::IndexType start{}; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; myImage->SetRegions(region); myImage->Allocate(); diff --git a/Modules/Core/Common/test/itkImageLinearIteratorTest.cxx b/Modules/Core/Common/test/itkImageLinearIteratorTest.cxx index cab2f5b49c7..7566718f48e 100644 --- a/Modules/Core/Common/test/itkImageLinearIteratorTest.cxx +++ b/Modules/Core/Common/test/itkImageLinearIteratorTest.cxx @@ -32,8 +32,8 @@ itkImageLinearIteratorTest(int, char *[]) using ImageType = itk::Image; - auto myImage = ImageType::New(); - ImageType::ConstPointer myConstImage = myImage; + auto myImage = ImageType::New(); + const ImageType::ConstPointer myConstImage = myImage; ImageType::SizeType size0; @@ -41,10 +41,9 @@ itkImageLinearIteratorTest(int, char *[]) size0[1] = 100; size0[2] = 100; - ImageType::IndexType start0; - start0.Fill(0); + constexpr ImageType::IndexType start0{}; - ImageType::RegionType region0{ start0, size0 }; + const ImageType::RegionType region0{ start0, size0 }; myImage->SetRegions(region0); myImage->Allocate(); @@ -101,7 +100,7 @@ itkImageLinearIteratorTest(int, char *[]) ConstIteratorType cot(myConstImage, region0); // Test exceptions - int direction = ImageType::GetImageDimension() + 1; + constexpr int direction = ImageType::GetImageDimension() + 1; ITK_TRY_EXPECT_EXCEPTION(cot.SetDirection(direction)); cot.GoToBegin(); @@ -154,7 +153,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 3; size[2] = 4; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; std::cout << " IteratorType ior( myImage, region );" << std::endl; IteratorType ior(myImage, region); @@ -233,7 +232,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; IteratorType bot(myImage, region); @@ -279,7 +278,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; ConstIteratorType cbot(myImage, region); @@ -325,7 +324,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; IteratorType cbot(myImage, region); @@ -336,8 +335,8 @@ itkImageLinearIteratorTest(int, char *[]) { while (!cbot.IsAtEndOfLine()) { - ImageType::IndexType index = cbot.GetIndex(); - ImageType::PixelType pixel = cbot.Get(); + const ImageType::IndexType index = cbot.GetIndex(); + const ImageType::PixelType pixel = cbot.Get(); if (index != pixel) { @@ -369,7 +368,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; ConstIteratorType cbot(myImage, region); @@ -380,8 +379,8 @@ itkImageLinearIteratorTest(int, char *[]) { while (!cbot.IsAtEndOfLine()) { - ImageType::IndexType index = cbot.GetIndex(); - ImageType::PixelType pixel = cbot.Get(); + const ImageType::IndexType index = cbot.GetIndex(); + const ImageType::PixelType pixel = cbot.Get(); if (index != pixel) { @@ -413,7 +412,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; std::cout << " IteratorType cbot( myImage, region );" << std::endl; IteratorType cbot(myImage, region); @@ -464,7 +463,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; std::cout << " IteratorType cbot( myImage, region );" << std::endl; IteratorType cbot(myImage, region); @@ -521,7 +520,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; ConstIteratorType cbot(myImage, region); @@ -562,7 +561,7 @@ itkImageLinearIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; ConstIteratorType cbot(myImage, region); diff --git a/Modules/Core/Common/test/itkImageNeighborhoodOffsetsGTest.cxx b/Modules/Core/Common/test/itkImageNeighborhoodOffsetsGTest.cxx index 18cf4af6ba1..8a40e104047 100644 --- a/Modules/Core/Common/test/itkImageNeighborhoodOffsetsGTest.cxx +++ b/Modules/Core/Common/test/itkImageNeighborhoodOffsetsGTest.cxx @@ -58,9 +58,9 @@ class EmptyImageNeighborhoodShape TEST(ImageNeighborhoodOffsets, GenerateImageNeighborhoodOffsetsReturnsEmptyVectorForEmptyShape) { - constexpr unsigned int ImageDimension = 2; - const EmptyImageNeighborhoodShape shape = {}; - const std::vector> offsets = itk::GenerateImageNeighborhoodOffsets(shape); + constexpr unsigned int ImageDimension = 2; + constexpr EmptyImageNeighborhoodShape shape = {}; + const std::vector> offsets = itk::GenerateImageNeighborhoodOffsets(shape); EXPECT_EQ(offsets, std::vector>()); } @@ -68,7 +68,7 @@ TEST(ImageNeighborhoodOffsets, GenerateImageNeighborhoodOffsetsReturnsEmptyVecto TEST(ImageNeighborhoodOffsets, GenerateRectangularImageNeighborhoodOffsetsReturnsOneOffsetForDefaultRadius) { - const itk::Size<> radius = { {} }; + constexpr itk::Size<> radius = { {} }; const std::vector> offsets = itk::GenerateRectangularImageNeighborhoodOffsets(radius); EXPECT_EQ(offsets, std::vector>(1)); @@ -77,7 +77,7 @@ TEST(ImageNeighborhoodOffsets, GenerateRectangularImageNeighborhoodOffsetsReturn TEST(ImageNeighborhoodOffsets, GenerateRectangularImageNeighborhoodOffsetsForSmallestHorizontalNeigborhood) { - const itk::Size<> radius = { { 1, 0 } }; + constexpr itk::Size<> radius = { { 1, 0 } }; const std::vector> offsets = itk::GenerateRectangularImageNeighborhoodOffsets(radius); EXPECT_EQ(offsets, (std::vector>{ { { -1, 0 } }, { { 0, 0 } }, { { 1, 0 } } })); @@ -86,7 +86,7 @@ TEST(ImageNeighborhoodOffsets, GenerateRectangularImageNeighborhoodOffsetsForSma TEST(ImageNeighborhoodOffsets, GenerateRectangularImageNeighborhoodOffsetsForSmallestVerticalNeigborhood) { - const itk::Size<> radius = { { 0, 1 } }; + constexpr itk::Size<> radius = { { 0, 1 } }; const std::vector> offsets = itk::GenerateRectangularImageNeighborhoodOffsets(radius); EXPECT_EQ(offsets, (std::vector>{ { { 0, -1 } }, { { 0, 0 } }, { { 0, 1 } } })); diff --git a/Modules/Core/Common/test/itkImageRandomConstIteratorWithIndexGTest.cxx b/Modules/Core/Common/test/itkImageRandomConstIteratorWithIndexGTest.cxx index 64ad7ba7441..9a5f248ecc8 100644 --- a/Modules/Core/Common/test/itkImageRandomConstIteratorWithIndexGTest.cxx +++ b/Modules/Core/Common/test/itkImageRandomConstIteratorWithIndexGTest.cxx @@ -32,7 +32,7 @@ TEST(ImageRandomConstIteratorWithIndex, IsDeterministicWhenGlobalRandomSeedsAreReset) { using PixelType = int; - const unsigned int Dimension{ 2 }; + constexpr unsigned int Dimension{ 2 }; using ImageType = itk::Image; // Create just a small test image, but still having enough pixels for the iterator to pick different samples from. @@ -64,7 +64,7 @@ TEST(ImageRandomConstIteratorWithIndex, IsDeterministicWhenGlobalRandomSeedsAreR while (!iterator.IsAtEnd()) { - samples.push_back({ iterator.Get(), iterator.GetIndex() }); + samples.emplace_back(iterator.Get(), iterator.GetIndex()); ++iterator; } return samples; diff --git a/Modules/Core/Common/test/itkImageRandomConstIteratorWithOnlyIndexTest.cxx b/Modules/Core/Common/test/itkImageRandomConstIteratorWithOnlyIndexTest.cxx index 679052e1e3d..9c0d16b0c65 100644 --- a/Modules/Core/Common/test/itkImageRandomConstIteratorWithOnlyIndexTest.cxx +++ b/Modules/Core/Common/test/itkImageRandomConstIteratorWithOnlyIndexTest.cxx @@ -32,8 +32,8 @@ itkImageRandomConstIteratorWithOnlyIndexTest(int, char *[]) using ImageType = itk::Image; - auto myImage = ImageType::New(); - ImageType::ConstPointer myConstImage = myImage; + auto myImage = ImageType::New(); + const ImageType::ConstPointer myConstImage = myImage; ImageType::SizeType size0; @@ -41,12 +41,11 @@ itkImageRandomConstIteratorWithOnlyIndexTest(int, char *[]) size0[1] = 100; size0[2] = 100; - unsigned long numberOfSamples = 10; + constexpr unsigned long numberOfSamples = 10; - ImageType::IndexType start0; - start0.Fill(0); + constexpr ImageType::IndexType start0{}; - ImageType::RegionType region0{ start0, size0 }; + const ImageType::RegionType region0{ start0, size0 }; myImage->SetRegions(region0); myImage->Allocate(); @@ -168,7 +167,7 @@ itkImageRandomConstIteratorWithOnlyIndexTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; RandomConstIteratorType cbot(myImage, region); @@ -177,9 +176,9 @@ itkImageRandomConstIteratorWithOnlyIndexTest(int, char *[]) while (!cbot.IsAtEnd()) { - ImageType::IndexType index = cbot.GetIndex(); + const ImageType::IndexType index = cbot.GetIndex(); it.SetIndex(index); - ImageType::PixelType pixel = it.Get(); + const ImageType::PixelType pixel = it.Get(); if (index != pixel) { diff --git a/Modules/Core/Common/test/itkImageRandomIteratorTest.cxx b/Modules/Core/Common/test/itkImageRandomIteratorTest.cxx index c00086b2d2a..38637d987fc 100644 --- a/Modules/Core/Common/test/itkImageRandomIteratorTest.cxx +++ b/Modules/Core/Common/test/itkImageRandomIteratorTest.cxx @@ -32,8 +32,8 @@ itkImageRandomIteratorTest(int, char *[]) using ImageType = itk::Image; - auto myImage = ImageType::New(); - ImageType::ConstPointer myConstImage = myImage; + auto myImage = ImageType::New(); + const ImageType::ConstPointer myConstImage = myImage; ImageType::SizeType size0; @@ -41,12 +41,11 @@ itkImageRandomIteratorTest(int, char *[]) size0[1] = 100; size0[2] = 100; - unsigned long numberOfSamples = 10; + constexpr unsigned long numberOfSamples = 10; - ImageType::IndexType start0; - start0.Fill(0); + constexpr ImageType::IndexType start0{}; - ImageType::RegionType region0{ start0, size0 }; + const ImageType::RegionType region0{ start0, size0 }; myImage->SetRegions(region0); myImage->Allocate(); @@ -218,7 +217,7 @@ itkImageRandomIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; RandomIteratorType cbot(myImage, region); @@ -227,8 +226,8 @@ itkImageRandomIteratorTest(int, char *[]) while (!cbot.IsAtEnd()) { - ImageType::IndexType index = cbot.GetIndex(); - ImageType::PixelType pixel = cbot.Get(); + const ImageType::IndexType index = cbot.GetIndex(); + const ImageType::PixelType pixel = cbot.Get(); if (index != pixel) { @@ -264,7 +263,7 @@ itkImageRandomIteratorTest(int, char *[]) size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; RandomConstIteratorType cbot(myImage, region); @@ -273,8 +272,8 @@ itkImageRandomIteratorTest(int, char *[]) while (!cbot.IsAtEnd()) { - ImageType::IndexType index = cbot.GetIndex(); - ImageType::PixelType pixel = cbot.Get(); + const ImageType::IndexType index = cbot.GetIndex(); + const ImageType::PixelType pixel = cbot.Get(); if (index != pixel) { diff --git a/Modules/Core/Common/test/itkImageRandomIteratorTest2.cxx b/Modules/Core/Common/test/itkImageRandomIteratorTest2.cxx index 8064889ed77..1a8f3ca787a 100644 --- a/Modules/Core/Common/test/itkImageRandomIteratorTest2.cxx +++ b/Modules/Core/Common/test/itkImageRandomIteratorTest2.cxx @@ -50,12 +50,11 @@ itkImageRandomIteratorTest2(int argc, char * argv[]) size[0] = 1000; size[1] = 1000; - unsigned long numberOfSamples = size[0] * size[1]; + const unsigned long numberOfSamples = size[0] * size[1]; - ImageType::IndexType start; - start.Fill(0); + constexpr ImageType::IndexType start{}; - ImageType::RegionType region{ start, size }; + const ImageType::RegionType region{ start, size }; image->SetRegions(region); image->AllocateInitialized(); diff --git a/Modules/Core/Common/test/itkImageRandomNonRepeatingIteratorWithIndexTest.cxx b/Modules/Core/Common/test/itkImageRandomNonRepeatingIteratorWithIndexTest.cxx index 8642596da47..490d7a0f4b6 100644 --- a/Modules/Core/Common/test/itkImageRandomNonRepeatingIteratorWithIndexTest.cxx +++ b/Modules/Core/Common/test/itkImageRandomNonRepeatingIteratorWithIndexTest.cxx @@ -40,16 +40,15 @@ itkImageRandomNonRepeatingIteratorWithIndexTest(int, char *[]) using RandomConstIteratorType = itk::ImageRandomNonRepeatingConstIteratorWithIndex; std::cout << "Creating images" << std::endl; - auto myImage = ImageType::New(); - ImageType::ConstPointer myConstImage = myImage; - ImageType::SizeType size0; + auto myImage = ImageType::New(); + const ImageType::ConstPointer myConstImage = myImage; + ImageType::SizeType size0; size0[0] = 50; size0[1] = 50; size0[2] = 50; - unsigned long numberOfSamples = 10; - ImageType::IndexType start0; - start0.Fill(0); - ImageType::RegionType region0{ start0, size0 }; + constexpr unsigned long numberOfSamples = 10; + constexpr ImageType::IndexType start0{}; + const ImageType::RegionType region0{ start0, size0 }; myImage->SetRegions(region0); myImage->Allocate(); // Make the priority image @@ -58,9 +57,8 @@ itkImageRandomNonRepeatingIteratorWithIndexTest(int, char *[]) prioritySize[0] = 50; prioritySize[1] = 50; prioritySize[2] = 50; - PriorityImageType::IndexType priorityStart; - priorityStart.Fill(0); - PriorityImageType::RegionType priorityRegion{ priorityStart, prioritySize }; + constexpr PriorityImageType::IndexType priorityStart{}; + const PriorityImageType::RegionType priorityRegion{ priorityStart, prioritySize }; priorityImage->SetRegions(priorityRegion); priorityImage->Allocate(); // we will make most of this image ones, with a small region of @@ -82,8 +80,8 @@ itkImageRandomNonRepeatingIteratorWithIndexTest(int, char *[]) subsize[0] = 3; subsize[1] = 4; subsize[2] = 5; - PriorityImageType::RegionType subregion{ substart, subsize }; - PriorityIteratorType subit(priorityImage, subregion); + const PriorityImageType::RegionType subregion{ substart, subsize }; + PriorityIteratorType subit(priorityImage, subregion); subit.GoToBegin(); while (!subit.IsAtEnd()) { @@ -235,14 +233,14 @@ itkImageRandomNonRepeatingIteratorWithIndexTest(int, char *[]) size[0] = 11; size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; - RandomIteratorType cbot(myImage, region); + const ImageType::RegionType region{ start, size }; + RandomIteratorType cbot(myImage, region); cbot.SetNumberOfSamples(numberOfSamples); // 0=x, 1=y, 2=z cbot.GoToBegin(); while (!cbot.IsAtEnd()) { - ImageType::IndexType index = cbot.GetIndex(); - ImageType::PixelType pixel = cbot.Get(); + const ImageType::IndexType index = cbot.GetIndex(); + const ImageType::PixelType pixel = cbot.Get(); if (index != pixel) { std::cerr << "Iterator in region test failed" << std::endl; @@ -272,14 +270,14 @@ itkImageRandomNonRepeatingIteratorWithIndexTest(int, char *[]) size[0] = 11; size[1] = 12; size[2] = 13; - ImageType::RegionType region{ start, size }; - RandomConstIteratorType cbot(myImage, region); + const ImageType::RegionType region{ start, size }; + RandomConstIteratorType cbot(myImage, region); cbot.SetNumberOfSamples(numberOfSamples); cbot.GoToBegin(); while (!cbot.IsAtEnd()) { - ImageType::IndexType index = cbot.GetIndex(); - ImageType::PixelType pixel = cbot.Get(); + const ImageType::IndexType index = cbot.GetIndex(); + const ImageType::PixelType pixel = cbot.Get(); if (index != pixel) { std::cerr << "Iterator in region test failed" << std::endl; @@ -311,7 +309,7 @@ itkImageRandomNonRepeatingIteratorWithIndexTest(int, char *[]) unsigned int count = 0; while (!cbot.IsAtEnd() && count < (subsize[0] * subsize[1] * subsize[2])) { - ImageType::IndexType index = cbot.GetIndex(); + const ImageType::IndexType index = cbot.GetIndex(); if (!subregion.IsInside(index)) { std::cerr << "Iterator in priority region test failed" << std::endl; @@ -342,7 +340,7 @@ itkImageRandomNonRepeatingIteratorWithIndexTest(int, char *[]) unsigned int count = 0; while (!cbot.IsAtEnd() && count < (subsize[0] * subsize[1] * subsize[2])) { - ImageType::IndexType index = cbot.GetIndex(); + const ImageType::IndexType index = cbot.GetIndex(); if (!subregion.IsInside(index)) { std::cerr << "Iterator in priority region test failed" << std::endl; diff --git a/Modules/Core/Common/test/itkImageRandomNonRepeatingIteratorWithIndexTest2.cxx b/Modules/Core/Common/test/itkImageRandomNonRepeatingIteratorWithIndexTest2.cxx index bcaa2ebf041..204776871a9 100644 --- a/Modules/Core/Common/test/itkImageRandomNonRepeatingIteratorWithIndexTest2.cxx +++ b/Modules/Core/Common/test/itkImageRandomNonRepeatingIteratorWithIndexTest2.cxx @@ -34,14 +34,12 @@ itkImageRandomNonRepeatingIteratorWithIndexTest2(int, char *[]) using ImageType = itk::Image; using RandomConstIteratorType = itk::ImageRandomNonRepeatingConstIteratorWithIndex; - constexpr unsigned long N = 10; - constexpr int Seed = 42; - ImageType::SizeType size; - size.Fill(N); - ImageType::IndexType start; - start.Fill(0); - ImageType::RegionType region{ start, size }; - auto myImage = ImageType::New(); + constexpr unsigned long N = 10; + constexpr int Seed = 42; + auto size = ImageType::SizeType::Filled(N); + constexpr ImageType::IndexType start{}; + const ImageType::RegionType region{ start, size }; + auto myImage = ImageType::New(); myImage->SetRegions(region); myImage->Allocate(); using WalkType = std::vector; @@ -62,8 +60,8 @@ itkImageRandomNonRepeatingIteratorWithIndexTest2(int, char *[]) { secondWalk.push_back(secondIt.GetIndex()); } - std::pair mismatchTest; - mismatchTest = std::mismatch(firstWalk.begin(), firstWalk.end(), secondWalk.begin()); + const std::pair mismatchTest = + std::mismatch(firstWalk.begin(), firstWalk.end(), secondWalk.begin()); if (mismatchTest.first != firstWalk.end()) { std::cerr << "Two iterations with the same seed do not" diff --git a/Modules/Core/Common/test/itkImageRegionConstIteratorWithOnlyIndexTest.cxx b/Modules/Core/Common/test/itkImageRegionConstIteratorWithOnlyIndexTest.cxx index aa394f9e576..a687c39693b 100644 --- a/Modules/Core/Common/test/itkImageRegionConstIteratorWithOnlyIndexTest.cxx +++ b/Modules/Core/Common/test/itkImageRegionConstIteratorWithOnlyIndexTest.cxx @@ -34,11 +34,9 @@ class itkImageRegionConstIteratorWithOnlyIndexTestIteratorTester { m_Image = ImageType::New(); - typename ImageType::SizeType size; - size.Fill(100); + auto size = ImageType::SizeType::Filled(100); - typename ImageType::IndexType start; - start.Fill(0); + typename ImageType::IndexType start{}; typename ImageType::RegionType region{ start, size }; @@ -83,9 +81,9 @@ class itkImageRegionConstIteratorWithOnlyIndexTestIteratorTester while (!it.IsAtEnd()) { - IndexType index = it.GetIndex(); + const IndexType index = it.GetIndex(); // Check to see if the index is within allowed bounds - bool isInside = region.IsInside(index); + const bool isInside = region.IsInside(index); if (!isInside) { std::cout << "Index is not inside region! - " << index << std::endl; diff --git a/Modules/Core/Common/test/itkImageRegionExclusionIteratorWithIndexTest.cxx b/Modules/Core/Common/test/itkImageRegionExclusionIteratorWithIndexTest.cxx index 07a4f9ed702..62aaef6dce0 100644 --- a/Modules/Core/Common/test/itkImageRegionExclusionIteratorWithIndexTest.cxx +++ b/Modules/Core/Common/test/itkImageRegionExclusionIteratorWithIndexTest.cxx @@ -71,7 +71,7 @@ RunTest(const TRegion & region, const TRegion & exclusionRegion) { // Exclusion region is completely outside the region. Set it to // have size 0. - typename TRegion::IndexType exclusionStart = region.GetIndex(); + const typename TRegion::IndexType exclusionStart = region.GetIndex(); croppedExclusionRegion.SetIndex(exclusionStart); typename TRegion::SizeType exclusionSize = croppedExclusionRegion.GetSize(); @@ -257,19 +257,13 @@ itkImageRegionExclusionIteratorWithIndexTest(int, char *[]) using IndexType = itk::Index; using RegionType = itk::ImageRegion; - SizeType regionSize; - IndexType regionStart; - RegionType region; + constexpr IndexType regionStart{}; + auto regionSize = itk::MakeFilled(7); + const RegionType region{ regionStart, regionSize }; - regionStart.Fill(0); - regionSize.Fill(7); + constexpr SizeType::SizeValueType size[2] = { 4, 7 }; - region.SetIndex(regionStart); - region.SetSize(regionSize); - - SizeType::SizeValueType size[2] = { 4, 7 }; - - for (SizeType::SizeValueType s : size) + for (const SizeType::SizeValueType s : size) { for (IndexType::IndexValueType k = -2; k < 6; ++k) { @@ -282,10 +276,9 @@ itkImageRegionExclusionIteratorWithIndexTest(int, char *[]) exclusionStart[1] = j; exclusionStart[2] = k; - SizeType exclusionSize; - exclusionSize.Fill(s); + auto exclusionSize = SizeType::Filled(s); - RegionType exclusionRegion(exclusionStart, exclusionSize); + const RegionType exclusionRegion(exclusionStart, exclusionSize); if (!RunTest(region, exclusionRegion)) { @@ -298,11 +291,9 @@ itkImageRegionExclusionIteratorWithIndexTest(int, char *[]) } // Test exclusion region completely outside the region. - IndexType exclusionStart; - exclusionStart.Fill(-3); - SizeType exclusionSize; - exclusionSize.Fill(2); - RegionType exclusionRegion(exclusionStart, exclusionSize); + auto exclusionStart = IndexType::Filled(-3); + auto exclusionSize = SizeType::Filled(2); + const RegionType exclusionRegion(exclusionStart, exclusionSize); if (!RunTest(region, exclusionRegion)) { diff --git a/Modules/Core/Common/test/itkImageRegionGTest.cxx b/Modules/Core/Common/test/itkImageRegionGTest.cxx index 66e727e5f4a..df937066ba9 100644 --- a/Modules/Core/Common/test/itkImageRegionGTest.cxx +++ b/Modules/Core/Common/test/itkImageRegionGTest.cxx @@ -26,17 +26,27 @@ namespace { +// Tells whether GetImageDimension() returns ImageDimension, for all of the specified values of VImageDimension. +template +constexpr bool GetImageDimension_returns_ImageDimension{ ( + (itk::ImageRegion::GetImageDimension() == VImageDimension) && ...) }; + +static_assert(GetImageDimension_returns_ImageDimension<2, 3, 4>, "GetImageDimension() should return ImageDimension."); + + template constexpr bool CheckTrivialCopyabilityOfImageRegion() { constexpr bool isImageRegionTriviallyCopyable{ std::is_trivially_copyable_v> }; -#ifdef ITK_FUTURE_LEGACY_REMOVE - static_assert(isImageRegionTriviallyCopyable, "In the future, ImageRegion should be trivially copyable."); +#ifdef ITK_LEGACY_REMOVE + static_assert(isImageRegionTriviallyCopyable, + "When legacy support is removed, ImageRegion should be trivially copyable."); return isImageRegionTriviallyCopyable; #else - static_assert(!isImageRegionTriviallyCopyable, "ImageRegion should *not* be trivially copyable."); + static_assert(!isImageRegionTriviallyCopyable, + "When legacy support is enabled, ImageRegion should *not* be trivially copyable."); return !isImageRegionTriviallyCopyable; #endif } @@ -222,19 +232,23 @@ TEST(ImageRegion, SupportsStructuredBinding) using IndexType = RegionType::IndexType; using SizeType = RegionType::SizeType; - RegionType region{}; - auto && [index, size] = region; - - static_assert(std::is_same_v); - static_assert(std::is_same_v); - EXPECT_EQ(&index, &(region.GetIndex())); - EXPECT_EQ(&size, &(region.GetSize())); - - const RegionType constRegion{}; - auto && [constIndex, constSize] = constRegion; + { + // Testing non-cost behavior + RegionType nonConstRegion{}; // NOLINT(misc-const-correctness) + auto && [index, size] = nonConstRegion; + + static_assert(std::is_same_v); + static_assert(std::is_same_v); + EXPECT_EQ(&index, &(nonConstRegion.GetIndex())); + EXPECT_EQ(&size, &(nonConstRegion.GetSize())); + } + { + const RegionType constRegion{}; + auto && [constIndex, constSize] = constRegion; - static_assert(std::is_same_v); - static_assert(std::is_same_v); - EXPECT_EQ(&constIndex, &(constRegion.GetIndex())); - EXPECT_EQ(&constSize, &(constRegion.GetSize())); + static_assert(std::is_same_v); + static_assert(std::is_same_v); + EXPECT_EQ(&constIndex, &(constRegion.GetIndex())); + EXPECT_EQ(&constSize, &(constRegion.GetSize())); + } } diff --git a/Modules/Core/Common/test/itkImageRegionIteratorGTest.cxx b/Modules/Core/Common/test/itkImageRegionIteratorGTest.cxx new file mode 100644 index 00000000000..e11e47e622f --- /dev/null +++ b/Modules/Core/Common/test/itkImageRegionIteratorGTest.cxx @@ -0,0 +1,136 @@ +/*========================================================================= + * + * Copyright NumFOCUS + * + * 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 + * + * https://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. + * + *=========================================================================*/ + +// First include the header files to be tested: +#include "itkImageConstIterator.h" +#include "itkImageConstIteratorWithIndex.h" +#include "itkImageConstIteratorWithOnlyIndex.h" +#include "itkImageIterator.h" +#include "itkImageIteratorWithIndex.h" +#include "itkImageLinearConstIteratorWithIndex.h" +#include "itkImageLinearIteratorWithIndex.h" +#include "itkImageRegionConstIterator.h" +#include "itkImageRegionConstIteratorWithIndex.h" +#include "itkImageRegionConstIteratorWithOnlyIndex.h" +#include "itkImageRegionExclusionConstIteratorWithIndex.h" +#include "itkImageRegionExclusionIteratorWithIndex.h" +#include "itkImageRegionIterator.h" +#include "itkImageRegionIteratorWithIndex.h" +#include "itkImageRegionReverseConstIterator.h" +#include "itkImageRegionReverseIterator.h" +#include "itkImageReverseConstIterator.h" +#include "itkImageReverseIterator.h" +#include "itkImageScanlineConstIterator.h" +#include "itkImageScanlineIterator.h" +#include "itkImageSliceConstIteratorWithIndex.h" +#include "itkImageSliceIteratorWithIndex.h" + +#include "itkImage.h" +#include +#include // For false_type and true_type. + +namespace +{ +// Has_IsAtBegin tells whether the specified iterator type has an `IsAtBegin()` member function, returning a `bool`. It +// is inspired by "How to detect whether there is a specific member variable in class?", answered by Andy Prowl, Jan 25, +// 2013 at https://stackoverflow.com/a/14523787 (the `has_id` example). +template +struct Has_IsAtBegin : std::false_type +{}; + +template +struct Has_IsAtBegin().IsAtBegin())> : std::true_type +{}; + + +template +void +CheckConstructedAtBegin() +{ + using ImageType = typename TIterator::ImageType; + using IndexType = typename TIterator::IndexType; + using SizeType = typename TIterator::SizeType; + using RegionType = typename TIterator::RegionType; + + const auto image = ImageType::New(); + + // Use a small image size, so that the unit test won't take a long time. + static constexpr itk::SizeValueType imageSizeValue{ 4 }; + + image->SetRegions(SizeType::Filled(imageSizeValue)); + image->Allocate(); + + // Check various regions, specified by the following `indexValue` and `sizeValue` combinations: + for (const itk::IndexValueType indexValue : { 0, 1 }) + { + for (const auto sizeValue : { itk::SizeValueType{ 1 }, imageSizeValue - 1 }) + { + const RegionType imageRegion(IndexType::Filled(indexValue), SizeType::Filled(sizeValue)); + + const TIterator iterator(image, imageRegion); + TIterator iteratorThatGoesToBegin = iterator; + iteratorThatGoesToBegin.GoToBegin(); + EXPECT_EQ(iterator, iteratorThatGoesToBegin); + + if constexpr (Has_IsAtBegin::value) + { + // Extra check, using IsAtBegin(), if the iterator has that member function. (Some iterators + // do not have an IsAtBegin() member function, for example, ImageRegionConstIteratorWithIndex.) + EXPECT_TRUE(TIterator(image, imageRegion).IsAtBegin()); + } + } + } +} + + +template