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

# Apply robust scaling using precomputed medians and IQRs
#
# INPUT:
# -------------------------------------------------------------------------------------
# X     Input feature matrix of shape n-by-m
# med   Column medians (Q2) of shape 1-by-m
# q1    Column first quantiles (Q1) of shape 1-by-m
# q3    Column first quantiles (Q3) of shape 1-by-m
# -------------------------------------------------------------------------------------
#
# OUTPUT:
# -------------------------------------------------------------------------------------
# Y     Scaled output matrix of shape n-by-m
# -------------------------------------------------------------------------------------

m_scaleRobustApply = function(Matrix[Double] X, Matrix[Double] med, Matrix[Double] q1, Matrix[Double] q3)
  return (Matrix[Double] Y)
{
  iqr = q3 - q1

  # Ensure robust scaling is safe by replacing invalid IQRs
  iqr = replace(target=iqr, pattern=0, replacement=1)
  iqr = replace(target=iqr, pattern=NaN, replacement=1)

  # Apply robust transformation
  Y = (X - med) / iqr
}
