Compute Library
 20.02.1
Helpers.inl
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2016-2020 ARM Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include "arm_compute/core/Error.h"
26 
27 #include <cmath>
28 #include <numeric>
29 
30 namespace arm_compute
31 {
32 inline uint8_t pixel_area_c1u8_clamp(const uint8_t *first_pixel_ptr, size_t stride, size_t width, size_t height, float wr, float hr, int x, int y)
33 {
34  ARM_COMPUTE_ERROR_ON(first_pixel_ptr == nullptr);
35 
36  // Calculate sampling position
37  float in_x = (x + 0.5f) * wr - 0.5f;
38  float in_y = (y + 0.5f) * hr - 0.5f;
39 
40  // Get bounding box offsets
41  int x_from = std::floor(x * wr - 0.5f - in_x);
42  int y_from = std::floor(y * hr - 0.5f - in_y);
43  int x_to = std::ceil((x + 1) * wr - 0.5f - in_x);
44  int y_to = std::ceil((y + 1) * hr - 0.5f - in_y);
45 
46  // Clamp position to borders
47  in_x = std::max(-1.f, std::min(in_x, static_cast<float>(width)));
48  in_y = std::max(-1.f, std::min(in_y, static_cast<float>(height)));
49 
50  // Clamp bounding box offsets to borders
51  x_from = ((in_x + x_from) < -1) ? -1 : x_from;
52  y_from = ((in_y + y_from) < -1) ? -1 : y_from;
53  x_to = ((in_x + x_to) > width) ? (width - in_x) : x_to;
54  y_to = ((in_y + y_to) > height) ? (height - in_y) : y_to;
55 
56  // Get pixel index
57  const int xi = std::floor(in_x);
58  const int yi = std::floor(in_y);
59 
60  // Bounding box elements in each dimension
61  const int x_elements = (x_to - x_from + 1);
62  const int y_elements = (y_to - y_from + 1);
63  ARM_COMPUTE_ERROR_ON(x_elements == 0 || y_elements == 0);
64 
65  // Sum pixels in area
66  int sum = 0;
67  for(int j = yi + y_from, je = yi + y_to; j <= je; ++j)
68  {
69  const uint8_t *ptr = first_pixel_ptr + j * stride + xi + x_from;
70  sum = std::accumulate(ptr, ptr + x_elements, sum);
71  }
72 
73  // Return average
74  return sum / (x_elements * y_elements);
75 }
76 
77 template <size_t dimension>
78 struct IncrementIterators
79 {
80  template <typename T, typename... Ts>
81  static void unroll(T &&it, Ts &&... iterators)
82  {
83  auto increment = [](T && it)
84  {
85  it.increment(dimension);
86  };
87  utility::for_each(increment, std::forward<T>(it), std::forward<Ts>(iterators)...);
88  }
89  static void unroll()
90  {
91  // End of recursion
92  }
93 };
94 
95 template <size_t dim>
96 struct ForEachDimension
97 {
98  template <typename L, typename... Ts>
99  static void unroll(const Window &w, Coordinates &id, L &&lambda_function, Ts &&... iterators)
100  {
101  const auto &d = w[dim - 1];
102 
103  for(auto v = d.start(); v < d.end(); v += d.step(), IncrementIterators < dim - 1 >::unroll(iterators...))
104  {
105  id.set(dim - 1, v);
106  ForEachDimension < dim - 1 >::unroll(w, id, lambda_function, iterators...);
107  }
108  }
109 };
110 
111 template <>
112 struct ForEachDimension<0>
113 {
114  template <typename L, typename... Ts>
115  static void unroll(const Window &w, Coordinates &id, L &&lambda_function, Ts &&... iterators)
116  {
117  ARM_COMPUTE_UNUSED(w, iterators...);
118  lambda_function(id);
119  }
120 };
121 
122 template <typename L, typename... Ts>
123 inline void execute_window_loop(const Window &w, L &&lambda_function, Ts &&... iterators)
124 {
125  w.validate();
126 
127  for(unsigned int i = 0; i < Coordinates::num_max_dimensions; ++i)
128  {
129  ARM_COMPUTE_ERROR_ON(w[i].step() == 0);
130  }
131 
132  Coordinates id;
133  ForEachDimension<Coordinates::num_max_dimensions>::unroll(w, id, std::forward<L>(lambda_function), std::forward<Ts>(iterators)...);
134 }
135 
136 inline constexpr Iterator::Iterator()
137  : _ptr(nullptr), _dims()
138 {
139 }
140 
141 inline Iterator::Iterator(const ITensor *tensor, const Window &win)
142  : Iterator()
143 {
144  ARM_COMPUTE_ERROR_ON(tensor == nullptr);
145  ARM_COMPUTE_ERROR_ON(tensor->info() == nullptr);
146 
147  const ITensorInfo *info = tensor->info();
148  const Strides &strides = info->strides_in_bytes();
149 
150  _ptr = tensor->buffer() + info->offset_first_element_in_bytes();
151 
152  //Initialize the stride for each dimension and calculate the position of the first element of the iteration:
153  for(unsigned int n = 0; n < info->num_dimensions(); ++n)
154  {
155  _dims[n]._stride = win[n].step() * strides[n];
156  std::get<0>(_dims)._dim_start += strides[n] * win[n].start();
157  }
158 
159  //Copy the starting point to all the dimensions:
160  for(unsigned int n = 1; n < Coordinates::num_max_dimensions; ++n)
161  {
162  _dims[n]._dim_start = std::get<0>(_dims)._dim_start;
163  }
164 
165  ARM_COMPUTE_ERROR_ON_WINDOW_DIMENSIONS_GTE(win, info->num_dimensions());
166 }
167 
168 inline void Iterator::increment(const size_t dimension)
169 {
171 
172  _dims[dimension]._dim_start += _dims[dimension]._stride;
173 
174  for(unsigned int n = 0; n < dimension; ++n)
175  {
176  _dims[n]._dim_start = _dims[dimension]._dim_start;
177  }
178 }
179 
180 inline constexpr int Iterator::offset() const
181 {
182  return _dims.at(0)._dim_start;
183 }
184 
185 inline constexpr uint8_t *Iterator::ptr() const
186 {
187  return _ptr + _dims.at(0)._dim_start;
188 }
189 
190 inline void Iterator::reset(const size_t dimension)
191 {
193 
194  _dims[dimension]._dim_start = _dims[dimension + 1]._dim_start;
195 
196  for(unsigned int n = 0; n < dimension; ++n)
197  {
198  _dims[n]._dim_start = _dims[dimension]._dim_start;
199  }
200 }
201 
203  const TensorShape &shape,
204  int num_channels,
206  QuantizationInfo quantization_info)
207 {
208  if(info.tensor_shape().total_size() == 0)
209  {
210  info.set_data_type(data_type);
211  info.set_num_channels(num_channels);
212  info.set_tensor_shape(shape);
213  info.set_quantization_info(quantization_info);
214  return true;
215  }
216 
217  return false;
218 }
219 
220 inline bool auto_init_if_empty(ITensorInfo &info_sink, const ITensorInfo &info_source)
221 {
222  if(info_sink.tensor_shape().total_size() == 0)
223  {
224  info_sink.set_data_type(info_source.data_type());
225  info_sink.set_num_channels(info_source.num_channels());
226  info_sink.set_tensor_shape(info_source.tensor_shape());
227  info_sink.set_quantization_info(info_source.quantization_info());
228  info_sink.set_data_layout(info_source.data_layout());
229  return true;
230  }
231 
232  return false;
233 }
234 
236 {
237  if(info.tensor_shape().total_size() == 0)
238  {
239  info.set_tensor_shape(shape);
240  return true;
241  }
242 
243  return false;
244 }
245 
247 {
248  if(info.data_type() == DataType::UNKNOWN)
249  {
250  info.set_format(format);
251  return true;
252  }
253 
254  return false;
255 }
256 
258 {
259  if(info.data_type() == DataType::UNKNOWN)
260  {
261  info.set_data_type(data_type);
262  return true;
263  }
264 
265  return false;
266 }
267 
269 {
270  if(info.data_layout() == DataLayout::UNKNOWN)
271  {
272  info.set_data_layout(data_layout);
273  return true;
274  }
275 
276  return false;
277 }
278 
280 {
281  if(info.quantization_info().empty() && (is_data_type_quantized_asymmetric(info.data_type())))
282  {
283  info.set_quantization_info(quantization_info);
284  return true;
285  }
286 
287  return false;
288 }
289 
290 inline Coordinates index2coords(const TensorShape &shape, int index)
291 {
292  int num_elements = shape.total_size();
293 
294  ARM_COMPUTE_ERROR_ON_MSG(index < 0 || index >= num_elements, "Index has to be in [0, num_elements]!");
295  ARM_COMPUTE_ERROR_ON_MSG(num_elements == 0, "Cannot create coordinate from empty shape!");
296 
297  Coordinates coord{ 0 };
298 
299  for(int d = shape.num_dimensions() - 1; d >= 0; --d)
300  {
301  num_elements /= shape[d];
302  coord.set(d, index / num_elements);
303  index %= num_elements;
304  }
305 
306  return coord;
307 }
308 
309 inline int coords2index(const TensorShape &shape, const Coordinates &coord)
310 {
311  int num_elements = shape.total_size();
312  ARM_COMPUTE_UNUSED(num_elements);
313  ARM_COMPUTE_ERROR_ON_MSG(num_elements == 0, "Cannot create linear index from empty shape!");
314 
315  int index = 0;
316  int stride = 1;
317 
318  for(unsigned int d = 0; d < coord.num_dimensions(); ++d)
319  {
320  index += coord[d] * stride;
321  stride *= shape[d];
322  }
323 
324  return index;
325 }
326 
327 inline size_t get_data_layout_dimension_index(const DataLayout data_layout, const DataLayoutDimension data_layout_dimension)
328 {
329  ARM_COMPUTE_ERROR_ON_MSG(data_layout == DataLayout::UNKNOWN, "Cannot retrieve the dimension index for an unknown layout!");
330 
331  /* Return the index based on the data layout
332  * [N C H W]
333  * [3 2 1 0]
334  * [N H W C]
335  */
336  switch(data_layout_dimension)
337  {
339  return (data_layout == DataLayout::NCHW) ? 2 : 0;
340  break;
342  return (data_layout == DataLayout::NCHW) ? 1 : 2;
343  break;
345  return (data_layout == DataLayout::NCHW) ? 0 : 1;
346  break;
348  return 3;
349  break;
350  default:
351  break;
352  }
353  ARM_COMPUTE_ERROR("Data layout index not supported!");
354 }
355 
357 {
358  ARM_COMPUTE_ERROR_ON_MSG(data_layout == DataLayout::UNKNOWN, "Cannot retrieve the dimension index for an unknown layout!");
359 
360  /* Return the index based on the data layout
361  * [N C H W]
362  * [3 2 1 0]
363  * [N H W C]
364  */
365  switch(index)
366  {
367  case 0:
369  break;
370  case 1:
372  break;
373  case 2:
375  break;
376  case 3:
378  break;
379  default:
380  ARM_COMPUTE_ERROR("Index value not supported!");
381  break;
382  }
383 }
384 } // namespace arm_compute
virtual ITensorInfo & set_num_channels(int num_channels)=0
Set the number of channels to the specified value.
SimpleTensor< float > w
Definition: DFT.cpp:156
Shape of a tensor.
Definition: TensorShape.h:39
const DataLayout data_layout
Definition: Im2Col.cpp:146
Coordinates index2coords(const TensorShape &shape, int index)
Convert a linear index into n-dimensional coordinates.
Definition: Helpers.inl:290
void increment(size_t dimension)
Increment the iterator along the specified dimension of the step value associated to the dimension.
Definition: Helpers.inl:168
#define ARM_COMPUTE_ERROR(msg)
Print the given message then throw an std::runtime_error.
Definition: Error.h:352
virtual ITensorInfo & set_tensor_shape(const TensorShape &shape)=0
Set the shape of an already initialized tensor.
DataLayoutDimension
[DataLayout enum definition]
Definition: Types.h:126
DATA_TYPE sum(__global const DATA_TYPE *input)
Calculate sum of a vector.
virtual DataType data_type() const =0
Data type used for each element of the tensor.
#define ARM_COMPUTE_ERROR_ON(cond)
If the condition is true then an error message is printed and an exception thrown.
Definition: Error.h:466
Store the tensor's metadata.
Definition: ITensorInfo.h:40
bool set_data_layout_if_unknown(ITensorInfo &info, DataLayout data_layout)
Set the data layout to the specified value if the current data layout is unknown.
Definition: Helpers.inl:268
Interface for NEON tensor.
Definition: ITensor.h:36
bool set_data_type_if_unknown(ITensorInfo &info, DataType data_type)
Set the data type and number of channels to the specified value if the current data type is unknown.
Definition: Helpers.inl:257
Copyright (c) 2017-2020 ARM Limited.
bool auto_init_if_empty(ITensorInfo &info, const TensorShape &shape, int num_channels, DataType data_type, QuantizationInfo quantization_info=QuantizationInfo())
Auto initialize the tensor info (shape, number of channels and data type) if the current assignment i...
Definition: Helpers.inl:202
Quantization information.
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
virtual const TensorShape & tensor_shape() const =0
Size for each dimension of the tensor.
virtual ITensorInfo & set_data_layout(const DataLayout &data_layout)=0
Set the data layout of the tensor.
Format
Image colour formats.
Definition: Types.h:53
constexpr int offset() const
Return the offset in bytes from the first element to the current position of the iterator.
Definition: Helpers.inl:180
#define ARM_COMPUTE_ERROR_ON_MSG(cond, msg)
Definition: Error.h:456
Coordinates of an item.
Definition: Coordinates.h:37
virtual uint8_t * buffer() const =0
Interface to be implemented by the child class to return a pointer to CPU memory.
size_t total_size() const
Collapses all dimensions to a single linear total size.
Definition: TensorShape.h:171
virtual ITensorInfo * info() const =0
Interface to be implemented by the child class to return the tensor's metadata.
int coords2index(const TensorShape &shape, const Coordinates &coord)
Convert n-dimensional coordinates into a linear index.
Definition: Helpers.inl:309
constexpr uint8_t * ptr() const
Return a pointer to the current pixel.
Definition: Helpers.inl:185
virtual ITensorInfo & set_quantization_info(const QuantizationInfo &quantization_info)=0
Set the quantization settings (scale and offset) of the tensor.
DataLayoutDimension get_index_data_layout_dimension(const DataLayout data_layout, const size_t index)
Get the DataLayoutDimension of a given index and layout.
Definition: Helpers.inl:356
virtual ITensorInfo & set_data_type(DataType data_type)=0
Set the data type to the specified value.
virtual QuantizationInfo quantization_info() const =0
Get the quantization settings (scale and offset) of the tensor.
constexpr Iterator()
Default constructor to create an empty iterator.
Definition: Helpers.inl:136
Num samples, channels, height, width.
#define ARM_COMPUTE_ERROR_ON_WINDOW_DIMENSIONS_GTE(w, md)
Definition: Validate.h:263
void for_each(F &&)
Base case of for_each.
Definition: Utility.h:108
bool is_data_type_quantized_asymmetric(DataType dt)
Check if a given data type is of asymmetric quantized type.
Definition: Utils.h:1139
Strides of an item in bytes.
Definition: Strides.h:37
uint8_t pixel_area_c1u8_clamp(const uint8_t *first_pixel_ptr, size_t stride, size_t width, size_t height, float wr, float hr, int x, int y)
Return the pixel at (x,y) using area interpolation by clamping when out of borders.
Definition: Helpers.inl:32
void reset(size_t dimension)
Move the iterator back to the beginning of the specified dimension.
Definition: Helpers.inl:190
unsigned int num_dimensions() const
Returns the effective dimensionality of the tensor.
Definition: Dimensions.h:122
bool set_shape_if_empty(ITensorInfo &info, const TensorShape &shape)
Set the shape to the specified value if the current assignment is empty.
Definition: Helpers.inl:235
__kernel void accumulate(__global uchar *input_ptr, uint input_stride_x, uint input_step_x, uint input_stride_y, uint input_step_y, uint input_offset_first_element_in_bytes, __global uchar *accu_ptr, uint accu_stride_x, uint accu_step_x, uint accu_stride_y, uint accu_step_y, uint accu_offset_first_element_in_bytes)
This function accumulates an input image into output image.
Definition: accumulate.cl:41
void execute_window_loop(const Window &w, L &&lambda_function, Ts &&... iterators)
Iterate through the passed window, automatically adjusting the iterators and calling the lambda_funct...
Definition: Helpers.inl:123
bool set_format_if_unknown(ITensorInfo &info, Format format)
Set the format, data type and number of channels to the specified value if the current data type is u...
Definition: Helpers.inl:246
size_t get_data_layout_dimension_index(const DataLayout data_layout, const DataLayoutDimension data_layout_dimension)
Get the index of the given dimension.
Definition: Helpers.inl:327
static constexpr size_t num_max_dimensions
Number of dimensions the tensor has.
Definition: Dimensions.h:45
Iterator updated by execute_window_loop for each window element.
Definition: Helpers.h:318
DataType
Available data types.
Definition: Types.h:75
DataLayout
[DataLayout enum definition]
Definition: Types.h:117
bool set_quantization_info_if_empty(ITensorInfo &info, QuantizationInfo quantization_info)
Set the quantization info to the specified value if the current quantization info is empty and the da...
Definition: Helpers.inl:279
Describe a multidimensional execution window.
Definition: Window.h:39
virtual size_t num_channels() const =0
The number of channels for each tensor element.
virtual DataLayout data_layout() const =0
Get the data layout of the tensor.