triplet_sparse_matrix.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2022 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/triplet_sparse_matrix.h"
  31. #include <algorithm>
  32. #include <memory>
  33. #include <random>
  34. #include "ceres/compressed_row_sparse_matrix.h"
  35. #include "ceres/crs_matrix.h"
  36. #include "ceres/internal/eigen.h"
  37. #include "ceres/internal/export.h"
  38. #include "ceres/types.h"
  39. #include "glog/logging.h"
  40. namespace ceres::internal {
  41. TripletSparseMatrix::TripletSparseMatrix()
  42. : num_rows_(0), num_cols_(0), max_num_nonzeros_(0), num_nonzeros_(0) {}
  43. TripletSparseMatrix::~TripletSparseMatrix() = default;
  44. TripletSparseMatrix::TripletSparseMatrix(int num_rows,
  45. int num_cols,
  46. int max_num_nonzeros)
  47. : num_rows_(num_rows),
  48. num_cols_(num_cols),
  49. max_num_nonzeros_(max_num_nonzeros),
  50. num_nonzeros_(0) {
  51. // All the sizes should at least be zero
  52. CHECK_GE(num_rows, 0);
  53. CHECK_GE(num_cols, 0);
  54. CHECK_GE(max_num_nonzeros, 0);
  55. AllocateMemory();
  56. }
  57. TripletSparseMatrix::TripletSparseMatrix(const int num_rows,
  58. const int num_cols,
  59. const std::vector<int>& rows,
  60. const std::vector<int>& cols,
  61. const std::vector<double>& values)
  62. : num_rows_(num_rows),
  63. num_cols_(num_cols),
  64. max_num_nonzeros_(values.size()),
  65. num_nonzeros_(values.size()) {
  66. // All the sizes should at least be zero
  67. CHECK_GE(num_rows, 0);
  68. CHECK_GE(num_cols, 0);
  69. CHECK_EQ(rows.size(), cols.size());
  70. CHECK_EQ(rows.size(), values.size());
  71. AllocateMemory();
  72. std::copy(rows.begin(), rows.end(), rows_.get());
  73. std::copy(cols.begin(), cols.end(), cols_.get());
  74. std::copy(values.begin(), values.end(), values_.get());
  75. }
  76. TripletSparseMatrix::TripletSparseMatrix(const TripletSparseMatrix& orig)
  77. : SparseMatrix(),
  78. num_rows_(orig.num_rows_),
  79. num_cols_(orig.num_cols_),
  80. max_num_nonzeros_(orig.max_num_nonzeros_),
  81. num_nonzeros_(orig.num_nonzeros_) {
  82. AllocateMemory();
  83. CopyData(orig);
  84. }
  85. TripletSparseMatrix& TripletSparseMatrix::operator=(
  86. const TripletSparseMatrix& rhs) {
  87. if (this == &rhs) {
  88. return *this;
  89. }
  90. num_rows_ = rhs.num_rows_;
  91. num_cols_ = rhs.num_cols_;
  92. num_nonzeros_ = rhs.num_nonzeros_;
  93. max_num_nonzeros_ = rhs.max_num_nonzeros_;
  94. AllocateMemory();
  95. CopyData(rhs);
  96. return *this;
  97. }
  98. bool TripletSparseMatrix::AllTripletsWithinBounds() const {
  99. for (int i = 0; i < num_nonzeros_; ++i) {
  100. // clang-format off
  101. if ((rows_[i] < 0) || (rows_[i] >= num_rows_) ||
  102. (cols_[i] < 0) || (cols_[i] >= num_cols_)) {
  103. return false;
  104. }
  105. // clang-format on
  106. }
  107. return true;
  108. }
  109. void TripletSparseMatrix::Reserve(int new_max_num_nonzeros) {
  110. CHECK_LE(num_nonzeros_, new_max_num_nonzeros)
  111. << "Reallocation will cause data loss";
  112. // Nothing to do if we have enough space already.
  113. if (new_max_num_nonzeros <= max_num_nonzeros_) return;
  114. std::unique_ptr<int[]> new_rows =
  115. std::make_unique<int[]>(new_max_num_nonzeros);
  116. std::unique_ptr<int[]> new_cols =
  117. std::make_unique<int[]>(new_max_num_nonzeros);
  118. std::unique_ptr<double[]> new_values =
  119. std::make_unique<double[]>(new_max_num_nonzeros);
  120. for (int i = 0; i < num_nonzeros_; ++i) {
  121. new_rows[i] = rows_[i];
  122. new_cols[i] = cols_[i];
  123. new_values[i] = values_[i];
  124. }
  125. rows_ = std::move(new_rows);
  126. cols_ = std::move(new_cols);
  127. values_ = std::move(new_values);
  128. max_num_nonzeros_ = new_max_num_nonzeros;
  129. }
  130. void TripletSparseMatrix::SetZero() {
  131. std::fill(values_.get(), values_.get() + max_num_nonzeros_, 0.0);
  132. num_nonzeros_ = 0;
  133. }
  134. void TripletSparseMatrix::set_num_nonzeros(int num_nonzeros) {
  135. CHECK_GE(num_nonzeros, 0);
  136. CHECK_LE(num_nonzeros, max_num_nonzeros_);
  137. num_nonzeros_ = num_nonzeros;
  138. }
  139. void TripletSparseMatrix::AllocateMemory() {
  140. rows_ = std::make_unique<int[]>(max_num_nonzeros_);
  141. cols_ = std::make_unique<int[]>(max_num_nonzeros_);
  142. values_ = std::make_unique<double[]>(max_num_nonzeros_);
  143. }
  144. void TripletSparseMatrix::CopyData(const TripletSparseMatrix& orig) {
  145. for (int i = 0; i < num_nonzeros_; ++i) {
  146. rows_[i] = orig.rows_[i];
  147. cols_[i] = orig.cols_[i];
  148. values_[i] = orig.values_[i];
  149. }
  150. }
  151. void TripletSparseMatrix::RightMultiplyAndAccumulate(const double* x,
  152. double* y) const {
  153. for (int i = 0; i < num_nonzeros_; ++i) {
  154. y[rows_[i]] += values_[i] * x[cols_[i]];
  155. }
  156. }
  157. void TripletSparseMatrix::LeftMultiplyAndAccumulate(const double* x,
  158. double* y) const {
  159. for (int i = 0; i < num_nonzeros_; ++i) {
  160. y[cols_[i]] += values_[i] * x[rows_[i]];
  161. }
  162. }
  163. void TripletSparseMatrix::SquaredColumnNorm(double* x) const {
  164. CHECK(x != nullptr);
  165. VectorRef(x, num_cols_).setZero();
  166. for (int i = 0; i < num_nonzeros_; ++i) {
  167. x[cols_[i]] += values_[i] * values_[i];
  168. }
  169. }
  170. void TripletSparseMatrix::ScaleColumns(const double* scale) {
  171. CHECK(scale != nullptr);
  172. for (int i = 0; i < num_nonzeros_; ++i) {
  173. values_[i] = values_[i] * scale[cols_[i]];
  174. }
  175. }
  176. void TripletSparseMatrix::ToCRSMatrix(CRSMatrix* crs_matrix) const {
  177. CompressedRowSparseMatrix::FromTripletSparseMatrix(*this)->ToCRSMatrix(
  178. crs_matrix);
  179. }
  180. void TripletSparseMatrix::ToDenseMatrix(Matrix* dense_matrix) const {
  181. dense_matrix->resize(num_rows_, num_cols_);
  182. dense_matrix->setZero();
  183. Matrix& m = *dense_matrix;
  184. for (int i = 0; i < num_nonzeros_; ++i) {
  185. m(rows_[i], cols_[i]) += values_[i];
  186. }
  187. }
  188. void TripletSparseMatrix::AppendRows(const TripletSparseMatrix& B) {
  189. CHECK_EQ(B.num_cols(), num_cols_);
  190. Reserve(num_nonzeros_ + B.num_nonzeros_);
  191. for (int i = 0; i < B.num_nonzeros_; ++i) {
  192. rows_.get()[num_nonzeros_] = B.rows()[i] + num_rows_;
  193. cols_.get()[num_nonzeros_] = B.cols()[i];
  194. values_.get()[num_nonzeros_++] = B.values()[i];
  195. }
  196. num_rows_ = num_rows_ + B.num_rows();
  197. }
  198. void TripletSparseMatrix::AppendCols(const TripletSparseMatrix& B) {
  199. CHECK_EQ(B.num_rows(), num_rows_);
  200. Reserve(num_nonzeros_ + B.num_nonzeros_);
  201. for (int i = 0; i < B.num_nonzeros_; ++i, ++num_nonzeros_) {
  202. rows_.get()[num_nonzeros_] = B.rows()[i];
  203. cols_.get()[num_nonzeros_] = B.cols()[i] + num_cols_;
  204. values_.get()[num_nonzeros_] = B.values()[i];
  205. }
  206. num_cols_ = num_cols_ + B.num_cols();
  207. }
  208. void TripletSparseMatrix::Resize(int new_num_rows, int new_num_cols) {
  209. if ((new_num_rows >= num_rows_) && (new_num_cols >= num_cols_)) {
  210. num_rows_ = new_num_rows;
  211. num_cols_ = new_num_cols;
  212. return;
  213. }
  214. num_rows_ = new_num_rows;
  215. num_cols_ = new_num_cols;
  216. int* r_ptr = rows_.get();
  217. int* c_ptr = cols_.get();
  218. double* v_ptr = values_.get();
  219. int dropped_terms = 0;
  220. for (int i = 0; i < num_nonzeros_; ++i) {
  221. if ((r_ptr[i] < num_rows_) && (c_ptr[i] < num_cols_)) {
  222. if (dropped_terms) {
  223. r_ptr[i - dropped_terms] = r_ptr[i];
  224. c_ptr[i - dropped_terms] = c_ptr[i];
  225. v_ptr[i - dropped_terms] = v_ptr[i];
  226. }
  227. } else {
  228. ++dropped_terms;
  229. }
  230. }
  231. num_nonzeros_ -= dropped_terms;
  232. }
  233. std::unique_ptr<TripletSparseMatrix>
  234. TripletSparseMatrix::CreateSparseDiagonalMatrix(const double* values,
  235. int num_rows) {
  236. std::unique_ptr<TripletSparseMatrix> m =
  237. std::make_unique<TripletSparseMatrix>(num_rows, num_rows, num_rows);
  238. for (int i = 0; i < num_rows; ++i) {
  239. m->mutable_rows()[i] = i;
  240. m->mutable_cols()[i] = i;
  241. m->mutable_values()[i] = values[i];
  242. }
  243. m->set_num_nonzeros(num_rows);
  244. return m;
  245. }
  246. void TripletSparseMatrix::ToTextFile(FILE* file) const {
  247. CHECK(file != nullptr);
  248. for (int i = 0; i < num_nonzeros_; ++i) {
  249. fprintf(file, "% 10d % 10d %17f\n", rows_[i], cols_[i], values_[i]);
  250. }
  251. }
  252. std::unique_ptr<TripletSparseMatrix> TripletSparseMatrix::CreateFromTextFile(
  253. FILE* file) {
  254. CHECK(file != nullptr);
  255. int num_rows = 0;
  256. int num_cols = 0;
  257. std::vector<int> rows;
  258. std::vector<int> cols;
  259. std::vector<double> values;
  260. while (true) {
  261. int row, col;
  262. double value;
  263. if (fscanf(file, "%d %d %lf", &row, &col, &value) != 3) {
  264. break;
  265. }
  266. rows.push_back(row);
  267. cols.push_back(col);
  268. values.push_back(value);
  269. num_rows = std::max(num_rows, row + 1);
  270. num_cols = std::max(num_cols, col + 1);
  271. }
  272. VLOG(1) << "Read " << rows.size() << " nonzeros from file.";
  273. return std::make_unique<TripletSparseMatrix>(
  274. num_rows, num_cols, rows, cols, values);
  275. }
  276. std::unique_ptr<TripletSparseMatrix> TripletSparseMatrix::CreateRandomMatrix(
  277. const TripletSparseMatrix::RandomMatrixOptions& options,
  278. std::mt19937& prng) {
  279. CHECK_GT(options.num_rows, 0);
  280. CHECK_GT(options.num_cols, 0);
  281. CHECK_GT(options.density, 0.0);
  282. CHECK_LE(options.density, 1.0);
  283. std::vector<int> rows;
  284. std::vector<int> cols;
  285. std::vector<double> values;
  286. std::uniform_real_distribution<double> uniform01(0.0, 1.0);
  287. std::normal_distribution<double> standard_normal;
  288. while (rows.empty()) {
  289. rows.clear();
  290. cols.clear();
  291. values.clear();
  292. for (int r = 0; r < options.num_rows; ++r) {
  293. for (int c = 0; c < options.num_cols; ++c) {
  294. if (uniform01(prng) <= options.density) {
  295. rows.push_back(r);
  296. cols.push_back(c);
  297. values.push_back(standard_normal(prng));
  298. }
  299. }
  300. }
  301. }
  302. return std::make_unique<TripletSparseMatrix>(
  303. options.num_rows, options.num_cols, rows, cols, values);
  304. }
  305. } // namespace ceres::internal