From: Bruno Turcksin Date: Sun, 2 Jun 2019 22:50:47 +0000 (-0400) Subject: Add function to print vector in a format readable by numpy X-Git-Tag: v9.2.0-rc1~1420^2~6 X-Git-Url: https://gitweb.dealii.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=8b15634fa87aa8686bc50864b4173cdfdbd0bf36;p=dealii.git Add function to print vector in a format readable by numpy --- diff --git a/include/deal.II/lac/la_vector.h b/include/deal.II/lac/la_vector.h index be07fcaa10..3002f7d5a7 100644 --- a/include/deal.II/lac/la_vector.h +++ b/include/deal.II/lac/la_vector.h @@ -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 + * + * vector = numpy.loadtxt('my_vector.txt') + * + */ + 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 diff --git a/include/deal.II/lac/la_vector.templates.h b/include/deal.II/lac/la_vector.templates.h index 6d1aacedc0..5d510a5125 100644 --- a/include/deal.II/lac/la_vector.templates.h +++ b/include/deal.II/lac/la_vector.templates.h @@ -560,6 +560,26 @@ namespace LinearAlgebra + template + void + Vector::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 void Vector::block_write(std::ostream &out) const