#-------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
#-------------------------------------------------------------

# This builtin function takes the outputs of SliceLine and the
# original transformencode meta data in order to print a human-
# readable debug output of the resulting top-k slices.
#
# INPUT:
# ------------------------------------------------------------------------------
# TK      top-k slices (k x ncol(X) if successful)
# TKC     score, total/max error, size of slices (k x 4)
# tfmeta  transformencode meta data
# tfspec  transform specification
# ------------------------------------------------------------------------------
#
# OUTPUT:
# ------------------------------------------------------------------------------
# S     debug output collected as a string
# ------------------------------------------------------------------------------

m_sliceLineDebug = function(Matrix[Double] TK,
  Matrix[Double] TKC, Frame[Unknown] tfmeta, String tfspec)
  return(Matrix[Double] S)
{
  print("\nsliceLineDebug: input\n"+toString(TK)+"\n"+toString(TKC)+"\n"+toString(tfmeta));

  # prepare essential decoding info
  N = colnames(tfmeta);
  TKsafe = TK + (TK==0); # for vectorized decoding
  FTK = transformdecode(target=TKsafe, meta=tfmeta, spec=tfspec);

  # actual debug output
  for(i in 1:nrow(TK)) {
    TKi = TK[i,]; FTKi = FTK[i,];
    print("-- Slice #"+i+": score="+as.scalar(TKC[i,1])+", size="+as.scalar(TKC[i,4]));
    print("---- avg error="+as.scalar(TKC[i,2]/TKC[i,4])+", max error="+as.scalar(TKC[i,3]));
    pred = "";
    for(j in 1:ncol(TKi)) {
        if( as.scalar(TKi[1,j]) != 0 ) {
           tmp = as.scalar(N[1,j]) + " = " + as.scalar(FTK[i,j]);
           pred = ifelse(pred=="", tmp, pred+" AND "+tmp);
        }
    }
    print("---- predicate: "+pred);
  }
  S = TK;
}

