content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
## File Name: cdm_timecat.R
## File Version: 0.02
cdm_timecat <- function(z0, label, print=FALSE)
{
if (print){
cat(label) ; z1 <- Sys.time(); print(z1-z0) ; z0 <- z1
}
return(z0)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/cdm_timecat.R
|
## File Name: cdm_trim_increment.R
## File Version: 0.10
cdm_trim_increment <- function( increment, max.increment, type=1 )
{
increment[ is.na(increment) ] <- 0
if ( type==1){
increment <- ifelse(abs(increment)> max.increment,
sign(increment)*max.increment, increment )
}
if ( type==2){
eps <- 1E-80
ci <- ceiling( abs(increment) / ( abs( max.increment) + eps ) )
increment <- ifelse( abs( increment) > abs(max.increment),
increment/(2*ci), increment )
}
return(increment)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/cdm_trim_increment.R
|
## File Name: check.input.R
## File Version: 1.14
################################################################################
# check consistency of input to din-method (data, q.matrix, ...) #
################################################################################
check.input <- function( data, q.matrix, conv.crit=0.001, maxit=100,
constraint.guess=NULL, constraint.slip=NULL,
guess.init=rep(.2, ncol(data) ), slip.init=guess.init,
weights=rep( 1, nrow( data ) ), rule="DINA",
progress=TRUE ){
# Call: from din()
# Input: cf. din()
# Output: if possible cleaned arguments
# else a warning message which leads to the termination of the procedure.
################################################################################
# check consistency of data object #
################################################################################
# check for data classes matrix and data.frame
if ((data.class(data) !="matrix") & (data.class(data) !="data.frame"))
return(warning("data must be matrix or data frame"))
data <- as.matrix(data)
# check for data entries being dichotomous or missing
gt <- data[ is.na( data )==F ]
# gt <- data[ ! is.na( data) ]
# if(any(gt==9||gt==99||gt==.99)){
if( sum(gt==9 ) + sum(gt==99 ) + sum(gt==.99) > 0 ){
return(warning("Recode your data! Only responses with values 0 or 1 (or NA) are valid.",
"\nMaybe missing values coded as 9, 99, .99.\n"))
}
# return all response pattern not containing NA
gt <- unique( gt[ gt %in% c(0,1)==F ] )
if(length(gt) > 0){
return(warning("Recode your data! Only responses with values 0 or 1 (or NA) are valid.\n"))
}
# check for provision of row- and colnames
if(is.null(rownames(data))) rownames(data) <- 1:nrow(data)
if(is.null(colnames(data))) colnames(data) <- paste("Item",1:ncol(data),sep="")
################################################################################
# check consistency of q.matrix object #
################################################################################
# check for data classes matrix and data.frame
if ((data.class(q.matrix) !="matrix") & (data.class(q.matrix) !="data.frame"))
return(warning("data must be matrix or data frame"))
att.lbl <- attributes(q.matrix)$skill.labels
q.matrix <- as.matrix(q.matrix)
# return all response pattern not containing NA
# gt_q <- data[ is.na( q.matrix )==F ]
gt_q <- q.matrix[ ! is.na( q.matrix ) ]
# gt_q <- unique( gt_q[ gt_q %in% c(0,1)==F ] )
gt_q <- setdiff( unique( gt_q ), c(0,1) )
if(length(gt) > 0){ return(warning("Check your Q-matrix! Only values 0 or 1 are valid.\n")) }
# check if q.matrix obtains same number of items as the data set
if(nrow(q.matrix)!=ncol(data)){ return(warning("Check your Q-matrix! Number of assigned items (rows)
must fit the number of items in the data (columns).\n")) }
# return warning message if there is a Zero-Row in the q.matrix
rq <- rowSums(q.matrix)
if (min(rq)==0){
return(warning("Check your Q-matrix! The following items are not related to attributes:"
, "\n", "Items ", paste( (1:(nrow(q.matrix)))[ rq==0], collapse=", " ), "\n" ))}
# check for provision of row- and colnames
if(is.null(rownames(q.matrix))) rownames(q.matrix) <- paste("Item",1:nrow(q.matrix),sep="")
if(is.null(colnames(q.matrix))) colnames(q.matrix) <- paste("Skill",1:ncol(q.matrix),sep="")
# check for provision of skill labels
if(is.null(att.lbl)) attr(q.matrix, "skill.labels") <- colnames(q.matrix)
if(length(att.lbl) !=ncol(q.matrix) & length(att.lbl) !=0){
attr(q.matrix, "skill.labels") <- colnames(q.matrix)
warning("Unreasonable number of skill labels; skill labels replaced by colnames of q.matrix")
}else{
attr(q.matrix, "skill.labels") <- att.lbl
}
################################################################################
# check consistency of arguments for parameter estimation routine #
################################################################################
if(!is.numeric(conv.crit)|!is.numeric(maxit)) return(warning("Check your routine criteria"))
if(conv.crit<=0|maxit<1) return(warning("Check your routine criteria"))
################################################################################
# check consistency of constraint arguments for parameter boundaries #
################################################################################
# slip constraints see help files
if(!is.null(constraint.slip)){ #NULL permitted
if (any(is.na(constraint.slip))|any(!is.numeric(constraint.slip))| #numeric values only
(!is.vector(constraint.slip) & (data.class(constraint.slip) !="matrix") &
(data.class(constraint.slip) !="data.frame"))| #object typ
(length(constraint.slip %% 2 !=0) & ncol(constraint.slip)!=2)){ #two columns!
return(warning("check your error parameter constraints. See Help-files."))
}
if(is.vector(constraint.slip))
# try(constraint.slip <- matrix(constraint.slip, ncol=2, byrow=T))
if(data.class(constraint.slip)=="data.frame"){
onstraint.slip <- as.matrix(constraint.slip) }
if(any(duplicated(constraint.slip[,1]))| #no duplicates
any(!constraint.slip[,1]%in%1:ncol(data))| #first column may only be indicees
all(!(constraint.slip[,2]>=0 & constraint.slip[,2]<=1))){ #all entries between 0 and 1
return(warning("check your error parameter constraints. See Help-files."))
}
}
# guessing constraints see help files
if(!is.null(constraint.guess)){ #NULL permitted
if(any(is.na(constraint.guess))|any(!is.numeric(constraint.guess))| #numeric values only
(!is.vector(constraint.guess) & (data.class(constraint.guess) !="matrix")
& (data.class(constraint.guess) !="data.frame"))| #object typ
(length(constraint.guess)%%2!=0 & ncol(constraint.guess)!=2)){ #two columns!
return(warning("check your error parameter constraints. See Help-files."))
}
# if(is.vector(constraint.guess))
# try(constraint.guess <- matrix(constraint.guess, ncol=2, byrow=T))
if(data.class(constraint.guess)=="data.frame"){
constraint.guess <- as.matrix(constraint.guess)
}
if(any(duplicated(constraint.guess[,1])) | #no duplicates
any(!constraint.guess[,1] %in% 1:ncol(data))| #first column may only be indicees
all(!(constraint.guess[,2]>=0&constraint.guess[,2]<=1))){ #all entries between 0 and 1
return(warning("check your error parameter constraints. See Help-files."))
}
}
################################################################################
# check consistency of init arguments #
################################################################################
# slipping initialization see help files
# try({slip.init <- as.vector(slip.init)
# guess.init <- as.vector(guess.init)}, silent=T)
if(!is.null(slip.init)){
if(any(is.na(slip.init))|
!all(is.numeric(slip.init))|
!all(slip.init>=0&slip.init<=1)|
(length(slip.init)!=ncol(data)))
return(warning("Check your initial error parameter values. See Help-files."))
}
# guessing initialization see help files
if(!is.null(guess.init)){
if(any(is.na(guess.init))|
!all(is.numeric(guess.init))|
!all(guess.init>=0&guess.init<=1)|
(length(guess.init)!=ncol(data)))
return(warning("Check your initial error parameter values. See Help-files."))
}
################################################################################
# check consistency of weight argument #
################################################################################
# weight see help files
# try(weights <- as.vector(weights), silent=T)
if(any(is.na(weights)) | is.null(weights) | !all(is.numeric(weights)) |
!all(weights>0)| (length(weights)!=nrow(data)))
return(warning("Check your specificated weights of the response patterns. See Help-files."))
################################################################################
# check consistency of rule argument #
################################################################################
# rule specification see help files
if(length(rule)!=1 & length(rule)!=ncol(data)){
return(warning("Check the condensation rule for parameter estimation. The character string has
to be of length 1 or of length ncol(data)."))
}
# try(if(!all(unique(rule)%in%c("DINA", "DINO")))
if(!all(unique(rule)%in%c("DINA", "DINO"))){
return(warning("Check the condensation rule for parameter estimation. Only \"DINA\" and \"DINO\" possible.")) }
################################################################################
# check consistency of progress argument #
################################################################################
# progress see help files
if(!(is.logical(progress))){
return(warning("Check specification whether or not the estimation progress should be printed."))
}
return(list("data"=data, "q.matrix"=q.matrix,
"conv.crit"=conv.crit, "maxit"=maxit, "constraint.guess"=constraint.guess,
"constraint.slip"=constraint.slip, "guess.init"=guess.init,
"slip.init"=slip.init, "weights"=weights, "rule"=rule, "progress"=progress))
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/check.input.R
|
## File Name: chisq_compute.R
## File Version: 0.02
chisq_compute <- function(obs, exp)
{
chisq <- sum( ( obs - exp)^2 / exp )
return(chisq)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/chisq_compute.R
|
## File Name: coef.R
## File Version: 0.06
########################
# coef for din object
coef.din <- function (object, ...)
{
cof <- object$coef
return(cof)
}
########################
# coef for gdina object
coef.gdina <- function (object, ...)
{
cof <- object$coef
return(cof)
}
########################
# coef for gdm object
coef.gdm <- function (object, ...)
{
cof <- object$item
return(cof)
}
########################
# coef for mcdina object
coef.mcdina <- function (object, ...)
{
cof <- object$item
return(cof)
}
########################
# coef for slca object
coef.slca <- function (object, ...)
{
cof <- object$Xlambda
return(cof)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/coef.R
|
## File Name: confint.din.R
## File Version: 0.172
# confidence interval for objects of class din
confint.din <- function(object, parm, level=.95, extended=FALSE,
ind.item.skillprobs=TRUE, ind.item=FALSE, diagcov=FALSE, h=.001,...)
{
if ( ! missing( parm) ){
partable <- object$partable
g1 <- parm %in% partable$parnames
if ( mean(g1) < 1 ){
stop("Not all requested parameters in parameter table!\n")
}
p1 <- partable[ partable$free,]
g1 <- parm %in% p1[,"parnames"]
if ( mean(g1) < 1 ){
extended <- TRUE
}
}
v1 <- vcov( object, extended=extended, infomat=FALSE,
ind.item.skillprobs=ind.item.skillprobs,
ind.item=ind.item, diagcov=diagcov, h=h,...)
c1 <- attr( v1, "coef" )
c1 <- c1[ ! duplicated(names(c1) ) ]
se1 <- sqrt( diag( v1 ) )
q1 <- stats::qnorm( 1 - (1-level)/2 )
res <- data.frame( c1 - q1*se1, c1+q1*se1)
rownames(res) <- names(c1)
colnames(res) <- c("2.5 %", "97.5 %")
if ( ! missing(parm) ){
res <- res[ parm, ]
}
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/confint.din.R
|
## File Name: csink.R
## File Version: 1.02
csink <- function( file)
{
if ( ! is.null( file ) ){
sink()
}
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/csink.R
|
## File Name: dataframe_summary.R
## File Version: 0.11
dataframe_summary <- function( dfr, exclude_index, labels, na.rm=TRUE )
{
if ( ! is.null(exclude_index) ){
dfr1 <- dfr[, - exclude_index, drop=FALSE]
} else {
dfr1 <- dfr
}
dfr_summary <- data.frame( "Parm"=labels,
"M"=apply( dfr1, 2, mean, na.rm=na.rm),
"SD"=apply( dfr1, 2, stats::sd, na.rm=na.rm),
"Min"=apply( dfr1, 2, min, na.rm=na.rm),
"Max"=apply( dfr1, 2, max, na.rm=na.rm )
)
rownames(dfr_summary) <- NULL
return(dfr_summary)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/dataframe_summary.R
|
## File Name: deltaMethod.R
## File Version: 0.11
###############################################################
deltaMethod <- function( derived.pars, est, Sigma, h=1E-5 )
{
#***
ND <- length(derived.pars)
#** select h parameters according to size of parameters
abs_par <- abs(est)
hvec <- h * ifelse( abs_par > 1, abs_par, 1 )
NP <- length(est)
#** create design matrix
M0 <- matrix( est, nrow=1, ncol=NP)
M1 <- diag(hvec)
M1 <- M0[ rep(1,NP), ] + M1
M2 <- as.data.frame( rbind( M0, M1 ) )
colnames(M2) <- names(est)
#--- loop over parameters
A <- matrix( NA, nrow=ND, ncol=NP)
rownames(A) <- names(derived.pars)
colnames(A) <- names(est)
derived.est <- rep( NA, ND)
names(derived.est) <- names(derived.pars)
for (dd in 1:ND){
#dd <- 1
Md <- stats::model.matrix(derived.pars[[dd]], M2 )
if ( ncol(Md) > 1 ){
Md <- Md[,2]
}
A[ dd, ] <- ( Md[-1] - Md[1] ) / hvec
derived.est[dd] <- Md[1]
}
#--- covariance matrix
derived.Sigma <- A %*% Sigma %*% t(A)
#--- univariate tests
se <- sqrt( diag(derived.Sigma) )
univarTest <- data.frame( parm=names(derived.pars),
est=derived.est, se=se, t=derived.est / se,
p=2*stats::pnorm( - abs( derived.est / se) ) )
rownames(univarTest) <- NULL
#--- multivariate test
R <- diag(ND)
wt <- WaldTest( delta=derived.est, vcov=derived.Sigma, R=R, nobs=NA)
#--- output
res <- list( coef=derived.est, vcov=derived.Sigma, se=se, A=A,
univarTest=univarTest, WaldTest=wt)
return(res)
}
###############################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/deltaMethod.R
|
## File Name: din.R
## File Version: 2.524
################################################################################
# Main function for parameter estimation in cognitive diagnosis models #
################################################################################
din <- function( data, q.matrix, skillclasses=NULL, conv.crit=0.001, dev.crit=10^(-5),
maxit=500, constraint.guess=NULL, constraint.slip=NULL,
guess.init=rep(.2, ncol(data) ), slip.init=guess.init,
guess.equal=FALSE, slip.equal=FALSE,
zeroprob.skillclasses=NULL, weights=rep( 1, nrow( data ) ),
rule="DINA", wgt.overrelax=0, wgtest.overrelax=FALSE,
param.history=FALSE, seed=0, progress=TRUE, guess.min=0,
slip.min=0, guess.max=1, slip.max=1)
{
# data: a required matrix of binary response data, whereas the items are in the columns
# and the response pattern in the rows. NA values are allowed.
#
# q.matrix: a required binary matrix describing which attributes are required, coded by 1,
# and which attributes are not required, coded by 0, to master the items, whereas the
# attributes are in the columns and the items in the rows.
#
# conv.crit: termination criterion of the iterations defined as the maximum change in parameter
# estimates. Iteration ends if maximal parameter change is below this value.
#
# maxit: maximal number of iterations.
#
# constraint.guess: an optional matrix of fixed guessing parameters. The first column of this
# matrix indicates the items whose guessing parameters are fixed and the second column
# the values the guessing parameters are fixed to.
#
# constraint.slip: an optional matrix of fixed slipping parameters. The first column of this matrix
# indicates the items whose guessing parameters are fixed and the second column the values
# the guessing parameters are fixed to.
#
# guess.init: an optional initial vector of guessing parameters. Guessing parameters are bounded between
# 0 and 1.
#
# slip.init: an optional initial vector of guessing parameters. Slipping parameters are bounded between
# 0 and 1.
#
# guess.equal: an optional logical indicating if all guessing parameters are equal to each other
#
# slip.equal: an optional logical indicating if all slipping parameters are equal to each other
#
# zeroprob.skillclasses: an optional vector of integers which indicates which skill classes should have
# zero probability
#
# weights: an optional vector of weights for the response pattern. Noninteger weights allow for different
# sampling schemes.
#
# wgt.overrelax ... convergence weight (overrelaxed EM)=> w=0 standard EM
# rule: an optional character string or vector of character strings specifying the model rule that is used.
# The character strings must be of "DINA" or "DINO". If a vector of character strings is specified,
# implying an itemwise condensation rule, the vector must be of length ncol(data). The default is the
# condensation rule "DINA" for all items.
#
# progress: an optional logical indicating whether the function should print the progress of iteration.
z0 <- Sys.time()
if ( progress){
cat("---------------------------------------------------------------------------------\n")
}
cl <- match.call()
################################################################################
# check consistency of input (data, q.matrix, ...) #
################################################################################
I <- ncol(data)
if ( is.null( colnames(data) ) ){
colnames(data) <- paste0("I", 1:I )
}
# different inits if seed larger than zero
if ( seed > 0 ){
set.seed(seed)
slip.init <- stats::runif( I, 0, .4 )
guess.init <- stats::runif( I, 0, .4 )
}
clean <- check.input(data, q.matrix, conv.crit, maxit, constraint.guess,
constraint.slip, guess.init, slip.init, weights, rule, progress)
if (is.character(clean)) return(clean)
dat.items <- clean$data; q.matrix <- clean$q.matrix; conv.crit <- clean$conv.crit;
maxit <- clean$maxit; constraint.guess <- clean$constraint.guess;
constraint.slip <- clean$constraint.slip; guess.init <- clean$guess.init;
slip.init <- clean$slip.init; weights <- clean$weights; rule <- clean$rule;
progress <- clean$progress
################################################################################
# model specification: DINA, DINO or itemwise specification of DINA or DINO #
################################################################################
if ( length(rule)==1){
if ( rule=="DINA" ){ r1 <- "DINA MODEL" }
if ( rule=="DINO" ){ r1 <- "DINO MODEL" }
} else { r1 <- "Mixed DINA & DINO Model" }
################################################################################
# display on R console #
################################################################################
disp <- r1
s1 <- Sys.time()
if (progress){
cat(disp,"\n")
cat( "**", paste(s1), "\n" )
cat("---------------------------------------------------------------------------------\n")
utils::flush.console()
}
################################################################################
# definition of model parameters #
################################################################################
I <- nrow(dat.items) # number of persons
J <- ncol(dat.items) # number of items
K <- ncol(q.matrix) # number of attributes
L <- 2^K # number of latent class pattern of attributes
dat.items <- as.matrix( dat.items)
q.matrix <- as.matrix( q.matrix)
################################################################################
# Initialization and missing data handling #
################################################################################
# initialize guessing and slipping parameters
# without constraints, the default is set equal to .2 for all items
guess <- guess.init ; slip <- slip.init
# missing data is coded by 9
resp <- 1 - is.na(dat.items)
dat.items[ resp==0 ] <- 9
# standardize weights such that the sum of defined weights is equal to the number of rows in the data frame
weights <- nrow(dat.items)*weights / sum(weights )
################################################################################
# calculate item response patterns #
################################################################################
# string with item response patterns
item.patt.subj <- dat.items[,1]
for (jj in 2:J){
item.patt.subj <- paste( item.patt.subj, dat.items[,jj], sep="")
}
# calculate frequency of each item response pattern
a2 <- rowsum( rep(1,I), item.patt.subj)
item.patt <- a2[,1]
# sort item response pattern according to their absolute frequencies
six <- item.patt
# define data frame 'item.patt' with item response pattern and its frequency (weight)
item.patt <- cbind( "pattern"=names(six), "freq"=as.numeric(as.vector( six ) ) )
# calculate weighted frequency for each item response pattern
h1 <- rowsum( weights, item.patt.subj )
item.patt[,2] <- h1[ match( item.patt[,1], rownames(h1) ), 1]
item.patt.freq <- as.numeric(item.patt[,2])
################################################################################
# generate all attribute patterns #
################################################################################
attr.patt <- matrix( rep( 0, K*L), ncol=K)
h1 <- 2
if ( K >=2 ){
for(ll in 1:(K-1) ){
lk <- utils::combn( 1:K, ll )
for ( jj in 1:( ncol(lk) ) ){
attr.patt[ h1, lk[,jj] ] <- 1
h1 <- h1 + 1
}
}
}
attr.patt[ L, ] <- rep( 1, K )
if ( ! is.null( skillclasses) ){
attr.patt <- skillclasses
L <- nrow(attr.patt)
}
if ( ! is.null(colnames(q.matrix) ) ){
if (ncol(attr.patt)==ncol(q.matrix) ){
colnames(attr.patt) <- colnames(q.matrix)
}
}
# combine all attributes in an attribute pattern as a string
attr.patt.c <- apply( attr.patt, 1, FUN=function(ll){ paste(ll,collapse="" ) } )
################################################################################
# uniform prior distribution of all latent class patterns #
################################################################################
attr.prob <- rep( 1/L, L )
if ( seed > 0 ){
attr.prob <- stats::runif( L, 0, 10/ L )
attr.prob <- attr.prob / sum( attr.prob )
}
################################################################################
# some prelimaries for EM algorithm #
################################################################################
# split item response pattern in a data frame with items as columns
spl <- sapply( as.vector(item.patt[,1]), FUN=function(ii){ strsplit( ii, split=NULL) } )
item.patt.split <- matrix( rep( 0, length(spl) * J ), ncol=J )
for (ll in 1:length(spl) ){
item.patt.split[ ll, ] <- as.numeric( spl[[ll]] )
}
# response pattern matrix: each observed entry corresponds to a 1, each unobserved entry to a 0
resp.patt <- 1* ( item.patt.split !=9 )
# number of item response patterns
IP <- nrow(item.patt.split)
# constraints for guessing and slipping parameters
if ( ! is.null( constraint.slip ) ){ slip[ constraint.slip[,1] ] <- constraint.slip[,2] }
if ( ! is.null( constraint.guess ) ){ guess[ constraint.guess[,1] ] <- constraint.guess[,2] }
iter <- 1 # Iteration number
likediff <- 1 # Difference in likelihood estimates
loglike <- 0 # init for log-Likelihood
# init value for maximum parameter change in likelihood maximization
dev.change <- max.par.change <- 1000
# calculate for each item how many attributes are necessary for solving the items
# according to the specified DINA or DINO rule
comp <- ( rowSums(q.matrix) )*( rule=="DINA") + 1* ( rule=="DINO" )
# need number of components for I.lj ...
compL <- cdm_matrix1( comp, ncol=L)
attrpatt.qmatr <- tcrossprod( q.matrix, attr.patt )
# compute latent response
latresp <- apply( attr.patt, 1, FUN=function(attr.patt.ll){
attr.patt.ll <- cdm_matrix2( attr.patt.ll, nrow=J)
ind <- 1*(rowSums(q.matrix * attr.patt.ll) >=comp )
return(ind)
} )
latresp1 <- latresp==1
# response patterns
cmresp <- colMeans( resp.patt )
some.missings <- if( mean(cmresp) < 1){ TRUE } else { FALSE }
# calculations for expected counts
# this matrix is needed for computing R.lj
ipr <- item.patt.split*item.patt.freq*resp.patt
ipfr <- item.patt.freq*resp.patt
item_patt_split1 <- item.patt.split==1
resp_patt_bool <- resp.patt==1
# response indicator list
resp.ind.list <- list( 1:J )
for (i in 1:J){
resp.ind.list[[i]] <- which( resp.patt[,i]==1)
}
# parameter history
if ( param.history ){
likelihood.history <- rep(NA, maxit )
slip.history <- guess.history <- matrix( NA, nrow=maxit, ncol=ncol(data) )
}
ones_matrix <- matrix( 1, nrow=IP, ncol=L )
# cat(" *** init proc ") ; z1 <- Sys.time(); print(z1-z0) ; z0 <- z1
################################################################################
# BEGIN OF THE ITERATION LOOP #
################################################################################
while ( iter <=maxit &
( ( max.par.change > conv.crit ) | ( dev.change > dev.crit ) )
){
################################################################################
# STEP I: #
# calculate P(X_i | alpha_l): #
# probability of each item response pattern given an attribute pattern #
################################################################################
pjm <- cdm_rcpp_din_calc_prob( latresp1=latresp1, guess=guess, slip=slip, J=J, L=L )
pjM <- array( pjm, dim=c(J,2,L) )
res.hwt <- cdm_calc_posterior( rprobs=pjM, gwt=ones_matrix, resp=item.patt.split, nitems=J,
resp.ind.list=resp.ind.list, normalization=FALSE, thetasamp.density=NULL,
snodes=0 )
p.xi.aj <- res.hwt$hwt
#-- set likelihood for skill classes with zero probability to zero
if ( ! is.null(zeroprob.skillclasses) ){
p.xi.aj[, zeroprob.skillclasses ] <- 0
}
################################################################################
# STEP II: #
# calculate P( \alpha_l | X_i ): #
# posterior probability of each attribute pattern given the item response pattern
################################################################################
#-- posterior probabilities P( \alpha_l | X_i )
p.aj.xi <- cdm_matrix2( attr.prob, nrow=IP ) * p.xi.aj
attr.prob0 <- attr.prob
if ( ! is.null( zeroprob.skillclasses ) ){
p.aj.xi[, zeroprob.skillclasses ] <- 0
}
p.aj.xi <- p.aj.xi / rowSums( p.aj.xi )
#-- calculate marginal probability P(\alpha_l) for attribute alpha_l
attr.prob <- colSums( p.aj.xi * item.patt.freq ) / I
################################################################################
# STEP III: #
# calculate I_{lj} and R_{lj} #
# for a derivation see De La Torre (2008, Journal of Educational and #
# Behavioral Statistics) #
# I_{lj} ... expected frequency of persons in attribute class l for item j #
# (in case of no missing data I_{lj}=I_l for all items j #
# R_{lj} ... expected frequency of persons in attribute class l for item j #
# which correctly solve item j #
################################################################################
if ( some.missings ){
I.lj <- crossprod( ipfr, p.aj.xi )
} else {
I.lj <- cdm_matrix2( crossprod( item.patt.freq, p.aj.xi), nrow=J )
}
R.lj <- cdm_rcpp_din_calc_counts( p_aj_xi=p.aj.xi, item_patt_freq=item.patt.freq,
item_patt_split1=item_patt_split1, resp_patt_bool=resp_patt_bool, J=J, L=L )
colnames(I.lj) <- colnames(R.lj) <- attr.patt.c
rownames(I.lj) <- rownames(R.lj) <- colnames(data)
################################################################################
# STEP IV: #
# calculate R_j0, I_j0, I_j1, R_j1 #
# R_{j1} ... expected frequency of students which correctly solve item j and #
# possess all necessary attributes for this item #
# I_{j1} ... expected frequency of students which correctly solve the item #
# I_{j0}, R_{j0} ... expected frequencies of students which incorrectly #
# solve the item #
################################################################################
ness <- attrpatt.qmatr >=compL
ness0 <- ! ness
I.j0 <- rowSums( ness0 * I.lj )
I.j1 <- rowSums( ness * I.lj )
R.j0 <- rowSums( ness0 * R.lj )
R.j1 <- rowSums( ness * R.lj )
################################################################################
# STEP V: #
# M-Step: update slipping and guessing parameters. #
# The guessing parameter 'guess.new' can be calculated as R.j0 / I.j0 #
# -> correct solution for item j if not all necessary attributes are possessed
################################################################################
pseudo_count <- .05
I.j0[ I.j0==0] <- pseudo_count
I.j1[ I.j1==0] <- pseudo_count
guess.new <- R.j0 / I.j0
slip.new <- ( I.j1 - R.j1 ) / I.j1
# equal guessing and slipping parameter
if (guess.equal){
guess.new <- rep( sum(R.j0) / sum(I.j0), J )
}
if (slip.equal){
slip.new <- rep( sum( I.j1 - R.j1 ) / sum( I.j1), J )
}
#*** overrelaxed convergence
if ( wgt.overrelax > 0 ){
eps1 <- 1e-5
if ( wgtest.overrelax & ( iter > 2) ){
l1 <- c( guess.new, slip.new )
l2 <- c( guess, slip )
l3 <- c( guess.old, slip.old )
lambda <- sum( abs( l1 - l2 ) ) / sum( abs( l3 - l2 ) )
wgt.overrelax <- lambda / ( 2 - lambda )
wgt.overrelax[ wgt.overrelax <=0 ] <- eps1
wgt.overrelax[ wgt.overrelax >=.98 ] <- .98
}
guess.new <- guess.new + wgt.overrelax * ( guess.new - guess )
slip.new <- slip.new + wgt.overrelax * ( slip.new - slip )
guess.new[ guess.new < 0 ] <- 0
slip.new[ slip.new < 0 ] <- 0
if ( wgtest.overrelax ){
slip.old <- slip
guess.old <- guess
}
}
# constrained slipping and guessing parameter
if ( ! is.null( constraint.slip ) ){
slip.new[ constraint.slip[,1] ] <- constraint.slip[,2]
}
if ( ! is.null( constraint.guess ) ){
guess.new[ constraint.guess[,1] ] <- constraint.guess[,2]
}
#*** adjustment parameters
if ( guess.min > 0 ){
guess.new <- ifelse( guess.new < guess.min, guess.min, guess.new )
}
if ( guess.max < 1 ){
guess.new <- ifelse( guess.new > guess.max, guess.max, guess.new )
}
if ( slip.min > 0 ){
slip.new <- ifelse( slip.new < slip.min, slip.min, slip.new )
}
if ( slip.max < 1 ){
slip.new <- ifelse( slip.new > slip.max, slip.max, slip.new )
}
# calculate the updated likelihood
eps0 <- 1e-300
like_individual <- rowSums( p.xi.aj * cdm_matrix2( attr.prob, nrow=IP) )
like.new <- sum( log( like_individual + eps0 ) * item.patt.freq )
likediff <- abs( loglike - like.new )
loglike <- like.new
dev.change <- abs( likediff / loglike )
# maximum parameter change
max.par.change <- max( abs( guess.new - guess ), abs( slip.new - slip ),
abs( attr.prob - attr.prob0 ) )
# define estimates which are updated in this iteration
guess <- guess.new
slip <- slip.new
if (progress) {
cat( "Iter. ",iter, " :",
substring( paste(Sys.time()), first=11 ), ", ", " loglike=",
round( like.new, 7),
" / max. param. ch. : ", round( max.par.change, 6),
" / relative deviance change : ", round( dev.change, 6)
)
if( wgt.overrelax > 0){
cat(" / overrelax. parameter=", round( wgt.overrelax, 4 ))
}
cat("\n", sep="")
utils::flush.console() # Output is flushing on the console
}
if ( param.history ){
likelihood.history[iter] <- like.new
slip.history[iter,] <- slip
guess.history[iter,] <- guess
}
iter <- iter + 1 # new iteration number
}
################################################################################
# END OF THE ITERATION LOOP #
################################################################################
# cat(" *** iterations ") ; z1 <- Sys.time(); print(z1-z0) ; z0 <- z1
# set likelihood for skill classes with zero probability to zero
if ( ! is.null(zeroprob.skillclasses) ){
p.xi.aj[, zeroprob.skillclasses ] <- 0
}
# calculate posterior probability for each attribute pattern
pattern <- data.frame( freq=round(as.numeric(item.patt[,-1]),3),
mle.est=attr.patt.c[ max.col( p.xi.aj ) ],
mle.post=rowMaxs( p.xi.aj ) / rowSums( p.xi.aj ),
map.est=attr.patt.c[ max.col( p.aj.xi ) ],
map.post=rowMaxs( p.aj.xi )
)
# calculate posterior probabilities for all skills separately
attr.postprob <- p.aj.xi %*% attr.patt
colnames( attr.postprob ) <- paste("post.attr",1:K, sep="")
pattern <- cbind( pattern, attr.postprob )
################################################################################
# estimation of the standard errors for slipping and guessing parameters #
# guessing parameters (DINA and DINO) #
# NOTE: In this calculation of standard errors, sample weights were not #
# taken into account. Use for example the bootstrap to do some inference. #
################################################################################
se.guess <- sapply( 1:J, FUN=function(jj){
indA0.jj <- rowSums( q.matrix[jj,] * attr.patt ) < comp[jj]
l1 <- rowSums( p.aj.xi * outer( resp.patt[,jj], rep(1,L) ) *
( outer( item.patt.split[,jj ], rep(1,L) ) - guess[ jj ] ) * outer( rep(1,IP), indA0.jj )
)
( sum( item.patt.freq * l1^2 ) / guess[jj]^2 / (1-guess[jj])^2 )^(-.5)
} )
# equal guessing parameter
if ( guess.equal ){ se.guess <- rep( sqrt( 1 / sum( 1/ se.guess^2 ) ), J ) }
# constrained guessing parameter
if ( ! is.null( constraint.guess ) ){ se.guess[ constraint.guess[,1] ] <- NA }
guess <- data.frame( est=guess, se=se.guess )
# slipping parameter (DINA and DINO)
se.slip <- sapply( 1:J, FUN=function(jj){
indA0.jj <- rowSums( q.matrix[jj,] * attr.patt ) >=comp[jj]
l1 <- rowSums( p.aj.xi * outer( resp.patt[,jj], rep(1,L) ) *
( outer( item.patt.split[,jj ], rep(1,L) ) - 1 + slip[ jj ] ) * outer( rep(1,IP), indA0.jj )
)
( sum( item.patt.freq * l1^2 ) / slip[jj]^2 / (1-slip[jj])^2 )^(-.5)
} )
# equal slipping parameter
if ( slip.equal ){ se.slip <- rep( sqrt( 1 / sum( 1/ se.slip^2 ) ), J ) }
# constrained slipping parameter
if ( ! is.null( constraint.slip ) ){ se.slip[ constraint.slip[,1] ] <- NA }
slip <- data.frame( est=slip, se=se.slip )
# attribute pattern
attr.prob <- matrix( attr.prob, ncol=1)
colnames( attr.prob ) <- "class.prob"
rownames( attr.prob ) <- attr.patt.c
# pattern for seperate skills
skill.patt <- matrix(apply( matrix( rep( attr.prob, K ), ncol=K) * attr.patt, 2, sum ),ncol=1)
# rownames(skill.patt) <- paste("Skill_", colnames(q.matrix),sep="")
rownames(skill.patt) <- colnames(q.matrix)
colnames(skill.patt) <- "skill.prob"
# calculation of the AIC und BIC
bb <- 0
if ( ! is.null( constraint.guess) ){ bb <- bb + nrow(constraint.guess) }
if ( ! is.null( constraint.slip ) ){ bb <- bb + nrow(constraint.slip) }
if( guess.equal){ bb <- bb + J - 1 }
if( slip.equal){ bb <- bb + J - 1 }
# collect number of parameters
pars <- data.frame( "itempars"=2*J - bb )
# number of skill classes
pars$skillpars <- L - 1 - length( zeroprob.skillclasses )
Np <- pars$itempars + pars$skillpars
aic <- -2*loglike + 2*Np
bic <- -2*loglike + log(I)*Np
rownames( p.aj.xi ) <- rownames( pattern ) # output rownames posterior probabilities
pattern <- data.frame(pattern) # convert pattern to numeric format
for (vv in seq(1,ncol(pattern))[ -c(2,4) ] ){
pattern[,vv ] <- as.numeric( paste( pattern[,vv] ) ) }
# subject pattern
# changed item.patt.subj$pattern.index (ARb 2012-06-05)
item.patt.subj <- data.frame( "case"=1:(nrow(data) ),
"pattern"=item.patt.subj,
"pattern.index"=match( item.patt.subj, item.patt[,1] )
)
# attribute pattern (expected frequencies)
attr.prob <- data.frame( attr.prob )
attr.prob$class.expfreq <- attr.prob[,1] * nrow(data)
#*****
# modify output (ARb 2012-06-05)
pattern <- pattern[ item.patt.subj$pattern.index, ]
pattern[,1] <- paste( item.patt.subj$pattern )
colnames(pattern)[1] <- "pattern"
p.aj.xi__ <- p.aj.xi
p.aj.xi <- p.aj.xi[ item.patt.subj$pattern.index, ]
rownames(p.aj.xi) <- pattern$pattern
colnames(p.aj.xi) <- rownames(attr.prob)
p.xi.aj <- p.xi.aj[ item.patt.subj$pattern.index, ]
rownames(p.xi.aj) <- pattern$pattern
colnames(p.xi.aj) <- colnames(p.aj.xi)
#########################################
# item fit [ items, theta, categories ]
# # n.ik [ 1:TP, 1:I, 1:(K+1), 1:G ]
n.ik <- array( 0, dim=c(L, J, 2, 1 ) )
n.ik[,, 2, 1 ] <- t(R.lj)
n.ik[,, 1, 1 ] <- t(I.lj-R.lj)
pi.k <- array( 0, dim=c(L,1) )
pi.k[,1] <- attr.prob$class.prob
probs <- aperm( pjM, c(3,1,2) )
itemfit.rmsea <- itemfit.rmsea( n.ik, pi.k, probs )$rmsea
#*****
datfr <- data.frame( round( cbind( guess, slip ), 3 ) )
colnames(datfr) <- c("guess", "se.guess", "slip", "se.slip" )
rownames(datfr) <- colnames( dat.items )
datfr <- data.frame( "type"=rule, datfr )
datfr$rmsea <- itemfit.rmsea
names(itemfit.rmsea) <- colnames(data)
s2 <- Sys.time()
#******
# parameter table for din object
res.partable <- din.partable( guess, slip, attribute.patt=attr.prob, data=data,
rule=paste0(datfr$type),
guess.equal, slip.equal, constraint.guess, constraint.slip,
zeroprob.skillclasses,
attribute.patt.splitted=attr.patt )
partable <- res.partable$partable
vcov.derived <- res.partable$vcov.derived
if (progress){ cat("---------------------------------------------------------------------------------\n") }
# coefficients
p1 <- partable[ partable$free, ]
p1 <- p1[ ! duplicated(p1$parindex), ]
p11 <- p1$value
names(p11) <- p1$parnames
res <- list( coef=p11,
item=datfr, guess=guess, slip=slip,
"IDI"=round(1 - guess[,1] - slip[,1],4),
"itemfit.rmsea"=itemfit.rmsea,
"mean.rmsea"=mean(itemfit.rmsea),
loglike=loglike, AIC=aic, BIC=bic,
"Npars"=pars,
posterior=p.aj.xi, "like"=p.xi.aj,
"data"=data, "q.matrix"=q.matrix,
pattern=pattern, attribute.patt=attr.prob, skill.patt=skill.patt,
"subj.pattern"=item.patt.subj, "attribute.patt.splitted"=attr.patt,
"display"=disp, "item.patt.split"=item.patt.split,
"item.patt.freq"=item.patt.freq, "model.type"=r1,
"rule"=rule, "zeroprob.skillclasses"=zeroprob.skillclasses,
"weights"=weights, "pjk"=pjM, "I"=I,
"I.lj"=I.lj, "R.lj"=R.lj, "partable"=partable,
"vcov.derived"=vcov.derived,
"seed"=seed,
"start.analysis"=s1, "end.analysis"=s2,
"iter"=iter ,
"converged"=iter < maxit
)
res$timediff <- s2 - s1
if (progress){ print(s2-s1) }
if (param.history){
param.history <- list( "likelihood.history"=likelihood.history,
"slip.history"=slip.history,
"guess.history"=guess.history )
res$param.history <- param.history
}
# control parameters
control <- list( q.matrix=q.matrix, skillclasses=skillclasses, conv.crit=conv.crit,
dev.crit=dev.crit, maxit=maxit,
constraint.guess=constraint.guess, constraint.slip=constraint.slip,
guess.init=guess.init, slip.init=slip.init,
guess.equal=guess.equal, slip.equal=slip.equal,
zeroprob.skillclasses=zeroprob.skillclasses,
weights=weights, rule=rule,
wgt.overrelax=wgt.overrelax, wgtest.overrelax=wgtest.overrelax,
latresp=latresp, resp.ind.list=resp.ind.list
)
res$control <- control
res$call <- cl
class(res) <- "din"
return(res)
}
# cat("calc.like") ; z1 <- Sys.time(); print(z1-z0) ; z0 <- z1
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/din.R
|
## File Name: din.deterministic.R
## File Version: 1.126
#*** Deterministic din estimation
din.deterministic <- function( dat, q.matrix, rule="DINA", method="JML",
conv=.001, maxiter=300, increment.factor=1.05, progress=TRUE)
{
#--- data preparations
dat0 <- dat
I <- ncol(dat)
N <- nrow(dat)
dat[ is.na(dat) ] <- 0
dat.resp <- 1*(1-is.na(dat0))
if ( length(rule)==1 ){ rule <- rep( rule, I ) }
dat <- as.matrix(dat)
dat.resp <- as.matrix(dat.resp)
# define attribute patterns
attr.patt <- define.attribute.space(q.matrix=q.matrix)
AP <- nrow(attr.patt)
rownames(q.matrix) <- colnames(dat)
# compute latent responses
latresp <- compute.latent.response( attr.patt=attr.patt,
q.matrix=q.matrix, rule=rule)
# initial guessing and slipping parameters
guess <- stats::runif( I, .1, .15)
slip <- stats::runif( I, .1, .15)
max.increment <- 1
# initial latent response vector
latresp.est <- latresp[ rep(1,N), ]
parchange <- 1000
if ( method=="weighted.hamming"){
pbar <- colMeans( dat0, na.rm=TRUE )
guess <- slip <- 1 / ( pbar * ( 1 - pbar ) )
maxiter <- 1
}
if ( method=="hamming"){
guess <- slip <- rep(.2,I)
maxiter <- 1
}
iter <- 0
while( ( iter < maxiter ) & (parchange > conv) ){
slip0 <- slip
guess0 <- guess
latresp.est0 <- latresp.est
# compute individual deviations
if (method!="JML"){
res <- cdm_rcpp_din_deterministic_devcrit( DAT=dat, DATRESP=dat.resp,
LATRESP=latresp, GUESS=guess, SLIP=slip )
}
if (method=="JML"){
res <- cdm_rcpp_din_jml_devcrit(DAT=dat, DATRESP=dat.resp,
LATRESP=latresp, GUESS=guess, SLIP=slip )
}
# compute individual classifications
attr.est <- attr.patt[ res$indexcrit, ]
attr.est.index <- res$indexcrit
# extract estimated latent responses
latresp.est <- latresp[ attr.est.index, ]
# changes in estimated skill patterns
latresp.change <- mean( abs( latresp.est - latresp.est0 ) )
# calculate guessing and slipping parameters
# slipping
L1 <- ( latresp.est==1 ) * (dat.resp==1 )
L2 <- L1*(dat==1)
slip <- 1 - colSums(L2) / ( colSums(L1) + .00001 )
# guessing
L1 <- ( latresp.est==0 ) * (dat.resp==1 )
L2 <- L1*(dat==0)
guess <- 1 - colSums(L2) / ( colSums(L1) + .00001 )
# update increment
if (maxiter > 1){
increment <- guess - guess0
max.increment <- max.increment/increment.factor
guess <- guess0 + ifelse( abs( increment) > max.increment,
sign(increment)*max.increment, increment )
increment <- slip - slip0
slip <- slip0 + ifelse( abs( increment) > max.increment,
sign(increment)*max.increment, increment )
}
max.increment <- parchange <- max( abs( c(guess-guess0, slip-slip0) ) )
# extract deviation value
if ( method!="JML"){
devval <- sum(res$mincrit) } else {
devval <- sum(-2*log(res$mincrit)) }
iter <- iter + 1
# print progress
if (progress){
cat("Iteration", iter )
if ( method=="JML"){
cat(" | Deviance=",round(devval,3) )
cat("\n ****")
}
if ( method!="JML"){ cat(" |") }
cat(" Average change in classifications=",round(latresp.change,5) )
if (method %in% c("JML","adaptive") ){
cat(" | Max. param. change=", round( max.increment,6), "\n")
} else {
cat("\n")
}
utils::flush.console()
}
}
#--- compute prediction error
prederror <- sum( dat.resp * abs( dat - latresp.est ) ) / sum( dat.resp )
if (progress){
cat("-------------------\n" )
cat("Average predictor error=",round(prederror,9) )
cat("\n")
}
# collect output values
res <- list( attr.est=latresp.est, criterion=devval,
guess=guess, slip=slip, prederror=prederror,
q.matrix=q.matrix, dat=dat0 )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/din.deterministic.R
|
## File Name: din.deterministic_alg.R
## File Version: 0.182
##############################################################
# link to Rcpp functions
din.deterministic.devcrit <- function( dat, datresp, latresp, guess, slip )
{
res <- cdm_rcpp_din_deterministic_devcrit( dat, datresp, latresp, guess, slip )
return(res)
}
#**********
# JML estimation function
din.jml.devcrit <- function( dat, datresp, latresp, guess, slip )
{
res <- cdm_rcpp_din_jml_devcrit(dat, datresp, latresp, guess, slip )
return(res)
}
#################################################################
# define different attribute pattern for dichotomous attributes
define.attribute.space <- function( q.matrix )
{
nodes <- c(0,1)
K <- ncol(q.matrix)
attr.patt <- as.matrix( expand.grid( as.data.frame( matrix(rep(nodes, K), ncol=K))))
if ( ! is.null( colnames(q.matrix) ) ){
colnames(attr.patt) <- colnames(q.matrix)
}
return(attr.patt)
}
#################################################################
# compute latent responses
compute.latent.response <- function( attr.patt, q.matrix, rule=NULL)
{
AP <- nrow(attr.patt)
I <- nrow(q.matrix)
if ( is.null(rule) ){ rule <- rep("DINA", I ) }
latresp <- matrix( NA, nrow=AP, ncol=I)
colnames(latresp) <- rownames(q.matrix)
for (ii in 1:I){
comp.ii <- 1
if ( rule[ii]=="DINA"){ comp.ii <- sum(q.matrix[ii,] ) }
latresp[,ii] <- 1 * ( attr.patt %*% q.matrix[ii,] >=comp.ii )
}
return( as.matrix(latresp) )
}
#####################################################################
# calculate deviation criterion
# loop over attributes
calc.devcrit <- function( dat, dat.resp, latresp,slip, guess, N, I, AP)
{
dev.crit <- matrix( NA, nrow=N, ncol=AP )
for (aa in 1:AP){
lat.aa <- matrix( latresp[aa,], nrow=N, ncol=I, byrow=TRUE)
dev.crit[,aa] <- rowSums( slip * ( lat.aa - dat ) * ( lat.aa==1 ) * dat.resp +
guess * ( dat - lat.aa ) * ( lat.aa==0 ) * dat.resp )
}
return(dev.crit)
}
#######################################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/din.deterministic_alg.R
|
## File Name: din.equivalent.class.R
## File Version: 0.191
#**** calculation of equivalent skill classes
din.equivalent.class <-function( q.matrix, rule="DINA")
{
Q <- q.matrix
# Matrix with all skill classes
S <- expand.grid( as.data.frame( t( matrix( rep( c(0,1), each=ncol(Q)), ncol=2 ))))
J <- nrow(Q)
if ( length(rule)==1){ rule <- rep( rule, J ) }
rownames(S) <- paste0("Skills_", apply( S, 1,
FUN=function(ll){ paste(ll, collapse="" ) } ) )
# Calculation of latent response of every skill class
A <- din_equivalent_class_latent_response(q.matrix=Q,S=S,rule=rule)
A <- t(A)
I <- nrow(A)
# calculate latent responses
latent.response <- paste0("LatResp_",
sapply( 1:I, FUN=function(ii){ paste( A[ ii, ], collapse="" ) } ) )
skillclasses <- data.frame( "skillclass"=rownames(S) )
skillclasses$latent.response <- latent.response
# define distinguishable skill classes
skillclasses$distinguish.class <- match( latent.response, unique( latent.response ) )
# calculates how many skill classes correspond to the same latent response
latent.response <- table( latent.response )
six <- sort( latent.response, index.return=FALSE, decreasing=TRUE)
gini_mod <- cdm_gini( as.numeric(six) )
res <- list( "latent.responseM"=A, "latent.response"=latent.response,
"S"=S, "gini"=gini_mod, "skillclasses"=skillclasses )
cat( nrow(S), "Skill classes |", max( skillclasses$distinguish.class ),
" distinguishable skill classes |",
"Gini coefficient=", round( gini_mod,3 ), "\n")
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/din.equivalent.class.R
|
## File Name: din.partable.R
## File Version: 0.24
##############################################
# parameter table for the din model
din.partable <- function( guess, slip, attribute.patt, data, rule,
guess.equal, slip.equal, constraint.guess, constraint.slip,
zeroprob.skillclasses, attribute.patt.splitted )
{
# parameters
J <- nrow(guess)
L <- nrow(attribute.patt)
items <- colnames(data)
K <- ncol(attribute.patt.splitted)
#**************
# create parameter table
partable <- data.frame( "partype"=c( rep( c("guess","slip"), J),
rep("probs", L), rep("margprobs", K ) )
)
partable$parindex <- c( 1:J, J + 1:J, 2*J + 1:(L-1), 0, rep( 0, K ))
partable$item <- c( rep(1:J, each=2 ), rep(0,L+K) )
partable$item.name <- c( rep(colnames(data),each=2), rep("",L+K) )
partable$skillclass <- c( rep(0,2*J), 1:(L), rep(0,K))
partable$varyindex <- c( rep(1:J, each=2 ), 1:(L-1), 0, rep(0,K))
m1 <- paste0( rep( items, each=2 ), "_", c( "guess", "slip" ) )
partable$parnames <- c( m1, paste0( "prob_class", 1:L ),
paste0( "prob_skill", 1:K ))
dfr <- cbind( guess$est, slip$est )
dfr <- matrix( t(dfr), nrow=1, byrow=TRUE )
# marginal skill probabilities
margskills <- colSums( attribute.patt.splitted * attribute.patt[,1] )
partable$value <- c( dfr[1,], attribute.patt[,1], margskills )
partable$fixed <- FALSE
partable$free <- partable$parindex > 0
partable$rule <- c( rep(rule,2), rep("",L+K) )
partable$totindex <- 1:(nrow(partable))
#**************************
# include item parameter constraints
if (guess.equal){
p1 <- partable[ partable$partype=="guess", ]
partable[ p1$totindex, "parindex" ] <- p1$parindex[1]
partable[ p1$totindex, "parnames" ] <- "all_guess"
}
if (slip.equal){
p1 <- partable[ partable$partype=="slip", ]
partable[ p1$totindex, "parindex" ] <- p1$parindex[1]
partable[ p1$totindex, "parnames" ] <- "all_slip"
}
if ( ! is.null(constraint.slip) ){
p1 <- partable[ ( partable$partype=="slip" ) &
( partable$item %in% constraint.slip[,1] ), ]
partable[ p1$totindex, "fixed" ] <- TRUE
partable[ p1$totindex, "free" ] <- FALSE
partable[ p1$totindex, "parindex" ] <- 0
}
if ( ! is.null(constraint.guess) ){
p1 <- partable[ ( partable$partype=="guess" ) &
( partable$item %in% constraint.guess[,1] ), ]
partable[ p1$totindex, "fixed" ] <- TRUE
partable[ p1$totindex, "free" ] <- FALSE
partable[ p1$totindex, "parindex" ] <- 0
}
if ( ! is.null(zeroprob.skillclasses) ){
p1 <- partable[ ( partable$partype=="probs" ) &
( partable$skillclass %in% zeroprob.skillclasses ), ]
partable[ p1$totindex, "fixed" ] <- TRUE
partable[ p1$totindex, "free" ] <- FALSE
partable[ p1$totindex, "parindex" ] <- 0
}
#*********************************
# include parameter transformation matrix
estpars <- unique( partable[ partable$parindex > 0, "parnames" ] )
allpars <- unique( partable$parnames )
MP <- length(allpars)
FP <- length(estpars)
A <- matrix( 0, nrow=MP, ncol=FP)
rownames(A) <- allpars
colnames(A) <- estpars
# free parameters
a1 <- match( estpars, allpars )
A[ cbind( a1, 1:FP ) ] <- 1
# probabilities of last class
probs_names <- partable[ partable$partype=="probs", "parnames" ]
v1 <- probs_names[ length(probs_names ) ]
v2 <- intersect( setdiff( probs_names, v1 ), estpars )
A[ v1, v2 ] <- - 1
# marginal skill probabilities
rownames(attribute.patt.splitted) <- probs_names
colnames(attribute.patt.splitted) <-
partable[ partable$partype=="margprobs", "parnames" ]
attribute.patt.splitted <- ( attribute.patt.splitted - 1 )
a1 <- t(attribute.patt.splitted)
a1 <- a1[, intersect( estpars, colnames(a1) ) ]
A[ rownames(a1), colnames(a1) ] <- a1
#*********************************
# introduce new parameter index
partable$parindex <- match( partable$parindex, sort(unique(partable$parindex) ) ) - 1
res <- list( "partable"=partable, "vcov.derived"=list("A"=A) )
return(res)
}
###########################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/din.partable.R
|
## File Name: din.validate.qmatrix.R
## File Version: 1.429
#---- Q-matrix validation based on the DINA model
din.validate.qmatrix <- function( object, IDI_diff=.02, print=TRUE )
{
s1 <- Sys.time()
#--- extract original Q-matrix
q.matrix <- object$q.matrix
rule <- object$rule
if (length(rule)==1){
rule <- rep( rule, nrow(q.matrix) )
}
# extract estimated parameters
guess <- object$guess[,1]
slip <- object$slip[,1]
# calculate originally estimated IDI
IDI <- 1 - slip - guess
#****
# define all possible Q-matrix vectors
nodes <- c(0,1)
K <- ncol(q.matrix)
L <- 2^K
q.matrix.poss <- as.matrix( expand.grid( as.data.frame( matrix( rep(nodes, K),
ncol=K ) ) ) )
colnames(q.matrix.poss) <- colnames(q.matrix)
q.matrix.poss <- q.matrix.poss[ ! ( rowMeans( q.matrix.poss ) %in% c(0) ), ]
QQM <- nrow(q.matrix.poss) # number of possible Q-matrix vectors
#****
# extract data and attributes
data <- object$data
I <- ncol(data) # number of items
I.lj <- object$I.lj
R.lj <- object$R.lj
attr.patt <- object$attribute.patt.splitted
# calculate modification item parameters
coef.modified <- matrix( 0, nrow=QQM*I, ncol=4 )
colnames(coef.modified) <- c("item", "qmatrix.row", "guess", "slip" )
coef.modified <- as.data.frame( coef.modified )
coef.modified$item <- rep( 1:I, QQM )
coef.modified$qmatrix.row <- rep( 1:QQM, each=I )
#-- Q-matrix validation core function
res <- cdm_rcpp_din_validate_update_qmatrix( qmatrix_poss=q.matrix.poss,
attr_patt=attr.patt, Ilj=I.lj, Rlj=R.lj, I=I, L=L, K=K, rule=rule )
coef.modified$guess <- res$guess_M
coef.modified$slip <- res$slip_M
coef.modified <- coef.modified[ order( coef.modified$item ), ]
coef.modified$IDI <- 1 - coef.modified$slip - coef.modified$guess
# look for original rows
coef.modified$qmatrix.orig <- 1*( rowMeans(q.matrix.poss[ coef.modified$qmatrix.row,]
==q.matrix[ coef.modified$item, ] )==1 )
coef.modified$IDI.orig <- IDI[ coef.modified$item ]
coef.modified$delta.IDI <- coef.modified$IDI - coef.modified$IDI.orig
# restructure matrix coef.modified
coef.modified <- data.frame( item=colnames(data)[ coef.modified$item ],
itemindex=coef.modified$item,
q.matrix.poss[ coef.modified$qmatrix.row, ],
coef.modified[, - c(1:2) ] )
#-- calculate maximum delta index per item
# a1 <- stats::aggregate( coef.modified$IDI, list( coef.modified$itemindex ), max )
a1 <- cdm_rcpp_din_validate_aggregate_max( IDI=coef.modified$IDI,
itemindex=coef.modified$itemindex, I=I)
coef.modified$max.IDI <- a1[ coef.modified$itemindex, 2]
coef.modified <- coef.modified[ order(coef.modified$itemindex - coef.modified$IDI ),]
# print output
coef.modified2 <- coef.modified
improve <- coef.modified2$IDI - coef.modified$IDI.orig > IDI_diff
coef.modified2 <- coef.modified2[ improve, ]
nochange <- nrow(coef.modified2)==0
# calculate proposed Q-matrix
q.matrix.prop <- q.matrix
if ( ! nochange ){
items <- unique( coef.modified2$itemindex )
for (ii in items ){
c2 <- ( coef.modified2[ coef.modified2$itemindex==ii, ] )[1,]
q.matrix.prop[ ii, ] <- as.vector( t(c2[ 1, seq(3, 3+K -1) ]) )
}
}
if ( print ){
if ( ! nochange ){
print( coef.modified2 )
cat("\nProposed Q-matrix:\n\n")
print(q.matrix.prop)
}
if ( nochange ){ cat("No Q-matrix entries should be changed.\n") }
}
s2 <- Sys.time()
res <- list( coef.modified=coef.modified, coef.modified.short=coef.modified2,
q.matrix.prop=q.matrix.prop, time_diff=s2 - s1 )
class(res) <- "din.validate.qmatrix"
return(res)
}
# cat("* loop") ; z1 <- Sys.time(); print(z1-z0) ; z0 <- z1
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/din.validate.qmatrix.R
|
## File Name: din_equivalent_class_latent_response.R
## File Version: 0.04
#**********************************************************
# calculates a latent response under the din function
din_equivalent_class_latent_response <- function( q.matrix, S, rule="DINA")
{
Q <- as.matrix(q.matrix)
S <- as.matrix(S)
L <- matrix(nrow=nrow(Q), ncol=nrow(S))
SQ <- S %*% t(Q)
nums <- rowSums(Q)
nums <- ifelse( rule=="DINO", 1, nums )
nums <- matrix( nums, nrow=nrow(SQ), ncol=ncol(SQ), byrow=TRUE )
SQ <- 1 * ( SQ >=nums )
L <- t(SQ)
colnames(L) <- rownames(S)
return(L)
}
din.latent.response <- din_equivalent_class_latent_response
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/din_equivalent_class_latent_response.R
|
## File Name: din_identifiability.R
## File Version: 0.071
din_identifiability <- function(q.matrix)
{
K <- ncol(q.matrix)
I <- nrow(q.matrix)
if (is.null(colnames(q.matrix))){
colnames(q.matrix) <- paste0("Skill", 1:K)
}
skills <- colnames(q.matrix)
#* search for identity matrix (single loadings)
vec0 <- rep(0,K)
index_single <- cdm_create_vector(names=skills, val=NA)
is_single <- cdm_create_vector(names=skills, val=FALSE)
for (kk in 1:K){
vec1 <- vec0
vec1[kk] <- 1
rm1 <- rowMeans( q.matrix==cdm_matrix2(vec1, nrow=I) )
ind1 <- which( rm1==1 )[1]
index_single[kk] <- ind1
if ( ! is.na(ind1) ){
is_single[kk] <- TRUE
}
}
#- each of the attributes measured by at least three items
skills_items <- colSums(q.matrix)
is_three_items <- skills_items >=3
#- distinctness of columns in submatrix
submat_distinct <- TRUE
Q_ast <- q.matrix[-na.omit(index_single),]
for (ii in 1:(K-1)){
for (jj in (ii+1):K){
submat_distinct <- submat_distinct & ( !( mean( Q_ast[,ii]==Q_ast[,jj] )==1 ))
}
}
# Q-matrix information
item_M <- mean( rowSums(q.matrix) )
qmat_stat <- list(item_M=item_M, skills_items=skills_items)
dina_identified <- prod(is_single) & prod(is_three_items) & submat_distinct
#-- output
res <- list( index_single=index_single, is_single=is_single,
is_three_items=is_three_items, submat_distinct=submat_distinct,
q.matrix=q.matrix, I=I, K=K, qmat_stat=qmat_stat,
dina_identified=dina_identified)
class(res) <- "din_identifiability"
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/din_identifiability.R
|
## File Name: discrim.index.R
## File Version: 0.11
discrim.index <- function(object, ...)
{
UseMethod("discrim.index")
}
discrim_index_cdm <- function( object, ...)
{
attr_patt <- object$attribute.patt.splitted
probs <- IRT.irfprob(object)
skill_names <- colnames(object$q.matrix)
res <- discrim_index_computation( attr_patt=attr_patt,
probs=probs, skill_names=skill_names, item_names=dimnames(probs)[[1]] )
return(res)
}
discrim.index.din <- discrim_index_cdm
discrim.index.gdina <- discrim_index_cdm
discrim.index.mcdina <- discrim_index_cdm
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/discrim.index.R
|
## File Name: discrim_index_computation.R
## File Version: 0.222
discrim_index_computation <- function( attr_patt, probs,
skill_names=NULL, item_names=NULL)
{
#-- matrix containing attribute vectors for comparison
comp_matrix <- cdm_rcpp_discrimination_index_attribute_patterns(attr_patt=attr_patt)
#--- compute discrimination indices
probs_ <- as.vector(probs)
dim_probs <- dim(probs)
ncat <- dim_probs[2]
K <- ncol(attr_patt)
discrim_item_attribute <- cdm_rcpp_discrimination_index_calc(
comp_matrix=comp_matrix, probs=probs_,
dim_probs=dim_probs, K=K )
colnames(discrim_item_attribute) <- skill_names
#--- item discrimination index IDI
idi <- cdm_rcpp_discrimination_index_idi( probs=probs_, dim_probs=dim_probs, K=K )
names(idi) <- item_names
#--- discrimination index at test level
discrim_test <- cdm_rcpp_discrimination_index_test_level(
discrim_item_attribute=discrim_item_attribute)
#--- labelling
if ( is.null(skill_names)){
skill_names <- colnames(attr_patt)
}
if ( is.null(item_names) ){
item_names <- dimnames(probs)[[1]]
}
colnames(discrim_item_attribute) <- skill_names
discrim_item_attribute <- data.frame( item=item_names, discrim_item_attribute )
#--- output
res <- list( comp_matrix=comp_matrix, discrim_item_attribute=discrim_item_attribute,
discrim_test=discrim_test, idi=idi)
class(res) <- "discrim.index"
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/discrim_index_computation.R
|
## File Name: dpm_calc_probs.R
## File Version: 0.02
dpm_calc_probs <- function( vh )
{
N_max <- length(vh)
probs <- rep( 1, N_max)
probs[1] <- vh[1]
for (tt in 2:N_max){
probs[tt] <- vh[tt] * prod( 1 - vh[ 1:(tt-1)] )
}
return(probs)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/dpm_calc_probs.R
|
## File Name: entropy.lca.R
## File Version: 0.194
#--- entropy for din, gdina and mcdina objects
entropy.lca <- function( object )
{
posterior <- object$like
data <- object$data
weights <- object$control$weights
pjk <- object$pjk
if ( inherits(object,"mcdina") ){
weights <- object$weights
data <- object$dat
data <- data - 1
pjk <- object$pik[,,,1]
}
skillspace <- object$attribute.patt.splitted
q.matrix <- object$q.matrix
data.resp <- 1-is.na(data)
data[is.na(data) ] <- 0
N <- length(weights)
weights <- N / sum(weights) * weights
L <- nrow(skillspace )
K <- ncol(skillspace)
I <- ncol(data)
eps <- 1E-10
posterior <- posterior / rowSums( posterior )
#*** calculate entropy for whole test
entropy.total <- 1 + sum( weights * posterior * log( posterior + eps) )/N/log(L)
#*** maximum number of skills
maxskill <- apply( skillspace, 2, max )
#*** entropy for each skill
entropy.skill <- rep(0,K)
for (kk in 1:K){
# kk <- 1
Nkk <- maxskill[kk]
posterior.kk <- matrix(NA, nrow=N, ncol=Nkk+1 )
for (vv in 0:Nkk){
posterior.kk[,vv+1] <- rowSums( posterior[, skillspace[,kk]==vv ] )
}
entropy.skill[kk] <- 1 +
sum( weights * posterior.kk * log(posterior.kk+eps))/ N / log(Nkk+1)
}
#******** entropy for each item
entropyM <- matrix( NA, nrow=I+1, ncol=K +1 )
entropyM[1,] <- c( entropy.total, entropy.skill )
for (ii in 1:I){
weights.ii <- weights * data.resp[,ii]
N.ii <- sum(weights.ii)
pjk.ii <- pjk[ii,,]
pjkM <- pjk.ii[ data[,ii] +1, ]
posterior.ii <- pjkM
posterior.ii <- posterior.ii / rowSums( posterior.ii )
entropyM[ii+1,1] <- 1 +
sum( weights.ii * posterior.ii * log(posterior.ii + eps) )/N.ii/log(L)
for (kk in 1:K){
# skill kk and item ii
Nkk <- maxskill[kk]
posterior.kk <- matrix(NA, nrow=N, ncol=Nkk+1 )
for (vv in 0:Nkk){
posterior.kk[,vv+1] <- rowSums( posterior.ii[, skillspace[,kk]==vv ] )
}
entropyM[ii+1,kk+1] <- 1 +
sum( weights * posterior.kk * log(posterior.kk + eps) )/N/log(Nkk+1)
}
}
res <- data.frame( "item"=c("test", colnames(data) ), entropyM )
colnames(res)[-1] <- c("entr_test",paste0("entr_skill", 1:K ) )
res2 <- list( "entropy"=res )
class(res2) <- "entropy.lca"
return(res2)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/entropy.lca.R
|
## File Name: equivalent.dina.R
## File Version: 2.20
equivalent.dina <- function (q.matrix, reparameterization="B")
{
reparametrization <- reparameterization
K <- ncol(q.matrix)
I <- nrow(q.matrix)
if (is.null(colnames(q.matrix))) {
colnames(q.matrix) <- paste("S", 1:K, sep="")
}
if (is.null(rownames(q.matrix))) {
rownames(q.matrix) <- paste("I", 1:I, sep="")
}
L <- 2^K
dich_vec <- c(0,1)
dfr <- as.matrix( dich_vec, ncol=1)
rownames(dfr) <- NULL
for (kk in 2:K){
dfr <- rbind( cbind( dfr, 0), cbind( dfr, 1) )
}
attr.patt <- as.matrix(dfr)
alpha <- attr.patt
l1 <- apply(alpha, 1, FUN=function(hh) {
paste(hh, collapse="")
})
alpha <- matrix(NA, L, K)
for (kk in 1:K) {
alpha[, kk] <- as.numeric(substring(l1, kk, kk))
}
alpha <- data.frame(alpha)
rownames(alpha) <- l1
colnames(alpha) <- colnames(q.matrix)
#*** link to alpha.ast
alpha_ast_index <- alpha[,1]
for ( kk in 2:K){
alpha_ast_index <- alpha_ast_index + 2^(kk-1)*alpha[,kk]
}
#--- reparametrization B
if (reparametrization=="B") {
qclasses <- q.matrix[,1]
for (kk in 2:K){
qclasses <- qclasses + 2^(kk-1) * q.matrix[,kk]
}
uqclasses <- setdiff(unique(qclasses),0)
qclasses <- match( qclasses, uqclasses )
L1 <- length( uqclasses )
q.matrix.ast <- matrix(0, I, L1)
q.matrix.ast[ cbind(1:I, qclasses) ] <- 1
qclasses[ is.na(qclasses) ] <- -9
rownames(q.matrix.ast) <- rownames(q.matrix)
v1 <- rep( "", L1 )
for (cc in 1:L1){
q_cc <- q.matrix[ which(qclasses==cc),, drop=FALSE]
q_cc <- q_cc[1,]
v1[cc] <- paste0("S*", paste0( q_cc, collapse="" ) )
}
colnames(q.matrix.ast) <- v1
alpha.ast <- matrix(0, L, L1)
rownames(alpha.ast) <- rownames(alpha)
colnames(alpha.ast) <- colnames(q.matrix.ast)
for (tt in 1:L){
alpha_tt <- alpha[ tt, ]
for (ll in 1:L1){
q_ll <- q.matrix[ qclasses==ll,, drop=FALSE]
q_ll <- q_ll[1,]
v_tt_ll <- prod( alpha_tt^q_ll )
if (v_tt_ll==1 ){
alpha.ast[tt,ll] <- 1
}
}
}
}
#----------------------------------------------
#--- reparametrization A
if (reparametrization=="A") {
alpha.ast <- matrix(0, L, L)
rownames(alpha.ast) <- rownames(alpha)
colnames(alpha.ast) <- rownames(alpha)
diag(alpha.ast) <- 1
alpha.ast <- alpha.ast[, -1]
q.matrix.ast <- matrix(0, I, L)
rownames(q.matrix.ast) <- rownames(q.matrix)
colnames(q.matrix.ast) <- paste("S*", rownames(alpha), sep="")
for (ii in 1:I) {
q.ii <- q.matrix[ii, ]
a1 <- rep(0,L)
for (hh in 1:L){
v_hh <- prod( alpha[hh, ]^q.ii )
if ( v_hh==1 ){
a1[hh] <- 1
}
}
q.matrix.ast[ii, ] <- a1
}
q.matrix.ast[ rowSums(q.matrix)==0, ] <- 0
q.matrix.ast <- q.matrix.ast[, -1]
}
#--- OUTPUT
res <- list(q.matrix=q.matrix, q.matrix.ast=q.matrix.ast,
alpha=alpha, alpha.ast=alpha.ast )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/equivalent.dina.R
|
## File Name: equivalent.skillclasses.R
## File Version: 0.16
#**********************************************************
# calculates a latent response under the din function
din.latent.response <- function( q.matrix, S, rule="DINA")
{
Q <- as.matrix(q.matrix)
S <- as.matrix(S)
L <- matrix(nrow=nrow(Q), ncol=nrow(S))
SQ <- S %*% t(Q)
nums <- rowSums(Q)
nums <- ifelse( rule=="DINO", 1, nums )
nums <- matrix( nums, nrow=nrow(SQ), ncol=ncol(SQ), byrow=TRUE )
SQ <- 1 * ( SQ >=nums )
L <- t(SQ)
colnames(L) <- rownames(S)
return(L)
}
###################################
# calculation of equivalent skill classes
din.equivalent.class <-function( q.matrix, rule="DINA")
{
Q <- q.matrix
# Matrix with all skill classes
S <- expand.grid( as.data.frame( t( matrix( rep( c(0,1), each=ncol(Q) ), ncol=2 ))))
J <- nrow(Q)
if ( length(rule)==1){ rule <- rep( rule, J ) }
rownames(S) <- paste0("Skills_", apply( S, 1,
FUN=function(ll){ paste(ll, collapse="" ) } ) )
# Calculation of latent response of every skill class
A <- din.latent.response(Q,S,rule=rule)
A <- t(A)
I <- nrow(A)
# calculate latent responses
latent.response <- paste0("LatResp_",
sapply( 1:I, FUN=function(ii){ paste( A[ ii, ], collapse="" ) } ) )
skillclasses <- data.frame( "skillclass"=rownames(S) )
skillclasses$latent.response <- latent.response
# define distinguishable skill classes
skillclasses$distinguish.class <- match( latent.response, unique( latent.response ) )
# calculates how many skill classes correspond to the same latent response
latent.response <- table( latent.response )
six <- sort( latent.response, index.return=FALSE, decreasing=TRUE)
gini_mod <- cdm_gini( as.numeric(six) )
res <- list( "latent.responseM"=A, "latent.response"=latent.response,
"S"=S, "gini"=gini_mod, "skillclasses"=skillclasses )
cat( nrow(S), "Skill classes |", max( skillclasses$distinguish.class ),
" distinguishable skill classes |",
"Gini coefficient=", round( gini_mod,3 ), "\n")
return(res)
}
#--- Gini coefficient, function simply copied from the R ineq package
cdm_gini <- function(x)
{
n <- length(x)
x <- sort(x)
G <- sum(x * 1:n)
G <- 2 * G/(n * sum(x))
G - 1 - (1/n)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/equivalent.skillclasses.R
|
## File Name: eval_likelihood.R
## File Version: 0.08
eval_likelihood <- function( data, irfprob, prior=NULL, normalization=FALSE, N=NULL )
{
long_format <- inherits(x=data, what="data_long_format")
if ( is.null(N) ){
N <- nrow(data)
if (long_format){
N <- data[ N, 1 ] + 1
}
}
TP <- dim(irfprob)[3]
#-- set prior if no prior is provided
if (is.null(prior)){
prior <- matrix(1, nrow=N, ncol=TP)
}
if (is.vector(prior)){
prior <- matrix( prior, nrow=N, ncol=TP, byrow=TRUE)
}
#-- evaluate likelihood in Rcpp
res <- cdm_rcpp_eval_likelihood(data=data, irfprob=as.vector(irfprob),
dim_irfprob=dim(irfprob), prior=prior, normalization=normalization,
long_format=long_format, N=N )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/eval_likelihood.R
|
## File Name: expand_matrix.R
## File Version: 0.03
expand_matrix <- function(x)
{
NR <- nrow(x)
NC <- ncol(x)
NY <- max(NR,NC)
y <- x
if (NR!=NC){
y <- matrix(0,nrow=NY,ncol=NY)
if (NR < NC){
y[ 1:NR, ] <- x
}
if (NR > NC){
y[, 1:NC ] <- x
}
}
return(y)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/expand_matrix.R
|
## File Name: gdd.R
## File Version: 0.19
#################################################################
# generalized distance discriminating method
gdd <- function( data, q.matrix, theta, b, a, skillclasses=NULL)
{
data <- as.matrix(data)
data_isna <- is.na(data)
dataresp <- as.matrix( 1 - data_isna )
data[ data_isna ] <- 0
q.matrix <- as.matrix(q.matrix)
skillspace <- skillclasses
# compute ideal response pattern
res <- ideal.response.pattern( q.matrix, skillspace )
idealresp <- res$idealresp
skillspace <- res$skillspace
# apply generalized distance discriminating method written in Rcpp
res <- cdm_rcpp_generalized_distance_method( data=data,
dataresp=dataresp, idealresp=idealresp, theta=theta, a=a, b=b )
# extract results
distmatrix <- res$dist
skillclass.est <- skillspace[ res$est_skill, ]
res <- list( skillclass.est=skillspace, distmatrix=distmatrix,
skillspace=skillspace, theta=theta )
return(res)
}
###############################################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdd.R
|
## File Name: gdina.R
## File Version: 9.351
################################################################################
# GDINA Model
################################################################################
gdina <- function( data, q.matrix, skillclasses=NULL, conv.crit=0.0001,
dev.crit=.1, maxit=1000, linkfct="identity", Mj=NULL, group=NULL,
invariance=TRUE, method=NULL, delta.init=NULL, delta.fixed=NULL,
delta.designmatrix=NULL, delta.basispar.lower=NULL, delta.basispar.upper=NULL,
delta.basispar.init=NULL, zeroprob.skillclasses=NULL, attr.prob.init=NULL,
attr.prob.fixed=NULL, reduced.skillspace=NULL, reduced.skillspace.method=2, HOGDINA=-1,
Z.skillspace=NULL, weights=rep(1, nrow(data)), rule="GDINA", bugs=NULL,
regular_lam=0, regular_type="none", regular_alpha=NA, regular_tau=NA,
regular_weights=NULL, mono.constr=FALSE, prior_intercepts=NULL, prior_slopes=NULL,
progress=TRUE, progress.item=FALSE, mstep_iter=10, mstep_conv=1E-4,
increment.factor=1.01, fac.oldxsi=0, max.increment=.3, avoid.zeroprobs=FALSE,
seed=0, save.devmin=TRUE, calc.se=TRUE, se_version=1, PEM=TRUE, PEM_itermax=maxit,
cd=FALSE, cd_steps=1, mono_maxiter=10, freq_weights=FALSE,
optimizer="CDM", ... )
{
cl <- CALL <- match.call()
s1 <- Sys.time()
display <- cdm_summary_display()
if (progress){
cat(display)
cdm_print_summary_package(pack="CDM")
}
time1 <- list( "s1"=Sys.time() )
#########################################################
# treat sequential items
#########################################################
res <- gdina_proc_sequential_items( data=data, q.matrix=q.matrix )
data <- res$data
sequential <- res$sequential
q.matrix <- res$q.matrix
#########################################################
# in case of item parameter noninvariance restructure dataset
#########################################################
res <- gdina_proc_noninvariance_multiple_groups( data=data, q.matrix=q.matrix,
invariance=invariance, group=group )
data <- res$data
q.matrix <- res$q.matrix
########################################################
# add item and attribute labels if necessary
########################################################
if ( is.null( colnames( data ) ) ){
colnames(data) <- paste( "Item", seq(1,ncol(data)), sep="")
}
if ( is.null( colnames( q.matrix ) ) ){
colnames(q.matrix) <- paste( "Attr", seq(1,ncol(q.matrix)), sep="")
}
################################################################################
# check consistency of input (data, q.matrix, ...) #
################################################################################
dat.items <- data
#---- check of admissible rules
res <- gdina_proc_check_admissible_rules(rule=rule)
#---- RRUM model specifications
res <- gdina_proc_spec_rrum( rule=rule, method=method, linkfct=linkfct,
optimizer=optimizer)
rrum.params <- res$rrum.params
rrum.model <- res$rrum.model
method <- res$method
linkfct <- res$linkfct
rule <- res$rule
optimizer <- res$optimizer
################################################################################
# model specification: DINA, DINO or itemwise specification of DINA or DINO #
################################################################################
r1 <- "GDINA Model"
################################################################################
# multiple group estimation
################################################################################
res <- gdina_proc_multiple_group_objects(group=group)
G <- res$G
group <- res$group
group0 <- res$group0
groupre <- res$groupre
group.stat <- res$group.stat
group2 <- res$group2
#---- parameters for HOGDINA model
tetrachoric <- NULL
if (HOGDINA >=0){
res <- gdina_proc_hogdina_theta_distribution(G=G)
theta.k <- res$theta.k
reduced.skillspace <- res$reduced.skillspace
wgt.theta <- res$wgt.theta
}
################################################################################
# display on R console #
################################################################################
disp <- r1
#--- display progress
res <- gdina_progress_start_estimation( progress=progress, linkfct=linkfct, disp=disp,
G=G, groupre=groupre, s1=s1, display=display )
################################################################################
# definition of model parameters #
################################################################################
res <- gdina_proc_define_model_parameters( dat.items=dat.items, q.matrix=q.matrix,
rule=rule, HOGDINA=HOGDINA, G=G )
rule <- res$rule
dat.items <- res$dat.items
q.matrix <- res$q.matrix
a.attr <- res$a.attr
b.attr <- res$b.attr
I <- res$I
J <- res$J
K <- res$K
a0 <- Sys.time()
################################################################################
# Initialization and missing data handling #
################################################################################
# recode missing data by 9
resp <- 1 - is.na(dat.items)
dat.items[ resp==0 ] <- 9
#--- standardize weights such that the sum of defined weights is equal to the number of rows in the data frame
weights <- gdina_standardize_weights( weights=weights )
################################################################################
# calculate item response patterns #
################################################################################
res <- gdina_proc_item_response_patterns( dat.items=dat.items, J=J, G=G, weights=weights,
group=group, freq_weights=freq_weights )
item.patt.subj <- res$item.patt.subj
item.patt <- res$item.patt
six <- res$six
item.patt.freq <- res$item.patt.freq
################################################################################
# generate all attribute patterns #
################################################################################
res <- gdina_create_attribute_patterns( q.matrix=q.matrix, skillclasses=skillclasses,
zeroprob.skillclasses=zeroprob.skillclasses, Z.skillspace=Z.skillspace,
G=G, reduced.skillspace=reduced.skillspace )
K <- res$K
maxAttr <- res$maxAttr
attr.patt <- res$attr.patt
L <- res$L
attr.patt.c <- res$attr.patt.c
reduced.skillspace <- res$reduced.skillspace
Z.skillspace <- res$Z.skillspace
Z <- res$Z
beta <- res$beta
covbeta <- res$covbeta
ncolZ <- res$ncolZ
q.entries <- res$q.entries
if ( reduced.skillspace ){
res <- gdina_attribute_patterns_reduced_skillspace( attr.patt=attr.patt, K=K, maxAttr=maxAttr, q.matrix=q.matrix,
Z.skillspace=Z.skillspace, G=G )
Z <- res$Z
ncolZ <- res$ncolZ
beta <- res$beta
}
################################################################################
# assign uniform prior distribution of all latent class patterns
################################################################################
res <- gdina_init_class_probabilities( G=G, L=L, seed=seed, attr.prob.init=attr.prob.init )
attr.prob <- res$attr.prob
################################################################################
# create design matrices
################################################################################
res <- gdina_create_designmatrices( J=J, Mj=Mj, Aj=Aj, q.matrix=q.matrix, rule=rule, L=L, attr.patt=attr.patt,
mono.constr=mono.constr, bugs=bugs)
Mj <- res$Mj
Mj.userdefined <- res$Mj.userdefined
Aj <- res$Aj
Nattr.items <- res$Nattr.items
necc.attr <- res$necc.attr
aggr.attr.patt <- res$aggr.attr.patt
attr.items <- res$attr.items
aggr.patt.designmatrix <- res$aggr.patt.designmatrix
Mj.index <- res$Mj.index
Aj_mono_constraints <- res$Aj_mono_constraints
###############################################################################
# initial item parameters
###############################################################################
delta <- gdina_init_item_parameters( delta.init=delta.init, linkfct=linkfct, J=J, seed=seed, Mj=Mj,
delta.basispar.init=delta.basispar.init, delta.designmatrix=delta.designmatrix, Mj.index=Mj.index,
rule=rule )
#------ some compute inverse matrices for least squares estimation
invM.list <- gdina_proc_uls_inverse_matrices(Mj=Mj, J=J)
if ( fac.oldxsi>=1){
fac.oldxsi <- 0
}
djj_old <- as.list( 1:J )
################################################################################
# some prelimaries for EM algorithm #
################################################################################
res <- gdina_proc_split_item_response_patterns( item.patt=item.patt, J=J,
freq_weights=freq_weights, resp=resp, dat.items=dat.items)
IP <- res$IP
resp.patt <- res$resp.patt
item.patt.split <- res$item.patt.split
iter <- 1 # Iteration number
likediff <- 1 # Difference in likelihood estimates
opt_fct <- loglike <- 0 # init for log-Likelihood
# init value for maximum parameter change in likelihood maximization
max.par.change <- 1000
devchange <- 1000
# analyze response patterns if there are some missings
cmresp <- colMeans( resp.patt )
some.missings <- mean(cmresp) < 1
# calculations for expected counts
# response indicator list
resp.ind.list <- list( 1:J )
for (i in 1:J){
resp.ind.list[[i]] <- which( resp.patt[,i]==1)
}
# this matrix ipr is needed for computing R.lj
if (G==1){
ipr <- item.patt.split * item.patt.freq*resp.patt
}
disp <- "...........................................................\n"
#** for reduced skillspace
if (reduced.skillspace){
if (G==1){
item_patt_freq_matr <- cdm_matrix1( item.patt.freq, ncol=L )
} else {
item_patt_freq_matr <- array( NA, dim=c(nrow(item.patt.freq), L, G ) )
for (gg in 1:G){
item_patt_freq_matr[,,gg] <- cdm_matrix1( item.patt.freq[,gg], ncol=L )
}
}
}
#--- attribute probabilities
if (!is.null(attr.prob.fixed)){
attr.prob <- attr.prob.fixed
}
#--- delta parameter indices
res <- gdina_proc_delta_indices(delta=delta, Mj=Mj)
delta_indices <- res$delta_indices
delta_partable <- res$delta_partable
delta_vec <- unlist(delta)
# reconvert vector into a list
delta <- gdina_delta_convert_into_list( delta_vec=delta_vec, delta_indices=delta_indices, J=J )
#-- preliminaries PEM acceleration
if (PEM){
envir <- environment()
if (! reduced.skillspace){
pem_pars <- c("delta_vec","attr.prob")
}
if (reduced.skillspace){
pem_pars <- c("delta_vec","beta")
}
if (HOGDINA > 0){ PEM <- FALSE }
pem_output_vars <- unique( c( pem_pars, "delta.new","attr.prob") )
parmlist <- cdm_pem_inits_assign_parmlist(pem_pars=pem_pars, envir=envir)
res <- cdm_pem_inits( parmlist=parmlist)
pem_parameter_index <- res$pem_parameter_index
pem_parameter_sequence <- res$pem_parameter_sequence
}
deviance.history <- rep(NA, maxit)
#--- choose regularization, coordinate descent and monotonicity constraints
res <- gdina_proc_regularization( regular_type=regular_type, cd=cd, mono.constr=mono.constr, linkfct=linkfct,
method=method, PEM=PEM, regular_lam=regular_lam,
regular_alpha=regular_alpha, regular_tau=regular_tau,
rule=rule, optimizer=optimizer)
linkfct <- res$linkfct
save.devmin <- res$save.devmin
method <- res$method
regularization <- res$regularization
cd_algorithm <- res$cd_algorithm
PEM <- res$PEM
regular_lam <- res$regular_lam
regular_alpha <- res$regular_alpha
regular_tau <- res$regular_tau
regularization_types <- res$regularization_types
optimizer <- res$optimizer
#--- process prior distributions
res <- gdina_proc_prior_distribution( prior_intercepts=prior_intercepts,
prior_slopes=prior_slopes, method=method, linkfct=linkfct, PEM=PEM )
prior_intercepts <- res$prior_intercepts
prior_slopes <- res$prior_slopes
linkfct <- res$linkfct
method <- res$method
use_prior <- res$use_prior
PEM <- res$PEM
#**** some precalculations
ones_matrix <- matrix( 1, nrow=IP, ncol=L )
#********************************
# extract parameters with minimal deviances
dev.min <- 1E99
R.lj.gg <- I.lj.gg <- NULL
suffstat_probs <- as.list(1:J)
devchange <- 0
################################################################################
# BEGIN OF THE ITERATION LOOP #
################################################################################
while ( ( iter <=maxit ) & ( ( max.par.change > conv.crit ) | ( devchange > dev.crit ) ) )
{
################################################################################
# STEP I: #
# calculate P(X_i | alpha_l): #
# probability of each item response pattern given an attribute pattern #
################################################################################
#--- calculate item response probabilities
pjM <- gdina_calc_prob( progress=progress, iter=iter, disp=disp, J=J, L=L,
aggr.attr.patt=aggr.attr.patt, Mj=Mj, delta=delta, linkfct=linkfct )
#--- calculate individual likelihood
p.xi.aj <- gdina_calc_individual_likelihood( IP=IP, L=L, pjM=pjM, item.patt.split=item.patt.split,
J=J, resp.ind.list=resp.ind.list, zeroprob.skillclasses=zeroprob.skillclasses,
ones_matrix=ones_matrix )
################################################################################
# STEP II: #
# calculate P( \alpha_l | X_i ): #
# posterior probability of each attribute pattern given the item response pattern
################################################################################
res <- gdina_calc_individual_posterior( G=G, IP=IP, attr.prob=attr.prob, p.xi.aj=p.xi.aj,
L=L, I=I, zeroprob.skillclasses=zeroprob.skillclasses,
reduced.skillspace=reduced.skillspace, item.patt.freq=item.patt.freq,
attr.prob.fixed=attr.prob.fixed)
p.aj.xi <- res$p.aj.xi
attr.prob <- res$attr.prob
#######################################################################
# STEP II0: higher order GDINA model
#######################################################################
if (HOGDINA >=0){
res <- gdina_attribute_structure_hogdina( G=G, attr.prob=attr.prob, attr.patt=attr.patt,
wgt.theta=wgt.theta, HOGDINA=HOGDINA, a.attr=a.attr, b.attr=b.attr, theta.k=theta.k,
tetrachoric=tetrachoric )
a.attr <- res$a.attr
b.attr <- res$b.attr
attr.prob <- res$attr.prob
tetrachoric <- res$tetrachoric
}
#######################################################################
# STEP IIa: reduction of skill space
#######################################################################
if (reduced.skillspace){
res <- gdina_reduced_skillspace_multiple_groups( Z=Z, reduced.skillspace.method=reduced.skillspace.method,
item_patt_freq_matr=item_patt_freq_matr, p.aj.xi=p.aj.xi, G=G )
beta <- res$beta
attr.prob <- res$attr.prob
}
################################################################################
# STEP III: #
# calculate I_{lj} and R_{lj} #
# for a derivation see De La Torre (2008, Journal of Educational and #
# Behavioral Statistics) #
# I_{lj} ... expected frequency of persons in attribute class l for item j #
# (in case of no missing data I_{lj}=I_l for all items j #
# R_{lj} ... expected frequency of persons in attribute class l for item j #
# which correctly solve item j #
################################################################################
res <- gdina_calc_expected_counts( G=G, J=J, L=L, item.patt.freq=item.patt.freq, p.aj.xi=p.aj.xi,
some.missings=some.missings, ipr=ipr, attr.patt.c=attr.patt.c, resp.patt=resp.patt,
item.patt.split=item.patt.split, data=data)
I.lj <- res$I.lj
R.lj <- res$R.lj
I.lj.gg <- res$I.lj.gg
R.lj.gg <- res$R.lj.gg
################################################################################
# STEP IV: #
# M Step #
# GDINA Model #
################################################################################
res <- gdina_mstep_item_parameters( R.lj=R.lj, I.lj=I.lj, aggr.patt.designmatrix=aggr.patt.designmatrix,
max.increment=max.increment, increment.factor=increment.factor, J=J, Aj=Aj, Mj=Mj,
delta=delta, method=method, avoid.zeroprobs=avoid.zeroprobs, invM.list=invM.list,
linkfct=linkfct, rule=rule, iter=iter, fac.oldxsi=fac.oldxsi, rrum.model=rrum.model,
delta.fixed=delta.fixed, devchange=devchange, mstep_iter=mstep_iter,
mstep_conv=mstep_conv, Mj.index=Mj.index, suffstat_probs=suffstat_probs,
regular_lam=regular_lam, regular_type=regular_type, cd_steps=cd_steps,
mono.constr=mono.constr, Aj_mono_constraints=Aj_mono_constraints,
mono_maxiter=mono_maxiter, regular_alpha=regular_alpha, regular_tau=regular_tau,
regularization_types=regularization_types, prior_intercepts=prior_intercepts,
prior_slopes=prior_slopes, use_prior=use_prior, optimizer=optimizer,
regularization=regularization, regular_weights=regular_weights )
delta.new <- res$delta.new
suffstat_probs <- res$suffstat_probs
mono_constraints_fitted <- res$mono_constraints_fitted
penalty <- res$penalty
ll_value <- res$ll_value
logprior_value <- res$logprior_value
numb_regular_pars <- res$numb_regular_pars
delta_regularized <- res$delta_regularized
##########################################################################
# estimation with a design matrix for delta parameters
##########################################################################
if ( ! is.null( delta.designmatrix ) ){
delta.new <- gdina_mstep_item_parameters_designmatrix( delta.new=delta.new,
delta.designmatrix=delta.designmatrix,
delta.basispar.lower=delta.basispar.lower,
delta.basispar.upper=delta.basispar.upper, Mj.index=Mj.index, J=J)
}
delta_vec <- unlist(delta.new)
#-- PEM acceleration
if (PEM){
#-- collect all parameters in a list
parmlist <- cdm_pem_inits_assign_parmlist(pem_pars=pem_pars, envir=envir)
#-- define log-likelihood function
ll_fct <- gdina_calc_loglikelihood
#- extract parameters
ll_args <- list( delta_vec=delta_vec, beta=beta, attr.prob=attr.prob, Z=Z, delta_indices=delta_indices, J=J,
iter=iter, disp=disp, L=L, aggr.attr.patt=aggr.attr.patt, Mj=Mj, linkfct=linkfct, IP=IP,
item.patt.split=item.patt.split, resp.ind.list=resp.ind.list,
zeroprob.skillclasses=zeroprob.skillclasses, item.patt.freq=item.patt.freq,
loglike=loglike, G=G, reduced.skillspace=reduced.skillspace )
#-- apply general acceleration function (take care of the correct iteration index:
# it must start at zero)
res <- cdm_pem_acceleration( iter=iter-1, pem_parameter_index=pem_parameter_index,
pem_parameter_sequence=pem_parameter_sequence, pem_pars=pem_pars,
PEM_itermax=PEM_itermax, parmlist=parmlist, ll_fct=ll_fct, ll_args=ll_args,
deviance.history=deviance.history )
#-- collect output
PEM <- res$PEM
pem_parameter_sequence <- res$pem_parameter_sequence
cdm_pem_acceleration_assign_output_parameters( res_ll_fct=res$res_ll_fct,
vars=pem_output_vars, envir=envir, update=res$pem_update )
}
#################################################
#--- calculate deviance
res <- gdina_calc_deviance( p.xi.aj=p.xi.aj, attr.prob=attr.prob, item.patt.freq=item.patt.freq,
loglike=loglike, G=G, IP=IP, regularization=regularization, penalty=penalty,
opt_fct=opt_fct, logprior_value=logprior_value)
like.new <- res$like.new
likediff <- res$likediff
opt_fct <- res$opt_fct
opt_fct_change <- res$opt_fct_change
loglikeold <- loglike
loglike <- like.new
#--- maximum parameter change
max.par.change <- gdina_maximum_parameter_change( delta=delta, delta.new=delta.new, linkfct=linkfct )
delta <- delta.new # reset delta parameter estimates
#--- progress EM algorithm
res <- gdina_progress_em_algorithm( delta=delta, data=data, like.new=like.new, loglikeold=loglikeold,
max.par.change=max.par.change, iter=iter, progress=progress,
progress.item=progress.item, regularization=regularization, penalty=penalty,
opt_fct=opt_fct, opt_fct_change=opt_fct_change, ll_value=ll_value,
regular_type=regular_type, logprior_value=logprior_value, use_prior=use_prior,
numb_regular_pars=numb_regular_pars)
utils::flush.console() # Output is flushing on the console
devchange <- abs( 2*(like.new-loglikeold) )
#**** update parameters at minimal deviance
dev <- -2*like.new
deviance.history[iter] <- dev
if (save.devmin){
if ( dev < dev.min ){
iter.min <- iter
delta.min <- delta
dev.min <- dev
p.aj.xi.min <- p.aj.xi
p.xi.aj.min <- p.xi.aj
R.lj.min <- R.lj
I.lj.min <- I.lj
attr.prob.min <- attr.prob
loglike.min <- loglike
}
}
if ( ! save.devmin ){
iter.min <- iter
}
#********************************
iter <- iter + 1 # new iteration number
}
################################################################################
# END OF THE ITERATION LOOP #
################################################################################
#***************************************
# use parameters with minimal deviance
iterused <- iter - 1
if (save.devmin){
iter.min -> iter
delta.min -> delta
dev.min -> dev
p.aj.xi.min -> p.aj.xi
p.xi.aj.min -> p.xi.aj
R.lj.min -> R.lj
I.lj.min -> I.lj
attr.prob.min -> attr.prob
loglike.min -> loglike
}
#****************************************
#--- pattern output
res <- gdina_post_pattern_output( G=G, p.xi.aj=p.xi.aj, zeroprob.skillclasses=zeroprob.skillclasses,
item.patt=item.patt, attr.patt.c=attr.patt.c, p.aj.xi=p.aj.xi, item.patt.subj=item.patt.subj,
group2=group2, attr.patt=attr.patt, K=K )
pattern <- res$pattern
p.xi.aj <- res$p.xi.aj
#####################################################
# itemwise standard error calculation
res <- gdina_post_calc_se( G=G, p.aj.xi=p.aj.xi, item.patt.freq=item.patt.freq, attr.prob=attr.prob,
p.xi.aj=p.xi.aj, IP=IP, J=J, calc.se=calc.se, aggr.attr.patt=aggr.attr.patt, Aj=Aj, Mj=Mj, R.lj=R.lj,
I.lj=I.lj, item.patt.split=item.patt.split, resp.patt=resp.patt, delta=delta, linkfct=linkfct, rule=rule,
avoid.zeroprobs=avoid.zeroprobs, data=data, se_version=se_version, method=method, delta.fixed=delta.fixed,
q.matrix=q.matrix, delta_regularized=delta_regularized, regularization=regularization )
varmat.delta <- res$varmat.delta
varmat.palj <- res$varmat.palj
se.delta <- res$se.delta
delta.summary <- res$delta.summary
freq.pattern <- res$freq.pattern
item.patt.freq <- res$item.patt.freq
# compute RRUM parametrization if model is specified
if (rrum.model){
rrum.params <- .rrum.param( delta.summary=delta.summary, q.matrix=q.matrix )
}
#--- skill pattern and attribute pattern
res <- gdina_post_skill_pattern( attr.prob=attr.prob, G=G, attr.patt.c=attr.patt.c, K=K, maxAttr=maxAttr,
q.matrix=q.matrix, q.entries=q.entries, attr.patt=attr.patt )
attr.prob <- res$attr.prob
skill.patt <- res$skill.patt
#--- monotonicity boundaries and regularized parameters
res <- gdina_postproc_regularized_constrained_parameters( mono.constr=mono.constr, delta=delta,
Aj_mono_constraints=Aj_mono_constraints, Mj=Mj, linkfct=linkfct, regularization=regularization,
data=data )
numb_bound_mono <- res$numb_bound_mono
numb_regular_pars <- res$numb_regular_pars
item_bound_mono <- res$item_bound_mono
#--- calculation of the AIC und BIC
res <- gdina_calc_ic( delta=delta, delta.designmatrix=delta.designmatrix, delta.fixed=delta.fixed,
G=G, ncolZ=ncolZ, K=K, HOGDINA=HOGDINA, item.patt.freq=item.patt.freq,
zeroprob.skillclasses=zeroprob.skillclasses, loglike=loglike,
numb_regular_pars=numb_regular_pars, attr.prob.fixed=attr.prob.fixed )
Npars <- res$Npars
aic <- res$aic
bic <- res$bic
caic <- res$caic
Nskillpar <- res$Nskillpar
Nipar <- res$Nipar
ic <- res$ic
#--- postprocess posterior distributions
res <- gdina_post_posterior_output( G=G, p.aj.xi=p.aj.xi, p.xi.aj=p.xi.aj, pattern=pattern, data=data,
item.patt.subj=item.patt.subj, item.patt=item.patt, attr.prob=attr.prob, group=group )
item.patt.subj <- res$item.patt.subj
attr.prob <- res$attr.prob
p.xi.aj <- res$p.xi.aj
posterior <- res$posterior
pattern <- res$pattern
attr.prob0 <- res$attr.prob0
attr_prob <- res$attr_prob
#--- item fit [ items, theta, categories ]
res <- gdina_itemfit( L=L, J=J, R.lj=R.lj, I.lj=I.lj, item.patt.freq=item.patt.freq, G=G,
attr.prob=attr.prob, data=data, pjM=pjM )
itemfit.rmsea <- res$itemfit.rmsea
pi.k <- res$pi.k
n.ik <- res$n.ik
pi.k <- res$pi.k
#---- calculate model implied probabilities
probitem <- gdina_probitem( Mj=Mj, Aj=Aj, delta=delta, rule=rule, linkfct=linkfct,
delta.summary=delta.summary, necc.attr=necc.attr )
#***************************** OUTPUT **********************************
if (progress){
cat(display)
}
iter <- iterused
res <- list( coef=delta.summary, item=delta.summary, delta=delta, se.delta=se.delta,
probitem=probitem, itemfit.rmsea=itemfit.rmsea, mean.rmsea=mean(itemfit.rmsea),
loglike=loglike, deviance=-2*loglike, G=G, N=colSums( as.matrix(item.patt.freq) ),
AIC=aic, BIC=bic, CAIC=caic, Npars=Npars, Nipar=Nipar, Nskillpar=Nskillpar,
Nskillclasses=L, varmat.delta=varmat.delta, varmat.palj=varmat.palj,
posterior=posterior, like=p.xi.aj, data=data, q.matrix=q.matrix,
pattern=pattern, attribute.patt=attr.prob, skill.patt=skill.patt,
attr.prob=attr_prob, subj.pattern=item.patt.subj, attribute.patt.splitted=attr.patt,
pjk=pjM, Mj=Mj, Aj=Aj, rule=rule, linkfct=linkfct, delta.designmatrix=delta.designmatrix,
reduced.skillspace=reduced.skillspace, Z.skillspace=if(reduced.skillspace){ Z } else { NULL },
beta=beta, covbeta=covbeta, display=disp, item.patt.split=item.patt.split,
resp.ind.list=resp.ind.list, dat=item.patt.split,
item.patt.freq=item.patt.freq, model.type=r1, iter=iter, iterused=iterused, rrum.model=rrum.model,
rrum.params=rrum.params, group.stat=group.stat, NAttr=maxAttr, invariance=invariance,
HOGDINA=HOGDINA, mono.constr=mono.constr, regularization=regularization, regular_lam=regular_lam,
regular_alpha=regular_alpha, regular_tau=regular_tau,
numb_bound_mono=numb_bound_mono, item_bound_mono=item_bound_mono, numb_regular_pars=numb_regular_pars,
regular_type=regular_type, delta_regularized=delta_regularized,
regular_weights=regular_weights, cd_algorithm=cd_algorithm, cd_steps=cd_steps,
prior_intercepts=prior_intercepts, prior_slopes=prior_slopes, use_prior=use_prior,
logprior_value=logprior_value,
seed=seed, iter=iter, converged=iter < maxit, iter.min=iter.min,
deviance.history=deviance.history, penalty=penalty, opt_fct=opt_fct,
optimizer=optimizer, method=method, ic=ic )
if (HOGDINA>=0) {
colnames(a.attr) <- paste0( "a.Gr", 1:G )
colnames(b.attr) <- paste0( "b.Gr", 1:G )
int.attr <- - b.attr / a.attr
colnames(int.attr) <- paste0( "int.Gr", 1:G )
rownames(int.attr) <- rownames(b.attr) <- rownames(a.attr) <- colnames(q.matrix)
res$a.attr <- a.attr
res$b.attr <- b.attr
res$int.attr <- int.attr
res$attr.rf <- cbind( b.attr, a.attr, int.attr )
}
# computation time
time1$s2 <- Sys.time()
res$time <- time1
# res$time$timediff <- print(res$time$s2 - res$time$s1)
res$time$timediff <- res$time$s2 - res$time$s1
if ( progress ){
print(res$time$s2 - res$time$s1)
}
# control parameter
control <- list( skillclasses=skillclasses, q.matrix=q.matrix, conv.crit=conv.crit,
dev.crit=dev.crit, maxit=maxit, linkfct=linkfct, Mj=Mj, Aj=Aj,
group=group, method=method, delta.designmatrix=delta.designmatrix,
delta.basispar.lower=delta.basispar.lower, delta.basispar.upper=delta.basispar.upper,
delta.basispar.init=delta.basispar.init, zeroprob.skillclasses=zeroprob.skillclasses,
reduced.skillspace=reduced.skillspace, HOGDINA=HOGDINA, Z.skillspace=Z.skillspace,
weights=weights, rule=rule, I.lj=I.lj, R.lj=R.lj, I.lj.gg=I.lj.gg,
R.lj.gg=R.lj.gg, aggr.patt.designmatrix=aggr.patt.designmatrix, Mj.index=Mj.index, method=method,
aggr.attr.patt=aggr.attr.patt, IP=IP, p.aj.xi=p.aj.xi,item.patt.split=item.patt.split,
resp.patt=resp.patt, freq.pattern=freq.pattern, item.patt.freq=item.patt.freq,invM.list=invM.list,
item.patt.subj=item.patt.subj, item.patt=item.patt, suffstat_probs=suffstat_probs,
increment.factor=increment.factor, fac.oldxsi=fac.oldxsi, avoid.zeroprobs=avoid.zeroprobs,
attr.prob=attr.prob0, delta.fixed=delta.fixed, sequential=sequential,
invariance=invariance, se_version=se_version )
res$control <- control
#--- create parameter table
res$partable <- gdina_partable(res)
#--- polychoric correlations
res$polychor <- CDM.calc.polychor(res)
res$call <- cl
class(res) <- "gdina"
return(res)
}
##################################################################
# cat(" *** time alg") ; z1 <- Sys.time(); print(z1-z0) ; z0 <- z1
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina.R
|
## File Name: gdina.dif.R
## File Version: 1.223
#** differential item functioning in the GDINA model
#** Wald test is used for testing item-wise DIF
gdina.dif <- function( object )
{
ocontrol <- object$control
G <- object$G
J <- ncol(object$dat)
delta.group <- as.list(1:G)
varmat.group <- as.list(1:G)
prob.exp.group <- varmat.group <- as.list(1:G)
names(varmat.group) <- names(prob.exp.group) <- paste0("Group", 1:G )
ocoef <- object$coef
for (gg in 1:G){ # gg <- 1
res.gg <- gdina_dif_compute( ocontrol=ocontrol, gg=gg, data=object$data)
prob.exp.group[[gg]] <- res.gg$prob_exp
names(prob.exp.group[[gg]]) <- colnames(object$data)
delta.group[[gg]] <- res.gg$delta
varmat.group[[gg]] <- res.gg$varmat.delta
}
ndj <- res.gg$ndj
# expanded delta vectors and design matrix
Rdesign <- varmat_all <- delta_all <- as.list(1:J)
difstats <- data.frame( "item"=colnames(object$data), "X2"=NA, "df"=NA)
dif_es <- rep(NA,J)
for (jj in 1:J){
nj <- ndj[[jj]]
delta.jj <- rep(NA, nj*G )
varmat.jj <- matrix(0, nj*G, nj*G )
Rdesign.jj <- matrix(0,nj*(G-1), nj*G )
for (gg in 1:G){
delta.jj[ 1:nj + nj*(gg-1) ] <- delta.group[[gg]][[jj]]
varmat.jj[ 1:nj + nj*(gg-1), 1:nj + nj*(gg-1) ] <- varmat.group[[gg]][[jj]]
if (gg <G){
for (vv in 1:nj){
Rdesign.jj[ vv + nj*(gg-1), vv + nj*(gg-1) ] <- 1
Rdesign.jj[ vv + nj*(gg-1), vv + nj*(gg) ] <- -1
}
}
ocoef[ ocoef$itemno== jj, paste0("est_Group",gg ) ] <- delta.group[[gg]][[jj]]
ocoef[ ocoef$itemno== jj, paste0("se_Group",gg ) ] <- sqrt( diag(varmat.group[[gg]][[jj]] ))
}
varmat_all[[jj]] <- varmat.jj
delta_all[[jj]] <- delta.jj
Rdesign[[jj]] <- Rdesign.jj
# calculate test value
d0 <- Rdesign.jj %*% delta.jj
# calculate variance matrix
ivm <- solve( Rdesign.jj %*% varmat.jj %*% t(Rdesign.jj ) )
difstats[jj,"X2"] <- ( t(d0) %*% ivm %*% d0 )[1,1]
difstats[jj,"df"] <- nrow(Rdesign.jj)
# effect size in case of two groups
if ( G==2 ){
tab1 <- prob.exp.group[[1]][[jj]]
tab2 <- prob.exp.group[[2]][[jj]]
g1 <- (tab1[,1]+tab2[,2])/2
g1 <- sum( g1 * abs( tab1[,2] - tab2[,2] ) )
dif_es[jj] <- g1
}
}
rownames(ocoef) <- paste0(ocoef$item,"_", ocoef$partype)
difstats$p <- 1 - stats::pchisq( difstats$X2, df=difstats$df )
difstats$p.holm <- stats::p.adjust( difstats$p )
if (G==2){ difstats$UA <- dif_es }
res <- list(difstats=difstats, coef=ocoef, delta_all=delta_all,
varmat_all=varmat_all, prob.exp.group=prob.exp.group)
class(res) <- "gdina.dif"
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina.dif.R
|
## File Name: gdina.wald.R
## File Version: 0.30
######################################################
# Wald tests at item level
gdina.wald <- function( object )
{
varmat.delta <- object$varmat.delta
delta <- object$delta
rule <- object$control$rule
#*****
# checks whether gdina.wald can be applied
if ( mean(rule=="GDINA") < 1 ){
stop("Specify a full GDINA model for performing a Wald test.\n")
}
Mj <- object$control$Mj
q.matrix <- object$q.matrix
I <- nrow(q.matrix)
dat <- object$dat
stats_vars <- c("_X2", "_df", "_p", "_sig", "_RMSEA",
"_wgtdist", "_uwgtdist")
SV <- length(stats_vars)
# number of rules
cdm_rules <- c("DINA", "DINO", "ACDM")
SR <- length(cdm_rules)
stats <- matrix( NA, nrow=I, ncol=SV*SR)
v1 <- NULL
for (ss in 1:SR){
v1 <- c( v1, paste0( cdm_rules[ss], stats_vars ) )
}
colnames(stats) <- v1
#-----------------
# extract relevant output
suffstat_probs <- object$control$suffstat_probs
Mj <- object$control$Mj
Aj <- object$control$Aj
attr.prob <- object$control$attr.prob
aggr.attr.patt <- object$control$aggr.attr.patt
link <- object$link
#******************************************
# loop over items
for (ii in 1:I){
delta.ii <- delta[[ii]]
var.delta.ii <- varmat.delta[[ii]]
# number of attributes
Kii <- sum( q.matrix[ii,] )
Mj.ii <- Mj[[ii]][[1]]
suffstat_probs.ii <- suffstat_probs[[ii]]
pjj <- suffstat_probs.ii
if ( link=="logit"){ pjj <- stats::qlogis(pjj) }
if ( link=="log"){ pjj <- log(pjj) }
aggr.attr.patt.ii <- aggr.attr.patt[[ii]]
attr.prob.ii <- rowsum( attr.prob, aggr.attr.patt.ii )
Aj.ii <- Aj[[ii]]
if (Kii>1){
nobs <- sum( 1 - is.na(dat[,ii] ) )
#--------------------------------
# Tests for different rules
for (rule in cdm_rules){
R <- contraint_matrix( delta.ii, rule=rule, Kii, Mj.ii )
res <- WaldTest( delta.ii, var.delta.ii, R, nobs )
stats[ii,paste0(rule,"_X2")] <- res$X2
stats[ii,paste0(rule,"_df")] <- res$df
stats[ii,paste0(rule,"_p")] <- res$p
stats[ii,paste0(rule,"_RMSEA")] <- res$RMSEA
Mj.ii0 <- .create.Mj( Aj.ii, rule)[[1]]
res.ii <- calc_dist_restricted_model(pjj, Mj.ii0, attr.prob.ii, link,
suffstat_probs.ii, aggr.attr.patt.ii)
stats[ii,paste0(rule,"_wgtdist")] <- res.ii$wgtdist
stats[ii,paste0(rule,"_uwgtdist")] <- res.ii$uwgtdist
}
} # end if Kii > 1
} # end item
stats <- data.frame( "item"=colnames(dat), "NAttr"=rowSums(q.matrix), stats )
levels <- c(.01, .05 )
labels <- c("**", "*")
for (rule in cdm_rules){
stats[,paste0(rule,"_sig")] <-
label_significance_level( stats[,paste0(rule,"_p")], levels, labels )
}
res <- list("stats"=stats, "cdm_rules"=cdm_rules)
class(res) <- "gdina.wald"
return(res)
}
####################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina.wald.R
|
## File Name: gdina.wald_aux.R
## File Version: 0.18
##############################################
##############################################
# calculate restricted model and output
# distance to estimated GDINA model
calc_dist_restricted_model <- function(pjj, Mj.ii0, attr.prob.ii, link,
suffstat_probs.ii, aggr.attr.patt.ii )
{
mod0.ii <- stats::lm( pjj ~ 0 + Mj.ii0, weights=attr.prob.ii )
fitted.ii <- stats::fitted(mod0.ii)
if ( link=="logit"){ fitted.ii <- stats::plogis(fitted.ii) }
if ( link=="log"){ fitted.ii <- exp(fitted.ii) }
# weighted distance
dist.ii <- sum( attr.prob.ii * ( suffstat_probs.ii - fitted.ii)^2 )
# unweighted distance
d1 <- ( suffstat_probs.ii - fitted.ii)^2
d1 <- as.vector(d1[ aggr.attr.patt.ii ])
d1 <- mean( d1 )
res <- list( "wgtdist"=dist.ii, "uwgtdist"=d1)
return(res)
}
###################################################
###################################################
# creation of constraint matrix
contraint_matrix <- function( delta.ii, rule, Kii, Mj.ii )
{
Dii <- length(delta.ii)
#***************************
# DINA
if ( rule=="DINA"){
R <- matrix( 0, nrow=Dii-2, ncol=Dii)
for (vv in 2:(Dii-1) ){
R[vv-1,vv] <- 1
}
}
#***************************
# ACDM
if (rule=="ACDM"){
R <- matrix( 0, nrow=Dii-(Kii+1), ncol=Dii)
for (vv in 1:(nrow(R)) ){
vv1 <- vv + ( Kii +1 )
R[vv,vv1] <- 1
}
}
#***************************
# DINO
if (rule=="DINO"){
Dii <- ncol(Mj.ii)
R <- matrix( 0, nrow=Dii-2, ncol=Dii)
for (vv in 1:(Dii-2)){
R[vv,] <- Mj.ii[vv+2,] - Mj.ii[vv+1, ]
}
}
#**********************************
return(R)
}
####################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina.wald_aux.R
|
## File Name: gdina_attr_rpf_hogdina.R
## File Version: 0.19
####################################
# function for calculating attribute response function
gdina_attr_rpf_hogdina <- function( attr.patt, attr.prob, theta.k, wgt.theta, HOGDINA,
tetrachoric=NULL )
{
#- use weights for calculation of tetrachoric correlation
wc <- cdm_tetrachoric( dat=attr.patt, weights=attr.prob, rho_init=tetrachoric$rho,
maxit=200 )
b <- wc$tau
NB <- length(b)
TP <- length(theta.k)
NAP <- nrow(attr.patt)
if (HOGDINA>0){
upper_bound <- .99
L <- cdm_fa1( Sigma=wc$rho, method=1 )$L
L <- as.vector( L )
L <- ifelse( L > upper_bound, upper_bound, L )
L <- L / ( max(1,max(L)) + .0025 )
L1 <- L / sqrt( 1 - L^2 )
} else {
L1 <- L <- rep(0,NB)
}
b1 <- b / sqrt( 1-L^2 )
# calculate probabilities using the factor model
probs <- stats::pnorm( L1 * matrix( theta.k, nrow=NB, ncol=TP, byrow=TRUE) - b1 )
probsL <- array( 0, dim=c( NB, 2, TP ) )
probsL[,2,] <- probs
probsL[,1,] <- 1 - probs
# probsL
probsAP <- array( 1, dim=c( NAP, TP) )
for (kk in 1:NB){
probsAP <- probsAP * probsL[ kk, attr.patt[,kk] + 1, ]
}
# expected attribute probabilities
attr.prob.exp <- rowSums( probsAP * matrix( wgt.theta, nrow=NAP, ncol=TP, byrow=TRUE ) )
res <- list( a.attr=L1, b.attr=b1, attr.prob.exp=attr.prob.exp,
tetrachoric=wc)
return(res)
}
#####################################################################
.attr.rpf <- gdina_attr_rpf_hogdina
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_attr_rpf_hogdina.R
|
## File Name: gdina_attribute_patterns_reduced_skillspace.R
## File Version: 0.10
gdina_attribute_patterns_reduced_skillspace <- function( attr.patt, K, maxAttr, q.matrix,
Z.skillspace, G )
{
A <- attr.patt
# combinations
kombis <- utils::combn( K, 2 )
KK <- ncol(kombis)
B <- NULL
for (kk in 1:KK){
B <- cbind( B, attr.patt[, kombis[1,kk] ] * attr.patt[, kombis[2,kk] ] )
}
Z <- cbind( 1, A, B )
ncolZ <- ncol(Z)
v1 <- c("Int", paste("A",1:K, sep="") )
v1 <- c(v1,apply( kombis, 2, FUN=function(ll){
paste( paste( "A", ll, sep=""), collapse="_" ) } ))
colnames(Z) <- v1
m1 <- which( maxAttr > 1 )
if ( max(maxAttr) > 1 ){
Z1 <- Z[, m1, drop=FALSE ]^2
colnames(Z1) <- paste0( colnames(q.matrix)[m1], "*2")
Z <- cbind( Z, Z1 )
}
if ( ! is.null(Z.skillspace) ){
Z <- Z.skillspace
}
ncolZ <- ncol(Z)
beta <- rep(0, ncolZ )
if (G > 1){
beta <- matrix( beta, nrow=ncolZ, ncol=G)
}
#----- OUTPUT
res <- list(Z=Z, ncolZ=ncolZ, beta=beta )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_attribute_patterns_reduced_skillspace.R
|
## File Name: gdina_attribute_structure_hogdina.R
## File Version: 0.13
gdina_attribute_structure_hogdina <- function(G, attr.prob, attr.patt, wgt.theta,
HOGDINA, a.attr, b.attr, theta.k, tetrachoric )
{
tetrachoric0 <- list()
for (gg in 1:G){
if (G==1){ ap.gg <- attr.prob
} else {
ap.gg <- attr.prob[,gg]
}
tetrachoric_init <- NULL
if ( ! is.null(tetrachoric ) ){
tetrachoric_init <- tetrachoric[[gg]]
}
res <- gdina_attr_rpf_hogdina( attr.patt=attr.patt, attr.prob=ap.gg, theta.k=theta.k,
wgt.theta=wgt.theta[,gg], HOGDINA=HOGDINA, tetrachoric=tetrachoric_init )
tetrachoric0[[gg]] <- res$tetrachoric
if (G==1){
attr.prob <- res$attr.prob
} else {
attr.prob[,gg] <- res$attr.prob
}
a.attr[,gg] <- res$a.attr
b.attr[,gg] <- res$b.attr
}
#--- OUTPUT
res <- list( a.attr=a.attr, b.attr=b.attr, attr.prob=attr.prob,
tetrachoric=tetrachoric0 )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_attribute_structure_hogdina.R
|
## File Name: gdina_calc_deviance.R
## File Version: 0.20
gdina_calc_deviance <- function( p.xi.aj, attr.prob, item.patt.freq, loglike, G, IP,
regularization, penalty=0, opt_fct=0, logprior_value=0 )
{
eps <- 1E-30
# calculate the updated likelihood
p.xi.aj[ p.xi.aj > 1 ] <- 1 - eps
p.xi.aj[ p.xi.aj < 0 ] <- eps
if (G==1){
l1 <- rowSums( p.xi.aj * cdm_matrix2( attr.prob, nrow=IP ) ) + eps
l1[ l1 < 0 ] <- eps
}
if (G>1){
l1 <- matrix( 0, IP, G )
for (gg in 1:G){
l1[,gg] <- rowSums( p.xi.aj * cdm_matrix2( attr.prob[,gg], nrow=IP ) ) + eps
l1[ l1[,gg] < 0,gg] <- eps
}
}
like.new <- sum( log( l1 ) * item.patt.freq )
likediff <- abs( loglike - like.new )
#--- regularization
opt_fct_old <- opt_fct
opt_fct <- -2*like.new + 2* penalty - 2*logprior_value
opt_fct_change <- - opt_fct + opt_fct_old
#--- OUTPUT
res <- list( like.new=like.new, likediff=likediff, opt_fct=opt_fct,
opt_fct_change=opt_fct_change)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_calc_deviance.R
|
## File Name: gdina_calc_expected_counts.R
## File Version: 0.14
gdina_calc_expected_counts <- function( G, J, L, item.patt.freq, p.aj.xi, some.missings,
ipr, attr.patt.c, resp.patt, item.patt.split, data )
{
R.lj.gg <- I.lj.gg <- NULL
#---------------------- single groups ------------------------------------------
if (G==1){
if ( some.missings ){
I.lj <- crossprod( item.patt.freq*resp.patt , p.aj.xi )
} else {
I.lj <- matrix( crossprod( item.patt.freq, p.aj.xi ), nrow=J, ncol=L, byrow=TRUE )
}
R.lj <- crossprod(ipr, p.aj.xi )
colnames(I.lj) <- colnames(R.lj) <- attr.patt.c
rownames(I.lj) <- rownames(R.lj) <- colnames(data)
} # end one group
#---------------------- multiple groups ------------------------------------------
if (G > 1){
R.lj.gg <- I.lj.gg <- array( 0, c( J, L, G ) )
for (gg in 1:G){
I.lj.gg[,,gg] <- crossprod( item.patt.freq[,gg]*resp.patt, p.aj.xi[,,gg] )
R.lj.gg[,,gg] <- crossprod( item.patt.split * item.patt.freq[,gg] * resp.patt, p.aj.xi[,,gg] )
colnames(I.lj.gg) <- colnames(R.lj.gg) <- attr.patt.c
rownames(I.lj.gg) <- rownames(R.lj.gg) <- colnames(data)
}
# calculate I.lj and R.lj
I.lj <- I.lj.gg[,,1]
R.lj <- R.lj.gg[,,1]
for (gg in 2:G){
I.lj <- I.lj + I.lj.gg[,,gg]
R.lj <- R.lj + R.lj.gg[,,gg]
}
}
#--- OUTPUT
res <- list( I.lj=I.lj, R.lj=R.lj, I.lj.gg=I.lj.gg, R.lj.gg=R.lj.gg)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_calc_expected_counts.R
|
## File Name: gdina_calc_ic.R
## File Version: 0.08
gdina_calc_ic <- function( delta, delta.designmatrix, delta.fixed, G, ncolZ, K, HOGDINA,
item.patt.freq, zeroprob.skillclasses, loglike, numb_regular_pars,
attr.prob.fixed=NULL)
{
bb <- 0
Nipar <- length( unlist(delta) )
if ( ! is.null( delta.designmatrix ) ){
Nipar <- ncol(delta.designmatrix )
}
if ( ! is.null( delta.fixed) ){
Nipar <- Nipar - sum(1 - is.na( unlist( delta.fixed )) )
}
if ( ! is.na(numb_regular_pars) ){
Nipar <- Nipar - numb_regular_pars
}
Nskillpar <- G*ncolZ - length( zeroprob.skillclasses )
if (!is.null(attr.prob.fixed)){
Nskillpar <- 0
}
if (HOGDINA==1){ Nskillpar <- 2*K*G }
if (HOGDINA==0){ Nskillpar <- K*G }
Npars <- Nipar - bb + Nskillpar
II <- sum( item.patt.freq )
aic <- -2*loglike + 2 * Npars
bic <- -2*loglike + Npars*log(II)
caic <- -2*loglike + ( log(II) + 1 ) * Npars
#*** create object ic
ic <- list(deviance=-2*loglike, AIC=aic, BIC=bic, CAIC=caic)
#---- OUTPUT
res <- list(Npars=Npars, aic=aic, bic=bic, caic=caic, Nskillpar=Nskillpar, Nipar=Nipar,
ic=ic)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_calc_ic.R
|
## File Name: gdina_calc_individual_likelihood.R
## File Version: 0.06
gdina_calc_individual_likelihood <- function(IP, L, pjM, item.patt.split, J,
resp.ind.list, zeroprob.skillclasses, ones_matrix=NULL)
{
if ( is.null(ones_matrix) ){
ones_matrix <- matrix( 1, nrow=IP, ncol=L )
}
p.xi.aj <- cdm_calc_posterior( rprobs=pjM, gwt=ones_matrix, resp=item.patt.split, nitems=J,
resp.ind.list=resp.ind.list, normalization=FALSE, thetasamp.density=NULL,
snodes=0 )$hwt
if ( ! is.null(zeroprob.skillclasses) ){
p.xi.aj[, zeroprob.skillclasses ] <- 0
}
#--- OUTPUT
return(p.xi.aj)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_calc_individual_likelihood.R
|
## File Name: gdina_calc_individual_posterior.R
## File Version: 0.192
gdina_calc_individual_posterior <- function(G, IP, attr.prob, p.xi.aj, L, I,
zeroprob.skillclasses, reduced.skillspace, item.patt.freq,
attr.prob.fixed=NULL)
{
# posterior probabilities P( \alpha_l | X_i )
if (G==1){
p.aj.xi <- cdm_matrix2( x=attr.prob, nrow=IP) * p.xi.aj
} else {
p.aj.xi <- array( 0, c( IP, L, G ) )
for (gg in 1:G){
p.aj.xi[,,gg] <- cdm_matrix2( x=as.vector(attr.prob[,gg]), nrow=IP) * p.xi.aj
}
}
if (G==1){
if ( ! is.null( zeroprob.skillclasses ) ){
p.aj.xi[, zeroprob.skillclasses ] <- 0
}
p.aj.xi <- p.aj.xi / rowSums( p.aj.xi )
# calculate marginal probability P(\alpha_l) for attribute alpha_l
if ( ! reduced.skillspace ){
attr.prob <- colSums( p.aj.xi * item.patt.freq ) / I
}
}
if ( G > 1 ){
if ( ! is.null( zeroprob.skillclasses ) ){
for (gg in 1:G){
p.aj.xi[, zeroprob.skillclasses, gg ] <- 0
}
}
for( gg in 1:G){
p.aj.xi[,,gg] <- p.aj.xi[,,gg] / rowSums( p.aj.xi[,,gg] )
Igg <- sum( item.patt.freq[,gg] )
attr.prob[,gg] <- colSums( p.aj.xi[,,gg] * item.patt.freq[,gg] ) / Igg
}
}
if (! is.null(attr.prob.fixed)){
attr.prob <- attr.prob.fixed
}
#---- OUTPUT
res <- list( p.aj.xi=p.aj.xi, attr.prob=attr.prob)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_calc_individual_posterior.R
|
## File Name: gdina_calc_loglikelihood.R
## File Version: 0.05
gdina_calc_loglikelihood <- function(delta_vec, beta, attr.prob, Z, delta_indices, J,
iter, disp, L, aggr.attr.patt, Mj, linkfct, IP, item.patt.split,
resp.ind.list, zeroprob.skillclasses, item.patt.freq, loglike, G, reduced.skillspace )
{
# input: delta, attr.prob, beta
# reconvert delta
delta <- delta.new <- gdina_delta_convert_into_list( delta_vec=delta_vec, delta_indices=delta_indices, J=J)
# beta parameter
if ( ! is.null(beta) ){
if (G==1){
attr.prob <- reduced_skillspace_beta_2_probs( Z=Z, beta=beta )
} else {
attr.prob <- matrix(NA, nrow=nrow(Z), ncol=G)
for (gg in 1:G){
attr.prob[,gg] <- reduced_skillspace_beta_2_probs( Z=Z, beta=beta[,gg] )
}
}
} else {
if (G==1){
attr.prob <- cdm_shrink_positive(x=attr.prob)
} else {
for (gg in 1:G){
attr.prob[,gg] <- cdm_shrink_positive(x=attr.prob[,gg])
}
}
}
#-- calculate total log-likelihood
pjM <- gdina_calc_prob( progress=FALSE, iter=iter, disp=disp, J=J, L=L,
aggr.attr.patt=aggr.attr.patt, Mj=Mj, delta=delta, linkfct=linkfct )
p.xi.aj <- gdina_calc_individual_likelihood( IP=IP, L=L, pjM=pjM, item.patt.split=item.patt.split,
J=J, resp.ind.list=resp.ind.list, zeroprob.skillclasses=zeroprob.skillclasses )
ll <- gdina_calc_deviance( p.xi.aj=p.xi.aj, attr.prob=attr.prob, item.patt.freq=item.patt.freq,
loglike=loglike, G=G, IP=IP )$like.new
res <- list( ll=ll, attr.prob=attr.prob, delta.new=delta.new, beta=beta, delta_vec=delta_vec )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_calc_loglikelihood.R
|
## File Name: gdina_calc_prob.R
## File Version: 0.19
gdina_calc_prob <- function( progress, iter, disp, J, L, aggr.attr.patt, Mj,
delta, linkfct)
{
if ( progress ){
cat(disp)
cat("Iteration", iter, " ", paste( Sys.time() ), "\n" )
}
pj1 <- matrix( 0, nrow=J, ncol=L )
#---- calculate P(X_j | alpha_l )
for (jj in 1:J){
ajj <- aggr.attr.patt[[jj]]
mjjj <- Mj[[jj]][[1]]
djj <- cdm_matrix2( delta[[jj]], nrow=nrow(mjjj) )
pj11 <- rowSums( mjjj * djj )
if (linkfct=="logit"){
pj11 <- stats::plogis( pj11 )
}
if (linkfct=="log"){
pj11 <- exp(pj11)
}
pj1[jj,] <- pj11[ ajj ]
}
#-- restrict probabilities in calculations
eps <- 1E-10
pj1[ pj1 < 0 ] <- eps
pj1[ pj1 > 1 ] <- 1 - eps
#-- create array
pjM <- array( NA, dim=c(J,2,L) )
pjM[,1,] <- 1 - pj1
pjM[,2,] <- pj1
#--- OUTPUT
return(pjM)
}
# cat( "\n Step 1a (calculate P(X_j|alpha_l)\n" ) ; a1 <- Sys.time() ; print(a1-a0) ; a0 <- a1
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_calc_prob.R
|
## File Name: gdina_calc_prob_one_item.R
## File Version: 0.06
gdina_calc_prob_one_item <- function( J, jj, L, aggr.attr.patt, Mj, delta,
linkfct)
{
pj1 <- matrix( 0, nrow=1, ncol=L )
#---- calculate P(X_j | alpha_l )
ajj <- ( aggr.attr.patt[[jj]] )
mjjj <- Mj[[jj]][[1]][ ajj, ]
djj <- matrix( delta[[jj]], nrow=L, ncol=length(delta[[jj]]), byrow=TRUE )
pj1[1,] <- rowSums( mjjj * djj )
if (linkfct=="logit"){
pj1[1,] <- stats::plogis( pj1[1,] )
}
if (linkfct=="log"){
pj1[1,] <- exp( pj1[1,] )
}
#-- restrict probabilities in calculations
eps <- 1E-10
pj1[ pj1 < 0 ] <- eps
pj1[ pj1 > 1 ] <- 1 - eps
#-- create array
pjM <- array( NA, dim=c(1,2,L) )
pjM[,1,] <- 1 - pj1
pjM[,2,] <- pj1
pjM <- pjM[1,,]
#--- OUTPUT
return(pjM)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_calc_prob_one_item.R
|
## File Name: gdina_create_attribute_patterns.R
## File Version: 0.07
gdina_create_attribute_patterns <- function( q.matrix, skillclasses, zeroprob.skillclasses,
Z.skillspace, G, reduced.skillspace )
{
# extract unique Q-matrix entries
K <- ncol(q.matrix)
q.entries <- as.list( 1:K )
maxAttr <- rep(1,K)
for (kk in 1:K){
q.entries[[kk]] <- sort(unique( c(0,q.matrix[,kk] )))
maxAttr[kk] <- length( q.entries[[kk]] ) - 1
}
attr.patt <- as.matrix( expand.grid( q.entries ) )
if ( ! is.null(skillclasses) ){
attr.patt <- skillclasses
}
colnames(attr.patt) <- colnames(q.matrix)
L <- nrow(attr.patt)
# combine all attributes in an attribute pattern as a string
attr.patt.c <- apply( attr.patt, 1, FUN=function(ll){ paste(ll,collapse="" ) } )
# create designmatrix for reduced skill space
if ( is.null(reduced.skillspace) ){
if (K < 4){
reduced.skillspace <- FALSE
} else {
reduced.skillspace <- TRUE
}
}
# if ( K < 4 | ( ! is.null( zeroprob.skillclasses ) ) | G > 1 ){
if ( ! is.null( zeroprob.skillclasses ) ){
reduced.skillspace <- FALSE
}
if ( ! is.null(Z.skillspace) ){
reduced.skillspace <- TRUE
Z.skillspace <- as.matrix(Z.skillspace)
}
Z <- NULL
covbeta <- NULL
beta <- NULL
ncolZ <- nrow(attr.patt)-1
#----- OUTPUT
res <- list( K=K, maxAttr=maxAttr, attr.patt=attr.patt, L=L, attr.patt.c=attr.patt.c,
reduced.skillspace=reduced.skillspace, Z.skillspace=Z.skillspace, Z=Z, beta=beta,
covbeta=covbeta, ncolZ=ncolZ, q.entries=q.entries)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_create_attribute_patterns.R
|
## File Name: gdina_create_designmatrices.R
## File Version: 0.22
gdina_create_designmatrices <- function( J, Mj, Aj, q.matrix, rule, L, attr.patt, mono.constr,
bugs=NULL )
{
Mj.userdefined <- TRUE
if ( is.null(Mj) ){
Mj.userdefined <- FALSE
Mj <- as.list( rep("noe", J ) )
}
if ( ! is.null(bugs) ){
bugs <- which( colnames(q.matrix) %in% bugs )
}
# Notation for Mj and Aj follows De La Torre (2011)
Aj <- NULL
Aj_mono_constraints <- NULL
Nattr.items <- rowSums(q.matrix >=1)
# list of necessary attributes per item
necc.attr <- as.list( rep(NA,J) )
# list of rows in attr.patt which correspond to attribute classes for one item
attr.items <- NULL
# list of indices of attribute patterns which should be aggregated for each item
aggr.attr.patt <- NULL
for (jj in 1:J){ # loop over items jj
q_jj <- as.numeric(q.matrix[jj,])
nj1 <- necc.attr[[jj]] <- which( q.matrix[jj,] > 0 )
if ( length(nj1)==0 ){
stop( paste("Q matrix row ", jj, " has only zero entries\n", sep="") )
}
Aj1 <- Aj[[jj]] <- gdina_designmatrices_create_Aj( Nattr.items[jj] )
#--- define monotonicity constraints
if (mono.constr){
Aj_mono_constraints[[jj]] <- gdina_create_designmatrices_monotonicity_constraints(Ajjj=Aj[[jj]] )
}
if ( ! Mj.userdefined ){
Mj[[jj]] <- gdina_designmatrices_create_Mj( Aj[[jj]], rule=rule[jj], q_jj=q_jj,
bugs=bugs)
}
l1 <- as.list( 1 )
l2 <- rep(0,L)
for (zz in seq(1,nrow(Aj1)) ){ # begin row zz
Aj1zz <- outer( rep(1,nrow(attr.patt)), Aj1[zz,] )
apzz <- attr.patt[, nj1 ]
apzz <- 1 * ( apzz >=q.matrix[ rep(jj,L),nj1] )
l1[[zz]] <- which( rowMeans( apzz==Aj1zz )==1)
l2[ l1[[zz]] ] <- zz
} # end row zz
attr.items[[jj]] <- l1
aggr.attr.patt[[jj]] <- l2
} # end item jj
#******
# indices for Mj
Mj.index <- matrix( 0, J, 6 )
for (jj in 1:J){
Mj.index[jj,1] <- ncol( Mj[[jj]][[1]] )
Mj.index[jj,4] <- nrow( Aj[[jj]])
}
Mj.index[,3] <- cumsum( Mj.index[,1] )
Mj.index[,2] <- c(1,Mj.index[-J,3] + 1 )
Mj.index[,6] <- cumsum( Mj.index[,4] )
Mj.index[,5] <- c(1,Mj.index[-J,6] + 1 )
# compute designmatrix of aggregation of pattern
aggr.patt.designmatrix <- matrix( 0, L, max(Mj.index[,6]) )
for (jj in 1:J){
Mj.index.jj <- Mj.index[jj,]
for (vv in seq(1,Mj.index.jj[4]) ){
aggr.patt.designmatrix[, Mj.index.jj[5] - 1 + vv ] <- 1 * ( aggr.attr.patt[[jj]]==vv )
}
}
#--- OUTPUT
res <- list(Mj=Mj, Mj.userdefined=Mj.userdefined, Aj=Aj, Nattr.items=Nattr.items, necc.attr=necc.attr,
aggr.attr.patt=aggr.attr.patt, attr.items=attr.items, aggr.patt.designmatrix=aggr.patt.designmatrix,
Mj.index=Mj.index, Aj_mono_constraints=Aj_mono_constraints )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_create_designmatrices.R
|
## File Name: gdina_create_designmatrices_monotonicity_constraints.R
## File Version: 0.05
gdina_create_designmatrices_monotonicity_constraints <- function(Ajjj)
{
N_Ajjj <- nrow(Ajjj)
Ajjj_sum <- rowSums(Ajjj)
# compute distance matrix
dist_Ajjj <- matrix( -9, nrow=N_Ajjj, ncol=N_Ajjj )
for (ii in 1:(N_Ajjj-1) ){
for (hh in (ii+1):N_Ajjj){
dist_Ajjj[hh,ii] <- sum( abs( Ajjj[hh,] - Ajjj[ii,] ) )
}
}
# define matrix for testing monotonicity constraints
NC <- sum( dist_Ajjj==1 )
Ajjj_mono <- matrix( 0, nrow=NC, ncol=N_Ajjj)
uu <- 1
for (ii in 1:N_Ajjj ){
for (hh in 1:N_Ajjj){
if ( dist_Ajjj[hh,ii]==1 ){
Ajjj_mono[uu,c(hh,ii) ] <- c(1,-1)
uu <- uu + 1
}
}
}
return(Ajjj_mono)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_create_designmatrices_monotonicity_constraints.R
|
## File Name: gdina_delta_convert_into_list.R
## File Version: 0.01
gdina_delta_convert_into_list <- function( delta_vec, delta_indices, J)
{
delta <- as.list(1:J)
for ( ii in 1:J){
delta[[ ii ]] <- delta_vec[ delta_indices[[ii]] ]
}
return(delta)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_delta_convert_into_list.R
|
## File Name: gdina_designmatrices_create_Aj.R
## File Version: 0.12
#**** design matrices for GDINA model
gdina_designmatrices_create_Aj <- function(nq)
{
Aj <- NULL
if (nq==1){ Aj <- matrix( c(0,1), ncol=1 ) }
if (nq==2){
Aj <- matrix( c( 0, 0,
1, 0,
0, 1,
1, 1 ), byrow=TRUE, ncol=2 )
}
if (nq==3){
Aj <- matrix( c( 0, 0, 0,
1, 0, 0, 0, 1, 0, 0, 0, 1,
1, 1, 0, 1, 0, 1, 0, 1, 1,
1, 1, 1 ), byrow=TRUE, ncol=3 )
}
if (nq==4){
Aj <- matrix( c( 0, 0, 0, 0,
1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1,
1,1,0,0, 1,0,1,0, 1,0,0,1, 0,1,1,0, 0,1,0,1, 0,0,1,1,
1,1,1,0, 1,0,1,1, 1,1,0,1, 0,1,1,1,
1, 1, 1,1), byrow=TRUE, ncol=4 )
}
if (nq==5){
Aj <- matrix( c( 0,0,0,0,0,
1,0,0,0,0,
0,1,0,0,0,
0,0,1,0,0,
0,0,0,1,0,
0,0,0,0,1,
1,1,0,0,0,
1,0,1,0,0,
1,0,0,1,0,
1,0,0,0,1,
0,1,1,0,0,
0,1,0,1,0,
0,1,0,0,1,
0,0,1,1,0,
0,0,1,0,1,
0,0,0,1,1,
1,1,1,0,0,
1,1,0,1,0,
1,1,0,0,1,
1,0,1,1,0,
1,0,1,0,1,
1,0,0,1,1,
0,1,1,1,0,
0,1,1,0,1,
0,1,0,1,1,
0,0,1,1,1,
1,1,1,1,0,
1,1,1,0,1,
1,1,0,1,1,
1,0,1,1,1,
0,1,1,1,1,
1,1,1,1,1 ), byrow=TRUE, ncol=5 )
}
if ( nq > 5){
Aj <- gdina_designmatrices_create_Aj_general(nq)
}
return(Aj)
}
.create.Aj <- gdina_designmatrices_create_Aj
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_designmatrices_create_Aj.R
|
## File Name: gdina_designmatrices_create_Aj_general.R
## File Version: 0.03
gdina_designmatrices_create_Aj_general <- function(nq)
{
Aj <- matrix( rep(0,nq), nrow=1, ncol=nq )
for (kk in 1:nq){
av <- t( utils::combn( nq, kk ) )
Aj1 <- matrix( 0, nrow=nrow(av), ncol=nq )
for (hh in 1:kk){
Aj1[ cbind( seq( 1, nrow(av) ), av[,hh] ) ] <- 1
}
Aj <- rbind( Aj, Aj1 )
}
return(Aj)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_designmatrices_create_Aj_general.R
|
## File Name: gdina_designmatrices_create_Mj.R
## File Version: 0.11
#***************************************************************
# design matrix Mj
gdina_designmatrices_create_Mj <- function( Aj, rule="GDINA", q_jj=NULL, bugs=NULL)
{
K <- ncol(Aj)
Mj <- NULL
Mj.lab <- NULL
#***********************************************
if (K==1){
Mj <- matrix( c( 1,0, 1,1 ), byrow=TRUE, ncol=2^1 )
Mj.lab <- c( "0", "1" )
}
#***********************************************
if (K==2){
Mj <- matrix( c( 1,0,0,0,
1,1,0,0, 1,0,1,0,
1,1,1,1 ), byrow=TRUE, ncol=2^2 )
Mj.lab <- c( "0", "1", "2", "1-2" )
if (rule=="DINA"){
M <- 2^2
selv <- c(1,M)
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv]
}
if (rule=="DINO"){
M <- 2^2
selv <- c(1,M)
Mj <- Mj[,selv]
Mj[,2] <- 1 ; Mj[1,2] <- 0
Mj.lab <- Mj.lab[ selv]
Mj.lab[2] <- gsub("-", "|", Mj.lab[2] )
}
if (rule=="ACDM" | rule=="GDINA1" ){
selv <- 1:3
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
# In case of K=2, GDINA2=GDINA
}
#***********************************************
if (K==3){
Mj <- cbind( 1, sapply( 1:3, FUN=function(jj){ 1*(Aj[,jj]==1) } ) )
Mj.lab <- c( "0", 1:3 )
g2 <- utils::combn( 3, 2 )
Mj <- cbind( Mj, sapply( seq( 1, ncol(g2)), FUN=function(jj){ rowProds2(Aj[, g2[,jj] ]) } ) )
Mj.lab <- c( Mj.lab, apply( g2, 2, FUN=function(ll){ paste( ll, collapse="-" ) } ) )
g2 <- utils::combn( 3, 3 )
g2 <- matrix( g2, nrow=length(g2), ncol=1 )
Mj <- cbind( Mj, sapply( seq( 1, ncol(g2)), FUN=function(jj){ rowProds2(Aj[, g2[,jj] ]) } ) )
Mj.lab <- c( Mj.lab, apply( g2, 2, FUN=function(ll){ paste( ll, collapse="-" ) } ) )
if (rule=="DINA"){
M <- 2^3
selv <- c(1,M)
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv]
}
if (rule=="DINO"){
M <- 2^3
selv <- c(1,M)
Mj <- Mj[,selv]
Mj[,2] <- 1 ; Mj[1,2] <- 0
Mj.lab <- Mj.lab[ selv]
Mj.lab[2] <- gsub("-", "|", Mj.lab[2] )
}
if (rule=="ACDM" | rule=="GDINA1"){
selv <- 1:4
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
if (rule=="GDINA2"){
selv <- 1:7
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
}
#********************************************************************************************
if (K==4){
Mj <- cbind( 1, sapply( 1:4, FUN=function(jj){ 1*(Aj[,jj]==1) } ) )
Mj.lab <- c( "0", 1:4 )
for (kk in 2:4){
g2 <- utils::combn( 4, kk )
if (kk==4){
g2 <- matrix( g2, nrow=length(g2), ncol=1 )
}
Mj <- cbind( Mj, sapply( seq( 1, ncol(g2)), FUN=function(jj){ rowProds2(Aj[, g2[,jj] ]) } ) )
Mj.lab <- c( Mj.lab, apply( g2, 2, FUN=function(ll){ paste( ll, collapse="-" ) } ) )
}
if (rule=="DINA"){
M <- 2^4
selv <- c(1,M)
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv]
}
if (rule=="DINO"){
M <- 2^4
selv <- c(1,M)
Mj <- Mj[,selv]
Mj[,2] <- 1 ; Mj[1,2] <- 0
Mj.lab <- Mj.lab[ selv]
Mj.lab[2] <- gsub("-", "|", Mj.lab[2] )
}
if (rule=="ACDM" | rule=="GDINA1"){
selv <- 1:5
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
if (rule=="GDINA2"){
selv <- 1:( 1 + 4 + 6 )
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
}
#***************************************
if (K==5){
Mj <- cbind( 1, sapply( 1:5, FUN=function(jj){ 1*(Aj[,jj]==1) } ) )
Mj.lab <- c( "0", 1:5 )
for (kk in 2:5){
g2 <- utils::combn( 5, kk )
if (kk==5){
g2 <- matrix( g2, nrow=length(g2), ncol=1 )
}
Mj <- cbind( Mj, sapply( seq( 1, ncol(g2)), FUN=function(jj){ rowProds2(Aj[, g2[,jj] ]) } ) )
Mj.lab <- c( Mj.lab, apply( g2, 2, FUN=function(ll){ paste( ll, collapse="-" ) } ) )
}
if (rule=="DINA"){
M <- 2^5
selv <- c(1,M)
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv]
}
if (rule=="DINO"){
M <- 2^5
selv <- c(1,M)
Mj <- Mj[,selv]
Mj[,2] <- 1 ; Mj[1,2] <- 0
Mj.lab <- Mj.lab[ selv]
Mj.lab[2] <- gsub("-", "|", Mj.lab[2] )
}
if (rule=="ACDM" | rule=="GDINA1"){
selv <- 1:6
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
if (rule=="GDINA2"){
selv <- 1:( 1 + 5 + 10 )
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
}
#*******************
if ( (K > 5 ) | ( rule=="SISM" ) ){
res <- gdina_designmatrices_create_Mj_general( K=K, Aj=Aj, rule=rule, bugs=bugs,
q_jj=q_jj )
Mj <- res$Mj
Mj.lab <- res$Mj.lab
}
res <- list( Mj, Mj.lab )
return(res)
}
#####################################################################
.create.Mj <- gdina_designmatrices_create_Mj
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_designmatrices_create_Mj.R
|
## File Name: gdina_designmatrices_create_Mj_general.R
## File Version: 0.07
gdina_designmatrices_create_Mj_general <- function( K, Aj, rule, bugs=NULL, q_jj=NULL )
{
Mj <- cbind( 1, sapply( 1:K, FUN=function(jj){ 1*(Aj[,jj]==1) } ) )
Mj.lab <- c( "0", 1:K )
if (K>1){
for (kk in 2:K){
g2 <- utils::combn( K, kk )
if (kk==K){
g2 <- matrix( g2, nrow=length(g2), ncol=1 )
}
Mj <- cbind( Mj, sapply( seq( 1, ncol(g2)), FUN=function(jj){ rowProds2(Aj[, g2[,jj] ]) } ) )
Mj.lab <- c( Mj.lab, apply( g2, 2, FUN=function(ll){ paste( ll, collapse="-" ) } ) )
}
} else {
Mj.lab <- c( "0", "1" )
}
if (rule=="DINA"){
M <- 2^K
selv <- c(1,M)
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv]
}
if (rule=="DINO"){
M <- 2^K
selv <- c(1,M)
Mj <- Mj[,selv]
Mj[,2] <- 1
Mj[1,2] <- 0
Mj.lab <- Mj.lab[ selv]
Mj.lab[2] <- gsub("-", "|", Mj.lab[2] )
}
if (rule=="ACDM" | rule=="GDINA1"){
selv <- 1:(K+1)
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
if (rule=="GDINA2"){
selv <- 1:( 1 + K + K*(K-1)/2 )
Mj <- Mj[,selv]
Mj.lab <- Mj.lab[ selv ]
}
#**** SISM model
if (rule=="SISM"){
Q_entries <- which( q_jj > 0)
K_jj1 <- length(q_jj)
skills <- setdiff( 1:K_jj1, bugs )
skills_jj <- intersect( skills, Q_entries )
bugs_jj <- intersect( bugs, Q_entries )
if( length(skills_jj) > 0){
ind_skills <- seq(1, length(skills_jj),1 )
} else {
ind_skills <- NULL
}
if( length(bugs_jj) > 0){
ind_bugs <- length(ind_skills) + seq(1, length(bugs_jj),1 )
} else {
ind_bugs <- NULL
}
NS <- length(ind_skills)
NB <- length(ind_bugs)
Mj <- 0*Mj
is_sism <- FALSE
if ( (NS>0) & (NB>0) ){
Mj <- Mj[, 1:4]
Mj.lab <- c("S0B1", "S0B0", "S1B1", "S1B0")
is_sism <- TRUE
} else {
Mj <- Mj[,1:2]
if (NS>0){
Mj.lab <- c("S0","S1")
}
if (NB>0){
Mj.lab <- c("B1","B0")
}
}
#*** latent response corresponding to skills
h1 <- 0
if (NS>1){ h1 <- rowMeans( Aj[, ind_skills] ) }
if (NS==1){ h1 <- Aj[, ind_skills] }
latresp_eta <- 1*( h1==1 )
#*** latent response bugs
h1 <- 0
if (NB>1){h1 <- rowSums(Aj[,ind_bugs]) }
if (NB==1){ h1 <- Aj[,ind_bugs] }
latresp_gamma <- 1 * ( h1 > 0 )
if (is_sism){
Mj[ ( latresp_eta==0 ) & ( latresp_gamma==1), 1 ] <- 1
Mj[ ( latresp_eta==0 ) & ( latresp_gamma==0), 2 ] <- 1
Mj[ ( latresp_eta==1 ) & ( latresp_gamma==1), 3 ] <- 1
Mj[ ( latresp_eta==1 ) & ( latresp_gamma==0), 4 ] <- 1
} else {
if (NS>0){
Mj[ latresp_eta==0, 1 ] <- 1
Mj[ latresp_eta==1, 2 ] <- 1
}
if (NB>0){
Mj[ latresp_gamma==1, 1 ] <- 1
Mj[ latresp_gamma==0, 2 ] <- 1
}
}
}
res <- list( Mj=Mj, Mj.lab=Mj.lab )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_designmatrices_create_Mj_general.R
|
## File Name: gdina_dif_compute.R
## File Version: 1.455
#-- auxiliary calculations in gdina model for
#-- detection of differential item functioning
gdina_dif_compute <- function( ocontrol, gg, data )
{
aggr.patt.designmatrix <- ocontrol$aggr.patt.designmatrix
Aj <- ocontrol$Aj
Mj <- ocontrol$Mj
Mj.index <- ocontrol$Mj.index
linkfct <- ocontrol$linkfct
rule <- ocontrol$rule
method <- ocontrol$method
aggr.attr.patt <- ocontrol$aggr.attr.patt
IP <- ocontrol$IP
p.aj.xi <- ocontrol$p.aj.xi[,,gg]
ind1 <- match( ocontrol$item.patt[,1], ocontrol$item.patt.subj)
ind1 <- stats::na.omit(ind1)
# p.aj.xi <- p.aj.xi[ ind1, ]
item.patt.split <- ocontrol$item.patt.split
resp.patt <- ocontrol$resp.patt
item.patt.freq <- ocontrol$item.patt.freq[,gg]
freq.pattern <- ocontrol$freq.pattern
invM.list <- ocontrol$invM.list
eps <- eps2 <- 1E-10
J <- length(Mj)
prob_exp <- varmat.delta <- varmat.palj <- delta <- ndj <- as.list(1:J)
R.lj <- ocontrol$R.lj.gg[,,gg]
I.lj <- ocontrol$I.lj.gg[,,gg]
# calculation of expected counts
R.ljM <- R.lj %*% aggr.patt.designmatrix
I.ljM <- I.lj %*% aggr.patt.designmatrix
for (jj in 1:J){ # begin item
Ajjj <- Aj[[jj]]
Mjjj <- Mj[[jj]][[1]]
Rlj.ast <- R.ljM[ jj, Mj.index[jj,5]:Mj.index[jj,6] ]
Ilj.ast <- I.ljM[ jj, Mj.index[jj,5]:Mj.index[jj,6] ]
pjjj <- Rlj.ast / ( Ilj.ast + eps2 )
if (linkfct=="logit" ){
pjjj[ pjjj > 1-eps ] <- 1 - eps
pjjj[ pjjj < eps ] <- eps
pjjj <- stats::qlogis( pjjj )
}
#*****
if (linkfct=="log" ){
pjjj[ pjjj < eps ] <- eps
pjjj <- log( pjjj )
}
Wj <- diag( Ilj.ast )
if ( ( rule[jj]=="GDINA" )| ( method=="ULS" ) ){
invM <- invM.list[[jj]]
delta.jj <- invM %*% crossprod(Mjjj,pjjj)
} else {
invM <- solve( crossprod(Mjjj, Wj ) %*% Mjjj + diag( rep( eps2, ncol(Mjjj) )) )
delta.jj <- tcrossprod( invM, Mjjj ) %*% Wj %*% pjjj
}
pjj_exp <- ( Mjjj %*% delta.jj )[,1]
if ( linkfct=="logit" ){
pjj_exp <- stats::plogis( pjj_exp)
}
if ( linkfct=="log" ){
pjj_exp <- exp( pjj_exp)
}
# data frame with counts and expected probabilities
prob_exp[[jj]] <- data.frame( "freq"=Ilj.ast / sum( Ilj.ast), "prob"=pjj_exp )
rownames(prob_exp[[jj]]) <- apply( Ajjj, 1,
FUN=function(ll){ paste0("S", paste0( ll, collapse="") ) } )
delta[[jj]] <- delta.jj[,1]
#**** variance matrix
PAJXI <- p.aj.xi
Ajjj <- Aj[[jj]]
Mjjj <- Mj[[jj]][[1]]
Mjj2 <- Mj[[jj]][[2]]
apjj <- aggr.attr.patt[[jj]]
M1 <- max( apjj )
p.ajast.xi <- matrix( 0, nrow=IP, ncol=M1 )
for (kk in 1:M1){
pg1 <- PAJXI[, apjj==kk ]
if ( is.vector(pg1) ){
p.ajast.xi[,kk] <- pg1
} else {
p.ajast.xi[,kk] <- rowSums( pg1 )
}
}
se_version <- ocontrol$se_version
res_jj <- gdina_se_itemwise( R.lj_jj=R.lj[jj,], I.lj_jj=I.lj[jj,],
apjj=apjj, Mjjj=Mjjj, Mjj2=Mjj2, PAJXI=PAJXI, IP=IP,
item.patt.split_jj=item.patt.split[,jj],
resp.patt_jj=resp.patt[,jj], freq.pattern=item.patt.freq,
item.patt.freq=item.patt.freq, avoid.zeroprobs=FALSE,
data=data, jj=jj, method=method, linkfct=linkfct,
delta_jj=delta[[jj]], se_version=se_version )
Rlj.ast <- stats::aggregate( R.lj[jj,], list( aggr.attr.patt[[jj]]), sum )
Ilj.ast <- stats::aggregate( I.lj[jj,], list( aggr.attr.patt[[jj]]), sum )
pjjj <- Rlj.ast[,2] / Ilj.ast[,2]
pjjjM <- outer( rep(1,IP), pjjj ) + eps
nM <- ncol(pjjjM)
x1 <- outer( item.patt.split[,jj], rep(1,nM) )
r1 <- outer( resp.patt[,jj] * item.patt.freq, rep(1,ncol(pjjjM) ) )
# Formula (17) for calculating the standard error
mat.jj <- p.ajast.xi * ( x1 - pjjjM) / ( pjjjM * ( 1 - pjjjM ) )
infomat.jj <- matrix( 0, nM, nM )
for (kk1 in 1:nM){
for (kk2 in kk1:nM){
# frequency weights must be taken into account
hh1 <- sum( mat.jj[,kk1] * mat.jj[,kk2] * item.patt.freq *
resp.patt[,jj] * item.patt.split[,jj] )
infomat.jj[kk2,kk1] <- infomat.jj[kk1,kk2] <- hh1
}
}
try( a1 <- solve( infomat.jj + diag( eps2, ncol(infomat.jj) ) ) )
if ( is.null(a1)){
cat( "Item", colnames(data)[jj], "Singular item parameter covariance matrix\n")
a1 <- NA*infomat.jj
}
varmat.palj[[jj]] <- Ijj <- a1
Wj <- diag( Ilj.ast[,2] )
if ( ( method=="ULS" ) ){
x1 <- t(Mjjj) %*% Mjjj
diag(x1) <- diag(x1) + eps
Wjjj <- solve(x1) %*% t(Mjjj)
} else {
x1 <- t(Mjjj) %*% Wj %*% Mjjj
diag(x1) <- diag(x1) + eps
Wjjj <- solve(x1) %*% t(Mjjj) %*% Wj
}
if ( linkfct=="logit" ){
pjjj.link <- 1 / ( ( pjjj * ( 1 - pjjj ) ) + eps2 )
pjjj.link <- diag( pjjj.link )
Wjjj <- Wjjj %*% pjjj.link
}
if ( linkfct=="log" ){
pjjj.link <- 1 / ( pjjj + eps2 )
pjjj.link <- diag( pjjj.link )
Wjjj <- Wjjj %*% pjjj.link
}
varmat.delta[[jj]] <- Wjjj %*% Ijj %*% t(Wjjj)
# varmat.delta[[jj]] <- t(Wjjj) %*% Ijj %*% Wjjj # this is wrong!!
varmat.delta[[jj]] <- res_jj$varmat.delta_jj
ndj[[jj]] <- length( delta[[jj]] )
} # end jj
#-- output
res <- list( delta=delta, varmat.delta=varmat.delta,
ndj=ndj, prob_exp=prob_exp )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_dif_compute.R
|
## File Name: gdina_init_class_probabilities.R
## File Version: 0.07
gdina_init_class_probabilities <- function( G, L, seed, attr.prob.init )
{
if (G==1){
attr.prob <- rep( 1/L, L )
if ( seed > 0 ){
set.seed(seed)
attr.prob <- cdm_sumnorm( stats::runif(L) )
}
} else {
attr.prob <- matrix( 1/L, L, G )
if ( seed > 0 ){
set.seed(seed)
for (gg in 1:G){
attr.prob[,gg] <- cdm_sumnorm( stats::runif(L) )
}
}
}
#--- initial class probabilities
if ( ! is.null(attr.prob.init) ){
attr.prob <- attr.prob.init
if (G==1){
attr.prob <- as.vector(attr.prob)
}
}
#---- OUTPUT
res <- list(attr.prob=attr.prob)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_init_class_probabilities.R
|
## File Name: gdina_init_item_parameters.R
## File Version: 0.10
gdina_init_item_parameters <- function( delta.init, linkfct, J, seed, Mj,
delta.basispar.init, delta.designmatrix, Mj.index, rule )
{
delta <- delta.init
if ( is.null( delta.init ) ){
#**** identity link
if (linkfct=="identity" ){
for (jj in 1:J){
N1jj <- ncol(Mj[[jj]][[1]])
l1 <- rep(0,N1jj)
if ( seed==0 ){
dd1 <- .2 ; dd2 <- .6
} else {
dd1 <- stats::runif( 1, 0, .4 )
dd2 <- stats::runif( 1, 0, 1 - dd1 - .1 )
}
l1[1] <- dd1
l1[2:N1jj] <- rep( dd2 / (N1jj - 1), N1jj - 1 )
delta[[jj]] <- l1
}
}
#**** logit link
if (linkfct=="logit" ){
for ( jj in 1:J){
N1jj <- ncol(Mj[[jj]][[1]])
l1 <- rep(0,N1jj)
l1[1] <- -2
l1[-1] <- 4 / N1jj
delta[[jj]] <- l1
}
}
#**** log link
if (linkfct=="log" ){
for ( jj in 1:J){
N1jj <- ncol(Mj[[jj]][[1]])
l1 <- rep(0,N1jj)
if ( seed==0 ){
dd1 <- -1.5 ; dd2 <- .75
} else {
dd1 <- stats::runif( 1, -3, -1 )
dd2 <- stats::runif( 1, .25, 1 )
}
l1[1] <- dd1
l1[N1jj] <- dd2
if ( rule[jj]=="ACDM"){
v1 <- .5 + 0*l1
v1[1] <- .80
l1 <- rrumpars2logpars(v1)
}
delta[[jj]] <- l1
}
}
}
###########################
# import inits delta basis parameter
if ( ! is.null( delta.basispar.init ) ){
u.delta <- delta.designmatrix %*% delta.basispar.init
for (jj in 1:J){
delta[[jj]] <- u.delta[ seq( Mj.index[jj,2], Mj.index[jj,3] ), 1]
}
}
#--- OUTPUT
return(delta)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_init_item_parameters.R
|
## File Name: gdina_itemfit.R
## File Version: 0.05
gdina_itemfit <- function( L, J, R.lj, I.lj, item.patt.freq, G, attr.prob, data, pjM )
{
# # n.ik [ 1:TP, 1:I, 1:(K+1), 1:G ]
n.ik <- array( 0, dim=c(L, J, 2, 1 ) )
n.ik[,, 2, 1 ] <- t(R.lj)
n.ik[,, 1, 1 ] <- t(I.lj-R.lj)
pi.k <- array( 0, dim=c(L,1) )
if (G>1){ # item fit only in multiple group case
g1 <- colSums( item.patt.freq )
g1 <- g1 / sum(g1)
for (gg in 1:G){
pi.k[,1] <- pi.k[,1] + attr.prob[,gg] * g1[gg]
}
}
if (G==1){ # item fit only in one group case
pi.k[,1] <- attr.prob$class.prob
}
probs <- aperm( pjM, c(3,1,2) )
itemfit.rmsea <- itemfit.rmsea( n.ik=n.ik, pi.k=pi.k, probs=probs )$rmsea
names(itemfit.rmsea) <- colnames(data)
#--- OUTPUT
res <- list( itemfit.rmsea=itemfit.rmsea, pi.k=pi.k, n.ik=n.ik, pi.k=pi.k)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_itemfit.R
|
## File Name: gdina_maximum_parameter_change.R
## File Version: 0.01
gdina_maximum_parameter_change <- function( delta, delta.new, linkfct )
{
max.par.change <- max( abs( unlist( delta.new ) - unlist( delta ) ) )
if ( linkfct %in% c("logit","log") ){
max.par.change <- max( abs( stats::plogis(unlist( delta.new )) - stats::plogis( unlist( delta ) )) )
}
return(max.par.change)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_maximum_parameter_change.R
|
## File Name: gdina_mstep_item_ml.R
## File Version: 0.952
#**** GDINA M-step item parameters
gdina_mstep_item_ml <- function( pjjj, Ilj.ast, Rlj.ast, eps, avoid.zeroprobs,
Mjjj, invM.list, linkfct, rule, method, iter, delta.new, max.increment, fac.oldxsi,
jj, delta, rrum.model, delta.fixed, mstep_iter, mstep_conv, devchange,
regular_type, regular_lam, cd_steps, mono.constr, Aj_mono_constraints_jj, mono_maxiter,
regular_alpha, regular_tau, regularization_types, prior_intercepts, prior_slopes, use_prior,
regular_weights=NULL, h=1e-4, optimizer="CDM", add_pseudo_count=.005 )
{
eps2 <- eps
delta_jj <- delta[[jj]]
delta_jj0 <- delta[[jj]]
if ( ! is.null(regular_weights) ){
regular_weights <- regular_weights[[jj]]
}
NP <- length(delta_jj)
converged <- FALSE
penalty <- 0
logprior_value <- 0
ii <- 0
max_increment <- max.increment
Rlj.ast <- Rlj.ast + add_pseudo_count
Ilj.ast <- Ilj.ast + 2*add_pseudo_count
N <- sum(Ilj.ast)
diag_only <- FALSE
regularization <- FALSE
if ( regular_type %in% regularization_types ){
diag_only <- TRUE
regularization <- TRUE
max_increment <- max( 3*regular_lam, max_increment )
}
#---- prior function
logprior_FUN <- function(x, p1, p2)
{
lp1 <- log_dgnorm(x=x[1], loc=p1[1], scale=p1[2], power=p1[3] )
lp2 <- log_dgnorm(x=x[-1], loc=p2[1], scale=p2[2], power=p2[3] )
lp <- sum(lp1) + sum(lp2)
return(lp)
}
#----
#------------------ define log-likelihood function without prior
ll_FUN0 <- function(x)
{
irf1 <- gdina_prob_item_designmatrix( delta_jj=x, Mjjj=Mjjj, linkfct=linkfct, eps_squeeze=eps )
ll <- - sum( Rlj.ast * log(abs(irf1)) + ( Ilj.ast - Rlj.ast ) * log( abs(1-irf1 ) ) )
return(ll)
}
#------------------ define log-likelihood function with prior
ll_FUN <- function(x)
{
ll <- ll_FUN0(x=x)
if (use_prior){
ll <- ll - logprior_FUN(x=x, p1=prior_intercepts, p2=prior_slopes)
}
return(ll)
}
#------------------
#------------------
#--- algorithm without monotonicity constraints
if (optimizer=="CDM"){
delta_jj <- gdina_mstep_item_ml_algorithm( delta_jj=delta_jj, max_increment=max_increment, regular_lam=regular_lam,
regular_type=regular_type, regularization=regularization, ll_FUN=ll_FUN, h=h,
mstep_conv=mstep_conv, cd_steps=cd_steps, mstep_iter=mstep_iter,
regular_alpha=regular_alpha, regular_tau=regular_tau, N=N,
regular_weights=regular_weights)
}
if (optimizer=="optim"){
mod <- stats::optim(par=delta_jj, fn=ll_FUN, method="L-BFGS-B",
control=list(maxit=mstep_iter) )
delta_jj <- mod$par
}
ll_value <- ll_FUN(x=delta_jj)
#--- algorithm with monotonicity constraints
if (mono.constr){
iterate_mono <- FALSE
C <- 1
crit_pen <- 1E-10
delta_jj_uncon <- delta_jj
irf1 <- gdina_prob_item_designmatrix( delta_jj=delta_jj, Mjjj=Mjjj, linkfct=linkfct, eps_squeeze=eps )
constraints_fitted_jj <- as.vector( Aj_mono_constraints_jj %*% irf1 )
penalty_constraints <- gdina_mstep_mono_constraints_penalty(x=constraints_fitted_jj)
pen <- sum(penalty_constraints)
if ( pen > crit_pen ){
iterate_mono <- TRUE
}
#------------------ define log-likelihood function with penalty
ll_FUN_mono <- function(x)
{
irf1 <- gdina_prob_item_designmatrix( delta_jj=x, Mjjj=Mjjj, linkfct=linkfct, eps_squeeze=eps )
ll <- - sum( Rlj.ast * log(abs(irf1)) + ( Ilj.ast - Rlj.ast ) * log( abs(1 - irf1 ) ) )
if (use_prior){
ll <- ll - logprior_FUN(x=x, p1=prior_intercepts, p2=prior_slopes)
}
# constraints
y <- gdina_mstep_mono_constraints_penalty( as.vector( Aj_mono_constraints_jj %*% irf1 ) )
y <- C * sum( y^2 )
ll <- ll + y
return(ll)
}
#------------------
# res <- ll_FUN(x=delta_jj)
ll_constraints <- function(x){
irf1 <- gdina_prob_item_designmatrix( delta_jj=x, Mjjj=Mjjj, linkfct=linkfct, eps_squeeze=eps )
con <- gdina_mstep_mono_constraints_penalty( as.vector( Aj_mono_constraints_jj %*% irf1 ) )
return(con)
}
#constraint function
confun <- function(x){
ceq <- -ll_constraints(x=x)
return(list(ceq=ceq,c=NULL))
}
monocon <- ll_constraints(x=delta_jj)
args <- list(start=delta_jj0, objective=ll_FUN, eqFun=ll_constraints,
control=list(maxit=10*mstep_iter))
optim_fn <- gdina_mstep_item_ml_mono_optim_function()
res <- do.call( what=optim_fn, args=args)
delta_jj <- res$par
ll_value <- ll_FUN_mono(x=delta_jj)
}
delta.new[[jj]] <- delta_jj
if ( (fac.oldxsi > 0 ) & (iter>3) ){
fac.oldxsi1 <- fac.oldxsi * ( devchange >=0 )
delta.new[[jj]] <- fac.oldxsi1*delta[[jj]] + ( 1 - fac.oldxsi1 ) * delta.new[[jj]]
}
# fix delta parameter here!!
if ( ! is.null( delta.fixed ) ){
delta.fixed.jj <- delta.fixed[[jj]]
if ( ! is.na( delta.fixed.jj)[1] ){
delta.new[[jj]] <- delta.fixed.jj
}
}
#-- penalty parameter for item
delta_jj <- delta.new[[jj]]
if (regularization){
x <- delta_jj[-1]
penalty1 <- cdm_penalty_values( x=x, regular_type=regular_type, regular_lam=regular_lam,
regular_alpha=regular_alpha, regular_tau=regular_tau )
if ( ! is.null(regular_weights) ){
penalty1 <- regular_weights[-1]*penalty1
}
penalty <- N*sum(penalty1)
ll_value <- ll_value - penalty
}
if (use_prior){
logprior_value <- logprior_FUN(x=delta_jj, p1=prior_intercepts, p2=prior_slopes)
}
#*** output
res <- list( delta.new=delta.new, penalty=penalty, ll_value=ll_value,
logprior_value=logprior_value)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_ml.R
|
## File Name: gdina_mstep_item_ml_algorithm.R
## File Version: 0.254
gdina_mstep_item_ml_algorithm <- function(delta_jj, max_increment,
regular_lam, regular_type, regularization, ll_FUN, h, mstep_conv, cd_steps,
mstep_iter, regular_alpha, regular_tau, N=NULL, regular_weights=NULL, ... )
{
ii <- 0
converged <- FALSE
while ( ! converged ){
delta_jj0 <- delta_jj
#-- parameter update
delta_jj <- gdina_mstep_item_ml_update_parameter( delta_jj=delta_jj,
max_increment=max_increment, regular_lam=regular_lam,
regular_type=regular_type, regularization=regularization,
ll_FUN=ll_FUN, h=h, mstep_conv=mstep_conv, cd_steps=cd_steps,
regular_alpha=regular_alpha, regular_tau=regular_tau, N=N,
regular_weights=regular_weights, ...)
ii <- ii + 1
decr <- max( abs( delta_jj - delta_jj0) )
if ( ii >=mstep_iter ){ converged <- TRUE }
if ( decr < mstep_conv ){ converged <- TRUE }
} # ----- end algorithm
#---- output
return(delta_jj)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_ml_algorithm.R
|
## File Name: gdina_mstep_item_ml_mono_optim_function.R
## File Version: 0.133
gdina_mstep_item_ml_mono_optim_function <- function()
{
CDM_require_namespace(pkg="ROI")
fun <- cdm_attach_internal_function(pack="ROI", fun="nlminb2")
# fun <- ROI::nlminb2
return(fun)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_ml_mono_optim_function.R
|
## File Name: gdina_mstep_item_ml_rrum.R
## File Version: 0.527
#####################################################
# GDINA M-step item parameters
gdina_mstep_item_ml_rrum <- function(
pjjj, Ilj.ast, Rlj.ast, eps, avoid.zeroprobs,
Mjjj, invM.list, linkfct, rule, method,
iter, delta.new, max.increment, fac.oldxsi,
jj, delta, rrum.model, delta.fixed,
mstep_iter, mstep_conv, devchange, optimizer="optim" )
{
eps2 <- eps
delta_jj <- delta[[jj]]
delta_jj <- stats::qlogis( logpars2rrumpars(delta_jj) )
converged <- FALSE
ii <- 0
max_increment <- max.increment
eps <- 1E-6
eps <- 1E-3
Rlj.ast <- Rlj.ast + .005
Ilj.ast <- Ilj.ast + .05
#*** log-likelihood function
ll_FUN <- function(x){
delta_jj <- x
delta_jj <- rrumpars2logpars( stats::plogis(delta_jj) )
irf1 <- ( Mjjj %*% delta_jj )[,1]
irf1 <- exp(irf1)
irf1 <- cdm_squeeze( irf1, c(eps,1-eps) )
ll <- - sum( Rlj.ast * log(abs(irf1)) +
( Ilj.ast - Rlj.ast ) * log( abs(1 - irf1 ) ) )
return(ll)
}
ll_new <- ll0 <- ll_FUN(delta_jj)
avoid_increasing_likelihood <- FALSE
if (optimizer!="CDM"){
converged <- TRUE
}
#*************************************
#*** optimization in R
while ( ! converged ){
delta_jj0 <- delta_jj
ll0 <- ll_new
#*** Newton step
res1 <- numerical_Hessian(par=delta_jj, h=1E-4,
FUN=ll_FUN, gradient=TRUE, hessian=TRUE )
hessian <- - res1$hessian
eps0 <- 1E-4
hessian <- hessian + diag(eps0, nrow(hessian) )
delta_change <- ( solve(hessian) %*% res1$grad )[,1]
while( max(abs(delta_change)) > max_increment ){
delta_change <- ifelse( abs(delta_change) > max_increment,
delta_change /2, delta_change )
}
delta_jj <- delta_jj + delta_change
ll_new <- ll_FUN(delta_jj)
if ((ll_new > ll0)&(avoid_increasing_likelihood)){
tt <- .5
iterate <- TRUE
iter_max <- 10
vv <- 1
while (iterate){
delta_jj <- delta_jj0 + tt*delta_change
ll_new <- ll_FUN(delta_jj)
tt <- tt / 2
if ( ll_new <=ll0){
iterate <- FALSE
}
vv <- vv + 1
if (vv > iter_max){
iterate <- FALSE
converged <- TRUE
}
}
}
ii <- ii + 1
decr <- max( abs( delta_jj - delta_jj0) )
if ( ii >=mstep_iter ){ converged <- TRUE }
if ( decr < mstep_conv ){ converged <- TRUE }
}
#******* optimization using optim
if (optimizer=="optim"){
mod <- stats::optim(par=delta_jj, fn=ll_FUN, method="L-BFGS-B",
control=list(maxit=mstep_iter))
delta_jj <- mod$par
}
#*** retransform
delta_jj <- stats::plogis( delta_jj )
delta_jj <- rrumpars2logpars( delta_jj )
delta.new[[jj]] <- delta_jj
if ( (fac.oldxsi > 0 ) & (iter>3)){
fac.oldxsi1 <- fac.oldxsi * ( devchange >=0 )
delta.new[[jj]] <- fac.oldxsi1*delta[[jj]] + ( 1 - fac.oldxsi1 ) * delta.new[[jj]]
}
# fix delta parameter here!!
if ( ! is.null( delta.fixed ) ){
delta.fixed.jj <- delta.fixed[[jj]]
if ( ! is.na( delta.fixed.jj)[1] ){
delta.new[[jj]] <- delta.fixed.jj
}
}
#*** output
res <- list( delta.new=delta.new )
return(res)
}
######################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_ml_rrum.R
|
## File Name: gdina_mstep_item_ml_rrum2.R
## File Version: 1.11
#####################################################
# GDINA M-step item parameters
gdina_mstep_item_ml_rrum2 <- function(
pjjj, Ilj.ast, Rlj.ast, eps, avoid.zeroprobs, Mjjj, invM.list, linkfct,
rule, method, iter, delta.new, max.increment, fac.oldxsi, jj, delta,
rrum.model, delta.fixed, mstep_iter, mstep_conv, devchange)
{
eps2 <- eps
delta_jj <- delta[[jj]]
delta_jj <- stats::qlogis( logpars2rrumpars(delta_jj) )
converged <- FALSE
ii <- 0
max_increment <- max.increment
eps <- 1E-3
Rlj.ast <- Rlj.ast + .005
Ilj.ast <- Ilj.ast + .05
#*** define function
ll_FUN <- function(par){
delta_jj <- par
delta_jj <- rrumpars2logpars( stats::plogis(delta_jj) )
irf1 <- ( Mjjj %*% delta_jj )[,1]
irf1 <- exp(irf1)
irf1 <- cdm_squeeze( irf1, c(eps,1-eps) )
ll <- - sum( Rlj.ast * log(abs(irf1)) +
( Ilj.ast - Rlj.ast ) * log( abs(1 - irf1 ) ) )
return(ll)
}
#*** optimzation
mstep_conv <- 1000
res0 <- stats::optim( par=delta_jj, fn=ll_FUN, method="BFGS",
control=list( maxit=mstep_conv) )
delta_jj <- res0$par
#*** retransform
delta_jj <- stats::plogis( delta_jj )
delta_jj <- rrumpars2logpars( delta_jj )
delta.new[[jj]] <- delta_jj
if ( (fac.oldxsi > 0 ) & (iter>3)){
fac.oldxsi1 <- fac.oldxsi * ( devchange >=0 )
delta.new[[jj]] <- fac.oldxsi1*delta[[jj]] + ( 1 - fac.oldxsi1 ) * delta.new[[jj]]
}
# fix delta parameter here!!
if ( ! is.null( delta.fixed ) ){
delta.fixed.jj <- delta.fixed[[jj]]
if ( ! is.na( delta.fixed.jj)[1] ){
delta.new[[jj]] <- delta.fixed.jj
}
}
#*** output
res <- list( delta.new=delta.new )
return(res)
}
######################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_ml_rrum2.R
|
## File Name: gdina_mstep_item_ml_update_parameter.R
## File Version: 0.609
gdina_mstep_item_ml_update_parameter <- function( delta_jj, max_increment,
regular_lam, regular_type, regularization, ll_FUN, h, mstep_conv, cd_steps,
regular_alpha, regular_tau, N=NULL, regular_weights=NULL)
{
eps <- 1E-5
if (is.null(N)){ N <- 1 }
#--- no regularization
if ( ! regularization ){
res1 <- numerical_Hessian(par=delta_jj, h=h, FUN=ll_FUN, gradient=TRUE,
hessian=TRUE, diag_only=FALSE )
grad <- res1$grad
hessian <- - res1$hessian
hessian <- cdm_add_ridge_diagonal(x=hessian, eps=eps )
delta_change <- as.vector( cdm_ginv(hessian) %*% grad )
delta_change <- cdm_trim_increment( increment=delta_change, max.increment=max_increment, type=2 )
delta_jj <- delta_jj + delta_change
}
#--- regularization
if (regularization){
NP <- length(delta_jj)
for (pp in 1:NP){
iterate_pp <- TRUE
#cat("---------- pp=", pp, "----------------\n")
vv <- 0
#- start iterations in coordinate descent algorithm
while (iterate_pp){
delta_jj_pp <- delta_jj
res <- numerical_Hessian_partial(par=delta_jj, FUN=ll_FUN, h=h, coordinate=pp )
grad <- res$grad
hessian <- - res$hessian
delta_change <- grad / ( abs(hessian) + eps )
delta_jj[pp] <- delta_jj[pp] - delta_change
vv <- vv + 1
if (pp >=2){
x0 <- delta_jj[pp]
regular_lam_temp <- regular_lam*N
regular_tau_temp <- regular_tau*N
#vt <- abs(hessian) / N
vt <- abs(hessian)
if ( ! is.null(regular_weights) ){
regular_lam_temp <- regular_lam_temp*regular_weights[pp]
regular_tau_temp <- regular_tau_temp*regular_weights[pp]
}
delta_jj[pp] <- gdina_mstep_item_ml_update_parameter_regularization(x=x0,
regular_type=regular_type, regular_lam=regular_lam_temp,
regular_alpha=regular_alpha, regular_tau=regular_tau_temp,
vt=vt )
}
parchange_pp <- max( abs( delta_jj_pp - delta_jj ))
if ( parchange_pp < mstep_conv ){ iterate_pp <- FALSE }
if ( vv > cd_steps ){ iterate_pp <- FALSE }
} # end while iterate_pp
} # end pp
}
#--- output
return(delta_jj)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_ml_update_parameter.R
|
## File Name: gdina_mstep_item_ml_update_parameter_regularization.R
## File Version: 0.23
gdina_mstep_item_ml_update_parameter_regularization <- function(x, regular_type, regular_lam,
regular_alpha, regular_tau, vt=1)
{
x <- x*vt
y <- cdm_parameter_regularization(x=x, regular_type=regular_type, regular_lam=regular_lam,
regular_alpha=regular_alpha, regular_tau=regular_tau )
y <- y / vt
return(y)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_ml_update_parameter_regularization.R
|
## File Name: gdina_mstep_item_parameters.R
## File Version: 0.671
gdina_mstep_item_parameters <- function(R.lj, I.lj, aggr.patt.designmatrix, max.increment,
increment.factor, J, Aj, Mj, delta, method, avoid.zeroprobs, invM.list, linkfct,
rule, iter, fac.oldxsi, rrum.model, delta.fixed, devchange, mstep_iter, mstep_conv,
Mj.index, suffstat_probs, regular_lam, regular_type, cd_steps,
mono.constr, Aj_mono_constraints, mono_maxiter, regular_alpha, regular_tau,
regularization_types, prior_intercepts, prior_slopes, use_prior,
optimizer="CDM", regularization=FALSE, regular_weights=NULL )
{
mono_constraints_fitted <- NULL
# calculation of expected counts
R.ljM <- R.lj %*% aggr.patt.designmatrix
I.ljM <- I.lj %*% aggr.patt.designmatrix
penalty <- 0
ll_value <- 0
logprior_value <- 0
eps2 <- eps <- 1E-10
max.increment <- max.increment / increment.factor
delta.new <- NULL
#----- loop over items
for (jj in 1:J){ # begin item
Ajjj <- Aj[[jj]]
Mjjj <- Mj[[jj]][[1]]
Rlj.ast <- R.ljM[ jj, Mj.index[jj,5]:Mj.index[jj,6] ]
Ilj.ast <- I.ljM[ jj, Mj.index[jj,5]:Mj.index[jj,6] ]
pjjj <- Rlj.ast / ( Ilj.ast + eps2 )
suffstat_probs[[jj]] <- pjjj
#--- define argument list
if ( method %in% c("ULS","WLS","ML") ){
arglist <- list( pjjj=pjjj, Ilj.ast=Ilj.ast, Rlj.ast=Rlj.ast, eps=eps,
avoid.zeroprobs=avoid.zeroprobs, Mjjj=Mjjj, invM.list=invM.list,
linkfct=linkfct, rule=rule, method=method, iter=iter,
delta.new=delta.new, max.increment=max.increment, fac.oldxsi=fac.oldxsi,
jj=jj, delta=delta, rrum.model=rrum.model, delta.fixed=delta.fixed,
devchange=devchange )
}
#*** optimization ULS / WLS
if ( method %in% c("ULS","WLS") ){
res_jj <- do.call( what=gdina_mstep_item_uls, args=arglist )
}
#*** optimization ML
rrum <- ( rule[jj]=="ACDM" ) & ( linkfct=="log")
if ( method %in% c("ML") ){
arglist$mstep_iter <- mstep_iter
arglist$mstep_conv <- mstep_conv
if ( ! rrum ){
arglist$regular_lam <- regular_lam
arglist$regular_type <- regular_type
arglist$cd_steps <- cd_steps
arglist$mono.constr <- mono.constr
arglist$Aj_mono_constraints_jj <- Aj_mono_constraints[[jj]]
arglist$mono_maxiter <- mono_maxiter
arglist$regular_alpha <- regular_alpha
arglist$regular_tau <- regular_tau
arglist$regularization_types <- regularization_types
arglist$prior_intercepts <- prior_intercepts
arglist$prior_slopes <- prior_slopes
arglist$use_prior <- use_prior
arglist$optimizer <- optimizer
arglist$regular_weights <- regular_weights
#-- estimation step
res_jj <- do.call( what=gdina_mstep_item_ml, args=arglist )
penalty <- penalty + res_jj$penalty
ll_value <- ll_value + res_jj$ll_value
logprior_value <- logprior_value + res_jj$logprior_value
}
if ( rrum ){
arglist$optimizer <- optimizer
res_jj <- do.call( what=gdina_mstep_item_ml_rrum, args=arglist )
}
}
delta.new <- res_jj$delta.new
} # end item
# number of regularized item parameters
res <- gdina_mstep_item_parameters_number_of_regularized_parameters(
regularization=regularization, delta=delta, J=J)
numb_regular_pars <- res$numb_regular_pars
delta_regularized <- res$delta_regularized
#----------------- OUTPUT -------------
res <- list( delta.new=delta.new, suffstat_probs=suffstat_probs,
mono_constraints_fitted=mono_constraints_fitted,
penalty=penalty, ll_value=ll_value, logprior_value=logprior_value,
numb_regular_pars=numb_regular_pars, delta_regularized=delta_regularized)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_parameters.R
|
## File Name: gdina_mstep_item_parameters_designmatrix.R
## File Version: 0.05
gdina_mstep_item_parameters_designmatrix <- function( delta.new, delta.designmatrix,
delta.basispar.lower, delta.basispar.upper, Mj.index, J )
{
u.delta.new <- unlist( delta.new )
# calculate basis parameter of delta
delta.basispar <- solve( t( delta.designmatrix) %*% delta.designmatrix ) %*%
t(delta.designmatrix) %*% u.delta.new
if ( ! is.null( delta.basispar.lower )){
delta.basispar <- ifelse( delta.basispar < delta.basispar.lower,
delta.basispar.lower, delta.basispar )
}
if ( ! is.null( delta.basispar.upper )){
delta.basispar <- ifelse( delta.basispar > delta.basispar.upper,
delta.basispar.upper, delta.basispar )
}
delta.new1 <- ( delta.designmatrix %*% delta.basispar )[,1]
for (jj in 1:J){
delta.new[[jj]] <- delta.new1[ seq( Mj.index[jj,2], Mj.index[jj,3] ) ]
}
return(delta.new)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_parameters_designmatrix.R
|
## File Name: gdina_mstep_item_parameters_number_of_regularized_parameters.R
## File Version: 0.06
gdina_mstep_item_parameters_number_of_regularized_parameters <- function( regularization,
delta, J, eps=1e-6)
{
#--- regularized parameters
numb_regular_pars <- NA
delta_regularized <- list()
if (regularization){
numb_regular_pars <- 0
for (jj in 1:J){
delta_jj <- delta[[jj]]
delta_reg <- abs( delta_jj ) < eps
delta_reg[1] <- FALSE
delta_regularized[[jj]] <- delta_reg
numb_regular_pars <- numb_regular_pars + sum(delta_regularized[[jj]])
}
}
#--- output
res <- list(numb_regular_pars=numb_regular_pars, delta_regularized=delta_regularized)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_parameters_number_of_regularized_parameters.R
|
## File Name: gdina_mstep_item_uls.R
## File Version: 0.34
#####################################################
# GDINA M-step item parameters
gdina_mstep_item_uls <- function( pjjj, Ilj.ast, Rlj.ast, eps, avoid.zeroprobs,
Mjjj, invM.list, linkfct, rule, method, iter, delta.new, max.increment, fac.oldxsi,
jj, delta, rrum.model, delta.fixed, devchange)
{
eps2 <- eps
if (linkfct=="logit" ){
pjjj <- cdm_squeeze( pjjj, c(eps,1-eps) )
pjjj <- stats::qlogis( pjjj )
}
if (linkfct=="log" ){
pjjj <- cdm_squeeze( pjjj, c(eps,10) )
pjjj <- log( pjjj )
}
Wj <- diag( Ilj.ast )
if ( avoid.zeroprobs ){
ind <- which( Ilj.ast < eps )
if ( length(ind) > 0 ){
Wj <- diag( Ilj.ast[-ind] )
Mjjj <- Mjjj[ - ind, ]
pjjj <- pjjj[ - ind ]
}
}
if ( ( rule[jj]=="GDINA" )| ( method=="ULS" ) ){
invM <- invM.list[[jj]]
delta.jj <- invM %*% crossprod(Mjjj,pjjj)
} else {
invM <- solve( crossprod(Mjjj, Wj ) %*% Mjjj + diag( rep( eps2, ncol(Mjjj) )) )
delta.jj <- tcrossprod( invM, Mjjj ) %*% Wj %*% pjjj
}
djj <- delta.jj[,1]
djj.change <- djj - delta[[jj]]
if (linkfct=="identity" & (iter > 3) ){
step.change <- .20
djj.change <- ifelse( abs(djj.change) > step.change, djj.change / 2, djj.change )
}
djj <- delta[[jj]] + djj.change
if ( linkfct=="identity"){
if ( sum(djj) > 1 ){
djj <- djj / ( sum( djj ) )
}
}
#######################################################################
iter_min <- 10
djj <- ifelse ( is.na(djj), delta[[jj]], djj )
# control
djj.change <- djj - delta[[jj]]
while( max(abs(djj.change)) > max.increment ){
djj.change <- ifelse( abs(djj.change) > max.increment, djj.change / 2, djj.change )
}
djj <- delta[[jj]] + djj.change
if ( rrum.model & (iter > 10) ){
#---
# RRUM parametrization
# log( P(X=1) )=b0 + b1*alpha1 + b2 * alpha2
# RRUM:
# P(X=1)=pi * r1^( 1- alpha1) * r2^(1-alpha2)
#=> log( P(X=1) )=log[ pi * r1 * r2 * r1^(-alpha1) * r2^(-alpha2) ]
#=log( pi ) + log(r1) + log(r2) + -log(r1)*alpha1 + -log(r2) * alpha2
#=> b1=-log(r1) and r1=exp( -b1 )
#=> log(pi)=b0 + b1 + b2 and pi=exp( b0 + b1 + b2 )
d1 <- djj
# d1 <- ifelse( d1 < 0, .1, d1 )
sum_d1 <- sum(d1)
if ( sum_d1 > 0 ){
d1 <- d1 - sum(d1)
}
d1_samp <- stats::runif( length(d1), 0, .01 )
d1[-1] <- ifelse( d1[-1] < 0, d1_samp[-1], d1[-1] )
sum_d1 <- sum(d1)
if ( sum_d1 > 0 ){
d1 <- d1 - sum(d1)
}
djj <- d1
}
delta.new[[jj]] <- djj
if ( (fac.oldxsi > 0 ) & (iter>3)){
fac.oldxsi1 <- fac.oldxsi * ( devchange >=0 )
delta.new[[jj]] <- fac.oldxsi1*delta[[jj]] + ( 1 - fac.oldxsi1 ) * delta.new[[jj]]
}
# fix delta parameter here!!
if ( ! is.null( delta.fixed ) ){
delta.fixed.jj <- delta.fixed[[jj]]
if ( ! is.na( delta.fixed.jj)[1] ){
delta.new[[jj]] <- delta.fixed.jj
}
}
#--- OUTPUT
res <- list( delta.new=delta.new )
return(res)
}
######################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_item_uls.R
|
## File Name: gdina_mstep_mono_constraints_penalty.R
## File Version: 0.06
gdina_mstep_mono_constraints_penalty <- function(x)
{
eps <- 1e-3
# y <- ifelse( x < 0, x^2, 0 )
y <- ifelse( x < 0, sqrt(x^2+eps), 0 )
return(y)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_mstep_mono_constraints_penalty.R
|
## File Name: gdina_partable.R
## File Version: 0.15
###################################################
# create parameter table for GDINA model
gdina_partable <- function(res)
{
item <- res$item
#**************************
# item parameters
dfr <- data.frame( "partype"="item", "parindex"=NA, "item"=item$itemno,
"item.name"=item$item )
dfr$skillclass <- 0
dfr$varyindex <- dfr$item
pa <- paste(item$partype.attr)
pa <- ifelse( pa=="", "Int", pa )
dfr$parnames <- paste0( dfr$item.name, "_", gsub( "-", "_", pa ) )
dfr$value <- item$est
# fixed vs. free parameters
dfr$fixed <- FALSE
dfr$free <- TRUE
if ( ! is.null( res$control$delta.fixed ) ){
z1 <- res$control$delta.fixed
m1 <- unlist( lapply( z1, FUN=function(ll){ sum( is.na( ll ) ) > 0 } ) )
m1 <- which( ! m1 )
dfr[ dfr$item %in% m1, "free"] <- FALSE
dfr[ dfr$item %in% m1, "fixed"] <- TRUE
}
dfr$rule <- item$rule
dfr$group <- 0
dfr$totindex <- NA
dfr0 <- dfr
#*************************************
# skill class distribution
G <- res$G
ap0 <- ap <- res$attribute.patt
if (G==1){
ap <- matrix( ap[,1], ncol=1 )
}
dfr1 <- NULL
for (gg in 1:G){
ap.names <- paste0("prob_class", rownames(ap0), "_group", gg)
L <- nrow(ap)
dfr <- data.frame( "partype"=rep("probs",L), "parindex"=NA, "item"=0,
"item.name"="")
dfr$skillclass <- 1:L
dfr$varyindex <- NA
dfr$parnames <- ap.names
dfr$value <- ap[,gg]
dfr$fixed <- FALSE
dfr$free <- TRUE
dfr$rule <- ""
dfr$group <- gg
dfr$totindex <- NA
dfr1 <- rbind( dfr1, dfr )
}
dfr0 <- rbind( dfr0, dfr1 )
#*************************************
# marginal skill distribution
G <- res$G
ap0 <- ap <- res$skill.patt
K <- nrow(ap)
V <- ncol(ap)
# gg <- 1
ap.names <- paste0("prob_skill", rownames(ap0) ) #, "_group", gg)
apnames <- NULL
l1 <- strsplit( colnames(ap0), split="prob", fixed=TRUE )
l1 <- unlist( lapply( l1, FUN=function(ll){ substring(ll[2],1,1) } ) )
l2 <- strsplit( colnames(ap0), split="group", fixed=TRUE )
l2 <- unlist( lapply( l2, FUN=function(ll){ substring(ll[2],1,1) } ) )
if (G==1 ){
l2 <- rep("1",V)
}
for (vv in 1:V){
apnames <- c( apnames, paste0( ap.names, "_lev", l1[vv], "_group", l2[vv]) )
}
L <- K*V
dfr <- data.frame( "partype"=rep("margprobs",L), "parindex"=NA, "item"=0,
"item.name"="")
dfr$skillclass <- 0
dfr$varyindex <- NA
dfr$parnames <- apnames
dfr$value <- as.vector(ap)
dfr$fixed <- FALSE
dfr$free <- TRUE
dfr$rule <- ""
dfr$group <- rep( l2, each=K)
dfr$totindex <- NA
dfr0 <- rbind( dfr0, dfr )
dfr0$totindex <- seq( 1, nrow(dfr0) )
return(dfr0)
}
######################################################
gdina.partable <- gdina_partable
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_partable.R
|
## File Name: gdina_post_calc_se.R
## File Version: 0.152
gdina_post_calc_se <- function(G, p.aj.xi, item.patt.freq, attr.prob, p.xi.aj, IP, J,
calc.se, aggr.attr.patt, Aj, Mj, R.lj, I.lj, item.patt.split, resp.patt, delta, linkfct,
rule, avoid.zeroprobs, data, se_version, method, delta.fixed, q.matrix,
delta_regularized, regularization)
{
varmat.delta <- NULL
varmat.palj <- NULL
se.delta <- NULL
delta.summary <- NULL
if (G==1){
PAJXI <- p.aj.xi
}
if (G>1){
a1 <- outer( rep(1,nrow(attr.prob) ), colSums( item.patt.freq ) ) / sum( item.patt.freq)
attr.prob.tot <- rowSums( attr.prob * a1 )
PAJXI <- outer( rep(1,IP), attr.prob.tot ) * p.xi.aj
PAJXI <- PAJXI / rowSums(PAJXI)
}
# matrix form of item.patt.freq
if (G==1){
item.patt.freq <- matrix( item.patt.freq, ncol=1 )
}
freq.pattern <- rowSums( item.patt.freq )
eps2 <- 1E-10
for (jj in 1:J){
se.jj <- NA
if ( calc.se ){
Ajjj <- Aj[[jj]]
Mjjj <- Mj[[jj]][[1]]
apjj <- aggr.attr.patt[[jj]]
R.lj_jj <- R.lj[jj,]
I.lj_jj <- I.lj[jj,]
Mjj2 <- Mj[[jj]][[2]]
item.patt.split_jj <- item.patt.split[,jj]
resp.patt_jj <- resp.patt[,jj]
delta_jj <- delta[[jj]]
res_jj <- gdina_se_itemwise( R.lj_jj=R.lj_jj, I.lj_jj=I.lj_jj, apjj=apjj, Mjjj=Mjjj, Mjj2=Mjj2,
PAJXI=PAJXI, IP=IP, item.patt.split_jj=item.patt.split_jj, resp.patt_jj=resp.patt_jj,
freq.pattern=freq.pattern, item.patt.freq=item.patt.freq,
avoid.zeroprobs=avoid.zeroprobs, data=data, jj=jj, method=method,
linkfct=linkfct, delta_jj=delta_jj,
se_version=se_version )
varmat.delta[[jj]] <- res_jj$varmat.delta_jj
varmat.palj[[jj]] <- res_jj$varmat.palj_jj
se.jj <- sqrt( diag(varmat.delta[[jj]] ) )
}
Mj_jj2 <- unlist(Mj[[jj]][2])
regul <- NULL
if (regularization){
regul <- 1*delta_regularized[[jj]]
}
delta.summary.jj <- data.frame( link=linkfct, item=colnames(data)[jj], itemno=jj,
partype=Mj_jj2)
delta.summary.jj$rule <- rule[jj]
delta.summary.jj$regul <- regul
delta.summary.jj$est <- delta[[jj]]
delta.summary.jj$se <- se.jj
# fix delta parameter here!!
if ( ! is.null( delta.fixed ) ){
delta.fixed.jj <- delta.fixed[[jj]]
if ( ! is.na( delta.fixed.jj)[1] ){
delta.summary.jj$se <- 0
}
}
# colnames(delta.summary.jj)[4] <- "partype"
delta.summary <- rbind( delta.summary, delta.summary.jj )
}
delta.summary$partype.attr <- paste(delta.summary$partype)
if (calc.se){
for (jj in 1:J){
ind.jj <- which( delta.summary$itemno==jj )
qjj <- which( q.matrix[ jj, ] > 0 )
pgjj <- pajj <- paste(delta.summary$partype.attr[ind.jj])
cjj <- paste(colnames(q.matrix)[qjj])
NN <- length(pajj)
pajj <- gsub( "|", "-", pajj )
pajj <- gsub( "=", "-", pajj )
for (nn in 1:NN){
st1 <- as.numeric(unlist( strsplit( paste(pajj[nn]), "-" ) ))
st1 <- st1[ ! is.na( st1 ) ]
st1 <- st1[ st1 > 0 ]
pgjj[nn] <- paste( cjj[ st1 ], collapse="-" )
}
delta.summary$partype.attr[ind.jj] <- pgjj
}
}
#--- OUTPUT
res <- list( varmat.delta=varmat.delta, varmat.palj=varmat.palj, se.delta=se.delta,
delta.summary=delta.summary, freq.pattern=freq.pattern,
item.patt.freq=item.patt.freq)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_post_calc_se.R
|
## File Name: gdina_post_pattern_output.R
## File Version: 0.07
gdina_post_pattern_output <- function(G, p.xi.aj, zeroprob.skillclasses,
item.patt, attr.patt.c, p.aj.xi, item.patt.subj, group2, attr.patt, K )
{
# calculate posterior probability for each attribute pattern
if (G==1){
# set likelihood for skill classes with zero probability to zero
if ( ! is.null(zeroprob.skillclasses) ){
p.xi.aj[, zeroprob.skillclasses ] <- 0
}
pattern <- data.frame(
freq=round(as.numeric(item.patt[,-1]),3),
mle.est=attr.patt.c[ max.col( p.xi.aj ) ],
mle.post=rowMaxs( p.xi.aj ) / rowSums( p.xi.aj ),
map.est=attr.patt.c[ max.col( p.aj.xi ) ],
map.post=rowMaxs( p.aj.xi ) )
}
if (G>1){
ind1 <- match( item.patt.subj, item.patt[,1] )
l1 <- attr.patt.c[ max.col( p.xi.aj ) ]
pattern <- data.frame( "mle.est"=l1[ind1] )
l1 <- rowMaxs( p.xi.aj ) / rowSums( p.xi.aj )
pattern$mle.post <- l1[ind1]
pattern$map.est <- NA
pattern$map.post <- NA
for (gg in 1:G){
# gg <- 1
ind.gg <- which( group2==gg )
ind2.gg <- match( item.patt.subj[ind.gg], item.patt[, 1] )
l1 <- attr.patt.c[ max.col( p.aj.xi[,,gg] ) ]
pattern$map.est[ind.gg] <- l1[ind2.gg]
l1 <- rowMaxs( p.aj.xi[,,gg] )
pattern$map.post[ind.gg] <- l1[ind2.gg]
}
}
# calculate posterior probabilities for all skills separately
if (G==1){
attr.postprob <- p.aj.xi %*% attr.patt
colnames( attr.postprob ) <- paste("post.attr",1:K, sep="")
pattern <- cbind( pattern, attr.postprob )
}
#--------- OUTPUT
res <- list( pattern=pattern, p.xi.aj=p.xi.aj )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_post_pattern_output.R
|
## File Name: gdina_post_posterior_output.R
## File Version: 0.10
gdina_post_posterior_output <- function(G, p.aj.xi, p.xi.aj, pattern, data, item.patt.subj,
item.patt, attr.prob, group)
{
if (G==1){
rownames( p.aj.xi ) <- rownames( pattern ) # output rownames posterior probabilities
pattern <- data.frame(pattern) # convert pattern to numeric format
for (vv in seq(1,ncol(pattern))[ -c(2,4) ] ){
pattern[,vv ] <- as.numeric( paste( pattern[,vv] ) ) }
# subject pattern
item.patt.subj <- data.frame( "case"=1:(nrow(data) ),
"pattern"=item.patt.subj,
"pattern.index"=match( item.patt.subj, item.patt[,1] ) )
# attribute pattern (expected frequencies)
attr.prob0 <- attr.prob
attr.prob <- data.frame( attr.prob )
attr.prob$class.expfreq <- attr.prob[,1] * nrow(data)
#*****
pattern <- pattern[ item.patt.subj$pattern.index, ]
pattern[,1] <- paste( item.patt.subj$pattern )
colnames(pattern)[1] <- "pattern"
p.aj.xi <- p.aj.xi[ item.patt.subj$pattern.index, ]
rownames(p.aj.xi) <- pattern$pattern
p.xi.aj <- p.xi.aj[ item.patt.subj$pattern.index, ]
rownames(p.xi.aj) <- pattern$pattern
}
#-------
if (G==1){
posterior <- p.aj.xi
}
if (G>1){
ind <- match( item.patt.subj, item.patt[,1] )
p.xi.aj <- p.xi.aj[ ind, ]
rownames(p.xi.aj) <- pattern$pattern
p.aj.xi <- p.aj.xi[ ind,, ]
rownames(p.aj.xi) <- pattern$pattern
ND <- dim(p.aj.xi)
posterior <- matrix( 0, nrow=ND[1], ncol=ND[2] )
for (gg in 1:G){
ind.gg <- which( group==gg )
posterior[ ind.gg, ] <- p.aj.xi[ ind.gg,, gg ]
}
attr.prob0 <- attr.prob
}
# labels likelihood
colnames(p.xi.aj) <- paste(rownames(attr.prob))
if (G==1){
attr_prob <- as.vector( attr.prob$class.prob )
} else {
attr_prob <- as.matrix( attr.prob )
}
#--------- OUTPUT
res <- list( item.patt.subj=item.patt.subj, attr.prob=attr.prob, p.xi.aj=p.xi.aj, posterior=posterior,
pattern=pattern, attr.prob0=attr.prob0, attr_prob=attr_prob )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_post_posterior_output.R
|
## File Name: gdina_post_skill_pattern.R
## File Version: 0.08
gdina_post_skill_pattern <- function( attr.prob, G, attr.patt.c, K, maxAttr, q.matrix,
q.entries, attr.patt )
{
# attribute pattern
if (G==1){
attr.prob <- matrix( attr.prob, ncol=1)
colnames( attr.prob ) <- "class.prob"
}
if (G>1){
colnames( attr.prob ) <- paste( "class.prob.group", 1:G, sep="")
}
rownames( attr.prob ) <- attr.patt.c
mA <- max(maxAttr)
if (G==1){
sp <- NULL
for (kk in 0:mA ){
skill.patt <- matrix(apply( matrix( rep( attr.prob, K ), ncol=K) *
(attr.patt==kk), 2, sum ),ncol=1)
rownames(skill.patt) <- colnames(q.matrix)
colnames(skill.patt) <- paste0("skill.prob",kk )
sp <- cbind( sp, skill.patt )
}
skill.patt <- sp
for (kk in 1:K){
ind.kk <- setdiff( 1:mA, 1 + q.entries[[kk]] )
if ( length(ind.kk) > 0 ){
skill.patt[ kk,ind.kk ] <- NA
}
}
}
if (G>1){
sp <- NULL
for (kk in 0:( mA ) ){
skill.patt <- matrix( 0, K, G )
for (gg in 1:G){
skill.patt[,gg] <- matrix(apply( matrix( rep( attr.prob[,gg], K ), ncol=K) *
( attr.patt==kk ), 2, sum ),ncol=1)
}
rownames(skill.patt) <- colnames(q.matrix)
colnames(skill.patt) <- paste0( "skill.prob", kk, ".group", 1:G )
sp <- cbind( sp, skill.patt )
}
skill.patt <- sp
for (kk in 1:K){
v1 <- rep(1:mA,each=G)
ind.kk <- setdiff( v1, rep(1 + q.entries[[kk]],each=G) )
ind.kk <- which( v1 %in% ind.kk )
if ( length(ind.kk) > 0 ){
skill.patt[ kk,ind.kk ] <- NA
}
}
}
#---- OUTPUT
res <- list( attr.prob=attr.prob, skill.patt=skill.patt)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_post_skill_pattern.R
|
## File Name: gdina_postproc_regularized_constrained_parameters.R
## File Version: 0.14
gdina_postproc_regularized_constrained_parameters <- function( mono.constr, delta, Aj_mono_constraints,
Mj, linkfct, regularization, data )
{
#--- number of boundary estimates for monotonicity constraint
numb_bound_mono <- NA
J <- length(delta)
item_bound_mono <- NULL
if ( mono.constr ){
eps_squeeze <- 1E-5
eps <- 1E-3
numb_bound_mono <- 0
for (jj in 1:J){
delta_jj <- delta[[jj]]
Aj_mono_constraints_jj <- Aj_mono_constraints[[jj]]
Mjjj <- Mj[[jj]][[1]]
irf1 <- gdina_prob_item_designmatrix( delta_jj=delta_jj, Mjjj=Mjjj, linkfct=linkfct, eps_squeeze=eps_squeeze )
constraints_fitted_jj <- as.vector( Aj_mono_constraints_jj %*% irf1 )
indi_bound <- any( constraints_fitted_jj < eps )
if (indi_bound){
numb_bound_mono <- numb_bound_mono + indi_bound
item_bound_mono <- c( item_bound_mono, colnames(data)[jj] )
}
}
}
#--- regularized parameters
numb_regular_pars <- NA
if (regularization){
numb_regular_pars <- 0
eps <- 1E-4
for (jj in 1:J){
delta_jj <- delta[[jj]]
numb_regular_pars <- numb_regular_pars + sum( abs( delta_jj ) < eps )
}
}
#--- output
res <- list( numb_bound_mono=numb_bound_mono, numb_regular_pars=numb_regular_pars,
item_bound_mono=item_bound_mono)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_postproc_regularized_constrained_parameters.R
|
## File Name: gdina_prob_item_designmatrix.R
## File Version: 0.06
gdina_prob_item_designmatrix <- function( delta_jj, Mjjj, linkfct, eps_squeeze )
{
irf1 <- ( Mjjj %*% delta_jj )[,1]
if ( linkfct=="log"){
irf1 <- exp(irf1)
}
if ( linkfct=="logit"){
irf1 <- stats::plogis(irf1)
}
irf1 <- cdm_squeeze( irf1, c(eps_squeeze, 1-eps_squeeze) )
return(irf1)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_prob_item_designmatrix.R
|
## File Name: gdina_probitem.R
## File Version: 0.22
#################################################################################
# calculate model implied probabilities in GDINA models
gdina_probitem <- function( Mj, Aj, delta, rule, linkfct, delta.summary,
necc.attr=NULL)
{
I <- length(delta)
pjj <- as.list( 1:I )
ljjj <- rep(0,I)
for (ii in 1:I){
pjjt <- ( Mj[[ii]][[1]] %*% delta[[ii]] )[,1]
names(pjjt) <- paste0("A",apply( Aj[[ii]], 1, FUN=function(ll){ paste(ll, collapse="") } ) )
if (linkfct=="logit"){ pjjt <- stats::plogis( pjjt ) }
if (linkfct=="log"){ pjjt <- exp( pjjt ) }
pjj[[ii]] <- pjjt
ljjj[ii] <- length(pjjt)
}
pjj <- unlist( pjj )
res <- data.frame( "itemno"=rep(1:I, ljjj), "skillcomb"=names(pjj), "prob"=pjj )
dres <- NULL
for (ii in 1:I){
dii <- delta.summary[ delta.summary$itemno==ii, ]
dii <- dii[ nrow(dii), c("item", "rule", "partype.attr" ) ]
necc_ii <- necc.attr[[ii]]
dii$partype.attr <- paste0( names(necc_ii), collapse="-")
colnames(dii)[3] <- "nessskill"
dres <- rbind( dres, dii )
}
res <- cbind( dres[ res$itemno, ], res )
rownames(res) <- NULL
return(res)
}
#################################################################################
gdina.probitem <- gdina_probitem
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_probitem.R
|
## File Name: gdina_probs_invlink.R
## File Version: 0.03
gdina_probs_invlink <- function(probs, linkfct)
{
if ( linkfct=="logit"){
probs <- stats::plogis(probs)
}
if ( linkfct=="log"){
probs <- exp(probs)
}
return(probs)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_probs_invlink.R
|
## File Name: gdina_proc_check_admissible_rules.R
## File Version: 0.05
gdina_proc_check_admissible_rules <- function(rule)
{
admiss.rules <- c("GDINA", "ACDM", "DINA", "DINO",
"GDINA1", "GDINA2", "RRUM", "SISM" )
i1 <- which( ! ( rule %in% admiss.rules ) )
if ( length(i1) > 0 ){
cat("The following rules are not implemented in gdina: ")
cat( paste( unique( rule[i1] ), collapse=" " ), "\n" )
stop("Change your argument 'rule'")
}
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_check_admissible_rules.R
|
## File Name: gdina_proc_define_model_parameters.R
## File Version: 0.06
gdina_proc_define_model_parameters <- function( dat.items, q.matrix, rule, HOGDINA, G )
{
b.attr <- a.attr <- NULL
I <- nrow(dat.items) # number of persons
J <- ncol(dat.items) # number of items
K <- ncol(q.matrix) # number of attributes
dat.items <- as.matrix(dat.items)
q.matrix <- as.matrix(q.matrix)
if ( length(rule)==1){
rule <- rep( rule, J )
}
if (HOGDINA >=0){
b.attr <- a.attr <- matrix( 0, nrow=K, ncol=G )
}
#--- OUTPUT
res <- list(rule=rule, dat.items=dat.items, q.matrix=q.matrix, a.attr=a.attr, b.attr=b.attr,
I=I, J=J, K=K )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_define_model_parameters.R
|
## File Name: gdina_proc_delta_indices.R
## File Version: 0.05
gdina_proc_delta_indices <- function(delta, Mj)
{
I <- length(delta)
dfr <- NULL
NP <- 0
delta_indices <- list()
for (ii in 1:I){
v1 <- delta[[ii]]
Mj_ii <- Mj[[ii]][[2]]
NV <- length(v1)
g1 <- NP + 1:NV
delta_indices[[ ii ]] <- g1
dfr1 <- data.frame("item"=ii, "np_item"=length(v1),
"combi"=Mj_ii, "index"=g1, "val"=v1 )
dfr <- rbind( dfr, dfr1 )
NP <- NP + NV
}
h1 <- strsplit( paste(dfr$combi), split="-" )
dfr$order <- unlist( lapply( h1, FUN=function(hh){ length(hh) } ) )
dfr[ paste(dfr$combi)=="0", "order" ] <- 0
#---- output
res <- list( delta_indices=delta_indices, delta_partable=dfr )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_delta_indices.R
|
## File Name: gdina_proc_hogdina_theta_distribution.R
## File Version: 0.03
gdina_proc_hogdina_theta_distribution <- function(G)
{
reduced.skillspace <- FALSE
theta.k <- seq( -6,6, len=21 )
wgt.theta <- stats::dnorm( theta.k )
w1 <- wgt.theta / sum( wgt.theta )
wgt.theta <- matrix( w1, nrow=length(w1), ncol=G)
#--- OUTPUT
res <- list(theta.k=theta.k, reduced.skillspace=reduced.skillspace, wgt.theta=wgt.theta)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_hogdina_theta_distribution.R
|
## File Name: gdina_proc_item_response_patterns.R
## File Version: 0.29
gdina_proc_item_response_patterns <- function( dat.items, J, G, weights, group,
freq_weights=TRUE)
{
# string with item response patterns
if (freq_weights){
item.patt.subj <- dat.items[,1]
for (jj in 2:J){
item.patt.subj <- paste( item.patt.subj, dat.items[,jj], sep="")
}
} else {
N <- nrow(dat.items)
item.patt.subj <- paste0( "P", 1E6 + 1:N )
}
# calculate frequency of each item response pattern
item.patt <- table( item.patt.subj )
# sort item response pattern according to their absolute frequencies
six <- sort( item.patt, index.return=FALSE, decreasing=TRUE)
# define data frame 'item.patt' with item response pattern and its frequency (weight)
item.patt <- cbind( "pattern"=rownames(six), "freq"=as.numeric(as.vector(six) ) )
# calculate weighted frequency for each item response pattern
if (G==1){
h1 <- rowsum( weights, item.patt.subj )
item.patt[,2] <- h1[ match( item.patt[,1], rownames(h1) ), 1]
item.patt.freq <- as.numeric(item.patt[,2])
}
if (G > 1){
item.patt.freq <- matrix( 0, nrow(item.patt), G )
for (gg in 1:G){
h1 <- rowsum( weights * (group==gg ), item.patt.subj )
item.patt[,2] <- h1[ match( item.patt[,1], rownames(h1) ), 1]
item.patt.freq[,gg] <- as.numeric(item.patt[,2])
}
}
#---- OUTPUT
res <- list(item.patt.subj=item.patt.subj, item.patt=item.patt, six=six,
item.patt.freq=item.patt.freq)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_item_response_patterns.R
|
## File Name: gdina_proc_multiple_group_objects.R
## File Version: 0.08
gdina_proc_multiple_group_objects <- function(group)
{
G <- 1
group0 <- group
groupre <- FALSE
group2 <- NULL
if ( is.factor( group ) ){
group <- paste( group )
}
if ( ! is.null( group) ){
group0 <- group
groups <- sort( unique( group) )
G <- length(groups)
group2 <- match( group, groups )
if ( any( group !=group2 ) ){
group <- group2
groupre <- TRUE
}
}
group.stat <- NULL
if ( G > 1 ){
# group statistics
a1 <- stats::aggregate( 1+0*group, list(group), sum )
a2 <- rep("",G)
for (gg in 1:G){
a2[gg] <- group0[ which( group==gg )[1] ]
}
group.stat <- cbind( a2, a1 )
colnames(group.stat) <- c( "group.orig", "group", "N" )
}
#---- OUTPUT
res <- list(G=G, group=group, group0=group0, groupre=groupre, group.stat=group.stat,
group2=group2)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_multiple_group_objects.R
|
## File Name: gdina_proc_noninvariance_multiple_groups.R
## File Version: 0.20
#--- handle non-invariance of multiple group parameters
gdina_proc_noninvariance_multiple_groups <- function( data, q.matrix,
invariance, group )
{
create_pseudo_items <- TRUE
invariant <- invariance
invariance_TRUE <- mean( invariance==TRUE )==1
invariance_FALSE <- mean( invariance==FALSE )==1
if (invariance_TRUE ){
create_pseudo_items <- FALSE
invariant <- NULL
}
if (invariance_FALSE){
invariant <- NULL
}
rownames(q.matrix) <- colnames(data)
if ( ( ! is.null(group) ) & create_pseudo_items ){
I <- ncol(data)
data <- item_by_group(dat=data, group=group, invariant=invariant)
G <- length( unique(group) )
ind <- c( attr(data, "invariant_index"), attr(data, "noninvariant_index_extended") )
q.matrix <- q.matrix[ ind, ]
rownames(q.matrix) <- colnames(data)
}
res <- list( data=data, q.matrix=q.matrix )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_noninvariance_multiple_groups.R
|
## File Name: gdina_proc_prior_distribution.R
## File Version: 0.09
gdina_proc_prior_distribution <- function( prior_intercepts, prior_slopes, method, linkfct, PEM )
{
prior_intercepts_null <- is.null(prior_intercepts)
prior_slopes_null <- is.null(prior_slopes)
use_prior <- FALSE
if ( ( ! prior_intercepts_null ) | ( ! prior_slopes_null ) ){
method <- "ML"
linkfct <- "logit"
use_prior <- TRUE
PEM <- FALSE
if (prior_intercepts_null){
prior_intercepts <- c(0,1,Inf)
}
if (prior_slopes_null){
prior_slopes <- c(0,1,Inf)
}
prior_intercepts <- gdina_proc_prior_distribution_extend_normal(prior=prior_intercepts)
prior_slopes <- gdina_proc_prior_distribution_extend_normal(prior=prior_slopes)
}
#---- output
res <- list(prior_intercepts=prior_intercepts, prior_slopes=prior_slopes, linkfct=linkfct,
method=method, use_prior=use_prior, PEM=PEM)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_prior_distribution.R
|
## File Name: gdina_proc_prior_distribution_extend_normal.R
## File Version: 0.01
gdina_proc_prior_distribution_extend_normal <- function(prior)
{
if (length(prior)==2){
prior <- c(prior, 2)
}
return(prior)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_prior_distribution_extend_normal.R
|
## File Name: gdina_proc_regularization.R
## File Version: 0.24
gdina_proc_regularization <- function( regular_type, cd, mono.constr, linkfct,
method, PEM, regular_lam, regular_alpha, regular_tau, rule, optimizer="CDM" )
{
save.devmin <- TRUE
regularization <- FALSE
cd_algorithm <- FALSE
regularization_types <- c("lasso","scad", "elnet","ridge", "scadL2", "tlp", "mcp")
if ( sum(rule=="SISM") > 0 ){
method <- "ML"
}
if (regular_type %in% regularization_types ){
regularization <- TRUE
cd_algorithm <- TRUE
method <- "ML"
}
if ( cd ){
cd_algorithm <- TRUE
}
if ( mono.constr ){
linkfct <- "logit"
method <- "ML"
PEM <- FALSE
}
if (regularization){
save.devmin <- FALSE
linkfct <- "logit"
PEM <- FALSE
optimizer <- "CDM"
}
if ( linkfct=="log"){
PEM <- FALSE
}
if ( ! ( regular_type %in% c("elnet", "scadL2") ) ){
regular_alpha <- NA
}
if ( ! ( regular_type %in% c("tlp") ) ){
regular_tau <- NA
}
#---- output
res <- list( linkfct=linkfct, save.devmin=save.devmin, method=method,
regularization=regularization, cd_algorithm=cd_algorithm,
PEM=PEM, regular_lam=regular_lam, regular_alpha=regular_alpha,
regular_tau=regular_tau, regularization_types=regularization_types,
optimizer=optimizer )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_regularization.R
|
## File Name: gdina_proc_sequential_items.R
## File Version: 0.14
gdina_proc_sequential_items <- function( data, q.matrix )
{
maxK <- max( data, na.rm=TRUE )
sequential <- FALSE
if ( maxK > 1){
res0 <- sequential.items( data=data )
data <- res0$dat.expand
iteminfo <- res0$iteminfo
sequential <- TRUE
if (! is.numeric(q.matrix[,1])){
q.matrix <- q.matrix[,-c(1:2)]
} else {
q.matrix <- q.matrix[ iteminfo$itemindex, ]
rownames(q.matrix) <- colnames(data)
}
}
res <- list( data=data, sequential=sequential, q.matrix=q.matrix )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_sequential_items.R
|
## File Name: gdina_proc_spec_rrum.R
## File Version: 0.12
gdina_proc_spec_rrum <- function(rule, method, linkfct, optimizer="CDM")
{
# estimation of a reduced RUM model
rrum.params <- FALSE
rrum.model <- FALSE
if ( any( rule=="RRUM" ) ){
rule <- "ACDM"
linkfct <- "log"
if ( is.null(method) ){
method <- "ML"
}
rrum.model <- TRUE
optimizer <- "optim"
} else {
if ( is.null(method) ){
method <- "WLS"
}
}
#---- OUTPUT
res <- list( rrum.params=rrum.params, rrum.model=rrum.model, method=method,
linkfct=linkfct, rule=rule, optimizer=optimizer)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_spec_rrum.R
|
## File Name: gdina_proc_split_item_response_patterns.R
## File Version: 0.07
gdina_proc_split_item_response_patterns <- function( item.patt, J, freq_weights=TRUE,
resp=NULL, dat.items=NULL )
{
#---------- use frequency weights
if (freq_weights ){
# split item response pattern in a data frame with items as columns
spl <- sapply( as.vector(item.patt[,1]), FUN=function(ii){ strsplit( ii, split=NULL) } )
item.patt.split <- matrix( rep( 0, length(spl) * J ), ncol=J )
for (ll in 1:length(spl) ){
item.patt.split[ ll, ] <- as.numeric( spl[[ll]] )
}
# response pattern matrix: each observed entry corresponds to a 1,
# each unobserved entry to a 0
resp.patt <- 1* ( item.patt.split !=9 )
}
#---------- do not use frequency weights
if ( ! freq_weights ){
item.patt.split <- dat.items
resp.patt <- resp
}
# number of item response patterns
IP <- nrow(item.patt.split)
#---- OUTPUT
res <- list(IP=IP, resp.patt=resp.patt, item.patt.split=item.patt.split)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_split_item_response_patterns.R
|
## File Name: gdina_proc_uls_inverse_matrices.R
## File Version: 0.01
gdina_proc_uls_inverse_matrices <- function(Mj, J)
{
invM.list <- list( 1:J )
for (jj in 1:J){
Mjjj <- Mj[[jj]][[1]]
invM.list[[jj]] <- solve( crossprod(Mjjj) )
}
return(invM.list)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_proc_uls_inverse_matrices.R
|
## File Name: gdina_progress_em_algorithm.R
## File Version: 0.34
gdina_progress_em_algorithm <- function( delta, data, like.new, loglikeold,
max.par.change, iter, progress, progress.item, regularization, penalty, opt_fct,
opt_fct_change, ll_value, regular_type, logprior_value, use_prior,
numb_regular_pars=NA)
{
digits_par_change <- 6
digits_opt_fct <- 5
digits_opt_fct_change <- 7
if (progress){
if (progress.item){
g1 <- unlist( lapply( delta, FUN=function(ll){ paste( round(ll,4), collapse=" " ) } ))
g1 <- matrix( paste( colnames(data), g1 ), ncol=1)
print(g1)
}
cat( "Deviance","=", round( -2*like.new, digits_opt_fct ) )
devchange <- 2*(like.new-loglikeold)
if (iter >1){
cat(" | Deviance change","=", round( 2*(like.new-loglikeold), digits_opt_fct_change) )
}
cat("\n" )
if (regularization | use_prior){
if ( regularization){
cat( "Penalty","=", round( penalty, digits_opt_fct ), "\n")
cat( "Number of regularized parameters","=", numb_regular_pars, "\n")
}
if ( use_prior){
cat( "Log prior","=", round( logprior_value, digits_opt_fct ), "\n")
}
cat( "Optimization function","=", round( opt_fct, digits_opt_fct ) )
if (iter>1){
cat(" | Function change","=", round( opt_fct_change, digits_opt_fct_change) )
}
cat("\n")
}
if ( ( ! regularization ) & ( ! use_prior ) ){
if ( devchange < 0 & iter>1){
cat( "**** Deviances decreases! Check for nonconvergence. ****\n")
}
}
cat("Maximum parameter change:", round( max.par.change, digits_par_change), "\n")
}
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_progress_em_algorithm.R
|
## File Name: gdina_progress_start_estimation.R
## File Version: 0.05
gdina_progress_start_estimation <- function( progress, linkfct, disp, G, groupre,
s1, display)
{
if (progress){
cat(disp,"\n")
cat( " Link function:", linkfct, "\n")
if (G>1){
cat(" Multiple group estimation with",G,"groups\n")
if (groupre){ cat( " Renumbered group identifier from 1 to",G,"\n") }
}
cat( " **", paste(s1), "\n" )
cat(display)
utils::flush.console()
}
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_progress_start_estimation.R
|
## File Name: gdina_reduced_skillspace.R
## File Version: 0.18
###################################################
# auxiliary function reduced skill space
gdina_reduced_skillspace <- function( ntheta, Z,
reduced.skillspace.method=2, eps=1E-10 )
{
#***********************************
ntheta <- cdm_sumnorm( ntheta )
lntheta <- matrix(log(ntheta+eps),ncol=1 )
V <- diag( ntheta)
#---------------------------
#*** skill space method 1 (CDM <=2.5)
if ( reduced.skillspace.method==1){
Z1 <- crossprod(Z, V) %*% Z
diag(Z1) <- diag(Z1)+eps
covbeta <- solve(Z1)
beta <- covbeta %*% ( crossprod(Z,V) %*% lntheta )
}
#------------------------------
#*** skill space method 2 (CDM >=2.6)
if ( reduced.skillspace.method==2){
mod <- stats::lm( lntheta ~ 0 + Z, weights=ntheta )
beta <- matrix( mod$coef, nrow=ncol(Z), ncol=1 )
beta[ is.na(beta) ] <- 0
}
#*******************************************
# calculate attribute probability
attr.prob <- reduced_skillspace_beta_2_probs( Z=Z, beta=beta )
#***** output
res <- list(beta=beta, attr.prob=attr.prob)
return(res)
}
############################################################
gdina.reduced.skillspace <- gdina_reduced_skillspace
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_reduced_skillspace.R
|
## File Name: gdina_reduced_skillspace_multiple_groups.R
## File Version: 0.10
gdina_reduced_skillspace_multiple_groups <- function( Z, reduced.skillspace.method, item_patt_freq_matr,
p.aj.xi, G )
{
#---- single group
if (G==1){
res <- gdina_reduced_skillspace_single_group( Z=Z, reduced.skillspace.method=reduced.skillspace.method,
ipmat=item_patt_freq_matr, post=p.aj.xi )
}
#---- multiple groups
if (G>1){
NZ <- ncol(Z)
L <- nrow(Z)
beta <- matrix(NA, nrow=NZ, ncol=G)
attr.prob <- matrix(NA, nrow=L, ncol=G)
for (gg in 1:G){
ipmat <- item_patt_freq_matr[,,gg]
post <- p.aj.xi[,,gg]
res <- gdina_reduced_skillspace_single_group( Z=Z, reduced.skillspace.method=reduced.skillspace.method,
ipmat=ipmat, post=post )
beta[,gg] <- res$beta
attr.prob[,gg] <- res$attr.prob
}
res <- list(beta=beta, attr.prob=attr.prob)
}
#--- output
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_reduced_skillspace_multiple_groups.R
|
## File Name: gdina_reduced_skillspace_single_group.R
## File Version: 0.04
gdina_reduced_skillspace_single_group <- function( Z, reduced.skillspace.method, ipmat, post )
{
ntheta <- colSums( ipmat * post )
res <- gdina_reduced_skillspace( ntheta=ntheta, Z=Z, reduced.skillspace.method=reduced.skillspace.method )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_reduced_skillspace_single_group.R
|
## File Name: gdina_se_itemwise.R
## File Version: 0.33
gdina_se_itemwise <- function( R.lj_jj, I.lj_jj, apjj,
Mjjj, Mjj2, PAJXI, IP, item.patt.split_jj, resp.patt_jj,
freq.pattern, item.patt.freq, avoid.zeroprobs , data, jj,
method, linkfct, delta_jj, se_version )
{
eps2 <- 1E-10
Rlj.ast <- rowsum( R.lj_jj, apjj)[,1]
Ilj.ast <- rowsum( I.lj_jj, apjj)[,1]
pjjj <- Rlj.ast / Ilj.ast
varmat.palj_jj <- NULL
infomat.jj <- NULL
#********* standard error calculation observed log-likelihood per item
if (se_version==1){
loglike_item_jj <- function(x){
pjjj_model <- ( Mjjj %*% x )[,1]
pjjj_model <- gdina_probs_invlink(probs=pjjj_model, linkfct=linkfct)
ll1 <- Rlj.ast * cdm_log(x=pjjj_model, eps=eps2)
ll2 <- (Ilj.ast-Rlj.ast) * cdm_log(x=1-pjjj_model, eps=eps2)
ll <- sum(ll1 + ll2)
return(ll)
}
res_jj <- loglike_item_jj(x=delta_jj)
hess_jj <- numerical_Hessian( par=delta_jj, FUN=loglike_item_jj )
varmat.delta_jj <- cdm_ginv( - hess_jj )
}
#********* standard error calculation formulas de la Torre (2011)
if (se_version==0){
Mjjj <- Mjjj[ sort(unique(apjj)), ]
M1 <- length( unique(apjj) )
p.ajast.xi <- matrix( 0, nrow=IP, ncol=M1 )
for (kk in 1:M1){
pg1 <- PAJXI[, apjj==kk ]
if ( is.vector(pg1)){
p.ajast.xi[,kk] <- pg1
} else {
p.ajast.xi[,kk] <- rowSums( pg1 )
}
}
pjjjM <- outer( rep(1,IP), pjjj ) + eps2
nM <- ncol(pjjjM)
x1 <- outer( item.patt.split_jj, rep(1,nM) )
r1 <- outer( resp.patt_jj * item.patt.freq, rep(1,ncol(pjjjM) ) )
# Formula (17) for calculating the standard error
mat.jj <- p.ajast.xi * ( x1 - pjjjM) / ( pjjjM * ( 1 - pjjjM ) + eps2)
infomat.jj <- matrix( 0, nM, nM )
for (kk1 in 1:nM){
for (kk2 in kk1:nM){
# frequency weights must be taken into account
hh1 <- sum( mat.jj[,kk1] * mat.jj[,kk2] * freq.pattern *
resp.patt_jj * item.patt.split_jj )
infomat.jj[kk2,kk1] <- infomat.jj[kk1,kk2] <- hh1
}
}
if ( avoid.zeroprobs ){
ind <- which( is.na(diag(infomat.jj) ))
if ( length(ind) > 0 ){
infomat.jj <- infomat.jj[-ind, -ind]
}
}
a1 <- try( solve( infomat.jj + diag( eps2, ncol(infomat.jj) ) ) )
if ( is(a1, "try-error") ){
cat( "Item", colnames(data)[jj], "Singular item parameter covariance matrix\n")
a1 <- NA*infomat.jj
}
varmat.palj_jj <- Ijj <- a1
Wj <- diag( Ilj.ast[,2] )
if ( avoid.zeroprobs ){
ind <- which( Ilj.ast[,2] < eps2 )
if ( length(ind) > 0 ){
Wj <- diag( Ilj.ast[-ind,2] )
Mjjj <- Mjjj[ - ind, ]
pjjj <- pjjj[ - ind ]
}
}
if ( ( method=="ULS" ) ){
x1 <- t(Mjjj) %*% Mjjj
diag(x1) <- diag(x1) + eps2
Wjjj <- solve( x1 ) %*% t(Mjjj)
} else {
x1 <- t(Mjjj) %*% Wj %*% Mjjj
diag(x1) <- diag(x1) + eps2
Wjjj <- solve( x1 ) %*% t(Mjjj) %*% Wj
}
if ( linkfct=="logit" ){
pjjj.link <- 1 / ( ( pjjj * ( 1 - pjjj ) ) + eps2 )
pjjj.link <- diag( pjjj.link )
Wjjj <- Wjjj %*% pjjj.link
}
if ( linkfct=="log" ){
pjjj.link <- 1 / ( pjjj + eps2 )
pjjj.link <- diag( pjjj.link )
Wjjj <- Wjjj %*% pjjj.link
}
varmat.delta_jj <- Wjjj %*% Ijj %*% t(Wjjj)
}
#--- output
res <- list( infomat.jj=infomat.jj, varmat.palj_jj=varmat.palj_jj,
varmat.delta_jj=varmat.delta_jj)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_se_itemwise.R
|
## File Name: gdina_standardize_weights.R
## File Version: 0.01
gdina_standardize_weights <- function( weights )
{
N <- length(weights)
weights <- N*weights / sum(weights)
return(weights)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdina_standardize_weights.R
|
## File Name: gdm.R
## File Version: 8.659
###########################################
# General Diagnostic Model
###########################################
#
#..........................#
# OUTLINE: #
#..........................#
#
# Input:
# ------
# data ... polytomous responses
# I Items with categories 0,1,...,K
# group ... 1, ..., G
# covariates and groups. Up to now, only use groups
# theta.k ... Multidimensional ability design vector
# as input. It is of dimension D and therefore a
# a [TH,D] matrix (TH is the number of theta points)
# Design matrix for smoothing of theta.k distribution
#
# Model:
# ------
# P(X_{pi}=k)=g( b_ik + a_i1 q_i1k theta_i1 + ... + a_iD q_iD*k theta_iD )
# b_ik ... item-category difficulty
# a_id ... item slopes
# q_ik ... design matrix for slopes
# * in general it will be (0,1,...,K)
# but can be specified by the user
# * The theta vectors can also be transformed in the R formula
# framework. Therefore D* will in general be larger
# than D. For example, an interaction \theta_1*\theta_2 or
# theta^2 can be used in the estimation.
#
# Algorithm:
# ----------
# b ... b[1:I,1:K] matrix of difficulties
# a ... a[1:I,1:D] array of item slopes
# n_tikg n.ik[1:TH,1:I,1:K,1:G] array of expected item responses
# of ability pattern t at item i in category k and group g
# pi.k ... [1:TH,1:G] marginal ability distribution in groups 1,...,G
#
# Specifications:
# ---------------
# o Q matrix: allocate items to dimensions:
# can be either a matrix or an array
# o matrix with fixed b or a parameters
# o itemgroups for a and b parameters / constraints
# est.a and est.b
# o log-linear smoothing of ability distribution
# -> design matrix of theta
#
# Details:
# --------
# o If there are different categories per item,
# then use the maximal category K for all items and
# set b_{ik} to infinity if for item i categeory k
# is not observed.
# o Calculations of probabilities:
# P(X_pi=k|\theta)=exp( b_{ik} + a_i1 * q_{i1k} theta_1 +
# ... + a_{iD} * q_{i1D} theta_D ) / NN
# The normalization constraint NN must be calculated
# appropriately .
#
#################################################################
# GDM function
#
gdm <- function( data, theta.k, irtmodel="2PL", group=NULL,
weights=rep(1, nrow(data)),
Qmatrix=NULL,thetaDes=NULL, skillspace="loglinear",
b.constraint=NULL, a.constraint=NULL,
mean.constraint=NULL, Sigma.constraint=NULL,
delta.designmatrix=NULL, standardized.latent=FALSE,
centered.latent=FALSE, centerintercepts=FALSE, centerslopes=FALSE,
maxiter=1000, conv=1E-5, globconv=1E-5, msteps=4,
convM=.0005, decrease.increments=FALSE, use.freqpatt=FALSE,
progress=TRUE, PEM=FALSE, PEM_itermax=maxiter, ...)
{
# mean.constraint [ dimension, group, value ]
# Sigma.constraint [ dimension1, dimension2, group, value ]
#*************************
# data preparation
s1 <- Sys.time()
e1 <- environment()
cl <- match.call()
## prevent from warnings in R CMD check "no visible binding"
## gdm: no visible binding for global variable 'TD'
TD <- TP <- EAP.rel <- mean.trait <- sd.trait <- skewness.trait <- NULL
K.item <- correlation.trait <- D <- NULL
se.theta.k <- NULL
data0 <- data <- as.matrix(data)
dat.resp0 <- dat.resp <- 1 - is.na(data)
dat <- data
dat[ is.na(data) ] <- 0
dat0 <- dat
# center slopes
if ( irtmodel!="2PL" ){
centerslopes <- FALSE
}
# use frequency pattern. If yes, then some data preparation follows.
if ( use.freqpatt ){
res <- gdm_data_prep( dat=dat, data=data, weights=weights, group=group )
weights <- res$weights
dat <- res$dat
dat.resp <- res$dat.resp
data <- res$data
item.patt <- res$item.patt
}
# maximal categories
K <- max(dat)
# list of indicator data frames
dat.ind <- as.list( 1:(K+1) )
for (ii in 0:K){
dat.ind[[ii+1]] <- 1 * ( dat==ii )*dat.resp
}
I <- ncol(dat) # number of items
n <- nrow(dat)
#--- response patterns
resp.ind.list <- gdm_proc_response_indicators(dat.resp=dat.resp)
#-- process data for multiple groups
res <- slca_proc_multiple_groups( group=group, n=n )
G <- res$G
group <- res$group
group0 <- res$group0
group.stat <- res$group.stat
Ngroup <- res$Ngroup
#--- theta design
res <- gdm_thetadesign( theta.k=theta.k, thetaDes=thetaDes, Qmatrix=Qmatrix )
D <- res$D
TD <- res$TD
TP <- res$TP
theta.k <- res$theta.k
thetaDes <- res$thetaDes
Qmatrix <- res$Qmatrix
#--- starting values for b
b <- gdm_inits_b( dat0=dat0, dat.resp0=dat.resp0, I=I, K=K )
#****
# item slope matrix
# a[1:I,1:TD] ... Items x theta dimension
# a <- matrix( 1, nrow=I, ncol=TD )
# item x category slopes are in principle also possible
KK <- K # if KK==1 then a slope parameter for all items is estimated
a <- array( 1, dim=c(I,TD,KK) )
# define Q matrix
res <- gdm_Qmatrix( Qmatrix=Qmatrix, irtmodel=irtmodel, I=I, TD=TD, K=K, a=a )
Qmatrix <- res$Qmatrix
a <- res$a
#--- constraints on item parameters
res <- gdm_constraints_itempars( b.constraint=b.constraint, a.constraint=a.constraint, K=K, TD=TD,
Qmatrix=Qmatrix, a=a )
a.constraint <- res$a.constraint
b.constraint <- res$b.constraint
a <- res$a
#--- starting values for distributions
Sigma <- diag(1,D)
pik <- mvtnorm::dmvnorm( matrix( theta.k,ncol=D), mean=rep(0,D), sigma=Sigma )
pi.k <- matrix( 0, nrow=TP, ncol=G )
for (gg in 1:G){
pi.k[,gg] <- cdm_sumnorm( pik )
}
n.ik <- array( 0, dim=c(TP,I,K+1,G) )
#***
# extract number of skills per dimensions
skill.levels <- rep(0,D)
for (dd in 1:D){
skill.levels[dd] <- length( unique(theta.k[,dd] ) )
}
#****
# create thetaDes design matrix for loglinear smoothing
res <- gdm_create_delta_designmatrix( delta.designmatrix=delta.designmatrix,
TP=TP, D=D, theta.k=theta.k, skill.levels=skill.levels, G=G )
delta <- res$delta
covdelta <- res$covdelta
delta.designmatrix <- res$delta.designmatrix
se.a <- 0*a
max.increment.a <- .3
max.increment.b <- 3
if ( standardized.latent ){
mean.constraint <- rbind( mean.constraint, cbind( 1:D, 1, 0 ) )
Sigma.constraint <- rbind( Sigma.constraint, cbind( 1:D, 1:D, 1, 1 ) )
skillspace <- "normal"
}
if ( centered.latent ){
mean.constraint <- rbind( mean.constraint, cbind( 1:D, 1, 0 ) )
skillspace <- "normal"
}
#***
# set constraints for a and b parameters if the maximal
# item category differs from item to item
res <- gdm_constraints_itempars2( b.constraint=b.constraint,
a.constraint=a.constraint, K=K, TD=TD, I=I, dat=dat )
K.item <- res$K.item
a.constraint <- res$a.constraint
b.constraint <- res$b.constraint
#***
# preparations for calc.counts
res <- gdm_prep_calc_counts( K=K, G=G, group=group, weights=weights,
dat.resp=dat.resp, dat.ind=dat.ind, use.freqpatt=use.freqpatt )
ind.group <- res$ind.group
dat.ind2 <- res$dat.ind2
#-- preliminaries PEM acceleration
if (PEM){
envir <- environment()
pem_pars <- c("b","a","pi.k")
if ( skillspace=="est"){
pem_pars <- c(pem_pars, "theta.k")
}
if ( skillspace=="loglinear"){
pem_pars <- c(pem_pars, "delta")
}
pem_output_vars <- unique( c( pem_pars ) )
parmlist <- cdm_pem_inits_assign_parmlist(pem_pars=pem_pars, envir=envir)
res <- cdm_pem_inits( parmlist=parmlist)
pem_parameter_index <- res$pem_parameter_index
pem_parameter_sequence <- res$pem_parameter_sequence
}
deviance.history <- rep(NA, maxiter )
gwt0 <- matrix( 1, nrow=n, ncol=TP )
#---
# initial values algorithm
dev <- 0
iter <- 0
globconv1 <- conv1 <- 1000
disp <- paste( paste( rep(".", 70 ), collapse=""),"\n", sep="")
# timecat <- TRUE
# timecat <- FALSE
############################################
# BEGIN MML Algorithm
############################################
while( ( iter < maxiter ) & ( ( globconv1 > globconv) | ( conv1 > conv) ) ){
z0 <- Sys.time()
#****
# collect old parameters
b0 <- b
a0 <- a
dev0 <- dev
delta0 <- delta
pi.k0 <- pi.k
#****
#1 calculate probabilities
probs <- gdm_calc_prob( a=a, b=b, thetaDes=thetaDes, Qmatrix=Qmatrix,
I=I, K=K, TP=TP, TD=TD )
#*****
#2 calculate individual likelihood
res.hwt <- gdm_calc_posterior( probs=probs, gwt0=gwt0, dat=dat, I=I,
resp.ind.list=resp.ind.list )
p.xi.aj <- res.hwt$hwt
#*****
#3 calculate posterior and marginal distributions
res <- gdm_calc_post( pi.k=pi.k, group=group, p.xi.aj=p.xi.aj, weights=weights, G=G,
ind.group=ind.group, use.freqpatt=use.freqpatt )
p.aj.xi <- res$p.aj.xi
pi.k <- res$pi.k
#*****
#4 calculate expected counts
# n.ik [ 1:TP, 1:I, 1:(K+1), 1:G ]
res <- gdm_calc_counts( G=G, weights=weights, dat.ind=dat.ind, dat=dat, dat.resp=dat.resp,
p.aj.xi=p.aj.xi, K=K, n.ik=n.ik, TP=TP, I=I, group=group, dat.ind2=dat.ind2,
ind.group=ind.group, use.freqpatt=use.freqpatt )
n.ik <- res$n.ik
N.ik <- res$N.ik
#*****
#5 M step: b parameter estimation
# n.ik [1:TP,1:I,1:K,1:G]
# probs[1:I,1:K,1:TP]
res <- gdm_est_b( probs=probs, n.ik=n.ik, N.ik=N.ik, I=I, K=K, G=G, b=b, b.constraint=b.constraint,
max.increment=max.increment.b, a=a, thetaDes=thetaDes, Qmatrix=Qmatrix, TP=TP,
TD=TD, msteps=msteps, convM=convM, centerintercepts=centerintercepts,
decrease.increments=decrease.increments )
b <- res$b
se.b <- res$se.b
max.increment.b <- res$max.increment.b
#*****
#6 M step: a parameter estimation
if ( irtmodel=="2PL"){
res <- gdm_est_a( probs=probs, n.ik=n.ik, N.ik=N.ik, I=I, K=K, G=G, a=a, a.constraint=a.constraint,
TD=TD, Qmatrix=Qmatrix, thetaDes=thetaDes, TP=TP, max.increment=max.increment.a, b=b,
msteps=msteps, convM=convM, centerslopes=centerslopes, decrease.increments=decrease.increments )
a <- res$a
se.a <- res$se.a
max.increment.a <- res$max.increment.a
}
if ( irtmodel=="2PLcat"){
res <- gdm_est_a_cat( probs=probs, n.ik=n.ik, N.ik=N.ik, I=I, K=K, G=G, a=a, a.constraint=a.constraint,
TD=TD, Qmatrix=Qmatrix, thetaDes=thetaDes, TP=TP, max.increment=max.increment.a, b=b, msteps=msteps,
convM=convM, decrease.increments=decrease.increments )
a <- res$a
se.a <- res$se.a
max.increment.a <- res$max.increment.a
}
#*****
#7 M step: estimate reduced skillspace
if ( skillspace=="loglinear" ){
res <- gdm_est_skillspace( Ngroup=Ngroup, pi.k=pi.k, Z=delta.designmatrix, G=G, delta=delta )
pi.k <- res$pi.k
delta <- res$delta
covdelta <- res$covdelta
}
if ( skillspace=="normal" ){
res <- gdm_est_normalskills( pi.k=pi.k, theta.k=theta.k, irtmodel=irtmodel, G=G, D=D,
mean.constraint=mean.constraint, Sigma.constraint=Sigma.constraint,
standardized.latent=standardized.latent, p.aj.xi=p.aj.xi, group=group, ind.group=ind.group,
weights=weights, b=b, a=a )
pi.k <- res$pi.k
b <- res$b
a <- res$a
}
# estimate skillspace
if ( skillspace=="est" ){
res <- gdm_est_skillspace_traits( n.ik=n.ik, a=a, b=b, theta.k=theta.k, Qmatrix=Qmatrix, I=I, K=K, TP=TP, TD=TD,
numdiff.parm=1E-3, max.increment=1, msteps=msteps, convM=convM )
theta.k <- res$theta.k
se.theta.k <- res$se.theta.k
thetaDes <- theta.k
}
#-- PEM acceleration
if (PEM){
#-- collect all parameters in a list
parmlist <- cdm_pem_inits_assign_parmlist(pem_pars=pem_pars, envir=envir)
#-- define log-likelihood function
ll_fct <- gdm_calc_loglikelihood
#- extract parameters
ll_args <- list( irtmodel=irtmodel, skillspace=skillspace, b=b, a=a, centerintercepts=centerintercepts,
centerslopes=centerslopes, TD=TD, Qmatrix=Qmatrix, Ngroup=Ngroup, pi.k=pi.k,
delta.designmatrix=delta.designmatrix, delta=delta, G=G, theta.k=theta.k, D=D,
mean.constraint=mean.constraint, Sigma.constraint=Sigma.constraint,
standardized.latent=standardized.latent, p.aj.xi=p.aj.xi, group=group,
ind.group=ind.group, weights=weights, thetaDes=thetaDes, I=I, K=K, gwt0=gwt0, dat=dat,
resp.ind.list=resp.ind.list, use.freqpatt=use.freqpatt, p.xi.aj=p.xi.aj, TP=TP )
#-- apply general acceleration function
res <- cdm_pem_acceleration( iter=iter, pem_parameter_index=pem_parameter_index,
pem_parameter_sequence=pem_parameter_sequence, pem_pars=pem_pars,
PEM_itermax=PEM_itermax, parmlist=parmlist, ll_fct=ll_fct, ll_args=ll_args,
deviance.history=deviance.history )
#-- collect output
PEM <- res$PEM
pem_parameter_sequence <- res$pem_parameter_sequence
cdm_pem_acceleration_assign_output_parameters( res_ll_fct=res$res_ll_fct,
vars=pem_output_vars, envir=envir, update=res$pem_update )
}
#*****
#8 calculate likelihood
res <- gdm_calc_deviance( G=G, use.freqpatt=use.freqpatt, ind.group=ind.group, p.xi.aj=p.xi.aj,
pi.k=pi.k, weights=weights )
ll <- res$ll
dev <- res$dev
deviance.history[iter+1] <- dev
#~~~~~~~~~~~~~~~~~~~~~~~~~~
# display progress
a_change <- gg0 <- max(abs( a - a0 ))
b_change <- gg1 <- max(abs( b - b0 ))
pardiff <- max( b_change, a_change )
deltadiff <- max( abs( pi.k - pi.k0 ))
conv1 <- max( c(pardiff,deltadiff))
globconv1 <- abs( dev - dev0)
iter <- iter + 1
res <- gdm_progress_em_algorithm( progress=progress, disp=disp, iter=iter, dev=dev, dev0=dev0, b_change=b_change,
a_change=a_change, deltadiff=deltadiff )
}
############################################
# END MML Algorithm
############################################
# collect item parameters
res <- gdm_collect_itempars( data=data, K=K, D=D, b=b, a=a, TD=TD, thetaDes=thetaDes, irtmodel=irtmodel, se.b=se.b,
se.a=se.a, data0=data0 )
item <- res$item
b <- res$b
se.b <- res$se.b
a <- res$a
# calculate distribution properties
res <- gdm_calc_distributionmoments( D=D, G=G, pi.k=pi.k, theta.k=theta.k )
mean.trait <- res$mean.trait
sd.trait <- res$sd.trait
skewness.trait <- res$skewness.trait
correlation.trait <- res$correlation.trait
# Information criteria
ic <- gdm_calc_ic( dev=dev, dat=dat, G=G, skillspace=skillspace, irtmodel=irtmodel, K=K, D=D, TD=TD, I=I,
b.constraint=b.constraint, a.constraint=a.constraint, mean.constraint=mean.constraint,
Sigma.constraint=Sigma.constraint, delta.designmatrix=delta.designmatrix,
standardized.latent=standardized.latent, data0=data0, centerslopes=centerslopes, TP=TP,
centerintercepts=centerintercepts, centered.latent=centered.latent )
#########################################
# item fit [ items, theta, categories ]
# # n.ik [ 1:TP, 1:I, 1:(K+1), 1:G ]
probs <- aperm( probs, c(3,1,2) )
itemfit.rmsea <- itemfit.rmsea( n.ik, pi.k, probs, itemnames=colnames(data) )
item$itemfit.rmsea <- itemfit.rmsea$rmsea
rownames(item) <- NULL
# person parameters
res <- gdm_person_parameters( data=data, D=D, theta.k=theta.k, p.xi.aj=p.xi.aj, p.aj.xi=p.aj.xi, weights=weights )
person <- res$person
EAP.rel <- res$EAP.rel
#*************************
# collect output
s2 <- Sys.time()
res <- list( item=item, person=person, EAP.rel=EAP.rel,
deviance=dev, ic=ic, b=b, se.b=se.b,
a=a, se.a=se.a,
itemfit.rmsea=itemfit.rmsea,
mean.rmsea=mean(itemfit.rmsea$rmsea),
Qmatrix=Qmatrix, pi.k=pi.k,
mean.trait=mean.trait, sd.trait=sd.trait,
skewness.trait=skewness.trait, correlation.trait=correlation.trait,
pjk=probs, n.ik=n.ik, delta.designmatrix=delta.designmatrix,
G=G, D=D, I=ncol(data), N=nrow(data),
delta=delta, covdelta=covdelta, data=data,
group.stat=group.stat )
res$p.xi.aj <- p.xi.aj ; res$posterior <- p.aj.xi
res$skill.levels <- skill.levels
res$K.item <- K.item
res$theta.k <- theta.k
res$thetaDes <- thetaDes
res$se.theta.k <- NULL
res$group <- group
res$time <- list( s1=s1,s2=s2, timediff=s2-s1)
res$skillspace <- skillspace
res$iter <- iter
res$converged <- iter < maxiter
# some further values for modelfit.gdm
res$AIC <- res$ic$AIC
res$BIC <- res$ic$BIC
res$Npars <- res$ic$np
res$loglike <- - res$deviance / 2
res$irtmodel <- irtmodel
res$deviance.history <- deviance.history
# control arguments
res$control$weights <- weights
res$control$group <- group
if (progress){
cat("----------------------------------- \n")
cat("Start:", paste( s1), "\n")
cat("End:", paste(s2), "\n")
cat("Difference:", print(s2 -s1), "\n")
cat("----------------------------------- \n")
}
class(res) <- "gdm"
res$call <- cl
return(res)
}
###################################################
# z0 <- cdm_timecat(z0, label=" *** gdm_calc_prob", timecat)
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdm.R
|
## File Name: gdm_Qmatrix.R
## File Version: 0.05
#################################################
# define Q matrix
gdm_Qmatrix <- function(Qmatrix,irtmodel,I,TD,K,a)
{
# Q matrix [1:I, 1:TD, 1:K]
if ( is.null(Qmatrix) ){
Qmatrix <- array( 1, dim=c(I,TD,K) )
# modify it possibly
if (K>1 & ( irtmodel !="2PLcat" ) ){
for (kk in 2:K){Qmatrix[,,kk] <- kk*Qmatrix[,,1] }
}
if ( irtmodel=="2PLcat"){
for (kk in 2:K ){
a[,,kk] <- kk * a[,,kk]
}
}
}
res <- list(Qmatrix=Qmatrix, a=a)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdm_Qmatrix.R
|
## File Name: gdm_calc_counts.R
## File Version: 0.09
################################################
# calculation of expected counts
gdm_calc_counts <- function(G, weights, dat.ind, dat, dat.resp,
p.aj.xi, K, n.ik, TP,I,group, dat.ind2, ind.group,
use.freqpatt )
{
# n.ik [ 1:TP, 1:I, 1:(K+1), 1:G ]
# N.ik [ 1:TP, 1:I, 1:G ]
N.ik <- array( 0, dim=c(TP,I,G) )
if (G==1){
gg <- 1
for (kk in 1:(K+1)){ # kk <- 1 # category 0 ( -> 1 )
dkk2 <- weights*dat.ind2[[kk]][[gg]]
n.ik[,,kk,gg] <- crossprod( p.aj.xi, dkk2 )
N.ik[,,gg] <- N.ik[,,gg] + n.ik[,,kk,gg]
}
}
if (G>1){
for (gg in 1:G){ # gg <- 1
ind.gg <- ind.group[[gg]]
if ( ! use.freqpatt ){
t.p.aj.xi.gg <- t( p.aj.xi[ind.gg,] )
}
if ( use.freqpatt ){
t.p.aj.xi.gg <- t( p.aj.xi[[gg]] )
}
for (kk in 1:(K+1)){ # kk <- 1 # category 0 ( -> 1 )
dkk2 <- weights[ind.gg] * dat.ind2[[kk]][[gg]]
if ( use.freqpatt ){
if (G>1){
dkk2 <- dkk2[ which(weights[,gg] > 0), ]
}
}
n.ik[,,kk,gg] <- t.p.aj.xi.gg %*% dkk2
N.ik[,,gg] <- N.ik[,,gg] + n.ik[,,kk,gg]
}
}
}
#--- OUTPUT
res <- list("n.ik"=n.ik, "N.ik"=N.ik )
return(res)
}
.gdm.calc.counts <- gdm_calc_counts
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdm_calc_counts.R
|
## File Name: gdm_calc_deviance.R
## File Version: 0.06
gdm_calc_deviance <- function(G, use.freqpatt, ind.group, p.xi.aj, pi.k, weights)
{
# n.ik [ TP, I, K+1, G ]
# N.ik [ TP, I, G ]
# probs [I, K+1, TP ]
ll <- 0
for (gg in 1:G){
if ( ! use.freqpatt ){
ind.gg <- ind.group[[gg]]
ll <- ll + sum( weights[ind.gg] * log( rowSums( p.xi.aj[ind.gg,] *
matrix( pi.k[,gg], nrow=length(ind.gg), ncol=nrow(pi.k), byrow=TRUE ) ) ) )
}
if ( use.freqpatt ){
if (G>1){
wgg <- weights[,gg]
}
if (G==1){
wgg <- weights
}
ll <- ll + sum( wgg * log( rowSums( p.xi.aj * matrix( pi.k[,gg], nrow=nrow(p.xi.aj),
ncol=nrow(pi.k), byrow=TRUE ) ) ) )
}
}
dev <- -2*ll
#--- OUTPUT
res <- list( ll=ll, dev=dev)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/gdm_calc_deviance.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.