# TODO: Add comment
# 
# Author: E.Korsching  20.02.2020
###############################################################################


# proximity measure : Pearson correlation
#   returned as a dissimilarity measure

prox.cor <- function(x, scale="", dist.obj=F, jitter.on=F){
	# x: matrix, data.frame: correlation is calculated column wise
	# scale: adjust cor output values: mv: mirror-invert : abs(-1..0..1) to 0..1,  lin : linear scaling from -1..0..1 to 0..1
	
	if(is.null(dim(x)|dim(x)[2]<2)){ stop("Matrix or data.frame with 2 and more columns need to be given")}
	if(jitter.on){ x <- apply(x,2,jitter) }		# intercepts problems with constant integer columns - CAVE: might result in wrong results !
	
	x.cor <- cor(x, use="everything")				# check manually for NAs - cor may have bugs in this constellation, values >1
	if(dist.obj){
		x.cor.vec <- x.cor[lower.tri(x.cor, diag=F)]		# from left to right from top to bottom - column wise
		
		if(scale=="mv"){		# mirror-invert: to get a positive dissimilarity matrix we have to transform the data by either
			# abs()		see the strength but not the direction of the cor
			#  mirror-inverted cor profiles and very identical cor profiles have the same values around 1
			x.cor.vec <- abs(x.cor.vec)
		}
		if(scale=="lin"){					# or by
			# linear scaling of cor coefficient from -1..0..1 to 0..1
			#   see both strength and direction of the cor
			x.cor.vec <- adaptScale(x.cor.vec,minS=-1,maxS=1,minT=0,maxT=1)
		}
		
		x.cor.vec <- 1-x.cor.vec		# make dissimilarity , greater numbers -> greater distance , analogous to Euclidean measure
		# create a dist object
		attr(x.cor.vec, "Size") <- dim(x.cor)[1]
		attr(x.cor.vec, "Metric") <- "1-cor"
		attr(x.cor.vec, "Labels") <- c(dimnames(x.cor)[[1]])
		class(x.cor.vec) <- "dissimilarity"
		y.cor <- x.cor.vec
	}else{
		if(scale=="mv"){		# to get a positive dissimilarity matrix we have to transform the data by either
			# abs()		see the strength but not the direction of the cor
			#  mirror-inverted cor profiles and very identical cor profiles have the same values around 1
			x.cor <- abs(x.cor)
		}
		if(scale=="lin"){					# or by
			# linear scaling of cor coefficient from -1..0..1 to 0..1
			#   see both strength and direction of the cor
			x.cor <- apply(x.cor, 2, adaptScale, minS=-1,maxS=1,minT=0,maxT=1)
		}
		y.cor <- 1-x.cor		# make dissimilarity , greater numbers -> greater distance , analogous to Euclidean measure
	}
	
	return(y.cor)
}



