Compute Library
 20.05
Utils.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-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 #ifndef ARM_COMPUTE_TEST_UTILS_H
25 #define ARM_COMPUTE_TEST_UTILS_H
26 
28 #include "arm_compute/core/Error.h"
34 #include "arm_compute/core/Types.h"
35 #include "support/StringSupport.h"
37 
38 #ifdef ARM_COMPUTE_CL
41 #endif /* ARM_COMPUTE_CL */
42 
43 #ifdef ARM_COMPUTE_GC
46 #endif /* ARM_COMPUTE_GC */
47 
48 #include <cmath>
49 #include <cstddef>
50 #include <limits>
51 #include <memory>
52 #include <random>
53 #include <sstream>
54 #include <string>
55 #include <type_traits>
56 #include <vector>
57 
60 
61 namespace arm_compute
62 {
63 #ifdef ARM_COMPUTE_CL
64 class CLTensor;
65 #endif /* ARM_COMPUTE_CL */
66 namespace test
67 {
68 /** Round floating-point value with half value rounding to positive infinity.
69  *
70  * @param[in] value floating-point value to be rounded.
71  *
72  * @return Floating-point value of rounded @p value.
73  */
74 template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
75 inline T round_half_up(T value)
76 {
77  return std::floor(value + 0.5f);
78 }
79 
80 /** Round floating-point value with half value rounding to nearest even.
81  *
82  * @param[in] value floating-point value to be rounded.
83  * @param[in] epsilon precision.
84  *
85  * @return Floating-point value of rounded @p value.
86  */
87 template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
89 {
90  T positive_value = std::abs(value);
91  T ipart = 0;
92  std::modf(positive_value, &ipart);
93  // If 'value' is exactly halfway between two integers
94  if(std::abs(positive_value - (ipart + 0.5f)) < epsilon)
95  {
96  // If 'ipart' is even then return 'ipart'
97  if(std::fmod(ipart, 2.f) < epsilon)
98  {
99  return support::cpp11::copysign(ipart, value);
100  }
101  // Else return the nearest even integer
102  return support::cpp11::copysign(std::ceil(ipart + 0.5f), value);
103  }
104  // Otherwise use the usual round to closest
105  return support::cpp11::copysign(support::cpp11::round(positive_value), value);
106 }
107 
108 namespace traits
109 {
110 // *INDENT-OFF*
111 // clang-format off
112 /** Promote a type */
113 template <typename T> struct promote { };
114 /** Promote uint8_t to uint16_t */
115 template <> struct promote<uint8_t> { using type = uint16_t; /**< Promoted type */ };
116 /** Promote int8_t to int16_t */
117 template <> struct promote<int8_t> { using type = int16_t; /**< Promoted type */ };
118 /** Promote uint16_t to uint32_t */
119 template <> struct promote<uint16_t> { using type = uint32_t; /**< Promoted type */ };
120 /** Promote int16_t to int32_t */
121 template <> struct promote<int16_t> { using type = int32_t; /**< Promoted type */ };
122 /** Promote uint32_t to uint64_t */
123 template <> struct promote<uint32_t> { using type = uint64_t; /**< Promoted type */ };
124 /** Promote int32_t to int64_t */
125 template <> struct promote<int32_t> { using type = int64_t; /**< Promoted type */ };
126 /** Promote float to float */
127 template <> struct promote<float> { using type = float; /**< Promoted type */ };
128 /** Promote half to half */
129 template <> struct promote<half> { using type = half; /**< Promoted type */ };
130 
131 /** Get promoted type */
132 template <typename T>
133 using promote_t = typename promote<T>::type;
134 
135 template <typename T>
136 using make_signed_conditional_t = typename std::conditional<std::is_integral<T>::value, std::make_signed<T>, std::common_type<T>>::type;
137 
138 template <typename T>
139 using make_unsigned_conditional_t = typename std::conditional<std::is_integral<T>::value, std::make_unsigned<T>, std::common_type<T>>::type;
140 
141 // clang-format on
142 // *INDENT-ON*
143 }
144 
145 /** Look up the format corresponding to a channel.
146  *
147  * @param[in] channel Channel type.
148  *
149  * @return Format that contains the given channel.
150  */
152 {
153  switch(channel)
154  {
155  case Channel::R:
156  case Channel::G:
157  case Channel::B:
158  return Format::RGB888;
159  default:
160  throw std::runtime_error("Unsupported channel");
161  }
162 }
163 
164 /** Return the format of a channel.
165  *
166  * @param[in] channel Channel type.
167  *
168  * @return Format of the given channel.
169  */
171 {
172  switch(channel)
173  {
174  case Channel::R:
175  case Channel::G:
176  case Channel::B:
177  return Format::U8;
178  default:
179  throw std::runtime_error("Unsupported channel");
180  }
181 }
182 
183 /** Base case of foldl.
184  *
185  * @return value.
186  */
187 template <typename F, typename T>
188 inline T foldl(F &&, const T &value)
189 {
190  return value;
191 }
192 
193 /** Base case of foldl.
194  *
195  * @return func(value1, value2).
196  */
197 template <typename F, typename T, typename U>
198 inline auto foldl(F &&func, T &&value1, U &&value2) -> decltype(func(value1, value2))
199 {
200  return func(value1, value2);
201 }
202 
203 /** Fold left.
204  *
205  * @param[in] func Binary function to be called.
206  * @param[in] initial Initial value.
207  * @param[in] value Argument passed to the function.
208  * @param[in] values Remaining arguments.
209  */
210 template <typename F, typename I, typename T, typename... Vs>
211 inline I foldl(F &&func, I &&initial, T &&value, Vs &&... values)
212 {
213  return foldl(std::forward<F>(func), func(std::forward<I>(initial), std::forward<T>(value)), std::forward<Vs>(values)...);
214 }
215 
216 /** Create a valid region based on tensor shape, border mode and border size
217  *
218  * @param[in] a_shape Shape used as size of the valid region.
219  * @param[in] border_undefined (Optional) Boolean indicating if the border mode is undefined.
220  * @param[in] border_size (Optional) Border size used to specify the region to exclude.
221  *
222  * @return A valid region starting at (0, 0, ...) with size of @p shape if @p border_undefined is false; otherwise
223  * return A valid region starting at (@p border_size.left, @p border_size.top, ...) with reduced size of @p shape.
224  */
225 inline ValidRegion shape_to_valid_region(const TensorShape &a_shape, bool border_undefined = false, BorderSize border_size = BorderSize(0))
226 {
227  ValidRegion valid_region{ Coordinates(), a_shape };
228 
229  Coordinates &anchor = valid_region.anchor;
231 
232  if(border_undefined)
233  {
234  ARM_COMPUTE_ERROR_ON(shape.num_dimensions() < 2);
235 
236  anchor.set(0, border_size.left);
237  anchor.set(1, border_size.top);
238 
239  const int valid_shape_x = std::max(0, static_cast<int>(shape.x()) - static_cast<int>(border_size.left) - static_cast<int>(border_size.right));
240  const int valid_shape_y = std::max(0, static_cast<int>(shape.y()) - static_cast<int>(border_size.top) - static_cast<int>(border_size.bottom));
241 
242  shape.set(0, valid_shape_x);
243  shape.set(1, valid_shape_y);
244  }
245 
246  return valid_region;
247 }
248 
249 /** Create a valid region for Gaussian Pyramid Half based on tensor shape and valid region at level "i - 1" and border mode
250  *
251  * @note The border size is 2 in case of Gaussian Pyramid Half
252  *
253  * @param[in] a_shape Shape used at level "i - 1" of Gaussian Pyramid Half
254  * @param[in] a_valid_region Valid region used at level "i - 1" of Gaussian Pyramid Half
255  * @param[in] border_undefined (Optional) Boolean indicating if the border mode is undefined.
256  *
257  * return The valid region for the level "i" of Gaussian Pyramid Half
258  */
259 inline ValidRegion shape_to_valid_region_gaussian_pyramid_half(const TensorShape &a_shape, const ValidRegion &a_valid_region, bool border_undefined = false)
260 {
261  constexpr int border_size = 2;
262 
263  ValidRegion valid_region{ Coordinates(), a_shape };
264 
265  Coordinates &anchor = valid_region.anchor;
267 
268  // Compute tensor shape for level "i" of Gaussian Pyramid Half
269  // dst_width = (src_width + 1) * 0.5f
270  // dst_height = (src_height + 1) * 0.5f
271  shape.set(0, (a_shape[0] + 1) * 0.5f);
272  shape.set(1, (a_shape[1] + 1) * 0.5f);
273 
274  if(border_undefined)
275  {
276  ARM_COMPUTE_ERROR_ON(shape.num_dimensions() < 2);
277 
278  // Compute the left and top invalid borders
279  float invalid_border_left = static_cast<float>(a_valid_region.anchor.x() + border_size) / 2.0f;
280  float invalid_border_top = static_cast<float>(a_valid_region.anchor.y() + border_size) / 2.0f;
281 
282  // For the new anchor point we can have 2 cases:
283  // 1) If the width/height of the tensor shape is odd, we have to take the ceil value of (a_valid_region.anchor.x() + border_size) / 2.0f or (a_valid_region.anchor.y() + border_size / 2.0f
284  // 2) If the width/height of the tensor shape is even, we have to take the floor value of (a_valid_region.anchor.x() + border_size) / 2.0f or (a_valid_region.anchor.y() + border_size) / 2.0f
285  // In this manner we should be able to propagate correctly the valid region along all levels of the pyramid
286  invalid_border_left = (a_shape[0] % 2) ? std::ceil(invalid_border_left) : std::floor(invalid_border_left);
287  invalid_border_top = (a_shape[1] % 2) ? std::ceil(invalid_border_top) : std::floor(invalid_border_top);
288 
289  // Set the anchor point
290  anchor.set(0, static_cast<int>(invalid_border_left));
291  anchor.set(1, static_cast<int>(invalid_border_top));
292 
293  // Compute shape
294  // Calculate the right and bottom invalid borders at the previous level of the pyramid
295  const float prev_invalid_border_right = static_cast<float>(a_shape[0] - (a_valid_region.anchor.x() + a_valid_region.shape[0]));
296  const float prev_invalid_border_bottom = static_cast<float>(a_shape[1] - (a_valid_region.anchor.y() + a_valid_region.shape[1]));
297 
298  // Calculate the right and bottom invalid borders at the current level of the pyramid
299  const float invalid_border_right = std::ceil((prev_invalid_border_right + static_cast<float>(border_size)) / 2.0f);
300  const float invalid_border_bottom = std::ceil((prev_invalid_border_bottom + static_cast<float>(border_size)) / 2.0f);
301 
302  const int valid_shape_x = std::max(0, static_cast<int>(shape.x()) - static_cast<int>(invalid_border_left) - static_cast<int>(invalid_border_right));
303  const int valid_shape_y = std::max(0, static_cast<int>(shape.y()) - static_cast<int>(invalid_border_top) - static_cast<int>(invalid_border_bottom));
304 
305  shape.set(0, valid_shape_x);
306  shape.set(1, valid_shape_y);
307  }
308 
309  return valid_region;
310 }
311 
312 /** Create a valid region for Laplacian Pyramid based on tensor shape and valid region at level "i - 1" and border mode
313  *
314  * @note The border size is 2 in case of Laplacian Pyramid
315  *
316  * @param[in] a_shape Shape used at level "i - 1" of Laplacian Pyramid
317  * @param[in] a_valid_region Valid region used at level "i - 1" of Laplacian Pyramid
318  * @param[in] border_undefined (Optional) Boolean indicating if the border mode is undefined.
319  *
320  * return The valid region for the level "i" of Laplacian Pyramid
321  */
322 inline ValidRegion shape_to_valid_region_laplacian_pyramid(const TensorShape &a_shape, const ValidRegion &a_valid_region, bool border_undefined = false)
323 {
324  ValidRegion valid_region = shape_to_valid_region_gaussian_pyramid_half(a_shape, a_valid_region, border_undefined);
325 
326  if(border_undefined)
327  {
328  const BorderSize gaussian5x5_border(2);
329 
330  auto border_left = static_cast<int>(gaussian5x5_border.left);
331  auto border_right = static_cast<int>(gaussian5x5_border.right);
332  auto border_top = static_cast<int>(gaussian5x5_border.top);
333  auto border_bottom = static_cast<int>(gaussian5x5_border.bottom);
334 
335  valid_region.anchor.set(0, valid_region.anchor[0] + border_left);
336  valid_region.anchor.set(1, valid_region.anchor[1] + border_top);
337  valid_region.shape.set(0, std::max(0, static_cast<int>(valid_region.shape[0]) - border_right - border_left));
338  valid_region.shape.set(1, std::max(0, static_cast<int>(valid_region.shape[1]) - border_top - border_bottom));
339  }
340 
341  return valid_region;
342 }
343 
344 /** Write the value after casting the pointer according to @p data_type.
345  *
346  * @warning The type of the value must match the specified data type.
347  *
348  * @param[out] ptr Pointer to memory where the @p value will be written.
349  * @param[in] value Value that will be written.
350  * @param[in] data_type Data type that will be written.
351  */
352 template <typename T>
354 {
355  switch(data_type)
356  {
357  case DataType::U8:
358  case DataType::QASYMM8:
359  *reinterpret_cast<uint8_t *>(ptr) = value;
360  break;
361  case DataType::S8:
363  case DataType::QSYMM8:
365  *reinterpret_cast<int8_t *>(ptr) = value;
366  break;
367  case DataType::U16:
368  case DataType::QASYMM16:
369  *reinterpret_cast<uint16_t *>(ptr) = value;
370  break;
371  case DataType::S16:
372  case DataType::QSYMM16:
373  *reinterpret_cast<int16_t *>(ptr) = value;
374  break;
375  case DataType::U32:
376  *reinterpret_cast<uint32_t *>(ptr) = value;
377  break;
378  case DataType::S32:
379  *reinterpret_cast<int32_t *>(ptr) = value;
380  break;
381  case DataType::U64:
382  *reinterpret_cast<uint64_t *>(ptr) = value;
383  break;
384  case DataType::S64:
385  *reinterpret_cast<int64_t *>(ptr) = value;
386  break;
387  case DataType::BFLOAT16:
388  *reinterpret_cast<bfloat16 *>(ptr) = bfloat16(value);
389  break;
390  case DataType::F16:
391  *reinterpret_cast<half *>(ptr) = value;
392  break;
393  case DataType::F32:
394  *reinterpret_cast<float *>(ptr) = value;
395  break;
396  case DataType::F64:
397  *reinterpret_cast<double *>(ptr) = value;
398  break;
399  case DataType::SIZET:
400  *reinterpret_cast<size_t *>(ptr) = value;
401  break;
402  default:
403  ARM_COMPUTE_ERROR("NOT SUPPORTED!");
404  }
405 }
406 
407 /** Saturate a value of type T against the numeric limits of type U.
408  *
409  * @param[in] val Value to be saturated.
410  *
411  * @return saturated value.
412  */
413 template <typename U, typename T>
415 {
416  if(val > static_cast<T>(std::numeric_limits<U>::max()))
417  {
418  val = static_cast<T>(std::numeric_limits<U>::max());
419  }
420  if(val < static_cast<T>(std::numeric_limits<U>::lowest()))
421  {
422  val = static_cast<T>(std::numeric_limits<U>::lowest());
423  }
424  return val;
425 }
426 
427 /** Find the signed promoted common type.
428  */
429 template <typename... T>
431 {
432  /** Common type */
433  using common_type = typename std::common_type<T...>::type;
434  /** Promoted type */
436  /** Intermediate type */
438 };
439 
440 /** Find the unsigned promoted common type.
441  */
442 template <typename... T>
444 {
445  /** Common type */
446  using common_type = typename std::common_type<T...>::type;
447  /** Promoted type */
449  /** Intermediate type */
451 };
452 
453 /** Convert a linear index into n-dimensional coordinates.
454  *
455  * @param[in] shape Shape of the n-dimensional tensor.
456  * @param[in] index Linear index specifying the i-th element.
457  *
458  * @return n-dimensional coordinates.
459  */
460 inline Coordinates index2coord(const TensorShape &shape, int index)
461 {
462  int num_elements = shape.total_size();
463 
464  ARM_COMPUTE_ERROR_ON_MSG(index < 0 || index >= num_elements, "Index has to be in [0, num_elements]");
465  ARM_COMPUTE_ERROR_ON_MSG(num_elements == 0, "Cannot create coordinate from empty shape");
466 
467  Coordinates coord{ 0 };
468 
469  for(int d = shape.num_dimensions() - 1; d >= 0; --d)
470  {
471  num_elements /= shape[d];
472  coord.set(d, index / num_elements);
473  index %= num_elements;
474  }
475 
476  return coord;
477 }
478 
479 /** Linearise the given coordinate.
480  *
481  * Transforms the given coordinate into a linear offset in terms of
482  * elements.
483  *
484  * @param[in] shape Shape of the n-dimensional tensor.
485  * @param[in] coord The to be converted coordinate.
486  *
487  * @return Linear offset to the element.
488  */
489 inline int coord2index(const TensorShape &shape, const Coordinates &coord)
490 {
491  ARM_COMPUTE_ERROR_ON_MSG(shape.total_size() == 0, "Cannot get index from empty shape");
492  ARM_COMPUTE_ERROR_ON_MSG(coord.num_dimensions() == 0, "Cannot get index of empty coordinate");
493 
494  int index = 0;
495  int dim_size = 1;
496 
497  for(unsigned int i = 0; i < coord.num_dimensions(); ++i)
498  {
499  index += coord[i] * dim_size;
500  dim_size *= shape[i];
501  }
502 
503  return index;
504 }
505 
506 /** Check if a coordinate is within a valid region */
508 {
509  for(size_t d = 0; d < Coordinates::num_max_dimensions; ++d)
510  {
511  if(coord[d] < valid_region.start(d) || coord[d] >= valid_region.end(d))
512  {
513  return false;
514  }
515  }
516 
517  return true;
518 }
519 
520 /** Create and initialize a tensor of the given type.
521  *
522  * @param[in] shape Tensor shape.
523  * @param[in] data_type Data type.
524  * @param[in] num_channels (Optional) Number of channels.
525  * @param[in] quantization_info (Optional) Quantization info for asymmetric quantized types.
526  * @param[in] data_layout (Optional) Data layout. Default is NCHW.
527  * @param[in] ctx (Optional) Pointer to the runtime context.
528  *
529  * @return Initialized tensor of given type.
530  */
531 template <typename T>
532 inline T create_tensor(const TensorShape &shape, DataType data_type, int num_channels = 1,
534 {
535  T tensor(ctx);
536  TensorInfo info(shape, num_channels, data_type);
537  info.set_quantization_info(quantization_info);
538  info.set_data_layout(data_layout);
539  tensor.allocator()->init(info);
540 
541  return tensor;
542 }
543 
544 /** Create and initialize a tensor of the given type.
545  *
546  * @param[in] shape Tensor shape.
547  * @param[in] format Format type.
548  * @param[in] ctx (Optional) Pointer to the runtime context.
549  *
550  * @return Initialized tensor of given type.
551  */
552 template <typename T>
553 inline T create_tensor(const TensorShape &shape, Format format, IRuntimeContext *ctx = nullptr)
554 {
555  TensorInfo info(shape, format);
556 
557  T tensor(ctx);
558  tensor.allocator()->init(info);
559 
560  return tensor;
561 }
562 
563 /** Create and initialize a multi-image of the given type.
564  *
565  * @param[in] shape Tensor shape.
566  * @param[in] format Format type.
567  *
568  * @return Initialized tensor of given type.
569  */
570 template <typename T>
571 inline T create_multi_image(const TensorShape &shape, Format format)
572 {
573  T multi_image;
574  multi_image.init(shape.x(), shape.y(), format);
575 
576  return multi_image;
577 }
578 
579 /** Create and initialize a HOG (Histogram of Oriented Gradients) of the given type.
580  *
581  * @param[in] hog_info HOGInfo object
582  *
583  * @return Initialized HOG of given type.
584  */
585 template <typename T>
586 inline T create_HOG(const HOGInfo &hog_info)
587 {
588  T hog;
589  hog.init(hog_info);
590 
591  return hog;
592 }
593 
594 /** Create and initialize a Pyramid of the given type.
595  *
596  * @param[in] pyramid_info The PyramidInfo object.
597  *
598  * @return Initialized Pyramid of given type.
599  */
600 template <typename T>
601 inline T create_pyramid(const PyramidInfo &pyramid_info)
602 {
603  T pyramid;
604  pyramid.init_auto_padding(pyramid_info);
605 
606  return pyramid;
607 }
608 
609 /** Initialize a convolution matrix.
610  *
611  * @param[in, out] conv The input convolution matrix.
612  * @param[in] width The width of the convolution matrix.
613  * @param[in] height The height of the convolution matrix.
614  * @param[in] seed The random seed to be used.
615  */
616 inline void init_conv(int16_t *conv, unsigned int width, unsigned int height, std::random_device::result_type seed)
617 {
618  std::mt19937 gen(seed);
619  std::uniform_int_distribution<int16_t> distribution_int16(-32768, 32767);
620 
621  for(unsigned int i = 0; i < width * height; ++i)
622  {
623  conv[i] = distribution_int16(gen);
624  }
625 }
626 
627 /** Initialize a separable convolution matrix.
628  *
629  * @param[in, out] conv The input convolution matrix.
630  * @param[in] width The width of the convolution matrix.
631  * @param[in] height The height of the convolution matrix.
632  * @param[in] seed The random seed to be used.
633  */
634 inline void init_separable_conv(int16_t *conv, unsigned int width, unsigned int height, std::random_device::result_type seed)
635 {
636  std::mt19937 gen(seed);
637  // Set it between -128 and 127 to ensure the matrix does not overflow
638  std::uniform_int_distribution<int16_t> distribution_int16(-128, 127);
639 
640  int16_t *conv_row = new int16_t[width];
641  int16_t *conv_col = new int16_t[height];
642 
643  conv_row[0] = conv_col[0] = 1;
644  for(unsigned int i = 1; i < width; ++i)
645  {
646  conv_row[i] = distribution_int16(gen);
647  }
648 
649  for(unsigned int i = 1; i < height; ++i)
650  {
651  conv_col[i] = distribution_int16(gen);
652  }
653 
654  // Multiply two matrices
655  for(unsigned int i = 0; i < width; ++i)
656  {
657  for(unsigned int j = 0; j < height; ++j)
658  {
659  conv[i * width + j] = conv_col[i] * conv_row[j];
660  }
661  }
662 
663  delete[] conv_row;
664  delete[] conv_col;
665 }
666 
667 /** Create a vector with a uniform distribution of floating point values across the specified range.
668  *
669  * @param[in] num_values The number of values to be created.
670  * @param[in] min The minimum value in distribution (inclusive).
671  * @param[in] max The maximum value in distribution (inclusive).
672  * @param[in] seed The random seed to be used.
673  *
674  * @return A vector that contains the requested number of random floating point values
675  */
676 template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
677 inline std::vector<T> generate_random_real(unsigned int num_values, T min, T max, std::random_device::result_type seed)
678 {
679  std::vector<T> v(num_values);
680  std::mt19937 gen(seed);
681  std::uniform_real_distribution<T> dist(min, max);
682 
683  for(unsigned int i = 0; i < num_values; ++i)
684  {
685  v.at(i) = dist(gen);
686  }
687 
688  return v;
689 }
690 
691 /** Create a vector of random keypoints for pyramid representation.
692  *
693  * @param[in] shape The shape of the input tensor.
694  * @param[in] num_keypoints The number of keypoints to be created.
695  * @param[in] seed The random seed to be used.
696  * @param[in] num_levels The number of pyramid levels.
697  *
698  * @return A vector that contains the requested number of random keypoints
699  */
700 inline std::vector<KeyPoint> generate_random_keypoints(const TensorShape &shape, size_t num_keypoints, std::random_device::result_type seed, size_t num_levels = 1)
701 {
702  std::vector<KeyPoint> keypoints;
703  std::mt19937 gen(seed);
704 
705  // Calculate distribution bounds
706  const auto min = static_cast<int>(std::pow(2, num_levels));
707  const auto max_width = static_cast<int>(shape.x());
708  const auto max_height = static_cast<int>(shape.y());
709 
710  ARM_COMPUTE_ERROR_ON(min > max_width || min > max_height);
711 
712  // Create distributions
713  std::uniform_int_distribution<> dist_w(min, max_width);
714  std::uniform_int_distribution<> dist_h(min, max_height);
715 
716  for(unsigned int i = 0; i < num_keypoints; i++)
717  {
718  KeyPoint keypoint;
719  keypoint.x = dist_w(gen);
720  keypoint.y = dist_h(gen);
721  keypoint.tracking_status = 1;
722 
723  keypoints.push_back(keypoint);
724  }
725 
726  return keypoints;
727 }
728 
729 template <typename T, typename ArrayAccessor_T>
730 inline void fill_array(ArrayAccessor_T &&array, const std::vector<T> &v)
731 {
732  array.resize(v.size());
733  std::memcpy(array.buffer(), v.data(), v.size() * sizeof(T));
734 }
735 
736 /** Obtain numpy type string from DataType.
737  *
738  * @param[in] data_type Data type.
739  *
740  * @return numpy type string.
741  */
742 inline std::string get_typestring(DataType data_type)
743 {
744  // Check endianness
745  const unsigned int i = 1;
746  const char *c = reinterpret_cast<const char *>(&i);
747  std::string endianness;
748  if(*c == 1)
749  {
750  endianness = std::string("<");
751  }
752  else
753  {
754  endianness = std::string(">");
755  }
756  const std::string no_endianness("|");
757 
758  switch(data_type)
759  {
760  case DataType::U8:
761  return no_endianness + "u" + support::cpp11::to_string(sizeof(uint8_t));
762  case DataType::S8:
763  return no_endianness + "i" + support::cpp11::to_string(sizeof(int8_t));
764  case DataType::U16:
765  return endianness + "u" + support::cpp11::to_string(sizeof(uint16_t));
766  case DataType::S16:
767  return endianness + "i" + support::cpp11::to_string(sizeof(int16_t));
768  case DataType::U32:
769  return endianness + "u" + support::cpp11::to_string(sizeof(uint32_t));
770  case DataType::S32:
771  return endianness + "i" + support::cpp11::to_string(sizeof(int32_t));
772  case DataType::U64:
773  return endianness + "u" + support::cpp11::to_string(sizeof(uint64_t));
774  case DataType::S64:
775  return endianness + "i" + support::cpp11::to_string(sizeof(int64_t));
776  case DataType::F32:
777  return endianness + "f" + support::cpp11::to_string(sizeof(float));
778  case DataType::F64:
779  return endianness + "f" + support::cpp11::to_string(sizeof(double));
780  case DataType::SIZET:
781  return endianness + "u" + support::cpp11::to_string(sizeof(size_t));
782  default:
783  ARM_COMPUTE_ERROR("NOT SUPPORTED!");
784  }
785 }
786 
787 /** Sync if necessary.
788  */
789 template <typename TensorType>
790 inline void sync_if_necessary()
791 {
792 #ifdef ARM_COMPUTE_CL
793  if(opencl_is_available() && std::is_same<typename std::decay<TensorType>::type, arm_compute::CLTensor>::value)
794  {
796  }
797 #endif /* ARM_COMPUTE_CL */
798 }
799 
800 /** Sync tensor if necessary.
801  *
802  * @note: If the destination tensor not being used on OpenGL ES, GPU will optimize out the operation.
803  *
804  * @param[in] tensor Tensor to be sync.
805  */
806 template <typename TensorType>
807 inline void sync_tensor_if_necessary(TensorType &tensor)
808 {
809 #ifdef ARM_COMPUTE_GC
810  if(opengles31_is_available() && std::is_same<typename std::decay<TensorType>::type, arm_compute::GCTensor>::value)
811  {
812  // Force sync the tensor by calling map and unmap.
813  IGCTensor &t = dynamic_cast<IGCTensor &>(tensor);
814  t.map();
815  t.unmap();
816  }
817 #else /* ARM_COMPUTE_GC */
818  ARM_COMPUTE_UNUSED(tensor);
819 #endif /* ARM_COMPUTE_GC */
820 }
821 } // namespace test
822 } // namespace arm_compute
823 #endif /* ARM_COMPUTE_TEST_UTILS_H */
unsigned int top
top of the border
Definition: Types.h:352
typename std::conditional< std::is_integral< T >::value, std::make_signed< T >, std::common_type< T > >::type make_signed_conditional_t
Definition: Utils.h:136
typename traits::make_unsigned_conditional_t< promoted_type >::type intermediate_type
Intermediate type.
Definition: Utils.h:450
Shape of a tensor.
Definition: TensorShape.h:39
const DataLayout data_layout
Definition: Im2Col.cpp:146
void init_conv(int16_t *conv, unsigned int width, unsigned int height, std::random_device::result_type seed)
Initialize a convolution matrix.
Definition: Utils.h:616
quantized, symmetric fixed-point 16-bit number
TensorShape shape
Shape of the valid region.
Definition: Types.h:260
T foldl(F &&, const T &value)
Base case of foldl.
Definition: Utils.h:188
void map(bool blocking=true)
Map on an allocated buffer.
Definition: IGCTensor.cpp:33
ValidRegion shape_to_valid_region_gaussian_pyramid_half(const TensorShape &a_shape, const ValidRegion &a_valid_region, bool border_undefined=false)
Create a valid region for Gaussian Pyramid Half based on tensor shape and valid region at level "i - ...
Definition: Utils.h:259
Container for 2D border size.
Definition: Types.h:272
static CLScheduler & get()
Access the scheduler singleton.
Definition: CLScheduler.cpp:99
int32_t x
X coordinates.
Definition: Types.h:418
#define ARM_COMPUTE_ERROR(msg)
Print the given message then throw an std::runtime_error.
Definition: Error.h:352
Format get_format_for_channel(Channel channel)
Look up the format corresponding to a channel.
Definition: Utils.h:151
T copysign(T x, T y)
Composes a floating point value with the magnitude of x and the sign of y.
1 channel, 1 U8 per channel
typename promote< T >::type promote_t
Get promoted type.
Definition: Utils.h:133
int32_t tracking_status
Status initialized to 1 by the corner detector, set to 0 when the point is lost.
Definition: Types.h:423
std::string to_string(T &&value)
Convert integer and float values to string.
Store the HOG's metadata.
Definition: HOGInfo.h:35
half_float::half half
16-bit floating point type
Definition: Types.h:46
1 channel, 1 F32 per channel
GCTensor create_tensor(const TensorShape &shape, DataType data_type, int num_channels=1)
Helper to create an empty tensor.
Definition: Helper.h:46
void sync_if_necessary()
Sync if necessary.
Definition: Utils.h:790
#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
void unmap()
Unmap an allocated and mapped buffer.
Definition: IGCTensor.cpp:38
Interface for GLES Compute tensor.
Definition: IGCTensor.h:35
quantized, asymmetric fixed-point 16-bit number
1 channel, 1 U16 per channel
unsigned int bottom
bottom of the border
Definition: Types.h:354
void set(size_t dimension, T value)
Accessor to set the value of one of the dimensions.
Definition: Dimensions.h:74
bool opengles31_is_available()
Check if the OpenGL ES 3.1 API is available at runtime.
Definition: OpenGLES.cpp:160
Interface for OpenGL ES tensor.
Definition: GCTensor.h:38
Copyright (c) 2017-2020 ARM Limited.
int coord2index(const TensorShape &shape, const Coordinates &coord)
Linearise the given coordinate.
Definition: Utils.h:489
1 channel, 1 F16 per channel
Keypoint type.
Definition: Types.h:416
arm_compute::bfloat16 bfloat16
Definition: bfloat.hpp:30
std::array< int16_t, 25 > conv
1 channel, 1 S32 per channel
T round_half_even(T value, T epsilon=std::numeric_limits< T >::epsilon())
Round floating-point value with half value rounding to nearest even.
Definition: Utils.h:88
16-bit brain floating-point number
T x() const
Alias to access the size of the first dimension.
Definition: Dimensions.h:81
signed 64-bit number
3 channels, 1 U8 per channel
Quantization information.
ValidRegion shape_to_valid_region_laplacian_pyramid(const TensorShape &a_shape, const ValidRegion &a_valid_region, bool border_undefined=false)
Create a valid region for Laplacian Pyramid based on tensor shape and valid region at level "i - 1" a...
Definition: Utils.h:322
Format get_channel_format(Channel channel)
Return the format of a channel.
Definition: Utils.h:170
void store_value_with_data_type(void *ptr, T value, DataType data_type)
Write the value after casting the pointer according to data_type.
Definition: Utils.h:353
bool is_in_valid_region(const ValidRegion &valid_region, Coordinates coord)
Check if a coordinate is within a valid region.
Definition: Utils.h:507
#define ARM_COMPUTE_UNUSED(...)
To avoid unused variables warnings.
Definition: Error.h:152
void sync_tensor_if_necessary(TensorType &tensor)
Sync tensor if necessary.
Definition: Utils.h:807
1 channel, 1 U32 per channel
Channel
Available channels.
Definition: Types.h:464
Format
Image colour formats.
Definition: Types.h:54
quantized, asymmetric fixed-point 8-bit number unsigned
T create_pyramid(const PyramidInfo &pyramid_info)
Create and initialize a Pyramid of the given type.
Definition: Utils.h:601
#define ARM_COMPUTE_ERROR_ON_MSG(cond, msg)
Definition: Error.h:456
Find the signed promoted common type.
Definition: Utils.h:430
int start(unsigned int d) const
Return the start of the valid region for the given dimension d.
Definition: Types.h:233
Coordinates of an item.
Definition: Coordinates.h:37
std::vector< KeyPoint > generate_random_keypoints(const TensorShape &shape, size_t num_keypoints, std::random_device::result_type seed, size_t num_levels=1)
Create a vector of random keypoints for pyramid representation.
Definition: Utils.h:700
void fill_array(ArrayAccessor_T &&array, const std::vector< T > &v)
Definition: Utils.h:730
Coordinates index2coord(const TensorShape &shape, int index)
Convert a linear index into n-dimensional coordinates.
Definition: Utils.h:460
unsigned int left
left of the border
Definition: Types.h:355
unsigned int right
right of the border
Definition: Types.h:353
1 channel, 1 S16 per channel
std::string get_typestring(DataType data_type)
Obtain numpy type string from DataType.
Definition: Utils.h:742
quantized, symmetric fixed-point 8-bit number
Num samples, channels, height, width.
int32_t y
Y coordinates.
Definition: Types.h:419
void sync()
Blocks until all commands in the associated command queue have finished.
Definition: CLScheduler.cpp:67
quantized, symmetric per channel fixed-point 8-bit number
Store the Pyramid's metadata.
Definition: PyramidInfo.h:35
T create_HOG(const HOGInfo &hog_info)
Create and initialize a HOG (Histogram of Oriented Gradients) of the given type.
Definition: Utils.h:586
int end(unsigned int d) const
Return the end of the valid region for the given dimension d.
Definition: Types.h:239
traits::promote_t< common_type > promoted_type
Promoted type.
Definition: Utils.h:435
T round(T value)
Round floating-point value with half value rounding away from zero.
unsigned int num_dimensions() const
Returns the effective dimensionality of the tensor.
Definition: Dimensions.h:122
typename traits::make_signed_conditional_t< promoted_type >::type intermediate_type
Intermediate type.
Definition: Utils.h:437
T saturate_cast(T val)
Saturate a value of type T against the numeric limits of type U.
Definition: Utils.h:414
TensorShape & set(size_t dimension, size_t value, bool apply_dim_correction=true)
Accessor to set the value of one of the dimensions.
Definition: TensorShape.h:78
traits::promote_t< common_type > promoted_type
Promoted type.
Definition: Utils.h:448
Store the tensor's metadata.
Definition: TensorInfo.h:45
T y() const
Alias to access the size of the second dimension.
Definition: Dimensions.h:86
quantized, asymmetric fixed-point 8-bit number signed
64-bit floating-point number
T round_half_up(T value)
Round floating-point value with half value rounding to positive infinity.
Definition: Utils.h:75
Container for valid region of a window.
Definition: Types.h:187
typename std::conditional< std::is_integral< T >::value, std::make_unsigned< T >, std::common_type< T > >::type make_unsigned_conditional_t
Definition: Utils.h:139
static constexpr size_t num_max_dimensions
Number of dimensions the tensor has.
Definition: Dimensions.h:45
unsigned 64-bit number
void init_separable_conv(int16_t *conv, unsigned int width, unsigned int height, std::random_device::result_type seed)
Initialize a separable convolution matrix.
Definition: Utils.h:634
DataType
Available data types.
Definition: Types.h:77
Find the unsigned promoted common type.
Definition: Utils.h:443
DataLayout
[DataLayout enum definition]
Definition: Types.h:120
signed 8-bit number
std::vector< T > generate_random_real(unsigned int num_values, T min, T max, std::random_device::result_type seed)
Create a vector with a uniform distribution of floating point values across the specified range.
Definition: Utils.h:677
Coordinates anchor
Anchor for the start of the valid region.
Definition: Types.h:259
ValidRegion shape_to_valid_region(const TensorShape &a_shape, bool border_undefined=false, BorderSize border_size=BorderSize(0))
Create a valid region based on tensor shape, border mode and border size.
Definition: Utils.h:225
typename std::common_type< T... >::type common_type
Common type.
Definition: Utils.h:433
typename std::common_type< T... >::type common_type
Common type.
Definition: Utils.h:446
bool opencl_is_available()
Check if OpenCL is available.
Definition: OpenCL.cpp:150
T create_multi_image(const TensorShape &shape, Format format)
Create and initialize a multi-image of the given type.
Definition: Utils.h:571
Basic implementation of the OpenCL tensor interface.
Definition: CLTensor.h:41