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

# DML builtin method for PageRank algorithm (power iterations)
#
# INPUT:
# ------------------------------------------------------------------------------
# G           Input Matrix
# p           initial page rank vector (number of nodes), e.g., rand intialized
#             default rand initialized with seed
# e           additional customization, default vector of ones
# u           personalization vector (number of nodes), default vector of ones
# alpha       teleport probability
# max_iter    maximum number of iterations
# seed        seed for default rand initialization of page rank vector
# ------------------------------------------------------------------------------
#
# OUTPUT:
# ---------------------------------------------------------------------------
# pprime      computed pagerank
# ---------------------------------------------------------------------------

m_pageRank = function (Matrix[Double] G, Matrix[Double] p = as.matrix(1),
  Matrix[Double] e = as.matrix(1), Matrix[Double] u = as.matrix(1),
  Double alpha = 0.85, Int max_iter = 20, Int seed = -1)
  return (Matrix[double] pprime)
{
  # default vectorized if not passed
  if( length(p) == 1 )
    p = rand(rows=ncol(G), cols=1, seed=seed);
  if( length(e) == 1 )
    e = matrix(1, rows=nrow(G), cols=1);
  if( length(u) == 1 )
    u = matrix(1, rows=1, cols=ncol(G));

  # page rank computation via power iterations
  i = 0;
  while( i < max_iter ) {
    p = alpha * (G %*% p) + (1 - alpha) * (e %*% u %*% p);
    i += 1;
  }
  pprime = p
}
