Vulpes  0.1.0
Versatile and parallel compUtational Library for high-order discontinuous Polytopal Element Simulations
Loading...
Searching...
No Matches
io.hpp
Go to the documentation of this file.
1// ----------------------------------------------------------------------
2//
3// Copyright (C) 2024 - 2026 by the Vulpes authors.
4// This file is part of Vulpes.
5//
6// Vulpes is free software; you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// Vulpes is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14// General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Vulpes. If not, see <http://www.gnu.org/licenses/>.
18//
19// ----------------------------------------------------------------------
20
21// Author: Francesco Daniele <francesco.daniele@polimi.it>
22// Author: Francesco Rosnati <francesco.rosnati@polimi.it>
23// Author: Matteo Caldana <matteo.caldana@polimi.it>
24// Author: Pedro Peixoto <ppeixoto@usp.br>
25
26#ifndef VULPES_UTILS_IO_HPP_
27#define VULPES_UTILS_IO_HPP_
28
29#include <fstream>
30#include <sstream>
31#include <stdexcept>
32#include <string>
33#include <vector>
34
35#include <Eigen/Dense>
36
38#include "vulpes/la/vector.hpp"
39
40namespace vulpes {
41namespace io {
42
47
49 la::SparseMatrix& result, const std::string& filename) {
50 Mat temp_mat;
51 PetscViewer viewer;
52
53 // 1. Use the binary viewer (required for MatLoad)
54 PetscCallAbortWorld(PetscViewerBinaryOpen(
55 PETSC_COMM_WORLD, filename.c_str(), FILE_MODE_READ, &viewer));
56
57 // 2. Load the matrix (MatLoad internally calls MatAssemblyBegin/End on
58 // temp_mat)
59 PetscCallAbortWorld(MatCreate(PETSC_COMM_WORLD, &temp_mat));
60 PetscCallAbortWorld(MatLoad(temp_mat, viewer));
61 PetscCallAbortWorld(PetscViewerDestroy(&viewer));
62
63 // 3. Get the internal matrix
64 Mat internal_mat = result.getPetscMatrix();
65
66 // 4. FIX: Make sure internal_mat is assembled before MatCopy
67 // Even if it is empty or new, PETSc must know that the insertion phase is
68 // closed
69 PetscCallAbortWorld(MatAssemblyBegin(internal_mat, MAT_FINAL_ASSEMBLY));
70 PetscCallAbortWorld(MatAssemblyEnd(internal_mat, MAT_FINAL_ASSEMBLY));
71
72 // 5. Copy the data
73 // If result and temp_mat have different block sizes, PETSc will handle it
74 // via .info
76 MatCopy(temp_mat, internal_mat, DIFFERENT_NONZERO_PATTERN));
77
78 // 6. Cleanup
79 PetscCallAbortWorld(MatDestroy(&temp_mat));
80}
81
85
87 la::Vector& result, const std::string& filename) {
88 Vec temp_vec;
89 PetscViewer viewer;
90
91 // 1. Use the binary viewer (required for VecLoad)
92 PetscCallAbortWorld(PetscViewerBinaryOpen(
93 PETSC_COMM_WORLD, filename.c_str(), FILE_MODE_READ, &viewer));
94
95 // 2. Load the vector (VecLoad internally calls VecAssemblyBegin/End on
96 // temp_vec)
97 PetscCallAbortWorld(VecCreate(PETSC_COMM_WORLD, &temp_vec));
98 PetscCallAbortWorld(VecLoad(temp_vec, viewer));
99 PetscCallAbortWorld(PetscViewerDestroy(&viewer));
100
101 // 3. Get the internal vector
102 Vec internal_vec = result.getPetscVector();
103
104 // 4. FIX: Make sure internal_vec is assembled before VecCopy
105 // Even if it is empty or new, PETSc must know that the insertion phase is
106 // closed
107 PetscCallAbortWorld(VecAssemblyBegin(internal_vec));
108 PetscCallAbortWorld(VecAssemblyEnd(internal_vec));
109
110 // 5. Copy the data
111 PetscCallAbortWorld(VecCopy(temp_vec, internal_vec));
112
113 // 6. Cleanup
114 PetscCallAbortWorld(VecDestroy(&temp_vec));
115}
116
127inline Eigen::MatrixXd readCSVToEigenMatrix(
128 const std::string& filename, char delimiter = ',') {
129 std::ifstream file(filename);
130 if (!file.is_open()) {
131 throw std::runtime_error("Could not open file: " + filename);
132 }
133
134 std::string line;
135 std::vector<double> data;
136 size_t numRows = 0;
137 size_t numCols = 0;
138 while (std::getline(file, line)) {
139 std::stringstream ss(line);
140 std::string cell;
141 size_t colsInCurrentRow = 0;
142
143 while (std::getline(ss, cell, delimiter)) {
144 // Trim whitespace
145 cell.erase(0, cell.find_first_not_of(" \t\r\n"));
146 cell.erase(cell.find_last_not_of(" \t\r\n") + 1);
147
148 // Convert to double and add to data
149 try {
150 data.push_back(std::stod(cell));
151 } catch (const std::exception& e) {
152 throw std::runtime_error(
153 "Failed to convert value to double at row " +
154 std::to_string(numRows + 1) + ", column " +
155 std::to_string(colsInCurrentRow + 1) + ": " + cell);
156 }
157
158 colsInCurrentRow++;
159 }
160
161 // For the first row, establish the column count
162 if (numRows == 0) {
163 numCols = colsInCurrentRow;
164 } else if (colsInCurrentRow != numCols) {
165 // For subsequent rows, check column consistency
166 throw std::runtime_error(
167 "Inconsistent number of columns at row " +
168 std::to_string(numRows + 1) + ": expected " +
169 std::to_string(numCols) + " but got " +
170 std::to_string(colsInCurrentRow));
171 }
172
173 numRows++;
174 }
175
176 return Eigen::Map<Eigen::Matrix<double, -1, -1, Eigen::RowMajor>>(
177 data.data(), numRows, numCols);
178}
179
190inline Eigen::VectorXd readCSVToEigenVector(
191 const std::string& filename, char delimiter = ',') {
192 std::ifstream file(filename);
193 if (!file.is_open()) {
194 throw std::runtime_error("Could not open file: " + filename);
195 }
196
197 std::string line;
198 std::vector<double> data;
199 size_t numRows = 0;
200 while (std::getline(file, line)) {
201 std::stringstream ss(line);
202 std::string cell;
203 size_t colInCurrentRow = 0;
204
205 while (std::getline(ss, cell, delimiter)) {
206 // Trim whitespace
207 cell.erase(0, cell.find_first_not_of(" \t\r\n"));
208 cell.erase(cell.find_last_not_of(" \t\r\n") + 1);
209
210 // Convert to double and add to data
211 try {
212 data.push_back(std::stod(cell));
213 } catch (const std::exception& e) {
214 throw std::runtime_error(
215 "Failed to convert value to double at row " +
216 std::to_string(numRows + 1) + ", column " +
217 std::to_string(colInCurrentRow + 1) + ": " + cell);
218 }
219
220 colInCurrentRow++;
221 }
222 numRows++;
223 }
224
225 file.close();
226
227 if (data.empty()) {
228 throw std::runtime_error("Empty file: " + filename);
229 }
230
231 return Eigen::VectorXd::Map(
232 data.data(), static_cast<Eigen::Index>(data.size()));
233}
234
235} // namespace io
236} // namespace vulpes
237
238#endif // VULPES_UTILS_IO_HPP_
Definition sparse_matrix.hpp:52
const auto & getPetscMatrix() const
Get the underlying PETSc matrix.
Definition sparse_matrix.hpp:307
A wrapper around PETSc Vec for distributed vectors.
Definition vector.hpp:54
const Vec & getPetscVector() const
Get the underlying PETSc vector (const version).
Definition vector.hpp:268
Definition io.hpp:41
void loadMatrixFromFile(la::SparseMatrix &result, const std::string &filename)
Load a PETSc matrix from a binary file and copy it into a SparseMatrix.
Definition io.hpp:48
void loadVectorFromFile(la::Vector &result, const std::string &filename)
Load a PETSc vector from a binary file and copy it into a Vector.
Definition io.hpp:86
Eigen::VectorXd readCSVToEigenVector(const std::string &filename, char delimiter=',')
Definition io.hpp:190
Eigen::MatrixXd readCSVToEigenMatrix(const std::string &filename, char delimiter=',')
Definition io.hpp:127
Definition cell_manager.hpp:38
#define PetscCallAbortWorld(...)
Definition petsc_utils.hpp:32