f9c7063709801c60470bbe2f3ecace84795c6356
[platform/core/ml/nnfw.git] / compute / cker / include / cker / eigen / Utils.h
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
3  * Copyright 2018 The TensorFlow Authors. All Rights Reserved.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #ifndef __NNFW_CKER_EIGEN_UTILS_H__
19 #define __NNFW_CKER_EIGEN_UTILS_H__
20
21 #include <Eigen/Core>
22 #include <type_traits>
23 #include "cker/Shape.h"
24
25 namespace nnfw
26 {
27 namespace cker
28 {
29
30 // Make a local VectorMap typedef allowing to map a float array
31 // as a Eigen vector expression. The std::conditional here is to
32 // construct the suitable Eigen type for the constness of the
33 // data. Indeed, for const data, we need to produce
34 //    Eigen::Map<const Eigen::Matrix<float, ...>>
35 // and not the more straightforward
36 //    Eigen::Map<Eigen::Matrix<const float, ...>>
37 template <typename Scalar>
38 using VectorMap = typename std::conditional<
39     std::is_const<Scalar>::value,
40     Eigen::Map<const Eigen::Matrix<typename std::remove_const<Scalar>::type, Eigen::Dynamic, 1>>,
41     Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, 1>>>::type;
42
43 template <typename Scalar> VectorMap<Scalar> MapAsVector(Scalar *data, const Shape &shape)
44 {
45   const int size = shape.FlatSize();
46   return VectorMap<Scalar>(data, size, 1);
47 }
48
49 // Make a local VectorMap typedef allowing to map a float array
50 // as a Eigen matrix expression. The same explanation as for VectorMap
51 // above also applies here.
52 template <typename Scalar>
53 using MatrixMap = typename std::conditional<
54     std::is_const<Scalar>::value,
55     Eigen::Map<const Eigen::Matrix<typename std::remove_const<Scalar>::type, Eigen::Dynamic,
56                                    Eigen::Dynamic>>,
57     Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>>>::type;
58
59 template <typename Scalar>
60 MatrixMap<Scalar> MapAsMatrixWithLastDimAsRows(Scalar *data, const Shape &shape)
61 {
62   const int dims_count = shape.DimensionsCount();
63   const int rows = shape.Dims(dims_count - 1);
64   const int cols = FlatSizeSkipDim(shape, dims_count - 1);
65   return MatrixMap<Scalar>(data, rows, cols);
66 }
67
68 } // namespace cker
69 } // namespace nnfw
70
71 #endif // __NNFW_CKER_EIGEN_UTILS_H__