From 91359e1d0acf74bd586900849c4ab94c117c138f Mon Sep 17 00:00:00 2001 From: Benoit Steiner Date: Wed, 22 Apr 2015 11:14:58 -0700 Subject: Added the ability to generate a tensor from a custom user defined 'generator'. This simplifies the creation of constant tensors initialized using specific regular patterns. Created a gaussian window generator as a first use case. --- unsupported/test/cxx11_tensor_generator.cpp | 87 +++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 unsupported/test/cxx11_tensor_generator.cpp (limited to 'unsupported/test/cxx11_tensor_generator.cpp') diff --git a/unsupported/test/cxx11_tensor_generator.cpp b/unsupported/test/cxx11_tensor_generator.cpp new file mode 100644 index 000000000..8ca52c7a5 --- /dev/null +++ b/unsupported/test/cxx11_tensor_generator.cpp @@ -0,0 +1,87 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include "main.h" + +#include + +struct Generator1D { + Generator1D() { } + + float operator()(const array& coordinates) const { + return coordinates[0]; + } +}; + +template +static void test_1D() +{ + Tensor vec(6); + Tensor result = vec.generate(Generator1D()); + + for (int i = 0; i < 6; ++i) { + VERIFY_IS_EQUAL(result(i), i); + } +} + + +struct Generator2D { + Generator2D() { } + + float operator()(const array& coordinates) const { + return 3 * coordinates[0] + 11 * coordinates[1]; + } +}; + +template +static void test_2D() +{ + Tensor matrix(5, 7); + Tensor result = matrix.generate(Generator2D()); + + for (int i = 0; i < 5; ++i) { + for (int j = 0; j < 5; ++j) { + VERIFY_IS_EQUAL(result(i, j), 3*i + 11*j); + } + } +} + + +template +static void test_gaussian() +{ + int rows = 32; + int cols = 48; + array means = { rows / 2.0f, cols / 2.0f }; + array std_devs = { 3.14f, 2.7f }; + internal::GaussianGenerator gaussian_gen(means, std_devs); + + Tensor matrix(rows, cols); + Tensor result = matrix.generate(gaussian_gen); + + for (int i = 0; i < rows; ++i) { + for (int j = 0; j < cols; ++j) { + float g_rows = powf(rows/2.0f - i, 2) / (3.14f * 3.14f) * 0.5f; + float g_cols = powf(cols/2.0f - j, 2) / (2.7f * 2.7f) * 0.5f; + float gaussian = expf(-g_rows - g_cols); + VERIFY_IS_EQUAL(result(i, j), gaussian); + } + } +} + + +void test_cxx11_tensor_generator() +{ + CALL_SUBTEST(test_1D()); + CALL_SUBTEST(test_1D()); + CALL_SUBTEST(test_2D()); + CALL_SUBTEST(test_2D()); + CALL_SUBTEST(test_gaussian()); + CALL_SUBTEST(test_gaussian()); +} -- cgit v1.2.3