% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/nmfkc.R
\name{nmfkc}
\alias{nmfkc}
\title{Optimize NMF with kernel covariates (Full Support for Missing Values)}
\usage{
nmfkc(
  Y,
  A = NULL,
  rank = NULL,
  data,
  epsilon = 1e-04,
  maxit = 5000,
  verbose = TRUE,
  ...
)
}
\arguments{
\item{Y}{Observation matrix (P x N), OR a formula object for Formula Mode.
In Formula Mode, use \code{Y1 + Y2 ~ A1 + A2} with \code{data}, or
\code{Y_matrix ~ A_matrix} for direct matrix evaluation.
Supports dot notation (\code{. ~ A1 + A2}) when \code{data} is supplied.}

\item{A}{Covariate matrix. Default is \code{NULL} (no covariates).
Ignored when \code{Y} is a formula.}

\item{rank}{Integer. The rank of the basis matrix \eqn{X} (Q). Preferred over \code{Q}.}

\item{data}{Optional. A data frame from which variables in the formula should be taken.}

\item{epsilon}{Positive convergence tolerance.}

\item{maxit}{Maximum number of iterations.}

\item{verbose}{Logical. If \code{TRUE} (default), prints matrix dimensions and elapsed time.}

\item{...}{Additional arguments passed for fine-tuning regularization, initialization, constraints,
and output control. This includes the backward-compatible arguments \code{Q} and \code{method}.
\itemize{
\item \code{Y.weights}: Optional weight matrix (P x N) or vector
(length N) with non-negative entries, analogous to the \code{weights}
argument of \code{\link[stats]{lm}}.  When supplied, the objective
becomes \eqn{\sum W_{ij} \, (Y_{ij} - (XB)_{ij})^2}
(i.e.\ \strong{linear} in \eqn{W}; \code{lm()}-style weighted
least squares).  Logical matrices (\code{TRUE} / \code{FALSE})
are also accepted and coerced to 1 / 0.  The primary use case is
missing-value masking for ECV / CV, where \eqn{W_{ij} \in \{0, 1\}}
(\code{FALSE} / \code{TRUE}) indicates held-out vs.\ used elements;
real-valued weights for observation-level importance weighting are
also supported.  Default \code{NULL}: if \code{Y} contains \code{NA}
a binary mask is auto-constructed (0 for \code{NA}, 1 elsewhere);
otherwise no weighting.
\item \code{X.L2.ortho}: Nonnegative penalty parameter for the orthogonality of \eqn{X} (default: 0).
It minimizes the off-diagonal elements of the Gram matrix \eqn{X^\top X}, reducing the correlation
between basis vectors (conceptually minimizing \eqn{\| X^\top X - \mathrm{diag}(X^\top X) \|_F^2}).
(Formerly \code{lambda.ortho}).
\item \code{B.L1}: Nonnegative penalty parameter for L1 regularization on \eqn{B = C A} (default: 0).
Promotes \strong{sparsity in the coefficients}. (Formerly \code{gamma}).
\item \code{C.L1}: Nonnegative penalty parameter for L1 regularization on \eqn{C} (default: 0).
Promotes \strong{sparsity in the parameter matrix}. (Formerly \code{lambda}).
\item \code{Q}: Backward-compatible name for the rank of the basis matrix (Q).
\item \code{method}: Objective function: Euclidean distance \code{"EU"} (default) or Kullback–Leibler divergence \code{"KL"}.
\item \code{X.restriction}: Constraint for columns of \eqn{X}. Options: \code{"colSums"} (default), \code{"colSqSums"}, \code{"totalSum"}, \code{"none"}, or \code{"fixed"}.
\code{"none"} applies no normalization to \eqn{X} after each update, allowing it to absorb the scale freely.
This is automatically set when \code{Y.symmetric = "bi"} or \code{"tri"}, because column normalization
would prevent \eqn{X X^\top} (or \eqn{X C X^\top}) from approximating \eqn{Y} at the correct scale.
\item \code{X.init}: Method for initializing the basis matrix \eqn{X}. Options: \code{"kmeans"} (default), \code{"kmeansar"}, \code{"runif"}, \code{"nndsvd"}, or a user-specified matrix. \code{"kmeansar"} applies \eqn{k}-means initialization and then fills zero entries with \code{Uniform(0, mean(Y)/100)}, analogous to NNDSVDar.
\item \code{nstart}: Number of random starts for initialization of \eqn{X} (default: 1).
Used by \code{kmeans} (when \code{X.init = "kmeans"} or \code{"kmeansar"}) and by the
multi-start evaluation (when \code{X.init = "runif"}).
For symmetric NMF (\code{Y.symmetric = "tri"} or \code{"bi"}), results are sensitive to
initial values; \code{nstart = 20} or higher is recommended.
\item \code{seed}: Integer seed for reproducibility (default: 123).
\item \code{C.init}: Optional numeric matrix giving the initial value of the parameter matrix \eqn{C}
(i.e., \eqn{\Theta}). If \code{A} is \code{NULL}, \code{C} has dimension \eqn{Q \times N} (equivalently \eqn{B});
otherwise, \code{C} has dimension \eqn{Q \times K} where \eqn{K = nrow(A)}. Default initializes all entries to 1.
\item \code{Y.symmetric}: Character string specifying the type of symmetric NMF.
\code{"none"} (default): standard NMF (\eqn{Y \approx XB}).
\code{"bi"}: 2-factor symmetric NMF (\eqn{Y \approx X X^\top}).
Internally implemented as the \code{"tri"} model with \eqn{C = I_Q} (identity matrix)
held fixed, so that \eqn{X} is updated freely without column normalization.
The multiplicative update for \eqn{X} uses cube-root damping
(\eqn{X \leftarrow X \circ (numerator / denominator)^{1/3}}) to prevent
oscillation, since \eqn{X} appears in both factors of the decomposition
(He et al., 2011, Proposition 1).
\code{"tri"}: 3-factor symmetric NMF (\eqn{Y \approx X C X^\top})
where \eqn{C} is a \eqn{Q \times Q} matrix representing cluster interactions
(Ding et al., 2006).
Both \code{"bi"} and \code{"tri"} require \code{Y} to be square
and cannot be used with covariate matrix \code{A}.
When \code{Y.symmetric = "bi"}, \code{X.restriction}
is automatically set to \code{"none"} (no column normalization), because
\eqn{C = I_Q} is fixed and cannot absorb the scale.
For \code{"tri"}, column normalization is retained (default \code{"colSums"})
because the free parameter matrix \eqn{C} absorbs the scale.
\item \code{prefix}: Prefix for column names of \eqn{X} and row names of \eqn{B} (default: "Basis").
\item \code{print.trace}: Logical. If \code{TRUE}, prints progress every 10 iterations (default: \code{FALSE}).
\item \code{print.dims}: Deprecated. Use \code{verbose} instead.
\item \code{detail}: Level of post-fit criterion computation.
\code{"full"} computes all criteria including silhouette, CPCC, dist.cor;
\code{"fast"} skips expensive distance-based criteria;
\code{"minimal"} returns only information criteria.
Default is \code{"full"}. For backward compatibility,
\code{save.time = TRUE} maps to \code{"fast"} and
\code{save.memory = TRUE} maps to \code{"minimal"}.
}}
}
\value{
A list with components:
\item{call}{The matched call, as captured by \code{match.call()}.}
\item{dims}{A character string summarizing the matrix dimensions of the model.}
\item{runtime}{A character string summarizing the computation time.}
\item{X}{Basis matrix. Column normalization depends on \code{X.restriction}.}
\item{B}{Coefficient matrix \eqn{B = C A}.}
\item{XB}{Fitted values for \eqn{Y}.}
\item{C}{Parameter matrix.}
\item{B.prob}{Soft-clustering probabilities derived from columns of \eqn{B}.}
\item{B.cluster}{Hard-clustering labels (argmax over \eqn{B.prob} for each column).}
\item{X.prob}{Row-wise soft-clustering probabilities derived from \eqn{X}.}
\item{X.cluster}{Hard-clustering labels (argmax over \eqn{X.prob} for each row).}
\item{A.attr}{List of attributes of the input covariate matrix \code{A}, containing metadata like lag order and intercept status if created by \code{nmfkc.ar} or \code{nmfkc.kernel}.}
\item{formula.meta}{If fitted via Formula Mode, a list with \code{formula}, \code{Y_cols}, and \code{A_cols}; otherwise \code{NULL}.}
\item{objfunc}{Final objective value.}
\item{objfunc.iter}{Objective values by iteration.}
\item{r.squared}{Coefficient of determination \eqn{R^2} between \eqn{Y} and \eqn{X B}.}
\item{method}{Character string indicating the optimization method used (\code{"EU"} or \code{"KL"}).}
\item{n.missing}{Number of missing (or zero-weighted) elements in \eqn{Y}.}
\item{n.total}{Total number of elements in \eqn{Y}.}
\item{rank}{The rank \eqn{Q} used in the factorization.}
\item{sigma}{The residual standard error, representing the typical deviation of the observed values \eqn{Y} from the fitted values \eqn{X B}.}
\item{mae}{Mean Absolute Error between \eqn{Y} and \eqn{X B}.}
\item{criterion}{A list of selection criteria, including \code{ICp} (\code{ICp1}, \code{ICp2}, \code{ICp3}), \code{CPCC}, \code{silhouette}, \code{AIC}, \code{BIC}, \code{dist.cor}, \code{B.prob.sd.min}, \code{B.prob.max.mean}, and \code{B.prob.entropy.mean}.}
}
\description{
\code{nmfkc} fits a nonnegative matrix factorization with kernel covariates
under the tri-factorization model \eqn{Y \approx X C A = X B}.

This function supports two major input modes:
\enumerate{
\item \strong{Matrix Mode (Existing)}: \code{nmfkc(Y=matrix, A=matrix, ...)}
\item \strong{Formula Mode (New)}: \code{nmfkc(formula=Y_vars ~ A_vars, data=df, rank=Q, ...)}
}

The rank of the basis matrix can be specified using either the \code{rank} argument
(preferred for formula mode) or the hidden \code{Q} argument (for backward compatibility).
}
\examples{
# Example 1. Matrix Mode (Existing)
X <- cbind(c(1,0,1),c(0,1,0))
B <- cbind(c(1,0),c(0,1),c(1,1))
Y <- X \%*\% B
rownames(Y) <- paste0("P",1:nrow(Y))
colnames(Y) <- paste0("N",1:ncol(Y))
print(X); print(B); print(Y)
res <- nmfkc(Y,rank=2,epsilon=1e-6)
res$X
res$B

# Example 2. Formula Mode
set.seed(1)
dummy_data <- data.frame(Y1=rpois(10,5), Y2=rpois(10,10),
                         A1=abs(rnorm(10,5)), A2=abs(rnorm(10,3)))
res_f <- nmfkc(Y1 + Y2 ~ A1 + A2, data=dummy_data, rank=2)

# Example 3. Symmetric NMF (bi: Y ~ X X^T)
S <- matrix(c(3,0,2, 0,3,1, 2,1,2), nrow=3)
res_bi <- nmfkc(S, rank=2, Y.symmetric="bi")
res_bi$X   # basis matrix (no column normalization)
res_bi$XB  # reconstruction X \%*\% t(X)

# Example 4. Symmetric NMF (tri: Y ~ X C X^T)
res_tri <- nmfkc(S, rank=2, Y.symmetric="tri")
res_tri$C  # Q x Q cluster interaction matrix
res_tri$XB # reconstruction X \%*\% C \%*\% t(X)

}
\references{
Satoh, K. (2024). Applying Non-negative Matrix Factorization with Covariates
to the Longitudinal Data as Growth Curve Model. arXiv:2403.05359.
\url{https://arxiv.org/abs/2403.05359}

Satoh, K. (2025). Applying non-negative matrix factorization with covariates
to multivariate time series data as a vector autoregression model.
\emph{Japanese Journal of Statistics and Data Science}. arXiv:2501.17446.
\doi{10.1007/s42081-025-00314-0}

Satoh, K. (2025). Applying non-negative matrix factorization with covariates
to label matrix for classification. arXiv:2510.10375.
\url{https://arxiv.org/abs/2510.10375}

Ding, C., Li, T., Peng, W., & Park, H. (2006). Orthogonal Nonnegative Matrix
Tri-Factorizations for Clustering.
In \emph{Proc. 12th ACM SIGKDD} (pp. 126--135).
\doi{10.1145/1150402.1150420}
}
\seealso{
\code{\link{nmfkc.cv}}, \code{\link{nmfkc.rank}}, \code{\link{nmfkc.kernel}}, \code{\link{nmfkc.ar}}, \code{\link{predict.nmfkc}}
}
