From a0c6ee3d923f55184847cb6482058298e15334f7 Mon Sep 17 00:00:00 2001 From: VXL Maintainers Date: Fri, 27 Dec 2024 14:43:32 -0600 Subject: [PATCH] VXL 2024-12-27 (b852f514) Code extracted from: https://github.com/vxl/vxl.git at commit b852f514cbd4a40573c1fc7c9c499bc453edfca0 (master). --- CMakeLists.txt | 6 +- config/cmake/Modules/FindOpenJPEG2.cmake | 1 - .../cmake/Modules/NewCMake/FindDC1394.cmake | 5 - .../cmake/Modules/NewCMake/FindGEOTIFF.cmake | 1 - .../Modules/NewCMake/FindSIMVoleon.cmake | 1 - .../cmake/Modules/NewCMake/FindWin32SDK.cmake | 2 - config/cmake/Modules/readme.txt | 2 - .../cmake/config/vxlGetCXXCompilerVersion.cxx | 19 +- config/cmake/config/vxl_platform_tests.cxx | 141 +- .../vxl_shared_link_test/shared_src.cxx | 6 +- .../vxl_shared_link_test/static_src.cxx | 6 +- config/cmake/config/vxl_utils.cmake | 2 +- config/cmake/doxygen/doxy-notes.txt | 2 +- config/cmake/doxygen/doxy_header.html | 2 +- core/testlib/testlib_main.cxx | 2 +- core/testlib/testlib_register.h | 31 +- core/testlib/testlib_root_dir.cxx | 8 +- core/testlib/testlib_root_dir.h | 3 +- core/testlib/testlib_test.cxx | 14 +- core/testlib/testlib_test.h | 183 ++- core/testlib/tests/test_root_dir.cxx | 2 +- core/vnl/algo/tests/test_algo.cxx | 36 +- core/vnl/algo/tests/test_bracket_minimum.cxx | 10 +- core/vnl/algo/tests/test_brent_minimizer.cxx | 6 +- core/vnl/algo/tests/test_cholesky.cxx | 13 +- core/vnl/algo/tests/test_complex_algo.cxx | 14 +- .../algo/tests/test_complex_eigensystem.cxx | 10 +- core/vnl/algo/tests/test_convolve.cxx | 23 +- core/vnl/algo/tests/test_cpoly_roots.cxx | 4 +- core/vnl/algo/tests/test_determinant.cxx | 66 +- core/vnl/algo/tests/test_fft.cxx | 4 +- core/vnl/algo/tests/test_fft1d.cxx | 12 +- core/vnl/algo/tests/test_fft2d.cxx | 16 +- core/vnl/algo/tests/test_functions.cxx | 6 +- .../tests/test_generalized_eigensystem.cxx | 8 +- core/vnl/algo/tests/test_integral.cxx | 14 +- core/vnl/algo/tests/test_ldl_cholesky.cxx | 48 +- .../algo/tests/test_levenberg_marquardt.cxx | 23 +- core/vnl/algo/tests/test_matrix_update.cxx | 12 +- core/vnl/algo/tests/test_powell.cxx | 14 +- core/vnl/algo/tests/test_qr.cxx | 34 +- core/vnl/algo/tests/test_qsvd.cxx | 15 +- core/vnl/algo/tests/test_rank.cxx | 2 +- core/vnl/algo/tests/test_real_eigensystem.cxx | 12 +- core/vnl/algo/tests/test_rnpoly_roots.cxx | 34 +- core/vnl/algo/tests/test_rpoly_roots.cxx | 4 +- core/vnl/algo/tests/test_solve_qp.cxx | 30 +- core/vnl/algo/tests/test_sparse_lm.cxx | 300 +++-- core/vnl/algo/tests/test_sparse_lu.cxx | 27 +- core/vnl/algo/tests/test_sparse_matrix.cxx | 31 +- core/vnl/algo/tests/test_svd.cxx | 62 +- core/vnl/algo/tests/test_svd_fixed.cxx | 47 +- .../algo/tests/test_symmetric_eigensystem.cxx | 102 +- core/vnl/algo/tests/test_util.cxx | 20 +- core/vnl/algo/tests/test_util.h | 2 +- core/vnl/algo/vnl_adaptsimpson_integral.cxx | 25 +- core/vnl/algo/vnl_adaptsimpson_integral.h | 20 +- core/vnl/algo/vnl_adjugate.h | 9 +- core/vnl/algo/vnl_adjugate.hxx | 26 +- core/vnl/algo/vnl_algo_fwd.h | 12 +- core/vnl/algo/vnl_amoeba.cxx | 25 +- core/vnl/algo/vnl_amoeba.h | 83 +- core/vnl/algo/vnl_bracket_minimum.cxx | 9 +- core/vnl/algo/vnl_bracket_minimum.h | 5 +- core/vnl/algo/vnl_brent.cxx | 8 +- core/vnl/algo/vnl_brent.h | 25 +- core/vnl/algo/vnl_brent_minimizer.cxx | 28 +- core/vnl/algo/vnl_brent_minimizer.h | 35 +- core/vnl/algo/vnl_chi_squared.h | 18 +- core/vnl/algo/vnl_chi_squared.hxx | 77 +- core/vnl/algo/vnl_cholesky.cxx | 24 +- core/vnl/algo/vnl_cholesky.h | 68 +- core/vnl/algo/vnl_complex_eigensystem.cxx | 12 +- core/vnl/algo/vnl_complex_eigensystem.h | 45 +- core/vnl/algo/vnl_complex_generalized_schur.h | 59 +- core/vnl/algo/vnl_conjugate_gradient.cxx | 10 +- core/vnl/algo/vnl_conjugate_gradient.h | 33 +- core/vnl/algo/vnl_convolve.h | 36 +- core/vnl/algo/vnl_convolve.hxx | 153 ++- core/vnl/algo/vnl_cpoly_roots.cxx | 6 +- core/vnl/algo/vnl_cpoly_roots.h | 12 +- core/vnl/algo/vnl_determinant.cxx | 4 +- core/vnl/algo/vnl_determinant.h | 32 +- core/vnl/algo/vnl_determinant.hxx | 144 +- core/vnl/algo/vnl_discrete_diff.cxx | 42 +- core/vnl/algo/vnl_discrete_diff.h | 44 +- core/vnl/algo/vnl_fft.cxx | 8 +- core/vnl/algo/vnl_fft.h | 34 +- core/vnl/algo/vnl_fft_1d.h | 73 +- core/vnl/algo/vnl_fft_1d.hxx | 3 +- core/vnl/algo/vnl_fft_2d.h | 36 +- core/vnl/algo/vnl_fft_2d.hxx | 3 +- core/vnl/algo/vnl_fft_base.h | 5 +- core/vnl/algo/vnl_fft_base.hxx | 51 +- core/vnl/algo/vnl_fft_prime_factors.h | 61 +- core/vnl/algo/vnl_fft_prime_factors.hxx | 20 +- core/vnl/algo/vnl_fit_parabola.h | 15 +- core/vnl/algo/vnl_gaussian_kernel_1d.cxx | 4 +- core/vnl/algo/vnl_gaussian_kernel_1d.h | 21 +- core/vnl/algo/vnl_generalized_eigensystem.cxx | 2 +- core/vnl/algo/vnl_generalized_eigensystem.h | 43 +- core/vnl/algo/vnl_generalized_schur.h | 57 +- core/vnl/algo/vnl_lbfgs.cxx | 16 +- core/vnl/algo/vnl_lbfgs.h | 14 +- core/vnl/algo/vnl_lbfgsb.cxx | 8 +- core/vnl/algo/vnl_lbfgsb.h | 108 +- core/vnl/algo/vnl_ldl_cholesky.cxx | 39 +- core/vnl/algo/vnl_ldl_cholesky.h | 92 +- core/vnl/algo/vnl_levenberg_marquardt.cxx | 23 +- core/vnl/algo/vnl_levenberg_marquardt.h | 79 +- core/vnl/algo/vnl_lsqr.cxx | 12 +- core/vnl/algo/vnl_lsqr.h | 59 +- core/vnl/algo/vnl_matrix_inverse.h | 35 +- core/vnl/algo/vnl_matrix_inverse.hxx | 8 +- core/vnl/algo/vnl_matrix_update.h | 28 +- core/vnl/algo/vnl_netlib.h | 49 +- core/vnl/algo/vnl_orthogonal_complement.h | 3 +- core/vnl/algo/vnl_orthogonal_complement.hxx | 13 +- core/vnl/algo/vnl_powell.cxx | 22 +- core/vnl/algo/vnl_powell.h | 38 +- core/vnl/algo/vnl_qr.h | 60 +- core/vnl/algo/vnl_qr.hxx | 215 +-- core/vnl/algo/vnl_real_eigensystem.cxx | 6 +- core/vnl/algo/vnl_real_eigensystem.h | 10 +- core/vnl/algo/vnl_rnpoly_solve.cxx | 220 +-- core/vnl/algo/vnl_rnpoly_solve.h | 49 +- core/vnl/algo/vnl_rpoly_roots.h | 55 +- core/vnl/algo/vnl_scatter_3x3.h | 53 +- core/vnl/algo/vnl_scatter_3x3.hxx | 78 +- core/vnl/algo/vnl_simpson_integral.h | 11 +- core/vnl/algo/vnl_solve_qp.cxx | 38 +- core/vnl/algo/vnl_solve_qp.h | 40 +- core/vnl/algo/vnl_sparse_lm.cxx | 109 +- core/vnl/algo/vnl_sparse_lm.h | 108 +- core/vnl/algo/vnl_sparse_lu.cxx | 41 +- core/vnl/algo/vnl_sparse_lu.h | 82 +- .../algo/vnl_sparse_symmetric_eigensystem.cxx | 22 +- .../algo/vnl_sparse_symmetric_eigensystem.h | 56 +- core/vnl/algo/vnl_svd.h | 203 ++- core/vnl/algo/vnl_svd.hxx | 253 ++-- core/vnl/algo/vnl_svd_economy.h | 45 +- core/vnl/algo/vnl_svd_economy.hxx | 41 +- core/vnl/algo/vnl_svd_fixed.h | 203 ++- core/vnl/algo/vnl_svd_fixed.hxx | 215 +-- core/vnl/algo/vnl_symmetric_eigensystem.h | 62 +- core/vnl/algo/vnl_symmetric_eigensystem.hxx | 137 +- core/vnl/dll.h | 10 +- core/vnl/examples/calculate.cxx | 38 +- core/vnl/examples/vnl_svd.cxx | 4 +- core/vnl/io/tests/test_matrix_fixed_io.cxx | 4 +- .../vnl/io/tests/test_real_npolynomial_io.cxx | 4 +- core/vnl/io/vnl_io_bignum.h | 9 +- core/vnl/io/vnl_io_diag_matrix.h | 9 +- core/vnl/io/vnl_io_diag_matrix.hxx | 48 +- core/vnl/io/vnl_io_matrix.h | 9 +- core/vnl/io/vnl_io_matrix.hxx | 102 +- core/vnl/io/vnl_io_matrix_fixed.h | 9 +- core/vnl/io/vnl_io_matrix_fixed.hxx | 120 +- core/vnl/io/vnl_io_nonlinear_minimizer.h | 54 +- core/vnl/io/vnl_io_rational.h | 9 +- core/vnl/io/vnl_io_real_npolynomial.h | 9 +- core/vnl/io/vnl_io_real_polynomial.h | 9 +- core/vnl/io/vnl_io_sparse_matrix.h | 9 +- core/vnl/io/vnl_io_sparse_matrix.hxx | 139 +- core/vnl/io/vnl_io_sym_matrix.h | 9 +- core/vnl/io/vnl_io_sym_matrix.hxx | 85 +- core/vnl/io/vnl_io_vector.h | 9 +- core/vnl/io/vnl_io_vector.hxx | 72 +- core/vnl/io/vnl_io_vector_fixed.h | 9 +- core/vnl/io/vnl_io_vector_fixed.hxx | 94 +- core/vnl/tests/basic_operation_timings.cxx | 22 +- core/vnl/tests/test_alignment.cxx | 74 +- core/vnl/tests/test_arithmetic.cxx | 24 +- core/vnl/tests/test_arithmetic_body.h | 541 ++++---- core/vnl/tests/test_bignum.cxx | 140 +- core/vnl/tests/test_complex.cxx | 33 +- core/vnl/tests/test_container_interface.cxx | 4 +- core/vnl/tests/test_crs_index.cxx | 6 +- core/vnl/tests/test_decnum.cxx | 153 ++- core/vnl/tests/test_diag_matrix.cxx | 10 +- core/vnl/tests/test_diag_matrix_fixed.cxx | 10 +- core/vnl/tests/test_fastops.cxx | 27 +- core/vnl/tests/test_finite.cxx | 55 +- core/vnl/tests/test_hungarian_algorithm.cxx | 48 +- core/vnl/tests/test_inverse.cxx | 22 +- core/vnl/tests/test_math.cxx | 54 +- core/vnl/tests/test_matlab.cxx | 16 +- core/vnl/tests/test_matrix.cxx | 70 +- core/vnl/tests/test_matrix_exp.cxx | 6 +- core/vnl/tests/test_matrix_fixed.cxx | 58 +- core/vnl/tests/test_matrix_fixed_ref.cxx | 59 +- core/vnl/tests/test_na.cxx | 24 +- core/vnl/tests/test_numeric_traits.cxx | 43 +- core/vnl/tests/test_polynomial.cxx | 92 +- core/vnl/tests/test_pow_log.cxx | 12 +- core/vnl/tests/test_power.cxx | 20 +- core/vnl/tests/test_quaternion.cxx | 79 +- core/vnl/tests/test_random.cxx | 10 +- core/vnl/tests/test_rational.cxx | 58 +- core/vnl/tests/test_real_npolynomial.cxx | 12 +- core/vnl/tests/test_real_polynomial.cxx | 22 +- core/vnl/tests/test_rotation_matrix.cxx | 12 +- core/vnl/tests/test_sample.cxx | 8 +- .../tests/test_sparse_lst_sqr_function.cxx | 55 +- core/vnl/tests/test_sparse_matrix.cxx | 10 +- core/vnl/tests/test_sym_matrix.cxx | 7 +- core/vnl/tests/test_transpose.cxx | 2 +- core/vnl/tests/test_vector.cxx | 64 +- core/vnl/tests/test_vector_fixed_ref.cxx | 56 +- core/vnl/tests/test_vnl_index_sort.cxx | 8 +- core/vnl/vnl_T_n.h | 69 +- core/vnl/vnl_alloc.cxx | 28 +- core/vnl/vnl_alloc.h | 82 +- core/vnl/vnl_analytic_integrant.h | 5 +- core/vnl/vnl_bessel.cxx | 14 +- core/vnl/vnl_bessel.h | 9 +- core/vnl/vnl_beta.h | 18 +- core/vnl/vnl_bignum.cxx | 148 +- core/vnl/vnl_bignum.h | 836 +++++++++--- core/vnl/vnl_bignum_traits.h | 3 +- core/vnl/vnl_block.cxx | 2 +- core/vnl/vnl_block.h | 152 ++- core/vnl/vnl_c_na_vector.h | 61 +- core/vnl/vnl_c_na_vector.hxx | 85 +- core/vnl/vnl_c_vector.h | 198 ++- core/vnl/vnl_c_vector.hxx | 439 +++--- core/vnl/vnl_complex.h | 18 +- core/vnl/vnl_complex_ops.hxx | 152 +-- core/vnl/vnl_complex_traits.h | 236 +++- core/vnl/vnl_complexify.h | 108 +- core/vnl/vnl_copy.cxx | 38 +- core/vnl/vnl_copy.h | 10 +- core/vnl/vnl_cost_function.cxx | 22 +- core/vnl/vnl_cost_function.h | 81 +- core/vnl/vnl_cross.h | 48 +- core/vnl/vnl_cross_product_matrix.h | 39 +- core/vnl/vnl_crs_index.cxx | 8 +- core/vnl/vnl_crs_index.h | 52 +- core/vnl/vnl_decnum.cxx | 108 +- core/vnl/vnl_decnum.h | 1200 +++++++++++++---- core/vnl/vnl_decnum_traits.h | 3 +- core/vnl/vnl_definite_integral.h | 12 +- core/vnl/vnl_det.h | 42 +- core/vnl/vnl_det.hxx | 64 +- core/vnl/vnl_diag_matrix.h | 367 +++-- core/vnl/vnl_diag_matrix.hxx | 43 +- core/vnl/vnl_diag_matrix_fixed.h | 309 +++-- core/vnl/vnl_diag_matrix_fixed.hxx | 43 +- core/vnl/vnl_double_1x1.h | 2 +- core/vnl/vnl_double_1x2.h | 2 +- core/vnl/vnl_double_1x3.h | 2 +- core/vnl/vnl_double_2.h | 6 +- core/vnl/vnl_double_2x1.h | 2 +- core/vnl/vnl_double_2x2.h | 2 +- core/vnl/vnl_double_2x3.h | 33 +- core/vnl/vnl_double_3.h | 6 +- core/vnl/vnl_double_3x1.h | 2 +- core/vnl/vnl_double_3x2.h | 20 +- core/vnl/vnl_double_3x3.h | 2 +- core/vnl/vnl_double_3x4.h | 2 +- core/vnl/vnl_double_4.h | 2 +- core/vnl/vnl_double_4x3.h | 2 +- core/vnl/vnl_double_4x4.h | 2 +- core/vnl/vnl_drand48.cpp | 8 +- core/vnl/vnl_drand48.h | 6 +- core/vnl/vnl_erf.cxx | 12 +- core/vnl/vnl_erf.h | 17 +- core/vnl/vnl_error.cxx | 12 +- core/vnl/vnl_error.h | 24 +- core/vnl/vnl_fastops.cxx | 78 +- core/vnl/vnl_fastops.h | 74 +- core/vnl/vnl_file_matrix.h | 23 +- core/vnl/vnl_file_matrix.hxx | 10 +- core/vnl/vnl_file_vector.h | 23 +- core/vnl/vnl_file_vector.hxx | 10 +- core/vnl/vnl_finite.h | 927 +++++++++---- core/vnl/vnl_float_1x1.h | 2 +- core/vnl/vnl_float_1x2.h | 2 +- core/vnl/vnl_float_1x3.h | 2 +- core/vnl/vnl_float_2.h | 6 +- core/vnl/vnl_float_2x1.h | 2 +- core/vnl/vnl_float_2x2.h | 2 +- core/vnl/vnl_float_3.h | 6 +- core/vnl/vnl_float_3x1.h | 2 +- core/vnl/vnl_float_3x3.h | 2 +- core/vnl/vnl_float_3x4.h | 2 +- core/vnl/vnl_float_4.h | 2 +- core/vnl/vnl_float_4x3.h | 2 +- core/vnl/vnl_float_4x4.h | 2 +- core/vnl/vnl_fortran_copy.h | 12 +- core/vnl/vnl_fortran_copy.hxx | 15 +- core/vnl/vnl_fortran_copy_fixed.h | 12 +- core/vnl/vnl_fortran_copy_fixed.hxx | 8 +- core/vnl/vnl_fwd.h | 94 +- core/vnl/vnl_gamma.cxx | 26 +- core/vnl/vnl_gamma.h | 25 +- core/vnl/vnl_hungarian_algorithm.h | 70 +- core/vnl/vnl_hungarian_algorithm.hxx | 239 ++-- core/vnl/vnl_identity.h | 14 +- core/vnl/vnl_imag.h | 60 +- core/vnl/vnl_index_sort.h | 81 +- core/vnl/vnl_int_1x1.h | 2 +- core/vnl/vnl_int_2.h | 2 +- core/vnl/vnl_int_2x2.h | 2 +- core/vnl/vnl_int_3.h | 2 +- core/vnl/vnl_int_4.h | 2 +- core/vnl/vnl_int_matrix.cxx | 6 +- core/vnl/vnl_int_matrix.h | 25 +- core/vnl/vnl_integrant_fnct.h | 5 +- core/vnl/vnl_inverse.h | 280 ++-- core/vnl/vnl_least_squares_cost_function.h | 14 +- core/vnl/vnl_least_squares_function.cxx | 30 +- core/vnl/vnl_least_squares_function.h | 85 +- core/vnl/vnl_linear_operators_3.h | 14 +- core/vnl/vnl_linear_system.cxx | 6 +- core/vnl/vnl_linear_system.h | 41 +- core/vnl/vnl_math.cxx | 2 +- core/vnl/vnl_math.h | 987 +++++++++----- core/vnl/vnl_matlab_filewrite.cxx | 24 +- core/vnl/vnl_matlab_filewrite.h | 35 +- core/vnl/vnl_matlab_header.h | 53 +- core/vnl/vnl_matlab_print.h | 89 +- core/vnl/vnl_matlab_print.hxx | 182 ++- core/vnl/vnl_matlab_print2.h | 36 +- core/vnl/vnl_matlab_print_format.cxx | 2 +- core/vnl/vnl_matlab_print_format.h | 6 +- core/vnl/vnl_matlab_print_scalar.cxx | 243 ++-- core/vnl/vnl_matlab_print_scalar.h | 33 +- core/vnl/vnl_matlab_read.cxx | 211 ++- core/vnl/vnl_matlab_read.h | 103 +- core/vnl/vnl_matlab_write.cxx | 46 +- core/vnl/vnl_matlab_write.h | 18 +- core/vnl/vnl_matops.cxx | 56 +- core/vnl/vnl_matops.h | 29 +- core/vnl/vnl_matrix.h | 653 ++++++--- core/vnl/vnl_matrix.hxx | 869 ++++++------ core/vnl/vnl_matrix_exp.h | 10 +- core/vnl/vnl_matrix_exp.hxx | 34 +- core/vnl/vnl_matrix_fixed.h | 784 +++++++---- core/vnl/vnl_matrix_fixed.hxx | 558 ++++---- core/vnl/vnl_matrix_fixed_ref.h | 794 +++++++---- core/vnl/vnl_matrix_fixed_ref.hxx | 377 +++--- core/vnl/vnl_matrix_ref.h | 45 +- core/vnl/vnl_na.h | 61 +- core/vnl/vnl_nonlinear_minimizer.cxx | 11 +- core/vnl/vnl_nonlinear_minimizer.h | 247 ++-- core/vnl/vnl_numeric_traits.h | 213 +-- core/vnl/vnl_operators.h | 64 +- core/vnl/vnl_polynomial.h | 164 ++- core/vnl/vnl_polynomial.hxx | 132 +- core/vnl/vnl_power.h | 32 +- core/vnl/vnl_quaternion.h | 128 +- core/vnl/vnl_quaternion.hxx | 215 +-- core/vnl/vnl_random.cxx | 42 +- core/vnl/vnl_random.h | 277 ++-- core/vnl/vnl_rank.h | 36 +- core/vnl/vnl_rank.hxx | 228 ++-- core/vnl/vnl_rational.cxx | 46 +- core/vnl/vnl_rational.h | 780 ++++++++--- core/vnl/vnl_rational_traits.cxx | 6 +- core/vnl/vnl_rational_traits.h | 27 +- core/vnl/vnl_real.h | 60 +- core/vnl/vnl_real_npolynomial.cxx | 35 +- core/vnl/vnl_real_npolynomial.h | 183 ++- core/vnl/vnl_real_polynomial.cxx | 37 +- core/vnl/vnl_real_polynomial.h | 131 +- core/vnl/vnl_rotation_matrix.cxx | 18 +- core/vnl/vnl_rotation_matrix.h | 33 +- core/vnl/vnl_sample.cxx | 8 +- core/vnl/vnl_sample.h | 54 +- core/vnl/vnl_scalar_join_iterator.h | 86 +- core/vnl/vnl_scalar_join_iterator.hxx | 66 +- core/vnl/vnl_sparse_lst_sqr_function.cxx | 146 +- core/vnl/vnl_sparse_lst_sqr_function.h | 316 +++-- core/vnl/vnl_sparse_matrix.h | 230 ++-- core/vnl/vnl_sparse_matrix.hxx | 522 +++---- core/vnl/vnl_sparse_matrix_linear_system.cxx | 10 +- core/vnl/vnl_sparse_matrix_linear_system.h | 46 +- core/vnl/vnl_sse.h | 255 ++-- core/vnl/vnl_sym_matrix.h | 257 ++-- core/vnl/vnl_sym_matrix.hxx | 133 +- core/vnl/vnl_trace.h | 12 +- core/vnl/vnl_transpose.h | 54 +- core/vnl/vnl_unary_function.h | 19 +- core/vnl/vnl_unary_function.hxx | 9 +- core/vnl/vnl_vector.h | 590 +++++--- core/vnl/vnl_vector.hxx | 569 ++++---- core/vnl/vnl_vector_fixed.h | 779 +++++++---- core/vnl/vnl_vector_fixed.hxx | 148 +- core/vnl/vnl_vector_fixed_ref.h | 731 ++++++---- core/vnl/vnl_vector_fixed_ref.hxx | 84 +- core/vnl/vnl_vector_ref.h | 43 +- core/vnl/vnl_vector_ref.hxx | 12 +- core/vnl/xio/vnl_xio_matrix.h | 8 +- core/vnl/xio/vnl_xio_matrix.hxx | 39 +- core/vnl/xio/vnl_xio_matrix_fixed.h | 8 +- core/vnl/xio/vnl_xio_matrix_fixed.hxx | 39 +- core/vnl/xio/vnl_xio_quaternion.h | 8 +- core/vnl/xio/vnl_xio_quaternion.hxx | 32 +- core/vnl/xio/vnl_xio_vector.h | 8 +- core/vnl/xio/vnl_xio_vector.hxx | 21 +- core/vnl/xio/vnl_xio_vector_fixed.h | 8 +- core/vnl/xio/vnl_xio_vector_fixed.hxx | 25 +- core/vxl_version.h | 14 +- v3p/netlib/linalg/lsmrBase.cxx | 52 +- v3p/netlib/linalg/lsqrBase.cxx | 18 +- v3p/netlib/sparse/spFactor.c | 6 +- v3p/netlib/sparse/spSolve.c | 6 +- v3p/netlib/sparse/spUtils.c | 2 +- vcl/CMakeLists.txt | 2 +- vcl/internal/vcl_atomic_count_gcc.h | 40 +- vcl/internal/vcl_atomic_count_gcc_x86.h | 87 +- vcl/internal/vcl_atomic_count_pthreads.h | 104 +- vcl/internal/vcl_atomic_count_solaris.h | 52 +- vcl/internal/vcl_atomic_count_sync.h | 50 +- vcl/internal/vcl_atomic_count_win32.h | 54 +- vcl/internal/vcl_interlocked.h | 122 +- vcl/tests/test_algorithm.cxx | 7 +- vcl/tests/test_atomic_count.cxx | 33 +- vcl/tests/test_cctype.cxx | 25 +- vcl/tests/test_cmath.cxx | 58 +- vcl/tests/test_compiler.cxx | 89 +- vcl/tests/test_complex.cxx | 69 +- vcl/tests/test_cstdio.cxx | 59 +- vcl/tests/test_deque.cxx | 5 +- vcl/tests/test_driver.cxx | 117 +- vcl/tests/test_exception.cxx | 14 +- vcl/tests/test_fstream.cxx | 6 +- vcl/tests/test_include.cxx | 6 +- vcl/tests/test_iostream.cxx | 88 +- vcl/tests/test_iterator.cxx | 7 +- vcl/tests/test_limits.cxx | 179 +-- vcl/tests/test_list.cxx | 3 +- vcl/tests/test_map.cxx | 7 +- vcl/tests/test_memory.cxx | 83 +- vcl/tests/test_multimap.cxx | 31 +- vcl/tests/test_preprocessor.cxx | 13 +- vcl/tests/test_set.cxx | 5 +- vcl/tests/test_sstream.cxx | 29 +- vcl/tests/test_stlfwd.cxx | 12 +- vcl/tests/test_string.cxx | 26 +- vcl/tests/test_typename.cxx | 47 +- vcl/tests/test_vector.cxx | 62 +- vcl/vcl_algorithm.h | 5 +- vcl/vcl_atomic_count.h | 10 +- vcl/vcl_bitset.h | 5 +- vcl/vcl_cassert.h | 5 +- vcl/vcl_cctype.h | 5 +- vcl/vcl_cerrno.h | 5 +- vcl/vcl_cfloat.h | 5 +- vcl/vcl_ciso646.h | 5 +- vcl/vcl_climits.h | 5 +- vcl/vcl_clocale.h | 5 +- vcl/vcl_cmath.h | 5 +- vcl/vcl_compiler_detection.h | 12 +- vcl/vcl_complex.h | 5 +- vcl/vcl_csetjmp.h | 5 +- vcl/vcl_csignal.h | 5 +- vcl/vcl_cstdarg.h | 5 +- vcl/vcl_cstddef.h | 5 +- vcl/vcl_cstdio.h | 5 +- vcl/vcl_cstdlib.h | 5 +- vcl/vcl_cstring.h | 5 +- vcl/vcl_ctime.h | 5 +- vcl/vcl_cwchar.h | 5 +- vcl/vcl_cwctype.h | 5 +- vcl/vcl_deprecated.cxx | 4 +- vcl/vcl_deprecated.h | 61 +- vcl/vcl_exception.h | 5 +- vcl/vcl_fstream.h | 5 +- vcl/vcl_functional.h | 5 +- vcl/vcl_iomanip.h | 5 +- vcl/vcl_ios.h | 5 +- vcl/vcl_iosfwd.h | 5 +- vcl/vcl_iostream.h | 5 +- vcl/vcl_istream.h | 5 +- vcl/vcl_iterator.h | 5 +- vcl/vcl_legacy_aliases.h | 60 +- vcl/vcl_limits.h | 5 +- vcl/vcl_list.h | 5 +- vcl/vcl_locale.h | 5 +- vcl/vcl_map.h | 5 +- vcl/vcl_memory.h | 5 +- vcl/vcl_msvc_warnings.h | 32 +- vcl/vcl_numeric.h | 5 +- vcl/vcl_ostream.h | 5 +- vcl/vcl_queue.h | 5 +- vcl/vcl_set.h | 5 +- vcl/vcl_sstream.h | 5 +- vcl/vcl_stack.h | 5 +- vcl/vcl_stdexcept.h | 5 +- vcl/vcl_stlfwd.h | 5 +- vcl/vcl_streambuf.h | 5 +- vcl/vcl_string.h | 5 +- vcl/vcl_sys/time.h | 39 +- vcl/vcl_typeinfo.h | 5 +- vcl/vcl_utility.h | 5 +- vcl/vcl_valarray.h | 5 +- vcl/vcl_windows_header.h | 35 +- 499 files changed, 20730 insertions(+), 13003 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 268027fb446..42e6d7f21a5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,11 +13,9 @@ # # vxl-maintainers@lists.sf.net -cmake_minimum_required(VERSION 3.10.2) +cmake_minimum_required(VERSION 3.10.2...3.20.3) if(CMAKE_VERSION VERSION_LESS 3.12.0) cmake_policy(VERSION ${CMAKE_VERSION}) -else() - cmake_policy(VERSION 3.10.2...3.20.3) endif() if(NOT CMAKE_CXX_STANDARD) @@ -67,7 +65,7 @@ foreach(p endforeach() project(VXL #Project name must be all caps to have properly generated VXL_VERSION_* variables - VERSION 5.3.0.0 # defines #MAJOR,MINOR,PATCH,TWEAK} + VERSION 5.5.1.0 # defines #MAJOR,MINOR,PATCH,TWEAK} DESCRIPTION "A multi-platform collection of C++ software libraries for Computer Vision and Image Understanding." LANGUAGES CXX C) diff --git a/config/cmake/Modules/FindOpenJPEG2.cmake b/config/cmake/Modules/FindOpenJPEG2.cmake index c76bc44f4b3..d2a62eaa056 100644 --- a/config/cmake/Modules/FindOpenJPEG2.cmake +++ b/config/cmake/Modules/FindOpenJPEG2.cmake @@ -72,4 +72,3 @@ else() endif () endif() endif() - diff --git a/config/cmake/Modules/NewCMake/FindDC1394.cmake b/config/cmake/Modules/NewCMake/FindDC1394.cmake index 1db1ff50c48..c1b0faa72bf 100644 --- a/config/cmake/Modules/NewCMake/FindDC1394.cmake +++ b/config/cmake/Modules/NewCMake/FindDC1394.cmake @@ -26,8 +26,3 @@ if(APPLE AND DC1394_FOUND) "-framework CoreServices" "-framework IOKit" ) endif() - - - - - diff --git a/config/cmake/Modules/NewCMake/FindGEOTIFF.cmake b/config/cmake/Modules/NewCMake/FindGEOTIFF.cmake index 1387fd23d16..ab21e84bff0 100644 --- a/config/cmake/Modules/NewCMake/FindGEOTIFF.cmake +++ b/config/cmake/Modules/NewCMake/FindGEOTIFF.cmake @@ -30,4 +30,3 @@ if(GEOTIFF_INCLUDE_DIR) set( GEOTIFF_LIBRARIES ${GEOTIFF_LIBRARY} ) endif() endif() - diff --git a/config/cmake/Modules/NewCMake/FindSIMVoleon.cmake b/config/cmake/Modules/NewCMake/FindSIMVoleon.cmake index e6912100179..aa73641eb49 100644 --- a/config/cmake/Modules/NewCMake/FindSIMVoleon.cmake +++ b/config/cmake/Modules/NewCMake/FindSIMVoleon.cmake @@ -72,4 +72,3 @@ endif() if(SIMVOLEON_LIBRARY) set( SIMVOLEON_FOUND "YES" ) endif() - diff --git a/config/cmake/Modules/NewCMake/FindWin32SDK.cmake b/config/cmake/Modules/NewCMake/FindWin32SDK.cmake index 4d75b556f99..fea7ff9cc87 100644 --- a/config/cmake/Modules/NewCMake/FindWin32SDK.cmake +++ b/config/cmake/Modules/NewCMake/FindWin32SDK.cmake @@ -52,5 +52,3 @@ if( WIN32 ) ) endif() - - diff --git a/config/cmake/Modules/readme.txt b/config/cmake/Modules/readme.txt index 76d21095110..38a6a300c2d 100644 --- a/config/cmake/Modules/readme.txt +++ b/config/cmake/Modules/readme.txt @@ -17,5 +17,3 @@ If you are adding some new functionality to VXL and you need a third party libra that VXL can depend on this additional library) then you can temporarily add the file to the NewCMake subdirectory. Please also submit it to CMake at cmake@www.cmake.org, and delete it from the VXL repository when the next version of CMake is widely available. - - diff --git a/config/cmake/config/vxlGetCXXCompilerVersion.cxx b/config/cmake/config/vxlGetCXXCompilerVersion.cxx index dd3c67bf927..11f59550986 100644 --- a/config/cmake/config/vxlGetCXXCompilerVersion.cxx +++ b/config/cmake/config/vxlGetCXXCompilerVersion.cxx @@ -1,13 +1,14 @@ #include -int main() +int +main() { - #if __cplusplus >= VXL_CXX_TEST_VERSION - std::cout << __cplusplus << ">=" << VXL_CXX_TEST_VERSION << std::endl; - return 0; - #else - #error "VERSION TEST FAILED" VXL_CXX_TEST_VERSION - std::cout << __cplusplus << ">=" << VXL_CXX_TEST_VERSION << std::endl; - return 1; - #endif +#if __cplusplus >= VXL_CXX_TEST_VERSION + std::cout << __cplusplus << ">=" << VXL_CXX_TEST_VERSION << std::endl; + return 0; +#else +# error "VERSION TEST FAILED" VXL_CXX_TEST_VERSION + std::cout << __cplusplus << ">=" << VXL_CXX_TEST_VERSION << std::endl; + return 1; +#endif } diff --git a/config/cmake/config/vxl_platform_tests.cxx b/config/cmake/config/vxl_platform_tests.cxx index 3eeb9f118f6..9595078dac4 100644 --- a/config/cmake/config/vxl_platform_tests.cxx +++ b/config/cmake/config/vxl_platform_tests.cxx @@ -3,9 +3,14 @@ #ifdef VXL_UNISTD_USLEEP_IS_VOID // VXL_UNISTD_USLEEP_IS_VOID is set to 1 if this test fails -#include +# include -int main() { int x = usleep(0); return x*0; } +int +main() +{ + int x = usleep(0); + return x * 0; +} #endif // VXL_UNISTD_USLEEP_IS_VOID //------------------------------------- #ifdef VCL_NUMERIC_LIMITS_HAS_INFINITY @@ -13,10 +18,11 @@ int main() { int x = usleep(0); return x*0; } // Several versions of gcc (3.0, 3.1, and 3.2) come with a // numeric_limits that reports that they have no infinity. -#include -int main() { - return std::numeric_limits::has_infinity && - std::numeric_limits::has_infinity ? 0 : 1; +# include +int +main() +{ + return std::numeric_limits::has_infinity && std::numeric_limits::has_infinity ? 0 : 1; } #endif // VCL_NUMERIC_LIMITS_HAS_INFINITY @@ -29,30 +35,33 @@ int main() { // functional. (It can't be cast to a double, for example.) // CHAR_BIT is the number of bits per char. -#include -#ifndef CHAR_BIT -# define CHAR_BIT 8 -#endif +# include +# ifndef CHAR_BIT +# define CHAR_BIT 8 +# endif -#include "config.h" +# include "config.h" -#if INTEGRAL_TYPE -double cast( THE_TYPE a, unsigned THE_TYPE b, signed THE_TYPE c ) +# if INTEGRAL_TYPE +double +cast(THE_TYPE a, unsigned THE_TYPE b, signed THE_TYPE c) { - return double( a ) + double( b ) + double( c ); + return double(a) + double(b) + double(c); } -#else // INTEGRAL_TYPE -double cast( THE_TYPE a ) +# else // INTEGRAL_TYPE +double +cast(THE_TYPE a) { - return double( a ); + return double(a); } -#endif // INTEGRAL_TYPE +# endif // INTEGRAL_TYPE // These declarations conflict unless the sizes match. extern int (*verify_size)[sizeof(THE_TYPE) * CHAR_BIT]; extern int (*verify_size)[THE_SIZE]; -int main() +int +main() { return 0; } @@ -63,18 +72,19 @@ int main() #ifdef VCL_HAS_LFS // Return 1 if compiler has #define-switchable Large File Support -#define _LARGEFILE_SOURCE -#define _FILE_OFFSET_BITS 64 +# define _LARGEFILE_SOURCE +# define _FILE_OFFSET_BITS 64 -#include -#include +# include +# include -int main(int argc, char * argv[]) +int +main(int argc, char * argv[]) { - if( sizeof(std::streamoff)==8 ) - return 0 ; - else - return 1; + if (sizeof(std::streamoff) == 8) + return 0; + else + return 1; } #endif // VCL_HAS_LFS @@ -84,10 +94,15 @@ int main(int argc, char * argv[]) #ifdef VXL_HAS_DBGHELP_H // This is a Windows header, and needs windows.h included first to make it compile properly. -#include -#include +# include +# include -int main() { MINIDUMP_EXCEPTION_INFORMATION dummy; return 0; } +int +main() +{ + MINIDUMP_EXCEPTION_INFORMATION dummy; + return 0; +} #endif // VXL_HAS_DBGHELP_H //------------------------------------- @@ -95,28 +110,34 @@ int main() { MINIDUMP_EXCEPTION_INFORMATION dummy; return 0; } //------------------------------------- #ifdef VXL_HAS_WIN_WCHAR_T -#ifdef _WCHAR_T_DEFINED -#include -int main() +# ifdef _WCHAR_T_DEFINED +# include +int +main() { - wchar_t buf [10]; + wchar_t buf[10]; buf[0] = L'1'; buf[1] = L'\0'; return 0; } -#else - int main() { return 1; } -#endif +# else +int +main() +{ + return 1; +} +# endif #endif //------------------------------------- #ifdef VXL_HAS_MM_MALLOC -#include -int main() +# include +int +main() { - void* x = _mm_malloc(4*sizeof(float),16); + void * x = _mm_malloc(4 * sizeof(float), 16); _mm_free(x); return 0; } @@ -125,10 +146,11 @@ int main() //------------------------------------- #ifdef VXL_HAS_ALIGNED_MALLOC -#include -int main() +# include +int +main() { - void* x = _aligned_malloc(4*sizeof(float),16); + void * x = _aligned_malloc(4 * sizeof(float), 16); _aligned_free(x); return 0; } @@ -137,10 +159,11 @@ int main() //------------------------------------- #ifdef VXL_HAS_MINGW_ALIGNED_MALLOC -#include -int main() +# include +int +main() { - void* x = __mingw_aligned_malloc(4*sizeof(float),16); + void * x = __mingw_aligned_malloc(4 * sizeof(float), 16); __mingw_aligned_free(x); return 0; } @@ -149,10 +172,11 @@ int main() //------------------------------------- #ifdef VXL_HAS_POSIX_MEMALIGN -#include -int main() +# include +int +main() { - void* x = memalign(16,4*sizeof(float)); + void * x = memalign(16, 4 * sizeof(float)); free(x); return 0; } @@ -161,18 +185,19 @@ int main() //------------------------------------- #if defined(VXL_HAS_SSE2_HARDWARE_SUPPORT) || defined(VXL_SSE2_HARDWARE_SUPPORT_POSSIBLE) -#include -int main() +# include +int +main() { - //try to do some sse2 calculations - double d_a[] = { 6.75, 3.42 }; - double d_b[] = { 2.3, 9.2 }; - double res[2] = {0.0}; + // try to do some sse2 calculations + double d_a[] = { 6.75, 3.42 }; + double d_b[] = { 2.3, 9.2 }; + double res[2] = { 0.0 }; __m128d z; - z = _mm_mul_pd(_mm_loadu_pd(d_a),_mm_loadu_pd(d_b)); + z = _mm_mul_pd(_mm_loadu_pd(d_a), _mm_loadu_pd(d_b)); - _mm_storeu_pd(res,z); + _mm_storeu_pd(res, z); return 0; } diff --git a/config/cmake/config/vxl_shared_link_test/shared_src.cxx b/config/cmake/config/vxl_shared_link_test/shared_src.cxx index 8ab85a317db..7c6e9ad8ed7 100644 --- a/config/cmake/config/vxl_shared_link_test/shared_src.cxx +++ b/config/cmake/config/vxl_shared_link_test/shared_src.cxx @@ -1,7 +1,9 @@ -void vxl_static_test_function(int i); +void +vxl_static_test_function(int i); -void vxl_shared_test_function(int i) +void +vxl_shared_test_function(int i) { vxl_static_test_function(i); } diff --git a/config/cmake/config/vxl_shared_link_test/static_src.cxx b/config/cmake/config/vxl_shared_link_test/static_src.cxx index 272c46eaf8c..12f4bc55459 100644 --- a/config/cmake/config/vxl_shared_link_test/static_src.cxx +++ b/config/cmake/config/vxl_shared_link_test/static_src.cxx @@ -1,4 +1,4 @@ -void vxl_static_test_function(int i) -{ -} +void +vxl_static_test_function(int i) +{} diff --git a/config/cmake/config/vxl_utils.cmake b/config/cmake/config/vxl_utils.cmake index c1e728783b1..953a5cc8916 100644 --- a/config/cmake/config/vxl_utils.cmake +++ b/config/cmake/config/vxl_utils.cmake @@ -70,7 +70,7 @@ endmacro() # not its default value; otherwise, the relative path in # the vxl source tree is used. # DISABLE_MSVC_MP Disable automatic addition of the "/MP" flag in MSVC -# builds. Avoids MSVC warning C5102: ignoring invalid +# builds. Avoids MSVC warning C5102: ignoring invalid # command-line macro definition '/MP' # function( vxl_add_library ) diff --git a/config/cmake/doxygen/doxy-notes.txt b/config/cmake/doxygen/doxy-notes.txt index 392ef4798e3..c046f394dd1 100644 --- a/config/cmake/doxygen/doxy-notes.txt +++ b/config/cmake/doxygen/doxy-notes.txt @@ -42,4 +42,4 @@ doxygen_makeall.cmake 4) Creates a directory ${DOXYGEN_OUTPUT_DIR}/html/${library}/html 5) Runs doxygen using the parameter file ${CMAKE_BINARY_DIR}/doxy/output/doxyfile.${libname} 6) Creates a global index, which expects data for each library to be in somewhere like: - obj/doxy/html/core/vnl/html/index.html \ No newline at end of file + obj/doxy/html/core/vnl/html/index.html diff --git a/config/cmake/doxygen/doxy_header.html b/config/cmake/doxygen/doxy_header.html index 075131e029d..98b25421744 100644 --- a/config/cmake/doxygen/doxy_header.html +++ b/config/cmake/doxygen/doxy_header.html @@ -8,4 +8,4 @@ - \ No newline at end of file + diff --git a/core/testlib/testlib_main.cxx b/core/testlib/testlib_main.cxx index dcf61a41a39..034d23ff354 100644 --- a/core/testlib/testlib_main.cxx +++ b/core/testlib/testlib_main.cxx @@ -171,7 +171,7 @@ testlib_main(int argc, char * argv[]) << "----------------------------------------\n" << std::flush; - int result = testlib_run_test_unit(i, argc, argv); + const int result = testlib_run_test_unit(i, argc, argv); std::cout << "----------------------------------------\n" << testlib_test_name_[i] << " returned " << result << ' ' << (result == 0 ? "(PASS)" : "(FAIL)") << '\n' diff --git a/core/testlib/testlib_register.h b/core/testlib/testlib_register.h index e6a73020db8..eb141d24797 100644 --- a/core/testlib/testlib_register.h +++ b/core/testlib/testlib_register.h @@ -27,22 +27,22 @@ # include #endif -typedef int (*TestMainFunction)( int, char*[] ); +typedef int (*TestMainFunction)(int, char *[]); //: Declare the existence of the test. // If you DECLARE( x ), then you will need to define a function int x_main(int,char*[]). #ifdef _MSC_VER -#define DECLARE( testname ) int _cdecl testname ## _main ( int argc, char* argv[] ) +# define DECLARE(testname) int _cdecl testname##_main(int argc, char * argv[]) #else -#define DECLARE( testname ) int testname ## _main ( int argc, char* argv[] ) +# define DECLARE(testname) int testname##_main(int argc, char * argv[]) #endif -void testlib_register_test(const std::string &, TestMainFunction); +void +testlib_register_test(const std::string &, TestMainFunction); //: Register the test with the driver. // \param testname should be the same as one of the tests declared with DECLARE. -#define REGISTER( testname ) \ - testlib_register_test(#testname, & testname ## _main ); +#define REGISTER(testname) testlib_register_test(#testname, &testname##_main); //: Define the main() routine for this test driver. // This allows the main function to be defined in the driver code @@ -50,14 +50,15 @@ void testlib_register_test(const std::string &, TestMainFunction); // "awf-weirdness". This also means that functionality from the test // library, such as testlib_root_dir, can be used even if it is not // used to create a test driver. -#define DEFINE_MAIN \ - int testlib_main(int,char*[]); \ - void testlib_cleanup(); \ - int main( int argc, char* argv[] ) { \ - register_tests(); \ - int retval = testlib_main( argc, argv ); \ - testlib_cleanup(); \ - return retval; \ - } +#define DEFINE_MAIN \ + int testlib_main(int, char *[]); \ + void testlib_cleanup(); \ + int main(int argc, char * argv[]) \ + { \ + register_tests(); \ + int retval = testlib_main(argc, argv); \ + testlib_cleanup(); \ + return retval; \ + } #endif // TESTLIB_REGISTER_H_ diff --git a/core/testlib/testlib_root_dir.cxx b/core/testlib/testlib_root_dir.cxx index 7fa4f268d99..67efb2f9024 100644 --- a/core/testlib/testlib_root_dir.cxx +++ b/core/testlib/testlib_root_dir.cxx @@ -19,17 +19,17 @@ testlib_root_dir() { char * ptr = std::getenv("VXLSRC"); if (ptr) - return std::string(ptr); + return { ptr }; ptr = std::getenv("VCLSRC"); if (ptr) - return std::string(ptr); + return { ptr }; ptr = std::getenv("VXL_SRC"); if (ptr) - return std::string(ptr); + return { ptr }; - return std::string(VCL_SOURCE_ROOT_DIR); + return { VCL_SOURCE_ROOT_DIR }; // std::cerr<<"ERROR: testlib_root_dir() Unable to retrieve directory from\n" // <<"$VCLSRC or $VXLSRC or $VXL_SRC. Sorry.\n"; diff --git a/core/testlib/testlib_root_dir.h b/core/testlib/testlib_root_dir.h index 3579af5acdf..211fec9fcd0 100644 --- a/core/testlib/testlib_root_dir.h +++ b/core/testlib/testlib_root_dir.h @@ -27,6 +27,7 @@ // If another build system is used in which this is not created, // the function will return the value of either of the environment // variables: VXLSRC, VCLSRC or VXL_SRC in that order. -std::string testlib_root_dir(); +std::string +testlib_root_dir(); #endif // testlib_root_dir_h_ diff --git a/core/testlib/testlib_test.cxx b/core/testlib/testlib_test.cxx index f0eaf9f3ab9..a25b6ee7e19 100644 --- a/core/testlib/testlib_test.cxx +++ b/core/testlib/testlib_test.cxx @@ -114,7 +114,7 @@ void testlib_test_assert_near(const std::string & msg, double expr, double target, double tol) { std::cout << msg << " should be " << target << ", is " << expr << ", " << std::flush; - double diff = std::abs(expr - target); + const double diff = std::abs(expr - target); if (target != 0.0 && diff != 0.0) std::cout << "difference " << diff << ", " << std::flush; testlib_test_perform(diff <= tol); @@ -124,7 +124,7 @@ void testlib_test_assert_near(const std::string & msg, std::complex expr, std::complex target, double tol) { std::cout << msg << " should be " << target << ", is " << expr << ", " << std::flush; - double diff = std::abs(expr - target); + const double diff = std::abs(expr - target); if (target != std::complex(0, 0) && diff != 0.0) std::cout << "difference " << diff << ", " << std::flush; testlib_test_perform(diff <= tol); @@ -139,7 +139,7 @@ testlib_test_assert_near_relative(const std::string & msg, double expr, double t max = std::abs(expr); if (max == 0.0 || target == 0.0) max = 1.0; - double diff = std::abs(expr - target) / max; + const double diff = std::abs(expr - target) / max; if (target != 0.0 && diff != 0.0) std::cout << "relative difference " << diff << ", " << std::flush; testlib_test_perform(diff <= tol); @@ -157,7 +157,7 @@ testlib_test_assert_near_relative(const std::string & msg, max = std::abs(expr); if (max == 0.0 || target == std::complex(0, 0)) max = 1.0; - double diff = std::abs(expr - target) / max; + const double diff = std::abs(expr - target) / max; if (target != std::complex(0, 0) && diff != 0.0) std::cout << "relative difference " << diff << ", " << std::flush; testlib_test_perform(diff <= tol); @@ -167,7 +167,7 @@ void testlib_test_assert_far(const std::string & msg, double expr, double target, double tol) { std::cout << msg << " should not be " << target << ", is " << expr << ", " << std::flush; - double diff = std::abs(expr - target); + const double diff = std::abs(expr - target); if (target != 0.0 && diff != 0.0) std::cout << "difference " << diff << ", " << std::flush; testlib_test_perform(diff > tol); @@ -177,7 +177,7 @@ void testlib_test_assert_far(const std::string & msg, std::complex expr, std::complex target, double tol) { std::cout << msg << " should not be " << target << ", is " << expr << ", " << std::flush; - double diff = std::abs(expr - target); + const double diff = std::abs(expr - target); if (target != std::complex(0, 0) && diff != 0.0) std::cout << "difference " << diff << ", " << std::flush; testlib_test_perform(diff > tol); @@ -187,7 +187,7 @@ void testlib_test_assert_equal(const std::string & msg, long expr, long target) { std::cout << msg << " should be " << target << ", is " << expr << ", " << std::flush; - long diff = std::abs(expr - target); + const long diff = std::abs(expr - target); if (target != 0 && diff != 0) std::cout << "difference " << diff << ", " << std::flush; testlib_test_perform(diff == 0); diff --git a/core/testlib/testlib_test.h b/core/testlib/testlib_test.h index e070f2aacce..941652ada45 100644 --- a/core/testlib/testlib_test.h +++ b/core/testlib/testlib_test.h @@ -16,38 +16,51 @@ #include //: initialise test counters, check test name 'name' exists -void testlib_test_start(const char* name = nullptr); +void +testlib_test_start(const char * name = nullptr); //: increment number of tests, then output msg -void testlib_test_begin(const char* msg); +void +testlib_test_begin(const char * msg); //: increment success/failure counters -void testlib_test_perform(bool success); +void +testlib_test_perform(bool success); //: output summary of tests performed -int testlib_test_summary(); +int +testlib_test_summary(); //: output msg, then perform test in expr -void testlib_test_assert(const std::string& msg, bool expr); +void +testlib_test_assert(const std::string & msg, bool expr); //: output msg, then perform test to see if expr is within tol of target -void testlib_test_assert_near(const std::string& msg, double expr, - double target = 0, double tol = 1e-12); +void +testlib_test_assert_near(const std::string & msg, double expr, double target = 0, double tol = 1e-12); //: output msg, then perform test to see if expr is within tol of target -void testlib_test_assert_near(const std::string& msg, std::complex expr, - std::complex target, double tol = 1e-12); +void +testlib_test_assert_near(const std::string & msg, + std::complex expr, + std::complex target, + double tol = 1e-12); //: output msg, then test to see if expr is within relative tol of target -void testlib_test_assert_near_relative(const std::string& msg, double expr, - double target = 0, double tol = 1e-12); +void +testlib_test_assert_near_relative(const std::string & msg, double expr, double target = 0, double tol = 1e-12); //: output msg, then test to see if expr is within relative tol of target -void testlib_test_assert_near_relative(const std::string& msg, - std::complex expr, - std::complex target, - double tol = 1e-12); +void +testlib_test_assert_near_relative(const std::string & msg, + std::complex expr, + std::complex target, + double tol = 1e-12); //: output msg, then perform test to see if expr is not within tol of target -void testlib_test_assert_far(const std::string& msg, double expr, - double target = 0, double tol = 1e-12); +void +testlib_test_assert_far(const std::string & msg, double expr, double target = 0, double tol = 1e-12); //: output msg, then perform test to see if expr is not within tol of target -void testlib_test_assert_far(const std::string& msg, std::complex expr, - std::complex target, double tol = 1e-12); +void +testlib_test_assert_far(const std::string & msg, + std::complex expr, + std::complex target, + double tol = 1e-12); //: output msg, then perform test to see if expr is equal to target -void testlib_test_assert_equal(const std::string& msg, long expr, long target); +void +testlib_test_assert_equal(const std::string & msg, long expr, long target); #define Assert testlib_test_assert #define AssertNear testlib_test_assert_near @@ -57,90 +70,126 @@ void testlib_test_assert_equal(const std::string& msg, long expr, long target); #define START(s) testlib_test_start(s) //: TEST function, s is message, test to see if p==v -#define TEST(s,p,v) \ -do { \ - testlib_test_begin(s); \ - testlib_test_perform((p)==(v)); \ -} while (false) +#define TEST(s, p, v) \ + do \ + { \ + testlib_test_begin(s); \ + testlib_test_perform((p) == (v)); \ + } while (false) //: TEST function, s is message, test to see if p==v for integral values -#define TEST_EQUAL(s,p,v) \ -do { \ - testlib_test_begin(s); \ - testlib_test_assert_equal("",p,v); \ -} while (false) +#define TEST_EQUAL(s, p, v) \ + do \ + { \ + testlib_test_begin(s); \ + testlib_test_assert_equal("", p, v); \ + } while (false) //: TEST function, s is message, test to see if p is close to v, tolerance t -#define TEST_NEAR(s,p,v,t) \ -do { \ - testlib_test_begin(s); \ - testlib_test_assert_near("",p,v,t); \ -} while (false) +#define TEST_NEAR(s, p, v, t) \ + do \ + { \ + testlib_test_begin(s); \ + testlib_test_assert_near("", p, v, t); \ + } while (false) //: TEST function, message s, test to see if (p-v)/p is small compared to t -#define TEST_NEAR_REL(s,p,v,t) \ -do { \ - testlib_test_begin(s); \ - testlib_test_assert_near_relative("",p,v,t); \ -} while (false) +#define TEST_NEAR_REL(s, p, v, t) \ + do \ + { \ + testlib_test_begin(s); \ + testlib_test_assert_near_relative("", p, v, t); \ + } while (false) //: TEST function, s is message, test to see if p is far from v, tolerance t -#define TEST_FAR(s,p,v,t) \ -do { \ - testlib_test_begin(s); \ - testlib_test_assert_far("",p,v,t); \ -} while (false) +#define TEST_FAR(s, p, v, t) \ + do \ + { \ + testlib_test_begin(s); \ + testlib_test_assert_far("", p, v, t); \ + } while (false) //: run x, s is message, then test to see if p==v -#define TEST_RUN(s,x,p,v) \ -do { \ - testlib_test_begin(s); \ - x; \ - testlib_test_perform((p)==(v)); \ -} while (false) +#define TEST_RUN(s, x, p, v) \ + do \ + { \ + testlib_test_begin(s); \ + x; \ + testlib_test_perform((p) == (v)); \ + } while (false) //: Summarise test #define SUMMARY() return testlib_test_summary() //: Run a singleton test function -#define RUN_TEST_FUNC(x) \ - testlib_test_start(#x); x(); return testlib_test_summary() +#define RUN_TEST_FUNC(x) \ + testlib_test_start(#x); \ + x(); \ + return testlib_test_summary() //: Declare the main function. -#define MAIN( testname ) \ - int testname ## _main(int,char*[]) +#define MAIN(testname) int testname##_main(int, char *[]) //: Declare the main function with parameter passing. -#define MAIN_ARGS( testname ) \ - int testname ## _main(int argc, char* argv[]) +#define MAIN_ARGS(testname) int testname##_main(int argc, char * argv[]) //: A simplified version of the main test, just in one line. // Avoids compiler warnings about "unused argc and argv". -#define TESTMAIN( testname ) \ - int testname ## _main(int,char*[]) { START(#testname); testname(); SUMMARY(); } +#define TESTMAIN(testname) \ + int testname##_main(int, char *[]) \ + { \ + START(#testname); \ + testname(); \ + SUMMARY(); \ + } //: A simplified version of the main test, just in one line. // This (new) variant is to be used with the (new) CMake GENERATE_TEST_DRIVER() -#define TEST_MAIN( testname ) \ - int testname(int,char*[]) { START(#testname); testname(); SUMMARY(); } +#define TEST_MAIN(testname) \ + int testname(int, char *[]) \ + { \ + START(#testname); \ + testname(); \ + SUMMARY(); \ + } //: A simplified version of the main test, with parameter passing. -#define TESTMAIN_ARGS( testname ) \ - int testname ## _main(int argc, char*argv[]) { START(#testname); testname(argc,argv); SUMMARY(); } +#define TESTMAIN_ARGS(testname) \ + int testname##_main(int argc, char * argv[]) \ + { \ + START(#testname); \ + testname(argc, argv); \ + SUMMARY(); \ + } //: A simplified version of the main test, with parameter passing. // This (new) variant is to be used with the (new) CMake GENERATE_TEST_DRIVER() -#define TEST_MAIN_ARGS( testname ) \ - int testname(int argc, char*argv[]) { START(#testname); testname(argc,argv); SUMMARY(); } +#define TEST_MAIN_ARGS(testname) \ + int testname(int argc, char * argv[]) \ + { \ + START(#testname); \ + testname(argc, argv); \ + SUMMARY(); \ + } //: Another simplified main test. To be used in a standalone executable. #undef TESTLIB_DEFINE_MAIN #define TESTLIB_DEFINE_MAIN(testname) \ - int main() { START(#testname); testname(); return testlib_test_summary(); } + int main() \ + { \ + START(#testname); \ + testname(); \ + return testlib_test_summary(); \ + } //: A simplified main test with parameter passing. To be used in a standalone executable. #undef TESTLIB_DEFINE_MAIN_ARGS #define TESTLIB_DEFINE_MAIN_ARGS(testname) \ - int main(int argc, char * argv[]) { START(#testname); testname(argc,argv); SUMMARY(); } + int main(int argc, char * argv[]) \ + { \ + START(#testname); \ + testname(argc, argv); \ + SUMMARY(); \ + } #endif // testlib_test_h_ diff --git a/core/testlib/tests/test_root_dir.cxx b/core/testlib/tests/test_root_dir.cxx index 40ceafae0ab..c763a8269e0 100644 --- a/core/testlib/tests/test_root_dir.cxx +++ b/core/testlib/tests/test_root_dir.cxx @@ -10,7 +10,7 @@ static void test_root_dir() { // Check that a file exists - std::string path = testlib_root_dir() + "/core/testlib/testlib_root_dir.h"; + const std::string path = testlib_root_dir() + "/core/testlib/testlib_root_dir.h"; std::fstream is(path.c_str(), std::ios::in); diff --git a/core/vnl/algo/tests/test_algo.cxx b/core/vnl/algo/tests/test_algo.cxx index 6932dbfe2cc..3c7cafc4e5e 100644 --- a/core/vnl/algo/tests/test_algo.cxx +++ b/core/vnl/algo/tests/test_algo.cxx @@ -45,8 +45,8 @@ static void test_adjugate() { int data[] = { 1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, -1, -1, 1 }; - vnl_matrix m(data, 4, 4); - vnl_matrix m_adj = vnl_adjugate(m); + const vnl_matrix m(data, 4, 4); + const vnl_matrix m_adj = vnl_adjugate(m); vnl_matrix identity(4, 4); identity.set_identity(); TEST("vnl_adjugate", (m * m_adj - 16 * identity).array_inf_norm(), 0); @@ -56,14 +56,14 @@ static void test_matrix_inverse() { double data[] = { 1., -1., 1., -1., 1., 1., -1., -1., 1., 1., 1., 1., 1., -1., -1., 1. }; - vnl_matrix m(data, 4, 4); + const vnl_matrix m(data, 4, 4); vnl_svd_economy svde(m); vnl_matrix V = svde.V(); vnl_svd svd(m); vnl_matrix V0 = svd.V(); TEST_NEAR("vnl_svd_economy", V[0][1], V0[0][1], 1e-6); - vnl_matrix inv{ vnl_matrix_inverse(m).as_matrix() }; + const vnl_matrix inv{ vnl_matrix_inverse(m).as_matrix() }; vnl_matrix identity(4, 4); identity.set_identity(); TEST_NEAR("vnl_matrix_inverse", (m * inv - identity).array_inf_norm(), 0, 1e-6); @@ -107,13 +107,14 @@ class F_test_powell : public vnl_cost_function : vnl_cost_function(2) {} double - f(vnl_vector const & x) override + f(const vnl_vector & x) override { - double u = x[0] - x[1] * x[1], v = x[1] - 1; + const double u = x[0] - x[1] * x[1]; + const double v = x[1] - 1; return u * u + v * v + 1; } void - gradf(vnl_vector const & x, vnl_vector & g) override + gradf(const vnl_vector & x, vnl_vector & g) override { g[0] = 2 * x[0] - 2 * x[1] * x[1]; g[1] = 4 * x[1] * x[1] * x[1] - 4 * x[0] * x[1] + 2 * x[1] - 2; @@ -128,12 +129,12 @@ class F_broken : public vnl_cost_function : vnl_cost_function(1) {} double - f(vnl_vector const &) override + f(const vnl_vector &) override { return 0; } void - gradf(vnl_vector const &, vnl_vector & gradient) override + gradf(const vnl_vector &, vnl_vector & gradient) override { gradient[0] = 1; } @@ -153,7 +154,7 @@ test_powell() F_broken fb; vnl_vector x2(1, 0); vnl_conjugate_gradient cg2(fb); - bool rv = cg2.minimize(x2); + const bool rv = cg2.minimize(x2); TEST("vnl_conjugate_gradient on broken function should fail", rv, false); @@ -215,7 +216,7 @@ class F_test_discrete_diff : public vnl_least_squares_function : vnl_least_squares_function(2, 2, no_gradient) {} void - f(vnl_vector const & x, vnl_vector & fx) override + f(const vnl_vector & x, vnl_vector & fx) override { fx[0] = x[0] - x[1] * x[1]; fx[1] = x[1] - 1; @@ -226,7 +227,7 @@ static void test_discrete_diff() { F_test_discrete_diff f; - double h = 0.1; + const double h = 0.1; vnl_vector x(2); x[0] = 5.0; x[1] = 9.0; @@ -240,9 +241,14 @@ test_discrete_diff() static void test_generalized_schur() { - vnl_matrix A(4, 4, 0.0f), B(4, 4, 0.0f), L(4, 4, 1.0f), R(4, 4, 1.0f); - vnl_vector ar(4, 0.0f), ai(4, 0.0f), b(4, 0.0f); - bool r = vnl_generalized_schur(&A, &B, &ar, &ai, &b, &L, &R); + vnl_matrix A(4, 4, 0.0f); + vnl_matrix B(4, 4, 0.0f); + vnl_matrix L(4, 4, 1.0f); + vnl_matrix R(4, 4, 1.0f); + vnl_vector ar(4, 0.0f); + vnl_vector ai(4, 0.0f); + vnl_vector b(4, 0.0f); + const bool r = vnl_generalized_schur(&A, &B, &ar, &ai, &b, &L, &R); TEST("vnl_generalized_schur", r, true); } diff --git a/core/vnl/algo/tests/test_bracket_minimum.cxx b/core/vnl/algo/tests/test_bracket_minimum.cxx index ddb6c6382ba..5b1ab01893d 100644 --- a/core/vnl/algo/tests/test_bracket_minimum.cxx +++ b/core/vnl/algo/tests/test_bracket_minimum.cxx @@ -26,7 +26,7 @@ struct bm_quartic1 : public vnl_cost_function double f(const vnl_vector & x) override { - double y = (2 - x[0]) * (2 - x[0]); + const double y = (2 - x[0]) * (2 - x[0]); return y * y + 10; } }; @@ -35,8 +35,12 @@ void test_bracket_minimum() { bm_square1 f1; - double a = 5, b = 6, c; - double fa, fb, fc; + double a = 5; + double b = 6; + double c; + double fa; + double fb; + double fc; vnl_bracket_minimum(f1, a, b, c, fa, fb, fc); diff --git a/core/vnl/algo/tests/test_brent_minimizer.cxx b/core/vnl/algo/tests/test_brent_minimizer.cxx index 44e500d05b4..4dbfcac6c32 100644 --- a/core/vnl/algo/tests/test_brent_minimizer.cxx +++ b/core/vnl/algo/tests/test_brent_minimizer.cxx @@ -30,7 +30,7 @@ struct brent_f2 : public vnl_cost_function f(const vnl_vector & x) override { n_evals++; - double y = (2 - x[0]) * (2 - x[0]); + const double y = (2 - x[0]) * (2 - x[0]); return y * y + 10; } }; @@ -65,9 +65,9 @@ test_brent_minimizer() vnl_vector v(1); v[0] = 2; - double f2_a = f2.f(v); + const double f2_a = f2.f(v); v[0] = x; - double f2_b = f2.f(v); + const double f2_b = f2.f(v); std::cout << "f2(2)-f2(x)=" << f2_a - f2_b << std::endl; } diff --git a/core/vnl/algo/tests/test_cholesky.cxx b/core/vnl/algo/tests/test_cholesky.cxx index fb72f24f01f..549c76a54f4 100644 --- a/core/vnl/algo/tests/test_cholesky.cxx +++ b/core/vnl/algo/tests/test_cholesky.cxx @@ -20,27 +20,28 @@ test_cholesky() I.set_identity(); { - vnl_cholesky chol(A); + const vnl_cholesky chol(A); std::cout << "cholesky inverse:\n" << chol.inverse() << '\n' << "direct inverse:\n" << vnl_inverse(A) << '\n'; testlib_test_assert_near("vnl_inverse() ~= cholesky.inverse()", (chol.inverse() - vnl_inverse(A)).fro_norm()); } { - vnl_cholesky chol(A); + const vnl_cholesky chol(A); testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm()); testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm()); } { - vnl_cholesky chol(A, vnl_cholesky::estimate_condition); + const vnl_cholesky chol(A, vnl_cholesky::estimate_condition); testlib_test_assert_near("Ai * A - I", (chol.inverse() * A - I).fro_norm()); testlib_test_assert_near("Ai * A - I", (A * chol.inverse() - I).fro_norm()); } { - vnl_vector b(3), x0(3), x; + vnl_vector b(3); + vnl_vector x0(3); test_util_fill_random(x0.begin(), x0.end(), rng); b = A * x0; - vnl_cholesky chol(A); - x = chol.solve(b); + const vnl_cholesky chol(A); + const vnl_vector x = chol.solve(b); testlib_test_assert_near("Solve Ax=b", (x - x0).one_norm(), 0, 1e-6); } } diff --git a/core/vnl/algo/tests/test_complex_algo.cxx b/core/vnl/algo/tests/test_complex_algo.cxx index 1fea455d92e..a81bf34348f 100644 --- a/core/vnl/algo/tests/test_complex_algo.cxx +++ b/core/vnl/algo/tests/test_complex_algo.cxx @@ -37,14 +37,14 @@ test_matrix_inverse() -1., std::complex(-1., -1.), 1. }; - vnl_matrix> m(data, 4, 4); + const vnl_matrix> m(data, 4, 4); vnl_svd_economy> svde(m); vnl_matrix> V = svde.V(); vnl_svd> svd(m); vnl_matrix> V0 = svd.V(); TEST_NEAR("complex vnl_svd_economy", V[0][1], V0[0][1], 1e-6); - vnl_matrix> inv{ vnl_matrix_inverse>(m).as_matrix() }; + const vnl_matrix> inv{ vnl_matrix_inverse>(m).as_matrix() }; vnl_matrix> identity(4, 4); identity.set_identity(); TEST_NEAR("complex vnl_matrix_inverse", (m * inv - identity).array_inf_norm(), 0, 1e-6); @@ -53,9 +53,13 @@ test_matrix_inverse() static void test_generalized_schur() { - vnl_matrix> A(4, 4, 0.0f), B(4, 4, 0.0f), L(4, 4, 1.0f), R(4, 4, 1.0f); - vnl_vector> a(4, 0.0f), b(4, 0.0f); - bool r = vnl_generalized_schur(&A, &B, &a, &b, &L, &R); + vnl_matrix> A(4, 4, 0.0f); + vnl_matrix> B(4, 4, 0.0f); + vnl_matrix> L(4, 4, 1.0f); + vnl_matrix> R(4, 4, 1.0f); + vnl_vector> a(4, 0.0f); + vnl_vector> b(4, 0.0f); + const bool r = vnl_generalized_schur(&A, &B, &a, &b, &L, &R); TEST("vnl_complex_generalized_schur", r, true); } diff --git a/core/vnl/algo/tests/test_complex_eigensystem.cxx b/core/vnl/algo/tests/test_complex_eigensystem.cxx index 1f19cec0ae8..25df1da0d93 100644 --- a/core/vnl/algo/tests/test_complex_eigensystem.cxx +++ b/core/vnl/algo/tests/test_complex_eigensystem.cxx @@ -35,14 +35,14 @@ test_complex_eigensystem1() TEST("vnl_complex_eigensystem constructor", eig.N, N); for (unsigned i = 0; i < N; i++) { - std::complex w = eig.W[i]; + const std::complex w = eig.W[i]; std::cout << " W[" << i << "] = " << w << '\n'; // - vnl_vector> l = eig.left_eigen_vector(i); + const vnl_vector> l = eig.left_eigen_vector(i); vnl_vector> err = l * A - l * w; testlib_test_assert_near(" Left eigenvalue residue", err.magnitude()); // - vnl_vector> r = eig.right_eigen_vector(i); + const vnl_vector> r = eig.right_eigen_vector(i); err = A * r - w * r; testlib_test_assert_near(" Right eigenvalue residue", err.magnitude()); } @@ -54,7 +54,7 @@ test_complex_eigensystem2() // The standard version of ZLAHQR fails to converge on this 6x6 matrix // because the maximum number of iterations is reached. Removing the // upper limit makes it work, though. - double Adata[6][6] = { + const double Adata[6][6] = { { 6.811898476755, -0.750947244402, 0.029620459055, 0.082784816274, -0.003265374870, 0.000128799864 }, { -0.302642078990, 7.243967032503, -0.238733709072, -1.593479414193, 0.057672293761, -0.002070468886 }, { -0.224780478514, 1.663978565954, 6.516036730518, -0.364143980645, -0.711203495953, 0.056672152613 }, @@ -66,7 +66,7 @@ test_complex_eigensystem2() for (int i = 0; i < 6; ++i) for (int j = 0; j < 6; ++j) A[i][j] = Adata[i][j]; //(0.77+i) + (0.1+j)*(0.33+j); - vnl_complex_eigensystem eig(A); + const vnl_complex_eigensystem eig(A); TEST("vnl_complex_eigensystem constructor", eig.N, 6); for (int i = 0; i < 6; ++i) std::cout << " W[" << i << "] = " << eig.eigen_value(i) << '\n'; diff --git a/core/vnl/algo/tests/test_convolve.cxx b/core/vnl/algo/tests/test_convolve.cxx index 0c4e0d08a9c..350da68d917 100644 --- a/core/vnl/algo/tests/test_convolve.cxx +++ b/core/vnl/algo/tests/test_convolve.cxx @@ -13,8 +13,8 @@ void test_convolve() { int b_data[] = { -2, 0, 4, 6, 2, 0 }; - vnl_vector b(6, 6, b_data); - vnl_vector k1 = vnl_double_2(0.5, -0.5).as_vector(); + const vnl_vector b(6, 6, b_data); + const vnl_vector k1 = vnl_double_2(0.5, -0.5).as_vector(); vnl_vector r1 = vnl_convolve(b, k1, (double *)nullptr); TEST("vnl_convolve() simple length", r1.size(), 7); @@ -23,26 +23,27 @@ test_convolve() true, r1[0] == -1 && r1[1] == 1 && r1[2] == 2 && r1[3] == 1 && r1[4] == -2 && r1[5] == -1 && r1[6] == 0); - vnl_vector k2 = vnl_int_2(1, -1).as_vector(); + const vnl_vector k2 = vnl_int_2(1, -1).as_vector(); vnl_vector r2 = vnl_convolve(b, k2); TEST("vnl_convolve() simple length", r2.size(), 7); std::cout << r2 << std::endl; TEST("vnl_convolve() simple values", true, r2[0] == -2 && r2[1] == 2 && r2[2] == 4 && r2[3] == 2 && r2[4] == -4 && r2[5] == -2 && r2[6] == 0); - vnl_vector r3 = vnl_convolve(b, k2, (int *)nullptr); + const vnl_vector r3 = vnl_convolve(b, k2, (int *)nullptr); TEST("vnl_convolve() 2nd form", r3, r2); - vnl_vector r4 = vnl_convolve(k2, b); + const vnl_vector r4 = vnl_convolve(k2, b); TEST("vnl_convolve() commutativity", r4, r2); - vnl_vector r7 = vnl_convolve(b, k1, (double *)nullptr, 1); + const vnl_vector r7 = vnl_convolve(b, k1, (double *)nullptr, 1); std::cout << r7 << std::endl; TEST_NEAR("vnl_convolve() with_fft(7)", (r7 - r1).two_norm(), 0.0, 1e-6); - vnl_vector r8 = vnl_convolve(b, k1, (double *)nullptr, 8); + const vnl_vector r8 = vnl_convolve(b, k1, (double *)nullptr, 8); std::cout << r8 << std::endl; TEST_NEAR("vnl_convolve() with_fft(8)", (r8 - r1).two_norm(), 0.0, 1e-6); // TIMING TEST on a very long convolution: - vnl_vector l(10000), k3(2000); + vnl_vector l(10000); + vnl_vector k3(2000); vnl_random rng; test_util_fill_random(l.begin(), l.end(), rng); test_util_fill_random(k3.begin(), k3.end(), rng); @@ -84,16 +85,16 @@ test_convolve() std::cout << "Done FFT-2,3-based 10000x2000 convolution in " << ms4 / double(ntimes) << " milliseconds\n"; double c1_data[] = { -1, 0, 1, 2, 3, 4 }; - vnl_vector c1(6, 6, c1_data); + const vnl_vector c1(6, 6, c1_data); double c2_data[] = { 5, 3, 1, -1, -3, -5 }; - vnl_vector c2(6, 6, c2_data); + const vnl_vector c2(6, 6, c2_data); vnl_vector r5 = vnl_convolve_cyclic(c1, c2, (double *)nullptr); TEST("vnl_convolve_cyclic() length", r5.size(), 6); std::cout << r5 << std::endl; TEST("vnl_convolve_cyclic() values", true, r5[0] == 5 && r5[1] == -13 && r5[2] == -19 && r5[3] == -13 && r5[4] == 5 && r5[5] == 35); - vnl_vector r6 = vnl_convolve_cyclic(c1, c2, (double *)nullptr, true); + const vnl_vector r6 = vnl_convolve_cyclic(c1, c2, (double *)nullptr, true); std::cout << r6 << std::endl; TEST_NEAR("vnl_convolve_cyclic() with_fft", (r6 - r5).two_norm(), 0.0, 1e-6); } diff --git a/core/vnl/algo/tests/test_cpoly_roots.cxx b/core/vnl/algo/tests/test_cpoly_roots.cxx index fe8f388b718..e9c468faa7f 100644 --- a/core/vnl/algo/tests/test_cpoly_roots.cxx +++ b/core/vnl/algo/tests/test_cpoly_roots.cxx @@ -9,13 +9,13 @@ test_cpoly_roots() const double coeffs[] = { 6, 5, 4, 3, 2, 1 }; vnl_vector a(coeffs, 6); - vnl_vector monic((a / a[0]).extract(a.size() - 1, 1)); + const vnl_vector monic((a / a[0]).extract(a.size() - 1, 1)); vnl_cpoly_roots roots(monic, 0.0 * monic); TEST("Number of solutions", roots.solns.size(), monic.size()); // Evaluate results - vnl_real_polynomial f(a); + const vnl_real_polynomial f(a); for (int i = 0; i < f.degree(); ++i) TEST_NEAR("Root residual", f.evaluate(roots.solns[i]), 0.0, 1e-12); } diff --git a/core/vnl/algo/tests/test_determinant.cxx b/core/vnl/algo/tests/test_determinant.cxx index 50d7470a847..539cc528c37 100644 --- a/core/vnl/algo/tests/test_determinant.cxx +++ b/core/vnl/algo/tests/test_determinant.cxx @@ -6,7 +6,7 @@ #include "testlib/testlib_test.h" double -qr_det(vnl_matrix const & M) +qr_det(const vnl_matrix & M) { return vnl_qr(M).determinant(); } @@ -14,25 +14,25 @@ qr_det(vnl_matrix const & M) void test_determinant() { - double eps = 1e-14; + const double eps = 1e-14; { double M2[2][2] = { { 0.60684258354179, 0.89129896614890 }, { 0.48598246870930, 0.76209683302739 } }; - vnl_matrix m2(&M2[0][0], 2, 2); - double d2 = qr_det(m2); + const vnl_matrix m2(&M2[0][0], 2, 2); + const double d2 = qr_det(m2); TEST_NEAR("2x2 vnl_determinant(vnl_matrix)", vnl_determinant(m2), d2, eps); TEST_NEAR("2x2 vnl_determinant(double, ...)", vnl_determinant(M2[0], M2[1]), d2, eps); - vnl_matrix_fixed m_2 = m2; + const vnl_matrix_fixed m_2 = m2; TEST_NEAR("vnl_det(vnl_matrix_fixed)", vnl_det(m_2), d2, eps); } { double N2[2][2] = { { 0.60684258354179, 0.89129896614890 }, { 0.48598246870930, -0.76209683302739 } }; - vnl_matrix n2(&N2[0][0], 2, 2); - double d2 = qr_det(n2); + const vnl_matrix n2(&N2[0][0], 2, 2); + const double d2 = qr_det(n2); TEST_NEAR("2x2 vnl_determinant(vnl_matrix)", vnl_determinant(n2), d2, eps); TEST_NEAR("2x2 vnl_determinant(double, ...)", vnl_determinant(N2[0], N2[1]), d2, eps); - vnl_matrix_fixed n_2 = n2; + const vnl_matrix_fixed n_2 = n2; TEST_NEAR("vnl_det(vnl_matrix_fixed)", vnl_det(n_2), d2, eps); } @@ -40,11 +40,11 @@ test_determinant() double M3[3][3] = { { 0.45646766516834, 0.44470336435319, 0.92181297074480 }, { 0.01850364324822, 0.61543234810009, 0.73820724581067 }, { 0.82140716429525, 0.79193703742704, 0.17626614449462 } }; - vnl_matrix m3(&M3[0][0], 3, 3); - double d3 = qr_det(m3); + const vnl_matrix m3(&M3[0][0], 3, 3); + const double d3 = qr_det(m3); TEST_NEAR("3x3 vnl_determinant(vnl_matrix)", vnl_determinant(m3), d3, eps); TEST_NEAR("3x3 vnl_determinant(double, ...)", vnl_determinant(M3[0], M3[1], M3[2]), d3, eps); - vnl_matrix_fixed m_3 = m3; + const vnl_matrix_fixed m_3 = m3; TEST_NEAR("vnl_det(vnl_matrix_fixed)", vnl_det(m_3), d3, eps); } @@ -52,11 +52,11 @@ test_determinant() double N3[3][3] = { { 0.45646766516834, 0.44470336435319, -0.92181297074480 }, { 0.01850364324822, 0.61543234810009, -0.73820724581067 }, { 0.82140716429525, 0.79193703742704, 0.17626614449462 } }; - vnl_matrix n3(&N3[0][0], 3, 3); - double d3 = qr_det(n3); + const vnl_matrix n3(&N3[0][0], 3, 3); + const double d3 = qr_det(n3); TEST_NEAR("3x3 vnl_determinant(vnl_matrix)", vnl_determinant(n3), d3, eps); TEST_NEAR("3x3 vnl_determinant(double, ...)", vnl_determinant(N3[0], N3[1], N3[2]), d3, eps); - vnl_matrix_fixed n_3 = n3; + const vnl_matrix_fixed n_3 = n3; TEST_NEAR("vnl_det(vnl_matrix_fixed)", vnl_det(n_3), d3, eps); } @@ -65,11 +65,11 @@ test_determinant() { 0.93546969910761, 0.05789130478427, 0.13889088195695, 0.27218792496996 }, { 0.91690443991341, 0.35286813221700, 0.20276521856027, 0.19881426776106 }, { 0.41027020699095, 0.81316649730376, 0.19872174266149, 0.01527392702904 } }; - vnl_matrix m4(&M4[0][0], 4, 4); - double d4 = qr_det(m4); + const vnl_matrix m4(&M4[0][0], 4, 4); + const double d4 = qr_det(m4); TEST_NEAR("4x4 vnl_determinant(vnl_matrix)", vnl_determinant(m4), d4, eps); TEST_NEAR("4x4 vnl_determinant(double, ...)", vnl_determinant(M4[0], M4[1], M4[2], M4[3]), d4, eps); - vnl_matrix_fixed m_4 = m4; + const vnl_matrix_fixed m_4 = m4; TEST_NEAR("vnl_det(vnl_matrix_fixed)", vnl_det(m_4), d4, eps); } @@ -78,36 +78,36 @@ test_determinant() { 0.93546969910761, 0.05789130478427, 0.13889088195695, 0.27218792496996 }, { 0.91690443991341, -0.35286813221700, 0.20276521856027, -0.19881426776106 }, { 0.41027020699095, 0.81316649730376, 0.19872174266149, 0.01527392702904 } }; - vnl_matrix n4(&N4[0][0], 4, 4); - double d4 = qr_det(n4); + const vnl_matrix n4(&N4[0][0], 4, 4); + const double d4 = qr_det(n4); TEST_NEAR("4x4 vnl_determinant(vnl_matrix)", vnl_determinant(n4), d4, eps); TEST_NEAR("4x4 vnl_determinant(double, ...)", vnl_determinant(N4[0], N4[1], N4[2], N4[3]), d4, eps); - vnl_matrix_fixed n_4 = n4; + const vnl_matrix_fixed n_4 = n4; TEST_NEAR("vnl_det(vnl_matrix_fixed)", vnl_det(n_4), d4, eps); - double N5[5][5] = { { 1, 0, 0, 0, 0 }, - { 0, N4[0][0], N4[0][1], N4[0][2], N4[0][3] }, - { 0, N4[1][0], N4[1][1], N4[1][2], N4[1][3] }, - { 0, N4[2][0], N4[2][1], N4[2][2], N4[2][3] }, - { 0, N4[3][0], N4[3][1], N4[3][2], N4[3][3] } }; - vnl_matrix n5(&N5[0][0], 5, 5); - double d5 = qr_det(n5); + const double N5[5][5] = { { 1, 0, 0, 0, 0 }, + { 0, N4[0][0], N4[0][1], N4[0][2], N4[0][3] }, + { 0, N4[1][0], N4[1][1], N4[1][2], N4[1][3] }, + { 0, N4[2][0], N4[2][1], N4[2][2], N4[2][3] }, + { 0, N4[3][0], N4[3][1], N4[3][2], N4[3][3] } }; + const vnl_matrix n5(&N5[0][0], 5, 5); + const double d5 = qr_det(n5); TEST_NEAR("5x5 qr_det equals 4x4 one", d5, d4, eps); TEST_NEAR("5x5 vnl_determinant(vnl_matrix)", vnl_determinant(n5), d5, eps); - vnl_matrix_fixed n_5 = n5; + const vnl_matrix_fixed n_5 = n5; TEST_NEAR("vnl_determinant(vnl_matrix_fixed)", vnl_determinant(n_5), d5, eps); } { - int M6[3][3] = { { 2, 0, 0 }, { 0, 1, 0 }, { 0, 0, 5 } }; - vnl_matrix m6(&M6[0][0], 3, 3); + const int M6[3][3] = { { 2, 0, 0 }, { 0, 1, 0 }, { 0, 0, 5 } }; + const vnl_matrix m6(&M6[0][0], 3, 3); TEST_NEAR("3x3 vnl_determinant(vnl_matrix)", vnl_determinant(m6), 10, eps); } { - int M7[6][6] = { { 2, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 0 }, { 0, 0, 5, 0, 0, 0 }, - { 0, 0, 0, 4, 0, 0 }, { 0, 0, 0, 0, 2, 0 }, { 0, 0, 0, 0, 0, 6 } }; - vnl_matrix m7(&M7[0][0], 6, 6); + const int M7[6][6] = { { 2, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 0 }, { 0, 0, 5, 0, 0, 0 }, + { 0, 0, 0, 4, 0, 0 }, { 0, 0, 0, 0, 2, 0 }, { 0, 0, 0, 0, 0, 6 } }; + const vnl_matrix m7(&M7[0][0], 6, 6); TEST_NEAR("6x6 vnl_determinant(vnl_matrix)", vnl_determinant(m7), 2 * 1 * 5 * 4 * 2 * 6, eps); } } diff --git a/core/vnl/algo/tests/test_fft.cxx b/core/vnl/algo/tests/test_fft.cxx index 814183b5e5e..f2f71fef2dc 100644 --- a/core/vnl/algo/tests/test_fft.cxx +++ b/core/vnl/algo/tests/test_fft.cxx @@ -35,7 +35,7 @@ test_fft_1d(unsigned int N) tmp /= N; vnl_matlab_print(std::cout, tmp, "tmp"); - double err = (tmp - signal).two_norm(); + const double err = (tmp - signal).two_norm(); std::cout << "err = " << err << std::endl; TEST_NEAR("test fwd-bwd", err, 0.0, 1e-10); } @@ -59,7 +59,7 @@ test_fft_2d(unsigned int M, unsigned int N) tmp /= (M * N); vnl_matlab_print(std::cout, tmp, "tmp"); - double err = (tmp - signal).fro_norm(); + const double err = (tmp - signal).fro_norm(); std::cout << "err = " << err << std::endl; TEST_NEAR("test fwd-bwd", err, 0.0, 1e-10); } diff --git a/core/vnl/algo/tests/test_fft1d.cxx b/core/vnl/algo/tests/test_fft1d.cxx index 5ad5438be16..0b85a1d911f 100644 --- a/core/vnl/algo/tests/test_fft1d.cxx +++ b/core/vnl/algo/tests/test_fft1d.cxx @@ -34,7 +34,7 @@ test_fft_1d(int n) // calculate prime factors for this size array //============================================ - vnl_fft_prime_factors oPFx(n); + const vnl_fft_prime_factors oPFx(n); if (!oPFx) { std::cerr << "cannot decompose X-size " << n << ")into the form (2^P)(3^Q)(5^R)\n"; @@ -98,8 +98,14 @@ test_fft_1d(int n) } TEST("test backward C-array", test_Ptr, true); - double fArrayRealError = 0.0, fArrayImagError = 0.0, fVecRealError = 0.0, fVecImagError = 0.0, fPtrRealError = 0.0, - fPtrImagError = 0.0, fFwdRealError = 0.0, fFwdImagError = 0.0; + double fArrayRealError = 0.0; + double fArrayImagError = 0.0; + double fVecRealError = 0.0; + double fVecImagError = 0.0; + double fPtrRealError = 0.0; + double fPtrImagError = 0.0; + double fFwdRealError = 0.0; + double fFwdImagError = 0.0; for (int iC = 0; iC < n; iC++) { diff --git a/core/vnl/algo/tests/test_fft2d.cxx b/core/vnl/algo/tests/test_fft2d.cxx index d5b849b0fa5..7fffe4a36b7 100644 --- a/core/vnl/algo/tests/test_fft2d.cxx +++ b/core/vnl/algo/tests/test_fft2d.cxx @@ -23,16 +23,16 @@ #include "vnl/vnl_complexify.h" #include -inline static double +static inline double function(unsigned i, unsigned j) { return i * j; } void -test_cplx(vnl_fft_prime_factors const & /*prx*/, - vnl_fft_prime_factors const & /*pry*/, - vnl_matrix> const & M, +test_cplx(const vnl_fft_prime_factors & /*prx*/, + const vnl_fft_prime_factors & /*pry*/, + const vnl_matrix> & M, int dir) { vnl_matrix> fft_matrix = M; @@ -50,8 +50,8 @@ test_fft2d() constexpr unsigned int cols = 64; // calculate prime factors for this size array - vnl_fft_prime_factors prx(rows); - vnl_fft_prime_factors pry(cols); + const vnl_fft_prime_factors prx(rows); + const vnl_fft_prime_factors pry(cols); if (!prx) { @@ -85,7 +85,7 @@ test_fft2d() vnl_complexify(real_array, imag_array, cplx_array, rows * cols); // data as matrices : - vnl_matrix> cplx_matrix(cplx_array, rows, cols); + const vnl_matrix> cplx_matrix(cplx_array, rows, cols); //-------------------------------------------------------------------------------- @@ -101,7 +101,7 @@ test_fft2d() fft.fwd_transform(fft_matrix); fft.bwd_transform(fft_matrix); - double error = (fft_matrix - std::complex(cplx_matrix.size()) * cplx_matrix).fro_norm(); + const double error = (fft_matrix - std::complex(cplx_matrix.size()) * cplx_matrix).fro_norm(); std::cout << "error = " << error << std::endl; TEST_NEAR("fwd-bwd error", error, 0.0, 1e-7); // increase for float } diff --git a/core/vnl/algo/tests/test_functions.cxx b/core/vnl/algo/tests/test_functions.cxx index 4d526822b35..d463aa50132 100644 --- a/core/vnl/algo/tests/test_functions.cxx +++ b/core/vnl/algo/tests/test_functions.cxx @@ -252,14 +252,14 @@ test_functions() for (double & i : hist1) { sample_seed = (sample_seed * 16807) % 2147483647L; - double u = double(sample_seed) / 0x7fffffff; // 0x7fffffff == 2147483711L - i = 10.0 + 20.0 * (u - 0.5); // uniform in the interval 0 - 20 + const double u = double(sample_seed) / 0x7fffffff; // 0x7fffffff == 2147483711L + i = 10.0 + 20.0 * (u - 0.5); // uniform in the interval 0 - 20 } double chisq = 0; for (int i = 0; i < 20; i++) { std::cout << i << ' ' << hist1[i] << std::endl; - double delta = hist1[i] - 10.0; + const double delta = hist1[i] - 10.0; chisq += delta * delta / (hist1[i] + 10.0); } std::cout << "cdf(" << chisq << ",20) = " << vnl_chi_squared_cumulative(chisq, 20) diff --git a/core/vnl/algo/tests/test_generalized_eigensystem.cxx b/core/vnl/algo/tests/test_generalized_eigensystem.cxx index 8340f6994ba..584d5251b23 100644 --- a/core/vnl/algo/tests/test_generalized_eigensystem.cxx +++ b/core/vnl/algo/tests/test_generalized_eigensystem.cxx @@ -23,15 +23,15 @@ test_generalized_eigensystem() 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, -1, 0, 0, 0, 0, 2, 0, 0, }; - vnl_matrix S(Sdata, 6, 6); - vnl_matrix C(Cdata, 6, 6); + const vnl_matrix S(Sdata, 6, 6); + const vnl_matrix C(Cdata, 6, 6); - vnl_generalized_eigensystem gev(C, S); + const vnl_generalized_eigensystem gev(C, S); std::cout << "V = " << gev.V << std::endl << "D = " << gev.D << std::endl << "residual = " << C * gev.V - S * gev.V * gev.D << std::endl; - double err = (C * gev.V - S * gev.V * gev.D).fro_norm(); + const double err = (C * gev.V - S * gev.V * gev.D).fro_norm(); std::cout << "Recomposition residual = " << err << std::endl; TEST_NEAR("Recomposition residual < 1e-12", err, 0.0, 1e-12); diff --git a/core/vnl/algo/tests/test_integral.cxx b/core/vnl/algo/tests/test_integral.cxx index d13978b1bf7..29fea8f23a9 100644 --- a/core/vnl/algo/tests/test_integral.cxx +++ b/core/vnl/algo/tests/test_integral.cxx @@ -41,11 +41,11 @@ class gaussian_integrant : public vnl_analytic_integrant double f_(double rho) override { - double x2 = std::pow(p0_.get(0) + rho * std::sin(theta_) * std::cos(phi_), 2); - double y2 = std::pow(p0_.get(1) + rho * std::sin(theta_) * std::sin(phi_), 2); - double z2 = std::pow(p0_.get(2) + rho * std::cos(theta_), 2); - double term1 = oneoversr2_ * ((x2 + y2) * oneoversr2_ - 2); - double term2 = std::exp(-(x2 + y2) * oneoversr2_ / 2) * std::exp(-z2 * oneoversz2_ / 2); + const double x2 = std::pow(p0_.get(0) + rho * std::sin(theta_) * std::cos(phi_), 2); + const double y2 = std::pow(p0_.get(1) + rho * std::sin(theta_) * std::sin(phi_), 2); + const double z2 = std::pow(p0_.get(2) + rho * std::cos(theta_), 2); + const double term1 = oneoversr2_ * ((x2 + y2) * oneoversr2_ - 2); + const double term2 = std::exp(-(x2 + y2) * oneoversr2_ / 2) * std::exp(-z2 * oneoversz2_ / 2); return normalizer_ * term1 * term2; } @@ -72,8 +72,8 @@ test_integral() my_test_integrant f; vnl_simpson_integral simpson_integral; - double a = 0; - double b = 1; + const double a = 0; + const double b = 1; TEST_NEAR("simpson integral of x/(1+x^2) from 0 to 1 is: ", simpson_integral.integral(&f, a, b, 100), diff --git a/core/vnl/algo/tests/test_ldl_cholesky.cxx b/core/vnl/algo/tests/test_ldl_cholesky.cxx index bb1e6d3f652..d7facfc3da9 100644 --- a/core/vnl/algo/tests/test_ldl_cholesky.cxx +++ b/core/vnl/algo/tests/test_ldl_cholesky.cxx @@ -21,8 +21,9 @@ test_ldl_cholesky() I.set_identity(); { - vnl_ldl_cholesky chol(A); - vnl_matrix A2 = chol.lower_triangle() * vnl_diag_matrix(chol.diagonal()) * chol.upper_triangle(); + const vnl_ldl_cholesky chol(A); + const vnl_matrix A2 = + chol.lower_triangle() * vnl_diag_matrix(chol.diagonal()) * chol.upper_triangle(); TEST_NEAR("LDL'=A", (A - A2).fro_norm(), 0.0, 1e-12); } { @@ -33,8 +34,9 @@ test_ldl_cholesky() Mv.set_column(0, v); vnl_ldl_cholesky chol(A); chol.rank1_update(v); - vnl_matrix A2 = A + Mv * Mv.transpose(); - vnl_matrix A3 = chol.lower_triangle() * vnl_diag_matrix(chol.diagonal()) * chol.upper_triangle(); + const vnl_matrix A2 = A + Mv * Mv.transpose(); + const vnl_matrix A3 = + chol.lower_triangle() * vnl_diag_matrix(chol.diagonal()) * chol.upper_triangle(); TEST_NEAR("Rank 1 update", (A2 - A3).fro_norm(), 0.0, 1e-12); } { @@ -43,8 +45,9 @@ test_ldl_cholesky() test_util_fill_random(W.begin(), W.end(), rng); vnl_ldl_cholesky chol(A); chol.update(W); - vnl_matrix A2 = A + W * W.transpose(); - vnl_matrix A3 = chol.lower_triangle() * vnl_diag_matrix(chol.diagonal()) * chol.upper_triangle(); + const vnl_matrix A2 = A + W * W.transpose(); + const vnl_matrix A3 = + chol.lower_triangle() * vnl_diag_matrix(chol.diagonal()) * chol.upper_triangle(); TEST_NEAR("Rank 2 update", (A2 - A3).fro_norm(), 0.0, 1e-12); } { @@ -54,37 +57,42 @@ test_ldl_cholesky() vnl_ldl_cholesky chol(A); chol.update(W); std::cout << "Adding: " << W * W.transpose() << std::endl; - vnl_matrix A2 = A + W * W.transpose(); - vnl_matrix A3 = chol.lower_triangle() * vnl_diag_matrix(chol.diagonal()) * chol.upper_triangle(); + const vnl_matrix A2 = A + W * W.transpose(); + const vnl_matrix A3 = + chol.lower_triangle() * vnl_diag_matrix(chol.diagonal()) * chol.upper_triangle(); TEST_NEAR("Rank 2 update", (A2 - A3).fro_norm(), 0.0, 1e-12); } { - vnl_ldl_cholesky chol(A); + const vnl_ldl_cholesky chol(A); std::cout << "cholesky inverse:\n" << chol.inverse() << '\n' << "vnl_inverse:\n" << vnl_inverse(A) << '\n'; TEST_NEAR("vnl_inverse() ~= cholesky.inverse()", (chol.inverse() - vnl_inverse(A)).fro_norm(), 0.0, 1e-12); } { - vnl_ldl_cholesky chol(A); + const vnl_ldl_cholesky chol(A); TEST_NEAR("Ai * A - I", (chol.inverse() * A - I).fro_norm(), 0.0, 1e-12); TEST_NEAR("Ai * A - I", (A * chol.inverse() - I).fro_norm(), 0.0, 1e-12); } { - vnl_ldl_cholesky chol(A, vnl_ldl_cholesky::estimate_condition); + const vnl_ldl_cholesky chol(A, vnl_ldl_cholesky::estimate_condition); TEST_NEAR("Ai * A - I", (chol.inverse() * A - I).fro_norm(), 0.0, 1e-12); TEST_NEAR("Ai * A - I", (A * chol.inverse() - I).fro_norm(), 0.0, 1e-12); } { - vnl_vector b(3), x0(3), x; + vnl_vector b(3); + vnl_vector x0(3); + vnl_vector x; test_util_fill_random(x0.begin(), x0.end(), rng); b = A * x0; - vnl_ldl_cholesky chol(A); + const vnl_ldl_cholesky chol(A); x = chol.solve(b); TEST_NEAR("Solve Ax=b", (x - x0).one_norm(), 0, 1e-6); } { - vnl_vector b(3), x0(3), x; + vnl_vector b(3); + vnl_vector x0(3); + vnl_vector x; test_util_fill_random(x0.begin(), x0.end(), rng); vnl_ldl_cholesky chol(A); b = chol.lower_triangle() * x0; @@ -93,22 +101,22 @@ test_ldl_cholesky() TEST_NEAR("Solve Lx=b", (x - x0).one_norm(), 0, 1e-6); } { - vnl_ldl_cholesky chol(A); + const vnl_ldl_cholesky chol(A); vnl_vector v(3); test_util_fill_random(v.begin(), v.end(), rng); - double res1 = chol.xt_m_inv_x(v); - double res2 = dot_product(v, chol.inverse() * v); + const double res1 = chol.xt_m_inv_x(v); + const double res2 = dot_product(v, chol.inverse() * v); TEST_NEAR("x' * inv(M) * x", res1, res2, 1e-12); } { - vnl_ldl_cholesky chol(A); + const vnl_ldl_cholesky chol(A); vnl_vector v(3); test_util_fill_random(v.begin(), v.end(), rng); - double res1 = chol.xt_m_x(v); - double res2 = dot_product(v, A * v); + const double res1 = chol.xt_m_x(v); + const double res2 = dot_product(v, A * v); TEST_NEAR("x' * M * x", res1, res2, 1e-12); } diff --git a/core/vnl/algo/tests/test_levenberg_marquardt.cxx b/core/vnl/algo/tests/test_levenberg_marquardt.cxx index 5663e3fc82d..11e163659b8 100644 --- a/core/vnl/algo/tests/test_levenberg_marquardt.cxx +++ b/core/vnl/algo/tests/test_levenberg_marquardt.cxx @@ -16,7 +16,7 @@ struct vnl_rosenbrock : public vnl_least_squares_function {} void - f(vnl_vector const & x, vnl_vector & y) override + f(const vnl_vector & x, vnl_vector & y) override { TEST("size of x", x.size(), 2); TEST("size of y", y.size(), 2); @@ -25,7 +25,7 @@ struct vnl_rosenbrock : public vnl_least_squares_function } void - gradf(vnl_vector const & x, vnl_matrix & J) override + gradf(const vnl_vector & x, vnl_matrix & J) override { TEST("size of x", x.size(), 2); TEST("size of J", J.rows() == 2 && J.cols() == 2, true); @@ -38,23 +38,22 @@ struct vnl_rosenbrock : public vnl_least_squares_function struct linear_est : public vnl_least_squares_function { - linear_est(vnl_matrix const &A, vnl_vector b, bool with_grad) - : vnl_least_squares_function(A.cols(), A.rows(), - with_grad ? use_gradient : no_gradient) - , A_(A) - , b_(std::move(b)) + linear_est(const vnl_matrix & A, vnl_vector b, bool with_grad) + : vnl_least_squares_function(A.cols(), A.rows(), with_grad ? use_gradient : no_gradient) + , A_(A) + , b_(std::move(b)) { assert(A_.rows() == b_.size()); } void - f(vnl_vector const & x, vnl_vector & y) override + f(const vnl_vector & x, vnl_vector & y) override { y = A_ * x - b_; } void - gradf(vnl_vector const & /*x*/, vnl_matrix & J) override + gradf(const vnl_vector & /*x*/, vnl_matrix & J) override { J = A_; } @@ -68,7 +67,7 @@ do_rosenbrock_test(bool with_grad) { vnl_rosenbrock f(with_grad); - vnl_double_2 x0(2.7, -1.3); + const vnl_double_2 x0(2.7, -1.3); std::cout << "x0 = " << x0 << std::endl; vnl_levenberg_marquardt lm(f); @@ -81,7 +80,7 @@ do_rosenbrock_test(bool with_grad) lm.diagnose_outcome(std::cout); std::cout << "x1 = " << x1 << std::endl; - double err = std::abs(x1[0] - 1) + std::abs(x1[1] - 1); + const double err = std::abs(x1[0] - 1) + std::abs(x1[1] - 1); std::cout << "err = " << err << std::endl; TEST_NEAR("converged to (1, 1)", err, 0.0, 1e-10); } @@ -135,7 +134,7 @@ do_linear_test(bool with_grad) true_cov(0, 1) = 75; true_cov(1, 1) = 1384.14; - vnl_matrix covar = lm.get_JtJ(); + const vnl_matrix covar = lm.get_JtJ(); std::cout << "Cov(x) =\n" << covar << std::endl; TEST_NEAR("covariance approximation", (true_cov - covar).array_two_norm(), 0, 1e-5); } diff --git a/core/vnl/algo/tests/test_matrix_update.cxx b/core/vnl/algo/tests/test_matrix_update.cxx index 619748ecaa7..9edd99d3186 100644 --- a/core/vnl/algo/tests/test_matrix_update.cxx +++ b/core/vnl/algo/tests/test_matrix_update.cxx @@ -10,10 +10,14 @@ extern "C" void test_matrix_update() { - unsigned nr = 5, nc = 7; - vnl_matrix M(nr, nc), true_M(nr, nc); - vnl_matrix Ma(nr, 1), Mb(1, nc); - vnl_vector a(nr), b(nc); + const unsigned nr = 5; + const unsigned nc = 7; + vnl_matrix M(nr, nc); + vnl_matrix true_M(nr, nc); + vnl_matrix Ma(nr, 1); + vnl_matrix Mb(1, nc); + vnl_vector a(nr); + vnl_vector b(nc); for (unsigned i = 0; i < nr; ++i) { diff --git a/core/vnl/algo/tests/test_powell.cxx b/core/vnl/algo/tests/test_powell.cxx index 2eaf5f8fc57..841e3a31f6e 100644 --- a/core/vnl/algo/tests/test_powell.cxx +++ b/core/vnl/algo/tests/test_powell.cxx @@ -48,16 +48,16 @@ class vnl_test_powell_rosenbrock : public vnl_cost_function double f(const vnl_vector & x) override { - double a = 10 * (x[1] - x[0] * x[0]); - double b = 1 - x[0]; + const double a = 10 * (x[1] - x[0] * x[0]); + const double b = 1 - x[0]; return a * a + b * b; } void gradf(const vnl_vector & x, vnl_vector & g) override { - double a = 10 * (x[1] - x[0] * x[0]); - double b = 1 - x[0]; + const double a = 10 * (x[1] - x[0] * x[0]); + const double b = 1 - x[0]; g[0] = 2 * a * (-20 * x[0]) - 2 * b; g[1] = 20 * a; } @@ -151,13 +151,13 @@ test_rosenbrock_2d() << " test_rosenbrock_2d()\n" << "----------------------\n"; vnl_test_powell_rosenbrock c; - vnl_double_2 xmin(1.0, 1.0); // true minimum + const vnl_double_2 xmin(1.0, 1.0); // true minimum vnl_powell powell(&c); - vnl_double_2 x0(-2, 2); // initial x + const vnl_double_2 x0(-2, 2); // initial x vnl_vector x = x0.as_vector(); powell.minimize(x); - double r = (x - xmin).magnitude(); + const double r = (x - xmin).magnitude(); TEST_NEAR("test_rosenbrock_2d", r, 0, 1e-6); std::cout << "Number of evaluations: " << powell.get_num_evaluations() << std::endl << std::endl; } diff --git a/core/vnl/algo/tests/test_qr.cxx b/core/vnl/algo/tests/test_qr.cxx index d8a0f0fa824..c5edae610b6 100644 --- a/core/vnl/algo/tests/test_qr.cxx +++ b/core/vnl/algo/tests/test_qr.cxx @@ -10,9 +10,9 @@ //-------------------------------------------------------------------------------- void -test_matrix(char const * name, const vnl_matrix & A, double det = 0) +test_matrix(const char * name, const vnl_matrix & A, double det = 0) { - vnl_qr qr(A); + const vnl_qr qr(A); std::string n(name); n += ": "; @@ -31,7 +31,7 @@ double_test() double A_data[] = { 89, 21, 27, 62, 71, 0, 84, 13, 41, 16, 9, 3, }; - vnl_matrix A(A_data, 4, 3); + const vnl_matrix A(A_data, 4, 3); test_matrix("A", A); test_matrix("AT", A.transpose()); @@ -43,15 +43,15 @@ double_test() double b_data[] = { 68, 39, 39, 50 }; - vnl_vector b(b_data, 4); - vnl_qr qr(A); + const vnl_vector b(b_data, 4); + const vnl_qr qr(A); vnl_matlab_print(std::cout, qr.Q(), "Q"); vnl_matlab_print(std::cout, qr.R(), "R"); - vnl_vector x = qr.solve(b); + const vnl_vector x = qr.solve(b); - double res = (A * x - b).magnitude(); + const double res = (A * x - b).magnitude(); TEST_NEAR("Solve residual", res, 37.8841, 1e-3); @@ -59,7 +59,7 @@ double_test() double S_data[] = { 89, 21, 27, 62, 71, 0, 84, 13, 41, }; - vnl_matrix S(S_data, 3, 3); + const vnl_matrix S(S_data, 3, 3); test_matrix("S", S, 66431); test_matrix("S-100", S - 100, -79869); } @@ -94,8 +94,8 @@ void new_test(T *) { vnl_random rng(1000); - unsigned m = 5; // m must be >= n when using the netlib QR algorithms, - unsigned n = 5; // but n >= m for a random A and b to have exact solution. + const unsigned m = 5; // m must be >= n when using the netlib QR algorithms, + const unsigned n = 5; // but n >= m for a random A and b to have exact solution. vnl_matrix A(m, n); test_util_fill_random(A.begin(), A.end(), rng); @@ -105,16 +105,16 @@ new_test(T *) test_util_fill_random(b.begin(), b.end(), rng); vnl_matlab_print(std::cout, b, "b"); - vnl_qr qr(A); - vnl_matrix const & Q = qr.Q(); - vnl_matrix const & R = qr.R(); - vnl_vector x = qr.solve(b); + const vnl_qr qr(A); + const vnl_matrix & Q = qr.Q(); + const vnl_matrix & R = qr.R(); + const vnl_vector x = qr.solve(b); vnl_matlab_print(std::cout, Q, "Q"); vnl_matlab_print(std::cout, R, "R"); vnl_matlab_print(std::cout, x, "x"); - vnl_matrix QR(Q * R); + const vnl_matrix QR(Q * R); vnl_matlab_print(std::cout, QR, "QR"); vnl_matrix I(m, m); @@ -166,13 +166,13 @@ complex_test() b(3) = ct(0.0538, 0.0402); b(4) = ct(1.8634, .64558); vnl_matlab_print(std::cout, b, "b"); - vnl_qr qr(A); + const vnl_qr qr(A); vnl_matlab_print(std::cout, A, "A"); const vnl_matrix & Q = qr.Q(); vnl_matlab_print(std::cout, Q, "Q"); const vnl_matrix & R = qr.R(); vnl_matlab_print(std::cout, R, "R"); - vnl_vector x = qr.solve(b); + const vnl_vector x = qr.solve(b); vnl_matlab_print(std::cout, x, "solve"); TEST_NEAR("||Ax - b||", (A * x - b).two_norm(), 0, 1e-5); } diff --git a/core/vnl/algo/tests/test_qsvd.cxx b/core/vnl/algo/tests/test_qsvd.cxx index 64f181c2b61..82116e146ad 100644 --- a/core/vnl/algo/tests/test_qsvd.cxx +++ b/core/vnl/algo/tests/test_qsvd.cxx @@ -10,8 +10,19 @@ test_qsvd() { float AA[9] = { 2.f / 3, -1.36f / 3, .2f / 3, 2.8f / 3, .4f / 3, 1.f / 3, 1, .16f, -.2f }; float BB[9] = { .16f, -.224f, -.768f, .8f, .36f, -.48f, 1.12f, -.168f, -.576f }; - float U[9], V[9], Q[9], Alpha[3], Beta[3], Work[12]; - long m = 3, n = 3, p = 3, k, l, Iwork[3], info; + float U[9]; + float V[9]; + float Q[9]; + float Alpha[3]; + float Beta[3]; + float Work[12]; + long m = 3; + long n = 3; + long p = 3; + long k; + long l; + long Iwork[3]; + long info; std::printf("m = 3, n = 3, p = 3\n"); v3p_netlib_sggsvd_( diff --git a/core/vnl/algo/tests/test_rank.cxx b/core/vnl/algo/tests/test_rank.cxx index 641a5ddd8b8..cfe60e92832 100644 --- a/core/vnl/algo/tests/test_rank.cxx +++ b/core/vnl/algo/tests/test_rank.cxx @@ -4,7 +4,7 @@ #include "testlib/testlib_test.h" inline int -svd_rank(vnl_matrix const & M) +svd_rank(const vnl_matrix & M) { return vnl_svd(M, 1e-8).rank(); } diff --git a/core/vnl/algo/tests/test_real_eigensystem.cxx b/core/vnl/algo/tests/test_real_eigensystem.cxx index 7f08f564582..ab0faf5f1a7 100644 --- a/core/vnl/algo/tests/test_real_eigensystem.cxx +++ b/core/vnl/algo/tests/test_real_eigensystem.cxx @@ -20,7 +20,7 @@ test_6x6() 13.9254, -2.4446, 20.2380, 3.6702, -0.2282, 28.6779, 13.7049, 1.3659, 3.6702, 12.5273, -1.6045, 3.9419, -2.4446, 3.6702, -0.2282, -1.6045, 3.9419, 2.5821, 20.2380, -0.2282, 28.6779, 3.9419, 2.5821, 44.0636, }; - vnl_matrix S(Sdata, 6, 6); + const vnl_matrix S(Sdata, 6, 6); vnl_real_eigensystem eig(S); vnl_diag_matrix> D(eig.D.rows()); @@ -32,7 +32,7 @@ test_6x6() std::cout << "D = " << eig.D << std::endl << "V = " << eig.V << std::endl; - vnl_matrix> diff = vnl_complexify(S * eig.Vreal) - vnl_complexify(eig.Vreal) * D; + const vnl_matrix> diff = vnl_complexify(S * eig.Vreal) - vnl_complexify(eig.Vreal) * D; std::cout << "X*V - V*D = " << diff << std::endl << "residual = " << diff.fro_norm() << std::endl; TEST_NEAR("recompose residual", diff.fro_norm(), 0.0, 1e-12); } @@ -42,15 +42,15 @@ test_4x4() { // unsympathetic double Xdata[] = { 686, 526, 701, 47, 588, 91, 910, 736, 930, 653, 762, 328, 846, 415, 262, 632 }; - vnl_matrix X(Xdata, 4, 4); + const vnl_matrix X(Xdata, 4, 4); - vnl_real_eigensystem eig(X); + const vnl_real_eigensystem eig(X); std::cout << "D = " << eig.D << std::endl << "V = " << eig.V << std::endl; - vnl_matrix> XC = vnl_complexify(X); + const vnl_matrix> XC = vnl_complexify(X); - vnl_matrix> diff = XC * eig.V - eig.V * eig.D; + const vnl_matrix> diff = XC * eig.V - eig.V * eig.D; std::cout << "X*V - V*D = " << diff << std::endl << "residual = " << diff.fro_norm() << std::endl; TEST_NEAR("recompose residual", diff.fro_norm(), 0.0, 1e-11); } diff --git a/core/vnl/algo/tests/test_rnpoly_roots.cxx b/core/vnl/algo/tests/test_rnpoly_roots.cxx index 23d0a544f42..31af578005a 100644 --- a/core/vnl/algo/tests/test_rnpoly_roots.cxx +++ b/core/vnl/algo/tests/test_rnpoly_roots.cxx @@ -11,7 +11,8 @@ print_roots(vnl_rnpoly_solve & solver) std::vector *> im = solver.imag(); const unsigned int dim = re[0]->size(); std::cout << "Roots are:" << std::endl; - std::vector *>::iterator rp, ip; + std::vector *>::iterator rp; + std::vector *>::iterator ip; for (rp = re.begin(), ip = im.begin(); rp != re.end(); ++rp, ++ip) { for (unsigned int i = 0; i < dim; ++i) @@ -31,7 +32,7 @@ unit_circles_intersect() constexpr unsigned int dim = 2; // two-dimensional problem setting double f1_data[] = { 1.0, 1.0, -1.0 }; - vnl_vector f1(f1_data, 3); + const vnl_vector f1(f1_data, 3); vnl_matrix p1(3, dim, 0); p1(0, 0) = 2; p1(1, 1) = 2; @@ -39,24 +40,25 @@ unit_circles_intersect() std::cout << poly1; // X^2 +Y^2 -1 double f2_data[] = { 1.0, -1.0 }; - vnl_vector f2(f2_data, 2); + const vnl_vector f2(f2_data, 2); vnl_matrix p2(2, 2, 0); p2(0, 0) = 1; - vnl_real_npolynomial monom1(f2, p2); + const vnl_real_npolynomial monom1(f2, p2); std::cout << monom1; // X-1 vnl_real_npolynomial poly2 = monom1 * monom1; // (X-1)^2 poly2 = poly2 - 1; - vnl_vector f3(1, 1.0); + const vnl_vector f3(1, 1.0); vnl_matrix p3(1, dim, 0); p3(0, 1) = 2; - vnl_real_npolynomial monom3(f3, p3); // Y^2 + const vnl_real_npolynomial monom3(f3, p3); // Y^2 poly2 = poly2 + monom3; std::cout << poly2; // (X-1)^2 +Y^2 -1 = X^2 -2X +Y^2 - std::vector *>::iterator rp, ip; + std::vector *>::iterator rp; + const std::vector *>::iterator ip; std::vector l(1, &poly1); l.push_back(&poly2); @@ -72,8 +74,8 @@ unit_circles_intersect() TEST_NEAR("x==0.5", root[0], 0.5, 1e-9); TEST_NEAR("y==sqrt(0.75)", root[1] * root[1], 0.75, 1e-9); } - std::vector *> roots_r = solver.real(); - std::vector *> roots_i = solver.imag(); + const std::vector *> roots_r = solver.real(); + const std::vector *> roots_i = solver.imag(); TEST("and no more finite imaginary roots", roots_r.size(), 2); TEST("and equally many imaginary parts", roots_i.size(), 2); print_roots(solver); @@ -98,7 +100,8 @@ ellipses_intersect() vnl_real_npolynomial poly4(f1, p1); std::cout << poly4; // 2 X^2 +Y^2 -1 - std::vector *>::iterator rp, ip; + std::vector *>::iterator rp; + const std::vector *>::iterator ip; std::vector l(1, &poly3); l.push_back(&poly4); @@ -164,10 +167,10 @@ single_fourth_degree() pol(3, 0) = 1; pol(4, 0) = 0; vnl_real_npolynomial monom1(coeffs, pol); - std::vector l(1, &monom1); + const std::vector l(1, &monom1); vnl_rnpoly_solve solver(l); std::vector *> realVal = solver.real(); - std::vector *> imagVal = solver.imag(); + const std::vector *> imagVal = solver.imag(); TEST("Real part of roots has size 4", realVal.size(), 4); TEST("Imag part of roots has size 4", imagVal.size(), 4); @@ -199,7 +202,7 @@ scaled_fourth_degree() coeffs[4] = 4121959965347122688.0; // Scale before computing roots: - double factor = std::sqrt(std::sqrt(coeffs[4] / coeffs[0])); + const double factor = std::sqrt(std::sqrt(coeffs[4] / coeffs[0])); // this is the 4th root of the scale difference between first and last coef double mfactor = 1.0; for (int i = 0; i <= 4; ++i) @@ -212,13 +215,14 @@ scaled_fourth_degree() pol(3, 0) = 1; pol(4, 0) = 0; vnl_real_npolynomial monom1(coeffs, pol); - std::vector l(1, &monom1); + const std::vector l(1, &monom1); vnl_rnpoly_solve solver(l); std::vector *> realVal = solver.real(); std::vector *> imagVal = solver.imag(); // Scale back the roots: - std::vector *>::iterator rp, ip; + std::vector *>::iterator rp; + std::vector *>::iterator ip; for (rp = realVal.begin(), ip = imagVal.begin(); rp != realVal.end(); ++rp, ++ip) { for (unsigned int i = 0; i < dim; ++i) diff --git a/core/vnl/algo/tests/test_rpoly_roots.cxx b/core/vnl/algo/tests/test_rpoly_roots.cxx index bb149c51252..f15617115d7 100644 --- a/core/vnl/algo/tests/test_rpoly_roots.cxx +++ b/core/vnl/algo/tests/test_rpoly_roots.cxx @@ -6,7 +6,7 @@ void test_rpoly_roots() { double coeffs[] = { 5, 4, 3, 2, 1 }; - vnl_vector a(coeffs, 5); + const vnl_vector a(coeffs, 5); vnl_rpoly_roots roots(a); @@ -16,7 +16,7 @@ test_rpoly_roots() // TEST("degree", roots.degree(), 4); // Evaluate results - vnl_real_polynomial p(a); + const vnl_real_polynomial p(a); for (int i = 0; i < p.degree(); ++i) TEST_NEAR("Root residual", std::abs(p.evaluate(roots[i])), 0.0, 1e-12); } diff --git a/core/vnl/algo/tests/test_solve_qp.cxx b/core/vnl/algo/tests/test_solve_qp.cxx index 05813451321..b199cb91bea 100644 --- a/core/vnl/algo/tests/test_solve_qp.cxx +++ b/core/vnl/algo/tests/test_solve_qp.cxx @@ -12,19 +12,21 @@ test_solve_qp_with_non_neg_constraints1() // Minimise |x|^2 subject to 1.x=1 and x(i)>=0 // x(i)>=0 not relevant for this solution - unsigned n = 4; + const unsigned n = 4; vnl_matrix H(n, n, 0.0); for (unsigned i = 0; i < n; ++i) H(i, i) = 1.0; - vnl_matrix A(1, n, 1.0); - vnl_vector g(n, 0.0), b(1, 1.0), x(n, 0.0); + const vnl_matrix A(1, n, 1.0); + const vnl_vector g(n, 0.0); + const vnl_vector b(1, 1.0); + vnl_vector x(n, 0.0); // Initialise to satisfy Ax=b x[0] = 1.0; vnl_solve_qp_with_non_neg_constraints(H, g, A, b, x); - vnl_vector sol(n, 1.0 / n); + const vnl_vector sol(n, 1.0 / n); std::cout << "Solution: " << x << std::endl; TEST_NEAR("|x-x_true|^2", vnl_vector_ssd(x, sol), 0, 1e-5); @@ -36,12 +38,14 @@ test_solve_qp_with_non_neg_constraints2() // Minimise 0.5|x|^2 -x.(1 -1 1 1) subject to 1.x=1 and x(i)>=0 // x(i)>=0 not relevant for this solution - unsigned n = 4; + const unsigned n = 4; vnl_matrix H(n, n, 0.0); for (unsigned i = 0; i < n; ++i) H(i, i) = 1.0; - vnl_matrix A(1, n, 1.0); - vnl_vector g(n, -1.0), b(1, 1.0), x(n, 0.0); + const vnl_matrix A(1, n, 1.0); + vnl_vector g(n, -1.0); + const vnl_vector b(1, 1.0); + vnl_vector x(n, 0.0); g[1] = 1.0; // Initialise to satisfy Ax=b @@ -62,18 +66,19 @@ test_solve_qp_non_neg_sum_one1() // Minimise |x|^2 subject to 1.x=1 and x(i)>=0 // x(i)>=0 not relevant for this solution - unsigned n = 4; + const unsigned n = 4; vnl_matrix H(n, n, 0.0); for (unsigned i = 0; i < n; ++i) H(i, i) = 1.0; - vnl_vector g(n, 0.0), x(n, 0.0); + const vnl_vector g(n, 0.0); + vnl_vector x(n, 0.0); // Initialise to satisfy sum(x)=1 x[0] = 1.0; vnl_solve_qp_non_neg_sum_one(H, g, x); - vnl_vector sol(n, 1.0 / n); + const vnl_vector sol(n, 1.0 / n); std::cout << "Solution: " << x << std::endl; TEST_NEAR("|x-x_true|^2", vnl_vector_ssd(x, sol), 0, 1e-5); @@ -85,11 +90,12 @@ test_solve_qp_non_neg_sum_one2() // Minimise 0.5|x|^2 -x.(1 -1 1 1) subject to 1.x=1 and x(i)>=0 // x(i)>=0 not relevant for this solution - unsigned n = 4; + const unsigned n = 4; vnl_matrix H(n, n, 0.0); for (unsigned i = 0; i < n; ++i) H(i, i) = 1.0; - vnl_vector g(n, -1.0), x(n, 0.0); + vnl_vector g(n, -1.0); + vnl_vector x(n, 0.0); g[1] = 1.0; // Initialise to satisfy sum(x)=1 diff --git a/core/vnl/algo/tests/test_sparse_lm.cxx b/core/vnl/algo/tests/test_sparse_lm.cxx index fc1aeb61568..6aa31ed8cb3 100644 --- a/core/vnl/algo/tests/test_sparse_lm.cxx +++ b/core/vnl/algo/tests/test_sparse_lm.cxx @@ -14,8 +14,9 @@ static void normalize(vnl_vector & a, vnl_vector & b) { - double x_mean = 0.0, y_mean = 0.0; - unsigned int num_pts = b.size() / 2; + double x_mean = 0.0; + double y_mean = 0.0; + const unsigned int num_pts = b.size() / 2; for (unsigned int i = 0; i < num_pts; ++i) { x_mean += b[2 * i]; @@ -33,8 +34,8 @@ normalize(vnl_vector & a, vnl_vector & b) // translate cameras for (unsigned int i = 0; i < a.size() / 3; ++i) { - double sa = std::sin(a[3 * i]); - double ca = std::cos(a[3 * i]); + const double sa = std::sin(a[3 * i]); + const double ca = std::cos(a[3 * i]); a[3 * i + 1] += ca * x_mean - sa * y_mean; a[3 * i + 2] += sa * x_mean + ca * y_mean; } @@ -59,17 +60,17 @@ normalize(vnl_vector & a, vnl_vector & b) } // use the vector between the first two points for orientation - double dx = b[0] - b[2]; - double dy = b[1] - b[3]; - double angle = -std::atan2(dy, dx); - double sa = std::sin(angle); - double ca = std::cos(angle); + const double dx = b[0] - b[2]; + const double dy = b[1] - b[3]; + const double angle = -std::atan2(dy, dx); + const double sa = std::sin(angle); + const double ca = std::cos(angle); // rotate points for (unsigned int i = 0; i < num_pts; ++i) { - double v1 = ca * b[2 * i] - sa * b[2 * i + 1]; - double v2 = sa * b[2 * i] + ca * b[2 * i + 1]; + const double v1 = ca * b[2 * i] - sa * b[2 * i + 1]; + const double v2 = sa * b[2 * i] + ca * b[2 * i + 1]; b[2 * i] = v1; b[2 * i + 1] = v2; } @@ -106,36 +107,40 @@ camera_diff(const vnl_vector & a1, const vnl_vector & a2) class bundle_2d : public vnl_sparse_lst_sqr_function { public: - bundle_2d(unsigned int num_cam, unsigned int num_pts, vnl_vector data, - const std::vector> &xmask, - UseGradient g = use_gradient, UseWeights w = no_weights) - : vnl_sparse_lst_sqr_function(num_cam, 3, num_pts, 2, 0, xmask, 1, g, w), - data_(std::move(data)) {} + bundle_2d(unsigned int num_cam, + unsigned int num_pts, + vnl_vector data, + const std::vector> & xmask, + UseGradient g = use_gradient, + UseWeights w = no_weights) + : vnl_sparse_lst_sqr_function(num_cam, 3, num_pts, 2, 0, xmask, 1, g, w) + , data_(std::move(data)) + {} void fij(int i, int j, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & /*c*/, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & /*c*/, vnl_vector & fxij) override { - double sa = std::sin(ai[0]); - double ca = std::cos(ai[0]); + const double sa = std::sin(ai[0]); + const double ca = std::cos(ai[0]); fxij[0] = (ca * bj[0] - sa * bj[1] + ai[1]) / (sa * bj[0] + ca * bj[1] + ai[2]) - data_[residual_indices_(i, j)]; } void jac_Aij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & /*c*/, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & /*c*/, vnl_matrix & Aij) override { - double sa = std::sin(ai[0]); - double ca = std::cos(ai[0]); - double denom = (sa * bj[0] + ca * bj[1] + ai[2]); + const double sa = std::sin(ai[0]); + const double ca = std::cos(ai[0]); + const double denom = (sa * bj[0] + ca * bj[1] + ai[2]); Aij[0][0] = -((sa * bj[0] + ca * bj[1]) + (ca * bj[0] - sa * bj[1] + ai[1]) * (ca * bj[0] - sa * bj[1]) / denom) / denom; Aij[0][1] = 1 / denom; @@ -145,25 +150,25 @@ class bundle_2d : public vnl_sparse_lst_sqr_function void jac_Bij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & /*c*/, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & /*c*/, vnl_matrix & Bij) override { - double sa = std::sin(ai[0]); - double ca = std::cos(ai[0]); - double denom = (sa * bj[0] + ca * bj[1] + ai[2]); - double numer = (ca * bj[0] - sa * bj[1] + ai[1]); + const double sa = std::sin(ai[0]); + const double ca = std::cos(ai[0]); + const double denom = (sa * bj[0] + ca * bj[1] + ai[2]); + const double numer = (ca * bj[0] - sa * bj[1] + ai[1]); Bij[0][0] = (ca - sa * numer / denom) / denom; Bij[0][1] = (-sa - ca * numer / denom) / denom; } void trace(int /*iteration*/, - vnl_vector const & /*a*/, - vnl_vector const & /*b*/, - vnl_vector const & /*c*/, - vnl_vector const & /*e*/) override + const vnl_vector & /*a*/, + const vnl_vector & /*b*/, + const vnl_vector & /*c*/, + const vnl_vector & /*e*/) override { // std::cout << "trace "< null_row(25, true); + const std::vector null_row(25, true); std::vector> mask(4, null_row); const double a_data[] = { 0.0, 0.0, 0.0, 0.8, 10.0, 8.0, -0.7, -8.5, 8.5, 0.4, 4.0, 4.0 }; @@ -184,8 +189,10 @@ test_prob1() 2.0, 12.0, 4.0, 12.0, -4.0, 14.0, -2.0, 14.0, 0.0, 14.0, 2.0, 14.0, 4.0, 14.0, -4.0, 16.0, -2.0, 16.0, 0.0, 16.0, 2.0, 16.0, 4.0, 16.0 }; - vnl_vector a(a_data, 12), b(b_data, 50), proj(100, 0.0); - vnl_vector c; + vnl_vector a(a_data, 12); + vnl_vector b(b_data, 50); + vnl_vector proj(100, 0.0); + const vnl_vector c; // create a generator function with ideal data and zeros for all projections // the residuals of this functions are the ideal project points @@ -204,7 +211,9 @@ test_prob1() // test 2D bundle adjustment with all data and no noise { // initial conditions (all points at origin) - vnl_vector pa(12, 0.0), pb(50, 0.0), pc; + vnl_vector pa(12, 0.0); + vnl_vector pb(50, 0.0); + vnl_vector pc; pa[2] = pa[5] = pa[8] = pa[11] = 10; pa[4] = 5; pa[7] = -5; @@ -227,8 +236,8 @@ test_prob1() std::cout << a << '|' << b << '\n' << pa << '|' << pb << std::endl; #endif - double rms_error_a = camera_diff(a, pa).rms(); - double rms_error_b = (b - pb).rms(); + double const rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_b = (b - pb).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_b << std::endl; TEST("convergence with all projections", rms_error_a + rms_error_b < 1e-10, true); } @@ -250,13 +259,13 @@ test_prob1() mask[2][12] = false; // create a subset of projections based on the mask - vnl_crs_index crs(mask); + const vnl_crs_index crs(mask); vnl_vector proj2(crs.num_non_zero()); for (int i = 0; i < crs.num_rows(); ++i) { for (int j = 0; j < crs.num_cols(); ++j) { - int k = crs(i, j); + const int k = crs(i, j); if (k >= 0) proj2[k] = proj[i * crs.num_cols() + j]; } @@ -265,7 +274,9 @@ test_prob1() // test 2D bundle adjustment with missing data and no noise { // initial conditions (all points at origin) - vnl_vector pa(12, 0.0), pb(50, 0.0), pc; + vnl_vector pa(12, 0.0); + vnl_vector pb(50, 0.0); + vnl_vector pc; pa[2] = pa[5] = pa[8] = pa[11] = 10; pa[4] = 5; pa[7] = -5; @@ -282,8 +293,8 @@ test_prob1() // first two points is on the x-axis normalize(pa, pb); - double rms_error_a = camera_diff(a, pa).rms(); - double rms_error_b = (b - pb).rms(); + const double rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_b = (b - pb).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_b << std::endl; TEST("convergence with missing projections", rms_error_a + rms_error_b < 1e-10, true); } @@ -299,7 +310,9 @@ test_prob1() // test 2D bundle adjustment with missing data and uniform noise { // initial conditions (all points at origin) - vnl_vector pa(12, 0.0), pb(50, 0.0), pc; + vnl_vector pa(12, 0.0); + vnl_vector pb(50, 0.0); + vnl_vector pc; pa[2] = pa[5] = pa[8] = pa[11] = 10; pa[4] = 5; pa[7] = -5; @@ -318,8 +331,8 @@ test_prob1() // first two points is on the x-axis normalize(pa, pb); - double rms_error_a = camera_diff(a, pa).rms(); - double rms_error_b = (b - pb).rms(); + const double rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_b = (b - pb).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_a << std::endl; TEST("convergence with missing projections and noise", rms_error_a < 1e-4 && rms_error_b < 1e-4, true); } @@ -339,23 +352,25 @@ test_prob1() class bundle_2d_shared : public vnl_sparse_lst_sqr_function { public: - bundle_2d_shared(unsigned int num_cam, unsigned int num_pts, + bundle_2d_shared(unsigned int num_cam, + unsigned int num_pts, vnl_vector data, - const std::vector> &xmask, + const std::vector> & xmask, UseGradient g = use_gradient) - : vnl_sparse_lst_sqr_function(num_cam, 3, num_pts, 2, 1, xmask, 1, g), - data_(std::move(data)) {} + : vnl_sparse_lst_sqr_function(num_cam, 3, num_pts, 2, 1, xmask, 1, g) + , data_(std::move(data)) + {} void fij(int i, int j, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & c, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, vnl_vector & fxij) override { - double sa = std::sin(ai[0]); - double ca = std::cos(ai[0]); + const double sa = std::sin(ai[0]); + const double ca = std::cos(ai[0]); fxij[0] = c[0] * (ca * bj[0] - sa * bj[1] + ai[1]) / (sa * bj[0] + ca * bj[1] + ai[2]) - data_[residual_indices_(i, j)]; } @@ -363,14 +378,14 @@ class bundle_2d_shared : public vnl_sparse_lst_sqr_function void jac_Aij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & c, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, vnl_matrix & Aij) override { - double sa = std::sin(ai[0]); - double ca = std::cos(ai[0]); - double denom = (sa * bj[0] + ca * bj[1] + ai[2]); + const double sa = std::sin(ai[0]); + const double ca = std::cos(ai[0]); + const double denom = (sa * bj[0] + ca * bj[1] + ai[2]); Aij[0][0] = -c[0] * ((sa * bj[0] + ca * bj[1]) + (ca * bj[0] - sa * bj[1] + ai[1]) * (ca * bj[0] - sa * bj[1]) / denom) / denom; @@ -381,15 +396,15 @@ class bundle_2d_shared : public vnl_sparse_lst_sqr_function void jac_Bij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & c, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, vnl_matrix & Bij) override { - double sa = std::sin(ai[0]); - double ca = std::cos(ai[0]); - double denom = (sa * bj[0] + ca * bj[1] + ai[2]); - double numer = c[0] * (ca * bj[0] - sa * bj[1] + ai[1]); + const double sa = std::sin(ai[0]); + const double ca = std::cos(ai[0]); + const double denom = (sa * bj[0] + ca * bj[1] + ai[2]); + const double numer = c[0] * (ca * bj[0] - sa * bj[1] + ai[1]); Bij[0][0] = (c[0] * ca - sa * numer / denom) / denom; Bij[0][1] = (-c[0] * sa - ca * numer / denom) / denom; } @@ -397,14 +412,14 @@ class bundle_2d_shared : public vnl_sparse_lst_sqr_function void jac_Cij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & /*c*/, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & /*c*/, vnl_matrix & Cij) override { - double sa = std::sin(ai[0]); - double ca = std::cos(ai[0]); - double denom = (sa * bj[0] + ca * bj[1] + ai[2]); + const double sa = std::sin(ai[0]); + const double ca = std::cos(ai[0]); + const double denom = (sa * bj[0] + ca * bj[1] + ai[2]); Cij[0][0] = (ca * bj[0] - sa * bj[1] + ai[1]) / denom; } @@ -415,7 +430,7 @@ class bundle_2d_shared : public vnl_sparse_lst_sqr_function void test_prob2() { - std::vector null_row(25, true); + const std::vector null_row(25, true); std::vector> mask(4, null_row); const double a_data[] = { 0.0, 0.0, 0.0, 0.8, 10.0, 8.0, -0.7, -8.5, 8.5, 0.4, 4.0, 4.0 }; @@ -424,7 +439,10 @@ test_prob2() 2.0, 12.0, 4.0, 12.0, -4.0, 14.0, -2.0, 14.0, 0.0, 14.0, 2.0, 14.0, 4.0, 14.0, -4.0, 16.0, -2.0, 16.0, 0.0, 16.0, 2.0, 16.0, 4.0, 16.0 }; - vnl_vector a(a_data, 12), b(b_data, 50), c(1, 1.5), proj(100, 0.0); + vnl_vector a(a_data, 12); + vnl_vector b(b_data, 50); + const vnl_vector c(1, 1.5); + vnl_vector proj(100, 0.0); // create a generator function with ideal data and zeros for all projections // the residuals of this functions are the ideal project points @@ -439,7 +457,9 @@ test_prob2() // test 2D bundle adjustment with all data and no noise { // initial conditions (all points at origin) - vnl_vector pa(12, 0.0), pb(50, 0.0), pc(1, 1.0); + vnl_vector pa(12, 0.0); + vnl_vector pb(50, 0.0); + vnl_vector pc(1, 1.0); pa[2] = pa[5] = pa[8] = pa[11] = 10; pa[4] = 5; pa[7] = -5; @@ -457,9 +477,9 @@ test_prob2() // first two points is on the x-axis normalize(pa, pb); - double rms_error_a = camera_diff(a, pa).rms(); - double rms_error_b = (b - pb).rms(); - double rms_error_c = (c - pc).rms(); + const double rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_b = (b - pb).rms(); + const double rms_error_c = (c - pc).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_b << "\nRMS globals error: " << rms_error_c << std::endl; TEST("w/ globals: convergence with all projections", rms_error_a + rms_error_b + rms_error_c < 1e-10, true); @@ -484,13 +504,13 @@ test_prob2() mask[2][12] = false; // create a subset of projections based on the mask - vnl_crs_index crs(mask); + const vnl_crs_index crs(mask); vnl_vector proj2(crs.num_non_zero()); for (int i = 0; i < crs.num_rows(); ++i) { for (int j = 0; j < crs.num_cols(); ++j) { - int k = crs(i, j); + const int k = crs(i, j); if (k >= 0) proj2[k] = proj[i * crs.num_cols() + j]; } @@ -499,7 +519,9 @@ test_prob2() // test 2D bundle adjustment with missing data and no noise { // initial conditions (all points at origin) - vnl_vector pa(12, 0.0), pb(50, 0.0), pc(1, 1.0); + vnl_vector pa(12, 0.0); + vnl_vector pb(50, 0.0); + vnl_vector pc(1, 1.0); pa[2] = pa[5] = pa[8] = pa[11] = 10; pa[4] = 5; pa[7] = -5; @@ -516,9 +538,9 @@ test_prob2() // first two points is on the x-axis normalize(pa, pb); - double rms_error_a = camera_diff(a, pa).rms(); - double rms_error_b = (b - pb).rms(); - double rms_error_c = (c - pc).rms(); + const double rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_b = (b - pb).rms(); + const double rms_error_c = (c - pc).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_b << "\nRMS globals error: " << rms_error_c << std::endl; TEST("w/ globals: convergence with missing projections", rms_error_a + rms_error_b + rms_error_c < 1e-10, true); @@ -535,7 +557,9 @@ test_prob2() // test 2D bundle adjustment with missing data and uniform noise { // initial conditions (all points at origin) - vnl_vector pa(12, 0.0), pb(50, 0.0), pc(1, 1.0); + vnl_vector pa(12, 0.0); + vnl_vector pb(50, 0.0); + vnl_vector pc(1, 1.0); pa[2] = pa[5] = pa[8] = pa[11] = 10; pa[4] = 5; pa[7] = -5; @@ -553,10 +577,10 @@ test_prob2() // first two points is on the x-axis normalize(pa, pb); - double rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_a = camera_diff(a, pa).rms(); ; - double rms_error_b = (b - pb).rms(); - double rms_error_c = (c - pc).rms(); + const double rms_error_b = (b - pb).rms(); + const double rms_error_c = (c - pc).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_b << "\nRMS globals error: " << rms_error_c << std::endl; TEST("w/ globals: convergence with missing projections and noise", @@ -579,7 +603,7 @@ class bundle_2d_robust : public bundle_2d const std::vector> & xmask, UseGradient g = use_gradient) : bundle_2d(num_cam, num_pts, data, xmask, g, use_weights) - , scale2_(1.0) + {} void @@ -591,15 +615,15 @@ class bundle_2d_robust : public bundle_2d void compute_weight_ij(int i, int j, - vnl_vector const & /*ai*/, - vnl_vector const & /*bj*/, - vnl_vector const & /*c*/, - vnl_vector const & fij, + const vnl_vector & /*ai*/, + const vnl_vector & /*bj*/, + const vnl_vector & /*c*/, + const vnl_vector & fij, double & weight) override { - int k = residual_indices_(i, j); + const int k = residual_indices_(i, j); assert(k >= 0); - double ek2 = fij.squared_magnitude(); + const double ek2 = fij.squared_magnitude(); weight = std::sqrt(mest(k, ek2)); } @@ -611,7 +635,7 @@ class bundle_2d_robust : public bundle_2d return 0.0; else { - double tmp = 1 - ek2 / scale2_; + const double tmp = 1 - ek2 / scale2_; return tmp * tmp; } } @@ -628,22 +652,22 @@ class bundle_2d_robust : public bundle_2d void trace(int /*iteration*/, - vnl_vector const & /*a*/, - vnl_vector const & /*b*/, - vnl_vector const & /*c*/, - vnl_vector const & /*e*/) override + const vnl_vector & /*a*/, + const vnl_vector & /*b*/, + const vnl_vector & /*c*/, + const vnl_vector & /*e*/) override { // std::cout << "trace "< null_row(25, true); + const std::vector null_row(25, true); std::vector> mask(4, null_row); const double a_data[] = { 0.0, 0.0, 0.0, 0.8, 10.0, 8.0, -0.7, -8.5, 8.5, 0.4, 4.0, 4.0 }; @@ -652,12 +676,16 @@ test_prob3() 2.0, 12.0, 4.0, 12.0, -4.0, 14.0, -2.0, 14.0, 0.0, 14.0, 2.0, 14.0, 4.0, 14.0, -4.0, 16.0, -2.0, 16.0, 0.0, 16.0, 2.0, 16.0, 4.0, 16.0 }; - vnl_vector a(a_data, 12), b(b_data, 50), proj(100, 0.0); - vnl_vector c; + vnl_vector a(a_data, 12); + vnl_vector b(b_data, 50); + vnl_vector proj(100, 0.0); + const vnl_vector c; // initial perturbed parameters, add random gaussian noise - vnl_vector init_a(a_data, 12), init_b(b_data, 50); - double sigma_pos = 1.0, sigma_ang = 0.1; + vnl_vector init_a(a_data, 12); + vnl_vector init_b(b_data, 50); + const double sigma_pos = 1.0; + const double sigma_ang = 0.1; vnl_random rnd(1234); for (unsigned i = 0; i < init_a.size() / 3; ++i) { @@ -679,8 +707,12 @@ test_prob3() bundle_2d_robust func(4, 25, proj, mask, vnl_sparse_lst_sqr_function::use_gradient); func.set_scale(0.3); - vnl_matrix A1(1, 3), A2(1, 3), B1(1, 2), B2(1, 2); - vnl_vector ai(3, 0.0), bj(2, 0.0); + vnl_matrix A1(1, 3); + vnl_matrix A2(1, 3); + vnl_matrix B1(1, 2); + vnl_matrix B2(1, 2); + vnl_vector ai(3, 0.0); + vnl_vector bj(2, 0.0); vnl_vector fxij(1, 0.0); ai[0] = 0.1; ai[1] = -0.0; @@ -688,10 +720,10 @@ test_prob3() bj[0] = -2; bj[1] = 10000; func.fij(0, 0, ai, bj, c, fxij); - double e2 = fxij.squared_magnitude(); - double m1 = func.mest(0, e2); - double dm1 = func.d_mest(0, e2); - double dm2 = (func.mest(0, e2 + 1e-8) - m1) / (1e-8); + const double e2 = fxij.squared_magnitude(); + const double m1 = func.mest(0, e2); + const double dm1 = func.d_mest(0, e2); + const double dm2 = (func.mest(0, e2 + 1e-8) - m1) / (1e-8); TEST_NEAR("derive mest = finite diff", dm1, dm2, 1e-4); std::cout << fxij << std::endl; func.jac_Aij(0, 0, ai, bj, c, A1); @@ -710,7 +742,9 @@ test_prob3() // test 2D bundle adjustment with all data and no noise { // initial conditions (all points at origin) - vnl_vector pa(init_a), pb(init_b), pc; + vnl_vector pa(init_a); + vnl_vector pb(init_b); + vnl_vector pc; bundle_2d_robust my_func(4, 25, proj, mask, vnl_sparse_lst_sqr_function::use_gradient); my_func.set_scale(1.0); @@ -730,8 +764,8 @@ test_prob3() std::cout << a << '|' << b << '\n' << pa << '|' << pb << std::endl; #endif - double rms_error_a = camera_diff(a, pa).rms(); - double rms_error_b = (b - pb).rms(); + double const rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_b = (b - pb).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_b << std::endl; TEST("robust convergence with all projections", rms_error_a + rms_error_b < 1e-10, true); } @@ -756,13 +790,13 @@ test_prob3() proj[33] -= 20.0; // create a subset of projections based on the mask - vnl_crs_index crs(mask); + const vnl_crs_index crs(mask); vnl_vector proj2(crs.num_non_zero()); for (int i = 0; i < crs.num_rows(); ++i) { for (int j = 0; j < crs.num_cols(); ++j) { - int k = crs(i, j); + const int k = crs(i, j); if (k >= 0) proj2[k] = proj[i * crs.num_cols() + j]; } @@ -771,7 +805,9 @@ test_prob3() // test 2D bundle adjustment with missing data and no noise { // initial conditions (all points at origin) - vnl_vector pa(init_a), pb(init_b), pc; + vnl_vector pa(init_a); + vnl_vector pb(init_b); + vnl_vector pc; bundle_2d_robust my_func(4, 25, proj2, mask, vnl_sparse_lst_sqr_function::use_gradient); my_func.set_scale(1.0); @@ -786,8 +822,8 @@ test_prob3() // first two points is on the x-axis normalize(pa, pb); - double rms_error_a = camera_diff(a, pa).rms(); - double rms_error_b = (b - pb).rms(); + const double rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_b = (b - pb).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_b << std::endl; TEST("convergence with missing projections", rms_error_a + rms_error_b < 1e-10, true); } @@ -801,7 +837,9 @@ test_prob3() // test 2D bundle adjustment with missing data and uniform noise { // initial conditions (all points at origin) - vnl_vector pa(init_a), pb(init_b), pc; + vnl_vector pa(init_a); + vnl_vector pb(init_b); + vnl_vector pc; bundle_2d_robust my_func(4, 25, proj2, mask, vnl_sparse_lst_sqr_function::use_gradient); my_func.set_scale(1.0); @@ -816,8 +854,8 @@ test_prob3() // first two points is on the x-axis normalize(pa, pb); - double rms_error_a = camera_diff(a, pa).rms(); - double rms_error_b = (b - pb).rms(); + const double rms_error_a = camera_diff(a, pa).rms(); + const double rms_error_b = (b - pb).rms(); std::cout << "RMS camera error: " << rms_error_a << "\nRMS points error: " << rms_error_b << std::endl; TEST("convergence with missing projections and noise", rms_error_a < 1e-4 && rms_error_b < 1e-4, true); } diff --git a/core/vnl/algo/tests/test_sparse_lu.cxx b/core/vnl/algo/tests/test_sparse_lu.cxx index e2abc081ccd..7053c65ac69 100644 --- a/core/vnl/algo/tests/test_sparse_lu.cxx +++ b/core/vnl/algo/tests/test_sparse_lu.cxx @@ -9,8 +9,14 @@ test_sparse_lu() { // mat0 of Kenneth S. Kunder's Sparse 1.3a release vnl_sparse_matrix A(4, 4); - std::vector cols0(2), cols1(3), cols2(3), cols3(2); - std::vector vals0(2), vals1(3), vals2(3), vals3(2); + std::vector cols0(2); + std::vector cols1(3); + std::vector cols2(3); + std::vector cols3(2); + std::vector vals0(2); + std::vector vals1(3); + std::vector vals2(3); + std::vector vals3(2); cols0[0] = 0; cols0[1] = 1; vals0[0] = 2.0; @@ -37,7 +43,8 @@ test_sparse_lu() A.set_row(3, cols3, vals3); for (A.reset(); A.next();) std::cout << "A[" << A.getrow() << "][" << A.getcolumn() << "]= " << A.value() << '\n'; - vnl_vector b(4, 0.0), x(4); + vnl_vector b(4, 0.0); + vnl_vector x(4); b[0] = 34.0; vnl_sparse_lu lu(A, vnl_sparse_lu::verbose); lu.solve(b, &x); @@ -57,7 +64,8 @@ test_sparse_lu() Ap(0, 1) = 1; Ap(1, 2) = 1; Ap(2, 0) = 1; - vnl_vector bp(3), xp(3); + vnl_vector bp(3); + vnl_vector xp(3); bp[0] = 2.0; bp[1] = 3.0; bp[2] = 1.0; @@ -68,7 +76,9 @@ test_sparse_lu() TEST_NEAR("solution of mat5 example", xp[2], 3, 1.e-03); // test matrix derived from Poisson birth-death queue - double s = -0.01, l = 0.5, m = 0.5; + const double s = -0.01; + const double l = 0.5; + const double m = 0.5; vnl_sparse_matrix S(6, 6); S(0, 0) = s + l; S(0, 1) = -l; @@ -84,7 +94,8 @@ test_sparse_lu() S(4, 5) = -l; S(5, 4) = -m; S(5, 5) = m + s; - vnl_vector bbd(6), xbd(6); + vnl_vector bbd(6); + vnl_vector xbd(6); bbd[0] = 0; bbd[1] = 0; bbd[2] = l; @@ -98,10 +109,10 @@ test_sparse_lu() TEST_NEAR("test solution of birth-death matrix", xbd[2], 1.06622, 1.e-04); det = lubd.determinant(); std::cout << "birth-death determinant = " << det << '\n'; - double cond = lubd.rcond(); + const double cond = lubd.rcond(); std::cout << "birth-death condition number = " << cond << '\n'; TEST_NEAR("birth-death matrix condition number", cond, 0.03756, 1.e-04); - double upbnd = lubd.max_error_bound(); + const double upbnd = lubd.max_error_bound(); std::cout << "birth-death upper error bound = " << upbnd << '\n'; TEST_NEAR("birth-death upper error", upbnd, 5.923e-015, 1.e-016); } diff --git a/core/vnl/algo/tests/test_sparse_matrix.cxx b/core/vnl/algo/tests/test_sparse_matrix.cxx index 4ce8ec38ad1..269fa551d38 100644 --- a/core/vnl/algo/tests/test_sparse_matrix.cxx +++ b/core/vnl/algo/tests/test_sparse_matrix.cxx @@ -94,9 +94,9 @@ doTest2() m2(i, (i + n - 3) % n) = 1.0; } - vnl_sparse_matrix prod = m1 * m2; + const vnl_sparse_matrix prod = m1 * m2; - std::clock_t tn = std::clock(); + const std::clock_t tn = std::clock(); std::cout << n << ' ' << tn - t << std::endl; t = tn; } @@ -166,10 +166,10 @@ doTest4() // Report 'em. for (unsigned i = 0; i < nvals; i++) { - double dense = ed.D(i, i); - double sparse = es.get_eigenvalue(i); + const double dense = ed.D(i, i); + const double sparse = es.get_eigenvalue(i); std::cout << "Dense[" << i << "] : " << dense << '\n' << "Sparse[" << i << "]: " << sparse << std::endl; - double err = sparse - dense; + const double err = sparse - dense; TEST_NEAR("vnl_sparse_symmetric_eigensystem eigenvalue difference", err, 0.0, 1e-10); } } @@ -183,7 +183,8 @@ doTest5() // A * x = lambda * B * x // test that B = identity produces same answers as // A * x = lambda * x - vnl_sparse_matrix ms(n, n), bIdentity(n, n); + vnl_sparse_matrix ms(n, n); + vnl_sparse_matrix bIdentity(n, n); vnl_matrix md(n, n); md = 0.0; // Initialise to all zeros // The matrix must be symmetric @@ -206,10 +207,10 @@ doTest5() // Report 'em. for (unsigned i = 0; i < nvals; i++) { - double dense = ed.D(i, i); - double sparse = es.get_eigenvalue(i); + const double dense = ed.D(i, i); + const double sparse = es.get_eigenvalue(i); std::cout << "Dense[" << i << "] : " << dense << '\n' << "Sparse[" << i << "]: " << sparse << std::endl; - double err = sparse - dense; + const double err = sparse - dense; TEST_NEAR("vnl_sparse_symmetric_eigensystem eigenvalue difference", err, 0.0, 1e-10); } } @@ -251,7 +252,7 @@ doTest6() vnl_sparse_symmetric_eigensystem sse; // can't get all eigenvals because 0 < evCount < numLanzcosVectors < matOrd - int evCount = matOrd - 1; + const int evCount = matOrd - 1; // vnl_generalized_eigensystem always does algebraic smallest to largest TEST("vnl_sparse_symmetric_eigensystem::CalculateNPairs(A,B) succeeded", @@ -279,9 +280,9 @@ doTest6() // Report eVals. for (int i = 0; i < evCount; ++i) { - double dense = gev.D(i, i); - double sparse = sse.get_eigenvalue(i); - double err = sparse - dense; + const double dense = gev.D(i, i); + const double sparse = sse.get_eigenvalue(i); + const double err = sparse - dense; TEST_NEAR("vnl_sparse_symmetric_eigensystem general case eigenvalue difference", err, 0.0, 1e-10); } @@ -289,8 +290,8 @@ doTest6() std::cout << "Eigenvectors:" << std::endl; for (int evIx = 0; evIx < evCount; evIx++) { - double errSameSign = (sse.get_eigenvector(evIx) - gev.V.get_column(evIx)).two_norm(); - double errOppSign = (sse.get_eigenvector(evIx) + gev.V.get_column(evIx)).two_norm(); + const double errSameSign = (sse.get_eigenvector(evIx) - gev.V.get_column(evIx)).two_norm(); + const double errOppSign = (sse.get_eigenvector(evIx) + gev.V.get_column(evIx)).two_norm(); TEST_NEAR("vnl_sparse_symmetric_eigensystem general case eigenvector difference", errSameSign < errOppSign ? errSameSign : errOppSign, 0.0, diff --git a/core/vnl/algo/tests/test_svd.cxx b/core/vnl/algo/tests/test_svd.cxx index 66f9fea0af2..ca95f4677a9 100644 --- a/core/vnl/algo/tests/test_svd.cxx +++ b/core/vnl/algo/tests/test_svd.cxx @@ -14,7 +14,7 @@ template static void -test_hilbert(T /*dummy*/, char const * type, S residual) +test_hilbert(T /*dummy*/, const char * type, S residual) { std::cout << "----- Testing svd<" << type << ">(Hilbert_3x3) -----" << std::endl; using abs_t = typename vnl_numeric_traits::abs_t; @@ -26,13 +26,13 @@ test_hilbert(T /*dummy*/, char const * type, S residual) std::cout << "H = <" << type << ">[ " << H << "]\n"; - vnl_svd svd(H); + const vnl_svd svd(H); std::cout << "rcond(H) = " << svd.well_condition() << std::endl; - vnl_matrix Hinv = svd.inverse(); + const vnl_matrix Hinv = svd.inverse(); - vnl_matrix X = Hinv * H; + const vnl_matrix X = Hinv * H; std::cout << "H*inv(H) = " << X << std::endl; @@ -40,7 +40,7 @@ test_hilbert(T /*dummy*/, char const * type, S residual) I = 0.0; I.fill_diagonal(1.0); - vnl_matrix res = X - I; + const vnl_matrix res = X - I; TEST_NEAR("Hilbert recomposition residual", res.fro_norm(), 0, residual); } @@ -49,15 +49,15 @@ static void test_ls() { std::cout << "----- Testing svd on a Least Squares problem -----" << std::endl; - double a = 0.15; - double b = 1.2; - double c = 3.1; + const double a = 0.15; + const double b = 1.2; + const double c = 3.1; // Generate parabola design matrix vnl_matrix D(100, 3); for (int n = 0; n < 100; ++n) { - double x = n; + const double x = n; D(n, 0) = x * x; D(n, 1) = x; D(n, 2) = 1.0; @@ -67,21 +67,21 @@ test_ls() vnl_vector y(100); for (int n = 0; n < 100; ++n) { - double x = n; - double fx = a * x * x + b * x + c; + const double x = n; + const double fx = a * x * x + b * x + c; // Add sawtooth "noise" y(n) = fx + (n % 4 - 2) / 10.0; } std::cout << "y = [" << y << "]\n"; // Extract vnl_svd - vnl_svd svd(D); + const vnl_svd svd(D); // Solve for parameters - vnl_double_3 A = svd.solve(y); + const vnl_double_3 A = svd.solve(y); std::cout << "A = " << A << '\n'; - vnl_double_3 T(a, b, c); + const vnl_double_3 T(a, b, c); TEST_NEAR("Least squares residual", (A - T).squared_magnitude(), 0, 0.005); } @@ -92,28 +92,28 @@ test_pmatrix() double pdata[] = { 2, 0, 0, 0, 3, 10, 5, 5, 5, 12, 6, 6, }; - vnl_matrix P(pdata, 3, 4); - vnl_svd svd(P, 1e-8); + const vnl_matrix P(pdata, 3, 4); + const vnl_svd svd(P, 1e-8); - vnl_matrix res = svd.recompose() - P; + const vnl_matrix res = svd.recompose() - P; TEST_NEAR("PMatrix recomposition residual", res.fro_norm(), 0, 1e-12); std::cout << " Inv = " << svd.inverse() << std::endl; TEST("singularities = 2", svd.singularities(), 2); TEST("rank = 2", svd.rank(), 2); - vnl_matrix N = svd.nullspace(); + const vnl_matrix N = svd.nullspace(); TEST("nullspace dimension", N.columns(), 2); std::cout << "null(P) =\n" << N << std::endl; - vnl_matrix PN = P * N; + const vnl_matrix PN = P * N; std::cout << "P * null(P) =\n" << PN << std::endl; TEST_NEAR("P nullspace residual", PN.fro_norm(), 0, 1e-12); - vnl_vector n = svd.nullvector(); + const vnl_vector n = svd.nullvector(); TEST_NEAR("P nullvector residual", (P * n).magnitude(), 0, 1e-12); - vnl_vector l = svd.left_nullvector(); + const vnl_vector l = svd.left_nullvector(); std::cout << "left_nullvector(P) = " << l << std::endl; TEST_NEAR("P left nullvector residual", (l * P).magnitude(), 0, 1e-12); } @@ -124,17 +124,17 @@ test_I() double Idata[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, }; - vnl_matrix P(3, 4, 12, Idata); + const vnl_matrix P(3, 4, 12, Idata); vnl_svd svd(P); std::cout << svd; - vnl_vector_fixed w_expected(1, 1, 1, 0); + const vnl_vector_fixed w_expected(1, 1, 1, 0); TEST_NEAR("Singular values", vnl_vector_ssd(w_expected, svd.W().diagonal().as_ref()), 0, 1e-16); } template void -test_svd_recomposition(char const * type, double maxres, T * /* tag */, vnl_random & rng) +test_svd_recomposition(const char * type, double maxres, T * /* tag */, vnl_random & rng) { // Test inversion of 5x5 matrix of T : std::cout << "----- Testing vnl_svd<" << type << "> recomposition -----\n"; @@ -143,12 +143,12 @@ test_svd_recomposition(char const * type, double maxres, T * /* tag */, vnl_rand test_util_fill_random(A.begin(), A.end(), rng); std::cout << "A = [\n" << A << "]\n"; - vnl_svd svd(A); + const vnl_svd svd(A); - vnl_matrix B = svd.recompose(); + const vnl_matrix B = svd.recompose(); std::cout << "B = [\n" << B << "]\n"; - double residual = (A - B).fro_norm(); + const double residual = (A - B).fro_norm(); TEST_NEAR("vnl_svd recomposition residual", residual, 0, maxres); } @@ -158,12 +158,12 @@ template static void test_nullvector(char const * type, double max_err, T *, vnl_random & rng) { - int n = 5; + const int n = 5; vnl_matrix A(n, n + 1); test_util_fill_random(A.begin(), A.end(), rng); - vnl_svd svd(A); - vnl_vector x = svd.nullvector(); - vnl_vector Ax = A * x; + const vnl_svd svd(A); + const vnl_vector x = svd.nullvector(); + const vnl_vector Ax = A * x; std::cout << __FILE__ ": type = " << type << std::endl; vnl_matlab_print(std::cout, A, "A", vnl_matlab_print_format_long); std::cout << __FILE__ ": || x|| = " << x.two_norm() << std::endl diff --git a/core/vnl/algo/tests/test_svd_fixed.cxx b/core/vnl/algo/tests/test_svd_fixed.cxx index 93ce138a746..c276645de06 100644 --- a/core/vnl/algo/tests/test_svd_fixed.cxx +++ b/core/vnl/algo/tests/test_svd_fixed.cxx @@ -17,7 +17,7 @@ template static void -test_hilbert(T /*dummy*/, char const * type, S residual) +test_hilbert(T /*dummy*/, const char * type, S residual) { std::cout << "----- Testing svd_fixed<" << type << ">(Hilbert_3x3) -----" << std::endl; using abs_t = typename vnl_numeric_traits::abs_t; @@ -29,13 +29,13 @@ test_hilbert(T /*dummy*/, char const * type, S residual) std::cout << "H = <" << type << ">[ " << H << "]\n"; - vnl_svd_fixed svd(H); + const vnl_svd_fixed svd(H); std::cout << "rcond(H) = " << svd.well_condition() << std::endl; - vnl_matrix_fixed Hinv = svd.inverse(); + const vnl_matrix_fixed Hinv = svd.inverse(); - vnl_matrix_fixed X = Hinv * H; + const vnl_matrix_fixed X = Hinv * H; std::cout << "H*inv(H) = " << X << std::endl; @@ -43,7 +43,7 @@ test_hilbert(T /*dummy*/, char const * type, S residual) I = 0.0; I.fill_diagonal(1.0); - vnl_matrix_fixed res = X - I; + const vnl_matrix_fixed res = X - I; TEST_NEAR("Hilbert recomposition residual", res.fro_norm(), 0, residual); } @@ -57,28 +57,28 @@ test_pmatrix() double pdata[] = { 2, 0, 0, 0, 3, 10, 5, 5, 5, 12, 6, 6, }; - vnl_matrix_fixed P(pdata); - vnl_svd_fixed svd(P, 1e-8); + const vnl_matrix_fixed P(pdata); + const vnl_svd_fixed svd(P, 1e-8); - vnl_matrix_fixed res = svd.recompose() - P; + const vnl_matrix_fixed res = svd.recompose() - P; TEST_NEAR("PMatrix recomposition residual", res.fro_norm(), 0, 1e-12); std::cout << " Inv = " << svd.inverse() << std::endl; TEST("singularities = 2", svd.singularities(), 2); TEST("rank = 2", svd.rank(), 2); - vnl_matrix N = svd.nullspace(); + const vnl_matrix N = svd.nullspace(); TEST("nullspace dimension", N.columns(), 2); std::cout << "null(P) =\n" << N << std::endl; - vnl_matrix PN = P * N; + const vnl_matrix PN = P * N; std::cout << "P * null(P) =\n" << PN << std::endl; TEST_NEAR("P nullspace residual", PN.fro_norm(), 0, 1e-12); - vnl_vector_fixed n = svd.nullvector(); + const vnl_vector_fixed n = svd.nullvector(); TEST_NEAR("P nullvector residual", (P * n).magnitude(), 0, 1e-12); - vnl_vector_fixed l = svd.left_nullvector(); + const vnl_vector_fixed l = svd.left_nullvector(); std::cout << "left_nullvector(P) = " << l << std::endl; TEST_NEAR("P left nullvector residual", (l * P).magnitude(), 0, 1e-12); } @@ -90,17 +90,17 @@ test_I() double Idata[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, }; - vnl_matrix_fixed P(Idata); + const vnl_matrix_fixed P(Idata); vnl_svd_fixed svd(P); std::cout << svd; - vnl_vector_fixed w_expected(1, 1, 1, 0); + const vnl_vector_fixed w_expected(1, 1, 1, 0); TEST_NEAR("Singular values", vnl_vector_ssd(w_expected, svd.W().diagonal().as_ref()), 0, 1e-16); } template void -test_svd_recomposition(char const * type, double maxres, T * /* tag */, vnl_random & rng) +test_svd_recomposition(const char * type, double maxres, T * /* tag */, vnl_random & rng) { // Test inversion of 3x3 matrix of T : std::cout << "----- Testing vnl_svd_fixed<" << type << "> recomposition -----" << std::endl; @@ -109,9 +109,9 @@ test_svd_recomposition(char const * type, double maxres, T * /* tag */, vnl_rand test_util_fill_random(A.begin(), A.end(), rng); std::cout << "A = [\n" << A << "]\n"; - vnl_svd_fixed svd(A); + const vnl_svd_fixed svd(A); - vnl_matrix_fixed B = svd.recompose(); + const vnl_matrix_fixed B = svd.recompose(); std::cout << "B = [\n" << B << "]\n"; const double residual = (A - B).fro_norm(); @@ -128,9 +128,9 @@ test_nullvector(char const * type, double max_err, T *, vnl_random & rng) constexpr int n = 3; vnl_matrix_fixed A; test_util_fill_random(A.begin(), A.end(), rng); - vnl_svd_fixed svd(A); - vnl_vector_fixed x = svd.nullvector(); - vnl_vector_fixed Ax = A * x; + const vnl_svd_fixed svd(A); + const vnl_vector_fixed x = svd.nullvector(); + const vnl_vector_fixed Ax = A * x; vnl_matlab_print(std::cout, A, "A", vnl_matlab_print_format_long); std::cout << "|| x|| = " << x.two_norm() << std::endl << "||Ax|| = " << Ax.two_norm() << std::endl; TEST_NEAR("||Ax||", Ax.two_norm(), 0.0, max_err); @@ -148,7 +148,7 @@ test_speed(vnl_random & rng) for (unsigned count = 0; count < 10000; ++count) { test_util_fill_random(A.begin(), A.end(), rng); - vnl_svd svd(A); + const vnl_svd svd(A); sum += svd.inverse().fro_norm(); } const std::clock_t timer_02 = std::clock(); @@ -163,14 +163,13 @@ test_speed(vnl_random & rng) for (unsigned count = 0; count < 10000; ++count) { test_util_fill_random(A.begin(), A.end(), rng); - vnl_svd_fixed svd(A); + const vnl_svd_fixed svd(A); sum += svd.inverse().fro_norm(); } const std::clock_t timer_04 = std::clock(); ms_stack = ((timer_04 - timer_03) * 1000) / CLOCKS_PER_SEC; std::cout << "vnl_svd_fixed time for 10000 3x3 inversions: " << ms_stack << "ms." << std::endl; } - int ms_nosvd; { double sum = 0; const std::clock_t timer_05 = std::clock(); @@ -181,7 +180,7 @@ test_speed(vnl_random & rng) sum += vnl_inverse(A).fro_norm(); } const std::clock_t timer_06 = std::clock(); - ms_nosvd = ((timer_06 - timer_05) * 1000) / CLOCKS_PER_SEC; + const int ms_nosvd = ((timer_06 - timer_05) * 1000) / CLOCKS_PER_SEC; std::cout << "(c.f. vnl_inverse no-SVD time for 10000 3x3 inversions: " << ms_nosvd << "ms.)" << std::endl; } std::cout << "Stack Memory Time: " << ms_stack << " vs. Heap Memory Time: " << ms_heap << std::endl; diff --git a/core/vnl/algo/tests/test_symmetric_eigensystem.cxx b/core/vnl/algo/tests/test_symmetric_eigensystem.cxx index 0d4c928dcd4..6db08430da0 100644 --- a/core/vnl/algo/tests/test_symmetric_eigensystem.cxx +++ b/core/vnl/algo/tests/test_symmetric_eigensystem.cxx @@ -26,11 +26,11 @@ test_symmetric_eigensystem() 13.9254, -2.4446, 20.2380, 3.6702, -0.2282, 28.6779, 13.7049, 1.3659, 3.6702, 12.5273, -1.6045, 3.9419, -2.4446, 3.6702, -0.2282, -1.6045, 3.9419, 2.5821, 20.2380, -0.2282, 28.6779, 3.9419, 2.5821, 44.0636, }; - vnl_matrix S(Sdata, 6, 6); + const vnl_matrix S(Sdata, 6, 6); { - vnl_symmetric_eigensystem eig(S); - vnl_matrix res = eig.recompose() - S; + const vnl_symmetric_eigensystem eig(S); + const vnl_matrix res = eig.recompose() - S; std::cout << "V'*D*V - S = " << res << std::endl << "residual = " << res.fro_norm() << std::endl; TEST_NEAR("recompose residual", res.fro_norm(), 0.0, 1e-12); @@ -44,11 +44,11 @@ test_symmetric_eigensystem() 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, -1, 0, 0, 0, 0, 2, 0, 0, }; - vnl_matrix C(Cdata, 6, 6); + const vnl_matrix C(Cdata, 6, 6); { - vnl_symmetric_eigensystem eig(C); - vnl_matrix res = eig.recompose() - C; + const vnl_symmetric_eigensystem eig(C); + const vnl_matrix res = eig.recompose() - C; std::cout << "V'*D*V - C = " << res << std::endl << "residual = " << res.fro_norm() << std::endl; TEST_NEAR("recompose residual", res.fro_norm(), 0.0, 1e-12); @@ -61,14 +61,14 @@ test_symmetric_eigensystem() { // Generate a random system vnl_random rng; - int n = 6; - int s = 10; + const int n = 6; + const int s = 10; vnl_matrix D_rand(s, n); for (int i = 0; i < s; ++i) for (int j = 0; j < n; ++j) D_rand(i, j) = 1.0 + 2.0 * rng.normal64(); - vnl_matrix S = D_rand.transpose() * D_rand; + const vnl_matrix S = D_rand.transpose() * D_rand; vnl_matrix evecs(n, n); vnl_vector evals(n); vnl_symmetric_eigensystem_compute(S, evecs, evals); @@ -81,7 +81,9 @@ test_symmetric_eigensystem() } { // test I with specialised 3x3 version - double l1, l2, l3; + double l1; + double l2; + double l3; vnl_symmetric_eigensystem_compute_eigenvals(1.0, 0.0, 0.0, 1.0, 0.0, 1.0, l1, l2, l3); std::cout << "Eigenvals: " << l1 << ' ' << l2 << ' ' << l3 << std::endl; TEST("Correct eigenvalues for I", l1 == 1.0 && l2 == 1.0 && l3 == 1.0, true); @@ -90,57 +92,63 @@ test_symmetric_eigensystem() { // compare speed and values of specialised 3x3 version with nxn version constexpr unsigned n = 20000; + // Generate a random system with seeded value to known value + vnl_random rng(5); double fixed_data[n][3]; unsigned int fixed_time = 0; + + double netlib_data[n][3]; + unsigned int netlib_time = 0; + + unsigned int count_fixed_is_faster = 0; + + // Ensure that the matrix values are the same for both tests + for (int mi = 0; mi < n; ++mi) { - double M11, M12, M13, M22, M23, M33; - // Generate a random system - vnl_random rng(5); - - for (auto & c : fixed_data) - { - M11 = rng.drand64() * 10.0 - 5.0; - M12 = rng.drand64() * 10.0 - 5.0; - M13 = rng.drand64() * 10.0 - 5.0; - M22 = rng.drand64() * 10.0 - 5.0; - M23 = rng.drand64() * 10.0 - 5.0; - M33 = rng.drand64() * 10.0 - 5.0; + vnl_double_3x3 M; + const double M11 = M(0, 0) = rng.drand64() * 10.0 - 5.0; + const double M12 = M(1, 0) = M(0, 1) = rng.drand64() * 10.0 - 5.0; + const double M13 = M(2, 0) = M(0, 2) = rng.drand64() * 10.0 - 5.0; + const double M22 = M(1, 1) = rng.drand64() * 10.0 - 5.0; + const double M23 = M(2, 1) = M(1, 2) = rng.drand64() * 10.0 - 5.0; + const double M33 = M(2, 2) = rng.drand64() * 10.0 - 5.0; + + unsigned int current_iter_fixed_time = 0; + { // Compute time for custom 3D + auto c = fixed_data[mi]; const auto timer_01 = std::chrono::high_resolution_clock::now(); vnl_symmetric_eigensystem_compute_eigenvals(M11, M12, M13, M22, M23, M33, c[0], c[1], c[2]); const auto timer_02 = std::chrono::high_resolution_clock::now(); - fixed_time += (timer_02 - timer_01).count(); + current_iter_fixed_time = (timer_02 - timer_01).count(); + fixed_time += current_iter_fixed_time; } - } - - double netlib_data[n][3]; - unsigned int netlib_time = 0; - { - // Generate same random system - vnl_random rng(5); - vnl_double_3x3 M, evecs; - vnl_double_3 evals; - - for (auto & c : netlib_data) - { - M(0, 0) = rng.drand64() * 10.0 - 5.0; - M(1, 0) = M(0, 1) = rng.drand64() * 10.0 - 5.0; - M(2, 0) = M(0, 2) = rng.drand64() * 10.0 - 5.0; - M(1, 1) = rng.drand64() * 10.0 - 5.0; - M(2, 1) = M(1, 2) = rng.drand64() * 10.0 - 5.0; - M(2, 2) = rng.drand64() * 10.0 - 5.0; - + unsigned int current_iter_netlib_time = 0; + { // Compute time for any size array + vnl_double_3x3 evecs; + vnl_double_3 evals; const auto timer_03 = std::chrono::high_resolution_clock::now(); vnl_symmetric_eigensystem_compute(M.as_ref(), evecs.as_ref().non_const(), evals.as_ref().non_const()); const auto timer_04 = std::chrono::high_resolution_clock::now(); - netlib_time += (timer_04 - timer_03).count(); + current_iter_netlib_time = (timer_04 - timer_03).count(); + netlib_time += current_iter_netlib_time; + auto c = netlib_data[mi]; c[0] = evals[0]; c[1] = evals[1]; c[2] = evals[2]; } + count_fixed_is_faster += (current_iter_fixed_time < current_iter_netlib_time) ? 1 : 0; } - std::cout << "Fixed Time: " << fixed_time << " netlib time: " << netlib_time << std::endl; - TEST("Specialised version is faster", fixed_time < netlib_time, true); + std::cout << "Cummulative fixed Time: " << fixed_time << " cummulative netlib time: " << netlib_time << std::endl; + const auto percent_faster = static_cast(count_fixed_is_faster) * 100.0 / static_cast(n); + std::cout << "Fixed test was faster than netlib test " << percent_faster << "% of the " << n << " tests\n"; + const auto speedup = static_cast(netlib_time) / static_cast(fixed_time); + std::cout << "Speedup for fixed tests was (on average) " << speedup << " times faster than " << " netlib tests\n"; + // Put a guard on the speed tests to make this test more stable. Running this test on as part of continuous + // integration environment indicated that it was not stable. The CI environment is not well controlled, and + // it was possible for the tests to give poor results due to overloaded CI hardware (or virutalized hardware) + // making the process of timing very unstable. This was observed when the CI systems are under heavy load + TEST("Specialised version is faster", fixed_time < netlib_time || percent_faster > 95.0, true); double sum_dsq = 0.0; double max_dsq = 0.0; @@ -155,7 +163,9 @@ test_symmetric_eigensystem() } { - double v1, v2, v3; + double v1; + double v2; + double v3; vnl_symmetric_eigensystem_compute_eigenvals(4199.0, 0.0, 0.0, 4199.0, 0.0, 4801.0, v1, v2, v3); TEST_NEAR("Numerically difficult values are ok v1", v1, 4199, 1e-3); TEST_NEAR("Numerically difficult values are ok v2", v2, 4199, 1e-3); diff --git a/core/vnl/algo/tests/test_util.cxx b/core/vnl/algo/tests/test_util.cxx index 9ae0b6a0ae5..6762e286d94 100644 --- a/core/vnl/algo/tests/test_util.cxx +++ b/core/vnl/algo/tests/test_util.cxx @@ -3,16 +3,16 @@ #include "test_util.h" #include "vnl/vnl_random.h" -#define macro(T) \ - void test_util_fill_random(T * b, T * e, vnl_random & rng) \ - { \ - for (T * p = b; p < e; ++p) \ - *p = (T)rng.drand64(-1.0, +1.0); \ - } \ - void test_util_fill_random(std::complex * b, std::complex * e, vnl_random & rng) \ - { \ - for (std::complex * p = b; p < e; ++p) \ - *p = std::complex((T)rng.drand64(-1.0, +1.0), (T)rng.drand64(-1.0, +1.0)); \ +#define macro(T) \ + void test_util_fill_random(T * b, T * e, vnl_random & rng) \ + { \ + for (T * p = b; p < e; ++p) \ + *p = (T)rng.drand64(-1.0, +1.0); \ + } \ + void test_util_fill_random(std::complex * b, std::complex * e, vnl_random & rng) \ + { \ + for (std::complex * p = b; p < e; ++p) \ + *p = std::complex((T)rng.drand64(-1.0, +1.0), (T)rng.drand64(-1.0, +1.0)); \ } macro(float); diff --git a/core/vnl/algo/tests/test_util.h b/core/vnl/algo/tests/test_util.h index 9af09e1889b..c42fd83d1fd 100644 --- a/core/vnl/algo/tests/test_util.h +++ b/core/vnl/algo/tests/test_util.h @@ -6,7 +6,7 @@ class vnl_random; #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif -#define macro(T) void test_util_fill_random(T *begin, T *end, vnl_random &rng) +#define macro(T) void test_util_fill_random(T * begin, T * end, vnl_random & rng) macro(float); macro(std::complex); macro(double); diff --git a/core/vnl/algo/vnl_adaptsimpson_integral.cxx b/core/vnl/algo/vnl_adaptsimpson_integral.cxx index d15c0ba4e37..5bb027b74db 100644 --- a/core/vnl/algo/vnl_adaptsimpson_integral.cxx +++ b/core/vnl/algo/vnl_adaptsimpson_integral.cxx @@ -2,7 +2,9 @@ #include #include "vnl_adaptsimpson_integral.h" -double vnl_adaptsimpson_integral::int_fnct_(double *x) { +double +vnl_adaptsimpson_integral::int_fnct_(double * x) +{ return pfnct_->f_(*x); } @@ -23,17 +25,14 @@ vnl_adaptsimpson_integral::adaptivesimpson(double (*f)(double *), int level, int level_max) { - double c, d, e, h, result; - double one_simpson, two_simpson; - double left_simpson, right_simpson; - - h = b - a; - c = 0.5 * (a + b); - one_simpson = h * (f(&a) + 4.0 * f(&c) + f(&b)) / 6.0; - d = 0.5 * (a + c); - e = 0.5 * (c + b); - two_simpson = h * (f(&a) + 4.0 * f(&d) + 2.0 * f(&c) + 4.0 * f(&e) + f(&b)) / 12.0; + const double h = b - a; + double c = 0.5 * (a + b); + const double one_simpson = h * (f(&a) + 4.0 * f(&c) + f(&b)) / 6.0; + double d = 0.5 * (a + c); + double e = 0.5 * (c + b); + const double two_simpson = h * (f(&a) + 4.0 * f(&d) + 2.0 * f(&c) + 4.0 * f(&e) + f(&b)) / 12.0; /* Check for level */ + double result; if (level + 1 >= level_max) { result = two_simpson; @@ -47,8 +46,8 @@ vnl_adaptsimpson_integral::adaptivesimpson(double (*f)(double *), /* Divide further */ else { - left_simpson = adaptivesimpson(f, a, c, eps / 2.0, level + 1, level_max); - right_simpson = adaptivesimpson(f, c, b, eps / 2.0, level + 1, level_max); + const double left_simpson = adaptivesimpson(f, a, c, eps / 2.0, level + 1, level_max); + const double right_simpson = adaptivesimpson(f, c, b, eps / 2.0, level + 1, level_max); result = left_simpson + right_simpson; } } diff --git a/core/vnl/algo/vnl_adaptsimpson_integral.h b/core/vnl/algo/vnl_adaptsimpson_integral.h index 139f551db76..0bec1f448c6 100644 --- a/core/vnl/algo/vnl_adaptsimpson_integral.h +++ b/core/vnl/algo/vnl_adaptsimpson_integral.h @@ -10,25 +10,29 @@ class VNL_ALGO_EXPORT vnl_adaptsimpson_integral : public vnl_definite_integral { - private: +private: //: used to wrap the function class to an ordinary function. - static double int_fnct_(double *x); - - protected: + static double + int_fnct_(double * x); +protected: //: maximum recursion depth int depth_; //: real computation - double adaptivesimpson(double(*f)(double*), double a, double b, double eps, int level, int level_max); + double + adaptivesimpson(double (*f)(double *), double a, double b, double eps, int level, int level_max); - public: - vnl_adaptsimpson_integral(int depth = 32) : depth_(depth) {} +public: + vnl_adaptsimpson_integral(int depth = 32) + : depth_(depth) + {} //: a and b are integral limits respectively. // n is the number of intervals used in integral. // accuracy is the accuracy you want to achieve. Normally accuracy > 1e-11) - double integral(vnl_integrant_fnct *f, double a, double b, double accuracy); + double + integral(vnl_integrant_fnct * f, double a, double b, double accuracy); }; #endif diff --git a/core/vnl/algo/vnl_adjugate.h b/core/vnl/algo/vnl_adjugate.h index ec0c085fcac..d96dfa33fc5 100644 --- a/core/vnl/algo/vnl_adjugate.h +++ b/core/vnl/algo/vnl_adjugate.h @@ -19,12 +19,15 @@ #include -template class vnl_matrix; +template +class vnl_matrix; template -void vnl_adjugate(vnl_matrix const &A, vnl_matrix *out); +void +vnl_adjugate(const vnl_matrix & A, vnl_matrix * out); template -vnl_matrix vnl_adjugate(vnl_matrix const &A); +vnl_matrix +vnl_adjugate(const vnl_matrix & A); #endif // vnl_adjugate_h_ diff --git a/core/vnl/algo/vnl_adjugate.hxx b/core/vnl/algo/vnl_adjugate.hxx index 5f4b42e5873..111b575090e 100644 --- a/core/vnl/algo/vnl_adjugate.hxx +++ b/core/vnl/algo/vnl_adjugate.hxx @@ -19,25 +19,27 @@ // and we want to keep T as general as possible. template -void vnl_adjugate(vnl_matrix const &A, vnl_matrix *out) +void +vnl_adjugate(const vnl_matrix & A, vnl_matrix * out) { - int n = A.rows(); + const int n = A.rows(); A.assert_size(n, n); out->assert_size(n, n); - vnl_matrix sub(n-1, n-1); - for (int i=0; i sub(n - 1, n - 1); + for (int i = 0; i < n; ++i) + for (int j = 0; j < n; ++j) { - for (int u=0; u -vnl_matrix vnl_adjugate(vnl_matrix const &A) +vnl_matrix +vnl_adjugate(const vnl_matrix & A) { vnl_matrix adj(A.rows(), A.cols()); vnl_adjugate(A, &adj); @@ -47,8 +49,8 @@ vnl_matrix vnl_adjugate(vnl_matrix const &A) //-------------------------------------------------------------------------------- #undef VNL_ADJUGATE_INSTANTIATE -#define VNL_ADJUGATE_INSTANTIATE(T) \ -template VNL_ALGO_EXPORT void vnl_adjugate(vnl_matrix const &, vnl_matrix *); \ -template VNL_ALGO_EXPORT vnl_matrix vnl_adjugate(vnl_matrix const &) +#define VNL_ADJUGATE_INSTANTIATE(T) \ + template VNL_ALGO_EXPORT void vnl_adjugate(vnl_matrix const &, vnl_matrix *); \ + template VNL_ALGO_EXPORT vnl_matrix vnl_adjugate(vnl_matrix const &) #endif diff --git a/core/vnl/algo/vnl_algo_fwd.h b/core/vnl/algo/vnl_algo_fwd.h index bbed089cff2..22ace9b1dbd 100644 --- a/core/vnl/algo/vnl_algo_fwd.h +++ b/core/vnl/algo/vnl_algo_fwd.h @@ -3,10 +3,14 @@ #define vnl_algo_fwd_h_ -template struct vnl_matrix_inverse; -template class vnl_svd; -template class vnl_qr; -template class vnl_symmetric_eigensystem; +template +struct vnl_matrix_inverse; +template +class vnl_svd; +template +class vnl_qr; +template +class vnl_symmetric_eigensystem; struct vnl_amoeba_SimplexCorner; class vnl_cholesky; class vnl_complex_eigensystem; diff --git a/core/vnl/algo/vnl_amoeba.cxx b/core/vnl/algo/vnl_amoeba.cxx index 05fa2b96b48..b7305ed3170 100644 --- a/core/vnl/algo/vnl_amoeba.cxx +++ b/core/vnl/algo/vnl_amoeba.cxx @@ -19,7 +19,7 @@ bool vnl_amoeba::default_verbose = false; vnl_amoeba::vnl_amoeba(vnl_cost_function & f) : fptr(&f) - , num_evaluations_(0) + { verbose = default_verbose; maxiter = f.get_number_of_unknowns() * 200; @@ -88,7 +88,7 @@ struct vnl_amoebaFit : public vnl_amoeba }; int -vnl_amoeba_SimplexCorner::compare(vnl_amoeba_SimplexCorner const & s1, vnl_amoeba_SimplexCorner const & s2) +vnl_amoeba_SimplexCorner::compare(const vnl_amoeba_SimplexCorner & s1, const vnl_amoeba_SimplexCorner & s2) { return vnl_math::sgn(s1.fv - s2.fv); } @@ -112,7 +112,7 @@ maxabsdiff(const vnl_vector & a, const vnl_vector & b) double v = 0; for (unsigned i = 0; i < a.size(); ++i) { - double ad = vnl_math::abs(a[i] - b[i]); + const double ad = vnl_math::abs(a[i] - b[i]); if (ad > v) v = ad; } @@ -131,7 +131,7 @@ simplex_diameter(const std::vector & simplex) double max = 0; for (unsigned i = 0; i < simplex.size() - 1; i++) { - double thismax = maxabsdiff(simplex[i].v, simplex[i + 1].v); + const double thismax = maxabsdiff(simplex[i].v, simplex[i + 1].v); if (thismax > max) max = thismax; } @@ -165,7 +165,7 @@ operator==(const vnl_amoeba_SimplexCorner & a, const vnl_amoeba_SimplexCorner & void vnl_amoebaFit::set_up_simplex_relative(std::vector & simplex, const vnl_vector & x) { - int n = x.size(); + const int n = x.size(); simplex[0].v = x; simplex[0].fv = f(x); @@ -195,7 +195,7 @@ vnl_amoebaFit::set_up_simplex_absolute(std::vector & s const vnl_vector & x, const vnl_vector & dx) { - int n = x.size(); + const int n = x.size(); simplex[0].v = x; simplex[0].fv = f(x); @@ -242,7 +242,7 @@ void vnl_amoebaFit::amoeba(vnl_vector & x) { // Set up a simplex near the initial guess. - int n = x.size(); + const int n = x.size(); std::vector simplex(n + 1, vnl_amoeba_SimplexCorner(n)); set_up_simplex_relative(simplex, x); @@ -253,7 +253,7 @@ void vnl_amoebaFit::amoeba(vnl_vector & x, const vnl_vector & dx) { // Set up a simplex near the initial guess. - int n = x.size(); + const int n = x.size(); std::vector simplex(n + 1, vnl_amoeba_SimplexCorner(n)); set_up_simplex_absolute(simplex, x, dx); @@ -264,7 +264,7 @@ vnl_amoebaFit::amoeba(vnl_vector & x, const vnl_vector & dx) void vnl_amoebaFit::amoeba(vnl_vector & x, std::vector & simplex) { - int n = x.size(); + const int n = x.size(); sort_simplex(simplex); if (verbose > 1) @@ -281,7 +281,6 @@ vnl_amoebaFit::amoeba(vnl_vector & x, std::vector vbar(n); while (cnt < maxiter) @@ -300,7 +299,7 @@ vnl_amoebaFit::amoeba(vnl_vector & x, std::vector & x, std::vector 1) { - std::streamsize a = std::cerr.width(10); + const std::streamsize a = std::cerr.width(10); std::cerr << '\n' << simplex << '\n'; std::cerr.width(a); } @@ -440,7 +439,7 @@ class vnl_amoeba_LSCF : public vnl_cost_function ~vnl_amoeba_LSCF() override = default; double - f(vnl_vector const & x) override + f(const vnl_vector & x) override { ls_->f(x, fx); return fx.squared_magnitude(); diff --git a/core/vnl/algo/vnl_amoeba.h b/core/vnl/algo/vnl_amoeba.h index c9485f7e3ba..eeffb6cf564 100644 --- a/core/vnl/algo/vnl_amoeba.h +++ b/core/vnl/algo/vnl_amoeba.h @@ -42,70 +42,102 @@ class vnl_least_squares_function; class VNL_ALGO_EXPORT vnl_amoeba { - public: +public: int verbose; int maxiter; double X_tolerance; double F_tolerance; //: Define maximum number of iterations to use - void set_max_iterations(int n) { maxiter = n; } + void + set_max_iterations(int n) + { + maxiter = n; + } //: Define tolerance on elements of x - void set_x_tolerance(double tol) { X_tolerance = tol; } + void + set_x_tolerance(double tol) + { + X_tolerance = tol; + } //: Define tolerance on function evaluation - void set_f_tolerance(double tol) { F_tolerance = tol; } + void + set_f_tolerance(double tol) + { + F_tolerance = tol; + } //: Define scaling used to select starting vertices relative to initial x0. // I.e. the i'th vertex has x[i] = x0[i]*(1+relative_diameter) - void set_relative_diameter(double r) { relative_diameter = r; } - - void set_zero_term_delta(double d) { zero_term_delta = d; } + void + set_relative_diameter(double r) + { + relative_diameter = r; + } + + void + set_zero_term_delta(double d) + { + zero_term_delta = d; + } //: Scaling used to select starting vertices relative to initial x0. // I.e. the i'th vertex has x[i] = x0[i]*(1+relative_diameter) double relative_diameter; double zero_term_delta; //: Construct and supply function to be minimized - vnl_amoeba(vnl_cost_function& f); + vnl_amoeba(vnl_cost_function & f); //: Modify x to minimise function supplied in constructor // Start simplex defined by scaling elements of x - void minimize(vnl_vector& x); + void + minimize(vnl_vector & x); //: Perform optimisation. // Start simplex defined by adding dx[i] to each x[i] - void minimize(vnl_vector& x, const vnl_vector& dx); + void + minimize(vnl_vector & x, const vnl_vector & dx); - double get_end_error() const { return end_error_; } + double + get_end_error() const + { + return end_error_; + } //: Number of evaluations used in last call to minimize - int get_num_evaluations() const { return num_evaluations_; } + int + get_num_evaluations() const + { + return num_evaluations_; + } - public: +public: //: Modify x so as to minimise f(x) - static void minimize(vnl_cost_function& f, vnl_vector& x); + static void + minimize(vnl_cost_function & f, vnl_vector & x); //: Modify x so as to minimise f(x) // Start simplex defined by adding dx[i] to each x[i] - static void minimize(vnl_cost_function& f, vnl_vector& x, - const vnl_vector& dx); + static void + minimize(vnl_cost_function & f, vnl_vector & x, const vnl_vector & dx); //: Modify x so as to minimise f(x) // delta defines relative size of initial simplex // ie the i'th vertex has xi[i] = x[i]*(1+delta) - static void minimize(vnl_cost_function& f, vnl_vector& x, - double delta); + static void + minimize(vnl_cost_function & f, vnl_vector & x, double delta); //: Modify x so as to minimise f(x) - static void minimize(vnl_least_squares_function& f, vnl_vector& x); + static void + minimize(vnl_least_squares_function & f, vnl_vector & x); static bool default_verbose; - protected: - vnl_cost_function* fptr; +protected: + vnl_cost_function * fptr; double end_error_; - int num_evaluations_; + int num_evaluations_{ 0 }; }; // Private struct needs to be declared in the header file @@ -116,9 +148,10 @@ struct vnl_amoeba_SimplexCorner double fv; vnl_amoeba_SimplexCorner(int = 0); - vnl_amoeba_SimplexCorner& operator= (const vnl_amoeba_SimplexCorner& that); - static int compare(vnl_amoeba_SimplexCorner const& s1, - vnl_amoeba_SimplexCorner const& s2); + vnl_amoeba_SimplexCorner & + operator=(const vnl_amoeba_SimplexCorner & that); + static int + compare(const vnl_amoeba_SimplexCorner & s1, const vnl_amoeba_SimplexCorner & s2); }; #endif // vnl_amoeba_h_ diff --git a/core/vnl/algo/vnl_bracket_minimum.cxx b/core/vnl/algo/vnl_bracket_minimum.cxx index 7e5be5e364d..80820b777f5 100644 --- a/core/vnl/algo/vnl_bracket_minimum.cxx +++ b/core/vnl/algo/vnl_bracket_minimum.cxx @@ -16,7 +16,7 @@ static const double EPSqr = 1e-14; inline void swap(double & a, double & b) { - double x = a; + const double x = a; a = b; b = x; } @@ -68,7 +68,8 @@ vnl_bracket_minimum(vnl_cost_function & fn, double & a, double & b, double & c, while (fc < fb) // Keep stepping until we go uphill again { // Use parabolic interpolation to estimate position of centre - double p, q; + double p; + double q; vnl_fit_parabola(a, b, c, fa, fb, fc, p, q); // Ensure q not within EPSqr of zero @@ -81,7 +82,7 @@ vnl_bracket_minimum(vnl_cost_function & fn, double & a, double & b, double & c, // For true quadratic function, minima is at b+p/q double du = p / q; - double tol = EPS * (1.0 + std::max(std::fabs(b), std::fabs(c))); + const double tol = EPS * (1.0 + std::max(std::fabs(b), std::fabs(c))); // Don't evaluate too close to b if (du >= 0 && du < tol) @@ -97,7 +98,7 @@ vnl_bracket_minimum(vnl_cost_function & fn, double & a, double & b, double & c, else if ((c - u) < tol && (c - u) >= 0) u -= tol; // u 0.0) // u in range (b,c), allowing for c bx > cx, f(b) < f(a), f(b) < f(c) for minimum. // Also returns fa = f(a), etc. // // You should probably use vnl_bracket_minimum instead of this function. - void bracket_minimum(double *ax, double *bx, double *cx, - double *fa, double *fb, double *fc); + void + bracket_minimum(double * ax, double * bx, double * cx, double * fa, double * fb, double * fc); //: Given distinct points ax, and bx, find a bracket for the minimum. // Return a bracket ax > bx > cx, f(b) < f(a), f(b) < f(c) for minimum. // // You should probably use vnl_bracket_minimum instead of this function. - void bracket_minimum(double *ax, double *bx, double *cx); + void + bracket_minimum(double * ax, double * bx, double * cx); }; #endif // vnl_brent_h_ diff --git a/core/vnl/algo/vnl_brent_minimizer.cxx b/core/vnl/algo/vnl_brent_minimizer.cxx index a4b082d3a1e..0092f949a3a 100644 --- a/core/vnl/algo/vnl_brent_minimizer.cxx +++ b/core/vnl/algo/vnl_brent_minimizer.cxx @@ -50,7 +50,7 @@ double vnl_brent_minimizer::minimize_given_bounds(double ax, double bx, double cx) { vnl_brent_minimizer_func f(*f_); - double fb = f(bx); + const double fb = f(bx); return minimize_given_bounds_and_one_f(ax, bx, cx, fb); } @@ -81,7 +81,6 @@ vnl_brent_minimizer::minimize_given_bounds_and_one_f(double ax, double bx, doubl double fx = fb; double fw = fx; double fv = fw; - double fu; double m = 0.5 * (ax + cx); // Midpoint of (a,c) double tol = EPS * std::fabs(x) + xtol; // Tolerance to use @@ -94,7 +93,9 @@ vnl_brent_minimizer::minimize_given_bounds_and_one_f(double ax, double bx, doubl while (std::fabs(x - m) > (tol2 - 0.5 * (cx - ax))) { // Variables for parabolic interpolation - double p = 0.0, q = 0.0, r = 0.0; + double p = 0.0; + double q = 0.0; + double r = 0.0; if (std::fabs(e) > tol) { // Fit a parabola @@ -139,7 +140,7 @@ vnl_brent_minimizer::minimize_given_bounds_and_one_f(double ax, double bx, doubl } // Perform the function evaluation - fu = f(u); + const double fu = f(u); // Update our current bounds if (fu <= fx) @@ -207,8 +208,10 @@ vnl_brent_minimizer::minimize_given_bounds_and_all_f(double ax, double bx, doubl double x = bx; // Current best estimate of minimum double fx = fb; - double w, fw; // Next best point - double v, fv; // Third best point + double w; + double fw; // Next best point + double v; + double fv; // Third best point if (fa < fc) { @@ -225,7 +228,8 @@ vnl_brent_minimizer::minimize_given_bounds_and_all_f(double ax, double bx, doubl fv = fa; } - double u, fu; // Most recently evaluated point and its value + double u; + // Most recently evaluated point and its value double m = 0.5 * (ax + cx); // Midpoint of (a,c) double tol = EPS * std::fabs(x) + xtol; // Tolerance to use @@ -238,7 +242,9 @@ vnl_brent_minimizer::minimize_given_bounds_and_all_f(double ax, double bx, doubl while (std::fabs(x - m) > (tol2 - 0.5 * (cx - ax))) { // Variables for parabolic interpolation - double p = 0.0, q = 0.0, r = 0.0; + double p = 0.0; + double q = 0.0; + double r = 0.0; if (std::fabs(e) > tol) { // Fit a parabola @@ -283,7 +289,7 @@ vnl_brent_minimizer::minimize_given_bounds_and_all_f(double ax, double bx, doubl } // Perform the function evaluation - fu = f(u); + const double fu = f(u); // Update our current bounds if (fu <= fx) @@ -334,7 +340,9 @@ vnl_brent_minimizer::minimize(double x) { double ax = x - 1.0; double cx = x + 1.0; - double fa, fx, fc; + double fa; + double fx; + double fc; vnl_bracket_minimum(*f_, ax, x, cx, fa, fx, fc); return minimize_given_bounds_and_all_f(ax, x, cx, fa, fx, fc); diff --git a/core/vnl/algo/vnl_brent_minimizer.h b/core/vnl/algo/vnl_brent_minimizer.h index 33a967df8e9..73f8a9de944 100644 --- a/core/vnl/algo/vnl_brent_minimizer.h +++ b/core/vnl/algo/vnl_brent_minimizer.h @@ -48,28 +48,35 @@ struct vnl_brent_data; // \endverbatim class VNL_ALGO_EXPORT vnl_brent_minimizer : public vnl_nonlinear_minimizer { - protected: - vnl_cost_function* f_; - //: Function evaluation at value returned by minimize(x) +protected: + vnl_cost_function * f_; + //: Function evaluation at value returned by minimize(x) double f_at_last_minimum_; - public: - vnl_brent_minimizer(vnl_cost_function& functor); - ~vnl_brent_minimizer() override; + +public: + vnl_brent_minimizer(vnl_cost_function & functor); + ~vnl_brent_minimizer() override; //: Find a minimum of f(x) near to ax. // The evaluation of f(x) at the returned value can be obtained // by a call to f_at_last_minimum(); - double minimize(double ax); + double + minimize(double ax); - //: Function evaluation at value returned by minimize(x) - double f_at_last_minimum() const { return f_at_last_minimum_; } + //: Function evaluation at value returned by minimize(x) + double + f_at_last_minimum() const + { + return f_at_last_minimum_; + } //: Find the minimum value of f(x) within a<= x <= c. // \retval The position,x, of the minimum x. // You need to provide a bracket for the minimum (af(b) -double vnl_chi_squared_cumulative(T chisq, long dof); +double +vnl_chi_squared_cumulative(T chisq, long dof); //------------------------------------------------------------ @@ -46,22 +47,21 @@ double vnl_chi_squared_cumulative(T chisq, long dof); // template -double vnl_chi_squared_statistic_1 (T const *A, T const *B, - int n, bool normalize); +double +vnl_chi_squared_statistic_1(const T * A, const T * B, int n, bool normalize); //: // $\displaystyle \sum_i \frac{ (a[i] - b[i])^2 }{ b[i] } $ template -double vnl_chi_squared_statistic_2 (T const *A, T const *B, - int n, bool normalize); +double +vnl_chi_squared_statistic_2(const T * A, const T * B, int n, bool normalize); //: // $\displaystyle \sum_i \frac{ (a[i] - b[i])^2 }{ a[i] + b[i] } $ template -double vnl_chi_squared_statistic_12(T const *A, T const *B, - int n, bool normalize); +double +vnl_chi_squared_statistic_12(const T * A, const T * B, int n, bool normalize); -#define VNL_CHI_SQUARED_INSTANTIATE(T) \ -extern "please include vnl/algo/vnl_chi_squared.hxx first" +#define VNL_CHI_SQUARED_INSTANTIATE(T) extern "please include vnl/algo/vnl_chi_squared.hxx first" #endif // vnl_chi_squared_h_ diff --git a/core/vnl/algo/vnl_chi_squared.hxx b/core/vnl/algo/vnl_chi_squared.hxx index 6dc691fcf75..98b5e1c0fda 100644 --- a/core/vnl/algo/vnl_chi_squared.hxx +++ b/core/vnl/algo/vnl_chi_squared.hxx @@ -11,17 +11,20 @@ #include // for dchscdf_() template -double vnl_chi_squared_cumulative(T chisq, long dof) +double +vnl_chi_squared_cumulative(T chisq, long dof) { - double cdf, chisqr = chisq; - v3p_netlib_dchscdf_(&chisqr,&dof,&cdf); + double cdf; + const double chisqr = chisq; + v3p_netlib_dchscdf_(&chisqr, &dof, &cdf); return cdf; } //------------------------------------------------------------ template -double vnl_chi_squared_statistic_1 (T const *A, T const *B, int n, bool normalize) +double +vnl_chi_squared_statistic_1(const T * A, const T * B, int n, bool normalize) { double sum = 0; @@ -29,25 +32,28 @@ double vnl_chi_squared_statistic_1 (T const *A, T const *B, int n, bool normaliz { T sumA = 0; T sumB = 0; - for (int i=0; i -double vnl_chi_squared_statistic_2 (T const *A, T const *B, int n, bool normalize) +double +vnl_chi_squared_statistic_2(const T * A, const T * B, int n, bool normalize) { return vnl_chi_squared_statistic_1(B, A, n, normalize); } template -double vnl_chi_squared_statistic_12(T const *A, T const *B, int n, bool normalize) +double +vnl_chi_squared_statistic_12(const T * A, const T * B, int n, bool normalize) { double sum = 0; @@ -69,25 +77,28 @@ double vnl_chi_squared_statistic_12(T const *A, T const *B, int n, bool normaliz { T sumA = 0; T sumB = 0; - for (int i=0; i const & M, Operation mode) +vnl_cholesky::vnl_cholesky(const vnl_matrix & M, Operation mode) : A_(M) { long n = M.columns(); @@ -55,22 +55,22 @@ vnl_cholesky::vnl_cholesky(vnl_matrix const & M, Operation mode) // The right-hand-side std::vector x may be b, // which will give a fractional increase in speed. void -vnl_cholesky::solve(vnl_vector const & b, vnl_vector * x) const +vnl_cholesky::solve(const vnl_vector & b, vnl_vector * x) const { assert(b.size() == A_.columns()); *x = b; - long n = A_.columns(); + const long n = A_.columns(); v3p_netlib_dposl_(A_.data_block(), &n, &n, x->data_block()); } //: Solve least squares problem M x = b. vnl_vector -vnl_cholesky::solve(vnl_vector const & b) const +vnl_cholesky::solve(const vnl_vector & b) const { assert(b.size() == A_.columns()); - long n = A_.columns(); + const long n = A_.columns(); vnl_vector ret = b; v3p_netlib_dposl_(A_.data_block(), &n, &n, ret.data_block()); return ret; @@ -80,10 +80,10 @@ vnl_cholesky::solve(vnl_vector const & b) const double vnl_cholesky::determinant() const { - long n = A_.columns(); + const long n = A_.columns(); vnl_matrix I = A_; double det[2]; - long job = 10; + const long job = 10; v3p_netlib_dpodi_(I.data_block(), &n, &n, det, &job); return det[0] * std::pow(10.0, det[1]); } @@ -95,12 +95,12 @@ vnl_cholesky::inverse() const if (num_dims_rank_def_) { std::cerr << "vnl_cholesky: Calling inverse() on rank-deficient matrix\n"; - return vnl_matrix(); + return {}; } - long n = A_.columns(); + const long n = A_.columns(); vnl_matrix I = A_; - long job = 01; + const long job = 01; v3p_netlib_dpodi_(I.data_block(), &n, &n, nullptr, &job); // Copy lower triangle into upper @@ -115,7 +115,7 @@ vnl_cholesky::inverse() const vnl_matrix vnl_cholesky::lower_triangle() const { - unsigned n = A_.columns(); + const unsigned n = A_.columns(); vnl_matrix L(n, n); // Zap upper triangle and transpose for (unsigned i = 0; i < n; ++i) @@ -135,7 +135,7 @@ vnl_cholesky::lower_triangle() const vnl_matrix vnl_cholesky::upper_triangle() const { - unsigned n = A_.columns(); + const unsigned n = A_.columns(); vnl_matrix U(n, n); // Zap lower triangle and transpose for (unsigned i = 0; i < n; ++i) diff --git a/core/vnl/algo/vnl_cholesky.h b/core/vnl/algo/vnl_cholesky.h index 6d426920cc9..03844df5221 100644 --- a/core/vnl/algo/vnl_cholesky.h +++ b/core/vnl/algo/vnl_cholesky.h @@ -30,68 +30,96 @@ // it might be a good idea to use vnl_svd instead. class VNL_ALGO_EXPORT vnl_cholesky { - public: +public: //: Modes of computation. See constructor for details. - enum Operation { + enum Operation + { quiet, verbose, estimate_condition }; //: Make cholesky decomposition of M optionally computing the reciprocal condition number. - vnl_cholesky(vnl_matrix const& M, Operation mode = verbose); - ~vnl_cholesky() = default; + vnl_cholesky(const vnl_matrix & M, Operation mode = verbose); + ~vnl_cholesky() = default; //: Solve LS problem M x = b - vnl_vector solve(vnl_vector const& b) const; + vnl_vector + solve(const vnl_vector & b) const; //: Solve LS problem M x = b - void solve(vnl_vector const& b, vnl_vector* x) const; + void + solve(const vnl_vector & b, vnl_vector * x) const; //: Compute determinant - double determinant() const; + double + determinant() const; // Compute inverse. Not efficient. // It's broken, I don't have time to fix it. // Mail awf@robots if you need it and I'll tell you as much as I can // to fix it. - vnl_matrix inverse() const; + vnl_matrix + inverse() const; //: Return lower-triangular factor. - vnl_matrix lower_triangle() const; + vnl_matrix + lower_triangle() const; //: Return upper-triangular factor. - vnl_matrix upper_triangle() const; + vnl_matrix + upper_triangle() const; //: Return the decomposition matrix - vnl_matrix const& L_badly_named_method() const { return A_; } + const vnl_matrix & + L_badly_named_method() const + { + return A_; + } //: A Success/failure flag - int rank_deficiency() const { return num_dims_rank_def_; } + int + rank_deficiency() const + { + return num_dims_rank_def_; + } //: Return reciprocal condition number (smallest/largest singular values). // As long as rcond()>sqrt(precision) the decomposition can be used for // solving equations safely. // Not calculated unless Operation mode at construction was estimate_condition. - double rcond() const { return rcond_; } + double + rcond() const + { + return rcond_; + } //: Return computed nullvector. // Not calculated unless Operation mode at construction was estimate_condition. - vnl_vector & nullvector() { return nullvector_; } - vnl_vector const& nullvector() const { return nullvector_; } - - protected: + vnl_vector & + nullvector() + { + return nullvector_; + } + const vnl_vector & + nullvector() const + { + return nullvector_; + } + +protected: // Data Members-------------------------------------------------------------- vnl_matrix A_; double rcond_; long num_dims_rank_def_; vnl_vector nullvector_; - private: +private: //: Copy constructor - privatised to avoid it being used - vnl_cholesky(vnl_cholesky const & that) = delete; + vnl_cholesky(const vnl_cholesky & that) = delete; //: Assignment operator - privatised to avoid it being used - vnl_cholesky& operator=(vnl_cholesky const & that) = delete; + vnl_cholesky & + operator=(const vnl_cholesky & that) = delete; }; #endif // vnl_cholesky_h_ diff --git a/core/vnl/algo/vnl_complex_eigensystem.cxx b/core/vnl/algo/vnl_complex_eigensystem.cxx index e87e775f3b1..84832073104 100644 --- a/core/vnl/algo/vnl_complex_eigensystem.cxx +++ b/core/vnl/algo/vnl_complex_eigensystem.cxx @@ -9,7 +9,7 @@ #include // zgeev_() void -vnl_complex_eigensystem::compute(vnl_matrix> const & A, bool right, bool left) +vnl_complex_eigensystem::compute(const vnl_matrix> & A, bool right, bool left) { A.assert_size(N, N); @@ -35,11 +35,11 @@ vnl_complex_eigensystem::compute(vnl_matrix> const & A, boo long work_space = 10 * N; vnl_vector> work(work_space); - long rwork_space = 2 * N; + const long rwork_space = 2 * N; vnl_vector rwork(rwork_space); long info; - long tmpN = N; + const long tmpN = N; v3p_netlib_zgeev_(right ? "V" : "N", // jobvl left ? "V" : "N", // jobvr &tmpN, // n @@ -88,7 +88,7 @@ vnl_complex_eigensystem::compute(vnl_matrix> const & A, boo //-------------------------------------------------------------------------------- // -vnl_complex_eigensystem::vnl_complex_eigensystem(vnl_matrix> const & A, bool right, bool left) +vnl_complex_eigensystem::vnl_complex_eigensystem(const vnl_matrix> & A, bool right, bool left) : N(A.rows()) // L and R are intentionally not initialized. , W(N) @@ -97,8 +97,8 @@ vnl_complex_eigensystem::vnl_complex_eigensystem(vnl_matrix } // -vnl_complex_eigensystem::vnl_complex_eigensystem(vnl_matrix const & A_real, - vnl_matrix const & A_imag, +vnl_complex_eigensystem::vnl_complex_eigensystem(const vnl_matrix & A_real, + const vnl_matrix & A_imag, bool right, bool left) : N(A_real.rows()) diff --git a/core/vnl/algo/vnl_complex_eigensystem.h b/core/vnl/algo/vnl_complex_eigensystem.h index 965cdd4a981..8a9832a136f 100644 --- a/core/vnl/algo/vnl_complex_eigensystem.h +++ b/core/vnl/algo/vnl_complex_eigensystem.h @@ -41,30 +41,41 @@ class VNL_ALGO_EXPORT vnl_complex_eigensystem { - public: +public: // please do not add underscores to my members - they are publicly accessible - unsigned int const N; - vnl_matrix > L; // left evecs - vnl_matrix > R; // right evecs - vnl_vector > W; // evals + const unsigned int N; + vnl_matrix> L; // left evecs + vnl_matrix> R; // right evecs + vnl_vector> W; // evals // constructors - vnl_complex_eigensystem(vnl_matrix const& A_real, - vnl_matrix const& A_imag, - bool right=true, bool left=false); + vnl_complex_eigensystem(const vnl_matrix & A_real, + const vnl_matrix & A_imag, + bool right = true, + bool left = false); - vnl_complex_eigensystem(vnl_matrix > const& A, - bool right=true, bool left=false); + vnl_complex_eigensystem(const vnl_matrix> & A, bool right = true, bool left = false); // convenience methods - std::complex eigen_value(unsigned i) const { return W[i]; } - vnl_vector > left_eigen_vector(unsigned i) - const { return L.get_row(i); } - vnl_vector > right_eigen_vector(unsigned i) - const { return R.get_row(i); } + std::complex + eigen_value(unsigned i) const + { + return W[i]; + } + vnl_vector> + left_eigen_vector(unsigned i) const + { + return L.get_row(i); + } + vnl_vector> + right_eigen_vector(unsigned i) const + { + return R.get_row(i); + } - private: - void compute(vnl_matrix > const&,bool,bool); +private: + void + compute(const vnl_matrix> &, bool, bool); }; #endif // vnl_complex_eigensystem_h_ diff --git a/core/vnl/algo/vnl_complex_generalized_schur.h b/core/vnl/algo/vnl_complex_generalized_schur.h index 76bb85af673..237aafe1ee5 100644 --- a/core/vnl/algo/vnl_complex_generalized_schur.h +++ b/core/vnl/algo/vnl_complex_generalized_schur.h @@ -29,47 +29,54 @@ // to complex matrices since they will be overwritten by they (complex) upper // triangular decomposition. template -bool vnl_generalized_schur(vnl_matrix > *A, - vnl_matrix > *B, - vnl_vector > *alpha, - vnl_vector > *beta, - vnl_matrix > *L, - vnl_matrix > *R); +bool +vnl_generalized_schur(vnl_matrix> * A, + vnl_matrix> * B, + vnl_vector> * alpha, + vnl_vector> * beta, + vnl_matrix> * L, + vnl_matrix> * R); template <> -VNL_ALGO_EXPORT bool vnl_generalized_schur(vnl_matrix > *A, - vnl_matrix > *B, - vnl_vector > *alpha, - vnl_vector > *beta, - vnl_matrix > *L, - vnl_matrix > *R); +VNL_ALGO_EXPORT bool +vnl_generalized_schur(vnl_matrix> * A, + vnl_matrix> * B, + vnl_vector> * alpha, + vnl_vector> * beta, + vnl_matrix> * L, + vnl_matrix> * R); #ifdef _MSC_VER # include #endif template -std::complex vnl_complex_generalized_schur_convert_cast(std::complex a) { return static_cast >(a); } +std::complex +vnl_complex_generalized_schur_convert_cast(std::complex a) +{ + return static_cast>(a); +} template -inline bool vnl_generalized_schur(vnl_matrix > *A, - vnl_matrix > *B, - vnl_vector > *alpha, - vnl_vector > *beta, - vnl_matrix > *L, - vnl_matrix > *R) +inline bool +vnl_generalized_schur(vnl_matrix> * A, + vnl_matrix> * B, + vnl_vector> * alpha, + vnl_vector> * beta, + vnl_matrix> * L, + vnl_matrix> * R) { - vnl_matrix > A_(A->rows(), A->cols()); - vnl_matrix > B_(B->rows(), B->cols()); + vnl_matrix> A_(A->rows(), A->cols()); + vnl_matrix> B_(B->rows(), B->cols()); std::copy(A->begin(), A->end(), A_.begin()); std::copy(B->begin(), B->end(), B_.begin()); - vnl_vector > alpha_; - vnl_vector > beta_; - vnl_matrix > L_; - vnl_matrix > R_; + vnl_vector> alpha_; + vnl_vector> beta_; + vnl_matrix> L_; + vnl_matrix> R_; - if (! vnl_generalized_schur/* >*/(&A_, &B_, &alpha_, &beta_, &L_, &R_)) + if (!vnl_generalized_schur /* >*/ (&A_, &B_, &alpha_, &beta_, &L_, &R_)) return false; std::transform(A_.begin(), A_.end(), A->begin(), vnl_complex_generalized_schur_convert_cast); diff --git a/core/vnl/algo/vnl_conjugate_gradient.cxx b/core/vnl/algo/vnl_conjugate_gradient.cxx index 69ce27541e4..bfa38a9fabf 100644 --- a/core/vnl/algo/vnl_conjugate_gradient.cxx +++ b/core/vnl/algo/vnl_conjugate_gradient.cxx @@ -33,7 +33,7 @@ vnl_conjugate_gradient::valuecomputer_(double * x, void * userdata) { auto * self = static_cast(userdata); vnl_cost_function * f = self->f_; - vnl_vector_ref ref_x(f->get_number_of_unknowns(), x); + const vnl_vector_ref ref_x(f->get_number_of_unknowns(), x); self->num_evaluations_++; @@ -45,7 +45,7 @@ vnl_conjugate_gradient::gradientcomputer_(double * g, double * x, void * userdat { auto * self = static_cast(userdata); vnl_cost_function * f = self->f_; - vnl_vector_ref ref_x(f->get_number_of_unknowns(), x); + const vnl_vector_ref ref_x(f->get_number_of_unknowns(), x); vnl_vector_ref ref_g(f->get_number_of_unknowns(), g); f->gradf(ref_x, ref_g); @@ -56,7 +56,7 @@ vnl_conjugate_gradient::valueandgradientcomputer_(double * v, double * g, double { auto * self = static_cast(userdata); vnl_cost_function * f = self->f_; - vnl_vector_ref ref_x(f->get_number_of_unknowns(), x); + const vnl_vector_ref ref_x(f->get_number_of_unknowns(), x); vnl_vector_ref ref_g(f->get_number_of_unknowns(), g); f->compute(ref_x, v, &ref_g); @@ -71,7 +71,7 @@ vnl_conjugate_gradient::preconditioner_(double * out, double * in, void * userda auto * self = static_cast(userdata); vnl_cost_function * f = self->f_; - int n = f->get_number_of_unknowns(); + const int n = f->get_number_of_unknowns(); for (int i = 0; i < n; ++i) out[i] = in[i]; } @@ -84,7 +84,7 @@ vnl_conjugate_gradient::minimize(vnl_vector & x) double max_norm_of_gradient; long number_of_iterations; final_step_size_ = 0; - double gradient_tolerance = gtol; + const double gradient_tolerance = gtol; vnl_vector workspace(f_->get_number_of_unknowns() * 3); long number_of_unknowns = f_->get_number_of_unknowns(); long error_code; diff --git a/core/vnl/algo/vnl_conjugate_gradient.h b/core/vnl/algo/vnl_conjugate_gradient.h index bcaaca8c2f4..dd454f0c87f 100644 --- a/core/vnl/algo/vnl_conjugate_gradient.h +++ b/core/vnl/algo/vnl_conjugate_gradient.h @@ -31,27 +31,30 @@ class vnl_cost_function; class VNL_ALGO_EXPORT vnl_conjugate_gradient : public vnl_nonlinear_minimizer { - public: +public: // Constructors/Destructors-------------------------------------------------- //: Initialize with the function object that is to be minimized. - vnl_conjugate_gradient(vnl_cost_function& f) { init( f); } + vnl_conjugate_gradient(vnl_cost_function & f) { init(f); } //: Initialize as above, and then run minimization. - vnl_conjugate_gradient(vnl_cost_function& f, vnl_vector& x) { + vnl_conjugate_gradient(vnl_cost_function & f, vnl_vector & x) + { init(f); minimize(x); } //: Initialize all variables - void init(vnl_cost_function &f); + void + init(vnl_cost_function & f); //: Destructor. ~vnl_conjugate_gradient() override; // Operations---------------------------------------------------------------- - void diagnose_outcome(std::ostream&) const; + void + diagnose_outcome(std::ostream &) const; void diagnose_outcome(/*std::ostream& = std::cout*/) const; // Computations-------------------------------------------------------------- @@ -59,21 +62,25 @@ class VNL_ALGO_EXPORT vnl_conjugate_gradient : public vnl_nonlinear_minimizer //: Minimize the function supplied in the constructor until convergence or failure. // On return, x is such that f(x) is the lowest value achieved. // Returns true for convergence, false for failure. - bool minimize(vnl_vector& x); + bool + minimize(vnl_vector & x); - protected: +protected: // Data Members-------------------------------------------------------------- - vnl_cost_function *f_; + vnl_cost_function * f_; double final_step_size_; // Helpers------------------------------------------------------------------- - static double valuecomputer_( double *x, void* userdata); - static void gradientcomputer_( double *g, double *x, void* userdata); - static void valueandgradientcomputer_( double *v, double *g, double *x, void* userdata); - static void preconditioner_( double *out, double *in, void* userdata); - + static double + valuecomputer_(double * x, void * userdata); + static void + gradientcomputer_(double * g, double * x, void * userdata); + static void + valueandgradientcomputer_(double * v, double * g, double * x, void * userdata); + static void + preconditioner_(double * out, double * in, void * userdata); }; #endif // vnl_conjugate_gradient_h_ diff --git a/core/vnl/algo/vnl_convolve.h b/core/vnl/algo/vnl_convolve.h index 8a34fff4b06..8c30147dbf3 100644 --- a/core/vnl/algo/vnl_convolve.h +++ b/core/vnl/algo/vnl_convolve.h @@ -36,10 +36,8 @@ // then vnl_convolve_cyclic() is applied. // template -VNL_EXPORT -vnl_vector -vnl_convolve(vnl_vector const& v1, vnl_vector const& v2, - U*, int use_fft = 0); +VNL_EXPORT vnl_vector +vnl_convolve(const vnl_vector & v1, const vnl_vector & v2, U *, int use_fft = 0); //: Convolve two vnl_vector's, with the same base type T. @@ -49,10 +47,8 @@ vnl_convolve(vnl_vector const& v1, vnl_vector const& v2, // // \relatesalso vnl_vector template -VNL_EXPORT -vnl_vector -vnl_convolve(vnl_vector const& v1, vnl_vector const& v2, - int use_fft = 0); +VNL_EXPORT vnl_vector +vnl_convolve(const vnl_vector & v1, const vnl_vector & v2, int use_fft = 0); //: Cyclically convolve two vnl_vector's of the same length. @@ -74,42 +70,34 @@ vnl_convolve(vnl_vector const& v1, vnl_vector const& v2, // \relatesalso vnl_vector template -VNL_EXPORT -vnl_vector -vnl_convolve_cyclic(vnl_vector const& v1, vnl_vector const& v2, - U*, bool use_fft = false); +VNL_EXPORT vnl_vector +vnl_convolve_cyclic(const vnl_vector & v1, const vnl_vector & v2, U *, bool use_fft = false); // Not yet implemented template vnl_matrix -vnl_convolve(vnl_matrix const& v1, vnl_matrix const& v2, - U*, int use_fft = 0); +vnl_convolve(const vnl_matrix & v1, const vnl_matrix & v2, U *, int use_fft = 0); // Not yet implemented template vnl_matrix -vnl_convolve(vnl_matrix const& v1, vnl_matrix const& v2, - int use_fft = 0); +vnl_convolve(const vnl_matrix & v1, const vnl_matrix & v2, int use_fft = 0); // Not yet implemented template vnl_matrix -vnl_convolve_cyclic(vnl_matrix const& v1, vnl_matrix const& v2, - U*, bool use_fft = false); +vnl_convolve_cyclic(const vnl_matrix & v1, const vnl_matrix & v2, U *, bool use_fft = false); // Not yet implemented template vnl_matrix -vnl_convolve(vnl_matrix const& v1, vnl_vector const& v2, - U*, int use_fft = 0); +vnl_convolve(const vnl_matrix & v1, const vnl_vector & v2, U *, int use_fft = 0); // Not yet implemented template vnl_matrix -vnl_convolve(vnl_matrix const& v1, vnl_vector const& v2, - int use_fft = 0); +vnl_convolve(const vnl_matrix & v1, const vnl_vector & v2, int use_fft = 0); -#define VNL_CONVOLVE_INSTANTIATE(T) \ -extern "please include vnl/algo/vnl_convolve.hxx first" +#define VNL_CONVOLVE_INSTANTIATE(T) extern "please include vnl/algo/vnl_convolve.hxx first" #endif // vnl_convolve_h_ diff --git a/core/vnl/algo/vnl_convolve.hxx b/core/vnl/algo/vnl_convolve.hxx index 5c00fd0f15b..514217bf1d4 100644 --- a/core/vnl/algo/vnl_convolve.hxx +++ b/core/vnl/algo/vnl_convolve.hxx @@ -11,138 +11,163 @@ #endif template -inline -vnl_vector vnl_convolve_cyclic_using_fft(vnl_vector const& v1, vnl_vector const& v2, U*) +inline vnl_vector +vnl_convolve_cyclic_using_fft(const vnl_vector & v1, const vnl_vector & v2, U *) { - assert (v1.size() == v2.size()); - unsigned int n = v1.size(); + assert(v1.size() == v2.size()); + const unsigned int n = v1.size(); typedef std::complex C; - vnl_vector w1(n, C(0)); for (unsigned i=0; i w2(n, C(0)); for (unsigned i=0; i fft(n); fft.fwd_transform(w1); fft.fwd_transform(w2); - for (unsigned int i=0; i w1(n, C(0)); + for (unsigned i = 0; i < n; ++i) + w1[i] = v1[i]; + vnl_vector w2(n, C(0)); + for (unsigned i = 0; i < n; ++i) + w2[i] = v2[i]; + + vnl_fft_1d fft(n); + fft.fwd_transform(w1); + fft.fwd_transform(w2); + for (unsigned int i = 0; i < n; ++i) + w1[i] *= w2[i]; fft.bwd_transform(w1); #ifdef DEBUG std::cout << w1 << std::endl; #endif vnl_vector r(n); - for (unsigned int i = 0; i -vnl_vector vnl_convolve_cyclic(vnl_vector const& v1, vnl_vector const& v2, U*, bool use_fft) +vnl_vector +vnl_convolve_cyclic(const vnl_vector & v1, const vnl_vector & v2, U *, bool use_fft) { - assert (v1.size() == v2.size()); - unsigned int n = v1.size(); + assert(v1.size() == v2.size()); + const unsigned int n = v1.size(); // Quick return if possible: - if (n == 0) return vnl_vector(0, U(0)); - if (n == 1) return vnl_vector(1, U(v1[0]*v2[0])); + if (n == 0) + return vnl_vector(0, U(0)); + if (n == 1) + return vnl_vector(1, U(v1[0] * v2[0])); if (use_fft) - return vnl_convolve_cyclic_using_fft(v1, v2, (U*)nullptr); + return vnl_convolve_cyclic_using_fft(v1, v2, (U *)nullptr); vnl_vector ret(n, (U)0); // all elements already initialized to zero - for (unsigned int k=0; k -inline -vnl_vector vnl_convolve_using_fft(vnl_vector const& v1, vnl_vector const& v2, U*, int n) +inline vnl_vector +vnl_convolve_using_fft(const vnl_vector & v1, const vnl_vector & v2, U *, int n) { - if (n+1 < int(v1.size() + v2.size())) n = v1.size() + v2.size() - 1; + if (n + 1 < int(v1.size() + v2.size())) + n = v1.size() + v2.size() - 1; // Make sure n has only prime factors 2, 3 and 5; if necessary, increase n. - while (!has_only_primefactors_2_3_5(n)) ++n; + while (!has_only_primefactors_2_3_5(n)) + ++n; // pad with zeros, so the cyclic convolution is a convolution: - vnl_vector w1(n, U(0)); for (unsigned i=0; i w2(n, U(0)); for (unsigned i=0; i w1(n, U(0)); + for (unsigned i = 0; i < v1.size(); ++i) + w1[i] = U(v1[i]); + vnl_vector w2(n, U(0)); + for (unsigned i = 0; i < v2.size(); ++i) + w2[i] = U(v2[i]); // convolve, using n-points FFT: - w1 = vnl_convolve_cyclic_using_fft(w1, w2, (U*)nullptr); + w1 = vnl_convolve_cyclic_using_fft(w1, w2, (U *)nullptr); // return w1, but possibly drop the last few (zero) entries: - return vnl_vector(v1.size()+v2.size()-1, v1.size()+v2.size()-1, w1.data_block()); + return vnl_vector(v1.size() + v2.size() - 1, v1.size() + v2.size() - 1, w1.data_block()); } template -vnl_vector vnl_convolve(vnl_vector const& v1, vnl_vector const& v2, int use_fft) +vnl_vector +vnl_convolve(const vnl_vector & v1, const vnl_vector & v2, int use_fft) { // Quick return if possible: - if (v1.size() == 0 || v2.size() == 0) + if (v1.empty() || v2.empty()) return vnl_vector(0); - if (v1.size() == 1) return v2*v1[0]; - if (v2.size() == 1) return v1*v2[0]; + if (v1.size() == 1) + return v2 * v1[0]; + if (v2.size() == 1) + return v1 * v2[0]; if (use_fft != 0) - return vnl_convolve_using_fft(v1, v2, (T*)nullptr, use_fft); + return vnl_convolve_using_fft(v1, v2, (T *)nullptr, use_fft); - unsigned int n = v1.size() + v2.size() - 1; + const unsigned int n = v1.size() + v2.size() - 1; vnl_vector ret(n, (T)0); // all elements already initialized to zero - for (unsigned int k=0; k -vnl_vector vnl_convolve(vnl_vector const& v1, vnl_vector const& v2, U*, int use_fft) +vnl_vector +vnl_convolve(const vnl_vector & v1, const vnl_vector & v2, U *, int use_fft) { // Quick return if possible: - if (v1.size() == 0 || v2.size() == 0) + if (v1.empty() || v2.empty()) return vnl_vector(0); if (use_fft != 0) - return vnl_convolve_using_fft(v1, v2, (U*)nullptr, use_fft); + return vnl_convolve_using_fft(v1, v2, (U *)nullptr, use_fft); - unsigned int n = v1.size() + v2.size() - 1; + const unsigned int n = v1.size() + v2.size() - 1; vnl_vector ret(n, (U)0); // all elements already initialized to zero - for (unsigned int k=0; k vnl_convolve(vnl_vector const&, vnl_vector const&, U*, int); \ -template vnl_vector vnl_convolve_cyclic(vnl_vector const&, vnl_vector const&, U*, bool) +#define VNL_CONVOLVE_INSTANTIATE_2(T, U) \ + template vnl_vector vnl_convolve(vnl_vector const &, vnl_vector const &, U *, int); \ + template vnl_vector vnl_convolve_cyclic(vnl_vector const &, vnl_vector const &, U *, bool) -#define VNL_CONVOLVE_INSTANTIATE(T,U) \ -VNL_CONVOLVE_INSTANTIATE_2(T,U); \ -template vnl_vector vnl_convolve(vnl_vector const&, vnl_vector const&, int) +#define VNL_CONVOLVE_INSTANTIATE(T, U) \ + VNL_CONVOLVE_INSTANTIATE_2(T, U); \ + template vnl_vector vnl_convolve(vnl_vector const &, vnl_vector const &, int) #endif // vnl_convolve_hxx_ diff --git a/core/vnl/algo/vnl_cpoly_roots.cxx b/core/vnl/algo/vnl_cpoly_roots.cxx index 78acb62e81b..ce6c001acd3 100644 --- a/core/vnl/algo/vnl_cpoly_roots.cxx +++ b/core/vnl/algo/vnl_cpoly_roots.cxx @@ -6,7 +6,7 @@ #include void -vnl_cpoly_roots::compute(vnl_vector> const & a) +vnl_cpoly_roots::compute(const vnl_vector> & a) { // construct companion matrix vnl_matrix> comp(N, N); @@ -26,14 +26,14 @@ vnl_cpoly_roots::compute(vnl_vector> const & a) #endif } -vnl_cpoly_roots::vnl_cpoly_roots(vnl_vector> const & a) +vnl_cpoly_roots::vnl_cpoly_roots(const vnl_vector> & a) : solns(a.size()) , N(a.size()) // degree { compute(a); } -vnl_cpoly_roots::vnl_cpoly_roots(vnl_vector const & a_real, vnl_vector const & a_imag) +vnl_cpoly_roots::vnl_cpoly_roots(const vnl_vector & a_real, const vnl_vector & a_imag) : solns(a_real.size()) , N(a_real.size()) // degree { diff --git a/core/vnl/algo/vnl_cpoly_roots.h b/core/vnl/algo/vnl_cpoly_roots.h index ab4df344ab7..fcca0dc39c1 100644 --- a/core/vnl/algo/vnl_cpoly_roots.h +++ b/core/vnl/algo/vnl_cpoly_roots.h @@ -30,17 +30,17 @@ class VNL_ALGO_EXPORT vnl_cpoly_roots { public: - vnl_cpoly_roots(vnl_vector > const & a); - vnl_cpoly_roots(vnl_vector const & a_real, - vnl_vector const & a_imag); + vnl_cpoly_roots(const vnl_vector> & a); + vnl_cpoly_roots(const vnl_vector & a_real, const vnl_vector & a_imag); // the roots can be found in here : - vnl_vector > solns; + vnl_vector> solns; private: - unsigned N; //degree + unsigned N; // degree //: does the actual work - void compute(vnl_vector > const & a); + void + compute(const vnl_vector> & a); }; #endif // vnl_cpoly_roots_h_ diff --git a/core/vnl/algo/vnl_determinant.cxx b/core/vnl/algo/vnl_determinant.cxx index a8fafb3b2f8..d3454dd8fb6 100644 --- a/core/vnl/algo/vnl_determinant.cxx +++ b/core/vnl/algo/vnl_determinant.cxx @@ -2,9 +2,9 @@ #include "vnl_determinant.h" int -vnl_determinant(vnl_matrix const & M, bool balance) +vnl_determinant(const vnl_matrix & M, bool balance) { - unsigned n = M.rows(); + const unsigned n = M.rows(); assert(M.cols() == n); switch (n) diff --git a/core/vnl/algo/vnl_determinant.h b/core/vnl/algo/vnl_determinant.h index cefea111a64..c1e6d0ff508 100644 --- a/core/vnl/algo/vnl_determinant.h +++ b/core/vnl/algo/vnl_determinant.h @@ -23,42 +23,44 @@ #include //: direct evaluation for 2x2 matrix -template T vnl_determinant(T const *row0, - T const *row1); +template +T +vnl_determinant(const T * row0, const T * row1); //: direct evaluation for 3x3 matrix -template T vnl_determinant(T const *row0, - T const *row1, - T const *row2); +template +T +vnl_determinant(const T * row0, const T * row1, const T * row2); //: direct evaluation for 4x4 matrix -template T vnl_determinant(T const *row0, - T const *row1, - T const *row2, - T const *row3); +template +T +vnl_determinant(const T * row0, const T * row1, const T * row2, const T * row3); // overload for int. Cannot specialize the template because gcc // 2.95.4 can't handle the default value. This overload must appear // before the template declaration because VC.net 7.0 gets confused // otherwise. -int VNL_ALGO_EXPORT vnl_determinant(vnl_matrix const &M, bool balance = false); +int VNL_ALGO_EXPORT +vnl_determinant(const vnl_matrix & M, bool balance = false); //: evaluation using direct methods for sizes of 2x2, 3x3, and 4x4 or qr decomposition for other matrices. // \relatesalso vnl_matrix template -T vnl_determinant(vnl_matrix const &M, bool balance = false); +T +vnl_determinant(const vnl_matrix & M, bool balance = false); //: evaluation using direct methods for sizes of 2x2, 3x3, and 4x4 or qr decomposition for other matrices. // convenience overload from vnl_matrix variant // \relatesalso vnl_matrix_fixed template -inline T vnl_determinant(vnl_matrix_fixed const &M, bool balance = false) +inline T +vnl_determinant(const vnl_matrix_fixed & M, bool balance = false) { - return vnl_determinant( M.as_ref(), balance ); + return vnl_determinant(M.as_ref(), balance); } -#define VNL_DETERMINANT_INSTANTIATE(T) \ -extern "you must include vnl/algo/vnl_determinant.hxx first" +#define VNL_DETERMINANT_INSTANTIATE(T) extern "you must include vnl/algo/vnl_determinant.hxx first" #endif // vnl_algo_determinant_h_ diff --git a/core/vnl/algo/vnl_determinant.hxx b/core/vnl/algo/vnl_determinant.hxx index f40de6e7071..14abde4413e 100644 --- a/core/vnl/algo/vnl_determinant.hxx +++ b/core/vnl/algo/vnl_determinant.hxx @@ -13,115 +13,109 @@ template -T vnl_determinant(T const *row0, T const *row1) +T +vnl_determinant(const T * row0, const T * row1) { - return row0[0]*row1[1] - row0[1]*row1[0]; + return row0[0] * row1[1] - row0[1] * row1[0]; } template -T vnl_determinant(T const *row0, T const *row1, T const *row2) +T +vnl_determinant(const T * row0, const T * row1, const T * row2) { return // the extra '+' makes it work nicely with emacs indentation. - + row0[0]*row1[1]*row2[2] - - row0[0]*row2[1]*row1[2] - - row1[0]*row0[1]*row2[2] - + row1[0]*row2[1]*row0[2] - + row2[0]*row0[1]*row1[2] - - row2[0]*row1[1]*row0[2]; + +row0[0] * row1[1] * row2[2] - row0[0] * row2[1] * row1[2] - row1[0] * row0[1] * row2[2] + + row1[0] * row2[1] * row0[2] + row2[0] * row0[1] * row1[2] - row2[0] * row1[1] * row0[2]; } template -T vnl_determinant(T const *row0, T const *row1, T const *row2, T const *row3) +T +vnl_determinant(const T * row0, const T * row1, const T * row2, const T * row3) { - return - + row0[0]*row1[1]*row2[2]*row3[3] - - row0[0]*row1[1]*row3[2]*row2[3] - - row0[0]*row2[1]*row1[2]*row3[3] - + row0[0]*row2[1]*row3[2]*row1[3] - + row0[0]*row3[1]*row1[2]*row2[3] - - row0[0]*row3[1]*row2[2]*row1[3] - - row1[0]*row0[1]*row2[2]*row3[3] - + row1[0]*row0[1]*row3[2]*row2[3] - + row1[0]*row2[1]*row0[2]*row3[3] - - row1[0]*row2[1]*row3[2]*row0[3] - - row1[0]*row3[1]*row0[2]*row2[3] - + row1[0]*row3[1]*row2[2]*row0[3] - + row2[0]*row0[1]*row1[2]*row3[3] - - row2[0]*row0[1]*row3[2]*row1[3] - - row2[0]*row1[1]*row0[2]*row3[3] - + row2[0]*row1[1]*row3[2]*row0[3] - + row2[0]*row3[1]*row0[2]*row1[3] - - row2[0]*row3[1]*row1[2]*row0[3] - - row3[0]*row0[1]*row1[2]*row2[3] - + row3[0]*row0[1]*row2[2]*row1[3] - + row3[0]*row1[1]*row0[2]*row2[3] - - row3[0]*row1[1]*row2[2]*row0[3] - - row3[0]*row2[1]*row0[2]*row1[3] - + row3[0]*row2[1]*row1[2]*row0[3]; + return +row0[0] * row1[1] * row2[2] * row3[3] - row0[0] * row1[1] * row3[2] * row2[3] - + row0[0] * row2[1] * row1[2] * row3[3] + row0[0] * row2[1] * row3[2] * row1[3] + + row0[0] * row3[1] * row1[2] * row2[3] - row0[0] * row3[1] * row2[2] * row1[3] - + row1[0] * row0[1] * row2[2] * row3[3] + row1[0] * row0[1] * row3[2] * row2[3] + + row1[0] * row2[1] * row0[2] * row3[3] - row1[0] * row2[1] * row3[2] * row0[3] - + row1[0] * row3[1] * row0[2] * row2[3] + row1[0] * row3[1] * row2[2] * row0[3] + + row2[0] * row0[1] * row1[2] * row3[3] - row2[0] * row0[1] * row3[2] * row1[3] - + row2[0] * row1[1] * row0[2] * row3[3] + row2[0] * row1[1] * row3[2] * row0[3] + + row2[0] * row3[1] * row0[2] * row1[3] - row2[0] * row3[1] * row1[2] * row0[3] - + row3[0] * row0[1] * row1[2] * row2[3] + row3[0] * row0[1] * row2[2] * row1[3] + + row3[0] * row1[1] * row0[2] * row2[3] - row3[0] * row1[1] * row2[2] * row0[3] - + row3[0] * row2[1] * row0[2] * row1[3] + row3[0] * row2[1] * row1[2] * row0[3]; } //-------------------------------------------------------------------------------- template -T vnl_determinant(vnl_matrix const &M, bool balance) +T +vnl_determinant(const vnl_matrix & M, bool balance) { - unsigned n = M.rows(); + const unsigned n = M.rows(); assert(M.cols() == n); switch (n) { - case 1: return M[0][0]; - case 2: return vnl_determinant(M[0], M[1]); - case 3: return vnl_determinant(M[0], M[1], M[2]); - case 4: return vnl_determinant(M[0], M[1], M[2], M[3]); - default: - if (balance) - { - vnl_matrix tmp(M); - typedef typename vnl_numeric_traits::abs_t abs_t; - abs_t scalings(1); - for (int t=0; t<5; ++t) + case 1: + return M[0][0]; + case 2: + return vnl_determinant(M[0], M[1]); + case 3: + return vnl_determinant(M[0], M[1], M[2]); + case 4: + return vnl_determinant(M[0], M[1], M[2], M[3]); + default: + if (balance) { - // normalize rows. - for (unsigned int i=0; i 0) { - scalings *= rn; - tmp.scale_row(i, abs_t(1)/rn); + vnl_matrix tmp(M); + typedef typename vnl_numeric_traits::abs_t abs_t; + abs_t scalings(1); + for (int t = 0; t < 5; ++t) + { + // normalize rows. + for (unsigned int i = 0; i < n; ++i) + { + const abs_t rn = tmp.get_row(i).rms(); + if (rn > 0) + { + scalings *= rn; + tmp.scale_row(i, abs_t(1) / rn); + } } - } - // normalize columns. - for (unsigned int i=0; i 0) { - scalings *= rn; - tmp.scale_column(i, abs_t(1)/rn); + // normalize columns. + for (unsigned int i = 0; i < n; ++i) + { + const abs_t rn = tmp.get_column(i).rms(); + if (rn > 0) + { + scalings *= rn; + tmp.scale_column(i, abs_t(1) / rn); + } } } + T balanced_det = vnl_qr(tmp).determinant(); + // std::clog << __FILE__ ": scalings, balanced_det = " << scalings << ", " << balanced_det << std::endl; + return T(scalings) * balanced_det; } - T balanced_det = vnl_qr(tmp).determinant(); - //std::clog << __FILE__ ": scalings, balanced_det = " << scalings << ", " << balanced_det << std::endl; - return T(scalings) * balanced_det; - } - else - return vnl_qr(M).determinant(); + else + return vnl_qr(M).determinant(); } } //-------------------------------------------------------------------------------- -#define VNL_DETERMINANT_INSTANTIATE_1(T) \ -template VNL_ALGO_EXPORT T vnl_determinant(T const *, T const *); \ -template VNL_ALGO_EXPORT T vnl_determinant(T const *, T const *, T const *); \ -template VNL_ALGO_EXPORT T vnl_determinant(T const *, T const *, T const *, T const *) +#define VNL_DETERMINANT_INSTANTIATE_1(T) \ + template VNL_ALGO_EXPORT T vnl_determinant(T const *, T const *); \ + template VNL_ALGO_EXPORT T vnl_determinant(T const *, T const *, T const *); \ + template VNL_ALGO_EXPORT T vnl_determinant(T const *, T const *, T const *, T const *) -#define VNL_DETERMINANT_INSTANTIATE_2(T) \ -template VNL_ALGO_EXPORT T vnl_determinant(vnl_matrix const &, bool) +#define VNL_DETERMINANT_INSTANTIATE_2(T) template VNL_ALGO_EXPORT T vnl_determinant(vnl_matrix const &, bool) #undef VNL_DETERMINANT_INSTANTIATE #define VNL_DETERMINANT_INSTANTIATE(T) \ -VNL_DETERMINANT_INSTANTIATE_1(T); \ -VNL_DETERMINANT_INSTANTIATE_2(T) + VNL_DETERMINANT_INSTANTIATE_1(T); \ + VNL_DETERMINANT_INSTANTIATE_2(T) #endif // vnl_algo_determinant_hxx_ diff --git a/core/vnl/algo/vnl_discrete_diff.cxx b/core/vnl/algo/vnl_discrete_diff.cxx index ab52d9f9aae..cc4df9cd659 100644 --- a/core/vnl/algo/vnl_discrete_diff.cxx +++ b/core/vnl/algo/vnl_discrete_diff.cxx @@ -8,7 +8,7 @@ */ bool -vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, double h_, vnl_vector const & x, vnl_matrix & J) +vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, double h_, const vnl_vector & x, vnl_matrix & J) { vnl_vector y(lsf->get_number_of_residuals()); lsf->f(x, y); @@ -21,8 +21,8 @@ vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, double h_, vnl_vector const & h, - vnl_vector const & x, + const vnl_vector & h, + const vnl_vector & x, vnl_matrix & J) { vnl_vector y(lsf->get_number_of_residuals()); @@ -34,13 +34,13 @@ vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, bool vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, - vnl_vector const & h, - vnl_vector const & x, - vnl_vector const & y, + const vnl_vector & h, + const vnl_vector & x, + const vnl_vector & y, vnl_matrix & J) { - unsigned m = J.rows(); - unsigned n = J.columns(); + const unsigned m = J.rows(); + const unsigned n = J.columns(); assert(m == lsf->get_number_of_residuals()); assert(m == y.size()); assert(n == lsf->get_number_of_unknowns()); @@ -64,7 +64,7 @@ vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, } bool -vnl_discrete_diff_sym(vnl_least_squares_function * lsf, double h_, vnl_vector const & x, vnl_matrix & J) +vnl_discrete_diff_sym(vnl_least_squares_function * lsf, double h_, const vnl_vector & x, vnl_matrix & J) { vnl_vector h(lsf->get_number_of_unknowns()); h.fill(h_); @@ -73,19 +73,21 @@ vnl_discrete_diff_sym(vnl_least_squares_function * lsf, double h_, vnl_vector const & h, - vnl_vector const & x, + const vnl_vector & h, + const vnl_vector & x, vnl_matrix & J) { - unsigned m = J.rows(); - unsigned n = J.columns(); + const unsigned m = J.rows(); + const unsigned n = J.columns(); assert(m == lsf->get_number_of_residuals()); assert(n == lsf->get_number_of_unknowns()); assert(n == h.size()); assert(n == x.size()); - vnl_vector xp(n), xm(n); - vnl_vector yp(m), ym(m); + vnl_vector xp(n); + vnl_vector xm(n); + vnl_vector yp(m); + vnl_vector ym(m); for (unsigned j = 0; j < n; j++) { @@ -110,10 +112,10 @@ vnl_discrete_diff_sym(vnl_least_squares_function * lsf, //---------------------------------------------------------------------- void -vnl_discrete_diff_test_lsf(vnl_least_squares_function * lsf, vnl_vector const & x) +vnl_discrete_diff_test_lsf(vnl_least_squares_function * lsf, const vnl_vector & x) { - unsigned int m = lsf->get_number_of_residuals(); - unsigned int n = lsf->get_number_of_unknowns(); + const unsigned int m = lsf->get_number_of_residuals(); + const unsigned int n = lsf->get_number_of_unknowns(); assert(x.size() == n); vnl_matrix J1(m, n); @@ -122,9 +124,9 @@ vnl_discrete_diff_test_lsf(vnl_least_squares_function * lsf, vnl_vector vnl_matrix J2(m, n); vnl_discrete_diff_sym(lsf, 0.0001, x, J2); - double e = (J1 - J2).fro_norm(); + const double e = (J1 - J2).fro_norm(); // assert(e <= 1e-3); - double t = cos_angle(J1, J2); + const double t = cos_angle(J1, J2); // assert(t >= 0.99); std::cerr << __FILE__ ": e = " << e << std::endl << __FILE__ ": t = " << t << std::endl; diff --git a/core/vnl/algo/vnl_discrete_diff.h b/core/vnl/algo/vnl_discrete_diff.h index cc3d88e74aa..1dd5e4064d8 100644 --- a/core/vnl/algo/vnl_discrete_diff.h +++ b/core/vnl/algo/vnl_discrete_diff.h @@ -34,40 +34,40 @@ class vnl_least_squares_function; //: forward differences // \relatesalso vnl_least_squares_function -bool VNL_ALGO_EXPORT vnl_discrete_diff_fwd(vnl_least_squares_function *lsf, - double h, - vnl_vector const &x, - vnl_matrix &J); +bool VNL_ALGO_EXPORT +vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, double h, const vnl_vector & x, vnl_matrix & J); //: forward differences // \relatesalso vnl_least_squares_function -bool VNL_ALGO_EXPORT vnl_discrete_diff_fwd(vnl_least_squares_function *lsf, - vnl_vector const &h, - vnl_vector const &x, - vnl_matrix &J); +bool VNL_ALGO_EXPORT +vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, + const vnl_vector & h, + const vnl_vector & x, + vnl_matrix & J); //: forward differences // \relatesalso vnl_least_squares_function -bool VNL_ALGO_EXPORT vnl_discrete_diff_fwd(vnl_least_squares_function *lsf, - vnl_vector const &h, - vnl_vector const &x, - vnl_vector const &y, - vnl_matrix &J); +bool VNL_ALGO_EXPORT +vnl_discrete_diff_fwd(vnl_least_squares_function * lsf, + const vnl_vector & h, + const vnl_vector & x, + const vnl_vector & y, + vnl_matrix & J); //: symmetric differences // \relatesalso vnl_least_squares_function -bool VNL_ALGO_EXPORT vnl_discrete_diff_sym(vnl_least_squares_function *lsf, - double h, - vnl_vector const &x, - vnl_matrix &J); +bool VNL_ALGO_EXPORT +vnl_discrete_diff_sym(vnl_least_squares_function * lsf, double h, const vnl_vector & x, vnl_matrix & J); //: symmetric differences // \relatesalso vnl_least_squares_function -bool VNL_ALGO_EXPORT vnl_discrete_diff_sym(vnl_least_squares_function *lsf, - vnl_vector const &h, - vnl_vector const &x, - vnl_matrix &J); +bool VNL_ALGO_EXPORT +vnl_discrete_diff_sym(vnl_least_squares_function * lsf, + const vnl_vector & h, + const vnl_vector & x, + vnl_matrix & J); -void vnl_discrete_diff_test_lsf(vnl_least_squares_function *lsf, vnl_vector const &x); +void +vnl_discrete_diff_test_lsf(vnl_least_squares_function * lsf, const vnl_vector & x); #endif // vnl_discrete_diff_h_ diff --git a/core/vnl/algo/vnl_fft.cxx b/core/vnl/algo/vnl_fft.cxx index 05d9fc9d388..df792443b8c 100644 --- a/core/vnl/algo/vnl_fft.cxx +++ b/core/vnl/algo/vnl_fft.cxx @@ -22,13 +22,13 @@ vnl_fft_setgpfa(double * triggs, long size, long pqr[3], long * info) void vnl_fft_gpfa(float * a, float * b, - float const * triggs, + const float * triggs, long inc, long jump, long n, long lot, long isign, - long const pqr[3], + const long pqr[3], long * info) { v3p_netlib_gpfa_(a, b, triggs, &inc, &jump, &n, &lot, &isign, pqr); @@ -38,13 +38,13 @@ vnl_fft_gpfa(float * a, void vnl_fft_gpfa(double * a, double * b, - double const * triggs, + const double * triggs, long inc, long jump, long n, long lot, long isign, - long const pqr[3], + const long pqr[3], long * info) { v3p_netlib_dgpfa_(a, b, triggs, &inc, &jump, &n, &lot, &isign, pqr); diff --git a/core/vnl/algo/vnl_fft.h b/core/vnl/algo/vnl_fft.h index 7889dbcde71..d21130f4b80 100644 --- a/core/vnl/algo/vnl_fft.h +++ b/core/vnl/algo/vnl_fft.h @@ -11,9 +11,11 @@ #include //: use C++ overloading to find the correct FORTRAN routine from templated FFT code. -void VNL_ALGO_EXPORT vnl_fft_setgpfa(float *triggs, long size, long pqr[3], long *info); +void VNL_ALGO_EXPORT +vnl_fft_setgpfa(float * triggs, long size, long pqr[3], long * info); //: use C++ overloading to find the correct FORTRAN routine from templated FFT code. -void VNL_ALGO_EXPORT vnl_fft_setgpfa(double *triggs, long size, long pqr[3], long *info); +void VNL_ALGO_EXPORT +vnl_fft_setgpfa(double * triggs, long size, long pqr[3], long * info); // CALL GPFA(A,B,TRIGS,INC,JUMP,N,LOT,ISIGN,NIPQ,INFO) @@ -38,11 +40,27 @@ void VNL_ALGO_EXPORT vnl_fft_setgpfa(double *triggs, long size, long pqr[3], lon // These functions perform a number (LOT) of 1D FFTs, each of the same signal size (N). // The signal is stored in two real arrays (A, B), with consecutive elements separated // by a stride (INC). The separation between the LOT signals to be transformed is JUMP. -void VNL_ALGO_EXPORT vnl_fft_gpfa(float *a, float *b, float const *triggs, - long inc, long jump, long n, - long lot, long isign, long const pqr[3], long *info); -void VNL_ALGO_EXPORT vnl_fft_gpfa(double *a, double *b, double const *triggs, - long inc, long jump, long n, - long lot, long isign, long const pqr[3], long *info); +void VNL_ALGO_EXPORT +vnl_fft_gpfa(float * a, + float * b, + const float * triggs, + long inc, + long jump, + long n, + long lot, + long isign, + const long pqr[3], + long * info); +void VNL_ALGO_EXPORT +vnl_fft_gpfa(double * a, + double * b, + const double * triggs, + long inc, + long jump, + long n, + long lot, + long isign, + const long pqr[3], + long * info); #endif // vnl_fft_h_ diff --git a/core/vnl/algo/vnl_fft_1d.h b/core/vnl/algo/vnl_fft_1d.h index 53cef25f196..701e1865631 100644 --- a/core/vnl/algo/vnl_fft_1d.h +++ b/core/vnl/algo/vnl_fft_1d.h @@ -26,48 +26,77 @@ struct vnl_fft_1d : public vnl_fft_base<1, T> typedef vnl_fft_base<1, T> base; //: constructor takes length of signal. - vnl_fft_1d(int N) { - base::factors_[0].resize(N); - } + vnl_fft_1d(int N) { base::factors_[0].resize(N); } //: return length of signal. - unsigned int size() const { return base::factors_[0].number(); } + unsigned int + size() const + { + return base::factors_[0].number(); + } //: dir = +1/-1 according to direction of transform. - void transform(std::vector > &signal, int dir) - { base::transform(&signal[0], dir); } + void + transform(std::vector> & signal, int dir) + { + base::transform(&signal[0], dir); + } //: dir = +1/-1 according to direction of transform. - void transform(std::complex *signal, int dir) - { base::transform(signal, dir); } + void + transform(std::complex * signal, int dir) + { + base::transform(signal, dir); + } //: dir = +1/-1 according to direction of transform. - void transform(vnl_vector > &signal, int dir) - { base::transform(signal.data_block(), dir); } + void + transform(vnl_vector> & signal, int dir) + { + base::transform(signal.data_block(), dir); + } //: forward FFT - void fwd_transform(std::vector > &signal) - { transform(signal, +1); } + void + fwd_transform(std::vector> & signal) + { + transform(signal, +1); + } //: forward FFT - void fwd_transform(std::complex *signal) - { transform(signal, +1); } + void + fwd_transform(std::complex * signal) + { + transform(signal, +1); + } //: forward FFT - void fwd_transform(vnl_vector > &signal) - { transform(signal, +1); } + void + fwd_transform(vnl_vector> & signal) + { + transform(signal, +1); + } //: backward (inverse) FFT - void bwd_transform(std::vector > &signal) - { transform(signal, -1); } + void + bwd_transform(std::vector> & signal) + { + transform(signal, -1); + } //: backward (inverse) FFT - void bwd_transform(std::complex *signal) - { transform(signal, -1); } + void + bwd_transform(std::complex * signal) + { + transform(signal, -1); + } //: backward (inverse) FFT - void bwd_transform(vnl_vector > &signal) - { transform(signal, -1); } + void + bwd_transform(vnl_vector> & signal) + { + transform(signal, -1); + } }; #endif // vnl_fft_1d_h_ diff --git a/core/vnl/algo/vnl_fft_1d.hxx b/core/vnl/algo/vnl_fft_1d.hxx index 0ce6a7fe12a..f0e3dd4ef7f 100644 --- a/core/vnl/algo/vnl_fft_1d.hxx +++ b/core/vnl/algo/vnl_fft_1d.hxx @@ -5,7 +5,6 @@ #include "vnl_fft_1d.h" #undef VNL_FFT_1D_INSTANTIATE -#define VNL_FFT_1D_INSTANTIATE(T) \ -template struct VNL_ALGO_EXPORT vnl_fft_1d +#define VNL_FFT_1D_INSTANTIATE(T) template struct VNL_ALGO_EXPORT vnl_fft_1d #endif diff --git a/core/vnl/algo/vnl_fft_2d.h b/core/vnl/algo/vnl_fft_2d.h index 76823406602..f364e80838b 100644 --- a/core/vnl/algo/vnl_fft_2d.h +++ b/core/vnl/algo/vnl_fft_2d.h @@ -17,26 +17,44 @@ struct vnl_fft_2d : public vnl_fft_base<2, T> typedef vnl_fft_base<2, T> base; //: constructor takes size of signal. - vnl_fft_2d(int M, int N) { + vnl_fft_2d(int M, int N) + { base::factors_[0].resize(M); base::factors_[1].resize(N); } //: dir = +1/-1 according to direction of transform. - void transform(vnl_matrix > &signal, int dir) - { base::transform(signal.data_block(), dir); } + void + transform(vnl_matrix> & signal, int dir) + { + base::transform(signal.data_block(), dir); + } //: forward FFT - void fwd_transform(vnl_matrix > &signal) - { transform(signal, +1); } + void + fwd_transform(vnl_matrix> & signal) + { + transform(signal, +1); + } //: backward (inverse) FFT - void bwd_transform(vnl_matrix > &signal) - { transform(signal, -1); } + void + bwd_transform(vnl_matrix> & signal) + { + transform(signal, -1); + } //: return size of signal. - unsigned rows() const { return base::factors_[0].number(); } - unsigned cols() const { return base::factors_[1].number(); } + unsigned + rows() const + { + return base::factors_[0].number(); + } + unsigned + cols() const + { + return base::factors_[1].number(); + } }; #endif // vnl_fft_2d_h_ diff --git a/core/vnl/algo/vnl_fft_2d.hxx b/core/vnl/algo/vnl_fft_2d.hxx index 3488901b411..edcc4e774a0 100644 --- a/core/vnl/algo/vnl_fft_2d.hxx +++ b/core/vnl/algo/vnl_fft_2d.hxx @@ -5,7 +5,6 @@ #include "vnl_fft_2d.h" #undef VNL_FFT_2D_INSTANTIATE -#define VNL_FFT_2D_INSTANTIATE(T) \ -template struct VNL_ALGO_EXPORT vnl_fft_2d +#define VNL_FFT_2D_INSTANTIATE(T) template struct VNL_ALGO_EXPORT vnl_fft_2d #endif diff --git a/core/vnl/algo/vnl_fft_base.h b/core/vnl/algo/vnl_fft_base.h index dc72c35b87f..4b6d435d31a 100644 --- a/core/vnl/algo/vnl_fft_base.h +++ b/core/vnl/algo/vnl_fft_base.h @@ -21,9 +21,10 @@ struct VNL_ALGO_EXPORT vnl_fft_base vnl_fft_base() = default; //: dir = +1/-1 according to direction of transform. - void transform(std::complex *signal, int dir); + void + transform(std::complex * signal, int dir); - protected: +protected: //: prime factorizations of signal dimensions. vnl_fft_prime_factors factors_[D]; }; diff --git a/core/vnl/algo/vnl_fft_base.hxx b/core/vnl/algo/vnl_fft_base.hxx index 6f15f2e3cf8..cf3315c7159 100644 --- a/core/vnl/algo/vnl_fft_base.hxx +++ b/core/vnl/algo/vnl_fft_base.hxx @@ -11,45 +11,53 @@ #endif template -void vnl_fft_base::transform(std::complex *signal, int dir) +void +vnl_fft_base::transform(std::complex * signal, int dir) { assert((dir == +1) || (dir == -1)); // transform along each dimension, i, in turn. - for (int i=0; i i) N3 *= d; + for (int j = 0; j < D; ++j) + { + const int d = factors_[j].number(); + if (j < i) + N1 *= d; + if (j == i) + N2 *= d; + if (j > i) + N3 *= d; } // pretend the signal is N1xN2xN3. we want to transform // along the second dimension. - for (int n1=0; n1 is layout // compatible with "struct { T real; T imag; }". It is probably // a valid assumption for all sane C++ libraries. - T *data = (T *) (signal + n1*N2*N3 + n3); + T * data = (T *)(signal + n1 * N2 * N3 + n3); long info = 0; - vnl_fft_gpfa (/* A */ data, - /* B */ data + 1, - /* TRIGS */ factors_[i].trigs (), - /* INC */ 2*N3, - /* JUMP */ 0, - /* N */ N2, - /* LOT */ 1, - /* ISIGN */ dir, - /* NIPQ */ factors_[i].pqr (), - /* INFO */ &info); + vnl_fft_gpfa(/* A */ data, + /* B */ data + 1, + /* TRIGS */ factors_[i].trigs(), + /* INC */ 2 * N3, + /* JUMP */ 0, + /* N */ N2, + /* LOT */ 1, + /* ISIGN */ dir, + /* NIPQ */ factors_[i].pqr(), + /* INFO */ &info); assert(info != -1); } } @@ -57,7 +65,6 @@ void vnl_fft_base::transform(std::complex *signal, int dir) } #undef VNL_FFT_BASE_INSTANTIATE -#define VNL_FFT_BASE_INSTANTIATE(D, T) \ -template struct VNL_ALGO_EXPORT vnl_fft_base +#define VNL_FFT_BASE_INSTANTIATE(D, T) template struct VNL_ALGO_EXPORT vnl_fft_base #endif diff --git a/core/vnl/algo/vnl_fft_prime_factors.h b/core/vnl/algo/vnl_fft_prime_factors.h index f142e509061..aa5007076d9 100644 --- a/core/vnl/algo/vnl_fft_prime_factors.h +++ b/core/vnl/algo/vnl_fft_prime_factors.h @@ -26,46 +26,71 @@ template struct vnl_fft_prime_factors { private: - public: vnl_fft_prime_factors(); //: constructor takes the size of the signal. vnl_fft_prime_factors(int N) { construct(N); } - ~vnl_fft_prime_factors () { destruct(); } + ~vnl_fft_prime_factors() { destruct(); } //: array of twiddle factors. - T const *trigs () const { return trigs_; } + const T * + trigs() const + { + return trigs_; + } //: number which was factorized - int number () const { return number_; } + int + number() const + { + return number_; + } //: exponents P, Q, R. - long const *pqr () const { return pqr_; } + const long * + pqr() const + { + return pqr_; + } - explicit operator bool () const - { return (trigs_ && info_ >= 0)? true : false; } - bool operator!() const - { return (trigs_ && info_ >= 0)? false : true; } + explicit + operator bool() const + { + return (trigs_ && info_ >= 0) ? true : false; + } + bool + operator!() const + { + return (trigs_ && info_ >= 0) ? false : true; + } - void resize(int N) { + void + resize(int N) + { destruct(); construct(N); } - private: - T *trigs_; - long number_; // the number that is being split into prime-facs - long pqr_[3]; // store P, Q and R +private: + T * trigs_; + long number_; // the number that is being split into prime-facs + long pqr_[3]; // store P, Q and R long info_; - void construct(int N); - void destruct(); + void + construct(int N); + void + destruct(); // disallow copying - vnl_fft_prime_factors (vnl_fft_prime_factors const &) { } - vnl_fft_prime_factors& operator= (vnl_fft_prime_factors const &) { return *this; } + vnl_fft_prime_factors(const vnl_fft_prime_factors &) {} + vnl_fft_prime_factors & + operator=(const vnl_fft_prime_factors &) + { + return *this; + } }; #endif // vnl_fft_prime_factors_h_ diff --git a/core/vnl/algo/vnl_fft_prime_factors.hxx b/core/vnl/algo/vnl_fft_prime_factors.hxx index 3feddefdc1e..0154f84c74f 100644 --- a/core/vnl/algo/vnl_fft_prime_factors.hxx +++ b/core/vnl/algo/vnl_fft_prime_factors.hxx @@ -14,30 +14,30 @@ template vnl_fft_prime_factors::vnl_fft_prime_factors() : trigs_(nullptr) , number_(0) -{ -} +{} template -void vnl_fft_prime_factors::construct(int N) +void +vnl_fft_prime_factors::construct(int N) { - assert(N>0); - trigs_ = new T[2*N]; + assert(N > 0); + trigs_ = new T[2 * N]; number_ = N; - vnl_fft_setgpfa (trigs_, number_, pqr_, &info_); + vnl_fft_setgpfa(trigs_, number_, pqr_, &info_); // info_ == -1 if cannot split into primes if (info_ == -1) assert(!"you probably gave a signal size not of the form 2^p 3^q 5^r"); } template -void vnl_fft_prime_factors::destruct() +void +vnl_fft_prime_factors::destruct() { if (trigs_) - delete [] trigs_; + delete[] trigs_; } #undef VNL_FFT_PRIME_FACTORS_INSTANTIATE -#define VNL_FFT_PRIME_FACTORS_INSTANTIATE(T) \ -template struct VNL_ALGO_EXPORT vnl_fft_prime_factors +#define VNL_FFT_PRIME_FACTORS_INSTANTIATE(T) template struct VNL_ALGO_EXPORT vnl_fft_prime_factors #endif diff --git a/core/vnl/algo/vnl_fit_parabola.h b/core/vnl/algo/vnl_fit_parabola.h index 7263fce5bd0..f40291df5f9 100644 --- a/core/vnl/algo/vnl_fit_parabola.h +++ b/core/vnl/algo/vnl_fit_parabola.h @@ -15,17 +15,18 @@ //: Fit a parabola so as to estimate the position of the centre line // The centre (maxima or minima) lies at xb + p/q. // If q is near zero, then the parabola is nearly flat -inline void vnl_fit_parabola(double xa, double xb, double xc, - double fa, double fb, double fc, - double& p, double& q) +inline void +vnl_fit_parabola(double xa, double xb, double xc, double fa, double fb, double fc, double & p, double & q) { // Effectively shift origin to (xb,fb) // Parabola is then y=a*x*x+b*x // Centre is then at -b/2a = p/q in the following - double x1=xa-xb, f1 = fa-fb; - double x2=xc-xb, f2 = fc-fb; - p = x2*x2*f1-x1*x1*f2; - q = 2*(x2*f1-x1*f2); + const double x1 = xa - xb; + const double f1 = fa - fb; + const double x2 = xc - xb; + const double f2 = fc - fb; + p = x2 * x2 * f1 - x1 * x1 * f2; + q = 2 * (x2 * f1 - x1 * f2); } #endif // vnl_fit_parabola_h_ diff --git a/core/vnl/algo/vnl_gaussian_kernel_1d.cxx b/core/vnl/algo/vnl_gaussian_kernel_1d.cxx index b784e744504..bd1c4b26786 100644 --- a/core/vnl/algo/vnl_gaussian_kernel_1d.cxx +++ b/core/vnl/algo/vnl_gaussian_kernel_1d.cxx @@ -25,12 +25,12 @@ compute_width(double sigma, double cutoff) vnl_gaussian_kernel_1d::vnl_gaussian_kernel_1d(double sigma, double cutoff) : vec_((int)std::ceil(compute_width(sigma, cutoff))) { - int wid = vec_.size(); + const int wid = vec_.size(); inscale_ = 0.5 / (sigma * sigma); double area = 0; for (int i = 0; i < wid; ++i) { - double v = G(i); + const double v = G(i); area += v; vec_[i] = v; } diff --git a/core/vnl/algo/vnl_gaussian_kernel_1d.h b/core/vnl/algo/vnl_gaussian_kernel_1d.h index d6c7172f1bd..83c84e2ab3c 100644 --- a/core/vnl/algo/vnl_gaussian_kernel_1d.h +++ b/core/vnl/algo/vnl_gaussian_kernel_1d.h @@ -19,16 +19,25 @@ //: Holds one half of a discretely sampled 1D gaussian distribution class VNL_ALGO_EXPORT vnl_gaussian_kernel_1d { - public: +public: // Constructors/Destructors-------------------------------------------------- - vnl_gaussian_kernel_1d(double sigma, double cutoff = 0.5/256.0); + vnl_gaussian_kernel_1d(double sigma, double cutoff = 0.5 / 256.0); - double G(double x) const; + double + G(double x) const; - int width() const { return vec_.size(); } - double operator [] (int i) const { return vec_[i]; } + int + width() const + { + return vec_.size(); + } + double + operator[](int i) const + { + return vec_[i]; + } - protected: +protected: // Data Members-------------------------------------------------------------- vnl_vector vec_; double inscale_; diff --git a/core/vnl/algo/vnl_generalized_eigensystem.cxx b/core/vnl/algo/vnl_generalized_eigensystem.cxx index 29059bd8325..540c80a764e 100644 --- a/core/vnl/algo/vnl_generalized_eigensystem.cxx +++ b/core/vnl/algo/vnl_generalized_eigensystem.cxx @@ -28,7 +28,7 @@ vnl_generalized_eigensystem::vnl_generalized_eigensystem(const vnl_matrix work2(n); vnl_vector V1(n * n); - long want_eigenvectors = 1; + const long want_eigenvectors = 1; long ierr = -1; // Call EISPACK rsg. diff --git a/core/vnl/algo/vnl_generalized_eigensystem.h b/core/vnl/algo/vnl_generalized_eigensystem.h index 2760fe0610a..4c3337b178f 100644 --- a/core/vnl/algo/vnl_generalized_eigensystem.h +++ b/core/vnl/algo/vnl_generalized_eigensystem.h @@ -23,32 +23,31 @@ class VNL_ALGO_EXPORT vnl_generalized_eigensystem { - public: -// Public data members because they're unique. +public: + // Public data members because they're unique. long n; -//: Solves the generalized eigenproblem Ax=Bx -// Solve real generalized eigensystem $A x = \lambda B x$ for -// $\lambda$ and $x$, where $A$ symmetric, $B$ positive definite. -// Initializes storage for the matrix $V = [ x_0 x_1 .. x_n ]$ and -// the vnl_diag_matrix $D = [ \lambda_0 \lambda_1 ... \lambda_n ]$. -// The eigenvalues are sorted into increasing order (of value, not -// absolute value). -// -// Uses vnl_cholesky decomposition $C^\top C = B$, to convert to -// $C^{-\top} A C^{-1} x = \lambda x$ and then uses the -// symmetric eigensystem code. It will print a verbose warning -// if $B$ is not positive definite. - - vnl_generalized_eigensystem(const vnl_matrix& A, - const vnl_matrix& B); - -//: Public eigenvectors. -// After construction, this contains the matrix of eigenvectors. + //: Solves the generalized eigenproblem Ax=Bx + // Solve real generalized eigensystem $A x = \lambda B x$ for + // $\lambda$ and $x$, where $A$ symmetric, $B$ positive definite. + // Initializes storage for the matrix $V = [ x_0 x_1 .. x_n ]$ and + // the vnl_diag_matrix $D = [ \lambda_0 \lambda_1 ... \lambda_n ]$. + // The eigenvalues are sorted into increasing order (of value, not + // absolute value). + // + // Uses vnl_cholesky decomposition $C^\top C = B$, to convert to + // $C^{-\top} A C^{-1} x = \lambda x$ and then uses the + // symmetric eigensystem code. It will print a verbose warning + // if $B$ is not positive definite. + + vnl_generalized_eigensystem(const vnl_matrix & A, const vnl_matrix & B); + + //: Public eigenvectors. + // After construction, this contains the matrix of eigenvectors. vnl_matrix V; -//: Public eigenvalues. -// After construction, this contains the diagonal matrix of eigenvalues, stored as a vector. + //: Public eigenvalues. + // After construction, this contains the diagonal matrix of eigenvalues, stored as a vector. vnl_diag_matrix D; }; diff --git a/core/vnl/algo/vnl_generalized_schur.h b/core/vnl/algo/vnl_generalized_schur.h index 33183d92c01..8f77fc497ae 100644 --- a/core/vnl/algo/vnl_generalized_schur.h +++ b/core/vnl/algo/vnl_generalized_schur.h @@ -36,38 +36,45 @@ // In addition, the function computes the generalized eigenvalues // (alphar(k) + i alphai(k) : beta(k) for k = 0, 1, 2,... template -bool vnl_generalized_schur(vnl_matrix *A, - vnl_matrix *B, - vnl_vector *alphar, - vnl_vector *alphai, - vnl_vector *beta, - vnl_matrix *L, - vnl_matrix *R); +bool +vnl_generalized_schur(vnl_matrix * A, + vnl_matrix * B, + vnl_vector * alphar, + vnl_vector * alphai, + vnl_vector * beta, + vnl_matrix * L, + vnl_matrix * R); template <> -VNL_ALGO_EXPORT bool vnl_generalized_schur(vnl_matrix *A, - vnl_matrix *B, - vnl_vector *alphar, - vnl_vector *alphai, - vnl_vector *beta, - vnl_matrix *L, - vnl_matrix *R); +VNL_ALGO_EXPORT bool +vnl_generalized_schur(vnl_matrix * A, + vnl_matrix * B, + vnl_vector * alphar, + vnl_vector * alphai, + vnl_vector * beta, + vnl_matrix * L, + vnl_matrix * R); #ifdef _MSC_VER # include #endif template -T vnl_generalized_schur_convert_cast(double a) { return static_cast(a); } +T +vnl_generalized_schur_convert_cast(double a) +{ + return static_cast(a); +} template -inline bool vnl_generalized_schur(vnl_matrix *A, - vnl_matrix *B, - vnl_vector *alphar, - vnl_vector *alphai, - vnl_vector *beta, - vnl_matrix *L, - vnl_matrix *R) +inline bool +vnl_generalized_schur(vnl_matrix * A, + vnl_matrix * B, + vnl_vector * alphar, + vnl_vector * alphai, + vnl_vector * beta, + vnl_matrix * L, + vnl_matrix * R) { vnl_matrix A_(A->rows(), A->cols()); vnl_matrix B_(B->rows(), B->cols()); @@ -80,7 +87,7 @@ inline bool vnl_generalized_schur(vnl_matrix *A, vnl_matrix L_; vnl_matrix R_; - if (! vnl_generalized_schur/**/(&A_, &B_, &alphar_, &alphai_, &beta_, &L_, &R_)) + if (!vnl_generalized_schur /**/ (&A_, &B_, &alphar_, &alphai_, &beta_, &L_, &R_)) return false; std::transform(A_.begin(), A_.end(), A->begin(), vnl_generalized_schur_convert_cast); @@ -92,8 +99,8 @@ inline bool vnl_generalized_schur(vnl_matrix *A, alphai->set_size(alphai_.size()); std::transform(alphai_.begin(), alphai_.end(), alphai->begin(), vnl_generalized_schur_convert_cast); - beta ->set_size(beta_ .size()); - std::transform(beta_ .begin(), beta_ .end(), beta ->begin(), vnl_generalized_schur_convert_cast); + beta->set_size(beta_.size()); + std::transform(beta_.begin(), beta_.end(), beta->begin(), vnl_generalized_schur_convert_cast); L->set_size(L_.rows(), L_.cols()); std::transform(L_.begin(), L_.end(), L->begin(), vnl_generalized_schur_convert_cast); diff --git a/core/vnl/algo/vnl_lbfgs.cxx b/core/vnl/algo/vnl_lbfgs.cxx index 8f2b4e9d4cf..c1bc701e8f2 100644 --- a/core/vnl/algo/vnl_lbfgs.cxx +++ b/core/vnl/algo/vnl_lbfgs.cxx @@ -17,11 +17,7 @@ //: Default constructor. // memory is set to 5, line_search_accuracy to 0.9. // Calls init_parameters -vnl_lbfgs::vnl_lbfgs() - -{ - init_parameters(); -} +vnl_lbfgs::vnl_lbfgs() { init_parameters(); } //: Constructor. f is the cost function to be minimized. // Calls init_parameters @@ -69,7 +65,7 @@ vnl_lbfgs::minimize(vnl_vector & x) << (w.size() / 128.0 / 1024.0) << " MB], ErrorScale = " << f_->reported_error(1) << ", xnorm = " << x.magnitude() << std::endl; - bool we_trace = (verbose_ && !trace); + const bool we_trace = (verbose_ && !trace); if (we_trace) std::cerr << "vnl_lbfgs: "; @@ -107,8 +103,8 @@ vnl_lbfgs::minimize(vnl_vector & x) best_f = f; } -#define print_(i, a, b, c, d) \ - std::cerr << std::setw(6) << (i) << ' ' << std::setw(20) << (a) << ' ' << std::setw(20) << (b) << ' ' \ +#define print_(i, a, b, c, d) \ + std::cerr << std::setw(6) << (i) << ' ' << std::setw(20) << (a) << ' ' << std::setw(20) << (b) << ' ' \ << std::setw(20) << (c) << ' ' << std::setw(20) << (d) << '\n' if (check_derivatives_) @@ -118,8 +114,8 @@ vnl_lbfgs::minimize(vnl_vector & x) if (verbose_) { int l = n; - int limit = 100; - int limit_tail = 10; + const int limit = 100; + const int limit_tail = 10; if (l > limit + limit_tail) { std::cerr << " [ Showing only first " << limit << " components ]\n"; diff --git a/core/vnl/algo/vnl_lbfgs.h b/core/vnl/algo/vnl_lbfgs.h index 5d6a5a7ee2c..5e2bf8b6b2c 100644 --- a/core/vnl/algo/vnl_lbfgs.h +++ b/core/vnl/algo/vnl_lbfgs.h @@ -38,11 +38,12 @@ class VNL_ALGO_EXPORT vnl_lbfgs : public vnl_nonlinear_minimizer { - public: +public: vnl_lbfgs(); - vnl_lbfgs(vnl_cost_function& f); + vnl_lbfgs(vnl_cost_function & f); - bool minimize(vnl_vector& x); + bool + minimize(vnl_vector & x); //: Step accuracy/speed tradeoff. // Effectively the number of correction vectors to the diagonal approximation @@ -66,9 +67,10 @@ class VNL_ALGO_EXPORT vnl_lbfgs : public vnl_nonlinear_minimizer // single evaluation. double default_step_length; - private: - void init_parameters(); - vnl_cost_function *f_{nullptr}; +private: + void + init_parameters(); + vnl_cost_function * f_{ nullptr }; // vnl_lbfgs() {} // default constructor makes no sense // does too. Can set values for parameters. }; diff --git a/core/vnl/algo/vnl_lbfgsb.cxx b/core/vnl/algo/vnl_lbfgsb.cxx index cf8446b8819..088f47cadee 100644 --- a/core/vnl/algo/vnl_lbfgsb.cxx +++ b/core/vnl/algo/vnl_lbfgsb.cxx @@ -24,7 +24,7 @@ vnl_lbfgsb::vnl_lbfgsb(vnl_cost_function & f) void vnl_lbfgsb::init_parameters() { - long n = this->f_->get_number_of_unknowns(); + const long n = this->f_->get_number_of_unknowns(); this->bound_selection_.set_size(n); this->bound_selection_.fill(0); this->max_corrections_ = 5; @@ -37,8 +37,8 @@ bool vnl_lbfgsb::minimize(vnl_vector & x) { // Basic setup. - long n = this->f_->get_number_of_unknowns(); - long m = this->max_corrections_; + const long n = this->f_->get_number_of_unknowns(); + const long m = this->max_corrections_; // Function and gradient. double f = 0; @@ -67,7 +67,7 @@ vnl_lbfgsb::minimize(vnl_vector & x) // Verbosity level inside lbfgs implementation. // (-1 no o/p, 0 start and end, 1 every iter) - long const iprint = trace ? 1 : -1; + const long iprint = trace ? 1 : -1; // Initialize iteration. this->num_evaluations_ = 0; diff --git a/core/vnl/algo/vnl_lbfgsb.h b/core/vnl/algo/vnl_lbfgsb.h index 936cff6e427..60e9ee8a318 100644 --- a/core/vnl/algo/vnl_lbfgsb.h +++ b/core/vnl/algo/vnl_lbfgsb.h @@ -25,12 +25,13 @@ class VNL_ALGO_EXPORT vnl_lbfgsb : public vnl_nonlinear_minimizer { - public: - vnl_lbfgsb(vnl_cost_function& f); +public: + vnl_lbfgsb(vnl_cost_function & f); //: Find a minimum in the feasible region given an initial guess. // Returns true if a minimum is found and false for failure. - bool minimize(vnl_vector& x); + bool + minimize(vnl_vector & x); //: Set the bounds to be enforced on each variable. // The argument should have one entry per unknown. @@ -39,73 +40,111 @@ class VNL_ALGO_EXPORT vnl_lbfgsb : public vnl_nonlinear_minimizer // 1 - variable has only a lower bound // 2 - variable has both lower and upper bounds // 3 - variable has only an upper bound - void set_bound_selection(vnl_vector const& nbd) - { this->bound_selection_ = nbd; } + void + set_bound_selection(const vnl_vector & nbd) + { + this->bound_selection_ = nbd; + } //: Get the bounds currently enforced on each variable. - void get_bound_selection(vnl_vector& nbd) const - { nbd = this->bound_selection_; } + void + get_bound_selection(vnl_vector & nbd) const + { + nbd = this->bound_selection_; + } //: Set the lower bounds for all variables. // The argument should have one entry per unknown. // The lower bound is used only if the corresponding entry // in the bound selection vector is set to 1 or 2. - void set_lower_bound(vnl_vector const& l) - { this->lower_bound_ = l; } + void + set_lower_bound(const vnl_vector & l) + { + this->lower_bound_ = l; + } //: Get the lower bounds for all variables. - void get_lower_bound(vnl_vector& l) const - { l = this->lower_bound_; } + void + get_lower_bound(vnl_vector & l) const + { + l = this->lower_bound_; + } //: Set the upper bounds for all variables. // The argument should have one entry per unknown. // The upper bound is used only if the corresponding entry // in the bound selection vector is set to 2 or 3. - void set_upper_bound(vnl_vector const& u) - { this->upper_bound_ = u; } + void + set_upper_bound(const vnl_vector & u) + { + this->upper_bound_ = u; + } //: Get the upper bounds for all variables. - void get_upper_bound(vnl_vector& u) const - { u = this->upper_bound_; } + void + get_upper_bound(vnl_vector & u) const + { + u = this->upper_bound_; + } //: Set the maximum number of variable metric corrections. // This is used to determine the size of the limited-memory matrix. // The default value is 5. - void set_max_variable_metric_corrections(long m) - { this->max_corrections_ = m; } + void + set_max_variable_metric_corrections(long m) + { + this->max_corrections_ = m; + } //: Get the maximum number of variable metric corrections. - long get_max_variable_metric_corrections() const - { return this->max_corrections_; } + long + get_max_variable_metric_corrections() const + { + return this->max_corrections_; + } //: Set the cost function convergence factor. // When an iteration changes the function value by an amount smaller than // this factor times the machine epsilon (scaled by function magnitude) // convergence is assumed. The default value is 1e+7. - void set_cost_function_convergence_factor(double factor) - { this->convergence_factor_ = factor; } + void + set_cost_function_convergence_factor(double factor) + { + this->convergence_factor_ = factor; + } //: Get the cost function convergence factor. - double get_cost_function_convergence_factor() const - { return this->convergence_factor_; } + double + get_cost_function_convergence_factor() const + { + return this->convergence_factor_; + } //: Set the projected gradient tolerance. // When the projected gradient vector has no component larger than // the given value convergence is assumed. The default value is // 1e-5. - void set_projected_gradient_tolerance(double tol) - { this->projected_gradient_tolerance_ = tol; } + void + set_projected_gradient_tolerance(double tol) + { + this->projected_gradient_tolerance_ = tol; + } //: Get the projected gradient tolerance. - double get_projected_gradient_tolerance() const - { return this->projected_gradient_tolerance_; } + double + get_projected_gradient_tolerance() const + { + return this->projected_gradient_tolerance_; + } //: Get the current infinity norm of the projected gradient. - double get_inf_norm_projected_gradient() const - { return this->inf_norm_projected_gradient_; } - - protected: + double + get_inf_norm_projected_gradient() const + { + return this->inf_norm_projected_gradient_; + } +protected: vnl_vector lower_bound_; vnl_vector upper_bound_; vnl_vector bound_selection_; @@ -114,10 +153,11 @@ class VNL_ALGO_EXPORT vnl_lbfgsb : public vnl_nonlinear_minimizer double projected_gradient_tolerance_; double inf_norm_projected_gradient_; - private: +private: vnl_lbfgsb() = delete; // Not implemented - void init_parameters(); - vnl_cost_function* f_; + void + init_parameters(); + vnl_cost_function * f_; }; #endif // vnl_lbfgsb_h_ diff --git a/core/vnl/algo/vnl_ldl_cholesky.cxx b/core/vnl/algo/vnl_ldl_cholesky.cxx index 345370c09a0..89fe9df9104 100644 --- a/core/vnl/algo/vnl_ldl_cholesky.cxx +++ b/core/vnl/algo/vnl_ldl_cholesky.cxx @@ -23,7 +23,7 @@ // slowdown: 7.0 4.6 2.8 1.4 1.18 1.04 1.02 // \endverbatim -vnl_ldl_cholesky::vnl_ldl_cholesky(vnl_matrix const & M, Operation mode) +vnl_ldl_cholesky::vnl_ldl_cholesky(const vnl_matrix & M, Operation mode) : L_(M) { long n = M.columns(); @@ -99,7 +99,7 @@ dot(const double * v1, unsigned s, const double * v2, unsigned n) void vnl_ldl_cholesky::solve_lx(vnl_vector & x) { - unsigned n = d_.size(); + const unsigned n = d_.size(); for (unsigned i = 1; i < n; ++i) x[i] -= dot(L_[i], x.data_block(), i); } @@ -110,7 +110,7 @@ vnl_ldl_cholesky::solve_lx(vnl_vector & x) void vnl_ldl_cholesky::inplace_solve(double * x) const { - unsigned n = d_.size(); + const unsigned n = d_.size(); // Solve Ly=b for y for (unsigned i = 1; i < n; ++i) x[i] -= dot(L_[i], x, i); @@ -135,7 +135,7 @@ vnl_ldl_cholesky::inplace_solve(double * x) const double vnl_ldl_cholesky::xt_m_inv_x(const vnl_vector & x) const { - unsigned n = d_.size(); + const unsigned n = d_.size(); assert(x.size() == n); vnl_vector y = x; // Solve Ly=x for y and compute sum as we go @@ -153,7 +153,7 @@ vnl_ldl_cholesky::xt_m_inv_x(const vnl_vector & x) const double vnl_ldl_cholesky::xt_m_x(const vnl_vector & x) const { - unsigned n = d_.size(); + const unsigned n = d_.size(); assert(x.size() == n); double sum = 0.0; const double * xd = x.data_block(); @@ -161,7 +161,7 @@ vnl_ldl_cholesky::xt_m_x(const vnl_vector & x) const unsigned c = n; for (unsigned i = 0; i < n; ++i, ++xd, L_col += (n + 1), --c) { - double xLi = dot(L_col, n, xd, c); // x * i-th column + const double xLi = dot(L_col, n, xd, c); // x * i-th column sum += xLi * xLi * d_[i]; } return sum; @@ -172,7 +172,7 @@ vnl_ldl_cholesky::xt_m_x(const vnl_vector & x) const // The right-hand-side std::vector x may be b, // which will give a fractional increase in speed. void -vnl_ldl_cholesky::solve(vnl_vector const & b, vnl_vector * xp) const +vnl_ldl_cholesky::solve(const vnl_vector & b, vnl_vector * xp) const { assert(b.size() == d_.size()); *xp = b; @@ -181,7 +181,7 @@ vnl_ldl_cholesky::solve(vnl_vector const & b, vnl_vector * xp) c //: Solve least squares problem M x = b. vnl_vector -vnl_ldl_cholesky::solve(vnl_vector const & b) const +vnl_ldl_cholesky::solve(const vnl_vector & b) const { assert(b.size() == L_.columns()); @@ -194,7 +194,7 @@ vnl_ldl_cholesky::solve(vnl_vector const & b) const double vnl_ldl_cholesky::determinant() const { - unsigned n = d_.size(); + const unsigned n = d_.size(); double det = 1.0; for (unsigned i = 0; i < n; ++i) det *= d_[i]; @@ -210,15 +210,15 @@ vnl_ldl_cholesky::determinant() const void vnl_ldl_cholesky::rank1_update(const vnl_vector & v) { - unsigned n = d_.size(); + const unsigned n = d_.size(); assert(v.size() == n); double a = 1.0; vnl_vector w = v; // Workspace, modified as algorithm goes along for (unsigned j = 0; j < n; ++j) { - double a2 = a + w[j] * w[j] / d_[j]; + const double a2 = a + w[j] * w[j] / d_[j]; d_[j] *= a2; - double gamma = w[j] / d_[j]; + const double gamma = w[j] / d_[j]; d_[j] /= a; a = a2; @@ -236,18 +236,19 @@ vnl_ldl_cholesky::rank1_update(const vnl_vector & v) void vnl_ldl_cholesky::update(const vnl_matrix & W0) { - unsigned n = d_.size(); + const unsigned n = d_.size(); assert(W0.rows() == n); - unsigned r = W0.columns(); + const unsigned r = W0.columns(); - vnl_matrix W(W0); // Workspace - vnl_vector a(r, 1.0), gamma(r); // Workspace + vnl_matrix W(W0); // Workspace + vnl_vector a(r, 1.0); + vnl_vector gamma(r); // Workspace for (unsigned j = 0; j < n; ++j) { double * Wj = W[j]; for (unsigned i = 0; i < r; ++i) { - double a2 = a[i] + Wj[i] * Wj[i] / d_[j]; + const double a2 = a[i] + Wj[i] * Wj[i] / d_[j]; d_[j] *= a2; gamma[i] = Wj[i] / d_[j]; d_[j] /= a[i]; @@ -273,10 +274,10 @@ vnl_ldl_cholesky::inverse() const if (num_dims_rank_def_) { std::cerr << "vnl_ldl_cholesky: Calling inverse() on rank-deficient matrix\n"; - return vnl_matrix(); + return {}; } - unsigned int n = d_.size(); + const unsigned int n = d_.size(); vnl_matrix R(n, n); R.set_identity(); diff --git a/core/vnl/algo/vnl_ldl_cholesky.h b/core/vnl/algo/vnl_ldl_cholesky.h index fda2c789254..f9e4fda300d 100644 --- a/core/vnl/algo/vnl_ldl_cholesky.h +++ b/core/vnl/algo/vnl_ldl_cholesky.h @@ -28,78 +28,116 @@ // it might be a good idea to use vnl_svd instead. class VNL_ALGO_EXPORT vnl_ldl_cholesky { - public: +public: //: Modes of computation. See constructor for details. - enum Operation { + enum Operation + { quiet, verbose, estimate_condition }; //: Make cholesky decomposition of M optionally computing the reciprocal condition number. - vnl_ldl_cholesky(vnl_matrix const& M, Operation mode = verbose); - ~vnl_ldl_cholesky() = default; + vnl_ldl_cholesky(const vnl_matrix & M, Operation mode = verbose); + ~vnl_ldl_cholesky() = default; //: Solve LS problem M x = b - vnl_vector solve(vnl_vector const& b) const; + vnl_vector + solve(const vnl_vector & b) const; //: Solve LS problem M x = b - void solve(vnl_vector const& b, vnl_vector* x) const; + void + solve(const vnl_vector & b, vnl_vector * x) const; //: Solve equation of form Lx=y (in-place) // x is overwritten with solution - void solve_lx(vnl_vector& y); + void + solve_lx(vnl_vector & y); //: Compute determinant - double determinant() const; + double + determinant() const; //: Compute rank-1 update, ie the decomposition of (M+v.v') // If the initial state is the decomposition of M, then // L and D are updated so that on exit LDL'=M+v.v' - void rank1_update(const vnl_vector& v); + void + rank1_update(const vnl_vector & v); //: Multi-rank update, ie the decomposition of (M+W.W') // If the initial state is the decomposition of M, then // L and D are updated so that on exit LDL'=M+W.W' - void update(const vnl_matrix& W); + void + update(const vnl_matrix & W); //: Compute inverse. Not efficient. // Note that you rarely need the inverse - backsubstitution // is faster and less prone to rounding errors. - vnl_matrix inverse() const; + vnl_matrix + inverse() const; //: Return lower-triangular factor. - const vnl_matrix& lower_triangle() const { return L_; } + const vnl_matrix & + lower_triangle() const + { + return L_; + } //: Return upper-triangular factor. - vnl_matrix upper_triangle() const { return L_.transpose(); } + vnl_matrix + upper_triangle() const + { + return L_.transpose(); + } //: Return elements of diagonal matrix D in LDL' - const vnl_vector& diagonal() const { return d_; } + const vnl_vector & + diagonal() const + { + return d_; + } //: Efficient computation of x' * inv(M) * x // Useful when M is a covariance matrix! - double xt_m_inv_x(const vnl_vector& x) const; + double + xt_m_inv_x(const vnl_vector & x) const; //: Efficient computation of x' * M * x // Twice as fast as explicitly computing x' * M * x - double xt_m_x(const vnl_vector& x) const; + double + xt_m_x(const vnl_vector & x) const; //: A Success/failure flag - int rank_deficiency() const { return num_dims_rank_def_; } + int + rank_deficiency() const + { + return num_dims_rank_def_; + } //: Return reciprocal condition number (smallest/largest singular values). // As long as rcond()>sqrt(precision) the decomposition can be used for // solving equations safely. // Not calculated unless Operation mode at construction was estimate_condition. - double rcond() const { return rcond_; } + double + rcond() const + { + return rcond_; + } //: Return computed nullvector. // Not calculated unless Operation mode at construction was estimate_condition. - vnl_vector & nullvector() { return nullvector_; } - vnl_vector const& nullvector() const { return nullvector_; } - - protected: + vnl_vector & + nullvector() + { + return nullvector_; + } + const vnl_vector & + nullvector() const + { + return nullvector_; + } + +protected: // Data Members-------------------------------------------------------------- //: Lower triangular matrix @@ -113,16 +151,18 @@ class VNL_ALGO_EXPORT vnl_ldl_cholesky long num_dims_rank_def_; vnl_vector nullvector_; - private: +private: //: Copy constructor - privatised to avoid it being used - vnl_ldl_cholesky(vnl_ldl_cholesky const & that) = delete; + vnl_ldl_cholesky(const vnl_ldl_cholesky & that) = delete; //: Assignment operator - privatised to avoid it being used - vnl_ldl_cholesky& operator=(vnl_ldl_cholesky const & that) = delete; + vnl_ldl_cholesky & + operator=(const vnl_ldl_cholesky & that) = delete; //: Solve Mx=b, overwriting input vector with the solution. // x points to beginning of an n-element vector containing b // On exit, x[i] filled with solution vector. - void inplace_solve(double* x) const; + void + inplace_solve(double * x) const; }; #endif // vnl_ldl_cholesky_h_ diff --git a/core/vnl/algo/vnl_levenberg_marquardt.cxx b/core/vnl/algo/vnl_levenberg_marquardt.cxx index a7842324f01..fc4ba70fd89 100644 --- a/core/vnl/algo/vnl_levenberg_marquardt.cxx +++ b/core/vnl/algo/vnl_levenberg_marquardt.cxx @@ -16,7 +16,7 @@ // see header vnl_vector -vnl_levenberg_marquardt_minimize(vnl_least_squares_function & f, vnl_vector const & initial_estimate) +vnl_levenberg_marquardt_minimize(vnl_least_squares_function & f, const vnl_vector & initial_estimate) { vnl_vector x = initial_estimate; vnl_levenberg_marquardt lm(f); @@ -38,8 +38,8 @@ vnl_levenberg_marquardt::init(vnl_least_squares_function * f) gtol = 1e-5; // Termination tolerance on Grad(F)' * F = 0 epsfcn = xtol * 0.001; // Step length for FD Jacobian - unsigned int m = f_->get_number_of_residuals(); // I Number of residuals, must be > #unknowns - unsigned int n = f_->get_number_of_unknowns(); // I Number of unknowns + const unsigned int m = f_->get_number_of_residuals(); // I Number of residuals, must be > #unknowns + const unsigned int n = f_->get_number_of_unknowns(); // I Number of unknowns set_covariance_ = false; fdjac_.set_size(n, m); @@ -76,7 +76,7 @@ vnl_levenberg_marquardt::lmdif_lsqfun(long * n, // I Number of residuals assert(*n == (int)f->get_number_of_residuals()); assert(*p > 0); assert(*n >= *p); - vnl_vector_ref ref_x(*p, const_cast(x)); + const vnl_vector_ref ref_x(*p, const_cast(x)); vnl_vector_ref ref_fx(*n, fx); if (*iflag == 0) @@ -249,7 +249,7 @@ vnl_levenberg_marquardt::lmder_lsqfun(long * n, // I Number of residuals assert(*n == (int)f->get_number_of_residuals()); assert(*p > 0); assert(*n >= *p); - vnl_vector_ref ref_x(*p, (double *)x); // const violation! + const vnl_vector_ref ref_x(*p, (double *)x); // const violation! vnl_vector_ref ref_fx(*n, fx); vnl_matrix_ref ref_fJ(*n, *p, fJ); @@ -294,7 +294,6 @@ vnl_levenberg_marquardt::lmder_lsqfun(long * n, // I Number of residuals vnl_matrix finite_jac(*p, *n, 0.0); vnl_vector wa1(*n); long info = 1; - double diff; f->f(ref_x, feval); v3p_netlib_fdjac2_(lmdif_lsqfun, n, @@ -311,7 +310,7 @@ vnl_levenberg_marquardt::lmder_lsqfun(long * n, // I Number of residuals for (unsigned i = 0; i < ref_fJ.cols(); ++i) for (unsigned j = 0; j < ref_fJ.rows(); ++j) { - diff = ref_fJ(j, i) - finite_jac(j, i); + double diff = ref_fJ(j, i) - finite_jac(j, i); diff = diff * diff; if (diff > self->epsfcn) { @@ -361,7 +360,9 @@ vnl_levenberg_marquardt::minimize_using_gradient(vnl_vector & x) double factor = 100; long nprint = 1; - long mode = 1, nfev, njev; + long mode = 1; + long nfev; + long njev; vnl_vector diag(n, 0); vnl_vector qtf(n, 0); @@ -471,7 +472,7 @@ vnl_levenberg_marquardt::diagnose_outcome(std::ostream & s) const s << (whoami ": OIOIOI: unkown info code from lmder.\n"); break; } - unsigned int m = f_->get_number_of_residuals(); + const unsigned int m = f_->get_number_of_residuals(); s << whoami ": " << num_iterations_ << " iterations, " << num_evaluations_ << " evaluations, " << m << " residuals. RMS error start/end " << get_start_error() << '/' << get_end_error() << std::endl; #undef whoami @@ -494,13 +495,13 @@ vnl_levenberg_marquardt::diagnose_outcome(std::ostream & s) const //: Get INVERSE of covariance at last minimum. // Code thanks to Joss Knight (joss@robots.ox.ac.uk) -vnl_matrix const & +const vnl_matrix & vnl_levenberg_marquardt::get_JtJ() { if (!set_covariance_) { std::cerr << __FILE__ ": get_covariance() not confirmed tested yet\n"; - unsigned int n = fdjac_.rows(); + const unsigned int n = fdjac_.rows(); // matrix in FORTRAN is column-wise. // transpose it to get C style order diff --git a/core/vnl/algo/vnl_levenberg_marquardt.h b/core/vnl/algo/vnl_levenberg_marquardt.h index 53611db6fe1..88b3e01ed48 100644 --- a/core/vnl/algo/vnl_levenberg_marquardt.h +++ b/core/vnl/algo/vnl_levenberg_marquardt.h @@ -42,10 +42,9 @@ class vnl_least_squares_function; class VNL_ALGO_EXPORT vnl_levenberg_marquardt : public vnl_nonlinear_minimizer { - public: - +public: //: Initialize with the function object that is to be minimized. - vnl_levenberg_marquardt(vnl_least_squares_function& f) { init(&f); } + vnl_levenberg_marquardt(vnl_least_squares_function & f) { init(&f); } ~vnl_levenberg_marquardt() override; @@ -53,54 +52,86 @@ class VNL_ALGO_EXPORT vnl_levenberg_marquardt : public vnl_nonlinear_minimizer // On return, x is such that f(x) is the lowest value achieved. // Returns true for convergence, false for failure. // Does not use the gradient even if the cost function provides one. - bool minimize_without_gradient(vnl_vector& x); + bool + minimize_without_gradient(vnl_vector & x); //: Minimize the function supplied in the constructor until convergence or failure. // On return, x is such that f(x) is the lowest value achieved. // Returns true for convergence, false for failure. // The cost function must provide a gradient. - bool minimize_using_gradient (vnl_vector& x); + bool + minimize_using_gradient(vnl_vector & x); //: Calls minimize_using_gradient() or minimize_without_gradient(), // depending on whether the cost function provides a gradient. - bool minimize(vnl_vector& x); - bool minimize(vnl_vector_fixed& x) { vnl_vector y=x.extract(1); bool b=minimize(y); x=y; return b; } - bool minimize(vnl_vector_fixed& x) { vnl_vector y=x.extract(2); bool b=minimize(y); x=y; return b; } - bool minimize(vnl_vector_fixed& x) { vnl_vector y=x.extract(3); bool b=minimize(y); x=y; return b; } - bool minimize(vnl_vector_fixed& x) { vnl_vector y=x.extract(4); bool b=minimize(y); x=y; return b; } + bool + minimize(vnl_vector & x); + bool + minimize(vnl_vector_fixed & x) + { + vnl_vector y = x.extract(1); + const bool b = minimize(y); + x = y; + return b; + } + bool + minimize(vnl_vector_fixed & x) + { + vnl_vector y = x.extract(2); + const bool b = minimize(y); + x = y; + return b; + } + bool + minimize(vnl_vector_fixed & x) + { + vnl_vector y = x.extract(3); + const bool b = minimize(y); + x = y; + return b; + } + bool + minimize(vnl_vector_fixed & x) + { + vnl_vector y = x.extract(4); + const bool b = minimize(y); + x = y; + return b; + } // Coping with failure------------------------------------------------------- //: Provide an ASCII diagnosis of the last minimization on std::ostream. void diagnose_outcome(/*std::cerr*/) const; - void diagnose_outcome(std::ostream&) const; + void + diagnose_outcome(std::ostream &) const; //: Return J'*J computed at last minimum. // it is an approximation of inverse of covariance - vnl_matrix const& get_JtJ(); - - protected: + const vnl_matrix & + get_JtJ(); - vnl_least_squares_function* f_; +protected: + vnl_least_squares_function * f_; vnl_matrix fdjac_; // Computed during lmdif/lmder - vnl_vector ipvt_; // Also computed, both needed to get J'*J at end. + vnl_vector ipvt_; // Also computed, both needed to get J'*J at end. vnl_matrix inv_covar_; bool set_covariance_; // Set if covariance_ holds J'*J - void init(vnl_least_squares_function* f); + void + init(vnl_least_squares_function * f); // Communication with callback - static void lmdif_lsqfun(long* m, long* n, double* x, - double* fx, long* iflag, void* userdata); - static void lmder_lsqfun(long* m, long* n, double* x, - double* fx, double* fJ, long*, long* iflag, - void* userdata); + static void + lmdif_lsqfun(long * m, long * n, double * x, double * fx, long * iflag, void * userdata); + static void + lmder_lsqfun(long * m, long * n, double * x, double * fx, double * fJ, long *, long * iflag, void * userdata); }; //: Find minimum of "f", starting at "initial_estimate", and return. -vnl_vector vnl_levenberg_marquardt_minimize(vnl_least_squares_function& f, - vnl_vector const& initial_estimate); +vnl_vector +vnl_levenberg_marquardt_minimize(vnl_least_squares_function & f, const vnl_vector & initial_estimate); #endif // vnl_levenberg_marquardt_h_ diff --git a/core/vnl/algo/vnl_lsqr.cxx b/core/vnl/algo/vnl_lsqr.cxx index 91974807e71..32bef2f3a9e 100644 --- a/core/vnl/algo/vnl_lsqr.cxx +++ b/core/vnl/algo/vnl_lsqr.cxx @@ -30,7 +30,7 @@ class lsqrVNL : public lsqrBase void Aprod1(unsigned int m, unsigned int n, const double * x, double * y) const override { - vnl_vector_ref x_ref(n, const_cast(x)); + const vnl_vector_ref x_ref(n, const_cast(x)); vnl_vector_ref y_ref(m, y); vnl_vector_ref tmp(m, rw); @@ -49,7 +49,7 @@ class lsqrVNL : public lsqrBase Aprod2(unsigned int m, unsigned int n, double * x, const double * y) const override { vnl_vector_ref x_ref(n, x); - vnl_vector_ref y_ref(m, const_cast(y)); + const vnl_vector_ref y_ref(m, const_cast(y)); vnl_vector_ref tmp(n, this->rw); this->ls_->transpose_multiply(y_ref, tmp); @@ -125,15 +125,15 @@ vnl_lsqr::minimize(vnl_vector & result) { const long m = ls_->get_number_of_residuals(); const long n = ls_->get_number_of_unknowns(); - double damp = 0; + const double damp = 0; // NOTE: rw is a scratch space used for both intermediate residual and unknown computations std::vector rw(std::max(m, n)); - std::vector v(n); + const std::vector v(n); std::vector se(n); - double atol = 0; - double btol = 0; + const double atol = 0; + const double btol = 0; vnl_vector rhs(m); ls_->get_rhs(rhs); diff --git a/core/vnl/algo/vnl_lsqr.h b/core/vnl/algo/vnl_lsqr.h index 14eedf5d69e..07a3da6119e 100644 --- a/core/vnl/algo/vnl_lsqr.h +++ b/core/vnl/algo/vnl_lsqr.h @@ -37,34 +37,55 @@ class VNL_ALGO_EXPORT vnl_lsqr { - public: - vnl_lsqr(vnl_linear_system& ls) : - ls_(&ls), max_iter_(4*ls.get_number_of_unknowns()) {} +public: + vnl_lsqr(vnl_linear_system & ls) + : ls_(&ls) + , max_iter_(4 * ls.get_number_of_unknowns()) + {} ~vnl_lsqr(); - void set_max_iterations(long max_iter) { max_iter_ = max_iter; } + void + set_max_iterations(long max_iter) + { + max_iter_ = max_iter; + } //: Perform the minimization starting from x=0 and putting the result into x. // Return code may be translated with translate_return_code(), or the result of the // minimization may be printed in more detail with diagnose_outcome() - int minimize(vnl_vector& x); + int + minimize(vnl_vector & x); - long get_number_of_iterations() const { return num_iter_; } + long + get_number_of_iterations() const + { + return num_iter_; + } //: Pontificate about the outcome of the last minimization. - void diagnose_outcome(std::ostream& os) const; + void + diagnose_outcome(std::ostream & os) const; - static void translate_return_code(std::ostream& os, int return_code); + static void + translate_return_code(std::ostream & os, int return_code); //: Return the residual norm estimate: - double get_resid_norm_estimate() const { return resid_norm_estimate_; } + double + get_resid_norm_estimate() const + { + return resid_norm_estimate_; + } //: Get the return code for the last minimization - inline long return_code() const { return return_code_; } + inline long + return_code() const + { + return return_code_; + } - protected: - vnl_linear_system* ls_; +protected: + vnl_linear_system * ls_; long max_iter_; long num_iter_; double resid_norm_estimate_; @@ -72,9 +93,17 @@ class VNL_ALGO_EXPORT vnl_lsqr double A_condition_estimate_; long return_code_; - static int aprod_(const long* mode, const long* m, const long* n, double* x, double* y, - long* leniw, long* lenrw, long* iw, double* rw, - void* userdata); + static int + aprod_(const long * mode, + const long * m, + const long * n, + double * x, + double * y, + long * leniw, + long * lenrw, + long * iw, + double * rw, + void * userdata); }; #endif // vnl_lsqr_h_ diff --git a/core/vnl/algo/vnl_matrix_inverse.h b/core/vnl/algo/vnl_matrix_inverse.h index 37078932a9f..42cf8297c25 100644 --- a/core/vnl/algo/vnl_matrix_inverse.h +++ b/core/vnl/algo/vnl_matrix_inverse.h @@ -31,33 +31,42 @@ template struct vnl_matrix_inverse : public vnl_svd { - vnl_matrix_inverse(vnl_matrix const & M): vnl_svd(M) { } + vnl_matrix_inverse(const vnl_matrix & M) + : vnl_svd(M) + {} ~vnl_matrix_inverse() override = default; - vnl_matrix as_matrix() const { return this->inverse(); } + vnl_matrix + as_matrix() const + { + return this->inverse(); + } -#if ! VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS - explicit operator vnl_matrix() const { return this->inverse(); } +#if !VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS + explicit + operator vnl_matrix() const + { + return this->inverse(); + } #else -#if VXL_LEGACY_FUTURE_REMOVE - VXL_DEPRECATED_MSG("Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") -#endif +# if VXL_LEGACY_FUTURE_REMOVE + VXL_DEPRECATED_MSG( + "Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") +# endif operator vnl_matrix() const { return this->inverse(); } #endif }; template -inline -vnl_vector operator*(vnl_matrix_inverse const & i, - vnl_vector const & B) +inline vnl_vector +operator*(const vnl_matrix_inverse & i, const vnl_vector & B) { return i.solve(B); } template -inline -vnl_matrix operator*(vnl_matrix_inverse const & i, - vnl_matrix const & B) +inline vnl_matrix +operator*(const vnl_matrix_inverse & i, const vnl_matrix & B) { return i.solve(B); } diff --git a/core/vnl/algo/vnl_matrix_inverse.hxx b/core/vnl/algo/vnl_matrix_inverse.hxx index 0206e8d826e..682460fe2f0 100644 --- a/core/vnl/algo/vnl_matrix_inverse.hxx +++ b/core/vnl/algo/vnl_matrix_inverse.hxx @@ -9,9 +9,9 @@ #include "vnl_matrix_inverse.h" #undef VNL_MATRIX_INVERSE_INSTANTIATE -#define VNL_MATRIX_INVERSE_INSTANTIATE(T) \ -template struct VNL_ALGO_EXPORT vnl_matrix_inverse;\ -/*template VNL_EXPORT vnl_vector operator*(vnl_matrix_inverse const &, vnl_vector const &) ; */ \ -/*template VNL_EXPORT vnl_matrix operator*(vnl_matrix_inverse const &, vnl_matrix const &) */ +#define VNL_MATRIX_INVERSE_INSTANTIATE(T) \ + template struct VNL_ALGO_EXPORT vnl_matrix_inverse; \ + /*template VNL_EXPORT vnl_vector operator*(vnl_matrix_inverse const &, vnl_vector const &) ; */ \ + /*template VNL_EXPORT vnl_matrix operator*(vnl_matrix_inverse const &, vnl_matrix const &) */ #endif // vnl_matrix_inverse_hxx_ diff --git a/core/vnl/algo/vnl_matrix_update.h b/core/vnl/algo/vnl_matrix_update.h index 542aa1ce263..f1849996ebe 100644 --- a/core/vnl/algo/vnl_matrix_update.h +++ b/core/vnl/algo/vnl_matrix_update.h @@ -16,24 +16,24 @@ //: Perform rank 1 update of M: M+=(a*b') // Requires a.size()==M.rows(), b.size()==M.columns() // \relatesalso vnl_matrix -template -inline void vnl_matrix_update(vnl_matrix& M, - const vnl_vector& a, - const vnl_vector& b) +template +inline void +vnl_matrix_update(vnl_matrix & M, const vnl_vector & a, const vnl_vector & b) { - unsigned nr=M.rows(); - unsigned nc=M.columns(); - assert(a.size()==nr); - assert(b.size()==nc); - T** rows=M.data_array(); - for (unsigned i=0;i // xSVDC -#define vnl_netlib_svd_proto(T) \ -T *x, long int const *ldx, long int const *m, long int const *n, \ -T *sv, \ -T *errors, \ -T *u, long int const *ldu, \ -T *v, long int const *ldv, \ -T *work, \ -long int const *job, long int *info -#define vnl_netlib_svd_params \ -x, ldx, m, n, sv, errors, u, ldu, v, ldv, work, job, info +#define vnl_netlib_svd_proto(T) \ + T *x, long int const *ldx, long int const *m, long int const *n, T *sv, T *errors, T *u, long int const *ldu, T *v, \ + long int const *ldv, T *work, long int const *job, long int *info +#define vnl_netlib_svd_params x, ldx, m, n, sv, errors, u, ldu, v, ldv, work, job, info // xQRDC -#define vnl_netlib_qrdc_proto(T) \ -T *x, \ -long int const* ldx, \ -long int const* n, \ -long int const* p, \ -T* qraux, \ -long int *jpvt, \ -T *work, \ -long int const* job -#define vnl_netlib_qrdc_params \ -x, ldx, n, p, qraux, jpvt, work, job +#define vnl_netlib_qrdc_proto(T) \ + T *x, long int const *ldx, long int const *n, long int const *p, T *qraux, long int *jpvt, T *work, \ + long int const *job +#define vnl_netlib_qrdc_params x, ldx, n, p, qraux, jpvt, work, job // xQRSL -#define vnl_netlib_qrsl_proto(T) \ -T const *x, \ -long int *ldx, \ -long int *n, \ -long int *k, \ -T const *qraux, \ -T const *y, \ -T *qy, \ -T *qty, \ -T *b, \ -T *rsd, \ -T *xb, \ -long int *job, \ -long int *info -#define vnl_netlib_qrsl_params \ -x, ldx, n, k, qraux, y, qy, qty, b, rsd, xb, job, info +#define vnl_netlib_qrsl_proto(T) \ + T const *x, long int *ldx, long int *n, long int *k, T const *qraux, T const *y, T *qy, T *qty, T *b, T *rsd, T *xb, \ + long int *job, long int *info +#define vnl_netlib_qrsl_params x, ldx, n, k, qraux, y, qy, qty, b, rsd, xb, job, info #endif // vnl_netlib_h_ diff --git a/core/vnl/algo/vnl_orthogonal_complement.h b/core/vnl/algo/vnl_orthogonal_complement.h index d06bc2c17c3..6e6a2d5a42a 100644 --- a/core/vnl/algo/vnl_orthogonal_complement.h +++ b/core/vnl/algo/vnl_orthogonal_complement.h @@ -19,6 +19,7 @@ //: Return a matrix whose columns span is the orthogonal complement of v. // \relatesalso vnl_matrix template -vnl_matrix vnl_orthogonal_complement(vnl_vector const &v); +vnl_matrix +vnl_orthogonal_complement(const vnl_vector & v); #endif // vnl_orthogonal_complement_h_ diff --git a/core/vnl/algo/vnl_orthogonal_complement.hxx b/core/vnl/algo/vnl_orthogonal_complement.hxx index 644f41905c0..e4b5c8a3ca4 100644 --- a/core/vnl/algo/vnl_orthogonal_complement.hxx +++ b/core/vnl/algo/vnl_orthogonal_complement.hxx @@ -8,19 +8,20 @@ #include template -vnl_matrix vnl_orthogonal_complement(vnl_vector const &v) +vnl_matrix +vnl_orthogonal_complement(const vnl_vector & v) { - unsigned n = v.size(); + const unsigned n = v.size(); vnl_matrix tmp(1, n); tmp.set_row(0, v); - return vnl_svd(tmp).V().extract(n, n-1, 0, 1); + return vnl_svd(tmp).V().extract(n, n - 1, 0, 1); } //-------------------------------------------------------------------------------- #undef VNL_ORTHOGONAL_COMPLEMENT_INSTANTIATE -#define VNL_ORTHOGONAL_COMPLEMENT_INSTANTIATE(T) \ -/* template vnl_matrix vnl_orthogonal_complement(vnl_matrix const &); */ \ -template VNL_ALGO_EXPORT vnl_matrix vnl_orthogonal_complement(vnl_vector const &) +#define VNL_ORTHOGONAL_COMPLEMENT_INSTANTIATE(T) \ + /* template vnl_matrix vnl_orthogonal_complement(vnl_matrix const &); */ \ + template VNL_ALGO_EXPORT vnl_matrix vnl_orthogonal_complement(vnl_vector const &) #endif // vnl_orthogonal_complement_hxx_ diff --git a/core/vnl/algo/vnl_powell.cxx b/core/vnl/algo/vnl_powell.cxx index 19d563c12ae..ba36e9ba673 100644 --- a/core/vnl/algo/vnl_powell.cxx +++ b/core/vnl/algo/vnl_powell.cxx @@ -42,7 +42,7 @@ class vnl_powell_1dfun : public vnl_cost_function {} void - init(vnl_vector const & x0, vnl_vector const & dx) + init(const vnl_vector & x0, const vnl_vector & dx) { x0_ = x0; dx_ = dx; @@ -54,7 +54,7 @@ class vnl_powell_1dfun : public vnl_cost_function f(const vnl_vector & x) override { uninit(x[0], tmpx_); - double e = f_->f(tmpx_); + const double e = f_->f(tmpx_); powell_->pub_report_eval(e); return e; } @@ -71,7 +71,7 @@ vnl_nonlinear_minimizer::ReturnCodes vnl_powell::minimize(vnl_vector & p) { // verbose_ = true; - int n = p.size(); + const int n = p.size(); vnl_powell_1dfun f1d(n, functor_, this); vnl_matrix xi(n, n, vnl_matrix_identity); @@ -82,7 +82,7 @@ vnl_powell::minimize(vnl_vector & p) vnl_vector pt = p; while (num_iterations_ < unsigned(maxfev)) { - double fp = fret; + const double fp = fret; int ibig = 0; double del = 0.0; @@ -91,7 +91,7 @@ vnl_powell::minimize(vnl_vector & p) // xit = ith column of xi for (int j = 0; j < n; ++j) xit[j] = xi[j][i]; - double fptt = fret; + const double fptt = fret; // 1D minimization along xi f1d.init(p, xit); @@ -108,7 +108,9 @@ vnl_powell::minimize(vnl_vector & p) double xx = initial_step_; double bx; { - double fa, fxx, fb; + double fa; + double fxx; + double fb; vnl_bracket_minimum(f1d, ax, xx, bx, fa, fxx, fb); } brent.set_x_tolerance(linmin_xtol_); @@ -144,11 +146,11 @@ vnl_powell::minimize(vnl_vector & p) pt[j] = p[j]; } - double fptt = functor_->f(ptt); + const double fptt = functor_->f(ptt); report_eval(fret); if (fptt < fp) { - double t = 2.0 * (fp - 2.0 * fret + fptt) * vnl_math::sqr(fp - fret - del) - del * vnl_math::sqr(fp - fptt); + const double t = 2.0 * (fp - 2.0 * fret + fptt) * vnl_math::sqr(fp - fret - del) - del * vnl_math::sqr(fp - fptt); if (t < 0.0) { f1d.init(p, xit); @@ -165,7 +167,9 @@ vnl_powell::minimize(vnl_vector & p) double xx = 1.0; double bx; { - double fa, fxx, fb; + double fa; + double fxx; + double fb; vnl_bracket_minimum(f1d, ax, xx, bx, fa, fxx, fb); } brent.set_x_tolerance(linmin_xtol_); diff --git a/core/vnl/algo/vnl_powell.h b/core/vnl/algo/vnl_powell.h index 872d46ecf42..0fe0fca99a8 100644 --- a/core/vnl/algo/vnl_powell.h +++ b/core/vnl/algo/vnl_powell.h @@ -23,34 +23,48 @@ // Implemented from scratch from NR. class VNL_ALGO_EXPORT vnl_powell : public vnl_nonlinear_minimizer { - public: - +public: //: Initialize a powell with the given cost function - vnl_powell(vnl_cost_function* functor) - : functor_(functor), linmin_xtol_(1e-4), initial_step_(1.0) {} + vnl_powell(vnl_cost_function * functor) + : functor_(functor) + + {} //: Run minimization, place result in x. - ReturnCodes minimize(vnl_vector& x); + ReturnCodes + minimize(vnl_vector & x); //: Set tolerance on line search parameter step // Default value is 0.0001 - void set_linmin_xtol(double tol) { linmin_xtol_ = tol; } + void + set_linmin_xtol(double tol) + { + linmin_xtol_ = tol; + } //: Set initial step when bracketing minima along a line // Default value is 1.0 - void set_initial_step(double step) { initial_step_ = step; } + void + set_initial_step(double step) + { + initial_step_ = step; + } - protected: - vnl_cost_function* functor_; +protected: + vnl_cost_function * functor_; friend class vnl_powell_1dfun; - void pub_report_eval(double e) { report_eval(e); } + void + pub_report_eval(double e) + { + report_eval(e); + } //: Tolerance on line search parameter step - double linmin_xtol_; + double linmin_xtol_{ 1e-4 }; //: Initial step when bracketing minima along a line - double initial_step_; + double initial_step_{ 1.0 }; }; #endif // vnl_powell_h_ diff --git a/core/vnl/algo/vnl_qr.h b/core/vnl/algo/vnl_qr.h index 9d0a98a3f20..307deb522b5 100644 --- a/core/vnl/algo/vnl_qr.h +++ b/core/vnl/algo/vnl_qr.h @@ -36,57 +36,77 @@ template class vnl_qr { - public: - vnl_qr(vnl_matrix const & M); - ~vnl_qr(); +public: + vnl_qr(const vnl_matrix & M); + ~vnl_qr(); //: return the inverse matrix of M - vnl_matrix inverse () const; + vnl_matrix + inverse() const; //: return the transpose of the inverse matrix of M - vnl_matrix tinverse () const; + vnl_matrix + tinverse() const; //: return the original matrix M - vnl_matrix recompose () const; + vnl_matrix + recompose() const; //: Solve equation M x = rhs for x using the computed decomposition. - vnl_matrix solve (const vnl_matrix& rhs) const; + vnl_matrix + solve(const vnl_matrix & rhs) const; //: Solve equation M x = rhs for x using the computed decomposition. - vnl_vector solve (const vnl_vector& rhs) const; + vnl_vector + solve(const vnl_vector & rhs) const; //: Return the determinant of M. This is computed from M = Q R as follows: // |M| = |Q| |R|. // |R| is the product of the diagonal elements. // |Q| is (-1)^n as it is a product of Householder reflections. // So det = -prod(-r_ii). - T determinant() const; + T + determinant() const; //: Unpack and return unitary part Q. - vnl_matrix const& Q() const; + const vnl_matrix & + Q() const; //: Unpack and return R. - vnl_matrix const& R() const; + const vnl_matrix & + R() const; //: Return residual vector d of M x = b -> d = Q'b - vnl_vector QtB(const vnl_vector& b) const; + vnl_vector + QtB(const vnl_vector & b) const; - void extract_q_and_r(vnl_matrix* q, vnl_matrix* r) const { *q = Q(); *r = R(); } + void + extract_q_and_r(vnl_matrix * q, vnl_matrix * r) const + { + *q = Q(); + *r = R(); + } - private: +private: vnl_matrix qrdc_out_; vnl_vector qraux_; vnl_vector jpvt_; - mutable vnl_matrix* Q_; - mutable vnl_matrix* R_; + mutable vnl_matrix * Q_; + mutable vnl_matrix * R_; // Disallow assignment. - vnl_qr(const vnl_qr &) { } - vnl_qr& operator=(const vnl_qr &) { return *this; } + vnl_qr(const vnl_qr &) {} + vnl_qr & + operator=(const vnl_qr &) + { + return *this; + } }; //: Compute determinant of matrix "M" using QR. template -inline T vnl_qr_determinant(vnl_matrix const& m) +inline T +vnl_qr_determinant(const vnl_matrix & m) { return vnl_qr(m).determinant(); } template -std::ostream& operator<<(std::ostream&, vnl_qr const & qr); +std::ostream & +operator<<(std::ostream &, const vnl_qr & qr); #endif // vnl_qr_h_ diff --git a/core/vnl/algo/vnl_qr.hxx b/core/vnl/algo/vnl_qr.hxx index 18f6310430d..7d7ff7ceac7 100644 --- a/core/vnl/algo/vnl_qr.hxx +++ b/core/vnl/algo/vnl_qr.hxx @@ -14,48 +14,48 @@ # include #endif #include -#include // vnl_math::squared_magnitude() +#include // vnl_math::squared_magnitude() #include #include #include // dqrdc_(), dqrsl_() // use C++ overloading to call the right linpack routine from the template code: #ifndef DOXYGEN_SHOULD_SKIP_THIS -#define macro(p, T) \ -inline void vnl_linpack_qrdc(vnl_netlib_qrdc_proto(T)) \ -{ v3p_netlib_##p##qrdc_(vnl_netlib_qrdc_params); } \ -inline void vnl_linpack_qrsl(vnl_netlib_qrsl_proto(T)) \ -{ v3p_netlib_##p##qrsl_(vnl_netlib_qrsl_params); } +# define macro(p, T) \ + inline void vnl_linpack_qrdc(vnl_netlib_qrdc_proto(T)) { v3p_netlib_##p##qrdc_(vnl_netlib_qrdc_params); } \ + inline void vnl_linpack_qrsl(vnl_netlib_qrsl_proto(T)) { v3p_netlib_##p##qrsl_(vnl_netlib_qrsl_params); } macro(s, float); macro(d, double); macro(c, std::complex); macro(z, std::complex); -#undef macro +# undef macro #endif template -vnl_qr::vnl_qr(vnl_matrix const& M): - qrdc_out_(M.columns(), M.rows()), - qraux_(M.columns()), - jpvt_(M.rows()), - Q_(nullptr), - R_(nullptr) +vnl_qr::vnl_qr(vnl_matrix const & M) + : qrdc_out_(M.columns(), M.rows()) + , qraux_(M.columns()) + , jpvt_(M.rows()) + , Q_(nullptr) + , R_(nullptr) { - assert(! M.empty()); + assert(!M.empty()); // Fill transposed O/P matrix - long c = M.columns(); - long r = M.rows(); + const long c = M.columns(); + const long r = M.rows(); for (int i = 0; i < r; ++i) for (int j = 0; j < c; ++j) - qrdc_out_(j,i) = M(i,j); + qrdc_out_(j, i) = M(i, j); - long do_pivot = 0; // Enable[!=0]/disable[==0] pivoting. - jpvt_.fill(0); // Allow all columns to be pivoted if pivoting is enabled. + const long do_pivot = 0; // Enable[!=0]/disable[==0] pivoting. + jpvt_.fill(0); // Allow all columns to be pivoted if pivoting is enabled. vnl_vector work(M.rows()); vnl_linpack_qrdc(qrdc_out_.data_block(), // On output, UT is R, below diag is mangled Q - &r, &r, &c, + &r, + &r, + &c, qraux_.data_block(), // Further information required to demangle Q jpvt_.data_block(), work.data_block(), @@ -75,38 +75,42 @@ vnl_qr::~vnl_qr() // |Q| is (-1)^n as it is a product of Householder reflections. // So det = -prod(-r_ii). template -T vnl_qr::determinant() const +T +vnl_qr::determinant() const { - int m = std::min((int)qrdc_out_.columns(), (int)qrdc_out_.rows()); - T det = qrdc_out_(0,0); + const int m = std::min((int)qrdc_out_.columns(), (int)qrdc_out_.rows()); + T det = qrdc_out_(0, 0); for (int i = 1; i < m; ++i) - det *= -qrdc_out_(i,i); + det *= -qrdc_out_(i, i); return det; } //: Unpack and return unitary part Q. template -vnl_matrix const& vnl_qr::Q() const +const vnl_matrix & +vnl_qr::Q() const { - int m = qrdc_out_.columns(); // column-major storage - int n = qrdc_out_.rows(); + const int m = qrdc_out_.columns(); // column-major storage + const int n = qrdc_out_.rows(); - bool verbose = false; + const bool verbose = false; - if (!Q_) { - Q_ = new vnl_matrix(m,m); + if (!Q_) + { + Q_ = new vnl_matrix(m, m); // extract Q. - if (verbose) { + if (verbose) + { std::cerr << __FILE__ ": vnl_qr::Q()\n" - << " m,n = " << m << ", " << n << '\n' - << " qr0 = [" << qrdc_out_ << "];\n" - << " aux = [" << qraux_ << "];\n"; + << " m,n = " << m << ", " << n << '\n' + << " qr0 = [" << qrdc_out_ << "];\n" + << " aux = [" << qraux_ << "];\n"; } Q_->set_identity(); - vnl_matrix& matrQ = *Q_; + vnl_matrix & matrQ = *Q_; vnl_vector v(m, T(0)); vnl_vector w(m, T(0)); @@ -114,36 +118,43 @@ vnl_matrix const& vnl_qr::Q() const // Golub and vanLoan, p199. backward accumulation of householder matrices // Householder vector k is [zeros(1,k-1) qraux_[k] qrdc_out_[k,:]] typedef typename vnl_numeric_traits::abs_t abs_t; - for (int k = n-1; k >= 0; --k) { - if (k >= m) continue; + for (int k = n - 1; k >= 0; --k) + { + if (k >= m) + continue; // Make housevec v, and accumulate norm at the same time. v[k] = qraux_[k]; abs_t sq = vnl_math::squared_magnitude(v[k]); - for (int j = k+1; j < m; ++j) { - v[j] = qrdc_out_(k,j); + for (int j = k + 1; j < m; ++j) + { + v[j] = qrdc_out_(k, j); sq += vnl_math::squared_magnitude(v[j]); } - if (verbose) vnl_matlab_print(std::cerr, v, "v"); + if (verbose) + vnl_matlab_print(std::cerr, v, "v"); #ifndef DOXYGEN_SHOULD_SKIP_THIS -# define c vnl_complex_traits::conjugate +# define c vnl_complex_traits::conjugate #endif // Premultiply emerging Q by house(v), noting that v[0..k-1] == 0. // Q_new = (1 - (2/v'*v) v v')Q // or Q -= (2/v'*v) v (v'Q) - if (sq > abs_t(0)) { - abs_t scale = abs_t(2)/sq; + if (sq > abs_t(0)) + { + const abs_t scale = abs_t(2) / sq; // w = (2/v'*v) v' Q - for (int i = k; i < m; ++i) { + for (int i = k; i < m; ++i) + { w[i] = T(0); for (int j = k; j < m; ++j) w[i] += scale * c(v[j]) * matrQ(j, i); } - if (verbose) vnl_matlab_print(std::cerr, w, "w"); + if (verbose) + vnl_matlab_print(std::cerr, w, "w"); // Q -= v w for (int i = k; i < m; ++i) for (int j = k; j < m; ++j) - matrQ(i,j) -= (v[i]) * (w[j]); + matrQ(i, j) -= (v[i]) * (w[j]); } #undef c } @@ -153,12 +164,14 @@ vnl_matrix const& vnl_qr::Q() const //: Unpack and return R. template -vnl_matrix const& vnl_qr::R() const +const vnl_matrix & +vnl_qr::R() const { - if (!R_) { - int m = qrdc_out_.columns(); // column-major storage - int n = qrdc_out_.rows(); - R_ = new vnl_matrix(m,n); + if (!R_) + { + const int m = qrdc_out_.columns(); // column-major storage + const int n = qrdc_out_.rows(); + R_ = new vnl_matrix(m, n); vnl_matrix & Rmatr = *R_; for (int i = 0; i < m; ++i) @@ -166,14 +179,15 @@ vnl_matrix const& vnl_qr::R() const if (i > j) Rmatr(i, j) = T(0); else - Rmatr(i, j) = qrdc_out_(j,i); + Rmatr(i, j) = qrdc_out_(j, i); } return *R_; } template -vnl_matrix vnl_qr::recompose() const +vnl_matrix +vnl_qr::recompose() const { return Q() * R(); } @@ -186,11 +200,12 @@ vnl_matrix vnl_qr::recompose() const //: Solve equation M x = b for x using the computed decomposition. template -vnl_vector vnl_qr::solve(const vnl_vector& b) const +vnl_vector +vnl_qr::solve(const vnl_vector & b) const { long n = qrdc_out_.columns(); long p = qrdc_out_.rows(); - const T* b_data = b.data_block(); + const T * b_data = b.data_block(); vnl_vector Qt_B(n); vnl_vector x(p); @@ -199,29 +214,33 @@ vnl_vector vnl_qr::solve(const vnl_vector& b) const long info = 0; vnl_linpack_qrsl(qrdc_out_.data_block(), - &n, &n, &p, + &n, + &n, + &p, qraux_.data_block(), - b_data, (T*)nullptr, Qt_B.data_block(), + b_data, + (T *)nullptr, + Qt_B.data_block(), x.data_block(), - (T*)nullptr/*residual*/, - (T*)nullptr/*Ax*/, + (T *)nullptr /*residual*/, + (T *)nullptr /*Ax*/, &JOB, &info); if (info > 0) - std::cerr << __FILE__ ": vnl_qr::solve() : matrix is rank-deficient by " - << info << '\n'; + std::cerr << __FILE__ ": vnl_qr::solve() : matrix is rank-deficient by " << info << '\n'; return x; } //: Return residual vector d of M x = b -> d = Q'b template -vnl_vector vnl_qr::QtB(const vnl_vector& b) const +vnl_vector +vnl_qr::QtB(const vnl_vector & b) const { long n = qrdc_out_.columns(); long p = qrdc_out_.rows(); - const T* b_data = b.data_block(); + const T * b_data = b.data_block(); vnl_vector Qt_B(n); // see comment above @@ -229,83 +248,87 @@ vnl_vector vnl_qr::QtB(const vnl_vector& b) const long info = 0; vnl_linpack_qrsl(qrdc_out_.data_block(), - &n, &n, &p, + &n, + &n, + &p, qraux_.data_block(), b_data, - (T*)nullptr, // A: Qb - Qt_B.data_block(), // B: Q'b - (T*)nullptr, // C: x - (T*)nullptr, // D: residual - (T*)nullptr, // E: Ax + (T *)nullptr, // A: Qb + Qt_B.data_block(), // B: Q'b + (T *)nullptr, // C: x + (T *)nullptr, // D: residual + (T *)nullptr, // E: Ax &JOB, &info); if (info > 0) - std::cerr << __FILE__ ": vnl_qr::QtB() -- matrix is rank-deficient by " - << info << '\n'; + std::cerr << __FILE__ ": vnl_qr::QtB() -- matrix is rank-deficient by " << info << '\n'; return Qt_B; } template -vnl_matrix vnl_qr::inverse() const +vnl_matrix +vnl_qr::inverse() const { - unsigned int r = qrdc_out_.columns(); + const unsigned int r = qrdc_out_.columns(); assert(r > 0 && r == qrdc_out_.rows()); - vnl_matrix inv(r,r); + vnl_matrix inv(r, r); // Use solve() to compute the inverse matrix, using (00..010..00) as rhs - vnl_vector rhs(r,T(0)); - for (unsigned int i=0; i rhs(r, T(0)); + for (unsigned int i = 0; i < r; ++i) { rhs(i) = T(1); - vnl_vector col = this->solve(rhs); // returns i-th column of inverse - inv.set_column(i,col); + const vnl_vector col = this->solve(rhs); // returns i-th column of inverse + inv.set_column(i, col); rhs(i) = T(0); } return inv; } template -vnl_matrix vnl_qr::tinverse() const +vnl_matrix +vnl_qr::tinverse() const { - unsigned int r = qrdc_out_.columns(); + const unsigned int r = qrdc_out_.columns(); assert(r > 0 && r == qrdc_out_.rows()); - vnl_matrix tinv(r,r); + vnl_matrix tinv(r, r); // Use solve() to compute the inverse matrix, using (00..010..00) as rhs - vnl_vector rhs(r,T(0)); - for (unsigned int i=0; i rhs(r, T(0)); + for (unsigned int i = 0; i < r; ++i) { rhs(i) = T(1); - vnl_vector col = this->solve(rhs); // returns i-th column of inverse - tinv.set_row(i,col); + const vnl_vector col = this->solve(rhs); // returns i-th column of inverse + tinv.set_row(i, col); rhs(i) = T(0); } return tinv; } template -vnl_matrix vnl_qr::solve(vnl_matrix const& rhs) const +vnl_matrix +vnl_qr::solve(const vnl_matrix & rhs) const { assert(rhs.rows() == qrdc_out_.columns()); // column-major storage - int c = qrdc_out_.rows(); - int n = rhs.columns(); - vnl_matrix result(c,n); + const int c = qrdc_out_.rows(); + const int n = rhs.columns(); + vnl_matrix result(c, n); - for (int i=0; i b = rhs.get_column(i); - vnl_vector col = this->solve(b); // returns i-th column of result - result.set_column(i,col); + const vnl_vector b = rhs.get_column(i); + const vnl_vector col = this->solve(b); // returns i-th column of result + result.set_column(i, col); } return result; } //------------------------------------------------------------------------------ -#define VNL_QR_INSTANTIATE(T) \ - template class VNL_ALGO_EXPORT vnl_qr; \ - /*template VNL_EXPORT T vnl_qr_determinant(vnl_matrix const&) */ +#define VNL_QR_INSTANTIATE(T) \ + template class VNL_ALGO_EXPORT vnl_qr; \ + /*template VNL_EXPORT T vnl_qr_determinant(vnl_matrix const&) */ #endif diff --git a/core/vnl/algo/vnl_real_eigensystem.cxx b/core/vnl/algo/vnl_real_eigensystem.cxx index 70680ae0f94..5afb82c1278 100644 --- a/core/vnl/algo/vnl_real_eigensystem.cxx +++ b/core/vnl/algo/vnl_real_eigensystem.cxx @@ -15,12 +15,12 @@ //: Extract eigensystem of non-symmetric matrix M, using the EISPACK routine rg. // Should probably switch to using LAPACK's dgeev to avoid transposing. -vnl_real_eigensystem::vnl_real_eigensystem(vnl_matrix const & M) +vnl_real_eigensystem::vnl_real_eigensystem(const vnl_matrix & M) : Vreal(M.rows(), M.columns()) , V(M.rows(), M.columns()) , D(M.rows()) { - long n = M.rows(); + const long n = M.rows(); assert(n == (int)(M.columns())); vnl_fortran_copy mf(M); @@ -32,7 +32,7 @@ vnl_real_eigensystem::vnl_real_eigensystem(vnl_matrix const & M) vnl_matrix devout(n, n); long ierr = 0; - long matz = 1; + const long matz = 1; v3p_netlib_rg_(&n, &n, mf, diff --git a/core/vnl/algo/vnl_real_eigensystem.h b/core/vnl/algo/vnl_real_eigensystem.h index ec9740e50fd..45c3909ba28 100644 --- a/core/vnl/algo/vnl_real_eigensystem.h +++ b/core/vnl/algo/vnl_real_eigensystem.h @@ -28,17 +28,17 @@ class VNL_ALGO_EXPORT vnl_real_eigensystem { - public: - vnl_real_eigensystem(vnl_matrix const& M); +public: + vnl_real_eigensystem(const vnl_matrix & M); - public: +public: vnl_matrix Vreal; //: Output matrix of eigenvectors, which will in general be complex. - vnl_matrix > V; + vnl_matrix> V; //: Output diagonal matrix of eigenvalues. - vnl_diag_matrix > D; + vnl_diag_matrix> D; }; #endif // vnl_real_eigensystem_h_ diff --git a/core/vnl/algo/vnl_rnpoly_solve.cxx b/core/vnl/algo/vnl_rnpoly_solve.cxx index 66af222a3d3..91a206be91c 100644 --- a/core/vnl/algo/vnl_rnpoly_solve.cxx +++ b/core/vnl/algo/vnl_rnpoly_solve.cxx @@ -35,40 +35,45 @@ class vnl_rnpoly_solve_cmplx return { -R, -C }; } inline vnl_rnpoly_solve_cmplx - operator+(vnl_rnpoly_solve_cmplx const & Y) const + operator+(const vnl_rnpoly_solve_cmplx & Y) const { return { R + Y.R, C + Y.C }; } inline vnl_rnpoly_solve_cmplx - operator-(vnl_rnpoly_solve_cmplx const & Y) const + operator-(const vnl_rnpoly_solve_cmplx & Y) const { return { R - Y.R, C - Y.C }; } inline vnl_rnpoly_solve_cmplx & - operator+=(vnl_rnpoly_solve_cmplx const & Y) + operator+=(const vnl_rnpoly_solve_cmplx & Y) { R += Y.R; C += Y.C; return *this; } inline vnl_rnpoly_solve_cmplx & - operator-=(vnl_rnpoly_solve_cmplx const & Y) + operator-=(const vnl_rnpoly_solve_cmplx & Y) { R -= Y.R; C -= Y.C; return *this; } - inline vnl_rnpoly_solve_cmplx operator*(vnl_rnpoly_solve_cmplx const & Y) const + inline vnl_rnpoly_solve_cmplx + operator*(const vnl_rnpoly_solve_cmplx & Y) const { return { R * Y.R - C * Y.C, R * Y.C + C * Y.R }; } inline vnl_rnpoly_solve_cmplx - operator/(vnl_rnpoly_solve_cmplx const & Y) const + operator/(const vnl_rnpoly_solve_cmplx & Y) const { - double N = 1.0 / Y.norm(); + const double N = 1.0 / Y.norm(); return { (R * Y.R + C * Y.C) * N, (C * Y.R - R * Y.C) * N }; } - inline vnl_rnpoly_solve_cmplx operator*(double T) const { return { R * T, C * T }; } + inline vnl_rnpoly_solve_cmplx + operator*(double T) const + { + return { R * T, C * T }; + } inline vnl_rnpoly_solve_cmplx & operator*=(double T) { @@ -77,15 +82,15 @@ class vnl_rnpoly_solve_cmplx return *this; } inline vnl_rnpoly_solve_cmplx & - operator*=(vnl_rnpoly_solve_cmplx const & Y) + operator*=(const vnl_rnpoly_solve_cmplx & Y) { - double r = R * Y.R - C * Y.C; + const double r = R * Y.R - C * Y.C; C = R * Y.C + C * Y.R; R = r; return *this; } inline vnl_rnpoly_solve_cmplx & - operator/=(vnl_rnpoly_solve_cmplx const & Y) + operator/=(const vnl_rnpoly_solve_cmplx & Y) { return *this = operator/(Y); } @@ -104,7 +109,8 @@ vnl_rnpoly_solve::realroots(double tol) { tol *= tol; // squared tolerance std::vector *> rr; - auto rp = r_.begin(), ip = i_.begin(); + auto rp = r_.begin(); + auto ip = i_.begin(); for (; rp != r_.end() && ip != i_.end(); ++rp, ++ip) if ((*ip)->squared_magnitude() < tol) rr.push_back(*rp); @@ -121,7 +127,8 @@ vnl_rnpoly_solve::realroots(double tol) static void inptbr(std::vector & p, std::vector & q) { - vnl_rnpoly_solve_cmplx pp[10], qq[10]; + vnl_rnpoly_solve_cmplx pp[10]; + vnl_rnpoly_solve_cmplx qq[10]; pp[0] = vnl_rnpoly_solve_cmplx(.12324754231, .76253746298); pp[1] = vnl_rnpoly_solve_cmplx(.93857838950, -.99375892810); @@ -149,7 +156,7 @@ inptbr(std::vector & p, std::vector & p, std::vector 0) @@ -172,9 +179,9 @@ powr(int n, vnl_rnpoly_solve_cmplx const & y) static void -initr(std::vector const & ideg, - std::vector const & p, - std::vector const & q, +initr(const std::vector & ideg, + const std::vector & p, + const std::vector & q, std::vector & r, std::vector & pdg, std::vector & qdg) @@ -207,10 +214,10 @@ degree(int index) //: Evaluate the target system component of h. // This is the system of equations that we are trying to find the roots. static void -ffunr(std::vector const & coeff, - std::vector const & polyn, - std::vector const & terms, - std::vector const & x, +ffunr(const std::vector & coeff, + const std::vector & polyn, + const std::vector & terms, + const std::vector & x, std::vector & pows, std::vector & f, std::vector & df) @@ -241,7 +248,7 @@ ffunr(std::vector const & coeff, vnl_rnpoly_solve_cmplx tmp(1, 0); for (unsigned int k = 0; k < dim_; ++k) // For each variable { - int index = polyn[i * dim_ * max_nterms_ + j * dim_ + k]; + const int index = polyn[i * dim_ * max_nterms_ + j * dim_ + k]; if (index >= 0) tmp *= pows[index]; } @@ -259,12 +266,12 @@ ffunr(std::vector const & coeff, vnl_rnpoly_solve_cmplx tmp = vnl_rnpoly_solve_cmplx(1, 0); for (int k = dim_ - 1; k >= 0; k--) // Over each variable in each term { - int index = polyn[i * dim_ * max_nterms_ + j * dim_ + k]; + const int index = polyn[i * dim_ * max_nterms_ + j * dim_ + k]; if (index >= 0) { if (k == l) { - int deg = degree(index); + const int deg = degree(index); if (deg > 1) tmp *= pows[index - 1]; tmp *= (double)deg; @@ -284,17 +291,18 @@ ffunr(std::vector const & coeff, // Evaluate the starting system component of h from a system // of equations that we already know the roots. (ex: x^n - 1) static void -gfunr(std::vector const & ideg, - std::vector const & pdg, - std::vector const & qdg, - std::vector const & pows, +gfunr(const std::vector & ideg, + const std::vector & pdg, + const std::vector & qdg, + const std::vector & pows, std::vector & g, std::vector & dg) { assert(ideg.size() == dim_); assert(g.size() == dim_); assert(dg.size() == dim_); - std::vector pxdgm1(dim_), pxdg(dim_); + std::vector pxdgm1(dim_); + std::vector pxdg(dim_); for (unsigned int j = 0; j < dim_; ++j) { @@ -309,7 +317,7 @@ gfunr(std::vector const & ideg, for (unsigned int j = 0; j < dim_; ++j) { - int index = j * max_deg_ + ideg[j] - 1; + const int index = j * max_deg_ + ideg[j] - 1; pxdg[j] = pdg[j] * pows[index]; } @@ -325,17 +333,17 @@ gfunr(std::vector const & ideg, //: This is the routine that traces the curve from the gfunr to the f function // (i.e. Evaluate the continuation function) static void -hfunr(std::vector const & ideg, - std::vector const & pdg, - std::vector const & qdg, +hfunr(const std::vector & ideg, + const std::vector & pdg, + const std::vector & qdg, double t, - std::vector const & x, + const std::vector & x, std::vector & h, std::vector & dhx, std::vector & dht, - std::vector const & polyn, - std::vector const & coeff, - std::vector const & terms) + const std::vector & polyn, + const std::vector & coeff, + const std::vector & terms) { assert(ideg.size() == dim_); assert(terms.size() == dim_); @@ -343,7 +351,10 @@ hfunr(std::vector const & ideg, assert(h.size() == dim_); assert(dht.size() == dim_); assert(dhx.size() == dim_ * dim_); - std::vector df(dim_ * dim_), dg(dim_), f(dim_), g(dim_); + std::vector df(dim_ * dim_); + std::vector dg(dim_); + std::vector f(dim_); + std::vector g(dim_); std::vector pows; // powers of variables [dim_ equations] [max_deg_ possible powers] ffunr(coeff, polyn, terms, x, pows, f, df); @@ -353,7 +364,7 @@ hfunr(std::vector const & ideg, assert(dg.size() == dim_); assert(df.size() == dim_ * dim_); - double onemt = 1.0 - t; + const double onemt = 1.0 - t; for (unsigned int j = 0; j < dim_; ++j) { for (unsigned int i = 0; i < dim_; ++i) @@ -379,7 +390,7 @@ ludcmp(std::vector & a, std::vector & indx) double big = 0.0; for (unsigned int j = 0; j < dim_; ++j) { - double temp = a[i * dim_ + j].norm(); + const double temp = a[i * dim_ + j].norm(); if (temp > big) big = temp; } @@ -405,7 +416,7 @@ ludcmp(std::vector & a, std::vector & indx) a[i * dim_ + j] -= a[i * dim_ + k] * a[k * dim_ + j]; // Is the figure of merit for the pivot better than the best so far? - double rdum = vv[i] * a[i * dim_ + j].norm(); + const double rdum = vv[i] * a[i * dim_ + j].norm(); if (rdum >= big) { big = rdum; @@ -419,7 +430,7 @@ ludcmp(std::vector & a, std::vector & indx) // Yes, do so... for (unsigned int k = 0; k < dim_; ++k) { - vnl_rnpoly_solve_cmplx dum = a[imax * dim_ + k]; + const vnl_rnpoly_solve_cmplx dum = a[imax * dim_ + k]; a[imax * dim_ + k] = a[j * dim_ + k]; a[j * dim_ + k] = dum; } @@ -436,7 +447,7 @@ ludcmp(std::vector & a, std::vector & indx) // Now, finally, divide by the pivot element if (j + 1 != dim_) { - vnl_rnpoly_solve_cmplx dum = vnl_rnpoly_solve_cmplx(1, 0) / ajj; + const vnl_rnpoly_solve_cmplx dum = vnl_rnpoly_solve_cmplx(1, 0) / ajj; // If the pivot element is zero the matrix is singular. for (unsigned int i = j + 1; i < dim_; ++i) @@ -449,9 +460,9 @@ ludcmp(std::vector & a, std::vector & indx) // ------------------------- LU Back Substitution ------------------------- static void -lubksb(std::vector const & a, - std::vector const & indx, - std::vector const & bb, +lubksb(const std::vector & a, + const std::vector & indx, + const std::vector & bb, std::vector & b) { int ii = -1; @@ -460,7 +471,7 @@ lubksb(std::vector const & a, for (unsigned int i = 0; i < dim_; ++i) { - int ip = indx[i]; + const int ip = indx[i]; vnl_rnpoly_solve_cmplx sum = b[ip]; b[ip] = b[i]; @@ -471,7 +482,7 @@ lubksb(std::vector const & a, // A nonzero element was encountered, so from now on we // will have to do the sums in the loop above if (sum.norm() > 0) - ii = i; + ii = i; b[i] = sum; } @@ -491,7 +502,7 @@ lubksb(std::vector const & a, //: Solve a complex system of equations by using l-u decomposition and then back substitution. static int linnr(std::vector & dhx, - std::vector const & rhs, + const std::vector & rhs, std::vector & resid) { std::vector irow(dim_); @@ -505,7 +516,7 @@ linnr(std::vector & dhx, //----------------------- XNORM -------------------- //: Finds the unit normal of a vector v static double -xnorm(std::vector const & v) +xnorm(const std::vector & v) { assert(v.size() == dim_); double txnorm = 0.0; @@ -517,25 +528,29 @@ xnorm(std::vector const & v) //---------------------- PREDICT --------------------- //: Predict new x vector using Taylor's Expansion. static void -predict(std::vector const & ideg, - std::vector const & pdg, - std::vector const & qdg, +predict(const std::vector & ideg, + const std::vector & pdg, + const std::vector & qdg, double step, double & t, std::vector & x, - std::vector const & polyn, - std::vector const & coeff, - std::vector const & terms) + const std::vector & polyn, + const std::vector & coeff, + const std::vector & terms) { assert(ideg.size() == dim_); assert(terms.size() == dim_); assert(x.size() == dim_); - double maxdt = .2; // Maximum change in t for a given step. If dt is - // too large, there seems to be greater chance of - // jumping to another path. Set this to 1 if you - // don't care. - std::vector dht(dim_), dhx(dim_ * dim_), dz(dim_), h(dim_), rhs(dim_); + const double maxdt = .2; // Maximum change in t for a given step. If dt is + // too large, there seems to be greater chance of + // jumping to another path. Set this to 1 if you + // don't care. + std::vector dht(dim_); + std::vector dhx(dim_ * dim_); + std::vector dz(dim_); + std::vector h(dim_); + std::vector rhs(dim_); // Call the continuation function that we are tracing hfunr(ideg, pdg, qdg, t, x, h, dhx, dht, polyn, coeff, terms); @@ -578,19 +593,22 @@ predict(std::vector const & ideg, // 2: Didn't converge in 'loop' iterations // 3: If the magnitude of x > maxroot static int -correct(std::vector const & ideg, +correct(const std::vector & ideg, int loop, double eps, - std::vector const & pdg, - std::vector const & qdg, + const std::vector & pdg, + const std::vector & qdg, double t, std::vector & x, - std::vector const & polyn, - std::vector const & coeff, - std::vector const & terms) + const std::vector & polyn, + const std::vector & coeff, + const std::vector & terms) { - double maxroot = 1000; // Maximum size of root where it is considered heading to infinity - std::vector dhx(dim_ * dim_), dht(dim_), h(dim_), resid(dim_); + const double maxroot = 1000; // Maximum size of root where it is considered heading to infinity + std::vector dhx(dim_ * dim_); + std::vector dht(dim_); + std::vector h(dim_); + std::vector resid(dim_); assert(ideg.size() == dim_); assert(terms.size() == dim_); @@ -607,7 +625,7 @@ correct(std::vector const & ideg, for (unsigned int j = 0; j < dim_; ++j) x[j] -= resid[j]; - double xresid = xnorm(resid); + const double xresid = xnorm(resid); if (xresid < eps) return 0; if (xresid > maxroot) @@ -630,27 +648,27 @@ correct(std::vector const & ideg, // 4: Singular Jacobian on Path static int trace(std::vector & x, - std::vector const & ideg, - std::vector const & pdg, - std::vector const & qdg, - std::vector const & polyn, - std::vector const & coeff, - std::vector const & terms) + const std::vector & ideg, + const std::vector & pdg, + const std::vector & qdg, + const std::vector & polyn, + const std::vector & coeff, + const std::vector & terms) { assert(ideg.size() == dim_); assert(terms.size() == dim_); assert(x.size() == dim_); - int maxns = 500; // Maximum number of path steps - int maxit = 5; // Maximum number of iterations to correct a step. - // For each step, Newton-Raphson is used to correct - // the step. This should be at least 3 to improve - // the chances of convergence. If function is well - // behaved, fewer than maxit steps will be needed + const int maxns = 500; // Maximum number of path steps + const int maxit = 5; // Maximum number of iterations to correct a step. + // For each step, Newton-Raphson is used to correct + // the step. This should be at least 3 to improve + // the chances of convergence. If function is well + // behaved, fewer than maxit steps will be needed double eps = 0; // epsilon value used in correct - double epsilonS = 1.0e-3 * epsilonB; // smallest path step for t>.95 - double stepmin = 1.0e-5 * stepinit; // Minimum stepsize allowed + const double epsilonS = 1.0e-3 * epsilonB; // smallest path step for t>.95 + const double stepmin = 1.0e-5 * stepinit; // Minimum stepsize allowed double step = stepinit; // stepsize double t = 0.0; // Continuation parameter 0 & x, #ifdef DEBUG std::cout << "path converged\n" << std::flush; #endif - double factor = (1.0 - oldt) / (t - oldt); + double const factor = (1.0 - oldt) / (t - oldt); for (unsigned int j = 0; j < dim_; ++j) x[j] = oldx[j] + (x[j] - oldx[j]) * factor; t = 1.0; - int cflag = correct(ideg, 10 * maxit, final_eps, pdg, qdg, t, x, polyn, coeff, terms); + const int cflag = correct(ideg, 10 * maxit, final_eps, pdg, qdg, t, x, polyn, coeff, terms); if ((cflag == 0) || (cflag == 2)) return 1; // Final Correction converged else if (cflag == 3) @@ -695,7 +713,7 @@ trace(std::vector & x, } // Newton's method brings us back to the curve - int cflag = correct(ideg, maxit, eps, pdg, qdg, t, x, polyn, coeff, terms); + const int cflag = correct(ideg, maxit, eps, pdg, qdg, t, x, polyn, coeff, terms); if (cflag == 0) { // Successful step @@ -733,8 +751,8 @@ trace(std::vector & x, // The new point to start tracing is stored in the x array. static void strptr(std::vector & icount, - std::vector const & ideg, - std::vector const & r, + const std::vector & ideg, + const std::vector & r, std::vector & x) { assert(ideg.size() == dim_); @@ -752,22 +770,27 @@ strptr(std::vector & icount, for (unsigned int j = 0; j < dim_; ++j) { - double angle = twopi / ideg[j] * icount[j]; + const double angle = twopi / ideg[j] * icount[j]; x[j] = r[j] * vnl_rnpoly_solve_cmplx(std::cos(angle), std::sin(angle)); } } static std::vector> -Perform_Distributed_Task(std::vector const & ideg, - std::vector const & terms, - std::vector const & polyn, - std::vector const & coeff) +Perform_Distributed_Task(const std::vector & ideg, + const std::vector & terms, + const std::vector & polyn, + const std::vector & coeff) { assert(ideg.size() == dim_); std::vector> sols; - std::vector pdg, qdg, p, q, r, x; + std::vector pdg; + std::vector qdg; + std::vector p; + std::vector q; + std::vector r; + std::vector x; std::vector icount(dim_, 1); icount[0] = 0; bool solflag; // flag used to remember if a root is found @@ -863,7 +886,7 @@ vnl_rnpoly_solve::Read_Input(std::vector & ideg, coeff[i * max_nterms_ + k] = ps_[i]->coeffs_(k); for (unsigned int j = 0; j < dim_; j++) { - int deg = ps_[i]->polyn_(k, j); + const int deg = ps_[i]->polyn_(k, j); polyn[i * dim_ * max_nterms_ + k * dim_ + j] = deg ? int(j * max_deg_) + deg - 1 : -1; } } @@ -888,7 +911,8 @@ vnl_rnpoly_solve::~vnl_rnpoly_solve() bool vnl_rnpoly_solve::compute() { - std::vector ideg, terms; + std::vector ideg; + std::vector terms; std::vector polyn; std::vector coeff; diff --git a/core/vnl/algo/vnl_rnpoly_solve.h b/core/vnl/algo/vnl_rnpoly_solve.h index bf49a026199..97ec4c26d96 100644 --- a/core/vnl/algo/vnl_rnpoly_solve.h +++ b/core/vnl/algo/vnl_rnpoly_solve.h @@ -34,45 +34,58 @@ class VNL_ALGO_EXPORT vnl_rnpoly_solve { // Data Members-------------------------------------------------------------- - std::vector ps_; // the input - std::vector*> r_; // the output (real part) - std::vector*> i_; // the output (imaginary part) - - public: + std::vector ps_; // the input + std::vector *> r_; // the output (real part) + std::vector *> i_; // the output (imaginary part) +public: // Constructor--------------------------------------------------------------- //: The constructor already does all the calculations - inline vnl_rnpoly_solve(std::vector ps) - : ps_(std::move(ps)) { compute(); } + inline vnl_rnpoly_solve(std::vector ps) + : ps_(std::move(ps)) + { + compute(); + } // Destructor---------------------------------------------------------------- - ~vnl_rnpoly_solve(); + ~vnl_rnpoly_solve(); // Operations---------------------------------------------------------------- //: Array of real parts of roots - inline std::vector*> real() { return r_; } + inline std::vector *> + real() + { + return r_; + } //: Array of imaginary parts of roots - inline std::vector*> imag() { return i_; } + inline std::vector *> + imag() + { + return i_; + } //: Return real roots only. // Roots are real if the absolute value of their imaginary part is less than // the optional argument tol, which defaults to 1e-12 [untested] - std::vector*> realroots(double tol = 1e-12); + std::vector *> + realroots(double tol = 1e-12); // Computations-------------------------------------------------------------- - private: +private: //: Compute roots using continuation algorithm. - bool compute(); - - void Read_Input(std::vector& ideg, - std::vector& terms, - std::vector& polyn, - std::vector& coeff); + bool + compute(); + + void + Read_Input(std::vector & ideg, + std::vector & terms, + std::vector & polyn, + std::vector & coeff); }; #endif // vnl_rnpoly_solve_h_ diff --git a/core/vnl/algo/vnl_rpoly_roots.h b/core/vnl/algo/vnl_rpoly_roots.h index f1d02e2155b..d21a5182fd6 100644 --- a/core/vnl/algo/vnl_rpoly_roots.h +++ b/core/vnl/algo/vnl_rpoly_roots.h @@ -36,8 +36,8 @@ class vnl_real_polynomial; class VNL_ALGO_EXPORT vnl_rpoly_roots { - public: -// Constructors/Destructors-------------------------------------------------- +public: + // Constructors/Destructors-------------------------------------------------- //: The constructor calculates the roots. // This is the most efficient interface @@ -47,48 +47,73 @@ class VNL_ALGO_EXPORT vnl_rpoly_roots // Note that if the routine fails, not all roots will be found. In this case, // the "realroots" and "roots" functions will return fewer than n roots. - vnl_rpoly_roots(const vnl_vector& a); + vnl_rpoly_roots(const vnl_vector & a); //: Calculate roots of a vnl_real_polynomial. Same comments apply. - vnl_rpoly_roots(const vnl_real_polynomial& poly); + vnl_rpoly_roots(const vnl_real_polynomial & poly); // Operations---------------------------------------------------------------- //: Return i'th complex root - std::complex operator [] (int i) const { return {r_[i], i_[i]}; } + std::complex + operator[](int i) const + { + return { r_[i], i_[i] }; + } //: Complex vector of all roots. - vnl_vector > roots() const; + vnl_vector> + roots() const; //: Real part of root I. - const double& real(int i) const { return r_[i]; } + const double & + real(int i) const + { + return r_[i]; + } //: Imaginary part of root I. - const double& imag(int i) const { return i_[i]; } + const double & + imag(int i) const + { + return i_[i]; + } //: Vector of real parts of roots - vnl_vector& real() { return r_; } + vnl_vector & + real() + { + return r_; + } //: Vector of imaginary parts of roots - vnl_vector& imag() { return i_; } + vnl_vector & + imag() + { + return i_; + } //: Return real roots only. // Roots are real if the absolute value of their imaginary part is less than // the optional argument TOL. TOL defaults to 1e-12 [untested] - vnl_vector realroots(double tol = 1e-12) const; + vnl_vector + realroots(double tol = 1e-12) const; // Computations-------------------------------------------------------------- //: Compute roots using Jenkins-Traub algorithm. - bool compute(); + bool + compute(); //: Compute roots using QR decomposition of companion matrix. [unimplemented] - bool compute_qr(); + bool + compute_qr(); //: Compute roots using Laguerre algorithm. [unimplemented] - bool compute_laguerre(); + bool + compute_laguerre(); - protected: +protected: // Data Members-------------------------------------------------------------- vnl_vector coeffs_; diff --git a/core/vnl/algo/vnl_scatter_3x3.h b/core/vnl/algo/vnl_scatter_3x3.h index ecc45edfa76..dd30fb14406 100644 --- a/core/vnl/algo/vnl_scatter_3x3.h +++ b/core/vnl/algo/vnl_scatter_3x3.h @@ -21,53 +21,62 @@ #include template -class vnl_scatter_3x3 : public vnl_matrix_fixed +class vnl_scatter_3x3 : public vnl_matrix_fixed { - public: - typedef vnl_matrix_fixed base; - typedef vnl_vector_fixed vect; +public: + typedef vnl_matrix_fixed base; + typedef vnl_vector_fixed vect; //: Constructor. Fills with zeros. vnl_scatter_3x3(); //: Add v*v' to scatter. - void add_outer_product(const vnl_vector_fixed & v); + void + add_outer_product(const vnl_vector_fixed & v); //: Add v*u' to scatter. - void add_outer_product(const vnl_vector_fixed & u, - const vnl_vector_fixed & v); + void + add_outer_product(const vnl_vector_fixed & u, const vnl_vector_fixed & v); //: Subtract v*v' from scatter. - void sub_outer_product(const vnl_vector_fixed & v); + void + sub_outer_product(const vnl_vector_fixed & v); //: Subtract v*u' from scatter. - void sub_outer_product(const vnl_vector_fixed & u, - const vnl_vector_fixed & v); + void + sub_outer_product(const vnl_vector_fixed & u, const vnl_vector_fixed & v); //: Replace S with $(S+S^\top)/2$. - void force_symmetric(); + void + force_symmetric(); //: Compute the eigensystem of S. - void compute_eigensystem(); + void + compute_eigensystem(); //: Return the eigenvector corresponding to the smallest eigenvalue. - vnl_vector_fixed minimum_eigenvector() { - if (!eigenvectors_currentp) compute_eigensystem(); - return vnl_vector_fixed(V_(0,0), V_(1,0), V_(2,0)); + vnl_vector_fixed + minimum_eigenvector() + { + if (!eigenvectors_currentp) + compute_eigensystem(); + return vnl_vector_fixed(V_(0, 0), V_(1, 0), V_(2, 0)); } //: Return the column matrix of eigenvectors, sorted in increasing order of eigenvalue. - vnl_matrix_fixed& V() + vnl_matrix_fixed & + V() { - if (!eigenvectors_currentp) compute_eigensystem(); + if (!eigenvectors_currentp) + compute_eigensystem(); return V_; } - protected: - bool symmetricp; - bool eigenvectors_currentp; - vnl_matrix_fixed V_; - vnl_vector_fixed D; +protected: + bool symmetricp{ true }; + bool eigenvectors_currentp{ false }; + vnl_matrix_fixed V_; + vnl_vector_fixed D; }; diff --git a/core/vnl/algo/vnl_scatter_3x3.hxx b/core/vnl/algo/vnl_scatter_3x3.hxx index efcce3ff6c5..626ed8f2c19 100644 --- a/core/vnl/algo/vnl_scatter_3x3.hxx +++ b/core/vnl/algo/vnl_scatter_3x3.hxx @@ -17,84 +17,93 @@ template vnl_scatter_3x3::vnl_scatter_3x3() : base(T(0)) - , symmetricp(true) - , eigenvectors_currentp(false) -{ -} + +{} template -void vnl_scatter_3x3::add_outer_product(const vnl_vector_fixed & v) +void +vnl_scatter_3x3::add_outer_product(const vnl_vector_fixed & v) { vnl_scatter_3x3 & S = *this; - for (int i = 0; i < 3; ++i) { - S(i,i) += v[i]*v[i]; - for (int j = i+1; j < 3; ++j) { - T value = v[i]*v[j]; - S(i,j) += value; - S(j,i) = S(i,j); + for (int i = 0; i < 3; ++i) + { + S(i, i) += v[i] * v[i]; + for (int j = i + 1; j < 3; ++j) + { + T value = v[i] * v[j]; + S(i, j) += value; + S(j, i) = S(i, j); } } } template -void vnl_scatter_3x3::add_outer_product(const vnl_vector_fixed & u, - const vnl_vector_fixed & v) +void +vnl_scatter_3x3::add_outer_product(const vnl_vector_fixed & u, const vnl_vector_fixed & v) { vnl_scatter_3x3 & S = *this; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) - S(i,j) += v[i]*u[j]; + S(i, j) += v[i] * u[j]; symmetricp = false; // conservative assumption -- use add_outer_product(v) to maintain symmetry } template -void vnl_scatter_3x3::sub_outer_product(const vnl_vector_fixed & v) +void +vnl_scatter_3x3::sub_outer_product(const vnl_vector_fixed & v) { vnl_scatter_3x3 & S = *this; - for (int i = 0; i < 3; ++i) { - S(i,i) -= v[i]*v[i]; - for (int j = i+1; j < 3; ++j) { - T value = v[i]*v[j]; - S(i,j) -= value; - S(j,i) = S(i,j); + for (int i = 0; i < 3; ++i) + { + S(i, i) -= v[i] * v[i]; + for (int j = i + 1; j < 3; ++j) + { + T value = v[i] * v[j]; + S(i, j) -= value; + S(j, i) = S(i, j); } } } template -void vnl_scatter_3x3::sub_outer_product(const vnl_vector_fixed & u, - const vnl_vector_fixed & v) +void +vnl_scatter_3x3::sub_outer_product(const vnl_vector_fixed & u, const vnl_vector_fixed & v) { vnl_scatter_3x3 & S = *this; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) - S(i,j) -= v[i]*u[j]; + S(i, j) -= v[i] * u[j]; symmetricp = false; // conservative assumption -- use sub_outer_product(v) to maintain symmetry } template -void vnl_scatter_3x3::force_symmetric() +void +vnl_scatter_3x3::force_symmetric() { if (symmetricp) return; vnl_scatter_3x3 & S = *this; for (int i = 0; i < 3; ++i) - for (int j = i+1; j < 3; ++j) { - T vbar = (S(i,j) + S(j,i)) / 2; - S(i,j) = S(j,i) = vbar; + for (int j = i + 1; j < 3; ++j) + { + T vbar = (S(i, j) + S(j, i)) / 2; + S(i, j) = S(j, i) = vbar; } symmetricp = true; } template -void vnl_scatter_3x3::compute_eigensystem() +void +vnl_scatter_3x3::compute_eigensystem() { - vnl_scatter_3x3 &S = *this; - vnl_matrix M = S.as_matrix(); - if (symmetricp) { + const vnl_scatter_3x3 & S = *this; + const vnl_matrix M = S.as_matrix(); + if (symmetricp) + { vnl_symmetric_eigensystem_compute(M, V_.as_ref().non_const(), D.as_ref().non_const()); } - else { + else + { std::cerr << "Asymmetric scatter not handled now\n"; } @@ -103,7 +112,6 @@ void vnl_scatter_3x3::compute_eigensystem() //-------------------------------------------------------------------------------- -#define VNL_SCATTER_3X3_INSTANTIATE(T) \ -template class VNL_ALGO_EXPORT vnl_scatter_3x3 +#define VNL_SCATTER_3X3_INSTANTIATE(T) template class VNL_ALGO_EXPORT vnl_scatter_3x3 #endif // vnl_scatter_3x3_hxx_ diff --git a/core/vnl/algo/vnl_simpson_integral.h b/core/vnl/algo/vnl_simpson_integral.h index cfce914bf72..8af81e1aab7 100644 --- a/core/vnl/algo/vnl_simpson_integral.h +++ b/core/vnl/algo/vnl_simpson_integral.h @@ -10,18 +10,19 @@ class VNL_ALGO_EXPORT vnl_simpson_integral : public vnl_definite_integral { - private: +private: //: used to extract integrand functions of the vnl_integrant_fnct. - static double int_fnct_(double* x); - - public: + static double + int_fnct_(double * x); +public: vnl_simpson_integral() = default; //: a and b are integral limits respectively. // n is the number of intervals used in integral. // The actual subinterval used is 2* num_intervals_ - double integral(vnl_integrant_fnct *f, double a, double b, long n); + double + integral(vnl_integrant_fnct * f, double a, double b, long n); }; #endif diff --git a/core/vnl/algo/vnl_solve_qp.cxx b/core/vnl/algo/vnl_solve_qp.cxx index 8800e6de93d..4c45bc270e5 100644 --- a/core/vnl/algo/vnl_solve_qp.cxx +++ b/core/vnl/algo/vnl_solve_qp.cxx @@ -14,12 +14,12 @@ static void vnl_solve_symmetric_le(const vnl_matrix & S, const vnl_vector & b, vnl_vector & x) { - vnl_cholesky chol(S, vnl_cholesky::estimate_condition); + const vnl_cholesky chol(S, vnl_cholesky::estimate_condition); if (chol.rcond() > 1e-8) x = chol.solve(b); else { - vnl_svd svd(S); + const vnl_svd svd(S); x = svd.solve(b); } } @@ -37,19 +37,19 @@ vnl_solve_qp_with_equality_constraints(const vnl_matrix & H, { // Test inputs // unsigned n=H.rows(); // Number of unknowns - unsigned nc = A.rows(); // Number of equality constraints + const unsigned nc = A.rows(); // Number of equality constraints assert(H.cols() == H.rows()); assert(g.size() == H.rows()); assert(A.cols() == H.rows()); assert(b.size() == nc); vnl_matrix H_inv; - vnl_cholesky Hchol(H, vnl_cholesky::estimate_condition); + const vnl_cholesky Hchol(H, vnl_cholesky::estimate_condition); if (Hchol.rcond() > 1e-8) H_inv = Hchol.inverse(); else { - vnl_svd Hsvd(H); + const vnl_svd Hsvd(H); H_inv = Hsvd.inverse(); } @@ -60,11 +60,11 @@ vnl_solve_qp_with_equality_constraints(const vnl_matrix & H, return true; } - vnl_vector b1 = (b + A * H_inv * g) * -1.0; + const vnl_vector b1 = (b + A * H_inv * g) * -1.0; // Solve for lagrange multipliers, lambda vnl_vector lambda; // Lagrange multipliers - vnl_matrix AHA = A * H_inv * A.transpose(); + const vnl_matrix AHA = A * H_inv * A.transpose(); vnl_solve_symmetric_le(AHA, b1, lambda); x = (H_inv * (g + A.transpose() * lambda)) * -1.0; @@ -85,19 +85,19 @@ vnl_solve_qp_zero_sum(const vnl_matrix & H, const vnl_vector & g assert(g.size() == H.rows()); vnl_matrix H_inv; - vnl_cholesky Hchol(H, vnl_cholesky::estimate_condition); + const vnl_cholesky Hchol(H, vnl_cholesky::estimate_condition); if (Hchol.rcond() > 1e-8) H_inv = Hchol.inverse(); else { - vnl_svd Hsvd(H); + const vnl_svd Hsvd(H); H_inv = Hsvd.inverse(); } - double b1 = -1.0 * (H_inv * g).sum(); + const double b1 = -1.0 * (H_inv * g).sum(); // Sum of elements in H_inv (= 1'*H_inv*1) - double H_inv_sum = vnl_c_vector::sum(H_inv.begin(), H_inv.size()); + const double H_inv_sum = vnl_c_vector::sum(H_inv.begin(), H_inv.size()); if (std::fabs(H_inv_sum) < 1e-8) { @@ -107,7 +107,7 @@ vnl_solve_qp_zero_sum(const vnl_matrix & H, const vnl_vector & g } // Solve for lagrange multiplier, lambda - double lambda = b1 / H_inv_sum; + const double lambda = b1 / H_inv_sum; vnl_vector g1(g); g1 += lambda; @@ -126,7 +126,7 @@ vnl_solve_qp_update_x(vnl_vector & x, std::vector & valid, unsigned & n_valid) { - unsigned n = x.size(); + const unsigned n = x.size(); // Check non-negativity constraints int worst_i = -1; double min_alpha = 1.0; @@ -134,7 +134,7 @@ vnl_solve_qp_update_x(vnl_vector & x, { if (dx[i] < 0.0) { - double alpha = -1.0 * x1[i] / dx[i]; + const double alpha = -1.0 * x1[i] / dx[i]; if (alpha < min_alpha) { min_alpha = alpha; @@ -180,8 +180,8 @@ vnl_solve_qp_non_neg_step(const vnl_matrix & H, // H1,A1,g1,x1 contain subsets defined by valid array // ie solve H1.dx+(H1.x+g1)=0 subject to A1.dx=(b-A1.x1) - unsigned n = H.rows(); // Full number of unknowns - unsigned nc = A.rows(); // Number of equality constraints + const unsigned n = H.rows(); // Full number of unknowns + const unsigned nc = A.rows(); // Number of equality constraints vnl_matrix H1(n_valid, n_valid); vnl_matrix A1(nc, n_valid); @@ -249,7 +249,7 @@ vnl_solve_qp_non_neg_sum_one_step(const vnl_matrix & H, // H1,g1,x1 contain subsets defined by valid array // ie solve H1.dx+(H1.x+g1)=0 subject to sum(dx)=0 - unsigned n = H.rows(); // Full number of unknowns + const unsigned n = H.rows(); // Full number of unknowns vnl_matrix H1(n_valid, n_valid); unsigned j1 = 0; @@ -317,7 +317,7 @@ vnl_solve_qp_with_non_neg_constraints(const vnl_matrix & H, bool verbose) { // Test inputs - unsigned n = H.rows(); // Number of unknowns + const unsigned n = H.rows(); // Number of unknowns // unsigned nc=A.rows(); // Number of equality constraints assert(H.cols() == n); assert(g.size() == n); @@ -376,7 +376,7 @@ vnl_solve_qp_non_neg_sum_one(const vnl_matrix & H, bool verbose) { // Test inputs - unsigned n = H.rows(); // Number of unknowns + const unsigned n = H.rows(); // Number of unknowns assert(H.cols() == n); assert(g.size() == n); diff --git a/core/vnl/algo/vnl_solve_qp.h b/core/vnl/algo/vnl_solve_qp.h index bd5be3a50dc..f25b44ffdfb 100644 --- a/core/vnl/algo/vnl_solve_qp.h +++ b/core/vnl/algo/vnl_solve_qp.h @@ -15,20 +15,20 @@ // Minimise F(x)=0.5x'Hx + g'x subject to Ax=b // \param H Hessian of F(x) - must be symmetric // \retval True if successful -bool vnl_solve_qp_with_equality_constraints(const vnl_matrix& H, - const vnl_vector& g, - const vnl_matrix& A, - const vnl_vector& b, - vnl_vector& x); +bool +vnl_solve_qp_with_equality_constraints(const vnl_matrix & H, + const vnl_vector & g, + const vnl_matrix & A, + const vnl_vector & b, + vnl_vector & x); //: Solve quadratic programming problem with constraint sum(x)=0 // Minimise F(x)=0.5x'Hx + g'x subject to sum(x)=0 // Special case of quadratic programming (Equality constraint: x.1=0) // \param H Hessian of F(x) - must be symmetric // \retval True if successful -bool vnl_solve_qp_zero_sum(const vnl_matrix& H, - const vnl_vector& g, - vnl_vector& x); +bool +vnl_solve_qp_zero_sum(const vnl_matrix & H, const vnl_vector & g, vnl_vector & x); //: Find non-negative solution to a constrained quadratic programming problem // Minimise F(x)=0.5x'Hx + g'x subject to Ax=b and x(i)>=0 for all i @@ -42,13 +42,14 @@ bool vnl_solve_qp_zero_sum(const vnl_matrix& H, // \param con_tol Tolerance for testing constraints: |Ax-b|^2& H, - const vnl_vector& g, - const vnl_matrix& A, - const vnl_vector& b, - vnl_vector& x, - double con_tol = 1e-8, - bool verbose=true); +bool VNL_ALGO_EXPORT +vnl_solve_qp_with_non_neg_constraints(const vnl_matrix & H, + const vnl_vector & g, + const vnl_matrix & A, + const vnl_vector & b, + vnl_vector & x, + double con_tol = 1e-8, + bool verbose = true); //: Find non-negative solution to a constrained quadratic programming problem // Minimise F(x)=0.5x'Hx + g'x subject to sum(x)=1 and x(i)>=0 for all i @@ -61,9 +62,10 @@ bool VNL_ALGO_EXPORT vnl_solve_qp_with_non_neg_constraints(const vnl_matrix=0) // \param verbose When true, output error messages to cerr if failed // \retval True if successful -bool VNL_ALGO_EXPORT vnl_solve_qp_non_neg_sum_one(const vnl_matrix& H, - const vnl_vector& g, - vnl_vector& x, - bool verbose=true); +bool VNL_ALGO_EXPORT +vnl_solve_qp_non_neg_sum_one(const vnl_matrix & H, + const vnl_vector & g, + vnl_vector & x, + bool verbose = true); #endif // vnl_solve_qp_h_ diff --git a/core/vnl/algo/vnl_sparse_lm.cxx b/core/vnl/algo/vnl_sparse_lm.cxx index 1168999074b..b6d4421d278 100644 --- a/core/vnl/algo/vnl_sparse_lm.cxx +++ b/core/vnl/algo/vnl_sparse_lm.cxx @@ -94,10 +94,14 @@ vnl_sparse_lm::minimize(vnl_vector & a, return false; //: Systems to solve will be Sc*dc=sec and Sa*da=sea - vnl_matrix Sc(size_c_, size_c_), Sa(size_a_, size_a_); - vnl_vector sec(size_c_), sea(size_a_); + const vnl_matrix Sc(size_c_, size_c_); + vnl_matrix Sa(size_a_, size_a_); + const vnl_vector sec(size_c_); + vnl_vector sea(size_a_); // update vectors - vnl_vector da(size_a_), db(size_b_), dc(size_c_); + vnl_vector da(size_a_); + vnl_vector db(size_b_); + vnl_vector dc(size_c_); // mu is initialized now because the compiler produces warnings -MM @@ -154,7 +158,7 @@ vnl_sparse_lm::minimize(vnl_vector & a, sqr_params += c.squared_magnitude(); // Extract the diagonal of J^T*J as a vector - vnl_vector diag_UVT = extract_diagonal(); + const vnl_vector diag_UVT = extract_diagonal(); // initialize mu if this is the first iteration // proportional to the diagonal entry with the largest magnitude @@ -177,7 +181,7 @@ vnl_sparse_lm::minimize(vnl_vector & a, // this large inverse is the bottle neck of this algorithm vnl_matrix H; - vnl_cholesky Sa_cholesky(Sa, vnl_cholesky::quiet); + const vnl_cholesky Sa_cholesky(Sa, vnl_cholesky::quiet); vnl_svd * Sa_svd = nullptr; // use SVD as a backup if Cholesky is deficient if (Sa_cholesky.rank_deficiency() > 0) @@ -226,11 +230,11 @@ vnl_sparse_lm::minimize(vnl_vector & a, // We could use a faster solver here, maybe conjugate gradients? // Solve the system Sa*da = sea for da - vnl_cholesky Sa_cholesky(Sa, vnl_cholesky::quiet); + const vnl_cholesky Sa_cholesky(Sa, vnl_cholesky::quiet); // use SVD as a backup if Cholesky is deficient if (Sa_cholesky.rank_deficiency() > 0) { - vnl_svd Sa_svd(Sa); + const vnl_svd Sa_svd(Sa); da = Sa_svd.solve(sea); } else @@ -252,8 +256,11 @@ vnl_sparse_lm::minimize(vnl_vector & a, } // compute updated parameters and residuals of the new parameters - vnl_vector new_a(a - da), new_b(b - db), new_c(c - dc); - vnl_vector new_e(e_.size()), new_weights(weights_.size()); + vnl_vector new_a(a - da); + vnl_vector new_b(b - db); + vnl_vector new_c(c - dc); + vnl_vector new_e(e_.size()); + vnl_vector new_weights(weights_.size()); f_->f(new_a, new_b, new_c, new_e); // compute the new residual vector ++num_evaluations_; @@ -264,14 +271,14 @@ vnl_sparse_lm::minimize(vnl_vector & a, f_->apply_weights(new_weights, new_e); } - double new_sqr_error = new_e.squared_magnitude(); + const double new_sqr_error = new_e.squared_magnitude(); - double dF = sqr_error - new_sqr_error; - double dL = + const double dF = sqr_error - new_sqr_error; + const double dL = dot_product(da, (mu * da + ea_)) + dot_product(db, (mu * db + eb_)) + dot_product(dc, (mu * dc + ec_)); if (dF > 0.0 && dL > 0.0) { - double tmp = 2.0 * dF / dL - 1.0; + const double tmp = 2.0 * dF / dL - 1.0; mu *= std::max(1.0 / 3.0, 1.0 - tmp * tmp * tmp); nu = 2.0; a.swap(new_a); @@ -318,9 +325,9 @@ vnl_sparse_lm::minimize(vnl_vector & a, //: check vector sizes and verify that they match the problem size bool -vnl_sparse_lm::check_vector_sizes(vnl_vector const & a, - vnl_vector const & b, - vnl_vector const & c) +vnl_sparse_lm::check_vector_sizes(const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c) { if (size_a_ + size_b_ > size_e_) { @@ -374,7 +381,7 @@ vnl_sparse_lm::allocate_matrices() Z_[i].set_size(size_c_, ai_size); Ma_[i].set_size(size_c_, ai_size); - vnl_crs_index::sparse_vector row = crs.sparse_row(i); + const vnl_crs_index::sparse_vector row = crs.sparse_row(i); for (auto & r_itr : row) { const unsigned int j = r_itr.second; @@ -428,18 +435,18 @@ vnl_sparse_lm::compute_normal_equations() Ui.fill(0.0); vnl_matrix & Qi = Q_[i]; Qi.fill(0.0); - unsigned int ai_size = f_->number_of_params_a(i); + const unsigned int ai_size = f_->number_of_params_a(i); vnl_vector_ref eai(ai_size, ea_.data_block() + f_->index_a(i)); - vnl_crs_index::sparse_vector row = crs.sparse_row(i); + const vnl_crs_index::sparse_vector row = crs.sparse_row(i); for (auto & r_itr : row) { - unsigned int j = r_itr.second; - unsigned int k = r_itr.first; + const unsigned int j = r_itr.second; + const unsigned int k = r_itr.first; ; - vnl_matrix & Aij = A_[k]; - vnl_matrix & Bij = B_[k]; - vnl_matrix & Cij = C_[k]; + const vnl_matrix & Aij = A_[k]; + const vnl_matrix & Bij = B_[k]; + const vnl_matrix & Cij = C_[k]; vnl_matrix & Vj = V_[j]; vnl_matrix & Rj = R_[j]; vnl_vector_ref ebj(Bij.cols(), eb_.data_block() + f_->index_b(j)); @@ -451,7 +458,7 @@ vnl_sparse_lm::compute_normal_equations() vnl_fastops::inc_X_by_AtB(Qi, Cij, Aij); // Qi += C_ij^T * A_ij vnl_fastops::inc_X_by_AtB(Rj, Cij, Bij); // Rj += C_ij^T * B_ij - vnl_vector_ref eij(f_->number_of_residuals(k), e_.data_block() + f_->index_e(k)); + const vnl_vector_ref eij(f_->number_of_residuals(k), e_.data_block() + f_->index_e(k)); vnl_fastops::inc_X_by_AtB(eai, Aij, eij); // e_a_i += A_ij^T * e_ij vnl_fastops::inc_X_by_AtB(ebj, Bij, eij); // e_b_j += B_ij^T * e_ij vnl_fastops::inc_X_by_AtB(ec_, Cij, eij); // e_c += C_ij^T * e_ij @@ -518,20 +525,20 @@ vnl_sparse_lm::compute_invV_Y() for (int j = 0; j < num_b_; ++j) { vnl_matrix & inv_Vj = inv_V_[j]; - vnl_cholesky Vj_cholesky(V_[j], vnl_cholesky::quiet); + const vnl_cholesky Vj_cholesky(V_[j], vnl_cholesky::quiet); // use SVD as a backup if Cholesky is deficient if (Vj_cholesky.rank_deficiency() > 0) { - vnl_svd Vj_svd(V_[j]); + const vnl_svd Vj_svd(V_[j]); inv_Vj = Vj_svd.inverse(); } else inv_Vj = Vj_cholesky.inverse(); - vnl_crs_index::sparse_vector col = crs.sparse_col(j); + const vnl_crs_index::sparse_vector col = crs.sparse_col(j); for (auto & c_itr : col) { - unsigned int k = c_itr.first; + const unsigned int k = c_itr.first; Y_[k] = W_[k] * inv_Vj; // Y_ij = W_ij * inv(V_j) } } @@ -558,9 +565,9 @@ vnl_sparse_lm::compute_Z_Sa(vnl_matrix & Sa) vnl_matrix Sii(U_[i]); // copy Ui to initialize Sii for (auto & ri : row_i) { - unsigned int j = ri.second; - unsigned int k = ri.first; - vnl_matrix & Yij = Y_[k]; + const unsigned int j = ri.second; + const unsigned int k = ri.first; + const vnl_matrix & Yij = Y_[k]; vnl_fastops::dec_X_by_ABt(Sii, Yij, W_[k]); // S_ii -= Y_ij * W_ij^T vnl_fastops::inc_X_by_ABt(Zi, R_[j], Yij); // Z_i += R_j * Y_ij^T } @@ -632,11 +639,11 @@ vnl_sparse_lm::compute_Mb() temp.fill(0.0); temp -= R_[j]; - vnl_crs_index::sparse_vector col = crs.sparse_col(j); + const vnl_crs_index::sparse_vector col = crs.sparse_col(j); for (auto & c_itr : col) { - unsigned int k = c_itr.first; - unsigned int i = c_itr.second; + const unsigned int k = c_itr.first; + const unsigned int i = c_itr.second; vnl_fastops::dec_X_by_AB(temp, Ma_[i], W_[k]); } vnl_fastops::AB(Mb_[j], temp, inv_V_[j]); @@ -673,11 +680,11 @@ vnl_sparse_lm::solve_dc(vnl_vector & dc) else { // Solve Sc*dc = sec for dc - vnl_cholesky Sc_cholesky(Sc, vnl_cholesky::quiet); + const vnl_cholesky Sc_cholesky(Sc, vnl_cholesky::quiet); // use SVD as a backup if Cholesky is deficient if (Sc_cholesky.rank_deficiency() > 0) { - vnl_svd Sc_svd(Sc); + const vnl_svd Sc_svd(Sc); dc = Sc_svd.solve(sec); } else @@ -688,7 +695,7 @@ vnl_sparse_lm::solve_dc(vnl_vector & dc) //: compute sea using ea, Z, dc, Y, and eb void -vnl_sparse_lm::compute_sea(vnl_vector const & dc, vnl_vector & sea) +vnl_sparse_lm::compute_sea(const vnl_vector & dc, vnl_vector & sea) { // CRS matrix of indices into e, A, B, C, W, Y const vnl_crs_index & crs = f_->residual_indices(); @@ -698,15 +705,15 @@ vnl_sparse_lm::compute_sea(vnl_vector const & dc, vnl_vector & s for (int i = 0; i < num_a_; ++i) { vnl_vector_ref sei(f_->number_of_params_a(i), sea.data_block() + f_->index_a(i)); - vnl_crs_index::sparse_vector row_i = crs.sparse_row(i); + const vnl_crs_index::sparse_vector row_i = crs.sparse_row(i); vnl_fastops::inc_X_by_AtB(sei, Z_[i], dc); for (auto & ri : row_i) { - unsigned int k = ri.first; - vnl_matrix & Yij = Y_[k]; - vnl_vector_ref ebj(Yij.cols(), eb_.data_block() + f_->index_b(ri.second)); + const unsigned int k = ri.first; + const vnl_matrix & Yij = Y_[k]; + const vnl_vector_ref ebj(Yij.cols(), eb_.data_block() + f_->index_b(ri.second)); sei -= Yij * ebj; // se_i -= Y_ij * e_b_j } } @@ -731,10 +738,10 @@ vnl_sparse_lm::compute_Sa_sea(vnl_matrix & Sa, vnl_vector & sea) vnl_matrix Sii(U_[i]); // copy Ui to initialize Sii for (auto & ri : row_i) { - unsigned int k = ri.first; - vnl_matrix & Yij = Y_[k]; + const unsigned int k = ri.first; + const vnl_matrix & Yij = Y_[k]; vnl_fastops::dec_X_by_ABt(Sii, Yij, W_[k]); // S_ii -= Y_ij * W_ij^T - vnl_vector_ref ebj(Yij.cols(), eb_.data_block() + f_->index_b(ri.second)); + const vnl_vector_ref ebj(Yij.cols(), eb_.data_block() + f_->index_b(ri.second)); sei -= Yij * ebj; // se_i -= Y_ij * e_b_j } Sa.update(Sii, f_->index_a(i), f_->index_a(i)); @@ -771,7 +778,7 @@ vnl_sparse_lm::compute_Sa_sea(vnl_matrix & Sa, vnl_vector & sea) //: back solve to find db using da and dc void -vnl_sparse_lm::backsolve_db(vnl_vector const & da, vnl_vector const & dc, vnl_vector & db) +vnl_sparse_lm::backsolve_db(const vnl_vector & da, const vnl_vector & dc, vnl_vector & db) { // CRS matrix of indices into e, A, B, C, W, Y const vnl_crs_index & crs = f_->residual_indices(); @@ -780,15 +787,15 @@ vnl_sparse_lm::backsolve_db(vnl_vector const & da, vnl_vector co for (int j = 0; j < num_b_; ++j) { vnl_vector seb(eb_.data_block() + f_->index_b(j), f_->number_of_params_b(j)); - vnl_crs_index::sparse_vector col = crs.sparse_col(j); + const vnl_crs_index::sparse_vector col = crs.sparse_col(j); if (size_c_ > 0) { vnl_fastops::dec_X_by_AtB(seb, R_[j], dc); } for (auto & c_itr : col) { - unsigned int k = c_itr.first; - unsigned int i = c_itr.second; + const unsigned int k = c_itr.first; + const unsigned int i = c_itr.second; const vnl_vector_ref dai(f_->number_of_params_a(i), const_cast(da.data_block() + f_->index_a(i))); vnl_fastops::dec_X_by_AtB(seb, W_[k], dai); @@ -849,14 +856,14 @@ vnl_sparse_lm::diagnose_outcome(std::ostream & s) const s << (whoami ": OIOIOI: unkown info code from lmder.\n"); break; } - unsigned int num_e = f_->number_of_e(); + const unsigned int num_e = f_->number_of_e(); s << whoami ": " << num_iterations_ << " iterations, " << num_evaluations_ << " evaluations, " << num_e << " residuals. RMS error start/end " << get_start_error() << '/' << get_end_error() << std::endl; #undef whoami } -vnl_matrix const & +const vnl_matrix & vnl_sparse_lm::get_JtJ() { return inv_covar_; diff --git a/core/vnl/algo/vnl_sparse_lm.h b/core/vnl/algo/vnl_sparse_lm.h index 670cd10c0e7..960989e8cec 100644 --- a/core/vnl/algo/vnl_sparse_lm.h +++ b/core/vnl/algo/vnl_sparse_lm.h @@ -34,10 +34,9 @@ class vnl_sparse_lst_sqr_function; // at http://www.ics.forth.gr/~lourakis/sba class VNL_ALGO_EXPORT vnl_sparse_lm : public vnl_nonlinear_minimizer { - public: - +public: //: Initialize with the function object that is to be minimized. - vnl_sparse_lm(vnl_sparse_lst_sqr_function& f); + vnl_sparse_lm(vnl_sparse_lst_sqr_function & f); //: Destructor ~vnl_sparse_lm() override; @@ -49,83 +48,97 @@ class VNL_ALGO_EXPORT vnl_sparse_lm : public vnl_nonlinear_minimizer // even if the Jacobian functions have been provided. // If use_weights is set to false, weights will not be computed even if a // weighting function has been provided. - bool minimize(vnl_vector& a, - vnl_vector& b, - vnl_vector& c, - bool use_gradient = true, - bool use_weights = true); + bool + minimize(vnl_vector & a, + vnl_vector & b, + vnl_vector & c, + bool use_gradient = true, + bool use_weights = true); // Coping with failure------------------------------------------------------- //: Provide an ASCII diagnosis of the last minimization on std::ostream. void diagnose_outcome(/*std::cerr*/) const; - void diagnose_outcome(std::ostream&) const; + void + diagnose_outcome(std::ostream &) const; //: Return J'*J computed at last minimum. // it is an approximation of inverse of covariance - vnl_matrix const& get_JtJ(); + const vnl_matrix & + get_JtJ(); //: Access the final weights after optimization - const vnl_vector& get_weights() const { return weights_; } + const vnl_vector & + get_weights() const + { + return weights_; + } protected: - //: used to compute the initial damping double tau_; //: the function to minimize - vnl_sparse_lst_sqr_function* f_; + vnl_sparse_lst_sqr_function * f_; vnl_matrix inv_covar_; bool set_covariance_; // Set if covariance_ holds J'*J - void init(vnl_sparse_lst_sqr_function* f); + void + init(vnl_sparse_lst_sqr_function * f); private: - //: allocate matrix memory by setting all the matrix sizes - void allocate_matrices(); + void + allocate_matrices(); //: check vector sizes and verify that they match the problem size - bool check_vector_sizes(vnl_vector const& a, - vnl_vector const& b, - vnl_vector const& c); + bool + check_vector_sizes(const vnl_vector & a, const vnl_vector & b, const vnl_vector & c); //: compute the blocks making up the the normal equations: Jt J d = Jt e - void compute_normal_equations(); + void + compute_normal_equations(); //: extract the vector on the diagonal of Jt J - vnl_vector extract_diagonal() const; + vnl_vector + extract_diagonal() const; //: set the vector on the diagonal of Jt J - void set_diagonal(const vnl_vector& diag); + void + set_diagonal(const vnl_vector & diag); //: compute all inv(Vi) and Yij - void compute_invV_Y(); + void + compute_invV_Y(); //: compute Z and Sa - void compute_Z_Sa(vnl_matrix& Sa); + void + compute_Z_Sa(vnl_matrix & Sa); //: compute Ma - void compute_Ma(const vnl_matrix& H); + void + compute_Ma(const vnl_matrix & H); //: compute Mb - void compute_Mb(); + void + compute_Mb(); //: solve for dc - void solve_dc(vnl_vector& dc); + void + solve_dc(vnl_vector & dc); //: compute sea using ea, Z, dc, Y, and eb - void compute_sea(vnl_vector const& dc, - vnl_vector& sea); + void + compute_sea(const vnl_vector & dc, vnl_vector & sea); //: compute Sa and sea // only used when size_c_ == 0 - void compute_Sa_sea(vnl_matrix& Sa, vnl_vector& sea); + void + compute_Sa_sea(vnl_matrix & Sa, vnl_vector & sea); //: back solve to find db using da and dc - void backsolve_db(vnl_vector const& da, - vnl_vector const& dc, - vnl_vector& db); + void + backsolve_db(const vnl_vector & da, const vnl_vector & dc, vnl_vector & db); const int num_a_; const int num_b_; @@ -138,19 +151,19 @@ class VNL_ALGO_EXPORT vnl_sparse_lm : public vnl_nonlinear_minimizer const int size_e_; //: Storage for each of the Jacobians A_ij, B_ij, and C_ij - std::vector > A_; - std::vector > B_; - std::vector > C_; + std::vector> A_; + std::vector> B_; + std::vector> C_; //: Storage for normal equation blocks // diagonals of JtJ - std::vector > U_; - std::vector > V_; - vnl_matrix T_; + std::vector> U_; + std::vector> V_; + vnl_matrix T_; // off-diagonals of JtJ - std::vector > W_; - std::vector > R_; - std::vector > Q_; + std::vector> W_; + std::vector> R_; + std::vector> Q_; // vectors Jte vnl_vector ea_; vnl_vector eb_; @@ -163,12 +176,11 @@ class VNL_ALGO_EXPORT vnl_sparse_lm : public vnl_nonlinear_minimizer vnl_vector weights_; // Storage for intermediate results - std::vector > inv_V_; - std::vector > Y_; - std::vector > Z_; - std::vector > Ma_; - std::vector > Mb_; - + std::vector> inv_V_; + std::vector> Y_; + std::vector> Z_; + std::vector> Ma_; + std::vector> Mb_; }; diff --git a/core/vnl/algo/vnl_sparse_lu.cxx b/core/vnl/algo/vnl_sparse_lu.cxx index fdc7ea16b70..efab549cf76 100644 --- a/core/vnl/algo/vnl_sparse_lu.cxx +++ b/core/vnl/algo/vnl_sparse_lu.cxx @@ -9,26 +9,15 @@ // destructor - undo the spCreate() from the constructor(s) // (memory leak fix of 7 Feb. 2008 by Toon Huysmans) -vnl_sparse_lu::~vnl_sparse_lu() -{ - spDestroy(pmatrix_); -} +vnl_sparse_lu::~vnl_sparse_lu() { spDestroy(pmatrix_); } //: constructor - controls if condition information is computed -vnl_sparse_lu::vnl_sparse_lu(vnl_sparse_matrix const & M, operation mode) +vnl_sparse_lu::vnl_sparse_lu(const vnl_sparse_matrix & M, operation mode) : A_(M) - , factored_(false) - , condition_computed_(false) , mode_(mode) - , norm_(0) - , rcond_(0) - , largest_(0) - , pivot_thresh_(0) - , absolute_thresh_(0) - , diag_pivoting_(1) - , pmatrix_(nullptr) + { - int n = (int)M.columns(); + const int n = (int)M.columns(); assert(n == (int)(M.rows())); int error = 0; pmatrix_ = spCreate(n, 0, &error); @@ -41,9 +30,9 @@ vnl_sparse_lu::vnl_sparse_lu(vnl_sparse_matrix const & M, operation mode spElement * pelement = nullptr; for (A_.reset(); A_.next();) { - int r = A_.getrow(); - int c = A_.getcolumn(); - double v = A_.value(); + const int r = A_.getrow(); + const int c = A_.getcolumn(); + const double v = A_.value(); pelement = spGetElement(pmatrix_, r + 1, c + 1); if (pelement == nullptr) { @@ -78,14 +67,14 @@ vnl_sparse_lu::est_condition() //: Solve least squares problem M x = b. void -vnl_sparse_lu::solve(vnl_vector const & b, vnl_vector * x) +vnl_sparse_lu::solve(const vnl_vector & b, vnl_vector * x) { if (!pmatrix_) { std::cout << "In vnl_sparse_lu::solve(..) - matrix not defined\n"; return; } - unsigned n = b.size(); + const unsigned n = b.size(); assert(n == A_.columns()); auto * rhs = new spREAL[n + 1]; for (unsigned i = 0; i < n; ++i) @@ -129,7 +118,7 @@ vnl_sparse_lu::solve(vnl_vector const & b, vnl_vector * x) //: Solve least squares problem M x = b. vnl_vector -vnl_sparse_lu::solve(vnl_vector const & b) +vnl_sparse_lu::solve(const vnl_vector & b) { vnl_vector ret(b.size()); this->solve(b, &ret); @@ -138,14 +127,14 @@ vnl_sparse_lu::solve(vnl_vector const & b) //: Solve problem M^t x = b void -vnl_sparse_lu::solve_transpose(vnl_vector const & b, vnl_vector * x) +vnl_sparse_lu::solve_transpose(const vnl_vector & b, vnl_vector * x) { if (!pmatrix_) { std::cout << "In vnl_sparse_lu::solve(..) - matrix not defined\n"; return; } - unsigned n = b.size(); + const unsigned n = b.size(); assert(n == A_.columns()); auto * rhs = new spREAL[n + 1]; for (unsigned i = 0; i < n; ++i) @@ -189,7 +178,7 @@ vnl_sparse_lu::solve_transpose(vnl_vector const & b, vnl_vector //: Solve problem M^t x = b vnl_vector -vnl_sparse_lu::solve_transpose(vnl_vector const & b) +vnl_sparse_lu::solve_transpose(const vnl_vector & b) { vnl_vector ret(b.size()); this->solve_transpose(b, &ret); @@ -245,7 +234,7 @@ vnl_sparse_lu::rcond() return rcond_; } -//:Estimated upper bound of error in solution +//: Estimated upper bound of error in solution double vnl_sparse_lu::max_error_bound() { @@ -259,7 +248,7 @@ vnl_sparse_lu::max_error_bound() return 0; factored_ = true; } - double roundoff = spRoundoff(pmatrix_, largest_); + const double roundoff = spRoundoff(pmatrix_, largest_); if (rcond_ > 0) return roundoff / rcond_; return 0; diff --git a/core/vnl/algo/vnl_sparse_lu.h b/core/vnl/algo/vnl_sparse_lu.h index ae6835da505..4a990bdd829 100644 --- a/core/vnl/algo/vnl_sparse_lu.h +++ b/core/vnl/algo/vnl_sparse_lu.h @@ -27,9 +27,10 @@ class VNL_ALGO_EXPORT vnl_sparse_lu { - public: +public: //: Modes of computation. See constructor for details. - enum operation { + enum operation + { quiet, verbose, estimate_condition, @@ -37,72 +38,95 @@ class VNL_ALGO_EXPORT vnl_sparse_lu }; //: Make sparse_lu decomposition of M optionally computing the reciprocal condition number. - vnl_sparse_lu(vnl_sparse_matrix const& M, operation mode = quiet); - ~vnl_sparse_lu(); + vnl_sparse_lu(const vnl_sparse_matrix & M, operation mode = quiet); + ~vnl_sparse_lu(); //: set the relative pivot threshold should be between 0 and 1 // If set to one then pivoting is complete and slow // If near zero then roundoff error may be prohibitive but computation is fast // Typical values are between 0.01 and 0.1. - void set_pivot_thresh(double pivot_thresh){pivot_thresh_=pivot_thresh;} + void + set_pivot_thresh(double pivot_thresh) + { + pivot_thresh_ = pivot_thresh; + } //: set the threshold on absolute element magnitude for pivoting // Should be either zero or significantly smaller than the absolute // value of the smallest diagonal element. - void set_absolute_thresh(double absolute_thresh){absolute_thresh_=absolute_thresh;} + void + set_absolute_thresh(double absolute_thresh) + { + absolute_thresh_ = absolute_thresh; + } //: set diagonal pivoting mode, normally 1 which gives priority to diagonal elements. - void set_diagonal_pivoting(int diag_pivoting){diag_pivoting_=diag_pivoting;} + void + set_diagonal_pivoting(int diag_pivoting) + { + diag_pivoting_ = diag_pivoting; + } //: Solve problem M x = b - vnl_vector solve(vnl_vector const& b); + vnl_vector + solve(const vnl_vector & b); //: Solve problem M x = b - void solve(vnl_vector const& b, vnl_vector* x); + void + solve(const vnl_vector & b, vnl_vector * x); //: Solve problem M^t x = b - vnl_vector solve_transpose(vnl_vector const& b); + vnl_vector + solve_transpose(const vnl_vector & b); //: Solve problem M^t x = b - void solve_transpose(vnl_vector const& b, vnl_vector* x); + void + solve_transpose(const vnl_vector & b, vnl_vector * x); //: Compute determinant - double determinant(); + double + determinant(); //: Return reciprocal condition number (smallest/largest singular values). // As long as rcond()>sqrt(precision) the decomposition can be used for // solving equations safely. // Not calculated unless operation mode at construction includes estimate_condition. - double rcond(); + double + rcond(); //: An estimate of maximum error in solution. // Not calculated unless operation mode at construction includes estimate_condition. - double max_error_bound(); + double + max_error_bound(); - protected: +protected: // Internals - void decompose_matrix(); - bool est_condition(); + void + decompose_matrix(); + bool + est_condition(); // Data Members-------------------------------------------------------------- vnl_sparse_matrix A_; - bool factored_; - bool condition_computed_; + bool factored_{ false }; + bool condition_computed_{ false }; operation mode_; - double norm_; - double rcond_; - double largest_; - double pivot_thresh_; - double absolute_thresh_; - int diag_pivoting_; - private: + double norm_{ 0 }; + double rcond_{ 0 }; + double largest_{ 0 }; + double pivot_thresh_{ 0 }; + double absolute_thresh_{ 0 }; + int diag_pivoting_{ 1 }; + +private: //: Copy constructor - privatised to avoid it being used - vnl_sparse_lu(vnl_sparse_lu const & that); + vnl_sparse_lu(const vnl_sparse_lu & that); //: Assignment operator - privatised to avoid it being used - vnl_sparse_lu& operator=(vnl_sparse_lu const & that); + vnl_sparse_lu & + operator=(const vnl_sparse_lu & that); //: The internal matrix representation // // We don't use the typedef spMatrix directly here to avoid exposing // the implementation detail (sparse/spMatrix.h) to the user. - void* pmatrix_; + void * pmatrix_{ nullptr }; }; #endif // vnl_sparse_lu_h_ diff --git a/core/vnl/algo/vnl_sparse_symmetric_eigensystem.cxx b/core/vnl/algo/vnl_sparse_symmetric_eigensystem.cxx index 772e4bb5bf0..f1a98691a61 100644 --- a/core/vnl/algo/vnl_sparse_symmetric_eigensystem.cxx +++ b/core/vnl/algo/vnl_sparse_symmetric_eigensystem.cxx @@ -45,7 +45,7 @@ sse_iovect_callback(const long * n, const long * m, double * q, const long * j, vnl_sparse_symmetric_eigensystem::vnl_sparse_symmetric_eigensystem() - = default; + = default; vnl_sparse_symmetric_eigensystem::~vnl_sparse_symmetric_eigensystem() { @@ -82,23 +82,23 @@ vnl_sparse_symmetric_eigensystem::CalculateNPairs(vnl_sparse_matrix & M, current_system = this; - long dim = mat->columns(); - long nvals = (smallest) ? -n : n; - long nperm = 0; - long nmval = n; - long nmvec = dim; + const long dim = mat->columns(); + const long nvals = (smallest) ? -n : n; + const long nperm = 0; + const long nmval = n; + const long nmvec = dim; std::vector temp_vals(n * 4); std::vector temp_vecs(n * dim); // set nblock = std::max(10, dim/6) : - long nblock = (dim < 60) ? dim / 6 : 10; + const long nblock = (dim < 60) ? dim / 6 : 10; // isn't this rather a lot ? -- fsm - long maxop = dim * 10; // dim*20; + const long maxop = dim * 10; // dim*20; // set maxj = std::max(40, maxop*nblock, 6*nblock+1) : long maxj = maxop * nblock; // 2*n+1; - long t1 = 6 * nblock + 1; + const long t1 = 6 * nblock + 1; if (maxj < t1) maxj = t1; if (maxj < 40) @@ -107,7 +107,7 @@ vnl_sparse_symmetric_eigensystem::CalculateNPairs(vnl_sparse_matrix & M, // Calculate size of workspace needed. These expressions come from // the LASO documentation. int work_size = dim * nblock; - int t2 = maxj * (2 * nblock + 3) + 2 * n + 6 + (2 * nblock + 2) * (nblock + 1); + const int t2 = maxj * (2 * nblock + 3) + 2 * n + 6 + (2 * nblock + 2) * (nblock + 1); if (work_size < t2) work_size = t2; work_size += 2 * dim * nblock + maxj * (nblock + n + 2) + 2 * nblock * nblock + 3 * n; @@ -466,7 +466,7 @@ vnl_sparse_symmetric_eigensystem::CalculateNPairs(vnl_sparse_matrix & A, int evIx; for (evIx = 0; evIx < nvalues; evIx++) { - vnl_vector_ref tempEVec(matSize, &Z[evIx * matSize]); + const vnl_vector_ref tempEVec(matSize, &Z[evIx * matSize]); vectors[evIx] = tempEVec; } diff --git a/core/vnl/algo/vnl_sparse_symmetric_eigensystem.h b/core/vnl/algo/vnl_sparse_symmetric_eigensystem.h index 62d1ed3ddcd..0f429956fdf 100644 --- a/core/vnl/algo/vnl_sparse_symmetric_eigensystem.h +++ b/core/vnl/algo/vnl_sparse_symmetric_eigensystem.h @@ -36,15 +36,15 @@ class VNL_ALGO_EXPORT vnl_sparse_symmetric_eigensystem { - public: +public: vnl_sparse_symmetric_eigensystem(); - ~vnl_sparse_symmetric_eigensystem(); + ~vnl_sparse_symmetric_eigensystem(); // Find n eigenvalue/eigenvectors of the eigenproblem A * x = lambda * x. // If smallest is true, will calculate the n smallest eigenpairs, // else the n largest. - int CalculateNPairs(vnl_sparse_matrix& M, int n, - bool smallest = true, long nfigures = 10); + int + CalculateNPairs(vnl_sparse_matrix & M, int n, bool smallest = true, long nfigures = 10); // Find n eigenvalue/eigenvectors of the eigenproblem A * x = lambda * B * x. // !smallest and !magnitude - compute the N largest (algebraic) eigenvalues @@ -52,33 +52,43 @@ class VNL_ALGO_EXPORT vnl_sparse_symmetric_eigensystem // !smallest and magnitude - compute the N largest (magnitude) eigenvalues // smallest and magnitude - compute the nev smallest (magnitude) eigenvalues // set sigma for shift/invert method - int CalculateNPairs(vnl_sparse_matrix& A, vnl_sparse_matrix& B, int nEV, - double tolerance = 0, int numberLanczosVecs = 0, - bool smallest = false, bool magnitude = true, - int maxIterations = 0, - double sigma = 0.0); + int + CalculateNPairs(vnl_sparse_matrix & A, + vnl_sparse_matrix & B, + int nEV, + double tolerance = 0, + int numberLanczosVecs = 0, + bool smallest = false, + bool magnitude = true, + int maxIterations = 0, + double sigma = 0.0); // Recover specified eigenvector after computation. The argument // must be less than the requested number of eigenvectors. - vnl_vector get_eigenvector(int i) const; - double get_eigenvalue(int i) const; + vnl_vector + get_eigenvector(int i) const; + double + get_eigenvalue(int i) const; // Used as a callback in solving. - int CalculateProduct(int n, int m, const double* p, double* q); - int SaveVectors(int n, int m, const double* q, int base); - int RestoreVectors(int n, int m, double* q, int base); + int + CalculateProduct(int n, int m, const double * p, double * q); + int + SaveVectors(int n, int m, const double * q, int base); + int + RestoreVectors(int n, int m, double * q, int base); - protected: - int nvalues{0}; // this is the size of the next two arrays. - vnl_vector *vectors{nullptr}; // eigenvectors - double *values{nullptr}; // eigenvalues +protected: + int nvalues{ 0 }; // this is the size of the next two arrays. + vnl_vector * vectors{ nullptr }; // eigenvectors + double * values{ nullptr }; // eigenvalues - // Matrix A of A*x = lambda*x (or lambda*B*x) - vnl_sparse_matrix *mat; - // Matrix B of A*x = lambda*B*x - vnl_sparse_matrix *Bmat; + // Matrix A of A*x = lambda*x (or lambda*B*x) + vnl_sparse_matrix * mat; + // Matrix B of A*x = lambda*B*x + vnl_sparse_matrix * Bmat; - std::vector temp_store; + std::vector temp_store; }; #endif // vnl_sparse_symmetric_eigensystem_h_ diff --git a/core/vnl/algo/vnl_svd.h b/core/vnl/algo/vnl_svd.h index 75a009b8d45..fb2773710a7 100644 --- a/core/vnl/algo/vnl_svd.h +++ b/core/vnl/algo/vnl_svd.h @@ -62,7 +62,7 @@ template class VNL_ALGO_EXPORT vnl_svd { - public: +public: //: The singular values of a matrix of complex are of type T, not complex typedef typename vnl_numeric_traits::abs_t singval_t; @@ -81,128 +81,225 @@ class VNL_ALGO_EXPORT vnl_svd // absolute value is set to zero. If zero_out_tol is negative, the // zeroing is relative to |zero_out_tol| * sigma_max(); - vnl_svd(vnl_matrix const &M, double zero_out_tol = 0.0); - virtual ~vnl_svd() = default; + vnl_svd(const vnl_matrix & M, double zero_out_tol = 0.0); + virtual ~vnl_svd() = default; // Data Access--------------------------------------------------------------- //: find weights below threshold tol, zero them out, and update W_ and Winverse_ - void zero_out_absolute(double tol = 1e-8); //sqrt(machine epsilon) + void + zero_out_absolute(double tol = 1e-8); // sqrt(machine epsilon) //: find weights below tol*max(w) and zero them out - void zero_out_relative(double tol = 1e-8); //sqrt(machine epsilon) - int singularities () const { return W_.rows() - rank(); } - unsigned int rank () const { return rank_; } - singval_t well_condition () const { return sigma_min()/sigma_max(); } + void + zero_out_relative(double tol = 1e-8); // sqrt(machine epsilon) + int + singularities() const + { + return W_.rows() - rank(); + } + unsigned int + rank() const + { + return rank_; + } + singval_t + well_condition() const + { + return sigma_min() / sigma_max(); + } //: Calculate determinant as product of diagonals in W. - singval_t determinant_magnitude () const; - singval_t norm() const; + singval_t + determinant_magnitude() const; + singval_t + norm() const; //: Return the matrix U. - vnl_matrix & U() { return U_; } + vnl_matrix & + U() + { + return U_; + } //: Return the matrix U. - vnl_matrix const& U() const { return U_; } + const vnl_matrix & + U() const + { + return U_; + } //: Return the matrix U's (i,j)th entry (to avoid svd.U()(i,j); ). - T U(int i, int j) const { return U_(i,j); } + T + U(int i, int j) const + { + return U_(i, j); + } //: Get at DiagMatrix (q.v.) of singular values, sorted from largest to smallest - vnl_diag_matrix & W() { return W_; } + vnl_diag_matrix & + W() + { + return W_; + } //: Get at DiagMatrix (q.v.) of singular values, sorted from largest to smallest - vnl_diag_matrix const & W() const { return W_; } - vnl_diag_matrix & Winverse() { return Winverse_; } - vnl_diag_matrix const & Winverse() const { return Winverse_; } - singval_t & W(int i, int j) { return W_(i,j); } - singval_t & W(int i) { return W_(i,i); } - singval_t sigma_max() const { return W_(0,0); } // largest - singval_t sigma_min() const { return W_(n_-1,n_-1); } // smallest + const vnl_diag_matrix & + W() const + { + return W_; + } + vnl_diag_matrix & + Winverse() + { + return Winverse_; + } + const vnl_diag_matrix & + Winverse() const + { + return Winverse_; + } + singval_t & + W(int i, int j) + { + return W_(i, j); + } + singval_t & + W(int i) + { + return W_(i, i); + } + singval_t + sigma_max() const + { + return W_(0, 0); + } // largest + singval_t + sigma_min() const + { + return W_(n_ - 1, n_ - 1); + } // smallest //: Return the matrix V. - vnl_matrix & V() { return V_; } + vnl_matrix & + V() + { + return V_; + } //: Return the matrix V. - vnl_matrix const& V() const { return V_; } + const vnl_matrix & + V() const + { + return V_; + } //: Return the matrix V's (i,j)th entry (to avoid svd.V()(i,j); ). - T V(int i, int j) const { return V_(i,j); } + T + V(int i, int j) const + { + return V_(i, j); + } //: - inline vnl_matrix inverse () const { return pinverse(); } + inline vnl_matrix + inverse() const + { + return pinverse(); + } //: pseudo-inverse (for non-square matrix) of desired rank. - vnl_matrix pinverse (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 + vnl_matrix + pinverse(unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 //: Calculate inverse of transpose, using desired rank. - vnl_matrix tinverse (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 + vnl_matrix + tinverse(unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 //: Recompose SVD to U*W*V', using desired rank. - vnl_matrix recompose (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 + vnl_matrix + recompose(unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 //: Solve the matrix equation M X = B, returning X - vnl_matrix solve (vnl_matrix const& B) const; + vnl_matrix + solve(const vnl_matrix & B) const; //: Solve the matrix-vector system M x = y, returning x. - vnl_vector solve (vnl_vector const& y) const; - void solve (T const *rhs, T *lhs) const; // min ||A*lhs - rhs|| + vnl_vector + solve(const vnl_vector & y) const; + void + solve(const T * rhs, T * lhs) const; // min ||A*lhs - rhs|| //: Solve the matrix-vector system M x = y. // Assuming that the singular values W have been preinverted by the caller. - void solve_preinverted(vnl_vector const& rhs, vnl_vector* out) const; + void + solve_preinverted(const vnl_vector & rhs, vnl_vector * out) const; //: Return N such that M * N = 0 - vnl_matrix nullspace() const; + vnl_matrix + nullspace() const; //: Return N such that M' * N = 0 - vnl_matrix left_nullspace() const; + vnl_matrix + left_nullspace() const; //: Return N such that M * N = 0 - vnl_matrix nullspace(int required_nullspace_dimension) const; + vnl_matrix + nullspace(int required_nullspace_dimension) const; //: Implementation to be done yet; currently returns left_nullspace(). - PVR. - vnl_matrix left_nullspace(int required_nullspace_dimension) const; + vnl_matrix + left_nullspace(int required_nullspace_dimension) const; //: Return the rightmost column of V. // Does not check to see whether or not the matrix actually was rank-deficient - // the caller is assumed to have examined W and decided that to his or her satisfaction. - vnl_vector nullvector() const; + vnl_vector + nullvector() const; //: Return the rightmost column of U. // Does not check to see whether or not the matrix actually was rank-deficient. - vnl_vector left_nullvector() const; - - bool valid() const { return valid_; } - - private: - - int m_, n_; // Size of M, local cache. - vnl_matrix U_; // Columns Ui are basis for range of M for Wi != 0 - vnl_diag_matrix W_;// Singular values, sorted in decreasing order + vnl_vector + left_nullvector() const; + + bool + valid() const + { + return valid_; + } + +private: + int m_, n_; // Size of M, local cache. + vnl_matrix U_; // Columns Ui are basis for range of M for Wi != 0 + vnl_diag_matrix W_; // Singular values, sorted in decreasing order vnl_diag_matrix Winverse_; - vnl_matrix V_; // Columns Vi are basis for nullspace of M for Wi = 0 + vnl_matrix V_; // Columns Vi are basis for nullspace of M for Wi = 0 unsigned rank_; bool have_max_; singval_t max_; bool have_min_; singval_t min_; double last_tol_; - bool valid_; // false if the NETLIB call failed. + bool valid_; // false if the NETLIB call failed. // Disallow assignment. - vnl_svd(vnl_svd const &) { } - vnl_svd& operator=(vnl_svd const &) { return *this; } + vnl_svd(const vnl_svd &) {} + vnl_svd & + operator=(const vnl_svd &) + { + return *this; + } }; template -inline -vnl_matrix vnl_svd_inverse(vnl_matrix const& m) +inline vnl_matrix +vnl_svd_inverse(const vnl_matrix & m) { return vnl_svd(m).inverse(); } template -std::ostream& operator<<(std::ostream&, vnl_svd const& svd); +std::ostream & +operator<<(std::ostream &, const vnl_svd & svd); #endif // vnl_svd_h_ diff --git a/core/vnl/algo/vnl_svd.hxx b/core/vnl/algo/vnl_svd.hxx index e486c49d4c9..0a8778b98be 100644 --- a/core/vnl/algo/vnl_svd.hxx +++ b/core/vnl/algo/vnl_svd.hxx @@ -22,8 +22,7 @@ // use C++ overloading to call the right linpack routine from the template code : #define macro(p, T) \ -inline void vnl_linpack_svdc(vnl_netlib_svd_proto(T)) \ -{ v3p_netlib_##p##svdc_(vnl_netlib_svd_params); } + inline void vnl_linpack_svdc(vnl_netlib_svd_proto(T)) { v3p_netlib_##p##svdc_(vnl_netlib_svd_params); } macro(s, float); macro(d, double); macro(c, std::complex); @@ -36,21 +35,21 @@ static bool vnl_svd_test_heavily = false; #include template -vnl_svd::vnl_svd(vnl_matrix const& M, double zero_out_tol): - m_(M.rows()), - n_(M.columns()), - U_(m_, n_), - W_(n_), - Winverse_(n_), - V_(n_, n_) +vnl_svd::vnl_svd(vnl_matrix const & M, double zero_out_tol) + : m_(M.rows()) + , n_(M.columns()) + , U_(m_, n_) + , W_(n_) + , Winverse_(n_) + , V_(n_, n_) { assert(m_ > 0); assert(n_ > 0); { - long n = M.rows(); - long p = M.columns(); - long mm = std::min(n+1L,p); + const long n = M.rows(); + const long p = M.columns(); + const long mm = std::min(n + 1L, p); // Copy source matrix into fortran storage // SVD is slow, don't worry about the cost of this transpose. @@ -58,21 +57,27 @@ vnl_svd::vnl_svd(vnl_matrix const& M, double zero_out_tol): // Make workspace vectors. vnl_vector work(n, T(0)); - vnl_vector uspace(n*p, T(0)); - vnl_vector vspace(p*p, T(0)); + vnl_vector uspace(n * p, T(0)); + vnl_vector vspace(p * p, T(0)); vnl_vector wspace(mm, T(0)); // complex fortran routine actually _wants_ complex W! vnl_vector espace(p, T(0)); // Call Linpack SVD long info = 0; constexpr long job = 21; // min(n,p) svs in U, n svs in V (i.e. economy size) - vnl_linpack_svdc((T*)X, &n, &n, &p, + vnl_linpack_svdc((T *)X, + &n, + &n, + &p, wspace.data_block(), espace.data_block(), - uspace.data_block(), &n, - vspace.data_block(), &p, + uspace.data_block(), + &n, + vspace.data_block(), + &p, work.data_block(), - &job, &info); + &job, + &info); // Error return? if (info != 0) @@ -105,7 +110,7 @@ vnl_svd::vnl_svd(vnl_matrix const& M, double zero_out_tol): // // You may be able to diagnose the problem here by printing a warning message. std::cerr << __FILE__ ": suspicious return value (" << info << ") from SVDC\n" - << __FILE__ ": M is " << M.rows() << 'x' << M.cols() << std::endl; + << __FILE__ ": M is " << M.rows() << 'x' << M.cols() << std::endl; vnl_matlab_print(std::cerr, M, "M", vnl_matlab_print_format_long); valid_ = false; @@ -115,10 +120,10 @@ vnl_svd::vnl_svd(vnl_matrix const& M, double zero_out_tol): // Copy fortran outputs into our storage { - const T *d = uspace.data_block(); + const T * d = uspace.data_block(); for (int j = 0; j < p; ++j) for (int i = 0; i < n; ++i) - U_(i,j) = *d++; + U_(i, j) = *d++; } for (int j = 0; j < mm; ++j) @@ -128,10 +133,10 @@ vnl_svd::vnl_svd(vnl_matrix const& M, double zero_out_tol): W_(j, j) = 0; { - const T *d = vspace.data_block(); + const T * d = vspace.data_block(); for (int j = 0; j < p; ++j) for (int i = 0; i < p; ++i) - V_(i,j) = *d++; + V_(i, j) = *d++; } } @@ -139,16 +144,16 @@ vnl_svd::vnl_svd(vnl_matrix const& M, double zero_out_tol): { // Test that recomposed matrix == M typedef typename vnl_numeric_traits::abs_t abs_t; - abs_t recomposition_residual = std::abs((recompose() - M).fro_norm()); - abs_t n = std::abs(M.fro_norm()); - abs_t thresh = abs_t(m_) * abs_t(vnl_math::eps) * n; + const abs_t recomposition_residual = std::abs((recompose() - M).fro_norm()); + const abs_t n = std::abs(M.fro_norm()); + const abs_t thresh = abs_t(m_) * abs_t(vnl_math::eps) * n; if (recomposition_residual > thresh) { - std::cerr << "vnl_svd::vnl_svd() -- Warning, recomposition_residual = " - << recomposition_residual << std::endl - << "fro_norm(M) = " << n << std::endl - << "eps*fro_norm(M) = " << thresh << std::endl - << "Press return to continue\n"; + std::cerr << "vnl_svd::vnl_svd() -- Warning, recomposition_residual = " << recomposition_residual + << std::endl + << "fro_norm(M) = " << n << std::endl + << "eps*fro_norm(M) = " << thresh << std::endl + << "Press return to continue\n"; char x; std::cin.get(&x, 1, '\n'); } @@ -163,13 +168,16 @@ vnl_svd::vnl_svd(vnl_matrix const& M, double zero_out_tol): } template -std::ostream& operator<<(std::ostream& s, const vnl_svd& svd) +std::ostream & +operator<<(std::ostream & s, const vnl_svd & svd) { s << "vnl_svd:\n" -// << "M = [\n" << M << "]\n" - << "U = [\n" << svd.U() << "]\n" + // << "M = [\n" << M << "]\n" + << "U = [\n" + << svd.U() << "]\n" << "W = " << svd.W() << '\n' - << "V = [\n" << svd.V() << "]\n" + << "V = [\n" + << svd.V() << "]\n" << "rank = " << svd.rank() << std::endl; return s; } @@ -186,36 +194,43 @@ vnl_svd::zero_out_absolute(double tol) rank_ = W_.rows(); for (unsigned k = 0; k < W_.rows(); k++) { - singval_t& weight = W_(k, k); + singval_t & weight = W_(k, k); if (std::abs(weight) <= tol) { - Winverse_(k,k) = 0; + Winverse_(k, k) = 0; weight = 0; --rank_; } else { - Winverse_(k,k) = singval_t(1.0)/weight; + Winverse_(k, k) = singval_t(1.0) / weight; } } } //: find weights below tol*max(w) and zero them out -template void vnl_svd::zero_out_relative(double tol) // sqrt(machine epsilon) +template +void +vnl_svd::zero_out_relative(double tol) // sqrt(machine epsilon) { zero_out_absolute(tol * std::abs(sigma_max())); } -static std::atomic_flag w=ATOMIC_FLAG_INIT; -inline bool vnl_svn_warned() { return std::atomic_flag_test_and_set(&w); } +static std::atomic_flag w = ATOMIC_FLAG_INIT; +inline bool +vnl_svn_warned() +{ + return std::atomic_flag_test_and_set(&w); +} //: Calculate determinant as product of diagonals in W. template -typename vnl_svd::singval_t vnl_svd::determinant_magnitude() const +typename vnl_svd::singval_t +vnl_svd::determinant_magnitude() const { if (!vnl_svn_warned() && m_ != n_) std::cerr << __FILE__ ": called determinant_magnitude() on SVD of non-square matrix\n" - << "(This warning is displayed only once)\n"; + << "(This warning is displayed only once)\n"; singval_t product = W_(0, 0); for (unsigned long k = 1; k < W_.columns(); k++) product *= W_(k, k); @@ -224,34 +239,39 @@ typename vnl_svd::singval_t vnl_svd::determinant_magnitude() const } template -typename vnl_svd::singval_t vnl_svd::norm() const +typename vnl_svd::singval_t +vnl_svd::norm() const { return std::abs(sigma_max()); } //: Recompose SVD to U*W*V' template -vnl_matrix vnl_svd::recompose(unsigned int rnk) const +vnl_matrix +vnl_svd::recompose(unsigned int rnk) const { - if (rnk > rank_) rnk=rank_; - vnl_matrix Wmatr(W_.rows(),W_.columns()); + if (rnk > rank_) + rnk = rank_; + vnl_matrix Wmatr(W_.rows(), W_.columns()); Wmatr.fill(T(0)); - for (unsigned int i=0;i -vnl_matrix vnl_svd::pinverse(unsigned int rnk) const +vnl_matrix +vnl_svd::pinverse(unsigned int rnk) const { - if (rnk > rank_) rnk=rank_; - vnl_matrix W_inverse(Winverse_.rows(),Winverse_.columns()); + if (rnk > rank_) + rnk = rank_; + vnl_matrix W_inverse(Winverse_.rows(), Winverse_.columns()); W_inverse.fill(T(0)); - for (unsigned int i=0;i vnl_svd::pinverse(unsigned int rnk) const //: Calculate (pseudo-)inverse of transpose. template -vnl_matrix vnl_svd::tinverse(unsigned int rnk) const +vnl_matrix +vnl_svd::tinverse(unsigned int rnk) const { - if (rnk > rank_) rnk=rank_; - vnl_matrix W_inverse(Winverse_.rows(),Winverse_.columns()); + if (rnk > rank_) + rnk = rank_; + vnl_matrix W_inverse(Winverse_.rows(), Winverse_.columns()); W_inverse.fill(T(0)); - for (unsigned int i=0;i vnl_svd::tinverse(unsigned int rnk) const //: Solve the matrix equation M X = B, returning X template -vnl_matrix vnl_svd::solve(vnl_matrix const& B) const +vnl_matrix +vnl_svd::solve(const vnl_matrix & B) const { - vnl_matrix x; // solution matrix - if (U_.rows() < U_.columns()) { // augment y with extra rows of - vnl_matrix yy(U_.rows(), B.columns(), T(0)); // zeros, so that it matches - yy.update(B); // cols of u.transpose. ??? + vnl_matrix x; // solution matrix + if (U_.rows() < U_.columns()) + { // augment y with extra rows of + vnl_matrix yy(U_.rows(), B.columns(), T(0)); // zeros, so that it matches + yy.update(B); // cols of u.transpose. ??? x = U_.conjugate_transpose() * yy; } else x = U_.conjugate_transpose() * B; - for (unsigned long i = 0; i < x.rows(); ++i) { // multiply with diagonal 1/W + for (unsigned long i = 0; i < x.rows(); ++i) + { // multiply with diagonal 1/W T weight = W_(i, i); if (weight != T(0)) // vnl_numeric_traits::zero weight = T(1) / weight; for (unsigned long j = 0; j < x.columns(); ++j) x(i, j) *= weight; } - x = V_ * x; // premultiply with v. + x = V_ * x; // premultiply with v. return x; } //: Solve the matrix-vector system M x = y, returning x. template -vnl_vector vnl_svd::solve(vnl_vector const& y) const +vnl_vector +vnl_svd::solve(const vnl_vector & y) const { // fsm sanity check : if (y.size() != U_.rows()) { std::cerr << __FILE__ << ": size of rhs is incompatible with no. of rows in U_\n" - << "y =" << y << '\n' - << "m_=" << m_ << '\n' - << "n_=" << n_ << '\n' - << "U_=\n" << U_ - << "V_=\n" << V_ - << "W_=\n" << W_; + << "y =" << y << '\n' + << "m_=" << m_ << '\n' + << "n_=" << n_ << '\n' + << "U_=\n" + << U_ << "V_=\n" + << V_ << "W_=\n" + << W_; } - vnl_vector x(V_.rows()); // Solution matrix. - if (U_.rows() < U_.columns()) { // Augment y with extra rows of - vnl_vector yy(U_.rows(), T(0)); // zeros, so that it matches - if (yy.size()::solve_preinverted() -- Augmenting y\n"; - vnl_vector yy(U_.rows(), T(0)); // zeros, so that it match - yy.update(y); // cols of u.transpose. ?? + vnl_vector yy(U_.rows(), T(0)); // zeros, so that it match + yy.update(y); // cols of u.transpose. ?? x = U_.conjugate_transpose() * yy; } else x = U_.conjugate_transpose() * y; - for (unsigned i = 0; i < x.size(); i++) // multiply with diagonal W, assumed inverted + for (unsigned i = 0; i < x.size(); i++) // multiply with diagonal W, assumed inverted x[i] *= W_(i, i); - *x_out = V_ * x; // premultiply with v. + *x_out = V_ * x; // premultiply with v. } //----------------------------------------------------------------------------- //: Return N s.t. M * N = 0 template -vnl_matrix vnl_svd::nullspace() const +vnl_matrix +vnl_svd::nullspace() const { - int k = rank(); + const int k = rank(); if (k == n_) std::cerr << "vnl_svd::nullspace() -- Matrix is full rank." << last_tol_ << std::endl; - return nullspace(n_-k); + return nullspace(n_ - k); } //----------------------------------------------------------------------------- //: Return N s.t. M * N = 0 template -vnl_matrix vnl_svd::nullspace(int required_nullspace_dimension) const +vnl_matrix +vnl_svd::nullspace(int required_nullspace_dimension) const { return V_.extract(V_.rows(), required_nullspace_dimension, 0, n_ - required_nullspace_dimension); } @@ -382,18 +417,20 @@ vnl_matrix vnl_svd::nullspace(int required_nullspace_dimension) const //----------------------------------------------------------------------------- //: Return N s.t. M' * N = 0 template -vnl_matrix vnl_svd::left_nullspace() const +vnl_matrix +vnl_svd::left_nullspace() const { - int k = rank(); + const int k = rank(); if (k == n_) std::cerr << "vnl_svd::left_nullspace() -- Matrix is full rank." << last_tol_ << std::endl; - return U_.extract(U_.rows(), n_-k, 0, k); + return U_.extract(U_.rows(), n_ - k, 0, k); } //: // \todo Implementation to be done yet; currently returns left_nullspace(). - PVr. template -vnl_matrix vnl_svd::left_nullspace(int /*required_nullspace_dimension*/) const +vnl_matrix +vnl_svd::left_nullspace(int /*required_nullspace_dimension*/) const { return left_nullspace(); } @@ -404,11 +441,12 @@ vnl_matrix vnl_svd::left_nullspace(int /*required_nullspace_dimension*/) c // Does not check to see whether or not the matrix actually was rank-deficient - // the caller is assumed to have examined W and decided that to his or her satisfaction. template -vnl_vector vnl_svd::nullvector() const +vnl_vector +vnl_svd::nullvector() const { vnl_vector ret(n_); for (int i = 0; i < n_; ++i) - ret(i) = V_(i, n_-1); + ret(i) = V_(i, n_ - 1); return ret; } @@ -416,10 +454,11 @@ vnl_vector vnl_svd::nullvector() const //: Return the rightmost column of U. // Does not check to see whether or not the matrix actually was rank-deficient. template -vnl_vector vnl_svd::left_nullvector() const +vnl_vector +vnl_svd::left_nullvector() const { vnl_vector ret(m_); - int col = std::min(m_, n_) - 1; + const int col = std::min(m_, n_) - 1; for (int i = 0; i < m_; ++i) ret(i) = U_(i, col); return ret; @@ -428,8 +467,8 @@ vnl_vector vnl_svd::left_nullvector() const //-------------------------------------------------------------------------------- #undef VNL_SVD_INSTANTIATE -#define VNL_SVD_INSTANTIATE(T) \ -template class VNL_ALGO_EXPORT vnl_svd; \ -template VNL_ALGO_EXPORT std::ostream& operator<<(std::ostream &, vnl_svd const &) +#define VNL_SVD_INSTANTIATE(T) \ + template class VNL_ALGO_EXPORT vnl_svd; \ + template VNL_ALGO_EXPORT std::ostream & operator<<(std::ostream &, vnl_svd const &) #endif // vnl_svd_hxx_ diff --git a/core/vnl/algo/vnl_svd_economy.h b/core/vnl/algo/vnl_svd_economy.h index b33d14cf9c0..15d7460ebca 100644 --- a/core/vnl/algo/vnl_svd_economy.h +++ b/core/vnl/algo/vnl_svd_economy.h @@ -18,31 +18,52 @@ template class vnl_svd_economy { - public: +public: //: The singular values of a matrix of complex are of type T, not complex typedef typename vnl_numeric_traits::abs_t singval_t; - vnl_svd_economy(vnl_matrix const& M); + vnl_svd_economy(const vnl_matrix & M); //: Return right singular vectors. - vnl_matrix const& V() const { return V_; } - vnl_matrix & V() { return V_; } + const vnl_matrix & + V() const + { + return V_; + } + vnl_matrix & + V() + { + return V_; + } //: Return singular values in decreasing order. - vnl_vector const& lambdas() const { return sv_; } - vnl_vector & lambdas() { return sv_; } + const vnl_vector & + lambdas() const + { + return sv_; + } + vnl_vector & + lambdas() + { + return sv_; + } //: Return the rightmost column of V. - vnl_vector nullvector(); + vnl_vector + nullvector(); - protected: +protected: long m_, n_; - vnl_matrix V_; + vnl_matrix V_; vnl_vector sv_; - private: - vnl_svd_economy( vnl_svd_economy const&) { } - vnl_svd_economy& operator=(vnl_svd_economy const&) { return *this; } +private: + vnl_svd_economy(const vnl_svd_economy &) {} + vnl_svd_economy & + operator=(const vnl_svd_economy &) + { + return *this; + } }; #endif diff --git a/core/vnl/algo/vnl_svd_economy.hxx b/core/vnl/algo/vnl_svd_economy.hxx index 68c26821b0b..eaa2c7d32a9 100644 --- a/core/vnl/algo/vnl_svd_economy.hxx +++ b/core/vnl/algo/vnl_svd_economy.hxx @@ -16,8 +16,7 @@ #include #define macro(p, T) \ -inline void vnl_linpack_svdc_economy(vnl_netlib_svd_proto(T)) \ -{ v3p_netlib_##p##svdc_(vnl_netlib_svd_params); } + inline void vnl_linpack_svdc_economy(vnl_netlib_svd_proto(T)) { v3p_netlib_##p##svdc_(vnl_netlib_svd_params); } macro(s, float); macro(d, double); macro(c, std::complex); @@ -25,32 +24,39 @@ macro(z, std::complex); #undef macro template -vnl_svd_economy::vnl_svd_economy( vnl_matrix const& M ) : - m_(M.rows()), n_(M.columns()), - V_(n_,n_), - sv_(n_) +vnl_svd_economy::vnl_svd_economy(vnl_matrix const & M) + : m_(M.rows()) + , n_(M.columns()) + , V_(n_, n_) + , sv_(n_) { vnl_fortran_copy X(M); - int mm = std::min(m_+1L,n_); + const int mm = std::min(m_ + 1L, n_); // Make workspace vectors. vnl_vector work(m_, real_t(0)); - vnl_vector vspace(n_*n_, real_t(0)); + vnl_vector vspace(n_ * n_, real_t(0)); vnl_vector wspace(mm, real_t(0)); // complex fortran routine actually _wants_ complex W! vnl_vector espace(n_, real_t(0)); // Call Linpack SVD - long ldu = 0; + const long ldu = 0; long info = 0; constexpr long job = 01; // no U, n svs in V (i.e. super-economy size) - vnl_linpack_svdc_economy((real_t*)X, &m_, &m_, &n_, + vnl_linpack_svdc_economy((real_t *)X, + &m_, + &m_, + &n_, wspace.data_block(), espace.data_block(), - nullptr, &ldu, - vspace.data_block(), &n_, + nullptr, + &ldu, + vspace.data_block(), + &n_, work.data_block(), - &job, &info); + &job, + &info); // Error return? if (info != 0) @@ -83,7 +89,7 @@ vnl_svd_economy::vnl_svd_economy( vnl_matrix const& M ) : // // You may be able to diagnose the problem here by printing a warning message. std::cerr << __FILE__ ": suspicious return value (" << info << ") from SVDC\n" - << __FILE__ ": M is " << M.rows() << 'x' << M.cols() << std::endl; + << __FILE__ ": M is " << M.rows() << 'x' << M.cols() << std::endl; vnl_matlab_print(std::cerr, M, "M", vnl_matlab_print_format_long); // valid_ = false; @@ -96,7 +102,7 @@ vnl_svd_economy::vnl_svd_economy( vnl_matrix const& M ) : sv_[j] = 0; { - const real_t *d = vspace.data_block(); + const real_t * d = vspace.data_block(); for (int j = 0; j < n_; ++j) for (int i = 0; i < n_; ++i) V_[i][j] = *(d++); @@ -107,12 +113,11 @@ template vnl_vector vnl_svd_economy::nullvector() { - return V_.get_column( n_ - 1 ); + return V_.get_column(n_ - 1); } #undef VNL_SVD_ECONOMY_INSTANTIATE -#define VNL_SVD_ECONOMY_INSTANTIATE(T) \ -template class VNL_ALGO_EXPORT vnl_svd_economy +#define VNL_SVD_ECONOMY_INSTANTIATE(T) template class VNL_ALGO_EXPORT vnl_svd_economy #endif // vnl_svd_economy_hxx_ diff --git a/core/vnl/algo/vnl_svd_fixed.h b/core/vnl/algo/vnl_svd_fixed.h index daf274d85ba..061b294b19a 100644 --- a/core/vnl/algo/vnl_svd_fixed.h +++ b/core/vnl/algo/vnl_svd_fixed.h @@ -35,7 +35,7 @@ template class vnl_svd_fixed { - public: +public: //: The singular values of a matrix of complex are of type T, not complex typedef typename vnl_numeric_traits::abs_t singval_t; @@ -54,127 +54,224 @@ class vnl_svd_fixed // absolute value is set to zero. If zero_out_tol is negative, the // zeroing is relative to |zero_out_tol| * sigma_max(); - vnl_svd_fixed(vnl_matrix_fixed const &M, double zero_out_tol = 0.0); - ~vnl_svd_fixed() = default; + vnl_svd_fixed(const vnl_matrix_fixed & M, double zero_out_tol = 0.0); + ~vnl_svd_fixed() = default; // Data Access--------------------------------------------------------------- //: find weights below threshold tol, zero them out, and update W_ and Winverse_ - void zero_out_absolute(double tol = 1e-8); //sqrt(machine epsilon) + void + zero_out_absolute(double tol = 1e-8); // sqrt(machine epsilon) //: find weights below tol*max(w) and zero them out - void zero_out_relative(double tol = 1e-8); //sqrt(machine epsilon) - int singularities () const { return W_.rows() - rank(); } - unsigned int rank () const { return rank_; } - singval_t well_condition () const { return sigma_min()/sigma_max(); } + void + zero_out_relative(double tol = 1e-8); // sqrt(machine epsilon) + int + singularities() const + { + return W_.rows() - rank(); + } + unsigned int + rank() const + { + return rank_; + } + singval_t + well_condition() const + { + return sigma_min() / sigma_max(); + } //: Calculate determinant as product of diagonals in W. - singval_t determinant_magnitude () const; - singval_t norm() const; + singval_t + determinant_magnitude() const; + singval_t + norm() const; //: Return the matrix U. - vnl_matrix_fixed & U() { return U_; } + vnl_matrix_fixed & + U() + { + return U_; + } //: Return the matrix U. - vnl_matrix_fixed const& U() const { return U_; } + const vnl_matrix_fixed & + U() const + { + return U_; + } //: Return the matrix U's (i,j)th entry (to avoid svd.U()(i,j); ). - T U(int i, int j) const { return U_(i,j); } + T + U(int i, int j) const + { + return U_(i, j); + } //: Get at DiagMatrix (q.v.) of singular values, sorted from largest to smallest - vnl_diag_matrix_fixed & W() { return W_; } + vnl_diag_matrix_fixed & + W() + { + return W_; + } //: Get at DiagMatrix (q.v.) of singular values, sorted from largest to smallest - vnl_diag_matrix_fixed const & W() const { return W_; } - vnl_diag_matrix_fixed & Winverse() { return Winverse_; } - vnl_diag_matrix_fixed const & Winverse() const { return Winverse_; } - singval_t & W(int i, int j) { return W_(i,j); } - singval_t & W(int i) { return W_(i,i); } - singval_t sigma_max() const { return W_(0,0); } // largest - singval_t sigma_min() const { return W_(C-1,C-1); } // smallest + const vnl_diag_matrix_fixed & + W() const + { + return W_; + } + vnl_diag_matrix_fixed & + Winverse() + { + return Winverse_; + } + const vnl_diag_matrix_fixed & + Winverse() const + { + return Winverse_; + } + singval_t & + W(int i, int j) + { + return W_(i, j); + } + singval_t & + W(int i) + { + return W_(i, i); + } + singval_t + sigma_max() const + { + return W_(0, 0); + } // largest + singval_t + sigma_min() const + { + return W_(C - 1, C - 1); + } // smallest //: Return the matrix V. - vnl_matrix_fixed & V() { return V_; } + vnl_matrix_fixed & + V() + { + return V_; + } //: Return the matrix V. - vnl_matrix_fixed const& V() const { return V_; } + const vnl_matrix_fixed & + V() const + { + return V_; + } //: Return the matrix V's (i,j)th entry (to avoid svd.V()(i,j); ). - T V(int i, int j) const { return V_(i,j); } + T + V(int i, int j) const + { + return V_(i, j); + } //: - inline vnl_matrix_fixed inverse () const { return pinverse(); } + inline vnl_matrix_fixed + inverse() const + { + return pinverse(); + } //: pseudo-inverse (for non-square matrix) of desired rank. - vnl_matrix_fixed pinverse (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 + vnl_matrix_fixed + pinverse(unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 //: Calculate inverse of transpose, using desired rank. - vnl_matrix_fixed tinverse (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 + vnl_matrix_fixed + tinverse(unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 //: Recompose SVD to U*W*V', using desired rank. - vnl_matrix_fixed recompose (unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 + vnl_matrix_fixed + recompose(unsigned int rank = ~0u) const; // ~0u == (unsigned int)-1 //: Solve the matrix equation M X = B, returning X - vnl_matrix solve (vnl_matrix const& B) const; + vnl_matrix + solve(const vnl_matrix & B) const; //: Solve the matrix-vector system M x = y, returning x. - vnl_vector_fixed solve (vnl_vector_fixed const& y) const; - void solve (T const *rhs, T *lhs) const; // min ||A*lhs - rhs|| + vnl_vector_fixed + solve(const vnl_vector_fixed & y) const; + void + solve(const T * rhs, T * lhs) const; // min ||A*lhs - rhs|| //: Solve the matrix-vector system M x = y. // Assuming that the singular values W have been preinverted by the caller. - void solve_preinverted(vnl_vector_fixed const& rhs, vnl_vector_fixed* out) const; + void + solve_preinverted(const vnl_vector_fixed & rhs, vnl_vector_fixed * out) const; //: Return N such that M * N = 0 - vnl_matrix nullspace() const; + vnl_matrix + nullspace() const; //: Return N such that M' * N = 0 - vnl_matrix left_nullspace() const; + vnl_matrix + left_nullspace() const; //: Return N such that M * N = 0 - vnl_matrix nullspace(int required_nullspace_dimension) const; + vnl_matrix + nullspace(int required_nullspace_dimension) const; //: Implementation to be done yet; currently returns left_nullspace(). - PVR. - vnl_matrix left_nullspace(int required_nullspace_dimension) const; + vnl_matrix + left_nullspace(int required_nullspace_dimension) const; //: Return the rightmost column of V. // Does not check to see whether or not the matrix actually was rank-deficient - // the caller is assumed to have examined W and decided that to his or her satisfaction. - vnl_vector_fixed nullvector() const; + vnl_vector_fixed + nullvector() const; //: Return the rightmost column of U. // Does not check to see whether or not the matrix actually was rank-deficient. - vnl_vector_fixed left_nullvector() const; - - bool valid() const { return valid_; } - - private: - - vnl_matrix_fixed U_; // Columns Ui are basis for range of M for Wi != 0 - vnl_diag_matrix_fixed W_;// Singular values, sorted in decreasing order + vnl_vector_fixed + left_nullvector() const; + + bool + valid() const + { + return valid_; + } + +private: + vnl_matrix_fixed U_; // Columns Ui are basis for range of M for Wi != 0 + vnl_diag_matrix_fixed W_; // Singular values, sorted in decreasing order vnl_diag_matrix_fixed Winverse_; - vnl_matrix_fixed V_; // Columns Vi are basis for nullspace of M for Wi = 0 + vnl_matrix_fixed V_; // Columns Vi are basis for nullspace of M for Wi = 0 unsigned rank_; bool have_max_; singval_t max_; bool have_min_; singval_t min_; double last_tol_; - bool valid_; // false if the NETLIB call failed. + bool valid_; // false if the NETLIB call failed. // Disallow assignment. - vnl_svd_fixed(vnl_svd_fixed const &) { } - vnl_svd_fixed& operator=(vnl_svd_fixed const &) { return *this; } + vnl_svd_fixed(const vnl_svd_fixed &) {} + vnl_svd_fixed & + operator=(const vnl_svd_fixed &) + { + return *this; + } }; template -inline -vnl_matrix_fixed vnl_svd_fixed_inverse(vnl_matrix_fixed const& m) +inline vnl_matrix_fixed +vnl_svd_fixed_inverse(const vnl_matrix_fixed & m) { - return vnl_svd_fixed(m).inverse(); + return vnl_svd_fixed(m).inverse(); } template -std::ostream& operator<<(std::ostream&, vnl_svd_fixed const& svd); +std::ostream & +operator<<(std::ostream &, const vnl_svd_fixed & svd); #endif // vnl_svd_fixed_h_ diff --git a/core/vnl/algo/vnl_svd_fixed.hxx b/core/vnl/algo/vnl_svd_fixed.hxx index 9e0c2aa4cb9..7076c2f368a 100644 --- a/core/vnl/algo/vnl_svd_fixed.hxx +++ b/core/vnl/algo/vnl_svd_fixed.hxx @@ -21,8 +21,7 @@ // use C++ overloading to call the right linpack routine from the template code : #define macro(p, T) \ -inline void vnl_linpack_svdc_fixed(vnl_netlib_svd_proto(T)) \ -{ v3p_netlib_##p##svdc_(vnl_netlib_svd_params); } + inline void vnl_linpack_svdc_fixed(vnl_netlib_svd_proto(T)) { v3p_netlib_##p##svdc_(vnl_netlib_svd_params); } macro(s, float); macro(d, double); macro(c, std::complex); @@ -35,33 +34,40 @@ static bool vnl_svd_fixed_test_heavily = false; #include template -vnl_svd_fixed::vnl_svd_fixed(vnl_matrix_fixed const& M, double zero_out_tol) +vnl_svd_fixed::vnl_svd_fixed(vnl_matrix_fixed const & M, double zero_out_tol) { { - const long n=R, p=C; - const unsigned mm = std::min(R+1u,C); + const long n = R; + const long p = C; + const unsigned mm = std::min(R + 1u, C); // Copy source matrix into fortran storage // SVD is slow, don't worry about the cost of this transpose. - vnl_fortran_copy_fixed X(M); + vnl_fortran_copy_fixed X(M); // Make workspace vectors. vnl_vector_fixed work(T(0)); - vnl_vector_fixed uspace(T(0)); - vnl_vector_fixed vspace(T(0)); - vnl_vector_fixed wspace(T(0)); // complex fortran routine actually _wants_ complex W! + vnl_vector_fixed uspace(T(0)); + vnl_vector_fixed vspace(T(0)); + vnl_vector_fixed wspace(T(0)); // complex fortran routine actually _wants_ complex W! vnl_vector_fixed espace(T(0)); // Call Linpack SVD long info = 0; constexpr long job = 21; // min(n,p) svs in U, n svs in V (i.e. economy size) - vnl_linpack_svdc_fixed((T*)X, &n, &n, &p, + vnl_linpack_svdc_fixed((T *)X, + &n, + &n, + &p, wspace.data_block(), espace.data_block(), - uspace.data_block(), &n, - vspace.data_block(), &p, + uspace.data_block(), + &n, + vspace.data_block(), + &p, work.data_block(), - &job, &info); + &job, + &info); // Error return? if (info != 0) @@ -94,7 +100,7 @@ vnl_svd_fixed::vnl_svd_fixed(vnl_matrix_fixed const& M, double zer // // You may be able to diagnose the problem here by printing a warning message. std::cerr << __FILE__ ": suspicious return value (" << info << ") from SVDC\n" - << __FILE__ ": M is " << M.rows() << 'x' << M.cols() << std::endl; + << __FILE__ ": M is " << M.rows() << 'x' << M.cols() << std::endl; vnl_matlab_print(std::cerr, M, "M", vnl_matlab_print_format_long); valid_ = false; @@ -104,10 +110,10 @@ vnl_svd_fixed::vnl_svd_fixed(vnl_matrix_fixed const& M, double zer // Copy fortran outputs into our storage { - const T *d = uspace.data_block(); + const T * d = uspace.data_block(); for (long j = 0; j < p; ++j) for (long i = 0; i < n; ++i) - U_(i,j) = *d++; + U_(i, j) = *d++; } for (unsigned j = 0; j < mm; ++j) @@ -117,10 +123,10 @@ vnl_svd_fixed::vnl_svd_fixed(vnl_matrix_fixed const& M, double zer W_(j, j) = 0; { - const T *d = vspace.data_block(); + const T * d = vspace.data_block(); for (unsigned j = 0; j < C; ++j) for (unsigned i = 0; i < C; ++i) - V_(i,j) = *d++; + V_(i, j) = *d++; } } @@ -128,16 +134,16 @@ vnl_svd_fixed::vnl_svd_fixed(vnl_matrix_fixed const& M, double zer { // Test that recomposed matrix == M typedef typename vnl_numeric_traits::abs_t abs_t; - abs_t recomposition_residual = std::abs((recompose() - M).fro_norm()); - abs_t n = std::abs(M.fro_norm()); - abs_t thresh = abs_t(R) * abs_t(vnl_math::eps) * n; + const abs_t recomposition_residual = std::abs((recompose() - M).fro_norm()); + const abs_t n = std::abs(M.fro_norm()); + const abs_t thresh = abs_t(R) * abs_t(vnl_math::eps) * n; if (recomposition_residual > thresh) { std::cerr << "vnl_svd_fixed::vnl_svd_fixed() -- Warning, recomposition_residual = " - << recomposition_residual << std::endl - << "fro_norm(M) = " << n << std::endl - << "eps*fro_norm(M) = " << thresh << std::endl - << "Press return to continue\n"; + << recomposition_residual << std::endl + << "fro_norm(M) = " << n << std::endl + << "eps*fro_norm(M) = " << thresh << std::endl + << "Press return to continue\n"; char x; std::cin.get(&x, 1, '\n'); } @@ -152,12 +158,15 @@ vnl_svd_fixed::vnl_svd_fixed(vnl_matrix_fixed const& M, double zer } template -std::ostream& operator<<(std::ostream& s, const vnl_svd_fixed& svd) +std::ostream & +operator<<(std::ostream & s, const vnl_svd_fixed & svd) { s << "vnl_svd_fixed:\n" - << "U = [\n" << svd.U() << "]\n" + << "U = [\n" + << svd.U() << "]\n" << "W = " << svd.W() << '\n' - << "V = [\n" << svd.V() << "]\n" + << "V = [\n" + << svd.V() << "]\n" << "rank = " << svd.rank() << std::endl; return s; } @@ -167,43 +176,56 @@ std::ostream& operator<<(std::ostream& s, const vnl_svd_fixed& svd) //: find weights below threshold tol, zero them out, and update W_ and Winverse_ template -void vnl_svd_fixed::zero_out_absolute(double tol) +void +vnl_svd_fixed::zero_out_absolute(double tol) { last_tol_ = tol; rank_ = C; for (unsigned k = 0; k < C; k++) { - singval_t& weight = W_(k, k); + singval_t & weight = W_(k, k); if (std::abs(weight) <= tol) { - Winverse_(k,k) = 0; + Winverse_(k, k) = 0; weight = 0; --rank_; } else { - Winverse_(k,k) = singval_t(1.0)/weight; + Winverse_(k, k) = singval_t(1.0) / weight; } } } //: find weights below tol*max(w) and zero them out template -void vnl_svd_fixed::zero_out_relative(double tol) // sqrt(machine epsilon) +void +vnl_svd_fixed::zero_out_relative(double tol) // sqrt(machine epsilon) { zero_out_absolute(tol * std::abs(sigma_max())); } -static bool wf=false; -inline bool warned_f() { if (wf) return true; else { wf=true; return false; } } +static bool wf = false; +inline bool +warned_f() +{ + if (wf) + return true; + else + { + wf = true; + return false; + } +} //: Calculate determinant as product of diagonals in W. template -typename vnl_svd_fixed::singval_t vnl_svd_fixed::determinant_magnitude() const +typename vnl_svd_fixed::singval_t +vnl_svd_fixed::determinant_magnitude() const { if (!warned_f() && R != C) std::cerr << __FILE__ ": called determinant_magnitude() on SVD of non-square matrix\n" - << "(This warning is displayed only once)\n"; + << "(This warning is displayed only once)\n"; singval_t product = W_(0, 0); for (unsigned long k = 1; k < C; k++) product *= W_(k, k); @@ -212,32 +234,37 @@ typename vnl_svd_fixed::singval_t vnl_svd_fixed::determinant_magni } template -typename vnl_svd_fixed::singval_t vnl_svd_fixed::norm() const +typename vnl_svd_fixed::singval_t +vnl_svd_fixed::norm() const { return std::abs(sigma_max()); } //: Recompose SVD to U*W*V' template -vnl_matrix_fixed vnl_svd_fixed::recompose(unsigned int rnk) const +vnl_matrix_fixed +vnl_svd_fixed::recompose(unsigned int rnk) const { - if (rnk > rank_) rnk=rank_; - vnl_diag_matrix_fixed Wmatr(W_); - for (unsigned int i=rnk;i rank_) + rnk = rank_; + vnl_diag_matrix_fixed Wmatr(W_); + for (unsigned int i = rnk; i < C; ++i) + Wmatr(i, i) = 0; - return U_*Wmatr*V_.conjugate_transpose(); + return U_ * Wmatr * V_.conjugate_transpose(); } //: Calculate pseudo-inverse. template -vnl_matrix_fixed vnl_svd_fixed::pinverse(unsigned int rnk) const +vnl_matrix_fixed +vnl_svd_fixed::pinverse(unsigned int rnk) const { - if (rnk > rank_) rnk=rank_; - vnl_diag_matrix_fixed W_inverse(Winverse_); - for (unsigned int i=rnk;i rank_) + rnk = rank_; + vnl_diag_matrix_fixed W_inverse(Winverse_); + for (unsigned int i = rnk; i < C; ++i) + W_inverse(i, i) = 0; return V_ * W_inverse * U_.conjugate_transpose(); } @@ -245,12 +272,14 @@ vnl_matrix_fixed vnl_svd_fixed::pinverse(unsigned int rnk) const //: Calculate (pseudo-)inverse of transpose. template -vnl_matrix_fixed vnl_svd_fixed::tinverse(unsigned int rnk) const +vnl_matrix_fixed +vnl_svd_fixed::tinverse(unsigned int rnk) const { - if (rnk > rank_) rnk=rank_; - vnl_diag_matrix_fixed W_inverse(Winverse_); - for (unsigned int i=rnk;i rank_) + rnk = rank_; + vnl_diag_matrix_fixed W_inverse(Winverse_); + for (unsigned int i = rnk; i < C; ++i) + W_inverse(i, i) = 0; return U_ * W_inverse * V_.conjugate_transpose(); } @@ -258,46 +287,53 @@ vnl_matrix_fixed vnl_svd_fixed::tinverse(unsigned int rnk) const //: Solve the matrix equation M X = B, returning X template -vnl_matrix vnl_svd_fixed::solve(vnl_matrix const& B) const +vnl_matrix +vnl_svd_fixed::solve(const vnl_matrix & B) const { - vnl_matrix x; // solution matrix - if (U_.rows() < U_.columns()) { // augment y with extra rows of - vnl_matrix yy(U_.rows(), B.columns(), T(0)); // zeros, so that it matches - yy.update(B); // cols of u.transpose. ??? + vnl_matrix x; // solution matrix + if (U_.rows() < U_.columns()) + { // augment y with extra rows of + vnl_matrix yy(U_.rows(), B.columns(), T(0)); // zeros, so that it matches + yy.update(B); // cols of u.transpose. ??? x = U_.conjugate_transpose() * yy; } else x = U_.conjugate_transpose() * B; - for (unsigned long i = 0; i < x.rows(); ++i) { // multiply with diagonal 1/W + for (unsigned long i = 0; i < x.rows(); ++i) + { // multiply with diagonal 1/W T weight = W_(i, i); if (weight != T(0)) // vnl_numeric_traits::zero weight = T(1) / weight; for (unsigned long j = 0; j < x.columns(); ++j) x(i, j) *= weight; } - x = V_ * x; // premultiply with v. + x = V_ * x; // premultiply with v. return x; } //: Solve the matrix-vector system M x = y, returning x. template -vnl_vector_fixed vnl_svd_fixed::solve(vnl_vector_fixed const& y) const +vnl_vector_fixed +vnl_svd_fixed::solve(const vnl_vector_fixed & y) const { - vnl_vector_fixed x; // Solution matrix. + vnl_vector_fixed x; // Solution matrix. x = U_.conjugate_transpose() * y; - for (unsigned i = 0; i < C; i++) { // multiply with diagonal 1/W - T weight = W_(i, i), zero_(0); + for (unsigned i = 0; i < C; i++) + { // multiply with diagonal 1/W + T weight = W_(i, i); + T zero_(0); if (weight != zero_) x[i] /= weight; else x[i] = zero_; } - return V_ * x; // premultiply with v. + return V_ * x; // premultiply with v. } template // FIXME. this should implement the above, not the other way round. -void vnl_svd_fixed::solve(T const *y, T *x) const +void +vnl_svd_fixed::solve(const T * y, T * x) const { solve(vnl_vector_fixed(y)).copy_out(x); } @@ -305,31 +341,34 @@ void vnl_svd_fixed::solve(T const *y, T *x) const //: Solve the matrix-vector system M x = y. // Assume that the singular values W have been preinverted by the caller. template -void vnl_svd_fixed::solve_preinverted(vnl_vector_fixed const& y, vnl_vector_fixed* x_out) const +void +vnl_svd_fixed::solve_preinverted(const vnl_vector_fixed & y, vnl_vector_fixed * x_out) const { - vnl_vector_fixed x; // solution matrix + vnl_vector_fixed x; // solution matrix x = U_.conjugate_transpose() * y; - for (unsigned i = 0; i < C; i++) // multiply with diagonal W, assumed inverted + for (unsigned i = 0; i < C; i++) // multiply with diagonal W, assumed inverted x[i] *= W_(i, i); - *x_out = V_ * x; // premultiply with v. + *x_out = V_ * x; // premultiply with v. } //----------------------------------------------------------------------------- //: Return N s.t. M * N = 0 template -vnl_matrix vnl_svd_fixed::nullspace() const +vnl_matrix +vnl_svd_fixed::nullspace() const { - int k = rank(); + const int k = rank(); if (k == C) std::cerr << "vnl_svd_fixed::nullspace() -- Matrix is full rank." << last_tol_ << std::endl; - return nullspace(C-k); + return nullspace(C - k); } //----------------------------------------------------------------------------- //: Return N s.t. M * N = 0 template -vnl_matrix vnl_svd_fixed::nullspace(int required_nullspace_dimension) const +vnl_matrix +vnl_svd_fixed::nullspace(int required_nullspace_dimension) const { return V_.extract(V_.rows(), required_nullspace_dimension, 0, C - required_nullspace_dimension); } @@ -337,18 +376,20 @@ vnl_matrix vnl_svd_fixed::nullspace(int required_nullspace_dimension) //----------------------------------------------------------------------------- //: Return N s.t. M' * N = 0 template -vnl_matrix vnl_svd_fixed::left_nullspace() const +vnl_matrix +vnl_svd_fixed::left_nullspace() const { - int k = rank(); + const int k = rank(); if (k == C) std::cerr << "vnl_svd_fixed::left_nullspace() -- Matrix is full rank." << last_tol_ << std::endl; - return U_.extract(U_.rows(), C-k, 0, k); + return U_.extract(U_.rows(), C - k, 0, k); } //: // \todo Implementation to be done yet; currently returns left_nullspace(). - PVr. template -vnl_matrix vnl_svd_fixed::left_nullspace(int /*required_nullspace_dimension*/) const +vnl_matrix +vnl_svd_fixed::left_nullspace(int /*required_nullspace_dimension*/) const { return left_nullspace(); } @@ -359,11 +400,12 @@ vnl_matrix vnl_svd_fixed::left_nullspace(int /*required_nullspace_dime // Does not check to see whether or not the matrix actually was rank-deficient - // the caller is assumed to have examined W and decided that to his or her satisfaction. template -vnl_vector_fixed vnl_svd_fixed::nullvector() const +vnl_vector_fixed +vnl_svd_fixed::nullvector() const { vnl_vector_fixed ret; for (unsigned i = 0; i < C; ++i) - ret(i) = V_(i, C-1); + ret(i) = V_(i, C - 1); return ret; } @@ -371,9 +413,10 @@ vnl_vector_fixed vnl_svd_fixed::nullvector() const //: Return the rightmost column of U. // Does not check to see whether or not the matrix actually was rank-deficient. template -vnl_vector_fixed vnl_svd_fixed::left_nullvector() const +vnl_vector_fixed +vnl_svd_fixed::left_nullvector() const { - vnl_vector_fixed ret; + vnl_vector_fixed ret; const unsigned col = std::min(R, C) - 1; for (unsigned i = 0; i < R; ++i) ret(i) = U_(i, col); @@ -383,8 +426,8 @@ vnl_vector_fixed vnl_svd_fixed::left_nullvector() const //-------------------------------------------------------------------------------- #undef VNL_SVD_FIXED_INSTANTIATE -#define VNL_SVD_FIXED_INSTANTIATE(T , R , C ) \ -template class VNL_ALGO_EXPORT vnl_svd_fixed; \ -template VNL_ALGO_EXPORT std::ostream& operator<<(std::ostream &, vnl_svd_fixed const &) +#define VNL_SVD_FIXED_INSTANTIATE(T, R, C) \ + template class VNL_ALGO_EXPORT vnl_svd_fixed; \ + template VNL_ALGO_EXPORT std::ostream & operator<<(std::ostream &, vnl_svd_fixed const &) #endif // vnl_svd_fixed_hxx_ diff --git a/core/vnl/algo/vnl_symmetric_eigensystem.h b/core/vnl/algo/vnl_symmetric_eigensystem.h index 7e90f206378..cda24193cbe 100644 --- a/core/vnl/algo/vnl_symmetric_eigensystem.h +++ b/core/vnl/algo/vnl_symmetric_eigensystem.h @@ -61,33 +61,29 @@ // M13 M23 M33 // \endverbatim template -void vnl_symmetric_eigensystem_compute_eigenvals( - T M11, T M12, T M13, - T M22, T M23, - T M33, - T &l1, T &l2, T &l3); +void +vnl_symmetric_eigensystem_compute_eigenvals(T M11, T M12, T M13, T M22, T M23, T M33, T & l1, T & l2, T & l3); //: Find eigenvalues of a symmetric matrix template -bool vnl_symmetric_eigensystem_compute(vnl_matrix const & A, - vnl_matrix & V, - vnl_vector & D); +bool +vnl_symmetric_eigensystem_compute(const vnl_matrix & A, vnl_matrix & V, vnl_vector & D); //: Computes and stores the eigensystem decomposition of a symmetric matrix. template class vnl_symmetric_eigensystem { - public: +public: //: Solve real symmetric eigensystem $A x = \lambda x$ - vnl_symmetric_eigensystem(vnl_matrix const & M); + vnl_symmetric_eigensystem(const vnl_matrix & M); - protected: +protected: // need this here to get inits in correct order, but still keep gentex // in the right order. int n_; - public: +public: //: Public eigenvectors. // After construction, the columns of V are the eigenvectors, sorted by // increasing eigenvalue, from most negative to most positive. @@ -99,14 +95,20 @@ class vnl_symmetric_eigensystem vnl_diag_matrix D; //: Recover specified eigenvector after computation. - vnl_vector get_eigenvector(int i) const; + vnl_vector + get_eigenvector(int i) const; //: Recover specified eigenvalue after computation. - T get_eigenvalue(int i) const; + T + get_eigenvalue(int i) const; //: Convenience method to get least-squares nullvector. // It is deliberate that the signature is the same as on vnl_svd. - vnl_vector nullvector() const { return get_eigenvector(0); } + vnl_vector + nullvector() const + { + return get_eigenvector(0); + } //: Return the matrix $V D V^\top$. // This can be useful if you've modified $D$. So an inverse is obtained using @@ -116,28 +118,40 @@ class vnl_symmetric_eigensystem // vnl_matrix Ainverse = eig.recompose(); // \endcode - vnl_matrix recompose() const { return V * D * V.transpose(); } + vnl_matrix + recompose() const + { + return V * D * V.transpose(); + } //: return product of eigenvalues. - T determinant() const; + T + determinant() const; //: return the pseudoinverse. - vnl_matrix pinverse() const; + vnl_matrix + pinverse() const; //: return the square root, if positive semi-definite. - vnl_matrix square_root() const; + vnl_matrix + square_root() const; //: return the inverse of the square root, if positive semi-definite. - vnl_matrix inverse_square_root() const; + vnl_matrix + inverse_square_root() const; //: Solve LS problem M x = b - vnl_vector solve(vnl_vector const & b); + vnl_vector + solve(const vnl_vector & b); //: Solve LS problem M x = b - void solve(vnl_vector const & b, vnl_vector * x) { *x = solve(b); } + void + solve(const vnl_vector & b, vnl_vector * x) + { + *x = solve(b); + } }; -#define VNL_SYMMETRIC_EIGENSYSTEM_INSTANTIATE(T) \ -extern "please include vnl/algo/vnl_symmetric_eigensystem.hxx first" +#define VNL_SYMMETRIC_EIGENSYSTEM_INSTANTIATE(T) extern "please include vnl/algo/vnl_symmetric_eigensystem.hxx first" #endif // vnl_symmetric_eigensystem_h_ diff --git a/core/vnl/algo/vnl_symmetric_eigensystem.hxx b/core/vnl/algo/vnl_symmetric_eigensystem.hxx index 7900d1568f9..aac662002ca 100644 --- a/core/vnl/algo/vnl_symmetric_eigensystem.hxx +++ b/core/vnl/algo/vnl_symmetric_eigensystem.hxx @@ -28,31 +28,28 @@ // M13 M23 M33 // \endverbatim template -void vnl_symmetric_eigensystem_compute_eigenvals( - T M11, T M12, T M13, - T M22, T M23, - T M33, - T &l1, T &l2, T &l3) +void +vnl_symmetric_eigensystem_compute_eigenvals(T M11, T M12, T M13, T M22, T M23, T M33, T & l1, T & l2, T & l3) { // Characteristic eqtn |M - xI| = 0 // x^3 + b x^2 + c x + d = 0 - const T b = -M11-M22-M33; - const T c = M11*M22 +M11*M33 +M22*M33 -M12*M12 -M13*M13 -M23*M23; - const T d = M11*M23*M23 +M12*M12*M33 +M13*M13*M22 -2*M12*M13*M23 -M11*M22*M33; + const T b = -M11 - M22 - M33; + const T c = M11 * M22 + M11 * M33 + M22 * M33 - M12 * M12 - M13 * M13 - M23 * M23; + const T d = M11 * M23 * M23 + M12 * M12 * M33 + M13 * M13 * M22 - 2 * M12 * M13 * M23 - M11 * M22 * M33; // Using a numerically tweaked version of the real cubic solver http://www.1728.com/cubic2.htm - const T b_3 = b/3; - const T f = b_3*b_3 - c/3 ; - const T g = b*c/6 - b_3*b_3*b_3 - d/2; + const T b_3 = b / 3; + const T f = b_3 * b_3 - c / 3; + const T g = b * c / 6 - b_3 * b_3 * b_3 - d / 2; if (f == 0 && g == 0) { - l1 = l2 = l3 = - b_3 ; + l1 = l2 = l3 = -b_3; return; } - const T f3 = f*f*f; - const T g2 = g*g; + const T f3 = f * f * f; + const T g2 = g * g; const T sqrt_f = -std::sqrt(f); // deal explicitly with repeated root and treat @@ -65,12 +62,12 @@ void vnl_symmetric_eigensystem_compute_eigenvals( { if (g < 0) { - l1 = 2 * sqrt_f - b_3; - l2 = l3 = - sqrt_f - b_3; + l1 = 2 * sqrt_f - b_3; + l2 = l3 = -sqrt_f - b_3; } else { - l1 = l2 = sqrt_f - b_3; + l1 = l2 = sqrt_f - b_3; l3 = -2 * sqrt_f - b_3; } return; @@ -84,18 +81,19 @@ void vnl_symmetric_eigensystem_compute_eigenvals( l2 = j * std::cos(k + T(vnl_math::twopi / 3.0)) - b_3; l3 = j * std::cos(k - T(vnl_math::twopi / 3.0)) - b_3; - if (l2 < l1) std::swap(l2, l1); + if (l2 < l1) + std::swap(l2, l1); if (l3 < l2) { std::swap(l2, l3); - if (l2 < l1) std::swap(l2, l1); + if (l2 < l1) + std::swap(l2, l1); } } template -bool vnl_symmetric_eigensystem_compute(vnl_matrix const & A, - vnl_matrix & V, - vnl_vector & D) +bool +vnl_symmetric_eigensystem_compute(const vnl_matrix & A, vnl_matrix & V, vnl_vector & D) { A.assert_finite(); const long n = A.rows(); @@ -105,31 +103,33 @@ bool vnl_symmetric_eigensystem_compute(vnl_matrix const & A, D.set_size(n); // convert to double - vnl_matrix Ad(A.rows(), A.cols()); vnl_copy(A, Ad); + vnl_matrix Ad(A.rows(), A.cols()); + vnl_copy(A, Ad); vnl_vector Dd(D.size()); vnl_vector work1(n); vnl_vector work2(n); - vnl_vector Vvec(n*n); + vnl_vector Vvec(n * n); - long want_eigenvectors = 1; - long ierr = 0; + const long want_eigenvectors = 1; + const long ierr = 0; // No need to transpose A, 'cos it's symmetric... v3p_netlib_rs_(&n, &n, Ad.data_block(), &Dd[0], &want_eigenvectors, &Vvec[0], &work1[0], &work2[0], &ierr); vnl_copy(Dd, D); - if (ierr) { + if (ierr) + { std::cerr << "vnl_symmetric_eigensystem: ierr = " << ierr << '\n'; return false; } // Transpose-copy into V, which is first resized if necessary if (V.rows() != A.rows() || V.cols() != A.rows()) - V.set_size(n,n); - double *vptr = &Vvec[0]; + V.set_size(n, n); + double * vptr = &Vvec[0]; for (int c = 0; c < n; ++c) for (int r = 0; r < n; ++r) - V(r,c) = T(*vptr++); + V(r, c) = T(*vptr++); return true; } @@ -138,8 +138,10 @@ bool vnl_symmetric_eigensystem_compute(vnl_matrix const & A, // - @{ Solve real symmetric eigensystem $A x = \lambda x$ @} template -vnl_symmetric_eigensystem::vnl_symmetric_eigensystem(vnl_matrix const& A) - : n_(A.rows()), V(n_, n_), D(n_) +vnl_symmetric_eigensystem::vnl_symmetric_eigensystem(const vnl_matrix & A) + : n_(A.rows()) + , V(n_, n_) + , D(n_) { vnl_vector Dvec(n_); @@ -147,27 +149,30 @@ vnl_symmetric_eigensystem::vnl_symmetric_eigensystem(vnl_matrix const& A) // Copy Dvec into diagonal of D for (int i = 0; i < n_; ++i) - D(i,i) = Dvec[i]; + D(i, i) = Dvec[i]; } template -vnl_vector vnl_symmetric_eigensystem::get_eigenvector(int i) const +vnl_vector +vnl_symmetric_eigensystem::get_eigenvector(int i) const { - return vnl_vector(V.extract(n_,1,0,i).data_block(), n_); + return vnl_vector(V.extract(n_, 1, 0, i).data_block(), n_); } template -T vnl_symmetric_eigensystem::get_eigenvalue(int i) const +T +vnl_symmetric_eigensystem::get_eigenvalue(int i) const { return D(i, i); } template -vnl_vector vnl_symmetric_eigensystem::solve(vnl_vector const& b) +vnl_vector +vnl_symmetric_eigensystem::solve(const vnl_vector & b) { - //vnl_vector ret(b.length()); - //FastOps::AtB(V, b, &ret); - vnl_vector ret(b*V); // same as V.transpose()*b + // vnl_vector ret(b.length()); + // FastOps::AtB(V, b, &ret); + const vnl_vector ret(b * V); // same as V.transpose()*b vnl_vector tmp(b.size()); D.solve(ret, &tmp); @@ -176,22 +181,25 @@ vnl_vector vnl_symmetric_eigensystem::solve(vnl_vector const& b) } template -T vnl_symmetric_eigensystem::determinant() const +T +vnl_symmetric_eigensystem::determinant() const { - int const n = D.size(); + const int n = D.size(); T det(1); - for (int i=0; i -vnl_matrix vnl_symmetric_eigensystem::pinverse() const +vnl_matrix +vnl_symmetric_eigensystem::pinverse() const { - unsigned n = D.rows(); + const unsigned n = D.rows(); vnl_diag_matrix invD(n); - for (unsigned i=0; i vnl_symmetric_eigensystem::pinverse() const } template -vnl_matrix vnl_symmetric_eigensystem::square_root() const +vnl_matrix +vnl_symmetric_eigensystem::square_root() const { - unsigned n = D.rows(); + const unsigned n = D.rows(); vnl_diag_matrix sqrtD(n); - for (unsigned i=0; i::real_t)(-D(i, i))); - // gives square root of the absolute value of T. + // gives square root of the absolute value of T. } else sqrtD(i, i) = (T)std::sqrt((typename vnl_numeric_traits::real_t)(D(i, i))); @@ -217,26 +227,29 @@ vnl_matrix vnl_symmetric_eigensystem::square_root() const } template -vnl_matrix vnl_symmetric_eigensystem::inverse_square_root() const +vnl_matrix +vnl_symmetric_eigensystem::inverse_square_root() const { - unsigned n = D.rows(); + const unsigned n = D.rows(); vnl_diag_matrix inv_sqrtD(n); - for (unsigned i=0; i::real_t)(D(i, i))); // ?? + inv_sqrtD(i, i) = (T)std::sqrt(-1.0 / (typename vnl_numeric_traits::real_t)(D(i, i))); // ?? } else - inv_sqrtD(i, i) = (T)std::sqrt(1.0/(typename vnl_numeric_traits::real_t)(D(i, i))); + inv_sqrtD(i, i) = (T)std::sqrt(1.0 / (typename vnl_numeric_traits::real_t)(D(i, i))); return V * inv_sqrtD * V.transpose(); } //-------------------------------------------------------------------------------- #undef VNL_SYMMETRIC_EIGENSYSTEM_INSTANTIATE -#define VNL_SYMMETRIC_EIGENSYSTEM_INSTANTIATE(T) \ -template class VNL_ALGO_EXPORT vnl_symmetric_eigensystem; \ -template VNL_ALGO_EXPORT void vnl_symmetric_eigensystem_compute_eigenvals(T,T,T,T,T,T,T&,T&,T&); \ -template VNL_ALGO_EXPORT bool vnl_symmetric_eigensystem_compute(vnl_matrix const&, vnl_matrix &, vnl_vector&) +#define VNL_SYMMETRIC_EIGENSYSTEM_INSTANTIATE(T) \ + template class VNL_ALGO_EXPORT vnl_symmetric_eigensystem; \ + template VNL_ALGO_EXPORT void vnl_symmetric_eigensystem_compute_eigenvals(T, T, T, T, T, T, T &, T &, T &); \ + template VNL_ALGO_EXPORT bool vnl_symmetric_eigensystem_compute( \ + vnl_matrix const &, vnl_matrix &, vnl_vector &) #endif // vnl_symmetric_eigensystem_hxx_ diff --git a/core/vnl/dll.h b/core/vnl/dll.h index debea3c7cbf..b3907e5a5c9 100644 --- a/core/vnl/dll.h +++ b/core/vnl/dll.h @@ -12,10 +12,10 @@ // if win32 and not building the DLL then you need a dllimport // Only if you are building a DLL linked application. -# ifdef BUILD_DLL -# undef VNL_DLL_DATA -# define VNL_DLL_DATA _declspec(dllimport) -# endif // BUILD_DLL -#endif // _WIN32 and !Building_*_dll +# ifdef BUILD_DLL +# undef VNL_DLL_DATA +# define VNL_DLL_DATA _declspec(dllimport) +# endif // BUILD_DLL +#endif // _WIN32 and !Building_*_dll #endif // vnl_dll_h_ diff --git a/core/vnl/examples/calculate.cxx b/core/vnl/examples/calculate.cxx index ff54b5637c9..4feb1229002 100644 --- a/core/vnl/examples/calculate.cxx +++ b/core/vnl/examples/calculate.cxx @@ -37,52 +37,52 @@ const vnl_decnum one("1"); const vnl_decnum half("5e-1"); vnl_decnum -round(vnl_decnum const & a) +round(const vnl_decnum & a) { return floor(a + half); } vnl_decnum -min(vnl_decnum const & a, vnl_decnum const & b) +min(const vnl_decnum & a, const vnl_decnum & b) { return (a < b) ? a : b; } vnl_decnum -max(vnl_decnum const & a, vnl_decnum const & b) +max(const vnl_decnum & a, const vnl_decnum & b) { return (a < b) ? b : a; } vnl_decnum -unaryminus(vnl_decnum const & a) +unaryminus(const vnl_decnum & a) { return -a; } vnl_decnum -prod(vnl_decnum const & a, vnl_decnum const & b) +prod(const vnl_decnum & a, const vnl_decnum & b) { return a * b; } vnl_decnum -quot(vnl_decnum const & a, vnl_decnum const & b) +quot(const vnl_decnum & a, const vnl_decnum & b) { return a / b; } vnl_decnum -modulo(vnl_decnum const & a, vnl_decnum const & b) +modulo(const vnl_decnum & a, const vnl_decnum & b) { return a % b; } vnl_decnum -sum(vnl_decnum const & a, vnl_decnum const & b) +sum(const vnl_decnum & a, const vnl_decnum & b) { return a + b; } vnl_decnum -diff(vnl_decnum const & a, vnl_decnum const & b) +diff(const vnl_decnum & a, const vnl_decnum & b) { return a - b; } vnl_decnum -fac(vnl_decnum const & a) +fac(const vnl_decnum & a) { if (a <= one) return one; @@ -90,7 +90,7 @@ fac(vnl_decnum const & a) return a * fac(a - one); } vnl_decnum -binom(vnl_decnum const & a, vnl_decnum const & b) +binom(const vnl_decnum & a, const vnl_decnum & b) { if (a < zero || b < zero || a < b) return zero; @@ -113,7 +113,7 @@ class node }; void -ErrorExit(std::string const & expr, char const * t, unsigned long s) +ErrorExit(const std::string & expr, const char * t, unsigned long s) { std::cerr << "Error parsing expression -- " << t << ":\n" << expr << '\n'; while (s--) @@ -124,7 +124,7 @@ ErrorExit(std::string const & expr, char const * t, unsigned long s) //: find end of argument, i.e., comma or ')' int -arglength(std::string const & expr, unsigned long s, int l) +arglength(const std::string & expr, unsigned long s, int l) { int i = 0; int level = 0; @@ -145,7 +145,7 @@ arglength(std::string const & expr, unsigned long s, int l) //: find matching bracket or other end of block int -blocklength(std::string const & expr, unsigned long s, int l) +blocklength(const std::string & expr, unsigned long s, int l) { int i = 0; if (expr[s] == '-' || expr[s] == '+') // unary minus or plus @@ -383,10 +383,8 @@ hierarchy_brackets(std::string & expr, unsigned long s, int l) } node -build_tree(std::string const & expr, unsigned long s, int l) +build_tree(const std::string & expr, unsigned long s, int l) { - int i, j; - node n; // expr[s]--expr[s+l-1] is any of: // (number) // function() @@ -400,7 +398,8 @@ build_tree(std::string const & expr, unsigned long s, int l) ErrorExit(expr, "empty block", s); if (expr[s] == ')') ErrorExit(expr, "empty ()", s); - j = blocklength(expr, s, l); + int j = blocklength(expr, s, l); + node n; if (j == l && expr[s] >= '0' && expr[s] <= '9') { // number n.func1 = nullptr; @@ -438,6 +437,7 @@ build_tree(std::string const & expr, unsigned long s, int l) ErrorExit(expr, "unknown function call", s); n.param1 = new node(); n.param2 = nullptr; + int i; for (i = j; i < l - 1; ++i) if (expr[s + i] == ',') break; @@ -496,7 +496,7 @@ build_tree(std::string const & expr, unsigned long s, int l) //: Return str, but after removing spaces, making lowercase, and adding () std::string -simplify(char const * str) +simplify(const char * str) { std::string expr = ""; // remove all spaces and tabs: diff --git a/core/vnl/examples/vnl_svd.cxx b/core/vnl/examples/vnl_svd.cxx index 519fe9d270c..23896684da4 100644 --- a/core/vnl/examples/vnl_svd.cxx +++ b/core/vnl/examples/vnl_svd.cxx @@ -6,7 +6,7 @@ template // D is often double or float vnl_matrix -solve_with_warning(vnl_matrix const & M, vnl_matrix const & B) +solve_with_warning(const vnl_matrix & M, const vnl_matrix & B) { // Take svd of vnl_matrix M, setting singular values // smaller than 1e-8 to 0, and hold the result. @@ -18,7 +18,7 @@ solve_with_warning(vnl_matrix const & M, vnl_matrix const & B) } template vnl_matrix -solve_with_warning(vnl_matrix const &, vnl_matrix const &); +solve_with_warning(const vnl_matrix &, const vnl_matrix &); int main() diff --git a/core/vnl/io/tests/test_matrix_fixed_io.cxx b/core/vnl/io/tests/test_matrix_fixed_io.cxx index cfdb402e083..24c90bad5e8 100644 --- a/core/vnl/io/tests/test_matrix_fixed_io.cxx +++ b/core/vnl/io/tests/test_matrix_fixed_io.cxx @@ -13,10 +13,10 @@ test_matrix_fixed_double_2_2_io() << "***************************************\n"; //// test constructors, accessors double datablock[4] = { 1.1, 1.2, 2.1, 2.2 }; - vnl_matrix_fixed m_out(datablock), m_in0, m_in1; + vnl_matrix_fixed m_out(datablock), m_in0; // Give some initial content - m_in1 = m_out * 2.0; + vnl_matrix_fixed m_in1 = m_out * 2.0; vsl_b_ofstream bfs_out("vnl_matrix_fixed_io.bvl.tmp", std::ios::out | std::ios::binary); TEST("vnl_matrix_fixed_io.bvl.tmp for writing", (!bfs_out), false); diff --git a/core/vnl/io/tests/test_real_npolynomial_io.cxx b/core/vnl/io/tests/test_real_npolynomial_io.cxx index 4640f5ff98f..b77176eb52d 100644 --- a/core/vnl/io/tests/test_real_npolynomial_io.cxx +++ b/core/vnl/io/tests/test_real_npolynomial_io.cxx @@ -14,7 +14,7 @@ test_real_npolynomial_io() << "test_real_npolynomial_io\n" << "************************\n"; //// test constructors, accessors - vnl_vector coeffs(4), coeffs2; + vnl_vector coeffs(4); vnl_matrix exponents(4, 2); coeffs(0) = 0.1; @@ -31,7 +31,7 @@ test_real_npolynomial_io() exponents(2, 1) = 7; exponents(3, 1) = 8; - coeffs2 = coeffs * 2.0; + vnl_vector coeffs2 = coeffs * 2.0; // vsl_print_summary(std::cout, coeffs); diff --git a/core/vnl/io/vnl_io_bignum.h b/core/vnl/io/vnl_io_bignum.h index 8739fb563aa..a95074daed3 100644 --- a/core/vnl/io/vnl_io_bignum.h +++ b/core/vnl/io/vnl_io_bignum.h @@ -15,14 +15,17 @@ //: Binary save vnl_bignum to stream. // \relatesalso vnl_bignum -void vsl_b_write(vsl_b_ostream & os, vnl_bignum const& v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_bignum & v); //: Binary load vnl_bignum from stream. // \relatesalso vnl_bignum -void vsl_b_read(vsl_b_istream & is, vnl_bignum & v); +void +vsl_b_read(vsl_b_istream & is, vnl_bignum & v); //: Print human readable summary of object to a stream // \relatesalso vnl_bignum -void vsl_print_summary(std::ostream & os, vnl_bignum const& b); +void +vsl_print_summary(std::ostream & os, const vnl_bignum & b); #endif // vnl_io_bignum_h diff --git a/core/vnl/io/vnl_io_diag_matrix.h b/core/vnl/io/vnl_io_diag_matrix.h index 0e7b289d1eb..3ff53719374 100644 --- a/core/vnl/io/vnl_io_diag_matrix.h +++ b/core/vnl/io/vnl_io_diag_matrix.h @@ -12,16 +12,19 @@ //: Binary save vnl_diag_matrix to stream. // \relatesalso vnl_diag_matrix template -void vsl_b_write(vsl_b_ostream &os, const vnl_diag_matrix & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_diag_matrix & v); //: Binary load vnl_diag_matrix from stream. // \relatesalso vnl_diag_matrix template -void vsl_b_read(vsl_b_istream &is, vnl_diag_matrix & v); +void +vsl_b_read(vsl_b_istream & is, vnl_diag_matrix & v); //: Print human readable summary of object to a stream // \relatesalso vnl_diag_matrix template -void vsl_print_summary(std::ostream& os,const vnl_diag_matrix & b); +void +vsl_print_summary(std::ostream & os, const vnl_diag_matrix & b); #endif // vnl_io_diag_matrix_h diff --git a/core/vnl/io/vnl_io_diag_matrix.hxx b/core/vnl/io/vnl_io_diag_matrix.hxx index f22e5674dbf..5c7959b1b52 100644 --- a/core/vnl/io/vnl_io_diag_matrix.hxx +++ b/core/vnl/io/vnl_io_diag_matrix.hxx @@ -12,8 +12,9 @@ //================================================================================= //: Binary save self to stream. -template -void vsl_b_write(vsl_b_ostream & os, const vnl_diag_matrix & p) +template +void +vsl_b_write(vsl_b_ostream & os, const vnl_diag_matrix & p) { constexpr short io_version_no = 1; vsl_b_write(os, io_version_no); @@ -22,41 +23,44 @@ void vsl_b_write(vsl_b_ostream & os, const vnl_diag_matrix & p) //================================================================================= //: Binary load self from stream. -template -void vsl_b_read(vsl_b_istream &is, vnl_diag_matrix & p) +template +void +vsl_b_read(vsl_b_istream & is, vnl_diag_matrix & p) { - if (!is) return; + if (!is) + return; short ver; vnl_vector v; vsl_b_read(is, ver); switch (ver) { - case 1: - vsl_b_read(is, v); - p.set(v); - break; - - default: - std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_diag_matrix&)\n" - << " Unknown version number "<< v << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; + case 1: + vsl_b_read(is, v); + p.set(v); + break; + + default: + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_diag_matrix&)\n" + << " Unknown version number " << v << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; } } //==================================================================================== //: Output a human readable summary to the stream -template -void vsl_print_summary(std::ostream & os,const vnl_diag_matrix & p) +template +void +vsl_print_summary(std::ostream & os, const vnl_diag_matrix & p) { - os<<"Diagonal: "; + os << "Diagonal: "; vsl_print_summary(os, p.diagonal()); } -#define VNL_IO_DIAG_MATRIX_INSTANTIATE(T) \ -template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_diag_matrix &); \ -template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_diag_matrix &); \ -template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_diag_matrix &) +#define VNL_IO_DIAG_MATRIX_INSTANTIATE(T) \ + template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_diag_matrix &); \ + template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_diag_matrix &); \ + template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_diag_matrix &) #endif // vnl_io_diag_matrix_hxx_ diff --git a/core/vnl/io/vnl_io_matrix.h b/core/vnl/io/vnl_io_matrix.h index edb12783fdf..d82796dc284 100644 --- a/core/vnl/io/vnl_io_matrix.h +++ b/core/vnl/io/vnl_io_matrix.h @@ -16,16 +16,19 @@ //: Binary save vnl_matrix to stream. // \relatesalso vnl_matrix template -void vsl_b_write(vsl_b_ostream & os, const vnl_matrix & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_matrix & v); //: Binary load vnl_matrix from stream. // \relatesalso vnl_matrix template -void vsl_b_read(vsl_b_istream & is, vnl_matrix & v); +void +vsl_b_read(vsl_b_istream & is, vnl_matrix & v); //: Print human readable summary of object to a stream // \relatesalso vnl_matrix template -void vsl_print_summary(std::ostream & os,const vnl_matrix & b); +void +vsl_print_summary(std::ostream & os, const vnl_matrix & b); #endif // vnl_io_matrix_h diff --git a/core/vnl/io/vnl_io_matrix.hxx b/core/vnl/io/vnl_io_matrix.hxx index f6104ca4195..19239b6468a 100644 --- a/core/vnl/io/vnl_io_matrix.hxx +++ b/core/vnl/io/vnl_io_matrix.hxx @@ -12,8 +12,9 @@ //================================================================================= //: Binary save self to stream. -template -void vsl_b_write(vsl_b_ostream & os, const vnl_matrix & p) +template +void +vsl_b_write(vsl_b_ostream & os, const vnl_matrix & p) { constexpr short version_no = 2; vsl_b_write(os, version_no); @@ -27,77 +28,86 @@ void vsl_b_write(vsl_b_ostream & os, const vnl_matrix & p) //================================================================================= //: Binary load self from stream. -template -void vsl_b_read(vsl_b_istream &is, vnl_matrix & p) +template +void +vsl_b_read(vsl_b_istream & is, vnl_matrix & p) { - if (!is) return; + if (!is) + return; short v; unsigned m, n; vsl_b_read(is, v); switch (v) { - case 1: + case 1: #if !VXL_LEGACY_FUTURE_REMOVE - vsl_b_read(is, m); - vsl_b_read(is, n); - p.set_size(m, n); - // Calling begin() on empty matrix causes segfault - if (m*n>0) - vsl_b_read_block_old(is, p.begin(), p.size()); + vsl_b_read(is, m); + vsl_b_read(is, n); + p.set_size(m, n); + // Calling begin() on empty matrix causes segfault + if (m * n > 0) + vsl_b_read_block_old(is, p.begin(), p.size()); #else - std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required function vsl_b_read_block_old in 2006\n"; + std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required " + "function vsl_b_read_block_old in 2006\n"; #endif - break; - - case 2: - vsl_b_read(is, m); - vsl_b_read(is, n); - p.set_size(m, n); - // Calling begin() on empty matrix causes segfault - if (m*n>0) - vsl_block_binary_read(is, p.data_block(), p.size()); - break; - - default: - std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_matrix&)\n" - << " Unknown version number "<< v << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; + break; + + case 2: + vsl_b_read(is, m); + vsl_b_read(is, n); + p.set_size(m, n); + // Calling begin() on empty matrix causes segfault + if (m * n > 0) + vsl_block_binary_read(is, p.data_block(), p.size()); + break; + + default: + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_matrix&)\n" + << " Unknown version number " << v << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; } } //==================================================================================== //: Output a human readable summary to the stream -template -void vsl_print_summary(std::ostream & os,const vnl_matrix & p) +template +void +vsl_print_summary(std::ostream & os, const vnl_matrix & p) { - os<<"Size: "<p.rows()) m=p.rows(); - if (n>p.cols()) n=p.cols(); + if (m > p.rows()) + m = p.rows(); + if (n > p.cols()) + n = p.cols(); vsl_indent_inc(os); - for (unsigned int i=0;in) os<<"..."; - os<<")\n"; + for (unsigned int j = 0; j < n; j++) + os << p(i, j) << ' '; + if (p.cols() > n) + os << "..."; + os << ")\n"; } - if (p.rows()>m) os < m) + os << vsl_indent() << " (...\n"; vsl_indent_dec(os); } -#define VNL_IO_MATRIX_INSTANTIATE(T) \ -template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_matrix &); \ -template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_matrix &); \ -template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_matrix &) +#define VNL_IO_MATRIX_INSTANTIATE(T) \ + template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_matrix &); \ + template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_matrix &); \ + template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_matrix &) #endif // vnl_io_matrix_hxx_ diff --git a/core/vnl/io/vnl_io_matrix_fixed.h b/core/vnl/io/vnl_io_matrix_fixed.h index a12dd89c368..378dda32574 100644 --- a/core/vnl/io/vnl_io_matrix_fixed.h +++ b/core/vnl/io/vnl_io_matrix_fixed.h @@ -12,16 +12,19 @@ //: Binary save vnl_matrix_fixed to stream. // \relatesalso vnl_matrix_fixed template -void vsl_b_write(vsl_b_ostream & os, const vnl_matrix_fixed & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_matrix_fixed & v); //: Binary load vnl_matrix_fixed from stream. // \relatesalso vnl_matrix_fixed template -void vsl_b_read(vsl_b_istream & is, vnl_matrix_fixed & v); +void +vsl_b_read(vsl_b_istream & is, vnl_matrix_fixed & v); //: Print human readable summary of object to a stream // \relatesalso vnl_matrix_fixed template -void vsl_print_summary(std::ostream & os,const vnl_matrix_fixed & b); +void +vsl_print_summary(std::ostream & os, const vnl_matrix_fixed & b); #endif // vnl_io_matrix_fixed_h diff --git a/core/vnl/io/vnl_io_matrix_fixed.hxx b/core/vnl/io/vnl_io_matrix_fixed.hxx index 52bb0a0576c..418f6627c6b 100644 --- a/core/vnl/io/vnl_io_matrix_fixed.hxx +++ b/core/vnl/io/vnl_io_matrix_fixed.hxx @@ -12,8 +12,9 @@ //================================================================================= //: Binary save self to stream. -template -void vsl_b_write(vsl_b_ostream & os, const vnl_matrix_fixed & p) +template +void +vsl_b_write(vsl_b_ostream & os, const vnl_matrix_fixed & p) { constexpr short version_no = 2; vsl_b_write(os, version_no); @@ -21,93 +22,104 @@ void vsl_b_write(vsl_b_ostream & os, const vnl_matrix_fixed & p) vsl_b_write(os, p.cols()); // Calling p.begin() on empty matrix_fixed causes segfault - if (p.size()>0) - vsl_block_binary_write(os, p.data_block(), m*n); + if (p.size() > 0) + vsl_block_binary_write(os, p.data_block(), m * n); } //================================================================================= //: Binary load self from stream. -template -void vsl_b_read(vsl_b_istream &is, vnl_matrix_fixed & p) +template +void +vsl_b_read(vsl_b_istream & is, vnl_matrix_fixed & p) { - if (!is) return; + if (!is) + return; short v; unsigned stream_m, stream_n; vsl_b_read(is, v); switch (v) { - case 1: + case 1: #if !VXL_LEGACY_FUTURE_REMOVE - vsl_b_read(is, stream_m); - vsl_b_read(is, stream_n); - if ( stream_n != n || stream_m != m ) { - std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_matrix_fixed&)\n" - << " Expected size " << m << ',' << n << "; got " << stream_m << ',' << stream_n << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; - } - // Calling begin() on empty matrix_fixed causes segfault - if (m*n>0) - vsl_b_read_block_old(is, p.begin(), p.size()); - break; + vsl_b_read(is, stream_m); + vsl_b_read(is, stream_n); + if (stream_n != n || stream_m != m) + { + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_matrix_fixed&)\n" + << " Expected size " << m << ',' << n << "; got " << stream_m << ',' << stream_n << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; + } + // Calling begin() on empty matrix_fixed causes segfault + if (m * n > 0) + vsl_b_read_block_old(is, p.begin(), p.size()); + break; #else - std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required function vsl_b_read_block_old in 2006\n"; + std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required " + "function vsl_b_read_block_old in 2006\n"; #endif - case 2: - vsl_b_read(is, stream_m); - vsl_b_read(is, stream_n); - if ( stream_n != n || stream_m != m ) { + case 2: + vsl_b_read(is, stream_m); + vsl_b_read(is, stream_n); + if (stream_n != n || stream_m != m) + { + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_matrix_fixed&)\n" + << " Expected size " << m << ',' << n << "; got " << stream_m << ',' << stream_n << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; + } + // Calling begin() on empty matrix_fixed causes segfault + if (m * n > 0) + vsl_block_binary_read(is, p.data_block(), m * n); + break; + + default: std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_matrix_fixed&)\n" - << " Expected size " << m << ',' << n << "; got " << stream_m << ',' << stream_n << '\n'; + << " Unknown version number " << v << '\n'; is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream return; - } - // Calling begin() on empty matrix_fixed causes segfault - if (m*n>0) - vsl_block_binary_read(is, p.data_block(), m*n); - break; - - default: - std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_matrix_fixed&)\n" - << " Unknown version number "<< v << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; } } //==================================================================================== //: Output a human readable summary to the stream -template -void vsl_print_summary(std::ostream & os,const vnl_matrix_fixed & p) +template +void +vsl_print_summary(std::ostream & os, const vnl_matrix_fixed & p) { - os<<"Size: "<p.rows()) m=p.rows(); - if (n>p.cols()) n=p.cols(); + if (m > p.rows()) + m = p.rows(); + if (n > p.cols()) + n = p.cols(); vsl_indent_inc(os); - for (unsigned int i=0;in) os<<"..."; - os<<")\n"; + for (unsigned int j = 0; j < n; j++) + os << p(i, j) << ' '; + if (p.cols() > n) + os << "..."; + os << ")\n"; } - if (p.rows()>m) os < m) + os << vsl_indent() << " (...\n"; vsl_indent_dec(os); } -#define VNL_IO_MATRIX_FIXED_INSTANTIATE(T,m,n) \ -template void vsl_print_summary(std::ostream &, const vnl_matrix_fixed &); \ -template void vsl_b_read(vsl_b_istream &, vnl_matrix_fixed &); \ -template void vsl_b_write(vsl_b_ostream &, const vnl_matrix_fixed &) +#define VNL_IO_MATRIX_FIXED_INSTANTIATE(T, m, n) \ + template void vsl_print_summary(std::ostream &, const vnl_matrix_fixed &); \ + template void vsl_b_read(vsl_b_istream &, vnl_matrix_fixed &); \ + template void vsl_b_write(vsl_b_ostream &, const vnl_matrix_fixed &) #endif // vnl_io_matrix_fixed_hxx_ diff --git a/core/vnl/io/vnl_io_nonlinear_minimizer.h b/core/vnl/io/vnl_io_nonlinear_minimizer.h index 77ece00ed01..6f973b61fd3 100644 --- a/core/vnl/io/vnl_io_nonlinear_minimizer.h +++ b/core/vnl/io/vnl_io_nonlinear_minimizer.h @@ -17,7 +17,7 @@ // for classes derived from vnl_nonlinear_minimizer class vnl_io_nonlinear_minimizer { - public: +public: //: Constructor vnl_io_nonlinear_minimizer() = default; @@ -25,56 +25,72 @@ class vnl_io_nonlinear_minimizer virtual ~vnl_io_nonlinear_minimizer() = default; //: Create new object of type vnl_nonlinear_minimizer on heap - virtual vnl_nonlinear_minimizer* new_object() const; + virtual vnl_nonlinear_minimizer * + new_object() const; //: Write derived class to os using vnl_nonlinear_minimizer reference - virtual void b_write_by_base(vsl_b_ostream& os, - const vnl_nonlinear_minimizer& base) const; + virtual void + b_write_by_base(vsl_b_ostream & os, const vnl_nonlinear_minimizer & base) const; //: Write derived class to os using vnl_nonlinear_minimizer reference - virtual void b_read_by_base(vsl_b_istream& is, - vnl_nonlinear_minimizer& base) const; + virtual void + b_read_by_base(vsl_b_istream & is, vnl_nonlinear_minimizer & base) const; //: Print summary of derived class to os // using vnl_nonlinear_minimizer reference - virtual void print_summary_by_base(std::ostream& os, - const vnl_nonlinear_minimizer& base) const; + virtual void + print_summary_by_base(std::ostream & os, const vnl_nonlinear_minimizer & base) const; //: Copy this object onto the heap and return a pointer - virtual vnl_io_nonlinear_minimizer* clone() const; + virtual vnl_io_nonlinear_minimizer * + clone() const; //: Return name of class for which this object provides IO - virtual std::string target_classname() const { return "vnl_nonlinear_minimizer"; } + virtual std::string + target_classname() const + { + return "vnl_nonlinear_minimizer"; + } //: Return true if b is of class target_classname() // Typically this will just be "return b.is_a()==target_classname()" // However, third party libraries may use a different system - virtual bool is_io_for(const vnl_nonlinear_minimizer& b) const - { return b.is_a()==target_classname(); } + virtual bool + is_io_for(const vnl_nonlinear_minimizer & b) const + { + return b.is_a() == target_classname(); + } }; //: Add example object to list of those that can be loaded // The vsl_binary_loader must see an example of each derived class // before it knows how to deal with them. // A clone is taken of b -void vsl_add_to_binary_loader(const vnl_io_nonlinear_minimizer& b); +void +vsl_add_to_binary_loader(const vnl_io_nonlinear_minimizer & b); //: Binary save to stream by vnl_nonlinear_minimizer pointer -void vsl_b_write(vsl_b_ostream &os, const vnl_nonlinear_minimizer * b); +void +vsl_b_write(vsl_b_ostream & os, const vnl_nonlinear_minimizer * b); //: Binary read from stream by vnl_nonlinear_minimizer pointer -void vsl_b_read(vsl_b_istream &is, vnl_nonlinear_minimizer* &b); +void +vsl_b_read(vsl_b_istream & is, vnl_nonlinear_minimizer *& b); //: Print summary to stream by vnl_nonlinear_minimizer pointer -void vsl_print_summary(std::ostream &os, const vnl_nonlinear_minimizer * b); +void +vsl_print_summary(std::ostream & os, const vnl_nonlinear_minimizer * b); //: Binary save vnl_real_polynomial to stream. -void vsl_b_write(vsl_b_ostream &os, const vnl_nonlinear_minimizer & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_nonlinear_minimizer & v); //: Binary load vnl_real_polynomial from stream. -void vsl_b_read(vsl_b_istream &is, vnl_nonlinear_minimizer & v); +void +vsl_b_read(vsl_b_istream & is, vnl_nonlinear_minimizer & v); //: Print human readable summary of object to a stream -void vsl_print_summary(std::ostream& os,const vnl_nonlinear_minimizer & b); +void +vsl_print_summary(std::ostream & os, const vnl_nonlinear_minimizer & b); #endif // vnl_io_nonlinear_minimizer_h diff --git a/core/vnl/io/vnl_io_rational.h b/core/vnl/io/vnl_io_rational.h index 5db1bc39716..fbc4f4cc71d 100644 --- a/core/vnl/io/vnl_io_rational.h +++ b/core/vnl/io/vnl_io_rational.h @@ -15,14 +15,17 @@ //: Binary save vnl_rational to stream. // \relatesalso vnl_rational -void vsl_b_write(vsl_b_ostream & os, vnl_rational const& v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_rational & v); //: Binary load vnl_rational from stream. // \relatesalso vnl_rational -void vsl_b_read(vsl_b_istream & is, vnl_rational & v); +void +vsl_b_read(vsl_b_istream & is, vnl_rational & v); //: Print human readable summary of object to a stream // \relatesalso vnl_rational -void vsl_print_summary(std::ostream & os, vnl_rational const& b); +void +vsl_print_summary(std::ostream & os, const vnl_rational & b); #endif // vnl_io_rational_h diff --git a/core/vnl/io/vnl_io_real_npolynomial.h b/core/vnl/io/vnl_io_real_npolynomial.h index 89709e1a416..2d9772fcc7d 100644 --- a/core/vnl/io/vnl_io_real_npolynomial.h +++ b/core/vnl/io/vnl_io_real_npolynomial.h @@ -11,14 +11,17 @@ //: Binary save vnl_real_npolynomial to stream. // \relatesalso vnl_real_npolynomial -void vsl_b_write(vsl_b_ostream &os, const vnl_real_npolynomial & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_real_npolynomial & v); //: Binary load vnl_real_polynomial from stream. // \relatesalso vnl_real_npolynomial -void vsl_b_read(vsl_b_istream &is, vnl_real_npolynomial & v); +void +vsl_b_read(vsl_b_istream & is, vnl_real_npolynomial & v); //: Print human readable summary of object to a stream // \relatesalso vnl_real_npolynomial -void vsl_print_summary(std::ostream& os,const vnl_real_npolynomial & b); +void +vsl_print_summary(std::ostream & os, const vnl_real_npolynomial & b); #endif // vnl_io_real_npolynomial_h diff --git a/core/vnl/io/vnl_io_real_polynomial.h b/core/vnl/io/vnl_io_real_polynomial.h index f4d8d53d3bc..8185f28e2c7 100644 --- a/core/vnl/io/vnl_io_real_polynomial.h +++ b/core/vnl/io/vnl_io_real_polynomial.h @@ -11,14 +11,17 @@ //: Binary save vnl_real_polynomial to stream. // \relatesalso vnl_real_polynomial -void vsl_b_write(vsl_b_ostream &os, const vnl_real_polynomial & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_real_polynomial & v); //: Binary load vnl_real_polynomial from stream. // \relatesalso vnl_real_polynomial -void vsl_b_read(vsl_b_istream &is, vnl_real_polynomial & v); +void +vsl_b_read(vsl_b_istream & is, vnl_real_polynomial & v); //: Print human readable summary of object to a stream // \relatesalso vnl_real_polynomial -void vsl_print_summary(std::ostream& os,const vnl_real_polynomial & b); +void +vsl_print_summary(std::ostream & os, const vnl_real_polynomial & b); #endif // vnl_io_real_polynomial_h diff --git a/core/vnl/io/vnl_io_sparse_matrix.h b/core/vnl/io/vnl_io_sparse_matrix.h index 18f2f893642..6d8c3f8bb36 100644 --- a/core/vnl/io/vnl_io_sparse_matrix.h +++ b/core/vnl/io/vnl_io_sparse_matrix.h @@ -12,16 +12,19 @@ //: Binary save vnl_sparse_matrix to stream. // \relatesalso vnl_sparse_matrix template -void vsl_b_write(vsl_b_ostream & os, const vnl_sparse_matrix & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_sparse_matrix & v); //: Binary load vnl_sparse_matrix from stream. // \relatesalso vnl_sparse_matrix template -void vsl_b_read(vsl_b_istream & is, vnl_sparse_matrix & v); +void +vsl_b_read(vsl_b_istream & is, vnl_sparse_matrix & v); //: Print human readable summary of object to a stream // \relatesalso vnl_sparse_matrix template -void vsl_print_summary(std::ostream & os,const vnl_sparse_matrix & b); +void +vsl_print_summary(std::ostream & os, const vnl_sparse_matrix & b); #endif // vnl_io_sparse_matrix_h diff --git a/core/vnl/io/vnl_io_sparse_matrix.hxx b/core/vnl/io/vnl_io_sparse_matrix.hxx index 826e8d575b7..ae8388df197 100644 --- a/core/vnl/io/vnl_io_sparse_matrix.hxx +++ b/core/vnl/io/vnl_io_sparse_matrix.hxx @@ -20,8 +20,9 @@ //================================================================================= //: Binary save self to stream. -template -void vsl_b_write(vsl_b_ostream &os, const vnl_sparse_matrix_pair & p) +template +void +vsl_b_write(vsl_b_ostream & os, const vnl_sparse_matrix_pair & p) { constexpr short io_version_no = 1; vsl_b_write(os, io_version_no); @@ -31,59 +32,63 @@ void vsl_b_write(vsl_b_ostream &os, const vnl_sparse_matrix_pair & p) //================================================================================= //: Binary load self from stream. -template -void vsl_b_read(vsl_b_istream &is, vnl_sparse_matrix_pair & p) +template +void +vsl_b_read(vsl_b_istream & is, vnl_sparse_matrix_pair & p) { - if (!is) return; + if (!is) + return; short ver; vsl_b_read(is, ver); switch (ver) { - case 1: - vsl_b_read(is, p.first); - vsl_b_read(is, p.second); - break; - - default: - std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_sparse_matrix_pair&)\n" - << " Unknown version number "<< ver << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; + case 1: + vsl_b_read(is, p.first); + vsl_b_read(is, p.second); + break; + + default: + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_sparse_matrix_pair&)\n" + << " Unknown version number " << ver << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; } } //================================================================================ //: Output a human readable summary to the stream -template -void vsl_print_summary(std::ostream& os,const vnl_sparse_matrix_pair& p) +template +void +vsl_print_summary(std::ostream & os, const vnl_sparse_matrix_pair & p) { - os<< "Sparse matrix pair ( " << p.first << ',' << p.second << " )\n"; + os << "Sparse matrix pair ( " << p.first << ',' << p.second << " )\n"; } // I/O for vnl_sparse_matrix //================================================================================= //: Binary save self to stream. -template -void vsl_b_write(vsl_b_ostream & os, const vnl_sparse_matrix & p) +template +void +vsl_b_write(vsl_b_ostream & os, const vnl_sparse_matrix & p) { typedef vnl_sparse_matrix_pair pair_t; - typedef std::vector < pair_t > row; + typedef std::vector row; row rw; - vnl_sparse_matrix v=p; + vnl_sparse_matrix v = p; constexpr short io_version_no = 1; vsl_b_write(os, io_version_no); vsl_b_write(os, v.rows()); vsl_b_write(os, v.columns()); - for (unsigned int i=0;i & p) //================================================================================= //: Binary load self from stream. -template -void vsl_b_read(vsl_b_istream &is, vnl_sparse_matrix & p) +template +void +vsl_b_read(vsl_b_istream & is, vnl_sparse_matrix & p) { - if (!is) return; + if (!is) + return; typedef vnl_sparse_matrix_pair pair_t; short ver; unsigned n_rows; unsigned n_cols; - unsigned row_size=0; + unsigned row_size = 0; vsl_b_read(is, ver); std::vector indexes(row_size); std::vector values(row_size); switch (ver) { - case 1: - vsl_b_read(is, n_rows); - vsl_b_read(is, n_cols); - // As we cannot resize the matrix, check that it is the correct size. - assert (n_rows==p.rows()); - assert (n_cols==p.columns()); - for (unsigned i=0;i&)\n" - << " Unknown version number "<< ver << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; + default: + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_sparse_matrix&)\n" + << " Unknown version number " << ver << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; } } //==================================================================================== //: Output a human readable summary to the stream -template -void vsl_print_summary(std::ostream & os,const vnl_sparse_matrix & p) +template +void +vsl_print_summary(std::ostream & os, const vnl_sparse_matrix & p) { - os<<"Rows x Columns: "< v=p; + os << "Rows x Columns: " << p.rows() << " x " << p.columns() << std::endl; + vnl_sparse_matrix v = p; v.reset(); v.next(); - for (int i=0;i<5;i++) + for (int i = 0; i < 5; i++) { - os<<" ("<< v.getrow() <<','<< v.getcolumn() <<") value "<< v.value()<<'\n'; - if (!v.next()) break; + os << " (" << v.getrow() << ',' << v.getcolumn() << ") value " << v.value() << '\n'; + if (!v.next()) + break; } } -#define VNL_IO_SPARSE_MATRIX_INSTANTIATE(T) \ - template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_sparse_matrix &); \ - template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_sparse_matrix &); \ - template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_sparse_matrix &) +#define VNL_IO_SPARSE_MATRIX_INSTANTIATE(T) \ + template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_sparse_matrix &); \ + template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_sparse_matrix &); \ + template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_sparse_matrix &) #endif // vnl_io_sparse_matrix_hxx_ diff --git a/core/vnl/io/vnl_io_sym_matrix.h b/core/vnl/io/vnl_io_sym_matrix.h index 052e043e231..c98be806f8b 100644 --- a/core/vnl/io/vnl_io_sym_matrix.h +++ b/core/vnl/io/vnl_io_sym_matrix.h @@ -12,16 +12,19 @@ //: Binary save vnl_matrix to stream. // \relatesalso vnl_sym_matrix template -void vsl_b_write(vsl_b_ostream & os, const vnl_sym_matrix & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_sym_matrix & v); //: Binary load vnl_matrix from stream. // \relatesalso vnl_sym_matrix template -void vsl_b_read(vsl_b_istream & is, vnl_sym_matrix & v); +void +vsl_b_read(vsl_b_istream & is, vnl_sym_matrix & v); //: Print human readable summary of object to a stream // \relatesalso vnl_sym_matrix template -void vsl_print_summary(std::ostream & os,const vnl_sym_matrix & b); +void +vsl_print_summary(std::ostream & os, const vnl_sym_matrix & b); #endif // vnl_io_sym_matrix_h diff --git a/core/vnl/io/vnl_io_sym_matrix.hxx b/core/vnl/io/vnl_io_sym_matrix.hxx index f0e5d93bd28..ddacfbb6c2b 100644 --- a/core/vnl/io/vnl_io_sym_matrix.hxx +++ b/core/vnl/io/vnl_io_sym_matrix.hxx @@ -12,86 +12,93 @@ //================================================================================= //: Binary save self to stream. -template -void vsl_b_write(vsl_b_ostream & os, const vnl_sym_matrix & p) +template +void +vsl_b_write(vsl_b_ostream & os, const vnl_sym_matrix & p) { constexpr short version_no = 2; vsl_b_write(os, version_no); vsl_b_write(os, p.rows()); // Calling p.begin() on empty matrix causes segfault - if (p.size()>0) + if (p.size() > 0) vsl_block_binary_write(os, p.data_block(), p.size()); } //================================================================================= //: Binary load self from stream. -template -void vsl_b_read(vsl_b_istream &is, vnl_sym_matrix & p) +template +void +vsl_b_read(vsl_b_istream & is, vnl_sym_matrix & p) { - if (!is) return; + if (!is) + return; short v; unsigned n; vsl_b_read(is, v); switch (v) { - case 1: + case 1: #if !VXL_LEGACY_FUTURE_REMOVE - vsl_b_read(is, n); - p.set_size(n); - // Calling begin() on empty matrix causes segfault - if (n>0) - vsl_b_read_block_old(is, p.data_block(), p.size()); - break; + vsl_b_read(is, n); + p.set_size(n); + // Calling begin() on empty matrix causes segfault + if (n > 0) + vsl_b_read_block_old(is, p.data_block(), p.size()); + break; #else - std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required function vsl_b_read_block_old in 2006\n"; + std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required " + "function vsl_b_read_block_old in 2006\n"; #endif - case 2: - vsl_b_read(is, n); - p.set_size(n); - // Calling begin() on empty matrix causes segfault - if (n>0) - vsl_block_binary_read(is, p.data_block(), p.size()); - break; + case 2: + vsl_b_read(is, n); + p.set_size(n); + // Calling begin() on empty matrix causes segfault + if (n > 0) + vsl_block_binary_read(is, p.data_block(), p.size()); + break; - default: - std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_sym_matrix&)\n" - << " Unknown version number "<< v << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; + default: + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_sym_matrix&)\n" + << " Unknown version number " << v << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; } } //==================================================================================== //: Output a human readable summary to the stream -template -void vsl_print_summary(std::ostream & os,const vnl_sym_matrix & p) +template +void +vsl_print_summary(std::ostream & os, const vnl_sym_matrix & p) { - os<<"Size: "<p.cols()) n=p.cols(); + if (n > p.cols()) + n = p.cols(); vsl_indent_inc(os); - for (unsigned int i=0;in) os < n) + os << vsl_indent() << " (...\n"; vsl_indent_dec(os); } -#define VNL_IO_SYM_MATRIX_INSTANTIATE(T) \ -template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_sym_matrix &); \ -template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_sym_matrix &); \ -template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_sym_matrix &) +#define VNL_IO_SYM_MATRIX_INSTANTIATE(T) \ + template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_sym_matrix &); \ + template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_sym_matrix &); \ + template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_sym_matrix &) #endif // vnl_io_sym_matrix_hxx_ diff --git a/core/vnl/io/vnl_io_vector.h b/core/vnl/io/vnl_io_vector.h index 28d46196c46..0c285bcf729 100644 --- a/core/vnl/io/vnl_io_vector.h +++ b/core/vnl/io/vnl_io_vector.h @@ -16,16 +16,19 @@ //: Binary save vnl_vector to stream. // \relatesalso vnl_vector template -void vsl_b_write(vsl_b_ostream & os, const vnl_vector & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_vector & v); //: Binary load vnl_vector from stream. // \relatesalso vnl_vector template -void vsl_b_read(vsl_b_istream & is, vnl_vector & v); +void +vsl_b_read(vsl_b_istream & is, vnl_vector & v); //: Print human readable summary of object to a stream // \relatesalso vnl_vector template -void vsl_print_summary(std::ostream & os,const vnl_vector & b); +void +vsl_print_summary(std::ostream & os, const vnl_vector & b); #endif // vnl_io_vector_h diff --git a/core/vnl/io/vnl_io_vector.hxx b/core/vnl/io/vnl_io_vector.hxx index 9e1a1882a9c..6f411238682 100644 --- a/core/vnl/io/vnl_io_vector.hxx +++ b/core/vnl/io/vnl_io_vector.hxx @@ -11,8 +11,9 @@ //================================================================================= //: Binary save self to stream. -template -void vsl_b_write(vsl_b_ostream & os, const vnl_vector & p) +template +void +vsl_b_write(vsl_b_ostream & os, const vnl_vector & p) { constexpr short io_version_no = 2; vsl_b_write(os, io_version_no); @@ -23,57 +24,62 @@ void vsl_b_write(vsl_b_ostream & os, const vnl_vector & p) //================================================================================= //: Binary load self from stream. -template -void vsl_b_read(vsl_b_istream &is, vnl_vector & p) +template +void +vsl_b_read(vsl_b_istream & is, vnl_vector & p) { - if (!is) return; + if (!is) + return; short ver; unsigned n; vsl_b_read(is, ver); switch (ver) { - case 1: + case 1: #if !VXL_LEGACY_FUTURE_REMOVE - vsl_b_read(is, n); - p.set_size(n); - if (n) - vsl_b_read_block_old(is, p.data_block(), n); + vsl_b_read(is, n); + p.set_size(n); + if (n) + vsl_b_read_block_old(is, p.data_block(), n); #else - std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required function vsl_b_read_block_old in 2006\n"; + std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required " + "function vsl_b_read_block_old in 2006\n"; #endif - break; + break; - case 2: - vsl_b_read(is, n); - p.set_size(n); - if (n) - vsl_block_binary_read(is, p.data_block(), n); - break; + case 2: + vsl_b_read(is, n); + p.set_size(n); + if (n) + vsl_block_binary_read(is, p.data_block(), n); + break; - default: - std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_vector&)\n" - << " Unknown version number "<< ver << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; + default: + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_vector&)\n" + << " Unknown version number " << ver << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; } } //==================================================================================== //: Output a human readable summary to the stream -template -void vsl_print_summary(std::ostream & os,const vnl_vector & p) +template +void +vsl_print_summary(std::ostream & os, const vnl_vector & p) { - os<<"Len: "< 5) os << " ..."; + os << "Len: " << p.size() << " ("; + for (unsigned int i = 0; i < p.size() && i < 5; ++i) + os << p.operator()(i) << ' '; + if (p.size() > 5) + os << " ..."; os << ')'; } -#define VNL_IO_VECTOR_INSTANTIATE(T) \ -template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_vector &); \ -template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_vector &); \ -template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_vector &) +#define VNL_IO_VECTOR_INSTANTIATE(T) \ + template VNL_EXPORT void vsl_print_summary(std::ostream &, const vnl_vector &); \ + template VNL_EXPORT void vsl_b_read(vsl_b_istream &, vnl_vector &); \ + template VNL_EXPORT void vsl_b_write(vsl_b_ostream &, const vnl_vector &) #endif // vnl_io_vector_hxx_ diff --git a/core/vnl/io/vnl_io_vector_fixed.h b/core/vnl/io/vnl_io_vector_fixed.h index 1089ac1351a..8242aa4a47b 100644 --- a/core/vnl/io/vnl_io_vector_fixed.h +++ b/core/vnl/io/vnl_io_vector_fixed.h @@ -16,16 +16,19 @@ //: Binary save vnl_vector_fixed to stream. // \relatesalso vnl_vector_fixed template -void vsl_b_write(vsl_b_ostream & os, const vnl_vector_fixed & v); +void +vsl_b_write(vsl_b_ostream & os, const vnl_vector_fixed & v); //: Binary load vnl_vector_fixed from stream. // \relatesalso vnl_vector_fixed template -void vsl_b_read(vsl_b_istream & is, vnl_vector_fixed & v); +void +vsl_b_read(vsl_b_istream & is, vnl_vector_fixed & v); //: Print human readable summary of object to a stream // \relatesalso vnl_vector_fixed template -void vsl_print_summary(std::ostream & os,const vnl_vector_fixed & b); +void +vsl_print_summary(std::ostream & os, const vnl_vector_fixed & b); #endif // vnl_io_vector_fixed_h diff --git a/core/vnl/io/vnl_io_vector_fixed.hxx b/core/vnl/io/vnl_io_vector_fixed.hxx index 0a7ad00ee0b..c279d8884cc 100644 --- a/core/vnl/io/vnl_io_vector_fixed.hxx +++ b/core/vnl/io/vnl_io_vector_fixed.hxx @@ -11,8 +11,9 @@ //================================================================================= //: Binary save self to stream. -template -void vsl_b_write(vsl_b_ostream & os, const vnl_vector_fixed & p) +template +void +vsl_b_write(vsl_b_ostream & os, const vnl_vector_fixed & p) { constexpr short io_version_no = 2; vsl_b_write(os, io_version_no); @@ -23,67 +24,78 @@ void vsl_b_write(vsl_b_ostream & os, const vnl_vector_fixed & p) //================================================================================= //: Binary load self from stream. -template -void vsl_b_read(vsl_b_istream &is, vnl_vector_fixed & p) +template +void +vsl_b_read(vsl_b_istream & is, vnl_vector_fixed & p) { - if (!is) return; + if (!is) + return; short ver; unsigned stream_n; vsl_b_read(is, ver); switch (ver) { - case 1: + case 1: #if !VXL_LEGACY_FUTURE_REMOVE - vsl_b_read(is, stream_n); - if ( n == stream_n ) { - vsl_b_read_block_old(is, p.begin(), n); - } else { - std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_vector_fixed&)\n" - << " Expected n="<&)\n" + << " Expected n=" << n << ", got " << stream_n << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; + } + break; #else - std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required function vsl_b_read_block_old in 2006\n"; + std::cerr << "I/O ERROR: Old version 1 file formats are no longer supported since deprecation of required " + "function vsl_b_read_block_old in 2006\n"; #endif - case 2: - vsl_b_read(is, stream_n); - if ( n == stream_n ) { - vsl_block_binary_read(is, p.data_block(), n); - } else { + case 2: + vsl_b_read(is, stream_n); + if (n == stream_n) + { + vsl_block_binary_read(is, p.data_block(), n); + } + else + { + std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_vector_fixed&)\n" + << " Expected n=" << n << ", got " << stream_n << '\n'; + is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream + return; + } + break; + + default: std::cerr << "I/O ERROR: vsl_b_read(vsl_b_istream&, vnl_vector_fixed&)\n" - << " Expected n="<&)\n" - << " Unknown version number "<< ver << '\n'; - is.is().clear(std::ios::badbit); // Set an unrecoverable IO error on stream - return; } } //==================================================================================== //: Output a human readable summary to the stream -template -void vsl_print_summary(std::ostream & os,const vnl_vector_fixed & p) +template +void +vsl_print_summary(std::ostream & os, const vnl_vector_fixed & p) { - os<<"Len: "< 5) os << " ..."; + os << "Len: " << p.size() << " [fixed] ("; + for (unsigned int i = 0; i < p.size() && i < 5; ++i) + os << p(i) << ' '; + if (p.size() > 5) + os << " ..."; os << ')'; } -#define VNL_IO_VECTOR_FIXED_INSTANTIATE(T,n) \ -template void vsl_print_summary(std::ostream &, const vnl_vector_fixed &); \ -template void vsl_b_read(vsl_b_istream &, vnl_vector_fixed &); \ -template void vsl_b_write(vsl_b_ostream &, const vnl_vector_fixed &) +#define VNL_IO_VECTOR_FIXED_INSTANTIATE(T, n) \ + template void vsl_print_summary(std::ostream &, const vnl_vector_fixed &); \ + template void vsl_b_read(vsl_b_istream &, vnl_vector_fixed &); \ + template void vsl_b_write(vsl_b_ostream &, const vnl_vector_fixed &) #endif // vnl_io_vector_fixed_hxx_ diff --git a/core/vnl/tests/basic_operation_timings.cxx b/core/vnl/tests/basic_operation_timings.cxx index fa895201ad5..d0515414c37 100644 --- a/core/vnl/tests/basic_operation_timings.cxx +++ b/core/vnl/tests/basic_operation_timings.cxx @@ -44,13 +44,13 @@ distance_squared(const std::vector> & s1, vnl_vector stats(nstests); for (unsigned st = 0; st < nstests; ++st) { - std::clock_t t0 = std::clock(); + const std::clock_t t0 = std::clock(); for (int l = 0; l < n_loops; ++l) { for (unsigned i = 0; i < d.size(); ++i) d[i] = vnl_vector_ssd(s1[i], s2[i]); } - std::clock_t t1 = std::clock(); + const std::clock_t t1 = std::clock(); stats[st] = (1e9 * ((double(t1) - double(t0))) / ((double)n_loops * (double)CLOCKS_PER_SEC)); } std::sort(stats.begin(), stats.end()); @@ -68,13 +68,13 @@ dot_product(const std::vector> & s1, vnl_vector stats(nstests); for (unsigned st = 0; st < nstests; ++st) { - std::clock_t t0 = std::clock(); + const std::clock_t t0 = std::clock(); for (int l = 0; l < n_loops; ++l) { for (unsigned i = 0; i < d.size(); ++i) d[i] = dot_product(s1[i], s2[i]); } - std::clock_t t1 = std::clock(); + const std::clock_t t1 = std::clock(); stats[st] = (1e9 * ((double(t1) - double(t0))) / ((double)n_loops * (double)CLOCKS_PER_SEC)); } std::sort(stats.begin(), stats.end()); @@ -89,13 +89,13 @@ mat_x_vec(const vnl_matrix & s1, const std::vector> & s2, int n vnl_vector stats(nstests); for (unsigned st = 0; st < nstests; ++st) { - std::clock_t t0 = std::clock(); + const std::clock_t t0 = std::clock(); for (int l = 0; l < n_loops; ++l) { for (unsigned i = 0; i < s2.size(); ++i) s1 * s2[i]; } - std::clock_t t1 = std::clock(); + const std::clock_t t1 = std::clock(); stats[st] = (1e6 * ((double(t1) - double(t0))) / ((double)n_loops * (double)CLOCKS_PER_SEC)); } std::sort(stats.begin(), stats.end()); @@ -110,13 +110,13 @@ vec_x_mat(const std::vector> & s1, const vnl_matrix & s2, int n vnl_vector stats(nstests); for (unsigned st = 0; st < nstests; ++st) { - std::clock_t t0 = std::clock(); + const std::clock_t t0 = std::clock(); for (int l = 0; l < n_loops; ++l) { for (unsigned i = 0; i < s2.size(); ++i) s1[i] * s2; } - std::clock_t t1 = std::clock(); + const std::clock_t t1 = std::clock(); stats[st] = (1e6 * ((double(t1) - double(t0))) / ((double)n_loops * (double)CLOCKS_PER_SEC)); } std::sort(stats.begin(), stats.end()); @@ -177,7 +177,9 @@ void run_for_size(unsigned m, unsigned n, T /*dummy*/, const char * type, const char * size, vnl_random & rng) { constexpr unsigned n_data = 10; - std::vector> x(n_data), y(n_data), z(n_data); + std::vector> x(n_data); + std::vector> y(n_data); + std::vector> z(n_data); std::vector v(n_data); vnl_matrix A(m, n); @@ -192,7 +194,7 @@ run_for_size(unsigned m, unsigned n, T /*dummy*/, const char * type, const char } fill_with_rng(A.begin(), A.end(), -10000, 10000, rng); - int n_loops = 1000000 / m; + const int n_loops = 1000000 / m; std::cout << "\nTimes to operator on " << type << ' ' << m << "-d vectors and " << m << " x " << n << " matrices, size " << size << '\n' << "Sum of square differences " << std::flush; diff --git a/core/vnl/tests/test_alignment.cxx b/core/vnl/tests/test_alignment.cxx index bf2c24c05d6..65fc6165f5c 100644 --- a/core/vnl/tests/test_alignment.cxx +++ b/core/vnl/tests/test_alignment.cxx @@ -14,14 +14,14 @@ inline bool test_element_product(const vnl_vector & vec, const vnl_vector & vec2, vnl_vector & result) { - unsigned n = result.size(); + const unsigned n = result.size(); vnl_c_vector::multiply(vec.data_block(), vec2.data_block(), result.data_block(), n); vnl_vector correct(n); for (unsigned i = 0; i < n; ++i) correct(i) = vec(i) * vec2(i); - float err = vnl_vector_ssd(correct, result); - float neps = float(n) * std::numeric_limits::epsilon(); + const float err = vnl_vector_ssd(correct, result); + const float neps = float(n) * std::numeric_limits::epsilon(); if (err < neps) return true; else @@ -35,14 +35,14 @@ test_element_product(const vnl_vector & vec, const vnl_vector & ve inline bool test_dot_product(const vnl_vector & vec, const vnl_vector & vec2) { - float val = dot_product(vec, vec2); - unsigned n = vec.size(); + const float val = dot_product(vec, vec2); + const unsigned n = vec.size(); float correct = 0.f; for (unsigned i = 0; i < n; ++i) correct += vec(i) * vec2(i); - float err = std::abs(correct - val); - float neps = float(n) * std::numeric_limits::epsilon(); + const float err = std::abs(correct - val); + const float neps = float(n) * std::numeric_limits::epsilon(); if (err < neps) return true; else @@ -55,14 +55,14 @@ test_dot_product(const vnl_vector & vec, const vnl_vector & vec2) inline bool test_euclid_dist_sq(const vnl_vector & vec, const vnl_vector & vec2) { - float val = vnl_vector_ssd(vec, vec2); - unsigned n = vec.size(); + const float val = vnl_vector_ssd(vec, vec2); + const unsigned n = vec.size(); float correct(0); for (unsigned i = 0; i < n; ++i) correct += vnl_math::sqr(vec(i) - vec2(i)); - float err = std::abs(correct - val); - float neps = float(n) * std::sqrt(std::numeric_limits::epsilon()); + const float err = std::abs(correct - val); + const float neps = float(n) * std::sqrt(std::numeric_limits::epsilon()); if (err < neps) return true; else @@ -75,7 +75,7 @@ test_euclid_dist_sq(const vnl_vector & vec, const vnl_vector & vec inline bool test_matrix_x_vector(const vnl_matrix & mat, const vnl_vector & vec, vnl_vector & result) { - unsigned n = vec.size(); + const unsigned n = vec.size(); vnl_sse::matrix_x_vector(mat.data_block(), vec.data_block(), result.data_block(), n, n); vnl_vector correct(n); @@ -87,8 +87,8 @@ test_matrix_x_vector(const vnl_matrix & mat, const vnl_vector & ve correct(i) = som; } - float err = vnl_vector_ssd(correct, result); - float neps = float(n) * std::numeric_limits::epsilon(); + const float err = vnl_vector_ssd(correct, result); + const float neps = float(n) * std::numeric_limits::epsilon(); if (err < neps) return true; else @@ -101,7 +101,7 @@ test_matrix_x_vector(const vnl_matrix & mat, const vnl_vector & ve inline bool test_vector_x_matrix(const vnl_vector & vec, const vnl_matrix & mat, vnl_vector & result) { - unsigned n = vec.size(); + const unsigned n = vec.size(); vnl_sse::vector_x_matrix(vec.data_block(), mat.data_block(), result.data_block(), n, n); vnl_vector correct(n); @@ -113,8 +113,8 @@ test_vector_x_matrix(const vnl_vector & vec, const vnl_matrix & ma correct(j) = som; } - float err = vnl_vector_ssd(correct, result); - float neps = float(n) * std::numeric_limits::epsilon(); + const float err = vnl_vector_ssd(correct, result); + const float neps = float(n) * std::numeric_limits::epsilon(); if (err < neps) return true; else @@ -127,14 +127,14 @@ test_vector_x_matrix(const vnl_vector & vec, const vnl_matrix & ma inline bool test_sum(const vnl_vector & vec) { - float val = vec.sum(); - unsigned n = vec.size(); + const float val = vec.sum(); + const unsigned n = vec.size(); float correct(0); for (unsigned i = 0; i < n; ++i) correct += vec(i); - float err = std::abs(correct - val); - float neps = float(n) * std::numeric_limits::epsilon(); + const float err = std::abs(correct - val); + const float neps = float(n) * std::numeric_limits::epsilon(); if (err < neps) return true; else @@ -147,14 +147,14 @@ test_sum(const vnl_vector & vec) inline bool test_max(const vnl_vector & vec) { - float val = vec.max_value(); - unsigned n = vec.size(); + const float val = vec.max_value(); + const unsigned n = vec.size(); float correct(-std::numeric_limits::max()); for (unsigned i = 0; i < n; ++i) correct = std::max(vec(i), correct); - float err = std::abs(correct - val); - float neps = float(n) * std::numeric_limits::epsilon(); + const float err = std::abs(correct - val); + const float neps = float(n) * std::numeric_limits::epsilon(); if (err < neps) return true; else @@ -167,14 +167,14 @@ test_max(const vnl_vector & vec) inline bool test_min(const vnl_vector & vec) { - float val = vec.min_value(); - unsigned n = vec.size(); + const float val = vec.min_value(); + const unsigned n = vec.size(); float correct(std::numeric_limits::max()); for (unsigned i = 0; i < n; ++i) correct = std::min(vec(i), correct); - float err = std::abs(correct - val); - float neps = float(n) * std::numeric_limits::epsilon(); + const float err = std::abs(correct - val); + const float neps = float(n) * std::numeric_limits::epsilon(); if (err < neps) return true; else @@ -187,8 +187,8 @@ test_min(const vnl_vector & vec) inline bool test_arg_max(const vnl_vector & vec) { - unsigned idx = vec.arg_max(); - unsigned n = vec.size(); + const unsigned idx = vec.arg_max(); + const unsigned n = vec.size(); float correct_val(-std::numeric_limits::max()); unsigned correct_idx = 0; for (unsigned i = 0; i < n; ++i) @@ -207,8 +207,8 @@ test_arg_max(const vnl_vector & vec) inline bool test_arg_min(const vnl_vector & vec) { - unsigned idx = vec.arg_min(); - unsigned n = vec.size(); + const unsigned idx = vec.arg_min(); + const unsigned n = vec.size(); float correct_val(std::numeric_limits::max()); unsigned correct_idx = 0; for (unsigned i = 0; i < n; ++i) @@ -260,10 +260,10 @@ test_alignment_type() const vnl_vector_ref vec2(nv, matrix_data + m); const vnl_vector_ref vec(nv, vector_data + v); vnl_vector_ref result(nv, result_data + r); - bool rvtest = test_element_product(vec, vec2, result) && test_dot_product(vec, vec2) && - test_euclid_dist_sq(vec, vec2) && test_matrix_x_vector(mat, vec, result) && - test_vector_x_matrix(vec, mat, result) && test_sum(vec) && test_max(vec) && test_min(vec) && - test_arg_max(vec) && test_arg_min(vec); + const bool rvtest = test_element_product(vec, vec2, result) && test_dot_product(vec, vec2) && + test_euclid_dist_sq(vec, vec2) && test_matrix_x_vector(mat, vec, result) && + test_vector_x_matrix(vec, mat, result) && test_sum(vec) && test_max(vec) && + test_min(vec) && test_arg_max(vec) && test_arg_min(vec); TEST("SSE", rvtest, true); } } diff --git a/core/vnl/tests/test_arithmetic.cxx b/core/vnl/tests/test_arithmetic.cxx index cdf5fbc3ea0..e2a0c8096f8 100644 --- a/core/vnl/tests/test_arithmetic.cxx +++ b/core/vnl/tests/test_arithmetic.cxx @@ -10,11 +10,11 @@ // --- dynamic ------------------------------ -#define NewMat(mat, r, c, data) \ - assert(sizeof(data) >= (r) * (c) * sizeof(double)); \ +#define NewMat(mat, r, c, data) \ + assert(sizeof(data) >= (r) * (c) * sizeof(double)); \ vnl_matrix mat(data, r, c) -#define NewVec(vec, n, data) \ - assert(sizeof(data) >= (n) * sizeof(double)); \ +#define NewVec(vec, n, data) \ + assert(sizeof(data) >= (n) * sizeof(double)); \ vnl_vector vec(data, n) static void @@ -29,11 +29,11 @@ test_arithmetic_dynamic() // --- ref ---------------------------------- -#define NewMat(mat, r, c, data) \ - assert(sizeof(data) >= (r) * (c) * sizeof(double)); \ +#define NewMat(mat, r, c, data) \ + assert(sizeof(data) >= (r) * (c) * sizeof(double)); \ vnl_matrix_ref mat(r, c, data) -#define NewVec(vec, n, data) \ - assert(sizeof(data) >= (n) * sizeof(double)); \ +#define NewVec(vec, n, data) \ + assert(sizeof(data) >= (n) * sizeof(double)); \ vnl_vector_ref vec(n, data) static void @@ -48,11 +48,11 @@ test_arithmetic_ref() #undef NewMat #undef NewVec -#define NewMat(mat, r, c, data) \ - assert(sizeof(data) >= (r) * (c) * sizeof(double)); \ +#define NewMat(mat, r, c, data) \ + assert(sizeof(data) >= (r) * (c) * sizeof(double)); \ vnl_matrix_fixed mat(data) -#define NewVec(vec, n, data) \ - assert(sizeof(data) >= (n) * sizeof(double)); \ +#define NewVec(vec, n, data) \ + assert(sizeof(data) >= (n) * sizeof(double)); \ vnl_vector_fixed vec(data) void diff --git a/core/vnl/tests/test_arithmetic_body.h b/core/vnl/tests/test_arithmetic_body.h index c527566b6ba..1af88225354 100644 --- a/core/vnl/tests/test_arithmetic_body.h +++ b/core/vnl/tests/test_arithmetic_body.h @@ -14,280 +14,275 @@ #include "testlib/testlib_test.h" -//void -//test_arithmetic() +// void +// test_arithmetic() //{ - double m1_data[] = { 1, 2, 3, 4, 5, 6 }; - double m2_data[] = { 7, 8, 9, 1, 2, 3 }; - double m3_data[] = { 3, 4, 5, 6, 7, 8 }; - double v1_data[] = { 3, 2 }; - double v2_data[] = { 1, 4 }; - double v3_data[] = { 1, 2, 3 }; - - double m1_data_copy[] = { 1, 2, 3, 4, 5, 6 }; - double m2_data_copy[] = { 7, 8, 9, 1, 2, 3 }; - //double m3_data_copy[] = { 3, 4, 5, 6, 7, 8 }; - double v1_data_copy[] = { 3, 2 }; - double v2_data_copy[] = { 1, 4 }; - //double v3_data_copy[] = { 1, 2, 3 }; - - // Storage for temporary vectors/matrices, when the actual type is a - // reference. - double tmp1[100]; - - NewMat( m1, 3, 2, m1_data ); - TEST( "3x2 matrix construction" , - m1.rows() == 3 && m1.cols() == 2 && - m1(0,0)==1 && m1(0,1)==2 && - m1(1,0)==3 && m1(1,1)==4 && - m1(2,0)==5 && m1(2,1)==6, true); - - NewMat( m3, 2, 3, m3_data ); - TEST( "2x3 matrix construction" , - m3.rows() == 2 && m3.cols() == 3 && - m3(0,0)==3 && m3(0,1)==4 && m3(0,2)==5 && - m3(1,0)==6 && m3(1,1)==7 && m3(1,2)==8, true); - - NewVec( v1, 2, v1_data ); - TEST( "2 vector construction" , - v1.size() == 2 && - v1[0] == 3 && v1[1] == 2, true); - - NewVec( v3, 3, v3_data ); - TEST( "3 vector construction" , - v3.size() == 3 && - v3[0] == 1 && v3[1] == 2 && v3[2] == 3, true); - - // Assume these will work - NewMat( m2, 3, 2, m2_data ); - NewVec( v2, 2, v2_data ); - NewMat( m1_orig, 3, 2, m1_data_copy ); - NewMat( m2_orig, 3, 2, m2_data_copy ); - //NewMat( m3_orig, 3, 2, m3_data_copy ); - NewVec( v1_orig, 2, v1_data_copy ); - NewVec( v2_orig, 2, v2_data_copy ); - //NewVec( v3_orig, 2, v3_data_copy ); - - // Equality - { - TEST( "Equality operator/1", v1 == v1_orig, true ); - TEST( "Equality operator/2", v1 == v2_orig, false ); - TEST( "Inequality operator/1", v1 != v1_orig, false ); - TEST( "Inequality operator/2", v1 != v2_orig, true ); - } - - // Assignment should do a data copy, even if the types are - // references. - { - double v_result_data[] = { 9, 2 }; - NewVec( v_result, 2, v_result_data ); - - NewVec( tv, 2, tmp1 ); - tv = v1; - tv(0) = 9; - TEST( "Assignment on vector", tv == v_result && v1 == v1_orig, true ); - - double m_result_data[] = { 1, 2, 3, 8, 5, 6 }; - NewMat( m_result, 3, 2, m_result_data ); - - NewMat( tm, 3, 2, tmp1 ); - tm = m1; - tm(1,1) = 8; - TEST( "Assignment on matrix", tm == m_result && m1 == m1_orig, true ); - } - - // Addition - { - // Vector-vector - double v_add1_data[] = { 4, 6 }; - NewVec( v_add1, 2, v_add1_data ); - - NewVec( tv1, 2, tmp1 ); - tv1 = v1; - tv1 += v2; - TEST( "v += v", tv1 == v_add1 && v2 == v2_orig, true ); - TEST( "v + v", v1+v2 == v_add1 && v1 == v1_orig && v2 == v2_orig, true ); - - // Vector-scalar - double v_add2_data[] = { 8, 7 }; - NewVec( v_add2, 2, v_add2_data ); - - NewVec( tv2, 2, tmp1 ); - tv2 = v1; - tv2 += 5; - TEST( "v += s", tv2 == v_add2, true ); - TEST( "v + s", v1+5.0 == v_add2 && v1 == v1_orig, true ); - TEST( "s + v", 5.0+v1 == v_add2 && v1 == v1_orig, true ); - - // Matrix-matrix - double m_add1_data[] = { 8, 10, 12, 5, 7, 9 }; - NewMat( m_add1, 3, 2, m_add1_data ); - - NewMat( mv1, 3, 2, tmp1 ); - mv1 = m1; - mv1 += m2; - TEST( "m += m", mv1 == m_add1 && m2 == m2_orig, true ); - TEST( "m + m", m1+m2 == m_add1 && m1 == m1_orig && m2 == m2_orig, true ); - - // Matrix-scalar - double m_add2_data[] = { 4, 5, 6, 7, 8, 9 }; - NewMat( m_add2, 3, 2, m_add2_data ); - - NewMat( mv2, 3, 2, tmp1 ); - mv2 = m1; - mv2 += 3; - TEST( "m += s", mv2 == m_add2, true ); - TEST( "m + s", m1+3.0 == m_add2 && m1 == m1_orig, true ); - TEST( "s + m", 3.0+m1 == m_add2 && m1 == m1_orig, true ); - } - - // Subtraction - { - // Vector-vector - double v_sub1_data[] = { 2, -2 }; - NewVec( v_sub1, 2, v_sub1_data ); - - NewVec( tv1, 2, tmp1 ); - tv1 = v1; - tv1 -= v2; - TEST( "v -= v", tv1 == v_sub1 && v2 == v2_orig, true ); - TEST( "v - v", v1-v2 == v_sub1 && v1 == v1_orig && v2 == v2_orig, true ); - - // Vector-scalar - double v_sub2_data[] = { 2, 1 }; - NewVec( v_sub2, 2, v_sub2_data ); - double v_sub3_data[] = { -2, -1 }; - NewVec( v_sub3, 2, v_sub3_data ); - - NewVec( tv2, 2, tmp1 ); - tv2 = v1; - tv2 -= 1; - TEST( "v -= s", tv2 == v_sub2, true ); - TEST( "v - s", v1-1.0 == v_sub2 && v1 == v1_orig, true ); - TEST( "s - v", 1.0-v1 == v_sub3 && v1 == v1_orig, true ); - - // Matrix-matrix - double m_sub1_data[] = { -6, -6, -6, 3, 3, 3 }; - NewMat( m_sub1, 3, 2, m_sub1_data ); - - NewMat( mv1, 3, 2, tmp1 ); - mv1 = m1; - mv1 -= m2; - TEST( "m -= m", mv1 == m_sub1 && m2 == m2_orig, true ); - TEST( "m - m", m1-m2 == m_sub1 && m1 == m1_orig && m2 == m2_orig, true ); - - // Matrix+scalar - double m_sub2_data[] = { 0, 1, 2, 3, 4, 5 }; - double m_sub3_data[] = { 0, -1, -2, -3, -4, -5 }; - NewMat( m_sub2, 3, 2, m_sub2_data ); - NewMat( m_sub3, 3, 2, m_sub3_data ); - - NewMat( mv2, 3, 2, tmp1 ); - mv2 = m1; - mv2 -= 1; - TEST( "m -= s", mv2 == m_sub2, true ); - TEST( "m - s", m1-1.0 == m_sub2 && m1 == m1_orig, true ); - TEST( "s - m", 1.0-m1 == m_sub3 && m1 == m1_orig, true ); - } - - // Multiplication - { - // Vector-scalar - double v_mul1_data[] = { 9, 6 }; - NewVec( v_mul1, 2, v_mul1_data ); - - NewVec( tv1, 2, tmp1 ); - tv1 = v1; - tv1 *= 3; - TEST( "v *= s", tv1 == v_mul1, true ); - TEST( "v * s", v1*3.0 == v_mul1 && v1 == v1_orig, true ); - TEST( "s * v", 3.0*v1 == v_mul1 && v1 == v1_orig, true ); - - // Matrix-scalar - double m_mul1_data[] = { 2, 4, 6, 8, 10, 12 }; - NewMat( m_mul1, 3, 2, m_mul1_data ); - - NewMat( mv1, 3, 2, tmp1 ); - mv1 = m1; - mv1 *= 2; - TEST( "m *= s", mv1 == m_mul1, true ); - TEST( "m * s", m1*2.0 == m_mul1 && m1 == m1_orig, true ); - TEST( "s * m", 2.0*m1 == m_mul1 && m1 == m1_orig, true ); - - // Matrix-vector - double v_mul2_data[] = { 7, 17, 27 }; - NewVec( v_mul2, 3, v_mul2_data ); - - TEST( "m * v", m1*v1 == v_mul2, true ); - } - - // Division - { - // Vector-scalar - double v_div1_data[] = { 1.5, 1 }; - NewVec( v_div1, 2, v_div1_data ); - - NewVec( tv1, 2, tmp1 ); - tv1 = v1; - tv1 /= 2; - TEST( "v /= s", tv1 == v_div1, true ); - TEST( "v / s", v1/2.0 == v_div1 && v1 == v1_orig, true ); - - // Matrix+scalar - double m_div1_data[] = { 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 }; - NewMat( m_div1, 3, 2, m_div1_data ); - - NewMat( tm1, 3, 2, tmp1 ); - tm1 = m1; - tm1 /= 2; - TEST( "m /= s", tm1 == m_div1, true ); - TEST( "m / s", m1/2.0 == m_div1 && m1 == m1_orig, true ); - } - - // Element product - { - // Vector - double v_ep1_data[] = { 3, 8 }; - NewVec( v_ep1, 2, v_ep1_data ); - - TEST( "element_product(v,v)", element_product(v1,v2) == v_ep1, true ); - - // Matrix - double m_ep1_data[] = { 7, 16, 27, 4, 10, 18 }; - NewMat( m_ep1, 3, 2, m_ep1_data ); - - TEST( "element_product(m,m)", element_product(m1,m2) == m_ep1, true ); - } - - // Element quotient - { - // Vector - double v_eq1_data[] = { 3, 0.5 }; - NewVec( v_eq1, 2, v_eq1_data ); - - TEST( "element_quotient(v,v)", element_quotient(v1,v2) == v_eq1, true ); - - // Matrix - double m_eq1_data[] = { 1.0/7.0, 2.0/8.0, 3.0/9.0, 4.0/1.0, 5.0/2.0, 6.0/3.0 }; - NewMat( m_eq1, 3, 2, m_eq1_data ); - - TEST( "element_quotient(m,m)", element_quotient(m1,m2) == m_eq1, true ); - } - - // Negation - { - // Vector - double v_neg1_data[] = { -3, -2 }; - NewVec( v_neg1, 2, v_neg1_data ); - - TEST( "-v", -v1 == v_neg1 && v1 == v1_orig, true ); - - // Matrix - double m_neg1_data[] = { -1, -2, -3, -4, -5, -6 }; - NewMat( m_neg1, 3, 2, m_neg1_data ); - - TEST( "-m", -m1 == m_neg1 && m1 == m1_orig, true ); - } +double m1_data[] = { 1, 2, 3, 4, 5, 6 }; +double m2_data[] = { 7, 8, 9, 1, 2, 3 }; +double m3_data[] = { 3, 4, 5, 6, 7, 8 }; +double v1_data[] = { 3, 2 }; +double v2_data[] = { 1, 4 }; +double v3_data[] = { 1, 2, 3 }; + +double m1_data_copy[] = { 1, 2, 3, 4, 5, 6 }; +double m2_data_copy[] = { 7, 8, 9, 1, 2, 3 }; +// double m3_data_copy[] = { 3, 4, 5, 6, 7, 8 }; +double v1_data_copy[] = { 3, 2 }; +double v2_data_copy[] = { 1, 4 }; +// double v3_data_copy[] = { 1, 2, 3 }; + +// Storage for temporary vectors/matrices, when the actual type is a +// reference. +double tmp1[100]; + +NewMat(m1, 3, 2, m1_data); +TEST("3x2 matrix construction", + m1.rows() == 3 && m1.cols() == 2 && m1(0, 0) == 1 && m1(0, 1) == 2 && m1(1, 0) == 3 && m1(1, 1) == 4 && + m1(2, 0) == 5 && m1(2, 1) == 6, + true); + +NewMat(m3, 2, 3, m3_data); +TEST("2x3 matrix construction", + m3.rows() == 2 && m3.cols() == 3 && m3(0, 0) == 3 && m3(0, 1) == 4 && m3(0, 2) == 5 && m3(1, 0) == 6 && + m3(1, 1) == 7 && m3(1, 2) == 8, + true); + +NewVec(v1, 2, v1_data); +TEST("2 vector construction", v1.size() == 2 && v1[0] == 3 && v1[1] == 2, true); + +NewVec(v3, 3, v3_data); +TEST("3 vector construction", v3.size() == 3 && v3[0] == 1 && v3[1] == 2 && v3[2] == 3, true); + +// Assume these will work +NewMat(m2, 3, 2, m2_data); +NewVec(v2, 2, v2_data); +NewMat(m1_orig, 3, 2, m1_data_copy); +NewMat(m2_orig, 3, 2, m2_data_copy); +// NewMat( m3_orig, 3, 2, m3_data_copy ); +NewVec(v1_orig, 2, v1_data_copy); +NewVec(v2_orig, 2, v2_data_copy); +// NewVec( v3_orig, 2, v3_data_copy ); + +// Equality +{ + TEST("Equality operator/1", v1 == v1_orig, true); + TEST("Equality operator/2", v1 == v2_orig, false); + TEST("Inequality operator/1", v1 != v1_orig, false); + TEST("Inequality operator/2", v1 != v2_orig, true); +} + +// Assignment should do a data copy, even if the types are +// references. +{ + double v_result_data[] = { 9, 2 }; + NewVec(v_result, 2, v_result_data); + + NewVec(tv, 2, tmp1); + tv = v1; + tv(0) = 9; + TEST("Assignment on vector", tv == v_result && v1 == v1_orig, true); + + double m_result_data[] = { 1, 2, 3, 8, 5, 6 }; + NewMat(m_result, 3, 2, m_result_data); + + NewMat(tm, 3, 2, tmp1); + tm = m1; + tm(1, 1) = 8; + TEST("Assignment on matrix", tm == m_result && m1 == m1_orig, true); +} + +// Addition +{ + // Vector-vector + double v_add1_data[] = { 4, 6 }; + NewVec(v_add1, 2, v_add1_data); + + NewVec(tv1, 2, tmp1); + tv1 = v1; + tv1 += v2; + TEST("v += v", tv1 == v_add1 && v2 == v2_orig, true); + TEST("v + v", v1 + v2 == v_add1 && v1 == v1_orig && v2 == v2_orig, true); + + // Vector-scalar + double v_add2_data[] = { 8, 7 }; + NewVec(v_add2, 2, v_add2_data); + + NewVec(tv2, 2, tmp1); + tv2 = v1; + tv2 += 5; + TEST("v += s", tv2 == v_add2, true); + TEST("v + s", v1 + 5.0 == v_add2 && v1 == v1_orig, true); + TEST("s + v", 5.0 + v1 == v_add2 && v1 == v1_orig, true); + + // Matrix-matrix + double m_add1_data[] = { 8, 10, 12, 5, 7, 9 }; + NewMat(m_add1, 3, 2, m_add1_data); + + NewMat(mv1, 3, 2, tmp1); + mv1 = m1; + mv1 += m2; + TEST("m += m", mv1 == m_add1 && m2 == m2_orig, true); + TEST("m + m", m1 + m2 == m_add1 && m1 == m1_orig && m2 == m2_orig, true); + + // Matrix-scalar + double m_add2_data[] = { 4, 5, 6, 7, 8, 9 }; + NewMat(m_add2, 3, 2, m_add2_data); + + NewMat(mv2, 3, 2, tmp1); + mv2 = m1; + mv2 += 3; + TEST("m += s", mv2 == m_add2, true); + TEST("m + s", m1 + 3.0 == m_add2 && m1 == m1_orig, true); + TEST("s + m", 3.0 + m1 == m_add2 && m1 == m1_orig, true); +} + +// Subtraction +{ + // Vector-vector + double v_sub1_data[] = { 2, -2 }; + NewVec(v_sub1, 2, v_sub1_data); + + NewVec(tv1, 2, tmp1); + tv1 = v1; + tv1 -= v2; + TEST("v -= v", tv1 == v_sub1 && v2 == v2_orig, true); + TEST("v - v", v1 - v2 == v_sub1 && v1 == v1_orig && v2 == v2_orig, true); + + // Vector-scalar + double v_sub2_data[] = { 2, 1 }; + NewVec(v_sub2, 2, v_sub2_data); + double v_sub3_data[] = { -2, -1 }; + NewVec(v_sub3, 2, v_sub3_data); + + NewVec(tv2, 2, tmp1); + tv2 = v1; + tv2 -= 1; + TEST("v -= s", tv2 == v_sub2, true); + TEST("v - s", v1 - 1.0 == v_sub2 && v1 == v1_orig, true); + TEST("s - v", 1.0 - v1 == v_sub3 && v1 == v1_orig, true); + + // Matrix-matrix + double m_sub1_data[] = { -6, -6, -6, 3, 3, 3 }; + NewMat(m_sub1, 3, 2, m_sub1_data); + + NewMat(mv1, 3, 2, tmp1); + mv1 = m1; + mv1 -= m2; + TEST("m -= m", mv1 == m_sub1 && m2 == m2_orig, true); + TEST("m - m", m1 - m2 == m_sub1 && m1 == m1_orig && m2 == m2_orig, true); + + // Matrix+scalar + double m_sub2_data[] = { 0, 1, 2, 3, 4, 5 }; + double m_sub3_data[] = { 0, -1, -2, -3, -4, -5 }; + NewMat(m_sub2, 3, 2, m_sub2_data); + NewMat(m_sub3, 3, 2, m_sub3_data); + + NewMat(mv2, 3, 2, tmp1); + mv2 = m1; + mv2 -= 1; + TEST("m -= s", mv2 == m_sub2, true); + TEST("m - s", m1 - 1.0 == m_sub2 && m1 == m1_orig, true); + TEST("s - m", 1.0 - m1 == m_sub3 && m1 == m1_orig, true); +} + +// Multiplication +{ + // Vector-scalar + double v_mul1_data[] = { 9, 6 }; + NewVec(v_mul1, 2, v_mul1_data); + + NewVec(tv1, 2, tmp1); + tv1 = v1; + tv1 *= 3; + TEST("v *= s", tv1 == v_mul1, true); + TEST("v * s", v1 * 3.0 == v_mul1 && v1 == v1_orig, true); + TEST("s * v", 3.0 * v1 == v_mul1 && v1 == v1_orig, true); + + // Matrix-scalar + double m_mul1_data[] = { 2, 4, 6, 8, 10, 12 }; + NewMat(m_mul1, 3, 2, m_mul1_data); + + NewMat(mv1, 3, 2, tmp1); + mv1 = m1; + mv1 *= 2; + TEST("m *= s", mv1 == m_mul1, true); + TEST("m * s", m1 * 2.0 == m_mul1 && m1 == m1_orig, true); + TEST("s * m", 2.0 * m1 == m_mul1 && m1 == m1_orig, true); + + // Matrix-vector + double v_mul2_data[] = { 7, 17, 27 }; + NewVec(v_mul2, 3, v_mul2_data); + + TEST("m * v", m1 * v1 == v_mul2, true); +} + +// Division +{ + // Vector-scalar + double v_div1_data[] = { 1.5, 1 }; + NewVec(v_div1, 2, v_div1_data); + + NewVec(tv1, 2, tmp1); + tv1 = v1; + tv1 /= 2; + TEST("v /= s", tv1 == v_div1, true); + TEST("v / s", v1 / 2.0 == v_div1 && v1 == v1_orig, true); + + // Matrix+scalar + double m_div1_data[] = { 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 }; + NewMat(m_div1, 3, 2, m_div1_data); + + NewMat(tm1, 3, 2, tmp1); + tm1 = m1; + tm1 /= 2; + TEST("m /= s", tm1 == m_div1, true); + TEST("m / s", m1 / 2.0 == m_div1 && m1 == m1_orig, true); +} + +// Element product +{ + // Vector + double v_ep1_data[] = { 3, 8 }; + NewVec(v_ep1, 2, v_ep1_data); + + TEST("element_product(v,v)", element_product(v1, v2) == v_ep1, true); + + // Matrix + double m_ep1_data[] = { 7, 16, 27, 4, 10, 18 }; + NewMat(m_ep1, 3, 2, m_ep1_data); + + TEST("element_product(m,m)", element_product(m1, m2) == m_ep1, true); +} + +// Element quotient +{ + // Vector + double v_eq1_data[] = { 3, 0.5 }; + NewVec(v_eq1, 2, v_eq1_data); + + TEST("element_quotient(v,v)", element_quotient(v1, v2) == v_eq1, true); + + // Matrix + double m_eq1_data[] = { 1.0 / 7.0, 2.0 / 8.0, 3.0 / 9.0, 4.0 / 1.0, 5.0 / 2.0, 6.0 / 3.0 }; + NewMat(m_eq1, 3, 2, m_eq1_data); + + TEST("element_quotient(m,m)", element_quotient(m1, m2) == m_eq1, true); +} + +// Negation +{ + // Vector + double v_neg1_data[] = { -3, -2 }; + NewVec(v_neg1, 2, v_neg1_data); + + TEST("-v", -v1 == v_neg1 && v1 == v1_orig, true); + + // Matrix + double m_neg1_data[] = { -1, -2, -3, -4, -5, -6 }; + NewMat(m_neg1, 3, 2, m_neg1_data); + + TEST("-m", -m1 == m_neg1 && m1 == m1_orig, true); +} //} #endif // vnl_test_arithmetic_body_h_ diff --git a/core/vnl/tests/test_bignum.cxx b/core/vnl/tests/test_bignum.cxx index 1a85385b1fe..6415003fcf2 100644 --- a/core/vnl/tests/test_bignum.cxx +++ b/core/vnl/tests/test_bignum.cxx @@ -96,43 +96,43 @@ run_constructor_tests() std::cout << "long constructor:\n"; { - vnl_bignum b(0L); + const vnl_bignum b(0L); TEST("vnl_bignum b(0L);", b, 0L); } { - vnl_bignum b(1L); + const vnl_bignum b(1L); TEST("vnl_bignum b(1L);", b, 1L); } { - vnl_bignum b(-1L); + const vnl_bignum b(-1L); TEST("vnl_bignum b(-1L);", b, -1L); } { - vnl_bignum b(0x7fffL); + const vnl_bignum b(0x7fffL); TEST("vnl_bignum b(0x7fffL);", b, 0x7fffL); } { - vnl_bignum b(-0x7fffL); + const vnl_bignum b(-0x7fffL); TEST("vnl_bignum b(-0x7fffL);", b, -0x7fffL); } { - vnl_bignum b(0x7fffffffL); + const vnl_bignum b(0x7fffffffL); TEST("vnl_bignum b(0x7fffffffL);", b, 0x7fffffffL); } { - vnl_bignum b(-0x7fffffffL); + const vnl_bignum b(-0x7fffffffL); TEST("vnl_bignum b(-0x7fffffffL);", b, -0x7fffffffL); } { - vnl_bignum b(0xf00000L); + const vnl_bignum b(0xf00000L); TEST("vnl_bignum b(0xf00000L);", b, 0xf00000); } { - vnl_bignum b(LONG_MAX); + const vnl_bignum b(LONG_MAX); TEST("vnl_bignum b(LONG_MAX);", b, LONG_MAX); } { - vnl_bignum b(LONG_MIN); + const vnl_bignum b(LONG_MIN); TEST("vnl_bignum b(LONG_MIN);", b, LONG_MIN); } @@ -174,7 +174,7 @@ run_constructor_tests() TEST("vnl_bignum b(-1234567e3);", (double)b, -1234567e3); } { - vnl_bignum b(double(0xf00000)); + const vnl_bignum b(double(0xf00000)); TEST("vnl_bignum b(double(0xf00000));", b, 0xf00000); } @@ -216,27 +216,27 @@ run_constructor_tests() std::cout << "char* constructor:\n"; { - vnl_bignum b("-1"); + const vnl_bignum b("-1"); TEST("vnl_bignum b(\"-1\");", b, -1L); } { - vnl_bignum b("+1"); + const vnl_bignum b("+1"); TEST("vnl_bignum b(\"+1\");", b, 1L); } { - vnl_bignum b("1"); + const vnl_bignum b("1"); TEST("vnl_bignum b(\"1\");", b, 1L); } { - vnl_bignum b("123"); + const vnl_bignum b("123"); TEST("vnl_bignum b(\"123\");", b, 123L); } { - vnl_bignum b("123e5"); + const vnl_bignum b("123e5"); TEST("vnl_bignum b(\"123e5\");", b, 12300000L); } { - vnl_bignum b("-123e+4"); + const vnl_bignum b("-123e+4"); TEST("vnl_bignum b(\"-123e+4\");", b, -1230000L); } { @@ -244,7 +244,7 @@ run_constructor_tests() TEST("vnl_bignum b(\"123e12\");", (double)b, 123e12); } { - vnl_bignum b("-1e120"); + const vnl_bignum b("-1e120"); std::stringstream s; s << b; std::cout << b << '\n'; @@ -262,64 +262,64 @@ run_constructor_tests() std::cout << "length of string: " << s.str().length() << std::endl; } { - vnl_bignum b("0x0"); + const vnl_bignum b("0x0"); TEST("vnl_bignum b(\"0x0\");", b, 0x0); } { - vnl_bignum b("0x9"); + const vnl_bignum b("0x9"); TEST("vnl_bignum b(\"0x9\");", b, 0x9); } { - vnl_bignum b("0xa"); + const vnl_bignum b("0xa"); TEST("vnl_bignum b(\"0xa\");", b, 0xa); } { - vnl_bignum b("0xf"); + const vnl_bignum b("0xf"); TEST("vnl_bignum b(\"0xf\");", b, 0xf); } { - vnl_bignum b("0xA"); + const vnl_bignum b("0xA"); TEST("vnl_bignum b(\"0xA\");", b, 0xa); } { - vnl_bignum b("0xF"); + const vnl_bignum b("0xF"); TEST("vnl_bignum b(\"0xF\");", b, 0xf); } { - vnl_bignum b("0x1aF"); + const vnl_bignum b("0x1aF"); TEST("vnl_bignum b(\"0x1aF\");", b, 0x1af); } { - vnl_bignum b("0"); + const vnl_bignum b("0"); TEST("vnl_bignum b(\"0\");", b, 0); } { - vnl_bignum b("00"); + const vnl_bignum b("00"); TEST("vnl_bignum b(\"00\");", b, 0); } { - vnl_bignum b("012334567"); + const vnl_bignum b("012334567"); TEST("vnl_bignum b(\"012334567\");", b, 012334567); } { - vnl_bignum b("9"); + const vnl_bignum b("9"); TEST("vnl_bignum b(\"9\");", b, 9); } { - vnl_bignum b(" 9"); + const vnl_bignum b(" 9"); TEST("vnl_bignum b(\" 9\");", b, 9); } // infinity: { - vnl_bignum b("+Inf"); + const vnl_bignum b("+Inf"); TEST("vnl_bignum b(\"+Inf\");", b.is_plus_infinity(), true); } { - vnl_bignum b("Infinity"); + const vnl_bignum b("Infinity"); TEST("vnl_bignum b(\"Infinity\");", b.is_plus_infinity(), true); } { - vnl_bignum b("-Infin"); + const vnl_bignum b("-Infin"); TEST("vnl_bignum b(\"-Infin\");", b.is_minus_infinity(), true); } @@ -551,7 +551,7 @@ run_assignment_tests() // vnl_bignum& assignment operator b1 = "0"; - vnl_bignum b5(0x1ffffL); + const vnl_bignum b5(0x1ffffL); TEST_RUN("b1 = b5", b1 = b5, b1, b5); } @@ -559,12 +559,12 @@ static void run_logical_comparison_tests() { std::cout << "\nStarting logical comparison tests:\n"; - vnl_bignum b0(0L); - vnl_bignum b1(1L); + const vnl_bignum b0(0L); + const vnl_bignum b1(1L); vnl_bignum b2(0x7fffL); - vnl_bignum b3(-0x7fffL); - vnl_bignum p_inf("+Inf"); - vnl_bignum m_inf("-Inf"); + const vnl_bignum b3(-0x7fffL); + const vnl_bignum p_inf("+Inf"); + const vnl_bignum m_inf("-Inf"); TEST("b0 == b0", b0 == b0, true); TEST("b0 == b1", b0 == b1, false); @@ -670,7 +670,6 @@ run_division_tests() TEST("vnl_bignum(\"+Inf\")/(-1L)", vnl_bignum("+Inf") / (-1L), vnl_bignum("-Inf")); TEST("vnl_bignum(-1L)/0L", vnl_bignum(-1L) / 0L, vnl_bignum("-Inf")); - long i, j, k, l; long div_errors = 0; long mod_errors = 0; @@ -678,18 +677,18 @@ run_division_tests() << " for (j = 0x7ffffff; j > 0; j /= 0x10)\n" << " for (k = 1; k < 17; ++k)\n" << " for (l = 1; l < 17; ++l)\n "; - for (i = 0xffffff; i > 0; i /= 0x10) + for (long i = 0xffffff; i > 0; i /= 0x10) { std::cout.put('.'); std::cout.flush(); - for (j = 0x7ffffff; j > 0; j /= 0x10) + for (long j = 0x7ffffff; j > 0; j /= 0x10) { - for (k = 1; k < 17; ++k) + for (long k = 1; k < 17; ++k) { - for (l = 1; l < 17; ++l) + for (long l = 1; l < 17; ++l) { - vnl_bignum b1(i + k); - vnl_bignum b2(j + l); + const vnl_bignum b1(i + k); + const vnl_bignum b2(j + l); vnl_bignum b3(long((i + k) / (j + l))); if (b1 / b2 != b3) { @@ -742,7 +741,8 @@ run_large_division_tests() { std::cout << "\nStarting large division tests:\n"; - vnl_bignum a("10000000"), b("10000001"); + vnl_bignum a("10000000"); + vnl_bignum b("10000001"); b *= a; vnl_bignum c = b / 10000001; std::cout << b << " / 10000001 = " << c << ", must be 10000000\n"; @@ -824,8 +824,8 @@ run_multiplication_division_tests() { std::cout << "\nCheck example in book:\n"; - vnl_bignum b2 = "0xffffffff"; // Create vnl_bignum object - vnl_bignum b3 = "12345e30"; // Create vnl_bignum object + const vnl_bignum b2 = "0xffffffff"; // Create vnl_bignum object + const vnl_bignum b3 = "12345e30"; // Create vnl_bignum object std::cout << "b2 = " << b2 << std::endl << "b3 = " << b3 << std::endl; @@ -839,24 +839,22 @@ run_addition_subtraction_tests() { std::cout << "\nStarting addition, subtraction tests:\n"; - long i, j; long add_errors = 0; long sub_errors = 0; - vnl_bignum bi, bj, bij; std::cout << " for (i = 1; i < 0xfffffff; i *= 3)\n" << " for (j = 1; j < 0xfffffff; j *= 3)\n "; { - for (i = 1; i < 0xfffffff; i *= 3) + for (long i = 1; i < 0xfffffff; i *= 3) { std::cout.put('.'); std::cout.flush(); - for (j = 1; j < 0xfffffff; j *= 3) + for (long j = 1; j < 0xfffffff; j *= 3) { - bi = i; - bj = j; - bij = vnl_bignum(i + j); + const vnl_bignum bi = i; + const vnl_bignum bj = j; + vnl_bignum bij = vnl_bignum(i + j); if (bi + bj != bij) { TEST("bi + bj == vnl_bignum(i + j)", false, true); @@ -877,10 +875,12 @@ run_addition_subtraction_tests() TEST("bi + bj == vnl_bignum(i + j)", add_errors, 0); TEST("bi - bj == vnl_bignum(i - j)", sub_errors, 0); - vnl_bignum b0(0L); - vnl_bignum zillion("1000000000000000000"); - vnl_bignum b1000(1000L), b1000000(1000000L); - vnl_bignum p_inf("+Inf"), m_inf("-Inf"); + const vnl_bignum b0(0L); + const vnl_bignum zillion("1000000000000000000"); + const vnl_bignum b1000(1000L); + const vnl_bignum b1000000(1000000L); + const vnl_bignum p_inf("+Inf"); + const vnl_bignum m_inf("-Inf"); TEST("-b0 == b0", -b0, b0); TEST("-p_inf == m_inf", -p_inf, m_inf); @@ -928,8 +928,8 @@ run_addition_subtraction_tests() TEST("m_inf - zillion == m_inf", m_inf - zillion, m_inf); // example in book - vnl_bignum b2 = "0xffffffff"; // Create vnl_bignum object - vnl_bignum b3 = "12345e30"; // Create vnl_bignum object + const vnl_bignum b2 = "0xffffffff"; // Create vnl_bignum object + const vnl_bignum b3 = "12345e30"; // Create vnl_bignum object TEST("(b2+b3) - b2 = b3", (b2 + b3) - b2 == b3, 1); TEST("(b2+b3) - b3 = b2", (b2 + b3) - b3 == b2, 1); b3.dump(); @@ -1012,8 +1012,12 @@ run_multiplication_tests() { std::cout << "\nStarting multiplication tests:\n"; - vnl_bignum b0(0L), b1000(1000L), b1000000(1000000L), zillion("1000000000000000000"); - vnl_bignum p_inf("+Inf"), m_inf("-Inf"); + const vnl_bignum b0(0L); + const vnl_bignum b1000(1000L); + const vnl_bignum b1000000(1000000L); + const vnl_bignum zillion("1000000000000000000"); + const vnl_bignum p_inf("+Inf"); + const vnl_bignum m_inf("-Inf"); TEST("b0*b0 == b0", b0 * b0, b0); TEST("b0*b1000 == b0", b0 * b1000, b0); @@ -1034,7 +1038,8 @@ static void run_left_shift_tests() { vnl_bignum b1(1L); - vnl_bignum p_inf("+Inf"), m_inf("-Inf"); + const vnl_bignum p_inf("+Inf"); + const vnl_bignum m_inf("-Inf"); // left shift TEST("int(b1) == 1", int(b1), 1); @@ -1083,8 +1088,9 @@ run_left_shift_tests() static void run_right_shift_tests() { - vnl_bignum b2("4294967296"); - vnl_bignum p_inf("+Inf"), m_inf("-Inf"); + const vnl_bignum b2("4294967296"); + const vnl_bignum p_inf("+Inf"); + const vnl_bignum m_inf("-Inf"); // right shift TEST("b2 == vnl_bignum(\"4294967296\")", b2, vnl_bignum("4294967296")); diff --git a/core/vnl/tests/test_complex.cxx b/core/vnl/tests/test_complex.cxx index c49b7d11bb4..e3afb5b9a83 100644 --- a/core/vnl/tests/test_complex.cxx +++ b/core/vnl/tests/test_complex.cxx @@ -28,10 +28,9 @@ static void test_operators() { std::complex a(-5.); - std::complex b(7., -1.); - std::complex c; + const std::complex b(7., -1.); // Numerically deterministic double precision - c = a + b; + std::complex c = a + b; TEST("sum", c, std::complex(2., -1.)); c = a - b; TEST("difference", c, std::complex(-12., 1.)); @@ -48,7 +47,7 @@ test_operators() a *= b; TEST("*=", a, std::complex(-35., 5.)); // Numerically could have small floating point truncation errors - std::complex a_pre = a; + const std::complex a_pre = a; a /= b; TEST_NEAR("/=", a, std::complex(-5.), 1e-12); std::cout << "a /= b " << a_pre << " /= " << b << "\n --> " << a @@ -69,7 +68,7 @@ test_vector() << "dot_product(a,b)=" << dot_product(a, b) << '\n' << "inner_product(a,b)=" << inner_product(a, b) << '\n'; - std::complex i(0, 1); + const std::complex i(0, 1); TEST_NEAR("inner_product() conjugates correctly", inner_product(i * a, b), i * inner_product(a, b), 1e-12); TEST_NEAR("inner_product() conjugates correctly", inner_product(a, i * b), -i * inner_product(a, b), 1e-12); @@ -90,11 +89,11 @@ test_cosine() vnl_random rng(1234567); for (int i = 0; i < 20; ++i) { - double u = rng.drand32(vnl_math::pi_over_2); - double v = rng.drand32(2.0); - std::complex c(u, v); - std::complex d = std::cos(c); - std::complex e = tc_acos(d); + const double u = rng.drand32(vnl_math::pi_over_2); + const double v = rng.drand32(2.0); + const std::complex c(u, v); + const std::complex d = std::cos(c); + const std::complex e = tc_acos(d); std::cout << c << ' ' << d << ' ' << e << '\n'; TEST_NEAR("acos", c, e, 1e-12); } @@ -115,7 +114,8 @@ TESTMAIN(test_complex); std::complex tc_acos(std::complex x) { - double a = std::real(x), b = std::imag(x); + const double a = std::real(x); + const double b = std::imag(x); // special cases: if (b == 0 && a > 1) return { 0.0, std::log(a + std::sqrt(a * a - 1)) }; // == acosh(a) @@ -125,11 +125,12 @@ tc_acos(std::complex x) // the general case: // the result c + d*i satisfies a = cos(c)*cosh(d), b = -sin(c)*sinh(d) // hence $\frac{a^2}{\cos^2(c)} - \frac{b^2}{\sin^2(c)} = 1$. - double q = (a * a - 1) * (a * a - 1) + b * b * (b * b + 2 * a * a + 2); - double t = 0.5 * (1 + a * a + b * b - std::sqrt(q)); + const double q = (a * a - 1) * (a * a - 1) + b * b * (b * b + 2 * a * a + 2); + const double t = 0.5 * (1 + a * a + b * b - std::sqrt(q)); // this $t = \cos^2(c)$ solves the latter biquadratic equation and lies in [0,1]. - double aa = a / std::sqrt(t), bb = b / std::sqrt(1 - t); - double r_real = std::acos(std::sqrt(t)); - double r_imag = std::log(std::fabs(aa - bb)); + const double aa = a / std::sqrt(t); + const double bb = b / std::sqrt(1 - t); + const double r_real = std::acos(std::sqrt(t)); + const double r_imag = std::log(std::fabs(aa - bb)); return { r_real, r_imag }; } diff --git a/core/vnl/tests/test_container_interface.cxx b/core/vnl/tests/test_container_interface.cxx index 61f4e4ffd16..0b7cc307575 100644 --- a/core/vnl/tests/test_container_interface.cxx +++ b/core/vnl/tests/test_container_interface.cxx @@ -49,7 +49,7 @@ test_common_interface() m(0, 0); m.fill(0); m.fill_diagonal(0); - vnl_vector v(2, 1); + const vnl_vector v(2, 1); m.set_diagonal(v); int data[4] = { 0, 1, 2, 3 }; m.set(data); @@ -93,7 +93,7 @@ test_common_interface() { typename TContainer::element_type data[4] = { 1, 2, 3, 4 }; unsigned int indices[2] = { 1, 0 }; - vnl_vector i(indices, 2); + const vnl_vector i(indices, 2); TContainer matrix(2, 2); matrix.copy_in(data); #if !defined(_MSC_VER) // This code is failing on VS15 in Release mode for vnl_matrix_fixed diff --git a/core/vnl/tests/test_crs_index.cxx b/core/vnl/tests/test_crs_index.cxx index f3c03dfce2b..44c2ccc9281 100644 --- a/core/vnl/tests/test_crs_index.cxx +++ b/core/vnl/tests/test_crs_index.cxx @@ -20,7 +20,7 @@ display_mask(const std::vector> & mask) static void test_crs_index() { - std::vector null_col(8, false); + const std::vector null_col(8, false); std::vector> mask(10, null_col); mask[0][1] = true; @@ -43,7 +43,7 @@ test_crs_index() display_mask(mask); - vnl_crs_index crs(mask); + const vnl_crs_index crs(mask); TEST("num rows", crs.num_rows(), (int)mask.size()); TEST("num cols", crs.num_cols(), (int)mask[0].size()); @@ -56,7 +56,7 @@ test_crs_index() { for (int j = 0; j < crs.num_cols(); ++j) { - int idx = crs(i, j); + const int idx = crs(i, j); if (((idx < 0) == mask[i][j]) && idx != curr++) valid = false; std::cout << crs(i, j) << ' '; diff --git a/core/vnl/tests/test_decnum.cxx b/core/vnl/tests/test_decnum.cxx index efee45b812d..d3536103c92 100644 --- a/core/vnl/tests/test_decnum.cxx +++ b/core/vnl/tests/test_decnum.cxx @@ -39,170 +39,170 @@ run_constructor_tests() std::cout << "long constructor:\n"; { - vnl_decnum b(0L); + const vnl_decnum b(0L); TEST("vnl_decnum b(0L);", b, 0L); } { - vnl_decnum b(1L); + const vnl_decnum b(1L); TEST("vnl_decnum b(1L);", b, 1L); } { - vnl_decnum b(-1L); + const vnl_decnum b(-1L); TEST("vnl_decnum b(-1L);", b, -1L); } { - vnl_decnum b(0x7fffL); + const vnl_decnum b(0x7fffL); TEST("vnl_decnum b(0x7fffL);", b, 0x7fffL); } { - vnl_decnum b(-0x7fffL); + const vnl_decnum b(-0x7fffL); TEST("vnl_decnum b(-0x7fffL);", b, -0x7fffL); } { - vnl_decnum b(0x7fffffffL); + const vnl_decnum b(0x7fffffffL); TEST("vnl_decnum b(0x7fffffffL);", b, 0x7fffffffL); } { - vnl_decnum b(-0x7fffffffL); + const vnl_decnum b(-0x7fffffffL); TEST("vnl_decnum b(-0x7fffffffL);", b, -0x7fffffffL); } { - vnl_decnum b(0xf00000L); + const vnl_decnum b(0xf00000L); TEST("vnl_decnum b(0xf00000L);", b, 0xf00000); } std::cout << "double constructor:\n"; { - vnl_decnum b(0.0); + const vnl_decnum b(0.0); TEST("vnl_decnum b(0.0);", b, 0L); } { - vnl_decnum b(1.0); + const vnl_decnum b(1.0); TEST("vnl_decnum b(1.0);", b, 1L); } { - vnl_decnum b(-1.0); + const vnl_decnum b(-1.0); TEST("vnl_decnum b(-1.0);", b, -1L); } { - vnl_decnum b(1234.0); + const vnl_decnum b(1234.0); TEST("vnl_decnum(1234.0)", b, 1234L); } { - vnl_decnum b(-1234.); + const vnl_decnum b(-1234.); TEST("vnl_decnum(-1234.)", b, -1234L); } { - vnl_decnum b(1234e3); + const vnl_decnum b(1234e3); TEST("vnl_decnum(1234e3)", b, 1234000L); } { - vnl_decnum b(-1234e3); + const vnl_decnum b(-1234e3); TEST("vnl_decnum(-1234e3)", b, -1234000L); } { - vnl_decnum b(1234e-3); + const vnl_decnum b(1234e-3); TEST("vnl_decnum(1234e-3)", long(b * "1000"), 1234L); } { - vnl_decnum b(1.234); + const vnl_decnum b(1.234); TEST("vnl_decnum(1.234)", long(b * "1000"), 1234L); } std::cout << "char* constructor:\n"; { - vnl_decnum b("-1"); + const vnl_decnum b("-1"); TEST("vnl_decnum b(\"-1\");", b, -1L); } { - vnl_decnum b("+1"); + const vnl_decnum b("+1"); TEST("vnl_decnum b(\"+1\");", b, 1L); } { - vnl_decnum b("1"); + const vnl_decnum b("1"); TEST("vnl_decnum b(\"1\");", b, 1L); } { - vnl_decnum b("123"); + const vnl_decnum b("123"); TEST("vnl_decnum b(\"123\");", b, 123L); } { - vnl_decnum b("123e5"); + const vnl_decnum b("123e5"); TEST("vnl_decnum b(\"123e5\");", b, 12300000L); } { - vnl_decnum b("-123e+4"); + const vnl_decnum b("-123e+4"); TEST("vnl_decnum b(\"-123e+4\");", b, -1230000L); } { - vnl_decnum b("-1e120"); + const vnl_decnum b("-1e120"); std::stringstream s; s << b << ' '; // verify that b outputs as "-1e120" - bool t = s.str()[0] == '-' && s.str()[1] == '1' && s.str()[2] == 'e' && s.str()[3] == '1' && s.str()[4] == '2' && - s.str()[5] == '0' && s.str()[6] == ' '; + const bool t = s.str()[0] == '-' && s.str()[1] == '1' && s.str()[2] == 'e' && s.str()[3] == '1' && + s.str()[4] == '2' && s.str()[5] == '0' && s.str()[6] == ' '; TEST("vnl_decnum b(\"-1e120\") outputs as \"-1e120\"", t, true); } { - vnl_decnum b("0"); + const vnl_decnum b("0"); TEST("vnl_decnum b(\"0\");", b, 0L); } { - vnl_decnum b("00"); + const vnl_decnum b("00"); TEST("vnl_decnum b(\"00\");", b, 0L); } { - vnl_decnum b("012334567"); + const vnl_decnum b("012334567"); TEST("vnl_decnum b(\"012334567\");", b, 12334567L); } { - vnl_decnum b("9"); + const vnl_decnum b("9"); TEST("vnl_decnum b(\"9\");", b, 9L); } { - vnl_decnum b(" 9"); + const vnl_decnum b(" 9"); TEST("vnl_decnum b(\" 9\");", b, 9L); } // infinity and NaN: { - vnl_decnum b("-123"); + const vnl_decnum b("-123"); TEST("isfinite(-123)", vnl_math::isfinite(b), true); } { - vnl_decnum b("0"); + const vnl_decnum b("0"); TEST("isfinite(0)", vnl_math::isfinite(b), true); } { - vnl_decnum b("1e999"); + const vnl_decnum b("1e999"); TEST("isfinite(1e999)", vnl_math::isfinite(b), true); } { - vnl_decnum b("NaN"); + const vnl_decnum b("NaN"); TEST("isfinite(NaN)", vnl_math::isfinite(b), false); } { - vnl_decnum b("NaN"); + const vnl_decnum b("NaN"); TEST("isnan(NaN)", vnl_math::isnan(b), true); } { - vnl_decnum b("1e999"); + const vnl_decnum b("1e999"); TEST("isnan(1e999)", vnl_math::isnan(b), false); } { - vnl_decnum b("+Inf"); + const vnl_decnum b("+Inf"); TEST("vnl_decnum(\"+Inf\")", vnl_math::isfinite(b), false); } { - vnl_decnum b("Infinity"); + const vnl_decnum b("Infinity"); TEST("vnl_decnum(\"Infinity\")", vnl_math::isfinite(b), false); } { - vnl_decnum b("-Infin"); + const vnl_decnum b("-Infin"); TEST("vnl_decnum(\"-Infin\")", vnl_math::isfinite(b), false); } { - vnl_decnum b("Inf"); + const vnl_decnum b("Inf"); TEST("isnan(Inf)", vnl_math::isnan(b), false); } @@ -252,12 +252,12 @@ run_constructor_tests() std::cout << "vnl_decnum& constructor:\n"; { - vnl_decnum b50(vnl_decnum(0L)); + const vnl_decnum b50(vnl_decnum(0L)); TEST("vnl_decnum b50(vnl_decnum(0L));", b50, 0L); } { - vnl_decnum b51(vnl_decnum(100L)); + const vnl_decnum b51(vnl_decnum(100L)); TEST("vnl_decnum b51(vnl_decnum(100L));", b51, 100L); } } @@ -296,7 +296,7 @@ run_assignment_tests() // vnl_decnum& assignment operator b1 = "0"; - vnl_decnum b5(0x1ffffL); + const vnl_decnum b5(0x1ffffL); TEST_RUN("b1 = b5", b1 = b5, b1, b5); } @@ -304,12 +304,12 @@ static void run_logical_comparison_tests() { std::cout << "\nStarting logical comparison tests:\n"; - vnl_decnum b0(0L); - vnl_decnum b1(1L); - vnl_decnum b2(0x7fffL); - vnl_decnum b3(-0x7fffL); - vnl_decnum p_inf("+Inf"); - vnl_decnum m_inf("-Inf"); + const vnl_decnum b0(0L); + const vnl_decnum b1(1L); + const vnl_decnum b2(0x7fffL); + const vnl_decnum b3(-0x7fffL); + const vnl_decnum p_inf("+Inf"); + const vnl_decnum m_inf("-Inf"); TEST("b0 == b0", b0 == b0, true); TEST("b0 == b1", b0 == b1, false); @@ -418,12 +418,12 @@ run_division_tests() { for (long k = -6; k < 9; k += 3) { - vnl_decnum bi(i + k); + const vnl_decnum bi(i + k); for (long j = 0xffff; j != 0; j /= -16) { for (long l = -4; l < 9; l += 3) { // avoid division by zero... - vnl_decnum bj(j + l); + const vnl_decnum bj(j + l); vnl_decnum bij(long((i + k) / (j + l))); { std::stringstream s; @@ -447,7 +447,8 @@ run_large_division_tests() { std::cout << "\nStarting large division tests:\n"; - vnl_decnum a("10000000"), b("10000001"); + vnl_decnum a("10000000"); + vnl_decnum b("10000001"); b *= a; vnl_decnum c = b / 10000001; std::cout << b << " / 10000001 = " << c << ", must be 10000000\n"; @@ -513,8 +514,8 @@ run_multiplication_division_tests() { std::cout << "\nCheck example in book:\n"; - vnl_decnum b2 = "4294967295"; // == 0xffffffff // Create vnl_decnum object - vnl_decnum b3 = "12345e30"; // Create vnl_decnum object + const vnl_decnum b2 = "4294967295"; // == 0xffffffff // Create vnl_decnum object + const vnl_decnum b3 = "12345e30"; // Create vnl_decnum object std::cout << "b2 = " << b2 << '\n' << "b3 = " << b3 << std::endl; @@ -531,8 +532,11 @@ run_addition_subtraction_tests() { std::cout << "\nStarting addition, subtraction tests:\n"; - long i, j; - vnl_decnum bi, bj, bij; + long i; + long j; + vnl_decnum bi; + vnl_decnum bj; + vnl_decnum bij; { for (i = 1; i < 0xffff; i *= -3) @@ -557,10 +561,12 @@ run_addition_subtraction_tests() } } - vnl_decnum b0(0L); - vnl_decnum zillion("1000000000000000000000000000000000000"); - vnl_decnum b1000000(1000000L), b1000000000000("1000000000000"); - vnl_decnum p_inf("+Inf"), m_inf("-Inf"); + const vnl_decnum b0(0L); + const vnl_decnum zillion("1000000000000000000000000000000000000"); + const vnl_decnum b1000000(1000000L); + const vnl_decnum b1000000000000("1000000000000"); + const vnl_decnum p_inf("+Inf"); + const vnl_decnum m_inf("-Inf"); TEST("-p_inf == m_inf", -p_inf, m_inf); TEST("-m_inf == p_inf", -m_inf, p_inf); @@ -616,8 +622,8 @@ run_addition_subtraction_tests() TEST("m_inf - zillion == m_inf", m_inf - zillion, m_inf); // example in book - vnl_decnum b2 = "4294967295"; // == 0xffffffff // Create vnl_decnum object - vnl_decnum b3 = "12345e30"; // Create vnl_decnum object + const vnl_decnum b2 = "4294967295"; // == 0xffffffff // Create vnl_decnum object + const vnl_decnum b3 = "12345e30"; // Create vnl_decnum object TEST("(b2+b3) - b2 = b3", (b2 + b3) - b2 == b3, 1); TEST("(b2+b3) - b3 = b2", (b2 + b3) - b3 == b2, 1); std::cout << b3 << '\n'; @@ -686,8 +692,12 @@ run_multiplication_tests() { std::cout << "\nStarting multiplication tests:\n"; - vnl_decnum b0(0L), b1000(1000L), b1000000(1000000L), zillion("1000000000000000000"); - vnl_decnum p_inf("+Inf"), m_inf("-Inf"); + const vnl_decnum b0(0L); + const vnl_decnum b1000(1000L); + const vnl_decnum b1000000(1000000L); + const vnl_decnum zillion("1000000000000000000"); + const vnl_decnum p_inf("+Inf"); + const vnl_decnum m_inf("-Inf"); TEST("b0*b0 == b0", b0 * b0, b0); TEST("b0*b1000 == b0", b0 * b1000, b0); @@ -707,8 +717,9 @@ run_multiplication_tests() static void run_left_shift_tests() { - vnl_decnum b1(1L); - vnl_decnum p_inf("+Inf"), m_inf("-Inf"); + const vnl_decnum b1(1L); + const vnl_decnum p_inf("+Inf"); + const vnl_decnum m_inf("-Inf"); // left shift TEST("int(b1) == 1", int(b1), 1); @@ -737,8 +748,9 @@ run_left_shift_tests() static void run_right_shift_tests() { - vnl_decnum b2("1e78"); - vnl_decnum p_inf("+Inf"), m_inf("-Inf"); + const vnl_decnum b2("1e78"); + const vnl_decnum p_inf("+Inf"); + const vnl_decnum m_inf("-Inf"); // right shift TEST("b2 == vnl_decnum(\"1e78\")", b2, vnl_decnum("1e78")); @@ -772,7 +784,8 @@ run_normalisation_tests() { std::cout << "\nStarting normalisation tests:\n"; - vnl_decnum a("-1e10"), b = a; + vnl_decnum a("-1e10"); + vnl_decnum b = a; TEST("a stored as -1e10", a.data(), "1"); TEST("b stored as -1e10", b.data(), "1"); a += 1L; diff --git a/core/vnl/tests/test_diag_matrix.cxx b/core/vnl/tests/test_diag_matrix.cxx index b2890af6611..24cd4f26536 100644 --- a/core/vnl/tests/test_diag_matrix.cxx +++ b/core/vnl/tests/test_diag_matrix.cxx @@ -18,7 +18,7 @@ test_diag_matrix() for (unsigned i = 0; i < N; i++) m1(i, i) = i * 0.25 - 0.25; - vnl_diag_matrix const m1c = m1; // must be const in order to use m(i,j) + const vnl_diag_matrix m1c = m1; // must be const in order to use m(i,j) std::cout << "m1 = " << m1 << " =\n"; for (unsigned i = 0; i < N; i++) { @@ -32,7 +32,7 @@ test_diag_matrix() for (unsigned i = 0; i < N; i++) m2(i, i) = 2.0 - 1.25 * i; - vnl_diag_matrix const m2c = m2; + const vnl_diag_matrix m2c = m2; std::cout << "m2 = " << m2 << " =\n"; for (unsigned i = 0; i < N; i++) { @@ -42,15 +42,15 @@ test_diag_matrix() std::cout << '\n'; } - vnl_diag_matrix const sum = m1 + m2; + const vnl_diag_matrix sum = m1 + m2; std::cout << "sum = " << sum << '\n'; TEST("sum", sum(0, 0) == 1.75 && sum(1, 1) == 0.75 && sum(2, 2) == -0.25, true); - vnl_diag_matrix const diff = m1 - m2; + const vnl_diag_matrix diff = m1 - m2; std::cout << "difference = " << diff << " =\n"; TEST("difference", diff(0, 0) == -2.25 && diff(1, 1) == -0.75 && diff(2, 2) == 0.75, true); - vnl_diag_matrix const prod = m1 * m2; + const vnl_diag_matrix prod = m1 * m2; std::cout << "product = " << prod << '\n'; TEST("product", prod(0, 0) == -0.5 && prod(1, 1) == 0.0 && prod(2, 2) == -0.125, true); diff --git a/core/vnl/tests/test_diag_matrix_fixed.cxx b/core/vnl/tests/test_diag_matrix_fixed.cxx index 27af460602b..3ef92e631d3 100644 --- a/core/vnl/tests/test_diag_matrix_fixed.cxx +++ b/core/vnl/tests/test_diag_matrix_fixed.cxx @@ -17,7 +17,7 @@ test_diag_matrix_fixed() for (unsigned i = 0; i < N; i++) m1(i, i) = i * 0.25 - 0.25; - vnl_diag_matrix_fixed const m1c = m1; // must be const in order to use m(i,j) + const vnl_diag_matrix_fixed m1c = m1; // must be const in order to use m(i,j) std::cout << "m1 = " << m1 << " =\n"; for (unsigned i = 0; i < N; i++) { @@ -31,7 +31,7 @@ test_diag_matrix_fixed() for (unsigned i = 0; i < N; i++) m2(i, i) = 2.0 - 1.25 * i; - vnl_diag_matrix_fixed const m2c = m2; + const vnl_diag_matrix_fixed m2c = m2; std::cout << "m2 = " << m2 << " =\n"; for (unsigned i = 0; i < N; i++) { @@ -41,15 +41,15 @@ test_diag_matrix_fixed() std::cout << '\n'; } - vnl_diag_matrix_fixed const sum = m1 + m2; + const vnl_diag_matrix_fixed sum = m1 + m2; std::cout << "sum = " << sum << '\n'; TEST("sum", sum(0, 0) == 1.75 && sum(1, 1) == 0.75 && sum(2, 2) == -0.25, true); - vnl_diag_matrix_fixed const diff = m1 - m2; + const vnl_diag_matrix_fixed diff = m1 - m2; std::cout << "difference = " << diff << " =\n"; TEST("difference", diff(0, 0) == -2.25 && diff(1, 1) == -0.75 && diff(2, 2) == 0.75, true); - vnl_diag_matrix_fixed const prod = m1 * m2; + const vnl_diag_matrix_fixed prod = m1 * m2; std::cout << "product = " << prod << '\n'; TEST("product", prod(0, 0) == -0.5 && prod(1, 1) == 0.0 && prod(2, 2) == -0.125, true); diff --git a/core/vnl/tests/test_fastops.cxx b/core/vnl/tests/test_fastops.cxx index bc2c6898c89..e4dc51e8284 100644 --- a/core/vnl/tests/test_fastops.cxx +++ b/core/vnl/tests/test_fastops.cxx @@ -10,8 +10,10 @@ void test_fastops() { // The data to work with - vnl_matrix result_m, X; - vnl_vector result_v, Y; + vnl_matrix result_m; + vnl_matrix X; + vnl_vector result_v; + vnl_vector Y; vnl_matrix id1x1(1, 1); id1x1.set_identity(); vnl_matrix id2x2(2, 2); @@ -23,16 +25,17 @@ test_fastops() vnl_matrix id99x99(99, 99); id99x99.set_identity(); double data[10] = { -7.5, 1.5, 0., -107.25, 511., -509.75, 1.25, -1., 0., 1. }; - vnl_matrix m1x1(data, 1, 1); // the number -7.5 - vnl_matrix m2x2(data, 2, 2); - vnl_matrix m2x2t = m2x2.transpose(); - vnl_matrix m3x3(data, 3, 3); - vnl_matrix m3x3t = m3x3.transpose(); - vnl_vector v1(data, 1); // the number -7.5 - vnl_vector v2(data, 2); - vnl_vector v3(data, 3); - vnl_vector v10(data, 10); - vnl_matrix m10x2(10, 2), m2x10(2, 10); + const vnl_matrix m1x1(data, 1, 1); // the number -7.5 + const vnl_matrix m2x2(data, 2, 2); + const vnl_matrix m2x2t = m2x2.transpose(); + const vnl_matrix m3x3(data, 3, 3); + const vnl_matrix m3x3t = m3x3.transpose(); + const vnl_vector v1(data, 1); // the number -7.5 + const vnl_vector v2(data, 2); + const vnl_vector v3(data, 3); + const vnl_vector v10(data, 10); + vnl_matrix m10x2(10, 2); + vnl_matrix m2x10(2, 10); for (unsigned int i = 0; i < 10; ++i) for (unsigned int j = 0; j < 2; ++j) m10x2[i][j] = m2x10[j][i] = (i + 1) * 1.5 + (j + 1) * (j + i); diff --git a/core/vnl/tests/test_finite.cxx b/core/vnl/tests/test_finite.cxx index 4949b2152d4..68018339805 100644 --- a/core/vnl/tests/test_finite.cxx +++ b/core/vnl/tests/test_finite.cxx @@ -7,7 +7,8 @@ #include "vnl/vnl_finite.h" template -void test_finite_int(vnl_finite_int) +void +test_finite_int(vnl_finite_int) { std::cout << "\n --- Testing vnl_finite_int<" << N << "> ---\n"; @@ -20,7 +21,7 @@ void test_finite_int(vnl_finite_int) } if (N <= 1000) { // calculating multiplicative order is time consuming - unsigned int m = vnl_finite_int(2).multiplicative_order(); + const unsigned int m = vnl_finite_int(2).multiplicative_order(); std::cout << "Order of 2 in Z_" << N << " is "; if (m == (unsigned int)(-1)) std::cout << "invalid\n"; @@ -31,27 +32,27 @@ void test_finite_int(vnl_finite_int) std::cout << "\nStarting constructor tests:\n"; { - vnl_finite_int b(0); + const vnl_finite_int b(0); TEST("vnl_finite_int b(0);", b, 0); } { - vnl_finite_int b(1); + const vnl_finite_int b(1); TEST("vnl_finite_int b(1);", b, 1); } { - vnl_finite_int b(-1); + const vnl_finite_int b(-1); TEST("vnl_finite_int b(-1);", b, -1); } { - vnl_finite_int b(-1); + const vnl_finite_int b(-1); TEST("b == N-1;", b, N - 1); } { - vnl_finite_int b(111); + const vnl_finite_int b(111); TEST("vnl_finite_int b(111);", b, 111); } { - vnl_finite_int b(-99); + const vnl_finite_int b(-99); TEST("vnl_finite_int b(-99);", b, -99); } @@ -64,7 +65,7 @@ void test_finite_int(vnl_finite_int) b1 = -77; TEST("vnl_finite_int b1; b1 = -77;", b1, 11 * N - 77); - vnl_finite_int b5 = 4321; + const vnl_finite_int b5 = 4321; b1 = b5; TEST("b1 = b5", b1, b5); @@ -75,7 +76,7 @@ void test_finite_int(vnl_finite_int) TEST("unary plus", +b5, b5); std::cout << "\nStarting logical comparison tests:\n"; - vnl_finite_int b0 = 0; + const vnl_finite_int b0 = 0; std::cout << "b0=" << b0 << '\n'; b1 = 1; std::cout << "b1=" << b1 << '\n'; @@ -105,7 +106,9 @@ void test_finite_int(vnl_finite_int) std::cout << "\nStarting addition, subtraction tests:\n"; - vnl_finite_int bi, bj, bij; + vnl_finite_int bi; + vnl_finite_int bj; + vnl_finite_int bij; std::cout << " for (i = 1; i < 1000; i *= 3)\n" << " for (j = 1; j < 1000; j *= 3)\n "; @@ -131,7 +134,7 @@ void test_finite_int(vnl_finite_int) } std::cout << std::endl; - vnl_finite_int b1000(1000); + const vnl_finite_int b1000(1000); TEST("-b0 == b0", -b0, b0); TEST("-b1000 == (-1)*b1000", -b1000, (-1) * b1000); @@ -161,7 +164,7 @@ void test_finite_int(vnl_finite_int) TEST("b0*b0 == b0", b0 * b0, b0); TEST("b0*b1000 == b0", b0 * b1000, b0); TEST("b1000*b0 == b0", b1000 * b0, b0); - vnl_finite_int b1000000(1000000); + const vnl_finite_int b1000000(1000000); TEST("b1000*b1000 == b1000000", b1000 * b1000, b1000000); TEST("b1000*b1000000 == b1000000*b1000", b1000 * b1000000, b1000000 * b1000); @@ -225,7 +228,7 @@ test_finite_poly(vnl_finite_int_poly, const std::string & s) std::cout << "\nStarting constructor tests:\n"; - vnl_finite_int_poly b0; + const vnl_finite_int_poly b0; std::cout << b0 << '\n'; TEST("vnl_finite_int_poly b0;", b0, 0); std::vector> p(1); @@ -235,7 +238,7 @@ test_finite_poly(vnl_finite_int_poly, const std::string & s) TEST("vnl_finite_int_poly b(p);", b, 1); std::cout << "\nStarting assignment tests:\n"; - vnl_finite_int b1 = 2; + const vnl_finite_int b1 = 2; b = b1; TEST("vnl_finite_int b1; b = b1;", b, 2); @@ -251,15 +254,17 @@ test_finite_poly(vnl_finite_int_poly, const std::string & s) { for (int j = 1000; j > 0; j /= 3) { - std::vector> v1(M), v2(M), v3(M); + std::vector> v1(M); + std::vector> v2(M); + std::vector> v3(M); for (int m = 0; m < M; ++m) { v1[m] = i + m; v2[m] = j + m, v3[m] = i + j + 2 * m; } - vnl_finite_int_poly p1(v1); - vnl_finite_int_poly p2(v2); - vnl_finite_int_poly p3(v3); + const vnl_finite_int_poly p1(v1); + const vnl_finite_int_poly p2(v2); + const vnl_finite_int_poly p3(v3); #ifdef DEBUG std::cout << p3 << "\n "; #endif @@ -287,13 +292,13 @@ test_finite_poly(vnl_finite_int_poly, const std::string & s) testlib_test_perform(true); mod_p.pop_back(); - vnl_finite_int_poly irred = mod_p; + const vnl_finite_int_poly irred = mod_p; std::cout << "X^" << M << " = " << irred << '\n'; std::vector> v(M); for (int m = 0; m < M; ++m) v[m] = m + 1 + m * m; - vnl_finite_int_poly f(v); + const vnl_finite_int_poly f(v); std::cout << "f(X) = " << f << '\n'; for (int m = 0; m < M; ++m) v[m] = m + 1 - m * m; @@ -329,11 +334,11 @@ test_finite() test_finite_int(vnl_finite_int<2>(0)); test_finite_int(vnl_finite_int<3>(0)); test_finite_int(vnl_finite_int<4>(0)); // not a field - vnl_finite_int<4> b4 = 2; + const vnl_finite_int<4> b4 = 2; TEST("2*2=0 mod 4", b4 * b4, 0); // zero divisor test_finite_int(vnl_finite_int<5>(0)); // Fermat prime test_finite_int(vnl_finite_int<6>(0)); - vnl_finite_int<6> b6 = 2; + const vnl_finite_int<6> b6 = 2; TEST("2*3=0 mod 6", b6 * 3, 0); // zero divisor test_finite_int(vnl_finite_int<7>(0)); // Mersenne prime test_finite_int(vnl_finite_int<8>(0)); @@ -342,12 +347,12 @@ test_finite() test_finite_int(vnl_finite_int<17>(0)); // Fermat prime test_finite_int(vnl_finite_int<31>(0)); // Mersenne prime test_finite_int(vnl_finite_int<100>(0)); // non-prime square - vnl_finite_int<100> b100 = 20; + const vnl_finite_int<100> b100 = 20; TEST("25*20=0 mod 100", 25 * b100, 0); // zero divisor test_finite_int(vnl_finite_int<243>(0)); // high prime power test_finite_int(vnl_finite_int<256>(0)); // high power of 2 test_finite_int(vnl_finite_int<432>(0)); // high combined power of 2 and 3 - vnl_finite_int<432> b432 = 180; + const vnl_finite_int<432> b432 = 180; TEST("180*12=0 mod 432", b432 * 12, 0); // zero divisor test_finite_int(vnl_finite_int<257>(0)); // Fermat prime test_finite_int(vnl_finite_int<0x10001>(0)); // Fermat prime diff --git a/core/vnl/tests/test_hungarian_algorithm.cxx b/core/vnl/tests/test_hungarian_algorithm.cxx index 6ebed4adfbf..c2461c4e146 100644 --- a/core/vnl/tests/test_hungarian_algorithm.cxx +++ b/core/vnl/tests/test_hungarian_algorithm.cxx @@ -11,10 +11,10 @@ test_hungarian_algorithm_1() { // Create input image constexpr int cost_val[6][6] = { { 4, 12, 11, 20, 16, 19 }, { 12, 8, 20, 13, 22, 18 }, { 6, 9, 4, 15, 9, 12 }, - { 12, 4, 12, 6, 14, 8 }, { 12, 10, 6, 9, 5, 3 }, { 13, 7, 12, 2, 10, 4 } }; + { 12, 4, 12, 6, 14, 8 }, { 12, 10, 6, 9, 5, 3 }, { 13, 7, 12, 2, 10, 4 } }; // Create the cost matrix - vnl_matrix cost(&cost_val[0][0], 6, 6); + const vnl_matrix cost(&cost_val[0][0], 6, 6); vnl_hungarian_algorithm HungarianClassTest; HungarianClassTest.SetCostMatrix(cost); @@ -34,7 +34,7 @@ test_hungarian_algorithm_1() std::vector assignment = HungarianClassTest.GetAssignmentVector(); std::cout << "assignment vector:\n" << '('; - for (unsigned int i : assignment) + for (const unsigned int i : assignment) std::cout << ' ' << i; std::cout << " )\n"; @@ -47,10 +47,10 @@ test_hungarian_algorithm_1() TEST_NEAR("total cost", HungarianClassTest.GetTotalCost(), 31, 1e-11); constexpr double cost_val2[6][6] = { { 2, 3.0, 1, 0.1, 2, 7 }, { 1, 0, 1, 2, 3.0, 4 }, { 0, 0, 9, 5, 4.4, 2 }, - { 1, 5, 6, 3, 0, 1 }, { 0, 1, 2, 0, 1, 2 }, { 2, 3, 1, 0.1, 1, 1 } }; + { 1, 5, 6, 3, 0, 1 }, { 0, 1, 2, 0, 1, 2 }, { 2, 3, 1, 0.1, 1, 1 } }; // Create the cost matrix - vnl_matrix cost2(&cost_val2[0][0], 6, 6); + const vnl_matrix cost2(&cost_val2[0][0], 6, 6); vnl_hungarian_algorithm HungarianClassTest2; HungarianClassTest2.SetCostMatrix(cost2); @@ -74,7 +74,7 @@ test_hungarian_algorithm_1() std::vector assignment2 = HungarianClassTest2.GetAssignmentVector(); std::cout << "assignment vector:" << std::endl << '('; - for (unsigned int i : assignment2) + for (const unsigned int i : assignment2) std::cout << ' ' << i; std::cout << " )\n"; @@ -90,7 +90,7 @@ test_hungarian_algorithm_1() static vnl_random randgen; static void -check_solution(std::vector const & assign, unsigned const * solution, unsigned const N) +check_solution(const std::vector & assign, const unsigned * solution, const unsigned N) { TEST(" assignment vector size", assign.size(), N); bool okay = true; @@ -112,7 +112,7 @@ check_solution(std::vector const & assign, unsigned const * solution, static std::vector -make_up_solution(unsigned const M, unsigned const N) +make_up_solution(const unsigned M, const unsigned N) { // True solution std::vector true_assn(M); @@ -138,11 +138,11 @@ make_up_solution(unsigned const M, unsigned const N) } static void -test_skewed_problem(unsigned const M, unsigned const N) +test_skewed_problem(const unsigned M, const unsigned N) { std::cout << "Creating " << M << 'x' << N << " matrix" << std::endl; vnl_matrix cost(M, N); - double low = std::min(M, N) + 5.0; + const double low = std::min(M, N) + 5.0; for (unsigned i = 0; i < M; ++i) { for (unsigned j = 0; j < N; ++j) @@ -173,25 +173,25 @@ test_skewed_problem(unsigned const M, unsigned const N) std::cout << "Costs computed for " << M << 'x' << N << " matrix" << std::endl; - std::vector assn = vnl_hungarian_algorithm(cost); + const std::vector assn = vnl_hungarian_algorithm(cost); check_solution(assn, &true_assn[0], M); } static void -run_test(vnl_matrix const & cost, unsigned solution[]) +run_test(const vnl_matrix & cost, unsigned solution[]) { { std::cout << "Test " << cost.rows() << 'x' << cost.cols() << " matrix" << std::endl; - std::vector assign = vnl_hungarian_algorithm(cost); + const std::vector assign = vnl_hungarian_algorithm(cost); check_solution(assign, solution, cost.rows()); } { std::cout << "Test transposed problem" << std::endl; - vnl_matrix costT = cost.transpose(); - std::vector assign = vnl_hungarian_algorithm(costT); + const vnl_matrix costT = cost.transpose(); + const std::vector assign = vnl_hungarian_algorithm(costT); std::vector solutionT(costT.rows(), unsigned(-1)); for (unsigned i = 0; i < cost.rows(); ++i) @@ -214,7 +214,7 @@ test_hungarian_algorithm_2() constexpr double cost_val[3][3] = { { 1, 2, 3 }, { 2, 4, 6 }, { 3, 6, 9 } }; // Create the cost matrix - vnl_matrix cost(&cost_val[0][0], 3, 3); + const vnl_matrix cost(&cost_val[0][0], 3, 3); std::cout << "//-----------------------//\n" << "// Matrix 3 //\n" @@ -224,7 +224,7 @@ test_hungarian_algorithm_2() std::vector assign = vnl_hungarian_algorithm(cost); std::cout << "assignment vector:\n" << '('; - for (unsigned int i : assign) + for (const unsigned int i : assign) std::cout << ' ' << i; std::cout << " )" << std::endl; TEST("Test 3x3 cost matrix", assign.size() == 3 && assign[0] == 2 && assign[1] == 1 && assign[2] == 0, true); @@ -234,7 +234,7 @@ test_hungarian_algorithm_2() constexpr double cost_val[4][4] = { { 2.0, 1.0, 5.0, 3.0 }, { 0.5, 6.0, 3.0, 0.5 }, { 5.0, 2.0, 1.0, 6.0 }, { 7.0, 1.0, 3.0, 0.1 } }; - vnl_matrix cost(&cost_val[0][0], 4, 4); + const vnl_matrix cost(&cost_val[0][0], 4, 4); std::cout << "//-----------------------//\n" << "// Matrix 4 //\n" @@ -250,7 +250,7 @@ test_hungarian_algorithm_2() { constexpr double cost_val[3][4] = { { 2.0, 1.0, 5.0, 3.0 }, { 0.5, 6.0, 3.0, 0.5 }, { 7.0, 1.0, 3.0, 0.1 } }; - vnl_matrix cost(&cost_val[0][0], 3, 4); + const vnl_matrix cost(&cost_val[0][0], 3, 4); std::cout << "//-----------------------//\n" << "// Matrix 5 //\n" @@ -266,7 +266,7 @@ test_hungarian_algorithm_2() // test where the greedy solution is not the optimal std::cout << "\n\nTest when greedy != optimal\n"; constexpr double cost_val[3][4] = { { 2.0, 1.0, 5.0, 3.0 }, { 0.5, 0.2, 3.0, 0.5 }, { 7.0, 1.0, 3.0, 0.1 } }; - vnl_matrix cost(&cost_val[0][0], 3, 4); + const vnl_matrix cost(&cost_val[0][0], 3, 4); std::cout << "//-----------------------//\n" << "// Matrix 6 //\n" @@ -283,7 +283,7 @@ test_hungarian_algorithm_2() // solution std::cout << "\n\nTest when row-by-row min != optimal\n"; constexpr double cost_val[3][4] = { { 2.0, 1.0, 5.0, 3.0 }, { 0.5, 6.0, 3.0, 0.5 }, { 0.1, 1.0, 3.0, 0.2 } }; - vnl_matrix cost(&cost_val[0][0], 3, 4); + const vnl_matrix cost(&cost_val[0][0], 3, 4); std::cout << "//-----------------------//\n" << "// Matrix 7 //\n" @@ -300,7 +300,7 @@ test_hungarian_algorithm_2() { 2.0, 0.5, 7.0 }, { 1.1, 6.0, 1.0 }, { 1.0, 2.0, 1.0 }, { 5.0, 3.0, 3.0 }, { 3.0, 0.5, 0.1 } }; - vnl_matrix cost(&cost_val[0][0], 5, 3); + const vnl_matrix cost(&cost_val[0][0], 5, 3); std::cout << "//-----------------------//\n" << "// Matrix 8 //\n" @@ -320,7 +320,7 @@ test_hungarian_algorithm_2() { 2.0, 0.5, 7.0 }, { 1.1, 6.0, 1.0 }, { 1.0, 2.0, 1.0 }, { Inf, 3.0, 3.0 }, { 3.0, 0.5, 0.1 } }; - vnl_matrix cost(&cost_val[0][0], 5, 3); + const vnl_matrix cost(&cost_val[0][0], 5, 3); std::cout << "//-----------------------//\n" << "// Matrix 9 //\n" @@ -338,7 +338,7 @@ test_hungarian_algorithm_2() { 2.0, 0.5, 7.0 }, { 1.1, 6.0, 1.0 }, { 1.0, 2.0, 1.0 }, { Inf, 3.0, 3.0 }, { 3.0, 0.5, 0.1 } }; - vnl_matrix cost(&cost_val[0][0], 5, 3); + const vnl_matrix cost(&cost_val[0][0], 5, 3); std::cout << "//-----------------------//\n" << "// Matrix 10 //\n" diff --git a/core/vnl/tests/test_inverse.cxx b/core/vnl/tests/test_inverse.cxx index a87b6abc54c..2ce76adc54e 100644 --- a/core/vnl/tests/test_inverse.cxx +++ b/core/vnl/tests/test_inverse.cxx @@ -9,15 +9,19 @@ static void test_inverse() { - double eps = 1e-11; + const double eps = 1e-11; vnl_random rng(9667566ul); - vnl_double_2x2 residue2, id2; + vnl_double_2x2 residue2; + vnl_double_2x2 id2; id2.set_identity(); - vnl_double_3x3 residue3, id3; + vnl_double_3x3 residue3; + vnl_double_3x3 id3; id3.set_identity(); - vnl_double_4x4 residue4, id4; + vnl_double_4x4 residue4; + vnl_double_4x4 id4; id4.set_identity(); - vnl_matrix M, Mi; + vnl_matrix M; + vnl_matrix Mi; // 2x2 inverse of a specific matrix vnl_double_2x2 id2i = vnl_inverse(id2); @@ -51,7 +55,7 @@ test_inverse() // 2x2 inverse of random matrix for (double & i : M2) i = rng.drand32(-1.0, 1.0); - vnl_double_2x2 m2r(M2); + const vnl_double_2x2 m2r(M2); m2i = vnl_inverse(m2r); residue2 = m2r * m2i - id2; TEST_NEAR("rand 2x2 vnl_inverse", residue2.array_inf_norm(), 0.0, eps); @@ -97,7 +101,7 @@ test_inverse() // 3x3 inverse of random matrix for (double & i : M3) i = rng.drand32(-1.0, 1.0); - vnl_double_3x3 m3r(M3); + const vnl_double_3x3 m3r(M3); m3i = vnl_inverse(m3r); residue3 = m3r * m3i - id3; TEST_NEAR("3x3 vnl_inverse", residue3.array_inf_norm(), 0.0, eps); @@ -145,7 +149,7 @@ test_inverse() // 4x4 inverse of random matrix for (double & i : M4) i = rng.drand32(-1.0, 1.0); - vnl_double_4x4 m4r(M4); + const vnl_double_4x4 m4r(M4); m4i = vnl_inverse(m4r); residue4 = m4r * m4i - id4; TEST_NEAR("4x4 vnl_inverse", residue4.array_inf_norm(), 0.0, eps); @@ -160,7 +164,7 @@ test_inverse() // 4x4 inverse of a specific sparse matrix double M4s[16] = { 0.9998, 0.0, 0.02, 0.059, 0.0, 1.0, 0.0, 0.0, -0.02, 0.0, 0.9998, 0.0, 0.0, 0.0, 0.0, 1.0 }; - vnl_double_4x4 m4s(M4s); + const vnl_double_4x4 m4s(M4s); m4i = vnl_inverse(m4s); residue4 = m4s * m4i - id4; TEST_NEAR("4x4 vnl_inverse", residue4.array_inf_norm(), 0.0, eps); diff --git a/core/vnl/tests/test_math.cxx b/core/vnl/tests/test_math.cxx index 2dee6c22ca4..c25fe3f5e32 100644 --- a/core/vnl/tests/test_math.cxx +++ b/core/vnl/tests/test_math.cxx @@ -23,7 +23,7 @@ print_hex(const T p) for (int i = (sizeof(p) - 1); i >= 0; --i) { str << std::setfill('0') << std::setw(2); - const auto curr_value = static_cast((reinterpret_cast(&p))[i]); + const auto curr_value = static_cast((reinterpret_cast(&p))[i]); str << curr_value; } str << std::dec; @@ -113,12 +113,12 @@ test_math() test_static_const_definition(); test_math_constants(); - int n = -11; - float f = -7.5f; - double d = -vnl_math::pi; - std::complex i(0, 1); - std::complex z(-1, 2); - std::complex e_ipi = std::exp(d * i); + const int n = -11; + const float f = -7.5f; + const double d = -vnl_math::pi; + const std::complex i(0, 1); + const std::complex z(-1, 2); + const std::complex e_ipi = std::exp(d * i); std::cout << "n = " << n << '\n' << "f = " << f << '\n' @@ -406,8 +406,8 @@ test_math() std::cout << "conv_eps = " << conv_eps << " = 2pi - " << vnl_math::twopi - conv_eps << std::endl; TEST( "vnl_math::angle_0_to_2pi(-10eps)", conv_eps < vnl_math::twopi - vnl_math_test_2_epsilon && conv_eps > 6.283, true); - double ang = vnl_math::twopi - eps; - double conv_ang = vnl_math::angle_0_to_2pi(ang); + const double ang = vnl_math::twopi - eps; + const double conv_ang = vnl_math::angle_0_to_2pi(ang); std::cout << "conv_ang = " << conv_ang << " = 2pi - " << vnl_math::twopi - conv_ang << std::endl; TEST("vnl_math::angle_0_to_2pi(2pi-10eps)", conv_ang, ang); // test vnl_math::angle_minuspi_to_pi() for "extreme values": @@ -436,16 +436,16 @@ test_math() std::cout << "+ +" << std::endl; - unsigned short x_short_u = 7; - unsigned short y_short_u = 2; + const unsigned short x_short_u = 7; + const unsigned short y_short_u = 2; signed short x_short_s = 7; signed short y_short_s = 2; - unsigned int x_int_u = 7; - unsigned int y_int_u = 2; + const unsigned int x_int_u = 7; + const unsigned int y_int_u = 2; signed int x_int_s = 7; signed int y_int_s = 2; - unsigned long x_long_u = 7; - unsigned long y_long_u = 2; + const unsigned long x_long_u = 7; + const unsigned long y_long_u = 2; signed long x_long_s = 7; signed long y_long_s = 2; float x_float = 7; @@ -596,16 +596,16 @@ test_math() std::cout << "+ +" << std::endl; - unsigned short x_short_u = 7; - unsigned short y_short_u = 2; + const unsigned short x_short_u = 7; + const unsigned short y_short_u = 2; signed short x_short_s = 7; signed short y_short_s = 2; - unsigned int x_int_u = 7; - unsigned int y_int_u = 2; + const unsigned int x_int_u = 7; + const unsigned int y_int_u = 2; signed int x_int_s = 7; signed int y_int_s = 2; - unsigned long x_long_u = 7; - unsigned long y_long_u = 2; + const unsigned long x_long_u = 7; + const unsigned long y_long_u = 2; signed long x_long_s = 7; signed long y_long_s = 2; float x_float = 7; @@ -717,12 +717,12 @@ test_math() #endif } -#define RETURN_TYPE_TEST(funcname, argtypename, returntypename) \ - { \ - const bool test_return_type = \ - std::is_same(123.4))), returntypename>(); \ - TEST("vnl_math::" #funcname "<" #argtypename "> returns " #returntypename " type", test_return_type, true); \ - } \ +#define RETURN_TYPE_TEST(funcname, argtypename, returntypename) \ + { \ + const bool test_return_type = \ + std::is_same(123.4))), returntypename>(); \ + TEST("vnl_math::" #funcname "<" #argtypename "> returns " #returntypename " type", test_return_type, true); \ + } \ void() RETURN_TYPE_TEST(isinf, int, bool); diff --git a/core/vnl/tests/test_matlab.cxx b/core/vnl/tests/test_matlab.cxx index dcaeb85c6ca..e8ffd974823 100644 --- a/core/vnl/tests/test_matlab.cxx +++ b/core/vnl/tests/test_matlab.cxx @@ -28,7 +28,7 @@ // get a byte-swapped file, short of reading in a native file and swapping it // and writing it back out, and that isn't any easier. void -matlab_write_swapped(std::ostream & f, const float * array, unsigned size, char const * name) +matlab_write_swapped(std::ostream & f, const float * array, unsigned size, const char * name) { vnl_matlab_header hdr; hdr.type = NONnative_BYTE_ORDER + vnl_matlab_header::vnl_COLUMN_WISE + vnl_matlab_header::vnl_SINGLE_PRECISION; @@ -41,18 +41,18 @@ matlab_write_swapped(std::ostream & f, const float * array, unsigned size, char byteswap::swap32(&hdr.cols); byteswap::swap32(&hdr.imag); byteswap::swap32(&hdr.namlen); - f.write((char const *)&hdr, sizeof(hdr)); - f.write((char const *)name, std::strlen(name) + 1); + f.write((const char *)&hdr, sizeof(hdr)); + f.write((const char *)name, std::strlen(name) + 1); for (unsigned i = 0; i < size; ++i) { float dummy = array[i]; byteswap::swap32(&dummy); - f.write((char const *)&dummy, sizeof(dummy)); + f.write((const char *)&dummy, sizeof(dummy)); } } static void -fsm_assert_(int lineno, bool pass, char const * expr) +fsm_assert_(int lineno, bool pass, const char * expr) { std::cout << __FILE__ " : " << lineno << std::endl; testlib_test_assert(expr, pass); @@ -90,15 +90,15 @@ test_matlab() // vnl_matlab_write, vnl_matlab_read { std::string tmp_nam = vul_temp_filename(), tmp_nam2 = vul_temp_filename(); - char const * file = !tmp_nam.empty() ? tmp_nam.c_str() : "smoo.mat"; - char const * file2 = !tmp_nam2.empty() ? tmp_nam2.c_str() : "smoo2.mat"; + const char * file = !tmp_nam.empty() ? tmp_nam.c_str() : "smoo.mat"; + const char * file2 = !tmp_nam2.empty() ? tmp_nam2.c_str() : "smoo2.mat"; { std::ofstream f(file); #ifdef LEAVE_IMAGES_BEHIND vpl_chmod(file, 0666); // -rw-rw-rw- #endif vnl_matlab_write(f, v.begin(), v.size(), "v"); - vnl_matlab_write(f, (double const * const *)M.data_array(), M.rows(), M.cols(), (char const *)"M"); + vnl_matlab_write(f, (const double * const *)M.data_array(), M.rows(), M.cols(), (const char *)"M"); // write swapped matlab file std::ofstream f2(file2); diff --git a/core/vnl/tests/test_matrix.cxx b/core/vnl/tests/test_matrix.cxx index 1c4965d3191..574c9a51a03 100644 --- a/core/vnl/tests/test_matrix.cxx +++ b/core/vnl/tests/test_matrix.cxx @@ -137,7 +137,7 @@ test_int() constexpr size_t lrow = 2; constexpr size_t lcol = 3; constexpr int some_data[lrow * lcol] = { 1, 2, 3, 4, 5, 6 }; - vnl_matrix mrc(some_data, lrow, lcol); + const vnl_matrix mrc(some_data, lrow, lcol); vnl_vector v; TEST("v = mrc.get_row(0)", (v = mrc.get_row(0), (v.get(0) == 1 && v.get(1) == 2 && v.get(2) == 3)), true); @@ -191,11 +191,11 @@ test_int() { int data[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; - vnl_vector flat(data, 16); + const vnl_vector flat(data, 16); - vnl_matrix sq(data, 4, 4); - vnl_matrix lg(data, 2, 8); - vnl_matrix wd(data, 8, 2); + const vnl_matrix sq(data, 4, 4); + const vnl_matrix lg(data, 2, 8); + const vnl_matrix wd(data, 8, 2); TEST("sq.flatten_row_major", flat.is_equal(sq.flatten_row_major(), 10e-6), true); TEST("lg.flatten_row_major", flat.is_equal(lg.flatten_row_major(), 10e-6), true); @@ -258,7 +258,7 @@ test_int() vnl_matrix m6(2, 2, 4, m6values); TEST("vnl_matrix m6(2,2,4,{1,2,3,4})", m6.get(1, 1), 4); int m7values[] = { 5, 6, 7, 8 }; - vnl_matrix m7(2, 2, 4, m7values); + const vnl_matrix m7(2, 2, 4, m7values); TEST("vnl_matrix m7(2,2,4,{5,6,7,8})", m7.get(1, 1), 8); TEST("m5=m6*m7", ((m5 = m6 * m7), (m5.get(0, 0) == 19 && m5.get(0, 1) == 22 && m5.get(1, 0) == 43 && m5.get(1, 1) == 50)), @@ -267,7 +267,7 @@ test_int() ((m6 *= m7), (m6.get(0, 0) == 19 && m6.get(0, 1) == 22 && m6.get(1, 0) == 43 && m6.get(1, 1) == 50)), true); int c0values[] = { 1, 0 }; - vnl_matrix c0(2, 1, 2, c0values); + const vnl_matrix c0(2, 1, 2, c0values); vnl_matrix c1; TEST("c1=m6*c0", ((c1 = m6 * c0), @@ -315,18 +315,18 @@ test_int() int v1values[] = { 1, 0, 0 }; int v2values[] = { 0, 1, 0 }; int v3values[] = { 0, 0, 1 }; - vnl_matrix v1(3, 1, 3, v1values); - vnl_matrix v2(3, 1, 3, v2values); - vnl_matrix v3(3, 1, 3, v3values); + const vnl_matrix v1(3, 1, 3, v1values); + const vnl_matrix v2(3, 1, 3, v2values); + const vnl_matrix v3(3, 1, 3, v3values); TEST("dot_product(v1,v2)", (dot_product(v1, v2) == 0 && dot_product(v1, v3) == 0 && dot_product(v2, v3) == 0), true); v = v3; TEST("4d-v=3d-v", (v.rows() == 3 && v.columns() == 1 && v == v3), true); // Zero-size { - vnl_matrix m1(0, 3); + const vnl_matrix m1(0, 3); vnl_matrix m2(3, 4); - vnl_matrix m3(4, 0); + const vnl_matrix m3(4, 0); vnl_matrix m = m1 * (m2 * m3); TEST("zero-size mult rows", m.rows(), 0); TEST("zero-size mult cols", m.columns(), 0); @@ -341,32 +341,32 @@ test_int() } { - vnl_matrix m(5, 10, 1); - vnl_vector vr = m.apply_rowwise(sum_vector); + const vnl_matrix m(5, 10, 1); + const vnl_vector vr = m.apply_rowwise(sum_vector); for (unsigned int i = 0; i < vr.size(); ++i) TEST("vr.apply_rowwise(sum_vector)", vr.get(i), 10); - vnl_vector vc = m.apply_columnwise(sum_vector); + const vnl_vector vc = m.apply_columnwise(sum_vector); for (unsigned int i = 0; i < vc.size(); ++i) TEST("vc.apply_columnwise(sum_vector)", vc.get(i), 5); } { // test operator-() on unsigned values - unsigned int vvalues[] = {1, 2, 3, 4}; - int out_values[] = {-1, -2, -3, -4}; + unsigned int vvalues[] = { 1, 2, 3, 4 }; + int out_values[] = { -1, -2, -3, -4 }; const vnl_matrix outm(2, 2, 4, out_values); - vnl_matrix unsigned_m22(2, 2, 4, vvalues); + const vnl_matrix unsigned_m22(2, 2, 4, vvalues); const vnl_matrix minus_v1 = -unsigned_m22; const vnl_matrix minus_v2 = unsigned_m22.operator-(); TEST("unsigned_m22.operator-()", (outm(0, 0) == minus_v1(0, 0) && outm(0, 1) == minus_v1(0, 1) && outm(1, 0) == minus_v1(1, 0) && - outm(1, 1) == minus_v1(1, 1)), true); + outm(1, 1) == minus_v1(1, 1)), + true); TEST("unsigned_m22.operator-()", (outm(0, 0) == minus_v2(0, 0) && outm(0, 1) == minus_v2(0, 1) && outm(1, 0) == minus_v2(1, 0) && - outm(1, 1) == minus_v2(1, 1)), true); + outm(1, 1) == minus_v2(1, 1)), + true); } - - } @@ -438,7 +438,7 @@ test_float() vnl_matrix d6(2, 2, 4, d6values); TEST("vnl_matrix d6(2,2,4,{1.0,2.0,3.0,4.0})", d6.get(1, 1), 4.0); float d7values[] = { 5.0, 6.0, 7.0, 8.0 }; - vnl_matrix d7(2, 2, 4, d7values); + const vnl_matrix d7(2, 2, 4, d7values); TEST("vnl_matrix d7(2,2,4,{5.0,6.0,7.0,8.0})", d7.get(1, 1), 8.0); TEST("d5=d6*d7", ((d5 = d6 * d7), (d5.get(0, 0) == 19.0 && d5.get(0, 1) == 22.0 && d5.get(1, 0) == 43.0 && d5.get(1, 1) == 50.0)), @@ -448,7 +448,9 @@ test_float() true); // additional tests - vnl_matrix m0, m1, m2; + vnl_matrix m0; + vnl_matrix m1; + vnl_matrix m2; float mvalues[] = { 0, -2, 2, 0 }; vnl_matrix m(2, 2, 4, mvalues); m0 = m; @@ -480,9 +482,9 @@ test_float() float v1values[] = { 1, 0, 0 }; float v2values[] = { 0, 1, 0 }; float v3values[] = { 0, 0, 1 }; - vnl_matrix v1(3, 1, 3, v1values); - vnl_matrix v2(3, 1, 3, v2values); - vnl_matrix v3(3, 1, 3, v3values); + const vnl_matrix v1(3, 1, 3, v1values); + const vnl_matrix v2(3, 1, 3, v2values); + const vnl_matrix v3(3, 1, 3, v3values); TEST("dot_product(v1,v2)", (dot_product(v1, v2) == 0 && dot_product(v1, v3) == 0 && dot_product(v2, v3) == 0), true); v = v3; TEST("4d-v=3d-v", (v.rows() == 3 && v.columns() == 1 && v == v3), true); @@ -492,11 +494,11 @@ test_float() TEST("zero-size after clear()", v.columns(), 0); { - vnl_matrix m(5, 10, 1); - vnl_vector vr = m.apply_rowwise(sum_vector); + const vnl_matrix m(5, 10, 1); + const vnl_vector vr = m.apply_rowwise(sum_vector); for (unsigned int i = 0; i < vr.size(); ++i) TEST("vr.apply_rowwise(sum_vector)", vr.get(i), 10); - vnl_vector vc = m.apply_columnwise(sum_vector); + const vnl_vector vc = m.apply_columnwise(sum_vector); for (unsigned int i = 0; i < vc.size(); ++i) TEST("vc.apply_columnwise(sum_vector)", vc.get(i), 5); } @@ -569,7 +571,7 @@ test_double() vnl_matrix d6(2, 2, 4, d6values); TEST("vnl_matrix d6(2,2,4,{1.0,2.0,3.0,4.0})", d6.get(1, 1), 4.0); double d7values[] = { 5.0, 6.0, 7.0, 8.0 }; - vnl_matrix d7(2, 2, 4, d7values); + const vnl_matrix d7(2, 2, 4, d7values); TEST("vnl_matrix d7(2,2,4,{5.0,6.0,7.0,8.0})", d7.get(1, 1), 8.0); TEST("d5=d6*d7", ((d5 = d6 * d7), (d5.get(0, 0) == 19.0 && d5.get(0, 1) == 22.0 && d5.get(1, 0) == 43.0 && d5.get(1, 1) == 50.0)), @@ -606,11 +608,11 @@ test_double() TEST("vnl_copy(T, S)", d9 == d2, true); { - vnl_matrix m(5, 10, 1); - vnl_vector vr = m.apply_rowwise(sum_vector); + const vnl_matrix m(5, 10, 1); + const vnl_vector vr = m.apply_rowwise(sum_vector); for (unsigned int i = 0; i < vr.size(); ++i) TEST("vr.apply_rowwise(sum_vector)", vr.get(i), 10); - vnl_vector vc = m.apply_columnwise(sum_vector); + const vnl_vector vc = m.apply_columnwise(sum_vector); for (unsigned int i = 0; i < vc.size(); ++i) TEST("vc.apply_columnwise(sum_vector)", vc.get(i), 5); } diff --git a/core/vnl/tests/test_matrix_exp.cxx b/core/vnl/tests/test_matrix_exp.cxx index faa3641a34a..22ebe476355 100644 --- a/core/vnl/tests/test_matrix_exp.cxx +++ b/core/vnl/tests/test_matrix_exp.cxx @@ -12,9 +12,9 @@ void test_matrix_exp() { - vnl_double_3 v(1.233, -0.572, 0.777); + const vnl_double_3 v(1.233, -0.572, 0.777); - vnl_cross_product_matrix X(v); + const vnl_cross_product_matrix X(v); vnl_matlab_print(std::cout, X, "[v]"); vnl_double_3x3 expX = vnl_matrix_exp(static_cast(X)); @@ -24,7 +24,7 @@ test_matrix_exp() TEST_NEAR("expX(1,1)", expX(1, 1), 0.1379544126, 1e-10); TEST_NEAR("expX(2,2)", expX(2, 2), 0.2501918781, 1e-10); - vnl_double_3x3 rotv = vnl_rotation_matrix(v); + const vnl_double_3x3 rotv = vnl_rotation_matrix(v); vnl_matlab_print(std::cout, rotv, "rotate exp([v])"); TEST_NEAR("rotv == expX", (rotv - expX).fro_norm(), 0.0, 1e-10); } diff --git a/core/vnl/tests/test_matrix_fixed.cxx b/core/vnl/tests/test_matrix_fixed.cxx index eaa62012231..40bfed4e2c8 100644 --- a/core/vnl/tests/test_matrix_fixed.cxx +++ b/core/vnl/tests/test_matrix_fixed.cxx @@ -2,6 +2,7 @@ #include #include #include +#include #include #include "vnl/vnl_matrix_fixed.h" @@ -39,7 +40,7 @@ sum_vector(const vnl_vector_fixed & v) static void test_size() { - vnl_matrix_fixed m; + const vnl_matrix_fixed m{}; TEST("memory footprint", sizeof(m), sizeof(double[12])); } @@ -50,9 +51,9 @@ test_multiply() double data_m2[8] = { 2, 3, 4, 5, 6, 7, 8, 9 }; double data_v1[2] = { 7, 8 }; - vnl_matrix_fixed m1(data_m1); - vnl_matrix_fixed m2(data_m2); - vnl_vector_fixed v1(data_v1); + const vnl_matrix_fixed m1(data_m1); + const vnl_matrix_fixed m2(data_m2); + const vnl_vector_fixed v1(data_v1); vnl_matrix_fixed mr = m1 * m2; TEST("Matrix-matrix multiply", @@ -236,7 +237,7 @@ test_int() vnl_int_2x2 m6(m6values); TEST("vnl_int_2x2 m6({1,2,3,4})", m6.get(1, 1), 4); int m7values[] = { 5, 6, 7, 8 }; - vnl_int_2x2 m7(m7values); + const vnl_int_2x2 m7(m7values); TEST("vnl_int_2x2 m7({5,6,7,8})", m7.get(1, 1), 8); TEST("m5=m6*m7", ((m5 = m6 * m7), (m5.get(0, 0) == 19 && m5.get(0, 1) == 22 && m5.get(1, 0) == 43 && m5.get(1, 1) == 50)), @@ -252,11 +253,11 @@ test_int() { int data[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; - vnl_vector flat(data, 16); + const vnl_vector flat(data, 16); - vnl_matrix_fixed sq(data); - vnl_matrix_fixed lg(data); - vnl_matrix_fixed wd(data); + const vnl_matrix_fixed sq(data); + const vnl_matrix_fixed lg(data); + const vnl_matrix_fixed wd(data); TEST("sq.flatten_row_major", flat.is_equal(sq.flatten_row_major().as_vector(), 10e-6), true); TEST("lg.flatten_row_major", flat.is_equal(lg.flatten_row_major().as_vector(), 10e-6), true); @@ -294,19 +295,21 @@ test_int() true); { // test operator-() on unsigned values - unsigned int vvalues[] = {1, 2, 3, 4}; - int out_values[] = {-1, -2, -3, -4}; - const vnl_matrix_fixed outm( out_values); + unsigned int vvalues[] = { 1, 2, 3, 4 }; + int out_values[] = { -1, -2, -3, -4 }; + const vnl_matrix_fixed outm(out_values); - vnl_matrix_fixed unsigned_m22(vvalues); - const vnl_matrix_fixed minus_v1 = -unsigned_m22; - const vnl_matrix_fixed minus_v2 = unsigned_m22.operator-(); + const vnl_matrix_fixed unsigned_m22(vvalues); + const vnl_matrix_fixed minus_v1 = -unsigned_m22; + const vnl_matrix_fixed minus_v2 = unsigned_m22.operator-(); TEST("unsigned_m22.operator-()", (outm(0, 0) == minus_v1(0, 0) && outm(0, 1) == minus_v1(0, 1) && outm(1, 0) == minus_v1(1, 0) && - outm(1, 1) == minus_v1(1, 1)), true); + outm(1, 1) == minus_v1(1, 1)), + true); TEST("unsigned_m22.operator-()", (outm(0, 0) == minus_v2(0, 0) && outm(0, 1) == minus_v2(0, 1) && outm(1, 0) == minus_v2(1, 0) && - outm(1, 1) == minus_v2(1, 1)), true); + outm(1, 1) == minus_v2(1, 1)), + true); } } @@ -372,7 +375,7 @@ test_float() vnl_float_2x2 d6(d6values); TEST("vnl_float_2x2 d6({1.0,2.0,3.0,4.0})", d6.get(1, 1), 4.0); float d7values[] = { 5.0, 6.0, 7.0, 8.0 }; - vnl_float_2x2 d7(d7values); + const vnl_float_2x2 d7(d7values); TEST("vnl_float_2x2 d7({5.0,6.0,7.0,8.0})", d7.get(1, 1), 8.0); TEST("d5=d6*d7", ((d5 = d6 * d7), (d5.get(0, 0) == 19.0 && d5.get(0, 1) == 22.0 && d5.get(1, 0) == 43.0 && d5.get(1, 1) == 50.0)), @@ -382,11 +385,10 @@ test_float() true); // additional tests - vnl_float_2x2 m1, m2; float mvalues[] = { 0, -2, 2, 0 }; vnl_float_2x2 m(mvalues); - m1 = m; - m2 = m; + vnl_float_2x2 m1 = m; + vnl_float_2x2 m2 = m; vnl_matrix m3; TEST("m(i,j)", (m(0, 0) == 0 && m(0, 1) == -2 && m(1, 0) == 2 && m(1, 1) == 0), true); TEST("m.max_value()", m.max_value(), 2); @@ -476,7 +478,7 @@ test_double() vnl_double_2x2 d6(d6values); TEST("vnl_double_2x2 d6({1.0,2.0,3.0,4.0})", d6.get(1, 1), 4.0); double d7values[] = { 5.0, 6.0, 7.0, 8.0 }; - vnl_double_2x2 d7(d7values); + const vnl_double_2x2 d7(d7values); TEST("vnl_double_2x2 d7({5.0,6.0,7.0,8.0})", d7.get(1, 1), 8.0); TEST("d5=d6*d7", ((d5 = d6 * d7), (d5.get(0, 0) == 19.0 && d5.get(0, 1) == 22.0 && d5.get(1, 0) == 43.0 && d5.get(1, 1) == 50.0)), @@ -492,11 +494,11 @@ test_double() TEST("apply(sqrt)", d8[0][0] == 0 && d8[0][1] == 1 && d8[1][0] == 3 && d8[1][1] == 4, true); { - vnl_matrix_fixed m(1.); - vnl_vector_fixed vr = m.apply_rowwise(sum_vector); + const vnl_matrix_fixed m(1.); + const vnl_vector_fixed vr = m.apply_rowwise(sum_vector); for (unsigned int i = 0; i < vr.size(); ++i) TEST("vr.apply_rowwise(sum_vector)", vr.get(i), 20.); - vnl_vector_fixed vc = m.apply_columnwise(sum_vector); + const vnl_vector_fixed vc = m.apply_columnwise(sum_vector); for (unsigned int i = 0; i < vc.size(); ++i) TEST("vc.apply_columnwise(sum_vector)", vc.get(i), 4.); } @@ -586,15 +588,15 @@ test_matrix_fixed() std::printf("splork = [ %g %g %g ]\n", splork(0), splork(1), splork(2)); std::printf("Now watch the mallocs\n"); - vnl_matrix_ref CX = X.as_ref(); - vnl_vector_ref cv = v.as_ref(); + const vnl_matrix_ref CX = X.as_ref(); + const vnl_vector_ref cv = v.as_ref(); vnl_vector Xv = CX * (cv + cv); std::printf("X v = [ %g %g %g ]\n", Xv[0], Xv[1], Xv[2]); verbose_malloc = false; // test that vnl_double_3x3's can be multiplied - vnl_double_3x3 A(datablock); + const vnl_double_3x3 A(datablock); vnl_double_3x3 B = A * A; // test that vnl_double_3x3's can be added and subtracted diff --git a/core/vnl/tests/test_matrix_fixed_ref.cxx b/core/vnl/tests/test_matrix_fixed_ref.cxx index b13a8386345..2db70dfa939 100644 --- a/core/vnl/tests/test_matrix_fixed_ref.cxx +++ b/core/vnl/tests/test_matrix_fixed_ref.cxx @@ -12,7 +12,7 @@ test_matrix_fixed_ref() { constexpr double bulk_data_array[4]{ 1.0, 2.0, 3.0, 4.0 }; vnl_matrix_fixed initial_fixed_size_matrix(bulk_data_array); - vnl_matrix_ref ref_to_data( initial_fixed_size_matrix.as_ref() ); + vnl_matrix_ref ref_to_data(initial_fixed_size_matrix.as_ref()); TEST("vnl_matrix_ref{ vnl_matrix_fixed } share data pointer", initial_fixed_size_matrix.data_block() == ref_to_data.data_block(), @@ -44,7 +44,8 @@ test_matrix_fixed_ref() typedef vnl_matrix_fixed_ref mfr; typedef vnl_matrix_fixed_ref_const mfrc; - unsigned int i, j; + unsigned int i; + unsigned int j; mf mat; // copy in for (i = 0; i < rows; ++i) for (j = 0; j < cols; ++j) @@ -55,7 +56,7 @@ test_matrix_fixed_ref() // fixed_ref_const const mf & cmf = mat; - mfrc cref(cmf); + const mfrc cref(cmf); // check address for (i = 0; i < rows; ++i) { @@ -69,24 +70,24 @@ test_matrix_fixed_ref() // get_row for (i = 0; i < rows; ++i) { - vnl_vector_fixed row_copy = cmf.get_row(i); - vnl_vector_fixed row_copy2 = mat.get_row(i); + const vnl_vector_fixed row_copy = cmf.get_row(i); + const vnl_vector_fixed row_copy2 = mat.get_row(i); TEST("get_row", row_copy, row_copy2); } // get_col for (j = 0; j < cols; ++j) { - vnl_vector_fixed col_copy = cmf.get_column(j); - vnl_vector_fixed col_copy2 = mat.get_column(j); + const vnl_vector_fixed col_copy = cmf.get_column(j); + const vnl_vector_fixed col_copy2 = mat.get_column(j); TEST("get_column", col_copy, col_copy2); } // get_diagonal - vnl_vector_fixed v(0, 11, 22); + const vnl_vector_fixed v(0, 11, 22); TEST("get_diagonal()", cmf.get_diagonal(), v); // fixed_ref (non-const) // wrap around mat - mfr ref(mat); + const mfr ref(mat); // check address for (i = 0; i < rows; ++i) { @@ -102,7 +103,7 @@ test_matrix_fixed_ref() std::generate(new_row.begin(), new_row.end(), std::rand); ref.set_row(i, new_row); - vnl_vector_fixed row_copy = mat.get_row(i); + const vnl_vector_fixed row_copy = mat.get_row(i); TEST("set_row", new_row, row_copy); } // set_col @@ -112,7 +113,7 @@ test_matrix_fixed_ref() std::generate(new_col.begin(), new_col.end(), std::rand); ref.set_column(j, new_col); - vnl_vector_fixed col_copy = mat.get_column(j); + const vnl_vector_fixed col_copy = mat.get_column(j); TEST("set_col", new_col, col_copy); } // set diagonal @@ -125,7 +126,7 @@ test_matrix_fixed_ref() { // assign from const mfr std::generate(other.begin(), other.end(), std::rand); - mfrc cref(other); + const mfrc cref(other); ref = cref; TEST("assign_const_ref", ref, other); // mfr vs mf // test different addresses @@ -135,34 +136,40 @@ test_matrix_fixed_ref() // arithmetic { // plus - mf a, b; + mf a; + mf b; std::generate(a.begin(), a.end(), std::rand); std::generate(b.begin(), b.end(), std::rand); - mfrc arefc(a), brefc(b); - mf mc = arefc + brefc; + const mfrc arefc(a); + const mfrc brefc(b); + const mf mc = arefc + brefc; - mfr aref(a), bref(b); - mf m = aref + bref; + const mfr aref(a); + const mfr bref(b); + const mf m = aref + bref; - mf m2 = arefc + bref; - mf m3 = arefc + brefc; + const mf m2 = arefc + bref; + const mf m3 = arefc + brefc; TEST("plus", mc, m); TEST("plus", mc, m2); TEST("plus", mc, m3); } { // times - mf a, b; + mf a; + mf b; std::generate(a.begin(), a.end(), std::rand); std::generate(b.begin(), b.end(), std::rand); - mfrc arefc(a), brefc(b); - mf mc = arefc + brefc; + const mfrc arefc(a); + const mfrc brefc(b); + const mf mc = arefc + brefc; - mfr aref(a), bref(b); - mf m = aref + bref; + const mfr aref(a); + const mfr bref(b); + const mf m = aref + bref; - mf m2 = arefc + bref; - mf m3 = arefc + brefc; + const mf m2 = arefc + bref; + const mf m3 = arefc + brefc; TEST("plus", mc, m); TEST("plus", mc, m2); TEST("plus", mc, m3); diff --git a/core/vnl/tests/test_na.cxx b/core/vnl/tests/test_na.cxx index b2629cf9588..72a30267b8a 100644 --- a/core/vnl/tests/test_na.cxx +++ b/core/vnl/tests/test_na.cxx @@ -67,7 +67,8 @@ test_na_type(T na_v, T qnan_v) } { - T x = 0.0, y = 0.0; + T x = 0.0; + T y = 0.0; std::istringstream ss("NA1.0"); vnl_na_extract(ss, x); vnl_na_extract(ss, y); @@ -76,7 +77,8 @@ test_na_type(T na_v, T qnan_v) } { - T x = 0.0, y = 0.0; + T x = 0.0; + T y = 0.0; std::istringstream ss("1.0NA"); vnl_na_extract(ss, x); vnl_na_extract(ss, y); @@ -85,7 +87,8 @@ test_na_type(T na_v, T qnan_v) } { - T x = 0.0, y = 0.0; + T x = 0.0; + T y = 0.0; std::istringstream ss("NANA"); vnl_na_extract(ss, x); vnl_na_extract(ss, y); @@ -94,7 +97,8 @@ test_na_type(T na_v, T qnan_v) } { - T x = 0.0, y = 0.0; + T x = 0.0; + T y = 0.0; std::istringstream ss("NA 1.0"); vnl_na_extract(ss, x); vnl_na_extract(ss, y); @@ -103,7 +107,8 @@ test_na_type(T na_v, T qnan_v) } { - T x = 0.0, y = 0.0; + T x = 0.0; + T y = 0.0; std::istringstream ss("1.0 NA"); vnl_na_extract(ss, x); vnl_na_extract(ss, y); @@ -112,7 +117,8 @@ test_na_type(T na_v, T qnan_v) } { - T x = 0.0, y = 0.0; + T x = 0.0; + T y = 0.0; std::istringstream ss("NA NA"); vnl_na_extract(ss, x); vnl_na_extract(ss, y); @@ -121,7 +127,8 @@ test_na_type(T na_v, T qnan_v) } { - T x = 0.0, y = 0.0; + T x = 0.0; + T y = 0.0; std::istringstream ss("-1.0-1.0"); vnl_na_extract(ss, x); vnl_na_extract(ss, y); @@ -140,7 +147,8 @@ test_na_type(T na_v, T qnan_v) { std::stringstream ss; ss << vnl_na_stream(-1.0) << ' ' << vnl_na_stream(vnl_na(T())); - T x = 0.0, y = 0.0; + T x = 0.0; + T y = 0.0; ss >> vnl_na_stream(x) >> vnl_na_stream(y); TEST("x,y=\"-1.0 NA\"", vnl_na_isna(y) && x == -1.0, true); std::cout << "y = " << y << " = " << print_hex(y) << '\n' << "ss = " << ss.str() << std::endl; diff --git a/core/vnl/tests/test_numeric_traits.cxx b/core/vnl/tests/test_numeric_traits.cxx index 9448d20c4fd..f2907d4b730 100644 --- a/core/vnl/tests/test_numeric_traits.cxx +++ b/core/vnl/tests/test_numeric_traits.cxx @@ -11,20 +11,20 @@ check_pointer(const void *) static void test_static_const_definition() { -#define ONE_ZERO(Type) \ - do \ - { \ - check_pointer(&vnl_numeric_traits::zero); \ - check_pointer(&vnl_numeric_traits::one); \ - check_pointer(&vnl_numeric_traits::zero); \ - check_pointer(&vnl_numeric_traits::one); \ +#define ONE_ZERO(Type) \ + do \ + { \ + check_pointer(&vnl_numeric_traits::zero); \ + check_pointer(&vnl_numeric_traits::one); \ + check_pointer(&vnl_numeric_traits::zero); \ + check_pointer(&vnl_numeric_traits::one); \ } while (false) -#define ALL(Type) \ - ONE_ZERO(Type); \ - do \ - { \ - check_pointer(&vnl_numeric_traits::maxval); \ - check_pointer(&vnl_numeric_traits::maxval); \ +#define ALL(Type) \ + ONE_ZERO(Type); \ + do \ + { \ + check_pointer(&vnl_numeric_traits::maxval); \ + check_pointer(&vnl_numeric_traits::maxval); \ } while (false) ALL(bool); @@ -125,14 +125,14 @@ test_numeric_traits() #endif // Testing maxval values - char cm = vnl_numeric_traits::maxval; - signed char scm = vnl_numeric_traits::maxval; + const char cm = vnl_numeric_traits::maxval; + const signed char scm = vnl_numeric_traits::maxval; unsigned char ucm = vnl_numeric_traits::maxval; - short sm = vnl_numeric_traits::maxval; + const short sm = vnl_numeric_traits::maxval; unsigned short usm = vnl_numeric_traits::maxval; - int im = vnl_numeric_traits::maxval; + const int im = vnl_numeric_traits::maxval; unsigned int uim = vnl_numeric_traits::maxval; - long lm = vnl_numeric_traits::maxval; + const long lm = vnl_numeric_traits::maxval; unsigned long ulm = vnl_numeric_traits::maxval; float fm = vnl_numeric_traits::maxval; double dm = vnl_numeric_traits::maxval; @@ -161,7 +161,10 @@ test_numeric_traits() TEST("vnl_numeric_traits::maxval must be at least 127", cm >= 127, true); TEST("vnl_numeric_traits::maxval must be at least 127", scm >= 127, true); TEST("vnl_numeric_traits::maxval must be larger than that", ucm > scm, true); + /* always true comparison of constant 32767 with expression of type 'unsigned char' is always true + * at compiletime, and throws a warning. TEST("vnl_numeric_traits::maxval must be larger than that", sm > ucm, true); + */ TEST("vnl_numeric_traits::maxval must be at least as large", im >= sm, true); TEST("vnl_numeric_traits::maxval must be larger than ", usm > sm, true); TEST( @@ -226,7 +229,7 @@ test_numeric_traits() #endif for (int j = 7; j >= 0; --j) { - int n = int(((x[i]) >> j) & 1); + const int n = int(((x[i]) >> j) & 1); nr_of_ones += n; std::cout << n; } @@ -244,7 +247,7 @@ test_numeric_traits() #endif for (int j = 7; j >= 0; --j) { - int n = int(((x[i]) >> j) & 1); + const int n = int(((x[i]) >> j) & 1); nr_of_ones += n; std::cout << n; } diff --git a/core/vnl/tests/test_polynomial.cxx b/core/vnl/tests/test_polynomial.cxx index a7fa5e4ad4e..50877b68042 100644 --- a/core/vnl/tests/test_polynomial.cxx +++ b/core/vnl/tests/test_polynomial.cxx @@ -10,7 +10,8 @@ void test_polynomial_double() { - vnl_polynomial f1(3), f2(4); + vnl_polynomial f1(3); + vnl_polynomial f2(4); for (int i = 0; i <= f1.degree(); ++i) f1[i] = 4.0 - i; // f1 = X^3 +2 X^2 +3 X + 4 @@ -18,7 +19,7 @@ test_polynomial_double() { std::stringstream testStream; testStream << f1; - std::string expected = " X^3 +2 X^2 +3 X +4"; + const std::string expected = " X^3 +2 X^2 +3 X +4"; TEST("f1 prints as X^3 +2 X^2 +3 X +4", testStream.str(), expected); } @@ -70,9 +71,9 @@ test_polynomial_double() std::cout << "f1%f2 =" << f3 << std::endl; TEST("f1%f2", f3, f1); - vnl_polynomial f1d = f1.derivative(); + const vnl_polynomial f1d = f1.derivative(); std::cout << "f1d =" << f1d << std::endl; - vnl_polynomial f2d = f2.derivative(); + const vnl_polynomial f2d = f2.derivative(); std::cout << "f2d =" << f2d << std::endl; f3 = f1 * f2; @@ -83,7 +84,7 @@ test_polynomial_double() std::cout << "f3d =" << f3.derivative() << std::endl; TEST("Derivative", f3.derivative(), f1d * f2 + f2d * f1); - vnl_polynomial f3p = (f1d * f2 + f2d * f1).primitive(); + const vnl_polynomial f3p = (f1d * f2 + f2d * f1).primitive(); std::cout << "f3p =" << f3p << std::endl; TEST("Primitive", f3p, f3 - f3.evaluate(0.0)); @@ -114,42 +115,42 @@ test_polynomial_double() { std::stringstream testStream; testStream << f4; - std::string expected = " X +1"; + const std::string expected = " X +1"; TEST("f4 prints as X +1", testStream.str(), expected); } f4 *= 2.0; // f4 = 2 X + 2 { std::stringstream testStream; testStream << f4; - std::string expected = " 2 X +2"; + const std::string expected = " 2 X +2"; TEST("f4 prints as 2 X +2", testStream.str(), expected); } f4 = -f4; // f4 = -2 X - 2 { std::stringstream testStream; testStream << f4; - std::string expected = " -2 X -2"; + const std::string expected = " -2 X -2"; TEST("f4 prints as -2 X -2", testStream.str(), expected); } f4[1] = 1; // f4 = X - 2 { std::stringstream testStream; testStream << f4; - std::string expected = " X -2"; + const std::string expected = " X -2"; TEST("f4 prints as X -2", testStream.str(), expected); } f4[0] = 0; // f4 = X { std::stringstream testStream; testStream << f4; - std::string expected = " X"; + const std::string expected = " X"; TEST("f4 prints as X", testStream.str(), expected); } f4[1] = 0; // f4 = 0 { std::stringstream testStream; testStream << f4; - std::string expected = " 0"; + const std::string expected = " 0"; TEST("f4 prints as 0", testStream.str(), expected); } } @@ -157,7 +158,8 @@ test_polynomial_double() void test_polynomial_long() { - vnl_polynomial f1(3), f2(4); + vnl_polynomial f1(3); + vnl_polynomial f2(4); for (int i = 0; i <= f1.degree(); ++i) f1[i] = 4 - i; // f1 = X^3 +2 X^2 +3 X + 4 @@ -165,7 +167,7 @@ test_polynomial_long() { std::stringstream testStream; testStream << f1; - std::string expected = " X^3 +2 X^2 +3 X +4"; + const std::string expected = " X^3 +2 X^2 +3 X +4"; TEST("f1 prints as X^3 +2 X^2 +3 X +4", testStream.str(), expected); } @@ -198,9 +200,9 @@ test_polynomial_long() TEST("f2(x)-f1(x)", f2.evaluate(302L) - f1.evaluate(302L), f3.evaluate(302L)); TEST("f2-f1", f3.degree() == 4 && f3[4] == 1 && f3[3] == 2 && f3[2] == 3 && f3[1] == 4 && f3[0] == 5, true); - vnl_polynomial f1d = f1.derivative(); + const vnl_polynomial f1d = f1.derivative(); std::cout << "f1d =" << f1d << std::endl; - vnl_polynomial f2d = f2.derivative(); + const vnl_polynomial f2d = f2.derivative(); std::cout << "f2d =" << f2d << std::endl; f3 = f1 * f2; @@ -211,7 +213,7 @@ test_polynomial_long() std::cout << "f3d =" << f3.derivative() << std::endl; TEST("Derivative", f3.derivative(), f1d * f2 + f2d * f1); - vnl_polynomial f3p = (f1d * f2 + f2d * f1).primitive(); + const vnl_polynomial f3p = (f1d * f2 + f2d * f1).primitive(); std::cout << "f3p =" << f3p << std::endl; TEST("Polynomial of degree 0", vnl_polynomial(12L).evaluate(302L), 12L); @@ -231,42 +233,42 @@ test_polynomial_long() { std::stringstream testStream; testStream << f4; - std::string expected = " X +1"; + const std::string expected = " X +1"; TEST("f4 prints as X +1", testStream.str(), expected); } f4 *= 2L; // f4 = 2 X + 2 { std::stringstream testStream; testStream << f4; - std::string expected = " 2 X +2"; + const std::string expected = " 2 X +2"; TEST("f4 prints as 2 X +2", testStream.str(), expected); } f4 = -f4; // f4 = -2 X - 2 { std::stringstream testStream; testStream << f4; - std::string expected = " -2 X -2"; + const std::string expected = " -2 X -2"; TEST("f4 prints as -2 X -2", testStream.str(), expected); } f4[1] = 1L; // f4 = X - 2 { std::stringstream testStream; testStream << f4; - std::string expected = " X -2"; + const std::string expected = " X -2"; TEST("f4 prints as X -2", testStream.str(), expected); } f4[0] = 0L; // f4 = X { std::stringstream testStream; testStream << f4; - std::string expected = " X"; + const std::string expected = " X"; TEST("f4 prints as X", testStream.str(), expected); } f4[1] = 0L; // f4 = 0 { std::stringstream testStream; testStream << f4; - std::string expected = " 0"; + const std::string expected = " 0"; TEST("f4 prints as 0", testStream.str(), expected); } } @@ -274,7 +276,8 @@ test_polynomial_long() void test_polynomial_rational() { - vnl_polynomial f1(3), f2(4); + vnl_polynomial f1(3); + vnl_polynomial f2(4); for (int i = 0; i <= f1.degree(); ++i) f1[i] = vnl_rational(1, 4 - i); // f1 = X^3 +1/2 X^2 +1/3 X + 1/4 @@ -282,7 +285,7 @@ test_polynomial_rational() { std::stringstream testStream; testStream << f1; - std::string expected = " X^3 +1/2 X^2 +1/3 X +1/4"; + const std::string expected = " X^3 +1/2 X^2 +1/3 X +1/4"; TEST("f1 prints as X^3 +1/2 X^2 +1/3 X +1/4", testStream.str(), expected); } @@ -355,9 +358,9 @@ test_polynomial_rational() std::cout << "f1%f2 =" << f3 << std::endl; TEST("f1%f2", f3, f1); - vnl_polynomial f1d = f1.derivative(); + const vnl_polynomial f1d = f1.derivative(); std::cout << "f1d =" << f1d << std::endl; - vnl_polynomial f2d = f2.derivative(); + const vnl_polynomial f2d = f2.derivative(); std::cout << "f2d =" << f2d << std::endl; f3 = f1 * f2; @@ -369,7 +372,7 @@ test_polynomial_rational() std::cout << "f3d =" << f3.derivative() << std::endl; TEST("Derivative", f3.derivative(), f1d * f2 + f2d * f1); - vnl_polynomial f3p = (f1d * f2 + f2d * f1).primitive(); + const vnl_polynomial f3p = (f1d * f2 + f2d * f1).primitive(); std::cout << "f3p =" << f3p << std::endl; TEST("Primitive", f3p, f3 - f3.evaluate(0)); @@ -400,42 +403,42 @@ test_polynomial_rational() { std::stringstream testStream; testStream << f4; - std::string expected = " X +1/1"; + const std::string expected = " X +1/1"; TEST("f4 prints as X +1/1", testStream.str(), expected); } f4 *= vnl_rational(2); // f4 = 2 X + 2 { std::stringstream testStream; testStream << f4; - std::string expected = " 2/1 X +2/1"; + const std::string expected = " 2/1 X +2/1"; TEST("f4 prints as 2/1 X +2/1", testStream.str(), expected); } f4 = -f4; // f4 = -2 X - 2 { std::stringstream testStream; testStream << f4; - std::string expected = " -2/1 X -2/1"; + const std::string expected = " -2/1 X -2/1"; TEST("f4 prints as -2/1 X -2/1", testStream.str(), expected); } f4[1] = 1; // f4 = X - 2 { std::stringstream testStream; testStream << f4; - std::string expected = " X -2/1"; + const std::string expected = " X -2/1"; TEST("f4 prints as X -2/1", testStream.str(), expected); } f4[0] = 0; // f4 = X { std::stringstream testStream; testStream << f4; - std::string expected = " X"; + const std::string expected = " X"; TEST("f4 prints as X", testStream.str(), expected); } f4[1] = 0; // f4 = 0 { std::stringstream testStream; testStream << f4; - std::string expected = " 0"; + const std::string expected = " 0"; TEST("f4 prints as 0", testStream.str(), expected); } } @@ -443,7 +446,8 @@ test_polynomial_rational() void test_polynomial_decnum() { - vnl_polynomial f1(3), f2(4); + vnl_polynomial f1(3); + vnl_polynomial f2(4); for (int i = 0; i <= f1.degree(); ++i) f1[i] = 4 - i; // f1 = X^3 +2 X^2 +3 X + 4 @@ -451,7 +455,7 @@ test_polynomial_decnum() { std::stringstream testStream; testStream << f1; - std::string expected = " X^3 +2 X^2 +3 X +4"; + const std::string expected = " X^3 +2 X^2 +3 X +4"; TEST("f1 prints as X^3 +2 X^2 +3 X +4", testStream.str(), expected); } @@ -484,9 +488,9 @@ test_polynomial_decnum() TEST("f2(x)-f1(x)", f2.evaluate("35e19") - f1.evaluate("35e19"), f3.evaluate("35e19")); TEST("f2-f1", f3.degree() == 4 && f3[4] == 1 && f3[3] == 2 && f3[2] == 3 && f3[1] == 4 && f3[0] == 5, true); - vnl_polynomial f1d = f1.derivative(); + const vnl_polynomial f1d = f1.derivative(); std::cout << "f1d =" << f1d << std::endl; - vnl_polynomial f2d = f2.derivative(); + const vnl_polynomial f2d = f2.derivative(); std::cout << "f2d =" << f2d << std::endl; f3 = f1 * f2; @@ -497,7 +501,7 @@ test_polynomial_decnum() std::cout << "f3d =" << f3.derivative() << std::endl; TEST("Derivative", f3.derivative(), f1d * f2 + f2d * f1); - vnl_polynomial f3p = (f1d * f2 + f2d * f1).primitive(); + const vnl_polynomial f3p = (f1d * f2 + f2d * f1).primitive(); std::cout << "f3p =" << f3p << std::endl; TEST("Polynomial of degree 0", vnl_polynomial("12").evaluate("35e19"), vnl_decnum("12")); @@ -517,42 +521,42 @@ test_polynomial_decnum() { std::stringstream testStream; testStream << f4; - std::string expected = " X +1"; + const std::string expected = " X +1"; TEST("f4 prints as X +1", testStream.str(), expected); } f4 *= vnl_decnum("2"); // f4 = 2 X + 2 { std::stringstream testStream; testStream << f4; - std::string expected = " 2 X +2"; + const std::string expected = " 2 X +2"; TEST("f4 prints as 2 X +2", testStream.str(), expected); } f4 = -f4; // f4 = -2 X - 2 { std::stringstream testStream; testStream << f4; - std::string expected = " -2 X -2"; + const std::string expected = " -2 X -2"; TEST("f4 prints as -2 X -2", testStream.str(), expected); } f4[1] = 1L; // f4 = X - 2 { std::stringstream testStream; testStream << f4; - std::string expected = " X -2"; + const std::string expected = " X -2"; TEST("f4 prints as X -2", testStream.str(), expected); } f4[0] = 0L; // f4 = X { std::stringstream testStream; testStream << f4; - std::string expected = " X"; + const std::string expected = " X"; TEST("f4 prints as X", testStream.str(), expected); } f4[1] = 0L; // f4 = 0 { std::stringstream testStream; testStream << f4; - std::string expected = " 0"; + const std::string expected = " 0"; TEST("f4 prints as 0", testStream.str(), expected); } } diff --git a/core/vnl/tests/test_pow_log.cxx b/core/vnl/tests/test_pow_log.cxx index 89aa08c4bf0..5adf8d1c685 100644 --- a/core/vnl/tests/test_pow_log.cxx +++ b/core/vnl/tests/test_pow_log.cxx @@ -7,7 +7,7 @@ // certainly in those cases where b is relatively small. // Negative exponents make of course no sense since the result must be int. // Beware of overflow! -inline static int +static inline int int_pow(int a, unsigned int b) { if (b == 0) @@ -16,9 +16,9 @@ int_pow(int a, unsigned int b) return a; else { - long asquare = static_cast(a) * static_cast(a); - long r1 = static_cast(int_pow(static_cast(asquare), b / 2)); - long r2 = static_cast(int_pow(a, b % 2)); + const long asquare = static_cast(a) * static_cast(a); + const long r1 = static_cast(int_pow(static_cast(asquare), b / 2)); + const long r2 = static_cast(int_pow(a, b % 2)); return static_cast(r1 * r2); } } @@ -26,7 +26,7 @@ int_pow(int a, unsigned int b) // A recursive implementation for a^b with a double and b integer; // this is a more accurate alternative for std::pow(double a,double b), // certainly in those cases where b is relatively small. -inline static double +static inline double int_pow(double a, int b) { if (b == 0) @@ -44,7 +44,7 @@ int_pow(double a, int b) // std::floor(std::log(double a)/std::log(8.0)). // Negative arguments make of course no sense; strictly speaking, also a=0 // makes no sense, but in that case a "very negative" value is returned. -inline static int +static inline int log8(unsigned int a) { if (a == 0) diff --git a/core/vnl/tests/test_power.cxx b/core/vnl/tests/test_power.cxx index 26856dffc8b..69317424e02 100644 --- a/core/vnl/tests/test_power.cxx +++ b/core/vnl/tests/test_power.cxx @@ -7,17 +7,21 @@ static void test_power() { - double eps = 1e-11; - vnl_double_2x2 residue2, id2; + const double eps = 1e-11; + vnl_double_2x2 residue2; + vnl_double_2x2 id2; id2.set_identity(); - vnl_matrix ID2 = id2.as_ref(); - vnl_double_3x3 residue3, id3; + const vnl_matrix ID2 = id2.as_ref(); + vnl_double_3x3 residue3; + vnl_double_3x3 id3; id3.set_identity(); - vnl_matrix ID3 = id3.as_ref(); - vnl_double_4x4 residue4, id4; + const vnl_matrix ID3 = id3.as_ref(); + vnl_double_4x4 residue4; + vnl_double_4x4 id4; id4.set_identity(); - vnl_matrix ID4 = id4.as_ref(); - vnl_matrix M, Mi; + const vnl_matrix ID4 = id4.as_ref(); + vnl_matrix M; + vnl_matrix Mi; // 11th power of the identity 2x2 matrix vnl_double_2x2 id2i = vnl_power(id2, 11); diff --git a/core/vnl/tests/test_quaternion.cxx b/core/vnl/tests/test_quaternion.cxx index 0544b081140..b747fda0ffd 100644 --- a/core/vnl/tests/test_quaternion.cxx +++ b/core/vnl/tests/test_quaternion.cxx @@ -15,10 +15,13 @@ const double dtol = 16 * std::numeric_limits::epsilon(); static void test_operators() { - vnl_quaternion a(0, 0, 0, 1), b(2, 2, 2, 2), c, d(2, 2, 2, 3), e(1, 2, 3, 4); + const vnl_quaternion a(0, 0, 0, 1); + const vnl_quaternion b(2, 2, 2, 2); + const vnl_quaternion d(2, 2, 2, 3); + vnl_quaternion e(1, 2, 3, 4); TEST("!=", a != b, true); TEST("==", a == a, true); - c = a + b; + const vnl_quaternion c = a + b; TEST("+", c, d); TEST(".x()", e.x(), 1.0); TEST(".y()", e.y(), 2.0); @@ -39,9 +42,9 @@ test_random_round_trip() // Need to be careful abount wrap around - don't test with angles that are too big vnl_vector_fixed euler( rng.normal() * vnl_math::pi / 18.0, rng.normal() * vnl_math::pi / 18.0, rng.normal() * vnl_math::pi / 18.0); - vnl_quaternion quat(euler(0), euler(1), euler(2)); - vnl_vector_fixed out = quat.rotation_euler_angles(); - double err = vnl_vector_ssd(euler, out); + const vnl_quaternion quat(euler(0), euler(1), euler(2)); + const vnl_vector_fixed out = quat.rotation_euler_angles(); + const double err = vnl_vector_ssd(euler, out); avg_sqr_error += err; if (err > 1e-16) { @@ -71,8 +74,8 @@ test_random_euler_near_zero() std::cout << "ERROR: should be small: " << euler << ": " << quat << std::endl; } quat *= -1.0; - vnl_vector_fixed out = quat.rotation_euler_angles(); - double err = vnl_vector_ssd(euler, out); + const vnl_vector_fixed out = quat.rotation_euler_angles(); + const double err = vnl_vector_ssd(euler, out); avg_sqr_error += err; if (err > 1e-16) { @@ -97,7 +100,7 @@ test_random_quat_near_zero() vnl_math::sgn0(rng.normal()) * (1.0 + rng.normal() / 1000.0)); quat.normalize(); - vnl_vector_fixed euler = quat.rotation_euler_angles(); + const vnl_vector_fixed euler = quat.rotation_euler_angles(); if (euler.magnitude() > 0.01) { @@ -120,25 +123,25 @@ test_rotation_matrix_and_euler_angles() for (unsigned i = 0; i < ntrials; ++i) { bool this_trial_ok = true; - double x = rng.drand32(-1.0, 1.0); - double y = rng.drand32(-1.0, 1.0); - double z = rng.drand32(-1.0, 1.0); + const double x = rng.drand32(-1.0, 1.0); + const double y = rng.drand32(-1.0, 1.0); + const double z = rng.drand32(-1.0, 1.0); vnl_vector_fixed axis(x, y, z); axis.normalize(); - double ang = rng.drand32(-4 * vnl_math::pi, 4 * vnl_math::pi); + const double ang = rng.drand32(-4 * vnl_math::pi, 4 * vnl_math::pi); // Construct the quaternion from this axis and angle, // and extract both euler_angles and rotation matrix. - vnl_quaternion q(axis, ang); + const vnl_quaternion q(axis, ang); vnl_vector_fixed eu = q.rotation_euler_angles(); - vnl_matrix_fixed R = (q.rotation_matrix_transpose()).transpose(); + const vnl_matrix_fixed R = (q.rotation_matrix_transpose()).transpose(); // Use vnl_rotation_matrix() with axis+angle form { - vnl_vector_fixed axis_ang = axis * ang; - vnl_matrix_fixed M = vnl_rotation_matrix(axis_ang); - vnl_matrix_fixed D = R - M; - double max_err = D.absolute_value_max(); + const vnl_vector_fixed axis_ang = axis * ang; + const vnl_matrix_fixed M = vnl_rotation_matrix(axis_ang); + const vnl_matrix_fixed D = R - M; + const double max_err = D.absolute_value_max(); this_trial_ok = this_trial_ok && (max_err <= dtol); #ifndef NDEBUG if (max_err > dtol) @@ -150,7 +153,9 @@ test_rotation_matrix_and_euler_angles() // Use vnl_rotation_matrix() with euler angles. { - vnl_vector ex(3), ey(3), ez(3); + vnl_vector ex(3); + vnl_vector ey(3); + vnl_vector ez(3); ex[0] = 1.0; ex[1] = 0.0; ex[2] = 0.0; @@ -163,12 +168,12 @@ test_rotation_matrix_and_euler_angles() ex *= eu[0]; ey *= eu[1]; ez *= eu[2]; - vnl_matrix Rx = vnl_rotation_matrix(ex); - vnl_matrix Ry = vnl_rotation_matrix(ey); - vnl_matrix Rz = vnl_rotation_matrix(ez); - vnl_matrix M = Rz * Ry * Rx; - vnl_matrix D = R - M; - double max_err = D.absolute_value_max(); + const vnl_matrix Rx = vnl_rotation_matrix(ex); + const vnl_matrix Ry = vnl_rotation_matrix(ey); + const vnl_matrix Rz = vnl_rotation_matrix(ez); + const vnl_matrix M = Rz * Ry * Rx; + const vnl_matrix D = R - M; + const double max_err = D.absolute_value_max(); this_trial_ok = this_trial_ok && (max_err <= dtol); #ifndef NDEBUG if (max_err > dtol) @@ -187,36 +192,38 @@ test_rotation_matrix_and_euler_angles() static void test_rotations() { - vnl_vector_fixed p1(2, 2, 2), p2(1, 0, 0), p3(0, 1, 0); - vnl_vector_fixed e0(0, 0, 0); - vnl_quaternion q0(0, 0, 0, 0); + const vnl_vector_fixed p1(2, 2, 2); + const vnl_vector_fixed p2(1, 0, 0); + const vnl_vector_fixed p3(0, 1, 0); + const vnl_vector_fixed e0(0, 0, 0); + const vnl_quaternion q0(0, 0, 0, 0); TEST_NEAR("rotate p1 using q0", vnl_vector_ssd(q0.rotate(p1), p1), 0.0, 1e-8); TEST_NEAR("rotate p2 using q0", vnl_vector_ssd(q0.rotate(p2), p2), 0.0, 1e-8); - vnl_quaternion q0_b(0, 0, 0, 1); + const vnl_quaternion q0_b(0, 0, 0, 1); TEST_NEAR("rotate p1 using q0_b", vnl_vector_ssd(q0_b.rotate(p1), p1), 0.0, 1e-8); TEST_NEAR("rotate p2 using q0_b", vnl_vector_ssd(q0_b.rotate(p2), p2), 0.0, 1e-8); TEST_NEAR("q0_b -> Euler angles", vnl_vector_ssd(q0_b.rotation_euler_angles(), e0), 0.0, 1e-8); std::cout << "q0_b -> Euler angles: " << q0_b.rotation_euler_angles() << std::endl; - vnl_quaternion q0_c(0, 0, 0, -4); + const vnl_quaternion q0_c(0, 0, 0, -4); TEST_NEAR("rotate p1 using q0_c", vnl_vector_ssd(q0_c.rotate(p1), p1), 0.0, 1e-8); TEST_NEAR("rotate p2 using q0_c", vnl_vector_ssd(q0_c.rotate(p2), p2), 0.0, 1e-8); - vnl_quaternion q0_d(0, 0, 0); + const vnl_quaternion q0_d(0, 0, 0); TEST_NEAR("rotate p1 using q0_d", vnl_vector_ssd(q0_d.rotate(p1), p1), 0.0, 1e-8); TEST_NEAR("rotate p2 using q0_d", vnl_vector_ssd(q0_d.rotate(p2), p2), 0.0, 1e-8); // The axis replacing rotation - i.e. 120 degrees about (1,1,1) vnl_vector_fixed e1(vnl_math::pi / 2, 0, vnl_math::pi / 2); - vnl_quaternion q1(p1 / p1.magnitude(), vnl_math::twopi / 3.0); + const vnl_quaternion q1(p1 / p1.magnitude(), vnl_math::twopi / 3.0); TEST_NEAR("rotate p1 using q1", vnl_vector_ssd(q1.rotate(p1), p1), 0.0, 1e-8); TEST_NEAR("rotate p2 using q1", vnl_vector_ssd(q1.rotate(p2), p3), 0.0, 1e-8); - vnl_vector_fixed e1_b = q1.rotation_euler_angles(); + const vnl_vector_fixed e1_b = q1.rotation_euler_angles(); TEST_NEAR("q1 -> Euler angles", vnl_vector_ssd(e1_b, e1), 0.0, 1e-8); - vnl_quaternion q1_c = -q1; - vnl_vector_fixed e1_c = q1_c.rotation_euler_angles(); + const vnl_quaternion q1_c = -q1; + const vnl_vector_fixed e1_c = q1_c.rotation_euler_angles(); TEST_NEAR("-q1 -> Euler angles", vnl_vector_ssd(e1_c, e1), 0.0, 1e-8); std::cout << "q1 -> Euler angles: " << e1 << std::endl; - vnl_quaternion q1_b(e1(0), e1(1), e1(2)); + const vnl_quaternion q1_b(e1(0), e1(1), e1(2)); std::cout << "q1 -> Euler angles: " << q1_b << std::endl; TEST_NEAR("Euler angles -> q1", vnl_vector_ssd(q1_b, q1), 0.0, 1e-8); diff --git a/core/vnl/tests/test_random.cxx b/core/vnl/tests/test_random.cxx index ac2d84aabcf..c4581319741 100644 --- a/core/vnl/tests/test_random.cxx +++ b/core/vnl/tests/test_random.cxx @@ -16,17 +16,17 @@ test_random() TEST("lrand32", mz_random.lrand32(), 3501493769ul); TEST("lrand32(0,10)", mz_random.lrand32(0, 10), 9); - double d1 = mz_random.drand32(0, 1); + const double d1 = mz_random.drand32(0, 1); TEST_NEAR("drand32(0,1)", d1, 0.6158541, 1e-7); - double d2 = mz_random.drand64(0, 1); + const double d2 = mz_random.drand64(0, 1); TEST_NEAR("drand64(0,1)", d2, 0.2257411, 1e-7); double sum = 0.0; double sum_sq = 0.0; - int n = 10000; + const int n = 10000; for (int i = 0; i < n; ++i) { - double r = mz_random.normal(); + const double r = mz_random.normal(); sum += r; sum_sq += r * r; } @@ -40,7 +40,7 @@ test_random() sum_sq = 0.0; for (int i = 0; i < n; ++i) { - double r = mz_random.normal64(); + const double r = mz_random.normal64(); sum += r; sum_sq += r * r; } diff --git a/core/vnl/tests/test_rational.cxx b/core/vnl/tests/test_rational.cxx index b0e817b86f3..1d9c7cb438f 100644 --- a/core/vnl/tests/test_rational.cxx +++ b/core/vnl/tests/test_rational.cxx @@ -16,7 +16,7 @@ inline vnl_rational vnl_sqrt(vnl_rational x) { - return vnl_rational(std::sqrt(double(x))); + return { std::sqrt(double(x)) }; } namespace @@ -101,23 +101,27 @@ test_converting_constructors() static void test_operators() { - vnl_rational a(-5L), b(7, -1), c, d(3, 7), e(2, 0); - vnl_rational z_default; + vnl_rational a(-5L); + const vnl_rational b(7, -1); + vnl_rational c; + vnl_rational d(3, 7); + const vnl_rational e(2, 0); + const vnl_rational z_default; TEST("==", z_default == 0L, true); - vnl_rational z_int(static_cast(0)); + const vnl_rational z_int(static_cast(0)); TEST("==", z_int == 0L, true); - vnl_rational z_uint(static_cast(0)); + const vnl_rational z_uint(static_cast(0)); TEST("==", z_uint == 0L, true); - vnl_rational z_short(static_cast(0)); + const vnl_rational z_short(static_cast(0)); TEST("==", z_short == 0L, true); - vnl_rational z_ushort(static_cast(0)); + const vnl_rational z_ushort(static_cast(0)); TEST("==", z_ushort == 0L, true); - vnl_rational z_long(static_cast(0)); + const vnl_rational z_long(static_cast(0)); TEST("==", z_long == 0L, true); - vnl_rational z_ulong(static_cast(0)); + const vnl_rational z_ulong(static_cast(0)); TEST("==", z_ulong == 0L, true); #if 0 vnl_rational z_mixed(static_cast(0), static_cast(1) ); @@ -235,17 +239,22 @@ test_infinite() static void test_frac() { - vnl_rational r(-15, -20), s(1234321L, -1111111L), p; + vnl_rational r(-15, -20); + vnl_rational s(1234321L, -1111111L); TEST("vnl_math::isfinite", vnl_math::isfinite(r), true); TEST("vnl_math::isnan", vnl_math::isnan(r), false); TEST("simplify", r.numerator() == 3 && r.denominator() == 4, true); TEST("sign in numerator", s.numerator() == -1234321L && s.denominator() == 1111111L, true); // All 5-digit numbers below are prime numbers, and small enough so that the multiplications in the constructors do // not overflow - long p1 = 46309L, p2 = 46349L, p3 = 46327L, p4 = 46337L, p5 = 46351L; + const long p1 = 46309L; + const long p2 = 46349L; + const long p3 = 46327L; + const long p4 = 46337L; + const long p5 = 46351L; r = vnl_rational(p1 * p2, p3 * p4); s = vnl_rational(p3 * p4, p1 * p5); - p = r * s; + vnl_rational p = r * s; TEST("large multiplication without overflow", p.numerator() == p2 && p.denominator() == p5, true); r = vnl_rational(p1 * p2, p3 * p4); s = vnl_rational(p1 * p5, p3 * p4); @@ -265,18 +274,26 @@ test_frac() static void test_long_64() { - long l1 = 1234321234321L, l2 = 2 * l1, l3 = 123456787654321L, l4 = l3 + 1; - vnl_rational r(-l1, -l2) /* denom = 2*num */, s(l3, -l4) /* relatively prime */, p; + const long l1 = 1234321234321L; + const long l2 = 2 * l1; + const long l3 = 123456787654321L; + const long l4 = l3 + 1; + vnl_rational r(-l1, -l2) /* denom = 2*num */; + vnl_rational s(l3, -l4) /* relatively prime */; TEST("vnl_math::isfinite", vnl_math::isfinite(r), true); TEST("vnl_math::isnan", vnl_math::isnan(s), false); TEST("simplify", r.numerator() == 1 && r.denominator() == 2, true); TEST("sign in numerator", s.numerator() == -l3 && s.denominator() == l4, true); // The 10-digit numbers below are prime numbers, and small enough so that the multiplications in the constructors do // not overflow (at least, on systems where "long" is 64 bit) - long p1 = 1999999117L, p2 = 1999999121L, p3 = 1999999151L, p4 = 1999999171L, p5 = 1999999207L; + const long p1 = 1999999117L; + const long p2 = 1999999121L; + const long p3 = 1999999151L; + const long p4 = 1999999171L; + const long p5 = 1999999207L; r = vnl_rational(p1 * p2, p3 * p4); s = vnl_rational(p4 * p3, p1 * p5); - p = r * s; + vnl_rational p = r * s; TEST("large multiplication without overflow", p.numerator() == p2 && p.denominator() == p5, true); r = vnl_rational(p1 * p2, p3 * p4); s = vnl_rational(p1 * p5, p4 * p3); @@ -304,7 +321,7 @@ test_approx() TEST("construct from double", d, vnl_rational(3, 7)); d = vnl_rational(-1.23456); TEST("construct from double", d, vnl_rational(-123456, 100000)); - vnl_rational pi = vnl_rational(vnl_math::pi); + const vnl_rational pi = vnl_rational(vnl_math::pi); auto pi_a = double(pi); TEST("pi", pi_a - vnl_math::pi < 1e-18 && vnl_math::pi - pi_a < 1e-18, true); std::cout << "Best rational approximation of pi: " << pi << " = " << pi_a << '\n' @@ -334,7 +351,8 @@ test_sqrt() vnl_rational d(16, 9); TEST("sqrt", vnl_sqrt(d), vnl_rational(4, 3)); d = vnl_sqrt(vnl_rational(2L)); - double sqrt2 = std::sqrt(2.0), sqrt_2 = double(d); + const double sqrt2 = std::sqrt(2.0); + const double sqrt_2 = double(d); std::cout << "Best rational approximation of sqrt(2): " << d << " = " << sqrt_2 << '\n' << "Compare this with sqrt(2) in 20 decimals: " << sqrt2 << std::endl; TEST("sqrt(2)", sqrt2 - sqrt_2 < 1e-18 && sqrt_2 - sqrt2 < 1e-18, true); @@ -343,10 +361,10 @@ test_sqrt() static void test_zero_one() { - vnl_rational n = vnl_numeric_traits::zero; + const vnl_rational n = vnl_numeric_traits::zero; std::cout << "zero = " << n << '\n'; TEST("zero", n, 0L); - vnl_rational u = vnl_numeric_traits::one; + const vnl_rational u = vnl_numeric_traits::one; std::cout << "one = " << u << '\n'; TEST("one", u, 1L); } diff --git a/core/vnl/tests/test_real_npolynomial.cxx b/core/vnl/tests/test_real_npolynomial.cxx index 2fd934d07a8..4be7831dbae 100644 --- a/core/vnl/tests/test_real_npolynomial.cxx +++ b/core/vnl/tests/test_real_npolynomial.cxx @@ -6,7 +6,9 @@ void test_real_npolynomial() { - vnl_vector coef_0(3), coef_1(3), coef_2(4); + vnl_vector coef_0(3); + vnl_vector coef_1(3); + vnl_vector coef_2(4); for (unsigned int i = 0; i < 3; ++i) coef_0(i) = i + 1.0; // f0 = X + 2Y + 3Z for (unsigned int i = 0; i < 3; ++i) @@ -14,7 +16,9 @@ test_real_npolynomial() for (unsigned int i = 0; i < 4; ++i) coef_2(i) = 2 * i + 1.0; // f2 = X^3 + 3X^2Y + 5XY^2 + 7Y^3 - vnl_matrix expo_0(3, 3, 0U), expo_1(3, 2, 0U), expo_2(4, 2, 0U); + vnl_matrix expo_0(3, 3, 0U); + vnl_matrix expo_1(3, 2, 0U); + vnl_matrix expo_2(4, 2, 0U); for (unsigned int i = 0; i < 3; ++i) expo_0(i, i) = 1; expo_1(0, 0) = 2; @@ -23,7 +27,9 @@ test_real_npolynomial() for (unsigned int i = 0; i < 4; ++i) expo_2(i, 1) = expo_2(3 - i, 0) = i; - vnl_real_npolynomial f0(coef_0, expo_0), f1(coef_1, expo_1), f2(coef_2, expo_2); + const vnl_real_npolynomial f0(coef_0, expo_0); + vnl_real_npolynomial f1(coef_1, expo_1); + vnl_real_npolynomial f2(coef_2, expo_2); std::cout << "f0 = " << f0 << "f1 = " << f1 << "f2 = " << f2; TEST("f0 has total degree 1", f0.degree(), 1); diff --git a/core/vnl/tests/test_real_polynomial.cxx b/core/vnl/tests/test_real_polynomial.cxx index 9611bc10721..42453d79793 100644 --- a/core/vnl/tests/test_real_polynomial.cxx +++ b/core/vnl/tests/test_real_polynomial.cxx @@ -17,7 +17,7 @@ test_real_polynomial() { std::stringstream testStream; f1.print(testStream); - std::string expected = " X^3 +2 X^2 +3 X +4"; + const std::string expected = " X^3 +2 X^2 +3 X +4"; TEST("f1 prints as X^3 +2 X^2 +3 X +4", testStream.str(), expected); std::cout << "Actual:\t\t\"" << testStream.str() << '"' << std::endl << "Expected:\t\"" << expected << '"' << std::endl; @@ -28,18 +28,18 @@ test_real_polynomial() f2.print(std::cout); std::cout << std::endl; - vnl_real_polynomial f3 = f1 + f2; + const vnl_real_polynomial f3 = f1 + f2; f3.print(std::cout); std::cout << std::endl; TEST("f1+f2=f3", f1.evaluate(2.5) + f2.evaluate(2.5), f3.evaluate(2.5)); // Evaluating in 2.5 is exact, since 2.5 is exactly representable (binary 10.1) - vnl_real_polynomial f4 = f1 - f2; + const vnl_real_polynomial f4 = f1 - f2; f4.print(std::cout); std::cout << std::endl; TEST("f1-f2=f4", f1.evaluate(2.5) - f2.evaluate(2.5), f4.evaluate(2.5)); - vnl_real_polynomial f5 = f1 * f2; + const vnl_real_polynomial f5 = f1 * f2; f5.print(std::cout); std::cout << std::endl; @@ -47,16 +47,16 @@ test_real_polynomial() TEST("f1*f2=f5", f1.evaluate(2.5) * f2.evaluate(2.5), f5.evaluate(2.5)); - vnl_real_polynomial f1d = f1.derivative(); + const vnl_real_polynomial f1d = f1.derivative(); f1d.print(std::cout); std::cout << std::endl; - vnl_real_polynomial f2d = f2.derivative(); + const vnl_real_polynomial f2d = f2.derivative(); f2d.print(std::cout); std::cout << std::endl; TEST("Derivative", f5.derivative(), f1d * f2 + f2d * f1); - vnl_real_polynomial f5p = (f1d * f2 + f2d * f1).primitive(); + const vnl_real_polynomial f5p = (f1d * f2 + f2d * f1).primitive(); f5p.print(std::cout); std::cout << std::endl; @@ -66,7 +66,7 @@ test_real_polynomial() TEST("Polynomial of degree 0", vnl_real_polynomial(1.0).evaluate(0.5), 1.0); double v_data[] = { 3.0, 2.0, 1.0 }; - vnl_vector v(v_data, 3); + const vnl_vector v(v_data, 3); TEST("Vector initialisation", vnl_real_polynomial(v).evaluate(2.0), 17.0); TEST_NEAR("RMS difference(f1,f2)", vnl_rms_difference(f1, f1, 0, 1), 0.0, 1e-9); @@ -76,7 +76,7 @@ test_real_polynomial() { std::stringstream testStream; f6.print(testStream); - std::string expected = " X +1"; + const std::string expected = " X +1"; TEST("f6 prints as X +1", testStream.str(), expected); std::cout << "Actual:\t\t\"" << testStream.str() << '"' << std::endl << "Expected:\t\"" << expected << '"' << std::endl; @@ -88,7 +88,7 @@ test_real_polynomial() { std::stringstream testStream; f7.print(testStream); - std::string expected = " X -1"; + const std::string expected = " X -1"; TEST("f7 prints as X -1", testStream.str(), expected); std::cout << "Actual:\t\t\"" << testStream.str() << '"' << std::endl << "Expected:\t\"" << expected << '"' << std::endl; @@ -100,7 +100,7 @@ test_real_polynomial() { std::stringstream testStream; f8.print(testStream); - std::string expected = " 0"; + const std::string expected = " 0"; TEST("f8 prints as 0", testStream.str(), expected); std::cout << "Actual:\t\t\"" << testStream.str() << '"' << std::endl << "Expected:\t\"" << expected << '"' << std::endl; diff --git a/core/vnl/tests/test_rotation_matrix.cxx b/core/vnl/tests/test_rotation_matrix.cxx index 21b6d5e1cc5..ce36ff02cd7 100644 --- a/core/vnl/tests/test_rotation_matrix.cxx +++ b/core/vnl/tests/test_rotation_matrix.cxx @@ -47,8 +47,8 @@ get_rotation_matrix_euler_angle(const double phi, const CartAxis axis, vnl_matri if (std::fabs(phi) < std::numeric_limits::epsilon()) return; - double cos_phi = std::cos(phi); - double sin_phi = std::sin(phi); + const double cos_phi = std::cos(phi); + const double sin_phi = std::sin(phi); switch (axis) { @@ -83,15 +83,15 @@ get_rotation_matrix_euler_angle(const double phi, const CartAxis axis, vnl_matri static bool calc_and_test_matrix(const vnl_vector & axis, const vnl_matrix_fixed & M) { - vnl_matrix R = vnl_rotation_matrix(axis); + const vnl_matrix R = vnl_rotation_matrix(axis); // Check that rotation matrix is 3x3 bool success = (3 == R.rows() && 3 == R.cols()); if (!success) return false; - vnl_matrix D = R - M; - double max_err = D.absolute_value_max(); + const vnl_matrix D = R - M; + const double max_err = D.absolute_value_max(); // Check that rotation matrix is correct within a tolerance success = success && (max_err <= dtol); @@ -118,7 +118,7 @@ test_euler_rotations() for (unsigned i = 0; i < ntrials; ++i) { bool this_trial_ok = true; - double ang = randgen.drand32(-4 * vnl_math::pi, 4 * vnl_math::pi); + const double ang = randgen.drand32(-4 * vnl_math::pi, 4 * vnl_math::pi); vnl_vector axis(3); // The magnitude of this vector indicates the angle of rotation vnl_matrix_fixed M; // True answer diff --git a/core/vnl/tests/test_sample.cxx b/core/vnl/tests/test_sample.cxx index 33380a85f9b..9e4f21f0aab 100644 --- a/core/vnl/tests/test_sample.cxx +++ b/core/vnl/tests/test_sample.cxx @@ -10,7 +10,7 @@ static void test_sample_uniform() { std::cout << "*************** sample uniform ***************\n"; - unsigned const N = 100000; + const unsigned N = 100000; double a = 123.456; double b = 543.210; vnl_sample_reseed(); // initialise the random seed in a random way @@ -59,7 +59,7 @@ static void test_sample_normal() { std::cout << "*************** sample normal ***************\n"; - unsigned const N = 100000; + const unsigned N = 100000; double mu = 1.552; double sigma = 3.729; vnl_sample_reseed(); // initialise the random seed in a random way @@ -108,7 +108,7 @@ static void test_sample_binomial() { std::cout << "*************** sample binomial ***************\n"; - unsigned const N = 100000; + const unsigned N = 100000; int n = 10; double p = 0.4; vnl_sample_reseed(); // initialise the random seed in a random way @@ -148,7 +148,7 @@ static void test_sample_bernoulli() { std::cout << "*************** sample Bernoulli ***************\n"; - unsigned const N = 100000; + const unsigned N = 100000; double p = 0.7; vnl_sample_reseed(); // initialise the random seed in a random way diff --git a/core/vnl/tests/test_sparse_lst_sqr_function.cxx b/core/vnl/tests/test_sparse_lst_sqr_function.cxx index 4a3378e5ec8..00b0cb1eea1 100644 --- a/core/vnl/tests/test_sparse_lst_sqr_function.cxx +++ b/core/vnl/tests/test_sparse_lst_sqr_function.cxx @@ -18,9 +18,9 @@ class test_func1 : public vnl_sparse_lst_sqr_function void fij(int /*i*/, int /*j*/, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & c, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, vnl_vector & eij) override { eij[0] = (ai[0] * ai[0] - bj[0] * ai[1]) * bj[2] * bj[2] * bj[2] + c[0] * ai[0]; @@ -30,9 +30,9 @@ class test_func1 : public vnl_sparse_lst_sqr_function void jac_Aij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & c, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, vnl_matrix & Aij) override { Aij[0][0] = 2.0 * ai[0] * bj[2] * bj[2] * bj[2] + c[0]; @@ -44,9 +44,9 @@ class test_func1 : public vnl_sparse_lst_sqr_function void jac_Bij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & /*c*/, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & /*c*/, vnl_matrix & Bij) override { Bij[0][0] = -ai[1] * bj[2] * bj[2] * bj[2]; @@ -60,9 +60,9 @@ class test_func1 : public vnl_sparse_lst_sqr_function void jac_Cij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & ai, - vnl_vector const & /*bj*/, - vnl_vector const & /*c*/, + const vnl_vector & ai, + const vnl_vector & /*bj*/, + const vnl_vector & /*c*/, vnl_matrix & Cij) override { Cij[0][0] = ai[0]; @@ -74,10 +74,10 @@ class test_func1 : public vnl_sparse_lst_sqr_function void compute_weight_ij(int i, int j, - vnl_vector const & /*ai*/, - vnl_vector const & /*bj*/, - vnl_vector const & /*c*/, - vnl_vector const & /*fij*/, + const vnl_vector & /*ai*/, + const vnl_vector & /*bj*/, + const vnl_vector & /*c*/, + const vnl_vector & /*fij*/, double & weight) override { weight = double((i + 1) * (j + 1)) / (this->number_of_a() * this->number_of_b()); @@ -88,7 +88,7 @@ class test_func1 : public vnl_sparse_lst_sqr_function static void test_sparse_lst_sqr_function() { - std::vector null_row(4, false); + const std::vector null_row(4, false); std::vector> mask(3, null_row); // |1 1 0 0| @@ -142,7 +142,10 @@ test_sparse_lst_sqr_function() TEST("number_of_residuals", num_valid, true); TEST("index_e", index_valid, true); - vnl_vector ai(2), bj(3), c(2), e(2); + vnl_vector ai(2); + vnl_vector bj(3); + vnl_vector c(2); + vnl_vector e(2); ai[0] = 5.0; ai[1] = -1.0; bj[0] = 1.2; @@ -154,8 +157,12 @@ test_sparse_lst_sqr_function() my_func.fij(0, 0, ai, bj, c, e); std::cout << "e = " << e << std::endl; - vnl_matrix Aij(2, 2), Bij(2, 3), Cij(2, 2); - vnl_matrix fd_Aij(2, 2), fd_Bij(2, 3), fd_Cij(2, 2); + vnl_matrix Aij(2, 2); + vnl_matrix Bij(2, 3); + vnl_matrix Cij(2, 2); + vnl_matrix fd_Aij(2, 2); + vnl_matrix fd_Bij(2, 3); + vnl_matrix fd_Cij(2, 2); my_func.jac_Aij(0, 0, ai, bj, c, Aij); my_func.fd_jac_Aij(0, 0, ai, bj, c, fd_Aij, step); my_func.jac_Bij(0, 0, ai, bj, c, Bij); @@ -194,16 +201,18 @@ test_sparse_lst_sqr_function() // apply weights vnl_vector wf(f); - std::vector> wA(A), wB(B), wC(C); + std::vector> wA(A); + std::vector> wB(B); + std::vector> wC(C); my_func.apply_weights(weights, wf); my_func.apply_weights(weights, wA, wB, wC); - double w_norm = my_func.number_of_a() * my_func.number_of_b(); + const double w_norm = my_func.number_of_a() * my_func.number_of_b(); for (unsigned int i = 0; i < my_func.number_of_a(); ++i) { for (unsigned int j = 0; j < my_func.number_of_b(); ++j) { - int k = my_func.residual_indices()(i, j); + const int k = my_func.residual_indices()(i, j); if (k < 0) continue; TEST_NEAR("valid weights", weights[k], double((i + 1) * (j + 1)) / w_norm, 1e-10); diff --git a/core/vnl/tests/test_sparse_matrix.cxx b/core/vnl/tests/test_sparse_matrix.cxx index 39ef19e38a2..0286a85ace2 100644 --- a/core/vnl/tests/test_sparse_matrix.cxx +++ b/core/vnl/tests/test_sparse_matrix.cxx @@ -18,7 +18,7 @@ test_sparse_int() TEST("(vnl_sparse_matrix)(i,j)", m0(1111, 2222), 3333); const vnl_sparse_matrix ma = m0; TEST("copy constructor", ma, m0); - vnl_sparse_matrix m2(m1); + const vnl_sparse_matrix m2(m1); TEST("vnl_sparse_matrix m2(m1)", m1, m2); TEST("(const vnl_sparse_matrix)(i,j)", ma(1111, 2222), 3333); vnl_sparse_matrix mb; @@ -147,7 +147,7 @@ test_sparse_double() << "***********************************\n"; vnl_sparse_matrix d0(2, 2); TEST("vnl_sparse_matrix d0(2,2)", (d0.rows() == 2 && d0.columns() == 2), true); - vnl_sparse_matrix d1(3, 4); + const vnl_sparse_matrix d1(3, 4); TEST("vnl_sparse_matrix d1(3,4)", (d1.rows() == 3 && d1.columns() == 4), true); vnl_sparse_matrix d2 = d0; TEST("copy constructor", d0, d2); @@ -157,7 +157,7 @@ test_sparse_double() TEST("d2(1,0) = 4.0", d2(1, 0), 4.0); TEST("!(d0 == d2)", (d0 == d2), false); TEST("d0 != d2", (d0 != d2), true); - vnl_sparse_matrix d3(d2); + const vnl_sparse_matrix d3(d2); TEST("vnl_sparse_matrix d3(d2)", d2, d3); TEST("d0=d2", (d0 = d2, (d0 == d2)), true); @@ -183,12 +183,12 @@ test_sparse_complex() TEST("copy constructor", d0, d2); TEST("d2.put(1,1,3.0)", (d2.put(1, 1, 3.0), d2.get(1, 1)), 3.0); TEST("d2.get(1,1)", d2.get(1, 1), 3.0); - std::complex r4i12(4.0, 12.0); + const std::complex r4i12(4.0, 12.0); d2(1, 0) = r4i12; TEST("d2(1,0) = 4+12i", d2(1, 0), r4i12); TEST("!(d0 == d2)", (d0 == d2), false); TEST("d0 != d2", (d0 != d2), true); - vnl_sparse_matrix> d3(d2); + const vnl_sparse_matrix> d3(d2); TEST("vnl_sparse_matrix d3(d2)", d2, d3); TEST("assignment operator", (d0 = d2, (d0 == d2)), true); diff --git a/core/vnl/tests/test_sym_matrix.cxx b/core/vnl/tests/test_sym_matrix.cxx index 55745bda8aa..8d61d2e4fec 100644 --- a/core/vnl/tests/test_sym_matrix.cxx +++ b/core/vnl/tests/test_sym_matrix.cxx @@ -14,7 +14,12 @@ test_int() // CONSTRUCTORS // ////////////////// +#if VNL_CONFIG_CHECK_BOUNDS + // ssm1 must be mutable for VNL_CONFIG_CHECK_BOUNDS vnl_sym_matrix sm1(2); +#else + const vnl_sym_matrix sm1(2); +#endif TEST("\n\nvnl_sym_matrix m1(2)", (sm1.rows() == 2 && sm1.columns() == 2), true); vnl_sym_matrix sm2(2, 2); TEST( @@ -59,7 +64,7 @@ test_int() TEST("operator ==", (sm5 == sm6 && !(sm5 == sm4) && !(sm4 == sm3)), true); std::cout << "sm4 sm3\n" << sm4 << std::endl << sm3 << std::endl << std::endl; - vnl_vector v1(2, 5); + const vnl_vector v1(2, 5); sm5.set_half_row(v1, 1); TEST("set_half_row", (sm5(0, 0) == 0 && sm5(0, 1) == 5 && sm5(0, 2) == 0 && sm5(1, 0) == 5 && sm5(1, 1) == 5 && sm5(1, 2) == 2 && diff --git a/core/vnl/tests/test_transpose.cxx b/core/vnl/tests/test_transpose.cxx index 6f00e005dd6..1669a8c8603 100644 --- a/core/vnl/tests/test_transpose.cxx +++ b/core/vnl/tests/test_transpose.cxx @@ -13,7 +13,7 @@ test_transpose() for (unsigned int j = 0; j < X.cols(); ++j) X[i][j] = (i + 1) * 3 + (j + 1) * (j + i); - vnl_matrix old_X(X); + const vnl_matrix old_X(X); vnl_matlab_print(std::cout, X, "X"); diff --git a/core/vnl/tests/test_vector.cxx b/core/vnl/tests/test_vector.cxx index 7a1d4b3d423..9f199af103a 100644 --- a/core/vnl/tests/test_vector.cxx +++ b/core/vnl/tests/test_vector.cxx @@ -1,6 +1,7 @@ // This is core/vnl/tests/test_vector.cxx #include #include +#include #include "vnl/vnl_math.h" #include "vnl/vnl_vector.h" #include "vnl/vnl_float_3.h" @@ -18,13 +19,13 @@ test_common_interface() const typename TContainer::element_type l_values[4] = { 0, 1, 2, 3 }; TContainer l(4, 4, l_values); - TEST("l.front()", l.front() , 0); - TEST("l.back()", l.back() , 3); + TEST("l.front()", l.front(), 0); + TEST("l.back()", l.back(), 3); const TContainer l_const(4, 4, l_values); - TEST("l_const.front()", l_const.front() , 0); - TEST("l_const.back()", l_const.back() , 3); + TEST("l_const.front()", l_const.front(), 0); + TEST("l_const.back()", l_const.back(), 3); TContainer l_swap(l); TContainer l_std_swap(l); @@ -41,7 +42,6 @@ test_common_interface() std::swap(l_std_swap, r_std_swap); TEST("std::swap left-right", l.is_equal(r_std_swap, 10e-6), true); TEST("std::swap right-left", r.is_equal(l_std_swap, 10e-6), true); - } @@ -186,7 +186,7 @@ vnl_vector_test_int() int v3values[] = { 0, 0, 1 }; vnl_vector v1(3, 3, v1values); vnl_vector v2(3, 3, v2values); - vnl_vector v3(3, 3, v3values); + const vnl_vector v3(3, 3, v3values); TEST( "dot_product(v1,v2)", (dot_product(v1, v2) == 0 && dot_product(v1, v3) == 0 && dot_product(v2, v3) == 0), true); TEST( @@ -195,7 +195,7 @@ vnl_vector_test_int() TEST("vnl_cross_3d(v1,v2)", vnl_cross_3d(v1, v2), v3); TEST("vnl_cross_3d(v2,v3)", vnl_cross_3d(v2, v3), v1); TEST("vnl_cross_3d(v1,v3)", vnl_cross_3d(v1, v3), -v2); - vnl_vector vv(2, 0); + const vnl_vector vv(2, 0); v1 = vv; v1[0] = 1; v2 = vv; @@ -205,7 +205,7 @@ vnl_vector_test_int() { int vvalues[] = { 1, 2, 3 }; - vnl_vector v(3, 3, vvalues); + const vnl_vector v(3, 3, vvalues); vnl_matrix m = outer_product(v, v); TEST("outer_product", (m(0, 0) == 1 && m(0, 1) == 2 && m(0, 2) == 3 && m(1, 0) == 2 && m(1, 1) == 4 && m(1, 2) == 6 && @@ -214,7 +214,7 @@ vnl_vector_test_int() } { int vvalues[] = { 1, 0, 0, 0 }; - vnl_vector v(4, 4, vvalues); + const vnl_vector v(4, 4, vvalues); TEST("v.squared_magnitude", (v.squared_magnitude() == 1), true); TEST("v.magnitude", (v.magnitude() == 1), true); // normalize not sensible for ints @@ -245,7 +245,7 @@ vnl_vector_test_int() { int vvalues[] = { 0, 1, 2, 3 }; - vnl_vector v(4, 4, vvalues); + const vnl_vector v(4, 4, vvalues); vnl_vector v_temp; // @@ -286,7 +286,7 @@ vnl_vector_test_int() { int vvalues[] = { 0, 1, 2, 3 }; vnl_vector v(4, 4, vvalues); - vnl_vector v_temp = v; + const vnl_vector v_temp = v; // // Check special cases @@ -319,33 +319,37 @@ vnl_vector_test_int() } { // test operator-() on unsigned values - unsigned int vvalues[] = {1, 2, 3, 4}; - int out_values[] = {-1, -2, -3, -4}; + unsigned int vvalues[] = { 1, 2, 3, 4 }; + const int out_values[] = { -1, -2, -3, -4 }; - vnl_vector unsigned_v(4, 4, vvalues); + const vnl_vector unsigned_v(4, 4, vvalues); const vnl_vector minus_v1 = -unsigned_v; const vnl_vector minus_v2 = unsigned_v.operator-(); TEST("unsigned_v.operator-()", (out_values[0] == minus_v1[0] && out_values[1] == minus_v1[1] && out_values[2] == minus_v1[2] && - out_values[3] == minus_v1[3]), true); + out_values[3] == minus_v1[3]), + true); TEST("unsigned_v.operator-()", (out_values[0] == minus_v2[0] && out_values[1] == minus_v2[1] && out_values[2] == minus_v2[2] && - out_values[3] == minus_v2[3]), true); + out_values[3] == minus_v2[3]), + true); } { // test operator-() on unsigned values - unsigned int vvalues[] = {1, 2, 3, 4}; - int out_values[] = {-1, -2, -3, -4}; + unsigned int vvalues[] = { 1, 2, 3, 4 }; + const int out_values[] = { -1, -2, -3, -4 }; - vnl_vector_fixed unsigned_v(vvalues); - const vnl_vector_fixed minus_v1 = -unsigned_v; - const vnl_vector_fixed minus_v2 = unsigned_v.operator-(); + const vnl_vector_fixed unsigned_v(vvalues); + const vnl_vector_fixed minus_v1 = -unsigned_v; + const vnl_vector_fixed minus_v2 = unsigned_v.operator-(); TEST("unsigned_v.operator-()", (out_values[0] == minus_v1[0] && out_values[1] == minus_v1[1] && out_values[2] == minus_v1[2] && - out_values[3] == minus_v1[3]), true); + out_values[3] == minus_v1[3]), + true); TEST("unsigned_v.operator-()", (out_values[0] == minus_v2[0] && out_values[1] == minus_v2[1] && out_values[2] == minus_v2[2] && - out_values[3] == minus_v2[3]), true); + out_values[3] == minus_v2[3]), + true); } { // test vnl_vector_fixed::is_equal using int_vector_fixed_type = vnl_vector_fixed; @@ -490,7 +494,7 @@ vnl_vector_test_float() TEST("vnl_cross_3d(v1,v2)", vnl_cross_3d(v1, v2), v3); TEST("vnl_cross_3d(v2,v3)", vnl_cross_3d(v2, v3), v1); TEST("vnl_cross_3d(v1,v3)", vnl_cross_3d(v1, v3), -v2); - vnl_vector vv(2, 0); + const vnl_vector vv(2, 0); v1 = vv; v1[0] = 1; v2 = vv; @@ -499,8 +503,8 @@ vnl_vector_test_float() } { - vnl_float_3 v(1.f, 2.f, 3.f); - vnl_float_4 v2(1.f, 2.f, 3.f, 4.f); + const vnl_float_3 v(1.f, 2.f, 3.f); + const vnl_float_4 v2(1.f, 2.f, 3.f, 4.f); vnl_matrix_fixed m = outer_product(v, v2); TEST("outer_product -> fixed 3 x fixed 4", (m(0, 0) == 1 && m(0, 1) == 2 && m(0, 2) == 3 && m(0, 3) == 4 && m(1, 0) == 2 && m(1, 1) == 4 && @@ -654,11 +658,13 @@ void vnl_vector_test_matrix() { int mvalues[] = { 1, 2, 3, 4, 5, 6 }; // product with matrices - vnl_matrix m(2, 3, 6, mvalues); + const vnl_matrix m(2, 3, 6, mvalues); int v2values[] = { 1, 0 }; int v3values[] = { 1, 0, 0 }; - vnl_vector v, v2(2, 2, v2values), v3(3, 3, v3values); + vnl_vector v; + const vnl_vector v2(2, 2, v2values); + const vnl_vector v3(3, 3, v3values); TEST("v.pre_multiply(m)", ((v = v3), (v.pre_multiply(m)), (v.size() == 2 && v(0) == 1 && v(1) == 4)), true); TEST("v.post_multiply(m)", ((v = v2), (v.post_multiply(m)), (v.size() == 3 && v(0) == 1 && v(1) == 2 && v(2) == 3)), @@ -723,7 +729,7 @@ static void vnl_vector_test_io() { double expected_data[] = { 1.0, 2.0, 3.0 }; - vnl_vector expected(expected_data, 3); + const vnl_vector expected(expected_data, 3); { std::stringstream ss; ss << ""; diff --git a/core/vnl/tests/test_vector_fixed_ref.cxx b/core/vnl/tests/test_vector_fixed_ref.cxx index ddbd56da737..c090fa7ec24 100644 --- a/core/vnl/tests/test_vector_fixed_ref.cxx +++ b/core/vnl/tests/test_vector_fixed_ref.cxx @@ -12,7 +12,7 @@ test_vector_fixed_ref() const double numbers[4]{ 0, 11, 22, 33 }; vnl_vector v{ numbers, 4 }; // vnl_vector_ref(numbers, 4); // Should fail to compile due to const double numbers - vnl_vector_ref memory_access_vnl_ref{ v.size(), v.data_block() }; + const vnl_vector_ref memory_access_vnl_ref{ v.size(), v.data_block() }; const vnl_vector_ref const_cpprefvector{ memory_access_vnl_ref }; const_cpprefvector.as_ref(); @@ -23,7 +23,7 @@ test_vector_fixed_ref() { constexpr double bulk_data_array[4]{ 1.0, 2.0, 3.0, 4.0 }; vnl_vector_fixed initial_fixed_size_matrix(bulk_data_array); - vnl_vector_ref ref_to_data( initial_fixed_size_matrix.as_ref() ); + vnl_vector_ref ref_to_data(initial_fixed_size_matrix.as_ref()); TEST("vnl_vector_ref{ vnl_vector_fixed } share data pointer", initial_fixed_size_matrix.data_block() == ref_to_data.data_block(), @@ -47,15 +47,15 @@ test_vector_fixed_ref() constexpr size_t size = 4; { - vnl_vector_fixed test_front_back{11, 22, 33, 44}; - TEST("test_front_back.front()", test_front_back.front() , 11); - TEST("test_front_back.back()", test_front_back.back() , 44); + vnl_vector_fixed test_front_back{ 11, 22, 33, 44 }; + TEST("test_front_back.front()", test_front_back.front(), 11); + TEST("test_front_back.back()", test_front_back.back(), 44); } { - const vnl_vector_fixed test_front_back_const{11, 22, 33, 44}; - TEST("test_front_back_const.front()", test_front_back_const.front() , 11); - TEST("test_front_back_const.back()", test_front_back_const.back() , 44); + const vnl_vector_fixed test_front_back_const{ 11, 22, 33, 44 }; + TEST("test_front_back_const.front()", test_front_back_const.front(), 11); + TEST("test_front_back_const.back()", test_front_back_const.back(), 44); } typedef vnl_vector_fixed vf; @@ -74,7 +74,7 @@ test_vector_fixed_ref() // fixed_ref_const const vf & cvf = vec; - vfrc cref(cvf); + const vfrc cref(cvf); // check address for (i = 0; i < size; ++i) { @@ -84,7 +84,7 @@ test_vector_fixed_ref() // fixed_ref (non-const) // wrap around vec - vfr ref(vec); + const vfr ref(vec); // check address for (i = 0; i < size; ++i) { @@ -99,7 +99,7 @@ test_vector_fixed_ref() { // assign from const vfr std::generate(other.begin(), other.end(), std::rand); - vfrc cref(other); + const vfrc cref(other); ref = cref; TEST("assign_const_ref", ref, other); // test different addresses @@ -109,34 +109,40 @@ test_vector_fixed_ref() // arithmetic { // plus - vf a, b; + vf a; + vf b; std::generate(a.begin(), a.end(), std::rand); std::generate(b.begin(), b.end(), std::rand); - vfrc arefc(a), brefc(b); - vf mc = arefc + brefc; + const vfrc arefc(a); + const vfrc brefc(b); + const vf mc = arefc + brefc; - vfr aref(a), bref(b); - vf m = aref + bref; + const vfr aref(a); + const vfr bref(b); + const vf m = aref + bref; - vf m2 = arefc + bref; - vf m3 = arefc + brefc; + const vf m2 = arefc + bref; + const vf m3 = arefc + brefc; TEST("plus", mc, m); TEST("plus", mc, m2); TEST("plus", mc, m3); } { // times - vf a, b; + vf a; + vf b; std::generate(a.begin(), a.end(), std::rand); std::generate(b.begin(), b.end(), std::rand); - vfrc arefc(a), brefc(b); - vf mc = arefc + brefc; + const vfrc arefc(a); + const vfrc brefc(b); + const vf mc = arefc + brefc; - vfr aref(a), bref(b); - vf m = aref + bref; + const vfr aref(a); + const vfr bref(b); + const vf m = aref + bref; - vf m2 = arefc + bref; - vf m3 = arefc + brefc; + const vf m2 = arefc + bref; + const vf m3 = arefc + brefc; TEST("plus", mc, m); TEST("plus", mc, m2); TEST("plus", mc, m3); diff --git a/core/vnl/tests/test_vnl_index_sort.cxx b/core/vnl/tests/test_vnl_index_sort.cxx index 3a03937b7e8..7f675ff7da1 100644 --- a/core/vnl/tests/test_vnl_index_sort.cxx +++ b/core/vnl/tests/test_vnl_index_sort.cxx @@ -75,10 +75,10 @@ main(int argc, char * argv[]) return r; } -# define TEST(t, a, b) \ - if (a != b) \ - std::cerr << t << " FAILED.\n"; \ - else \ +# define TEST(t, a, b) \ + if (a != b) \ + std::cerr << t << " FAILED.\n"; \ + else \ std::cout << t << " check PASSED." << std::endl; # define TESTMAIN(x) // no-op diff --git a/core/vnl/vnl_T_n.h b/core/vnl/vnl_T_n.h index 6723718ae46..8cd3e7bce74 100644 --- a/core/vnl/vnl_T_n.h +++ b/core/vnl/vnl_T_n.h @@ -16,26 +16,63 @@ #include "vnl/vnl_export.h" //: cpp traits! -#define vnl_T_n_aux_1(T) (T x) { data_[0] = x; } static_assert(true, "") -#define vnl_T_n_aux_2(T) (T x, T y) { data_[0] = x; data_[1] = y; } static_assert(true, "") -#define vnl_T_n_aux_3(T) (T x, T y, T z) { data_[0] = x; data_[1] = y; data_[2] = z; } static_assert(true, "") -#define vnl_T_n_aux_4(T) (T x, T y, T z, T w) { data_[0] = x; data_[1] = y; data_[2] = z; data_[3] = w; } static_assert(true, "") -#define vnl_T_n_aux_5(T) (T x, T y, T z, T w, T u) { data_[0] = x; data_[1] = y; data_[2] = z; data_[3] = w; data_[4]= u; } static_assert(true, "") +#define vnl_T_n_aux_1(T) \ + (T x) { data_[0] = x; } \ + static_assert(true, "") +#define vnl_T_n_aux_2(T) \ + (T x, T y) \ + { \ + data_[0] = x; \ + data_[1] = y; \ + } \ + static_assert(true, "") +#define vnl_T_n_aux_3(T) \ + (T x, T y, T z) \ + { \ + data_[0] = x; \ + data_[1] = y; \ + data_[2] = z; \ + } \ + static_assert(true, "") +#define vnl_T_n_aux_4(T) \ + (T x, T y, T z, T w) \ + { \ + data_[0] = x; \ + data_[1] = y; \ + data_[2] = z; \ + data_[3] = w; \ + } \ + static_assert(true, "") +#define vnl_T_n_aux_5(T) \ + (T x, T y, T z, T w, T u) \ + { \ + data_[0] = x; \ + data_[1] = y; \ + data_[2] = z; \ + data_[3] = w; \ + data_[4] = u; \ + } \ + static_assert(true, "") //: this macro defines the class. // e.g. use vnl_T_n_impl(int,2) to implement class vnl_int_2. -#define vnl_T_n_class_impl(T,n) \ -class vnl_##T##_##n : public vnl_vector_fixed \ -{ \ - public: \ - vnl_##T##_##n() = default; \ - vnl_##T##_##n(vnl_vector const & rhs) : vnl_vector_fixed(rhs) { } \ - vnl_##T##_##n(vnl_vector_fixed const & rhs) : vnl_vector_fixed(rhs) { } \ - vnl_##T##_##n vnl_T_n_aux_##n(T); \ -} +#define vnl_T_n_class_impl(T, n) \ + class vnl_##T##_##n : public vnl_vector_fixed \ + { \ + public: \ + vnl_##T##_##n() = default; \ + vnl_##T##_##n(vnl_vector const & rhs) \ + : vnl_vector_fixed(rhs) \ + {} \ + vnl_##T##_##n(vnl_vector_fixed const & rhs) \ + : vnl_vector_fixed(rhs) \ + {} \ + vnl_##T##_##n vnl_T_n_aux_##n(T); \ + } //: clients use this. -#define vnl_T_n_impl(T,n); \ -vnl_T_n_class_impl(T,n); +#define vnl_T_n_impl(T, n) \ + ; \ + vnl_T_n_class_impl(T, n); #endif // vnl_T_n_h_ diff --git a/core/vnl/vnl_alloc.cxx b/core/vnl/vnl_alloc.cxx index 6668cc141d8..ecd4cad18ee 100644 --- a/core/vnl/vnl_alloc.cxx +++ b/core/vnl/vnl_alloc.cxx @@ -10,7 +10,7 @@ vnl_alloc::chunk_alloc(std::size_t size, int & nobjs) { char * result; std::size_t total_bytes = size * nobjs; - std::size_t bytes_left = end_free - start_free; + const std::size_t bytes_left = end_free - start_free; if (bytes_left >= total_bytes) { @@ -28,7 +28,7 @@ vnl_alloc::chunk_alloc(std::size_t size, int & nobjs) } else { - std::size_t bytes_to_get = 2 * total_bytes + ROUND_UP(heap_size >> 4); + const std::size_t bytes_to_get = 2 * total_bytes + ROUND_UP(heap_size >> 4); // Try to make use of the left-over piece. if (bytes_left > 0) { @@ -39,14 +39,13 @@ vnl_alloc::chunk_alloc(std::size_t size, int & nobjs) start_free = (char *)std::malloc(bytes_to_get); if (nullptr == start_free) { - obj **my_free_list, *p; // Try to make do with what we have. That can't // hurt. We do not try smaller requests, since that tends // to result in disaster on multi-process machines. for (std::size_t i = size; i <= VNL_ALLOC_MAX_BYTES; i += VNL_ALLOC_ALIGN) { - my_free_list = free_list + FREELIST_INDEX(i); - p = *my_free_list; + obj ** my_free_list = free_list + FREELIST_INDEX(i); + obj * p = *my_free_list; if (nullptr != p) { *my_free_list = p->free_list_link; @@ -77,21 +76,18 @@ vnl_alloc::refill(std::size_t n) { int nobjs = 20; char * chunk = chunk_alloc(n, nobjs); - obj ** my_free_list; - obj * result; - obj *current_obj, *next_obj; - int i; + obj * next_obj; if (1 == nobjs) return chunk; - my_free_list = free_list + FREELIST_INDEX(n); + obj ** my_free_list = free_list + FREELIST_INDEX(n); /* Build free std::list in chunk */ - result = (obj *)chunk; + obj * result = (obj *)chunk; *my_free_list = next_obj = (obj *)(chunk + n); - for (i = 1;; i++) + for (int i = 1;; i++) { - current_obj = next_obj; + obj * current_obj = next_obj; next_obj = (obj *)((char *)next_obj + n); if (nobjs - 1 == i) { @@ -109,8 +105,6 @@ vnl_alloc::refill(std::size_t n) void * vnl_alloc::reallocate(void * p, std::size_t old_sz, std::size_t new_sz) { - void * result; - std::size_t copy_sz; if (old_sz > VNL_ALLOC_MAX_BYTES && new_sz > VNL_ALLOC_MAX_BYTES) { @@ -118,8 +112,8 @@ vnl_alloc::reallocate(void * p, std::size_t old_sz, std::size_t new_sz) } if (ROUND_UP(old_sz) == ROUND_UP(new_sz)) return p; - result = allocate(new_sz); - copy_sz = new_sz > old_sz ? old_sz : new_sz; + void * result = allocate(new_sz); + const std::size_t copy_sz = new_sz > old_sz ? old_sz : new_sz; std::memcpy(result, p, copy_sz); deallocate(p, old_sz); return result; diff --git a/core/vnl/vnl_alloc.h b/core/vnl/vnl_alloc.h index 3be91d43c69..8137199471b 100644 --- a/core/vnl/vnl_alloc.h +++ b/core/vnl/vnl_alloc.h @@ -39,89 +39,99 @@ constexpr int VNL_ALLOC_ALIGN = 8; constexpr std::size_t VNL_ALLOC_MAX_BYTES = 256; -constexpr std::size_t VNL_ALLOC_NFREELISTS = VNL_ALLOC_MAX_BYTES/VNL_ALLOC_ALIGN; +constexpr std::size_t VNL_ALLOC_NFREELISTS = VNL_ALLOC_MAX_BYTES / VNL_ALLOC_ALIGN; class VNL_EXPORT vnl_alloc { - static std::size_t ROUND_UP(std::size_t bytes) { - return (bytes + VNL_ALLOC_ALIGN-1) & ~(VNL_ALLOC_ALIGN - 1); + static std::size_t + ROUND_UP(std::size_t bytes) + { + return (bytes + VNL_ALLOC_ALIGN - 1) & ~(VNL_ALLOC_ALIGN - 1); } union obj; friend union obj; - union obj { + union obj + { union obj * free_list_link; - char client_data[1]; /* The client sees this. */ + char client_data[1]; /* The client sees this. */ }; -# if defined ( _AIX ) +#if defined(_AIX) static obj * free_list[]; // Specifying a size results in duplicate def for 4.1 -# else +#else static obj * free_list[VNL_ALLOC_NFREELISTS]; -# endif - static std::size_t FREELIST_INDEX(std::size_t bytes) { - return (bytes + VNL_ALLOC_ALIGN-1)/VNL_ALLOC_ALIGN - 1; +#endif + static std::size_t + FREELIST_INDEX(std::size_t bytes) + { + return (bytes + VNL_ALLOC_ALIGN - 1) / VNL_ALLOC_ALIGN - 1; } // Returns an object of size n, and optionally adds to size n free li*st. - static void *refill(std::size_t n); + static void * + refill(std::size_t n); // Allocates a chunk for nobjs of size size. nobjs may be reduced // if it is inconvenient to allocate the requested number. - static char *chunk_alloc(std::size_t size, int &nobjs); + static char * + chunk_alloc(std::size_t size, int & nobjs); // Chunk allocation state. - static char *start_free; - static char *end_free; + static char * start_free; + static char * end_free; static std::size_t heap_size; class lock { - public: + public: lock() = default; ~lock() = default; }; friend class lock; - public: +public: // this one is needed for proper vcl_simple_alloc wrapping typedef char value_type; /* n must be > 0 */ - static void * allocate(std::size_t n) { - obj * * my_free_list; - obj * result; - - if (n > VNL_ALLOC_MAX_BYTES) { - return (void*)new char[n]; + static void * + allocate(std::size_t n) + { + if (n > VNL_ALLOC_MAX_BYTES) + { + return (void *)new char[n]; } - my_free_list = free_list + FREELIST_INDEX(n); + obj ** my_free_list = free_list + FREELIST_INDEX(n); // Acquire the lock here with a constructor call. // This ensures that it is released in exit or during stack // unwinding. - result = *my_free_list; - if (result == nullptr) { - void *r = refill(ROUND_UP(n)); + obj * result = *my_free_list; + if (result == nullptr) + { + void * r = refill(ROUND_UP(n)); return r; } - *my_free_list = result -> free_list_link; + *my_free_list = result->free_list_link; return result; } /* p may not be 0 */ - static void deallocate(void *p, std::size_t n) + static void + deallocate(void * p, std::size_t n) { - obj *q = (obj *)p; - obj * * my_free_list; + obj * q = (obj *)p; - if (n > VNL_ALLOC_MAX_BYTES) { - delete [] (char*)p; + if (n > VNL_ALLOC_MAX_BYTES) + { + delete[] (char *)p; return; } - my_free_list = free_list + FREELIST_INDEX(n); - q -> free_list_link = *my_free_list; + obj ** my_free_list = free_list + FREELIST_INDEX(n); + q->free_list_link = *my_free_list; *my_free_list = q; } - static void * reallocate(void *p, std::size_t old_sz, std::size_t new_sz); + static void * + reallocate(void * p, std::size_t old_sz, std::size_t new_sz); }; -# endif // vnl_alloc_h_ +#endif // vnl_alloc_h_ diff --git a/core/vnl/vnl_analytic_integrant.h b/core/vnl/vnl_analytic_integrant.h index 095509baeee..6e170b0ea5c 100644 --- a/core/vnl/vnl_analytic_integrant.h +++ b/core/vnl/vnl_analytic_integrant.h @@ -10,13 +10,14 @@ class vnl_analytic_integrant : public vnl_integrant_fnct { - public: +public: vnl_analytic_integrant() = default; ~vnl_analytic_integrant() override = default; // the function every derived class has to implement, which is to evaluate // the function value at point x - double f_(double /*x*/) override = 0; + double + f_(double /*x*/) override = 0; }; #endif diff --git a/core/vnl/vnl_bessel.cxx b/core/vnl/vnl_bessel.cxx index 53b6231e048..a1fee7e364e 100644 --- a/core/vnl/vnl_bessel.cxx +++ b/core/vnl/vnl_bessel.cxx @@ -24,7 +24,7 @@ vnl_bessel(unsigned n_max, double x, vnl_vector & J) J[0] = 1.0; return; } - int nhi = 2 * ((std::max(int(n_max), int(x)) + 15) / 2 + 1); + const int nhi = 2 * ((std::max(int(n_max), int(x)) + 15) / 2 + 1); vnl_vector j(nhi + 1); j[nhi] = 0.0; j[nhi - 1] = 1.0; @@ -50,15 +50,15 @@ vnl_bessel0(double x) { if (x == 0) return 1.0; - int nhi = 2 * ((int(x) + 15) / 2); // Even + const int nhi = 2 * ((int(x) + 15) / 2); // Even double j3 = 0.0; double j2 = 1.0; - double j0 = j2, j1; + double j0 = j2; double even_sum = j2; for (int i = nhi; i >= 0; i -= 2) { // j0 is i-th term, j1 is i+1-th etc - j1 = 2 * (i + 2) * j2 / x - j3; + const double j1 = 2 * (i + 2) * j2 / x - j3; j0 = 2 * (i + 1) * j1 / x - j2; even_sum += j0; j3 = j1; @@ -82,16 +82,16 @@ vnl_bessel(unsigned n, double x) return 0.0; } - int nhi = 2 * ((std::max(int(n), int(x)) + 15) / 2 + 1); + const int nhi = 2 * ((std::max(int(n), int(x)) + 15) / 2 + 1); double j3 = 0.0; double j2 = 1.0; - double j0 = j2, j1; + double j0 = j2; double even_sum = j2; double jn = j0; for (int i = nhi; i >= 0; i -= 2) { // j0 is i-th term, j1 is i+1-th etc - j1 = 2 * (i + 2) * j2 / x - j3; + const double j1 = 2 * (i + 2) * j2 / x - j3; j0 = 2 * (i + 1) * j1 / x - j2; even_sum += j0; j3 = j1; diff --git a/core/vnl/vnl_bessel.h b/core/vnl/vnl_bessel.h index aeb6c28d951..1a8c952589c 100644 --- a/core/vnl/vnl_bessel.h +++ b/core/vnl/vnl_bessel.h @@ -11,14 +11,17 @@ //: Returns J_n(x), the value of the Bessel function of order n at x // Bessel function of the first kind of order n -VNL_EXPORT double vnl_bessel(unsigned n, double x); +VNL_EXPORT double +vnl_bessel(unsigned n, double x); //: Returns J_0(x), the value of the Bessel function of order 0 at x // Bessel function of the first kind of order zero -VNL_EXPORT double vnl_bessel0(double x); +VNL_EXPORT double +vnl_bessel0(double x); //: Compute Bessel functions of first kind up to order n_max // On exit, J[i] = J_i(x) for i=0..n_max -VNL_EXPORT void vnl_bessel(unsigned n_max, double x, vnl_vector& J); +VNL_EXPORT void +vnl_bessel(unsigned n_max, double x, vnl_vector & J); #endif // vnl_bessel_h_ diff --git a/core/vnl/vnl_beta.h b/core/vnl/vnl_beta.h index eca7e16ef4c..14a663bbbff 100644 --- a/core/vnl/vnl_beta.h +++ b/core/vnl/vnl_beta.h @@ -14,16 +14,28 @@ // Actually, this implementation refers to vnl_log_gamma, // since this involves just a single call to std::exp instead of three. template -inline VNL_EXPORT double vnl_beta(T x, T y) {return std::exp(vnl_log_gamma(x)+vnl_log_gamma(y)-vnl_log_gamma(x+y)); } +inline VNL_EXPORT double +vnl_beta(T x, T y) +{ + return std::exp(vnl_log_gamma(x) + vnl_log_gamma(y) - vnl_log_gamma(x + y)); +} #else // implementation via vnl_gamma; less efficient since it needs 3x std::exp //: Computation of beta function in terms of gamma function. template -inline double vnl_beta(T x, T y) {return (vnl_gamma(x)*vnl_gamma(y))/vnl_gamma(x+y); } +inline double +vnl_beta(T x, T y) +{ + return (vnl_gamma(x) * vnl_gamma(y)) / vnl_gamma(x + y); +} #endif //: Computation of the log beta function in terms of the log gamma function. // vnl_log_beta is just the std::log (natural logarithm) of the beta function. template -inline VNL_EXPORT double vnl_log_beta(T x, T y) {return vnl_log_gamma(x)+vnl_log_gamma(y)-vnl_log_gamma(x+y); } +inline VNL_EXPORT double +vnl_log_beta(T x, T y) +{ + return vnl_log_gamma(x) + vnl_log_gamma(y) - vnl_log_gamma(x + y); +} #endif diff --git a/core/vnl/vnl_bignum.cxx b/core/vnl/vnl_bignum.cxx index bd291cc89e5..575570e8311 100644 --- a/core/vnl/vnl_bignum.cxx +++ b/core/vnl/vnl_bignum.cxx @@ -17,9 +17,7 @@ using Data = unsigned short; //: Creates a vnl_bignum from a single-precision floating point number. vnl_bignum::vnl_bignum(float f) - : count(0) - , sign(1) - , data(nullptr) + { double d = f; if (d < 0.0) @@ -55,9 +53,7 @@ vnl_bignum::vnl_bignum(float f) //: Creates a vnl_bignum from a double floating point number. vnl_bignum::vnl_bignum(double d) - : count(0) - , sign(1) - , data(nullptr) + { if (d < 0.0) { // Get sign of d @@ -92,9 +88,7 @@ vnl_bignum::vnl_bignum(double d) //: Creates a vnl_bignum from a "long double" floating point number. vnl_bignum::vnl_bignum(long double d) - : count(0) - , sign(1) - , data(nullptr) + { if (d < 0.0) { // Get sign of d @@ -141,7 +135,7 @@ next(const char *& s, std::istream ** is) { if (!is || *s) { - char c = *s; + const char c = *s; if (c) ++rt_pos, ++s; return c; @@ -318,9 +312,7 @@ is_minus_inf(const char * s, std::istream ** is = nullptr) //: Creates a vnl_bignum from the character string representation. vnl_bignum::vnl_bignum(const char * s) - : count(0) - , sign(1) - , data(nullptr) + { // decimal: "^ *[-+]?[1-9][0-9]*$" // exponential: "^ *[-+]?[1-9][0-9]*[eE][+]?[0-9]+$" @@ -509,8 +501,8 @@ vnl_bignum::operator+(const vnl_bignum & b) const sum.sign = this->sign; // Attach proper sign } else - { // Else different signs - int mag = magnitude_cmp(*this, b); // Determine relative sizes + { // Else different signs + const int mag = magnitude_cmp(*this, b); // Determine relative sizes if (mag > 0) { // If abs(*this) > abs(b) subtract(*this, b, sum); // sum = *this - b @@ -520,9 +512,9 @@ vnl_bignum::operator+(const vnl_bignum & b) const { // Else if abs(*this) < abs(b) subtract(b, *this, sum); // sum = b - *this sum.sign = b.sign; // Sign of sum follows b - } // (Else abs(*this) == abs(b) - } // so sum must be zero) - return sum; // shallow swap on return + } // (Else abs(*this) == abs(b) + } // so sum must be zero) + return sum; // shallow swap on return } //: Multiplies this with a vnl_bignum @@ -564,7 +556,8 @@ vnl_bignum::operator/=(const vnl_bignum & b) if (b.count == 0) return (*this) = (this->sign < 0 ? vnl_bignum("-Inf") : vnl_bignum("+Inf")); - vnl_bignum quot, r; // Quotient and remainder + vnl_bignum quot; + vnl_bignum r; // Quotient and remainder divide(*this, b, quot, r); // Call divide fn return (*this) = quot; } @@ -584,7 +577,8 @@ vnl_bignum::operator%=(const vnl_bignum & b) if (b.count == 0) return (*this) = 0L; // convention: remainder is 0 - vnl_bignum remain, q; // Quotient and remainder + vnl_bignum remain; + vnl_bignum q; // Quotient and remainder divide(*this, b, q, remain); // divide by b and save remainder return (*this) = remain; // shallow swap on return } @@ -673,7 +667,8 @@ operator<<(std::ostream & os, const vnl_bignum & b) } if (d.is_infinity()) return os << "Inf"; - vnl_bignum q, r; // Temp quotient and remainder + vnl_bignum q; + vnl_bignum r; // Temp quotient and remainder char * cbuf = new char[5 * (b.count + 1)]; // Temp character buffer Counter i = 0; do @@ -682,13 +677,13 @@ operator<<(std::ostream & os, const vnl_bignum & b) cbuf[i++] = char(long(r) + '0'); // Get one's digit d = q; // Then discard one's digit q = r = 0L; // Prep for next divide - } while (d != 0L); // until no more one's digits + } while (d != 0L); // until no more one's digits do { // repeat; os << cbuf[--i]; // output char buf in reverse - } while (i); // until no more chars - delete[] cbuf; // delete temp char buf - return os; // return output stream + } while (i); // until no more chars + delete[] cbuf; // delete temp char buf + return os; // return output stream } //: Convert the number to a decimal representation in a string. @@ -708,14 +703,15 @@ vnl_bignum_to_string(std::string & s, const vnl_bignum & b) } if (d.is_infinity()) return s += "Inf"; - vnl_bignum q, r; // Temp quotient and remainder + vnl_bignum q; + vnl_bignum r; // Temp quotient and remainder do { // repeat: divide(d, 10L, q, r); // Divide vnl_bignum by ten s.insert(insert_point, 1, char('0' + long(r))); // Get one's digit, and insert it at head. d = q; // Then discard one's digit q = r = 0L; // Prep for next divide - } while (d != 0L); // until no more one's digits + } while (d != 0L); // until no more one's digits return s; } @@ -740,7 +736,7 @@ vnl_bignum_from_string(vnl_bignum & b, const std::string & s) vnl_bignum::operator short() const { - int j = this->operator int(); + const int j = this->operator int(); return (short)j; } @@ -977,7 +973,8 @@ vnl_bignum::trim() void add(const vnl_bignum & b1, const vnl_bignum & b2, vnl_bignum & sum) { - const vnl_bignum *bmax, *bmin; // Determine which of the two + const vnl_bignum * bmax; + const vnl_bignum * bmin; // Determine which of the two if (b1.count >= b2.count) { // addends has the most bmax = &b1; // data. @@ -989,7 +986,8 @@ add(const vnl_bignum & b1, const vnl_bignum & b2, vnl_bignum & sum) bmin = &b1; } sum.resize(bmax->count); // Allocate data for their sum - unsigned long temp, carry = 0; + unsigned long temp; + unsigned long carry = 0; Counter i = 0; if (b1.data) { @@ -1028,7 +1026,7 @@ increment(vnl_bignum & bnum) unsigned long carry = 1; while (i < bnum.count && carry) { // increment, element by element. - unsigned long temp = (unsigned long)bnum.data[i] + carry; + const unsigned long temp = (unsigned long)bnum.data[i] + carry; carry = temp / 0x10000L; bnum.data[i] = (Data)temp; ++i; @@ -1074,7 +1072,7 @@ decrement(vnl_bignum & bnum) unsigned long borrow = 1; while (i < bnum.count && borrow) { // decrement, element by element. - unsigned long temp = (unsigned long)bnum.data[i] + 0x10000L - borrow; + const unsigned long temp = (unsigned long)bnum.data[i] + 0x10000L - borrow; borrow = (temp / 0x10000L == 0); // Did we have to borrow? bnum.data[i] = (Data)temp; // Reduce modulo radix and save ++i; @@ -1110,7 +1108,7 @@ magnitude_cmp(const vnl_bignum & b1, const vnl_bignum & b2) else if (b1.data[i - 1] < b2.data[i - 1]) return -1; i--; - } // No data, or all elements same + } // No data, or all elements same return 0; // so must be equal } @@ -1134,14 +1132,13 @@ multiply_aux(const vnl_bignum & b, Data d, vnl_bignum & prod, Counter i) } if (d != 0) { // if d == 0, nothing to do - unsigned long temp; Data carry = 0; Counter j = 0; for (; j < b.count; j++) { // for each of b's data elements, multiply times d and add running product - temp = (unsigned long)b.data[j] * (unsigned long)d + (unsigned long)prod.data[i + j] + carry; + const unsigned long temp = (unsigned long)b.data[j] * (unsigned long)d + (unsigned long)prod.data[i + j] + carry; prod.data[i + j] = Data(temp % 0x10000L); // store result in product carry = Data(temp / 0x10000L); // keep track of carry } @@ -1160,13 +1157,13 @@ multiply_aux(const vnl_bignum & b, Data d, vnl_bignum & prod, Counter i) Data normalize(const vnl_bignum & b1, const vnl_bignum & b2, vnl_bignum & u, vnl_bignum & v) { - Data d = Data(0x10000L / ((unsigned long)(b2.data[b2.count - 1]) + 1L)); // Calculate normalization factor. - u.resize(b1.count + 1); // Get data for u (plus extra) - v.resize(b2.count); // Get data for v - u.data[b1.count] = 0; // Set u's leading digit to 0 - multiply_aux(b1, d, u, 0); // u = b1 * d - multiply_aux(b2, d, v, 0); // v = b2 * d - return d; // return normalization factor + const Data d = Data(0x10000L / ((unsigned long)(b2.data[b2.count - 1]) + 1L)); // Calculate normalization factor. + u.resize(b1.count + 1); // Get data for u (plus extra) + v.resize(b2.count); // Get data for v + u.data[b1.count] = 0; // Set u's leading digit to 0 + multiply_aux(b1, d, u, 0); // u = b1 * d + multiply_aux(b2, d, v, 0); // v = b2 * d + return d; // return normalization factor } //: divide a vnl_bignum by a "single digit" @@ -1247,8 +1244,8 @@ estimate_q_hat(const vnl_bignum & u, const vnl_bignum & v, Counter j) if (lhs <= rhs) // if lhs <= rhs break; // test fails q_hat--; // Test passes: decrement q_hat - } // Loop again - return q_hat; // Return estimate + } // Loop again + return q_hat; // Return estimate } //: calculate u - v*q_hat @@ -1266,26 +1263,26 @@ multiply_subtract(vnl_bignum & u, const vnl_bignum & v, Data q_hat, Counter j) // correct number of times or one too large. if (q_hat == 0) - return q_hat; // if q_hat 0, nothing to do - vnl_bignum rslt; // create a temporary vnl_bignum - Counter tmpcnt; + return q_hat; // if q_hat 0, nothing to do + vnl_bignum rslt; // create a temporary vnl_bignum rslt.resize(v.count + 1u); // allocate data for it // simultaneous computation of u - v*q_hat - unsigned long prod, diff; - Data carry = 0, borrow = 0; + unsigned long diff; + Data carry = 0; + Data borrow = 0; Counter i = 0; for (; i < v.count; ++i) { // for each digit of v, multiply it by q_hat and subtract the result - prod = (unsigned long)v.data[i] * (unsigned long)q_hat + carry; + const unsigned long prod = (unsigned long)v.data[i] * (unsigned long)q_hat + carry; diff = (unsigned long)u.data[u.count - v.count - 1 - j + i] + (0x10000L - (unsigned long)borrow); diff -= (unsigned long)Data(prod); // form proper digit of u rslt.data[i] = Data(diff); // save the result borrow = (diff / 0x10000L == 0) ? 1 : 0; // keep track of any borrows carry = Data(prod / 0x10000L); // keep track of carries } - tmpcnt = Counter(u.count - v.count + i - j - 1); + const Counter tmpcnt = Counter(u.count - v.count + i - j - 1); diff = (unsigned long)u.data[tmpcnt] // special case for the last digit + (0x10000L - (unsigned long)borrow); diff -= (unsigned long)carry; @@ -1299,10 +1296,9 @@ multiply_subtract(vnl_bignum & u, const vnl_bignum & v, Data q_hat, Counter j) { q_hat--; carry = 0; - unsigned long sum; for (i = 0; i < v.count; ++i) { - sum = (unsigned long)rslt.data[i] + (unsigned long)v.data[i] + carry; + const unsigned long sum = (unsigned long)rslt.data[i] + (unsigned long)v.data[i] + carry; carry = Data(sum / 0x10000L); u.data[u.count - v.count + i - 1 - j] = Data(sum); } @@ -1328,13 +1324,13 @@ divide(const vnl_bignum & b1, const vnl_bignum & b2, vnl_bignum & q, vnl_bignum // Note that q or r may *not* be identical to either b1 or b2 ! assert(&b1 != &q && &b2 != &q && &b1 != &r && &b2 != &r); q = r = 0L; - if (b1 == 0L) // If divisor is zero - return; // return zero quotient and remainder - int mag = magnitude_cmp(b1, b2); // Compare magnitudes - if (mag < 0) // if abs(b1) < abs(b2) - r = b1; // return zero quotient, b1 remainder - else if (mag == 0) // if abs(b1) == abs(b2) - q = 1L; // quotient is 1, remainder is 0 + if (b1 == 0L) // If divisor is zero + return; // return zero quotient and remainder + const int mag = magnitude_cmp(b1, b2); // Compare magnitudes + if (mag < 0) // if abs(b1) < abs(b2) + r = b1; // return zero quotient, b1 remainder + else if (mag == 0) // if abs(b1) == abs(b2) + q = 1L; // quotient is 1, remainder is 0 else { // otherwise abs(b1) > abs(b2), so divide q.resize(b1.count + 1u - b2.count); // Allocate quotient @@ -1352,7 +1348,7 @@ divide(const vnl_bignum & b1, const vnl_bignum & b2, vnl_bignum & q, vnl_bignum std::cerr << "vnl_bignum::divide: b2 ="; b2.dump(std::cerr); #endif - Data d = normalize(b1, b2, u, v); // Set u = b1*d, v = b2*d + Data const d = normalize(b1, b2, u, v); // Set u = b1*d, v = b2*d #ifdef DEBUG std::cerr << "vnl_bignum::divide: d = " << d << std::hex << " (0x" << d << ")\n" << std::dec; std::cerr << "vnl_bignum::divide: u = "; @@ -1362,9 +1358,9 @@ divide(const vnl_bignum & b1, const vnl_bignum & b2, vnl_bignum & q, vnl_bignum #endif Counter j = 0; while (j <= b1.count - b2.count) - { // Main division loop - Data q_hat = estimate_q_hat(u, v, j); // Estimate # times v divides u - q.data[q.count - 1 - j] = // Do division, get true answ. + { // Main division loop + const Data q_hat = estimate_q_hat(u, v, j); // Estimate # times v divides u + q.data[q.count - 1 - j] = // Do division, get true answ. multiply_subtract(u, v, q_hat, j); j++; #ifdef DEBUG @@ -1403,9 +1399,9 @@ left_shift(const vnl_bignum & b1, int l) vnl_bignum rslt; // result of shift rslt.sign = b1.sign; // result follows sign of input auto growth = Counter(l / 16); // # of words rslt will grow by - Data shift = Data(l % 16); // amount to actually shift - Data rshift = Data(16 - shift); // amount to shift next word by - Data carry = Data( // value that will be shifted + const Data shift = Data(l % 16); // amount to actually shift + const Data rshift = Data(16 - shift); // amount to shift next word by + const Data carry = Data( // value that will be shifted b1.data[b1.count - 1] >> (16 - shift)); // out end of current array rslt.resize(b1.count + growth + (carry ? 1u : 0u)); // allocate new data array Counter i = 0; @@ -1426,8 +1422,8 @@ left_shift(const vnl_bignum & b1, int l) rslt.data[i] = (b1.data[i - growth] << shift) // do like the rest + (b1.data[i - 1 - growth] >> rshift); } - vnl_bignum & result = *((vnl_bignum *)&rslt); // same physical object - return result; // shallow swap on return + const vnl_bignum & result = *((vnl_bignum *)&rslt); // same physical object + return result; // shallow swap on return } //: right shift (arithmetic) non-infinite vnl_bignum by positive number. @@ -1437,15 +1433,15 @@ left_shift(const vnl_bignum & b1, int l) vnl_bignum right_shift(const vnl_bignum & b1, int l) { - vnl_bignum rslt; // result of shift - auto shrinkage = Counter(l / 16); // # of words rslt will shrink - Data shift = Data(l % 16); // amount to actually shift - Data dregs = Data(b1.data[b1.count - 1] >> shift); // high end data to save + vnl_bignum rslt; // result of shift + auto shrinkage = Counter(l / 16); // # of words rslt will shrink + const Data shift = Data(l % 16); // amount to actually shift + const Data dregs = Data(b1.data[b1.count - 1] >> shift); // high end data to save if (shrinkage + (dregs == 0) < b1.count) { // if not all data shifted out rslt.sign = b1.sign; // rslt follows sign of input rslt.resize(b1.count - shrinkage - (dregs == 0 ? 1 : 0)); // allocate new data - Data lshift = Data(16 - shift); // amount to shift high word + const Data lshift = Data(16 - shift); // amount to shift high word Counter i = 0; while (i < rslt.count - 1) { // shift current word @@ -1460,6 +1456,6 @@ right_shift(const vnl_bignum & b1, int l) rslt.data[i] = (b1.data[i + shrinkage] >> shift) + (b1.data[i + shrinkage + 1u] << lshift); } } - vnl_bignum & result = *((vnl_bignum *)&rslt); // same physical object - return result; // shallow swap on return + const vnl_bignum & result = *((vnl_bignum *)&rslt); // same physical object + return result; // shallow swap on return } diff --git a/core/vnl/vnl_bignum.h b/core/vnl/vnl_bignum.h index 9ff3488f166..d72181cc37b 100644 --- a/core/vnl/vnl_bignum.h +++ b/core/vnl/vnl_bignum.h @@ -69,7 +69,7 @@ #include #include #include -#include +#include #include // For enable_if and is_unsigned. #ifdef _MSC_VER # include @@ -80,27 +80,42 @@ class vnl_bignum; // These are all auxiliary functions: -VNL_EXPORT int magnitude_cmp(const vnl_bignum&, const vnl_bignum&); -VNL_EXPORT void add(const vnl_bignum&, const vnl_bignum&, vnl_bignum&); -VNL_EXPORT void subtract(const vnl_bignum&, const vnl_bignum&, vnl_bignum&); -VNL_EXPORT void multiply_aux(const vnl_bignum&, unsigned short d, vnl_bignum&, unsigned short i); -VNL_EXPORT unsigned short normalize(const vnl_bignum&, const vnl_bignum&, vnl_bignum&, vnl_bignum&); -VNL_EXPORT void divide_aux(const vnl_bignum&, unsigned short, vnl_bignum&, unsigned short&); -VNL_EXPORT unsigned short estimate_q_hat(const vnl_bignum&, const vnl_bignum&, unsigned short); -VNL_EXPORT unsigned short multiply_subtract(vnl_bignum&, const vnl_bignum&, unsigned short, unsigned short); -VNL_EXPORT void divide(const vnl_bignum&, const vnl_bignum&, vnl_bignum&, vnl_bignum&); -VNL_EXPORT vnl_bignum left_shift(const vnl_bignum& b1, int l); -VNL_EXPORT vnl_bignum right_shift(const vnl_bignum& b1, int l); -VNL_EXPORT void decrement (vnl_bignum& bnum); -VNL_EXPORT void increment (vnl_bignum& bnum); +VNL_EXPORT int +magnitude_cmp(const vnl_bignum &, const vnl_bignum &); +VNL_EXPORT void +add(const vnl_bignum &, const vnl_bignum &, vnl_bignum &); +VNL_EXPORT void +subtract(const vnl_bignum &, const vnl_bignum &, vnl_bignum &); +VNL_EXPORT void +multiply_aux(const vnl_bignum &, unsigned short d, vnl_bignum &, unsigned short i); +VNL_EXPORT unsigned short +normalize(const vnl_bignum &, const vnl_bignum &, vnl_bignum &, vnl_bignum &); +VNL_EXPORT void +divide_aux(const vnl_bignum &, unsigned short, vnl_bignum &, unsigned short &); +VNL_EXPORT unsigned short +estimate_q_hat(const vnl_bignum &, const vnl_bignum &, unsigned short); +VNL_EXPORT unsigned short +multiply_subtract(vnl_bignum &, const vnl_bignum &, unsigned short, unsigned short); +VNL_EXPORT void +divide(const vnl_bignum &, const vnl_bignum &, vnl_bignum &, vnl_bignum &); +VNL_EXPORT vnl_bignum +left_shift(const vnl_bignum & b1, int l); +VNL_EXPORT vnl_bignum +right_shift(const vnl_bignum & b1, int l); +VNL_EXPORT void +decrement(vnl_bignum & bnum); +VNL_EXPORT void +increment(vnl_bignum & bnum); //: formatted output // \relatesalso vnl_bignum -VNL_EXPORT std::ostream& operator<<(std::ostream& s, vnl_bignum const& r); +VNL_EXPORT std::ostream & +operator<<(std::ostream & s, const vnl_bignum & r); //: simple input // \relatesalso vnl_bignum -VNL_EXPORT std::istream& operator>>(std::istream& s, vnl_bignum& r); +VNL_EXPORT std::istream & +operator>>(std::istream & s, vnl_bignum & r); //: Infinite precision integers // @@ -146,12 +161,12 @@ VNL_EXPORT std::istream& operator>>(std::istream& s, vnl_bignum& r); // class VNL_EXPORT vnl_bignum { - private: +private: using Counter = unsigned short; using Data = unsigned short; - unsigned short count{0}; // Number of data elements (never 0 except for "0") - int sign{1}; // Sign of vnl_bignum (+1 or -1, nothing else!!) - unsigned short *data{nullptr}; // Pointer to data value + unsigned short count{ 0 }; // Number of data elements (never 0 except for "0") + int sign{ 1 }; // Sign of vnl_bignum (+1 or -1, nothing else!!) + unsigned short * data{ nullptr }; // Pointer to data value // Provides the absolute value and the sign of the constructor argument. template ::value> @@ -169,12 +184,9 @@ class VNL_EXPORT vnl_bignum // might cause integer overflow (undefined behavior). constexpr auto lowest = std::numeric_limits::lowest(); constexpr auto absolute_value_of_lowest = - static_cast( - static_cast(-(lowest + 1)) + 1U); + static_cast(static_cast(-(lowest + 1)) + 1U); - absolute_value = (arg == lowest) ? - absolute_value_of_lowest : - static_cast(-arg); + absolute_value = (arg == lowest) ? absolute_value_of_lowest : static_cast(-arg); sign = -1; } else @@ -193,325 +205,703 @@ class VNL_EXPORT vnl_bignum static constexpr int sign = 1; explicit constructor_helper(const T arg) - : - absolute_value{ arg } - { - } + : absolute_value{ arg } + {} }; public: vnl_bignum() = default; // Void constructor // Converting constructor template for any integer type. - template ::value>::type> + template ::value>::type> vnl_bignum(const T arg) - : count(0), data(nullptr) + { - const constructor_helper helper{arg}; + const constructor_helper helper{ arg }; auto l = helper.absolute_value; this->sign = helper.sign; - Data buf[sizeof(l)]; // Temp buffer to store l in - Counter i = 0; // buffer index - while (l) { // While more bits in l - assert(i < sizeof(l)); // no more buffer space - buf[i] = Data(l); // Peel off lower order bits + Data buf[sizeof(l)]; // Temp buffer to store l in + Counter i = 0; // buffer index + while (l) + { // While more bits in l + assert(i < sizeof(l)); // no more buffer space + buf[i] = Data(l); // Peel off lower order bits - //NOTE: shifting by more than number of bits results in all zeros - constexpr int maxbits = sizeof(l)*8; - l >>= std::min(16,maxbits); // Shift next bits into place + // NOTE: shifting by more than number of bits results in all zeros + constexpr int maxbits = sizeof(l) * 8; + l >>= std::min(16, maxbits); // Shift next bits into place i++; } if (i > 0) - this->data = new Data[this->count=i]; // Allocate permanent data + this->data = new Data[this->count = i]; // Allocate permanent data - while (i--) // Save buffer into perm. data + while (i--) // Save buffer into perm. data this->data[i] = buf[i]; } - vnl_bignum(float); // Float constructor - vnl_bignum(double); // Double constructor - vnl_bignum(long double); // Long Double constructor - vnl_bignum(vnl_bignum const&); // Copy constructor - vnl_bignum(const char*); // String constructor - ~vnl_bignum(); // Destructor - - operator short() const; // Implicit type conversion - operator int() const; // Implicit type conversion - operator long() const; // Implicit type conversion - operator float() const; // Implicit type conversion - operator double() const; // Implicit type conversion - operator long double() const; // Implicit type conversion - inline operator short() { return ((const vnl_bignum*)this)->operator short(); } - inline operator int() { return ((const vnl_bignum*)this)->operator int(); } - inline operator long() { return ((const vnl_bignum*)this)->operator long(); } - inline operator float() { return ((const vnl_bignum*)this)->operator float(); } - inline operator double() { return ((const vnl_bignum*)this)->operator double(); } - inline operator long double() { return ((const vnl_bignum*)this)->operator long double(); } - - vnl_bignum operator-() const; // Unary minus operator - inline vnl_bignum operator+() const { return *this; } // Unary plus operator - - vnl_bignum& operator=(const vnl_bignum&); // Assignment operator - - vnl_bignum operator<<(int l) const; // Bit shift - vnl_bignum operator>>(int l) const; // Bit shift - vnl_bignum operator+(vnl_bignum const& r) const; - inline vnl_bignum& operator+=(vnl_bignum const& r) { return *this = operator+(r); } - inline vnl_bignum& operator-=(vnl_bignum const& r) { return *this = operator+(-r); } - vnl_bignum& operator*=(vnl_bignum const& r); - vnl_bignum& operator/=(vnl_bignum const& r); - vnl_bignum& operator%=(vnl_bignum const& r); - inline vnl_bignum& operator<<=(int l) { return *this = *this << l; } - inline vnl_bignum& operator>>=(int l) { return *this = *this >> l; } + vnl_bignum(float); // Float constructor + vnl_bignum(double); // Double constructor + vnl_bignum(long double); // Long Double constructor + vnl_bignum(const vnl_bignum &); // Copy constructor + vnl_bignum(const char *); // String constructor + ~vnl_bignum(); // Destructor + + operator short() const; // Implicit type conversion + operator int() const; // Implicit type conversion + operator long() const; // Implicit type conversion + operator float() const; // Implicit type conversion + operator double() const; // Implicit type conversion + operator long double() const; // Implicit type conversion + inline + operator short() + { + return ((const vnl_bignum *)this)->operator short(); + } + inline + operator int() + { + return ((const vnl_bignum *)this)->operator int(); + } + inline + operator long() + { + return ((const vnl_bignum *)this)->operator long(); + } + inline + operator float() + { + return ((const vnl_bignum *)this)->operator float(); + } + inline + operator double() + { + return ((const vnl_bignum *)this)->operator double(); + } + inline + operator long double() + { + return ((const vnl_bignum *)this)->operator long double(); + } + + vnl_bignum + operator-() const; // Unary minus operator + inline vnl_bignum + operator+() const + { + return *this; + } // Unary plus operator + + vnl_bignum & + operator=(const vnl_bignum &); // Assignment operator + + vnl_bignum + operator<<(int l) const; // Bit shift + vnl_bignum + operator>>(int l) const; // Bit shift + vnl_bignum + operator+(const vnl_bignum & r) const; + inline vnl_bignum & + operator+=(const vnl_bignum & r) + { + return *this = operator+(r); + } + inline vnl_bignum & + operator-=(const vnl_bignum & r) + { + return *this = operator+(-r); + } + vnl_bignum & + operator*=(const vnl_bignum & r); + vnl_bignum & + operator/=(const vnl_bignum & r); + vnl_bignum & + operator%=(const vnl_bignum & r); + inline vnl_bignum & + operator<<=(int l) + { + return *this = *this << l; + } + inline vnl_bignum & + operator>>=(int l) + { + return *this = *this >> l; + } //: prefix increment (++b) - vnl_bignum& operator++(); + vnl_bignum & + operator++(); //: decrement - vnl_bignum& operator--(); + vnl_bignum & + operator--(); //: postfix increment (b++) - inline vnl_bignum operator++(int) { vnl_bignum b=(*this); operator++(); return b; } + inline vnl_bignum + operator++(int) + { + const vnl_bignum b = (*this); + operator++(); + return b; + } //: decrement - inline vnl_bignum operator--(int) { vnl_bignum b=(*this); operator--(); return b; } - - bool operator==(vnl_bignum const&) const; // equality - bool operator< (vnl_bignum const&) const; // less than - inline bool operator!=(vnl_bignum const& r) const { return !operator==(r); } - inline bool operator> (vnl_bignum const& r) const { return r<(*this); } - inline bool operator<=(vnl_bignum const& r) const { return !operator>(r); } - inline bool operator>=(vnl_bignum const& r) const { return !operator<(r); } - inline bool operator==(long r) const { return operator==(vnl_bignum(r)); } - inline bool operator!=(long r) const { return !operator==(vnl_bignum(r)); } - inline bool operator< (long r) const { return operator<(vnl_bignum(r)); } - inline bool operator> (long r) const { return vnl_bignum(r) < (*this); } - inline bool operator<=(long r) const { return !operator>(vnl_bignum(r)); } - inline bool operator>=(long r) const { return !operator<(vnl_bignum(r)); } - inline bool operator==(int r) const { return operator==(long(r)); } - inline bool operator!=(int r) const { return !operator==(long(r)); } - inline bool operator< (int r) const { return operator<(long(r)); } - inline bool operator> (int r) const { return vnl_bignum(long(r)) < (*this); } - inline bool operator<=(int r) const { return !operator>(long(r)); } - inline bool operator>=(int r) const { return !operator<(long(r)); } - inline bool operator==(double r) const { return r == this->operator double(); } - inline bool operator!=(double r) const { return r != this->operator double(); } - inline bool operator< (double r) const { return r > this->operator double(); } - inline bool operator> (double r) const { return r < this->operator double(); } - inline bool operator<=(double r) const { return r >= this->operator double(); } - inline bool operator>=(double r) const { return r <= this->operator double(); } - inline bool operator==(long double r) const { return r == this->operator long double(); } - inline bool operator!=(long double r) const { return r != this->operator long double(); } - inline bool operator< (long double r) const { return r > this->operator long double(); } - inline bool operator> (long double r) const { return r < this->operator long double(); } - inline bool operator<=(long double r) const { return r >= this->operator long double(); } - inline bool operator>=(long double r) const { return r <= this->operator long double(); } - - inline vnl_bignum abs() const { return operator<(0L) ? operator-() : *this; } + inline vnl_bignum + operator--(int) + { + const vnl_bignum b = (*this); + operator--(); + return b; + } + + bool + operator==(const vnl_bignum &) const; // equality + bool + operator<(const vnl_bignum &) const; // less than + inline bool + operator!=(const vnl_bignum & r) const + { + return !operator==(r); + } + inline bool + operator>(const vnl_bignum & r) const + { + return r < (*this); + } + inline bool + operator<=(const vnl_bignum & r) const + { + return !operator>(r); + } + inline bool + operator>=(const vnl_bignum & r) const + { + return !operator<(r); + } + inline bool + operator==(long r) const + { + return operator==(vnl_bignum(r)); + } + inline bool + operator!=(long r) const + { + return !operator==(vnl_bignum(r)); + } + inline bool + operator<(long r) const + { + return operator<(vnl_bignum(r)); + } + inline bool + operator>(long r) const + { + return vnl_bignum(r) < (*this); + } + inline bool + operator<=(long r) const + { + return !operator>(vnl_bignum(r)); + } + inline bool + operator>=(long r) const + { + return !operator<(vnl_bignum(r)); + } + inline bool + operator==(int r) const + { + return operator==(long(r)); + } + inline bool + operator!=(int r) const + { + return !operator==(long(r)); + } + inline bool + operator<(int r) const + { + return operator<(long(r)); + } + inline bool + operator>(int r) const + { + return vnl_bignum(long(r)) < (*this); + } + inline bool + operator<=(int r) const + { + return !operator>(long(r)); + } + inline bool + operator>=(int r) const + { + return !operator<(long(r)); + } + inline bool + operator==(double r) const + { + return r == this->operator double(); + } + inline bool + operator!=(double r) const + { + return r != this->operator double(); + } + inline bool + operator<(double r) const + { + return r > this->operator double(); + } + inline bool + operator>(double r) const + { + return r < this->operator double(); + } + inline bool + operator<=(double r) const + { + return r >= this->operator double(); + } + inline bool + operator>=(double r) const + { + return r <= this->operator double(); + } + inline bool + operator==(long double r) const + { + return r == this->operator long double(); + } + inline bool + operator!=(long double r) const + { + return r != this->operator long double(); + } + inline bool + operator<(long double r) const + { + return r > this->operator long double(); + } + inline bool + operator>(long double r) const + { + return r < this->operator long double(); + } + inline bool + operator<=(long double r) const + { + return r >= this->operator long double(); + } + inline bool + operator>=(long double r) const + { + return r <= this->operator long double(); + } + + inline vnl_bignum + abs() const + { + return operator<(0L) ? operator-() : *this; + } // "+/-Inf" is represented as: count=1, data[0]=0, sign=+/-1 : - inline bool is_infinity() const { return count==1 && data && data[0]==0; } - inline bool is_plus_infinity() const { return is_infinity() && sign==1; } - inline bool is_minus_infinity() const { return is_infinity() && sign==-1; } - - void dump(std::ostream& = std::cout) const; // Dump contents of vnl_bignum - - friend int magnitude_cmp(const vnl_bignum&, const vnl_bignum&); - friend void add(const vnl_bignum&, const vnl_bignum&, vnl_bignum&); - friend void subtract(const vnl_bignum&, const vnl_bignum&, vnl_bignum&); - friend void increment (vnl_bignum& bnum); - friend void decrement (vnl_bignum& bnum); - friend void multiply_aux(const vnl_bignum&, unsigned short, vnl_bignum&, unsigned short); - friend unsigned short normalize(const vnl_bignum&, const vnl_bignum&, vnl_bignum&, vnl_bignum&); - friend void divide_aux(const vnl_bignum&, unsigned short, vnl_bignum&, unsigned short&); - friend unsigned short estimate_q_hat(const vnl_bignum&, const vnl_bignum&, unsigned short); - friend unsigned short multiply_subtract(vnl_bignum&, const vnl_bignum&, unsigned short, unsigned short); - friend void divide(const vnl_bignum&, const vnl_bignum&, vnl_bignum&, vnl_bignum&); - friend vnl_bignum left_shift(const vnl_bignum& b1, int l); - friend vnl_bignum right_shift(const vnl_bignum& b1, int l); - friend std::ostream& operator<< (std::ostream&, const vnl_bignum&); - friend std::istream& operator>> (std::istream&, vnl_bignum&); - friend VNL_EXPORT std::string& vnl_bignum_to_string (std::string& s, const vnl_bignum& b); - friend VNL_EXPORT vnl_bignum& vnl_bignum_from_string (vnl_bignum& b, const std::string& s); - - private: - void xtoBigNum(const char *s); // convert hex to vnl_bignum - int dtoBigNum(const char *s); // convert decimal to vnl_bignum - void otoBigNum(const char *s); // convert octal to vnl_bignum - void exptoBigNum(const char *s); // convert exponential to vnl_bignum - - void resize(short); // Resize vnl_bignum data - vnl_bignum& trim(); // Trim vnl_bignum data + inline bool + is_infinity() const + { + return count == 1 && data && data[0] == 0; + } + inline bool + is_plus_infinity() const + { + return is_infinity() && sign == 1; + } + inline bool + is_minus_infinity() const + { + return is_infinity() && sign == -1; + } + + void + dump(std::ostream & = std::cout) const; // Dump contents of vnl_bignum + + friend int + magnitude_cmp(const vnl_bignum &, const vnl_bignum &); + friend void + add(const vnl_bignum &, const vnl_bignum &, vnl_bignum &); + friend void + subtract(const vnl_bignum &, const vnl_bignum &, vnl_bignum &); + friend void + increment(vnl_bignum & bnum); + friend void + decrement(vnl_bignum & bnum); + friend void + multiply_aux(const vnl_bignum &, unsigned short, vnl_bignum &, unsigned short); + friend unsigned short + normalize(const vnl_bignum &, const vnl_bignum &, vnl_bignum &, vnl_bignum &); + friend void + divide_aux(const vnl_bignum &, unsigned short, vnl_bignum &, unsigned short &); + friend unsigned short + estimate_q_hat(const vnl_bignum &, const vnl_bignum &, unsigned short); + friend unsigned short + multiply_subtract(vnl_bignum &, const vnl_bignum &, unsigned short, unsigned short); + friend void + divide(const vnl_bignum &, const vnl_bignum &, vnl_bignum &, vnl_bignum &); + friend vnl_bignum + left_shift(const vnl_bignum & b1, int l); + friend vnl_bignum + right_shift(const vnl_bignum & b1, int l); + friend std::ostream & + operator<<(std::ostream &, const vnl_bignum &); + friend std::istream & + operator>>(std::istream &, vnl_bignum &); + friend VNL_EXPORT std::string & + vnl_bignum_to_string(std::string & s, const vnl_bignum & b); + friend VNL_EXPORT vnl_bignum & + vnl_bignum_from_string(vnl_bignum & b, const std::string & s); + +private: + void + xtoBigNum(const char * s); // convert hex to vnl_bignum + int + dtoBigNum(const char * s); // convert decimal to vnl_bignum + void + otoBigNum(const char * s); // convert octal to vnl_bignum + void + exptoBigNum(const char * s); // convert exponential to vnl_bignum + + void + resize(short); // Resize vnl_bignum data + vnl_bignum & + trim(); // Trim vnl_bignum data }; //: Convert the number to a decimal representation in a string. // \relatesalso vnl_bignum -VNL_EXPORT std::string& vnl_bignum_to_string (std::string& s, const vnl_bignum& b); +VNL_EXPORT std::string & +vnl_bignum_to_string(std::string & s, const vnl_bignum & b); //: Convert the number from a decimal representation in a string. // \relatesalso vnl_bignum -VNL_EXPORT vnl_bignum& vnl_bignum_from_string (vnl_bignum& b, const std::string& s); +VNL_EXPORT vnl_bignum & +vnl_bignum_from_string(vnl_bignum & b, const std::string & s); //: Returns the sum of two bignum numbers. // \relatesalso vnl_bignum -inline vnl_bignum operator+(vnl_bignum const& r1, long r2) { return r1+vnl_bignum(r2); } -inline vnl_bignum operator+(vnl_bignum const& r1, int r2) { return r1+long(r2); } -inline vnl_bignum operator+(vnl_bignum const& r1, double r2) { return r1+vnl_bignum(r2); } -inline vnl_bignum operator+(vnl_bignum const& r1, long double r2) { return r1+vnl_bignum(r2); } -inline vnl_bignum operator+(long r2, vnl_bignum const& r1) { return r1 + r2; } -inline vnl_bignum operator+(int r2, vnl_bignum const& r1) { return r1 + r2; } -inline vnl_bignum operator+(double r2, vnl_bignum const& r1) { return r1 + r2; } -inline vnl_bignum operator+(long double r2, vnl_bignum const& r1) { return r1 + r2; } +inline vnl_bignum +operator+(const vnl_bignum & r1, long r2) +{ + return r1 + vnl_bignum(r2); +} +inline vnl_bignum +operator+(const vnl_bignum & r1, int r2) +{ + return r1 + long(r2); +} +inline vnl_bignum +operator+(const vnl_bignum & r1, double r2) +{ + return r1 + vnl_bignum(r2); +} +inline vnl_bignum +operator+(const vnl_bignum & r1, long double r2) +{ + return r1 + vnl_bignum(r2); +} +inline vnl_bignum +operator+(long r2, const vnl_bignum & r1) +{ + return r1 + r2; +} +inline vnl_bignum +operator+(int r2, const vnl_bignum & r1) +{ + return r1 + r2; +} +inline vnl_bignum +operator+(double r2, const vnl_bignum & r1) +{ + return r1 + r2; +} +inline vnl_bignum +operator+(long double r2, const vnl_bignum & r1) +{ + return r1 + r2; +} //: Returns the difference of two bignum numbers. // \relatesalso vnl_bignum -inline vnl_bignum operator-(vnl_bignum const& r1, vnl_bignum const& r2) { return r1 + (-r2); } -inline vnl_bignum operator-(vnl_bignum const& r1, long r2) { return r1 + (-r2); } -inline vnl_bignum operator-(vnl_bignum const& r1, int r2) { return r1 + (-r2); } -inline vnl_bignum operator-(vnl_bignum const& r1, double r2) { return r1 + (-r2); } -inline vnl_bignum operator-(vnl_bignum const& r1, long double r2) { return r1 + (-r2); } -inline vnl_bignum operator-(long r2, vnl_bignum const& r1) { return -(r1 + (-r2)); } -inline vnl_bignum operator-(int r2, vnl_bignum const& r1) { return -(r1 + (-r2)); } -inline vnl_bignum operator-(double r2, vnl_bignum const& r1) { return -(r1 + (-r2)); } -inline vnl_bignum operator-(long double r2, vnl_bignum const& r1) { return -(r1 + (-r2)); } +inline vnl_bignum +operator-(const vnl_bignum & r1, const vnl_bignum & r2) +{ + return r1 + (-r2); +} +inline vnl_bignum +operator-(const vnl_bignum & r1, long r2) +{ + return r1 + (-r2); +} +inline vnl_bignum +operator-(const vnl_bignum & r1, int r2) +{ + return r1 + (-r2); +} +inline vnl_bignum +operator-(const vnl_bignum & r1, double r2) +{ + return r1 + (-r2); +} +inline vnl_bignum +operator-(const vnl_bignum & r1, long double r2) +{ + return r1 + (-r2); +} +inline vnl_bignum +operator-(long r2, const vnl_bignum & r1) +{ + return -(r1 + (-r2)); +} +inline vnl_bignum +operator-(int r2, const vnl_bignum & r1) +{ + return -(r1 + (-r2)); +} +inline vnl_bignum +operator-(double r2, const vnl_bignum & r1) +{ + return -(r1 + (-r2)); +} +inline vnl_bignum +operator-(long double r2, const vnl_bignum & r1) +{ + return -(r1 + (-r2)); +} //: Returns the product of two bignum numbers. // \relatesalso vnl_bignum -inline vnl_bignum operator*(vnl_bignum const& r1, vnl_bignum const& r2) +inline vnl_bignum +operator*(const vnl_bignum & r1, const vnl_bignum & r2) { - vnl_bignum result(r1); return result *= r2; + vnl_bignum result(r1); + return result *= r2; } -inline vnl_bignum operator*(vnl_bignum const& r1, long r2) +inline vnl_bignum +operator*(const vnl_bignum & r1, long r2) { - vnl_bignum result(r1); return result *= vnl_bignum(r2); + vnl_bignum result(r1); + return result *= vnl_bignum(r2); } -inline vnl_bignum operator*(vnl_bignum const& r1, int r2) +inline vnl_bignum +operator*(const vnl_bignum & r1, int r2) { - vnl_bignum result(r1); return result *= (long)r2; + vnl_bignum result(r1); + return result *= (long)r2; } -inline vnl_bignum operator*(vnl_bignum const& r1, double r2) +inline vnl_bignum +operator*(const vnl_bignum & r1, double r2) { - vnl_bignum result(r1); return result *= (vnl_bignum)r2; + vnl_bignum result(r1); + return result *= (vnl_bignum)r2; } -inline vnl_bignum operator*(vnl_bignum const& r1, long double r2) +inline vnl_bignum +operator*(const vnl_bignum & r1, long double r2) { - vnl_bignum result(r1); return result *= (vnl_bignum)r2; + vnl_bignum result(r1); + return result *= (vnl_bignum)r2; } -inline vnl_bignum operator*(long r2, vnl_bignum const& r1) +inline vnl_bignum +operator*(long r2, const vnl_bignum & r1) { - vnl_bignum result(r1); return result *= r2; + vnl_bignum result(r1); + return result *= r2; } -inline vnl_bignum operator*(int r2, vnl_bignum const& r1) +inline vnl_bignum +operator*(int r2, const vnl_bignum & r1) { - vnl_bignum result(r1); return result *= (long)r2; + vnl_bignum result(r1); + return result *= (long)r2; } -inline vnl_bignum operator*(double r2, vnl_bignum const& r1) +inline vnl_bignum +operator*(double r2, const vnl_bignum & r1) { - vnl_bignum result(r1); return result *= (vnl_bignum)r2; + vnl_bignum result(r1); + return result *= (vnl_bignum)r2; } -inline vnl_bignum operator*(long double r2, vnl_bignum const& r1) +inline vnl_bignum +operator*(long double r2, const vnl_bignum & r1) { - vnl_bignum result(r1); return result *= (vnl_bignum)r2; + vnl_bignum result(r1); + return result *= (vnl_bignum)r2; } //: Returns the division of two bignum numbers. // \relatesalso vnl_bignum -inline vnl_bignum operator/(vnl_bignum const& r1, vnl_bignum const& r2) +inline vnl_bignum +operator/(const vnl_bignum & r1, const vnl_bignum & r2) { - vnl_bignum result(r1); return result /= r2; + vnl_bignum result(r1); + return result /= r2; } -inline vnl_bignum operator/(vnl_bignum const& r1, long r2) +inline vnl_bignum +operator/(const vnl_bignum & r1, long r2) { - vnl_bignum result(r1); return result /= r2; + vnl_bignum result(r1); + return result /= r2; } -inline vnl_bignum operator/(vnl_bignum const& r1, int r2) +inline vnl_bignum +operator/(const vnl_bignum & r1, int r2) { - vnl_bignum result(r1); return result /= (long)r2; + vnl_bignum result(r1); + return result /= (long)r2; } -inline vnl_bignum operator/(vnl_bignum const& r1, double r2) +inline vnl_bignum +operator/(const vnl_bignum & r1, double r2) { - vnl_bignum result(r1); return result /= (vnl_bignum)r2; + vnl_bignum result(r1); + return result /= (vnl_bignum)r2; } -inline vnl_bignum operator/(vnl_bignum const& r1, long double r2) +inline vnl_bignum +operator/(const vnl_bignum & r1, long double r2) { - vnl_bignum result(r1); return result /= (vnl_bignum)r2; + vnl_bignum result(r1); + return result /= (vnl_bignum)r2; } -inline vnl_bignum operator/(long r1, vnl_bignum const& r2) +inline vnl_bignum +operator/(long r1, const vnl_bignum & r2) { - vnl_bignum result(r1); return result /= r2; + vnl_bignum result(r1); + return result /= r2; } -inline vnl_bignum operator/(int r1, vnl_bignum const& r2) +inline vnl_bignum +operator/(int r1, const vnl_bignum & r2) { - vnl_bignum result((long)r1); return result /= r2; + vnl_bignum result((long)r1); + return result /= r2; } -inline vnl_bignum operator/(double r1, vnl_bignum const& r2) +inline vnl_bignum +operator/(double r1, const vnl_bignum & r2) { - vnl_bignum result(r1); return result /= r2; + vnl_bignum result(r1); + return result /= r2; } -inline vnl_bignum operator/(long double r1, vnl_bignum const& r2) +inline vnl_bignum +operator/(long double r1, const vnl_bignum & r2) { - vnl_bignum result(r1); return result /= r2; + vnl_bignum result(r1); + return result /= r2; } //: Returns the remainder of r1 divided by r2. // \relatesalso vnl_bignum -inline vnl_bignum operator%(vnl_bignum const& r1, vnl_bignum const& r2) +inline vnl_bignum +operator%(const vnl_bignum & r1, const vnl_bignum & r2) { - vnl_bignum result(r1); return result %= r2; + vnl_bignum result(r1); + return result %= r2; } -inline vnl_bignum operator%(vnl_bignum const& r1, long r2) +inline vnl_bignum +operator%(const vnl_bignum & r1, long r2) { - vnl_bignum result(r1); return result %= vnl_bignum(r2); + vnl_bignum result(r1); + return result %= vnl_bignum(r2); } -inline vnl_bignum operator%(vnl_bignum const& r1, int r2) +inline vnl_bignum +operator%(const vnl_bignum & r1, int r2) { - vnl_bignum result(r1); return result %= vnl_bignum((long)r2); + vnl_bignum result(r1); + return result %= vnl_bignum((long)r2); } -inline vnl_bignum operator%(long r1, vnl_bignum const& r2) +inline vnl_bignum +operator%(long r1, const vnl_bignum & r2) { - vnl_bignum result(r1); return result %= r2; + vnl_bignum result(r1); + return result %= r2; } -inline vnl_bignum operator%(int r1, vnl_bignum const& r2) +inline vnl_bignum +operator%(int r1, const vnl_bignum & r2) { - vnl_bignum result((long)r1); return result %= r2; + vnl_bignum result((long)r1); + return result %= r2; } // Miscellaneous operators and functions -inline bool operator==(long r1, vnl_bignum const& r2) { return r2==r1; } -inline bool operator!=(long r1, vnl_bignum const& r2) { return r2!=r1; } -inline bool operator< (long r1, vnl_bignum const& r2) { return r2> r1; } -inline bool operator> (long r1, vnl_bignum const& r2) { return r2< r1; } -inline bool operator<=(long r1, vnl_bignum const& r2) { return r2>=r1; } -inline bool operator>=(long r1, vnl_bignum const& r2) { return r2<=r1; } +inline bool +operator==(long r1, const vnl_bignum & r2) +{ + return r2 == r1; +} +inline bool +operator!=(long r1, const vnl_bignum & r2) +{ + return r2 != r1; +} +inline bool +operator<(long r1, const vnl_bignum & r2) +{ + return r2 > r1; +} +inline bool +operator>(long r1, const vnl_bignum & r2) +{ + return r2 < r1; +} +inline bool +operator<=(long r1, const vnl_bignum & r2) +{ + return r2 >= r1; +} +inline bool +operator>=(long r1, const vnl_bignum & r2) +{ + return r2 <= r1; +} namespace vnl_math { - inline vnl_bignum abs(vnl_bignum const& x) { return x.abs(); } - inline vnl_bignum squared_magnitude(vnl_bignum const& x) { return x*x; } - inline vnl_bignum sqr(vnl_bignum const& x) { return x*x; } - inline bool isnan(vnl_bignum const& ) { return false; } - inline bool isfinite(vnl_bignum const& x) { return ! x.is_infinity(); } +inline vnl_bignum +abs(const vnl_bignum & x) +{ + return x.abs(); +} +inline vnl_bignum +squared_magnitude(const vnl_bignum & x) +{ + return x * x; +} +inline vnl_bignum +sqr(const vnl_bignum & x) +{ + return x * x; +} +inline bool +isnan(const vnl_bignum &) +{ + return false; +} +inline bool +isfinite(const vnl_bignum & x) +{ + return !x.is_infinity(); } +} // namespace vnl_math #endif // vnl_bignum_h_ diff --git a/core/vnl/vnl_bignum_traits.h b/core/vnl/vnl_bignum_traits.h index a5a88d4951f..907cd570325 100644 --- a/core/vnl/vnl_bignum_traits.h +++ b/core/vnl/vnl_bignum_traits.h @@ -12,7 +12,7 @@ template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static const vnl_bignum zero; // = 0L //: Multiplicative identity @@ -29,7 +29,6 @@ class VNL_EXPORT vnl_numeric_traits using self = vnl_bignum; //: Name of type which results from using a unary operator-() using signed_t = self; - }; #endif // vnl_bignum_traits_h_ diff --git a/core/vnl/vnl_block.cxx b/core/vnl/vnl_block.cxx index d3fc2ef0af1..dce9e8fefbd 100644 --- a/core/vnl/vnl_block.cxx +++ b/core/vnl/vnl_block.cxx @@ -7,7 +7,7 @@ #include void -vnl_block_raise_exception(char const * FILE, int LINE, char const * why) +vnl_block_raise_exception(const char * FILE, int LINE, const char * why) { std::cerr << FILE << ":" << LINE << ": " << why << std::endl; assert(!"raise_exeption() called"); diff --git a/core/vnl/vnl_block.h b/core/vnl/vnl_block.h index 6904a97f0d9..09a056c07c0 100644 --- a/core/vnl/vnl_block.h +++ b/core/vnl/vnl_block.h @@ -15,39 +15,45 @@ #endif #include "vnl/vnl_export.h" -VNL_EXPORT void vnl_block_raise_exception(char const *FILE, int LINE, char const *why); +VNL_EXPORT void +vnl_block_raise_exception(const char * FILE, int LINE, const char * why); //: return sum of elements -template inline -T vnl_block_sum(T const x[], unsigned n) +template +inline T +vnl_block_sum(const T x[], unsigned n) { if (n == 0) return T(0); - else { + else + { T ans = x[0]; - for (unsigned i=1; i inline -T vnl_block_product(T const x[], unsigned n) +template +inline T +vnl_block_product(const T x[], unsigned n) { if (n == 0) return T(1); - else { + else + { T ans = x[0]; - for (unsigned i=1; i inline -T vnl_block_min_value(T const *x, unsigned n) +template +inline T +vnl_block_min_value(const T * x, unsigned n) { if (n == 0) vnl_block_raise_exception(__FILE__, __LINE__, "n is 0"); @@ -59,8 +65,9 @@ T vnl_block_min_value(T const *x, unsigned n) } //: return largest value. -template inline -T vnl_block_max_value(T const *x, unsigned n) +template +inline T +vnl_block_max_value(const T * x, unsigned n) { if (n == 0) vnl_block_raise_exception(__FILE__, __LINE__, "n is 0"); @@ -72,146 +79,163 @@ T vnl_block_max_value(T const *x, unsigned n) } //: return index of smallest value. -template inline -unsigned vnl_block_arg_min(T const x[], unsigned n) +template +inline unsigned +vnl_block_arg_min(const T x[], unsigned n) { if (n == 0) vnl_block_raise_exception(__FILE__, __LINE__, "n is 0"); T tmp = *x; unsigned idx = 0; - for (unsigned i=1; i *++x) tmp = *x, idx = i; return idx; } //: return index of largest value. -template inline -unsigned vnl_block_arg_max(T const x[], unsigned n) +template +inline unsigned +vnl_block_arg_max(const T x[], unsigned n) { if (n == 0) vnl_block_raise_exception(__FILE__, __LINE__, "n is 0"); T tmp = *x; unsigned idx = 0; - for (unsigned i=1; i inline -void vnl_block_copy(T const x[], T y[], unsigned n) +template +inline void +vnl_block_copy(const T x[], T y[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_reverse(T x[], unsigned n) +template +inline void +vnl_block_reverse(T x[], unsigned n) { T tmp; - for (unsigned i=0; 2*i inline -void vnl_block_scale(T a, T x[], unsigned n) +template +inline void +vnl_block_scale(T a, T x[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_scale(T a, T const x[], T y[], unsigned n) +template +inline void +vnl_block_scale(T a, const T x[], T y[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_add(T const x[], T y[], unsigned n) +template +inline void +vnl_block_add(const T x[], T y[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_add(T const x[], T const y[], T z[], unsigned n) +template +inline void +vnl_block_add(const T x[], const T y[], T z[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_sub(T const x[], T const y[], T z[], unsigned n) +template +inline void +vnl_block_sub(const T x[], const T y[], T z[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_mul(T const x[], T y[], unsigned n) +template +inline void +vnl_block_mul(const T x[], T y[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_mul(T const x[], T const y[], T z[], unsigned n) +template +inline void +vnl_block_mul(const T x[], const T y[], T z[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_div(T const x[], T const y[], T z[], unsigned n) +template +inline void +vnl_block_div(const T x[], const T y[], T z[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_negate(T const x[], T y[], unsigned n) +template +inline void +vnl_block_negate(const T x[], T y[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_invert(T const x[], T y[], unsigned n) +template +inline void +vnl_block_invert(const T x[], T y[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_axpy(T a, T const x[], T y[], unsigned n) +template +inline void +vnl_block_axpy(T a, const T x[], T y[], unsigned n) { - for (unsigned i=0; i inline -void vnl_block_fill(T x[], unsigned n, T value) +template +inline void +vnl_block_fill(T x[], unsigned n, T value) { - for (unsigned i=0; i VNL_EXPORT void vnl_c_na_vector_one_norm(T const *p, unsigned n, S *out); -template VNL_EXPORT void vnl_c_na_vector_two_norm(T const *p, unsigned n, S *out); -template VNL_EXPORT void vnl_c_na_vector_two_norm_squared(T const *p, unsigned n, S *out); +template +VNL_EXPORT void +vnl_c_na_vector_one_norm(const T * p, unsigned n, S * out); +template +VNL_EXPORT void +vnl_c_na_vector_two_norm(const T * p, unsigned n, S * out); +template +VNL_EXPORT void +vnl_c_na_vector_two_norm_squared(const T * p, unsigned n, S * out); //: vnl_c_na_vector interfaces to NA-aware lowlevel memory-block operations. template class VNL_EXPORT vnl_c_na_vector { - public: +public: typedef typename vnl_numeric_traits::abs_t abs_t; typedef typename vnl_numeric_traits::real_t real_t; - static T sum(T const* v, unsigned n); - static inline abs_t squared_magnitude(T const *p, unsigned n) - { abs_t val; vnl_c_na_vector_two_norm_squared(p, n, &val); return val; } + static T + sum(const T * v, unsigned n); + static inline abs_t + squared_magnitude(const T * p, unsigned n) + { + abs_t val; + vnl_c_na_vector_two_norm_squared(p, n, &val); + return val; + } - static T mean(T const *p, unsigned n); + static T + mean(const T * p, unsigned n); //: one_norm : sum of abs values - static inline abs_t one_norm(T const *p, unsigned n) - { abs_t val; vnl_c_na_vector_one_norm(p, n, &val); return val; } + static inline abs_t + one_norm(const T * p, unsigned n) + { + abs_t val; + vnl_c_na_vector_one_norm(p, n, &val); + return val; + } //: two_norm : sqrt of sum of squared abs values - static inline abs_t two_norm(T const *p, unsigned n) - { abs_t val; vnl_c_na_vector_two_norm(p, n, &val); return val; } + static inline abs_t + two_norm(const T * p, unsigned n) + { + abs_t val; + vnl_c_na_vector_two_norm(p, n, &val); + return val; + } //: two_nrm2 : sum of squared abs values - static inline abs_t two_nrm2(T const *p, unsigned n) - { abs_t val; vnl_c_na_vector_two_norm_squared(p, n, &val); return val; } + static inline abs_t + two_nrm2(const T * p, unsigned n) + { + abs_t val; + vnl_c_na_vector_two_norm_squared(p, n, &val); + return val; + } }; //: Input & output // \relatesalso vnl_c_na_vector -template VNL_EXPORT -std::ostream& print_na_vector(std::ostream&, T const*, unsigned); +template +VNL_EXPORT std::ostream & +print_na_vector(std::ostream &, const T *, unsigned); #endif // vnl_c_na_vector_h_ diff --git a/core/vnl/vnl_c_na_vector.hxx b/core/vnl/vnl_c_na_vector.hxx index 85e7504d036..08f817c09fc 100644 --- a/core/vnl/vnl_c_na_vector.hxx +++ b/core/vnl/vnl_c_na_vector.hxx @@ -20,33 +20,35 @@ template -T vnl_c_na_vector::sum(T const* v, unsigned n) +T +vnl_c_na_vector::sum(const T * v, unsigned n) { T tot(0); bool any_valid(false); - for (const T* end = v+n; v != end; v++) + for (const T * end = v + n; v != end; v++) { if (!vnl_na_isna(*v)) { tot += *v; - any_valid=true; + any_valid = true; } } return any_valid ? tot : vnl_na(T()); } template -T vnl_c_na_vector::mean(T const *p, unsigned n) +T +vnl_c_na_vector::mean(const T * p, unsigned n) { T tot(0); - unsigned n_finite=0; - for (const T* end = p+n; p != end; p++) + unsigned n_finite = 0; + for (const T * end = p + n; p != end; p++) if (!vnl_na_isna(*p)) { tot += *p; n_finite++; } - return n_finite ? tot/abs_t(n_finite) : vnl_na(T()); + return n_finite ? tot / abs_t(n_finite) : vnl_na(T()); } @@ -54,27 +56,29 @@ T vnl_c_na_vector::mean(T const *p, unsigned n) template -void vnl_c_na_vector_two_norm_squared(T const *p, unsigned n, S *out) +void +vnl_c_na_vector_two_norm_squared(const T * p, unsigned n, S * out) { S val = 0; bool any_valid(false); - for (T const * end = p+n; p != end; p++) + for (const T * end = p + n; p != end; p++) { if (!vnl_na_isna(*p)) { val += S(vnl_math::squared_magnitude(*p)); - any_valid=true; + any_valid = true; } } *out = any_valid ? val : vnl_na(T()); } template -void vnl_c_na_vector_rms_norm(T const *p, unsigned n, S *out) +void +vnl_c_na_vector_rms_norm(const T * p, unsigned n, S * out) { S val = 0; - unsigned n_finite=0; - for (T const* end = p+n; p != end; p++) + unsigned n_finite = 0; + for (const T * end = p + n; p != end; p++) { if (!vnl_na_isna(*p)) { @@ -83,27 +87,29 @@ void vnl_c_na_vector_rms_norm(T const *p, unsigned n, S *out) } } typedef typename vnl_numeric_traits::real_t real_t; - *out = n_finite ? S(std::sqrt(real_t(val/n_finite))) : vnl_na(T()); + *out = n_finite ? S(std::sqrt(real_t(val / n_finite))) : vnl_na(T()); } template -void vnl_c_na_vector_one_norm(T const *p, unsigned n, S *out) +void +vnl_c_na_vector_one_norm(const T * p, unsigned n, S * out) { T val = 0; bool any_valid(false); - for (T const* end = p+n; p != end; p++) + for (const T * end = p + n; p != end; p++) { if (!vnl_na_isna(*p)) { val += vnl_math::abs(*p++); - any_valid=true; + any_valid = true; } } *out = any_valid ? val : vnl_na(T()); } template -void vnl_c_na_vector_two_norm(T const *p, unsigned n, S *out) +void +vnl_c_na_vector_two_norm(const T * p, unsigned n, S * out) { vnl_c_na_vector_two_norm_squared(p, n, out); typedef typename vnl_numeric_traits::real_t real_t; @@ -112,17 +118,18 @@ void vnl_c_na_vector_two_norm(T const *p, unsigned n, S *out) template -void vnl_c_na_vector_inf_norm(T const *p, unsigned n, S *out) +void +vnl_c_na_vector_inf_norm(const T * p, unsigned n, S * out) { T val = 0; bool any_valid(false); - for (T const* end = p+n; p != end; p++) + for (const T * end = p + n; p != end; p++) { S v = vnl_math::abs(*p); if (v > val) // don't need to test for NA, because NA > x is always false. { v = val; - any_valid=true; + any_valid = true; } } *out = any_valid ? val : vnl_na(T()); @@ -131,40 +138,42 @@ void vnl_c_na_vector_inf_norm(T const *p, unsigned n, S *out) //--------------------------------------------------------------------------- -template -std::ostream& print_na_vector(std::ostream& s, T const* v, unsigned size) +template +std::ostream & +print_na_vector(std::ostream & s, const T * v, unsigned size) { - if (size != 0) vnl_na_insert(s, *v++); - for (T const* end = v+size-1; v != end; v++) + if (size != 0) + vnl_na_insert(s, *v++); + for (const T * end = v + size - 1; v != end; v++) { s << ' '; - vnl_na_insert(s, *v); // Output data element + vnl_na_insert(s, *v); // Output data element } return s; } //--------------------------------------------------------------------------- -#define VNL_C_NA_VECTOR_INSTANTIATE_norm(T, S) \ -template VNL_EXPORT void vnl_c_na_vector_two_norm_squared(T const *, unsigned, S *); \ -template VNL_EXPORT void vnl_c_na_vector_two_norm(T const *, unsigned, S *); \ -template VNL_EXPORT void vnl_c_na_vector_one_norm(T const *, unsigned, S *); \ -template VNL_EXPORT void vnl_c_na_vector_rms_norm(T const *, unsigned, S *); \ -template VNL_EXPORT void vnl_c_na_vector_inf_norm(T const *, unsigned, S *) +#define VNL_C_NA_VECTOR_INSTANTIATE_norm(T, S) \ + template VNL_EXPORT void vnl_c_na_vector_two_norm_squared(T const *, unsigned, S *); \ + template VNL_EXPORT void vnl_c_na_vector_two_norm(T const *, unsigned, S *); \ + template VNL_EXPORT void vnl_c_na_vector_one_norm(T const *, unsigned, S *); \ + template VNL_EXPORT void vnl_c_na_vector_rms_norm(T const *, unsigned, S *); \ + template VNL_EXPORT void vnl_c_na_vector_inf_norm(T const *, unsigned, S *) #undef VNL_C_NA_VECTOR_INSTANTIATE_ordered -#define VNL_C_NA_VECTOR_INSTANTIATE_ordered(T) \ -VNL_C_NA_VECTOR_INSTANTIATE_norm(T, vnl_c_na_vector::abs_t); \ -template class vnl_c_na_vector; \ -template std::ostream& print_na_vector(std::ostream &,T const *,unsigned) +#define VNL_C_NA_VECTOR_INSTANTIATE_ordered(T) \ + VNL_C_NA_VECTOR_INSTANTIATE_norm(T, vnl_c_na_vector::abs_t); \ + template class vnl_c_na_vector; \ + template std::ostream & print_na_vector(std::ostream &, T const *, unsigned) #undef VNL_C_NA_VECTOR_INSTANTIATE_unordered #define VNL_C_NA_VECTOR_INSTANTIATE_unordered(T) #ifndef DOXYGEN_SHOULD_SKIP_THIS -#undef VNL_C_NA_VECTOR_INSTANTIATE -#define VNL_C_NA_VECTOR_INSTANTIATE(T) extern "no such macro; use e.g. VNL_C_NA_VECTOR_INSTANTIATE_ordered instead" +# undef VNL_C_NA_VECTOR_INSTANTIATE +# define VNL_C_NA_VECTOR_INSTANTIATE(T) extern "no such macro; use e.g. VNL_C_NA_VECTOR_INSTANTIATE_ordered instead" #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // vnl_c_na_vector_hxx_ diff --git a/core/vnl/vnl_c_vector.h b/core/vnl/vnl_c_vector.h index e11456f452c..408b55d2842 100644 --- a/core/vnl/vnl_c_vector.h +++ b/core/vnl/vnl_c_vector.h @@ -29,128 +29,208 @@ #include // avoid messing about with aux_* functions for gcc 2.7 -- fsm -template VNL_EXPORT void vnl_c_vector_one_norm(T const *p, unsigned n, S *out); -template VNL_EXPORT void vnl_c_vector_two_norm(T const *p, unsigned n, S *out); -template VNL_EXPORT void vnl_c_vector_inf_norm(T const *p, unsigned n, S *out); -template VNL_EXPORT void vnl_c_vector_two_norm_squared(T const *p, unsigned n, S *out); -template VNL_EXPORT void vnl_c_vector_rms_norm(T const *p, unsigned n, S *out); +template +VNL_EXPORT void +vnl_c_vector_one_norm(const T * p, unsigned n, S * out); +template +VNL_EXPORT void +vnl_c_vector_two_norm(const T * p, unsigned n, S * out); +template +VNL_EXPORT void +vnl_c_vector_inf_norm(const T * p, unsigned n, S * out); +template +VNL_EXPORT void +vnl_c_vector_two_norm_squared(const T * p, unsigned n, S * out); +template +VNL_EXPORT void +vnl_c_vector_rms_norm(const T * p, unsigned n, S * out); //: vnl_c_vector interfaces to lowlevel memory-block operations. template class VNL_EXPORT vnl_c_vector { - public: +public: typedef typename vnl_numeric_traits::abs_t abs_t; typedef typename vnl_numeric_traits::real_t real_t; - static T sum(T const* v, unsigned n); - static inline abs_t squared_magnitude(T const *p, unsigned n) - { abs_t val; vnl_c_vector_two_norm_squared(p, n, &val); return val; } - static void normalize(T *, unsigned n); - static void apply(T const *, unsigned, T (*f)(T), T* v_out); - static void apply(T const *, unsigned, T (*f)(T const&), T* v_out); + static T + sum(const T * v, unsigned n); + static inline abs_t + squared_magnitude(const T * p, unsigned n) + { + abs_t val; + vnl_c_vector_two_norm_squared(p, n, &val); + return val; + } + static void + normalize(T *, unsigned n); + static void + apply(const T *, unsigned, T (*f)(T), T * v_out); + static void + apply(const T *, unsigned, T (*f)(const T &), T * v_out); //: y[i] = x[i] - static void copy (T const *x, T *y, unsigned); + static void + copy(const T * x, T * y, unsigned); //: y[i] = a*x[i] - static void scale (T const *x, T *y, unsigned, T const &); + static void + scale(const T * x, T * y, unsigned, const T &); //: z[i] = x[i] + y[i]; - static void add (T const *x, T const *y, T *z, unsigned); + static void + add(const T * x, const T * y, T * z, unsigned); //: z[i] = x[i] + y; - static void add (T const *x, T const& y, T *z, unsigned); + static void + add(const T * x, const T & y, T * z, unsigned); //: z[i] = x[i] - y[i] - static void subtract(T const *x, T const *y, T *z, unsigned); + static void + subtract(const T * x, const T * y, T * z, unsigned); //: z[i] = x[i] - y[i] - static void subtract(T const *x, T const& y, T *z, unsigned); + static void + subtract(const T * x, const T & y, T * z, unsigned); //: z[i] = x[i] * y[i] - static void multiply(T const *x, T const *y, T *z, unsigned); + static void + multiply(const T * x, const T * y, T * z, unsigned); //: z[i] = x[i] * y[i] - static void multiply(T const *x, T const& y, T *z, unsigned); + static void + multiply(const T * x, const T & y, T * z, unsigned); //: z[i] = x[i] / y[i] - static void divide (T const *x, T const *y, T *z, unsigned); + static void + divide(const T * x, const T * y, T * z, unsigned); //: z[i] = x[i] / y[i] - static void divide (T const *x, T const& y, T *z, unsigned); + static void + divide(const T * x, const T & y, T * z, unsigned); //: y[i] = -x[i] // Note that this is a no-op when T is an unsigned type. - static void negate (T const *x, T *y, unsigned); + static void + negate(const T * x, T * y, unsigned); //: y[i] = 1/x[i] - static void invert (T const *x, T *y, unsigned); + static void + invert(const T * x, T * y, unsigned); //: y[i] += a*x[i] - static void saxpy (T const &a, T const *x, T *y, unsigned); + static void + saxpy(const T & a, const T * x, T * y, unsigned); //: x[i] = v - static void fill (T *x, unsigned, T const &v); + static void + fill(T * x, unsigned, const T & v); - static void reverse (T *x, unsigned); - static T dot_product (T const *, T const *, unsigned); + static void + reverse(T * x, unsigned); + static T + dot_product(const T *, const T *, unsigned); //: conjugate second - static T inner_product(T const *, T const *, unsigned); - static void conjugate(T const *, T *, unsigned); - - static T max_value(T const *, unsigned); - static T min_value(T const *, unsigned); - static unsigned arg_max(T const *, unsigned); - static unsigned arg_min(T const *, unsigned); - - static T mean(T const *p, unsigned n) { return T(sum(p,n)/abs_t(n)); } + static T + inner_product(const T *, const T *, unsigned); + static void + conjugate(const T *, T *, unsigned); + + static T + max_value(const T *, unsigned); + static T + min_value(const T *, unsigned); + static unsigned + arg_max(const T *, unsigned); + static unsigned + arg_min(const T *, unsigned); + + static T + mean(const T * p, unsigned n) + { + return T(sum(p, n) / abs_t(n)); + } //: The standard deviation // This method uses the 1/(n-1) normalisation, assuming that your // data is a sample of a population. - static inline real_t std(T const *p, unsigned n) { - return std::sqrt(real_t(sum_sq_diff_means(p, n))/real_t(abs_t(n-1)));} + static inline real_t + std(const T * p, unsigned n) + { + return std::sqrt(real_t(sum_sq_diff_means(p, n)) / real_t(abs_t(n - 1))); + } //: The sum of squared differences from the mean - static T sum_sq_diff_means(T const* v, unsigned n); + static T + sum_sq_diff_means(const T * v, unsigned n); //: one_norm : sum of abs values - static inline abs_t one_norm(T const *p, unsigned n) - { abs_t val; vnl_c_vector_one_norm(p, n, &val); return val; } + static inline abs_t + one_norm(const T * p, unsigned n) + { + abs_t val; + vnl_c_vector_one_norm(p, n, &val); + return val; + } //: two_norm : sqrt of sum of squared abs values - static inline abs_t two_norm(T const *p, unsigned n) - { abs_t val; vnl_c_vector_two_norm(p, n, &val); return val; } - - //: inf_norm : max of abs values - static inline abs_t inf_norm(T const *p, unsigned n) - { abs_t val; vnl_c_vector_inf_norm(p, n, &val); return val; } + static inline abs_t + two_norm(const T * p, unsigned n) + { + abs_t val; + vnl_c_vector_two_norm(p, n, &val); + return val; + } + + //: inf_norm : max of abs values + static inline abs_t + inf_norm(const T * p, unsigned n) + { + abs_t val; + vnl_c_vector_inf_norm(p, n, &val); + return val; + } //: two_nrm2 : sum of squared abs values - static inline abs_t two_nrm2(T const *p, unsigned n) - { abs_t val; vnl_c_vector_two_norm_squared(p, n, &val); return val; } + static inline abs_t + two_nrm2(const T * p, unsigned n) + { + abs_t val; + vnl_c_vector_two_norm_squared(p, n, &val); + return val; + } //: rms_norm : sqrt of mean sum of squared abs values - static inline abs_t rms_norm(T const *p, unsigned n) - { abs_t val; vnl_c_vector_rms_norm(p, n, &val); return val; } + static inline abs_t + rms_norm(const T * p, unsigned n) + { + abs_t val; + vnl_c_vector_rms_norm(p, n, &val); + return val; + } //: Euclidean Distance between two vectors. // Sum of Differences squared. - static T euclid_dist_sq(T const *, T const *, unsigned); + static T + euclid_dist_sq(const T *, const T *, unsigned); //: Memory allocation - static T** allocate_Tptr(const std::size_t n); - static T* allocate_T(const std::size_t n); - static void deallocate(T**, const std::size_t n_when_allocated); - static void deallocate(T*, const std::size_t n_when_allocated); + static T ** + allocate_Tptr(const std::size_t n); + static T * + allocate_T(const std::size_t n); + static void + deallocate(T **, const std::size_t n_when_allocated); + static void + deallocate(T *, const std::size_t n_when_allocated); }; //: Input & output // \relatesalso vnl_c_vector -template VNL_EXPORT -std::ostream& print_vector(std::ostream&, T const*, unsigned); +template +VNL_EXPORT std::ostream & +print_vector(std::ostream &, const T *, unsigned); #endif // vnl_c_vector_h_ diff --git a/core/vnl/vnl_c_vector.hxx b/core/vnl/vnl_c_vector.hxx index 98fc4576d5e..b45baca4f47 100644 --- a/core/vnl/vnl_c_vector.hxx +++ b/core/vnl/vnl_c_vector.hxx @@ -19,141 +19,155 @@ #include "vnl_sse.h" template -T vnl_c_vector::sum(T const* v, unsigned n) +T +vnl_c_vector::sum(const T * v, unsigned n) { - return vnl_sse::sum(v,n); + return vnl_sse::sum(v, n); } template -void vnl_c_vector::normalize(T* v, unsigned n) +void +vnl_c_vector::normalize(T * v, unsigned n) { typedef typename vnl_numeric_traits::real_t real_abs_t; abs_t tmp(0); for (unsigned i = 0; i < n; ++i) tmp += vnl_math::squared_magnitude(v[i]); - if (tmp!=0) + if (tmp != 0) { tmp = abs_t(real_abs_t(1) / std::sqrt(real_abs_t(tmp))); for (unsigned i = 0; i < n; ++i) - v[i] = T(tmp*v[i]); + v[i] = T(tmp * v[i]); } } template -void vnl_c_vector::apply(T const* v, unsigned n, T (*f)(T const&), T* v_out) +void +vnl_c_vector::apply(const T * v, unsigned n, T (*f)(const T &), T * v_out) { for (unsigned i = 0; i < n; ++i) v_out[i] = f(v[i]); } template -void vnl_c_vector::apply(T const* v, unsigned n, T (*f)(T), T* v_out) +void +vnl_c_vector::apply(const T * v, unsigned n, T (*f)(T), T * v_out) { for (unsigned i = 0; i < n; ++i) v_out[i] = f(v[i]); } template -void vnl_c_vector::copy(T const *src, T *dst, unsigned n) +void +vnl_c_vector::copy(const T * src, T * dst, unsigned n) { - for (unsigned i=0; i -void vnl_c_vector::scale(T const *x, T *y, unsigned n, T const &a_) +void +vnl_c_vector::scale(const T * x, T * y, unsigned n, const T & a_) { T a = a_; if (x == y) - for (unsigned i=0; i -void vnl_c_vector::add(T const *x, T const *y, T *z, unsigned n) +void +vnl_c_vector::add(T const * x, T const * y, T * z, unsigned n) { impl_elmt_wise_commutative(+); } template -void vnl_c_vector::add(T const *x, T const& y, T *z, unsigned n) +void +vnl_c_vector::add(const T * x, const T & y, T * z, unsigned n) { impl_elmt_wise_commutative_a(+); } template -void vnl_c_vector::subtract(T const *x, T const *y, T *z, unsigned n) +void +vnl_c_vector::subtract(const T * x, const T * y, T * z, unsigned n) { impl_elmt_wise_non_commutative(-); } template -void vnl_c_vector::subtract(T const *x, T const& y, T *z, unsigned n) +void +vnl_c_vector::subtract(const T * x, const T & y, T * z, unsigned n) { impl_elmt_wise_commutative_a(-); } template -void vnl_c_vector::multiply(T const *x, T const *y, T *z, unsigned n) +void +vnl_c_vector::multiply(const T * x, const T * y, T * z, unsigned n) { impl_elmt_wise_commutative(*); } template -void vnl_c_vector::multiply(T const *x, T const& y, T *z, unsigned n) +void +vnl_c_vector::multiply(const T * x, const T & y, T * z, unsigned n) { impl_elmt_wise_commutative_a(*); } template -void vnl_c_vector::divide(T const *x, T const *y, T *z, unsigned n) +void +vnl_c_vector::divide(const T * x, const T * y, T * z, unsigned n) { impl_elmt_wise_non_commutative(/); } template -void vnl_c_vector::divide(T const *x, T const& y, T *z, unsigned n) +void +vnl_c_vector::divide(const T * x, const T & y, T * z, unsigned n) { impl_elmt_wise_commutative_a(/); } @@ -163,121 +177,136 @@ void vnl_c_vector::divide(T const *x, T const& y, T *z, unsigned n) //-------------------------------------------------------------------------- template -void vnl_c_vector::negate(T const *x, T *y, unsigned n) +void +vnl_c_vector::negate(const T * x, T * y, unsigned n) { if (x == y) - for (unsigned i=0; i -void vnl_c_vector::invert(T const *x, T *y, unsigned n) +void +vnl_c_vector::invert(const T * x, T * y, unsigned n) { if (x == y) - for (unsigned i=0; i -void vnl_c_vector::saxpy(T const &a_, T const *x, T *y, unsigned n) +void +vnl_c_vector::saxpy(const T & a_, const T * x, T * y, unsigned n) { T a = a_; - for (unsigned i=0; i -void vnl_c_vector::fill(T *x, unsigned n, T const &v_) +void +vnl_c_vector::fill(T * x, unsigned n, const T & v_) { T v = v_; - for (unsigned i=0; i -void vnl_c_vector::reverse(T *x, unsigned n) +void +vnl_c_vector::reverse(T * x, unsigned n) { - for (unsigned i=0; 2*i+1 -T vnl_c_vector::dot_product(T const *a, T const *b, unsigned n) +template +T +vnl_c_vector::dot_product(const T * a, const T * b, unsigned n) { - return vnl_sse::dot_product(a,b,n); + return vnl_sse::dot_product(a, b, n); } // conjugating "dot" product. -template -T vnl_c_vector::inner_product(T const *a, T const *b, unsigned n) +template +T +vnl_c_vector::inner_product(const T * a, const T * b, unsigned n) { T ip(0); - for (unsigned i=0; i::conjugate(b[i]); return ip; } // conjugates one block of data into another block. -template -void vnl_c_vector::conjugate(T const *src, T *dst, unsigned n) +template +void +vnl_c_vector::conjugate(const T * src, T * dst, unsigned n) { - for (unsigned i=0; i::conjugate( src[i] ); + for (unsigned i = 0; i < n; ++i) + dst[i] = vnl_complex_traits::conjugate(src[i]); } //------------------------------------------------------------------------------ //: Returns max value of the vector. -template -T vnl_c_vector::max_value(T const *src, unsigned n) +template +T +vnl_c_vector::max_value(const T * src, unsigned n) { - assert(n!=0); // max_value of an empty vector is undefined - return vnl_sse::max(src,n); + assert(n != 0); // max_value of an empty vector is undefined + return vnl_sse::max(src, n); } //: Returns min value of the vector. -template -T vnl_c_vector::min_value(T const *src, unsigned n) +template +T +vnl_c_vector::min_value(const T * src, unsigned n) { - assert(n!=0); // min_value of an empty vector is undefined - return vnl_sse::min(src,n); + assert(n != 0); // min_value of an empty vector is undefined + return vnl_sse::min(src, n); } //: Returns location of max value of the vector. -template -unsigned vnl_c_vector::arg_max(T const *src, unsigned n) +template +unsigned +vnl_c_vector::arg_max(const T * src, unsigned n) { - assert(n!=0); // max value of an empty vector is undefined - return vnl_sse::arg_max(src,n); + assert(n != 0); // max value of an empty vector is undefined + return vnl_sse::arg_max(src, n); } //: Returns location of min value of the vector. -template -unsigned vnl_c_vector::arg_min(T const *src, unsigned n) +template +unsigned +vnl_c_vector::arg_min(const T * src, unsigned n) { - assert(n!=0); // min value of an empty vector is undefined - return vnl_sse::arg_min(src,n); + assert(n != 0); // min value of an empty vector is undefined + return vnl_sse::arg_min(src, n); } //: Sum of Differences squared. -template -T vnl_c_vector::euclid_dist_sq(T const *a, T const *b, unsigned n) +template +T +vnl_c_vector::euclid_dist_sq(const T * a, const T * b, unsigned n) { - return vnl_sse::euclid_dist_sq(a,b,n); + return vnl_sse::euclid_dist_sq(a, b, n); } template -T vnl_c_vector::sum_sq_diff_means(T const* v, unsigned n) +T +vnl_c_vector::sum_sq_diff_means(const T * v, unsigned n) { T sum(0); T sum_sq(0); @@ -286,25 +315,27 @@ T vnl_c_vector::sum_sq_diff_means(T const* v, unsigned n) sum += *v; sum_sq += *v * *v; } - return sum_sq - sum*sum / abs_t(n); + return sum_sq - sum * sum / abs_t(n); } //------------------------------------------------------------ template -void vnl_c_vector_two_norm_squared(T const *p, unsigned n, S *out) +void +vnl_c_vector_two_norm_squared(const T * p, unsigned n, S * out) { // IMS: MSVC's optimiser does much better with *p++ than with p[i]; // consistently about 30% better over vectors from 4 to 20000 dimensions. S val = S(0); - T const* end = p+n; + const T * end = p + n; while (p != end) val += S(vnl_math::squared_magnitude(*p++)); *out = val; } template -void vnl_c_vector_rms_norm(T const *p, unsigned n, S *out) +void +vnl_c_vector_rms_norm(const T * p, unsigned n, S * out) { vnl_c_vector_two_norm_squared(p, n, out); *out /= n; @@ -313,16 +344,18 @@ void vnl_c_vector_rms_norm(T const *p, unsigned n, S *out) } template -void vnl_c_vector_one_norm(T const *p, unsigned n, S *out) +void +vnl_c_vector_one_norm(const T * p, unsigned n, S * out) { *out = 0; - T const* end = p+n; + const T * end = p + n; while (p != end) *out += vnl_math::abs(*p++); } template -void vnl_c_vector_two_norm(T const *p, unsigned n, S *out) +void +vnl_c_vector_two_norm(const T * p, unsigned n, S * out) { vnl_c_vector_two_norm_squared(p, n, out); typedef typename vnl_numeric_traits::real_t real_t; @@ -330,11 +363,13 @@ void vnl_c_vector_two_norm(T const *p, unsigned n, S *out) } template -void vnl_c_vector_inf_norm(T const *p, unsigned n, S *out) +void +vnl_c_vector_inf_norm(const T * p, unsigned n, S * out) { *out = 0; - T const* end = p+n; - while (p != end) { + const T * end = p + n; + while (p != end) + { S v = vnl_math::abs(*p++); if (v > *out) *out = v; @@ -345,110 +380,162 @@ void vnl_c_vector_inf_norm(T const *p, unsigned n, S *out) //--------------------------------------------------------------------------- -inline void* vnl_c_vector_alloc(std::size_t n, unsigned size) +inline void * +vnl_c_vector_alloc(std::size_t n, unsigned size) { - return vnl_sse_alloc(n,size); + return vnl_sse_alloc(n, size); } -inline void vnl_c_vector_dealloc(void* v, std::size_t n, unsigned size) +inline void +vnl_c_vector_dealloc(void * v, std::size_t n, unsigned size) { - vnl_sse_dealloc(v,n,size); + vnl_sse_dealloc(v, n, size); } -template -T** vnl_c_vector::allocate_Tptr(const std::size_t n) +template +T ** +vnl_c_vector::allocate_Tptr(const std::size_t n) { - return (T**)vnl_c_vector_alloc(n, sizeof (T*)); + return (T **)vnl_c_vector_alloc(n, sizeof(T *)); } -template -void vnl_c_vector::deallocate(T** v, const std::size_t n) +template +void +vnl_c_vector::deallocate(T ** v, const std::size_t n) { - vnl_c_vector_dealloc(v, n, sizeof (T*)); + vnl_c_vector_dealloc(v, n, sizeof(T *)); } // "T *" is POD, but "T" might not be. #ifdef _MSC_VER # include #endif -template inline void vnl_c_vector_construct(T *p, std::size_t n) -{ - for (std::size_t i=0; i *, std::size_t) { } -inline void vnl_c_vector_construct(std::complex *, std::size_t) { } -inline void vnl_c_vector_construct(std::complex *, std::size_t) { } - -template inline void vnl_c_vector_destruct(T *p, std::size_t n) -{ - for (std::size_t i=0; i~T(); -} +template +inline void +vnl_c_vector_construct(T * p, std::size_t n) +{ + for (std::size_t i = 0; i < n; ++i) + new (p + i) T(); +} + +inline void +vnl_c_vector_construct(float *, std::size_t) +{} +inline void +vnl_c_vector_construct(double *, std::size_t) +{} +inline void +vnl_c_vector_construct(long double *, std::size_t) +{} +inline void +vnl_c_vector_construct(std::complex *, std::size_t) +{} +inline void +vnl_c_vector_construct(std::complex *, std::size_t) +{} +inline void +vnl_c_vector_construct(std::complex *, std::size_t) +{} -inline void vnl_c_vector_destruct(float *, std::size_t) { } -inline void vnl_c_vector_destruct(double *, std::size_t) { } -inline void vnl_c_vector_destruct(long double *, std::size_t) { } -inline void vnl_c_vector_destruct(std::complex *, std::size_t) { } -inline void vnl_c_vector_destruct(std::complex *, std::size_t) { } -inline void vnl_c_vector_destruct(std::complex *, std::size_t) { } +template +inline void +vnl_c_vector_destruct(T * p, std::size_t n) +{ + for (std::size_t i = 0; i < n; ++i) + (p + i)->~T(); +} + +inline void +vnl_c_vector_destruct(float *, std::size_t) +{} +inline void +vnl_c_vector_destruct(double *, std::size_t) +{} +inline void +vnl_c_vector_destruct(long double *, std::size_t) +{} +inline void +vnl_c_vector_destruct(std::complex *, std::size_t) +{} +inline void +vnl_c_vector_destruct(std::complex *, std::size_t) +{} +inline void +vnl_c_vector_destruct(std::complex *, std::size_t) +{} -template -T* vnl_c_vector::allocate_T(const std::size_t n) +template +T * +vnl_c_vector::allocate_T(const std::size_t n) { - T *p = (T*)vnl_c_vector_alloc(n, sizeof (T)); + T * p = (T *)vnl_c_vector_alloc(n, sizeof(T)); vnl_c_vector_construct(p, n); return p; } -template -void vnl_c_vector::deallocate(T* p, const std::size_t n) +template +void +vnl_c_vector::deallocate(T * p, const std::size_t n) { vnl_c_vector_destruct(p, n); - vnl_c_vector_dealloc(p, n, sizeof (T)); + vnl_c_vector_dealloc(p, n, sizeof(T)); } -template -std::ostream& print_vector(std::ostream& s, T const* v, unsigned size) +template +std::ostream & +print_vector(std::ostream & s, const T * v, unsigned size) { - if (size != 0) s << v[0]; - for (unsigned i = 1; i < size; ++i) // For each index in vector - s << ' ' << v[i]; // Output data element + if (size != 0) + s << v[0]; + for (unsigned i = 1; i < size; ++i) // For each index in vector + s << ' ' << v[i]; // Output data element return s; } //--------------------------------------------------------------------------- -#define VNL_C_VECTOR_INSTANTIATE_norm(T, S) \ -template VNL_EXPORT void vnl_c_vector_two_norm_squared(T const *, unsigned, S *); \ -template VNL_EXPORT void vnl_c_vector_rms_norm(T const *, unsigned, S *); \ -template VNL_EXPORT void vnl_c_vector_one_norm(T const *, unsigned, S *); \ -template VNL_EXPORT void vnl_c_vector_two_norm(T const *, unsigned, S *); \ -template VNL_EXPORT void vnl_c_vector_inf_norm(T const *, unsigned, S *) +#define VNL_C_VECTOR_INSTANTIATE_norm(T, S) \ + template VNL_EXPORT void vnl_c_vector_two_norm_squared(T const *, unsigned, S *); \ + template VNL_EXPORT void vnl_c_vector_rms_norm(T const *, unsigned, S *); \ + template VNL_EXPORT void vnl_c_vector_one_norm(T const *, unsigned, S *); \ + template VNL_EXPORT void vnl_c_vector_two_norm(T const *, unsigned, S *); \ + template VNL_EXPORT void vnl_c_vector_inf_norm(T const *, unsigned, S *) #undef VNL_C_VECTOR_INSTANTIATE_ordered -#define VNL_C_VECTOR_INSTANTIATE_ordered(T) \ -VNL_C_VECTOR_INSTANTIATE_norm(T, vnl_c_vector::abs_t); \ -template class vnl_c_vector; \ -template VNL_EXPORT std::ostream& print_vector(std::ostream &,T const *,unsigned) +#define VNL_C_VECTOR_INSTANTIATE_ordered(T) \ + VNL_C_VECTOR_INSTANTIATE_norm(T, vnl_c_vector::abs_t); \ + template class vnl_c_vector; \ + template VNL_EXPORT std::ostream & print_vector(std::ostream &, T const *, unsigned) #undef VNL_C_VECTOR_INSTANTIATE_unordered -#define VNL_C_VECTOR_INSTANTIATE_unordered(T) \ -template <> T vnl_c_vector::max_value(T const *, unsigned) { return T(0); } \ -template <> T vnl_c_vector::min_value(T const *, unsigned) { return T(0); } \ -template <> unsigned vnl_c_vector::arg_max(T const *, unsigned) { return 0U; } \ -template <> unsigned vnl_c_vector::arg_min(T const *, unsigned) { return 0U; } \ -template class vnl_c_vector; \ -VNL_C_VECTOR_INSTANTIATE_norm(T, vnl_c_vector::abs_t); +#define VNL_C_VECTOR_INSTANTIATE_unordered(T) \ + template <> \ + T vnl_c_vector::max_value(T const *, unsigned) \ + { \ + return T(0); \ + } \ + template <> \ + T vnl_c_vector::min_value(T const *, unsigned) \ + { \ + return T(0); \ + } \ + template <> \ + unsigned vnl_c_vector::arg_max(T const *, unsigned) \ + { \ + return 0U; \ + } \ + template <> \ + unsigned vnl_c_vector::arg_min(T const *, unsigned) \ + { \ + return 0U; \ + } \ + template class vnl_c_vector; \ + VNL_C_VECTOR_INSTANTIATE_norm(T, vnl_c_vector::abs_t); #ifndef DOXYGEN_SHOULD_SKIP_THIS -#undef VNL_C_VECTOR_INSTANTIATE -#define VNL_C_VECTOR_INSTANTIATE(T) extern "no such macro; use e.g. VNL_C_VECTOR_INSTANTIATE_ordered instead" +# undef VNL_C_VECTOR_INSTANTIATE +# define VNL_C_VECTOR_INSTANTIATE(T) extern "no such macro; use e.g. VNL_C_VECTOR_INSTANTIATE_ordered instead" #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // vnl_c_vector_hxx_ diff --git a/core/vnl/vnl_complex.h b/core/vnl/vnl_complex.h index 58ac91a8072..91834761209 100644 --- a/core/vnl/vnl_complex.h +++ b/core/vnl/vnl_complex.h @@ -27,16 +27,14 @@ namespace vnl_math { - // should consider making these function templated, -#define type_macro(T) \ - inline bool isnan(std::complexconst& z) { return isnan(std::real(z)) || isnan(std::imag(z)); } \ - inline bool isfinite(std::complexconst& z) { return isfinite(std::real(z)) && isfinite(std::imag(z)); } \ - inline T abs(std::complex const& z) { return std::abs(z); } \ - inline std::complex sqr(std::complex const& z) { return z*z; } \ - inline T squared_magnitude(std::complex const& z) { return std::norm(z); } - type_macro(float) - type_macro(double) - type_macro(long double) +// should consider making these function templated, +#define type_macro(T) \ + inline bool isnan(std::complex const & z) { return isnan(std::real(z)) || isnan(std::imag(z)); } \ + inline bool isfinite(std::complex const & z) { return isfinite(std::real(z)) && isfinite(std::imag(z)); } \ + inline T abs(std::complex const & z) { return std::abs(z); } \ + inline std::complex sqr(std::complex const & z) { return z * z; } \ + inline T squared_magnitude(std::complex const & z) { return std::norm(z); } +type_macro(float) type_macro(double) type_macro(long double) #undef type_macro } // end namespace vnl_math diff --git a/core/vnl/vnl_complex_ops.hxx b/core/vnl/vnl_complex_ops.hxx index 235efbfc837..a16dff38986 100644 --- a/core/vnl/vnl_complex_ops.hxx +++ b/core/vnl/vnl_complex_ops.hxx @@ -20,17 +20,17 @@ template void -vnl_complexify(T const *src, std::complex *dst, unsigned n) +vnl_complexify(const T * src, std::complex * dst, unsigned n) { - for (unsigned i=0; i void -vnl_complexify(T const *re, T const *im, std::complex *dst, unsigned n) +vnl_complexify(const T * re, const T * im, std::complex * dst, unsigned n) { - for (unsigned i=0; i(re[i], im[i]); } @@ -44,37 +44,37 @@ vnl_complexify(T const *re, T const *im, std::complex *dst, unsigned n) // - vnl_sym_matrix template -vnl_vector > - vnl_complexify(vnl_vector const &R) +vnl_vector> +vnl_complexify(const vnl_vector & R) { - vnl_vector > C(R.size()); + vnl_vector> C(R.size()); vnl_complexify(R.begin(), C.begin(), R.size()); return C; } template -vnl_matrix > - vnl_complexify(vnl_matrix const &R) +vnl_matrix> +vnl_complexify(const vnl_matrix & R) { - vnl_matrix > C(R.rows(), R.cols()); + vnl_matrix> C(R.rows(), R.cols()); vnl_complexify(R.begin(), C.begin(), R.size()); return C; } template -vnl_diag_matrix > - vnl_complexify(vnl_diag_matrix const& R) +vnl_diag_matrix> +vnl_complexify(const vnl_diag_matrix & R) { - vnl_diag_matrix > C(R.rows(), R.cols()); + vnl_diag_matrix> C(R.rows(), R.cols()); vnl_complexify(R.begin(), C.begin(), R.size()); return C; } template -vnl_sym_matrix > - vnl_complexify(vnl_sym_matrix const& R) +vnl_sym_matrix> +vnl_complexify(const vnl_sym_matrix & R) { - vnl_sym_matrix > C(R.size()); + vnl_sym_matrix> C(R.size()); vnl_complexify(R.begin(), C.begin(), R.size()); return C; } @@ -91,42 +91,42 @@ vnl_sym_matrix > // - vnl_sym_matrix template -vnl_vector > - vnl_complexify(vnl_vector const &R, vnl_vector const &I) +vnl_vector> +vnl_complexify(const vnl_vector & R, const vnl_vector & I) { assert(R.size() == I.size()); - vnl_vector > C(R.size()); + vnl_vector> C(R.size()); vnl_complexify(R.begin(), I.begin(), C.begin(), R.size()); return C; } template -vnl_matrix > - vnl_complexify(vnl_matrix const &R, vnl_matrix const &I) +vnl_matrix> +vnl_complexify(const vnl_matrix & R, const vnl_matrix & I) { assert(R.rows() == I.rows()); assert(R.cols() == I.cols()); - vnl_matrix > C(R.rows(), R.cols()); + vnl_matrix> C(R.rows(), R.cols()); vnl_complexify(R.begin(), I.begin(), C.begin(), R.size()); return C; } template -vnl_diag_matrix > - vnl_complexify(vnl_diag_matrix const &R, vnl_diag_matrix const &I) +vnl_diag_matrix> +vnl_complexify(const vnl_diag_matrix & R, const vnl_diag_matrix & I) { assert(R.rows() == I.rows()); - vnl_diag_matrix > C(R.rows()); + vnl_diag_matrix> C(R.rows()); vnl_complexify(R.begin(), I.begin(), C.begin(), R.size()); return C; } template -vnl_sym_matrix > - vnl_complexify(vnl_sym_matrix const &R, vnl_sym_matrix const &I) +vnl_sym_matrix> +vnl_complexify(const vnl_sym_matrix & R, const vnl_sym_matrix & I) { assert(R.rows() == I.rows()); - vnl_sym_matrix > C(R.rows()); + vnl_sym_matrix> C(R.rows()); vnl_complexify(R.begin(), I.begin(), C.begin(), R.size()); return C; } @@ -144,19 +144,19 @@ vnl_sym_matrix > //: Return array of real parts of complex array. template void - vnl_real(std::complex const* C, T* R, unsigned int n) +vnl_real(const std::complex * C, T * R, unsigned int n) { - for (unsigned int i=0; i >. template vnl_vector - vnl_real(vnl_vector > const & C) +vnl_real(const vnl_vector> & C) { vnl_vector R(C.size()); - typename vnl_vector >::const_iterator cIt = C.begin(); + typename vnl_vector>::const_iterator cIt = C.begin(); typename vnl_vector::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::real(*cIt); @@ -166,10 +166,10 @@ vnl_vector //: Matrix of real parts of vnl_matrix >. template vnl_matrix - vnl_real(vnl_matrix > const& C) +vnl_real(const vnl_matrix> & C) { vnl_matrix R(C.rows(), C.columns()); - typename vnl_matrix >::const_iterator cIt = C.begin(); + typename vnl_matrix>::const_iterator cIt = C.begin(); typename vnl_matrix::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::real(*cIt); @@ -179,10 +179,10 @@ vnl_matrix //: Matrix of real parts of vnl_diag_matrix >. template vnl_diag_matrix - vnl_real(vnl_diag_matrix > const& C) +vnl_real(const vnl_diag_matrix> & C) { vnl_diag_matrix R(C.rows()); - typename vnl_diag_matrix >::const_iterator cIt = C.begin(); + typename vnl_diag_matrix>::const_iterator cIt = C.begin(); typename vnl_diag_matrix::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::real(*cIt); @@ -192,10 +192,10 @@ vnl_diag_matrix //: Matrix of real parts of vnl_sym_matrix >. template vnl_sym_matrix - vnl_real(vnl_sym_matrix > const& C) +vnl_real(const vnl_sym_matrix> & C) { vnl_sym_matrix R(C.rows()); - typename vnl_sym_matrix >::const_iterator cIt = C.begin(); + typename vnl_sym_matrix>::const_iterator cIt = C.begin(); typename vnl_sym_matrix::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::real(*cIt); @@ -215,19 +215,19 @@ vnl_sym_matrix //: Return array of imaginary parts of complex array. template void - vnl_imag(std::complex const* C, T* I, unsigned int n) +vnl_imag(const std::complex * C, T * I, unsigned int n) { - for (unsigned int i=0; i >. template vnl_vector - vnl_imag(vnl_vector > const & C) +vnl_imag(const vnl_vector> & C) { vnl_vector R(C.size()); - typename vnl_vector >::const_iterator cIt = C.begin(); + typename vnl_vector>::const_iterator cIt = C.begin(); typename vnl_vector::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::imag(*cIt); @@ -237,10 +237,10 @@ vnl_vector //: Matrix of imaginary parts of vnl_matrix >. template vnl_matrix - vnl_imag(vnl_matrix > const& C) +vnl_imag(const vnl_matrix> & C) { vnl_matrix R(C.rows(), C.columns()); - typename vnl_matrix >::const_iterator cIt = C.begin(); + typename vnl_matrix>::const_iterator cIt = C.begin(); typename vnl_matrix::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::imag(*cIt); @@ -250,10 +250,10 @@ vnl_matrix //: Matrix of real parts of vnl_diag_matrix >. template vnl_diag_matrix - vnl_imag(vnl_diag_matrix > const& C) +vnl_imag(const vnl_diag_matrix> & C) { vnl_diag_matrix R(C.rows()); - typename vnl_diag_matrix >::const_iterator cIt = C.begin(); + typename vnl_diag_matrix>::const_iterator cIt = C.begin(); typename vnl_diag_matrix::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::imag(*cIt); @@ -263,10 +263,10 @@ vnl_diag_matrix //: Matrix of real parts of vnl_sym_matrix >. template vnl_sym_matrix - vnl_imag(vnl_sym_matrix > const& C) +vnl_imag(const vnl_sym_matrix> & C) { vnl_sym_matrix R(C.rows()); - typename vnl_sym_matrix >::const_iterator cIt = C.begin(); + typename vnl_sym_matrix>::const_iterator cIt = C.begin(); typename vnl_sym_matrix::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::imag(*cIt); @@ -275,32 +275,34 @@ vnl_sym_matrix //------------------------------------------------------------------------- -#define VNL_COMPLEX_OPS_INSTANTIATE(T) \ -template VNL_EXPORT void vnl_complexify(T const *, std::complex *, unsigned); \ -template VNL_EXPORT void vnl_complexify(T const *, T const *, std::complex *, unsigned); \ -\ -template VNL_EXPORT vnl_vector > vnl_complexify(vnl_vector const &); \ -template VNL_EXPORT vnl_vector > vnl_complexify(vnl_vector const &, vnl_vector const &); \ -template VNL_EXPORT vnl_matrix > vnl_complexify(vnl_matrix const &); \ -template VNL_EXPORT vnl_matrix > vnl_complexify(vnl_matrix const &, vnl_matrix const &); \ -template VNL_EXPORT vnl_diag_matrix > vnl_complexify(vnl_diag_matrix const &); \ -template VNL_EXPORT vnl_diag_matrix > vnl_complexify(vnl_diag_matrix const &,vnl_diag_matrix const&); \ -template VNL_EXPORT vnl_sym_matrix > vnl_complexify(vnl_sym_matrix const &); \ -template VNL_EXPORT vnl_sym_matrix > vnl_complexify(vnl_sym_matrix const &,vnl_sym_matrix const&); \ -\ -template VNL_EXPORT void vnl_real(std::complex const*, T*, unsigned int); \ -template VNL_EXPORT void vnl_imag(std::complex const*, T*, unsigned int); \ -\ -template VNL_EXPORT vnl_vector vnl_real(vnl_vector > const&); \ -template VNL_EXPORT vnl_vector vnl_imag(vnl_vector > const&); \ -\ -template VNL_EXPORT vnl_matrix vnl_real(vnl_matrix > const&); \ -template VNL_EXPORT vnl_matrix vnl_imag(vnl_matrix > const&); \ -\ -template VNL_EXPORT vnl_diag_matrix vnl_real(vnl_diag_matrix > const&); \ -template VNL_EXPORT vnl_diag_matrix vnl_imag(vnl_diag_matrix > const&); \ -\ -template VNL_EXPORT vnl_sym_matrix vnl_real(vnl_sym_matrix > const&); \ -template VNL_EXPORT vnl_sym_matrix vnl_imag(vnl_sym_matrix > const&) +#define VNL_COMPLEX_OPS_INSTANTIATE(T) \ + template VNL_EXPORT void vnl_complexify(T const *, std::complex *, unsigned); \ + template VNL_EXPORT void vnl_complexify(T const *, T const *, std::complex *, unsigned); \ + \ + template VNL_EXPORT vnl_vector> vnl_complexify(vnl_vector const &); \ + template VNL_EXPORT vnl_vector> vnl_complexify(vnl_vector const &, vnl_vector const &); \ + template VNL_EXPORT vnl_matrix> vnl_complexify(vnl_matrix const &); \ + template VNL_EXPORT vnl_matrix> vnl_complexify(vnl_matrix const &, vnl_matrix const &); \ + template VNL_EXPORT vnl_diag_matrix> vnl_complexify(vnl_diag_matrix const &); \ + template VNL_EXPORT vnl_diag_matrix> vnl_complexify(vnl_diag_matrix const &, \ + vnl_diag_matrix const &); \ + template VNL_EXPORT vnl_sym_matrix> vnl_complexify(vnl_sym_matrix const &); \ + template VNL_EXPORT vnl_sym_matrix> vnl_complexify(vnl_sym_matrix const &, \ + vnl_sym_matrix const &); \ + \ + template VNL_EXPORT void vnl_real(std::complex const *, T *, unsigned int); \ + template VNL_EXPORT void vnl_imag(std::complex const *, T *, unsigned int); \ + \ + template VNL_EXPORT vnl_vector vnl_real(vnl_vector> const &); \ + template VNL_EXPORT vnl_vector vnl_imag(vnl_vector> const &); \ + \ + template VNL_EXPORT vnl_matrix vnl_real(vnl_matrix> const &); \ + template VNL_EXPORT vnl_matrix vnl_imag(vnl_matrix> const &); \ + \ + template VNL_EXPORT vnl_diag_matrix vnl_real(vnl_diag_matrix> const &); \ + template VNL_EXPORT vnl_diag_matrix vnl_imag(vnl_diag_matrix> const &); \ + \ + template VNL_EXPORT vnl_sym_matrix vnl_real(vnl_sym_matrix> const &); \ + template VNL_EXPORT vnl_sym_matrix vnl_imag(vnl_sym_matrix> const &) #endif // vnl_complex_ops_hxx_ diff --git a/core/vnl/vnl_complex_traits.h b/core/vnl/vnl_complex_traits.h index 992db22fe13..6623092a321 100644 --- a/core/vnl/vnl_complex_traits.h +++ b/core/vnl/vnl_complex_traits.h @@ -22,102 +22,234 @@ template // the primary template is empty, by design. struct vnl_complex_traits; #define VCL_DEFINE_SPECIALIZATION_MACRO(T) \ -template <> struct VNL_EXPORT vnl_complex_traits \ -{ \ - enum { isreal = true }; \ - static T conjugate(T x) { return x; } \ - static std::complex complexify(T x) { return std::complex(x, (T)0); } \ -} + template <> \ + struct VNL_EXPORT vnl_complex_traits \ + { \ + enum \ + { \ + isreal = true \ + }; \ + static T \ + conjugate(T x) \ + { \ + return x; \ + } \ + static std::complex \ + complexify(T x) \ + { \ + return std::complex(x, (T)0); \ + } \ + } #define VCL_DEFINE_SPECIALIZATION_MACRO_SIGNED_UNSIGNED(T) \ -VCL_DEFINE_SPECIALIZATION_MACRO(signed T); \ -VCL_DEFINE_SPECIALIZATION_MACRO(unsigned T) + VCL_DEFINE_SPECIALIZATION_MACRO(signed T); \ + VCL_DEFINE_SPECIALIZATION_MACRO(unsigned T) VCL_DEFINE_SPECIALIZATION_MACRO_SIGNED_UNSIGNED(char); VCL_DEFINE_SPECIALIZATION_MACRO_SIGNED_UNSIGNED(short); VCL_DEFINE_SPECIALIZATION_MACRO_SIGNED_UNSIGNED(int); VCL_DEFINE_SPECIALIZATION_MACRO_SIGNED_UNSIGNED(long); -//long long - target type will have width of at least 64 bits. (since C++11) +// long long - target type will have width of at least 64 bits. (since C++11) VCL_DEFINE_SPECIALIZATION_MACRO_SIGNED_UNSIGNED(long long); -//3.9.1 Fundamental types [basic.fundamental] -//Plain char, signed char, and unsigned char are three distinct types -// We must explicitly instantiate the char type without signed/unsigned prefix +// 3.9.1 Fundamental types [basic.fundamental] +// Plain char, signed char, and unsigned char are three distinct types +// We must explicitly instantiate the char type without signed/unsigned prefix VCL_DEFINE_SPECIALIZATION_MACRO(char); #undef VCL_DEFINE_SPECIALIZATION_MACRO_SIGNED_UNSIGNED #undef VCL_DEFINE_SPECIALIZATION_MACRO -template <> struct VNL_EXPORT vnl_complex_traits +template <> +struct VNL_EXPORT vnl_complex_traits { - enum { isreal = true }; - static float conjugate(float x) { return x; } - static std::complex complexify(float x) { return {x, 0.0f}; } + enum + { + isreal = true + }; + static float + conjugate(float x) + { + return x; + } + static std::complex + complexify(float x) + { + return { x, 0.0f }; + } }; -template <> struct VNL_EXPORT vnl_complex_traits +template <> +struct VNL_EXPORT vnl_complex_traits { - enum { isreal = true }; - static double conjugate(double x) { return x; } - static std::complex complexify(double x) { return {x, 0.0}; } + enum + { + isreal = true + }; + static double + conjugate(double x) + { + return x; + } + static std::complex + complexify(double x) + { + return { x, 0.0 }; + } }; -template <> struct VNL_EXPORT vnl_complex_traits +template <> +struct VNL_EXPORT vnl_complex_traits { - enum { isreal = true }; - static long double conjugate(long double x) { return x; } - static std::complex complexify(long double x) { return {x, 0.0}; } + enum + { + isreal = true + }; + static long double + conjugate(long double x) + { + return x; + } + static std::complex + complexify(long double x) + { + return { x, 0.0 }; + } }; -template <> struct VNL_EXPORT vnl_complex_traits > +template <> +struct VNL_EXPORT vnl_complex_traits> { - enum { isreal = false }; - static std::complex conjugate(std::complex x) { return std::conj(x); } - static std::complex complexify(float x) { return x; } + enum + { + isreal = false + }; + static std::complex + conjugate(std::complex x) + { + return std::conj(x); + } + static std::complex + complexify(float x) + { + return x; + } }; -template <> struct VNL_EXPORT vnl_complex_traits > +template <> +struct VNL_EXPORT vnl_complex_traits> { - enum { isreal = false }; - static std::complex conjugate(std::complex x) { return std::conj(x); } - static std::complex complexify(double x) { return x; } + enum + { + isreal = false + }; + static std::complex + conjugate(std::complex x) + { + return std::conj(x); + } + static std::complex + complexify(double x) + { + return x; + } }; -template <> struct VNL_EXPORT vnl_complex_traits > +template <> +struct VNL_EXPORT vnl_complex_traits> { - enum { isreal = false }; - static std::complex conjugate(std::complex x) { return std::conj(x); } - static std::complex complexify(long double x) { return x; } + enum + { + isreal = false + }; + static std::complex + conjugate(std::complex x) + { + return std::conj(x); + } + static std::complex + complexify(long double x) + { + return x; + } }; #include "vnl_bignum.h" -template <> struct VNL_EXPORT vnl_complex_traits +template <> +struct VNL_EXPORT vnl_complex_traits { - enum { isreal = true }; - static vnl_bignum conjugate(vnl_bignum x) { return x; } - static std::complex complexify(vnl_bignum x) { return std::complex(x,vnl_bignum(0L)); } + enum + { + isreal = true + }; + static vnl_bignum + conjugate(vnl_bignum x) + { + return x; + } + static std::complex + complexify(vnl_bignum x) + { + return std::complex(x, vnl_bignum(0L)); + } }; -template <> struct VNL_EXPORT vnl_complex_traits > +template <> +struct VNL_EXPORT vnl_complex_traits> { - enum { isreal = false }; - static std::complex conjugate(std::complex x) { return std::complex(x.real(),-x.imag()); } - static std::complex complexify(std::complex x) { return x; } + enum + { + isreal = false + }; + static std::complex + conjugate(std::complex x) + { + return std::complex(x.real(), -x.imag()); + } + static std::complex + complexify(std::complex x) + { + return x; + } }; #include "vnl_rational.h" -template <> struct VNL_EXPORT vnl_complex_traits +template <> +struct VNL_EXPORT vnl_complex_traits { - enum { isreal = true }; - static vnl_rational conjugate(vnl_rational x) { return x; } - static std::complex complexify(vnl_rational x) { return std::complex(x, vnl_rational(0,1)); } + enum + { + isreal = true + }; + static vnl_rational + conjugate(vnl_rational x) + { + return x; + } + static std::complex + complexify(vnl_rational x) + { + return std::complex(x, vnl_rational(0, 1)); + } }; -template <> struct VNL_EXPORT vnl_complex_traits > +template <> +struct VNL_EXPORT vnl_complex_traits> { - enum { isreal = false }; - static std::complex conjugate(std::complex x) {return std::complex(x.real(),-x.imag());} - static std::complex complexify(std::complex x) { return x; } + enum + { + isreal = false + }; + static std::complex + conjugate(std::complex x) + { + return std::complex(x.real(), -x.imag()); + } + static std::complex + complexify(std::complex x) + { + return x; + } }; #endif // vnl_complex_traits_h_ diff --git a/core/vnl/vnl_complexify.h b/core/vnl/vnl_complexify.h index 96635da6cee..e27eca1c02e 100644 --- a/core/vnl/vnl_complexify.h +++ b/core/vnl/vnl_complexify.h @@ -25,13 +25,13 @@ #include "vnl/vnl_export.h" //: Overwrite complex array C (of length n) with pairs from real arrays R and I. -template VNL_EXPORT -void - vnl_complexify(T const* R, T const* I, std::complex* C, unsigned n); +template +VNL_EXPORT void +vnl_complexify(const T * R, const T * I, std::complex * C, unsigned n); //: Overwrite complex array C (sz n) with complexified version of real array R. -template VNL_EXPORT -void - vnl_complexify(T const* R, std::complex* C, unsigned n); +template +VNL_EXPORT void +vnl_complexify(const T * R, std::complex * C, unsigned n); // Real Alone: // - vnl_vector @@ -44,69 +44,69 @@ void //: Return complexified version of real vector R. // \relatesalso vnl_vector -template VNL_EXPORT -vnl_vector > - vnl_complexify(vnl_vector const& R); +template +VNL_EXPORT vnl_vector> +vnl_complexify(const vnl_vector & R); -template VNL_EXPORT -vnl_vector_fixed, n> -vnl_complexify(vnl_vector_fixed const& R); +template +VNL_EXPORT vnl_vector_fixed, n> +vnl_complexify(const vnl_vector_fixed & R); //: Return complexified version of real fixed vector R. // \relatesalso vnl_vector_fixed template -vnl_vector_fixed,n> - vnl_complexify(vnl_vector_fixed const& R) +vnl_vector_fixed, n> +vnl_complexify(const vnl_vector_fixed & R) { - vnl_vector_fixed,n> C; + vnl_vector_fixed, n> C; vnl_complexify(R.begin(), C.begin(), R.size()); return C; } //: Return complexified version of real matrix R. // \relatesalso vnl_matrix -template VNL_EXPORT -vnl_matrix > - vnl_complexify(vnl_matrix const& R); +template +VNL_EXPORT vnl_matrix> +vnl_complexify(const vnl_matrix & R); //: Return complexified version of real fixed matrix R. // \relatesalso vnl_matrix_fixed -template VNL_EXPORT -vnl_matrix_fixed, r, c > -vnl_complexify(vnl_matrix_fixed const& R); +template +VNL_EXPORT vnl_matrix_fixed, r, c> +vnl_complexify(const vnl_matrix_fixed & R); template -vnl_matrix_fixed,r,c > - vnl_complexify(vnl_matrix_fixed const& R) +vnl_matrix_fixed, r, c> +vnl_complexify(const vnl_matrix_fixed & R) { - vnl_matrix_fixed,r,c> C; + vnl_matrix_fixed, r, c> C; vnl_complexify(R.begin(), C.begin(), R.size()); return C; } //: Return complexified version of real diagonal matrix R. // \relatesalso vnl_diag_matrix -template VNL_EXPORT -vnl_diag_matrix > - vnl_complexify(vnl_diag_matrix const& R); +template +VNL_EXPORT vnl_diag_matrix> +vnl_complexify(const vnl_diag_matrix & R); //: Return complexified version of real fixed diagonal matrix R. // \relatesalso vnl_diag_matrix_fixed template -vnl_diag_matrix_fixed,n > - vnl_complexify(vnl_diag_matrix_fixed const& R) +vnl_diag_matrix_fixed, n> +vnl_complexify(const vnl_diag_matrix_fixed & R) { - vnl_diag_matrix_fixed,n> C; + vnl_diag_matrix_fixed, n> C; vnl_complexify(R.begin(), C.begin(), R.size()); return C; } //: Return complexified version of real symmetric matrix R. // \relatesalso vnl_sym_matrix -template VNL_EXPORT -vnl_sym_matrix > - vnl_complexify(vnl_sym_matrix const& R); +template +VNL_EXPORT vnl_sym_matrix> +vnl_complexify(const vnl_sym_matrix & R); //---------------------------------------------------------------------- @@ -121,59 +121,59 @@ vnl_sym_matrix > //: Return complex vector R+j*I from two real vectors R and I. // \relatesalso vnl_vector -template VNL_EXPORT -vnl_vector > - vnl_complexify(vnl_vector const& R, vnl_vector const& I); +template +VNL_EXPORT vnl_vector> +vnl_complexify(const vnl_vector & R, const vnl_vector & I); //: Return complex fixed vector R+j*I from two real fixed vectors R and I. // \relatesalso vnl_vector_fixed template -vnl_vector_fixed,n > - vnl_complexify(vnl_vector_fixed const& R, vnl_vector_fixed const& I) +vnl_vector_fixed, n> +vnl_complexify(const vnl_vector_fixed & R, const vnl_vector_fixed & I) { - vnl_vector_fixed,n > C; + vnl_vector_fixed, n> C; vnl_complexify(R.begin(), I.begin(), C.begin(), R.size()); return C; } //: Return complex matrix R+j*I from two real matrices R and I. // \relatesalso vnl_matrix -template VNL_EXPORT -vnl_matrix > - vnl_complexify(vnl_matrix const& R, vnl_matrix const& I); +template +VNL_EXPORT vnl_matrix> +vnl_complexify(const vnl_matrix & R, const vnl_matrix & I); //: Return complex fixed matrix R+j*I from two real fixed matrices R and I. // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed,r,c> - vnl_complexify(vnl_matrix_fixed const& R, vnl_matrix_fixed const& I) +vnl_matrix_fixed, r, c> +vnl_complexify(const vnl_matrix_fixed & R, const vnl_matrix_fixed & I) { - vnl_matrix_fixed,r,c > C; + vnl_matrix_fixed, r, c> C; vnl_complexify(R.begin(), I.begin(), C.begin(), R.size()); return C; } //: Return complex diagonal matrix R+j*I from two real diagonal matrices R and I. // \relatesalso vnl_diag_matrix -template VNL_EXPORT -vnl_diag_matrix > - vnl_complexify(vnl_diag_matrix const& R, vnl_diag_matrix const& I); +template +VNL_EXPORT vnl_diag_matrix> +vnl_complexify(const vnl_diag_matrix & R, const vnl_diag_matrix & I); //: Return complex fixed diagonal matrix R+j*I from two real fixed diagonal matrices R and I. // \relatesalso vnl_matrix_fixed template -vnl_diag_matrix_fixed,n> - vnl_complexify(vnl_diag_matrix_fixed const& R, vnl_diag_matrix_fixed const& I) +vnl_diag_matrix_fixed, n> +vnl_complexify(const vnl_diag_matrix_fixed & R, const vnl_diag_matrix_fixed & I) { - vnl_diag_matrix_fixed,n > C; + vnl_diag_matrix_fixed, n> C; vnl_complexify(R.begin(), I.begin(), C.begin(), R.size()); return C; } //: Return complex diagonal matrix R+j*I from two real diagonal matrices R and I. // \relatesalso vnl_diag_matrix -template VNL_EXPORT -vnl_sym_matrix > - vnl_complexify(vnl_sym_matrix const& R, vnl_sym_matrix const& I); +template +VNL_EXPORT vnl_sym_matrix> +vnl_complexify(const vnl_sym_matrix & R, const vnl_sym_matrix & I); #endif // vnl_complexify_h_ diff --git a/core/vnl/vnl_copy.cxx b/core/vnl/vnl_copy.cxx index eeefdc706fe..1f6a5765c9e 100644 --- a/core/vnl/vnl_copy.cxx +++ b/core/vnl/vnl_copy.cxx @@ -13,7 +13,7 @@ template void -vnl_copy(S const * const src, T * const dst, const unsigned n) +vnl_copy(const S * const src, T * const dst, const unsigned n) { for (unsigned int i = 0; i < n; ++i) dst[i] = T(src[i]); @@ -21,7 +21,7 @@ vnl_copy(S const * const src, T * const dst, const unsigned n) template void -vnl_copy(S const & src, T & dst) +vnl_copy(const S & src, T & dst) { assert(src.size() == dst.size()); vnl_copy(src.begin(), dst.begin(), src.size()); @@ -39,12 +39,12 @@ VNL_COPY_INSTANTIATE0(double, long double); VNL_COPY_INSTANTIATE0(long double, double); #endif -#define vnl_copy_macro(S, D) \ - template <> \ - VNL_EXPORT void vnl_copy(std::complex const * const src, std::complex * const dst, const unsigned n) \ - { \ - for (unsigned int i = 0; i < n; ++i) \ - dst[i] = std::complex((D)std::real(src[i]), (D)std::imag(src[i])); \ +#define vnl_copy_macro(S, D) \ + template <> \ + VNL_EXPORT void vnl_copy(std::complex const * const src, std::complex * const dst, const unsigned n) \ + { \ + for (unsigned int i = 0; i < n; ++i) \ + dst[i] = std::complex((D)std::real(src[i]), (D)std::imag(src[i])); \ } vnl_copy_macro(float, double); @@ -53,12 +53,12 @@ vnl_copy_macro(double, long double); vnl_copy_macro(long double, double); #undef vnl_copy_macro -#define vnl_copy_dumb(S) \ - template <> \ - VNL_EXPORT void vnl_copy(S const * const src, S * const dst, const unsigned n) \ - { \ - for (unsigned int i = 0; i < n; ++i) \ - dst[i] = src[i]; \ +#define vnl_copy_dumb(S) \ + template <> \ + VNL_EXPORT void vnl_copy(S const * const src, S * const dst, const unsigned n) \ + { \ + for (unsigned int i = 0; i < n; ++i) \ + dst[i] = src[i]; \ } vnl_copy_dumb(float); @@ -66,16 +66,16 @@ vnl_copy_dumb(double); #undef vnl_copy_dumb // vnl_* containers -#define VNL_COPY_INSTANTIATE(S, T) \ - template VNL_EXPORT void vnl_copy(vnl_vector const &, vnl_vector &); \ - template VNL_EXPORT void vnl_copy(vnl_matrix const &, vnl_matrix &); \ +#define VNL_COPY_INSTANTIATE(S, T) \ + template VNL_EXPORT void vnl_copy(vnl_vector const &, vnl_vector &); \ + template VNL_EXPORT void vnl_copy(vnl_matrix const &, vnl_matrix &); \ template VNL_EXPORT void vnl_copy(vnl_diag_matrix const &, vnl_diag_matrix &) VNL_COPY_INSTANTIATE(float, float); VNL_COPY_INSTANTIATE(double, double); -#define VNL_COPY_INSTANTIATE_twoway(S, T) \ - VNL_COPY_INSTANTIATE(S, T); \ +#define VNL_COPY_INSTANTIATE_twoway(S, T) \ + VNL_COPY_INSTANTIATE(S, T); \ VNL_COPY_INSTANTIATE(T, S) VNL_COPY_INSTANTIATE_twoway(float, double); diff --git a/core/vnl/vnl_copy.h b/core/vnl/vnl_copy.h index 4ad348219dc..0f0f605d061 100644 --- a/core/vnl/vnl_copy.h +++ b/core/vnl/vnl_copy.h @@ -15,14 +15,16 @@ //: Easy conversion between vectors and matrices templated over different types. // \relatesalso vnl_matrix // \relatesalso vnl_vector -template VNL_EXPORT -void vnl_copy(S const * const src, T *const dst, const unsigned n); +template +VNL_EXPORT void +vnl_copy(const S * const src, T * const dst, const unsigned n); //: Easy conversion between vectors and matrices templated over different types. // \relatesalso vnl_matrix // \relatesalso vnl_vector -template VNL_EXPORT -void vnl_copy(S const &, T &); +template +VNL_EXPORT void +vnl_copy(const S &, T &); #endif // vnl_copy_h_ diff --git a/core/vnl/vnl_cost_function.cxx b/core/vnl/vnl_cost_function.cxx index 3fb22b8e3d8..c5bd589dd89 100644 --- a/core/vnl/vnl_cost_function.cxx +++ b/core/vnl/vnl_cost_function.cxx @@ -12,7 +12,7 @@ static bool f_calling_compute; void -vnl_cost_function::compute(vnl_vector const & x, double * val, vnl_vector * g) +vnl_cost_function::compute(const vnl_vector & x, double * val, vnl_vector * g) { if (val) *val = this->f(x); @@ -22,7 +22,7 @@ vnl_cost_function::compute(vnl_vector const & x, double * val, vnl_vecto //: Default implementation of f is compute... double -vnl_cost_function::f(vnl_vector const & x) +vnl_cost_function::f(const vnl_vector & x) { // if we get back here from compute, neither vf was implemented. if (f_calling_compute) @@ -36,7 +36,7 @@ vnl_cost_function::f(vnl_vector const & x) //: Default implementation of gradf is to call compute void -vnl_cost_function::gradf(vnl_vector const & x, vnl_vector & g) +vnl_cost_function::gradf(const vnl_vector & x, vnl_vector & g) { if (f_calling_compute) assert(!"vnl_cost_function: RECURSION"); @@ -47,19 +47,19 @@ vnl_cost_function::gradf(vnl_vector const & x, vnl_vector & g) //: Compute fd gradient void -vnl_cost_function::fdgradf(vnl_vector const & x, vnl_vector & gradient, double stepsize) +vnl_cost_function::fdgradf(const vnl_vector & x, vnl_vector & gradient, double stepsize) { vnl_vector tx = x; - double h = stepsize; + const double h = stepsize; for (int i = 0; i < dim; ++i) { - double tplus = x[i] + h; + const double tplus = x[i] + h; tx[i] = tplus; - double fplus = this->f(tx); + const double fplus = this->f(tx); - double tminus = x[i] - h; + const double tminus = x[i] - h; tx[i] = tminus; - double fminus = this->f(tx); + const double fminus = this->f(tx); gradient[i] = (fplus - fminus) / (tplus - tminus); tx[i] = x[i]; @@ -67,7 +67,7 @@ vnl_cost_function::fdgradf(vnl_vector const & x, vnl_vector & gr } vnl_vector -vnl_cost_function::gradf(vnl_vector const & x) +vnl_cost_function::gradf(const vnl_vector & x) { vnl_vector g(dim); this->gradf(x, g); @@ -75,7 +75,7 @@ vnl_cost_function::gradf(vnl_vector const & x) } vnl_vector -vnl_cost_function::fdgradf(vnl_vector const & x) +vnl_cost_function::fdgradf(const vnl_vector & x) { vnl_vector g(dim); this->fdgradf(x, g); diff --git a/core/vnl/vnl_cost_function.h b/core/vnl/vnl_cost_function.h index 7ef5ab17db5..07987878be3 100644 --- a/core/vnl/vnl_cost_function.h +++ b/core/vnl/vnl_cost_function.h @@ -23,53 +23,68 @@ //: An object that represents a function from R^n -> R. // It is commonly used to express the // interface of a minimizer. -class VNL_EXPORT vnl_cost_function : public vnl_unary_function > +class VNL_EXPORT vnl_cost_function : public vnl_unary_function> { - public: - +public: //! Default constructor - vnl_cost_function() = default; + vnl_cost_function() = default; - //! Construct with a specified number of unknowns - vnl_cost_function(int number_of_unknowns) : dim(number_of_unknowns) {} + //! Construct with a specified number of unknowns + vnl_cost_function(int number_of_unknowns) + : dim(number_of_unknowns) + {} - ~vnl_cost_function() override = default; + ~vnl_cost_function() override = default; - //: The main function. Given the parameter vector x, compute the value of - //f(x). - double f(vnl_vector const &x) override; + //: The main function. Given the parameter vector x, compute the value of + // f(x). + double + f(const vnl_vector & x) override; - //: Calculate the gradient of f at parameter vector x. - virtual void gradf(vnl_vector const &x, - vnl_vector &gradient); + //: Calculate the gradient of f at parameter vector x. + virtual void + gradf(const vnl_vector & x, vnl_vector & gradient); - //: Compute one or both of f and g. - // Normally implemented in terms of the above two, but may be faster if - // specialized. f != 0 => compute f - virtual void compute(vnl_vector const &x, double *f, - vnl_vector *g); + //: Compute one or both of f and g. + // Normally implemented in terms of the above two, but may be faster if + // specialized. f != 0 => compute f + virtual void + compute(const vnl_vector & x, double * f, vnl_vector * g); - //: Return the number of unknowns - int get_number_of_unknowns() const { return dim; } + //: Return the number of unknowns + int + get_number_of_unknowns() const + { + return dim; + } - //: Compute finite-difference gradient - void fdgradf(vnl_vector const &x, vnl_vector &gradient, - double stepsize = 1e-5); + //: Compute finite-difference gradient + void + fdgradf(const vnl_vector & x, vnl_vector & gradient, double stepsize = 1e-5); - //: Called when error is printed for user. - virtual double reported_error(double f_value) { return f_value; } + //: Called when error is printed for user. + virtual double + reported_error(double f_value) + { + return f_value; + } - //: Conveniences for printing grad, fdgrad - vnl_vector gradf(vnl_vector const &x); - vnl_vector fdgradf(vnl_vector const &x); + //: Conveniences for printing grad, fdgrad + vnl_vector + gradf(const vnl_vector & x); + vnl_vector + fdgradf(const vnl_vector & x); - protected: - //! Set number of unknowns. - void set_number_of_unknowns(int number_of_unknowns) { - dim = number_of_unknowns; } +protected: + //! Set number of unknowns. + void + set_number_of_unknowns(int number_of_unknowns) + { + dim = number_of_unknowns; + } public: - int dim{0}; + int dim{ 0 }; }; #endif // vnl_cost_function_h_ diff --git a/core/vnl/vnl_cross.h b/core/vnl/vnl_cross.h index 2861914439f..29ab060d663 100644 --- a/core/vnl/vnl_cross.h +++ b/core/vnl/vnl_cross.h @@ -19,19 +19,19 @@ //: Compute the 2-D cross product // \relatesalso vnl_vector -template +template inline T -vnl_cross_2d( const vnl_vector& v1, const vnl_vector& v2 ) +vnl_cross_2d(const vnl_vector & v1, const vnl_vector & v2) { - assert( v1.size() >= 2 && v2.size() >= 2 ); + assert(v1.size() >= 2 && v2.size() >= 2); return v1[0] * v2[1] - v1[1] * v2[0]; } //: Compute the 2-D cross product // \relatesalso vnl_vector_fixed -template +template inline T -vnl_cross_2d( const vnl_vector_fixed& v1, const vnl_vector_fixed& v2 ) +vnl_cross_2d(const vnl_vector_fixed & v1, const vnl_vector_fixed & v2) { return v1[0] * v2[1] - v1[1] * v2[0]; } @@ -39,32 +39,32 @@ vnl_cross_2d( const vnl_vector_fixed& v1, const vnl_vector_fixed& v2 ) //: Compute the 2-D cross product // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template +template inline T -vnl_cross_2d(vnl_vector_fixed const& v1, vnl_vector const& v2) +vnl_cross_2d(const vnl_vector_fixed & v1, const vnl_vector & v2) { - assert( v2.size() == 2 ); + assert(v2.size() == 2); return v1[0] * v2[1] - v1[1] * v2[0]; } //: Compute the 2-D cross product // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template +template inline T -vnl_cross_2d(vnl_vector const& v1, vnl_vector_fixed const& v2) +vnl_cross_2d(const vnl_vector & v1, const vnl_vector_fixed & v2) { - assert( v1.size() == 2 ); + assert(v1.size() == 2); return v1[0] * v2[1] - v1[1] * v2[0]; } //: Compute the 3-D cross product // \relatesalso vnl_vector -template +template inline vnl_vector -vnl_cross_3d( const vnl_vector& v1, const vnl_vector& v2 ) +vnl_cross_3d(const vnl_vector & v1, const vnl_vector & v2) { - assert( v1.size() == 3 && v2.size() == 3 ); + assert(v1.size() == 3 && v2.size() == 3); vnl_vector result(3); result[0] = v1[1] * v2[2] - v1[2] * v2[1]; // work for both col/row result[1] = v1[2] * v2[0] - v1[0] * v2[2]; // representation @@ -74,11 +74,11 @@ vnl_cross_3d( const vnl_vector& v1, const vnl_vector& v2 ) //: Compute the 3-D cross product // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed -vnl_cross_3d( const vnl_vector_fixed& v1, const vnl_vector_fixed& v2 ) +template +inline vnl_vector_fixed +vnl_cross_3d(const vnl_vector_fixed & v1, const vnl_vector_fixed & v2) { - vnl_vector_fixed result; + vnl_vector_fixed result; result[0] = v1[1] * v2[2] - v1[2] * v2[1]; // work for both col/row result[1] = v1[2] * v2[0] - v1[0] * v2[2]; // representation result[2] = v1[0] * v2[1] - v1[1] * v2[0]; @@ -88,9 +88,9 @@ vnl_cross_3d( const vnl_vector_fixed& v1, const vnl_vector_fixed& v2 ) //: Compute the 3-D cross product // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed -vnl_cross_3d( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline vnl_vector_fixed +vnl_cross_3d(const vnl_vector_fixed & a, const vnl_vector & b) { return vnl_cross_3d(a.as_ref(), b); } @@ -98,9 +98,9 @@ vnl_cross_3d( const vnl_vector_fixed& a, const vnl_vector& b ) //: Compute the 3-D cross product // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed -vnl_cross_3d( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline vnl_vector_fixed +vnl_cross_3d(const vnl_vector & a, const vnl_vector_fixed & b) { return vnl_cross_3d(a, b.as_ref()); } diff --git a/core/vnl/vnl_cross_product_matrix.h b/core/vnl/vnl_cross_product_matrix.h index 2e6b3ac2c2a..3402af3e573 100644 --- a/core/vnl/vnl_cross_product_matrix.h +++ b/core/vnl/vnl_cross_product_matrix.h @@ -30,33 +30,38 @@ // \endverbatim class vnl_cross_product_matrix : public vnl_double_3x3 { - public: +public: typedef vnl_double_3x3 base; - vnl_cross_product_matrix(vnl_vector_fixed const& v) { set(v.data_block()); } - vnl_cross_product_matrix(vnl_vector const& v) { set(v.data_block()); } - vnl_cross_product_matrix(const double* v) { set(v); } - vnl_cross_product_matrix(vnl_cross_product_matrix const& that) = default; - ~vnl_cross_product_matrix() = default; + vnl_cross_product_matrix(const vnl_vector_fixed & v) { set(v.data_block()); } + vnl_cross_product_matrix(const vnl_vector & v) { set(v.data_block()); } + vnl_cross_product_matrix(const double * v) { set(v); } + vnl_cross_product_matrix(const vnl_cross_product_matrix & that) = default; + ~vnl_cross_product_matrix() = default; - vnl_cross_product_matrix& operator=(const vnl_cross_product_matrix& that) { - base::operator= (that); - return *this; - } + vnl_cross_product_matrix & + operator=(const vnl_cross_product_matrix & that) = default; //: Construct a vnl_cross_product_matrix from a C-array of 3 doubles. // Overrides a method in vnl_matrix. - inline vnl_cross_product_matrix& set(const double* v) + inline vnl_cross_product_matrix & + set(const double * v) { - double const& e1 = v[0]; - double const& e2 = v[1]; - double const& e3 = v[2]; + const double & e1 = v[0]; + const double & e2 = v[1]; + const double & e3 = v[2]; vnl_cross_product_matrix & E = *this; - E(0,0) = 0; E(0,1) = -e3; E(0,2) = e2; - E(1,0) = e3; E(1,1) = 0; E(1,2) = -e1; - E(2,0) = -e2; E(2,1) = e1; E(2,2) = 0; + E(0, 0) = 0; + E(0, 1) = -e3; + E(0, 2) = e2; + E(1, 0) = e3; + E(1, 1) = 0; + E(1, 2) = -e1; + E(2, 0) = -e2; + E(2, 1) = e1; + E(2, 2) = 0; return *this; } diff --git a/core/vnl/vnl_crs_index.cxx b/core/vnl/vnl_crs_index.cxx index 13239c1988a..055e6645e93 100644 --- a/core/vnl/vnl_crs_index.cxx +++ b/core/vnl/vnl_crs_index.cxx @@ -44,7 +44,7 @@ vnl_crs_index::operator()(int i, int j) const if (j < col_idx_[low] || j > col_idx_[high]) return -1; // element is zero (no index) - int mid = (low + high) >> 1; //(low+high)/2; + const int mid = (low + high) >> 1; //(low+high)/2; if (j < (int)col_idx_[mid]) high = mid - 1; else if (j > (int)col_idx_[mid]) @@ -64,7 +64,7 @@ vnl_crs_index::sparse_row(int i) const sparse_vector row; for (int j = row_ptr_[i]; j < row_ptr_[i + 1]; ++j) { - row.push_back(idx_pair(j, col_idx_[j])); + row.emplace_back(j, col_idx_[j]); } return row; } @@ -78,9 +78,9 @@ vnl_crs_index::sparse_col(int j) const sparse_vector col; for (int i = 0; i < num_rows(); ++i) { - int idx = (*this)(i, j); + const int idx = (*this)(i, j); if (idx >= 0) - col.push_back(idx_pair(idx, i)); + col.emplace_back(idx, i); } return col; diff --git a/core/vnl/vnl_crs_index.h b/core/vnl/vnl_crs_index.h index 6c07c84989b..f773c3e5a46 100644 --- a/core/vnl/vnl_crs_index.h +++ b/core/vnl/vnl_crs_index.h @@ -25,46 +25,64 @@ // share a common sparse structure. class VNL_EXPORT vnl_crs_index { - public: - typedef std::pair idx_pair; +public: + typedef std::pair idx_pair; typedef std::vector sparse_vector; //: Constructor - default - vnl_crs_index() : col_idx_(), row_ptr_() {} + vnl_crs_index() + : col_idx_() + , row_ptr_() + {} //: Constructor - from a binary mask - vnl_crs_index(const std::vector >& mask); + vnl_crs_index(const std::vector> & mask); //: Destructor - ~vnl_crs_index()= default; + ~vnl_crs_index() = default; //: number of rows in the sparse matrix - int num_rows() const { return int(row_ptr_.size())-1; } + int + num_rows() const + { + return int(row_ptr_.size()) - 1; + } //: number of columns in the sparse matrix - int num_cols() const { return num_cols_; } + int + num_cols() const + { + return num_cols_; + } //: number of non-zero elements - int num_non_zero() const { return int(col_idx_.size()); } + int + num_non_zero() const + { + return int(col_idx_.size()); + } //: returns row \p i as a vector of index-column pairs - sparse_vector sparse_row(int i) const; + sparse_vector + sparse_row(int i) const; //: returns column \p j as a vector of index-row pairs // \note because of CRS this method is a bit less efficient than sparse_row - sparse_vector sparse_col(int j) const; + sparse_vector + sparse_col(int j) const; //: return the index at location (i,j) // returns -1 if the entry is 0 - int operator() (int i, int j) const; + int + operator()(int i, int j) const; - private: +private: //: The number of columns in the matrix - unsigned int num_cols_{0}; - //: The column for each non-zero element - std::vector col_idx_; - //: The index of the first non-zero element in each row - std::vector row_ptr_; + unsigned int num_cols_{ 0 }; + //: The column for each non-zero element + std::vector col_idx_; + //: The index of the first non-zero element in each row + std::vector row_ptr_; }; #endif // vnl_crs_index_h_ diff --git a/core/vnl/vnl_decnum.cxx b/core/vnl/vnl_decnum.cxx index 9c4ab6556a2..78a21bdfb79 100644 --- a/core/vnl/vnl_decnum.cxx +++ b/core/vnl/vnl_decnum.cxx @@ -12,13 +12,13 @@ // * If the mantissa contains a decimal point, it is ignored (but the exponent is adapted accordingly). // Alternatively, the input might also be "NaN", "Inf", "+Inf", or "-Inf". // See also operator>>(std::istream& s, vnl_decnum& r). -vnl_decnum::vnl_decnum(std::string const & r) +vnl_decnum::vnl_decnum(const std::string & r) : sign_('+') , data_("") - , exp_(0L) + { long exp = 0L; - char const * p = r.c_str(); + const char * p = r.c_str(); while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') ++p; if (*p == '-') @@ -78,7 +78,7 @@ vnl_decnum::vnl_decnum(std::string const & r) vnl_decnum::vnl_decnum(unsigned long r) : sign_('+') , data_("") - , exp_(0L) + { if (r == 0) sign_ = ' '; @@ -145,7 +145,7 @@ vnl_decnum::operator unsigned long() const l *= 10; if (i < long(data_.length())) l += (data_.c_str()[i] - '0'); - } // might overflow!!! + } // might overflow!!! return l; // forget the sign } @@ -179,7 +179,7 @@ vnl_decnum::operator unsigned int() const l *= 10; if (i < long(data_.length())) l += (data_.c_str()[i] - '0'); - } // might overflow!!! + } // might overflow!!! return l; // forget the sign } @@ -202,7 +202,7 @@ vnl_decnum::operator int() const } bool -vnl_decnum::operator==(vnl_decnum const & r) const +vnl_decnum::operator==(const vnl_decnum & r) const { // quick return if exponents are identical or signs are different: if (sign_ != r.sign()) @@ -232,12 +232,15 @@ vnl_decnum::operator==(vnl_decnum const & r) const // The arguments should consist of digits only (interpreted as mantissas with the same exponent). // The shorter of the two arguments is implicitly zero-padded. bool -vnl_decnum::comp(std::string const & a, std::string const & b) +vnl_decnum::comp(const std::string & a, const std::string & b) { #ifdef DEBUG std::cerr << "Entering vnl_decnum::comp with " << a << " and " << b << '\n'; #endif - int i, na = int(a.length()), nb = int(b.length()), nc = na < nb ? na : nb; + int i; + const int na = int(a.length()); + const int nb = int(b.length()); + const int nc = na < nb ? na : nb; for (i = 0; i < nc; ++i) { if (a.c_str()[i] < b.c_str()[i]) @@ -254,12 +257,12 @@ vnl_decnum::comp(std::string const & a, std::string const & b) } bool -vnl_decnum::operator<(vnl_decnum const & r) const +vnl_decnum::operator<(const vnl_decnum & r) const { #ifdef DEBUG std::cerr << "Entering vnl_decnum::operator< with " << data_ << " and " << r.data() << '\n'; #endif - std::string rs = r.data(); + std::string const rs = r.data(); if (data_ == "NaN" || rs == "NaN") return false; // NaN compares to nothing! else if (operator==(r)) @@ -291,13 +294,15 @@ vnl_decnum::operator<(vnl_decnum const & r) const // Both arguments should consist of digits only. // The third argument will be the exponent of the result. vnl_decnum -vnl_decnum::plus(std::string const & a, std::string const & b, long exp) +vnl_decnum::plus(const std::string & a, const std::string & b, long exp) { #ifdef DEBUG std::cerr << "Entering vnl_decnum::plus with " << a << " and " << b << '\n'; #endif std::string result = ""; - int na = int(a.length()), nb = int(b.length()), carry = 0; + int na = int(a.length()); + int nb = int(b.length()); + int carry = 0; for (--na, --nb; na >= 0 && nb >= 0; --na, --nb) { char c = a.c_str()[na] + (b.c_str()[nb] - '0') + carry; @@ -327,7 +332,7 @@ vnl_decnum::plus(std::string const & a, std::string const & b, long exp) } if (carry) result.insert(result.begin(), '1'); - return vnl_decnum('+', result, exp); + return { '+', result, exp }; } // Returns the difference of the two first arguments (interpreted as mantissas with the same exponent). @@ -335,13 +340,15 @@ vnl_decnum::plus(std::string const & a, std::string const & b, long exp) // and the first one should be numerically larger than the second one. // The third argument will be the exponent of the result. vnl_decnum -vnl_decnum::minus(std::string const & a, std::string const & b, long exp) +vnl_decnum::minus(const std::string & a, const std::string & b, long exp) { #ifdef DEBUG std::cerr << "Entering vnl_decnum::minus with " << a << " and " << b << '\n'; #endif std::string result = ""; - int na = int(a.length()), nb = int(b.length()), carry = 0; + int na = int(a.length()); + int nb = int(b.length()); + int carry = 0; assert(na >= nb); for (--na, --nb; na >= 0 && nb >= 0; --na, --nb) { @@ -366,11 +373,11 @@ vnl_decnum::minus(std::string const & a, std::string const & b, long exp) if (na) result.erase(0, na); assert(carry == 0); - return vnl_decnum('+', result, exp); + return { '+', result, exp }; } vnl_decnum -vnl_decnum::operator+(vnl_decnum const & r) const +vnl_decnum::operator+(const vnl_decnum & r) const { #ifdef DEBUG std::cerr << "Entering vnl_decnum::operator+ with " << sign_ << data_ << 'e' << exp_ << " and " << r.sign() @@ -420,13 +427,15 @@ vnl_decnum::operator+(vnl_decnum const & r) const // The first argument should consist of digits only; // the second argument should be a single digit. std::string -vnl_decnum::mult(std::string const & a, char b) +vnl_decnum::mult(const std::string & a, char b) { #ifdef DEBUG std::cerr << "Entering vnl_decnum::mult with " << a << " and " << b << '\n'; #endif std::string result = ""; - int na = int(a.length()), carry = 0, bb = b - '0'; + int na = int(a.length()); + int carry = 0; + const int bb = b - '0'; assert(bb >= 0 && bb <= 9); for (--na; na >= 0; --na) { @@ -441,7 +450,8 @@ vnl_decnum::mult(std::string const & a, char b) return result; } -vnl_decnum vnl_decnum::operator*(vnl_decnum const & r) const +vnl_decnum +vnl_decnum::operator*(const vnl_decnum & r) const { #ifdef DEBUG std::cerr << "Entering vnl_decnum::operator* with " << sign_ << data_ << 'e' << exp_ << " and " << r.sign() @@ -452,10 +462,11 @@ vnl_decnum vnl_decnum::operator*(vnl_decnum const & r) const else if (r.data() == "NaN") return r; else if (data_ == "Inf" || r.data() == "Inf") - return sign_ == r.sign() ? vnl_decnum("+Inf") - : (sign_ == ' ' || r.sign() == ' ') ? vnl_decnum("NaN") : vnl_decnum("-Inf"); + return sign_ == r.sign() ? vnl_decnum("+Inf") + : (sign_ == ' ' || r.sign() == ' ') ? vnl_decnum("NaN") + : vnl_decnum("-Inf"); - int sign = (sign_ == ' ' ? 0 : sign_ == '-' ? -1 : 1) * (r.sign() == ' ' ? 0 : r.sign() == '-' ? -1 : 1); + const int sign = (sign_ == ' ' ? 0 : sign_ == '-' ? -1 : 1) * (r.sign() == ' ' ? 0 : r.sign() == '-' ? -1 : 1); vnl_decnum result(0L); if (sign == 0) return result; @@ -476,12 +487,13 @@ vnl_decnum vnl_decnum::operator*(vnl_decnum const & r) const // The arguments should consist of digits only // and the first one should be numerically larger than the second one. std::string -vnl_decnum::div(std::string const & a, std::string & b) +vnl_decnum::div(const std::string & a, std::string & b) { #ifdef DEBUG std::cerr << "Entering vnl_decnum::div with " << a << " and " << b << '\n'; #endif - int na = int(a.length()), nb = int(b.length()); + int const na = int(a.length()); + int nb = int(b.length()); assert(na >= nb); if (comp(a, b)) ++nb; @@ -494,7 +506,7 @@ vnl_decnum::div(std::string const & a, std::string & b) std::string c = b; for (; u[0] < '9'; u[0]++) { - vnl_decnum d = plus(c, b, 0L); + const vnl_decnum d = plus(c, b, 0L); if (vnl_decnum(a) < d) { b = c; @@ -508,7 +520,7 @@ vnl_decnum::div(std::string const & a, std::string & b) } vnl_decnum -vnl_decnum::operator/(vnl_decnum const & r) const +vnl_decnum::operator/(const vnl_decnum & r) const { #ifdef DEBUG std::cerr << "Entering vnl_decnum::operator/ with " << sign_ << data_ << 'e' << exp_ << " and " << r.sign() @@ -519,7 +531,7 @@ vnl_decnum::operator/(vnl_decnum const & r) const else if (r.data() == "NaN") return r; else if (data_ == "Inf" && r.data() == "Inf") - return vnl_decnum("NaN"); + return { "NaN" }; else if (r.data() == "Inf") return vnl_decnum(0L); else if (data_ == "Inf") @@ -530,29 +542,31 @@ vnl_decnum::operator/(vnl_decnum const & r) const if (r == 1L) return *this; if (operator==(r)) - return vnl_decnum('+', "1", 0L); - std::string a = data_, b = r.data(); - int na = int(a.length()), nb = int(b.length()); + return { '+', "1", 0L }; + std::string a = data_; + const std::string b = r.data(); + int na = int(a.length()); + const int nb = int(b.length()); vnl_decnum result(0L); while (na > nb || (na == nb && !comp(a, b))) { std::string c = b; - std::string d = div(a, c); + const std::string d = div(a, c); #ifdef DEBUG std::cerr << "vnl_decnum::div returns " << d << '\n'; #endif result += vnl_decnum(d); - vnl_decnum m = vnl_decnum(a) - vnl_decnum(c); + const vnl_decnum m = vnl_decnum(a) - vnl_decnum(c); a = m.data(); na = a.length(); } result <<= (exp_ - r.exp()); - int sign = (sign_ == '-' ? -1 : 1) * (r.sign() == '-' ? -1 : 1); + const int sign = (sign_ == '-' ? -1 : 1) * (r.sign() == '-' ? -1 : 1); return sign == -1 ? -result : result; } vnl_decnum -vnl_decnum::operator%(vnl_decnum const & r) const +vnl_decnum::operator%(const vnl_decnum & r) const { #ifdef DEBUG std::cerr << "Entering vnl_decnum::operator% with " << sign_ << data_ << 'e' << exp_ << " and " << r.sign() @@ -565,31 +579,33 @@ vnl_decnum::operator%(vnl_decnum const & r) const else if (r.data() == "NaN") return r; else if (r.data() == "Inf") - return vnl_decnum("NaN"); + return { "NaN" }; else if (data_ == "Inf") return *this; if (r == vnl_decnum("1")) - return vnl_decnum("0"); + return { "0" }; if (operator==(r)) - return vnl_decnum("0"); - std::string a = data_, b = r.data(); - int na = int(a.length()), nb = int(b.length()); + return { "0" }; + std::string a = data_; + const std::string b = r.data(); + int na = int(a.length()); + const int nb = int(b.length()); while (na > nb || (na == nb && !comp(a, b))) { std::string c = b; - std::string d = div(a, c); + const std::string d = div(a, c); #ifdef DEBUG std::cerr << "vnl_decnum::div returns " << d << '\n'; #endif - vnl_decnum m = vnl_decnum(a) - vnl_decnum(c); + vnl_decnum const m = vnl_decnum(a) - vnl_decnum(c); a = m.data(); na = a.length(); } if (na == 0) return vnl_decnum(0L); else - return vnl_decnum(sign_, a, exp_); + return { sign_, a, exp_ }; } // See also the constructor from std::string. @@ -665,8 +681,8 @@ vnl_decnum::compactify() exp_ = 0L; return *this; } - unsigned long n = data_.find_last_not_of('0') + 1; - unsigned long l = data_.length(); + const unsigned long n = data_.find_last_not_of('0') + 1; + const unsigned long l = data_.length(); if (n < l) { // at least one trailing zero is found exp_ += l - n; diff --git a/core/vnl/vnl_decnum.h b/core/vnl/vnl_decnum.h index 7e7bcd3fb22..6e1d4f7e538 100644 --- a/core/vnl/vnl_decnum.h +++ b/core/vnl/vnl_decnum.h @@ -84,339 +84,1067 @@ class VNL_EXPORT vnl_decnum { - private: - char sign_{' '}; // Sign of vnl_decnum ('+' or '-'; for zero and NaN, the - // sign is ' ') - std::string - data_; // The decimal mantissa data (absolute value) - // data_ consists of decimals (0-9) only, guaranteed without - // leading zero. This holds even for zero: represented by "". - // The only exceptions are "Inf" and "NaN". - long exp_{ - 0L}; // The exponent; nonnegative for integers. Zero for Inf and NaN. - - // private constructor: arguments should satisfy the above constraints - vnl_decnum(char s, std::string d, long e) - : sign_(s), data_(std::move(d)), exp_(e) {} - public: - std::string data() const { return data_; } - char sign() const { return sign_; } - long exp () const { return exp_; } +private: + char sign_{ ' ' }; // Sign of vnl_decnum ('+' or '-'; for zero and NaN, the + // sign is ' ') + std::string data_; // The decimal mantissa data (absolute value) + // data_ consists of decimals (0-9) only, guaranteed without + // leading zero. This holds even for zero: represented by "". + // The only exceptions are "Inf" and "NaN". + long exp_{ 0L }; // The exponent; nonnegative for integers. Zero for Inf and NaN. + + // private constructor: arguments should satisfy the above constraints + vnl_decnum(char s, std::string d, long e) + : sign_(s) + , data_(std::move(d)) + , exp_(e) + {} + +public: + std::string + data() const + { + return data_; + } + char + sign() const + { + return sign_; + } + long + exp() const + { + return exp_; + } //: Default constructor - creates the number zero. - vnl_decnum() : data_("") {} + vnl_decnum() + : data_("") + {} // Copy constructor - vnl_decnum(vnl_decnum const& r) = default; + vnl_decnum(const vnl_decnum & r) = default; //: Constructor from string // This is the principal constructor for vnl_decnum; it essentially parses // the input into (in that order) the sign, the mantissa, and the exponent, // which turn out (surprise!) to be the three data members of this class. // Parsing stops at the first unexpected character, so in the worst case // no characters can be used and the decnum is zero. - vnl_decnum(std::string const&); - vnl_decnum(char const* r) { operator=(std::string(r)); } + vnl_decnum(const std::string &); + vnl_decnum(const char * r) { operator=(std::string(r)); } //: Creates a vnl_decnum from an unsigned long integer. explicit vnl_decnum(unsigned long); //: Creates a vnl_decnum from a long integer. // Uses the "unsigned long" constructor and additionally sets the sign explicit vnl_decnum(long r) - : sign_(r<0 ? '-' : r>0 ? '+' : ' ') - { vnl_decnum d((unsigned long)(r<0?-r:r)); data_=d.data(); exp_=d.exp(); } + : sign_(r < 0 ? '-' + : r > 0 ? '+' + : ' ') + { + const vnl_decnum d((unsigned long)(r < 0 ? -r : r)); + data_ = d.data(); + exp_ = d.exp(); + } //: Creates a vnl_decnum from an unsigned integer. // Uses the "unsigned long" constructor. explicit vnl_decnum(unsigned int r) - : sign_(r>0 ? '+' : ' ') - { vnl_decnum d((unsigned long)r); data_=d.data(); exp_=d.exp(); } + : sign_(r > 0 ? '+' : ' ') + { + const vnl_decnum d((unsigned long)r); + data_ = d.data(); + exp_ = d.exp(); + } //: Creates a vnl_decnum from an integer. // Uses the "unsigned long" constructor and additionally sets the sign explicit vnl_decnum(int r) - : sign_(r<0 ? '-' : r>0 ? '+' : ' ') - { vnl_decnum d((unsigned long)(r<0?-r:r)); data_=d.data(); exp_=d.exp(); } + : sign_(r < 0 ? '-' + : r > 0 ? '+' + : ' ') + { + const vnl_decnum d((unsigned long)(r < 0 ? -r : r)); + data_ = d.data(); + exp_ = d.exp(); + } //: Creates a vnl_decnum from a double. // No guarantees on the precise result! // Integers will be correctly converted, though. vnl_decnum(double); - ~vnl_decnum() = default; // Destructor + ~vnl_decnum() = default; // Destructor //: Implicit type conversion to a decimal string operator std::string() const; - operator long() const; // type conversion - operator unsigned long() const; // type conversion, drop the sign - operator int() const; // type conversion + operator long() const; // type conversion + operator unsigned long() const; // type conversion, drop the sign + operator int() const; // type conversion operator unsigned int() const; // type conversion, drop the sign //: Unary plus operator - inline vnl_decnum operator+() const { return *this; } + inline vnl_decnum + operator+() const + { + return *this; + } //: Unary minus operator - inline vnl_decnum operator-() const { if (sign_==' ') return *this; else return vnl_decnum(sign_=='-'?'+':'-', data_, exp_); } + inline vnl_decnum + operator-() const + { + if (sign_ == ' ') + return *this; + else + return { sign_ == '-' ? '+' : '-', data_, exp_ }; + } //: Left "bit" shift operator (actually: digit shift, or exponent translation) - inline vnl_decnum operator<<(long int r) const { return sign_==' ' ? *this : vnl_decnum(sign_, data_, exp_+r); } - inline vnl_decnum operator<<(int r) const { return operator<<((long int)r); } + inline vnl_decnum + operator<<(long int r) const + { + return sign_ == ' ' ? *this : vnl_decnum(sign_, data_, exp_ + r); + } + inline vnl_decnum + operator<<(int r) const + { + return operator<<((long int)r); + } //: Right "bit" shift operator (actually: digit shift, or exponent translation) - inline vnl_decnum operator>>(long int r) const { return sign_==' ' ? *this : vnl_decnum(sign_, data_, exp_-r); } - inline vnl_decnum operator>>(int r) const { return operator>>((long int)r); } + inline vnl_decnum + operator>>(long int r) const + { + return sign_ == ' ' ? *this : vnl_decnum(sign_, data_, exp_ - r); + } + inline vnl_decnum + operator>>(int r) const + { + return operator>>((long int)r); + } //: Left "bit" shift operator (actually: digit shift, or exponent translation) - inline vnl_decnum& operator<<=(long int r) { if (sign_!=' ') exp_ += r; return *this; } - inline vnl_decnum& operator<<=(int r) { if (sign_!=' ') exp_ += r; return *this; } + inline vnl_decnum & + operator<<=(long int r) + { + if (sign_ != ' ') + exp_ += r; + return *this; + } + inline vnl_decnum & + operator<<=(int r) + { + if (sign_ != ' ') + exp_ += r; + return *this; + } //: Right "bit" shift operator (actually: digit shift, or exponent translation) - inline vnl_decnum& operator>>=(long int r) { if (sign_!=' ') exp_ -= r; return *this; } - inline vnl_decnum& operator>>=(int r) { if (sign_!=' ') exp_ -= r; return *this; } + inline vnl_decnum & + operator>>=(long int r) + { + if (sign_ != ' ') + exp_ -= r; + return *this; + } + inline vnl_decnum & + operator>>=(int r) + { + if (sign_ != ' ') + exp_ -= r; + return *this; + } //: Remove all trailing zeros from the mantissa, and increase the exponent accordingly. // Return the (thus modified) *this. // This effectively compactifies the data representation of *this, and meanwhile increases the exponent. // No other methods have this effect; to the contrary: e.g. operator+(1) often decreases the exponent to 0. - vnl_decnum& compactify(); + vnl_decnum & + compactify(); //: Expand integers to their non-compactified representation, i.e., without "e" notation. // Other operators (like + or -) might implicitly have this effect, as the implementation here indeed suggests. - inline vnl_decnum& expand() { return *this = operator+(1L)-1L; } + inline vnl_decnum & + expand() + { + return *this = operator+(1L) - 1L; + } //: Assignment operator; no compactification or expansion occurs - inline vnl_decnum& operator=(const vnl_decnum& r) { sign_=r.sign(); data_=r.data(); exp_=r.exp(); return *this; } + inline vnl_decnum & + operator=(const vnl_decnum & r) + { + sign_ = r.sign(); + data_ = r.data(); + exp_ = r.exp(); + return *this; + } //: Sum - vnl_decnum operator+(vnl_decnum const& r) const; + vnl_decnum + operator+(const vnl_decnum & r) const; //: Difference - inline vnl_decnum operator-(vnl_decnum const& r) const { return operator+(-r); } + inline vnl_decnum + operator-(const vnl_decnum & r) const + { + return operator+(-r); + } //: Product - vnl_decnum operator*(vnl_decnum const& r) const; + vnl_decnum + operator*(const vnl_decnum & r) const; //: division operator // \returns integral part of quotient (long division) of *this with \p r // When \p r is zero, the result is Inf, // unless also *this is zero, in which case the result is NaN. - vnl_decnum operator/(vnl_decnum const& r) const; + vnl_decnum + operator/(const vnl_decnum & r) const; //: modulo operator // \returns remainder of long division of *this with \p r // When \p r is zero, the result equals *this. - vnl_decnum operator%(vnl_decnum const& r) const; + vnl_decnum + operator%(const vnl_decnum & r) const; - inline vnl_decnum& operator+=(vnl_decnum const& r) { return *this = operator+(r); } - inline vnl_decnum& operator-=(vnl_decnum const& r) { return *this = operator+(-r); } - inline vnl_decnum& operator*=(vnl_decnum const& r) { return *this = operator*(r); } - inline vnl_decnum& operator/=(vnl_decnum const& r) { return *this = operator/(r); } - inline vnl_decnum& operator%=(vnl_decnum const& r) { return *this = operator%(r); } + inline vnl_decnum & + operator+=(const vnl_decnum & r) + { + return *this = operator+(r); + } + inline vnl_decnum & + operator-=(const vnl_decnum & r) + { + return *this = operator+(-r); + } + inline vnl_decnum & + operator*=(const vnl_decnum & r) + { + return *this = operator*(r); + } + inline vnl_decnum & + operator/=(const vnl_decnum & r) + { + return *this = operator/(r); + } + inline vnl_decnum & + operator%=(const vnl_decnum & r) + { + return *this = operator%(r); + } // === overloads for the above operators with other datatypes as rhs: - inline vnl_decnum& operator=(std::string const& r) { return operator=(vnl_decnum(r)); } - inline vnl_decnum& operator=(char const* r) { return operator=(vnl_decnum(std::string(r))); } - inline vnl_decnum& operator=(unsigned long r) { return operator=(vnl_decnum(r)); } - inline vnl_decnum& operator=(long r) { return operator=(vnl_decnum(r)); } - inline vnl_decnum& operator=(unsigned int r) { return operator=(vnl_decnum(r)); } - inline vnl_decnum& operator=(int r) { return operator=(vnl_decnum(r)); } - inline vnl_decnum& operator=(double r) { return operator=(vnl_decnum(r)); } - - inline vnl_decnum operator+(std::string const& r) const { return operator+(vnl_decnum(r)); } - inline vnl_decnum operator+(char const* r) const { return operator+(vnl_decnum(std::string(r))); } - inline vnl_decnum operator+(unsigned long r) const { return operator+(vnl_decnum(r)); } - inline vnl_decnum operator+(long r) const { return operator+(vnl_decnum(r)); } - inline vnl_decnum operator+(unsigned int r) const { return operator+(vnl_decnum(r)); } - inline vnl_decnum operator+(int r) const { return operator+(vnl_decnum(r)); } - inline vnl_decnum operator+(double r) const { return operator+(vnl_decnum(r)); } - - inline vnl_decnum operator-(std::string const& r) const { return operator-(vnl_decnum(r)); } - inline vnl_decnum operator-(char const* r) const { return operator-(vnl_decnum(std::string(r))); } - inline vnl_decnum operator-(unsigned long r) const { return operator-(vnl_decnum(r)); } - inline vnl_decnum operator-(long r) const { return operator+(vnl_decnum(-r)); } - inline vnl_decnum operator-(unsigned int r) const { return operator-(vnl_decnum(r)); } - inline vnl_decnum operator-(int r) const { return operator+(vnl_decnum(-r)); } - inline vnl_decnum operator-(double r) const { return operator+(vnl_decnum(-r)); } - - inline vnl_decnum operator*(std::string const& r) const { return operator*(vnl_decnum(r)); } - inline vnl_decnum operator*(char const* r) const { return operator*(vnl_decnum(std::string(r))); } - inline vnl_decnum operator*(unsigned long r) const { return operator*(vnl_decnum(r)); } - inline vnl_decnum operator*(long r) const { return operator*(vnl_decnum(r)); } - inline vnl_decnum operator*(unsigned int r) const { return operator*(vnl_decnum(r)); } - inline vnl_decnum operator*(int r) const { return operator*(vnl_decnum(r)); } - inline vnl_decnum operator*(double r) const { return operator*(vnl_decnum(r)); } - - inline vnl_decnum operator/(std::string const& r) const { return operator/(vnl_decnum(r)); } - inline vnl_decnum operator/(char const* r) const { return operator/(vnl_decnum(std::string(r))); } - inline vnl_decnum operator/(unsigned long r) const { return operator/(vnl_decnum(r)); } - inline vnl_decnum operator/(long r) const { return operator/(vnl_decnum(r)); } - inline vnl_decnum operator/(unsigned int r) const { return operator/(vnl_decnum(r)); } - inline vnl_decnum operator/(int r) const { return operator/(vnl_decnum(r)); } - inline vnl_decnum operator/(double r) const { return operator/(vnl_decnum(r)); } - - inline vnl_decnum operator%(std::string const& r) const { return operator%(vnl_decnum(r)); } - inline vnl_decnum operator%(char const* r) const { return operator%(vnl_decnum(std::string(r))); } - inline vnl_decnum operator%(unsigned long r) const { return operator%(vnl_decnum(r)); } - inline vnl_decnum operator%(long r) const { return operator%(vnl_decnum(r)); } - inline vnl_decnum operator%(unsigned int r) const { return operator%(vnl_decnum(r)); } - inline vnl_decnum operator%(int r) const { return operator%(vnl_decnum(r)); } - inline vnl_decnum operator%(double r) const { return operator%(vnl_decnum(r)); } - - inline vnl_decnum& operator+=(std::string const& r) { return *this = operator+(vnl_decnum(r)); } - inline vnl_decnum& operator-=(std::string const& r) { return *this = operator-(vnl_decnum(r)); } - inline vnl_decnum& operator*=(std::string const& r) { return *this = operator*(vnl_decnum(r)); } - inline vnl_decnum& operator/=(std::string const& r) { return *this = operator/(vnl_decnum(r)); } - inline vnl_decnum& operator%=(std::string const& r) { return *this = operator%(vnl_decnum(r)); } - - inline vnl_decnum& operator+=(char const* r) { return *this = operator+(std::string(r)); } - inline vnl_decnum& operator-=(char const* r) { return *this = operator-(std::string(r)); } - inline vnl_decnum& operator*=(char const* r) { return *this = operator*(std::string(r)); } - inline vnl_decnum& operator/=(char const* r) { return *this = operator/(std::string(r)); } - inline vnl_decnum& operator%=(char const* r) { return *this = operator%(std::string(r)); } - - inline vnl_decnum& operator+=(unsigned long r) { return *this = operator+(vnl_decnum(r)); } - inline vnl_decnum& operator-=(unsigned long r) { return *this = operator-(vnl_decnum(r)); } - inline vnl_decnum& operator*=(unsigned long r) { return *this = operator*(vnl_decnum(r)); } - inline vnl_decnum& operator/=(unsigned long r) { return *this = operator/(vnl_decnum(r)); } - inline vnl_decnum& operator%=(unsigned long r) { return *this = operator%(vnl_decnum(r)); } - - inline vnl_decnum& operator+=(long r) { return *this = operator+(vnl_decnum(r)); } - inline vnl_decnum& operator-=(long r) { return *this = operator+(vnl_decnum(-r)); } - inline vnl_decnum& operator*=(long r) { return *this = operator*(vnl_decnum(r)); } - inline vnl_decnum& operator/=(long r) { return *this = operator/(vnl_decnum(r)); } - inline vnl_decnum& operator%=(long r) { return *this = operator%(vnl_decnum(r)); } - - inline vnl_decnum& operator+=(unsigned int r) { return *this = operator+(vnl_decnum(r)); } - inline vnl_decnum& operator-=(unsigned int r) { return *this = operator-(vnl_decnum(r)); } - inline vnl_decnum& operator*=(unsigned int r) { return *this = operator*(vnl_decnum(r)); } - inline vnl_decnum& operator/=(unsigned int r) { return *this = operator/(vnl_decnum(r)); } - inline vnl_decnum& operator%=(unsigned int r) { return *this = operator%(vnl_decnum(r)); } - - inline vnl_decnum& operator+=(int r) { return *this = operator+(vnl_decnum(r)); } - inline vnl_decnum& operator-=(int r) { return *this = operator+(vnl_decnum(-r)); } - inline vnl_decnum& operator*=(int r) { return *this = operator*(vnl_decnum(r)); } - inline vnl_decnum& operator/=(int r) { return *this = operator/(vnl_decnum(r)); } - inline vnl_decnum& operator%=(int r) { return *this = operator%(vnl_decnum(r)); } - - inline vnl_decnum& operator+=(double r) { return *this = operator+(vnl_decnum(r)); } - inline vnl_decnum& operator-=(double r) { return *this = operator+(vnl_decnum(-r)); } - inline vnl_decnum& operator*=(double r) { return *this = operator*(vnl_decnum(r)); } - inline vnl_decnum& operator/=(double r) { return *this = operator/(vnl_decnum(r)); } - inline vnl_decnum& operator%=(double r) { return *this = operator%(vnl_decnum(r)); } + inline vnl_decnum & + operator=(const std::string & r) + { + return operator=(vnl_decnum(r)); + } + inline vnl_decnum & + operator=(const char * r) + { + return operator=(vnl_decnum(std::string(r))); + } + inline vnl_decnum & + operator=(unsigned long r) + { + return operator=(vnl_decnum(r)); + } + inline vnl_decnum & + operator=(long r) + { + return operator=(vnl_decnum(r)); + } + inline vnl_decnum & + operator=(unsigned int r) + { + return operator=(vnl_decnum(r)); + } + inline vnl_decnum & + operator=(int r) + { + return operator=(vnl_decnum(r)); + } + inline vnl_decnum & + operator=(double r) + { + return operator=(vnl_decnum(r)); + } + + inline vnl_decnum + operator+(const std::string & r) const + { + return operator+(vnl_decnum(r)); + } + inline vnl_decnum + operator+(const char * r) const + { + return operator+(vnl_decnum(std::string(r))); + } + inline vnl_decnum + operator+(unsigned long r) const + { + return operator+(vnl_decnum(r)); + } + inline vnl_decnum + operator+(long r) const + { + return operator+(vnl_decnum(r)); + } + inline vnl_decnum + operator+(unsigned int r) const + { + return operator+(vnl_decnum(r)); + } + inline vnl_decnum + operator+(int r) const + { + return operator+(vnl_decnum(r)); + } + inline vnl_decnum + operator+(double r) const + { + return operator+(vnl_decnum(r)); + } + + inline vnl_decnum + operator-(const std::string & r) const + { + return operator-(vnl_decnum(r)); + } + inline vnl_decnum + operator-(const char * r) const + { + return operator-(vnl_decnum(std::string(r))); + } + inline vnl_decnum + operator-(unsigned long r) const + { + return operator-(vnl_decnum(r)); + } + inline vnl_decnum + operator-(long r) const + { + return operator+(vnl_decnum(-r)); + } + inline vnl_decnum + operator-(unsigned int r) const + { + return operator-(vnl_decnum(r)); + } + inline vnl_decnum + operator-(int r) const + { + return operator+(vnl_decnum(-r)); + } + inline vnl_decnum + operator-(double r) const + { + return operator+(vnl_decnum(-r)); + } + + inline vnl_decnum + operator*(const std::string & r) const + { + return operator*(vnl_decnum(r)); + } + inline vnl_decnum + operator*(const char * r) const + { + return operator*(vnl_decnum(std::string(r))); + } + inline vnl_decnum + operator*(unsigned long r) const + { + return operator*(vnl_decnum(r)); + } + inline vnl_decnum + operator*(long r) const + { + return operator*(vnl_decnum(r)); + } + inline vnl_decnum + operator*(unsigned int r) const + { + return operator*(vnl_decnum(r)); + } + inline vnl_decnum + operator*(int r) const + { + return operator*(vnl_decnum(r)); + } + inline vnl_decnum + operator*(double r) const + { + return operator*(vnl_decnum(r)); + } + + inline vnl_decnum + operator/(const std::string & r) const + { + return operator/(vnl_decnum(r)); + } + inline vnl_decnum + operator/(const char * r) const + { + return operator/(vnl_decnum(std::string(r))); + } + inline vnl_decnum + operator/(unsigned long r) const + { + return operator/(vnl_decnum(r)); + } + inline vnl_decnum + operator/(long r) const + { + return operator/(vnl_decnum(r)); + } + inline vnl_decnum + operator/(unsigned int r) const + { + return operator/(vnl_decnum(r)); + } + inline vnl_decnum + operator/(int r) const + { + return operator/(vnl_decnum(r)); + } + inline vnl_decnum + operator/(double r) const + { + return operator/(vnl_decnum(r)); + } + + inline vnl_decnum + operator%(const std::string & r) const + { + return operator%(vnl_decnum(r)); + } + inline vnl_decnum + operator%(const char * r) const + { + return operator%(vnl_decnum(std::string(r))); + } + inline vnl_decnum + operator%(unsigned long r) const + { + return operator%(vnl_decnum(r)); + } + inline vnl_decnum + operator%(long r) const + { + return operator%(vnl_decnum(r)); + } + inline vnl_decnum + operator%(unsigned int r) const + { + return operator%(vnl_decnum(r)); + } + inline vnl_decnum + operator%(int r) const + { + return operator%(vnl_decnum(r)); + } + inline vnl_decnum + operator%(double r) const + { + return operator%(vnl_decnum(r)); + } + + inline vnl_decnum & + operator+=(const std::string & r) + { + return *this = operator+(vnl_decnum(r)); + } + inline vnl_decnum & + operator-=(const std::string & r) + { + return *this = operator-(vnl_decnum(r)); + } + inline vnl_decnum & + operator*=(const std::string & r) + { + return *this = operator*(vnl_decnum(r)); + } + inline vnl_decnum & + operator/=(const std::string & r) + { + return *this = operator/(vnl_decnum(r)); + } + inline vnl_decnum & + operator%=(const std::string & r) + { + return *this = operator%(vnl_decnum(r)); + } + + inline vnl_decnum & + operator+=(const char * r) + { + return *this = operator+(std::string(r)); + } + inline vnl_decnum & + operator-=(const char * r) + { + return *this = operator-(std::string(r)); + } + inline vnl_decnum & + operator*=(const char * r) + { + return *this = operator*(std::string(r)); + } + inline vnl_decnum & + operator/=(const char * r) + { + return *this = operator/(std::string(r)); + } + inline vnl_decnum & + operator%=(const char * r) + { + return *this = operator%(std::string(r)); + } + + inline vnl_decnum & + operator+=(unsigned long r) + { + return *this = operator+(vnl_decnum(r)); + } + inline vnl_decnum & + operator-=(unsigned long r) + { + return *this = operator-(vnl_decnum(r)); + } + inline vnl_decnum & + operator*=(unsigned long r) + { + return *this = operator*(vnl_decnum(r)); + } + inline vnl_decnum & + operator/=(unsigned long r) + { + return *this = operator/(vnl_decnum(r)); + } + inline vnl_decnum & + operator%=(unsigned long r) + { + return *this = operator%(vnl_decnum(r)); + } + + inline vnl_decnum & + operator+=(long r) + { + return *this = operator+(vnl_decnum(r)); + } + inline vnl_decnum & + operator-=(long r) + { + return *this = operator+(vnl_decnum(-r)); + } + inline vnl_decnum & + operator*=(long r) + { + return *this = operator*(vnl_decnum(r)); + } + inline vnl_decnum & + operator/=(long r) + { + return *this = operator/(vnl_decnum(r)); + } + inline vnl_decnum & + operator%=(long r) + { + return *this = operator%(vnl_decnum(r)); + } + + inline vnl_decnum & + operator+=(unsigned int r) + { + return *this = operator+(vnl_decnum(r)); + } + inline vnl_decnum & + operator-=(unsigned int r) + { + return *this = operator-(vnl_decnum(r)); + } + inline vnl_decnum & + operator*=(unsigned int r) + { + return *this = operator*(vnl_decnum(r)); + } + inline vnl_decnum & + operator/=(unsigned int r) + { + return *this = operator/(vnl_decnum(r)); + } + inline vnl_decnum & + operator%=(unsigned int r) + { + return *this = operator%(vnl_decnum(r)); + } + + inline vnl_decnum & + operator+=(int r) + { + return *this = operator+(vnl_decnum(r)); + } + inline vnl_decnum & + operator-=(int r) + { + return *this = operator+(vnl_decnum(-r)); + } + inline vnl_decnum & + operator*=(int r) + { + return *this = operator*(vnl_decnum(r)); + } + inline vnl_decnum & + operator/=(int r) + { + return *this = operator/(vnl_decnum(r)); + } + inline vnl_decnum & + operator%=(int r) + { + return *this = operator%(vnl_decnum(r)); + } + + inline vnl_decnum & + operator+=(double r) + { + return *this = operator+(vnl_decnum(r)); + } + inline vnl_decnum & + operator-=(double r) + { + return *this = operator+(vnl_decnum(-r)); + } + inline vnl_decnum & + operator*=(double r) + { + return *this = operator*(vnl_decnum(r)); + } + inline vnl_decnum & + operator/=(double r) + { + return *this = operator/(vnl_decnum(r)); + } + inline vnl_decnum & + operator%=(double r) + { + return *this = operator%(vnl_decnum(r)); + } //: prefix increment (++b) - inline vnl_decnum& operator++() { return *this = operator+(1L); } + inline vnl_decnum & + operator++() + { + return *this = operator+(1L); + } //: decrement - inline vnl_decnum& operator--() { return *this = operator-(1L); } + inline vnl_decnum & + operator--() + { + return *this = operator-(1L); + } //: postfix increment (b++) - inline vnl_decnum operator++(int) { vnl_decnum b=(*this); operator++(); return b; } + inline vnl_decnum + operator++(int) + { + const vnl_decnum b = (*this); + operator++(); + return b; + } //: decrement - inline vnl_decnum operator--(int) { vnl_decnum b=(*this); operator--(); return b; } - - bool operator==(vnl_decnum const&) const; // equality - bool operator< (vnl_decnum const&) const; // less than - inline bool operator!=(vnl_decnum const& r) const { return !operator==(r); } - inline bool operator> (vnl_decnum const& r) const { return r<(*this); } - inline bool operator<=(vnl_decnum const& r) const { return !operator>(r); } - inline bool operator>=(vnl_decnum const& r) const { return !operator<(r); } - - inline bool operator==(std::string const& r) const { return operator==(vnl_decnum(r)); } - inline bool operator< (std::string const& r) const { return operator< (vnl_decnum(r)); } - inline bool operator!=(std::string const& r) const { return operator!=(vnl_decnum(r)); } - inline bool operator> (std::string const& r) const { return operator> (vnl_decnum(r)); } - inline bool operator<=(std::string const& r) const { return operator<=(vnl_decnum(r)); } - inline bool operator>=(std::string const& r) const { return operator>=(vnl_decnum(r)); } - - inline bool operator==(char const* r) const { return operator==(std::string(r)); } - inline bool operator< (char const* r) const { return operator< (std::string(r)); } - inline bool operator!=(char const* r) const { return operator!=(std::string(r)); } - inline bool operator> (char const* r) const { return operator> (std::string(r)); } - inline bool operator<=(char const* r) const { return operator<=(std::string(r)); } - inline bool operator>=(char const* r) const { return operator>=(std::string(r)); } - - inline bool operator==(unsigned long r) const { return operator==(vnl_decnum(r)); } - inline bool operator< (unsigned long r) const { return operator< (vnl_decnum(r)); } - inline bool operator!=(unsigned long r) const { return operator!=(vnl_decnum(r)); } - inline bool operator> (unsigned long r) const { return operator> (vnl_decnum(r)); } - inline bool operator<=(unsigned long r) const { return operator<=(vnl_decnum(r)); } - inline bool operator>=(unsigned long r) const { return operator>=(vnl_decnum(r)); } - - inline bool operator==(long r) const { return operator==(vnl_decnum(r)); } - inline bool operator< (long r) const { return operator< (vnl_decnum(r)); } - inline bool operator!=(long r) const { return operator!=(vnl_decnum(r)); } - inline bool operator> (long r) const { return operator> (vnl_decnum(r)); } - inline bool operator<=(long r) const { return operator<=(vnl_decnum(r)); } - inline bool operator>=(long r) const { return operator>=(vnl_decnum(r)); } - - inline bool operator==(unsigned int r) const { return operator==(vnl_decnum(r)); } - inline bool operator< (unsigned int r) const { return operator< (vnl_decnum(r)); } - inline bool operator!=(unsigned int r) const { return operator!=(vnl_decnum(r)); } - inline bool operator> (unsigned int r) const { return operator> (vnl_decnum(r)); } - inline bool operator<=(unsigned int r) const { return operator<=(vnl_decnum(r)); } - inline bool operator>=(unsigned int r) const { return operator>=(vnl_decnum(r)); } - - inline bool operator==(int r) const { return operator==(vnl_decnum(r)); } - inline bool operator< (int r) const { return operator< (vnl_decnum(r)); } - inline bool operator!=(int r) const { return operator!=(vnl_decnum(r)); } - inline bool operator> (int r) const { return operator> (vnl_decnum(r)); } - inline bool operator<=(int r) const { return operator<=(vnl_decnum(r)); } - inline bool operator>=(int r) const { return operator>=(vnl_decnum(r)); } - - inline bool operator==(double r) const { return operator==(vnl_decnum(r)); } - inline bool operator< (double r) const { return operator< (vnl_decnum(r)); } - inline bool operator!=(double r) const { return operator!=(vnl_decnum(r)); } - inline bool operator> (double r) const { return operator> (vnl_decnum(r)); } - inline bool operator<=(double r) const { return operator<=(vnl_decnum(r)); } - inline bool operator>=(double r) const { return operator>=(vnl_decnum(r)); } - - inline vnl_decnum abs() const { return sign_=='-' ? operator-() : *this; } - inline vnl_decnum trunc() const { return exp_>=0L ? *this : vnl_decnum(sign_,data_.substr(0L,data_.length()+exp_),0L); } - inline vnl_decnum roundup() const { return operator==(trunc()) ? *this : sign_=='-' ? trunc()-1 : trunc()+1; } - inline vnl_decnum floor() const { return sign_=='-' ? roundup() : trunc(); } - inline vnl_decnum ceil() const { return sign_=='-' ? trunc() : roundup(); } - inline vnl_decnum pow(unsigned long p) const { return p==0L ? vnl_decnum(1L) : p==1L ? *this : pow(p/2)*pow((p+1)/2); } - - private: // === Helper functions === + inline vnl_decnum + operator--(int) + { + const vnl_decnum b = (*this); + operator--(); + return b; + } + + bool + operator==(const vnl_decnum &) const; // equality + bool + operator<(const vnl_decnum &) const; // less than + inline bool + operator!=(const vnl_decnum & r) const + { + return !operator==(r); + } + inline bool + operator>(const vnl_decnum & r) const + { + return r < (*this); + } + inline bool + operator<=(const vnl_decnum & r) const + { + return !operator>(r); + } + inline bool + operator>=(const vnl_decnum & r) const + { + return !operator<(r); + } + + inline bool + operator==(const std::string & r) const + { + return operator==(vnl_decnum(r)); + } + inline bool + operator<(const std::string & r) const + { + return operator<(vnl_decnum(r)); + } + inline bool + operator!=(const std::string & r) const + { + return operator!=(vnl_decnum(r)); + } + inline bool + operator>(const std::string & r) const + { + return operator>(vnl_decnum(r)); + } + inline bool + operator<=(const std::string & r) const + { + return operator<=(vnl_decnum(r)); + } + inline bool + operator>=(const std::string & r) const + { + return operator>=(vnl_decnum(r)); + } + + inline bool + operator==(const char * r) const + { + return operator==(std::string(r)); + } + inline bool + operator<(const char * r) const + { + return operator<(std::string(r)); + } + inline bool + operator!=(const char * r) const + { + return operator!=(std::string(r)); + } + inline bool + operator>(const char * r) const + { + return operator>(std::string(r)); + } + inline bool + operator<=(const char * r) const + { + return operator<=(std::string(r)); + } + inline bool + operator>=(const char * r) const + { + return operator>=(std::string(r)); + } + + inline bool + operator==(unsigned long r) const + { + return operator==(vnl_decnum(r)); + } + inline bool + operator<(unsigned long r) const + { + return operator<(vnl_decnum(r)); + } + inline bool + operator!=(unsigned long r) const + { + return operator!=(vnl_decnum(r)); + } + inline bool + operator>(unsigned long r) const + { + return operator>(vnl_decnum(r)); + } + inline bool + operator<=(unsigned long r) const + { + return operator<=(vnl_decnum(r)); + } + inline bool + operator>=(unsigned long r) const + { + return operator>=(vnl_decnum(r)); + } + + inline bool + operator==(long r) const + { + return operator==(vnl_decnum(r)); + } + inline bool + operator<(long r) const + { + return operator<(vnl_decnum(r)); + } + inline bool + operator!=(long r) const + { + return operator!=(vnl_decnum(r)); + } + inline bool + operator>(long r) const + { + return operator>(vnl_decnum(r)); + } + inline bool + operator<=(long r) const + { + return operator<=(vnl_decnum(r)); + } + inline bool + operator>=(long r) const + { + return operator>=(vnl_decnum(r)); + } + + inline bool + operator==(unsigned int r) const + { + return operator==(vnl_decnum(r)); + } + inline bool + operator<(unsigned int r) const + { + return operator<(vnl_decnum(r)); + } + inline bool + operator!=(unsigned int r) const + { + return operator!=(vnl_decnum(r)); + } + inline bool + operator>(unsigned int r) const + { + return operator>(vnl_decnum(r)); + } + inline bool + operator<=(unsigned int r) const + { + return operator<=(vnl_decnum(r)); + } + inline bool + operator>=(unsigned int r) const + { + return operator>=(vnl_decnum(r)); + } + + inline bool + operator==(int r) const + { + return operator==(vnl_decnum(r)); + } + inline bool + operator<(int r) const + { + return operator<(vnl_decnum(r)); + } + inline bool + operator!=(int r) const + { + return operator!=(vnl_decnum(r)); + } + inline bool + operator>(int r) const + { + return operator>(vnl_decnum(r)); + } + inline bool + operator<=(int r) const + { + return operator<=(vnl_decnum(r)); + } + inline bool + operator>=(int r) const + { + return operator>=(vnl_decnum(r)); + } + + inline bool + operator==(double r) const + { + return operator==(vnl_decnum(r)); + } + inline bool + operator<(double r) const + { + return operator<(vnl_decnum(r)); + } + inline bool + operator!=(double r) const + { + return operator!=(vnl_decnum(r)); + } + inline bool + operator>(double r) const + { + return operator>(vnl_decnum(r)); + } + inline bool + operator<=(double r) const + { + return operator<=(vnl_decnum(r)); + } + inline bool + operator>=(double r) const + { + return operator>=(vnl_decnum(r)); + } + + inline vnl_decnum + abs() const + { + return sign_ == '-' ? operator-() : *this; + } + inline vnl_decnum + trunc() const + { + return exp_ >= 0L ? *this : vnl_decnum(sign_, data_.substr(0L, data_.length() + exp_), 0L); + } + inline vnl_decnum + roundup() const + { + return operator==(trunc()) ? *this : sign_ == '-' ? trunc() - 1 : trunc() + 1; + } + inline vnl_decnum + floor() const + { + return sign_ == '-' ? roundup() : trunc(); + } + inline vnl_decnum + ceil() const + { + return sign_ == '-' ? trunc() : roundup(); + } + inline vnl_decnum + pow(unsigned long p) const + { + return p == 0L ? vnl_decnum(1L) : p == 1L ? *this : pow(p / 2) * pow((p + 1) / 2); + } + +private: // === Helper functions === //: Returns the sum of the two first arguments (interpreted as mantissas with the same exponent). // Both arguments should consist of digits only. // The third argument will be used as the exponent of the result. - static vnl_decnum plus(std::string const&, std::string const&, long); + static vnl_decnum + plus(const std::string &, const std::string &, long); //: Returns the difference of the two first arguments (interpreted as mantissas with the same exponent). // Both arguments should consist of digits only // and the first one should be numerically larger than the second one. // The third argument will be used as the exponent of the result. - static vnl_decnum minus(std::string const&, std::string const&, long); + static vnl_decnum + minus(const std::string &, const std::string &, long); //: This is "operator<" for strings. // The arguments should consist of digits only (interpreted as mantissas with the same exponent). // The shorter of the two arguments is implicitly zero-padded. - static bool comp(std::string const&, std::string const&); + static bool + comp(const std::string &, const std::string &); // Append n zeros to the source string, and return the new padded string - inline static std::string add_zeros(std::string const& source, unsigned long n) - { std::string d = source; while (n--!=0) d.push_back('0'); return d; } + static inline std::string + add_zeros(const std::string & source, unsigned long n) + { + std::string d = source; + while (n-- != 0) + d.push_back('0'); + return d; + } //: Returns the product of the two arguments. // The first argument should consist of digits only; // the second argument should be a single digit. - static std::string mult(std::string const&, char); + static std::string + mult(const std::string &, char); //: Returns the largest one-significant-digit divisor of the two arguments. // The largest multiple of the second argument not larger than the first one // is returned in the second argument. // (I.e.: the product of the original second argument with the returned divisor.) // The arguments should consist of digits only // and the first one should be numerically larger than the second one. - static std::string div(std::string const&, std::string&); + static std::string + div(const std::string &, std::string &); }; //: decimal output // \relatesalso vnl_decnum -inline std::ostream& operator<<(std::ostream& s, vnl_decnum const& r) -{ return s << std::string(r); } +inline std::ostream & +operator<<(std::ostream & s, const vnl_decnum & r) +{ + return s << std::string(r); +} //: decimal input // \relatesalso vnl_decnum -VNL_EXPORT std::istream& operator>>(std::istream& s, vnl_decnum& r); +VNL_EXPORT std::istream & +operator>>(std::istream & s, vnl_decnum & r); -inline vnl_decnum ceil(vnl_decnum const& x) { return x.ceil(); } -inline vnl_decnum floor(vnl_decnum const& x) { return x.floor(); } -inline vnl_decnum pow(vnl_decnum const& x, unsigned long p) { return x.pow(p); } +inline vnl_decnum +ceil(const vnl_decnum & x) +{ + return x.ceil(); +} +inline vnl_decnum +floor(const vnl_decnum & x) +{ + return x.floor(); +} +inline vnl_decnum +pow(const vnl_decnum & x, unsigned long p) +{ + return x.pow(p); +} namespace vnl_math { - inline vnl_decnum abs(vnl_decnum const& x) { return x.abs(); } - inline vnl_decnum sqr(vnl_decnum const& x) { return x*x; } - inline vnl_decnum cube(vnl_decnum const& x) { return x*x*x; } - inline vnl_decnum squared_magnitude(vnl_decnum const& x) { return x*x; } - inline bool isnan(vnl_decnum const& x) { return x.data() == "NaN"; } - inline bool isfinite(vnl_decnum const& x) { return x.data() != "Inf" && x.data() != "NaN"; } - inline vnl_decnum max(vnl_decnum const& x, vnl_decnum const& y) { return (x < y) ? y : x; } - inline vnl_decnum min(vnl_decnum const& x, vnl_decnum const& y) { return (x < y) ? x : y; } - inline int sgn(vnl_decnum x) { return x.sign()==' '?0:x.sign()=='+'?1:-1; } - inline int sgn0(vnl_decnum x) { return x.sign()=='-'?-1:1; } +inline vnl_decnum +abs(const vnl_decnum & x) +{ + return x.abs(); +} +inline vnl_decnum +sqr(const vnl_decnum & x) +{ + return x * x; +} +inline vnl_decnum +cube(const vnl_decnum & x) +{ + return x * x * x; +} +inline vnl_decnum +squared_magnitude(const vnl_decnum & x) +{ + return x * x; +} +inline bool +isnan(const vnl_decnum & x) +{ + return x.data() == "NaN"; +} +inline bool +isfinite(const vnl_decnum & x) +{ + return x.data() != "Inf" && x.data() != "NaN"; +} +inline vnl_decnum +max(const vnl_decnum & x, const vnl_decnum & y) +{ + return (x < y) ? y : x; +} +inline vnl_decnum +min(const vnl_decnum & x, const vnl_decnum & y) +{ + return (x < y) ? x : y; +} +inline int +sgn(vnl_decnum x) +{ + return x.sign() == ' ' ? 0 : x.sign() == '+' ? 1 : -1; +} +inline int +sgn0(vnl_decnum x) +{ + return x.sign() == '-' ? -1 : 1; } +} // namespace vnl_math #endif // vnl_decnum_h_ diff --git a/core/vnl/vnl_decnum_traits.h b/core/vnl/vnl_decnum_traits.h index 08e580add50..358960f2e73 100644 --- a/core/vnl/vnl_decnum_traits.h +++ b/core/vnl/vnl_decnum_traits.h @@ -12,7 +12,7 @@ template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static const vnl_decnum zero; // = 0L //: Multiplicative identity @@ -29,7 +29,6 @@ class VNL_EXPORT vnl_numeric_traits using self = vnl_decnum; //: Name of type which results from using a unary operator-() using signed_t = self; - }; #endif // vnl_decnum_traits_h_ diff --git a/core/vnl/vnl_definite_integral.h b/core/vnl/vnl_definite_integral.h index aeafcba0206..088ed7f783a 100644 --- a/core/vnl/vnl_definite_integral.h +++ b/core/vnl/vnl_definite_integral.h @@ -14,13 +14,17 @@ class VNL_EXPORT vnl_definite_integral { - protected: - static vnl_integrant_fnct *pfnct_; +protected: + static vnl_integrant_fnct * pfnct_; - public: +public: vnl_definite_integral() { pfnct_ = nullptr; } - void set_fnct(vnl_integrant_fnct* f) { pfnct_ = f; } + void + set_fnct(vnl_integrant_fnct * f) + { + pfnct_ = f; + } // destructor virtual ~vnl_definite_integral() { pfnct_ = nullptr; } diff --git a/core/vnl/vnl_det.h b/core/vnl/vnl_det.h index fc5d3fffcad..bd2751331c0 100644 --- a/core/vnl/vnl_det.h +++ b/core/vnl/vnl_det.h @@ -16,38 +16,54 @@ #include "vnl/vnl_export.h" //: 2x2 matrix -template VNL_EXPORT T vnl_det(T const *row0, - T const *row1); +template +VNL_EXPORT T +vnl_det(const T * row0, const T * row1); //: 3x3 matrix -template VNL_EXPORT T vnl_det(T const *row0, - T const *row1, - T const *row2); +template +VNL_EXPORT T +vnl_det(const T * row0, const T * row1, const T * row2); //: 4x4 matrix -template VNL_EXPORT T vnl_det(T const *row0, - T const *row1, - T const *row2, - T const *row3); +template +VNL_EXPORT T +vnl_det(const T * row0, const T * row1, const T * row2, const T * row3); //: Determinant of small size matrices // \relatesalso vnl_matrix_fixed template -inline T vnl_det(vnl_matrix_fixed const& m) { return m[0][0]; } +inline T +vnl_det(const vnl_matrix_fixed & m) +{ + return m[0][0]; +} //: Determinant of small size matrices // \relatesalso vnl_matrix_fixed template -inline T vnl_det(vnl_matrix_fixed const& m) { return vnl_det(m[0],m[1]); } +inline T +vnl_det(const vnl_matrix_fixed & m) +{ + return vnl_det(m[0], m[1]); +} //: Determinant of small size matrices // \relatesalso vnl_matrix_fixed template -inline T vnl_det(vnl_matrix_fixed const& m) { return vnl_det(m[0],m[1],m[2]); } +inline T +vnl_det(const vnl_matrix_fixed & m) +{ + return vnl_det(m[0], m[1], m[2]); +} //: Determinant of small size matrices // \relatesalso vnl_matrix_fixed template -inline T vnl_det(vnl_matrix_fixed const& m) { return vnl_det(m[0],m[1],m[2],m[3]); } +inline T +vnl_det(const vnl_matrix_fixed & m) +{ + return vnl_det(m[0], m[1], m[2], m[3]); +} #endif // vnl_det_h_ diff --git a/core/vnl/vnl_det.hxx b/core/vnl/vnl_det.hxx index cb8b67e07fc..920fd74a565 100644 --- a/core/vnl/vnl_det.hxx +++ b/core/vnl/vnl_det.hxx @@ -5,58 +5,44 @@ #include "vnl_det.h" template -T vnl_det(T const *row0, T const *row1) +T +vnl_det(const T * row0, const T * row1) { - return row0[0]*row1[1] - row0[1]*row1[0]; + return row0[0] * row1[1] - row0[1] * row1[0]; } template -T vnl_det(T const *row0, T const *row1, T const *row2) +T +vnl_det(const T * row0, const T * row1, const T * row2) { return // the extra '+' makes it work nicely with emacs indentation. - + row0[0]*row1[1]*row2[2] - - row0[0]*row2[1]*row1[2] - - row1[0]*row0[1]*row2[2] - + row1[0]*row2[1]*row0[2] - + row2[0]*row0[1]*row1[2] - - row2[0]*row1[1]*row0[2]; + +row0[0] * row1[1] * row2[2] - row0[0] * row2[1] * row1[2] - row1[0] * row0[1] * row2[2] + + row1[0] * row2[1] * row0[2] + row2[0] * row0[1] * row1[2] - row2[0] * row1[1] * row0[2]; } template -T vnl_det(T const *row0, T const *row1, T const *row2, T const *row3) +T +vnl_det(const T * row0, const T * row1, const T * row2, const T * row3) { - return - + row0[0]*row1[1]*row2[2]*row3[3] - - row0[0]*row1[1]*row3[2]*row2[3] - - row0[0]*row2[1]*row1[2]*row3[3] - + row0[0]*row2[1]*row3[2]*row1[3] - + row0[0]*row3[1]*row1[2]*row2[3] - - row0[0]*row3[1]*row2[2]*row1[3] - - row1[0]*row0[1]*row2[2]*row3[3] - + row1[0]*row0[1]*row3[2]*row2[3] - + row1[0]*row2[1]*row0[2]*row3[3] - - row1[0]*row2[1]*row3[2]*row0[3] - - row1[0]*row3[1]*row0[2]*row2[3] - + row1[0]*row3[1]*row2[2]*row0[3] - + row2[0]*row0[1]*row1[2]*row3[3] - - row2[0]*row0[1]*row3[2]*row1[3] - - row2[0]*row1[1]*row0[2]*row3[3] - + row2[0]*row1[1]*row3[2]*row0[3] - + row2[0]*row3[1]*row0[2]*row1[3] - - row2[0]*row3[1]*row1[2]*row0[3] - - row3[0]*row0[1]*row1[2]*row2[3] - + row3[0]*row0[1]*row2[2]*row1[3] - + row3[0]*row1[1]*row0[2]*row2[3] - - row3[0]*row1[1]*row2[2]*row0[3] - - row3[0]*row2[1]*row0[2]*row1[3] - + row3[0]*row2[1]*row1[2]*row0[3]; + return +row0[0] * row1[1] * row2[2] * row3[3] - row0[0] * row1[1] * row3[2] * row2[3] - + row0[0] * row2[1] * row1[2] * row3[3] + row0[0] * row2[1] * row3[2] * row1[3] + + row0[0] * row3[1] * row1[2] * row2[3] - row0[0] * row3[1] * row2[2] * row1[3] - + row1[0] * row0[1] * row2[2] * row3[3] + row1[0] * row0[1] * row3[2] * row2[3] + + row1[0] * row2[1] * row0[2] * row3[3] - row1[0] * row2[1] * row3[2] * row0[3] - + row1[0] * row3[1] * row0[2] * row2[3] + row1[0] * row3[1] * row2[2] * row0[3] + + row2[0] * row0[1] * row1[2] * row3[3] - row2[0] * row0[1] * row3[2] * row1[3] - + row2[0] * row1[1] * row0[2] * row3[3] + row2[0] * row1[1] * row3[2] * row0[3] + + row2[0] * row3[1] * row0[2] * row1[3] - row2[0] * row3[1] * row1[2] * row0[3] - + row3[0] * row0[1] * row1[2] * row2[3] + row3[0] * row0[1] * row2[2] * row1[3] + + row3[0] * row1[1] * row0[2] * row2[3] - row3[0] * row1[1] * row2[2] * row0[3] - + row3[0] * row2[1] * row0[2] * row1[3] + row3[0] * row2[1] * row1[2] * row0[3]; } //-------------------------------------------------------------------------------- -#define VNL_DET_INSTANTIATE(T) \ -template VNL_EXPORT T vnl_det(T const *, T const *); \ -template VNL_EXPORT T vnl_det(T const *, T const *, T const *); \ -template VNL_EXPORT T vnl_det(T const *, T const *, T const *, T const *) +#define VNL_DET_INSTANTIATE(T) \ + template VNL_EXPORT T vnl_det(T const *, T const *); \ + template VNL_EXPORT T vnl_det(T const *, T const *, T const *); \ + template VNL_EXPORT T vnl_det(T const *, T const *, T const *, T const *) #endif // vnl_det_hxx_ diff --git a/core/vnl/vnl_diag_matrix.h b/core/vnl/vnl_diag_matrix.h index dbf777eb5e0..cbfe9f61737 100644 --- a/core/vnl/vnl_diag_matrix.h +++ b/core/vnl/vnl_diag_matrix.h @@ -29,8 +29,11 @@ #include "vnl/vnl_export.h" // forward declarations -template class vnl_diag_matrix; -template VNL_EXPORT vnl_vector operator*(vnl_diag_matrix const&, vnl_vector const&); +template +class vnl_diag_matrix; +template +VNL_EXPORT vnl_vector +operator*(const vnl_diag_matrix &, const vnl_vector &); //: stores a diagonal matrix as a single vector. // vnl_diag_matrix stores a diagonal matrix for time and space efficiency. @@ -43,173 +46,313 @@ class VNL_EXPORT vnl_diag_matrix { vnl_vector diagonal_; - public: +public: vnl_diag_matrix() = default; - vnl_diag_matrix(const vnl_diag_matrix &) = default; - vnl_diag_matrix(vnl_diag_matrix &&) = default; - vnl_diag_matrix& operator=(const vnl_diag_matrix &) = default; - vnl_diag_matrix& operator=(vnl_diag_matrix &&) = default; + vnl_diag_matrix(const vnl_diag_matrix &) = default; + vnl_diag_matrix(vnl_diag_matrix &&) = default; + vnl_diag_matrix & + operator=(const vnl_diag_matrix &) = default; + vnl_diag_matrix & + operator=(vnl_diag_matrix &&) = default; ~vnl_diag_matrix() = default; //: Construct an empty diagonal matrix. - vnl_diag_matrix(unsigned nn) : diagonal_(nn) {} + vnl_diag_matrix(unsigned nn) + : diagonal_(nn) + {} //: Construct a diagonal matrix with diagonal elements equal to value. - vnl_diag_matrix(unsigned nn, T const& value) : diagonal_(nn, value) {} + vnl_diag_matrix(unsigned nn, const T & value) + : diagonal_(nn, value) + {} //: Construct a diagonal matrix from a vnl_vector. // The vector elements become the diagonal elements. - vnl_diag_matrix(vnl_vector that) : diagonal_(std::move(that)) {} + vnl_diag_matrix(vnl_vector that) + : diagonal_(std::move(that)) + {} // Operations---------------------------------------------------------------- //: In-place arithmetic operation - inline vnl_diag_matrix& operator*=(T v) { diagonal_ *= v; return *this; } + inline vnl_diag_matrix & + operator*=(T v) + { + diagonal_ *= v; + return *this; + } //: In-place arithmetic operation - inline vnl_diag_matrix& operator/=(T v) { diagonal_ /= v; return *this; } + inline vnl_diag_matrix & + operator/=(T v) + { + diagonal_ /= v; + return *this; + } // Computations-------------------------------------------------------------- - vnl_diag_matrix& invert_in_place(); - T determinant() const; - vnl_vector solve(vnl_vector const& b) const; - void solve(vnl_vector const& b, vnl_vector* out) const; + vnl_diag_matrix & + invert_in_place(); + T + determinant() const; + vnl_vector + solve(const vnl_vector & b) const; + void + solve(const vnl_vector & b, vnl_vector * out) const; // Data Access--------------------------------------------------------------- - inline T operator () (unsigned i, unsigned j) const { + inline T + operator()(unsigned i, unsigned j) const + { return (i != j) ? T(0) : diagonal_[i]; } - inline T& operator () (unsigned i, unsigned j) { - assert(i == j); (void)j; + inline T & + operator()(unsigned i, unsigned j) + { + assert(i == j); + (void)j; + return diagonal_[i]; + } + inline T & + operator()(unsigned i) + { + return diagonal_[i]; + } + inline const T & + operator()(unsigned i) const + { return diagonal_[i]; } - inline T& operator() (unsigned i) { return diagonal_[i]; } - inline T const& operator() (unsigned i) const { return diagonal_[i]; } - inline T& operator[] (unsigned i) { return diagonal_[i]; } - inline T const& operator[] (unsigned i) const { return diagonal_[i]; } + inline T & + operator[](unsigned i) + { + return diagonal_[i]; + } + inline const T & + operator[](unsigned i) const + { + return diagonal_[i]; + } //: Return a vector (copy) with the content of the (main) diagonal - inline vnl_vector get_diagonal() const { return diagonal_; } + inline vnl_vector + get_diagonal() const + { + return diagonal_; + } //: Return diagonal elements as a vector - inline vnl_vector const& diagonal() const { return diagonal_; } + inline const vnl_vector & + diagonal() const + { + return diagonal_; + } //: Set all diagonal elements of matrix to specified value. - inline vnl_diag_matrix& fill_diagonal (T const& v) { diagonal_.fill(v); return *this; } + inline vnl_diag_matrix & + fill_diagonal(const T & v) + { + diagonal_.fill(v); + return *this; + } //: Sets the diagonal elements of this matrix to the specified list of values. - inline vnl_diag_matrix& set_diagonal(vnl_vector const& v) { diagonal_ = v; return *this; } + inline vnl_diag_matrix & + set_diagonal(const vnl_vector & v) + { + diagonal_ = v; + return *this; + } // iterators typedef typename vnl_vector::iterator iterator; - inline iterator begin() { return diagonal_.begin(); } - inline iterator end() { return diagonal_.end(); } + inline iterator + begin() + { + return diagonal_.begin(); + } + inline iterator + end() + { + return diagonal_.end(); + } typedef typename vnl_vector::const_iterator const_iterator; - inline const_iterator begin() const { return diagonal_.begin(); } - inline const_iterator end() const { return diagonal_.end(); } + inline const_iterator + begin() const + { + return diagonal_.begin(); + } + inline const_iterator + end() const + { + return diagonal_.end(); + } //: Return the total number of elements stored by the matrix. // Since vnl_diag_matrix only stores values on the diagonal // and must be square, size() == rows() == cols(). - inline unsigned int size() const { return diagonal_.size(); } + inline unsigned int + size() const + { + return diagonal_.size(); + } //: Return the number of rows. - inline unsigned int rows() const { return diagonal_.size(); } + inline unsigned int + rows() const + { + return diagonal_.size(); + } //: Return the number of columns. // A synonym for columns(). - inline unsigned int cols() const { return diagonal_.size(); } + inline unsigned int + cols() const + { + return diagonal_.size(); + } //: Return the number of columns. // A synonym for cols(). - inline unsigned int columns() const { return diagonal_.size(); } + inline unsigned int + columns() const + { + return diagonal_.size(); + } //: set element with boundary checks. - inline void put (unsigned r, unsigned c, T const& v) { + inline void + put(unsigned r, unsigned c, const T & v) + { assert(r == c); (void)c; #if VNL_CONFIG_CHECK_BOUNDS - if (r >= this->size()) // If invalid size specified - { + if (r >= this->size()) // If invalid size specified + { vnl_error_matrix_row_index("get", r); // Raise exception - } + } #endif diagonal_[r] = v; } //: get element with boundary checks. - inline T get (unsigned r, unsigned c) const { + inline T + get(unsigned r, unsigned c) const + { assert(r == c); (void)c; #if VNL_CONFIG_CHECK_BOUNDS - if (r >= this->size()) // If invalid size specified - { + if (r >= this->size()) // If invalid size specified + { vnl_error_matrix_row_index("get", r); // Raise exception - } + } #endif return diagonal_[r]; } #if VXL_LEGACY_FUTURE_REMOVE - VXL_DEPRECATED_MSG("Deprecated inconsistent return type.\nWARNING: .as_ref returns a vnl_matrix, not a vnl_matrix_ref, use .as_matrix() directly") + VXL_DEPRECATED_MSG("Deprecated inconsistent return type.\nWARNING: .as_ref returns a vnl_matrix, not a " + "vnl_matrix_ref, use .as_matrix() directly") #endif - vnl_matrix as_ref() const { return as_matrix(); } + vnl_matrix + as_ref() const + { + return as_matrix(); + } // Need this until we add a vnl_diag_matrix ctor to vnl_matrix; - vnl_matrix as_matrix( ) const; -#if ! VXL_LEGACY_FUTURE_REMOVE + vnl_matrix + as_matrix() const; +#if !VXL_LEGACY_FUTURE_REMOVE VXL_DEPRECATED_MSG("Deprecated inconsistent name.\nUSE: .as_matrix() new consistent name.") - vnl_matrix asMatrix () const { return this->as_matrix(); } + vnl_matrix + asMatrix() const + { + return this->as_matrix(); + } #endif // This is as good as a vnl_diag_matrix ctor for vnl_matrix: -#if ! VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS - explicit operator vnl_matrix () const { return this->as_matrix(); } +#if !VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS + explicit + operator vnl_matrix() const + { + return this->as_matrix(); + } #else -#if VXL_LEGACY_FUTURE_REMOVE - VXL_DEPRECATED_MSG("Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") -#endif - operator vnl_matrix () const { return this->as_matrix(); } +# if VXL_LEGACY_FUTURE_REMOVE + VXL_DEPRECATED_MSG( + "Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") +# endif + operator vnl_matrix() const { return this->as_matrix(); } #endif - inline void set_size(int n) { diagonal_.set_size(n); } + inline void + set_size(int n) + { + diagonal_.set_size(n); + } - inline void clear() { diagonal_.clear(); } - inline vnl_diag_matrix& fill(T const &x) { diagonal_.fill(x); return *this; } + inline void + clear() + { + diagonal_.clear(); + } + inline vnl_diag_matrix & + fill(const T & x) + { + diagonal_.fill(x); + return *this; + } //: Return pointer to the diagonal elements as a contiguous 1D C array; - inline T* data_block() { return diagonal_.data_block(); } - inline T const* data_block() const { return diagonal_.data_block(); } + inline T * + data_block() + { + return diagonal_.data_block(); + } + inline const T * + data_block() const + { + return diagonal_.data_block(); + } //: Set diagonal elements using vector - inline vnl_diag_matrix& set(vnl_vector const& v) { diagonal_=v; return *this; } + inline vnl_diag_matrix & + set(const vnl_vector & v) + { + diagonal_ = v; + return *this; + } - private: +private: }; //: // \relatesalso vnl_diag_matrix -template VNL_EXPORT -std::ostream& operator<< (std::ostream&, vnl_diag_matrix const&); +template +VNL_EXPORT std::ostream & +operator<<(std::ostream &, const vnl_diag_matrix &); //: Convert a vnl_diag_matrix to a Matrix. template -vnl_matrix vnl_diag_matrix::as_matrix() const +vnl_matrix +vnl_diag_matrix::as_matrix() const { - unsigned len = diagonal_.size(); + const unsigned len = diagonal_.size(); vnl_matrix ret(len, len); for (unsigned i = 0; i < len; ++i) { unsigned j; for (j = 0; j < i; ++j) - ret(i,j) = T(0); - for (j = i+1; j < len; ++j) - ret(i,j) = T(0); - ret(i,i) = diagonal_[i]; + ret(i, j) = T(0); + for (j = i + 1; j < len; ++j) + ret(i, j) = T(0); + ret(i, i) = diagonal_[i]; } return ret; } @@ -217,10 +360,11 @@ vnl_matrix vnl_diag_matrix::as_matrix() const //: Invert a vnl_diag_matrix in-situ. // Just replaces each element with its reciprocal. template -inline vnl_diag_matrix& vnl_diag_matrix::invert_in_place() +inline vnl_diag_matrix & +vnl_diag_matrix::invert_in_place() { - unsigned len = diagonal_.size(); - T* d = data_block(); + const unsigned len = diagonal_.size(); + T * d = data_block(); T one = T(1); for (unsigned i = 0; i < len; ++i) d[i] = one / d[i]; @@ -229,11 +373,12 @@ inline vnl_diag_matrix& vnl_diag_matrix::invert_in_place() //: Return determinant as product of diagonal values. template -inline T vnl_diag_matrix::determinant() const +inline T +vnl_diag_matrix::determinant() const { T det = T(1); - T const* d = data_block(); - unsigned len = diagonal_.size(); + const T * d = data_block(); + const unsigned len = diagonal_.size(); for (unsigned i = 0; i < len; ++i) det *= d[i]; return det; @@ -242,12 +387,13 @@ inline T vnl_diag_matrix::determinant() const //: Multiply two vnl_diag_matrices. Just multiply the diag elements - n flops // \relatesalso vnl_diag_matrix template -inline vnl_diag_matrix operator* (vnl_diag_matrix const& A, vnl_diag_matrix const& B) +inline vnl_diag_matrix +operator*(const vnl_diag_matrix & A, const vnl_diag_matrix & B) { assert(A.size() == B.size()); vnl_diag_matrix ret = A; for (unsigned i = 0; i < A.size(); ++i) - ret(i,i) *= B(i,i); + ret(i, i) *= B(i, i); return ret; } @@ -255,13 +401,14 @@ inline vnl_diag_matrix operator* (vnl_diag_matrix const& A, vnl_diag_matri // \relatesalso vnl_diag_matrix // \relatesalso vnl_matrix template -inline vnl_matrix operator* (vnl_matrix const& A, vnl_diag_matrix const& D) +inline vnl_matrix +operator*(const vnl_matrix & A, const vnl_diag_matrix & D) { assert(A.columns() == D.size()); vnl_matrix ret(A.rows(), A.columns()); for (unsigned i = 0; i < A.rows(); ++i) for (unsigned j = 0; j < A.columns(); ++j) - ret(i,j) = A(i,j) * D(j,j); + ret(i, j) = A(i, j) * D(j, j); return ret; } @@ -269,26 +416,28 @@ inline vnl_matrix operator* (vnl_matrix const& A, vnl_diag_matrix const // \relatesalso vnl_diag_matrix // \relatesalso vnl_matrix template -inline vnl_matrix operator* (vnl_diag_matrix const& D, vnl_matrix const& A) +inline vnl_matrix +operator*(const vnl_diag_matrix & D, const vnl_matrix & A) { assert(A.rows() == D.size()); vnl_matrix ret(A.rows(), A.columns()); - T const* d = D.data_block(); + const T * d = D.data_block(); for (unsigned i = 0; i < A.rows(); ++i) for (unsigned j = 0; j < A.columns(); ++j) - ret(i,j) = A(i,j) * d[i]; + ret(i, j) = A(i, j) * d[i]; return ret; } //: Add two vnl_diag_matrices. Just add the diag elements - n flops // \relatesalso vnl_diag_matrix template -inline vnl_diag_matrix operator+ (vnl_diag_matrix const& A, vnl_diag_matrix const& B) +inline vnl_diag_matrix +operator+(const vnl_diag_matrix & A, const vnl_diag_matrix & B) { assert(A.size() == B.size()); vnl_diag_matrix ret = A; for (unsigned i = 0; i < A.size(); ++i) - ret(i,i) += B(i,i); + ret(i, i) += B(i, i); return ret; } @@ -296,14 +445,16 @@ inline vnl_diag_matrix operator+ (vnl_diag_matrix const& A, vnl_diag_matri // \relatesalso vnl_diag_matrix // \relatesalso vnl_matrix template -inline vnl_matrix operator+ (vnl_matrix const& A, vnl_diag_matrix const& D) +inline vnl_matrix +operator+(const vnl_matrix & A, const vnl_diag_matrix & D) { const unsigned n = D.size(); - assert(A.rows() == n); assert(A.columns() == n); + assert(A.rows() == n); + assert(A.columns() == n); vnl_matrix ret(A); - T const* d = D.data_block(); + const T * d = D.data_block(); for (unsigned j = 0; j < n; ++j) - ret(j,j) += d[j]; + ret(j, j) += d[j]; return ret; } @@ -311,7 +462,8 @@ inline vnl_matrix operator+ (vnl_matrix const& A, vnl_diag_matrix const // \relatesalso vnl_diag_matrix // \relatesalso vnl_matrix template -inline vnl_matrix operator+ (vnl_diag_matrix const& D, vnl_matrix const& A) +inline vnl_matrix +operator+(const vnl_diag_matrix & D, const vnl_matrix & A) { return A + D; } @@ -319,12 +471,13 @@ inline vnl_matrix operator+ (vnl_diag_matrix const& D, vnl_matrix const //: Subtract two vnl_diag_matrices. Just subtract the diag elements - n flops // \relatesalso vnl_diag_matrix template -inline vnl_diag_matrix operator- (vnl_diag_matrix const& A, vnl_diag_matrix const& B) +inline vnl_diag_matrix +operator-(const vnl_diag_matrix & A, const vnl_diag_matrix & B) { assert(A.size() == B.size()); vnl_diag_matrix ret = A; for (unsigned i = 0; i < A.size(); ++i) - ret(i,i) -= B(i,i); + ret(i, i) -= B(i, i); return ret; } @@ -332,14 +485,16 @@ inline vnl_diag_matrix operator- (vnl_diag_matrix const& A, vnl_diag_matri // \relatesalso vnl_diag_matrix // \relatesalso vnl_matrix template -inline vnl_matrix operator- (vnl_matrix const& A, vnl_diag_matrix const& D) +inline vnl_matrix +operator-(const vnl_matrix & A, const vnl_diag_matrix & D) { const unsigned n = D.size(); - assert(A.rows() == n); assert(A.columns() == n); + assert(A.rows() == n); + assert(A.columns() == n); vnl_matrix ret(A); - T const* d = D.data_block(); + const T * d = D.data_block(); for (unsigned j = 0; j < n; ++j) - ret(j,j) -= d[j]; + ret(j, j) -= d[j]; return ret; } @@ -347,19 +502,21 @@ inline vnl_matrix operator- (vnl_matrix const& A, vnl_diag_matrix const // \relatesalso vnl_diag_matrix // \relatesalso vnl_matrix template -inline vnl_matrix operator- (vnl_diag_matrix const& D, vnl_matrix const& A) +inline vnl_matrix +operator-(const vnl_diag_matrix & D, const vnl_matrix & A) { const unsigned n = D.size(); - assert(A.rows() == n); assert(A.columns() == n); + assert(A.rows() == n); + assert(A.columns() == n); vnl_matrix ret(n, n); - T const* d = D.data_block(); + const T * d = D.data_block(); for (unsigned i = 0; i < n; ++i) { for (unsigned j = 0; j < i; ++j) - ret(i,j) = -A(i,j); - for (unsigned j = i+1; j < n; ++j) - ret(i,j) = -A(i,j); - ret(i,i) = d[i] - A(i,i); + ret(i, j) = -A(i, j); + for (unsigned j = i + 1; j < n; ++j) + ret(i, j) = -A(i, j); + ret(i, i) = d[i] - A(i, i); } return ret; } @@ -368,7 +525,8 @@ inline vnl_matrix operator- (vnl_diag_matrix const& D, vnl_matrix const // \relatesalso vnl_diag_matrix // \relatesalso vnl_vector template -inline vnl_vector operator* (vnl_diag_matrix const& D, vnl_vector const& A) +inline vnl_vector +operator*(const vnl_diag_matrix & D, const vnl_vector & A) { assert(A.size() == D.size()); return element_product(D.diagonal(), A); @@ -378,7 +536,8 @@ inline vnl_vector operator* (vnl_diag_matrix const& D, vnl_vector const // \relatesalso vnl_diag_matrix // \relatesalso vnl_vector template -inline vnl_vector operator* (vnl_vector const& A, vnl_diag_matrix const& D) +inline vnl_vector +operator*(const vnl_vector & A, const vnl_diag_matrix & D) { assert(A.size() == D.size()); return element_product(D.diagonal(), A); diff --git a/core/vnl/vnl_diag_matrix.hxx b/core/vnl/vnl_diag_matrix.hxx index 73fbfd4e7d0..0ea9df276db 100644 --- a/core/vnl/vnl_diag_matrix.hxx +++ b/core/vnl/vnl_diag_matrix.hxx @@ -14,9 +14,10 @@ //: Return inv(D) * b. template -vnl_vector vnl_diag_matrix::solve(vnl_vector const& b) const +vnl_vector +vnl_diag_matrix::solve(const vnl_vector & b) const { - unsigned len = diagonal_.size(); + const unsigned len = diagonal_.size(); vnl_vector ret(len); for (unsigned i = 0; i < len; ++i) ret[i] = b[i] / diagonal_[i]; @@ -25,36 +26,38 @@ vnl_vector vnl_diag_matrix::solve(vnl_vector const& b) const //: Return inv(D) * b. template -void vnl_diag_matrix::solve(vnl_vector const& b, vnl_vector* out) const +void +vnl_diag_matrix::solve(const vnl_vector & b, vnl_vector * out) const { - unsigned len = diagonal_.size(); + const unsigned len = diagonal_.size(); for (unsigned i = 0; i < len; ++i) (*out)[i] = b[i] / diagonal_[i]; } //: Print in MATLAB diag([1 2 3]) form. template -std::ostream& operator<< (std::ostream& s, const vnl_diag_matrix& D) +std::ostream & +operator<<(std::ostream & s, const vnl_diag_matrix & D) { s << "diag([ "; - for (unsigned i=0; i; \ -/*template VNL_EXPORT vnl_matrix operator* (vnl_matrix const &, vnl_diag_matrix const &); */\ -/*template VNL_EXPORT vnl_matrix operator* (vnl_diag_matrix const &, vnl_matrix const &); */\ -/*template VNL_EXPORT vnl_matrix operator+ (vnl_matrix const &, vnl_diag_matrix const &); */\ -/*template VNL_EXPORT vnl_matrix operator+ (vnl_diag_matrix const &, vnl_matrix const &); */\ -/*template VNL_EXPORT vnl_matrix operator- (vnl_matrix const &, vnl_diag_matrix const &); */\ -/*template VNL_EXPORT vnl_matrix operator- (vnl_diag_matrix const &, vnl_matrix const &); */\ -/*template VNL_EXPORT vnl_vector operator* (const vnl_vector&, vnl_diag_matrix const &); */\ -/*template VNL_EXPORT vnl_vector operator* (vnl_diag_matrix const &, const vnl_vector&); */\ -template VNL_EXPORT std::ostream& operator<< (std::ostream& s, vnl_diag_matrix const &) - -//template bool epsilon_equals (vnl_diag_matrix const & , vnl_diag_matrix const & , double) +#define VNL_DIAG_MATRIX_INSTANTIATE(T) \ + template class VNL_EXPORT vnl_diag_matrix; \ + /*template VNL_EXPORT vnl_matrix operator* (vnl_matrix const &, vnl_diag_matrix const &); */ \ + /*template VNL_EXPORT vnl_matrix operator* (vnl_diag_matrix const &, vnl_matrix const &); */ \ + /*template VNL_EXPORT vnl_matrix operator+ (vnl_matrix const &, vnl_diag_matrix const &); */ \ + /*template VNL_EXPORT vnl_matrix operator+ (vnl_diag_matrix const &, vnl_matrix const &); */ \ + /*template VNL_EXPORT vnl_matrix operator- (vnl_matrix const &, vnl_diag_matrix const &); */ \ + /*template VNL_EXPORT vnl_matrix operator- (vnl_diag_matrix const &, vnl_matrix const &); */ \ + /*template VNL_EXPORT vnl_vector operator* (const vnl_vector&, vnl_diag_matrix const &); */ \ + /*template VNL_EXPORT vnl_vector operator* (vnl_diag_matrix const &, const vnl_vector&); */ \ + template VNL_EXPORT std::ostream & operator<<(std::ostream & s, vnl_diag_matrix const &) + +// template bool epsilon_equals (vnl_diag_matrix const & , vnl_diag_matrix const & , double) #endif // vnl_diag_matrix_hxx_ diff --git a/core/vnl/vnl_diag_matrix_fixed.h b/core/vnl/vnl_diag_matrix_fixed.h index bfbb261bd84..715631661e4 100644 --- a/core/vnl/vnl_diag_matrix_fixed.h +++ b/core/vnl/vnl_diag_matrix_fixed.h @@ -27,8 +27,11 @@ #include "vnl/vnl_export.h" // forward declarations -template class vnl_diag_matrix_fixed; -template VNL_EXPORT vnl_vector_fixed operator*(vnl_diag_matrix_fixed const&, vnl_vector_fixed const&); +template +class vnl_diag_matrix_fixed; +template +VNL_EXPORT vnl_vector_fixed +operator*(const vnl_diag_matrix_fixed &, const vnl_vector_fixed &); //: stores a diagonal matrix as a single vector. // vnl_diag_matrix_fixed stores a diagonal matrix for time and space efficiency. @@ -39,95 +42,174 @@ template VNL_EXPORT vnl_vector_fixed operator*(vn template class VNL_EXPORT vnl_diag_matrix_fixed { - vnl_vector_fixed diagonal_; + vnl_vector_fixed diagonal_; - public: +public: vnl_diag_matrix_fixed() = default; - vnl_diag_matrix_fixed(const vnl_diag_matrix_fixed & that) = default; - vnl_diag_matrix_fixed(vnl_diag_matrix_fixed && that) = default; - vnl_diag_matrix_fixed& operator=(const vnl_diag_matrix_fixed & that) = default; - vnl_diag_matrix_fixed& operator=(vnl_diag_matrix_fixed && that) = default; + vnl_diag_matrix_fixed(const vnl_diag_matrix_fixed & that) = default; + vnl_diag_matrix_fixed(vnl_diag_matrix_fixed && that) = default; + vnl_diag_matrix_fixed & + operator=(const vnl_diag_matrix_fixed & that) = default; + vnl_diag_matrix_fixed & + operator=(vnl_diag_matrix_fixed && that) = default; ~vnl_diag_matrix_fixed() = default; //: Construct a diagonal matrix with diagonal elements equal to value. - vnl_diag_matrix_fixed(T const& value) : diagonal_(value) {} + vnl_diag_matrix_fixed(const T & value) + : diagonal_(value) + {} //: Construct a diagonal matrix from a vnl_vector_fixed. // The vector elements become the diagonal elements. - explicit vnl_diag_matrix_fixed(vnl_vector_fixed const& that): diagonal_(that) {} + explicit vnl_diag_matrix_fixed(const vnl_vector_fixed & that) + : diagonal_(that) + {} // Operations---------------------------------------------------------------- //: In-place arithmetic operation - inline vnl_diag_matrix_fixed& operator*=(T v) { diagonal_ *= v; return *this; } + inline vnl_diag_matrix_fixed & + operator*=(T v) + { + diagonal_ *= v; + return *this; + } //: In-place arithmetic operation - inline vnl_diag_matrix_fixed& operator/=(T v) { diagonal_ /= v; return *this; } + inline vnl_diag_matrix_fixed & + operator/=(T v) + { + diagonal_ /= v; + return *this; + } // Computations-------------------------------------------------------------- - inline vnl_diag_matrix_fixed& invert_in_place(); - T determinant() const; - vnl_vector_fixed solve(vnl_vector_fixed const& b) const; - void solve(vnl_vector_fixed const& b, vnl_vector_fixed* out) const; + inline vnl_diag_matrix_fixed & + invert_in_place(); + T + determinant() const; + vnl_vector_fixed + solve(const vnl_vector_fixed & b) const; + void + solve(const vnl_vector_fixed & b, vnl_vector_fixed * out) const; // Data Access--------------------------------------------------------------- - inline T operator () (unsigned i, unsigned j) const { + inline T + operator()(unsigned i, unsigned j) const + { return (i != j) ? T(0) : diagonal_[i]; } - inline T& operator () (unsigned i, unsigned j) { + inline T & + operator()(unsigned i, unsigned j) + { assert(i == j); // Avoid unused parameter warning (void)j; return diagonal_[i]; } - inline T& operator() (unsigned i) { return diagonal_[i]; } - inline T const& operator() (unsigned i) const { return diagonal_[i]; } + inline T & + operator()(unsigned i) + { + return diagonal_[i]; + } + inline const T & + operator()(unsigned i) const + { + return diagonal_[i]; + } - inline T& operator[] (unsigned i) { return diagonal_[i]; } - inline T const& operator[] (unsigned i) const { return diagonal_[i]; } + inline T & + operator[](unsigned i) + { + return diagonal_[i]; + } + inline const T & + operator[](unsigned i) const + { + return diagonal_[i]; + } //: Return a vector (copy) with the content of the (main) diagonal - inline vnl_vector_fixed get_diagonal() const { return diagonal_; } + inline vnl_vector_fixed + get_diagonal() const + { + return diagonal_; + } //: Return diagonal elements as a vector - inline vnl_vector_fixed const& diagonal() const { return diagonal_; } + inline const vnl_vector_fixed & + diagonal() const + { + return diagonal_; + } //: Set all diagonal elements of matrix to specified value. - inline vnl_diag_matrix_fixed& fill_diagonal (T const& v) { diagonal_.fill(v); return *this; } + inline vnl_diag_matrix_fixed & + fill_diagonal(const T & v) + { + diagonal_.fill(v); + return *this; + } //: Sets the diagonal elements of this matrix to the specified list of values. - inline vnl_diag_matrix_fixed& set_diagonal(vnl_vector_fixed const& v) { diagonal_ = v; return *this; } + inline vnl_diag_matrix_fixed & + set_diagonal(const vnl_vector_fixed & v) + { + diagonal_ = v; + return *this; + } // iterators - typedef typename vnl_vector_fixed::iterator iterator; - iterator begin(); - iterator end(); - typedef typename vnl_vector_fixed::const_iterator const_iterator; - const_iterator begin() const; - const_iterator end() const; + typedef typename vnl_vector_fixed::iterator iterator; + iterator + begin(); + iterator + end(); + typedef typename vnl_vector_fixed::const_iterator const_iterator; + const_iterator + begin() const; + const_iterator + end() const; //: Return the total number of elements stored by the matrix. // Since vnl_diag_matrix_fixed only stores values on the diagonal // and must be square, size() == rows() == cols(). - inline unsigned int size() const { return diagonal_.size(); } + inline unsigned int + size() const + { + return diagonal_.size(); + } //: Return the number of rows. - inline unsigned int rows() const { return diagonal_.size(); } + inline unsigned int + rows() const + { + return diagonal_.size(); + } //: Return the number of columns. // A synonym for columns(). - inline unsigned int cols() const { return diagonal_.size(); } + inline unsigned int + cols() const + { + return diagonal_.size(); + } //: Return the number of columns. // A synonym for cols(). - inline unsigned int columns() const { return diagonal_.size(); } + inline unsigned int + columns() const + { + return diagonal_.size(); + } //: set element with boundary checks. - inline void put (unsigned r, unsigned c, T const& v) + inline void + put(unsigned r, unsigned c, const T & v) { assert(r == c); (void)c; @@ -139,7 +221,8 @@ class VNL_EXPORT vnl_diag_matrix_fixed } //: get element with boundary checks. - inline T get (unsigned r, unsigned c) const + inline T + get(unsigned r, unsigned c) const { assert(r == c); (void)c; @@ -151,43 +234,72 @@ class VNL_EXPORT vnl_diag_matrix_fixed } // Need this until we add a vnl_diag_matrix_fixed ctor to vnl_matrix; - inline vnl_matrix_fixed as_matrix_fixed() const; + inline vnl_matrix_fixed + as_matrix_fixed() const; - inline vnl_matrix_fixed as_ref() const { return as_matrix_fixed(); } + inline vnl_matrix_fixed + as_ref() const + { + return as_matrix_fixed(); + } // This is as good as a vnl_diag_matrix_fixed ctor for vnl_matrix_fixed: - inline operator vnl_matrix_fixed () const { return as_matrix_fixed(); } + inline + operator vnl_matrix_fixed() const + { + return as_matrix_fixed(); + } - inline vnl_diag_matrix_fixed& fill(T const &x) { diagonal_.fill(x); return *this; } + inline vnl_diag_matrix_fixed & + fill(const T & x) + { + diagonal_.fill(x); + return *this; + } //: Return pointer to the diagonal elements as a contiguous 1D C array; - inline T* data_block() { return diagonal_.data_block(); } - inline T const* data_block() const { return diagonal_.data_block(); } + inline T * + data_block() + { + return diagonal_.data_block(); + } + inline const T * + data_block() const + { + return diagonal_.data_block(); + } //: Set diagonal elements using vector, then return *this - inline vnl_diag_matrix_fixed& set(vnl_vector_fixed const& v) { diagonal_=v; return *this; } + inline vnl_diag_matrix_fixed & + set(const vnl_vector_fixed & v) + { + diagonal_ = v; + return *this; + } - private: +private: }; //: // \relatesalso vnl_diag_matrix_fixed -template VNL_EXPORT -std::ostream& operator<< (std::ostream&, vnl_diag_matrix_fixed const&); +template +VNL_EXPORT std::ostream & +operator<<(std::ostream &, const vnl_diag_matrix_fixed &); //: Convert a vnl_diag_matrix_fixed to a Matrix. template -inline vnl_matrix_fixed vnl_diag_matrix_fixed::as_matrix_fixed() const +inline vnl_matrix_fixed +vnl_diag_matrix_fixed::as_matrix_fixed() const { - vnl_matrix_fixed ret; + vnl_matrix_fixed ret; for (unsigned i = 0; i < N; ++i) { unsigned j; for (j = 0; j < i; ++j) - ret(i,j) = T(0); - for (j = i+1; j < N; ++j) - ret(i,j) = T(0); - ret(i,i) = diagonal_[i]; + ret(i, j) = T(0); + for (j = i + 1; j < N; ++j) + ret(i, j) = T(0); + ret(i, i) = diagonal_[i]; } return ret; } @@ -195,9 +307,10 @@ inline vnl_matrix_fixed vnl_diag_matrix_fixed::as_matrix_fixed() con //: Invert a vnl_diag_matrix_fixed in-situ, then returns *this. // Just replaces each element with its reciprocal. template -inline vnl_diag_matrix_fixed& vnl_diag_matrix_fixed::invert_in_place() +inline vnl_diag_matrix_fixed & +vnl_diag_matrix_fixed::invert_in_place() { - T* d = data_block(); + T * d = data_block(); T one = T(1); for (unsigned i = 0; i < N; ++i) d[i] = one / d[i]; @@ -206,10 +319,11 @@ inline vnl_diag_matrix_fixed& vnl_diag_matrix_fixed::invert_in_place() //: Return determinant as product of diagonal values. template -inline T vnl_diag_matrix_fixed::determinant() const +inline T +vnl_diag_matrix_fixed::determinant() const { T det = T(1); - T const* d = data_block(); + const T * d = data_block(); for (unsigned i = 0; i < N; ++i) det *= d[i]; return det; @@ -218,11 +332,12 @@ inline T vnl_diag_matrix_fixed::determinant() const //: Multiply two vnl_diag_matrices. Just multiply the diag elements - n flops // \relatesalso vnl_diag_matrix_fixed template -inline vnl_diag_matrix_fixed operator* (vnl_diag_matrix_fixed const& A, vnl_diag_matrix_fixed const& B) +inline vnl_diag_matrix_fixed +operator*(const vnl_diag_matrix_fixed & A, const vnl_diag_matrix_fixed & B) { - vnl_diag_matrix_fixed ret = A; + vnl_diag_matrix_fixed ret = A; for (unsigned i = 0; i < N; ++i) - ret(i,i) *= B(i,i); + ret(i, i) *= B(i, i); return ret; } @@ -230,12 +345,13 @@ inline vnl_diag_matrix_fixed operator* (vnl_diag_matrix_fixed const& A // \relatesalso vnl_diag_matrix_fixed // \relatesalso vnl_matrix template -inline vnl_matrix_fixed operator* (vnl_matrix_fixed const& A, vnl_diag_matrix_fixed const& D) +inline vnl_matrix_fixed +operator*(const vnl_matrix_fixed & A, const vnl_diag_matrix_fixed & D) { - vnl_matrix_fixed ret; + vnl_matrix_fixed ret; for (unsigned i = 0; i < R; ++i) for (unsigned j = 0; j < C; ++j) - ret(i,j) = A(i,j) * D(j,j); + ret(i, j) = A(i, j) * D(j, j); return ret; } @@ -243,24 +359,26 @@ inline vnl_matrix_fixed operator* (vnl_matrix_fixed const& A, vnl_ // \relatesalso vnl_diag_matrix_fixed // \relatesalso vnl_matrix template -inline vnl_matrix_fixed operator* (vnl_diag_matrix_fixed const& D, vnl_matrix_fixed const& A) +inline vnl_matrix_fixed +operator*(const vnl_diag_matrix_fixed & D, const vnl_matrix_fixed & A) { - vnl_matrix_fixed ret; - T const* d = D.data_block(); + vnl_matrix_fixed ret; + const T * d = D.data_block(); for (unsigned i = 0; i < R; ++i) for (unsigned j = 0; j < C; ++j) - ret(i,j) = A(i,j) * d[i]; + ret(i, j) = A(i, j) * d[i]; return ret; } //: Add two vnl_diag_matrices. Just add the diag elements - n flops // \relatesalso vnl_diag_matrix_fixed template -inline vnl_diag_matrix_fixed operator+ (vnl_diag_matrix_fixed const& A, vnl_diag_matrix_fixed const& B) +inline vnl_diag_matrix_fixed +operator+(const vnl_diag_matrix_fixed & A, const vnl_diag_matrix_fixed & B) { - vnl_diag_matrix_fixed ret = A; + vnl_diag_matrix_fixed ret = A; for (unsigned i = 0; i < N; ++i) - ret(i,i) += B(i,i); + ret(i, i) += B(i, i); return ret; } @@ -268,12 +386,13 @@ inline vnl_diag_matrix_fixed operator+ (vnl_diag_matrix_fixed const& A // \relatesalso vnl_diag_matrix_fixed // \relatesalso vnl_matrix template -inline vnl_matrix_fixed operator+ (vnl_matrix_fixed const& A, vnl_diag_matrix_fixed const& D) +inline vnl_matrix_fixed +operator+(const vnl_matrix_fixed & A, const vnl_diag_matrix_fixed & D) { - vnl_matrix_fixed ret(A); - T const* d = D.data_block(); + vnl_matrix_fixed ret(A); + const T * d = D.data_block(); for (unsigned j = 0; j < N; ++j) - ret(j,j) += d[j]; + ret(j, j) += d[j]; return ret; } @@ -281,7 +400,8 @@ inline vnl_matrix_fixed operator+ (vnl_matrix_fixed const& A, vnl_ // \relatesalso vnl_diag_matrix_fixed // \relatesalso vnl_matrix template -inline vnl_matrix_fixed operator+ (vnl_diag_matrix_fixed const& D, vnl_matrix_fixed const& A) +inline vnl_matrix_fixed +operator+(const vnl_diag_matrix_fixed & D, const vnl_matrix_fixed & A) { return A + D; } @@ -289,11 +409,12 @@ inline vnl_matrix_fixed operator+ (vnl_diag_matrix_fixed const& D, v //: Subtract two vnl_diag_matrices. Just subtract the diag elements - n flops // \relatesalso vnl_diag_matrix_fixed template -inline vnl_diag_matrix_fixed operator- (vnl_diag_matrix_fixed const& A, vnl_diag_matrix_fixed const& B) +inline vnl_diag_matrix_fixed +operator-(const vnl_diag_matrix_fixed & A, const vnl_diag_matrix_fixed & B) { - vnl_diag_matrix_fixed ret(A); + vnl_diag_matrix_fixed ret(A); for (unsigned i = 0; i < N; ++i) - ret(i,i) -= B(i,i); + ret(i, i) -= B(i, i); return ret; } @@ -301,12 +422,13 @@ inline vnl_diag_matrix_fixed operator- (vnl_diag_matrix_fixed const& A // \relatesalso vnl_diag_matrix_fixed // \relatesalso vnl_matrix template -inline vnl_matrix_fixed operator- (vnl_matrix_fixed const& A, vnl_diag_matrix_fixed const& D) +inline vnl_matrix_fixed +operator-(const vnl_matrix_fixed & A, const vnl_diag_matrix_fixed & D) { - vnl_matrix_fixed ret(A); - T const* d = D.data_block(); + vnl_matrix_fixed ret(A); + const T * d = D.data_block(); for (unsigned j = 0; j < N; ++j) - ret(j,j) -= d[j]; + ret(j, j) -= d[j]; return ret; } @@ -314,17 +436,18 @@ inline vnl_matrix_fixed operator- (vnl_matrix_fixed const& A, vnl_ // \relatesalso vnl_diag_matrix_fixed // \relatesalso vnl_matrix template -inline vnl_matrix_fixed operator- (vnl_diag_matrix_fixed const& D, vnl_matrix_fixed const& A) +inline vnl_matrix_fixed +operator-(const vnl_diag_matrix_fixed & D, const vnl_matrix_fixed & A) { - vnl_matrix_fixed ret; - T const* d = D.data_block(); + vnl_matrix_fixed ret; + const T * d = D.data_block(); for (unsigned i = 0; i < N; ++i) { for (unsigned j = 0; j < i; ++j) - ret(i,j) = -A(i,j); - for (unsigned j = i+1; j < N; ++j) - ret(i,j) = -A(i,j); - ret(i,i) = d[i] - A(i,i); + ret(i, j) = -A(i, j); + for (unsigned j = i + 1; j < N; ++j) + ret(i, j) = -A(i, j); + ret(i, i) = d[i] - A(i, i); } return ret; } @@ -333,7 +456,8 @@ inline vnl_matrix_fixed operator- (vnl_diag_matrix_fixed const& D, v // \relatesalso vnl_diag_matrix_fixed // \relatesalso vnl_vector_fixed template -inline vnl_vector_fixed operator* (vnl_diag_matrix_fixed const& D, vnl_vector_fixed const& A) +inline vnl_vector_fixed +operator*(const vnl_diag_matrix_fixed & D, const vnl_vector_fixed & A) { return element_product(D.diagonal(), A); } @@ -342,7 +466,8 @@ inline vnl_vector_fixed operator* (vnl_diag_matrix_fixed const& D, vnl // \relatesalso vnl_diag_matrix_fixed // \relatesalso vnl_vector_fixed template -inline vnl_vector_fixed operator* (vnl_vector_fixed const& A, vnl_diag_matrix_fixed const& D) +inline vnl_vector_fixed +operator*(const vnl_vector_fixed & A, const vnl_diag_matrix_fixed & D) { return element_product(D.diagonal(), A); } diff --git a/core/vnl/vnl_diag_matrix_fixed.hxx b/core/vnl/vnl_diag_matrix_fixed.hxx index 9c54e889fa7..e9aaec3f775 100644 --- a/core/vnl/vnl_diag_matrix_fixed.hxx +++ b/core/vnl/vnl_diag_matrix_fixed.hxx @@ -13,25 +13,38 @@ template typename vnl_diag_matrix_fixed::iterator -vnl_diag_matrix_fixed::begin() { return diagonal_.begin(); } +vnl_diag_matrix_fixed::begin() +{ + return diagonal_.begin(); +} template typename vnl_diag_matrix_fixed::iterator -vnl_diag_matrix_fixed::end() { return diagonal_.end(); } +vnl_diag_matrix_fixed::end() +{ + return diagonal_.end(); +} template typename vnl_diag_matrix_fixed::const_iterator -vnl_diag_matrix_fixed::begin() const { return diagonal_.begin(); } +vnl_diag_matrix_fixed::begin() const +{ + return diagonal_.begin(); +} template typename vnl_diag_matrix_fixed::const_iterator -vnl_diag_matrix_fixed::end() const { return diagonal_.end(); } +vnl_diag_matrix_fixed::end() const +{ + return diagonal_.end(); +} //: Return inv(D) * b. template -vnl_vector_fixed vnl_diag_matrix_fixed::solve(vnl_vector_fixed const& b) const +vnl_vector_fixed +vnl_diag_matrix_fixed::solve(const vnl_vector_fixed & b) const { - vnl_vector_fixed ret; + vnl_vector_fixed ret; for (unsigned i = 0; i < N; ++i) ret[i] = b[i] / diagonal_[i]; return ret; @@ -39,7 +52,8 @@ vnl_vector_fixed vnl_diag_matrix_fixed::solve(vnl_vector_fixed co //: Return inv(D) * b. template -void vnl_diag_matrix_fixed::solve(vnl_vector_fixed const& b, vnl_vector_fixed* out) const +void +vnl_diag_matrix_fixed::solve(const vnl_vector_fixed & b, vnl_vector_fixed * out) const { for (unsigned i = 0; i < N; ++i) (*out)[i] = b[i] / diagonal_[i]; @@ -47,19 +61,20 @@ void vnl_diag_matrix_fixed::solve(vnl_vector_fixed const& b, vnl_vecto //: Print in MATLAB diag([1 2 3]) form. template -std::ostream& operator<< (std::ostream& s, const vnl_diag_matrix_fixed& D) +std::ostream & +operator<<(std::ostream & s, const vnl_diag_matrix_fixed & D) { s << "diag([ "; - for (unsigned i=0; i; \ -template VNL_EXPORT std::ostream& operator<< (std::ostream& s, vnl_diag_matrix_fixed const &) +#define VNL_DIAG_MATRIX_FIXED_INSTANTIATE(T, N) \ + template class VNL_EXPORT vnl_diag_matrix_fixed; \ + template VNL_EXPORT std::ostream & operator<<(std::ostream & s, vnl_diag_matrix_fixed const &) -//template bool epsilon_equals (vnl_diag_matrix_fixed const & , vnl_diag_matrix_fixed const & , double) +// template bool epsilon_equals (vnl_diag_matrix_fixed const & , vnl_diag_matrix_fixed const & , double) #endif // vnl_diag_matrix_fixed_hxx_ diff --git a/core/vnl/vnl_double_1x1.h b/core/vnl/vnl_double_1x1.h index 35f3bafdc9b..d3ed105d881 100644 --- a/core/vnl/vnl_double_1x1.h +++ b/core/vnl/vnl_double_1x1.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_1x1; +typedef vnl_matrix_fixed vnl_double_1x1; #endif // vnl_double_1x1_h_ diff --git a/core/vnl/vnl_double_1x2.h b/core/vnl/vnl_double_1x2.h index 638232da99f..34d2af07118 100644 --- a/core/vnl/vnl_double_1x2.h +++ b/core/vnl/vnl_double_1x2.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_1x2; +typedef vnl_matrix_fixed vnl_double_1x2; #endif // vnl_double_1x2_h_ diff --git a/core/vnl/vnl_double_1x3.h b/core/vnl/vnl_double_1x3.h index b039fdca5df..b334d9808c0 100644 --- a/core/vnl/vnl_double_1x3.h +++ b/core/vnl/vnl_double_1x3.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_1x3; +typedef vnl_matrix_fixed vnl_double_1x3; #endif // vnl_double_1x3_h_ diff --git a/core/vnl/vnl_double_2.h b/core/vnl/vnl_double_2.h index 45665ae035c..8b8bb1dc7ea 100644 --- a/core/vnl/vnl_double_2.h +++ b/core/vnl/vnl_double_2.h @@ -17,12 +17,12 @@ #include "vnl_T_n.h" //: class vnl_double_2 : a vnl_vector of 2 doubles. -vnl_T_n_impl(double,2); +vnl_T_n_impl(double, 2); //: Cross product of two 2-vectors // \relatesalso vnl_vector_fixed -inline -double vnl_cross_2d(vnl_double_2 const& v1, vnl_double_2 const& v2) +inline double +vnl_cross_2d(const vnl_double_2 & v1, const vnl_double_2 & v2) { return v1[0] * v2[1] - v1[1] * v2[0]; } diff --git a/core/vnl/vnl_double_2x1.h b/core/vnl/vnl_double_2x1.h index cc7ab0e947d..82bfa0b0a91 100644 --- a/core/vnl/vnl_double_2x1.h +++ b/core/vnl/vnl_double_2x1.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_2x1; +typedef vnl_matrix_fixed vnl_double_2x1; #endif // vnl_double_2x1_h_ diff --git a/core/vnl/vnl_double_2x2.h b/core/vnl/vnl_double_2x2.h index cda9032fe01..91057e083b2 100644 --- a/core/vnl/vnl_double_2x2.h +++ b/core/vnl/vnl_double_2x2.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_2x2; +typedef vnl_matrix_fixed vnl_double_2x2; #endif // vnl_double_2x2_h_ diff --git a/core/vnl/vnl_double_2x3.h b/core/vnl/vnl_double_2x3.h index 9649b6bf50a..0eb4618740a 100644 --- a/core/vnl/vnl_double_2x3.h +++ b/core/vnl/vnl_double_2x3.h @@ -21,27 +21,36 @@ class VNL_EXPORT vnl_double_2x3 : public vnl_matrix_fixed { - private: +private: typedef vnl_matrix_fixed Base; - public: +public: vnl_double_2x3() = default; - vnl_double_2x3(const vnl_double_3& row1, const vnl_double_3& row2) + vnl_double_2x3(const vnl_double_3 & row1, const vnl_double_3 & row2) { - vnl_double_2x3& M = *this; - M(0,0) = row1[0]; M(0,1) = row1[1]; M(0,2) = row1[2]; - M(1,0) = row2[0]; M(1,1) = row2[1]; M(1,2) = row2[2]; + vnl_double_2x3 & M = *this; + M(0, 0) = row1[0]; + M(0, 1) = row1[1]; + M(0, 2) = row1[2]; + M(1, 0) = row2[0]; + M(1, 1) = row2[1]; + M(1, 2) = row2[2]; } - vnl_double_2x3(double r00, double r01, double r02, - double r10, double r11, double r12) + vnl_double_2x3(double r00, double r01, double r02, double r10, double r11, double r12) { - vnl_double_2x3& M = *this; - M(0,0) = r00; M(0,1) = r01; M(0,2) = r02; - M(1,0) = r10; M(1,1) = r11; M(1,2) = r12; + vnl_double_2x3 & M = *this; + M(0, 0) = r00; + M(0, 1) = r01; + M(0, 2) = r02; + M(1, 0) = r10; + M(1, 1) = r11; + M(1, 2) = r12; } - vnl_double_2x3(Base const& M) : Base(M) { } + vnl_double_2x3(const Base & M) + : Base(M) + {} }; #endif // vnl_double_2x3_h_ diff --git a/core/vnl/vnl_double_3.h b/core/vnl/vnl_double_3.h index 81233e97da7..14488f851de 100644 --- a/core/vnl/vnl_double_3.h +++ b/core/vnl/vnl_double_3.h @@ -17,12 +17,12 @@ #include "vnl_T_n.h" //: class vnl_double_3 : a vnl_vector of 3 doubles. -vnl_T_n_impl(double,3); +vnl_T_n_impl(double, 3); //: Cross product of two 3-vectors // \relatesalso vnl_vector_fixed -inline -vnl_double_3 vnl_cross_3d(vnl_double_3 const& v1, vnl_double_3 const& v2) +inline vnl_double_3 +vnl_cross_3d(const vnl_double_3 & v1, const vnl_double_3 & v2) { vnl_double_3 result; result[0] = v1[1] * v2[2] - v1[2] * v2[1]; diff --git a/core/vnl/vnl_double_3x1.h b/core/vnl/vnl_double_3x1.h index 2f50f6f510c..53a0012a1b7 100644 --- a/core/vnl/vnl_double_3x1.h +++ b/core/vnl/vnl_double_3x1.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_3x1; +typedef vnl_matrix_fixed vnl_double_3x1; #endif // vnl_double_3x1_h_ diff --git a/core/vnl/vnl_double_3x2.h b/core/vnl/vnl_double_3x2.h index 429ea36a1fe..fb41829249d 100644 --- a/core/vnl/vnl_double_3x2.h +++ b/core/vnl/vnl_double_3x2.h @@ -20,19 +20,21 @@ class VNL_EXPORT vnl_double_3x2 : public vnl_matrix_fixed { - private: +private: typedef vnl_matrix_fixed Base; - public: +public: vnl_double_3x2() = default; - vnl_double_3x2(double r00, double r01, - double r10, double r11, - double r20, double r21) { - vnl_double_3x2& M = *this; - M(0,0) = r00; M(0,1) = r01; - M(1,0) = r10; M(1,1) = r11; - M(2,0) = r20; M(2,1) = r21; + vnl_double_3x2(double r00, double r01, double r10, double r11, double r20, double r21) + { + vnl_double_3x2 & M = *this; + M(0, 0) = r00; + M(0, 1) = r01; + M(1, 0) = r10; + M(1, 1) = r11; + M(2, 0) = r20; + M(2, 1) = r21; } }; diff --git a/core/vnl/vnl_double_3x3.h b/core/vnl/vnl_double_3x3.h index 1da4500bbe0..0c0fbc9f019 100644 --- a/core/vnl/vnl_double_3x3.h +++ b/core/vnl/vnl_double_3x3.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_3x3; +typedef vnl_matrix_fixed vnl_double_3x3; #endif // vnl_double_3x3_h_ diff --git a/core/vnl/vnl_double_3x4.h b/core/vnl/vnl_double_3x4.h index 12db261d966..1064408d670 100644 --- a/core/vnl/vnl_double_3x4.h +++ b/core/vnl/vnl_double_3x4.h @@ -18,6 +18,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_3x4; +typedef vnl_matrix_fixed vnl_double_3x4; #endif // vnl_double_3x4_h_ diff --git a/core/vnl/vnl_double_4.h b/core/vnl/vnl_double_4.h index 2876932f65a..1b9f1c5e388 100644 --- a/core/vnl/vnl_double_4.h +++ b/core/vnl/vnl_double_4.h @@ -15,6 +15,6 @@ #include "vnl_T_n.h" //: class vnl_double_4 : a vnl_vector of 4 doubles. -vnl_T_n_impl(double,4); +vnl_T_n_impl(double, 4); #endif // vnl_double_4_h_ diff --git a/core/vnl/vnl_double_4x3.h b/core/vnl/vnl_double_4x3.h index f961e2aacf3..cf1698c8321 100644 --- a/core/vnl/vnl_double_4x3.h +++ b/core/vnl/vnl_double_4x3.h @@ -14,6 +14,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_4x3; +typedef vnl_matrix_fixed vnl_double_4x3; #endif // vnl_double_4x3_h_ diff --git a/core/vnl/vnl_double_4x4.h b/core/vnl/vnl_double_4x4.h index a5b9f03b6ec..7b29cd5a043 100644 --- a/core/vnl/vnl_double_4x4.h +++ b/core/vnl/vnl_double_4x4.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_double_4x4; +typedef vnl_matrix_fixed vnl_double_4x4; #endif // vnl_double_4x4_h_ diff --git a/core/vnl/vnl_drand48.cpp b/core/vnl/vnl_drand48.cpp index 606b31ad8f9..1c8f238f639 100644 --- a/core/vnl/vnl_drand48.cpp +++ b/core/vnl/vnl_drand48.cpp @@ -93,7 +93,8 @@ static constexpr double tiny = 1.0e-300; static double local_copysign(double x, double y) { - std::uint32_t hx, hy; + std::uint32_t hx; + std::uint32_t hy; GET_HIGH_WORD(hx, x); GET_HIGH_WORD(hy, y); SET_HIGH_WORD(x, (hx & 0x7fffffff) | (hy & 0x80000000)); @@ -103,9 +104,10 @@ local_copysign(double x, double y) static double local_ldexp(double x, int n) { - std::int32_t k, hx, lx; + std::int32_t hx; + std::int32_t lx; EXTRACT_WORDS(hx, lx, x); - k = (hx & 0x7ff00000) >> 20; /* extract exponent */ + std::int32_t k = (hx & 0x7ff00000) >> 20; /* extract exponent */ if (k == 0) { /* 0 or subnormal x */ if ((lx | (hx & 0x7fffffff)) == 0) diff --git a/core/vnl/vnl_drand48.h b/core/vnl/vnl_drand48.h index eeac9900437..79d5ce4d378 100644 --- a/core/vnl/vnl_drand48.h +++ b/core/vnl/vnl_drand48.h @@ -1,7 +1,9 @@ #ifndef __local_drand48_h__ #define __local_drand48_h__ -extern double vnl_drand48(); -extern void vnl_srand48(long seed); +extern double +vnl_drand48(); +extern void +vnl_srand48(long seed); #endif diff --git a/core/vnl/vnl_erf.cxx b/core/vnl/vnl_erf.cxx index 0951f31ef41..281ad020bbc 100644 --- a/core/vnl/vnl_erf.cxx +++ b/core/vnl/vnl_erf.cxx @@ -34,9 +34,11 @@ vnl_erfc(double x) // Local variables - double xden, xnum, result; - int i; - double y, del, ysq; + double xden; + double xnum; + double result; + double del; + double ysq; // ------------------------------------------------------------------ @@ -137,7 +139,7 @@ vnl_erfc(double x) // // Latest modification: March 19, 1990 - y = std::abs(x); + const double y = std::abs(x); // ------------------------------------------------------------------ // Evaluate erfc for |X| <= 0.46875 // ------------------------------------------------------------------ @@ -151,7 +153,7 @@ vnl_erfc(double x) { xnum = c[8] * y; xden = y; - for (i = 0; i < 7; ++i) + for (int i = 0; i < 7; ++i) { xnum = (xnum + c[i]) * y; xden = (xden + d[i]) * y; diff --git a/core/vnl/vnl_erf.h b/core/vnl/vnl_erf.h index dfa7cbd355a..20e05abe181 100644 --- a/core/vnl/vnl_erf.h +++ b/core/vnl/vnl_erf.h @@ -13,21 +13,28 @@ //: The Error function. // erf(x) = (2/sqrt(pi)) Integral from 0 to x (exp(-t^2) dt) // \note the output ranges from -1 to 1, and vnl_erf(0) = 0. -inline double vnl_erf(double x) -{ return (x<0)?-vnl_gamma_p(0.5,x*x):vnl_gamma_p(0.5,x*x); } +inline double +vnl_erf(double x) +{ + return (x < 0) ? -vnl_gamma_p(0.5, x * x) : vnl_gamma_p(0.5, x * x); +} //: The Complementary Error function. // erfc(x) = 1 - erf(x) = 1 - (2/sqrt(pi)) Integral from 0 to x (exp(-t^2) dt) // This value is useful for large x, when erf(x) ~= 1 and erfc(x) < eps. // \note the output ranges from 0 to 2, and vnl_erfc(0) = 1. -VNL_EXPORT double vnl_erfc(double x); +VNL_EXPORT double +vnl_erfc(double x); //: The Scaled Complementary Error function. // erfc_scaled(x) = exp(x^2) * erfc(x) // This value is useful for very large x, where erf and erfc returns // respectively ~1 and ~0. // It can be approximated by (1/sqrt(pi)) * (1/x) -inline double vnl_scaled_erfc(double x) -{ return (vnl_math::two_over_sqrtpi/2.)*(1./x); } +inline double +vnl_scaled_erfc(double x) +{ + return (vnl_math::two_over_sqrtpi / 2.) * (1. / x); +} #endif // vnl_erf_h_ diff --git a/core/vnl/vnl_error.cxx b/core/vnl/vnl_error.cxx index b0b5b7ce356..264ebd1a938 100644 --- a/core/vnl/vnl_error.cxx +++ b/core/vnl/vnl_error.cxx @@ -19,7 +19,7 @@ //: Raise exception for invalid index. void -vnl_error_vector_index(char const * fcn, int index) +vnl_error_vector_index(const char * fcn, int index) { // RAISE Error, SYM(vnl_error_vector), SYM(Invalid_Index), std::cerr << "vnl_error_vector_index:" << fcn << ": Invalid value " << index << " specified for index.\n"; @@ -28,7 +28,7 @@ vnl_error_vector_index(char const * fcn, int index) //: Raise exception for invalid dimension. void -vnl_error_vector_dimension(char const * fcn, int l1, int l2) +vnl_error_vector_dimension(const char * fcn, int l1, int l2) { // RAISE Error, SYM(vnl_error_vector), SYM(Invalid_Dim), std::cerr << "vnl_error_vector_dimension:" << fcn << ": Dimensions [" << l1 << "] and [" << l2 << "] do not match.\n"; @@ -50,7 +50,7 @@ vnl_error_vector_va_arg(int n) //: Raise exception for invalid row index. void -vnl_error_matrix_row_index(char const * fcn, unsigned r) +vnl_error_matrix_row_index(const char * fcn, unsigned r) { // RAISE Error, SYM(vnl_error_matrix), SYM(Invalid_Row), std::cerr << "vnl_error_matrix_row_index:" << fcn << ": Invalid value " << r << " specified for row.\n"; @@ -60,7 +60,7 @@ vnl_error_matrix_row_index(char const * fcn, unsigned r) //: Raise exception for invalid col index. void -vnl_error_matrix_col_index(char const * fcn, unsigned c) +vnl_error_matrix_col_index(const char * fcn, unsigned c) { // RAISE Error, SYM(vnl_error_matrix), SYM(Invalid_Col), std::cerr << "vnl_error_matrix_col_index:" << fcn << ": Invalid value " << c << " specified for column.\n"; @@ -69,7 +69,7 @@ vnl_error_matrix_col_index(char const * fcn, unsigned c) //: Raise exception for invalid dimensions. void -vnl_error_matrix_dimension(char const * fcn, int r1, int c1, int r2, int c2) +vnl_error_matrix_dimension(const char * fcn, int r1, int c1, int r2, int c2) { // RAISE Error, SYM(vnl_error_matrix), SYM(Invalid_Dim), std::cerr << "vnl_error_matrix_dimension:" << fcn << ": Dimensions [" << r1 << ',' << c1 << "] and [" << r2 << ',' @@ -80,7 +80,7 @@ vnl_error_matrix_dimension(char const * fcn, int r1, int c1, int r2, int c2) //: Raise exception for a nonsquare matrix. void -vnl_error_matrix_nonsquare(char const * fcn) +vnl_error_matrix_nonsquare(const char * fcn) { // RAISE Error, SYM(vnl_error_matrix), SYM(Invalid_Dim), std::cerr << "vnl_error_matrix_nonsquare:" << fcn << ": Matrix must be square.\n"; diff --git a/core/vnl/vnl_error.h b/core/vnl/vnl_error.h index 057b659754a..f0a05bdbec4 100644 --- a/core/vnl/vnl_error.h +++ b/core/vnl/vnl_error.h @@ -7,27 +7,35 @@ #include "vnl/vnl_export.h" //: Raise exception for invalid index. -extern VNL_EXPORT void vnl_error_vector_index (const char* fcn, int index); +extern VNL_EXPORT void +vnl_error_vector_index(const char * fcn, int index); //: Raise exception for invalid dimension. -extern VNL_EXPORT void vnl_error_vector_dimension (const char* fcn, int l1, int l2); +extern VNL_EXPORT void +vnl_error_vector_dimension(const char * fcn, int l1, int l2); //: Raise exception for using class objects, or chars in (...). -extern VNL_EXPORT void vnl_error_vector_va_arg (int n); +extern VNL_EXPORT void +vnl_error_vector_va_arg(int n); //: Raise exception for invalid row index. -extern VNL_EXPORT void vnl_error_matrix_row_index (char const* fcn, unsigned r); +extern VNL_EXPORT void +vnl_error_matrix_row_index(const char * fcn, unsigned r); //: Raise exception for invalid col index. -extern VNL_EXPORT void vnl_error_matrix_col_index (char const* fcn, unsigned c); +extern VNL_EXPORT void +vnl_error_matrix_col_index(const char * fcn, unsigned c); //: Raise exception for invalid dimensions. -extern VNL_EXPORT void vnl_error_matrix_dimension (char const* fcn, int r1, int c1, int r2, int c2); +extern VNL_EXPORT void +vnl_error_matrix_dimension(const char * fcn, int r1, int c1, int r2, int c2); //: Raise exception for a nonsquare matrix. -extern VNL_EXPORT void vnl_error_matrix_nonsquare (char const* fcn); +extern VNL_EXPORT void +vnl_error_matrix_nonsquare(const char * fcn); //: Raise exception for using class objects, or chars in (...). -extern VNL_EXPORT void vnl_error_matrix_va_arg (int n); +extern VNL_EXPORT void +vnl_error_matrix_va_arg(int n); #endif // vnl_error_h_ diff --git a/core/vnl/vnl_fastops.cxx b/core/vnl/vnl_fastops.cxx index a45295039da..77d4dd64ba0 100644 --- a/core/vnl/vnl_fastops.cxx +++ b/core/vnl/vnl_fastops.cxx @@ -22,7 +22,7 @@ vnl_fastops::AtA(vnl_matrix & out, const vnl_matrix & A) const unsigned int m = A.rows(); - double const * const * a = A.data_array(); + const double * const * a = A.data_array(); double ** ata = out.data_array(); /* Simple Implementation for reference: @@ -41,9 +41,9 @@ vnl_fastops::AtA(vnl_matrix & out, const vnl_matrix & A) for (unsigned int i = 0; i < n; ++i) { const double aki = a[k][i]; - double const * arow = a[k] + i; + const double * arow = a[k] + i; double * atarow = ata[i] + i; - double const * arowend = a[k] + n; + const double * arowend = a[k] + n; while (arow != arowend) *atarow++ += aki * *arow++; } @@ -74,8 +74,8 @@ vnl_fastops::AB(vnl_matrix & out, const vnl_matrix & A, const vn if (out.rows() != ma || out.columns() != nb) out.set_size(ma, nb); - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** outdata = out.data_array(); for (unsigned int i = 0; i < ma; ++i) @@ -109,8 +109,8 @@ vnl_fastops::AtB(vnl_matrix & out, const vnl_matrix & A, const v if (out.rows() != na || out.columns() != nb) out.set_size(na, nb); - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** outdata = out.data_array(); for (unsigned int i = 0; i < na; ++i) @@ -143,8 +143,8 @@ vnl_fastops::AtB(vnl_vector & out, const vnl_matrix & A, const v if (out.size() != n) out.set_size(n); - double const * const * a = A.data_array(); - double const * b = B.data_block(); + const double * const * a = A.data_array(); + const double * b = B.data_block(); double * outdata = out.data_block(); for (unsigned int i = 0; i < n; ++i) @@ -176,8 +176,8 @@ vnl_fastops::Ab(vnl_vector & out, const vnl_matrix & A, const vn if (out.size() != n) out.set_size(n); - double const * const * a = A.data_array(); - double const * bb = b.data_block(); + const double * const * a = A.data_array(); + const double * bb = b.data_block(); double * outdata = out.data_block(); for (unsigned int i = 0; i < n; ++i) @@ -210,8 +210,8 @@ vnl_fastops::ABt(vnl_matrix & out, const vnl_matrix & A, const v if (out.rows() != ma || out.columns() != mb) out.set_size(ma, mb); - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** outdata = out.data_array(); for (unsigned int i = 0; i < ma; ++i) @@ -253,8 +253,8 @@ vnl_fastops::ABAt(vnl_matrix & out, const vnl_matrix & A, const out.set_size(ma, mb); - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** outdata = out.data_array(); // initialize @@ -294,8 +294,8 @@ vnl_fastops::btAb(const vnl_matrix & A, const vnl_vector & b) } - double const * const * a = A.data_array(); - double const * bb = b.data_block(); + const double * const * a = A.data_array(); + const double * bb = b.data_block(); double accum = 0; for (unsigned int i = 0; i < n; ++i) @@ -322,7 +322,7 @@ vnl_fastops::inc_X_by_AtA(vnl_matrix & X, const vnl_matrix & A) const unsigned int l = A.rows(); - double const * const * a = A.data_array(); + const double * const * a = A.data_array(); double ** x = X.data_array(); if (l == 2) @@ -332,7 +332,7 @@ vnl_fastops::inc_X_by_AtA(vnl_matrix & X, const vnl_matrix & A) x[i][i] += (a[0][i] * a[0][i] + a[1][i] * a[1][i]); for (unsigned int j = i + 1; j < n; ++j) { - double accum = (a[0][i] * a[0][j] + a[1][i] * a[1][j]); + const double accum = (a[0][i] * a[0][j] + a[1][i] * a[1][j]); x[i][j] += accum; x[j][i] += accum; } @@ -379,8 +379,8 @@ vnl_fastops::inc_X_by_AB(vnl_matrix & X, const vnl_matrix & A, c std::abort(); } - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** x = X.data_array(); for (unsigned int i = 0; i < ma; ++i) @@ -415,8 +415,8 @@ vnl_fastops::dec_X_by_AB(vnl_matrix & X, const vnl_matrix & A, c std::abort(); } - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** x = X.data_array(); for (unsigned int i = 0; i < ma; ++i) @@ -451,8 +451,8 @@ vnl_fastops::inc_X_by_AtB(vnl_matrix & X, const vnl_matrix & A, std::abort(); } - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** x = X.data_array(); for (unsigned int i = 0; i < na; ++i) @@ -491,8 +491,8 @@ vnl_fastops::dec_X_by_AtB(vnl_matrix & X, const vnl_matrix & A, std::abort(); } - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** x = X.data_array(); for (unsigned int i = 0; i < na; ++i) @@ -529,8 +529,8 @@ vnl_fastops::inc_X_by_AtB(vnl_vector & X, const vnl_matrix & A, std::abort(); } - double const * const * a = A.data_array(); - double const * b = B.data_block(); + const double * const * a = A.data_array(); + const double * b = B.data_block(); double * x = X.data_block(); for (unsigned int i = 0; i < na; ++i) @@ -566,8 +566,8 @@ vnl_fastops::dec_X_by_AtB(vnl_vector & X, const vnl_matrix & A, std::abort(); } - double const * const * a = A.data_array(); - double const * b = B.data_block(); + const double * const * a = A.data_array(); + const double * b = B.data_block(); double * x = X.data_block(); for (unsigned int i = 0; i < na; ++i) @@ -595,7 +595,7 @@ vnl_fastops::dec_X_by_AtA(vnl_matrix & X, const vnl_matrix & A) const unsigned int l = A.rows(); - double const * const * a = A.data_array(); + const double * const * a = A.data_array(); double ** x = X.data_array(); if (l == 2) @@ -605,7 +605,7 @@ vnl_fastops::dec_X_by_AtA(vnl_matrix & X, const vnl_matrix & A) x[i][i] -= (a[0][i] * a[0][i] + a[1][i] * a[1][i]); for (unsigned int j = i + 1; j < n; ++j) { - double accum = (a[0][i] * a[0][j] + a[1][i] * a[1][j]); + const double accum = (a[0][i] * a[0][j] + a[1][i] * a[1][j]); x[i][j] -= accum; x[j][i] -= accum; } @@ -680,8 +680,8 @@ vnl_fastops::inc_X_by_ABt(vnl_matrix & X, const vnl_matrix & A, std::abort(); } - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** x = X.data_array(); if (na == 3) @@ -736,8 +736,8 @@ vnl_fastops::dec_X_by_ABt(vnl_matrix & X, const vnl_matrix & A, std::abort(); } - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** x = X.data_array(); if (na == 3) @@ -796,8 +796,8 @@ vnl_fastops::inc_X_by_ABAt(vnl_matrix & X, const vnl_matrix & A, X.set_size(ma, mb); - double const * const * a = A.data_array(); - double const * const * b = B.data_array(); + const double * const * a = A.data_array(); + const double * const * b = B.data_array(); double ** Xdata = X.data_array(); for (unsigned int i = 0; i < ma; ++i) diff --git a/core/vnl/vnl_fastops.h b/core/vnl/vnl_fastops.h index 5ca4f6e8ed1..6cd930dcacd 100644 --- a/core/vnl/vnl_fastops.h +++ b/core/vnl/vnl_fastops.h @@ -24,34 +24,54 @@ // class to achieve the same results with about a 10% speed penalty. class VNL_EXPORT vnl_fastops { - public: - static void AtA(vnl_matrix& out, const vnl_matrix& A); - static void AB (vnl_matrix& out, const vnl_matrix& A, const vnl_matrix& B); - static void AtB(vnl_matrix& out, const vnl_matrix& A, const vnl_matrix& B); - static void AtB(vnl_vector& out, const vnl_matrix& A, const vnl_vector& b); - static void Ab (vnl_vector& out, const vnl_matrix& A, const vnl_vector& b); - static void ABt(vnl_matrix& out, const vnl_matrix& A, const vnl_matrix& B); - - static double btAb (const vnl_matrix& A, const vnl_vector& b); - - static void ABAt(vnl_matrix& out, const vnl_matrix& A, const vnl_matrix& B); - - static void inc_X_by_AtA(vnl_matrix& X, const vnl_matrix& A); - static void inc_X_by_AB (vnl_matrix& X, const vnl_matrix& A, const vnl_matrix& B); - static void inc_X_by_AtB(vnl_matrix& X, const vnl_matrix& A, const vnl_matrix& B); - static void inc_X_by_AtB(vnl_vector& X, const vnl_matrix& A, const vnl_vector& b); - static void inc_X_by_ABt(vnl_matrix& X, const vnl_matrix& A, const vnl_matrix& B); - static void inc_X_by_ABAt(vnl_matrix& X, const vnl_matrix& A, const vnl_matrix& B); - - static void dec_X_by_AtA(vnl_matrix& X, const vnl_matrix& A); - static void dec_X_by_AB (vnl_matrix& X, const vnl_matrix& A, const vnl_matrix& B); - static void dec_X_by_AtB(vnl_matrix& X, const vnl_matrix& A, const vnl_matrix& B); - static void dec_X_by_AtB(vnl_vector& X, const vnl_matrix& A, const vnl_vector& b); - static void dec_X_by_ABt(vnl_matrix& X, const vnl_matrix& A, const vnl_matrix& B); - - private: +public: + static void + AtA(vnl_matrix & out, const vnl_matrix & A); + static void + AB(vnl_matrix & out, const vnl_matrix & A, const vnl_matrix & B); + static void + AtB(vnl_matrix & out, const vnl_matrix & A, const vnl_matrix & B); + static void + AtB(vnl_vector & out, const vnl_matrix & A, const vnl_vector & b); + static void + Ab(vnl_vector & out, const vnl_matrix & A, const vnl_vector & b); + static void + ABt(vnl_matrix & out, const vnl_matrix & A, const vnl_matrix & B); + + static double + btAb(const vnl_matrix & A, const vnl_vector & b); + + static void + ABAt(vnl_matrix & out, const vnl_matrix & A, const vnl_matrix & B); + + static void + inc_X_by_AtA(vnl_matrix & X, const vnl_matrix & A); + static void + inc_X_by_AB(vnl_matrix & X, const vnl_matrix & A, const vnl_matrix & B); + static void + inc_X_by_AtB(vnl_matrix & X, const vnl_matrix & A, const vnl_matrix & B); + static void + inc_X_by_AtB(vnl_vector & X, const vnl_matrix & A, const vnl_vector & b); + static void + inc_X_by_ABt(vnl_matrix & X, const vnl_matrix & A, const vnl_matrix & B); + static void + inc_X_by_ABAt(vnl_matrix & X, const vnl_matrix & A, const vnl_matrix & B); + + static void + dec_X_by_AtA(vnl_matrix & X, const vnl_matrix & A); + static void + dec_X_by_AB(vnl_matrix & X, const vnl_matrix & A, const vnl_matrix & B); + static void + dec_X_by_AtB(vnl_matrix & X, const vnl_matrix & A, const vnl_matrix & B); + static void + dec_X_by_AtB(vnl_vector & X, const vnl_matrix & A, const vnl_vector & b); + static void + dec_X_by_ABt(vnl_matrix & X, const vnl_matrix & A, const vnl_matrix & B); + +private: // BLAS-like operations - static double dot(const double* a, const double* b, unsigned int n); + static double + dot(const double * a, const double * b, unsigned int n); }; #endif // vnl_fastops_h_ diff --git a/core/vnl/vnl_file_matrix.h b/core/vnl/vnl_file_matrix.h index 66af3286746..348b225474f 100644 --- a/core/vnl/vnl_file_matrix.h +++ b/core/vnl/vnl_file_matrix.h @@ -21,17 +21,22 @@ template class VNL_EXPORT vnl_file_matrix : public vnl_matrix { - private: +private: +public: + vnl_file_matrix(const char * filename); - public: - vnl_file_matrix(char const* filename); + explicit + operator bool() const + { + return (ok_) ? true : false; + } + bool + operator!() const + { + return !ok_; + } - explicit operator bool () const - { return (ok_)? true : false; } - bool operator!() const - { return !ok_; } - - private: +private: bool ok_; }; diff --git a/core/vnl/vnl_file_matrix.hxx b/core/vnl/vnl_file_matrix.hxx index 0a8935898bf..adccc9d47c8 100644 --- a/core/vnl/vnl_file_matrix.hxx +++ b/core/vnl/vnl_file_matrix.hxx @@ -18,11 +18,12 @@ //: Load matrix from filename. template -vnl_file_matrix::vnl_file_matrix(char const* filename) +vnl_file_matrix::vnl_file_matrix(const char * filename) { - if (filename && filename[0]=='-' && filename[1]=='\0') + if (filename && filename[0] == '-' && filename[1] == '\0') ok_ = this->read_ascii(std::cin); - else { + else + { std::ifstream o(filename); ok_ = this->read_ascii(o); } @@ -34,7 +35,6 @@ vnl_file_matrix::vnl_file_matrix(char const* filename) //-------------------------------------------------------------------------------- #undef VNL_FILE_MATRIX_INSTANTIATE -#define VNL_FILE_MATRIX_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_file_matrix +#define VNL_FILE_MATRIX_INSTANTIATE(T) template class VNL_EXPORT vnl_file_matrix #endif // vnl_file_matrix_hxx_ diff --git a/core/vnl/vnl_file_vector.h b/core/vnl/vnl_file_vector.h index 4bdcfe6c861..5aa50cd3039 100644 --- a/core/vnl/vnl_file_vector.h +++ b/core/vnl/vnl_file_vector.h @@ -22,17 +22,22 @@ template class VNL_EXPORT vnl_file_vector : public vnl_vector { - private: +private: +public: + vnl_file_vector(const char * filename); - public: - vnl_file_vector(char const* filename); + explicit + operator bool() const + { + return (ok_) ? true : false; + } + bool + operator!() const + { + return !ok_; + } - explicit operator bool () const - { return (ok_)? true : false; } - bool operator!() const - { return !ok_; } - - private: +private: bool ok_; }; diff --git a/core/vnl/vnl_file_vector.hxx b/core/vnl/vnl_file_vector.hxx index edfa1b24620..dfc188c9dd1 100644 --- a/core/vnl/vnl_file_vector.hxx +++ b/core/vnl/vnl_file_vector.hxx @@ -15,20 +15,21 @@ //: Load vector from filename. template -vnl_file_vector::vnl_file_vector(char const* filename) +vnl_file_vector::vnl_file_vector(const char * filename) : vnl_vector() // makes an empty vector. { #ifdef DEBUG std::cerr << "filename=" << filename << "\nsize=" << this->size() << '\n'; #endif - if (filename && std::strcmp(filename, "-")) { + if (filename && std::strcmp(filename, "-")) + { std::ifstream o(filename); ok_ = this->read_ascii(o); } else ok_ = this->read_ascii(std::cin); #ifdef DEBUG - std::cerr << "size=" << this->size() << '\n'; + std::cerr << "size=" << this->size() << '\n'; #endif if (!ok_) std::cerr << "vnl_file_vector: ERROR loading from " << filename << '\n'; @@ -37,7 +38,6 @@ vnl_file_vector::vnl_file_vector(char const* filename) //-------------------------------------------------------------------------------- #undef VNL_FILE_VECTOR_INSTANTIATE -#define VNL_FILE_VECTOR_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_file_vector +#define VNL_FILE_VECTOR_INSTANTIATE(T) template class VNL_EXPORT vnl_file_vector #endif // vnl_file_vector_hxx_ diff --git a/core/vnl/vnl_finite.h b/core/vnl/vnl_finite.h index dfde163008e..9f0c41fb2c2 100644 --- a/core/vnl/vnl_finite.h +++ b/core/vnl/vnl_finite.h @@ -53,85 +53,231 @@ template class vnl_finite_int { - private: +private: int val_; //!< value of this number (smallest nonnegative representation) typedef vnl_finite_int Base; - public: + +public: //: The number of different finite_int numbers of this type - static unsigned int cardinality() { return N; } + static unsigned int + cardinality() + { + return N; + } //: Creates a finite int element. // Default constructor gives 0. // Also serves as automatic cast from int to vnl_finite_int. - inline vnl_finite_int(int x = 0) : val_((x %= N) < 0 ? N + x : x) { + inline vnl_finite_int(int x = 0) + : val_((x %= N) < 0 ? N + x : x) + { assert(N > 1); } // Copy constructor - inline vnl_finite_int(Base const& x) : val_(int(x)), mo_(x.mo_), lp1_(x.lp1_) {} + inline vnl_finite_int(const Base & x) + : val_(int(x)) + , mo_(x.mo_) + , lp1_(x.lp1_) + {} // Destructor inline ~vnl_finite_int() = default; // Implicit conversions - inline operator int() const { return val_; } - inline operator int() { return val_; } - inline operator long() const { return val_; } - inline operator long() { return val_; } - inline operator short() const { short r = (short)val_; assert(r == val_); return r; } - inline operator short() { short r = (short)val_; assert(r == val_); return r; } + inline + operator int() const + { + return val_; + } + inline + operator int() + { + return val_; + } + inline + operator long() const + { + return val_; + } + inline + operator long() + { + return val_; + } + inline + operator short() const + { + short r = (short)val_; + assert(r == val_); + return r; + } + inline + operator short() + { + short r = (short)val_; + assert(r == val_); + return r; + } //: Assignment - inline Base& operator=(Base const& x) { val_ = int(x); mo_=x.mo_; lp1_=x.lp1_; return *this; } - inline Base& operator=(int x) { x%=N; val_ = x<0 ? N+x : x; mo_=lp1_=0; return *this; } + inline Base & + operator=(const Base & x) + { + val_ = int(x); + mo_ = x.mo_; + lp1_ = x.lp1_; + return *this; + } + inline Base & + operator=(int x) + { + x %= N; + val_ = x < 0 ? N + x : x; + mo_ = lp1_ = 0; + return *this; + } //: Comparison of finite int numbers. // Note that finite ints have no order, so < and > make no sense. - inline bool operator==(Base const& x) const { return val_ == int(x); } - inline bool operator!=(Base const& x) const { return val_ != int(x); } - inline bool operator==(int x) const { return operator==(Base(x)); } - inline bool operator!=(int x) const { return !operator==(x); } + inline bool + operator==(const Base & x) const + { + return val_ == int(x); + } + inline bool + operator!=(const Base & x) const + { + return val_ != int(x); + } + inline bool + operator==(int x) const + { + return operator==(Base(x)); + } + inline bool + operator!=(int x) const + { + return !operator==(x); + } //: Unary minus - returns the additive inverse - inline Base operator-() const { return Base(N-val_); } + inline Base + operator-() const + { + return Base(N - val_); + } //: Unary plus - returns the current number - inline Base operator+() const { return *this; } + inline Base + operator+() const + { + return *this; + } //: Unary not - returns true if finite int number is equal to zero. - inline bool operator!() const { return val_ == 0; } + inline bool + operator!() const + { + return val_ == 0; + } //: Plus&assign: replace lhs by lhs + rhs - inline Base& operator+=(Base const& r) { mo_=lp1_=0; val_ += int(r); if (val_ >= int(N)) val_ -= N; return *this; } - inline Base& operator+=(int r) { return operator=(val_+r); } + inline Base & + operator+=(const Base & r) + { + mo_ = lp1_ = 0; + val_ += int(r); + if (val_ >= int(N)) + val_ -= N; + return *this; + } + inline Base & + operator+=(int r) + { + return operator=(val_ + r); + } //: Minus&assign: replace lhs by lhs - rhs - inline Base& operator-=(Base const& r) { mo_=lp1_=0; val_ -= int(r); if (val_ < 0) val_ += N; return *this; } - inline Base& operator-=(int r) { return operator=(val_-r); } + inline Base & + operator-=(const Base & r) + { + mo_ = lp1_ = 0; + val_ -= int(r); + if (val_ < 0) + val_ += N; + return *this; + } + inline Base & + operator-=(int r) + { + return operator=(val_ - r); + } //: Multiply&assign: replace lhs by lhs * rhs - inline Base& operator*=(int r) { - r %=N; if (r<0) r=N+r; + inline Base & + operator*=(int r) + { + r %= N; + if (r < 0) + r = N + r; // This rather complicated implementation is necessary to avoid integer overflow - if (N<=0x7fff || (val_<=0x7fff && r<=0x7fff)) { val_ *= r; val_ %= N; return *this; } - else { int v=val_; operator+=(v); operator*=(r/2); if (r%2) operator+=(v); return *this; } + if (N <= 0x7fff || (val_ <= 0x7fff && r <= 0x7fff)) + { + val_ *= r; + val_ %= N; + return *this; + } + else + { + const int v = val_; + operator+=(v); + operator*=(r / 2); + if (r % 2) + operator+=(v); + return *this; + } } //: Multiply&assign: replace lhs by lhs * rhs - inline Base& operator*=(Base const& r) { - mo_=0; - if (lp1_!=0 && r.lp1_!=0) set_log(lp1_+r.lp1_-2); else lp1_=0; + inline Base & + operator*=(const Base & r) + { + mo_ = 0; + if (lp1_ != 0 && r.lp1_ != 0) + set_log(lp1_ + r.lp1_ - 2); + else + lp1_ = 0; // This rather complicated implementation is necessary to avoid integer overflow - unsigned int s=int(r); - if (N<=0x7fff || (val_<=0x7fff && s<=0x7fff)) { val_ *= s; val_ %= N; return *this; } - else { int v=val_; operator+=(v); operator*=(s/2); if (s%2) operator+=(v); return *this; } + const unsigned int s = int(r); + if (N <= 0x7fff || (val_ <= 0x7fff && s <= 0x7fff)) + { + val_ *= s; + val_ %= N; + return *this; + } + else + { + const int v = val_; + operator+=(v); + operator*=(s / 2); + if (s % 2) + operator+=(v); + return *this; + } } //: Return the Euler totient function, i.e., the number of units of this ring // This number also equals the periodicity of the exponent: every unit, // when raised to this power, yields 1. - static unsigned int totient() { + static unsigned int + totient() + { static unsigned int t_ = 0; // cached value - if (t_ != 0) return t_; - std::vector d = decompose(); - t_ = 1; unsigned int p = 1; - for (unsigned int i : d) + if (t_ != 0) + return t_; + const std::vector d = decompose(); + t_ = 1; + unsigned int p = 1; + for (const unsigned int i : d) { - if (p != i) t_ *= i-1; - else t_ *= i; + if (p != i) + t_ *= i - 1; + else + t_ *= i; p = i; } return t_; @@ -139,68 +285,144 @@ class vnl_finite_int //: Multiplicative inverse. // Uses exp() and log() for efficient computation, unless log() is not defined. - Base reciproc() const { + Base + reciproc() const + { assert(is_unit()); - if (val_==1) return *this; - Base z = smallest_generator(); - if (z!=1) return exp(Base::totient()-log()); - for (unsigned int r=1; r<=N/2; ++r) { - unsigned int t=int(*this*int(r)); - if (t==1) return r; else if (t==N-1) return N-r; + if (val_ == 1) + return *this; + const Base z = smallest_generator(); + if (z != 1) + return exp(Base::totient() - log()); + for (unsigned int r = 1; r <= N / 2; ++r) + { + const unsigned int t = int(*this * int(r)); + if (t == 1) + return r; + else if (t == N - 1) + return N - r; } return 0; // This will never be executed } //: Divide&assign. Uses r.reciproc() for efficient computation. - inline Base& operator/=(Base const& r) { + inline Base & + operator/=(const Base & r) + { assert(r.is_unit()); return val_ == 0 ? operator=(0) : operator*=(r.reciproc()); } //: Pre-increment (++r). - inline Base& operator++() { mo_=lp1_=0; ++val_; if (val_==N) val_=0; return *this; } + inline Base & + operator++() + { + mo_ = lp1_ = 0; + ++val_; + if (val_ == N) + val_ = 0; + return *this; + } //: Pre-decrement (--r). - inline Base& operator--() { mo_=lp1_=0; if (val_==0) val_=N; --val_; return *this; } + inline Base & + operator--() + { + mo_ = lp1_ = 0; + if (val_ == 0) + val_ = N; + --val_; + return *this; + } //: Post-increment (r++). - inline Base operator++(int) {Base b=*this; mo_=lp1_=0; ++val_; if (val_==N) val_=0; return b; } + inline Base + operator++(int) + { + Base b = *this; + mo_ = lp1_ = 0; + ++val_; + if (val_ == N) + val_ = 0; + return b; + } //: Post-decrement (r--). - inline Base operator--(int) {Base b=*this; mo_=lp1_=0; if (val_==0) val_=N; --val_; return b;} + inline Base + operator--(int) + { + Base b = *this; + mo_ = lp1_ = 0; + if (val_ == 0) + val_ = N; + --val_; + return b; + } //: Write N as the unique product of prime factors. - static std::vector decompose() { + static std::vector + decompose() + { static std::vector decomposition_ = std::vector(); // cached value if (!decomposition_.empty()) return decomposition_; unsigned int r = N; - for (unsigned int d=2; d*d<=r; ++d) - while (r%d == 0) { decomposition_.push_back(d); r /= d; } - if (r > 1) decomposition_.push_back(r); + for (unsigned int d = 2; d * d <= r; ++d) + while (r % d == 0) + { + decomposition_.push_back(d); + r /= d; + } + if (r > 1) + decomposition_.push_back(r); return decomposition_; } //: Return true when N is a prime number, i.e., when this ring is a field - static inline bool is_field() { - std::vector d = Base::decompose(); + static inline bool + is_field() + { + const std::vector d = Base::decompose(); return d.size() == 1; } //: Return true only when x is a unit in this ring. // In a field, all numbers except 0 are units. // The total number of units is given by the Euler totient function. - bool is_unit() const { return gcd(val_) == 1; } + bool + is_unit() const + { + return gcd(val_) == 1; + } //: Return true only when x is a zero divisor, i.e., is not a unit. - inline bool is_zero_divisor() const { return gcd(val_) != 1; } + inline bool + is_zero_divisor() const + { + return gcd(val_) != 1; + } //: The additive order of x is the smallest nonnegative r such that r*x == 0. - inline unsigned int additive_order() const { if (val_ == 0) return 1; return N/gcd(val_); } + inline unsigned int + additive_order() const + { + if (val_ == 0) + return 1; + return N / gcd(val_); + } //: The multiplicative order of x is the smallest r (>0) such that x^r == 1. - unsigned int multiplicative_order() const { - if (mo_ != 0) return mo_; - if (gcd(val_) != 1) return -1; // should actually return infinity + unsigned int + multiplicative_order() const + { + if (mo_ != 0) + return mo_; + if (gcd(val_) != 1) + return -1; // should actually return infinity Base y = val_; - for (int r=1; r0) { if (g%2) y *= z; g/=2; z*=z; } + unsigned int g = h; + Base y = 1; + Base z = gen_; + while (g > 0) + { + if (g % 2) + y *= z; + g /= 2; + z *= z; + } // quick elimination of non-generator: - if (y == 1) continue; + if (y == 1) + continue; // calculate gen_.multiplicative_order() only if really necessary: - if (gen_.multiplicative_order() == Base::totient()) { gen_.set_log(1); return gen_; } + if (gen_.multiplicative_order() == Base::totient()) + { + gen_.set_log(1); + return gen_; + } } assert(!Base::is_field()); // can only reach this point when N is not prime - return gen_=1; + return gen_ = 1; } //: Return the r-th power of this number. - inline Base pow(int r) { - r %= Base::totient(); if (r<0) r += Base::totient(); - if (r==0) return 1; if (r==1) return *this; - Base y = 1, z = *this; int s=r; while (s!=0) { if (s%2) y*=z; s/=2; z*=z; } - if (lp1_ != 0) y.set_log(r*(lp1_-1)); + inline Base + pow(int r) + { + r %= Base::totient(); + if (r < 0) + r += Base::totient(); + if (r == 0) + return 1; + if (r == 1) + return *this; + Base y = 1; + Base z = *this; + int s = r; + while (s != 0) + { + if (s % 2) + y *= z; + s /= 2; + z *= z; + } + if (lp1_ != 0) + y.set_log(r * (lp1_ - 1)); return y; } //: Return the smallest nonnegative exponent r for which x=g^r, where g is the smallest generator. - unsigned int log() const { - if (is_zero_divisor()) return -1; // should actually return minus infinity - if (lp1_ != 0) return lp1_-1; - Base z = smallest_generator(); - assert(N==2||z!=1); // otherwise, the units of this ring do not form a cyclic group + unsigned int + log() const + { + if (is_zero_divisor()) + return -1; // should actually return minus infinity + if (lp1_ != 0) + return lp1_ - 1; + const Base z = smallest_generator(); + assert(N == 2 || z != 1); // otherwise, the units of this ring do not form a cyclic group Base y = 1; - for (lp1_=1; lp1_<=N; ++lp1_) { - if (y == *this) return lp1_-1; + for (lp1_ = 1; lp1_ <= N; ++lp1_) + { + if (y == *this) + return lp1_ - 1; y *= z; } return -1; // should never reach this point } //: Return the inverse of log(), i.e., return g^r where g is the smallest generator. - static inline Base exp(int r) { + static inline Base + exp(int r) + { Base z = smallest_generator(); - assert(N==2||z!=1); // otherwise, the units of this ring do not form a cyclic group + assert(N == 2 || z != 1); // otherwise, the units of this ring do not form a cyclic group return z.pow(r); } //: Calculate the greatest common divisor of l and N. - static inline unsigned int gcd(unsigned int l, unsigned int n) { + static inline unsigned int + gcd(unsigned int l, unsigned int n) + { unsigned int l1 = n; - while (l!=0) { unsigned int t = l; l = l1 % l; l1 = t; } + while (l != 0) + { + const unsigned int t = l; + l = l1 % l; + l1 = t; + } return l1; } - static inline unsigned int gcd(unsigned int l) { return gcd(l, N); } + static inline unsigned int + gcd(unsigned int l) + { + return gcd(l, N); + } - private: +private: //: private function to set cached value of lp1_ when available - void set_log(unsigned int r) const { r %= Base::totient(); lp1_ = r+1; } + void + set_log(unsigned int r) const + { + r %= Base::totient(); + lp1_ = r + 1; + } - mutable unsigned int mo_{0}; //!< cached value for multiplicative order - mutable unsigned int lp1_{0}; //!< cached value for 1+log() + mutable unsigned int mo_{ 0 }; //!< cached value for multiplicative order + mutable unsigned int lp1_{ 0 }; //!< cached value for 1+log() }; //: formatted output // \relatesalso vnl_finite_int template -inline std::ostream& operator<< (std::ostream& s, vnl_finite_int const& r) +inline std::ostream & +operator<<(std::ostream & s, const vnl_finite_int & r) { return s << int(r); } @@ -282,141 +565,193 @@ inline std::ostream& operator<< (std::ostream& s, vnl_finite_int const& r) //: simple input // \relatesalso vnl_finite_int template -inline std::istream& operator>> (std::istream& s, vnl_finite_int& r) +inline std::istream & +operator>>(std::istream & s, vnl_finite_int & r) { - int n; s >> n; r=n; return s; + int n; + s >> n; + r = n; + return s; } //: Returns the sum of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator+ (vnl_finite_int const& r1, vnl_finite_int const& r2) +inline vnl_finite_int +operator+(const vnl_finite_int & r1, const vnl_finite_int & r2) { - vnl_finite_int result(r1); return result += r2; + vnl_finite_int result(r1); + return result += r2; } //: Returns the sum of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator+ (vnl_finite_int const& r1, int r2) +inline vnl_finite_int +operator+(const vnl_finite_int & r1, int r2) { - vnl_finite_int result(r1); return result += r2; + vnl_finite_int result(r1); + return result += r2; } //: Returns the sum of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator+ (int r2, vnl_finite_int const& r1) +inline vnl_finite_int +operator+(int r2, const vnl_finite_int & r1) { - vnl_finite_int result(r1); return result += r2; + vnl_finite_int result(r1); + return result += r2; } //: Returns the difference of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator- (vnl_finite_int const& r1, vnl_finite_int const& r2) +inline vnl_finite_int +operator-(const vnl_finite_int & r1, const vnl_finite_int & r2) { - vnl_finite_int result(r1); return result -= r2; + vnl_finite_int result(r1); + return result -= r2; } //: Returns the difference of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator- (vnl_finite_int const& r1, int r2) +inline vnl_finite_int +operator-(const vnl_finite_int & r1, int r2) { - vnl_finite_int result(r1); return result -= r2; + vnl_finite_int result(r1); + return result -= r2; } //: Returns the difference of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator- (int r2, vnl_finite_int const& r1) +inline vnl_finite_int +operator-(int r2, const vnl_finite_int & r1) { - vnl_finite_int result(-r1); return result += r2; + vnl_finite_int result(-r1); + return result += r2; } //: Returns the product of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator* (vnl_finite_int const& r1, vnl_finite_int const& r2) +inline vnl_finite_int +operator*(const vnl_finite_int & r1, const vnl_finite_int & r2) { - vnl_finite_int result(r1); return result *= r2; + vnl_finite_int result(r1); + return result *= r2; } //: Returns the product of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator* (vnl_finite_int const& r1, int r2) +inline vnl_finite_int +operator*(const vnl_finite_int & r1, int r2) { - vnl_finite_int result(r1); return result *= r2; + vnl_finite_int result(r1); + return result *= r2; } //: Returns the product of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator* (int r2, vnl_finite_int const& r1) +inline vnl_finite_int +operator*(int r2, const vnl_finite_int & r1) { - vnl_finite_int result(r1); return result *= r2; + vnl_finite_int result(r1); + return result *= r2; } //: Returns the quotient of two finite int numbers. // Uses r2.reciproc() for efficient computation. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator/(vnl_finite_int const& r1, vnl_finite_int const& r2) +inline vnl_finite_int +operator/(const vnl_finite_int & r1, const vnl_finite_int & r2) { - assert(r2.is_unit()); return r1 == 0 ? vnl_finite_int(0) : r1*r2.reciproc(); + assert(r2.is_unit()); + return r1 == 0 ? vnl_finite_int(0) : r1 * r2.reciproc(); } //: Returns the quotient of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator/ (vnl_finite_int const& r1, int r2) +inline vnl_finite_int +operator/(const vnl_finite_int & r1, int r2) { - vnl_finite_int result(r1); return result /= r2; + vnl_finite_int result(r1); + return result /= r2; } //: Returns the quotient of two finite int numbers. // \relatesalso vnl_finite_int template -inline vnl_finite_int operator/ (int r1, vnl_finite_int const& r2) +inline vnl_finite_int +operator/(int r1, const vnl_finite_int & r2) { - vnl_finite_int result(r1); return result /= r2; + vnl_finite_int result(r1); + return result /= r2; } //: // \relatesalso vnl_finite_int template -inline bool operator== (int r1, vnl_finite_int const& r2) { return r2==r1; } +inline bool +operator==(int r1, const vnl_finite_int & r2) +{ + return r2 == r1; +} //: // \relatesalso vnl_finite_int template -inline bool operator!= (int r1, vnl_finite_int const& r2) { return r2!=r1; } +inline bool +operator!=(int r1, const vnl_finite_int & r2) +{ + return r2 != r1; +} namespace vnl_math { - //: - // \relatesalso vnl_finite_int - template - inline vnl_finite_int squared_magnitude(vnl_finite_int const& x) { return x*x; } +//: +// \relatesalso vnl_finite_int +template +inline vnl_finite_int +squared_magnitude(const vnl_finite_int & x) +{ + return x * x; +} - //: - // \relatesalso vnl_finite_int - template - inline vnl_finite_int sqr(vnl_finite_int const& x) { return x*x; } +//: +// \relatesalso vnl_finite_int +template +inline vnl_finite_int +sqr(const vnl_finite_int & x) +{ + return x * x; +} - //: - // \relatesalso vnl_finite_int - template - inline bool isnan(vnl_finite_int const& ) {return false;} +//: +// \relatesalso vnl_finite_int +template +inline bool +isnan(const vnl_finite_int &) +{ + return false; +} - //: - // \relatesalso vnl_finite_int - template - inline bool isfinite(vnl_finite_int const& ) {return true;} +//: +// \relatesalso vnl_finite_int +template +inline bool +isfinite(const vnl_finite_int &) +{ + return true; +} - } // end namespace vnl_math +} // end namespace vnl_math //: finite modulo-N arithmetic with polynomials of degree < M // @@ -435,159 +770,283 @@ namespace vnl_math template class vnl_finite_int_poly { - typedef vnl_finite_int_poly Base; + typedef vnl_finite_int_poly Base; typedef vnl_finite_int Scalar; std::vector val_; //!< M-tuple (or degree M-1 polynomial) representing this // This essentially implements std::pow(N,int) which is not always available - static unsigned int Ntothe(unsigned int m) { return m==0?1:m==1?N:Ntothe(m/2)*Ntothe((m+1)/2); } - public: + static unsigned int + Ntothe(unsigned int m) + { + return m == 0 ? 1 : m == 1 ? N : Ntothe(m / 2) * Ntothe((m + 1) / 2); + } + +public: //: The number of different finite_int polynomials of this type - static unsigned int cardinality() { return Ntothe(M); } + static unsigned int + cardinality() + { + return Ntothe(M); + } //: Creates a general finite_int_poly. - inline vnl_finite_int_poly(std::vector p) : val_(std::move(p)) { + inline vnl_finite_int_poly(std::vector p) + : val_(std::move(p)) + { static_assert(N > 1, "N must be > 1"); static_assert(M > 0, "M must be > 0"); assert(val_.size() <= M); } //: Creates a degree 0 finite_int_poly. - inline vnl_finite_int_poly(Scalar const& n) : val_(std::vector(1)) { assert(N>1); assert(M>0); val_[0]=n; } + inline vnl_finite_int_poly(const Scalar & n) + : val_(std::vector(1)) + { + assert(N > 1); + assert(M > 0); + val_[0] = n; + } //: Default constructor. Creates a degree 0 finite_int_poly equal to 0. - inline vnl_finite_int_poly() : val_(std::vector(1)) { assert(N>1); assert(M>0); val_[0]=0; } + inline vnl_finite_int_poly() + : val_(std::vector(1)) + { + assert(N > 1); + assert(M > 0); + val_[0] = 0; + } // Copy constructor - inline vnl_finite_int_poly(Base const& x) : val_(x.val_) {} + inline vnl_finite_int_poly(const Base & x) + : val_(x.val_) + {} // Destructor inline ~vnl_finite_int_poly() = default; //: Formal degree of this polynomial - inline std::size_t deg() const { return val_.size() - 1; } + inline std::size_t + deg() const + { + return val_.size() - 1; + } //: Effective degree of this polynomial; equals -1 when this polynomial is 0. - int degree() const { for (int i=deg(); i>=0; --i) if (val_[i]!=0) return i; return -1; } + int + degree() const + { + for (int i = deg(); i >= 0; --i) + if (val_[i] != 0) + return i; + return -1; + } //: Access to individual coefficients - inline Scalar operator[](unsigned int i) const { assert(i(1); val_[0] = n; return *this; } + inline Base & + operator=(const Base & x) = default; + inline Base & + operator=(const Scalar & n) + { + val_ = std::vector(1); + val_[0] = n; + return *this; + } //: Comparison of finite int polys. - bool operator==(Base const& x) const { - for (unsigned int i=0; i<=deg(); ++i) - if (val_[i] != x[i]) return false; - for (unsigned int i=deg()+1; i<=x.deg(); ++i) - if (x[i] != 0) return false; + bool + operator==(const Base & x) const + { + for (unsigned int i = 0; i <= deg(); ++i) + if (val_[i] != x[i]) + return false; + for (unsigned int i = deg() + 1; i <= x.deg(); ++i) + if (x[i] != 0) + return false; return true; } - inline bool operator!=(Base const& x) const { return !operator==(x); } - bool operator==(Scalar const& x) const { - if (x!=val_[0]) return false; - for (unsigned int i=1; i<=deg(); ++i) if (val_[i] != 0) return false; + inline bool + operator!=(const Base & x) const + { + return !operator==(x); + } + bool + operator==(const Scalar & x) const + { + if (x != val_[0]) + return false; + for (unsigned int i = 1; i <= deg(); ++i) + if (val_[i] != 0) + return false; return true; } - inline bool operator!=(Scalar const& x) const { return !operator==(x); } + inline bool + operator!=(const Scalar & x) const + { + return !operator==(x); + } //: Unary minus - returns the additive inverse - Base operator-() const { std::vector p = val_; for (unsigned int i=0; i p = val_; + for (unsigned int i = 0; i < p.size(); ++i) + p[i] = -p[i]; + return p; + } //: Unary plus - returns the current polynomial - inline Base operator+() const { return *this; } + inline Base + operator+() const + { + return *this; + } //: Unary not - returns true if finite int poly is equal to zero. - bool operator!() const { for (unsigned int i=0; i<=deg(); ++i) if (val_[i] != 0) return false; return true; } + bool + operator!() const + { + for (unsigned int i = 0; i <= deg(); ++i) + if (val_[i] != 0) + return false; + return true; + } //: Plus&assign: replace lhs by lhs + rhs - Base& operator+=(Base const& r) { - for (unsigned int i=0; i<=r.deg(); ++i) - if (i<=deg()) val_[i] += r[i]; - else val_.push_back(r[i]); + Base & + operator+=(const Base & r) + { + for (unsigned int i = 0; i <= r.deg(); ++i) + if (i <= deg()) + val_[i] += r[i]; + else + val_.push_back(r[i]); return *this; } //: Minus&assign: replace lhs by lhs - rhs - Base& operator-=(Base const& r) { - for (unsigned int i=0; i<=r.deg(); ++i) - if (i<=deg()) val_[i] -= r[i]; - else val_.push_back(-r[i]); + Base & + operator-=(const Base & r) + { + for (unsigned int i = 0; i <= r.deg(); ++i) + if (i <= deg()) + val_[i] -= r[i]; + else + val_.push_back(-r[i]); return *this; } //: Scalar multiple of this - Base& operator*=(Scalar const& n) { for (unsigned int i=0; i<=deg(); ++i) val_[i] *= n; return *this; } + Base & + operator*=(const Scalar & n) + { + for (unsigned int i = 0; i <= deg(); ++i) + val_[i] *= n; + return *this; + } //: The additive order of x is the smallest positive r such that r*x == 0. - unsigned int additive_order() const { + unsigned int + additive_order() const + { unsigned int r = N; - for (unsigned int i=0; i<=deg(); ++i) - if (val_[i] != 0) r=Scalar::gcd(val_[i],r); - return N/r; + for (unsigned int i = 0; i <= deg(); ++i) + if (val_[i] != 0) + r = Scalar::gcd(val_[i], r); + return N / r; } //: get/set the (irreducible) modulo polynomial of degree M // Note that this polynomial has to be set only once, i.e., once set, // it applies to all vnl_finite_int_polys with the same N and M. - static std::vector& modulo_polynomial(std::vector p = std::vector()) + static std::vector & + modulo_polynomial(std::vector p = std::vector()) { - static std::vector poly_(M+1, Scalar(0)); - if (p.empty()) { // retrieval + static std::vector poly_(M + 1, Scalar(0)); + if (p.empty()) + { // retrieval assert(poly_[M] != 0); // cannot retrieve before having set - } else { - assert(p.size() == M+1 && p[M].is_unit());// must be of effective degree M + } + else + { + assert(p.size() == M + 1 && p[M].is_unit()); // must be of effective degree M // Now set poly_, thereby making the coefficient poly_[M] equal to -1. - Scalar f = -1/p[M]; - for (int m=0; m<=M; ++m) poly_[m] = f*p[m]; + const Scalar f = -1 / p[M]; + for (int m = 0; m <= M; ++m) + poly_[m] = f * p[m]; } return poly_; } //: Multiply&assign: replace lhs by lhs * rhs, modulo the "modulo" polynomial - Base& operator*=(Base const& r) { - Base x = *this; *this = r; *this *= x[0]; - while (val_.size() < M) val_.push_back(0); - for (int i=1; i<=x.degree(); ++i) - for (unsigned int j=0; j<=r.deg(); ++j) - add_modulo_poly(i+j, x[i]*r[j]); + Base & + operator*=(const Base & r) + { + const Base x = *this; + *this = r; + *this *= x[0]; + while (val_.size() < M) + val_.push_back(0); + for (int i = 1; i <= x.degree(); ++i) + for (unsigned int j = 0; j <= r.deg(); ++j) + add_modulo_poly(i + j, x[i] * r[j]); return *this; } //: Return the multiplicative order of this polynomial. - inline unsigned int multiplicative_order() const { + inline unsigned int + multiplicative_order() const + { Base t = Scalar(1); unsigned int order = 0; - do t *= *this, ++order; while (t != Scalar(1) && t != Scalar(0)); - return t==Scalar(1) ? order : -1; + do + t *= *this, ++order; + while (t != Scalar(1) && t != Scalar(0)); + return t == Scalar(1) ? order : -1; } //: Return true when this ring is a field. // Note that this requires that N is a prime, but that condition is not // sufficient: also the "modulo" polynomial must be irreducible. - static inline bool is_field() { - if (!Scalar::is_field()) return false; + static inline bool + is_field() + { + if (!Scalar::is_field()) + return false; std::vector mod_p = Base::modulo_polynomial(); mod_p.pop_back(); // remove the "-1" coefficient of X^M - return Base(mod_p).multiplicative_order()+1 == Base::cardinality(); + return Base(mod_p).multiplicative_order() + 1 == Base::cardinality(); } //: Return the smallest multiplicative generator of the units in this ring. // This is only possible if the units form a cyclic group for multiplication. // If not, smallest_generator() returns 1 to indicate this fact. // Note that the multiplication group of a finite \e field is always cyclic. - static Base smallest_generator() { - if (!Base::is_field()) return Scalar(1); + static Base + smallest_generator() + { + if (!Base::is_field()) + return Scalar(1); std::vector mod_p = Base::modulo_polynomial(); mod_p.pop_back(); // remove the "-1" coefficient of X^M return Base(mod_p); } - private: +private: //: Add x to the i-th degree coefficient of val_, possibly reducing modulo the "modulo" poly. - void add_modulo_poly(unsigned int m, Scalar const& x) + void + add_modulo_poly(unsigned int m, const Scalar & x) { - if (m < M) val_[m] += x; - else { + if (m < M) + val_[m] += x; + else + { std::vector p = modulo_polynomial(); // where p[M] == -1 - for (int k=0; k -inline vnl_finite_int_poly operator+ (vnl_finite_int_poly const& r1, vnl_finite_int_poly const& r2) +inline vnl_finite_int_poly +operator+(const vnl_finite_int_poly & r1, const vnl_finite_int_poly & r2) { - vnl_finite_int_poly result=r1; return result += r2; + vnl_finite_int_poly result = r1; + return result += r2; } //: Returns the difference of two finite int polynomials. // \relatesalso vnl_finite_int_poly template -inline vnl_finite_int_poly operator- (vnl_finite_int_poly const& r1, vnl_finite_int_poly const& r2) +inline vnl_finite_int_poly +operator-(const vnl_finite_int_poly & r1, const vnl_finite_int_poly & r2) { - vnl_finite_int_poly result=r1; return result -= r2; + vnl_finite_int_poly result = r1; + return result -= r2; } //: Returns a scalar multiple of a finite int polynomial. // \relatesalso vnl_finite_int // \relatesalso vnl_finite_int_poly template -inline vnl_finite_int_poly operator* (vnl_finite_int_poly const& r1, vnl_finite_int const& r2) +inline vnl_finite_int_poly +operator*(const vnl_finite_int_poly & r1, const vnl_finite_int & r2) { - vnl_finite_int_poly result(r1); return result *= r2; + vnl_finite_int_poly result(r1); + return result *= r2; } //: Returns a scalar multiple of a finite int polynomial. // \relatesalso vnl_finite_int // \relatesalso vnl_finite_int_poly template -inline vnl_finite_int_poly operator* (vnl_finite_int const& r2, vnl_finite_int_poly const& r1) +inline vnl_finite_int_poly +operator*(const vnl_finite_int & r2, const vnl_finite_int_poly & r1) { - vnl_finite_int_poly result(r1); return result *= r2; + vnl_finite_int_poly result(r1); + return result *= r2; } //: Multiplies two finite int polynomials. @@ -631,26 +1098,36 @@ inline vnl_finite_int_poly operator* (vnl_finite_int const& r2, vnl_fini // Do this by calling modulo_polynomial(p), where p is a vector of length M+1. // \relatesalso vnl_finite_int_poly template -inline vnl_finite_int_poly operator* (vnl_finite_int_poly const& r1, vnl_finite_int_poly const& r2) +inline vnl_finite_int_poly +operator*(const vnl_finite_int_poly & r1, const vnl_finite_int_poly & r2) { - vnl_finite_int_poly result(r1); return result *= r2; + vnl_finite_int_poly result(r1); + return result *= r2; } //: formatted output // \relatesalso vnl_finite_int_poly template -inline std::ostream& operator<< (std::ostream& s, vnl_finite_int_poly const& r) +inline std::ostream & +operator<<(std::ostream & s, const vnl_finite_int_poly & r) { bool out = false; - for (unsigned int i=0; i<=r.deg(); ++i) { - if (r[i] == 0) continue; - if (out) s << '+'; + for (unsigned int i = 0; i <= r.deg(); ++i) + { + if (r[i] == 0) + continue; + if (out) + s << '+'; out = true; - if (r[i] != 1 || i==0) s << r[i]; - if (i>0) s << 'X'; - if (i>1) s << '^' << i; + if (r[i] != 1 || i == 0) + s << r[i]; + if (i > 0) + s << 'X'; + if (i > 1) + s << '^' << i; } - if (!out) s << '0'; + if (!out) + s << '0'; return s; } diff --git a/core/vnl/vnl_float_1x1.h b/core/vnl/vnl_float_1x1.h index 460db89c461..2dfa131a458 100644 --- a/core/vnl/vnl_float_1x1.h +++ b/core/vnl/vnl_float_1x1.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_1x1; +typedef vnl_matrix_fixed vnl_float_1x1; #endif // vnl_float_1x1_h_ diff --git a/core/vnl/vnl_float_1x2.h b/core/vnl/vnl_float_1x2.h index ea63224e3ed..f2f5824a76a 100644 --- a/core/vnl/vnl_float_1x2.h +++ b/core/vnl/vnl_float_1x2.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_1x2; +typedef vnl_matrix_fixed vnl_float_1x2; #endif // vnl_float_1x2_h_ diff --git a/core/vnl/vnl_float_1x3.h b/core/vnl/vnl_float_1x3.h index bab29262f62..9ae7cf41f82 100644 --- a/core/vnl/vnl_float_1x3.h +++ b/core/vnl/vnl_float_1x3.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_1x3; +typedef vnl_matrix_fixed vnl_float_1x3; #endif // vnl_float_1x3_h_ diff --git a/core/vnl/vnl_float_2.h b/core/vnl/vnl_float_2.h index 7a4ce9b8985..46b2e411b1d 100644 --- a/core/vnl/vnl_float_2.h +++ b/core/vnl/vnl_float_2.h @@ -17,12 +17,12 @@ #include "vnl_T_n.h" //: class vnl_float_2 : a vnl_vector of 2 floats. -vnl_T_n_impl(float,2); +vnl_T_n_impl(float, 2); //: Cross product of two 2-vectors // \relatesalso vnl_vector_fixed -inline -float vnl_cross_2d(vnl_float_2 const& v1, vnl_float_2 const& v2) +inline float +vnl_cross_2d(const vnl_float_2 & v1, const vnl_float_2 & v2) { return v1[0] * v2[1] - v1[1] * v2[0]; } diff --git a/core/vnl/vnl_float_2x1.h b/core/vnl/vnl_float_2x1.h index fb4e1165180..9cefb8bd728 100644 --- a/core/vnl/vnl_float_2x1.h +++ b/core/vnl/vnl_float_2x1.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_2x1; +typedef vnl_matrix_fixed vnl_float_2x1; #endif // vnl_float_2x1_h_ diff --git a/core/vnl/vnl_float_2x2.h b/core/vnl/vnl_float_2x2.h index 4413f6ca0f3..21243531583 100644 --- a/core/vnl/vnl_float_2x2.h +++ b/core/vnl/vnl_float_2x2.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_2x2; +typedef vnl_matrix_fixed vnl_float_2x2; #endif // vnl_float_2x2_h_ diff --git a/core/vnl/vnl_float_3.h b/core/vnl/vnl_float_3.h index 0183ab24f37..0ce2120b644 100644 --- a/core/vnl/vnl_float_3.h +++ b/core/vnl/vnl_float_3.h @@ -17,12 +17,12 @@ #include "vnl_T_n.h" //: class vnl_float_3 : a vnl_vector of 3 floats. -vnl_T_n_impl(float,3); +vnl_T_n_impl(float, 3); //: Cross product of two 3-vectors // \relatesalso vnl_vector_fixed -inline -vnl_float_3 vnl_cross_3d(vnl_float_3 const& v1, vnl_float_3 const& v2) +inline vnl_float_3 +vnl_cross_3d(const vnl_float_3 & v1, const vnl_float_3 & v2) { vnl_float_3 result; result[0] = v1[1] * v2[2] - v1[2] * v2[1]; diff --git a/core/vnl/vnl_float_3x1.h b/core/vnl/vnl_float_3x1.h index 42c2fade39f..b59b803a9a8 100644 --- a/core/vnl/vnl_float_3x1.h +++ b/core/vnl/vnl_float_3x1.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_3x1; +typedef vnl_matrix_fixed vnl_float_3x1; #endif // vnl_float_3x1_h_ diff --git a/core/vnl/vnl_float_3x3.h b/core/vnl/vnl_float_3x3.h index 0e227e5d905..2c662db9fb2 100644 --- a/core/vnl/vnl_float_3x3.h +++ b/core/vnl/vnl_float_3x3.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_3x3; +typedef vnl_matrix_fixed vnl_float_3x3; #endif // vnl_float_3x3_h_ diff --git a/core/vnl/vnl_float_3x4.h b/core/vnl/vnl_float_3x4.h index fde32f1a28f..df9954a3c8b 100644 --- a/core/vnl/vnl_float_3x4.h +++ b/core/vnl/vnl_float_3x4.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_3x4; +typedef vnl_matrix_fixed vnl_float_3x4; #endif // vnl_float_3x4_h_ diff --git a/core/vnl/vnl_float_4.h b/core/vnl/vnl_float_4.h index 786533bd991..3037505dc4a 100644 --- a/core/vnl/vnl_float_4.h +++ b/core/vnl/vnl_float_4.h @@ -15,6 +15,6 @@ #include "vnl_T_n.h" //: class vnl_float_4 : a vnl_vector of 4 floats. -vnl_T_n_impl(float,4); +vnl_T_n_impl(float, 4); #endif // vnl_float_4_h_ diff --git a/core/vnl/vnl_float_4x3.h b/core/vnl/vnl_float_4x3.h index 8102c6ed67a..89450f0a6f0 100644 --- a/core/vnl/vnl_float_4x3.h +++ b/core/vnl/vnl_float_4x3.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_4x3; +typedef vnl_matrix_fixed vnl_float_4x3; #endif // vnl_float_4x3_h_ diff --git a/core/vnl/vnl_float_4x4.h b/core/vnl/vnl_float_4x4.h index 90131ac66c7..df03b574272 100644 --- a/core/vnl/vnl_float_4x4.h +++ b/core/vnl/vnl_float_4x4.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_float_4x4; +typedef vnl_matrix_fixed vnl_float_4x4; #endif // vnl_float_4x4_h_ diff --git a/core/vnl/vnl_fortran_copy.h b/core/vnl/vnl_fortran_copy.h index 8f4414d7ffa..7b507bf06f5 100644 --- a/core/vnl/vnl_fortran_copy.h +++ b/core/vnl/vnl_fortran_copy.h @@ -25,22 +25,22 @@ template class VNL_EXPORT vnl_fortran_copy { - public: +public: // Constructors/Destructors-------------------------------------------------- - vnl_fortran_copy(vnl_matrix const & M); + vnl_fortran_copy(const vnl_matrix & M); ~vnl_fortran_copy(); // Operations---------------------------------------------------------------- - operator T*() { return data; } + operator T *() { return data; } - protected: +protected: // Data Members-------------------------------------------------------------- int sz; - T *data; + T * data; - private: +private: // Helpers------------------------------------------------------------------- }; diff --git a/core/vnl/vnl_fortran_copy.hxx b/core/vnl/vnl_fortran_copy.hxx index 42ea9980a38..7b880c1f194 100644 --- a/core/vnl/vnl_fortran_copy.hxx +++ b/core/vnl/vnl_fortran_copy.hxx @@ -11,16 +11,16 @@ //: Generate a fortran column-storage matrix from the given matrix. template -vnl_fortran_copy::vnl_fortran_copy(vnl_matrix const & M) +vnl_fortran_copy::vnl_fortran_copy(const vnl_matrix & M) { - unsigned n = M.rows(); - unsigned p = M.columns(); + const unsigned n = M.rows(); + const unsigned p = M.columns(); - data = vnl_c_vector::allocate_T(sz = n*p); - T *d = data; + data = vnl_c_vector::allocate_T(sz = n * p); + T * d = data; for (unsigned j = 0; j < p; ++j) for (unsigned i = 0; i < n; ++i) - *d++ = M(i,j); + *d++ = M(i, j); } //: Destructor @@ -33,7 +33,6 @@ vnl_fortran_copy::~vnl_fortran_copy() //-------------------------------------------------------------------------------- #undef VNL_FORTRAN_COPY_INSTANTIATE -#define VNL_FORTRAN_COPY_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_fortran_copy +#define VNL_FORTRAN_COPY_INSTANTIATE(T) template class VNL_EXPORT vnl_fortran_copy #endif // vnl_fortran_copy_hxx_ diff --git a/core/vnl/vnl_fortran_copy_fixed.h b/core/vnl/vnl_fortran_copy_fixed.h index 2a3f89acf97..2bd20fd6171 100644 --- a/core/vnl/vnl_fortran_copy_fixed.h +++ b/core/vnl/vnl_fortran_copy_fixed.h @@ -26,19 +26,19 @@ template class VNL_EXPORT vnl_fortran_copy_fixed { - public: +public: // Constructors/Destructors-------------------------------------------------- - vnl_fortran_copy_fixed(vnl_matrix_fixed const & M); + vnl_fortran_copy_fixed(const vnl_matrix_fixed & M); // Operations---------------------------------------------------------------- - operator T*() { return data; } + operator T *() { return data; } - protected: +protected: // Data Members-------------------------------------------------------------- - T data[R*C]; + T data[R * C]; - private: +private: // Helpers------------------------------------------------------------------- }; diff --git a/core/vnl/vnl_fortran_copy_fixed.hxx b/core/vnl/vnl_fortran_copy_fixed.hxx index 5aed92d0b61..d7fcd591aec 100644 --- a/core/vnl/vnl_fortran_copy_fixed.hxx +++ b/core/vnl/vnl_fortran_copy_fixed.hxx @@ -11,18 +11,18 @@ //: Generate a fortran column-storage matrix from the given matrix. template -vnl_fortran_copy_fixed::vnl_fortran_copy_fixed(vnl_matrix_fixed const & M) +vnl_fortran_copy_fixed::vnl_fortran_copy_fixed(const vnl_matrix_fixed & M) { - T *d = data; + T * d = data; for (unsigned j = 0; j < C; ++j) for (unsigned i = 0; i < R; ++i) - *d++ = M(i,j); + *d++ = M(i, j); } //-------------------------------------------------------------------------------- #undef VNL_FORTRAN_COPY_FIXED_INSTANTIATE -#define VNL_FORTRAN_COPY_FIXED_INSTANTIATE(T , R , C ) template class VNL_EXPORT vnl_fortran_copy_fixed +#define VNL_FORTRAN_COPY_FIXED_INSTANTIATE(T, R, C) template class VNL_EXPORT vnl_fortran_copy_fixed #endif // vnl_fortran_copy_fixed_hxx_ diff --git a/core/vnl/vnl_fwd.h b/core/vnl/vnl_fwd.h index 9364432443b..f09202e7078 100644 --- a/core/vnl/vnl_fwd.h +++ b/core/vnl/vnl_fwd.h @@ -9,28 +9,46 @@ # include #endif -template struct vnl_complex_traits; -template class vnl_numeric_traits; -template class vnl_c_vector; +template +struct vnl_complex_traits; +template +class vnl_numeric_traits; +template +class vnl_c_vector; -template class vnl_vector; -template class vnl_vector_ref; +template +class vnl_vector; +template +class vnl_vector_ref; -template class vnl_matrix; -template class vnl_matrix_ref; +template +class vnl_matrix; +template +class vnl_matrix_ref; -template class vnl_vector_fixed; -template class vnl_matrix_fixed; -template class vnl_vector_fixed_ref; -template class vnl_matrix_fixed_ref; -template class vnl_vector_fixed_ref_const; -template class vnl_matrix_fixed_ref_const; +template +class vnl_vector_fixed; +template +class vnl_matrix_fixed; +template +class vnl_vector_fixed_ref; +template +class vnl_matrix_fixed_ref; +template +class vnl_vector_fixed_ref_const; +template +class vnl_matrix_fixed_ref_const; -template class vnl_quaternion; -template class vnl_unary_function; -template class vnl_diag_matrix; -template class vnl_fortran_copy; -template class vnl_identity; +template +class vnl_quaternion; +template +class vnl_unary_function; +template +class vnl_diag_matrix; +template +class vnl_fortran_copy; +template +class vnl_identity; class vnl_cost_function; class vnl_cross_product_matrix; @@ -39,32 +57,32 @@ class vnl_double_3; class vnl_double_4; class vnl_double_2x3; class vnl_double_3x2; -typedef vnl_matrix_fixed vnl_double_1x1; -typedef vnl_matrix_fixed vnl_double_1x2; -typedef vnl_matrix_fixed vnl_double_2x1; -typedef vnl_matrix_fixed vnl_double_2x2; -typedef vnl_matrix_fixed vnl_double_1x3; -typedef vnl_matrix_fixed vnl_double_3x1; -typedef vnl_matrix_fixed vnl_double_3x3; -typedef vnl_matrix_fixed vnl_double_3x4; -typedef vnl_matrix_fixed vnl_double_4x3; -typedef vnl_matrix_fixed vnl_double_4x4; +typedef vnl_matrix_fixed vnl_double_1x1; +typedef vnl_matrix_fixed vnl_double_1x2; +typedef vnl_matrix_fixed vnl_double_2x1; +typedef vnl_matrix_fixed vnl_double_2x2; +typedef vnl_matrix_fixed vnl_double_1x3; +typedef vnl_matrix_fixed vnl_double_3x1; +typedef vnl_matrix_fixed vnl_double_3x3; +typedef vnl_matrix_fixed vnl_double_3x4; +typedef vnl_matrix_fixed vnl_double_4x3; +typedef vnl_matrix_fixed vnl_double_4x4; class vnl_float_2; class vnl_float_3; class vnl_float_4; -typedef vnl_matrix_fixed vnl_float_1x2; -typedef vnl_matrix_fixed vnl_float_2x1; -typedef vnl_matrix_fixed vnl_float_2x2; -typedef vnl_matrix_fixed vnl_float_1x3; -typedef vnl_matrix_fixed vnl_float_3x1; -typedef vnl_matrix_fixed vnl_float_3x3; -typedef vnl_matrix_fixed vnl_float_3x4; -typedef vnl_matrix_fixed vnl_float_4x3; -typedef vnl_matrix_fixed vnl_float_4x4; +typedef vnl_matrix_fixed vnl_float_1x2; +typedef vnl_matrix_fixed vnl_float_2x1; +typedef vnl_matrix_fixed vnl_float_2x2; +typedef vnl_matrix_fixed vnl_float_1x3; +typedef vnl_matrix_fixed vnl_float_3x1; +typedef vnl_matrix_fixed vnl_float_3x3; +typedef vnl_matrix_fixed vnl_float_3x4; +typedef vnl_matrix_fixed vnl_float_4x3; +typedef vnl_matrix_fixed vnl_float_4x4; class vnl_int_2; class vnl_int_3; class vnl_int_4; -typedef vnl_matrix_fixed vnl_int_2x2; +typedef vnl_matrix_fixed vnl_int_2x2; struct vnl_identity_3x3; class vnl_least_squares_cost_function; class vnl_least_squares_function; diff --git a/core/vnl/vnl_gamma.cxx b/core/vnl/vnl_gamma.cxx index 0e2e428eff3..f906d3506da 100644 --- a/core/vnl/vnl_gamma.cxx +++ b/core/vnl/vnl_gamma.cxx @@ -25,7 +25,7 @@ vnl_log_gamma(double x) zp -= 5.00757863970517583837 / (x + 3.0); zp += 0.0114684895434781459556 / (x + 4.0); - double x1 = x + 4.65; + const double x1 = x + 4.65; return std::log(zp) + (x - 0.5) * std::log(x1) - x1; } @@ -74,7 +74,7 @@ vnl_gamma_cont_frac(double a, double x) double cf = d; for (int i = 1; i <= MAX_ITS; i++) { - double a_i = i * (a - i); + const double a_i = i * (a - i); b_i += 2.0; d = a_i * d + b_i; if (std::fabs(d) < vnl_very_small) @@ -83,7 +83,7 @@ vnl_gamma_cont_frac(double a, double x) if (std::fabs(c) < vnl_very_small) c = vnl_very_small; d = 1.0 / d; - double delta = d * c; + const double delta = d * c; cf *= delta; if (std::fabs(delta - 1.0) < MaxRelError) return std::exp(-x + a * std::log(x) - vnl_log_gamma(a)) * cf; @@ -121,15 +121,15 @@ vnl_gamma_q(double a, double x) double vnl_digamma(double z) { - double t0 = (z - 0.5) / (z + 4.65) - 1.0; - double tlg = std::log(4.65 + z); - double tc = 2.50662827563479526904; - double t1 = 225.525584619175212544 / z; - double t2 = -268.295973841304927459 / (1 + z); - double t3 = +80.9030806934622512966 / (2 + z); - double t4 = -5.00757863970517583837 / (3 + z); - double t5 = 0.0114684895434781459556 / (4 + z); - double neu = t1 / z + t2 / (1 + z) + t3 / (2 + z) + t4 / (3 + z) + t5 / (4 + z); - double den = tc + t1 + t2 + t3 + t4 + t5; + const double t0 = (z - 0.5) / (z + 4.65) - 1.0; + const double tlg = std::log(4.65 + z); + const double tc = 2.50662827563479526904; + const double t1 = 225.525584619175212544 / z; + const double t2 = -268.295973841304927459 / (1 + z); + const double t3 = +80.9030806934622512966 / (2 + z); + const double t4 = -5.00757863970517583837 / (3 + z); + const double t5 = 0.0114684895434781459556 / (4 + z); + const double neu = t1 / z + t2 / (1 + z) + t3 / (2 + z) + t4 / (3 + z) + t5 / (4 + z); + const double den = tc + t1 + t2 + t3 + t4 + t5; return t0 - (neu / den) + tlg; } diff --git a/core/vnl/vnl_gamma.h b/core/vnl/vnl_gamma.h index e9ed01f232f..f299dfdb8ea 100644 --- a/core/vnl/vnl_gamma.h +++ b/core/vnl/vnl_gamma.h @@ -16,23 +16,30 @@ // Uses 6 parameter Lanczos approximation as described by Toth // (http://www.rskey.org/gamma.htm) // Accurate to about one part in 3e-11. -VNL_EXPORT double vnl_log_gamma(double x); +VNL_EXPORT double +vnl_log_gamma(double x); //: Approximate gamma function // Uses 6 parameter Lanczos approximation as described by Toth // (http://www.rskey.org/gamma.htm) // Accurate to about one part in 3e-11. -inline double vnl_gamma(double x) { return std::exp(vnl_log_gamma(x)); } +inline double +vnl_gamma(double x) +{ + return std::exp(vnl_log_gamma(x)); +} //: Normalised Incomplete gamma function, P(a,x) // $P(a,x)=\frac{1}{\Gamma(a)}\int_0^x e^{-t}t^{a-1}dt$ // Note the order of parameters - this is the normal maths order. // MATLAB uses gammainc(x,a), ie the other way around -VNL_EXPORT double vnl_gamma_p(double a, double x); +VNL_EXPORT double +vnl_gamma_p(double a, double x); -//:Normalised Incomplete gamma function, Q(a,x) +//: Normalised Incomplete gamma function, Q(a,x) // $Q(a,x)=\frac{1}{\Gamma(a)}\int_x^{\infty}e^{-t}t^{a-1}dt$ -VNL_EXPORT double vnl_gamma_q(double a, double x); +VNL_EXPORT double +vnl_gamma_q(double a, double x); //: P(chi class VNL_EXPORT vnl_hungarian_algorithm { - public: - +public: // The steps of the algorithm described below are taken from // http://www.cs.duke.edu/brd/Teaching/Bio/asmb/current/Handouts/munkres.html - enum STEP_TYPE { + enum STEP_TYPE + { STEP_0 = 0, STEP_1, STEP_2, @@ -48,61 +48,78 @@ class VNL_EXPORT vnl_hungarian_algorithm STEP_done }; - enum STATE_TYPE { - NORMAL=0, + enum STATE_TYPE + { + NORMAL = 0, STAR, PRIME }; - typedef vnl_matrix< int > AssignmentMatrixType; + typedef vnl_matrix AssignmentMatrixType; typedef std::vector AssignmentVectorType; - vnl_hungarian_algorithm() : m_TotalCost(0) {} + vnl_hungarian_algorithm() + : m_TotalCost(0) + {} ~vnl_hungarian_algorithm() = default; - //: This constructor (and the following cast operator) is provided for backward compatibility with the original function implementation - vnl_hungarian_algorithm(vnl_matrix const& cost) { SetCostMatrix(cost); StartAssignment(); } + //: This constructor (and the following cast operator) is provided for backward compatibility with the original + //: function implementation + vnl_hungarian_algorithm(const vnl_matrix & cost) + { + SetCostMatrix(cost); + StartAssignment(); + } operator std::vector() { return GetAssignmentVector(); } //: Starts the assignment - void SetCostMatrix( vnl_matrix< T > const& ); + void + SetCostMatrix(const vnl_matrix &); //: Starts the assignment - void StartAssignment(); + void + StartAssignment(); //: Returns the total cost of the assignment - T GetTotalCost(); + T + GetTotalCost(); //: Returns the assignment matrix - AssignmentMatrixType GetAssignmentMatrix(); + AssignmentMatrixType + GetAssignmentMatrix(); //: Returns the assignment vector - AssignmentVectorType GetAssignmentVector(); + AssignmentVectorType + GetAssignmentVector(); - protected: +protected: //: Step 0 - Make sure there are at least as many rows as columns in the cost matrix // The nxm cost matrix is a matrix in which each element represents // the cost of assigning one of n workers to one of m jobs. // \returns the next step to go to (which is Step 1). - STEP_TYPE Step_0(); + STEP_TYPE + Step_0(); //: Step 1 - For each row of the matrix, find the smallest element and subtract it from every element in its row. // \returns the next step to go to (which is Step 2). - STEP_TYPE Step_1(); + STEP_TYPE + Step_1(); //: Step 2 - Find a zero (Z) in the resulting matrix. // If there is no starred zero in its row or column, star Z. // Repeat for each element in the matrix. // \returns the next step to go to (which is Step 3) - STEP_TYPE Step_2(); + STEP_TYPE + Step_2(); //: Step 3 - Cover each column containing a starred zero. // If K columns are covered, the starred zeros describe a complete // set of unique assignments. // In this case, Go to DONE, otherwise, Go to Step 4. // \returns the next step to go to - STEP_TYPE Step_3(); + STEP_TYPE + Step_3(); //: Step 4: Find a noncovered zero and prime it. // If there is no starred zero in the row containing this primed zero, Go to Step 5. @@ -110,7 +127,8 @@ class VNL_EXPORT vnl_hungarian_algorithm // zero. Continue in this manner until there are no uncovered zeros left. // Save the smallest uncovered value and Go to Step 6. // \returns the next step to go to - STEP_TYPE Step_4(); + STEP_TYPE + Step_4(); //: Step 5 - Construct a series of alternating primed and starred zeros as follows. // Let Z0 represent the uncovered primed zero found in Step 4. @@ -121,24 +139,28 @@ class VNL_EXPORT vnl_hungarian_algorithm // star each primed zero of the series, erase all primes and uncover every // line in the matrix. Return to Step 3. // \returns the next step to go to - STEP_TYPE Step_5(); + STEP_TYPE + Step_5(); //: Step 6 - // Add the value found in Step 4 to every element of each covered row, // and subtract it from every element of each uncovered column. // Return to Step 4 without altering any stars, primes, or covered lines. // \returns the next step to go to - STEP_TYPE Step_6(); + STEP_TYPE + Step_6(); //: Step done - Returns a vector containing the result of the assignment. // Assignment pairs are indicated by the positions of the // starred zeros in the cost matrix. If C(i,j) is a starred zero, // then the element associated with row i is assigned to the element // associated with column j. - void Step_done(); + void + Step_done(); //: Sets all the values in the input bool vector to false. - void clear_vector( std::vector& ); + void + clear_vector(std::vector &); vnl_matrix m_Cost; vnl_matrix m_Cost_in; diff --git a/core/vnl/vnl_hungarian_algorithm.hxx b/core/vnl/vnl_hungarian_algorithm.hxx index a69b97e1f74..ffc28a78631 100644 --- a/core/vnl/vnl_hungarian_algorithm.hxx +++ b/core/vnl/vnl_hungarian_algorithm.hxx @@ -19,10 +19,9 @@ //----------------------------------------------------------------------------- // Set Cost Matrix //----------------------------------------------------------------------------- -template +template void -vnl_hungarian_algorithm:: -SetCostMatrix( vnl_matrix const& cost_in ) +vnl_hungarian_algorithm::SetCostMatrix(const vnl_matrix & cost_in) { m_Cost_in = cost_in; m_TotalCost = 0; @@ -32,14 +31,14 @@ SetCostMatrix( vnl_matrix const& cost_in ) // constant cost. // Get Max size of the matrix - m_N = std::max( cost_in.rows(), cost_in.cols() ); + m_N = std::max(cost_in.rows(), cost_in.cols()); - m_Cost.set_size( m_N, m_N); - m_Cost.fill( static_cast(0) ); + m_Cost.set_size(m_N, m_N); + m_Cost.fill(static_cast(0)); // Initialize cost matrix // Update the cost matrix () - m_Cost.update( cost_in, 0, 0 ); + m_Cost.update(cost_in, 0, 0); } //----------------------------------------------------------------------------- @@ -47,12 +46,11 @@ SetCostMatrix( vnl_matrix const& cost_in ) //----------------------------------------------------------------------------- template void -vnl_hungarian_algorithm:: -clear_vector( std::vector& v ) +vnl_hungarian_algorithm::clear_vector(std::vector & v) { typedef std::vector::iterator iter; - iter end = v.end(); - for ( iter i = v.begin(); i != end; ++i ) + const iter end = v.end(); + for (iter i = v.begin(); i != end; ++i) { *i = false; } @@ -63,8 +61,7 @@ clear_vector( std::vector& v ) //----------------------------------------------------------------------------- template void -vnl_hungarian_algorithm:: -StartAssignment() +vnl_hungarian_algorithm::StartAssignment() { // Step 0 // Make sure there are at least as many rows as columns @@ -88,50 +85,50 @@ StartAssignment() STEP_TYPE step = STEP_3; - while ( step != STEP_done ) + while (step != STEP_done) { - switch ( step ) + switch (step) { - case STEP_3 : - // Step 3: Cover each column containing a starred zero. If K - // columns are covered, the starred zeros describe a complete set of - // unique assignments. In this case, Go to DONE, otherwise, Go to - // Step 4. + case STEP_3: + // Step 3: Cover each column containing a starred zero. If K + // columns are covered, the starred zeros describe a complete set of + // unique assignments. In this case, Go to DONE, otherwise, Go to + // Step 4. step = Step_3(); break; - case STEP_4 : - // Step 4: Find a noncovered zero and prime it. If there is no - // starred zero in the row containing this primed zero, Go to Step - // 5. Otherwise, cover this row and uncover the column containing - // the starred zero. Continue in this manner until there are no - // uncovered zeros left. Save the smallest uncovered value and Go to - // Step 6. + case STEP_4: + // Step 4: Find a noncovered zero and prime it. If there is no + // starred zero in the row containing this primed zero, Go to Step + // 5. Otherwise, cover this row and uncover the column containing + // the starred zero. Continue in this manner until there are no + // uncovered zeros left. Save the smallest uncovered value and Go to + // Step 6. step = Step_4(); break; - case STEP_5 : - // Step 5: Construct a series of alternating primed and starred - // zeros as follows. Let Z0 represent the uncovered primed zero - // found in Step 4. Let Z1 denote the starred zero in the column of - // Z0 (if any). Let Z2 denote the primed zero in the row of Z1 - // (there will always be one). Continue until the series terminates - // at a primed zero that has no starred zero in its column. Unstar - // each starred zero of the series, star each primed zero of the - // series, erase all primes and uncover every line in the matrix. - // Return to Step 3. + case STEP_5: + // Step 5: Construct a series of alternating primed and starred + // zeros as follows. Let Z0 represent the uncovered primed zero + // found in Step 4. Let Z1 denote the starred zero in the column of + // Z0 (if any). Let Z2 denote the primed zero in the row of Z1 + // (there will always be one). Continue until the series terminates + // at a primed zero that has no starred zero in its column. Unstar + // each starred zero of the series, star each primed zero of the + // series, erase all primes and uncover every line in the matrix. + // Return to Step 3. step = Step_5(); break; - case STEP_6 : - // Step 6: Add the value found in Step 4 to every element of each - // covered row, and subtract it from every element of each uncovered - // column. Return to Step 4 without altering any stars, primes, or - // covered + case STEP_6: + // Step 6: Add the value found in Step 4 to every element of each + // covered row, and subtract it from every element of each uncovered + // column. Return to Step 4 without altering any stars, primes, or + // covered step = Step_6(); break; - default : + default: step = STEP_done; break; } @@ -159,8 +156,8 @@ vnl_hungarian_algorithm::Step_0() // M(i,j) = STAR => cost(i,j) is starred // M(i,j) = PRIME => cost(i,j) is primed - m_M.set_size( m_N, m_N); - m_M.fill( NORMAL ); + m_M.set_size(m_N, m_N); + m_M.fill(NORMAL); // R_cov[i] = true => row i is covered // C_cov[j] = true => column j is covered @@ -179,21 +176,21 @@ template typename vnl_hungarian_algorithm::STEP_TYPE vnl_hungarian_algorithm::Step_1() { -//creer j a l'exterieur + // creer j a l'exterieur - for ( unsigned i = 0; i < m_N; ++i ) + for (unsigned i = 0; i < m_N; ++i) { - T mn = m_Cost(i,0); - for ( unsigned j = 1; j < m_N; ++j ) + T mn = m_Cost(i, 0); + for (unsigned j = 1; j < m_N; ++j) { - if ( mn > m_Cost(i,j) ) + if (mn > m_Cost(i, j)) { - mn = m_Cost(i,j); + mn = m_Cost(i, j); } } - for ( unsigned j = 0; j < m_N; ++j ) + for (unsigned j = 0; j < m_N; ++j) { - m_Cost(i,j) -= mn; + m_Cost(i, j) -= mn; } } return STEP_2; @@ -212,15 +209,15 @@ vnl_hungarian_algorithm::Step_2() { // We'll use C_cov and R_cov to indicate if there is a starred // zero in that column or row, respectively - for ( unsigned i = 0; i < m_N; ++i ) + for (unsigned i = 0; i < m_N; ++i) { - if ( ! m_R_cov[i] ) + if (!m_R_cov[i]) { - for ( unsigned j = 0; j < m_N; ++j ) + for (unsigned j = 0; j < m_N; ++j) { - if ( m_Cost(i,j) == 0 && ! m_C_cov[j] ) + if (m_Cost(i, j) == 0 && !m_C_cov[j]) { - m_M(i,j) = STAR; // star it + m_M(i, j) = STAR; // star it m_R_cov[i] = true; // and update the row & col status. m_C_cov[j] = true; break; // the row is now starred. Don't look at the rest. @@ -228,8 +225,8 @@ vnl_hungarian_algorithm::Step_2() } } } - clear_vector( m_R_cov ); - clear_vector( m_C_cov ); + clear_vector(m_R_cov); + clear_vector(m_C_cov); return STEP_3; } @@ -244,11 +241,11 @@ typename vnl_hungarian_algorithm::STEP_TYPE vnl_hungarian_algorithm::Step_3() { unsigned count = 0; - for ( unsigned j = 0; j < m_N; ++j ) + for (unsigned j = 0; j < m_N; ++j) { - for ( unsigned i = 0; i < m_N; ++i ) + for (unsigned i = 0; i < m_N; ++i) { - if ( m_M(i,j) == STAR ) + if (m_M(i, j) == STAR) { m_C_cov[j] = true; ++count; @@ -257,7 +254,7 @@ vnl_hungarian_algorithm::Step_3() } } - if ( count == m_N ) + if (count == m_N) { return STEP_done; } @@ -283,24 +280,24 @@ vnl_hungarian_algorithm::Step_4() // Find an uncovered zero // This loop will exit with a goto step_five or step_six. - unsigned i, j; // row and column of the uncovered zero, if any. - for (i = 0 ; i < m_N; ++i ) + // row and column of the uncovered zero, if any. + for (unsigned i = 0; i < m_N; ++i) + { + if (!m_R_cov[i]) { - if ( ! m_R_cov[i] ) + for (unsigned j = 0; j < m_N; ++j) { - for ( j = 0; j < m_N; ++j ) - { #ifdef DEBUG - std::cout << m_Cost(i,j) << std::endl; + std::cout << m_Cost(i, j) << std::endl; #endif - if ( m_Cost(i,j) == 0 && ! m_C_cov[j] ) + if (m_Cost(i, j) == 0 && !m_C_cov[j]) + { + m_M(i, j) = PRIME; // prime it + bool star_in_row = false; + for (unsigned j2 = 0; j2 < m_N; ++j2) { - m_M(i,j) = PRIME; // prime it - bool star_in_row = false; - for ( unsigned j2 = 0; j2 < m_N; ++j2 ) + if (m_M(i, j2) == STAR) { - if ( m_M(i,j2) == STAR ) - { star_in_row = true; // cover the row, uncover the star column m_R_cov[i] = true; @@ -310,7 +307,7 @@ vnl_hungarian_algorithm::Step_4() } // If there isn't go to step 5 - if ( ! star_in_row ) + if (!star_in_row) { m_Z0_r = i; m_Z0_c = j; @@ -345,79 +342,80 @@ vnl_hungarian_algorithm::Step_5() { unsigned i = m_Z0_r; unsigned j = m_Z0_c; - std::vector rows, cols; + std::vector rows; + std::vector cols; - while ( true ) + while (true) { // This is the primed zero - assert( m_M(i,j) == PRIME ); - rows.push_back( i ); - cols.push_back( j ); + assert(m_M(i, j) == PRIME); + rows.push_back(i); + cols.push_back(j); // Look for a starred zero in this column - for ( i = 0; i < m_N; ++i ) + for (i = 0; i < m_N; ++i) { - if ( m_M(i,j) == STAR ) + if (m_M(i, j) == STAR) { break; } } - if ( i == m_N ) + if (i == m_N) { // we didn't find a starred zero. Stop the loop break; } // This is the starred zero - rows.push_back( i ); - cols.push_back( j ); + rows.push_back(i); + cols.push_back(j); // Look for the primed zero in the row of the starred zero - for ( j = 0; j < m_N; ++j ) + for (j = 0; j < m_N; ++j) { - if ( m_M(i,j) == PRIME ) + if (m_M(i, j) == PRIME) { break; } } - assert( j < m_N ); // there should always be one + assert(j < m_N); // there should always be one // go back to the top to mark the primed zero, and repeat. } // Series has terminated. Unstar each star and star each prime in // the series. - for ( unsigned idx = 0; idx < rows.size(); ++idx ) + for (unsigned idx = 0; idx < rows.size(); ++idx) { - unsigned i = rows[idx]; - unsigned j = cols[idx]; - if ( m_M(i,j) == STAR ) + const unsigned i = rows[idx]; + const unsigned j = cols[idx]; + if (m_M(i, j) == STAR) { - m_M(i,j) = NORMAL; // unstar each starred zero - } + m_M(i, j) = NORMAL; // unstar each starred zero + } else { - assert( m_M(i,j) == PRIME ); - m_M(i,j) = STAR; // star each primed zero + assert(m_M(i, j) == PRIME); + m_M(i, j) = STAR; // star each primed zero } } // Erase all primes. - for ( unsigned i = 0; i < m_N; ++i ) + for (unsigned i = 0; i < m_N; ++i) { - for ( unsigned j = 0; j < m_N; ++j ) + for (unsigned j = 0; j < m_N; ++j) { - if ( m_M(i,j) == PRIME ) + if (m_M(i, j) == PRIME) { - m_M(i,j) = NORMAL; + m_M(i, j) = NORMAL; } } } // Uncover everything - clear_vector( m_R_cov ); - clear_vector( m_C_cov ); + clear_vector(m_R_cov); + clear_vector(m_C_cov); return STEP_3; } @@ -434,32 +432,32 @@ vnl_hungarian_algorithm::Step_6() { // The value found in step 4 is the smallest uncovered value. Find it now. T minval = std::numeric_limits::max(); - for ( unsigned i = 0; i < m_N; ++i ) + for (unsigned i = 0; i < m_N; ++i) { - if ( ! m_R_cov[i] ) + if (!m_R_cov[i]) { - for ( unsigned j = 0; j < m_N; ++j ) + for (unsigned j = 0; j < m_N; ++j) { - if ( ! m_C_cov[j] && m_Cost(i,j) < minval ) + if (!m_C_cov[j] && m_Cost(i, j) < minval) { - minval = m_Cost(i,j); + minval = m_Cost(i, j); } } } } // Modify the matrix as instructed. - for ( unsigned i = 0; i < m_N; ++i ) + for (unsigned i = 0; i < m_N; ++i) { - for ( unsigned j = 0; j < m_N; ++j ) + for (unsigned j = 0; j < m_N; ++j) { - if ( m_R_cov[i] ) + if (m_R_cov[i]) { - m_Cost(i,j) += minval; + m_Cost(i, j) += minval; } - if ( ! m_C_cov[j] ) + if (!m_C_cov[j]) { - m_Cost(i,j) -= minval; + m_Cost(i, j) -= minval; } } } @@ -478,17 +476,17 @@ template void vnl_hungarian_algorithm::Step_done() { - std::vector assign( m_Cost_in.rows(), (unsigned int)(-1) ); + const std::vector assign(m_Cost_in.rows(), (unsigned int)(-1)); m_AssignmentVector = assign; // Find the stars and generate the resulting assignment. Only // check the sub-matrix of cost that corresponds to the input cost // matrix. The remaining rows and columns are unassigned. - for ( unsigned j = 0; j < m_Cost_in.cols(); ++j ) + for (unsigned j = 0; j < m_Cost_in.cols(); ++j) { - for ( unsigned i = 0; i < m_Cost_in.rows(); ++i ) + for (unsigned i = 0; i < m_Cost_in.rows(); ++i) { - if ( m_M(i,j) == STAR ) + if (m_M(i, j) == STAR) { m_AssignmentVector[i] = j; m_TotalCost += m_Cost_in[i][j]; @@ -528,7 +526,6 @@ vnl_hungarian_algorithm::GetAssignmentVector() } #undef VNL_HUNGARIAN_ALGORITHM_INSTANTIATE -#define VNL_HUNGARIAN_ALGORITHM_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_hungarian_algorithm +#define VNL_HUNGARIAN_ALGORITHM_INSTANTIATE(T) template class VNL_EXPORT vnl_hungarian_algorithm #endif // vnl_hungarian_algorithm_hxx_ diff --git a/core/vnl/vnl_identity.h b/core/vnl/vnl_identity.h index 7635f720acc..16e8ee36f6b 100644 --- a/core/vnl/vnl_identity.h +++ b/core/vnl/vnl_identity.h @@ -17,16 +17,20 @@ #include "vnl/vnl_export.h" template -class VNL_EXPORT vnl_identity : public vnl_unary_function +class VNL_EXPORT vnl_identity : public vnl_unary_function { - public: - vnl_unary_function* Copy() const override { - vnl_identity* copy = new vnl_identity; +public: + vnl_unary_function * + Copy() const override + { + vnl_identity * copy = new vnl_identity; *copy = *this; return copy; } - T f(T const& x) override { + T + f(const T & x) override + { return x; } }; diff --git a/core/vnl/vnl_imag.h b/core/vnl/vnl_imag.h index 498d7239551..44df2a5311c 100644 --- a/core/vnl/vnl_imag.h +++ b/core/vnl/vnl_imag.h @@ -24,9 +24,9 @@ #include "vnl/vnl_export.h" //: Return array I of imaginary parts of complex array C. -template VNL_EXPORT -void -vnl_imag(std::complex const* C, T* I, unsigned int n); +template +VNL_EXPORT void +vnl_imag(const std::complex * C, T * I, unsigned int n); // - vnl_vector // - vnl_vector_fixed @@ -38,19 +38,19 @@ vnl_imag(std::complex const* C, T* I, unsigned int n); //: Vector of imaginary parts of vnl_vector >. // \relatesalso vnl_vector -template VNL_EXPORT -vnl_vector -vnl_imag(vnl_vector > const& C); +template +VNL_EXPORT vnl_vector +vnl_imag(const vnl_vector> & C); //: Vector of imaginary parts of vnl_vector_fixed, N >. // \relatesalso vnl_vector_fixed template -vnl_vector_fixed -vnl_imag(vnl_vector_fixed, N > const& C) +vnl_vector_fixed +vnl_imag(const vnl_vector_fixed, N> & C) { - vnl_vector_fixed R; - typename vnl_vector_fixed,N >::const_iterator cIt = C.begin(); - typename vnl_vector_fixed::iterator rIt = R.begin(); + vnl_vector_fixed R; + typename vnl_vector_fixed, N>::const_iterator cIt = C.begin(); + typename vnl_vector_fixed::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::imag(*cIt); return R; @@ -58,19 +58,19 @@ vnl_imag(vnl_vector_fixed, N > const& C) //: Matrix of imaginary parts of vnl_matrix >. // \relatesalso vnl_matrix -template VNL_EXPORT -vnl_matrix -vnl_imag(vnl_matrix > const& C); +template +VNL_EXPORT vnl_matrix +vnl_imag(const vnl_matrix> & C); //: Matrix of imaginary parts of vnl_matrix_fixed,NRow,NCol >. // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed -vnl_imag(vnl_matrix_fixed,NRow,NCol > const& C) +vnl_matrix_fixed +vnl_imag(const vnl_matrix_fixed, NRow, NCol> & C) { - vnl_matrix_fixed R; - typename vnl_matrix_fixed,NRow,NCol >::const_iterator cIt = C.begin(); - typename vnl_matrix_fixed::iterator rIt = R.begin(); + vnl_matrix_fixed R; + typename vnl_matrix_fixed, NRow, NCol>::const_iterator cIt = C.begin(); + typename vnl_matrix_fixed::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::imag(*cIt); return R; @@ -78,19 +78,19 @@ vnl_imag(vnl_matrix_fixed,NRow,NCol > const& C) //: Matrix of imaginary parts of vnl_diag_matrix >. // \relatesalso vnl_diag_matrix -template VNL_EXPORT -vnl_diag_matrix -vnl_imag(vnl_diag_matrix > const& C); +template +VNL_EXPORT vnl_diag_matrix +vnl_imag(const vnl_diag_matrix> & C); //: Matrix of imaginary parts of vnl_diag_matrix_fixed >. // \relatesalso vnl_diag_matrix_fixed template -vnl_diag_matrix_fixed -vnl_imag(vnl_diag_matrix_fixed,N > const& C) +vnl_diag_matrix_fixed +vnl_imag(const vnl_diag_matrix_fixed, N> & C) { - vnl_diag_matrix_fixed R; - typename vnl_diag_matrix_fixed,N >::const_iterator cIt = C.begin(); - typename vnl_diag_matrix_fixed::iterator rIt = R.begin(); + vnl_diag_matrix_fixed R; + typename vnl_diag_matrix_fixed, N>::const_iterator cIt = C.begin(); + typename vnl_diag_matrix_fixed::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::imag(*cIt); return R; @@ -98,9 +98,9 @@ vnl_imag(vnl_diag_matrix_fixed,N > const& C) //: Matrix of imaginary parts of vnl_sym_matrix >. // \relatesalso vnl_sym_matrix -template VNL_EXPORT -vnl_sym_matrix -vnl_imag(vnl_sym_matrix > const& C); +template +VNL_EXPORT vnl_sym_matrix +vnl_imag(const vnl_sym_matrix> & C); #endif // vnl_imag_h_ diff --git a/core/vnl/vnl_index_sort.h b/core/vnl/vnl_index_sort.h index c2281b58efd..878bb0f1592 100644 --- a/core/vnl/vnl_index_sort.h +++ b/core/vnl/vnl_index_sort.h @@ -17,9 +17,8 @@ template class vnl_index_sort { - public: - - //: typedefs for vector sorting +public: + //: typedefs for vector sorting typedef vnl_vector SortVectorType; typedef vnl_vector SortVectorIndexType; @@ -28,21 +27,22 @@ class vnl_index_sort typedef vnl_matrix SortMatrixIndexType; //: matrix sort along rows or columns? - enum DirectionType {ByRow, ByColumn} Direction; + enum DirectionType + { + ByRow, + ByColumn + } Direction; //: just sort indices - void vector_sort( - const SortVectorType& values, - SortVectorIndexType& indices) + void + vector_sort(const SortVectorType & values, SortVectorIndexType & indices) { sortIndices(values, indices); } //: sort indices and values - void vector_sort( - const SortVectorType& values, - SortVectorType& sorted_values, - SortVectorIndexType& indices) + void + vector_sort(const SortVectorType & values, SortVectorType & sorted_values, SortVectorIndexType & indices) { vector_sort(values, indices); @@ -51,12 +51,11 @@ class vnl_index_sort } //: sort indices, return sorted values in place - void vector_sort_in_place( - SortVectorType& values, - SortVectorIndexType& indices) + void + vector_sort_in_place(SortVectorType & values, SortVectorIndexType & indices) { vector_sort(values, indices); - SortVectorType tmpValues(values); + const SortVectorType tmpValues(values); // gets values and indices from sorted indices reindexValues(tmpValues, indices, values); @@ -64,11 +63,11 @@ class vnl_index_sort //: matrix sort // specify along rows or columns - void matrix_sort( - DirectionType direction, - const SortMatrixType& values, - SortMatrixType& sorted_values, - SortMatrixIndexType& indices) + void + matrix_sort(DirectionType direction, + const SortMatrixType & values, + SortMatrixType & sorted_values, + SortMatrixIndexType & indices) { sorted_values.set_size(values.rows(), values.cols()); indices.set_size(values.rows(), values.cols()); @@ -76,8 +75,7 @@ class vnl_index_sort SortVectorType valVect; SortVectorType sortedValVect; SortVectorIndexType indVect; - for (unsigned int vIx = 0; - vIx < (direction == ByRow ? values.rows() : values.cols()); vIx++) + for (unsigned int vIx = 0; vIx < (direction == ByRow ? values.rows() : values.cols()); vIx++) { getVector(values, direction, vIx, valVect); vector_sort(valVect, sortedValVect, indVect); @@ -86,14 +84,15 @@ class vnl_index_sort } } - private: +private: //: Implementation class - Do Not Use. // Author - Ian Scott template struct sort_index_compare_functor { - const T *data; - bool operator () (const I &a, const I &b) + const T * data; + bool + operator()(const I & a, const I & b) { return data[a] < data[b]; } @@ -101,35 +100,32 @@ class vnl_index_sort //: sort the indices of a vector // Author - Ian Scott - void sortIndices(const SortVectorType& v, SortVectorIndexType& s) + void + sortIndices(const SortVectorType & v, SortVectorIndexType & s) { sort_index_compare_functor c; c.data = v.data_block(); s.set_size(v.size()); - for (TIndex ix = 0; ix < (TIndex) v.size(); ix++) s[ix] = ix; + for (TIndex ix = 0; ix < (TIndex)v.size(); ix++) + s[ix] = ix; std::sort(s.begin(), s.end(), c); } //: reorder values from sorted indices - void reindexValues( - const SortVectorType& values, - const SortVectorIndexType& indices, - SortVectorType& sorted_values) + void + reindexValues(const SortVectorType & values, const SortVectorIndexType & indices, SortVectorType & sorted_values) { sorted_values.set_size(values.size()); - for (TIndex ix = 0; ix < (TIndex) values.size(); ix++) + for (TIndex ix = 0; ix < (TIndex)values.size(); ix++) sorted_values[ix] = values[indices[ix]]; } //: get specified vector from matrix depending on direction - template - void getVector( - const vnl_matrix& fromMat, - DirectionType direction, - int whichVect, - vnl_vector& toVect) + template + void + getVector(const vnl_matrix & fromMat, DirectionType direction, int whichVect, vnl_vector & toVect) { switch (direction) { @@ -146,12 +142,9 @@ class vnl_index_sort } //: put specified vector to matrix depending on direction - template - void putVector( - const vnl_vector& fromVect, - DirectionType direction, - int whichVect, - vnl_matrix& toMat) + template + void + putVector(const vnl_vector & fromVect, DirectionType direction, int whichVect, vnl_matrix & toMat) { switch (direction) { diff --git a/core/vnl/vnl_int_1x1.h b/core/vnl/vnl_int_1x1.h index f2eecdab0c2..0604acb1325 100644 --- a/core/vnl/vnl_int_1x1.h +++ b/core/vnl/vnl_int_1x1.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_int_1x1; +typedef vnl_matrix_fixed vnl_int_1x1; #endif // vnl_int_1x1_h_ diff --git a/core/vnl/vnl_int_2.h b/core/vnl/vnl_int_2.h index 04cdd3f7f2f..a3d4d375e09 100644 --- a/core/vnl/vnl_int_2.h +++ b/core/vnl/vnl_int_2.h @@ -15,6 +15,6 @@ #include "vnl_T_n.h" //: class vnl_int_2 : a vnl_vector of 2 ints. -vnl_T_n_impl(int,2); +vnl_T_n_impl(int, 2); #endif // vnl_int_2_h_ diff --git a/core/vnl/vnl_int_2x2.h b/core/vnl/vnl_int_2x2.h index d3003fe6e91..deeff4d30d6 100644 --- a/core/vnl/vnl_int_2x2.h +++ b/core/vnl/vnl_int_2x2.h @@ -15,6 +15,6 @@ #include "vnl_matrix_fixed.h" -typedef vnl_matrix_fixed vnl_int_2x2; +typedef vnl_matrix_fixed vnl_int_2x2; #endif // vnl_int_2x2_h_ diff --git a/core/vnl/vnl_int_3.h b/core/vnl/vnl_int_3.h index 5249f32deab..cc7bee1f965 100644 --- a/core/vnl/vnl_int_3.h +++ b/core/vnl/vnl_int_3.h @@ -15,6 +15,6 @@ #include "vnl_T_n.h" //: class vnl_int_3 : a vnl_vector of 3 ints. -vnl_T_n_impl(int,3); +vnl_T_n_impl(int, 3); #endif // vnl_int_3_h_ diff --git a/core/vnl/vnl_int_4.h b/core/vnl/vnl_int_4.h index 1558befbb65..3c0639f1195 100644 --- a/core/vnl/vnl_int_4.h +++ b/core/vnl/vnl_int_4.h @@ -15,6 +15,6 @@ #include "vnl_T_n.h" //: class vnl_int_4 : a vnl_vector of 4 ints. -vnl_T_n_impl(int,4); +vnl_T_n_impl(int, 4); #endif // vnl_int_4_h_ diff --git a/core/vnl/vnl_int_matrix.cxx b/core/vnl/vnl_int_matrix.cxx index a28a70ad280..2d7e142de17 100644 --- a/core/vnl/vnl_int_matrix.cxx +++ b/core/vnl/vnl_int_matrix.cxx @@ -16,8 +16,8 @@ vnl_int_matrix::vnl_int_matrix(const vnl_matrix & d) : Base(d.rows(), d.columns()) { - unsigned m = d.rows(); - unsigned n = d.columns(); + const unsigned m = d.rows(); + const unsigned n = d.columns(); for (unsigned i = 0; i < m; ++i) for (unsigned j = 0; j < n; ++j) @@ -25,7 +25,7 @@ vnl_int_matrix::vnl_int_matrix(const vnl_matrix & d) } //: Load from disk -vnl_int_matrix::vnl_int_matrix(char const * filename) +vnl_int_matrix::vnl_int_matrix(const char * filename) { std::ifstream s(filename); read_ascii(s); diff --git a/core/vnl/vnl_int_matrix.h b/core/vnl/vnl_int_matrix.h index ca1fb652923..0f4512f6790 100644 --- a/core/vnl/vnl_int_matrix.h +++ b/core/vnl/vnl_int_matrix.h @@ -22,15 +22,26 @@ class VNL_EXPORT vnl_int_matrix : public vnl_matrix { typedef vnl_matrix Base; - public: +public: vnl_int_matrix() = default; - vnl_int_matrix(char const* filename); - vnl_int_matrix(unsigned r, unsigned c): Base(r, c) {} - vnl_int_matrix(unsigned r, unsigned c, int fillvalue): Base(r, c, fillvalue) {} - vnl_int_matrix(const vnl_matrix& d); - vnl_int_matrix(const vnl_matrix& d):Base(d) {} - vnl_int_matrix& operator=(const vnl_matrix& d) { Base::operator=(d); return *this; } + vnl_int_matrix(const char * filename); + vnl_int_matrix(unsigned r, unsigned c) + : Base(r, c) + {} + vnl_int_matrix(unsigned r, unsigned c, int fillvalue) + : Base(r, c, fillvalue) + {} + vnl_int_matrix(const vnl_matrix & d); + vnl_int_matrix(const vnl_matrix & d) + : Base(d) + {} + vnl_int_matrix & + operator=(const vnl_matrix & d) + { + Base::operator=(d); + return *this; + } }; #endif // vnl_int_matrix_h_ diff --git a/core/vnl/vnl_integrant_fnct.h b/core/vnl/vnl_integrant_fnct.h index ec78f221e6f..c3ae994fd14 100644 --- a/core/vnl/vnl_integrant_fnct.h +++ b/core/vnl/vnl_integrant_fnct.h @@ -9,11 +9,12 @@ class VNL_EXPORT vnl_integrant_fnct { - public: +public: vnl_integrant_fnct() = default; virtual ~vnl_integrant_fnct() = default; - virtual double f_(double /*x*/) = 0; + virtual double + f_(double /*x*/) = 0; }; #endif diff --git a/core/vnl/vnl_inverse.h b/core/vnl/vnl_inverse.h index 22319e18a1d..83cd9143c9e 100644 --- a/core/vnl/vnl_inverse.h +++ b/core/vnl/vnl_inverse.h @@ -36,9 +36,10 @@ // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_inverse(vnl_matrix_fixed const& m) +vnl_matrix_fixed +vnl_inverse(const vnl_matrix_fixed & m) { - return vnl_matrix_fixed(T(1)/m(0,0)); + return vnl_matrix_fixed(T(1) / m(0, 0)); } //: Calculates inverse of a small vnl_matrix_fixed (not using svd) @@ -53,18 +54,22 @@ vnl_matrix_fixed vnl_inverse(vnl_matrix_fixed const& m) // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_inverse(vnl_matrix_fixed const& m) +vnl_matrix_fixed +vnl_inverse(const vnl_matrix_fixed & m) { T det = vnl_det(m); - if (det==0) { + if (det == 0) + { assert(!"Cannot invert 2x2 matrix with zero determinant"); - return vnl_matrix_fixed(); + return vnl_matrix_fixed(); } - det = T(1)/det; + det = T(1) / det; T d[4]; - d[0] = m(1,1)*det; d[1] = - m(0,1)*det; - d[3] = m(0,0)*det; d[2] = - m(1,0)*det; - return vnl_matrix_fixed(d); + d[0] = m(1, 1) * det; + d[1] = -m(0, 1) * det; + d[3] = m(0, 0) * det; + d[2] = -m(1, 0) * det; + return vnl_matrix_fixed(d); } //: Calculates inverse of a small vnl_matrix_fixed (not using svd) @@ -79,25 +84,27 @@ vnl_matrix_fixed vnl_inverse(vnl_matrix_fixed const& m) // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_inverse(vnl_matrix_fixed const& m) +vnl_matrix_fixed +vnl_inverse(const vnl_matrix_fixed & m) { T det = vnl_det(m); - if (det==0) { + if (det == 0) + { assert(!"Cannot invert 3x3 matrix with zero determinant"); - return vnl_matrix_fixed(); + return vnl_matrix_fixed(); } - det = T(1)/det; + det = T(1) / det; T d[9]; - d[0] = (m(1,1)*m(2,2)-m(1,2)*m(2,1))*det; - d[1] = (m(2,1)*m(0,2)-m(2,2)*m(0,1))*det; - d[2] = (m(0,1)*m(1,2)-m(0,2)*m(1,1))*det; - d[3] = (m(1,2)*m(2,0)-m(1,0)*m(2,2))*det; - d[4] = (m(0,0)*m(2,2)-m(0,2)*m(2,0))*det; - d[5] = (m(1,0)*m(0,2)-m(1,2)*m(0,0))*det; - d[6] = (m(1,0)*m(2,1)-m(1,1)*m(2,0))*det; - d[7] = (m(0,1)*m(2,0)-m(0,0)*m(2,1))*det; - d[8] = (m(0,0)*m(1,1)-m(0,1)*m(1,0))*det; - return vnl_matrix_fixed(d); + d[0] = (m(1, 1) * m(2, 2) - m(1, 2) * m(2, 1)) * det; + d[1] = (m(2, 1) * m(0, 2) - m(2, 2) * m(0, 1)) * det; + d[2] = (m(0, 1) * m(1, 2) - m(0, 2) * m(1, 1)) * det; + d[3] = (m(1, 2) * m(2, 0) - m(1, 0) * m(2, 2)) * det; + d[4] = (m(0, 0) * m(2, 2) - m(0, 2) * m(2, 0)) * det; + d[5] = (m(1, 0) * m(0, 2) - m(1, 2) * m(0, 0)) * det; + d[6] = (m(1, 0) * m(2, 1) - m(1, 1) * m(2, 0)) * det; + d[7] = (m(0, 1) * m(2, 0) - m(0, 0) * m(2, 1)) * det; + d[8] = (m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0)) * det; + return vnl_matrix_fixed(d); } //: Calculates inverse of a small vnl_matrix_fixed (not using svd) @@ -112,48 +119,50 @@ vnl_matrix_fixed vnl_inverse(vnl_matrix_fixed const& m) // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_inverse(vnl_matrix_fixed const& m) +vnl_matrix_fixed +vnl_inverse(const vnl_matrix_fixed & m) { T det = vnl_det(m); - if (det==0) { + if (det == 0) + { assert(!"Cannot invert 4x4 matrix with zero determinant"); - return vnl_matrix_fixed(); + return vnl_matrix_fixed(); } - det = T(1)/det; + det = T(1) / det; T d[16]; - d[0] = m(1,1)*m(2,2)*m(3,3) - m(1,1)*m(2,3)*m(3,2) - m(2,1)*m(1,2)*m(3,3) - + m(2,1)*m(1,3)*m(3,2) + m(3,1)*m(1,2)*m(2,3) - m(3,1)*m(1,3)*m(2,2); - d[1] = -m(0,1)*m(2,2)*m(3,3) + m(0,1)*m(2,3)*m(3,2) + m(2,1)*m(0,2)*m(3,3) - - m(2,1)*m(0,3)*m(3,2) - m(3,1)*m(0,2)*m(2,3) + m(3,1)*m(0,3)*m(2,2); - d[2] = m(0,1)*m(1,2)*m(3,3) - m(0,1)*m(1,3)*m(3,2) - m(1,1)*m(0,2)*m(3,3) - + m(1,1)*m(0,3)*m(3,2) + m(3,1)*m(0,2)*m(1,3) - m(3,1)*m(0,3)*m(1,2); - d[3] = -m(0,1)*m(1,2)*m(2,3) + m(0,1)*m(1,3)*m(2,2) + m(1,1)*m(0,2)*m(2,3) - - m(1,1)*m(0,3)*m(2,2) - m(2,1)*m(0,2)*m(1,3) + m(2,1)*m(0,3)*m(1,2); - d[4] = -m(1,0)*m(2,2)*m(3,3) + m(1,0)*m(2,3)*m(3,2) + m(2,0)*m(1,2)*m(3,3) - - m(2,0)*m(1,3)*m(3,2) - m(3,0)*m(1,2)*m(2,3) + m(3,0)*m(1,3)*m(2,2); - d[5] = m(0,0)*m(2,2)*m(3,3) - m(0,0)*m(2,3)*m(3,2) - m(2,0)*m(0,2)*m(3,3) - + m(2,0)*m(0,3)*m(3,2) + m(3,0)*m(0,2)*m(2,3) - m(3,0)*m(0,3)*m(2,2); - d[6] = -m(0,0)*m(1,2)*m(3,3) + m(0,0)*m(1,3)*m(3,2) + m(1,0)*m(0,2)*m(3,3) - - m(1,0)*m(0,3)*m(3,2) - m(3,0)*m(0,2)*m(1,3) + m(3,0)*m(0,3)*m(1,2); - d[7] = m(0,0)*m(1,2)*m(2,3) - m(0,0)*m(1,3)*m(2,2) - m(1,0)*m(0,2)*m(2,3) - + m(1,0)*m(0,3)*m(2,2) + m(2,0)*m(0,2)*m(1,3) - m(2,0)*m(0,3)*m(1,2); - d[8] = m(1,0)*m(2,1)*m(3,3) - m(1,0)*m(2,3)*m(3,1) - m(2,0)*m(1,1)*m(3,3) - + m(2,0)*m(1,3)*m(3,1) + m(3,0)*m(1,1)*m(2,3) - m(3,0)*m(1,3)*m(2,1); - d[9] = -m(0,0)*m(2,1)*m(3,3) + m(0,0)*m(2,3)*m(3,1) + m(2,0)*m(0,1)*m(3,3) - - m(2,0)*m(0,3)*m(3,1) - m(3,0)*m(0,1)*m(2,3) + m(3,0)*m(0,3)*m(2,1); - d[10]= m(0,0)*m(1,1)*m(3,3) - m(0,0)*m(1,3)*m(3,1) - m(1,0)*m(0,1)*m(3,3) - + m(1,0)*m(0,3)*m(3,1) + m(3,0)*m(0,1)*m(1,3) - m(3,0)*m(0,3)*m(1,1); - d[11]= -m(0,0)*m(1,1)*m(2,3) + m(0,0)*m(1,3)*m(2,1) + m(1,0)*m(0,1)*m(2,3) - - m(1,0)*m(0,3)*m(2,1) - m(2,0)*m(0,1)*m(1,3) + m(2,0)*m(0,3)*m(1,1); - d[12]= -m(1,0)*m(2,1)*m(3,2) + m(1,0)*m(2,2)*m(3,1) + m(2,0)*m(1,1)*m(3,2) - - m(2,0)*m(1,2)*m(3,1) - m(3,0)*m(1,1)*m(2,2) + m(3,0)*m(1,2)*m(2,1); - d[13]= m(0,0)*m(2,1)*m(3,2) - m(0,0)*m(2,2)*m(3,1) - m(2,0)*m(0,1)*m(3,2) - + m(2,0)*m(0,2)*m(3,1) + m(3,0)*m(0,1)*m(2,2) - m(3,0)*m(0,2)*m(2,1); - d[14]= -m(0,0)*m(1,1)*m(3,2) + m(0,0)*m(1,2)*m(3,1) + m(1,0)*m(0,1)*m(3,2) - - m(1,0)*m(0,2)*m(3,1) - m(3,0)*m(0,1)*m(1,2) + m(3,0)*m(0,2)*m(1,1); - d[15]= m(0,0)*m(1,1)*m(2,2) - m(0,0)*m(1,2)*m(2,1) - m(1,0)*m(0,1)*m(2,2) - + m(1,0)*m(0,2)*m(2,1) + m(2,0)*m(0,1)*m(1,2) - m(2,0)*m(0,2)*m(1,1); - return vnl_matrix_fixed(d)*det; + d[0] = m(1, 1) * m(2, 2) * m(3, 3) - m(1, 1) * m(2, 3) * m(3, 2) - m(2, 1) * m(1, 2) * m(3, 3) + + m(2, 1) * m(1, 3) * m(3, 2) + m(3, 1) * m(1, 2) * m(2, 3) - m(3, 1) * m(1, 3) * m(2, 2); + d[1] = -m(0, 1) * m(2, 2) * m(3, 3) + m(0, 1) * m(2, 3) * m(3, 2) + m(2, 1) * m(0, 2) * m(3, 3) - + m(2, 1) * m(0, 3) * m(3, 2) - m(3, 1) * m(0, 2) * m(2, 3) + m(3, 1) * m(0, 3) * m(2, 2); + d[2] = m(0, 1) * m(1, 2) * m(3, 3) - m(0, 1) * m(1, 3) * m(3, 2) - m(1, 1) * m(0, 2) * m(3, 3) + + m(1, 1) * m(0, 3) * m(3, 2) + m(3, 1) * m(0, 2) * m(1, 3) - m(3, 1) * m(0, 3) * m(1, 2); + d[3] = -m(0, 1) * m(1, 2) * m(2, 3) + m(0, 1) * m(1, 3) * m(2, 2) + m(1, 1) * m(0, 2) * m(2, 3) - + m(1, 1) * m(0, 3) * m(2, 2) - m(2, 1) * m(0, 2) * m(1, 3) + m(2, 1) * m(0, 3) * m(1, 2); + d[4] = -m(1, 0) * m(2, 2) * m(3, 3) + m(1, 0) * m(2, 3) * m(3, 2) + m(2, 0) * m(1, 2) * m(3, 3) - + m(2, 0) * m(1, 3) * m(3, 2) - m(3, 0) * m(1, 2) * m(2, 3) + m(3, 0) * m(1, 3) * m(2, 2); + d[5] = m(0, 0) * m(2, 2) * m(3, 3) - m(0, 0) * m(2, 3) * m(3, 2) - m(2, 0) * m(0, 2) * m(3, 3) + + m(2, 0) * m(0, 3) * m(3, 2) + m(3, 0) * m(0, 2) * m(2, 3) - m(3, 0) * m(0, 3) * m(2, 2); + d[6] = -m(0, 0) * m(1, 2) * m(3, 3) + m(0, 0) * m(1, 3) * m(3, 2) + m(1, 0) * m(0, 2) * m(3, 3) - + m(1, 0) * m(0, 3) * m(3, 2) - m(3, 0) * m(0, 2) * m(1, 3) + m(3, 0) * m(0, 3) * m(1, 2); + d[7] = m(0, 0) * m(1, 2) * m(2, 3) - m(0, 0) * m(1, 3) * m(2, 2) - m(1, 0) * m(0, 2) * m(2, 3) + + m(1, 0) * m(0, 3) * m(2, 2) + m(2, 0) * m(0, 2) * m(1, 3) - m(2, 0) * m(0, 3) * m(1, 2); + d[8] = m(1, 0) * m(2, 1) * m(3, 3) - m(1, 0) * m(2, 3) * m(3, 1) - m(2, 0) * m(1, 1) * m(3, 3) + + m(2, 0) * m(1, 3) * m(3, 1) + m(3, 0) * m(1, 1) * m(2, 3) - m(3, 0) * m(1, 3) * m(2, 1); + d[9] = -m(0, 0) * m(2, 1) * m(3, 3) + m(0, 0) * m(2, 3) * m(3, 1) + m(2, 0) * m(0, 1) * m(3, 3) - + m(2, 0) * m(0, 3) * m(3, 1) - m(3, 0) * m(0, 1) * m(2, 3) + m(3, 0) * m(0, 3) * m(2, 1); + d[10] = m(0, 0) * m(1, 1) * m(3, 3) - m(0, 0) * m(1, 3) * m(3, 1) - m(1, 0) * m(0, 1) * m(3, 3) + + m(1, 0) * m(0, 3) * m(3, 1) + m(3, 0) * m(0, 1) * m(1, 3) - m(3, 0) * m(0, 3) * m(1, 1); + d[11] = -m(0, 0) * m(1, 1) * m(2, 3) + m(0, 0) * m(1, 3) * m(2, 1) + m(1, 0) * m(0, 1) * m(2, 3) - + m(1, 0) * m(0, 3) * m(2, 1) - m(2, 0) * m(0, 1) * m(1, 3) + m(2, 0) * m(0, 3) * m(1, 1); + d[12] = -m(1, 0) * m(2, 1) * m(3, 2) + m(1, 0) * m(2, 2) * m(3, 1) + m(2, 0) * m(1, 1) * m(3, 2) - + m(2, 0) * m(1, 2) * m(3, 1) - m(3, 0) * m(1, 1) * m(2, 2) + m(3, 0) * m(1, 2) * m(2, 1); + d[13] = m(0, 0) * m(2, 1) * m(3, 2) - m(0, 0) * m(2, 2) * m(3, 1) - m(2, 0) * m(0, 1) * m(3, 2) + + m(2, 0) * m(0, 2) * m(3, 1) + m(3, 0) * m(0, 1) * m(2, 2) - m(3, 0) * m(0, 2) * m(2, 1); + d[14] = -m(0, 0) * m(1, 1) * m(3, 2) + m(0, 0) * m(1, 2) * m(3, 1) + m(1, 0) * m(0, 1) * m(3, 2) - + m(1, 0) * m(0, 2) * m(3, 1) - m(3, 0) * m(0, 1) * m(1, 2) + m(3, 0) * m(0, 2) * m(1, 1); + d[15] = m(0, 0) * m(1, 1) * m(2, 2) - m(0, 0) * m(1, 2) * m(2, 1) - m(1, 0) * m(0, 1) * m(2, 2) + + m(1, 0) * m(0, 2) * m(2, 1) + m(2, 0) * m(0, 1) * m(1, 2) - m(2, 0) * m(0, 2) * m(1, 1); + return vnl_matrix_fixed(d) * det; } //: Calculates inverse of a small vnl_matrix_fixed (not using svd) @@ -168,18 +177,19 @@ vnl_matrix_fixed vnl_inverse(vnl_matrix_fixed const& m) // \relatesalso vnl_matrix template -vnl_matrix vnl_inverse(vnl_matrix const& m) +vnl_matrix +vnl_inverse(const vnl_matrix & m) { assert(m.rows() == m.columns()); assert(m.rows() <= 4); if (m.rows() == 1) - return vnl_matrix(1,1, T(1)/m(0,0)); + return vnl_matrix(1, 1, T(1) / m(0, 0)); else if (m.rows() == 2) - return vnl_inverse(vnl_matrix_fixed(m)).as_matrix(); + return vnl_inverse(vnl_matrix_fixed(m)).as_matrix(); else if (m.rows() == 3) - return vnl_inverse(vnl_matrix_fixed(m)).as_matrix(); + return vnl_inverse(vnl_matrix_fixed(m)).as_matrix(); else - return vnl_inverse(vnl_matrix_fixed(m)).as_matrix(); + return vnl_inverse(vnl_matrix_fixed(m)).as_matrix(); } //: Calculates transpose of the inverse of a small vnl_matrix_fixed (not using svd) @@ -196,9 +206,10 @@ vnl_matrix vnl_inverse(vnl_matrix const& m) // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_inverse_transpose(vnl_matrix_fixed const& m) +vnl_matrix_fixed +vnl_inverse_transpose(const vnl_matrix_fixed & m) { - return vnl_matrix_fixed(T(1)/m(0,0)); + return vnl_matrix_fixed(T(1) / m(0, 0)); } //: Calculates transpose of the inverse of a small vnl_matrix_fixed (not using svd) @@ -215,18 +226,22 @@ vnl_matrix_fixed vnl_inverse_transpose(vnl_matrix_fixed const& m) // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_inverse_transpose(vnl_matrix_fixed const& m) +vnl_matrix_fixed +vnl_inverse_transpose(const vnl_matrix_fixed & m) { T det = vnl_det(m); - if (det==0) { + if (det == 0) + { assert(!"Cannot invert 2x2 matrix with zero determinant"); - return vnl_matrix_fixed(); + return vnl_matrix_fixed(); } - det = T(1)/det; + det = T(1) / det; T d[4]; - d[0] = m(1,1)*det; d[2] = - m(0,1)*det; - d[3] = m(0,0)*det; d[1] = - m(1,0)*det; - return vnl_matrix_fixed(d); + d[0] = m(1, 1) * det; + d[2] = -m(0, 1) * det; + d[3] = m(0, 0) * det; + d[1] = -m(1, 0) * det; + return vnl_matrix_fixed(d); } //: Calculates transpose of the inverse of a small vnl_matrix_fixed (not using svd) @@ -243,25 +258,27 @@ vnl_matrix_fixed vnl_inverse_transpose(vnl_matrix_fixed const& m) // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_inverse_transpose(vnl_matrix_fixed const& m) +vnl_matrix_fixed +vnl_inverse_transpose(const vnl_matrix_fixed & m) { T det = vnl_det(m); - if (det==0) { + if (det == 0) + { assert(!"Cannot invert 3x3 matrix with zero determinant"); - return vnl_matrix_fixed(); + return vnl_matrix_fixed(); } - det = T(1)/det; + det = T(1) / det; T d[9]; - d[0] = (m(1,1)*m(2,2)-m(1,2)*m(2,1))*det; - d[3] = (m(2,1)*m(0,2)-m(2,2)*m(0,1))*det; - d[6] = (m(0,1)*m(1,2)-m(0,2)*m(1,1))*det; - d[1] = (m(1,2)*m(2,0)-m(1,0)*m(2,2))*det; - d[4] = (m(0,0)*m(2,2)-m(0,2)*m(2,0))*det; - d[7] = (m(1,0)*m(0,2)-m(1,2)*m(0,0))*det; - d[2] = (m(1,0)*m(2,1)-m(1,1)*m(2,0))*det; - d[5] = (m(0,1)*m(2,0)-m(0,0)*m(2,1))*det; - d[8] = (m(0,0)*m(1,1)-m(0,1)*m(1,0))*det; - return vnl_matrix_fixed(d); + d[0] = (m(1, 1) * m(2, 2) - m(1, 2) * m(2, 1)) * det; + d[3] = (m(2, 1) * m(0, 2) - m(2, 2) * m(0, 1)) * det; + d[6] = (m(0, 1) * m(1, 2) - m(0, 2) * m(1, 1)) * det; + d[1] = (m(1, 2) * m(2, 0) - m(1, 0) * m(2, 2)) * det; + d[4] = (m(0, 0) * m(2, 2) - m(0, 2) * m(2, 0)) * det; + d[7] = (m(1, 0) * m(0, 2) - m(1, 2) * m(0, 0)) * det; + d[2] = (m(1, 0) * m(2, 1) - m(1, 1) * m(2, 0)) * det; + d[5] = (m(0, 1) * m(2, 0) - m(0, 0) * m(2, 1)) * det; + d[8] = (m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0)) * det; + return vnl_matrix_fixed(d); } //: Calculates transpose of the inverse of a small vnl_matrix_fixed (not using svd) @@ -278,48 +295,50 @@ vnl_matrix_fixed vnl_inverse_transpose(vnl_matrix_fixed const& m) // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_inverse_transpose(vnl_matrix_fixed const& m) +vnl_matrix_fixed +vnl_inverse_transpose(const vnl_matrix_fixed & m) { T det = vnl_det(m); - if (det==0) { + if (det == 0) + { assert(!"Cannot invert 4x4 matrix with zero determinant"); - return vnl_matrix_fixed(); + return vnl_matrix_fixed(); } - det = T(1)/det; + det = T(1) / det; T d[16]; - d[0] = m(1,1)*m(2,2)*m(3,3) - m(1,1)*m(2,3)*m(3,2) - m(2,1)*m(1,2)*m(3,3) - + m(2,1)*m(1,3)*m(3,2) + m(3,1)*m(1,2)*m(2,3) - m(3,1)*m(1,3)*m(2,2); - d[4] = -m(0,1)*m(2,2)*m(3,3) + m(0,1)*m(2,3)*m(3,2) + m(2,1)*m(0,2)*m(3,3) - - m(2,1)*m(0,3)*m(3,2) - m(3,1)*m(0,2)*m(2,3) + m(3,1)*m(0,3)*m(2,2); - d[8] = m(0,1)*m(1,2)*m(3,3) - m(0,1)*m(1,3)*m(3,2) - m(1,1)*m(0,2)*m(3,3) - + m(1,1)*m(0,3)*m(3,2) + m(3,1)*m(0,2)*m(1,3) - m(3,1)*m(0,3)*m(1,2); - d[12]= -m(0,1)*m(1,2)*m(2,3) + m(0,1)*m(1,3)*m(2,2) + m(1,1)*m(0,2)*m(2,3) - - m(1,1)*m(0,3)*m(2,2) - m(2,1)*m(0,2)*m(1,3) + m(2,1)*m(0,3)*m(1,2); - d[1] = -m(1,0)*m(2,2)*m(3,3) + m(1,0)*m(2,3)*m(3,2) + m(2,0)*m(1,2)*m(3,3) - - m(2,0)*m(1,3)*m(3,2) - m(3,0)*m(1,2)*m(2,3) + m(3,0)*m(1,3)*m(2,2); - d[5] = m(0,0)*m(2,2)*m(3,3) - m(0,0)*m(2,3)*m(3,2) - m(2,0)*m(0,2)*m(3,3) - + m(2,0)*m(0,3)*m(3,2) + m(3,0)*m(0,2)*m(2,3) - m(3,0)*m(0,3)*m(2,2); - d[9] = -m(0,0)*m(1,2)*m(3,3) + m(0,0)*m(1,3)*m(3,2) + m(1,0)*m(0,2)*m(3,3) - - m(1,0)*m(0,3)*m(3,2) - m(3,0)*m(0,2)*m(1,3) + m(3,0)*m(0,3)*m(1,2); - d[13]= m(0,0)*m(1,2)*m(2,3) - m(0,0)*m(1,3)*m(2,2) - m(1,0)*m(0,2)*m(2,3) - + m(1,0)*m(0,3)*m(2,2) + m(2,0)*m(0,2)*m(1,3) - m(2,0)*m(0,3)*m(1,2); - d[2] = m(1,0)*m(2,1)*m(3,3) - m(1,0)*m(2,3)*m(3,1) - m(2,0)*m(1,1)*m(3,3) - + m(2,0)*m(1,3)*m(3,1) + m(3,0)*m(1,1)*m(2,3) - m(3,0)*m(1,3)*m(2,1); - d[6] = -m(0,0)*m(2,1)*m(3,3) + m(0,0)*m(2,3)*m(3,1) + m(2,0)*m(0,1)*m(3,3) - - m(2,0)*m(0,3)*m(3,1) - m(3,0)*m(0,1)*m(2,3) + m(3,0)*m(0,3)*m(2,1); - d[10]= m(0,0)*m(1,1)*m(3,3) - m(0,0)*m(1,3)*m(3,1) - m(1,0)*m(0,1)*m(3,3) - + m(1,0)*m(0,3)*m(3,1) + m(3,0)*m(0,1)*m(1,3) - m(3,0)*m(0,3)*m(1,1); - d[14]= -m(0,0)*m(1,1)*m(2,3) + m(0,0)*m(1,3)*m(2,1) + m(1,0)*m(0,1)*m(2,3) - - m(1,0)*m(0,3)*m(2,1) - m(2,0)*m(0,1)*m(1,3) + m(2,0)*m(0,3)*m(1,1); - d[3] = -m(1,0)*m(2,1)*m(3,2) + m(1,0)*m(2,2)*m(3,1) + m(2,0)*m(1,1)*m(3,2) - - m(2,0)*m(1,2)*m(3,1) - m(3,0)*m(1,1)*m(2,2) + m(3,0)*m(1,2)*m(2,1); - d[7] = m(0,0)*m(2,1)*m(3,2) - m(0,0)*m(2,2)*m(3,1) - m(2,0)*m(0,1)*m(3,2) - + m(2,0)*m(0,2)*m(3,1) + m(3,0)*m(0,1)*m(2,2) - m(3,0)*m(0,2)*m(2,1); - d[11]= -m(0,0)*m(1,1)*m(3,2) + m(0,0)*m(1,2)*m(3,1) + m(1,0)*m(0,1)*m(3,2) - - m(1,0)*m(0,2)*m(3,1) - m(3,0)*m(0,1)*m(1,2) + m(3,0)*m(0,2)*m(1,1); - d[15]= m(0,0)*m(1,1)*m(2,2) - m(0,0)*m(1,2)*m(2,1) - m(1,0)*m(0,1)*m(2,2) - + m(1,0)*m(0,2)*m(2,1) + m(2,0)*m(0,1)*m(1,2) - m(2,0)*m(0,2)*m(1,1); - return vnl_matrix_fixed(d)*det; + d[0] = m(1, 1) * m(2, 2) * m(3, 3) - m(1, 1) * m(2, 3) * m(3, 2) - m(2, 1) * m(1, 2) * m(3, 3) + + m(2, 1) * m(1, 3) * m(3, 2) + m(3, 1) * m(1, 2) * m(2, 3) - m(3, 1) * m(1, 3) * m(2, 2); + d[4] = -m(0, 1) * m(2, 2) * m(3, 3) + m(0, 1) * m(2, 3) * m(3, 2) + m(2, 1) * m(0, 2) * m(3, 3) - + m(2, 1) * m(0, 3) * m(3, 2) - m(3, 1) * m(0, 2) * m(2, 3) + m(3, 1) * m(0, 3) * m(2, 2); + d[8] = m(0, 1) * m(1, 2) * m(3, 3) - m(0, 1) * m(1, 3) * m(3, 2) - m(1, 1) * m(0, 2) * m(3, 3) + + m(1, 1) * m(0, 3) * m(3, 2) + m(3, 1) * m(0, 2) * m(1, 3) - m(3, 1) * m(0, 3) * m(1, 2); + d[12] = -m(0, 1) * m(1, 2) * m(2, 3) + m(0, 1) * m(1, 3) * m(2, 2) + m(1, 1) * m(0, 2) * m(2, 3) - + m(1, 1) * m(0, 3) * m(2, 2) - m(2, 1) * m(0, 2) * m(1, 3) + m(2, 1) * m(0, 3) * m(1, 2); + d[1] = -m(1, 0) * m(2, 2) * m(3, 3) + m(1, 0) * m(2, 3) * m(3, 2) + m(2, 0) * m(1, 2) * m(3, 3) - + m(2, 0) * m(1, 3) * m(3, 2) - m(3, 0) * m(1, 2) * m(2, 3) + m(3, 0) * m(1, 3) * m(2, 2); + d[5] = m(0, 0) * m(2, 2) * m(3, 3) - m(0, 0) * m(2, 3) * m(3, 2) - m(2, 0) * m(0, 2) * m(3, 3) + + m(2, 0) * m(0, 3) * m(3, 2) + m(3, 0) * m(0, 2) * m(2, 3) - m(3, 0) * m(0, 3) * m(2, 2); + d[9] = -m(0, 0) * m(1, 2) * m(3, 3) + m(0, 0) * m(1, 3) * m(3, 2) + m(1, 0) * m(0, 2) * m(3, 3) - + m(1, 0) * m(0, 3) * m(3, 2) - m(3, 0) * m(0, 2) * m(1, 3) + m(3, 0) * m(0, 3) * m(1, 2); + d[13] = m(0, 0) * m(1, 2) * m(2, 3) - m(0, 0) * m(1, 3) * m(2, 2) - m(1, 0) * m(0, 2) * m(2, 3) + + m(1, 0) * m(0, 3) * m(2, 2) + m(2, 0) * m(0, 2) * m(1, 3) - m(2, 0) * m(0, 3) * m(1, 2); + d[2] = m(1, 0) * m(2, 1) * m(3, 3) - m(1, 0) * m(2, 3) * m(3, 1) - m(2, 0) * m(1, 1) * m(3, 3) + + m(2, 0) * m(1, 3) * m(3, 1) + m(3, 0) * m(1, 1) * m(2, 3) - m(3, 0) * m(1, 3) * m(2, 1); + d[6] = -m(0, 0) * m(2, 1) * m(3, 3) + m(0, 0) * m(2, 3) * m(3, 1) + m(2, 0) * m(0, 1) * m(3, 3) - + m(2, 0) * m(0, 3) * m(3, 1) - m(3, 0) * m(0, 1) * m(2, 3) + m(3, 0) * m(0, 3) * m(2, 1); + d[10] = m(0, 0) * m(1, 1) * m(3, 3) - m(0, 0) * m(1, 3) * m(3, 1) - m(1, 0) * m(0, 1) * m(3, 3) + + m(1, 0) * m(0, 3) * m(3, 1) + m(3, 0) * m(0, 1) * m(1, 3) - m(3, 0) * m(0, 3) * m(1, 1); + d[14] = -m(0, 0) * m(1, 1) * m(2, 3) + m(0, 0) * m(1, 3) * m(2, 1) + m(1, 0) * m(0, 1) * m(2, 3) - + m(1, 0) * m(0, 3) * m(2, 1) - m(2, 0) * m(0, 1) * m(1, 3) + m(2, 0) * m(0, 3) * m(1, 1); + d[3] = -m(1, 0) * m(2, 1) * m(3, 2) + m(1, 0) * m(2, 2) * m(3, 1) + m(2, 0) * m(1, 1) * m(3, 2) - + m(2, 0) * m(1, 2) * m(3, 1) - m(3, 0) * m(1, 1) * m(2, 2) + m(3, 0) * m(1, 2) * m(2, 1); + d[7] = m(0, 0) * m(2, 1) * m(3, 2) - m(0, 0) * m(2, 2) * m(3, 1) - m(2, 0) * m(0, 1) * m(3, 2) + + m(2, 0) * m(0, 2) * m(3, 1) + m(3, 0) * m(0, 1) * m(2, 2) - m(3, 0) * m(0, 2) * m(2, 1); + d[11] = -m(0, 0) * m(1, 1) * m(3, 2) + m(0, 0) * m(1, 2) * m(3, 1) + m(1, 0) * m(0, 1) * m(3, 2) - + m(1, 0) * m(0, 2) * m(3, 1) - m(3, 0) * m(0, 1) * m(1, 2) + m(3, 0) * m(0, 2) * m(1, 1); + d[15] = m(0, 0) * m(1, 1) * m(2, 2) - m(0, 0) * m(1, 2) * m(2, 1) - m(1, 0) * m(0, 1) * m(2, 2) + + m(1, 0) * m(0, 2) * m(2, 1) + m(2, 0) * m(0, 1) * m(1, 2) - m(2, 0) * m(0, 2) * m(1, 1); + return vnl_matrix_fixed(d) * det; } //: Calculates transpose of the inverse of a small vnl_matrix_fixed (not using svd) @@ -335,18 +354,19 @@ vnl_matrix_fixed vnl_inverse_transpose(vnl_matrix_fixed const& m) // // \relatesalso vnl_matrix template -vnl_matrix vnl_inverse_transpose(vnl_matrix const& m) +vnl_matrix +vnl_inverse_transpose(const vnl_matrix & m) { assert(m.rows() == m.columns()); assert(m.rows() <= 4); if (m.rows() == 1) - return vnl_matrix(1,1, T(1)/m(0,0)); + return vnl_matrix(1, 1, T(1) / m(0, 0)); else if (m.rows() == 2) - return vnl_inverse_transpose(vnl_matrix_fixed(m)).as_matrix(); + return vnl_inverse_transpose(vnl_matrix_fixed(m)).as_matrix(); else if (m.rows() == 3) - return vnl_inverse_transpose(vnl_matrix_fixed(m)).as_matrix(); + return vnl_inverse_transpose(vnl_matrix_fixed(m)).as_matrix(); else - return vnl_inverse_transpose(vnl_matrix_fixed(m)).as_matrix(); + return vnl_inverse_transpose(vnl_matrix_fixed(m)).as_matrix(); } #endif // vnl_inverse_h_ diff --git a/core/vnl/vnl_least_squares_cost_function.h b/core/vnl/vnl_least_squares_cost_function.h index ab72f45d69c..cd349242a52 100644 --- a/core/vnl/vnl_least_squares_cost_function.h +++ b/core/vnl/vnl_least_squares_cost_function.h @@ -22,17 +22,19 @@ //: An adaptor that converts a vnl_least_squares_function to a vnl_cost_function class VNL_EXPORT vnl_least_squares_cost_function : public vnl_cost_function { - public: - vnl_least_squares_cost_function(vnl_least_squares_function* f); +public: + vnl_least_squares_cost_function(vnl_least_squares_function * f); - double f(const vnl_vector& x) override; + double + f(const vnl_vector & x) override; - void gradf(const vnl_vector& x, vnl_vector& gradient) override; + void + gradf(const vnl_vector & x, vnl_vector & gradient) override; - protected: +protected: vnl_vector storage_; vnl_matrix jacobian_; - vnl_least_squares_function* f_; + vnl_least_squares_function * f_; }; #endif // vnl_least_squares_cost_function_h_ diff --git a/core/vnl/vnl_least_squares_function.cxx b/core/vnl/vnl_least_squares_function.cxx index 4620a6bdeb5..f552a4efe3c 100644 --- a/core/vnl/vnl_least_squares_function.cxx +++ b/core/vnl/vnl_least_squares_function.cxx @@ -18,17 +18,17 @@ vnl_least_squares_function::dim_warning(unsigned int number_of_unknowns, unsigne } void -vnl_least_squares_function::gradf(vnl_vector const & /*x*/, vnl_matrix & /*jacobian*/) +vnl_least_squares_function::gradf(const vnl_vector & /*x*/, vnl_matrix & /*jacobian*/) { std::cerr << "Warning: gradf() called but not implemented in derived class\n"; } //: Compute finite differences gradient using central differences. void -vnl_least_squares_function::fdgradf(vnl_vector const & x, vnl_matrix & jacobian, double stepsize) +vnl_least_squares_function::fdgradf(const vnl_vector & x, vnl_matrix & jacobian, double stepsize) { - unsigned int dim = x.size(); - unsigned int n = jacobian.rows(); + const unsigned int dim = x.size(); + const unsigned int n = jacobian.rows(); assert(dim == get_number_of_unknowns()); assert(n == get_number_of_residuals()); assert(dim == jacobian.columns()); @@ -39,14 +39,14 @@ vnl_least_squares_function::fdgradf(vnl_vector const & x, vnl_matrixf(tx, fplus); // calculate f just to the left of x[i] - double tminus = tx[i] = x[i] - stepsize; + const double tminus = tx[i] = x[i] - stepsize; this->f(tx, fminus); - double h = 1.0 / (tplus - tminus); + const double h = 1.0 / (tplus - tminus); for (unsigned int j = 0; j < n; ++j) jacobian(j, i) = (fplus[j] - fminus[j]) * h; @@ -58,10 +58,10 @@ vnl_least_squares_function::fdgradf(vnl_vector const & x, vnl_matrix const & x, vnl_matrix & jacobian, double stepsize) +vnl_least_squares_function::ffdgradf(const vnl_vector & x, vnl_matrix & jacobian, double stepsize) { - unsigned int dim = x.size(); - unsigned int n = jacobian.rows(); + const unsigned int dim = x.size(); + const unsigned int n = jacobian.rows(); assert(dim == get_number_of_unknowns()); assert(n == get_number_of_residuals()); assert(dim == jacobian.columns()); @@ -73,10 +73,10 @@ vnl_least_squares_function::ffdgradf(vnl_vector const & x, vnl_matrixf(tx, fplus); - double h = 1.0 / (tplus - x[i]); + const double h = 1.0 / (tplus - x[i]); for (unsigned int j = 0; j < n; ++j) jacobian(j, i) = (fplus[j] - fcentre[j]) * h; @@ -87,14 +87,14 @@ vnl_least_squares_function::ffdgradf(vnl_vector const & x, vnl_matrix const & /*x*/, - vnl_vector const & /*fx*/) + const vnl_vector & /*x*/, + const vnl_vector & /*fx*/) { // This default implementation is empty; overloaded in derived class. } double -vnl_least_squares_function::rms(vnl_vector const & x) +vnl_least_squares_function::rms(const vnl_vector & x) { vnl_vector fx(n_); f(x, fx); diff --git a/core/vnl/vnl_least_squares_function.h b/core/vnl/vnl_least_squares_function.h index eda66686a76..9c92408ecc7 100644 --- a/core/vnl/vnl_least_squares_function.h +++ b/core/vnl/vnl_least_squares_function.h @@ -34,12 +34,13 @@ // computation. For the moment it's non-const, but we'll see... class VNL_EXPORT vnl_least_squares_function { - public: - enum UseGradient { +public: + enum UseGradient + { no_gradient, use_gradient }; - bool failure; + bool failure{ false }; //: Construct vnl_least_squares_function. // Passing number of parameters (unknowns, domain dimension) and number of @@ -49,59 +50,91 @@ class VNL_EXPORT vnl_least_squares_function vnl_least_squares_function(unsigned int number_of_unknowns, unsigned int number_of_residuals, UseGradient g = use_gradient) - : failure(false), p_(number_of_unknowns), n_(number_of_residuals), - use_gradient_(g == use_gradient) - { dim_warning(p_,n_); } + : p_(number_of_unknowns) + , n_(number_of_residuals) + , use_gradient_(g == use_gradient) + { + dim_warning(p_, n_); + } virtual ~vnl_least_squares_function() = default; // the virtuals may call this to signal a failure. - void throw_failure() { failure = true; } - void clear_failure() { failure = false; } + void + throw_failure() + { + failure = true; + } + void + clear_failure() + { + failure = false; + } //: The main function. // Given the parameter vector x, compute the vector of residuals fx. // Fx has been sized appropriately before the call. - virtual void f(vnl_vector const& x, vnl_vector& fx) = 0; + virtual void + f(const vnl_vector & x, vnl_vector & fx) = 0; //: Calculate the Jacobian, given the parameter vector x. - virtual void gradf(vnl_vector const& x, vnl_matrix& jacobian); + virtual void + gradf(const vnl_vector & x, vnl_matrix & jacobian); //: Use this to compute a finite-difference gradient other than lmdif - void fdgradf(vnl_vector const& x, vnl_matrix& jacobian, - double stepsize); + void + fdgradf(const vnl_vector & x, vnl_matrix & jacobian, double stepsize); //: Use this to compute a finite-forward-difference gradient other than lmdif // This takes about half as many estimates as fdgradf - void ffdgradf(vnl_vector const& x, vnl_matrix& jacobian, - double stepsize); + void + ffdgradf(const vnl_vector & x, vnl_matrix & jacobian, double stepsize); //: Called after each LM iteration to print debugging etc. - virtual void trace(int iteration, - vnl_vector const& x, - vnl_vector const& fx); + virtual void + trace(int iteration, const vnl_vector & x, const vnl_vector & fx); //: Compute the rms error at x by calling f and returning the norm of the residual vector. - double rms(vnl_vector const& x); + double + rms(const vnl_vector & x); //: Return the number of unknowns - unsigned int get_number_of_unknowns() const { return p_; } + unsigned int + get_number_of_unknowns() const + { + return p_; + } //: Return the number of residuals. - unsigned int get_number_of_residuals() const { return n_; } + unsigned int + get_number_of_residuals() const + { + return n_; + } //: Return true if the derived class has indicated that gradf has been implemented - bool has_gradient() const { return use_gradient_; } + bool + has_gradient() const + { + return use_gradient_; + } - protected: +protected: unsigned int p_; unsigned int n_; bool use_gradient_; - void init(unsigned int number_of_unknowns, unsigned int number_of_residuals) - { p_ = number_of_unknowns; n_ = number_of_residuals; dim_warning(p_,n_); } - private: - void dim_warning(unsigned int n_unknowns, unsigned int n_residuals); + void + init(unsigned int number_of_unknowns, unsigned int number_of_residuals) + { + p_ = number_of_unknowns; + n_ = number_of_residuals; + dim_warning(p_, n_); + } + +private: + void + dim_warning(unsigned int n_unknowns, unsigned int n_residuals); }; #endif // vnl_least_squares_function_h_ diff --git a/core/vnl/vnl_linear_operators_3.h b/core/vnl/vnl_linear_operators_3.h index 2c02380f55f..99d8e10833d 100644 --- a/core/vnl/vnl_linear_operators_3.h +++ b/core/vnl/vnl_linear_operators_3.h @@ -22,25 +22,25 @@ //: The binary multiplication operator // \relatesalso vnl_matrix_fixed -inline -vnl_double_3 operator* (const vnl_double_3x3& A, const vnl_double_3& x) +inline vnl_double_3 +operator*(const vnl_double_3x3 & A, const vnl_double_3 & x) { - const double* a = A.data_block(); + const double * a = A.data_block(); double r0 = a[0] * x[0] + a[1] * x[1] + a[2] * x[2]; double r1 = a[3] * x[0] + a[4] * x[1] + a[5] * x[2]; double r2 = a[6] * x[0] + a[7] * x[1] + a[8] * x[2]; - return {r0, r1, r2}; + return { r0, r1, r2 }; } //: The binary addition operator // \relatesalso vnl_vector_fixed -inline -vnl_double_3 operator+ (const vnl_double_3& a, const vnl_double_3& b) +inline vnl_double_3 +operator+(const vnl_double_3 & a, const vnl_double_3 & b) { double r0 = a[0] + b[0]; double r1 = a[1] + b[1]; double r2 = a[2] + b[2]; - return {r0, r1, r2}; + return { r0, r1, r2 }; } #endif // vnl_linear_operators_3_h_ diff --git a/core/vnl/vnl_linear_system.cxx b/core/vnl/vnl_linear_system.cxx index 7638d43ca2f..e6821f36f01 100644 --- a/core/vnl/vnl_linear_system.cxx +++ b/core/vnl/vnl_linear_system.cxx @@ -10,7 +10,7 @@ vnl_linear_system::~vnl_linear_system() = default; void -vnl_linear_system::apply_preconditioner(vnl_vector const & x, vnl_vector & px) const +vnl_linear_system::apply_preconditioner(const vnl_vector & x, vnl_vector & px) const { assert(px.size() == x.size()); @@ -18,7 +18,7 @@ vnl_linear_system::apply_preconditioner(vnl_vector const & x, vnl_vector } double -vnl_linear_system::get_rms_error(vnl_vector const & x) const +vnl_linear_system::get_rms_error(const vnl_vector & x) const { vnl_vector resid(n_); vnl_vector b(n_); @@ -32,7 +32,7 @@ vnl_linear_system::get_rms_error(vnl_vector const & x) const } double -vnl_linear_system::get_relative_residual(vnl_vector const & x) const +vnl_linear_system::get_relative_residual(const vnl_vector & x) const { vnl_vector resid(n_); vnl_vector b(n_); diff --git a/core/vnl/vnl_linear_system.h b/core/vnl/vnl_linear_system.h index 8e90ed987aa..ad38d312196 100644 --- a/core/vnl/vnl_linear_system.h +++ b/core/vnl/vnl_linear_system.h @@ -26,42 +26,57 @@ // To solve the system, use an algorithm like vnl_lsqr. class VNL_EXPORT vnl_linear_system { - public: - - vnl_linear_system(unsigned int number_of_unknowns, unsigned int number_of_residuals) : - p_(number_of_unknowns), n_(number_of_residuals) {} +public: + vnl_linear_system(unsigned int number_of_unknowns, unsigned int number_of_residuals) + : p_(number_of_unknowns) + , n_(number_of_residuals) + {} virtual ~vnl_linear_system(); //: Compute A*x, putting result in y - virtual void multiply(vnl_vector const& x, vnl_vector& y) const = 0; + virtual void + multiply(const vnl_vector & x, vnl_vector & y) const = 0; //: Compute A_transpose * y, putting result in x - virtual void transpose_multiply(vnl_vector const& y, vnl_vector& x) const = 0; + virtual void + transpose_multiply(const vnl_vector & y, vnl_vector & x) const = 0; //; Put the right-hand side of the system Ax = b into b - virtual void get_rhs(vnl_vector& b) const = 0; + virtual void + get_rhs(vnl_vector & b) const = 0; //; (Optional) Apply a suitable preconditioner to x. // A preconditioner is an approximation of the inverse of A. // Common choices are Jacobi (1/diag(A'A)), Gauss-Seidel, // and incomplete LU or Cholesky decompositions. // The default implementation applies the identity. - virtual void apply_preconditioner(vnl_vector const& x, vnl_vector& px) const; + virtual void + apply_preconditioner(const vnl_vector & x, vnl_vector & px) const; //: Return the number of unknowns - unsigned int get_number_of_unknowns() const { return p_; } + unsigned int + get_number_of_unknowns() const + { + return p_; + } //: Return the number of residuals. - unsigned int get_number_of_residuals() const { return n_; } + unsigned int + get_number_of_residuals() const + { + return n_; + } //: Compute rms error for parameter vector x - double get_rms_error(vnl_vector const& x) const; + double + get_rms_error(const vnl_vector & x) const; //: Compute relative residual (|Ax - b| / |b| )for parameter vector x - double get_relative_residual(vnl_vector const& x) const; + double + get_relative_residual(const vnl_vector & x) const; - protected: +protected: unsigned int p_; unsigned int n_; }; diff --git a/core/vnl/vnl_math.cxx b/core/vnl/vnl_math.cxx index ceeef248d45..3016aea8bad 100644 --- a/core/vnl/vnl_math.cxx +++ b/core/vnl/vnl_math.cxx @@ -65,7 +65,7 @@ angle_0_to_2pi(double angle) angle = std::fmod(angle, vnl_math::twopi); if (angle >= 0) return angle; - double a = angle + vnl_math::twopi; + const double a = angle + vnl_math::twopi; if (a > 0 && a < vnl_math::twopi) return a; // added by Nhon: this fixes a bug when angle >= -1.1721201390607859e-016 : diff --git a/core/vnl/vnl_math.h b/core/vnl/vnl_math.h index 095bfd746d7..e8fcb4895e8 100644 --- a/core/vnl/vnl_math.h +++ b/core/vnl/vnl_math.h @@ -45,45 +45,52 @@ #include // for VNL_CONFIG_ENABLE_SSE2_ROUNDING #include #ifdef VNL_CHECK_FPU_ROUNDING_MODE -#include +# include #endif // Figure out when the fast implementation can be used #if VNL_CONFIG_ENABLE_SSE2_ROUNDING && defined(__SSE2__) -# if !VXL_HAS_EMMINTRIN_H -# error "Required file emmintrin.h for SSE2 not found" -# else -# include // sse 2 intrinsics -# define USE_SSE2_IMPL 1 -# endif +# if !VXL_HAS_EMMINTRIN_H +# error "Required file emmintrin.h for SSE2 not found" +# else +# include // sse 2 intrinsics +# define USE_SSE2_IMPL 1 +# endif #else -# define USE_SSE2_IMPL 0 +# define USE_SSE2_IMPL 0 #endif // Turn on fast impl when using GCC on Intel-based machines with the following exception: #if defined(__GNUC__) && ((defined(__i386__) || defined(__i386) || defined(__x86_64__) || defined(__x86_64))) -# define GCC_USE_FAST_IMPL 1 +# define GCC_USE_FAST_IMPL 1 #else -# define GCC_USE_FAST_IMPL 0 +# define GCC_USE_FAST_IMPL 0 #endif // Turn on fast impl when using msvc on 32 bits windows #if defined(_MSC_VER) && !defined(_WIN64) -# define VC_USE_FAST_IMPL 1 +# define VC_USE_FAST_IMPL 1 #else -# define VC_USE_FAST_IMPL 0 +# define VC_USE_FAST_IMPL 0 #endif - //: Type-accessible infinities for use in templates. -template VNL_EXPORT T vnl_huge_val(T); -extern VNL_EXPORT long double vnl_huge_val(long double); -extern VNL_EXPORT double vnl_huge_val(double); -extern VNL_EXPORT float vnl_huge_val(float); -extern VNL_EXPORT long int vnl_huge_val(long int); -extern VNL_EXPORT int vnl_huge_val(int); -extern VNL_EXPORT short vnl_huge_val(short); -extern VNL_EXPORT char vnl_huge_val(char); +template +VNL_EXPORT T vnl_huge_val(T); +extern VNL_EXPORT long double +vnl_huge_val(long double); +extern VNL_EXPORT double +vnl_huge_val(double); +extern VNL_EXPORT float +vnl_huge_val(float); +extern VNL_EXPORT long int +vnl_huge_val(long int); +extern VNL_EXPORT int +vnl_huge_val(int); +extern VNL_EXPORT short +vnl_huge_val(short); +extern VNL_EXPORT char +vnl_huge_val(char); //: real numerical constants // Strictly speaking, the static declaration of the constant variables is @@ -96,40 +103,42 @@ extern VNL_EXPORT char vnl_huge_val(char); // understand. namespace vnl_math { - //: pi, e and all that. Constants are rounded to the shown precision. - static constexpr double e = 2.71828182845904523536; // http://oeis.org/A001113 - static constexpr double log2e = 1.44269504088896340736; // http://oeis.org/A007525 - static constexpr double log10e = 0.43429448190325182765; // http://oeis.org/A002285 - static constexpr double ln2 = 0.69314718055994530942; // http://oeis.org/A002162 - static constexpr double ln10 = 2.30258509299404568402; // http://oeis.org/A002392 - static constexpr double pi = 3.14159265358979323846; // http://oeis.org/A000796 - static constexpr double twopi = 6.28318530717958647693; // http://oeis.org/A019692 - static constexpr double pi_over_2 = 1.57079632679489661923; // http://oeis.org/A019669 - static constexpr double pi_over_4 = 0.78539816339744830962; // http://oeis.org/A003881 - static constexpr double pi_over_180 = 0.01745329251994329577; // http://oeis.org/A019685 - static constexpr double one_over_pi = 0.31830988618379067154; // http://oeis.org/A049541 - static constexpr double two_over_pi = 0.63661977236758134308; // http://oeis.org/A060294 - static constexpr double deg_per_rad = 57.2957795130823208768; // http://oeis.org/A072097 - static constexpr double sqrt2pi = 2.50662827463100050242; // http://oeis.org/A019727 - static constexpr double two_over_sqrtpi = 1.12837916709551257390; // http://oeis.org/A190732 - static constexpr double one_over_sqrt2pi = 0.39894228040143267794; // http://oeis.org/A231863 - static constexpr double sqrt2 = 1.41421356237309504880; // http://oeis.org/A002193 - static constexpr double sqrt1_2 = 0.70710678118654752440; // http://oeis.org/A010503 - static constexpr double sqrt1_3 = 0.57735026918962576451; // http://oeis.org/A020760 - static constexpr double euler = 0.57721566490153286061; // http://oeis.org/A001620 - - //: IEEE double machine precision - static constexpr double eps = 2.2204460492503131e-16; - static constexpr double sqrteps = 1.490116119384766e-08; - //: IEEE single machine precision - static constexpr float float_eps = 1.192092896e-07f; - static constexpr float float_sqrteps = 3.4526698300e-4f; - - //: Convert an angle to [0, 2Pi) range - VNL_EXPORT double angle_0_to_2pi(double angle); - //: Convert an angle to [-Pi, Pi) range - VNL_EXPORT double angle_minuspi_to_pi(double angle); -} +//: pi, e and all that. Constants are rounded to the shown precision. +static constexpr double e = 2.71828182845904523536; // http://oeis.org/A001113 +static constexpr double log2e = 1.44269504088896340736; // http://oeis.org/A007525 +static constexpr double log10e = 0.43429448190325182765; // http://oeis.org/A002285 +static constexpr double ln2 = 0.69314718055994530942; // http://oeis.org/A002162 +static constexpr double ln10 = 2.30258509299404568402; // http://oeis.org/A002392 +static constexpr double pi = 3.14159265358979323846; // http://oeis.org/A000796 +static constexpr double twopi = 6.28318530717958647693; // http://oeis.org/A019692 +static constexpr double pi_over_2 = 1.57079632679489661923; // http://oeis.org/A019669 +static constexpr double pi_over_4 = 0.78539816339744830962; // http://oeis.org/A003881 +static constexpr double pi_over_180 = 0.01745329251994329577; // http://oeis.org/A019685 +static constexpr double one_over_pi = 0.31830988618379067154; // http://oeis.org/A049541 +static constexpr double two_over_pi = 0.63661977236758134308; // http://oeis.org/A060294 +static constexpr double deg_per_rad = 57.2957795130823208768; // http://oeis.org/A072097 +static constexpr double sqrt2pi = 2.50662827463100050242; // http://oeis.org/A019727 +static constexpr double two_over_sqrtpi = 1.12837916709551257390; // http://oeis.org/A190732 +static constexpr double one_over_sqrt2pi = 0.39894228040143267794; // http://oeis.org/A231863 +static constexpr double sqrt2 = 1.41421356237309504880; // http://oeis.org/A002193 +static constexpr double sqrt1_2 = 0.70710678118654752440; // http://oeis.org/A010503 +static constexpr double sqrt1_3 = 0.57735026918962576451; // http://oeis.org/A020760 +static constexpr double euler = 0.57721566490153286061; // http://oeis.org/A001620 + +//: IEEE double machine precision +static constexpr double eps = 2.2204460492503131e-16; +static constexpr double sqrteps = 1.490116119384766e-08; +//: IEEE single machine precision +static constexpr float float_eps = 1.192092896e-07f; +static constexpr float float_sqrteps = 3.4526698300e-4f; + +//: Convert an angle to [0, 2Pi) range +VNL_EXPORT double +angle_0_to_2pi(double angle); +//: Convert an angle to [-Pi, Pi) range +VNL_EXPORT double +angle_minuspi_to_pi(double angle); +} // namespace vnl_math // Note that the three template functions below should not be declared "inline" // since that would override the non-inline specialisations. - PVr. @@ -138,75 +147,99 @@ namespace vnl_math namespace vnl_math { #if defined(_MSC_VER) - // MSVC does not properly implement isfinite, iinf, isnan for C++11 conformance for integral types - // For integral types only: - template - _Check_return_ typename std::enable_if::value, bool>::type isnan(_In_ T t) throw() - { - return std::isnan(static_cast(t)); - } - template - _Check_return_ typename std::enable_if::value, bool>::type isinf(_In_ T t) throw() - { - return std::isinf(static_cast(t)); - } - template - _Check_return_ typename std::enable_if::value, bool>::type isfinite(_In_ T t) throw() - { - return std::isfinite(static_cast(t)); - } - template - _Check_return_ typename std::enable_if::value, bool>::type isnormal(_In_ T t) throw() - { - return std::isnormal(static_cast(t)); - } +// MSVC does not properly implement isfinite, iinf, isnan for C++11 conformance for integral types +// For integral types only: +template +_Check_return_ typename std::enable_if::value, bool>::type +isnan(_In_ T t) throw() +{ + return std::isnan(static_cast(t)); +} +template +_Check_return_ typename std::enable_if::value, bool>::type +isinf(_In_ T t) throw() +{ + return std::isinf(static_cast(t)); +} +template +_Check_return_ typename std::enable_if::value, bool>::type +isfinite(_In_ T t) throw() +{ + return std::isfinite(static_cast(t)); +} +template +_Check_return_ typename std::enable_if::value, bool>::type +isnormal(_In_ T t) throw() +{ + return std::isnormal(static_cast(t)); +} - // Floating point types can alias C++ standard that is implemented - template - _Check_return_ typename std::enable_if::value, bool>::type isnan(_In_ T t) throw() - { - return std::isnan(t); - } - template - _Check_return_ typename std::enable_if::value, bool>::type isinf(_In_ T t) throw() - { - return std::isinf(t); - } - template - _Check_return_ typename std::enable_if::value, bool>::type isfinite(_In_ T t) throw() - { - return std::isfinite(t); - } - template - _Check_return_ typename std::enable_if::value, bool>::type isnormal(_In_ T t) throw() - { - return std::isnormal(t); - } +// Floating point types can alias C++ standard that is implemented +template +_Check_return_ typename std::enable_if::value, bool>::type +isnan(_In_ T t) throw() +{ + return std::isnan(t); +} +template +_Check_return_ typename std::enable_if::value, bool>::type +isinf(_In_ T t) throw() +{ + return std::isinf(t); +} +template +_Check_return_ typename std::enable_if::value, bool>::type +isfinite(_In_ T t) throw() +{ + return std::isfinite(t); +} +template +_Check_return_ typename std::enable_if::value, bool>::type +isnormal(_In_ T t) throw() +{ + return std::isnormal(t); +} #else - // https://en.cppreference.com/w/cpp/numeric/math/isinf indicates that isinf should return bool - // However, several compiler environments do not properly conform to the C++11 standard for - // returning bool from these functions. Wrap them to ensure conformance, and - // rely on the compiler to optimize the overhead away. - - // Return a signed integer type has been seen with the following - // compilers/libstdc++: - // RHEL7-devtool-6-gcc6.3 - // RHEL7-devtool-6-gcc6.3-m32 - // RHEL7-devtool-7-gcc7.2 - // RHEL7-devtool-7-gcc7.2-m32 - - template - inline bool isinf(TArg arg) { return bool(std::isinf(arg)); } - template - inline bool isnan(TArg arg) { return bool(std::isnan(arg)); } - template - inline bool isfinite(TArg arg) { return bool(std::isfinite(arg)); } - template - inline bool isnormal(TArg arg) { return bool(std::isnormal(arg)); } +// https://en.cppreference.com/w/cpp/numeric/math/isinf indicates that isinf should return bool +// However, several compiler environments do not properly conform to the C++11 standard for +// returning bool from these functions. Wrap them to ensure conformance, and +// rely on the compiler to optimize the overhead away. + +// Return a signed integer type has been seen with the following +// compilers/libstdc++: +// RHEL7-devtool-6-gcc6.3 +// RHEL7-devtool-6-gcc6.3-m32 +// RHEL7-devtool-7-gcc7.2 +// RHEL7-devtool-7-gcc7.2-m32 + +template +inline bool +isinf(TArg arg) +{ + return bool(std::isinf(arg)); +} +template +inline bool +isnan(TArg arg) +{ + return bool(std::isnan(arg)); +} +template +inline bool +isfinite(TArg arg) +{ + return bool(std::isfinite(arg)); +} +template +inline bool +isnormal(TArg arg) +{ + return bool(std::isnormal(arg)); +} #endif - using std::max; - using std::min; - using std::cbrt; +using std::max; +using std::min; +using std::cbrt; #if 0 // Use std::cbrt template TArg cuberoot(TArg&& arg) @@ -214,7 +247,7 @@ namespace vnl_math return std::cbrt(std::forward(arg)); } #endif - using std::hypot; +using std::hypot; #if USE_SSE2_IMPL // Fast sse2 implementation @@ -227,47 +260,52 @@ namespace vnl_math // // We assume that the rounding mode is not changed from the default // one (or at least that it is always restored to the default one). -inline int rnd_halfinttoeven(float x) +inline int +rnd_halfinttoeven(float x) { -# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) - assert(fegetround()==FE_TONEAREST); -# endif +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround() == FE_TONEAREST); +# endif return _mm_cvtss_si32(_mm_set_ss(x)); } -inline int rnd_halfinttoeven(double x) +inline int +rnd_halfinttoeven(double x) { -# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) - assert(fegetround()==FE_TONEAREST); -# endif +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround() == FE_TONEAREST); +# endif return _mm_cvtsd_si32(_mm_set_sd(x)); } #elif GCC_USE_FAST_IMPL // Fast gcc asm implementation -inline int rnd_halfinttoeven(float x) +inline int +rnd_halfinttoeven(float x) { -# ifdef VNL_CHECK_FPU_ROUNDING_MODE - assert(fegetround()==FE_TONEAREST); -# endif +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround() == FE_TONEAREST); +# endif int r; - __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); + __asm__ __volatile__("fistpl %0" : "=m"(r) : "t"(x) : "st"); return r; } -inline int rnd_halfinttoeven(double x) +inline int +rnd_halfinttoeven(double x) { -# ifdef VNL_CHECK_FPU_ROUNDING_MODE - assert(fegetround()==FE_TONEAREST); -# endif +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround() == FE_TONEAREST); +# endif int r; - __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); + __asm__ __volatile__("fistpl %0" : "=m"(r) : "t"(x) : "st"); return r; } #elif VC_USE_FAST_IMPL // Fast msvc asm implementation -inline int rnd_halfinttoeven(float x) +inline int +rnd_halfinttoeven(float x) { int r; __asm { @@ -277,7 +315,8 @@ inline int rnd_halfinttoeven(float x) return r; } -inline int rnd_halfinttoeven(double x) +inline int +rnd_halfinttoeven(double x) { int r; __asm { @@ -289,39 +328,45 @@ inline int rnd_halfinttoeven(double x) #else // Vanilla implementation -inline int rnd_halfinttoeven(float x) +inline int +rnd_halfinttoeven(float x) { - if (x>=0.f) + if (x >= 0.f) { - x+=0.5f; - const int r = static_cast(x); - if ( x != static_cast(r) ) return r; - return 2*(r/2); + x += 0.5f; + const int r = static_cast(x); + if (x != static_cast(r)) + return r; + return 2 * (r / 2); } else { - x-=0.5f; - const int r = static_cast(x); - if ( x != static_cast(r) ) return r; - return 2*(r/2); + x -= 0.5f; + const int r = static_cast(x); + if (x != static_cast(r)) + return r; + return 2 * (r / 2); } } -inline int rnd_halfinttoeven(double x) +inline int +rnd_halfinttoeven(double x) { - if (x>=0.) + if (x >= 0.) { - x+=0.5; - const int r = static_cast(x); - if ( x != static_cast(r) ) return r; - return 2*(r/2); + x += 0.5; + const int r = static_cast(x); + if (x != static_cast(r)) + return r; + return 2 * (r / 2); } else { - x-=0.5; - const int r = static_cast(x); - if ( x != static_cast(r) ) return r; - return 2*(r/2); + x -= 0.5; + const int r = static_cast(x); + if (x != static_cast(r)) + return r; + return 2 * (r / 2); } } @@ -341,26 +386,36 @@ inline int rnd_halfinttoeven(double x) // We also assume that the rounding mode is not changed from the default // one (or at least that it is always restored to the default one). -inline int rnd_halfintup(float x) { return rnd_halfinttoeven(2*x+0.5f)>>1; } -inline int rnd_halfintup(double x) { return rnd_halfinttoeven(2*x+0.5)>>1; } +inline int +rnd_halfintup(float x) +{ + return rnd_halfinttoeven(2 * x + 0.5f) >> 1; +} +inline int +rnd_halfintup(double x) +{ + return rnd_halfinttoeven(2 * x + 0.5) >> 1; +} #else // Vanilla implementation -inline int rnd_halfintup(float x) +inline int +rnd_halfintup(float x) { - x+=0.5f; - return static_cast(x>=0.f?x:(x==static_cast(x)?x:x-1.f)); + x += 0.5f; + return static_cast(x >= 0.f ? x : (x == static_cast(x) ? x : x - 1.f)); } -inline int rnd_halfintup(double x) +inline int +rnd_halfintup(double x) { - x+=0.5; - return static_cast(x>=0.?x:(x==static_cast(x)?x:x-1.)); + x += 0.5; + return static_cast(x >= 0. ? x : (x == static_cast(x) ? x : x - 1.)); } #endif -#if USE_SSE2_IMPL || GCC_USE_FAST_IMPL || VC_USE_FAST_IMPL +#if USE_SSE2_IMPL || GCC_USE_FAST_IMPL || VC_USE_FAST_IMPL // rnd -- round towards nearest integer // halfway cases such as 0.5 may be rounded either up or down // so as to maximize the efficiency, e.g. @@ -371,17 +426,33 @@ inline int rnd_halfintup(double x) // // We assume that the rounding mode is not changed from the default // one (or at least that it is always restored to the default one). -inline int rnd(float x) { return rnd_halfinttoeven(x); } -inline int rnd(double x) { return rnd_halfinttoeven(x); } +inline int +rnd(float x) +{ + return rnd_halfinttoeven(x); +} +inline int +rnd(double x) +{ + return rnd_halfinttoeven(x); +} #else // Vanilla implementation -inline int rnd(float x) { return x>=0.f?static_cast(x+.5f):static_cast(x-.5f); } -inline int rnd(double x) { return x>=0.0?static_cast(x+0.5):static_cast(x-0.5); } +inline int +rnd(float x) +{ + return x >= 0.f ? static_cast(x + .5f) : static_cast(x - .5f); +} +inline int +rnd(double x) +{ + return x >= 0.0 ? static_cast(x + 0.5) : static_cast(x - 0.5); +} #endif -#if USE_SSE2_IMPL // Fast sse2 implementation +#if USE_SSE2_IMPL // Fast sse2 implementation // floor -- round towards minus infinity // // Be careful: argument absolute value must be less than INT_MAX/2 @@ -389,86 +460,94 @@ inline int rnd(double x) { return x>=0.0?static_cast(x+0.5):static_cast>1; +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround() == FE_TONEAREST); +# endif + return _mm_cvtss_si32(_mm_set_ss(2 * x - .5f)) >> 1; } -inline int floor(double x) +inline int +floor(double x) { -# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) - assert(fegetround()==FE_TONEAREST); -# endif - return _mm_cvtsd_si32(_mm_set_sd(2*x-.5))>>1; +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround() == FE_TONEAREST); +# endif + return _mm_cvtsd_si32(_mm_set_sd(2 * x - .5)) >> 1; } #elif GCC_USE_FAST_IMPL // Fast gcc asm implementation -inline int floor(float x) +inline int +floor(float x) { -# ifdef VNL_CHECK_FPU_ROUNDING_MODE - assert(fegetround()==FE_TONEAREST); -# endif +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround() == FE_TONEAREST); +# endif int r; - x = 2*x-.5f; - __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); - return r>>1; + x = 2 * x - .5f; + __asm__ __volatile__("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return r >> 1; } -inline int floor(double x) +inline int +floor(double x) { -# ifdef VNL_CHECK_FPU_ROUNDING_MODE - assert(fegetround()==FE_TONEAREST); -# endif +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround() == FE_TONEAREST); +# endif int r; - x = 2*x-.5; - __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); - return r>>1; + x = 2 * x - .5; + __asm__ __volatile__("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return r >> 1; } #elif VC_USE_FAST_IMPL // Fast msvc asm implementation -inline int floor(float x) +inline int +floor(float x) { int r; - x = 2*x-.5f; + x = 2 * x - .5f; __asm { fld x fistp r } - return r>>1; + return r >> 1; } -inline int floor(double x) +inline int +floor(double x) { int r; - x = 2*x-.5; + x = 2 * x - .5; __asm { fld x fistp r } - return r>>1; + return r >> 1; } #else // Vanilla implementation -inline int floor(float x) +inline int +floor(float x) { - return static_cast(x>=0.f?x:(x==static_cast(x)?x:x-1.f)); + return static_cast(x >= 0.f ? x : (x == static_cast(x) ? x : x - 1.f)); } -inline int floor(double x) +inline int +floor(double x) { - return static_cast(x>=0.0?x:(x==static_cast(x)?x:x-1.0)); + return static_cast(x >= 0.0 ? x : (x == static_cast(x) ? x : x - 1.0)); } #endif -#if USE_SSE2_IMPL // Fast sse2 implementation +#if USE_SSE2_IMPL // Fast sse2 implementation // ceil -- round towards plus infinity // // Be careful: argument absolute value must be less than INT_MAX/2 @@ -476,179 +555,451 @@ inline int floor(double x) // We also assume that the rounding mode is not changed from the default // one (or at least that it is always restored to the default one). -inline int ceil(float x) +inline int +ceil(float x) { -# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) - assert(fegetround()==FE_TONEAREST); -# endif - return -(_mm_cvtss_si32(_mm_set_ss(-.5f-2*x))>>1); +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround() == FE_TONEAREST); +# endif + return -(_mm_cvtss_si32(_mm_set_ss(-.5f - 2 * x)) >> 1); } -inline int ceil(double x) +inline int +ceil(double x) { -# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) - assert(fegetround()==FE_TONEAREST); -# endif - return -(_mm_cvtsd_si32(_mm_set_sd(-.5-2*x))>>1); +# if defined(VNL_CHECK_FPU_ROUNDING_MODE) && defined(__GNUC__) + assert(fegetround() == FE_TONEAREST); +# endif + return -(_mm_cvtsd_si32(_mm_set_sd(-.5 - 2 * x)) >> 1); } #elif GCC_USE_FAST_IMPL // Fast gcc asm implementation -inline int ceil(float x) +inline int +ceil(float x) { -# ifdef VNL_CHECK_FPU_ROUNDING_MODE - assert(fegetround()==FE_TONEAREST); -# endif +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround() == FE_TONEAREST); +# endif int r; - x = -.5f-2*x; - __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); - return -(r>>1); + x = -.5f - 2 * x; + __asm__ __volatile__("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return -(r >> 1); } -inline int ceil(double x) +inline int +ceil(double x) { -# ifdef VNL_CHECK_FPU_ROUNDING_MODE - assert(fegetround()==FE_TONEAREST); -# endif +# ifdef VNL_CHECK_FPU_ROUNDING_MODE + assert(fegetround() == FE_TONEAREST); +# endif int r; - x = -.5-2*x; - __asm__ __volatile__ ("fistpl %0" : "=m"(r) : "t"(x) : "st"); - return -(r>>1); + x = -.5 - 2 * x; + __asm__ __volatile__("fistpl %0" : "=m"(r) : "t"(x) : "st"); + return -(r >> 1); } #elif VC_USE_FAST_IMPL // Fast msvc asm implementation -inline int ceil(float x) +inline int +ceil(float x) { int r; - x = -.5f-2*x; + x = -.5f - 2 * x; __asm { fld x fistp r } - return -(r>>1); + return -(r >> 1); } -inline int ceil(double x) +inline int +ceil(double x) { int r; - x = -.5-2*x; + x = -.5 - 2 * x; __asm { fld x fistp r } - return -(r>>1); + return -(r >> 1); } #else // Vanilla implementation -inline int ceil(float x) +inline int +ceil(float x) { - return static_cast(x<0.f?x:(x==static_cast(x)?x:x+1.f)); + return static_cast(x < 0.f ? x : (x == static_cast(x) ? x : x + 1.f)); } -inline int ceil(double x) +inline int +ceil(double x) { - return static_cast(x<0.0?x:(x==static_cast(x)?x:x+1.0)); + return static_cast(x < 0.0 ? x : (x == static_cast(x) ? x : x + 1.0)); } #endif // abs -inline bool abs(bool x) { return x; } -inline unsigned char abs(unsigned char x) { return x; } -inline unsigned char abs(signed char x) { return x < 0 ? static_cast(-x) : x; } -inline unsigned char abs(char x) { return static_cast(x); } -inline unsigned short abs(short x) { return x < 0 ? static_cast(-x) : x; } -inline unsigned short abs(unsigned short x) { return x; } -inline unsigned int abs(unsigned int x) { return x; } -inline unsigned long abs(unsigned long x) { return x; } +inline bool +abs(bool x) +{ + return x; +} +inline unsigned char +abs(unsigned char x) +{ + return x; +} +inline unsigned char +abs(signed char x) +{ + return x < 0 ? static_cast(-x) : x; +} +inline unsigned char +abs(char x) +{ + return static_cast(x); +} +inline unsigned short +abs(short x) +{ + return x < 0 ? static_cast(-x) : x; +} +inline unsigned short +abs(unsigned short x) +{ + return x; +} +inline unsigned int +abs(unsigned int x) +{ + return x; +} +inline unsigned long +abs(unsigned long x) +{ + return x; +} ////long long - target type will have width of at least 64 bits. (since C++11) -inline unsigned long long abs(unsigned long long x) { return x; } +inline unsigned long long +abs(unsigned long long x) +{ + return x; +} // using std::abs; // (covers int, long, long long, float, double, long double // sqr (square) -inline bool sqr(bool x) { return x; } -inline int sqr(int x) { return x*x; } -inline unsigned int sqr(unsigned int x) { return x*x; } -inline long sqr(long x) { return x*x; } -inline unsigned long sqr(unsigned long x) { return x*x; } -//long long - target type will have width of at least 64 bits. (since C++11) -inline long long sqr(long long x) { return x*x; } -inline unsigned long long sqr(unsigned long long x) { return x*x; } - -inline float sqr(float x) { return x*x; } -inline double sqr(double x) { return x*x; } +inline bool +sqr(bool x) +{ + return x; +} +inline int +sqr(int x) +{ + return x * x; +} +inline unsigned int +sqr(unsigned int x) +{ + return x * x; +} +inline long +sqr(long x) +{ + return x * x; +} +inline unsigned long +sqr(unsigned long x) +{ + return x * x; +} +// long long - target type will have width of at least 64 bits. (since C++11) +inline long long +sqr(long long x) +{ + return x * x; +} +inline unsigned long long +sqr(unsigned long long x) +{ + return x * x; +} + +inline float +sqr(float x) +{ + return x * x; +} +inline double +sqr(double x) +{ + return x * x; +} // cube -inline bool cube(bool x) { return x; } -inline int cube(int x) { return x*x*x; } -inline unsigned int cube(unsigned int x) { return x*x*x; } -inline long cube(long x) { return x*x*x; } -inline unsigned long cube(unsigned long x) { return x*x*x; } -//long long - target type will have width of at least 64 bits. (since C++11) -inline long long cube(long long x) { return x*x*x; } -inline unsigned long long cube(unsigned long long x) { return x*x*x; } - -inline float cube(float x) { return x*x*x; } -inline double cube(double x) { return x*x*x; } +inline bool +cube(bool x) +{ + return x; +} +inline int +cube(int x) +{ + return x * x * x; +} +inline unsigned int +cube(unsigned int x) +{ + return x * x * x; +} +inline long +cube(long x) +{ + return x * x * x; +} +inline unsigned long +cube(unsigned long x) +{ + return x * x * x; +} +// long long - target type will have width of at least 64 bits. (since C++11) +inline long long +cube(long long x) +{ + return x * x * x; +} +inline unsigned long long +cube(unsigned long long x) +{ + return x * x * x; +} + +inline float +cube(float x) +{ + return x * x * x; +} +inline double +cube(double x) +{ + return x * x * x; +} // sgn (sign in -1, 0, +1) -inline int sgn(int x) { return x?((x>0)?1:-1):0; } -inline int sgn(long x) { return x?((x>0)?1:-1):0; } -//long long - target type will have width of at least 64 bits. (since C++11) -inline int sgn(long long x) { return x?((x>0)?1:-1):0; } +inline int +sgn(int x) +{ + return x ? ((x > 0) ? 1 : -1) : 0; +} +inline int +sgn(long x) +{ + return x ? ((x > 0) ? 1 : -1) : 0; +} +// long long - target type will have width of at least 64 bits. (since C++11) +inline int +sgn(long long x) +{ + return x ? ((x > 0) ? 1 : -1) : 0; +} -inline int sgn(float x) { return (x != 0)?((x>0)?1:-1):0; } -inline int sgn(double x) { return (x != 0)?((x>0)?1:-1):0; } +inline int +sgn(float x) +{ + return (x != 0) ? ((x > 0) ? 1 : -1) : 0; +} +inline int +sgn(double x) +{ + return (x != 0) ? ((x > 0) ? 1 : -1) : 0; +} // sgn0 (sign in -1, +1 only, useful for reals) -inline int sgn0(int x) { return (x>=0)?1:-1; } -inline int sgn0(long x) { return (x>=0)?1:-1; } -//long long - target type will have width of at least 64 bits. (since C++11) -inline int sgn0(long long x) { return (x>=0)?1:-1; } +inline int +sgn0(int x) +{ + return (x >= 0) ? 1 : -1; +} +inline int +sgn0(long x) +{ + return (x >= 0) ? 1 : -1; +} +// long long - target type will have width of at least 64 bits. (since C++11) +inline int +sgn0(long long x) +{ + return (x >= 0) ? 1 : -1; +} -inline int sgn0(float x) { return (x>=0)?1:-1; } -inline int sgn0(double x) { return (x>=0)?1:-1; } +inline int +sgn0(float x) +{ + return (x >= 0) ? 1 : -1; +} +inline int +sgn0(double x) +{ + return (x >= 0) ? 1 : -1; +} // squared_magnitude -inline unsigned int squared_magnitude(char x) { return int(x)*int(x); } -inline unsigned int squared_magnitude(unsigned char x) { return int(x)*int(x); } -inline unsigned int squared_magnitude(int x) { return x*x; } -inline unsigned int squared_magnitude(unsigned int x) { return x*x; } -inline unsigned long squared_magnitude(long x) { return x*x; } -inline unsigned long squared_magnitude(unsigned long x) { return x*x; } -//long long - target type will have width of at least 64 bits. (since C++11) -inline unsigned long long squared_magnitude(long long x) { return x*x; } -inline unsigned long long squared_magnitude(unsigned long long x) { return x*x; } +inline unsigned int +squared_magnitude(char x) +{ + return int(x) * int(x); +} +inline unsigned int +squared_magnitude(unsigned char x) +{ + return int(x) * int(x); +} +inline unsigned int +squared_magnitude(int x) +{ + return x * x; +} +inline unsigned int +squared_magnitude(unsigned int x) +{ + return x * x; +} +inline unsigned long +squared_magnitude(long x) +{ + return x * x; +} +inline unsigned long +squared_magnitude(unsigned long x) +{ + return x * x; +} +// long long - target type will have width of at least 64 bits. (since C++11) +inline unsigned long long +squared_magnitude(long long x) +{ + return x * x; +} +inline unsigned long long +squared_magnitude(unsigned long long x) +{ + return x * x; +} -inline float squared_magnitude(float x) { return x*x; } -inline double squared_magnitude(double x) { return x*x; } -inline long double squared_magnitude(long double x) { return x*x; } +inline float +squared_magnitude(float x) +{ + return x * x; +} +inline double +squared_magnitude(double x) +{ + return x * x; +} +inline long double +squared_magnitude(long double x) +{ + return x * x; +} // truncated remainder -inline int remainder_truncated(int x, int y) { return x % y; } -inline unsigned int remainder_truncated(unsigned int x, unsigned int y) { return x % y; } -inline long remainder_truncated(long x, long y) { return x % y; } -inline unsigned long remainder_truncated(unsigned long x, unsigned long y) { return x % y; } -inline long long remainder_truncated(long long x, long long y) { return x % y; } -inline unsigned long long remainder_truncated(unsigned long long x, unsigned long long y) { return x % y; } -inline float remainder_truncated(float x, float y) { return fmod(x,y); } -inline double remainder_truncated(double x, double y) { return fmod(x,y); } -inline long double remainder_truncated(long double x, long double y) { return fmod(x,y); } +inline int +remainder_truncated(int x, int y) +{ + return x % y; +} +inline unsigned int +remainder_truncated(unsigned int x, unsigned int y) +{ + return x % y; +} +inline long +remainder_truncated(long x, long y) +{ + return x % y; +} +inline unsigned long +remainder_truncated(unsigned long x, unsigned long y) +{ + return x % y; +} +inline long long +remainder_truncated(long long x, long long y) +{ + return x % y; +} +inline unsigned long long +remainder_truncated(unsigned long long x, unsigned long long y) +{ + return x % y; +} +inline float +remainder_truncated(float x, float y) +{ + return fmod(x, y); +} +inline double +remainder_truncated(double x, double y) +{ + return fmod(x, y); +} +inline long double +remainder_truncated(long double x, long double y) +{ + return fmod(x, y); +} // floored remainder -inline int remainder_floored(int x, int y) { return ((x % y) + y) % y; } -inline unsigned int remainder_floored(unsigned int x, unsigned int y) { return x % y; } -inline long remainder_floored(long x, long y) { return ((x % y) + y) % y; } -inline unsigned long remainder_floored(unsigned long x, unsigned long y) { return x % y; } -inline long long remainder_floored(long long x, long long y) { return ((x % y) + y) % y; } -inline unsigned long long remainder_floored(unsigned long long x, unsigned long long y) { return x % y; } -inline float remainder_floored(float x, float y) { return fmod(fmod(x,y)+y,y); } -inline double remainder_floored(double x, double y) { return fmod(fmod(x,y)+y,y); } -inline long double remainder_floored(long double x, long double y) { return fmod(fmod(x,y)+y,y); } +inline int +remainder_floored(int x, int y) +{ + return ((x % y) + y) % y; +} +inline unsigned int +remainder_floored(unsigned int x, unsigned int y) +{ + return x % y; +} +inline long +remainder_floored(long x, long y) +{ + return ((x % y) + y) % y; +} +inline unsigned long +remainder_floored(unsigned long x, unsigned long y) +{ + return x % y; +} +inline long long +remainder_floored(long long x, long long y) +{ + return ((x % y) + y) % y; +} +inline unsigned long long +remainder_floored(unsigned long long x, unsigned long long y) +{ + return x % y; +} +inline float +remainder_floored(float x, float y) +{ + return fmod(fmod(x, y) + y, y); +} +inline double +remainder_floored(double x, double y) +{ + return fmod(fmod(x, y) + y, y); +} +inline long double +remainder_floored(long double x, long double y) +{ + return fmod(fmod(x, y) + y, y); +} } // end of namespace vnl_math #endif // vnl_math_h_ diff --git a/core/vnl/vnl_matlab_filewrite.cxx b/core/vnl/vnl_matlab_filewrite.cxx index 55db16143b9..876b312b3f9 100644 --- a/core/vnl/vnl_matlab_filewrite.cxx +++ b/core/vnl/vnl_matlab_filewrite.cxx @@ -9,9 +9,9 @@ #include "vnl/vnl_matlab_write.h" -vnl_matlab_filewrite::vnl_matlab_filewrite(char const * file_name, char const * basename) +vnl_matlab_filewrite::vnl_matlab_filewrite(const char * file_name, const char * basename) : basename_(basename ? basename : "targetvar") - , variable_int_(0) + { out_.open(file_name, std::ios::out | std::ios::binary); if (out_.bad()) @@ -19,10 +19,10 @@ vnl_matlab_filewrite::vnl_matlab_filewrite(char const * file_name, char const * } std::string -vnl_matlab_filewrite::make_var_name(char const * variable_name) +vnl_matlab_filewrite::make_var_name(const char * variable_name) { if (variable_name) - return std::string(variable_name); + return { variable_name }; else { std::stringstream ss; @@ -35,51 +35,51 @@ vnl_matlab_filewrite::make_var_name(char const * variable_name) //: scalar void -vnl_matlab_filewrite::write(double v, char const * variable_name) +vnl_matlab_filewrite::write(double v, const char * variable_name) { vnl_matlab_write(out_, v, make_var_name(variable_name).c_str()); } //: vector void -vnl_matlab_filewrite::write(vnl_vector const & v, char const * variable_name) +vnl_matlab_filewrite::write(const vnl_vector & v, const char * variable_name) { vnl_matlab_write(out_, v.data_block(), v.size(), make_var_name(variable_name).c_str()); } void -vnl_matlab_filewrite::write(vnl_vector> const & v, char const * variable_name) +vnl_matlab_filewrite::write(const vnl_vector> & v, const char * variable_name) { vnl_matlab_write(out_, v.data_block(), v.size(), make_var_name(variable_name).c_str()); } //: matrix void -vnl_matlab_filewrite::write(vnl_matrix const & M, char const * variable_name) +vnl_matlab_filewrite::write(const vnl_matrix & M, const char * variable_name) { vnl_matlab_write(out_, M.data_array(), M.rows(), M.cols(), make_var_name(variable_name).c_str()); } void -vnl_matlab_filewrite::write(vnl_matrix const & M, char const * variable_name) +vnl_matlab_filewrite::write(const vnl_matrix & M, const char * variable_name) { vnl_matlab_write(out_, M.data_array(), M.rows(), M.cols(), make_var_name(variable_name).c_str()); } void -vnl_matlab_filewrite::write(vnl_matrix> const & M, char const * variable_name) +vnl_matlab_filewrite::write(const vnl_matrix> & M, const char * variable_name) { vnl_matlab_write(out_, M.data_array(), M.rows(), M.cols(), make_var_name(variable_name).c_str()); } void -vnl_matlab_filewrite::write(vnl_matrix> const & M, char const * variable_name) +vnl_matlab_filewrite::write(const vnl_matrix> & M, const char * variable_name) { vnl_matlab_write(out_, M.data_array(), M.rows(), M.cols(), make_var_name(variable_name).c_str()); } void -vnl_matlab_filewrite::write(double const * const * M, int rows, int cols, char const * variable_name) +vnl_matlab_filewrite::write(const double * const * M, int rows, int cols, const char * variable_name) { vnl_matlab_write(out_, M, rows, cols, make_var_name(variable_name).c_str()); } diff --git a/core/vnl/vnl_matlab_filewrite.h b/core/vnl/vnl_matlab_filewrite.h index 98628fe991a..836316a46b6 100644 --- a/core/vnl/vnl_matlab_filewrite.h +++ b/core/vnl/vnl_matlab_filewrite.h @@ -29,30 +29,39 @@ class VNL_EXPORT vnl_matlab_filewrite { - public: - vnl_matlab_filewrite (char const* file_name, char const *basename = nullptr); +public: + vnl_matlab_filewrite(const char * file_name, const char * basename = nullptr); //: Add scalar/vector/matrix variable to the MAT file using specified variable name. // If no name is given, variables will be generated by // appending 0,1,2 etc to the given basename. - void write(double v, char const* variable_name = nullptr); + void + write(double v, const char * variable_name = nullptr); - void write(vnl_vector const & v, char const* variable_name = nullptr); - void write(vnl_vector > const & v, char const* variable_name = nullptr); + void + write(const vnl_vector & v, const char * variable_name = nullptr); + void + write(const vnl_vector> & v, const char * variable_name = nullptr); - void write(vnl_matrix const & M, char const* variable_name = nullptr); - void write(vnl_matrix const & M, char const* variable_name = nullptr); - void write(vnl_matrix > const & M, char const* variable_name = nullptr); - void write(vnl_matrix > const & M, char const* variable_name = nullptr); + void + write(const vnl_matrix & M, const char * variable_name = nullptr); + void + write(const vnl_matrix & M, const char * variable_name = nullptr); + void + write(const vnl_matrix> & M, const char * variable_name = nullptr); + void + write(const vnl_matrix> & M, const char * variable_name = nullptr); - void write(double const * const *M, int rows, int cols, char const* variable_name = nullptr); + void + write(const double * const * M, int rows, int cols, const char * variable_name = nullptr); - protected: +protected: std::string basename_; - int variable_int_; + int variable_int_{ 0 }; std::fstream out_; - std::string make_var_name(char const* variable_name); + std::string + make_var_name(const char * variable_name); }; #endif // vnl_matlab_filewrite_h_ diff --git a/core/vnl/vnl_matlab_header.h b/core/vnl/vnl_matlab_header.h index 3df231e3014..4b20eb5807f 100644 --- a/core/vnl/vnl_matlab_header.h +++ b/core/vnl/vnl_matlab_header.h @@ -25,16 +25,17 @@ struct VNL_EXPORT vnl_matlab_header vxl_int_32 imag; vxl_int_32 namlen; - enum type_t { + enum type_t + { // precision specifier vnl_DOUBLE_PRECISION = 0, vnl_SINGLE_PRECISION = 10, // storage specifier vnl_COLUMN_WISE = 0, - vnl_ROW_WISE = 100, + vnl_ROW_WISE = 100, // byte order vnl_LITTLE_ENDIAN = 0, - vnl_BIG_ENDIAN = 1000, + vnl_BIG_ENDIAN = 1000, // vnl_none = 0 }; @@ -42,24 +43,34 @@ struct VNL_EXPORT vnl_matlab_header namespace byteswap // byteswap routines, stolen from ITK { - inline void - swap32(void *ptr) - { - char one_byte; - char *p = reinterpret_cast(ptr); - one_byte = p[0]; p[0] = p[3]; p[3] = one_byte; - one_byte = p[1]; p[1] = p[2]; p[2] = one_byte; - } - inline void - swap64(void *ptr) - { - char one_byte; - char *p = reinterpret_cast(ptr); - one_byte = p[0]; p[0] = p[7]; p[7] = one_byte; - one_byte = p[1]; p[1] = p[6]; p[6] = one_byte; - one_byte = p[2]; p[2] = p[5]; p[5] = one_byte; - one_byte = p[3]; p[3] = p[4]; p[4] = one_byte; - } +inline void +swap32(void * ptr) +{ + char * p = reinterpret_cast(ptr); + char one_byte = p[0]; + p[0] = p[3]; + p[3] = one_byte; + one_byte = p[1]; + p[1] = p[2]; + p[2] = one_byte; +} +inline void +swap64(void * ptr) +{ + char * p = reinterpret_cast(ptr); + char one_byte = p[0]; + p[0] = p[7]; + p[7] = one_byte; + one_byte = p[1]; + p[1] = p[6]; + p[6] = one_byte; + one_byte = p[2]; + p[2] = p[5]; + p[5] = one_byte; + one_byte = p[3]; + p[3] = p[4]; + p[4] = one_byte; } +} // namespace byteswap #endif // vnl_matlab_header_h_ diff --git a/core/vnl/vnl_matlab_print.h b/core/vnl/vnl_matlab_print.h index 988e37e3c00..3144b9d41c2 100644 --- a/core/vnl/vnl_matlab_print.h +++ b/core/vnl/vnl_matlab_print.h @@ -25,68 +25,77 @@ //-------------------- "unnamed" forms. //: print a 1D array. -template VNL_EXPORT -std::ostream &vnl_matlab_print(std::ostream &, - T const *array, - unsigned length, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print(std::ostream &, + const T * array, + unsigned length, + vnl_matlab_print_format = vnl_matlab_print_format_default); //: print a 2D array. -template VNL_EXPORT -std::ostream &vnl_matlab_print(std::ostream &, - T const * const *array, - unsigned rows, unsigned cols, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print(std::ostream &, + const T * const * array, + unsigned rows, + unsigned cols, + vnl_matlab_print_format = vnl_matlab_print_format_default); //-------------------- "named" forms. //: print a vnl_diagonal_matrix. // \relatesalso vnl_diag_matrix -template VNL_EXPORT -std::ostream &vnl_matlab_print(std::ostream &, - vnl_diag_matrix const&, - char const *variable_name =nullptr, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print(std::ostream &, + const vnl_diag_matrix &, + const char * variable_name = nullptr, + vnl_matlab_print_format = vnl_matlab_print_format_default); //: print a vnl_matrix. // \relatesalso vnl_matrix -template VNL_EXPORT -std::ostream &vnl_matlab_print(std::ostream &, - vnl_matrix const&, - char const *variable_name =nullptr, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print(std::ostream &, + const vnl_matrix &, + const char * variable_name = nullptr, + vnl_matlab_print_format = vnl_matlab_print_format_default); //: print a vnl_matrix_fixed. // \relatesalso vnl_matrix_fixed -template VNL_EXPORT -std::ostream &vnl_matlab_print(std::ostream &, - vnl_matrix_fixed const&, - char const *variable_name =nullptr, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print(std::ostream &, + const vnl_matrix_fixed &, + const char * variable_name = nullptr, + vnl_matlab_print_format = vnl_matlab_print_format_default); //: print a vnl_matrix_ref. // \relatesalso vnl_matrix_ref -template VNL_EXPORT -std::ostream &vnl_matlab_print(std::ostream &, - vnl_matrix_ref const &, - char const *variable_name =nullptr, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print(std::ostream &, + const vnl_matrix_ref &, + const char * variable_name = nullptr, + vnl_matlab_print_format = vnl_matlab_print_format_default); //: print a vnl_vector. // \relatesalso vnl_vector -template VNL_EXPORT -std::ostream &vnl_matlab_print(std::ostream &, - vnl_vector const &, - char const *variable_name =nullptr, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print(std::ostream &, + const vnl_vector &, + const char * variable_name = nullptr, + vnl_matlab_print_format = vnl_matlab_print_format_default); //: print a vnl_vector_fixed. // \relatesalso vnl_vector_fixed -template VNL_EXPORT -std::ostream &vnl_matlab_print(std::ostream &, - vnl_vector_fixed const &, - char const *variable_name =nullptr, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print(std::ostream &, + const vnl_vector_fixed &, + const char * variable_name = nullptr, + vnl_matlab_print_format = vnl_matlab_print_format_default); //: naughty naming-convention-defying-but-handy macro. diff --git a/core/vnl/vnl_matlab_print.hxx b/core/vnl/vnl_matlab_print.hxx index 0d05a37f3f7..9827fda398b 100644 --- a/core/vnl/vnl_matlab_print.hxx +++ b/core/vnl/vnl_matlab_print.hxx @@ -23,13 +23,12 @@ //-------------------------------------------------------------------------------- template -std::ostream &vnl_matlab_print(std::ostream& s, - T const* array, - unsigned length, - vnl_matlab_print_format format) +std::ostream & +vnl_matlab_print(std::ostream & s, const T * array, unsigned length, vnl_matlab_print_format format) { char buf[1024]; - for (unsigned j=0; j -std::ostream &vnl_matlab_print(std::ostream &s, - T const * const *array, - unsigned rows, unsigned cols, - vnl_matlab_print_format format) +std::ostream & +vnl_matlab_print(std::ostream & s, + const T * const * array, + unsigned rows, + unsigned cols, + vnl_matlab_print_format format) { - for (unsigned i=0; i -std::ostream& vnl_matlab_print(std::ostream& s, - vnl_diag_matrix const& D, - char const* variable_name, - vnl_matlab_print_format format) +std::ostream & +vnl_matlab_print(std::ostream & s, + const vnl_diag_matrix & D, + const char * variable_name, + vnl_matlab_print_format format) { if (variable_name) s << variable_name << " = diag([ "; @@ -68,10 +70,8 @@ std::ostream& vnl_matlab_print(std::ostream& s, } template -std::ostream& vnl_matlab_print(std::ostream& s, - vnl_matrix const& M, - char const* variable_name, - vnl_matlab_print_format format) +std::ostream & +vnl_matlab_print(std::ostream & s, const vnl_matrix & M, const char * variable_name, vnl_matlab_print_format format) { if (variable_name) s << variable_name << " = [ ...\n"; @@ -79,10 +79,11 @@ std::ostream& vnl_matlab_print(std::ostream& s, if (variable_name && M.rows() == 0) return s << "];\n"; - for (unsigned int i=0; i -std::ostream& vnl_matlab_print(std::ostream& s, - vnl_vector const & v, - char const* variable_name, - vnl_matlab_print_format format) +std::ostream & +vnl_matlab_print(std::ostream & s, const vnl_vector & v, const char * variable_name, vnl_matlab_print_format format) { if (variable_name) s << variable_name << " = [ "; @@ -109,10 +108,11 @@ std::ostream& vnl_matlab_print(std::ostream& s, } template -std::ostream& vnl_matlab_print(std::ostream& s, - vnl_matrix_fixed const& M, - char const* variable_name, - vnl_matlab_print_format format) +std::ostream & +vnl_matlab_print(std::ostream & s, + const vnl_matrix_fixed & M, + const char * variable_name, + vnl_matlab_print_format format) { if (variable_name) s << variable_name << " = [ ...\n"; @@ -120,10 +120,11 @@ std::ostream& vnl_matlab_print(std::ostream& s, if (variable_name && M.rows() == 0) return s << "];\n"; - for (unsigned int i=0; i -std::ostream& vnl_matlab_print(std::ostream& s, - vnl_matrix_ref const& M, - char const* variable_name, - vnl_matlab_print_format format) +std::ostream & +vnl_matlab_print(std::ostream & s, + const vnl_matrix_ref & M, + const char * variable_name, + vnl_matlab_print_format format) { if (variable_name) s << variable_name << " = [ ...\n"; @@ -144,11 +146,11 @@ std::ostream& vnl_matlab_print(std::ostream& s, if (variable_name && M.rows() == 0) return s << "];\n"; - for (unsigned int i=0; i -std::ostream& vnl_matlab_print(std::ostream& s, - vnl_vector_fixed const & v, - char const* variable_name, - vnl_matlab_print_format format) +std::ostream & +vnl_matlab_print(std::ostream & s, + const vnl_vector_fixed & v, + const char * variable_name, + vnl_matlab_print_format format) { if (variable_name) s << variable_name << " = [ "; @@ -176,39 +179,70 @@ std::ostream& vnl_matlab_print(std::ostream& s, //-------------------------------------------------------------------------------- -#undef VNL_MATLAB_PRINT_INSTANTIATE -#define VNL_MATLAB_PRINT_INSTANTIATE(T) \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, T const*, unsigned, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, T const* const*, unsigned, unsigned, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_diag_matrix const&, char const *, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_ref const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_matrix_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format); \ -template VNL_EXPORT std::ostream &vnl_matlab_print(std::ostream &, vnl_vector_fixed const&, char const*, vnl_matlab_print_format) +#undef VNL_MATLAB_PRINT_INSTANTIATE +#define VNL_MATLAB_PRINT_INSTANTIATE(T) \ + template VNL_EXPORT std::ostream & vnl_matlab_print(std::ostream &, T const *, unsigned, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, T const * const *, unsigned, unsigned, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_diag_matrix const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_ref const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_matrix_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format); \ + template VNL_EXPORT std::ostream & vnl_matlab_print( \ + std::ostream &, vnl_vector_fixed const &, char const *, vnl_matlab_print_format) #endif // vnl_matlab_print_hxx_ diff --git a/core/vnl/vnl_matlab_print2.h b/core/vnl/vnl_matlab_print2.h index 6c42a9c6152..5b43661b9c2 100644 --- a/core/vnl/vnl_matlab_print2.h +++ b/core/vnl/vnl_matlab_print2.h @@ -35,20 +35,21 @@ template struct VNL_EXPORT vnl_matlab_print_proxy { - T const &obj; - char const *name; + const T & obj; + const char * name; vnl_matlab_print_format format; - vnl_matlab_print_proxy(T const &obj_, - char const *name_, - vnl_matlab_print_format format_) - : obj(obj_), name(name_), format(format_) { } + vnl_matlab_print_proxy(const T & obj_, const char * name_, vnl_matlab_print_format format_) + : obj(obj_) + , name(name_) + , format(format_) + {} ~vnl_matlab_print_proxy() = default; }; // Output operator for the proxies. template -inline -std::ostream &operator<<(std::ostream &os, vnl_matlab_print_proxy const &mp) +inline std::ostream & +operator<<(std::ostream & os, const vnl_matlab_print_proxy & mp) { return vnl_matlab_print(os, mp.obj, mp.name, mp.format); } @@ -57,20 +58,19 @@ std::ostream &operator<<(std::ostream &os, vnl_matlab_print_proxy const &mp) // derived from vnl_vector, vnl_matrix etc because the overload // resolution is done in the operator<< above. template -inline -vnl_matlab_print_proxy -vnl_matlab_print(T const &obj, - char const *name = nullptr, +inline vnl_matlab_print_proxy +vnl_matlab_print(const T & obj, + const char * name = nullptr, vnl_matlab_print_format format = vnl_matlab_print_format_default) { return vnl_matlab_print_proxy(obj, name, format); } -#define VNL_MATLAB_PRINT2_INSTANTIATE(T) \ -template struct VNL_EXPORT vnl_matlab_print_proxy; \ -/* template std::ostream& \ - operator<<(std::ostream&, vnl_matlab_print_proxy const&); */ \ -/* template vnl_matlab_print_proxy \ - vnl_matlab_print(T const&, char const*, vnl_matlab_print_format) */ +#define VNL_MATLAB_PRINT2_INSTANTIATE(T) \ + template struct VNL_EXPORT vnl_matlab_print_proxy; \ + /* template std::ostream& \ + operator<<(std::ostream&, vnl_matlab_print_proxy const&); */ \ + /* template vnl_matlab_print_proxy \ + vnl_matlab_print(T const&, char const*, vnl_matlab_print_format) */ #endif // vnl_matlab_print2_h_ diff --git a/core/vnl/vnl_matlab_print_format.cxx b/core/vnl/vnl_matlab_print_format.cxx index 66a4fbdb092..c226f12031a 100644 --- a/core/vnl/vnl_matlab_print_format.cxx +++ b/core/vnl/vnl_matlab_print_format.cxx @@ -48,7 +48,7 @@ vnl_matlab_print_format vnl_matlab_print_format_set(vnl_matlab_print_format f) { vnl_matlab_print_format_init(); - vnl_matlab_print_format old = the_format; + const vnl_matlab_print_format old = the_format; the_format = f; return old; } diff --git a/core/vnl/vnl_matlab_print_format.h b/core/vnl/vnl_matlab_print_format.h index 56241a84dea..21e59ba1cdf 100644 --- a/core/vnl/vnl_matlab_print_format.h +++ b/core/vnl/vnl_matlab_print_format.h @@ -22,13 +22,15 @@ enum vnl_matlab_print_format // -------------------- Setting the default format. //: get top of stack : -VNL_EXPORT vnl_matlab_print_format vnl_matlab_print_format_top(); +VNL_EXPORT vnl_matlab_print_format +vnl_matlab_print_format_top(); //: set new, get old format at top of stack : VNL_EXPORT vnl_matlab_print_format vnl_matlab_print_format_set(vnl_matlab_print_format); //: push/pop the top of the stack : VNL_EXPORT void vnl_matlab_print_format_push(vnl_matlab_print_format); -VNL_EXPORT void vnl_matlab_print_format_pop (); +VNL_EXPORT void +vnl_matlab_print_format_pop(); #endif diff --git a/core/vnl/vnl_matlab_print_scalar.cxx b/core/vnl/vnl_matlab_print_scalar.cxx index 4e75f808254..4b4bfa9b368 100644 --- a/core/vnl/vnl_matlab_print_scalar.cxx +++ b/core/vnl/vnl_matlab_print_scalar.cxx @@ -2,24 +2,44 @@ #include #include +#include #include #include + #include "vnl_matlab_print_scalar.h" +#include "vcl_compiler.h" + + +void +vnl_matlab_print_scalar(int v, char * buf, size_t buf_len, vnl_matlab_print_format) +{ + std::snprintf(buf, buf_len, "%4d ", v); +} +#if !VXL_LEGACY_FUTURE_REMOVE void vnl_matlab_print_scalar(int v, char * buf, vnl_matlab_print_format) { - std::sprintf(buf, "%4d ", v); + vnl_matlab_print_scalar(v, buf, SIZE_MAX); } +#endif +void +vnl_matlab_print_scalar(unsigned v, char * buf, size_t buf_len, vnl_matlab_print_format) +{ + std::snprintf(buf, buf_len, "%4u ", v); +} + +#if !VXL_LEGACY_FUTURE_REMOVE void vnl_matlab_print_scalar(unsigned v, char * buf, vnl_matlab_print_format) { - std::sprintf(buf, "%4u ", v); + vnl_matlab_print_scalar(v, buf, SIZE_MAX); } +#endif void -vnl_matlab_print_scalar(float v, char * buf, vnl_matlab_print_format format) +vnl_matlab_print_scalar(float v, char * buf, size_t buf_len, vnl_matlab_print_format format) { if (format == vnl_matlab_print_format_default) format = vnl_matlab_print_format_top(); @@ -27,29 +47,37 @@ vnl_matlab_print_scalar(float v, char * buf, vnl_matlab_print_format format) { case vnl_matlab_print_format_long: if (v == 0.0) - std::sprintf(buf, "%8d ", 0); + std::snprintf(buf, buf_len, "%8d ", 0); else - std::sprintf(buf, "%8.5f ", v); + std::snprintf(buf, buf_len, "%8.5f ", v); break; case vnl_matlab_print_format_short: if (v == 0.0) - std::sprintf(buf, "%6d ", 0); + std::snprintf(buf, buf_len, "%6d ", 0); else - std::sprintf(buf, "%6.3f ", v); + std::snprintf(buf, buf_len, "%6.3f ", v); break; case vnl_matlab_print_format_long_e: - std::sprintf(buf, "%11.7e ", v); + std::snprintf(buf, buf_len, "%11.7e ", v); break; case vnl_matlab_print_format_short_e: - std::sprintf(buf, "%8.4e ", v); + std::snprintf(buf, buf_len, "%8.4e ", v); break; default: /*vnl_matlab_print_format_default:*/ std::abort(); } } +#if !VXL_LEGACY_FUTURE_REMOVE void -vnl_matlab_print_scalar(double v, char * buf, vnl_matlab_print_format format) +vnl_matlab_print_scalar(float v, char * buf, vnl_matlab_print_format format) +{ + vnl_matlab_print_scalar(v, buf, SIZE_MAX, format); +} +#endif + +void +vnl_matlab_print_scalar(double v, char * buf, size_t buf_len, vnl_matlab_print_format format) { if (format == vnl_matlab_print_format_default) format = vnl_matlab_print_format_top(); @@ -57,35 +85,51 @@ vnl_matlab_print_scalar(double v, char * buf, vnl_matlab_print_format format) { case vnl_matlab_print_format_long: if (v == 0.0) - std::sprintf(buf, "%16d ", 0); + std::snprintf(buf, buf_len, "%16d ", 0); else - std::sprintf(buf, "%16.13f ", v); + std::snprintf(buf, buf_len, "%16.13f ", v); break; case vnl_matlab_print_format_short: if (v == 0.0) - std::sprintf(buf, "%8d ", 0); + std::snprintf(buf, buf_len, "%8d ", 0); else - std::sprintf(buf, "%8.4f ", v); + std::snprintf(buf, buf_len, "%8.4f ", v); break; case vnl_matlab_print_format_long_e: - std::sprintf(buf, "%20.14e ", v); + std::snprintf(buf, buf_len, "%20.14e ", v); break; case vnl_matlab_print_format_short_e: - std::sprintf(buf, "%10.4e ", v); + std::snprintf(buf, buf_len, "%10.4e ", v); break; default: /*vnl_matlab_print_format_default:*/ std::abort(); } } +#if !VXL_LEGACY_FUTURE_REMOVE +void +vnl_matlab_print_scalar(double v, char * buf, vnl_matlab_print_format format) +{ + vnl_matlab_print_scalar(v, buf, SIZE_MAX, format); +} +#endif + +void +vnl_matlab_print_scalar(long double v, char * buf, size_t buf_len, vnl_matlab_print_format format) +{ + vnl_matlab_print_scalar(double(v), buf, buf_len, format); // FIXME +} + +#if !VXL_LEGACY_FUTURE_REMOVE void vnl_matlab_print_scalar(long double v, char * buf, vnl_matlab_print_format format) { - vnl_matlab_print_scalar(double(v), buf, format); // FIXME + vnl_matlab_print_scalar(v, buf, SIZE_MAX, format); } +#endif void -vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_format format) +vnl_matlab_print_scalar(std::complex v, char * buf, size_t buf_len, vnl_matlab_print_format format) { if (format == vnl_matlab_print_format_default) format = vnl_matlab_print_format_top(); @@ -123,32 +167,34 @@ vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_for std::abort(); } - double r = std::real(v); + const double r = std::real(v); double i = std::imag(v); char fmt[1024]; // Real part if (r == 0) { - std::sprintf(fmt, - "%%" - "%d" - "d ", - width); - std::sprintf(buf, fmt, 0); + std::snprintf(fmt, + sizeof(fmt), + "%%" + "%d" + "d ", + width); + std::snprintf(buf, buf_len, fmt, 0); } else { - std::sprintf(fmt, - "%%" - "%d" - "." - "%d" - "%c ", - width, - precision, - conv); - std::sprintf(buf, fmt, r); + std::snprintf(fmt, + sizeof(fmt), + "%%" + "%d" + "." + "%d" + "%c ", + width, + precision, + conv); + std::snprintf(buf, buf_len, fmt, r); } buf += std::strlen(buf); @@ -156,12 +202,13 @@ vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_for // Imaginary part. Width is reduced as sign is taken care of separately if (i == 0) { - std::sprintf(fmt, - " %%" - "%d" - "s ", - width - 1); - std::sprintf(buf, fmt, ""); + std::snprintf(fmt, + sizeof(fmt), + " %%" + "%d" + "s ", + width - 1); + std::snprintf(buf, buf_len, fmt, ""); } else { @@ -171,19 +218,28 @@ vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_for sign = '-'; i = -i; } - std::sprintf(fmt, - "%c%%" - "%d.%d%ci ", - sign, - width - 1, - precision, - conv); - std::sprintf(buf, fmt, i); + std::snprintf(fmt, + sizeof(fmt), + "%c%%" + "%d.%d%ci ", + sign, + width - 1, + precision, + conv); + std::snprintf(buf, buf_len, fmt, i); } } +#if !VXL_LEGACY_FUTURE_REMOVE void -vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_format format) +vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_format format) +{ + vnl_matlab_print_scalar(v, buf, SIZE_MAX, format); +} +#endif + +void +vnl_matlab_print_scalar(std::complex v, char * buf, size_t buf_len, vnl_matlab_print_format format) { if (format == vnl_matlab_print_format_default) format = vnl_matlab_print_format_top(); @@ -221,32 +277,34 @@ vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_form std::abort(); } - float r = std::real(v); + const float r = std::real(v); float i = std::imag(v); char fmt[1024]; // Real part if (r == 0) { - std::sprintf(fmt, - "%%" - "%d" - "d ", - width); - std::sprintf(buf, fmt, 0); + std::snprintf(fmt, + sizeof(fmt), + "%%" + "%d" + "d ", + width); + std::snprintf(buf, buf_len, fmt, 0); } else { - std::sprintf(fmt, - "%%" - "%d" - "." - "%d" - "%c ", - width, - precision, - conv); - std::sprintf(buf, fmt, r); + std::snprintf(fmt, + sizeof(fmt), + "%%" + "%d" + "." + "%d" + "%c ", + width, + precision, + conv); + std::snprintf(buf, buf_len, fmt, r); } buf += std::strlen(buf); @@ -254,12 +312,13 @@ vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_form // Imaginary part. Width is reduced as sign is taken care of separately if (i == 0) { - std::sprintf(fmt, - " %%" - "%d" - "s ", - width - 1); - std::sprintf(buf, fmt, ""); + std::snprintf(fmt, + sizeof(fmt), + " %%" + "%d" + "s ", + width - 1); + std::snprintf(buf, buf_len, fmt, ""); } else { @@ -269,30 +328,46 @@ vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_form sign = '-'; i = -i; } - std::sprintf(fmt, - "%c%%" - "%d.%d%ci ", - sign, - width - 1, - precision, - conv); - std::sprintf(buf, fmt, i); + std::snprintf(fmt, + sizeof(fmt), + "%c%%" + "%d.%d%ci ", + sign, + width - 1, + precision, + conv); + std::snprintf(buf, buf_len, fmt, i); } } +#if !VXL_LEGACY_FUTURE_REMOVE void -vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_format format) +vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_format format) +{ + vnl_matlab_print_scalar(v, buf, SIZE_MAX, format); +} +#endif + +void +vnl_matlab_print_scalar(std::complex v, char * buf, size_t buf_len, vnl_matlab_print_format format) { - vnl_matlab_print_scalar(std::complex(std::real(v), std::imag(v)), buf, format); // FIXME + vnl_matlab_print_scalar(std::complex(std::real(v), std::imag(v)), buf, buf_len, format); // FIXME } +#if !VXL_LEGACY_FUTURE_REMOVE +void +vnl_matlab_print_scalar(std::complex v, char * buf, vnl_matlab_print_format format) +{ + vnl_matlab_print_scalar(v, buf, SIZE_MAX, format); +} +#endif template std::ostream & vnl_matlab_print_scalar(std::ostream & s, T value, vnl_matlab_print_format format) { char buf[1024]; - vnl_matlab_print_scalar(value, buf, format); + vnl_matlab_print_scalar(value, buf, sizeof(buf), format); return s << buf; } diff --git a/core/vnl/vnl_matlab_print_scalar.h b/core/vnl/vnl_matlab_print_scalar.h index a35efbb9388..5d3c0f632a5 100644 --- a/core/vnl/vnl_matlab_print_scalar.h +++ b/core/vnl/vnl_matlab_print_scalar.h @@ -14,12 +14,12 @@ #endif #include "vnl_matlab_print_format.h" #include "vnl/vnl_export.h" +#include "vcl_compiler.h" //: print real or complex scalar into character buffer. #define vnl_matlab_print_scalar_declare(T) \ -VNL_EXPORT void vnl_matlab_print_scalar(T v, \ - char *buf, \ - vnl_matlab_print_format =vnl_matlab_print_format_default) + VNL_EXPORT void vnl_matlab_print_scalar( \ + T v, char * buf, size_t buf_len, vnl_matlab_print_format = vnl_matlab_print_format_default) // Even with a function template we would have to // forward declare all the specializations anyway. @@ -32,10 +32,29 @@ vnl_matlab_print_scalar_declare(std::complex); vnl_matlab_print_scalar_declare(std::complex); vnl_matlab_print_scalar_declare(std::complex); +#if !VXL_LEGACY_FUTURE_REMOVE +//: print real or complex scalar into character buffer. +// These variants are deprecated because the buffer size is not provided +# define vnl_matlab_print_scalar_declare_old(T) \ + VNL_EXPORT VXL_DEPRECATED void vnl_matlab_print_scalar( \ + T v, char * buf, vnl_matlab_print_format = vnl_matlab_print_format_default) + +// Even with a function template we would have to +// forward declare all the specializations anyway. +vnl_matlab_print_scalar_declare_old(int); +vnl_matlab_print_scalar_declare_old(unsigned int); +vnl_matlab_print_scalar_declare_old(float); +vnl_matlab_print_scalar_declare_old(double); +vnl_matlab_print_scalar_declare_old(long double); +vnl_matlab_print_scalar_declare_old(std::complex); +vnl_matlab_print_scalar_declare_old(std::complex); +vnl_matlab_print_scalar_declare_old(std::complex); + +#endif + //: print scalar to std::ostream. -template VNL_EXPORT -std::ostream &vnl_matlab_print_scalar(std::ostream &, - T value, - vnl_matlab_print_format =vnl_matlab_print_format_default); +template +VNL_EXPORT std::ostream & +vnl_matlab_print_scalar(std::ostream &, T value, vnl_matlab_print_format = vnl_matlab_print_format_default); #endif diff --git a/core/vnl/vnl_matlab_read.cxx b/core/vnl/vnl_matlab_read.cxx index a8eded49b0d..ea6ebfc7122 100644 --- a/core/vnl/vnl_matlab_read.cxx +++ b/core/vnl/vnl_matlab_read.cxx @@ -20,7 +20,7 @@ vcl_destroy(T * p) template inline void -vcl_construct(U * p, V const & value) +vcl_construct(U * p, const V & value) { new (p) U(value); } @@ -47,18 +47,18 @@ vnl_matlab_read_data(std::istream & s, double * p, unsigned n) ::vnl_read_bytes(s, p, n * sizeof(*p)); } -#define implement_read_complex_data(T) \ - template <> \ - void vnl_matlab_read_data(std::istream & s, std::complex * ptr, unsigned n) \ - { \ - T * re = vnl_c_vector::allocate_T(n); \ - T * im = vnl_c_vector::allocate_T(n); \ - ::vnl_read_bytes(s, re, n * sizeof(T)); \ - ::vnl_read_bytes(s, im, n * sizeof(T)); \ - for (unsigned i = 0; i < n; ++i) \ - ptr[i] = std::complex(re[i], im[i]); \ - vnl_c_vector::deallocate(re, n); \ - vnl_c_vector::deallocate(im, n); \ +#define implement_read_complex_data(T) \ + template <> \ + void vnl_matlab_read_data(std::istream & s, std::complex * ptr, unsigned n) \ + { \ + T * re = vnl_c_vector::allocate_T(n); \ + T * im = vnl_c_vector::allocate_T(n); \ + ::vnl_read_bytes(s, re, n * sizeof(T)); \ + ::vnl_read_bytes(s, im, n * sizeof(T)); \ + for (unsigned i = 0; i < n; ++i) \ + ptr[i] = std::complex(re[i], im[i]); \ + vnl_c_vector::deallocate(re, n); \ + vnl_c_vector::deallocate(im, n); \ } implement_read_complex_data(float) implement_read_complex_data(double) @@ -69,9 +69,7 @@ implement_read_complex_data(float) implement_read_complex_data(double) vnl_matlab_readhdr::vnl_matlab_readhdr(std::istream & s_) : s(s_) - , varname(nullptr) - , data_read(false) - , need_swap(false) + { read_hdr(); } @@ -88,7 +86,8 @@ vnl_matlab_readhdr::operator bool() const return (s.good() && !s.eof()) ? true : false; // FIXME } -bool vnl_matlab_readhdr::operator!() const +bool +vnl_matlab_readhdr::operator!() const { return (s.good() && !s.eof()) ? false : true; // FIXME } @@ -215,92 +214,92 @@ vnl_matlab_readhdr::type_chck(std::complex &) return !is_single() && is_complex(); } -#define fsm_define_methods(T) \ - bool vnl_matlab_readhdr::read_data(T & v) \ - { \ - if (!type_chck(v)) \ - { \ - std::cerr << "type_check\n"; \ - return false; \ - } \ - if (rows() != 1U || cols() != 1U) \ - { \ - std::cerr << "size0\n"; \ - return false; \ - } \ - vnl_matlab_read_data(s, &v, 1); \ - if (need_swap) \ - { \ - if (sizeof(v) == 4U) \ - byteswap::swap32(&v); \ - else \ - byteswap::swap64(&v); \ - } \ - data_read = true; \ - return !!*this; \ - } \ - bool vnl_matlab_readhdr::read_data(T * p) \ - { \ - if (!type_chck(p[0])) \ - { \ - std::cerr << "type_check\n"; \ - return false; \ - } \ - if (rows() != 1U && cols() != 1U) \ - { \ - std::cerr << "size1\n"; \ - return false; \ - } \ - vnl_matlab_read_data(s, p, rows() * cols()); \ - if (need_swap) \ - { \ - for (long i = 0; i < rows() * cols(); ++i) \ - { \ - if (sizeof(*p) == 4U) \ - byteswap::swap32(&(p[i])); \ - else \ - byteswap::swap64(&(p[i])); \ - } \ - } \ - data_read = true; \ - return !!*this; \ - } \ - bool vnl_matlab_readhdr::read_data(T * const * m) \ - { \ - if (!type_chck(m[0][0])) \ - { \ - std::cerr << "type_check\n"; \ - return false; \ - } \ - T * tmp = vnl_c_vector::allocate_T(rows() * cols()); \ - vnl_matlab_read_data(s, tmp, rows() * cols()); \ - if (need_swap) \ - { \ - for (long i = 0; i < rows() * cols(); ++i) \ - { \ - if (sizeof(T) == 4U) \ - byteswap::swap32(&(tmp[i])); \ - else \ - byteswap::swap64(&(tmp[i])); \ - } \ - } \ - int a, b; \ - if (is_rowwise()) \ - { \ - a = cols(); \ - b = 1; \ - } \ - else \ - { \ - a = 1; \ - b = rows(); \ - } \ - for (long i = 0; i < rows(); ++i) \ - for (long j = 0; j < cols(); ++j) \ - m[i][j] = tmp[a * i + b * j]; \ - vnl_c_vector::deallocate(tmp, rows() * cols()); \ - data_read = true; \ - return !!*this; \ +#define fsm_define_methods(T) \ + bool vnl_matlab_readhdr::read_data(T & v) \ + { \ + if (!type_chck(v)) \ + { \ + std::cerr << "type_check\n"; \ + return false; \ + } \ + if (rows() != 1U || cols() != 1U) \ + { \ + std::cerr << "size0\n"; \ + return false; \ + } \ + vnl_matlab_read_data(s, &v, 1); \ + if (need_swap) \ + { \ + if (sizeof(v) == 4U) \ + byteswap::swap32(&v); \ + else \ + byteswap::swap64(&v); \ + } \ + data_read = true; \ + return !!*this; \ + } \ + bool vnl_matlab_readhdr::read_data(T * p) \ + { \ + if (!type_chck(p[0])) \ + { \ + std::cerr << "type_check\n"; \ + return false; \ + } \ + if (rows() != 1U && cols() != 1U) \ + { \ + std::cerr << "size1\n"; \ + return false; \ + } \ + vnl_matlab_read_data(s, p, rows() * cols()); \ + if (need_swap) \ + { \ + for (long i = 0; i < rows() * cols(); ++i) \ + { \ + if (sizeof(*p) == 4U) \ + byteswap::swap32(&(p[i])); \ + else \ + byteswap::swap64(&(p[i])); \ + } \ + } \ + data_read = true; \ + return !!*this; \ + } \ + bool vnl_matlab_readhdr::read_data(T * const * m) \ + { \ + if (!type_chck(m[0][0])) \ + { \ + std::cerr << "type_check\n"; \ + return false; \ + } \ + T * tmp = vnl_c_vector::allocate_T(rows() * cols()); \ + vnl_matlab_read_data(s, tmp, rows() * cols()); \ + if (need_swap) \ + { \ + for (long i = 0; i < rows() * cols(); ++i) \ + { \ + if (sizeof(T) == 4U) \ + byteswap::swap32(&(tmp[i])); \ + else \ + byteswap::swap64(&(tmp[i])); \ + } \ + } \ + int a, b; \ + if (is_rowwise()) \ + { \ + a = cols(); \ + b = 1; \ + } \ + else \ + { \ + a = 1; \ + b = rows(); \ + } \ + for (long i = 0; i < rows(); ++i) \ + for (long j = 0; j < cols(); ++j) \ + m[i][j] = tmp[a * i + b * j]; \ + vnl_c_vector::deallocate(tmp, rows() * cols()); \ + data_read = true; \ + return !!*this; \ } fsm_define_methods(float); @@ -344,7 +343,7 @@ vnl_matlab_read_or_die(std::istream & s, vnl_vector & v, char const * name) template bool -vnl_matlab_read_or_die(std::istream & s, vnl_matrix & M, char const * name) +vnl_matlab_read_or_die(std::istream & s, vnl_matrix & M, const char * name) { vnl_matlab_readhdr h(s); if (!s) // eof? @@ -370,8 +369,8 @@ vnl_matlab_read_or_die(std::istream & s, vnl_matrix & M, char const * name) return true; } -#define inst(T) \ - template VNL_EXPORT bool vnl_matlab_read_or_die(std::istream &, vnl_vector &, char const *); \ +#define inst(T) \ + template VNL_EXPORT bool vnl_matlab_read_or_die(std::istream &, vnl_vector &, char const *); \ template VNL_EXPORT bool vnl_matlab_read_or_die(std::istream &, vnl_matrix &, char const *); inst(double); diff --git a/core/vnl/vnl_matlab_read.h b/core/vnl/vnl_matlab_read.h index fa0d7ce594e..a1eecb5e9e7 100644 --- a/core/vnl/vnl_matlab_read.h +++ b/core/vnl/vnl_matlab_read.h @@ -24,8 +24,10 @@ // ------------------------------ easy ------------------------------ -template class vnl_vector; -template class vnl_matrix; +template +class vnl_vector; +template +class vnl_matrix; //: Attempt to read vector or matrix. // If the MATLAB header cannot be read, return false. @@ -33,60 +35,89 @@ template class vnl_matrix; // If the data in the file cannot reasonably be read into the destination, abort(). // // The vector/matrix will be resized if necessary. -template VNL_EXPORT bool vnl_matlab_read_or_die(std::istream &, vnl_vector &, char const *name =nullptr); -template VNL_EXPORT bool vnl_matlab_read_or_die(std::istream &, vnl_matrix &, char const *name =nullptr); +template +VNL_EXPORT bool +vnl_matlab_read_or_die(std::istream &, vnl_vector &, const char * name = nullptr); +template +VNL_EXPORT bool +vnl_matlab_read_or_die(std::istream &, vnl_matrix &, const char * name = nullptr); // ------------------------------ less easy ------------------------------ //: MATLAB stores its data as a real block followed by an imaginary block. // This function will read both blocks and interleave them into the area // pointed to by ptr. For real T, it is equivalent to s.read(ptr, sizeof(T)*n); -template VNL_EXPORT void vnl_matlab_read_data(std::istream &s, T *ptr, unsigned n); +template +VNL_EXPORT void +vnl_matlab_read_data(std::istream & s, T * ptr, unsigned n); class VNL_EXPORT vnl_matlab_readhdr { - private: - - public: +private: +public: vnl_matlab_readhdr(std::istream &); ~vnl_matlab_readhdr(); - explicit operator bool () const; - bool operator!() const; - void read_next(); // skip to next header in file + explicit + operator bool() const; + bool + operator!() const; + void + read_next(); // skip to next header in file - bool is_single() const; - bool is_rowwise() const; - bool is_bigendian() const; // don't use this - long rows() const { return hdr.rows; } - long cols() const { return hdr.cols; } - bool is_complex() const { return hdr.imag != 0; } - char const *name() const { return varname; } + bool + is_single() const; + bool + is_rowwise() const; + bool + is_bigendian() const; // don't use this + long + rows() const + { + return hdr.rows; + } + long + cols() const + { + return hdr.cols; + } + bool + is_complex() const + { + return hdr.imag != 0; + } + const char * + name() const + { + return varname; + } // bah! no member templates - //template bool read_data(T &); // scalar - //template bool read_data(T *); // vector - //template bool read_data(T * const *); // 2D array + // template bool read_data(T &); // scalar + // template bool read_data(T *); // vector + // template bool read_data(T * const *); // 2D array #define fsm_declare_methods(T) \ - private: \ - bool type_chck(T &); \ - public: \ - bool read_data(T &); \ - bool read_data(T *); \ +private: \ + bool type_chck(T &); \ + \ +public: \ + bool read_data(T &); \ + bool read_data(T *); \ bool read_data(T * const *) // no ; here, please. -fsm_declare_methods(float); -fsm_declare_methods(double); -fsm_declare_methods(std::complex); -fsm_declare_methods(std::complex); + fsm_declare_methods(float); + fsm_declare_methods(double); + fsm_declare_methods(std::complex); + fsm_declare_methods(std::complex); #undef fsm_declare_methods - private: - std::istream &s; +private: + std::istream & s; vnl_matlab_header hdr; - char *varname; - bool data_read; - bool need_swap; - void read_hdr(); // internal work routine + char * varname{ nullptr }; + bool data_read{ false }; + bool need_swap{ false }; + void + read_hdr(); // internal work routine }; #endif // vnl_matlab_read_h_ diff --git a/core/vnl/vnl_matlab_write.cxx b/core/vnl/vnl_matlab_write.cxx index 1ec8bd17a98..f7a4f579c00 100644 --- a/core/vnl/vnl_matlab_write.cxx +++ b/core/vnl/vnl_matlab_write.cxx @@ -16,72 +16,72 @@ #endif static void -vnl_write_bytes(std::ostream & s, void const * p, unsigned bytes) +vnl_write_bytes(std::ostream & s, const void * p, unsigned bytes) { - s.write((char const *)p, bytes); + s.write((const char *)p, bytes); } // ------------------------------ traits without tears ------------------------------ // template long scalar_precision(T const &); static long -vnl_scalar_precision(float const &) +vnl_scalar_precision(const float &) { return vnl_matlab_header::vnl_SINGLE_PRECISION; } static long -vnl_scalar_precision(double const &) +vnl_scalar_precision(const double &) { return vnl_matlab_header::vnl_DOUBLE_PRECISION; } static long -vnl_scalar_precision(std::complex const &) +vnl_scalar_precision(const std::complex &) { return vnl_matlab_header::vnl_SINGLE_PRECISION; } static long -vnl_scalar_precision(std::complex const &) +vnl_scalar_precision(const std::complex &) { return vnl_matlab_header::vnl_DOUBLE_PRECISION; } // template long is_complex(T const &); static long -vnl_is_complex(float const &) +vnl_is_complex(const float &) { return 0; } static long -vnl_is_complex(double const &) +vnl_is_complex(const double &) { return 0; } static long -vnl_is_complex(std::complex const &) +vnl_is_complex(const std::complex &) { return 1; } static long -vnl_is_complex(std::complex const &) +vnl_is_complex(const std::complex &) { return 1; } // template void vnl_write_real(std::ostream &, T const *, unsigned ); static void -vnl_write_real(std::ostream & s, float const * data, unsigned n) +vnl_write_real(std::ostream & s, const float * data, unsigned n) { ::vnl_write_bytes(s, data, n * sizeof(*data)); } static void -vnl_write_real(std::ostream & s, double const * data, unsigned n) +vnl_write_real(std::ostream & s, const double * data, unsigned n) { ::vnl_write_bytes(s, data, n * sizeof(*data)); } static void -vnl_write_real(std::ostream & s, std::complex const * data, unsigned n) +vnl_write_real(std::ostream & s, const std::complex * data, unsigned n) { float dummy; for (unsigned i = 0; i < n; ++i) @@ -92,7 +92,7 @@ vnl_write_real(std::ostream & s, std::complex const * data, unsigned n) } static void -vnl_write_real(std::ostream & s, std::complex const * data, unsigned n) +vnl_write_real(std::ostream & s, const std::complex * data, unsigned n) { double dummy; for (unsigned i = 0; i < n; ++i) @@ -105,15 +105,15 @@ vnl_write_real(std::ostream & s, std::complex const * data, unsigned n) // template void vnl_write_imag(std::ostream &, T const *, unsigned ); static void -vnl_write_imag(std::ostream &, float const *, unsigned) +vnl_write_imag(std::ostream &, const float *, unsigned) {} static void -vnl_write_imag(std::ostream &, double const *, unsigned) +vnl_write_imag(std::ostream &, const double *, unsigned) {} static void -vnl_write_imag(std::ostream & s, std::complex const * data, unsigned n) +vnl_write_imag(std::ostream & s, const std::complex * data, unsigned n) { float dummy; for (unsigned i = 0; i < n; ++i) @@ -124,7 +124,7 @@ vnl_write_imag(std::ostream & s, std::complex const * data, unsigned n) } static void -vnl_write_imag(std::ostream & s, std::complex const * data, unsigned n) +vnl_write_imag(std::ostream & s, const std::complex * data, unsigned n) { double dummy; for (unsigned i = 0; i < n; ++i) @@ -139,7 +139,7 @@ vnl_write_imag(std::ostream & s, std::complex const * data, unsigned n) //: scalars template bool -vnl_matlab_write(std::ostream & s, T const & x, char const * name) +vnl_matlab_write(std::ostream & s, const T & x, const char * name) { vnl_matlab_header hdr; hdr.type = native_BYTE_ORDER + vnl_matlab_header::vnl_COLUMN_WISE + vnl_scalar_precision(x); @@ -160,7 +160,7 @@ vnl_matlab_write(std::ostream & s, T const & x, char const * name) //: 1D array template bool -vnl_matlab_write(std::ostream & s, T const * v, unsigned n, char const * name) +vnl_matlab_write(std::ostream & s, const T * v, unsigned n, const char * name) { vnl_matlab_header hdr; hdr.type = native_BYTE_ORDER + vnl_matlab_header::vnl_COLUMN_WISE + vnl_scalar_precision(v[0]); @@ -176,13 +176,13 @@ vnl_matlab_write(std::ostream & s, T const * v, unsigned n, char const * name) return s.good() != 0; } -#define array1D_instantiate(T) \ +#define array1D_instantiate(T) \ template VNL_EXPORT bool vnl_matlab_write(std::ostream &, T const *, unsigned, char const *); //: 2D array template bool -vnl_matlab_write(std::ostream & s, T const * const * data, unsigned rows, unsigned cols, char const * name) +vnl_matlab_write(std::ostream & s, const T * const * data, unsigned rows, unsigned cols, const char * name) { vnl_matlab_header hdr; hdr.type = native_BYTE_ORDER + vnl_matlab_header::vnl_ROW_WISE + vnl_scalar_precision(data[0][0]); @@ -200,7 +200,7 @@ vnl_matlab_write(std::ostream & s, T const * const * data, unsigned rows, unsign return s.good() != 0; } -#define array2D_instantiate(T) \ +#define array2D_instantiate(T) \ template VNL_EXPORT bool vnl_matlab_write(std::ostream &, T const * const *, unsigned, unsigned, char const *); //-------------------------------------------------------------------------------- diff --git a/core/vnl/vnl_matlab_write.h b/core/vnl/vnl_matlab_write.h index 9e251f7ea15..10c10306541 100644 --- a/core/vnl/vnl_matlab_write.h +++ b/core/vnl/vnl_matlab_write.h @@ -24,13 +24,19 @@ #endif #include "vnl/vnl_export.h" -template VNL_EXPORT // scalar -bool vnl_matlab_write(std::ostream &, T const &, char const *variable_name); +template +VNL_EXPORT // scalar + bool + vnl_matlab_write(std::ostream &, const T &, const char * variable_name); -template VNL_EXPORT // 1D array -bool vnl_matlab_write(std::ostream &, T const *, unsigned size, char const *variable_name); +template +VNL_EXPORT // 1D array + bool + vnl_matlab_write(std::ostream &, const T *, unsigned size, const char * variable_name); -template VNL_EXPORT // 2D array -bool vnl_matlab_write(std::ostream &, T const * const *, unsigned rows, unsigned cols, char const *variable_name); +template +VNL_EXPORT // 2D array + bool + vnl_matlab_write(std::ostream &, const T * const *, unsigned rows, unsigned cols, const char * variable_name); #endif // vnl_matlab_write_h_ diff --git a/core/vnl/vnl_matops.cxx b/core/vnl/vnl_matops.cxx index f8b68fa5b41..d345455499d 100644 --- a/core/vnl/vnl_matops.cxx +++ b/core/vnl/vnl_matops.cxx @@ -10,7 +10,7 @@ #include vnl_matrix -vnl_matops::cat(vnl_matrix const & A, vnl_matrix const & B) +vnl_matops::cat(const vnl_matrix & A, const vnl_matrix & B) { assert(A.rows() == B.rows()); @@ -22,7 +22,7 @@ vnl_matops::cat(vnl_matrix const & A, vnl_matrix const & B) } vnl_matrix -vnl_matops::cat(vnl_matrix const & A, vnl_vector const & B) +vnl_matops::cat(const vnl_matrix & A, const vnl_vector & B) { assert(A.rows() == B.size()); @@ -34,7 +34,7 @@ vnl_matops::cat(vnl_matrix const & A, vnl_vector const & B) } vnl_matrix -vnl_matops::cat(vnl_vector const & A, vnl_matrix const & B) +vnl_matops::cat(const vnl_vector & A, const vnl_matrix & B) { assert(A.size() == B.rows()); @@ -46,7 +46,7 @@ vnl_matops::cat(vnl_vector const & A, vnl_matrix const & B) } vnl_matrix -vnl_matops::vcat(vnl_matrix const & A, vnl_matrix const & B) +vnl_matops::vcat(const vnl_matrix & A, const vnl_matrix & B) { assert(A.columns() == B.columns()); @@ -59,32 +59,32 @@ vnl_matops::vcat(vnl_matrix const & A, vnl_matrix const & B) //: Return fro_norm( (A ./ B) - mean(A ./ B) ) double -vnl_matops::homg_diff(vnl_matrix const & A, vnl_matrix const & B) +vnl_matops::homg_diff(const vnl_matrix & A, const vnl_matrix & B) { - vnl_matrix ratio = element_quotient(A, B); + const vnl_matrix ratio = element_quotient(A, B); return (ratio - ratio.mean()).fro_norm(); } -#define implement_converters(U, V) \ - vnl_matrix make_matrix_##U(vnl_matrix const & M) \ - { \ - unsigned m = M.rows(); \ - unsigned n = M.columns(); \ - vnl_matrix ret(m, n); \ - for (unsigned i = 0; i < m; ++i) \ - for (unsigned j = 0; j < n; ++j) \ - ret(i, j) = static_cast(M(i, j)); \ - return ret; \ - } \ - \ - vnl_vector make_vector_##U(vnl_vector const & v) \ - { \ - unsigned n = v.size(); \ - vnl_vector ret(n); \ - for (unsigned i = 0; i < n; ++i) \ - ret[i] = static_cast(v[i]); \ - return ret; \ +#define implement_converters(U, V) \ + vnl_matrix make_matrix_##U(vnl_matrix const & M) \ + { \ + unsigned m = M.rows(); \ + unsigned n = M.columns(); \ + vnl_matrix ret(m, n); \ + for (unsigned i = 0; i < m; ++i) \ + for (unsigned j = 0; j < n; ++j) \ + ret(i, j) = static_cast(M(i, j)); \ + return ret; \ + } \ + \ + vnl_vector make_vector_##U(vnl_vector const & v) \ + { \ + unsigned n = v.size(); \ + vnl_vector ret(n); \ + for (unsigned i = 0; i < n; ++i) \ + ret[i] = static_cast(v[i]); \ + return ret; \ } implement_converters(double, float) @@ -97,19 +97,19 @@ implement_converters(double, float) } vnl_matrix -vnl_matops::d2f(vnl_matrix const & M) +vnl_matops::d2f(const vnl_matrix & M) { return make_matrix_float(M); } vnl_vector -vnl_matops::f2d(vnl_vector const & M) +vnl_matops::f2d(const vnl_vector & M) { return make_vector_double(M); } vnl_vector -vnl_matops::d2f(vnl_vector const & M) +vnl_matops::d2f(const vnl_vector & M) { return make_vector_float(M); } diff --git a/core/vnl/vnl_matops.h b/core/vnl/vnl_matops.h index ca9a5f21624..1e24b271215 100644 --- a/core/vnl/vnl_matops.h +++ b/core/vnl/vnl_matops.h @@ -24,21 +24,30 @@ // matlab_print has been moved to vnl_matlab_print.h. class VNL_EXPORT vnl_matops { - public: - static double homg_diff(vnl_matrix const& A, vnl_matrix const& B); +public: + static double + homg_diff(const vnl_matrix & A, const vnl_matrix & B); //: Laminating - static vnl_matrix cat(vnl_matrix const& A, vnl_matrix const& B); - static vnl_matrix cat(vnl_matrix const& A, vnl_vector const& B); - static vnl_matrix cat(vnl_vector const& A, vnl_matrix const& B); + static vnl_matrix + cat(const vnl_matrix & A, const vnl_matrix & B); + static vnl_matrix + cat(const vnl_matrix & A, const vnl_vector & B); + static vnl_matrix + cat(const vnl_vector & A, const vnl_matrix & B); - static vnl_matrix vcat(vnl_matrix const& A, vnl_matrix const& B); + static vnl_matrix + vcat(const vnl_matrix & A, const vnl_matrix & B); //: Conversions - static vnl_matrix f2d(vnl_matrix const&); - static vnl_vector f2d(vnl_vector const&); - static vnl_matrix d2f(vnl_matrix const&); - static vnl_vector d2f(vnl_vector const&); + static vnl_matrix + f2d(const vnl_matrix &); + static vnl_vector + f2d(const vnl_vector &); + static vnl_matrix + d2f(const vnl_matrix &); + static vnl_vector + d2f(const vnl_vector &); }; #endif // vnl_matops_h_ diff --git a/core/vnl/vnl_matrix.h b/core/vnl/vnl_matrix.h index 1a80fe97f9a..32ed3cf1925 100644 --- a/core/vnl/vnl_matrix.h +++ b/core/vnl/vnl_matrix.h @@ -39,35 +39,57 @@ #include #include "vnl_error.h" #ifndef NDEBUG -# if VNL_CONFIG_CHECK_BOUNDS -#include -# endif +# if VNL_CONFIG_CHECK_BOUNDS +# include +# endif #else -# undef VNL_CONFIG_CHECK_BOUNDS -# define VNL_CONFIG_CHECK_BOUNDS 0 -# undef ERROR_CHECKING +# undef VNL_CONFIG_CHECK_BOUNDS +# define VNL_CONFIG_CHECK_BOUNDS 0 +# undef ERROR_CHECKING #endif #include "vnl/vnl_export.h" -template class vnl_vector; -template class vnl_matrix; +template +class vnl_vector; +template +class vnl_matrix; //-------------------------------------------------------------------------------- #ifndef DOXYGEN_SHOULD_SKIP_THIS -#define v vnl_vector -#define m vnl_matrix +# define v vnl_vector +# define m vnl_matrix #endif // DOXYGEN_SHOULD_SKIP_THIS -template VNL_EXPORT m operator+(T const&, m const&); -template VNL_EXPORT m operator-(T const&, m const&); -template VNL_EXPORT m operator*(T const&, m const&); -template VNL_EXPORT m element_product(m const&, m const&); -template VNL_EXPORT m element_quotient(m const&, m const&); -template VNL_EXPORT T dot_product(m const&, m const&); -template VNL_EXPORT T inner_product(m const&, m const&); -template VNL_EXPORT T cos_angle(m const&, m const& ); -template VNL_EXPORT std::ostream& operator<<(std::ostream&, m const&); -template VNL_EXPORT std::istream& operator>>(std::istream&, m&); +template +VNL_EXPORT m +operator+(T const &, m const &); +template +VNL_EXPORT m +operator-(const T &, const m &); +template +VNL_EXPORT m +operator*(const T &, const m &); +template +VNL_EXPORT m +element_product(const m &, const m &); +template +VNL_EXPORT m +element_quotient(const m &, const m &); +template +VNL_EXPORT T +dot_product(const m &, const m &); +template +VNL_EXPORT T +inner_product(const m &, const m &); +template +VNL_EXPORT T +cos_angle(const m &, const m &); +template +VNL_EXPORT std::ostream & +operator<<(std::ostream &, const m &); +template +VNL_EXPORT std::istream & +operator>>(std::istream &, m &); #undef v #undef m @@ -105,40 +127,40 @@ enum VNL_EXPORT vnl_matrix_type // // Note: Use a vnl_vector with these matrices. -template +template class VNL_EXPORT vnl_matrix { - public: +public: //: Default constructor creates an empty matrix of size 0,0. vnl_matrix(); //: Construct a matrix of size r rows by c columns // Contents are unspecified. // Complexity $O(1)$ - vnl_matrix(unsigned r, unsigned c); // r rows, c cols. + vnl_matrix(unsigned r, unsigned c); // r rows, c cols. //: Construct a matrix of size r rows by c columns, and all elements equal to v0 // Complexity $O(r.c)$ - vnl_matrix(unsigned r, unsigned c, T const& v0); // r rows, c cols, value v0. + vnl_matrix(unsigned r, unsigned c, const T & v0); // r rows, c cols, value v0. //: Construct a matrix of size r rows by c columns, with a special type // Contents are specified by t // Complexity $O(r.c)$ - vnl_matrix(unsigned r, unsigned c, vnl_matrix_type t); // r rows, c cols, special type + vnl_matrix(unsigned r, unsigned c, vnl_matrix_type t); // r rows, c cols, special type //: Construct a matrix of size r rows by c columns, initialised by an automatic array // The first n elements, are initialised row-wise, to values. // Complexity $O(n)$ - vnl_matrix(unsigned r, unsigned c, unsigned n, T const values[]); // use automatic arrays. + vnl_matrix(unsigned r, unsigned c, unsigned n, const T values[]); // use automatic arrays. //: Construct a matrix of size r rows by c columns, initialised by a memory block // The values are initialise row wise from the data. // Complexity $O(r.c)$ - vnl_matrix(T const* data_block, unsigned r, unsigned c); // fill row-wise. + vnl_matrix(const T * data_block, unsigned r, unsigned c); // fill row-wise. //: Copy construct a matrix // Complexity $O(r.c)$ - vnl_matrix(vnl_matrix const&); // from another matrix. + vnl_matrix(const vnl_matrix &); // from another matrix. // NOTE: move-assignment must be allowed to throw an exception, because we need to maintain // backwards compatibility and the move-construction & move-aasignment @@ -147,49 +169,78 @@ class VNL_EXPORT vnl_matrix //: Move-constructor. vnl_matrix(vnl_matrix &&); //: Move-assignment operator - vnl_matrix& operator=(vnl_matrix&& rhs); + vnl_matrix & + operator=(vnl_matrix && rhs); //: Matrix destructor virtual ~vnl_matrix(); -// Basic 2D-Array functionality------------------------------------------- + // Basic 2D-Array functionality------------------------------------------- //: Return the total number of elements stored by the matrix. // This equals rows() * cols() - inline unsigned int size() const { return this->num_rows*this->num_cols; } + inline unsigned int + size() const + { + return this->num_rows * this->num_cols; + } //: Return the number of rows. - inline unsigned int rows() const { return this->num_rows; } + inline unsigned int + rows() const + { + return this->num_rows; + } //: Return the number of columns. // A synonym for columns(). - inline unsigned int cols() const { return this->num_cols; } + inline unsigned int + cols() const + { + return this->num_cols; + } //: Return the number of columns. // A synonym for cols(). - inline unsigned int columns() const { return this->num_cols; } + inline unsigned int + columns() const + { + return this->num_cols; + } //: set element with boundary checks if error checking is on. - inline void put(unsigned r, unsigned c, T const&); + inline void + put(unsigned r, unsigned c, const T &); //: get element with boundary checks if error checking is on. - inline T get(unsigned r, unsigned c) const; + inline T + get(unsigned r, unsigned c) const; //: return pointer to given row // No boundary checking here. - T * operator[](unsigned r) { return data[r]; } + T * + operator[](unsigned r) + { + return data[r]; + } //: return pointer to given row // No boundary checking here. - T const * operator[](unsigned r) const { return data[r]; } + const T * + operator[](unsigned r) const + { + return data[r]; + } //: Access an element for reading or writing // There are assert style boundary checks - #define NDEBUG to turn them off. - T & operator()(unsigned r, unsigned c); + T & + operator()(unsigned r, unsigned c); //: Access an element for reading // There are assert style boundary checks - #define NDEBUG to turn them off. - T const & operator()(unsigned r, unsigned c) const; + const T & + operator()(unsigned r, unsigned c) const; // ----------------------- Filling and copying ----------------------- @@ -206,7 +257,8 @@ class VNL_EXPORT vnl_matrix // \code // f(vnl_matrix(5,5,1.0).normalize_columns()); // \endcode - vnl_matrix& fill(T const&); + vnl_matrix & + fill(const T &); //: Sets all diagonal elements of matrix to specified value; returns "*this". // Complexity $O(\min(r,c))$ @@ -220,13 +272,15 @@ class VNL_EXPORT vnl_matrix // \code // f(vnl_matrix(3,3).fill_diagonal(5)); // \endcode - vnl_matrix& fill_diagonal(T const&); + vnl_matrix & + fill_diagonal(const T &); //: Sets the diagonal elements of this matrix to the specified list of values. // Returning "*this" allows "chaining" two or more operations: see the // reasoning (and the examples) in the documentation for method // fill_diagonal(). - vnl_matrix& set_diagonal(vnl_vector const&); + vnl_matrix & + set_diagonal(const vnl_vector &); //: Fills (laminates) this matrix with the given data, then returns it. // We assume that the argument points to a contiguous rows*cols array, stored rowwise. @@ -241,58 +295,83 @@ class VNL_EXPORT vnl_matrix // \code // f(vnl_matrix(3,3).copy_in(array)); // \endcode - vnl_matrix& copy_in(T const *); + vnl_matrix & + copy_in(const T *); //: Fills (laminates) this matrix with the given data, then returns it. // A synonym for copy_in() - vnl_matrix& set(T const *d) { return copy_in(d); } + vnl_matrix & + set(const T * d) + { + return copy_in(d); + } //: Fills the given array with this matrix. // We assume that the argument points to a contiguous rows*cols array, stored rowwise. // No bounds checking on the array. - void copy_out(T *) const; + void + copy_out(T *) const; //: Set all elements to value v // Complexity $O(r.c)$ - vnl_matrix& operator=(T const&v) { fill(v); return *this; } + vnl_matrix & + operator=(const T & v) + { + fill(v); + return *this; + } //: Copies all elements of rhs matrix into lhs matrix. // Complexity $O(\min(r,c))$ - vnl_matrix& operator=(vnl_matrix const&); + vnl_matrix & + operator=(const vnl_matrix &); // ----------------------- Arithmetic -------------------------------- // note that these functions should not pass scalar as a const&. // Look what would happen to A /= A(0,0). //: Add rhs to each element of lhs matrix in situ - vnl_matrix& operator+=(T value); + vnl_matrix & + operator+=(T value); //: Subtract rhs from each element of lhs matrix in situ - vnl_matrix& operator-=(T value); + vnl_matrix & + operator-=(T value); //: Scalar multiplication in situ of lhs matrix by rhs - vnl_matrix& operator*=(T value); + vnl_matrix & + operator*=(T value); //: Scalar division of lhs matrix in situ by rhs - vnl_matrix& operator/=(T value); + vnl_matrix & + operator/=(T value); //: Add rhs to lhs matrix in situ - vnl_matrix& operator+=(vnl_matrix const&); + vnl_matrix & + operator+=(const vnl_matrix &); //: Subtract rhs from lhs matrix in situ - vnl_matrix& operator-=(vnl_matrix const&); + vnl_matrix & + operator-=(const vnl_matrix &); //: Multiply lhs matrix in situ by rhs - vnl_matrix& operator*=(vnl_matrix const&rhs) { return *this = (*this) * rhs; } + vnl_matrix & + operator*=(const vnl_matrix & rhs) + { + return *this = (*this) * rhs; + } //: Negate all elements of matrix - vnl_matrix::signed_t> operator-() const; + vnl_matrix::signed_t> + operator-() const; //: Add rhs to each element of lhs matrix and return result in new matrix - vnl_matrix operator+(T const& v) const { + vnl_matrix + operator+(const T & v) const + { vnl_matrix result(this->rows(), this->cols()); const unsigned int n = this->num_rows * this->num_cols; - T const *m = this->data[0]; - T *dst = result.data[0]; + const T * m = this->data[0]; + T * dst = result.data[0]; for (unsigned int i = 0; i < n; ++i) dst[i] = T(m[i] + v); @@ -300,11 +379,13 @@ class VNL_EXPORT vnl_matrix } //: Subtract rhs from each element of lhs matrix and return result in new matrix - vnl_matrix operator-(T const& v) const { + vnl_matrix + operator-(const T & v) const + { vnl_matrix result(this->rows(), this->cols()); const unsigned int n = this->num_rows * this->num_cols; - T const *m = this->data[0]; - T *dst = result.data[0]; + const T * m = this->data[0]; + T * dst = result.data[0]; for (unsigned int i = 0; i < n; ++i) dst[i] = T(m[i] - v); @@ -312,11 +393,13 @@ class VNL_EXPORT vnl_matrix } //: Scalar multiplication of lhs matrix by rhs and return result in new matrix - vnl_matrix operator*(T const& v) const { + vnl_matrix + operator*(const T & v) const + { vnl_matrix result(this->rows(), this->cols()); const unsigned int n = this->num_rows * this->num_cols; - T const *m = this->data[0]; - T *dst = result.data[0]; + const T * m = this->data[0]; + T * dst = result.data[0]; for (unsigned int i = 0; i < n; ++i) dst[i] = T(m[i] * v); @@ -324,11 +407,13 @@ class VNL_EXPORT vnl_matrix } //: Scalar division of lhs matrix by rhs and return result in new matrix - vnl_matrix operator/(T const& v) const { + vnl_matrix + operator/(const T & v) const + { vnl_matrix result(this->rows(), this->cols()); const unsigned int n = this->num_rows * this->num_cols; - T const *m = this->data[0]; - T *dst = result.data[0]; + const T * m = this->data[0]; + T * dst = result.data[0]; for (unsigned int i = 0; i < n; ++i) dst[i] = T(m[i] / v); @@ -336,59 +421,66 @@ class VNL_EXPORT vnl_matrix } //: Matrix add rhs to lhs matrix and return result in new matrix - vnl_matrix operator+(vnl_matrix const& rhs) const + vnl_matrix + operator+(const vnl_matrix & rhs) const { - vnl_matrix result(rhs.rows(),rhs.cols()); + vnl_matrix result(rhs.rows(), rhs.cols()); #ifndef NDEBUG if (this->num_rows != rhs.num_rows || this->num_cols != rhs.num_cols) - vnl_error_matrix_dimension ("vnl_matrix::operator+", this->num_rows, this->num_cols, rhs.num_rows, rhs.num_cols); + vnl_error_matrix_dimension( + "vnl_matrix::operator+", this->num_rows, this->num_cols, rhs.num_rows, rhs.num_cols); #endif const unsigned int n = this->num_rows * this->num_cols; - T const *a = this->data[0]; - T const *b = rhs.data[0]; - T *dst = result.data[0]; + const T * a = this->data[0]; + const T * b = rhs.data[0]; + T * dst = result.data[0]; - for (unsigned int i=0; i operator-(vnl_matrix const& rhs) const + vnl_matrix + operator-(const vnl_matrix & rhs) const { - vnl_matrix result(rhs.rows(),rhs.cols()); + vnl_matrix result(rhs.rows(), rhs.cols()); #ifndef NDEBUG if (this->num_rows != rhs.num_rows || this->num_cols != rhs.num_cols) - vnl_error_matrix_dimension ("vnl_matrix::operator+", this->num_rows, this->num_cols, rhs.num_rows, rhs.num_cols); + vnl_error_matrix_dimension( + "vnl_matrix::operator+", this->num_rows, this->num_cols, rhs.num_rows, rhs.num_cols); #endif const unsigned int n = this->num_rows * this->num_cols; - T const *a = this->data[0]; - T const *b = rhs.data[0]; - T *dst = result.data[0]; + const T * a = this->data[0]; + const T * b = rhs.data[0]; + T * dst = result.data[0]; - for (unsigned int i=0; i operator*(vnl_matrix const& rhs) const + vnl_matrix + operator*(const vnl_matrix & rhs) const { vnl_matrix result(this->rows(), rhs.cols()); #ifndef NDEBUG if (this->num_cols != rhs.num_rows) - vnl_error_matrix_dimension("vnl_matrix::operator*", this->num_rows, this->num_cols, - rhs.num_rows, rhs.num_cols); + vnl_error_matrix_dimension( + "vnl_matrix::operator*", this->num_rows, this->num_cols, rhs.num_rows, rhs.num_cols); #endif const unsigned int l = this->num_rows; const unsigned int m = this->num_cols; // == rhs.num_rows const unsigned int n = rhs.num_cols; - for (unsigned int i = 0; i < l; ++i) { - for (unsigned int k = 0; k < n; ++k) { - T sum{0}; + for (unsigned int i = 0; i < l; ++i) + { + for (unsigned int k = 0; k < n; ++k) + { + T sum{ 0 }; for (unsigned int j = 0; j < m; ++j) sum += T(this->data[i][j] * rhs.data[j][k]); result.data[i][k] = sum; @@ -403,84 +495,103 @@ class VNL_EXPORT vnl_matrix vnl_matrix apply(T (*f)(T)) const; //: Make a new matrix by applying function to each element. - vnl_matrix apply(T (*f)(T const&)) const; + vnl_matrix apply(T (*f)(const T &)) const; //: Make a vector by applying a function across rows. - vnl_vector apply_rowwise(T (*f)(vnl_vector const&)) const; + vnl_vector apply_rowwise(T (*f)(const vnl_vector &)) const; //: Make a vector by applying a function across columns. - vnl_vector apply_columnwise(T (*f)(vnl_vector const&)) const; + vnl_vector apply_columnwise(T (*f)(const vnl_vector &)) const; //: Return transpose - vnl_matrix transpose() const; + vnl_matrix + transpose() const; //: Return conjugate transpose - vnl_matrix conjugate_transpose() const; + vnl_matrix + conjugate_transpose() const; //: Set values of this matrix to those of M, starting at [top,left] - vnl_matrix& update(vnl_matrix const&, unsigned top=0, unsigned left=0); + vnl_matrix & + update(const vnl_matrix &, unsigned top = 0, unsigned left = 0); //: Set the elements of the i'th column to v[i] (No bounds checking) - vnl_matrix& set_column(unsigned i, T const * v); + vnl_matrix & + set_column(unsigned i, const T * v); //: Set the elements of the i'th column to value, then return *this. - vnl_matrix& set_column(unsigned i, T value ); + vnl_matrix & + set_column(unsigned i, T value); //: Set j-th column to v, then return *this. - vnl_matrix& set_column(unsigned j, vnl_vector const& v); + vnl_matrix & + set_column(unsigned j, const vnl_vector & v); //: Set columns to those in M, starting at starting_column, then return *this. - vnl_matrix& set_columns(unsigned starting_column, vnl_matrix const& M); + vnl_matrix & + set_columns(unsigned starting_column, const vnl_matrix & M); //: Set the elements of the i'th row to v[i] (No bounds checking) - vnl_matrix& set_row(unsigned i, T const * v); + vnl_matrix & + set_row(unsigned i, const T * v); //: Set the elements of the i'th row to value, then return *this. - vnl_matrix& set_row(unsigned i, T value ); + vnl_matrix & + set_row(unsigned i, T value); //: Set the i-th row - vnl_matrix& set_row(unsigned i, vnl_vector const&); + vnl_matrix & + set_row(unsigned i, const vnl_vector &); //: Extract a sub-matrix of size r x c, starting at (top,left) // Thus it contains elements [top,top+r-1][left,left+c-1] - vnl_matrix extract(unsigned r, unsigned c, - unsigned top=0, unsigned left=0) const; + vnl_matrix + extract(unsigned r, unsigned c, unsigned top = 0, unsigned left = 0) const; //: Extract a sub-matrix starting at (top,left) // // The output is stored in \a sub_matrix, and it should have the // required size on entry. Thus the result will contain elements // [top,top+sub_matrix.rows()-1][left,left+sub_matrix.cols()-1] - void extract ( vnl_matrix& sub_matrix, - unsigned top=0, unsigned left=0) const; + void + extract(vnl_matrix & sub_matrix, unsigned top = 0, unsigned left = 0) const; //: Get a vector equal to the given row - vnl_vector get_row(unsigned r) const; + vnl_vector + get_row(unsigned r) const; //: Get a vector equal to the given column - vnl_vector get_column(unsigned c) const; + vnl_vector + get_column(unsigned c) const; //: Get a matrix composed of rows from the indices specified in the supplied vector. - vnl_matrix get_rows(vnl_vector i) const; + vnl_matrix + get_rows(vnl_vector i) const; //: Get a matrix composed of columns from the indices specified in the supplied vector. - vnl_matrix get_columns(vnl_vector i) const; + vnl_matrix + get_columns(vnl_vector i) const; //: Get n rows beginning at rowstart - vnl_matrix get_n_rows(unsigned rowstart, unsigned n) const; + vnl_matrix + get_n_rows(unsigned rowstart, unsigned n) const; //: Get n columns beginning at colstart - vnl_matrix get_n_columns(unsigned colstart, unsigned n) const; + vnl_matrix + get_n_columns(unsigned colstart, unsigned n) const; //: Return a vector with the content of the (main) diagonal - vnl_vector get_diagonal() const; + vnl_vector + get_diagonal() const; //: Flatten row-major (C-style) - vnl_vector flatten_row_major() const; + vnl_vector + flatten_row_major() const; //: Flatten column-major (Fortran-style) - vnl_vector flatten_column_major() const; + vnl_vector + flatten_column_major() const; // ==== mutators ==== @@ -496,7 +607,8 @@ class VNL_EXPORT vnl_matrix // M.set_identity().scale_row(0,3).scale_column(1,2); // \endcode // If the matrix is not square, anyhow set main diagonal to 1, the rest to 0. - vnl_matrix& set_identity(); + vnl_matrix & + set_identity(); //: Transposes this matrix efficiently, and returns it. // Returning "*this" allows "chaining" two or more operations: @@ -504,7 +616,8 @@ class VNL_EXPORT vnl_matrix // \code // M.copy_in(array).inplace_transpose(); // \endcode - vnl_matrix& inplace_transpose(); + vnl_matrix & + inplace_transpose(); //: Reverses the order of rows, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -512,7 +625,8 @@ class VNL_EXPORT vnl_matrix // \code // M.flipud().fliplr(); // \endcode - vnl_matrix& flipud(); + vnl_matrix & + flipud(); //: Reverses the order of columns, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -520,7 +634,8 @@ class VNL_EXPORT vnl_matrix // \code // M.flipud().fliplr(); // \endcode - vnl_matrix& fliplr(); + vnl_matrix & + fliplr(); //: Normalizes each row so it is a unit vector, and returns "*this". // Zero rows are not modified @@ -534,7 +649,8 @@ class VNL_EXPORT vnl_matrix // \code // f(vnl_matrix(5,5,1.0).normalize_rows()); // \endcode - vnl_matrix& normalize_rows(); + vnl_matrix & + normalize_rows(); //: Normalizes each column so it is a unit vector, and returns "*this". // Zero columns are not modified @@ -548,7 +664,8 @@ class VNL_EXPORT vnl_matrix // \code // f(vnl_matrix(5,5,1.0).normalize_columns()); // \endcode - vnl_matrix& normalize_columns(); + vnl_matrix & + normalize_columns(); //: Scales elements in given row by a factor T, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -556,7 +673,8 @@ class VNL_EXPORT vnl_matrix // \code // M.set_identity().scale_row(0,3).scale_column(1,2); // \endcode - vnl_matrix& scale_row(unsigned row, T value); + vnl_matrix & + scale_row(unsigned row, T value); //: Scales elements in given column by a factor T, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -564,88 +682,156 @@ class VNL_EXPORT vnl_matrix // \code // M.set_identity().scale_row(0,3).scale_column(1,2); // \endcode - vnl_matrix& scale_column(unsigned col, T value); + vnl_matrix & + scale_column(unsigned col, T value); //: Swap this matrix with that matrix - void swap(vnl_matrix & that) noexcept; + void + swap(vnl_matrix & that) noexcept; //: Type def for norms. typedef typename vnl_c_vector::abs_t abs_t; //: Return sum of absolute values of elements - abs_t array_one_norm() const { return vnl_c_vector::one_norm(begin(), size()); } + abs_t + array_one_norm() const + { + return vnl_c_vector::one_norm(begin(), size()); + } //: Return square root of sum of squared absolute element values - abs_t array_two_norm() const { return vnl_c_vector::two_norm(begin(), size()); } + abs_t + array_two_norm() const + { + return vnl_c_vector::two_norm(begin(), size()); + } //: Return largest absolute element value - abs_t array_inf_norm() const { return vnl_c_vector::inf_norm(begin(), size()); } + abs_t + array_inf_norm() const + { + return vnl_c_vector::inf_norm(begin(), size()); + } //: Return sum of absolute values of elements - abs_t absolute_value_sum() const { return array_one_norm(); } + abs_t + absolute_value_sum() const + { + return array_one_norm(); + } //: Return largest absolute value - abs_t absolute_value_max() const { return array_inf_norm(); } + abs_t + absolute_value_max() const + { + return array_inf_norm(); + } // $ || M ||_1 := \max_j \sum_i | M_{ij} | $ - abs_t operator_one_norm() const; + abs_t + operator_one_norm() const; // $ || M ||_\inf := \max_i \sum_j | M_{ij} | $ - abs_t operator_inf_norm() const; + abs_t + operator_inf_norm() const; //: Return Frobenius norm of matrix (sqrt of sum of squares of its elements) - abs_t frobenius_norm() const { return vnl_c_vector::two_norm(begin(), size()); } + abs_t + frobenius_norm() const + { + return vnl_c_vector::two_norm(begin(), size()); + } //: Return Frobenius norm of matrix (sqrt of sum of squares of its elements) - abs_t fro_norm() const { return frobenius_norm(); } + abs_t + fro_norm() const + { + return frobenius_norm(); + } //: Return RMS of all elements - abs_t rms() const { return vnl_c_vector::rms_norm(begin(), size()); } + abs_t + rms() const + { + return vnl_c_vector::rms_norm(begin(), size()); + } //: Return minimum value of elements - T min_value() const { return vnl_c_vector::min_value(begin(), size()); } + T + min_value() const + { + return vnl_c_vector::min_value(begin(), size()); + } //: Return maximum value of elements - T max_value() const { return vnl_c_vector::max_value(begin(), size()); } + T + max_value() const + { + return vnl_c_vector::max_value(begin(), size()); + } //: Return location of minimum value of elements - unsigned arg_min() const { return vnl_c_vector::arg_min(begin(), size()); } + unsigned + arg_min() const + { + return vnl_c_vector::arg_min(begin(), size()); + } //: Return location of maximum value of elements - unsigned arg_max() const { return vnl_c_vector::arg_max(begin(), size()); } + unsigned + arg_max() const + { + return vnl_c_vector::arg_max(begin(), size()); + } //: Return mean of all matrix elements - T mean() const { return vnl_c_vector::mean(begin(), size()); } + T + mean() const + { + return vnl_c_vector::mean(begin(), size()); + } // predicates //: Return true iff the size is zero. - bool empty() const { return !data || !num_rows || !num_cols; } + bool + empty() const + { + return !data || !num_rows || !num_cols; + } //: Return true if all elements equal to identity. - bool is_identity() const; + bool + is_identity() const; //: Return true if all elements equal to identity, within given tolerance - bool is_identity(double tol) const; + bool + is_identity(double tol) const; //: Return true if all elements equal to zero. - bool is_zero() const; + bool + is_zero() const; //: Return true if all elements equal to zero, within given tolerance - bool is_zero(double tol) const; + bool + is_zero(double tol) const; //: Return true if all elements of both matrices are equal, within given tolerance - bool is_equal(vnl_matrix const& rhs, double tol) const; + bool + is_equal(const vnl_matrix & rhs, double tol) const; //: Return true if finite - bool is_finite() const; + bool + is_finite() const; //: Return true if matrix contains NaNs - bool has_nans() const; + bool + has_nans() const; //: abort if size is not as expected // This function does or tests nothing if NDEBUG is defined - void assert_size(unsigned VXL_USED_IN_DEBUG(r), unsigned VXL_USED_IN_DEBUG(c)) const + void + assert_size(unsigned VXL_USED_IN_DEBUG(r), unsigned VXL_USED_IN_DEBUG(c)) const { #ifndef NDEBUG assert_size_internal(r, c); @@ -653,7 +839,8 @@ class VNL_EXPORT vnl_matrix } //: abort if matrix contains any INFs or NANs. // This function does or tests nothing if NDEBUG is defined - void assert_finite() const + void + assert_finite() const { #ifndef NDEBUG assert_finite_internal(); @@ -662,103 +849,161 @@ class VNL_EXPORT vnl_matrix ////----------------------- Input/Output ---------------------------- - //: Read a vnl_matrix from an ascii std::istream, automatically determining file size if the input matrix has zero size. - static vnl_matrix read(std::istream& s); + //: Read a vnl_matrix from an ascii std::istream, automatically determining file size if the input matrix has zero + //: size. + static vnl_matrix + read(std::istream & s); - // : Read a vnl_matrix from an ascii std::istream, automatically determining file size if the input matrix has zero size. - bool read_ascii(std::istream& s); + // : Read a vnl_matrix from an ascii std::istream, automatically determining file size if the input matrix has zero + // size. + bool + read_ascii(std::istream & s); //-------------------------------------------------------------------------------- //: Access the contiguous block storing the elements in the matrix row-wise. O(1). // 1d array, row-major order. - T const* data_block() const { return data[0]; } + const T * + data_block() const + { + return data[0]; + } //: Access the contiguous block storing the elements in the matrix row-wise. O(1). // 1d array, row-major order. - T * data_block() { return data[0]; } + T * + data_block() + { + return data[0]; + } //: Access the 2D array, so that elements can be accessed with array[row][col] directly. // 2d array, [row][column]. - T const* const* data_array() const { return data; } + const T * const * + data_array() const + { + return data; + } //: Access the 2D array, so that elements can be accessed with array[row][col] directly. // 2d array, [row][column]. - T * * data_array() { return data; } + T ** + data_array() + { + return data; + } typedef T element_type; //: Iterators - typedef T *iterator; + typedef T * iterator; //: Iterator pointing to start of data - iterator begin() { return data?data[0]:nullptr; } + iterator + begin() + { + return data ? data[0] : nullptr; + } //: Iterator pointing to element beyond end of data - iterator end() { return data?data[0]+num_rows*num_cols:nullptr; } + iterator + end() + { + return data ? data[0] + num_rows * num_cols : nullptr; + } //: Const iterators - typedef T const *const_iterator; + typedef const T * const_iterator; //: Iterator pointing to start of data - const_iterator begin() const { return data?data[0]:nullptr; } + const_iterator + begin() const + { + return data ? data[0] : nullptr; + } //: Iterator pointing to element beyond end of data - const_iterator end() const { return data?data[0]+num_rows*num_cols:nullptr; } + const_iterator + end() const + { + return data ? data[0] + num_rows * num_cols : nullptr; + } //: Return a reference to this. // Useful in code which would prefer not to know if its argument // is a matrix, matrix_ref or a matrix_fixed. Note that it doesn't // return a matrix_ref, so it's only useful in templates or macros. - vnl_matrix const& as_ref() const { return *this; } + const vnl_matrix & + as_ref() const + { + return *this; + } //: Return a reference to this. - vnl_matrix& as_ref() { return *this; } + vnl_matrix & + as_ref() + { + return *this; + } //-------------------------------------------------------------------------------- //: Return true if *this == rhs - bool operator_eq(vnl_matrix const & rhs) const; + bool + operator_eq(const vnl_matrix & rhs) const; //: Equality operator - bool operator==(vnl_matrix const &that) const { return this->operator_eq(that); } + bool + operator==(const vnl_matrix & that) const + { + return this->operator_eq(that); + } //: Inequality operator - bool operator!=(vnl_matrix const &that) const { return !this->operator_eq(that); } + bool + operator!=(const vnl_matrix & that) const + { + return !this->operator_eq(that); + } //: Print matrix to os in some hopefully sensible format - void print(std::ostream& os) const; + void + print(std::ostream & os) const; //: Make the matrix as if it had been default-constructed. - void clear(); + void + clear(); //: Resize to r rows by c columns. Old data lost. // Returns true if size changed. - bool set_size(unsigned r, unsigned c); + bool + set_size(unsigned r, unsigned c); -//-------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------- - protected: - vnl_matrix( unsigned ext_num_rows, unsigned ext_num_cols, - T * continuous_external_memory_block, bool manage_own_memory ) - : num_rows{ ext_num_rows} - , num_cols{ ext_num_cols} - , m_LetArrayManageMemory{ manage_own_memory } +protected: + vnl_matrix(unsigned ext_num_rows, unsigned ext_num_cols, T * continuous_external_memory_block, bool manage_own_memory) + : num_rows{ ext_num_rows } + , num_cols{ ext_num_cols } + , m_LetArrayManageMemory{ manage_own_memory } { this->data = vnl_c_vector::allocate_Tptr(num_rows); for (unsigned int i = 0; i < num_rows; ++i) this->data[i] = continuous_external_memory_block + i * num_cols; } - void assert_size_internal(unsigned r, unsigned c) const; - void assert_finite_internal() const; + void + assert_size_internal(unsigned r, unsigned c) const; + void + assert_finite_internal() const; //: Delete data - void destroy(); + void + destroy(); -#if ! VXL_USE_HISTORICAL_PROTECTED_IVARS - private: +#if !VXL_USE_HISTORICAL_PROTECTED_IVARS +private: #endif - unsigned num_rows{0}; // Number of rows - unsigned num_cols{0}; // Number of columns - T** data{nullptr}; // Pointer to the vnl_matrix - bool m_LetArrayManageMemory{true}; + unsigned num_rows{ 0 }; // Number of rows + unsigned num_cols{ 0 }; // Number of columns + T ** data{ nullptr }; // Pointer to the vnl_matrix + bool m_LetArrayManageMemory{ true }; }; @@ -768,9 +1013,9 @@ class VNL_EXPORT vnl_matrix //: Returns the value of the element at specified row and column. O(1). // Checks for valid range of indices. -template -inline T vnl_matrix -::get(unsigned r, unsigned c) const +template +inline T +vnl_matrix::get(unsigned r, unsigned c) const { #if VNL_CONFIG_CHECK_BOUNDS if (r >= this->num_rows) // If invalid size specified @@ -784,9 +1029,9 @@ ::get(unsigned r, unsigned c) const //: Puts value into element at specified row and column. O(1). // Checks for valid range of indices. -template -inline void vnl_matrix -::put(unsigned r, unsigned c, T const& v) +template +inline void +vnl_matrix::put(unsigned r, unsigned c, const T & v) { #if VNL_CONFIG_CHECK_BOUNDS if (r >= this->num_rows) // If invalid size specified @@ -794,7 +1039,7 @@ ::put(unsigned r, unsigned c, T const& v) if (c >= this->num_cols) // If invalid size specified vnl_error_matrix_col_index("put", c); // Raise exception #endif - this->data[r][c] = v; // Assign data value + this->data[r][c] = v; // Assign data value } @@ -802,23 +1047,29 @@ ::put(unsigned r, unsigned c, T const& v) //: // \relatesalso vnl_matrix -template -inline vnl_matrix operator*(T const& value, vnl_matrix const& m) +template +inline vnl_matrix +operator*(const T & value, const vnl_matrix & m) { - return m*value; + return m * value; } //: // \relatesalso vnl_matrix -template -inline vnl_matrix operator+(T const& value, vnl_matrix const& m) +template +inline vnl_matrix +operator+(const T & value, const vnl_matrix & m) { - return m+value; + return m + value; } //: Swap two matrices // \relatesalso vnl_matrix -template -inline void swap(vnl_matrix &A, vnl_matrix &B) noexcept { A.swap(B); } +template +inline void +swap(vnl_matrix & A, vnl_matrix & B) noexcept +{ + A.swap(B); +} #endif // vnl_matrix_h_ diff --git a/core/vnl/vnl_matrix.hxx b/core/vnl/vnl_matrix.hxx index 51e5cb0839e..b7c5a0ca78e 100644 --- a/core/vnl/vnl_matrix.hxx +++ b/core/vnl/vnl_matrix.hxx @@ -98,110 +98,119 @@ //-------------------------------------------------------------------------------- // This macro allocates and initializes the dynamic storage used by a vnl_matrix. -#define vnl_matrix_alloc_blah() \ -do { /* Macro needs to be a single statement to allow semicolon at macro end */ \ - assert(this->m_LetArrayManageMemory); /*Resizing memory requires management rights */ \ - if (this->num_rows && this->num_cols) { \ - /* Allocate memory to hold the row pointers */ \ - this->data = vnl_c_vector::allocate_Tptr(this->num_rows); \ - /* Allocate memory to hold the elements of the matrix */ \ - T* elmns = vnl_c_vector::allocate_T(this->num_rows * this->num_cols); \ - /* Fill in the array of row pointers */ \ - for (unsigned int i = 0; i < this->num_rows; ++ i) \ - this->data[i] = elmns + i*this->num_cols; \ - } \ - else { \ - /* This is to make sure .begin() and .end() work for 0xN matrices: */ \ - this->data = vnl_c_vector::allocate_Tptr(1);\ - this->data[0] = nullptr; \ - } \ -} while(false) +#define vnl_matrix_alloc_blah() \ + do \ + { /* Macro needs to be a single statement to allow semicolon at macro end */ \ + assert(this->m_LetArrayManageMemory); /*Resizing memory requires management rights */ \ + if (this->num_rows && this->num_cols) \ + { \ + /* Allocate memory to hold the row pointers */ \ + this->data = vnl_c_vector::allocate_Tptr(this->num_rows); \ + /* Allocate memory to hold the elements of the matrix */ \ + T * elmns = vnl_c_vector::allocate_T(this->num_rows * this->num_cols); \ + /* Fill in the array of row pointers */ \ + for (unsigned int i = 0; i < this->num_rows; ++i) \ + this->data[i] = elmns + i * this->num_cols; \ + } \ + else \ + { \ + /* This is to make sure .begin() and .end() work for 0xN matrices: */ \ + this->data = vnl_c_vector::allocate_Tptr(1); \ + this->data[0] = nullptr; \ + } \ + } while (false) //: Default constructor creates an empty matrix of size 0,0. -template< class T > -vnl_matrix< T >::vnl_matrix() - : num_rows( 0 ) - , num_cols( 0 ) - , data( nullptr ) -{ -} +template +vnl_matrix::vnl_matrix() + : data(nullptr) +{} //: Creates a matrix with given number of rows and columns. // Elements are not initialized. O(m*n). template -vnl_matrix::vnl_matrix (unsigned rowz, unsigned colz) -: num_rows(rowz), num_cols(colz) +vnl_matrix::vnl_matrix(unsigned rowz, unsigned colz) + : num_rows(rowz) + , num_cols(colz) { vnl_matrix_alloc_blah(); } //: Creates a matrix with given number of rows and columns, and initialize all elements to value. O(m*n). template -vnl_matrix::vnl_matrix (unsigned rowz, unsigned colz, T const& value) -: num_rows(rowz), num_cols(colz) +vnl_matrix::vnl_matrix(unsigned rowz, unsigned colz, const T & value) + : num_rows(rowz) + , num_cols(colz) { vnl_matrix_alloc_blah(); - std::fill_n( this->data[0], rowz * colz, value ); + std::fill_n(this->data[0], rowz * colz, value); } //: r rows, c cols, special type. Currently implements "identity" and "null". template vnl_matrix::vnl_matrix(unsigned r, unsigned c, vnl_matrix_type t) -: num_rows(r), num_cols(c) + : num_rows(r) + , num_cols(c) { vnl_matrix_alloc_blah(); - switch (t) { - case vnl_matrix_identity: - assert(r == c); - for (unsigned int i = 0; i < r; ++ i) - for (unsigned int j = 0; j < c; ++ j) - this->data[i][j] = (i==j) ? T(1) : T(0); - break; - case vnl_matrix_null: - std::fill_n( this->data[0], r * c, T(0) ); - break; - default: - assert(false); - break; + switch (t) + { + case vnl_matrix_identity: + assert(r == c); + for (unsigned int i = 0; i < r; ++i) + for (unsigned int j = 0; j < c; ++j) + this->data[i][j] = (i == j) ? T(1) : T(0); + break; + case vnl_matrix_null: + std::fill_n(this->data[0], r * c, T(0)); + break; + default: + assert(false); + break; } } #if 1 // fsm: who uses this? //: Creates a matrix with given dimension (rows, cols) and initialize first n elements, row-wise, to values. O(m*n). template -vnl_matrix::vnl_matrix (unsigned rowz, unsigned colz, unsigned n, T const values[]) -: num_rows(rowz), num_cols(colz) +vnl_matrix::vnl_matrix(unsigned rowz, unsigned colz, unsigned n, const T values[]) + : num_rows(rowz) + , num_cols(colz) { vnl_matrix_alloc_blah(); - if (n > rowz*colz) - n = rowz*colz; - std::copy( values, values + n, this->data[0] ); + if (n > rowz * colz) + n = rowz * colz; + std::copy(values, values + n, this->data[0]); } #endif //: Creates a matrix from a block array of data, stored row-wise. // O(m*n). template -vnl_matrix::vnl_matrix (T const* datablck, unsigned rowz, unsigned colz) -: num_rows(rowz), num_cols(colz) +vnl_matrix::vnl_matrix(const T * datablck, unsigned rowz, unsigned colz) + : num_rows(rowz) + , num_cols(colz) { vnl_matrix_alloc_blah(); - std::copy( datablck, datablck + rowz * colz, this->data[0] ); + std::copy(datablck, datablck + rowz * colz, this->data[0]); } //: Creates a new matrix and copies all the elements. // O(m*n). template -vnl_matrix::vnl_matrix (vnl_matrix const& from) -: num_rows(from.num_rows), num_cols(from.num_cols) +vnl_matrix::vnl_matrix(const vnl_matrix & from) + : num_rows(from.num_rows) + , num_cols(from.num_cols) { - if (from.data && from.data[0]) { + if (from.data && from.data[0]) + { vnl_matrix_alloc_blah(); - T const *src = from.data[0]; - std::copy( src, src + this->num_rows * this->num_cols, this->data[0] ); + const T * src = from.data[0]; + std::copy(src, src + this->num_rows * this->num_cols, this->data[0]); } - else { + else + { num_rows = 0; num_cols = 0; data = nullptr; @@ -209,35 +218,35 @@ vnl_matrix::vnl_matrix (vnl_matrix const& from) } //: Move-constructs a vector. O(1). -template -vnl_matrix::vnl_matrix(vnl_matrix&& rhs) +template +vnl_matrix::vnl_matrix(vnl_matrix && rhs) { // Copy the data pointer and its length from the source object. this->operator=(std::move(rhs)); } //: Move-assigns rhs vector into lhs vector. O(1). -template -vnl_matrix& vnl_matrix::operator=(vnl_matrix&& rhs) +template +vnl_matrix & +vnl_matrix::operator=(vnl_matrix && rhs) { // Self-assignment detection if (&rhs != this) { - if(!rhs.m_LetArrayManageMemory) + if (!rhs.m_LetArrayManageMemory) { this->operator=(rhs); // Call non-move assignment operator. return *this; } - else if(!this->m_LetArrayManageMemory) + else if (!this->m_LetArrayManageMemory) { /* If `this` is managing own memory, then you are not allowed * to replace the data pointer * This code only works when the object is an vnl_matrix_ref correctly sized. * Undefined behavior if this->m_LetArrayManageMemory==false, * and rows,cols are not the same between `this` and rhs. */ - assert( (rhs.num_rows == this->num_rows ) - && ( rhs.num_cols == this->num_cols ) ); - std::copy( rhs.begin(), rhs.end(), this->begin() ); + assert((rhs.num_rows == this->num_rows) && (rhs.num_cols == this->num_cols)); + std::copy(rhs.begin(), rhs.end(), this->begin()); } else { @@ -264,7 +273,8 @@ template vnl_matrix::~vnl_matrix() { // save some fcalls if data is 0 (i.e. in matrix_fixed) - if (data) destroy(); + if (data) + destroy(); } //: Frees up the dynamic storage used by matrix. @@ -300,9 +310,11 @@ vnl_matrix::destroy() } template -void vnl_matrix::clear() +void +vnl_matrix::clear() { - if (data) { + if (data) + { destroy(); num_rows = 0; num_cols = 0; @@ -315,21 +327,26 @@ void vnl_matrix::clear() // Returns true if size is changed. template -bool vnl_matrix::set_size (unsigned rowz, unsigned colz) +bool +vnl_matrix::set_size(unsigned rowz, unsigned colz) { - if (this->data) { + if (this->data) + { // if no change in size, do not reallocate. if (this->num_rows == rowz && this->num_cols == colz) return false; // else, simply release old storage and allocate new. this->destroy(); - this->num_rows = rowz; this->num_cols = colz; + this->num_rows = rowz; + this->num_cols = colz; vnl_matrix_alloc_blah(); } - else { + else + { // This happens if the matrix is default constructed. - this->num_rows = rowz; this->num_cols = colz; + this->num_rows = rowz; + this->num_cols = colz; vnl_matrix_alloc_blah(); } @@ -343,18 +360,20 @@ bool vnl_matrix::set_size (unsigned rowz, unsigned colz) //: Sets all elements of matrix to specified value. O(m*n). template -vnl_matrix& vnl_matrix::fill (T const& value) +vnl_matrix & +vnl_matrix::fill(const T & value) { // not safe if data == NULL, due to data[0] call if (data && data[0]) - std::fill_n( this->data[0], this->num_rows * this->num_cols, value ); + std::fill_n(this->data[0], this->num_rows * this->num_cols, value); return *this; } //: Sets all diagonal elements of matrix to specified value. O(n). template -vnl_matrix& vnl_matrix::fill_diagonal (T const& value) +vnl_matrix & +vnl_matrix::fill_diagonal(const T & value) { for (unsigned int i = 0; i < this->num_rows && i < this->num_cols; ++i) this->data[i][i] = value; @@ -364,10 +383,10 @@ vnl_matrix& vnl_matrix::fill_diagonal (T const& value) //: Sets the diagonal elements of this matrix to the specified list of values. template -vnl_matrix& vnl_matrix::set_diagonal(vnl_vector const& diag) +vnl_matrix & +vnl_matrix::set_diagonal(const vnl_vector & diag) { - assert(diag.size() >= this->num_rows || - diag.size() >= this->num_cols); + assert(diag.size() >= this->num_rows || diag.size() >= this->num_cols); // The length of the diagonal of a non-square matrix is the minimum of // the matrix's width & height; that explains the "||" in the assert, // and the "&&" in the upper bound for the "for". @@ -379,25 +398,27 @@ vnl_matrix& vnl_matrix::set_diagonal(vnl_vector const& diag) //: Access an element for reading or writing // There are assert style boundary checks - #define NDEBUG to turn them off. template -T & vnl_matrix::operator()(unsigned r, unsigned c) +T & +vnl_matrix::operator()(unsigned r, unsigned c) { #if VNL_CONFIG_CHECK_BOUNDS - assert(r < rows()); // Check the row index is valid - assert(c < cols()); // Check the column index is valid + assert(r < rows()); // Check the row index is valid + assert(c < cols()); // Check the column index is valid #endif - return this->data[r][c]; + return this->data[r][c]; } //: Access an element for reading // There are assert style boundary checks - #define NDEBUG to turn them off. template -T const & vnl_matrix::operator()(unsigned r, unsigned c) const +const T & +vnl_matrix::operator()(unsigned r, unsigned c) const { #if VNL_CONFIG_CHECK_BOUNDS - assert(r < rows()); // Check the row index is valid - assert(c < cols()); // Check the column index is valid + assert(r < rows()); // Check the row index is valid + assert(c < cols()); // Check the column index is valid #endif - return this->data[r][c]; + return this->data[r][c]; } @@ -406,16 +427,21 @@ T const & vnl_matrix::operator()(unsigned r, unsigned c) const // allocated to match the dimensions of the rhs matrix. template -vnl_matrix& vnl_matrix::operator= (vnl_matrix const& rhs) +vnl_matrix & +vnl_matrix::operator=(const vnl_matrix & rhs) { - if (this != &rhs) { // make sure *this != m - if (rhs.data) { + if (this != &rhs) + { // make sure *this != m + if (rhs.data) + { this->set_size(rhs.num_rows, rhs.num_cols); - if (rhs.data[0]) { - std::copy( rhs.data[0], rhs.data[0] + this->num_rows * this->num_cols, this->data[0] ); + if (rhs.data[0]) + { + std::copy(rhs.data[0], rhs.data[0] + this->num_rows * this->num_cols, this->data[0]); } } - else { + else + { // rhs is default-constructed. clear(); } @@ -424,9 +450,11 @@ vnl_matrix& vnl_matrix::operator= (vnl_matrix const& rhs) } template -void vnl_matrix::print(std::ostream& os) const +void +vnl_matrix::print(std::ostream & os) const { - for (unsigned int i = 0; i < this->rows(); i++) { + for (unsigned int i = 0; i < this->rows(); i++) + { for (unsigned int j = 0; j < this->columns(); j++) os << this->data[i][j] << ' '; os << '\n'; @@ -437,9 +465,11 @@ void vnl_matrix::print(std::ostream& os) const // O(m*n). template -std::ostream& operator<< (std::ostream& os, vnl_matrix const& m) +std::ostream & +operator<<(std::ostream & os, const vnl_matrix & m) { - for (unsigned int i = 0; i < m.rows(); ++i) { + for (unsigned int i = 0; i < m.rows(); ++i) + { for (unsigned int j = 0; j < m.columns(); ++j) os << m(i, j) << ' '; os << '\n'; @@ -450,14 +480,16 @@ std::ostream& operator<< (std::ostream& os, vnl_matrix const& m) //: Read a vnl_matrix from an ascii std::istream. // Automatically determines file size if the input matrix has zero size. template -std::istream& operator>>(std::istream& s, vnl_matrix& M) +std::istream & +operator>>(std::istream & s, vnl_matrix & M) { M.read_ascii(s); return s; } template -vnl_matrix& vnl_matrix::operator+= (T value) +vnl_matrix & +vnl_matrix::operator+=(T value) { for (unsigned int i = 0; i < this->num_rows; i++) for (unsigned int j = 0; j < this->num_cols; j++) @@ -466,7 +498,8 @@ vnl_matrix& vnl_matrix::operator+= (T value) } template -vnl_matrix& vnl_matrix::operator-= (T value) +vnl_matrix & +vnl_matrix::operator-=(T value) { for (unsigned int i = 0; i < this->num_rows; i++) for (unsigned int j = 0; j < this->num_cols; j++) @@ -475,7 +508,8 @@ vnl_matrix& vnl_matrix::operator-= (T value) } template -vnl_matrix& vnl_matrix::operator*= (T value) +vnl_matrix & +vnl_matrix::operator*=(T value) { for (unsigned int i = 0; i < this->num_rows; i++) for (unsigned int j = 0; j < this->num_cols; j++) @@ -484,7 +518,8 @@ vnl_matrix& vnl_matrix::operator*= (T value) } template -vnl_matrix& vnl_matrix::operator/= (T value) +vnl_matrix & +vnl_matrix::operator/=(T value) { for (unsigned int i = 0; i < this->num_rows; i++) for (unsigned int j = 0; j < this->num_cols; j++) @@ -497,18 +532,16 @@ vnl_matrix& vnl_matrix::operator/= (T value) // O(m*n). The dimensions of the two matrices must be identical. template -vnl_matrix& vnl_matrix::operator+= (vnl_matrix const& rhs) +vnl_matrix & +vnl_matrix::operator+=(const vnl_matrix & rhs) { #ifndef NDEBUG - if (this->num_rows != rhs.num_rows || - this->num_cols != rhs.num_cols) // Size match? - vnl_error_matrix_dimension ("operator+=", - this->num_rows, this->num_cols, - rhs.num_rows, rhs.num_cols); + if (this->num_rows != rhs.num_rows || this->num_cols != rhs.num_cols) // Size match? + vnl_error_matrix_dimension("operator+=", this->num_rows, this->num_cols, rhs.num_rows, rhs.num_cols); #endif - for (unsigned int i = 0; i < this->num_rows; i++) // For each row - for (unsigned int j = 0; j < this->num_cols; j++) // For each element in column - this->data[i][j] += rhs.data[i][j]; // Add elements + for (unsigned int i = 0; i < this->num_rows; i++) // For each row + for (unsigned int j = 0; j < this->num_cols; j++) // For each element in column + this->data[i][j] += rhs.data[i][j]; // Add elements return *this; } @@ -518,14 +551,12 @@ vnl_matrix& vnl_matrix::operator+= (vnl_matrix const& rhs) // The dimensions of the two matrices must be identical. template -vnl_matrix& vnl_matrix::operator-= (vnl_matrix const& rhs) +vnl_matrix & +vnl_matrix::operator-=(const vnl_matrix & rhs) { #ifndef NDEBUG - if (this->num_rows != rhs.num_rows || - this->num_cols != rhs.num_cols) // Size? - vnl_error_matrix_dimension ("operator-=", - this->num_rows, this->num_cols, - rhs.num_rows, rhs.num_cols); + if (this->num_rows != rhs.num_rows || this->num_cols != rhs.num_cols) // Size? + vnl_error_matrix_dimension("operator-=", this->num_rows, this->num_cols, rhs.num_rows, rhs.num_cols); #endif for (unsigned int i = 0; i < this->num_rows; i++) for (unsigned int j = 0; j < this->num_cols; j++) @@ -535,12 +566,13 @@ vnl_matrix& vnl_matrix::operator-= (vnl_matrix const& rhs) template -vnl_matrix operator- (T const& value, vnl_matrix const& m) +vnl_matrix +operator-(const T & value, const vnl_matrix & m) { - vnl_matrix result(m.rows(),m.columns()); - for (unsigned int i = 0; i < m.rows(); i++) // For each row + vnl_matrix result(m.rows(), m.columns()); + for (unsigned int i = 0; i < m.rows(); i++) // For each row for (unsigned int j = 0; j < m.columns(); j++) // For each element in column - result.put(i,j, T(value - m.get(i,j)) ); // subtract from value element. + result.put(i, j, T(value - m.get(i, j))); // subtract from value element. return result; } @@ -548,18 +580,20 @@ vnl_matrix operator- (T const& value, vnl_matrix const& m) // O(m*n). template -vnl_matrix::signed_t> vnl_matrix::operator- () const +vnl_matrix::signed_t> +vnl_matrix::operator-() const { vnl_matrix::signed_t> result(this->num_rows, this->num_cols); for (unsigned int i = 0; i < this->num_rows; i++) for (unsigned int j = 0; j < this->num_cols; j++) - result(i,j) = - this->data[i][j]; + result(i, j) = -this->data[i][j]; return result; } //: Return the matrix made by applying "f" to each element. template -vnl_matrix vnl_matrix::apply(T (*f)(T const&)) const +vnl_matrix +vnl_matrix::apply(T (*f)(const T &)) const { vnl_matrix ret(num_rows, num_cols); vnl_c_vector::apply(this->data[0], num_rows * num_cols, f, ret.data_block()); @@ -568,7 +602,8 @@ vnl_matrix vnl_matrix::apply(T (*f)(T const&)) const //: Return the matrix made by applying "f" to each element. template -vnl_matrix vnl_matrix::apply(T (*f)(T)) const +vnl_matrix +vnl_matrix::apply(T (*f)(T)) const { vnl_matrix ret(num_rows, num_cols); vnl_c_vector::apply(this->data[0], num_rows * num_cols, f, ret.data_block()); @@ -578,24 +613,22 @@ vnl_matrix vnl_matrix::apply(T (*f)(T)) const //: Make a vector by applying a function across rows. template vnl_vector -vnl_matrix -::apply_rowwise(T (*f)(vnl_vector const&)) const +vnl_matrix::apply_rowwise(T (*f)(const vnl_vector &)) const { vnl_vector v(this->num_rows); for (unsigned int i = 0; i < this->num_rows; ++i) - v.put(i,f(this->get_row(i))); + v.put(i, f(this->get_row(i))); return v; } //: Make a vector by applying a function across columns. template vnl_vector -vnl_matrix -::apply_columnwise(T (*f)(vnl_vector const&)) const +vnl_matrix::apply_columnwise(T (*f)(const vnl_vector &)) const { vnl_vector v(this->num_cols); for (unsigned int i = 0; i < this->num_cols; ++i) - v.put(i,f(this->get_column(i))); + v.put(i, f(this->get_column(i))); return v; } @@ -606,7 +639,8 @@ vnl_matrix // O(m*n). template -vnl_matrix vnl_matrix::transpose() const +vnl_matrix +vnl_matrix::transpose() const { vnl_matrix result(this->num_cols, this->num_rows); for (unsigned int i = 0; i < this->num_cols; i++) @@ -618,12 +652,13 @@ vnl_matrix vnl_matrix::transpose() const // adjoint/hermitian transpose template -vnl_matrix vnl_matrix::conjugate_transpose() const +vnl_matrix +vnl_matrix::conjugate_transpose() const { vnl_matrix result(transpose()); - vnl_c_vector::conjugate(result.begin(), // src - result.begin(), // dst - result.size()); // size of block + vnl_c_vector::conjugate(result.begin(), // src + result.begin(), // dst + result.size()); // size of block return result; } @@ -631,19 +666,18 @@ vnl_matrix vnl_matrix::conjugate_transpose() const // This is the reverse of extract(). template -vnl_matrix& vnl_matrix::update (vnl_matrix const& m, - unsigned top, unsigned left) +vnl_matrix & +vnl_matrix::update(const vnl_matrix & m, unsigned top, unsigned left) { - unsigned int bottom = top + m.num_rows; - unsigned int right = left + m.num_cols; + const unsigned int bottom = top + m.num_rows; + const unsigned int right = left + m.num_cols; #ifndef NDEBUG if (this->num_rows < bottom || this->num_cols < right) - vnl_error_matrix_dimension ("update", - bottom, right, m.num_rows, m.num_cols); + vnl_error_matrix_dimension("update", bottom, right, m.num_rows, m.num_cols); #endif for (unsigned int i = top; i < bottom; i++) for (unsigned int j = left; j < right; j++) - this->data[i][j] = m.data[i-top][j-left]; + this->data[i][j] = m.data[i - top][j - left]; return *this; } @@ -652,90 +686,89 @@ vnl_matrix& vnl_matrix::update (vnl_matrix const& m, // Use update() to copy new values of this submatrix back into THIS matrix. template -vnl_matrix vnl_matrix::extract (unsigned rowz, unsigned colz, - unsigned top, unsigned left) const { +vnl_matrix +vnl_matrix::extract(unsigned rowz, unsigned colz, unsigned top, unsigned left) const +{ vnl_matrix result(rowz, colz); - this->extract( result, top, left ); + this->extract(result, top, left); return result; } template -void vnl_matrix::extract( vnl_matrix& submatrix, - unsigned top, unsigned left) const { - unsigned const rowz = submatrix.rows(); - unsigned const colz = submatrix.cols(); +void +vnl_matrix::extract(vnl_matrix & submatrix, unsigned top, unsigned left) const +{ + const unsigned rowz = submatrix.rows(); + const unsigned colz = submatrix.cols(); #ifndef NDEBUG unsigned int bottom = top + rowz; unsigned int right = left + colz; if ((this->num_rows < bottom) || (this->num_cols < right)) - vnl_error_matrix_dimension ("extract", - this->num_rows, this->num_cols, bottom, right); + vnl_error_matrix_dimension("extract", this->num_rows, this->num_cols, bottom, right); #endif - for (unsigned int i = 0; i < rowz; i++) // actual copy of all elements - for (unsigned int j = 0; j < colz; j++) // in submatrix - submatrix.data[i][j] = data[top+i][left+j]; + for (unsigned int i = 0; i < rowz; i++) // actual copy of all elements + for (unsigned int j = 0; j < colz; j++) // in submatrix + submatrix.data[i][j] = data[top + i][left + j]; } //: Returns the dot product of the two matrices. O(m*n). // This is the sum of all pairwise products of the elements m1[i,j]*m2[i,j]. template -T dot_product (vnl_matrix const& m1, vnl_matrix const& m2) +T +dot_product(const vnl_matrix & m1, const vnl_matrix & m2) { #ifndef NDEBUG if (m1.rows() != m2.rows() || m1.columns() != m2.columns()) // Size? - vnl_error_matrix_dimension ("dot_product", - m1.rows(), m1.columns(), - m2.rows(), m2.columns()); + vnl_error_matrix_dimension("dot_product", m1.rows(), m1.columns(), m2.rows(), m2.columns()); #endif - return vnl_c_vector::dot_product(m1.begin(), m2.begin(), m1.rows()*m1.cols()); + return vnl_c_vector::dot_product(m1.begin(), m2.begin(), m1.rows() * m1.cols()); } //: Hermitian inner product. // O(mn). template -T inner_product (vnl_matrix const& m1, vnl_matrix const& m2) +T +inner_product(const vnl_matrix & m1, const vnl_matrix & m2) { #ifndef NDEBUG if (m1.rows() != m2.rows() || m1.columns() != m2.columns()) // Size? - vnl_error_matrix_dimension ("inner_product", - m1.rows(), m1.columns(), - m2.rows(), m2.columns()); + vnl_error_matrix_dimension("inner_product", m1.rows(), m1.columns(), m2.rows(), m2.columns()); #endif - return vnl_c_vector::inner_product(m1.begin(), m2.begin(), m1.rows()*m1.cols()); + return vnl_c_vector::inner_product(m1.begin(), m2.begin(), m1.rows() * m1.cols()); } // cos_angle. O(mn). template -T cos_angle (vnl_matrix const& a, vnl_matrix const& b) +T +cos_angle(const vnl_matrix & a, const vnl_matrix & b) { typedef typename vnl_numeric_traits::abs_t Abs_t; typedef typename vnl_numeric_traits::real_t abs_r; - T ab = inner_product(a,b); - Abs_t a_b = (Abs_t)std::sqrt( (abs_r)vnl_math::abs(inner_product(a,a) * inner_product(b,b)) ); + T ab = inner_product(a, b); + const Abs_t a_b = (Abs_t)std::sqrt((abs_r)vnl_math::abs(inner_product(a, a) * inner_product(b, b))); - return T( ab / a_b); + return T(ab / a_b); } //: Returns new matrix whose elements are the products m1[ij]*m2[ij]. // O(m*n). template -vnl_matrix element_product (vnl_matrix const& m1, - vnl_matrix const& m2) +vnl_matrix +element_product(const vnl_matrix & m1, const vnl_matrix & m2) { #ifndef NDEBUG if (m1.rows() != m2.rows() || m1.columns() != m2.columns()) // Size? - vnl_error_matrix_dimension ("element_product", - m1.rows(), m1.columns(), m2.rows(), m2.columns()); + vnl_error_matrix_dimension("element_product", m1.rows(), m1.columns(), m2.rows(), m2.columns()); #endif vnl_matrix result(m1.rows(), m1.columns()); for (unsigned int i = 0; i < m1.rows(); i++) for (unsigned int j = 0; j < m1.columns(); j++) - result.put(i,j, T(m1.get(i,j) * m2.get(i,j)) ); + result.put(i, j, T(m1.get(i, j) * m2.get(i, j))); return result; } @@ -743,41 +776,43 @@ vnl_matrix element_product (vnl_matrix const& m1, // O(m*n). template -vnl_matrix element_quotient (vnl_matrix const& m1, - vnl_matrix const& m2) +vnl_matrix +element_quotient(const vnl_matrix & m1, const vnl_matrix & m2) { #ifndef NDEBUG if (m1.rows() != m2.rows() || m1.columns() != m2.columns()) // Size? - vnl_error_matrix_dimension("element_quotient", - m1.rows(), m1.columns(), m2.rows(), m2.columns()); + vnl_error_matrix_dimension("element_quotient", m1.rows(), m1.columns(), m2.rows(), m2.columns()); #endif vnl_matrix result(m1.rows(), m1.columns()); for (unsigned int i = 0; i < m1.rows(); i++) for (unsigned int j = 0; j < m1.columns(); j++) - result.put(i,j, T(m1.get(i,j) / m2.get(i,j)) ); + result.put(i, j, T(m1.get(i, j) / m2.get(i, j))); return result; } //: Fill this matrix with the given data. // We assume that p points to a contiguous rows*cols array, stored rowwise. template -vnl_matrix& vnl_matrix::copy_in(T const *p) +vnl_matrix & +vnl_matrix::copy_in(const T * p) { - std::copy( p, p + this->num_rows * this->num_cols, this->data[0] ); + std::copy(p, p + this->num_rows * this->num_cols, this->data[0]); return *this; } //: Fill the given array with this matrix. // We assume that p points to a contiguous rows*cols array, stored rowwise. template -void vnl_matrix::copy_out(T *p) const +void +vnl_matrix::copy_out(T * p) const { - std::copy( this->data[0], this->data[0] + this->num_rows * this->num_cols, p ); + std::copy(this->data[0], this->data[0] + this->num_rows * this->num_cols, p); } //: Fill this matrix with a matrix having 1s on the main diagonal and 0s elsewhere. template -vnl_matrix& vnl_matrix::set_identity() +vnl_matrix & +vnl_matrix::set_identity() { // Zero-filling all data, followed by a loop over the diagonal, is // probably better than having a branch inside the loop. Similar to @@ -785,8 +820,8 @@ vnl_matrix& vnl_matrix::set_identity() auto count = this->num_rows * this->num_cols; if (count > 0) // this->data[0] can cause a crash when data is null (count is zero) { - std::fill_n( this->data[0], count, T() ); - const unsigned n = std::min( this->num_rows, this->num_cols ); + std::fill_n(this->data[0], count, T()); + const unsigned n = std::min(this->num_rows, this->num_cols); for (unsigned int i = 0; i < n; ++i) this->data[i][i] = 1; } @@ -796,18 +831,21 @@ vnl_matrix& vnl_matrix::set_identity() //: Make each row of the matrix have unit norm. // All-zero rows are ignored. template -vnl_matrix& vnl_matrix::normalize_rows() +vnl_matrix & +vnl_matrix::normalize_rows() { typedef typename vnl_numeric_traits::abs_t Abs_t; typedef typename vnl_numeric_traits::real_t Real_t; typedef typename vnl_numeric_traits::abs_t abs_real_t; - for (unsigned int i = 0; i < this->num_rows; ++i) { // For each row in the Matrix - Abs_t norm(0); // double will not do for all types. - for (unsigned int j = 0; j < this->num_cols; ++j) // For each element in row + for (unsigned int i = 0; i < this->num_rows; ++i) + { // For each row in the Matrix + Abs_t norm(0); // double will not do for all types. + for (unsigned int j = 0; j < this->num_cols; ++j) // For each element in row norm += vnl_math::squared_magnitude(this->data[i][j]); - if (norm != 0) { - abs_real_t scale = abs_real_t(1)/(std::sqrt((abs_real_t)norm)); + if (norm != 0) + { + const abs_real_t scale = abs_real_t(1) / (std::sqrt((abs_real_t)norm)); for (unsigned int j = 0; j < this->num_cols; ++j) this->data[i][j] = T(Real_t(this->data[i][j]) * scale); } @@ -818,18 +856,21 @@ vnl_matrix& vnl_matrix::normalize_rows() //: Make each column of the matrix have unit norm. // All-zero columns are ignored. template -vnl_matrix& vnl_matrix::normalize_columns() +vnl_matrix & +vnl_matrix::normalize_columns() { typedef typename vnl_numeric_traits::abs_t Abs_t; typedef typename vnl_numeric_traits::real_t Real_t; typedef typename vnl_numeric_traits::abs_t abs_real_t; - for (unsigned int j = 0; j < this->num_cols; j++) { // For each column in the Matrix + for (unsigned int j = 0; j < this->num_cols; j++) + { // For each column in the Matrix Abs_t norm(0); // double will not do for all types. for (unsigned int i = 0; i < this->num_rows; i++) norm += vnl_math::squared_magnitude(this->data[i][j]); - if (norm != 0) { - abs_real_t scale = abs_real_t(1)/(std::sqrt((abs_real_t)norm)); + if (norm != 0) + { + const abs_real_t scale = abs_real_t(1) / (std::sqrt((abs_real_t)norm)); for (unsigned int i = 0; i < this->num_rows; i++) this->data[i][j] = T(Real_t(this->data[i][j]) * scale); } @@ -839,37 +880,40 @@ vnl_matrix& vnl_matrix::normalize_columns() //: Multiply row[row_index] by value template -vnl_matrix& vnl_matrix::scale_row(unsigned row_index, T value) +vnl_matrix & +vnl_matrix::scale_row(unsigned row_index, T value) { #ifndef NDEBUG if (row_index >= this->num_rows) vnl_error_matrix_row_index("scale_row", row_index); #endif - for (unsigned int j = 0; j < this->num_cols; j++) // For each element in row + for (unsigned int j = 0; j < this->num_cols; j++) // For each element in row this->data[row_index][j] *= value; return *this; } //: Multiply column[column_index] by value template -vnl_matrix& vnl_matrix::scale_column(unsigned column_index, T value) +vnl_matrix & +vnl_matrix::scale_column(unsigned column_index, T value) { #ifndef NDEBUG if (column_index >= this->num_cols) vnl_error_matrix_col_index("scale_column", column_index); #endif - for (unsigned int j = 0; j < this->num_rows; j++) // For each element in column + for (unsigned int j = 0; j < this->num_rows; j++) // For each element in column this->data[j][column_index] *= value; return *this; } //: Returns a copy of n rows, starting from "row" template -vnl_matrix vnl_matrix::get_n_rows (unsigned row, unsigned n) const +vnl_matrix +vnl_matrix::get_n_rows(unsigned row, unsigned n) const { #ifndef NDEBUG if (row + n > this->num_rows) - vnl_error_matrix_row_index ("get_n_rows", row); + vnl_error_matrix_row_index("get_n_rows", row); #endif // Extract data rowwise. @@ -878,11 +922,12 @@ vnl_matrix vnl_matrix::get_n_rows (unsigned row, unsigned n) const //: Returns a copy of n columns, starting from "column". template -vnl_matrix vnl_matrix::get_n_columns (unsigned column, unsigned n) const +vnl_matrix +vnl_matrix::get_n_columns(unsigned column, unsigned n) const { #ifndef NDEBUG if (column + n > this->num_cols) - vnl_error_matrix_col_index ("get_n_columns", column); + vnl_error_matrix_col_index("get_n_columns", column); #endif vnl_matrix result(this->num_rows, n); @@ -894,30 +939,32 @@ vnl_matrix vnl_matrix::get_n_columns (unsigned column, unsigned n) const //: Create a vector out of row[row_index]. template -vnl_vector vnl_matrix::get_row(unsigned row_index) const +vnl_vector +vnl_matrix::get_row(unsigned row_index) const { #ifdef ERROR_CHECKING if (row_index >= this->num_rows) - vnl_error_matrix_row_index ("get_row", row_index); + vnl_error_matrix_row_index("get_row", row_index); #endif vnl_vector v(this->num_cols); - for (unsigned int j = 0; j < this->num_cols; j++) // For each element in row + for (unsigned int j = 0; j < this->num_cols; j++) // For each element in row v[j] = this->data[row_index][j]; return v; } //: Create a vector out of column[column_index]. template -vnl_vector vnl_matrix::get_column(unsigned column_index) const +vnl_vector +vnl_matrix::get_column(unsigned column_index) const { #ifdef ERROR_CHECKING if (column_index >= this->num_cols) - vnl_error_matrix_col_index ("get_column", column_index); + vnl_error_matrix_col_index("get_column", column_index); #endif vnl_vector v(this->num_rows); - for (unsigned int j = 0; j < this->num_rows; j++) // For each element in row + for (unsigned int j = 0; j < this->num_rows; j++) // For each element in row v[j] = this->data[j][column_index]; return v; } @@ -925,8 +972,7 @@ vnl_vector vnl_matrix::get_column(unsigned column_index) const //: Create a vector out of row[row_index]. template vnl_matrix -vnl_matrix -::get_rows(vnl_vector i) const +vnl_matrix::get_rows(vnl_vector i) const { vnl_matrix m(i.size(), this->num_cols); for (unsigned int j = 0; j < i.size(); ++j) @@ -937,8 +983,7 @@ vnl_matrix //: Create a vector out of column[column_index]. template vnl_matrix -vnl_matrix -::get_columns(vnl_vector i) const +vnl_matrix::get_columns(vnl_vector i) const { vnl_matrix m(this->num_rows, i.size()); for (unsigned int j = 0; j < i.size(); ++j) @@ -948,7 +993,8 @@ vnl_matrix //: Return a vector with the content of the (main) diagonal template -vnl_vector vnl_matrix::get_diagonal() const +vnl_vector +vnl_matrix::get_diagonal() const { vnl_vector v(this->num_rows < this->num_cols ? this->num_rows : this->num_cols); for (unsigned int j = 0; j < this->num_rows && j < this->num_cols; ++j) @@ -958,7 +1004,8 @@ vnl_vector vnl_matrix::get_diagonal() const //: Flatten row-major (C-style) template -vnl_vector vnl_matrix::flatten_row_major() const +vnl_vector +vnl_matrix::flatten_row_major() const { vnl_vector v(this->num_rows * this->num_cols); v.copy_in(this->data_block()); @@ -967,12 +1014,13 @@ vnl_vector vnl_matrix::flatten_row_major() const //: Flatten column-major (Fortran-style) template -vnl_vector vnl_matrix::flatten_column_major() const +vnl_vector +vnl_matrix::flatten_column_major() const { vnl_vector v(this->num_rows * this->num_cols); for (unsigned int c = 0; c < this->num_cols; ++c) for (unsigned int r = 0; r < this->num_rows; ++r) - v[c*this->num_rows+r] = this->data[r][c]; + v[c * this->num_rows + r] = this->data[r][c]; return v; } @@ -980,30 +1028,33 @@ vnl_vector vnl_matrix::flatten_column_major() const //: Set row[row_index] to data at given address. No bounds check. template -vnl_matrix& vnl_matrix::set_row(unsigned row_index, T const *v) +vnl_matrix & +vnl_matrix::set_row(unsigned row_index, const T * v) { - for (unsigned int j = 0; j < this->num_cols; j++) // For each element in row + for (unsigned int j = 0; j < this->num_cols; j++) // For each element in row this->data[row_index][j] = v[j]; return *this; } //: Set row[row_index] to given vector. template -vnl_matrix& vnl_matrix::set_row(unsigned row_index, vnl_vector const &v) +vnl_matrix & +vnl_matrix::set_row(unsigned row_index, const vnl_vector & v) { #ifndef NDEBUG if (v.size() != this->num_cols) - vnl_error_vector_dimension ("vnl_matrix::set_row", v.size(), this->num_cols); + vnl_error_vector_dimension("vnl_matrix::set_row", v.size(), this->num_cols); #endif - set_row(row_index,v.data_block()); + set_row(row_index, v.data_block()); return *this; } //: Set row[row_index] to given value. template -vnl_matrix& vnl_matrix::set_row(unsigned row_index, T v) +vnl_matrix & +vnl_matrix::set_row(unsigned row_index, T v) { - for (unsigned int j = 0; j < this->num_cols; j++) // For each element in row + for (unsigned int j = 0; j < this->num_cols; j++) // For each element in row this->data[row_index][j] = v; return *this; } @@ -1012,30 +1063,33 @@ vnl_matrix& vnl_matrix::set_row(unsigned row_index, T v) //: Set column[column_index] to data at given address. template -vnl_matrix& vnl_matrix::set_column(unsigned column_index, T const *v) +vnl_matrix & +vnl_matrix::set_column(unsigned column_index, const T * v) { - for (unsigned int i = 0; i < this->num_rows; i++) // For each element in row + for (unsigned int i = 0; i < this->num_rows; i++) // For each element in row this->data[i][column_index] = v[i]; return *this; } //: Set column[column_index] to given vector. template -vnl_matrix& vnl_matrix::set_column(unsigned column_index, vnl_vector const &v) +vnl_matrix & +vnl_matrix::set_column(unsigned column_index, const vnl_vector & v) { #ifndef NDEBUG if (v.size() != this->num_rows) - vnl_error_vector_dimension ("vnl_matrix::set_column", v.size(), this->num_rows); + vnl_error_vector_dimension("vnl_matrix::set_column", v.size(), this->num_rows); #endif - set_column(column_index,v.data_block()); + set_column(column_index, v.data_block()); return *this; } //: Set column[column_index] to given value. template -vnl_matrix& vnl_matrix::set_column(unsigned column_index, T v) +vnl_matrix & +vnl_matrix::set_column(unsigned column_index, T v) { - for (unsigned int j = 0; j < this->num_rows; j++) // For each element in row + for (unsigned int j = 0; j < this->num_rows; j++) // For each element in row this->data[j][column_index] = v; return *this; } @@ -1043,18 +1097,16 @@ vnl_matrix& vnl_matrix::set_column(unsigned column_index, T v) //: Set columns starting at starting_column to given matrix template -vnl_matrix& vnl_matrix::set_columns(unsigned starting_column, vnl_matrix const& m) +vnl_matrix & +vnl_matrix::set_columns(unsigned starting_column, const vnl_matrix & m) { #ifndef NDEBUG - if (this->num_rows != m.num_rows || - this->num_cols < m.num_cols + starting_column) // Size match? - vnl_error_matrix_dimension ("set_columns", - this->num_rows, this->num_cols, - m.num_rows, m.num_cols); + if (this->num_rows != m.num_rows || this->num_cols < m.num_cols + starting_column) // Size match? + vnl_error_matrix_dimension("set_columns", this->num_rows, this->num_cols, m.num_rows, m.num_cols); #endif for (unsigned int j = 0; j < m.num_cols; ++j) - for (unsigned int i = 0; i < this->num_rows; i++) // For each element in row + for (unsigned int i = 0; i < this->num_rows; i++) // For each element in row this->data[i][starting_column + j] = m.data[i][j]; return *this; } @@ -1068,49 +1120,53 @@ vnl_matrix& vnl_matrix::set_columns(unsigned starting_column, vnl_matrix -bool vnl_matrix::operator_eq(vnl_matrix const& rhs) const +bool +vnl_matrix::operator_eq(const vnl_matrix & rhs) const { - if (this == &rhs) // same object => equal. + if (this == &rhs) // same object => equal. return true; if (this->num_rows != rhs.num_rows || this->num_cols != rhs.num_cols) - return false; // different sizes => not equal. + return false; // different sizes => not equal. - for (unsigned int i = 0; i < this->num_rows; i++) // For each row - for (unsigned int j = 0; j < this->num_cols; j++) // For each column - if (!(this->data[i][j] == rhs.data[i][j])) // different element ? - return false; // Then not equal. + for (unsigned int i = 0; i < this->num_rows; i++) // For each row + for (unsigned int j = 0; j < this->num_cols; j++) // For each column + if (!(this->data[i][j] == rhs.data[i][j])) // different element ? + return false; // Then not equal. - return true; // Else same; return true + return true; // Else same; return true } template -bool vnl_matrix::is_equal(vnl_matrix const& rhs, double tol) const +bool +vnl_matrix::is_equal(const vnl_matrix & rhs, double tol) const { - if (this == &rhs) // same object => equal. + if (this == &rhs) // same object => equal. return true; if (this->num_rows != rhs.num_rows || this->num_cols != rhs.num_cols) - return false; // different sizes => not equal. + return false; // different sizes => not equal. for (unsigned int i = 0; i < this->rows(); ++i) for (unsigned int j = 0; j < this->columns(); ++j) if (!(vnl_math::abs(this->data[i][j] - rhs.data[i][j]) <= tol)) - return false; // difference greater than tol + return false; // difference greater than tol return true; } template -bool vnl_matrix::is_identity() const +bool +vnl_matrix::is_identity() const { - T const zero(0); - T const one(1); + const T zero(0); + const T one(1); for (unsigned int i = 0; i < this->rows(); ++i) - for (unsigned int j = 0; j < this->columns(); ++j) { - T xm = (*this)(i,j); - if ( !((i == j) ? (xm == one) : (xm == zero)) ) + for (unsigned int j = 0; j < this->columns(); ++j) + { + T xm = (*this)(i, j); + if (!((i == j) ? (xm == one) : (xm == zero))) return false; } return true; @@ -1118,13 +1174,15 @@ bool vnl_matrix::is_identity() const //: Return true if maximum absolute deviation of M from identity is <= tol. template -bool vnl_matrix::is_identity(double tol) const +bool +vnl_matrix::is_identity(double tol) const { T one(1); for (unsigned int i = 0; i < this->rows(); ++i) - for (unsigned int j = 0; j < this->columns(); ++j) { - T xm = (*this)(i,j); - abs_t absdev = (i == j) ? vnl_math::abs(xm - one) : vnl_math::abs(xm); + for (unsigned int j = 0; j < this->columns(); ++j) + { + T xm = (*this)(i, j); + const abs_t absdev = (i == j) ? vnl_math::abs(xm - one) : vnl_math::abs(xm); if (absdev > tol) return false; } @@ -1132,12 +1190,13 @@ bool vnl_matrix::is_identity(double tol) const } template -bool vnl_matrix::is_zero() const +bool +vnl_matrix::is_zero() const { - T const zero(0); + const T zero(0); for (unsigned int i = 0; i < this->rows(); ++i) for (unsigned int j = 0; j < this->columns(); ++j) - if ( !( (*this)(i, j) == zero) ) + if (!((*this)(i, j) == zero)) return false; return true; @@ -1145,11 +1204,12 @@ bool vnl_matrix::is_zero() const //: Return true if max(abs((*this))) <= tol. template -bool vnl_matrix::is_zero(double tol) const +bool +vnl_matrix::is_zero(double tol) const { for (unsigned int i = 0; i < this->rows(); ++i) for (unsigned int j = 0; j < this->columns(); ++j) - if (vnl_math::abs((*this)(i,j)) > tol) + if (vnl_math::abs((*this)(i, j)) > tol) return false; return true; @@ -1157,11 +1217,12 @@ bool vnl_matrix::is_zero(double tol) const //: Return true if any element of (*this) is nan template -bool vnl_matrix::has_nans() const +bool +vnl_matrix::has_nans() const { for (unsigned int i = 0; i < this->rows(); ++i) for (unsigned int j = 0; j < this->columns(); ++j) - if (vnl_math::isnan((*this)(i,j))) + if (vnl_math::isnan((*this)(i, j))) return true; return false; @@ -1169,11 +1230,12 @@ bool vnl_matrix::has_nans() const //: Return false if any element of (*this) is inf or nan template -bool vnl_matrix::is_finite() const +bool +vnl_matrix::is_finite() const { for (unsigned int i = 0; i < this->rows(); ++i) for (unsigned int j = 0; j < this->columns(); ++j) - if (!vnl_math::isfinite((*this)(i,j))) + if (!vnl_math::isfinite((*this)(i, j))) return false; return true; @@ -1181,22 +1243,26 @@ bool vnl_matrix::is_finite() const //: Abort if any element of M is inf or nan template -void vnl_matrix::assert_finite_internal() const +void +vnl_matrix::assert_finite_internal() const { if (is_finite()) return; std::cerr << "\n\n" __FILE__ ": " << __LINE__ << ": matrix has non-finite elements\n"; - if (rows() <= 20 && cols() <= 20) { + if (rows() <= 20 && cols() <= 20) + { std::cerr << __FILE__ ": here it is:\n" << *this; } - else { + else + { std::cerr << __FILE__ ": it is quite big (" << rows() << 'x' << cols() << ")\n" - << __FILE__ ": in the following picture '-' means finite and '*' means non-finite:\n"; + << __FILE__ ": in the following picture '-' means finite and '*' means non-finite:\n"; - for (unsigned int i=0; i::assert_finite_internal() const //: Abort unless M has the given size. template -void vnl_matrix::assert_size_internal(unsigned rs,unsigned cs) const +void +vnl_matrix::assert_size_internal(unsigned rs, unsigned cs) const { - if (this->rows()!=rs || this->cols()!=cs) { - std::cerr << __FILE__ ": size is " << this->rows() << 'x' << this->cols() - << ". should be " << rs << 'x' << cs << std::endl; + if (this->rows() != rs || this->cols() != cs) + { + std::cerr << __FILE__ ": size is " << this->rows() << 'x' << this->cols() << ". should be " << rs << 'x' << cs + << std::endl; std::abort(); } } @@ -1219,16 +1287,19 @@ void vnl_matrix::assert_size_internal(unsigned rs,unsigned cs) const //: Read a vnl_matrix from an ascii std::istream. // Automatically determines file size if the input matrix has zero size. template -bool vnl_matrix::read_ascii(std::istream& s) +bool +vnl_matrix::read_ascii(std::istream & s) { - if (!s.good()) { + if (!s.good()) + { std::cerr << __FILE__ ": vnl_matrix::read_ascii: Called with bad stream\n"; return false; } - bool size_known = (this->rows() != 0); + const bool size_known = (this->rows() != 0); - if (size_known) { + if (size_known) + { for (unsigned int i = 0; i < this->rows(); ++i) for (unsigned int j = 0; j < this->columns(); ++j) s >> this->data[i][j]; @@ -1236,27 +1307,30 @@ bool vnl_matrix::read_ascii(std::istream& s) return s.good() || s.eof(); } - bool debug = false; + const bool debug = false; std::vector first_row_vals; if (debug) std::cerr << __FILE__ ": vnl_matrix::read_ascii: Determining file dimensions: "; - for (;;) { + for (;;) + { // Clear whitespace, looking for a newline while (true) { - int c = s.get(); + const int c = s.get(); if (c == EOF) goto loademup; - if (!std::isspace(c)) { + if (!std::isspace(c)) + { if (!s.putback(char(c)).good()) std::cerr << "vnl_matrix::read_ascii: Could not push back '" << c << "'\n"; goto readfloat; } // First newline after first number tells us the column dimension - if (c == '\n' && first_row_vals.size() > 0) { + if (c == '\n' && first_row_vals.size() > 0) + { goto loademup; } } @@ -1268,21 +1342,22 @@ bool vnl_matrix::read_ascii(std::istream& s) if (s.eof()) goto loademup; } - loademup: - std::size_t colz = first_row_vals.size(); +loademup: + const std::size_t colz = first_row_vals.size(); - if (debug) std::cerr << colz << " cols, "; + if (debug) + std::cerr << colz << " cols, "; if (colz == 0) return false; // need to be careful with resizing here as will often be reading humungous files // So let's just build an array of row pointers - std::vector row_vals; + std::vector row_vals; row_vals.reserve(1000); { // Copy first row. Can't use first_row_vals, as may be a vector of bool... - T* row = vnl_c_vector::allocate_T(colz); + T * row = vnl_c_vector::allocate_T(colz); for (unsigned int k = 0; k < colz; ++k) row[k] = first_row_vals[k]; row_vals.push_back(row); @@ -1290,10 +1365,10 @@ bool vnl_matrix::read_ascii(std::istream& s) while (true) { - T* row = vnl_c_vector::allocate_T(colz); - if (row == nullptr) { - std::cerr << "vnl_matrix::read_ascii: Error, Out of memory on row " - << row_vals.size() << std::endl; + T * row = vnl_c_vector::allocate_T(colz); + if (row == nullptr) + { + std::cerr << "vnl_matrix::read_ascii: Error, Out of memory on row " << row_vals.size() << std::endl; return false; } s >> row[0]; @@ -1302,32 +1377,36 @@ bool vnl_matrix::read_ascii(std::istream& s) vnl_c_vector::deallocate(row, colz); break; } - for (unsigned int k = 1; k < colz; ++k) { - if (s.eof()) { - std::cerr << "vnl_matrix::read_ascii: Error, EOF on row " - << row_vals.size() << ", column " << k << std::endl; + for (unsigned int k = 1; k < colz; ++k) + { + if (s.eof()) + { + std::cerr << "vnl_matrix::read_ascii: Error, EOF on row " << row_vals.size() << ", column " << k + << std::endl; return false; } s >> row[k]; - if (s.fail()) { - std::cerr << "vnl_matrix::read_ascii: Error, row " - << row_vals.size() << " failed on column " << k << std::endl; + if (s.fail()) + { + std::cerr << "vnl_matrix::read_ascii: Error, row " << row_vals.size() << " failed on column " << k + << std::endl; return false; } } row_vals.push_back(row); } - std::size_t rowz = row_vals.size(); + const std::size_t rowz = row_vals.size(); if (debug) std::cerr << rowz << " rows.\n"; set_size((unsigned int)rowz, (unsigned int)colz); - T* p = this->data[0]; - for (unsigned int i = 0; i < rowz; ++i) { + T * p = this->data[0]; + for (unsigned int i = 0; i < rowz; ++i) + { for (unsigned int j = 0; j < colz; ++j) *p++ = row_vals[i][j]; /*if (i>0)*/ vnl_c_vector::deallocate(row_vals[i], colz); @@ -1344,7 +1423,8 @@ bool vnl_matrix::read_ascii(std::istream& s) // // which many people prefer to the ">>" alternative. template -vnl_matrix vnl_matrix::read(std::istream& s) +vnl_matrix +vnl_matrix::read(std::istream & s) { vnl_matrix M; s >> M; @@ -1352,7 +1432,8 @@ vnl_matrix vnl_matrix::read(std::istream& s) } template -void vnl_matrix::swap(vnl_matrix &that) noexcept +void +vnl_matrix::swap(vnl_matrix & that) noexcept { std::swap(this->num_rows, that.num_rows); std::swap(this->num_cols, that.num_cols); @@ -1362,16 +1443,19 @@ void vnl_matrix::swap(vnl_matrix &that) noexcept //: Reverse order of rows. Name is from Matlab, meaning "flip upside down". template -vnl_matrix& vnl_matrix::flipud() +vnl_matrix & +vnl_matrix::flipud() { const unsigned int n = this->rows(); const unsigned int colz = this->columns(); const unsigned int m = n / 2; - for (unsigned int r = 0; r < m; ++r) { + for (unsigned int r = 0; r < m; ++r) + { const unsigned int r1 = r; const unsigned int r2 = n - 1 - r; - for (unsigned int c = 0; c < colz; ++c) { + for (unsigned int c = 0; c < colz; ++c) + { const T tmp = (*this)(r1, c); (*this)(r1, c) = (*this)(r2, c); (*this)(r2, c) = tmp; @@ -1382,16 +1466,19 @@ vnl_matrix& vnl_matrix::flipud() //: Reverse order of columns. template -vnl_matrix& vnl_matrix::fliplr() +vnl_matrix & +vnl_matrix::fliplr() { const unsigned int n = this->cols(); const unsigned int rowz = this->rows(); const unsigned int m = n / 2; - for (unsigned int c = 0; c < m; ++c) { + for (unsigned int c = 0; c < m; ++c) + { const unsigned int c1 = c; const unsigned int c2 = n - 1 - c; - for (unsigned int r = 0; r < rowz; ++r) { + for (unsigned int r = 0; r < rowz; ++r) + { const T tmp = (*this)(r, c1); (*this)(r, c1) = (*this)(r, c2); (*this)(r, c2) = tmp; @@ -1403,12 +1490,14 @@ vnl_matrix& vnl_matrix::fliplr() // || M || = \max \sum | M | // 1 j i ij template -typename vnl_matrix::abs_t vnl_matrix::operator_one_norm() const +typename vnl_matrix::abs_t +vnl_matrix::operator_one_norm() const { abs_t max = 0; - for (unsigned int j=0; jnum_cols; ++j) { + for (unsigned int j = 0; j < this->num_cols; ++j) + { abs_t tmp = 0; - for (unsigned int i=0; inum_rows; ++i) + for (unsigned int i = 0; i < this->num_rows; ++i) tmp += vnl_math::abs(this->data[i][j]); if (tmp > max) max = tmp; @@ -1419,12 +1508,14 @@ typename vnl_matrix::abs_t vnl_matrix::operator_one_norm() const // || M || = \max \sum | M | // oo i j ij template -typename vnl_matrix::abs_t vnl_matrix::operator_inf_norm() const +typename vnl_matrix::abs_t +vnl_matrix::operator_inf_norm() const { abs_t max = 0; - for (unsigned int i=0; inum_rows; ++i) { + for (unsigned int i = 0; i < this->num_rows; ++i) + { abs_t tmp = 0; - for (unsigned int j=0; jnum_cols; ++j) + for (unsigned int j = 0; j < this->num_cols; ++j) tmp += vnl_math::abs(this->data[i][j]); if (tmp > max) max = tmp; @@ -1432,64 +1523,69 @@ typename vnl_matrix::abs_t vnl_matrix::operator_inf_norm() const return max; } -template // ideally, char* should be bool* - PVr -int vnl_inplace_transpose(doublereal *a, unsigned m, unsigned n, char* move, unsigned iwrk) +template // ideally, char* should be bool* - PVr +int +vnl_inplace_transpose(doublereal * a, unsigned m, unsigned n, char * move, unsigned iwrk) { doublereal b, c; - int k = m * n - 1; + const int k = m * n - 1; int iter, i1, i2, im, i1c, i2c, ncount, max_; -// ***** -// ALGORITHM 380 - REVISED -// ***** -// A IS A ONE-DIMENSIONAL ARRAY OF LENGTH MN=M*N, WHICH -// CONTAINS THE MXN MATRIX TO BE TRANSPOSED (STORED -// COLUMNWISE). MOVE IS A ONE-DIMENSIONAL ARRAY OF LENGTH IWRK -// USED TO STORE INFORMATION TO SPEED UP THE PROCESS. THE -// VALUE IWRK=(M+N)/2 IS RECOMMENDED. IOK INDICATES THE -// SUCCESS OR FAILURE OF THE ROUTINE. -// NORMAL RETURN IOK=0 -// ERRORS IOK=-2 ,IWRK NEGATIVE OR ZERO -// IOK.GT.0, (SHOULD NEVER OCCUR),IN THIS CASE -// WE SET IOK EQUAL TO THE FINAL VALUE OF ITER WHEN THE SEARCH -// IS COMPLETED BUT SOME LOOPS HAVE NOT BEEN MOVED -// NOTE * MOVE(I) WILL STAY ZERO FOR FIXED POINTS + // ***** + // ALGORITHM 380 - REVISED + // ***** + // A IS A ONE-DIMENSIONAL ARRAY OF LENGTH MN=M*N, WHICH + // CONTAINS THE MXN MATRIX TO BE TRANSPOSED (STORED + // COLUMNWISE). MOVE IS A ONE-DIMENSIONAL ARRAY OF LENGTH IWRK + // USED TO STORE INFORMATION TO SPEED UP THE PROCESS. THE + // VALUE IWRK=(M+N)/2 IS RECOMMENDED. IOK INDICATES THE + // SUCCESS OR FAILURE OF THE ROUTINE. + // NORMAL RETURN IOK=0 + // ERRORS IOK=-2 ,IWRK NEGATIVE OR ZERO + // IOK.GT.0, (SHOULD NEVER OCCUR),IN THIS CASE + // WE SET IOK EQUAL TO THE FINAL VALUE OF ITER WHEN THE SEARCH + // IS COMPLETED BUT SOME LOOPS HAVE NOT BEEN MOVED + // NOTE * MOVE(I) WILL STAY ZERO FOR FIXED POINTS if (m < 2 || n < 2) return 0; // JUST RETURN IF MATRIX IS SINGLE ROW OR COLUMN if (iwrk < 1) return -2; // ERROR RETURN - if (m == n) { + if (m == n) + { // IF MATRIX IS SQUARE, EXCHANGE ELEMENTS A(I,J) AND A(J,I). for (unsigned i = 0; i < n; ++i) - for (unsigned j = i+1; j < n; ++j) { - i1 = i + j * n; - i2 = j + i * m; - b = a[i1]; - a[i1] = a[i2]; - a[i2] = b; - } + for (unsigned j = i + 1; j < n; ++j) + { + i1 = i + j * n; + i2 = j + i * m; + b = a[i1]; + a[i1] = a[i2]; + a[i2] = b; + } return 0; // NORMAL RETURN } ncount = 2; for (unsigned i = 0; i < iwrk; ++i) move[i] = char(0); // false; - if (m > 2 && n > 2) { + if (m > 2 && n > 2) + { // CALCULATE THE NUMBER OF FIXED POINTS, EUCLIDS ALGORITHM FOR GCD(M-1,N-1). int ir2 = m - 1; int ir1 = n - 1; int ir0 = ir2 % ir1; - while (ir0 != 0) { + while (ir0 != 0) + { ir2 = ir1; ir1 = ir0; ir0 = ir2 % ir1; } ncount += ir1 - 1; } -// SET INITIAL VALUES FOR SEARCH + // SET INITIAL VALUES FOR SEARCH iter = 1; im = m; -// AT LEAST ONE LOOP MUST BE RE-ARRANGED + // AT LEAST ONE LOOP MUST BE RE-ARRANGED goto L80; // SEARCH FOR LOOPS TO REARRANGE L40: @@ -1503,13 +1599,15 @@ L40: i2 = im; if (iter == i2) goto L40; - if (iter <= (int)iwrk) { - if (move[iter-1]) + if (iter <= (int)iwrk) + { + if (move[iter - 1]) goto L40; else goto L80; } - while (i2 > iter && i2 < max_) { + while (i2 > iter && i2 < max_) + { i1 = i2; i2 = m * i1 - k * (i1 / n); } @@ -1521,18 +1619,22 @@ L80: b = a[i1]; i1c = k - iter; c = a[i1c]; - while (true) { + while (true) + { i2 = m * i1 - k * (i1 / n); i2c = k - i2; if (i1 <= (int)iwrk) - move[i1-1] = '1'; // true; + move[i1 - 1] = '1'; // true; if (i1c <= (int)iwrk) - move[i1c-1] = '1'; // true; + move[i1c - 1] = '1'; // true; ncount += 2; if (i2 == iter) break; - if (i2+iter == k) { - doublereal d = b; b = c; c = d; // interchange b and c + if (i2 + iter == k) + { + doublereal d = b; + b = c; + c = d; // interchange b and c break; } a[i1] = a[i2]; @@ -1540,7 +1642,7 @@ L80: i1 = i2; i1c = i2c; } -// FINAL STORE AND TEST FOR FINISHED + // FINAL STORE AND TEST FOR FINISHED a[i1] = b; a[i1c] = c; if (ncount > k) @@ -1552,14 +1654,15 @@ L80: //: Transpose matrix M in place. // Works for rectangular matrices using an enormously clever algorithm from ACM TOMS. template -vnl_matrix& vnl_matrix::inplace_transpose() +vnl_matrix & +vnl_matrix::inplace_transpose() { - unsigned m = rows(); - unsigned n = columns(); - unsigned iwrk = (m+n)/2; + const unsigned m = rows(); + const unsigned n = columns(); + const unsigned iwrk = (m + n) / 2; std::vector move(iwrk); - int iok = ::vnl_inplace_transpose(data_block(), n, m, &move[0], iwrk); + const int iok = ::vnl_inplace_transpose(data_block(), n, m, &move[0], iwrk); if (iok != 0) std::cerr << __FILE__ " : inplace_transpose() -- iok = " << iok << '\n'; @@ -1569,10 +1672,10 @@ vnl_matrix& vnl_matrix::inplace_transpose() // row pointers. we have to reallocate even when n<=m because // vnl_c_vector::deallocate needs to know n_when_allocatod. { - T *tmp = data[0]; + T * tmp = data[0]; vnl_c_vector::deallocate(data, m); data = vnl_c_vector::allocate_Tptr(n); - for (unsigned i=0; i& vnl_matrix::inplace_transpose() //------------------------------------------------------------------------------ -#define VNL_MATRIX_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_matrix; \ -template VNL_EXPORT vnl_matrix operator-(T const &, vnl_matrix const &); \ -/*template VNL_EXPORT vnl_matrix operator+(T const &, vnl_matrix const &) ; */ \ -/*template VNL_EXPORT vnl_matrix operator*(T const &, vnl_matrix const &) ; */ \ -template VNL_EXPORT T dot_product(vnl_matrix const &, vnl_matrix const &); \ -template VNL_EXPORT T inner_product(vnl_matrix const &, vnl_matrix const &); \ -template VNL_EXPORT T cos_angle(vnl_matrix const &, vnl_matrix const &); \ -template VNL_EXPORT vnl_matrix element_product(vnl_matrix const &, vnl_matrix const &); \ -template VNL_EXPORT vnl_matrix element_quotient(vnl_matrix const &, vnl_matrix const &); \ -template VNL_EXPORT int vnl_inplace_transpose(T*, unsigned, unsigned, char*, unsigned); \ -template VNL_EXPORT std::ostream & operator<<(std::ostream &, vnl_matrix const &); \ -template VNL_EXPORT std::istream & operator>>(std::istream &, vnl_matrix &) +#define VNL_MATRIX_INSTANTIATE(T) \ + template class VNL_EXPORT vnl_matrix; \ + template VNL_EXPORT vnl_matrix operator-(T const &, vnl_matrix const &); \ + /*template VNL_EXPORT vnl_matrix operator+(T const &, vnl_matrix const &) ; */ \ + /*template VNL_EXPORT vnl_matrix operator*(T const &, vnl_matrix const &) ; */ \ + template VNL_EXPORT T dot_product(vnl_matrix const &, vnl_matrix const &); \ + template VNL_EXPORT T inner_product(vnl_matrix const &, vnl_matrix const &); \ + template VNL_EXPORT T cos_angle(vnl_matrix const &, vnl_matrix const &); \ + template VNL_EXPORT vnl_matrix element_product(vnl_matrix const &, vnl_matrix const &); \ + template VNL_EXPORT vnl_matrix element_quotient(vnl_matrix const &, vnl_matrix const &); \ + template VNL_EXPORT int vnl_inplace_transpose(T *, unsigned, unsigned, char *, unsigned); \ + template VNL_EXPORT std::ostream & operator<<(std::ostream &, vnl_matrix const &); \ + template VNL_EXPORT std::istream & operator>>(std::istream &, vnl_matrix &) #endif // vnl_matrix_hxx_ diff --git a/core/vnl/vnl_matrix_exp.h b/core/vnl/vnl_matrix_exp.h index c33f38fa5fb..2d11c2c6b67 100644 --- a/core/vnl/vnl_matrix_exp.h +++ b/core/vnl/vnl_matrix_exp.h @@ -24,14 +24,16 @@ //: Compute the exponential of a square matrix - fiddly form // \relatesalso vnl_matrix // \relatesalso vnl_matrix_fixed -template VNL_EXPORT -bool vnl_matrix_exp(SquareMatrix const &X, SquareMatrix &expX, double max_err); +template +VNL_EXPORT bool +vnl_matrix_exp(const SquareMatrix & X, SquareMatrix & expX, double max_err); //: Compute the exponential of a square matrix - easy form. // \relatesalso vnl_matrix // \relatesalso vnl_matrix_fixed -template VNL_EXPORT -SquareMatrix vnl_matrix_exp(SquareMatrix const &X); +template +VNL_EXPORT SquareMatrix +vnl_matrix_exp(const SquareMatrix & X); #endif // vnl_matrix_exp_h_ diff --git a/core/vnl/vnl_matrix_exp.hxx b/core/vnl/vnl_matrix_exp.hxx index a26c365594f..47aa415a980 100644 --- a/core/vnl/vnl_matrix_exp.hxx +++ b/core/vnl/vnl_matrix_exp.hxx @@ -8,20 +8,21 @@ #include "vnl_matrix_exp.h" #include #ifdef DEBUG -#ifdef _MSC_VER -# include -#endif +# ifdef _MSC_VER +# include +# endif #endif template -bool vnl_matrix_exp(Matrix const &X, Matrix &expX, double max_err) +bool +vnl_matrix_exp(const Matrix & X, Matrix & expX, double max_err) { assert(X.rows() == X.cols()); assert(X.rows() == expX.rows()); assert(X.cols() == expX.cols()); assert(max_err > 0); - double norm_X = X.operator_inf_norm(); + const double norm_X = X.operator_inf_norm(); #ifdef DEBUG std::cerr << "norm_X = " << norm_X << std::endl; #endif @@ -30,14 +31,16 @@ bool vnl_matrix_exp(Matrix const &X, Matrix &expX, double max_err) expX.set_identity(); Matrix acc(X); double norm_acc_bound = norm_X; - for (unsigned n=1; true; ++n) { + for (unsigned n = 1; true; ++n) + { expX += acc; #ifdef DEBUG std::cerr << "n=" << n << std::endl; #endif - if (norm_X < n) { - double err_bound = norm_acc_bound / (1 - norm_X/n); + if (norm_X < n) + { + const double err_bound = norm_acc_bound / (1 - norm_X / n); #ifdef DEBUG std::cerr << "err_bound = " << err_bound << std::endl; #endif @@ -46,9 +49,9 @@ bool vnl_matrix_exp(Matrix const &X, Matrix &expX, double max_err) } acc = acc * X; - acc /= n+1; + acc /= n + 1; - norm_acc_bound *= norm_X/(n+1); + norm_acc_bound *= norm_X / (n + 1); } return true; @@ -56,13 +59,14 @@ bool vnl_matrix_exp(Matrix const &X, Matrix &expX, double max_err) template -Matrix vnl_matrix_exp(Matrix const &X) +Matrix +vnl_matrix_exp(const Matrix & X) { Matrix expX(X.rows(), X.cols()); #ifndef NDEBUG bool retval = #endif - vnl_matrix_exp(X, expX, 1e-10); + vnl_matrix_exp(X, expX, 1e-10); assert(retval); return expX; @@ -71,8 +75,8 @@ Matrix vnl_matrix_exp(Matrix const &X) //------------------------------------------------------------------------------ #undef VNL_MATRIX_EXP_INSTANTIATE -#define VNL_MATRIX_EXP_INSTANTIATE(Matrix) \ -template VNL_EXPORT bool vnl_matrix_exp(Matrix const&, Matrix &, double); \ -template VNL_EXPORT Matrix vnl_matrix_exp(Matrix const&) +#define VNL_MATRIX_EXP_INSTANTIATE(Matrix) \ + template VNL_EXPORT bool vnl_matrix_exp(Matrix const &, Matrix &, double); \ + template VNL_EXPORT Matrix vnl_matrix_exp(Matrix const &) #endif // vnl_matrix_exp_hxx_ diff --git a/core/vnl/vnl_matrix_fixed.h b/core/vnl/vnl_matrix_fixed.h index b0ff0afe176..58eab91e7a0 100644 --- a/core/vnl/vnl_matrix_fixed.h +++ b/core/vnl/vnl_matrix_fixed.h @@ -39,7 +39,8 @@ #include // for VNL_CONFIG_CHECK_BOUNDS #include "vnl/vnl_export.h" -template class vnl_matrix_fixed; +template +class vnl_matrix_fixed; // This mess is for a MSVC6 workaround. // @@ -86,11 +87,11 @@ template class vnl_matri template class vnl_matrix_fixed; template -inline -vnl_vector_fixed vnl_matrix_fixed_mat_vec_mult(const vnl_matrix_fixed& a, const vnl_vector_fixed& b); +inline vnl_vector_fixed +vnl_matrix_fixed_mat_vec_mult(const vnl_matrix_fixed & a, const vnl_vector_fixed & b); template -inline -vnl_matrix_fixed vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed& a, const vnl_matrix_fixed& b); +inline vnl_matrix_fixed +vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed & a, const vnl_matrix_fixed & b); //: Fixed size, stack-stored, space-efficient matrix. // vnl_matrix_fixed is a fixed-length, stack storage vector. It has @@ -103,29 +104,31 @@ vnl_matrix_fixed vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed class VNL_EXPORT vnl_matrix_fixed { - private: - static constexpr size_t num_elements = num_rows*num_cols; - static constexpr size_t num_bytes = num_elements*sizeof(T); - T data_[num_rows][num_cols]; // Local storage +private: + static constexpr size_t num_elements = num_rows * num_cols; + static constexpr size_t num_bytes = num_elements * sizeof(T); + T data_[num_rows][num_cols]; // Local storage - public: - typedef vnl_matrix_fixed self; +public: + typedef vnl_matrix_fixed self; typedef size_t size_type; //: Construct an empty num_rows*num_cols matrix vnl_matrix_fixed() = default; //: Construct an m*n Matrix and copy rhs into it. // Abort if rhs is not the same size. - vnl_matrix_fixed(const vnl_matrix_fixed& rhs) = default; + vnl_matrix_fixed(const vnl_matrix_fixed & rhs) = default; //: Copy another vnl_matrix_fixed into this. - vnl_matrix_fixed& operator=(const vnl_matrix_fixed& rhs) = default; + vnl_matrix_fixed & + operator=(const vnl_matrix_fixed & rhs) = default; // NOTE: move-assignment must be allowed to throw an exception, because we need to maintain // backwards compatibility and the move-construction & move-aasignment // operators fall back to the copy-assignment operator behavior in // cases when the memory is externally managed. - vnl_matrix_fixed(vnl_matrix_fixed&& other) = default; - vnl_matrix_fixed& operator=(vnl_matrix_fixed&& rhs) = default; + vnl_matrix_fixed(vnl_matrix_fixed && other) = default; + vnl_matrix_fixed & + operator=(vnl_matrix_fixed && rhs) = default; ~vnl_matrix_fixed() = default; @@ -135,26 +138,20 @@ class VNL_EXPORT vnl_matrix_fixed // vnl_matrix, so that algorithms can template over the matrix type // itself. It is illegal to call this constructor without // n==num_rows and m==num_cols. - vnl_matrix_fixed( unsigned VXL_USED_IN_DEBUG(n), unsigned VXL_USED_IN_DEBUG(m) ) + vnl_matrix_fixed(unsigned VXL_USED_IN_DEBUG(n), unsigned VXL_USED_IN_DEBUG(m)) { - assert( n == num_rows && m == num_cols ); + assert(n == num_rows && m == num_cols); } //: Construct an m*n matrix and fill with value - explicit vnl_matrix_fixed(T value) - { - std::fill_n(data_[0],num_elements,value); - } + explicit vnl_matrix_fixed(T value) { std::fill_n(data_[0], num_elements, value); } //: Construct an m*n Matrix and copy data into it row-wise. - explicit vnl_matrix_fixed(const T* datablck) - { - std::memcpy(data_[0], datablck, num_bytes); - } + explicit vnl_matrix_fixed(const T * datablck) { std::memcpy(data_[0], datablck, num_bytes); } //: Construct an m*n Matrix and copy rhs into it. // Abort if rhs is not the same size. - vnl_matrix_fixed(const vnl_matrix& rhs) + vnl_matrix_fixed(const vnl_matrix & rhs) { assert(rhs.rows() == num_rows && rhs.columns() == num_cols); std::memcpy(data_[0], rhs.data_block(), num_bytes); @@ -163,71 +160,105 @@ class VNL_EXPORT vnl_matrix_fixed //: Set all elements to value v // Complexity $O(r.c)$ - vnl_matrix_fixed& operator= (T const&v); + vnl_matrix_fixed & + operator=(const T & v); //: Copy a vnl_matrix into this. // Abort if rhs is not the same size. - vnl_matrix_fixed& operator=(const vnl_matrix& rhs); + vnl_matrix_fixed & + operator=(const vnl_matrix & rhs); -// Basic 2D-Array functionality------------------------------------------- + // Basic 2D-Array functionality------------------------------------------- //: Return the total number of elements stored by the matrix. // This equals rows() * cols() - constexpr unsigned int size() const { return num_elements; } + constexpr unsigned int + size() const + { + return num_elements; + } //: Return the number of rows. - constexpr unsigned int rows() const { return num_rows; } + constexpr unsigned int + rows() const + { + return num_rows; + } //: Return the number of columns. // A synonym for columns(). - constexpr unsigned int cols() const { return num_cols; } + constexpr unsigned int + cols() const + { + return num_cols; + } //: Return the number of columns. // A synonym for cols(). - constexpr unsigned int columns() const { return num_cols; } + constexpr unsigned int + columns() const + { + return num_cols; + } //: set element - inline void put (unsigned r, unsigned c, T const& v) + inline void + put(unsigned r, unsigned c, const T & v) { #if VNL_CONFIG_CHECK_BOUNDS - if (r >= num_rows) // If invalid size specified + if (r >= num_rows) // If invalid size specified vnl_error_matrix_row_index("put", r); // Raise exception - if (c >= num_cols) // If invalid size specified + if (c >= num_cols) // If invalid size specified vnl_error_matrix_col_index("put", c); // Raise exception #endif this->data_[r][c] = v; } //: get element - inline T get (unsigned r, unsigned c) const + inline T + get(unsigned r, unsigned c) const { #if VNL_CONFIG_CHECK_BOUNDS - if (r >= num_rows) // If invalid size specified + if (r >= num_rows) // If invalid size specified vnl_error_matrix_row_index("get", r); // Raise exception - if (c >= num_cols) // If invalid size specified + if (c >= num_cols) // If invalid size specified vnl_error_matrix_col_index("get", c); // Raise exception #endif return this->data_[r][c]; } //: set element, and return *this - vnl_matrix_fixed& set (unsigned r, unsigned c, T const& v) { (*this)(r,c) = v; return *this; } + vnl_matrix_fixed & + set(unsigned r, unsigned c, const T & v) + { + (*this)(r, c) = v; + return *this; + } //: return pointer to given row // No boundary checking here. - T * operator[] (unsigned r) { return data_[r]; } + T * + operator[](unsigned r) + { + return data_[r]; + } //: return pointer to given row // No boundary checking here. - T const * operator[] (unsigned r) const { return data_[r]; } + const T * + operator[](unsigned r) const + { + return data_[r]; + } //: Access an element for reading or writing // There are assert style boundary checks - #define NDEBUG to turn them off. - T & operator() (unsigned r, unsigned c) + T & + operator()(unsigned r, unsigned c) { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert(r < rows()); // Check the row index is valid - assert(c < cols()); // Check the column index is valid +#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) + assert(r < rows()); // Check the row index is valid + assert(c < cols()); // Check the column index is valid #endif return this->data_[r][c]; } @@ -235,11 +266,12 @@ class VNL_EXPORT vnl_matrix_fixed //: Access an element for reading // There are assert style boundary checks - #define NDEBUG to turn them off. - T const & operator() (unsigned r, unsigned c) const + const T & + operator()(unsigned r, unsigned c) const { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert(r < rows()); // Check the row index is valid - assert(c < cols()); // Check the column index is valid +#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) + assert(r < rows()); // Check the row index is valid + assert(c < cols()); // Check the column index is valid #endif return this->data_[r][c]; } @@ -258,7 +290,7 @@ class VNL_EXPORT vnl_matrix_fixed // \code // f(vnl_matrix_fixed(1.0).normalize_columns()); // \endcode - vnl_matrix_fixed& fill(T); + vnl_matrix_fixed & fill(T); //: Sets all diagonal elements of matrix to specified value; returns "*this". // Complexity $O(\min(r,c))$ @@ -272,13 +304,14 @@ class VNL_EXPORT vnl_matrix_fixed // \code // f(vnl_matrix_fixed().fill_diagonal(5)); // \endcode - vnl_matrix_fixed& fill_diagonal(T); + vnl_matrix_fixed & fill_diagonal(T); //: Sets the diagonal elements of this matrix to the specified list of values. // Returning "*this" allows "chaining" two or more operations: see the // reasoning (and the examples) in the documentation for method // fill_diagonal(). - vnl_matrix_fixed& set_diagonal(vnl_vector const&); + vnl_matrix_fixed & + set_diagonal(const vnl_vector &); //: Fills (laminates) this matrix with the given data, then returns it. // We assume that the argument points to a contiguous rows*cols array, stored rowwise. @@ -293,16 +326,22 @@ class VNL_EXPORT vnl_matrix_fixed // \code // f(vnl_matrix_fixed().copy_in(array)); // \endcode - vnl_matrix_fixed& copy_in(T const *); + vnl_matrix_fixed & + copy_in(const T *); //: Fills (laminates) this matrix with the given data, then returns it. // A synonym for copy_in() - vnl_matrix_fixed& set(T const *d) { return copy_in(d); } + vnl_matrix_fixed & + set(const T * d) + { + return copy_in(d); + } //: Fills the given array with this matrix. // We assume that the argument points to a contiguous rows*cols array, stored rowwise. // No bounds checking on the array. - void copy_out(T *) const; + void + copy_out(T *) const; //: Transposes this matrix efficiently, if it is square, and returns it. // Returning "*this" allows "chaining" two or more operations: @@ -310,84 +349,102 @@ class VNL_EXPORT vnl_matrix_fixed // \code // M.copy_in(array).inplace_transpose(); // \endcode - vnl_matrix_fixed& inplace_transpose(); + vnl_matrix_fixed & + inplace_transpose(); // ----------------------- Arithmetic -------------------------------- // note that these functions should not pass scalar as a const&. // Look what would happen to A /= A(0,0). //: Add \a s to each element of lhs matrix in situ - vnl_matrix_fixed& operator+= (T s) + vnl_matrix_fixed & + operator+=(T s) { - self::add( data_block(), s, data_block() ); return *this; + self::add(data_block(), s, data_block()); + return *this; } //: Subtract \a s from each element of lhs matrix in situ - vnl_matrix_fixed& operator-= (T s) + vnl_matrix_fixed & + operator-=(T s) { - self::sub( data_block(), s, data_block() ); return *this; + self::sub(data_block(), s, data_block()); + return *this; } //: - vnl_matrix_fixed& operator*= (T s) + vnl_matrix_fixed & + operator*=(T s) { - self::mul( data_block(), s, data_block() ); return *this; + self::mul(data_block(), s, data_block()); + return *this; } //: - vnl_matrix_fixed& operator/= (T s) + vnl_matrix_fixed & + operator/=(T s) { - self::div( data_block(), s, data_block() ); return *this; + self::div(data_block(), s, data_block()); + return *this; } //: - vnl_matrix_fixed& operator+= (vnl_matrix_fixed const& m) + vnl_matrix_fixed & + operator+=(const vnl_matrix_fixed & m) { - self::add( data_block(), m.data_block(), data_block() ); return *this; + self::add(data_block(), m.data_block(), data_block()); + return *this; } //: - vnl_matrix_fixed& operator+= (vnl_matrix const& m) + vnl_matrix_fixed & + operator+=(const vnl_matrix & m) { - assert( m.rows() == rows() && m.cols() == cols() ); - self::add( data_block(), m.data_block(), data_block() ); return *this; + assert(m.rows() == rows() && m.cols() == cols()); + self::add(data_block(), m.data_block(), data_block()); + return *this; } //: - vnl_matrix_fixed& operator-= (vnl_matrix_fixed const& m) + vnl_matrix_fixed & + operator-=(const vnl_matrix_fixed & m) { - self::sub( data_block(), m.data_block(), data_block() ); return *this; + self::sub(data_block(), m.data_block(), data_block()); + return *this; } //: - vnl_matrix_fixed& operator-= (vnl_matrix const& m) + vnl_matrix_fixed & + operator-=(const vnl_matrix & m) { - assert( m.rows() == rows() && m.cols() == cols() ); - self::sub( data_block(), m.data_block(), data_block() ); + assert(m.rows() == rows() && m.cols() == cols()); + self::sub(data_block(), m.data_block(), data_block()); return *this; } //: Negate all elements of matrix - vnl_matrix_fixed::signed_t, num_rows,num_cols> operator- () const + vnl_matrix_fixed::signed_t, num_rows, num_cols> + operator-() const { - vnl_matrix_fixed::signed_t, num_rows,num_cols> r; - for(int i=0; i::signed_t, num_rows, num_cols> r; + for (int i = 0; i < num_rows; ++i) + for (int j = 0; j < num_cols; ++j) + r(i, j) = -(*this)(i, j); return r; } //: - vnl_matrix_fixed& operator*= (vnl_matrix_fixed const& s) + vnl_matrix_fixed & + operator*=(const vnl_matrix_fixed & s) { vnl_matrix_fixed out; for (unsigned i = 0; i < num_rows; ++i) for (unsigned j = 0; j < num_cols; ++j) { - T accum = this->data_[i][0] * s(0,j); + T accum = this->data_[i][0] * s(0, j); for (unsigned k = 1; k < num_cols; ++k) - accum += this->data_[i][k] * s(k,j); - out(i,j) = accum; + accum += this->data_[i][k] * s(k, j); + out(i, j) = accum; } return *this = out; } @@ -398,94 +455,114 @@ class VNL_EXPORT vnl_matrix_fixed vnl_matrix_fixed apply(T (*f)(T)) const; //: Make a new matrix by applying function to each element. - vnl_matrix_fixed apply(T (*f)(T const&)) const; + vnl_matrix_fixed apply(T (*f)(const T &)) const; //: Make a vector by applying a function across rows. - vnl_vector_fixed apply_rowwise(T (*f)(vnl_vector_fixed const&)) const; + vnl_vector_fixed apply_rowwise(T (*f)(const vnl_vector_fixed &)) const; //: Make a vector by applying a function across columns. - vnl_vector_fixed apply_columnwise(T (*f)(vnl_vector_fixed const&)) const; + vnl_vector_fixed apply_columnwise(T (*f)(const vnl_vector_fixed &)) const; //: Return transpose - vnl_matrix_fixed transpose() const; + vnl_matrix_fixed + transpose() const; //: Return conjugate transpose - vnl_matrix_fixed conjugate_transpose() const; + vnl_matrix_fixed + conjugate_transpose() const; //: Set values of this matrix to those of M, starting at [top,left] - vnl_matrix_fixed& update(vnl_matrix const&, unsigned top=0, unsigned left=0); + vnl_matrix_fixed & + update(const vnl_matrix &, unsigned top = 0, unsigned left = 0); //: Set values of this matrix to those of M, starting at [top,left] - vnl_matrix_fixed& update( - vnl_matrix_fixed const& m, - unsigned top=0, unsigned left=0); + vnl_matrix_fixed & + update(const vnl_matrix_fixed & m, unsigned top = 0, unsigned left = 0); //: Set the elements of the i'th column to v[i] (No bounds checking) - vnl_matrix_fixed& set_column(unsigned i, T const * v); + vnl_matrix_fixed & + set_column(unsigned i, const T * v); //: Set the elements of the i'th column to value, then return *this. - vnl_matrix_fixed& set_column(unsigned i, T value ); + vnl_matrix_fixed & + set_column(unsigned i, T value); //: Set j-th column to v, then return *this. - vnl_matrix_fixed& set_column(unsigned j, vnl_vector const& v); + vnl_matrix_fixed & + set_column(unsigned j, const vnl_vector & v); //: Set j-th column to v, then return *this. - vnl_matrix_fixed& set_column(unsigned j, vnl_vector_fixed const& v); + vnl_matrix_fixed & + set_column(unsigned j, const vnl_vector_fixed & v); //: Set columns to those in M, starting at starting_column, then return *this. - vnl_matrix_fixed& set_columns(unsigned starting_column, vnl_matrix const& M); + vnl_matrix_fixed & + set_columns(unsigned starting_column, const vnl_matrix & M); //: Set the elements of the i'th row to v[i] (No bounds checking) - vnl_matrix_fixed& set_row (unsigned i, T const * v); + vnl_matrix_fixed & + set_row(unsigned i, const T * v); //: Set the elements of the i'th row to value, then return *this. - vnl_matrix_fixed& set_row (unsigned i, T value ); + vnl_matrix_fixed & + set_row(unsigned i, T value); //: Set the i-th row, then return *this. - vnl_matrix_fixed& set_row (unsigned i, vnl_vector const&); + vnl_matrix_fixed & + set_row(unsigned i, const vnl_vector &); //: Set the i-th row, then return *this. - vnl_matrix_fixed& set_row (unsigned i, vnl_vector_fixed const&); + vnl_matrix_fixed & + set_row(unsigned i, const vnl_vector_fixed &); //: Extract a sub-matrix of size r x c, starting at (top,left) // Thus it contains elements [top,top+r-1][left,left+c-1] - vnl_matrix extract (unsigned r, unsigned c, - unsigned top=0, unsigned left=0) const; + vnl_matrix + extract(unsigned r, unsigned c, unsigned top = 0, unsigned left = 0) const; //: Extract a sub-matrix starting at (top,left) // // The output is stored in \a sub_matrix, and it should have the // required size on entry. Thus the result will contain elements // [top,top+sub_matrix.rows()-1][left,left+sub_matrix.cols()-1] - void extract ( vnl_matrix& sub_matrix, - unsigned top=0, unsigned left=0) const; + void + extract(vnl_matrix & sub_matrix, unsigned top = 0, unsigned left = 0) const; //: Get a vector equal to the given row - vnl_vector_fixed get_row (unsigned row) const; + vnl_vector_fixed + get_row(unsigned row) const; //: Get a vector equal to the given column - vnl_vector_fixed get_column(unsigned col) const; + vnl_vector_fixed + get_column(unsigned col) const; //: Get a matrix composed of rows from the indices specified in the supplied vector. - vnl_matrix get_rows(const vnl_vector &i) const; + vnl_matrix + get_rows(const vnl_vector & i) const; //: Get a matrix composed of columns from the indices specified in the supplied vector. - vnl_matrix get_columns(const vnl_vector &i) const; + vnl_matrix + get_columns(const vnl_vector & i) const; //: Get n rows beginning at rowstart - vnl_matrix get_n_rows (unsigned rowstart, unsigned n) const; + vnl_matrix + get_n_rows(unsigned rowstart, unsigned n) const; //: Get n columns beginning at colstart - vnl_matrix get_n_columns(unsigned colstart, unsigned n) const; + vnl_matrix + get_n_columns(unsigned colstart, unsigned n) const; //: Return a vector with the content of the (main) diagonal - vnl_vector get_diagonal() const; + vnl_vector + get_diagonal() const; //: Flatten row-major (C-style) - vnl_vector_fixed flatten_row_major() const; + vnl_vector_fixed + flatten_row_major() const; //: Flatten column-major (Fortran-style) - vnl_vector_fixed flatten_column_major() const; + vnl_vector_fixed + flatten_column_major() const; // ==== mutators ==== @@ -501,7 +578,8 @@ class VNL_EXPORT vnl_matrix_fixed // M.set_identity().scale_row(0,3).scale_column(1,2); // \endcode // If the matrix is not square, anyhow set main diagonal to 1, the rest to 0. - vnl_matrix_fixed& set_identity(); + vnl_matrix_fixed & + set_identity(); //: Reverses the order of rows, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -509,7 +587,8 @@ class VNL_EXPORT vnl_matrix_fixed // \code // M.flipud().fliplr(); // \endcode - vnl_matrix_fixed& flipud(); + vnl_matrix_fixed & + flipud(); //: Reverses the order of columns, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -517,7 +596,8 @@ class VNL_EXPORT vnl_matrix_fixed // \code // M.flipud().fliplr(); // \endcode - vnl_matrix_fixed& fliplr(); + vnl_matrix_fixed & + fliplr(); //: Normalizes each row so it is a unit vector, and returns "*this". // Zero rows are not modified @@ -531,7 +611,8 @@ class VNL_EXPORT vnl_matrix_fixed // \code // f(vnl_matrix_fixed(1.0).normalize_rows()); // \endcode - vnl_matrix_fixed& normalize_rows(); + vnl_matrix_fixed & + normalize_rows(); //: Normalizes each column so it is a unit vector, and returns "*this". // Zero columns are not modified @@ -545,7 +626,8 @@ class VNL_EXPORT vnl_matrix_fixed // \code // f(vnl_matrix_fixed(1.0).normalize_columns()); // \endcode - vnl_matrix_fixed& normalize_columns(); + vnl_matrix_fixed & + normalize_columns(); //: Scales elements in given row by a factor T, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -553,7 +635,8 @@ class VNL_EXPORT vnl_matrix_fixed // \code // M.set_identity().scale_row(0,3).scale_column(1,2); // \endcode - vnl_matrix_fixed& scale_row (unsigned row, T value); + vnl_matrix_fixed & + scale_row(unsigned row, T value); //: Scales elements in given column by a factor T, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -561,88 +644,156 @@ class VNL_EXPORT vnl_matrix_fixed // \code // M.set_identity().scale_row(0,3).scale_column(1,2); // \endcode - vnl_matrix_fixed& scale_column(unsigned col, T value); + vnl_matrix_fixed & + scale_column(unsigned col, T value); //: Swap this matrix with that matrix - void swap(vnl_matrix_fixed & that); + void + swap(vnl_matrix_fixed & that); //: Type def for norms. typedef typename vnl_c_vector::abs_t abs_t; //: Return sum of absolute values of elements - abs_t array_one_norm() const { return vnl_c_vector::one_norm(begin(), size()); } + abs_t + array_one_norm() const + { + return vnl_c_vector::one_norm(begin(), size()); + } //: Return square root of sum of squared absolute element values - abs_t array_two_norm() const { return vnl_c_vector::two_norm(begin(), size()); } + abs_t + array_two_norm() const + { + return vnl_c_vector::two_norm(begin(), size()); + } //: Return largest absolute element value - abs_t array_inf_norm() const { return vnl_c_vector::inf_norm(begin(), size()); } + abs_t + array_inf_norm() const + { + return vnl_c_vector::inf_norm(begin(), size()); + } //: Return sum of absolute values of elements - abs_t absolute_value_sum() const { return array_one_norm(); } + abs_t + absolute_value_sum() const + { + return array_one_norm(); + } //: Return largest absolute value - abs_t absolute_value_max() const { return array_inf_norm(); } + abs_t + absolute_value_max() const + { + return array_inf_norm(); + } // $ || M ||_1 := \max_j \sum_i | M_{ij} | $ - abs_t operator_one_norm() const; + abs_t + operator_one_norm() const; // $ || M ||_\inf := \max_i \sum_j | M_{ij} | $ - abs_t operator_inf_norm() const; + abs_t + operator_inf_norm() const; //: Return Frobenius norm of matrix (sqrt of sum of squares of its elements) - abs_t frobenius_norm() const { return vnl_c_vector::two_norm(begin(), size()); } + abs_t + frobenius_norm() const + { + return vnl_c_vector::two_norm(begin(), size()); + } //: Return Frobenius norm of matrix (sqrt of sum of squares of its elements) - abs_t fro_norm() const { return frobenius_norm(); } + abs_t + fro_norm() const + { + return frobenius_norm(); + } //: Return RMS of all elements - abs_t rms() const { return vnl_c_vector::rms_norm(begin(), size()); } + abs_t + rms() const + { + return vnl_c_vector::rms_norm(begin(), size()); + } //: Return minimum value of elements - T min_value() const { return vnl_c_vector::min_value(begin(), size()); } + T + min_value() const + { + return vnl_c_vector::min_value(begin(), size()); + } //: Return maximum value of elements - T max_value() const { return vnl_c_vector::max_value(begin(), size()); } + T + max_value() const + { + return vnl_c_vector::max_value(begin(), size()); + } //: Return location of minimum value of elements - unsigned arg_min() const { return vnl_c_vector::arg_min(begin(), size()); } + unsigned + arg_min() const + { + return vnl_c_vector::arg_min(begin(), size()); + } //: Return location of maximum value of elements - unsigned arg_max() const { return vnl_c_vector::arg_max(begin(), size()); } + unsigned + arg_max() const + { + return vnl_c_vector::arg_max(begin(), size()); + } //: Return mean of all matrix elements - T mean() const { return vnl_c_vector::mean(begin(), size()); } + T + mean() const + { + return vnl_c_vector::mean(begin(), size()); + } // predicates //: Return true iff the size is zero. - bool empty() const { return num_rows==0 && num_cols==0; } + bool + empty() const + { + return num_rows == 0 && num_cols == 0; + } //: Return true if all elements equal to identity. - bool is_identity() const; + bool + is_identity() const; //: Return true if all elements equal to identity, within given tolerance - bool is_identity(double tol) const; + bool + is_identity(double tol) const; //: Return true if all elements equal to zero. - bool is_zero() const; + bool + is_zero() const; //: Return true if all elements equal to zero, within given tolerance - bool is_zero(double tol) const; + bool + is_zero(double tol) const; //: Return true if all elements of both matrices are equal, within given tolerance - bool is_equal(vnl_matrix_fixed const& rhs, double tol) const; + bool + is_equal(const vnl_matrix_fixed & rhs, double tol) const; //: Return true if finite - bool is_finite() const; + bool + is_finite() const; //: Return true if matrix contains NaNs - bool has_nans() const; + bool + has_nans() const; //: abort if size is not as expected // This function does or tests nothing if NDEBUG is defined - void assert_size(unsigned VXL_USED_IN_DEBUG(nr_rows), unsigned VXL_USED_IN_DEBUG(nr_cols) ) const + void + assert_size(unsigned VXL_USED_IN_DEBUG(nr_rows), unsigned VXL_USED_IN_DEBUG(nr_cols)) const { #ifndef NDEBUG assert_size_internal(nr_rows, nr_cols); @@ -651,7 +802,8 @@ class VNL_EXPORT vnl_matrix_fixed //: abort if matrix contains any INFs or NANs. // This function does or tests nothing if NDEBUG is defined - void assert_finite() const + void + assert_finite() const { #ifndef NDEBUG assert_finite_internal(); @@ -660,18 +812,22 @@ class VNL_EXPORT vnl_matrix_fixed ////----------------------- Input/Output ---------------------------- - // : Read a vnl_matrix from an ascii std::istream, automatically determining file size if the input matrix has zero size. - bool read_ascii(std::istream& s); + // : Read a vnl_matrix from an ascii std::istream, automatically determining file size if the input matrix has zero + // size. + bool + read_ascii(std::istream & s); //-------------------------------------------------------------------------------- //: Access the contiguous block storing the elements in the matrix row-wise. O(1). // 1d array, row-major order. - T const* data_block() const; + const T * + data_block() const; //: Access the contiguous block storing the elements in the matrix row-wise. O(1). // 1d array, row-major order. - T * data_block(); + T * + data_block(); //---------------------------------------------------------------------- @@ -687,23 +843,44 @@ class VNL_EXPORT vnl_matrix_fixed // for vnl_matrix but not for vnl_matrix_fixed. There is also a // conversion operator that should work most of the time. // \sa vnl_matrix_ref::non_const - vnl_matrix_ref as_ref() { return vnl_matrix_ref( num_rows, num_cols, data_block() ); } - const vnl_matrix_ref as_ref() const { return vnl_matrix_ref( num_rows, num_cols, data_block() ); } - vnl_matrix as_matrix() const { return vnl_matrix(const_cast(data_block()),num_rows,num_cols); } + vnl_matrix_ref + as_ref() + { + return vnl_matrix_ref(num_rows, num_cols, data_block()); + } + const vnl_matrix_ref + as_ref() const + { + return vnl_matrix_ref(num_rows, num_cols, data_block()); + } + vnl_matrix + as_matrix() const + { + return vnl_matrix(const_cast(data_block()), num_rows, num_cols); + } //: Cheap conversion to vnl_matrix_ref // Sometimes, such as with templated functions, the compiler cannot // use this user-defined conversion. For those cases, use the // explicit as_ref() method instead. -#if ! VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS - explicit operator const vnl_matrix_ref() const { return this->as_ref(); } +#if !VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS + explicit + operator const vnl_matrix_ref() const + { + return this->as_ref(); + } #else -#if VXL_LEGACY_FUTURE_REMOVE - VXL_DEPRECATED_MSG("Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") +# if VXL_LEGACY_FUTURE_REMOVE + VXL_DEPRECATED_MSG( + "Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") +# endif + operator const vnl_matrix_ref() const { return this->as_ref(); } #endif - operator const vnl_matrix_ref() const { return this->as_ref(); } -#endif - explicit operator vnl_matrix() const { return this->as_matrix(); } + explicit + operator vnl_matrix() const + { + return this->as_matrix(); + } //---------------------------------------------------------------------- @@ -711,65 +888,111 @@ class VNL_EXPORT vnl_matrix_fixed typedef T element_type; //: Iterators - typedef T *iterator; + typedef T * iterator; //: Iterator pointing to start of data - inline iterator begin() { return data_[0]; } + inline iterator + begin() + { + return data_[0]; + } //: Iterator pointing to element beyond end of data - inline iterator end() { return begin() + size(); } + inline iterator + end() + { + return begin() + size(); + } //: Const iterators - typedef T const *const_iterator; + typedef const T * const_iterator; //: Iterator pointing to start of data - inline const_iterator begin() const { return data_[0]; } + inline const_iterator + begin() const + { + return data_[0]; + } //: Iterator pointing to element beyond end of data - inline const_iterator end() const { return begin() + size(); } + inline const_iterator + end() const + { + return begin() + size(); + } //-------------------------------------------------------------------------------- //: Return true if *this == rhs - bool operator_eq (vnl_matrix_fixed const & rhs) const + bool + operator_eq(const vnl_matrix_fixed & rhs) const { - return equal( this->data_block(), rhs.data_block() ); + return equal(this->data_block(), rhs.data_block()); } //: Equality operator - bool operator==(vnl_matrix_fixed const &that) const { return this->operator_eq(that); } + bool + operator==(const vnl_matrix_fixed & that) const + { + return this->operator_eq(that); + } //: Inequality operator - bool operator!=(vnl_matrix_fixed const &that) const { return !this->operator_eq(that); } + bool + operator!=(const vnl_matrix_fixed & that) const + { + return !this->operator_eq(that); + } //: Equality operator - bool operator==(vnl_matrix const &that) const { return this->operator_eq(that); } + bool + operator==(const vnl_matrix & that) const + { + return this->operator_eq(that); + } //: Inequality operator - bool operator!=(vnl_matrix const &that) const { return !this->operator_eq(that); } + bool + operator!=(const vnl_matrix & that) const + { + return !this->operator_eq(that); + } //: Print matrix to os in some hopefully sensible format - void print(std::ostream& os) const; + void + print(std::ostream & os) const; -//-------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------- // Helper routines for arithmetic. These routines know the size from // the template parameters. The vector-vector operations are // element-wise. - static void add( const T* a, const T* b, T* r ); - static void add( const T* a, T b, T* r ); - static void sub( const T* a, const T* b, T* r ); - static void sub( const T* a, T b, T* r ); - static void sub( T a, const T* b, T* r ); - static void mul( const T* a, const T* b, T* r ); - static void mul( const T* a, T b, T* r ); - static void div( const T* a, const T* b, T* r ); - static void div( const T* a, T b, T* r ); - - static bool equal( const T* a, const T* b ); - - private: - void assert_finite_internal() const; - - void assert_size_internal(unsigned, unsigned) const; + static void + add(const T * a, const T * b, T * r); + static void + add(const T * a, T b, T * r); + static void + sub(const T * a, const T * b, T * r); + static void + sub(const T * a, T b, T * r); + static void + sub(T a, const T * b, T * r); + static void + mul(const T * a, const T * b, T * r); + static void + mul(const T * a, T b, T * r); + static void + div(const T * a, const T * b, T * r); + static void + div(const T * a, T b, T * r); + + static bool + equal(const T * a, const T * b); + +private: + void + assert_finite_internal() const; + + void + assert_size_internal(unsigned, unsigned) const; }; // Make the operators below inline because (1) they are small and @@ -779,108 +1002,103 @@ class VNL_EXPORT vnl_matrix_fixed // --- Matrix-scalar ------------------------------------------------------------- template -inline -vnl_matrix_fixed operator+( const vnl_matrix_fixed& mat1, const vnl_matrix_fixed& mat2 ) +inline vnl_matrix_fixed +operator+(const vnl_matrix_fixed & mat1, const vnl_matrix_fixed & mat2) { - vnl_matrix_fixed r; - vnl_matrix_fixed::add( mat1.data_block(), mat2.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::add(mat1.data_block(), mat2.data_block(), r.data_block()); return r; } template -inline -vnl_matrix_fixed operator+( const vnl_matrix_fixed& mat, T s ) +inline vnl_matrix_fixed +operator+(const vnl_matrix_fixed & mat, T s) { - vnl_matrix_fixed r; - vnl_matrix_fixed::add( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::add(mat.data_block(), s, r.data_block()); return r; } template -inline -vnl_matrix_fixed operator+( const T& s, - const vnl_matrix_fixed& mat ) +inline vnl_matrix_fixed +operator+(const T & s, const vnl_matrix_fixed & mat) { - vnl_matrix_fixed r; - vnl_matrix_fixed::add( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::add(mat.data_block(), s, r.data_block()); return r; } template -inline -vnl_matrix_fixed operator-( const vnl_matrix_fixed& mat1, const vnl_matrix_fixed& mat2 ) +inline vnl_matrix_fixed +operator-(const vnl_matrix_fixed & mat1, const vnl_matrix_fixed & mat2) { - vnl_matrix_fixed r; - vnl_matrix_fixed::sub( mat1.data_block(), mat2.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::sub(mat1.data_block(), mat2.data_block(), r.data_block()); return r; } template -inline -vnl_matrix_fixed operator-( const vnl_matrix_fixed& mat, T s ) +inline vnl_matrix_fixed +operator-(const vnl_matrix_fixed & mat, T s) { - vnl_matrix_fixed r; - vnl_matrix_fixed::sub( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::sub(mat.data_block(), s, r.data_block()); return r; } template -inline -vnl_matrix_fixed operator-( const T& s, - const vnl_matrix_fixed& mat ) +inline vnl_matrix_fixed +operator-(const T & s, const vnl_matrix_fixed & mat) { - vnl_matrix_fixed r; - vnl_matrix_fixed::sub( s, mat.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::sub(s, mat.data_block(), r.data_block()); return r; } template -inline -vnl_matrix_fixed operator*( const vnl_matrix_fixed& mat, T s ) +inline vnl_matrix_fixed +operator*(const vnl_matrix_fixed & mat, T s) { - vnl_matrix_fixed r; - vnl_matrix_fixed::mul( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::mul(mat.data_block(), s, r.data_block()); return r; } template -inline -vnl_matrix_fixed operator*( const T& s, - const vnl_matrix_fixed& mat ) +inline vnl_matrix_fixed +operator*(const T & s, const vnl_matrix_fixed & mat) { - vnl_matrix_fixed r; - vnl_matrix_fixed::mul( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::mul(mat.data_block(), s, r.data_block()); return r; } template -inline -vnl_matrix_fixed operator/( const vnl_matrix_fixed& mat, T s ) +inline vnl_matrix_fixed +operator/(const vnl_matrix_fixed & mat, T s) { - vnl_matrix_fixed r; - vnl_matrix_fixed::div( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::div(mat.data_block(), s, r.data_block()); return r; } template -inline -vnl_matrix_fixed element_product( const vnl_matrix_fixed& mat1, - const vnl_matrix_fixed& mat2 ) +inline vnl_matrix_fixed +element_product(const vnl_matrix_fixed & mat1, const vnl_matrix_fixed & mat2) { - vnl_matrix_fixed r; - vnl_matrix_fixed::mul( mat1.data_block(), mat2.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::mul(mat1.data_block(), mat2.data_block(), r.data_block()); return r; } template -inline -vnl_matrix_fixed element_quotient( const vnl_matrix_fixed& mat1, - const vnl_matrix_fixed& mat2) +inline vnl_matrix_fixed +element_quotient(const vnl_matrix_fixed & mat1, const vnl_matrix_fixed & mat2) { - vnl_matrix_fixed r; - vnl_matrix_fixed::div( mat1.data_block(), mat2.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::div(mat1.data_block(), mat2.data_block(), r.data_block()); return r; } @@ -889,34 +1107,30 @@ vnl_matrix_fixed element_quotient( const vnl_matrix_fixed& mat1, // matrix-matrix and matrix-vector multiplication code in one place, // so that bug fixes, etc, can be localized. template -inline -vnl_vector_fixed -vnl_matrix_fixed_mat_vec_mult(const vnl_matrix_fixed& a, - const vnl_vector_fixed& b) +inline vnl_vector_fixed +vnl_matrix_fixed_mat_vec_mult(const vnl_matrix_fixed & a, const vnl_vector_fixed & b) { vnl_vector_fixed out; for (unsigned i = 0; i < M; ++i) { - T accum = a(i,0) * b(0); + T accum = a(i, 0) * b(0); for (unsigned k = 1; k < N; ++k) - accum += a(i,k) * b(k); + accum += a(i, k) * b(k); out(i) = accum; } return out; } template -inline -vnl_vector_fixed -vnl_matrix_fixed_vec_mat_mult(const vnl_vector_fixed& a, - const vnl_matrix_fixed& b) +inline vnl_vector_fixed +vnl_matrix_fixed_vec_mat_mult(const vnl_vector_fixed & a, const vnl_matrix_fixed & b) { vnl_vector_fixed out; for (unsigned i = 0; i < N; ++i) { - T accum = a(0) * b(0,i); + T accum = a(0) * b(0, i); for (unsigned k = 1; k < M; ++k) - accum += a(k) * b(k,i); + accum += a(k) * b(k, i); out(i) = accum; } return out; @@ -924,19 +1138,17 @@ vnl_matrix_fixed_vec_mat_mult(const vnl_vector_fixed& a, // see comment above template -inline -vnl_matrix_fixed -vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed& a, - const vnl_matrix_fixed& b) +inline vnl_matrix_fixed +vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed & a, const vnl_matrix_fixed & b) { vnl_matrix_fixed out; for (unsigned i = 0; i < M; ++i) for (unsigned j = 0; j < O; ++j) { - T accum = a(i,0) * b(0,j); + T accum = a(i, 0) * b(0, j); for (unsigned k = 1; k < N; ++k) - accum += a(i,k) * b(k,j); - out(i,j) = accum; + accum += a(i, k) * b(k, j); + out(i, j) = accum; } return out; } @@ -947,8 +1159,8 @@ vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed& a, // \relatesalso vnl_vector_fixed // \relatesalso vnl_matrix_fixed template -inline -vnl_vector_fixed operator*(const vnl_matrix_fixed& a, const vnl_vector_fixed& b) +inline vnl_vector_fixed +operator*(const vnl_matrix_fixed & a, const vnl_vector_fixed & b) { return vnl_matrix_fixed_mat_vec_mult(a, b); } @@ -957,8 +1169,8 @@ vnl_vector_fixed operator*(const vnl_matrix_fixed& a, const vnl_v // \relatesalso vnl_vector_fixed // \relatesalso vnl_matrix_fixed template -inline -vnl_vector_fixed operator*(const vnl_vector_fixed& a, const vnl_matrix_fixed& b) +inline vnl_vector_fixed +operator*(const vnl_vector_fixed & a, const vnl_matrix_fixed & b) { return vnl_matrix_fixed_vec_mat_mult(a, b); } @@ -966,8 +1178,8 @@ vnl_vector_fixed operator*(const vnl_vector_fixed& a, const vnl_matr //: Multiply two conformant vnl_matrix_fixed (M x N) times (N x O) // \relatesalso vnl_matrix_fixed template -inline -vnl_matrix_fixed operator*(const vnl_matrix_fixed& a, const vnl_matrix_fixed& b) +inline vnl_matrix_fixed +operator*(const vnl_matrix_fixed & a, const vnl_matrix_fixed & b) { return vnl_matrix_fixed_mat_mat_mult(a, b); } @@ -978,49 +1190,57 @@ vnl_matrix_fixed operator*(const vnl_matrix_fixed& a, const vn // be automatically converted to a non-fixed-ref. These do it for you. template -inline vnl_matrix operator+( const vnl_matrix_fixed& a, const vnl_matrix& b ) +inline vnl_matrix +operator+(const vnl_matrix_fixed & a, const vnl_matrix & b) { return a.as_ref() + b; } template -inline vnl_matrix operator+( const vnl_matrix& a, const vnl_matrix_fixed& b ) +inline vnl_matrix +operator+(const vnl_matrix & a, const vnl_matrix_fixed & b) { return a + b.as_ref(); } template -inline vnl_matrix operator-( const vnl_matrix_fixed& a, const vnl_matrix& b ) +inline vnl_matrix +operator-(const vnl_matrix_fixed & a, const vnl_matrix & b) { return a.as_ref() - b; } template -inline vnl_matrix operator-( const vnl_matrix& a, const vnl_matrix_fixed& b ) +inline vnl_matrix +operator-(const vnl_matrix & a, const vnl_matrix_fixed & b) { return a - b.as_ref(); } template -inline vnl_matrix operator*( const vnl_matrix_fixed& a, const vnl_matrix& b ) +inline vnl_matrix +operator*(const vnl_matrix_fixed & a, const vnl_matrix & b) { return a.as_ref() * b; } template -inline vnl_matrix operator*( const vnl_matrix& a, const vnl_matrix_fixed& b ) +inline vnl_matrix +operator*(const vnl_matrix & a, const vnl_matrix_fixed & b) { return a * b.as_ref(); } template -inline vnl_vector operator*( const vnl_matrix_fixed& a, const vnl_vector& b ) +inline vnl_vector +operator*(const vnl_matrix_fixed & a, const vnl_vector & b) { return a.as_ref() * b; } template -inline vnl_vector operator*( const vnl_matrix& a, const vnl_vector_fixed& b ) +inline vnl_vector +operator*(const vnl_matrix & a, const vnl_vector_fixed & b) { return a * b.as_ref(); } @@ -1029,16 +1249,16 @@ inline vnl_vector operator*( const vnl_matrix& a, const vnl_vector_fixed -inline -std::ostream& operator<< (std::ostream& os, vnl_matrix_fixed const& mat) +inline std::ostream & +operator<<(std::ostream & os, const vnl_matrix_fixed & mat) { mat.print(os); return os; } template -inline -std::istream& operator>> (std::istream& is, vnl_matrix_fixed& mat) +inline std::istream & +operator>>(std::istream & is, vnl_matrix_fixed & mat) { mat.read_ascii(is); return is; @@ -1046,10 +1266,10 @@ std::istream& operator>> (std::istream& is, vnl_matrix_fixed& mat) //: // \relatesalso vnl_vector_fixed -template VNL_EXPORT -vnl_matrix_fixed outer_product(vnl_vector_fixed const& a, vnl_vector_fixed const& b); +template +VNL_EXPORT vnl_matrix_fixed +outer_product(const vnl_vector_fixed & a, const vnl_vector_fixed & b); -#define VNL_MATRIX_FIXED_INSTANTIATE(T, M, N) \ -extern "please include vnl/vnl_matrix_fixed.hxx instead" +#define VNL_MATRIX_FIXED_INSTANTIATE(T, M, N) extern "please include vnl/vnl_matrix_fixed.hxx instead" #endif // vnl_matrix_fixed_h_ diff --git a/core/vnl/vnl_matrix_fixed.hxx b/core/vnl/vnl_matrix_fixed.hxx index d6836ae8abf..ea84c685372 100644 --- a/core/vnl/vnl_matrix_fixed.hxx +++ b/core/vnl/vnl_matrix_fixed.hxx @@ -15,127 +15,126 @@ #include "vnl_error.h" #include "vnl_math.h" -#include "vnl_complex.h" //vnl_math functions for complex variables +#include "vnl_complex.h" //vnl_math functions for complex variables #include "vnl_vector_fixed.h" -template -vnl_matrix_fixed& -vnl_matrix_fixed::operator= (T const&v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::operator=(const T & v) { - fill(v); return *this; + fill(v); + return *this; } -template +template vnl_matrix_fixed & -vnl_matrix_fixed::operator=(const vnl_matrix& rhs) +vnl_matrix_fixed::operator=(const vnl_matrix & rhs) { - assert(rhs.rows() == num_rows && rhs.columns() == num_cols); - std::memcpy(data_[0], rhs.data_block(), num_rows*num_cols * sizeof(T)); - return *this; + assert(rhs.rows() == num_rows && rhs.columns() == num_cols); + std::memcpy(data_[0], rhs.data_block(), num_rows * num_cols * sizeof(T)); + return *this; } - - - -template +template void -vnl_matrix_fixed::add( const T* a, const T* b, T* r ) +vnl_matrix_fixed::add(const T * a, const T * b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = *(a++) + *(b++); } -template +template void -vnl_matrix_fixed::add( const T* a, T b, T* r ) +vnl_matrix_fixed::add(const T * a, T b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = *(a++) + b; } -template +template void -vnl_matrix_fixed::sub( const T* a, const T* b, T* r ) +vnl_matrix_fixed::sub(const T * a, const T * b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = *(a++) - *(b++); } -template +template void -vnl_matrix_fixed::sub( const T* a, T b, T* r ) +vnl_matrix_fixed::sub(const T * a, T b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = *(a++) - b; } -template +template void -vnl_matrix_fixed::sub( T a, const T* b, T* r ) +vnl_matrix_fixed::sub(T a, const T * b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = a - *(b++); } -template +template void -vnl_matrix_fixed::mul( const T* a, const T* b, T* r ) +vnl_matrix_fixed::mul(const T * a, const T * b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = *(a++) * *(b++); } -template +template void -vnl_matrix_fixed::mul( const T* a, T b, T* r ) +vnl_matrix_fixed::mul(const T * a, T b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = *(a++) * b; } -template +template void -vnl_matrix_fixed::div( const T* a, const T* b, T* r ) +vnl_matrix_fixed::div(const T * a, const T * b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = *(a++) / *(b++); } -template +template void -vnl_matrix_fixed::div( const T* a, T b, T* r ) +vnl_matrix_fixed::div(const T * a, T b, T * r) { - unsigned int count = nrows*ncols; - while ( count-- ) + unsigned int count = nrows * ncols; + while (count--) *(r++) = *(a++) / b; } -template +template bool -vnl_matrix_fixed::equal( const T* a, const T* b ) +vnl_matrix_fixed::equal(const T * a, const T * b) { - unsigned int count = nrows*ncols; - while ( count-- ) - if ( *(a++) != *(b++) ) return false; + unsigned int count = nrows * ncols; + while (count--) + if (*(a++) != *(b++)) + return false; return true; } //------------------------------------------------------------ -template -vnl_matrix_fixed& -vnl_matrix_fixed::fill (T value) +template +vnl_matrix_fixed & +vnl_matrix_fixed::fill(T value) { for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) @@ -144,9 +143,9 @@ vnl_matrix_fixed::fill (T value) } -template -vnl_matrix_fixed& -vnl_matrix_fixed::fill_diagonal (T value) +template +vnl_matrix_fixed & +vnl_matrix_fixed::fill_diagonal(T value) { for (unsigned int i = 0; i < nrows && i < ncols; ++i) this->data_[i][i] = value; @@ -154,9 +153,9 @@ vnl_matrix_fixed::fill_diagonal (T value) } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_diagonal(vnl_vector const& diag) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_diagonal(const vnl_vector & diag) { assert(diag.size() >= nrows || diag.size() >= ncols); // The length of the diagonal of a non-square matrix is the minimum of @@ -168,9 +167,9 @@ vnl_matrix_fixed::set_diagonal(vnl_vector const& diag) } -template +template void -vnl_matrix_fixed::print(std::ostream& os) const +vnl_matrix_fixed::print(std::ostream & os) const { for (unsigned int i = 0; i < nrows; ++i) { @@ -183,167 +182,157 @@ vnl_matrix_fixed::print(std::ostream& os) const template -vnl_matrix_fixed -vnl_matrix_fixed -::apply(T (*f)(T const&)) const +vnl_matrix_fixed +vnl_matrix_fixed::apply(T (*f)(const T &)) const { - vnl_matrix_fixed ret; - vnl_c_vector::apply(this->data_[0], rows()*cols(), f, ret.data_block()); + vnl_matrix_fixed ret; + vnl_c_vector::apply(this->data_[0], rows() * cols(), f, ret.data_block()); return ret; } template -vnl_matrix_fixed -vnl_matrix_fixed -::apply(T (*f)(T)) const +vnl_matrix_fixed +vnl_matrix_fixed::apply(T (*f)(T)) const { - vnl_matrix_fixed ret; - vnl_c_vector::apply(this->data_[0], rows()*cols(), f, ret.data_block()); + vnl_matrix_fixed ret; + vnl_c_vector::apply(this->data_[0], rows() * cols(), f, ret.data_block()); return ret; } //: Make a vector by applying a function across rows. template -vnl_vector_fixed -vnl_matrix_fixed -::apply_rowwise(T (*f)(vnl_vector_fixed const&)) const +vnl_vector_fixed +vnl_matrix_fixed::apply_rowwise(T (*f)(const vnl_vector_fixed &)) const { - vnl_vector_fixed v; + vnl_vector_fixed v; for (unsigned int i = 0; i < nrows; ++i) - v.put(i,f(this->get_row(i))); + v.put(i, f(this->get_row(i))); return v; } //: Make a vector by applying a function across columns. template -vnl_vector_fixed -vnl_matrix_fixed -::apply_columnwise(T (*f)(vnl_vector_fixed const&)) const +vnl_vector_fixed +vnl_matrix_fixed::apply_columnwise(T (*f)(const vnl_vector_fixed &)) const { - vnl_vector_fixed v; + vnl_vector_fixed v; for (unsigned int i = 0; i < ncols; ++i) - v.put(i,f(this->get_column(i))); + v.put(i, f(this->get_column(i))); return v; } ////--------------------------- Additions------------------------------------ -template -vnl_matrix_fixed -vnl_matrix_fixed::transpose() const +template +vnl_matrix_fixed +vnl_matrix_fixed::transpose() const { - vnl_matrix_fixed result; + vnl_matrix_fixed result; for (unsigned int i = 0; i < cols(); ++i) for (unsigned int j = 0; j < rows(); ++j) - result(i,j) = this->data_[j][i]; + result(i, j) = this->data_[j][i]; return result; } -template -vnl_matrix_fixed -vnl_matrix_fixed::conjugate_transpose() const +template +vnl_matrix_fixed +vnl_matrix_fixed::conjugate_transpose() const { - vnl_matrix_fixed result(transpose()); - vnl_c_vector::conjugate(result.begin(), // src - result.begin(), // dst - result.size()); // size of block + vnl_matrix_fixed result(transpose()); + vnl_c_vector::conjugate(result.begin(), // src + result.begin(), // dst + result.size()); // size of block return result; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::update (vnl_matrix const& m, - unsigned top, unsigned left) +template +vnl_matrix_fixed & +vnl_matrix_fixed::update(const vnl_matrix & m, unsigned top, unsigned left) { const unsigned int bottom = top + m.rows(); const unsigned int right = left + m.cols(); #ifndef NDEBUG if (nrows < bottom || ncols < right) - vnl_error_matrix_dimension ("update", - bottom, right, m.rows(), m.cols()); + vnl_error_matrix_dimension("update", bottom, right, m.rows(), m.cols()); #endif for (unsigned int i = top; i < bottom; ++i) for (unsigned int j = left; j < right; ++j) - this->data_[i][j] = m(i-top,j-left); + this->data_[i][j] = m(i - top, j - left); return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::update (vnl_matrix_fixed const& m, - unsigned top, unsigned left) +template +vnl_matrix_fixed & +vnl_matrix_fixed::update(const vnl_matrix_fixed & m, unsigned top, unsigned left) { const unsigned int bottom = top + m.rows(); const unsigned int right = left + m.cols(); #ifndef NDEBUG if (nrows < bottom || ncols < right) - vnl_error_matrix_dimension ("update", - bottom, right, m.rows(), m.cols()); + vnl_error_matrix_dimension("update", bottom, right, m.rows(), m.cols()); #endif for (unsigned int i = top; i < bottom; ++i) for (unsigned int j = left; j < right; ++j) - this->data_[i][j] = m(i-top,j-left); + this->data_[i][j] = m(i - top, j - left); return *this; } -template +template vnl_matrix -vnl_matrix_fixed::extract (unsigned rowz, unsigned colz, - unsigned top, unsigned left) const +vnl_matrix_fixed::extract(unsigned rowz, unsigned colz, unsigned top, unsigned left) const { vnl_matrix result(rowz, colz); - this->extract( result, top, left ); + this->extract(result, top, left); return result; } -template +template void -vnl_matrix_fixed::extract (vnl_matrix& sub_matrix, - unsigned top, unsigned left) const +vnl_matrix_fixed::extract(vnl_matrix & sub_matrix, unsigned top, unsigned left) const { - unsigned int rowz = sub_matrix.rows(); - unsigned int colz = sub_matrix.cols(); + const unsigned int rowz = sub_matrix.rows(); + const unsigned int colz = sub_matrix.cols(); #ifndef NDEBUG unsigned int bottom = top + rowz; unsigned int right = left + colz; if ((nrows < bottom) || (ncols < right)) - vnl_error_matrix_dimension ("extract", - nrows, ncols, bottom, right); + vnl_error_matrix_dimension("extract", nrows, ncols, bottom, right); #endif - for (unsigned int i = 0; i < rowz; ++i) // actual copy of all elements - for (unsigned int j = 0; j < colz; ++j) // in submatrix - sub_matrix(i,j) = this->data_[top+i][left+j]; + for (unsigned int i = 0; i < rowz; ++i) // actual copy of all elements + for (unsigned int j = 0; j < colz; ++j) // in submatrix + sub_matrix(i, j) = this->data_[top + i][left + j]; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::copy_in(T const *p) +template +vnl_matrix_fixed & +vnl_matrix_fixed::copy_in(const T * p) { - T* dp = this->data_block(); - std::copy( p, p + nrows * ncols, dp ); + T * dp = this->data_block(); + std::copy(p, p + nrows * ncols, dp); return *this; } -template -void vnl_matrix_fixed::copy_out(T *p) const +template +void +vnl_matrix_fixed::copy_out(T * p) const { - T const* dp = this->data_block(); - std::copy( dp, dp + nrows * ncols, p ); + const T * dp = this->data_block(); + std::copy(dp, dp + nrows * ncols, p); } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_identity() +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_identity() { // A reset of this object, followed by a loop over the diagonal, is // probably better than having a branch inside the loop. Probably // worth the O(n) extra writes. *this = vnl_matrix_fixed(); - const unsigned n = std::min( nrows, ncols ); + const unsigned n = std::min(nrows, ncols); for (unsigned int i = 0; i < n; ++i) this->data_[i][i] = 1; return *this; @@ -351,20 +340,20 @@ vnl_matrix_fixed::set_identity() //: Make each row of the matrix have unit norm. // All-zero rows are ignored. -template -vnl_matrix_fixed& -vnl_matrix_fixed::normalize_rows() +template +vnl_matrix_fixed & +vnl_matrix_fixed::normalize_rows() { for (unsigned int i = 0; i < nrows; ++i) { abs_t norm(0); // double will not do for all types. for (unsigned int j = 0; j < ncols; ++j) - norm += vnl_math::squared_magnitude( this->data_[i][j] ); + norm += vnl_math::squared_magnitude(this->data_[i][j]); if (norm != 0) { typedef typename vnl_numeric_traits::real_t real_t; - real_t scale = real_t(1)/std::sqrt((real_t)norm); + const real_t scale = real_t(1) / std::sqrt((real_t)norm); for (unsigned int j = 0; j < ncols; ++j) { // FIXME need correct rounding here @@ -376,19 +365,20 @@ vnl_matrix_fixed::normalize_rows() return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::normalize_columns() +template +vnl_matrix_fixed & +vnl_matrix_fixed::normalize_columns() { - for (unsigned int j = 0; j < ncols; ++j) { // For each column in the Matrix + for (unsigned int j = 0; j < ncols; ++j) + { // For each column in the Matrix abs_t norm(0); // double will not do for all types. for (unsigned int i = 0; i < nrows; ++i) - norm += vnl_math::squared_magnitude( this->data_[i][j] ); + norm += vnl_math::squared_magnitude(this->data_[i][j]); if (norm != 0) { typedef typename vnl_numeric_traits::real_t real_t; - real_t scale = real_t(1)/std::sqrt((real_t)norm); + const real_t scale = real_t(1) / std::sqrt((real_t)norm); for (unsigned int i = 0; i < nrows; ++i) { // FIXME need correct rounding here @@ -400,9 +390,9 @@ vnl_matrix_fixed::normalize_columns() return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::scale_row(unsigned row_index, T value) +template +vnl_matrix_fixed & +vnl_matrix_fixed::scale_row(unsigned row_index, T value) { #ifndef NDEBUG if (row_index >= nrows) @@ -413,9 +403,9 @@ vnl_matrix_fixed::scale_row(unsigned row_index, T value) return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::scale_column(unsigned column_index, T value) +template +vnl_matrix_fixed & +vnl_matrix_fixed::scale_column(unsigned column_index, T value) { #ifndef NDEBUG if (column_index >= ncols) @@ -428,39 +418,38 @@ vnl_matrix_fixed::scale_column(unsigned column_index, T value) template void -vnl_matrix_fixed -::swap(vnl_matrix_fixed &that) +vnl_matrix_fixed::swap(vnl_matrix_fixed & that) { for (unsigned int r = 0; r < nrows; ++r) { for (unsigned int c = 0; c < ncols; ++c) { - std::swap(this->data_[r][c], that.data_[r][c]); + std::swap(this->data_[r][c], that.data_[r][c]); } } } //: Returns a copy of n rows, starting from "row" -template +template vnl_matrix -vnl_matrix_fixed::get_n_rows (unsigned row, unsigned n) const +vnl_matrix_fixed::get_n_rows(unsigned row, unsigned n) const { #ifndef NDEBUG if (row + n > nrows) - vnl_error_matrix_row_index ("get_n_rows", row); + vnl_error_matrix_row_index("get_n_rows", row); #endif // Extract data rowwise. return vnl_matrix(data_[row], n, ncols); } -template +template vnl_matrix -vnl_matrix_fixed::get_n_columns (unsigned column, unsigned n) const +vnl_matrix_fixed::get_n_columns(unsigned column, unsigned n) const { #ifndef NDEBUG if (column + n > ncols) - vnl_error_matrix_col_index ("get_n_columns", column); + vnl_error_matrix_col_index("get_n_columns", column); #endif vnl_matrix result(nrows, n); @@ -471,30 +460,32 @@ vnl_matrix_fixed::get_n_columns (unsigned column, unsigned n) con } //: Create a vector out of row[row_index]. -template -vnl_vector_fixed vnl_matrix_fixed::get_row(unsigned row_index) const +template +vnl_vector_fixed +vnl_matrix_fixed::get_row(unsigned row_index) const { #ifdef ERROR_CHECKING if (row_index >= nrows) - vnl_error_matrix_row_index ("get_row", row_index); + vnl_error_matrix_row_index("get_row", row_index); #endif - vnl_vector_fixed v; - for (unsigned int j = 0; j < ncols; ++j) // For each element in row + vnl_vector_fixed v; + for (unsigned int j = 0; j < ncols; ++j) // For each element in row v[j] = this->data_[row_index][j]; return v; } //: Create a vector out of column[column_index]. -template -vnl_vector_fixed vnl_matrix_fixed::get_column(unsigned column_index) const +template +vnl_vector_fixed +vnl_matrix_fixed::get_column(unsigned column_index) const { #ifdef ERROR_CHECKING if (column_index >= ncols) - vnl_error_matrix_col_index ("get_column", column_index); + vnl_error_matrix_col_index("get_column", column_index); #endif - vnl_vector_fixed v; + vnl_vector_fixed v; for (unsigned int j = 0; j < nrows; ++j) v[j] = this->data_[j][column_index]; return v; @@ -503,8 +494,7 @@ vnl_vector_fixed vnl_matrix_fixed::get_column(unsigned c //: Create a vector out of row[row_index]. template vnl_matrix -vnl_matrix_fixed -::get_rows(const vnl_vector &i) const +vnl_matrix_fixed::get_rows(const vnl_vector & i) const { vnl_matrix m(i.size(), this->cols()); for (unsigned int j = 0; j < i.size(); ++j) @@ -515,8 +505,7 @@ vnl_matrix_fixed //: Create a vector out of column[column_index]. template vnl_matrix -vnl_matrix_fixed -::get_columns(const vnl_vector & i) const +vnl_matrix_fixed::get_columns(const vnl_vector & i) const { vnl_matrix m(this->rows(), i.size()); for (unsigned int j = 0; j < i.size(); ++j) @@ -525,8 +514,9 @@ vnl_matrix_fixed } //: Return a vector with the content of the (main) diagonal -template -vnl_vector vnl_matrix_fixed::get_diagonal() const +template +vnl_vector +vnl_matrix_fixed::get_diagonal() const { vnl_vector v(nrows < ncols ? nrows : ncols); for (unsigned int j = 0; j < nrows && j < ncols; ++j) @@ -536,58 +526,60 @@ vnl_vector vnl_matrix_fixed::get_diagonal() const //: Flatten row-major (C-style) template -vnl_vector_fixed vnl_matrix_fixed::flatten_row_major() const +vnl_vector_fixed +vnl_matrix_fixed::flatten_row_major() const { - vnl_vector_fixed v; + vnl_vector_fixed v; v.copy_in(this->data_block()); return v; } //: Flatten column-major (Fortran-style) template -vnl_vector_fixed vnl_matrix_fixed::flatten_column_major() const +vnl_vector_fixed +vnl_matrix_fixed::flatten_column_major() const { - vnl_vector_fixed v; + vnl_vector_fixed v; for (unsigned int c = 0; c < ncols; ++c) for (unsigned int r = 0; r < nrows; ++r) - v[c*nrows+r] = this->data_[r][c]; + v[c * nrows + r] = this->data_[r][c]; return v; } //-------------------------------------------------------------------------------- -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_row(unsigned row_index, T const *v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_row(unsigned row_index, const T * v) { for (unsigned int j = 0; j < ncols; ++j) this->data_[row_index][j] = v[j]; return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_row(unsigned row_index, vnl_vector const &v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_row(unsigned row_index, const vnl_vector & v) { if (v.size() >= ncols) - set_row(row_index,v.data_block()); + set_row(row_index, v.data_block()); else for (unsigned int j = 0; j < v.size(); ++j) this->data_[row_index][j] = v[j]; return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_row(unsigned row_index, vnl_vector_fixed const &v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_row(unsigned row_index, const vnl_vector_fixed & v) { - set_row(row_index,v.data_block()); + set_row(row_index, v.data_block()); return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_row(unsigned row_index, T v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_row(unsigned row_index, T v) { for (unsigned int j = 0; j < ncols; ++j) this->data_[row_index][j] = v; @@ -596,38 +588,38 @@ vnl_matrix_fixed::set_row(unsigned row_index, T v) //-------------------------------------------------------------------------------- -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_column(unsigned column_index, T const *v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_column(unsigned column_index, const T * v) { for (unsigned int i = 0; i < nrows; ++i) this->data_[i][column_index] = v[i]; return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_column(unsigned column_index, vnl_vector const &v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_column(unsigned column_index, const vnl_vector & v) { if (v.size() >= nrows) - set_column(column_index,v.data_block()); + set_column(column_index, v.data_block()); else for (unsigned int i = 0; i < v.size(); ++i) this->data_[i][column_index] = v[i]; return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_column(unsigned column_index, vnl_vector_fixed const &v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_column(unsigned column_index, const vnl_vector_fixed & v) { - set_column(column_index,v.data_block()); + set_column(column_index, v.data_block()); return *this; } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_column(unsigned column_index, T v) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_column(unsigned column_index, T v) { for (unsigned int j = 0; j < nrows; ++j) this->data_[j][column_index] = v; @@ -635,28 +627,29 @@ vnl_matrix_fixed::set_column(unsigned column_index, T v) } -template -vnl_matrix_fixed& -vnl_matrix_fixed::set_columns(unsigned starting_column, vnl_matrix const& m) +template +vnl_matrix_fixed & +vnl_matrix_fixed::set_columns(unsigned starting_column, const vnl_matrix & m) { - for (unsigned int j = 0; j < m.cols() && starting_column+j < ncols; ++j) // don't go too far right; possibly only use part of m + for (unsigned int j = 0; j < m.cols() && starting_column + j < ncols; + ++j) // don't go too far right; possibly only use part of m for (unsigned int i = 0; i < nrows && i < m.rows(); ++i) // smallest of the two heights; possibly only use part of m - this->data_[i][starting_column + j] = m(i,j); + this->data_[i][starting_column + j] = m(i, j); return *this; } template bool -vnl_matrix_fixed::is_identity() const +vnl_matrix_fixed::is_identity() const { - T const zero(0); - T const one(1); + const T zero(0); + const T one(1); for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) { T xm = this->data_[i][j]; - if ( !((i == j) ? (xm == one) : (xm == zero)) ) + if (!((i == j) ? (xm == one) : (xm == zero))) return false; } return true; @@ -665,14 +658,14 @@ vnl_matrix_fixed::is_identity() const //: Return true if maximum absolute deviation of M from identity is <= tol. template bool -vnl_matrix_fixed::is_identity(double tol) const +vnl_matrix_fixed::is_identity(double tol) const { T one(1); for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) { T xm = this->data_[i][j]; - abs_t absdev = (i == j) ? vnl_math::abs(xm - one) : vnl_math::abs(xm); + const abs_t absdev = (i == j) ? vnl_math::abs(xm - one) : vnl_math::abs(xm); if (absdev > tol) return false; } @@ -681,35 +674,35 @@ vnl_matrix_fixed::is_identity(double tol) const template bool -vnl_matrix_fixed::is_zero() const +vnl_matrix_fixed::is_zero() const { - T const zero(0); + const T zero(0); for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) - if ( !( this->data_[i][ j] == zero) ) + if (!(this->data_[i][j] == zero)) return false; return true; } template -bool vnl_matrix_fixed -::is_equal(vnl_matrix_fixed const& rhs, double tol) const +bool +vnl_matrix_fixed::is_equal(const vnl_matrix_fixed & rhs, double tol) const { - if (this == &rhs) // same object => equal. + if (this == &rhs) // same object => equal. return true; for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) if (!(vnl_math::abs(this->data_[i][j] - rhs.data_[i][j]) <= tol)) - return false; // difference greater than tol + return false; // difference greater than tol return true; } template bool -vnl_matrix_fixed::is_zero(double tol) const +vnl_matrix_fixed::is_zero(double tol) const { for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) @@ -721,7 +714,7 @@ vnl_matrix_fixed::is_zero(double tol) const template bool -vnl_matrix_fixed::has_nans() const +vnl_matrix_fixed::has_nans() const { for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) @@ -733,7 +726,7 @@ vnl_matrix_fixed::has_nans() const template bool -vnl_matrix_fixed::is_finite() const +vnl_matrix_fixed::is_finite() const { for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) @@ -746,7 +739,7 @@ vnl_matrix_fixed::is_finite() const //: Abort if any element of M is inf or nan template void -vnl_matrix_fixed::assert_finite_internal() const +vnl_matrix_fixed::assert_finite_internal() const { if (is_finite()) return; @@ -758,12 +751,12 @@ vnl_matrix_fixed::assert_finite_internal() const else { std::cerr << __FILE__ ": it is quite big (" << rows() << 'x' << cols() << ")\n" - << __FILE__ ": in the following picture '-' means finite and '*' means non-finite:\n"; + << __FILE__ ": in the following picture '-' means finite and '*' means non-finite:\n"; - for (unsigned int i=0; idata_[i][ j]) ? '-' : '*'); + for (unsigned int j = 0; j < cols(); ++j) + std::cerr << char(vnl_math::isfinite(this->data_[i][j]) ? '-' : '*'); std::cerr << '\n'; } } @@ -774,19 +767,18 @@ vnl_matrix_fixed::assert_finite_internal() const //: Abort unless M has the given size. template void -vnl_matrix_fixed::assert_size_internal(unsigned rs,unsigned cs) const +vnl_matrix_fixed::assert_size_internal(unsigned rs, unsigned cs) const { - if (nrows!=rs || ncols!=cs) + if (nrows != rs || ncols != cs) { - std::cerr << __FILE__ ": size is " << nrows << 'x' << ncols - << ". should be " << rs << 'x' << cs << std::endl; + std::cerr << __FILE__ ": size is " << nrows << 'x' << ncols << ". should be " << rs << 'x' << cs << std::endl; std::abort(); } } template bool -vnl_matrix_fixed::read_ascii(std::istream& s) +vnl_matrix_fixed::read_ascii(std::istream & s) { if (!s.good()) { @@ -803,15 +795,15 @@ vnl_matrix_fixed::read_ascii(std::istream& s) template -vnl_matrix_fixed& -vnl_matrix_fixed::flipud() +vnl_matrix_fixed & +vnl_matrix_fixed::flipud() { - for (unsigned int r1 = 0; 2*r1+1 < nrows; ++r1) + for (unsigned int r1 = 0; 2 * r1 + 1 < nrows; ++r1) { const unsigned int r2 = nrows - 1 - r1; for (unsigned int c = 0; c < ncols; ++c) { - std::swap(this->data_[r1][c], this->data_[r2][c]); + std::swap(this->data_[r1][c], this->data_[r2][c]); } } return *this; @@ -819,30 +811,30 @@ vnl_matrix_fixed::flipud() template -vnl_matrix_fixed& -vnl_matrix_fixed::fliplr() +vnl_matrix_fixed & +vnl_matrix_fixed::fliplr() { - for (unsigned int c1 = 0; 2*c1+1 < ncols; ++c1) + for (unsigned int c1 = 0; 2 * c1 + 1 < ncols; ++c1) { const unsigned int c2 = ncols - 1 - c1; for (unsigned int r = 0; r < nrows; ++r) { - std::swap(this->data_[r][c1], this->data_[r][c2]); + std::swap(this->data_[r][c1], this->data_[r][c2]); } } return *this; } template -typename vnl_matrix_fixed::abs_t -vnl_matrix_fixed::operator_one_norm() const +typename vnl_matrix_fixed::abs_t +vnl_matrix_fixed::operator_one_norm() const { abs_t m(0); - for (unsigned int j=0; jdata_[i][j] ); + for (unsigned int i = 0; i < nrows; ++i) + t += vnl_math::abs(this->data_[i][j]); if (t > m) m = t; } @@ -850,15 +842,15 @@ vnl_matrix_fixed::operator_one_norm() const } template -typename vnl_matrix_fixed::abs_t -vnl_matrix_fixed::operator_inf_norm() const +typename vnl_matrix_fixed::abs_t +vnl_matrix_fixed::operator_inf_norm() const { abs_t m(0); - for (unsigned int i=0; idata_[i][j] ); + for (unsigned int j = 0; j < ncols; ++j) + t += vnl_math::abs(this->data_[i][j]); if (t > m) m = t; } @@ -867,52 +859,52 @@ vnl_matrix_fixed::operator_inf_norm() const //: Transpose square matrix M in place. template -vnl_matrix_fixed& -vnl_matrix_fixed::inplace_transpose() +vnl_matrix_fixed & +vnl_matrix_fixed::inplace_transpose() { - assert(nrows==ncols); // cannot inplace_transpose non-square fixed size matrix + assert(nrows == ncols); // cannot inplace_transpose non-square fixed size matrix for (unsigned i = 0; i < nrows; ++i) - for (unsigned j = i+1; j < ncols; ++j) - { - T t = this->data_[i][j]; - this->data_[i][j] = this->data_[j][i]; - this->data_[j][i] = t; - } + for (unsigned j = i + 1; j < ncols; ++j) + { + T t = this->data_[i][j]; + this->data_[i][j] = this->data_[j][i]; + this->data_[j][i] = t; + } return *this; } template -T const* +const T * vnl_matrix_fixed::data_block() const { - return data_[0]; + return data_[0]; } template -T * +T * vnl_matrix_fixed::data_block() { - return data_[0]; + return data_[0]; } template -vnl_matrix_fixed -outer_product(vnl_vector_fixed const& a, vnl_vector_fixed const& b) +vnl_matrix_fixed +outer_product(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - vnl_matrix_fixed out; // = a.column() * b.row() + vnl_matrix_fixed out; // = a.column() * b.row() for (unsigned int i = 0; i < m; ++i) for (unsigned int j = 0; j < n; ++j) out[i][j] = a[i] * b[j]; return out; } -#define VNL_OUTER_PRODUCT_FIXED_INSTANTIATE( T, M, N ) \ -template VNL_EXPORT vnl_matrix_fixed outer_product(vnl_vector_fixed const&,\ - vnl_vector_fixed const& ) +#define VNL_OUTER_PRODUCT_FIXED_INSTANTIATE(T, M, N) \ + template VNL_EXPORT vnl_matrix_fixed outer_product(vnl_vector_fixed const &, \ + vnl_vector_fixed const &) #undef VNL_MATRIX_FIXED_INSTANTIATE -#define VNL_MATRIX_FIXED_INSTANTIATE(T, M, N) \ -template class VNL_EXPORT vnl_matrix_fixed; \ -VNL_OUTER_PRODUCT_FIXED_INSTANTIATE( T, M, N ) +#define VNL_MATRIX_FIXED_INSTANTIATE(T, M, N) \ + template class VNL_EXPORT vnl_matrix_fixed; \ + VNL_OUTER_PRODUCT_FIXED_INSTANTIATE(T, M, N) #endif // vnl_matrix_fixed_hxx_ diff --git a/core/vnl/vnl_matrix_fixed_ref.h b/core/vnl/vnl_matrix_fixed_ref.h index a0f97b27af5..02ab3788eef 100644 --- a/core/vnl/vnl_matrix_fixed_ref.h +++ b/core/vnl/vnl_matrix_fixed_ref.h @@ -169,191 +169,297 @@ template class VNL_EXPORT vnl_matrix_fixed_ref_const { - protected: - const T* data_; - public: - vnl_matrix_fixed_ref_const(const vnl_matrix_fixed& rhs) +protected: + const T * data_; + +public: + vnl_matrix_fixed_ref_const(const vnl_matrix_fixed & rhs) : data_(rhs.data_block()) - { - } + {} explicit vnl_matrix_fixed_ref_const(const T * dataptr) : data_(dataptr) - { - } - vnl_matrix_fixed_ref_const(const vnl_matrix_fixed_ref_const & rhs) + {} + vnl_matrix_fixed_ref_const(const vnl_matrix_fixed_ref_const & rhs) : data_(rhs.data_) - { - } + {} //: Get j-th row - vnl_vector_fixed get_row(unsigned row_index) const + vnl_vector_fixed + get_row(unsigned row_index) const { vnl_vector v(num_cols); - for (unsigned int j = 0; j < num_cols; j++) // For each element in row - v[j] = (*this)(row_index,j); + for (unsigned int j = 0; j < num_cols; j++) // For each element in row + v[j] = (*this)(row_index, j); return v; } //: Get j-th column - vnl_vector_fixed get_column(unsigned column_index) const + vnl_vector_fixed + get_column(unsigned column_index) const { vnl_vector v(num_rows); for (unsigned int j = 0; j < num_rows; j++) - v[j] = (*this)(j,column_index); + v[j] = (*this)(j, column_index); return v; } //: Return a vector with the content of the (main) diagonal - vnl_vector get_diagonal() const; + vnl_vector + get_diagonal() const; - const T * data_block() const { return data_; } + const T * + data_block() const + { + return data_; + } //: Const iterators - typedef T const *const_iterator; + typedef const T * const_iterator; //: Iterator pointing to start of data - const_iterator begin() const { return data_; } + const_iterator + begin() const + { + return data_; + } //: Iterator pointing to element beyond end of data - const_iterator end() const { return begin() + this->size(); } + const_iterator + end() const + { + return begin() + this->size(); + } //: Type defs for iterators typedef const T element_type; //: Type defs for iterators - typedef const T *iterator; + typedef const T * iterator; - T const & operator() (unsigned r, unsigned c) const + const T & + operator()(unsigned r, unsigned c) const { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert(r apply(T (*f)(T)) const; + vnl_matrix_fixed apply(T (*f)(T)) const; //: Make a new matrix by applying function to each element. - vnl_matrix_fixed apply(T (*f)(T const&)) const; + vnl_matrix_fixed apply(T (*f)(const T &)) const; //: Return transpose - vnl_matrix_fixed transpose () const; + vnl_matrix_fixed + transpose() const; //: Return conjugate transpose - vnl_matrix_fixed conjugate_transpose () const; + vnl_matrix_fixed + conjugate_transpose() const; //: Extract a sub-matrix of size rows x cols, starting at (top,left) // Thus it contains elements [top,top+rows-1][left,left+cols-1] - vnl_matrix extract (unsigned rowz, unsigned colz, - unsigned top=0, unsigned left=0) const; + vnl_matrix + extract(unsigned rowz, unsigned colz, unsigned top = 0, unsigned left = 0) const; //: Get n rows beginning at rowstart - vnl_matrix get_n_rows (unsigned rowstart, unsigned n) const; + vnl_matrix + get_n_rows(unsigned rowstart, unsigned n) const; //: Get n columns beginning at colstart - vnl_matrix get_n_columns(unsigned colstart, unsigned n) const; + vnl_matrix + get_n_columns(unsigned colstart, unsigned n) const; //: Type def for norms. typedef typename vnl_c_vector::abs_t abs_t; //: Return sum of absolute values of elements - abs_t array_one_norm() const { return vnl_c_vector::one_norm(begin(), size()); } + abs_t + array_one_norm() const + { + return vnl_c_vector::one_norm(begin(), size()); + } //: Return square root of sum of squared absolute element values - abs_t array_two_norm() const { return vnl_c_vector::two_norm(begin(), size()); } + abs_t + array_two_norm() const + { + return vnl_c_vector::two_norm(begin(), size()); + } //: Return largest absolute element value - abs_t array_inf_norm() const { return vnl_c_vector::inf_norm(begin(), size()); } + abs_t + array_inf_norm() const + { + return vnl_c_vector::inf_norm(begin(), size()); + } //: Return sum of absolute values of elements - abs_t absolute_value_sum() const { return array_one_norm(); } + abs_t + absolute_value_sum() const + { + return array_one_norm(); + } //: Return largest absolute value - abs_t absolute_value_max() const { return array_inf_norm(); } + abs_t + absolute_value_max() const + { + return array_inf_norm(); + } // $ || M ||_1 := \max_j \sum_i | M_{ij} | $ - abs_t operator_one_norm() const; + abs_t + operator_one_norm() const; // $ || M ||_\inf := \max_i \sum_j | M_{ij} | $ - abs_t operator_inf_norm() const; + abs_t + operator_inf_norm() const; //: Return Frobenius norm of matrix (sqrt of sum of squares of its elements) - abs_t frobenius_norm() const { return vnl_c_vector::two_norm(begin(), size()); } + abs_t + frobenius_norm() const + { + return vnl_c_vector::two_norm(begin(), size()); + } //: Return Frobenius norm of matrix (sqrt of sum of squares of its elements) - abs_t fro_norm() const { return frobenius_norm(); } + abs_t + fro_norm() const + { + return frobenius_norm(); + } //: Return RMS of all elements - abs_t rms() const { return vnl_c_vector::rms_norm(begin(), size()); } + abs_t + rms() const + { + return vnl_c_vector::rms_norm(begin(), size()); + } //: Return minimum value of elements - T min_value() const { return vnl_c_vector::min_value(begin(), size()); } + T + min_value() const + { + return vnl_c_vector::min_value(begin(), size()); + } //: Return maximum value of elements - T max_value() const { return vnl_c_vector::max_value(begin(), size()); } + T + max_value() const + { + return vnl_c_vector::max_value(begin(), size()); + } //: Return location of minimum value of elements - unsigned arg_min() const { return vnl_c_vector::arg_min(begin(), size()); } + unsigned + arg_min() const + { + return vnl_c_vector::arg_min(begin(), size()); + } //: Return location of maximum value of elements - unsigned arg_max() const { return vnl_c_vector::arg_max(begin(), size()); } + unsigned + arg_max() const + { + return vnl_c_vector::arg_max(begin(), size()); + } //: Return mean of all matrix elements - T mean() const { return vnl_c_vector::mean(begin(), size()); } + T + mean() const + { + return vnl_c_vector::mean(begin(), size()); + } // predicates //: Return true iff the size is zero. - bool empty() const { return num_rows==0 && num_cols==0; } + bool + empty() const + { + return num_rows == 0 && num_cols == 0; + } //: Return true if all elements equal to identity. - bool is_identity() const; + bool + is_identity() const; //: Return true if all elements equal to identity, within given tolerance - bool is_identity(double tol) const; + bool + is_identity(double tol) const; //: Return true if all elements equal to zero. - bool is_zero() const; + bool + is_zero() const; //: Return true if all elements equal to zero, within given tolerance - bool is_zero(double tol) const; + bool + is_zero(double tol) const; //: Return true if finite - bool is_finite() const; + bool + is_finite() const; //: Return true if matrix contains NaNs - bool has_nans() const; + bool + has_nans() const; //: abort if size is not as expected // This function does or tests nothing if NDEBUG is defined #ifndef NDEBUG - void assert_size(unsigned rowz, unsigned colz) const + void + assert_size(unsigned rowz, unsigned colz) const #else - void assert_size(unsigned , unsigned ) const + void + assert_size(unsigned, unsigned) const #endif { #ifndef NDEBUG @@ -362,84 +468,142 @@ class VNL_EXPORT vnl_matrix_fixed_ref_const } //: abort if matrix contains any INFs or NANs. // This function does or tests nothing if NDEBUG is defined - void assert_finite() const + void + assert_finite() const { #ifndef NDEBUG assert_finite_internal(); #endif } - static void add( const T* a, const T* b, T* r ) { vnl_matrix_fixed::add(a,b,r); } - static void add( const T* a, T b, T* r ) { vnl_matrix_fixed::add(a,b,r); } - static void sub( const T* a, const T* b, T* r ) { vnl_matrix_fixed::sub(a,b,r); } - static void sub( const T* a, T b, T* r ) { vnl_matrix_fixed::sub(a,b,r); } - static void sub( T a, const T* b, T* r ) { vnl_matrix_fixed::sub(a,b,r); } - static void mul( const T* a, const T* b, T* r ) { vnl_matrix_fixed::mul(a,b,r); } - static void mul( const T* a, T b, T* r ) { vnl_matrix_fixed::mul(a,b,r); } - static void div( const T* a, const T* b, T* r ) { vnl_matrix_fixed::div(a,b,r); } - static void div( const T* a, T b, T* r ) { vnl_matrix_fixed::div(a,b,r); } + static void + add(const T * a, const T * b, T * r) + { + vnl_matrix_fixed::add(a, b, r); + } + static void + add(const T * a, T b, T * r) + { + vnl_matrix_fixed::add(a, b, r); + } + static void + sub(const T * a, const T * b, T * r) + { + vnl_matrix_fixed::sub(a, b, r); + } + static void + sub(const T * a, T b, T * r) + { + vnl_matrix_fixed::sub(a, b, r); + } + static void + sub(T a, const T * b, T * r) + { + vnl_matrix_fixed::sub(a, b, r); + } + static void + mul(const T * a, const T * b, T * r) + { + vnl_matrix_fixed::mul(a, b, r); + } + static void + mul(const T * a, T b, T * r) + { + vnl_matrix_fixed::mul(a, b, r); + } + static void + div(const T * a, const T * b, T * r) + { + vnl_matrix_fixed::div(a, b, r); + } + static void + div(const T * a, T b, T * r) + { + vnl_matrix_fixed::div(a, b, r); + } - static bool equal( const T* a, const T* b ) { return vnl_matrix_fixed::equal(a,b); } + static bool + equal(const T * a, const T * b) + { + return vnl_matrix_fixed::equal(a, b); + } - private: - const vnl_matrix_fixed_ref_const & operator=(const vnl_matrix_fixed_ref_const& ) const +private: + const vnl_matrix_fixed_ref_const & + operator=(const vnl_matrix_fixed_ref_const &) const { assert(!"Assignment is illegal for a vnl_matrix_fixed_ref_const"); return *this; } - void assert_finite_internal() const; + void + assert_finite_internal() const; - void assert_size_internal(unsigned, unsigned) const; + void + assert_size_internal(unsigned, unsigned) const; }; template -class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const +class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const { - typedef vnl_matrix_fixed_ref_const base; + typedef vnl_matrix_fixed_ref_const base; - public: +public: // this is the only point where the const_cast happens // the base class is used to store the pointer, so that conversion is not necessary - T * data_block() const { - return const_cast(this->data_); - } - vnl_matrix_fixed_ref(vnl_matrix_fixed& rhs) - : base(rhs.data_block()) + T * + data_block() const { + return const_cast(this->data_); } + vnl_matrix_fixed_ref(vnl_matrix_fixed & rhs) + : base(rhs.data_block()) + {} explicit vnl_matrix_fixed_ref(T * dataptr) : base(dataptr) - { - } + {} //: Copy another vnl_matrix_fixed into this. - vnl_matrix_fixed_ref const & operator=(const vnl_matrix_fixed_ref_const& rhs) const + const vnl_matrix_fixed_ref & + operator=(const vnl_matrix_fixed_ref_const & rhs) const { - std::memcpy(data_block(), rhs.data_block(), num_rows*num_cols*sizeof(T)); + std::memcpy(data_block(), rhs.data_block(), num_rows * num_cols * sizeof(T)); return *this; } // Basic 2D-Array functionality------------------------------------------- //: set element - void put (unsigned r, unsigned c, T const& v) { (*this)(r,c) = v; } + void + put(unsigned r, unsigned c, const T & v) + { + (*this)(r, c) = v; + } //: get element - T get (unsigned r, unsigned c) const { return (*this)(r,c); } + T + get(unsigned r, unsigned c) const + { + return (*this)(r, c); + } //: return pointer to given row // No boundary checking here. - T * operator[] (unsigned r) const { return data_block() + num_cols * r; } + T * + operator[](unsigned r) const + { + return data_block() + num_cols * r; + } //: Access an element for reading or writing // There are assert style boundary checks - #define NDEBUG to turn them off. - T & operator() (unsigned r, unsigned c) const + T & + operator()(unsigned r, unsigned c) const { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert(rdata_block() + num_cols * r + c); } @@ -458,7 +622,7 @@ class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const(1.0).normalize_columns()); // \endcode - vnl_matrix_fixed_ref const& fill (T) const; + const vnl_matrix_fixed_ref & fill(T) const; //: Sets all diagonal elements of matrix to specified value; returns "*this". // Complexity $O(\min(r,c))$ @@ -472,13 +636,14 @@ class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const().fill_diagonal(5)); // \endcode - vnl_matrix_fixed_ref const& fill_diagonal (T) const; + const vnl_matrix_fixed_ref & fill_diagonal(T) const; //: Sets the diagonal elements of this matrix to the specified list of values. // Returning "*this" allows "chaining" two or more operations: see the // reasoning (and the examples) in the documentation for method // fill_diagonal(). - vnl_matrix_fixed_ref const& set_diagonal(vnl_vector const&) const; + const vnl_matrix_fixed_ref & + set_diagonal(const vnl_vector &) const; //: Fills (laminates) this matrix with the given data, then returns it. // We assume that the argument points to a contiguous rows*cols array, stored rowwise. @@ -493,11 +658,16 @@ class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const().copy_in(array)); // \endcode - vnl_matrix_fixed_ref const& copy_in(T const *) const; + const vnl_matrix_fixed_ref & + copy_in(const T *) const; //: Fills (laminates) this matrix with the given data, then returns it. // A synonym for copy_in() - vnl_matrix_fixed_ref const& set(T const *d) const { return copy_in(d); } + const vnl_matrix_fixed_ref & + set(const T * d) const + { + return copy_in(d); + } //: Fills the given array with this matrix. // We assume that the argument points to a contiguous rows*cols array, stored rowwise. @@ -509,115 +679,144 @@ class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const const& m) const + const vnl_matrix_fixed_ref & + operator+=(const vnl_matrix_fixed_ref_const & m) const { - base::add( data_block(), m.data_block(), data_block() ); return *this; + base::add(data_block(), m.data_block(), data_block()); + return *this; } //: - vnl_matrix_fixed_ref const& operator+= (vnl_matrix const& m) const + const vnl_matrix_fixed_ref & + operator+=(const vnl_matrix & m) const { - assert( m.rows() == num_rows && m.cols() == num_cols ); - base::add( data_block(), m.data_block(), data_block() ); return *this; + assert(m.rows() == num_rows && m.cols() == num_cols); + base::add(data_block(), m.data_block(), data_block()); + return *this; } //: - vnl_matrix_fixed_ref const& operator-= (vnl_matrix_fixed_ref_const const& m) const + const vnl_matrix_fixed_ref & + operator-=(const vnl_matrix_fixed_ref_const & m) const { - base::sub( data_block(), m.data_block(), data_block() ); return *this; + base::sub(data_block(), m.data_block(), data_block()); + return *this; } //: - vnl_matrix_fixed_ref const& operator-= (vnl_matrix const& m) const + const vnl_matrix_fixed_ref & + operator-=(const vnl_matrix & m) const { - assert( m.rows() == num_rows && m.cols() == num_cols ); - base::sub( data_block(), m.data_block(), data_block() ); return *this; + assert(m.rows() == num_rows && m.cols() == num_cols); + base::sub(data_block(), m.data_block(), data_block()); + return *this; } //: Negate all elements of matrix - vnl_matrix_fixed operator- () const + vnl_matrix_fixed + operator-() const { - vnl_matrix_fixed r; - base::sub( T(0), data_block(), r.data_block() ); + vnl_matrix_fixed r; + base::sub(T(0), data_block(), r.data_block()); return r; } //: - vnl_matrix_fixed_ref const& operator*= (vnl_matrix_fixed_ref_const const& s) const + const vnl_matrix_fixed_ref & + operator*=(const vnl_matrix_fixed_ref_const & s) const { vnl_matrix_fixed out; for (unsigned i = 0; i < num_rows; ++i) for (unsigned j = 0; j < num_cols; ++j) { - T accum = this->operator()(i,0) * s(0,j); + T accum = this->operator()(i, 0) * s(0, j); for (unsigned k = 1; k < num_cols; ++k) - accum += this->operator()(i,k) * s(k,j); - out(i,j) = accum; + accum += this->operator()(i, k) * s(k, j); + out(i, j) = accum; } *this = out; return *this; } //: Set values of this matrix to those of M, starting at [top,left] - vnl_matrix_fixed_ref const & update (vnl_matrix const&, unsigned top=0, unsigned left=0) const; + const vnl_matrix_fixed_ref & + update(const vnl_matrix &, unsigned top = 0, unsigned left = 0) const; //: Set the elements of the i'th column to v[i] (No bounds checking) - vnl_matrix_fixed_ref const& set_column(unsigned i, T const * v) const; + const vnl_matrix_fixed_ref & + set_column(unsigned i, const T * v) const; //: Set the elements of the i'th column to value, then return *this. - vnl_matrix_fixed_ref const& set_column(unsigned i, T value ) const; + const vnl_matrix_fixed_ref & + set_column(unsigned i, T value) const; //: Set j-th column to v, then return *this. - vnl_matrix_fixed_ref const& set_column(unsigned j, vnl_vector const& v) const; + const vnl_matrix_fixed_ref & + set_column(unsigned j, const vnl_vector & v) const; //: Set j-th column to v, then return *this. - vnl_matrix_fixed_ref const& set_column(unsigned j, vnl_vector_fixed const& v) const; + const vnl_matrix_fixed_ref & + set_column(unsigned j, const vnl_vector_fixed & v) const; //: Set columns to those in M, starting at starting_column, then return *this. - vnl_matrix_fixed_ref const& set_columns(unsigned starting_column, vnl_matrix const& M) const; + const vnl_matrix_fixed_ref & + set_columns(unsigned starting_column, const vnl_matrix & M) const; //: Set the elements of the i'th row to v[i] (No bounds checking) - vnl_matrix_fixed_ref const& set_row (unsigned i, T const * v) const; + const vnl_matrix_fixed_ref & + set_row(unsigned i, const T * v) const; //: Set the elements of the i'th row to value, then return *this. - vnl_matrix_fixed_ref const& set_row (unsigned i, T value ) const; + const vnl_matrix_fixed_ref & + set_row(unsigned i, T value) const; //: Set the i-th row to v, then return *this. - vnl_matrix_fixed_ref const& set_row (unsigned i, vnl_vector const& v) const; + const vnl_matrix_fixed_ref & + set_row(unsigned i, const vnl_vector & v) const; //: Set the i-th row to v, then return *this. - vnl_matrix_fixed_ref const& set_row (unsigned i, vnl_vector_fixed const& v) const; + const vnl_matrix_fixed_ref & + set_row(unsigned i, const vnl_vector_fixed & v) const; // ==== mutators ==== @@ -633,7 +832,8 @@ class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const(1.0).normalize_rows()); // \endcode - vnl_matrix_fixed_ref const& normalize_rows() const; + const vnl_matrix_fixed_ref & + normalize_rows() const; //: Normalizes each column so it is a unit vector, and returns "*this". // Zero columns are not modified @@ -677,7 +880,8 @@ class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const(1.0).normalize_columns()); // \endcode - vnl_matrix_fixed_ref const& normalize_columns() const; + const vnl_matrix_fixed_ref & + normalize_columns() const; //: Scales elements in given row by a factor T, and returns "*this". // Returning "*this" allows "chaining" two or more operations: @@ -685,7 +889,8 @@ class VNL_EXPORT vnl_matrix_fixed_ref : public vnl_matrix_fixed_ref_const as_ref() { return vnl_matrix_ref( num_rows, num_cols, const_cast(data_block()) ); } - const vnl_matrix_ref as_ref() const { return vnl_matrix_ref( num_rows, num_cols, const_cast(data_block()) ); } - vnl_matrix as_matrix() const { return vnl_matrix(const_cast(data_block()),num_rows,num_cols); } + vnl_matrix_ref + as_ref() + { + return vnl_matrix_ref(num_rows, num_cols, const_cast(data_block())); + } + const vnl_matrix_ref + as_ref() const + { + return vnl_matrix_ref(num_rows, num_cols, const_cast(data_block())); + } + vnl_matrix + as_matrix() const + { + return vnl_matrix(const_cast(data_block()), num_rows, num_cols); + } //: Cheap conversion to vnl_matrix_ref // Sometimes, such as with templated functions, the compiler cannot // use this user-defined conversion. For those cases, use the // explicit as_ref() method instead. -#if ! VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS - explicit operator const vnl_matrix_ref() const { return vnl_matrix_ref( num_rows, num_cols, const_cast(data_block()) ); } +#if !VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS + explicit + operator const vnl_matrix_ref() const + { + return vnl_matrix_ref(num_rows, num_cols, const_cast(data_block())); + } #else -#if VXL_LEGACY_FUTURE_REMOVE - VXL_DEPRECATED_MSG("Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") -#endif - operator const vnl_matrix_ref() const { return vnl_matrix_ref( num_rows, num_cols, const_cast(data_block()) ); } +# if VXL_LEGACY_FUTURE_REMOVE + VXL_DEPRECATED_MSG( + "Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") +# endif + operator const vnl_matrix_ref() const + { + return vnl_matrix_ref(num_rows, num_cols, const_cast(data_block())); + } #endif - explicit operator vnl_matrix() const { return this->as_matrix(); } + explicit + operator vnl_matrix() const + { + return this->as_matrix(); + } //---------------------------------------------------------------------- typedef T element_type; //: Iterators - typedef T *iterator; + typedef T * iterator; //: Iterator pointing to start of data - iterator begin() const { return data_block(); } + iterator + begin() const + { + return data_block(); + } //: Iterator pointing to element beyond end of data - iterator end() const { return begin() + this->size(); } + iterator + end() const + { + return begin() + this->size(); + } //-------------------------------------------------------------------------------- //: Return true if *this == rhs - bool operator_eq (vnl_matrix_fixed_ref_const const & rhs) const + bool + operator_eq(const vnl_matrix_fixed_ref_const & rhs) const { - return vnl_matrix_fixed_ref::equal( this->data_block(), rhs.data_block() ); + return vnl_matrix_fixed_ref::equal(this->data_block(), rhs.data_block()); } //: Equality operator - bool operator==(vnl_matrix_fixed_ref_const const &that) const { return this->operator_eq(that); } + bool + operator==(const vnl_matrix_fixed_ref_const & that) const + { + return this->operator_eq(that); + } //: Equality operator with vnl_matrix_fixed (fix c++20 ambigous overload) - bool operator==(vnl_matrix_fixed const &that) const { return this->operator_eq(that); } + bool + operator==(const vnl_matrix_fixed & that) const + { + return this->operator_eq(that); + } //: Inequality operator - bool operator!=(vnl_matrix_fixed_ref_const const &that) const { return !this->operator_eq(that); } + bool + operator!=(const vnl_matrix_fixed_ref_const & that) const + { + return !this->operator_eq(that); + } -//-------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------- }; - // Helper routines for arithmetic. These routines know the size from - // the template parameters. The vector-vector operations are - // element-wise. +// Helper routines for arithmetic. These routines know the size from +// the template parameters. The vector-vector operations are +// element-wise. // Make the operators below inline because (1) they are small and // (2) we then have less explicit instantiation trouble. // --- Matrix-scalar ------------------------------------------------------------- -template -inline -vnl_matrix_fixed operator+( const vnl_matrix_fixed_ref_const& mat1, const vnl_matrix_fixed_ref_const& mat2 ) +template +inline vnl_matrix_fixed +operator+(const vnl_matrix_fixed_ref_const & mat1, const vnl_matrix_fixed_ref_const & mat2) { - vnl_matrix_fixed r; - vnl_matrix_fixed::add( mat1.data_block(), mat2.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::add(mat1.data_block(), mat2.data_block(), r.data_block()); return r; } -template -inline -vnl_matrix_fixed operator+( const vnl_matrix_fixed_ref_const& mat, T s ) +template +inline vnl_matrix_fixed +operator+(const vnl_matrix_fixed_ref_const & mat, T s) { - vnl_matrix_fixed r; - vnl_matrix_fixed::add( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::add(mat.data_block(), s, r.data_block()); return r; } -template -inline -vnl_matrix_fixed operator+( T s, const vnl_matrix_fixed_ref_const& mat ) +template +inline vnl_matrix_fixed +operator+(T s, const vnl_matrix_fixed_ref_const & mat) { - vnl_matrix_fixed r; - vnl_matrix_fixed::add( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::add(mat.data_block(), s, r.data_block()); return r; } -template -inline -vnl_matrix_fixed operator-( const vnl_matrix_fixed_ref_const& mat1, const vnl_matrix_fixed_ref_const& mat2 ) +template +inline vnl_matrix_fixed +operator-(const vnl_matrix_fixed_ref_const & mat1, const vnl_matrix_fixed_ref_const & mat2) { - vnl_matrix_fixed r; - vnl_matrix_fixed::sub( mat1.data_block(), mat2.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::sub(mat1.data_block(), mat2.data_block(), r.data_block()); return r; } -template -inline -vnl_matrix_fixed operator-( const vnl_matrix_fixed_ref_const& mat, T s ) +template +inline vnl_matrix_fixed +operator-(const vnl_matrix_fixed_ref_const & mat, T s) { - vnl_matrix_fixed r; - vnl_matrix_fixed::sub( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::sub(mat.data_block(), s, r.data_block()); return r; } -template -inline -vnl_matrix_fixed operator-( T s, const vnl_matrix_fixed_ref_const& mat ) +template +inline vnl_matrix_fixed +operator-(T s, const vnl_matrix_fixed_ref_const & mat) { - vnl_matrix_fixed r; - vnl_matrix_fixed::sub( s, mat.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::sub(s, mat.data_block(), r.data_block()); return r; } -template -inline -vnl_matrix_fixed operator*( const vnl_matrix_fixed_ref_const& mat, T s ) +template +inline vnl_matrix_fixed +operator*(const vnl_matrix_fixed_ref_const & mat, T s) { - vnl_matrix_fixed r; - vnl_matrix_fixed::mul( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::mul(mat.data_block(), s, r.data_block()); return r; } -template -inline -vnl_matrix_fixed operator*( T s, const vnl_matrix_fixed_ref_const& mat ) +template +inline vnl_matrix_fixed +operator*(T s, const vnl_matrix_fixed_ref_const & mat) { - vnl_matrix_fixed r; - vnl_matrix_fixed::mul( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::mul(mat.data_block(), s, r.data_block()); return r; } -template -inline -vnl_matrix_fixed operator/( const vnl_matrix_fixed_ref_const& mat, T s ) +template +inline vnl_matrix_fixed +operator/(const vnl_matrix_fixed_ref_const & mat, T s) { - vnl_matrix_fixed r; - vnl_matrix_fixed::div( mat.data_block(), s, r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::div(mat.data_block(), s, r.data_block()); return r; } -template -inline -vnl_matrix_fixed element_product( const vnl_matrix_fixed_ref_const& mat1, - const vnl_matrix_fixed_ref_const& mat2 ) +template +inline vnl_matrix_fixed +element_product(const vnl_matrix_fixed_ref_const & mat1, const vnl_matrix_fixed_ref_const & mat2) { - vnl_matrix_fixed r; - vnl_matrix_fixed::mul( mat1.data_block(), mat2.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::mul(mat1.data_block(), mat2.data_block(), r.data_block()); return r; } -template -inline -vnl_matrix_fixed element_quotient( const vnl_matrix_fixed_ref_const& mat1, - const vnl_matrix_fixed_ref_const& mat2) +template +inline vnl_matrix_fixed +element_quotient(const vnl_matrix_fixed_ref_const & mat1, const vnl_matrix_fixed_ref_const & mat2) { - vnl_matrix_fixed r; - vnl_matrix_fixed::div( mat1.data_block(), mat2.data_block(), r.data_block() ); + vnl_matrix_fixed r; + vnl_matrix_fixed::div(mat1.data_block(), mat2.data_block(), r.data_block()); return r; } @@ -878,17 +1129,15 @@ vnl_matrix_fixed element_quotient( const vnl_matrix_fixed_ref_const -inline -vnl_vector_fixed -vnl_matrix_fixed_mat_vec_mult(const vnl_matrix_fixed_ref_const& a, - const vnl_vector_fixed_ref_const& b) +inline vnl_vector_fixed +vnl_matrix_fixed_mat_vec_mult(const vnl_matrix_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { vnl_vector_fixed out; for (unsigned i = 0; i < M; ++i) { - T accum = a(i,0) * b(0); + T accum = a(i, 0) * b(0); for (unsigned k = 1; k < N; ++k) - accum += a(i,k) * b(k); + accum += a(i, k) * b(k); out(i) = accum; } return out; @@ -896,19 +1145,18 @@ vnl_matrix_fixed_mat_vec_mult(const vnl_matrix_fixed_ref_const& a, // see comment above template -inline -vnl_matrix_fixed -vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed_ref_const& a, - const vnl_matrix_fixed_ref_const& b) +inline vnl_matrix_fixed +vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed_ref_const & a, + const vnl_matrix_fixed_ref_const & b) { vnl_matrix_fixed out; for (unsigned i = 0; i < M; ++i) for (unsigned j = 0; j < O; ++j) { - T accum = a(i,0) * b(0,j); + T accum = a(i, 0) * b(0, j); for (unsigned k = 1; k < N; ++k) - accum += a(i,k) * b(k,j); - out(i,j) = accum; + accum += a(i, k) * b(k, j); + out(i, j) = accum; } return out; } @@ -919,69 +1167,77 @@ vnl_matrix_fixed_mat_mat_mult(const vnl_matrix_fixed_ref_const& a, // \relatesalso vnl_vector_fixed // \relatesalso vnl_matrix_fixed template -inline -vnl_vector_fixed operator*(const vnl_matrix_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b) +inline vnl_vector_fixed +operator*(const vnl_matrix_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - return vnl_matrix_fixed_mat_vec_mult(a,b); + return vnl_matrix_fixed_mat_vec_mult(a, b); } //: Multiply two conformant vnl_matrix_fixed (M x N) times (N x O) // \relatesalso vnl_matrix_fixed template -inline -vnl_matrix_fixed operator*(const vnl_matrix_fixed_ref_const& a, const vnl_matrix_fixed_ref_const& b) +inline vnl_matrix_fixed +operator*(const vnl_matrix_fixed_ref_const & a, const vnl_matrix_fixed_ref_const & b) { - return vnl_matrix_fixed_mat_mat_mult(a,b); + return vnl_matrix_fixed_mat_mat_mult(a, b); } // These overloads for the common case of mixing a fixed with a // non-fixed. Because the operator* are templated, the fixed will not // be automatically converted to a non-fixed-ref. These do it for you. -template -inline vnl_matrix operator+( const vnl_matrix_fixed_ref_const& a, const vnl_matrix& b ) +template +inline vnl_matrix +operator+(const vnl_matrix_fixed_ref_const & a, const vnl_matrix & b) { return a.as_ref() + b; } -template -inline vnl_matrix operator+( const vnl_matrix& a, const vnl_matrix_fixed_ref_const& b ) +template +inline vnl_matrix +operator+(const vnl_matrix & a, const vnl_matrix_fixed_ref_const & b) { return a + b.as_ref(); } -template -inline vnl_matrix operator-( const vnl_matrix_fixed_ref_const& a, const vnl_matrix& b ) +template +inline vnl_matrix +operator-(const vnl_matrix_fixed_ref_const & a, const vnl_matrix & b) { return a.as_ref() - b; } -template -inline vnl_matrix operator-( const vnl_matrix& a, const vnl_matrix_fixed_ref_const& b ) +template +inline vnl_matrix +operator-(const vnl_matrix & a, const vnl_matrix_fixed_ref_const & b) { return a - b.as_ref(); } -template -inline vnl_matrix operator*( const vnl_matrix_fixed_ref_const& a, const vnl_matrix& b ) +template +inline vnl_matrix +operator*(const vnl_matrix_fixed_ref_const & a, const vnl_matrix & b) { return a.as_ref() * b; } -template -inline vnl_matrix operator*( const vnl_matrix& a, const vnl_matrix_fixed_ref_const& b ) +template +inline vnl_matrix +operator*(const vnl_matrix & a, const vnl_matrix_fixed_ref_const & b) { return a * b.as_ref(); } -template -inline vnl_vector operator*( const vnl_matrix_fixed_ref_const& a, const vnl_vector& b ) +template +inline vnl_vector +operator*(const vnl_matrix_fixed_ref_const & a, const vnl_vector & b) { return a.as_ref() * b; } -template -inline vnl_vector operator*( const vnl_matrix& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_vector +operator*(const vnl_matrix & a, const vnl_vector_fixed_ref_const & b) { return a * b.as_ref(); } @@ -989,17 +1245,17 @@ inline vnl_vector operator*( const vnl_matrix& a, const vnl_vector_fixed_r // --- I/O operations ------------------------------------------------------------ -template -inline -std::ostream& operator<< (std::ostream& os, vnl_matrix_fixed_ref_const const& mat) +template +inline std::ostream & +operator<<(std::ostream & os, const vnl_matrix_fixed_ref_const & mat) { mat.print(os); return os; } -template -inline -std::istream& operator>> (std::istream& is, vnl_matrix_fixed_ref const& mat) +template +inline std::istream & +operator>>(std::istream & is, const vnl_matrix_fixed_ref & mat) { mat.read_ascii(is); return is; diff --git a/core/vnl/vnl_matrix_fixed_ref.hxx b/core/vnl/vnl_matrix_fixed_ref.hxx index 235f6828fb9..29af7ea2254 100644 --- a/core/vnl/vnl_matrix_fixed_ref.hxx +++ b/core/vnl/vnl_matrix_fixed_ref.hxx @@ -19,393 +19,389 @@ //------------------------------------------------------------ -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::fill (T value) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::fill(T value) const { for (unsigned int i = 0; i < nrows; i++) for (unsigned int j = 0; j < ncols; j++) - (*this)(i,j) = value; + (*this)(i, j) = value; return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::fill_diagonal(T value) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::fill_diagonal(T value) const { for (unsigned int i = 0; i < nrows && i < ncols; i++) - (*this)(i,i) = value; + (*this)(i, i) = value; return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_diagonal(vnl_vector const& diag) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_diagonal(const vnl_vector & diag) const { assert(diag.size() >= nrows || diag.size() >= ncols); // The length of the diagonal of a non-square matrix is the minimum of // the matrix's width & height; that explains the "||" in the assert, // and the "&&" in the upper bound for the "for". for (unsigned int i = 0; i < nrows && i < ncols; ++i) - (*this)(i,i) = diag[i]; + (*this)(i, i) = diag[i]; return *this; } -template +template void -vnl_matrix_fixed_ref_const::print(std::ostream& os) const +vnl_matrix_fixed_ref_const::print(std::ostream & os) const { for (unsigned int i = 0; i < nrows; i++) { - os << (*this)(i,0); + os << (*this)(i, 0); for (unsigned int j = 1; j < ncols; j++) - os << ' ' << (*this)(i,j); + os << ' ' << (*this)(i, j); os << '\n'; } } template -vnl_matrix_fixed -vnl_matrix_fixed_ref_const::apply(T (*f)(T const&)) const +vnl_matrix_fixed +vnl_matrix_fixed_ref_const::apply(T (*f)(const T &)) const { - vnl_matrix_fixed ret; - vnl_c_vector::apply(this->begin(), rows()*cols(), f, ret.data_block()); + vnl_matrix_fixed ret; + vnl_c_vector::apply(this->begin(), rows() * cols(), f, ret.data_block()); return ret; } template -vnl_matrix_fixed -vnl_matrix_fixed_ref_const::apply(T (*f)(T)) const +vnl_matrix_fixed +vnl_matrix_fixed_ref_const::apply(T (*f)(T)) const { - vnl_matrix_fixed ret; - vnl_c_vector::apply(this->begin(), rows()*cols(), f, ret.data_block()); + vnl_matrix_fixed ret; + vnl_c_vector::apply(this->begin(), rows() * cols(), f, ret.data_block()); return ret; } ////--------------------------- Additions------------------------------------ -template -vnl_matrix_fixed -vnl_matrix_fixed_ref_const::transpose() const +template +vnl_matrix_fixed +vnl_matrix_fixed_ref_const::transpose() const { - vnl_matrix_fixed result; + vnl_matrix_fixed result; for (unsigned int i = 0; i < cols(); i++) for (unsigned int j = 0; j < rows(); j++) - result(i,j) = (*this)(j,i); + result(i, j) = (*this)(j, i); return result; } -template -vnl_matrix_fixed -vnl_matrix_fixed_ref_const::conjugate_transpose() const +template +vnl_matrix_fixed +vnl_matrix_fixed_ref_const::conjugate_transpose() const { - vnl_matrix_fixed result(transpose()); - vnl_c_vector::conjugate(result.begin(), // src - result.begin(), // dst - result.size()); // size of block + vnl_matrix_fixed result(transpose()); + vnl_c_vector::conjugate(result.begin(), // src + result.begin(), // dst + result.size()); // size of block return result; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::update (vnl_matrix const& m, - unsigned top, unsigned left) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::update(const vnl_matrix & m, unsigned top, unsigned left) const { const unsigned int bottom = top + m.rows(); const unsigned int right = left + m.cols(); #ifndef NDEBUG if (nrows < bottom || ncols < right) - vnl_error_matrix_dimension ("update", - bottom, right, m.rows(), m.cols()); + vnl_error_matrix_dimension("update", bottom, right, m.rows(), m.cols()); #endif for (unsigned int i = top; i < bottom; i++) for (unsigned int j = left; j < right; j++) - (*this)(i,j) = m(i-top,j-left); + (*this)(i, j) = m(i - top, j - left); return *this; } -template +template vnl_matrix -vnl_matrix_fixed_ref_const::extract (unsigned rowz, unsigned colz, - unsigned top, unsigned left) const +vnl_matrix_fixed_ref_const::extract(unsigned rowz, unsigned colz, unsigned top, unsigned left) const { #ifndef NDEBUG unsigned int bottom = top + rowz; unsigned int right = left + colz; if ((nrows < bottom) || (ncols < right)) - vnl_error_matrix_dimension ("extract", - nrows, ncols, bottom, right); + vnl_error_matrix_dimension("extract", nrows, ncols, bottom, right); #endif vnl_matrix result(rowz, colz); - for (unsigned int i = 0; i < rowz; i++) // actual copy of all elements - for (unsigned int j = 0; j < colz; j++) // in submatrix - result(i,j) = (*this)(top+i,left+j); + for (unsigned int i = 0; i < rowz; i++) // actual copy of all elements + for (unsigned int j = 0; j < colz; j++) // in submatrix + result(i, j) = (*this)(top + i, left + j); return result; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::copy_in(T const *p) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::copy_in(const T * p) const { - T* dp = this->data_block(); + T * dp = this->data_block(); unsigned int i = nrows * ncols; while (i--) *dp++ = *p++; return *this; } -template -void vnl_matrix_fixed_ref_const::copy_out(T *p) const +template +void +vnl_matrix_fixed_ref_const::copy_out(T * p) const { - T const* dp = this->data_block(); - unsigned int i = nrows*ncols; + const T * dp = this->data_block(); + unsigned int i = nrows * ncols; while (i--) *p++ = *dp++; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_identity() const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_identity() const { // Two simple loops are generally better than having a branch inside // the loop. Probably worth the O(n) extra writes. for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) - (*this)(i,j) = T(0); + (*this)(i, j) = T(0); for (unsigned int i = 0; i < nrows && i < ncols; ++i) - (*this)(i,i) = T(1); + (*this)(i, i) = T(1); return *this; } //: Make each row of the matrix have unit norm. // All-zero rows are ignored. -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::normalize_rows() const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::normalize_rows() const { typedef typename vnl_numeric_traits::abs_t Abs_t; for (unsigned int i = 0; i < nrows; i++) { Abs_t norm(0); // double will not do for all types. for (unsigned int j = 0; j < ncols; j++) - norm += vnl_math::squared_magnitude( (*this)(i,j) ); + norm += vnl_math::squared_magnitude((*this)(i, j)); if (norm != 0) { typedef typename vnl_numeric_traits::real_t real_t; - real_t scale = real_t(1)/std::sqrt((real_t)norm); + const real_t scale = real_t(1) / std::sqrt((real_t)norm); for (unsigned int j = 0; j < ncols; j++) { // FIXME need correct rounding here // There is e.g. no *standard* operator*=(complex, double), hence the T() cast. - (*this)(i,j) *= (T)(scale); + (*this)(i, j) *= (T)(scale); } } } return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::normalize_columns() const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::normalize_columns() const { typedef typename vnl_numeric_traits::abs_t Abs_t; - for (unsigned int j = 0; j < ncols; j++) { // For each column in the Matrix + for (unsigned int j = 0; j < ncols; j++) + { // For each column in the Matrix Abs_t norm(0); // double will not do for all types. for (unsigned int i = 0; i < nrows; i++) - norm += vnl_math::squared_magnitude( (*this)(i,j) ); + norm += vnl_math::squared_magnitude((*this)(i, j)); if (norm != 0) { typedef typename vnl_numeric_traits::real_t real_t; - real_t scale = real_t(1)/std::sqrt((real_t)norm); + const real_t scale = real_t(1) / std::sqrt((real_t)norm); for (unsigned int i = 0; i < nrows; i++) { // FIXME need correct rounding here // There is e.g. no *standard* operator*=(complex, double), hence the T() cast. - (*this)(i,j) *= (T)(scale); + (*this)(i, j) *= (T)(scale); } } } return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::scale_row(unsigned row_index, T value) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::scale_row(unsigned row_index, T value) const { #ifndef NDEBUG if (row_index >= nrows) vnl_error_matrix_row_index("scale_row", row_index); #endif for (unsigned int j = 0; j < ncols; j++) - (*this)(row_index,j) *= value; + (*this)(row_index, j) *= value; return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::scale_column(unsigned column_index, T value) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::scale_column(unsigned column_index, T value) const { #ifndef NDEBUG if (column_index >= ncols) vnl_error_matrix_col_index("scale_column", column_index); #endif for (unsigned int j = 0; j < nrows; j++) - (*this)(j,column_index) *= value; + (*this)(j, column_index) *= value; return *this; } //: Returns a copy of n rows, starting from "row" -template +template vnl_matrix -vnl_matrix_fixed_ref_const::get_n_rows (unsigned row, unsigned n) const +vnl_matrix_fixed_ref_const::get_n_rows(unsigned row, unsigned n) const { #ifndef NDEBUG if (row + n > nrows) - vnl_error_matrix_row_index ("get_n_rows", row); + vnl_error_matrix_row_index("get_n_rows", row); #endif // Extract data rowwise. return vnl_matrix((*this)[row], n, ncols); } -template +template vnl_matrix -vnl_matrix_fixed_ref_const::get_n_columns (unsigned column, unsigned n) const +vnl_matrix_fixed_ref_const::get_n_columns(unsigned column, unsigned n) const { #ifndef NDEBUG if (column + n > ncols) - vnl_error_matrix_col_index ("get_n_columns", column); + vnl_error_matrix_col_index("get_n_columns", column); #endif vnl_matrix result(nrows, n); for (unsigned int c = 0; c < n; ++c) for (unsigned int r = 0; r < nrows; ++r) - result(r, c) = (*this)(r,column + c); + result(r, c) = (*this)(r, column + c); return result; } //: Return a vector with the content of the (main) diagonal -template -vnl_vector vnl_matrix_fixed_ref_const::get_diagonal() const +template +vnl_vector +vnl_matrix_fixed_ref_const::get_diagonal() const { vnl_vector v(nrows < ncols ? nrows : ncols); for (unsigned int j = 0; j < nrows && j < ncols; ++j) - v[j] = (*this)(j,j); + v[j] = (*this)(j, j); return v; } //-------------------------------------------------------------------------------- -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_row(unsigned row_index, T const *v) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_row(unsigned row_index, const T * v) const { for (unsigned int j = 0; j < ncols; j++) - (*this)(row_index,j) = v[j]; + (*this)(row_index, j) = v[j]; return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_row(unsigned row_index, vnl_vector_fixed const &v) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_row(unsigned row_index, const vnl_vector_fixed & v) const { - set_row(row_index,v.data_block()); + set_row(row_index, v.data_block()); return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_row(unsigned row_index, vnl_vector const &v) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_row(unsigned row_index, const vnl_vector & v) const { - set_row(row_index,v.data_block()); + set_row(row_index, v.data_block()); return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_row(unsigned row_index, T v) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_row(unsigned row_index, T v) const { for (unsigned int j = 0; j < ncols; j++) - (*this)(row_index,j) = v; + (*this)(row_index, j) = v; return *this; } //-------------------------------------------------------------------------------- -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_column(unsigned column_index, T const *v) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_column(unsigned column_index, const T * v) const { for (unsigned int i = 0; i < nrows; i++) - (*this)(i,column_index) = v[i]; + (*this)(i, column_index) = v[i]; return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_column(unsigned column_index, vnl_vector_fixed const &v) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_column(unsigned column_index, const vnl_vector_fixed & v) const { - set_column(column_index,v.data_block()); + set_column(column_index, v.data_block()); return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_column(unsigned column_index, vnl_vector const &v) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_column(unsigned column_index, const vnl_vector & v) const { - set_column(column_index,v.data_block()); + set_column(column_index, v.data_block()); return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_column(unsigned column_index, T v) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_column(unsigned column_index, T v) const { for (unsigned int j = 0; j < nrows; j++) - (*this)(j,column_index) = v; + (*this)(j, column_index) = v; return *this; } -template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::set_columns(unsigned starting_column, vnl_matrix const& m) const +template +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::set_columns(unsigned starting_column, const vnl_matrix & m) const { #ifndef NDEBUG - if (nrows != m.rows() || - ncols < m.cols() + starting_column) // Size match? - vnl_error_matrix_dimension ("set_columns", - nrows, ncols, - m.rows(), m.cols()); + if (nrows != m.rows() || ncols < m.cols() + starting_column) // Size match? + vnl_error_matrix_dimension("set_columns", nrows, ncols, m.rows(), m.cols()); #endif for (unsigned int j = 0; j < m.cols(); ++j) for (unsigned int i = 0; i < nrows; i++) - (*this)(i,starting_column + j) = m(i,j); + (*this)(i, starting_column + j) = m(i, j); return *this; } template bool -vnl_matrix_fixed_ref_const::is_identity() const +vnl_matrix_fixed_ref_const::is_identity() const { - T const zero(0); - T const one(1); + const T zero(0); + const T one(1); for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) { - T xm = (*this)(i,j); - if ( !((i == j) ? (xm == one) : (xm == zero)) ) + T xm = (*this)(i, j); + if (!((i == j) ? (xm == one) : (xm == zero))) return false; } return true; @@ -414,14 +410,14 @@ vnl_matrix_fixed_ref_const::is_identity() const //: Return true if maximum absolute deviation of M from identity is <= tol. template bool -vnl_matrix_fixed_ref_const::is_identity(double tol) const +vnl_matrix_fixed_ref_const::is_identity(double tol) const { T one(1); for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) { - T xm = (*this)(i,j); - abs_t absdev = (i == j) ? vnl_math::abs(xm - one) : vnl_math::abs(xm); + T xm = (*this)(i, j); + const abs_t absdev = (i == j) ? vnl_math::abs(xm - one) : vnl_math::abs(xm); if (absdev > tol) return false; } @@ -430,12 +426,12 @@ vnl_matrix_fixed_ref_const::is_identity(double tol) const template bool -vnl_matrix_fixed_ref_const::is_zero() const +vnl_matrix_fixed_ref_const::is_zero() const { - T const zero(0); + const T zero(0); for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) - if ( !( (*this)(i, j) == zero) ) + if (!((*this)(i, j) == zero)) return false; return true; @@ -443,11 +439,11 @@ vnl_matrix_fixed_ref_const::is_zero() const template bool -vnl_matrix_fixed_ref_const::is_zero(double tol) const +vnl_matrix_fixed_ref_const::is_zero(double tol) const { for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) - if (vnl_math::abs((*this)(i,j)) > tol) + if (vnl_math::abs((*this)(i, j)) > tol) return false; return true; @@ -455,11 +451,11 @@ vnl_matrix_fixed_ref_const::is_zero(double tol) const template bool -vnl_matrix_fixed_ref_const::has_nans() const +vnl_matrix_fixed_ref_const::has_nans() const { for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) - if (vnl_math::isnan((*this)(i,j))) + if (vnl_math::isnan((*this)(i, j))) return true; return false; @@ -467,11 +463,11 @@ vnl_matrix_fixed_ref_const::has_nans() const template bool -vnl_matrix_fixed_ref_const::is_finite() const +vnl_matrix_fixed_ref_const::is_finite() const { for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) - if (!vnl_math::isfinite((*this)(i,j))) + if (!vnl_math::isfinite((*this)(i, j))) return false; return true; @@ -480,7 +476,7 @@ vnl_matrix_fixed_ref_const::is_finite() const //: Abort if any element of M is inf or nan template void -vnl_matrix_fixed_ref_const::assert_finite_internal() const +vnl_matrix_fixed_ref_const::assert_finite_internal() const { if (is_finite()) return; @@ -492,11 +488,11 @@ vnl_matrix_fixed_ref_const::assert_finite_internal() const else { std::cerr << __FILE__ ": it is quite big (" << rows() << 'x' << cols() << ")\n" - << __FILE__ ": in the following picture '-' means finite and '*' means non-finite:\n"; + << __FILE__ ": in the following picture '-' means finite and '*' means non-finite:\n"; - for (unsigned int i=0; i::assert_finite_internal() const //: Abort unless M has the given size. template void -vnl_matrix_fixed_ref_const::assert_size_internal(unsigned rs,unsigned cs) const +vnl_matrix_fixed_ref_const::assert_size_internal(unsigned rs, unsigned cs) const { - if (nrows!=rs || ncols!=cs) + if (nrows != rs || ncols != cs) { - std::cerr << __FILE__ ": size is " << nrows << 'x' << ncols - << ". should be " << rs << 'x' << cs << std::endl; + std::cerr << __FILE__ ": size is " << nrows << 'x' << ncols << ". should be " << rs << 'x' << cs << std::endl; std::abort(); } } template bool -vnl_matrix_fixed_ref::read_ascii(std::istream& s) const +vnl_matrix_fixed_ref::read_ascii(std::istream & s) const { if (!s.good()) { @@ -530,17 +525,17 @@ vnl_matrix_fixed_ref::read_ascii(std::istream& s) const for (unsigned int i = 0; i < nrows; ++i) for (unsigned int j = 0; j < ncols; ++j) - s >> (*this)(i,j); + s >> (*this)(i, j); return s.good() || s.eof(); } template -vnl_matrix_fixed_ref & -vnl_matrix_fixed_ref::flipud() +vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::flipud() { - for (unsigned int r1 = 0; 2*r1+1 < nrows; ++r1) + for (unsigned int r1 = 0; 2 * r1 + 1 < nrows; ++r1) { const unsigned int r2 = nrows - 1 - r1; for (unsigned int c = 0; c < ncols; ++c) @@ -555,10 +550,10 @@ vnl_matrix_fixed_ref::flipud() template -vnl_matrix_fixed_ref & -vnl_matrix_fixed_ref::fliplr() +vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::fliplr() { - for (unsigned int c1 = 0; 2*c1+1 < ncols; ++c1) + for (unsigned int c1 = 0; 2 * c1 + 1 < ncols; ++c1) { const unsigned int c2 = ncols - 1 - c1; for (unsigned int r = 0; r < nrows; ++r) @@ -572,15 +567,15 @@ vnl_matrix_fixed_ref::fliplr() } template -typename vnl_matrix_fixed_ref_const::abs_t -vnl_matrix_fixed_ref_const::operator_one_norm() const +typename vnl_matrix_fixed_ref_const::abs_t +vnl_matrix_fixed_ref_const::operator_one_norm() const { abs_t m(0); - for (unsigned int j=0; j m) m = t; } @@ -588,15 +583,15 @@ vnl_matrix_fixed_ref_const::operator_one_norm() const } template -typename vnl_matrix_fixed_ref_const::abs_t -vnl_matrix_fixed_ref_const::operator_inf_norm() const +typename vnl_matrix_fixed_ref_const::abs_t +vnl_matrix_fixed_ref_const::operator_inf_norm() const { abs_t m(0); - for (unsigned int i=0; i m) m = t; } @@ -605,23 +600,23 @@ vnl_matrix_fixed_ref_const::operator_inf_norm() const //: Transpose square matrix M in place. template -vnl_matrix_fixed_ref const& -vnl_matrix_fixed_ref::inplace_transpose() const +const vnl_matrix_fixed_ref & +vnl_matrix_fixed_ref::inplace_transpose() const { - assert(nrows==ncols); // cannot inplace_transpose non-square fixed size matrix + assert(nrows == ncols); // cannot inplace_transpose non-square fixed size matrix for (unsigned i = 0; i < nrows; ++i) - for (unsigned j = i+1; j < ncols; ++j) - { - T t = (*this)(i,j); - (*this)(i,j) = (*this)(j,i); - (*this)(j,i) = t; - } + for (unsigned j = i + 1; j < ncols; ++j) + { + T t = (*this)(i, j); + (*this)(i, j) = (*this)(j, i); + (*this)(j, i) = t; + } return *this; } -#define VNL_MATRIX_FIXED_REF_INSTANTIATE(T,m,n) \ -template class VNL_EXPORT vnl_matrix_fixed_ref_const; \ -template class VNL_EXPORT vnl_matrix_fixed_ref +#define VNL_MATRIX_FIXED_REF_INSTANTIATE(T, m, n) \ + template class VNL_EXPORT vnl_matrix_fixed_ref_const; \ + template class VNL_EXPORT vnl_matrix_fixed_ref #endif // vnl_matrix_fixed_ref_hxx_ diff --git a/core/vnl/vnl_matrix_ref.h b/core/vnl/vnl_matrix_ref.h index f94c893668f..091fb5f3652 100644 --- a/core/vnl/vnl_matrix_ref.h +++ b/core/vnl/vnl_matrix_ref.h @@ -37,17 +37,15 @@ class VNL_EXPORT vnl_matrix_ref : public vnl_matrix { typedef vnl_matrix Base; - public: - +public: // Constructors/Destructors-------------------------------------------------- - vnl_matrix_ref(unsigned int row, unsigned int col, const T *datablck) + vnl_matrix_ref(unsigned int row, unsigned int col, const T * datablck) : vnl_matrix(row, col, const_cast(datablck), false) - { } + {} vnl_matrix_ref(const vnl_matrix_ref & other) - : vnl_matrix(other.rows(), other.cols(), - const_cast(other.data_block()), false) - { } + : vnl_matrix(other.rows(), other.cols(), const_cast(other.data_block()), false) + {} ~vnl_matrix_ref() override = default; @@ -55,8 +53,10 @@ class VNL_EXPORT vnl_matrix_ref : public vnl_matrix // due to other constructor definitions. //: assignment and move-assignment is disallowed // because it does not define external memory to be managed. - vnl_matrix_ref & operator=( vnl_matrix_ref const& ) = delete; - vnl_matrix_ref & operator=( vnl_matrix_ref && ) = delete; + vnl_matrix_ref & + operator=(const vnl_matrix_ref &) = delete; + vnl_matrix_ref & + operator=(vnl_matrix_ref &&) = delete; //: Reference to self to make non-const temporaries. // This is intended for passing vnl_matrix_fixed objects to @@ -72,16 +72,31 @@ class VNL_EXPORT vnl_matrix_ref : public vnl_matrix // \attention Use this only to pass the reference to a // function. Otherwise, the underlying object will be destructed and // you'll be left with undefined behaviour. - vnl_matrix_ref& non_const() { return *this; } + vnl_matrix_ref & + non_const() + { + return *this; + } - private: +private: //: Resizing is disallowed - bool resize (unsigned int, unsigned int) { return false; } + bool + resize(unsigned int, unsigned int) + { + return false; + } //: Resizing is disallowed - bool make_size (unsigned int, unsigned int) { return false; } + bool + make_size(unsigned int, unsigned int) + { + return false; + } //: Resizing is disallowed - bool set_size (unsigned int, unsigned int) { return false; } - + bool + set_size(unsigned int, unsigned int) + { + return false; + } }; #endif // vnl_matrix_ref_h_ diff --git a/core/vnl/vnl_na.h b/core/vnl/vnl_na.h index e21909b5c47..fe37fc60cda 100644 --- a/core/vnl/vnl_na.h +++ b/core/vnl/vnl_na.h @@ -42,97 +42,120 @@ //: qNaN to indicate value Not Available. // Don't assume that any VXL functions will do something sensible in the face of NA, unless // explicitly documented. -VNL_EXPORT double vnl_na(double dummy); +VNL_EXPORT double +vnl_na(double dummy); //: qNaN to indicate value Not Available. // Don't assume that any VXL functions will do something sensible in the face of NA, unless // explicitly documented. -VNL_EXPORT float vnl_na(float dummy); +VNL_EXPORT float +vnl_na(float dummy); //: True if parameter is specific NA qNaN. // Tests for bit pattern 0x7ff00000000007a2, as used by Octave and R -VNL_EXPORT bool vnl_na_isna(double); +VNL_EXPORT bool +vnl_na_isna(double); //: True if parameter is specific NA qNaN. // Tests for bit pattern 0x7f8007a2 -VNL_EXPORT bool vnl_na_isna(float); +VNL_EXPORT bool +vnl_na_isna(float); //: Replace NaNs with NA, leave other values alone. -VNL_EXPORT double vnl_na_nan_to_na(double v); +VNL_EXPORT double +vnl_na_nan_to_na(double v); //: Replace NaNs with NA, leave other values alone. -VNL_EXPORT float vnl_na_nan_to_na(float v); +VNL_EXPORT float +vnl_na_nan_to_na(float v); //: Read a floating point number or "NA" from a stream. // Should behave exactly like a>>x, if the extraction operator was aware of the // character sequence \code NA. -VNL_EXPORT void vnl_na_extract(std::istream &is, double& x); +VNL_EXPORT void +vnl_na_extract(std::istream & is, double & x); //: Write a floating point number or "NA" to a stream. // Should behave exactly like a<>x, if the extraction operator was aware of the // character sequence \code NA. -VNL_EXPORT void vnl_na_extract(std::istream &is, float& x); +VNL_EXPORT void +vnl_na_extract(std::istream & is, float & x); //: Write a floating point number or "NA" to a stream. // Should behave exactly like a< struct vnl_na_stream_t { - T& x_; - vnl_na_stream_t(T& x): x_(x) {} + T & x_; + vnl_na_stream_t(T & x) + : x_(x) + {} }; //: Wrapper around a double or float that handles streaming NA. template struct vnl_na_stream_const_t { - const T& x_; - vnl_na_stream_const_t(const T& x): x_(x) {} + const T & x_; + vnl_na_stream_const_t(const T & x) + : x_(x) + {} }; //: Wrap a double or float to handle streaming NA. template -inline vnl_na_stream_t vnl_na_stream(T& x) +inline vnl_na_stream_t +vnl_na_stream(T & x) { return vnl_na_stream_t(x); } //: Wrap a double or float to handle streaming NA. -template inline vnl_na_stream_const_t vnl_na_stream(const T& x) +template +inline vnl_na_stream_const_t +vnl_na_stream(const T & x) { return vnl_na_stream_const_t(x); } //: Insert wrapped double or float into stream, whilst handling NA. -template inline std::ostream& operator <<(std::ostream &os, const vnl_na_stream_t& ns) +template +inline std::ostream & +operator<<(std::ostream & os, const vnl_na_stream_t & ns) { vnl_na_insert(os, ns.x_); return os; } //: Insert wrapped double or float into stream, whilst handling NA. -template inline std::ostream& operator <<(std::ostream &os, const vnl_na_stream_const_t& ns) +template +inline std::ostream & +operator<<(std::ostream & os, const vnl_na_stream_const_t & ns) { vnl_na_insert(os, ns.x_); return os; } //: Extract wrapped double or float from stream, whilst handling NA. -template inline std::istream& operator >>(std::istream &is, const vnl_na_stream_t& ns) +template +inline std::istream & +operator>>(std::istream & is, const vnl_na_stream_t & ns) { vnl_na_extract(is, ns.x_); return is; diff --git a/core/vnl/vnl_nonlinear_minimizer.cxx b/core/vnl/vnl_nonlinear_minimizer.cxx index 4f5b7b10d3d..486c3835503 100644 --- a/core/vnl/vnl_nonlinear_minimizer.cxx +++ b/core/vnl/vnl_nonlinear_minimizer.cxx @@ -9,18 +9,17 @@ //: Default ctor sets verbosity etc. vnl_nonlinear_minimizer::vnl_nonlinear_minimizer() - : ftol(xtol * 0.01) // Termination tolerance on F (sum of squared residuals) - , - epsfcn(xtol * 0.001) // Step length for FD Jacobian + : ftol(xtol * 0.01) // Termination tolerance on F (sum of squared residuals) + , epsfcn(xtol * 0.001) // Step length for FD Jacobian {} vnl_nonlinear_minimizer::~vnl_nonlinear_minimizer() = default; -vnl_matrix const & +const vnl_matrix & vnl_nonlinear_minimizer::get_covariance() { - static vnl_matrix null; + static const vnl_matrix null; return null; } @@ -71,7 +70,7 @@ vnl_nonlinear_minimizer::is_a() const //: Return true if the name of the class matches the argument // Used by polymorphic IO bool -vnl_nonlinear_minimizer::is_class(std::string const & s) const +vnl_nonlinear_minimizer::is_class(const std::string & s) const { return s == vnl_nonlinear_minimizer::is_a(); } diff --git a/core/vnl/vnl_nonlinear_minimizer.h b/core/vnl/vnl_nonlinear_minimizer.h index 5bb8f9b1609..4f0dabf7b01 100644 --- a/core/vnl/vnl_nonlinear_minimizer.h +++ b/core/vnl/vnl_nonlinear_minimizer.h @@ -30,7 +30,7 @@ // - vnl_powell class VNL_EXPORT vnl_nonlinear_minimizer { - public: +public: vnl_nonlinear_minimizer(); virtual ~vnl_nonlinear_minimizer(); @@ -42,128 +42,221 @@ class VNL_EXPORT vnl_nonlinear_minimizer // minimization. Setting it too low wastes time, too high might cause early // convergence. The default of 1e-9 is on the safe side, but if speed is an // issue, you can try raising it. - void set_f_tolerance(double v) { ftol = v; } - double get_f_tolerance() const { return ftol; } + void + set_f_tolerance(double v) + { + ftol = v; + } + double + get_f_tolerance() const + { + return ftol; + } //: Set the convergence tolerance on X. // When the length of the steps taken in X are about this long, the routine // terminates. The default is 1e-8, which should work for many problems, // but if you can get away with 1e-4, say, minimizations will be much quicker. - void set_x_tolerance(double v) { + void + set_x_tolerance(double v) + { xtol = v; epsfcn = xtol * 0.001; } - double get_x_tolerance() const { return xtol; } + double + get_x_tolerance() const + { + return xtol; + } //: Set the convergence tolerance on Grad(F)' * F. - void set_g_tolerance(double v) { gtol = v; } - double get_g_tolerance() const { return gtol; } + void + set_g_tolerance(double v) + { + gtol = v; + } + double + get_g_tolerance() const + { + return gtol; + } //: Set the termination maximum number of iterations. - void set_max_function_evals(int v) { maxfev = v; } - int get_max_function_evals() const { return maxfev; } + void + set_max_function_evals(int v) + { + maxfev = v; + } + int + get_max_function_evals() const + { + return maxfev; + } //: Set the step length for FD Jacobian. // Be aware that set_x_tolerance will reset this to xtol * 0.001. // The default is 1e-11. - void set_epsilon_function(double v) { epsfcn = v; } - double get_epsilon_function() const { return epsfcn; } + void + set_epsilon_function(double v) + { + epsfcn = v; + } + double + get_epsilon_function() const + { + return epsfcn; + } //: Turn on per-iteration printouts. - void set_trace(bool on) { trace = on; } - bool get_trace() const { return trace; } + void + set_trace(bool on) + { + trace = on; + } + bool + get_trace() const + { + return trace; + } //: Set verbose flag - void set_verbose(bool verb) { verbose_ = verb; } - bool get_verbose() const { return verbose_; } + void + set_verbose(bool verb) + { + verbose_ = verb; + } + bool + get_verbose() const + { + return verbose_; + } //: Set check_derivatives flag. Negative values may mean fewer checks. - void set_check_derivatives(int cd) { check_derivatives_ = cd; } - int get_check_derivatives() const { return check_derivatives_; } + void + set_check_derivatives(int cd) + { + check_derivatives_ = cd; + } + int + get_check_derivatives() const + { + return check_derivatives_; + } //: Return the error of the function when it was evaluated at the start point of the last minimization. // For minimizers driven by a vnl_least_squares_function (Levenberg-Marquardt) // this is usually the RMS error. // For those driven by a vnl_cost_function (CG, LBFGS, Amoeba) it is simply the // value of the vnl_cost_function at the start (usually the sum of squared residuals). - double get_start_error() const { return start_error_; } + double + get_start_error() const + { + return start_error_; + } - //:Return the best error that was achieved by the last minimization, corresponding to the returned x. - double get_end_error() const { return end_error_; } + //: Return the best error that was achieved by the last minimization, corresponding to the returned x. + double + get_end_error() const + { + return end_error_; + } - //:Return the total number of times the function was evaluated by the last minimization. - int get_num_evaluations() const { return num_evaluations_; } + //: Return the total number of times the function was evaluated by the last minimization. + int + get_num_evaluations() const + { + return num_evaluations_; + } - //:Return the number of {\em iterations} in the last minimization. + //: Return the number of {\em iterations} in the last minimization. // Each iteration may have comprised several function evaluations. - int get_num_iterations() const { return num_iterations_; } - - //:Some generic return codes that apply to all minimizers. - enum ReturnCodes { - ERROR_FAILURE =-1, - ERROR_DODGY_INPUT = 0, - CONVERGED_FTOL = 1, - CONVERGED_XTOL = 2, - CONVERGED_XFTOL = 3, - CONVERGED_GTOL = 4, - FAILED_TOO_MANY_ITERATIONS = 5, - TOO_MANY_ITERATIONS = FAILED_TOO_MANY_ITERATIONS, // for backward-compatibility - FAILED_FTOL_TOO_SMALL = 6, - FAILED_XTOL_TOO_SMALL = 7, - FAILED_GTOL_TOO_SMALL = 8, - FAILED_USER_REQUEST = 9, + int + get_num_iterations() const + { + return num_iterations_; + } + + //: Some generic return codes that apply to all minimizers. + enum ReturnCodes + { + ERROR_FAILURE = -1, + ERROR_DODGY_INPUT = 0, + CONVERGED_FTOL = 1, + CONVERGED_XTOL = 2, + CONVERGED_XFTOL = 3, + CONVERGED_GTOL = 4, + FAILED_TOO_MANY_ITERATIONS = 5, + TOO_MANY_ITERATIONS = FAILED_TOO_MANY_ITERATIONS, // for backward-compatibility + FAILED_FTOL_TOO_SMALL = 6, + FAILED_XTOL_TOO_SMALL = 7, + FAILED_GTOL_TOO_SMALL = 8, + FAILED_USER_REQUEST = 9, ABNORMAL_TERMINATION_IN_LNSRCH = 10 }; - //:Whether the error reduced in the last minimization - bool obj_value_reduced() { return failure_code_ != ERROR_FAILURE && failure_code_ != ERROR_DODGY_INPUT && end_error_ < start_error_; } + //: Whether the error reduced in the last minimization + bool + obj_value_reduced() + { + return failure_code_ != ERROR_FAILURE && failure_code_ != ERROR_DODGY_INPUT && end_error_ < start_error_; + } - //:Return the covariance of the estimate at the end. - virtual vnl_matrix const& get_covariance(); + //: Return the covariance of the estimate at the end. + virtual const vnl_matrix & + get_covariance(); //: Return the name of the class. // Used by polymorphic IO - virtual std::string is_a() const; + virtual std::string + is_a() const; //: Return true if the name of the class matches the argument. // Used by polymorphic IO - virtual bool is_class(std::string const& s) const; + virtual bool + is_class(const std::string & s) const; - //:Return the failure code of the last minimization - ReturnCodes get_failure_code() const { return failure_code_; } + //: Return the failure code of the last minimization + ReturnCodes + get_failure_code() const + { + return failure_code_; + } - protected: +protected: // Data Members-------------------------------------------------------------- // Input variables - double xtol{1e-8}; //!< Termination tolerance on X (solution vector) - long maxfev{2000}; //!< Termination maximum number of iterations - double ftol; //!< Termination tolerance on F (sum of squared residuals) - double gtol{1e-5}; //!< Termination tolerance on Grad(F)' * F = 0 - double epsfcn; //!< Step length for FD Jacobian - - // Output variables - unsigned num_iterations_{0}; - long num_evaluations_{0}; - double start_error_{0}; - double end_error_{0}; - - bool trace{false}; - - // Verbose flag. - bool verbose_{false}; - int check_derivatives_{0}; - ReturnCodes failure_code_{ERROR_FAILURE}; - - void reset(); - - //: Called by derived classes after each function evaluation. - void report_eval(double f); - - //: Called by derived classes after each iteration. - // When true is returned, minimizer should stop with code - // FAILED_USER_REQUEST. Derived classes can redefine this function to make - // the optimizer stop when a condition is satisfied. - virtual bool report_iter(); + double xtol{ 1e-8 }; //!< Termination tolerance on X (solution vector) + long maxfev{ 2000 }; //!< Termination maximum number of iterations + double ftol; //!< Termination tolerance on F (sum of squared residuals) + double gtol{ 1e-5 }; //!< Termination tolerance on Grad(F)' * F = 0 + double epsfcn; //!< Step length for FD Jacobian + + // Output variables + unsigned num_iterations_{ 0 }; + long num_evaluations_{ 0 }; + double start_error_{ 0 }; + double end_error_{ 0 }; + + bool trace{ false }; + + // Verbose flag. + bool verbose_{ false }; + int check_derivatives_{ 0 }; + ReturnCodes failure_code_{ ERROR_FAILURE }; + + void + reset(); + + //: Called by derived classes after each function evaluation. + void + report_eval(double f); + + //: Called by derived classes after each iteration. + // When true is returned, minimizer should stop with code + // FAILED_USER_REQUEST. Derived classes can redefine this function to make + // the optimizer stop when a condition is satisfied. + virtual bool + report_iter(); }; #endif // vnl_nonlinear_minimizer_h_ diff --git a/core/vnl/vnl_numeric_traits.h b/core/vnl/vnl_numeric_traits.h index 26491b2b1a9..182157cab5b 100644 --- a/core/vnl/vnl_numeric_traits.h +++ b/core/vnl/vnl_numeric_traits.h @@ -33,7 +33,7 @@ // this is an empty class template. // only the specializations make sense. -#if !defined(_MSC_VER) || (_MSC_VER >= 1800 ) +#if !defined(_MSC_VER) || (_MSC_VER >= 1800) template class VNL_EXPORT vnl_numeric_traits; #else @@ -42,11 +42,11 @@ class VNL_EXPORT vnl_numeric_traits; // Since the non-specialized template doesn't make any sense, make // sure that any types "accidently" derived from it will cause // compiler errors. -class VNL_EXPORT vnl_numeric_traits_not_a_valid_type { }; +class VNL_EXPORT vnl_numeric_traits_not_a_valid_type{}; template class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static constexpr vnl_numeric_traits_not_a_valid_type zero; @@ -74,7 +74,7 @@ class VNL_EXPORT vnl_numeric_traits template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static constexpr bool zero = false; //: Multiplicative identity @@ -94,13 +94,14 @@ class VNL_EXPORT vnl_numeric_traits }; template <> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; #endif -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static constexpr char zero = 0; //: Multiplicative identity @@ -108,13 +109,13 @@ class VNL_EXPORT vnl_numeric_traits //: Maximum value which this type can assume. // It is 127 (and not 255) since "char" is not guaranteed to be unsigned. #ifdef _MSC_VER -#ifdef _CHAR_UNSIGNED +# ifdef _CHAR_UNSIGNED static constexpr char maxval = 255; -#else +# else static constexpr char maxval = 127; -#endif +# endif #else - static constexpr char maxval = (char(255) using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static constexpr unsigned char zero = 0; //: Multiplicative identity @@ -153,13 +155,14 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static constexpr signed char zero = 0; //: Multiplicative identity @@ -178,15 +181,16 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity - static constexpr short zero = 0; + static constexpr short zero = 0; //: Multiplicative identity static constexpr short one = 1; //: Maximum value which this type can assume @@ -203,15 +207,16 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity - static constexpr unsigned short zero = 0; + static constexpr unsigned short zero = 0; //: Multiplicative identity static constexpr unsigned short one = 1; //: Maximum value which this type can assume @@ -228,15 +233,16 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity - static constexpr int zero = 0; + static constexpr int zero = 0; //: Multiplicative identity static constexpr int one = 1; //: Maximum value which this type can assume @@ -253,15 +259,16 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity - static constexpr unsigned int zero = 0; + static constexpr unsigned int zero = 0; //: Multiplicative identity static constexpr unsigned int one = 1; //: Maximum value which this type can assume @@ -278,19 +285,21 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity - static constexpr long zero = 0; + static constexpr long zero = 0; //: Multiplicative identity static constexpr long one = 1; //: Maximum value which this type can assume - static constexpr long maxval = sizeof(long)==8?static_cast((vxl_uint_64)(-1)/2):0x7fffffffL; // = 0x7fffffffL or 0x7fffffffffffffffL; + static constexpr long maxval = + sizeof(long) == 8 ? static_cast((vxl_uint_64)(-1) / 2) : 0x7fffffffL; // = 0x7fffffffL or 0x7fffffffffffffffL; //: Return value of abs() typedef unsigned long abs_t; //: Name of a type twice as long as this one for accumulators and products. @@ -303,19 +312,21 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity - static constexpr unsigned long zero = 0; + static constexpr unsigned long zero = 0; //: Multiplicative identity static constexpr unsigned long one = 1; //: Maximum value which this type can assume - static constexpr unsigned long maxval = sizeof(unsigned long)==8?static_cast((vxl_uint_64)(-1)):0xffffffffL ; + static constexpr unsigned long maxval = + sizeof(unsigned long) == 8 ? static_cast((vxl_uint_64)(-1)) : 0xffffffffL; // = 0xffffffffL or 0xffffffffffffffffL; //: Return value of abs() typedef unsigned long abs_t; @@ -329,21 +340,22 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -//long long - target type will have width of at least 64 bits. (since C++11) -template<> +// long long - target type will have width of at least 64 bits. (since C++11) +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity - static constexpr long long zero = 0; + static constexpr long long zero = 0; //: Multiplicative identity static constexpr long long one = 1; //: Maximum value which this type can assume - static constexpr long long maxval = sizeof(long long)==8?((vxl_uint_64)(-1))/2:0x7fffffffL ; + static constexpr long long maxval = sizeof(long long) == 8 ? ((vxl_uint_64)(-1)) / 2 : 0x7fffffffL; //: Return value of abs() typedef unsigned long long abs_t; //: Name of a type twice as long as this one for accumulators and products. @@ -356,19 +368,20 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity - static constexpr unsigned long long zero = 0; + static constexpr unsigned long long zero = 0; //: Multiplicative identity static constexpr unsigned long long one = 1; //: Maximum value which this type can assume - static constexpr unsigned long long maxval = sizeof(unsigned long long)==8?(vxl_uint_64)(-1):0xffffffffL; + static constexpr unsigned long long maxval = sizeof(unsigned long long) == 8 ? (vxl_uint_64)(-1) : 0xffffffffL; //: Return value of abs() typedef unsigned long long abs_t; //: Name of a type twice as long as this one for accumulators and products. @@ -381,14 +394,15 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = std::make_signed::type; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static constexpr float zero = 0.0F; //: Multiplicative identity @@ -407,13 +421,14 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = self; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static constexpr double zero = 0.0; //: Multiplicative identity @@ -432,13 +447,14 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = self; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> +template <> class VNL_EXPORT vnl_numeric_traits { - public: +public: //: Additive identity static constexpr long double zero = 0.0; //: Multiplicative identity @@ -457,19 +473,20 @@ class VNL_EXPORT vnl_numeric_traits using signed_t = self; }; -template<> -class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits {}; +template <> +class VNL_EXPORT vnl_numeric_traits : public vnl_numeric_traits +{}; -template<> -class VNL_EXPORT vnl_numeric_traits< std::complex > +template <> +class VNL_EXPORT vnl_numeric_traits> { - public: +public: //: Additive identity static const std::complex zero; //: Multiplicative identity static const std::complex one; // Maximum value which this type can assume; makes no sense for this type - //static const std::complex maxval; + // static const std::complex maxval; //: Return value of abs() typedef float abs_t; @@ -483,19 +500,20 @@ class VNL_EXPORT vnl_numeric_traits< std::complex > using signed_t = self; }; -template<> -class VNL_EXPORT vnl_numeric_traits const> : public vnl_numeric_traits > {}; +template <> +class VNL_EXPORT vnl_numeric_traits> : public vnl_numeric_traits> +{}; -template<> -class VNL_EXPORT vnl_numeric_traits< std::complex > +template <> +class VNL_EXPORT vnl_numeric_traits> { - public: +public: //: Additive identity static const std::complex zero; //: Multiplicative identity static const std::complex one; // Maximum value which this type can assume; makes no sense for this type - //static const std::complex maxval; + // static const std::complex maxval; //: Return value of abs() typedef double abs_t; @@ -509,19 +527,20 @@ class VNL_EXPORT vnl_numeric_traits< std::complex > using signed_t = self; }; -template<> -class VNL_EXPORT vnl_numeric_traits const> : public vnl_numeric_traits > {}; +template <> +class VNL_EXPORT vnl_numeric_traits> : public vnl_numeric_traits> +{}; -template<> -class VNL_EXPORT vnl_numeric_traits< std::complex > +template <> +class VNL_EXPORT vnl_numeric_traits> { - public: +public: //: Additive identity static const std::complex zero; //: Multiplicative identity static const std::complex one; // Maximum value which this type can assume; makes no sense for this type - //static const std::complex maxval; + // static const std::complex maxval; //: Return value of abs() typedef long double abs_t; @@ -535,7 +554,9 @@ class VNL_EXPORT vnl_numeric_traits< std::complex > using signed_t = self; }; -template<> -class VNL_EXPORT vnl_numeric_traits const> : public vnl_numeric_traits > {}; +template <> +class VNL_EXPORT vnl_numeric_traits> + : public vnl_numeric_traits> +{}; #endif // vnl_numeric_traits_h_ diff --git a/core/vnl/vnl_operators.h b/core/vnl/vnl_operators.h index 4a2062fc590..0e2478982df 100644 --- a/core/vnl/vnl_operators.h +++ b/core/vnl/vnl_operators.h @@ -20,20 +20,26 @@ // // \relatesalso vnl_vector -template VNL_EXPORT -bool operator<(vnl_vector const& lhs, vnl_vector const& rhs) +template +VNL_EXPORT bool +operator<(const vnl_vector & lhs, const vnl_vector & rhs) { - if (&lhs == &rhs) return false; // same object => equal. + if (&lhs == &rhs) + return false; // same object => equal. - if (lhs.size() < rhs.size()) return true; // Size different ? - else if (lhs.size() > rhs.size()) return false; + if (lhs.size() < rhs.size()) + return true; // Size different ? + else if (lhs.size() > rhs.size()) + return false; - for (unsigned i = 0; i < lhs.size(); i++) // For each index + for (unsigned i = 0; i < lhs.size(); i++) // For each index { - if (lhs(i) < rhs(i)) return true; // Element different ? - else if (lhs(i) > rhs(i)) return false; + if (lhs(i) < rhs(i)) + return true; // Element different ? + else if (lhs(i) > rhs(i)) + return false; } - return false; // Else all same. + return false; // Else all same. } //: Define a complete ordering on vnl_matrix @@ -44,22 +50,30 @@ bool operator<(vnl_vector const& lhs, vnl_vector const& rhs) // // \relatesalso vnl_matrix -template VNL_EXPORT -bool operator<(vnl_matrix const& lhs, vnl_matrix const& rhs) +template +VNL_EXPORT bool +operator<(const vnl_matrix & lhs, const vnl_matrix & rhs) { - if (&lhs == &rhs) return false; // same object => equal. + if (&lhs == &rhs) + return false; // same object => equal. - if (lhs.rows() < rhs.rows()) return true; // Size different ? - else if (lhs.rows() > rhs.rows()) return false; - else if (lhs.cols() < rhs.cols()) return true; - else if (lhs.cols() > rhs.cols()) return false; + if (lhs.rows() < rhs.rows()) + return true; // Size different ? + else if (lhs.rows() > rhs.rows()) + return false; + else if (lhs.cols() < rhs.cols()) + return true; + else if (lhs.cols() > rhs.cols()) + return false; - for (unsigned i = 0; i < lhs.size(); i++) // For each index + for (unsigned i = 0; i < lhs.size(); i++) // For each index { - if (lhs.data_block()[i] < rhs.data_block()[i]) return true; // Element different ? - else if (lhs.data_block()[i] > rhs.data_block()[i]) return false; + if (lhs.data_block()[i] < rhs.data_block()[i]) + return true; // Element different ? + else if (lhs.data_block()[i] > rhs.data_block()[i]) + return false; } - return false; // Else all same. + return false; // Else all same. } //: Define a complete ordering on vnl_vector_fixed @@ -67,8 +81,9 @@ bool operator<(vnl_matrix const& lhs, vnl_matrix const& rhs) // // \relatesalso vnl_vector_fixed -template VNL_EXPORT -bool operator<(vnl_vector_fixed const& lhs, vnl_vector_fixed const& rhs) +template +VNL_EXPORT bool +operator<(const vnl_vector_fixed & lhs, const vnl_vector_fixed & rhs) { return lhs.as_ref() < rhs.as_ref(); } @@ -78,8 +93,9 @@ bool operator<(vnl_vector_fixed const& lhs, vnl_vector_fixed const& rh // // \relatesalso vnl_matrix_fixed -template VNL_EXPORT -bool operator<(vnl_matrix_fixed const& lhs, vnl_matrix_fixed const& rhs) +template +VNL_EXPORT bool +operator<(const vnl_matrix_fixed & lhs, const vnl_matrix_fixed & rhs) { return lhs.as_ref() < rhs.as_ref(); } diff --git a/core/vnl/vnl_polynomial.h b/core/vnl/vnl_polynomial.h index ebe33ddf823..9e0335b62a1 100644 --- a/core/vnl/vnl_polynomial.h +++ b/core/vnl/vnl_polynomial.h @@ -56,88 +56,152 @@ template class VNL_EXPORT vnl_polynomial { - public: +public: //: Initialize the polynomial from its coefficients, lowest order first. // The polynomial is $ a[d] X^d + a[d-1] X^{d-1} + \cdots + a[0] = 0 $. // Note that this constructor expects the constant term coefficient first, // as opposed to the C array constructor! // An assertion makes sure that the input vector is in normalised form, i.e., // that it is either empty or that the highest order coefficient is nonzero. - vnl_polynomial(std::vector a) : coeffs_(std::move(a)) { - assert(coeffs_.begin() == coeffs_.end() || coeffs_.back() != T(0)); - } + vnl_polynomial(std::vector a) + : coeffs_(std::move(a)) + { + assert(coeffs_.begin() == coeffs_.end() || coeffs_.back() != T(0)); + } //: Initialize polynomial from C array, highest order first. // The parameter \p len is the number of coefficients passed in, // which equals the degree plus one. // Note that this constructor expects the highest order coefficients first, // as opposed to the std::vector constructor! - vnl_polynomial(T const* a, unsigned len) { assert(len==0 || *a != T(0)); while (len--) coeffs_.push_back(a[len]); } + vnl_polynomial(const T * a, unsigned len) + { + assert(len == 0 || *a != T(0)); + while (len--) + coeffs_.push_back(a[len]); + } //: Initialize polynomial from single value, thus creating a monomial. // This is effectively an implicit cast from type T to class vnl_polynomial, // useful when adding or multiplying a polynomial with a number. - vnl_polynomial(T const& a): coeffs_(1u, a) { if (a==T(0)) coeffs_.clear(); } + vnl_polynomial(const T & a) + : coeffs_(1u, a) + { + if (a == T(0)) + coeffs_.clear(); + } //: Initialize polynomial of a given degree. // The default constructor initializes to the zero polynomial (which has degree -1). // but even with an explicit argument, the polynomial is the zero polynomial // (with non-compact storage) so it should always be used in conjunction with // operator[] for setting individual coefficients, at least coefficient [d]. - vnl_polynomial(int d=-1): coeffs_(d+1) { assert (d>=-1); } + vnl_polynomial(int d = -1) + : coeffs_(d + 1) + { + assert(d >= -1); + } //: comparison operator - bool operator==(vnl_polynomial const& p) const { return p.coefficients() == coeffs_; } + bool + operator==(const vnl_polynomial & p) const + { + return p.coefficients() == coeffs_; + } //: Returns negative of this polynomial - vnl_polynomial::signed_t> operator-() const; + vnl_polynomial::signed_t> + operator-() const; //: Returns polynomial which is sum of this with polynomial f - vnl_polynomial operator+(vnl_polynomial const& f) const; + vnl_polynomial + operator+(const vnl_polynomial & f) const; //: Returns polynomial which is difference of this with polynomial f - vnl_polynomial operator-(vnl_polynomial const& f) const { return operator+(-f); } + vnl_polynomial + operator-(const vnl_polynomial & f) const + { + return operator+(-f); + } //: Returns polynomial which is product of this with polynomial f - vnl_polynomial operator*(vnl_polynomial const& f) const; + vnl_polynomial + operator*(const vnl_polynomial & f) const; //: Returns polynomial which is the result of the long division by polynomial f // Beware that this operation might not make sense for integral types T // if the highest order coefficient of f is not 1 or -1! - vnl_polynomial operator/(vnl_polynomial const& f) const; + vnl_polynomial + operator/(const vnl_polynomial & f) const; //: Returns polynomial which is the remainder after a long division by polynomial f // Beware that this operation might not make sense for integral types T // if the highest order coefficient of f is not 1 or -1! - vnl_polynomial operator%(vnl_polynomial const& f) const; + vnl_polynomial + operator%(const vnl_polynomial & f) const; - vnl_polynomial& operator+=(vnl_polynomial const& f) { return *this = operator+(f); } - vnl_polynomial& operator-=(vnl_polynomial const& f) { return *this = operator-(f); } - vnl_polynomial& operator*=(vnl_polynomial const& f) { return *this = operator*(f); } - vnl_polynomial& operator/=(vnl_polynomial const& f) { return *this = operator/(f); } - vnl_polynomial& operator%=(vnl_polynomial const& f) { return *this = operator%(f); } + vnl_polynomial & + operator+=(const vnl_polynomial & f) + { + return *this = operator+(f); + } + vnl_polynomial & + operator-=(const vnl_polynomial & f) + { + return *this = operator-(f); + } + vnl_polynomial & + operator*=(const vnl_polynomial & f) + { + return *this = operator*(f); + } + vnl_polynomial & + operator/=(const vnl_polynomial & f) + { + return *this = operator/(f); + } + vnl_polynomial & + operator%=(const vnl_polynomial & f) + { + return *this = operator%(f); + } //: Evaluate polynomial at value \p x - T evaluate(T const& x) const; + T + evaluate(const T & x) const; //: Return derivative of this polynomial - vnl_polynomial derivative() const; + vnl_polynomial + derivative() const; //: Evaluate derivative at value \p x - T devaluate(T const& x) const { return derivative().evaluate(x); } + T + devaluate(const T & x) const + { + return derivative().evaluate(x); + } //: Return primitive function (inverse derivative) of this polynomial // Since a primitive function is not unique, the one with constant term 0 is returned. // Beware that this operation might not make sense for integral types T! - vnl_polynomial primitive() const; + vnl_polynomial + primitive() const; //: Evaluate integral at \p x (assuming constant of integration is zero) // Beware that this operation might not make sense for integral types T! - T evaluate_integral(T const& x) const { return primitive().evaluate(x); } + T + evaluate_integral(const T & x) const + { + return primitive().evaluate(x); + } //: Evaluate integral between \p x1 and \p x2 // Beware that this operation might not make sense for integral types T! - T evaluate_integral(T const& x1, T const& x2) const { return evaluate_integral(x2)-evaluate_integral(x1); } + T + evaluate_integral(const T & x1, const T & x2) const + { + return evaluate_integral(x2) - evaluate_integral(x1); + } // Data Access--------------------------------------------------------------- @@ -146,24 +210,51 @@ class VNL_EXPORT vnl_polynomial // Note that this method assumes a compactified representation, i.e., one // where the highest order coefficient is non-zero. Otherwise, the value // returned by degree() will be larger than the degree. - int degree() const { return int(coeffs_.size()) - 1; } + int + degree() const + { + return int(coeffs_.size()) - 1; + } //: Access to the polynomial coefficient of $X^i$ - T& operator [] (unsigned int i) { assert(int(i)<=degree()); return coeffs_[i]; } + T & + operator[](unsigned int i) + { + assert(int(i) <= degree()); + return coeffs_[i]; + } //: Access to the polynomial coefficient of $X^i$ - T operator [] (unsigned int i) const { assert(int(i)<=degree()); return coeffs_[i]; } + T + operator[](unsigned int i) const + { + assert(int(i) <= degree()); + return coeffs_[i]; + } //: Return the vector of coefficients - const std::vector& coefficients() const { return coeffs_; } + const std::vector & + coefficients() const + { + return coeffs_; + } //: Return the vector of coefficients - std::vector& coefficients() { return coeffs_; } + std::vector & + coefficients() + { + return coeffs_; + } - void set_coefficients(std::vector const& coeffs) {coeffs_ = coeffs;} + void + set_coefficients(const std::vector & coeffs) + { + coeffs_ = coeffs; + } //: Print this polynomial to stream - void print(std::ostream& os) const; + void + print(std::ostream & os) const; - protected: +protected: //: The coefficients of the polynomial. // coeffs_.front() is the const term. // coeffs_[n] is the coefficient of the $X^n$ term @@ -171,7 +262,12 @@ class VNL_EXPORT vnl_polynomial }; template -std::ostream& operator<<(std::ostream& os, vnl_polynomial const& p) { p.print(os); return os; } +std::ostream & +operator<<(std::ostream & os, const vnl_polynomial & p) +{ + p.print(os); + return os; +} #define VNL_POLYNOMIAL_INSTANTIATE(T) extern "please #include vnl/vnl_polynomial.hxx instead" diff --git a/core/vnl/vnl_polynomial.hxx b/core/vnl/vnl_polynomial.hxx index 6968a4a8b4e..533cfab4bc9 100644 --- a/core/vnl/vnl_polynomial.hxx +++ b/core/vnl/vnl_polynomial.hxx @@ -19,13 +19,16 @@ //: Evaluate polynomial at value x template -T vnl_polynomial::evaluate(T const& x) const +T +vnl_polynomial::evaluate(const T & x) const { typename std::vector::const_iterator i = coeffs_.begin(); - if (i == coeffs_.end()) return T(0); + if (i == coeffs_.end()) + return T(0); T acc = *i; T xi = x; // will be x^i - for (++i; i!=coeffs_.end(); ++i) { + for (++i; i != coeffs_.end(); ++i) + { acc += *i * xi; xi *= x; } @@ -34,38 +37,49 @@ T vnl_polynomial::evaluate(T const& x) const //: Returns negative of this polynomial template -vnl_polynomial::signed_t> vnl_polynomial::operator-() const +vnl_polynomial::signed_t> +vnl_polynomial::operator-() const { std::vector neg = coeffs_; typename std::vector::iterator i = neg.begin(); - for (; i!=neg.end(); ++i) *i = - *i; + for (; i != neg.end(); ++i) + *i = -*i; return vnl_polynomial(neg); } //: Returns polynomial which is sum of this with polynomial f template -vnl_polynomial vnl_polynomial::operator+(vnl_polynomial const& f) const +vnl_polynomial +vnl_polynomial::operator+(const vnl_polynomial & f) const { // Degree of result is (at most) the maximum of the two input degrees: - int d=degree(), d2=f.degree(); // any or both of these might be -1 ! + const int d = degree(); + const int d2 = f.degree(); // any or both of these might be -1 ! std::vector sum = coeffs_; - for (int i=0;i<=d&&i<=d2;++i) sum[i]+=f[i]; - for (int i=d+1;i<=d2;++i) sum.push_back(f[i]); + for (int i = 0; i <= d && i <= d2; ++i) + sum[i] += f[i]; + for (int i = d + 1; i <= d2; ++i) + sum.push_back(f[i]); // normalise the result, viz. such that the highest order coefficient is zero: - while (sum.end() != sum.begin() && sum.back() == T(0)) sum.pop_back(); + while (sum.end() != sum.begin() && sum.back() == T(0)) + sum.pop_back(); return vnl_polynomial(sum); } //: Returns polynomial which is product of this with polynomial f template -vnl_polynomial vnl_polynomial::operator*(vnl_polynomial const& f) const +vnl_polynomial +vnl_polynomial::operator*(const vnl_polynomial & f) const { - int d1=degree(), d2=f.degree(), d = d1+d2; - if (d1<0 || d2<0) return vnl_polynomial(); // one of the factors is zero - std::vector prod(d+1, T(0)); - for (int i=0;i<=d1;++i) - for (int j=0;j<=d2;++j) - prod[i+j] += coeffs_[i]*f[j]; + const int d1 = degree(); + const int d2 = f.degree(); + const int d = d1 + d2; + if (d1 < 0 || d2 < 0) + return vnl_polynomial(); // one of the factors is zero + std::vector prod(d + 1, T(0)); + for (int i = 0; i <= d1; ++i) + for (int j = 0; j <= d2; ++j) + prod[i + j] += coeffs_[i] * f[j]; return vnl_polynomial(prod); } @@ -73,16 +87,22 @@ vnl_polynomial vnl_polynomial::operator*(vnl_polynomial const& f) const // Beware that this operation might not make sense for integral types T // if the highest order coefficient of f is not 1 or -1! template -vnl_polynomial vnl_polynomial::operator/(vnl_polynomial const& f) const +vnl_polynomial +vnl_polynomial::operator/(const vnl_polynomial & f) const { - int d1=degree(), d2=f.degree(), d=d1-d2; // d will be the degree of the quotient - assert (d2 >= 0 && f[d2] != T(0)); // denominator should not be zero - if (d<0) return vnl_polynomial(); // nominator is zero, or denominator has higher degree than nominator + const int d1 = degree(); + const int d2 = f.degree(); + const int d = d1 - d2; // d will be the degree of the quotient + assert(d2 >= 0 && f[d2] != T(0)); // denominator should not be zero + if (d < 0) + return vnl_polynomial(); // nominator is zero, or denominator has higher degree than nominator std::vector quot; - for (int i=0;i<=d;++i) { - T acc = coeffs_[d1-i]; - for (int j=0;j(quot); } @@ -91,27 +111,32 @@ vnl_polynomial vnl_polynomial::operator/(vnl_polynomial const& f) const // Beware that this operation might not make sense for integral types T // if the highest order coefficient of f is not 1 or -1! template -vnl_polynomial vnl_polynomial::operator%(vnl_polynomial const& f) const +vnl_polynomial +vnl_polynomial::operator%(const vnl_polynomial & f) const { - vnl_polynomial quot = operator/(f); - if (quot.degree() < 0) return *this; + const vnl_polynomial quot = operator/(f); + if (quot.degree() < 0) + return *this; vnl_polynomial prod = f * quot; - int n=f.degree(); // size of the result, i.e., one more than degree of the result + const int n = f.degree(); // size of the result, i.e., one more than degree of the result std::vector diff; - for (int i=0; i(diff); } //: Return derivative of this polynomial template -vnl_polynomial vnl_polynomial::derivative() const +vnl_polynomial +vnl_polynomial::derivative() const { std::vector cd; // will be one shorter than coeffs_ typename std::vector::const_iterator i = coeffs_.begin(); T n = T(1); - for (++i; i!=coeffs_.end(); ++i,++n) + for (++i; i != coeffs_.end(); ++i, ++n) cd.push_back(*i * n); return vnl_polynomial(cd); } @@ -120,39 +145,50 @@ vnl_polynomial vnl_polynomial::derivative() const // Since a primitive function is not unique, the one with constant = 0 is returned // Beware that this operation might not make sense for integral types T! template -vnl_polynomial vnl_polynomial::primitive() const +vnl_polynomial +vnl_polynomial::primitive() const { std::vector cd; // will be one longer than coeffs_ T n = T(0); cd.push_back(n); typename std::vector::const_iterator i = coeffs_.begin(); - for (++n; i!=coeffs_.end(); ++i,++n) + for (++n; i != coeffs_.end(); ++i, ++n) cd.push_back(*i / n); return vnl_polynomial(cd); } template -void vnl_polynomial::print(std::ostream& os) const +void +vnl_polynomial::print(std::ostream & os) const { bool first_coeff = true; - for (int i=degree(); i >= 0; --i) { - if (coeffs_[i] == T(0)) continue; + for (int i = degree(); i >= 0; --i) + { + if (coeffs_[i] == T(0)) + continue; os << ' '; - if (coeffs_[i] > T(0) && !first_coeff) os << '+'; - if (i==0) os << coeffs_[i]; - else if (coeffs_[i] == -T(1)) os << '-'; - else if (coeffs_[i] != T(1)) os << coeffs_[i] << ' '; - if (i == 1) os << 'X'; - else if (i != 0) os << "X^" << i; + if (coeffs_[i] > T(0) && !first_coeff) + os << '+'; + if (i == 0) + os << coeffs_[i]; + else if (coeffs_[i] == -T(1)) + os << '-'; + else if (coeffs_[i] != T(1)) + os << coeffs_[i] << ' '; + if (i == 1) + os << 'X'; + else if (i != 0) + os << "X^" << i; first_coeff = false; } - if (first_coeff) os << " 0"; + if (first_coeff) + os << " 0"; } #undef VNL_POLYNOMIAL_INSTANTIATE -#define VNL_POLYNOMIAL_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_polynomial; \ -template VNL_EXPORT std::ostream& operator<<(std::ostream& os, vnl_polynomial const&) +#define VNL_POLYNOMIAL_INSTANTIATE(T) \ + template class VNL_EXPORT vnl_polynomial; \ + template VNL_EXPORT std::ostream & operator<<(std::ostream & os, vnl_polynomial const &) #endif // vnl_polynomial_hxx_ diff --git a/core/vnl/vnl_power.h b/core/vnl/vnl_power.h index 64b79729216..4b42bbf88cc 100644 --- a/core/vnl/vnl_power.h +++ b/core/vnl/vnl_power.h @@ -33,18 +33,20 @@ // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed vnl_power(vnl_matrix_fixed const& m, int n) +vnl_matrix_fixed +vnl_power(const vnl_matrix_fixed & m, int n) { assert(n >= 0 || d <= 4); // to allow the use of vnl_inverse() if (n == 0) - return vnl_matrix_fixed().set_identity(); + return vnl_matrix_fixed().set_identity(); else if (n == 1 || m.is_identity()) return m; else if (n < 0) return vnl_inverse(vnl_power(m, -n)); - else { - vnl_matrix_fixed r = vnl_power(m, n/2); - return n%2==0 ? r * r : r * r * m; + else + { + const vnl_matrix_fixed r = vnl_power(m, n / 2); + return n % 2 == 0 ? r * r : r * r * m; } } @@ -60,25 +62,27 @@ vnl_matrix_fixed vnl_power(vnl_matrix_fixed const& m, int n) // \relatesalso vnl_matrix template -vnl_matrix vnl_power(vnl_matrix const& m, int n) +vnl_matrix +vnl_power(const vnl_matrix & m, int n) { assert(m.rows() == m.columns()); assert(n >= 0 || m.rows() <= 4); if (n == 0) - return vnl_matrix(m.rows(),m.columns()).set_identity(); + return vnl_matrix(m.rows(), m.columns()).set_identity(); else if (n == 1 || m.is_identity()) return m; else if (n < 0 && m.rows() == 1) - return vnl_power(vnl_matrix_fixed(m),n).as_ref(); + return vnl_power(vnl_matrix_fixed(m), n).as_ref(); else if (n < 0 && m.rows() == 2) - return vnl_power(vnl_matrix_fixed(m),n).as_ref(); + return vnl_power(vnl_matrix_fixed(m), n).as_ref(); else if (n < 0 && m.rows() == 3) - return vnl_power(vnl_matrix_fixed(m),n).as_ref(); + return vnl_power(vnl_matrix_fixed(m), n).as_ref(); else if (n < 0 && m.rows() == 4) - return vnl_power(vnl_matrix_fixed(m),n).as_ref(); - else { - vnl_matrix r = vnl_power(m, n/2); - return n%2==0 ? r * r : r * r * m; + return vnl_power(vnl_matrix_fixed(m), n).as_ref(); + else + { + const vnl_matrix r = vnl_power(m, n / 2); + return n % 2 == 0 ? r * r : r * r * m; } } diff --git a/core/vnl/vnl_quaternion.h b/core/vnl/vnl_quaternion.h index ac44ea352e2..0c4a2b04c38 100644 --- a/core/vnl/vnl_quaternion.h +++ b/core/vnl/vnl_quaternion.h @@ -62,10 +62,10 @@ template class VNL_EXPORT vnl_quaternion : public vnl_vector_fixed { - private: - typedef vnl_vector_fixed Base; - public: +private: + typedef vnl_vector_fixed Base; +public: //: Constructor for null quaternion vnl_quaternion() = default; @@ -79,87 +79,144 @@ class VNL_EXPORT vnl_quaternion : public vnl_vector_fixed //: Construct quaternion from axis and angle of rotation. // \note If you specify an angle in [0, 2pi], then methods angle() and axis() will return the same values. - // However, if you specify an angle in [-2pi, 0], then methods angle() and axis() will return values with opposite signs. + // However, if you specify an angle in [-2pi, 0], then methods angle() and axis() will return values with opposite + // signs. // \sa vnl_quaternion::angle() // \sa vnl_quaternion::axis() - vnl_quaternion(vnl_vector_fixed const& axis, double angle); + vnl_quaternion(const vnl_vector_fixed & axis, double angle); //: Construct quaternion from 3x3 row-major matrix - explicit vnl_quaternion(vnl_matrix_fixed const& transform); + explicit vnl_quaternion(const vnl_matrix_fixed & transform); //: Construct quaternion from a 3D vector - vnl_quaternion(vnl_vector_fixed const& vec); + vnl_quaternion(const vnl_vector_fixed & vec); //: Construct quaternion from a 4D vector - vnl_quaternion (vnl_vector_fixed const& vec); + vnl_quaternion(const vnl_vector_fixed & vec); //: Copy constructor -- Creates a copy of from quaternion. - inline vnl_quaternion(vnl_quaternion const& from) : Base(from) {} + inline vnl_quaternion(const vnl_quaternion & from) + : Base(from) + {} //: Free internal array inline ~vnl_quaternion() = default; // vnl_vector_fixed will free data array //: Overloads assignment operator to copy rhs quaternion into lhs quaternion. - inline vnl_quaternion& operator= (vnl_quaternion const& rhs) { Base::operator=(rhs); return *this; } + inline vnl_quaternion & + operator=(const vnl_quaternion & rhs) + { + Base::operator=(rhs); + return *this; + } //: Imaginary component, parallel to axis of rotation. // Use this accessor to both get and set the component. - inline T& x() { return this->operator()(0); } + inline T & + x() + { + return this->operator()(0); + } //: Imaginary component, parallel to axis of rotation. // Use this accessor to both get and set the component. - inline T& y() { return this->operator()(1); } + inline T & + y() + { + return this->operator()(1); + } //: Imaginary component, parallel to axis of rotation. // Use this accessor to both get and set the component. - inline T& z() { return this->operator()(2); } + inline T & + z() + { + return this->operator()(2); + } //: Real component. // Use this accessor to both get and set the component. - inline T& r() { return this->operator()(3); } + inline T & + r() + { + return this->operator()(3); + } //: Imaginary component, parallel to axis of rotation. // Use this accessor to get the component. - inline T x() const { return this->operator()(0); } + inline T + x() const + { + return this->operator()(0); + } //: Imaginary component, parallel to axis of rotation. // Use this accessor to get the component. - inline T y() const { return this->operator()(1); } + inline T + y() const + { + return this->operator()(1); + } //: Imaginary component, parallel to axis of rotation. // Use this accessor to get the component. - inline T z() const { return this->operator()(2); } + inline T + z() const + { + return this->operator()(2); + } //: Real component. // Use this accessor to get the component. - inline T r() const { return this->operator()(3); } + inline T + r() const + { + return this->operator()(3); + } //: Copies and returns the real part. - inline T real() const { return (*this)[3]; } + inline T + real() const + { + return (*this)[3]; + } //: Copies and returns the imaginary part. - inline vnl_vector_fixed imaginary() const { return this->extract(3,0); } + inline vnl_vector_fixed + imaginary() const + { + return this->extract(3, 0); + } //: Axis of rotation. - // \note Axis not well defined for theta==0. In such a case (or if provided axis==(0,0,0)), this function returns (0,0,1). - vnl_vector_fixed axis() const; + // \note Axis not well defined for theta==0. In such a case (or if provided axis==(0,0,0)), this function returns + // (0,0,1). + vnl_vector_fixed + axis() const; //: Angle of rotation. // \note Returned angle lies in [0, 2*pi] - double angle() const; + double + angle() const; //: 3x3 rotation matrix // The orthonormal vectors are the rows of the matrix, not its columns - vnl_matrix_fixed rotation_matrix_transpose() const; + vnl_matrix_fixed + rotation_matrix_transpose() const; //: 4x4 rotation matrix - vnl_matrix_fixed rotation_matrix_transpose_4() const; + vnl_matrix_fixed + rotation_matrix_transpose_4() const; //: Same real, opposite img part - vnl_quaternion conjugate() const; + vnl_quaternion + conjugate() const; //: Inverse for nonzero quat - vnl_quaternion inverse() const; + vnl_quaternion + inverse() const; - vnl_quaternion operator* (vnl_quaternion const&) const; + vnl_quaternion + operator*(const vnl_quaternion &) const; //: Rotate 3D v // The quaternion must be normalised first. - vnl_vector_fixed rotate(vnl_vector_fixed const&) const; + vnl_vector_fixed + rotate(const vnl_vector_fixed &) const; //: Rotation representation in Euler angles. // The angles returned will be [theta_X,theta_Y,theta_Z] @@ -167,15 +224,17 @@ class VNL_EXPORT vnl_quaternion : public vnl_vector_fixed // about the X axis, then theta_Y about the Y-axis, etc. // The axes stay in a fixed reference frame. // The quaternion mut be normalised first. - vnl_vector_fixed rotation_euler_angles() const; + vnl_vector_fixed + rotation_euler_angles() const; }; //: operator<< // \relatesalso vnl_quaternion template -std::istream& operator>> (std::istream& is, vnl_quaternion &q) +std::istream & +operator>>(std::istream & is, vnl_quaternion & q) { - vnl_vector_fixed v; + vnl_vector_fixed v; is >> v; q = vnl_quaternion(v); return is; @@ -185,9 +244,10 @@ std::istream& operator>> (std::istream& is, vnl_quaternion &q) //: operator<< // \relatesalso vnl_quaternion template -inline std::ostream& operator<< (std::ostream& os, vnl_quaternion const& q) +inline std::ostream & +operator<<(std::ostream & os, const vnl_quaternion & q) { - return os << *((const vnl_vector_fixed*) &q); + return os << *((const vnl_vector_fixed *)&q); } #define VNL_QUATERNION_INSTANTIATE(T) extern "Please #include first" diff --git a/core/vnl/vnl_quaternion.hxx b/core/vnl/vnl_quaternion.hxx index 526d7f3267c..0a2163b8a55 100644 --- a/core/vnl/vnl_quaternion.hxx +++ b/core/vnl/vnl_quaternion.hxx @@ -52,23 +52,23 @@ // rotation axis. template -vnl_quaternion::vnl_quaternion (T tx, T ty, T tz, T rea) +vnl_quaternion::vnl_quaternion(T tx, T ty, T tz, T rea) { - this->operator[](0) = tx; // 3 first elements are - this->operator[](1) = ty; // imaginary parts + this->operator[](0) = tx; // 3 first elements are + this->operator[](1) = ty; // imaginary parts this->operator[](2) = tz; - this->operator[](3) = rea; // last element is real part + this->operator[](3) = rea; // last element is real part } //: Creates a quaternion from the normalized axis direction and the angle of rotation in radians. template -vnl_quaternion::vnl_quaternion(vnl_vector_fixed const& Axis, double Angle) +vnl_quaternion::vnl_quaternion(const vnl_vector_fixed & Axis, double Angle) { - double a = Angle * 0.5; // half angle + const double a = Angle * 0.5; // half angle T s = T(std::sin(a)); - for (int i = 0; i < 3; i++) // imaginary vector is sine of - this->operator[](i) = T(s * Axis(i));// half angle multiplied with axis + for (int i = 0; i < 3; i++) // imaginary vector is sine of + this->operator[](i) = T(s * Axis(i)); // half angle multiplied with axis this->operator[](3) = T(std::cos(a)); // real part is cosine of half angle } @@ -77,7 +77,7 @@ vnl_quaternion::vnl_quaternion(vnl_vector_fixed const& Axis, double Angl // (x, y, z) components. template -vnl_quaternion::vnl_quaternion(vnl_vector_fixed const& vec) +vnl_quaternion::vnl_quaternion(const vnl_vector_fixed & vec) { for (unsigned int i = 0; i < 3; ++i) this->operator[](i) = vec(i); @@ -89,7 +89,7 @@ vnl_quaternion::vnl_quaternion(vnl_vector_fixed const& vec) // provide casting between vector and quaternion template -vnl_quaternion::vnl_quaternion(vnl_vector_fixed const& vec) +vnl_quaternion::vnl_quaternion(const vnl_vector_fixed & vec) { for (unsigned int i = 0; i < 4; ++i) // 1-1 layout between vector & quaternion this->operator[](i) = vec[i]; @@ -102,50 +102,59 @@ vnl_quaternion::vnl_quaternion(vnl_vector_fixed const& vec) // \warning Takes the transpose of the rotation matrix, i.e., // the orthonormal vectors must be the rows of the matrix, not the columns. template -vnl_quaternion::vnl_quaternion(vnl_matrix_fixed const& rot) +vnl_quaternion::vnl_quaternion(const vnl_matrix_fixed & rot) { - double d0 = rot(0,0), d1 = rot(1,1), d2 = rot(2,2); - double xx = 1.0 + d0 - d1 - d2; // from the diagonal of the rotation - double yy = 1.0 - d0 + d1 - d2; // matrix, find the terms in - double zz = 1.0 - d0 - d1 + d2; // each Quaternion component - double rr = 1.0 + d0 + d1 + d2; // (using the fact that rr+xx+yy+zz=4) - - double max = rr; // find the maximum of all terms; - if (xx > max) max = xx; // dividing by the maximum makes - if (yy > max) max = yy; // the computations more stable - if (zz > max) max = zz; // and avoid division by zero - - if (rr == max) { - T r4 = T(std::sqrt(rr)*2); + const double d0 = rot(0, 0); + const double d1 = rot(1, 1); + const double d2 = rot(2, 2); + const double xx = 1.0 + d0 - d1 - d2; // from the diagonal of the rotation + const double yy = 1.0 - d0 + d1 - d2; // matrix, find the terms in + const double zz = 1.0 - d0 - d1 + d2; // each Quaternion component + const double rr = 1.0 + d0 + d1 + d2; // (using the fact that rr+xx+yy+zz=4) + + double max = rr; // find the maximum of all terms; + if (xx > max) + max = xx; // dividing by the maximum makes + if (yy > max) + max = yy; // the computations more stable + if (zz > max) + max = zz; // and avoid division by zero + + if (rr == max) + { + T r4 = T(std::sqrt(rr) * 2); this->r() = r4 / 4; r4 = T(1) / r4; - this->x() = (rot(1,2) - rot(2,1)) * r4; // find other components from - this->y() = (rot(2,0) - rot(0,2)) * r4; // off diagonal terms of - this->z() = (rot(0,1) - rot(1,0)) * r4; // rotation matrix. + this->x() = (rot(1, 2) - rot(2, 1)) * r4; // find other components from + this->y() = (rot(2, 0) - rot(0, 2)) * r4; // off diagonal terms of + this->z() = (rot(0, 1) - rot(1, 0)) * r4; // rotation matrix. } - else if (xx == max) { - T x4 = T(std::sqrt(xx)*2); + else if (xx == max) + { + T x4 = T(std::sqrt(xx) * 2); this->x() = x4 / 4; x4 = T(1) / x4; - this->y() = (rot(0,1) + rot(1,0)) * x4; - this->z() = (rot(0,2) + rot(2,0)) * x4; - this->r() = (rot(1,2) - rot(2,1)) * x4; + this->y() = (rot(0, 1) + rot(1, 0)) * x4; + this->z() = (rot(0, 2) + rot(2, 0)) * x4; + this->r() = (rot(1, 2) - rot(2, 1)) * x4; } - else if (yy == max) { - T y4 = T(std::sqrt(yy)*2); - this->y() = y4 / 4; + else if (yy == max) + { + T y4 = T(std::sqrt(yy) * 2); + this->y() = y4 / 4; y4 = T(1) / y4; - this->x() = (rot(0,1) + rot(1,0)) * y4; - this->z() = (rot(1,2) + rot(2,1)) * y4; - this->r() = (rot(2,0) - rot(0,2)) * y4; + this->x() = (rot(0, 1) + rot(1, 0)) * y4; + this->z() = (rot(1, 2) + rot(2, 1)) * y4; + this->r() = (rot(2, 0) - rot(0, 2)) * y4; } - else { - T z4 = T(std::sqrt(zz)*2); - this->z() = z4 / 4; + else + { + T z4 = T(std::sqrt(zz) * 2); + this->z() = z4 / 4; z4 = T(1) / z4; - this->x() = (rot(0,2) + rot(2,0)) * z4; - this->y() = (rot(1,2) + rot(2,1)) * z4; - this->r() = (rot(0,1) - rot(1,0)) * z4; + this->x() = (rot(0, 2) + rot(2, 0)) * z4; + this->y() = (rot(1, 2) + rot(2, 1)) * z4; + this->r() = (rot(0, 1) - rot(1, 0)) * z4; } } @@ -156,9 +165,9 @@ vnl_quaternion::vnl_quaternion(vnl_matrix_fixed const& rot) template vnl_quaternion::vnl_quaternion(T theta_X, T theta_Y, T theta_Z) { - vnl_quaternion Rx(T(std::sin(double(theta_X)*0.5)), 0, 0, T(std::cos(double(theta_X)*0.5))); - vnl_quaternion Ry(0, T(std::sin(double(theta_Y)*0.5)), 0, T(std::cos(double(theta_Y)*0.5))); - vnl_quaternion Rz(0, 0, T(std::sin(double(theta_Z)*0.5)), T(std::cos(double(theta_Z)*0.5))); + const vnl_quaternion Rx(T(std::sin(double(theta_X) * 0.5)), 0, 0, T(std::cos(double(theta_X) * 0.5))); + const vnl_quaternion Ry(0, T(std::sin(double(theta_Y) * 0.5)), 0, T(std::cos(double(theta_Y) * 0.5))); + const vnl_quaternion Rz(0, 0, T(std::sin(double(theta_Z) * 0.5)), T(std::cos(double(theta_Z) * 0.5))); *this = Rz * Ry * Rx; } @@ -168,22 +177,23 @@ vnl_quaternion::vnl_quaternion(T theta_X, T theta_Y, T theta_Z) // about the X axis, then theta_Y about the Y-axis, etc. // The axes stay in a fixed reference frame. template -vnl_vector_fixed vnl_quaternion::rotation_euler_angles() const +vnl_vector_fixed +vnl_quaternion::rotation_euler_angles() const { - vnl_vector_fixed angles; + vnl_vector_fixed angles; - vnl_matrix_fixed rotM = rotation_matrix_transpose_4(); - T xy = T(std::sqrt(double(vnl_math::sqr(rotM(0,0)) + vnl_math::sqr(rotM(0,1))))); + vnl_matrix_fixed rotM = rotation_matrix_transpose_4(); + T xy = T(std::sqrt(double(vnl_math::sqr(rotM(0, 0)) + vnl_math::sqr(rotM(0, 1))))); if (xy > std::numeric_limits::epsilon() * T(8)) { - angles(0) = T(std::atan2(double(rotM(1,2)), double(rotM(2,2)))); - angles(1) = T(std::atan2(double(-rotM(0,2)), double(xy))); - angles(2) = T(std::atan2(double(rotM(0,1)), double(rotM(0,0)))); + angles(0) = T(std::atan2(double(rotM(1, 2)), double(rotM(2, 2)))); + angles(1) = T(std::atan2(double(-rotM(0, 2)), double(xy))); + angles(2) = T(std::atan2(double(rotM(0, 1)), double(rotM(0, 0)))); } else { - angles(0) = T(std::atan2(double(-rotM(2,1)), double(rotM(1,1)))); - angles(1) = T(std::atan2(double(-rotM(0,2)), double(xy))); + angles(0) = T(std::atan2(double(-rotM(2, 1)), double(rotM(1, 1)))); + angles(1) = T(std::atan2(double(-rotM(0, 2)), double(xy))); angles(2) = T(0); } return angles; @@ -193,25 +203,28 @@ vnl_vector_fixed vnl_quaternion::rotation_euler_angles() const //: Queries the rotation angle of the quaternion. // Returned angle lies in [0, 2*pi] template -double vnl_quaternion::angle() const +double +vnl_quaternion::angle() const { return 2 * std::atan2(double(this->imaginary().magnitude()), - double(this->real())); // angle is always positive + double(this->real())); // angle is always positive } //: Queries the direction of the rotation axis of the quaternion. // A null quaternion will return zero for angle and k direction for axis. template -vnl_vector_fixed vnl_quaternion::axis() const +vnl_vector_fixed +vnl_quaternion::axis() const { - vnl_vector_fixed direc = this->imaginary(); // direc parallel to imag. part + vnl_vector_fixed direc = this->imaginary(); // direc parallel to imag. part T mag = direc.magnitude(); - if (mag == T(0)) { + if (mag == T(0)) + { std::cout << "Axis not well defined for zero Quaternion. Using (0,0,1) instead.\n"; - direc[2] = T(1); // or signal exception here. + direc[2] = T(1); // or signal exception here. } else - direc /= mag; // normalize direction vector + direc /= mag; // normalize direction vector return direc; } @@ -221,40 +234,49 @@ vnl_vector_fixed vnl_quaternion::axis() const // WARNING this is inconsistent with the quaternion docs and q.rotate() template -vnl_matrix_fixed vnl_quaternion::rotation_matrix_transpose() const +vnl_matrix_fixed +vnl_quaternion::rotation_matrix_transpose() const { - T x2 = x() * x(), xy = x() * y(), rx = r() * x(), - y2 = y() * y(), yz = y() * z(), ry = r() * y(), - z2 = z() * z(), zx = z() * x(), rz = r() * z(), - r2 = r() * r(); - vnl_matrix_fixed rot; - rot(0,0) = r2 + x2 - y2 - z2; // fill diagonal terms - rot(1,1) = r2 - x2 + y2 - z2; - rot(2,2) = r2 - x2 - y2 + z2; - rot(0,1) = 2 * (xy + rz); // fill off diagonal terms - rot(0,2) = 2 * (zx - ry); - rot(1,2) = 2 * (yz + rx); - rot(1,0) = 2 * (xy - rz); - rot(2,0) = 2 * (zx + ry); - rot(2,1) = 2 * (yz - rx); + T x2 = x() * x(); + T xy = x() * y(); + T rx = r() * x(); + T y2 = y() * y(); + T yz = y() * z(); + T ry = r() * y(); + T z2 = z() * z(); + T zx = z() * x(); + T rz = r() * z(); + T r2 = r() * r(); + vnl_matrix_fixed rot; + rot(0, 0) = r2 + x2 - y2 - z2; // fill diagonal terms + rot(1, 1) = r2 - x2 + y2 - z2; + rot(2, 2) = r2 - x2 - y2 + z2; + rot(0, 1) = 2 * (xy + rz); // fill off diagonal terms + rot(0, 2) = 2 * (zx - ry); + rot(1, 2) = 2 * (yz + rx); + rot(1, 0) = 2 * (xy - rz); + rot(2, 0) = 2 * (zx + ry); + rot(2, 1) = 2 * (yz - rx); return rot; } template -vnl_matrix_fixed vnl_quaternion::rotation_matrix_transpose_4() const +vnl_matrix_fixed +vnl_quaternion::rotation_matrix_transpose_4() const { - vnl_matrix_fixed rot; + vnl_matrix_fixed rot; return rot.set_identity().update(this->rotation_matrix_transpose().as_ref()); } //: Returns the conjugate of given quaternion, having same real and opposite imaginary parts. template -vnl_quaternion vnl_quaternion::conjugate() const +vnl_quaternion +vnl_quaternion::conjugate() const { - return vnl_quaternion (-x(), -y(), -z(), r()); + return vnl_quaternion(-x(), -y(), -z(), r()); } //: Returns the inverse of given quaternion. @@ -262,7 +284,8 @@ vnl_quaternion vnl_quaternion::conjugate() const // same as the conjugate. template -vnl_quaternion vnl_quaternion::inverse() const +vnl_quaternion +vnl_quaternion::inverse() const { vnl_quaternion inv = this->conjugate(); inv /= vnl_c_vector::dot_product(this->data_, this->data_, 4); @@ -279,14 +302,15 @@ vnl_quaternion vnl_quaternion::inverse() const // and vectors are represented row-wise. template -vnl_quaternion vnl_quaternion::operator* (vnl_quaternion const& rhs) const +vnl_quaternion +vnl_quaternion::operator*(const vnl_quaternion & rhs) const { - T r1 = this->real(); // real and img parts of args + T r1 = this->real(); // real and img parts of args T r2 = rhs.real(); - vnl_vector_fixed i1 = this->imaginary(); - vnl_vector_fixed i2 = rhs.imaginary(); + const vnl_vector_fixed i1 = this->imaginary(); + const vnl_vector_fixed i2 = rhs.imaginary(); T real_v = (r1 * r2) - ::dot_product(i1, i2); // real&img of product q1*q2 - vnl_vector_fixed img = vnl_cross_3d(i1, i2); + vnl_vector_fixed img = vnl_cross_3d(i1, i2); img += (i2 * r1) + (i1 * r2); return vnl_quaternion(img[0], img[1], img[2], real_v); } @@ -296,17 +320,18 @@ vnl_quaternion vnl_quaternion::operator* (vnl_quaternion const& rhs) co // matrix, then use matrix multiplication to rotate many vectors. template -vnl_vector_fixed vnl_quaternion::rotate(vnl_vector_fixed const& v) const +vnl_vector_fixed +vnl_quaternion::rotate(const vnl_vector_fixed & v) const { T rea = this->real(); - vnl_vector_fixed i = this->imaginary(); - vnl_vector_fixed i_x_v(vnl_cross_3d(i, v)); - return v + i_x_v * T(2*rea) - vnl_cross_3d(i_x_v, i) * T(2); + const vnl_vector_fixed i = this->imaginary(); + const vnl_vector_fixed i_x_v(vnl_cross_3d(i, v)); + return v + i_x_v * T(2 * rea) - vnl_cross_3d(i_x_v, i) * T(2); } #undef VNL_QUATERNION_INSTANTIATE -#define VNL_QUATERNION_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_quaternion;\ -/*template VNL_EXPORT std::ostream& operator<< (std::ostream&, vnl_quaternion const&) */ +#define VNL_QUATERNION_INSTANTIATE(T) \ + template class VNL_EXPORT vnl_quaternion; \ + /*template VNL_EXPORT std::ostream& operator<< (std::ostream&, vnl_quaternion const&) */ #endif // vnl_quaternion_hxx_ diff --git a/core/vnl/vnl_random.cxx b/core/vnl/vnl_random.cxx index 1ec1eb68782..1a04ba59719 100644 --- a/core/vnl/vnl_random.cxx +++ b/core/vnl/vnl_random.cxx @@ -17,21 +17,13 @@ vnl_random::linear_congruential_lrand32() //: Construct with seed vnl_random::vnl_random(unsigned long seed) : linear_congruential_previous(seed) - , mz_array_position(0UL) - , mz_borrow(0) - , mz_previous_normal_flag(0) + { reseed(seed); } //: Construct with seed -vnl_random::vnl_random(unsigned long seed[vnl_random_array_size]) - : mz_array_position(0UL) - , mz_borrow(0) - , mz_previous_normal_flag(0) -{ - reseed(seed); -} +vnl_random::vnl_random(unsigned long seed[vnl_random_array_size]) { reseed(seed); } vnl_random::vnl_random(const vnl_random & r) : linear_congruential_previous(r.linear_congruential_previous) @@ -61,11 +53,7 @@ vnl_random::operator=(const vnl_random & r) return *this; } -vnl_random::vnl_random() - -{ - reseed(); -} +vnl_random::vnl_random() { reseed(); } vnl_random::~vnl_random() { @@ -135,14 +123,16 @@ vnl_random::normal() } else { - double x, y, r2; + double x; + double y; + double r2; do { x = drand32(-1.0, 1.0); y = drand32(-1.0, 1.0); r2 = x * x + y * y; } while (r2 >= 1.0 || r2 == 0.0); - double fac = std::sqrt(-2.0 * std::log(r2) / r2); + const double fac = std::sqrt(-2.0 * std::log(r2) / r2); mz_previous_normal = x * fac; mz_previous_normal_flag = 1; return y * fac; @@ -165,14 +155,16 @@ vnl_random::normal64() } else { - double x, y, r2; + double x; + double y; + double r2; do { x = drand64(-1.0, 1.0); y = drand64(-1.0, 1.0); r2 = x * x + y * y; } while (r2 >= 1.0 || r2 == 0.0); - double fac = std::sqrt(-2.0 * std::log(r2) / r2); + const double fac = std::sqrt(-2.0 * std::log(r2) / r2); mz_previous_normal = x * fac; mz_previous_normal_flag = 1; return y * fac; @@ -182,8 +174,8 @@ vnl_random::normal64() unsigned long vnl_random::lrand32() { - unsigned long p1 = mz_array[(vnl_random_array_size + mz_array_position - mz_previous1) % vnl_random_array_size]; - unsigned long p2 = (p1 - mz_array[mz_array_position] - mz_borrow) & 0xffffffff; + const unsigned long p1 = mz_array[(vnl_random_array_size + mz_array_position - mz_previous1) % vnl_random_array_size]; + const unsigned long p2 = (p1 - mz_array[mz_array_position] - mz_borrow) & 0xffffffff; if (p2 < p1) mz_borrow = 0; if (p2 > p1) @@ -201,8 +193,8 @@ vnl_random::lrand32(int lower, int upper) // Note: we have to reject some numbers otherwise we get a very slight bias // towards the lower part of the range lower - upper. See below - unsigned long range = upper - lower + 1; - unsigned long denom = 0xffffffff / range; + const unsigned long range = upper - lower + 1; + const unsigned long denom = 0xffffffff / range; unsigned long ran; while ((ran = lrand32()) >= denom * range) ; @@ -220,8 +212,8 @@ vnl_random::lrand32(int lower, int upper, int & count) // version of the above function that returns the number of lrand32() // calls made. - unsigned long range = upper - lower + 1; - unsigned long denom = 0xffffffff / range; + const unsigned long range = upper - lower + 1; + const unsigned long denom = 0xffffffff / range; unsigned long ran; count = 1; while ((ran = lrand32()) >= denom * range) diff --git a/core/vnl/vnl_random.h b/core/vnl/vnl_random.h index cbafd159437..12b05dc9338 100644 --- a/core/vnl/vnl_random.h +++ b/core/vnl/vnl_random.h @@ -24,124 +24,165 @@ constexpr unsigned int vnl_random_array_size = 37; // Annals of Applied Probability 1991, Vol. 1, No. 3, 462. class VNL_EXPORT vnl_random { - enum {linear_congruential_multiplier = 1664525, mz_previous1 = 24}; - unsigned long linear_congruential_previous; - unsigned long mz_seed_array[vnl_random_array_size]; - unsigned long mz_array[vnl_random_array_size]; - unsigned int mz_array_position{0UL}; - int mz_borrow{0}; - unsigned long linear_congruential_lrand32(); - - double mz_previous_normal; - int mz_previous_normal_flag{0}; - - public: - //: Default constructor. - // Initializes the random number generator non-deterministically. - // i.e. it will generate a different series of random numbers each - // time the program is run. - vnl_random(); - - //: Destructor - ~vnl_random(); - - //: Construct with seed. - // Initializes the random number generator deterministically - // using a single ulong as the 'seed'. A linear congruential - // generator is used to generate the 37 ulongs needed - // as the real seed. The same seed will produce the - // same series of random numbers. - // - // 9667566 is a good seed. - vnl_random(unsigned long seed); - - //: Construct with seed. - // Initializes the random number generator deterministically - // using 37 ulongs as the 'seed'. The same seed will - // produce the same series of random numbers. - vnl_random(unsigned long seed[vnl_random_array_size]); - - //: Copy constructor. - // Initializes/sets the random number generator to exactly - // the same state as the argument, i.e. both will generate exactly - // the same series of random numbers from then on. - vnl_random(const vnl_random&); - - //: Copy operator. - // Initializes/sets the random number generator to exactly - // the same state as the argument, i.e. both will generate exactly - // the same series of random numbers from then on. - vnl_random& operator=(const vnl_random&); - - //: Starts a new non-deterministic sequence from an already declared generator. - void reseed(); - - //: Starts a new deterministic sequence from an already declared generator using the provided seed. - void reseed(unsigned long); - - //: Starts a new deterministic sequence from an already declared generator using the provided seed. - void reseed(const unsigned long[vnl_random_array_size]); - - //: This restarts the sequence of random numbers. - // Restarts so that it repeats - // from the point at which you declared the generator, last - // initialized it, or last called a 'reseed'. - void restart(); - - //: Generates a random unsigned 32-bit number. - unsigned long lrand32(); - - //: Generates a random unsigned long in [a,b] - int lrand32(int a, int b); - - //: Generates a random unsigned long in [0,b] - int lrand32(int b) {return lrand32(0, b);} - - //: Generates a random unsigned long in [a,b] - int lrand32(int a, int b, int&); - - //: Generates a random double in the range a <= x <= b with 32 bit randomness. - // drand32(1,0) is random down to about the 10th decimal place. - double drand32(double a, double b); - - //: Generates a random unsigned integer in [0,n) - // This function allows the random number generator to be used as - // a functor, e.g. with std::random_shuffle() - unsigned long operator()(unsigned n) { return lrand32(0, n-1); } - - //: Generates a random double in the range 0 <= x <= b with 32 bit randomness. - // drand32(1.0) is random down to about the 10th decimal place. - double drand32(double b) {return drand32(0.0, b);} - - //: Generates a random double in the range 0 <= x <= 1 with 32 bit randomness. - // drand32() is random down to about the 10th decimal place. - double drand32() {return drand32(0.0, 1.0);} - - //: Generates a random double in the range a <= x <= b with 64 bit randomness. - // Completely random down to the accuracy of an IEEE double. - double drand64(double a, double b); - - //: Generates a random double in the range 0 <= x <= b with 64 bit randomness. - // Completely random down to the accuracy of an IEEE double. - double drand64(double b) {return drand64(0.0, b);} - - //: Generates a random double in the range 0 <= x <= 1 with 64 bit randomness. - // Completely random down to the accuracy of an IEEE double. - double drand64() {return drand64(0.0, 1.0);} - - //: Random value from a unit normal distribution about zero. - // Uses a drand32() as its underlying generator. - // Because the function uses a probability transform, the randomness (and - // quantisation) is non-linearly dependent on the value. The further the - // sample is from zero, the lower the number of bits on which it is random. - double normal(); - - //: Random value from a unit normal distribution about zero. - // Uses a drand64() as its underlying generator. - // Because the function uses a probability transform, the randomness (and - // quantisation) is non-linearly dependent on the value. The further the - // sample is from zero, the lower the number of bits on which it is random. - double normal64(); + enum + { + linear_congruential_multiplier = 1664525, + mz_previous1 = 24 + }; + unsigned long linear_congruential_previous; + unsigned long mz_seed_array[vnl_random_array_size]; + unsigned long mz_array[vnl_random_array_size]; + unsigned int mz_array_position{ 0UL }; + int mz_borrow{ 0 }; + unsigned long + linear_congruential_lrand32(); + + double mz_previous_normal; + int mz_previous_normal_flag{ 0 }; + +public: + //: Default constructor. + // Initializes the random number generator non-deterministically. + // i.e. it will generate a different series of random numbers each + // time the program is run. + vnl_random(); + + //: Destructor + ~vnl_random(); + + //: Construct with seed. + // Initializes the random number generator deterministically + // using a single ulong as the 'seed'. A linear congruential + // generator is used to generate the 37 ulongs needed + // as the real seed. The same seed will produce the + // same series of random numbers. + // + // 9667566 is a good seed. + vnl_random(unsigned long seed); + + //: Construct with seed. + // Initializes the random number generator deterministically + // using 37 ulongs as the 'seed'. The same seed will + // produce the same series of random numbers. + vnl_random(unsigned long seed[vnl_random_array_size]); + + //: Copy constructor. + // Initializes/sets the random number generator to exactly + // the same state as the argument, i.e. both will generate exactly + // the same series of random numbers from then on. + vnl_random(const vnl_random &); + + //: Copy operator. + // Initializes/sets the random number generator to exactly + // the same state as the argument, i.e. both will generate exactly + // the same series of random numbers from then on. + vnl_random & + operator=(const vnl_random &); + + //: Starts a new non-deterministic sequence from an already declared generator. + void + reseed(); + + //: Starts a new deterministic sequence from an already declared generator using the provided seed. + void + reseed(unsigned long); + + //: Starts a new deterministic sequence from an already declared generator using the provided seed. + void + reseed(const unsigned long[vnl_random_array_size]); + + //: This restarts the sequence of random numbers. + // Restarts so that it repeats + // from the point at which you declared the generator, last + // initialized it, or last called a 'reseed'. + void + restart(); + + //: Generates a random unsigned 32-bit number. + unsigned long + lrand32(); + + //: Generates a random unsigned long in [a,b] + int + lrand32(int a, int b); + + //: Generates a random unsigned long in [0,b] + int + lrand32(int b) + { + return lrand32(0, b); + } + + //: Generates a random unsigned long in [a,b] + int + lrand32(int a, int b, int &); + + //: Generates a random double in the range a <= x <= b with 32 bit randomness. + // drand32(1,0) is random down to about the 10th decimal place. + double + drand32(double a, double b); + + //: Generates a random unsigned integer in [0,n) + // This function allows the random number generator to be used as + // a functor, e.g. with std::random_shuffle() + unsigned long + operator()(unsigned n) + { + return lrand32(0, n - 1); + } + + //: Generates a random double in the range 0 <= x <= b with 32 bit randomness. + // drand32(1.0) is random down to about the 10th decimal place. + double + drand32(double b) + { + return drand32(0.0, b); + } + + //: Generates a random double in the range 0 <= x <= 1 with 32 bit randomness. + // drand32() is random down to about the 10th decimal place. + double + drand32() + { + return drand32(0.0, 1.0); + } + + //: Generates a random double in the range a <= x <= b with 64 bit randomness. + // Completely random down to the accuracy of an IEEE double. + double + drand64(double a, double b); + + //: Generates a random double in the range 0 <= x <= b with 64 bit randomness. + // Completely random down to the accuracy of an IEEE double. + double + drand64(double b) + { + return drand64(0.0, b); + } + + //: Generates a random double in the range 0 <= x <= 1 with 64 bit randomness. + // Completely random down to the accuracy of an IEEE double. + double + drand64() + { + return drand64(0.0, 1.0); + } + + //: Random value from a unit normal distribution about zero. + // Uses a drand32() as its underlying generator. + // Because the function uses a probability transform, the randomness (and + // quantisation) is non-linearly dependent on the value. The further the + // sample is from zero, the lower the number of bits on which it is random. + double + normal(); + + //: Random value from a unit normal distribution about zero. + // Uses a drand64() as its underlying generator. + // Because the function uses a probability transform, the randomness (and + // quantisation) is non-linearly dependent on the value. The further the + // sample is from zero, the lower the number of bits on which it is random. + double + normal64(); }; #endif // vnl_random_h diff --git a/core/vnl/vnl_rank.h b/core/vnl/vnl_rank.h index 1987e33c5a8..8fc725d897c 100644 --- a/core/vnl/vnl_rank.h +++ b/core/vnl/vnl_rank.h @@ -16,16 +16,26 @@ #include "vnl_matrix.h" #include "vnl/vnl_export.h" -typedef enum { vnl_rank_row, vnl_rank_column, vnl_rank_both } vnl_rank_type; -typedef enum { vnl_rank_pivot_one, vnl_rank_pivot_all } vnl_rank_pivot_type; +typedef enum +{ + vnl_rank_row, + vnl_rank_column, + vnl_rank_both +} vnl_rank_type; +typedef enum +{ + vnl_rank_pivot_one, + vnl_rank_pivot_all +} vnl_rank_pivot_type; //: Returns the rank of a matrix // By default, the row rank of the matrix is determined. // Specify vnl_rank_column to obtain the column rank. // // \relatesalso vnl_matrix -template VNL_EXPORT -unsigned int vnl_rank(vnl_matrix const& mat, vnl_rank_type = vnl_rank_both); +template +VNL_EXPORT unsigned int +vnl_rank(const vnl_matrix & mat, vnl_rank_type = vnl_rank_both); //: Row reduce a matrix. // First try to use 1 or -1 as pivot element in each row, to avoid divisions; @@ -42,17 +52,17 @@ unsigned int vnl_rank(vnl_matrix const& mat, vnl_rank_type = vnl_rank_both); // // \relatesalso vnl_matrix // -template VNL_EXPORT -vnl_matrix vnl_rank_row_reduce(vnl_matrix const& mat, - vnl_rank_pivot_type = vnl_rank_pivot_all); +template +VNL_EXPORT vnl_matrix +vnl_rank_row_reduce(const vnl_matrix & mat, vnl_rank_pivot_type = vnl_rank_pivot_all); //: Column reduce a matrix. // // \relatesalso vnl_matrix // -template VNL_EXPORT -vnl_matrix vnl_rank_column_reduce(vnl_matrix const& mat, - vnl_rank_pivot_type = vnl_rank_pivot_all); +template +VNL_EXPORT vnl_matrix +vnl_rank_column_reduce(const vnl_matrix & mat, vnl_rank_pivot_type = vnl_rank_pivot_all); //: Row and column reduce a matrix. // Perform both row reduction and column reduction on a matrix. @@ -63,9 +73,9 @@ vnl_matrix vnl_rank_column_reduce(vnl_matrix const& mat, // // \relatesalso vnl_matrix // -template VNL_EXPORT -vnl_matrix vnl_rank_row_column_reduce(vnl_matrix const& mat, - vnl_rank_pivot_type = vnl_rank_pivot_all); +template +VNL_EXPORT vnl_matrix +vnl_rank_row_column_reduce(const vnl_matrix & mat, vnl_rank_pivot_type = vnl_rank_pivot_all); #define VNL_RANK_INSTANTIATE(T) extern "please #include vnl/vnl_rank.hxx instead" diff --git a/core/vnl/vnl_rank.hxx b/core/vnl/vnl_rank.hxx index 0ec8244925b..32165fbbb91 100644 --- a/core/vnl/vnl_rank.hxx +++ b/core/vnl/vnl_rank.hxx @@ -5,46 +5,60 @@ #include "vnl_rank.h" template -vnl_matrix vnl_rank_row_reduce(vnl_matrix const& mat, vnl_rank_pivot_type t) +vnl_matrix +vnl_rank_row_reduce(const vnl_matrix & mat, vnl_rank_pivot_type t) { vnl_matrix a = mat; bool changed = true; - unsigned int m = a.rows(), n=a.columns(); + const unsigned int m = a.rows(); + const unsigned int n = a.columns(); while (changed) { changed = false; - for (unsigned int r=0; r vnl_rank_row_reduce(vnl_matrix const& mat, vnl_rank_pivot_type } template -vnl_matrix vnl_rank_column_reduce(vnl_matrix const& mat, vnl_rank_pivot_type t) +vnl_matrix +vnl_rank_column_reduce(const vnl_matrix & mat, vnl_rank_pivot_type t) { vnl_matrix a = mat; bool changed = true; - unsigned int m = a.rows(), n=a.columns(); + const unsigned int m = a.rows(); + const unsigned int n = a.columns(); while (changed) { changed = false; - for (unsigned int c=0; c vnl_rank_column_reduce(vnl_matrix const& mat, vnl_rank_pivot_ty } template -vnl_matrix vnl_rank_row_column_reduce(vnl_matrix const& mat, vnl_rank_pivot_type t) +vnl_matrix +vnl_rank_row_column_reduce(const vnl_matrix & mat, vnl_rank_pivot_type t) { vnl_matrix a = mat; bool changed = true; - unsigned int m = a.rows(), n=a.columns(); + const unsigned int m = a.rows(); + const unsigned int n = a.columns(); while (changed) { changed = false; - for (unsigned int r=0; r vnl_rank_row_column_reduce(vnl_matrix const& mat, vnl_rank_pivo } template -unsigned int vnl_rank(vnl_matrix const& mat, vnl_rank_type t) +unsigned int +vnl_rank(const vnl_matrix & mat, vnl_rank_type t) { unsigned int rank = 0; if (t == vnl_rank_row) { vnl_matrix a = vnl_rank_row_reduce(mat, vnl_rank_pivot_all); - for (unsigned int r=0; r a = (t == vnl_rank_column) ? vnl_rank_column_reduce(mat,vnl_rank_pivot_all) : - vnl_rank_row_column_reduce(mat,vnl_rank_pivot_all); - for (unsigned int c=0; c a = (t == vnl_rank_column) ? vnl_rank_column_reduce(mat, vnl_rank_pivot_all) + : vnl_rank_row_column_reduce(mat, vnl_rank_pivot_all); + for (unsigned int c = 0; c < a.columns(); ++c) { - unsigned int r=0; - while (r vnl_rank_row_reduce(vnl_matrix const&, vnl_rank_pivot_type);\ -template VNL_EXPORT vnl_matrix vnl_rank_column_reduce(vnl_matrix const&, vnl_rank_pivot_type);\ -template VNL_EXPORT vnl_matrix vnl_rank_row_column_reduce(vnl_matrix const&, vnl_rank_pivot_type);\ -template VNL_EXPORT unsigned int vnl_rank(vnl_matrix const&, vnl_rank_type) +#define VNL_RANK_INSTANTIATE(T) \ + template VNL_EXPORT vnl_matrix vnl_rank_row_reduce(vnl_matrix const &, vnl_rank_pivot_type); \ + template VNL_EXPORT vnl_matrix vnl_rank_column_reduce(vnl_matrix const &, vnl_rank_pivot_type); \ + template VNL_EXPORT vnl_matrix vnl_rank_row_column_reduce(vnl_matrix const &, vnl_rank_pivot_type); \ + template VNL_EXPORT unsigned int vnl_rank(vnl_matrix const &, vnl_rank_type) #endif // vnl_rank_hxx_ diff --git a/core/vnl/vnl_rational.cxx b/core/vnl/vnl_rational.cxx index 0e93fbc4ddd..204610aa957 100644 --- a/core/vnl/vnl_rational.cxx +++ b/core/vnl/vnl_rational.cxx @@ -14,17 +14,20 @@ template inline void makeNumDen(FloatingType d, int_type & num_, int_type & den_) { - bool sign = d < 0; + const bool sign = d < 0; if (sign) d = -d; // Continued fraction approximation of abs(d): recursively determined - int_type den = 0L, num = 1L, prev_den = 1L, prev_num = 0L; + int_type den = 0L; + int_type num = 1L; + int_type prev_den = 1L; + int_type prev_num = 0L; while (d * num < 1e9 && d * den < 1e9) { - int_type a = static_cast(d); // integral part of d - d -= a; // certainly >= 0 + const int_type a = static_cast(d); // integral part of d + d -= a; // certainly >= 0 int_type temp = num; num = a * num + prev_num; prev_num = temp; @@ -44,34 +47,29 @@ makeNumDen(FloatingType d, int_type & num_, int_type & den_) //: Creates a rational from a double. // This is done by computing the continued fraction approximation for d. -vnl_rational::vnl_rational(double d) -{ - makeNumDen(d, num_, den_); -} +vnl_rational::vnl_rational(double d) { makeNumDen(d, num_, den_); } //: Creates a rational from a double. // This is done by computing the continued fraction approximation for d. -vnl_rational::vnl_rational(float f) -{ - makeNumDen(f, num_, den_); -} +vnl_rational::vnl_rational(float f) { makeNumDen(f, num_, den_); } //: Multiply/assign: replace lhs by lhs * rhs // Note that 0 * Inf and Inf * 0 are undefined. // Also note that there could be integer overflow during this calculation! // In that case, an approximate result will be returned. vnl_rational & -vnl_rational::operator*=(vnl_rational const & r) +vnl_rational::operator*=(const vnl_rational & r) { assert(num_ != 0 || den_ != 0); // 0 * Inf is undefined - int_type a = vnl_rational::gcd(r.numerator(), den_), b = vnl_rational::gcd(r.denominator(), num_); + int_type a = vnl_rational::gcd(r.numerator(), den_); + int_type b = vnl_rational::gcd(r.denominator(), num_); num_ /= b; den_ /= a; a = r.numerator() / a; b = r.denominator() / b; // find out whether overflow would occur; in that case, return approximate result - double n = double(a) * double(num_); - double d = double(b) * double(den_); + const double n = double(a) * double(num_); + const double d = double(b) * double(den_); if (n < maxint_as_double && d < maxint_as_double) { num_ *= a; @@ -89,11 +87,11 @@ vnl_rational::operator*=(vnl_rational const & r) vnl_rational & vnl_rational::operator*=(int_type r) { - int_type a = vnl_rational::gcd(r, den_); + const int_type a = vnl_rational::gcd(r, den_); den_ /= a; r /= a; // find out whether overflow would occur; in that case, return approximate result - double n = double(r) * double(num_); + const double n = double(r) * double(num_); if (n < maxint_as_double) { num_ *= r; @@ -109,16 +107,18 @@ vnl_rational::operator*=(int_type r) // Also note that there could be integer overflow during this calculation! // In that case, an approximate result will be returned. vnl_rational & -vnl_rational::operator/=(vnl_rational const & r) +vnl_rational::operator/=(const vnl_rational & r) { assert(num_ != 0 || den_ != 0); // 0/0, Inf/Inf undefined - int_type a = vnl_rational::gcd(r.numerator(), num_), b = vnl_rational::gcd(r.denominator(), den_); + int_type a = vnl_rational::gcd(r.numerator(), num_); + int_type b = vnl_rational::gcd(r.denominator(), den_); num_ /= a; den_ /= b; a = r.numerator() / a; b = r.denominator() / b; // find out whether overflow would occur; in that case, return approximate result - double n = double(b) * double(num_), d = double(a) * double(den_); + const double n = double(b) * double(num_); + const double d = double(a) * double(den_); if (n < maxint_as_double && d < maxint_as_double) { num_ *= b; @@ -138,11 +138,11 @@ vnl_rational & vnl_rational::operator/=(int_type r) { assert(num_ != 0 || r != 0); // 0/0 undefined - int_type a = vnl_rational::gcd(r, num_); + const int_type a = vnl_rational::gcd(r, num_); num_ /= a; r /= a; // find out whether overflow would occur; in that case, return approximate result - double d = double(r) * double(den_); + const double d = double(r) * double(den_); if (d < maxint_as_double) { den_ *= r; diff --git a/core/vnl/vnl_rational.h b/core/vnl/vnl_rational.h index 5096ea46d24..911b6990e1e 100644 --- a/core/vnl/vnl_rational.h +++ b/core/vnl/vnl_rational.h @@ -74,19 +74,19 @@ // class VNL_EXPORT vnl_rational { - public: +public: //! The integer type of the numerator and the denominator. using int_type = std::int64_t; - private: - int_type num_{0L}; //!< Numerator portion - int_type den_{1L}; //!< Denominator portion +private: + int_type num_{ 0L }; //!< Numerator portion + int_type den_{ 1L }; //!< Denominator portion - public: - // Helper type alias to be used for SFINAE. - template - using enable_if_signed_integral_type = typename std::enable_if< - std::is_signed::value && std::is_integral::value>::type; +public: + // Helper type alias to be used for SFINAE. + template + using enable_if_signed_integral_type = + typename std::enable_if::value && std::is_integral::value>::type; //: Creates a rational with given numerator and denominator. // Default constructor gives 0. @@ -94,19 +94,27 @@ class VNL_EXPORT vnl_rational // The only input which is not allowed is (0,0); // the denominator is allowed to be 0, to represent +Inf or -Inf. - inline vnl_rational() { normalize(); } + inline vnl_rational() { normalize(); } - inline vnl_rational(int_type num) : num_(num) { - assert(num != 0 || den_ != 0); - normalize(); - } + inline vnl_rational(int_type num) + : num_(num) + { + assert(num != 0 || den_ != 0); + normalize(); + } inline vnl_rational(int_type num, int_type den) - : num_(num), den_(den) { assert(num!=0||den!=0); normalize(); } + : num_(num) + , den_(den) + { + assert(num != 0 || den != 0); + normalize(); + } //: Implicitly converts a signed or unsigned integer to a rational. - template ::value>::type> - inline vnl_rational(const T num) : num_{static_cast(num)} {} + template ::value>::type> + inline vnl_rational(const T num) + : num_{ static_cast(num) } + {} //: Creates a rational from a double. // This is done by computing the continued fraction approximation for d. @@ -114,376 +122,774 @@ class VNL_EXPORT vnl_rational vnl_rational(double d); vnl_rational(float d); // Copy constructor - inline vnl_rational(vnl_rational const& from) - : num_(from.numerator()), den_(from.denominator()) {} + inline vnl_rational(const vnl_rational & from) + : num_(from.numerator()) + , den_(from.denominator()) + {} // Destructor inline ~vnl_rational() = default; // Assignment: overwrite an existing vnl_rational - inline void set(int_type num, int_type den) { assert(num!=0||den!=0); num_=num; den_=den; normalize(); } + inline void + set(int_type num, int_type den) + { + assert(num != 0 || den != 0); + num_ = num; + den_ = den; + normalize(); + } //: Return the numerator of the (simplified) rational number representation - inline int_type numerator() const { return num_; } + inline int_type + numerator() const + { + return num_; + } //: Return the denominator of the (simplified) rational number representation - inline int_type denominator() const { return den_; } + inline int_type + denominator() const + { + return den_; + } //: Copies the contents and state of rhs rational over to the lhs - inline vnl_rational& operator=(vnl_rational const& rhs) { - num_ = rhs.numerator(); den_ = rhs.denominator(); return *this; } + inline vnl_rational & + operator=(const vnl_rational & rhs) + { + num_ = rhs.numerator(); + den_ = rhs.denominator(); + return *this; + } //: Returns true if the two rationals have the same representation - inline bool operator==(vnl_rational const& rhs) const { - return num_ == rhs.numerator() && den_ == rhs.denominator(); } - inline bool operator!=(vnl_rational const& rhs) const { return !operator==(rhs); } - inline bool operator==(int_type rhs) const { return num_ == rhs && den_ == 1; } - inline bool operator!=(int_type rhs) const { return !operator==(rhs); } + inline bool + operator==(const vnl_rational & rhs) const + { + return num_ == rhs.numerator() && den_ == rhs.denominator(); + } + inline bool + operator!=(const vnl_rational & rhs) const + { + return !operator==(rhs); + } + inline bool + operator==(int_type rhs) const + { + return num_ == rhs && den_ == 1; + } + inline bool + operator!=(int_type rhs) const + { + return !operator==(rhs); + } template > - inline bool operator==(const T rhs) const { return num_ == rhs && den_ == 1; } + inline bool + operator==(const T rhs) const + { + return num_ == rhs && den_ == 1; + } template > - inline bool operator!=(const T rhs) const { return !operator==(rhs); } + inline bool + operator!=(const T rhs) const + { + return !operator==(rhs); + } //: Unary minus - returns the negation of the current rational. - inline vnl_rational operator-() const { return vnl_rational(-num_, den_); } + inline vnl_rational + operator-() const + { + return { -num_, den_ }; + } //: Unary plus - returns the current rational. - inline vnl_rational operator+() const { return *this; } + inline vnl_rational + operator+() const + { + return *this; + } //: Unary not - returns true if rational is equal to zero. - inline bool operator!() const { return num_ == 0L; } + inline bool + operator!() const + { + return num_ == 0L; + } //: Returns the absolute value of the current rational. - inline vnl_rational abs() const { return vnl_rational(num_<0?-num_:num_, den_); } + inline vnl_rational + abs() const + { + return { num_ < 0 ? -num_ : num_, den_ }; + } //: Replaces rational with 1/rational and returns it. // Inverting 0 gives +Inf, inverting +-Inf gives 0. - vnl_rational& invert() { - int_type t = num_; num_ = den_; den_ = t; normalize(); return *this; } + vnl_rational & + invert() + { + const int_type t = num_; + num_ = den_; + den_ = t; + normalize(); + return *this; + } //: Plus/assign: replace lhs by lhs + rhs // Note that +Inf + -Inf and -Inf + +Inf are undefined. - inline vnl_rational& operator+=(vnl_rational const& r) { - if (den_ == r.denominator()) num_ += r.numerator(); - else { int_type c = vnl_rational::gcd(den_,r.denominator()); if (c==0) c=1; - num_ = num_*(r.denominator()/c) + (den_/c)*r.numerator(); - den_ *= r.denominator()/c; } - assert(num_!=0 || den_ != 0); // +Inf + -Inf is undefined - normalize(); return *this; - } - inline vnl_rational& operator+=(int_type r) { num_ += den_*r; return *this; } + inline vnl_rational & + operator+=(const vnl_rational & r) + { + if (den_ == r.denominator()) + num_ += r.numerator(); + else + { + int_type c = vnl_rational::gcd(den_, r.denominator()); + if (c == 0) + c = 1; + num_ = num_ * (r.denominator() / c) + (den_ / c) * r.numerator(); + den_ *= r.denominator() / c; + } + assert(num_ != 0 || den_ != 0); // +Inf + -Inf is undefined + normalize(); + return *this; + } + inline vnl_rational & + operator+=(int_type r) + { + num_ += den_ * r; + return *this; + } //: Minus/assign: replace lhs by lhs - rhs // Note that +Inf - +Inf and -Inf - -Inf are undefined. - inline vnl_rational& operator-=(vnl_rational const& r) { - if (den_ == r.denominator()) num_ -= r.num_; - else { int_type c = vnl_rational::gcd(den_,r.denominator()); if (c==0) c=1; - num_ = num_*(r.denominator()/c) - (den_/c)*r.numerator(); - den_ *= r.denominator()/c; } - assert(num_!=0 || den_ != 0); // +Inf - +Inf is undefined - normalize(); return *this; - } - inline vnl_rational& operator-=(int_type r) { num_ -= den_*r; return *this; } + inline vnl_rational & + operator-=(const vnl_rational & r) + { + if (den_ == r.denominator()) + num_ -= r.num_; + else + { + int_type c = vnl_rational::gcd(den_, r.denominator()); + if (c == 0) + c = 1; + num_ = num_ * (r.denominator() / c) - (den_ / c) * r.numerator(); + den_ *= r.denominator() / c; + } + assert(num_ != 0 || den_ != 0); // +Inf - +Inf is undefined + normalize(); + return *this; + } + inline vnl_rational & + operator-=(int_type r) + { + num_ -= den_ * r; + return *this; + } //: Multiply/assign: replace lhs by lhs * rhs // Note that 0 * Inf and Inf * 0 are undefined. // Also note that there could be integer overflow during this calculation! // In that case, an approximate result will be returned. - vnl_rational& operator*=(vnl_rational const& r); + vnl_rational & + operator*=(const vnl_rational & r); //: Multiply/assign: replace lhs by lhs * rhs // Note that there could be integer overflow during this calculation! // In that case, an approximate result will be returned. - vnl_rational& operator*=(int_type r); + vnl_rational & + operator*=(int_type r); //: Divide/assign: replace lhs by lhs / rhs // Note that 0 / 0 and Inf / Inf are undefined. // Also note that there could be integer overflow during this calculation! // In that case, an approximate result will be returned. - vnl_rational& operator/=(vnl_rational const& r); + vnl_rational & + operator/=(const vnl_rational & r); //: Divide/assign: replace lhs by lhs / rhs // Note that 0 / 0 is undefined. // Also note that there could be integer overflow during this calculation! // In that case, an approximate result will be returned. - vnl_rational& operator/=(int_type r); + vnl_rational & + operator/=(int_type r); //: Modulus/assign: replace lhs by lhs % rhs // Note that r % Inf is r, and that r % 0 and Inf % r are undefined. - inline vnl_rational& operator%=(vnl_rational const& r) { + inline vnl_rational & + operator%=(const vnl_rational & r) + { assert(r.numerator() != 0); - if (den_ == r.denominator()) num_ %= r.numerator(); - else { int_type c = vnl_rational::gcd(den_,r.denominator()); if (c==0) c=1; - num_ *= r.denominator()/c; - num_ %= (den_/c)*r.numerator(); - den_ *= r.denominator()/c; } - normalize(); return *this; + if (den_ == r.denominator()) + num_ %= r.numerator(); + else + { + int_type c = vnl_rational::gcd(den_, r.denominator()); + if (c == 0) + c = 1; + num_ *= r.denominator() / c; + num_ %= (den_ / c) * r.numerator(); + den_ *= r.denominator() / c; + } + normalize(); + return *this; + } + inline vnl_rational & + operator%=(int_type r) + { + assert(r); + num_ %= den_ * r; + normalize(); + return *this; } - inline vnl_rational& operator%=(int_type r) {assert(r);num_%=den_*r;normalize();return *this;} //: Pre-increment (++r). No-op when +-Inf. - inline vnl_rational& operator++() { num_ += den_; return *this; } + inline vnl_rational & + operator++() + { + num_ += den_; + return *this; + } //: Pre-decrement (--r). No-op when +-Inf. - inline vnl_rational& operator--() { num_ -= den_; return *this; } + inline vnl_rational & + operator--() + { + num_ -= den_; + return *this; + } //: Post-increment (r++). No-op when +-Inf. - inline vnl_rational operator++(int) {vnl_rational b=*this;num_+=den_;return b;} + inline vnl_rational + operator++(int) + { + const vnl_rational b = *this; + num_ += den_; + return b; + } //: Post-decrement (r--). No-op when +-Inf. - inline vnl_rational operator--(int) {vnl_rational b=*this;num_-=den_;return b;} + inline vnl_rational + operator--(int) + { + const vnl_rational b = *this; + num_ -= den_; + return b; + } - inline bool operator<(vnl_rational const& rhs) const { + inline bool + operator<(const vnl_rational & rhs) const + { if (den_ == rhs.denominator()) // If same denominator return num_ < rhs.numerator(); // includes the case -Inf < +Inf // note that denominator is always >= 0: else return num_ * rhs.denominator() < den_ * rhs.numerator(); } - inline bool operator>(vnl_rational const& r) const { return r < *this; } - inline bool operator<=(vnl_rational const& r) const { return !operator>(r); } - inline bool operator>=(vnl_rational const& r) const { return !operator<(r); } - inline bool operator<(int_type r) const { return num_ < den_ * r; } - inline bool operator>(int_type r) const { return num_ > den_ * r; } - inline bool operator<=(int_type r) const { return !operator>(r); } - inline bool operator>=(int_type r) const { return !operator<(r); } + inline bool + operator>(const vnl_rational & r) const + { + return r < *this; + } + inline bool + operator<=(const vnl_rational & r) const + { + return !operator>(r); + } + inline bool + operator>=(const vnl_rational & r) const + { + return !operator<(r); + } + inline bool + operator<(int_type r) const + { + return num_ < den_ * r; + } + inline bool + operator>(int_type r) const + { + return num_ > den_ * r; + } + inline bool + operator<=(int_type r) const + { + return !operator>(r); + } + inline bool + operator>=(int_type r) const + { + return !operator<(r); + } template > - inline bool operator<(const T r) const { return num_ < den_ * r; } + inline bool + operator<(const T r) const + { + return num_ < den_ * r; + } template > - inline bool operator>(const T r) const { return num_ > den_ * r; } + inline bool + operator>(const T r) const + { + return num_ > den_ * r; + } template > - inline bool operator<=(const T r) const { return !operator>(r); } + inline bool + operator<=(const T r) const + { + return !operator>(r); + } template > - inline bool operator>=(const T r) const { return !operator<(r); } + inline bool + operator>=(const T r) const + { + return !operator<(r); + } - inline bool operator<(double r) const { return num_ < den_ * r; } - inline bool operator>(double r) const { return num_ > den_ * r; } - inline bool operator<=(double r) const { return !operator>(r); } - inline bool operator>=(double r) const { return !operator<(r); } + inline bool + operator<(double r) const + { + return num_ < den_ * r; + } + inline bool + operator>(double r) const + { + return num_ > den_ * r; + } + inline bool + operator<=(double r) const + { + return !operator>(r); + } + inline bool + operator>=(double r) const + { + return !operator<(r); + } //: Converts rational value to integer by truncating towards zero. - inline int_type truncate() const { assert(den_ != 0); return num_/den_; } + inline int_type + truncate() const + { + assert(den_ != 0); + return num_ / den_; + } //: Converts rational value to integer by truncating towards negative infinity. - inline int_type floor() const { int_type t = truncate(); - return num_<0L && (num_%den_) != 0 ? t-1 : t; } + inline int_type + floor() const + { + const int_type t = truncate(); + return num_ < 0L && (num_ % den_) != 0 ? t - 1 : t; + } //: Converts rational value to integer by truncating towards positive infinity. - inline int_type ceil() const { int_type t = truncate(); - return num_>0L && (num_%den_) != 0 ? t+1 : t; } + inline int_type + ceil() const + { + const int_type t = truncate(); + return num_ > 0L && (num_ % den_) != 0 ? t + 1 : t; + } //: Rounds rational to nearest integer. - inline int_type round() const { int_type t = truncate(); - if (num_ < 0) return ((-num_)%den_) >= 0.5*den_ ? t-1 : t; - else return (num_ %den_) >= 0.5*den_ ? t+1 : t; + inline int_type + round() const + { + const int_type t = truncate(); + if (num_ < 0) + return ((-num_) % den_) >= 0.5 * den_ ? t - 1 : t; + else + return (num_ % den_) >= 0.5 * den_ ? t + 1 : t; } // Implicit conversions template > - inline operator T() const { - int_type t = truncate(); auto r = static_cast(t); + inline + operator T() const + { + const int_type t = truncate(); + auto r = static_cast(t); assert(r == t); // abort on underflow or overflow return r; } - inline operator int_type() const { return truncate(); } - inline operator float() const { return ((float)num_)/((float)den_); } - inline operator double() const { return ((double)num_)/((double)den_); } + inline + operator int_type() const + { + return truncate(); + } + inline + operator float() const + { + return ((float)num_) / ((float)den_); + } + inline + operator double() const + { + return ((double)num_) / ((double)den_); + } //: Calculate greatest common divisor of two integers. // Used to simplify rational number. - static inline int_type gcd (int_type l1, int_type l2) { - while (l2!=0) { int_type t = l2; l2 = l1 % l2; l1 = t; } - return l1<0 ? (-l1) : l1; + static inline int_type + gcd(int_type l1, int_type l2) + { + while (l2 != 0) + { + const int_type t = l2; + l2 = l1 % l2; + l1 = t; + } + return l1 < 0 ? (-l1) : l1; } - private: +private: //: Private function to normalize numerator/denominator of rational number. // If num_ and den_ are both nonzero, their gcd is made 1 and den_ made positive. // Otherwise, the nonzero den_ is set to 1 or the nonzero num_ to +1 or -1. - inline void normalize() { - if (num_ == 0) { den_ = 1; return; } // zero - if (den_ == 0) { num_ = (num_>0) ? 1 : -1; return; } // +-Inf - if (num_ != 1 && num_ != -1 && den_ != 1) { - int_type common = vnl_rational::gcd(num_, den_); - if (common != 1) { num_ /= common; den_ /= common; } + inline void + normalize() + { + if (num_ == 0) + { + den_ = 1; + return; + } // zero + if (den_ == 0) + { + num_ = (num_ > 0) ? 1 : -1; + return; + } // +-Inf + if (num_ != 1 && num_ != -1 && den_ != 1) + { + const int_type common = vnl_rational::gcd(num_, den_); + if (common != 1) + { + num_ /= common; + den_ /= common; + } } // if negative, put sign in numerator: - if (den_ < 0) { num_ *= -1; den_ *= -1; } + if (den_ < 0) + { + num_ *= -1; + den_ *= -1; + } } }; //: formatted output // \relatesalso vnl_rational -inline std::ostream& operator<<(std::ostream& s, vnl_rational const& r) +inline std::ostream & +operator<<(std::ostream & s, const vnl_rational & r) { return s << r.numerator() << '/' << r.denominator(); } //: simple input // \relatesalso vnl_rational -inline std::istream& operator>>(std::istream& s, vnl_rational& r) +inline std::istream & +operator>>(std::istream & s, vnl_rational & r) { - vnl_rational::int_type n, d; s >> n >> d; - r.set(n,d); return s; + vnl_rational::int_type n; + vnl_rational::int_type d; + s >> n >> d; + r.set(n, d); + return s; } //: Returns the sum of two rational numbers. // \relatesalso vnl_rational -inline vnl_rational operator+(vnl_rational const& r1, vnl_rational const& r2) +inline vnl_rational +operator+(const vnl_rational & r1, const vnl_rational & r2) { - vnl_rational result(r1); return result += r2; + vnl_rational result(r1); + return result += r2; } -inline vnl_rational operator+(vnl_rational const& r1, vnl_rational::int_type r2) +inline vnl_rational +operator+(const vnl_rational & r1, vnl_rational::int_type r2) { - vnl_rational result(r1); return result += r2; + vnl_rational result(r1); + return result += r2; } template > -inline vnl_rational operator+(vnl_rational const& r1, const T r2) +inline vnl_rational +operator+(const vnl_rational & r1, const T r2) { - vnl_rational result(r1); return result += vnl_rational::int_type{r2}; + vnl_rational result(r1); + return result += vnl_rational::int_type{ r2 }; } -inline vnl_rational operator+(vnl_rational::int_type r2, vnl_rational const& r1) +inline vnl_rational +operator+(vnl_rational::int_type r2, const vnl_rational & r1) { - vnl_rational result(r1); return result += r2; + vnl_rational result(r1); + return result += r2; } template > -inline vnl_rational operator+(const T r2, vnl_rational const& r1) +inline vnl_rational +operator+(const T r2, const vnl_rational & r1) { - vnl_rational result(r1); return result += vnl_rational::int_type{r2}; + vnl_rational result(r1); + return result += vnl_rational::int_type{ r2 }; } //: Returns the difference of two rational numbers. // \relatesalso vnl_rational -inline vnl_rational operator-(vnl_rational const& r1, vnl_rational const& r2) +inline vnl_rational +operator-(const vnl_rational & r1, const vnl_rational & r2) { - vnl_rational result(r1); return result -= r2; + vnl_rational result(r1); + return result -= r2; } -inline vnl_rational operator-(vnl_rational const& r1, vnl_rational::int_type r2) +inline vnl_rational +operator-(const vnl_rational & r1, vnl_rational::int_type r2) { - vnl_rational result(r1); return result -= r2; + vnl_rational result(r1); + return result -= r2; } template > -inline vnl_rational operator-(vnl_rational const& r1, const T r2) +inline vnl_rational +operator-(const vnl_rational & r1, const T r2) { - vnl_rational result(r1); return result -= vnl_rational::int_type{r2}; + vnl_rational result(r1); + return result -= vnl_rational::int_type{ r2 }; } -inline vnl_rational operator-(vnl_rational::int_type r2, vnl_rational const& r1) +inline vnl_rational +operator-(vnl_rational::int_type r2, const vnl_rational & r1) { - vnl_rational result(-r1); return result += r2; + vnl_rational result(-r1); + return result += r2; } template > -inline vnl_rational operator-(const T r2, vnl_rational const& r1) +inline vnl_rational +operator-(const T r2, const vnl_rational & r1) { - vnl_rational result(-r1); return result += vnl_rational::int_type{r2}; + vnl_rational result(-r1); + return result += vnl_rational::int_type{ r2 }; } //: Returns the product of two rational numbers. // \relatesalso vnl_rational -inline vnl_rational operator*(vnl_rational const& r1, vnl_rational const& r2) +inline vnl_rational +operator*(const vnl_rational & r1, const vnl_rational & r2) { - vnl_rational result(r1); return result *= r2; + vnl_rational result(r1); + return result *= r2; } -inline vnl_rational operator*(vnl_rational const& r1, vnl_rational::int_type r2) +inline vnl_rational +operator*(const vnl_rational & r1, vnl_rational::int_type r2) { - vnl_rational result(r1); return result *= r2; + vnl_rational result(r1); + return result *= r2; } template > -inline vnl_rational operator*(vnl_rational const& r1, const T r2) +inline vnl_rational +operator*(const vnl_rational & r1, const T r2) { - vnl_rational result(r1); return result *= vnl_rational::int_type{r2}; + vnl_rational result(r1); + return result *= vnl_rational::int_type{ r2 }; } -inline vnl_rational operator*(vnl_rational::int_type r2, vnl_rational const& r1) +inline vnl_rational +operator*(vnl_rational::int_type r2, const vnl_rational & r1) { - vnl_rational result(r1); return result *= r2; + vnl_rational result(r1); + return result *= r2; } template > -inline vnl_rational operator*(const T r2, vnl_rational const& r1) +inline vnl_rational +operator*(const T r2, const vnl_rational & r1) { - vnl_rational result(r1); return result *= vnl_rational::int_type{r2}; + vnl_rational result(r1); + return result *= vnl_rational::int_type{ r2 }; } //: Returns the quotient of two rational numbers. // \relatesalso vnl_rational -inline vnl_rational operator/(vnl_rational const& r1, vnl_rational const& r2) +inline vnl_rational +operator/(const vnl_rational & r1, const vnl_rational & r2) { - vnl_rational result(r1); return result /= r2; + vnl_rational result(r1); + return result /= r2; } -inline vnl_rational operator/(vnl_rational const& r1, vnl_rational::int_type r2) +inline vnl_rational +operator/(const vnl_rational & r1, vnl_rational::int_type r2) { - vnl_rational result(r1); return result /= r2; + vnl_rational result(r1); + return result /= r2; } template > -inline vnl_rational operator/(vnl_rational const& r1, const T r2) +inline vnl_rational +operator/(const vnl_rational & r1, const T r2) { - vnl_rational result(r1); return result /= vnl_rational::int_type{r2}; + vnl_rational result(r1); + return result /= vnl_rational::int_type{ r2 }; } -inline vnl_rational operator/(vnl_rational::int_type r1, vnl_rational const& r2) +inline vnl_rational +operator/(vnl_rational::int_type r1, const vnl_rational & r2) { - vnl_rational result(r1); return result /= r2; + vnl_rational result(r1); + return result /= r2; } template > -inline vnl_rational operator/(const T r1, vnl_rational const& r2) +inline vnl_rational +operator/(const T r1, const vnl_rational & r2) { - vnl_rational result(vnl_rational::int_type{r1}); return result /= r2; + vnl_rational result(vnl_rational::int_type{ r1 }); + return result /= r2; } //: Returns the remainder of r1 divided by r2. // \relatesalso vnl_rational -inline vnl_rational operator%(vnl_rational const& r1, vnl_rational const& r2) +inline vnl_rational +operator%(const vnl_rational & r1, const vnl_rational & r2) { - vnl_rational result(r1); return result %= r2; + vnl_rational result(r1); + return result %= r2; } -inline vnl_rational operator%(vnl_rational const& r1, vnl_rational::int_type r2) +inline vnl_rational +operator%(const vnl_rational & r1, vnl_rational::int_type r2) { - vnl_rational result(r1); return result %= r2; + vnl_rational result(r1); + return result %= r2; } template > -inline vnl_rational operator%(vnl_rational const& r1, const T r2) +inline vnl_rational +operator%(const vnl_rational & r1, const T r2) { - vnl_rational result(r1); return result %= vnl_rational::int_type{r2}; + vnl_rational result(r1); + return result %= vnl_rational::int_type{ r2 }; } -inline vnl_rational operator%(vnl_rational::int_type r1, vnl_rational const& r2) +inline vnl_rational +operator%(vnl_rational::int_type r1, const vnl_rational & r2) { - vnl_rational result(r1); return result %= r2; + vnl_rational result(r1); + return result %= r2; } template > -inline vnl_rational operator%(const T r1, vnl_rational const& r2) +inline vnl_rational +operator%(const T r1, const vnl_rational & r2) { - vnl_rational result(vnl_rational::int_type{r1}); return result %= r2; + vnl_rational result(vnl_rational::int_type{ r1 }); + return result %= r2; } template > -inline bool operator==(const T r1, vnl_rational const& r2) { return r2.operator==(r1); } -inline bool operator==(vnl_rational::int_type r1, vnl_rational const& r2) { return r2==r1; } +inline bool +operator==(const T r1, const vnl_rational & r2) +{ + return r2.operator==(r1); +} +inline bool +operator==(vnl_rational::int_type r1, const vnl_rational & r2) +{ + return r2 == r1; +} template > -inline bool operator!=(const T r1, vnl_rational const& r2) { return r2 != r1; } -inline bool operator!=(vnl_rational::int_type r1, vnl_rational const& r2) { return r2!=r1; } +inline bool +operator!=(const T r1, const vnl_rational & r2) +{ + return r2 != r1; +} +inline bool +operator!=(vnl_rational::int_type r1, const vnl_rational & r2) +{ + return r2 != r1; +} template > -inline bool operator< (const T r1, vnl_rational const& r2) { return r2 > r1; } -inline bool operator< (vnl_rational::int_type r1, vnl_rational const& r2) { return r2> r1; } +inline bool +operator<(const T r1, const vnl_rational & r2) +{ + return r2 > r1; +} +inline bool +operator<(vnl_rational::int_type r1, const vnl_rational & r2) +{ + return r2 > r1; +} template > -inline bool operator> (const T r1, vnl_rational const& r2) { return r2 < r1; } -inline bool operator> (vnl_rational::int_type r1, vnl_rational const& r2) { return r2< r1; } +inline bool +operator>(const T r1, const vnl_rational & r2) +{ + return r2 < r1; +} +inline bool +operator>(vnl_rational::int_type r1, const vnl_rational & r2) +{ + return r2 < r1; +} template > -inline bool operator<=(const T r1, vnl_rational const& r2) { return r2>=r1; } -inline bool operator<=(vnl_rational::int_type r1, vnl_rational const& r2) { return r2>=r1; } +inline bool +operator<=(const T r1, const vnl_rational & r2) +{ + return r2 >= r1; +} +inline bool +operator<=(vnl_rational::int_type r1, const vnl_rational & r2) +{ + return r2 >= r1; +} template > -inline bool operator>=(const T r1, vnl_rational const& r2) { return r2 <= r1; } -inline bool operator>=(vnl_rational::int_type r1, vnl_rational const& r2) { return r2<=r1; } +inline bool +operator>=(const T r1, const vnl_rational & r2) +{ + return r2 <= r1; +} +inline bool +operator>=(vnl_rational::int_type r1, const vnl_rational & r2) +{ + return r2 <= r1; +} -inline vnl_rational::int_type truncate(vnl_rational const& r) { return r.truncate(); } -inline vnl_rational::int_type floor(vnl_rational const& r) { return r.floor(); } -inline vnl_rational::int_type ceil(vnl_rational const& r) { return r.ceil(); } -inline vnl_rational::int_type round(vnl_rational const& r) { return r.round(); } +inline vnl_rational::int_type +truncate(const vnl_rational & r) +{ + return r.truncate(); +} +inline vnl_rational::int_type +floor(const vnl_rational & r) +{ + return r.floor(); +} +inline vnl_rational::int_type +ceil(const vnl_rational & r) +{ + return r.ceil(); +} +inline vnl_rational::int_type +round(const vnl_rational & r) +{ + return r.round(); +} namespace vnl_math { - inline vnl_rational abs(vnl_rational const& x) { return x<0L ? -x : x; } - inline vnl_rational squared_magnitude(vnl_rational const& x) { return x*x; } - inline vnl_rational sqr(vnl_rational const& x) { return x*x; } - inline bool isnan(vnl_rational const& ) {return false;} - inline bool isfinite(vnl_rational const& x) {return x.denominator() != 0L;} +inline vnl_rational +abs(const vnl_rational & x) +{ + return x < 0L ? -x : x; +} +inline vnl_rational +squared_magnitude(const vnl_rational & x) +{ + return x * x; +} +inline vnl_rational +sqr(const vnl_rational & x) +{ + return x * x; +} +inline bool +isnan(const vnl_rational &) +{ + return false; +} +inline bool +isfinite(const vnl_rational & x) +{ + return x.denominator() != 0L; } +} // namespace vnl_math #endif // vnl_rational_h_ diff --git a/core/vnl/vnl_rational_traits.cxx b/core/vnl/vnl_rational_traits.cxx index 00e570113b3..9c0967bbb09 100644 --- a/core/vnl/vnl_rational_traits.cxx +++ b/core/vnl/vnl_rational_traits.cxx @@ -20,15 +20,15 @@ const std::complex vnl_numeric_traits>: namespace vnl_math { vnl_rational -squared_magnitude(std::complex const & x) +squared_magnitude(const std::complex & x) { return x.real() * x.real() + x.imag() * x.imag(); } vnl_rational -abs(std::complex const & x) +abs(const std::complex & x) { - return vnl_rational(std::sqrt(double(x.real() * x.real() + x.imag() * x.imag()))); + return { std::sqrt(double(x.real() * x.real() + x.imag() * x.imag())) }; } } // namespace vnl_math diff --git a/core/vnl/vnl_rational_traits.h b/core/vnl/vnl_rational_traits.h index 708a0bf02c1..45be8268f2a 100644 --- a/core/vnl/vnl_rational_traits.h +++ b/core/vnl/vnl_rational_traits.h @@ -16,7 +16,7 @@ template <> class vnl_numeric_traits { - public: +public: //: Additive identity static VNL_EXPORT const vnl_rational zero; // = 0L //: Multiplicative identity @@ -39,16 +39,16 @@ class vnl_numeric_traits }; template <> -class vnl_numeric_traits : public vnl_numeric_traits -{ -}; +class vnl_numeric_traits : public vnl_numeric_traits +{}; -std::ostream& operator<<(std::ostream&, const std::complex&); +std::ostream & +operator<<(std::ostream &, const std::complex &); template <> -class vnl_numeric_traits > +class vnl_numeric_traits> { - public: +public: //: Additive identity static const std::complex zero; // = std::complex(0L,0L) //: Multiplicative identity @@ -64,14 +64,15 @@ class vnl_numeric_traits > }; template <> -class vnl_numeric_traits const> : public vnl_numeric_traits > -{ -}; +class vnl_numeric_traits> : public vnl_numeric_traits> +{}; namespace vnl_math { - vnl_rational squared_magnitude(std::complex const& ); - vnl_rational abs(std::complex const& ); -} +vnl_rational +squared_magnitude(const std::complex &); +vnl_rational +abs(const std::complex &); +} // namespace vnl_math #endif // vnl_rational_traits_h_ diff --git a/core/vnl/vnl_real.h b/core/vnl/vnl_real.h index 1afeb49c5f1..c58f4054fdd 100644 --- a/core/vnl/vnl_real.h +++ b/core/vnl/vnl_real.h @@ -24,9 +24,9 @@ #include "vnl/vnl_export.h" //: Return array R of real parts of complex array C. -template VNL_EXPORT -void -vnl_real(std::complex const* C, T* R, unsigned int n); +template +VNL_EXPORT void +vnl_real(const std::complex * C, T * R, unsigned int n); // - vnl_vector // - vnl_vector_fixed @@ -38,19 +38,19 @@ vnl_real(std::complex const* C, T* R, unsigned int n); //: Vector of real parts of vnl_vector >. // \relatesalso vnl_vector -template VNL_EXPORT -vnl_vector -vnl_real(vnl_vector > const& C); +template +VNL_EXPORT vnl_vector +vnl_real(const vnl_vector> & C); //: Vector of real parts of vnl_vector_fixed, N >. // \relatesalso vnl_vector_fixed template -vnl_vector_fixed -vnl_real(vnl_vector_fixed, N > const& C) +vnl_vector_fixed +vnl_real(const vnl_vector_fixed, N> & C) { - vnl_vector_fixed R; - typename vnl_vector_fixed,N >::const_iterator cIt = C.begin(); - typename vnl_vector_fixed::iterator rIt = R.begin(); + vnl_vector_fixed R; + typename vnl_vector_fixed, N>::const_iterator cIt = C.begin(); + typename vnl_vector_fixed::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::real(*cIt); return R; @@ -58,19 +58,19 @@ vnl_real(vnl_vector_fixed, N > const& C) //: Matrix of real parts of vnl_matrix >. // \relatesalso vnl_matrix -template VNL_EXPORT -vnl_matrix -vnl_real(vnl_matrix > const& C); +template +VNL_EXPORT vnl_matrix +vnl_real(const vnl_matrix> & C); //: Matrix of real parts of vnl_matrix_fixed,NRow,NCol >. // \relatesalso vnl_matrix_fixed template -vnl_matrix_fixed -vnl_real(vnl_matrix_fixed,NRow,NCol > const& C) +vnl_matrix_fixed +vnl_real(const vnl_matrix_fixed, NRow, NCol> & C) { - vnl_matrix_fixed R; - typename vnl_matrix_fixed,NRow,NCol >::const_iterator cIt = C.begin(); - typename vnl_matrix_fixed::iterator rIt = R.begin(); + vnl_matrix_fixed R; + typename vnl_matrix_fixed, NRow, NCol>::const_iterator cIt = C.begin(); + typename vnl_matrix_fixed::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::real(*cIt); return R; @@ -78,19 +78,19 @@ vnl_real(vnl_matrix_fixed,NRow,NCol > const& C) //: Matrix of real parts of vnl_diag_matrix >. // \relatesalso vnl_diag_matrix -template VNL_EXPORT -vnl_diag_matrix -vnl_real(vnl_diag_matrix > const& C); +template +VNL_EXPORT vnl_diag_matrix +vnl_real(const vnl_diag_matrix> & C); //: Matrix of real parts of vnl_diag_matrix_fixed >. // \relatesalso vnl_diag_matrix_fixed template -vnl_diag_matrix_fixed -vnl_real(vnl_diag_matrix_fixed,N > const& C) +vnl_diag_matrix_fixed +vnl_real(const vnl_diag_matrix_fixed, N> & C) { - vnl_diag_matrix_fixed R; - typename vnl_diag_matrix_fixed,N >::const_iterator cIt = C.begin(); - typename vnl_diag_matrix_fixed::iterator rIt = R.begin(); + vnl_diag_matrix_fixed R; + typename vnl_diag_matrix_fixed, N>::const_iterator cIt = C.begin(); + typename vnl_diag_matrix_fixed::iterator rIt = R.begin(); for (; cIt != C.end(); ++cIt, ++rIt) *rIt = std::real(*cIt); return R; @@ -98,8 +98,8 @@ vnl_real(vnl_diag_matrix_fixed,N > const& C) //: Matrix of real parts of vnl_sym_matrix >. // \relatesalso vnl_sym_matrix -template VNL_EXPORT -vnl_sym_matrix -vnl_real(vnl_sym_matrix > const& C); +template +VNL_EXPORT vnl_sym_matrix +vnl_real(const vnl_sym_matrix> & C); #endif // vnl_real_h_ diff --git a/core/vnl/vnl_real_npolynomial.cxx b/core/vnl/vnl_real_npolynomial.cxx index a3f5c8db0d8..eacefd423d6 100644 --- a/core/vnl/vnl_real_npolynomial.cxx +++ b/core/vnl/vnl_real_npolynomial.cxx @@ -27,13 +27,12 @@ // [1 2]; // \endverbatim -vnl_real_npolynomial::vnl_real_npolynomial(vnl_vector c, - const vnl_matrix &p) - : coeffs_{std::move(c)} - , polyn_(p) - , nvar_{p.cols()} - , nterms_{p.rows()} - , ideg_{p.max_value()} +vnl_real_npolynomial::vnl_real_npolynomial(vnl_vector c, const vnl_matrix & p) + : coeffs_{ std::move(c) } + , polyn_(p) + , nvar_{ p.cols() } + , nterms_{ p.rows() } + , ideg_{ p.max_value() } { assert(coeffs_.size() == polyn_.rows()); simplify(); @@ -184,13 +183,13 @@ vnl_real_npolynomial::operator-() const for (unsigned int i = 0; i < nterms_; ++i) coef(i) = -coeffs_(i); - vnl_matrix poly = polyn_; + const vnl_matrix poly = polyn_; return vnl_real_npolynomial(coef, poly); } vnl_real_npolynomial -vnl_real_npolynomial::operator+(vnl_real_npolynomial const & P) const +vnl_real_npolynomial::operator+(const vnl_real_npolynomial & P) const { assert(nvar_ == P.nvar_); // both polynomials must have the same variables @@ -231,7 +230,7 @@ vnl_real_npolynomial::operator+(double P) const } vnl_real_npolynomial -vnl_real_npolynomial::operator-(vnl_real_npolynomial const & P) const +vnl_real_npolynomial::operator-(const vnl_real_npolynomial & P) const { assert(nvar_ == P.nvar_); // both polynomials must have the same variables @@ -253,7 +252,8 @@ vnl_real_npolynomial::operator-(vnl_real_npolynomial const & P) const return vnl_real_npolynomial(coef, poly); } -vnl_real_npolynomial vnl_real_npolynomial::operator*(vnl_real_npolynomial const & P) const +vnl_real_npolynomial +vnl_real_npolynomial::operator*(const vnl_real_npolynomial & P) const { assert(nvar_ == P.nvar_); // both polynomials must have the same variables @@ -273,36 +273,37 @@ vnl_real_npolynomial vnl_real_npolynomial::operator*(vnl_real_npolynomial const return vnl_real_npolynomial(coef, poly); } -vnl_real_npolynomial vnl_real_npolynomial::operator*(double P) const +vnl_real_npolynomial +vnl_real_npolynomial::operator*(double P) const { vnl_vector coef(nterms_); for (unsigned int i = 0; i < nterms_; ++i) coef(i) = coeffs_(i) * P; - vnl_matrix poly = polyn_; + const vnl_matrix poly = polyn_; return vnl_real_npolynomial(coef, poly); } std::ostream & -operator<<(std::ostream & os, vnl_real_npolynomial const & P) +operator<<(std::ostream & os, const vnl_real_npolynomial & P) { return os << P.asString() << std::endl; } vnl_real_npolynomial & -vnl_real_npolynomial::operator+=(vnl_real_npolynomial const & rhs) +vnl_real_npolynomial::operator+=(const vnl_real_npolynomial & rhs) { *this = (*this) + rhs; return *this; } vnl_real_npolynomial & -vnl_real_npolynomial::operator-=(vnl_real_npolynomial const & rhs) +vnl_real_npolynomial::operator-=(const vnl_real_npolynomial & rhs) { *this = (*this) - rhs; return *this; } vnl_real_npolynomial & -vnl_real_npolynomial::operator*=(vnl_real_npolynomial const & rhs) +vnl_real_npolynomial::operator*=(const vnl_real_npolynomial & rhs) { *this = (*this) * rhs; return *this; diff --git a/core/vnl/vnl_real_npolynomial.h b/core/vnl/vnl_real_npolynomial.h index 890c2ecaf31..d94185d8eae 100644 --- a/core/vnl/vnl_real_npolynomial.h +++ b/core/vnl/vnl_real_npolynomial.h @@ -54,102 +54,165 @@ class VNL_EXPORT vnl_real_npolynomial { - private: +private: //: coefficients - vnl_vector coeffs_; + vnl_vector coeffs_; //: degrees of every term for every variable vnl_matrix polyn_; //: number of variables = # columns of polyn_ - unsigned int nvar_{0}; + unsigned int nvar_{ 0 }; //: number of terms of polynomial - unsigned int nterms_{0}; + unsigned int nterms_{ 0 }; //: max. degree of polynomial - unsigned int ideg_{0}; + unsigned int ideg_{ 0 }; friend class vnl_rnpoly_solve; - public: - +public: // Constructor----------------------------------------------------------------- - vnl_real_npolynomial() - : coeffs_(), polyn_() { - } // don't use this: only here for the STL vector class. - - //: Construct the polynomial with coefficients vector c and with exponents - //matrix p - vnl_real_npolynomial(vnl_vector c, - const vnl_matrix &p); - - // Computations-------------------------------------------------------------- - - //: Evaluate the polynomial at x. - double eval(const vnl_vector &x); - //: Evaluate the derivative of the polynomial at x with respect to the ith - //variable. - double deval(const vnl_vector &x, unsigned int i); - //: Evaluate the gradient of the polynomial at x. - vnl_vector deval(const vnl_vector &x); - //: Differentiate the polynomial with respect to the ith variable. - vnl_real_npolynomial deriv(unsigned int i); - - vnl_real_npolynomial operator-() const; // unary minus - vnl_real_npolynomial operator+(vnl_real_npolynomial const &) const; - vnl_real_npolynomial operator-(vnl_real_npolynomial const &) const; - vnl_real_npolynomial operator*(vnl_real_npolynomial const &) const; - vnl_real_npolynomial &operator+=(vnl_real_npolynomial const &rhs); - vnl_real_npolynomial &operator-=(vnl_real_npolynomial const &rhs); - vnl_real_npolynomial &operator*=(vnl_real_npolynomial const &rhs); - vnl_real_npolynomial operator+(double) const; - vnl_real_npolynomial operator-(double P) const { return operator+(-P); } - vnl_real_npolynomial operator*(double) const; - vnl_real_npolynomial &operator*=(double P) { - coeffs_ *= P; - return *this; } - vnl_real_npolynomial operator/(double P) const { return operator*(1.0/P); } - vnl_real_npolynomial& operator/=(double P) { return operator*=(1.0/P); } - friend VNL_EXPORT std::ostream& operator<<(std::ostream& , vnl_real_npolynomial const& ); + vnl_real_npolynomial() + : coeffs_() + , polyn_() + {} // don't use this: only here for the STL vector class. + + //: Construct the polynomial with coefficients vector c and with exponents + // matrix p + vnl_real_npolynomial(vnl_vector c, const vnl_matrix & p); + + // Computations-------------------------------------------------------------- + + //: Evaluate the polynomial at x. + double + eval(const vnl_vector & x); + //: Evaluate the derivative of the polynomial at x with respect to the ith + // variable. + double + deval(const vnl_vector & x, unsigned int i); + //: Evaluate the gradient of the polynomial at x. + vnl_vector + deval(const vnl_vector & x); + //: Differentiate the polynomial with respect to the ith variable. + vnl_real_npolynomial + deriv(unsigned int i); + + vnl_real_npolynomial + operator-() const; // unary minus + vnl_real_npolynomial + operator+(const vnl_real_npolynomial &) const; + vnl_real_npolynomial + operator-(const vnl_real_npolynomial &) const; + vnl_real_npolynomial + operator*(const vnl_real_npolynomial &) const; + vnl_real_npolynomial & + operator+=(const vnl_real_npolynomial & rhs); + vnl_real_npolynomial & + operator-=(const vnl_real_npolynomial & rhs); + vnl_real_npolynomial & + operator*=(const vnl_real_npolynomial & rhs); + vnl_real_npolynomial + operator+(double) const; + vnl_real_npolynomial + operator-(double P) const + { + return operator+(-P); + } + vnl_real_npolynomial + operator*(double) const; + vnl_real_npolynomial & + operator*=(double P) + { + coeffs_ *= P; + return *this; + } + vnl_real_npolynomial + operator/(double P) const + { + return operator*(1.0 / P); + } + vnl_real_npolynomial & + operator/=(double P) + { + return operator*=(1.0 / P); + } + friend VNL_EXPORT std::ostream & + operator<<(std::ostream &, const vnl_real_npolynomial &); // nb also added functions to access the coeffs_ member variable //--- Data Access------------------------------------------------------------ //: Return the degree (highest total power of all terms) of the polynomial. - unsigned int degree() const; + unsigned int + degree() const; //: Return the highest degree of the polynomial in an individual variable. - unsigned int maxdegree() const { return ideg_; } + unsigned int + maxdegree() const + { + return ideg_; + } //: Return the degrees (highest power of all terms) in each of the variables. - std::vector degrees() const; + std::vector + degrees() const; //: Access to the polynomial coefficients - double& operator [] (unsigned int i) { return coeffs_[i]; } + double & + operator[](unsigned int i) + { + return coeffs_[i]; + } //: Access to the polynomial coefficients - double operator [] (unsigned int i) const { return coeffs_[i]; } + double + operator[](unsigned int i) const + { + return coeffs_[i]; + } //: Return the vector of coefficients - const vnl_vector& coefficients() const { return coeffs_; } + const vnl_vector & + coefficients() const + { + return coeffs_; + } //: Return the vector of coefficients - vnl_vector& coefficients() { return coeffs_; } + vnl_vector & + coefficients() + { + return coeffs_; + } //: Set vector of coefficients of each product - void set(const vnl_vector & c, const vnl_matrix & p); + void + set(const vnl_vector & c, const vnl_matrix & p); //: Return the polynomial matrix // (ie specifying the variables in each product) - const vnl_matrix& polyn() const { return polyn_; } + const vnl_matrix & + polyn() const + { + return polyn_; + } //: Return the vector of coefficients - vnl_matrix& polyn() { return polyn_; } + vnl_matrix & + polyn() + { + return polyn_; + } //: Return the textual representation of this polynomial - std::string asString() const; - - private: - void simplify(); - double eval(const vnl_matrix& xn); + std::string + asString() const; + +private: + void + simplify(); + double + eval(const vnl_matrix & xn); }; -VNL_EXPORT std::ostream& operator<<(std::ostream& , vnl_real_npolynomial const& ); +VNL_EXPORT std::ostream & +operator<<(std::ostream &, const vnl_real_npolynomial &); #endif // vnl_real_npolynomial_h_ diff --git a/core/vnl/vnl_real_polynomial.cxx b/core/vnl/vnl_real_polynomial.cxx index 288d4159045..243da5d7b38 100644 --- a/core/vnl/vnl_real_polynomial.cxx +++ b/core/vnl/vnl_real_polynomial.cxx @@ -14,7 +14,7 @@ // This is replacing a member template... template T -vnl_real_polynomial_evaluate(double const * a, int n, T const & x) +vnl_real_polynomial_evaluate(const double * a, int n, const T & x) { --n; T acc = a[n]; @@ -39,10 +39,10 @@ vnl_real_polynomial_evaluate(double const * a, int n, T const & x) //: Instantiate templates before use template double vnl_real_polynomial_evaluate -SELECT(double)(double const *, int, double const &); -template std::complex vnl_real_polynomial_evaluate SELECT(std::complex)(double const *, +SELECT(double)(const double *, int, const double &); +template std::complex vnl_real_polynomial_evaluate SELECT(std::complex)(const double *, int, - std::complex const &); + const std::complex &); //: Evaluate polynomial at value x double @@ -54,7 +54,7 @@ vnl_real_polynomial::evaluate(double x) const //: Evaluate polynomial at complex value x std::complex -vnl_real_polynomial::evaluate(std::complex const & x) const +vnl_real_polynomial::evaluate(const std::complex & x) const { return vnl_real_polynomial_evaluate SELECT(std::complex)(coeffs_.data_block(), coeffs_.size(), x); } @@ -70,7 +70,7 @@ vnl_real_polynomial::devaluate(double x) const //: Evaluate derivative at complex value x. Not implemented. std::complex -vnl_real_polynomial::devaluate(std::complex const & x) const +vnl_real_polynomial::devaluate(const std::complex & x) const { return derivative().evaluate(x); } @@ -79,7 +79,7 @@ vnl_real_polynomial::devaluate(std::complex const & x) const double vnl_real_polynomial::evaluate_integral(double x) const { - int d = coeffs_.size() - 1; + const int d = coeffs_.size() - 1; const double * f = coeffs_.data_block(); double sum = 0.0; int di = 1; @@ -154,7 +154,8 @@ operator-(const vnl_real_polynomial & f1, const vnl_real_polynomial & f2) } //: Returns polynomial which is product of two polynomials f1(x)*f2(x) -vnl_real_polynomial operator*(const vnl_real_polynomial & f1, const vnl_real_polynomial & f2) +vnl_real_polynomial +operator*(const vnl_real_polynomial & f1, const vnl_real_polynomial & f2) { const unsigned int d1 = f1.degree(); const unsigned int d2 = f2.degree(); @@ -171,7 +172,7 @@ vnl_real_polynomial operator*(const vnl_real_polynomial & f1, const vnl_real_pol } //: Add rhs to this and return *this vnl_real_polynomial & -vnl_real_polynomial::operator+=(vnl_real_polynomial const & rhs) +vnl_real_polynomial::operator+=(const vnl_real_polynomial & rhs) { *this = (*this) + rhs; return *this; @@ -179,7 +180,7 @@ vnl_real_polynomial::operator+=(vnl_real_polynomial const & rhs) //: Subtract rhs from this and return *this vnl_real_polynomial & -vnl_real_polynomial::operator-=(vnl_real_polynomial const & rhs) +vnl_real_polynomial::operator-=(const vnl_real_polynomial & rhs) { *this = (*this) - rhs; return *this; @@ -187,7 +188,7 @@ vnl_real_polynomial::operator-=(vnl_real_polynomial const & rhs) //: multiply rhs with this and return *this vnl_real_polynomial & -vnl_real_polynomial::operator*=(vnl_real_polynomial const & rhs) +vnl_real_polynomial::operator*=(const vnl_real_polynomial & rhs) { *this = (*this) * rhs; return *this; @@ -198,13 +199,13 @@ vnl_real_polynomial::operator*=(vnl_real_polynomial const & rhs) double vnl_rms_difference(const vnl_real_polynomial & f1, const vnl_real_polynomial & f2, double x1, double x2) { - double dx = std::fabs(x2 - x1); + const double dx = std::fabs(x2 - x1); if (dx == 0.0) return 0; - vnl_real_polynomial df = f2 - f1; - vnl_real_polynomial df2 = df * df; - double area = std::fabs(df2.evaluate_integral(x1, x2)); + const vnl_real_polynomial df = f2 - f1; + const vnl_real_polynomial df2 = df * df; + const double area = std::fabs(df2.evaluate_integral(x1, x2)); return std::sqrt(area / dx); } @@ -212,7 +213,7 @@ vnl_rms_difference(const vnl_real_polynomial & f1, const vnl_real_polynomial & f vnl_real_polynomial vnl_real_polynomial::derivative() const { - int d = degree(); + const int d = degree(); vnl_vector cd(d); for (int i = d - 1, di = 1; i >= 0; --i, ++di) cd[i] = coeffs_[i] * di; @@ -224,7 +225,7 @@ vnl_real_polynomial::derivative() const vnl_real_polynomial vnl_real_polynomial::primitive() const { - int d = coeffs_.size(); // degree+1 + const int d = coeffs_.size(); // degree+1 vnl_vector cd(d + 1); cd[d] = 0.0; // constant term for (int i = d - 1, di = 1; i >= 0; --i, ++di) @@ -235,7 +236,7 @@ vnl_real_polynomial::primitive() const void vnl_real_polynomial::print(std::ostream & os) const { - int d = degree(); + const int d = degree(); bool first_coeff = true; // to avoid '+' in front of equation for (int i = 0; i <= d; ++i) diff --git a/core/vnl/vnl_real_polynomial.h b/core/vnl/vnl_real_polynomial.h index d1f8abb43dc..19888dc286d 100644 --- a/core/vnl/vnl_real_polynomial.h +++ b/core/vnl/vnl_real_polynomial.h @@ -25,7 +25,7 @@ #include #include "vnl/vnl_export.h" -//:Evaluation of real polynomials at real and complex points. +//: Evaluation of real polynomials at real and complex points. // vnl_real_polynomial represents a univariate polynomial with real // coefficients, stored as a vector of doubles. This allows // evaluation of the polynomial $p(x)$ at given values of $x$, @@ -39,87 +39,147 @@ // Roots may be extracted using the roots() method. class VNL_EXPORT vnl_real_polynomial { - public: +public: //: Initialize polynomial. // The polynomial is $ a[0] x^d + a[1] x^{d-1} + \cdots + a[d] = 0 $. - vnl_real_polynomial(vnl_vector const & a): coeffs_(a) { - if (a.empty()) { coeffs_.set_size(1); coeffs_(0)=0.0; } + vnl_real_polynomial(const vnl_vector & a) + : coeffs_(a) + { + if (a.empty()) + { + coeffs_.set_size(1); + coeffs_(0) = 0.0; + } } //: Initialize polynomial from C vector. // The parameter len is the number // of coefficients, one greater than the degree. - vnl_real_polynomial(double const * a, unsigned len): coeffs_(a, len) { - if (len==0) { coeffs_.set_size(1); coeffs_(0)=0.0; } + vnl_real_polynomial(const double * a, unsigned len) + : coeffs_(a, len) + { + if (len == 0) + { + coeffs_.set_size(1); + coeffs_(0) = 0.0; + } } //: Initialize polynomial from double. // Useful when adding or multiplying a polynomial and a number. - vnl_real_polynomial(double a): coeffs_(1u, a) {} + vnl_real_polynomial(double a) + : coeffs_(1u, a) + {} //: Initialize polynomial of a given degree. - vnl_real_polynomial(int d): coeffs_(static_cast(d)+1u) { assert (d>=0); } - vnl_real_polynomial(unsigned int d): coeffs_(d+1u) { } + vnl_real_polynomial(int d) + : coeffs_(static_cast(d) + 1u) + { + assert(d >= 0); + } + vnl_real_polynomial(unsigned int d) + : coeffs_(d + 1u) + {} //: comparison operator - bool operator==(vnl_real_polynomial const& p) const { return p.coefficients() == coeffs_; } + bool + operator==(const vnl_real_polynomial & p) const + { + return p.coefficients() == coeffs_; + } //: Evaluate polynomial at value x - double evaluate(double x) const; + double + evaluate(double x) const; //: Evaluate integral at x (assuming constant of integration is zero) - double evaluate_integral(double x) const; + double + evaluate_integral(double x) const; //: Evaluate integral between x1 and x2 - double evaluate_integral(double x1, double x2) const; + double + evaluate_integral(double x1, double x2) const; //: Evaluate derivative at value x - double devaluate(double x) const; + double + devaluate(double x) const; //: Evaluate polynomial at complex value x - std::complex evaluate(std::complex const& x) const; + std::complex + evaluate(const std::complex & x) const; //: Evaluate derivative at complex value x - std::complex devaluate(std::complex const& x) const; + std::complex + devaluate(const std::complex & x) const; //: Return derivative of this polynomial - vnl_real_polynomial derivative() const; + vnl_real_polynomial + derivative() const; //: Return primitive function (inverse derivative) of this polynomial // Since a primitive function is not unique, the one with constant = 0 is returned - vnl_real_polynomial primitive() const; + vnl_real_polynomial + primitive() const; //: Add rhs to this and return *this - vnl_real_polynomial& operator+=(vnl_real_polynomial const& rhs); + vnl_real_polynomial & + operator+=(const vnl_real_polynomial & rhs); //: Subtract rhs from this and return *this - vnl_real_polynomial& operator-=(vnl_real_polynomial const& rhs); + vnl_real_polynomial & + operator-=(const vnl_real_polynomial & rhs); //: Multiply rhs with this and return *this - vnl_real_polynomial& operator*=(vnl_real_polynomial const& rhs); + vnl_real_polynomial & + operator*=(const vnl_real_polynomial & rhs); // Data Access--------------------------------------------------------------- //: Return the degree (highest power of x) of the polynomial. - int degree() const { return int(coeffs_.size()) - 1; } + int + degree() const + { + return int(coeffs_.size()) - 1; + } //: Access to the polynomial coefficients - double& operator [] (int i) { return coeffs_[i]; } + double & + operator[](int i) + { + return coeffs_[i]; + } //: Access to the polynomial coefficients - double operator [] (int i) const { return coeffs_[i]; } + double + operator[](int i) const + { + return coeffs_[i]; + } //: Return the vector of coefficients - const vnl_vector& coefficients() const { return coeffs_; } + const vnl_vector & + coefficients() const + { + return coeffs_; + } //: Return the vector of coefficients - vnl_vector& coefficients() { return coeffs_; } + vnl_vector & + coefficients() + { + return coeffs_; + } - void set_coefficients(vnl_vector const& coeffs) {coeffs_ = coeffs;} + void + set_coefficients(const vnl_vector & coeffs) + { + coeffs_ = coeffs; + } //: Print this polynomial to stream - void print(std::ostream& os) const; + void + print(std::ostream & os) const; - protected: +protected: //: The coefficients of the polynomial. // coeffs_.back() is the const term. // coeffs_[n] is the coefficient of the x^(d-n) term, @@ -130,19 +190,22 @@ class VNL_EXPORT vnl_real_polynomial //: Returns polynomial which is sum of two polynomials f1(x)+f2(x) // \relatesalso vnl_real_polynomial -VNL_EXPORT vnl_real_polynomial operator+(const vnl_real_polynomial& f1, const vnl_real_polynomial& f2); +VNL_EXPORT vnl_real_polynomial +operator+(const vnl_real_polynomial & f1, const vnl_real_polynomial & f2); //: Returns polynomial which is different of two polynomials f1(x)-f2(x) // \relatesalso vnl_real_polynomial -VNL_EXPORT vnl_real_polynomial operator-(const vnl_real_polynomial& f1, const vnl_real_polynomial& f2); +VNL_EXPORT vnl_real_polynomial +operator-(const vnl_real_polynomial & f1, const vnl_real_polynomial & f2); //: Returns polynomial which is product of two polynomials f1(x)*f2(x) -VNL_EXPORT vnl_real_polynomial operator*(const vnl_real_polynomial& f1, const vnl_real_polynomial& f2); +VNL_EXPORT vnl_real_polynomial +operator*(const vnl_real_polynomial & f1, const vnl_real_polynomial & f2); //: Returns RMS difference between f1 and f2 over range [x1,x2] // $\frac1{\sqrt{|x_2-x_1|}}\,\sqrt{\int_{x_1}^{x_2}\left(f_1(x)-f_2(x)\right)^2\,dx}$ // \relatesalso vnl_real_polynomial -VNL_EXPORT double vnl_rms_difference(const vnl_real_polynomial& f1, const vnl_real_polynomial& f2, - double x1, double x2); +VNL_EXPORT double +vnl_rms_difference(const vnl_real_polynomial & f1, const vnl_real_polynomial & f2, double x1, double x2); #endif // vnl_real_polynomial_h_ diff --git a/core/vnl/vnl_rotation_matrix.cxx b/core/vnl/vnl_rotation_matrix.cxx index 6d452a56403..d92da2e81ff 100644 --- a/core/vnl/vnl_rotation_matrix.cxx +++ b/core/vnl/vnl_rotation_matrix.cxx @@ -3,7 +3,7 @@ #include "vnl_rotation_matrix.h" bool -vnl_rotation_matrix(double const x[3], double ** R) +vnl_rotation_matrix(const double x[3], double ** R) { // start with an identity matrix. for (unsigned i = 0; i < 3; ++i) @@ -12,7 +12,7 @@ vnl_rotation_matrix(double const x[3], double ** R) // normalize x to a unit vector u, of norm 'angle'. double u[3] = { x[0], x[1], x[2] }; - double angle = std::sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]); + const double angle = std::sqrt(u[0] * u[0] + u[1] * u[1] + u[2] * u[2]); if (angle == 0) return true; u[0] /= angle; @@ -20,13 +20,13 @@ vnl_rotation_matrix(double const x[3], double ** R) u[2] /= angle; // add (cos(angle)-1)*(1 - u u'). - double cos_angle = std::cos(angle); + const double cos_angle = std::cos(angle); for (unsigned i = 0; i < 3; ++i) for (unsigned j = 0; j < 3; ++j) R[i][j] += (cos_angle - 1) * ((i == j ? 1 : 0) - u[i] * u[j]); // add sin(angle) * [u] - double sin_angle = std::sin(angle); + const double sin_angle = std::sin(angle); /* */ R[0][1] -= sin_angle * u[2]; R[0][2] += sin_angle * u[1]; R[1][0] += sin_angle * u[2]; /* */ @@ -38,14 +38,14 @@ vnl_rotation_matrix(double const x[3], double ** R) } bool -vnl_rotation_matrix(double const axis[3], double R[3][3]) +vnl_rotation_matrix(const double axis[3], double R[3][3]) { double * R_[3] = { R[0], R[1], R[2] }; return vnl_rotation_matrix(axis, R_); } bool -vnl_rotation_matrix(double const axis[3], double * R0, double * R1, double * R2) +vnl_rotation_matrix(const double axis[3], double * R0, double * R1, double * R2) { double * R[3] = { R0, R1, R2 }; return vnl_rotation_matrix(axis, R); @@ -61,7 +61,7 @@ vnl_rotation_matrix(vnl_vector_fixed const & axis, vnl_matrix_fixed -vnl_rotation_matrix(vnl_vector_fixed const & axis) +vnl_rotation_matrix(const vnl_vector_fixed & axis) { vnl_matrix_fixed R; vnl_rotation_matrix(&axis[0], R[0], R[1], R[2]); @@ -69,13 +69,13 @@ vnl_rotation_matrix(vnl_vector_fixed const & axis) } bool -vnl_rotation_matrix(vnl_vector const & axis, vnl_matrix & R) +vnl_rotation_matrix(const vnl_vector & axis, vnl_matrix & R) { return vnl_rotation_matrix(&axis[0], R.data_array()); } vnl_matrix -vnl_rotation_matrix(vnl_vector const & axis) +vnl_rotation_matrix(const vnl_vector & axis) { vnl_matrix R(3, 3); vnl_rotation_matrix(&axis[0], R.data_array()); diff --git a/core/vnl/vnl_rotation_matrix.h b/core/vnl/vnl_rotation_matrix.h index 5b06a83e510..d1132e4ca24 100644 --- a/core/vnl/vnl_rotation_matrix.h +++ b/core/vnl/vnl_rotation_matrix.h @@ -15,23 +15,34 @@ // 12-Jan-2007 Peter Vanroose - Added vnl_matrix_fixed interface // \endverbatim -template class vnl_vector; -template class vnl_matrix; -template class vnl_vector_fixed; -template class vnl_matrix_fixed; +template +class vnl_vector; +template +class vnl_matrix; +template +class vnl_vector_fixed; +template +class vnl_matrix_fixed; -VNL_EXPORT bool vnl_rotation_matrix(double const axis[3], double** R); -VNL_EXPORT bool vnl_rotation_matrix(double const axis[3], double* R0, double* R1, double* R2); -VNL_EXPORT bool vnl_rotation_matrix(double const axis[3], double R[3][3]); -VNL_EXPORT bool vnl_rotation_matrix(vnl_vector const &axis, vnl_matrix& R); -VNL_EXPORT bool vnl_rotation_matrix(vnl_vector_fixed const& axis, vnl_matrix_fixed& R); +VNL_EXPORT bool +vnl_rotation_matrix(const double axis[3], double ** R); +VNL_EXPORT bool +vnl_rotation_matrix(const double axis[3], double * R0, double * R1, double * R2); +VNL_EXPORT bool +vnl_rotation_matrix(const double axis[3], double R[3][3]); +VNL_EXPORT bool +vnl_rotation_matrix(const vnl_vector & axis, vnl_matrix & R); +VNL_EXPORT bool +vnl_rotation_matrix(const vnl_vector_fixed & axis, vnl_matrix_fixed & R); //: Returns an orthogonal 3x3 matrix which is a rotation about the axis, by an angle equal to ||axis||. // \relatesalso vnl_matrix_fixed -VNL_EXPORT vnl_matrix_fixed vnl_rotation_matrix(vnl_vector_fixed const& axis); +VNL_EXPORT vnl_matrix_fixed +vnl_rotation_matrix(const vnl_vector_fixed & axis); //: Returns an orthogonal 3x3 matrix which is a rotation about the axis, by an angle equal to ||axis||. // \relatesalso vnl_matrix -VNL_EXPORT vnl_matrix vnl_rotation_matrix(vnl_vector const& axis); +VNL_EXPORT vnl_matrix +vnl_rotation_matrix(const vnl_vector & axis); #endif // vnl_rotation_matrix_h_ diff --git a/core/vnl/vnl_sample.cxx b/core/vnl/vnl_sample.cxx index 4c61d2132a3..6a66052c0f0 100644 --- a/core/vnl/vnl_sample.cxx +++ b/core/vnl/vnl_sample.cxx @@ -21,7 +21,7 @@ vnl_sample_reseed(int seed) double vnl_sample_uniform(double a, double b) { - double u = vnl_drand48(); // uniform on [0, 1) + const double u = vnl_drand48(); // uniform on [0, 1) return (1.0 - u) * a + u * b; } @@ -34,10 +34,10 @@ vnl_sample_uniform01() void vnl_sample_normal_2(double * x, double * y) { - double u = vnl_sample_uniform(1, 0); // not (0,1): should not return 0 - double theta = vnl_sample_uniform(0, vnl_math::twopi); + const double u = vnl_sample_uniform(1, 0); // not (0,1): should not return 0 + const double theta = vnl_sample_uniform(0, vnl_math::twopi); - double r = std::sqrt(-2 * std::log(u)); + const double r = std::sqrt(-2 * std::log(u)); if (x) *x = r * std::cos(theta); diff --git a/core/vnl/vnl_sample.h b/core/vnl/vnl_sample.h index b2b2f2020cc..486f5643331 100644 --- a/core/vnl/vnl_sample.h +++ b/core/vnl/vnl_sample.h @@ -15,80 +15,94 @@ // \endverbatim //: re-seed the random number generator. -VNL_EXPORT void vnl_sample_reseed(); +VNL_EXPORT void +vnl_sample_reseed(); //: re-seed the random number generator given a seed. -VNL_EXPORT void vnl_sample_reseed(int seed); +VNL_EXPORT void +vnl_sample_reseed(int seed); //: return a random number uniformly drawn on [0, 1.0) -VNL_EXPORT double vnl_sample_uniform01(); +VNL_EXPORT double +vnl_sample_uniform01(); //: return a random number uniformly drawn on [a, b) -VNL_EXPORT double vnl_sample_uniform(double a, double b); +VNL_EXPORT double +vnl_sample_uniform(double a, double b); //: two independent samples from a standard normal distribution. -VNL_EXPORT void vnl_sample_normal_2(double *x, double *y); +VNL_EXPORT void +vnl_sample_normal_2(double * x, double * y); //: Normal distribution with given mean and standard deviation -VNL_EXPORT double vnl_sample_normal(double mean, double sigma); +VNL_EXPORT double +vnl_sample_normal(double mean, double sigma); //: Return random k, where P(X = k) = [kth term in binomial expansion of (q + (1-q))^n]. // The returned value will lie between 0 and n (but will be -1 when input is nonsense). -VNL_EXPORT int vnl_sample_binomial(int n, double q); +VNL_EXPORT int +vnl_sample_binomial(int n, double q); //: Bernoulli distribution ("coin toss"). // The returned value will be 0 (with probability q) or 1 (with probability 1-q). // For a "fair" coin toss, use q=0.5. // When q does not lie between 0 and 1, the value -1 is returned. -VNL_EXPORT int vnl_sample_bernoulli(double q); +VNL_EXPORT int +vnl_sample_bernoulli(double q); // ---------------------------------------- //: handy function to fill a range of values. template -inline void vnl_sample_uniform(I begin, I end, double a, double b) +inline void +vnl_sample_uniform(I begin, I end, double a, double b) { - for (I p=begin; p!=end; ++p) + for (I p = begin; p != end; ++p) (*p) = vnl_sample_uniform(a, b); } //: handy function to fill a range of values. template -inline void vnl_sample_normal(I begin, I end, double mean, double sigma) +inline void +vnl_sample_normal(I begin, I end, double mean, double sigma) { - for (I p=begin; p!=end; ++p) + for (I p = begin; p != end; ++p) (*p) = vnl_sample_normal(mean, sigma); } //: handy function to fill a range of values. template -inline void vnl_sample_binomial(I begin, I end, int n, double q) +inline void +vnl_sample_binomial(I begin, I end, int n, double q) { - for (I p=begin; p!=end; ++p) + for (I p = begin; p != end; ++p) (*p) = vnl_sample_binomial(n, q); } //: handy function to fill a range of values. template -inline void vnl_sample_bernoulli(I begin, I end, double q) +inline void +vnl_sample_bernoulli(I begin, I end, double q) { - for (I p=begin; p!=end; ++p) + for (I p = begin; p != end; ++p) (*p) = vnl_sample_bernoulli(q); } //: handy function to fill a range of values. template -inline void vnl_sample_uniform(I begin, I end, double a, double b, T /*dummy*/) +inline void +vnl_sample_uniform(I begin, I end, double a, double b, T /*dummy*/) { - for (I p=begin; p!=end; ++p) + for (I p = begin; p != end; ++p) (*p) = T(vnl_sample_uniform(a, b)); } //: handy function to fill a range of values. template -inline void vnl_sample_normal(I begin, I end, double mean, double sigma, T /*dummy*/) +inline void +vnl_sample_normal(I begin, I end, double mean, double sigma, T /*dummy*/) { - for (I p=begin; p!=end; ++p) + for (I p = begin; p != end; ++p) (*p) = T(vnl_sample_normal(mean, sigma)); } diff --git a/core/vnl/vnl_scalar_join_iterator.h b/core/vnl/vnl_scalar_join_iterator.h index fe973e76a87..7fd6c837e98 100644 --- a/core/vnl/vnl_scalar_join_iterator.h +++ b/core/vnl/vnl_scalar_join_iterator.h @@ -69,68 +69,88 @@ class vnl_scalar_join_iterator_indexed_pair; template class VNL_EXPORT vnl_scalar_join_iterator { - private: - - protected: +private: +protected: unsigned n1; unsigned n2; - std::list >* pI1; - std::list >* pI2; - std::list >& I1; - std::list >& I2; - typename std::list >::iterator index1; - typename std::list >::iterator index2; - - public: - + std::list> * pI1; + std::list> * pI2; + std::list> & I1; + std::list> & I2; + typename std::list>::iterator index1; + typename std::list>::iterator index2; + +public: //: Initialize this iterator to the join of relation1(:,column1) and relation2(:,column2). // The algorithm sorts an array of pointers to each row and // traversal of the iterator runs through these to produce the join. // After construction the row1() and row2() methods indicate the first pair. - vnl_scalar_join_iterator(const vnl_matrix& relation1, unsigned column1, - const vnl_matrix& relation2, unsigned column2); + vnl_scalar_join_iterator(const vnl_matrix & relation1, + unsigned column1, + const vnl_matrix & relation2, + unsigned column2); ~vnl_scalar_join_iterator(); //: Return true if all pairs have been seen. - explicit operator bool () const - { return (!done())? true : false; } + explicit + operator bool() const + { + return (!done()) ? true : false; + } //: Return false if all pairs have been seen. - bool operator!() const - { return (!done())? false : true; } + bool + operator!() const + { + return (!done()) ? false : true; + } //: Advance to the next pair. This is prefix ++. - inline vnl_scalar_join_iterator& operator ++ () { next(); return *this; } - - bool done() const; - void next(); + inline vnl_scalar_join_iterator & + operator++() + { + next(); + return *this; + } + + bool + done() const; + void + next(); //: Return the index of the current row in the first relation. - unsigned row1() const; + unsigned + row1() const; //: Return the index of the current row in the second relation. - unsigned row2() const; + unsigned + row2() const; - private: +private: // Postfix ++ is private as it would be costly to implement. - vnl_scalar_join_iterator operator++ (int); - + vnl_scalar_join_iterator + operator++(int); }; //: Helper class to hold the sorted arrays of indices. template class VNL_EXPORT vnl_scalar_join_iterator_indexed_pair { - public: - const T* object; +public: + const T * object; int original_index; vnl_scalar_join_iterator_indexed_pair() = default; - vnl_scalar_join_iterator_indexed_pair(const T* object_, int original_index_):object(object_), original_index(original_index_) {} - - bool operator == (const vnl_scalar_join_iterator_indexed_pair& that) const; - bool operator < (const vnl_scalar_join_iterator_indexed_pair& that) const; + vnl_scalar_join_iterator_indexed_pair(const T * object_, int original_index_) + : object(object_) + , original_index(original_index_) + {} + + bool + operator==(const vnl_scalar_join_iterator_indexed_pair & that) const; + bool + operator<(const vnl_scalar_join_iterator_indexed_pair & that) const; }; #endif // vnl_scalar_join_iterator_h_ diff --git a/core/vnl/vnl_scalar_join_iterator.hxx b/core/vnl/vnl_scalar_join_iterator.hxx index cc47590953e..f75be6d4d92 100644 --- a/core/vnl/vnl_scalar_join_iterator.hxx +++ b/core/vnl/vnl_scalar_join_iterator.hxx @@ -16,10 +16,10 @@ # include #endif -#define VNL_SCALAR_JOIN_ITERATOR_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_scalar_join_iterator_indexed_pair;\ -template class VNL_EXPORT vnl_scalar_join_iterator; \ -template VNL_EXPORT std::ostream& operator<<(std::ostream& s, const vnl_scalar_join_iterator_indexed_pair& p);\ +#define VNL_SCALAR_JOIN_ITERATOR_INSTANTIATE(T) \ + template class VNL_EXPORT vnl_scalar_join_iterator_indexed_pair; \ + template class VNL_EXPORT vnl_scalar_join_iterator; \ + template VNL_EXPORT std::ostream & operator<<(std::ostream & s, const vnl_scalar_join_iterator_indexed_pair & p); #include #include "vnl_matrix.h" @@ -27,36 +27,37 @@ template VNL_EXPORT std::ostream& operator<<(std::ostream& s, const vnl_scalar_j // Helper class to hold the sorted arrays of indices. template -bool vnl_scalar_join_iterator_indexed_pair::operator == - (const vnl_scalar_join_iterator_indexed_pair& that) const +bool +vnl_scalar_join_iterator_indexed_pair::operator==(const vnl_scalar_join_iterator_indexed_pair & that) const { return (*that.object) == (*object); } template -bool vnl_scalar_join_iterator_indexed_pair::operator < - (const vnl_scalar_join_iterator_indexed_pair& that) const +bool +vnl_scalar_join_iterator_indexed_pair::operator<(const vnl_scalar_join_iterator_indexed_pair & that) const { return (*object) < (*that.object); } template -std::ostream& operator<<(std::ostream& s, - const vnl_scalar_join_iterator_indexed_pair& p) +std::ostream & +operator<<(std::ostream & s, const vnl_scalar_join_iterator_indexed_pair & p) { return s << p.original_index << ' ' << *(p.object) << '\n'; } template -vnl_scalar_join_iterator::vnl_scalar_join_iterator - (const vnl_matrix& relation1, unsigned column1, - const vnl_matrix& relation2, unsigned column2): - n1(relation1.rows()), - n2(relation2.rows()), - pI1(new std::list >(n1)), - pI2(new std::list >(n2)), - I1(*pI1), - I2(*pI2) +vnl_scalar_join_iterator::vnl_scalar_join_iterator(const vnl_matrix & relation1, + unsigned column1, + const vnl_matrix & relation2, + unsigned column2) + : n1(relation1.rows()) + , n2(relation2.rows()) + , pI1(new std::list>(n1)) + , pI2(new std::list>(n2)) + , I1(*pI1) + , I2(*pI2) { // Sort on appropriate columns { @@ -75,7 +76,8 @@ vnl_scalar_join_iterator::vnl_scalar_join_iterator index2 = I2.begin(); // Loop to first - for (;;) { + for (;;) + { T star1 = *(*index1).object; T star2 = *(*index2).object; if (star1 == star2) @@ -97,18 +99,21 @@ vnl_scalar_join_iterator::~vnl_scalar_join_iterator() } template -bool vnl_scalar_join_iterator::done() const +bool +vnl_scalar_join_iterator::done() const { return (index1 == I1.end()) || (index2 == I2.end()); } //: Increment the iterator to point to the next pair of rows. template -void vnl_scalar_join_iterator::next() +void +vnl_scalar_join_iterator::next() { T obj1 = *(*index1).object; // increment i2, check if still valid/same - if (++index2 == I2.end()) return; + if (++index2 == I2.end()) + return; T nextobj2 = *(*index2).object; if (obj1 == nextobj2) @@ -119,11 +124,13 @@ void vnl_scalar_join_iterator::next() // So, objects are different (in fact, obj1 > obj2 right now), lockstep until // they match or we're done. - while (!done()) { + while (!done()) + { T obj1 = *(*index1).object; T obj2 = *(*index2).object; - if (obj1 == obj2) { + if (obj1 == obj2) + { // If they're equal, hack back along obj2's array to find the start of the // stretch of equal ones. This allows join // 1 3 3 5 @@ -141,20 +148,23 @@ void vnl_scalar_join_iterator::next() } template -unsigned vnl_scalar_join_iterator::row1() const +unsigned +vnl_scalar_join_iterator::row1() const { return (*index1).original_index; } template -unsigned vnl_scalar_join_iterator::row2() const +unsigned +vnl_scalar_join_iterator::row2() const { return (*index2).original_index; } //: Postfix ++ should not be used. Only present for instantiation purposes. template -vnl_scalar_join_iterator vnl_scalar_join_iterator::operator++(int) +vnl_scalar_join_iterator +vnl_scalar_join_iterator::operator++(int) { std::cerr << "This should not happen! postfix ++ called\n"; return *this; diff --git a/core/vnl/vnl_sparse_lst_sqr_function.cxx b/core/vnl/vnl_sparse_lst_sqr_function.cxx index 4b8a4d1b922..2f41a19d02b 100644 --- a/core/vnl/vnl_sparse_lst_sqr_function.cxx +++ b/core/vnl/vnl_sparse_lst_sqr_function.cxx @@ -148,9 +148,9 @@ vnl_sparse_lst_sqr_function::vnl_sparse_lst_sqr_function(const std::vector const & a, - vnl_vector const & b, - vnl_vector const & c, +vnl_sparse_lst_sqr_function::f(const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c, vnl_vector & e) { for (unsigned int i = 0; i < number_of_a(); ++i) @@ -158,11 +158,11 @@ vnl_sparse_lst_sqr_function::f(vnl_vector const & a, // This is semi const incorrect - there is no vnl_vector_ref_const const vnl_vector_ref ai(number_of_params_a(i), const_cast(a.data_block()) + index_a(i)); - vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); + const vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); for (auto & r_itr : row) { - unsigned int j = r_itr.second; - unsigned int k = r_itr.first; + const unsigned int j = r_itr.second; + const unsigned int k = r_itr.first; // This is semi const incorrect - there is no vnl_vector_ref_const const vnl_vector_ref bj(number_of_params_b(j), const_cast(b.data_block()) + index_b(j)); vnl_vector_ref eij(number_of_residuals(k), e.data_block() + index_e(k)); @@ -181,9 +181,9 @@ vnl_sparse_lst_sqr_function::f(vnl_vector const & a, // You do not need to overload this method unless you want to provide // a more efficient implementation for your problem. void -vnl_sparse_lst_sqr_function::jac_blocks(vnl_vector const & a, - vnl_vector const & b, - vnl_vector const & c, +vnl_sparse_lst_sqr_function::jac_blocks(const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c, std::vector> & A, std::vector> & B, std::vector> & C) @@ -193,11 +193,11 @@ vnl_sparse_lst_sqr_function::jac_blocks(vnl_vector const & a, // This is semi const incorrect - there is no vnl_vector_ref_const const vnl_vector_ref ai(number_of_params_a(i), const_cast(a.data_block()) + index_a(i)); - vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); + const vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); for (auto & r_itr : row) { - unsigned int j = r_itr.second; - unsigned int k = r_itr.first; + const unsigned int j = r_itr.second; + const unsigned int k = r_itr.first; // This is semi const incorrect - there is no vnl_vector_ref_const const vnl_vector_ref bj(number_of_params_b(j), const_cast(b.data_block()) + index_b(j)); @@ -218,9 +218,9 @@ vnl_sparse_lst_sqr_function::jac_blocks(vnl_vector const & a, // You do not need to overload this method unless you want to provide // a more efficient implementation for your problem. void -vnl_sparse_lst_sqr_function::fd_jac_blocks(vnl_vector const & a, - vnl_vector const & b, - vnl_vector const & c, +vnl_sparse_lst_sqr_function::fd_jac_blocks(const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c, std::vector> & A, std::vector> & B, std::vector> & C, @@ -231,11 +231,11 @@ vnl_sparse_lst_sqr_function::fd_jac_blocks(vnl_vector const & a, // This is semi const incorrect - there is no vnl_vector_ref_const const vnl_vector_ref ai(number_of_params_a(i), const_cast(a.data_block()) + index_a(i)); - vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); + const vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); for (auto & r_itr : row) { - unsigned int j = r_itr.second; - unsigned int k = r_itr.first; + const unsigned int j = r_itr.second; + const unsigned int k = r_itr.first; // This is semi const incorrect - there is no vnl_vector_ref_const const vnl_vector_ref bj(number_of_params_b(j), const_cast(b.data_block()) + index_b(j)); @@ -254,10 +254,10 @@ vnl_sparse_lst_sqr_function::fd_jac_blocks(vnl_vector const & a, // You do not need to overload this method unless you want to provide // a more specialized implementation for your problem. void -vnl_sparse_lst_sqr_function::compute_weights(vnl_vector const & a, - vnl_vector const & b, - vnl_vector const & c, - vnl_vector const & e, +vnl_sparse_lst_sqr_function::compute_weights(const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c, + const vnl_vector & e, vnl_vector & weights) { for (unsigned int i = 0; i < number_of_a(); ++i) @@ -265,11 +265,11 @@ vnl_sparse_lst_sqr_function::compute_weights(vnl_vector const & a, // This is semi const incorrect - there is no vnl_vector_ref_const const vnl_vector_ref ai(number_of_params_a(i), const_cast(a.data_block()) + index_a(i)); - vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); + const vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); for (auto & r_itr : row) { - unsigned int j = r_itr.second; - unsigned int k = r_itr.first; + const unsigned int j = r_itr.second; + const unsigned int k = r_itr.first; // This is semi const incorrect - there is no vnl_vector_ref_const const vnl_vector_ref bj(number_of_params_b(j), const_cast(b.data_block()) + index_b(j)); const vnl_vector_ref eij(number_of_residuals(k), const_cast(e.data_block() + index_e(k))); @@ -285,15 +285,15 @@ vnl_sparse_lst_sqr_function::compute_weights(vnl_vector const & a, // You do not need to overload this method unless you want to provide // a more specialized implementation for your problem. void -vnl_sparse_lst_sqr_function::apply_weights(vnl_vector const & weights, vnl_vector & e) +vnl_sparse_lst_sqr_function::apply_weights(const vnl_vector & weights, vnl_vector & e) { for (unsigned int i = 0; i < number_of_a(); ++i) { - vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); + const vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); for (auto & r_itr : row) { - unsigned int j = r_itr.second; - unsigned int k = r_itr.first; + const unsigned int j = r_itr.second; + const unsigned int k = r_itr.first; vnl_vector_ref eij(number_of_residuals(k), e.data_block() + index_e(k)); apply_weight_ij(i, j, weights[k], eij); } @@ -307,18 +307,18 @@ vnl_sparse_lst_sqr_function::apply_weights(vnl_vector const & weights, v // You do not need to overload this method unless you want to provide // a more specialized implementation for your problem. void -vnl_sparse_lst_sqr_function::apply_weights(vnl_vector const & weights, +vnl_sparse_lst_sqr_function::apply_weights(const vnl_vector & weights, std::vector> & A, std::vector> & B, std::vector> & C) { for (unsigned int i = 0; i < number_of_a(); ++i) { - vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); + const vnl_crs_index::sparse_vector row = residual_indices_.sparse_row(i); for (auto & r_itr : row) { - unsigned int j = r_itr.second; - unsigned int k = r_itr.first; + const unsigned int j = r_itr.second; + const unsigned int k = r_itr.first; apply_weight_ij(i, j, weights[k], A[k], B[k], C[k]); } } @@ -331,9 +331,9 @@ vnl_sparse_lst_sqr_function::apply_weights(vnl_vector const & weights, void vnl_sparse_lst_sqr_function::fij(int /*i*/, int /*j*/, - vnl_vector const & /*ai*/, - vnl_vector const & /*bj*/, - vnl_vector const & /*c*/, + const vnl_vector & /*ai*/, + const vnl_vector & /*bj*/, + const vnl_vector & /*c*/, vnl_vector & /*f_i_j*/) { std::cerr << "Warning: fij() called but not implemented in derived class\n"; @@ -343,9 +343,9 @@ vnl_sparse_lst_sqr_function::fij(int /*i*/, void vnl_sparse_lst_sqr_function::jac_Aij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & /*ai*/, - vnl_vector const & /*bj*/, - vnl_vector const & /*c*/, + const vnl_vector & /*ai*/, + const vnl_vector & /*bj*/, + const vnl_vector & /*c*/, vnl_matrix & /*Aij*/) { std::cerr << "Warning: jac_Aij() called but not implemented in derived class\n"; @@ -355,9 +355,9 @@ vnl_sparse_lst_sqr_function::jac_Aij(unsigned int /*i*/, void vnl_sparse_lst_sqr_function::jac_Bij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & /*ai*/, - vnl_vector const & /*bj*/, - vnl_vector const & /*c*/, + const vnl_vector & /*ai*/, + const vnl_vector & /*bj*/, + const vnl_vector & /*c*/, vnl_matrix & /*Bij*/) { std::cerr << "Warning: jac_Bij() called but not implemented in derived class\n"; @@ -367,9 +367,9 @@ vnl_sparse_lst_sqr_function::jac_Bij(unsigned int /*i*/, void vnl_sparse_lst_sqr_function::jac_Cij(unsigned int /*i*/, unsigned int /*j*/, - vnl_vector const & /*ai*/, - vnl_vector const & /*bj*/, - vnl_vector const & /*c*/, + const vnl_vector & /*ai*/, + const vnl_vector & /*bj*/, + const vnl_vector & /*c*/, vnl_matrix & /*Cij*/) { if (num_params_c_ > 0) @@ -380,9 +380,9 @@ vnl_sparse_lst_sqr_function::jac_Cij(unsigned int /*i*/, void vnl_sparse_lst_sqr_function::fd_jac_Aij(int i, int j, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & c, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, vnl_matrix & Aij, double stepsize) { @@ -400,14 +400,14 @@ vnl_sparse_lst_sqr_function::fd_jac_Aij(int i, for (unsigned int ii = 0; ii < dim; ++ii) { // calculate f just to the right of ai[ii] - double tplus = tai[ii] = ai[ii] + stepsize; + const double tplus = tai[ii] = ai[ii] + stepsize; this->fij(i, j, tai, bj, c, fplus); // calculate f just to the left of ai[ii] - double tminus = tai[ii] = ai[ii] - stepsize; + const double tminus = tai[ii] = ai[ii] - stepsize; this->fij(i, j, tai, bj, c, fminus); - double h = 1.0 / (tplus - tminus); + const double h = 1.0 / (tplus - tminus); for (unsigned int jj = 0; jj < n; ++jj) Aij(jj, ii) = (fplus[jj] - fminus[jj]) * h; @@ -421,9 +421,9 @@ vnl_sparse_lst_sqr_function::fd_jac_Aij(int i, void vnl_sparse_lst_sqr_function::fd_jac_Bij(int i, int j, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & c, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, vnl_matrix & Bij, double stepsize) { @@ -441,14 +441,14 @@ vnl_sparse_lst_sqr_function::fd_jac_Bij(int i, for (unsigned int ii = 0; ii < dim; ++ii) { // calculate f just to the right of bj[ii] - double tplus = tbj[ii] = bj[ii] + stepsize; + const double tplus = tbj[ii] = bj[ii] + stepsize; this->fij(i, j, ai, tbj, c, fplus); // calculate f just to the left of bj[ii] - double tminus = tbj[ii] = bj[ii] - stepsize; + const double tminus = tbj[ii] = bj[ii] - stepsize; this->fij(i, j, ai, tbj, c, fminus); - double h = 1.0 / (tplus - tminus); + const double h = 1.0 / (tplus - tminus); for (unsigned int jj = 0; jj < n; ++jj) Bij(jj, ii) = (fplus[jj] - fminus[jj]) * h; @@ -462,9 +462,9 @@ vnl_sparse_lst_sqr_function::fd_jac_Bij(int i, void vnl_sparse_lst_sqr_function::fd_jac_Cij(int i, int j, - vnl_vector const & ai, - vnl_vector const & bj, - vnl_vector const & c, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, vnl_matrix & Cij, double stepsize) { @@ -486,14 +486,14 @@ vnl_sparse_lst_sqr_function::fd_jac_Cij(int i, for (unsigned int ii = 0; ii < dim; ++ii) { // calculate f just to the right of c[ii] - double tplus = tc[ii] = c[ii] + stepsize; + const double tplus = tc[ii] = c[ii] + stepsize; this->fij(i, j, ai, bj, tc, fplus); // calculate f just to the left of c[ii] - double tminus = tc[ii] = c[ii] - stepsize; + const double tminus = tc[ii] = c[ii] - stepsize; this->fij(i, j, ai, bj, tc, fminus); - double h = 1.0 / (tplus - tminus); + const double h = 1.0 / (tplus - tminus); for (unsigned int jj = 0; jj < n; ++jj) Cij(jj, ii) = (fplus[jj] - fminus[jj]) * h; @@ -509,10 +509,10 @@ vnl_sparse_lst_sqr_function::fd_jac_Cij(int i, void vnl_sparse_lst_sqr_function::compute_weight_ij(int /*i*/, int /*j*/, - vnl_vector const & /*ai*/, - vnl_vector const & /*bj*/, - vnl_vector const & /*c*/, - vnl_vector const & /*fij*/, + const vnl_vector & /*ai*/, + const vnl_vector & /*bj*/, + const vnl_vector & /*c*/, + const vnl_vector & /*fij*/, double & weight) { weight = 1.0; @@ -522,7 +522,7 @@ vnl_sparse_lst_sqr_function::compute_weight_ij(int /*i*/, //: If using weighted least squares, apply the weight to fij. // The default implementation multiplies fij by weight. void -vnl_sparse_lst_sqr_function::apply_weight_ij(int /*i*/, int /*j*/, double const & weight, vnl_vector & fij) +vnl_sparse_lst_sqr_function::apply_weight_ij(int /*i*/, int /*j*/, const double & weight, vnl_vector & fij) { fij *= weight; } @@ -533,7 +533,7 @@ vnl_sparse_lst_sqr_function::apply_weight_ij(int /*i*/, int /*j*/, double const void vnl_sparse_lst_sqr_function::apply_weight_ij(int /*i*/, int /*j*/, - double const & weight, + const double & weight, vnl_matrix & Aij, vnl_matrix & Bij, vnl_matrix & Cij) @@ -546,10 +546,10 @@ vnl_sparse_lst_sqr_function::apply_weight_ij(int /*i*/, void vnl_sparse_lst_sqr_function::trace(int /* iteration */, - vnl_vector const & /*a*/, - vnl_vector const & /*b*/, - vnl_vector const & /*c*/, - vnl_vector const & /*e*/) + const vnl_vector & /*a*/, + const vnl_vector & /*b*/, + const vnl_vector & /*c*/, + const vnl_vector & /*e*/) { // This default implementation is empty; overloaded in derived class. } diff --git a/core/vnl/vnl_sparse_lst_sqr_function.h b/core/vnl/vnl_sparse_lst_sqr_function.h index 3fe03e75a4a..5b827789f8f 100644 --- a/core/vnl/vnl_sparse_lst_sqr_function.h +++ b/core/vnl/vnl_sparse_lst_sqr_function.h @@ -44,12 +44,14 @@ // parameters that are assumed to be fixed over all images. class VNL_EXPORT vnl_sparse_lst_sqr_function { - public: - enum UseGradient { +public: + enum UseGradient + { no_gradient, use_gradient }; - enum UseWeights { + enum UseWeights + { no_weights, use_weights }; @@ -84,7 +86,7 @@ class VNL_EXPORT vnl_sparse_lst_sqr_function unsigned int num_b, unsigned int num_params_per_b, unsigned int num_params_c, - const std::vector >& xmask, + const std::vector> & xmask, unsigned int num_residuals_per_e, UseGradient g = use_gradient, UseWeights w = no_weights); @@ -99,19 +101,27 @@ class VNL_EXPORT vnl_sparse_lst_sqr_function // xmask must be a_sizes.size() by b_sizes.size() and contain e_sizes.size() true entries // The optional argument should be no_gradient if the gradf function has not // been implemented. Default is use_gradient. - vnl_sparse_lst_sqr_function(const std::vector& a_sizes, - const std::vector& b_sizes, + vnl_sparse_lst_sqr_function(const std::vector & a_sizes, + const std::vector & b_sizes, unsigned int num_params_c, - const std::vector& e_sizes, - const std::vector >& xmask, + const std::vector & e_sizes, + const std::vector> & xmask, UseGradient g = use_gradient, UseWeights w = no_weights); virtual ~vnl_sparse_lst_sqr_function() = default; // the virtuals may call this to signal a failure. - void throw_failure() { failure = true; } - void clear_failure() { failure = false; } + void + throw_failure() + { + failure = true; + } + void + clear_failure() + { + failure = false; + } //: Compute all residuals. // Given the parameter vectors a, b, and c, compute the vector of residuals f. @@ -119,10 +129,8 @@ class VNL_EXPORT vnl_sparse_lst_sqr_function // The default implementation computes f by calling fij for each valid // pair of i and j. You do not need to overload this method unless you // want to provide a more efficient implementation for your problem. - virtual void f(vnl_vector const& a, - vnl_vector const& b, - vnl_vector const& c, - vnl_vector& f); + virtual void + f(const vnl_vector & a, const vnl_vector & b, const vnl_vector & c, vnl_vector & f); //: Compute the sparse Jacobian in block form. // Given the parameter vectors a, b, and c, compute the set of block @@ -132,12 +140,13 @@ class VNL_EXPORT vnl_sparse_lst_sqr_function // jac_Aij, jac_Bij, and jac_Cij for each valid pair of i and j. // You do not need to overload this method unless you want to provide // a more efficient implementation for your problem. - virtual void jac_blocks(vnl_vector const& a, - vnl_vector const& b, - vnl_vector const& c, - std::vector >& A, - std::vector >& B, - std::vector >& C); + virtual void + jac_blocks(const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c, + std::vector> & A, + std::vector> & B, + std::vector> & C); //: Compute the sparse Jacobian in block form using a finite difference approximation. // Given the parameter vectors a, b and c, compute the set of block Jacobians @@ -147,13 +156,14 @@ class VNL_EXPORT vnl_sparse_lst_sqr_function // jac_Aij, jac_Bij, and jac_Cij for each valid pair of i and j. // You do not need to overload this method unless you want to provide // a more efficient implementation for your problem. - virtual void fd_jac_blocks(vnl_vector const& a, - vnl_vector const& b, - vnl_vector const& c, - std::vector >& A, - std::vector >& B, - std::vector >& C, - double stepsize); + virtual void + fd_jac_blocks(const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c, + std::vector> & A, + std::vector> & B, + std::vector> & C, + double stepsize); //: If using weighted least squares, compute the weights for each i and j. // Return the weights in \a weights. @@ -161,164 +171,239 @@ class VNL_EXPORT vnl_sparse_lst_sqr_function // compute_weight_ij for each valid pair of i and j. // You do not need to overload this method unless you want to provide // a more specialized implementation for your problem. - virtual void compute_weights(vnl_vector const& a, - vnl_vector const& b, - vnl_vector const& c, - vnl_vector const& f, - vnl_vector& weights); + virtual void + compute_weights(const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c, + const vnl_vector & f, + vnl_vector & weights); //: If using weighted least squares, apply the weights to residuals f. // The default implementation applies \a weights by calling // apply_weight_ij for each valid pair of i and j. // You do not need to overload this method unless you want to provide // a more specialized implementation for your problem. - virtual void apply_weights(vnl_vector const& weights, - vnl_vector& f); + virtual void + apply_weights(const vnl_vector & weights, vnl_vector & f); //: If using weighted least squares, apply the weights to residuals A, B, C. // The default implementation applies \a weights by calling // apply_weight_ij for each valid pair of i and j. // You do not need to overload this method unless you want to provide // a more specialized implementation for your problem. - virtual void apply_weights(vnl_vector const& weights, - std::vector >& A, - std::vector >& B, - std::vector >& C); + virtual void + apply_weights(const vnl_vector & weights, + std::vector> & A, + std::vector> & B, + std::vector> & C); //: Compute the residuals from the ith component of a, the jth component of b. // Given the parameter vectors ai, bj, and c, compute the vector of residuals fij. // fij has been sized appropriately before the call. - virtual void fij(int i, int j, - vnl_vector const& ai, - vnl_vector const& bj, - vnl_vector const& c, - vnl_vector& fij); + virtual void + fij(int i, + int j, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, + vnl_vector & fij); //: Calculate the Jacobian A_ij, given the parameter vectors a_i, b_j, and c. - virtual void jac_Aij(unsigned int i, unsigned int j, - vnl_vector const& ai, - vnl_vector const& bj, - vnl_vector const& c, - vnl_matrix& Aij); + virtual void + jac_Aij(unsigned int i, + unsigned int j, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, + vnl_matrix & Aij); //: Calculate the Jacobian B_ij, given the parameter vectors a_i, b_j, and c. - virtual void jac_Bij(unsigned int i, unsigned int j, - vnl_vector const& ai, - vnl_vector const& bj, - vnl_vector const& c, - vnl_matrix& Bij); + virtual void + jac_Bij(unsigned int i, + unsigned int j, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, + vnl_matrix & Bij); //: Calculate the Jacobian C_ij, given the parameter vectors a_i, b_j, and c. - virtual void jac_Cij(unsigned int i, unsigned int j, - vnl_vector const& ai, - vnl_vector const& bj, - vnl_vector const& c, - vnl_matrix& Cij); + virtual void + jac_Cij(unsigned int i, + unsigned int j, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, + vnl_matrix & Cij); //: Use this to compute a finite-difference Jacobian A_ij - void fd_jac_Aij(int i, int j, - vnl_vector const& ai, - vnl_vector const& bj, - vnl_vector const& c, - vnl_matrix& Aij, - double stepsize); + void + fd_jac_Aij(int i, + int j, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, + vnl_matrix & Aij, + double stepsize); //: Use this to compute a finite-difference Jacobian B_ij - void fd_jac_Bij(int i, int j, - vnl_vector const& ai, - vnl_vector const& bj, - vnl_vector const& c, - vnl_matrix& Bij, - double stepsize); + void + fd_jac_Bij(int i, + int j, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, + vnl_matrix & Bij, + double stepsize); //: Use this to compute a finite-difference Jacobian C_ij - void fd_jac_Cij(int i, int j, - vnl_vector const& ai, - vnl_vector const& bj, - vnl_vector const& c, - vnl_matrix& Cij, - double stepsize); + void + fd_jac_Cij(int i, + int j, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, + vnl_matrix & Cij, + double stepsize); //: If using weighted least squares, compute the weight. // Return the weight in \a weight. // The default implementation sets weight = 1 - virtual void compute_weight_ij(int i, int j, - vnl_vector const& ai, - vnl_vector const& bj, - vnl_vector const& c, - vnl_vector const& fij, - double& weight); + virtual void + compute_weight_ij(int i, + int j, + const vnl_vector & ai, + const vnl_vector & bj, + const vnl_vector & c, + const vnl_vector & fij, + double & weight); //: If using weighted least squares, apply the weight to fij. // The default implementation multiplies fij by weight. - virtual void apply_weight_ij(int i, int j, - double const& weight, - vnl_vector& fij); + virtual void + apply_weight_ij(int i, int j, const double & weight, vnl_vector & fij); //: If using weighted least squares, apply the weight to Aij, Bij, Cij. // The default implementation multiplies each matrix by weight. - virtual void apply_weight_ij(int i, int j, - double const& weight, - vnl_matrix& Aij, - vnl_matrix& Bij, - vnl_matrix& Cij); + virtual void + apply_weight_ij(int i, + int j, + const double & weight, + vnl_matrix & Aij, + vnl_matrix & Bij, + vnl_matrix & Cij); //: Called after each LM iteration to print debugging etc. - virtual void trace(int iteration, - vnl_vector const& a, - vnl_vector const& b, - vnl_vector const& c, - vnl_vector const& e); + virtual void + trace(int iteration, + const vnl_vector & a, + const vnl_vector & b, + const vnl_vector & c, + const vnl_vector & e); //: Return the number of parameters of a_j - unsigned int number_of_params_a(int i) const { return indices_a_[i+1]-indices_a_[i]; } + unsigned int + number_of_params_a(int i) const + { + return indices_a_[i + 1] - indices_a_[i]; + } //: Return the number of parameters of b_i - unsigned int number_of_params_b(int j) const { return indices_b_[j+1]-indices_b_[j]; } + unsigned int + number_of_params_b(int j) const + { + return indices_b_[j + 1] - indices_b_[j]; + } //: Return the number of parameters of c - unsigned int number_of_params_c() const { return num_params_c_; } + unsigned int + number_of_params_c() const + { + return num_params_c_; + } //: Return the number of residuals in the kth residual vector. - unsigned int number_of_residuals(int k) const { return indices_e_[k+1]-indices_e_[k]; } + unsigned int + number_of_residuals(int k) const + { + return indices_e_[k + 1] - indices_e_[k]; + } //: Return the number of residuals for x_ij. - unsigned int number_of_residuals(int i, int j) const + unsigned int + number_of_residuals(int i, int j) const { - int k = residual_indices_(i,j); - if (k<0) return 0; - else return number_of_residuals(k); + const int k = residual_indices_(i, j); + if (k < 0) + return 0; + else + return number_of_residuals(k); } //: return the index of aj in a - unsigned int index_a(int i) const { return indices_a_[i]; } + unsigned int + index_a(int i) const + { + return indices_a_[i]; + } //: return the index of bj in b - unsigned int index_b(int j) const { return indices_b_[j]; } + unsigned int + index_b(int j) const + { + return indices_b_[j]; + } //: return the index of ek in e - unsigned int index_e(int k) const { return indices_e_[k]; } + unsigned int + index_e(int k) const + { + return indices_e_[k]; + } //: Return the number of subsets in \p a - unsigned int number_of_a() const { return (unsigned int)(indices_a_.size()-1); } + unsigned int + number_of_a() const + { + return (unsigned int)(indices_a_.size() - 1); + } //: Return the number of subsets in \p b - unsigned int number_of_b() const { return (unsigned int)(indices_b_.size()-1); } + unsigned int + number_of_b() const + { + return (unsigned int)(indices_b_.size() - 1); + } //: Return the number of residual vectors - unsigned int number_of_e() const { return (unsigned int)(indices_e_.size()-1); } + unsigned int + number_of_e() const + { + return (unsigned int)(indices_e_.size() - 1); + } //: Return true if the derived class has indicated that gradf has been implemented - bool has_gradient() const { return use_gradient_; } + bool + has_gradient() const + { + return use_gradient_; + } //: Return true if the derived class has indicated that // \a apply_weights or \a apply_weight_ij have been implemented - bool has_weights() const { return use_weights_; } + bool + has_weights() const + { + return use_weights_; + } //: Return a const reference to the residual indexer - const vnl_crs_index& residual_indices() const { return residual_indices_; } + const vnl_crs_index & + residual_indices() const + { + return residual_indices_; + } - protected: +protected: vnl_crs_index residual_indices_; std::vector indices_a_; std::vector indices_b_; @@ -328,8 +413,9 @@ class VNL_EXPORT vnl_sparse_lst_sqr_function bool use_gradient_; bool use_weights_; - private: - void dim_warning(unsigned int n_unknowns, unsigned int n_residuals); +private: + void + dim_warning(unsigned int n_unknowns, unsigned int n_residuals); }; #endif // vnl_sparse_lst_sqr_function_h_ diff --git a/core/vnl/vnl_sparse_matrix.h b/core/vnl/vnl_sparse_matrix.h index e94c492aa83..7e86438e5cf 100644 --- a/core/vnl/vnl_sparse_matrix.h +++ b/core/vnl/vnl_sparse_matrix.h @@ -73,31 +73,42 @@ template class VNL_EXPORT vnl_sparse_matrix_pair { - public: - unsigned int first{0}; - T second; - - //: Constructs a pair with null values - vnl_sparse_matrix_pair() : second(T(0)) {} - - //: Constructs a pair with position a and value b - vnl_sparse_matrix_pair(unsigned int const &a, T const &b) - : first(a), second(b) {} - - vnl_sparse_matrix_pair(const vnl_sparse_matrix_pair &o) - : first(o.first), second(o.second) {} - - vnl_sparse_matrix_pair &operator=(vnl_sparse_matrix_pair const &o) { - if (&o != this) { - first = o.first; - second = o.second; - } - return *this; +public: + unsigned int first{ 0 }; + T second; + + //: Constructs a pair with null values + vnl_sparse_matrix_pair() + : second(T(0)) + {} + + //: Constructs a pair with position a and value b + vnl_sparse_matrix_pair(const unsigned int & a, const T & b) + : first(a) + , second(b) + {} + + vnl_sparse_matrix_pair(const vnl_sparse_matrix_pair & o) + : first(o.first) + , second(o.second) + {} + + vnl_sparse_matrix_pair & + operator=(const vnl_sparse_matrix_pair & o) + { + if (&o != this) + { + first = o.first; + second = o.second; + } + return *this; } struct less { - bool operator() (vnl_sparse_matrix_pair const& p1, vnl_sparse_matrix_pair const& p2) { + bool + operator()(const vnl_sparse_matrix_pair & p1, const vnl_sparse_matrix_pair & p2) + { return p1.first < p2.first; } }; @@ -109,10 +120,10 @@ class VNL_EXPORT vnl_sparse_matrix_pair template class VNL_EXPORT vnl_sparse_matrix { - public: +public: typedef vnl_sparse_matrix_pair pair_t; - typedef std::vector < pair_t > row; - typedef std::vector < row > vnl_sparse_matrix_elements; + typedef std::vector row; + typedef std::vector vnl_sparse_matrix_elements; //: Construct an empty matrix vnl_sparse_matrix(); @@ -121,138 +132,197 @@ class VNL_EXPORT vnl_sparse_matrix vnl_sparse_matrix(unsigned int m, unsigned int n); //: Construct an m*n Matrix and copy rhs into it. - vnl_sparse_matrix(vnl_sparse_matrix const& rhs); + vnl_sparse_matrix(const vnl_sparse_matrix & rhs); //: Copy another vnl_sparse_matrix into this. - vnl_sparse_matrix& operator=(vnl_sparse_matrix const& rhs); + vnl_sparse_matrix & + operator=(const vnl_sparse_matrix & rhs); //: Multiply this*rhs, where rhs is a vector. - void mult(vnl_vector const& rhs, vnl_vector& result) const; + void + mult(const vnl_vector & rhs, vnl_vector & result) const; //: Multiply this*p, a fortran order matrix. - void mult(unsigned int n, unsigned int m, T const* p, T* q) const; + void + mult(unsigned int n, unsigned int m, const T * p, T * q) const; //: Multiplies lhs*this, where lhs is a vector - void pre_mult(const vnl_vector& lhs, vnl_vector& result) const; + void + pre_mult(const vnl_vector & lhs, vnl_vector & result) const; //: Get a reference to an entry in the matrix. - T& operator()(unsigned int row, unsigned int column); + T & + operator()(unsigned int row, unsigned int column); //: Get the value of an entry in the matrix. - T operator()(unsigned int row, unsigned int column) const; + T + operator()(unsigned int row, unsigned int column) const; //: Get an entry in the matrix. // This is the "const" version of operator(). - T get(unsigned int row, unsigned int column) const; + T + get(unsigned int row, unsigned int column) const; //: Put (i.e., add or overwrite) an entry into the matrix. - void put(unsigned int row, unsigned int column, T value); + void + put(unsigned int row, unsigned int column, T value); //: Get diag(A_transpose * A). // Useful for forming Jacobi preconditioners for linear solvers. - void diag_AtA(vnl_vector& result) const; + void + diag_AtA(vnl_vector & result) const; //: Set a whole row at once. Much faster. Returns *this. - vnl_sparse_matrix& set_row(unsigned int r, - std::vector const& cols, - std::vector const& vals); + vnl_sparse_matrix & + set_row(unsigned int r, const std::vector & cols, const std::vector & vals); //: Return row as vector of pairs // Added to aid binary I/O - row& get_row(unsigned int r) {return elements[r];} + row & + get_row(unsigned int r) + { + return elements[r]; + } //: Laminate matrix A onto the bottom of this one - vnl_sparse_matrix& vcat(vnl_sparse_matrix const& A); + vnl_sparse_matrix & + vcat(const vnl_sparse_matrix & A); //: Get the number of rows in the matrix. - unsigned int rows() const { return rs_; } + unsigned int + rows() const + { + return rs_; + } //: Get the number of columns in the matrix. - unsigned int columns() const { return cs_; } + unsigned int + columns() const + { + return cs_; + } //: Get the number of columns in the matrix. - unsigned int cols() const { return cs_; } + unsigned int + cols() const + { + return cs_; + } //: Return whether a given row is empty - bool empty_row(unsigned int r) const { return elements[r].empty(); } + bool + empty_row(unsigned int r) const + { + return elements[r].empty(); + } //: This is occasionally useful. - T sum_row(unsigned int r); + T + sum_row(unsigned int r); //: Useful for normalizing row sums in convolution operators - vnl_sparse_matrix& scale_row(unsigned int r, T scale); + vnl_sparse_matrix & + scale_row(unsigned int r, T scale); //: Set all elements to null - void clear() { elements.clear(); } + void + clear() + { + elements.clear(); + } //: Resizes the array to have r rows and c cols -- sets elements to null - void set_size( int r, int c ); + void + set_size(int r, int c); //: Resizes the array to have r rows and c cols - void resize( int r, int c ); + void + resize(int r, int c); //: Resets the internal iterator - void reset() const; + void + reset() const; //: Moves the internal iterator to next non-zero entry in matrix. // Returns true if there is another value, false otherwise. Use // in combination with methods reset, getrow, getcolumn, and value. - bool next() const; + bool + next() const; //: Returns the row of the entry pointed to by internal iterator. - int getrow() const; + int + getrow() const; //: Returns the column of the entry pointed to by internal iterator. - int getcolumn() const; + int + getcolumn() const; //: Returns the value pointed to by the internal iterator. - T value() const; + T + value() const; //: Comparison - bool operator==(vnl_sparse_matrix const& rhs) const; + bool + operator==(const vnl_sparse_matrix & rhs) const; //: Inequality - bool operator!=(vnl_sparse_matrix const& rhs) const - { return !operator==(rhs); } + bool + operator!=(const vnl_sparse_matrix & rhs) const + { + return !operator==(rhs); + } //: Unary minus - vnl_sparse_matrix::signed_t> operator-() const; + vnl_sparse_matrix::signed_t> + operator-() const; //: addition - vnl_sparse_matrix operator+(vnl_sparse_matrix const& rhs) const; + vnl_sparse_matrix + operator+(const vnl_sparse_matrix & rhs) const; //: subtraction - vnl_sparse_matrix operator-(vnl_sparse_matrix const& rhs) const; + vnl_sparse_matrix + operator-(const vnl_sparse_matrix & rhs) const; //: multiplication - vnl_sparse_matrix operator*(vnl_sparse_matrix const& rhs) const; + vnl_sparse_matrix + operator*(const vnl_sparse_matrix & rhs) const; //: in-place addition - vnl_sparse_matrix& operator+=(vnl_sparse_matrix const& rhs); + vnl_sparse_matrix & + operator+=(const vnl_sparse_matrix & rhs); //: in-place subtraction - vnl_sparse_matrix& operator-=(vnl_sparse_matrix const& rhs); + vnl_sparse_matrix & + operator-=(const vnl_sparse_matrix & rhs); //: in-place multiplication - vnl_sparse_matrix& operator*=(vnl_sparse_matrix const& rhs); + vnl_sparse_matrix & + operator*=(const vnl_sparse_matrix & rhs); //: scalar multiplication - vnl_sparse_matrix operator*(T const& rhs) const; + vnl_sparse_matrix + operator*(const T & rhs) const; //: in-place scalar multiplication - vnl_sparse_matrix& operator*=(T const& rhs); + vnl_sparse_matrix & + operator*=(const T & rhs); //: scalar division - vnl_sparse_matrix operator/(T const& rhs) const; + vnl_sparse_matrix + operator/(const T & rhs) const; //: in-place scalar division - vnl_sparse_matrix& operator/=(T const& rhs); + vnl_sparse_matrix & + operator/=(const T & rhs); //: returns a new sparse matrix, viz. the transpose of this - vnl_sparse_matrix transpose() const; + vnl_sparse_matrix + transpose() const; //: returns a new sparse matrix, viz. the conjugate (or Hermitian) transpose of this - vnl_sparse_matrix conjugate_transpose() const; + vnl_sparse_matrix + conjugate_transpose() const; //: Sets this matrix to an identity matrix, then returns "*this". // Returning "*this" allows e.g. passing an identity matrix as argument to @@ -266,7 +336,8 @@ class VNL_EXPORT vnl_sparse_matrix // M.set_identity() += M2; // \endcode // If the matrix is not square, anyhow set main diagonal to 1, the rest to 0. - vnl_sparse_matrix& set_identity(); + vnl_sparse_matrix & + set_identity(); //: Normalizes each row so it is a unit vector, and returns "*this". // Zero rows are not modified @@ -276,7 +347,8 @@ class VNL_EXPORT vnl_sparse_matrix // \endcode // Note that there is no method normalize_columns() since its implementation // would be much more inefficient than normalize_rows()! - vnl_sparse_matrix& normalize_rows(); + vnl_sparse_matrix & + normalize_rows(); // These three methods are used to implement their operator() variants // They should ideally be protected, but for backward compatibility reasons @@ -284,17 +356,20 @@ class VNL_EXPORT vnl_sparse_matrix //: Add rhs to this. // Deprecated for direct use: please use operator "+" instead. - void add(const vnl_sparse_matrix& rhs, vnl_sparse_matrix& result) const; + void + add(const vnl_sparse_matrix & rhs, vnl_sparse_matrix & result) const; //: Subtract rhs from this. // Deprecated for direct use: please use operator "-" instead. - void subtract(const vnl_sparse_matrix& rhs, vnl_sparse_matrix& result) const; + void + subtract(const vnl_sparse_matrix & rhs, vnl_sparse_matrix & result) const; //: Multiply this*rhs, another sparse matrix. // Deprecated for direct use: please use operator "*" instead. - void mult(vnl_sparse_matrix const& rhs, vnl_sparse_matrix& result) const; + void + mult(const vnl_sparse_matrix & rhs, vnl_sparse_matrix & result) const; - protected: +protected: vnl_sparse_matrix_elements elements; unsigned int rs_, cs_; @@ -308,8 +383,9 @@ class VNL_EXPORT vnl_sparse_matrix //: // \relatesalso vnl_matrix -template -inline vnl_sparse_matrix operator*(T const& value, vnl_sparse_matrix const& m) +template +inline vnl_sparse_matrix +operator*(const T & value, const vnl_sparse_matrix & m) { return m * value; } diff --git a/core/vnl/vnl_sparse_matrix.hxx b/core/vnl/vnl_sparse_matrix.hxx index 9bb48980db2..5647af2e48f 100644 --- a/core/vnl/vnl_sparse_matrix.hxx +++ b/core/vnl/vnl_sparse_matrix.hxx @@ -17,7 +17,7 @@ #include "vnl_complex_traits.h" #ifdef DEBUG_SPARSE -# include "vnl_matrix.h" +# include "vnl_matrix.h" #endif // Implementation of vnl_sparse_matrix @@ -26,30 +26,33 @@ //: Construct an empty matrix template vnl_sparse_matrix::vnl_sparse_matrix() - : rs_(0), cs_(0) -{ -} + : rs_(0) + , cs_(0) +{} //------------------------------------------------------------ //: Construct an empty m*n matrix. There are m rows and n columns. template vnl_sparse_matrix::vnl_sparse_matrix(unsigned int m, unsigned int n) - : elements(m), rs_(m), cs_(n) -{ -} + : elements(m) + , rs_(m) + , cs_(n) +{} //------------------------------------------------------------ //: Construct an m*n Matrix and copy rhs into it. template -vnl_sparse_matrix::vnl_sparse_matrix(const vnl_sparse_matrix& rhs) - : elements(rhs.elements), rs_(rhs.rs_), cs_(rhs.cs_) -{ -} +vnl_sparse_matrix::vnl_sparse_matrix(const vnl_sparse_matrix & rhs) + : elements(rhs.elements) + , rs_(rhs.rs_) + , cs_(rhs.cs_) +{} //------------------------------------------------------------ //: Copy another vnl_sparse_matrix into this. template -vnl_sparse_matrix& vnl_sparse_matrix::operator=(const vnl_sparse_matrix& rhs) +vnl_sparse_matrix & +vnl_sparse_matrix::operator=(const vnl_sparse_matrix & rhs) { if (this == &rhs) return *this; @@ -64,16 +67,18 @@ vnl_sparse_matrix& vnl_sparse_matrix::operator=(const vnl_sparse_matrix //------------------------------------------------------------ //: Multiply this*rhs, another sparse matrix. template -void vnl_sparse_matrix::mult(vnl_sparse_matrix const& rhs, vnl_sparse_matrix& result) const +void +vnl_sparse_matrix::mult(const vnl_sparse_matrix & rhs, vnl_sparse_matrix & result) const { assert(rhs.rows() == columns()); assert(this != &result); // make sure not to overwrite *this assert(&rhs != &result); // make sure not to overwrite rhs - unsigned int result_rows = rows(); - unsigned int result_cols = rhs.columns(); + const unsigned int result_rows = rows(); + const unsigned int result_cols = rhs.columns(); // Early return: empty result matrix - if (result_rows <= 0 || result_cols <= 0) return; + if (result_rows <= 0 || result_cols <= 0) + return; result.cs_ = result_cols; if (result.rows() != result_rows) @@ -83,62 +88,57 @@ void vnl_sparse_matrix::mult(vnl_sparse_matrix const& rhs, vnl_sparse_matr // give the result matrix enough rows (but only if not yet correct). result.elements.resize(result_rows); result.rs_ = result_rows; - for (unsigned row_id=0; row_id const & entry = *col_iter; - unsigned const col_id = entry.first; + const vnl_sparse_matrix_pair & entry = *col_iter; + const unsigned col_id = entry.first; // So we are at (row_id,col_id) = this_val in lhs matrix (this). // This must be multiplied by each entry in row col_id in // the rhs matrix, and the result added to result_row[col_id]. // If that row in rhs is empty, there is nothing to do. - row const & rhs_row = rhs.elements[col_id]; + const row & rhs_row = rhs.elements[col_id]; if (rhs_row.empty()) continue; // Else iterate over rhs's row. typename row::iterator result_col_iter = result_row.begin(); - for (typename row::const_iterator rhs_col_iter = rhs_row.begin(); - rhs_col_iter != rhs_row.end(); - ++rhs_col_iter) + for (typename row::const_iterator rhs_col_iter = rhs_row.begin(); rhs_col_iter != rhs_row.end(); ++rhs_col_iter) { - const vnl_sparse_matrix_pair& rhs_entry = *rhs_col_iter; - unsigned int const dest_col = rhs_entry.first; + const vnl_sparse_matrix_pair & rhs_entry = *rhs_col_iter; + const unsigned int dest_col = rhs_entry.first; // Calculate the product. T prod = entry.second * rhs_entry.second; // This must be added into result_row, at column dest_col. - while ((result_col_iter != result_row.end()) && - ((*result_col_iter).first < dest_col)) + while ((result_col_iter != result_row.end()) && ((*result_col_iter).first < dest_col)) ++result_col_iter; - if ((result_col_iter == result_row.end()) || - ((*result_col_iter).first != dest_col)) + if ((result_col_iter == result_row.end()) || ((*result_col_iter).first != dest_col)) { // Add new column to the row. - result_col_iter = result_row.insert(result_col_iter, vnl_sparse_matrix_pair(dest_col,prod)); + result_col_iter = result_row.insert(result_col_iter, vnl_sparse_matrix_pair(dest_col, prod)); } else { @@ -154,31 +154,33 @@ void vnl_sparse_matrix::mult(vnl_sparse_matrix const& rhs, vnl_sparse_matr //: Multiply this*p, a fortran order matrix. // The matrix p has n rows and m columns, and is in fortran order, ie. columns first. template -void vnl_sparse_matrix::mult(unsigned int prows, unsigned int pcols, - T const* p, T* q) const +void +vnl_sparse_matrix::mult(unsigned int prows, unsigned int pcols, const T * p, T * q) const { assert(prows == columns()); // Clear q matrix. - int size = rows()*pcols; - for (int temp=0; temp md(rows(),columns()); - for (int rr = 0; rr md(rows(), columns()); + for (int rr = 0; rr < rows(); rr++) + for (int cc = 0; cc < columns(); cc++) + md(rr, cc) = (*this)(rr, cc); - vnl_matrix pd(prows,pcols); - for (int rr = 0; rr pd(prows, pcols); + for (int rr = 0; rr < prows; rr++) + for (int cc = 0; cc < pcols; cc++) + pd(rr, cc) = p[rr + cc * prows]; std::cout << "Initial p:\n"; - for (int rr = 0; rr::mult(unsigned int prows, unsigned int pcols, #endif // Now, iterate over non-zero rows of this. - for (unsigned row_id=0; row_id const & entry = *col_iter; - unsigned const col_id = entry.first; + const vnl_sparse_matrix_pair & entry = *col_iter; + const unsigned col_id = entry.first; // So we are at (row_id,col_id) = this_val in lhs matrix // (this). This must be multiplied by each entry in row @@ -210,29 +211,32 @@ void vnl_sparse_matrix::mult(unsigned int prows, unsigned int pcols, // // Iterate over p's row. - for (unsigned int p_col_id = 0; p_col_id < pcols; p_col_id++) { + for (unsigned int p_col_id = 0; p_col_id < pcols; p_col_id++) + { // Get the correct position from p. - T pval = p[col_id + p_col_id*prows]; + T pval = p[col_id + p_col_id * prows]; // Calculate the product. T prod = entry.second * pval; // Add the product into the correct position in q (fortran order) - q[row_id + p_col_id*rows()] += prod; + q[row_id + p_col_id * rows()] += prod; } } } #ifdef DEBUG_SPARSE std::cout << "Final q:\n"; - for (int rr = 0; rr::mult(unsigned int prows, unsigned int pcols, //------------------------------------------------------------ //: Multiply this*rhs, a vector. template -void vnl_sparse_matrix::mult(vnl_vector const& rhs, vnl_vector& result) const +void +vnl_sparse_matrix::mult(const vnl_vector & rhs, vnl_vector & result) const { assert(rhs.size() == columns()); - result.set_size( rows() ); + result.set_size(rows()); result.fill(T(0)); - int rhs_row_id =0; + int rhs_row_id = 0; typename std::vector::const_iterator lhs_row_iter = elements.begin(); - for ( ; lhs_row_iter != elements.end(); ++lhs_row_iter, rhs_row_id++ ) { - row const & lhs_row = *lhs_row_iter; - if (lhs_row.empty()) continue; + for (; lhs_row_iter != elements.end(); ++lhs_row_iter, rhs_row_id++) + { + const row & lhs_row = *lhs_row_iter; + if (lhs_row.empty()) + continue; typename row::const_iterator lhs_col_iter = lhs_row.begin(); - for ( ; lhs_col_iter != lhs_row.end(); ++lhs_col_iter) { - vnl_sparse_matrix_pair const & entry = *lhs_col_iter; - unsigned const lhs_col_id = entry.first; + for (; lhs_col_iter != lhs_row.end(); ++lhs_col_iter) + { + const vnl_sparse_matrix_pair & entry = *lhs_col_iter; + const unsigned lhs_col_id = entry.first; - result[ rhs_row_id ] += rhs[ lhs_col_id ] * entry.second; + result[rhs_row_id] += rhs[lhs_col_id] * entry.second; } } } @@ -266,36 +274,35 @@ void vnl_sparse_matrix::mult(vnl_vector const& rhs, vnl_vector& result) //------------------------------------------------------------ //: Multiply lhs*this, where lhs is a vector template -void vnl_sparse_matrix::pre_mult(const vnl_vector& lhs, vnl_vector& result) const +void +vnl_sparse_matrix::pre_mult(const vnl_vector & lhs, vnl_vector & result) const { assert(lhs.size() == rows()); // Resize and clear result vector - result.set_size( columns() ); + result.set_size(columns()); result.fill(T(0)); // Now, iterate over lhs values and rows of rhs unsigned lhs_col_id = 0; - for (typename std::vector::const_iterator rhs_row_iter = elements.begin(); - rhs_row_iter != elements.end(); - ++rhs_row_iter, lhs_col_id++ ) + for (typename std::vector::const_iterator rhs_row_iter = elements.begin(); rhs_row_iter != elements.end(); + ++rhs_row_iter, lhs_col_id++) { // Get the row from rhs matrix. - row const & rhs_row = *rhs_row_iter; + const row & rhs_row = *rhs_row_iter; // Skip to next row if empty. - if (rhs_row.empty()) continue; + if (rhs_row.empty()) + continue; // Iterate over values in rhs row - for (typename row::const_iterator rhs_col_iter = rhs_row.begin(); - rhs_col_iter != rhs_row.end(); - ++rhs_col_iter) + for (typename row::const_iterator rhs_col_iter = rhs_row.begin(); rhs_col_iter != rhs_row.end(); ++rhs_col_iter) { // Get the element from the row. - vnl_sparse_matrix_pair const& entry = *rhs_col_iter; - unsigned const rhs_col_id = entry.first; + const vnl_sparse_matrix_pair & entry = *rhs_col_iter; + const unsigned rhs_col_id = entry.first; - result[ rhs_col_id ] += lhs[ lhs_col_id ] * entry.second; + result[rhs_col_id] += lhs[lhs_col_id] * entry.second; } } } @@ -303,8 +310,8 @@ void vnl_sparse_matrix::pre_mult(const vnl_vector& lhs, vnl_vector& res //------------------------------------------------------------ //: Add rhs to this. template -void vnl_sparse_matrix::add(const vnl_sparse_matrix& rhs, - vnl_sparse_matrix& result) const +void +vnl_sparse_matrix::add(const vnl_sparse_matrix & rhs, vnl_sparse_matrix & result) const { assert((rhs.rows() == rows()) && (rhs.columns() == columns())); @@ -318,15 +325,14 @@ void vnl_sparse_matrix::add(const vnl_sparse_matrix& rhs, // Now, iterate over non-zero rows of this. unsigned int row_id = 0; - for (typename std::vector::const_iterator row_iter = elements.begin(); - row_iter != elements.end(); + for (typename std::vector::const_iterator row_iter = elements.begin(); row_iter != elements.end(); ++row_iter, ++row_id) { // Get the row from this matrix (lhs). - row const & this_row = *row_iter; + const row & this_row = *row_iter; // Get the new row in the result matrix. - row& result_row = result.elements[row_id]; + row & result_row = result.elements[row_id]; // Store this into result row. result_row = this_row; @@ -336,19 +342,17 @@ void vnl_sparse_matrix::add(const vnl_sparse_matrix& rhs, continue; // Get the rhs row. - row const& rhs_row = rhs.elements[row_id]; + const row & rhs_row = rhs.elements[row_id]; // Iterate over the rhs row. - for (typename row::const_iterator col_iter = rhs_row.begin(); - col_iter != rhs_row.end(); - ++col_iter) + for (typename row::const_iterator col_iter = rhs_row.begin(); col_iter != rhs_row.end(); ++col_iter) { // Get the element from the row. - vnl_sparse_matrix_pair const& entry = *col_iter; - unsigned const col_id = entry.first; + const vnl_sparse_matrix_pair & entry = *col_iter; + const unsigned col_id = entry.first; // So we are at (row_id,col_id) in rhs matrix. - result(row_id,col_id) += entry.second; + result(row_id, col_id) += entry.second; } } } @@ -356,8 +360,8 @@ void vnl_sparse_matrix::add(const vnl_sparse_matrix& rhs, //------------------------------------------------------------ //: Subtract rhs from this. template -void vnl_sparse_matrix::subtract(const vnl_sparse_matrix& rhs, - vnl_sparse_matrix& result) const +void +vnl_sparse_matrix::subtract(const vnl_sparse_matrix & rhs, vnl_sparse_matrix & result) const { assert((rhs.rows() == rows()) && (rhs.columns() == columns())); @@ -371,15 +375,14 @@ void vnl_sparse_matrix::subtract(const vnl_sparse_matrix& rhs, // Now, iterate over non-zero rows of this. unsigned int row_id = 0; - for (typename std::vector::const_iterator row_iter = elements.begin(); - row_iter != elements.end(); + for (typename std::vector::const_iterator row_iter = elements.begin(); row_iter != elements.end(); ++row_iter, ++row_id) { // Get the row from this matrix (lhs). - row const& this_row = *row_iter; + const row & this_row = *row_iter; // Get the new row in the result matrix. - row& result_row = result.elements[row_id]; + row & result_row = result.elements[row_id]; // Store this into result row. result_row = this_row; @@ -389,19 +392,17 @@ void vnl_sparse_matrix::subtract(const vnl_sparse_matrix& rhs, continue; // Get the rhs row. - row const& rhs_row = rhs.elements[row_id]; + const row & rhs_row = rhs.elements[row_id]; // Iterate over the rhs row. - for (typename row::const_iterator col_iter = rhs_row.begin(); - col_iter != rhs_row.end(); - ++col_iter) + for (typename row::const_iterator col_iter = rhs_row.begin(); col_iter != rhs_row.end(); ++col_iter) { // Get the element from the row. - vnl_sparse_matrix_pair const& entry = *col_iter; - unsigned const col_id = entry.first; + const vnl_sparse_matrix_pair & entry = *col_iter; + const unsigned col_id = entry.first; // So we are at (row_id,col_id) in rhs matrix. - result(row_id,col_id) -= entry.second; + result(row_id, col_id) -= entry.second; } } } @@ -409,10 +410,11 @@ void vnl_sparse_matrix::subtract(const vnl_sparse_matrix& rhs, //------------------------------------------------------------ //: Get a reference to an entry in the matrix. template -T& vnl_sparse_matrix::operator()(unsigned int r, unsigned int c) +T & +vnl_sparse_matrix::operator()(unsigned int r, unsigned int c) { assert((r < rows()) && (c < columns())); - row& rw = elements[r]; + row & rw = elements[r]; if (rw.empty()) { @@ -440,7 +442,8 @@ T& vnl_sparse_matrix::operator()(unsigned int r, unsigned int c) //------------------------------------------------------------ //: Get the value of an entry in the matrix. template -T vnl_sparse_matrix::operator()(unsigned int r, unsigned int c) const +T +vnl_sparse_matrix::operator()(unsigned int r, unsigned int c) const { return this->get(r, c); } @@ -449,10 +452,11 @@ T vnl_sparse_matrix::operator()(unsigned int r, unsigned int c) const //: Get an entry in the matrix. // This is the "const" version of operator(). template -T vnl_sparse_matrix::get(unsigned int r, unsigned int c) const +T +vnl_sparse_matrix::get(unsigned int r, unsigned int c) const { assert((r < rows()) && (c < columns())); - row const& rw = elements[r]; + const row & rw = elements[r]; if (rw.empty() || c > rw.back().first) return T(); @@ -471,10 +475,11 @@ T vnl_sparse_matrix::get(unsigned int r, unsigned int c) const //------------------------------------------------------------ //: Put (i.e., add or overwrite) an entry into the matrix. template -void vnl_sparse_matrix::put(unsigned int r, unsigned int c, T v) +void +vnl_sparse_matrix::put(unsigned int r, unsigned int c, T v) { assert((r < rows()) && (c < columns())); - row& rw = elements[r]; + row & rw = elements[r]; if (rw.empty()) { @@ -494,7 +499,7 @@ void vnl_sparse_matrix::put(unsigned int r, unsigned int c, T v) if (ri->first == c) ri->second = v; else - rw.insert(ri, vnl_sparse_matrix_pair(c, v)); + rw.insert(ri, vnl_sparse_matrix_pair(c, v)); } else { @@ -507,18 +512,21 @@ void vnl_sparse_matrix::put(unsigned int r, unsigned int c, T v) } template -void vnl_sparse_matrix::diag_AtA(vnl_vector & result) const +void +vnl_sparse_matrix::diag_AtA(vnl_vector & result) const { - result.set_size( columns() ); + result.set_size(columns()); result.fill(T(0)); typename std::vector::const_iterator row_iter = elements.begin(); - for ( ; row_iter != elements.end(); ++row_iter) { - row const& this_row = *row_iter; + for (; row_iter != elements.end(); ++row_iter) + { + const row & this_row = *row_iter; typename row::const_iterator col_iter = this_row.begin(); - for ( ; col_iter != this_row.end(); ++col_iter) { - vnl_sparse_matrix_pair const& entry = *col_iter; - unsigned const col_id = entry.first; + for (; col_iter != this_row.end(); ++col_iter) + { + const vnl_sparse_matrix_pair & entry = *col_iter; + const unsigned col_id = entry.first; result[col_id] += entry.second * entry.second; } } @@ -528,17 +536,16 @@ void vnl_sparse_matrix::diag_AtA(vnl_vector & result) const //: Set row in the matrix. template -vnl_sparse_matrix& -vnl_sparse_matrix::set_row(unsigned int r, - std::vector const& colz, - std::vector const& vals) +vnl_sparse_matrix & +vnl_sparse_matrix::set_row(unsigned int r, const std::vector & colz, const std::vector & vals) { - assert (r < rows()); - assert (colz.size() == vals.size()); + assert(r < rows()); + assert(colz.size() == vals.size()); - row& rw = elements[r]; - if (rw.size() != colz.size()) rw = row(colz.size()); - for (unsigned int i=0; i < colz.size(); ++i) + row & rw = elements[r]; + if (rw.size() != colz.size()) + rw = row(colz.size()); + for (unsigned int i = 0; i < colz.size(); ++i) rw[i] = vnl_sparse_matrix_pair(colz[i], vals[i]); typedef typename vnl_sparse_matrix_pair::less less; std::sort(rw.begin(), rw.end(), less()); @@ -546,15 +553,17 @@ vnl_sparse_matrix::set_row(unsigned int r, } template -vnl_sparse_matrix& -vnl_sparse_matrix::vcat(vnl_sparse_matrix const& A) +vnl_sparse_matrix & +vnl_sparse_matrix::vcat(const vnl_sparse_matrix & A) { - if (rs_ == 0) { + if (rs_ == 0) + { rs_ = A.rs_; cs_ = A.cs_; elements = A.elements; } - else { + else + { assert(cs_ == A.cs_); rs_ += A.rs_; elements.insert(elements.end(), A.elements.begin(), A.elements.end()); @@ -566,7 +575,8 @@ vnl_sparse_matrix::vcat(vnl_sparse_matrix const& A) //------------------------------------------------------------ //: This is occasionally useful. Sums a row of the matrix efficiently. template -T vnl_sparse_matrix::sum_row(unsigned int r) +T +vnl_sparse_matrix::sum_row(unsigned int r) { assert(r < rows()); row & rw = elements[r]; @@ -578,11 +588,11 @@ T vnl_sparse_matrix::sum_row(unsigned int r) } template -vnl_sparse_matrix& +vnl_sparse_matrix & vnl_sparse_matrix::scale_row(unsigned int r, T scale) { assert(r < rows()); - row& rw = elements[r]; + row & rw = elements[r]; for (typename row::iterator ri = rw.begin(); ri != rw.end(); ++ri) (*ri).second *= scale; return *this; @@ -592,7 +602,8 @@ vnl_sparse_matrix::scale_row(unsigned int r, T scale) //: Resizes the matrix so that it has r rows and c columns, clearing the current contents. // template -void vnl_sparse_matrix::set_size( int r, int c) +void +vnl_sparse_matrix::set_size(int r, int c) { rs_ = r; cs_ = c; @@ -611,22 +622,26 @@ void vnl_sparse_matrix::set_size( int r, int c) // This is more wasteful of resources than set_size, but it preserves the contents. // template -void vnl_sparse_matrix::resize( int r, int c) +void +vnl_sparse_matrix::resize(int r, int c) { - unsigned int oldCs = cs_; + const unsigned int oldCs = cs_; rs_ = r; cs_ = c; elements.resize(r); // If the array has fewer columns now, we also need to cut them out - if (oldCs > cs_) { - for (unsigned int i = 0; i < elements.size(); ++i) { - row& rw = elements[i]; + if (oldCs > cs_) + { + for (unsigned int i = 0; i < elements.size(); ++i) + { + row & rw = elements[i]; typename row::iterator iter; - for (iter = rw.begin(); iter != rw.end() && (*iter).first::resize( int r, int c) //------------------------------------------------------------ //: Resets the internal iterator template -void vnl_sparse_matrix::reset() const +void +vnl_sparse_matrix::reset() const { itr_isreset = true; itr_row = 0; @@ -648,30 +664,34 @@ void vnl_sparse_matrix::reset() const // in combination with methods reset, getrow, getcolumn, and value. // template -bool vnl_sparse_matrix::next() const +bool +vnl_sparse_matrix::next() const { - if ( itr_row >= rows() ) + if (itr_row >= rows()) return false; - if ( itr_isreset ) { + if (itr_isreset) + { // itr_cur is not pointing to an entry itr_row = 0; itr_isreset = false; } - else { + else + { // itr_cur is pointing to an entry. // Try to move to next entry in current row. itr_cur++; - if ( itr_cur != elements[itr_row].end() ) - return true; // found next entry in current row + if (itr_cur != elements[itr_row].end()) + return true; // found next entry in current row else itr_row++; } // search for next entry starting at row itr_row - while ( itr_row < rows() ) { + while (itr_row < rows()) + { itr_cur = elements[itr_row].begin(); - if ( itr_cur != elements[itr_row].end() ) + if (itr_cur != elements[itr_row].end()) return true; else itr_row++; @@ -684,7 +704,8 @@ bool vnl_sparse_matrix::next() const //: Returns the row of the entry pointed to by internal iterator. // template -int vnl_sparse_matrix::getrow() const +int +vnl_sparse_matrix::getrow() const { return itr_row; } @@ -693,7 +714,8 @@ int vnl_sparse_matrix::getrow() const //: Returns the column of the entry pointed to by internal iterator. // template -int vnl_sparse_matrix::getcolumn() const +int +vnl_sparse_matrix::getcolumn() const { return (*itr_cur).first; } @@ -702,7 +724,8 @@ int vnl_sparse_matrix::getcolumn() const //: Returns the value pointed to by the internal iterator. // template -T vnl_sparse_matrix::value() const +T +vnl_sparse_matrix::value() const { return (*itr_cur).second; } @@ -711,43 +734,43 @@ T vnl_sparse_matrix::value() const //: Comparison // template -bool vnl_sparse_matrix::operator==(vnl_sparse_matrix const& rhs) const +bool +vnl_sparse_matrix::operator==(const vnl_sparse_matrix & rhs) const { // first of all, sizes must match: - if (rhs.rows() != rows() || rhs.columns() != columns()) { + if (rhs.rows() != rows() || rhs.columns() != columns()) + { #ifdef DEBUG_SPARSE - std::cerr << "Sizes are different: " << rows() << 'x' << columns() << ' ' << rhs.rows() << 'x' << rhs.columns() << '\n'; + std::cerr << "Sizes are different: " << rows() << 'x' << columns() << ' ' << rhs.rows() << 'x' << rhs.columns() + << '\n'; #endif return false; } // Now, iterate over non-zero rows of this and of rhs. unsigned int row_id = 0; - for (typename std::vector::const_iterator row_iter = elements.begin(); - row_iter != elements.end(); + for (typename std::vector::const_iterator row_iter = elements.begin(); row_iter != elements.end(); ++row_iter, ++row_id) { // Get the row from this matrix (lhs). - row const& this_row = *row_iter; + const row & this_row = *row_iter; // Get the rhs row. - row const& rhs_row = rhs.elements[row_id]; + const row & rhs_row = rhs.elements[row_id]; // first of all, row sizes must match: if (rhs_row.size() != this_row.size()) return false; // Iterate over the rhs row. - for (typename row::const_iterator col_iter = rhs_row.begin(); - col_iter != rhs_row.end(); - ++col_iter) + for (typename row::const_iterator col_iter = rhs_row.begin(); col_iter != rhs_row.end(); ++col_iter) { // Get the element from the row. - vnl_sparse_matrix_pair const& entry = *col_iter; - unsigned const col_id = entry.first; + const vnl_sparse_matrix_pair & entry = *col_iter; + const unsigned col_id = entry.first; // So we are at (row_id,col_id) in rhs matrix. - if (get(row_id,col_id) != entry.second) + if (get(row_id, col_id) != entry.second) return false; } } @@ -757,28 +780,26 @@ bool vnl_sparse_matrix::operator==(vnl_sparse_matrix const& rhs) const //: Unary minus template -vnl_sparse_matrix::signed_t> vnl_sparse_matrix::operator-() const +vnl_sparse_matrix::signed_t> +vnl_sparse_matrix::operator-() const { // The matrix to be returned: vnl_sparse_matrix result(rows(), columns()); // Iterate over non-zero rows of this matrix. unsigned int row_id = 0; - for (typename std::vector::const_iterator row_iter = elements.begin(); - row_iter != elements.end(); + for (typename std::vector::const_iterator row_iter = elements.begin(); row_iter != elements.end(); ++row_iter, ++row_id) { // Get the row. - row const& this_row = *row_iter; + const row & this_row = *row_iter; // Iterate over the row. - for (typename row::const_iterator col_iter = this_row.begin(); - col_iter != this_row.end(); - ++col_iter) + for (typename row::const_iterator col_iter = this_row.begin(); col_iter != this_row.end(); ++col_iter) { // Assign the corresponding result element. - vnl_sparse_matrix_pair const& entry = *col_iter; - result(row_id, entry.first) = - entry.second; + const vnl_sparse_matrix_pair & entry = *col_iter; + result(row_id, entry.first) = -entry.second; } } return result; @@ -786,7 +807,8 @@ vnl_sparse_matrix::signed_t> vnl_sparse_matrix //: addition template -vnl_sparse_matrix vnl_sparse_matrix::operator+(vnl_sparse_matrix const& rhs) const +vnl_sparse_matrix +vnl_sparse_matrix::operator+(const vnl_sparse_matrix & rhs) const { vnl_sparse_matrix result(rows(), columns()); add(rhs, result); @@ -795,7 +817,8 @@ vnl_sparse_matrix vnl_sparse_matrix::operator+(vnl_sparse_matrix const& //: subtraction template -vnl_sparse_matrix vnl_sparse_matrix::operator-(vnl_sparse_matrix const& rhs) const +vnl_sparse_matrix +vnl_sparse_matrix::operator-(const vnl_sparse_matrix & rhs) const { vnl_sparse_matrix result(rows(), columns()); subtract(rhs, result); @@ -804,7 +827,8 @@ vnl_sparse_matrix vnl_sparse_matrix::operator-(vnl_sparse_matrix const& //: multiplication template -vnl_sparse_matrix vnl_sparse_matrix::operator*(vnl_sparse_matrix const& rhs) const +vnl_sparse_matrix +vnl_sparse_matrix::operator*(const vnl_sparse_matrix & rhs) const { vnl_sparse_matrix result(rows(), rhs.columns()); mult(rhs, result); @@ -813,20 +837,17 @@ vnl_sparse_matrix vnl_sparse_matrix::operator*(vnl_sparse_matrix const& //: in-place scalar multiplication template -vnl_sparse_matrix& vnl_sparse_matrix::operator*=(T const& rhs) +vnl_sparse_matrix & +vnl_sparse_matrix::operator*=(const T & rhs) { // Iterate over non-zero rows of this matrix. - for (typename std::vector::iterator row_iter = elements.begin(); - row_iter != elements.end(); - ++row_iter) + for (typename std::vector::iterator row_iter = elements.begin(); row_iter != elements.end(); ++row_iter) { // Get the row. - row& this_row = *row_iter; + row & this_row = *row_iter; // Iterate over the row. - for (typename row::iterator col_iter = this_row.begin(); - col_iter != this_row.end(); - ++col_iter) + for (typename row::iterator col_iter = this_row.begin(); col_iter != this_row.end(); ++col_iter) { // Change the corresponding element. col_iter->second *= rhs; @@ -837,20 +858,17 @@ vnl_sparse_matrix& vnl_sparse_matrix::operator*=(T const& rhs) //: in-place scalar division template -vnl_sparse_matrix& vnl_sparse_matrix::operator/=(T const& rhs) +vnl_sparse_matrix & +vnl_sparse_matrix::operator/=(const T & rhs) { // Iterate over non-zero rows of this matrix. - for (typename std::vector::iterator row_iter = elements.begin(); - row_iter != elements.end(); - ++row_iter) + for (typename std::vector::iterator row_iter = elements.begin(); row_iter != elements.end(); ++row_iter) { // Get the row. - row& this_row = *row_iter; + row & this_row = *row_iter; // Iterate over the row. - for (typename row::iterator col_iter = this_row.begin(); - col_iter != this_row.end(); - ++col_iter) + for (typename row::iterator col_iter = this_row.begin(); col_iter != this_row.end(); ++col_iter) { // Change the corresponding element. col_iter->second /= rhs; @@ -861,7 +879,8 @@ vnl_sparse_matrix& vnl_sparse_matrix::operator/=(T const& rhs) //: scalar multiplication template -vnl_sparse_matrix vnl_sparse_matrix::operator*(T const& rhs) const +vnl_sparse_matrix +vnl_sparse_matrix::operator*(const T & rhs) const { vnl_sparse_matrix result = *this; return result *= rhs; @@ -869,7 +888,8 @@ vnl_sparse_matrix vnl_sparse_matrix::operator*(T const& rhs) const //: scalar division template -vnl_sparse_matrix vnl_sparse_matrix::operator/(T const& rhs) const +vnl_sparse_matrix +vnl_sparse_matrix::operator/(const T & rhs) const { vnl_sparse_matrix result = *this; return result /= rhs; @@ -877,60 +897,59 @@ vnl_sparse_matrix vnl_sparse_matrix::operator/(T const& rhs) const //: in-place addition template -vnl_sparse_matrix& vnl_sparse_matrix::operator+=(vnl_sparse_matrix const& rhs) +vnl_sparse_matrix & +vnl_sparse_matrix::operator+=(const vnl_sparse_matrix & rhs) { return *this = operator+(rhs); } //: in-place subtraction template -vnl_sparse_matrix& vnl_sparse_matrix::operator-=(vnl_sparse_matrix const& rhs) +vnl_sparse_matrix & +vnl_sparse_matrix::operator-=(const vnl_sparse_matrix & rhs) { return *this = operator-(rhs); } //: in-place multiplication template -vnl_sparse_matrix& vnl_sparse_matrix::operator*=(vnl_sparse_matrix const& rhs) +vnl_sparse_matrix & +vnl_sparse_matrix::operator*=(const vnl_sparse_matrix & rhs) { return *this = operator*(rhs); } //: Make each row of the matrix have unit norm. // All-zero rows are ignored. -template -vnl_sparse_matrix& vnl_sparse_matrix::normalize_rows() +template +vnl_sparse_matrix & +vnl_sparse_matrix::normalize_rows() { typedef typename vnl_numeric_traits::abs_t Abs_t; typedef typename vnl_numeric_traits::real_t Real_t; typedef typename vnl_numeric_traits::abs_t abs_real_t; // Iterate through the matrix rows, and normalize one at a time: - for (typename std::vector::iterator row_iter = elements.begin(); - row_iter != elements.end(); - ++row_iter) + for (typename std::vector::iterator row_iter = elements.begin(); row_iter != elements.end(); ++row_iter) { // Get the row. - row& this_row = *row_iter; + row & this_row = *row_iter; Abs_t norm(0); // double will not do for all types. // Iterate over the row - for (typename row::iterator col_iter = this_row.begin(); - col_iter != this_row.end(); - ++col_iter) + for (typename row::iterator col_iter = this_row.begin(); col_iter != this_row.end(); ++col_iter) { - vnl_sparse_matrix_pair& entry = *col_iter; + const vnl_sparse_matrix_pair & entry = *col_iter; norm += vnl_math::squared_magnitude(entry.second); } - if (norm != 0) { - abs_real_t scale = abs_real_t(1)/(std::sqrt((abs_real_t)norm)); + if (norm != 0) + { + const abs_real_t scale = abs_real_t(1) / (std::sqrt((abs_real_t)norm)); // Iterate again over the row - for (typename row::iterator col_iter = this_row.begin(); - col_iter != this_row.end(); - ++col_iter) + for (typename row::iterator col_iter = this_row.begin(); col_iter != this_row.end(); ++col_iter) { - vnl_sparse_matrix_pair& entry = *col_iter; + vnl_sparse_matrix_pair & entry = *col_iter; entry.second = T(Real_t(entry.second) * scale); } } @@ -939,42 +958,40 @@ vnl_sparse_matrix& vnl_sparse_matrix::normalize_rows() } //: Fill this matrix with 1s on the main diagonal and 0s elsewhere. -template -vnl_sparse_matrix& vnl_sparse_matrix::set_identity() +template +vnl_sparse_matrix & +vnl_sparse_matrix::set_identity() { // Iterate through the matrix rows, and set one at a time: unsigned int rownum = 0; - for (typename std::vector::iterator row_iter = elements.begin(); - row_iter != elements.end() && rownum < cols(); + for (typename std::vector::iterator row_iter = elements.begin(); row_iter != elements.end() && rownum < cols(); ++row_iter, ++rownum) { - row& rw = *row_iter; + row & rw = *row_iter; rw.clear(); - rw[0] = vnl_sparse_matrix_pair(rownum,T(1)); + rw[0] = vnl_sparse_matrix_pair(rownum, T(1)); } return *this; } //: returns a new sparse matrix, viz. the transpose of this -template -vnl_sparse_matrix vnl_sparse_matrix::transpose() const +template +vnl_sparse_matrix +vnl_sparse_matrix::transpose() const { vnl_sparse_matrix result(cols(), rows()); unsigned int rownum = 0; // row number in this matrix // iterate through the rows of this matrix, // and add every element thus found to the new result matrix - for (typename std::vector::const_iterator row_iter = elements.begin(); - row_iter != elements.end(); + for (typename std::vector::const_iterator row_iter = elements.begin(); row_iter != elements.end(); ++row_iter, ++rownum) { - row const& this_row = *row_iter; - for (typename row::const_iterator col_iter = this_row.begin(); - col_iter != this_row.end(); - ++col_iter) + const row & this_row = *row_iter; + for (typename row::const_iterator col_iter = this_row.begin(); col_iter != this_row.end(); ++col_iter) { vnl_sparse_matrix_pair entry = *col_iter; // new copy of element - row& rw = result.elements[entry.first]; - entry.first = rownum; // modify element: its column number is now rownum + row & rw = result.elements[entry.first]; + entry.first = rownum; // modify element: its column number is now rownum rw.insert(rw.end(), entry); // insert at the end of the row } } @@ -982,27 +999,24 @@ vnl_sparse_matrix vnl_sparse_matrix::transpose() const } //: returns a new sparse matrix, viz. the conjugate (or Hermitian) transpose of this -template -vnl_sparse_matrix vnl_sparse_matrix::conjugate_transpose() const +template +vnl_sparse_matrix +vnl_sparse_matrix::conjugate_transpose() const { vnl_sparse_matrix result(transpose()); - for (typename std::vector::iterator row_iter = result.elements.begin(); - row_iter != result.elements.end(); + for (typename std::vector::iterator row_iter = result.elements.begin(); row_iter != result.elements.end(); ++row_iter) { - row& this_row = *row_iter; - for (typename row::iterator col_iter = this_row.begin(); - col_iter != this_row.end(); - ++col_iter) + row & this_row = *row_iter; + for (typename row::iterator col_iter = this_row.begin(); col_iter != this_row.end(); ++col_iter) { - vnl_sparse_matrix_pair& entry = *col_iter; + vnl_sparse_matrix_pair & entry = *col_iter; entry.second = vnl_complex_traits::conjugate(entry.second); } } return result; } -#define VNL_SPARSE_MATRIX_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_sparse_matrix +#define VNL_SPARSE_MATRIX_INSTANTIATE(T) template class VNL_EXPORT vnl_sparse_matrix #endif // vnl_sparse_matrix_hxx_ diff --git a/core/vnl/vnl_sparse_matrix_linear_system.cxx b/core/vnl/vnl_sparse_matrix_linear_system.cxx index e08cca60bb5..33a8c34cac3 100644 --- a/core/vnl/vnl_sparse_matrix_linear_system.cxx +++ b/core/vnl/vnl_sparse_matrix_linear_system.cxx @@ -13,7 +13,7 @@ vnl_sparse_matrix_linear_system::get_rhs(vnl_vector & b) const template <> void -vnl_sparse_matrix_linear_system::transpose_multiply(vnl_vector const & b, vnl_vector & x) const +vnl_sparse_matrix_linear_system::transpose_multiply(const vnl_vector & b, vnl_vector & x) const { A_.pre_mult(b, x); } @@ -27,7 +27,7 @@ vnl_sparse_matrix_linear_system::get_rhs(vnl_vector & b) const template <> void -vnl_sparse_matrix_linear_system::transpose_multiply(vnl_vector const & b, vnl_vector & x) const +vnl_sparse_matrix_linear_system::transpose_multiply(const vnl_vector & b, vnl_vector & x) const { static vnl_vector x_float; static vnl_vector b_float; @@ -44,7 +44,7 @@ vnl_sparse_matrix_linear_system::transpose_multiply(vnl_vector co template <> void -vnl_sparse_matrix_linear_system::multiply(vnl_vector const & x, vnl_vector & b) const +vnl_sparse_matrix_linear_system::multiply(const vnl_vector & x, vnl_vector & b) const { A_.mult(x, b); } @@ -52,7 +52,7 @@ vnl_sparse_matrix_linear_system::multiply(vnl_vector const & x, template <> void -vnl_sparse_matrix_linear_system::multiply(vnl_vector const & x, vnl_vector & b) const +vnl_sparse_matrix_linear_system::multiply(const vnl_vector & x, vnl_vector & b) const { static vnl_vector x_float; static vnl_vector b_float; @@ -70,7 +70,7 @@ vnl_sparse_matrix_linear_system::multiply(vnl_vector const & x, v template void -vnl_sparse_matrix_linear_system::apply_preconditioner(vnl_vector const & x, vnl_vector & px) const +vnl_sparse_matrix_linear_system::apply_preconditioner(const vnl_vector & x, vnl_vector & px) const { assert(x.size() == px.size()); diff --git a/core/vnl/vnl_sparse_matrix_linear_system.h b/core/vnl/vnl_sparse_matrix_linear_system.h index de22fda4239..8339b9f2e76 100644 --- a/core/vnl/vnl_sparse_matrix_linear_system.h +++ b/core/vnl/vnl_sparse_matrix_linear_system.h @@ -26,38 +26,52 @@ template class VNL_EXPORT vnl_sparse_matrix_linear_system : public vnl_linear_system { - public: +public: //::Constructor from vnl_sparse_matrix for system Ax = b // Keeps a reference to the original sparse matrix A and vector b so DO NOT DELETE THEM!! - vnl_sparse_matrix_linear_system(vnl_sparse_matrix const& A, vnl_vector const& b) : - vnl_linear_system(A.columns(), A.rows()), A_(A), b_(b), jacobi_precond_() {} + vnl_sparse_matrix_linear_system(const vnl_sparse_matrix & A, const vnl_vector & b) + : vnl_linear_system(A.columns(), A.rows()) + , A_(A) + , b_(b) + , jacobi_precond_() + {} //: Implementations of the vnl_linear_system virtuals. - void multiply(vnl_vector const& x, vnl_vector & b) const override; + void + multiply(const vnl_vector & x, vnl_vector & b) const override; //: Implementations of the vnl_linear_system virtuals. - void transpose_multiply(vnl_vector const& b, vnl_vector & x) const override; + void + transpose_multiply(const vnl_vector & b, vnl_vector & x) const override; //: Implementations of the vnl_linear_system virtuals. - void get_rhs(vnl_vector& b) const override; + void + get_rhs(vnl_vector & b) const override; //: Implementations of the vnl_linear_system virtuals. - void apply_preconditioner(vnl_vector const& x, vnl_vector & px) const override; + void + apply_preconditioner(const vnl_vector & x, vnl_vector & px) const override; - protected: - vnl_sparse_matrix const& A_; - vnl_vector const& b_; +protected: + const vnl_sparse_matrix & A_; + const vnl_vector & b_; vnl_vector jacobi_precond_; }; template <> -VNL_EXPORT void vnl_sparse_matrix_linear_system::get_rhs(vnl_vector& b) const; +VNL_EXPORT void +vnl_sparse_matrix_linear_system::get_rhs(vnl_vector & b) const; template <> -VNL_EXPORT void vnl_sparse_matrix_linear_system::transpose_multiply(vnl_vector const& b, vnl_vector & x) const; +VNL_EXPORT void +vnl_sparse_matrix_linear_system::transpose_multiply(const vnl_vector & b, vnl_vector & x) const; template <> -VNL_EXPORT void vnl_sparse_matrix_linear_system::get_rhs(vnl_vector& b) const; +VNL_EXPORT void +vnl_sparse_matrix_linear_system::get_rhs(vnl_vector & b) const; template <> -VNL_EXPORT void vnl_sparse_matrix_linear_system::transpose_multiply(vnl_vector const& b, vnl_vector & x) const; +VNL_EXPORT void +vnl_sparse_matrix_linear_system::transpose_multiply(const vnl_vector & b, vnl_vector & x) const; template <> -VNL_EXPORT void vnl_sparse_matrix_linear_system::multiply(vnl_vector const& x, vnl_vector & b) const; +VNL_EXPORT void +vnl_sparse_matrix_linear_system::multiply(const vnl_vector & x, vnl_vector & b) const; template <> -VNL_EXPORT void vnl_sparse_matrix_linear_system::multiply(vnl_vector const& x, vnl_vector & b) const; +VNL_EXPORT void +vnl_sparse_matrix_linear_system::multiply(const vnl_vector & x, vnl_vector & b) const; #endif // vnl_sparse_matrix_linear_system_h_ diff --git a/core/vnl/vnl_sse.h b/core/vnl/vnl_sse.h index 43357bfbad9..5c1cd758606 100644 --- a/core/vnl/vnl_sse.h +++ b/core/vnl/vnl_sse.h @@ -12,12 +12,12 @@ #ifdef _MSC_VER # include -#endif // for macro decisions based on compiler type -#include // for checking supported integer data types -#include // for DBL_MAX and FLT_MAX +#endif // for macro decisions based on compiler type +#include // for checking supported integer data types +#include // for DBL_MAX and FLT_MAX #include // is SSE enabled -#include "vnl_alloc.h" // is SSE enabled +#include "vnl_alloc.h" // is SSE enabled #include "vnl/vnl_export.h" // some caveats... @@ -26,174 +26,189 @@ // - The GCC 3.4 intrinsics seem to be horrendously slow... - // Try and use compiler instructions for forcing inlining if possible // Also instruction for aligning stack memory is compiler dependent #if defined(__GNUC__) // With attribute always_inline, gcc can give an error if a function // cannot be inlined, so it is disabled. Problem seen on 64 bit // platforms with std::vector. -# define VNL_SSE_FORCE_INLINE /* __attribute__((always_inline)) */ inline -# define VNL_SSE_STACK_ALIGNED(x) __attribute__((aligned(x))) VNL_EXPORT +# define VNL_SSE_FORCE_INLINE /* __attribute__((always_inline)) */ inline +# define VNL_SSE_STACK_ALIGNED(x) __attribute__((aligned(x))) VNL_EXPORT #elif defined _MSC_VER -# define VNL_SSE_FORCE_INLINE __forceinline -# define VNL_SSE_STACK_ALIGNED(x) __declspec(align(x)) VNL_EXPORT +# define VNL_SSE_FORCE_INLINE __forceinline +# define VNL_SSE_STACK_ALIGNED(x) __declspec(align(x)) VNL_EXPORT #else -# define VNL_SSE_FORCE_INLINE inline -# define VNL_SSE_STACK_ALIGNED(x) -# define VNL_SSE_STACK_STORE(pf) _mm_storeu_##pf // no stack alignment so use unaligned store (slower!) +# define VNL_SSE_FORCE_INLINE inline +# define VNL_SSE_STACK_ALIGNED(x) +# define VNL_SSE_STACK_STORE(pf) _mm_storeu_##pf // no stack alignment so use unaligned store (slower!) #endif - -# define VNL_SSE_HEAP_STORE(pf) _mm_storeu_##pf -# define VNL_SSE_HEAP_LOAD(pf) _mm_loadu_##pf -# if VNL_CONFIG_THREAD_SAFE -# define VNL_SSE_ALLOC(n,s,a) new char[(n)*(s)] -# define VNL_SSE_FREE(v,n,s) (delete [] static_cast(v)) -# else -# define VNL_SSE_ALLOC(n,s,a) vnl_alloc::allocate((n == 0) ? 8 : (n * s)); -# define VNL_SSE_FREE(v,n,s) if (v) vnl_alloc::deallocate(v, (n == 0) ? 8 : (n * s)); -# endif +#define VNL_SSE_HEAP_STORE(pf) _mm_storeu_##pf +#define VNL_SSE_HEAP_LOAD(pf) _mm_loadu_##pf +#if VNL_CONFIG_THREAD_SAFE +# define VNL_SSE_ALLOC(n, s, a) new char[(n) * (s)] +# define VNL_SSE_FREE(v, n, s) (delete[] static_cast(v)) +#else +# define VNL_SSE_ALLOC(n, s, a) vnl_alloc::allocate((n == 0) ? 8 : (n * s)); +# define VNL_SSE_FREE(v, n, s) \ + if (v) \ + vnl_alloc::deallocate(v, (n == 0) ? 8 : (n * s)); +#endif // Stack memory can be aligned -> use SSE aligned store #ifndef VNL_SSE_STACK_STORE -# define VNL_SSE_STACK_STORE(pf) _mm_store_##pf +# define VNL_SSE_STACK_STORE(pf) _mm_store_##pf #endif // Heap memory can be aligned -> use SSE aligned load & store #ifndef VNL_SSE_HEAP_STORE -# define VNL_SSE_HEAP_STORE(pf) _mm_store_##pf -# define VNL_SSE_HEAP_LOAD(pf) _mm_load_##pf +# define VNL_SSE_HEAP_STORE(pf) _mm_store_##pf +# define VNL_SSE_HEAP_LOAD(pf) _mm_load_##pf #endif //: Custom memory allocation function to force 16 byte alignment of data -VNL_SSE_FORCE_INLINE void* vnl_sse_alloc(std::size_t n, unsigned size) +VNL_SSE_FORCE_INLINE void * +vnl_sse_alloc(std::size_t n, unsigned size) { - return VNL_SSE_ALLOC(n,size,16); + return VNL_SSE_ALLOC(n, size, 16); } //: Custom memory deallocation function to free 16 byte aligned of data -VNL_SSE_FORCE_INLINE void vnl_sse_dealloc(void* mem, std::size_t n, unsigned size) +VNL_SSE_FORCE_INLINE void +vnl_sse_dealloc(void * mem, std::size_t n, unsigned size) { // Variables n and size are not used in all versions of the VNL_SSE_FREE macro. // Cast to void here to avoid unused variable warnings. - (void)n,(void)size; - VNL_SSE_FREE(mem,n,size); + (void)n, (void)size; + VNL_SSE_FREE(mem, n, size); } // avoid inlining when debugging #ifndef NDEBUG -#undef VNL_SSE_FORCE_INLINE -#define VNL_SSE_FORCE_INLINE +# undef VNL_SSE_FORCE_INLINE +# define VNL_SSE_FORCE_INLINE #endif -//: Bog standard (no sse) implementation for non sse enabled hardware and any type which doesn't have a template specialisation. +//: Bog standard (no sse) implementation for non sse enabled hardware and any type which doesn't have a template +//: specialisation. template -class VNL_EXPORT vnl_sse -{ - public: - static VNL_SSE_FORCE_INLINE void element_product(const T* x, const T* y, T* r, unsigned n) - { - for (unsigned i = 0; i < n; ++i) - r[i] = x[i] * y[i]; - } +class VNL_EXPORT +vnl_sse{ public: static VNL_SSE_FORCE_INLINE void element_product(const T * x, const T * y, T * r, unsigned n){ + for (unsigned i = 0; i < n; ++i) r[i] = x[i] * y[i]; +} - static VNL_SSE_FORCE_INLINE T dot_product(const T* x, const T* y, unsigned n) - { - T sum(0); - for (unsigned i = 0; i < n; ++i) - sum += x[i] * y[i]; - return sum; - } +static VNL_SSE_FORCE_INLINE T +dot_product(const T * x, const T * y, unsigned n) +{ + T sum(0); + for (unsigned i = 0; i < n; ++i) + sum += x[i] * y[i]; + return sum; +} - static VNL_SSE_FORCE_INLINE T euclid_dist_sq(const T* x, const T* y, unsigned n) +static VNL_SSE_FORCE_INLINE T +euclid_dist_sq(const T * x, const T * y, unsigned n) +{ + // IMS: Unable to optimise this any further for MSVC compiler + T sum(0); + --x; + --y; + while (n != 0) { - // IMS: Unable to optimise this any further for MSVC compiler - T sum(0); - --x; - --y; - while (n!=0) - { - const T diff = x[n] - y[n]; - sum += diff*diff; - --n; - } - return sum; + const T diff = x[n] - y[n]; + sum += diff * diff; + --n; } + return sum; +} - static VNL_SSE_FORCE_INLINE void vector_x_matrix(const T* v, const T* m, T* r, unsigned rows, unsigned cols) +static VNL_SSE_FORCE_INLINE void +vector_x_matrix(const T * v, const T * m, T * r, unsigned rows, unsigned cols) +{ + for (unsigned int j = 0; j < cols; ++j) { - for (unsigned int j=0; j 0) - if (*++v > tmp) - tmp = *v; - return tmp; - } +static VNL_SSE_FORCE_INLINE T +max(const T * v, unsigned n) +{ + if (n == 0) + return T(0); // the maximum of an empty set is undefined + T tmp = *v; + while (--n > 0) + if (*++v > tmp) + tmp = *v; + return tmp; +} - static VNL_SSE_FORCE_INLINE T min(const T* v, unsigned n) - { - if (n==0) return T(0); // the minimum of an empty set is undefined - T tmp = *v; - while (--n > 0) - if (*++v < tmp) - tmp = *v; - return tmp; - } +static VNL_SSE_FORCE_INLINE T +min(const T * v, unsigned n) +{ + if (n == 0) + return T(0); // the minimum of an empty set is undefined + T tmp = *v; + while (--n > 0) + if (*++v < tmp) + tmp = *v; + return tmp; +} - static VNL_SSE_FORCE_INLINE unsigned arg_max(const T* v, unsigned n) - { - if (n==0) return unsigned(-1); // the maximum of an empty set is undefined - T tmp = *v; - unsigned idx = 0; - for (unsigned i=1; i tmp) - tmp = *v, idx = i; - return idx; - } +static VNL_SSE_FORCE_INLINE unsigned +arg_max(const T * v, unsigned n) +{ + if (n == 0) + return unsigned(-1); // the maximum of an empty set is undefined + T tmp = *v; + unsigned idx = 0; + for (unsigned i = 1; i < n; ++i) + if (*++v > tmp) + tmp = *v, idx = i; + return idx; +} - static VNL_SSE_FORCE_INLINE unsigned arg_min(const T* v, unsigned n) - { - if (n==0) return unsigned(-1); // the minimum of an empty set is undefined - T tmp = *v; - unsigned idx = 0; - for (unsigned i=1; i class vnl_sym_matrix; +template +class vnl_sym_matrix; //: stores a symmetric matrix as just the diagonal and lower triangular part // vnl_sym_matrix stores a symmetric matrix for time and space efficiency. @@ -26,177 +27,254 @@ template class vnl_sym_matrix; template class VNL_EXPORT vnl_sym_matrix { - public: +public: //: Construct an empty symmetric matrix. - vnl_sym_matrix() : data_(nullptr), index_(nullptr) {} - - //: Construct a symmetric matrix of size nn by nn. - explicit vnl_sym_matrix(unsigned nn) - : data_(vnl_c_vector::allocate_T(nn * (nn + 1) / 2)), - index_(vnl_c_vector::allocate_Tptr(nn)), nn_(nn) { - setup_index(); } + vnl_sym_matrix() + : data_(nullptr) + , index_(nullptr) + {} + + //: Construct a symmetric matrix of size nn by nn. + explicit vnl_sym_matrix(unsigned nn) + : data_(vnl_c_vector::allocate_T(nn * (nn + 1) / 2)) + , index_(vnl_c_vector::allocate_Tptr(nn)) + , nn_(nn) + { + setup_index(); + } //: Construct a symmetric matrix with elements equal to data // Value should be stored row-wise, and contain the // n*(n+1)/2 diagonal and lower triangular elements - inline vnl_sym_matrix(T const * data, unsigned nn); + inline vnl_sym_matrix(const T * data, unsigned nn); //: Construct a symmetric matrix with all elements equal to value inline vnl_sym_matrix(unsigned nn, const T & value); //: Construct a symmetric matrix from a full matrix. // If NDEBUG is set, the symmetry of the matrix will be asserted. - inline explicit vnl_sym_matrix(vnl_matrix const& that); + inline explicit vnl_sym_matrix(const vnl_matrix & that); //: Copy constructor - inline vnl_sym_matrix(vnl_sym_matrix const& that); + inline vnl_sym_matrix(const vnl_sym_matrix & that); ~vnl_sym_matrix(); - vnl_sym_matrix& operator=(vnl_sym_matrix const& that); + vnl_sym_matrix & + operator=(const vnl_sym_matrix & that); // Operations---------------------------------------------------------------- //: In-place arithmetic operations - inline vnl_sym_matrix& operator*=(T v) { vnl_c_vector::scale(data_, data_, size(), v); return *this; } + inline vnl_sym_matrix & + operator*=(T v) + { + vnl_c_vector::scale(data_, data_, size(), v); + return *this; + } //: In-place arithmetic operations - inline vnl_sym_matrix& operator/=(T v) { vnl_c_vector::scale(data_, data_, size(), ((T)1)/v); return *this; } + inline vnl_sym_matrix & + operator/=(T v) + { + vnl_c_vector::scale(data_, data_, size(), ((T)1) / v); + return *this; + } // Data Access--------------------------------------------------------------- - inline T operator () (unsigned i, unsigned j) const { + inline T + operator()(unsigned i, unsigned j) const + { return (i > j) ? index_[i][j] : index_[j][i]; } - inline T& operator () (unsigned i, unsigned j) { + inline T & + operator()(unsigned i, unsigned j) + { return (i > j) ? index_[i][j] : index_[j][i]; } //: Access a half-row of data. // Only the first i+1 values from this pointer are valid. - inline const T* operator [] (unsigned i) const { - assert (i < nn_); + inline const T * + operator[](unsigned i) const + { + assert(i < nn_); return index_[i]; } //: fast access, however i >= j - inline T fast (unsigned i, unsigned j) const { - assert (i >= j); + inline T + fast(unsigned i, unsigned j) const + { + assert(i >= j); return index_[i][j]; } //: fast access, however i >= j - inline T& fast (unsigned i, unsigned j) { - assert (i >= j); + inline T & + fast(unsigned i, unsigned j) + { + assert(i >= j); return index_[i][j]; } // iterators - typedef T* iterator; - inline iterator begin() { return data_; } - inline iterator end() { return data_ + size(); } - typedef const T* const_iterator; - inline const_iterator begin() const { return data_; } - inline const_iterator end() const { return data_ + size(); } + typedef T * iterator; + inline iterator + begin() + { + return data_; + } + inline iterator + end() + { + return data_ + size(); + } + typedef const T * const_iterator; + inline const_iterator + begin() const + { + return data_; + } + inline const_iterator + end() const + { + return data_ + size(); + } //: Return the total number of elements stored by the matrix. // Since vnl_sym_matrix only stores the diagonal and lower // triangular elements and must be square, this returns // n*(n+1)/2, where n == rows() == cols(). - inline unsigned int size() const { return nn_ * (nn_ + 1) / 2; } + inline unsigned int + size() const + { + return nn_ * (nn_ + 1) / 2; + } //: Return the number of rows. - inline unsigned int rows() const { return nn_; } + inline unsigned int + rows() const + { + return nn_; + } //: Return the number of columns. // A synonym for columns(). - inline unsigned int cols() const { return nn_; } + inline unsigned int + cols() const + { + return nn_; + } //: Return the number of columns. // A synonym for cols(). - inline unsigned int columns() const { return nn_; } + inline unsigned int + columns() const + { + return nn_; + } //: set element - inline void put (unsigned r, unsigned c, T const& v) + inline void + put(unsigned r, unsigned c, const T & v) { #if VNL_CONFIG_CHECK_BOUNDS - if (r >= this->nn_) // If invalid size specified + if (r >= this->nn_) // If invalid size specified vnl_error_matrix_row_index("put", r); // Raise exception - if (c >= this->nn_) // If invalid size specified + if (c >= this->nn_) // If invalid size specified vnl_error_matrix_col_index("put", c); // Raise exception #endif (r > c) ? index_[r][c] = v : index_[c][r] = v; } //: get element - inline T get (unsigned r, unsigned c) const + inline T + get(unsigned r, unsigned c) const { #if VNL_CONFIG_CHECK_BOUNDS - if (r >= this->nn_) // If invalid size specified + if (r >= this->nn_) // If invalid size specified vnl_error_matrix_row_index("get", r); // Raise exception - if (c >= this->nn_) // If invalid size specified + if (c >= this->nn_) // If invalid size specified vnl_error_matrix_col_index("get", c); // Raise exception #endif return (r > c) ? index_[r][c] : index_[c][r]; } // Need this until we add a vnl_sym_matrix ctor to vnl_matrix; - inline vnl_matrix as_matrix() const; + inline vnl_matrix + as_matrix() const; //: Resize matrix to n by n. // You will loose any existing data. - inline void set_size(int n); + inline void + set_size(int n); //: Return pointer to the lower triangular elements as a contiguous 1D C array; - T* data_block() { return data_; } + T * + data_block() + { + return data_; + } //: Return pointer to the lower triangular elements as a contiguous 1D C array; - T const* data_block() const { return data_; } + const T * + data_block() const + { + return data_; + } //: Set the first i values of row i // or the top i values of column i - void set_half_row (const vnl_vector &half_row, unsigned i); + void + set_half_row(const vnl_vector & half_row, unsigned i); //: Replaces the symmetric submatrix of THIS matrix with the elements of matrix m. // Starting at top left corner. Complexity is $O(m^2)$. - vnl_sym_matrix& update (vnl_sym_matrix const& m, unsigned diag_start=0); + vnl_sym_matrix & + update(const vnl_sym_matrix & m, unsigned diag_start = 0); //: Swap contents of m with THIS - void swap(vnl_sym_matrix &m) noexcept; + void + swap(vnl_sym_matrix & m) noexcept; - protected: -//: Set up the index array - void setup_index(); +protected: + //: Set up the index array + void + setup_index(); - T* data_{nullptr}; - T** index_{nullptr}; - unsigned nn_{0}; + T * data_{ nullptr }; + T ** index_{ nullptr }; + unsigned nn_{ 0 }; }; //: // \relatesalso vnl_sym_matrix -template VNL_EXPORT std::ostream& operator<< (std::ostream&, vnl_sym_matrix const&); +template +VNL_EXPORT std::ostream & +operator<<(std::ostream &, const vnl_sym_matrix &); template -inline vnl_sym_matrix::vnl_sym_matrix(T const * data, unsigned nn): - data_(vnl_c_vector::allocate_T(nn * (nn + 1) / 2)), - index_(vnl_c_vector::allocate_Tptr(nn)), - nn_(nn) +inline vnl_sym_matrix::vnl_sym_matrix(const T * data, unsigned nn) + : data_(vnl_c_vector::allocate_T(nn * (nn + 1) / 2)) + , index_(vnl_c_vector::allocate_Tptr(nn)) + , nn_(nn) { setup_index(); for (unsigned i = 0; i < nn_; ++i) for (unsigned j = 0; j <= i; ++j) - fast(i,j) = *(data++); + fast(i, j) = *(data++); } template -inline vnl_sym_matrix::vnl_sym_matrix(unsigned nn, const T & value): - data_(vnl_c_vector::allocate_T(nn * (nn + 1) / 2)), - index_(vnl_c_vector::allocate_Tptr(nn)), - nn_(nn) +inline vnl_sym_matrix::vnl_sym_matrix(unsigned nn, const T & value) + : data_(vnl_c_vector::allocate_T(nn * (nn + 1) / 2)) + , index_(vnl_c_vector::allocate_Tptr(nn)) + , nn_(nn) { setup_index(); vnl_c_vector::fill(data_, size(), value); @@ -204,47 +282,52 @@ inline vnl_sym_matrix::vnl_sym_matrix(unsigned nn, const T & value): template -inline vnl_sym_matrix::vnl_sym_matrix(vnl_matrix const& that): - data_(vnl_c_vector::allocate_T(that.rows() * (that.rows() + 1) / 2)), - index_(vnl_c_vector::allocate_Tptr(that.rows())), - nn_(that.rows()) +inline vnl_sym_matrix::vnl_sym_matrix(const vnl_matrix & that) + : data_(vnl_c_vector::allocate_T(that.rows() * (that.rows() + 1) / 2)) + , index_(vnl_c_vector::allocate_Tptr(that.rows())) + , nn_(that.rows()) { setup_index(); - assert (nn_ == that.cols()); + assert(nn_ == that.cols()); for (unsigned i = 0; i < nn_; ++i) for (unsigned j = 0; j <= i; ++j) { - assert( that(i,j) == that(j,i) ); - fast(i,j) = that(i,j); + assert(that(i, j) == that(j, i)); + fast(i, j) = that(i, j); } } template -inline vnl_sym_matrix::vnl_sym_matrix(vnl_sym_matrix const &that) - : data_(nullptr), index_(nullptr) { +inline vnl_sym_matrix::vnl_sym_matrix(const vnl_sym_matrix & that) + : data_(nullptr) + , index_(nullptr) +{ set_size(that.rows()); update(that); } //: Convert a vnl_sym_matrix to a vnl_matrix. template -inline vnl_matrix vnl_sym_matrix::as_matrix() const +inline vnl_matrix +vnl_sym_matrix::as_matrix() const { vnl_matrix ret(nn_, nn_); for (unsigned i = 0; i < nn_; ++i) for (unsigned j = 0; j <= i; ++j) - ret(i,j) = ret(j,i) = fast(i,j); + ret(i, j) = ret(j, i) = fast(i, j); return ret; } template -inline void vnl_sym_matrix::set_size(int n) +inline void +vnl_sym_matrix::set_size(int n) { - if (n == (int)nn_) return; + if (n == (int)nn_) + return; vnl_c_vector::deallocate(data_, static_cast(size())); - vnl_c_vector::deallocate(index_, static_cast( nn_)); + vnl_c_vector::deallocate(index_, static_cast(nn_)); nn_ = n; data_ = vnl_c_vector::allocate_T(size()); @@ -253,19 +336,25 @@ inline void vnl_sym_matrix::set_size(int n) setup_index(); } -template VNL_EXPORT -bool operator==(const vnl_sym_matrix &a, const vnl_sym_matrix &b); +template +VNL_EXPORT bool +operator==(const vnl_sym_matrix & a, const vnl_sym_matrix & b); -template VNL_EXPORT -bool operator==(const vnl_sym_matrix &a, const vnl_matrix &b); +template +VNL_EXPORT bool +operator==(const vnl_sym_matrix & a, const vnl_matrix & b); -template VNL_EXPORT -bool operator==(const vnl_matrix &a, const vnl_sym_matrix &b); +template +VNL_EXPORT bool +operator==(const vnl_matrix & a, const vnl_sym_matrix & b); //: Swap the contents of a and b. // \relatesalso vnl_sym_matrix template -inline void swap(vnl_sym_matrix &a, vnl_sym_matrix &b) noexcept -{ a.swap(b); } +inline void +swap(vnl_sym_matrix & a, vnl_sym_matrix & b) noexcept +{ + a.swap(b); +} #endif // vnl_sym_matrix_h_ diff --git a/core/vnl/vnl_sym_matrix.hxx b/core/vnl/vnl_sym_matrix.hxx index cf7555e4606..4aff5bfb024 100644 --- a/core/vnl/vnl_sym_matrix.hxx +++ b/core/vnl/vnl_sym_matrix.hxx @@ -14,44 +14,46 @@ // ========================================================================== //: Replaces the symmetric submatrix of THIS matrix, starting at top left corner, by the elements of matrix m. // O(m*m). -template -vnl_sym_matrix& vnl_sym_matrix::update (vnl_sym_matrix const& m, - unsigned diagonal_start) +template +vnl_sym_matrix & +vnl_sym_matrix::update(const vnl_sym_matrix & m, unsigned diagonal_start) { - unsigned int end_val = diagonal_start + m.nn_; -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) + const unsigned int end_val = diagonal_start + m.nn_; +#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) if (this->nn_ < end_val) - vnl_error_matrix_dimension ("vnl_sym_matrix::update", - end_val, end_val, m.nn_, m.nn_); + vnl_error_matrix_dimension("vnl_sym_matrix::update", end_val, end_val, m.nn_, m.nn_); #endif for (unsigned int i = diagonal_start; i < end_val; i++) for (unsigned int j = diagonal_start; j <= i; j++) - this->fast(i,j) = m.fast(i-diagonal_start,j-diagonal_start); + this->fast(i, j) = m.fast(i - diagonal_start, j - diagonal_start); return *this; } // ========================================================================== //: Swap contents of m with THIS template -void vnl_sym_matrix::swap(vnl_sym_matrix &m) noexcept +void +vnl_sym_matrix::swap(vnl_sym_matrix & m) noexcept { - unsigned nn = nn_; - T **index = index_; - T *data = data_; - nn_ =m.nn_; - index_ =m.index_; - data_ =m.data_; - m.nn_ =nn; - m.index_ =index; - m.data_ =data; + const unsigned nn = nn_; + T ** index = index_; + T * data = data_; + nn_ = m.nn_; + index_ = m.index_; + data_ = m.data_; + m.nn_ = nn; + m.index_ = index; + m.data_ = data; } // ========================================================================== template -vnl_sym_matrix& vnl_sym_matrix::operator=(vnl_sym_matrix const& that) +vnl_sym_matrix & +vnl_sym_matrix::operator=(const vnl_sym_matrix & that) { - if (&that == this) return *this; + if (&that == this) + return *this; set_size(that.rows()); update(that); @@ -60,32 +62,36 @@ vnl_sym_matrix& vnl_sym_matrix::operator=(vnl_sym_matrix const& that) // ========================================================================== template vnl_sym_matrix::~vnl_sym_matrix() - { - vnl_c_vector::deallocate(data_, static_cast( size() ) ); - vnl_c_vector::deallocate(index_, static_cast ( nn_ ) ); - } +{ + vnl_c_vector::deallocate(data_, static_cast(size())); + vnl_c_vector::deallocate(index_, static_cast(nn_)); +} template -void vnl_sym_matrix::setup_index() +void +vnl_sym_matrix::setup_index() { - T * data = data_; - for (unsigned i=0; i< nn_; ++i) { index_[i] = data; data += i+1; } + T * data = data_; + for (unsigned i = 0; i < nn_; ++i) + { + index_[i] = data; + data += i + 1; + } } // ========================================================================== //: Set the first i values of row i // or the top i values of column i template -void vnl_sym_matrix::set_half_row (const vnl_vector &half_row, unsigned i) +void +vnl_sym_matrix::set_half_row(const vnl_vector & half_row, unsigned i) { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - if (half_row.size() != i+1) - vnl_error_vector_dimension ("vnl_sym_matrix::set_half_row wrong size for half row", - half_row.size(), i+1); - if ( i > nn_) - vnl_error_vector_dimension ("vnl_sym_matrix::set_half_row wrong sizes", - i+1, rows()); +#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) + if (half_row.size() != i + 1) + vnl_error_vector_dimension("vnl_sym_matrix::set_half_row wrong size for half row", half_row.size(), i + 1); + if (i > nn_) + vnl_error_vector_dimension("vnl_sym_matrix::set_half_row wrong sizes", i + 1, rows()); #endif half_row.copy_out(index_[i]); } @@ -93,13 +99,14 @@ void vnl_sym_matrix::set_half_row (const vnl_vector &half_row, unsigned i) // ========================================================================== //: print in lower triangular form template -std::ostream& operator<< (std::ostream& s, const vnl_sym_matrix& M) +std::ostream & +operator<<(std::ostream & s, const vnl_sym_matrix & M) { - for (unsigned i=0; i& M) // ========================================================================== template -bool operator==(const vnl_sym_matrix &a, const vnl_sym_matrix &b) +bool +operator==(const vnl_sym_matrix & a, const vnl_sym_matrix & b) { - if (a.rows() != b.rows()) return false; - const T* a_data = a.data_block(); - const T* b_data = b.data_block(); + if (a.rows() != b.rows()) + return false; + const T * a_data = a.data_block(); + const T * b_data = b.data_block(); const unsigned mn = a.size(); for (unsigned i = 0; i < mn; ++i) - if (a_data[i] != b_data[i]) return false; + if (a_data[i] != b_data[i]) + return false; return true; } // ========================================================================== template -bool operator==(const vnl_sym_matrix &a, const vnl_matrix &b) +bool +operator==(const vnl_sym_matrix & a, const vnl_matrix & b) { - if (a.rows() != b.rows() || a.cols() != b.cols()) return false; + if (a.rows() != b.rows() || a.cols() != b.cols()) + return false; const unsigned n = a.rows(); - for (unsigned i=0; i< n; ++i) + for (unsigned i = 0; i < n; ++i) { - for (unsigned j=0; j &a, const vnl_matrix &b) // ========================================================================== template -bool operator==(const vnl_matrix &a, const vnl_sym_matrix &b) +bool +operator==(const vnl_matrix & a, const vnl_sym_matrix & b) { - return operator==(b,a); + return operator==(b, a); } // ========================================================================== #undef VNL_SYM_MATRIX_INSTANTIATE -#define VNL_SYM_MATRIX_INSTANTIATE(T) \ -template class VNL_EXPORT vnl_sym_matrix; \ -template VNL_EXPORT std::ostream& operator<< (std::ostream& s, vnl_sym_matrix const &); \ -template VNL_EXPORT bool operator==(const vnl_sym_matrix &a, const vnl_sym_matrix &b); \ -template VNL_EXPORT bool operator==(const vnl_sym_matrix &a, const vnl_matrix &b); \ -template VNL_EXPORT bool operator==(const vnl_matrix &a, const vnl_sym_matrix &b) +#define VNL_SYM_MATRIX_INSTANTIATE(T) \ + template class VNL_EXPORT vnl_sym_matrix; \ + template VNL_EXPORT std::ostream & operator<<(std::ostream & s, vnl_sym_matrix const &); \ + template VNL_EXPORT bool operator==(const vnl_sym_matrix & a, const vnl_sym_matrix & b); \ + template VNL_EXPORT bool operator==(const vnl_sym_matrix & a, const vnl_matrix & b); \ + template VNL_EXPORT bool operator==(const vnl_matrix & a, const vnl_sym_matrix & b) #endif // vnl_sym_matrix_hxx_ diff --git a/core/vnl/vnl_trace.h b/core/vnl/vnl_trace.h index 9c60e9b6eb5..f5f2035ab06 100644 --- a/core/vnl/vnl_trace.h +++ b/core/vnl/vnl_trace.h @@ -19,11 +19,12 @@ //: Calculate trace of a matrix // \relatesalso vnl_matrix template -T vnl_trace(vnl_matrix const& M) +T +vnl_trace(const vnl_matrix & M) { T sum(0); - const unsigned int N = M.rows() const& M) //: Calculate trace of a matrix // \relatesalso vnl_matrix_fixed template -T vnl_trace(vnl_matrix_fixed const& M) +T +vnl_trace(const vnl_matrix_fixed & M) { T sum(0); - for (unsigned int i=0; i& M_; - public: + const vnl_matrix & M_; +public: //: Make a vnl_transpose object referring to matrix M - vnl_transpose(const vnl_matrix& M): M_(M) {} + vnl_transpose(const vnl_matrix & M) + : M_(M) + {} //: Noisily convert a vnl_transpose to a matrix -#if ! VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS - explicit operator vnl_matrix () const { return M_.transpose(); } +#if !VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS + explicit + operator vnl_matrix() const + { + return M_.transpose(); + } #else -#if VXL_LEGACY_FUTURE_REMOVE - VXL_DEPRECATED_MSG("Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") -#endif - operator vnl_matrix () const { +# if VXL_LEGACY_FUTURE_REMOVE + VXL_DEPRECATED_MSG( + "Implicit cast conversion is dangerous.\nUSE: .as_matrix() or .as_ref() member function for clarity.") +# endif + operator vnl_matrix() const + { std::cerr << "vnl_transpose being converted to matrix -- help! I don't wanna go!\n"; return M_.transpose(); } #endif -//: Quietly convert a vnl_transpose to a matrix -vnl_matrix as_matrix( ) const { return M_.transpose(); } -#if ! VXL_LEGACY_FUTURE_REMOVE + //: Quietly convert a vnl_transpose to a matrix + vnl_matrix + as_matrix() const + { + return M_.transpose(); + } +#if !VXL_LEGACY_FUTURE_REMOVE VXL_DEPRECATED_MSG("Deprecated inconsistent name.\nUSE: .as_matrix() new consistent name.") - vnl_matrix asMatrix () const { return this->as_matrix(); } + vnl_matrix + asMatrix() const + { + return this->as_matrix(); + } #endif //: Return M' * O - vnl_matrix operator* (const vnl_matrix& O) { + vnl_matrix + operator*(const vnl_matrix & O) + { vnl_matrix ret(M_.columns(), O.columns()); vnl_fastops::AtB(ret, M_, O); return ret; } //: Return M' * O - vnl_vector operator* (const vnl_vector& O) { + vnl_vector + operator*(const vnl_vector & O) + { vnl_vector ret(M_.columns()); vnl_fastops::AtB(ret, M_, O); return ret; } //: Return A * B' - friend vnl_matrix operator* (const vnl_matrix& A, const vnl_transpose& B) { + friend vnl_matrix + operator*(const vnl_matrix & A, const vnl_transpose & B) + { vnl_matrix ret(A.rows(), B.M_.rows()); vnl_fastops::ABt(ret, A, B.M_); return ret; diff --git a/core/vnl/vnl_unary_function.h b/core/vnl/vnl_unary_function.h index 9bece4eae08..4b340d0de39 100644 --- a/core/vnl/vnl_unary_function.h +++ b/core/vnl/vnl_unary_function.h @@ -27,22 +27,29 @@ template class VNL_EXPORT vnl_unary_function { - public: -// typedef std::numeric_limits limits; +public: + // typedef std::numeric_limits limits; //: Apply the function. // The name is "f" rather than operator(), as the function will generally be // called through a pointer. Note that the function is NOT const when you subclass. - virtual Return f(Argument const& i) = 0; + virtual Return + f(const Argument & i) = 0; //: Return bounding cube of range (outputs) - virtual Return get_range_min() const; - virtual Return get_range_max() const; + virtual Return + get_range_min() const; + virtual Return + get_range_max() const; //: Copy should allocate a copy of this on the heap and return it. // If Subclasses do not implement this function, it will return null, but many // applications will never call it, so this may not be a problem for you. - virtual vnl_unary_function * Copy() const { return nullptr; } + virtual vnl_unary_function * + Copy() const + { + return nullptr; + } virtual ~vnl_unary_function() = default; }; diff --git a/core/vnl/vnl_unary_function.hxx b/core/vnl/vnl_unary_function.hxx index c1507559497..64f81f3d257 100644 --- a/core/vnl/vnl_unary_function.hxx +++ b/core/vnl/vnl_unary_function.hxx @@ -27,19 +27,20 @@ //: Return bounding cube of range (outputs) template -RETURN vnl_unary_function::get_range_min() const +RETURN +vnl_unary_function::get_range_min() const { return std::numeric_limits::min(); } //: Return bounding cube of range (outputs) template -RETURN vnl_unary_function::get_range_max() const +RETURN +vnl_unary_function::get_range_max() const { return std::numeric_limits::max(); } -#define VNL_UNARY_FUNCTION_INSTANTIATE(S,T) \ -template class VNL_EXPORT vnl_unary_function +#define VNL_UNARY_FUNCTION_INSTANTIATE(S, T) template class VNL_EXPORT vnl_unary_function #endif // vnl_unary_function_hxx_ diff --git a/core/vnl/vnl_vector.h b/core/vnl/vnl_vector.h index 4e562de5b1d..2b65c811997 100644 --- a/core/vnl/vnl_vector.h +++ b/core/vnl/vnl_vector.h @@ -25,40 +25,70 @@ #include "vnl_error.h" #include "vnl/vnl_export.h" #ifndef NDEBUG -# if VNL_CONFIG_CHECK_BOUNDS -#include -# endif +# if VNL_CONFIG_CHECK_BOUNDS +# include +# endif #else -# undef VNL_CONFIG_CHECK_BOUNDS -# define VNL_CONFIG_CHECK_BOUNDS 0 -# undef ERROR_CHECKING +# undef VNL_CONFIG_CHECK_BOUNDS +# define VNL_CONFIG_CHECK_BOUNDS 0 +# undef ERROR_CHECKING #endif #include "vnl_sse.h" #include "vnl_numeric_traits.h" #include -template class vnl_vector; -template class vnl_matrix; +template +class vnl_vector; +template +class vnl_matrix; //---------------------------------------------------------------------- #define v vnl_vector #define m vnl_matrix -template VNL_EXPORT T dot_product(v const&, v const&); -template VNL_EXPORT T inner_product(v const&, v const&); -template VNL_EXPORT T bracket(v const &, m const &, v const &); -template VNL_EXPORT T cos_angle(v const&, v const& ); -template VNL_EXPORT double angle(v const&, v const&); -template VNL_EXPORT m outer_product(v const&, v const&); -template VNL_EXPORT v operator+(T, v const&); -template VNL_EXPORT v operator-(T, v const&); -template VNL_EXPORT v operator*(T, v const&); +template +VNL_EXPORT T +dot_product(v const &, v const &); +template +VNL_EXPORT T +inner_product(const v &, const v &); +template +VNL_EXPORT T +bracket(const v &, const m &, const v &); +template +VNL_EXPORT T +cos_angle(const v &, const v &); +template +VNL_EXPORT double +angle(const v &, const v &); +template +VNL_EXPORT m +outer_product(const v &, const v &); +template +VNL_EXPORT v +operator+(T, const v &); +template +VNL_EXPORT v +operator-(T, const v &); +template +VNL_EXPORT v +operator*(T, const v &); // also exists as method: template VNL_EXPORT v operator*(m const&, v const&); -template VNL_EXPORT v operator*(v const&, m const&); -template VNL_EXPORT v element_product(v const&,v const&); -template VNL_EXPORT v element_quotient(v const&,v const&); -template VNL_EXPORT T vnl_vector_ssd(v const&, v const&); -template VNL_EXPORT void swap(v &, v &) noexcept; +template +VNL_EXPORT v +operator*(const v &, const m &); +template +VNL_EXPORT v +element_product(const v &, const v &); +template +VNL_EXPORT v +element_quotient(const v &, const v &); +template +VNL_EXPORT T +vnl_vector_ssd(const v &, const v &); +template +VNL_EXPORT void +swap(v &, v &) noexcept; #undef v #undef m @@ -73,10 +103,10 @@ template VNL_EXPORT void swap(v &, v &) noexcept; // time, use vnl_vector_fixed* or vnl_T_n (e.g. vnl_double_3). // // NOTE: Vectors are indexed from zero! Thus valid elements are [0,size()-1]. -template +template class VNL_EXPORT vnl_vector { - public: +public: friend class vnl_matrix; //: Creates an empty vector. O(1). @@ -86,18 +116,18 @@ class VNL_EXPORT vnl_vector explicit vnl_vector(size_t len); //: Creates a vector containing n elements, all set to v0. - vnl_vector(size_t len, T const& v0); + vnl_vector(size_t len, const T & v0); //: Creates a vector containing len elements, with the first n // elements taken from the array values[]. O(n). - vnl_vector(size_t len, size_t n, T const values[]); + vnl_vector(size_t len, size_t n, const T values[]); //: Creates a vector containing len elements, initialized with values from // a data block. - vnl_vector(T const* data_block,size_t n); + vnl_vector(const T * data_block, size_t n); //: Copy constructor. - vnl_vector(vnl_vector const&); + vnl_vector(const vnl_vector &); // NOTE: move-assignment must be allowed to throw an exception, because we need to maintain // backwards compatibility and the move-construction & move-aasignment @@ -106,7 +136,8 @@ class VNL_EXPORT vnl_vector //: Move-constructor. vnl_vector(vnl_vector &&); //: Move-assignment operator - vnl_vector& operator=(vnl_vector&& rhs); + vnl_vector & + operator=(vnl_vector && rhs); //: Destructor /** This destructor *must* be virtual to ensure that the vnl_vector_ref subclass destructor @@ -114,154 +145,204 @@ class VNL_EXPORT vnl_vector virtual ~vnl_vector(); //: Return the length, number of elements, dimension of this vector. - size_t size() const { return this->num_elmts; } + size_t + size() const + { + return this->num_elmts; + } //: Put value at given position in vector. - inline void put(size_t i, T const& v); + inline void + put(size_t i, const T & v); //: Get value at element i - inline T get(size_t i) const; + inline T + get(size_t i) const; //: Set all values to v - vnl_vector& fill(T const& v); + vnl_vector & + fill(const T & v); //: Sets elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - vnl_vector& copy_in(T const * ptr); + vnl_vector & + copy_in(const T * ptr); //: Copy elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - void copy_out(T *) const; // from vector to array[]. + void + copy_out(T *) const; // from vector to array[]. //: Sets elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - vnl_vector& set(T const *ptr) { return copy_in(ptr); } + vnl_vector & + set(const T * ptr) + { + return copy_in(ptr); + } //: Return reference to the element at specified index. // There are assert style boundary checks - #define NDEBUG to turn them off. - T & operator()(size_t i) + T & + operator()(size_t i) { #if VNL_CONFIG_CHECK_BOUNDS - assert(i& operator=(T const&v) { fill(v); return *this; } + vnl_vector & + operator=(const T & v) + { + fill(v); + return *this; + } //: Copy operator - vnl_vector& operator=(vnl_vector const& rhs); + vnl_vector & + operator=(const vnl_vector & rhs); //: Add scalar value to all elements - vnl_vector& operator+=(T ); + vnl_vector & operator+=(T); //: Subtract scalar value from all elements - vnl_vector& operator-=(T value) { return *this += T(-value); } + vnl_vector & + operator-=(T value) + { + return *this += T(-value); + } //: Multiply all elements by scalar - vnl_vector& operator*=(T ); + vnl_vector & operator*=(T); //: Divide all elements by scalar - vnl_vector& operator/=(T ); + vnl_vector & operator/=(T); //: Add rhs to this and return *this - vnl_vector& operator+=(vnl_vector const& rhs); + vnl_vector & + operator+=(const vnl_vector & rhs); //: Subtract rhs from this and return *this - vnl_vector& operator-=(vnl_vector const& rhs); + vnl_vector & + operator-=(const vnl_vector & rhs); //: *this = M*(*this) where M is a suitable matrix. // this is treated as a column vector - vnl_vector& pre_multiply(vnl_matrix const& M); + vnl_vector & + pre_multiply(const vnl_matrix & M); //: *this = (*this)*M where M is a suitable matrix. // this is treated as a row vector - vnl_vector& post_multiply(vnl_matrix const& M); + vnl_vector & + post_multiply(const vnl_matrix & M); //: *this = (*this)*M where M is a suitable matrix. // this is treated as a row vector - vnl_vector& operator*=(vnl_matrix const& m) { return this->post_multiply(m); } + vnl_vector & + operator*=(const vnl_matrix & m) + { + return this->post_multiply(m); + } //: Unary plus operator // Return new vector = (*this) - vnl_vector operator+() const { return *this; } + vnl_vector + operator+() const + { + return *this; + } //: Unary minus operator // Return new vector = -1*(*this) - vnl_vector::signed_t> operator-() const; + vnl_vector::signed_t> + operator-() const; - vnl_vector operator+(T v) const { + vnl_vector + operator+(T v) const + { vnl_vector result(this->size()); - std::transform(this->begin(), this->end(), result.begin(), - [v](T d) -> T { return d + v; }); + std::transform(this->begin(), this->end(), result.begin(), [v](T d) -> T { return d + v; }); return result; } - vnl_vector operator-(T v) const { + vnl_vector + operator-(T v) const + { vnl_vector result(this->size()); - std::transform(this->begin(), this->end(), result.begin(), - [v](T d) -> T { return d - v; }); + std::transform(this->begin(), this->end(), result.begin(), [v](T d) -> T { return d - v; }); return result; } - vnl_vector operator*(T v) const { + vnl_vector + operator*(T v) const + { vnl_vector result(this->size()); - std::transform(this->begin(), this->end(), result.begin(), - [v](T d) -> T { return d * v; }); + std::transform(this->begin(), this->end(), result.begin(), [v](T d) -> T { return d * v; }); return result; } - vnl_vector operator/(T v) const { + vnl_vector + operator/(T v) const + { vnl_vector result(this->size()); - std::transform(this->begin(), this->end(), result.begin(), - [v](T d) -> T { return d / v; }); + std::transform(this->begin(), this->end(), result.begin(), [v](T d) -> T { return d / v; }); return result; } - vnl_vector operator+(vnl_vector const &v) const { + vnl_vector + operator+(const vnl_vector & v) const + { vnl_vector result(this->size()); #ifndef NDEBUG if (this->size() != v.size()) - vnl_error_vector_dimension("vnl_vector<>::operator+()", this->size(), - v.size()); + vnl_error_vector_dimension("vnl_vector<>::operator+()", this->size(), v.size()); #endif - std::transform(this->begin(), this->end(), v.begin(), result.begin(), - std::plus()); + std::transform(this->begin(), this->end(), v.begin(), result.begin(), std::plus()); return result; } - vnl_vector operator-(vnl_vector const &v) const { + vnl_vector + operator-(const vnl_vector & v) const + { vnl_vector result(this->size()); #ifndef NDEBUG if (this->size() != v.size()) - vnl_error_vector_dimension("vnl_vector<>::operator-()", this->size(), - v.size()); + vnl_error_vector_dimension("vnl_vector<>::operator-()", this->size(), v.size()); #endif - std::transform(this->begin(), this->end(), v.begin(), result.begin(), - std::minus()); + std::transform(this->begin(), this->end(), v.begin(), result.begin(), std::minus()); return result; } - vnl_vector operator*(vnl_matrix const &M) const { + vnl_vector + operator*(const vnl_matrix & M) const + { vnl_vector result(M.cols()); #ifndef NDEBUG if (this->size() != M.rows()) - vnl_error_vector_dimension("vnl_vector<>::operator*(M)", this->size(), - M.rows()); + vnl_error_vector_dimension("vnl_vector<>::operator*(M)", this->size(), M.rows()); #endif - vnl_sse::vector_x_matrix(this->begin(), M.begin(), result.begin(), - M.rows(), M.cols()); + vnl_sse::vector_x_matrix(this->begin(), M.begin(), result.begin(), M.rows(), M.cols()); return result; } @@ -269,134 +350,244 @@ class VNL_EXPORT vnl_vector //: Access the contiguous block storing the elements in the vector. O(1). // data_block()[0] is the first element of the vector - T const* data_block() const { return data; } + const T * + data_block() const + { + return data; + } //: Access the contiguous block storing the elements in the vector. O(1). // data_block()[0] is the first element of the vector - T * data_block() { return data; } + T * + data_block() + { + return data; + } //: Type defs for iterators typedef T element_type; - typedef size_t size_type; + typedef size_t size_type; //: Type defs for iterators - typedef T *iterator; + typedef T * iterator; //: Iterator pointing to start of data - iterator begin() { return data; } + iterator + begin() + { + return data; + } //: Iterator pointing to element beyond end of data - iterator end() { return data+num_elmts; } + iterator + end() + { + return data + num_elmts; + } //: Const iterator type - typedef T const *const_iterator; + typedef const T * const_iterator; //: Iterator pointing to start of data - const_iterator begin() const { return data; } + const_iterator + begin() const + { + return data; + } //: Iterator pointing to element beyond end of data - const_iterator end() const { return data+num_elmts; } + const_iterator + end() const + { + return data + num_elmts; + } //: Analogous to std::vector::front(). - T& front() { return *data; } + T & + front() + { + return *data; + } //: Analogous to std::vector::back(). - T& back() { return data[num_elmts - 1]; } + T & + back() + { + return data[num_elmts - 1]; + } //: Analogous to std::vector::front() (const overload). - const T& front() const { return *data; } + const T & + front() const + { + return *data; + } //: Analogous to std::vector::back() (const overload). - const T& back() const { return data[num_elmts - 1]; } + const T & + back() const + { + return data[num_elmts - 1]; + } //: Return a reference to this. // Useful in code which would prefer not to know if its argument // is a vector, vector_ref or a vector_fixed. Note that it doesn't // return a vector_ref, so it's only useful in templates or macros. - vnl_vector const& as_ref() const { return *this; } + const vnl_vector & + as_ref() const + { + return *this; + } //: Return a reference to this. - vnl_vector& as_ref() { return *this; } + vnl_vector & + as_ref() + { + return *this; + } //: Applies function to elements vnl_vector apply(T (*f)(T)) const; //: Applies function to elements - vnl_vector apply(T (*f)(T const&)) const; + vnl_vector apply(T (*f)(const T &)) const; //: Returns a subvector specified by the start index and length. O(n). - vnl_vector extract(size_t len, size_t start=0) const; + vnl_vector + extract(size_t len, size_t start = 0) const; //: Replaces elements with index beginning at start, by values of v. O(n). - vnl_vector& update(vnl_vector const&, size_t start=0); + vnl_vector & + update(const vnl_vector &, size_t start = 0); // norms etc typedef typename vnl_c_vector::abs_t abs_t; //: Return sum of squares of elements - abs_t squared_magnitude() const { return vnl_c_vector::two_nrm2(begin(), size()); } + abs_t + squared_magnitude() const + { + return vnl_c_vector::two_nrm2(begin(), size()); + } //: Return magnitude (length) of vector - abs_t magnitude() const { return two_norm(); } + abs_t + magnitude() const + { + return two_norm(); + } //: Return sum of absolute values of the elements - abs_t one_norm() const { return vnl_c_vector::one_norm(begin(), size()); } + abs_t + one_norm() const + { + return vnl_c_vector::one_norm(begin(), size()); + } //: Return sqrt of sum of squares of values of elements - abs_t two_norm() const { return vnl_c_vector::two_norm(begin(), size()); } + abs_t + two_norm() const + { + return vnl_c_vector::two_norm(begin(), size()); + } //: Return largest absolute element value - abs_t inf_norm() const { return vnl_c_vector::inf_norm(begin(), size()); } + abs_t + inf_norm() const + { + return vnl_c_vector::inf_norm(begin(), size()); + } //: Normalise by dividing through by the magnitude - vnl_vector& normalize() { vnl_c_vector::normalize(begin(), size()); return *this; } + vnl_vector & + normalize() + { + vnl_c_vector::normalize(begin(), size()); + return *this; + } // These next 6 functions are should really be helper functions since they aren't // really proper functions on a vector in a philosophical sense. //: Root Mean Squares of values - abs_t rms() const { return vnl_c_vector::rms_norm(begin(), size()); } + abs_t + rms() const + { + return vnl_c_vector::rms_norm(begin(), size()); + } //: Smallest value - T min_value() const { return vnl_c_vector::min_value(begin(), size()); } + T + min_value() const + { + return vnl_c_vector::min_value(begin(), size()); + } //: Largest value - T max_value() const { return vnl_c_vector::max_value(begin(), size()); } + T + max_value() const + { + return vnl_c_vector::max_value(begin(), size()); + } //: Location of smallest value - size_t arg_min() const { return vnl_c_vector::arg_min(begin(), size()); } + size_t + arg_min() const + { + return vnl_c_vector::arg_min(begin(), size()); + } //: Location of largest value - size_t arg_max() const { return vnl_c_vector::arg_max(begin(), size()); } + size_t + arg_max() const + { + return vnl_c_vector::arg_max(begin(), size()); + } //: Mean of values in vector - T mean() const { return vnl_c_vector::mean(begin(), size()); } + T + mean() const + { + return vnl_c_vector::mean(begin(), size()); + } //: Sum of values in a vector - T sum() const { return vnl_c_vector::sum(begin(), size()); } + T + sum() const + { + return vnl_c_vector::sum(begin(), size()); + } //: Reverse the order of the elements // Element i swaps with element size()-1-i - vnl_vector& flip(); + vnl_vector & + flip(); //: Reverse the order of the elements from index b to 1-e, inclusive. // When b = 0 and e = size(), this is equivalent to flip(); - vnl_vector& flip(const size_t &b, const size_t &e); + vnl_vector & + flip(const size_t & b, const size_t & e); //: Roll the vector forward by the specified shift. // The shift is cyclical, such that the elements which // are displaced from the end reappear at the beginning. // Negative shifts and shifts >= the length of the array are supported. // A new vector is returned; the underlying data is unchanged. - vnl_vector roll(const int &shift) const; + vnl_vector + roll(const int & shift) const; //: Roll the vector forward by the specified shift. // The shift is cyclical, such that the elements which // are displaced from the end reappear at the beginning. // Negative shifts and shifts >= the length of the array are supported. // - vnl_vector& roll_inplace(const int &shift); + vnl_vector & + roll_inplace(const int & shift); //: Set this to that and that to this - void swap(vnl_vector & that) noexcept; + void + swap(vnl_vector & that) noexcept; //: Check that size()==sz if not, abort(); // This function does or tests nothing if NDEBUG is defined - void assert_size(size_t VXL_USED_IN_DEBUG(sz) ) const { + void + assert_size(size_t VXL_USED_IN_DEBUG(sz)) const + { #ifndef NDEBUG assert_size_internal(sz); #endif @@ -404,92 +595,120 @@ class VNL_EXPORT vnl_vector //: Check that this is finite if not, abort(); // This function does or tests nothing if NDEBUG is defined - void assert_finite() const { + void + assert_finite() const + { #ifndef NDEBUG assert_finite_internal(); #endif } //: Return true if it's finite - bool is_finite() const; + bool + is_finite() const; //: Return true iff all the entries are zero. - bool is_zero() const; + bool + is_zero() const; //: Return true iff the size is zero. - bool empty() const { return !data || !num_elmts; } + bool + empty() const + { + return !data || !num_elmts; + } //: Return true if all elements of vectors are equal, within given tolerance - bool is_equal(vnl_vector const& rhs, double tol) const; + bool + is_equal(const vnl_vector & rhs, double tol) const; //: Return true if *this == v - bool operator_eq(vnl_vector const& v) const; + bool + operator_eq(const vnl_vector & v) const; //: Equality test - bool operator==(vnl_vector const &that) const { return this->operator_eq(that); } + bool + operator==(const vnl_vector & that) const + { + return this->operator_eq(that); + } //: Inequality test - bool operator!=(vnl_vector const &that) const { return !this->operator_eq(that); } + bool + operator!=(const vnl_vector & that) const + { + return !this->operator_eq(that); + } //: Resize to n elements. // This is a destructive resize, in that the old data is lost if size() != \a n before the call. // If size() is already \a n, this is a null operation. - bool set_size(size_t n); + bool + set_size(size_t n); //: Make the vector as if it had been default-constructed. - void clear(); + void + clear(); //: Read from text stream - bool read_ascii(std::istream& s); + bool + read_ascii(std::istream & s); //: Read from text stream - static vnl_vector read(std::istream& s); + static vnl_vector + read(std::istream & s); //: Support external memory - void set_data(T * datain, size_t sz, bool LetArrayManageMemory) + void + set_data(T * datain, size_t sz, bool LetArrayManageMemory) { if (m_LetArrayManageMemory) { vnl_vector::destroy(); } - vnl_vector::protected_set_data( datain, sz, m_LetArrayManageMemory ); + vnl_vector::protected_set_data(datain, sz, m_LetArrayManageMemory); m_LetArrayManageMemory = LetArrayManageMemory; } - void set_data_same_size(T * datain, bool LetArrayManageMemory) + void + set_data_same_size(T * datain, bool LetArrayManageMemory) { set_data(datain, this->size(), LetArrayManageMemory); } - protected: - vnl_vector( size_t ext_num_elmts, T * extdata, bool manage_own_memory ) + +protected: + vnl_vector(size_t ext_num_elmts, T * extdata, bool manage_own_memory) : num_elmts{ ext_num_elmts } , data{ extdata } , m_LetArrayManageMemory{ manage_own_memory } - { } + {} -//#if !VXL_LEGACY_FUTURE_REMOVE + // #if !VXL_LEGACY_FUTURE_REMOVE /* * This function is a work around for transitioning to data members * being private - */ - void protected_set_data(T * indata, size_t nelmts, bool manage_own_memory) + */ + void + protected_set_data(T * indata, size_t nelmts, bool manage_own_memory) { - this->data= indata ; - this->num_elmts = nelmts; - this->m_LetArrayManageMemory = manage_own_memory; + this->data = indata; + this->num_elmts = nelmts; + this->m_LetArrayManageMemory = manage_own_memory; } -//#endif + // #endif - void assert_size_internal(size_t sz) const; - void assert_finite_internal() const; - void destroy(); + void + assert_size_internal(size_t sz) const; + void + assert_finite_internal() const; + void + destroy(); -#if ! VXL_USE_HISTORICAL_PROTECTED_IVARS - private: +#if !VXL_USE_HISTORICAL_PROTECTED_IVARS +private: #endif - size_t num_elmts{0}; // Number of elements (length) - T* data{nullptr}; // Pointer to the actual data - bool m_LetArrayManageMemory{true}; - + size_t num_elmts{ 0 }; // Number of elements (length) + T * data{ nullptr }; // Pointer to the actual data + bool m_LetArrayManageMemory{ true }; }; @@ -500,12 +719,12 @@ class VNL_EXPORT vnl_vector // Range check is performed. template -inline T vnl_vector -::get(size_t i) const +inline T +vnl_vector::get(size_t i) const { #if VNL_CONFIG_CHECK_BOUNDS - if (i >= this->size()) // If invalid index specified - vnl_error_vector_index("get", i); // Raise exception + if (i >= this->size()) // If invalid index specified + vnl_error_vector_index("get", i); // Raise exception #endif return this->data[i]; } @@ -514,26 +733,27 @@ ::get(size_t i) const // Range check is performed. template -inline void vnl_vector -::put(size_t i, T const& v) +inline void +vnl_vector::put(size_t i, const T & v) { #if VNL_CONFIG_CHECK_BOUNDS - if (i >= this->size()) // If invalid index specified + if (i >= this->size()) // If invalid index specified vnl_error_vector_index("put", i); // Raise exception #endif - this->data[i] = v; // Assign data value + this->data[i] = v; // Assign data value } //: multiply matrix and (column) vector. O(m*n). // \relatesalso vnl_vector // \relatesalso vnl_matrix -template -inline vnl_vector operator*(vnl_matrix const& M, vnl_vector const& v) +template +inline vnl_vector +operator*(const vnl_matrix & M, const vnl_vector & v) { vnl_vector result(M.rows()); #ifndef NDEBUG if (M.cols() != v.size()) - vnl_error_vector_dimension ("vnl_vector<>::operator*(M, v)", M.cols(), v.size()); + vnl_error_vector_dimension("vnl_vector<>::operator*(M, v)", M.cols(), v.size()); #endif vnl_sse::matrix_x_vector(M.begin(), v.begin(), result.begin(), M.rows(), M.cols()); return result; @@ -541,41 +761,49 @@ inline vnl_vector operator*(vnl_matrix const& M, vnl_vector const& v) //: add scalar and vector. O(n). // \relatesalso vnl_vector -template -inline vnl_vector operator+(T s, vnl_vector const& v) +template +inline vnl_vector +operator+(T s, const vnl_vector & v) { return v.operator+(s); } //: subtract vector from scalar. O(n). // \relatesalso vnl_vector -template -inline vnl_vector operator-(T s, vnl_vector const& v) +template +inline vnl_vector +operator-(T s, const vnl_vector & v) { vnl_vector result(v.size()); - for(size_t i=0; i< result.size(); ++i) - result[i]= s - v[i]; + for (size_t i = 0; i < result.size(); ++i) + result[i] = s - v[i]; return result; } //: multiply scalar and vector. O(n). // \relatesalso vnl_vector -template -inline vnl_vector operator*(T s, vnl_vector const& v) +template +inline vnl_vector +operator*(T s, const vnl_vector & v) { - return v*s; + return v * s; } //: Interchange the two vectors // \relatesalso vnl_vector -template -inline void swap(vnl_vector &a, vnl_vector &b) noexcept { a.swap(b); } +template +inline void +swap(vnl_vector & a, vnl_vector & b) noexcept +{ + a.swap(b); +} //: Euclidean Distance between two vectors. // Sum of Differences squared. // \relatesalso vnl_vector -template -inline T vnl_vector_ssd(vnl_vector const& v1, vnl_vector const& v2) +template +inline T +vnl_vector_ssd(const vnl_vector & v1, const vnl_vector & v2) { #ifndef NDEBUG if (v1.size() != v2.size()) @@ -588,9 +816,13 @@ inline T vnl_vector_ssd(vnl_vector const& v1, vnl_vector const& v2) //: Write vector to a std::ostream // \relatesalso vnl_vector -template VNL_EXPORT std::ostream& operator<<(std::ostream &, vnl_vector const&); +template +VNL_EXPORT std::ostream & +operator<<(std::ostream &, const vnl_vector &); //: Read vector from a std::istream // \relatesalso vnl_vector -template VNL_EXPORT std::istream& operator>>(std::istream &, vnl_vector &); +template +VNL_EXPORT std::istream & +operator>>(std::istream &, vnl_vector &); #endif // vnl_vector_h_ diff --git a/core/vnl/vnl_vector.hxx b/core/vnl/vnl_vector.hxx index 1790bcd9282..b023cfd472f 100644 --- a/core/vnl/vnl_vector.hxx +++ b/core/vnl/vnl_vector.hxx @@ -53,34 +53,36 @@ //-------------------------------------------------------------------------------- // This macro allocates the dynamic storage used by a vnl_vector. -#define vnl_vector_alloc_blah(size) \ -do { /* Macro needs to be a single statement to allow semicolon at macro end */ \ - assert(this->m_LetArrayManageMemory); /*Resizing memory requires management rights */ \ - this->num_elmts = (size); \ - this->data = (size) ? vnl_c_vector::allocate_T(size) : nullptr; \ -} while(false) +#define vnl_vector_alloc_blah(size) \ + do \ + { /* Macro needs to be a single statement to allow semicolon at macro end */ \ + assert(this->m_LetArrayManageMemory); /*Resizing memory requires management rights */ \ + this->num_elmts = (size); \ + this->data = (size) ? vnl_c_vector::allocate_T(size) : nullptr; \ + } while (false) // This macro deallocates the dynamic storage used by a vnl_vector. -#define vnl_vector_free_blah \ -do { /* Macro needs to be a single statement to allow semicolon at macro end */ \ - if ( this->m_LetArrayManageMemory ) \ - { \ - if (this->data) \ - { \ - vnl_c_vector::deallocate(this->data, this->num_elmts); \ - } \ - } \ - else \ - { \ - this->data = nullptr; \ - this->num_elmts = 0; \ - } \ -} while(false) +#define vnl_vector_free_blah \ + do \ + { /* Macro needs to be a single statement to allow semicolon at macro end */ \ + if (this->m_LetArrayManageMemory) \ + { \ + if (this->data) \ + { \ + vnl_c_vector::deallocate(this->data, this->num_elmts); \ + } \ + } \ + else \ + { \ + this->data = nullptr; \ + this->num_elmts = 0; \ + } \ + } while (false) //: Creates a vector with specified length. O(n). // Elements are not initialized. -template -vnl_vector::vnl_vector (size_t len) +template +vnl_vector::vnl_vector(size_t len) { vnl_vector_alloc_blah(len); } @@ -88,75 +90,77 @@ vnl_vector::vnl_vector (size_t len) //: Creates a vector of specified length, and initialize all elements with value. O(n). -template -vnl_vector::vnl_vector (size_t len, T const& value) +template +vnl_vector::vnl_vector(size_t len, const T & value) { vnl_vector_alloc_blah(len); - if (this->data) //VS2012 Runtime Library's std::fill_n has debug assertion when data is null + if (this->data) // VS2012 Runtime Library's std::fill_n has debug assertion when data is null { - std::fill_n( this->data, len, value ); + std::fill_n(this->data, len, value); } } //: Creates a vector of specified length and initialize first n elements with values. O(n). -template -vnl_vector::vnl_vector (size_t len, size_t n, T const values[]) +template +vnl_vector::vnl_vector(size_t len, size_t n, const T values[]) { vnl_vector_alloc_blah(len); // If user specified values, initialize first n elements with values // n.b Assignment is used over universal initialization to avoid a // gcc 4.8.5 ICE. - const size_t copy_num = std::min(len,n); + const size_t copy_num = std::min(len, n); std::copy(values, values + copy_num, data); } //: Creates a new copy of vector v. O(n). -template -vnl_vector::vnl_vector (vnl_vector const& v) +template +vnl_vector::vnl_vector(const vnl_vector & v) { vnl_vector_alloc_blah(v.num_elmts); - if ( v.data ) { - std::copy( v.data, v.data + v.num_elmts, this->data ); + if (v.data) + { + std::copy(v.data, v.data + v.num_elmts, this->data); } } //: Move-constructs a vector. O(1). -template -vnl_vector::vnl_vector(vnl_vector&& rhs) +template +vnl_vector::vnl_vector(vnl_vector && rhs) { // Copy the data pointer and its length from the source object. this->operator=(std::move(rhs)); } //: Move-assigns rhs vector into lhs vector. O(1). -template -vnl_vector& vnl_vector::operator=(vnl_vector&& rhs) +template +vnl_vector & +vnl_vector::operator=(vnl_vector && rhs) { // Self-assignment detection if (&rhs != this) { - if(!rhs.m_LetArrayManageMemory) + if (!rhs.m_LetArrayManageMemory) { this->operator=(rhs); // Call non-move assignment operator. return *this; } - else if(!this->m_LetArrayManageMemory) + else if (!this->m_LetArrayManageMemory) { /* If `this` is managing own memory, then you are not allowed * to replace the data pointer * This code only works when the object is an vnl_matrix_ref correctly sized. * Undefined behavior if this->m_LetArrayManageMemory==false, * and rows,cols are not the same between `this` and rhs. */ - assert(rhs.num_elmts == this->num_elmts ); - std::copy( rhs.begin(), rhs.end(), this->begin() ); + assert(rhs.num_elmts == this->num_elmts); + std::copy(rhs.begin(), rhs.end(), this->begin()); } else { // Release any resource we're previously holding - if(this->data) + if (this->data) { vnl_c_vector::deallocate(this->data, this->num_elmts); } @@ -173,47 +177,52 @@ vnl_vector& vnl_vector::operator=(vnl_vector&& rhs) } - //: Creates a vector from a block array of data, stored row-wise. // Values in datablck are copied. O(n). -template -vnl_vector::vnl_vector (T const* datablck, size_t len) +template +vnl_vector::vnl_vector(const T * datablck, size_t len) { vnl_vector_alloc_blah(len); - std::copy( datablck, datablck + len, this->data ); + std::copy(datablck, datablck + len, this->data); } //------------------------------------------------------------ -template +template vnl_vector::~vnl_vector() { - if (data) destroy(); + if (data) + destroy(); } //: Frees up the array inside vector. O(1). -template -void vnl_vector::destroy() +template +void +vnl_vector::destroy() { vnl_vector_free_blah; } -template -void vnl_vector::clear() +template +void +vnl_vector::clear() { - if (data) { + if (data) + { destroy(); num_elmts = 0; data = nullptr; } } -template -bool vnl_vector::set_size(size_t n) +template +bool +vnl_vector::set_size(size_t n) { - if (this->data) { + if (this->data) + { // if no change in size, do not reallocate. if (this->num_elmts == n) return false; @@ -221,7 +230,8 @@ bool vnl_vector::set_size(size_t n) vnl_vector_free_blah; vnl_vector_alloc_blah(n); } - else { + else + { // this happens if the vector is default constructed. vnl_vector_alloc_blah(n); } @@ -237,12 +247,16 @@ bool vnl_vector::set_size(size_t n) // If the vector has nonzero size on input, read that many values. // Otherwise, read to EOF. template -bool vnl_vector::read_ascii(std::istream& s) +bool +vnl_vector::read_ascii(std::istream & s) { - bool size_known = (this->size() != 0); - if (size_known) { - for (size_t i = 0; i < this->size(); ++i) { - if ( ! (s >> (*this)(i)) ) { + const bool size_known = (this->size() != 0); + if (size_known) + { + for (size_t i = 0; i < this->size(); ++i) + { + if (!(s >> (*this)(i))) + { return false; } } @@ -253,7 +267,8 @@ bool vnl_vector::read_ascii(std::istream& s) std::vector allvals; size_t n = 0; T value; - while ( s >> value ) { + while (s >> value) + { allvals.push_back(value); ++n; } @@ -264,7 +279,8 @@ bool vnl_vector::read_ascii(std::istream& s) } template -vnl_vector vnl_vector::read(std::istream& s) +vnl_vector +vnl_vector::read(std::istream & s) { vnl_vector V; V.read_ascii(s); @@ -273,49 +289,55 @@ vnl_vector vnl_vector::read(std::istream& s) //: Sets all elements of a vector to a specified fill value. O(n). -template -vnl_vector& -vnl_vector::fill (T const& value) +template +vnl_vector & +vnl_vector::fill(const T & value) { - if (this->data) //VS2012 Runtime Library's std::fill_n has debug assertion when data is null + if (this->data) // VS2012 Runtime Library's std::fill_n has debug assertion when data is null { - std::fill_n( this->data, this->num_elmts, value ); + std::fill_n(this->data, this->num_elmts, value); } return *this; } //: Sets elements of a vector to those in an array. O(n). -template -vnl_vector& -vnl_vector::copy_in (T const *ptr) +template +vnl_vector & +vnl_vector::copy_in(const T * ptr) { - std::copy( ptr, ptr + this->num_elmts, this->data ); + std::copy(ptr, ptr + this->num_elmts, this->data); return *this; } //: Sets elements of an array to those in vector. O(n). -template -void vnl_vector::copy_out (T *ptr) const +template +void +vnl_vector::copy_out(T * ptr) const { - std::copy( this->data, this->data + this->num_elmts, ptr ); + std::copy(this->data, this->data + this->num_elmts, ptr); } //: Copies rhs vector into lhs vector. O(n). // Changes the dimension of lhs vector if necessary. -template -vnl_vector& vnl_vector::operator= (vnl_vector const& rhs) +template +vnl_vector & +vnl_vector::operator=(const vnl_vector & rhs) { - if (this != &rhs) { // make sure *this != m - if (rhs.data) { + if (this != &rhs) + { // make sure *this != m + if (rhs.data) + { this->set_size(rhs.size()); - if(rhs.data) { + if (rhs.data) + { std::copy(rhs.data, rhs.data + this->num_elmts, this->data); } } - else { + else + { // rhs is default-constructed. clear(); } @@ -325,8 +347,9 @@ vnl_vector& vnl_vector::operator= (vnl_vector const& rhs) //: Increments all elements of vector with value. O(n). -template -vnl_vector& vnl_vector::operator+= (T value) +template +vnl_vector & +vnl_vector::operator+=(T value) { for (size_t i = 0; i < this->num_elmts; i++) this->data[i] += value; @@ -335,8 +358,9 @@ vnl_vector& vnl_vector::operator+= (T value) //: Multiplies all elements of vector with value. O(n). -template -vnl_vector& vnl_vector::operator*= (T value) +template +vnl_vector & +vnl_vector::operator*=(T value) { for (size_t i = 0; i < this->num_elmts; i++) this->data[i] *= value; @@ -345,8 +369,9 @@ vnl_vector& vnl_vector::operator*= (T value) //: Divides all elements of vector by value. O(n). -template -vnl_vector& vnl_vector::operator/= (T value) +template +vnl_vector & +vnl_vector::operator/=(T value) { for (size_t i = 0; i < this->num_elmts; i++) this->data[i] /= value; @@ -356,12 +381,13 @@ vnl_vector& vnl_vector::operator/= (T value) //: Mutates lhs vector with its addition with rhs vector. O(n). -template -vnl_vector& vnl_vector::operator+= (vnl_vector const& rhs) +template +vnl_vector & +vnl_vector::operator+=(const vnl_vector & rhs) { #ifndef NDEBUG if (this->num_elmts != rhs.num_elmts) - vnl_error_vector_dimension ("operator+=", this->num_elmts, rhs.num_elmts); + vnl_error_vector_dimension("operator+=", this->num_elmts, rhs.num_elmts); #endif for (size_t i = 0; i < this->num_elmts; i++) this->data[i] += rhs.data[i]; @@ -371,12 +397,13 @@ vnl_vector& vnl_vector::operator+= (vnl_vector const& rhs) //: Mutates lhs vector with its subtraction with rhs vector. O(n). -template -vnl_vector& vnl_vector::operator-= (vnl_vector const& rhs) +template +vnl_vector & +vnl_vector::operator-=(const vnl_vector & rhs) { #ifndef NDEBUG if (this->num_elmts != rhs.num_elmts) - vnl_error_vector_dimension ("operator-=", this->num_elmts, rhs.num_elmts); + vnl_error_vector_dimension("operator-=", this->num_elmts, rhs.num_elmts); #endif for (size_t i = 0; i < this->num_elmts; i++) this->data[i] -= rhs.data[i]; @@ -386,102 +413,111 @@ vnl_vector& vnl_vector::operator-= (vnl_vector const& rhs) //: Pre-multiplies vector with matrix and stores result back in vector. // v = m * v. O(m*n). Vector is assumed a column matrix. -template -vnl_vector& vnl_vector::pre_multiply (vnl_matrix const& m) +template +vnl_vector & +vnl_vector::pre_multiply(const vnl_matrix & m) { #ifndef NDEBUG - if (m.columns() != this->num_elmts) // dimensions do not match? - vnl_error_vector_dimension ("operator*=", this->num_elmts, m.columns()); + if (m.columns() != this->num_elmts) // dimensions do not match? + vnl_error_vector_dimension("operator*=", this->num_elmts, m.columns()); #endif - T* temp= vnl_c_vector::allocate_T(m.rows()); // Temporary - for (size_t i = 0; i < m.rows(); i++) { // For each index - temp[i] = (T)0; // Initialize element value - for (size_t k = 0; k < this->num_elmts; k++) // Loop over column values - temp[i] += (m.get(i,k) * this->data[k]); // Multiply + T * temp = vnl_c_vector::allocate_T(m.rows()); // Temporary + for (size_t i = 0; i < m.rows(); i++) + { // For each index + temp[i] = (T)0; // Initialize element value + for (size_t k = 0; k < this->num_elmts; k++) // Loop over column values + temp[i] += (m.get(i, k) * this->data[k]); // Multiply } vnl_c_vector::deallocate(this->data, this->num_elmts); // Free up the data space - num_elmts = m.rows(); // Set new num_elmts - this->data = temp; // Pointer to new storage - return *this; // Return vector reference + num_elmts = m.rows(); // Set new num_elmts + this->data = temp; // Pointer to new storage + return *this; // Return vector reference } //: Post-multiplies vector with matrix and stores result back in vector. // v = v * m. O(m*n). Vector is assumed a row matrix. -template -vnl_vector& vnl_vector::post_multiply (vnl_matrix const& m) +template +vnl_vector & +vnl_vector::post_multiply(const vnl_matrix & m) { #ifndef NDEBUG - if (this->num_elmts != m.rows()) // dimensions do not match? - vnl_error_vector_dimension ("operator*=", this->num_elmts, m.rows()); + if (this->num_elmts != m.rows()) // dimensions do not match? + vnl_error_vector_dimension("operator*=", this->num_elmts, m.rows()); #endif - T* temp= vnl_c_vector::allocate_T(m.columns()); // Temporary - for (size_t i = 0; i < m.columns(); i++) { // For each index - temp[i] = (T)0; // Initialize element value + T * temp = vnl_c_vector::allocate_T(m.columns()); // Temporary + for (size_t i = 0; i < m.columns(); i++) + { // For each index + temp[i] = (T)0; // Initialize element value for (size_t k = 0; k < this->num_elmts; k++) // Loop over column values - temp[i] += (this->data[k] * m.get(k,i)); // Multiply + temp[i] += (this->data[k] * m.get(k, i)); // Multiply } vnl_c_vector::deallocate(this->data, num_elmts); // Free up the data space - num_elmts = m.columns(); // Set new num_elmts - this->data = temp; // Pointer to new storage - return *this; // Return vector reference + num_elmts = m.columns(); // Set new num_elmts + this->data = temp; // Pointer to new storage + return *this; // Return vector reference } //: Creates new vector containing the negation of THIS vector. O(n). -template -vnl_vector< typename vnl_numeric_traits::signed_t> vnl_vector::operator- () const +template +vnl_vector::signed_t> +vnl_vector::operator-() const { vnl_vector::signed_t> result(this->num_elmts); - for (size_t i = 0; i < this->num_elmts; i++) { - result(i) = -this->data[i]; // negate element + for (size_t i = 0; i < this->num_elmts; i++) + { + result(i) = -this->data[i]; // negate element } return result; } //: Replaces elements with index beginning at start, by values of v. O(n). -template -vnl_vector& vnl_vector::update (vnl_vector const& v, size_t start) +template +vnl_vector & +vnl_vector::update(const vnl_vector & v, size_t start) { - size_t stop = start + v.size(); + const size_t stop = start + v.size(); #ifndef NDEBUG - if ( stop > this->num_elmts) - vnl_error_vector_dimension ("update", stop-start, v.size()); + if (stop > this->num_elmts) + vnl_error_vector_dimension("update", stop - start, v.size()); #endif - //std::copy_n( v.data, stop - start, this->data + start ); + // std::copy_n( v.data, stop - start, this->data + start ); for (size_t i = start; i < stop; i++) - this->data[i] = v.data[i-start]; + this->data[i] = v.data[i - start]; return *this; } //: Returns a subvector specified by the start index and length. O(n). -template -vnl_vector vnl_vector::extract (size_t len, size_t start) const +template +vnl_vector +vnl_vector::extract(size_t len, size_t start) const { #ifndef NDEBUG size_t stop = start + len; if (this->num_elmts < stop) - vnl_error_vector_dimension ("extract", stop-start, len); + vnl_error_vector_dimension("extract", stop - start, len); #endif vnl_vector result(len); - //std::copy_n( this->data + start, len, result.data ); + // std::copy_n( this->data + start, len, result.data ); for (size_t i = 0; i < len; i++) - result.data[i] = data[start+i]; + result.data[i] = data[start + i]; return result; } //: Returns new vector whose elements are the products v1[i]*v2[i]. O(n). -template -vnl_vector element_product (vnl_vector const& v1, vnl_vector const& v2) +template +vnl_vector +element_product(const vnl_vector & v1, const vnl_vector & v2) { #ifndef NDEBUG if (v1.size() != v2.size()) - vnl_error_vector_dimension ("element_product", v1.size(), v2.size()); + vnl_error_vector_dimension("element_product", v1.size(), v2.size()); #endif vnl_vector result(v1.size()); @@ -493,12 +529,13 @@ vnl_vector element_product (vnl_vector const& v1, vnl_vector const& v2) //: Returns new vector whose elements are the quotients v1[i]/v2[i]. O(n). -template -vnl_vector element_quotient (vnl_vector const& v1, vnl_vector const& v2) +template +vnl_vector +element_quotient(const vnl_vector & v1, const vnl_vector & v2) { #ifndef NDEBUG if (v1.size() != v2.size()) - vnl_error_vector_dimension ("element_quotient", v1.size(), v2.size()); + vnl_error_vector_dimension("element_quotient", v1.size(), v2.size()); #endif vnl_vector result(v1.size()); for (size_t i = 0; i < v1.size(); i++) @@ -508,7 +545,8 @@ vnl_vector element_quotient (vnl_vector const& v1, vnl_vector const& v2 //: template -vnl_vector vnl_vector::apply(T (*f)(T const&)) const +vnl_vector +vnl_vector::apply(T (*f)(const T &)) const { vnl_vector ret(size()); vnl_c_vector::apply(this->data, num_elmts, f, ret.data); @@ -517,7 +555,8 @@ vnl_vector vnl_vector::apply(T (*f)(T const&)) const //: Return the vector made by applying "f" to each element. template -vnl_vector vnl_vector::apply(T (*f)(T)) const +vnl_vector +vnl_vector::apply(T (*f)(T)) const { vnl_vector ret(num_elmts); vnl_c_vector::apply(this->data, num_elmts, f, ret.data); @@ -526,57 +565,57 @@ vnl_vector vnl_vector::apply(T (*f)(T)) const //: Returns the dot product of two nd-vectors, or [v1]*[v2]^T. O(n). -template -T dot_product (vnl_vector const& v1, vnl_vector const& v2) +template +T +dot_product(const vnl_vector & v1, const vnl_vector & v2) { #ifndef NDEBUG if (v1.size() != v2.size()) - vnl_error_vector_dimension ("dot_product", v1.size(), v2.size()); + vnl_error_vector_dimension("dot_product", v1.size(), v2.size()); #endif - return vnl_c_vector::dot_product(v1.begin(), - v2.begin(), - v1.size()); + return vnl_c_vector::dot_product(v1.begin(), v2.begin(), v1.size()); } //: Hermitian inner product. O(n) -template -T inner_product (vnl_vector const& v1, vnl_vector const& v2) +template +T +inner_product(const vnl_vector & v1, const vnl_vector & v2) { #ifndef NDEBUG if (v1.size() != v2.size()) - vnl_error_vector_dimension ("inner_product", v1.size(), v2.size()); + vnl_error_vector_dimension("inner_product", v1.size(), v2.size()); #endif - return vnl_c_vector::inner_product(v1.begin(), - v2.begin(), - v1.size()); + return vnl_c_vector::inner_product(v1.begin(), v2.begin(), v1.size()); } //: Returns the 'matrix element' = u^t * A * v. O(mn). -template -T bracket(vnl_vector const &u, vnl_matrix const &A, vnl_vector const &v) +template +T +bracket(const vnl_vector & u, const vnl_matrix & A, const vnl_vector & v) { #ifndef NDEBUG if (u.size() != A.rows()) - vnl_error_vector_dimension("bracket",u.size(),A.rows()); + vnl_error_vector_dimension("bracket", u.size(), A.rows()); if (A.columns() != v.size()) - vnl_error_vector_dimension("bracket",A.columns(),v.size()); + vnl_error_vector_dimension("bracket", A.columns(), v.size()); #endif T brak(0); - for (size_t i=0; i -vnl_matrix outer_product (vnl_vector const& v1, - vnl_vector const& v2) { +template +vnl_matrix +outer_product(const vnl_vector & v1, const vnl_vector & v2) +{ vnl_matrix out(v1.size(), v2.size()); - for (size_t i = 0; i < out.rows(); i++) // v1.column() * v2.row() + for (size_t i = 0; i < out.rows(); i++) // v1.column() * v2.row() for (size_t j = 0; j < out.columns(); j++) out[i][j] = v1[i] * v2[j]; return out; @@ -586,63 +625,65 @@ vnl_matrix outer_product (vnl_vector const& v1, //-------------------------------------------------------------------------------- template -vnl_vector& +vnl_vector & vnl_vector::flip() { - for (size_t i=0;i -vnl_vector& -vnl_vector::flip(const size_t &b, const size_t &e) +vnl_vector & +vnl_vector::flip(const size_t & b, const size_t & e) { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert (!(b > this->num_elmts || e > this->num_elmts || b > e)); +#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) + assert(!(b > this->num_elmts || e > this->num_elmts || b > e)); #endif - for (size_t i=b;i<(e-b)/2+b;++i) { - T tmp=data[i]; - const size_t endIndex = e - 1 - (i-b); - data[i]=data[endIndex]; - data[endIndex]=tmp; + for (size_t i = b; i < (e - b) / 2 + b; ++i) + { + T tmp = data[i]; + const size_t endIndex = e - 1 - (i - b); + data[i] = data[endIndex]; + data[endIndex] = tmp; } return *this; - } template vnl_vector -vnl_vector::roll(const int &shift) const +vnl_vector::roll(const int & shift) const { vnl_vector v(this->num_elmts); const size_t wrapped_shift = shift % this->num_elmts; if (0 == wrapped_shift) return v.copy_in(this->data_block()); for (size_t i = 0; i < this->num_elmts; ++i) - { - v[(i + wrapped_shift)%this->num_elmts] = this->data_block()[i]; - } + { + v[(i + wrapped_shift) % this->num_elmts] = this->data_block()[i]; + } return v; } template -vnl_vector& -vnl_vector::roll_inplace(const int &shift) +vnl_vector & +vnl_vector::roll_inplace(const int & shift) { const size_t wrapped_shift = shift % this->num_elmts; if (0 == wrapped_shift) return *this; - return this->flip().flip(0,wrapped_shift).flip(wrapped_shift,this->num_elmts); + return this->flip().flip(0, wrapped_shift).flip(wrapped_shift, this->num_elmts); } template -void vnl_vector::swap(vnl_vector &that) noexcept +void +vnl_vector::swap(vnl_vector & that) noexcept { std::swap(this->num_elmts, that.num_elmts); std::swap(this->data, that.data); @@ -654,66 +695,72 @@ void vnl_vector::swap(vnl_vector &that) noexcept // Disable warning caused when T is complex. The static_cast // to real_t constructs a complex from a double. #if defined(_MSC_VER) -# pragma warning (push) -# pragma warning (disable: 4244) /* conversion with loss of data */ +# pragma warning(push) +# pragma warning(disable : 4244) /* conversion with loss of data */ #endif // fsm : cos_angle should return a T, or a double-precision extension // of T. "double" is wrong since it won't work if T is complex. template -T cos_angle(vnl_vector const& a, vnl_vector const& b) +T +cos_angle(const vnl_vector & a, const vnl_vector & b) { typedef typename vnl_numeric_traits::real_t real_t; typedef typename vnl_numeric_traits::abs_t abs_t; typedef typename vnl_numeric_traits::real_t abs_r; - real_t ab = inner_product(a,b); - real_t a_b = static_cast( - std::sqrt( abs_r(a.squared_magnitude() * b.squared_magnitude()) )); - return T( ab / a_b); + const real_t ab = inner_product(a, b); + const real_t a_b = static_cast(std::sqrt(abs_r(a.squared_magnitude() * b.squared_magnitude()))); + return T(ab / a_b); } #if defined(_MSC_VER) -# pragma warning (pop) +# pragma warning(pop) #endif //: Returns smallest angle between two non-zero n-dimensional vectors. O(n). -template -double angle (vnl_vector const& a, vnl_vector const& b) +template +double +angle(const vnl_vector & a, const vnl_vector & b) { typedef typename vnl_numeric_traits::abs_t abs_t; typedef typename vnl_numeric_traits::real_t abs_r; - const abs_r c = abs_r( cos_angle(a, b) ); + const abs_r c = abs_r(cos_angle(a, b)); // IMS: sometimes cos_angle returns 1+eps, which can mess up std::acos. - if (c >= 1.0) return 0; - if (c <= -1.0) return vnl_math::pi; - return std::acos( c ); + if (c >= 1.0) + return 0; + if (c <= -1.0) + return vnl_math::pi; + return std::acos(c); } template -bool vnl_vector::is_finite() const +bool +vnl_vector::is_finite() const { - for (size_t i = 0; i < this->size();++i) - if (!vnl_math::isfinite( (*this)[i] )) + for (size_t i = 0; i < this->size(); ++i) + if (!vnl_math::isfinite((*this)[i])) return false; return true; } template -bool vnl_vector::is_zero() const +bool +vnl_vector::is_zero() const { - T const zero(0); - for (size_t i = 0; i < this->size();++i) - if ( !( (*this)[i] == zero) ) + const T zero(0); + for (size_t i = 0; i < this->size(); ++i) + if (!((*this)[i] == zero)) return false; return true; } template -void vnl_vector::assert_finite_internal() const +void +vnl_vector::assert_finite_internal() const { if (this->is_finite()) return; @@ -723,54 +770,60 @@ void vnl_vector::assert_finite_internal() const } template -void vnl_vector::assert_size_internal(size_t sz) const +void +vnl_vector::assert_size_internal(size_t sz) const { - if (this->size() != sz) { + if (this->size() != sz) + { std::cerr << __FILE__ ": Size is " << this->size() << ". Should be " << sz << '\n'; std::abort(); } } template -bool vnl_vector::is_equal(vnl_vector const& rhs, double tol) const +bool +vnl_vector::is_equal(const vnl_vector & rhs, double tol) const { - if (this == &rhs) //Same object ? => equal. + if (this == &rhs) // Same object ? => equal. return true; - if (this->size() != rhs.size()) //Size different ? + if (this->size() != rhs.size()) // Size different ? return false; for (size_t i = 0; i < size(); i++) - if (!(vnl_math::abs(this->data[i] - rhs.data[i]) <= tol)) //Element different ? + if (!(vnl_math::abs(this->data[i] - rhs.data[i]) <= tol)) // Element different ? return false; return true; } -template -bool vnl_vector::operator_eq (vnl_vector const& rhs) const +template +bool +vnl_vector::operator_eq(const vnl_vector & rhs) const { - if (this == &rhs) // same object => equal. + if (this == &rhs) // same object => equal. return true; - if (this->size() != rhs.size()) // Size different ? - return false; // Then not equal. - for (size_t i = 0; i < size(); i++) // For each index - if (!(this->data[i] == rhs.data[i])) // Element different ? - return false; // Then not equal. + if (this->size() != rhs.size()) // Size different ? + return false; // Then not equal. + for (size_t i = 0; i < size(); i++) // For each index + if (!(this->data[i] == rhs.data[i])) // Element different ? + return false; // Then not equal. - return true; // Else same; return true. + return true; // Else same; return true. } //-------------------------------------------------------------------------------- //: Overloads the output operator to print a vector. O(n). -template -std::ostream& operator<< (std::ostream& s, vnl_vector const& v) +template +std::ostream & +operator<<(std::ostream & s, const vnl_vector & v) { - for (size_t i = 0; i+1 < v.size(); ++i) // For each index in vector - s << v[i] << ' '; // Output data element - if (v.size() > 0) s << v[v.size()-1]; + for (size_t i = 0; i + 1 < v.size(); ++i) // For each index in vector + s << v[i] << ' '; // Output data element + if (v.size() > 0) + s << v[v.size() - 1]; return s; } @@ -778,9 +831,11 @@ std::ostream& operator<< (std::ostream& s, vnl_vector const& v) // If the vector has nonzero size on input, read that many values. // Otherwise, read to EOF. template -std::istream& operator>>(std::istream& s, vnl_vector& M) +std::istream & +operator>>(std::istream & s, vnl_vector & M) { - M.read_ascii(s); return s; + M.read_ascii(s); + return s; } //-------------------------------------------------------------------------------- @@ -788,32 +843,32 @@ std::istream& operator>>(std::istream& s, vnl_vector& M) // The instantiation macros are split because some functions (angle, cos_angle) // shouldn't be instantiated for complex and/or integral types. -#define VNL_VECTOR_INSTANTIATE_COMMON(T) \ -template class VNL_EXPORT vnl_vector; \ -/* arithmetic, comparison etc */ \ -/*template VNL_EXPORT vnl_vector operator+(T const, vnl_vector const &) ; */ \ -/*template VNL_EXPORT vnl_vector operator-(T const, vnl_vector const &) ; */ \ -/*template VNL_EXPORT vnl_vector operator*(T const, vnl_vector const &) ; */ \ -template VNL_EXPORT vnl_vector operator*(vnl_matrix const &, vnl_vector const &); \ -/* element-wise */ \ -template VNL_EXPORT vnl_vector element_product(vnl_vector const &, vnl_vector const &); \ -template VNL_EXPORT vnl_vector element_quotient(vnl_vector const &, vnl_vector const &); \ -/* dot products, angles etc */ \ -template VNL_EXPORT T inner_product(vnl_vector const &, vnl_vector const &); \ -template VNL_EXPORT T dot_product(vnl_vector const &, vnl_vector const &); \ -template VNL_EXPORT T bracket(vnl_vector const &, vnl_matrix const &, vnl_vector const &); \ -template VNL_EXPORT vnl_matrix outer_product(vnl_vector const &,vnl_vector const &); \ -/* I/O */ \ -template VNL_EXPORT std::ostream & operator<<(std::ostream &, vnl_vector const &); \ -template VNL_EXPORT std::istream & operator>>(std::istream &, vnl_vector &) - -#define VNL_VECTOR_INSTANTIATE(T) \ -VNL_VECTOR_INSTANTIATE_COMMON(T); \ -template VNL_EXPORT T cos_angle(vnl_vector const & , vnl_vector const &); \ -template VNL_EXPORT double angle(vnl_vector const & , vnl_vector const &) +#define VNL_VECTOR_INSTANTIATE_COMMON(T) \ + template class VNL_EXPORT vnl_vector; \ + /* arithmetic, comparison etc */ \ + /*template VNL_EXPORT vnl_vector operator+(T const, vnl_vector const &) ; */ \ + /*template VNL_EXPORT vnl_vector operator-(T const, vnl_vector const &) ; */ \ + /*template VNL_EXPORT vnl_vector operator*(T const, vnl_vector const &) ; */ \ + template VNL_EXPORT vnl_vector operator*(vnl_matrix const &, vnl_vector const &); \ + /* element-wise */ \ + template VNL_EXPORT vnl_vector element_product(vnl_vector const &, vnl_vector const &); \ + template VNL_EXPORT vnl_vector element_quotient(vnl_vector const &, vnl_vector const &); \ + /* dot products, angles etc */ \ + template VNL_EXPORT T inner_product(vnl_vector const &, vnl_vector const &); \ + template VNL_EXPORT T dot_product(vnl_vector const &, vnl_vector const &); \ + template VNL_EXPORT T bracket(vnl_vector const &, vnl_matrix const &, vnl_vector const &); \ + template VNL_EXPORT vnl_matrix outer_product(vnl_vector const &, vnl_vector const &); \ + /* I/O */ \ + template VNL_EXPORT std::ostream & operator<<(std::ostream &, vnl_vector const &); \ + template VNL_EXPORT std::istream & operator>>(std::istream &, vnl_vector &) + +#define VNL_VECTOR_INSTANTIATE(T) \ + VNL_VECTOR_INSTANTIATE_COMMON(T); \ + template VNL_EXPORT T cos_angle(vnl_vector const &, vnl_vector const &); \ + template VNL_EXPORT double angle(vnl_vector const &, vnl_vector const &) #define VNL_VECTOR_INSTANTIATE_COMPLEX(T) \ -VNL_VECTOR_INSTANTIATE_COMMON(T); \ -template VNL_EXPORT T cos_angle(vnl_vector const & , vnl_vector const &) + VNL_VECTOR_INSTANTIATE_COMMON(T); \ + template VNL_EXPORT T cos_angle(vnl_vector const &, vnl_vector const &) #endif // vnl_vector_hxx_ diff --git a/core/vnl/vnl_vector_fixed.h b/core/vnl/vnl_vector_fixed.h index 159a1edeec7..cf4295f8a9e 100644 --- a/core/vnl/vnl_vector_fixed.h +++ b/core/vnl/vnl_vector_fixed.h @@ -34,13 +34,15 @@ #include "vnl_vector.h" #include "vnl_vector_ref.h" #include "vnl_c_vector.h" -#include "vnl_matrix.h" // outerproduct +#include "vnl_matrix.h" // outerproduct #include // for VNL_CONFIG_CHECK_BOUNDS #include "vnl_error.h" #include "vnl/vnl_export.h" -template class vnl_vector_fixed; -template class vnl_matrix_fixed; +template +class vnl_vector_fixed; +template +class vnl_matrix_fixed; //: Fixed length stack-stored, space-efficient vector. // vnl_vector_fixed is a fixed-length, stack storage vector. It has @@ -86,14 +88,17 @@ template class vnl_matri template class VNL_EXPORT vnl_vector_fixed { - protected: +protected: T data_[n]; - public: - typedef vnl_vector_fixed self; +public: + typedef vnl_vector_fixed self; typedef size_t size_type; // Compile-time accessible attribute to get the dimensionality of the vector. - enum { SIZE = n }; + enum + { + SIZE = n + }; // Don't out-of-line the constructors, as extra the function call // adds a significant overhead. (memcpy is often implemented with a @@ -104,153 +109,179 @@ class VNL_EXPORT vnl_vector_fixed //: Copy constructor // The dimensions must match. - vnl_vector_fixed( const vnl_vector_fixed& rhs ) = default; - vnl_vector_fixed( vnl_vector_fixed&& rhs ) = default; + vnl_vector_fixed(const vnl_vector_fixed & rhs) = default; + vnl_vector_fixed(vnl_vector_fixed && rhs) = default; //: Copy operator - vnl_vector_fixed& operator=( const vnl_vector_fixed& rhs ) = default; - vnl_vector_fixed& operator=( vnl_vector_fixed&& rhs ) = default; + vnl_vector_fixed & + operator=(const vnl_vector_fixed & rhs) = default; + vnl_vector_fixed & + operator=(vnl_vector_fixed && rhs) = default; //: Construct a fixed-n-vector copy of \a rhs. // The dimensions must match. - vnl_vector_fixed( const vnl_vector& rhs ) + vnl_vector_fixed(const vnl_vector & rhs) { - assert( n == rhs.size() ); - std::memcpy( data_, rhs.data_block(), sizeof data_ ); + assert(n == rhs.size()); + std::memcpy(data_, rhs.data_block(), sizeof data_); } //: Constructs n-vector with all elements initialised to \a v - explicit vnl_vector_fixed( const T& v ) { fill( v ); } + explicit vnl_vector_fixed(const T & v) { fill(v); } //: Construct a fixed-n-vector initialized from \a datablck // The data \e must have enough data. No checks performed. - explicit vnl_vector_fixed( const T* datablck ) - { - std::memcpy( data_, datablck, sizeof data_ ); - } + explicit vnl_vector_fixed(const T * datablck) { std::memcpy(data_, datablck, sizeof data_); } //: Convenience constructor for 2-D vectors // While this constructor is sometimes useful, consider using // vnl_double_2 or vnl_float_2 instead. - vnl_vector_fixed( const T& x0, const T& x1 ) + vnl_vector_fixed(const T & x0, const T & x1) { - if ( n != 2 ) + if (n != 2) { - #ifndef NDEBUG +#ifndef NDEBUG vnl_error_vector_dimension("vnl_vector_fixed()", 2, n); - #endif +#endif return; } - data_[0] = x0; data_[1] = x1; + data_[0] = x0; + data_[1] = x1; } //: Convenience constructor for 3-D vectors // While this constructor is sometimes useful, consider using // vnl_double_3 or vnl_float_3 instead. - vnl_vector_fixed( const T& x0, const T& x1, const T& x2 ) + vnl_vector_fixed(const T & x0, const T & x1, const T & x2) { - if ( n != 3 ) + if (n != 3) { - #ifndef NDEBUG +#ifndef NDEBUG vnl_error_vector_dimension("vnl_vector_fixed()", 3, n); - #endif +#endif return; } - data_[0] = x0; data_[1] = x1; data_[2] = x2; + data_[0] = x0; + data_[1] = x1; + data_[2] = x2; } //: Convenience constructor for 4-D vectors - vnl_vector_fixed( const T& x0, const T& x1, const T& x2, const T& x3 ) + vnl_vector_fixed(const T & x0, const T & x1, const T & x2, const T & x3) { - if ( n != 4 ) + if (n != 4) { - #ifndef NDEBUG +#ifndef NDEBUG vnl_error_vector_dimension("vnl_vector_fixed()", 4, n); - #endif +#endif return; } - data_[0] = x0; data_[1] = x1; data_[2] = x2; data_[3] = x3; + data_[0] = x0; + data_[1] = x1; + data_[2] = x2; + data_[3] = x3; } //: Copy data from a dynamic vector // The dimensions must match. - vnl_vector_fixed& operator=( const vnl_vector& rhs) { - assert( n == rhs.size() ); - std::memcpy( data_, rhs.data_block(), sizeof data_ ); + vnl_vector_fixed & + operator=(const vnl_vector & rhs) + { + assert(n == rhs.size()); + std::memcpy(data_, rhs.data_block(), sizeof data_); return *this; } //: Length of the vector. // This is always \a n. - unsigned int size() const { return n; } + unsigned int + size() const + { + return n; + } //: Put value at given position in vector. - inline void put (unsigned int i, T const& v) + inline void + put(unsigned int i, const T & v) { #if VNL_CONFIG_CHECK_BOUNDS - if (i >= this->size()) // If invalid index specified + if (i >= this->size()) // If invalid index specified vnl_error_vector_index("put", i); // Raise exception #endif this->data_[i] = v; } //: Get value at element i - T get(unsigned int i) const; + T + get(unsigned int i) const; //: Set all values to v - vnl_vector_fixed& fill( T const& v ) + vnl_vector_fixed & + fill(const T & v) { - for ( size_type i = 0; i < n; ++i ) + for (size_type i = 0; i < n; ++i) this->data_[i] = v; return *this; } //: Sets elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - vnl_vector_fixed& copy_in( T const * ptr ) + vnl_vector_fixed & + copy_in(const T * ptr) { - for ( size_type i = 0; i < n; ++i ) + for (size_type i = 0; i < n; ++i) data_[i] = ptr[i]; return *this; } //: Copy elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - void copy_out( T* ptr ) const + void + copy_out(T * ptr) const { - for ( size_type i = 0; i < n; ++i ) + for (size_type i = 0; i < n; ++i) ptr[i] = data_[i]; } //: Sets elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - vnl_vector_fixed& set( T const *ptr ) { return copy_in(ptr); } + vnl_vector_fixed & + set(const T * ptr) + { + return copy_in(ptr); + } //: Return reference to the element at specified index. // There are assert style boundary checks - #define NDEBUG to turn them off. - T & operator() (unsigned int i); + T & + operator()(unsigned int i); //: Return reference to the element at specified index. // There are assert style boundary checks - #define NDEBUG to turn them off. - T const & operator() (unsigned int i) const; + const T & + operator()(unsigned int i) const; //: Return the i-th element - T& operator[] (const size_t i); + T & + operator[](const size_t i); //: Return the i-th element - const T& operator[] (const size_t i) const; + const T & + operator[](const size_t i) const; //: Access the contiguous block storing the elements in the vector. // O(1). // data_block()[0] is the first element of the vector - T const* data_block() const; + const T * + data_block() const; //: Access the contiguous block storing the elements in the vector. // O(1). // data_block()[0] is the first element of the vector - T * data_block(); + T * + data_block(); //---------------------------------------------------------------------- // Conversion to vnl_vector_ref. @@ -265,97 +296,185 @@ class VNL_EXPORT vnl_vector_fixed // for vnl_vector but not for vnl_vector_fixed. There is also a // conversion operator that should work most of the time. // \sa vnl_vector_ref::non_const - vnl_vector_ref as_ref() { return vnl_vector_ref( n, data_ ); } - const vnl_vector_ref as_ref() const { return vnl_vector_ref( n, const_cast(data_) ); } - vnl_vector as_vector() const { return vnl_vector(data_, n); } + vnl_vector_ref + as_ref() + { + return vnl_vector_ref(n, data_); + } + const vnl_vector_ref + as_ref() const + { + return vnl_vector_ref(n, const_cast(data_)); + } + vnl_vector + as_vector() const + { + return vnl_vector(data_, n); + } //: Cheap conversion to vnl_vector_ref // Sometimes, such as with templated functions, the compiler cannot // use this user-defined conversion. For those cases, use the // explicit as_ref() method instead. -#if ! VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS - explicit operator const vnl_vector_ref() const { return this->as_ref(); } +#if !VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS + explicit + operator const vnl_vector_ref() const + { + return this->as_ref(); + } #else -#if VXL_LEGACY_FUTURE_REMOVE - VXL_DEPRECATED_MSG("Implicit cast conversion is dangerous.\nUSE: .as_vector() or .as_ref() member function for clarity.") -#endif - operator const vnl_vector_ref() const { return this->as_ref(); } //Implicit for backwards compatibility +# if VXL_LEGACY_FUTURE_REMOVE + VXL_DEPRECATED_MSG( + "Implicit cast conversion is dangerous.\nUSE: .as_vector() or .as_ref() member function for clarity.") +# endif + operator const vnl_vector_ref() const { return this->as_ref(); } // Implicit for backwards compatibility #endif - explicit operator vnl_vector() const { return this->as_vector(); } + explicit + operator vnl_vector() const + { + return this->as_vector(); + } //---------------------------------------------------------------------- //: Type defs for iterators typedef T element_type; //: Type defs for iterators - typedef T *iterator; + typedef T * iterator; //: Iterator pointing to start of data - iterator begin() { return data_; } + iterator + begin() + { + return data_; + } //: Iterator pointing to element beyond end of data - iterator end() { return data_+n; } + iterator + end() + { + return data_ + n; + } //: Const iterator type - typedef T const *const_iterator; + typedef const T * const_iterator; //: Iterator pointing to start of data - const_iterator begin() const { return data_; } + const_iterator + begin() const + { + return data_; + } //: Iterator pointing to element beyond end of data - const_iterator end() const { return data_+n; } + const_iterator + end() const + { + return data_ + n; + } //: Analogous to std::array::front(). - T& front() { return *data_; } + T & + front() + { + return *data_; + } //: Analogous to std::array::back(). - T& back() { return data_[n - 1]; } + T & + back() + { + return data_[n - 1]; + } //: Analogous to std::array::front() (const overload). - const T& front() const { return *data_; } + const T & + front() const + { + return *data_; + } //: Analogous to std::array::back() (const overload). - const T& back() const { return data_[n - 1]; } + const T & + back() const + { + return data_[n - 1]; + } //: Apply f to each element. // Returns a new vector with the result. - vnl_vector_fixed apply(T (*f)(T)); + vnl_vector_fixed apply(T (*f)(T)); //: Apply f to each element. // Returns a new vector with the result. - vnl_vector_fixed apply(T (*f)(const T&)); + vnl_vector_fixed apply(T (*f)(const T &)); //: - vnl_vector_fixed& operator+=( T s ) { self::add( data_, s, data_ ); return *this; } + vnl_vector_fixed & + operator+=(T s) + { + self::add(data_, s, data_); + return *this; + } //: - vnl_vector_fixed& operator-=( T s ) { self::sub( data_, s, data_ ); return *this; } + vnl_vector_fixed & + operator-=(T s) + { + self::sub(data_, s, data_); + return *this; + } //: - vnl_vector_fixed& operator*=( T s ) { self::mul( data_, s, data_ ); return *this; } + vnl_vector_fixed & + operator*=(T s) + { + self::mul(data_, s, data_); + return *this; + } //: - vnl_vector_fixed& operator/=( T s ) { self::div( data_, s, data_ ); return *this; } + vnl_vector_fixed & + operator/=(T s) + { + self::div(data_, s, data_); + return *this; + } //: - vnl_vector_fixed& operator+=( const vnl_vector_fixed& v ) { self::add( data_, v.data_block(), data_ ); return *this; } + vnl_vector_fixed & + operator+=(const vnl_vector_fixed & v) + { + self::add(data_, v.data_block(), data_); + return *this; + } //: - vnl_vector_fixed& operator-=( const vnl_vector_fixed& v ) { self::sub( data_, v.data_block(), data_ ); return *this; } + vnl_vector_fixed & + operator-=(const vnl_vector_fixed & v) + { + self::sub(data_, v.data_block(), data_); + return *this; + } //: - vnl_vector_fixed& operator+=( const vnl_vector& v ) + vnl_vector_fixed & + operator+=(const vnl_vector & v) { - assert( v.size() == n ); - self::add( data_, v.data_block(), data_ ); return *this; + assert(v.size() == n); + self::add(data_, v.data_block(), data_); + return *this; } //: - vnl_vector_fixed& operator-=( const vnl_vector& v ) + vnl_vector_fixed & + operator-=(const vnl_vector & v) { - assert( v.size() == n ); - self::sub( data_, v.data_block(), data_ ); return *this; + assert(v.size() == n); + self::sub(data_, v.data_block(), data_); + return *this; } //: - vnl_vector_fixed::signed_t,n> operator-() const + vnl_vector_fixed::signed_t, n> + operator-() const { - vnl_vector_fixed::signed_t,n> result; - for(size_t i=0; i< n; ++i) + vnl_vector_fixed::signed_t, n> result; + for (size_t i = 0; i < n; ++i) { result[i] = -data_[i]; } @@ -363,71 +482,133 @@ class VNL_EXPORT vnl_vector_fixed } //: Returns a subvector specified by the start index and length. O(n). - vnl_vector extract (unsigned int len, unsigned int start=0) const + vnl_vector + extract(unsigned int len, unsigned int start = 0) const { - assert( start < n && start + len <= n ); - return vnl_vector( data_ + start, len ); + assert(start < n && start + len <= n); + return vnl_vector(data_ + start, len); } //: Replaces elements with index beginning at start, by values of v. O(n). - vnl_vector_fixed& update(vnl_vector const&, unsigned int start=0); + vnl_vector_fixed & + update(const vnl_vector &, unsigned int start = 0); // norms etc typedef typename vnl_c_vector::abs_t abs_t; //: Return sum of squares of elements - abs_t squared_magnitude() const { return vnl_c_vector::two_nrm2(begin(), size()); } + abs_t + squared_magnitude() const + { + return vnl_c_vector::two_nrm2(begin(), size()); + } //: Return magnitude (length) of vector - abs_t magnitude() const { return two_norm(); } + abs_t + magnitude() const + { + return two_norm(); + } //: Return sum of absolute values of the elements - abs_t one_norm() const { return vnl_c_vector::one_norm(begin(), size()); } + abs_t + one_norm() const + { + return vnl_c_vector::one_norm(begin(), size()); + } //: Return sqrt of sum of squares of values of elements - abs_t two_norm() const { return vnl_c_vector::two_norm(begin(), size()); } + abs_t + two_norm() const + { + return vnl_c_vector::two_norm(begin(), size()); + } //: Return largest absolute element value - abs_t inf_norm() const { return vnl_c_vector::inf_norm(begin(), size()); } + abs_t + inf_norm() const + { + return vnl_c_vector::inf_norm(begin(), size()); + } //: Normalise by dividing through by the magnitude - vnl_vector_fixed& normalize() { vnl_c_vector::normalize(begin(), size()); return *this; } + vnl_vector_fixed & + normalize() + { + vnl_c_vector::normalize(begin(), size()); + return *this; + } // These next 6 functions are should really be helper functions since they aren't // really proper functions on a vector in a philosophical sense. //: Root Mean Squares of values - abs_t rms () const { return vnl_c_vector::rms_norm(begin(), size()); } + abs_t + rms() const + { + return vnl_c_vector::rms_norm(begin(), size()); + } //: Smallest value - T min_value () const { return vnl_c_vector::min_value(begin(), size()); } + T + min_value() const + { + return vnl_c_vector::min_value(begin(), size()); + } //: Largest value - T max_value () const { return vnl_c_vector::max_value(begin(), size()); } + T + max_value() const + { + return vnl_c_vector::max_value(begin(), size()); + } //: Location of smallest value - unsigned arg_min() const { return vnl_c_vector::arg_min(begin(), size()); } + unsigned + arg_min() const + { + return vnl_c_vector::arg_min(begin(), size()); + } //: Location of largest value - unsigned arg_max() const { return vnl_c_vector::arg_max(begin(), size()); } + unsigned + arg_max() const + { + return vnl_c_vector::arg_max(begin(), size()); + } //: Mean of values in vector - T mean() const { return vnl_c_vector::mean(begin(), size()); } + T + mean() const + { + return vnl_c_vector::mean(begin(), size()); + } //: Sum of values in a vector - T sum() const { return vnl_c_vector::sum(begin(), size()); } + T + sum() const + { + return vnl_c_vector::sum(begin(), size()); + } //: Reverse the order of the elements // Element i swaps with element size()-1-i - vnl_vector_fixed& flip(); + vnl_vector_fixed & + flip(); //: Check that size()==sz if not, abort(); // This function does or tests nothing if NDEBUG is defined - void assert_size( unsigned sz ) const { assert( sz == n ); (void)sz; } + void + assert_size(unsigned sz) const + { + assert(sz == n); + (void)sz; + } //: Check that this is finite if not, abort(); // This function does or tests nothing if NDEBUG is defined - void assert_finite() const + void + assert_finite() const { #ifndef NDEBUG assert_finite_internal(); @@ -435,105 +616,126 @@ class VNL_EXPORT vnl_vector_fixed } //: Return true if it's finite - bool is_finite() const; + bool + is_finite() const; //: Return true iff all the entries are zero. - bool is_zero() const; + bool + is_zero() const; //: Return true iff the size is zero. - bool empty() const { return n==0; } + bool + empty() const + { + return n == 0; + } //: Return true if all elements of the two vectors are equal, within given tolerance - bool is_equal(vnl_vector_fixed const& rhs, double tol) const; + bool + is_equal(const vnl_vector_fixed & rhs, double tol) const; //: Return true if *this == v - bool operator_eq (vnl_vector_fixed const& v) const + bool + operator_eq(const vnl_vector_fixed & v) const { - for ( size_type i = 0; i < n; ++i ) - if ( (*this)[i] != v[i] ) + for (size_type i = 0; i < n; ++i) + if ((*this)[i] != v[i]) return false; return true; } //: Return true if *this == v - bool operator_eq (vnl_vector const& v) const + bool + operator_eq(const vnl_vector & v) const { - assert( v.size() == n ); - for ( size_type i = 0; i < n; ++i ) - if ( (*this)[i] != v[i] ) + assert(v.size() == n); + for (size_type i = 0; i < n; ++i) + if ((*this)[i] != v[i]) return false; return true; } //: Read from text stream - bool read_ascii(std::istream& s); + bool + read_ascii(std::istream & s); //: Display the vector // Output each element separated by a single space. - void print( std::ostream& s ) const; + void + print(std::ostream & s) const; - public: +public: // Helper routines for arithmetic. n is the size, and is the // template parameter. - inline static void add( const T* a, const T* b, T* r ) + static inline void + add(const T * a, const T * b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++a,++b ) + for (unsigned int i = 0; i < n; ++i, ++r, ++a, ++b) *r = *a + *b; } - inline static void add( const T* a, T b, T* r ) + static inline void + add(const T * a, T b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++a ) + for (unsigned int i = 0; i < n; ++i, ++r, ++a) *r = *a + b; } - inline static void sub( const T* a, const T* b, T* r ) + static inline void + sub(const T * a, const T * b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++a,++b ) + for (unsigned int i = 0; i < n; ++i, ++r, ++a, ++b) *r = *a - *b; } - inline static void sub( const T* a, T b, T* r ) + static inline void + sub(const T * a, T b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++a ) + for (unsigned int i = 0; i < n; ++i, ++r, ++a) *r = *a - b; } - inline static void sub( T a, const T* b, T* r ) + static inline void + sub(T a, const T * b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++b ) + for (unsigned int i = 0; i < n; ++i, ++r, ++b) *r = a - *b; } - inline static void mul( const T* a, const T* b, T* r ) + static inline void + mul(const T * a, const T * b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++a,++b ) + for (unsigned int i = 0; i < n; ++i, ++r, ++a, ++b) *r = *a * *b; } - inline static void mul( const T* a, T b, T* r ) + static inline void + mul(const T * a, T b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++a ) + for (unsigned int i = 0; i < n; ++i, ++r, ++a) *r = *a * b; } - inline static void div( const T* a, const T* b, T* r ) + static inline void + div(const T * a, const T * b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++a,++b ) + for (unsigned int i = 0; i < n; ++i, ++r, ++a, ++b) *r = *a / *b; } - inline static void div( const T* a, T b, T* r ) + static inline void + div(const T * a, T b, T * r) { - for ( unsigned int i=0; i < n; ++i,++r,++a ) + for (unsigned int i = 0; i < n; ++i, ++r, ++a) *r = *a / b; } - private: +private: //: See assert_finite(). - void assert_finite_internal() const; + void + assert_finite_internal() const; }; @@ -541,74 +743,78 @@ class VNL_EXPORT vnl_vector_fixed //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator+( const vnl_vector_fixed& v, T s ) +template +inline vnl_vector_fixed +operator+(const vnl_vector_fixed & v, T s) { - vnl_vector_fixed r; - vnl_vector_fixed::add( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::add(v.data_block(), s, r.data_block()); return r; } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator+( const T& s, - const vnl_vector_fixed& v ) +template +inline vnl_vector_fixed +operator+(const T & s, const vnl_vector_fixed & v) { - vnl_vector_fixed r; - vnl_vector_fixed::add( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::add(v.data_block(), s, r.data_block()); return r; } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator-( const vnl_vector_fixed& v, T s ) +template +inline vnl_vector_fixed +operator-(const vnl_vector_fixed & v, T s) { - vnl_vector_fixed r; - vnl_vector_fixed::sub( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::sub(v.data_block(), s, r.data_block()); return r; } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator-( const T& s, - const vnl_vector_fixed& v ) +template +inline vnl_vector_fixed +operator-(const T & s, const vnl_vector_fixed & v) { - vnl_vector_fixed r; - vnl_vector_fixed::sub( s, v.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::sub(s, v.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator*( const vnl_vector_fixed& v, T s ) +template +inline vnl_vector_fixed +operator*(const vnl_vector_fixed & v, T s) { - vnl_vector_fixed r; - vnl_vector_fixed::mul( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::mul(v.data_block(), s, r.data_block()); return r; } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator*( const T& s, - const vnl_vector_fixed& v ) +template +inline vnl_vector_fixed +operator*(const T & s, const vnl_vector_fixed & v) { - vnl_vector_fixed r; - vnl_vector_fixed::mul( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::mul(v.data_block(), s, r.data_block()); return r; } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator/( const vnl_vector_fixed& v, T s ) +template +inline vnl_vector_fixed +operator/(const vnl_vector_fixed & v, T s) { - vnl_vector_fixed r; - vnl_vector_fixed::div( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::div(v.data_block(), s, r.data_block()); return r; } @@ -621,19 +827,21 @@ inline vnl_vector_fixed operator/( const vnl_vector_fixed& v, T s ) //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator+( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline vnl_vector_fixed +operator+(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - vnl_vector_fixed r; - vnl_vector_fixed::add( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::add(a.data_block(), b.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector operator+( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline vnl_vector +operator+(const vnl_vector_fixed & a, const vnl_vector & b) { return a.as_ref() + b; } @@ -641,27 +849,30 @@ inline vnl_vector operator+( const vnl_vector_fixed& a, const vnl_vector //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector operator+( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline vnl_vector +operator+(const vnl_vector & a, const vnl_vector_fixed & b) { return a + b.as_ref(); } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator-( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline vnl_vector_fixed +operator-(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - vnl_vector_fixed r; - vnl_vector_fixed::sub( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::sub(a.data_block(), b.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector operator-( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline vnl_vector +operator-(const vnl_vector_fixed & a, const vnl_vector & b) { return a.as_ref() - b; } @@ -669,182 +880,201 @@ inline vnl_vector operator-( const vnl_vector_fixed& a, const vnl_vector //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector operator-( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline vnl_vector +operator-(const vnl_vector & a, const vnl_vector_fixed & b) { return a - b.as_ref(); } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed element_product( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline vnl_vector_fixed +element_product(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - vnl_vector_fixed r; - vnl_vector_fixed::mul( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::mul(a.data_block(), b.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector element_product( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline vnl_vector +element_product(const vnl_vector_fixed & a, const vnl_vector & b) { - assert( b.size() == n ); + assert(b.size() == n); vnl_vector r(n); - vnl_vector_fixed::mul( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed::mul(a.data_block(), b.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector element_product( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline vnl_vector +element_product(const vnl_vector & a, const vnl_vector_fixed & b) { - assert( a.size() == n ); + assert(a.size() == n); vnl_vector r(n); - vnl_vector_fixed::mul( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed::mul(a.data_block(), b.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed element_quotient( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline vnl_vector_fixed +element_quotient(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - vnl_vector_fixed r; - vnl_vector_fixed::div( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::div(a.data_block(), b.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector element_quotient( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline vnl_vector +element_quotient(const vnl_vector_fixed & a, const vnl_vector & b) { - assert( b.size() == n ); + assert(b.size() == n); vnl_vector r(n); - vnl_vector_fixed::div( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed::div(a.data_block(), b.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_vector element_quotient( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline vnl_vector +element_quotient(const vnl_vector & a, const vnl_vector_fixed & b) { - assert( a.size() == n ); + assert(a.size() == n); vnl_vector r(n); - vnl_vector_fixed::div( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed::div(a.data_block(), b.data_block(), r.data_block()); return r; } //: // \relatesalso vnl_vector_fixed -template -inline T dot_product( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline T +dot_product(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - return dot_product( a.as_ref(), b.as_ref() ); + return dot_product(a.as_ref(), b.as_ref()); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline T dot_product( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline T +dot_product(const vnl_vector_fixed & a, const vnl_vector & b) { - return dot_product( a.as_ref(), b ); + return dot_product(a.as_ref(), b); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline T dot_product( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline T +dot_product(const vnl_vector & a, const vnl_vector_fixed & b) { - return dot_product( a, b.as_ref() ); + return dot_product(a, b.as_ref()); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_matrix outer_product( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline vnl_matrix +outer_product(const vnl_vector & a, const vnl_vector_fixed & b) { - return outer_product( a, b.as_ref()); + return outer_product(a, b.as_ref()); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline vnl_matrix outer_product( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline vnl_matrix +outer_product(const vnl_vector_fixed & a, const vnl_vector & b) { - return outer_product( a.as_ref(), b); + return outer_product(a.as_ref(), b); } //: // \relatesalso vnl_vector_fixed -template -inline T angle( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline T +angle(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - return angle( a.as_ref(), b.as_ref() ); + return angle(a.as_ref(), b.as_ref()); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline T angle( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline T +angle(const vnl_vector_fixed & a, const vnl_vector & b) { - return angle( a.as_ref(), b ); + return angle(a.as_ref(), b); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline T angle( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline T +angle(const vnl_vector & a, const vnl_vector_fixed & b) { - return angle( a, b.as_ref() ); + return angle(a, b.as_ref()); } //: // \relatesalso vnl_vector_fixed -template -inline T vnl_vector_ssd( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline T +vnl_vector_ssd(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - return vnl_vector_ssd( a.as_ref(), b.as_ref() ); + return vnl_vector_ssd(a.as_ref(), b.as_ref()); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline T vnl_vector_ssd( const vnl_vector_fixed& a, const vnl_vector& b ) +template +inline T +vnl_vector_ssd(const vnl_vector_fixed & a, const vnl_vector & b) { - return vnl_vector_ssd( a.as_ref(), b ); + return vnl_vector_ssd(a.as_ref(), b); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline T vnl_vector_ssd( const vnl_vector& a, const vnl_vector_fixed& b ) +template +inline T +vnl_vector_ssd(const vnl_vector & a, const vnl_vector_fixed & b) { - return vnl_vector_ssd( a, b.as_ref() ); + return vnl_vector_ssd(a, b.as_ref()); } //: // \relatesalso vnl_vector_fixed -template -inline bool operator==( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline bool +operator==(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { return a.operator_eq(b); } @@ -852,8 +1082,9 @@ inline bool operator==( const vnl_vector_fixed& a, const vnl_vector_fixed -inline bool operator==( vnl_vector_fixed const& a, vnl_vector const& b ) +template +inline bool +operator==(const vnl_vector_fixed & a, const vnl_vector & b) { return a.operator_eq(b); } @@ -861,36 +1092,40 @@ inline bool operator==( vnl_vector_fixed const& a, vnl_vector const& b ) //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline bool operator==( vnl_vector const& a, vnl_vector_fixed const& b ) +template +inline bool +operator==(const vnl_vector & a, const vnl_vector_fixed & b) { return b.operator_eq(a); } //: // \relatesalso vnl_vector_fixed -template -inline bool operator!=( const vnl_vector_fixed& a, const vnl_vector_fixed& b ) +template +inline bool +operator!=(const vnl_vector_fixed & a, const vnl_vector_fixed & b) { - return ! a.operator_eq(b); + return !a.operator_eq(b); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline bool operator!=( vnl_vector_fixed const& a, vnl_vector const& b ) +template +inline bool +operator!=(const vnl_vector_fixed & a, const vnl_vector & b) { - return ! a.operator_eq(b); + return !a.operator_eq(b); } //: // \relatesalso vnl_vector // \relatesalso vnl_vector_fixed -template -inline bool operator!=( vnl_vector const& a, vnl_vector_fixed const& b ) +template +inline bool +operator!=(const vnl_vector & a, const vnl_vector_fixed & b) { - return ! b.operator_eq(a); + return !b.operator_eq(a); } @@ -899,21 +1134,21 @@ inline bool operator!=( vnl_vector const& a, vnl_vector_fixed const& b ) //: // \relatesalso vnl_vector_fixed -template -inline -std::ostream& operator<< ( std::ostream& ostr, const vnl_vector_fixed& v ) +template +inline std::ostream & +operator<<(std::ostream & ostr, const vnl_vector_fixed & v) { - v.print( ostr ); + v.print(ostr); return ostr; } //: // \relatesalso vnl_vector_fixed -template -inline -std::istream& operator>> ( std::istream& ostr, vnl_vector_fixed& v ) +template +inline std::istream & +operator>>(std::istream & ostr, vnl_vector_fixed & v) { - v.read_ascii( ostr ); + v.read_ascii(ostr); return ostr; } diff --git a/core/vnl/vnl_vector_fixed.hxx b/core/vnl/vnl_vector_fixed.hxx index d636f936c9c..6039d167701 100644 --- a/core/vnl/vnl_vector_fixed.hxx +++ b/core/vnl/vnl_vector_fixed.hxx @@ -13,94 +13,102 @@ #ifdef _MSC_VER # include #endif -#include "vnl_math.h" // for vnl_math::isfinite - -template -T & -vnl_vector_fixed::operator() (unsigned int i) - { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert(i < n); // Check the index is valid. +#include "vnl_math.h" // for vnl_math::isfinite + +template +T & +vnl_vector_fixed::operator()(unsigned int i) +{ +#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) + assert(i < n); // Check the index is valid. #endif return data_[i]; - } +} -template -T const & -vnl_vector_fixed::operator() (unsigned int i) const +template +const T & +vnl_vector_fixed::operator()(unsigned int i) const { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert(i < n); // Check the index is valid +#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) + assert(i < n); // Check the index is valid #endif - return data_[i]; + return data_[i]; } -template -T& -vnl_vector_fixed::operator[] (const size_t i) -{ return data_[i]; } +template +T & +vnl_vector_fixed::operator[](const size_t i) +{ + return data_[i]; +} -template -const T& -vnl_vector_fixed::operator[] (const size_t i) const -{ return data_[i]; } +template +const T & +vnl_vector_fixed::operator[](const size_t i) const +{ + return data_[i]; +} -template -T const* +template +const T * vnl_vector_fixed::data_block() const -{ return data_; } +{ + return data_; +} -template -T * +template +T * vnl_vector_fixed::data_block() -{ return data_; } +{ + return data_; +} -template -vnl_vector_fixed -vnl_vector_fixed::apply( T (*f)(T) ) +template +vnl_vector_fixed +vnl_vector_fixed::apply(T (*f)(T)) { - vnl_vector_fixed ret; - for ( size_type i = 0; i < n; ++i ) - ret[i] = f( data_[i] ); + vnl_vector_fixed ret; + for (size_type i = 0; i < n; ++i) + ret[i] = f(data_[i]); return ret; } -template -vnl_vector_fixed -vnl_vector_fixed::apply( T (*f)(const T&) ) +template +vnl_vector_fixed +vnl_vector_fixed::apply(T (*f)(const T &)) { - vnl_vector_fixed ret; - for ( size_type i = 0; i < n; ++i ) - ret[i] = f( data_[i] ); + vnl_vector_fixed ret; + for (size_type i = 0; i < n; ++i) + ret[i] = f(data_[i]); return ret; } -template -vnl_vector_fixed& -vnl_vector_fixed::update( const vnl_vector& v, unsigned int start ) +template +vnl_vector_fixed & +vnl_vector_fixed::update(const vnl_vector & v, unsigned int start) { - size_type stop = start + v.size(); - assert( stop <= n ); + const size_type stop = start + v.size(); + assert(stop <= n); for (size_type i = start; i < stop; i++) - this->data_[i] = v[i-start]; + this->data_[i] = v[i - start]; return *this; } template -vnl_vector_fixed& -vnl_vector_fixed::flip() +vnl_vector_fixed & +vnl_vector_fixed::flip() { - for ( unsigned int i=0; 2*i+1 < n; ++i ) - std::swap( data_[i], data_[n-1-i] ); + for (unsigned int i = 0; 2 * i + 1 < n; ++i) + std::swap(data_[i], data_[n - 1 - i]); return *this; } template bool -vnl_vector_fixed::is_finite() const +vnl_vector_fixed::is_finite() const { - for ( size_type i = 0; i < this->size(); ++i ) - if ( !vnl_math::isfinite( (*this)[i] ) ) + for (size_type i = 0; i < this->size(); ++i) + if (!vnl_math::isfinite((*this)[i])) return false; return true; @@ -109,11 +117,11 @@ vnl_vector_fixed::is_finite() const template bool -vnl_vector_fixed::is_zero() const +vnl_vector_fixed::is_zero() const { - T const zero(0); - for ( size_type i = 0; i < this->size(); ++i ) - if ( !( (*this)[i] == zero) ) + const T zero(0); + for (size_type i = 0; i < this->size(); ++i) + if (!((*this)[i] == zero)) return false; return true; @@ -122,7 +130,7 @@ vnl_vector_fixed::is_zero() const template bool -vnl_vector_fixed::read_ascii(std::istream& s) +vnl_vector_fixed::read_ascii(std::istream & s) { for (size_type i = 0; i < this->size(); ++i) s >> (*this)(i); @@ -132,7 +140,7 @@ vnl_vector_fixed::read_ascii(std::istream& s) template void -vnl_vector_fixed::assert_finite_internal() const +vnl_vector_fixed::assert_finite_internal() const { if (this->is_finite()) return; @@ -142,13 +150,14 @@ vnl_vector_fixed::assert_finite_internal() const } template -bool vnl_vector_fixed::is_equal(vnl_vector_fixed const& rhs, double tol) const +bool +vnl_vector_fixed::is_equal(const vnl_vector_fixed & rhs, double tol) const { - if (this == &rhs) //Same object ? => equal. + if (this == &rhs) // Same object ? => equal. return true; for (size_t i = 0; i < n; ++i) - if (!(vnl_math::abs(this->data_[i] - rhs.data_[i]) <= tol)) //Element different ? + if (!(vnl_math::abs(this->data_[i] - rhs.data_[i]) <= tol)) // Element different ? return false; return true; @@ -156,11 +165,11 @@ bool vnl_vector_fixed::is_equal(vnl_vector_fixed const& rhs, double to template void -vnl_vector_fixed::print(std::ostream& s) const +vnl_vector_fixed::print(std::ostream & s) const { if (this->size() > 0) s << (*this)[0]; - for (size_type i=1; i < this->size(); ++i) + for (size_type i = 1; i < this->size(); ++i) s << ' ' << (*this)[i]; } @@ -169,16 +178,15 @@ T vnl_vector_fixed::get(unsigned int i) const { #if VNL_CONFIG_CHECK_BOUNDS - if (i >= this->size()) // If invalid index specified - vnl_error_vector_index("get", i); // Raise exception + if (i >= this->size()) // If invalid index specified + vnl_error_vector_index("get", i); // Raise exception #endif - return this->data_[i]; + return this->data_[i]; } // we don't need to explicitly instantiate all the operator+ and such // since they appear in the .h file and are inline. -#define VNL_VECTOR_FIXED_INSTANTIATE(T,n) \ -template class VNL_EXPORT vnl_vector_fixed +#define VNL_VECTOR_FIXED_INSTANTIATE(T, n) template class VNL_EXPORT vnl_vector_fixed #endif // vnl_vector_fixed_hxx_ diff --git a/core/vnl/vnl_vector_fixed_ref.h b/core/vnl/vnl_vector_fixed_ref.h index 6df0a902b4e..e0a446c8c9a 100644 --- a/core/vnl/vnl_vector_fixed_ref.h +++ b/core/vnl/vnl_vector_fixed_ref.h @@ -28,19 +28,29 @@ template class VNL_EXPORT vnl_vector_fixed_ref_const { - protected: - const T* data_; +protected: + const T * data_; - public: +public: typedef size_t size_type; - vnl_vector_fixed_ref_const(vnl_vector_fixed const& rhs) : data_(rhs.data_block()) {} + vnl_vector_fixed_ref_const(const vnl_vector_fixed & rhs) + : data_(rhs.data_block()) + {} - explicit vnl_vector_fixed_ref_const(const T * dataptr) : data_(dataptr) {} + explicit vnl_vector_fixed_ref_const(const T * dataptr) + : data_(dataptr) + {} - vnl_vector_fixed_ref_const(const vnl_vector_fixed_ref_const & rhs) : data_(rhs.data_block()) {} + vnl_vector_fixed_ref_const(const vnl_vector_fixed_ref_const & rhs) + : data_(rhs.data_block()) + {} - const T * data_block() const { return data_; } + const T * + data_block() const + { + return data_; + } // Don't out-of-line the constructors, as the extra function call // adds a significant overhead. (memcpy is often implemented with a @@ -49,32 +59,47 @@ class VNL_EXPORT vnl_vector_fixed_ref_const //: Length of the vector. // This is always \a n. - unsigned size() const { return n; } + unsigned + size() const + { + return n; + } //: Get value at element i - T get (unsigned int i) const { return data_[i]; } + T + get(unsigned int i) const + { + return data_[i]; + } //: Copy elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - void copy_out( T* ptr ) const { - for ( size_type i = 0; i < n; ++i ) + void + copy_out(T * ptr) const + { + for (size_type i = 0; i < n; ++i) ptr[i] = data_[i]; } //: Return reference to the element at specified index. // There are assert style boundary checks - #define NDEBUG to turn them off. - T const & operator() (unsigned int i) const + const T & + operator()(unsigned int i) const { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert(i as_ref() { return vnl_vector_ref( n, const_cast(data_block()) ); } - const vnl_vector_ref as_ref() const { return vnl_vector_ref( n, const_cast(data_block()) ); } - vnl_vector as_vector() const { return vnl_vector(const_cast(data_block()), n); } + vnl_vector_ref + as_ref() + { + return vnl_vector_ref(n, const_cast(data_block())); + } + const vnl_vector_ref + as_ref() const + { + return vnl_vector_ref(n, const_cast(data_block())); + } + vnl_vector + as_vector() const + { + return vnl_vector(const_cast(data_block()), n); + } //: Cheap conversion to vnl_vector_ref // Sometimes, such as with templated functions, the compiler cannot // use this user-defined conversion. For those cases, use the // explicit as_ref() method instead. - explicit operator vnl_vector_ref() { return this->as_ref(); } -#if ! VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS - explicit operator const vnl_vector_ref() const { return vnl_vector_ref( n, const_cast(data_) ); } + explicit + operator vnl_vector_ref() + { + return this->as_ref(); + } +#if !VXL_USE_HISTORICAL_IMPLICIT_CONVERSIONS + explicit + operator const vnl_vector_ref() const + { + return vnl_vector_ref(n, const_cast(data_)); + } #else -#if VXL_LEGACY_FUTURE_REMOVE - VXL_DEPRECATED_MSG("Implicit cast conversion is dangerous.\nUSE: .as_vector() or .as_ref() member function for clarity.") -#endif - operator const vnl_vector_ref() const { return vnl_vector_ref( n, const_cast(data_) ); } //Implicit for backwards compatibility +# if VXL_LEGACY_FUTURE_REMOVE + VXL_DEPRECATED_MSG( + "Implicit cast conversion is dangerous.\nUSE: .as_vector() or .as_ref() member function for clarity.") +# endif + operator const vnl_vector_ref() const + { + return vnl_vector_ref(n, const_cast(data_)); + } // Implicit for backwards compatibility #endif - explicit operator vnl_vector() const { return this->as_vector(); } + explicit + operator vnl_vector() const + { + return this->as_vector(); + } //---------------------------------------------------------------------- //: Type defs for iterators typedef T element_type; //: Type defs for iterators - typedef T const *iterator; + typedef const T * iterator; //: Const iterator type - typedef T const *const_iterator; + typedef const T * const_iterator; //: Iterator pointing to start of data - const_iterator begin() const { return data_; } + const_iterator + begin() const + { + return data_; + } //: Iterator pointing to element beyond end of data - const_iterator end() const { return data_+n; } + const_iterator + end() const + { + return data_ + n; + } //: Apply f to each element. // Returns a new vector with the result. - vnl_vector_fixed apply(T (*f)(T)) const; + vnl_vector_fixed apply(T (*f)(T)) const; //: Apply f to each element. // Returns a new vector with the result. - vnl_vector_fixed apply(T (*f)(const T&)) const; + vnl_vector_fixed apply(T (*f)(const T &)) const; //: - vnl_vector_fixed::signed_t,n> operator-() const { - vnl_vector_fixed::signed_t,n> result; - sub( (T)0, data_, result.data_block() ); + vnl_vector_fixed::signed_t, n> + operator-() const + { + vnl_vector_fixed::signed_t, n> result; + sub((T)0, data_, result.data_block()); return result; } //: Returns a subvector specified by the start index and length. O(n). - vnl_vector extract (unsigned int len, unsigned int start=0) const; + vnl_vector + extract(unsigned int len, unsigned int start = 0) const; // norms etc typedef typename vnl_c_vector::abs_t abs_t; //: Return sum of squares of elements - abs_t squared_magnitude() const { return vnl_c_vector::two_nrm2(begin(), n); } + abs_t + squared_magnitude() const + { + return vnl_c_vector::two_nrm2(begin(), n); + } //: Return magnitude (length) of vector - abs_t magnitude() const { return two_norm(); } + abs_t + magnitude() const + { + return two_norm(); + } //: Return sum of absolute values of the elements - abs_t one_norm() const { return vnl_c_vector::one_norm(begin(), n); } + abs_t + one_norm() const + { + return vnl_c_vector::one_norm(begin(), n); + } //: Return sqrt of sum of squares of values of elements - abs_t two_norm() const { return vnl_c_vector::two_norm(begin(), n); } + abs_t + two_norm() const + { + return vnl_c_vector::two_norm(begin(), n); + } //: Return largest absolute element value - abs_t inf_norm() const { return vnl_c_vector::inf_norm(begin(), n); } + abs_t + inf_norm() const + { + return vnl_c_vector::inf_norm(begin(), n); + } // These next 6 functions are should really be helper functions since they aren't // really proper functions on a vector in a philosophical sense. //: Root Mean Squares of values - abs_t rms () const { return vnl_c_vector::rms_norm(begin(), n); } + abs_t + rms() const + { + return vnl_c_vector::rms_norm(begin(), n); + } //: Smallest value - T min_value () const { return vnl_c_vector::min_value(begin(), n); } + T + min_value() const + { + return vnl_c_vector::min_value(begin(), n); + } //: Largest value - T max_value () const { return vnl_c_vector::max_value(begin(), n); } + T + max_value() const + { + return vnl_c_vector::max_value(begin(), n); + } //: Location of smallest value - unsigned arg_min() const { return vnl_c_vector::arg_min(begin(), n); } + unsigned + arg_min() const + { + return vnl_c_vector::arg_min(begin(), n); + } //: Location of largest value - unsigned arg_max() const { return vnl_c_vector::arg_max(begin(), n); } + unsigned + arg_max() const + { + return vnl_c_vector::arg_max(begin(), n); + } //: Mean of values in vector - T mean() const { return vnl_c_vector::mean(begin(), n); } + T + mean() const + { + return vnl_c_vector::mean(begin(), n); + } //: Sum of values in a vector - T sum() const { return vnl_c_vector::sum(begin(), n); } + T + sum() const + { + return vnl_c_vector::sum(begin(), n); + } //: Check that size()==sz if not, abort(); // This function does or tests nothing if NDEBUG is defined #if !defined(NDEBUG) - void assert_size( unsigned sz ) const { assert( sz == n ); } + void + assert_size(unsigned sz) const + { + assert(sz == n); + } #else - void assert_size( unsigned /* sz */ ) const { } + void + assert_size(unsigned /* sz */) const + {} #endif //: Check that this is finite if not, abort(); // This function does or tests nothing if NDEBUG is defined - void assert_finite() const { + void + assert_finite() const + { #ifndef NDEBUG assert_finite_internal(); #endif } //: Return true if it's finite - bool is_finite() const; + bool + is_finite() const; //: Return true iff all the entries are zero. - bool is_zero() const; + bool + is_zero() const; //: Return true iff the size is zero. - bool empty() const { return n==0; } + bool + empty() const + { + return n == 0; + } //: Return true if *this == v - bool operator_eq (vnl_vector_fixed_ref_const const& v) const { - for ( size_type i = 0; i < n; ++i ) - if ( (*this)[i] != v[i] ) + bool + operator_eq(const vnl_vector_fixed_ref_const & v) const + { + for (size_type i = 0; i < n; ++i) + if ((*this)[i] != v[i]) return false; return true; } //: Return true if *this == v - bool operator_eq (vnl_vector const& v) const { - assert( v.size() == n ); - for ( size_type i = 0; i < n; ++i ) - if ( (*this)[i] != v[i] ) + bool + operator_eq(const vnl_vector & v) const + { + assert(v.size() == n); + for (size_type i = 0; i < n; ++i) + if ((*this)[i] != v[i]) return false; return true; } @@ -231,206 +361,303 @@ class VNL_EXPORT vnl_vector_fixed_ref_const //: Display the vector // Output each element separated by a single space. - void print( std::ostream& s ) const; + void + print(std::ostream & s) const; - public: +public: // Helper routines for arithmetic. n is the size, and is the // template parameter. - inline static void add( const T* a, const T* b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++a,++b ) + static inline void + add(const T * a, const T * b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++a, ++b) *r = *a + *b; } - inline static void add( const T* a, T b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++a ) + static inline void + add(const T * a, T b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++a) *r = *a + b; } - inline static void sub( const T* a, const T* b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++a,++b ) + static inline void + sub(const T * a, const T * b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++a, ++b) *r = *a - *b; } - inline static void sub( const T* a, T b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++a ) + static inline void + sub(const T * a, T b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++a) *r = *a - b; } - inline static void sub( T a, const T* b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++b ) + static inline void + sub(T a, const T * b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++b) *r = a - *b; } - inline static void mul( const T* a, const T* b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++a,++b ) + static inline void + mul(const T * a, const T * b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++a, ++b) *r = *a * *b; } - inline static void mul( const T* a, T b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++a ) + static inline void + mul(const T * a, T b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++a) *r = *a * b; } - inline static void div( const T* a, const T* b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++a,++b ) + static inline void + div(const T * a, const T * b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++a, ++b) *r = *a / *b; } - inline static void div( const T* a, T b, T* r ) { - for ( unsigned int i=0; i < n; ++i,++r,++a ) + static inline void + div(const T * a, T b, T * r) + { + for (unsigned int i = 0; i < n; ++i, ++r, ++a) *r = *a / b; } //: Equality operator - bool operator==(vnl_vector_fixed_ref_const const &that) const { return this->operator_eq(that); } + bool + operator==(const vnl_vector_fixed_ref_const & that) const + { + return this->operator_eq(that); + } //: Inequality operator - bool operator!=(vnl_vector_fixed_ref_const const &that) const { return !this->operator_eq(that); } + bool + operator!=(const vnl_vector_fixed_ref_const & that) const + { + return !this->operator_eq(that); + } - private: +private: //: See assert_finite(). - const vnl_vector_fixed_ref_const & operator=(const vnl_vector_fixed & ) const + const vnl_vector_fixed_ref_const & + operator=(const vnl_vector_fixed &) const { assert(!"Assignment is illegal for a vnl_vector_fixed_ref_const"); return *this; } - const vnl_vector_fixed_ref_const & operator=(const vnl_vector_fixed_ref_const & ) const + const vnl_vector_fixed_ref_const & + operator=(const vnl_vector_fixed_ref_const &) const { assert(!"Assignment is illegal for a vnl_vector_fixed_ref_const"); return *this; } - void assert_finite_internal() const; + void + assert_finite_internal() const; }; // Non const vector fixed reference template -class VNL_EXPORT vnl_vector_fixed_ref : public vnl_vector_fixed_ref_const +class VNL_EXPORT vnl_vector_fixed_ref : public vnl_vector_fixed_ref_const { - typedef vnl_vector_fixed_ref_const base; + typedef vnl_vector_fixed_ref_const base; - public: +public: typedef unsigned int size_type; // this is the only point where the const_cast happens // the base class is used to store the pointer, so that conversion is not necessary - T * data_block() const { return const_cast(this->data_); } + T * + data_block() const + { + return const_cast(this->data_); + } - vnl_vector_fixed_ref(vnl_vector_fixed& rhs) : base(rhs.data_block()) {} + vnl_vector_fixed_ref(vnl_vector_fixed & rhs) + : base(rhs.data_block()) + {} - explicit vnl_vector_fixed_ref(T * dataptr) : base(dataptr) {} + explicit vnl_vector_fixed_ref(T * dataptr) + : base(dataptr) + {} //: Copy operator - vnl_vector_fixed_ref const & operator=( const vnl_vector_fixed& rhs ) const { - std::memcpy( data_block(), rhs.data_block(), n * sizeof(T) ); + const vnl_vector_fixed_ref & + operator=(const vnl_vector_fixed & rhs) const + { + std::memcpy(data_block(), rhs.data_block(), n * sizeof(T)); return *this; } //: Copy operator - vnl_vector_fixed_ref const& operator=( const vnl_vector_fixed_ref& rhs ) const { - std::memcpy( data_block(), rhs.data_block(), n * sizeof(T) ); + const vnl_vector_fixed_ref & + operator=(const vnl_vector_fixed_ref & rhs) const + { + std::memcpy(data_block(), rhs.data_block(), n * sizeof(T)); return *this; } //: Copy operator - vnl_vector_fixed_ref const& operator=( const vnl_vector_fixed_ref_const& rhs ) const { - std::memcpy( data_block(), rhs.data_block(), n * sizeof(T) ); + const vnl_vector_fixed_ref & + operator=(const vnl_vector_fixed_ref_const & rhs) const + { + std::memcpy(data_block(), rhs.data_block(), n * sizeof(T)); return *this; } //: Put value at given position in vector. - void put (unsigned int i, T const& v) const { data_block()[i] = v; } + void + put(unsigned int i, const T & v) const + { + data_block()[i] = v; + } //: Set all values to v - vnl_vector_fixed_ref& fill( T const& v ) + vnl_vector_fixed_ref & + fill(const T & v) { - for ( size_type i = 0; i < n; ++i ) data_block()[i] = v; + for (size_type i = 0; i < n; ++i) + data_block()[i] = v; return *this; } //: Sets elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - vnl_vector_fixed_ref const& copy_in( T const * ptr ) const + const vnl_vector_fixed_ref & + copy_in(const T * ptr) const { - for ( size_type i = 0; i < n; ++i ) data_block()[i] = ptr[i]; + for (size_type i = 0; i < n; ++i) + data_block()[i] = ptr[i]; return *this; } //: Sets elements to ptr[i] // Note: ptr[i] must be valid for i=0..size()-1 - vnl_vector_fixed_ref const& set( T const *ptr ) const { copy_in(ptr); return *this; } + const vnl_vector_fixed_ref & + set(const T * ptr) const + { + copy_in(ptr); + return *this; + } //: Return reference to the element at specified index. // There are assert style boundary checks - #define NDEBUG to turn them off. - T & operator() (unsigned int i) const + T & + operator()(unsigned int i) const { -#if VNL_CONFIG_CHECK_BOUNDS && (!defined NDEBUG) - assert(i const&, unsigned int start=0) const; + const vnl_vector_fixed_ref & + update(const vnl_vector &, unsigned int start = 0) const; //: Read from text stream - bool read_ascii(std::istream& s) const; + bool + read_ascii(std::istream & s) const; - vnl_vector_fixed_ref const& flip() const; + const vnl_vector_fixed_ref & + flip() const; //: - vnl_vector_fixed_ref const & operator+=( T s ) const { - base::add( data_block(), s, data_block() ); return *this; + const vnl_vector_fixed_ref & + operator+=(T s) const + { + base::add(data_block(), s, data_block()); + return *this; } //: - vnl_vector_fixed_ref const & operator-=( T s ) const { - base::sub( data_block(), s, data_block() ); return *this; + const vnl_vector_fixed_ref & + operator-=(T s) const + { + base::sub(data_block(), s, data_block()); + return *this; } //: - vnl_vector_fixed_ref const & operator*=( T s ) const { - base::mul( data_block(), s, data_block() ); return *this; + const vnl_vector_fixed_ref & + operator*=(T s) const + { + base::mul(data_block(), s, data_block()); + return *this; } //: - vnl_vector_fixed_ref const & operator/=( T s ) const { - base::div( data_block(), s, data_block() ); return *this; + const vnl_vector_fixed_ref & + operator/=(T s) const + { + base::div(data_block(), s, data_block()); + return *this; } //: - vnl_vector_fixed_ref const & operator+=( const vnl_vector_fixed& v ) const { - base::add( data_block(), v.data_block(), data_block() ); return *this; + const vnl_vector_fixed_ref & + operator+=(const vnl_vector_fixed & v) const + { + base::add(data_block(), v.data_block(), data_block()); + return *this; } //: - vnl_vector_fixed_ref const & operator-=( const vnl_vector_fixed& v ) const { - base::sub( data_block(), v.data_block(), data_block() ); return *this; + const vnl_vector_fixed_ref & + operator-=(const vnl_vector_fixed & v) const + { + base::sub(data_block(), v.data_block(), data_block()); + return *this; } //: - vnl_vector_fixed_ref const & operator+=( const vnl_vector& v ) const { - assert( v.size() == n ); - base::add( data_block(), v.data_block(), data_block() ); return *this; + const vnl_vector_fixed_ref & + operator+=(const vnl_vector & v) const + { + assert(v.size() == n); + base::add(data_block(), v.data_block(), data_block()); + return *this; } //: - vnl_vector_fixed_ref const & operator-=( const vnl_vector& v ) const { - assert( v.size() == n ); - base::sub( data_block(), v.data_block(), data_block() ); return *this; + const vnl_vector_fixed_ref & + operator-=(const vnl_vector & v) const + { + assert(v.size() == n); + base::sub(data_block(), v.data_block(), data_block()); + return *this; } }; @@ -443,65 +670,72 @@ class VNL_EXPORT vnl_vector_fixed_ref : public vnl_vector_fixed_ref_const //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator+( const vnl_vector_fixed_ref_const& v, T s ) +template +inline vnl_vector_fixed +operator+(const vnl_vector_fixed_ref_const & v, T s) { - vnl_vector_fixed r; - vnl_vector_fixed::add( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::add(v.data_block(), s, r.data_block()); return r; } //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator+( T s, const vnl_vector_fixed_ref_const& v ) +template +inline vnl_vector_fixed +operator+(T s, const vnl_vector_fixed_ref_const & v) { - vnl_vector_fixed r; - vnl_vector_fixed::add( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::add(v.data_block(), s, r.data_block()); return r; } //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator-( const vnl_vector_fixed_ref_const& v, T s ) +template +inline vnl_vector_fixed +operator-(const vnl_vector_fixed_ref_const & v, T s) { - vnl_vector_fixed r; - vnl_vector_fixed::sub( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::sub(v.data_block(), s, r.data_block()); return r; } //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator-( T s, const vnl_vector_fixed_ref_const& v ) +template +inline vnl_vector_fixed +operator-(T s, const vnl_vector_fixed_ref_const & v) { - vnl_vector_fixed r; - vnl_vector_fixed::sub( s, v.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::sub(s, v.data_block(), r.data_block()); return r; } //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator*( const vnl_vector_fixed_ref_const& v, T s ) +template +inline vnl_vector_fixed +operator*(const vnl_vector_fixed_ref_const & v, T s) { - vnl_vector_fixed r; - vnl_vector_fixed::mul( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::mul(v.data_block(), s, r.data_block()); return r; } //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator*( T s, const vnl_vector_fixed_ref_const& v ) +template +inline vnl_vector_fixed +operator*(T s, const vnl_vector_fixed_ref_const & v) { - vnl_vector_fixed r; - vnl_vector_fixed::mul( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::mul(v.data_block(), s, r.data_block()); return r; } //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator/( const vnl_vector_fixed_ref_const& v, T s ) +template +inline vnl_vector_fixed +operator/(const vnl_vector_fixed_ref_const & v, T s) { - vnl_vector_fixed r; - vnl_vector_fixed::div( v.data_block(), s, r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::div(v.data_block(), s, r.data_block()); return r; } @@ -510,43 +744,48 @@ inline vnl_vector_fixed operator/( const vnl_vector_fixed_ref_const& v //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator+( const vnl_vector_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_vector_fixed +operator+(const vnl_vector_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - vnl_vector_fixed r; - vnl_vector_fixed::add( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::add(a.data_block(), b.data_block(), r.data_block()); return r; } //: \relatesalso vnl_vector_fixed -template -inline vnl_vector_fixed operator-( const vnl_vector_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_vector_fixed +operator-(const vnl_vector_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - vnl_vector_fixed r; - vnl_vector_fixed::sub( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::sub(a.data_block(), b.data_block(), r.data_block()); return r; } -template -inline vnl_vector_fixed element_product( const vnl_vector_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_vector_fixed +element_product(const vnl_vector_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - vnl_vector_fixed r; - vnl_vector_fixed::mul( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::mul(a.data_block(), b.data_block(), r.data_block()); return r; } -template -inline vnl_vector_fixed element_quotient( const vnl_vector_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_vector_fixed +element_quotient(const vnl_vector_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - vnl_vector_fixed r; - vnl_vector_fixed::div( a.data_block(), b.data_block(), r.data_block() ); + vnl_vector_fixed r; + vnl_vector_fixed::div(a.data_block(), b.data_block(), r.data_block()); return r; } -template -vnl_vector_fixed vnl_cross_3d(vnl_vector_fixed_ref_const const& v1, vnl_vector_fixed_ref_const const& v2) +template +vnl_vector_fixed +vnl_cross_3d(const vnl_vector_fixed_ref_const & v1, const vnl_vector_fixed_ref_const & v2) { - vnl_vector_fixed result; + vnl_vector_fixed result; result[0] = v1[1] * v2[2] - v1[2] * v2[1]; result[1] = v1[2] * v2[0] - v1[0] * v2[2]; @@ -558,116 +797,136 @@ vnl_vector_fixed vnl_cross_3d(vnl_vector_fixed_ref_const const& v1, vn // non-fixed. Because the operator* are templated, the fixed will not // be automatically converted to a non-fixed-ref. These do it for you. -template -inline vnl_vector operator+( const vnl_vector_fixed_ref_const& a, const vnl_vector& b ) +template +inline vnl_vector +operator+(const vnl_vector_fixed_ref_const & a, const vnl_vector & b) { return a.as_ref() + b; } -template -inline vnl_vector operator+( const vnl_vector& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_vector +operator+(const vnl_vector & a, const vnl_vector_fixed_ref_const & b) { return a + b.as_ref(); } -template -inline vnl_vector operator-( const vnl_vector_fixed_ref_const& a, const vnl_vector& b ) +template +inline vnl_vector +operator-(const vnl_vector_fixed_ref_const & a, const vnl_vector & b) { return a.as_ref() - b; } -template -inline vnl_vector operator-( const vnl_vector& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_vector +operator-(const vnl_vector & a, const vnl_vector_fixed_ref_const & b) { return a - b.as_ref(); } -template -inline T dot_product( const vnl_vector_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b ) +template +inline T +dot_product(const vnl_vector_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - return dot_product( a.as_ref(), b.as_ref() ); + return dot_product(a.as_ref(), b.as_ref()); } -template -inline T dot_product( const vnl_vector_fixed_ref_const& a, const vnl_vector& b ) +template +inline T +dot_product(const vnl_vector_fixed_ref_const & a, const vnl_vector & b) { - return dot_product( a.as_ref(), b ); + return dot_product(a.as_ref(), b); } -template -inline T dot_product( const vnl_vector& a, const vnl_vector_fixed_ref_const& b ) +template +inline T +dot_product(const vnl_vector & a, const vnl_vector_fixed_ref_const & b) { - return dot_product( a, b.as_ref() ); + return dot_product(a, b.as_ref()); } -template -inline vnl_matrix_fixed outer_product( const vnl_vector_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_matrix_fixed +outer_product(const vnl_vector_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - vnl_matrix_fixed out; // = a.column() * b.row() + vnl_matrix_fixed out; // = a.column() * b.row() for (unsigned int i = 0; i < m; i++) for (unsigned int j = 0; j < n; j++) out[i][j] = a[i] * b[j]; return out; } -template - inline vnl_vector_fixed vnl_cross_3d( const vnl_vector_fixed_ref_const& a, const vnl_vector& b ) { - return vnl_cross_3d( a.as_ref(), b); +template +inline vnl_vector_fixed +vnl_cross_3d(const vnl_vector_fixed_ref_const & a, const vnl_vector & b) +{ + return vnl_cross_3d(a.as_ref(), b); } -template - inline vnl_vector_fixed vnl_cross_3d( const vnl_vector& a, const vnl_vector_fixed_ref_const& b ) { - return vnl_cross_3d( a, b.as_ref()); +template +inline vnl_vector_fixed +vnl_cross_3d(const vnl_vector & a, const vnl_vector_fixed_ref_const & b) +{ + return vnl_cross_3d(a, b.as_ref()); } -template -inline vnl_matrix outer_product( const vnl_vector& a, const vnl_vector_fixed_ref_const& b ) +template +inline vnl_matrix +outer_product(const vnl_vector & a, const vnl_vector_fixed_ref_const & b) { - return outer_product( a, b.as_ref()); + return outer_product(a, b.as_ref()); } -template -inline vnl_matrix outer_product( const vnl_vector_fixed_ref_const& a, const vnl_vector& b ) +template +inline vnl_matrix +outer_product(const vnl_vector_fixed_ref_const & a, const vnl_vector & b) { - return outer_product( a.as_ref(), b); + return outer_product(a.as_ref(), b); } -template -inline T angle( const vnl_vector_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b ) +template +inline T +angle(const vnl_vector_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - return angle( a.as_ref(), b.as_ref() ); + return angle(a.as_ref(), b.as_ref()); } -template -inline T angle( const vnl_vector_fixed_ref_const& a, const vnl_vector& b ) +template +inline T +angle(const vnl_vector_fixed_ref_const & a, const vnl_vector & b) { - return angle( a.as_ref(), b ); + return angle(a.as_ref(), b); } -template -inline T angle( const vnl_vector& a, const vnl_vector_fixed_ref_const& b ) +template +inline T +angle(const vnl_vector & a, const vnl_vector_fixed_ref_const & b) { - return angle( a, b.as_ref() ); + return angle(a, b.as_ref()); } -template -inline T vnl_vector_ssd( const vnl_vector_fixed_ref_const& a, const vnl_vector_fixed_ref_const& b ) +template +inline T +vnl_vector_ssd(const vnl_vector_fixed_ref_const & a, const vnl_vector_fixed_ref_const & b) { - return vnl_vector_ssd( a.as_ref(), b.as_ref() ); + return vnl_vector_ssd(a.as_ref(), b.as_ref()); } -template -inline T vnl_vector_ssd( const vnl_vector_fixed_ref_const& a, const vnl_vector& b ) +template +inline T +vnl_vector_ssd(const vnl_vector_fixed_ref_const & a, const vnl_vector & b) { - return vnl_vector_ssd( a.as_ref(), b ); + return vnl_vector_ssd(a.as_ref(), b); } -template -inline T vnl_vector_ssd( const vnl_vector& a, const vnl_vector_fixed_ref_const& b ) +template +inline T +vnl_vector_ssd(const vnl_vector & a, const vnl_vector_fixed_ref_const & b) { - return vnl_vector_ssd( a, b.as_ref() ); + return vnl_vector_ssd(a, b.as_ref()); } @@ -675,18 +934,18 @@ inline T vnl_vector_ssd( const vnl_vector& a, const vnl_vector_fixed_ref_cons //: \relatesalso vnl_vector_fixed -template -inline -std::ostream& operator<<(std::ostream& o,const vnl_vector_fixed_ref_const& v) +template +inline std::ostream & +operator<<(std::ostream & o, const vnl_vector_fixed_ref_const & v) { v.print(o); return o; } //: \relatesalso vnl_vector_fixed -template -inline -std::istream& operator>>(std::istream& i, const vnl_vector_fixed_ref& v) +template +inline std::istream & +operator>>(std::istream & i, const vnl_vector_fixed_ref & v) { v.read_ascii(i); return i; diff --git a/core/vnl/vnl_vector_fixed_ref.hxx b/core/vnl/vnl_vector_fixed_ref.hxx index 572c41144ca..0ba7a794d70 100644 --- a/core/vnl/vnl_vector_fixed_ref.hxx +++ b/core/vnl/vnl_vector_fixed_ref.hxx @@ -12,66 +12,66 @@ #ifdef _MSC_VER # include #endif -#include "vnl_math.h" // for vnl_math::isfinite +#include "vnl_math.h" // for vnl_math::isfinite //------------------------------------------------------------ -template -vnl_vector_fixed -vnl_vector_fixed_ref_const::apply( T (*f)(T) ) const +template +vnl_vector_fixed +vnl_vector_fixed_ref_const::apply(T (*f)(T)) const { - vnl_vector_fixed ret; - for ( size_type i = 0; i < n; ++i ) - ret[i] = f( data_block()[i] ); + vnl_vector_fixed ret; + for (size_type i = 0; i < n; ++i) + ret[i] = f(data_block()[i]); return ret; } -template -vnl_vector_fixed -vnl_vector_fixed_ref_const::apply( T (*f)(const T&) ) const +template +vnl_vector_fixed +vnl_vector_fixed_ref_const::apply(T (*f)(const T &)) const { - vnl_vector_fixed ret; - for ( size_type i = 0; i < n; ++i ) - ret[i] = f( data_block()[i] ); + vnl_vector_fixed ret; + for (size_type i = 0; i < n; ++i) + ret[i] = f(data_block()[i]); return ret; } -template +template vnl_vector -vnl_vector_fixed_ref_const::extract( unsigned int len, unsigned int start ) const +vnl_vector_fixed_ref_const::extract(unsigned int len, unsigned int start) const { - assert( start < n && start + len <= n ); - return vnl_vector( data_block() + start, len ); + assert(start < n && start + len <= n); + return vnl_vector(data_block() + start, len); } -template -vnl_vector_fixed_ref const& -vnl_vector_fixed_ref::update( const vnl_vector& v, unsigned int start ) const +template +const vnl_vector_fixed_ref & +vnl_vector_fixed_ref::update(const vnl_vector & v, unsigned int start) const { - size_type stop = start + v.size(); - assert( stop <= n ); + const size_type stop = start + v.size(); + assert(stop <= n); for (size_type i = start; i < stop; i++) - this->data_block()[i] = v[i-start]; + this->data_block()[i] = v[i - start]; return *this; } template -vnl_vector_fixed_ref const& -vnl_vector_fixed_ref::flip() const +const vnl_vector_fixed_ref & +vnl_vector_fixed_ref::flip() const { - for ( unsigned int i=0; 2*i+1 < n; ++i ) - std::swap( data_block()[i], data_block()[n-1-i] ); + for (unsigned int i = 0; 2 * i + 1 < n; ++i) + std::swap(data_block()[i], data_block()[n - 1 - i]); return *this; } template bool -vnl_vector_fixed_ref_const::is_finite() const +vnl_vector_fixed_ref_const::is_finite() const { - for ( size_type i = 0; i < this->size(); ++i ) - if ( !vnl_math::isfinite( (*this)[i] ) ) + for (size_type i = 0; i < this->size(); ++i) + if (!vnl_math::isfinite((*this)[i])) return false; return true; @@ -80,11 +80,11 @@ vnl_vector_fixed_ref_const::is_finite() const template bool -vnl_vector_fixed_ref_const::is_zero() const +vnl_vector_fixed_ref_const::is_zero() const { - T const zero(0); - for ( size_type i = 0; i < this->size(); ++i ) - if ( !( (*this)[i] == zero) ) + const T zero(0); + for (size_type i = 0; i < this->size(); ++i) + if (!((*this)[i] == zero)) return false; return true; @@ -93,7 +93,7 @@ vnl_vector_fixed_ref_const::is_zero() const template bool -vnl_vector_fixed_ref::read_ascii(std::istream& s) const +vnl_vector_fixed_ref::read_ascii(std::istream & s) const { for (unsigned i = 0; i < this->size(); ++i) s >> (*this)(i); @@ -103,7 +103,7 @@ vnl_vector_fixed_ref::read_ascii(std::istream& s) const template void -vnl_vector_fixed_ref_const::assert_finite_internal() const +vnl_vector_fixed_ref_const::assert_finite_internal() const { if (this->is_finite()) return; @@ -114,18 +114,18 @@ vnl_vector_fixed_ref_const::assert_finite_internal() const template void -vnl_vector_fixed_ref_const::print( std::ostream& s ) const +vnl_vector_fixed_ref_const::print(std::ostream & s) const { - if ( this->size() > 0 ) + if (this->size() > 0) s << (*this)[0]; - for ( size_type i = 1; i < this->size(); ++i ) + for (size_type i = 1; i < this->size(); ++i) s << ' ' << (*this)[i]; } // instantiation macros for vnl_vector_fixed_ref : -#define VNL_VECTOR_FIXED_REF_INSTANTIATE(T,n) \ -template class vnl_vector_fixed_ref; \ -template class vnl_vector_fixed_ref_const +#define VNL_VECTOR_FIXED_REF_INSTANTIATE(T, n) \ + template class vnl_vector_fixed_ref; \ + template class vnl_vector_fixed_ref_const #endif // vnl_vector_fixed_ref_hxx_ diff --git a/core/vnl/vnl_vector_ref.h b/core/vnl/vnl_vector_ref.h index f987190d27a..86c7ddeaca7 100644 --- a/core/vnl/vnl_vector_ref.h +++ b/core/vnl/vnl_vector_ref.h @@ -23,7 +23,7 @@ template class VNL_EXPORT vnl_vector_ref : public vnl_vector { - public: +public: using Base = vnl_vector; //: Constructor @@ -32,13 +32,13 @@ class VNL_EXPORT vnl_vector_ref : public vnl_vector // and can only be used on data in a read/write senses. // There is no way to pass 'const T *' in a way that vnl_vector_ref // can preserve memory access. - vnl_vector_ref(size_t n, T *space); + vnl_vector_ref(size_t n, T * space); //: Copy constructor // Do \e not call anything else than the default constructor of vnl_vector // (That is why the default copy constructor is \e not good.) // NOTE: This interface breaks const correctness, - vnl_vector_ref(const vnl_vector_ref& v); + vnl_vector_ref(const vnl_vector_ref & v); //: Destructor // Prevents base destructor from releasing memory we don't own @@ -58,37 +58,54 @@ class VNL_EXPORT vnl_vector_ref : public vnl_vector // \attention Use this only to pass the reference to a // function. Otherwise, the underlying object will be destructed and // you'll be left with undefined behaviour. - vnl_vector_ref& non_const(); + vnl_vector_ref & + non_const(); //: Copy and move constructor from vnl_matrix_ref is disallowed by default // due to other constructor definitions. //: assignment and move-assignment is disallowed // because it does not define external memory to be managed. - vnl_vector_ref & operator=( vnl_vector_ref const& ) = delete; - vnl_vector_ref & operator=( vnl_vector_ref && ) = delete; + vnl_vector_ref & + operator=(const vnl_vector_ref &) = delete; + vnl_vector_ref & + operator=(vnl_vector_ref &&) = delete; //: Explicit conversion to a vnl_vector_ref or vnl_vector. // This is a cheap conversion for those functions that have an interface // for vnl_vector but not for vnl_vector_fixed. There is also a // conversion operator that should work most of the time. // \sa vnl_vector_ref::non_const - vnl_vector_ref as_ref() { return *this; } - const vnl_vector_ref as_ref() const { return *this; } - vnl_vector as_vector() const { return vnl_vector(this->data_block(), this->size()); } + vnl_vector_ref + as_ref() + { + return *this; + } + const vnl_vector_ref + as_ref() const + { + return *this; + } + vnl_vector + as_vector() const + { + return vnl_vector(this->data_block(), this->size()); + } }; //: Create a reference vector with part of an existing vector. template -inline const vnl_vector_ref vnl_vector_ref_extract(const vnl_vector &v, unsigned start, unsigned len) +inline const vnl_vector_ref +vnl_vector_ref_extract(const vnl_vector & v, unsigned start, unsigned len) { - return vnl_vector_ref(len, const_cast(v.data_block()+start)); + return vnl_vector_ref(len, const_cast(v.data_block() + start)); } //: Create a reference vector with part of an existing vector. template -inline vnl_vector_ref vnl_vector_ref_extract(vnl_vector &v, unsigned start, unsigned len) +inline vnl_vector_ref +vnl_vector_ref_extract(vnl_vector & v, unsigned start, unsigned len) { - return vnl_vector_ref(len, v.data_block()+start); + return vnl_vector_ref(len, v.data_block() + start); } diff --git a/core/vnl/vnl_vector_ref.hxx b/core/vnl/vnl_vector_ref.hxx index 70f3e313860..d002dc633f4 100644 --- a/core/vnl/vnl_vector_ref.hxx +++ b/core/vnl/vnl_vector_ref.hxx @@ -9,27 +9,27 @@ #ifdef _MSC_VER # include #endif -#include "vnl_math.h" // for vnl_math::isfinite +#include "vnl_math.h" // for vnl_math::isfinite //------------------------------------------------------------ template vnl_vector_ref::vnl_vector_ref(size_t n, T * space) - : vnl_vector(n, space, false) + : vnl_vector(n, space, false) {} template vnl_vector_ref::vnl_vector_ref(const vnl_vector_ref & v) - : vnl_vector(v.size(), const_cast(v.data_block()),false) + : vnl_vector(v.size(), const_cast(v.data_block()), false) {} template -vnl_vector_ref& vnl_vector_ref::non_const() +vnl_vector_ref & +vnl_vector_ref::non_const() { return *this; } -#define VNL_VECTOR_REF_INSTANTIATE(T) \ -template class vnl_vector_ref +#define VNL_VECTOR_REF_INSTANTIATE(T) template class vnl_vector_ref #endif // vnl_vector_ref_hxx_ diff --git a/core/vnl/xio/vnl_xio_matrix.h b/core/vnl/xio/vnl_xio_matrix.h index af0d66e5b6c..66d1d0f55df 100644 --- a/core/vnl/xio/vnl_xio_matrix.h +++ b/core/vnl/xio/vnl_xio_matrix.h @@ -31,14 +31,14 @@ //: XML save vnl_matrix to stream. // \relatesalso vnl_matrix template -void VNL_EXPORT x_write(std::ostream & os, vnl_matrix const& v, - std::string name="vnl_matrix"); +void VNL_EXPORT +x_write(std::ostream & os, const vnl_matrix & v, std::string name = "vnl_matrix"); //: XML save vnl_matrix as a 3-level tree to stream. // \relatesalso vnl_matrix template -void VNL_EXPORT x_write_tree(std::ostream & os, vnl_matrix const& v, - std::string name="vnl_matrix"); +void VNL_EXPORT +x_write_tree(std::ostream & os, const vnl_matrix & v, std::string name = "vnl_matrix"); #define VNL_XIO_MATRIX_INSTANTIATE(T) extern "Please #include first" diff --git a/core/vnl/xio/vnl_xio_matrix.hxx b/core/vnl/xio/vnl_xio_matrix.hxx index 1e08193556a..a94aa7d980e 100644 --- a/core/vnl/xio/vnl_xio_matrix.hxx +++ b/core/vnl/xio/vnl_xio_matrix.hxx @@ -7,31 +7,36 @@ #include //================================================================================= -template -void x_write(std::ostream & os, vnl_matrix const& M, std::string name) +template +void +x_write(std::ostream & os, const vnl_matrix & M, std::string name) { vsl_basic_xml_element element(name); - element.add_attribute("rows", (int) M.rows()); - element.add_attribute("cols", (int) M.cols()); - for (unsigned int r=0; r -void x_write_tree(std::ostream & os, vnl_matrix const& M, std::string name) +template +void +x_write_tree(std::ostream & os, const vnl_matrix & M, std::string name) { vsl_basic_xml_element element(name); - element.add_attribute("rows", (int) M.rows()); - element.add_attribute("cols", (int) M.cols()); - for (unsigned int r=0; r"); - for (unsigned int c=0; c"); - element.append_cdata(M.get(r,c)); + element.append_cdata(M.get(r, c)); element.append_cdata(""); } element.append_cdata(""); @@ -40,8 +45,8 @@ void x_write_tree(std::ostream & os, vnl_matrix const& M, std::string name) } #undef VNL_XIO_MATRIX_INSTANTIATE -#define VNL_XIO_MATRIX_INSTANTIATE(T) \ -template VNL_EXPORT void x_write(std::ostream &, vnl_matrix const&, std::string); \ -template VNL_EXPORT void x_write_tree(std::ostream &, vnl_matrix const&, std::string) +#define VNL_XIO_MATRIX_INSTANTIATE(T) \ + template VNL_EXPORT void x_write(std::ostream &, vnl_matrix const &, std::string); \ + template VNL_EXPORT void x_write_tree(std::ostream &, vnl_matrix const &, std::string) #endif // vnl_xio_matrix_hxx_ diff --git a/core/vnl/xio/vnl_xio_matrix_fixed.h b/core/vnl/xio/vnl_xio_matrix_fixed.h index eadca5f5903..63274058af1 100644 --- a/core/vnl/xio/vnl_xio_matrix_fixed.h +++ b/core/vnl/xio/vnl_xio_matrix_fixed.h @@ -31,14 +31,14 @@ //: XML save vnl_matrix_fixed to stream. // \relatesalso vnl_matrix_fixed template -void x_write(std::ostream & os, vnl_matrix_fixed const& v, - std::string name="vnl_matrix_fixed"); +void +x_write(std::ostream & os, const vnl_matrix_fixed & v, std::string name = "vnl_matrix_fixed"); //: XML save vnl_matrix_fixed as a 3-level tree to stream. // \relatesalso vnl_matrix_fixed template -void x_write_tree(std::ostream & os, vnl_matrix_fixed const& v, - std::string name="vnl_matrix_fixed"); +void +x_write_tree(std::ostream & os, const vnl_matrix_fixed & v, std::string name = "vnl_matrix_fixed"); #define VNL_XIO_MATRIX_FIXED_INSTANTIATE(T) extern "Please #include first" diff --git a/core/vnl/xio/vnl_xio_matrix_fixed.hxx b/core/vnl/xio/vnl_xio_matrix_fixed.hxx index 3dee39257b4..7a60a7e6e55 100644 --- a/core/vnl/xio/vnl_xio_matrix_fixed.hxx +++ b/core/vnl/xio/vnl_xio_matrix_fixed.hxx @@ -7,31 +7,36 @@ #include //================================================================================= -template -void x_write(std::ostream & os, vnl_matrix_fixed const& M, std::string name) +template +void +x_write(std::ostream & os, const vnl_matrix_fixed & M, std::string name) { vsl_basic_xml_element element(name); - element.add_attribute("rows", (int) m); - element.add_attribute("cols", (int) n); - for (unsigned int r=0; r -void x_write_tree(std::ostream & os, vnl_matrix_fixed const& M, std::string name) +template +void +x_write_tree(std::ostream & os, const vnl_matrix_fixed & M, std::string name) { vsl_basic_xml_element element(name); - element.add_attribute("rows", (int) m); - element.add_attribute("cols", (int) n); - for (unsigned int r=0; r"); - for (unsigned int c=0; c"); - element.append_cdata(M.get(r,c)); + element.append_cdata(M.get(r, c)); element.append_cdata(""); } element.append_cdata(""); @@ -40,8 +45,8 @@ void x_write_tree(std::ostream & os, vnl_matrix_fixed const& M, std::stri } #undef VNL_XIO_MATRIX_FIXED_INSTANTIATE -#define VNL_XIO_MATRIX_FIXED_INSTANTIATE(T,m,n) \ -template void x_write(std::ostream &, vnl_matrix_fixed const&, std::string); \ -template void x_write_tree(std::ostream &, vnl_matrix_fixed const&, std::string) +#define VNL_XIO_MATRIX_FIXED_INSTANTIATE(T, m, n) \ + template void x_write(std::ostream &, vnl_matrix_fixed const &, std::string); \ + template void x_write_tree(std::ostream &, vnl_matrix_fixed const &, std::string) #endif // vnl_xio_matrix_fixed_hxx_ diff --git a/core/vnl/xio/vnl_xio_quaternion.h b/core/vnl/xio/vnl_xio_quaternion.h index 318d657f2f8..30232c3b717 100644 --- a/core/vnl/xio/vnl_xio_quaternion.h +++ b/core/vnl/xio/vnl_xio_quaternion.h @@ -28,14 +28,14 @@ //: XML save vnl_quaternion to stream. // \relatesalso vnl_quaternion template -void x_write(std::ostream & os, vnl_quaternion const& v, - std::string name="vnl_quaternion"); +void +x_write(std::ostream & os, const vnl_quaternion & v, std::string name = "vnl_quaternion"); //: XML save vnl_quaternion as a 2-level tree to stream. // \relatesalso vnl_quaternion template -void x_write_tree(std::ostream & os, vnl_quaternion const& v, - std::string name="vnl_quaternion"); +void +x_write_tree(std::ostream & os, const vnl_quaternion & v, std::string name = "vnl_quaternion"); #define VNL_XIO_QUATERNION_INSTANTIATE(T) extern "Please #include first" diff --git a/core/vnl/xio/vnl_xio_quaternion.hxx b/core/vnl/xio/vnl_xio_quaternion.hxx index 09989ee7866..7248d7596f3 100644 --- a/core/vnl/xio/vnl_xio_quaternion.hxx +++ b/core/vnl/xio/vnl_xio_quaternion.hxx @@ -7,8 +7,9 @@ #include //================================================================================= -template -void x_write(std::ostream & os, vnl_quaternion const& q, std::string name) +template +void +x_write(std::ostream & os, const vnl_quaternion & q, std::string name) { vsl_basic_xml_element element(name); element.add_attribute("x", q.x()); @@ -19,20 +20,29 @@ void x_write(std::ostream & os, vnl_quaternion const& q, std::string name) } //================================================================================= -template -void x_write_tree(std::ostream & os, vnl_quaternion const& q, std::string name) +template +void +x_write_tree(std::ostream & os, const vnl_quaternion & q, std::string name) { vsl_basic_xml_element element(name); - element.append_cdata(""); element.append_cdata(q.x()); element.append_cdata(""); - element.append_cdata(""); element.append_cdata(q.y()); element.append_cdata(""); - element.append_cdata(""); element.append_cdata(q.z()); element.append_cdata(""); - element.append_cdata(""); element.append_cdata(q.r()); element.append_cdata(""); + element.append_cdata(""); + element.append_cdata(q.x()); + element.append_cdata(""); + element.append_cdata(""); + element.append_cdata(q.y()); + element.append_cdata(""); + element.append_cdata(""); + element.append_cdata(q.z()); + element.append_cdata(""); + element.append_cdata(""); + element.append_cdata(q.r()); + element.append_cdata(""); element.x_write(os); } #undef VNL_XIO_QUATERNION_INSTANTIATE -#define VNL_XIO_QUATERNION_INSTANTIATE(T) \ -template VNL_EXPORT void x_write(std::ostream &, vnl_quaternion const&, std::string); \ -template VNL_EXPORT void x_write_tree(std::ostream &, vnl_quaternion const&, std::string) +#define VNL_XIO_QUATERNION_INSTANTIATE(T) \ + template VNL_EXPORT void x_write(std::ostream &, vnl_quaternion const &, std::string); \ + template VNL_EXPORT void x_write_tree(std::ostream &, vnl_quaternion const &, std::string) #endif // vnl_xio_quaternion_hxx_ diff --git a/core/vnl/xio/vnl_xio_vector.h b/core/vnl/xio/vnl_xio_vector.h index b0e80441cd2..79f731be462 100644 --- a/core/vnl/xio/vnl_xio_vector.h +++ b/core/vnl/xio/vnl_xio_vector.h @@ -29,14 +29,14 @@ //: XML save vnl_vector to stream. // \relatesalso vnl_vector template -void x_write(std::ostream & os, vnl_vector const& v, - std::string name="vnl_vector"); +void +x_write(std::ostream & os, const vnl_vector & v, std::string name = "vnl_vector"); //: XML save vnl_vector as a 2-level tree to stream. // \relatesalso vnl_vector template -void x_write_tree(std::ostream & os, vnl_vector const& v, - std::string name="vnl_vector"); +void +x_write_tree(std::ostream & os, const vnl_vector & v, std::string name = "vnl_vector"); #define VNL_XIO_VECTOR_INSTANTIATE(T) extern "Please #include first" diff --git a/core/vnl/xio/vnl_xio_vector.hxx b/core/vnl/xio/vnl_xio_vector.hxx index 3a981f1b10d..64d57d442c6 100644 --- a/core/vnl/xio/vnl_xio_vector.hxx +++ b/core/vnl/xio/vnl_xio_vector.hxx @@ -6,23 +6,26 @@ #include //================================================================================= -template -void x_write(std::ostream & os, vnl_vector const& v, std::string name) +template +void +x_write(std::ostream & os, const vnl_vector & v, std::string name) { vsl_basic_xml_element element(name); element.add_attribute("size", v.size()); - for (unsigned i=0; i -void x_write_tree(std::ostream & os, vnl_vector const& v, std::string name) +template +void +x_write_tree(std::ostream & os, const vnl_vector & v, std::string name) { vsl_basic_xml_element element(name); element.add_attribute("size", v.size()); - for (unsigned i=0; i"); element.append_cdata(v.get(i)); element.append_cdata(""); @@ -31,8 +34,8 @@ void x_write_tree(std::ostream & os, vnl_vector const& v, std::string name) } #undef VNL_XIO_VECTOR_INSTANTIATE -#define VNL_XIO_VECTOR_INSTANTIATE(T) \ -template VNL_EXPORT void x_write(std::ostream &, vnl_vector const&, std::string); \ -template VNL_EXPORT void x_write_tree(std::ostream &, vnl_vector const&, std::string) +#define VNL_XIO_VECTOR_INSTANTIATE(T) \ + template VNL_EXPORT void x_write(std::ostream &, vnl_vector const &, std::string); \ + template VNL_EXPORT void x_write_tree(std::ostream &, vnl_vector const &, std::string) #endif // vnl_xio_vector_hxx_ diff --git a/core/vnl/xio/vnl_xio_vector_fixed.h b/core/vnl/xio/vnl_xio_vector_fixed.h index ea9490affcc..48835a904b1 100644 --- a/core/vnl/xio/vnl_xio_vector_fixed.h +++ b/core/vnl/xio/vnl_xio_vector_fixed.h @@ -30,14 +30,14 @@ //: XML save vnl_vector_fixed to stream. // \relatesalso vnl_vector_fixed template -void x_write(std::ostream & os, vnl_vector_fixed const& v, - std::string name="vnl_vector_fixed"); +void +x_write(std::ostream & os, const vnl_vector_fixed & v, std::string name = "vnl_vector_fixed"); //: XML save vnl_vector_fixed as a 2-level tree to stream. // \relatesalso vnl_vector_fixed template -void x_write_tree(std::ostream & os, vnl_vector_fixed const& v, - std::string name="vnl_vector_fixed"); +void +x_write_tree(std::ostream & os, const vnl_vector_fixed & v, std::string name = "vnl_vector_fixed"); #define VNL_XIO_VECTOR_FIXED_INSTANTIATE(T) extern "Please #include first" diff --git a/core/vnl/xio/vnl_xio_vector_fixed.hxx b/core/vnl/xio/vnl_xio_vector_fixed.hxx index 2c0053475f8..e542a6f4ef8 100644 --- a/core/vnl/xio/vnl_xio_vector_fixed.hxx +++ b/core/vnl/xio/vnl_xio_vector_fixed.hxx @@ -6,23 +6,26 @@ #include //================================================================================= -template -void x_write(std::ostream & os, vnl_vector_fixed const& v, std::string name) +template +void +x_write(std::ostream & os, const vnl_vector_fixed & v, std::string name) { vsl_basic_xml_element element(name); - element.add_attribute("size", (int) n); - for (unsigned i=0; i -void x_write_tree(std::ostream & os, vnl_vector_fixed const& v, std::string name) +template +void +x_write_tree(std::ostream & os, const vnl_vector_fixed & v, std::string name) { vsl_basic_xml_element element(name); - element.add_attribute("size", (int) n); - for (unsigned i=0; i"); element.append_cdata(v.get(i)); element.append_cdata(""); @@ -31,8 +34,8 @@ void x_write_tree(std::ostream & os, vnl_vector_fixed const& v, std::string } #undef VNL_XIO_VECTOR_FIXED_INSTANTIATE -#define VNL_XIO_VECTOR_FIXED_INSTANTIATE(T,n) \ -template void x_write(std::ostream &, vnl_vector_fixed const&, std::string); \ -template void x_write_tree(std::ostream &, vnl_vector_fixed const&, std::string) +#define VNL_XIO_VECTOR_FIXED_INSTANTIATE(T, n) \ + template void x_write(std::ostream &, vnl_vector_fixed const &, std::string); \ + template void x_write_tree(std::ostream &, vnl_vector_fixed const &, std::string) #endif // vnl_xio_vector_fixed_hxx_ diff --git a/core/vxl_version.h b/core/vxl_version.h index 0f8f11a1fd8..edea5d77153 100644 --- a/core/vxl_version.h +++ b/core/vxl_version.h @@ -21,21 +21,17 @@ //: Version number as a string literal. // This is in the format "major.minor.patch". -#define VXL_VERSION_STRING \ - VXL_VERSION_TO_STRING(VXL_VERSION_MAJOR.VXL_VERSION_MINOR.VXL_VERSION_PATCH) +#define VXL_VERSION_STRING VXL_VERSION_TO_STRING(VXL_VERSION_MAJOR.VXL_VERSION_MINOR.VXL_VERSION_PATCH) //: Version date as a string literal. // This is in the format "CCYY-MM-DD". -#define VXL_VERSION_DATE \ - VXL_VERSION_TO_STRING(VXL_VERSION_DATE_YEAR-VXL_VERSION_DATE_MONTH-VXL_VERSION_DATE_DAY) +#define VXL_VERSION_DATE VXL_VERSION_TO_STRING(VXL_VERSION_DATE_YEAR - VXL_VERSION_DATE_MONTH - VXL_VERSION_DATE_DAY) //: Version date accessible from preprocessor. // This is an integer in the format CCYYMMDD. #define VXL_VERSION_DATE_FULL \ - VXL_VERSION_DATE_FULL0(VXL_VERSION_DATE_YEAR, \ - VXL_VERSION_DATE_MONTH, \ - VXL_VERSION_DATE_DAY) -#define VXL_VERSION_DATE_FULL0(y,m,d) VXL_VERSION_DATE_FULL1(y,m,d) -#define VXL_VERSION_DATE_FULL1(y,m,d) y##m##d + VXL_VERSION_DATE_FULL0(VXL_VERSION_DATE_YEAR, VXL_VERSION_DATE_MONTH, VXL_VERSION_DATE_DAY) +#define VXL_VERSION_DATE_FULL0(y, m, d) VXL_VERSION_DATE_FULL1(y, m, d) +#define VXL_VERSION_DATE_FULL1(y, m, d) y##m##d #endif // vxl_version_h_ diff --git a/v3p/netlib/linalg/lsmrBase.cxx b/v3p/netlib/linalg/lsmrBase.cxx index 70d524eecdf..174a16607ca 100644 --- a/v3p/netlib/linalg/lsmrBase.cxx +++ b/v3p/netlib/linalg/lsmrBase.cxx @@ -249,7 +249,7 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) // Initialize. - unsigned int localVecs = std::min( localSize, std::min( m,n ) ); + unsigned int const localVecs = std::min( localSize, std::min( m,n ) ); if( this->nout ) { @@ -261,7 +261,7 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) (*this->nout) << " localSize (no. of vectors for local reorthogonalization) = " << this->localSize << std::endl; } - int pfreq = 20; + int const pfreq = 20; int pcount = 0; this->damped = ( this->damp > zero ); @@ -405,11 +405,11 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) this->Scale( n, (- beta), v ); this->Aprod2( m, n, v, u ); // v = A'*u if ( localOrtho ) { - unsigned int localOrthoLimit = localVQueueFull ? localVecs : localPointer+1; + unsigned int const localOrthoLimit = localVQueueFull ? localVecs : localPointer+1; for( unsigned int localOrthoCount =0; localOrthoCountD2Norm( alphabar, damp ); - double chat = alphabar/alphahat; - double shat = damp/alphahat; + double const alphahat = this->D2Norm( alphabar, damp ); + double const chat = alphabar/alphahat; + double const shat = damp/alphahat; // Use a plane rotation (Q_i) to turn B_i to R_i. - double rhoold = rho; + double const rhoold = rho; rho = D2Norm(alphahat, beta); - double c = alphahat/rho; - double s = beta/rho; - double thetanew = s*alpha; + double const c = alphahat/rho; + double const s = beta/rho; + double const thetanew = s*alpha; alphabar = c*alpha; // Use a plane rotation (Qbar_i) to turn R_i^T into R_i^bar. - double rhobarold = rhobar; - double zetaold = zeta; - double thetabar = sbar*rho; - double rhotemp = cbar*rho; + double const rhobarold = rhobar; + double const zetaold = zeta; + double const thetabar = sbar*rho; + double const rhotemp = cbar*rho; rhobar = this->D2Norm(cbar*rho, thetanew); cbar = cbar*rho/rhobar; sbar = thetanew/rhobar; @@ -464,20 +464,20 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) // Estimate ||r||. // Apply rotation Qhat_{k,2k+1}. - double betaacute = chat* betadd; - double betacheck = - shat* betadd; + double const betaacute = chat* betadd; + double const betacheck = - shat* betadd; // Apply rotation Q_{k,k+1}. - double betahat = c*betaacute; + double const betahat = c*betaacute; betadd = - s*betaacute; // Apply rotation Qtilde_{k-1}. // betad = betad_{k-1} here. - double thetatildeold = thetatilde; - double rhotildeold = this->D2Norm(rhodold, thetabar); - double ctildeold = rhodold/rhotildeold; - double stildeold = thetabar/rhotildeold; + double const thetatildeold = thetatilde; + double const rhotildeold = this->D2Norm(rhodold, thetabar); + double const ctildeold = rhodold/rhotildeold; + double const stildeold = thetabar/rhotildeold; thetatilde = stildeold* rhobar; rhodold = ctildeold* rhobar; betad = - stildeold*betad + ctildeold*betahat; @@ -486,7 +486,7 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) // rhodold = rhod_k here. tautildeold = (zetaold - thetatildeold*tautildeold)/rhotildeold; - double taud = (zeta - thetatilde*tautildeold)/rhodold; + double const taud = (zeta - thetatilde*tautildeold)/rhodold; d = d + betacheck*betacheck; this->normr = sqrt(d + Sqr(betad - taud) + Sqr(betadd)); @@ -515,9 +515,9 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) test1 = this->normr / this->normb; test2 = this->normAr/(this->normA*this->normr); - double test3 = one/this->condA; - double t1 = test1/(one + this->normA*this->normx/this->normb); - double rtol = this->btol + this->atol*this->normA*normx/this->normb; + double const test3 = one/this->condA; + double const t1 = test1/(one + this->normA*this->normx/this->normb); + double const rtol = this->btol + this->atol*this->normA*normx/this->normb; // The following tests guard against extremely small values of // atol, btol or ctol. (The user may have set any or all of diff --git a/v3p/netlib/linalg/lsqrBase.cxx b/v3p/netlib/linalg/lsqrBase.cxx index 677235f0d70..e0092a744be 100644 --- a/v3p/netlib/linalg/lsqrBase.cxx +++ b/v3p/netlib/linalg/lsqrBase.cxx @@ -436,14 +436,14 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) // Use a plane rotation to eliminate the subdiagonal element (beta) // of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix. //---------------------------------------------------------------- - double rho = this->D2Norm( rhbar1, beta ); - double cs = rhbar1/rho; - double sn = beta /rho; - double theta = sn * alpha; + double const rho = this->D2Norm( rhbar1, beta ); + double const cs = rhbar1/rho; + double const sn = beta /rho; + double const theta = sn * alpha; rhobar = - cs * alpha; - double phi = cs * phibar; + double const phi = cs * phibar; phibar = sn * phibar; - double tau = sn * phi; + double const tau = sn * phi; //---------------------------------------------------------------- @@ -470,7 +470,7 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) { for ( unsigned int i = 0; i < n; i++ ) { - double t = w[i]; + double const t = w[i]; x[i] = t1 * t + x[i]; w[i] = t2 * t + v[i]; dknorm = ( t3 * t )*( t3 * t ) + dknorm; @@ -486,7 +486,7 @@ Solve( unsigned int m, unsigned int n, const double * b, double * x ) //---------------------------------------------------------------- dknorm = sqrt( dknorm ); dnorm = this->D2Norm( dnorm, dknorm ); - double dxk = fabs( phi* dknorm ); + double const dxk = fabs( phi* dknorm ); if ( this->dxmax < dxk) { this->dxmax = dxk; @@ -664,7 +664,7 @@ TerminationPrintOut() if ( this->nout ) { - std::string exitt = " Exit LSQR. "; + std::string const exitt = " Exit LSQR. "; (*this->nout) << exitt.c_str(); (*this->nout) << "istop = "; diff --git a/v3p/netlib/sparse/spFactor.c b/v3p/netlib/sparse/spFactor.c index 23f3af3d671..a5061c44d34 100644 --- a/v3p/netlib/sparse/spFactor.c +++ b/v3p/netlib/sparse/spFactor.c @@ -1541,7 +1541,7 @@ register ElementPtr pDiag; int I; ElementPtr ChosenPivot, pOtherInRow, pOtherInCol; RealNumber Magnitude, LargestInCol, LargestOffDiagonal; -RealNumber FindBiggestInColExclude(); +RealNumber FindBiggestInColExclude(MatrixPtr, ElementPtr, int); /* Begin `QuicklySearchDiagonal'. */ ChosenPivot = NULL; @@ -1708,7 +1708,7 @@ register ElementPtr pDiag; int NumberOfTies=0, Size = Matrix->Size; ElementPtr ChosenPivot=0; RealNumber Magnitude=0, Ratio=0, RatioOfAccepted =0, LargestInCol=0; -RealNumber FindBiggestInColExclude(); +RealNumber FindBiggestInColExclude(MatrixPtr, ElementPtr, int); /* Begin `SearchDiagonal'. */ ChosenPivot = NULL; @@ -1837,7 +1837,7 @@ long Product=0, MinMarkowitzProduct=0; ElementPtr ChosenPivot=0, pLargestElement=0; RealNumber Magnitude=0, LargestElementMag=0, Ratio=0, RatioOfAccepted=0, LargestInCol=0; -RealNumber FindLargestInCol(); +RealNumber FindLargestInCol(ElementPtr); /* Begin `SearchEntireMatrix'. */ ChosenPivot = NULL; diff --git a/v3p/netlib/sparse/spSolve.c b/v3p/netlib/sparse/spSolve.c index 1840534ffd6..5ee8738d08e 100644 --- a/v3p/netlib/sparse/spSolve.c +++ b/v3p/netlib/sparse/spSolve.c @@ -62,7 +62,7 @@ static void SolveComplexMatrix( MatrixPtr, RealVector, RealVector, RealVector, RealVector ); static void SolveComplexTransposedMatrix( MatrixPtr, RealVector, RealVector, RealVector, RealVector ); -#elseif spCOMPLEX +#elif spCOMPLEX static void SolveComplexMatrix( MatrixPtr, RealVector, RealVector ); static void SolveComplexTransposedMatrix( MatrixPtr, RealVector, RealVector ); @@ -73,7 +73,6 @@ static void SolveComplexTransposedMatrix( MatrixPtr, - /*! * Performs forward elimination and back substitution to find the * unknown vector from the \a RHS vector and factored matrix. This @@ -224,7 +223,6 @@ void SolveComplexMatrix(); - #if spCOMPLEX /*! * Performs forward elimination and back substitution to find the @@ -390,7 +388,6 @@ ComplexNumber Temp; - #if TRANSPOSE /*! * Performs forward elimination and back substitution to find the @@ -535,7 +532,6 @@ void SolveComplexTransposedMatrix(); - #if TRANSPOSE AND spCOMPLEX /*! * Performs forward elimination and back substitution to find the diff --git a/v3p/netlib/sparse/spUtils.c b/v3p/netlib/sparse/spUtils.c index 94036ba93c2..172805cd369 100644 --- a/v3p/netlib/sparse/spUtils.c +++ b/v3p/netlib/sparse/spUtils.c @@ -80,7 +80,7 @@ static void ComplexMatrixMultiply( MatrixPtr, RealVector, RealVector, RealVector, RealVector ); static void ComplexTransposedMatrixMultiply( MatrixPtr, RealVector, RealVector, RealVector, RealVector ); -#elseif spCOMPLEX +#elif spCOMPLEX static void ComplexMatrixMultiply( MatrixPtr, RealVector, RealVector ); static void ComplexTransposedMatrixMultiply( MatrixPtr, diff --git a/vcl/CMakeLists.txt b/vcl/CMakeLists.txt index 9ce9515be4e..54988d32fd8 100644 --- a/vcl/CMakeLists.txt +++ b/vcl/CMakeLists.txt @@ -93,7 +93,7 @@ set( vcl_sources internal/vcl_atomic_count_sync.h internal/vcl_atomic_count_win32.h internal/vcl_interlocked.h - + ) diff --git a/vcl/internal/vcl_atomic_count_gcc.h b/vcl/internal/vcl_atomic_count_gcc.h index dea6f06d4ec..163a4b66399 100644 --- a/vcl/internal/vcl_atomic_count_gcc.h +++ b/vcl/internal/vcl_atomic_count_gcc.h @@ -36,31 +36,31 @@ using __gnu_cxx::__exchange_and_add; class vcl_atomic_count { - public: +public: + explicit vcl_atomic_count(long v) + : value_(v) + {} - explicit vcl_atomic_count(long v) : value_(v) {} + void + operator++() + { + __atomic_add(&value_, 1); + } - void operator++() - { - __atomic_add(&value_, 1); - } + long + operator--() + { + return __exchange_and_add(&value_, -1) - 1; + } - long operator--() - { - return __exchange_and_add(&value_, -1) - 1; - } + operator long() const { return __exchange_and_add(&value_, 0); } - operator long() const - { - return __exchange_and_add(&value_, 0); - } +private: + vcl_atomic_count(const vcl_atomic_count &) = delete; + vcl_atomic_count & + operator=(const vcl_atomic_count &) = delete; - private: - - vcl_atomic_count(vcl_atomic_count const &); - vcl_atomic_count & operator=(vcl_atomic_count const &); - - mutable _Atomic_word value_; + mutable _Atomic_word value_; }; #endif // #ifndef vcl_atomic_count_gcc_h_ diff --git a/vcl/internal/vcl_atomic_count_gcc_x86.h b/vcl/internal/vcl_atomic_count_gcc_x86.h index 30423a27e3a..b90eaf11a5d 100644 --- a/vcl/internal/vcl_atomic_count_gcc_x86.h +++ b/vcl/internal/vcl_atomic_count_gcc_x86.h @@ -22,60 +22,59 @@ class vcl_atomic_count { - public: +public: + explicit vcl_atomic_count(long v) + : value_(static_cast(v)) + {} - explicit vcl_atomic_count( long v ) : value_( static_cast< int >( v ) ) {} - - void operator++() - { - __asm__ - ( - "lock\n\t" - "incl %0": - "+m"( value_ ): // output (%0) - : // inputs + void + operator++() + { + __asm__("lock\n\t" + "incl %0" + : "+m"(value_) + : // output (%0) + : // inputs "cc" // clobbers - ); - } - - long operator--() - { - return atomic_exchange_and_add( &value_, -1 ) - 1; - } - - operator long() const - { - return atomic_exchange_and_add( &value_, 0 ); - } + ); + } - private: + long + operator--() + { + return atomic_exchange_and_add(&value_, -1) - 1; + } - vcl_atomic_count(vcl_atomic_count const &) = delete; - vcl_atomic_count & operator=(vcl_atomic_count const &) = delete; + operator long() const { return atomic_exchange_and_add(&value_, 0); } - mutable int value_; +private: + vcl_atomic_count(const vcl_atomic_count &) = delete; + vcl_atomic_count & + operator=(const vcl_atomic_count &) = delete; - private: + mutable int value_; - static int atomic_exchange_and_add( int * pw, int dv ) - { - // int r = *pw; - // *pw += dv; - // return r; +private: + static int + atomic_exchange_and_add(int * pw, int dv) + { + // int r = *pw; + // *pw += dv; + // return r; - int r; + int r; - __asm__ __volatile__ - ( - "lock\n\t" - "xadd %1, %0": - "+m"( *pw ), "=r"( r ): // outputs (%0, %1) - "1"( dv ): // inputs (%2 == %1) - "memory", "cc" // clobbers - ); + __asm__ __volatile__("lock\n\t" + "xadd %1, %0" + : "+m"(*pw), "=r"(r) + : // outputs (%0, %1) + "1"(dv) + : // inputs (%2 == %1) + "memory", "cc" // clobbers + ); - return r; - } + return r; + } }; #endif // #ifndef vcl_atomic_count_gcc_x86_h_ diff --git a/vcl/internal/vcl_atomic_count_pthreads.h b/vcl/internal/vcl_atomic_count_pthreads.h index 6822a8968ae..76d0611d82f 100644 --- a/vcl/internal/vcl_atomic_count_pthreads.h +++ b/vcl/internal/vcl_atomic_count_pthreads.h @@ -30,64 +30,58 @@ class vcl_atomic_count { - private: - - class scoped_lock - { - public: - - scoped_lock(pthread_mutex_t & m): m_(m) - { - pthread_mutex_lock(&m_); - } - - ~scoped_lock() - { - pthread_mutex_unlock(&m_); - } - - private: - - pthread_mutex_t & m_; - }; - - public: - - explicit vcl_atomic_count(long v): value_(v) - { - pthread_mutex_init(&mutex_, 0); - } - - ~vcl_atomic_count() +private: + class scoped_lock + { + public: + scoped_lock(pthread_mutex_t & m) + : m_(m) { - pthread_mutex_destroy(&mutex_); + pthread_mutex_lock(&m_); } - void operator++() - { - scoped_lock lock(mutex_); - ++value_; - } - - long operator--() - { - scoped_lock lock(mutex_); - return --value_; - } - - operator long() const - { - scoped_lock lock(mutex_); - return value_; - } - - private: - - vcl_atomic_count(vcl_atomic_count const &); - vcl_atomic_count & operator=(vcl_atomic_count const &); - - mutable pthread_mutex_t mutex_; - long value_; + ~scoped_lock() { pthread_mutex_unlock(&m_); } + + private: + pthread_mutex_t & m_; + }; + +public: + explicit vcl_atomic_count(long v) + : value_(v) + { + pthread_mutex_init(&mutex_, 0); + } + + ~vcl_atomic_count() { pthread_mutex_destroy(&mutex_); } + + void + operator++() + { + scoped_lock lock(mutex_); + ++value_; + } + + long + operator--() + { + scoped_lock lock(mutex_); + return --value_; + } + + operator long() const + { + scoped_lock lock(mutex_); + return value_; + } + +private: + vcl_atomic_count(const vcl_atomic_count &) = delete; + vcl_atomic_count & + operator=(const vcl_atomic_count &) = delete; + + mutable pthread_mutex_t mutex_; + long value_; }; #endif // #ifndef vcl_atomic_count_pthreads_h_ diff --git a/vcl/internal/vcl_atomic_count_solaris.h b/vcl/internal/vcl_atomic_count_solaris.h index cd2462c0014..c975d00906f 100644 --- a/vcl/internal/vcl_atomic_count_solaris.h +++ b/vcl/internal/vcl_atomic_count_solaris.h @@ -24,33 +24,31 @@ class vcl_atomic_count { - public: - - explicit vcl_atomic_count( uint32_t v ): value_( v ) - { - } - - long operator++() - { - return atomic_inc_32_nv( &value_ ); - } - - long operator--() - { - return atomic_dec_32_nv( &value_ ); - } - - operator uint32_t() const - { - return static_cast( value_ ); - } - - private: - - vcl_atomic_count( vcl_atomic_count const & ); - vcl_atomic_count & operator=( vcl_atomic_count const & ); - - uint32_t value_; +public: + explicit vcl_atomic_count(uint32_t v) + : value_(v) + {} + + long + operator++() + { + return atomic_inc_32_nv(&value_); + } + + long + operator--() + { + return atomic_dec_32_nv(&value_); + } + + operator uint32_t() const { return static_cast(value_); } + +private: + vcl_atomic_count(const vcl_atomic_count &) = delete; + vcl_atomic_count & + operator=(const vcl_atomic_count &) = delete; + + uint32_t value_; }; #endif // #ifndef vcl_atomic_count_solaris_h_ diff --git a/vcl/internal/vcl_atomic_count_sync.h b/vcl/internal/vcl_atomic_count_sync.h index 5e4747a621b..1172dde7621 100644 --- a/vcl/internal/vcl_atomic_count_sync.h +++ b/vcl/internal/vcl_atomic_count_sync.h @@ -24,31 +24,31 @@ class vcl_atomic_count { - public: - - explicit vcl_atomic_count( long v ) : value_( v ) {} - - void operator++() - { - __sync_add_and_fetch( &value_, 1 ); - } - - long operator--() - { - return __sync_add_and_fetch( &value_, -1 ); - } - - operator long() const - { - return __sync_fetch_and_add( &value_, 0 ); - } - - private: - - vcl_atomic_count(vcl_atomic_count const &); - vcl_atomic_count & operator=(vcl_atomic_count const &); - - mutable long value_; +public: + explicit vcl_atomic_count(long v) + : value_(v) + {} + + void + operator++() + { + __sync_add_and_fetch(&value_, 1); + } + + long + operator--() + { + return __sync_add_and_fetch(&value_, -1); + } + + operator long() const { return __sync_fetch_and_add(&value_, 0); } + +private: + vcl_atomic_count(const vcl_atomic_count &) = delete; + vcl_atomic_count & + operator=(const vcl_atomic_count &) = delete; + + mutable long value_; }; #endif // #ifndef vcl_atomic_count_sync_h_ diff --git a/vcl/internal/vcl_atomic_count_win32.h b/vcl/internal/vcl_atomic_count_win32.h index 88860ff0e86..113f9a1a234 100644 --- a/vcl/internal/vcl_atomic_count_win32.h +++ b/vcl/internal/vcl_atomic_count_win32.h @@ -4,7 +4,7 @@ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) -# pragma once +# pragma once #endif //: // \file @@ -28,33 +28,31 @@ class vcl_atomic_count { - public: - - explicit vcl_atomic_count( long v ): value_( v ) - { - } - - long operator++() - { - return BOOST_INTERLOCKED_INCREMENT( &value_ ); - } - - long operator--() - { - return BOOST_INTERLOCKED_DECREMENT( &value_ ); - } - - operator long() const - { - return static_cast( value_ ); - } - - private: - - vcl_atomic_count( vcl_atomic_count const & ); - vcl_atomic_count & operator=( vcl_atomic_count const & ); - - long value_; +public: + explicit vcl_atomic_count(long v) + : value_(v) + {} + + long + operator++() + { + return BOOST_INTERLOCKED_INCREMENT(&value_); + } + + long + operator--() + { + return BOOST_INTERLOCKED_DECREMENT(&value_); + } + + operator long() const { return static_cast(value_); } + +private: + vcl_atomic_count(const vcl_atomic_count &) = delete; + vcl_atomic_count & + operator=(const vcl_atomic_count &) = delete; + + long value_; }; #endif // #ifndef vcl_atomic_count_win32_h_ diff --git a/vcl/internal/vcl_interlocked.h b/vcl/internal/vcl_interlocked.h index 417a6e2b43a..fad595da7d2 100644 --- a/vcl/internal/vcl_interlocked.h +++ b/vcl/internal/vcl_interlocked.h @@ -4,7 +4,7 @@ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) -# pragma once +# pragma once #endif //: // \file @@ -22,91 +22,91 @@ // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) - // +// #if defined(_WIN32_WCE) // under Windows CE we still have old-style Interlocked* functions - extern "C" long __cdecl InterlockedIncrement( long* ); - extern "C" long __cdecl InterlockedDecrement( long* ); - extern "C" long __cdecl InterlockedCompareExchange( long*, long, long ); - extern "C" long __cdecl InterlockedExchange( long*, long ); - extern "C" long __cdecl InterlockedExchangeAdd( long*, long ); +extern "C" long __cdecl InterlockedIncrement(long *); +extern "C" long __cdecl InterlockedDecrement(long *); +extern "C" long __cdecl InterlockedCompareExchange(long *, long, long); +extern "C" long __cdecl InterlockedExchange(long *, long); +extern "C" long __cdecl InterlockedExchangeAdd(long *, long); -# define BOOST_INTERLOCKED_INCREMENT InterlockedIncrement -# define BOOST_INTERLOCKED_DECREMENT InterlockedDecrement -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE InterlockedCompareExchange -# define BOOST_INTERLOCKED_EXCHANGE InterlockedExchange -# define BOOST_INTERLOCKED_EXCHANGE_ADD InterlockedExchangeAdd +# define BOOST_INTERLOCKED_INCREMENT InterlockedIncrement +# define BOOST_INTERLOCKED_DECREMENT InterlockedDecrement +# define BOOST_INTERLOCKED_COMPARE_EXCHANGE InterlockedCompareExchange +# define BOOST_INTERLOCKED_EXCHANGE InterlockedExchange +# define BOOST_INTERLOCKED_EXCHANGE_ADD InterlockedExchangeAdd -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \ - ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long*)(dest),(long)(exchange),(long)(compare))) -# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \ - ((void*)BOOST_INTERLOCKED_EXCHANGE((long*)(dest),(long)(exchange))) +# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) \ + ((void *)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long *)(dest), (long)(exchange), (long)(compare))) +# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest, exchange) \ + ((void *)BOOST_INTERLOCKED_EXCHANGE((long *)(dest), (long)(exchange))) -#elif defined( _MSC_VER ) || defined( __ICC ) +#elif defined(_MSC_VER) || defined(__ICC) - extern "C" long __cdecl _InterlockedIncrement( long volatile * ); - extern "C" long __cdecl _InterlockedDecrement( long volatile * ); - extern "C" long __cdecl _InterlockedCompareExchange( long volatile *, long, long ); - extern "C" long __cdecl _InterlockedExchange( long volatile *, long); - extern "C" long __cdecl _InterlockedExchangeAdd( long volatile *, long); +extern "C" long __cdecl _InterlockedIncrement(long volatile *); +extern "C" long __cdecl _InterlockedDecrement(long volatile *); +extern "C" long __cdecl _InterlockedCompareExchange(long volatile *, long, long); +extern "C" long __cdecl _InterlockedExchange(long volatile *, long); +extern "C" long __cdecl _InterlockedExchangeAdd(long volatile *, long); -# pragma intrinsic( _InterlockedIncrement ) -# pragma intrinsic( _InterlockedDecrement ) -# pragma intrinsic( _InterlockedCompareExchange ) -# pragma intrinsic( _InterlockedExchange ) -# pragma intrinsic( _InterlockedExchangeAdd ) +# pragma intrinsic(_InterlockedIncrement) +# pragma intrinsic(_InterlockedDecrement) +# pragma intrinsic(_InterlockedCompareExchange) +# pragma intrinsic(_InterlockedExchange) +# pragma intrinsic(_InterlockedExchangeAdd) -# if defined(_M_IA64) || defined(_M_AMD64) +# if defined(_M_IA64) || defined(_M_AMD64) - extern "C" void* __cdecl _InterlockedCompareExchangePointer( void* volatile *, void*, void* ); - extern "C" void* __cdecl _InterlockedExchangePointer( void* volatile *, void* ); +extern "C" void * __cdecl _InterlockedCompareExchangePointer(void * volatile *, void *, void *); +extern "C" void * __cdecl _InterlockedExchangePointer(void * volatile *, void *); -# pragma intrinsic( _InterlockedCompareExchangePointer ) -# pragma intrinsic( _InterlockedExchangePointer ) +# pragma intrinsic(_InterlockedCompareExchangePointer) +# pragma intrinsic(_InterlockedExchangePointer) -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER _InterlockedCompareExchangePointer -# define BOOST_INTERLOCKED_EXCHANGE_POINTER _InterlockedExchangePointer +# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER _InterlockedCompareExchangePointer +# define BOOST_INTERLOCKED_EXCHANGE_POINTER _InterlockedExchangePointer -# else +# else -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \ - ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare))) -# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \ - ((void*)BOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange))) +# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) \ + ((void *)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile *)(dest), (long)(exchange), (long)(compare))) +# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest, exchange) \ + ((void *)BOOST_INTERLOCKED_EXCHANGE((long volatile *)(dest), (long)(exchange))) -# endif +# endif -# define BOOST_INTERLOCKED_INCREMENT _InterlockedIncrement -# define BOOST_INTERLOCKED_DECREMENT _InterlockedDecrement -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange -# define BOOST_INTERLOCKED_EXCHANGE _InterlockedExchange -# define BOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd +# define BOOST_INTERLOCKED_INCREMENT _InterlockedIncrement +# define BOOST_INTERLOCKED_DECREMENT _InterlockedDecrement +# define BOOST_INTERLOCKED_COMPARE_EXCHANGE _InterlockedCompareExchange +# define BOOST_INTERLOCKED_EXCHANGE _InterlockedExchange +# define BOOST_INTERLOCKED_EXCHANGE_ADD _InterlockedExchangeAdd -#elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined( __CYGWIN__ ) +#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) - extern "C" __declspec(dllimport) long __stdcall InterlockedIncrement( long volatile * ); - extern "C" __declspec(dllimport) long __stdcall InterlockedDecrement( long volatile * ); - extern "C" __declspec(dllimport) long __stdcall InterlockedCompareExchange( long volatile *, long, long ); - extern "C" __declspec(dllimport) long __stdcall InterlockedExchange( long volatile *, long ); - extern "C" __declspec(dllimport) long __stdcall InterlockedExchangeAdd( long volatile *, long ); +extern "C" __declspec(dllimport) long __stdcall InterlockedIncrement(long volatile *); +extern "C" __declspec(dllimport) long __stdcall InterlockedDecrement(long volatile *); +extern "C" __declspec(dllimport) long __stdcall InterlockedCompareExchange(long volatile *, long, long); +extern "C" __declspec(dllimport) long __stdcall InterlockedExchange(long volatile *, long); +extern "C" __declspec(dllimport) long __stdcall InterlockedExchangeAdd(long volatile *, long); -# define BOOST_INTERLOCKED_INCREMENT InterlockedIncrement -# define BOOST_INTERLOCKED_DECREMENT InterlockedDecrement -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE InterlockedCompareExchange -# define BOOST_INTERLOCKED_EXCHANGE InterlockedExchange -# define BOOST_INTERLOCKED_EXCHANGE_ADD InterlockedExchangeAdd +# define BOOST_INTERLOCKED_INCREMENT InterlockedIncrement +# define BOOST_INTERLOCKED_DECREMENT InterlockedDecrement +# define BOOST_INTERLOCKED_COMPARE_EXCHANGE InterlockedCompareExchange +# define BOOST_INTERLOCKED_EXCHANGE InterlockedExchange +# define BOOST_INTERLOCKED_EXCHANGE_ADD InterlockedExchangeAdd -# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest,exchange,compare) \ - ((void*)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile*)(dest),(long)(exchange),(long)(compare))) -# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest,exchange) \ - ((void*)BOOST_INTERLOCKED_EXCHANGE((long volatile*)(dest),(long)(exchange))) +# define BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(dest, exchange, compare) \ + ((void *)BOOST_INTERLOCKED_COMPARE_EXCHANGE((long volatile *)(dest), (long)(exchange), (long)(compare))) +# define BOOST_INTERLOCKED_EXCHANGE_POINTER(dest, exchange) \ + ((void *)BOOST_INTERLOCKED_EXCHANGE((long volatile *)(dest), (long)(exchange))) #else -# error "Interlocked intrinsics not available" +# error "Interlocked intrinsics not available" #endif diff --git a/vcl/tests/test_algorithm.cxx b/vcl/tests/test_algorithm.cxx index 06efaa069c6..53f39eac89b 100644 --- a/vcl/tests/test_algorithm.cxx +++ b/vcl/tests/test_algorithm.cxx @@ -7,10 +7,11 @@ # include "vcl_msvc_warnings.h" #endif -int test_algorithm_main(int /*argc*/,char* /*argv*/[]) +int +test_algorithm_main(int /*argc*/, char * /*argv*/[]) { - double v[5] = {1.,5.,2.,4.,3.}; - std::sort(v, v+5); + double v[5] = { 1., 5., 2., 4., 3. }; + std::sort(v, v + 5); return 0; } diff --git a/vcl/tests/test_atomic_count.cxx b/vcl/tests/test_atomic_count.cxx index 419daecb0b4..a9989ae368e 100644 --- a/vcl/tests/test_atomic_count.cxx +++ b/vcl/tests/test_atomic_count.cxx @@ -5,9 +5,21 @@ # include "vcl_msvc_warnings.h" #endif -#define TEST(str,x,y) std::printf(str ": "); if ((x)!=(y)) { std::printf("FAILED\n"); status = 1; } else { std::printf("PASSED\n"); } static_assert(true, "") +#define TEST(str, x, y) \ + std::printf(str ": "); \ + if ((x) != (y)) \ + { \ + std::printf("FAILED\n"); \ + status = 1; \ + } \ + else \ + { \ + std::printf("PASSED\n"); \ + } \ + static_assert(true, "") -int test_atomic_count_main(int /*argc*/,char* /*argv*/[]) +int +test_atomic_count_main(int /*argc*/, char * /*argv*/[]) { int status = 0; @@ -22,20 +34,23 @@ int test_atomic_count_main(int /*argc*/,char* /*argv*/[]) ++c; // now c==2 TEST("Increment is correct", c, 2); - for (int i=0; i<5;++i) ++c; + for (int i = 0; i < 5; ++i) + ++c; // now c==7 TEST("Increment in a loop is correct", c, 7); --c; // now c==6 TEST("Decrement is correct", c, 6); - --c; --c; // now c==4 + --c; + --c; // now c==4 TEST("Decrement is correct", c, 4); ++c; // now c==5 TEST("Increment is correct", c, 5); - for (int i=0; i<4;++i) --c; + for (int i = 0; i < 4; ++i) + --c; // now c==1 TEST("Decrement in a loop is correct", c, 1); @@ -47,7 +62,11 @@ int test_atomic_count_main(int /*argc*/,char* /*argv*/[]) // vcl_atomic_count d(1); - ++c; ++d; ++d; --c; ++d; // now c==0 and d==4 - TEST("Multiple instances act independently", (d==4&&c==0), true); + ++c; + ++d; + ++d; + --c; + ++d; // now c==0 and d==4 + TEST("Multiple instances act independently", (d == 4 && c == 0), true); return status; } diff --git a/vcl/tests/test_cctype.cxx b/vcl/tests/test_cctype.cxx index b237e9373dc..921f8bdbd1c 100644 --- a/vcl/tests/test_cctype.cxx +++ b/vcl/tests/test_cctype.cxx @@ -7,19 +7,16 @@ // Test the functionality, and also cause a link to make sure the // function exists. -int test_cctype_main(int /*argc*/,char* /*argv*/[]) +int +test_cctype_main(int /*argc*/, char * /*argv*/[]) { - return ! ( std::isspace(' ') && std::isspace('\n') && !std::isspace('a') && - std::isalnum('1') && std::isalnum('z') && !std::isalnum('@') && - std::isdigit('4') && !std::isdigit('k') && !std::isdigit('%') && - std::isprint(' ') && std::isprint('(') && !std::isprint('\n') && - std::isupper('A') && !std::isupper('a') && !std::isupper('1') && - std::islower('b') && !std::islower('G') && !std::islower('8') && - std::isalpha('A') && std::isalpha('a') && !std::isalpha('1') && - std::isgraph('%') && std::isgraph('j') && !std::isgraph(' ') && - std::ispunct('&') && !std::ispunct('a') && !std::ispunct(' ') && - std::isxdigit('8') && std::isxdigit('F') && std::isxdigit('f') && !std::isxdigit('g') && - std::iscntrl('\n') && std::iscntrl('\177') && !std::iscntrl('i') && - std::tolower('A')=='a' && std::tolower('a')=='a' && std::tolower('@')=='@' && - std::toupper('K')=='K' && std::toupper('j')=='J' && std::toupper('$')=='$' ); + return !(std::isspace(' ') && std::isspace('\n') && !std::isspace('a') && std::isalnum('1') && std::isalnum('z') && + !std::isalnum('@') && std::isdigit('4') && !std::isdigit('k') && !std::isdigit('%') && std::isprint(' ') && + std::isprint('(') && !std::isprint('\n') && std::isupper('A') && !std::isupper('a') && !std::isupper('1') && + std::islower('b') && !std::islower('G') && !std::islower('8') && std::isalpha('A') && std::isalpha('a') && + !std::isalpha('1') && std::isgraph('%') && std::isgraph('j') && !std::isgraph(' ') && std::ispunct('&') && + !std::ispunct('a') && !std::ispunct(' ') && std::isxdigit('8') && std::isxdigit('F') && std::isxdigit('f') && + !std::isxdigit('g') && std::iscntrl('\n') && std::iscntrl('\177') && !std::iscntrl('i') && + std::tolower('A') == 'a' && std::tolower('a') == 'a' && std::tolower('@') == '@' && + std::toupper('K') == 'K' && std::toupper('j') == 'J' && std::toupper('$') == '$'); } diff --git a/vcl/tests/test_cmath.cxx b/vcl/tests/test_cmath.cxx index 9a73b458f0e..c8a7a232680 100644 --- a/vcl/tests/test_cmath.cxx +++ b/vcl/tests/test_cmath.cxx @@ -13,25 +13,27 @@ #endif -int test_cmath_main(int /*argc*/,char* /*argv*/[]) +int +test_cmath_main(int /*argc*/, char * /*argv*/[]) { { - int xi = 314159265; - long xl = 314159265L; - float xf = 13.14159265358979323846f; - double xd = 23.14159265358979323846; + const int xi = 314159265; + const long xl = 314159265L; + const float xf = 13.14159265358979323846f; + const double xd = 23.14159265358979323846; #ifdef INCLUDE_LONG_DOUBLE_TESTS long double ld = xd; #endif - std::complex xc(xd,0.0); + std::complex const xc(xd, 0.0); -#define macro(var, type) \ -do { \ - if (std::abs(var) == (var) && std::abs(- (var)) == (var)) \ - std::cout << "std::abs(" #type ") PASSED" << std::endl; \ - else \ - std::cerr << "std::abs(" #type ") *** FAILED *** " << std::endl; \ -} while (false) +#define macro(var, type) \ + do \ + { \ + if (std::abs(var) == (var) && std::abs(-(var)) == (var)) \ + std::cout << "std::abs(" #type ") PASSED" << std::endl; \ + else \ + std::cerr << "std::abs(" #type ") *** FAILED *** " << std::endl; \ + } while (false) macro(xi, int); macro(xl, long); macro(xf, float); @@ -50,23 +52,27 @@ do { \ // #define std::cos ::cos // or // #define std::cos std::cos - double theta = 0.1234; - double cos = std::cos(theta); - double sin = std::sin(theta); - double tan = std::tan(theta); - (void)theta; (void)cos; (void)sin; (void)tan; // quell 'unused variable' warning. + const double theta = 0.1234; + const double cos = std::cos(theta); + const double sin = std::sin(theta); + const double tan = std::tan(theta); + (void)theta; + (void)cos; + (void)sin; + (void)tan; // quell 'unused variable' warning. } -#define macro(T, eps) \ - do { \ - T x = 2; \ - T y = std::sqrt(x); \ - if (std::abs(x - y*y) < (eps)) \ - std::cout << "std::sqrt(" #T ") PASSED" << std::endl; \ - else \ +#define macro(T, eps) \ + do \ + { \ + T x = 2; \ + T y = std::sqrt(x); \ + if (std::abs(x - y * y) < (eps)) \ + std::cout << "std::sqrt(" #T ") PASSED" << std::endl; \ + else \ std::cout << "std::sqrt(" #T ") *** FAILED *** " << std::endl; \ } while (false) - macro(float, 1e-6); // actually sqrtf() + macro(float, 1e-6); // actually sqrtf() macro(double, 1e-14); #ifdef INCLUDE_LONG_DOUBLE_TESTS macro(long double, 1e-14); // actually sqrtl() diff --git a/vcl/tests/test_compiler.cxx b/vcl/tests/test_compiler.cxx index 525ce0ddcdf..e75e1a49bd8 100644 --- a/vcl/tests/test_compiler.cxx +++ b/vcl/tests/test_compiler.cxx @@ -11,17 +11,18 @@ template struct X { - int x{1728}; + int x{ 1728 }; X(); // declaration of static template member. - static X *pl; + static X * pl; }; -template X::X() = default; +template +X::X() = default; // definition (not specialization) of static template member. template -X *X::pl = nullptr; +X * X::pl = nullptr; // explicit instantiation of class also instantiates statics. template struct X; @@ -30,28 +31,40 @@ template struct X; struct A { - int x{0}; - mutable int y{0}; + int x{ 0 }; + mutable int y{ 0 }; A() = default; - void f() { ++ x; } - void g() const { ++ y; } + void + f() + { + ++x; + } + void + g() const + { + ++y; + } }; // ------------------------------------------------ -void vcl_test_implicit_instantiation(int n); +void +vcl_test_implicit_instantiation(int n); -int test_compiler_main(int /*argc*/,char* /*argv*/[]) +int +test_compiler_main(int /*argc*/, char * /*argv*/[]) { int result = 0; std::cout << "Testing static template member..." << std::flush; - if ( X::pl == nullptr ) { + if (X::pl == nullptr) + { std::cout << " PASSED" << std::endl; } - else { + else + { std::cout << "**FAILED**" << std::endl; result = 1; } @@ -68,47 +81,61 @@ struct mystery_type { mystery_type(); mystery_type(int, float); - mystery_type(mystery_type const &); - mystery_type &operator=(mystery_type const &); + mystery_type(const mystery_type &); + mystery_type & + operator=(const mystery_type &); int a; float b; }; -bool operator==(mystery_type const &, mystery_type const &); -bool operator< (mystery_type const &, mystery_type const &); +bool +operator==(const mystery_type &, const mystery_type &); +bool +operator<(const mystery_type &, const mystery_type &); -void vcl_test_implicit_instantiation(int n) +void +vcl_test_implicit_instantiation(int n) { std::vector v; v.resize(n); - for (int i=0; i > map_t; + typedef std::map> map_t; map_t m; - for (int i=0; i doublify(std::complex const &z) +std::complex +doublify(const std::complex & z) { - return {std::real(z), std::imag(z)}; + return { std::real(z), std::imag(z) }; } -int test_complex_main(int /*argc*/,char* /*argv*/[]) +int +test_complex_main(int /*argc*/, char * /*argv*/[]) { - std::complex dc1(1.1,1.2), dc2(2.1,2.2); - std::complex fc1(1.1f,1.2f), fc2(2.1f,2.2f); + const std::complex dc1(1.1, 1.2); + const std::complex dc2(2.1, 2.2); + const std::complex fc1(1.1f, 1.2f); + const std::complex fc2(2.1f, 2.2f); - std::cout << dc1 << " + " << dc2 << " = " << (dc1+dc2) << std::endl - << fc1 << " + " << fc2 << " = " << (fc1+fc2) << std::endl; + std::cout << dc1 << " + " << dc2 << " = " << (dc1 + dc2) << std::endl + << fc1 << " + " << fc2 << " = " << (fc1 + fc2) << std::endl; - std::complex dc3(std::real(dc1),std::imag(dc2)); - std::complex fc3(std::real(fc1),std::imag(fc2)); + const std::complex dc3(std::real(dc1), std::imag(dc2)); + const std::complex fc3(std::real(fc1), std::imag(fc2)); - std::cout << dc3 << " / " << dc1 << " = " << dc3/dc1 << std::endl - << fc3 << " / " << fc1 << " = " << fc3/fc1 << std::endl; + std::cout << dc3 << " / " << dc1 << " = " << dc3 / dc1 << std::endl + << fc3 << " / " << fc1 << " = " << fc3 / fc1 << std::endl; std::cout << "polar representation of " << dc3 << " is [" << std::abs(dc3) << ',' << std::arg(dc3) << "]\n" - << "going back: " << dc3 << " must be = " << std::polar(std::abs(dc3), std::arg(dc3)) << std::endl; - std::complex fcsr3 = std::sqrt(fc3); - std::cout << "sqrt(" << fc3 << ") is " << fcsr3 << ", so " << fcsr3 << " * " << fcsr3 << " = " << fcsr3*fcsr3 << std::endl; + << "going back: " << dc3 << " must be = " << std::polar(std::abs(dc3), std::arg(dc3)) << std::endl; + const std::complex fcsr3 = std::sqrt(fc3); + std::cout << "sqrt(" << fc3 << ") is " << fcsr3 << ", so " << fcsr3 << " * " << fcsr3 << " = " << fcsr3 * fcsr3 + << std::endl; // Should also test form of complex stream input and output. The standard says: // [26.2.6.12] operator>> understands "u", "(u)" and "(u,v)" where u, v are real. @@ -41,7 +46,7 @@ int test_complex_main(int /*argc*/,char* /*argv*/[]) // operator>>. // complex should have a type called value_type; - std::complex::value_type tmp = 1.0f; + const std::complex::value_type tmp = 1.0f; (void)tmp; // to avoid unused variable warnings. @@ -50,41 +55,39 @@ int test_complex_main(int /*argc*/,char* /*argv*/[]) bool success = true; const std::complex neg1(-1.0, 0.0); - const std::complex i(0.0,1.0); + const std::complex i(0.0, 1.0); std::complex sqrt_neg1 = std::pow(neg1, 0.5); - std::cout << "pow("< half(0.5,0.0); + const std::complex half(0.5, 0.0); sqrt_neg1 = std::pow(neg1, half); - std::cout << "pow("< zero(0.0,0.0); - std::cout << "Implementation defines std::pow((0,0),(0,0)) = " - << std::pow(zero, zero) << std::endl; + const std::complex zero(0.0, 0.0); + std::cout << "Implementation defines std::pow((0,0),(0,0)) = " << std::pow(zero, zero) << std::endl; { - std::complex x(2, 3); - std::complex xc = std::conj(x); + const std::complex x(2, 3); + const std::complex xc = std::conj(x); std::cout << "Conjugate " << x << " = " << xc << '\n'; - if ( xc != std::complex(2,-3) ) { + if (xc != std::complex(2, -3)) + { success = false; } } - return success?0:1; + return success ? 0 : 1; } diff --git a/vcl/tests/test_cstdio.cxx b/vcl/tests/test_cstdio.cxx index 864ddbccff4..94a9c787f86 100644 --- a/vcl/tests/test_cstdio.cxx +++ b/vcl/tests/test_cstdio.cxx @@ -3,45 +3,62 @@ # include "vcl_msvc_warnings.h" #endif -#define ASSERT(x,y) if (!(x)) { std::printf("FAIL: " y "\n"); fail=true; } static_assert(true, "") -#define ASSERT1(x,y,a) if (!(x)) { std::printf("FAIL: " y "\n",a); fail=true; } static_assert(true, "") -#define ASSERT2(x,y,a,b) if (!(x)){std::printf("FAIL: " y "\n",a,b);fail=true;} static_assert(true, "") +#define ASSERT(x, y) \ + if (!(x)) \ + { \ + std::printf("FAIL: " y "\n"); \ + fail = true; \ + } \ + static_assert(true, "") +#define ASSERT1(x, y, a) \ + if (!(x)) \ + { \ + std::printf("FAIL: " y "\n", a); \ + fail = true; \ + } \ + static_assert(true, "") +#define ASSERT2(x, y, a, b) \ + if (!(x)) \ + { \ + std::printf("FAIL: " y "\n", a, b); \ + fail = true; \ + } \ + static_assert(true, "") -int test_cstdio_main(int argc,char* argv[]) +int +test_cstdio_main(int argc, char * argv[]) { - std::printf( "Hello. %d %f %03x.\n", 1, 2.0f, 3 ); + std::printf("Hello. %d %f %03x.\n", 1, 2.0f, 3); bool fail = false; // global status of the test suite - int rc; // return code - // Close the standard input. All reads from // stdin should fail after this. - rc = std::fclose(stdin); - ASSERT(rc==0, "couldn't close standard input"); + int rc = std::fclose(stdin); + ASSERT(rc == 0, "couldn't close standard input"); rc = std::getchar(); - ASSERT(rc==EOF, "std::getchar() read a value from a closed stream"); + ASSERT(rc == EOF, "std::getchar() read a value from a closed stream"); - ASSERT(argc>=2, "no file name given as the first command line argument"); - std::FILE* fh = std::fopen( argv[1], "r" ); + ASSERT(argc >= 2, "no file name given as the first command line argument"); + std::FILE * fh = std::fopen(argv[1], "r"); ASSERT1(fh, "couldn't open %s\n (skipping file tests)", argv[1]); if (fh) { - rc = std::getc( fh ); - ASSERT(rc=='t', "first character read was not 't'"); + rc = std::getc(fh); + ASSERT(rc == 't', "first character read was not 't'"); - rc = std::ungetc( 'x', fh ); - ASSERT(rc=='x', "ungetc failed"); - if( rc == 'x') + rc = std::ungetc('x', fh); + ASSERT(rc == 'x', "ungetc failed"); + if (rc == 'x') { - rc = std::getc( fh ); - ASSERT2(rc=='x', "getc returned %d, and not %d ('x') as expected",rc,'x'); + rc = std::getc(fh); + ASSERT2(rc == 'x', "getc returned %d, and not %d ('x') as expected", rc, 'x'); } - rc = std::fclose( fh ); - ASSERT(rc==0, "failed to close file"); + rc = std::fclose(fh); + ASSERT(rc == 0, "failed to close file"); } return fail ? 1 : 0; } diff --git a/vcl/tests/test_deque.cxx b/vcl/tests/test_deque.cxx index 735013d8abf..102a6dd5776 100644 --- a/vcl/tests/test_deque.cxx +++ b/vcl/tests/test_deque.cxx @@ -4,7 +4,8 @@ # include "vcl_msvc_warnings.h" #endif -int test_deque_main(int /*argc*/,char* /*argv*/[]) +int +test_deque_main(int /*argc*/, char * /*argv*/[]) { using mydeque = std::deque; mydeque dq; @@ -13,7 +14,7 @@ int test_deque_main(int /*argc*/,char* /*argv*/[]) dq.push_back(3); dq.push_front(1); - for (int & p : dq) + for (const int & p : dq) std::cout << p << std::endl; return 0; diff --git a/vcl/tests/test_driver.cxx b/vcl/tests/test_driver.cxx index 579efdeae0c..4b807b2b3ed 100644 --- a/vcl/tests/test_driver.cxx +++ b/vcl/tests/test_driver.cxx @@ -11,67 +11,101 @@ # include "vcl_msvc_warnings.h" #endif -int test_algorithm_main(int, char*[]); -int test_cctype_main(int, char*[]); -int test_cmath_main(int, char*[]); -int test_compiler_main(int, char*[]); -int test_complex_main(int, char*[]); -int test_deque_main(int, char*[]); -int test_exception_main(int, char*[]); -int test_fstream_main(int, char*[]); -int test_headers_main(int, char**); // need not be called: just a compiler test -int test_iostream_main(int, char*[]); -int test_iterator_main(int, char*[]); -int test_list_main(int, char*[]); -int test_limits_main(int, char*[]); -int test_map_main(int, char*[]); -int test_memory_main(int, char*[]); -int test_multimap_main(int, char*[]); -int test_new_main(int, char*[]); -int test_set_main(int, char*[]); -int test_stlfwd_main(int, char*[]); // need not be called: just a compiler test -int test_string_main(int, char*[]); -int test_sstream_main(int, char*[]); -int test_vector_main(int, char*[]); -int test_cstdio_main(int, char*[]); -int test_preprocessor_main(int, char*[]); -int test_atomic_count_main(int, char*[]); -int test_typename_main(int, char*[]); // need not be called: just a compiler test +int +test_algorithm_main(int, char *[]); +int +test_cctype_main(int, char *[]); +int +test_cmath_main(int, char *[]); +int +test_compiler_main(int, char *[]); +int +test_complex_main(int, char *[]); +int +test_deque_main(int, char *[]); +int +test_exception_main(int, char *[]); +int +test_fstream_main(int, char *[]); +int +test_headers_main(int, char **); // need not be called: just a compiler test +int +test_iostream_main(int, char *[]); +int +test_iterator_main(int, char *[]); +int +test_list_main(int, char *[]); +int +test_limits_main(int, char *[]); +int +test_map_main(int, char *[]); +int +test_memory_main(int, char *[]); +int +test_multimap_main(int, char *[]); +int +test_new_main(int, char *[]); +int +test_set_main(int, char *[]); +int +test_stlfwd_main(int, char *[]); // need not be called: just a compiler test +int +test_string_main(int, char *[]); +int +test_sstream_main(int, char *[]); +int +test_vector_main(int, char *[]); +int +test_cstdio_main(int, char *[]); +int +test_preprocessor_main(int, char *[]); +int +test_atomic_count_main(int, char *[]); +int +test_typename_main(int, char *[]); // need not be called: just a compiler test int passed; int failed; -void testname( const char* testname ) +void +testname(const char * testname) { std::cout << " Testing vcl_" << testname << " ... "; std::cout.flush(); } -void testresult( int testresult ) +void +testresult(int testresult) { - if ( testresult==0 ) { + if (testresult == 0) + { ++passed; std::cout << " PASSED" << std::endl; - } else { + } + else + { ++failed; std::cout << " **FAILED**" << std::endl; } } -#define DO_TEST( Name ) \ - if ( name == "" || name == "test_" #Name ) { \ - testname( #Name ); \ - testresult( test_##Name##_main(argc,argv) ); \ - test_run = 1; \ +#define DO_TEST(Name) \ + if (name == "" || name == "test_" #Name) \ + { \ + testname(#Name); \ + testresult(test_##Name##_main(argc, argv)); \ + test_run = 1; \ } -int main( int argc, char* argv[] ) +int +main(int argc, char * argv[]) { int test_run = 0; passed = failed = 0; std::string name = ""; - if ( argc > 1 ) { + if (argc > 1) + { name = argv[1]; ++argv; --argc; @@ -102,18 +136,17 @@ int main( int argc, char* argv[] ) if (test_run == 0) { - std::cout << "Unsupported test " << name - << "; should first be added to test_driver.cxx\n"; + std::cout << "Unsupported test " << name << "; should first be added to test_driver.cxx\n"; failed = true; } std::cout << name << " Test Summary: "; if (failed > 0) - std::cout< 1) - std::cout<<"All "< #include -int test_exception_main(int /*argc*/,char* /*argv*/[]) +int +test_exception_main(int /*argc*/, char * /*argv*/[]) { - const char *ex = "\"const char* exception\""; + const char * ex = "\"const char* exception\""; int result; - try { + try + { std::cout << "throw " << ex << std::endl; throw ex; } - catch (const char* e) { + catch (const char * e) + { std::cout << "caught " << e << ". Good." << std::endl; result = 0; } - catch(...) { + catch (...) + { std::cout << "caught nothing. Bad." << std::endl; result = 1; } diff --git a/vcl/tests/test_fstream.cxx b/vcl/tests/test_fstream.cxx index fdba75d038f..cd3c6663951 100644 --- a/vcl/tests/test_fstream.cxx +++ b/vcl/tests/test_fstream.cxx @@ -4,9 +4,11 @@ # include "vcl_msvc_warnings.h" #endif -int test_fstream_main(int /*argc*/,char* /*argv*/[]) +int +test_fstream_main(int /*argc*/, char * /*argv*/[]) { - if (false) { + if (false) + { std::fstream f("dont_worry_this_file_is_not_created", std::ios::out | std::ios::binary); f.write("hello, file", 11); diff --git a/vcl/tests/test_include.cxx b/vcl/tests/test_include.cxx index c6dd2a39f2b..b44367e506a 100644 --- a/vcl/tests/test_include.cxx +++ b/vcl/tests/test_include.cxx @@ -54,4 +54,8 @@ #include // #include // This causes compile warnings -int main() { return 0; } +int +main() +{ + return 0; +} diff --git a/vcl/tests/test_iostream.cxx b/vcl/tests/test_iostream.cxx index 1d7233165ee..c1152c2a565 100644 --- a/vcl/tests/test_iostream.cxx +++ b/vcl/tests/test_iostream.cxx @@ -17,31 +17,32 @@ struct flux : public std::fstream { // check that bitwise OR of {openmode}s works. flux(std::ios::openmode mode = std::ios::in | std::ios::binary) - : std::fstream("/tmp/flux", mode) { } + : std::fstream("/tmp/flux", mode) + {} }; #endif -int test_iostream_main(int /*argc*/,char* /*argv*/[]) +int +test_iostream_main(int /*argc*/, char * /*argv*/[]) { std::cout << std::string("hello, vcl") << std::endl - << std::oct << 01000 << std::endl - << std::hex << 0x1000 << std::endl - << std::dec << 1000 << std::endl - << std::endl; + << std::oct << 01000 << std::endl + << std::hex << 0x1000 << std::endl + << std::dec << 1000 << std::endl + << std::endl; // I/O formatting std::cin.flags(std::ios::skipws | std::ios::boolalpha); std::cout.unsetf(std::ios::dec); - std::ios::fmtflags flgs = - std::cout.setf(std::ios::uppercase | - std::ios::showbase | - std::ios::showpos | - std::ios::showpoint); + const std::ios::fmtflags flgs = + std::cout.setf(std::ios::uppercase | std::ios::showbase | std::ios::showpos | std::ios::showpoint); std::cout.setf(std::ios::oct, std::ios::basefield); std::cout.setf(std::ios::scientific, std::ios::floatfield); std::cout.setf(std::ios::left, std::ios::adjustfield); std::cout << "Scientific, precision=2, width=20, pad_right : ["; - std::cout.precision(2); std::cout.width(20); std::cout.fill('x'); + std::cout.precision(2); + std::cout.width(20); + std::cout.fill('x'); // Note that precision() only applies to the next numeric or string entry! std::cout << 27182.81828 << "] oct " << 10 << std::endl; std::cout.flags(std::ios::showbase | std::ios::showpoint); @@ -56,42 +57,40 @@ int test_iostream_main(int /*argc*/,char* /*argv*/[]) std::cout.setf((std::ios::fmtflags)0, std::ios::floatfield); std::cout.setf(std::ios::internal, std::ios::adjustfield); std::cout << "Default, precision=2, width=20, pad_intern: ["; - std::cout.precision(2); std::cout.width(20); + std::cout.precision(2); + std::cout.width(20); std::cout << 27182.81828 << "] dec " << 10 << std::endl << std::endl; // Now the same output, using manipulators from : - if (false) std::cin >> std::ws >> std::boolalpha; - std::cout << std::resetiosflags(std::ios::dec) - << std::uppercase << std::showbase << std::showpos << std::showpoint - << std::oct << std::scientific << std::left - << "Scientific, precision=2, width=20, pad_right : [" - << std::setprecision(2) << std::setw(20) << std::setfill('x') - << 27182.81828 << "] oct " << 10 << std::endl - << std::nouppercase << std::noshowpos - << std::hex << std::fixed << std::right - << "Fixed, precision=2, width=20, pad_left : [" - << std::setw(20) - << 27182.81828 << "] hex " << 10 << std::endl - << std::noshowbase << std::showpos << std::noshowpoint - << std::resetiosflags(std::ios::fixed | std::ios::scientific) - << std::resetiosflags(std::ios::right | std::ios::left) - << std::dec << std::internal - << "Default, precision=2, width=20, pad_intern: [" - << std::setprecision(2) << std::setw(20) - << 27182.81828 << "] dec " << 10 << std::endl << std::endl; + if (false) + std::cin >> std::ws >> std::boolalpha; + std::cout << std::resetiosflags(std::ios::dec) << std::uppercase << std::showbase << std::showpos << std::showpoint + << std::oct << std::scientific << std::left << "Scientific, precision=2, width=20, pad_right : [" + << std::setprecision(2) << std::setw(20) << std::setfill('x') << 27182.81828 << "] oct " << 10 << std::endl + << std::nouppercase << std::noshowpos << std::hex << std::fixed << std::right + << "Fixed, precision=2, width=20, pad_left : [" << std::setw(20) << 27182.81828 << "] hex " << 10 + << std::endl + << std::noshowbase << std::showpos << std::noshowpoint + << std::resetiosflags(std::ios::fixed | std::ios::scientific) + << std::resetiosflags(std::ios::right | std::ios::left) << std::dec << std::internal + << "Default, precision=2, width=20, pad_intern: [" << std::setprecision(2) << std::setw(20) + << 27182.81828 << "] dec " << 10 << std::endl + << std::endl; std::streampos a = std::cin.tellg(); std::streampos b = std::cout.tellp(); - a = b; b = a; // quell warning about unused vars. compilers are sooo gullible. + a = b; + b = a; // quell warning about unused vars. compilers are sooo gullible. - std::streambuf *ptr = nullptr; + std::streambuf * ptr = nullptr; if (ptr) // quell warning. - ++ ptr; + ++ptr; std::streamsize size = 3141; - ++ size; // quell warning. + ++size; // quell warning. - if (false) { + if (false) + { int x; std::cin >> x; // read from stdin [27.3.1.2] std::cout << "cout goes to stdout [27.3.1.3]" << std::endl; @@ -99,14 +98,10 @@ int test_iostream_main(int /*argc*/,char* /*argv*/[]) std::clog << "clog goes to stderr [27.3.1.5]" << std::endl; } - if (false) { + if (false) + { std::ofstream f("dont_worry_this_file_is_not_created", - std::ios::in | - std::ios::out | - std::ios::ate | - std::ios::app | - std::ios::trunc | - std::ios::binary); + std::ios::in | std::ios::out | std::ios::ate | std::ios::app | std::ios::trunc | std::ios::binary); f.write("hello, file", 11); f.seekp(10); @@ -116,7 +111,8 @@ int test_iostream_main(int /*argc*/,char* /*argv*/[]) f.close(); } - if (false) { + if (false) + { signed char sc; std::cin >> sc; @@ -124,7 +120,7 @@ int test_iostream_main(int /*argc*/,char* /*argv*/[]) std::cin >> bb; } - std::stringstream s(std::ios::in | std::ios::out | std::ios::binary); + const std::stringstream s(std::ios::in | std::ios::out | std::ios::binary); return !s; } diff --git a/vcl/tests/test_iterator.cxx b/vcl/tests/test_iterator.cxx index 456de9c67c9..df0e530853f 100644 --- a/vcl/tests/test_iterator.cxx +++ b/vcl/tests/test_iterator.cxx @@ -7,9 +7,12 @@ # include "vcl_msvc_warnings.h" #endif -void f(std::iterator *) { } +void +f(std::iterator *) +{} -int test_iterator_main(int /*argc*/,char* /*argv*/[]) +int +test_iterator_main(int /*argc*/, char * /*argv*/[]) { // invent some more tests. return 0; diff --git a/vcl/tests/test_limits.cxx b/vcl/tests/test_limits.cxx index ab9907cc76e..5b3888d241f 100644 --- a/vcl/tests/test_limits.cxx +++ b/vcl/tests/test_limits.cxx @@ -4,43 +4,41 @@ # include "vcl_msvc_warnings.h" #endif -static -void test_if_bool_defined( bool ) -{ -} +static void +test_if_bool_defined(bool) +{} -static -void test_if_int_defined( int ) -{ -} +static void +test_if_int_defined(int) +{} // if this function compiles and links, then all the constants have // definitions as they should. -static -void test_static_const_definition() +static void +test_static_const_definition() { -#define TEST_TYPE( Type ) \ - test_if_bool_defined( std::numeric_limits< Type >::is_specialized ); \ - test_if_int_defined( std::numeric_limits< Type >::digits ); \ - test_if_int_defined( std::numeric_limits< Type >::digits10 ); \ - test_if_bool_defined( std::numeric_limits< Type >::is_signed ); \ - test_if_bool_defined( std::numeric_limits< Type >::is_integer ); \ - test_if_bool_defined( std::numeric_limits< Type >::is_exact ); \ - test_if_int_defined( std::numeric_limits< Type >::radix ); \ - test_if_int_defined( std::numeric_limits< Type >::min_exponent ); \ - test_if_int_defined( std::numeric_limits< Type >::min_exponent10 ); \ - test_if_int_defined( std::numeric_limits< Type >::max_exponent ); \ - test_if_int_defined( std::numeric_limits< Type >::max_exponent10 ); \ - test_if_bool_defined( std::numeric_limits< Type >::has_infinity ); \ - test_if_bool_defined( std::numeric_limits< Type >::has_quiet_NaN ); \ - test_if_bool_defined( std::numeric_limits< Type >::has_signaling_NaN ); \ - test_if_bool_defined( std::numeric_limits< Type >::has_denorm ); \ - test_if_bool_defined( std::numeric_limits< Type >::is_iec559 ); \ - test_if_bool_defined( std::numeric_limits< Type >::is_bounded ); \ - test_if_bool_defined( std::numeric_limits< Type >::is_modulo ); \ - test_if_bool_defined( std::numeric_limits< Type >::traps ); \ - test_if_bool_defined( std::numeric_limits< Type >::tinyness_before ); +#define TEST_TYPE(Type) \ + test_if_bool_defined(std::numeric_limits::is_specialized); \ + test_if_int_defined(std::numeric_limits::digits); \ + test_if_int_defined(std::numeric_limits::digits10); \ + test_if_bool_defined(std::numeric_limits::is_signed); \ + test_if_bool_defined(std::numeric_limits::is_integer); \ + test_if_bool_defined(std::numeric_limits::is_exact); \ + test_if_int_defined(std::numeric_limits::radix); \ + test_if_int_defined(std::numeric_limits::min_exponent); \ + test_if_int_defined(std::numeric_limits::min_exponent10); \ + test_if_int_defined(std::numeric_limits::max_exponent); \ + test_if_int_defined(std::numeric_limits::max_exponent10); \ + test_if_bool_defined(std::numeric_limits::has_infinity); \ + test_if_bool_defined(std::numeric_limits::has_quiet_NaN); \ + test_if_bool_defined(std::numeric_limits::has_signaling_NaN); \ + test_if_bool_defined(std::numeric_limits::has_denorm); \ + test_if_bool_defined(std::numeric_limits::is_iec559); \ + test_if_bool_defined(std::numeric_limits::is_bounded); \ + test_if_bool_defined(std::numeric_limits::is_modulo); \ + test_if_bool_defined(std::numeric_limits::traps); \ + test_if_bool_defined(std::numeric_limits::tinyness_before); TEST_TYPE(int); TEST_TYPE(long); @@ -52,73 +50,78 @@ void test_static_const_definition() #undef TEST_TYPE } -#define TEST(m,x,y) if ((x)!=(y)) { std::cout<< "FAIL: " << (m) << '\n'; fail=true; } \ - else { std::cout<< "PASS: " << (m) << '\n'; } +#define TEST(m, x, y) \ + if ((x) != (y)) \ + { \ + std::cout << "FAIL: " << (m) << '\n'; \ + fail = true; \ + } \ + else \ + { \ + std::cout << "PASS: " << (m) << '\n'; \ + } -int test_limits_main(int /*argc*/, char* /*argv*/[]) +int +test_limits_main(int /*argc*/, char * /*argv*/[]) { // call it to avoid "unused function" compiler warnings, // and to force compilation with "very clever" compilers: test_static_const_definition(); - bool fail=false; + bool fail = false; std::cout << "dmax = " << std::numeric_limits::max() << std::endl - << "dmin = " << std::numeric_limits::min() << std::endl - << "deps = " << std::numeric_limits::epsilon() << std::endl - << "dnmin = " << std::numeric_limits::denorm_min() << std::endl - << "dnan = " << std::numeric_limits::quiet_NaN() << std::endl - << "dsnan = " << std::numeric_limits::signaling_NaN() << std::endl - << "dinf = " << std::numeric_limits::infinity() << std::endl - << "-dinf = " <<-std::numeric_limits::infinity() << std::endl - << "rnder = " << std::numeric_limits::round_error() << std::endl - - << "fmax = " << std::numeric_limits::max() << std::endl - << "fmin = " << std::numeric_limits::min() << std::endl - << "feps = " << std::numeric_limits::epsilon() << std::endl - << "fnmin = " << std::numeric_limits::denorm_min() << std::endl - << "fnan = " << std::numeric_limits::quiet_NaN() << std::endl - << "fsnan = " << std::numeric_limits::signaling_NaN() << std::endl - << "finf = " << std::numeric_limits::infinity() << std::endl - << "-finf = " <<-std::numeric_limits::infinity() << std::endl - << "rnder = " << std::numeric_limits::round_error() << std::endl - - << "s8max = " << int(std::numeric_limits::max()) << std::endl - << "s8min = " << int(std::numeric_limits::min()) << std::endl - - << "u8max = " << int(std::numeric_limits::max()) << std::endl - << "u8min = " << int(std::numeric_limits::min()) << std::endl - - << "s16max = " << std::numeric_limits::max() << std::endl - << "s16min = " << std::numeric_limits::min() << std::endl - - << "u16max = " << std::numeric_limits::max() << std::endl - << "u16min = " << std::numeric_limits::min() << std::endl - - << "s32max = " << std::numeric_limits::max() << std::endl - << "s32min = " << std::numeric_limits::min() << std::endl - - << "u32max = " << std::numeric_limits::max() << std::endl - << "u32min = " << std::numeric_limits::min() << std::endl; + << "dmin = " << std::numeric_limits::min() << std::endl + << "deps = " << std::numeric_limits::epsilon() << std::endl + << "dnmin = " << std::numeric_limits::denorm_min() << std::endl + << "dnan = " << std::numeric_limits::quiet_NaN() << std::endl + << "dsnan = " << std::numeric_limits::signaling_NaN() << std::endl + << "dinf = " << std::numeric_limits::infinity() << std::endl + << "-dinf = " << -std::numeric_limits::infinity() << std::endl + << "rnder = " << std::numeric_limits::round_error() << std::endl + + << "fmax = " << std::numeric_limits::max() << std::endl + << "fmin = " << std::numeric_limits::min() << std::endl + << "feps = " << std::numeric_limits::epsilon() << std::endl + << "fnmin = " << std::numeric_limits::denorm_min() << std::endl + << "fnan = " << std::numeric_limits::quiet_NaN() << std::endl + << "fsnan = " << std::numeric_limits::signaling_NaN() << std::endl + << "finf = " << std::numeric_limits::infinity() << std::endl + << "-finf = " << -std::numeric_limits::infinity() << std::endl + << "rnder = " << std::numeric_limits::round_error() << std::endl + + << "s8max = " << int(std::numeric_limits::max()) << std::endl + << "s8min = " << int(std::numeric_limits::min()) << std::endl + + << "u8max = " << int(std::numeric_limits::max()) << std::endl + << "u8min = " << int(std::numeric_limits::min()) << std::endl + + << "s16max = " << std::numeric_limits::max() << std::endl + << "s16min = " << std::numeric_limits::min() << std::endl + + << "u16max = " << std::numeric_limits::max() << std::endl + << "u16min = " << std::numeric_limits::min() << std::endl + + << "s32max = " << std::numeric_limits::max() << std::endl + << "s32min = " << std::numeric_limits::min() << std::endl + + << "u32max = " << std::numeric_limits::max() << std::endl + << "u32min = " << std::numeric_limits::min() << std::endl; TEST("dmax", std::numeric_limits::max() > 1e308, true); - if (std::numeric_limits::has_infinity) { - TEST("dinf", std::numeric_limits::infinity() > - std::numeric_limits::max(), true); + if (std::numeric_limits::has_infinity) + { + TEST("dinf", std::numeric_limits::infinity() > std::numeric_limits::max(), true); } - TEST("dmin", std::numeric_limits::min() < 1e-307 && - std::numeric_limits::min() > 0, true); - TEST("deps", std::numeric_limits::epsilon() < 1e-12 && - std::numeric_limits::epsilon() > 0, true); - TEST("rnder",std::numeric_limits::round_error() <= 1.0, true); + TEST("dmin", std::numeric_limits::min() < 1e-307 && std::numeric_limits::min() > 0, true); + TEST("deps", std::numeric_limits::epsilon() < 1e-12 && std::numeric_limits::epsilon() > 0, true); + TEST("rnder", std::numeric_limits::round_error() <= 1.0, true); TEST("fmax", std::numeric_limits::max() > 1e38f, true); - if (std::numeric_limits::has_infinity) { - TEST("finf", std::numeric_limits::infinity() > - std::numeric_limits::max(), true); + if (std::numeric_limits::has_infinity) + { + TEST("finf", std::numeric_limits::infinity() > std::numeric_limits::max(), true); } - TEST("fmin", std::numeric_limits::min() < 1e-37f && - std::numeric_limits::min() > 0, true); - TEST("feps", std::numeric_limits::epsilon() < 1e-6f && - std::numeric_limits::epsilon() > 0, true); - TEST("rnder",std::numeric_limits::round_error() <= 1.0, true); - return fail?1:0; + TEST("fmin", std::numeric_limits::min() < 1e-37f && std::numeric_limits::min() > 0, true); + TEST("feps", std::numeric_limits::epsilon() < 1e-6f && std::numeric_limits::epsilon() > 0, true); + TEST("rnder", std::numeric_limits::round_error() <= 1.0, true); + return fail ? 1 : 0; } diff --git a/vcl/tests/test_list.cxx b/vcl/tests/test_list.cxx index 9d73d9f9b01..f3500f35523 100644 --- a/vcl/tests/test_list.cxx +++ b/vcl/tests/test_list.cxx @@ -5,7 +5,8 @@ # include "vcl_msvc_warnings.h" #endif -int test_list_main(int /*argc*/,char* /*argv*/[]) +int +test_list_main(int /*argc*/, char * /*argv*/[]) { using container = std::list; container m; diff --git a/vcl/tests/test_map.cxx b/vcl/tests/test_map.cxx index 5d4f5afa3d1..824ea8e8554 100644 --- a/vcl/tests/test_map.cxx +++ b/vcl/tests/test_map.cxx @@ -6,10 +6,11 @@ # include "vcl_msvc_warnings.h" #endif -int test_map_main(int /*argc*/,char* /*argv*/[]) +int +test_map_main(int /*argc*/, char * /*argv*/[]) { bool okay = true; - typedef std::map > mymap; + typedef std::map> mymap; mymap m; m.insert(mymap::value_type(1, 2718)); @@ -23,7 +24,7 @@ int test_map_main(int /*argc*/,char* /*argv*/[]) i = m.find(2); okay = okay && (i != m.end()) && ((*i).second == 3141); - if ( okay ) + if (okay) return 0; else return 1; diff --git a/vcl/tests/test_memory.cxx b/vcl/tests/test_memory.cxx index fe443a2d4d8..390ff13c9da 100644 --- a/vcl/tests/test_memory.cxx +++ b/vcl/tests/test_memory.cxx @@ -4,7 +4,13 @@ # include "vcl_msvc_warnings.h" #endif -#define ASSERT(x,y) if (!(x)) { std::printf("FAIL: " y "\n"); status = 1; } static_assert(true, "") +#define ASSERT(x, y) \ + if (!(x)) \ + { \ + std::printf("FAIL: " y "\n"); \ + status = 1; \ + } \ + static_assert(true, "") static int instances = 0; @@ -12,21 +18,36 @@ struct A { A() { ++instances; } ~A() { --instances; } - A* self() {return this; } + A * + self() + { + return this; + } }; -struct B: public A {}; +struct B : public A +{}; -static int function_call(std::unique_ptr a) +static int +function_call(std::unique_ptr a) { - return a.get()? 1:0; + return a.get() ? 1 : 0; } -static A* get_A(A& a) { return &a; } +static A * +get_A(A & a) +{ + return &a; +} -static std::unique_ptr generate_auto_ptr () { return std::unique_ptr(new A); } +static std::unique_ptr +generate_auto_ptr() +{ + return std::unique_ptr(new A); +} -int test_memory_main(int /*argc*/,char* /*argv*/[]) +int +test_memory_main(int /*argc*/, char * /*argv*/[]) { int status = 0; @@ -38,36 +59,32 @@ int test_memory_main(int /*argc*/,char* /*argv*/[]) std::unique_ptr pa2(new B()); std::unique_ptr pa3(std::move(pb1)); - A* ptr = get_A(*pa1); - ASSERT(ptr == pa1.get(), - "auto_ptr does not return correct object when dereferenced"); + A * ptr = get_A(*pa1); + ASSERT(ptr == pa1.get(), "auto_ptr does not return correct object when dereferenced"); ptr = pa1->self(); - ASSERT(ptr == pa1.get(), - "auto_ptr does not return correct pointer from operator->"); + ASSERT(ptr == pa1.get(), "auto_ptr does not return correct pointer from operator->"); - A* before = pa0.get(); + A * before = pa0.get(); pa0.reset(new A()); - ASSERT(pa0.get() && pa0.get() != before, - "auto_ptr does not hold a new object after reset(new A())"); + ASSERT(pa0.get() && pa0.get() != before, "auto_ptr does not hold a new object after reset(new A())"); before = pa0.get(); pa0.reset(new B()); - ASSERT(pa0.get() && pa0.get() != before, - "auto_ptr does not hold a new object after reset(new B())"); + ASSERT(pa0.get() && pa0.get() != before, "auto_ptr does not hold a new object after reset(new B())"); delete pa0.release(); ASSERT(!pa0.get(), "auto_ptr holds an object after release()"); pa1 = std::move(pa3); - int copied = function_call(std::move(pa2)); + const int copied = function_call(std::move(pa2)); ASSERT(copied, "auto_ptr did not receive ownership in called function"); - // can not access pa2 after being moved: ASSERT(!pa2.get(), "auto_ptr did not release ownership to called function"); + // can not access pa2 after being moved: ASSERT(!pa2.get(), "auto_ptr did not release ownership to called + // function"); pa3 = generate_auto_ptr(); - ASSERT(pa3.get(), - "auto_ptr does not hold an object after assignment from factory function"); + ASSERT(pa3.get(), "auto_ptr does not hold an object after assignment from factory function"); } ASSERT(instances == 0, "auto_ptr leaked an object"); @@ -76,19 +93,17 @@ int test_memory_main(int /*argc*/,char* /*argv*/[]) // reset instance count for shared pointer tests instances = 0; { - std::shared_ptr spa0; - std::shared_ptr spa1(new A()); - std::shared_ptr spb1(new B()); - std::shared_ptr spa2(new B()); - std::shared_ptr spa3(spb1); - std::weak_ptr wpa1(spa1); - - A* ptr = get_A(*spa1); - ASSERT(ptr == spa1.get(), - "shared_ptr does not return correct object when dereferenced"); + const std::shared_ptr spa0; + const std::shared_ptr spa1(new A()); + const std::shared_ptr spb1(new B()); + const std::shared_ptr spa2(new B()); + const std::shared_ptr spa3(spb1); + const std::weak_ptr wpa1(spa1); + + A * ptr = get_A(*spa1); + ASSERT(ptr == spa1.get(), "shared_ptr does not return correct object when dereferenced"); ptr = spa1->self(); - ASSERT(ptr == spa1.get(), - "shared_ptr does not return correct pointer from operator->"); + ASSERT(ptr == spa1.get(), "shared_ptr does not return correct pointer from operator->"); // FIXME several more tests are needed here } diff --git a/vcl/tests/test_multimap.cxx b/vcl/tests/test_multimap.cxx index 937aa83a89e..925d2647853 100644 --- a/vcl/tests/test_multimap.cxx +++ b/vcl/tests/test_multimap.cxx @@ -6,20 +6,22 @@ # include "vcl_msvc_warnings.h" #endif -typedef std::multimap > mymap; +typedef std::multimap> mymap; -std::ostream &operator<<(std::ostream &s, mymap::value_type const &x) +std::ostream & +operator<<(std::ostream & s, const mymap::value_type & x) { return s << '(' << x.first << ',' << x.second << ')'; } -int test_multimap_main(int /*argc*/,char* /*argv*/[]) +int +test_multimap_main(int /*argc*/, char * /*argv*/[]) { mymap m; m.insert(mymap::value_type(0, 2.718281828459045)); // e m.insert(mymap::value_type(1, 3.141592653589793)); // pi m.insert(mymap::value_type(2, 1.414213562373095)); // sqrt(2) - m.insert(mymap::value_type(3, 1.61803398874989)); // golden number + m.insert(mymap::value_type(3, 1.61803398874989)); // golden number auto b = m.begin(); auto e = m.end(); @@ -29,21 +31,28 @@ int test_multimap_main(int /*argc*/,char* /*argv*/[]) std::cout << *p << std::endl; std::cout << "lower_bound() and upper_bound():" << std::endl; - for (int k=-1; k<=4; ++k) { + for (int k = -1; k <= 4; ++k) + { std::cout << "k=" << k << std::endl; auto lo = m.lower_bound(k); std::cout << " lo: "; - if (lo==b) std::cout << "begin"; - else if (lo==e) std::cout << "end"; - else std::cout << *lo; + if (lo == b) + std::cout << "begin"; + else if (lo == e) + std::cout << "end"; + else + std::cout << *lo; std::cout << std::endl; auto hi = m.upper_bound(k); std::cout << " hi: "; - if (hi==b) std::cout << "begin"; - else if (hi==e) std::cout << "end"; - else std::cout << *hi; + if (hi == b) + std::cout << "begin"; + else if (hi == e) + std::cout << "end"; + else + std::cout << *hi; std::cout << std::endl; } diff --git a/vcl/tests/test_preprocessor.cxx b/vcl/tests/test_preprocessor.cxx index 4fed28fa745..faf2fbeb020 100644 --- a/vcl/tests/test_preprocessor.cxx +++ b/vcl/tests/test_preprocessor.cxx @@ -6,15 +6,14 @@ #endif #include "vcl_compiler.h" -int test_preprocessor_main(int /*argc*/,char* /*argv*/[]) +int +test_preprocessor_main(int /*argc*/, char * /*argv*/[]) { - int result = 0; - std::cout << "VXL version identified as: " - << VXL_VERSION_MAJOR << "." - << VXL_VERSION_MINOR << "." - << VXL_VERSION_PATCH ; + const int result = 0; + std::cout << "VXL version identified as: " << VXL_VERSION_MAJOR << "." << VXL_VERSION_MINOR << "." + << VXL_VERSION_PATCH; - std::cout << "Version identified implies release identified: "; + std::cout << "Version identified implies release identified: "; std::cout << "PASSED\n"; return result; } diff --git a/vcl/tests/test_set.cxx b/vcl/tests/test_set.cxx index be56b434e0e..6b973a7b89b 100644 --- a/vcl/tests/test_set.cxx +++ b/vcl/tests/test_set.cxx @@ -5,9 +5,10 @@ # include "vcl_msvc_warnings.h" #endif -int test_set_main(int /*argc*/,char* /*argv*/[]) +int +test_set_main(int /*argc*/, char * /*argv*/[]) { - typedef std::set > myset; + typedef std::set> myset; myset s; s.insert(1); diff --git a/vcl/tests/test_sstream.cxx b/vcl/tests/test_sstream.cxx index b1056b84774..92cb64b5c8e 100644 --- a/vcl/tests/test_sstream.cxx +++ b/vcl/tests/test_sstream.cxx @@ -5,26 +5,37 @@ # include "vcl_msvc_warnings.h" #endif -#define AssertEq(x,y) {status+=((x)==(y))?0:1;std::cout<<"TEST ["<<(x)<<"] == ["<<(y)<<"] : "<<((x)==(y)?"PASSED":"FAILED")<> fred; - AssertEq(fred,"fred"); + AssertEq(fred, "fred"); std::istringstream s("wilma"); char w = '?'; - s >> w; AssertEq((int)w,'w'); - s >> w; AssertEq((int)w,'i'); - s >> w; AssertEq((int)w,'l'); - s >> w; AssertEq((int)w,'m'); - s >> w; AssertEq((int)w,'a'); + s >> w; + AssertEq((int)w, 'w'); + s >> w; + AssertEq((int)w, 'i'); + s >> w; + AssertEq((int)w, 'l'); + s >> w; + AssertEq((int)w, 'm'); + s >> w; + AssertEq((int)w, 'a'); return status; } diff --git a/vcl/tests/test_stlfwd.cxx b/vcl/tests/test_stlfwd.cxx index 5b699d519e6..29a766d6ca4 100644 --- a/vcl/tests/test_stlfwd.cxx +++ b/vcl/tests/test_stlfwd.cxx @@ -9,15 +9,13 @@ # include "vcl_msvc_warnings.h" #endif -void f(std::map >*, - std::set >*, - std::list* - ) -{ -} +void +f(std::map> *, std::set> *, std::list *) +{} -int test_stlfwd_main(int /*argc*/,char* /*argv*/[]) +int +test_stlfwd_main(int /*argc*/, char * /*argv*/[]) { return 0; } diff --git a/vcl/tests/test_string.cxx b/vcl/tests/test_string.cxx index 45507040e29..d976a32085d 100644 --- a/vcl/tests/test_string.cxx +++ b/vcl/tests/test_string.cxx @@ -4,21 +4,31 @@ # include "vcl_msvc_warnings.h" #endif -#define Assert(x) {std::cout << "TEST " #x " : "; std::cout << ((x)?"PASSED":"FAILED")} static_assert(true, "") - -#define AssertEq(x) {std::cout<<"TEST ["< class vcl_test_vec { - T* data_; + T * data_; int size_; - public: - vcl_test_vec(int s=1) : size_(s) { data_ = new T[s]; } + +public: + vcl_test_vec(int s = 1) + : size_(s) + { + data_ = new T[s]; + } ~vcl_test_vec() { delete[] data_; } - int size() const { return size_; } + int + size() const + { + return size_; + } }; template @@ -22,18 +31,36 @@ struct vcl_test_type_templ template class vcl_test_typename { - public: +public: using vector = typename vcl_test_type_templ::type; vector v; - vcl_test_typename() { if (vcl_test_typename_func(v) < 1) v = 1; } + vcl_test_typename() + { + if (vcl_test_typename_func(v) < 1) + v = 1; + } }; -inline int vcl_test_typename_func(float /*v*/) { return 1; } -inline int vcl_test_typename_func(double /*v*/) { return 1; } -template inline int vcl_test_typename_func(vcl_test_vec const& v) { return v.size(); } +inline int +vcl_test_typename_func(float /*v*/) +{ + return 1; +} +inline int +vcl_test_typename_func(double /*v*/) +{ + return 1; +} +template +inline int +vcl_test_typename_func(const vcl_test_vec & v) +{ + return v.size(); +} -int test_typename_main(int /*argc*/,char* /*argv*/[]) +int +test_typename_main(int /*argc*/, char * /*argv*/[]) { return 0; } diff --git a/vcl/tests/test_vector.cxx b/vcl/tests/test_vector.cxx index 41932579a1f..d4d854853a7 100644 --- a/vcl/tests/test_vector.cxx +++ b/vcl/tests/test_vector.cxx @@ -6,14 +6,15 @@ # include "vcl_msvc_warnings.h" #endif -std::ostream &delim(std::ostream &os) +std::ostream & +delim(std::ostream & os) { - //return os << endl; + // return os << endl; return os << ", "; } -int frurk(std::vector const &a, - std::vector const &b) +int +frurk(const std::vector & a, const std::vector & b) { if (a == b) return 0; @@ -22,7 +23,8 @@ int frurk(std::vector const &a, return 2; } -int test_vector_main(int /*argc*/,char* /*argv*/[]) +int +test_vector_main(int /*argc*/, char * /*argv*/[]) { bool fail = false; { @@ -32,18 +34,16 @@ int test_vector_main(int /*argc*/,char* /*argv*/[]) m.push_back(1); m.push_back(2); - for (int & p : m) + for (const int & p : m) std::cout << p << std::endl; } { std::vector v; - for (unsigned i=0; i<10; ++i) + for (unsigned i = 0; i < 10; ++i) { - std::cout << "size : " << v.size() << delim - << "capacity : " << v.capacity() << delim; - if (i>0) - std::cout << "begin : " << (void*) &* v.begin() - << delim << "end - 1: " << (void*) &* (v.end() - 1) << std::endl; + std::cout << "size : " << v.size() << delim << "capacity : " << v.capacity() << delim; + if (i > 0) + std::cout << "begin : " << (void *)&*v.begin() << delim << "end - 1: " << (void *)&*(v.end() - 1) << std::endl; else std::cout << std::endl; @@ -51,20 +51,34 @@ int test_vector_main(int /*argc*/,char* /*argv*/[]) } } { - std::vector bv(2); - bv[0] = true; - bv[1] = false; - std::nth_element(bv.begin(), bv.begin()+1, bv.end()); + std::vector bv(2); + bv[0] = true; + bv[1] = false; + std::nth_element(bv.begin(), bv.begin() + 1, bv.end()); } { // check contiguity -#define macro(T) do { \ - std::vector v; \ - for (int i=0; i<5; ++i) v.push_back(T(i)); \ - bool ok = true; \ - for (unsigned int i=1; i has contiguous storage\n"; \ - else { std::cout << "FAIL: vector<" << #T << "> has non-contiguous storage\n"; fail = true; } \ -} while (false) +#define macro(T) \ + do \ + { \ + std::vector v; \ + for (int i = 0; i < 5; ++i) \ + v.push_back(T(i)); \ + bool ok = true; \ + for (unsigned int i = 1; i < v.size(); ++i) \ + { \ + T * p = &v[i - 1]; \ + T * q = &v[i]; \ + if (p + 1 != q) \ + ok = false; \ + } \ + if (ok) \ + std::cout << "PASS: vector<" << #T << "> has contiguous storage\n"; \ + else \ + { \ + std::cout << "FAIL: vector<" << #T << "> has non-contiguous storage\n"; \ + fail = true; \ + } \ + } while (false) macro(char); macro(int); macro(double); diff --git a/vcl/vcl_algorithm.h b/vcl/vcl_algorithm.h index d37b8f01d48..50ac1e3eb2f 100644 --- a/vcl/vcl_algorithm.h +++ b/vcl/vcl_algorithm.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_algorithm_h_ diff --git a/vcl/vcl_atomic_count.h b/vcl/vcl_atomic_count.h index d4f74564ca3..7823d2a02a2 100644 --- a/vcl/vcl_atomic_count.h +++ b/vcl/vcl_atomic_count.h @@ -3,7 +3,7 @@ // MS compatible compilers support #pragma once #if defined(_MSC_VER) -# pragma once +# pragma once #endif //: // \file @@ -79,15 +79,15 @@ // are called driven by smart_ptr interface... // -#if defined( __GNUC__ ) && ( defined( __i386__ ) || defined( __x86_64__ ) ) +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) -# include "internal/vcl_atomic_count_gcc_x86.h" +# include "internal/vcl_atomic_count_gcc_x86.h" #elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) # include "internal/vcl_atomic_count_win32.h" -#elif defined( __GNUC__ ) && ( __GNUC__ * 100 + __GNUC_MINOR__ >= 401 ) +#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 401) # include "internal/vcl_atomic_count_sync.h" @@ -103,7 +103,7 @@ #else // Use #define BOOST_DISABLE_THREADS to avoid the error -#error Unrecognized threading platform +# error Unrecognized threading platform #endif diff --git a/vcl/vcl_bitset.h b/vcl/vcl_bitset.h index c13430aa356..287aa4231db 100644 --- a/vcl/vcl_bitset.h +++ b/vcl/vcl_bitset.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_bitset_h_ diff --git a/vcl/vcl_cassert.h b/vcl/vcl_cassert.h index 29de5b14f36..422d5f70139 100644 --- a/vcl/vcl_cassert.h +++ b/vcl/vcl_cassert.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cassert_h_ diff --git a/vcl/vcl_cctype.h b/vcl/vcl_cctype.h index c853d34f7d5..bf631085128 100644 --- a/vcl/vcl_cctype.h +++ b/vcl/vcl_cctype.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cctype_h_ diff --git a/vcl/vcl_cerrno.h b/vcl/vcl_cerrno.h index 810a21b5b0c..ae033f9a91a 100644 --- a/vcl/vcl_cerrno.h +++ b/vcl/vcl_cerrno.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cerrno_h_ diff --git a/vcl/vcl_cfloat.h b/vcl/vcl_cfloat.h index 548e11005a6..0f54f501d4b 100644 --- a/vcl/vcl_cfloat.h +++ b/vcl/vcl_cfloat.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cfloat_h_ diff --git a/vcl/vcl_ciso646.h b/vcl/vcl_ciso646.h index 6664650b4b0..5e8a2429850 100644 --- a/vcl/vcl_ciso646.h +++ b/vcl/vcl_ciso646.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_ciso646_h_ diff --git a/vcl/vcl_climits.h b/vcl/vcl_climits.h index 24c1dd7f7e2..63063222379 100644 --- a/vcl/vcl_climits.h +++ b/vcl/vcl_climits.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_climits_h_ diff --git a/vcl/vcl_clocale.h b/vcl/vcl_clocale.h index 8330fc83e3f..d25925b50de 100644 --- a/vcl/vcl_clocale.h +++ b/vcl/vcl_clocale.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_clocale_h_ diff --git a/vcl/vcl_cmath.h b/vcl/vcl_cmath.h index c1b6f85d1b6..0319e01dab7 100644 --- a/vcl/vcl_cmath.h +++ b/vcl/vcl_cmath.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cmath_h_ diff --git a/vcl/vcl_compiler_detection.h b/vcl/vcl_compiler_detection.h index 60783bd1c35..1396e448e92 100644 --- a/vcl/vcl_compiler_detection.h +++ b/vcl/vcl_compiler_detection.h @@ -12,13 +12,13 @@ Run "cmake --help-policy CMP0120" for policy details. Prevent configuration time warning messages when using cmake versions greater than 3.20 */ -#if !defined(_MSC_VER) //MSVC does not consistently define __cplusplus -#pragma message "The vcl_compiler_detection.h header file is no longer used.\n" \ - "In most cases, references to this file can simply be removed.\n" \ - "Use of VXL_DEPRECATED or VXL_DEPRECATED_MSG should include\n" \ - "vcl_compiler.h instead." +#if !defined(_MSC_VER) // MSVC does not consistently define __cplusplus +# pragma message "The vcl_compiler_detection.h header file is no longer used.\n" \ + "In most cases, references to this file can simply be removed.\n" \ + "Use of VXL_DEPRECATED or VXL_DEPRECATED_MSG should include\n" \ + "vcl_compiler.h instead." #else -#warning "The vcl_compiler_detection.h header file is no longer used.\n" \ +# warning "The vcl_compiler_detection.h header file is no longer used.\n" \ "In most cases, references to this file can simply be removed.\n" \ "Use of VXL_DEPRECATED or VXL_DEPRECATED_MSG should include\n" \ "vcl_compiler.h instead." diff --git a/vcl/vcl_complex.h b/vcl/vcl_complex.h index fbb48ef2021..96a7f3f819e 100644 --- a/vcl/vcl_complex.h +++ b/vcl/vcl_complex.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_complex_h_ diff --git a/vcl/vcl_csetjmp.h b/vcl/vcl_csetjmp.h index b1510cc9f28..d0a955e83fb 100644 --- a/vcl/vcl_csetjmp.h +++ b/vcl/vcl_csetjmp.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_csetjmp_h_ diff --git a/vcl/vcl_csignal.h b/vcl/vcl_csignal.h index 13522bda8cc..2d913534c6b 100644 --- a/vcl/vcl_csignal.h +++ b/vcl/vcl_csignal.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_csignal_h_ diff --git a/vcl/vcl_cstdarg.h b/vcl/vcl_cstdarg.h index ef494299ee8..b4abb840992 100644 --- a/vcl/vcl_cstdarg.h +++ b/vcl/vcl_cstdarg.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cstdarg_h_ diff --git a/vcl/vcl_cstddef.h b/vcl/vcl_cstddef.h index 0653ecfa828..37a2a44fcac 100644 --- a/vcl/vcl_cstddef.h +++ b/vcl/vcl_cstddef.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cstddef_h_ diff --git a/vcl/vcl_cstdio.h b/vcl/vcl_cstdio.h index fab442aed46..2d46b35ba37 100644 --- a/vcl/vcl_cstdio.h +++ b/vcl/vcl_cstdio.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cstdio_h_ diff --git a/vcl/vcl_cstdlib.h b/vcl/vcl_cstdlib.h index 58d74fdcae0..3e0e81a585f 100644 --- a/vcl/vcl_cstdlib.h +++ b/vcl/vcl_cstdlib.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cstdlib_h_ diff --git a/vcl/vcl_cstring.h b/vcl/vcl_cstring.h index cde784fa064..c1e092b6ab1 100644 --- a/vcl/vcl_cstring.h +++ b/vcl/vcl_cstring.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cstring_h_ diff --git a/vcl/vcl_ctime.h b/vcl/vcl_ctime.h index 8fe7999c89a..d3f81b9b959 100644 --- a/vcl/vcl_ctime.h +++ b/vcl/vcl_ctime.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_ctime_h_ diff --git a/vcl/vcl_cwchar.h b/vcl/vcl_cwchar.h index 1319402684f..1c3e31af0c6 100644 --- a/vcl/vcl_cwchar.h +++ b/vcl/vcl_cwchar.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cwchar_h_ diff --git a/vcl/vcl_cwctype.h b/vcl/vcl_cwctype.h index 4285d5c134a..b1f4352fb46 100644 --- a/vcl/vcl_cwctype.h +++ b/vcl/vcl_cwctype.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_cwctype_h_ diff --git a/vcl/vcl_deprecated.cxx b/vcl/vcl_deprecated.cxx index 73b6238ea3e..e5ffa781af7 100644 --- a/vcl/vcl_deprecated.cxx +++ b/vcl/vcl_deprecated.cxx @@ -6,7 +6,7 @@ #ifdef VXL_WARN_DEPRECATED_ABORT void -vcl_deprecated_abort( const char * func_name ) +vcl_deprecated_abort(const char * func_name) { std::cerr << "Function " << func_name << " is deprecated." << std::endl; std::abort(); @@ -15,7 +15,7 @@ vcl_deprecated_abort( const char * func_name ) #else void -vcl_deprecated_warn( const char* func_name ) +vcl_deprecated_warn(const char * func_name) { std::cerr << "Function " << func_name << " is deprecated." << std::endl; } diff --git a/vcl/vcl_deprecated.h b/vcl/vcl_deprecated.h index 08b8f78c3be..cb895950e65 100644 --- a/vcl/vcl_deprecated.h +++ b/vcl/vcl_deprecated.h @@ -30,37 +30,44 @@ // to define VXL_WARN_DEPRECATED_ABORT and then do a stack trace using // a debugger! -#ifdef VXL_WARN_DEPRECATED - #ifdef VXL_WARN_DEPRECATED_ABORT - void vcl_deprecated_abort( const char* func_name ); - #define VXL_DEPRECATED_MACRO(f) vcl_deprecated_abort( f ) - #else - void vcl_deprecated_warn( const char* func_name ); - #ifdef VXL_WARN_DEPRECATED_ONCE - #define VXL_DEPRECATED_MACRO(f) \ - do { \ +# ifdef VXL_WARN_DEPRECATED +# ifdef VXL_WARN_DEPRECATED_ABORT +void +vcl_deprecated_abort(const char * func_name); +# define VXL_DEPRECATED_MACRO(f) vcl_deprecated_abort(f) +# else +void +vcl_deprecated_warn(const char * func_name); +# ifdef VXL_WARN_DEPRECATED_ONCE +# define VXL_DEPRECATED_MACRO(f) \ + do \ + { \ static bool vcl_deprecated_flag = true; \ - if( vcl_deprecated_flag ) { \ - vcl_deprecated_warn( f ); \ - vcl_deprecated_flag=false; \ - } \ - } while (0) - #else - #define VXL_DEPRECATED_MACRO(f) vcl_deprecated_warn( f ) - #endif - #endif -#else - #define VXL_DEPRECATED_MACRO(f) /* suppress deprecation warning */ -#endif + if (vcl_deprecated_flag) \ + { \ + vcl_deprecated_warn(f); \ + vcl_deprecated_flag = false; \ + } \ + } while (0) +# else +# define VXL_DEPRECATED_MACRO(f) vcl_deprecated_warn(f) +# endif +# endif +# else +# define VXL_DEPRECATED_MACRO(f) /* suppress deprecation warning */ +# endif -#ifdef _MSC_VER -#pragma message ( "warning: vcl_deprecated.h, and it's associated VXL_WARN_DEPRECATED functions should be replaced with vcl_compiler.h and VXL_DEPRECATED_MSG variants." ) -#else -#warning "vcl_deprecated.h, and it's associated VXL_WARN_DEPRECATED functions should be replaced with vcl_compiler.h and VXL_DEPRECATED_MSG variants." -#endif +# ifdef _MSC_VER +# pragma message( \ + "warning: vcl_deprecated.h, and it's associated VXL_WARN_DEPRECATED functions should be replaced with vcl_compiler.h and VXL_DEPRECATED_MSG variants.") +# else +# warning \ + "vcl_deprecated.h, and it's associated VXL_WARN_DEPRECATED functions should be replaced with vcl_compiler.h and VXL_DEPRECATED_MSG variants." +# endif #else -#error "vcl_deprecated.h, and it's associated VXL_WARN_DEPRECATED functions should be replaced with vcl_compiler.h and VXL_DEPRECATED_MSG variants." +# error \ + "vcl_deprecated.h, and it's associated VXL_WARN_DEPRECATED functions should be replaced with vcl_compiler.h and VXL_DEPRECATED_MSG variants." #endif #endif diff --git a/vcl/vcl_exception.h b/vcl/vcl_exception.h index 143f27806c2..94dee08cf12 100644 --- a/vcl/vcl_exception.h +++ b/vcl/vcl_exception.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_exception_h_ diff --git a/vcl/vcl_fstream.h b/vcl/vcl_fstream.h index 31051b0f2bc..a8fc2f739f4 100644 --- a/vcl/vcl_fstream.h +++ b/vcl/vcl_fstream.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_fstream_h_ diff --git a/vcl/vcl_functional.h b/vcl/vcl_functional.h index 08a148e2ff5..7a80725d74c 100644 --- a/vcl/vcl_functional.h +++ b/vcl/vcl_functional.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_functional_h_ diff --git a/vcl/vcl_iomanip.h b/vcl/vcl_iomanip.h index 9bfbc80f6ba..a6a91930dfa 100644 --- a/vcl/vcl_iomanip.h +++ b/vcl/vcl_iomanip.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_iomanip_h_ diff --git a/vcl/vcl_ios.h b/vcl/vcl_ios.h index fd8426237fa..a2e995d92f5 100644 --- a/vcl/vcl_ios.h +++ b/vcl/vcl_ios.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_ios_h_ diff --git a/vcl/vcl_iosfwd.h b/vcl/vcl_iosfwd.h index 45d70dec0d4..31f0ba19774 100644 --- a/vcl/vcl_iosfwd.h +++ b/vcl/vcl_iosfwd.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_iosfwd_h_ diff --git a/vcl/vcl_iostream.h b/vcl/vcl_iostream.h index f24708f7bdd..565e681e163 100644 --- a/vcl/vcl_iostream.h +++ b/vcl/vcl_iostream.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_iostream_h_ diff --git a/vcl/vcl_istream.h b/vcl/vcl_istream.h index 1a0870d4b7b..024b10cade1 100644 --- a/vcl/vcl_istream.h +++ b/vcl/vcl_istream.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_istream_h_ diff --git a/vcl/vcl_iterator.h b/vcl/vcl_iterator.h index e73c08ce0a5..4ef0ff125ef 100644 --- a/vcl/vcl_iterator.h +++ b/vcl/vcl_iterator.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_iterator_h_ diff --git a/vcl/vcl_legacy_aliases.h b/vcl/vcl_legacy_aliases.h index f2df19e18f2..0568c1ab540 100644 --- a/vcl/vcl_legacy_aliases.h +++ b/vcl/vcl_legacy_aliases.h @@ -2,11 +2,11 @@ #define VCL_LEGACY_ALIASES_H_ #if !defined(VXL_LEGACY_FUTURE_REMOVE) -# define VXL_CONSTEXPR_FUNC constexpr //constexpr in C++11, empty in C++98 -# define VXL_CONSTEXPR_VAR constexpr //constexpr in C++11, empty in C++98 -# define VXL_FULLCXX11SUPPORT 1 -# define VCL_STATIC_CONST_INIT_FLOAT_DECL(x) = x -# define VCL_STATIC_CONST_INIT_FLOAT_DEFN(x) /* initialized at declaration */ +# define VXL_CONSTEXPR_FUNC constexpr // constexpr in C++11, empty in C++98 +# define VXL_CONSTEXPR_VAR constexpr // constexpr in C++11, empty in C++98 +# define VXL_FULLCXX11SUPPORT 1 +# define VCL_STATIC_CONST_INIT_FLOAT_DECL(x) = x +# define VCL_STATIC_CONST_INIT_FLOAT_DEFN(x) /* initialized at declaration */ #endif /* @@ -193,31 +193,33 @@ // Microsoft has finally implemented snprintf in Visual Studio 2015. On earlier // versions you can simulate it as below. #if defined(_MSC_VER) && _MSC_VER < 1900 -__inline int c99_vsnprintf(char *outBuf, size_t size, const char *format, va_list ap) +__inline int +c99_vsnprintf(char * outBuf, size_t size, const char * format, va_list ap) { - int count = -1; + int count = -1; - if (size != 0) - count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap); - if (count == -1) - count = _vscprintf(format, ap); + if (size != 0) + count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap); + if (count == -1) + count = _vscprintf(format, ap); - return count; + return count; } -__inline int vcl_snprintf(char *outBuf, size_t size, const char *format, ...) +__inline int +vcl_snprintf(char * outBuf, size_t size, const char * format, ...) { - int count; - va_list ap; + int count; + va_list ap; - va_start(ap, format); - count = c99_vsnprintf(outBuf, size, format, ap); - va_end(ap); + va_start(ap, format); + count = c99_vsnprintf(outBuf, size, format, ap); + va_end(ap); - return count; + return count; } #else -#define vcl_snprintf std::snprintf +# define vcl_snprintf std::snprintf #endif #define vcl_scanf std::scanf @@ -630,15 +632,15 @@ __inline int vcl_snprintf(char *outBuf, size_t size, const char *format, ...) #define vcl_indirect_array std::indirect_array #define vcl_vector std::vector -# define vcl_memory_prefix std +#define vcl_memory_prefix std -#define vcl_bad_weak_ptr std::bad_weak_ptr -#define vcl_shared_ptr std::shared_ptr -#define vcl_static_pointer_cast std::static_pointer_cast -#define vcl_dynamic_pointer_cast std::dynamic_pointer_cast -#define vcl_const_pointer_cast std::const_pointer_cast -#define vcl_get_deleter std::get_deleter -#define vcl_weak_ptr std::weak_ptr +#define vcl_bad_weak_ptr std::bad_weak_ptr +#define vcl_shared_ptr std::shared_ptr +#define vcl_static_pointer_cast std::static_pointer_cast +#define vcl_dynamic_pointer_cast std::dynamic_pointer_cast +#define vcl_const_pointer_cast std::const_pointer_cast +#define vcl_get_deleter std::get_deleter +#define vcl_weak_ptr std::weak_ptr #define vcl_enable_shared_from_this std::enable_shared_from_this #define vnl_math_isnan vnl_math::isnan @@ -661,4 +663,4 @@ __inline int vcl_snprintf(char *outBuf, size_t size, const char *format, ...) #define vnl_math_hypot vnl_math::hypot -#endif //VCL_LEGACY_ALIASES_H_ +#endif // VCL_LEGACY_ALIASES_H_ diff --git a/vcl/vcl_limits.h b/vcl/vcl_limits.h index 3fcb26ca190..206ba9b068f 100644 --- a/vcl/vcl_limits.h +++ b/vcl/vcl_limits.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_limits_h_ diff --git a/vcl/vcl_list.h b/vcl/vcl_list.h index 883642c17b2..2ac7ad84bdd 100644 --- a/vcl/vcl_list.h +++ b/vcl/vcl_list.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_list_h_ diff --git a/vcl/vcl_locale.h b/vcl/vcl_locale.h index 84c422a517b..9fc77c41353 100644 --- a/vcl/vcl_locale.h +++ b/vcl/vcl_locale.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_locale_h_ diff --git a/vcl/vcl_map.h b/vcl/vcl_map.h index 5ae268b802e..783ee6bea71 100644 --- a/vcl/vcl_map.h +++ b/vcl/vcl_map.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_map_h_ diff --git a/vcl/vcl_memory.h b/vcl/vcl_memory.h index 5414ce4ccf4..d957e7c187a 100644 --- a/vcl/vcl_memory.h +++ b/vcl/vcl_memory.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_memory_h_ diff --git a/vcl/vcl_msvc_warnings.h b/vcl/vcl_msvc_warnings.h index ba476a226a8..bf992fd9f5d 100644 --- a/vcl/vcl_msvc_warnings.h +++ b/vcl/vcl_msvc_warnings.h @@ -2,48 +2,48 @@ #define vcl_msvc_warnings_h__ /** Disable some common warnings in MS VC++ */ /* This is the set of warnings suppressed by ITK */ -#if defined( _MSC_VER ) +#if defined(_MSC_VER) // 'conversion' conversion from 'type1' to 'type2', possible loss of data -#pragma warning ( disable : 4244 ) +# pragma warning(disable : 4244) // 'identifier' : truncation from 'type1' to 'type2' -#pragma warning ( disable : 4305 ) +# pragma warning(disable : 4305) // 'conversion' : truncation of constant value -#pragma warning ( disable : 4309 ) +# pragma warning(disable : 4309) // decorated name length exceeded, name was truncated -#pragma warning ( disable : 4503 ) +# pragma warning(disable : 4503) // 'type' : forcing value to bool 'true' or 'false' (performance warning) -#pragma warning ( disable : 4800 ) +# pragma warning(disable : 4800) // 'identifier' : class 'type' needs to have dll-interface to be used by // clients of class 'type2' -#pragma warning ( disable : 4251 ) +# pragma warning(disable : 4251) // non dll-interface class 'type' used as base for dll-interface class 'type2' -#pragma warning ( disable : 4275 ) +# pragma warning(disable : 4275) // C++ exception specification ignored except to indicate a // function is not __declspec(nothrow) -#pragma warning ( disable : 4290 ) +# pragma warning(disable : 4290) // 'type' : inconsistent dll linkage. dllexport assumed. -#pragma warning ( disable : 4273 ) +# pragma warning(disable : 4273) // conditional expression is constant -#pragma warning ( disable : 4127 ) +# pragma warning(disable : 4127) // unreferenced local function has been removed -#pragma warning ( disable : 4505 ) +# pragma warning(disable : 4505) // 'identifier' : identifier was truncated to 'number' characters in the debug information -#pragma warning ( disable : 4786 ) +# pragma warning(disable : 4786) // data-conversion related to 'size_t' -#pragma warning ( disable : 4267 ) - +# pragma warning(disable : 4267) + #endif // _MSC_VER -#endif //vcl_msvc_warnings_h__ +#endif // vcl_msvc_warnings_h__ diff --git a/vcl/vcl_numeric.h b/vcl/vcl_numeric.h index fad4c176a66..58acf38859b 100644 --- a/vcl/vcl_numeric.h +++ b/vcl/vcl_numeric.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_numeric_h_ diff --git a/vcl/vcl_ostream.h b/vcl/vcl_ostream.h index 506f0bec596..cc02a1059f1 100644 --- a/vcl/vcl_ostream.h +++ b/vcl/vcl_ostream.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_ostream_h_ diff --git a/vcl/vcl_queue.h b/vcl/vcl_queue.h index 603c907b9b9..c8bf7eef851 100644 --- a/vcl/vcl_queue.h +++ b/vcl/vcl_queue.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_queue_h_ diff --git a/vcl/vcl_set.h b/vcl/vcl_set.h index 4984d599c0b..e17be56bc6d 100644 --- a/vcl/vcl_set.h +++ b/vcl/vcl_set.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_set_h_ diff --git a/vcl/vcl_sstream.h b/vcl/vcl_sstream.h index d22450d96f2..20b4066d2ef 100644 --- a/vcl/vcl_sstream.h +++ b/vcl/vcl_sstream.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_sstream_h_ diff --git a/vcl/vcl_stack.h b/vcl/vcl_stack.h index ce425b0dcb9..29f0feccedd 100644 --- a/vcl/vcl_stack.h +++ b/vcl/vcl_stack.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_stack_h_ diff --git a/vcl/vcl_stdexcept.h b/vcl/vcl_stdexcept.h index 6df19fa0750..db1d42e692c 100644 --- a/vcl/vcl_stdexcept.h +++ b/vcl/vcl_stdexcept.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_stdexcept_h_ diff --git a/vcl/vcl_stlfwd.h b/vcl/vcl_stlfwd.h index 640b6963694..e644f00fd6c 100644 --- a/vcl/vcl_stlfwd.h +++ b/vcl/vcl_stlfwd.h @@ -12,8 +12,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_stlfwd_h_ diff --git a/vcl/vcl_streambuf.h b/vcl/vcl_streambuf.h index 0747d3e288c..3662afcb9cb 100644 --- a/vcl/vcl_streambuf.h +++ b/vcl/vcl_streambuf.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_streambuf_h_ diff --git a/vcl/vcl_string.h b/vcl/vcl_string.h index 2db23fbef91..e6ff05f3954 100644 --- a/vcl/vcl_string.h +++ b/vcl/vcl_string.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_string_h_ diff --git a/vcl/vcl_sys/time.h b/vcl/vcl_sys/time.h index 0840b8c4325..e5d6a13c914 100644 --- a/vcl/vcl_sys/time.h +++ b/vcl/vcl_sys/time.h @@ -6,40 +6,43 @@ #endif #ifndef _WIN32 -#include +# include #endif #if defined(_WIN32) && !defined(__CYGWIN__) -# include -extern "C" int gettimeofday(struct timeval*, struct timezone*); +# include +extern "C" int +gettimeofday(struct timeval *, struct timezone *); #elif defined(__CYGWIN__) -# include -# include -# include +# include +# include +# include #elif defined(__GNUC__) && !defined(__INTEL_COMPILER) -# define __restrict /* */ -# include -# undef __restrict +# define __restrict /* */ +# include +# undef __restrict #elif !defined(VCL_NO_SYS_TIME_H) -# include +# include #elif defined(SYSV) -extern "C" int gettimeofday(struct timeval *tp); +extern "C" int +gettimeofday(struct timeval * tp); #else -extern "C" int gettimeofday(struct timeval*, struct timezone*); +extern "C" int +gettimeofday(struct timeval *, struct timezone *); #endif -//struct timeval: -// time_t tv_sec seconds -// suseconds_t tv_usec microseconds +// struct timeval: +// time_t tv_sec seconds +// suseconds_t tv_usec microseconds -//struct itimerval: -// struct timeval it_interval timer interval -// struct timeval it_value current value +// struct itimerval: +// struct timeval it_interval timer interval +// struct timeval it_value current value // int getitimer(int, struct itimerval *); // int setitimer(int, const struct itimerval *, struct itimerval *); diff --git a/vcl/vcl_typeinfo.h b/vcl/vcl_typeinfo.h index 365bc80ed3a..013950f8631 100644 --- a/vcl/vcl_typeinfo.h +++ b/vcl/vcl_typeinfo.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_typeinfo_h_ diff --git a/vcl/vcl_utility.h b/vcl/vcl_utility.h index cb8036cbf01..79e6b71c184 100644 --- a/vcl/vcl_utility.h +++ b/vcl/vcl_utility.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_utility_h_ diff --git a/vcl/vcl_valarray.h b/vcl/vcl_valarray.h index 9f34bd59f56..ad91457265c 100644 --- a/vcl/vcl_valarray.h +++ b/vcl/vcl_valarray.h @@ -6,8 +6,9 @@ # include #endif #if VXL_LEGACY_FUTURE_REMOVE - # error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# error "Deprecated. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #else - # warning "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" +# warning \ + "This header will be removed in future versions of VXL. Use equivalent C++11 header instead. see: vxl/scripts/UseStandardHeaders.py" #endif #endif // vcl_valarray_h_ diff --git a/vcl/vcl_windows_header.h b/vcl/vcl_windows_header.h index c57f16dd66b..758c7e0bead 100644 --- a/vcl/vcl_windows_header.h +++ b/vcl/vcl_windows_header.h @@ -1,19 +1,22 @@ #ifndef __vcl_windows_header_h__ #define __vcl_windows_header_h__ /** Disable some common warnings in MS VC++ */ -#if defined( _MSC_VER ) -# pragma warning ( disable : 4244 ) // 'conversion' conversion from 'type1' to 'type2', possible loss of data -# pragma warning ( disable : 4305 ) // 'identifier' : truncation from 'type1' to 'type2' -# pragma warning ( disable : 4309 ) // 'conversion' : truncation of constant value -# pragma warning ( disable : 4503 ) // decorated name length exceeded, name was truncated -# pragma warning ( disable : 4800 ) // 'type' : forcing value to bool 'true' or 'false' (performance warning) -# pragma warning ( disable : 4251 ) // 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' -# pragma warning ( disable : 4275 ) // non dll-interface class 'type' used as base for dll-interface class 'type2' -# pragma warning ( disable : 4290 ) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) -# pragma warning ( disable : 4273 ) // 'type' : inconsistent dll linkage. dllexport assumed. -# pragma warning ( disable : 4127 ) // conditional expression is constant -# pragma warning ( disable : 4505 ) // unreferenced local function has been removed -# pragma warning ( disable : 4786 ) // 'identifier' : identifier was truncated to 'number' characters in the debug information -# pragma warning ( disable : 4267 ) // data-conversion related to 'size_t' -# endif // _MSC_VER -#endif // __vcl_windows_header_h__ +#if defined(_MSC_VER) +# pragma warning(disable : 4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data +# pragma warning(disable : 4305) // 'identifier' : truncation from 'type1' to 'type2' +# pragma warning(disable : 4309) // 'conversion' : truncation of constant value +# pragma warning(disable : 4503) // decorated name length exceeded, name was truncated +# pragma warning(disable : 4800) // 'type' : forcing value to bool 'true' or 'false' (performance warning) +# pragma warning( \ + disable : 4251) // 'identifier' : class 'type' needs to have dll-interface to be used by clients of class 'type2' +# pragma warning(disable : 4275) // non dll-interface class 'type' used as base for dll-interface class 'type2' +# pragma warning( \ + disable : 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +# pragma warning(disable : 4273) // 'type' : inconsistent dll linkage. dllexport assumed. +# pragma warning(disable : 4127) // conditional expression is constant +# pragma warning(disable : 4505) // unreferenced local function has been removed +# pragma warning( \ + disable : 4786) // 'identifier' : identifier was truncated to 'number' characters in the debug information +# pragma warning(disable : 4267) // data-conversion related to 'size_t' +#endif // _MSC_VER +#endif // __vcl_windows_header_h__