DiSMEC++
numpy.h
Go to the documentation of this file.
1 // Copyright (c) 2021, Aalto University, developed by Erik Schultheis
2 // All rights reserved.
3 //
4 // SPDX-License-Identifier: MIT
5 
6 #ifndef DISMEC_NUMPY_H
7 #define DISMEC_NUMPY_H
8 
9 #include <iosfwd>
10 #include <string>
11 #include <string_view>
12 #include "matrix_types.h"
13 
14 namespace dismec::io {
20  bool is_npy(std::istream& target);
21 
32  void write_npy_header(std::streambuf& target, std::string_view description);
33 
41  std::string make_npy_description(std::string_view dtype_desc, bool column_major, std::size_t size);
42 
51  std::string make_npy_description(std::string_view dtype_desc, bool column_major, std::size_t rows, std::size_t cols);
52 
56  struct NpyHeaderData {
57  std::string DataType;
58  bool ColumnMajor;
59  long Rows;
60  long Cols;
62  };
63 
71  NpyHeaderData parse_npy_header(std::streambuf& source);
72 
75  template<class S>
76  const char* data_type_string();
77 
84  template<class Derived>
85  std::string make_npy_description(const Eigen::DenseBase<Derived>& matrix) {
86  return make_npy_description(data_type_string<typename Derived::Scalar>(), !Derived::IsRowMajor, matrix.rows(), matrix.cols());
87  }
88 
93  types::DenseRowMajor<real_t> load_matrix_from_npy(const std::string& path);
94 
98  void save_matrix_to_npy(std::ostream& source, const types::DenseRowMajor<real_t>&);
99  void save_matrix_to_npy(const std::string& path, const types::DenseRowMajor<real_t>&);
100 }
101 
102 #endif //DISMEC_NUMPY_H
std::string make_npy_description(std::string_view dtype_desc, bool column_major, std::size_t size)
Creates a string with the data description dictionary for (1 dimensional) arrays.
Definition: numpy.cpp:48
const char * data_type_string()
void write_npy_header(std::streambuf &target, std::string_view description)
Writes the header for a npy file.
Definition: numpy.cpp:32
bool is_npy(std::istream &target)
Check whether the stream is a npy file.
Definition: numpy.cpp:22
types::DenseRowMajor< real_t > load_matrix_from_npy(std::istream &source)
Loads a matrix from a numpy array.
Definition: numpy.cpp:342
void save_matrix_to_npy(std::ostream &source, const types::DenseRowMajor< real_t > &)
Saves a matrix to a numpy array.
NpyHeaderData parse_npy_header(std::streambuf &source)
Parses the header of the npy file given by source.
Definition: numpy.cpp:280
outer_const< T, dense_row_major_h > DenseRowMajor
Definition: type_helpers.h:43
Contains the data of the header of a npy file with an array that has at most 2 dimensions.
Definition: numpy.h:56
long Rows
The number of rows in the data.
Definition: numpy.h:59
std::string DataType
The data type descr
Definition: numpy.h:57
bool ColumnMajor
Whether the data is column major (Fortran)
Definition: numpy.h:58