Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,19 @@

### Added

- **Kingsbury-Zara constrained CAT (CCAT) content balancing**
(`fast_mlsirm.ccat_select`; in `mlsirm_core::exposure`). Single-step
content-balanced item selection: eligible groups with zero administered
items have priority, otherwise the eligible group with the maximal
target-minus-empirical-proportion discrepancy is chosen; within the chosen
group the unadministered item with maximal logistic 3PL Fisher information
`a^2 (Q/P) ((P-c)/(1-c))^2` is selected. Ties go to the lowest index
(documented deterministic deviation from catR's random tie-break).
Kingsbury & Zara (1989, doi:10.1207/s15324818ame0204_6) itself NOT read
(paywalled); the rule is implemented as reproduced by the R catR package
(`nextItem.R` `cbControl` branch; READ), and the information formula was
verified against catR `Ii.R`/`Pi.R`. Pinned oracles computed in exact
arithmetic by the adversarial spec review.
- **Owen approximate Bayesian sequential CAT** (`fast_mlsirm.owen_update`,
`fast_mlsirm.owen_cat`; in `mlsirm_core::exposure`). Closed-form
normal-approximation posterior moment updates for the 3PNO model
Expand Down
60 changes: 57 additions & 3 deletions crates/fast-mlsirm-py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@ use mlsirm_core::dif::{
MhDifConfig, MhDifRow, PurifyConfig, SibtestConfig,
};
use mlsirm_core::exposure::{
a_stratified as core_a_stratified, kl_information as core_kl_information,
kl_select as core_kl_select, owen_cat as core_owen_cat, owen_update as core_owen_update,
sympson_hetter as core_sympson_hetter, AStratifiedConfig, SympsonHetterConfig,
a_stratified as core_a_stratified, ccat_select as core_ccat_select,
kl_information as core_kl_information, kl_select as core_kl_select, owen_cat as core_owen_cat,
owen_update as core_owen_update, sympson_hetter as core_sympson_hetter, AStratifiedConfig,
SympsonHetterConfig,
};
use mlsirm_core::facets::fit_facets as core_fit_facets;
use mlsirm_core::factor::{
Expand Down Expand Up @@ -2328,6 +2329,58 @@ fn py_owen_cat(
Ok(out.into())
}

/// Kingsbury & Zara (1989) constrained CAT (CCAT) content-balanced item
/// selection (`mlsirm_core::exposure::ccat_select`). The primary source was
/// NOT read (paywalled; https://doi.org/10.1207/s15324818ame0204_6); the rule
/// is implemented as reproduced by the R catR package (`nextItem.R`,
/// `cbControl`): any eligible group with zero administered items has
/// priority, otherwise the eligible group with the maximal
/// target-minus-empirical-proportion discrepancy wins; within the chosen
/// group the most informative unadministered item (logistic 3PL Fisher
/// information, no D constant) is selected. Ties go to the lowest index
/// (documented deviation from catR's random tie-break). Returns
/// {selected, group, discrepancy, info}.
///
/// References:
/// Kingsbury, G. G., & Zara, A. R. (1989). Procedures for selecting items
/// for computerized adaptive tests. Applied Measurement in Education, 2(4),
/// 359-375. https://doi.org/10.1207/s15324818ame0204_6
/// Magis, D., & Raiche, G. (2012). Random generation of response patterns
/// under computerized adaptive testing with the R package catR. Journal of
/// Statistical Software, 48(8), 1-31. https://doi.org/10.18637/jss.v048.i08
#[pyfunction]
#[allow(clippy::too_many_arguments)]
fn py_ccat_select(
py: Python<'_>,
a: PyReadonlyArray1<'_, f64>,
b: PyReadonlyArray1<'_, f64>,
c: PyReadonlyArray1<'_, f64>,
groups: PyReadonlyArray1<'_, usize>,
targets: PyReadonlyArray1<'_, f64>,
administered: PyReadonlyArray1<'_, bool>,
theta0: f64,
) -> PyResult<Py<pyo3::types::PyDict>> {
let res = core_ccat_select(
a.as_slice()?,
b.as_slice()?,
c.as_slice()?,
groups.as_slice()?,
targets.as_slice()?,
administered.as_slice()?,
theta0,
)
.map_err(PyValueError::new_err)?;
let out = pyo3::types::PyDict::new(py);
out.set_item("selected", res.selected)?;
out.set_item("group", res.group)?;
out.set_item(
"discrepancy",
numpy::PyArray1::from_slice(py, &res.discrepancy),
)?;
out.set_item("info", numpy::PyArray1::from_slice(py, &res.info))?;
Ok(out.into())
}

/// Horn's parallel analysis for principal-component retention
/// (`mlsirm_core::parallel`; oracle: CRAN paran 1.5.6, PCA path). `data` is
/// a flattened row-major `n_persons * n_items` matrix; `centile` is 0 for
Expand Down Expand Up @@ -6146,6 +6199,7 @@ fn fast_mlsirm_core(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(py_kl_select, m)?)?;
m.add_function(wrap_pyfunction!(py_owen_update, m)?)?;
m.add_function(wrap_pyfunction!(py_owen_cat, m)?)?;
m.add_function(wrap_pyfunction!(py_ccat_select, m)?)?;
m.add_function(wrap_pyfunction!(guttman_lambdas, m)?)?;
m.add_function(wrap_pyfunction!(tenberge_mu, m)?)?;
m.add_function(wrap_pyfunction!(cronbach_alpha, m)?)?;
Expand Down
212 changes: 212 additions & 0 deletions crates/mlsirm-core/src/exposure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1054,3 +1054,215 @@ pub fn owen_cat(
sig2,
})
}

// ===================== Kingsbury-Zara (1989) constrained CAT content balancing =====================
//
// Kingsbury and Zara (1989) introduced constrained CAT (C-CAT) procedures
// for selecting items under content-area constraints. CITATION GOVERNANCE:
// the primary full text was NOT read (not obtainable in this environment);
// the exact content-balancing rule implemented here follows the catR
// `nextItem` documentation and source reproduction of the Kingsbury-Zara
// content-balancing control (READ: catR/R/nextItem.R, cbControl branch, and
// the nextItem manual page): first cover any content group with zero
// administered items, then select from the eligible group maximizing
// `target_prop - empirical_prop`, and finally choose the most informative
// item within that group. catR breaks group/item ties RANDOMLY; this
// implementation deterministically takes the LOWEST index (documented
// deviation for reproducible tests). Skipping groups with no unadministered
// item is an implementation safety rule, not verified K&Z text.
//
// The logistic 3PL Fisher information used within the chosen group,
// I_i(theta) = a_i^2 * (Q_i / P_i) * ((P_i - c_i) / (1 - c_i))^2,
// was verified against catR's `Ii.R` (I = dP^2 / (P Q)) with `Pi.R`'s
// P/dP at D = 1, d = 1, which reduce algebraically to this form
// (adversarial spec review against catR formulas).
//
// References:
// Kingsbury, G. G., & Zara, A. R. (1989). Procedures for selecting items
// for computerized adaptive tests. Applied Measurement in Education, 2(4),
// 359-375. https://doi.org/10.1207/s15324818ame0204_6 (NOT read; rule per
// the catR reproduction cited below)
// Magis, D., & Raiche, G. (2012). Random generation of response patterns
// under computerized adaptive testing with the R package catR. Journal of
// Statistical Software, 48(8), 1-31. https://doi.org/10.18637/jss.v048.i08

/// Result of one Kingsbury-Zara constrained-CAT selection step.
#[derive(Debug, Clone)]
pub struct CcatSelectResult {
/// Selected item index (unadministered, inside `group`).
pub selected: usize,
/// Content group the selection was constrained to.
pub group: usize,
/// Per-group `target - empirical` discrepancies (diagnostics; the
/// zero-coverage priority rule may override the argmax of this vector).
pub discrepancy: Vec<f64>,
/// Logistic 3PL Fisher information at `theta0` for ALL items
/// (administered items keep their value; masking applies to selection
/// only, matching `kl_select`).
pub info: Vec<f64>,
}

/// One Kingsbury-Zara content-balanced CAT selection step. See the section
/// comment for the exact rule, its source status, and references.
///
/// `groups[i]` is the content area of item `i` (must be `< targets.len()`);
/// `targets` are strictly positive proportions summing to 1 (tol 1e-8).
/// Errors on empty/mismatched inputs, invalid item parameters, non-finite
/// `theta0`, invalid targets, or when no group has an unadministered item.
pub fn ccat_select(
a: &[f64],
b: &[f64],
c: &[f64],
groups: &[usize],
targets: &[f64],
administered: &[bool],
theta0: f64,
) -> Result<CcatSelectResult, String> {
let n = a.len();
if n == 0 {
return Err("ccat_select: empty item pool".to_string());
}
if b.len() != n || c.len() != n || groups.len() != n || administered.len() != n {
return Err(format!(
"ccat_select: length mismatch (a: {n}, b: {}, c: {}, groups: {}, administered: {})",
b.len(),
c.len(),
groups.len(),
administered.len()
));
}
let n_groups = targets.len();
if n_groups == 0 {
return Err("ccat_select: targets must be non-empty".to_string());
}
if !theta0.is_finite() {
return Err("ccat_select: theta0 must be finite".to_string());
}
let mut tsum = 0.0;
for (g, &t) in targets.iter().enumerate() {
if !t.is_finite() || t <= 0.0 {
return Err(format!(
"ccat_select: targets must be finite positive, got targets[{g}] = {t}"
));
}
tsum += t;
}
if (tsum - 1.0).abs() > 1e-8 {
return Err(format!("ccat_select: targets must sum to 1, got {tsum}"));
}
for i in 0..n {
if !a[i].is_finite() || a[i] <= 0.0 {
return Err(format!(
"ccat_select: a must be finite positive, got a[{i}] = {}",
a[i]
));
}
if !b[i].is_finite() {
return Err(format!("ccat_select: b[{i}] must be finite"));
}
if !c[i].is_finite() || !(0.0..1.0).contains(&c[i]) {
return Err(format!(
"ccat_select: c must be in [0, 1), got c[{i}] = {}",
c[i]
));
}
if groups[i] >= n_groups {
return Err(format!(
"ccat_select: groups[{i}] = {} out of range for {n_groups} targets",
groups[i]
));
}
}

// Administered counts and eligibility (a group is eligible if it still
// has at least one unadministered item).
let mut k_g = vec![0usize; n_groups];
let mut eligible = vec![false; n_groups];
let mut k = 0usize;
for i in 0..n {
if administered[i] {
k_g[groups[i]] += 1;
k += 1;
} else {
eligible[groups[i]] = true;
}
}
if !eligible.iter().any(|&e| e) {
return Err("ccat_select: all items administered".to_string());
}

let discrepancy: Vec<f64> = (0..n_groups)
.map(|g| targets[g] - if k > 0 { k_g[g] as f64 / k as f64 } else { 0.0 })
.collect();

// catR rule: any eligible group with zero administered items has
// priority (lowest index = documented deterministic substitute for
// catR's random tie); otherwise the eligible group with the maximal
// target-minus-empirical discrepancy wins (strict > keeps the lowest
// index on ties).
let group = match (0..n_groups).find(|&g| eligible[g] && k_g[g] == 0) {
Some(g) => g,
None => {
let mut best: Option<(f64, usize)> = None;
for g in 0..n_groups {
if eligible[g] && best.map_or(true, |(bd, _)| discrepancy[g] > bd) {
best = Some((discrepancy[g], g));
}
}
best.expect("at least one eligible group").1
}
};

// Logistic 3PL Fisher information at theta0 for every item, computed in
// log space for numerical robustness (impl-review rounds 1-2 findings;
// regression-tested): the naive q/p * r^2 form produced NaN via inf * 0
// at logistic underflow (P -> c, including subnormal c) and spurious
// +inf from multiplication order at extreme a, and a pointwise p == 0
// guard masked genuinely informative extreme items. Algebra: with
// z = a(theta0 - b) and L = sigmoid(z), P = c + (1 - c) L, so
// r = (P - c)/(1 - c) = L exactly and
// I = a^2 (1 - c)(1 - L) L^2 / (c + (1 - c) L); when c = 0 this reduces
// to I = a^2 L (1 - L). ln L = -softplus(-z) and ln(1-L) = -softplus(z)
// are stable for all finite (or overflowed-to-inf) z. A genuinely
// astronomical information (a >= ~1e155 near theta0 = b) still
// overflows to +inf, which orders correctly in the argmax below.
let softplus = |x: f64| {
if x > 0.0 {
x + (-x).exp().ln_1p()
} else {
x.exp().ln_1p()
}
};
Comment thread
seonghobae marked this conversation as resolved.
Resolved
let info: Vec<f64> = (0..n)
.map(|i| {
let z = a[i] * (theta0 - b[i]);
let ln_l = -softplus(-z);
let ln_1ml = -softplus(z);
let ln_i = if c[i] == 0.0 {
2.0 * a[i].ln() + ln_l + ln_1ml
} else {
// p >= c > 0, so ln(p) is finite even when L underflows.
let p = c[i] + (1.0 - c[i]) * ln_l.exp();
2.0 * a[i].ln() + (1.0 - c[i]).ln() + ln_1ml + 2.0 * ln_l - p.ln()
};
ln_i.exp()
})
.collect();

// Most informative unadministered item within the chosen group; strict >
// keeps the lowest index on ties.
let mut best: Option<(f64, usize)> = None;
for i in 0..n {
if groups[i] == group && !administered[i] && best.map_or(true, |(bi, _)| info[i] > bi) {
best = Some((info[i], i));
}
}
let selected = best.expect("chosen group is eligible").1;

Ok(CcatSelectResult {
selected,
group,
discrepancy,
info,
})
}
2 changes: 2 additions & 0 deletions python/fast_mlsirm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
kl_select as kl_select,
owen_update as owen_update,
owen_cat as owen_cat,
ccat_select as ccat_select,
)
from .rsm import fit_rsm as fit_rsm, RsmFit as RsmFit
from .mixed import fit_mixed_items as fit_mixed_items, MixedFormatFit as MixedFormatFit, MixedItemParameters as MixedItemParameters
Expand Down Expand Up @@ -250,6 +251,7 @@
"kl_select",
"owen_update",
"owen_cat",
"ccat_select",
"AStratifiedResult",
"omega_total_1f",
"omega_total_1f_from_data",
Expand Down
Loading
Loading