blob: 25023d46e63e08df2811571fb96ca653246aca95 [file] [log] [blame]
Anthony Barbier6ff3b192017-09-04 18:44:23 +01001/*
2 * Copyright (c) 2017 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
27#include "arm_compute/core/Coordinates.h"
28#include "arm_compute/core/Error.h"
29#include "arm_compute/core/FixedPoint.h"
30#include "arm_compute/core/TensorShape.h"
31#include "arm_compute/core/Types.h"
32
33#include <cmath>
34#include <cstddef>
35#include <limits>
36#include <memory>
37#include <sstream>
38#include <string>
39#include <type_traits>
40
Pablo Tello383deec2017-06-23 10:40:05 +010041#if ARM_COMPUTE_ENABLE_FP16
42#include <arm_fp16.h> // needed for float16_t
43#endif
44
Anthony Barbier6ff3b192017-09-04 18:44:23 +010045namespace arm_compute
46{
47namespace test
48{
49namespace cpp11
50{
51#ifdef __ANDROID__
52/** Convert integer and float values to string.
53 *
54 * @note This function implements the same behaviour as std::to_string. The
55 * latter is missing in some Android toolchains.
56 *
57 * @param[in] value Value to be converted to string.
58 *
59 * @return String representation of @p value.
60 */
61template <typename T, typename std::enable_if<std::is_arithmetic<typename std::decay<T>::type>::value, int>::type = 0>
62std::string to_string(T && value)
63{
64 std::stringstream stream;
65 stream << std::forward<T>(value);
66 return stream.str();
67}
68
69/** Convert string values to integer.
70 *
71 * @note This function implements the same behaviour as std::stoi. The latter
72 * is missing in some Android toolchains.
73 *
74 * @param[in] str String to be converted to int.
75 *
76 * @return Integer representation of @p str.
77 */
78inline int stoi(const std::string &str)
79{
80 std::stringstream stream(str);
81 int value = 0;
82 stream >> value;
83 return value;
84}
85
86/** Convert string values to unsigned long.
87 *
88 * @note This function implements the same behaviour as std::stoul. The latter
89 * is missing in some Android toolchains.
90 *
91 * @param[in] str String to be converted to unsigned long.
92 *
93 * @return Unsigned long representation of @p str.
94 */
95inline unsigned long stoul(const std::string &str)
96{
97 std::stringstream stream(str);
98 unsigned long value = 0;
99 stream >> value;
100 return value;
101}
102
103/** Convert string values to float.
104 *
105 * @note This function implements the same behaviour as std::stof. The latter
106 * is missing in some Android toolchains.
107 *
108 * @param[in] str String to be converted to float.
109 *
110 * @return Float representation of @p str.
111 */
112inline float stof(const std::string &str)
113{
114 std::stringstream stream(str);
115 float value = 0.f;
116 stream >> value;
117 return value;
118}
119
120/** Round floating-point value with half value rounding away from zero.
121 *
122 * @note This function implements the same behaviour as std::round except that it doesn't
123 * support Integral type. The latter is not in the namespace std in some Android toolchains.
124 *
125 * @param[in] value floating-point value to be rounded.
126 *
127 * @return Floating-point value of rounded @p value.
128 */
129template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
130inline T round(T value)
131{
132 return ::round(value);
133}
134
135/** Truncate floating-point value.
136 *
137 * @note This function implements the same behaviour as std::truncate except that it doesn't
138 * support Integral type. The latter is not in the namespace std in some Android toolchains.
139 *
140 * @param[in] value floating-point value to be truncated.
141 *
142 * @return Floating-point value of truncated @p value.
143 */
144template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
145inline T trunc(T value)
146{
147 return ::trunc(value);
148}
149
150/** Composes a floating point value with the magnitude of @p x and the sign of @p y.
151 *
152 * @note This function implements the same behaviour as std::copysign except that it doesn't
153 * support Integral type. The latter is not in the namespace std in some Android toolchains.
154 *
155 * @param[in] x value that contains the magnitued to be used in constructing the result.
156 * @param[in] y value that contains the sign to be used in constructin the result.
157 *
158 * @return Floating-point value with magnitude of @p x and sign of @p y.
159 */
160template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
161inline T copysign(T x, T y)
162{
163 return ::copysign(x, y);
164}
165#else
166/** Convert integer and float values to string.
167 *
168 * @note This function acts as a convenience wrapper around std::to_string. The
169 * latter is missing in some Android toolchains.
170 *
171 * @param[in] value Value to be converted to string.
172 *
173 * @return String representation of @p value.
174 */
175template <typename T>
176std::string to_string(T &&value)
177{
178 return ::std::to_string(std::forward<T>(value));
179}
180
181/** Convert string values to integer.
182 *
183 * @note This function acts as a convenience wrapper around std::stoi. The
184 * latter is missing in some Android toolchains.
185 *
186 * @param[in] args Arguments forwarded to std::stoi.
187 *
188 * @return Integer representation of input string.
189 */
190template <typename... Ts>
191int stoi(Ts &&... args)
192{
193 return ::std::stoi(std::forward<Ts>(args)...);
194}
195
196/** Convert string values to unsigned long.
197 *
198 * @note This function acts as a convenience wrapper around std::stoul. The
199 * latter is missing in some Android toolchains.
200 *
201 * @param[in] args Arguments forwarded to std::stoul.
202 *
203 * @return Unsigned long representation of input string.
204 */
205template <typename... Ts>
206int stoul(Ts &&... args)
207{
208 return ::std::stoul(std::forward<Ts>(args)...);
209}
210
211/** Convert string values to float.
212 *
213 * @note This function acts as a convenience wrapper around std::stof. The
214 * latter is missing in some Android toolchains.
215 *
216 * @param[in] args Arguments forwarded to std::stof.
217 *
218 * @return Float representation of input string.
219 */
220template <typename... Ts>
221int stof(Ts &&... args)
222{
223 return ::std::stof(std::forward<Ts>(args)...);
224}
225
226/** Round floating-point value with half value rounding away from zero.
227 *
228 * @note This function implements the same behaviour as std::round except that it doesn't
229 * support Integral type. The latter is not in the namespace std in some Android toolchains.
230 *
231 * @param[in] value floating-point value to be rounded.
232 *
233 * @return Floating-point value of rounded @p value.
234 */
235template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
236inline T round(T value)
237{
238 return std::round(value);
239}
240
241/** Truncate floating-point value.
242 *
243 * @note This function implements the same behaviour as std::truncate except that it doesn't
244 * support Integral type. The latter is not in the namespace std in some Android toolchains.
245 *
246 * @param[in] value floating-point value to be truncated.
247 *
248 * @return Floating-point value of truncated @p value.
249 */
250template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
251inline T trunc(T value)
252{
253 return std::trunc(value);
254}
255
256/** Composes a floating point value with the magnitude of @p x and the sign of @p y.
257 *
258 * @note This function implements the same behaviour as std::copysign except that it doesn't
259 * support Integral type. The latter is not in the namespace std in some Android toolchains.
260 *
261 * @param[in] x value that contains the magnitued to be used in constructing the result.
262 * @param[in] y value that contains the sign to be used in constructin the result.
263 *
264 * @return Floating-point value with magnitude of @p x and sign of @p y.
265 */
266template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
267inline T copysign(T x, T y)
268{
269 return std::copysign(x, y);
270}
271#endif
272
273/** Round floating-point value with half value rounding to positive infinity.
274 *
275 * @param[in] value floating-point value to be rounded.
276 *
277 * @return Floating-point value of rounded @p value.
278 */
279template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
280inline T round_half_up(T value)
281{
282 return std::floor(value + 0.5f);
283}
284
285/** Round floating-point value with half value rounding to nearest even.
286 *
287 * @param[in] value floating-point value to be rounded.
288 * @param[in] epsilon precision.
289 *
290 * @return Floating-point value of rounded @p value.
291 */
292template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value>::type>
293inline T round_half_even(T value, T epsilon = std::numeric_limits<T>::epsilon())
294{
295 T positive_value = std::abs(value);
296 T ipart = 0;
297 std::modf(positive_value, &ipart);
298 // If 'value' is exactly halfway between two integers
299 if(std::abs(positive_value - (ipart + 0.5f)) < epsilon)
300 {
301 // If 'ipart' is even then return 'ipart'
302 if(std::fmod(ipart, 2.f) < epsilon)
303 {
304 return cpp11::copysign(ipart, value);
305 }
306 // Else return the nearest even integer
307 return cpp11::copysign(std::ceil(ipart + 0.5f), value);
308 }
309 // Otherwise use the usual round to closest
310 return cpp11::copysign(cpp11::round(positive_value), value);
311}
312} // namespace cpp11
313
314namespace cpp14
315{
316/** make_unqiue is missing in CPP11. Reimplement it according to the standard
317 * proposal.
318 */
319template <class T>
320struct _Unique_if
321{
322 typedef std::unique_ptr<T> _Single_object;
323};
324
325template <class T>
326struct _Unique_if<T[]>
327{
328 typedef std::unique_ptr<T[]> _Unknown_bound;
329};
330
331template <class T, size_t N>
332struct _Unique_if<T[N]>
333{
334 typedef void _Known_bound;
335};
336
337template <class T, class... Args>
338typename _Unique_if<T>::_Single_object
339make_unique(Args &&... args)
340{
341 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
342}
343
344template <class T>
345typename _Unique_if<T>::_Unknown_bound
346make_unique(size_t n)
347{
348 typedef typename std::remove_extent<T>::type U;
349 return std::unique_ptr<T>(new U[n]());
350}
351
352template <class T, class... Args>
353typename _Unique_if<T>::_Known_bound
354make_unique(Args &&...) = delete;
355} // namespace cpp14
356
357namespace traits
358{
359// *INDENT-OFF*
360// clang-format off
361template <typename T> struct promote { };
362template <> struct promote<uint8_t> { using type = uint16_t; };
363template <> struct promote<int8_t> { using type = int16_t; };
364template <> struct promote<uint16_t> { using type = uint32_t; };
365template <> struct promote<int16_t> { using type = int32_t; };
366template <> struct promote<uint32_t> { using type = uint64_t; };
367template <> struct promote<int32_t> { using type = int64_t; };
368template <> struct promote<float> { using type = float; };
Pablo Tello383deec2017-06-23 10:40:05 +0100369#ifdef ARM_COMPUTE_ENABLE_FP16
370template <> struct promote<float16_t> { using type = float16_t; };
371#endif
372
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100373
374template <typename T>
375using promote_t = typename promote<T>::type;
376
377template <typename T>
378using make_signed_conditional_t = typename std::conditional<std::is_integral<T>::value, std::make_signed<T>, std::common_type<T>>::type;
379// clang-format on
380// *INDENT-ON*
381}
382
383/** Look up the format corresponding to a channel.
384 *
385 * @param[in] channel Channel type.
386 *
387 * @return Format that contains the given channel.
388 */
389inline Format get_format_for_channel(Channel channel)
390{
391 switch(channel)
392 {
393 case Channel::R:
394 case Channel::G:
395 case Channel::B:
396 return Format::RGB888;
397 default:
398 throw std::runtime_error("Unsupported channel");
399 }
400}
401
402/** Return the format of a channel.
403 *
404 * @param[in] channel Channel type.
405 *
406 * @return Format of the given channel.
407 */
408inline Format get_channel_format(Channel channel)
409{
410 switch(channel)
411 {
412 case Channel::R:
413 case Channel::G:
414 case Channel::B:
415 return Format::U8;
416 default:
417 throw std::runtime_error("Unsupported channel");
418 }
419}
420
421/** Base case of foldl.
422 *
423 * @return value.
424 */
425template <typename F, typename T>
426inline T foldl(F &&, const T &value)
427{
428 return value;
429}
430
431/** Base case of foldl.
432 *
433 * @return func(value1, value2).
434 */
435template <typename F, typename T, typename U>
436inline auto foldl(F &&func, T &&value1, U &&value2) -> decltype(func(value1, value2))
437{
438 return func(value1, value2);
439}
440
441/** Fold left.
442 *
443 * @param[in] func Binary function to be called.
444 * @param[in] initial Initial value.
445 * @param[in] value Argument passed to the function.
446 * @param[in] values Remaining arguments.
447 */
448template <typename F, typename I, typename T, typename... Vs>
449inline I foldl(F &&func, I &&initial, T &&value, Vs &&... values)
450{
451 return foldl(std::forward<F>(func), func(std::forward<I>(initial), std::forward<T>(value)), std::forward<Vs>(values)...);
452}
453
SiCong Libacaf9a2017-06-19 13:41:45 +0100454/** Create a valid region based on tensor shape, border mode and border size
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100455 *
SiCong Libacaf9a2017-06-19 13:41:45 +0100456 * @param[in] shape Shape used as size of the valid region.
457 * @param[in] border_undefined (Optional) Boolean indicating if the border mode is undefined.
458 * @param[in] border_size (Optional) Border size used to specify the region to exclude.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100459 *
SiCong Libacaf9a2017-06-19 13:41:45 +0100460 * @return A valid region starting at (0, 0, ...) with size of @p shape if @p border_undefined is false; otherwise
461 * return A valid region starting at (@p border_size.left, @p border_size.top, ...) with reduced size of @p shape.
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100462 */
SiCong Libacaf9a2017-06-19 13:41:45 +0100463inline ValidRegion shape_to_valid_region(TensorShape shape, bool border_undefined = false, BorderSize border_size = BorderSize(0))
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100464{
465 Coordinates anchor;
SiCong Libacaf9a2017-06-19 13:41:45 +0100466 anchor.set(std::max(0, static_cast<int>(shape.num_dimensions()) - 1), 0);
467 if(border_undefined)
468 {
469 ARM_COMPUTE_ERROR_ON(shape.num_dimensions() < 2);
470 anchor.set(0, border_size.left);
471 anchor.set(1, border_size.top);
472 shape.set(0, shape.x() - border_size.left - border_size.right);
473 shape.set(1, shape.y() - border_size.top - border_size.bottom);
474 }
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100475 return ValidRegion(std::move(anchor), std::move(shape));
476}
477
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100478/** Write the value after casting the pointer according to @p data_type.
479 *
480 * @warning The type of the value must match the specified data type.
481 *
482 * @param[out] ptr Pointer to memory where the @p value will be written.
483 * @param[in] value Value that will be written.
484 * @param[in] data_type Data type that will be written.
485 */
486template <typename T>
487void store_value_with_data_type(void *ptr, T value, DataType data_type)
488{
489 switch(data_type)
490 {
491 case DataType::U8:
492 *reinterpret_cast<uint8_t *>(ptr) = value;
493 break;
494 case DataType::S8:
495 case DataType::QS8:
496 *reinterpret_cast<int8_t *>(ptr) = value;
497 break;
498 case DataType::U16:
499 *reinterpret_cast<uint16_t *>(ptr) = value;
500 break;
501 case DataType::S16:
Michalis Spyrou0a8334c2017-06-14 18:00:05 +0100502 case DataType::QS16:
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100503 *reinterpret_cast<int16_t *>(ptr) = value;
504 break;
505 case DataType::U32:
506 *reinterpret_cast<uint32_t *>(ptr) = value;
507 break;
508 case DataType::S32:
509 *reinterpret_cast<int32_t *>(ptr) = value;
510 break;
511 case DataType::U64:
512 *reinterpret_cast<uint64_t *>(ptr) = value;
513 break;
514 case DataType::S64:
515 *reinterpret_cast<int64_t *>(ptr) = value;
516 break;
Pablo Tello383deec2017-06-23 10:40:05 +0100517#if ARM_COMPUTE_ENABLE_FP16
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100518 case DataType::F16:
519 *reinterpret_cast<float16_t *>(ptr) = value;
520 break;
Pablo Tello383deec2017-06-23 10:40:05 +0100521#endif /* ARM_COMPUTE_ENABLE_FP16 */
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100522 case DataType::F32:
523 *reinterpret_cast<float *>(ptr) = value;
524 break;
525 case DataType::F64:
526 *reinterpret_cast<double *>(ptr) = value;
527 break;
528 case DataType::SIZET:
529 *reinterpret_cast<size_t *>(ptr) = value;
530 break;
531 default:
532 ARM_COMPUTE_ERROR("NOT SUPPORTED!");
533 }
534}
535
536/** Saturate a value of type T against the numeric limits of type U.
537 *
538 * @param[in] val Value to be saturated.
539 *
540 * @return saturated value.
541 */
542template <typename U, typename T>
543T saturate_cast(T val)
544{
545 if(val > static_cast<T>(std::numeric_limits<U>::max()))
546 {
547 val = static_cast<T>(std::numeric_limits<U>::max());
548 }
549 if(val < static_cast<T>(std::numeric_limits<U>::lowest()))
550 {
551 val = static_cast<T>(std::numeric_limits<U>::lowest());
552 }
553 return val;
554}
555
556/** Find the signed promoted common type.
557 */
558template <typename... T>
559struct common_promoted_signed_type
560{
561 using common_type = typename std::common_type<T...>::type;
562 using promoted_type = traits::promote_t<common_type>;
563 using intermediate_type = typename traits::make_signed_conditional_t<promoted_type>::type;
564};
565
566/** Convert a linear index into n-dimensional coordinates.
567 *
568 * @param[in] shape Shape of the n-dimensional tensor.
569 * @param[in] index Linear index specifying the i-th element.
570 *
571 * @return n-dimensional coordinates.
572 */
573inline Coordinates index2coord(const TensorShape &shape, int index)
574{
575 int num_elements = shape.total_size();
576
577 ARM_COMPUTE_ERROR_ON_MSG(index < 0 || index >= num_elements, "Index has to be in [0, num_elements]");
578 ARM_COMPUTE_ERROR_ON_MSG(num_elements == 0, "Cannot create coordinate from empty shape");
579
580 Coordinates coord{ 0 };
581
582 for(int d = shape.num_dimensions() - 1; d >= 0; --d)
583 {
584 num_elements /= shape[d];
585 coord.set(d, index / num_elements);
586 index %= num_elements;
587 }
588
589 return coord;
590}
591
592/** Linearise the given coordinate.
593 *
594 * Transforms the given coordinate into a linear offset in terms of
595 * elements.
596 *
597 * @param[in] shape Shape of the n-dimensional tensor.
598 * @param[in] coord The to be converted coordinate.
599 *
600 * @return Linear offset to the element.
601 */
602inline int coord2index(const TensorShape &shape, const Coordinates &coord)
603{
604 ARM_COMPUTE_ERROR_ON_MSG(shape.total_size() == 0, "Cannot get index from empty shape");
605 ARM_COMPUTE_ERROR_ON_MSG(coord.num_dimensions() == 0, "Cannot get index of empty coordinate");
606
607 int index = 0;
608 int dim_size = 1;
609
610 for(unsigned int i = 0; i < coord.num_dimensions(); ++i)
611 {
612 index += coord[i] * dim_size;
613 dim_size *= shape[i];
614 }
615
616 return index;
617}
618
Georgios Pinitasce093142017-06-19 16:11:53 +0100619/** Check if Coordinates dimensionality can match the respective shape one.
620 *
621 * @param coords Coordinates
622 * @param shape Shape to match dimensionality
623 *
624 * @return True if Coordinates can match the dimensionality of the shape else false.
625 */
626inline bool match_shape(Coordinates &coords, const TensorShape &shape)
627{
628 auto check_nz = [](unsigned int i)
629 {
630 return i != 0;
631 };
632
633 unsigned int coords_dims = coords.num_dimensions();
634 unsigned int shape_dims = shape.num_dimensions();
635
636 // Increase coordinates scenario
637 if(coords_dims < shape_dims)
638 {
639 coords.set_num_dimensions(shape_dims);
640 return true;
641 }
642 // Decrease coordinates scenario
643 if(coords_dims > shape_dims && !std::any_of(coords.begin() + shape_dims, coords.end(), check_nz))
644 {
645 coords.set_num_dimensions(shape_dims);
646 return true;
647 }
648
649 return (coords_dims == shape_dims);
650}
651
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100652/** Check if a coordinate is within a valid region */
653inline bool is_in_valid_region(const ValidRegion &valid_region, const Coordinates &coord)
654{
Georgios Pinitasce093142017-06-19 16:11:53 +0100655 Coordinates coords(coord);
656 ARM_COMPUTE_ERROR_ON_MSG(!match_shape(coords, valid_region.shape), "Shapes of valid region and coordinates do not agree");
657 for(int d = 0; static_cast<size_t>(d) < coords.num_dimensions(); ++d)
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100658 {
Georgios Pinitasce093142017-06-19 16:11:53 +0100659 if(coords[d] < valid_region.start(d) || coords[d] >= valid_region.end(d))
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100660 {
661 return false;
662 }
663 }
664 return true;
665}
Isabella Gottardi3b77e9d2017-06-22 11:05:41 +0100666
Anthony Barbier6ff3b192017-09-04 18:44:23 +0100667} // namespace test
668} // namespace arm_compute
669#endif