# Kaiser normalization

#NormalizingWeight <- function(A, normalize=FALSE){
# if ("function" == mode(normalize)) normalize <- normalize(A)
# if (is.logical(normalize)){
#    if (normalize) normalize <- sqrt(rowSums(A^2))
#    else return(array(1, dim(A)))
#    }
# if (is.vector(normalize)) 
#    {if(nrow(A) != length(normalize))
#        stop("normalize length wrong in NormalizingWeight")
#     return(array(normalize, dim(A)))
#    }
# stop("normalize argument not recognized in NormalizingWeight")
#}
# 

#
# Version below submitted by Kim-Laura Speck, Uni Kassel, 25 October 2023
#
# avoid NaNs in matrix A by adding machine precision values to zeros


NormalizingWeight <- function(A, normalize = FALSE) {
  if (is.function(normalize)) normalize <- normalize(A)
 
  if (is.logical(normalize)) {
    if (normalize) {
      # Use pmax to ensure we never have a true zero (avoids NaNs)
      normalize <- pmax(sqrt(rowSums(A^2)), .Machine$double.eps)
    } else {
      return(array(1, dim(A)))
    }
  }
 
  if (is.vector(normalize)) {
    if (nrow(A) != length(normalize)) stop("normalize length wrong")
    # Return a matrix of the weights for easy element-wise division
    return(matrix(normalize, nrow(A), ncol(A)))
  }
 
  stop("normalize argument not recognized")
}