Home | History | Annotate | Download | only in framework
      1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
      2 
      3 Licensed under the Apache License, Version 2.0 (the "License");
      4 you may not use this file except in compliance with the License.
      5 You may obtain a copy of the License at
      6 
      7     http://www.apache.org/licenses/LICENSE-2.0
      8 
      9 Unless required by applicable law or agreed to in writing, software
     10 distributed under the License is distributed on an "AS IS" BASIS,
     11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 See the License for the specific language governing permissions and
     13 limitations under the License.
     14 ==============================================================================*/
     15 
     16 #include "tensorflow/core/framework/tensor_testutil.h"
     17 #include <cmath>
     18 
     19 namespace tensorflow {
     20 namespace test {
     21 
     22 template <typename T>
     23 bool IsClose(const T& x, const T& y, double atol, double rtol) {
     24   // Need x == y so that infinities are close to themselves
     25   return x == y || std::abs(x - y) < atol + rtol * std::abs(x);
     26 }
     27 
     28 template <typename T>
     29 void ExpectClose(const Tensor& x, const Tensor& y, double atol, double rtol) {
     30   auto Tx = x.flat<T>();
     31   auto Ty = y.flat<T>();
     32   for (int i = 0; i < Tx.size(); ++i) {
     33     if (!IsClose(Tx(i), Ty(i), atol, rtol)) {
     34       LOG(ERROR) << "x = " << x.DebugString();
     35       LOG(ERROR) << "y = " << y.DebugString();
     36       LOG(ERROR) << "atol = " << atol << " rtol = " << rtol
     37                  << " tol = " << atol + rtol * std::abs(Tx(i));
     38       EXPECT_TRUE(false) << i << "-th element is not close " << Tx(i) << " vs. "
     39                          << Ty(i);
     40     }
     41   }
     42 }
     43 
     44 void ExpectClose(const Tensor& x, const Tensor& y, double atol, double rtol) {
     45   internal::AssertSameTypeDims(x, y);
     46   switch (x.dtype()) {
     47     case DT_FLOAT:
     48       ExpectClose<float>(x, y, atol, rtol);
     49       break;
     50     case DT_DOUBLE:
     51       ExpectClose<double>(x, y, atol, rtol);
     52       break;
     53     case DT_COMPLEX64:
     54       ExpectClose<complex64>(x, y, atol, rtol);
     55       break;
     56     case DT_COMPLEX128:
     57       ExpectClose<complex128>(x, y, atol, rtol);
     58       break;
     59     default:
     60       LOG(FATAL) << "Unexpected type : " << DataTypeString(x.dtype());
     61   }
     62 }
     63 
     64 }  // end namespace test
     65 }  // end namespace tensorflow
     66