Alexandria  2.19
Please provide a description of the project.
NpyReader.icpp
Go to the documentation of this file.
1 /*
2  * Copyright (C) 2012-2021 Euclid Science Ground Segment
3  *
4  * This library is free software; you can redistribute it and/or modify it under
5  * the terms of the GNU Lesser General Public License as published by the Free
6  * Software Foundation; either version 3.0 of the License, or (at your option)
7  * any later version.
8  *
9  * This library is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12  * details.
13  *
14  * You should have received a copy of the GNU Lesser General Public License
15  * along with this library; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18 
19 #ifdef NPY_IMPL
20 
21 #include "NdArray/NdArray.h"
22 #include "NpyCommon.h"
23 #include <ElementsKernel/Exception.h>
24 #include <cstring>
25 #include <istream>
26 
27 namespace Euclid {
28 namespace NdArray {
29 
30 using boost::endian::little_uint16_t;
31 using boost::endian::little_uint32_t;
32 
33 template <typename T>
34 NdArray<T> readNpy(std::istream& input) {
35  std::string dtype;
36  size_t n_elements;
37  std::vector<size_t> shape;
38  std::vector<std::string> attr_names;
39 
40  readNpyHeader(input, dtype, shape, attr_names, n_elements);
41  if (dtype != NpyDtype<T>::str)
42  throw Elements::Exception() << "Can not cast " << dtype << " into " << typeid(T).name();
43 
44  if (!attr_names.empty()) {
45  n_elements *= attr_names.size();
46  }
47 
48  std::vector<T> data(n_elements);
49  input.read(reinterpret_cast<char*>(&data[0]), sizeof(T) * data.size());
50  return {shape, attr_names, std::move(data)};
51 }
52 
53 } // end of namespace NdArray
54 } // end of namespace Euclid
55 
56 #endif // NPY_IMPL