1 /*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "SkGaussFilter.h"
9
10 #include <cmath>
11 #include <tuple>
12 #include <vector>
13 #include "Test.h"
14
15 // one part in a million
16 static constexpr double kEpsilon = 0.000001;
17
careful_add(int n,double * gauss)18 static double careful_add(int n, double* gauss) {
19 // Sum smallest to largest to retain precision.
20 double sum = 0;
21 for (int i = n - 1; i >= 1; i--) {
22 sum += 2.0 * gauss[i];
23 }
24 sum += gauss[0];
25 return sum;
26 }
27
DEF_TEST(SkGaussFilterCommon,r)28 DEF_TEST(SkGaussFilterCommon, r) {
29 using Test = std::tuple<double, std::vector<double>>;
30
31 auto golden_check = [&](const Test& test) {
32 double sigma; std::vector<double> golden;
33 std::tie(sigma, golden) = test;
34 SkGaussFilter filter{sigma};
35 double result[SkGaussFilter::kGaussArrayMax];
36 int n = 0;
37 for (auto d : filter) {
38 result[n++] = d;
39 }
40 REPORTER_ASSERT(r, static_cast<size_t>(n) == golden.size());
41 double sum = careful_add(n, result);
42 REPORTER_ASSERT(r, sum == 1.0);
43 for (size_t i = 0; i < golden.size(); i++) {
44 REPORTER_ASSERT(r, std::abs(golden[i] - result[i]) < kEpsilon);
45 }
46 };
47
48 // The following two sigmas account for about 85% of all sigmas used for masks.
49 // Golden values generated using Mathematica.
50 auto tests = {
51 // GaussianMatrix[{{Automatic}, {.788675}}]
52 Test{0.788675, {0.593605, 0.176225, 0.0269721}},
53
54 // GaussianMatrix[{{4}, {1.07735}}, Method -> "Bessel"]
55 Test{1.07735, {0.429537, 0.214955, 0.059143, 0.0111337}},
56 };
57
58 for (auto& test : tests) {
59 golden_check(test);
60 }
61 }
62
DEF_TEST(SkGaussFilterSweep,r)63 DEF_TEST(SkGaussFilterSweep, r) {
64 // The double just before 2.0.
65 const double maxSigma = nextafter(2.0, 0.0);
66 auto check = [&](double sigma) {
67 SkGaussFilter filter{sigma};
68 double result[SkGaussFilter::kGaussArrayMax];
69 int n = 0;
70 for (auto d : filter) {
71 result[n++] = d;
72 }
73 REPORTER_ASSERT(r, n <= SkGaussFilter::kGaussArrayMax);
74 double sum = careful_add(n, result);
75 REPORTER_ASSERT(r, sum == 1.0);
76 };
77
78 for (double sigma = 0.0; sigma < 2.0; sigma += 0.1) {
79 check(sigma);
80 }
81 check(maxSigma);
82 }
83