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

index be07fcaa1055aba2b5615aab73184f8ea2d43912..3002f7d5a790281f835ac48391be27806f83d0d7 100644 (file)
@@ -344,7 +344,7 @@ namespace LinearAlgebra
     locally_owned_elements() const override;
 
     /**
-     * Prints the vector to the output stream @p out.
+     * Print the vector to the output stream @p out.
      */
     virtual void
     print(std::ostream &     out,
@@ -352,6 +352,18 @@ namespace LinearAlgebra
           const bool         scientific = true,
           const bool         across     = true) const override;
 
+    /**
+     * Print the vector to the output stream @p out in a format that can be
+     * read by numpy::readtxt(). Note that the IndexSet is not printed but only
+     * the values stored in the Vector. To load the vector in python just do
+     * <code>
+     * vector = numpy.loadtxt('my_vector.txt')
+     * </code>
+     */
+    void
+    print_numpy_array(std::ostream &     out,
+                      const unsigned int precision = 9) const;
+
     /**
      * Write the vector 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 6d1aacedc0bdf86a18aca3d395ec3ea4c99fdd3d..5d510a512505b3cb9a11b92a9b7710bd2bc13cbd 100644 (file)
@@ -560,6 +560,26 @@ namespace LinearAlgebra
 
 
 
+  template <typename Number>
+  void
+  Vector<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);
+
+    const unsigned int n_elements = this->n_elements();
+    for (unsigned int i = 0; i < n_elements; ++i)
+      out << this->values[i] << ' ';
+    out << '\n' << std::flush;
+
+    AssertThrow(out, ExcIO());
+  }
+
+
+
   template <typename Number>
   void
   Vector<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.