#-------------------------------------------------------------
#
# 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.
#
#-------------------------------------------------------------

# Builtin function for detecting and repairing outliers using standard deviation 
#
# INPUT:
# -------------------------------------------------------------------------------------------
# X               Matrix X
# colMean         Matrix X
# k               a constant used to discern outliers k*IQR
# isIterative     iterative repair or single repair
# repairMethod    values: 0 = delete rows having outliers,
#                    1 = replace outliers with zeros
#                    2 = replace outliers as missing values
# max_iterations  values: 0 = arbitrary number of iteraition until all outliers are removed,
#                 n = any constant defined by user
# verbose         flag specifying if logging information should be printed
# -------------------------------------------------------------------------------------------
#
# OUTPUT:
# ---------------------------------------------------------------------------------
# Y     Matrix X with no outliers
# ---------------------------------------------------------------------------------

m_outlierBySdApply = function(Matrix[Double] X, Matrix[Double] colMean, Matrix[Double] colSD, Double k, Integer repairMethod) 
  return(Matrix[Double] Y) 
{

  upperBound = colMean + k * colSD
  lowerBound = colMean - k * colSD

  outlierFilter = (X < lowerBound) | (X > upperBound)
  if(sum(outlierFilter) > 1) 
    Y = filterOutliers(X, outlierFilter, repairMethod)
  else Y = X
}
  
filterOutliers = function(Matrix[Double] X, Matrix[Double] outlierFilter, Integer repairMethod = 1)
  return(Matrix[Double] fixed_X)
{
  rows = nrow(X)
  cols = ncol(X)
  if(repairMethod == 0) {
    sel = rowMaxs(outlierFilter) == 0
    X = removeEmpty(target = X, margin = "rows", select = sel)
  }
  else if(repairMethod == 1)
    X = (outlierFilter == 0) * X
  else if(repairMethod == 2)
  {
    outlierFilter = replace(target = (outlierFilter == 0), pattern = 0, replacement = NaN)
    X = outlierFilter * X
  }
  else
    stop("outlierByIQR: invalid argument - repair required 0-2 found: "+repairMethod)

  fixed_X = X
}

