## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----setup_data---------------------------------------------------------------
set.seed(42)
n_steps <- 50
dim_z <- 5

# 1. Generate latent walk (smooth)
z_clean <- matrix(0, nrow = n_steps, ncol = dim_z)
for (t in 2:n_steps) {
  z_clean[t, ] <- z_clean[t-1, ] + rnorm(dim_z, 0, 0.1)
}

# 2. Inject Faults
z_corrupt <- z_clean
# Shock at t=21
z_corrupt[21, ] <- z_corrupt[21, ] + 5.0 
# Noise burst at t=30
z_corrupt[30, ] <- z_corrupt[30, ] + rnorm(dim_z, 0, 2.0)


## ----encoder------------------------------------------------------------------
# Random projection matrix
W <- matrix(rnorm(dim_z * dim_z), nrow = dim_z)

# Encoder function
encode <- function(z) {
  tanh(z %*% W)
}

# Encode the sequences
feat_clean <- encode(z_clean)
feat_corrupt <- encode(z_corrupt)

## ----reference_stats----------------------------------------------------------
ref_mean <- colMeans(feat_clean)
ref_sd <- apply(feat_clean, 2, sd)

# Ensure sd is positive (avoid division by zero)
ref_sd[ref_sd < 1e-6] <- 1.0

## ----sensor_reslik------------------------------------------------------------
library(resLIK)

# We analyze steps 2 to 50 (since TCS needs t-1)
z_test <- feat_corrupt[2:n_steps, ]

res_out <- reslik(z_test, ref_mean = ref_mean, ref_sd = ref_sd)

# Inspect diagnostics
summary(res_out$diagnostics$discrepancy)

## ----sensor_tcs---------------------------------------------------------------
z_prev <- feat_corrupt[1:(n_steps-1), ]
tcs_out <- tcs(z_test, z_prev)

# We expect a drop in consistency at the shock index (t=21 in original -> index 20 in reduced)
plot(tcs_out$consistency, type='l', main="Temporal Consistency", ylim=c(0,1))

## ----sensor_agreement---------------------------------------------------------
# Create a second view
z_view2 <- z_test + matrix(rnorm(length(z_test), 0, 0.1), ncol=dim_z)

# At the shock (row 20), make view2 disagree completely
z_view2[20, ] <- -z_test[20, ]

agree_out <- agreement(z_test, z_view2)

## ----control_surface----------------------------------------------------------
# Using default thresholds
# reslik_max_disc > 3.0 -> ABSTAIN
# tcs_consistency < 0.2 -> DEFER
# agreement < 0.3 -> DEFER

signals <- rlcs_control(res_out, tcs = tcs_out, agreement = agree_out)

## ----results------------------------------------------------------------------
table(signals)

# Check the signal at the shock point (t=21 of original -> index 20)
print(paste("Signal at Shock (t=21):", signals[20]))

# Check the signal at the noise burst (t=30 of original -> index 29)
print(paste("Signal at Noise (t=30):", signals[29]))

