Eigen-Contrib  5.0.1
 
Loading...
Searching...
No Matches
MarketIO.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2011 Gael Guennebaud <gael.guennebaud@inria.fr>
5// Copyright (C) 2012 Desire NUENTSA WAKAM <desire.nuentsa_wakam@inria.fr>
6//
7// This Source Code Form is subject to the terms of the Mozilla
8// Public License v. 2.0. If a copy of the MPL was not distributed
9// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10// SPDX-License-Identifier: MPL-2.0
11
12#ifndef EIGEN_SPARSE_MARKET_IO_H
13#define EIGEN_SPARSE_MARKET_IO_H
14
15#include <iostream>
16#include <vector>
17
18// IWYU pragma: private
19#include "./InternalHeaderCheck.h"
20
21namespace Eigen {
22
23namespace internal {
24template <typename Scalar, typename StorageIndex>
25inline void GetMarketLine(const char* line, StorageIndex& i, StorageIndex& j, Scalar& value) {
26 std::stringstream sline(line);
27 sline >> i >> j >> value;
28}
29
30template <>
31inline void GetMarketLine(const char* line, int& i, int& j, float& value) {
32 std::sscanf(line, "%d %d %g", &i, &j, &value);
33}
34
35template <>
36inline void GetMarketLine(const char* line, int& i, int& j, double& value) {
37 std::sscanf(line, "%d %d %lg", &i, &j, &value);
38}
39
40template <>
41inline void GetMarketLine(const char* line, int& i, int& j, std::complex<float>& value) {
42 std::sscanf(line, "%d %d %g %g", &i, &j, &numext::real_ref(value), &numext::imag_ref(value));
43}
44
45template <>
46inline void GetMarketLine(const char* line, int& i, int& j, std::complex<double>& value) {
47 std::sscanf(line, "%d %d %lg %lg", &i, &j, &numext::real_ref(value), &numext::imag_ref(value));
48}
49
50template <typename Scalar, typename StorageIndex>
51inline void GetMarketLine(const char* line, StorageIndex& i, StorageIndex& j, std::complex<Scalar>& value) {
52 std::stringstream sline(line);
53 Scalar valR, valI;
54 sline >> i >> j >> valR >> valI;
55 value = std::complex<Scalar>(valR, valI);
56}
57
58template <typename RealScalar>
59inline void GetDenseElt(const std::string& line, RealScalar& val) {
60 std::istringstream newline(line);
61 newline >> val;
62}
63
64template <typename RealScalar>
65inline void GetDenseElt(const std::string& line, std::complex<RealScalar>& val) {
66 RealScalar valR, valI;
67 std::istringstream newline(line);
68 newline >> valR >> valI;
69 val = std::complex<RealScalar>(valR, valI);
70}
71
72template <typename Scalar>
73inline void putMarketHeader(std::string& header, int sym) {
74 header = "%%MatrixMarket matrix coordinate ";
75 EIGEN_IF_CONSTEXPR ((std::is_same<Scalar, std::complex<float> >::value ||
76 std::is_same<Scalar, std::complex<double> >::value)) {
77 header += " complex";
78 if (sym == Symmetric)
79 header += " symmetric";
80 else if (sym == SelfAdjoint)
81 header += " Hermitian";
82 else
83 header += " general";
84 } else {
85 header += " real";
86 if (sym == Symmetric)
87 header += " symmetric";
88 else
89 header += " general";
90 }
91}
92
93template <typename Scalar, typename StorageIndex>
94inline void PutMatrixElt(Scalar value, StorageIndex row, StorageIndex col, std::ofstream& out) {
95 out << row << " " << col << " " << value << "\n";
96}
97template <typename Scalar, typename StorageIndex>
98inline void PutMatrixElt(std::complex<Scalar> value, StorageIndex row, StorageIndex col, std::ofstream& out) {
99 out << row << " " << col << " " << value.real() << " " << value.imag() << "\n";
100}
101
102template <typename Scalar>
103inline void putDenseElt(Scalar value, std::ofstream& out) {
104 out << value << "\n";
105}
106template <typename Scalar>
107inline void putDenseElt(std::complex<Scalar> value, std::ofstream& out) {
108 out << value.real() << " " << value.imag() << "\n";
109}
110
111} // end namespace internal
112
123inline bool getMarketHeader(const std::string& filename, int& sym, bool& iscomplex, bool& isdense) {
124 sym = 0;
125 iscomplex = false;
126 isdense = false;
127 std::ifstream in(filename.c_str(), std::ios::in);
128 if (!in) return false;
129
130 std::string line;
131 // The matrix header is always the first line in the file
132 std::getline(in, line);
133 eigen_assert(in.good());
134
135 std::stringstream fmtline(line);
136 std::string substr[5];
137 fmtline >> substr[0] >> substr[1] >> substr[2] >> substr[3] >> substr[4];
138 if (substr[2].compare("array") == 0) isdense = true;
139 if (substr[3].compare("complex") == 0) iscomplex = true;
140 if (substr[4].compare("symmetric") == 0)
141 sym = Symmetric;
142 else if (substr[4].compare("Hermitian") == 0)
143 sym = SelfAdjoint;
144
145 return true;
146}
147
156template <typename SparseMatrixType>
157bool loadMarket(SparseMatrixType& mat, const std::string& filename) {
158 typedef typename SparseMatrixType::Scalar Scalar;
159 typedef typename SparseMatrixType::StorageIndex StorageIndex;
160 std::ifstream input(filename.c_str(), std::ios::in);
161 if (!input) return false;
162
163 char rdbuffer[4096];
164 input.rdbuf()->pubsetbuf(rdbuffer, 4096);
165
166 const int maxBuffersize = 2048;
167 char buffer[maxBuffersize];
168
169 bool readsizes = false;
170
172 std::vector<T> elements;
173
174 Index M(-1), N(-1), NNZ(-1);
175 Index count = 0;
176 while (input.getline(buffer, maxBuffersize)) {
177 // skip comments
178 // NOTE An appropriate test should be done on the header to get the symmetry
179 if (buffer[0] == '%') continue;
180
181 if (!readsizes) {
182 std::stringstream line(buffer);
183 line >> M >> N >> NNZ;
184 if (M > 0 && N > 0) {
185 readsizes = true;
186 mat.resize(M, N);
187 mat.reserve(NNZ);
188 elements.reserve(NNZ);
189 }
190 } else {
191 StorageIndex i(-1), j(-1);
192 Scalar value;
193 internal::GetMarketLine(buffer, i, j, value);
194
195 i--;
196 j--;
197 if (i >= 0 && j >= 0 && i < M && j < N) {
198 ++count;
199 elements.push_back(T(i, j, value));
200 } else {
201 std::cerr << "Invalid read: " << i << "," << j << "\n";
202 return false;
203 }
204 }
205 }
206
207 mat.setFromTriplets(elements.begin(), elements.end());
208 if (count != NNZ) {
209 std::cerr << count << "!=" << NNZ << "\n";
210 return false;
211 }
212 input.close();
213 return true;
214}
215
226template <typename DenseType>
227bool loadMarketDense(DenseType& mat, const std::string& filename) {
228 typedef typename DenseType::Scalar Scalar;
229 std::ifstream in(filename.c_str(), std::ios::in);
230 if (!in) return false;
231
232 std::string line;
233 Index rows(0), cols(0);
234 do { // Skip comments
235 std::getline(in, line);
236 eigen_assert(in.good());
237 } while (line[0] == '%');
238 std::istringstream newline(line);
239 newline >> rows >> cols;
240
241 bool sizes_not_positive = (rows < 1 || cols < 1);
242 bool wrong_input_rows = (DenseType::MaxRowsAtCompileTime != Dynamic && rows > DenseType::MaxRowsAtCompileTime) ||
243 (DenseType::RowsAtCompileTime != Dynamic && rows != DenseType::RowsAtCompileTime);
244 bool wrong_input_cols = (DenseType::MaxColsAtCompileTime != Dynamic && cols > DenseType::MaxColsAtCompileTime) ||
245 (DenseType::ColsAtCompileTime != Dynamic && cols != DenseType::ColsAtCompileTime);
246
247 if (sizes_not_positive || wrong_input_rows || wrong_input_cols) {
248 if (sizes_not_positive) {
249 std::cerr << "non-positive row or column size in file" << filename << "\n";
250 } else {
251 std::cerr << "Input matrix can not be resized to" << rows << " x " << cols << "as given in " << filename << "\n";
252 }
253 in.close();
254 return false;
255 }
256
257 mat.resize(rows, cols);
258 Index row = 0;
259 Index col = 0;
260 Index n = 0;
261 Scalar value;
262 while (std::getline(in, line) && (row < rows) && (col < cols)) {
263 internal::GetDenseElt(line, value);
264 // matrixmarket format is column major
265 mat(row, col) = value;
266 row++;
267 if (row == rows) {
268 row = 0;
269 col++;
270 }
271 n++;
272 }
273 in.close();
274 if (n != mat.size()) {
275 std::cerr << "Unable to read all elements from file " << filename << "\n";
276 return false;
277 }
278 return true;
279}
280
284template <typename VectorType>
285bool loadMarketVector(VectorType& vec, const std::string& filename) {
286 return loadMarketDense(vec, filename);
287}
288
299template <typename SparseMatrixType>
300bool saveMarket(const SparseMatrixType& mat, const std::string& filename, int sym = 0) {
301 typedef typename SparseMatrixType::Scalar Scalar;
302 typedef typename SparseMatrixType::RealScalar RealScalar;
303 std::ofstream out(filename.c_str(), std::ios::out);
304 if (!out) return false;
305
306 out.flags(std::ios_base::scientific);
307 out.precision(std::numeric_limits<RealScalar>::digits10 + 2);
308 std::string header;
309 internal::putMarketHeader<Scalar>(header, sym);
310 out << header << std::endl;
311 out << mat.rows() << " " << mat.cols() << " " << mat.nonZeros() << "\n";
312 int count = 0;
313 EIGEN_UNUSED_VARIABLE(count);
314 for (int j = 0; j < mat.outerSize(); ++j)
315 for (typename SparseMatrixType::InnerIterator it(mat, j); it; ++it) {
316 ++count;
317 internal::PutMatrixElt(it.value(), it.row() + 1, it.col() + 1, out);
318 }
319 out.close();
320 return true;
321}
322
332
333template <typename DenseType>
334bool saveMarketDense(const DenseType& mat, const std::string& filename) {
335 typedef typename DenseType::Scalar Scalar;
336 typedef typename DenseType::RealScalar RealScalar;
337 std::ofstream out(filename.c_str(), std::ios::out);
338 if (!out) return false;
339
340 out.flags(std::ios_base::scientific);
341 out.precision(std::numeric_limits<RealScalar>::digits10 + 2);
342 EIGEN_IF_CONSTEXPR ((std::is_same<Scalar, std::complex<float> >::value ||
343 std::is_same<Scalar, std::complex<double> >::value)) {
344 out << "%%MatrixMarket matrix array complex general\n";
345 } else {
346 out << "%%MatrixMarket matrix array real general\n";
347 }
348 out << mat.rows() << " " << mat.cols() << "\n";
349 for (Index i = 0; i < mat.cols(); i++) {
350 for (Index j = 0; j < mat.rows(); j++) {
351 internal::putDenseElt(mat(j, i), out);
352 }
353 }
354 out.close();
355 return true;
356}
357
362template <typename VectorType>
363bool saveMarketVector(const VectorType& vec, const std::string& filename) {
364 return saveMarketDense(vec, filename);
365}
366
367} // end namespace Eigen
368
369#endif // EIGEN_SPARSE_MARKET_IO_H
bool loadMarketVector(VectorType &vec, const std::string &filename)
Same functionality as loadMarketDense, deprecated.
Definition MarketIO.h:285
bool saveMarket(const SparseMatrixType &mat, const std::string &filename, int sym=0)
writes a sparse Matrix to a matrixmarket format file
Definition MarketIO.h:300
bool loadMarket(SparseMatrixType &mat, const std::string &filename)
Loads a sparse matrix from a matrixmarket format file.
Definition MarketIO.h:157
bool saveMarketVector(const VectorType &vec, const std::string &filename)
Same functionality as saveMarketDense, deprecated.
Definition MarketIO.h:363
bool getMarketHeader(const std::string &filename, int &sym, bool &iscomplex, bool &isdense)
Reads the header of a matrixmarket file and determines the properties of a matrix.
Definition MarketIO.h:123
bool loadMarketDense(DenseType &mat, const std::string &filename)
Loads a dense Matrix or Vector from a matrixmarket file. If a statically sized matrix has to be parse...
Definition MarketIO.h:227
bool saveMarketDense(const DenseType &mat, const std::string &filename)
writes a dense Matrix or vector to a matrixmarket format file
Definition MarketIO.h:334
Namespace containing all symbols from the Eigen library.