2023-11-14 13:35:43 +00:00
|
|
|
#' Projection Distance of two matrices
|
2021-11-16 11:01:12 +00:00
|
|
|
#'
|
|
|
|
#' Defined as sine of the maximum principal angle between the column spaces
|
|
|
|
#' of the matrices
|
|
|
|
#' max{ sin theta_i, i = 1, ..., min(d1, d2) }
|
2021-12-07 18:00:00 +00:00
|
|
|
#' In case of rank(A) = rank(B) this measure is equivalent to
|
|
|
|
#' || A A' - B B' ||_2
|
|
|
|
#' where ||.||_2 is the spectral norm (max singular value).
|
|
|
|
#'
|
2021-11-16 11:01:12 +00:00
|
|
|
#' @param A,B matrices of size \eqn{p\times d_1} and \eqn{p\times d_2}.
|
|
|
|
#'
|
|
|
|
#' @export
|
|
|
|
dist.projection <- function(A, B, is.ortho = FALSE,
|
|
|
|
tol = sqrt(.Machine$double.eps)
|
|
|
|
) {
|
2021-12-07 18:00:00 +00:00
|
|
|
if (!is.matrix(A)) A <- as.matrix(A)
|
|
|
|
if (!is.matrix(B)) B <- as.matrix(B)
|
|
|
|
|
2021-11-16 11:01:12 +00:00
|
|
|
if (!is.ortho) {
|
|
|
|
qrA <- qr(A, tol)
|
2021-12-07 18:00:00 +00:00
|
|
|
rankA <- qrA$rank
|
2021-11-16 11:01:12 +00:00
|
|
|
A <- qr.Q(qrA)[, seq_len(qrA$rank), drop = FALSE]
|
|
|
|
qrB <- qr(B, tol)
|
2021-12-07 18:00:00 +00:00
|
|
|
rankB <- qrB$rank
|
2021-11-16 11:01:12 +00:00
|
|
|
B <- qr.Q(qrB)[, seq_len(qrB$rank), drop = FALSE]
|
2021-12-07 18:00:00 +00:00
|
|
|
} else {
|
|
|
|
rankA <- ncol(A)
|
|
|
|
rankB <- ncol(B)
|
2021-11-16 11:01:12 +00:00
|
|
|
}
|
|
|
|
|
2021-12-07 18:00:00 +00:00
|
|
|
if (rankA == 0 || rankB == 0) {
|
|
|
|
return(as.double(rankA != rankB))
|
|
|
|
} else if (rankA == 1 && rankB == 1) {
|
|
|
|
sigma.min <- min(abs(sum(A * B)), 1)
|
|
|
|
} else {
|
|
|
|
sigma.min <- min(La.svd(crossprod(A, B), 0, 0)$d, 1)
|
|
|
|
}
|
|
|
|
if (sigma.min < 0.5) {
|
|
|
|
sin(acos(sigma.min))
|
2021-11-16 11:01:12 +00:00
|
|
|
} else {
|
2021-12-07 18:00:00 +00:00
|
|
|
cos(asin(sigma.min))
|
2021-11-16 11:01:12 +00:00
|
|
|
}
|
|
|
|
}
|