Debian Codegraph @

mex/sources/libkorder/sylv/tests/MMMatrix.cc

raw
1 /*
2 * Copyright © 2004-2011 Ondra Kamenik
3 * Copyright © 2019-2026 Dynare Team
4 *
5 * This file is part of Dynare.
6 *
7 * Dynare is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * Dynare is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with Dynare. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21 #include "MMMatrix.hh"
22
23 #include <fstream>
24 #include <iomanip>
25
26 MMMatrixIn::MMMatrixIn(const std::string& fname)
27 {
28 std::ifstream fd {fname};
29 if (fd.fail())
30 throw MMException("Cannot open file " + fname + " for reading\n");
31
32 // jump over initial comments
33 while (fd.peek() == '%')
34 fd.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
35
36 // read in number of rows and cols
37 fd >> rows >> cols;
38 if (fd.fail())
39 throw MMException("Couldn't parse rows and cols\n");
40 // read in data
41 int len = rows * cols;
42 data.resize(len);
43 int i = 0;
44 while (!fd.eof() && i < len)
45 {
46 fd >> data[i];
47 if (fd.fail())
48 throw MMException("Couldn't parse float number\n");
49 i++;
50 }
51 if (i < len)
52 throw MMException("Couldn't read all " + std::to_string(len) + " elements, read "
53 + std::to_string(i) + " so far\n");
54 fd.close();
55 }
56
57 void
58 MMMatrixOut::write(const std::string& fname, const GeneralMatrix& m)
59 {
60 std::ofstream fd {fname, std::ios::out | std::ios::trunc};
61 if (fd.fail())
62 throw MMException("Cannot open file " + fname + " for writing\n");
63
64 fd << "%%%%MatrixMarket matrix array real general" << '\n'
65 << m.nrows() << ' ' << m.ncols() << '\n'
66 << std::setprecision(35);
67 for (int i = 0; i < m.ncols(); i++)
68 for (int j = 0; j < m.nrows(); j++)
69 fd << std::setw(40) << m.get(i, j);
70 fd.close();
71 }