# Tests for IsingPL() (pseudo-likelihood):
# (a) 'beta' must actually be used (previously ignored in the C++ code) and
#     the result must equal the manually computed pseudo-log-likelihood;
# (b) real-valued response options must be preserved (previously silently
#     truncated to integers by an IntegerVector parameter);
# (c) the default binary 0/1, beta = 1 path must reproduce the pre-fix value.
# Plain stopifnot tests, no package dependencies beyond IsingSampler itself.

library("IsingSampler")

# Manual R implementation of the node-conditional pseudo-log-likelihood:
# logPL = sum_i sum_j [ beta * x_ij * e_ij
#                       - log( exp(beta*r1*e_ij) + exp(beta*r2*e_ij) ) ]
# with e_ij = thresholds_j + sum_jj x_i,jj * graph_j,jj
plR <- function(x, graph, thresholds, beta, responses) {
  logPL <- 0
  for (i in seq_len(nrow(x))) {
    for (j in seq_len(ncol(x))) {
      e <- thresholds[j] + sum(x[i, ] * graph[j, ])
      logPL <- logPL + beta * x[i, j] * e -
        log(exp(beta * responses[1] * e) + exp(beta * responses[2] * e))
    }
  }
  logPL
}

## Small 3-node test model -----------------------------------------------------
set.seed(42)
N <- 3
graph <- matrix(0, N, N)
graph[upper.tri(graph)] <- c(0.5, -0.3, 0.8)
graph <- graph + t(graph)
thresholds <- c(-0.2, 0.1, 0.3)
x <- as.matrix(IsingSampler(10, graph, thresholds, responses = c(0L, 1L)))

## (a) beta is used and matches the manual R computation -----------------------
pl1 <- IsingPL(x, graph, thresholds, beta = 1)
pl2 <- IsingPL(x, graph, thresholds, beta = 2)
stopifnot(pl1 != pl2)
stopifnot(isTRUE(all.equal(pl1, plR(x, graph, thresholds, 1, c(0, 1)))))
stopifnot(isTRUE(all.equal(pl2, plR(x, graph, thresholds, 2, c(0, 1)))))

## (b) non-integer response options are preserved ------------------------------
xHalf <- x * 0.5  # data on the c(0, 0.5) response scale
plHalf  <- IsingPL(xHalf, graph, thresholds, beta = 1, responses = c(0, 0.5))
plSeven <- IsingPL(xHalf, graph, thresholds, beta = 1, responses = c(0, 0.7))
stopifnot(plHalf != plSeven)
stopifnot(isTRUE(all.equal(plHalf,
                           plR(xHalf, graph, thresholds, 1, c(0, 0.5)))))
stopifnot(isTRUE(all.equal(plSeven,
                           plR(xHalf, graph, thresholds, 1, c(0, 0.7)))))

## (c) backward compatibility: binary 0/1 with beta = 1 ------------------------
# Pre-fix reference value computed with IsingSampler before this fix on the
# exact same seeded example (seed 42, model and data as above):
preFixReference <- -16.420410068413286
stopifnot(isTRUE(all.equal(pl1, preFixReference)))

## Numerical stability: large beta must not overflow to NaN/Inf ----------------
plBig <- IsingPL(x, graph, thresholds, beta = 500)
stopifnot(is.finite(plBig))

cat("All pseudo-likelihood tests passed.\n")
