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

# How to invoke this dml script GNMF.dml?
# Assume GNMF_HOME is set to the home of the dml script
# Assume input and output directories are on hdfs as INPUT_DIR and OUTPUT_DIR
# Assume rows = 2000 and cols = 1500 for v,  rows = 2000 and cols = 50 for w, rows = 50 and cols = 1500 for h, max_iteration = 3
# hadoop jar SystemDS.jar -f $GNMF_HOME/GNMF.dml -args "$INPUT_DIR/in/v" "$INPUT_DIR/in/w" "$INPUT_DIR/in/h" 3 "$OUPUT_DIR/out/w" "$OUTPUT_DIR/out/h"

vFile = ifdef($1, "")
wFile = ifdef($2, "")
hFile = ifdef($3, "")
wOutFile = ifdef($5, "")
hOutFile = ifdef($6, "")

V = read(vFile);
W = read(wFile);
H = read(hFile);
max_iteration = $4;
i = 0;

Eps = 10^-8;

while(i < max_iteration) {
	H = H * ((t(W) %*% V) / (((t(W) %*% W) %*% H)+Eps));
	W = W * ((V %*% t(H)) / ((W %*% (H %*% t(H)))+Eps));
	i = i + 1;
}

write(W, wOutFile, format="text");
write(H, hOutFile, format="text");