├── .gitattributes
├── .github
└── workflows
│ ├── build_wheels.yml
│ ├── publish_on_pypi.yml
│ └── run_tests.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── commit
├── __init__.py
├── core.pyx
├── models.py
├── operator
│ ├── __init__.py
│ └── operator.pyx
├── proximals.pyx
├── solvers.py
└── trk2dictionary
│ ├── ProgressBar.h
│ ├── Vector.h
│ ├── trk2dictionary.pyx
│ └── trk2dictionary_c.cpp
├── extras
├── .gitignore
├── CMake
│ ├── FindBLITZ.cmake
│ └── FindNIFTI.cmake
├── CMakeLists.txt
├── COMMIT_debugger
│ ├── CMakeLists.txt
│ ├── OPENGL_callbacks.cxx
│ ├── OPENGL_utils.h
│ └── main.cxx
└── include
│ ├── COLOR_ui.h
│ ├── NIFTI.h
│ ├── TrackVis.h
│ ├── VECTOR.h
│ ├── colormaps.h
│ └── tclap
│ ├── Arg.h
│ ├── ArgException.h
│ ├── ArgTraits.h
│ ├── CmdLine.h
│ ├── CmdLineInterface.h
│ ├── CmdLineOutput.h
│ ├── Constraint.h
│ ├── DocBookOutput.h
│ ├── HelpVisitor.h
│ ├── IgnoreRestVisitor.h
│ ├── Makefile.am
│ ├── Makefile.in
│ ├── MultiArg.h
│ ├── MultiSwitchArg.h
│ ├── OptionalUnlabeledTracker.h
│ ├── StandardTraits.h
│ ├── StdOutput.h
│ ├── SwitchArg.h
│ ├── UnlabeledMultiArg.h
│ ├── UnlabeledValueArg.h
│ ├── ValueArg.h
│ ├── ValuesConstraint.h
│ ├── VersionVisitor.h
│ ├── Visitor.h
│ ├── XorHandler.h
│ └── ZshCompletionOutput.h
├── pyproject.toml
├── requirements.txt
├── setup.py
├── setup_operator.py
└── tests
├── .keep
├── demo_data
└── ref_results
│ ├── ref_results_BallandStick.pickle
│ └── ref_results_StickZeppelinBall.pickle
└── test_demo.py
/.gitattributes:
--------------------------------------------------------------------------------
1 | extras/* linguist-vendored
2 |
--------------------------------------------------------------------------------
/.github/workflows/build_wheels.yml:
--------------------------------------------------------------------------------
1 | name: Build wheels
2 | run-name: Build wheels - ${{ github.sha }}
3 | on:
4 | push:
5 | branches:
6 | - 'master'
7 | - 'release/**'
8 | jobs:
9 | build_windows_wheels:
10 | strategy:
11 | matrix:
12 | py: [cp38, cp39, cp310, cp311, cp312]
13 | arch:
14 | - [AMD64, win_amd64, x64, x64, 64bit]
15 | - [x86, win32, x86, Win32, 32bit]
16 | name: ${{ matrix.py }}-${{ matrix.arch[1] }}
17 | runs-on: windows-latest
18 | steps:
19 | - name: Checkout
20 | uses: actions/checkout@v4
21 |
22 | - name: Compile pthread-win32
23 | run: |
24 | Import-Module 'C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\Tools\Microsoft.VisualStudio.DevShell.dll'
25 | Enter-VsDevShell -VsInstallPath 'C:\Program Files\Microsoft Visual Studio\2022\Enterprise' -DevCmdArguments '-arch=x64' -StartInPath 'C:\'
26 | git clone https://github.com/GerHobbelt/pthread-win32.git
27 | cd C:\pthread-win32\windows\VS2022
28 | msbuild .\pthread.2022.sln -t:pthread_static_lib -p:Configuration=Release,Platform=${{ matrix.arch[3] }}
29 | cd C:\
30 | mkdir C:\pthread-win32_static_lib
31 | mkdir C:\pthread-win32_static_lib\include
32 | mkdir C:\pthread-win32_static_lib\lib
33 | cp C:\pthread-win32\windows\VS2022\bin\Release-Unicode-${{ matrix.arch[4] }}-${{ matrix.arch[2] }}\pthread_static_lib.lib C:\pthread-win32_static_lib\lib\pthread.lib
34 | cp C:\pthread-win32\_ptw32.h C:\pthread-win32_static_lib\include
35 | cp C:\pthread-win32\pthread.h C:\pthread-win32_static_lib\include
36 | cp C:\pthread-win32\sched.h C:\pthread-win32_static_lib\include
37 | cp C:\pthread-win32\semaphore.h C:\pthread-win32_static_lib\include
38 |
39 | - name: Build wheel ${{ matrix.py }}-${{ matrix.arch[1] }}
40 | uses: pypa/cibuildwheel@v2.19.1
41 | env:
42 | PTHREAD_WIN_INCLUDE: C:\pthread-win32_static_lib\include
43 | PTHREAD_WIN_LIB: C:\pthread-win32_static_lib\lib
44 | CIBW_PLATFORM: windows
45 | CIBW_BUILD: ${{ matrix.py }}-${{ matrix.arch[1] }}
46 | CIBW_ARCHS_WINDOWS: ${{ matrix.arch[0] }}
47 |
48 | - name: Upload artifacts
49 | uses: actions/upload-artifact@v4
50 | with:
51 | name: wheels_${{ matrix.py }}_${{ matrix.arch[1] }}
52 | path: ./wheelhouse/*.whl
53 | if-no-files-found: error
54 |
55 | build_macos_wheels:
56 | strategy:
57 | matrix:
58 | config:
59 | [
60 | {
61 | py: cp38,
62 | arch: [x86_64, macosx_x86_64, 12.0, macos-12]
63 | },
64 | {
65 | py: cp39,
66 | arch: [x86_64, macosx_x86_64, 12.0, macos-12]
67 | },
68 | {
69 | py: cp310,
70 | arch: [x86_64, macosx_x86_64, 12.0, macos-12]
71 | },
72 | {
73 | py: cp311,
74 | arch: [x86_64, macosx_x86_64, 12.0, macos-12]
75 | },
76 | {
77 | py: cp312,
78 | arch: [x86_64, macosx_x86_64, 12.0, macos-12]
79 | },
80 | {
81 | py: cp38,
82 | arch: [arm64, macosx_arm64, 12.0, macos-14]
83 | },
84 | {
85 | py: cp39,
86 | arch: [arm64, macosx_arm64, 12.0, macos-14]
87 | },
88 | {
89 | py: cp310,
90 | arch: [arm64, macosx_arm64, 12.0, macos-14]
91 | },
92 | {
93 | py: cp311,
94 | arch: [arm64, macosx_arm64, 12.0, macos-14]
95 | },
96 | {
97 | py: cp312,
98 | arch: [arm64, macosx_arm64, 12.0, macos-14]
99 | }
100 | ]
101 | name: ${{ matrix.config.py }}-${{ matrix.config.arch[1] }}
102 | runs-on: ${{ matrix.config.arch[3] }}
103 | if:
104 | steps:
105 | - name: Checkout
106 | uses: actions/checkout@v4
107 |
108 | - name: Install pipx # NOTE: required only for arm64
109 | if: startsWith(matrix.config.arch[0], 'arm64')
110 | run: |
111 | brew install pipx
112 |
113 | - name: Build wheel ${{ matrix.config.py }}-${{ matrix.config.arch[1] }}
114 | uses: pypa/cibuildwheel@v2.19.1
115 | env:
116 | MACOSX_DEPLOYMENT_TARGET: ${{ matrix.config.arch[2] }}
117 | CIBW_PLATFORM: macos
118 | CIBW_BUILD: ${{ matrix.config.py }}-${{ matrix.config.arch[1] }}
119 | CIBW_ARCHS_MACOS: ${{ matrix.config.arch[0] }}
120 |
121 | - name: Upload artifacts
122 | uses: actions/upload-artifact@v4
123 | with:
124 | name: wheels_${{ matrix.config.py }}_${{ matrix.config.arch[1] }}
125 | path: ./wheelhouse/*.whl
126 | if-no-files-found: error
127 |
128 | build_linux_wheels:
129 | strategy:
130 | matrix:
131 | py: [cp38, cp39, cp310, cp311, cp312]
132 | arch:
133 | - [x86_64, manylinux_x86_64, amd64]
134 | - [aarch64, manylinux_aarch64, arm64]
135 | name: ${{ matrix.py }}-${{ matrix.arch[1] }}
136 | runs-on: ubuntu-latest
137 | steps:
138 | - name: Checkout
139 | uses: actions/checkout@v4
140 |
141 | - name: Set up QEMU
142 | uses: docker/setup-qemu-action@v3.0.0
143 | with:
144 | platforms: ${{ matrix.arch[2] }}
145 |
146 | - name: Build wheel ${{ matrix.py }}-${{ matrix.arch[1] }}
147 | uses: pypa/cibuildwheel@v2.19.1
148 | env:
149 | CIBW_PLATFORM: linux
150 | CIBW_BUILD: ${{ matrix.py }}-${{ matrix.arch[1] }}
151 | CIBW_ARCHS_LINUX: ${{ matrix.arch[0] }}
152 |
153 | - name: Upload artifacts
154 | uses: actions/upload-artifact@v4
155 | with:
156 | name: wheels_${{ matrix.py }}_${{ matrix.arch[1] }}
157 | path: ./wheelhouse/*.whl
158 | if-no-files-found: error
159 |
160 | build_source_distribution:
161 | name: sdist
162 | runs-on: ubuntu-latest
163 | steps:
164 | - name: Checkout
165 | uses: actions/checkout@v4
166 |
167 | - name: Build source distribution
168 | run: |
169 | pip install -U pip
170 | pip install -U build
171 | python -m build --sdist
172 |
173 | - name: Upload artifacts
174 | uses: actions/upload-artifact@v4
175 | with:
176 | name: sdist
177 | path: ./dist/*.tar.gz
178 | if-no-files-found: error
179 |
180 | run_id:
181 | name: Create/Update WHEELS_ARTIFACTS_RUN_ID secret
182 | runs-on: ubuntu-latest
183 | needs: [build_windows_wheels, build_macos_wheels, build_linux_wheels, build_source_distribution]
184 | steps:
185 | - uses: actions/checkout@v4
186 | - run: |
187 | gh secret set WHEELS_ARTIFACTS_RUN_ID --body ${{ github.run_id }}
188 | env:
189 | GH_TOKEN: ${{ secrets.GH_PAT }}
190 |
--------------------------------------------------------------------------------
/.github/workflows/publish_on_pypi.yml:
--------------------------------------------------------------------------------
1 | name: Publish on PyPI
2 | run-name: Publish on PyPI - ${{ github.sha }}
3 | on:
4 | release:
5 | types: [published]
6 | jobs:
7 | publish_on_pypi:
8 | name: Publish on PyPI
9 | if: github.event.release.prerelease == false
10 | runs-on: ubuntu-latest
11 | environment:
12 | name: pypi
13 | url: https://pypi.org/project/dmri-commit
14 | permissions:
15 | id-token: write # IMPORTANT: this permission is mandatory for trusted publishing
16 | steps:
17 | - name: Download artifacts
18 | uses: actions/download-artifact@v4
19 | with:
20 | github-token: ${{ secrets.GH_PAT }}
21 | run-id: ${{ secrets.WHEELS_ARTIFACTS_RUN_ID }}
22 | path: dist
23 | merge-multiple: true
24 |
25 | - name: Publish on PyPI
26 | uses: pypa/gh-action-pypi-publish@release/v1
27 | with:
28 | skip-existing: true
29 | verbose: true
30 | print-hash: true
31 |
32 | publish_on_pypi_test:
33 | name: Publish on PyPI Test
34 | if: github.event.release.prerelease == true && contains(github.event.release.tag_name, 'rc')
35 | runs-on: ubuntu-latest
36 | environment:
37 | name: testpypi
38 | url: https://test.pypi.org/project/dmri-commit
39 | permissions:
40 | id-token: write # IMPORTANT: this permission is mandatory for trusted publishing
41 | steps:
42 | - name: Download artifacts
43 | uses: actions/download-artifact@v4
44 | with:
45 | github-token: ${{ secrets.GH_PAT }}
46 | run-id: ${{ secrets.WHEELS_ARTIFACTS_RUN_ID }}
47 | path: dist
48 | merge-multiple: true
49 |
50 | - name: Publish on PyPI Test
51 | uses: pypa/gh-action-pypi-publish@release/v1
52 | with:
53 | repository-url: https://test.pypi.org/legacy/
54 | skip-existing: true
55 | verbose: true
56 | print-hash: true
57 |
--------------------------------------------------------------------------------
/.github/workflows/run_tests.yml:
--------------------------------------------------------------------------------
1 | name: Run tests
2 | run-name: Run tests - ${{ github.sha }}
3 | on: push
4 | env:
5 | OPENBLAS_NUM_THREADS: 1
6 | jobs:
7 | run_test:
8 | strategy:
9 | matrix:
10 | # NOTE: Python 3.12 is not supported yet
11 | config:
12 | [
13 | {os: ubuntu-20.04, py: '3.8'},
14 | {os: ubuntu-20.04, py: '3.9'},
15 | {os: ubuntu-20.04, py: '3.10'},
16 | {os: ubuntu-20.04, py: '3.11'},
17 | {os: ubuntu-latest, py: '3.8'},
18 | {os: ubuntu-latest, py: '3.9'},
19 | {os: ubuntu-latest, py: '3.10'},
20 | {os: ubuntu-latest, py: '3.11'}
21 | # {os: ubuntu-20.04, py: '3.12'},
22 | # {os: macos-latest, py: '3.8'},
23 | # {os: macos-latest, py: '3.9'},
24 | # {os: macos-latest, py: '3.10'},
25 | # {os: macos-latest, py: '3.11'},
26 | # {os: macos-latest, py: '3.12'},
27 | # {os: macos-14, py: '3.10'},
28 | # {os: macos-14, py: '3.11'},
29 | # {os: macos-14, py: '3.12'}
30 | ]
31 | name: Python ${{ matrix.config.py }} on ${{ matrix.config.os }}
32 | runs-on: ${{ matrix.config.os }}
33 | steps:
34 | - name: Checkout
35 | uses: actions/checkout@v4.1.1
36 | - name: Download data
37 | working-directory: tests
38 | run: |
39 | curl -L -O https://github.com/daducci/COMMIT/wiki/files/demo01_data.zip
40 | curl -L -O https://github.com/daducci/COMMIT/wiki/files/demo01_fibers.tck
41 | 7z x demo01_data.zip
42 | mv demo01_fibers.tck demo_data
43 | mv demo01_data/* demo_data
44 | - name: Set up Python ${{ matrix.config.py }}
45 | uses: actions/setup-python@v5.0.0
46 | with:
47 | python-version: ${{ matrix.config.py }}
48 | - name: Install dmri-commit
49 | run: pip install . --no-cache-dir
50 | - name: Run test
51 | id: run_test
52 | working-directory: tests
53 | run: |
54 | echo "Run tests"
55 | python test_demo.py
56 | continue-on-error: true
57 | - name: Check on failures
58 | if: steps.run_test.outcome != 'success'
59 | run: |
60 | echo "Test failed"
61 | exit 1
62 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | build
2 | .ipynb_checkpoints
3 | .DS_Store
4 | .DS_Store?
5 | ._*
6 | .Spotlight-V100
7 | .Trashes
8 | ehthumbs.db
9 | Thumbs.db
10 | __pycache__/
11 | .vscode/
12 | .eggs/
13 | *.egg-info/
14 | *.so
15 | *.cpp
16 | dist/
17 |
18 | trk2dictionary.c
19 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 | ### All notable changes to `COMMIT` will be documented in this file.
3 |
4 | ## `v2.3.1`
_2024-09-24_
5 | ### 🐛Fixed
6 | - Revert changes when save results in `results.pickle`
7 | - Add checks on `group_weights_extra`
8 |
9 | ---
10 | ---
11 |
12 | ## `v2.3.0`
_2024-07-04_
13 | ### ✨Added
14 | - Added support for Windows (requires the `pthread-win32` library)
15 | - Precompiled wheels for Windows, MacOS, and Linux are now available on PyPI
16 |
17 | ### 🛠️Changed
18 | - `operator.pyx` no more compiled at runtime
19 | - Restict the `numpy` version to `<2.0.0`
20 |
21 | ### 🐛Fixed
22 | - Improved output when running from Jupyter notebooks
23 |
24 | ---
25 | ---
26 |
27 | ## `v2.2.0`
_2024-04-12_
28 | ### 🐛Fixed
29 | - Fix `set_thread` isotropic compartment voxel distribution
30 |
31 | ### ✨Added
32 | - Add `do_reweighting` parameter to `save_results()`
33 | - Add logging module to handle console output
34 |
35 | ---
36 | ---
37 |
38 | ## `v2.1.0`
_2024-01-22_
39 | ### ✨Added
40 | - Work In Progress (WIP) models
41 | - Different regularizers
42 |
43 | ### 🐛Fixed
44 | - Merged PR [#127](https://github.com/daducci/COMMIT/pull/127): [FIX] Operator is not recompiled when some parameters are changed
45 | - Merged PR [#129](https://github.com/daducci/COMMIT/pull/129): [FIX] Fista update
46 |
47 | ---
48 | ---
49 |
50 | ## `v2.0.1`
_2023-10-31_
51 | ### 🛠️Changed
52 | - Bump dependencies
53 |
54 | ### 🐛Fixed
55 | - Add `dtype=np.object_` to inhomogemeous shape arrays
56 | - Fix `egg_base` option in `setup.cfg` (create the `build` folder before running `setup()`)
57 | - Fix `trk2didtionary` crash when run from Jupyter notebooks (removed C-level stdout from Jupyter notebook)
58 |
59 | ---
60 | ---
61 |
62 | ## `v2.0.0`
_2023-09-14_
63 | ### 🛠️Changed
64 | - Default `ndirs=500` in `core.generate_kernels()` and in `trk2dictionary.run()`
65 | - Expire the deprecated `ndirs` parameter in `amico.core.setup()`
66 | - Expire the deprecated `filename_trk` and `gen_trk` parameters in `trk2dictionary.run()`
67 | - Removed unused parameter `ndirs` from `trk2dictionary_c.cpp()`
68 | - Build output goes into `build`
69 | - Switched to proprietary license (see `LICENSE` file)
70 |
71 | ### ✨Added
72 | - Added clustering in trk2dictionary.run()
73 | * geometry-based clustering using `blur_clust_thr` parameter
74 | * anatomical information streamlines clustering based on their endpoints using `blur_clust_groupby` parameter
75 |
76 | - Added trk2dictionary.run() parallel computation using `n_threads` parameter
77 | - Changed internal streamlines representation using `blur_core_extent` and `blur_gauss_extent` parameters
78 | - Added possibility to keep temporal files created by parallel trk2dictionary.run() and clustering using `keep_temp` parameter
79 | - Parallel compilation
80 |
81 | ### 🐛Fixed
82 | - Bugfixes
83 |
84 | ---
85 | ---
86 |
87 | ## [1.6.5] - 2023-08-03
88 |
89 | ### Changed
90 | - Build output goes into 'build'
91 | - Require `dmri-amico>=1.3.2,<2.0.0`
92 |
93 | ### Fixed
94 | - Solve [#121](https://github.com/daducci/COMMIT/issues/121)
95 |
96 | ## [1.6.4] - 2023-02-14
97 |
98 | ### Fixed
99 | - Invalid command 'bdist_wheel' error when install with pip<=20.0.2
100 |
101 | ## [1.6.3] - 2022-10-21
102 |
103 | ### Changed
104 | - Ensure non-negative values in the 'y' vector before fit
105 |
106 | ### Added
107 | - 'replace_bad_voxels' parameter in 'load_data()' to replace NaN and Inf values in the signal
108 |
109 | ## [1.6.2] - 2022-05-05
110 |
111 | ### Fixed
112 | - Problem with very anisotropic voxelsizes
113 |
114 | ## [1.6.1] - 2022-01-31
115 |
116 | ### Changed
117 | - generate_kernels: forcing 'ndirs' to 1 in case of 'VolumeFraction' model
118 | - core.setup: removed 'ndirs' parameter, now precomputes all directions
119 |
120 | ### Added
121 | - Shortcut 'commit.core.setup' to 'commit.setup'
122 |
123 | ## [1.6.0] - 2021-12-03
124 |
125 | ### Changed
126 | - Improved the blur functionality
127 |
128 | ## [1.5.3] - 2021-12-03
129 |
130 | ### Added
131 | - Option 'coeffs_format' to 'save_results()'
132 |
133 | ### Changed
134 | - Install information are stored (and taken from) commit/info.py
135 |
136 | ## [1.5.2] - 2021-10-27
137 |
138 | ### Fixed
139 | - Missing dependencies
140 |
141 | ## [1.5.1] - 2021-10-11
142 |
143 | ### Added
144 | - Option 'get_normalized' to 'save_coeffs()'
145 |
146 |
147 | ## [1.5.0] - 2021-06-19
148 |
149 | ### Added
150 | - Possibility to specify a voxel confidence map
151 |
152 | ### Fixed
153 | - Set license: BSD-3-Clause License
154 | - Indices of groups in case of streamlines that were pre-filtered during trk2dictionary
155 |
156 | ### Changed
157 | - Loading of nii data using (np.asanyarray( nii.dataobj )) in core and trk2dictionary
158 | - confidence_map from float64 to float32
159 |
160 | ## [1.4.6] - 2021-03-25
161 |
162 | ### Fixed
163 | - Length of short segments to neglect
164 | - Streamline weights, in case of blur, are properly scaled
165 |
166 | ## [1.4.5] - 2021-02-08
167 |
168 | ### Fixed
169 | - operator.pyxbld: Changed the condition to create a new operator
170 | - trk2dictionary.pyx: Check that the tractogram exists before trying to
171 | load it and remove the try section
172 | - trk2dictionary.run(): fixed bug with blur parameters and computing the blur
173 |
174 | ### Added
175 | - core.pyx: Add to the function build_operator the parameter build_dir
176 |
177 | ### Changed
178 | - core.pyx: The function build_operator checks if the LUT configuration
179 | changed before build a new operator
180 | - verbose variables in core.pyx and solvers.py changed to be boolean
181 | - trk2dictionary.run(): removed 'points_to_skip' option
182 |
183 | ## [1.4.4] - 2020-10-28
184 |
185 | ### Changed
186 | - Option to set one single direction in the resolution of the LUT
187 |
188 | ## [1.4.3] - 2020-10-22
189 |
190 | ### Added
191 | - store model parameters to results.pickle
192 |
193 | ## [1.4.2] - 2020-10-22
194 |
195 | ### Fixed
196 | - trk2dictionary.run(): check for invalid parameters passed to the blur
197 |
198 | ## [1.4.1] - 2020-10-21
199 |
200 | ### Fixed
201 | - operator.pyxbld: Changed the condition to create a new operator
202 |
203 | ### Added
204 | - COMMIT version is stored in results.pickle
205 | - COMMIT version is stored in output NIFTI files
206 |
207 | ## [1.4.0.4] - 2020-09-24
208 |
209 | ### Fixed
210 | - trk2dictionary.run(): bug in the blurring functionality
211 | - trk2dictionary.run(): 'blur_sigma' defaults to 0
212 |
213 | ## [1.4.0.3] - 2020-08-07
214 |
215 | ### Fixed
216 | - COMMIT_debugger: compilation problem
217 | - COMMIT_debugger: wrong visualization in Linux
218 |
219 | ## [1.4.0.2] - 2020-08-07
220 |
221 | ### Changed
222 | - Moved the documentation to the Wiki
223 |
224 | ## [1.4.0.1] - 2020-08-03
225 |
226 | ### Changed
227 | - Updated the installation guide
228 |
229 | ## [1.4.0.0] - 2020-07-30
230 |
231 | ### Changed
232 | - trk2dictionary.run(): removed 'gen_trk' option
233 | - save_results(): removed 'save_coeff' and 'save_opt_details' parameters
234 | - save_results(): now saving only streamline_weights.txt (not anymore xic.txt, xec.txt, xiso.txt)
235 | - load_dictionary(): renamed 'use_mask' to 'use_all_voxels_in_mask'
236 | - Removed unused 'dictionary_ndirs.dict' file
237 | - trk2dictionary.run(): 'min_fiber_len' defaults to 0.0 for backward compatibility
238 |
239 | ### Added
240 | - added 'get_coeffs()' function to get all estimated coefficients
241 | - save_results(): added 'stat_coeffs' parameter for saving streamline weights
242 | - trk2dictionary.run(): added 'max_fiber_len' parameter to discard long streamlines
243 | - load_data(): added 'b0_min_signal' to discard voxels with very low signal
244 |
245 | ## [1.3.9] - 2020-06-09
246 |
247 | ### Changed
248 | - Modify setup.py and fix spams dependencies
249 |
250 | ## [1.3.8] - 2020-05-12
251 |
252 | ### Changed
253 | - Improvements to the COMMIT_debugger.
254 |
255 | ## [1.3.7] - 2020-04-25
256 |
257 | ### Changed
258 | - Adapt demos to use d_perps instead of ICVFs for setting model parameters.
259 |
260 | ## [1.3.6] - 2020-04-22
261 |
262 | ### Fixed
263 | - Bug when the selected model has EC compartments but no peaks are provided (in trk2dictionary).
264 |
265 | ## [1.3.5] - 2020-04-08
266 |
267 | ### Added
268 | - Parameter 'min_fiber_len' in trk2dictionary to discard streamlines shorter than a given length in mm.
269 |
270 | ### Fixed
271 | - Bug when 'points_to_skip' was higher then streamline length.
272 | - Few corrections to docstring of trk2dictionary.
273 |
274 | ## [1.3.4] - 2020-04-02
275 |
276 | ### Changed
277 | - Added colorized output. NB: needs AMICO 1.2.0 or above.
278 |
279 | ## [1.3.3] - 2020-03-31
280 |
281 | ### Added
282 | - Added possibility to save the predicted DW-MR signal in save_results.
283 |
284 | ### Fixed
285 | - Minor cleanup.
286 |
287 |
288 | ## [1.3.2] - 2020-03-27
289 |
290 | ### Added
291 | - Check if dictionary (upon loading) and data have the same geometry.
292 |
293 | ### Fixed
294 | - Bug while saving coefficients in save_results.
295 |
296 |
297 | ## [1.3.1] - 2020-03-27
298 |
299 | ### Fixed
300 | - Improved the loading of the streamlines in trk2dictionary
301 |
302 |
303 | ## [1.3] - 2019-10-30
304 |
305 | This version of COMMIT *is not compatible* with [AMICO](https://github.com/daducci/AMICO) v1.0.1 of below. If you update COMMIT to this version, please update AMICO to version 1.1.0 or above.
306 |
307 | ### Added
308 | - Changelog file to keep tracking of the COMMIT versions.
309 |
310 | ### Changed
311 | - Added compatibility with low resolution LUTs.
312 |
313 | ### Fixed
314 | - Nothing.
315 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | ################################################################################
2 | COMMIT software license agreement
3 | Version 2, 24 July 2023
4 | ################################################################################
5 |
6 | ------------------------------------PREAMBLE------------------------------------
7 | This license agreement (“Agreement”) is a legal agreement between you and the
8 | Diffusion Imaging and Connectivity Estimation laboratory (“DICE lab”) for the
9 | use of the COMMIT software (“Software”). By downloading and/or using the
10 | Software, you hereby accept and agree to all the terms and conditions of this
11 | Agreement. As used in this Agreement, “you” refers to any individual or
12 | organization that uses the Software.
13 |
14 |
15 | ------------------------------TERMS AND CONDITIONS------------------------------
16 | [1] License Grant
17 | Subject to all the terms and conditions of this Agreement, the DICE lab hereby
18 | grants you a worldwide, non-exclusive, non-transferable, limited license to
19 | copy, use, modify, and redistribute the Software solely for research and
20 | educational purposes, free of charge.
21 |
22 | [2] Commercial use
23 | You may not use the Software and/or any work based on or using the Software for
24 | any commercial purpose, including but not limited to selling, licensing,
25 | distributing, renting, or leasing the Software for profit. If you want to use
26 | the Software for commercial purposes, you may contact the DICE lab to obtain a
27 | commercial license agreement. The DICE lab may consider offering a commercial
28 | license, subject to negotiation of appropriate terms and conditions, including
29 | but not limited to the payment of a license fee and compliance with any
30 | additional restriction on the use of the Software.
31 |
32 | [3] Attributions and Acknowledgments
33 | You agree to provide an acknowledgement identifying the Software and referencing
34 | its use in any publication, presentation, research result, and product related
35 | to or arising from the use of the Software. You also agree to give proper
36 | attribution to the original Software and reproduce this Agreement in any
37 | modified and/or redistributed work based on the Software.
38 |
39 | [4] Patents
40 | If you plan to file a patent application based on or using the Software, you
41 | must contact the DICE lab. The DICE lab may have certain rights or restrictions
42 | related to such patents that need to be addressed before filing the application.
43 |
44 | [5] Compliance with Law
45 | In exercising your rights under this Agreement, you agree to comply with all
46 | applicable governmental laws and regulations, including but not limited to the
47 | use, export, and transmission of the Software. You are solely responsible for
48 | ensuring that your use of the Software complies with such laws and regulations.
49 | The DICE lab is not responsible for any violations of such laws or regulations
50 | by you.
51 |
52 | [6] Warranty
53 | The Software is provided "AS IS" without warranty of any kind, express or
54 | implied, including but not limited to the warranties of merchantability, fitness
55 | for a particular purpose and non-infringement of third-party rights. The
56 | Software may also contain errors and is subject to further development and
57 | revision. The DICE lab does not guarantee the accuracy of the Software or any
58 | result or data arising from the use of the Software.
59 |
60 | [7] Disclaimers
61 | The Software has been designed for research purposes only and has not been
62 | reviewed or approved by the Food and Drug Administration or by any other agency.
63 | You acknowledge and agree that clinical applications are neither recommended nor
64 | advised.
65 |
66 | [8] Limitation of Liability
67 | In no event shall the DICE lab be liable to any party for any direct, indirect,
68 | special, incidental, exemplary, or consequential damages, however caused and
69 | under any theory of liability, arising in any way related to the Software, even
70 | if the DICE lab has been advised of the possibility of such damages. Except to
71 | the extent prohibited by law or regulation, you assume all risk and liability
72 | for your use of the Software. You also agree to indemnify and hold harmless the
73 | DICE lab from and against all claims, suits, actions, demands, and judgments
74 | arising from your use or misuse of the Software.
75 |
76 |
77 | ------------------------------------CONTACT-------------------------------------
78 | If you have any question about the terms of this Agreement, you may contact the
79 | head of the DICE lab Alessandro Daducci at alessandro.daducci@univr.it
80 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | recursive-include commit *.c
2 | recursive-include commit *.cpp
3 | recursive-include commit *.h
4 | recursive-include commit *pyx
5 | include setup_operator.py
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://pypi.org/project/dmri-commit/)
2 | [](#)
3 | [](https://github.com/daducci/COMMIT/blob/master/LICENSE)
4 | [](#)
5 | [](https://ieeexplore.ieee.org/document/6884830)
6 |
7 | [](#)
8 | [](#)
9 | [](#)
10 | [](#)
11 | [](#)
12 | [](https://twitter.com/intent/follow?screen_name=ADaducci)
13 |
14 | # COMMIT
15 |
16 | The reconstructions recovered with existing tractography algorithms are not really quantitative even though diffusion MRI is a quantitative modality. COMMIT stands for *Convex Optimization for Microstructure Informed Tractography* and is a **powerful framework for enhancing the anatomical accuracy of the reconstructions** by combining tractography with microstructural features of the neuronal tissue.
17 |
18 |
19 |
20 | **How?** Starting from an input set of candidate fiber-tracts estimated using standard fiber-tracking techniques, COMMIT models the diffusion MRI signal in each voxel of the image as a *linear combination* of the restricted and hindered contributions generated in every location of the brain by these candidate tracts. Then, COMMIT seeks for the effective contribution of each of them such that they globally fit the measured signal at best.
21 | These weights can be *efficiently estimated by solving a convenient linear system*.
22 |
23 | Results clearly demonstrated the benefits of the proposed formulation, opening new perspectives for a more quantitative and biologically-plausible assessment of the structural connectivity of the brain. See the [references](https://github.com/daducci/COMMIT/wiki/References) for more information.
24 |
25 |
26 |
27 |
28 |
29 | ## Main features
30 |
31 | - Very efficient: COMMIT is implemented in Python but the core of the algorithm is implemented in C++ and using **multi-thread programming** for efficient parallel computation.
32 | - Accepts and works with **any input tractogram** (i.e. set of fiber tracts).
33 | - Can easily implement and consider **any multi-compartment model** available in the literature: possibility to account for restricted, hindered as well as isotropic contributions into the signal forward model.
34 | - **Low memory** consumption using optimized sparse data structures, e.g. it can easily run on a standard laptop with 8GB RAM a full-brain tractogram from the HCP data (1M fibers, 3 shells, 1.25 mm^3 resolution).
35 | - **Soon**: **GPU implementation** for even faster model fitting.
36 |
37 |
38 | ## Documentation
39 |
40 | More information/documentation, as well as a series of tutorials, can be found in the [wiki pages](https://github.com/daducci/COMMIT/wiki/Home).
41 |
42 | ### Installation
43 | To install COMMIT, refer to the [installation guide](https://github.com/daducci/COMMIT/wiki/Installation).
44 |
45 | ### Getting started
46 |
47 | To get started with the COMMIT framework, have a look at [this tutorial](https://github.com/daducci/COMMIT/wiki/Getting-started), which will guide you through the main steps of the processing.
48 |
49 |
--------------------------------------------------------------------------------
/commit/__init__.py:
--------------------------------------------------------------------------------
1 | from importlib import metadata
2 |
3 | from .core import Evaluation, setup
4 |
5 | __all__ = ['core','models','solvers','trk2dictionary']
6 |
7 | try:
8 | __version__ = metadata.version('dmri-commit')
9 | except metadata.PackageNotFoundError:
10 | __version__ = 'not installed'
11 |
--------------------------------------------------------------------------------
/commit/models.py:
--------------------------------------------------------------------------------
1 | from Cython.Build.Inline import _get_build_extension
2 | from Cython.Build import cythonize
3 | from os import environ
4 | import os
5 | from setuptools import Extension
6 | import sys
7 |
8 | import numpy as np
9 |
10 | from amico.models import BaseModel, StickZeppelinBall as _StickZeppelinBall, CylinderZeppelinBall as _CylinderZeppelinBall
11 | import amico.util as util
12 |
13 | from dicelib.ui import setup_logger
14 |
15 |
16 | logger = setup_logger('models')
17 |
18 | try:
19 | sys.path.append(environ["WIP_MODEL"])
20 | extension = Extension(name='commitwipmodels',
21 | language='c++',
22 | sources=[os.environ['WIP_MODEL'] + '/commitwipmodels.pyx'],
23 | extra_compile_args=['-w'])
24 | build_extension = _get_build_extension()
25 | build_extension.extensions = cythonize([extension],
26 | include_path=[],
27 | quiet=False)
28 | build_extension.build_temp = os.environ['WIP_MODEL'] + '/build'
29 | build_extension.build_lib = os.environ['WIP_MODEL']
30 |
31 | build_extension.run()
32 | from commitwipmodels import *
33 |
34 | except ValueError:
35 | # check if .so exists
36 | path_files = os.listdir(environ["WIP_MODEL"])
37 | for f in path_files:
38 | if f.startswith('commitwipmodels') and f.endswith('.so'):
39 | from commitwipmodels import *
40 | else:
41 | pass
42 |
43 | except KeyError:
44 | pass
45 | except ImportError:
46 | pass
47 |
48 |
49 | class StickZeppelinBall(_StickZeppelinBall):
50 | """Simulate the response functions according to the Stick-Zeppelin-Ball model.
51 | See the AMICO.model module for details.
52 | """
53 | def resample(self, in_path, idx_out, Ylm_out, doMergeB0, ndirs):
54 | util.set_verbose(2)
55 | return super().resample(in_path, idx_out, Ylm_out, doMergeB0, ndirs)
56 |
57 |
58 |
59 | class CylinderZeppelinBall(_CylinderZeppelinBall):
60 | """Simulate the response functions according to the Cylinder-Zeppelin-Ball model.
61 | See the AMICO.model module for details.
62 | """
63 | def resample(self, in_path, idx_out, Ylm_out, doMergeB0, ndirs):
64 | util.set_verbose(2)
65 | return super().resample(in_path, idx_out, Ylm_out, doMergeB0, ndirs)
66 |
67 | class VolumeFractions(BaseModel):
68 | """Implements a simple model where each compartment contributes only with
69 | its own volume fraction. This model has been created to test there
70 | ability to remove false positive fibers with COMMIT.
71 | """
72 | def __init__(self):
73 | self.id = 'VolumeFractions'
74 | self.name = 'Volume fractions'
75 | self.maps_name = []
76 | self.maps_descr = []
77 | self.nolut = True
78 |
79 | def set(self):
80 | return
81 |
82 | def get_params(self):
83 | params = {}
84 | params['id'] = self.id
85 | params['name'] = self.name
86 | return params
87 |
88 | def set_solver(self):
89 | ERROR('Not implemented')
90 |
91 | def generate(self, out_path, aux, idx_in, idx_out, ndirs):
92 | return
93 |
94 | def resample(self, in_path, idx_out, Ylm_out, doMergeB0, ndirs):
95 | if doMergeB0:
96 | nS = 1 + self.scheme.dwi_count
97 | merge_idx = np.hstack((self.scheme.b0_idx[0], self.scheme.dwi_idx))
98 | else:
99 | nS = self.scheme.nS
100 | merge_idx = np.arange(nS)
101 |
102 | KERNELS = {}
103 | KERNELS['model'] = self.id
104 | KERNELS['wmr'] = np.ones((1, ndirs, nS), dtype=np.float32)
105 | KERNELS['wmh'] = np.ones((0, ndirs, nS), dtype=np.float32)
106 | KERNELS['iso'] = np.ones((0, nS), dtype=np.float32)
107 | return KERNELS
108 |
109 | def fit(self, evaluation):
110 | ERROR('Not implemented')
--------------------------------------------------------------------------------
/commit/operator/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/daducci/COMMIT/61946ab97a6ee2b867feb7a1313b9e7f9664d288/commit/operator/__init__.py
--------------------------------------------------------------------------------
/commit/operator/operator.pyx:
--------------------------------------------------------------------------------
1 | #!python
2 | #cython: language_level=3, boundscheck=False, wraparound=False, profile=False
3 |
4 | import numpy as np
5 |
6 | from dicelib.ui import setup_logger
7 |
8 | # Interfaces to actual C code performing the multiplications
9 | cdef extern void COMMIT_A(
10 | int _nF, int _nE, int _nV, int _nS, int _ndirs,
11 | double *_v_in, double *_v_out,
12 | unsigned int *_ICf, unsigned int *_ICv, unsigned short *_ICo, float *_ICl,
13 | unsigned int *_ECv, unsigned short *_ECo,
14 | unsigned int *_ISOv,
15 | float *_wmrSFP, float *_wmhSFP, float *_isoSFP,
16 | unsigned int* _ICthreads, unsigned int* _ECthreads, unsigned int* _ISOthreads,
17 | unsigned int _nIC, unsigned int _nEC, unsigned int _nISO, unsigned int _nThreads
18 | ) nogil
19 |
20 | cdef extern void COMMIT_At(
21 | int _nF, int _n, int _nE, int _nV, int _nS, int _ndirs,
22 | double *_v_in, double *_v_out,
23 | unsigned int *_ICf, unsigned int *_ICv, unsigned short *_ICo, float *_ICl,
24 | unsigned int *_ECv, unsigned short *_ECo,
25 | unsigned int *_ISOv,
26 | float *_wmrSFP, float *_wmhSFP, float *_isoSFP,
27 | unsigned char* _ICthreadsT, unsigned int* _ECthreadsT, unsigned int* _ISOthreadsT,
28 | unsigned int _nIC, unsigned int _nEC, unsigned int _nISO, unsigned int _nThreads
29 | ) nogil
30 |
31 | cdef extern void COMMIT_A_nolut(
32 | int _nF,
33 | double *_v_in, double *_v_out,
34 | unsigned int *_ICf, unsigned int *_ICv, float *_ICl,
35 | unsigned int *_ISOv,
36 | unsigned int* _ICthreads, unsigned int* _ISOthreads,
37 | unsigned int _nISO, unsigned int _nThreads
38 | ) nogil
39 |
40 | cdef extern void COMMIT_At_nolut(
41 | int _nF, int _n,
42 | double *_v_in, double *_v_out,
43 | unsigned int *_ICf, unsigned int *_ICv, float *_ICl,
44 | unsigned int *_ISOv,
45 | unsigned char* _ICthreadsT, unsigned int* _ISOthreadsT,
46 | unsigned int _nISO, unsigned int _nThreads
47 | ) nogil
48 |
49 | logger = setup_logger('operator')
50 |
51 | cdef class LinearOperator :
52 | """This class is a wrapper to the C code for performing marix-vector multiplications
53 | with the COMMIT linear operator A. The multiplications are done using C code
54 | that uses information from the DICTIONARY, KERNELS and THREADS data structures.
55 | """
56 | cdef int nS, nF, nR, nE, nT, nV, nI, n, ndirs
57 | cdef public int adjoint, n1, n2
58 |
59 | cdef DICTIONARY
60 | cdef KERNELS
61 | cdef THREADS
62 | cdef nolut
63 |
64 | cdef unsigned int* ICf
65 | cdef float* ICl
66 | cdef unsigned int* ICv
67 | cdef unsigned short* ICo
68 | cdef unsigned int* ECv
69 | cdef unsigned short* ECo
70 | cdef unsigned int* ISOv
71 |
72 | cdef float* LUT_IC
73 | cdef float* LUT_EC
74 | cdef float* LUT_ISO
75 |
76 | cdef unsigned int* ICthreads
77 | cdef unsigned int* ECthreads
78 | cdef unsigned int* ISOthreads
79 |
80 | cdef unsigned char* ICthreadsT
81 | cdef unsigned int* ECthreadsT
82 | cdef unsigned int* ISOthreadsT
83 |
84 |
85 | def __init__( self, DICTIONARY, KERNELS, THREADS, nolut=False ) :
86 | """Set the pointers to the data structures used by the C code."""
87 | self.DICTIONARY = DICTIONARY
88 | self.KERNELS = KERNELS
89 | self.THREADS = THREADS
90 | self.nolut = nolut
91 |
92 | self.nF = DICTIONARY['IC']['nF'] # number of FIBERS
93 | self.nR = KERNELS['wmr'].shape[0] # number of FIBER RADII
94 | self.nE = DICTIONARY['EC']['nE'] # number of EC segments
95 | self.nT = KERNELS['wmh'].shape[0] # number of EC TORTUOSITY values
96 | self.nV = DICTIONARY['nV'] # number of VOXELS
97 | self.nI = KERNELS['iso'].shape[0] # number of ISO contributions
98 | self.n = DICTIONARY['IC']['n'] # numbner of IC segments
99 | self.ndirs = KERNELS['wmr'].shape[1] # number of directions
100 |
101 | if KERNELS['wmr'].size > 0 :
102 | self.nS = KERNELS['wmr'].shape[2] # number of SAMPLES
103 | elif KERNELS['wmh'].size > 0 :
104 | self.nS = KERNELS['wmh'].shape[2]
105 | else :
106 | self.nS = KERNELS['wmr'].shape[1]
107 |
108 | self.adjoint = 0 # direct of inverse product
109 |
110 | self.n1 = self.nV*self.nS
111 | self.n2 = self.nR*self.nF + self.nT*self.nE + self.nI*self.nV
112 |
113 | # get C pointers to arrays in DICTIONARY
114 | cdef unsigned int [::1] ICf = DICTIONARY['IC']['fiber']
115 | self.ICf = &ICf[0]
116 | cdef float [::1] ICl = DICTIONARY['IC']['len']
117 | self.ICl = &ICl[0]
118 | cdef unsigned int [::1] ICv = DICTIONARY['IC']['v']
119 | self.ICv = &ICv[0]
120 | cdef unsigned short [::1] ICo = DICTIONARY['IC']['o']
121 | self.ICo = &ICo[0]
122 | cdef unsigned int [::1] ECv = DICTIONARY['EC']['v']
123 | self.ECv = &ECv[0]
124 | cdef unsigned short [::1] ECo = DICTIONARY['EC']['o']
125 | self.ECo = &ECo[0]
126 | cdef unsigned int [::1] ISOv = DICTIONARY['ISO']['v']
127 | self.ISOv = &ISOv[0]
128 |
129 | # get C pointers to arrays in KERNELS
130 | cdef float [:, :, ::1] wmrSFP = KERNELS['wmr']
131 | self.LUT_IC = &wmrSFP[0,0,0]
132 | cdef float [:, :, ::1] wmhSFP = KERNELS['wmh']
133 | self.LUT_EC = &wmhSFP[0,0,0]
134 | cdef float [:, ::1] isoSFP = KERNELS['iso']
135 | self.LUT_ISO = &isoSFP[0,0]
136 |
137 | # get C pointers to arrays in THREADS
138 | cdef unsigned int [::1] ICthreads = THREADS['IC']
139 | self.ICthreads = &ICthreads[0]
140 | cdef unsigned int [::1] ECthreads = THREADS['EC']
141 | self.ECthreads = &ECthreads[0]
142 | cdef unsigned int [::1] ISOthreads = THREADS['ISO']
143 | self.ISOthreads = &ISOthreads[0]
144 |
145 | cdef unsigned char [::1] ICthreadsT = THREADS['ICt']
146 | self.ICthreadsT = &ICthreadsT[0]
147 | cdef unsigned int [::1] ECthreadsT = THREADS['ECt']
148 | self.ECthreadsT = &ECthreadsT[0]
149 | cdef unsigned int [::1] ISOthreadsT = THREADS['ISOt']
150 | self.ISOthreadsT = &ISOthreadsT[0]
151 |
152 |
153 | @property
154 | def T( self ) :
155 | """Transpose of the explicit matrix."""
156 | C = LinearOperator( self.DICTIONARY, self.KERNELS, self.THREADS, self.nolut )
157 | C.adjoint = 1 - C.adjoint
158 | return C
159 |
160 |
161 | @property
162 | def shape( self ) :
163 | """Size of the explicit matrix."""
164 | if not self.adjoint :
165 | return ( self.n1, self.n2 )
166 | else :
167 | return ( self.n2, self.n1 )
168 |
169 |
170 | def dot( self, double [::1] v_in ):
171 | """Wrapper to C code for efficiently performing the matrix-vector multiplications.
172 |
173 | Parameters
174 | ----------
175 | v_in : 1D numpy.array of double
176 | Input vector for the matrix-vector multiplication
177 |
178 | Returns
179 | -------
180 | v_out : 1D numpy.array of double
181 | Results of the multiplication
182 | """
183 |
184 | # Permit only matrix-vector multiplications
185 | if v_in.size != self.shape[1] :
186 | raise RuntimeError( "A.dot(): dimensions do not match" )
187 |
188 | # Create output array
189 | cdef double [::1] v_out = np.zeros( self.shape[0], dtype=np.float64 )
190 |
191 | cdef unsigned int nthreads = self.THREADS['n']
192 | cdef unsigned int nIC = self.KERNELS['wmr'].shape[0]
193 | cdef unsigned int nEC = self.KERNELS['wmh'].shape[0]
194 | cdef unsigned int nISO = self.KERNELS['iso'].shape[0]
195 |
196 | # Call the cython function to read the memory pointers
197 | if not self.adjoint :
198 | # DIRECT PRODUCT A*x
199 | if self.nolut:
200 | with nogil:
201 | COMMIT_A_nolut(
202 | self.nF,
203 | &v_in[0], &v_out[0],
204 | self.ICf, self.ICv, self.ICl,
205 | self.ISOv,
206 | self.ICthreads, self.ISOthreads,
207 | nISO, nthreads
208 | )
209 | else:
210 | with nogil:
211 | COMMIT_A(
212 | self.nF, self.nE, self.nV, self.nS, self.ndirs,
213 | &v_in[0], &v_out[0],
214 | self.ICf, self.ICv, self.ICo, self.ICl,
215 | self.ECv, self.ECo,
216 | self.ISOv,
217 | self.LUT_IC, self.LUT_EC, self.LUT_ISO,
218 | self.ICthreads, self.ECthreads, self.ISOthreads,
219 | nIC, nEC, nISO, nthreads
220 | )
221 | else :
222 | # INVERSE PRODUCT A'*y
223 | if self.nolut:
224 | with nogil:
225 | COMMIT_At_nolut(
226 | self.nF, self.n,
227 | &v_in[0], &v_out[0],
228 | self.ICf, self.ICv, self.ICl,
229 | self.ISOv,
230 | self.ICthreadsT, self.ISOthreadsT,
231 | nISO, nthreads
232 | )
233 | else:
234 | with nogil:
235 | COMMIT_At(
236 | self.nF, self.n, self.nE, self.nV, self.nS, self.ndirs,
237 | &v_in[0], &v_out[0],
238 | self.ICf, self.ICv, self.ICo, self.ICl,
239 | self.ECv, self.ECo,
240 | self.ISOv,
241 | self.LUT_IC, self.LUT_EC, self.LUT_ISO,
242 | self.ICthreadsT, self.ECthreadsT, self.ISOthreadsT,
243 | nIC, nEC, nISO, nthreads
244 | )
245 |
246 | return v_out
247 |
--------------------------------------------------------------------------------
/commit/proximals.pyx:
--------------------------------------------------------------------------------
1 | #!python
2 | #cython: language_level=3, boundscheck=False, wraparound=False, profile=False
3 |
4 | from libc.math cimport sqrt
5 |
6 | import numpy as np
7 |
8 | from dicelib.ui import setup_logger
9 |
10 | logger = setup_logger('proximals')
11 |
12 |
13 | cpdef non_negativity(double [::1] x, int compartment_start, int compartment_size):
14 | """
15 | POCS for the first orthant (non-negativity)
16 | """
17 | cdef:
18 | int i
19 | for i in xrange(compartment_start, compartment_start+compartment_size):
20 | if x[i] <= 0.0 :
21 | x[i] = 0.0
22 | return np.asarray( x )
23 |
24 |
25 | cpdef soft_thresholding(double [::1] x, double lam, int compartment_start, int compartment_size) :
26 | """
27 | Proximal of L1 norm
28 | """
29 | # NB: this preserves non-negativity
30 | cdef:
31 | int i
32 | for i in xrange(compartment_start, compartment_start+compartment_size):
33 | if x[i] > lam:
34 | x[i] = x[i] - lam
35 | elif x[i] < -lam:
36 | x[i] = x[i] + lam
37 | else:
38 | x[i] = 0.0
39 | return np.asarray( x )
40 |
41 |
42 | cpdef w_soft_thresholding(double [::1] x, double [::1] w, double lam, int compartment_start, int compartment_size) :
43 | """
44 | Proximal of weighted L1 norm
45 | """
46 | # NB: this preserves non-negativity
47 | cdef:
48 | int i
49 | for i in xrange(compartment_start, compartment_start+compartment_size):
50 | if x[i] > w[i]*lam:
51 | x[i] = x[i] - w[i]*lam
52 | elif x[i] < -w[i]*lam:
53 | x[i] = x[i] + w[i]*lam
54 | else:
55 | x[i] = 0.0
56 | return np.asarray( x )
57 |
58 |
59 | cpdef projection_onto_l2_ball(double [::1] x, double lam, int compartment_start, int compartment_size) :
60 | """
61 | Proximal of L2 norm
62 | """
63 | # NB: this preserves non-negativity
64 | cdef:
65 | double xn = 0.0, k
66 | int i
67 | for i in xrange(compartment_start, compartment_start+compartment_size):
68 | xn += x[i]*x[i]
69 | xn = sqrt(xn)
70 | if xn > lam :
71 | k = 1. - lam/xn
72 | for i in xrange(compartment_start, compartment_start+compartment_size):
73 | x[i] = x[i]*k
74 | else :
75 | for i in xrange(compartment_start, compartment_start+compartment_size):
76 | x[i] = 0
77 | return np.asarray( x )
78 |
79 |
80 | cpdef omega_group_lasso(double [::1] x, int [::1] group_idx, int [::1] group_size, double [::1] group_weight, double lam) :
81 | """
82 | References:
83 | [1] Jenatton et al. - `Proximal Methods for Hierarchical Sparse Coding`
84 | """
85 | cdef:
86 | int nG = group_size.size, N
87 | int k, i, j = 0
88 | double omega = 0.0, gNorm, x_i
89 |
90 | if lam != 0:
91 | for k in xrange(nG):
92 | N = group_size[k]
93 | gNorm = 0.0
94 | for i in xrange(j,j+N) :
95 | x_i = x[group_idx[i]]
96 | gNorm += x_i*x_i
97 | omega += group_weight[k] * sqrt( gNorm )
98 | j += N
99 | return lam*omega
100 |
101 |
102 |
103 | cpdef prox_group_lasso( double [::1] x, int [::1] group_idx, int [::1] group_size, double [::1] group_weight, double lam) :
104 | """
105 | References:
106 | [1] Jenatton et al. - `Proximal Methods for Hierarchical Sparse Coding`
107 | """
108 | cdef:
109 | int nG = group_size.size
110 | int N = 0
111 | int k = 0
112 | int i = 0
113 | int j = 0
114 | double wl, gNorm, x_i
115 |
116 | if lam != 0:
117 | for k in xrange(nG) :
118 | N = group_size[k]
119 | gNorm = 0.0
120 | for i in xrange(j,j+N) :
121 | x_i = x[group_idx[i]]
122 | gNorm += x_i*x_i
123 | gNorm = sqrt( gNorm )
124 |
125 | wl = group_weight[k] * lam
126 | if gNorm <= wl :
127 | for i in xrange(j,j+N) :
128 | x[ group_idx[i] ] = 0.0
129 | else :
130 | wl = (gNorm-wl)/gNorm
131 | for i in xrange(j,j+N) :
132 | x[ group_idx[i] ] *= wl
133 | j += N
134 | return np.asarray( x )
135 |
136 |
137 |
138 | cpdef omega_sparse_group_lasso(double [::1] x, int [::1] group_idx, int [::1] group_size, double [::1] group_weight, double lam1, double lam2) :
139 | cdef:
140 | int nG = group_size.size
141 | int N = 0
142 | int k = 0
143 | int i = 0
144 | int j = 0
145 | double gNorm, x_i
146 | double omega1 = 0.0
147 | double omega2 = 0.0
148 |
149 | if lam1 != 0 or lam2 != 0:
150 | omega1 = np.sum(np.abs(x)) # l1 penalty
151 | for k in xrange(nG):
152 | N = group_size[k]
153 | gNorm = 0.0
154 | for i in xrange(j,j+N) :
155 | x_i = x[group_idx[i]]
156 | gNorm += x_i*x_i
157 | omega2 += group_weight[k] * sqrt( gNorm ) # group l2 penalty
158 | j += N
159 | return lam1*omega1 + lam2*omega2
160 |
161 |
162 | cpdef omega_w_sparse_group_lasso(double [::1] x, double [::1] w, int [::1] group_idx, int [::1] group_size, double [::1] group_weight, double lam1, double lam2) :
163 | cdef:
164 | int nG = group_size.size
165 | int N = 0
166 | int k = 0
167 | int i = 0
168 | int j = 0
169 | int ii = 0
170 | double gNorm, x_i
171 | double omega1 = 0.0
172 | double omega2 = 0.0
173 |
174 | if lam1 != 0 or lam2 != 0:
175 | for ii in xrange(x.shape[0]):
176 | omega1 += np.abs(w[ii]*x[ii]) # l1 penalty
177 | for k in xrange(nG):
178 | N = group_size[k]
179 | gNorm = 0.0
180 | for i in xrange(j,j+N) :
181 | x_i = x[group_idx[i]]
182 | gNorm += x_i*x_i
183 | omega2 += group_weight[k] * sqrt( gNorm ) # group l2 penalty
184 | j += N
185 |
186 | return lam1*omega1 + lam2*omega2
187 |
188 |
189 |
--------------------------------------------------------------------------------
/commit/trk2dictionary/ProgressBar.h:
--------------------------------------------------------------------------------
1 | #ifndef __PROGRESSBAR_H__
2 | #define __PROGRESSBAR_H__
3 |
4 | #include
5 | #include
6 | #include
7 |
8 | #define EXTRA_ERASE_CHARS 50
9 |
10 | class ProgressBar
11 | {
12 | private:
13 | int width, i, N;
14 | std::string prefix, msg;
15 |
16 | public:
17 | void reset( unsigned int _N );
18 | void setPrefix( std::string _prefix );
19 | void inc();
20 | void close();
21 |
22 | ProgressBar( unsigned int _N, unsigned int _width );
23 | ProgressBar(unsigned int _width = 25);
24 | ~ProgressBar();
25 | };
26 |
27 | ProgressBar::ProgressBar(unsigned int _width){
28 | width = _width;
29 | };
30 |
31 | ProgressBar::ProgressBar( unsigned int _N, unsigned int _width = 25 )
32 | {
33 | width = _width;
34 | reset( _N );
35 | }
36 |
37 | ProgressBar::~ProgressBar()
38 | {
39 | };
40 |
41 |
42 | void ProgressBar::reset( unsigned int _N )
43 | {
44 | i = 1;
45 | N = _N;
46 | msg = "";
47 | }
48 |
49 | void ProgressBar::setPrefix( std::string _prefix )
50 | {
51 | prefix = _prefix;
52 | }
53 |
54 | /* ****************************************************** */
55 | /* Increment the counter and, if needed, the progress bar */
56 | /* ****************************************************** */
57 | void ProgressBar::inc()
58 | {
59 | if ( i < 1 || i > N ) return;
60 |
61 | if ( i % width == 0 || i==N )
62 | {
63 | int p = floor( float(i)/N*width );
64 | msg = prefix + "[" + std::string(p,'=') + std::string(width-p,' ') + "]";
65 | printf( "%s\r", msg.c_str() );
66 | fflush( stdout );
67 | }
68 | i++;
69 | }
70 |
71 |
72 | /* **************************************** */
73 | /* Fill the progress bar and go to new line */
74 | /* **************************************** */
75 | void ProgressBar::close()
76 | {
77 | msg = std::string(prefix.length()+width+2+EXTRA_ERASE_CHARS,' ');
78 | printf("%s\r",msg.c_str());
79 | fflush( stdout );
80 | i = 0;
81 | N = 0;
82 | msg = "";
83 | }
84 |
85 |
86 | #endif
87 |
--------------------------------------------------------------------------------
/commit/trk2dictionary/Vector.h:
--------------------------------------------------------------------------------
1 | #ifndef __Vector_H__
2 | #define __Vector_H__
3 |
4 | #include
5 |
6 |
7 | template
8 | class Vector
9 | {
10 | public:
11 | T x, y, z;
12 |
13 | void Set( T _x, T _y, T _z );
14 | float norm();
15 | void Normalize();
16 | void Multiply( T k );
17 | void VectorProduct( const Vector & v1, const Vector & v2 );
18 | T ScalarProduct( const Vector & v );
19 | float DistanceTo( const Vector & v );
20 |
21 | void operator=( const Vector & v );
22 |
23 | Vector();
24 | Vector( T _x, T _y, T _z );
25 | };
26 |
27 |
28 | template
29 | Vector::Vector()
30 | { x = y = z = 0; }
31 |
32 |
33 | template
34 | Vector::Vector( T _x, T _y, T _z )
35 | { x = _x; y = _y; z = _z; }
36 |
37 |
38 | template
39 | void Vector::Set( T _x, T _y, T _z )
40 | { x = _x; y = _y; z = _z; }
41 |
42 |
43 | template
44 | float Vector::norm()
45 | {
46 | return sqrt(x*x+y*y+z*z);
47 | }
48 |
49 |
50 | template
51 | void Vector::Normalize()
52 | {
53 | float len = sqrt(x*x+y*y+z*z);
54 | if (len==0) return;
55 | x = x/len;
56 | y = y/len;
57 | z = z/len;
58 | }
59 |
60 |
61 | template
62 | void Vector::Multiply( T k )
63 | {
64 | x *= k;
65 | y *= k;
66 | z *= k;
67 | }
68 |
69 |
70 | template
71 | T Vector::ScalarProduct( const Vector & v )
72 | {
73 | return x*v.x + y*v.y + z*v.z;
74 | }
75 |
76 |
77 | template
78 | void Vector::VectorProduct( const Vector & v1, const Vector & v2 )
79 | {
80 | x = v1.y*v2.z - v2.y*v1.z;
81 | y = v1.z*v2.x - v2.z*v1.x;
82 | z = v1.x*v2.y - v2.x*v1.y;
83 | }
84 |
85 | template
86 | float Vector::DistanceTo( const Vector & v )
87 | {
88 | return sqrt( pow(x-v.x,2) + pow(y-v.y,2) + pow(z-v.z,2) );
89 | }
90 |
91 | template
92 | void Vector::operator=( const Vector & v )
93 | {
94 | x = v.x;
95 | y = v.y;
96 | z = v.z;
97 | }
98 |
99 | #endif
100 |
--------------------------------------------------------------------------------
/extras/.gitignore:
--------------------------------------------------------------------------------
1 | build/
2 |
--------------------------------------------------------------------------------
/extras/CMake/FindBLITZ.cmake:
--------------------------------------------------------------------------------
1 | FIND_PATH( BLITZ_INCLUDE_DIR
2 | blitz/blitz.h
3 | PATHS /usr/local/include /usr/include
4 | ONLY_CMAKE_FIND_ROOT_PATH
5 | )
6 |
7 | FIND_LIBRARY( BLITZ_LIBRARIES
8 | NAMES libblitz${CMAKE_STATIC_LIBRARY_SUFFIX} libblitz${CMAKE_SHARED_LIBRARY_SUFFIX}
9 | )
10 |
11 | IF ( BLITZ_INCLUDE_DIR AND BLITZ_LIBRARIES )
12 | SET(BLITZ_FOUND TRUE)
13 | ENDIF ( BLITZ_INCLUDE_DIR AND BLITZ_LIBRARIES )
14 |
15 | IF (BLITZ_FOUND)
16 | IF (NOT BLITZ_FIND_QUIETLY)
17 | MESSAGE(STATUS "Found BLITZ: ${BLITZ_LIBRARIES}")
18 | ENDIF (NOT BLITZ_FIND_QUIETLY)
19 | ELSE (BLITZ_FOUND)
20 | IF (BLITZ_FIND_REQUIRED)
21 | MESSAGE(FATAL_ERROR "Could not find BLITZ (which is required)")
22 | ENDIF (BLITZ_FIND_REQUIRED)
23 | ENDIF (BLITZ_FOUND)
24 |
--------------------------------------------------------------------------------
/extras/CMake/FindNIFTI.cmake:
--------------------------------------------------------------------------------
1 | # ZLIB is required
2 | # ================
3 | FIND_PACKAGE( ZLIB REQUIRED )
4 |
5 |
6 | # Search for nifticlib headers and libraries
7 | # ==========================================
8 | FIND_PATH( NIFTI_INCLUDE_DIR
9 | nifti1.h
10 | /usr/local/include/nifti /usr/include/nifti
11 | )
12 |
13 | FIND_LIBRARY( NIFTI_BASE_LIBRARY
14 | NAMES libniftiio${CMAKE_SHARED_LIBRARY_SUFFIX} libniftiio${CMAKE_STATIC_LIBRARY_SUFFIX}
15 | )
16 |
17 | FIND_LIBRARY( NIFTI_ZNZ_LIBRARY
18 | NAMES libznz${CMAKE_SHARED_LIBRARY_SUFFIX} libznz${CMAKE_STATIC_LIBRARY_SUFFIX}
19 | )
20 |
21 |
22 | # If everything is ok, set variable for the package
23 | # =================================================
24 | IF( NIFTI_INCLUDE_DIR AND NIFTI_BASE_LIBRARY AND NIFTI_ZNZ_LIBRARY )
25 |
26 | SET( NIFTI_FOUND TRUE )
27 | SET( NIFTI_INCLUDE_DIRS
28 | ${NIFTI_INCLUDE_DIR}
29 | ${ZLIB_INCLUDE_DIRS}
30 | )
31 | SET( NIFTI_LIBRARIES
32 | ${NIFTI_BASE_LIBRARY}
33 | ${NIFTI_ZNZ_LIBRARY}
34 | ${ZLIB_LIBRARIES}
35 | )
36 | IF( NOT NIFTI_FIND_QUIETLY )
37 | MESSAGE(STATUS "Found NIFTI: ${NIFTI_LIBRARIES}")
38 | ENDIF (NOT NIFTI_FIND_QUIETLY)
39 |
40 | ELSE()
41 |
42 | SET( NIFTI_FOUND FALSE )
43 | IF( NIFTI_FIND_REQUIRED )
44 | MESSAGE(FATAL_ERROR "Could not find NIFTI (which is required)")
45 | ENDIF()
46 |
47 | ENDIF()
48 |
--------------------------------------------------------------------------------
/extras/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.8)
2 |
3 | PROJECT( COMMITcpp )
4 | set( CMAKE_CXX_STANDARD 11 )
5 |
6 | set( CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/CMake" )
7 | SET( CMAKE_CXX_FLAGS "-w" )
8 |
9 | INCLUDE_DIRECTORIES ("${PROJECT_SOURCE_DIR}/include")
10 |
11 | ADD_SUBDIRECTORY( COMMIT_debugger )
12 |
--------------------------------------------------------------------------------
/extras/COMMIT_debugger/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | PROJECT( COMMIT_debugger )
2 | ADD_EXECUTABLE( ${PROJECT_NAME} main.cxx )
3 |
4 |
5 | ######################## FIND PACKAGES USED #######################################
6 | FIND_PACKAGE( BLITZ REQUIRED )
7 | FIND_PACKAGE( NIFTI REQUIRED )
8 | FIND_PACKAGE( OpenGL REQUIRED )
9 | FIND_PACKAGE( GLUT REQUIRED )
10 |
11 |
12 | ############################ INCLUDE / LINK #######################################
13 | INCLUDE_DIRECTORIES( ${BLITZ_INCLUDE_DIR} )
14 | INCLUDE_DIRECTORIES( ${NIFTI_INCLUDE_DIRS} )
15 | INCLUDE_DIRECTORIES( ${OPENGL_INCLUDE_DIR} )
16 | INCLUDE_DIRECTORIES( ${GLUT_INCLUDE_DIR} )
17 |
18 | TARGET_LINK_LIBRARIES( ${PROJECT_NAME}
19 | ${BLITZ_LIBRARIES}
20 | ${NIFTI_LIBRARIES}
21 | ${OPENGL_LIBRARIES}
22 | ${GLUT_LIBRARIES}
23 | )
24 |
25 | ################################### INSTALL #######################################
26 | INSTALL( TARGETS ${PROJECT_NAME}
27 | RUNTIME DESTINATION "bin"
28 | )
29 |
--------------------------------------------------------------------------------
/extras/COMMIT_debugger/OPENGL_utils.h:
--------------------------------------------------------------------------------
1 | #ifndef __OPENGL_UTILS_H__
2 | #define __OPENGL_UTILS_H__
3 |
4 | #include
5 |
6 | #include "VECTOR.h"
7 | typedef VECTOR Vec3Di;
8 | typedef VECTOR Vec3Df;
9 |
10 |
11 | namespace OPENGL_utils
12 | {
13 |
14 | void identity(GLfloat* result)
15 | {
16 | for (int i=0; i<4; i++)
17 | for (int j=0; j<4; j++)
18 | if (i==j) result[4*i+j]=1; else result[4*i+j]=0;
19 | }
20 |
21 |
22 | void matXMat(GLfloat* m, GLfloat* m1, GLfloat* result)
23 | {
24 | for (int i=0; i<4; i++)
25 | for (int j=0; j<4; j++)
26 | {
27 | result[4*i+j]=0;
28 | for (int t=0; t<4; t++)
29 | result[4*i+j]=result[4*i+j]+m[4*i+t]*m1[4*t+j];
30 | }
31 | }
32 |
33 |
34 | void rotateZ(GLfloat* m, GLfloat ang, GLfloat* result)
35 | {
36 | static GLfloat matrix[16];
37 |
38 | for (int i=0; i<16 ; i++) matrix[i] = 0;
39 | matrix[0] = cos(ang/180*3.1415);
40 | matrix[5] = cos(ang/180*3.1415);
41 | matrix[1] = -sin(ang/180*3.1415);
42 | matrix[4] = sin(ang/180*3.1415);
43 | matrix[10] = 1;
44 | matrix[15] = 1;
45 | matXMat(matrix,m,result);
46 | }
47 |
48 |
49 | void rotateY(GLfloat* m, GLfloat ang, GLfloat* result)
50 | {
51 | static GLfloat matrix[16];
52 |
53 | for (int i=0; i<16 ; i++) matrix[i] = 0;
54 | matrix[0] = cos(ang/180*3.1415);
55 | matrix[10] = cos(ang/180*3.1415);
56 | matrix[8] = -sin(ang/180*3.1415);
57 | matrix[2] = sin(ang/180*3.1415);
58 | matrix[5] = 1;
59 | matrix[15] = 1;
60 | matXMat(matrix,m,result);
61 | }
62 |
63 |
64 | void rotateX(GLfloat* m, GLfloat ang, GLfloat* result)
65 | {
66 | static GLfloat matrix[16];
67 |
68 | for (int i=0; i<16 ; i++) matrix[i] = 0;
69 | matrix[5] = cos(ang/180*3.1415);
70 | matrix[10] = cos(ang/180*3.1415);
71 | matrix[6] = -sin(ang/180*3.1415);
72 | matrix[9] = sin(ang/180*3.1415);
73 | matrix[0] = 1;
74 | matrix[15] = 1;
75 | matXMat(matrix,m,result);
76 | }
77 |
78 |
79 | void translate(GLfloat* m, GLfloat x,GLfloat y,GLfloat z, GLfloat* result)
80 | {
81 | static GLfloat matrix[16];
82 |
83 | for (int i=0; i<16 ; i++) matrix[i] = 0;
84 | matrix[0] = 1;
85 | matrix[5] = 1;
86 | matrix[10] = 1;
87 | matrix[15] = 1;
88 | matrix[12] = x;
89 | matrix[13] = y;
90 | matrix[14] = z;
91 | matXMat(matrix,m,result);
92 | }
93 |
94 | }
95 | #endif
96 |
--------------------------------------------------------------------------------
/extras/include/COLOR_ui.h:
--------------------------------------------------------------------------------
1 | #ifndef __UI_H__
2 | #define __UI_H__
3 |
4 |
5 | #include
6 | #include
7 | #include
8 | #include
9 | using namespace std;
10 |
11 |
12 | /* COLOR constants (abckground is foreground+10) */
13 | #define COLOR_black 30
14 | #define COLOR_red 31
15 | #define COLOR_green 32
16 | #define COLOR_yellow 33
17 | #define COLOR_blue 34
18 | #define COLOR_magenta 35
19 | #define COLOR_cyan 36
20 | #define COLOR_white 37
21 |
22 | #define COLOR_normal 0
23 | #define COLOR_bold 1
24 | #define COLOR_underline 4
25 | #define COLOR_blink 5
26 |
27 | #define COLOR(FG,BG,FONT) "\033["#FONT";"#FG";"#BG"m"
28 | #define COLOR_reset "\033[0m"
29 | #define COLOR_strERR COLOR(31,48,7) "[ERROR]" COLOR(31,48,0) " "
30 | #define COLOR_strWAR COLOR(33,48,7) "[WARNING]" COLOR(33,48,0) " "
31 |
32 |
33 | void COLOR_print(string str, short int FG=COLOR_white, short int BG=COLOR_black, short int FONT=COLOR_normal)
34 | {
35 | printf("\033[%d;%d;%dm%s\033[0m", FONT,FG,BG+10, str.c_str());
36 | }
37 |
38 |
39 | void COLOR_log(string str, short int FG=COLOR_green, short int BG=COLOR_black, short int FONT=COLOR_normal)
40 | {
41 | char buffer [80];
42 | time_t rawtime = time(0);
43 | struct tm * timeinfo = localtime ( &rawtime );
44 | strftime (buffer,80,"%H:%M:%S",timeinfo);
45 |
46 | printf("\n\033[0;%d;%dm[ %s ]\033[%d;%d;%dm %s\033[0m\n", BG,FG+10,buffer, FONT,FG,BG+10,str.c_str());
47 | }
48 |
49 |
50 | void COLOR_msg( string msg, string prefix="" )
51 | {
52 | if ( !prefix.empty() )
53 | cerr << prefix;
54 | cerr << "\033[0;34m "<< msg.c_str() <<"\033[0m\n";
55 | }
56 |
57 |
58 | void COLOR_error( string msg, string prefix="" )
59 | {
60 | if ( !prefix.empty() )
61 | cerr << prefix;
62 | cerr << "\033[0;30;41m[ ERROR ]\033[0;31m "<< msg.c_str() <<"\033[0m\n";
63 | }
64 |
65 |
66 | void COLOR_warning( string msg, string prefix="" )
67 | {
68 | if ( !prefix.empty() )
69 | cerr << prefix;
70 | cerr << "\033[0;30;43m[ WARNING ]\033[0;33m "<< msg.c_str() <<"\033[0m\n";
71 | }
72 |
73 | #endif
74 |
--------------------------------------------------------------------------------
/extras/include/NIFTI.h:
--------------------------------------------------------------------------------
1 | #ifndef __NIFTI_H__
2 | #define __NIFTI_H__
3 |
4 | #include
5 | using namespace blitz;
6 | #include
7 |
8 |
9 | #ifdef INT_2_BYTES
10 | typedef char INT8;
11 | typedef unsigned char UINT8;
12 | typedef int INT16;
13 | typedef unsigned int UINT16;
14 | typedef long INT32;
15 | typedef unsigned long UINT32;
16 | typedef double FLOAT32;
17 | #else
18 | typedef char INT8;
19 | typedef unsigned char UINT8;
20 | typedef short INT16;
21 | typedef unsigned short UINT16;
22 | typedef int INT32;
23 | typedef unsigned int UINT32;
24 | typedef float FLOAT32;
25 | #endif
26 |
27 |
28 | /* Errorcode used for the field "errorCode" */
29 | #define NIFTI_ERROR_NOERROR 0
30 | #define NIFTI_ERROR_WRONGFILETYPE 1
31 | #define NIFTI_ERROR_DATANOTLOADED 2
32 | #define NIFTI_ERROR_UNKNOWN 9
33 |
34 |
35 |
36 | /*****************************************************
37 | ***** NIFTI class *****
38 | ****************************************************/
39 | class NIFTI
40 | {
41 | public:
42 | nifti_image* hdr;
43 | Array* img;
44 |
45 | short isValid() { return errorCode==NIFTI_ERROR_NOERROR; };
46 | short getErrorCode() { return errorCode; };
47 |
48 | short make( const int ndims, const int* dim, const float* pixdim, const short datatype = DT_FLOAT32 );
49 | short open( string filename, bool loadData = true );
50 | short load();
51 | short unload();
52 | short save( string NEW_filename = "" );
53 | void copyHeader( const nifti_image* src );
54 |
55 | NIFTI( string filename, bool loadData = true );
56 | NIFTI();
57 | ~NIFTI();
58 |
59 | private:
60 | short errorCode;
61 | // short getDatatypeCode();
62 | };
63 |
64 |
65 | /* Constructor/destructor */
66 | NIFTI::NIFTI( void )
67 | {
68 | img = NULL;
69 | hdr = NULL;
70 | errorCode = NIFTI_ERROR_DATANOTLOADED;
71 | };
72 |
73 |
74 | NIFTI::NIFTI( string filename, bool loadData )
75 | {
76 | img = NULL;
77 | hdr = NULL;
78 | this->open( filename, loadData );
79 | }
80 |
81 |
82 | NIFTI::~NIFTI()
83 | {
84 | if ( hdr ) nifti_image_unload( hdr );
85 | if ( img ) img->free();
86 | }
87 |
88 |
89 | /* OPEN a nifti file (only the header is loaded) */
90 | short NIFTI::open( string filename, bool loadData )
91 | {
92 | unload();
93 |
94 | try
95 | {
96 | // not a NIFTI file
97 | if ( is_nifti_file(filename.c_str()) < 1 ) { errorCode = NIFTI_ERROR_WRONGFILETYPE; return 0; }
98 |
99 | hdr = nifti_image_read( filename.c_str(), 0 );
100 | if ( hdr==NULL ) { errorCode = NIFTI_ERROR_DATANOTLOADED; return 0; }
101 | }
102 | catch(exception& ex)
103 | {
104 | errorCode = NIFTI_ERROR_UNKNOWN;
105 | return 0;
106 | }
107 |
108 | // correct the "dim" field if it contains zeros
109 | for(int i=1; i<8 ;i++)
110 | if ( hdr->dim[i]==0 ) hdr->dim[i] = 1;
111 |
112 | errorCode = NIFTI_ERROR_NOERROR;
113 | if ( loadData ) return this->load();
114 | return 1;
115 | }
116 |
117 |
118 | /* MAKE a new dataset */
119 | short NIFTI::make( const int ndims, const int* dim, const float* pixdim, const short datatype )
120 | {
121 | if ( ndims<1 || ndims>7 ) return 0;
122 | if ( datatype!=DT_INT8 && datatype!=DT_UINT8 && datatype!=DT_INT16 && datatype!=DT_UINT16 && datatype!=DT_INT32 && datatype!=DT_UINT32 && datatype!=DT_FLOAT32 ) return 0;
123 |
124 | int d[8] = {0,1,1,1,1,1,1,1};
125 | float p[8] = {1,1,1,1,1,1,1,1};
126 | for(int i=0; ipixdim[i+1] = p[i+1];
134 | nifti_update_dims_from_array( hdr );
135 |
136 | try
137 | {
138 | if ( img ) img->free();
139 | img = new Array(
140 | shape(hdr->dim[1], hdr->dim[2], hdr->dim[3], hdr->dim[4], hdr->dim[5], hdr->dim[6], hdr->dim[7]),
141 | ColumnMajorArray<7>()
142 | );
143 |
144 | // cast data to FLOAT 32 (internal format)
145 | FLOAT32* outPtr = (FLOAT32*)( img->data() );
146 | FLOAT32* outPtrEnd = outPtr + hdr->nvox;
147 | switch( hdr->datatype )
148 | {
149 | case DT_INT8:
150 | {
151 | INT8* inPtr = (INT8*)(hdr->data);
152 | while( outPtr != outPtrEnd )
153 | *(outPtr++) = (FLOAT32)(*inPtr++);
154 | break;
155 | }
156 | case DT_UINT8:
157 | {
158 | UINT8* inPtr = (UINT8*)(hdr->data);
159 | while( outPtr != outPtrEnd )
160 | *(outPtr++) = (FLOAT32)(*inPtr++);
161 | break;
162 | }
163 | case DT_INT16:
164 | {
165 | INT16* inPtr = (INT16*)(hdr->data);
166 | while( outPtr != outPtrEnd )
167 | *(outPtr++) = (FLOAT32)(*inPtr++);
168 | break;
169 | }
170 | case DT_UINT16:
171 | {
172 | UINT16* inPtr = (UINT16*)(hdr->data);
173 | while( outPtr != outPtrEnd )
174 | *(outPtr++) = (FLOAT32)(*inPtr++);
175 | break;
176 | }
177 | case DT_INT32:
178 | {
179 | INT32* inPtr = (INT32*)(hdr->data);
180 | while( outPtr != outPtrEnd )
181 | *(outPtr++) = (FLOAT32)(*inPtr++);
182 | break;
183 | }
184 | case DT_UINT32:
185 | {
186 | UINT32* inPtr = (UINT32*)(hdr->data);
187 | while( outPtr != outPtrEnd )
188 | *(outPtr++) = (FLOAT32)(*inPtr++);
189 | break;
190 | }
191 | case DT_FLOAT32:
192 | {
193 | FLOAT32* inPtr = (FLOAT32*)(hdr->data);
194 | while( outPtr != outPtrEnd )
195 | *(outPtr++) = (FLOAT32)(*inPtr++);
196 | break;
197 | }
198 | default:
199 | return 0;
200 | }
201 | }
202 | catch(exception& ex)
203 | {
204 | return 0;
205 | }
206 |
207 | return (img==NULL?0:1);
208 | }
209 |
210 |
211 |
212 | /* LOAD/UNLOAD data */
213 | short NIFTI::load()
214 | {
215 | if ( errorCode>0 ) return 0;
216 | if ( nifti_image_load(hdr) < 0 ) return 0;
217 |
218 | try
219 | {
220 | if ( img ) img->free();
221 | img = new Array(
222 | shape(hdr->dim[1], hdr->dim[2], hdr->dim[3], hdr->dim[4], hdr->dim[5], hdr->dim[6], hdr->dim[7]),
223 | ColumnMajorArray<7>()
224 | );
225 |
226 | // cast data to FLOAT 32 (internal format)
227 | FLOAT32* outPtr = (FLOAT32*)( img->data() );
228 | FLOAT32* outPtrEnd = outPtr + hdr->nvox;
229 | switch( hdr->datatype )
230 | {
231 | case DT_INT8:
232 | {
233 | INT8* inPtr = (INT8*)(hdr->data);
234 | while( outPtr != outPtrEnd )
235 | *(outPtr++) = (FLOAT32)(*inPtr++);
236 | break;
237 | }
238 | case DT_UINT8:
239 | {
240 | UINT8* inPtr = (UINT8*)(hdr->data);
241 | while( outPtr != outPtrEnd )
242 | *(outPtr++) = (FLOAT32)(*inPtr++);
243 | break;
244 | }
245 | case DT_INT16:
246 | {
247 | INT16* inPtr = (INT16*)(hdr->data);
248 | while( outPtr != outPtrEnd )
249 | *(outPtr++) = (FLOAT32)(*inPtr++);
250 | break;
251 | }
252 | case DT_UINT16:
253 | {
254 | UINT16* inPtr = (UINT16*)(hdr->data);
255 | while( outPtr != outPtrEnd )
256 | *(outPtr++) = (FLOAT32)(*inPtr++);
257 | break;
258 | }
259 | case DT_INT32:
260 | {
261 | INT32* inPtr = (INT32*)(hdr->data);
262 | while( outPtr != outPtrEnd )
263 | *(outPtr++) = (FLOAT32)(*inPtr++);
264 | break;
265 | }
266 | case DT_UINT32:
267 | {
268 | UINT32* inPtr = (UINT32*)(hdr->data);
269 | while( outPtr != outPtrEnd )
270 | *(outPtr++) = (FLOAT32)(*inPtr++);
271 | break;
272 | }
273 | case DT_FLOAT32:
274 | {
275 | FLOAT32* inPtr = (FLOAT32*)(hdr->data);
276 | while( outPtr != outPtrEnd )
277 | *(outPtr++) = (FLOAT32)(*inPtr++);
278 | break;
279 | }
280 | default:
281 | return 0;
282 | }
283 | }
284 | catch(exception& ex)
285 | {
286 | return 0;
287 | }
288 |
289 | return (img==NULL?0:1);
290 | }
291 |
292 |
293 | /* Unload the data but keep the metadata */
294 | short NIFTI::unload( )
295 | {
296 | nifti_image_unload( hdr );
297 | if ( img ) img->free();
298 | return 1;
299 | }
300 |
301 |
302 | /* SAVE data */
303 | short NIFTI::save( string NEW_filename )
304 | {
305 | if ( !nifti_validfilename( NEW_filename.c_str() ) ) return 0;
306 | nifti_set_filenames( hdr, NEW_filename.c_str(), 0, hdr->byteorder );
307 |
308 | try
309 | {
310 | // cast data from FLOAT 32 (internal format)
311 | FLOAT32* inPtr = (FLOAT32*)( img->data() );
312 | FLOAT32* inPtrEnd = inPtr + hdr->nvox;
313 | switch( hdr->datatype )
314 | {
315 | case DT_INT8:
316 | {
317 | INT8* outPtr = (INT8*)(hdr->data);
318 | while( inPtr != inPtrEnd )
319 | *(outPtr++) = (INT8)(*inPtr++);
320 | break;
321 | }
322 | case DT_UINT8:
323 | {
324 | UINT8* outPtr = (UINT8*)(hdr->data);
325 | while( inPtr != inPtrEnd )
326 | *(outPtr++) = (UINT8)(*inPtr++);
327 | break;
328 | }
329 | case DT_INT16:
330 | {
331 | INT16* outPtr = (INT16*)(hdr->data);
332 | while( inPtr != inPtrEnd )
333 | *(outPtr++) = (INT16)(*inPtr++);
334 | break;
335 | }
336 | case DT_UINT16:
337 | {
338 | UINT16* outPtr = (UINT16*)(hdr->data);
339 | while( inPtr != inPtrEnd )
340 | *(outPtr++) = (UINT16)(*inPtr++);
341 | break;
342 | }
343 | case DT_INT32:
344 | {
345 | INT32* outPtr = (INT32*)(hdr->data);
346 | while( inPtr != inPtrEnd )
347 | *(outPtr++) = (INT32)(*inPtr++);
348 | break;
349 | }
350 | case DT_UINT32:
351 | {
352 | UINT32* outPtr = (UINT32*)(hdr->data);
353 | while( inPtr != inPtrEnd )
354 | *(outPtr++) = (UINT32)(*inPtr++);
355 | break;
356 | }
357 | case DT_FLOAT32:
358 | {
359 | FLOAT32* outPtr = (FLOAT32*)(hdr->data);
360 | while( inPtr != inPtrEnd )
361 | *(outPtr++) = (FLOAT32)( *inPtr++);
362 | break;
363 | }
364 | default:
365 | return 0;
366 | }
367 | }
368 | catch(exception& ex)
369 | {
370 | return 0;
371 | }
372 |
373 | nifti_image_write( hdr );
374 | return 1;
375 | }
376 |
377 |
378 | void NIFTI::copyHeader( const nifti_image* src )
379 | {
380 | if ( !src ) return;
381 |
382 | void* tmp = hdr->data;
383 | hdr = nifti_copy_nim_info( src );
384 | hdr->data = tmp;
385 | }
386 |
387 | #endif
388 |
--------------------------------------------------------------------------------
/extras/include/TrackVis.h:
--------------------------------------------------------------------------------
1 | #ifndef __TRACKVIS_H__
2 | #define __TRACKVIS_H__
3 |
4 | #include
5 | #include
6 |
7 |
8 | #define TRACKVIS_SAVE_ALL 0
9 | #define TRACKVIS_SAVE_HALF 1
10 | #define TRACKVIS_SAVE_UNIQUE 2
11 |
12 | #define TRACKVIS_VOXEL_OFFSET 0
13 |
14 |
15 |
16 | // Structure to hold metadata of a TrackVis file
17 | // ---------------------------------------------
18 | struct TrackVis_header
19 | {
20 | char id_string[6];
21 | short int dim[3];
22 | float voxel_size[3];
23 | float origin[3];
24 | short int n_scalars;
25 | char scalar_name[10][20];
26 | short int n_properties;
27 | char property_name[10][20];
28 | char reserved[508];
29 | char voxel_order[4];
30 | char pad2[4];
31 | float image_orientation_patient[6];
32 | char pad1[2];
33 | unsigned char invert_x;
34 | unsigned char invert_y;
35 | unsigned char invert_z;
36 | unsigned char swap_xy;
37 | unsigned char swap_yz;
38 | unsigned char swap_zx;
39 | int n_count;
40 | int version;
41 | int hdr_size;
42 | };
43 |
44 |
45 |
46 | // Class to handle TrackVis files.
47 | // -------------------------------
48 | class TrackVis
49 | {
50 | private:
51 | string filename;
52 | FILE* fp;
53 | int maxSteps; // [TODO] should be related to the variable defined for fiber-tracking
54 |
55 | public:
56 | TrackVis_header hdr;
57 |
58 | short create( string filename, short int* dim, float* pixdim );
59 | short open( string filename );
60 | short read( blitz::Array* fiber, blitz::Array* scalars=NULL, blitz::Array* properties=NULL );
61 | short append( blitz::Array* fiber, int numPoints, short saveMethod=TRACKVIS_SAVE_UNIQUE );
62 | void writeHdr();
63 | void updateTotal( int totFibers );
64 | void close();
65 | FILE* getFilePtr();
66 |
67 | void mm2vox( blitz::Array P_mm, blitz::Array* P );
68 |
69 | TrackVis();
70 | ~TrackVis();
71 | };
72 |
73 |
74 | TrackVis::TrackVis() { filename = ""; fp = NULL; maxSteps = 20000; }
75 | TrackVis::~TrackVis() { if (fp) fclose( fp ); }
76 |
77 |
78 | // Create a TrackVis file and store standard metadata. The file is ready to append fibers.
79 | // ---------------------------------------------------------------------------------------
80 | short TrackVis::create( string filename, short int* dim, float* pixdim )
81 | {
82 | // prepare the header
83 | for(int i=0; i<3 ;i++)
84 | {
85 | if ( dim[i]<=0 || pixdim[i]<=0 ) return 0;
86 | hdr.dim[i] = dim[i];
87 | hdr.voxel_size[i] = pixdim[i];
88 | hdr.origin[i] = 0;
89 | }
90 | hdr.n_scalars = 0;
91 | hdr.n_properties = 0;
92 | sprintf(hdr.voxel_order,"LPS");
93 | sprintf(hdr.pad2,"RAS");
94 | hdr.image_orientation_patient[0] = 1.0;
95 | hdr.image_orientation_patient[1] = 0.0;
96 | hdr.image_orientation_patient[2] = 0.0;
97 | hdr.image_orientation_patient[3] = 0.0;
98 | hdr.image_orientation_patient[4] = 1.0;
99 | hdr.image_orientation_patient[5] = 0.0;
100 | hdr.pad1[0] = 0;
101 | hdr.pad1[1] = 0;
102 | hdr.invert_x = 0;
103 | hdr.invert_y = 0;
104 | hdr.invert_z = 0;
105 | hdr.swap_xy = 0;
106 | hdr.swap_yz = 0;
107 | hdr.swap_zx = 0;
108 | hdr.n_count = 0;
109 | hdr.version = 1;
110 | hdr.hdr_size = 1000;
111 |
112 | // write the header to the file
113 | fp = fopen(filename.c_str(),"w+b");
114 | if (fp == NULL) { printf("\n\n[ERROR] Unable to create file '%s'\n\n",filename.c_str()); return 0; }
115 | sprintf(hdr.id_string,"TRACK");
116 | fwrite((char*)&hdr, 1, 1000, fp);
117 |
118 | this->filename = filename;
119 |
120 | return 1;
121 | }
122 |
123 |
124 |
125 | // Open an existing TrackVis file and read metadata information.
126 | // The file pointer is positiond at the beginning of fibers data
127 | // -------------------------------------------------------------
128 | short TrackVis::open( string filename )
129 | {
130 | fp = fopen(filename.c_str(),"r+b");
131 | if (fp == NULL) { printf("\n\n[ERROR] Unable to open file '%s'\n\n",filename.c_str()); return 0; }
132 | this->filename = filename;
133 |
134 | return fread((char*)(&hdr), 1, 1000, fp);
135 | }
136 |
137 |
138 |
139 | // Append a fiber to the file
140 | // --------------------------
141 | short TrackVis::append( blitz::Array* fiber, int numPoints, short saveMethod )
142 | {
143 | unsigned int numSaved, pos = 0;
144 | float tmp[3*maxSteps];
145 |
146 | if ( numPoints > maxSteps )
147 | {
148 | cerr <0 ;i-=2)
158 | {
159 | tmp[pos++] = ( (*fiber)(0,i)+TRACKVIS_VOXEL_OFFSET );
160 | tmp[pos++] = ( (*fiber)(1,i)+TRACKVIS_VOXEL_OFFSET );
161 | tmp[pos++] = ( (*fiber)(2,i)+TRACKVIS_VOXEL_OFFSET );
162 | }
163 | tmp[pos++] = ( (*fiber)(0,0)+TRACKVIS_VOXEL_OFFSET );
164 | tmp[pos++] = ( (*fiber)(1,0)+TRACKVIS_VOXEL_OFFSET );
165 | tmp[pos++] = ( (*fiber)(2,0)+TRACKVIS_VOXEL_OFFSET );
166 | }
167 | else if ( saveMethod == TRACKVIS_SAVE_UNIQUE )
168 | {
169 | // Save UNIQUE points (discard consecutive points inside the same voxel)
170 | numSaved = 0;
171 | int oldX = 0, oldY = 0, oldZ = 0;
172 | int X = 0, Y = 0, Z = 0;
173 | for(int i=0; i* fiber, blitz::Array* scalars, blitz::Array* properties )
220 | {
221 | int numPoints;
222 | fread((char*)&numPoints, 1, 4, fp);
223 |
224 | if ( numPoints >= maxSteps || numPoints <= 0 )
225 | {
226 | cerr <resize( 3, numPoints );
231 | if ( scalars!=NULL )
232 | scalars->resize( numPoints, hdr.n_scalars );
233 | if ( properties!=NULL )
234 | properties->resize( 1, hdr.n_properties );
235 |
236 |
237 | float tmp[3];
238 | for(int i=0; i P_mm, blitz::Array* P )
292 | {
293 | (*P)(0) = round( P_mm(0) / hdr.voxel_size[0] - TRACKVIS_VOXEL_OFFSET );
294 | (*P)(1) = round( P_mm(1) / hdr.voxel_size[1] - TRACKVIS_VOXEL_OFFSET );
295 | (*P)(2) = round( P_mm(2) / hdr.voxel_size[2] - TRACKVIS_VOXEL_OFFSET );
296 | if ( (*P)(0)<0 ) (*P)(0) = 0;
297 | if ( (*P)(1)<0 ) (*P)(1) = 0;
298 | if ( (*P)(2)<0 ) (*P)(2) = 0;
299 | if( (*P)(0) > hdr.dim[0]-1 ) (*P)(0) = hdr.dim[0]-1;
300 | if( (*P)(1) > hdr.dim[1]-1 ) (*P)(1) = hdr.dim[1]-1;
301 | if( (*P)(2) > hdr.dim[2]-1 ) (*P)(2) = hdr.dim[2]-1;
302 | }
303 |
304 |
305 | // Return the file pointer
306 | // -----------------------
307 | FILE* TrackVis::getFilePtr()
308 | {
309 | return fp;
310 | }
311 |
312 | #endif
313 |
--------------------------------------------------------------------------------
/extras/include/VECTOR.h:
--------------------------------------------------------------------------------
1 | #ifndef __VECTOR_H__
2 | #define __VECTOR_H__
3 |
4 | #include // [CHECK]
5 |
6 | template
7 | class VECTOR
8 | {
9 | public:
10 | T x, y, z;
11 |
12 | void Set( T _x, T _y, T _z );
13 | float norm();
14 | void Normalize();
15 | void Multiply( T k );
16 | void VectorProduct( const VECTOR & v1, const VECTOR & v2 );
17 | T ScalarProduct( const VECTOR & v );
18 | float DistanceTo( const VECTOR & v );
19 |
20 | void operator=( const VECTOR & v );
21 |
22 | VECTOR();
23 | VECTOR( T _x, T _y, T _z );
24 | };
25 |
26 |
27 | template
28 | VECTOR::VECTOR()
29 | { x = y = z = 0; }
30 |
31 |
32 | template
33 | VECTOR::VECTOR( T _x, T _y, T _z )
34 | { x = _x; y = _y; z = _z; }
35 |
36 |
37 | template
38 | void VECTOR::Set( T _x, T _y, T _z )
39 | { x = _x; y = _y; z = _z; }
40 |
41 |
42 | template
43 | float VECTOR::norm()
44 | {
45 | return sqrt(x*x+y*y+z*z);
46 | }
47 |
48 |
49 | template
50 | void VECTOR::Normalize()
51 | {
52 | float len = sqrt(x*x+y*y+z*z);
53 | if (len==0) return;
54 | x = x/len;
55 | y = y/len;
56 | z = z/len;
57 | }
58 |
59 |
60 | template
61 | void VECTOR::Multiply( T k )
62 | {
63 | x *= k;
64 | y *= k;
65 | z *= k;
66 | }
67 |
68 |
69 | template
70 | T VECTOR::ScalarProduct( const VECTOR & v )
71 | {
72 | return x*v.x + y*v.y + z*v.z;
73 | }
74 |
75 |
76 | template
77 | void VECTOR::VectorProduct( const VECTOR & v1, const VECTOR & v2 )
78 | {
79 | x = v1.y*v2.z - v2.y*v1.z;
80 | y = v1.z*v2.x - v2.z*v1.x;
81 | z = v1.x*v2.y - v2.x*v1.y;
82 | }
83 |
84 | template
85 | float VECTOR::DistanceTo( const VECTOR & v )
86 | {
87 | return sqrt( pow(x-v.x,2) + pow(y-v.y,2) + pow(z-v.z,2) );
88 | }
89 |
90 | template
91 | void VECTOR::operator=( const VECTOR & v )
92 | {
93 | x = v.x;
94 | y = v.y;
95 | z = v.z;
96 | }
97 |
98 |
99 | typedef VECTOR POINT;
100 |
101 |
102 | #endif
103 |
--------------------------------------------------------------------------------
/extras/include/tclap/ArgException.h:
--------------------------------------------------------------------------------
1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
2 |
3 | /******************************************************************************
4 | *
5 | * file: ArgException.h
6 | *
7 | * Copyright (c) 2003, Michael E. Smoot .
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 |
24 | #ifndef TCLAP_ARG_EXCEPTION_H
25 | #define TCLAP_ARG_EXCEPTION_H
26 |
27 | #include
28 | #include
29 |
30 | namespace TCLAP {
31 |
32 | /**
33 | * A simple class that defines and argument exception. Should be caught
34 | * whenever a CmdLine is created and parsed.
35 | */
36 | class ArgException : public std::exception
37 | {
38 | public:
39 |
40 | /**
41 | * Constructor.
42 | * \param text - The text of the exception.
43 | * \param id - The text identifying the argument source.
44 | * \param td - Text describing the type of ArgException it is.
45 | * of the exception.
46 | */
47 | ArgException( const std::string& text = "undefined exception",
48 | const std::string& id = "undefined",
49 | const std::string& td = "Generic ArgException")
50 | : std::exception(),
51 | _errorText(text),
52 | _argId( id ),
53 | _typeDescription(td)
54 | { }
55 |
56 | /**
57 | * Destructor.
58 | */
59 | virtual ~ArgException() throw() { }
60 |
61 | /**
62 | * Returns the error text.
63 | */
64 | std::string error() const { return ( _errorText ); }
65 |
66 | /**
67 | * Returns the argument id.
68 | */
69 | std::string argId() const
70 | {
71 | if ( _argId == "undefined" )
72 | return " ";
73 | else
74 | return ( "Argument: " + _argId );
75 | }
76 |
77 | /**
78 | * Returns the arg id and error text.
79 | */
80 | const char* what() const throw()
81 | {
82 | static std::string ex;
83 | ex = _argId + " -- " + _errorText;
84 | return ex.c_str();
85 | }
86 |
87 | /**
88 | * Returns the type of the exception. Used to explain and distinguish
89 | * between different child exceptions.
90 | */
91 | std::string typeDescription() const
92 | {
93 | return _typeDescription;
94 | }
95 |
96 |
97 | private:
98 |
99 | /**
100 | * The text of the exception message.
101 | */
102 | std::string _errorText;
103 |
104 | /**
105 | * The argument related to this exception.
106 | */
107 | std::string _argId;
108 |
109 | /**
110 | * Describes the type of the exception. Used to distinguish
111 | * between different child exceptions.
112 | */
113 | std::string _typeDescription;
114 |
115 | };
116 |
117 | /**
118 | * Thrown from within the child Arg classes when it fails to properly
119 | * parse the argument it has been passed.
120 | */
121 | class ArgParseException : public ArgException
122 | {
123 | public:
124 | /**
125 | * Constructor.
126 | * \param text - The text of the exception.
127 | * \param id - The text identifying the argument source
128 | * of the exception.
129 | */
130 | ArgParseException( const std::string& text = "undefined exception",
131 | const std::string& id = "undefined" )
132 | : ArgException( text,
133 | id,
134 | std::string( "Exception found while parsing " ) +
135 | std::string( "the value the Arg has been passed." ))
136 | { }
137 | };
138 |
139 | /**
140 | * Thrown from CmdLine when the arguments on the command line are not
141 | * properly specified, e.g. too many arguments, required argument missing, etc.
142 | */
143 | class CmdLineParseException : public ArgException
144 | {
145 | public:
146 | /**
147 | * Constructor.
148 | * \param text - The text of the exception.
149 | * \param id - The text identifying the argument source
150 | * of the exception.
151 | */
152 | CmdLineParseException( const std::string& text = "undefined exception",
153 | const std::string& id = "undefined" )
154 | : ArgException( text,
155 | id,
156 | std::string( "Exception found when the values ") +
157 | std::string( "on the command line do not meet ") +
158 | std::string( "the requirements of the defined ") +
159 | std::string( "Args." ))
160 | { }
161 | };
162 |
163 | /**
164 | * Thrown from Arg and CmdLine when an Arg is improperly specified, e.g.
165 | * same flag as another Arg, same name, etc.
166 | */
167 | class SpecificationException : public ArgException
168 | {
169 | public:
170 | /**
171 | * Constructor.
172 | * \param text - The text of the exception.
173 | * \param id - The text identifying the argument source
174 | * of the exception.
175 | */
176 | SpecificationException( const std::string& text = "undefined exception",
177 | const std::string& id = "undefined" )
178 | : ArgException( text,
179 | id,
180 | std::string("Exception found when an Arg object ")+
181 | std::string("is improperly defined by the ") +
182 | std::string("developer." ))
183 | { }
184 |
185 | };
186 |
187 | class ExitException {
188 | public:
189 | ExitException(int estat) : _estat(estat) {}
190 |
191 | int getExitStatus() const { return _estat; }
192 |
193 | private:
194 | int _estat;
195 | };
196 |
197 | } // namespace TCLAP
198 |
199 | #endif
200 |
201 |
--------------------------------------------------------------------------------
/extras/include/tclap/ArgTraits.h:
--------------------------------------------------------------------------------
1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
2 |
3 | /******************************************************************************
4 | *
5 | * file: ArgTraits.h
6 | *
7 | * Copyright (c) 2007, Daniel Aarno, Michael E. Smoot .
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 | // This is an internal tclap file, you should probably not have to
24 | // include this directly
25 |
26 | #ifndef TCLAP_ARGTRAITS_H
27 | #define TCLAP_ARGTRAITS_H
28 |
29 | namespace TCLAP {
30 |
31 | // We use two empty structs to get compile type specialization
32 | // function to work
33 |
34 | /**
35 | * A value like argument value type is a value that can be set using
36 | * operator>>. This is the default value type.
37 | */
38 | struct ValueLike {
39 | typedef ValueLike ValueCategory;
40 | virtual ~ValueLike() {}
41 | };
42 |
43 | /**
44 | * A string like argument value type is a value that can be set using
45 | * operator=(string). Usefull if the value type contains spaces which
46 | * will be broken up into individual tokens by operator>>.
47 | */
48 | struct StringLike {
49 | virtual ~StringLike() {}
50 | };
51 |
52 | /**
53 | * A class can inherit from this object to make it have string like
54 | * traits. This is a compile time thing and does not add any overhead
55 | * to the inherenting class.
56 | */
57 | struct StringLikeTrait {
58 | typedef StringLike ValueCategory;
59 | virtual ~StringLikeTrait() {}
60 | };
61 |
62 | /**
63 | * A class can inherit from this object to make it have value like
64 | * traits. This is a compile time thing and does not add any overhead
65 | * to the inherenting class.
66 | */
67 | struct ValueLikeTrait {
68 | typedef ValueLike ValueCategory;
69 | virtual ~ValueLikeTrait() {}
70 | };
71 |
72 | /**
73 | * Arg traits are used to get compile type specialization when parsing
74 | * argument values. Using an ArgTraits you can specify the way that
75 | * values gets assigned to any particular type during parsing. The two
76 | * supported types are StringLike and ValueLike.
77 | */
78 | template
79 | struct ArgTraits {
80 | typedef typename T::ValueCategory ValueCategory;
81 | virtual ~ArgTraits() {}
82 | //typedef ValueLike ValueCategory;
83 | };
84 |
85 | #endif
86 |
87 | } // namespace
88 |
--------------------------------------------------------------------------------
/extras/include/tclap/CmdLineInterface.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | *
4 | * file: CmdLineInterface.h
5 | *
6 | * Copyright (c) 2003, Michael E. Smoot .
7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 | #ifndef TCLAP_COMMANDLINE_INTERFACE_H
24 | #define TCLAP_COMMANDLINE_INTERFACE_H
25 |
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 |
32 |
33 | namespace TCLAP {
34 |
35 | class Arg;
36 | class CmdLineOutput;
37 | class XorHandler;
38 |
39 | /**
40 | * The base class that manages the command line definition and passes
41 | * along the parsing to the appropriate Arg classes.
42 | */
43 | class CmdLineInterface
44 | {
45 | public:
46 |
47 | /**
48 | * Destructor
49 | */
50 | virtual ~CmdLineInterface() {}
51 |
52 | /**
53 | * Adds an argument to the list of arguments to be parsed.
54 | * \param a - Argument to be added.
55 | */
56 | virtual void add( Arg& a )=0;
57 |
58 | /**
59 | * An alternative add. Functionally identical.
60 | * \param a - Argument to be added.
61 | */
62 | virtual void add( Arg* a )=0;
63 |
64 | /**
65 | * Add two Args that will be xor'd.
66 | * If this method is used, add does
67 | * not need to be called.
68 | * \param a - Argument to be added and xor'd.
69 | * \param b - Argument to be added and xor'd.
70 | */
71 | virtual void xorAdd( Arg& a, Arg& b )=0;
72 |
73 | /**
74 | * Add a list of Args that will be xor'd. If this method is used,
75 | * add does not need to be called.
76 | * \param xors - List of Args to be added and xor'd.
77 | */
78 | virtual void xorAdd( std::vector& xors )=0;
79 |
80 | /**
81 | * Parses the command line.
82 | * \param argc - Number of arguments.
83 | * \param argv - Array of arguments.
84 | */
85 | virtual void parse(int argc, const char * const * argv)=0;
86 |
87 | /**
88 | * Parses the command line.
89 | * \param args - A vector of strings representing the args.
90 | * args[0] is still the program name.
91 | */
92 | void parse(std::vector& args);
93 |
94 | /**
95 | * Returns the CmdLineOutput object.
96 | */
97 | virtual CmdLineOutput* getOutput()=0;
98 |
99 | /**
100 | * \param co - CmdLineOutput object that we want to use instead.
101 | */
102 | virtual void setOutput(CmdLineOutput* co)=0;
103 |
104 | /**
105 | * Returns the version string.
106 | */
107 | virtual std::string& getVersion()=0;
108 |
109 | /**
110 | * Returns the program name string.
111 | */
112 | virtual std::string& getProgramName()=0;
113 |
114 | /**
115 | * Returns the argList.
116 | */
117 | virtual std::list& getArgList()=0;
118 |
119 | /**
120 | * Returns the XorHandler.
121 | */
122 | virtual XorHandler& getXorHandler()=0;
123 |
124 | /**
125 | * Returns the delimiter string.
126 | */
127 | virtual char getDelimiter()=0;
128 |
129 | /**
130 | * Returns the message string.
131 | */
132 | virtual std::string& getMessage()=0;
133 |
134 | /**
135 | * Indicates whether or not the help and version switches were created
136 | * automatically.
137 | */
138 | virtual bool hasHelpAndVersion()=0;
139 |
140 | /**
141 | * Resets the instance as if it had just been constructed so that the
142 | * instance can be reused.
143 | */
144 | virtual void reset()=0;
145 | };
146 |
147 | } //namespace
148 |
149 |
150 | #endif
151 |
--------------------------------------------------------------------------------
/extras/include/tclap/CmdLineOutput.h:
--------------------------------------------------------------------------------
1 |
2 |
3 | /******************************************************************************
4 | *
5 | * file: CmdLineOutput.h
6 | *
7 | * Copyright (c) 2004, Michael E. Smoot
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 | #ifndef TCLAP_CMDLINEOUTPUT_H
24 | #define TCLAP_CMDLINEOUTPUT_H
25 |
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 |
33 | namespace TCLAP {
34 |
35 | class CmdLineInterface;
36 | class ArgException;
37 |
38 | /**
39 | * The interface that any output object must implement.
40 | */
41 | class CmdLineOutput
42 | {
43 |
44 | public:
45 |
46 | /**
47 | * Virtual destructor.
48 | */
49 | virtual ~CmdLineOutput() {}
50 |
51 | /**
52 | * Generates some sort of output for the USAGE.
53 | * \param c - The CmdLine object the output is generated for.
54 | */
55 | virtual void usage(CmdLineInterface& c)=0;
56 |
57 | /**
58 | * Generates some sort of output for the version.
59 | * \param c - The CmdLine object the output is generated for.
60 | */
61 | virtual void version(CmdLineInterface& c)=0;
62 |
63 | /**
64 | * Generates some sort of output for a failure.
65 | * \param c - The CmdLine object the output is generated for.
66 | * \param e - The ArgException that caused the failure.
67 | */
68 | virtual void failure( CmdLineInterface& c,
69 | ArgException& e )=0;
70 |
71 | };
72 |
73 | } //namespace TCLAP
74 | #endif
75 |
--------------------------------------------------------------------------------
/extras/include/tclap/Constraint.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | *
4 | * file: Constraint.h
5 | *
6 | * Copyright (c) 2005, Michael E. Smoot
7 | * All rights reverved.
8 | *
9 | * See the file COPYING in the top directory of this distribution for
10 | * more information.
11 | *
12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
18 | * DEALINGS IN THE SOFTWARE.
19 | *
20 | *****************************************************************************/
21 |
22 | #ifndef TCLAP_CONSTRAINT_H
23 | #define TCLAP_CONSTRAINT_H
24 |
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 |
32 | namespace TCLAP {
33 |
34 | /**
35 | * The interface that defines the interaction between the Arg and Constraint.
36 | */
37 | template
38 | class Constraint
39 | {
40 |
41 | public:
42 | /**
43 | * Returns a description of the Constraint.
44 | */
45 | virtual std::string description() const =0;
46 |
47 | /**
48 | * Returns the short ID for the Constraint.
49 | */
50 | virtual std::string shortID() const =0;
51 |
52 | /**
53 | * The method used to verify that the value parsed from the command
54 | * line meets the constraint.
55 | * \param value - The value that will be checked.
56 | */
57 | virtual bool check(const T& value) const =0;
58 |
59 | /**
60 | * Destructor.
61 | * Silences warnings about Constraint being a base class with virtual
62 | * functions but without a virtual destructor.
63 | */
64 | virtual ~Constraint() { ; }
65 | };
66 |
67 | } //namespace TCLAP
68 | #endif
69 |
--------------------------------------------------------------------------------
/extras/include/tclap/DocBookOutput.h:
--------------------------------------------------------------------------------
1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
2 |
3 | /******************************************************************************
4 | *
5 | * file: DocBookOutput.h
6 | *
7 | * Copyright (c) 2004, Michael E. Smoot
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 | #ifndef TCLAP_DOCBOOKOUTPUT_H
24 | #define TCLAP_DOCBOOKOUTPUT_H
25 |
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 |
32 | #include
33 | #include
34 | #include
35 | #include
36 |
37 | namespace TCLAP {
38 |
39 | /**
40 | * A class that generates DocBook output for usage() method for the
41 | * given CmdLine and its Args.
42 | */
43 | class DocBookOutput : public CmdLineOutput
44 | {
45 |
46 | public:
47 |
48 | /**
49 | * Prints the usage to stdout. Can be overridden to
50 | * produce alternative behavior.
51 | * \param c - The CmdLine object the output is generated for.
52 | */
53 | virtual void usage(CmdLineInterface& c);
54 |
55 | /**
56 | * Prints the version to stdout. Can be overridden
57 | * to produce alternative behavior.
58 | * \param c - The CmdLine object the output is generated for.
59 | */
60 | virtual void version(CmdLineInterface& c);
61 |
62 | /**
63 | * Prints (to stderr) an error message, short usage
64 | * Can be overridden to produce alternative behavior.
65 | * \param c - The CmdLine object the output is generated for.
66 | * \param e - The ArgException that caused the failure.
67 | */
68 | virtual void failure(CmdLineInterface& c,
69 | ArgException& e );
70 |
71 | protected:
72 |
73 | /**
74 | * Substitutes the char r for string x in string s.
75 | * \param s - The string to operate on.
76 | * \param r - The char to replace.
77 | * \param x - What to replace r with.
78 | */
79 | void substituteSpecialChars( std::string& s, char r, std::string& x );
80 | void removeChar( std::string& s, char r);
81 | void basename( std::string& s );
82 |
83 | void printShortArg(Arg* it);
84 | void printLongArg(Arg* it);
85 |
86 | char theDelimiter;
87 | };
88 |
89 |
90 | inline void DocBookOutput::version(CmdLineInterface& _cmd)
91 | {
92 | std::cout << _cmd.getVersion() << std::endl;
93 | }
94 |
95 | inline void DocBookOutput::usage(CmdLineInterface& _cmd )
96 | {
97 | std::list argList = _cmd.getArgList();
98 | std::string progName = _cmd.getProgramName();
99 | std::string xversion = _cmd.getVersion();
100 | theDelimiter = _cmd.getDelimiter();
101 | XorHandler xorHandler = _cmd.getXorHandler();
102 | std::vector< std::vector > xorList = xorHandler.getXorList();
103 | basename(progName);
104 |
105 | std::cout << "" << std::endl;
106 | std::cout << "" << std::endl << std::endl;
108 |
109 | std::cout << "" << std::endl;
110 |
111 | std::cout << "" << std::endl;
112 | std::cout << "" << progName << "" << std::endl;
113 | std::cout << "1" << std::endl;
114 | std::cout << "" << std::endl;
115 |
116 | std::cout << "" << std::endl;
117 | std::cout << "" << progName << "" << std::endl;
118 | std::cout << "" << _cmd.getMessage() << "" << std::endl;
119 | std::cout << "" << std::endl;
120 |
121 | std::cout << "" << std::endl;
122 | std::cout << "" << std::endl;
123 |
124 | std::cout << "" << progName << "" << std::endl;
125 |
126 | // xor
127 | for ( int i = 0; (unsigned int)i < xorList.size(); i++ )
128 | {
129 | std::cout << "" << std::endl;
130 | for ( ArgVectorIterator it = xorList[i].begin();
131 | it != xorList[i].end(); it++ )
132 | printShortArg((*it));
133 |
134 | std::cout << "" << std::endl;
135 | }
136 |
137 | // rest of args
138 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
139 | if ( !xorHandler.contains( (*it) ) )
140 | printShortArg((*it));
141 |
142 | std::cout << "" << std::endl;
143 | std::cout << "" << std::endl;
144 |
145 | std::cout << "" << std::endl;
146 | std::cout << "Description" << std::endl;
147 | std::cout << "" << std::endl;
148 | std::cout << _cmd.getMessage() << std::endl;
149 | std::cout << "" << std::endl;
150 | std::cout << "" << std::endl;
151 |
152 | std::cout << "" << std::endl;
153 | std::cout << "Options" << std::endl;
154 |
155 | std::cout << "" << std::endl;
156 |
157 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
158 | printLongArg((*it));
159 |
160 | std::cout << "" << std::endl;
161 | std::cout << "" << std::endl;
162 |
163 | std::cout << "" << std::endl;
164 | std::cout << "Version" << std::endl;
165 | std::cout << "" << std::endl;
166 | std::cout << xversion << std::endl;
167 | std::cout << "" << std::endl;
168 | std::cout << "" << std::endl;
169 |
170 | std::cout << "" << std::endl;
171 |
172 | }
173 |
174 | inline void DocBookOutput::failure( CmdLineInterface& _cmd,
175 | ArgException& e )
176 | {
177 | static_cast(_cmd); // unused
178 | std::cout << e.what() << std::endl;
179 | throw ExitException(1);
180 | }
181 |
182 | inline void DocBookOutput::substituteSpecialChars( std::string& s,
183 | char r,
184 | std::string& x )
185 | {
186 | size_t p;
187 | while ( (p = s.find_first_of(r)) != std::string::npos )
188 | {
189 | s.erase(p,1);
190 | s.insert(p,x);
191 | }
192 | }
193 |
194 | inline void DocBookOutput::removeChar( std::string& s, char r)
195 | {
196 | size_t p;
197 | while ( (p = s.find_first_of(r)) != std::string::npos )
198 | {
199 | s.erase(p,1);
200 | }
201 | }
202 |
203 | inline void DocBookOutput::basename( std::string& s )
204 | {
205 | size_t p = s.find_last_of('/');
206 | if ( p != std::string::npos )
207 | {
208 | s.erase(0, p + 1);
209 | }
210 | }
211 |
212 | inline void DocBookOutput::printShortArg(Arg* a)
213 | {
214 | std::string lt = "<";
215 | std::string gt = ">";
216 |
217 | std::string id = a->shortID();
218 | substituteSpecialChars(id,'<',lt);
219 | substituteSpecialChars(id,'>',gt);
220 | removeChar(id,'[');
221 | removeChar(id,']');
222 |
223 | std::string choice = "opt";
224 | if ( a->isRequired() )
225 | choice = "plain";
226 |
227 | std::cout << "acceptsMultipleValues() )
229 | std::cout << " rep='repeat'";
230 |
231 |
232 | std::cout << '>';
233 | if ( !a->getFlag().empty() )
234 | std::cout << a->flagStartChar() << a->getFlag();
235 | else
236 | std::cout << a->nameStartString() << a->getName();
237 | if ( a->isValueRequired() )
238 | {
239 | std::string arg = a->shortID();
240 | removeChar(arg,'[');
241 | removeChar(arg,']');
242 | removeChar(arg,'<');
243 | removeChar(arg,'>');
244 | arg.erase(0, arg.find_last_of(theDelimiter) + 1);
245 | std::cout << theDelimiter;
246 | std::cout << "" << arg << "";
247 | }
248 | std::cout << "" << std::endl;
249 |
250 | }
251 |
252 | inline void DocBookOutput::printLongArg(Arg* a)
253 | {
254 | std::string lt = "<";
255 | std::string gt = ">";
256 |
257 | std::string desc = a->getDescription();
258 | substituteSpecialChars(desc,'<',lt);
259 | substituteSpecialChars(desc,'>',gt);
260 |
261 | std::cout << "" << std::endl;
262 |
263 | if ( !a->getFlag().empty() )
264 | {
265 | std::cout << "" << std::endl;
266 | std::cout << "" << std::endl;
269 | std::cout << "" << std::endl;
270 | }
271 |
272 | std::cout << "" << std::endl;
273 | std::cout << "" << std::endl;
287 | std::cout << "" << std::endl;
288 |
289 | std::cout << "" << std::endl;
290 | std::cout << "" << std::endl;
291 | std::cout << desc << std::endl;
292 | std::cout << "" << std::endl;
293 | std::cout << "" << std::endl;
294 |
295 | std::cout << "" << std::endl;
296 | }
297 |
298 | } //namespace TCLAP
299 | #endif
300 |
--------------------------------------------------------------------------------
/extras/include/tclap/HelpVisitor.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | *
4 | * file: HelpVisitor.h
5 | *
6 | * Copyright (c) 2003, Michael E. Smoot .
7 | * All rights reverved.
8 | *
9 | * See the file COPYING in the top directory of this distribution for
10 | * more information.
11 | *
12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
18 | * DEALINGS IN THE SOFTWARE.
19 | *
20 | *****************************************************************************/
21 |
22 | #ifndef TCLAP_HELP_VISITOR_H
23 | #define TCLAP_HELP_VISITOR_H
24 |
25 | #include
26 | #include
27 | #include
28 |
29 | namespace TCLAP {
30 |
31 | /**
32 | * A Visitor object that calls the usage method of the given CmdLineOutput
33 | * object for the specified CmdLine object.
34 | */
35 | class HelpVisitor: public Visitor
36 | {
37 | private:
38 | /**
39 | * Prevent accidental copying.
40 | */
41 | HelpVisitor(const HelpVisitor& rhs);
42 | HelpVisitor& operator=(const HelpVisitor& rhs);
43 |
44 | protected:
45 |
46 | /**
47 | * The CmdLine the output will be generated for.
48 | */
49 | CmdLineInterface* _cmd;
50 |
51 | /**
52 | * The output object.
53 | */
54 | CmdLineOutput** _out;
55 |
56 | public:
57 |
58 | /**
59 | * Constructor.
60 | * \param cmd - The CmdLine the output will be generated for.
61 | * \param out - The type of output.
62 | */
63 | HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out)
64 | : Visitor(), _cmd( cmd ), _out( out ) { }
65 |
66 | /**
67 | * Calls the usage method of the CmdLineOutput for the
68 | * specified CmdLine.
69 | */
70 | void visit() { (*_out)->usage(*_cmd); throw ExitException(0); }
71 |
72 | };
73 |
74 | }
75 |
76 | #endif
77 |
--------------------------------------------------------------------------------
/extras/include/tclap/IgnoreRestVisitor.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | *
4 | * file: IgnoreRestVisitor.h
5 | *
6 | * Copyright (c) 2003, Michael E. Smoot .
7 | * All rights reverved.
8 | *
9 | * See the file COPYING in the top directory of this distribution for
10 | * more information.
11 | *
12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
18 | * DEALINGS IN THE SOFTWARE.
19 | *
20 | *****************************************************************************/
21 |
22 |
23 | #ifndef TCLAP_IGNORE_REST_VISITOR_H
24 | #define TCLAP_IGNORE_REST_VISITOR_H
25 |
26 | #include
27 | #include
28 |
29 | namespace TCLAP {
30 |
31 | /**
32 | * A Vistor that tells the CmdLine to begin ignoring arguments after
33 | * this one is parsed.
34 | */
35 | class IgnoreRestVisitor: public Visitor
36 | {
37 | public:
38 |
39 | /**
40 | * Constructor.
41 | */
42 | IgnoreRestVisitor() : Visitor() {}
43 |
44 | /**
45 | * Sets Arg::_ignoreRest.
46 | */
47 | void visit() { Arg::beginIgnoring(); }
48 | };
49 |
50 | }
51 |
52 | #endif
53 |
--------------------------------------------------------------------------------
/extras/include/tclap/Makefile.am:
--------------------------------------------------------------------------------
1 |
2 | libtclapincludedir = $(includedir)/tclap
3 |
4 | libtclapinclude_HEADERS = \
5 | CmdLineInterface.h \
6 | ArgException.h \
7 | CmdLine.h \
8 | XorHandler.h \
9 | MultiArg.h \
10 | UnlabeledMultiArg.h \
11 | ValueArg.h \
12 | UnlabeledValueArg.h \
13 | Visitor.h Arg.h \
14 | HelpVisitor.h \
15 | SwitchArg.h \
16 | MultiSwitchArg.h \
17 | VersionVisitor.h \
18 | IgnoreRestVisitor.h \
19 | CmdLineOutput.h \
20 | StdOutput.h \
21 | DocBookOutput.h \
22 | ZshCompletionOutput.h \
23 | OptionalUnlabeledTracker.h \
24 | Constraint.h \
25 | ValuesConstraint.h \
26 | ArgTraits.h \
27 | StandardTraits.h
28 |
29 |
--------------------------------------------------------------------------------
/extras/include/tclap/Makefile.in:
--------------------------------------------------------------------------------
1 | # Makefile.in generated by automake 1.10 from Makefile.am.
2 | # @configure_input@
3 |
4 | # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
5 | # 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
6 | # This Makefile.in is free software; the Free Software Foundation
7 | # gives unlimited permission to copy and/or distribute it,
8 | # with or without modifications, as long as this notice is preserved.
9 |
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY, to the extent permitted by law; without
12 | # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13 | # PARTICULAR PURPOSE.
14 |
15 | @SET_MAKE@
16 |
17 | VPATH = @srcdir@
18 | pkgdatadir = $(datadir)/@PACKAGE@
19 | pkglibdir = $(libdir)/@PACKAGE@
20 | pkgincludedir = $(includedir)/@PACKAGE@
21 | am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
22 | install_sh_DATA = $(install_sh) -c -m 644
23 | install_sh_PROGRAM = $(install_sh) -c
24 | install_sh_SCRIPT = $(install_sh) -c
25 | INSTALL_HEADER = $(INSTALL_DATA)
26 | transform = $(program_transform_name)
27 | NORMAL_INSTALL = :
28 | PRE_INSTALL = :
29 | POST_INSTALL = :
30 | NORMAL_UNINSTALL = :
31 | PRE_UNINSTALL = :
32 | POST_UNINSTALL = :
33 | subdir = include/tclap
34 | DIST_COMMON = $(libtclapinclude_HEADERS) $(srcdir)/Makefile.am \
35 | $(srcdir)/Makefile.in
36 | ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
37 | am__aclocal_m4_deps = $(top_srcdir)/config/ac_cxx_have_long_long.m4 \
38 | $(top_srcdir)/config/ac_cxx_have_sstream.m4 \
39 | $(top_srcdir)/config/ac_cxx_have_strstream.m4 \
40 | $(top_srcdir)/config/ac_cxx_namespaces.m4 \
41 | $(top_srcdir)/config/ac_cxx_warn_effective_cxx.m4 \
42 | $(top_srcdir)/config/bb_enable_doxygen.m4 \
43 | $(top_srcdir)/configure.in
44 | am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
45 | $(ACLOCAL_M4)
46 | mkinstalldirs = $(SHELL) $(top_srcdir)/config/mkinstalldirs
47 | CONFIG_HEADER = $(top_builddir)/config/config.h
48 | CONFIG_CLEAN_FILES =
49 | SOURCES =
50 | DIST_SOURCES =
51 | am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
52 | am__vpath_adj = case $$p in \
53 | $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
54 | *) f=$$p;; \
55 | esac;
56 | am__strip_dir = `echo $$p | sed -e 's|^.*/||'`;
57 | am__installdirs = "$(DESTDIR)$(libtclapincludedir)"
58 | libtclapincludeHEADERS_INSTALL = $(INSTALL_HEADER)
59 | HEADERS = $(libtclapinclude_HEADERS)
60 | ETAGS = etags
61 | CTAGS = ctags
62 | DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
63 | ACLOCAL = @ACLOCAL@
64 | AMTAR = @AMTAR@
65 | AUTOCONF = @AUTOCONF@
66 | AUTOHEADER = @AUTOHEADER@
67 | AUTOMAKE = @AUTOMAKE@
68 | AWK = @AWK@
69 | CPPFLAGS = @CPPFLAGS@
70 | CXX = @CXX@
71 | CXXCPP = @CXXCPP@
72 | CXXDEPMODE = @CXXDEPMODE@
73 | CXXFLAGS = @CXXFLAGS@
74 | CYGPATH_W = @CYGPATH_W@
75 | DEFS = @DEFS@
76 | DEPDIR = @DEPDIR@
77 | DOT = @DOT@
78 | DOXYGEN = @DOXYGEN@
79 | ECHO_C = @ECHO_C@
80 | ECHO_N = @ECHO_N@
81 | ECHO_T = @ECHO_T@
82 | EGREP = @EGREP@
83 | EXEEXT = @EXEEXT@
84 | GREP = @GREP@
85 | INSTALL = @INSTALL@
86 | INSTALL_DATA = @INSTALL_DATA@
87 | INSTALL_PROGRAM = @INSTALL_PROGRAM@
88 | INSTALL_SCRIPT = @INSTALL_SCRIPT@
89 | INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@
90 | LDFLAGS = @LDFLAGS@
91 | LIBOBJS = @LIBOBJS@
92 | LIBS = @LIBS@
93 | LTLIBOBJS = @LTLIBOBJS@
94 | MAKEINFO = @MAKEINFO@
95 | MKDIR_P = @MKDIR_P@
96 | OBJEXT = @OBJEXT@
97 | PACKAGE = @PACKAGE@
98 | PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
99 | PACKAGE_NAME = @PACKAGE_NAME@
100 | PACKAGE_STRING = @PACKAGE_STRING@
101 | PACKAGE_TARNAME = @PACKAGE_TARNAME@
102 | PACKAGE_VERSION = @PACKAGE_VERSION@
103 | PATH_SEPARATOR = @PATH_SEPARATOR@
104 | RANLIB = @RANLIB@
105 | SET_MAKE = @SET_MAKE@
106 | SHELL = @SHELL@
107 | STRIP = @STRIP@
108 | VERSION = @VERSION@
109 | WARN_EFFECTIVE_CXX = @WARN_EFFECTIVE_CXX@
110 | WARN_NO_EFFECTIVE_CXX = @WARN_NO_EFFECTIVE_CXX@
111 | abs_builddir = @abs_builddir@
112 | abs_srcdir = @abs_srcdir@
113 | abs_top_builddir = @abs_top_builddir@
114 | abs_top_srcdir = @abs_top_srcdir@
115 | ac_ct_CXX = @ac_ct_CXX@
116 | am__include = @am__include@
117 | am__leading_dot = @am__leading_dot@
118 | am__quote = @am__quote@
119 | am__tar = @am__tar@
120 | am__untar = @am__untar@
121 | bindir = @bindir@
122 | build_alias = @build_alias@
123 | builddir = @builddir@
124 | datadir = @datadir@
125 | datarootdir = @datarootdir@
126 | docdir = @docdir@
127 | dvidir = @dvidir@
128 | exec_prefix = @exec_prefix@
129 | host_alias = @host_alias@
130 | htmldir = @htmldir@
131 | includedir = @includedir@
132 | infodir = @infodir@
133 | install_sh = @install_sh@
134 | libdir = @libdir@
135 | libexecdir = @libexecdir@
136 | localedir = @localedir@
137 | localstatedir = @localstatedir@
138 | mandir = @mandir@
139 | mkdir_p = @mkdir_p@
140 | oldincludedir = @oldincludedir@
141 | pdfdir = @pdfdir@
142 | prefix = @prefix@
143 | program_transform_name = @program_transform_name@
144 | psdir = @psdir@
145 | sbindir = @sbindir@
146 | sharedstatedir = @sharedstatedir@
147 | srcdir = @srcdir@
148 | sysconfdir = @sysconfdir@
149 | target_alias = @target_alias@
150 | top_builddir = @top_builddir@
151 | top_srcdir = @top_srcdir@
152 | libtclapincludedir = $(includedir)/tclap
153 | libtclapinclude_HEADERS = \
154 | CmdLineInterface.h \
155 | ArgException.h \
156 | CmdLine.h \
157 | XorHandler.h \
158 | MultiArg.h \
159 | UnlabeledMultiArg.h \
160 | ValueArg.h \
161 | UnlabeledValueArg.h \
162 | Visitor.h Arg.h \
163 | HelpVisitor.h \
164 | SwitchArg.h \
165 | MultiSwitchArg.h \
166 | VersionVisitor.h \
167 | IgnoreRestVisitor.h \
168 | CmdLineOutput.h \
169 | StdOutput.h \
170 | DocBookOutput.h \
171 | ZshCompletionOutput.h \
172 | OptionalUnlabeledTracker.h \
173 | Constraint.h \
174 | ValuesConstraint.h \
175 | ArgTraits.h \
176 | StandardTraits.h
177 |
178 | all: all-am
179 |
180 | .SUFFIXES:
181 | $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
182 | @for dep in $?; do \
183 | case '$(am__configure_deps)' in \
184 | *$$dep*) \
185 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
186 | && exit 0; \
187 | exit 1;; \
188 | esac; \
189 | done; \
190 | echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/tclap/Makefile'; \
191 | cd $(top_srcdir) && \
192 | $(AUTOMAKE) --gnu include/tclap/Makefile
193 | .PRECIOUS: Makefile
194 | Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
195 | @case '$?' in \
196 | *config.status*) \
197 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
198 | *) \
199 | echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
200 | cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
201 | esac;
202 |
203 | $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
204 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
205 |
206 | $(top_srcdir)/configure: $(am__configure_deps)
207 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
208 | $(ACLOCAL_M4): $(am__aclocal_m4_deps)
209 | cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
210 | install-libtclapincludeHEADERS: $(libtclapinclude_HEADERS)
211 | @$(NORMAL_INSTALL)
212 | test -z "$(libtclapincludedir)" || $(MKDIR_P) "$(DESTDIR)$(libtclapincludedir)"
213 | @list='$(libtclapinclude_HEADERS)'; for p in $$list; do \
214 | if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
215 | f=$(am__strip_dir) \
216 | echo " $(libtclapincludeHEADERS_INSTALL) '$$d$$p' '$(DESTDIR)$(libtclapincludedir)/$$f'"; \
217 | $(libtclapincludeHEADERS_INSTALL) "$$d$$p" "$(DESTDIR)$(libtclapincludedir)/$$f"; \
218 | done
219 |
220 | uninstall-libtclapincludeHEADERS:
221 | @$(NORMAL_UNINSTALL)
222 | @list='$(libtclapinclude_HEADERS)'; for p in $$list; do \
223 | f=$(am__strip_dir) \
224 | echo " rm -f '$(DESTDIR)$(libtclapincludedir)/$$f'"; \
225 | rm -f "$(DESTDIR)$(libtclapincludedir)/$$f"; \
226 | done
227 |
228 | ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
229 | list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
230 | unique=`for i in $$list; do \
231 | if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
232 | done | \
233 | $(AWK) ' { files[$$0] = 1; } \
234 | END { for (i in files) print i; }'`; \
235 | mkid -fID $$unique
236 | tags: TAGS
237 |
238 | TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
239 | $(TAGS_FILES) $(LISP)
240 | tags=; \
241 | here=`pwd`; \
242 | list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
243 | unique=`for i in $$list; do \
244 | if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
245 | done | \
246 | $(AWK) ' { files[$$0] = 1; } \
247 | END { for (i in files) print i; }'`; \
248 | if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
249 | test -n "$$unique" || unique=$$empty_fix; \
250 | $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
251 | $$tags $$unique; \
252 | fi
253 | ctags: CTAGS
254 | CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \
255 | $(TAGS_FILES) $(LISP)
256 | tags=; \
257 | here=`pwd`; \
258 | list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
259 | unique=`for i in $$list; do \
260 | if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
261 | done | \
262 | $(AWK) ' { files[$$0] = 1; } \
263 | END { for (i in files) print i; }'`; \
264 | test -z "$(CTAGS_ARGS)$$tags$$unique" \
265 | || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
266 | $$tags $$unique
267 |
268 | GTAGS:
269 | here=`$(am__cd) $(top_builddir) && pwd` \
270 | && cd $(top_srcdir) \
271 | && gtags -i $(GTAGS_ARGS) $$here
272 |
273 | distclean-tags:
274 | -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
275 |
276 | distdir: $(DISTFILES)
277 | @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
278 | topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
279 | list='$(DISTFILES)'; \
280 | dist_files=`for file in $$list; do echo $$file; done | \
281 | sed -e "s|^$$srcdirstrip/||;t" \
282 | -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
283 | case $$dist_files in \
284 | */*) $(MKDIR_P) `echo "$$dist_files" | \
285 | sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
286 | sort -u` ;; \
287 | esac; \
288 | for file in $$dist_files; do \
289 | if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
290 | if test -d $$d/$$file; then \
291 | dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
292 | if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
293 | cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
294 | fi; \
295 | cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
296 | else \
297 | test -f $(distdir)/$$file \
298 | || cp -p $$d/$$file $(distdir)/$$file \
299 | || exit 1; \
300 | fi; \
301 | done
302 | check-am: all-am
303 | check: check-am
304 | all-am: Makefile $(HEADERS)
305 | installdirs:
306 | for dir in "$(DESTDIR)$(libtclapincludedir)"; do \
307 | test -z "$$dir" || $(MKDIR_P) "$$dir"; \
308 | done
309 | install: install-am
310 | install-exec: install-exec-am
311 | install-data: install-data-am
312 | uninstall: uninstall-am
313 |
314 | install-am: all-am
315 | @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
316 |
317 | installcheck: installcheck-am
318 | install-strip:
319 | $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
320 | install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
321 | `test -z '$(STRIP)' || \
322 | echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
323 | mostlyclean-generic:
324 |
325 | clean-generic:
326 |
327 | distclean-generic:
328 | -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
329 |
330 | maintainer-clean-generic:
331 | @echo "This command is intended for maintainers to use"
332 | @echo "it deletes files that may require special tools to rebuild."
333 | clean: clean-am
334 |
335 | clean-am: clean-generic mostlyclean-am
336 |
337 | distclean: distclean-am
338 | -rm -f Makefile
339 | distclean-am: clean-am distclean-generic distclean-tags
340 |
341 | dvi: dvi-am
342 |
343 | dvi-am:
344 |
345 | html: html-am
346 |
347 | info: info-am
348 |
349 | info-am:
350 |
351 | install-data-am: install-libtclapincludeHEADERS
352 |
353 | install-dvi: install-dvi-am
354 |
355 | install-exec-am:
356 |
357 | install-html: install-html-am
358 |
359 | install-info: install-info-am
360 |
361 | install-man:
362 |
363 | install-pdf: install-pdf-am
364 |
365 | install-ps: install-ps-am
366 |
367 | installcheck-am:
368 |
369 | maintainer-clean: maintainer-clean-am
370 | -rm -f Makefile
371 | maintainer-clean-am: distclean-am maintainer-clean-generic
372 |
373 | mostlyclean: mostlyclean-am
374 |
375 | mostlyclean-am: mostlyclean-generic
376 |
377 | pdf: pdf-am
378 |
379 | pdf-am:
380 |
381 | ps: ps-am
382 |
383 | ps-am:
384 |
385 | uninstall-am: uninstall-libtclapincludeHEADERS
386 |
387 | .MAKE: install-am install-strip
388 |
389 | .PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \
390 | ctags distclean distclean-generic distclean-tags distdir dvi \
391 | dvi-am html html-am info info-am install install-am \
392 | install-data install-data-am install-dvi install-dvi-am \
393 | install-exec install-exec-am install-html install-html-am \
394 | install-info install-info-am install-libtclapincludeHEADERS \
395 | install-man install-pdf install-pdf-am install-ps \
396 | install-ps-am install-strip installcheck installcheck-am \
397 | installdirs maintainer-clean maintainer-clean-generic \
398 | mostlyclean mostlyclean-generic pdf pdf-am ps ps-am tags \
399 | uninstall uninstall-am uninstall-libtclapincludeHEADERS
400 |
401 | # Tell versions [3.59,3.63) of GNU make to not export all variables.
402 | # Otherwise a system limit (for SysV at least) may be exceeded.
403 | .NOEXPORT:
404 |
--------------------------------------------------------------------------------
/extras/include/tclap/MultiSwitchArg.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | *
4 | * file: MultiSwitchArg.h
5 | *
6 | * Copyright (c) 2003, Michael E. Smoot .
7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
8 | * Copyright (c) 2005, Michael E. Smoot, Daniel Aarno, Erik Zeek.
9 | * All rights reverved.
10 | *
11 | * See the file COPYING in the top directory of this distribution for
12 | * more information.
13 | *
14 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 | * DEALINGS IN THE SOFTWARE.
21 | *
22 | *****************************************************************************/
23 |
24 |
25 | #ifndef TCLAP_MULTI_SWITCH_ARG_H
26 | #define TCLAP_MULTI_SWITCH_ARG_H
27 |
28 | #include
29 | #include
30 |
31 | #include
32 |
33 | namespace TCLAP {
34 |
35 | /**
36 | * A multiple switch argument. If the switch is set on the command line, then
37 | * the getValue method will return the number of times the switch appears.
38 | */
39 | class MultiSwitchArg : public SwitchArg
40 | {
41 | protected:
42 |
43 | /**
44 | * The value of the switch.
45 | */
46 | int _value;
47 |
48 | /**
49 | * Used to support the reset() method so that ValueArg can be
50 | * reset to their constructed value.
51 | */
52 | int _default;
53 |
54 | public:
55 |
56 | /**
57 | * MultiSwitchArg constructor.
58 | * \param flag - The one character flag that identifies this
59 | * argument on the command line.
60 | * \param name - A one word name for the argument. Can be
61 | * used as a long flag on the command line.
62 | * \param desc - A description of what the argument is for or
63 | * does.
64 | * \param init - Optional. The initial/default value of this Arg.
65 | * Defaults to 0.
66 | * \param v - An optional visitor. You probably should not
67 | * use this unless you have a very good reason.
68 | */
69 | MultiSwitchArg(const std::string& flag,
70 | const std::string& name,
71 | const std::string& desc,
72 | int init = 0,
73 | Visitor* v = NULL);
74 |
75 |
76 | /**
77 | * MultiSwitchArg constructor.
78 | * \param flag - The one character flag that identifies this
79 | * argument on the command line.
80 | * \param name - A one word name for the argument. Can be
81 | * used as a long flag on the command line.
82 | * \param desc - A description of what the argument is for or
83 | * does.
84 | * \param parser - A CmdLine parser object to add this Arg to
85 | * \param init - Optional. The initial/default value of this Arg.
86 | * Defaults to 0.
87 | * \param v - An optional visitor. You probably should not
88 | * use this unless you have a very good reason.
89 | */
90 | MultiSwitchArg(const std::string& flag,
91 | const std::string& name,
92 | const std::string& desc,
93 | CmdLineInterface& parser,
94 | int init = 0,
95 | Visitor* v = NULL);
96 |
97 |
98 | /**
99 | * Handles the processing of the argument.
100 | * This re-implements the SwitchArg version of this method to set the
101 | * _value of the argument appropriately.
102 | * \param i - Pointer the the current argument in the list.
103 | * \param args - Mutable list of strings. Passed
104 | * in from main().
105 | */
106 | virtual bool processArg(int* i, std::vector& args);
107 |
108 | /**
109 | * Returns int, the number of times the switch has been set.
110 | */
111 | int getValue();
112 |
113 | /**
114 | * Returns the shortID for this Arg.
115 | */
116 | std::string shortID(const std::string& val) const;
117 |
118 | /**
119 | * Returns the longID for this Arg.
120 | */
121 | std::string longID(const std::string& val) const;
122 |
123 | void reset();
124 |
125 | };
126 |
127 | //////////////////////////////////////////////////////////////////////
128 | //BEGIN MultiSwitchArg.cpp
129 | //////////////////////////////////////////////////////////////////////
130 | inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
131 | const std::string& name,
132 | const std::string& desc,
133 | int init,
134 | Visitor* v )
135 | : SwitchArg(flag, name, desc, false, v),
136 | _value( init ),
137 | _default( init )
138 | { }
139 |
140 | inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
141 | const std::string& name,
142 | const std::string& desc,
143 | CmdLineInterface& parser,
144 | int init,
145 | Visitor* v )
146 | : SwitchArg(flag, name, desc, false, v),
147 | _value( init ),
148 | _default( init )
149 | {
150 | parser.add( this );
151 | }
152 |
153 | inline int MultiSwitchArg::getValue() { return _value; }
154 |
155 | inline bool MultiSwitchArg::processArg(int *i, std::vector& args)
156 | {
157 | if ( _ignoreable && Arg::ignoreRest() )
158 | return false;
159 |
160 | if ( argMatches( args[*i] ))
161 | {
162 | // so the isSet() method will work
163 | _alreadySet = true;
164 |
165 | // Matched argument: increment value.
166 | ++_value;
167 |
168 | _checkWithVisitor();
169 |
170 | return true;
171 | }
172 | else if ( combinedSwitchesMatch( args[*i] ) )
173 | {
174 | // so the isSet() method will work
175 | _alreadySet = true;
176 |
177 | // Matched argument: increment value.
178 | ++_value;
179 |
180 | // Check for more in argument and increment value.
181 | while ( combinedSwitchesMatch( args[*i] ) )
182 | ++_value;
183 |
184 | _checkWithVisitor();
185 |
186 | return false;
187 | }
188 | else
189 | return false;
190 | }
191 |
192 | inline std::string
193 | MultiSwitchArg::shortID(const std::string& val) const
194 | {
195 | return Arg::shortID(val) + " ... ";
196 | }
197 |
198 | inline std::string
199 | MultiSwitchArg::longID(const std::string& val) const
200 | {
201 | return Arg::longID(val) + " (accepted multiple times)";
202 | }
203 |
204 | inline void
205 | MultiSwitchArg::reset()
206 | {
207 | MultiSwitchArg::_value = MultiSwitchArg::_default;
208 | }
209 |
210 | //////////////////////////////////////////////////////////////////////
211 | //END MultiSwitchArg.cpp
212 | //////////////////////////////////////////////////////////////////////
213 |
214 | } //namespace TCLAP
215 |
216 | #endif
217 |
--------------------------------------------------------------------------------
/extras/include/tclap/OptionalUnlabeledTracker.h:
--------------------------------------------------------------------------------
1 |
2 |
3 | /******************************************************************************
4 | *
5 | * file: OptionalUnlabeledTracker.h
6 | *
7 | * Copyright (c) 2005, Michael E. Smoot .
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 |
24 | #ifndef TCLAP_OPTIONAL_UNLABELED_TRACKER_H
25 | #define TCLAP_OPTIONAL_UNLABELED_TRACKER_H
26 |
27 | #include
28 |
29 | namespace TCLAP {
30 |
31 | class OptionalUnlabeledTracker
32 | {
33 |
34 | public:
35 |
36 | static void check( bool req, const std::string& argName );
37 |
38 | static void gotOptional() { alreadyOptionalRef() = true; }
39 |
40 | static bool& alreadyOptional() { return alreadyOptionalRef(); }
41 |
42 | private:
43 |
44 | static bool& alreadyOptionalRef() { static bool ct = false; return ct; }
45 | };
46 |
47 |
48 | inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName )
49 | {
50 | if ( OptionalUnlabeledTracker::alreadyOptional() )
51 | throw( SpecificationException(
52 | "You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg",
53 | argName ) );
54 |
55 | if ( !req )
56 | OptionalUnlabeledTracker::gotOptional();
57 | }
58 |
59 |
60 | } // namespace TCLAP
61 |
62 | #endif
63 |
--------------------------------------------------------------------------------
/extras/include/tclap/StandardTraits.h:
--------------------------------------------------------------------------------
1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
2 |
3 | /******************************************************************************
4 | *
5 | * file: StandardTraits.h
6 | *
7 | * Copyright (c) 2007, Daniel Aarno, Michael E. Smoot .
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 | // This is an internal tclap file, you should probably not have to
24 | // include this directly
25 |
26 | #ifndef TCLAP_STANDARD_TRAITS_H
27 | #define TCLAP_STANDARD_TRAITS_H
28 |
29 | #ifdef HAVE_CONFIG_H
30 | #include // To check for long long
31 | #endif
32 |
33 | // If Microsoft has already typedef'd wchar_t as an unsigned
34 | // short, then compiles will break because it's as if we're
35 | // creating ArgTraits twice for unsigned short. Thus...
36 | #ifdef _MSC_VER
37 | #ifndef _NATIVE_WCHAR_T_DEFINED
38 | #define TCLAP_DONT_DECLARE_WCHAR_T_ARGTRAITS
39 | #endif
40 | #endif
41 |
42 | namespace TCLAP {
43 |
44 | // ======================================================================
45 | // Integer types
46 | // ======================================================================
47 |
48 | /**
49 | * longs have value-like semantics.
50 | */
51 | template<>
52 | struct ArgTraits {
53 | typedef ValueLike ValueCategory;
54 | };
55 |
56 | /**
57 | * ints have value-like semantics.
58 | */
59 | template<>
60 | struct ArgTraits {
61 | typedef ValueLike ValueCategory;
62 | };
63 |
64 | /**
65 | * shorts have value-like semantics.
66 | */
67 | template<>
68 | struct ArgTraits {
69 | typedef ValueLike ValueCategory;
70 | };
71 |
72 | /**
73 | * chars have value-like semantics.
74 | */
75 | template<>
76 | struct ArgTraits {
77 | typedef ValueLike ValueCategory;
78 | };
79 |
80 | #ifdef HAVE_LONG_LONG
81 | /**
82 | * long longs have value-like semantics.
83 | */
84 | template<>
85 | struct ArgTraits {
86 | typedef ValueLike ValueCategory;
87 | };
88 | #endif
89 |
90 | // ======================================================================
91 | // Unsigned integer types
92 | // ======================================================================
93 |
94 | /**
95 | * unsigned longs have value-like semantics.
96 | */
97 | template<>
98 | struct ArgTraits {
99 | typedef ValueLike ValueCategory;
100 | };
101 |
102 | /**
103 | * unsigned ints have value-like semantics.
104 | */
105 | template<>
106 | struct ArgTraits {
107 | typedef ValueLike ValueCategory;
108 | };
109 |
110 | /**
111 | * unsigned shorts have value-like semantics.
112 | */
113 | template<>
114 | struct ArgTraits {
115 | typedef ValueLike ValueCategory;
116 | };
117 |
118 | /**
119 | * unsigned chars have value-like semantics.
120 | */
121 | template<>
122 | struct ArgTraits {
123 | typedef ValueLike ValueCategory;
124 | };
125 |
126 | // Microsoft implements size_t awkwardly.
127 | #if defined(_MSC_VER) && defined(_M_X64)
128 | /**
129 | * size_ts have value-like semantics.
130 | */
131 | template<>
132 | struct ArgTraits {
133 | typedef ValueLike ValueCategory;
134 | };
135 | #endif
136 |
137 |
138 | #ifdef HAVE_LONG_LONG
139 | /**
140 | * unsigned long longs have value-like semantics.
141 | */
142 | template<>
143 | struct ArgTraits {
144 | typedef ValueLike ValueCategory;
145 | };
146 | #endif
147 |
148 | // ======================================================================
149 | // Float types
150 | // ======================================================================
151 |
152 | /**
153 | * floats have value-like semantics.
154 | */
155 | template<>
156 | struct ArgTraits {
157 | typedef ValueLike ValueCategory;
158 | };
159 |
160 | /**
161 | * doubles have value-like semantics.
162 | */
163 | template<>
164 | struct ArgTraits {
165 | typedef ValueLike ValueCategory;
166 | };
167 |
168 | // ======================================================================
169 | // Other types
170 | // ======================================================================
171 |
172 | /**
173 | * bools have value-like semantics.
174 | */
175 | template<>
176 | struct ArgTraits {
177 | typedef ValueLike ValueCategory;
178 | };
179 |
180 |
181 | /**
182 | * wchar_ts have value-like semantics.
183 | */
184 | #ifndef TCLAP_DONT_DECLARE_WCHAR_T_ARGTRAITS
185 | template<>
186 | struct ArgTraits {
187 | typedef ValueLike ValueCategory;
188 | };
189 | #endif
190 |
191 | /**
192 | * Strings have string like argument traits.
193 | */
194 | template<>
195 | struct ArgTraits {
196 | typedef StringLike ValueCategory;
197 | };
198 |
199 | template
200 | void SetString(T &dst, const std::string &src)
201 | {
202 | dst = src;
203 | }
204 |
205 | } // namespace
206 |
207 | #endif
208 |
209 |
--------------------------------------------------------------------------------
/extras/include/tclap/StdOutput.h:
--------------------------------------------------------------------------------
1 | // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*-
2 |
3 | /******************************************************************************
4 | *
5 | * file: StdOutput.h
6 | *
7 | * Copyright (c) 2004, Michael E. Smoot
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 | #ifndef TCLAP_STDCMDLINEOUTPUT_H
24 | #define TCLAP_STDCMDLINEOUTPUT_H
25 |
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 |
32 | #include
33 | #include
34 | #include
35 | #include
36 |
37 | namespace TCLAP {
38 |
39 | /**
40 | * A class that isolates any output from the CmdLine object so that it
41 | * may be easily modified.
42 | */
43 | class StdOutput : public CmdLineOutput
44 | {
45 |
46 | public:
47 |
48 | /**
49 | * Prints the usage to stdout. Can be overridden to
50 | * produce alternative behavior.
51 | * \param c - The CmdLine object the output is generated for.
52 | */
53 | virtual void usage(CmdLineInterface& c);
54 |
55 | /**
56 | * Prints the version to stdout. Can be overridden
57 | * to produce alternative behavior.
58 | * \param c - The CmdLine object the output is generated for.
59 | */
60 | virtual void version(CmdLineInterface& c);
61 |
62 | /**
63 | * Prints (to stderr) an error message, short usage
64 | * Can be overridden to produce alternative behavior.
65 | * \param c - The CmdLine object the output is generated for.
66 | * \param e - The ArgException that caused the failure.
67 | */
68 | virtual void failure(CmdLineInterface& c,
69 | ArgException& e );
70 |
71 | protected:
72 |
73 | /**
74 | * Writes a brief usage message with short args.
75 | * \param c - The CmdLine object the output is generated for.
76 | * \param os - The stream to write the message to.
77 | */
78 | void _shortUsage( CmdLineInterface& c, std::ostream& os ) const;
79 |
80 | /**
81 | * Writes a longer usage message with long and short args,
82 | * provides descriptions and prints message.
83 | * \param c - The CmdLine object the output is generated for.
84 | * \param os - The stream to write the message to.
85 | */
86 | void _longUsage( CmdLineInterface& c, std::ostream& os ) const;
87 |
88 | /**
89 | * This function inserts line breaks and indents long strings
90 | * according the params input. It will only break lines at spaces,
91 | * commas and pipes.
92 | * \param os - The stream to be printed to.
93 | * \param s - The string to be printed.
94 | * \param maxWidth - The maxWidth allowed for the output line.
95 | * \param indentSpaces - The number of spaces to indent the first line.
96 | * \param secondLineOffset - The number of spaces to indent the second
97 | * and all subsequent lines in addition to indentSpaces.
98 | */
99 | void spacePrint( std::ostream& os,
100 | const std::string& s,
101 | int maxWidth,
102 | int indentSpaces,
103 | int secondLineOffset ) const;
104 |
105 | };
106 |
107 |
108 | inline void StdOutput::version(CmdLineInterface& _cmd)
109 | {
110 | std::string progName = _cmd.getProgramName();
111 | std::string xversion = _cmd.getVersion();
112 |
113 | std::cout << std::endl << progName << " version: "
114 | << xversion << std::endl << std::endl;
115 | }
116 |
117 | inline void StdOutput::usage(CmdLineInterface& _cmd )
118 | {
119 | std::cout << std::endl << "USAGE: " << std::endl << std::endl;
120 |
121 | _shortUsage( _cmd, std::cout );
122 |
123 | std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl;
124 |
125 | _longUsage( _cmd, std::cout );
126 |
127 | std::cout << std::endl;
128 |
129 | }
130 |
131 | inline void StdOutput::failure( CmdLineInterface& _cmd,
132 | ArgException& e )
133 | {
134 | std::string progName = _cmd.getProgramName();
135 |
136 | std::cerr << "PARSE ERROR: " << e.argId() << std::endl
137 | << " " << e.error() << std::endl << std::endl;
138 |
139 | if ( _cmd.hasHelpAndVersion() )
140 | {
141 | std::cerr << "Brief USAGE: " << std::endl;
142 |
143 | _shortUsage( _cmd, std::cerr );
144 |
145 | std::cerr << std::endl << "For complete USAGE and HELP type: "
146 | << std::endl << " " << progName << " --help"
147 | << std::endl << std::endl;
148 | }
149 | else
150 | usage(_cmd);
151 |
152 | throw ExitException(1);
153 | }
154 |
155 | inline void
156 | StdOutput::_shortUsage( CmdLineInterface& _cmd,
157 | std::ostream& os ) const
158 | {
159 | std::list argList = _cmd.getArgList();
160 | std::string progName = _cmd.getProgramName();
161 | XorHandler xorHandler = _cmd.getXorHandler();
162 | std::vector< std::vector > xorList = xorHandler.getXorList();
163 |
164 | std::string s = progName + " ";
165 |
166 | // first the xor
167 | for ( int i = 0; static_cast(i) < xorList.size(); i++ )
168 | {
169 | s += " {";
170 | for ( ArgVectorIterator it = xorList[i].begin();
171 | it != xorList[i].end(); it++ )
172 | s += (*it)->shortID() + "|";
173 |
174 | s[s.length()-1] = '}';
175 | }
176 |
177 | // then the rest
178 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
179 | if ( !xorHandler.contains( (*it) ) )
180 | s += " " + (*it)->shortID();
181 |
182 | // if the program name is too long, then adjust the second line offset
183 | int secondLineOffset = static_cast(progName.length()) + 2;
184 | if ( secondLineOffset > 75/2 )
185 | secondLineOffset = static_cast(75/2);
186 |
187 | spacePrint( os, s, 75, 3, secondLineOffset );
188 | }
189 |
190 | inline void
191 | StdOutput::_longUsage( CmdLineInterface& _cmd,
192 | std::ostream& os ) const
193 | {
194 | std::list argList = _cmd.getArgList();
195 | std::string message = _cmd.getMessage();
196 | XorHandler xorHandler = _cmd.getXorHandler();
197 | std::vector< std::vector > xorList = xorHandler.getXorList();
198 |
199 | // first the xor
200 | for ( int i = 0; static_cast(i) < xorList.size(); i++ )
201 | {
202 | for ( ArgVectorIterator it = xorList[i].begin();
203 | it != xorList[i].end();
204 | it++ )
205 | {
206 | spacePrint( os, (*it)->longID(), 75, 3, 3 );
207 | spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
208 |
209 | if ( it+1 != xorList[i].end() )
210 | spacePrint(os, "-- OR --", 75, 9, 0);
211 | }
212 | os << std::endl << std::endl;
213 | }
214 |
215 | // then the rest
216 | for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
217 | if ( !xorHandler.contains( (*it) ) )
218 | {
219 | spacePrint( os, (*it)->longID(), 75, 3, 3 );
220 | spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
221 | os << std::endl;
222 | }
223 |
224 | os << std::endl;
225 |
226 | spacePrint( os, message, 75, 3, 0 );
227 | }
228 |
229 | inline void StdOutput::spacePrint( std::ostream& os,
230 | const std::string& s,
231 | int maxWidth,
232 | int indentSpaces,
233 | int secondLineOffset ) const
234 | {
235 | int len = static_cast(s.length());
236 |
237 | if ( (len + indentSpaces > maxWidth) && maxWidth > 0 )
238 | {
239 | int allowedLen = maxWidth - indentSpaces;
240 | int start = 0;
241 | while ( start < len )
242 | {
243 | // find the substring length
244 | // int stringLen = std::min( len - start, allowedLen );
245 | // doing it this way to support a VisualC++ 2005 bug
246 | using namespace std;
247 | int stringLen = min( len - start, allowedLen );
248 |
249 | // trim the length so it doesn't end in middle of a word
250 | if ( stringLen == allowedLen )
251 | while ( stringLen >= 0 &&
252 | s[stringLen+start] != ' ' &&
253 | s[stringLen+start] != ',' &&
254 | s[stringLen+start] != '|' )
255 | stringLen--;
256 |
257 | // ok, the word is longer than the line, so just split
258 | // wherever the line ends
259 | if ( stringLen <= 0 )
260 | stringLen = allowedLen;
261 |
262 | // check for newlines
263 | for ( int i = 0; i < stringLen; i++ )
264 | if ( s[start+i] == '\n' )
265 | stringLen = i+1;
266 |
267 | // print the indent
268 | for ( int i = 0; i < indentSpaces; i++ )
269 | os << " ";
270 |
271 | if ( start == 0 )
272 | {
273 | // handle second line offsets
274 | indentSpaces += secondLineOffset;
275 |
276 | // adjust allowed len
277 | allowedLen -= secondLineOffset;
278 | }
279 |
280 | os << s.substr(start,stringLen) << std::endl;
281 |
282 | // so we don't start a line with a space
283 | while ( s[stringLen+start] == ' ' && start < len )
284 | start++;
285 |
286 | start += stringLen;
287 | }
288 | }
289 | else
290 | {
291 | for ( int i = 0; i < indentSpaces; i++ )
292 | os << " ";
293 | os << s << std::endl;
294 | }
295 | }
296 |
297 | } //namespace TCLAP
298 | #endif
299 |
--------------------------------------------------------------------------------
/extras/include/tclap/SwitchArg.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | *
4 | * file: SwitchArg.h
5 | *
6 | * Copyright (c) 2003, Michael E. Smoot .
7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 |
24 | #ifndef TCLAP_SWITCH_ARG_H
25 | #define TCLAP_SWITCH_ARG_H
26 |
27 | #include
28 | #include
29 |
30 | #include
31 |
32 | namespace TCLAP {
33 |
34 | /**
35 | * A simple switch argument. If the switch is set on the command line, then
36 | * the getValue method will return the opposite of the default value for the
37 | * switch.
38 | */
39 | class SwitchArg : public Arg
40 | {
41 | protected:
42 |
43 | /**
44 | * The value of the switch.
45 | */
46 | bool _value;
47 |
48 | /**
49 | * Used to support the reset() method so that ValueArg can be
50 | * reset to their constructed value.
51 | */
52 | bool _default;
53 |
54 | public:
55 |
56 | /**
57 | * SwitchArg constructor.
58 | * \param flag - The one character flag that identifies this
59 | * argument on the command line.
60 | * \param name - A one word name for the argument. Can be
61 | * used as a long flag on the command line.
62 | * \param desc - A description of what the argument is for or
63 | * does.
64 | * \param def - The default value for this Switch.
65 | * \param v - An optional visitor. You probably should not
66 | * use this unless you have a very good reason.
67 | */
68 | SwitchArg(const std::string& flag,
69 | const std::string& name,
70 | const std::string& desc,
71 | bool def = false,
72 | Visitor* v = NULL);
73 |
74 |
75 | /**
76 | * SwitchArg constructor.
77 | * \param flag - The one character flag that identifies this
78 | * argument on the command line.
79 | * \param name - A one word name for the argument. Can be
80 | * used as a long flag on the command line.
81 | * \param desc - A description of what the argument is for or
82 | * does.
83 | * \param parser - A CmdLine parser object to add this Arg to
84 | * \param def - The default value for this Switch.
85 | * \param v - An optional visitor. You probably should not
86 | * use this unless you have a very good reason.
87 | */
88 | SwitchArg(const std::string& flag,
89 | const std::string& name,
90 | const std::string& desc,
91 | CmdLineInterface& parser,
92 | bool def = false,
93 | Visitor* v = NULL);
94 |
95 |
96 | /**
97 | * Handles the processing of the argument.
98 | * This re-implements the Arg version of this method to set the
99 | * _value of the argument appropriately.
100 | * \param i - Pointer the the current argument in the list.
101 | * \param args - Mutable list of strings. Passed
102 | * in from main().
103 | */
104 | virtual bool processArg(int* i, std::vector& args);
105 |
106 | /**
107 | * Checks a string to see if any of the chars in the string
108 | * match the flag for this Switch.
109 | */
110 | bool combinedSwitchesMatch(std::string& combined);
111 |
112 | /**
113 | * Returns bool, whether or not the switch has been set.
114 | */
115 | bool getValue();
116 |
117 | virtual void reset();
118 |
119 | private:
120 | /**
121 | * Checks to see if we've found the last match in
122 | * a combined string.
123 | */
124 | bool lastCombined(std::string& combined);
125 |
126 | /**
127 | * Does the common processing of processArg.
128 | */
129 | void commonProcessing();
130 | };
131 |
132 | //////////////////////////////////////////////////////////////////////
133 | //BEGIN SwitchArg.cpp
134 | //////////////////////////////////////////////////////////////////////
135 | inline SwitchArg::SwitchArg(const std::string& flag,
136 | const std::string& name,
137 | const std::string& desc,
138 | bool default_val,
139 | Visitor* v )
140 | : Arg(flag, name, desc, false, false, v),
141 | _value( default_val ),
142 | _default( default_val )
143 | { }
144 |
145 | inline SwitchArg::SwitchArg(const std::string& flag,
146 | const std::string& name,
147 | const std::string& desc,
148 | CmdLineInterface& parser,
149 | bool default_val,
150 | Visitor* v )
151 | : Arg(flag, name, desc, false, false, v),
152 | _value( default_val ),
153 | _default(default_val)
154 | {
155 | parser.add( this );
156 | }
157 |
158 | inline bool SwitchArg::getValue() { return _value; }
159 |
160 | inline bool SwitchArg::lastCombined(std::string& combinedSwitches )
161 | {
162 | for ( unsigned int i = 1; i < combinedSwitches.length(); i++ )
163 | if ( combinedSwitches[i] != Arg::blankChar() )
164 | return false;
165 |
166 | return true;
167 | }
168 |
169 | inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches )
170 | {
171 | // make sure this is actually a combined switch
172 | if ( combinedSwitches.length() > 0 &&
173 | combinedSwitches[0] != Arg::flagStartString()[0] )
174 | return false;
175 |
176 | // make sure it isn't a long name
177 | if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) ==
178 | Arg::nameStartString() )
179 | return false;
180 |
181 | // make sure the delimiter isn't in the string
182 | if ( combinedSwitches.find_first_of( Arg::delimiter() ) != std::string::npos )
183 | return false;
184 |
185 | // ok, we're not specifying a ValueArg, so we know that we have
186 | // a combined switch list.
187 | for ( unsigned int i = 1; i < combinedSwitches.length(); i++ )
188 | if ( _flag.length() > 0 &&
189 | combinedSwitches[i] == _flag[0] &&
190 | _flag[0] != Arg::flagStartString()[0] )
191 | {
192 | // update the combined switches so this one is no longer present
193 | // this is necessary so that no unlabeled args are matched
194 | // later in the processing.
195 | //combinedSwitches.erase(i,1);
196 | combinedSwitches[i] = Arg::blankChar();
197 | return true;
198 | }
199 |
200 | // none of the switches passed in the list match.
201 | return false;
202 | }
203 |
204 | inline void SwitchArg::commonProcessing()
205 | {
206 | if ( _xorSet )
207 | throw(CmdLineParseException(
208 | "Mutually exclusive argument already set!", toString()));
209 |
210 | if ( _alreadySet )
211 | throw(CmdLineParseException("Argument already set!", toString()));
212 |
213 | _alreadySet = true;
214 |
215 | if ( _value == true )
216 | _value = false;
217 | else
218 | _value = true;
219 |
220 | _checkWithVisitor();
221 | }
222 |
223 | inline bool SwitchArg::processArg(int *i, std::vector& args)
224 | {
225 | if ( _ignoreable && Arg::ignoreRest() )
226 | return false;
227 |
228 | // if the whole string matches the flag or name string
229 | if ( argMatches( args[*i] ) )
230 | {
231 | commonProcessing();
232 |
233 | return true;
234 | }
235 | // if a substring matches the flag as part of a combination
236 | else if ( combinedSwitchesMatch( args[*i] ) )
237 | {
238 | // check again to ensure we don't misinterpret
239 | // this as a MultiSwitchArg
240 | if ( combinedSwitchesMatch( args[*i] ) )
241 | throw(CmdLineParseException("Argument already set!",
242 | toString()));
243 |
244 | commonProcessing();
245 |
246 | // We only want to return true if we've found the last combined
247 | // match in the string, otherwise we return true so that other
248 | // switches in the combination will have a chance to match.
249 | return lastCombined( args[*i] );
250 | }
251 | else
252 | return false;
253 | }
254 |
255 | inline void SwitchArg::reset()
256 | {
257 | Arg::reset();
258 | _value = _default;
259 | }
260 | //////////////////////////////////////////////////////////////////////
261 | //End SwitchArg.cpp
262 | //////////////////////////////////////////////////////////////////////
263 |
264 | } //namespace TCLAP
265 |
266 | #endif
267 |
--------------------------------------------------------------------------------
/extras/include/tclap/UnlabeledMultiArg.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | *
4 | * file: UnlabeledMultiArg.h
5 | *
6 | * Copyright (c) 2003, Michael E. Smoot.
7 | * All rights reverved.
8 | *
9 | * See the file COPYING in the top directory of this distribution for
10 | * more information.
11 | *
12 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
13 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
15 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
18 | * DEALINGS IN THE SOFTWARE.
19 | *
20 | *****************************************************************************/
21 |
22 |
23 | #ifndef TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H
24 | #define TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H
25 |
26 | #include
27 | #include
28 |
29 | #include
30 | #include
31 |
32 | namespace TCLAP {
33 |
34 | /**
35 | * Just like a MultiArg, except that the arguments are unlabeled. Basically,
36 | * this Arg will slurp up everything that hasn't been matched to another
37 | * Arg.
38 | */
39 | template
40 | class UnlabeledMultiArg : public MultiArg
41 | {
42 |
43 | // If compiler has two stage name lookup (as gcc >= 3.4 does)
44 | // this is requried to prevent undef. symbols
45 | using MultiArg::_ignoreable;
46 | using MultiArg::_hasBlanks;
47 | using MultiArg::_extractValue;
48 | using MultiArg::_typeDesc;
49 | using MultiArg::_name;
50 | using MultiArg::_description;
51 | using MultiArg::_alreadySet;
52 | using MultiArg::toString;
53 |
54 | public:
55 |
56 | /**
57 | * Constructor.
58 | * \param name - The name of the Arg. Note that this is used for
59 | * identification, not as a long flag.
60 | * \param desc - A description of what the argument is for or
61 | * does.
62 | * \param req - Whether the argument is required on the command
63 | * line.
64 | * \param typeDesc - A short, human readable description of the
65 | * type that this object expects. This is used in the generation
66 | * of the USAGE statement. The goal is to be helpful to the end user
67 | * of the program.
68 | * \param ignoreable - Whether or not this argument can be ignored
69 | * using the "--" flag.
70 | * \param v - An optional visitor. You probably should not
71 | * use this unless you have a very good reason.
72 | */
73 | UnlabeledMultiArg( const std::string& name,
74 | const std::string& desc,
75 | bool req,
76 | const std::string& typeDesc,
77 | bool ignoreable = false,
78 | Visitor* v = NULL );
79 | /**
80 | * Constructor.
81 | * \param name - The name of the Arg. Note that this is used for
82 | * identification, not as a long flag.
83 | * \param desc - A description of what the argument is for or
84 | * does.
85 | * \param req - Whether the argument is required on the command
86 | * line.
87 | * \param typeDesc - A short, human readable description of the
88 | * type that this object expects. This is used in the generation
89 | * of the USAGE statement. The goal is to be helpful to the end user
90 | * of the program.
91 | * \param parser - A CmdLine parser object to add this Arg to
92 | * \param ignoreable - Whether or not this argument can be ignored
93 | * using the "--" flag.
94 | * \param v - An optional visitor. You probably should not
95 | * use this unless you have a very good reason.
96 | */
97 | UnlabeledMultiArg( const std::string& name,
98 | const std::string& desc,
99 | bool req,
100 | const std::string& typeDesc,
101 | CmdLineInterface& parser,
102 | bool ignoreable = false,
103 | Visitor* v = NULL );
104 |
105 | /**
106 | * Constructor.
107 | * \param name - The name of the Arg. Note that this is used for
108 | * identification, not as a long flag.
109 | * \param desc - A description of what the argument is for or
110 | * does.
111 | * \param req - Whether the argument is required on the command
112 | * line.
113 | * \param constraint - A pointer to a Constraint object used
114 | * to constrain this Arg.
115 | * \param ignoreable - Whether or not this argument can be ignored
116 | * using the "--" flag.
117 | * \param v - An optional visitor. You probably should not
118 | * use this unless you have a very good reason.
119 | */
120 | UnlabeledMultiArg( const std::string& name,
121 | const std::string& desc,
122 | bool req,
123 | Constraint* constraint,
124 | bool ignoreable = false,
125 | Visitor* v = NULL );
126 |
127 | /**
128 | * Constructor.
129 | * \param name - The name of the Arg. Note that this is used for
130 | * identification, not as a long flag.
131 | * \param desc - A description of what the argument is for or
132 | * does.
133 | * \param req - Whether the argument is required on the command
134 | * line.
135 | * \param constraint - A pointer to a Constraint object used
136 | * to constrain this Arg.
137 | * \param parser - A CmdLine parser object to add this Arg to
138 | * \param ignoreable - Whether or not this argument can be ignored
139 | * using the "--" flag.
140 | * \param v - An optional visitor. You probably should not
141 | * use this unless you have a very good reason.
142 | */
143 | UnlabeledMultiArg( const std::string& name,
144 | const std::string& desc,
145 | bool req,
146 | Constraint* constraint,
147 | CmdLineInterface& parser,
148 | bool ignoreable = false,
149 | Visitor* v = NULL );
150 |
151 | /**
152 | * Handles the processing of the argument.
153 | * This re-implements the Arg version of this method to set the
154 | * _value of the argument appropriately. It knows the difference
155 | * between labeled and unlabeled.
156 | * \param i - Pointer the the current argument in the list.
157 | * \param args - Mutable list of strings. Passed from main().
158 | */
159 | virtual bool processArg(int* i, std::vector& args);
160 |
161 | /**
162 | * Returns the a short id string. Used in the usage.
163 | * \param val - value to be used.
164 | */
165 | virtual std::string shortID(const std::string& val="val") const;
166 |
167 | /**
168 | * Returns the a long id string. Used in the usage.
169 | * \param val - value to be used.
170 | */
171 | virtual std::string longID(const std::string& val="val") const;
172 |
173 | /**
174 | * Opertor ==.
175 | * \param a - The Arg to be compared to this.
176 | */
177 | virtual bool operator==(const Arg& a) const;
178 |
179 | /**
180 | * Pushes this to back of list rather than front.
181 | * \param argList - The list this should be added to.
182 | */
183 | virtual void addToList( std::list& argList ) const;
184 | };
185 |
186 | template
187 | UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name,
188 | const std::string& desc,
189 | bool req,
190 | const std::string& typeDesc,
191 | bool ignoreable,
192 | Visitor* v)
193 | : MultiArg("", name, desc, req, typeDesc, v)
194 | {
195 | _ignoreable = ignoreable;
196 | OptionalUnlabeledTracker::check(true, toString());
197 | }
198 |
199 | template
200 | UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name,
201 | const std::string& desc,
202 | bool req,
203 | const std::string& typeDesc,
204 | CmdLineInterface& parser,
205 | bool ignoreable,
206 | Visitor* v)
207 | : MultiArg("", name, desc, req, typeDesc, v)
208 | {
209 | _ignoreable = ignoreable;
210 | OptionalUnlabeledTracker::check(true, toString());
211 | parser.add( this );
212 | }
213 |
214 |
215 | template
216 | UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name,
217 | const std::string& desc,
218 | bool req,
219 | Constraint* constraint,
220 | bool ignoreable,
221 | Visitor* v)
222 | : MultiArg("", name, desc, req, constraint, v)
223 | {
224 | _ignoreable = ignoreable;
225 | OptionalUnlabeledTracker::check(true, toString());
226 | }
227 |
228 | template
229 | UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name,
230 | const std::string& desc,
231 | bool req,
232 | Constraint* constraint,
233 | CmdLineInterface& parser,
234 | bool ignoreable,
235 | Visitor* v)
236 | : MultiArg("", name, desc, req, constraint, v)
237 | {
238 | _ignoreable = ignoreable;
239 | OptionalUnlabeledTracker::check(true, toString());
240 | parser.add( this );
241 | }
242 |
243 |
244 | template
245 | bool UnlabeledMultiArg::processArg(int *i, std::vector& args)
246 | {
247 |
248 | if ( _hasBlanks( args[*i] ) )
249 | return false;
250 |
251 | // never ignore an unlabeled multi arg
252 |
253 |
254 | // always take the first value, regardless of the start string
255 | _extractValue( args[(*i)] );
256 |
257 | /*
258 | // continue taking args until we hit the end or a start string
259 | while ( (unsigned int)(*i)+1 < args.size() &&
260 | args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
261 | args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
262 | _extractValue( args[++(*i)] );
263 | */
264 |
265 | _alreadySet = true;
266 |
267 | return true;
268 | }
269 |
270 | template
271 | std::string UnlabeledMultiArg::shortID(const std::string& val) const
272 | {
273 | static_cast(val); // Ignore input, don't warn
274 | return std::string("<") + _typeDesc + "> ...";
275 | }
276 |
277 | template
278 | std::string UnlabeledMultiArg::longID(const std::string& val) const
279 | {
280 | static_cast(val); // Ignore input, don't warn
281 | return std::string("<") + _typeDesc + "> (accepted multiple times)";
282 | }
283 |
284 | template
285 | bool UnlabeledMultiArg::operator==(const Arg& a) const
286 | {
287 | if ( _name == a.getName() || _description == a.getDescription() )
288 | return true;
289 | else
290 | return false;
291 | }
292 |
293 | template
294 | void UnlabeledMultiArg::addToList( std::list& argList ) const
295 | {
296 | argList.push_back( const_cast(static_cast(this)) );
297 | }
298 |
299 | }
300 |
301 | #endif
302 |
--------------------------------------------------------------------------------
/extras/include/tclap/UnlabeledValueArg.h:
--------------------------------------------------------------------------------
1 |
2 | /******************************************************************************
3 | *
4 | * file: UnlabeledValueArg.h
5 | *
6 | * Copyright (c) 2003, Michael E. Smoot .
7 | * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno.
8 | * All rights reverved.
9 | *
10 | * See the file COPYING in the top directory of this distribution for
11 | * more information.
12 | *
13 | * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS
14 | * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19 | * DEALINGS IN THE SOFTWARE.
20 | *
21 | *****************************************************************************/
22 |
23 |
24 | #ifndef TCLAP_UNLABELED_VALUE_ARGUMENT_H
25 | #define TCLAP_UNLABELED_VALUE_ARGUMENT_H
26 |
27 | #include
28 | #include
29 |
30 | #include
31 | #include
32 |
33 |
34 | namespace TCLAP {
35 |
36 | /**
37 | * The basic unlabeled argument that parses a value.
38 | * This is a template class, which means the type T defines the type
39 | * that a given object will attempt to parse when an UnlabeledValueArg
40 | * is reached in the list of args that the CmdLine iterates over.
41 | */
42 | template
43 | class UnlabeledValueArg : public ValueArg
44 | {
45 |
46 | // If compiler has two stage name lookup (as gcc >= 3.4 does)
47 | // this is requried to prevent undef. symbols
48 | using ValueArg::_ignoreable;
49 | using ValueArg::_hasBlanks;
50 | using ValueArg::_extractValue;
51 | using ValueArg::_typeDesc;
52 | using ValueArg::_name;
53 | using ValueArg::_description;
54 | using ValueArg::_alreadySet;
55 | using ValueArg::toString;
56 |
57 | public:
58 |
59 | /**
60 | * UnlabeledValueArg constructor.
61 | * \param name - A one word name for the argument. Note that this is used for
62 | * identification, not as a long flag.
63 | * \param desc - A description of what the argument is for or
64 | * does.
65 | * \param req - Whether the argument is required on the command
66 | * line.
67 | * \param value - The default value assigned to this argument if it
68 | * is not present on the command line.
69 | * \param typeDesc - A short, human readable description of the
70 | * type that this object expects. This is used in the generation
71 | * of the USAGE statement. The goal is to be helpful to the end user
72 | * of the program.
73 | * \param ignoreable - Allows you to specify that this argument can be
74 | * ignored if the '--' flag is set. This defaults to false (cannot
75 | * be ignored) and should generally stay that way unless you have
76 | * some special need for certain arguments to be ignored.
77 | * \param v - Optional Vistor. You should leave this blank unless
78 | * you have a very good reason.
79 | */
80 | UnlabeledValueArg( const std::string& name,
81 | const std::string& desc,
82 | bool req,
83 | T value,
84 | const std::string& typeDesc,
85 | bool ignoreable = false,
86 | Visitor* v = NULL);
87 |
88 | /**
89 | * UnlabeledValueArg constructor.
90 | * \param name - A one word name for the argument. Note that this is used for
91 | * identification, not as a long flag.
92 | * \param desc - A description of what the argument is for or
93 | * does.
94 | * \param req - Whether the argument is required on the command
95 | * line.
96 | * \param value - The default value assigned to this argument if it
97 | * is not present on the command line.
98 | * \param typeDesc - A short, human readable description of the
99 | * type that this object expects. This is used in the generation
100 | * of the USAGE statement. The goal is to be helpful to the end user
101 | * of the program.
102 | * \param parser - A CmdLine parser object to add this Arg to
103 | * \param ignoreable - Allows you to specify that this argument can be
104 | * ignored if the '--' flag is set. This defaults to false (cannot
105 | * be ignored) and should generally stay that way unless you have
106 | * some special need for certain arguments to be ignored.
107 | * \param v - Optional Vistor. You should leave this blank unless
108 | * you have a very good reason.
109 | */
110 | UnlabeledValueArg( const std::string& name,
111 | const std::string& desc,
112 | bool req,
113 | T value,
114 | const std::string& typeDesc,
115 | CmdLineInterface& parser,
116 | bool ignoreable = false,
117 | Visitor* v = NULL );
118 |
119 | /**
120 | * UnlabeledValueArg constructor.
121 | * \param name - A one word name for the argument. Note that this is used for
122 | * identification, not as a long flag.
123 | * \param desc - A description of what the argument is for or
124 | * does.
125 | * \param req - Whether the argument is required on the command
126 | * line.
127 | * \param value - The default value assigned to this argument if it
128 | * is not present on the command line.
129 | * \param constraint - A pointer to a Constraint object used
130 | * to constrain this Arg.
131 | * \param ignoreable - Allows you to specify that this argument can be
132 | * ignored if the '--' flag is set. This defaults to false (cannot
133 | * be ignored) and should generally stay that way unless you have
134 | * some special need for certain arguments to be ignored.
135 | * \param v - Optional Vistor. You should leave this blank unless
136 | * you have a very good reason.
137 | */
138 | UnlabeledValueArg( const std::string& name,
139 | const std::string& desc,
140 | bool req,
141 | T value,
142 | Constraint* constraint,
143 | bool ignoreable = false,
144 | Visitor* v = NULL );
145 |
146 |
147 | /**
148 | * UnlabeledValueArg constructor.
149 | * \param name - A one word name for the argument. Note that this is used for
150 | * identification, not as a long flag.
151 | * \param desc - A description of what the argument is for or
152 | * does.
153 | * \param req - Whether the argument is required on the command
154 | * line.
155 | * \param value - The default value assigned to this argument if it
156 | * is not present on the command line.
157 | * \param constraint - A pointer to a Constraint object used
158 | * to constrain this Arg.
159 | * \param parser - A CmdLine parser object to add this Arg to
160 | * \param ignoreable - Allows you to specify that this argument can be
161 | * ignored if the '--' flag is set. This defaults to false (cannot
162 | * be ignored) and should generally stay that way unless you have
163 | * some special need for certain arguments to be ignored.
164 | * \param v - Optional Vistor. You should leave this blank unless
165 | * you have a very good reason.
166 | */
167 | UnlabeledValueArg( const std::string& name,
168 | const std::string& desc,
169 | bool req,
170 | T value,
171 | Constraint* constraint,
172 | CmdLineInterface& parser,
173 | bool ignoreable = false,
174 | Visitor* v = NULL);
175 |
176 | /**
177 | * Handles the processing of the argument.
178 | * This re-implements the Arg version of this method to set the
179 | * _value of the argument appropriately. Handling specific to
180 | * unlabled arguments.
181 | * \param i - Pointer the the current argument in the list.
182 | * \param args - Mutable list of strings.
183 | */
184 | virtual bool processArg(int* i, std::vector& args);
185 |
186 | /**
187 | * Overrides shortID for specific behavior.
188 | */
189 | virtual std::string shortID(const std::string& val="val") const;
190 |
191 | /**
192 | * Overrides longID for specific behavior.
193 | */
194 | virtual std::string longID(const std::string& val="val") const;
195 |
196 | /**
197 | * Overrides operator== for specific behavior.
198 | */
199 | virtual bool operator==(const Arg& a ) const;
200 |
201 | /**
202 | * Instead of pushing to the front of list, push to the back.
203 | * \param argList - The list to add this to.
204 | */
205 | virtual void addToList( std::list& argList ) const;
206 |
207 | };
208 |
209 | /**
210 | * Constructor implemenation.
211 | */
212 | template