]> https://gitweb.dealii.org/ - dealii.git/commitdiff
Add function to print a sparse matrix in a format readable by numpy
authorBruno Turcksin <bruno.turcksin@gmail.com>
Sun, 2 Jun 2019 22:58:10 +0000 (18:58 -0400)
committerBruno Turcksin <bruno.turcksin@gmail.com>
Wed, 12 Jun 2019 13:01:30 +0000 (09:01 -0400)
include/deal.II/lac/sparse_matrix.h
include/deal.II/lac/sparse_matrix.templates.h

index eeddd5de0e7697bf49afd4642057377d805dcff1..b7e6a9b34fe189217c14ab096cb9fb34c9887a45 100644 (file)
@@ -1583,6 +1583,17 @@ public:
   void
   print_pattern(std::ostream &out, const double threshold = 0.) const;
 
+  /**
+   * Print the vector to the output stream @p out in a format that can be
+   * read by numpy::readtxt(). To load the matrix in python just do
+   * <code>
+   *  [data, row, column] = numpy.loadtxt('my_matrix.txt')
+   *  sparse_matrix = scipy.sparse.csr_matrix((data, (row, column)))
+   * </code>
+   */
+  void
+  print_numpy_array(std::ostream &out, const unsigned int precision = 9) const;
+
   /**
    * Write the data of this object en bloc to a file. This is done in a binary
    * mode, so the output is neither readable by humans nor (probably) by other
index a1b62de95b933a7c42da33daff11f2d86027b0b5..a9b7bd40d285d1410a2d16f1d01330063ddc8dbd 100644 (file)
@@ -1965,6 +1965,54 @@ SparseMatrix<number>::print_pattern(std::ostream &out,
 
 
 
+template <typename number>
+void
+SparseMatrix<number>::print_numpy_array(std::ostream &     out,
+                                        const unsigned int precision) const
+{
+  AssertThrow(out, ExcIO());
+  boost::io::ios_flags_saver restore_flags(out);
+
+  out.precision(precision);
+
+  Assert(cols != nullptr, ExcNotInitialized());
+  Assert(val != nullptr, ExcNotInitialized());
+
+  std::vector<number> rows;
+  std::vector<number> columns;
+  std::vector<number> values;
+  rows.reserve(n_nonzero_elements());
+  columns.reserve(n_nonzero_elements());
+  values.reserve(n_nonzero_elements());
+
+  for (size_type i = 0; i < cols->rows; ++i)
+    {
+      for (size_type j = cols->rowstart[i]; j < cols->rowstart[i + 1]; ++j)
+        {
+          rows.push_back(i);
+          columns.push_back(cols->colnums[j]);
+          values.push_back(j);
+        }
+    }
+
+  for (auto d : values)
+    out << d << ' ';
+  out << '\n';
+
+  for (auto r : rows)
+    out << r << ' ';
+  out << '\n';
+
+  for (auto c : columns)
+    out << c << ' ';
+  out << '\n';
+  out << std::flush;
+
+  AssertThrow(out, ExcIO());
+}
+
+
+
 template <typename number>
 void
 SparseMatrix<number>::block_write(std::ostream &out) const

In the beginning the Universe was created. This has made a lot of people very angry and has been widely regarded as a bad move.

Douglas Adams


Typeset in Trocchi and Trocchi Bold Sans Serif.