Home | History | Annotate | Download | only in kernels
      1 /* Copyright 2016 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 // See docs in ../ops/string_ops.cc.
     17 
     18 #include <string>
     19 
     20 #include "tensorflow/core/framework/kernel_def_builder.h"
     21 #include "tensorflow/core/framework/op_kernel.h"
     22 #include "tensorflow/core/framework/tensor.h"
     23 #include "tensorflow/core/lib/core/errors.h"
     24 #include "tensorflow/core/lib/core/status.h"
     25 #include "tensorflow/core/lib/strings/stringprintf.h"
     26 
     27 namespace tensorflow {
     28 
     29 class AsStringOp : public OpKernel {
     30  public:
     31   using OpKernel::OpKernel;
     32 
     33   explicit AsStringOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
     34     int32 precision;
     35     bool scientific;
     36     bool shortest;
     37     int32 width;
     38     string fill_string;
     39     DataType dtype;
     40     OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype));
     41     OP_REQUIRES_OK(ctx, ctx->GetAttr("precision", &precision));
     42     OP_REQUIRES_OK(ctx, ctx->GetAttr("scientific", &scientific));
     43     OP_REQUIRES_OK(ctx, ctx->GetAttr("shortest", &shortest));
     44     OP_REQUIRES_OK(ctx, ctx->GetAttr("width", &width));
     45     OP_REQUIRES_OK(ctx, ctx->GetAttr("fill", &fill_string));
     46     switch (dtype) {
     47       case DT_FLOAT:
     48       case DT_DOUBLE:
     49       case DT_COMPLEX64:
     50         break;
     51       default:
     52         OP_REQUIRES(ctx, !(scientific || shortest),
     53                     errors::InvalidArgument("scientific and shortest format "
     54                                             "not supported for datatype ",
     55                                             DataTypeString(dtype)));
     56         OP_REQUIRES(ctx, precision < 0,
     57                     errors::InvalidArgument("precision not supported "
     58                                             "for datatype ",
     59                                             DataTypeString(dtype)));
     60     }
     61     OP_REQUIRES(
     62         ctx, fill_string.size() <= 1,
     63         errors::InvalidArgument("Fill string must be one or fewer characters"));
     64     OP_REQUIRES(ctx, !(scientific && shortest),
     65                 errors::InvalidArgument(
     66                     "Cannot select both scientific and shortest notation"));
     67     format_ = "%";
     68     if (width > -1) {
     69       strings::Appendf(&format_, "%s%d", fill_string.c_str(), width);
     70     }
     71     if (precision > -1) {
     72       strings::Appendf(&format_, ".%d", precision);
     73     }
     74     switch (dtype) {
     75       case DT_INT8:
     76       case DT_INT32:
     77         strings::Appendf(&format_, "d");
     78         break;
     79       case DT_INT64:
     80         strings::Appendf(&format_, "lld");
     81         break;
     82       case DT_FLOAT:
     83       case DT_DOUBLE:
     84       case DT_COMPLEX64:
     85         if (shortest) {
     86           strings::Appendf(&format_, "g");
     87         } else if (scientific) {
     88           strings::Appendf(&format_, "e");
     89         } else {
     90           strings::Appendf(&format_, "f");
     91         }
     92         break;
     93       case DT_BOOL:
     94         break;
     95       default:
     96         bool type_not_supported = true;
     97         OP_REQUIRES(ctx, !type_not_supported,
     98                     errors::InvalidArgument("Type not supported: ",
     99                                             DataTypeString(dtype)));
    100     }
    101 
    102     if (dtype == DT_COMPLEX64) {
    103       format_ = strings::Printf("(%s,%s)", format_.c_str(), format_.c_str());
    104     }
    105   }
    106 
    107   void Compute(OpKernelContext* context) override {
    108     const Tensor* input_tensor;
    109     OP_REQUIRES_OK(context, context->input("input", &input_tensor));
    110     const DataType& dtype = input_tensor->dtype();
    111 
    112     Tensor* output_tensor = nullptr;
    113     OP_REQUIRES_OK(context,
    114                    context->allocate_output("output", input_tensor->shape(),
    115                                             &output_tensor));
    116     auto output_flat = output_tensor->flat<string>();
    117 
    118 #define ENCODE_TYPE(type, T, enc_str)                                     \
    119   case (type): {                                                          \
    120     const auto& input_flat = input_tensor->flat<T>();                     \
    121     for (int i = 0; i < input_flat.size(); ++i) {                         \
    122       output_flat(i) = strings::Printf((enc_str.c_str()), input_flat(i)); \
    123     }                                                                     \
    124   } break
    125 
    126     switch (dtype) {
    127       ENCODE_TYPE(DT_INT32, int32, format_);
    128       ENCODE_TYPE(DT_INT64, int64, format_);
    129       ENCODE_TYPE(DT_FLOAT, float, format_);
    130       ENCODE_TYPE(DT_DOUBLE, double, format_);
    131       ENCODE_TYPE(DT_INT8, int8, format_);
    132       case (DT_BOOL): {
    133         const auto& input_flat = input_tensor->flat<bool>();
    134         for (int i = 0; i < input_flat.size(); ++i) {
    135           output_flat(i) = (input_flat(i)) ? "true" : "false";
    136         }
    137       } break;
    138       case (DT_COMPLEX64): {
    139         const auto& input_flat = input_tensor->flat<complex64>();
    140         for (int i = 0; i < input_flat.size(); ++i) {
    141           output_flat(i) = strings::Printf(
    142               format_.c_str(), input_flat(i).real(), input_flat(i).imag());
    143         }
    144       } break;
    145       default:
    146         bool can_encode_type = false;
    147         OP_REQUIRES(context, can_encode_type,
    148                     errors::InvalidArgument("Cannot encode input of type ",
    149                                             DataTypeString(dtype)));
    150     }
    151 
    152 #undef ENCODE_TYPE
    153   }
    154 
    155  private:
    156   string format_;
    157 };
    158 
    159 REGISTER_KERNEL_BUILDER(Name("AsString").Device(DEVICE_CPU), AsStringOp);
    160 
    161 }  // namespace tensorflow
    162