Skip to content

Commit a159e3e

Browse files
committed
printing residual vector too
1 parent f8d0ac0 commit a159e3e

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

examples/ScaleMicrogrid/ScaleMicrogrid.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,8 @@ int test(index_type Nsize, real_type error_tol, bool debug_output)
306306

307307
sys_model->initialize();
308308
sys_model->evaluateResidual();
309-
309+
// print the residual in matrix market format
310+
sys_model->printResidualMatrixMarket("ScaleMicrogrid_Residual_N" + std::to_string(Nsize) + ".mtx", "ScaleMicrogrid Residual N" + std::to_string(Nsize));
310311
std::vector<real_type>& fres = sys_model->getResidual();
311312
if (debug_output)
312313
{

src/Model/PowerElectronics/SystemModelPowerElectronics.hpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,46 @@
1212

1313
namespace GridKit
1414
{
15+
/**
16+
* Writes a vector to a file in Matrix Market format
17+
*
18+
* @param vec The vector to write
19+
* @param filename The name of the output file
20+
* @param header Additional header information/comments
21+
* @return true if the write was successful, false otherwise
22+
*/
23+
template <typename T>
24+
bool writeVectorToMatrixMarket(const std::vector<T>& vec, const std::string& filename, const std::string& header) {
25+
std::ofstream outFile(filename);
26+
27+
if (!outFile.is_open()) {
28+
std::cerr << "Error: Could not open file " << filename << " for writing." << std::endl;
29+
return false;
30+
}
31+
32+
// Write Matrix Market header
33+
outFile << "%%MatrixMarket vector array real general" << std::endl;
34+
35+
// Write additional header information as comments
36+
if (!header.empty()) {
37+
outFile << "% " << header << std::endl;
38+
}
39+
40+
// Write the vector size
41+
outFile << vec.size() << std::endl;
42+
43+
// Write the vector elements
44+
outFile << std::scientific << std::setprecision(16);
45+
for (const auto& val : vec) {
46+
outFile << val << std::endl;
47+
}
48+
49+
outFile.close();
50+
51+
std::cout << "Vector successfully written to " << filename << std::endl;
52+
return true;
53+
}
54+
1555

1656
template <class ScalarT, typename IdxT>
1757
class PowerElectronicsModel : public CircuitComponent<ScalarT, IdxT>
@@ -324,6 +364,17 @@ namespace GridKit
324364
alpha_ = a;
325365
}
326366

367+
/**
368+
* @brief print the system residual in COO format
369+
*
370+
* @param[in] filename
371+
* @param[in] title
372+
*/
373+
void printResidualMatrixMarket(std::string filename, std::string title)
374+
{
375+
writeVectorToMatrixMarket(f_, filename, title);
376+
}
377+
327378
/**
328379
* @brief print the system Jacobian in COO format
329380
*

0 commit comments

Comments
 (0)