1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_PACKAGES_MODULES_NEURALNETWORKS_COMMON_INDEXED_SHAPE_WRAPPER_H
18 #define ANDROID_PACKAGES_MODULES_NEURALNETWORKS_COMMON_INDEXED_SHAPE_WRAPPER_H
19 
20 #include <vector>
21 
22 #include "OperationsExecutionUtils.h"
23 
24 namespace android {
25 namespace nn {
26 
27 // A wrapper over a Shape class implementing some indexing logic for a wrapped
28 // shape.
29 // To get an offset for an element in a tensor from vector index, one needs to
30 // calculate strides first. This class removes the need to recalculate strides
31 // for every indexing and also provides some utility functions.
32 class IndexedShapeWrapper {
33    public:
34     IndexedShapeWrapper(const Shape& wrapped_shape);
35 
36     // Calculates the next index in a lexicograpical order for a wrapped shape
37     // inplace. Only accepts valid index for a given shape as an input.
38     // Sets lastIndex to true if the received index was the last in a
39     // lexicographical order for a given shape. In this case, index stays the
40     // same.
41     bool nextIndexInplace(std::vector<uint32_t>* index, bool* lastIndex) const;
42 
43     // Given an index as a vector with per-dimension indices, calculates an
44     // offset of the element in a flattened tensor.
45     bool indexToFlatIndex(const std::vector<uint32_t>& index, uint32_t* flatIndex) const;
46 
47     // Same as indexToFlatIndex, only ignores first dimensions of an index if
48     // they are not present in the shape. Also ignores dimensions of a shape of
49     // size 1.
50     // For example:
51     //    for shape:    [3, 1, 2]
52     //    and index: [4, 2, 5, 1]
53     // the function will ignore dimensions with indices 4 and 5 and set
54     // flatIndex to 5 as a result.
55     bool broadcastedIndexToFlatIndex(const std::vector<uint32_t>& index, uint32_t* flatIndex) const;
56 
57    private:
58     const Shape* const shape;
59     std::vector<uint32_t> strides;
60 
61     bool isValid(const std::vector<uint32_t>& index) const;
62 };
63 
64 }  // namespace nn
65 }  // namespace android
66 
67 #endif  // ANDROID_PACKAGES_MODULES_NEURALNETWORKS_COMMON_INDEXED_SHAPE_WRAPPER_H
68