// This Stan block defines a Bayesian PCA, Joseph H. Sakaya & Suleiman A. Khan but with the dependent variable changed to Binomial and missing values added by Sean  van der Merwe, UFS
data {
	int<lower=0> N; // Number of samples
	int<lower=0> D; // The original dimension
	int<lower=0> K; // The maximum latent dimension, must be < D
	int<lower=0> M; // The binomial maximum
	int<lower = 0> N_obs; // Total number of observed values in matrix
	int<lower=0, upper=M> X[N_obs]; // The data matrix as vector, only observed
	int<lower = 1, upper = N*D> ii_obs[N_obs]; 
  // Indicator vector of which values are observed in the matrix (column wise)
}

parameters {
	matrix[N, K] Z; // The latent matrix
	matrix[D, K] W; // The weight matrix
	vector<lower=0>[K] alpha; // ARD prior
}

transformed parameters{
	vector<lower=0>[K] t_alpha;
	vector[N*D] zw;
  t_alpha = inv(sqrt(alpha));
  zw = to_vector(Z*W');
}

model {
	to_vector(Z) ~ normal(0,1);
	alpha ~ gamma(1e-3,1e-3);				
	for(k in 1:K) W[,k] ~ normal(0, t_alpha[k]);
	X ~ binomial_logit(M, zw[ii_obs]);
}

CXXFLAGS = -O2 -Wall $(DEBUGFLAG) -mfpmath=sse -msse2 -mstackrealign $(LTO)

std::vector<double, std::allocator<double> > constrain_pars(std::vector<double, std::allocator<double> >)

std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > constrained_param_names(bool, bool)

Rcpp::NumericVector grad_log_prob(std::vector<double, std::allocator<double> >, bool)

Rcpp::NumericVector log_prob(std::vector<double, std::allocator<double> >, bool, bool)

std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > param_fnames_oi()

std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > param_names()