You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

npy.hpp 20 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /*
  2. Copyright 2017-2023 Leon Merten Lohse
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  17. SOFTWARE.
  18. */
  19. #ifndef NPY_HPP_
  20. #define NPY_HPP_
  21. #include <algorithm>
  22. #include <array>
  23. #include <complex>
  24. #include <cstdint>
  25. #include <cstring>
  26. #include <fstream>
  27. #include <iostream>
  28. #include <iterator>
  29. #include <sstream>
  30. #include <stdexcept>
  31. #include <string>
  32. #include <type_traits>
  33. #include <typeindex>
  34. #include <typeinfo>
  35. #include <unordered_map>
  36. #include <utility>
  37. #include <vector>
  38. namespace npy {
  39. /* Compile-time test for byte order.
  40. If your compiler does not define these per default, you may want to define
  41. one of these constants manually.
  42. Defaults to little endian order. */
  43. #if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN || defined(__BIG_ENDIAN__) || defined(__ARMEB__) || \
  44. defined(__THUMBEB__) || defined(__AARCH64EB__) || defined(_MIBSEB) || defined(__MIBSEB) || defined(__MIBSEB__)
  45. const bool big_endian = true;
  46. #else
  47. const bool big_endian = false;
  48. #endif
  49. const size_t magic_string_length = 6;
  50. const std::array<char, magic_string_length> magic_string = {'\x93', 'N', 'U', 'M', 'P', 'Y'};
  51. const char little_endian_char = '<';
  52. const char big_endian_char = '>';
  53. const char no_endian_char = '|';
  54. constexpr std::array<char, 3> endian_chars = {little_endian_char, big_endian_char, no_endian_char};
  55. constexpr std::array<char, 4> numtype_chars = {'f', 'i', 'u', 'c'};
  56. constexpr char host_endian_char = (big_endian ? big_endian_char : little_endian_char);
  57. /* npy array length */
  58. using ndarray_len_t = unsigned long int;
  59. using shape_t = std::vector<ndarray_len_t>;
  60. using version_t = std::pair<char, char>;
  61. struct dtype_t {
  62. char byteorder;
  63. char kind;
  64. unsigned int itemsize;
  65. inline std::string str() const {
  66. std::stringstream ss;
  67. ss << byteorder << kind << itemsize;
  68. return ss.str();
  69. }
  70. inline std::tuple<const char, const char, const unsigned int> tie() const {
  71. return std::tie(byteorder, kind, itemsize);
  72. }
  73. };
  74. struct header_t {
  75. dtype_t dtype;
  76. bool fortran_order;
  77. shape_t shape;
  78. };
  79. inline void write_magic(std::ostream &ostream, version_t version) {
  80. ostream.write(magic_string.data(), magic_string_length);
  81. ostream.put(version.first);
  82. ostream.put(version.second);
  83. }
  84. inline version_t read_magic(std::istream &istream) {
  85. std::array<char, magic_string_length + 2> buf{};
  86. istream.read(buf.data(), sizeof(buf));
  87. if (!istream) {
  88. throw std::runtime_error("io error: failed reading file");
  89. }
  90. if (!std::equal(magic_string.begin(), magic_string.end(), buf.begin()))
  91. throw std::runtime_error("this file does not have a valid npy format.");
  92. version_t version;
  93. version.first = buf[magic_string_length];
  94. version.second = buf[magic_string_length + 1];
  95. return version;
  96. }
  97. const std::unordered_map<std::type_index, dtype_t> dtype_map = {
  98. {std::type_index(typeid(float)), {host_endian_char, 'f', sizeof(float)}},
  99. {std::type_index(typeid(double)), {host_endian_char, 'f', sizeof(double)}},
  100. {std::type_index(typeid(long double)), {host_endian_char, 'f', sizeof(long double)}},
  101. {std::type_index(typeid(char)), {no_endian_char, 'i', sizeof(char)}},
  102. {std::type_index(typeid(signed char)), {no_endian_char, 'i', sizeof(signed char)}},
  103. {std::type_index(typeid(short)), {host_endian_char, 'i', sizeof(short)}},
  104. {std::type_index(typeid(int)), {host_endian_char, 'i', sizeof(int)}},
  105. {std::type_index(typeid(long)), {host_endian_char, 'i', sizeof(long)}},
  106. {std::type_index(typeid(long long)), {host_endian_char, 'i', sizeof(long long)}},
  107. {std::type_index(typeid(unsigned char)), {no_endian_char, 'u', sizeof(unsigned char)}},
  108. {std::type_index(typeid(unsigned short)), {host_endian_char, 'u', sizeof(unsigned short)}},
  109. {std::type_index(typeid(unsigned int)), {host_endian_char, 'u', sizeof(unsigned int)}},
  110. {std::type_index(typeid(unsigned long)), {host_endian_char, 'u', sizeof(unsigned long)}},
  111. {std::type_index(typeid(unsigned long long)), {host_endian_char, 'u', sizeof(unsigned long long)}},
  112. {std::type_index(typeid(std::complex<float>)), {host_endian_char, 'c', sizeof(std::complex<float>)}},
  113. {std::type_index(typeid(std::complex<double>)), {host_endian_char, 'c', sizeof(std::complex<double>)}},
  114. {std::type_index(typeid(std::complex<long double>)), {host_endian_char, 'c', sizeof(std::complex<long double>)}}};
  115. // helpers
  116. inline bool is_digits(const std::string &str) { return std::all_of(str.begin(), str.end(), ::isdigit); }
  117. template <typename T, size_t N>
  118. inline bool in_array(T val, const std::array<T, N> &arr) {
  119. return std::find(std::begin(arr), std::end(arr), val) != std::end(arr);
  120. }
  121. inline dtype_t parse_descr(std::string typestring) {
  122. if (typestring.length() < 3) {
  123. throw std::runtime_error("invalid typestring (length)");
  124. }
  125. char byteorder_c = typestring.at(0);
  126. char kind_c = typestring.at(1);
  127. std::string itemsize_s = typestring.substr(2);
  128. if (!in_array(byteorder_c, endian_chars)) {
  129. throw std::runtime_error("invalid typestring (byteorder)");
  130. }
  131. if (!in_array(kind_c, numtype_chars)) {
  132. throw std::runtime_error("invalid typestring (kind)");
  133. }
  134. if (!is_digits(itemsize_s)) {
  135. throw std::runtime_error("invalid typestring (itemsize)");
  136. }
  137. unsigned int itemsize = std::stoul(itemsize_s);
  138. return {byteorder_c, kind_c, itemsize};
  139. }
  140. namespace pyparse {
  141. /**
  142. Removes leading and trailing whitespaces
  143. */
  144. inline std::string trim(const std::string &str) {
  145. const std::string whitespace = " \t";
  146. auto begin = str.find_first_not_of(whitespace);
  147. if (begin == std::string::npos) return "";
  148. auto end = str.find_last_not_of(whitespace);
  149. return str.substr(begin, end - begin + 1);
  150. }
  151. inline std::string get_value_from_map(const std::string &mapstr) {
  152. size_t sep_pos = mapstr.find_first_of(":");
  153. if (sep_pos == std::string::npos) return "";
  154. std::string tmp = mapstr.substr(sep_pos + 1);
  155. return trim(tmp);
  156. }
  157. /**
  158. Parses the string representation of a Python dict
  159. The keys need to be known and may not appear anywhere else in the data.
  160. */
  161. inline std::unordered_map<std::string, std::string> parse_dict(std::string in, const std::vector<std::string> &keys) {
  162. std::unordered_map<std::string, std::string> map;
  163. if (keys.size() == 0) return map;
  164. in = trim(in);
  165. // unwrap dictionary
  166. if ((in.front() == '{') && (in.back() == '}'))
  167. in = in.substr(1, in.length() - 2);
  168. else
  169. throw std::runtime_error("Not a Python dictionary.");
  170. std::vector<std::pair<size_t, std::string>> positions;
  171. for (auto const &value : keys) {
  172. size_t pos = in.find("'" + value + "'");
  173. if (pos == std::string::npos) throw std::runtime_error("Missing '" + value + "' key.");
  174. std::pair<size_t, std::string> position_pair{pos, value};
  175. positions.push_back(position_pair);
  176. }
  177. // sort by position in dict
  178. std::sort(positions.begin(), positions.end());
  179. for (size_t i = 0; i < positions.size(); ++i) {
  180. std::string raw_value;
  181. size_t begin{positions[i].first};
  182. size_t end{std::string::npos};
  183. std::string key = positions[i].second;
  184. if (i + 1 < positions.size()) end = positions[i + 1].first;
  185. raw_value = in.substr(begin, end - begin);
  186. raw_value = trim(raw_value);
  187. if (raw_value.back() == ',') raw_value.pop_back();
  188. map[key] = get_value_from_map(raw_value);
  189. }
  190. return map;
  191. }
  192. /**
  193. Parses the string representation of a Python boolean
  194. */
  195. inline bool parse_bool(const std::string &in) {
  196. if (in == "True") return true;
  197. if (in == "False") return false;
  198. throw std::runtime_error("Invalid python boolan.");
  199. }
  200. /**
  201. Parses the string representation of a Python str
  202. */
  203. inline std::string parse_str(const std::string &in) {
  204. if ((in.front() == '\'') && (in.back() == '\'')) return in.substr(1, in.length() - 2);
  205. throw std::runtime_error("Invalid python string.");
  206. }
  207. /**
  208. Parses the string represenatation of a Python tuple into a vector of its items
  209. */
  210. inline std::vector<std::string> parse_tuple(std::string in) {
  211. std::vector<std::string> v;
  212. const char seperator = ',';
  213. in = trim(in);
  214. if ((in.front() == '(') && (in.back() == ')'))
  215. in = in.substr(1, in.length() - 2);
  216. else
  217. throw std::runtime_error("Invalid Python tuple.");
  218. std::istringstream iss(in);
  219. for (std::string token; std::getline(iss, token, seperator);) {
  220. v.push_back(token);
  221. }
  222. return v;
  223. }
  224. template <typename T>
  225. inline std::string write_tuple(const std::vector<T> &v) {
  226. if (v.size() == 0) return "()";
  227. std::ostringstream ss;
  228. ss.imbue(std::locale("C"));
  229. if (v.size() == 1) {
  230. ss << "(" << v.front() << ",)";
  231. } else {
  232. const std::string delimiter = ", ";
  233. // v.size() > 1
  234. ss << "(";
  235. std::copy(v.begin(), v.end() - 1, std::ostream_iterator<T>(ss, delimiter.c_str()));
  236. ss << v.back();
  237. ss << ")";
  238. }
  239. return ss.str();
  240. }
  241. inline std::string write_boolean(bool b) {
  242. if (b)
  243. return "True";
  244. else
  245. return "False";
  246. }
  247. } // namespace pyparse
  248. inline header_t parse_header(std::string header) {
  249. /*
  250. The first 6 bytes are a magic string: exactly "x93NUMPY".
  251. The next 1 byte is an unsigned byte: the major version number of the file
  252. format, e.g. x01. The next 1 byte is an unsigned byte: the minor version
  253. number of the file format, e.g. x00. Note: the version of the file format
  254. is not tied to the version of the numpy package. The next 2 bytes form a
  255. little-endian unsigned short int: the length of the header data HEADER_LEN.
  256. The next HEADER_LEN bytes form the header data describing the array's
  257. format. It is an ASCII string which contains a Python literal expression of
  258. a dictionary. It is terminated by a newline ('n') and padded with spaces
  259. ('x20') to make the total length of the magic string + 4 + HEADER_LEN be
  260. evenly divisible by 16 for alignment purposes. The dictionary contains
  261. three keys:
  262. "descr" : dtype.descr
  263. An object that can be passed as an argument to the numpy.dtype()
  264. constructor to create the array's dtype. "fortran_order" : bool Whether the
  265. array data is Fortran-contiguous or not. Since Fortran-contiguous arrays
  266. are a common form of non-C-contiguity, we allow them to be written directly
  267. to disk for efficiency. "shape" : tuple of int The shape of the array. For
  268. repeatability and readability, this dictionary is formatted using
  269. pprint.pformat() so the keys are in alphabetic order.
  270. */
  271. // remove trailing newline
  272. if (header.back() != '\n') throw std::runtime_error("invalid header");
  273. header.pop_back();
  274. // parse the dictionary
  275. std::vector<std::string> keys{"descr", "fortran_order", "shape"};
  276. auto dict_map = npy::pyparse::parse_dict(header, keys);
  277. if (dict_map.size() == 0) throw std::runtime_error("invalid dictionary in header");
  278. std::string descr_s = dict_map["descr"];
  279. std::string fortran_s = dict_map["fortran_order"];
  280. std::string shape_s = dict_map["shape"];
  281. std::string descr = npy::pyparse::parse_str(descr_s);
  282. dtype_t dtype = parse_descr(descr);
  283. // convert literal Python bool to C++ bool
  284. bool fortran_order = npy::pyparse::parse_bool(fortran_s);
  285. // parse the shape tuple
  286. auto shape_v = npy::pyparse::parse_tuple(shape_s);
  287. shape_t shape;
  288. for (auto item : shape_v) {
  289. auto dim = static_cast<ndarray_len_t>(std::stoul(item));
  290. shape.push_back(dim);
  291. }
  292. return {dtype, fortran_order, shape};
  293. }
  294. inline std::string write_header_dict(const std::string &descr, bool fortran_order, const shape_t &shape) {
  295. std::string s_fortran_order = npy::pyparse::write_boolean(fortran_order);
  296. std::string shape_s = npy::pyparse::write_tuple(shape);
  297. return "{'descr': '" + descr + "', 'fortran_order': " + s_fortran_order + ", 'shape': " + shape_s + ", }";
  298. }
  299. inline void write_header(std::ostream &out, const header_t &header) {
  300. std::string header_dict = write_header_dict(header.dtype.str(), header.fortran_order, header.shape);
  301. size_t length = magic_string_length + 2 + 2 + header_dict.length() + 1;
  302. version_t version{1, 0};
  303. if (length >= 255 * 255) {
  304. length = magic_string_length + 2 + 4 + header_dict.length() + 1;
  305. version = {2, 0};
  306. }
  307. size_t padding_len = 16 - length % 16;
  308. std::string padding(padding_len, ' ');
  309. // write magic
  310. write_magic(out, version);
  311. // write header length
  312. if (version == version_t{1, 0}) {
  313. auto header_len = static_cast<uint16_t>(header_dict.length() + padding.length() + 1);
  314. std::array<uint8_t, 2> header_len_le16{static_cast<uint8_t>((header_len >> 0) & 0xff),
  315. static_cast<uint8_t>((header_len >> 8) & 0xff)};
  316. out.write(reinterpret_cast<char *>(header_len_le16.data()), 2);
  317. } else {
  318. auto header_len = static_cast<uint32_t>(header_dict.length() + padding.length() + 1);
  319. std::array<uint8_t, 4> header_len_le32{
  320. static_cast<uint8_t>((header_len >> 0) & 0xff), static_cast<uint8_t>((header_len >> 8) & 0xff),
  321. static_cast<uint8_t>((header_len >> 16) & 0xff), static_cast<uint8_t>((header_len >> 24) & 0xff)};
  322. out.write(reinterpret_cast<char *>(header_len_le32.data()), 4);
  323. }
  324. out << header_dict << padding << '\n';
  325. }
  326. inline std::string read_header(std::istream &istream) {
  327. // check magic bytes an version number
  328. version_t version = read_magic(istream);
  329. uint32_t header_length = 0;
  330. if (version == version_t{1, 0}) {
  331. std::array<uint8_t, 2> header_len_le16{};
  332. istream.read(reinterpret_cast<char *>(header_len_le16.data()), 2);
  333. header_length = (header_len_le16[0] << 0) | (header_len_le16[1] << 8);
  334. if ((magic_string_length + 2 + 2 + header_length) % 16 != 0) {
  335. // TODO(llohse): display warning
  336. }
  337. } else if (version == version_t{2, 0}) {
  338. std::array<uint8_t, 4> header_len_le32{};
  339. istream.read(reinterpret_cast<char *>(header_len_le32.data()), 4);
  340. header_length =
  341. (header_len_le32[0] << 0) | (header_len_le32[1] << 8) | (header_len_le32[2] << 16) | (header_len_le32[3] << 24);
  342. if ((magic_string_length + 2 + 4 + header_length) % 16 != 0) {
  343. // TODO(llohse): display warning
  344. }
  345. } else {
  346. throw std::runtime_error("unsupported file format version");
  347. }
  348. auto buf_v = std::vector<char>(header_length);
  349. istream.read(buf_v.data(), header_length);
  350. std::string header(buf_v.data(), header_length);
  351. return header;
  352. }
  353. inline ndarray_len_t comp_size(const shape_t &shape) {
  354. ndarray_len_t size = 1;
  355. for (ndarray_len_t i : shape) size *= i;
  356. return size;
  357. }
  358. template <typename Scalar>
  359. struct npy_data {
  360. std::vector<Scalar> data = {};
  361. shape_t shape = {};
  362. bool fortran_order = false;
  363. };
  364. template <typename Scalar>
  365. struct npy_data_ptr {
  366. const Scalar *data_ptr = nullptr;
  367. shape_t shape = {};
  368. bool fortran_order = false;
  369. };
  370. template <typename Scalar>
  371. inline npy_data<Scalar> read_npy(std::istream &in) {
  372. std::string header_s = read_header(in);
  373. // parse header
  374. header_t header = parse_header(header_s);
  375. // check if the typestring matches the given one
  376. const dtype_t dtype = dtype_map.at(std::type_index(typeid(Scalar)));
  377. if (header.dtype.tie() != dtype.tie()) {
  378. throw std::runtime_error("formatting error: typestrings not matching");
  379. }
  380. // compute the data size based on the shape
  381. auto size = static_cast<size_t>(comp_size(header.shape));
  382. npy_data<Scalar> data;
  383. data.shape = header.shape;
  384. data.fortran_order = header.fortran_order;
  385. data.data.resize(size);
  386. // read the data
  387. in.read(reinterpret_cast<char *>(data.data.data()), sizeof(Scalar) * size);
  388. return data;
  389. }
  390. template <typename Scalar>
  391. inline npy_data<Scalar> read_npy(const std::string &filename) {
  392. std::ifstream stream(filename, std::ifstream::binary);
  393. if (!stream) {
  394. throw std::runtime_error("io error: failed to open a file.");
  395. }
  396. return read_npy<Scalar>(stream);
  397. }
  398. template <typename Scalar>
  399. inline void write_npy(std::ostream &out, const npy_data<Scalar> &data) {
  400. // static_assert(has_typestring<Scalar>::value, "scalar type not
  401. // understood");
  402. const dtype_t dtype = dtype_map.at(std::type_index(typeid(Scalar)));
  403. header_t header{dtype, data.fortran_order, data.shape};
  404. write_header(out, header);
  405. auto size = static_cast<size_t>(comp_size(data.shape));
  406. out.write(reinterpret_cast<const char *>(data.data.data()), sizeof(Scalar) * size);
  407. }
  408. template <typename Scalar>
  409. inline void write_npy(const std::string &filename, const npy_data<Scalar> &data) {
  410. std::ofstream stream(filename, std::ofstream::binary);
  411. if (!stream) {
  412. throw std::runtime_error("io error: failed to open a file.");
  413. }
  414. write_npy<Scalar>(stream, data);
  415. }
  416. template <typename Scalar>
  417. inline void write_npy(std::ostream &out, const npy_data_ptr<Scalar> &data_ptr) {
  418. const dtype_t dtype = dtype_map.at(std::type_index(typeid(Scalar)));
  419. header_t header{dtype, data_ptr.fortran_order, data_ptr.shape};
  420. write_header(out, header);
  421. auto size = static_cast<size_t>(comp_size(data_ptr.shape));
  422. out.write(reinterpret_cast<const char *>(data_ptr.data_ptr), sizeof(Scalar) * size);
  423. }
  424. template <typename Scalar>
  425. inline void write_npy(const std::string &filename, const npy_data_ptr<Scalar> &data_ptr) {
  426. std::ofstream stream(filename, std::ofstream::binary);
  427. if (!stream) {
  428. throw std::runtime_error("io error: failed to open a file.");
  429. }
  430. write_npy<Scalar>(stream, data_ptr);
  431. }
  432. // old interface
  433. // NOLINTBEGIN(*-avoid-c-arrays)
  434. template <typename Scalar>
  435. inline void SaveArrayAsNumpy(const std::string &filename, bool fortran_order, unsigned int n_dims,
  436. const unsigned long shape[], const Scalar *data) {
  437. const npy_data_ptr<Scalar> ptr{data, {shape, shape + n_dims}, fortran_order};
  438. write_npy<Scalar>(filename, ptr);
  439. }
  440. template <typename Scalar>
  441. inline void SaveArrayAsNumpy(const std::string &filename, bool fortran_order, unsigned int n_dims,
  442. const unsigned long shape[], const std::vector<Scalar> &data) {
  443. SaveArrayAsNumpy(filename, fortran_order, n_dims, shape, data.data());
  444. }
  445. template <typename Scalar>
  446. inline void LoadArrayFromNumpy(const std::string &filename, std::vector<unsigned long> &shape, bool &fortran_order,
  447. std::vector<Scalar> &data) {
  448. const npy_data<Scalar> n_data = read_npy<Scalar>(filename);
  449. shape = n_data.shape;
  450. fortran_order = n_data.fortran_order;
  451. std::copy(n_data.data.begin(), n_data.data.end(), std::back_inserter(data));
  452. }
  453. template <typename Scalar>
  454. inline void LoadArrayFromNumpy(const std::string &filename, std::vector<unsigned long> &shape,
  455. std::vector<Scalar> &data) {
  456. bool fortran_order = false;
  457. LoadArrayFromNumpy<Scalar>(filename, shape, fortran_order, data);
  458. }
  459. // NOLINTEND(*-avoid-c-arrays)
  460. } // namespace npy
  461. #endif // NPY_HPP_