compressed_row_sparse_matrix_test.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2023 Google Inc. All rights reserved.
  3. // http://ceres-solver.org/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Google Inc. nor the names of its contributors may be
  14. // used to endorse or promote products derived from this software without
  15. // specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. // POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Author: sameeragarwal@google.com (Sameer Agarwal)
  30. #include "ceres/compressed_row_sparse_matrix.h"
  31. #include <algorithm>
  32. #include <memory>
  33. #include <numeric>
  34. #include <random>
  35. #include <string>
  36. #include <vector>
  37. #include "Eigen/SparseCore"
  38. #include "ceres/casts.h"
  39. #include "ceres/context_impl.h"
  40. #include "ceres/crs_matrix.h"
  41. #include "ceres/internal/eigen.h"
  42. #include "ceres/linear_least_squares_problems.h"
  43. #include "ceres/triplet_sparse_matrix.h"
  44. #include "glog/logging.h"
  45. #include "gtest/gtest.h"
  46. namespace ceres::internal {
  47. static void CompareMatrices(const SparseMatrix* a, const SparseMatrix* b) {
  48. EXPECT_EQ(a->num_rows(), b->num_rows());
  49. EXPECT_EQ(a->num_cols(), b->num_cols());
  50. int num_rows = a->num_rows();
  51. int num_cols = a->num_cols();
  52. for (int i = 0; i < num_cols; ++i) {
  53. Vector x = Vector::Zero(num_cols);
  54. x(i) = 1.0;
  55. Vector y_a = Vector::Zero(num_rows);
  56. Vector y_b = Vector::Zero(num_rows);
  57. a->RightMultiplyAndAccumulate(x.data(), y_a.data());
  58. b->RightMultiplyAndAccumulate(x.data(), y_b.data());
  59. EXPECT_EQ((y_a - y_b).norm(), 0);
  60. }
  61. }
  62. class CompressedRowSparseMatrixTest : public ::testing::Test {
  63. protected:
  64. void SetUp() final {
  65. auto problem = CreateLinearLeastSquaresProblemFromId(1);
  66. CHECK(problem != nullptr);
  67. tsm.reset(down_cast<TripletSparseMatrix*>(problem->A.release()));
  68. crsm = CompressedRowSparseMatrix::FromTripletSparseMatrix(*tsm);
  69. num_rows = tsm->num_rows();
  70. num_cols = tsm->num_cols();
  71. std::vector<Block>* row_blocks = crsm->mutable_row_blocks();
  72. row_blocks->resize(num_rows);
  73. for (int i = 0; i < row_blocks->size(); ++i) {
  74. (*row_blocks)[i] = Block(1, i);
  75. }
  76. std::vector<Block>* col_blocks = crsm->mutable_col_blocks();
  77. col_blocks->resize(num_cols);
  78. for (int i = 0; i < col_blocks->size(); ++i) {
  79. (*col_blocks)[i] = Block(1, i);
  80. }
  81. }
  82. int num_rows;
  83. int num_cols;
  84. std::unique_ptr<TripletSparseMatrix> tsm;
  85. std::unique_ptr<CompressedRowSparseMatrix> crsm;
  86. };
  87. TEST_F(CompressedRowSparseMatrixTest, Scale) {
  88. Vector scale(num_cols);
  89. for (int i = 0; i < num_cols; ++i) {
  90. scale(i) = i + 1;
  91. }
  92. tsm->ScaleColumns(scale.data());
  93. crsm->ScaleColumns(scale.data());
  94. CompareMatrices(tsm.get(), crsm.get());
  95. }
  96. TEST_F(CompressedRowSparseMatrixTest, DeleteRows) {
  97. // Clear the row and column blocks as these are purely scalar tests.
  98. crsm->mutable_row_blocks()->clear();
  99. crsm->mutable_col_blocks()->clear();
  100. for (int i = 0; i < num_rows; ++i) {
  101. tsm->Resize(num_rows - i, num_cols);
  102. crsm->DeleteRows(crsm->num_rows() - tsm->num_rows());
  103. CompareMatrices(tsm.get(), crsm.get());
  104. }
  105. }
  106. TEST_F(CompressedRowSparseMatrixTest, AppendRows) {
  107. // Clear the row and column blocks as these are purely scalar tests.
  108. crsm->mutable_row_blocks()->clear();
  109. crsm->mutable_col_blocks()->clear();
  110. for (int i = 0; i < num_rows; ++i) {
  111. TripletSparseMatrix tsm_appendage(*tsm);
  112. tsm_appendage.Resize(i, num_cols);
  113. tsm->AppendRows(tsm_appendage);
  114. auto crsm_appendage =
  115. CompressedRowSparseMatrix::FromTripletSparseMatrix(tsm_appendage);
  116. crsm->AppendRows(*crsm_appendage);
  117. CompareMatrices(tsm.get(), crsm.get());
  118. }
  119. }
  120. TEST_F(CompressedRowSparseMatrixTest, AppendAndDeleteBlockDiagonalMatrix) {
  121. int num_diagonal_rows = crsm->num_cols();
  122. auto diagonal = std::make_unique<double[]>(num_diagonal_rows);
  123. for (int i = 0; i < num_diagonal_rows; ++i) {
  124. diagonal[i] = i;
  125. }
  126. std::vector<Block> row_and_column_blocks;
  127. row_and_column_blocks.emplace_back(1, 0);
  128. row_and_column_blocks.emplace_back(2, 1);
  129. row_and_column_blocks.emplace_back(2, 3);
  130. const std::vector<Block> pre_row_blocks = crsm->row_blocks();
  131. const std::vector<Block> pre_col_blocks = crsm->col_blocks();
  132. auto appendage = CompressedRowSparseMatrix::CreateBlockDiagonalMatrix(
  133. diagonal.get(), row_and_column_blocks);
  134. crsm->AppendRows(*appendage);
  135. const std::vector<Block> post_row_blocks = crsm->row_blocks();
  136. const std::vector<Block> post_col_blocks = crsm->col_blocks();
  137. std::vector<Block> expected_row_blocks = pre_row_blocks;
  138. expected_row_blocks.insert(expected_row_blocks.end(),
  139. row_and_column_blocks.begin(),
  140. row_and_column_blocks.end());
  141. std::vector<Block> expected_col_blocks = pre_col_blocks;
  142. EXPECT_EQ(expected_row_blocks, crsm->row_blocks());
  143. EXPECT_EQ(expected_col_blocks, crsm->col_blocks());
  144. crsm->DeleteRows(num_diagonal_rows);
  145. EXPECT_EQ(crsm->row_blocks(), pre_row_blocks);
  146. EXPECT_EQ(crsm->col_blocks(), pre_col_blocks);
  147. }
  148. TEST_F(CompressedRowSparseMatrixTest, ToDenseMatrix) {
  149. Matrix tsm_dense;
  150. Matrix crsm_dense;
  151. tsm->ToDenseMatrix(&tsm_dense);
  152. crsm->ToDenseMatrix(&crsm_dense);
  153. EXPECT_EQ((tsm_dense - crsm_dense).norm(), 0.0);
  154. }
  155. TEST_F(CompressedRowSparseMatrixTest, ToCRSMatrix) {
  156. CRSMatrix crs_matrix;
  157. crsm->ToCRSMatrix(&crs_matrix);
  158. EXPECT_EQ(crsm->num_rows(), crs_matrix.num_rows);
  159. EXPECT_EQ(crsm->num_cols(), crs_matrix.num_cols);
  160. EXPECT_EQ(crsm->num_rows() + 1, crs_matrix.rows.size());
  161. EXPECT_EQ(crsm->num_nonzeros(), crs_matrix.cols.size());
  162. EXPECT_EQ(crsm->num_nonzeros(), crs_matrix.values.size());
  163. for (int i = 0; i < crsm->num_rows() + 1; ++i) {
  164. EXPECT_EQ(crsm->rows()[i], crs_matrix.rows[i]);
  165. }
  166. for (int i = 0; i < crsm->num_nonzeros(); ++i) {
  167. EXPECT_EQ(crsm->cols()[i], crs_matrix.cols[i]);
  168. EXPECT_EQ(crsm->values()[i], crs_matrix.values[i]);
  169. }
  170. }
  171. TEST(CompressedRowSparseMatrix, CreateBlockDiagonalMatrix) {
  172. std::vector<Block> blocks;
  173. blocks.emplace_back(1, 0);
  174. blocks.emplace_back(2, 1);
  175. blocks.emplace_back(2, 3);
  176. Vector diagonal(5);
  177. for (int i = 0; i < 5; ++i) {
  178. diagonal(i) = i + 1;
  179. }
  180. auto matrix = CompressedRowSparseMatrix::CreateBlockDiagonalMatrix(
  181. diagonal.data(), blocks);
  182. EXPECT_EQ(matrix->num_rows(), 5);
  183. EXPECT_EQ(matrix->num_cols(), 5);
  184. EXPECT_EQ(matrix->num_nonzeros(), 9);
  185. EXPECT_EQ(blocks, matrix->row_blocks());
  186. EXPECT_EQ(blocks, matrix->col_blocks());
  187. Vector x(5);
  188. Vector y(5);
  189. x.setOnes();
  190. y.setZero();
  191. matrix->RightMultiplyAndAccumulate(x.data(), y.data());
  192. for (int i = 0; i < diagonal.size(); ++i) {
  193. EXPECT_EQ(y[i], diagonal[i]);
  194. }
  195. y.setZero();
  196. matrix->LeftMultiplyAndAccumulate(x.data(), y.data());
  197. for (int i = 0; i < diagonal.size(); ++i) {
  198. EXPECT_EQ(y[i], diagonal[i]);
  199. }
  200. Matrix dense;
  201. matrix->ToDenseMatrix(&dense);
  202. EXPECT_EQ((dense.diagonal() - diagonal).norm(), 0.0);
  203. }
  204. TEST(CompressedRowSparseMatrix, Transpose) {
  205. // 0 1 0 2 3 0
  206. // 4 5 6 0 0 7
  207. // 8 9 0 10 11 0
  208. // 12 0 13 14 15 0
  209. // 0 16 17 0 0 0
  210. // Block structure:
  211. // A A A A B B
  212. // A A A A B B
  213. // A A A A B B
  214. // C C C C D D
  215. // C C C C D D
  216. // C C C C D D
  217. CompressedRowSparseMatrix matrix(5, 6, 30);
  218. int* rows = matrix.mutable_rows();
  219. int* cols = matrix.mutable_cols();
  220. double* values = matrix.mutable_values();
  221. matrix.mutable_row_blocks()->emplace_back(3, 0);
  222. matrix.mutable_row_blocks()->emplace_back(3, 3);
  223. matrix.mutable_col_blocks()->emplace_back(4, 0);
  224. matrix.mutable_col_blocks()->emplace_back(2, 4);
  225. rows[0] = 0;
  226. cols[0] = 1;
  227. cols[1] = 3;
  228. cols[2] = 4;
  229. rows[1] = 3;
  230. cols[3] = 0;
  231. cols[4] = 1;
  232. cols[5] = 2;
  233. cols[6] = 5;
  234. rows[2] = 7;
  235. cols[7] = 0;
  236. cols[8] = 1;
  237. cols[9] = 3;
  238. cols[10] = 4;
  239. rows[3] = 11;
  240. cols[11] = 0;
  241. cols[12] = 2;
  242. cols[13] = 3;
  243. cols[14] = 4;
  244. rows[4] = 15;
  245. cols[15] = 1;
  246. cols[16] = 2;
  247. rows[5] = 17;
  248. std::iota(values, values + 17, 1);
  249. auto transpose = matrix.Transpose();
  250. ASSERT_EQ(transpose->row_blocks().size(), matrix.col_blocks().size());
  251. for (int i = 0; i < transpose->row_blocks().size(); ++i) {
  252. EXPECT_EQ(transpose->row_blocks()[i], matrix.col_blocks()[i]);
  253. }
  254. ASSERT_EQ(transpose->col_blocks().size(), matrix.row_blocks().size());
  255. for (int i = 0; i < transpose->col_blocks().size(); ++i) {
  256. EXPECT_EQ(transpose->col_blocks()[i], matrix.row_blocks()[i]);
  257. }
  258. Matrix dense_matrix;
  259. matrix.ToDenseMatrix(&dense_matrix);
  260. Matrix dense_transpose;
  261. transpose->ToDenseMatrix(&dense_transpose);
  262. EXPECT_NEAR((dense_matrix - dense_transpose.transpose()).norm(), 0.0, 1e-14);
  263. }
  264. TEST(CompressedRowSparseMatrix, FromTripletSparseMatrix) {
  265. std::mt19937 prng;
  266. TripletSparseMatrix::RandomMatrixOptions options;
  267. options.num_rows = 5;
  268. options.num_cols = 7;
  269. options.density = 0.5;
  270. const int kNumTrials = 10;
  271. for (int i = 0; i < kNumTrials; ++i) {
  272. auto tsm = TripletSparseMatrix::CreateRandomMatrix(options, prng);
  273. auto crsm = CompressedRowSparseMatrix::FromTripletSparseMatrix(*tsm);
  274. Matrix expected;
  275. tsm->ToDenseMatrix(&expected);
  276. Matrix actual;
  277. crsm->ToDenseMatrix(&actual);
  278. EXPECT_NEAR((expected - actual).norm() / actual.norm(),
  279. 0.0,
  280. std::numeric_limits<double>::epsilon())
  281. << "\nexpected: \n"
  282. << expected << "\nactual: \n"
  283. << actual;
  284. }
  285. }
  286. TEST(CompressedRowSparseMatrix, FromTripletSparseMatrixTransposed) {
  287. std::mt19937 prng;
  288. TripletSparseMatrix::RandomMatrixOptions options;
  289. options.num_rows = 5;
  290. options.num_cols = 7;
  291. options.density = 0.5;
  292. const int kNumTrials = 10;
  293. for (int i = 0; i < kNumTrials; ++i) {
  294. auto tsm = TripletSparseMatrix::CreateRandomMatrix(options, prng);
  295. auto crsm =
  296. CompressedRowSparseMatrix::FromTripletSparseMatrixTransposed(*tsm);
  297. Matrix tmp;
  298. tsm->ToDenseMatrix(&tmp);
  299. Matrix expected = tmp.transpose();
  300. Matrix actual;
  301. crsm->ToDenseMatrix(&actual);
  302. EXPECT_NEAR((expected - actual).norm() / actual.norm(),
  303. 0.0,
  304. std::numeric_limits<double>::epsilon())
  305. << "\nexpected: \n"
  306. << expected << "\nactual: \n"
  307. << actual;
  308. }
  309. }
  310. using Param = ::testing::tuple<CompressedRowSparseMatrix::StorageType>;
  311. static std::string ParamInfoToString(testing::TestParamInfo<Param> info) {
  312. if (::testing::get<0>(info.param) ==
  313. CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
  314. return "UPPER";
  315. }
  316. if (::testing::get<0>(info.param) ==
  317. CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
  318. return "LOWER";
  319. }
  320. return "UNSYMMETRIC";
  321. }
  322. class RightMultiplyAndAccumulateTest : public ::testing::TestWithParam<Param> {
  323. };
  324. TEST_P(RightMultiplyAndAccumulateTest, _) {
  325. const int kMinNumBlocks = 1;
  326. const int kMaxNumBlocks = 10;
  327. const int kMinBlockSize = 1;
  328. const int kMaxBlockSize = 5;
  329. const int kNumTrials = 10;
  330. std::mt19937 prng;
  331. std::uniform_real_distribution<double> uniform(0.5, 1.0);
  332. for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
  333. ++num_blocks) {
  334. for (int trial = 0; trial < kNumTrials; ++trial) {
  335. Param param = GetParam();
  336. CompressedRowSparseMatrix::RandomMatrixOptions options;
  337. options.num_col_blocks = num_blocks;
  338. options.min_col_block_size = kMinBlockSize;
  339. options.max_col_block_size = kMaxBlockSize;
  340. options.num_row_blocks = 2 * num_blocks;
  341. options.min_row_block_size = kMinBlockSize;
  342. options.max_row_block_size = kMaxBlockSize;
  343. options.block_density = uniform(prng);
  344. options.storage_type = ::testing::get<0>(param);
  345. auto matrix =
  346. CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
  347. const int num_rows = matrix->num_rows();
  348. const int num_cols = matrix->num_cols();
  349. Vector x(num_cols);
  350. x.setRandom();
  351. Vector actual_y(num_rows);
  352. actual_y.setZero();
  353. matrix->RightMultiplyAndAccumulate(x.data(), actual_y.data());
  354. Matrix dense;
  355. matrix->ToDenseMatrix(&dense);
  356. Vector expected_y;
  357. if (::testing::get<0>(param) ==
  358. CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
  359. expected_y = dense.selfadjointView<Eigen::Upper>() * x;
  360. } else if (::testing::get<0>(param) ==
  361. CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
  362. expected_y = dense.selfadjointView<Eigen::Lower>() * x;
  363. } else {
  364. expected_y = dense * x;
  365. }
  366. ASSERT_NEAR((expected_y - actual_y).norm() / actual_y.norm(),
  367. 0.0,
  368. std::numeric_limits<double>::epsilon() * 10)
  369. << "\n"
  370. << dense << "x:\n"
  371. << x.transpose() << "\n"
  372. << "expected: \n"
  373. << expected_y.transpose() << "\n"
  374. << "actual: \n"
  375. << actual_y.transpose();
  376. }
  377. }
  378. }
  379. INSTANTIATE_TEST_SUITE_P(
  380. CompressedRowSparseMatrix,
  381. RightMultiplyAndAccumulateTest,
  382. ::testing::Values(CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR,
  383. CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR,
  384. CompressedRowSparseMatrix::StorageType::UNSYMMETRIC),
  385. ParamInfoToString);
  386. class LeftMultiplyAndAccumulateTest : public ::testing::TestWithParam<Param> {};
  387. TEST_P(LeftMultiplyAndAccumulateTest, _) {
  388. const int kMinNumBlocks = 1;
  389. const int kMaxNumBlocks = 10;
  390. const int kMinBlockSize = 1;
  391. const int kMaxBlockSize = 5;
  392. const int kNumTrials = 10;
  393. std::mt19937 prng;
  394. std::uniform_real_distribution<double> uniform(0.5, 1.0);
  395. for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
  396. ++num_blocks) {
  397. for (int trial = 0; trial < kNumTrials; ++trial) {
  398. Param param = GetParam();
  399. CompressedRowSparseMatrix::RandomMatrixOptions options;
  400. options.num_col_blocks = num_blocks;
  401. options.min_col_block_size = kMinBlockSize;
  402. options.max_col_block_size = kMaxBlockSize;
  403. options.num_row_blocks = 2 * num_blocks;
  404. options.min_row_block_size = kMinBlockSize;
  405. options.max_row_block_size = kMaxBlockSize;
  406. options.block_density = uniform(prng);
  407. options.storage_type = ::testing::get<0>(param);
  408. auto matrix =
  409. CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
  410. const int num_rows = matrix->num_rows();
  411. const int num_cols = matrix->num_cols();
  412. Vector x(num_rows);
  413. x.setRandom();
  414. Vector actual_y(num_cols);
  415. actual_y.setZero();
  416. matrix->LeftMultiplyAndAccumulate(x.data(), actual_y.data());
  417. Matrix dense;
  418. matrix->ToDenseMatrix(&dense);
  419. Vector expected_y;
  420. if (::testing::get<0>(param) ==
  421. CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
  422. expected_y = dense.selfadjointView<Eigen::Upper>() * x;
  423. } else if (::testing::get<0>(param) ==
  424. CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
  425. expected_y = dense.selfadjointView<Eigen::Lower>() * x;
  426. } else {
  427. expected_y = dense.transpose() * x;
  428. }
  429. ASSERT_NEAR((expected_y - actual_y).norm() / actual_y.norm(),
  430. 0.0,
  431. std::numeric_limits<double>::epsilon() * 10)
  432. << "\n"
  433. << dense << "x\n"
  434. << x.transpose() << "\n"
  435. << "expected: \n"
  436. << expected_y.transpose() << "\n"
  437. << "actual: \n"
  438. << actual_y.transpose();
  439. }
  440. }
  441. }
  442. INSTANTIATE_TEST_SUITE_P(
  443. CompressedRowSparseMatrix,
  444. LeftMultiplyAndAccumulateTest,
  445. ::testing::Values(CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR,
  446. CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR,
  447. CompressedRowSparseMatrix::StorageType::UNSYMMETRIC),
  448. ParamInfoToString);
  449. class SquaredColumnNormTest : public ::testing::TestWithParam<Param> {};
  450. TEST_P(SquaredColumnNormTest, _) {
  451. const int kMinNumBlocks = 1;
  452. const int kMaxNumBlocks = 10;
  453. const int kMinBlockSize = 1;
  454. const int kMaxBlockSize = 5;
  455. const int kNumTrials = 10;
  456. std::mt19937 prng;
  457. std::uniform_real_distribution<double> uniform(0.5, 1.0);
  458. for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
  459. ++num_blocks) {
  460. for (int trial = 0; trial < kNumTrials; ++trial) {
  461. Param param = GetParam();
  462. CompressedRowSparseMatrix::RandomMatrixOptions options;
  463. options.num_col_blocks = num_blocks;
  464. options.min_col_block_size = kMinBlockSize;
  465. options.max_col_block_size = kMaxBlockSize;
  466. options.num_row_blocks = 2 * num_blocks;
  467. options.min_row_block_size = kMinBlockSize;
  468. options.max_row_block_size = kMaxBlockSize;
  469. options.block_density = uniform(prng);
  470. options.storage_type = ::testing::get<0>(param);
  471. auto matrix =
  472. CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
  473. const int num_cols = matrix->num_cols();
  474. Vector actual(num_cols);
  475. actual.setZero();
  476. matrix->SquaredColumnNorm(actual.data());
  477. Matrix dense;
  478. matrix->ToDenseMatrix(&dense);
  479. Vector expected;
  480. if (::testing::get<0>(param) ==
  481. CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
  482. const Matrix full = dense.selfadjointView<Eigen::Upper>();
  483. expected = full.colwise().squaredNorm();
  484. } else if (::testing::get<0>(param) ==
  485. CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR) {
  486. const Matrix full = dense.selfadjointView<Eigen::Lower>();
  487. expected = full.colwise().squaredNorm();
  488. } else {
  489. expected = dense.colwise().squaredNorm();
  490. }
  491. ASSERT_NEAR((expected - actual).norm() / actual.norm(),
  492. 0.0,
  493. std::numeric_limits<double>::epsilon() * 10)
  494. << "\n"
  495. << dense << "expected: \n"
  496. << expected.transpose() << "\n"
  497. << "actual: \n"
  498. << actual.transpose();
  499. }
  500. }
  501. }
  502. INSTANTIATE_TEST_SUITE_P(
  503. CompressedRowSparseMatrix,
  504. SquaredColumnNormTest,
  505. ::testing::Values(CompressedRowSparseMatrix::StorageType::LOWER_TRIANGULAR,
  506. CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR,
  507. CompressedRowSparseMatrix::StorageType::UNSYMMETRIC),
  508. ParamInfoToString);
  509. const int kMaxNumThreads = 8;
  510. class CompressedRowSparseMatrixParallelTest
  511. : public ::testing::TestWithParam<int> {
  512. void SetUp() final { context_.EnsureMinimumThreads(kMaxNumThreads); }
  513. protected:
  514. ContextImpl context_;
  515. };
  516. TEST_P(CompressedRowSparseMatrixParallelTest,
  517. RightMultiplyAndAccumulateUnsymmetric) {
  518. const int kMinNumBlocks = 1;
  519. const int kMaxNumBlocks = 10;
  520. const int kMinBlockSize = 1;
  521. const int kMaxBlockSize = 5;
  522. const int kNumTrials = 10;
  523. const int kNumThreads = GetParam();
  524. std::mt19937 prng;
  525. std::uniform_real_distribution<double> uniform(0.5, 1.0);
  526. for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
  527. ++num_blocks) {
  528. for (int trial = 0; trial < kNumTrials; ++trial) {
  529. CompressedRowSparseMatrix::RandomMatrixOptions options;
  530. options.num_col_blocks = num_blocks;
  531. options.min_col_block_size = kMinBlockSize;
  532. options.max_col_block_size = kMaxBlockSize;
  533. options.num_row_blocks = 2 * num_blocks;
  534. options.min_row_block_size = kMinBlockSize;
  535. options.max_row_block_size = kMaxBlockSize;
  536. options.block_density = uniform(prng);
  537. options.storage_type =
  538. CompressedRowSparseMatrix::StorageType::UNSYMMETRIC;
  539. auto matrix =
  540. CompressedRowSparseMatrix::CreateRandomMatrix(options, prng);
  541. const int num_rows = matrix->num_rows();
  542. const int num_cols = matrix->num_cols();
  543. Vector x(num_cols);
  544. x.setRandom();
  545. Vector actual_y(num_rows);
  546. actual_y.setZero();
  547. matrix->RightMultiplyAndAccumulate(
  548. x.data(), actual_y.data(), &context_, kNumThreads);
  549. Matrix dense;
  550. matrix->ToDenseMatrix(&dense);
  551. Vector expected_y = dense * x;
  552. ASSERT_NEAR((expected_y - actual_y).norm() / actual_y.norm(),
  553. 0.0,
  554. std::numeric_limits<double>::epsilon() * 10)
  555. << "\n"
  556. << dense << "x:\n"
  557. << x.transpose() << "\n"
  558. << "expected: \n"
  559. << expected_y.transpose() << "\n"
  560. << "actual: \n"
  561. << actual_y.transpose();
  562. }
  563. }
  564. }
  565. INSTANTIATE_TEST_SUITE_P(ParallelProducts,
  566. CompressedRowSparseMatrixParallelTest,
  567. ::testing::Values(1, 2, 4, 8),
  568. ::testing::PrintToStringParamName());
  569. // TODO(sameeragarwal) Add tests for the random matrix creation methods.
  570. } // namespace ceres::internal