content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
"xbarRCC" <-
function (qc.obj, k = 3, sigma, mu, revise = TRUE, newdata)
{
if (revise) {
if (!inherits(qc.obj, "CC")) {
x <- qc.obj
R <- apply(x, 1, diffrange)
n <- length(x[1, ])
xbar <- apply(x, 1, mean)
qc.obj <- list(R = R, xbar = xbar, k = k, n = n,
R.chart.label = "R-chart", x.chart.label = "xbar-chart",
R.ylabel = "R", x.ylabel = "xbar")
class(qc.obj) <- c("CC")
}
if (!missing(sigma)) {
R.par <- RCC(qc.obj$R, qc.obj$n, qc.obj$k, sigma)
}
else {
R.par <- RCC(qc.obj$R, qc.obj$n, qc.obj$k)
}
if (!missing(mu)) {
xbar.par <- xbarCC(qc.obj$xbar[!R.par$ooc], qc.obj$n,
R.par$sigma, qc.obj$k, mu)
}
else {
xbar.par <- xbarCC(qc.obj$xbar[!R.par$ooc], qc.obj$n,
R.par$sigma, qc.obj$k)
}
qc.obj$R.par <- R.par
qc.obj$xbar.par <- xbar.par
}
if (!missing(newdata)) {
if (is.vector(newdata)) {
R.new <- diffrange(newdata)
xbar.new <- mean(newdata)
}
else {
R.new <- apply(newdata, 1, diffrange)
xbar.new <- apply(newdata, 1, mean)
}
qc.obj$R <- c(qc.obj$R, R.new)
qc.obj$xbar <- c(qc.obj$xbar, xbar.new)
}
qc.obj
}
|
/scratch/gouwar.j/cran-all/cranData/CC/R/xbarRCC.R
|
"cc" =
function (X, Y)
{
Xnames = dimnames(X)[[2]]
Ynames = dimnames(Y)[[2]]
ind.names = dimnames(X)[[1]]
res = rcc(X, Y, 0, 0)
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/cc.R
|
"comput" =
function (X, Y, res)
{
X.aux = scale(X, center=TRUE, scale=FALSE)
Y.aux = scale(Y, center=TRUE, scale=FALSE)
X.aux[is.na(X.aux)] = 0
Y.aux[is.na(Y.aux)] = 0
xscores = X.aux%*%res$xcoef
yscores = Y.aux%*%res$ycoef
corr.X.xscores = cor(X, xscores, use = "pairwise")
corr.Y.xscores = cor(Y, xscores, use = "pairwise")
corr.X.yscores = cor(X, yscores, use = "pairwise")
corr.Y.yscores = cor(Y, yscores, use = "pairwise")
return(list(xscores = xscores, yscores = yscores,
corr.X.xscores = corr.X.xscores,
corr.Y.xscores = corr.Y.xscores,
corr.X.yscores = corr.X.yscores,
corr.Y.yscores = corr.Y.yscores))
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/comput.R
|
"estim.regul" <-
function (X, Y, grid1 = NULL, grid2 = NULL, plt = TRUE)
{
if (is.null(grid1)) {grid1 = seq(0.001, 1, length = 5)}
if (is.null(grid2)) {grid2 = seq(0.001, 1, length = 5)}
grid = expand.grid(grid1, grid2)
res = apply(grid, 1, function(x) {loo(X, Y, x[1], x[2])})
res.grid = cbind(grid, res)
mat = matrix(res, ncol = length(grid2))
if (isTRUE(plt)) {
img.estim.regul(list(grid1 = grid1, grid2 = grid2, mat = mat))
}
opt = res.grid[res.grid[, 3] == max(res.grid[, 3]), ]
cat(" lambda1 = ", opt[[1]], "\n", " lambda2 = ", opt[[2]], "\n",
"CV-score = ", opt[[3]], "\n")
return(invisible(list(lambda1 = opt[[1]], lambda2 = opt[[2]],
CVscore = opt[[3]], grid1 = grid1, grid2 = grid2, mat = mat)))
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/estim.regul.R
|
"img.estim.regul" <-
function (estim)
{
grid1 = estim$grid1
grid2 = estim$grid2
mat = estim$mat
nlevel = min(512, length(c(unique(mat))))
par(mar = c(4.5, 4.5, 4.5, 6))
image(grid1, grid2, mat, col = heat.colors(nlevel),
xlab = expression(lambda[1]), ylab=expression(lambda[2]),
main = expression(CV(lambda[1], lambda[2])), axes = FALSE,
zlim = c(min(mat), max(mat)), oldstyle = TRUE)
if (length(grid1) > 10) {
grid1 = seq(min(grid1), max(grid1), length = 11)
}
if (length(grid2) > 10) {
grid2 = seq(min(grid2), max(grid2), length = 11)
}
axis(1, at = grid1, labels = as.character(round(grid1, 4)))
axis(2, at = grid2, labels = as.character(round(grid2, 4)))
box()
image.plot(legend.only = TRUE, nlevel = nlevel,
zlim = c(min(mat), max(mat)), col = heat.colors(nlevel),
legend.width = 1.8)
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/img.estim.regul.R
|
"img.matcor" <-
function (correl, type = 1)
{
matcorX = correl$Xcor
matcorY = correl$Ycor
matcorXY = correl$XYcor
lX = ncol(matcorX)
lY = ncol(matcorY)
def.par <- par(no.readonly = TRUE)
if (type == 1) {
par(mfrow = c(1, 1), pty = "s")
image(1:(lX + lY), 1:(lX + lY), t(matcorXY[nrow(matcorXY):1, ]),
zlim = c(-1, 1), main = "XY correlation",
col = tim.colors(64),
axes = FALSE, , xlab = "", ylab = "")
box()
abline(h = lY + 0.5, v = lX + 0.5, lwd = 2, lty = 2)
image.plot(legend.only = TRUE, zlim = c(-1, 1),
col = tim.colors(64), horizontal = TRUE)
}
else {
layout(matrix(c(1, 2, 3, 3, 0, 0), ncol = 2, nrow = 3,
byrow = TRUE), widths = 1, heights = c(0.8, 1, 0.06))
#layout 1
par(pty = "s", mar = c(2, 2, 2, 1))
image(1:lX, 1:lX, t(matcorX[lX:1, ]), zlim = c(-1, 1),
main = "X correlation", axes = FALSE, xlab = "", ylab = "",
col = tim.colors(64))
box()
image(1:lY, 1:lY, t(matcorY[lY:1, ]), zlim = c(-1, 1),
main = "Y correlation",
col = tim.colors(64), axes = FALSE,
xlab = "", ylab = "")
box()
#layout 2
partXY = matcorXY[lX:1, (lX + 1):(lX + lY)]
if (lX > lY) {
partXY = matcorXY[(lX + lY):(lX + 1), 1:lX]
lX = ncol(matcorY)
lY = ncol(matcorX)
}
par(pty = "m", mar = c(5,4,2,3), mai = c(0.8, 0.5, 0.3, 0.4))
image(1:lY, 1:lX, t(partXY), zlim = c(-1, 1),
main = "Cross-correlation", axes = FALSE, xlab = "",
ylab = "", col = tim.colors(64))
box()
image.plot(legend.only = TRUE, zlim = c(-1, 1),
horizontal = TRUE, col = tim.colors(64),
legend.width = 2.5)
}
par(def.par)
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/img.matcor.R
|
"loo" =
function (X, Y, lambda1, lambda2)
{
n = nrow(X)
xscore = vector(mode = "numeric", length = n)
yscore = vector(mode = "numeric", length = n)
for (i in 1:n) {
Xcv = X[-i, ]
Ycv = Y[-i, ]
res = rcc(Xcv, Ycv, lambda1, lambda2)
xscore[i] = t(X[i, ]) %*% res$xcoef[, 1]
yscore[i] = t(Y[i, ]) %*% res$ycoef[, 1]
}
cv = cor(xscore, yscore, use = "pairwise")
return(invisible(cv))
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/loo.R
|
"matcor" <-
function (X, Y)
{
matcorX = cor(X, use = "pairwise")
matcorY = cor(Y, use = "pairwise")
matcorXY = cor(cbind(X, Y), use = "pairwise")
return(list(Xcor = matcorX, Ycor = matcorY, XYcor = matcorXY))
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/matcor.R
|
"plt.cc" <-
function (res, d1 = 1, d2 = 2, int = 0.5, type = "b", ind.names=NULL, var.label=FALSE, Xnames=NULL, Ynames=NULL)
{
par(mfrow = c(1, 1), pty = "s")
if (type == "v")
plt.var(res, d1, d2, int, var.label, Xnames, Ynames)
if (type == "i")
plt.indiv(res, d1, d2, ind.names)
if (type == "b") {
def.par <- par(no.readonly = TRUE)
layout(matrix(c(0, 0, 1, 2, 0, 0), ncol = 2, nrow = 3,
byrow = TRUE), widths = 1, heights = c(0.1, 1, 0.1))
par(pty = "s", mar = c(4, 4.5, 0, 1))
plt.var(res, d1, d2, int, var.label, Xnames, Ynames)
plt.indiv(res, d1, d2, ind.names)
par(def.par)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/plt.cc.R
|
"plt.indiv" <-
function (res, d1, d2, ind.names = NULL)
{
if (is.null(ind.names)) ind.names = res$names$ind.names
if (is.null(ind.names)) ind.names = 1:nrow(res$scores$xscores)
plot(res$scores$xscores[, d1], res$scores$xscores[, d2],
type = "n", main = "", xlab = paste("Dimension ", d1),
ylab = paste("Dimension ", d2))
text(res$scores$xscores[, d1], res$scores$xscores[, d2],
ind.names)
abline(v = 0, h = 0, lty=2)
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/plt.indiv.R
|
"plt.var" =
function (res, d1, d2, int = 0.5, var.label = FALSE,
Xnames = NULL, Ynames = NULL)
{
if (!var.label) {
plot(0, type = "n", xlim = c(-1, 1), ylim = c(-1, 1),
xlab = paste("Dimension ", d1), ylab = paste("Dimension ", d2))
points(res$scores$corr.X.xscores[, d1],
res$scores$corr.X.xscores[, d2],
pch = 20, cex = 1.2, col = "red")
points(res$scores$corr.Y.xscores[, d1],
res$scores$corr.Y.xscores[, d2],
pch = 24, cex = 0.7, col = "blue")
}
else {
if (is.null(Xnames)) Xnames = res$names$Xnames
if (is.null(Ynames)) Ynames = res$names$Ynames
plot(0, type = "n", xlim = c(-1, 1), ylim = c(-1, 1),
xlab = paste("Dimension ", d1), ylab = paste("Dimension ", d2))
text(res$scores$corr.X.xscores[, d1],
res$scores$corr.X.xscores[, d2],
Xnames, col = "red", font = 2)
text(res$scores$corr.Y.xscores[, d1],
res$scores$corr.Y.xscores[, d2],
Ynames, col = "blue", font = 3)
}
abline(v = 0, h = 0)
lines(cos(seq(0, 2 * pi, l = 100)), sin(seq(0, 2 * pi, l = 100)))
lines(int * cos(seq(0, 2 * pi, l = 100)),
int * sin(seq(0, 2 * pi, l = 100)))
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/plt.var.R
|
"rcc" <-
function (X, Y, lambda1, lambda2)
{
Xnames <- dimnames(X)[[2]]
Ynames <- dimnames(Y)[[2]]
ind.names <- dimnames(X)[[1]]
Cxx <- var(X, na.rm = TRUE, use = "pairwise") + diag(lambda1,
ncol(X))
Cyy <- var(Y, na.rm = TRUE, use = "pairwise") + diag(lambda2,
ncol(Y))
Cxy <- cov(X, Y, use = "pairwise")
res <- geigen(Cxy, Cxx, Cyy)
names(res) <- c("cor", "xcoef", "ycoef")
scores <- comput(X, Y, res)
return(list(cor = res$cor, names = list(Xnames = Xnames,
Ynames = Ynames, ind.names = ind.names), xcoef = res$xcoef,
ycoef = res$ycoef, scores = scores))
}
|
/scratch/gouwar.j/cran-all/cranData/CCA/R/rcc.R
|
utils::globalVariables(c('CCAMLRp','Coast','Depth_cols','Depth_cuts','Depth_cols2','Depth_cuts2',
'GridData','Labels','LineData','PointData','PolyData','ID','PieData','PieData2',
'Lat','Lon','N','Tot','p','Ass_Ar_Key','Min','Max','Iso','AreaKm2','Latitude','Longitude','Pwidth'))
#'
#' Loads and creates spatial data, including layers and tools that are relevant to CCAMLR activities.
#' All operations use the Lambert azimuthal equal-area projection (via EPSG:6932).
#'
#' This package provides two broad categories of functions: load functions and create functions.
#'
#' @section Load functions:
#' Load functions are used to import CCAMLR geo-referenced layers and include:
#' \itemize{
#' \item \link{load_ASDs}
#' \item \link{load_SSRUs}
#' \item \link{load_RBs}
#' \item \link{load_SSMUs}
#' \item \link{load_MAs}
#' \item \link{load_Coastline}
#' \item \link{load_MPAs}
#' \item \link{load_EEZs}
#' \item \link{load_Bathy}
#' }
#'
#' @section Create functions:
#' Create functions are used to create geo-referenced layers from user-generated data and include:
#' \itemize{
#' \item \link{create_Points}
#' \item \link{create_Lines}
#' \item \link{create_Polys}
#' \item \link{create_PolyGrids}
#' \item \link{create_Stations}
#' \item \link{create_Pies}
#' \item \link{create_Arrow}
#' }
#'
#' @section Vignette:
#' To learn more about CCAMLRGIS, start with the GitHub ReadMe (see \url{https://github.com/ccamlr/CCAMLRGIS#table-of-contents}).
#' Some basemaps are given here \url{https://github.com/ccamlr/CCAMLRGIS/blob/master/Basemaps/Basemaps.md}
#'
#' @seealso
#' The CCAMLRGIS package relies on several other package which users may want to familiarize themselves with,
#' namely sf (\url{https://CRAN.R-project.org/package=sf}) and
#' terra (\url{https://CRAN.R-project.org/package=terra}).
#'
#'
#' @keywords internal
"_PACKAGE"
## usethis namespace: start
#' @import sf
#' @importFrom dplyr distinct filter group_by left_join select summarise summarise_all
#' @importFrom grDevices colorRampPalette recordPlot replayPlot chull col2rgb rgb
#' @importFrom graphics abline legend lines par plot rect segments text
#' @importFrom stats median quantile sd
#' @importFrom terra as.polygons clamp classify click crop expanse ext extend extract mask plot project rast vect
#' @importFrom utils download.file edit globalVariables menu read.csv setTxtProgressBar txtProgressBar
#' @importFrom magrittr %>%
#' @importFrom stars st_as_stars st_contour
#' @importFrom bezier bezier
#' @importFrom lwgeom st_transform_proj
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/CCAMLRGIS-package.R
|
#' CCAMLRGIS Projection
#'
#' The CCAMLRGIS package uses the Lambert azimuthal equal-area projection (see \url{https://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection}).
#' Source: \url{http://gis.ccamlr.org/}.
#' In order to align with recent developments within Geographic Information Software, this projection
#' will be accessed via EPSG code 6932 (see \url{https://epsg.org/crs_6932/WGS-84-NSIDC-EASE-Grid-2-0-South.html}).
#'
#' @docType data
#' @usage data(CCAMLRp)
#' @format character string
#' @return "+proj=laea +lat_0=-90 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
#' @name CCAMLRp
NULL
#' Simplified and subsettable coastline
#'
#' Coastline polygons generated from \link{load_Coastline} and sub-sampled to only contain data that falls
#' within the boundaries of the Convention Area. This spatial object may be subsetted to plot the coastline for selected
#' ASDs or EEZs (see examples). Source: \url{http://gis.ccamlr.org/}
#'
#' @docType data
#' @usage data(Coast)
#' @format sf
#' @examples
#' #Complete coastline:
#' plot(st_geometry(Coast[Coast$ID=='All',]),col='grey')
#'
#' #ASD 48.1 coastline:
#' plot(st_geometry(Coast[Coast$ID=='48.1',]),col='grey')
#' @seealso \code{\link{Clip2Coast}}, \code{\link{load_Coastline}}.
#' @name Coast
NULL
#' Bathymetry colors
#'
#' Set of standard colors to plot bathymetry, to be used in conjunction with \link{Depth_cuts}.
#'
#' @docType data
#' @usage data(Depth_cols)
#' @format character vector
#' @examples terra::plot(SmallBathy(),breaks=Depth_cuts,col=Depth_cols,axes=FALSE)
#' @seealso \code{\link{Depth_cols2}}, \code{\link{add_col}}, \code{\link{add_Cscale}}, \code{\link{SmallBathy}}.
#' @name Depth_cols
NULL
#' Bathymetry depth classes
#'
#' Set of depth classes to plot bathymetry, to be used in conjunction with \link{Depth_cols}.
#'
#' @docType data
#' @usage data(Depth_cuts)
#' @format numeric vector
#' @examples terra::plot(SmallBathy(),breaks=Depth_cuts,col=Depth_cols,axes=FALSE,box=FALSE)
#' @seealso \code{\link{Depth_cuts2}}, \code{\link{add_col}}, \code{\link{add_Cscale}}, \code{\link{SmallBathy}}.
#' @name Depth_cuts
NULL
#' Bathymetry colors with Fishable Depth range
#'
#' Set of colors to plot bathymetry and highlight Fishable Depth range (600-1800), to be used in conjunction with \link{Depth_cuts2}.
#'
#' @docType data
#' @usage data(Depth_cols2)
#' @format character vector
#' @examples terra::plot(SmallBathy(),breaks=Depth_cuts2,col=Depth_cols2,axes=FALSE,box=FALSE)
#' @seealso \code{\link{Depth_cols}}, \code{\link{add_col}}, \code{\link{add_Cscale}}, \code{\link{SmallBathy}}.
#' @name Depth_cols2
NULL
#' Bathymetry depth classes with Fishable Depth range
#'
#' Set of depth classes to plot bathymetry and highlight Fishable Depth range (600-1800), to be used in conjunction with \link{Depth_cols2}.
#'
#' @docType data
#' @usage data(Depth_cuts2)
#' @format numeric vector
#' @examples terra::plot(SmallBathy(),breaks=Depth_cuts2,col=Depth_cols2,axes=FALSE,box=FALSE)
#' @seealso \code{\link{Depth_cuts}}, \code{\link{add_col}}, \code{\link{add_Cscale}}, \code{\link{SmallBathy}}.
#' @name Depth_cuts2
NULL
#' Example dataset for create_PolyGrids
#'
#' To be used in conjunction with \link{create_PolyGrids}.
#'
#' @docType data
#' @usage data(GridData)
#' @format data.frame
#' @examples
#' #View(GridData)
#'
#' MyGrid=create_PolyGrids(Input=GridData,dlon=2,dlat=1)
#' plot(st_geometry(MyGrid),col=MyGrid$Col_Catch_sum)
#' @seealso \code{\link{create_PolyGrids}}.
#' @name GridData
NULL
#' Example dataset for create_Lines
#'
#' To be used in conjunction with \link{create_Lines}.
#'
#' @docType data
#' @usage data(LineData)
#' @format data.frame
#' @examples
#' #View(LineData)
#'
#' MyLines=create_Lines(LineData)
#' plot(st_geometry(MyLines),lwd=2,col=rainbow(5))
#' @seealso \code{\link{create_Lines}}.
#' @name LineData
NULL
#' Example dataset for create_Points
#'
#' To be used in conjunction with \link{create_Points}.
#'
#' @docType data
#' @usage data(PointData)
#' @format data.frame
#' @examples
#' #View(PointData)
#'
#' MyPoints=create_Points(PointData)
#' plot(st_geometry(MyPoints))
#' text(MyPoints$x,MyPoints$y,MyPoints$name,adj=c(0.5,-0.5),xpd=TRUE)
#' plot(st_geometry(MyPoints[MyPoints$name=='four',]),bg='red',pch=21,cex=1.5,add=TRUE)
#' @seealso \code{\link{create_Points}}.
#' @name PointData
NULL
#' Example dataset for create_Polys
#'
#' To be used in conjunction with \link{create_Polys}.
#'
#' @docType data
#' @usage data(PolyData)
#' @format data.frame
#' @examples
#' #View(PolyData)
#'
#' MyPolys=create_Polys(PolyData,Densify=TRUE)
#' plot(st_geometry(MyPolys),col='green')
#' text(MyPolys$Labx,MyPolys$Laby,MyPolys$ID)
#' plot(st_geometry(MyPolys[MyPolys$ID=='three',]),border='red',lwd=3,add=TRUE)
#' @seealso \code{\link{create_Polys}}.
#' @name PolyData
NULL
#' Polygon labels
#'
#' Labels for the layers obtained via 'load_' functions. Positions correspond to the centroids
#' of polygon parts. Can be used in conjunction with \code{\link{add_labels}}.
#'
#' @docType data
#' @usage data(Labels)
#' @format data.frame
#' @examples
#' \donttest{
#'
#'
#' #View(Labels)
#'
#' ASDs=load_ASDs()
#' plot(st_geometry(ASDs))
#' add_labels(mode='auto',layer='ASDs',fontsize=1,fonttype=2)
#'
#'
#' }
#'
#' @seealso \code{\link{add_labels}}, \code{\link{load_ASDs}}, \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}}, \code{\link{load_EEZs}},
#' \code{\link{load_MPAs}}.
#' @name Labels
NULL
#' Example dataset for create_Pies
#'
#' To be used in conjunction with \link{create_Pies}. Count and catch of species per location.
#'
#' @docType data
#' @usage data(PieData)
#' @format data.frame
#' @examples
#' #View(PieData)
#'
#' #Create pies
#' MyPies=create_Pies(Input=PieData,
#' NamesIn=c("Lat","Lon","Sp","N"),
#' Size=50
#' )
#' #Plot Pies
#' plot(st_geometry(MyPies),col=MyPies$col)
#' #Add Pies legend
#' add_PieLegend(Pies=MyPies,PosX=-0.1,PosY=-1.6,Boxexp=c(0.5,0.45,0.12,0.45),
#' PieTitle="Species")
#'
#' @seealso \code{\link{create_Pies}}.
#' @name PieData
NULL
#' Example dataset for create_Pies
#'
#' To be used in conjunction with \link{create_Pies}. Count and catch of species per location.
#'
#' @docType data
#' @usage data(PieData2)
#' @format data.frame
#' @examples
#' #View(PieData2)
#'
#'MyPies=create_Pies(Input=PieData2,
#' NamesIn=c("Lat","Lon","Sp","N"),
#' Size=5,
#' GridKm=250
#')
#'#Plot Pies
#'plot(st_geometry(MyPies),col=MyPies$col)
#'#Add Pies legend
#'add_PieLegend(Pies=MyPies,PosX=-0.8,PosY=-0.3,Boxexp=c(0.5,0.45,0.12,0.45),
#' PieTitle="Species")
#'
#' @seealso \code{\link{create_Pies}}.
#' @name PieData2
NULL
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/CCAMLRGIS_DataDescription.R
|
#' Clip Polygons to a simplified Antarctic coastline
#'
#' Clip Polygons to the \link{Coast} (removes polygon parts that fall on land) and computes the area of the resulting polygon.
#' Uses an sf object as input which may be user-generated or created via buffered points (see \link{create_Points}),
#' buffered lines (see \link{create_Lines}) or polygons (see \link{create_Polys}). N.B.: this function uses a
#' simplified coastline. For more accurate results, load the high resolution coastline (see \link{load_Coastline}), and
#' use sf::st_difference().
#'
#' @param Input sf polygon(s) to be clipped.
#'
#' @examples
#'
#' MyPolys=create_Polys(PolyData,Densify=TRUE,Buffer=c(10,-15,120))
#' plot(st_geometry(MyPolys),col='red')
#' plot(st_geometry(Coast[Coast$ID=='All',]),add=TRUE)
#' MyPolysClipped=Clip2Coast(MyPolys)
#' plot(st_geometry(MyPolysClipped),col='blue',add=TRUE)
#' #View(MyPolysClipped)
#'
#'
#' @seealso
#' \link{Coast}, \code{\link{create_Points}}, \code{\link{create_Lines}}, \code{\link{create_Polys}},
#' \code{\link{create_PolyGrids}}.
#'
#' @return sf polygon carrying the same data as the \code{Input}.
#' @export
Clip2Coast=function(Input){
Output=suppressWarnings(st_difference(Input,Coast[Coast$ID=='All',],validate=TRUE))
#Get areas
Ar=round(st_area(Output)/1000000,1)
if("Buffered_AreaKm2"%in%colnames(Output)){
Output$Buffered_and_clipped_AreaKm2=as.numeric(Ar)
}
if("AreaKm2"%in%colnames(Output)){
Output$Clipped_AreaKm2=as.numeric(Ar)
}
return(Output)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/Clip2Coast.R
|
DensifyData=function(Lon,Lat){
dlon=0.1
GridLon=seq(0,360,by=dlon)
Lon=Lon+180
DenLon=NULL
DenLat=NULL
for (di in (1:(length(Lon)-1))){
if(abs(diff(Lon[c(di,di+1)]))<=dlon){ #No need to densify
DenLon=c(DenLon,c(Lon[di],Lon[di+1]))
DenLat=c(DenLat,c(Lat[di],Lat[di+1]))
}else{ #Need to densify
alpha=((Lon[di+1]-Lon[di])+180)%%360-180 #Angle
if (abs(alpha)==180){warning("A line is exactly 180 degrees wide in longitude","\n",
"Please add an intermediate point in the line","\n")}
if (alpha>0){ #Clockwise
if (length(which(GridLon>Lon[di] & GridLon<Lon[di+1]))>0){ #Continuous
GridLoc=GridLon[(which(GridLon>Lon[di] & GridLon<Lon[di+1]))]
}else{ #Crossing the Antimeridian
GridLoc=c(GridLon[which(GridLon>Lon[di])],GridLon[which(GridLon<Lon[di+1])])
}
}
if (alpha<0){ #Counterclockwise
if (length(which(GridLon<Lon[di] & GridLon>Lon[di+1]))>0){ #Continuous
GridLoc=GridLon[rev(which(GridLon<Lon[di] & GridLon>Lon[di+1]))]
}else{ #Crossing the Antimeridian
GridLoc=c(GridLon[rev(which(GridLon<Lon[di]))],GridLon[rev(which(GridLon>Lon[di+1]))])
}
}
if (Lat[di+1]==Lat[di]){ #Isolatitude
DenLon=c(DenLon,c(Lon[di],GridLoc,Lon[di+1]))
DenLat=c(DenLat,c(Lat[di],rep(Lat[di],length(GridLoc)),Lat[di+1]))
}else{ #GetCInt
if(all(c(360,0)%in%GridLoc)==F){ #Without crossing the Antimeridian
Out=NULL
for(Dl in seq(1,length(GridLoc))){
Out=rbind(Out,
suppressWarnings( get_C_intersection(Line1=c(Lon[di],Lat[di],Lon[di+1],Lat[di+1]),
Line2=c(GridLoc[Dl],Lat[di],GridLoc[Dl],Lat[di+1]),
Plot=F) )
)
}
}else{ #If Antimeridian is crossed
if(which(GridLoc==360)<which(GridLoc==0)){ #Clockwise
TmpInt=get_C_intersection(Line1=c(Lon[di]-180,Lat[di],Lon[di+1]+180,Lat[di+1]),
Line2=c(180,Lat[di],180,Lat[di+1]),
Plot=F)
TmpInt=TmpInt[2] #Latitude of crossing
#Then split GridLoc at crossing and get intersections for each piece
GridLoc1=GridLoc[1:which(GridLoc==360)]
GridLoc2=GridLoc[which(GridLoc==0):length(GridLoc)]
Out=NULL
for(Dl in seq(1,length(GridLoc1))){
Out=rbind(Out,
suppressWarnings( get_C_intersection(Line1=c(Lon[di],Lat[di],360,TmpInt),
Line2=c(GridLoc1[Dl],Lat[di],GridLoc1[Dl],Lat[di+1]),
Plot=F) )
)
}
for(Dl in seq(1,length(GridLoc2))){
Out=rbind(Out,
suppressWarnings( get_C_intersection(Line1=c(0,TmpInt,Lon[di+1],Lat[di+1]),
Line2=c(GridLoc2[Dl],Lat[di],GridLoc2[Dl],Lat[di+1]),
Plot=F) )
)
}
}else{ #Counterclockwise
TmpInt=get_C_intersection(Line1=c(Lon[di]+180,Lat[di],Lon[di+1]-180,Lat[di+1]),
Line2=c(180,Lat[di],180,Lat[di+1]),
Plot=F)
TmpInt=TmpInt[2] #Latitude of crossing
#Then split GridLoc at crossing and get intersections for each piece
GridLoc1=GridLoc[1:which(GridLoc==0)]
GridLoc2=GridLoc[which(GridLoc==360):length(GridLoc)]
Out=NULL
for(Dl in seq(1,length(GridLoc1))){
Out=rbind(Out,
suppressWarnings( get_C_intersection(Line1=c(Lon[di],Lat[di],0,TmpInt),
Line2=c(GridLoc1[Dl],Lat[di],GridLoc1[Dl],Lat[di+1]),
Plot=F) )
)
}
for(Dl in seq(1,length(GridLoc2))){
Out=rbind(Out,
suppressWarnings( get_C_intersection(Line1=c(360,TmpInt,Lon[di+1],Lat[di+1]),
Line2=c(GridLoc2[Dl],Lat[di],GridLoc2[Dl],Lat[di+1]),
Plot=F) )
)
}
}
}
DenLon=c(DenLon,c(Lon[di],Out[,1],Lon[di+1]))
DenLat=c(DenLat,c(Lat[di],Out[,2],Lat[di+1]))
}
}
}
DenLon=DenLon-180
Densified=cbind(DenLon,DenLat)
return(Densified)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/DensifyData.R
|
GetPerp=function(Input,d=Pwidth){
x=NULL
y=NULL
#First get Perp for first point
m=(Input$y[1]-Input$y[2])/(Input$x[1]-Input$x[2])
if(m==0){m=1e-12}
x_1=Input$x[1]+sqrt(d^2/(1+(1/m^2)))
y_1=Input$y[1]-(1/m)*(x_1-Input$x[1])
x_2=Input$x[1]-sqrt(d^2/(1+(1/m^2)))
y_2=Input$y[1]-(1/m)*(x_2-Input$x[1])
x=c(x,x_1,x_2)
y=c(y,y_1,y_2)
#Then loop over other points
for(i in seq(2,nrow(Input))){
m=(Input$y[i]-Input$y[i-1])/(Input$x[i]-Input$x[i-1])
if(m==0){m=1e-12}
x_1=Input$x[i]+sqrt(d^2/(1+(1/m^2)))
y_1=Input$y[i]-(1/m)*(x_1-Input$x[i])
x_2=Input$x[i]-sqrt(d^2/(1+(1/m^2)))
y_2=Input$y[i]-(1/m)*(x_2-Input$x[i])
x=c(x,x_1,x_2)
y=c(y,y_1,y_2)
}
return(data.frame(x=x,y=y))
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/GetPerp.R
|
#' Create Pies
#'
#' Generates pie charts that can be overlaid on maps. The \code{Input} data must be a dataframe with, at least,
#' columns for latitude, longitude, class and value. For each location, a pie is created with pieces for each class,
#' and the size of each piece depends on the proportion of each class (the value of each class divided by the sum of values).
#' Optionally, the area of each pie can be proportional to a chosen variable (if that variable is different than the
#' value mentioned above, the \code{Input} data must have a fifth column and that variable must be unique to each location).
#' If the \code{Input} data contains locations that are too close together, the data can be gridded by setting \code{GridKm}.
#' Once pie charts have been created, the function \link{add_PieLegend} may be used to add a legend to the figure.
#'
#' @param Input input dataframe.
#'
#' @param NamesIn character vector of length 4 specifying the column names of Latitude, Longitude,
#' Class and value fields in the \code{Input}.
#'
#' Names must be given in that order, e.g.:
#'
#' \code{NamesIn=c('Latitude','Longitude','Class','Value')}.
#'
#' @param Classes character, optional vector of classes to be displayed. If this excludes classes that are in the \code{Input},
#' those excluded classes will be pooled in a 'Other' class.
#'
#' @param cols character, vector of two or more color names to colorize pie pieces.
#'
#' @param Size numeric, value controlling the size of pies.
#'
#' @param SizeVar numeric, optional, name of the field in the \code{Input} that should be used to scale the area of pies.
#' Must be unique to locations in the input.
#'
#' @param GridKm numeric, optional, cell size of the grid in kilometers. If provided, locations are pooled by grid
#' cell and values are summed for each class.
#'
#' @param Other numeric, optional, percentage threshold below which classes are pooled in a 'Other' class.
#'
#' @param Othercol character, optional, color of the pie piece for the 'Other' class.
#'
#' @return Spatial object in your environment, ready to be plotted.
#'
#' @seealso
#' \code{\link{add_PieLegend}}, \code{\link{PieData}}, \code{\link{PieData2}}.
#'
#' @examples
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#23-create-pies
#'
#' #Pies of constant size, all classes displayed:
#' #Create pies
#' MyPies=create_Pies(Input=PieData,NamesIn=c("Lat","Lon","Sp","N"),Size=50)
#' #Plot Pies
#' plot(st_geometry(MyPies),col=MyPies$col)
#' #Add Pies legend
#' add_PieLegend(Pies=MyPies,PosX=-0.1,PosY=-1,Boxexp=c(0.5,0.45,0.12,0.45),
#' PieTitle="Species")
#'
#'
#'
#' @export
create_Pies=function(Input,NamesIn=NULL,Classes=NULL,cols=c("green","red"),Size=50,SizeVar=NULL,GridKm=NULL,Other=0,Othercol="grey"){
Input = as.data.frame(Input)
if (is.null(NamesIn) == FALSE) {
if (length(NamesIn) != 4) {
stop("'NamesIn' should be a character vector of length 4")
}
if (any(NamesIn %in% colnames(Input) == FALSE)) {
stop("'NamesIn' do not match column names in 'Input'")
}
}else{
stop("'NamesIn' not specified")
}
if(is.null(SizeVar)==FALSE){
if(SizeVar%in%colnames(Input)==FALSE){
stop("'SizeVar' does not match any column name in 'Input'")
}else{
NamesIn=unique(c(NamesIn,SizeVar))
}
}
D=Input[,NamesIn]
if(length(NamesIn)==4){
colnames(D)=c("Lat","Lon","Cl","N")
}else{
colnames(D)=c("Lat","Lon","Cl","N","SizeVar")
Chck=dplyr::summarise(group_by(D,Lat,Lon),
n=length(unique(SizeVar)),
Svar=unique(SizeVar)[1],.groups = 'drop')
if(max(Chck$n)!=1){
stop("Some location(s) have more than one 'SizeVar'")
}
}
if(is.null(Classes)==TRUE){
Classes=sort(unique(D$Cl))
}else{
ClassesInData=sort(unique(D$Cl))
if(all(ClassesInData%in%Classes)==FALSE){ #Chosen classes are excluding 1 or more classes that are in the data
ExclCl=ClassesInData[!ClassesInData%in%Classes] #Classes to exclude
D$Cl[D$Cl%in%ExclCl]="Other"
}
}
if(is.null(GridKm)==FALSE){
Gr=GridKm*1000
Locs=project_data(D,NamesIn = c("Lat","Lon"),append = TRUE)
#X
Cl=seq(Gr*floor((min(Locs$X)-Gr)/Gr),Gr*ceiling((max(Locs$X)+Gr)/Gr),by=Gr)
Locs$Xc=Cl[cut(Locs$X,Cl,include.lowest=TRUE,right=FALSE)]+Gr/2
#Y
Cl=seq(Gr*floor((min(Locs$Y)-Gr)/Gr),Gr*ceiling((max(Locs$Y)+Gr)/Gr),by=Gr)
Locs$Yc=Cl[cut(Locs$Y,Cl,include.lowest=TRUE,right=FALSE)]+Gr/2
Locs=project_data(Locs,NamesIn = c("Yc","Xc"),inv=TRUE)
D$Lat=Locs$Latitude
D$Lon=Locs$Longitude
if(ncol(D)==4){
D=dplyr::summarise(group_by(D,Lat,Lon,Cl),N=sum(N,na.rm=TRUE),.groups = 'drop')
D=as.data.frame(D)
}
if(ncol(D)==5){
#Append gridded Lat/Lon to Chck (contains SizeVar per unique locations)
Locs=Locs%>%dplyr::select(Lat,Lon,Latitude,Longitude)%>%distinct()
Chck=dplyr::left_join(Chck,Locs,by = c("Lat", "Lon"))
#Summarize per location
D=dplyr::summarise(group_by(D,Lat,Lon,Cl),N=sum(N,na.rm=TRUE),.groups = 'drop')
Svar=dplyr::summarise(group_by(Chck,Lat=Latitude,Lon=Longitude),SizeVar=sum(Svar,na.rm = TRUE),.groups = 'drop')
D=dplyr::left_join(D,Svar,by = c("Lat", "Lon"))
D=as.data.frame(D)
}
}
#Compute sum(N) and append to D
C=dplyr::summarise(group_by(D,Lat,Lon),Tot=sum(N,na.rm=TRUE),.groups = 'drop')
C$ID=seq(1,nrow(C))
D=dplyr::left_join(D,C, by = c("Lat", "Lon"))
if(is.null(SizeVar)==FALSE){
if(SizeVar==NamesIn[4]){
D$SizeVar=D$Tot
}
}
#Compute proportions
D$p=D$N/D$Tot
if(Other>0){
D$Cl[100*D$p<Other]="Other"
}
#Re-group if some Cl have become 'Other'
if(is.null(SizeVar)==FALSE){
D=dplyr::summarise(group_by(D,ID,Lat,Lon,Cl),
N=sum(N,na.rm=TRUE),SizeVar=unique(SizeVar),
Tot=unique(Tot),p=sum(p,na.rm=TRUE),.groups = 'drop')
}else{
D=dplyr::summarise(group_by(D,ID,Lat,Lon,Cl),
N=sum(N,na.rm=TRUE),
Tot=unique(Tot),p=sum(p,na.rm=TRUE),.groups = 'drop')
}
D=as.data.frame(D)
pal=colorRampPalette(cols)
cols=pal(length(Classes))
if("Other"%in%D$Cl & "Other"%in%Classes==F){
Classes=c(Classes,"Other")
cols=c(cols,colorRampPalette(Othercol)(1))
}
D$col=cols[match(D$Cl,Classes)]
D=project_data(D,NamesIn = c("Lat","Lon")) #Project locations
D$Area=Size*1e10
if(is.null(SizeVar)==FALSE){
D$Area=D$Area*D$SizeVar/mean(unique(D$SizeVar))
}
D$R=sqrt(D$Area/pi)
D$PolID=seq(1,nrow(D))
D$LegT=NA
D$Leg=NA
D$LegT[1]="Classes"
D$Leg[1]=paste0(Classes,collapse = ";")
D$LegT[2]="cols"
D$Leg[2]=paste0(cols,collapse = ";")
Pl=list()
#Loop over pies
for(i in unique(D$ID)){
dat=D[D$ID==i,]
#Order according to classes
dat=dat[order(match(dat$Cl,Classes)),]
#Get center
Cx=dat$X[1]
Cy=dat$Y[1]
#Convert values to angles
dat$ang=2*pi*dat$p
#Get starts and ends
As=c(0,cumsum(dat$ang)) #angles
Starts=As[seq(1,length(As)-1)]
Ends=As[seq(2,length(As))]
R=dat$R[1]
for(j in seq(1,dim(dat)[1])){
PolID=dat$PolID[j]
A=c(Starts[j],Ends[j]) #angles
if(diff(A)>0.1){A=sort(unique(c(A,seq(A[1],A[2],by=0.1))))} #Densify
X=c(Cx,Cx+R*sin(A),Cx)
Y=c(Cy,Cy+R*cos(A),Cy)
if(dat$p[j]==1){
A=c(A,0)
X=Cx+R*sin(A)
Y=Cy+R*cos(A)
}
Pl[[PolID]]=st_polygon(list(cbind(X,Y)))
}
}
Pols=st_sfc(Pl, crs = 6932)
Pols=st_set_geometry(D,Pols)
#Re-order polys if needed
if(length(unique(Pols$R))>1){
Pols=Pols[order(Pols$R,decreasing = TRUE),]
}
return(Pols)
}
#' Add a legend to Pies
#'
#' Adds a legend to pies created using \link{create_Pies}.
#'
#' @param Pies Spatial object created using \link{create_Pies}.
#'
#' @param bb Spatial object, sf bounding box created with \code{st_bbox()}. If provided,
#' the legend will be centered in that bb. Otherwise it is centered on the \code{min(Latitudes)}
#' and \code{median(Longitudes)} of coordinates found in the input \code{Pies}.
#'
#' @param PosX numeric, horizontal adjustment of legend.
#'
#' @param PosY numeric, vertical adjustment of legend.
#'
#' @param Size numeric, controls the size of pies.
#'
#' @param lwd numeric, line thickness of pies.
#'
#' @param Boxexp numeric, vector of length 4 controls the expansion of the legend box, given
#' as \code{c(xmin,xmax,ymin,ymax)}.
#'
#' @param Boxbd character, color of the background of the legend box.
#'
#' @param Boxlwd numeric, line thickness of the legend box. Set to zero if no box is desired.
#'
#' @param Labexp numeric, controls the distance of the pie labels to the center of the pie.
#'
#' @param fontsize numeric, size of the legend font.
#'
#' @param LegSp numeric, spacing between the pie and the size chart (only used if \code{SizeVar}
#' was specified in \link{create_Pies}).
#'
#' @param Horiz logical. Set to FALSE for vertical layout (only used if \code{SizeVar}
#' was specified in \link{create_Pies}).
#'
#' @param PieTitle character, title of the pie chart.
#'
#' @param SizeTitle character, title of the size chart (only used if \code{SizeVar}
#' was specified in \link{create_Pies}).
#'
#' @param PieTitleVadj numeric, vertical adjustment of the title of the pie chart.
#'
#' @param SizeTitleVadj numeric, vertical adjustment of the title of the size chart (only used if \code{SizeVar}
#' was specified in \link{create_Pies}).
#'
#' @param nSizes integer, number of size classes to display in the size chart. Minimum and maximum sizes are
#' displayed by default. (only used if \code{SizeVar} was specified in \link{create_Pies}).
#'
#' @param SizeClasses numeric, vector (e.g. c(1,10,100)) of size classes to display in the size chart
#' (only used if \code{SizeVar} was specified in \link{create_Pies}). If set, overrides \code{nSizes}.
#'
#' @return Adds a legend to a pre-existing pie plot.
#'
#' @seealso
#' \code{\link{create_Pies}}, \code{\link{PieData}}, \code{\link{PieData2}}.
#'
#' @examples
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#23-create-pies
#'
#' #Pies of constant size, all classes displayed:
#' #Create pies
#' MyPies=create_Pies(Input=PieData,
#' NamesIn=c("Lat","Lon","Sp","N"),
#' Size=50
#' )
#' #Plot Pies
#' plot(st_geometry(MyPies),col=MyPies$col)
#' #Add Pies legend
#' add_PieLegend(Pies=MyPies,PosX=-0.1,PosY=-1,Boxexp=c(0.5,0.45,0.12,0.45),
#' PieTitle="Species")
#'
#'
#'
#' @export
add_PieLegend=function(Pies=NULL,bb=NULL,PosX=0,PosY=0,Size=25,lwd=1,Boxexp=c(0.2,0.2,0.12,0.3), #xmin,xmax,ymin,ymax
Boxbd='white',Boxlwd=1,Labexp=0.3,fontsize=1,LegSp=0.5,Horiz=TRUE,
PieTitle="Pie chart",SizeTitle="Size chart",
PieTitleVadj=0.5,SizeTitleVadj=0.3,nSizes=3,SizeClasses=NULL){
if(class(Pies)[1]!="sf"){
stop("'Pies' must be generated using create_Pies()")
}
if("LegT"%in%colnames(Pies)==FALSE){
stop("'Pies' must be generated using create_Pies()")
}
if(is.null(PosX)==TRUE){
stop("Argument 'PosX' is missing")
}
if(is.null(PosY)==TRUE){
stop("Argument 'PosY' is missing")
}
if(is.null(SizeClasses) & is.null(nSizes)){
stop("'SizeClasses' and 'nSizes' cannot be both NULL")
}
if(is.null(SizeClasses)==FALSE & is.null(nSizes)==FALSE){
nSizes=NULL
}
Pdata=st_drop_geometry(Pies)
Classes=Pdata$Leg[which(Pdata$LegT=="Classes")]
cols=Pdata$Leg[which(Pdata$LegT=="cols")]
Classes=strsplit(Classes,";")[[1]]
cols=strsplit(cols,";")[[1]]
dat=data.frame(Cl=Classes,col=cols)
if(is.null(bb)){
Lat=min(Pdata$Lat)
Lon=median(Pdata$Lon)
}else{
if(inherits(bb,"bbox")==FALSE){stop("bb is not an sf bounding box, use st_bbox() to create bb.")}
Lat=mean(bb[c('ymin','ymax')])
Lon=mean(bb[c('xmin','xmax')])
Lat=project_data(data.frame(La=Lat,Lo=Lon),NamesIn=c("La","Lo"),inv=TRUE,append=FALSE)
Lon=Lat$Longitude
Lat=Lat$Latitude
}
if(length(unique(Pdata$R))==1){ #No SizeVar
dat$Lat=Lat
dat$Lon=Lon
dat=project_data(dat,NamesIn = c("Lat","Lon")) #Project locations
dat$X=dat$X+PosX*1e6
dat$Y=dat$Y+PosY*1e6
dat$p=1/nrow(dat)
dat$PolID=seq(1,nrow(dat))
dat$LabA=NA
dat$Labx=NA
dat$Laby=NA
#Build pie
Area=Size*1e10
R=sqrt(Area/pi)
Pl=list()
#Get center
Cx=dat$X[1]
Cy=dat$Y[1]
#Convert values to angles
dat$ang=2*pi*dat$p
#Get starts and ends
As=c(0,cumsum(dat$ang)) #angles
Starts=As[seq(1,length(As)-1)]
Ends=As[seq(2,length(As))]
for(j in seq(1,dim(dat)[1])){
PolID=dat$PolID[j]
A=c(Starts[j],Ends[j]) #angles
dat$LabA[j]=mean(A)
dat$Labx[j]=Cx+(R+R*Labexp)*sin(dat$LabA[j])
dat$Laby[j]=Cy+(R+R*Labexp)*cos(dat$LabA[j])
if(diff(A)>0.1){A=sort(unique(c(A,seq(A[1],A[2],by=0.1))))} #Densify
X=c(Cx,Cx+R*sin(A),Cx)
Y=c(Cy,Cy+R*cos(A),Cy)
Pl[[PolID]]=st_polygon(list(cbind(X,Y)))
}
Pols=st_sfc(Pl, crs = 6932)
Pols=st_set_geometry(dat,Pols)
PieTitlex=Cx
PieTitley=Cy+(R+R*PieTitleVadj)
dat$Ladjx=0
dat$Ladjx[dat$LabA==0]=0.5
dat$Ladjx[dat$LabA==pi]=0.5
dat$Ladjx[dat$LabA>pi & dat$LabA<2*pi]=1
if(is.null(Boxexp)==FALSE){
bb=st_bbox(Pols)
Xmin=bb['xmin']
Ymin=bb['ymin']
Xmax=bb['xmax']
Ymax=bb['ymax']
dX=abs(Xmax-Xmin)
dY=abs(Ymax-Ymin)
Xmin=min(c(Xmin,dat$Labx))
Ymin=min(c(Ymin,dat$Laby))
Xmax=max(c(Xmax,dat$Labx))
Ymax=max(c(Ymax,dat$Laby))
Xmin=Xmin-Boxexp[1]*dX
Xmax=Xmax+Boxexp[2]*dX
Ymin=Ymin-Boxexp[3]*dY
Ymax=Ymax+Boxexp[4]*dY
X=c(Xmin,Xmin,Xmax,Xmax,Xmin)
Y=c(Ymin,Ymax,Ymax,Ymin,Ymin)
if(Boxlwd>0){
Bpol=st_sfc(st_polygon(list(cbind(X,Y))), crs = 6932)
plot(st_geometry(Bpol),col=Boxbd,lwd=Boxlwd,add=TRUE,xpd=TRUE)
}
}
for(i in seq(1,nrow(dat))){
text(dat$Labx[i],dat$Laby[i],dat$Cl[i],adj=c(dat$Ladjx[i],0.5),xpd=TRUE,cex=fontsize)
}
plot(st_geometry(Pols),col=Pols$col,add=TRUE,xpd=TRUE,lwd=lwd)
text(PieTitlex,PieTitley,PieTitle,adj=c(0.5,0),cex=fontsize*1.2,xpd=TRUE)
}else{ #With SizeVar
#Get centers
Cen=project_data(data.frame(Lat=Lat,Lon=Lon),NamesIn = c("Lat","Lon"))
if(Horiz==TRUE){
dX=LegSp*1000000
PieX=Cen$X-dX+PosX*1e6
SvarX=Cen$X+dX+PosX*1e6
PieY=Cen$Y+PosY*1e6
SvarY=Cen$Y+PosY*1e6
}else{
dY=LegSp*1000000
PieX=Cen$X+PosX*1e6
SvarX=Cen$X+PosX*1e6
PieY=Cen$Y+dY+PosY*1e6
SvarY=Cen$Y-dY+PosY*1e6
}
#Do pie
dat$p=1/nrow(dat)
dat$PolID=seq(1,nrow(dat))
dat$LabA=NA
dat$Labx=NA
dat$Laby=NA
#Build pie
Area=Size*1e10
R=sqrt(Area/pi)
Pl=list()
#Get center
Cx=PieX
Cy=PieY
#Convert values to angles
dat$ang=2*pi*dat$p
#Get starts and ends
As=c(0,cumsum(dat$ang)) #angles
Starts=As[seq(1,length(As)-1)]
Ends=As[seq(2,length(As))]
for(j in seq(1,dim(dat)[1])){
PolID=dat$PolID[j]
A=c(Starts[j],Ends[j]) #angles
dat$LabA[j]=mean(A)
dat$Labx[j]=Cx+(R+R*Labexp)*sin(dat$LabA[j])
dat$Laby[j]=Cy+(R+R*Labexp)*cos(dat$LabA[j])
if(diff(A)>0.1){A=sort(unique(c(A,seq(A[1],A[2],by=0.1))))} #Densify
X=c(Cx,Cx+R*sin(A),Cx)
Y=c(Cy,Cy+R*cos(A),Cy)
Pl[[PolID]]=st_polygon(list(cbind(X,Y)))
}
Pols=st_sfc(Pl, crs = 6932)
Pols=st_set_geometry(dat,Pols)
PieTitlex=Cx
PieTitley=Cy+(R+R*PieTitleVadj)
dat$Ladjx=0
dat$Ladjx[dat$LabA==0]=0.5
dat$Ladjx[dat$LabA==pi]=0.5
dat$Ladjx[dat$LabA>pi & dat$LabA<2*pi]=1
#Do Svar
if(is.null(nSizes)==FALSE){
if(nSizes==1){nSizes=2}
Svars=seq(min(Pdata$SizeVar),max(Pdata$SizeVar),length.out=nSizes)
}
if(is.null(SizeClasses)==FALSE){
Svars=SizeClasses
}
Svars=sort(Svars,decreasing = TRUE)
Ssize=Pdata$Area[1]/(1e10*Pdata$SizeVar[1]/mean(unique(Pdata$SizeVar))) #Get back to Size
Rs=sqrt((Ssize* 1e10* Svars / mean(unique(Pdata$SizeVar)) )/pi)
Sdat=data.frame(ID=seq(1,length(Svars)),vals=Svars,R=Rs,X=SvarX,Y=SvarY,Xs=NA,Xe=NA,Ys=NA,Ye=NA,row.names=NULL)
Pl=list()
for(j in seq(1,dim(Sdat)[1])){
PolID=Sdat$ID[j]
A=c(seq(0,2*pi,length.out=50),0) #angles
X=SvarX+Sdat$R[j]*sin(A)
Y=SvarY+Sdat$R[j]*cos(A)
Pl[[PolID]]=st_polygon(list(cbind(X,Y)))
Sdat$Xs[j]=X[1]
Sdat$Ys[j]=Y[1]
Sdat$Xe[j]=SvarX+Sdat$R[1]+(Sdat$R[1]-Sdat$R[2])/10
Sdat$Ye[j]=Y[1]
}
Polsvar=st_sfc(Pl, crs = 6932)
Polsvar=st_set_geometry(Sdat,Polsvar)
SizeTitlex=SvarX
SizeTitley=SvarY+(Sdat$R[1]+Sdat$R[1]*SizeTitleVadj)
#Do box
if(is.null(Boxexp)==FALSE){
bb=st_bbox(Polsvar)
Xmin=bb['xmin']
Ymin=bb['ymin']
Xmax=bb['xmax']
Ymax=bb['ymax']
Xmin=min(c(Xmin,dat$Labx))
Ymin=min(c(Ymin,dat$Laby))
Xmax=max(c(Xmax,dat$Labx,Sdat$Xe))
Ymax=max(c(Ymax,dat$Laby))
dX=abs(Xmax-Xmin)
dY=abs(Ymax-Ymin)
Xmin=Xmin-Boxexp[1]*dX
Xmax=Xmax+Boxexp[2]*dX
Ymin=Ymin-Boxexp[3]*dY
Ymax=Ymax+Boxexp[4]*dY
X=c(Xmin,Xmin,Xmax,Xmax,Xmin)
Y=c(Ymin,Ymax,Ymax,Ymin,Ymin)
if(Boxlwd>0){
Bpol=st_sfc(st_polygon(list(cbind(X,Y))), crs = 6932)
plot(st_geometry(Bpol),col=Boxbd,lwd=Boxlwd,add=TRUE,xpd=TRUE)
}
}
#Plot Pols
plot(st_geometry(Pols),col=Pols$col,add=TRUE,xpd=TRUE,lwd=lwd)
plot(st_geometry(Polsvar),add=TRUE,xpd=TRUE,col='white',lwd=lwd)
#Add Pie labels
for(i in seq(1,nrow(dat))){
text(dat$Labx[i],dat$Laby[i],dat$Cl[i],adj=c(dat$Ladjx[i],0.5),xpd=TRUE,cex=fontsize)
}
#add Svar labels
segments(x0=Polsvar$Xs,y0=Polsvar$Ys,x1=Polsvar$Xe,y1=Polsvar$Ye,xpd=TRUE,lwd=lwd)
text(Polsvar$Xe,Polsvar$Ye,Polsvar$vals,adj=c(-0.1,0.5),xpd=TRUE,cex=fontsize)
text(PieTitlex,PieTitley,PieTitle,adj=c(0.5,0),xpd=TRUE,cex=fontsize*1.2)
text(SizeTitlex,SizeTitley,SizeTitle,adj=c(0.5,0),xpd=TRUE,cex=fontsize*1.2)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/Pies.R
|
#' Rotate object
#'
#' Rotate a spatial object by setting the longitude that should point up.
#'
#' @param Input Spatial object of class \code{sf}, \code{sfc} or \code{SpatRaster (terra)}.
#'
#' @param Lon0 numeric, longitude that will point up in the resulting map.
#'
#' @return Spatial object in your environment to only be used for plotting, not for analysis.
#'
#' @seealso
#' \code{\link{create_Points}}, \code{\link{create_Lines}}, \code{\link{create_Polys}},
#' \code{\link{create_PolyGrids}}, \code{\link{create_Stations}}, \code{\link{create_Pies}},
#' \code{\link{create_Arrow}}.
#'
#' @examples
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#47-rotate_obj
#' # and:
#' # https://github.com/ccamlr/CCAMLRGIS/blob/master/Basemaps/Basemaps.md
#'
#' RotB=Rotate_obj(SmallBathy(),Lon0=-180)
#' terra::plot(RotB,breaks=Depth_cuts,col=Depth_cols,axes=FALSE,box=FALSE,legend=FALSE)
#' add_RefGrid(bb=st_bbox(RotB),ResLat=10,ResLon=20,LabLon = -180,offset = 3)
#'
#' @export
Rotate_obj=function(Input,Lon0=NULL){
if(any(class(Input)%in%c("sf","sfc","SpatRaster"))==FALSE){
stop("The input must be an object of class sf, sfc or SpatRaster.")
}
if(is.numeric(Lon0)==FALSE){
stop("Lon0 must be numeric.")
}
CRSto=paste0("+proj=laea +lat_0=-90 +lon_0=",Lon0," +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs")
if(any(class(Input)%in%c("sf","sfc"))){
Robj=st_transform(Input,crs=CRSto)
}
if(any(class(Input)=="SpatRaster")){
Robj=terra::project(Input,CRSto)
}
return(Robj)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/Rotate_obj.R
|
#' Add a color scale
#'
#' Adds a color scale to plots. Default behavior set for bathymetry. May also be used to
#' place a \code{\link[graphics]{legend}}.
#'
#' @param pos character, fraction indicating the vertical position of the color scale (which, by default, is on the
#' right side of plots). if \code{pos="1/1"}, the color scale will be centered.
#' if \code{pos="1/2"}, the color scale will be centered on the top half of the plotting region.
#' if \code{pos="2/2"}, the color scale will be centered on the bottom half of the plotting region.
#' @param title character, title of the color scale.
#' @param width numeric, width of the color scale box, expressed in \% of the width of the plotting region.
#' @param height numeric, height of the color scale box, expressed in \% of the height of the plotting region.
#' @param cuts numeric, vector of color classes. May be generated via \code{\link{add_col}}.
#' @param cols character, vector of color names. May be generated via \code{\link{add_col}}.
#' @param minVal numeric, if desired, the color scale may be generated starting from the value \code{minVal}. See examples.
#' @param maxVal numeric, if desired, the color scale may be generated up to the value \code{maxVal}. See examples.
#' @param fontsize numeric, size of the text in the color scale.
#' @param offset numeric, controls the horizontal position of the color scale.
#' @param lwd numeric, thickness of lines.
#' @param Titlefontsize numeric, size of the title text.
#' @param TitleVAdj numeric, vertical adjustment of the title.
#' @param BoxAdj numeric vector of 4 values to adjust the sides of the box, given as \code{c(bottom,left,top,right)}.
#' @param BoxCol Color of the legend box frame.
#' @param BoxBG Color of the legend box background.
#' @param mode character, if 'Cscale', the default, the function builds a color scale. if 'Legend', the function
#' gives you the location of a \code{\link[graphics]{legend}}, arguments \code{pos}, \code{offset} and \code{height}
#' may be used for adjustments. See examples.
#'
#' @seealso
#' \code{\link{load_Bathy}}, \code{\link{SmallBathy}}, \code{\link{Depth_cuts}}, \code{\link{Depth_cols}},
#' \code{\link{Depth_cuts2}}, \code{\link{Depth_cols2}}, \code{\link{add_col}},
#' \href{http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf}{R colors}, \code{\link[graphics]{legend}}.
#'
#' @examples
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#5-adding-colors-legends-and-labels
#'
#' library(terra)
#'
#' #Example 1: Adding two color scales
#'
#' plot(SmallBathy(),breaks=Depth_cuts,col=Depth_cols,legend=FALSE,axes=FALSE,box=FALSE)
#' add_Cscale(pos='1/2',height=45,maxVal=0,minVal=-4000,fontsize=0.8)
#' #Some gridded data
#' MyGrid=create_PolyGrids(GridData,dlon=2,dlat=1)
#' Gridcol=add_col(MyGrid$Catch_sum,cuts=10)
#' plot(st_geometry(MyGrid),col=Gridcol$varcol,add=TRUE)
#' #Add color scale using cuts and cols generated by add_col, note the use of 'round'
#' add_Cscale(pos='2/2',height=45,title='Catch (t)',
#' cuts=round(Gridcol$cuts,1),cols=Gridcol$cols,fontsize=0.8)
#'
#' #Example 2: Adding a color scale and a legend
#'
#' #Create some point data
#' MyPoints=create_Points(PointData)
#'
#' #Crop the bathymetry to match the extent of MyPoints
#'
#' BathyCr=crop(SmallBathy(),extend(ext(MyPoints),100000))
#' plot(BathyCr,breaks=Depth_cuts,col=Depth_cols,legend=FALSE,axes=FALSE,mar=c(0,0,0,7))
#' add_Cscale(pos='1/2',height=45,maxVal=0,minVal=-4000,fontsize=0.8)
#'
#' #Plot points with different symbols and colors (see ?points)
#' Psymbols=c(21,22,23,24)
#' Pcolors=c('red','green','blue','yellow')
#' plot(st_geometry(MyPoints[MyPoints$name=='one',]),pch=Psymbols[1],bg=Pcolors[1],add=TRUE)
#' plot(st_geometry(MyPoints[MyPoints$name=='two',]),pch=Psymbols[2],bg=Pcolors[2],add=TRUE)
#' plot(st_geometry(MyPoints[MyPoints$name=='three',]),pch=Psymbols[3],bg=Pcolors[3],add=TRUE)
#' plot(st_geometry(MyPoints[MyPoints$name=='four',]),pch=Psymbols[4],bg=Pcolors[4],add=TRUE)
#'
#' #Add legend with position determined by add_Cscale
#' Loc=add_Cscale(pos='2/2',height=45,mode='Legend')
#' legend(Loc,legend=c('one','two','three','four'),title='Vessel',pch=Psymbols,
#' pt.bg=Pcolors,xpd=TRUE)
#'
#' @export
add_Cscale=function(pos='1/1',title='Depth (m)',width=18,height=70,
cuts=Depth_cuts,cols=Depth_cols,
minVal=NA,maxVal=NA,fontsize=1,offset=100,lwd=1,
Titlefontsize=1.2*fontsize,TitleVAdj=0,BoxAdj=c(0,0,0,0),
BoxCol="black",BoxBG="white",
mode="Cscale"){
offset=offset*1000
#Get plot boundaries
ls=par("usr")
xmin=ls[1]
xmax=ls[2]
ymin=ls[3]
ymax=ls[4]
xdist=xmax-xmin
ydist=ymax-ymin
#Midpoint
n=as.numeric(strsplit(pos,'/')[[1]])
N=n[2]
n=n[1]
ymid=seq(ymax,ymin,length.out=2*N+1)[seq(2,n+N,by=2)[n]]
#Overall box
bxmin=xmax+0.005*xdist+offset
bxmax=xmax+(width/100)*xdist+offset
bymin=ymid-(height/200)*ydist
bymax=ymid+(height/200)*ydist
if(mode=='Legend'){
out=cbind(x=bxmin,y=bymax)
return(out)
}else{
#constrain colors and breaks
cutsTo=cuts
colsTo=cols
if(is.na(minVal)==FALSE & is.na(maxVal)==FALSE){
if(minVal>=maxVal){stop("minVal should be inferior to maxVal")}
}
if(is.na(minVal)==FALSE){
indx=which(cuts>=minVal)[1]
if(cuts[indx]>minVal & indx>1){indx=indx-1}
cutsTo=cuts[indx:length(cuts)]
colsTo=cols[indx:length(cols)]
cuts=cutsTo
cols=colsTo
}
if(is.na(maxVal)==FALSE){
indx=rev(which(cuts<=maxVal))[1]
if(cuts[indx]<maxVal & indx<length(cuts)){indx=indx+1}
cutsTo=cuts[1:indx]
colsTo=cols[1:(indx-1)]
}
#plot Overall box
rect(xleft=bxmin+BoxAdj[2]*xdist,
ybottom=bymin+BoxAdj[1]*ydist,
xright=bxmax+BoxAdj[4]*xdist,
ytop=bymax+BoxAdj[3]*ydist,
xpd=TRUE,lwd=lwd,col=BoxBG,border=BoxCol)
#Col box
cxmin=bxmin+0.01*xdist
cxmax=bxmin+0.05*xdist
cymin=bymin+0.02*ydist
cymax=bymax-0.07*ydist
Ys=seq(cymin,cymax,length.out=length(colsTo)+1)
rect(xleft=cxmin,
ybottom=Ys[1:(length(Ys)-1)],
xright=cxmax,
ytop=Ys[2:length(Ys)],xpd=TRUE,lwd=0,col=colsTo)
rect(xleft=cxmin,
ybottom=cymin,
xright=cxmax,
ytop=cymax,xpd=TRUE,lwd=lwd)
#Ticks
segments(x0=cxmax,
y0=Ys,
x1=cxmax+0.01*xdist,
y1=Ys,lwd=lwd,xpd=TRUE,lend=1)
text(cxmax+0.02*xdist,Ys,
cutsTo,adj=c(0,0.5),xpd=TRUE,cex=fontsize)
#Title
text(cxmin,cymax+0.04*ydist+TitleVAdj*ydist,title,
cex=Titlefontsize,adj=c(0,0.5),xpd=TRUE)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/add_Cscale.R
|
#' Add a Reference grid
#'
#' Add a Latitude/Longitude reference grid to maps.
#'
#' @param bb bounding box of the first plotted object. for example, \code{bb=st_bbox(SmallBathy())} or \code{bb=st_bbox(MyPolys)}.
#' @param ResLat numeric, latitude resolution in decimal degrees.
#' @param ResLon numeric, longitude resolution in decimal degrees.
#' @param LabLon numeric, longitude at which Latitude labels should appear. if set, the resulting Reference grid will be circumpolar.
#' @param LatR numeric, range of latitudes of circumpolar grid.
#' @param lwd numeric, line thickness of the Reference grid.
#' @param lcol character, line color of the Reference grid.
#' @param fontsize numeric, font size of the Reference grid's labels.
#' @param fontcol character, font color of the Reference grid's labels.
#' @param offset numeric, offset of the Reference grid's labels (distance to plot border).
#' @seealso
#' \code{\link{load_Bathy}}, \code{\link{SmallBathy}}.
#'
#' @examples
#' library(terra)
#'
#' #Example 1: Circumpolar grid with Latitude labels at Longitude 0
#'
#' plot(SmallBathy(),breaks=Depth_cuts, col=Depth_cols, legend=FALSE,axes=FALSE,box=FALSE)
#' add_RefGrid(bb=st_bbox(SmallBathy()),ResLat=10,ResLon=20,LabLon = 0)
#'
#' #Example 2: Local grid around created polygons
#'
#' MyPolys=create_Polys(PolyData,Densify=TRUE)
#' BathyC=crop(SmallBathy(),ext(MyPolys))#crop the bathymetry to match the extent of MyPolys
#' Mypar=par(mai=c(0.5,0.5,0.5,0.5)) #Figure margins as c(bottom, left, top, right)
#' par(Mypar)
#' plot(BathyC,breaks=Depth_cuts, col=Depth_cols, legend=FALSE,axes=FALSE,box=FALSE)
#' add_RefGrid(bb=st_bbox(BathyC),ResLat=2,ResLon=6)
#' plot(st_geometry(MyPolys),add=TRUE,col='orange',border='brown',lwd=2)
#'
#' @export
add_RefGrid=function(bb,ResLat=1,ResLon=2,LabLon=NA,LatR=c(-80,-45),lwd=1,lcol="black",fontsize=1,fontcol="black",offset=NA){
#Get bbox
xmin=as.numeric(bb['xmin'])
xmax=as.numeric(bb['xmax'])
ymin=as.numeric(bb['ymin'])
ymax=as.numeric(bb['ymax'])
Locs=cbind(c(xmin,xmin,xmax,xmax,xmin),
c(ymin,ymax,ymax,ymin,ymin))
#Get offset
if(is.na(sum(offset))==TRUE){
#auto offset
xd=xmax-xmin
offsetx=0.01*xd
yd=ymax-ymin
offsety=0.02*yd
if(is.na(LabLon)==FALSE){offsetx=0}
}else{
if(length(offset)==1){offsetx=offset;offsety=offset}else{offsetx=offset[1];offsety=offset[2]}
}
#Create Lat/Lon lines
Lats=seq(LatR[1],LatR[2],by=ResLat)
if(is.na(LabLon)==FALSE){
Lons=sort(unique(c(seq(-180,180,by=ResLon),LabLon)))
}else{
Lons=seq(-180,180,by=ResLon)
}
LLats=list()
for(i in seq(1,length(Lats))){
LLats[[i]]=st_linestring(cbind(seq(-180,180,by=0.1),Lats[i]))
}
LLats=st_sfc(LLats, crs = 4326)
LLons=list()
for(i in seq(1,length(Lons))){
LLons[[i]]=st_linestring(cbind(Lons[i],range(Lats)))
}
LLons=st_sfc(LLons, crs = 4326)
gr=c(LLats,LLons)
gr=st_transform(gr,st_crs(bb))
#Create Lat/Lon points
Ps=expand.grid(Lon=Lons,Lat=Lats)
grP=st_as_sf(x=Ps,coords=c(1,2),crs=4326,remove=FALSE)
grP=st_transform(grP,st_crs(bb))
#Create box
LocsP=st_sfc(st_polygon(list(Locs)), crs = st_crs(bb))
#Get labels
#Circumpolar
if(is.na(LabLon)==FALSE){
Labsxy=st_coordinates(grP)
Labs=st_drop_geometry(grP)
Labs$x=Labsxy[,1]
Labs$y=Labsxy[,2]
LatLabs=Labs[Labs$Lon==LabLon,]
LonLabs=Labs[Labs$Lat==max(Labs$Lat),]
#Offset Longitude labels
Lps=st_as_sf(x=data.frame(Lon=Lons,Lat=max(Lats)+2+offsetx),coords=c(1,2),crs=4326)
Lps=st_transform(Lps,st_crs(bb))
Lps=st_coordinates(Lps)
LonLabs$x=Lps[,1]
LonLabs$y=Lps[,2]
#Adjust
LonLabs$xadj=0.5
LatLabs$xadj=0.5
#Remove one of the antimeridians
LonLabs=LonLabs[-which(LonLabs$Lon==-180),]
}else{
grlat=st_transform(LLats,st_crs(bb))
grlon=st_transform(LLons,st_crs(bb))
grlat=sf::st_intersection(LocsP,grlat)
grlon=sf::st_intersection(LocsP,grlon)
gr=c(grlat,grlon)
grPlat=sf::st_intersection(st_cast(LocsP,"LINESTRING"),grlat)
grPlon=sf::st_intersection(st_cast(LocsP,"LINESTRING"),grlon)
grPlat=st_cast(grPlat,'MULTIPOINT')
grPlon=st_cast(grPlon,'MULTIPOINT')
tmp=st_coordinates(grPlat)
Labslat=data.frame(x=tmp[,1],y=tmp[,2])
tmp=st_coordinates(grPlon)
Labslon=data.frame(x=tmp[,1],y=tmp[,2])
LabslatV=Labslat[Labslat$x==min(Labslat$x)|Labslat$x==max(Labslat$x),]
LabslatH=Labslat[Labslat$y==min(Labslat$y)|Labslat$y==max(Labslat$y),]
LabslonV=Labslon[Labslon$x==min(Labslon$x)|Labslon$x==max(Labslon$x),]
LabslonH=Labslon[Labslon$y==min(Labslon$y)|Labslon$y==max(Labslon$y),]
#Rounding thing
DecLat=nchar(strsplit(sub('0+$', '', as.character(ResLat)), ".", fixed = TRUE)[[1]])
DecLon=nchar(strsplit(sub('0+$', '', as.character(ResLon)), ".", fixed = TRUE)[[1]])
if(length(DecLat)==1){DecLat=0}else{DecLat=DecLat[[2]]}
if(length(DecLon)==1){DecLon=0}else{DecLon=DecLon[[2]]}
if((dim(LabslatH)[1]+dim(LabslonV)[1])>(dim(LabslatV)[1]+dim(LabslonH)[1])){
#go with LabslatH and LabslonV
#Get Lat/Lon
Locs=st_as_sf(x=LabslatH,coords=c(2,1),crs=st_crs(bb),remove=FALSE)
Locs=lwgeom::st_transform_proj(Locs,st_crs(LLons))
Locs=as.data.frame(st_coordinates(Locs))
colnames(Locs)=c('Lon','Lat')
LabslatH=cbind(LabslatH,Locs)
Locs=st_as_sf(x=LabslonV,coords=c(2,1),crs=st_crs(bb),remove=FALSE)
Locs=lwgeom::st_transform_proj(Locs,st_crs(LLons))
Locs=as.data.frame(st_coordinates(Locs))
colnames(Locs)=c('Lon','Lat')
LabslonV=cbind(LabslonV,Locs)
#Add offset
LabslatH$y[LabslatH$y==max(LabslatH$y)]=LabslatH$y[LabslatH$y==max(LabslatH$y)]+offsety
LabslatH$y[LabslatH$y==min(LabslatH$y)]=LabslatH$y[LabslatH$y==min(LabslatH$y)]-offsety
LabslatH$xadj=0.5
LabslonV$xadj=1
LabslonV$xadj[LabslonV$x==max(LabslonV$x)]=0
LabslonV$x[LabslonV$x==max(LabslonV$x)]=LabslonV$x[LabslonV$x==max(LabslonV$x)]+offsetx
LabslonV$x[LabslonV$x==min(LabslonV$x)]=LabslonV$x[LabslonV$x==min(LabslonV$x)]-offsetx
#rename Labs
LatLabs=LabslatH
LonLabs=LabslonV
}else{
#go with LabslatV and LabslonH
#Get Lat/Lon
Locs=st_as_sf(x=LabslatV,coords=c(2,1),crs=st_crs(bb),remove=FALSE)
Locs=lwgeom::st_transform_proj(Locs,st_crs(LLons))
Locs=as.data.frame(st_coordinates(Locs))
colnames(Locs)=c('Lon','Lat')
LabslatV=cbind(LabslatV,Locs)
Locs=st_as_sf(x=LabslonH,coords=c(2,1),crs=st_crs(bb),remove=FALSE)
Locs=lwgeom::st_transform_proj(Locs,st_crs(LLons))
Locs=as.data.frame(st_coordinates(Locs))
colnames(Locs)=c('Lon','Lat')
LabslonH=cbind(LabslonH,Locs)
#Add offset
LabslonH$xadj=0.5
LabslatV$xadj=1
LabslatV$xadj[LabslatV$x==max(LabslatV$x)]=0
LabslatV$x[LabslatV$x==max(LabslatV$x)]=LabslatV$x[LabslatV$x==max(LabslatV$x)]+offsetx
LabslatV$x[LabslatV$x==min(LabslatV$x)]=LabslatV$x[LabslatV$x==min(LabslatV$x)]-offsetx
LabslonH$y[LabslonH$y==max(LabslonH$y)]=LabslonH$y[LabslonH$y==max(LabslonH$y)]+offsety
LabslonH$y[LabslonH$y==min(LabslonH$y)]=LabslonH$y[LabslonH$y==min(LabslonH$y)]-offsety
#rename Labs
LatLabs=LabslatV
LonLabs=LabslonH
}
#round
LatLabs$Lat=round(LatLabs$Lat,DecLat)
LonLabs$Lon=round(LonLabs$Lon,DecLon)
}
#Add W/E and S
LatLabs$Lat=paste0(abs(LatLabs$Lat),'S')
tmp=LonLabs$Lon
indx=which(tmp%in%c(0,-180,180))
indxW=which(LonLabs$Lon<0 & (LonLabs$Lon%in%c(0,-180,180)==FALSE))
indxE=which(LonLabs$Lon>0 & (LonLabs$Lon%in%c(0,-180,180)==FALSE))
LonLabs$Lon[indxW]=paste0(abs(LonLabs$Lon[indxW]),'W')
LonLabs$Lon[indxE]=paste0(LonLabs$Lon[indxE],'E')
LonLabs$Lon[LonLabs$Lon%in%c('180','-180')]='180'
Mypar=par(xpd=TRUE)
graphics::plot(gr,lty=3,add=TRUE,lwd=lwd,col=lcol)
par(Mypar)
if(0.5%in%LatLabs$xadj){
text(LatLabs$x[LatLabs$xadj==0.5],LatLabs$y[LatLabs$xadj==0.5],LatLabs$Lat[LatLabs$xadj==0.5],
cex=fontsize,adj=c(0.5,0.5),xpd=TRUE,col=fontcol)}
if(1%in%LatLabs$xadj){
text(LatLabs$x[LatLabs$xadj==1],LatLabs$y[LatLabs$xadj==1],LatLabs$Lat[LatLabs$xadj==1],
cex=fontsize,adj=c(1,0.5),xpd=TRUE,col=fontcol)}
if(0%in%LatLabs$xadj){
text(LatLabs$x[LatLabs$xadj==0],LatLabs$y[LatLabs$xadj==0],LatLabs$Lat[LatLabs$xadj==0],
cex=fontsize,adj=c(0,0.5),xpd=TRUE,col=fontcol)}
if(0.5%in%LonLabs$xadj){
text(LonLabs$x[LonLabs$xadj==0.5],LonLabs$y[LonLabs$xadj==0.5],LonLabs$Lon[LonLabs$xadj==0.5],
cex=fontsize,adj=c(0.5,0.5),xpd=TRUE,col=fontcol)}
if(0%in%LonLabs$xadj){
text(LonLabs$x[LonLabs$xadj==0],LonLabs$y[LonLabs$xadj==0],LonLabs$Lon[LonLabs$xadj==0],
cex=fontsize,adj=c(0,0.5),xpd=TRUE,col=fontcol)}
if(1%in%LonLabs$xadj){
text(LonLabs$x[LonLabs$xadj==1],LonLabs$y[LonLabs$xadj==1],LonLabs$Lon[LonLabs$xadj==1],
cex=fontsize,adj=c(1,0.5),xpd=TRUE,col=fontcol)}
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/add_RefGrid.R
|
add_buffer=function(Input,buf=NA,SeparateBuf=TRUE){
buf=buf*1852
Shp=st_buffer(x=Input,dist=buf)
if(SeparateBuf==FALSE){
Shp=st_union(Shp)
Shp=st_set_geometry(x=data.frame(ID=1), Shp)
}
if("AreaKm2"%in%colnames(Shp)){
colnames(Shp)[which(colnames(Shp)=="AreaKm2")]="Unbuffered_AreaKm2"
}
#Get buffered areas
Ar=round(st_area(Shp)/1000000,1)
Shp$Buffered_AreaKm2=as.numeric(Ar)
return(Shp)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/add_buffer.R
|
#' Add colors
#'
#' Given an input variable, generates either a continuous color gradient or color classes.
#' To be used in conjunction with \code{\link{add_Cscale}}.
#'
#' @param var numeric vector of the variable to be colorized. Either all values (in which case all
#' values will be assigned to a color) or only two values (in which case these are considered to be
#' the range of values).
#' @param cuts numeric, controls color classes. Either one value (in which case \code{n=cuts} equally
#' spaced color classes are generated) or a vector (in which case irregular color classes are
#' generated e.g.: \code{c(-10,0,100,2000)}).
#' @param cols character vector of colors (see R standard color names \href{http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf}{here}).
#' \code{cols} are interpolated along \code{cuts}. Color codes as those generated,
#' for example, by \code{\link[grDevices]{rgb}} may also be used.
#' @return list containing the colors for the variable \code{var} (given as \code{$varcol} in the output) as
#' well as the single \code{cols} and \code{cuts}, to be used as inputs in \code{\link{add_Cscale}}.
#'
#' @seealso
#' \code{\link{add_Cscale}}, \code{\link{create_PolyGrids}}, \href{http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf}{R colors}.
#'
#' @examples
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#52-adding-colors-to-data
#'
#' MyPoints=create_Points(PointData)
#' MyCols=add_col(MyPoints$Nfishes)
#' plot(st_geometry(MyPoints),pch=21,bg=MyCols$varcol,cex=2)
#'
#'
#' @export
add_col=function(var,cuts=100,cols=c('green','yellow','red')){
pal=colorRampPalette(cols)
if(length(cuts)==1){
cutsTo=seq(min(var,na.rm=TRUE),max(var,na.rm=TRUE),length.out=cuts)
}else{
cutsTo=cuts
}
colsTo=pal(length(cutsTo)-1)
if(length(unique(quantile(var,na.rm=TRUE)))==1){varcol=rep(colsTo[1],length(var))}else{
varcol=colsTo[cut(var,cutsTo,include.lowest=TRUE,right=FALSE)]}
return(list('cuts'=cutsTo,'cols'=colsTo,'varcol'=varcol))
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/add_col.R
|
#' Add labels
#'
#' Adds labels to plots. Three modes are available:
#' In \code{'auto'} mode, labels are placed at the centres of polygon parts of spatial objects
#' loaded via the \code{load_} functions. Internally used in conjunction with \code{\link{Labels}}.
#' In \code{'manual'} mode, users may click on their plot to position labels. An editable label table is generated
#' to allow fine-tuning of labels appearance, and may be saved for external use. To edit the label table,
#' double-click inside one of its cells, edit the value, then close the table.
#' In \code{'input'} mode, a label table that was generated in \code{'manual'} mode is re-used.
#'
#' @param mode character, either \code{'auto'}, \code{'manual'} or \code{'input'}. See Description above.
#' @param layer character, in \code{'auto'} mode, single or vector of characters, may only be one, some or all of:
#' \code{c("ASDs","SSRUs","RBs","SSMUs","MAs","MPAs","EEZs")}.
#' @param fontsize numeric, in \code{'auto'} mode, size of the text.
#' @param fonttype numeric, in \code{'auto'} mode, type of the text (1 to 4), where 1 corresponds to plain text,
#' 2 to bold face, 3 to italic and 4 to bold italic.
#' @param angle numeric, in \code{'auto'} mode, rotation of the text in degrees.
#' @param col character, in \code{'auto'} mode, color of the text.
#' @param LabelTable in \code{'input'} mode, name of the label table that was generated in \code{'manual'} mode.
#' @return Adds labels to plot. To save a label table generated in \code{'manual'} mode, use:
#' \code{MyLabelTable=add_labels(mode='auto')}.
#' To re-use that label table, use:
#' \code{add_labels(mode='input',LabelTable=MyLabelTable)}.
#'
#' @seealso \code{\link{Labels}}, \code{\link{load_ASDs}}, \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}}, \code{\link{load_EEZs}},
#' \code{\link{load_MPAs}},
#' \href{http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf}{R colors}.
#'
#' @examples
#' \donttest{
#'
#' #Example 1: 'auto' mode
#' #label ASDs in bold and red
#' ASDs=load_ASDs()
#' plot(st_geometry(ASDs))
#' add_labels(mode='auto',layer='ASDs',fontsize=1,fonttype=2,col='red')
#' #add EEZs and their labels in large, green and vertical text
#' EEZs=load_EEZs()
#' plot(st_geometry(EEZs),add=TRUE,border='green')
#' add_labels(mode='auto',layer='EEZs',fontsize=2,col='green',angle=90)
#'
#'
#' #Example 2: 'manual' mode (you will have to do it yourself)
#' #Examples 2 and 3 below are commented (remove the # to test)
#' #library(terra)
#' #plot(SmallBathy())
#' #ASDs=load_ASDs()
#' #plot(st_geometry(ASDs),add=TRUE)
#' #MyLabels=add_labels(mode='manual')
#'
#'
#' #Example 3: Re-use the label table generated in Example 2
#' #plot(SmallBathy())
#' #plot(st_geometry(ASDs),add=TRUE)
#' #add_labels(mode='input',LabelTable=MyLabels)
#'
#'
#'
#' }
#'
#' @export
add_labels=function(mode=NULL,layer=NULL,fontsize=1,fonttype=1,angle=0,col='black',LabelTable=NULL){
if(mode=='auto'){
for(l in layer){
text(Labels[Labels$p==l,1:2],Labels$t[Labels$p==l],cex=fontsize,font=fonttype,srt=angle,col=col,xpd=TRUE)
}
}
if(mode=='manual'){
#Initialize
P=recordPlot()
Lab=data.frame(
x=numeric(),
y=numeric(),
text=character(),
fontsize=numeric(),
fonttype=numeric(),
angle=numeric(),
col=character()
)
ls=par("usr")
Gr=terra::rast(terra::ext(ls),nrows=100,ncols=100,vals=NA)
#First label
replayPlot(P)
message('Click on your figure to add a label\n')
message('Then edit the label table and close it\n')
a=terra::click(Gr,xy=TRUE,n=1,show=FALSE,type="n")
Lab=rbind(Lab,
data.frame(
x=a$x,
y=a$y,
text='NewLabel',
fontsize=1,
fonttype=1,
angle=0,
col='black',
stringsAsFactors=FALSE
)
)
Lab=project_data(Input=Lab,NamesIn=c('y','x'),NamesOut=c('Latitude','Longitude'),append=TRUE,inv=TRUE)
for(ang in unique(Lab$angle)){
text(Lab$x[Lab$angle==ang],Lab$y[Lab$angle==ang],
Lab$text[Lab$angle==ang],cex=Lab$fontsize[Lab$angle==ang],
font=Lab$fonttype[Lab$angle==ang],srt=ang,
col=Lab$col[Lab$angle==ang],xpd=TRUE)
}
Lab=suppressWarnings(edit(Lab))
replayPlot(P)
for(ang in unique(Lab$angle)){
text(Lab$x[Lab$angle==ang],Lab$y[Lab$angle==ang],
Lab$text[Lab$angle==ang],cex=Lab$fontsize[Lab$angle==ang],
font=Lab$fonttype[Lab$angle==ang],srt=ang,
col=Lab$col[Lab$angle==ang],xpd=TRUE)
}
#Next labels
xx=menu(c('Add a new label','Edit the label table'),title = 'What would you like to do?')
while(xx!=3){
if(xx==1){
message('Click on your figure to add a label\n')
message('Then edit the label table and close it\n')
a=terra::click(Gr,xy=TRUE,n=1,show=FALSE,type="n")
Lab=rbind(Lab,
project_data(Input=data.frame(
x=a$x,
y=a$y,
text='NewLabel',
fontsize=1,
fonttype=1,
angle=0,
col='black',
stringsAsFactors=FALSE
),NamesIn=c('y','x'),NamesOut=c('Latitude','Longitude'),append=TRUE,inv=TRUE)
)
for(ang in unique(Lab$angle)){
text(Lab$x[Lab$angle==ang],Lab$y[Lab$angle==ang],
Lab$text[Lab$angle==ang],cex=Lab$fontsize[Lab$angle==ang],
font=Lab$fonttype[Lab$angle==ang],srt=ang,
col=Lab$col[Lab$angle==ang],xpd=TRUE)
}
Lab=suppressWarnings(edit(Lab))
replayPlot(P)
for(ang in unique(Lab$angle)){
text(Lab$x[Lab$angle==ang],Lab$y[Lab$angle==ang],
Lab$text[Lab$angle==ang],cex=Lab$fontsize[Lab$angle==ang],
font=Lab$fonttype[Lab$angle==ang],srt=ang,
col=Lab$col[Lab$angle==ang],xpd=TRUE)
}
}
if(xx==2){
message('Edit the label table and close it\n')
Lab=suppressWarnings(edit(Lab))
replayPlot(P)
for(ang in unique(Lab$angle)){
text(Lab$x[Lab$angle==ang],Lab$y[Lab$angle==ang],
Lab$text[Lab$angle==ang],cex=Lab$fontsize[Lab$angle==ang],
font=Lab$fonttype[Lab$angle==ang],srt=ang,
col=Lab$col[Lab$angle==ang],xpd=TRUE)
}
}
xx=menu(c('Add a new label','Edit the label table','Exit'),title = 'What would you like to do?')
}
return(Lab)
}
if(mode=='input'){
Lab=LabelTable
for(ang in unique(Lab$angle)){
text(Lab$x[Lab$angle==ang],Lab$y[Lab$angle==ang],
Lab$text[Lab$angle==ang],cex=Lab$fontsize[Lab$angle==ang],
font=Lab$fonttype[Lab$angle==ang],srt=ang,
col=Lab$col[Lab$angle==ang],xpd=TRUE)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/add_labels.R
|
#' Assign point locations to polygons
#'
#' Given a set of polygons and a set of point locations (given in decimal degrees),
#' finds in which polygon those locations fall.
#' Finds, for example, in which Subarea the given fishing locations occurred.
#'
#' @param Input dataframe containing - at the minimum - Latitudes and Longitudes to be assigned to polygons.
#'
#' If \code{NamesIn} is not provided, the columns in the \code{Input} must be in the following order:
#' Latitude, Longitude, Variable 1, Variable 2, ... Variable x..
#'
#' @param NamesIn character vector of length 2 specifying the column names of Latitude and Longitude fields in
#' the \code{Input}. Latitudes name must be given first, e.g.:
#'
#' \code{NamesIn=c('MyLatitudes','MyLongitudes')}.
#'
#' @param Polys character vector of polygon names (e.g., \code{Polys=c('ASDs','RBs')}).
#'
#' Must be matching the names of the pre-loaded spatial objects (loaded via e.g., \code{ASDs=load_ASDs()}).
#'
#' @param AreaNameFormat dependent on the polygons loaded. For the Secretariat's spatial objects loaded via 'load_' functions,
#' we have the following:
#'
#' \code{'GAR_Name'} e.g., \code{'Subarea 88.2'}
#'
#' \code{'GAR_Short_Label'} e.g., \code{'882'}
#'
#' \code{'GAR_Long_Label'} (default) e.g., \code{'88.2'}
#'
#' Several values may be entered if several \code{Polys} are used, e.g.:
#'
#' \code{c('GAR_Short_Label','GAR_Name')}, in which case \code{AreaNameFormat} must be given in the same order as \code{Polys}.
#'
#' @param Buffer numeric, distance in nautical miles to be added around the \code{Polys} of interest.
#' Can be specified for each of the \code{Polys} (e.g., \code{Buffer=c(2,5)}). Useful to determine whether locations are within
#' \code{Buffer} nautical miles of a polygon.
#' @param NamesOut character, names of the resulting column names in the output dataframe,
#' with order matching that of \code{Polys} (e.g., \code{NamesOut=c('Recapture_ASD','Recapture_RB')}).
#' If not provided will be set as equal to \code{Polys}.
#' @return dataframe with the same structure as the \code{Input}, with additional columns corresponding
#' to the \code{Polys} used and named after \code{NamesOut}.
#'
#' @seealso
#' \code{\link{load_ASDs}}, \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}},
#' \code{\link{load_MPAs}}, \code{\link{load_EEZs}}.
#'
#' @examples
#' \donttest{
#'
#'
#' #Generate a dataframe
#' MyData=data.frame(Lat=runif(100,min=-65,max=-50),
#' Lon=runif(100,min=20,max=40))
#'
#' #Assign ASDs and SSRUs to these locations (first load ASDs and SSRUs)
#' ASDs=load_ASDs()
#' SSRUs=load_SSRUs()
#'
#' MyData=assign_areas(Input=MyData,Polys=c('ASDs','SSRUs'),NamesOut=c('MyASDs','MySSRUs'))
#'
#' #View(MyData)
#' table(MyData$MyASDs) #count of locations per ASD
#' table(MyData$MySSRUs) #count of locations per SSRU
#'
#' }
#'
#' @export
assign_areas=function(Input,Polys,AreaNameFormat='GAR_Long_Label',Buffer=0,NamesIn=NULL,NamesOut=NULL){
#coerce Input to a data.frame
Input=as.data.frame(Input)
#Check NamesIn
if(is.null(NamesIn)==FALSE){
if(length(NamesIn)!=2){stop("'NamesIn' should be a character vector of length 2")}
if(any(NamesIn%in%colnames(Input)==FALSE)){stop("'NamesIn' do not match column names in 'Input'")}
}
#Set NamesOut if not provided
if(is.null(NamesOut)==TRUE){NamesOut=Polys}
if(any(NamesOut%in%colnames(Input)==TRUE)){stop("'NamesOut' matches column names in 'Input', please use different names")}
#Repeat Buffer if needed
if(length(Buffer)==1 & length(Polys)>1){Buffer=rep(Buffer,length(Polys))}
#Repeat AreaNameFormat if needed
if(length(AreaNameFormat)==1 & length(Polys)>1){AreaNameFormat=rep(AreaNameFormat,length(Polys))}
#Get locations
if(is.null(NamesIn)==TRUE){
Locs=Input[,c(2,1)]
}else{
Locs=Input[,c(NamesIn[c(2,1)])]
}
#Count missing locations to warn user
Missing=which(is.na(Locs[,1])==TRUE | is.na(Locs[,2])==TRUE)
if(length(Missing)>1){
warning(paste0(length(Missing),' records are missing location and will not be assigned to any area\n'))
}
if(length(Missing)==1){
warning('One record is missing location and will not be assigned to any area\n')
}
#Count impossible locations to warn user and replace with NAs
Impossible=which(Locs[,1]>180 | Locs[,1]<(-180) | Locs[,2]>90 | Locs[,2]<(-90))
if(length(Impossible)>1){
warning(paste0(length(Impossible),' records are not on Earth and will not be assigned to any area\n'))
Locs[Impossible,]=NA
}
if(length(Impossible)==1){
warning('One record is not on Earth and will not be assigned to any area\n')
Locs[Impossible,]=NA
}
#Get uniques
Locu=unique(Locs)
#Remove missing locations
Locu=Locu[is.na(Locu[,1])==FALSE & is.na(Locu[,2])==FALSE,]
#Turn uniques into Spatial data
SPls=st_as_sf(x=Locu,coords=c(1,2),crs=4326,remove=FALSE)
#Project to match Polys projection
SPls=st_transform(x=SPls,crs=6932)
#Initialize a dataframe which will collate assigned Polys
Assigned_Areas=data.frame(matrix(NA,nrow=dim(Locu)[1],ncol=length(Polys),dimnames=list(NULL,NamesOut)))
Assigned_Areas$Lat=Locu[,2]
Assigned_Areas$Lon=Locu[,1]
#loop over Polys to assign them to locations
for(i in seq(1,length(Polys))){
#Get each Area sequentially
tmpArea=get(Polys[i])
#Add buffer to Area if desired
if(Buffer[i]>0){
tmpArea=st_buffer(tmpArea,dist=Buffer[i]*1852)
}
#Match points to polygons
match=sapply(st_intersects(SPls,tmpArea), function(z) if (length(z)==0) NA_integer_ else z[1])
tmpArea=st_drop_geometry(tmpArea)
if(ncol(tmpArea)==1){tmpArea$xyz123=NA}#Add empty column to avoid subsetting error when only 1 column
match=tmpArea[match,]
#Store results (an Area name per unique location)
Assigned_Areas[,NamesOut[i]]=as.character(match[,AreaNameFormat[i]])
}
#Merge Assigned_Areas to Input
join_cols=c("Lat","Lon")
if(is.null(NamesIn)==TRUE){
names(join_cols)=colnames(Input)[c(1,2)]
}else{
names(join_cols)=NamesIn
}
Input=dplyr::left_join(Input,Assigned_Areas,by = join_cols)
Input=as.data.frame(Input)
return(Input)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/assign_areas.R
|
cGrid=function(Input,dlon=NA,dlat=NA,Area=NA,cuts=100,cols=c('green','yellow','red')){
if(is.na(sum(c(dlon,dlat,Area)))==FALSE){
stop('Values should not be specified for dlon/dlat and Area.')
}
if(all(is.na(c(dlon,dlat,Area)))){
stop('Values should be specified for either dlon/dlat or Area.')
}
data=Input
colnames(data)[1:2]=c("lat","lon")
#If only Lat and Lon are provided, add a 'Count' column to simply grid counts of observations
if(dim(data)[2]==2){data$Count=1}
if(is.na(Area)==TRUE){
#Prepare Lat/Lon grid
data$lon=(ceiling((data$lon+dlon)/dlon)*dlon-dlon)-dlon/2
data$lat=(ceiling((data$lat+dlat)/dlat)*dlat-dlat)-dlat/2
Glon=data$lon
Glat=data$lat
tmp=distinct(data.frame(Glon,Glat))
GLONS=tmp$Glon
GLATS=tmp$Glat
#Loop over cells to generate SpatialPolygon
Pl=list()
for (i in (1:length(GLONS))){ #Loop over polygons
xmin=GLONS[i]-dlon/2
xmax=GLONS[i]+dlon/2
ymin=GLATS[i]-dlat/2
ymax=GLATS[i]+dlat/2
if(dlon<=0.1){ #don't fortify
lons=c(xmin,xmax,xmax,xmin)
lats=c(ymax,ymax,ymin,ymin)
}else{ #do fortify
lons=c(xmin,seq(xmin,xmax,by=0.1),xmax)
lons=unique(lons)
lats=c(rep(ymax,length(lons)),rep(ymin,length(lons)))
lons=c(lons,rev(lons))
}
#close polygons
lons=c(lons,lons[1])
lats=c(lats,lats[1])
Pl[[i]]=st_polygon(list(cbind(lons,lats)))
}
Group=st_sfc(Pl, crs = 4326)
#project
Group=st_transform(x=Group,crs=6932)
#Get area
tmp=round(st_area(Group)/1000000,1)
tmp=data.frame(ID=seq(1,length(tmp)),AreaKm2=as.numeric(tmp))
Group=st_set_geometry(tmp,Group)
}else{
#Equal-area grid
Area=Area*1e6 #Convert area to sq m
s=sqrt(Area) #first rough estimate of length of cell side
PolyIndx=1 #Index of polygon (cell)
Group = list() #Initialize storage of cells
StartP=cbind(0,ceiling(max(data$lat)+0.001))
LatS=0
while(LatS>min(data$lat)){
#Compute circumference at Northern latitude of cells
NLine=st_sfc(st_linestring(cbind(seq(-180,180,length.out=10000),rep(StartP[,2],10000))), crs = 4326)
NLine=st_transform(x=NLine,crs=6932)
L=as.numeric(st_length(NLine))
#Compute number of cells
N=floor(L/s)
lx=L/N
ly=Area/lx
#Prepare cell boundaries
Lons=seq(-180,180,length.out=N)
LatN=StartP[1,2]
#Get preliminary LatS by buffering point
LatSpoint=create_Points(Input=data.frame(Lat=LatN,Lon=Lons[1]),Buffer = ly/1852)
LatSpoint=sf::st_transform(LatSpoint,4326)
LatS=as.numeric(sf::st_bbox(LatSpoint)$ymin)
# LatS=as.numeric(geosphere::destPoint(cbind(Lons[1],LatN), 180, d=ly)[,2]) #old method
#Refine LatS
lons=unique(c(Lons[1],seq(Lons[1],Lons[2],by=0.1),Lons[2]))
PLon=c(lons,rev(lons),lons[1])
PLat=c(rep(LatN,length(lons)),rep(LatS,length(lons)),LatN)
PRO=project_data(Input = data.frame(Lat=PLat,Lon=PLon),
NamesIn = c("Lat","Lon"),NamesOut = c("y","x"),append = FALSE)
Pl=st_polygon(list(cbind(PRO$x,PRO$y)))
Pl_a=st_area(Pl)
Res=10/10^(0:15)
while(Area>Pl_a & length(Res)!=0){
LatSBase=LatS
LatS=LatS-Res[1]
if(LatS<(-90)){
message('______________________________________________________________________________','\n')
message('Southern-most grid cells should not extend below -90deg to maintain equal-area','\n')
message('Reduce desired area of cells to avoid this issue','\n')
message('______________________________________________________________________________','\n')
LatS=-90
break}
PLat=c(rep(LatN,length(lons)),rep(LatS,length(lons)),LatN)
PRO=project_data(Input = data.frame(Lat=PLat,Lon=PLon),
NamesIn = c("Lat","Lon"),NamesOut = c("y","x"),append = FALSE)
Pl=st_polygon(list(cbind(PRO$x,PRO$y)))
Pl_a=st_area(Pl)
if(Area<Pl_a){
LatS=LatSBase
PLat=c(rep(LatN,length(lons)),rep(LatS,length(lons)),LatN)
PRO=project_data(Input = data.frame(Lat=PLat,Lon=PLon),
NamesIn = c("Lat","Lon"),NamesOut = c("y","x"),append = FALSE)
Pl=st_polygon(list(cbind(PRO$x,PRO$y)))
Pl_a=st_area(Pl)
Res=Res[-1]
}
}
#Build polygons at a given longitude
for (i in seq(1,length(Lons)-1)) {
lons=unique(c(Lons[i],seq(Lons[i],Lons[i+1],by=0.1),Lons[i+1]))
PLon=c(lons,rev(lons),lons[1])
PLat=c(rep(LatN,length(lons)),rep(LatS,length(lons)),LatN)
PRO=project_data(Input = data.frame(Lat=PLat,Lon=PLon),
NamesIn = c("Lat","Lon"),NamesOut = c("y","x"),append = FALSE)
Pl=st_polygon(list(cbind(PRO$x,PRO$y)))
Group[[PolyIndx]] = Pl
PolyIndx=PolyIndx+1
}
rm(NLine,Pl,PRO,StartP,i,L,LatSBase,Lons,lons,lx,ly,N,PLat,PLon,Res)
StartP=cbind(0,LatS)
}
Group=st_sfc(Group, crs = 6932)
#Get area
tmp=round(st_area(Group)/1000000,1)
tmp=data.frame(ID=seq(1,length(tmp)),AreaKm2=as.numeric(tmp))
Group=st_set_geometry(tmp,Group)
}
#Add cell labels centers
#Get labels locations
labs=st_coordinates(st_centroid(st_geometry(Group)))
Group$Centrex=labs[,1]
Group$Centrey=labs[,2]
#project to get Lat/Lon of centres
CenLL=project_data(Input=st_drop_geometry(Group),NamesIn=c('Centrey','Centrex'),
NamesOut = c('Centrelat','Centrelon'),append = FALSE,inv=TRUE)
Group$Centrelon=CenLL$Centrelon
Group$Centrelat=CenLL$Centrelat
rm(CenLL)
#Match data to grid cells
tmp_p=project_data(Input=data,NamesIn=c('lat','lon'),NamesOut = c('y','x'),append = FALSE,inv=FALSE)
tmp_p=st_as_sf(x=tmp_p,coords=c(2,1),crs=6932,remove=TRUE)
tmp=sapply(st_intersects(tmp_p,Group), function(z) if (length(z)==0) NA_integer_ else z[1]) #sp::over replacement
#Look for un-assigned data points (falling on an edge between cells)
Iout=which(is.na(tmp)==TRUE) #Index of those falling out
DegDev=0
while(length(Iout)>0){
tmp=tmp[-Iout]
datatmp=data[Iout,]
data=data[-Iout,]
Mov=c(-(0.0001+DegDev),0.0001+DegDev)
MovLat=Mov[sample(c(1,2),length(Iout),replace = TRUE)]
MovLon=Mov[sample(c(1,2),length(Iout),replace = TRUE)]
datatmp$lat=datatmp$lat+MovLat
datatmp$lon=datatmp$lon+MovLon
data=rbind(data,datatmp)
tmptmp_p=project_data(Input=datatmp,NamesIn=c('lat','lon'),NamesOut = c('y','x'),append = FALSE,inv=FALSE)
tmptmp_p=st_as_sf(x=tmptmp_p,coords=c(2,1),crs=6932,remove=TRUE)
tmptmp=sapply(st_intersects(tmptmp_p,Group), function(z) if (length(z)==0) NA_integer_ else z[1]) #sp::over replacement
tmp=c(tmp,tmptmp)
rm(datatmp,tmptmp)
DegDev=DegDev+0.0001
Iout=which(is.na(tmp)==TRUE) #Index of those falling out
}
#Append cell ID to data
data$ID=as.character(tmp)
rm(tmp)
Group=Group[Group$ID%in%unique(data$ID),]
#Summarise data
data=as.data.frame(data[,-c(1,2)])
nums = which(unlist(lapply(data, is.numeric))==TRUE)
if(length(nums)>0){
data=data[,c(which(colnames(data)=='ID'),nums)]
Sdata=data%>%
group_by(ID)%>%
summarise_all(list(min=~min(.,na.rm=TRUE),
max=~max(.,na.rm=TRUE),
mean=~mean(.,na.rm=TRUE),
sum=~sum(.,na.rm=TRUE),
count=~length(.),
sd=~sd(.,na.rm=TRUE),
median=~median(.,na.rm=TRUE)))
Sdata=as.data.frame(Sdata)}else{Sdata=data.frame(ID=as.character(unique(data$ID)))}
#Merge data to Polygons
Group$ID=as.character(Group$ID)
Group=dplyr::left_join(Group,Sdata,by="ID")
#Add colors
GroupData=st_drop_geometry(Group)
VarToColor=which(unlist(lapply(GroupData, class))%in%c("integer","numeric"))
VarNotToColor=which(colnames(GroupData)%in%c("Centrex","Centrey","Centrelon","Centrelat"))
VarToColor=VarToColor[-which(VarToColor%in%VarNotToColor)]
for(i in VarToColor){
coldata=GroupData[,i]
if(all(is.na(coldata))){
Group[,paste0('Col_',colnames(GroupData)[i])]=NA
}else{
tmp=add_col(var=coldata,cuts=cuts,cols=cols)
Group[,paste0('Col_',colnames(GroupData)[i])]=tmp$varcol
}
}
return(Group)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/cGrid.R
|
cLines=function(Input,Densify=FALSE){
#Build Line list
Ll=list()
Input[,1]=as.character(Input[,1])
ids=unique(Input[,1])
Llengths=NULL
for(i in seq(1,length(ids))){
indx=which(Input[,1]==ids[i])
lons=Input[indx,3]
lats=Input[indx,2]
diflons=abs(diff(lons))
if(length(diflons)>1){diflons=max(abs(diflons[diflons!=0]))}
if(length(diflons)==0){diflons=0}
if(diflons>0.1 & Densify==TRUE){
tmp=DensifyData(lons,lats)
lons=tmp[,1]
lats=tmp[,2]
}
Ll[[i]]=st_linestring(cbind(lons,lats))
Llengths=rbind(Llengths,cbind(id=as.character(ids[i]),
L=as.numeric(st_length(st_sfc(Ll[[i]], crs = 4326)))/1000))
}
Locs=st_sfc(Ll, crs = 4326)
#Format lengths
Llengths=as.data.frame(Llengths)
Llengths$id=as.character(Llengths$id)
Llengths$L=as.numeric(as.character(Llengths$L))
Llengths$LengthKm=round(Llengths$L,4)
Llengths$LengthNm=round(Llengths$L/1.852,4)
#Summarise data
Input=as.data.frame(Input[,-c(2,3)])
colnames(Input)[1]='ID'
nums = which(unlist(lapply(Input, is.numeric))==TRUE)
if(length(nums)>0){
Input=Input[,c(1,nums)]
Sdata=Input%>%
group_by(ID)%>%
summarise_all(list(min=~min(.,na.rm=TRUE),
max=~max(.,na.rm=TRUE),
mean=~mean(.,na.rm=TRUE),
sum=~sum(.,na.rm=TRUE),
count=~length(.),
sd=~sd(.,na.rm=TRUE),
median=~median(.,na.rm=TRUE)))
#add line lengths
Sdata=as.data.frame(Sdata)}else{Sdata=data.frame(ID=as.character(unique(Input$ID)))}
if(length(ids)>1 & ncol(Sdata)>1){
Sdata=Sdata[match(ids,Sdata$ID),]
}
indx=match(Sdata$ID,Llengths$id)
Sdata$LengthKm=Llengths$LengthKm[indx]
Sdata$LengthNm=Llengths$LengthNm[indx]
#Merge data to SpatialLines
row.names(Sdata)=Sdata$ID
Locs=st_set_geometry(Sdata,Locs)
#Project
Locs=st_transform(x=Locs,crs=6932)
return(Locs)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/cLines.R
|
cPoints=function(Input){
Locs=st_as_sf(x=Input,coords=c(2,1),crs=4326,remove=FALSE)
Locs=st_transform(x=Locs,crs=6932)
tmp=st_coordinates(Locs)
Locs$x=tmp[,1]
Locs$y=tmp[,2]
Locs$ID=seq(1,length(Locs$x))
return(Locs)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/cPoints.R
|
cPolys=function(Input,Densify=FALSE){
#Build Poly list
Pl=list()
Input[,1]=as.character(Input[,1])
ids=unique(Input[,1])
for(i in seq(1,length(ids))){
indx=which(Input[,1]==ids[i])
indx=c(indx,indx[1])
lons=Input[indx,3]
lats=Input[indx,2]
diflons=abs(diff(lons))
if(length(diflons)>1){diflons=max(abs(diflons[diflons!=0]))}
if(length(diflons)==0){diflons=0}
if(diflons>0.1 & Densify==TRUE){
tmp=DensifyData(lons,lats)
lons=tmp[,1]
lats=tmp[,2]
}
Pl[[i]]=st_polygon(list(cbind(lons,lats)))
}
Locs=st_sfc(Pl, crs = 4326)
#Summarise data
Input=as.data.frame(Input[,-c(2,3)])
colnames(Input)[1]='ID'
nums = which(unlist(lapply(Input, is.numeric))==TRUE)
if(length(nums)>0){
Input=Input[,c(1,nums)]
Sdata=Input%>%
group_by(ID)%>%
summarise_all(list(min=~min(.,na.rm=TRUE),
max=~max(.,na.rm=TRUE),
mean=~mean(.,na.rm=TRUE),
sum=~sum(.,na.rm=TRUE),
count=~length(.),
sd=~sd(.,na.rm=TRUE),
median=~median(.,na.rm=TRUE)))
Sdata=as.data.frame(Sdata)}else{Sdata=data.frame(ID=as.character(unique(Input$ID)))}
#Merge data to polys
row.names(Sdata)=Sdata$ID
if(length(ids)>1 & ncol(Sdata)>1){
Sdata=Sdata[match(ids,Sdata$ID),]
}
Locs=st_set_geometry(Sdata,Locs)
#Project
Locs=st_transform(x=Locs,crs=6932)
#Get areas
Ar=round(st_area(Locs)/1000000,1)
Locs$AreaKm2=as.numeric(Ar)
#Get labels locations
labs=st_coordinates(st_centroid(st_geometry(Locs)))
Locs$Labx=labs[,1]
Locs$Laby=labs[,2]
return(Locs)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/cPolys.R
|
#' Create Polygons
#'
#' Create Polygons such as proposed Research Blocks or Marine Protected Areas.
#'
#' @param Input input dataframe.
#'
#' If \code{NamesIn} is not provided, the columns in the \code{Input} must be in the following order:
#'
#' Polygon name, Latitude, Longitude.
#'
#' Latitudes and Longitudes must be given clockwise.
#'
#' @param NamesIn character vector of length 3 specifying the column names of polygon identifier, Latitude
#' and Longitude fields in the \code{Input}.
#'
#' Names must be given in that order, e.g.:
#'
#' \code{NamesIn=c('Polygon ID','Poly Latitudes','Poly Longitudes')}.
#'
#' @param Buffer numeric, distance in nautical miles by which to expand the polygons. Can be specified for
#' each polygon (as a numeric vector).
#' @param SeparateBuf logical, if set to FALSE when adding a \code{Buffer},
#' all spatial objects are merged, resulting in a single spatial object.
#' @param Densify logical, if set to TRUE, additional points between extremities of lines spanning more
#' than 0.1 degree longitude are added at every 0.1 degree of longitude prior to projection
#' (compare examples 1 and 2 below).
#' @param Clip logical, if set to TRUE, polygon parts that fall on land are removed (see \link{Clip2Coast}).
#'
#' @return Spatial object in your environment.
#' Data within the resulting spatial object contains the data provided in the \code{Input} after aggregation
#' within polygons. For each numeric variable, the minimum, maximum, mean, sum, count, standard deviation, and,
#' median of values in each polygon is returned. In addition, for each polygon, its area (AreaKm2) and projected
#' centroid (Labx, Laby) are given (which may be used to add labels to polygons).
#'
#' To see the data contained in your spatial object, type: \code{View(MyPolygons)}.
#'
#' @seealso
#' \code{\link{create_Points}}, \code{\link{create_Lines}}, \code{\link{create_PolyGrids}},
#' \code{\link{create_Stations}}, \code{\link{add_RefGrid}}.
#'
#' @examples
#' \donttest{
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#create-polygons
#'
#'
#' #Densified polygons (note the curvature of lines)
#'
#' MyPolys=create_Polys(Input=PolyData)
#' plot(st_geometry(MyPolys),col='red')
#' text(MyPolys$Labx,MyPolys$Laby,MyPolys$ID,col='white')
#'
#'
#' }
#'
#' @export
create_Polys=function(Input,NamesIn=NULL,Buffer=0,Densify=TRUE,Clip=FALSE,SeparateBuf=TRUE){
# Load data
Input=as.data.frame(Input)
#Use NamesIn to reorder columns
if(is.null(NamesIn)==FALSE){
if(length(NamesIn)!=3){stop("'NamesIn' should be a character vector of length 3")}
if(any(NamesIn%in%colnames(Input)==FALSE)){stop("'NamesIn' do not match column names in 'Input'")}
Input=Input[,c(NamesIn,colnames(Input)[which(!colnames(Input)%in%NamesIn)])]
}
# Run cPolys
Output=cPolys(Input,Densify=Densify)
# Run add_buffer
if(length(Buffer)==1){
if(Buffer>0){Output=add_buffer(Output,buf=Buffer,SeparateBuf=SeparateBuf)}
}else{
Output=add_buffer(Output,buf=Buffer,SeparateBuf=SeparateBuf)
}
# Run Clip2Coast
if(Clip==TRUE){Output=Clip2Coast(Output)}
return(Output)
}
#' Create a Polygon Grid
#'
#' Create a polygon grid to spatially aggregate data in cells of chosen size.
#' Cell size may be specified in degrees or as a desired area in square kilometers
#' (in which case cells are of equal area).
#'
#' @param Input input dataframe.
#'
#' If \code{NamesIn} is not provided, the columns in the \code{Input} must be in the following order:
#'
#' Latitude, Longitude, Variable 1, Variable 2 ... Variable x.
#'
#' @param NamesIn character vector of length 2 specifying the column names of Latitude and Longitude fields in
#' the \code{Input}. Latitudes name must be given first, e.g.:
#'
#' \code{NamesIn=c('MyLatitudes','MyLongitudes')}.
#'
#' @param dlon numeric, width of the grid cells in decimal degrees of longitude.
#' @param dlat numeric, height of the grid cells in decimal degrees of latitude.
#' @param Area numeric, area in square kilometers of the grid cells. The smaller the \code{Area}, the longer it will take.
#' @param cuts numeric, number of desired color classes.
#' @param cols character, desired colors. If more that one color is provided, a linear color gradient is generated.
#' @return Spatial object in your environment.
#' Data within the resulting spatial object contains the data provided in the \code{Input} after aggregation
#' within cells. For each Variable, the minimum, maximum, mean, sum, count, standard deviation, and,
#' median of values in each cell is returned. In addition, for each cell, its area (AreaKm2), projected
#' centroid (Centrex, Centrey) and unprojected centroid (Centrelon, Centrelat) is given.
#'
#' To see the data contained in your spatial object, type: \code{View(MyGrid)}.
#'
#' Also, colors are generated for each aggregated values according to the chosen \code{cuts}
#' and \code{cols}.
#'
#' To generate a custom color scale after the grid creation, refer to \code{\link{add_col}} and
#' \code{\link{add_Cscale}}. See Example 4 below.
#'
#' @seealso
#' \code{\link{create_Points}}, \code{\link{create_Lines}}, \code{\link{create_Polys}},
#' \code{\link{create_Stations}}, \code{\link{create_Pies}}, \code{\link{add_col}}, \code{\link{add_Cscale}}.
#'
#' @examples
#' \donttest{
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#create-grids
#' # And:
#' # https://github.com/ccamlr/CCAMLRGIS/blob/master/Advanced_Grids/Advanced_Grids.md
#'
#' #Simple grid, using automatic colors
#'
#' MyGrid=create_PolyGrids(Input=GridData,dlon=2,dlat=1)
#' #View(MyGrid)
#' plot(st_geometry(MyGrid),col=MyGrid$Col_Catch_sum)
#'
#'
#' }
#'
#' @export
create_PolyGrids=function(Input,NamesIn=NULL,dlon=NA,dlat=NA,Area=NA,cuts=100,cols=c('green','yellow','red')){
Input=as.data.frame(Input)
#Use NamesIn to reorder columns
if(is.null(NamesIn)==FALSE){
if(length(NamesIn)!=2){stop("'NamesIn' should be a character vector of length 2")}
if(any(NamesIn%in%colnames(Input)==FALSE)){stop("'NamesIn' do not match column names in 'Input'")}
Input=Input[,c(NamesIn,colnames(Input)[which(!colnames(Input)%in%NamesIn)])]
}
#Run cGrid
Output=cGrid(Input,dlon=dlon,dlat=dlat,Area=Area,cuts=cuts,cols=cols)
return(Output)
}
#' Create Lines
#'
#' Create lines to display, for example, fishing line locations or tagging data.
#'
#' @param Input input dataframe.
#'
#' If \code{NamesIn} is not provided, the columns in the \code{Input} must be in the following order:
#'
#' Line name, Latitude, Longitude.
#'
#' If a given line is made of more than two points, the locations of points
#' must be given in order, from one end of the line to the other.
#'
#' @param NamesIn character vector of length 3 specifying the column names of line identifier, Latitude
#' and Longitude fields in the \code{Input}.
#'
#' Names must be given in that order, e.g.:
#'
#' \code{NamesIn=c('Line ID','Line Latitudes','Line Longitudes')}.
#'
#' @param Buffer numeric, distance in nautical miles by which to expand the lines. Can be specified for
#' each line (as a numeric vector).
#' @param Densify logical, if set to TRUE, additional points between extremities of lines spanning more
#' than 0.1 degree longitude are added at every 0.1 degree of longitude prior to projection (see examples).
#' @param Clip logical, if set to TRUE, polygon parts (from buffered lines) that fall on land are removed (see \link{Clip2Coast}).
#' @param SeparateBuf logical, if set to FALSE when adding a \code{Buffer},
#' all spatial objects are merged, resulting in a single spatial object.
#'
#' @return Spatial object in your environment.
#' Data within the resulting spatial object contains the data provided in the \code{Input} plus
#' additional "LengthKm" and "LengthNm" columns which corresponds to the lines lengths,
#' in kilometers and nautical miles respectively. If additional data was included in the \code{Input},
#' any numerical values are summarized for each line (min, max, mean, median, sum, count and sd).
#'
#' To see the data contained in your spatial object, type: \code{View(MyLines)}.
#'
#' @seealso
#' \code{\link{create_Points}}, \code{\link{create_Polys}}, \code{\link{create_PolyGrids}},
#' \code{\link{create_Stations}}, \code{\link{create_Pies}}.
#'
#' @examples
#' \donttest{
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#create-lines
#'
#' #Densified lines (note the curvature of the lines)
#'
#' MyLines=create_Lines(Input=LineData,Densify=TRUE)
#' plot(st_geometry(MyLines),lwd=2,col=rainbow(nrow(MyLines)))
#'
#' }
#'
#' @export
create_Lines=function(Input,NamesIn=NULL,Buffer=0,Densify=FALSE,Clip=FALSE,SeparateBuf=TRUE){
# Load data
Input=as.data.frame(Input)
#Use NamesIn to reorder columns
if(is.null(NamesIn)==FALSE){
if(length(NamesIn)!=3){stop("'NamesIn' should be a character vector of length 3")}
if(any(NamesIn%in%colnames(Input)==FALSE)){stop("'NamesIn' do not match column names in 'Input'")}
Input=Input[,c(NamesIn,colnames(Input)[which(!colnames(Input)%in%NamesIn)])]
}
# Run cLines
Output=cLines(Input,Densify=Densify)
# Run add_buffer
if(length(Buffer)==1){
if(Buffer>0){Output=add_buffer(Output,buf=Buffer,SeparateBuf=SeparateBuf)}
}else{
Output=add_buffer(Output,buf=Buffer,SeparateBuf=SeparateBuf)
}
# Run Clip2Coast
if(Clip==TRUE){Output=Clip2Coast(Output)}
return(Output)
}
#' Create Points
#'
#' Create Points to display point locations. Buffering points may be used to produce bubble charts.
#'
#' @param Input input dataframe.
#'
#' If \code{NamesIn} is not provided, the columns in the \code{Input} must be in the following order:
#'
#' Latitude, Longitude, Variable 1, Variable 2, ... Variable x.
#'
#' @param NamesIn character vector of length 2 specifying the column names of Latitude and Longitude fields in
#' the \code{Input}. Latitudes name must be given first, e.g.:
#'
#' \code{NamesIn=c('MyLatitudes','MyLongitudes')}.
#'
#' @param Buffer numeric, radius in nautical miles by which to expand the points. Can be specified for
#' each point (as a numeric vector).
#' @param Clip logical, if set to TRUE, polygon parts (from buffered points) that fall on land are removed (see \link{Clip2Coast}).
#' @param SeparateBuf logical, if set to FALSE when adding a \code{Buffer},
#' all spatial objects are merged, resulting in a single spatial object.
#'
#' @return Spatial object in your environment.
#' Data within the resulting spatial object contains the data provided in the \code{Input} plus
#' additional "x" and "y" columns which corresponds to the projected points locations
#' and may be used to label points (see examples).
#'
#' To see the data contained in your spatial object, type: \code{View(MyPoints)}.
#'
#' @seealso
#' \code{\link{create_Lines}}, \code{\link{create_Polys}}, \code{\link{create_PolyGrids}},
#' \code{\link{create_Stations}}, \code{\link{create_Pies}}.
#'
#' @examples
#' \donttest{
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#create-points
#'
#' #Simple points with labels
#'
#' MyPoints=create_Points(Input=PointData)
#' plot(st_geometry(MyPoints))
#' text(MyPoints$x,MyPoints$y,MyPoints$name,adj=c(0.5,-0.5),xpd=TRUE)
#'
#'
#'
#' }
#'
#' @export
create_Points=function(Input,NamesIn=NULL,Buffer=0,Clip=FALSE,SeparateBuf=TRUE){
# Load data
Input=as.data.frame(Input)
#Use NamesIn to reorder columns
if(is.null(NamesIn)==FALSE){
if(length(NamesIn)!=2){stop("'NamesIn' should be a character vector of length 2")}
if(any(NamesIn%in%colnames(Input)==FALSE)){stop("'NamesIn' do not match column names in 'Input'")}
Input=Input[,c(NamesIn,colnames(Input)[which(!colnames(Input)%in%NamesIn)])]
}
# Run cPoints
Output=cPoints(Input)
# Run add_buffer
if(all(Buffer>0)){Output=add_buffer(Output,buf=Buffer,SeparateBuf=SeparateBuf)}
if(any(Buffer<0)){stop("'Buffer' should be positive")}
# Run Clip2Coast
if(Clip==TRUE){Output=Clip2Coast(Output)}
return(Output)
}
#' Create Stations
#'
#' Create random point locations inside a polygon and within bathymetry strata constraints.
#' A distance constraint between stations may also be used if desired.
#'
#' @param Poly single polygon inside which stations will be generated. May be created using \code{\link{create_Polys}}.
#' @param Bathy bathymetry raster with the appropriate \code{\link[CCAMLRGIS:CCAMLRp]{projection}}, such as \code{\link[CCAMLRGIS:SmallBathy]{this one}}.
#' @param Depths numeric, vector of depths. For example, if the depth strata required are 600 to 1000 and 1000 to 2000,
#' \code{Depths=c(-600,-1000,-2000)}.
#' @param N numeric, vector of number of stations required in each depth strata,
#' therefore \code{length(N)} must equal \code{length(Depths)-1}.
#' @param Nauto numeric, instead of specifying \code{N}, a number of stations proportional to the areas of the depth strata
#' may be created. \code{Nauto} is the maximum number of stations required in any depth stratum.
#' @param dist numeric, if desired, a distance constraint in nautical miles may be applied. For example, if \code{dist=2},
#' stations will be at least 2 nautical miles apart.
#' @param Buf numeric, distance in meters from isobaths. Useful to avoid stations falling on strata boundaries.
#' @param ShowProgress logical, if set to \code{TRUE}, a progress bar is shown (\code{create_Stations} may take a while).
#' @return Spatial object in your environment. Data within the resulting object contains the strata and stations
#' locations in both projected space ("x" and "y") and decimal degrees of Latitude/Longitude.
#'
#' To see the data contained in your spatial object, type: \code{View(MyStations)}.
#'
#' @seealso
#' \code{\link{create_Polys}}, \code{\link{SmallBathy}}.
#'
#' @examples
#' \donttest{
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#22-create-stations
#'
#' #First, create a polygon within which stations will be created
#' MyPoly=create_Polys(
#' data.frame(Name="mypol",
#' Latitude=c(-75,-75,-70,-70),
#' Longitude=c(-170,-180,-180,-170))
#' ,Densify=TRUE)
#'
#' par(mai=c(0,0,0,0))
#' plot(st_geometry(Coast[Coast$ID=='88.1',]),col='grey')
#' plot(st_geometry(MyPoly),col='green',add=TRUE)
#' text(MyPoly$Labx,MyPoly$Laby,MyPoly$ID)
#'
#' #Create a set numbers of stations, without distance constraint:
#' library(terra)
#' #optional: crop your bathymetry raster to match the extent of your polygon
#' BathyCroped=crop(SmallBathy(),ext(MyPoly))
#'
#' #Create stations
#' MyStations=create_Stations(MyPoly,BathyCroped,Depths=c(-2000,-1500,-1000,-550),N=c(20,15,10))
#'
#' #add custom colors to the bathymetry to indicate the strata of interest
#' MyCols=add_col(var=c(-10000,10000),cuts=c(-2000,-1500,-1000,-550),cols=c('blue','cyan'))
#' plot(BathyCroped,breaks=MyCols$cuts,col=MyCols$cols,legend=FALSE,axes=FALSE)
#' add_Cscale(height=90,fontsize=0.75,width=16,lwd=0.5,
#' offset=-130,cuts=MyCols$cuts,cols=MyCols$cols)
#' plot(st_geometry(MyPoly),add=TRUE,border='red',lwd=2,xpd=TRUE)
#' plot(st_geometry(MyStations),add=TRUE,col='orange',cex=0.75,lwd=1.5,pch=3)
#'
#'
#' }
#'
#' @export
create_Stations=function(Poly,Bathy,Depths,N=NA,Nauto=NA,dist=NA,Buf=1000,ShowProgress=FALSE){
if(is.na(sum(N))==FALSE & is.na(Nauto)==FALSE){
stop('Values should not be specified for both N and Nauto.')
}
if(is.na(sum(N))==FALSE & length(N)!=length(Depths)-1){
stop('Incorrect number of stations specified.')
}
if(class(Poly)[1]!="sf"){
stop("'Poly' must be an sf object")
}
if(class(Bathy)[1]!="SpatRaster"){
Bathy=terra::rast(Bathy)
}
#Crop Bathy
Bathy=terra::crop(Bathy,terra::extend(ext(Poly),10000))
#Generate Isobaths polygons
IsoDs=data.frame(top=Depths[1:(length(Depths)-1)],
bot=Depths[2:length(Depths)])
IsoNames=paste0(abs(IsoDs$top),'-',abs(IsoDs$bot))
#start with first strata, then loop over remainder
if(ShowProgress==TRUE){
message('Depth strata creation started',sep='\n')
pb=txtProgressBar(min=0,max=dim(IsoDs)[1],style=3,char=" )>(((*> ")
}
Biso=terra::clamp(Bathy,lower=IsoDs$top[1], upper=IsoDs$bot[1],values=FALSE)
Biso=terra::classify(Biso,cbind(IsoDs$top[1],IsoDs$bot[1],1),include.lowest=TRUE)
Isos=terra::as.polygons(Biso,values=FALSE)
Isos$Stratum=IsoNames[1]
if(ShowProgress==TRUE){setTxtProgressBar(pb, 1)}
if(dim(IsoDs)[1]>1){
for(i in seq(2,dim(IsoDs)[1])){
Biso=terra::clamp(Bathy,lower=IsoDs$top[i], upper=IsoDs$bot[i],values=FALSE)
Biso=terra::classify(Biso,cbind(IsoDs$top[i],IsoDs$bot[i],1),include.lowest=TRUE)
Isotmp=terra::as.polygons(Biso,values=FALSE)
Isotmp$Stratum=IsoNames[i]
Isos=rbind(Isos,Isotmp)
if(ShowProgress==TRUE){setTxtProgressBar(pb, i)}
}
}
if(ShowProgress==TRUE){
message('\n')
message('Depth strata creation ended',sep='\n')
close(pb)
}
#crop Isos by Poly
Isos=sf::st_as_sf(Isos)
Poly=sf::st_as_sf(Poly)
st_crs(Isos)=6932
Poly=st_transform(Poly,crs=6932)
Isos=st_make_valid(Isos)
Isos=sf::st_intersection(st_geometry(Poly),Isos)
#Get number of stations per strata
if(is.na(Nauto)==TRUE){
IsoDs$n=N
}else{
#Get area of strata
ar=as.numeric(st_area(Isos))
ar=ar/max(ar)
IsoDs$n=round(ar*Nauto)
}
#Generate locations
#Create a fine grid from which to sample from
if(ShowProgress==TRUE){
message('Station creation started',sep='\n')
pb=txtProgressBar(min=0,max=dim(IsoDs)[1],style=3,char=" )>(((*> ")
}
Grid=st_make_grid(x=Isos,cellsize = 1000,what="centers")
#Remove points outside of strata
Gridtmp=NULL
for(i in seq(1,dim(IsoDs)[1])){
tmp=st_buffer(Isos[[i]],dist=-Buf)
tmp=st_sfc(tmp, crs = 6932)
GridL=unlist(sf::st_intersects(tmp,Grid))
Gridtmp=rbind(Gridtmp,cbind(st_coordinates(Grid)[GridL,],i))
}
Grid=as.data.frame(Gridtmp)
Grid=st_as_sf(x=Grid,coords=c(1,2),crs=6932,remove=FALSE)
if(is.na(dist)==TRUE){ #Random locations
Locs=NULL
for(i in seq(1,dim(IsoDs)[1])){
Locs=rbind(Locs,cbind(Grid[Grid$i==i,][sample(seq(1,length(which(Grid$i==i))),IsoDs$n[i]),]))
if(ShowProgress==TRUE){setTxtProgressBar(pb, i)}
}
Locs$Stratum=IsoNames[Locs$i]
#Add Lat/Lon
Locs=project_data(Input=Locs,NamesIn = c('Y','X'),NamesOut = c('Lat','Lon'),append = TRUE,inv=TRUE)
Stations=st_as_sf(x=Locs,coords=c('X','Y'),crs=6932,remove=FALSE)
if(ShowProgress==TRUE){
message('\n')
message('Station creation ended',sep='\n')
close(pb)
}
}else{ #Pseudo-random locations
#Get starting point
indx=floor(dim(Grid)[1]/2)
tmpx=Grid$X[indx]
tmpy=Grid$Y[indx]
lay=Grid$i[indx]
#Set buffer width
wdth=100*ceiling(1852*dist/100)
Locs=NULL
while(nrow(Grid)>0){
smallB=st_buffer(st_as_sf(x=data.frame(tmpx,tmpy),coords=c(1,2),crs=6932),dist = wdth,nQuadSegs=25)
smallBi=unlist(st_intersects(smallB,Grid))
#Save central point locations
Locs=rbind(Locs,cbind(tmpx,tmpy,lay))
#Remove points within buffer
Grid=Grid[-smallBi,]
#Get new point
if(nrow(Grid)>0){
indx=as.numeric(sample(seq(1,nrow(Grid)),1))
tmpx=Grid$X[indx]
tmpy=Grid$Y[indx]
lay=Grid$i[indx]
}
}
Locs=data.frame(layer=Locs[,3],
Stratum=IsoNames[Locs[,3]],
x=Locs[,1],
y=Locs[,2])
Locs$Stratum=as.character(Locs$Stratum)
#Report results
message('\n')
for(s in sort(unique(Locs$layer))){
ns=length(which(Locs$layer==s))
message(paste0('Stratum ',IsoNames[s],' may contain up to ',ns,' stations given the distance desired'),sep='\n')
}
message('\n')
for(s in sort(unique(Locs$layer))){
ns=length(which(Locs$layer==s))
if(ns<IsoDs$n[s]){
stop('Cannot generate stations given the constraints. Reduce dist and/or number of stations and/or Buf.')
}
}
#Sample locs within constraints
indx=NULL
for(i in sort(unique(Locs$layer))){
indx=c(indx,sample(which(Locs$layer==i),IsoDs$n[i]))
}
Locs=Locs[indx,]
#Add Lat/Lon
Locs=project_data(Input=Locs,NamesIn = c('y','x'),NamesOut = c('Lat','Lon'),append = TRUE,inv=TRUE)
Stations=st_as_sf(x=Locs,coords=c('x','y'),crs=6932,remove=FALSE)
if(ShowProgress==TRUE){
message('\n')
message('Station creation ended',sep='\n')
close(pb)
}
}
#Check results
ns=NULL
for(i in sort(unique(Stations$layer))){
ns=c(ns,length(which(Stations$layer==i)))
}
if(sum(ns-IsoDs$n)!=0){
stop('Something unexpected happened. Please report the error to the package maintainer')
}
return(Stations)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/create.R
|
#' Create Arrow
#'
#' Create an arrow which can be curved and/or segmented.
#'
#' @param Input input dataframe with at least two columns (Latitudes then Longitudes) and an
#' optional third column for weights. First row is the location of the start of the arrow,
#' Last row is the location of the end of the arrow (where the arrow will point to). Optional
#' intermediate rows are the locations of points towards which the arrow's path will bend.
#' Weights (third column) can be added to the intermediate points to make the arrow's path
#' bend more towards them.
#'
#' @param Np integer, number of additional points generated to create a curved path. If the
#' arrow's path appears too segmented, increase \code{Np}.
#'
#' @param Pwidth numeric, width of the arrow's path.
#'
#' @param Hlength numeric, length of the arrow's head.
#'
#' @param Hwidth numeric, width of the arrow's head.
#'
#' @param dlength numeric, length of dashes for dashed arrows.
#'
#' @param Atype character, arrow type either "normal" or "dashed". A normal arrow is a single polygon,
#' with a single color (set by \code{Acol}) and transparency (set by \code{Atrans}). A dashed arrow
#' is a series of polygons which can be colored separately by setting two or more values as
#' \code{Acol=c("color start","color end")} and two or more transparency values as
#' \code{Atrans=c("transparency start","transparency end")}. The length of dashes is controlled
#' by \code{dlength}.
#'
#' @param Acol Color of the arrow, see \code{Atype} above.
#'
#' @param Atrans Numeric, transparency of the arrow, see \code{Atype} above.
#'
#' @return Spatial object in your environment with colors included in the dataframe (see examples).
#'
#' @seealso
#' \code{\link{create_Points}}, \code{\link{create_Lines}}, \code{\link{create_Polys}},
#' \code{\link{create_PolyGrids}}, \code{\link{create_Stations}}, \code{\link{create_Pies}}.
#'
#' @examples
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#24-create-arrow
#'
#' #Example 1: straight green arrow
#' myInput=data.frame(lat=c(-61,-52),
#' lon=c(-60,-40))
#' Arrow=create_Arrow(Input=myInput)
#' plot(st_geometry(Arrow),col=Arrow$col,main="Example 1")
#'
#'
#' #Example 2: blue arrow with one bend
#' myInput=data.frame(lat=c(-61,-65,-52),
#' lon=c(-60,-45,-40))
#' Arrow=create_Arrow(Input=myInput,Acol="lightblue")
#' plot(st_geometry(Arrow),col=Arrow$col,main="Example 2")
#'
#' #Example 3: blue arrow with two bends
#' myInput=data.frame(lat=c(-61,-60,-65,-52),
#' lon=c(-60,-50,-45,-40))
#' Arrow=create_Arrow(Input=myInput,Acol="lightblue")
#' plot(st_geometry(Arrow),col=Arrow$col,main="Example 3")
#'
#' #Example 4: blue arrow with two bends, with more weight on the second bend
#' #and a big head
#' myInput=data.frame(lat=c(-61,-60,-65,-52),
#' lon=c(-60,-50,-45,-40),
#' w=c(1,1,2,1))
#' Arrow=create_Arrow(Input=myInput,Acol="lightblue",Hlength=20,Hwidth=20)
#' plot(st_geometry(Arrow),col=Arrow$col,main="Example 4")
#'
#' #Example 5: Dashed arrow, small dashes
#' myInput=data.frame(lat=c(-61,-60,-65,-52),
#' lon=c(-60,-50,-45,-40),
#' w=c(1,1,2,1))
#' Arrow=create_Arrow(Input=myInput,Acol="blue",Atype = "dashed",dlength = 1)
#' plot(st_geometry(Arrow),col=Arrow$col,main="Example 5",border=NA)
#'
#' #Example 6: Dashed arrow, big dashes
#' myInput=data.frame(lat=c(-61,-60,-65,-52),
#' lon=c(-60,-50,-45,-40),
#' w=c(1,1,2,1))
#' Arrow=create_Arrow(Input=myInput,Acol="blue",Atype = "dashed",dlength = 2)
#' plot(st_geometry(Arrow),col=Arrow$col,main="Example 6",border=NA)
#'
#' #Example 7: Dashed arrow, no dashes, 3 colors and transparency gradient
#' myInput=data.frame(lat=c(-61,-60,-65,-52),
#' lon=c(-60,-50,-45,-40),
#' w=c(1,1,2,1))
#' Arrow=create_Arrow(Input=myInput,Acol=c("red","green","blue"),
#' Atrans = c(0,0.9,0),Atype = "dashed",dlength = 0)
#' plot(st_geometry(Arrow),col=Arrow$col,main="Example 7",border=NA)
#'
#' #Example 8: Same as example 7 but with more points, so smoother
#' myInput=data.frame(lat=c(-61,-60,-65,-52),
#' lon=c(-60,-50,-45,-40),
#' w=c(1,1,2,1))
#' Arrow=create_Arrow(Input=myInput,Np=200,Acol=c("red","green","blue"),
#' Atrans = c(0,0.9,0),Atype = "dashed",dlength = 0)
#' plot(st_geometry(Arrow),col=Arrow$col,main="Example 8",border=NA)
#'
#' @export
create_Arrow=function(Input,Np=50,Pwidth=5,Hlength=15,Hwidth=10,dlength=0,Atype="normal",Acol="green",Atrans=0){
if(Atype=="normal" & length(Acol)>1){
stop("A 'normal' arrow can only have one color.")
}
if(length(Acol)>1 & length(Atrans)==1){
Atrans=rep(Atrans,length(Acol))
}
if(length(Acol)!=length(Atrans)){
stop("length(Atrans) should equal length(Acol).")
}
Pwidth=Pwidth*10000
Hlength=Hlength*10000
Hwidth=Hwidth*10000
Hwidth=max(c(Pwidth,Hwidth))
Input=as.data.frame(Input)
if(ncol(Input)==2){
Input$w=1
}
Input[,3]=round(Input[,3])
if(any(is.na(Input[,3]))==TRUE){
stop("Missing weight(s) in the Input.")
}
Ps=data.frame(Lat=Input[,1],Lon=Input[,2],w=Input[,3])
if(nrow(Input)>2 & length(unique(Input[,3]))>1){
Ps=Ps[rep(seq(1,nrow(Ps)),Ps$w),]
}
#Get curve
Ps=project_data(Ps,NamesIn=c("Lat","Lon"),append = FALSE)
Bs=bezier::bezier(t=seq(0,1,length=Np),p=Ps)
#Get perpendiculars
Input=data.frame(x=Bs[,2],
y=Bs[,1])
Perps=GetPerp(Input, d=Pwidth)
#Get cummulated distance between points, from the head
Bsp=sf::st_as_sf(x=as.data.frame(Bs),coords=c(2,1),crs=6932)
Ds=as.numeric(sf::st_distance(Bsp,Bsp[nrow(Bsp),]))
#Find points covering that distance
Hp=max(which(Ds>Hlength)) #Head starts between Hp and Hp+1
HL=sf::st_linestring(sf::st_coordinates(Bsp[c(Hp,Hp+1),]))
HL=sf::st_sfc(HL, crs = 6932)
#Densify that line
HLs=sf::st_line_sample(HL,n=50)
HLs=sf::st_cast(HLs,"POINT")
Ds=as.numeric(sf::st_distance(HLs,Bsp[nrow(Bsp),]))
Hp2=max(which(Ds>Hlength))
if(Hp2==length(HLs)){
stop("Please reduce Np.")
}
Hp2=sf::st_coordinates(HLs)[c(Hp2,Hp2+1),] #Head center start
#Build cropper
Input=data.frame(x=c(Hp2[2,1],Bs[(Hp+1):nrow(Bs),2]),
y=c(Hp2[2,2],Bs[(Hp+1):nrow(Bs),1]))
Cro=GetPerp(Input, d=Pwidth+1)
x=Cro$x
y=Cro$y
ci=grDevices::chull(x,y)
x=x[ci]
y=y[ci]
x=c(x,x[1])
y=c(y,y[1])
Cro=sf::st_polygon(list(cbind(x,y)))
#Build head
Input=data.frame(x=c(Hp2[,1],Bs[(Hp+1):nrow(Bs),2]),
y=c(Hp2[,2],Bs[(Hp+1):nrow(Bs),1]))
Hea=GetPerp(Input, d=Hwidth)
Hea=Hea[1:2,]
x=c(Hea$x,Bs[nrow(Bs),2])
y=c(Hea$y,Bs[nrow(Bs),1])
ci=grDevices::chull(x,y)
x=x[ci]
y=y[ci]
x=c(x,x[1])
y=c(y,y[1])
Hea=sf::st_polygon(list(cbind(x,y)))
#Loop over perps to build squares
Seqs=seq(1, nrow(Perps)-2,by=2)
Seqs=Seqs[-length(Seqs)]
if(dlength>0){
dlength=round(dlength)
itmp=rep(c(1,0),each=dlength,length.out=length(Seqs))
Seqs=Seqs[itmp==1]
}
Pl=list()
np=1
for(i in Seqs){
x=Perps$x[i:(i+3)]
y=Perps$y[i:(i+3)]
ci=grDevices::chull(x,y)
x=x[ci]
y=y[ci]
x=c(x,x[1])
y=c(y,y[1])
Pl[[np]]=sf::st_polygon(list(cbind(x,y)))
np=np+1
}
pPl=sf::st_sfc(Pl, crs = 6932)
pCro=sf::st_sfc(Cro, crs = 6932)
pHea=sf::st_sfc(Hea, crs = 6932)
pPl=sf::st_difference(pPl,pCro)
#Build color ramp
Cols=NULL
for(i in seq(1,length(Acol))){
Col=grDevices::col2rgb(Acol[i],alpha = TRUE)
Col=as.vector(Col)/255
Col[4]=Col[4]-Atrans[i]
Col=grDevices::rgb(red=Col[1], green=Col[2], blue=Col[3], alpha=Col[4])
Cols=c(Cols,Col)
}
pal=grDevices::colorRampPalette(Cols, alpha=TRUE)
if(Atype=="normal"){
Ar=sf::st_union(pHea,pPl)
Ar=sf::st_union(Ar)
Ardata=data.frame(col=pal(1))
}
if(Atype=="dashed"){
Ar=c(pPl,pHea)
Ardata=data.frame(col=pal(length(Ar)))
}
Ar=sf::st_set_geometry(Ardata,Ar)
return(Ar)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/create_Arrow.R
|
#' Get Cartesian coordinates of lines intersection in Euclidean space
#'
#' Given two lines defined by the Latitudes/Longitudes of their extremities, finds the location of their
#' intersection, in Euclidean space, using
#' this approach: \url{https://en.wikipedia.org/wiki/Line-line_intersection}.
#'
#' @param Line1 Vector of 4 coordinates, given in decimal degrees as:
#'
#' \code{c(Longitude_start,Latitude_start,Longitude_end,Latitude_end)}.
#'
#' @param Line2 Same as \code{Line1}.
#'
#' @param Plot logical, if set to TRUE, plots a schematic of calculations.
#'
#' @examples
#' \donttest{
#'
#'
#'#Example 1 (Intersection beyond the range of segments)
#'get_C_intersection(Line1=c(-30,-55,-29,-50),Line2=c(-50,-60,-40,-60))
#'
#'#Example 2 (Intersection on one of the segments)
#'get_C_intersection(Line1=c(-30,-65,-29,-50),Line2=c(-50,-60,-40,-60))
#'
#'#Example 3 (Crossed segments)
#'get_C_intersection(Line1=c(-30,-65,-29,-50),Line2=c(-50,-60,-25,-60))
#'
#'#Example 4 (Antimeridian crossed)
#'get_C_intersection(Line1=c(-179,-60,-150,-50),Line2=c(-120,-60,-130,-62))
#'
#'#Example 5 (Parallel lines - uncomment to test as it will return an error)
#'#get_C_intersection(Line1=c(0,-60,10,-60),Line2=c(-10,-60,10,-60))
#'
#'
#'}
#'
#' @export
get_C_intersection=function(Line1,Line2,Plot=TRUE){
#Line 1
x1=Line1[1]
y1=Line1[2]
x2=Line1[3]
y2=Line1[4]
#Line 2
x3=Line2[1]
y3=Line2[2]
x4=Line2[3]
y4=Line2[4]
#Compute intersection:
D=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)
if(D==0){
if(Plot==TRUE){graphics::plot(1,1);text(1,1,"Parallel lines",col="red")}
stop("Parallel lines.")
}
Px=((x1*y2-y1*x2)*(x3-x4)-(x1-x2)*(x3*y4-y3*x4))/D
Py=((x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4))/D
#Warn user if the longitude of the intersection crosses the antimeridian.
if(abs(Px)>180){warning("Antimeridian crossed. Find where your line crosses it first, using Line=c(180,-90,180,0) or Line=c(-180,-90,-180,0).")}
if(Plot==TRUE){
XL=range(c(x1,x2,x3,x4,Px))
XL=c(XL[1]-0.1*abs(mean(XL)),XL[2]+0.1*abs(mean(XL)))
YL=range(c(y1,y2,y3,y4,Py))
YL=c(YL[1]-0.1*abs(mean(YL)),YL[2]+0.1*abs(mean(YL)))
graphics::plot(c(x1,x2,x3,x4),c(y1,y2,y3,y4),xlim=XL,ylim=YL,pch=21,bg=c("green","green","blue","blue"),xlab="Longitude",ylab="Latitude")
par(new=TRUE)
graphics::plot(Px,Py,xlim=XL,ylim=YL,pch=4,col="red",xlab="Longitude",ylab="Latitude",lwd=2)
lines(c(x1,x2),c(y1,y2),col="green",lwd=2)
lines(c(x3,x4),c(y3,y4),col="blue",lwd=2)
lines(c(x1,x2,Px),c(y1,y2,Py),col="green",lty=2)
lines(c(x3,x4,Px),c(y3,y4,Py),col="blue",lty=2)
if(abs(Px)>180){abline(v=c(-180,180),col="red",lwd=2);text(Px,Py,"Antimeridian crossed",col="red",xpd=TRUE)}
legend("topleft",c("Line 1","Line 2","Intersection"),col=c("green","blue","red"),lwd=c(2,2,NA),pch=c(21,21,4),pt.bg=c("green","blue","red"))
}
return(c(Lon=Px,Lat=Py))
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/get_C_intersection.R
|
#' Get depths of locations from a bathymetry raster
#'
#' Given a bathymetry raster and an input dataframe of point locations (given in decimal degrees),
#' computes the depths at these locations (values for the cell each point falls in). The accuracy is
#' dependent on the resolution of the bathymetry raster (see \code{\link{load_Bathy}} to get high resolution data).
#'
#' @param Input dataframe with, at least, Latitudes and Longitudes.
#' If \code{NamesIn} is not provided, the columns in the \code{Input} must be in the following order:
#'
#' Latitude, Longitude, Variable 1, Variable 2, ... Variable x.
#'
#' @param NamesIn character vector of length 2 specifying the column names of Latitude and Longitude fields in
#' the \code{Input}. Latitudes name must be given first, e.g.:
#'
#' \code{NamesIn=c('MyLatitudes','MyLongitudes')}.
#'
#' @param Bathy bathymetry raster with the appropriate \code{\link[CCAMLRGIS:CCAMLRp]{projection}},
#' such as \code{\link[CCAMLRGIS:SmallBathy]{this one}}. It is highly recommended to use a raster of higher
#' resolution than \code{\link{SmallBathy}} (see \code{\link{load_Bathy}}).
#' @return dataframe with the same structure as the \code{Input} with an additional depth column \code{'d'}.
#'
#' @seealso
#' \code{\link{load_Bathy}}, \code{\link{create_Points}},
#' \code{\link{create_Stations}}, \code{\link{get_iso_polys}}.
#'
#' @examples
#'
#'
#' #Generate a dataframe
#' MyData=data.frame(Lat=PointData$Lat,
#' Lon=PointData$Lon,
#' Catch=PointData$Catch)
#'
#' #get depths of locations
#' MyDataD=get_depths(Input=MyData,Bathy=SmallBathy())
#' #View(MyDataD)
#' plot(MyDataD$d,MyDataD$Catch,xlab='Depth',ylab='Catch',pch=21,bg='blue')
#'
#'
#'
#' @export
get_depths=function(Input,Bathy,NamesIn=NULL){
Input = as.data.frame(Input)
#Check NamesIn
if (is.null(NamesIn) == FALSE) {
if (length(NamesIn) != 2) {
stop("'NamesIn' should be a character vector of length 2")
}
if (any(NamesIn %in% colnames(Input) == FALSE)) {
stop("'NamesIn' do not match column names in 'Input'")
}
}else{
NamesIn=colnames(Input)[1:2]
}
#Coerce Bathy
if(class(Bathy)[1]!="SpatRaster"){
Bathy=terra::rast(Bathy)
}
#Project Lat/Lon
xy=project_data(Input,NamesIn=NamesIn,append=FALSE)
xy=cbind(xy[,2],xy[,1])
#extract depths
ds=terra::extract(Bathy,xy)
colnames(ds)="d"
#Combine
out=Input
out$d=ds$d
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/get_depths.R
|
#' Generate Polygons from Isobaths
#'
#' From an input bathymetry and chosen depths, turns areas between isobaths into polygons.
#' An input polygon may optionally be given to constrain boundaries.
#' The accuracy is dependent on the resolution of the bathymetry raster
#' (see \code{\link{load_Bathy}} to get high resolution data).
#'
#' @param Poly optional, single polygon inside which isobaths will be computed.
#' May be created using \code{\link{create_Polys}} or by subsetting an object obtained
#' using one of the \code{load_} functions (see examples).
#'
#' @param Bathy bathymetry raster with the appropriate projection, such as
#' \code{\link[CCAMLRGIS:SmallBathy]{SmallBathy}}.
#' It is highly recommended to use a raster of higher resolution (see \code{\link{load_Bathy}}).
#'
#' @param Depths numeric, vector of desired isobaths. For example,
#' \code{Depths=c(-2000,-1000,-500)}.
#'
#' @return Spatial object in your environment. Data within the resulting object contains
#' a polygon in each row. Columns are as follows: \code{ID} is a unique polygon identifier;
#' \code{Iso} is an isobath identifier; \code{Min} and \code{Max} is the depth range of isobaths;
#' \code{Grp} is a group identifier (e.g., a seamount constituted of several isobaths);
#' \code{AreaKm2} is the polygon area in square kilometers; \code{Labx} and \code{Laby} can be used
#' to label groups (see examples).
#'
#' @seealso
#' \code{\link{load_Bathy}}, \code{\link{create_Polys}}, \code{\link{get_depths}}.
#'
#' @examples
#'
#' # For more examples, see:
#' # https://github.com/ccamlr/CCAMLRGIS#46-get_iso_polys
#'
#'
#' Poly=create_Polys(Input=data.frame(ID=1,Lat=c(-55,-55,-61,-61),Lon=c(-30,-25,-25,-30)))
#' IsoPols=get_iso_polys(Bathy=SmallBathy(),Poly=Poly,Depths=seq(-8000,0,length.out=10))
#'
#' plot(st_geometry(Poly))
#' for(i in unique(IsoPols$Iso)){
#' plot(st_geometry(IsoPols[IsoPols$Iso==i,]),col=rainbow(9)[i],add=TRUE)
#' }
#'
#'
#' @export
get_iso_polys=function(Bathy,Poly=NULL,Depths){
if(is.null(Poly)==FALSE){
Bathy=terra::crop(Bathy,Poly)
Bathy=terra::mask(Bathy,Poly)
}
Depths=sort(Depths)
B=stars::st_as_stars(Bathy)
Cs=stars::st_contour(B,breaks=Depths)
Cs=sf::st_cast(Cs,"POLYGON",warn=FALSE)
Cs=Cs%>%dplyr::filter(is.finite(Min)==TRUE & is.finite(Max)==TRUE)
Cs=Cs[,-1]
row.names(Cs)=NULL
Grp=sf::st_touches(Cs,sparse = TRUE)
#Add Isobath ID
tmp=data.frame(Min=sort(unique(Cs$Min)))
tmp$Iso=seq(1,nrow(tmp))
Cs=dplyr::left_join(Cs,tmp,by="Min")
#Add Group
Cs$Grp=NA
Cs$Grp[1]=1
for(i in seq(2,nrow(Cs))){
Gr=Grp[[i]]
if(length(Gr)==0){
Cs$Grp[i]=Cs$Grp[i-1]+1
}else{
if(is.na(Cs$Grp[i])){Cs$Grp[c(i,Gr)]=Cs$Grp[i-1]+1}
}
}
#Add area
Ar=round(st_area(Cs)/1000000,2)
Cs$AreaKm2=as.numeric(Ar)
#Add group label location
labs=st_coordinates(st_centroid(st_geometry(Cs)))
Cs$Labx=labs[,1]
Cs$Laby=labs[,2]
#Keep label location for shallowest pol within group
tmp=st_drop_geometry(Cs)%>%dplyr::select(Iso,Grp,AreaKm2)
tmp2=tmp%>%dplyr::group_by(Grp)%>%dplyr::summarise(Iso2=max(Iso),AreaKm2=max(AreaKm2[Iso==max(Iso)]))
colnames(tmp2)[2]="Iso"
tmp2$L="Y"
tmp=dplyr::left_join(tmp,tmp2,by = c("Iso", "Grp","AreaKm2"))
Cs$Labx[which(is.na(tmp$L))]=NA
Cs$Laby[which(is.na(tmp$L))]=NA
Cs$ID=seq(1,nrow(Cs))
Cs=Cs[,c(9,3,1,2,5,6,7,8,4)]
return(Cs)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/get_iso_polys.R
|
#' Load CCAMLR statistical Areas, Subareas and Divisions
#'
#' Download the up-to-date spatial layer from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' See examples for offline use. All layers use the Lambert azimuthal equal-area projection
#' (\code{\link{CCAMLRp}})
#'
#' @seealso
#' \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}}, \code{\link{load_Coastline}},
#' \code{\link{load_MPAs}}, \code{\link{load_EEZs}}.
#'
#' @export
#' @examples
#' \donttest{
#'
#' #When online:
#' ASDs=load_ASDs()
#' plot(st_geometry(ASDs))
#'
#' #For offline use, see:
#' #https://github.com/ccamlr/CCAMLRGIS#32-offline-use
#'
#'
#' }
load_ASDs=function(){
#NB: use http not https
ccamlrgisurl="http://gis.ccamlr.org/geoserver/gis/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=gis:statistical_areas_6932&outputFormat=json"
CCAMLR_data = st_read(ccamlrgisurl,quiet = TRUE)
CCAMLR_data = st_transform(CCAMLR_data,6932)
return(CCAMLR_data)
}
#' Load CCAMLR Small Scale Research Units
#'
#' Download the up-to-date spatial layer from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' See examples for offline use. All layers use the Lambert azimuthal equal-area projection
#' (\code{\link{CCAMLRp}})
#'
#' @seealso
#' \code{\link{load_ASDs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}}, \code{\link{load_Coastline}},
#' \code{\link{load_MPAs}}, \code{\link{load_EEZs}}.
#'
#' @export
#' @examples
#' \donttest{
#'
#' #When online:
#' SSRUs=load_SSRUs()
#' plot(st_geometry(SSRUs))
#'
#' #For offline use, see:
#' #https://github.com/ccamlr/CCAMLRGIS#32-offline-use
#'
#' }
#'
load_SSRUs=function(){
#NB: use http not https
ccamlrgisurl="http://gis.ccamlr.org/geoserver/gis/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=gis:ssrus_6932&outputFormat=json"
CCAMLR_data = st_read(ccamlrgisurl,quiet = TRUE)
CCAMLR_data = st_transform(CCAMLR_data,6932)
return(CCAMLR_data)
}
#' Load the full CCAMLR Coastline
#'
#' Download the up-to-date spatial layer from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' See examples for offline use. All layers use the Lambert azimuthal equal-area projection
#' (\code{\link{CCAMLRp}}).
#' Note that this coastline expands further north than \link{Coast}.
#' Sources: UK Polar Data Centre/BAS and Natural Earth. Projection: EPSG 6932.
#' More details here: \url{https://github.com/ccamlr/geospatial_operations}
#'
#' @seealso
#' \code{\link{load_ASDs}}, \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}},
#' \code{\link{load_MPAs}}, \code{\link{load_EEZs}}.
#'
#' @references UK Polar Data Centre/BAS and Natural Earth.
#'
#' @export
#' @examples
#' \donttest{
#'
#' #When online:
#' Coastline=load_Coastline()
#' plot(st_geometry(Coastline))
#'
#' #For offline use, see:
#' #https://github.com/ccamlr/CCAMLRGIS#32-offline-use
#'
#' }
#'
load_Coastline=function(){
#NB: use http not https
ccamlrgisurl="http://gis.ccamlr.org/geoserver/gis/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=gis:coastline_v1_6932&outputFormat=json"
CCAMLR_data = st_read(ccamlrgisurl,quiet = TRUE)
return(CCAMLR_data)
}
#' Load CCAMLR Research Blocks
#'
#' Download the up-to-date spatial layer from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' See examples for offline use. All layers use the Lambert azimuthal equal-area projection
#' (\code{\link{CCAMLRp}})
#'
#' @seealso
#' \code{\link{load_ASDs}}, \code{\link{load_SSRUs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}}, \code{\link{load_Coastline}},
#' \code{\link{load_MPAs}}, \code{\link{load_EEZs}}.
#'
#' @export
#' @examples
#' \donttest{
#'
#' #When online:
#' RBs=load_RBs()
#' plot(st_geometry(RBs))
#'
#' #For offline use, see:
#' #https://github.com/ccamlr/CCAMLRGIS#32-offline-use
#'
#' }
#'
load_RBs=function(){
#NB: use http not https
ccamlrgisurl="http://gis.ccamlr.org/geoserver/gis/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=gis:research_blocks_6932&outputFormat=json"
CCAMLR_data = st_read(ccamlrgisurl,quiet = TRUE)
CCAMLR_data = st_transform(CCAMLR_data,6932)
return(CCAMLR_data)
}
#' Load CCAMLR Small Scale Management Units
#'
#' Download the up-to-date spatial layer from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' See examples for offline use. All layers use the Lambert azimuthal equal-area projection
#' (\code{\link{CCAMLRp}})
#'
#' @seealso
#' \code{\link{load_ASDs}}, \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_MAs}}, \code{\link{load_Coastline}},
#' \code{\link{load_MPAs}}, \code{\link{load_EEZs}}.
#'
#' @export
#' @examples
#' \donttest{
#'
#' #When online:
#' SSMUs=load_SSMUs()
#' plot(st_geometry(SSMUs))
#'
#' #For offline use, see:
#' #https://github.com/ccamlr/CCAMLRGIS#32-offline-use
#'
#' }
#'
load_SSMUs=function(){
#NB: use http not https
ccamlrgisurl="http://gis.ccamlr.org/geoserver/gis/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=gis:ssmus_6932&outputFormat=json"
CCAMLR_data = st_read(ccamlrgisurl,quiet = TRUE)
CCAMLR_data = st_transform(CCAMLR_data,6932)
return(CCAMLR_data)
}
#' Load CCAMLR Management Areas
#'
#' Download the up-to-date spatial layer from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' See examples for offline use. All layers use the Lambert azimuthal equal-area projection
#' (\code{\link{CCAMLRp}})
#'
#' @seealso
#' \code{\link{load_ASDs}}, \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_Coastline}},
#' \code{\link{load_MPAs}}, \code{\link{load_EEZs}}.
#'
#' @export
#' @examples
#' \donttest{
#'
#' #When online:
#' MAs=load_MAs()
#' plot(st_geometry(MAs))
#'
#' #For offline use, see:
#' #https://github.com/ccamlr/CCAMLRGIS#32-offline-use
#'
#' }
#'
load_MAs=function(){
#NB: use http not https
ccamlrgisurl="http://gis.ccamlr.org/geoserver/gis/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=gis:omas_6932&outputFormat=json"
CCAMLR_data = st_read(ccamlrgisurl,quiet = TRUE)
CCAMLR_data = st_transform(CCAMLR_data,6932)
return(CCAMLR_data)
}
#' Load CCAMLR Marine Protected Areas
#'
#' Download the up-to-date spatial layer from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' See examples for offline use. All layers use the Lambert azimuthal equal-area projection
#' (\code{\link{CCAMLRp}})
#'
#' @seealso
#' \code{\link{load_ASDs}}, \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}}, \code{\link{load_Coastline}},
#' \code{\link{load_EEZs}}.
#'
#' @export
#' @examples
#' \donttest{
#'
#' #When online:
#' MPAs=load_MPAs()
#' plot(st_geometry(MPAs))
#'
#' #For offline use, see:
#' #https://github.com/ccamlr/CCAMLRGIS#32-offline-use
#'
#' }
#'
load_MPAs=function(){
#NB: use http not https
ccamlrgisurl="http://gis.ccamlr.org/geoserver/gis/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=gis:mpas_6932&outputFormat=json"
CCAMLR_data = st_read(ccamlrgisurl,quiet = TRUE)
CCAMLR_data = st_transform(CCAMLR_data,6932)
return(CCAMLR_data)
}
#' Load Exclusive Economic Zones
#'
#' Download the up-to-date spatial layer from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' See examples for offline use. All layers use the Lambert azimuthal equal-area projection
#' (\code{\link{CCAMLRp}})
#'
#' @seealso
#' \code{\link{load_ASDs}}, \code{\link{load_SSRUs}}, \code{\link{load_RBs}},
#' \code{\link{load_SSMUs}}, \code{\link{load_MAs}}, \code{\link{load_Coastline}},
#' \code{\link{load_MPAs}}.
#'
#' @export
#' @examples
#' \donttest{
#'
#' #When online:
#' EEZs=load_EEZs()
#' plot(st_geometry(EEZs))
#'
#' #For offline use, see:
#' #https://github.com/ccamlr/CCAMLRGIS#32-offline-use
#'
#' }
#'
load_EEZs=function(){
#NB: use http not https
ccamlrgisurl="http://gis.ccamlr.org/geoserver/gis/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=gis:eez_6932&outputFormat=json"
CCAMLR_data = st_read(ccamlrgisurl,quiet = TRUE)
CCAMLR_data = st_transform(CCAMLR_data,6932)
return(CCAMLR_data)
}
#' Load Bathymetry data
#'
#' Download the up-to-date projected GEBCO data from the online CCAMLRGIS (\url{http://gis.ccamlr.org/}) and load it to your environment.
#' This functions can be used in two steps, to first download the data and then use it. If you keep the downloaded data, you can then
#' re-use it in all your scripts.
#'
#' To download the data, you must either have set your working directory using \code{\link[base]{setwd}}, or be working within an Rproject.
#' In any case, your file will be downloaded to the folder path given by \code{\link[base]{getwd}}.
#'
#' It is strongly recommended to first download the lowest resolution data (set \code{Res=5000}) to ensure it is working as expected.
#'
#' To re-use the downloaded data, you must provide the full path to that file, for example:
#'
#' \code{LocalFile="C:/Desktop/GEBCO2023_5000.tif"}.
#'
#' This data was reprojected from the original GEBCO Grid after cropping at 40 degrees South. Projection was made using the Lambert
#' azimuthal equal-area projection (\code{\link{CCAMLRp}}),
#' and the data was aggregated at several resolutions.
#'
#' @param LocalFile To download the data, set to \code{FALSE}. To re-use a downloaded file, set to the full path of the file
#' (e.g., \code{LocalFile="C:/Desktop/GEBCO2023_5000.tif"}).
#' @param Res Desired resolution in meters. May only be one of: 500, 1000, 2500 or 5000.
#' @return Bathymetry raster.
#'
#' @seealso
#' \code{\link{add_col}}, \code{\link{add_Cscale}}, \code{\link{Depth_cols}}, \code{\link{Depth_cuts}},
#' \code{\link{Depth_cols2}}, \code{\link{Depth_cuts2}}, \code{\link{get_depths}},
#' \code{\link{create_Stations}}, \code{\link{get_iso_polys}},
#' \code{\link{SmallBathy}}.
#'
#' @references GEBCO Compilation Group (2023) GEBCO 2023 Grid (doi:10.5285/f98b053b-0cbc-6c23-e053-6c86abc0af7b)
#'
#' @export
#' @examples
#' \donttest{
#'
#' #The examples below are commented. To test, remove the '#'.
#'
#' ##Download the data. It will go in the folder given by getwd():
#' #Bathy=load_Bathy(LocalFile = FALSE,Res=5000)
#' #plot(Bathy, breaks=Depth_cuts,col=Depth_cols,axes=FALSE)
#'
#' ##Re-use the downloaded data (provided it's here: "C:/Desktop/GEBCO2023_5000.tif"):
#' #Bathy=load_Bathy(LocalFile = "C:/Desktop/GEBCO2023_5000.tif")
#' #plot(Bathy, breaks=Depth_cuts,col=Depth_cols,axes=FALSE)
#'
#' }
#'
load_Bathy=function(LocalFile,Res=5000){
if(LocalFile==FALSE){
if(Res%in%c(500,1000,2500,5000)==FALSE){stop("'Res' should be one of: 500, 1000, 2500 or 5000")}
Fname=paste0("GEBCO2023_",Res,".tif")
url=paste0("https://gis.ccamlr.org/geoserver/www/",Fname)
download.file(url, destfile=paste0(getwd(),"/",Fname),mode="wb")
Bathy=terra::rast(paste0(getwd(),"/",Fname))
}else{
if(file.exists(LocalFile)==FALSE){stop("File not found. Either the file is missing or 'LocalFile' is not properly set.")}
Bathy=terra::rast(LocalFile)
}
return(Bathy)
}
#' Small bathymetry dataset
#'
#' Bathymetry dataset derived from the GEBCO 2023 (see \url{https://www.gebco.net/}) dataset.
#' Subsampled at a 10,000m resolution. Projected using the CCAMLR standard projection (\code{\link{CCAMLRp}}).
#' To highlight the Fishable Depth range, use \code{\link{Depth_cols2}} and \code{\link{Depth_cuts2}}.
#' To be only used for large scale illustrative purposes. Please refer to \code{\link{load_Bathy}}
#' to get higher resolution data.
#'
#'
#' @usage SmallBathy()
#' @format raster
#' @export
#' @examples terra::plot(SmallBathy(),breaks=Depth_cuts,col=Depth_cols,axes=FALSE,box=FALSE)
#' @seealso \code{\link{load_Bathy}}, \code{\link{add_col}}, \code{\link{add_Cscale}}, \code{\link{Depth_cols}},
#' \code{\link{Depth_cuts}},
#' \code{\link{Depth_cols2}}, \code{\link{Depth_cuts2}}, \code{\link{get_depths}}, \code{\link{create_Stations}}.
#' @references GEBCO Compilation Group (2023) GEBCO 2023 Grid (doi:10.5285/f98b053b-0cbc-6c23-e053-6c86abc0af7b)
#'
SmallBathy=function(){
terra::rast(system.file("extdata/SmallBathy.tif", package="CCAMLRGIS"))
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/load.R
|
#' Project user-supplied locations
#'
#' Given an input dataframe containing locations given in decimal degrees or meters (if projected),
#' projects these locations and, if desired, appends them to the input dataframe.
#' May also be used to back-project to Latitudes/Longitudes provided the input was projected
#' using a Lambert azimuthal equal-area projection (\code{\link{CCAMLRp}}).
#'
#' @param Input dataframe containing - at the minimum - Latitudes and Longitudes to be projected (or Y and X to be back-projected).
#'
#' @param NamesIn character vector of length 2 specifying the column names of Latitude and Longitude fields in
#' the \code{Input}. Latitudes (or Y) name must be given first, e.g.:
#'
#' \code{NamesIn=c('MyLatitudes','MyLongitudes')}.
#'
#' @param NamesOut character vector of length 2, optional. Names of the resulting columns in the output dataframe,
#' with order matching that of \code{NamesIn} (e.g., \code{NamesOut=c('Y','X')}).
#'
#' @param append logical (T/F). Should the projected locations be appended to the \code{Input}?
#'
#' @param inv logical (T/F). Should a back-projection be performed? In such case, locations must be given in meters
#' and have been projected using a Lambert azimuthal equal-area projection (\code{\link{CCAMLRp}}).
#'
#'
#' @seealso
#' \code{\link{assign_areas}}.
#'
#' @examples
#'
#'
#' #Generate a dataframe
#' MyData=data.frame(Lat=runif(100,min=-65,max=-50),
#' Lon=runif(100,min=20,max=40))
#'
#' #Project data using a Lambert azimuthal equal-area projection
#' MyData=project_data(Input=MyData,NamesIn=c("Lat","Lon"))
#' #View(MyData)
#'
#' @export
project_data=function(Input,NamesIn=NULL,NamesOut=NULL,append=TRUE,inv=FALSE){
Input = as.data.frame(Input)
if (is.null(NamesIn) == FALSE) {
if (length(NamesIn) != 2) {
stop("'NamesIn' should be a character vector of length 2")
}
if (any(NamesIn %in% colnames(Input) == FALSE)) {
stop("'NamesIn' do not match column names in 'Input'")
}
}else{
stop("'NamesIn' not specified")
}
if (is.null(NamesOut) == TRUE) {
if(inv==FALSE){
NamesOut=c("Y","X")
}else{
NamesOut=c("Latitude","Longitude")
}
}
Locs = Input[, c(NamesIn[2], NamesIn[1])]
Missing = which(is.na(Locs[, 1]) == TRUE | is.na(Locs[, 2]) == TRUE)
if (length(Missing) > 1) {
warning(paste0(length(Missing), " records are missing location and will not be projected\n"))
}
if (length(Missing) == 1) {
warning("One record is missing location and will not be projected\n")
}
if(inv==FALSE){
Impossible = which(Locs[, 1] > 180 | Locs[, 1] < (-180) | Locs[, 2] > 90 | Locs[, 2] < (-90))
if (length(Impossible) > 1) {
warning(paste0(length(Impossible), " records are not on Earth and will not be projected\n"))
Locs[Impossible, ] = NA
}
if (length(Impossible) == 1) {
warning("One record is not on Earth and will not be projected\n")
Locs[Impossible, ] = NA
}
}else{
Impossible=NULL
}
#Temporary fill
tmpf=unique(c(Missing,Impossible))
if(length(tmpf)>0){
Locs[tmpf,1]=0
Locs[tmpf,2]=-60
}
if(inv==FALSE){
Locs=st_as_sf(x=Locs,coords=c(1,2),crs=4326,remove=FALSE)
Locs=st_transform(x=Locs,crs=6932)
Locs=as.data.frame(st_coordinates(Locs))
colnames(Locs)=c(NamesOut[2],NamesOut[1])
Locs=Locs[,NamesOut]
}else{
Locs=st_as_sf(x=Locs,coords=c(1,2),crs=6932,remove=FALSE)
Locs=st_transform(x=Locs,crs=4326)
Locs=as.data.frame(st_coordinates(Locs))
colnames(Locs)=c(NamesOut[2],NamesOut[1])
Locs=Locs[,NamesOut]
}
#Remove temporary fill
if(length(tmpf)>0){
Locs[tmpf,1]=NA
Locs[tmpf,2]=NA
}
if(append==TRUE){
out=cbind(Input,Locs)
return(out)
}else{
return(Locs)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/project_data.R
|
#' Calculate planimetric seabed area
#'
#' Calculate planimetric seabed area within polygons and depth strata in square kilometers.
#'
#' @param Bathy bathymetry raster with the appropriate \code{\link[CCAMLRGIS:CCAMLRp]{projection}}.
#' It is highly recommended to use a raster of higher
#' resolution than \code{\link{SmallBathy}}, see \code{\link{load_Bathy}}.
#' @param Poly polygon(s) within which the areas of depth strata are computed.
#' @param PolyNames character, column name (from the polygon object) to be used in the output.
#' @param depth_classes numeric vector of strata depths. for example, \code{depth_classes=c(-600,-1000,-2000)}.
#' If the values \code{-600,-1800} are given within \code{depth_classes}, the computed area will be labelled as 'Fishable_area'.
#' @return dataframe with the name of polygons in the first column and the area for each strata in the following columns.
#'
#' @seealso
#' \code{\link{load_Bathy}}, \code{\link{SmallBathy}}, \code{\link{create_Polys}}, \code{\link{load_RBs}}.
#'
#' @examples
#' \donttest{
#'
#'#create some polygons
#'MyPolys=create_Polys(PolyData,Densify=TRUE)
#'#compute the seabed areas
#'FishDepth=seabed_area(SmallBathy(),MyPolys,PolyNames="ID",
#'depth_classes=c(0,-200,-600,-1800,-3000,-5000))
#'#Result looks like this (note that the 600-1800 stratum is renamed 'Fishable_area')
#'#View(FishDepth)
#'
#'
#' }
#'
#' @export
seabed_area=function (Bathy, Poly, PolyNames=NULL, depth_classes=c(-600,-1800)){
if(class(Poly)[1]!="sf"){
stop("'Poly' must be an sf object")
}
if(is.null(PolyNames)){
stop("'PolyNames' is missing")
}else{
if(PolyNames%in%colnames(Poly)==FALSE){
stop("'PolyNames' does not match column names in 'Poly'")
}
}
#Coerce Bathy
if(class(Bathy)[1]!="SpatRaster"){
Bathy=terra::rast(Bathy)
}
OUT=data.frame(matrix(nrow=nrow(Poly),ncol=length(depth_classes)))
colnames(OUT)=c(PolyNames, paste(depth_classes[1:length(depth_classes)-1],depth_classes[2:length(depth_classes)],sep='|'))
for(i in seq(1,nrow(Poly))){
poly=Poly[i,]
OUT[i,1]=as.character(st_drop_geometry(poly[,PolyNames]))
#crop bathymetry data to the extent of the polygon
CrB=terra::crop(Bathy,terra::ext(poly))
#Turn bathy cells that are not inside the polygon into NAs
CrB=terra::mask(CrB,terra::vect(poly))
for(j in seq(1,(length(depth_classes)-1))){
dtop=depth_classes[j]
dbot=depth_classes[j+1]
#Turn cells outside depth classes into NAs
Btmp = terra::classify(CrB, cbind(-100000, dbot, NA), right=TRUE)
Btmp = terra::classify(Btmp, cbind(dtop, 100000, NA), right=FALSE)
#Compute the area covered by cells that are not NA
Ar=round(terra::expanse(Btmp, unit="km"),2)[2]
OUT[i,j+1]=Ar
}
}
colnames(OUT)[which(colnames(OUT)=="-600|-1800")]="Fishable_area"
return(OUT)
}
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/R/seabed_area.R
|
---
title: "CCAMLRGIS R Package"
author: 'CCAMLR Secretariat'
output: rmarkdown::html_vignette
date: "`r format(Sys.time(), '%d %b %Y')`"
vignette: >
%\VignetteIndexEntry{CCAMLRGIS R Package}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
<center>
### A package to load and create spatial data, including layers and tools that are relevant to CCAMLR activities.
</center>
___
[here]:https://github.com/ccamlr/CCAMLRGIS#table-of-contents
All contents of the vignette have been moved [here].
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/inst/doc/CCAMLRGIS.Rmd
|
---
title: "CCAMLRGIS R Package"
author: 'CCAMLR Secretariat'
output: rmarkdown::html_vignette
date: "`r format(Sys.time(), '%d %b %Y')`"
vignette: >
%\VignetteIndexEntry{CCAMLRGIS R Package}
%\VignetteEngine{knitr::rmarkdown}
\usepackage[utf8]{inputenc}
---
<center>
### A package to load and create spatial data, including layers and tools that are relevant to CCAMLR activities.
</center>
___
[here]:https://github.com/ccamlr/CCAMLRGIS#table-of-contents
All contents of the vignette have been moved [here].
|
/scratch/gouwar.j/cran-all/cranData/CCAMLRGIS/vignettes/CCAMLRGIS.Rmd
|
cor.by.class <-
function(x,y, method = "pearson", use = "complete") {
index = 1:length(y)
index.by.class = split(index, y)
K.list = list(NULL)
for (i in 1:length(index.by.class)) {
cat("calculating cor for: ", names(index.by.class)[i], "\n")
K.list[[i]] = cor(x[,index.by.class[[i]]], method = method)
}
names = names(index.by.class)
KK = list(NULL)
for (i in 1:length(K.list)) {
diag(K.list[[i]]) = NA
K.list[[i]] = K.list[[i]][!is.na(K.list[[i]])]
KK[[i]] = as.vector(K.list[[i]])
}
names(KK) = names
return(K = KK)
}
|
/scratch/gouwar.j/cran-all/cranData/CCM/R/cor.by.class.R
|
create.CCM <-
function(X.test, X.train = NULL, method = "pearson", use = "everything", verbose = 1) {
if (is.null(X.train)) {
K = cor(X.test, method = method, use = use)
diag(K) = NA
attr(K, "class") <- "CCM"
return(K)
}
if (is.null(rownames(X.train)) | is.null(rownames(X.test))) {
if (nrow(X.train) != nrow(X.test)) {
cat("error: X.test and X.train must have the same number of rows or matching rownames must exist\n")
return(NULL)
}
m = 1:nrow(X.train)
}
m = match(rownames(X.train), rownames(X.test))
if (method == "spearman") {
if (verbose) cat("calculating ranks...\n")
X.test = apply(X.test,2,rank)
X.train = apply(X.train,2,rank)
}
if (verbose) cat("calculating cors...\n")
K = matrix(NA, nrow = ncol(X.test[m,]), ncol = ncol(X.train))
for (i in 1:ncol(X.test)) {
K[i,] = apply(X.train,2,cor,X.test[m,i])
}
attr(K, "class") <- "CCM"
return(K)
}
|
/scratch/gouwar.j/cran-all/cranData/CCM/R/create.CCM.R
|
plot.CCM <-
function(x, y, index, no.plot = FALSE, ...) {
KK = split(x[index,], y)
if (no.plot) return(KK)
boxplot(KK, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/CCM/R/plot.cors.R
|
predict.CCM <-
function(object, y, func = mean, ret.scores = FALSE, ...) {
keep = !is.na(y)
y = y[keep]
object = object[,keep]
preds = rep(NA,nrow(object))
scores = NULL
for (i in 1:nrow(object)) {
s = split(object[i,], y)
l = (lapply(s,func, na.rm=TRUE, ...))
w = which.max(l)
if (ret.scores) scores = rbind(scores, unlist(l))
preds[i] = names(w)
}
if (ret.scores) {
scores = t(scores)
return(scores)
}
if (is.numeric(y)) preds = as.numeric(preds)
if (is.factor(y)) preds = as.factor(preds)
return(preds)
}
|
/scratch/gouwar.j/cran-all/cranData/CCM/R/predict.CCM.R
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
.convex_clusterpath <- function(X, W_idx, W_val, lambdas, target_losses, eps_conv, eps_fusions, scale, save_clusterpath, use_target, save_losses, save_convergence_norms, burnin_iter, max_iter_conv) {
.Call(`_CCMMR_convex_clusterpath`, X, W_idx, W_val, lambdas, target_losses, eps_conv, eps_fusions, scale, save_clusterpath, use_target, save_losses, save_convergence_norms, burnin_iter, max_iter_conv)
}
.convex_clustering <- function(X, W_idx, W_val, eps_conv, eps_fusions, scale, save_clusterpath, burnin_iter, max_iter_conv, target_low, target_high, max_iter_phase_1, max_iter_phase_2, verbose, lambda_init, factor) {
.Call(`_CCMMR_convex_clustering`, X, W_idx, W_val, eps_conv, eps_fusions, scale, save_clusterpath, burnin_iter, max_iter_conv, target_low, target_high, max_iter_phase_1, max_iter_phase_2, verbose, lambda_init, factor)
}
.fusion_threshold <- function(X, tau) {
.Call(`_CCMMR_fusion_threshold`, X, tau)
}
.find_mst <- function(G) {
.Call(`_CCMMR_find_mst`, G)
}
.find_subgraphs <- function(E, n) {
.Call(`_CCMMR_find_subgraphs`, E, n)
}
.sparse_weights <- function(X, indices, distances, phi, k, sym_circ, scale) {
.Call(`_CCMMR_sparse_weights`, X, indices, distances, phi, k, sym_circ, scale)
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/RcppExports.R
|
#' Conversion of a \code{cvxclust} object into an \code{hclust} object
#'
#' @description Converts the output of \link{convex_clustering} or
#' \link{convex_clusterpath} into a hclust object. Note that a step in the
#' clusterpath from one value for lambda to the next may cause the number of
#' clusters to decrease by more than one. It is a hard requirement that the
#' clusterpath ends in a single cluster, as standard dendrogram plotting
#' methods fail if this is not the case.
#'
#' @param x A \code{cvxclust} object.
#' @param ... Unused.
#'
#' @return A \code{hclust} object.
#'
#' @examples
#' # Demonstration of converting a clusterpath into a dendrogram, first generate
#' # data
#' set.seed(6)
#' X = matrix(rnorm(14), ncol = 2)
#' y = rep(1, nrow(X))
#'
#' # Get sparse distances in dictionary of keys format with k = 3
#' W = sparse_weights(X, 3, 4.0)
#'
#' # Sequence for lambda
#' lambdas = seq(0, 45, 0.02)
#'
#' # Compute results
#' res = convex_clusterpath(X, W, lambdas)
#'
#' # Generate hclust object
#' hcl = as.hclust(res)
#' hcl$height = sqrt(hcl$height)
#'
#' # Plot clusterpath and dendrogram
#' oldpar = par(mfrow=c(1, 2))
#' plot(res, y, label = c(1:7))
#' plot(hcl, ylab = expression(sqrt(lambda)), xlab = NA, sub = NA, main = NA,
#' hang = -1)
#' par(oldpar)
#'
#' @seealso \link{hclust}
#'
#' @export
as.hclust.cvxclust <- function(x, ...)
{
# Input checks
.check_cvxclust(x, "x")
if (!(1 %in% x$num_clusters)) {
message = paste("The clusterpath does not terminate in a single",
"cluster. Consider setting connected = TRUE in",
"sparse_weights(...) or choose a higher maximum value",
"for lambda")
stop(message)
}
# Create hclust object
result = list()
result$merge = x$merge
result$height = x$height
result$order = x$order
result$labels = c(1:x$n)
result$call = list()
result$call[[1]] = "Convex Clustering"
result$call$d[[1]] = "dist"
result$call$d[[2]] = "X"
result$dist.method = "Euclidean"
# Set class
class(result) = "hclust"
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/as.hclust.R
|
#' Obtain clustering from a clusterpath
#'
#' @description Get a particular clustering of the data. If there is a
#' clustering for \code{n_clusters}, it is returned, otherwise the function will
#' stop with a message. To know whether a query is going to be successful
#' beforehand, check the \code{num_clusters} attribute of the \code{cvxclust}
#' object, this lists all possible options for the number of clusters.
#'
#' @param obj A \code{cvxclust} object.
#' @param n_clusters An integer that specifies the number of clusters that
#' should be returned.
#'
#' @return A vector with the cluster labels for each object in the data.
#'
#' @examples
#' # Load data
#' data(two_half_moons)
#' data = as.matrix(two_half_moons)
#' X = data[, -3]
#' y = data[, 3]
#'
#' # Get sparse distances in dictionary of keys format with k = 5 and phi = 8
#' W = sparse_weights(X, 5, 8.0)
#'
#' # Set a sequence for lambda
#' lambdas = seq(0, 2400, 1)
#'
#' # Compute results CMM
#' res = convex_clusterpath(X, W, lambdas)
#'
#' # Get labels for three clusters
#' labels = clusters(res, 3)
#'
#' @export
clusters <- function(obj, n_clusters)
{
# Input checks
.check_cvxclust(obj)
.check_int(n_clusters, TRUE, "n_clusters")
if (!(n_clusters %in% obj$num_clusters)) {
message = paste(n_clusters, "is not among the possible number of",
"clusters")
stop(message)
}
# Start with an entry in a hashmap for each observation
d = hashmap()
for (i in 1:obj$n) {
d[[-i]] = i
}
# Work through the merge table to reduce the number of clusters until
# the desired number is reached
for (i in 1:nrow(obj$merge)) {
if (length(d) == n_clusters) {
break
}
d[[i]] = c(d[[obj$merge[i, 1]]], d[[obj$merge[i, 2]]])
delete(d, obj$merge[i, 1])
delete(d, obj$merge[i, 2])
}
# Create cluster labels
result = rep(0, obj$n)
label = 1
for (key in keys(d)) {
result[d[[key]]] = label
# Increment label
label = label + 1
}
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/clusters.R
|
#' Find a target number of clusters in the data using convex clustering
#'
#' @description \code{convex_clustering} attempts to find the number of clusters
#' specified by the user by means of convex clustering. The algorithm looks for
#' each number of clusters between \code{target_low} and \code{target_high}. If
#' \code{target_low} = \code{target_high}, the algorithm searches for a single
#' clustering. It is recommended to specify a range around the desired number of
#' clusters, as not each number of clusters between 1 and \code{nrow(X)} may be
#' attainable due to numerical inaccuracies.
#'
#' @param X An \eqn{n} x \eqn{p} numeric matrix. This function assumes that each
#' row represents an object with \eqn{p} attributes.
#' @param W A \code{sparseweights} object, see \link{sparse_weights}.
#' @param target_low Lower bound on the number of clusters that should be
#' searched for. If \code{target_high = NULL}, this is the exact number of
#' clusters that is searched for.
#' @param target_high Upper bound on the number of clusters that should be
#' searched for. Default is \code{NULL}, in that case, it is set equal to
#' \code{target_low}.
#' @param max_iter_phase_1 Maximum number of iterations to find an upper and
#' lower bound for the value for lambda for which the desired number of clusters
#' is attained. Default is 2000.
#' @param max_iter_phase_2 Maximum number of iterations to to refine the upper
#' and lower bounds for lambda. Default is 20.
#' @param lambda_init The first value for lambda other than 0 to use for convex
#' clustering. Default is 0.01.
#' @param factor The percentage by which to increase lambda in each step.
#' Default is 0.025.
#' @param tau Parameter to compute the threshold to fuse clusters. Default is
#' 0.001.
#' @param center If \code{TRUE}, center \code{X} so that each column has mean
#' zero. Default is \code{TRUE}.
#' @param scale If \code{TRUE}, scale the loss function to ensure that the
#' cluster solution is invariant to the scale of \code{X}. Default is
#' \code{TRUE}. Not recommended to set to \code{FALSE} unless comparing to
#' algorithms that minimize the unscaled convex clustering loss function.
#' @param eps_conv Parameter for determining convergence of the minimization.
#' Default is 1e-6.
#' @param burnin_iter Number of updates of the loss function that are done
#' without step doubling. Default is 25.
#' @param max_iter_conv Maximum number of iterations for minimizing the loss
#' function. Default is 5000.
#' @param save_clusterpath If \code{TRUE}, store the solution that minimized
#' the loss function for each lambda. Is required for drawing the clusterpath.
#' Default is \code{FALSE}. To store the clusterpath coordinates, \eqn{n} x
#' \eqn{p} x \eqn{no. lambdas} values have to be stored, this may require too
#' much memory for large data sets.
#' @param verbose Verbosity of the information printed during clustering.
#' Default is 0, no output.
#'
#' @return A \code{cvxclust} object containing the following
#' \item{\code{info}}{A dataframe containing for each value for lambda: the
#' number of different clusters, and the value of the loss function at the
#' minimum.}
#' \item{\code{merge}}{The merge table containing the order at which the
#' observations in \code{X} are clustered.}
#' \item{\code{height}}{The value for lambda at which each reduction in the
#' number of clusters occurs.}
#' \item{\code{order}}{The order of the observations in \code{X} in order to
#' draw a dendrogram without conflicting branches.}
#' \item{\code{elapsed_time}}{The number of seconds that elapsed while
#' running the code. Note that this does not include the time required for
#' input checking and possibly scaling and centering \code{X}.}
#' \item{\code{coordinates}}{The clusterpath coordinates. Only part of the
#' output in case that \code{save_clusterpath=TRUE}.}
#' \item{\code{lambdas}}{The values for lambda for which a clustering was
#' found.}
#' \item{\code{eps_fusions}}{The threshold for cluster fusions that was used by
#' the algorithm.}
#' \item{\code{phase_1_instances}}{The number of instances of the loss function
#' that were minimized while finding an upper and lower bound for lambda. The
#' sum \code{phase_1_iterations + phase_2_iterations} gives the total number of
#' instances solved.}
#' \item{\code{phase_2_instances}}{The number of instances of the loss function
#' that were minimized while refining the value for lambda. The sum
#' \code{phase_1_iterations + phase_2_iterations} gives the total number of
#' instances solved.}
#' \item{\code{num_clusters}}{The different numbers of clusters that have been
#' found.}
#' \item{\code{n}}{The number of observations in \code{X}.}
#'
#' @examples
#' # Load data
#' data(two_half_moons)
#' data = as.matrix(two_half_moons)
#' X = data[, -3]
#' y = data[, 3]
#'
#' # Get sparse weights in dictionary of keys format with k = 5 and phi = 8
#' W = sparse_weights(X, 5, 8.0)
#'
#' # Perform convex clustering with a target number of clusters
#' res1 = convex_clustering(X, W, target_low = 2, target_high = 5)
#'
#' # Plot the clustering for 2 to 5 clusters
#' oldpar = par(mfrow=c(2, 2))
#' plot(X, col = clusters(res1, 2), main = "2 clusters", pch = 19)
#' plot(X, col = clusters(res1, 3), main = "3 clusters", pch = 19)
#' plot(X, col = clusters(res1, 4), main = "4 clusters", pch = 19)
#' plot(X, col = clusters(res1, 5), main = "5 clusters", pch = 19)
#'
#' # A more generalized approach to plotting the results of a range of clusters
#' res2 = convex_clustering(X, W, target_low = 2, target_high = 7)
#'
#' # Plot the clusterings
#' k = length(res2$num_clusters)
#' par(mfrow=c(ceiling(k / ceiling(sqrt(k))), ceiling(sqrt(k))))
#'
#' for (i in 1:k) {
#' labels = clusters(res2, res2$num_clusters[i])
#' c = length(unique(labels))
#'
#' plot(X, col = labels, main = paste(c, "clusters"), pch = 19)
#' }
#' par(oldpar)
#'
#' @seealso \link{convex_clusterpath}, \link{sparse_weights}
#'
#' @export
convex_clustering <- function(X, W, target_low, target_high = NULL,
max_iter_phase_1 = 2000, max_iter_phase_2 = 20,
lambda_init = 0.01, factor = 0.025, tau = 1e-3,
center = TRUE, scale = TRUE, eps_conv = 1e-6,
burnin_iter = 25, max_iter_conv = 5000,
save_clusterpath = FALSE, verbose = 0)
{
# Input checks
.check_array(X, 2, "X")
.check_weights(W)
.check_int(max_iter_phase_1, FALSE, "max_iter_phase_1")
.check_int(max_iter_phase_2, FALSE, "max_iter_phase_2")
.check_scalar(lambda_init, TRUE, "lambda_init")
.check_scalar(factor, TRUE, "factor")
.check_scalar(tau, TRUE, "tau", upper_bound = 1)
.check_boolean(center, "center")
.check_boolean(scale, "scale")
.check_scalar(eps_conv, TRUE, "eps_conv", upper_bound = 1)
.check_int(burnin_iter, FALSE, "burnin_iter")
.check_int(max_iter_conv, FALSE, "max_iter_conv")
.check_boolean(save_clusterpath, "save_clusterpath")
.check_int(verbose, FALSE, "verbose")
if (is.null(target_high)) {
target_high = target_low
}
.check_cluster_targets(target_low, target_high, nrow(X))
# Preliminaries
n = nrow(X)
# Set the means of each column of X to zero
if (center) {
X_ = X - matrix(apply(X, 2, mean), byrow = TRUE, ncol = ncol(X),
nrow = nrow(X))
} else {
X_ = X
}
# Transpose X
X_ = t(X_)
# Separate the weights into keys and values
W_idx = t(W$keys) - 1
W_val = W$values
# Compute fusion threshold
eps_fusions = .fusion_threshold(X_, tau)
t_start = Sys.time()
clust = .convex_clustering(X_, W_idx, W_val, eps_conv, eps_fusions, scale,
save_clusterpath, burnin_iter, max_iter_conv,
target_low, target_high, max_iter_phase_1,
max_iter_phase_2, verbose, lambda_init, factor)
elapsed_time = difftime(Sys.time(), t_start, units = "secs")
# Stop the program if no clusterings in the range [low, high] have been
# found
if (clust$targets_found < 1) {
message = paste("No clusterings within the range [target_low,",
"target_high] were found. Consider a wider range or",
"set connected = TRUE in sparse_weights(...)")
stop(message)
}
# Construct result
result = list()
result$info = data.frame(
clust$info_d[1, ],
clust$info_i[2, ],
clust$info_d[2, ]
)
result$info = result$info[1:clust$targets_found, ]
names(result$info) = c("lambda", "clusters", "loss")
# Merge table and height vector
result$merge = t(clust$merge)
result$height = clust$height
# Determine order of the observations for a dendrogram
# Start with an entry in a hashmap for each observation
d = hashmap()
for (i in 1:n) {
d[[-i]] = i
}
# Work through the merge table to make sure that everything that is
# merged is next to each other
if (nrow(result$merge) >= 1) {
for (i in 1:nrow(result$merge)) {
d[[i]] = c(d[[result$merge[i, 1]]], d[[result$merge[i, 2]]])
delete(d, result$merge[i, 1])
delete(d, result$merge[i, 2])
}
}
# Finally, create a vector with the order of the observations
result$order = c()
keys = keys(d)
for (key in keys) {
result$order = c(result$order, d[[key]])
}
# Add elapsed time
result$elapsed_time = elapsed_time
# Add clusterpath coordinates
if (save_clusterpath) {
result$coordinates = t(clust$clusterpath)
}
# Add lambdas
result$lambdas = result$info$lambda
# Add fusion threshold
result$eps_fusions = eps_fusions
# Add the number of instances solved
result$phase_1_instances = clust$phase_1_instances
result$phase_2_instances = clust$phase_2_instances
# Add vector of possible cluster counts
result$num_clusters = result$info$clusters
# Add the number of observations
result$n = nrow(X)
# Give the result a class
class(result) = "cvxclust"
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/convex_clustering.R
|
#' Minimize the convex clustering loss function
#'
#' @description Minimizes the convex clustering loss function for a given set of
#' values for lambda.
#'
#' @param X An \eqn{n} x \eqn{p} numeric matrix. This function assumes that each
#' row represents an object with \eqn{p} attributes.
#' @param W A \code{sparseweights} object, see \link{sparse_weights}.
#' @param lambdas A vector containing the values for the penalty parameter.
#' @param tau Parameter to compute the threshold to fuse clusters. Default is
#' 0.001.
#' @param center If \code{TRUE}, center \code{X} so that each column has mean
#' zero. Default is \code{TRUE}.
#' @param scale If \code{TRUE}, scale the loss function to ensure that the
#' cluster solution is invariant to the scale of \code{X}. Default is
#' \code{TRUE}. Not recommended to set to \code{FALSE} unless comparing to
#' algorithms that minimize the unscaled convex clustering loss function.
#' @param eps_conv Parameter for determining convergence of the minimization.
#' Default is 1e-6.
#' @param burnin_iter Number of updates of the loss function that are done
#' without step doubling. Default is 25.
#' @param max_iter_conv Maximum number of iterations for minimizing the loss
#' function. Default is 5000.
#' @param save_clusterpath If \code{TRUE}, store the solution that minimized
#' the loss function for each lambda. Is required for drawing the clusterpath.
#' Default is \code{FALSE}. To store the clusterpath coordinates, \eqn{n} x
#' \eqn{p} x \eqn{no. lambdas} have to be stored, this may require too much
#' memory for large data sets.
#' @param target_losses The values of the loss function that are used to
#' determine convergence of the algorithm (tested as: loss - target <=
#' \code{eps_conv} * target). If the input is not \code{NULL}, it should be a
#' vector with the same length as \code{lambdas}. Great care should be exercised
#' to make sure that the target losses correspond to attainable values for the
#' minimization. The inputs (\code{X}, \code{W}, \code{lambdas}) should be the
#' same, but also the same version of the loss function (centered, scaled)
#' should be used. Default is \code{NULL}.
#' @param save_losses If \code{TRUE}, return the values of the loss function
#' attained during minimization for each value of lambda. Default is
#' \code{FALSE}.
#' @param save_convergence_norms If \code{TRUE}, return the norm of the
#' difference between consecutive iterates during minimization for each value
#' of lambda. Default is \code{FALSE}. If timing the algorithm is of importance,
#' do not set this to \code{TRUE}, as additional computations are done for
#' bookkeeping that are irrelevant to the optimization.
#'
#' @return A \code{cvxclust} object containing the following
#' \item{\code{info}}{A dataframe containing for each value for lambda: the
#' number of different clusters, and the value of the loss function at the
#' minimum.}
#' \item{\code{merge}}{The merge table containing the order at which the
#' observations in \code{X} are clustered.}
#' \item{\code{height}}{The value for lambda at which each reduction in the
#' number of clusters occurs.}
#' \item{\code{order}}{The order of the observations in \code{X} in order to
#' draw a dendrogram without conflicting branches.}
#' \item{\code{elapsed_time}}{The number of seconds that elapsed while
#' running the code. Note that this does not include the time required for
#' input checking and possibly scaling and centering \code{X}.}
#' \item{\code{coordinates}}{The clusterpath coordinates. Only part of the
#' output in case that \code{save_clusterpath=TRUE}.}
#' \item{\code{lambdas}}{The values for lambda for which a clustering was
#' found.}
#' \item{\code{eps_fusions}}{The threshold for cluster fusions that was used by
#' the algorithm.}
#' \item{\code{num_clusters}}{The different numbers of clusters that have been
#' found.}
#' \item{\code{n}}{The number of observations in \code{X}.}
#' \item{\code{losses}}{Optional: if \code{save_losses = TRUE}, the values of
#' the loss function during minimization.}
#' \item{\code{convergence_norms}}{Optional: if
#' \code{save_convergence_norms = TRUE}, the norms of the differences between
#' consecutive iterates during minimization.}
#'
#' @examples
#' # Load data
#' data(two_half_moons)
#' data = as.matrix(two_half_moons)
#' X = data[, -3]
#' y = data[, 3]
#'
#' # Get sparse weights in dictionary of keys format with k = 5 and phi = 8
#' W = sparse_weights(X, 5, 8.0)
#'
#' # Set a sequence for lambda
#' lambdas = seq(0, 2400, 1)
#'
#' # Compute clusterpath
#' res = convex_clusterpath(X, W, lambdas)
#'
#' # Get cluster labels for two clusters
#' labels = clusters(res, 2)
#'
#' # Plot the clusterpath with colors based on the cluster labels
#' plot(res, col = labels)
#'
#' @seealso \link{convex_clustering}, \link{sparse_weights}
#'
#' @export
convex_clusterpath <- function(X, W, lambdas, tau = 1e-3, center = TRUE,
scale = TRUE, eps_conv = 1e-6, burnin_iter = 25,
max_iter_conv = 5000, save_clusterpath = TRUE,
target_losses = NULL, save_losses = FALSE,
save_convergence_norms = FALSE)
{
# Input checks
.check_array(X, 2, "X")
.check_weights(W)
.check_lambdas(lambdas)
.check_scalar(tau, TRUE, "tau", upper_bound = 1)
.check_boolean(center, "center")
.check_boolean(scale, "scale")
.check_scalar(eps_conv, TRUE, "eps_conv", upper_bound = 1)
.check_int(burnin_iter, FALSE, "burnin_iter")
.check_int(max_iter_conv, FALSE, "max_iter_conv")
.check_boolean(save_clusterpath, "save_clusterpath")
.check_boolean(save_losses, "save_losses")
.check_boolean(save_convergence_norms, "save_convergence_norms")
# Check the vector of target losses
if (!is.null(target_losses)) {
.check_array(target_losses, 1, "target_losses")
if (length(lambdas) != length(target_losses)) {
message = "target_losses should have the same length as lambdas"
stop(message)
}
use_target = TRUE
} else {
target_losses = rep(-1, length(lambdas))
use_target = FALSE
}
# Preliminaries
n = nrow(X)
# Set the means of each column of X to zero
if (center) {
X_ = X - matrix(apply(X, 2, mean), byrow = TRUE, ncol = ncol(X),
nrow = nrow(X))
} else {
X_ = X
}
# Transpose X
X_ = t(X_)
# Separate the weights into keys and values
W_idx = t(W$keys) - 1
W_val = W$values
# Compute fusion threshold
eps_fusions = .fusion_threshold(X_, tau)
t_start = Sys.time()
clust = .convex_clusterpath(X_, W_idx, W_val, lambdas, target_losses,
eps_conv, eps_fusions, scale, save_clusterpath,
use_target, save_losses,
save_convergence_norms, burnin_iter,
max_iter_conv)
elapsed_time = difftime(Sys.time(), t_start, units = "secs")
# Construct result
result = list()
result$info = data.frame(
clust$info_d[1, ],
clust$info_i[2, ],
clust$info_d[2, ],
clust$info_i[1, ]
)
names(result$info) = c("lambda", "clusters", "loss", "iterations")
# Merge table and height vector
result$merge = t(clust$merge)
result$height = clust$height
# Determine order of the observations for a dendrogram
# Start with an entry in a hashmap for each observation
d = hashmap()
for (i in 1:n) {
d[[-i]] = i
}
# Work through the merge table to make sure that everything that is
# merged is next to each other
if (nrow(result$merge) >= 1) {
for (i in 1:nrow(result$merge)) {
d[[i]] = c(d[[result$merge[i, 1]]], d[[result$merge[i, 2]]])
delete(d, result$merge[i, 1])
delete(d, result$merge[i, 2])
}
}
# Finally, create a vector with the order of the observations
result$order = c()
keys = keys(d)
for (key in keys) {
result$order = c(result$order, d[[key]])
}
# Add elapsed time
result$elapsed_time = elapsed_time
# Add clusterpath coordinates
if (save_clusterpath) {
result$coordinates = t(clust$clusterpath)
}
# Add lambdas
result$lambdas = result$info$lambda
# Add fusion threshold
result$eps_fusions = eps_fusions
# Add vector of possible cluster counts
result$num_clusters = unique(result$info$clusters)
# Add the number of observations
result$n = nrow(X)
# Give the result a class
class(result) = "cvxclust"
# Add losses
if (save_losses) {
result$losses = clust$losses
}
# Add convergence norms
if (save_convergence_norms) {
result$convergence_norms = clust$convergence_norms
}
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/convex_clusterpath.R
|
#' Two interlocking half moons data set
#'
#' @name two_half_moons
#'
#' @usage data(two_half_moons)
#'
#' @description A dataset containing 150 observations generated according to the
#' two interlocking half moons data generating process. The first two columns
#' contain the x and y-coordinates and the third column contains the cluster ID.
#' Each moon contains 75 observations.
#'
"two_half_moons"
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/data.R
|
.check_array <- function(array, ndim, input_name)
{
if (ndim == 1) {
if (!is.vector(array) || !is.numeric(array)) {
message = paste("Expected 1D numeric vector for", input_name)
stop(message)
}
} else if (ndim == 2) {
if (!is.matrix(array) || !is.numeric(array)) {
message = paste("Expected 2D numeric matrix for", input_name)
stop(message)
}
}
if (sum(is.na(array)) > 0) {
message = paste("Input", input_name, "contains NaN")
stop(message)
}
}
.check_scalar <- function(scalar, positive, input_name, upper_bound = NULL)
{
if (positive && is.null(upper_bound)) {
message = paste("Expected positive numeric value for", input_name)
} else if (positive) {
message = paste("Expected positive numeric value below", upper_bound,
"for", input_name)
} else if (!positive && is.null(upper_bound)) {
message = paste("Expected nonnegative numeric value for", input_name)
} else {
message = paste("Expected nonnegative numeric value below", upper_bound,
"for", input_name)
}
if (length(scalar) != 1 || !is.numeric(scalar)) {
stop(message)
}
if (positive && scalar <= 0) {
stop(message)
} else if (scalar < 0) {
stop(message)
}
if (!is.null(upper_bound)) {
if (scalar >= upper_bound) {
stop(message)
}
}
}
.check_int <- function(scalar, positive, input_name)
{
if (positive) {
message = paste("Expected positive integer for", input_name)
} else {
message = paste("Expected nonnegative integer for", input_name)
}
if (length(scalar) != 1 || !is.numeric(scalar)) {
stop(message)
} else if (scalar != as.integer(scalar)) {
stop(message)
}
if (positive && scalar <= 0) {
stop(message)
} else if (scalar < 0) {
stop(message)
}
}
.check_boolean <- function(boolean, input_name)
{
if (length(boolean) != 1 || !is.logical(boolean)) {
message = paste("Expected logical for", input_name)
stop(message)
}
}
.check_cluster_targets <- function(low, high, n) {
.check_int(low, TRUE, "target_low")
.check_int(high, TRUE, "target_high")
if (high > n) {
message = "Expected target_high <= nrow(X)"
stop(message)
}
if (low > high) {
message = "Expected target_low <= target_high"
stop(message)
}
}
.check_weights <- function(obj)
{
if (!is(obj, "sparseweights")) {
message = paste("Expected sparseweights object for W (generated by",
"sparse_weights(...))")
stop(message)
}
}
.check_lambdas <- function(lambdas)
{
.check_array(lambdas, 1, "lambdas")
if (any(diff(lambdas) <= 0)) {
message = "Expected monotonically increasing values for lambdas"
stop(message)
}
if (any(lambdas < 0)) {
message = "Expected nonnegative values for lambdas"
stop(message)
}
}
.check_cvxclust <- function(obj, input_name)
{
if (!is(obj, "cvxclust")) {
message = paste("Expected cvxclust object for", input_name,
"(generated by convex_clustering(...) or",
"convex_clusterpath(...))")
stop(message)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/input_checks.R
|
#' Plot 2D clusterpath
#'
#' @description Plot a clusterpath for two-dimensional data.
#'
#' @param x A \code{cvxclust} object.
#' @param col A vector containing cluster membership information. Default is
#' \code{NULL}.
#' @param labels A vector containing labels for each object. Default is
#' \code{NULL}.
#' @param ... Further graphical parameters.
#'
#' @return
#' A plot in the console.
#'
#' @examples
#' # Load data
#' data(two_half_moons)
#' data = as.matrix(two_half_moons)
#' X = data[, -3]
#' y = data[, 3]
#'
#' # Get sparse distances in dictionary of keys format with k = 5 and phi = 8
#' W = sparse_weights(X, 5, 8.0)
#'
#' # Set a sequence for lambda
#' lambdas = seq(0, 2400, 1)
#'
#' # Compute results CMM
#' res = convex_clusterpath(X, W, lambdas)
#' plot(res, y + 1)
#'
#' @export
plot.cvxclust <- function(x, col = NULL, labels = NULL, ...)
{
# Input checks
.check_cvxclust(x, "x")
if (is.null(x$coordinates)) {
message = paste("The clusterpath coordinates were not saved. Make sure",
"to set save_clusterpath = TRUE in",
"convex_clustering(...) or convex_clusterpath(...)")
stop(message)
}
if (ncol(x$coordinates) != 2) {
stop(paste("plot.clusterpath is only implemented for two-dimensional",
"clusterpaths"))
}
# Get the number of observations and the number of lambdas used for the path
n_obs = x$n
n_lam = length(x$lambdas)
# X is the first set of observations
X = x$coordinates[c(1:n_obs), ]
plot(X, pch = 1, las = 1, xlab = expression(X[1]), ylab = expression(X[2]),
asp = 1, ...)
# Draw the paths
for (i in 1:n_obs) {
graphics::lines(x$coordinates[seq(i, n_obs * n_lam, n_obs), ],
col = "grey", cex=0.5)
}
# Give the dots colors to denote cluster membership
if (!is.null(col)) {
graphics::points(X[, 1:2], pch = 19, col = col)
} else {
graphics::points(X[, 1:2], pch = 19, col = "black")
}
# Add labels
if (!is.null(labels)) {
graphics::text(X[, 1], X[, 2], labels = labels, cex= 0.7, pos=3)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/plot.R
|
#' Computation of sparse weight matrix
#'
#' @description Construct a sparse weight matrix in a dictionary-of-keys format.
#' Each nonzero weight is computed as \eqn{exp(-phi * ||x_i - x_j||^2)}, where
#' the squared Euclidean distance may be scaled by the average squared Euclidean
#' distance, depending on the argument \code{scale}. Sparsity is achieved by
#' only setting weights to nonzero values that correspond to two objects that
#' are among each other's \eqn{k} nearest neighbors.
#'
#' @param X An \eqn{n} x \eqn{p} numeric matrix. This function assumes that each
#' row represents an object with \eqn{p} attributes.
#' @param k The number of nearest neighbors to be used for non-zero weights.
#' @param phi Tuning parameter of the Gaussian weights. Input should be a
#' nonnegative value.
#' @param connected If \code{TRUE}, guarantee a connected structure of the
#' weight matrix. This ensures that groups of observations that would not be
#' connected through weights that are based only on the \code{k} nearest
#' neighbors are (indirectly) connected anyway. The method is determined by
#' the argument \code{connection_type}. Default is \code{TRUE}.
#' @param scale If \code{TRUE}, scale each squared l2-norm by the mean squared
#' l2-norm to ensure scale invariance of the weights. Default is \code{TRUE}.
#' @param connection_type Determines the method to ensure a connected weight
#' matrix if \code{connected} is \code{TRUE}. Should be one of
#' \code{c("SC", "MST")}. SC stands for the method using a symmetric circulant
#' matrix, connecting objects \eqn{i} with objects \eqn{i+1} (and \eqn{n} with
#' \eqn{1}). MST stands for minimum spanning tree. The graph that results from
#' the nonzero weights determined by the \eqn{k} nearest neighbors is divided
#' into \eqn{c} subgraphs and a minimum spanning tree algorithm is used to add
#' \eqn{c-1} nonzero weights to ensure that all objects are indirectly
#' connected. Default is \code{"SC"}.
#'
#' @return A \code{sparseweights} object containing the nonzero weights in
#' dictionary-of-keys format.
#'
#' @examples
#' # Load data
#' data(two_half_moons)
#' data = as.matrix(two_half_moons)
#' X = data[, -3]
#' y = data[, 3]
#'
#' # Get sparse distances in dictionary of keys format with k = 5 and phi = 8
#' W = sparse_weights(X, 5, 8.0)
#'
#' @export
sparse_weights <- function(X, k, phi, connected = TRUE, scale = TRUE,
connection_type = "SC")
{
# Input checks
.check_array(X, 2, "X")
.check_int(k, TRUE, "k")
.check_scalar(phi, FALSE, "phi")
.check_boolean(connected, "connected")
.check_boolean(scale, "scale")
if (!(connection_type %in% c("SC", "MST"))) {
message = "Expected one of 'SC' and 'MST' for connection_type"
stop(message)
}
# Preliminaries
n = nrow(X)
# Get the k nearest neighbors
nn_res = RANN::nn2(X, X, k + 1)
nn_idx = nn_res$nn.idx - 1
nn_dists = nn_res$nn.dists
# Transform the indices of the k-nn into a dictionary of keys sparse matrix
res = .sparse_weights(t(X), t(nn_idx), t(nn_dists), phi, k,
(connection_type == "SC") && connected, scale)
# Unique keys and value pairs
keys = t(res$keys)
values = res$values
u_idx = !duplicated(keys)
keys = keys[u_idx, ]
values = values[u_idx]
if (connection_type == "MST" && connected) {
# Use the keys of the sparse weight matrix to find clusters in the data
id = .find_subgraphs(t(keys), nrow(X)) + 1
# Number of disconnected parts of the graph
n_clusters = max(id)
if (n_clusters > 1) {
# List to keep track of which objects are responsible for those
# distances
closest_objects = list()
# Matrix to keep track of the shortest distance between the clusters
D_between = matrix(0, nrow = n_clusters, ncol = n_clusters)
for (a in 2:nrow(D_between)) {
for (b in 1:(a - 1)) {
# Find out which member of cluster a is closest to each of
# the members of cluster b
nn_between = RANN::nn2(X[id == a, ], X[id == b, ], 1)
# Get the indices of the objects with respect to their
# cluster
b_idx = which.min(nn_between$nn.dists)
a_idx = nn_between$nn.idx[b_idx]
# Save the distance
D_between[a, b] = nn_between$nn.dists[b_idx]
D_between[b, a] = nn_between$nn.dists[b_idx]
# Get the original indices of the objects
a_idx = c(1:nrow(X))[id == a][a_idx] - 1
b_idx = c(1:nrow(X))[id == b][b_idx] - 1
# Store the objects
idx = (a - 1) * (a - 2) / 2 + b
closest_objects[[idx]] = c(a_idx, b_idx)
}
}
# Find minimum spanning tree for D_between
mst_keys = .find_mst(D_between) + 1
# Vector for the weights
mst_values = rep(0, nrow(mst_keys))
# Get the true object indices from the closest_objects list
for (i in 1:nrow(mst_keys)) {
# Get the index for the closest_objects list
ii = min(mst_keys[i, 1], mst_keys[i, 2]) - 1
jj = max(mst_keys[i, 1], mst_keys[i, 2]) - 1
idx = jj * (jj - 1) / 2 + ii + 1
# Fill in the weights in the values vector
mst_values[i] = D_between[mst_keys[i, 1], mst_keys[i, 2]]
# Replace the cluster ids by the object ids
mst_keys[i, ] = closest_objects[[idx]]
}
# Because both the upper and lower part of the weight matrix are
# stored, the key and value pairs are duplicated
mst_keys = rbind(mst_keys, mst_keys[, c(2, 1)])
mst_values = c(mst_values, mst_values)
# Compute the weights from the distances
if (scale) {
mst_values = exp(-phi * mst_values^2 / res$msd)
} else {
mst_values = exp(-phi * mst_values^2)
}
# Append everything to the existing keys and values, ensuring a
# connected weight matrix based on a minimum spanning tree
keys = rbind(keys, mst_keys)
values = c(values, mst_values)
}
}
# Store the keys in column major format
sorted_idx = order(keys[, 2], keys[, 1])
keys = keys[sorted_idx, ]
values = values[sorted_idx]
# In R, counting starts at 1
keys = keys + 1
# Prepare result
result = list()
result$keys = keys
result$values = values
class(result) = "sparseweights"
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/sparse_weights.R
|
.onUnload <- function (libpath)
{
library.dynam.unload("CCMMR", libpath)
}
.onAttach <- function(libname, pkgname)
{
package_citation = paste("\nTouw, D.J.W., Groenen, P.J.F., and Terada, Y.",
"(2022). Convex Clustering through MM: An",
"Efficient Algorithm to Perform Hierarchical",
"Clustering. arXiv preprint arXiv:2211.01877.\n")
msg = paste("Thank you for using CCMMR!",
"To acknowledge our work, please cite the paper:",
package_citation, sep = "\n")
packageStartupMessage(msg)
}
|
/scratch/gouwar.j/cran-all/cranData/CCMMR/R/zzz.R
|
.packageName <- "CCP"
"WilksLambda" <-
function(rho,p,q)
{
minpq <- min(p, q)
WilksLambda <- numeric(minpq)
for (rhostart in 1:minpq) {
WilksLambda[rhostart] <- prod((1 - rho^2)[rhostart:minpq])
}
invisible(WilksLambda)
}
"HotellingLawleyTrace" <-
function (rho, p, q)
{
minpq <- min(p, q)
HotellingLawleyTrace <- numeric(minpq)
for (rhostart in 1:minpq) {
rhosq = rho^2
HotellingLawleyTrace[rhostart] = sum((rhosq/(1-rhosq))[rhostart:minpq])
}
invisible(HotellingLawleyTrace)
}
"PillaiBartlettTrace" <-
function (rho, p, q)
{
minpq <- min(p, q)
PillaiBartlettTrace <- numeric(minpq)
for (rhostart in 1:minpq) {
PillaiBartlettTrace[rhostart] = sum((rho^2)[rhostart:minpq])
}
invisible(PillaiBartlettTrace)
}
"RaoF.stat" <-
function (rho, N, p, q)
{
minpq <- min(p, q)
WilksLambda <- WilksLambda(rho,p,q)
RaoF <- numeric(minpq)
df1 <- numeric(minpq)
df2 <- numeric(minpq)
de = N - 1.5 - (p + q)/2
for (rhostart in 1:minpq) {
k = rhostart - 1 # 0,1,2
df1[rhostart] = (p-k)*(q-k)
if ((p-k == 1)||(q-k == 1))
nu = 1
else
nu = sqrt((df1[rhostart]^2-4)/((p-k)^2+(q-k)^2-5))
df2[rhostart] = de*nu - df1[rhostart]/2 + 1
nu1 = 1/nu
w = WilksLambda[rhostart]^nu1
RaoF[rhostart] = df2[rhostart]/df1[rhostart]*(1-w)/w
}
invisible(list(stat = WilksLambda, approx = RaoF, df1 = df1, df2 = df2))
}
"Hotelling.stat" <-
function (rho, N, p, q)
{
minpq <- min(p, q)
HotellingLawleyTrace <- HotellingLawleyTrace(rho, p, q)
Hotelling <- numeric(minpq)
df1 <- numeric(minpq)
df2 <- numeric(minpq)
for (rhostart in 1:minpq) {
k = rhostart - 1
df1[rhostart] = (p - k)*(q - k)
df2[rhostart] = minpq*(N - 2 - p - q + 2*k) + 2
Hotelling[rhostart] = HotellingLawleyTrace[rhostart]/minpq/df1[rhostart] * df2[rhostart]
}
invisible(list(stat = HotellingLawleyTrace, approx = Hotelling, df1 = df1, df2 = df2))
}
"Pillai.stat" <-
function (rho, N, p, q)
{
minpq <- min(p, q)
PillaiBartlettTrace <- PillaiBartlettTrace(rho, p, q)
Pillai <- numeric(minpq)
df1 <- numeric(minpq)
df2 <- numeric(minpq)
for (rhostart in 1:minpq) {
k = rhostart - 1
df1[rhostart] = (p - k)*(q - k)
df2[rhostart] = minpq*(N - 1 + minpq - p - q + 2*k)
Pillai[rhostart] = PillaiBartlettTrace[rhostart] / df1[rhostart] * df2[rhostart] / ( minpq - PillaiBartlettTrace[rhostart] )
}
invisible(list(stat = PillaiBartlettTrace, approx = Pillai, df1 = df1, df2 = df2))
}
"p.Roy" <-
function (rho, N, p, q)
{
stat <- rho[1]^2 # Roy
df1 <- q
df2 <- N - 1 - q
approx <- stat / df1 * df2 / ( 1 - stat )
p.value <- 1 - pf(approx, df1, df2)
invisible(list(id="Roy", stat = stat, approx = approx, df1 = df1, df2 = df2, p.value = p.value))
}
"p.asym" <-
function (rho, N, p, q, tstat = "Wilks")
{
minpq <- min(p, q)
if (length(rho) != minpq)
stop(" Function p.asym: Improper length of vector containing the canonical correlations.\n")
if (tstat == "Wilks")
{
out <- RaoF.stat(rho, N, p, q)
head <- paste("Wilks' Lambda, using F-approximation (Rao's F):\n")
}
else if ( tstat == "Hotelling" )
{
out <- Hotelling.stat(rho, N, p, q)
head <- paste(" Hotelling-Lawley Trace, using F-approximation:\n")
}
else if ( tstat == "Pillai" )
{
out <- Pillai.stat(rho, N, p, q)
head <- paste(" Pillai-Bartlett Trace, using F-approximation:\n")
}
else if ( tstat == "Roy" )
{
minpq = 1
out <- p.Roy(rho, N, p, q)
head <- paste(" Roy's Largest Root, using F-approximation:\n")
}
else
stop(" Function p.asym: test statistic must be of type 'Wilks', 'Hotelling', 'Pillai', or 'Roy'.\n")
stat <- out$stat
approx <- out$approx
df1 <- out$df1
df2 <- out$df2
p.value <- numeric(minpq)
for (rhostart in 1:minpq) {
p.value[rhostart] <- 1 - pf(approx[rhostart], df1[rhostart], df2[rhostart])
}
tab <- cbind(stat, approx, df1, df2, p.value)
rn = character(length = minpq)
for (k in 1:minpq) rn[k] = paste(k," to ",minpq,": ",sep = "")
rownames(tab) = rn
cat(head)
print(tab)
if ( tstat == "Roy" )
cat("\n F statistic for Roy's Greatest Root is an upper bound.\n")
invisible(list(id = tstat, stat = stat, approx = approx, df1 = df1, df2 = df2, p.value = p.value))
}
"p.perm" <-
function(X, Y, nboot = 999, rhostart = 1, type = "Wilks")
{
if( nrow(Y) != nrow(X))
stop(" Function p.perm: Input arrays must not have unequal number of rows.\n")
if( (type == "Roy") && (rhostart > 1) )
stop(" Function p.perm: When using Roy's Largest Root, parameter rhostart can only be 1.\n")
N <- nrow(Y)
ind <- 1:N
p = dim(X)[2]
q = dim(Y)[2]
minpq = min(p,q)
if( rhostart > minpq )
stop(" Function p.perm: Parameter rhostart too big.\n")
rho0 <- cancor(X,Y[ind,])$cor
if (type == "Wilks")
stat0 <- WilksLambda(rho0,p,q)[rhostart]
else if ( type == "Hotelling" )
stat0 <- HotellingLawleyTrace(rho0,p,q)[rhostart]
else if ( type == "Pillai" )
stat0 <- PillaiBartlettTrace(rho0,p,q)[rhostart]
else if ( type == "Roy" )
stat0 <- p.Roy(rho0,N,p,q)$stat
else
stop(" Function p.perm: Illegal type of test statistic.\n")
stat <- numeric(nboot)
for (i in 1:nboot ) {
ind.mixed <- sample(ind, size = N, replace = FALSE)
rho <- cancor(X,Y[ind.mixed,])$cor
if (type == "Wilks")
stat[i] <- WilksLambda(rho,p,q)[rhostart]
else if ( type == "Hotelling" )
stat[i] <- HotellingLawleyTrace(rho,p,q)[rhostart]
else if ( type == "Pillai" )
stat[i] <- PillaiBartlettTrace(rho,p,q)[rhostart]
else if ( type == "Roy" )
stat[i] <- p.Roy(rho,N,p,q)$stat
}
if (type == "Wilks") {
nexcess <- sum(stat <= stat0)
p <- mean(stat <= stat0)
}
else {
nexcess <- sum(stat >= stat0)
p <- mean(stat >= stat0)
}
mstat = mean(stat)
tab <- cbind(stat0,mstat,nboot,nexcess,p)
rownames(tab) = ""
cat(" Permutation resampling using",type,"'s statistic:\n")
print(tab)
invisible(list(id="Permutation", type = type, stat0 = stat0, stat = stat, nexcess = nexcess, p.value = p))
}
"plt.asym" <-
function(p.asym.out, rhostart = 1)
{
if ("id" %in% names(p.asym.out))
type <- p.asym.out$id
else
stop(" Function plt.asym: Use output of 'p.asym' as input for 'plt.asym'.\n")
if ( rhostart > length(p.asym.out$stat) )
stop(" Function plt.asym: Parameter 'rhostart' too big for this dataset.\n")
df1 <- p.asym.out$df1[rhostart]
df2 <- p.asym.out$df2[rhostart]
stat <- p.asym.out$approx[rhostart]
pval <- p.asym.out$p.value[rhostart]
minpq = length(p.asym.out$df1)
if (type == "Wilks")
head <- paste("F-approximation for Wilks Lambda, rho =", rhostart, "to", minpq)
else if ( type == "Hotelling" )
head <- paste("F-approximation for Hotelling-Lawley Trace, rho=", rhostart, "to", minpq)
else if ( type == "Pillai" )
head <- paste("F-approximation for Pillai-Bartlett Trace, rho=", rhostart, "to", minpq)
else if ( type == "Roy" )
head <- paste("F-approximation for Roys Largest Root, rho=", rhostart, "to", minpq)
pv = format(pval, scientific = FALSE, digits = 3)
dv2 = format(df2, scientific = FALSE, digits = 3)
statf = format(stat, scientific = FALSE, digits = 3)
subtext = paste("F=", statf, ", df1=", df1, ", df2=", dv2,", p=", pv)
x = seq(qf(0.005,df1,df2), qf(0.995,df1,df2), length.out= 200)
plot(x, df(x,df1,df2), main = head, ylab = "", xlab = "", lwd = 2, type = "l", col = "grey", sub = subtext)
abline(v = stat, lwd = 3, col = "red", lty=3)
abline(h = 0, lwd = 2, col = "grey", lty = 3)
}
"plt.perm" <-
function(p.perm.out)
{
if ("id" %in% names(p.perm.out))
id = p.perm.out$id
else
stop(" Function plot.perm: Use output of p.perm as input for plot.perm(1).\n")
if (id != "Permutation")
stop(" Function plot.perm: Use output of p.perm as input for plot.perm(2).\n")
stat0 = p.perm.out$stat0
stat = p.perm.out$stat
pval = p.perm.out$p.value
nexcess = p.perm.out$nexcess
type = p.perm.out$type
head <- "Permutation distribution"
hist(stat, breaks = 30, freq = FALSE, main = head)
sform = format(stat0, scientific = FALSE, digits = 3)
pv = format(pval, scientific = FALSE, digits = 3)
mtext(paste("test=",type, ", original test statistic=", sform, ", p=",pv), side = 3)
abline(v=mean(stat),lwd=2,col="grey",lty=3)
abline(v=stat0,lwd=3,col="red",lty=3)
}
|
/scratch/gouwar.j/cran-all/cranData/CCP/R/CCP.R
|
######################
#Begin CCTpack
######################
.onLoad <- function(libname, pkgname) {
assign("pkg_globals", new.env(), envir=parent.env(environment()))
}
######################
#Initializations
######################
options(warn=-3)
### Some users have reported memory allocation errors when a high limit is not set here.
suppressMessages(try(memory.limit(10000),silent=TRUE))
suppressMessages(try(memory.limit(20000),silent=TRUE))
options(warn=0)
######################
#Supplementary Functions
######################
Mode <- function(x) {ux <- unique(x); ux[which.max(tabulate(match(x, ux)))] }
probit <- function(x) {probval <- qnorm(x,0,1); return(probval)}
invprobit <- function(x) {invprobval <- pnorm(x,0,1); return(invprobval)}
######################
#CCTpack GUI, invoked with the command cctgui()
######################
cctgui <- function(){
######################
#Sets Default GUI Variables and Frames
######################
guidat <- list();
guidat$tt <- tktoplevel(bg="#CDEED6")
guidat$datframe <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$datframe2 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$datframe3 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$datframe4 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$applyframe1 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$applyframe2 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$applyframe3 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$resultsframe1 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$resultsframe2 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$resultsframe3 <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$settingsframe <- tkframe(guidat$tt, borderwidth = 0,bg="#CDEED6")
guidat$polywind <- FALSE
guidat$mval <- FALSE
guidat$samplesvar <- tclVar("10000")
guidat$chainsvar <- tclVar("3")
guidat$burninvar <- tclVar("2000")
guidat$thinvar <- tclVar("1")
guidat$culturesvar <- tclVar("1")
guidat$paravar <- tclVar("1")
guidat$itemdiffvar <- tclVar("0")
guidat$polyvar <- tclVar("0")
guidat$varnametry <- tclVar("cctfit")
tkwm.title(guidat$tt,"CCT Model Application Software")
######################
#The GUI Grid Setup
######################
guidat$samples.entry <- tkentry(guidat$settingsframe, textvariable=guidat$samplesvar,width="6")
guidat$chains.entry <- tkentry(guidat$settingsframe, textvariable=guidat$chainsvar,width="2")
guidat$burnin.entry <- tkentry(guidat$settingsframe, textvariable=guidat$burninvar,width="6")
guidat$thin.entry <- tkentry(guidat$settingsframe, textvariable=guidat$thinvar,width="2")
guidat$loaddata.but <- tkbutton(guidat$datframe, text="Load Data", command=loadfilefuncbutton)
guidat$screeplot.but <- tkbutton(guidat$datframe, text="Scree Plot", command=screeplotfuncbutton)
guidat$poly.but <- tkcheckbutton(guidat$datframe4,variable=guidat$polyvar,text="Use polychoric correlations",bg="#CDEED6")
guidat$para.but <- tkcheckbutton(guidat$applyframe2,variable=guidat$paravar,text="Parallel run",bg="#CDEED6")
guidat$item.but <- tkcheckbutton(guidat$applyframe2,variable=guidat$itemdiffvar,text="Item difficulty",bg="#CDEED6")
guidat$cultdown.but <- tkbutton(guidat$applyframe2, text="<", command=cultdownfuncbutton)
guidat$cultup.but <- tkbutton(guidat$applyframe2, text=">", command=cultupfuncbutton)
guidat$applymodel.but <- tkbutton(guidat$applyframe2, text="Apply CCT Model", command=applymodelfuncbutton)
guidat$cultures.entry <- tkentry(guidat$applyframe2, textvariable=guidat$culturesvar,width="2",disabledforeground="black",disabledbackground="white")
guidat$varname.entry <- tkentry(guidat$applyframe3, textvariable=guidat$varnametry,width="10")
tkbind(guidat$varname.entry, "<Key>", valid_inputkey)
tkbind(guidat$varname.entry, "<FocusOut>", valid_inputfo)
tkbind(guidat$varname.entry, "<Return>", valid_inputfo)
guidat$plotresults.but <- tkbutton(guidat$resultsframe1, text = "Plot Results", command = plotresultsfuncbutton)
guidat$doppc.but <- tkbutton(guidat$resultsframe1, text = "Run Checks", command = ppcfuncbutton)
guidat$exportresults.but <- tkbutton(guidat$resultsframe1, text = "Export Results", command = exportfuncbutton)
guidat$memb.but <- tkbutton(guidat$resultsframe2, text = "Cluster Membs", command = membfuncbutton)
guidat$mvest.but <- tkbutton(guidat$resultsframe2, text = "NA Value Est", command = mvestfuncbutton)
guidat$traceplotdiscrete.but <- tkbutton(guidat$resultsframe2, text = "Traceplot Discrete", command = traceplotdiscretefuncbutton)
guidat$traceplotall.but <- tkbutton(guidat$resultsframe2, text = "Traceplot All", command = traceplotallfuncbutton)
guidat$printfit.but <- tkbutton(guidat$resultsframe3, text = "Print Fit", command = printfitfuncbutton)
guidat$summary.but <- tkbutton(guidat$resultsframe3, text = "Fit Summary", command = summaryfuncbutton)
guidat$sendconsole.but <- tkbutton(guidat$resultsframe3, text = "Send Console", command = sendconsolefuncbutton)
guidat$datafiletxt <- tktext(guidat$tt,bg="white",width=20,height=1)
guidat$resptxt <- tktext(guidat$tt,bg="white",width=4,height=1)
guidat$itemtxt <- tktext(guidat$tt,bg="white",width=4,height=1)
guidat$dattypetxt <- tktext(guidat$tt,bg="white",width=11,height=1)
guidat$modeltxt <- tktext(guidat$tt,bg="white",width=4,height=1)
tkgrid(guidat$datframe,columnspan=3,row=1,column=0)
tkgrid(guidat$datframe2,columnspan=4,row=2,column=0)
tkgrid(guidat$datframe3,columnspan=4,row=3,column=0)
tkgrid(guidat$datframe4,columnspan=5,row=4,column=0)
tkgrid(guidat$applyframe1,columnspan=10,row=5,column=0)
tkgrid(guidat$applyframe2,columnspan=10,row=6,column=0)
tkgrid(guidat$applyframe3,columnspan=10,row=7,column=0)
tkgrid(guidat$resultsframe1,columnspan=3,row=8)
tkgrid(guidat$resultsframe2,columnspan=4,row=9)
tkgrid(guidat$resultsframe3,columnspan=3,row=10)
tkgrid(guidat$settingsframe,columnspan=8,row=11)
tkgrid(tklabel(guidat$datframe,text="",bg="#CDEED6"),columnspan=3, pady = 0)
tkgrid(tklabel(guidat$datframe,text="Data Input",bg="#CDEED6"),columnspan=3, pady = 2)
tkgrid(guidat$loaddata.but,guidat$datafiletxt,guidat$screeplot.but,pady= 10, padx= 10)
tkgrid(tklabel(guidat$datframe2,text="Number of Respondents",bg="#CDEED6"),guidat$resptxt,tklabel(guidat$datframe2,text="Number of Items",bg="#CDEED6"),guidat$itemtxt, padx = 2, pady = 5)
tkgrid(tklabel(guidat$datframe3,text="Data Type Detected",bg="#CDEED6"),guidat$dattypetxt,tklabel(guidat$datframe3,text="CCT Model",bg="#CDEED6"),guidat$modeltxt, padx = 2, pady = 5)
tkgrid(tklabel(guidat$applyframe1,text="Model Application",bg="#CDEED6"),columnspan=3, pady = 5)
tkgrid(guidat$cultdown.but, guidat$cultures.entry, guidat$cultup.but, tklabel(guidat$applyframe2,text="Cultures",bg="#CDEED6"),guidat$item.but,guidat$para.but,guidat$applymodel.but,pady= 10, padx= 2)
tkgrid(guidat$varname.entry,tklabel(guidat$applyframe3,text="Name of Fit",bg="#CDEED6"),padx= 2)
tkconfigure(guidat$screeplot.but, state="disabled")
tkgrid(tklabel(guidat$resultsframe1,text="Application Results",bg="#CDEED6"),columnspan=3, pady = 5)
tkgrid(guidat$doppc.but,guidat$plotresults.but,guidat$exportresults.but,pady= 5, padx= 10)
tkgrid(guidat$memb.but,guidat$mvest.but,guidat$traceplotdiscrete.but,guidat$traceplotall.but,pady= 5, padx= 5)
tkgrid(guidat$printfit.but,guidat$summary.but,guidat$sendconsole.but,pady= 5, padx= 10)
tkconfigure(guidat$applymodel.but, state="disabled")
tkconfigure(guidat$plotresults.but, state="disabled")
tkconfigure(guidat$doppc.but, state="disabled")
tkconfigure(guidat$exportresults.but, state="disabled")
tkconfigure(guidat$printfit.but, state="disabled")
tkconfigure(guidat$summary.but, state="disabled")
tkconfigure(guidat$sendconsole.but, state="disabled")
tkconfigure(guidat$memb.but, state="disabled")
tkconfigure(guidat$mvest.but, state="disabled")
tkconfigure(guidat$traceplotdiscrete.but, state="disabled")
tkconfigure(guidat$traceplotall.but, state="disabled")
tkgrid(tklabel(guidat$settingsframe,text="Sampler Settings (Optional)",bg="#CDEED6"),columnspan=8, pady = 5)
tkgrid(tklabel(guidat$settingsframe,text="Samples",bg="#CDEED6"), guidat$samples.entry, tklabel(guidat$settingsframe,text="Chains",bg="#CDEED6"), guidat$chains.entry, tklabel(guidat$settingsframe,text="Burn-in",bg="#CDEED6"), guidat$burnin.entry, tklabel(guidat$settingsframe,text="Thinning",bg="#CDEED6"), guidat$thin.entry, pady= 10, padx= 2)
tkgrid(tklabel(guidat$settingsframe,text="",bg="#CDEED6"),columnspan=8, pady = 0)
tkconfigure(guidat$cultures.entry, bg="white", state="disabled", background="black")
tkinsert(guidat$datafiletxt,"end","(load data file)")
tkconfigure(guidat$datafiletxt, state="disabled")
tkconfigure(guidat$resptxt, state="disabled")
tkconfigure(guidat$itemtxt, state="disabled")
tkconfigure(guidat$dattypetxt, state="disabled")
tkconfigure(guidat$modeltxt, state="disabled")
tkconfigure(guidat$varname.entry, state="disabled")
tkconfigure(guidat$para.but, state="disabled")
tkconfigure(guidat$item.but, state="disabled")
tkconfigure(guidat$cultdown.but, state="disabled")
tkconfigure(guidat$cultup.but, state="disabled")
tkgrid.columnconfigure(guidat$tt,0,weight=1)
tkgrid.rowconfigure(guidat$tt,0,weight=1)
tkwm.resizable(guidat$tt,0,0)
guidat$guidatnames <- names(guidat)
list2env(guidat,pkg_globals)
assign("guidat", guidat, pkg_globals)
message("\n ...Starting CCT Inference Software\n")
}
######################
#Standalone Functions to use instead of the GUI
######################
######################
#All-in-one function to do each of the GUI tasks, if the gui is not compatible for the user, or not preferred
#- Takes in a data as a respondent by item array or matrix
#- 'clusters' defines # of clusters, and 'itemdiff' if item difficulty is wanted
#- 'jags' defines for the JAGS MCMC, the number of samples, chains, burn-in, thinning
#- 'runchecks' if one wants the posterior predictive checks calculated after inference
#- 'exportfilename' set a name different from "" if one wants to automatically export the results
# to the working directory
######################
cctapply <- function(data,clusters=1,itemdiff=FALSE,biases=TRUE,samples=10000,chains=3,burnin=2000,thinning=1,runchecks=FALSE,exportfilename="",polych=FALSE,parallel=FALSE,seed=NULL,plotr=FALSE){
if(!is.null(seed)){
set.seed(1); rm(list=".Random.seed", envir=globalenv())
set.seed(seed)
}else{set.seed(1); rm(list=".Random.seed", envir=globalenv())}
datob <- loadfilefunc(data)
datob <- screeplotfunc(datob,noplot=TRUE)
cctfit <- applymodelfunc(datob,clusters=clusters,itemdiff=itemdiff,biases=biases,jags.iter=samples,jags.chains=chains,jags.burnin=burnin,jags.thin=thinning,parallel=parallel)
if(plotr==TRUE){plotresultsfunc(cctfit)}
if(runchecks==TRUE){
cctfit <- ppcfunc(cctfit,polych=polych,doplot=FALSE)
}
if(exportfilename!=""){
exportfunc(cctfit,filename=exportfilename)
}
return(cctfit)
}
######################
#Manual function to do the scree plot, equivalent to the 'Scree Plot Button'
#- Takes in a data as a respondent by item array or matrix
######################
cctscree <- function(data,polych=FALSE){
datob <- loadfilefunc(data)
datob <- screeplotfunc(datob,polych=polych)
}
######################
#Manual function to plot the results, equivalent to the 'Plot Results Button'
#- Takes the cctfit object from cctapply() or the 'Apply CCT Model' button
######################
cctresults <- function(cctfit){
plotresultsfunc(cctfit)
}
######################
#Manual function to plot the posterior predictive check plots, equivalent to the 'Run Checks Button'
#- Takes the cctfit object from cctapply() or the 'Apply CCT Model' button
#- Plots the posterior predictive checks, or calculates them and then plots them (if they have not been calculated yet)
######################
cctchecks <- cctppc <- function(cctfit,polych=FALSE,doplot=TRUE){
if(cctfit$whmodel=="LTRM" && cctfit$checksrun==TRUE){
if(cctfit$polycor!=polych){cctfit$checksrun <- FALSE}
}
cctfit <- ppcfunc(cctfit,polych=polych)
return(cctfit)
}
######################
#Manual function to export the results, equivalent to the 'Export Results Button'
#- Takes the cctfit object from cctapply() or the 'Apply CCT Model' button
#- Exports the cctfit object as a .Rdata file, and plots of the scree plot,
# posterior results, and posterior predictive checks
######################
cctexport <- function(cctfit,filename="CCTpackdata.Rdata"){
cctfit <- exportfunc(cctfit,filename=filename)
}
######################
#End of Standalone Functions
######################
#######################
#Background Functions for the GUI and/or Standalone Functions
######################
######################
#Function for the 'Load Data' Button
#- Detects the type of data
#- Detects the number of respondents and number of items
#- Selects the appropriate model for the data
#- Detects the number of missing data points (NA values)
#- Estimates initial estimates for missing data (if any) for the initial scree plot
#- Reports this information back to the GUI or R console
#- Enables the Apply Model Button on the GUI
#- Disables buttons GUI buttons: 'Run Checks', 'Plot Results', 'Export Results'
# if they are active from a previous run
######################
loadfilefuncbutton <- function(){
loadfilefunc(gui=TRUE)
}
loadfilefunc <- function(data=0,gui=FALSE,polych=FALSE){
if(gui==TRUE){guidat <- get("guidat", pkg_globals)}
datob <- list(); datob$polych <- polych; datob$datfactorsp <- 1; datob$datfactorsc
if(gui==TRUE){
datob$fileName <- file.path(tclvalue(tkgetOpenFile(filetypes = "{{csv Files} {.csv .txt}}")))
if (!nchar(datob$fileName)) {
return()
}else{
datob$dat <- as.matrix(read.csv(datob$fileName,header=FALSE))
if(is.list(datob$dat)){
datob$dat <- matrix(as.numeric(unlist(datob$dat)),dim(datob$dat)[1],dim(datob$dat)[2])
}
options(warn=-3)
if(!is.numeric(datob$dat[1,1])){datob$dat <- matrix(as.numeric(datob$dat),dim(datob$dat)[1],dim(datob$dat)[2])
if(all(is.na(datob$dat[,1]))){datob$dat <- datob$dat[,-1];
}
if(all(is.na(datob$dat[1,]))){datob$dat <- datob$dat[-1,];
}
}
if(sum(is.na(datob$dat))>0){
datob$thena <- which(is.na(datob$dat),arr.ind=TRUE)
datob$thenalist <- which(is.na(datob$dat))
datob$dat[datob$thena] <- datob$dat[max(which(!is.na(datob$dat)),arr.ind=TRUE)]
datob$mval <- TRUE
}else{datob$mval <- FALSE}
options(warn=0)
if(all(datob$dat[1:dim(datob$dat)[1],1]==1:dim(datob$dat)[1])){datob$dat <- datob$dat[,-1]; if(datob$mval==TRUE){datob$thena[,2] <- datob$thena[,2] - 1}}
setwd(file.path(dirname(datob$fileName)))
tkconfigure(guidat$screeplot.but, state="normal")
tkconfigure(guidat$applymodel.but, state="normal")
}
tkconfigure(guidat$datafiletxt, state="normal")
tkconfigure(guidat$resptxt, state="normal")
tkconfigure(guidat$itemtxt, state="normal")
tkconfigure(guidat$dattypetxt, state="normal")
tkconfigure(guidat$modeltxt, state="normal")
tkconfigure(guidat$para.but, state="normal")
tkconfigure(guidat$item.but, state="normal")
tkconfigure(guidat$cultdown.but, state="normal")
tkconfigure(guidat$cultup.but, state="normal")
tkdelete(guidat$datafiletxt,"1.0","800.0")
tkdelete(guidat$resptxt,"1.0","800.0")
tkdelete(guidat$itemtxt,"1.0","800.0")
tkdelete(guidat$dattypetxt,"1.0","800.0")
tkdelete(guidat$modeltxt,"1.0","800.0")
tkinsert(guidat$datafiletxt,"end",basename(datob$fileName)); datob$nmiss <- 0
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol
if(!all(is.wholenumber(datob$dat))){
invlogit <- function(x){x <- 1 / (1 + exp(-x)); return(x)}
logit <- function(x){x <- log(x/(1-x)); return(x)}
tkinsert(guidat$modeltxt,"end","CRM")
datob$whmodel <- "CRM"
if(min(datob$dat) >= 0 && max(datob$dat) <= 1){
datob$datatype <- "Continuous"
message("\n ...Continuous data detected")
tkinsert(guidat$dattypetxt,"end","Continuous in [0,1]")
datob$dat[datob$dat<=0] <- .001; datob$dat[datob$dat>=1] <- .999
datob$dat <- logit(datob$dat)
if(datob$mval==TRUE){
datob$dat[datob$thena] <- NA
datob$thenalist <- which(is.na(datob$dat))
datob$dat[datob$thena] <- colMeans(datob$dat[,datob$thena[,2]],na.rm=TRUE)
}
}else{
datob$datatype <- "Continuous"
tkinsert(guidat$dattypetxt,"end","Continuous")
datob$dat <- invlogit(datob$dat)
datob$dat[datob$dat<=0] <- .001; datob$dat[datob$dat>=1] <- .999
datob$dat <- logit(datob$dat)
if(datob$mval==TRUE){
datob$dat[datob$thena] <- NA
datob$thenalist <- which(is.na(datob$dat))
datob$dat[datob$thena] <- colMeans(datob$dat[,datob$thena[,2]],na.rm=TRUE)
}
datob$datatype <- "Continuous"
message("\n ...Continuous data detected")
}
}else{if(min(datob$dat) >= 0 && max(datob$dat) <= 1){
tkinsert(guidat$modeltxt,"end","GCM")
datob$whmodel <- "GCM"
datob$datatype <- "Binary"
tkinsert(guidat$dattypetxt,"end","Binary")
message("\n ...Binary (dichotomous) data detected")
if(datob$mval==TRUE){
datob$dat[datob$thena] <- NA
datob$thenalist <- which(is.na(datob$dat))
for(i in unique(datob$thena[,2])){
datob$dat[,i][is.na(datob$dat[,i])] <- Mode(datob$dat[,i][which(!is.na(datob$dat[,i]))])
}
}
}else{
tkinsert(guidat$modeltxt,"end","LTRM")
datob$whmodel <- "LTRM"
datob$datatype <- "Ordinal"
tkinsert(guidat$dattypetxt,"end","Ordinal")
message("\n ...Ordinal (categorical) data detected")
if(guidat$polywind==FALSE){
tkgrid(guidat$poly.but,pady= 10, padx= 2)
guidat$polywind <- TRUE
}
if(datob$mval==TRUE){
datob$dat[datob$thena] <- NA
datob$thenalist <- which(is.na(datob$dat))
for(i in unique(datob$thena[,2])){
datob$dat[,i][is.na(datob$dat[,i])] <- Mode(datob$dat[,i][which(!is.na(datob$dat[,i]))])
}
}
}
}
tkinsert(guidat$resptxt,"end",dim(datob$dat)[1])
tkinsert(guidat$itemtxt,"end",dim(datob$dat)[2])
tkconfigure(guidat$datafiletxt, state="disabled")
tkconfigure(guidat$resptxt, state="disabled")
tkconfigure(guidat$itemtxt, state="disabled")
tkconfigure(guidat$dattypetxt, state="disabled")
tkconfigure(guidat$modeltxt, state="disabled")
datob$datind <- cbind(expand.grid(t(row(datob$dat))),expand.grid(t(col(datob$dat))),expand.grid(t(datob$dat)))
if(datob$mval==TRUE){
datob$nmiss <- dim(datob$thena)[1]
datob$datind <- datob$datind[-datob$thenalist,]
datob$datna <- datob$dat
datob$datna[datob$thena] <- NA
message("\n ...Data has ",datob$nmiss," missing values out of ",length(datob$dat))
}
if(datob$whmodel=="LTRM"){
tkconfigure(guidat$poly.but, state="normal")
}else{
if(guidat$polywind==TRUE){
tkconfigure(guidat$poly.but, state="disabled")
} }
tkconfigure(guidat$varname.entry, state="normal")
tkconfigure(guidat$plotresults.but, state="disabled")
tkconfigure(guidat$doppc.but, state="disabled")
tkconfigure(guidat$exportresults.but, state="disabled")
tkconfigure(guidat$printfit.but, state="disabled")
tkconfigure(guidat$summary.but, state="disabled")
tkconfigure(guidat$sendconsole.but, state="disabled")
tkconfigure(guidat$memb.but, state="disabled")
tkconfigure(guidat$mvest.but, state="disabled")
tkconfigure(guidat$traceplotdiscrete.but, state="disabled")
tkconfigure(guidat$traceplotall.but, state="disabled")
datob$nobs <- dim(datob$datind)[1]
datob$datobnames <- names(datob)
#list2env(datob,pkg_globals)
assign("datob", datob, pkg_globals)
guidat$n <- dim(datob$dat)[1]; guidat$m <- dim(datob$dat)[2]; guidat$mval <- datob$mval
assign("guidat", guidat, pkg_globals)
message("\n ...Data loaded")
}
if(gui==FALSE){
if(is.list(data)){
datob$dat <- matrix(as.numeric(unlist(data)),dim(data)[1],dim(data)[2])
}else{
datob$dat <- data
}
options(warn=-3)
if(!is.numeric(datob$dat[1,1])){datob$dat <- matrix(as.numeric(datob$dat),dim(datob$dat)[1],dim(datob$dat)[2])
if(all(is.na(datob$dat[,1]))){datob$dat <- datob$dat[,-1];
}
if(all(is.na(datob$dat[1,]))){datob$dat <- datob$dat[-1,];
}
}
datob$nmiss <- 0
if(sum(is.na(datob$dat))>0){
datob$thena <- which(is.na(datob$dat),arr.ind=TRUE)
datob$thenalist <- which(is.na(datob$dat))
datob$dat[datob$thena] <- unlist(datob$dat)[max(which(!is.na(datob$dat)),arr.ind=TRUE)]
datob$mval <- TRUE
}else{datob$mval <- FALSE}
options(warn=0)
if(all(datob$dat[1:dim(datob$dat)[1],1]==1:dim(datob$dat)[1])){datob$dat <- datob$dat[,-1]; if(datob$mval==TRUE){datob$thena[,2] <- datob$thena[,2] - 1}}
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol
if(!all(is.wholenumber(datob$dat))){
invlogit <- function(x){x <- 1 / (1 + exp(-x)); return(x)}
logit <- function(x){x <- log(x/(1-x)); return(x)}
datob$whmodel <- "CRM"
if(min(datob$dat) >= 0 && max(datob$dat) <= 1){
datob$datatype <- "Continuous"
message("\n ...Continuous data detected")
datob$dat[datob$dat<=0] <- .001; datob$dat[datob$dat>=1] <- .999
#datob$dat <- logit(datob$dat)
datob$dat <- logit(datob$dat)
if(datob$mval==TRUE){
datob$nmiss <- dim(datob$thena)[1]
datob$dat[datob$thena] <- NA
datob$thenalist <- which(is.na(datob$dat))
datob$dat[datob$thena] <- colMeans(datob$dat[,datob$thena[,2]],na.rm=TRUE)
}
}else{
datob$dat <- invlogit(datob$dat)
datob$dat[datob$dat<=0] <- .001; datob$dat[datob$dat>=1] <- .999
datob$dat <- logit(datob$dat)
if(datob$mval==TRUE){
datob$nmiss <- dim(datob$thena)[1]
datob$dat[datob$thena] <- NA
datob$thenalist <- which(is.na(datob$dat))
datob$dat[datob$thena] <- colMeans(datob$dat[,datob$thena[,2]],na.rm=TRUE)
}
message("\n ...Continuous data detected")}
}else{if(min(datob$dat) >= 0 && max(datob$dat) <= 1){
datob$whmodel <- "GCM"
datob$datatype <- "Binary"
message("\n ...Binary (dichotomous) data detected")
if(datob$mval==TRUE){
datob$nmiss <- dim(datob$thena)[1]
datob$dat[datob$thena] <- NA
datob$thenalist <- which(is.na(datob$dat))
for(i in unique(datob$thena[,2])){
datob$dat[,i][is.na(datob$dat[,i])] <- Mode(datob$dat[,i][which(!is.na(datob$dat[,i]))])
}
}
}else{
datob$whmodel <- "LTRM"
datob$datatype <- "Ordinal"
message("\n ...Ordinal (categorical) data detected")
if(datob$mval==TRUE){
datob$nmiss <- dim(datob$thena)[1]
datob$dat[datob$thena] <- NA
datob$thenalist <- which(is.na(datob$dat))
for(i in unique(datob$thena[,2])){
datob$dat[,i][is.na(datob$dat[,i])] <- Mode(datob$dat[,i][which(!is.na(datob$dat[,i]))])
}
}
}
}
message("\n ...",dim(datob$dat)[1]," respondents and ",dim(datob$dat)[2]," items")
datob$datind <- cbind(expand.grid(t(row(datob$dat))),expand.grid(t(col(datob$dat))),expand.grid(t(datob$dat)))
if(datob$mval==TRUE){message("\n ...Data has ",dim(datob$thena)[1]," missing values out of ",length(datob$dat))
datob$datind <- datob$datind[-datob$thenalist,]
datob$datna <- datob$dat
datob$datna[datob$thena] <- NA
}
datob$nobs <- dim(datob$datind)[1]
return(datob)
}
}
######################
#Function for the 'Scree Plot' Button
#- Uses the data object from loaddatafunc
#- Performs factor analysis on the Pearson correlations of the data
# using the fa() function from psych package
#- If polychoric correlations are picked for the LTRM, uses fa() on the polychoric
# correlations instead using polychoric() from the polycor package
#- Creates a plot of 8 eigenvalues with appropriate titles and labels
#- When exporting the results, this function is run and produces .eps and .jpeg's of the plot
######################
screeplotfuncbutton <- function() {
datob <- get("datob", pkg_globals)
guidat <- get("guidat", pkg_globals)
screeplotfunc(datob=datob,saveplots=0,savedir="",polych=as.logical(as.numeric(tclvalue(guidat$polyvar))))
}
screeplotfunc <- function(datob,saveplots=0,savedir="",gui=FALSE,polych=FALSE,noplot=FALSE) {
options(warn=-3)
if(datob$whmodel!="LTRM"){
if(saveplots==0 && noplot==FALSE){
tmp <- ""
if(datob$mval==TRUE && datob$whmodel=="GCM"){tmp <- ", missing data handled by mode of respective columns"}
if(datob$mval==TRUE && datob$whmodel=="CRM"){tmp <- ", missing data handled by mean of respective columns"}
message("\n ...Producing Scree Plot",tmp)
}
if(saveplots==1){jpeg(file.path(gsub(".Rdata","scree.jpg",savedir)),width = 6, height = 6, units = "in", pointsize = 12,quality=100,res=400)}
if(saveplots==2){postscript(file=file.path(gsub(".Rdata","scree.eps",savedir)), onefile=FALSE, horizontal=FALSE, width = 6, height = 6, paper="special", family="Times")}
if(noplot==FALSE){
if(sum(apply(datob$dat,1,function(x) sd(x,na.rm=TRUE))==0) > 0){
tmp <- datob$dat
if(sum(apply(datob$dat,1,function(x) sd(x,na.rm=TRUE))==0)==1){
tmp[which(apply(tmp,1,function(x) sd(x,na.rm=TRUE))==0),1] <- min(tmp[which(apply(tmp,1,function(x) sd(x,na.rm=TRUE))==0),1]+.01,.99)
}else{
tmp[which(apply(tmp,1,function(x) sd(x,na.rm=TRUE))==0),1] <- sapply(apply(tmp[which(apply(tmp,1,function(x) sd(x,na.rm=TRUE))==0),],1,mean),function(x) min(x+.01,.99))
}
par(oma=c(0,0,0,0),mar=c(4,4,3,1),mgp=c(2.25,.75,0),mfrow=c(1,1))
datob$factors <- suppressMessages(fa(cor(t(datob$dat)))$values[1:8])
suppressMessages(plot(datob$factors,las=1,type="b",bg="black",pch=21,xlab="Factor",ylab="Magnitude",main="Scree Plot of Data"))
}else{
par(oma=c(0,0,0,0),mar=c(4,4,3,1),mgp=c(2.25,.75,0),mfrow=c(1,1))
datob$factors <- suppressMessages(fa(cor(t(datob$dat)))$values[1:8])
suppressMessages(plot(datob$factors,las=1,type="b",bg="black",pch=21,xlab="Factor",ylab="Magnitude",main="Scree Plot of Data"))
}
}
if(saveplots==1 || saveplots ==2){dev.off()}
}else{
if(saveplots==0 && noplot==FALSE){
tmp <- ""
if(datob$mval==TRUE && datob$whmodel=="LTRM"){tmp <- ", missing data handled by mode of respective columns"}
message("\n ...Producing Scree Plot",tmp)
}
if(saveplots==1){jpeg(file.path(gsub(".Rdata","scree.jpg",savedir)),width = 6, height = 6, units = "in", pointsize = 12,quality=100,res=400)}
if(saveplots==2){postscript(file=file.path(gsub(".Rdata","scree.eps",savedir)), onefile=FALSE, horizontal=FALSE, width = 6, height = 6, paper="special", family="Times")}
if(polych==TRUE){
if(length(datob$datfactorsp)==1){
message(" note: utilizing polychoric correlations (time intensive)")
datob$factors <- datob$datfactorsp <- suppressMessages(fa(polychoric(t(datob$dat),global=FALSE)$rho)$values[1:8])
}
datob$datfactors <- datob$datfactorsp
}else{
if(length(datob$datfactorsp)==1){
datob$factors <- datob$datfactorsc <- suppressMessages(fa(cor(t(datob$dat)))$values[1:8])
}
datob$datfactors <- datob$datfactorsc
}
if(noplot==FALSE){
par(oma=c(0,0,0,0),mar=c(4,4,3,1),mgp=c(2.25,.75,0),mfrow=c(1,1))
plot(datob$datfactors,las=1,type="b",bg="black",pch=21,xlab="Factor",ylab="Magnitude",main="Scree Plot of Data")
}
if(gui==TRUE){
datob$datobnames <- names(datob)
#list2env(datob,pkg_globals)
assign("datob", datob, pkg_globals)
}
if(saveplots==1 || saveplots ==2){dev.off()}
}
if(gui==FALSE){return(datob)}
options(warn=0)
}
######################
#Functions for the Increasing/Decreasing Cultures Buttons
######################
#For testing
#itemdifffuncbutton <- function(){print(tclvalue(get("guidat", pkg_globals)$itemdiffvar)) }
cultdownfuncbutton <- function(){guidat <- get("guidat", pkg_globals); guidat$culturesvar <- tclVar(as.character(max(1,as.numeric(tclvalue(guidat$culturesvar))-1))); tkconfigure(guidat$cultures.entry, textvariable=guidat$culturesvar); assign("guidat", guidat, pkg_globals)}
cultupfuncbutton <- function(){guidat <- get("guidat", pkg_globals); guidat$culturesvar <- tclVar(as.character(min(floor(guidat$n/4),as.numeric(tclvalue(guidat$culturesvar))+1))); tkconfigure(guidat$cultures.entry, textvariable=guidat$culturesvar); assign("guidat", guidat, pkg_globals)}
#cultdownfuncbutton <- function(){guidat <- get("guidat", pkg_globals); guidat$culturesvar <- tclVar(as.character(max(1,as.numeric(tclvalue(guidat$culturesvar))-1))); tkconfigure(guidat$cultures.entry, textvariable=guidat$culturesvar); assign("guidat", guidat, pkg_globals)}
#cultupfuncbutton <- function(){guidat <- get("guidat", pkg_globals); guidat$culturesvar <- tclVar(as.character(min(floor(dim(datob$dat)[1]/4),as.numeric(tclvalue(guidat$culturesvar))+1))); tkconfigure(guidat$cultures.entry, textvariable=guidat$culturesvar); assign("guidat", guidat, pkg_globals)}
######################
#Functions for Inputting Object Name Entry Field
######################
valid_inputkey <- function() {
guidat <- get("guidat", pkg_globals);
val <- gsub(" ","",tclvalue(guidat$varnametry))
nchars <- nchar(make.names(val))
if(val != ""){
if(nchars > 10){
guidat$varnametry <- tclVar(as.character(substr(make.names(val),start=1,stop=10)))
tkconfigure(guidat$varname.entry, textvariable=guidat$varnametry)
}else{
guidat$varnametry <- tclVar(as.character(make.names(val)))
tkconfigure(guidat$varname.entry, textvariable=guidat$varnametry)
}}
assign("guidat", guidat, pkg_globals)
}
valid_inputfo <- function() {
guidat <- get("guidat", pkg_globals);
val <- gsub(" ","",tclvalue(guidat$varnametry))
nchars <- nchar(make.names(val))
if(val == ""){
guidat$varnametry <- tclVar("cctfit")
tkconfigure(guidat$varname.entry, textvariable=guidat$varnametry)
assign("guidat", guidat, pkg_globals)
return()
}
if(nchars>10){
guidat$varnametry <- tclVar(as.character(substr(make.names(val),start=1,stop=10)))
tkconfigure(guidat$varname.entry, textvariable=guidat$varnametry)
}else{
guidat$varnametry <- tclVar(as.character(make.names(val)))
tkconfigure(guidat$varname.entry, textvariable=guidat$varnametry)
}
assign("guidat", guidat, pkg_globals)
}
######################
#Function for the 'Apply CCT Model' Button
#- Uses the data object from loaddatafunc
#- Applies hierarchical Bayesian inference for the model using JAGS by packages rjags and R2jags
#- Model code for each of the three models are at the bottom of this rcode file
#- Reads in user preferences for model specifications from the GUI
#- Uses these specifications to apply different form(s) of the model
#- During mixture model cases, applies an algorithm that corrects for label-switching/mixing issues
#- Recalculates the statistics for all parameters after correcting for label-switching, as well as
# the Rhat statistics, and DIC
#- Enables the user to look at traceplots for discrete nodes via dtraceplots()
#- Provides the model-based clustering by cctfit$respmem (respondent membership)
#- Provides cctfit$Lik, which is the likelihood of the model evaluated at each sample
#- Enables GUI buttons: 'Run Checks', 'Plot Results', 'Export Results'
######################
applymodelfuncbutton <- function() {
guidat <- get("guidat", pkg_globals)
datob <- get("datob", pkg_globals)
guidat$varname <- tclvalue(guidat$varnametry)
tkconfigure(guidat$varname.entry, state="disabled")
assign("guidat", guidat, pkg_globals)
assign(guidat$varname,
applymodelfunc(datob=datob,clusters=as.numeric(tclvalue(guidat$culturesvar)),itemdiff=as.logical(as.numeric(tclvalue(guidat$itemdiffvar))),
jags.iter=as.numeric(tclvalue(guidat$samplesvar)),jags.chains= as.numeric(tclvalue(guidat$chainsvar)),jags.burnin=as.numeric(tclvalue(guidat$burninvar)),
jags.thin=as.numeric(tclvalue(guidat$thinvar)),parallel= as.logical(as.numeric(tclvalue(guidat$paravar))),gui=TRUE),
pkg_globals
)
#User-friendly (for novices) but not CRAN compliant because it assigns the fit object in the Global environment
#assign(guidat$varname,
#applymodelfunc(datob=datob,clusters=as.numeric(tclvalue(guidat$culturesvar)),itemdiff=as.logical(as.numeric(tclvalue(guidat$itemdiffvar))),
# jags.iter=as.numeric(tclvalue(guidat$samplesvar)),jags.chains= as.numeric(tclvalue(guidat$chainsvar)),jags.burnin=as.numeric(tclvalue(guidat$burninvar)),
# jags.thin=as.numeric(tclvalue(guidat$thinvar)),parallel= as.logical(as.numeric(tclvalue(guidat$paravar))),gui=TRUE),
#inherits=TRUE
#)
}
applymodelfunc <- function(datob,clusters=1,itemdiff=FALSE,biases=TRUE,jags.iter=10000,jags.chains=3,jags.burnin=2000,jags.thin=1,parallel=FALSE,gui=FALSE) {
if(gui==TRUE){guidat <- get("guidat", pkg_globals)}
######################
#Model Codes
#- Used by the 'Apply CCT Model' button/function
#- Each model has 2 code versions, 1 without item difficulty, 1 with item difficulty
######################
mcgcm <-
"model{
for (l in 1:nobs){
D[Y[l,1],Y[l,2]] <- (th[Y[l,1]]*(1-lam[Y[l,2]])) / ((th[Y[l,1]]*(1-lam[Y[l,2]]))+(lam[Y[l,2]]*(1-th[Y[l,1]])))
pY[Y[l,1],Y[l,2]] <- (D[Y[l,1],Y[l,2]]*Z[Y[l,2],Om[Y[l,1]]]) +((1-D[Y[l,1],Y[l,2]])*g[Y[l,1]])
Y[l,3] ~ dbern(pY[Y[l,1],Y[l,2]]) }
for (i in 1:nresp){
Om[i] ~ dcat(pi)
th[i] ~ dbeta(thmu[Om[i]]*thtau[Om[i]],(1-thmu[Om[i]])*thtau[Om[i]])
g[i] ~ dbeta(gmu[Om[i]]*gtau[Om[i]],(1-gmu[Om[i]])*gtau[Om[i]]) }
for (k in 1:nitem){
lam[k] <- .5
for (v in 1:V){
Z[k,v] ~ dbern(p[v]) }}
#Hyper Parameters
gsmu <- 10
gssig <- 10
dsmu <- 10
dssig <- 10
pi[1:V] ~ ddirch(L)
alpha <- 2
for (v in 1:V){
p[v] ~ dunif(0,1)
gmu[v] <- .5
gtau[v] ~ dgamma(pow(gsmu,2)/pow(gssig,2),gsmu/pow(gssig,2))
thmu[v] ~ dbeta(alpha,alpha)
thtau[v] ~ dgamma(pow(dsmu,2)/pow(dssig,2),dsmu/pow(dssig,2))
L[v] <- 1 }
}"
mcgcmid <-
"model{
for (l in 1:nobs){
D[Y[l,1],Y[l,2]] <- (th[Y[l,1]]*(1-lam[Y[l,2],Om[Y[l,1]]])) / ((th[Y[l,1]]*(1-lam[Y[l,2],Om[Y[l,1]]]))+(lam[Y[l,2],Om[Y[l,1]]]*(1-th[Y[l,1]])))
pY[Y[l,1],Y[l,2]] <- (D[Y[l,1],Y[l,2]]*Z[Y[l,2],Om[Y[l,1]]]) +((1-D[Y[l,1],Y[l,2]])*g[Y[l,1]])
Y[l,3] ~ dbern(pY[Y[l,1],Y[l,2]]) }
for (i in 1:nresp){
Om[i] ~ dcat(pi)
th[i] ~ dbeta(thmu[Om[i]]*thtau[Om[i]],(1-thmu[Om[i]])*thtau[Om[i]])
g[i] ~ dbeta(gmu[Om[i]]*gtau[Om[i]],(1-gmu[Om[i]])*gtau[Om[i]]) }
for (k in 1:nitem){
for (v in 1:V){
Z[k,v] ~ dbern(p[v])
lam[k,v] ~ dbeta(lammu[v]*lamtau[v],(1-lammu[v])*lamtau[v])
}}
#Hyper Parameters
lamsmu <- 10
lamssig <- 10
gsmu <- 10
gssig <- 10
dsmu <- 10
dssig <- 10
alpha <- 2
pi[1:V] ~ ddirch(L)
for (v in 1:V){
p[v] ~ dunif(0,1)
lammu[v] <- .5
lamtau[v] ~ dgamma(pow(lamsmu,2)/pow(lamssig,2),lamsmu/pow(lamssig,2))
gmu[v] <- .5
gtau[v] ~ dgamma(pow(gsmu,2)/pow(gssig,2),gsmu/pow(gssig,2))
thmu[v] ~ dbeta(alpha,alpha)
thtau[v] ~ dgamma(pow(dsmu,2)/pow(dssig,2),dsmu/pow(dssig,2))
L[v] <- 1
}
}"
mcgcmidsingle <-
"model{
for (l in 1:nobs){
D[Y[l,1],Y[l,2]] <- (th[Y[l,1]]*(1-lam[Y[l,2],Om[Y[l,1]]])) / ((th[Y[l,1]]*(1-lam[Y[l,2],Om[Y[l,1]]]))+(lam[Y[l,2],Om[Y[l,1]]]*(1-th[Y[l,1]])))
pY[Y[l,1],Y[l,2]] <- (D[Y[l,1],Y[l,2]]*Z[Y[l,2],Om[Y[l,1]]]) +((1-D[Y[l,1],Y[l,2]])*g[Y[l,1]])
Y[l,3] ~ dbern(pY[Y[l,1],Y[l,2]]) }
for (i in 1:nresp){
Om[i] ~ dcat(pi)
th[i] ~ dbeta(thmu[Om[i]]*thtau[Om[i]],(1-thmu[Om[i]])*thtau[Om[i]])
g[i] ~ dbeta(gmu[Om[i]]*gtau[Om[i]],(1-gmu[Om[i]])*gtau[Om[i]]) }
for (k in 1:nitem){
lam[k] ~ dbeta(lammu*lamtau,(1-lammu)*lamtau)
for (v in 1:V){
Z[k,v] ~ dbern(p[v])
}}
#Hyper Parameters
lamsmu <- 10
lamssig <- 10
gsmu <- 10
gssig <- 10
dsmu <- 10
dssig <- 10
alpha <- 2
pi[1:V] ~ ddirch(L)
lammu <- .5
lamtau ~ dgamma(pow(lamsmu,2)/pow(lamssig,2),lamsmu/pow(lamssig,2))
for (v in 1:V){
p[v] ~ dunif(0,1)
gmu[v] <- .5
gtau[v] ~ dgamma(pow(gsmu,2)/pow(gssig,2),gsmu/pow(gssig,2))
thmu[v] ~ dbeta(alpha,alpha)
thtau[v] ~ dgamma(pow(dsmu,2)/pow(dssig,2),dsmu/pow(dssig,2))
L[v] <- 1
}
}"
mcltrm <-
"model{
for (l in 1:nobs){
tau[Y[l,1],Y[l,2]] <- pow(E[Y[l,1]],-2)
pY[Y[l,1],Y[l,2],1] <- pnorm((a[Y[l,1]]*gam[1,Om[Y[l,1]]]) + b[Y[l,1]],T[Y[l,2],Om[Y[l,1]]],tau[Y[l,1],Y[l,2]])
for (c in 2:(C-1)){pY[Y[l,1],Y[l,2],c] <- pnorm((a[Y[l,1]]*gam[c,Om[Y[l,1]]]) + b[Y[l,1]],T[Y[l,2],Om[Y[l,1]]],tau[Y[l,1],Y[l,2]]) - sum(pY[Y[l,1],Y[l,2],1:(c-1)])}
pY[Y[l,1],Y[l,2],C] <- (1 - sum(pY[Y[l,1],Y[l,2],1:(C-1)]))
Y[l,3] ~ dcat(pY[Y[l,1],Y[l,2],1:C])
}
#Parameters
for (i in 1:nresp){
Om[i] ~ dcat(pi)
Elog[i] ~ dnorm(Emu[Om[i]],Etau[Om[i]])
E[i] <- exp(Elog[i])
alog[i] ~ dnorm(amu[Om[i]],atau[Om[i]])T(-2.3,2.3)
a[i] <- exp(alog[i])
b[i] ~ dnorm(bmu[Om[i]],btau[Om[i]]) }
for (k in 1:nitem){
for (v in 1:V){
T[k,v] ~ dnorm(Tmu[v],Ttau[v]) }}
for (v in 1:V){
gam[1:(C-1),v] <- sort(tgam2[1:(C-1),v])
for (c in 1:(C-2)){tgam[c,v] ~ dnorm(0,.1)}
tgam2[1:(C-2),v] <- tgam[1:(C-2),v]
tgam2[C-1,v] <- -sum(tgam[1:(C-2),v]) }
pi[1:V] ~ ddirch(L)
#Hyperparameters
for (v in 1:V){
L[v] <- 1
Tmu[v] ~ dnorm(0,.25)
Tsig[v] ~ dunif(.25,3)
Ttau[v] <- pow(Tsig[v],-2)
Emu[v] ~ dnorm(0,.01)
Etau[v] ~ dgamma(.01, .01)
amu[v] <- 0
atau[v] ~ dgamma(.01, .01)T(.01,)
bmu[v] <- 0
btau[v] ~ dgamma(.01, .01)
}
}"
mcltrmid <-
"model{
for (l in 1:nobs){
tau[Y[l,1],Y[l,2]] <- pow(E[Y[l,1]]*exp(lam[Y[l,2],Om[Y[l,1]]]),-2)
pY[Y[l,1],Y[l,2],1] <- pnorm((a[Y[l,1]]*gam[1,Om[Y[l,1]]]) + b[Y[l,1]],T[Y[l,2],Om[Y[l,1]]],tau[Y[l,1],Y[l,2]])
for (c in 2:(C-1)){pY[Y[l,1],Y[l,2],c] <- pnorm((a[Y[l,1]]*gam[c,Om[Y[l,1]]]) + b[Y[l,1]],T[Y[l,2],Om[Y[l,1]]],tau[Y[l,1],Y[l,2]]) - sum(pY[Y[l,1],Y[l,2],1:(c-1)])}
pY[Y[l,1],Y[l,2],C] <- (1 - sum(pY[Y[l,1],Y[l,2],1:(C-1)]))
Y[l,3] ~ dcat(pY[Y[l,1],Y[l,2],1:C])
}
#Parameters
for (i in 1:nresp){
Om[i] ~ dcat(pi)
Elog[i] ~ dnorm(Emu[Om[i]],Etau[Om[i]])
E[i] <- exp(Elog[i])
alog[i] ~ dnorm(amu[Om[i]],atau[Om[i]])T(-2.3,2.3)
a[i] <- exp(alog[i])
b[i] ~ dnorm(bmu[Om[i]],btau[Om[i]])
}
for (k in 1:nitem){
for (v in 1:V){
T[k,v] ~ dnorm(Tmu[v],Ttau[v])
lam[k,v] ~ dnorm(lammu[v],lamtau[v])T(-2.3,2.3)
} }
for (v in 1:V){
gam[1:(C-1),v] <- sort(tgam2[1:(C-1),v])
for (c in 1:(C-2)){tgam[c,v] ~ dnorm(0,.1)}
tgam2[1:(C-2),v] <- tgam[1:(C-2),v]
tgam2[C-1,v] <- -sum(tgam[1:(C-2),v])
}
pi[1:V] ~ ddirch(L)
#Hyperparameters
for (v in 1:V){
L[v] <- 1
Tmu[v] ~ dnorm(0,.25)
Tsig[v] ~ dunif(.25,3)
Ttau[v] <- pow(Tsig[v],-2)
Emu[v] ~ dnorm(0,.01)
Etau[v] ~ dgamma(.01, .01)
amu[v] <- 0
atau[v] ~ dgamma(.01, .01)T(.01,)
bmu[v] <- 0
btau[v] ~ dgamma(.01, .01)
lammu[v] <- 0
lamsig[v] ~ dunif(.25, 2)
lamtau[v] <- pow(lamsig[v],-2)
}
}"
mccrm <-
"model{
for (l in 1:nobs){
Y[l,3] ~ dnorm((a[Y[l,1]]*T[Y[l,2],Om[Y[l,1]]])+b[Y[l,1]],pow(a[Y[l,1]]*E[Y[l,1]],-2))
}
#Parameters
for (i in 1:nresp){
Om[i] ~ dcat(pi)
Elog[i] ~ dnorm(Emu[Om[i]],Etau[Om[i]])
E[i] <- exp(Elog[i])
alog[i] ~ dnorm(amu[Om[i]],atau[Om[i]])T(-2.3,2.3)
a[i] <- exp(alog[i])
b[i] ~ dnorm(bmu[Om[i]],btau[Om[i]]) }
for (k in 1:nitem){
for (v in 1:V){
T[k,v] ~ dnorm(Tmu[v],Ttau[v])
}}
pi[1:V] ~ ddirch(L)
#Hyperparameters
for (v in 1:V){
L[v] <- 1
Tmu[v] ~ dnorm(0,0.25)
Tsig[v] ~ dunif(.25,3)
Ttau[v] <- pow(Tsig[v],-2)
Emu[v] ~ dnorm(0,.01)
Etau[v] ~ dgamma(.01, .01)
amu[v] <- 0
atau[v] ~ dgamma(.01, .01)T(.01,)
bmu[v] <- 0
btau[v] ~ dgamma(.01, .01)
}
}"
mccrmid <-
"model{
for (l in 1:nobs){
Y[l,3] ~ dnorm((a[Y[l,1]]*T[Y[l,2],Om[Y[l,1]]])+b[Y[l,1]],pow(a[Y[l,1]]*E[Y[l,1]]*exp(lam[Y[l,2],Om[Y[l,1]]]),-2))
}
#Parameters
for (i in 1:nresp){
Om[i] ~ dcat(pi)
Elog[i] ~ dnorm(Emu[Om[i]],Etau[Om[i]])
E[i] <- exp(Elog[i])
alog[i] ~ dnorm(amu[Om[i]],atau[Om[i]])T(-2.3,2.3)
a[i] <- exp(alog[i])
b[i] ~ dnorm(bmu[Om[i]],btau[Om[i]]) }
for (k in 1:nitem){
for (v in 1:V){
T[k,v] ~ dnorm(Tmu[v],Ttau[v])
lam[k,v] ~ dnorm(lammu[v],lamtau[v])T(-2.3,2.3)
}}
pi[1:V] ~ ddirch(L)
#Hyperparameters
for (v in 1:V){
L[v] <- 1
Tmu[v] ~ dnorm(0,.25)
Tsig[v] ~ dunif(.25,3)
Ttau[v] <- pow(Tsig[v],-2)
Emu[v] ~ dnorm(0,.01)
Etau[v] ~ dgamma(.01, .01)
amu[v] <- 0
atau[v] ~ dgamma(.01, .01)T(.01,)
bmu[v] <- 0
btau[v] ~ dgamma(.01, .01)
lammu[v] <- 0
lamsig[v] ~ dunif(.25, 2)
lamtau[v] <- pow(lamsig[v],-2)
}
}"
## Diffuse Settings
# L[v] <- 1
# Tmu[v] ~ dnorm(0,.25)
# Ttau[v] ~ dgamma(.01, .01)
# Emu[v] ~ dnorm(0,.01)
# Etau[v] ~ dgamma(.01, .01)
# amu[v] <- 0
# atau[v] ~ dgamma(.01, .01)T(.01,)
# bmu[v] <- 0
# btau[v] ~ dgamma(.01, .01)
# lammu[v] <- 0
# lamtau[v] ~ dgamma(.01, .01)T(.01,)
######################
#Sets up Parameters, Variables, and Data for JAGS for the model selected
######################
if(datob$whmodel=="GCM"){
Y <- datob$datind; nresp <- dim(datob$dat)[1]; nitem <- dim(datob$dat)[2]; V <- clusters; nobs <- dim(datob$datind)[1]
jags.data <- list("Y","nresp","nitem","V","nobs")
if(itemdiff==FALSE){
model.file <- mcgcm
jags.params <- c("Z","th","g","p","thmu","thtau","gmu","gtau","Om","pi")
if(clusters>1){
if(biases==TRUE){
jags.inits <- function(){ list("Z"=matrix(rbinom(nitem*V,1,.5),nitem,V),"th"= runif(nresp,.2,.8), "g"= runif(nresp,.2,.8),"Om"= sample(1:V,nresp,replace=TRUE) )}
}else{
jags.inits <- function(){ list("Z"=matrix(rbinom(nitem*V,1,.5),nitem,V),"th"= runif(nresp,.2,.8), "Om"= sample(1:V,nresp,replace=TRUE) )}
}
}else{
if(biases==TRUE){
jags.inits <- function(){ list("Z"=matrix(rbinom(nitem*V,1,.5),nitem,V),"th"= runif(nresp,.2,.8), "g"= runif(nresp,.2,.8) )}
}else{
jags.inits <- function(){ list("Z"=matrix(rbinom(nitem*V,1,.5),nitem,V),"th"= runif(nresp,.2,.8) )}
}
}
}
if(itemdiff==TRUE){
model.file <- mcgcmid
jags.params <- c("Z","th","g","lam","p","thmu","thtau","gmu","gtau","lammu","lamtau","Om","pi")
if(clusters>1){
if(biases==TRUE){
jags.inits <- function(){ list("Z"=matrix(rbinom(nitem*V,1,.5),nitem,V),"th"= runif(nresp,.2,.8), "g"= runif(nresp,.2,.8), "lam"= matrix(runif(nitem*V,.2,.8),nitem,V), "Om"= sample(1:V,nresp,replace=TRUE) )}
}else{
jags.inits <- function(){ list("Z"=matrix(rbinom(nitem*V,1,.5),nitem,V),"th"= runif(nresp,.2,.8), "lam"= matrix(runif(nitem*V,.2,.8),nitem,V), "Om"= sample(1:V,nresp,replace=TRUE) )}
}
}else{
if(biases==TRUE){
jags.inits <- function(){ list("Z"=matrix(rbinom(nitem*V,1,.5),nitem,V),"th"= runif(nresp,.2,.8), "g"= runif(nresp,.2,.8), "lam"= matrix(runif(nitem*V,.2,.8),nitem,V) )}
}else{
jags.inits <- function(){ list("Z"=matrix(rbinom(nitem*V,1,.5),nitem,V),"th"= runif(nresp,.2,.8), "lam"= matrix(runif(nitem*V,.2,.8),nitem,V) )}
}
}
}
if(clusters==1){
model.file <- gsub(pattern="pi\\[1\\:V\\] ~ ddirch\\(L\\)", "pi <- 1", model.file)
model.file <- gsub(pattern="Om\\[i\\] ~ dcat\\(pi\\)", "Om\\[i\\] <- 1", model.file)
}
if(biases==FALSE){
model.file <- gsub(pattern="g\\[i\\] ~ dbeta\\(gmu\\[Om\\[i\\]\\]\\*gtau\\[Om\\[i\\]\\],\\(1-gmu\\[Om\\[i\\]\\]\\)\\*gtau\\[Om\\[i\\]\\]\\)", "g\\[i\\] <- .5", model.file)
model.file <- gsub(pattern="gtau\\[v\\] ~ dgamma\\(pow\\(gsmu,2\\)/pow\\(gssig,2\\),gsmu/pow\\(gssig,2\\)\\)", "gtau\\[v\\] <- 0", model.file)
}
}
if(datob$whmodel=="LTRM"){
Y <- datob$datind; nresp <- dim(datob$dat)[1]; nitem <- dim(datob$dat)[2]; V <- clusters; C <- max(datob$datind[,3]); nobs <- dim(datob$datind)[1]
jags.data <- list("Y","nresp","nitem","C","V","nobs")
if(itemdiff==FALSE){
model.file <- mcltrm
jags.params <- c("T","gam","E","a","b","Tmu","Ttau","Emu","Etau","amu","atau","bmu","btau","Om","pi")
if(clusters>1){
jags.inits <- function(){ list("tgam"=matrix(rnorm((C-2)*V,0,1),(C-2),V),"T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6), "asig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6),"Om"= sample(1:V,nresp,replace=TRUE) )}
}else{
jags.inits <- function(){ list("tgam"=matrix(rnorm((C-2)*V,0,1),(C-2),V),"T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6), "asig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6) )}
}
if(C==2){
if(clusters>1){
jags.inits <- function(){ list("T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6),"Om"= sample(1:V,nresp,replace=TRUE) )}
}else{
jags.inits <- function(){ list("T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6) )}
}
model.file <- gsub(pattern="a\\[i\\] <- exp\\(alog\\[i\\]\\)", "a\\[i\\] <- 1", model.file)
model.file <- gsub(pattern="alog\\[i\\] ~ dnorm\\(amu\\[Om\\[i\\]\\],atau\\[Om\\[i\\]\\]\\)T\\(-2.3,2.3\\)", "", model.file)
model.file <- gsub(pattern="atau\\[v\\] ~ dgamma\\(.01,.01\\)T\\(.01,\\)", "atau\\[v\\] <- 0", model.file)
model.file <- gsub(pattern="for \\(c in 2\\:\\(C-1\\)\\)", " #for \\(c in 2\\:\\(C-1\\)\\)", model.file)
model.file <- gsub(pattern="gam\\[1\\:\\(C-1\\),v\\] <- sort\\(tgam2\\[1\\:\\(C-1\\),v\\]\\)", "gam\\[1,v\\] <- 0 }", model.file)
model.file <- gsub(pattern="for \\(c in 1\\:\\(C-2\\)\\)", "#for \\(c in 1\\:\\(C-2\\)\\)", model.file)
model.file <- gsub(pattern="\\(1 - sum\\(pY\\[i,k,1\\:\\(C-1\\)\\]\\)\\)", "1 - pY\\[i,k,1\\]", model.file)
model.file <- gsub(pattern="tgam2\\[1", "#tgam2\\[1", model.file)
model.file <- gsub(pattern="tgam2\\[C", "#tgam2\\[C", model.file)
}
}
if(itemdiff==TRUE){
model.file <- mcltrmid
jags.params <- c("T","lam","gam","E","a","b","Tmu","Ttau","Emu","Etau","amu","atau","bmu","btau","lammu","lamtau","Om","pi")
if(clusters>1){
jags.inits <- function(){ list("tgam"=matrix(rnorm((C-2)*V,0,1),(C-2),V),"T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6), "asig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6),"lamsig"= runif(V,.25,.30), "Om"= sample(1:V,nresp,replace=TRUE) )}
}else{
jags.inits <- function(){ list("tgam"=matrix(rnorm((C-2)*V,0,1),(C-2),V),"T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6), "asig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6),"lamsig"= runif(V,.25,.30) )}
}
if(C==2){
if(clusters>1){
jags.inits <- function(){ list("T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6),"lamsig"= runif(V,.25,.30), "Om"= sample(1:V,nresp,replace=TRUE) )}
}else{
jags.inits <- function(){ list("T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6),"lamsig"= runif(V,.25,.30) )}
}
model.file <- gsub(pattern="a\\[i\\] <- exp\\(alog\\[i\\]\\)", "a\\[i\\] <- 1", model.file)
model.file <- gsub(pattern="alog\\[i\\] ~ dnorm\\(amu\\[Om\\[i\\]\\],atau\\[Om\\[i\\]\\]\\)T\\(-2.3,2.3\\)", "", model.file)
model.file <- gsub(pattern="atau\\[v\\] ~ dgamma\\(.01, .01\\)T\\(.01,\\)", "atau\\[v\\] <- 0", model.file)
model.file <- gsub(pattern="for \\(c in 2\\:\\(C-1\\)\\)", " #for \\(c in 2\\:\\(C-1\\)\\)", model.file)
model.file <- gsub(pattern="gam\\[1\\:\\(C-1\\),v\\] <- sort\\(tgam2\\[1\\:\\(C-1\\),v\\]\\)", "gam\\[1,v\\] <- 0 }", model.file)
model.file <- gsub(pattern="for \\(c in 1\\:\\(C-2\\)\\)", "#for \\(c in 1\\:\\(C-2\\)\\)", model.file)
model.file <- gsub(pattern="\\(1 - sum\\(pY\\[i,k,1\\:\\(C-1\\)\\]\\)\\)", "1 - pY\\[i,k,1\\]", model.file)
model.file <- gsub(pattern="tgam2\\[1", "#tgam2\\[1", model.file)
model.file <- gsub(pattern="tgam2\\[C", "#tgam2\\[C", model.file)
}
}
if(clusters==1){
model.file <- gsub(pattern="pi\\[1\\:V\\] ~ ddirch\\(L\\)", "pi <- 1", model.file)
model.file <- gsub(pattern="Om\\[i\\] ~ dcat\\(pi\\)", "Om\\[i\\] <- 1", model.file)
}
if(biases==FALSE){
model.file <- gsub(pattern="a\\[i\\] <- exp\\(alog\\[i\\]\\)", "a\\[i\\] <- 1", model.file)
model.file <- gsub(pattern="alog\\[i\\] ~ dnorm\\(amu\\[Om\\[i\\]\\],atau\\[Om\\[i\\]\\]\\)T\\(-2.3,2.3\\)", "alog\\[i\\] <- 0", model.file)
model.file <- gsub(pattern="atau\\[v\\] ~ dgamma\\(.01, .01\\)T\\(.01,\\)", "atau\\[v\\] <- 0", model.file)
model.file <- gsub(pattern="b\\[i\\] ~ dnorm\\(bmu\\[Om\\[i\\]\\],btau\\[Om\\[i\\]\\]) ", "b\\[i\\] <- 0", model.file)
model.file <- gsub(pattern="btau\\[v\\] ~ dgamma\\(.01, .01\\)", "btau\\[v\\] <- 0", model.file)
}
}
if(datob$whmodel=="CRM"){
Y <- datob$datind; nresp <- dim(datob$dat)[1]; nitem <- dim(datob$dat)[2]; V <- clusters; nobs <- dim(datob$datind)[1]
jags.data <- list("Y","nresp","nitem","V","nobs")
if(itemdiff==FALSE){
model.file <- mccrm
jags.params <- c("T","E","a","alog","b","Tmu","Ttau","Emu","Etau","amu","atau","bmu","btau","Om","pi")
if(clusters>1){
jags.inits <- function(){ list("T"=matrix(rnorm(nitem*V,0,.5),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.5,.8), "asig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6), "Om"= sample(1:V,nresp,replace=TRUE) )}
}else{
jags.inits <- function(){ list("T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.5,.8), "asig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6) )}
}
}
if(itemdiff==TRUE){
model.file <- mccrmid
jags.params <- c("T","E","a","alog","b","lam","Tmu","Ttau","Emu","Etau","amu","atau","bmu","btau","lammu","lamtau","Om","pi")
if(clusters>1){
jags.inits <- function(){ list("T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6), "asig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6),"lamsig"= runif(V,.25,.30), "Om"= sample(1:V,nresp,replace=TRUE) )}
}else{
jags.inits <- function(){ list("T"=matrix(rnorm(nitem*V,0,1),nitem,V),"Emu"= runif(V,.8,2),"Esig"= runif(V,.4,.6), "asig"= runif(V,.4,.6),"bsig"= runif(V,.4,.6),"lamsig"= runif(V,.25,.30) )}
}
}
if(clusters==1){
model.file <- gsub(pattern="pi\\[1\\:V\\] ~ ddirch\\(L\\)", "pi <- 1", model.file)
model.file <- gsub(pattern="Om\\[i\\] ~ dcat\\(pi\\)", "Om\\[i\\] <- 1", model.file)
}
if(biases==FALSE){
model.file <- gsub(pattern="a\\[i\\] <- exp\\(alog\\[i\\]\\)", "a\\[i\\] <- 1", model.file)
model.file <- gsub(pattern="alog\\[i\\] ~ dnorm\\(amu\\[Om\\[i\\]\\],atau\\[Om\\[i\\]\\]\\)T\\(-2.3,2.3\\)", "alog\\[i\\] <- 0", model.file)
model.file <- gsub(pattern="atau\\[v\\] ~ dgamma\\(.01, .01\\)T\\(.01,\\)", "atau\\[v\\] <- 0", model.file)
model.file <- gsub(pattern="b\\[i\\] ~ dnorm\\(bmu\\[Om\\[i\\]\\],btau\\[Om\\[i\\]\\]) ", "b\\[i\\] <- 0", model.file)
model.file <- gsub(pattern="btau\\[v\\] ~ dgamma\\(.01, .01\\)", "btau\\[v\\] <- 0", model.file)
}
}
######################
#Runs the Model in JAGS
#- saves the data object from loadfilefunc within the jags object
#- saves other useful details used later into the jags object
######################
if(parallel==FALSE){
cctfit <- jags(data=jags.data, inits=jags.inits, parameters.to.save=jags.params,
n.chains=jags.chains, n.iter=(jags.iter+jags.burnin), n.burnin=jags.burnin,
n.thin=jags.thin, model.file=textConnection(model.file)) #textConnection(model.file)
cctfit$dataind <- datob$datind; cctfit$data <- datob$dat; cctfit$n <- nresp; cctfit$m <- nitem; cctfit$V <- V
cctfit$mval <- datob$mval; cctfit$itemdiff <- itemdiff; cctfit$checksrun <- FALSE; cctfit$whmodel <- datob$whmodel; cctfit$datob <- datob
if(cctfit$mval==TRUE){cctfit$datamiss <- datob$datna}
if(cctfit$whmodel=="LTRM"){cctfit$C <- C;cctfit$polycor <- FALSE}
}else{
### Prepare / Evaluate parameters for Parallel JAGS run
jags.burnin <- jags.burnin; jags.iter <- jags.iter; jags.chains <- jags.chains; jags.thin <- jags.thin;
tmpfn=tempfile()
tmpcn=file(tmpfn,"w"); cat(model.file,file=tmpcn); close(tmpcn);
message("\n ...Fitting model in parallel \n note: progress bar currently not available with parallel option")
cctfit <- jags.parallel(data=jags.data, inits=jags.inits, parameters.to.save=jags.params,
n.chains=jags.chains, n.iter=(jags.iter+jags.burnin), n.burnin=jags.burnin,
n.thin=jags.thin, model.file=tmpfn, envir=environment(),jags.seed = abs(.Random.seed[3]))
cctfit$dataind <- datob$datind; cctfit$data <- datob$dat; cctfit$n <- nresp; cctfit$m <- nitem; cctfit$V <- V
cctfit$mval <- datob$mval; cctfit$itemdiff <- itemdiff; cctfit$checksrun <- FALSE; cctfit$whmodel <- datob$whmodel; cctfit$datob <- datob
if(cctfit$mval==TRUE){cctfit$datamiss <- datob$datna}
if(cctfit$whmodel=="LTRM"){cctfit$C <- C}
}
######################
#Function used to calculate the Rhats
######################
Rhat1 <- function(mat) {
m <- ncol(mat)
n <- nrow(mat)
b <- apply(mat,2,mean)
B <- sum((b-mean(mat))^2)*n/(m-1)
w <- apply(mat,2,var)
W <- mean(w)
s2hat <- (n-1)/n*W + B/n
Vhat <- s2hat + B/m/n
covWB <- n /m * (cov(w,b^2)-2*mean(b)*cov(w,b))
varV <- (n-1)^2 / n^2 * var(w)/m +
(m+1)^2 / m^2 / n^2 * 2*B^2/(m-1) +
2 * (m-1)*(n-1)/m/n^2 * covWB
df <- 2 * Vhat^2 / varV
R <- sqrt((df+3) * Vhat / (df+1) / W)
return(R)
}
Rhat <- function(arr) {
dm <- dim(arr)
if (length(dm)==2) return(Rhat1(arr))
if (dm[2]==1) return(NULL)
if (dm[3]==1) return(Rhat1(arr[,,1]))
return(apply(arr,3,Rhat1))
}
######################
#Algorithm that corrects for label switching for the GCM
######################
labelswitchalggcm <- function(cctfit,chnind=0){
cctfit2 <- cctfit
nch <- cctfit2$BUGSoutput$n.chains
nsamp <- cctfit2$BUGSoutput$n.keep
if(nch!=1){
ntruths <- cctfit2$V
truths <- array(NA,c(cctfit2$m,nch,ntruths))
inds <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]
inds <- matrix(inds,cctfit2$m,cctfit2$V)
for(v in 1:cctfit$V){truths[,,v] <- t(apply(cctfit$BUGSoutput$sims.array[ ,,inds[,v]],c(2,3),mean))}
V <- cctfit2$V
chstart <- 1
if(length(chnind)==1){
chstart <- 2
chnind <- array(NA,c(V,nch))
chnind[1:V,1] <- 1:V
for(v in 1:V){
for(ch in chstart:nch){
Tind <- c(1:V)[-chnind[,ch][!is.na(chnind[,ch])]]
if(length(Tind)==0){Tind <- c(1:V)}
chnind[v,ch] <- which(max(cor(truths[1:cctfit2$m, 1, v],truths[1:cctfit2$m, ch, Tind]))==cor(truths[1:cctfit2$m, 1, v],truths[1:cctfit2$m, ch, ]))
}}
}
nsamp <- cctfit$BUGSoutput$n.keep
if(cctfit$itemdiff==TRUE){
inds2 <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]]
inds2 <- matrix(inds2,cctfit2$m,cctfit2$V)
inds <- rbind(inds,
inds2,
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lammu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lamtau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="thmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="thtau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gtau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="p")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]])
}else{
inds <- rbind(inds,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="thmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="thtau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gtau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="p")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]])
}
einds <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]
tmpeinds <- cctfit$BUGSoutput$sims.array[ ,,einds]
for(v in 1:cctfit$V){
for(ch in chstart:nch){
cctfit2$BUGSoutput$sims.array[ ,ch,inds[,v]] <- cctfit$BUGSoutput$sims.array[ ,ch,inds[,chnind[v,ch]]] #this cctfit2 vs. cctfit difference is intentional
if(chstart==2){cctfit2$BUGSoutput$sims.array[ ,ch,einds][cctfit$BUGSoutput$sims.array[ ,ch,einds]==chnind[v,ch]] <- chnind[v,1]}
if(chstart==1){cctfit2$BUGSoutput$sims.array[ ,ch,einds][cctfit$BUGSoutput$sims.array[ ,ch,einds]==v] <- chnind[v,1]}
}}
}
cctfit2$BUGSoutput$sims.list[["Om"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]], c(nsamp*nch,cctfit$n))
cctfit2$BUGSoutput$mean$Om <- apply(cctfit2$BUGSoutput$sims.list[["Om"]],2,mean)
cctfit2$BUGSoutput$sims.matrix <- array(cctfit2$BUGSoutput$sims.array,c(nsamp*nch,dim(cctfit$BUGSoutput$sims.array)[3])) #this cctfit2 vs. cctfit difference is intentional
cctfit2$BUGSoutput$sims.list[["th"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="th")]]], c(nsamp*nch,cctfit$n))
cctfit2$BUGSoutput$sims.list[["g"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="g")]]], c(nsamp*nch,cctfit$n))
#new code
cctfit2$BUGSoutput$mean[["th"]] <- apply(cctfit2$BUGSoutput$sims.list[["th"]],2,mean)
cctfit2$BUGSoutput$mean[["g"]] <- apply(cctfit2$BUGSoutput$sims.list[["g"]],2,mean)
if(cctfit$itemdiff==TRUE){cctfit2$BUGSoutput$sims.list[["lam"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]]], c(nsamp*nch,cctfit$m))}
cctfit2$BUGSoutput$sims.list[["Z"]] <- array(NA, c(nsamp*nch,cctfit$m,cctfit$V))
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$sims.list[["lam"]] <- array(NA, c(nsamp*nch,cctfit$m,cctfit$V))
cctfit2$BUGSoutput$sims.list[["lammu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["lamtau"]] <- array(NA, c(nsamp*nch,cctfit$V))
}
cctfit2$BUGSoutput$sims.list[["thmu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["thtau"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["gmu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["gtau"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["p"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["pi"]] <- array(NA, c(nsamp*nch,cctfit$V))
for(v in 1:V){
cctfit2$BUGSoutput$sims.list[["Z"]][,,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]][1:cctfit$m +((v-1)*cctfit$m)]], c(nsamp*nch,cctfit$m))
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$sims.list[["lam"]][,,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]][1:cctfit$m +((v-1)*cctfit$m)]], c(nsamp*nch,cctfit$m))
cctfit2$BUGSoutput$sims.list[["lammu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lammu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["lamtau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lamtau")]][v]], c(nsamp*nch))
}
cctfit2$BUGSoutput$sims.list[["thmu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="thmu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["thtau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="thtau")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["gmu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gmu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["gtau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gtau")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["p"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="p")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["pi"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$mean$Z[,v] <- apply(cctfit2$BUGSoutput$sims.list[["Z"]][,,v],2,mean)
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$mean$lam[,v] <- apply(cctfit2$BUGSoutput$sims.list[["lam"]][,,v],2,mean)
cctfit2$BUGSoutput$mean$lammu[v] <- mean(cctfit2$BUGSoutput$sims.list[["lammu"]][,v])
cctfit2$BUGSoutput$mean$lamtau[v] <- mean(cctfit2$BUGSoutput$sims.list[["lamtau"]][,v])
}
cctfit2$BUGSoutput$mean$thmu[v] <- mean(cctfit2$BUGSoutput$sims.list[["thmu"]][,v])
cctfit2$BUGSoutput$mean$thtau[v] <- mean(cctfit2$BUGSoutput$sims.list[["thtau"]][,v])
cctfit2$BUGSoutput$mean$gmu[v] <- mean(cctfit2$BUGSoutput$sims.list[["gmu"]][,v])
cctfit2$BUGSoutput$mean$gtau[v] <- mean(cctfit2$BUGSoutput$sims.list[["gtau"]][,v])
cctfit2$BUGSoutput$mean$p[v] <- mean(cctfit2$BUGSoutput$sims.list[["p"]][,v])
cctfit2$BUGSoutput$mean$pi[v] <- mean(cctfit2$BUGSoutput$sims.list[["pi"]][,v])
}
if(nch!=1){
cctfit2$BUGSoutput$summary[,1] <- apply(apply(cctfit2$BUGSoutput$sims.array,c(2,3),mean),2,mean)
cctfit2$BUGSoutput$summary[,2] <- apply(apply(cctfit2$BUGSoutput$sims.array,c(2,3),sd),2,sd)
cctfit2$BUGSoutput$summary[,3:7] <- t(apply(cctfit2$BUGSoutput$sims.matrix,2,function(x) quantile(x,probs=c(.025,.25,.50,.75,.975))))
cctfit2$BUGSoutput$summary[,8] <- Rhat(cctfit2$BUGSoutput$sims.array)
cctfit2$BUGSoutput$summary[,8][is.nan(cctfit2$BUGSoutput$summary[,8])] <- 1.000000
dimnames(cctfit2$BUGSoutput$sims.array) <- list(NULL,NULL,rownames(cctfit$BUGSoutput$summary))
dimnames(cctfit2$BUGSoutput$sims.matrix) <- list(NULL,rownames(cctfit$BUGSoutput$summary))
}else{
cctfit2$BUGSoutput$summary[,1] <- apply(cctfit2$BUGSoutput$sims.array,2,mean)
cctfit2$BUGSoutput$summary[,2] <- apply(cctfit2$BUGSoutput$sims.array,2,sd)
cctfit2$BUGSoutput$summary[,3:7] <- t(apply(cctfit2$BUGSoutput$sims.matrix,2,function(x) quantile(x,probs=c(.025,.25,.50,.75,.975))))
cctfit2$BUGSoutput$summary <- cctfit2$BUGSoutput$summary[,-c(8,9)]
dimnames(cctfit2$BUGSoutput$sims.array) <- list(NULL,NULL,rownames(cctfit$BUGSoutput$summary))
dimnames(cctfit2$BUGSoutput$sims.matrix) <- list(NULL,rownames(cctfit$BUGSoutput$summary))
}
cctfit <- cctfit2; rm(cctfit2)
return(cctfit)
}
######################
#Algorithm that corrects for label switching for the LTRM
######################
labelswitchalgltrm <- function(cctfit,chnind=0){
cctfit2 <- cctfit
nch <- cctfit2$BUGSoutput$n.chains
nsamp <- cctfit2$BUGSoutput$n.keep
if(nch!=1){
ntruths <- cctfit2$V
truths <- array(NA,c(cctfit2$m,nch,ntruths))
inds <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="T")]]
inds <- matrix(inds,cctfit2$m,cctfit2$V)
for(v in 1:cctfit$V){truths[,,v] <- t(apply(cctfit$BUGSoutput$sims.array[ ,,inds[,v]],c(2,3),mean))}
V <- cctfit2$V
chstart <- 1
if(length(chnind)==1){
chstart <- 2
chnind <- array(NA,c(V,nch))
chnind[1:V,1] <- 1:V
for(v in 1:V){
for(ch in chstart:nch){
Tind <- c(1:V)[-chnind[,ch][!is.na(chnind[,ch])]]
if(length(Tind)==0){Tind <- c(1:V)}
chnind[v,ch] <- which(max(cor(truths[1:cctfit2$m, 1, v],truths[1:cctfit2$m, ch, Tind]))==cor(truths[1:cctfit2$m, 1, v],truths[1:cctfit2$m, ch, ]))
}}
}
nsamp <- cctfit$BUGSoutput$n.keep
if(cctfit$itemdiff==TRUE){
inds2 <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]]
inds2 <- matrix(inds2,cctfit2$m,cctfit2$V)
inds <- rbind(inds,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Tmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Ttau")]],
inds2,
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lammu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lamtau")]],
matrix(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gam")]],cctfit2$C-1,cctfit2$V),
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Emu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Etau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="amu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="atau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="bmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="btau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]])
rm(inds2)
}else{
inds <- rbind(inds,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Tmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Ttau")]],
matrix(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gam")]],cctfit2$C-1,cctfit2$V),
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Emu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Etau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="amu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="atau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="bmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="btau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]])
}
einds <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]
tmpeinds <- cctfit$BUGSoutput$sims.array[ ,,einds]
for(v in 1:cctfit$V){
for(ch in chstart:nch){
cctfit2$BUGSoutput$sims.array[ ,ch,inds[,v]] <- cctfit$BUGSoutput$sims.array[ ,ch,inds[,chnind[v,ch]]] #this cctfit2 vs. cctfit difference is intentional
if(chstart==2){cctfit2$BUGSoutput$sims.array[ ,ch,einds][cctfit$BUGSoutput$sims.array[ ,ch,einds]==chnind[v,ch]] <- chnind[v,1]}
if(chstart==1){cctfit2$BUGSoutput$sims.array[ ,ch,einds][cctfit$BUGSoutput$sims.array[ ,ch,einds]==v] <- chnind[v,1]}
}}
}
cctfit2$BUGSoutput$sims.list[["Om"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]], c(nsamp*nch,cctfit$n))
cctfit2$BUGSoutput$mean$Om <- apply(cctfit2$BUGSoutput$sims.list[["Om"]],2,mean)
cctfit2$BUGSoutput$sims.matrix <- array(cctfit2$BUGSoutput$sims.array,c(nsamp*nch,dim(cctfit$BUGSoutput$sims.array)[3])) #this cctfit2 vs. cctfit difference is intentional
cctfit2$BUGSoutput$sims.list[["E"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="E")]]], c(nsamp*nch,cctfit$n))
cctfit2$BUGSoutput$sims.list[["a"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="a")]]], c(nsamp*nch,cctfit$n))
cctfit2$BUGSoutput$sims.list[["b"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="b")]]], c(nsamp*nch,cctfit$n))
#new code
cctfit2$BUGSoutput$mean[["E"]] <- apply(cctfit2$BUGSoutput$sims.list[["E"]],2,mean)
cctfit2$BUGSoutput$mean[["a"]] <- apply(cctfit2$BUGSoutput$sims.list[["a"]],2,mean)
cctfit2$BUGSoutput$mean[["b"]] <- apply(cctfit2$BUGSoutput$sims.list[["b"]],2,mean)
if(cctfit$itemdiff==TRUE){cctfit2$BUGSoutput$sims.list[["lam"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]]], c(nsamp*nch,cctfit$m))}
cctfit2$BUGSoutput$sims.list[["T"]] <- array(NA, c(nsamp*nch,cctfit$m,cctfit$V))
cctfit2$BUGSoutput$sims.list[["Tmu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["Ttau"]] <- array(NA, c(nsamp*nch,cctfit$V))
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$sims.list[["lam"]] <- array(NA, c(nsamp*nch,cctfit$m,cctfit$V))
cctfit2$BUGSoutput$sims.list[["lammu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["lamtau"]] <- array(NA, c(nsamp*nch,cctfit$V))
}
cctfit2$BUGSoutput$sims.list[["gam"]] <- array(NA, c(nsamp*nch,cctfit$C-1,cctfit$V))
cctfit2$BUGSoutput$sims.list[["Emu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["Etau"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["amu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["atau"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["bmu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["btau"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["pi"]] <- array(NA, c(nsamp*nch,cctfit$V))
if(cctfit$C==2 && length(dim(cctfit2$BUGSoutput$sims.list[["gam"]])) < 3 ){
cctfit2$BUGSoutput$sims.list[["gam"]] <- array(cctfit2$BUGSoutput$sims.list[["gam"]], c(nsamp*nch,cctfit$C-1,cctfit$V))
}
for(v in 1:cctfit2$V){
cctfit2$BUGSoutput$sims.list[["T"]][,,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="T")]][1:cctfit$m +((v-1)*cctfit$m)]], c(nsamp*nch,cctfit$m))
cctfit2$BUGSoutput$sims.list[["Tmu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Tmu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["Ttau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Ttau")]][v]], c(nsamp*nch))
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$sims.list[["lam"]][,,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]][1:cctfit$m +((v-1)*cctfit$m)]], c(nsamp*nch,cctfit$m))
cctfit2$BUGSoutput$sims.list[["lammu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lammu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["lamtau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lamtau")]][v]], c(nsamp*nch))
}
cctfit2$BUGSoutput$sims.list[["gam"]][,,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="gam")]][1:(cctfit$C-1) +((v-1)*(cctfit$C-1))]], c(nsamp*nch,cctfit$C-1))
cctfit2$BUGSoutput$sims.list[["Emu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Emu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["Etau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Etau")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["amu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="amu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["atau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="atau")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["bmu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="bmu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["btau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="btau")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["pi"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$mean$T[,v] <- apply(cctfit2$BUGSoutput$sims.list[["T"]][,,v],2,mean)
cctfit2$BUGSoutput$mean$Tmu[v] <- mean(cctfit2$BUGSoutput$sims.list[["Tmu"]][,v])
cctfit2$BUGSoutput$mean$Ttau[v] <- mean(cctfit2$BUGSoutput$sims.list[["Ttau"]][,v])
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$mean$lam[,v] <- apply(cctfit2$BUGSoutput$sims.list[["lam"]][,,v],2,mean)
cctfit2$BUGSoutput$mean$lammu[v] <- mean(cctfit2$BUGSoutput$sims.list[["lammu"]][,v])
cctfit2$BUGSoutput$mean$lamtau[v] <- mean(cctfit2$BUGSoutput$sims.list[["lamtau"]][,v])
}
if(cctfit$C==2){
cctfit2$BUGSoutput$mean$gam[v] <- mean(cctfit2$BUGSoutput$sims.list[["gam"]][,,v])
}else{cctfit2$BUGSoutput$mean$gam[,v] <- apply(cctfit2$BUGSoutput$sims.list[["gam"]][,,v],2,mean)}
cctfit2$BUGSoutput$mean$Emu[v] <- mean(cctfit2$BUGSoutput$sims.list[["Emu"]][,v])
cctfit2$BUGSoutput$mean$Etau[v] <- mean(cctfit2$BUGSoutput$sims.list[["Etau"]][,v])
cctfit2$BUGSoutput$mean$amu[v] <- mean(cctfit2$BUGSoutput$sims.list[["amu"]][,v])
cctfit2$BUGSoutput$mean$atau[v] <- mean(cctfit2$BUGSoutput$sims.list[["atau"]][,v])
cctfit2$BUGSoutput$mean$bmu[v] <- mean(cctfit2$BUGSoutput$sims.list[["bmu"]][,v])
cctfit2$BUGSoutput$mean$btau[v] <- mean(cctfit2$BUGSoutput$sims.list[["btau"]][,v])
cctfit2$BUGSoutput$mean$pi[v] <- mean(cctfit2$BUGSoutput$sims.list[["pi"]][,v])
}
if(nch!=1){
cctfit2$BUGSoutput$summary[,1] <- apply(apply(cctfit2$BUGSoutput$sims.array,c(2,3),mean),2,mean)
cctfit2$BUGSoutput$summary[,2] <- apply(apply(cctfit2$BUGSoutput$sims.array,c(2,3),sd),2,sd)
cctfit2$BUGSoutput$summary[,3:7] <- t(apply(cctfit2$BUGSoutput$sims.matrix,2,function(x) quantile(x,probs=c(.025,.25,.50,.75,.975))))
cctfit2$BUGSoutput$summary[,8] <- Rhat(cctfit2$BUGSoutput$sims.array)
cctfit2$BUGSoutput$summary[,8][is.nan(cctfit2$BUGSoutput$summary[,8])] <- 1.000000
dimnames(cctfit2$BUGSoutput$sims.array) <- list(NULL,NULL,rownames(cctfit$BUGSoutput$summary))
dimnames(cctfit2$BUGSoutput$sims.matrix) <- list(NULL,rownames(cctfit$BUGSoutput$summary))
}else{
cctfit2$BUGSoutput$summary[,1] <- apply(cctfit2$BUGSoutput$sims.array,2,mean)
cctfit2$BUGSoutput$summary[,2] <- apply(cctfit2$BUGSoutput$sims.array,2,sd)
cctfit2$BUGSoutput$summary[,3:7] <- t(apply(cctfit2$BUGSoutput$sims.matrix,2,function(x) quantile(x,probs=c(.025,.25,.50,.75,.975))))
cctfit2$BUGSoutput$summary <- cctfit2$BUGSoutput$summary[,-c(8,9)]
dimnames(cctfit2$BUGSoutput$sims.array) <- list(NULL,NULL,rownames(cctfit$BUGSoutput$summary))
dimnames(cctfit2$BUGSoutput$sims.matrix) <- list(NULL,rownames(cctfit$BUGSoutput$summary))
}
cctfit <- cctfit2; rm(cctfit2)
return(cctfit)
}
######################
#Algorithm that corrects for label switching for the CRM
######################
labelswitchalgcrm <- function(cctfit,chnind=0){
cctfit2 <- cctfit
nch <- cctfit2$BUGSoutput$n.chains
nsamp <- cctfit2$BUGSoutput$n.keep
if(nch!=1){
ntruths <- cctfit2$V
truths <- array(NA,c(cctfit2$m,nch,ntruths))
inds <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="T")]]
inds <- matrix(inds,cctfit2$m,cctfit2$V)
for(v in 1:cctfit$V){truths[,,v] <- t(apply(cctfit$BUGSoutput$sims.array[ ,,inds[,v]],c(2,3),mean))}
V <- cctfit2$V
chstart <- 1
if(length(chnind)==1){
chstart <- 2
chnind <- array(NA,c(V,nch))
chnind[1:cctfit2$V,1] <- 1:cctfit2$V
for(v in 1:cctfit2$V){
for(ch in chstart:nch){
Tind <- c(1:cctfit2$V)[-chnind[,ch][!is.na(chnind[,ch])]]
if(length(Tind)==0){Tind <- c(1:cctfit2$V)}
chnind[v,ch] <- which(max(cor(truths[1:cctfit2$m, 1, v],truths[1:cctfit2$m, ch, Tind]))==cor(truths[1:cctfit2$m, 1, v],truths[1:cctfit2$m, ch, ]))
}}
}
nsamp <- cctfit$BUGSoutput$n.keep
if(cctfit$itemdiff==TRUE){
inds2 <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]]
inds2 <- matrix(inds2,cctfit2$m,cctfit2$V)
inds <- rbind(inds,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Tmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Ttau")]],
inds2,
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lammu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lamtau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Emu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Etau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="amu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="atau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="bmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="btau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]])
rm(inds2)
}else{
inds <- rbind(inds,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Tmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Ttau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Emu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Etau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="amu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="atau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="bmu")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="btau")]],
cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]])
}
einds <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]
tmpeinds <- cctfit$BUGSoutput$sims.array[ ,,einds]
for(v in 1:cctfit$V){
for(ch in chstart:nch){
cctfit2$BUGSoutput$sims.array[ ,ch,inds[,v]] <- cctfit$BUGSoutput$sims.array[ ,ch,inds[,chnind[v,ch]]] #this cctfit2 vs. cctfit difference is intentional
if(chstart==2){cctfit2$BUGSoutput$sims.array[ ,ch,einds][cctfit$BUGSoutput$sims.array[ ,ch,einds]==chnind[v,ch]] <- chnind[v,1]}
if(chstart==1){cctfit2$BUGSoutput$sims.array[ ,ch,einds][cctfit$BUGSoutput$sims.array[ ,ch,einds]==v] <- chnind[v,1]}
}}
}
cctfit2$BUGSoutput$sims.list[["Om"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]], c(nsamp*nch,cctfit$n))
cctfit2$BUGSoutput$mean$Om <- apply(cctfit2$BUGSoutput$sims.list[["Om"]],2,mean)
cctfit2$BUGSoutput$sims.matrix <- array(cctfit2$BUGSoutput$sims.array,c(nsamp*nch,dim(cctfit$BUGSoutput$sims.array)[3])) #this cctfit2 vs. cctfit difference is intentional
cctfit2$BUGSoutput$sims.list[["E"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="E")]]], c(nsamp*nch,cctfit$n))
cctfit2$BUGSoutput$sims.list[["a"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="a")]]], c(nsamp*nch,cctfit$n))
cctfit2$BUGSoutput$sims.list[["b"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="b")]]], c(nsamp*nch,cctfit$n))
#new code
cctfit2$BUGSoutput$mean[["E"]] <- apply(cctfit2$BUGSoutput$sims.list[["E"]],2,mean)
cctfit2$BUGSoutput$mean[["a"]] <- apply(cctfit2$BUGSoutput$sims.list[["a"]],2,mean)
cctfit2$BUGSoutput$mean[["b"]] <- apply(cctfit2$BUGSoutput$sims.list[["b"]],2,mean)
if(cctfit$itemdiff==TRUE){cctfit2$BUGSoutput$sims.list[["lam"]] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]]], c(nsamp*nch,cctfit$m))}
cctfit2$BUGSoutput$sims.list[["T"]] <- array(NA, c(nsamp*nch,cctfit$m,cctfit$V))
cctfit2$BUGSoutput$sims.list[["Tmu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["Ttau"]] <- array(NA, c(nsamp*nch,cctfit$V))
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$sims.list[["lam"]] <- array(NA, c(nsamp*nch,cctfit$m,cctfit$V))
cctfit2$BUGSoutput$sims.list[["lammu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["lamtau"]] <- array(NA, c(nsamp*nch,cctfit$V))
}
cctfit2$BUGSoutput$sims.list[["Emu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["Etau"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["amu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["atau"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["bmu"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["btau"]] <- array(NA, c(nsamp*nch,cctfit$V))
cctfit2$BUGSoutput$sims.list[["pi"]] <- array(NA, c(nsamp*nch,cctfit$V))
for(v in 1:cctfit2$V){
cctfit2$BUGSoutput$sims.list[["T"]][,,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="T")]][1:cctfit$m +((v-1)*cctfit$m)]], c(nsamp*nch,cctfit$m))
cctfit2$BUGSoutput$sims.list[["Tmu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Tmu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["Ttau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Ttau")]][v]], c(nsamp*nch))
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$sims.list[["lam"]][,,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lam")]][1:cctfit$m +((v-1)*cctfit$m)]], c(nsamp*nch,cctfit$m))
cctfit2$BUGSoutput$sims.list[["lammu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lammu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["lamtau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="lamtau")]][v]], c(nsamp*nch))
}
cctfit2$BUGSoutput$sims.list[["Emu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Emu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["Etau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Etau")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["amu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="amu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["atau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="atau")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["bmu"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="bmu")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["btau"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="btau")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$sims.list[["pi"]][,v] <- array(cctfit2$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="pi")]][v]], c(nsamp*nch))
cctfit2$BUGSoutput$mean$T[,v] <- apply(cctfit2$BUGSoutput$sims.list[["T"]][,,v],2,mean)
cctfit2$BUGSoutput$mean$Tmu[v] <- mean(cctfit2$BUGSoutput$sims.list[["Tmu"]][,v])
cctfit2$BUGSoutput$mean$Ttau[v] <- mean(cctfit2$BUGSoutput$sims.list[["Ttau"]][,v])
if(cctfit$itemdiff==TRUE){
cctfit2$BUGSoutput$mean$lam[,v] <- apply(cctfit2$BUGSoutput$sims.list[["lam"]][,,v],2,mean)
cctfit2$BUGSoutput$mean$lammu[v] <- mean(cctfit2$BUGSoutput$sims.list[["lammu"]][,v])
cctfit2$BUGSoutput$mean$lamtau[v] <- mean(cctfit2$BUGSoutput$sims.list[["lamtau"]][,v])
}
cctfit2$BUGSoutput$mean$Emu[v] <- mean(cctfit2$BUGSoutput$sims.list[["Emu"]][,v])
cctfit2$BUGSoutput$mean$Etau[v] <- mean(cctfit2$BUGSoutput$sims.list[["Etau"]][,v])
cctfit2$BUGSoutput$mean$amu[v] <- mean(cctfit2$BUGSoutput$sims.list[["amu"]][,v])
cctfit2$BUGSoutput$mean$atau[v] <- mean(cctfit2$BUGSoutput$sims.list[["atau"]][,v])
cctfit2$BUGSoutput$mean$bmu[v] <- mean(cctfit2$BUGSoutput$sims.list[["bmu"]][,v])
cctfit2$BUGSoutput$mean$btau[v] <- mean(cctfit2$BUGSoutput$sims.list[["btau"]][,v])
cctfit2$BUGSoutput$mean$pi[v] <- mean(cctfit2$BUGSoutput$sims.list[["pi"]][,v])
}
if(nch!=1){
cctfit2$BUGSoutput$summary[,1] <- apply(apply(cctfit2$BUGSoutput$sims.array,c(2,3),mean),2,mean)
cctfit2$BUGSoutput$summary[,2] <- apply(apply(cctfit2$BUGSoutput$sims.array,c(2,3),sd),2,sd)
cctfit2$BUGSoutput$summary[,3:7] <- t(apply(cctfit2$BUGSoutput$sims.matrix,2,function(x) quantile(x,probs=c(.025,.25,.50,.75,.975))))
cctfit2$BUGSoutput$summary[,8] <- Rhat(cctfit2$BUGSoutput$sims.array)
cctfit2$BUGSoutput$summary[,8][is.nan(cctfit2$BUGSoutput$summary[,8])] <- 1.000000
dimnames(cctfit2$BUGSoutput$sims.array) <- list(NULL,NULL,rownames(cctfit$BUGSoutput$summary))
dimnames(cctfit2$BUGSoutput$sims.matrix) <- list(NULL,rownames(cctfit$BUGSoutput$summary))
}else{
cctfit2$BUGSoutput$summary[,1] <- apply(cctfit2$BUGSoutput$sims.array,2,mean)
cctfit2$BUGSoutput$summary[,2] <- apply(cctfit2$BUGSoutput$sims.array,2,sd)
cctfit2$BUGSoutput$summary[,3:7] <- t(apply(cctfit2$BUGSoutput$sims.matrix,2,function(x) quantile(x,probs=c(.025,.25,.50,.75,.975))))
cctfit2$BUGSoutput$summary <- cctfit2$BUGSoutput$summary[,-c(8,9)]
dimnames(cctfit2$BUGSoutput$sims.array) <- list(NULL,NULL,rownames(cctfit$BUGSoutput$summary))
dimnames(cctfit2$BUGSoutput$sims.matrix) <- list(NULL,rownames(cctfit$BUGSoutput$summary))
}
cctfit <- cctfit2; rm(cctfit2)
return(cctfit)
}
######################
#This is run after the jags inference, we are still in the 'Apply CCT Model' function
#- Reports the number of Rhats above 1.05 and 1.10 (before applying the algorithm that corrects for label-switching)
#- Detects if a mixture model was applied
#- If so, the appropriate label-correcting algorithm is applied
#- Recalculates the Rhats, DIC, and statistics for the parameters
#- Reports the number of Rhats above 1.05 and 1.10
#- Outputs the DIC that is calculated after the label-correcting algorithm (if applicable)
######################
# message("\n ...Inference complete, data is saved as '",guidat$varname,"'")
# if(clusters > 1){
# message("\n 'cctfit$respmem' provides the respondent clustering")
# }
hdi <- function(sampleVec, credMass=0.95){
sortedPts = sort(sampleVec)
ciIdxInc = floor(credMass * length( sortedPts) )
nCIs = length( sortedPts) - ciIdxInc
ciwidth = rep(0, nCIs)
for(i in 1:nCIs){
ciwidth[i] = sortedPts[i + ciIdxInc] - sortedPts[i]}
HDImin = sortedPts[which.min(ciwidth)]
HDImax = sortedPts[which.min(ciwidth)+ciIdxInc]
HDIlim = c(HDImin,HDImax)
return(HDIlim)
}
message("\n ...Performing final calculations")
# }
if(cctfit$BUGSoutput$n.chains > 1){
cctfit$BUGSoutput$summary[,8] <- Rhat(cctfit$BUGSoutput$sims.array)
cctfit$BUGSoutput$summary[,8][is.nan(cctfit$BUGSoutput$summary[,8])] <- 1.000000
if(cctfit$whmodel== "GCM"){
cctfit$Rhat$ncp <- length(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8])
cctfit$Rhat$above110 <- sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8]>1.10)
cctfit$Rhat$above105 <- sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8]>1.050)
}else{
cctfit$Rhat$ncp <- length(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8])
cctfit$Rhat$above110 <- sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8]>1.10)
cctfit$Rhat$above105 <- sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8]>1.050)
}
message(paste("\nFor Continuous Parameters"))
message(paste("Number of Rhats above 1.10 : ",cctfit$Rhat$above110,"/",cctfit$Rhat$ncp,"\nNumber of Rhats above 1.05 : ",cctfit$Rhat$above105,"/",cctfit$Rhat$ncp))
}
if(cctfit$V>1 && cctfit$BUGSoutput$n.chains==1){
tmp <- unique(apply(cctfit$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]],c(2),Mode))
if(length(tmp)==1){
message(paste("\n ...This chain has ",length(tmp)," culture rather than the ",cctfit$V," cultures requested", sep=""))
message(paste("\n ...Try running the inference again",sep="" ))
}
if(length(tmp)!=1 && length(tmp) < cctfit$V){
message(paste("\n ...This chain has ",tmp," cultures rather than the ",cctfit$V," cultures requested", sep=""))
message(paste("\n ...Try running the inference again",sep="" ))
}
}
if(cctfit$V>1 && cctfit$BUGSoutput$n.chains > 1){
message("\n ...More than 1 culture applied with more than 1 chain")
einds <- cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]
tmp <- apply(apply(cctfit$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]],c(2,3),Mode),1,unique)
chntoremove <- NULL
if(is.list(tmp)){
for(i in 1:cctfit$BUGSoutput$n.chains){
if(length(tmp[[i]])!=cctfit$V){chntoremove <- c(chntoremove,i)}
}
}
if(length(dim(tmp))==2){
for(i in 1:cctfit$BUGSoutput$n.chains){
if(length(tmp[,i])!=cctfit$V){chntoremove <- c(chntoremove,i)}
}
}
if(is.null(dim(tmp)) && !is.list(tmp)){chntoremove <- c(1:cctfit$BUGSoutput$n.chains)}
if(length(chntoremove)>0){
if(length(chntoremove) < cctfit$BUGSoutput$n.chains){
if(length(chntoremove)==1){
message(paste("\n ...",length(chntoremove)," chain out of ",cctfit$BUGSoutput$n.chains," had fewer than ",cctfit$V," cultures requested",sep=""))
message(paste("\n ...", "removing the ", length(chntoremove)," chain", sep=""))
}else{
message(paste("\n ...",length(chntoremove)," chains out of ",cctfit$BUGSoutput$n.chains," had fewer than ",cctfit$V," cultures requested",sep=""))
message(paste("\n ...", "removing these ", length(chntoremove)," chains", sep=""))
}
cctfit$BUGSoutput$n.chains <- cctfit$BUGSoutput$n.chains-length(chntoremove)
cctfit$BUGSoutput$n.chain <- cctfit$BUGSoutput$n.chains
cctfit$BUGSoutput$n.sims <- cctfit$BUGSoutput$n.chains*cctfit$BUGSoutput$n.keep
if(cctfit$BUGSoutput$n.chain==1){
cctfit$BUGSoutput$sims.array <- array(cctfit$BUGSoutput$sims.array[,-chntoremove,], c(dim(cctfit$BUGSoutput$sims.array)[1],1,dim(cctfit$BUGSoutput$sims.array)[3]))
}else{cctfit$BUGSoutput$sims.array <- cctfit$BUGSoutput$sims.array[,-chntoremove,]}
}else{
message(paste("\n ...All chains out of ",cctfit$BUGSoutput$n.chains," had fewer than ",cctfit$V," cultures requested", sep=""))
message(paste("\n ...Try running the inference again",sep="" ))
}
}
message("\n ...Computing the most-consistent labeling across chains")
if(cctfit$whmodel=="GCM"){
cctfit <- labelswitchalggcm(cctfit)
cctfit$respmem <- apply(cctfit$BUGSoutput$sims.list$Om[,],2,Mode)
tmeans <- cctfit$BUGSoutput$mean$Z
tmeans[tmeans<.5] <- tmeans[tmeans<.5]+1
ind <- rank(apply(abs(1-tmeans),2,mean))
}
if(cctfit$whmodel=="LTRM"){
cctfit <- labelswitchalgltrm(cctfit)
cctfit$respmem <- apply(cctfit$BUGSoutput$sims.list$Om[,],2,Mode)
tmeans <- cctfit$BUGSoutput$mean$T
ind <- rank(-apply(tmeans,2,sd))
}
if(cctfit$whmodel=="CRM"){
cctfit <- labelswitchalgcrm(cctfit)
cctfit$respmem <- apply(cctfit$BUGSoutput$sims.list$Om[,],2,Mode)
tmeans <- cctfit$BUGSoutput$mean$T
ind <- rank(-apply(tmeans,2,sd))
}
# old code:
# if(cctfit$BUGSoutput$n.chains > 1){
# message(paste("\nFor Continuous Parameters:"))
# if(cctfit$whmodel== "GCM"){
# message(paste("Number of Rhats above 1.10 : ",sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8]>1.10),"/",length(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8]),"\nNumber of Rhats above 1.05 : ",sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8]>1.050),"/",length(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8]),sep=""))
# }else{
# message(paste("Number of Rhats above 1.10 : ",sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8]>1.10),"/",length(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8]),"\nNumber of Rhats above 1.05 : ",sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8]>1.050),"/",length(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8]),sep=""))
# }
# }
if(cctfit$BUGSoutput$n.chains > 1){
cctfit$BUGSoutput$summary[,8] <- Rhat(cctfit$BUGSoutput$sims.array)
cctfit$BUGSoutput$summary[,8][is.nan(cctfit$BUGSoutput$summary[,8])] <- 1.000000
if(cctfit$whmodel== "GCM"){
cctfit$Rhat$ncp <- length(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8])
cctfit$Rhat$above110 <- sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8]>1.10)
cctfit$Rhat$above105 <- sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]]),8]>1.050)
}else{
cctfit$Rhat$ncp <- length(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8])
cctfit$Rhat$above110 <- sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8]>1.10)
cctfit$Rhat$above105 <- sum(cctfit$BUGSoutput$summary[-c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]]),8]>1.050)
}
message(paste("\nFor Continuous Parameters"))
message(paste("Number of Rhats above 1.10 : ",cctfit$Rhat$above110,"/",cctfit$Rhat$ncp,"\nNumber of Rhats above 1.05 : ",cctfit$Rhat$above105,"/",cctfit$Rhat$ncp))
}
if(cctfit$BUGSoutput$n.chains > 1){
if(gui==TRUE){message(paste("\nFor Discrete Parameters:"))
message(paste("Use button 'Traceplot Discrete' to see their trace plots",sep=""))
}else{
message(paste("\nFor Discrete Parameters:"))
message(paste("Use function 'dtraceplot()' to see their trace plots",sep=""))
message(paste("\nUse function 'cctmemb()' to see the respondent cluster assignments",sep=""))
}
}
}else{
cctfit$respmem <- rep(1,cctfit$n)
if(cctfit$BUGSoutput$n.chains > 1){
if(gui==TRUE){message(paste("\nFor Discrete Parameters:"))
message(paste("Use button 'Traceplot Discrete' to see their trace plots",sep=""))
}else{
message(paste("\nFor Discrete Parameters:"))
message(paste("Use function 'dtraceplot()' to see their trace plots",sep=""))
}
}
}
######################
#Calculates Read-out tables for subjects and items
#
#######################
Mode <- function(x) {ux <- unique(x); ux[which.max(tabulate(match(x, ux)))] }
cctfit$paramsall <- cctfit$parameters.to.save
cctfit$params <- cctfit$paramsall[cctfit$parameters.to.save %in% c("Z","T","Om","th","E","a","b","g","lam","gam")]
if(cctfit$V > 1){appdims <- c(2,3)}else{appdims <- 2}
a <- data.frame(ans=round(cctfit$BUGSoutput$mean[[cctfit$params[cctfit$params %in% c("Z","T")]]],2));
#a <- data.frame(ans=round(apply(cctfit$BUGSoutput$sims.list[[cctfit$params[1]]],c(2,3),mean),2)) # should be c(2,3) in all cases here;
dimnames(a)[[2]] <- gsub(pattern="s.",replacement=paste("s",sep=""),x=dimnames(a)[[2]]); dimnames(a)[[2]] <- paste(dimnames(a)[[2]],"_",cctfit$params[cctfit$params %in% c("Z","T")],sep="")
a <- data.frame(item=1:cctfit$m,a)
if(cctfit$itemdiff==TRUE){
d <- data.frame(diff=round(cctfit$BUGSoutput$mean[["lam"]],2))
#d <- data.frame(diff=round(apply(cctfit$BUGSoutput$sims.list[["lam"]],c(2,3),mean),2)); # should be c(2,3) in all cases here;
dimnames(d)[[2]] <- gsub(pattern="ff.",replacement=paste("ff",sep=""),x=dimnames(d)[[2]]); dimnames(d)[[2]] <- paste(dimnames(d)[[2]],"_lam",sep="")
a <- data.frame(a,d)
}
cctfit$item <- a
p <- data.frame(group_Om=apply(cctfit$BUGSoutput$sims.list$Om[,],2,Mode),
#comp=apply(cctfit$BUGSoutput$sims.list[[cctfit$params[3]]],2,mean));
comp=round(cctfit$BUGSoutput$mean[[cctfit$params[cctfit$params %in% c("th","E")]]],2));
dimnames(p)[[2]][2] <- paste(dimnames(p)[[2]][2],"_",cctfit$params[cctfit$params %in% c("th","E")],sep="")
b <- round(as.data.frame(cctfit$BUGSoutput$mean[which(names(cctfit$BUGSoutput$mean) %in% c("a","b","g"))]),2)
dimnames(b)[[2]] <- paste("bias_",dimnames(b)[[2]],sep="")
p <- data.frame(participant=1:cctfit$n,p,b)
cctfit$subj <- p
tmphdi <- apply(cctfit$BUGSoutput$sims.list[[cctfit$params[1]]],appdims,hdi)
ahdi <- NULL;
if(cctfit$V>1){for(i in 1:cctfit$V){ ahdi <- cbind(ahdi,t(tmphdi[,,i])) };
}else{ahdi <- t(tmphdi)}; ahdi <- data.frame(ahdi)
for(i in seq(from=1,to=(cctfit$V*2),by=2)){dimnames(ahdi)[[2]][i] <- paste("l_ans",ceiling(i/2),sep=""); dimnames(ahdi)[[2]][i+1] <- paste("u_ans",ceiling(i/2),sep="")}
if(cctfit$itemdiff==TRUE){
tmphdi <- apply(cctfit$BUGSoutput$sims.list[["lam"]],appdims,hdi)
dhdi <- NULL;
if(cctfit$V>1){
for(i in 1:cctfit$V){ dhdi <- round(cbind(dhdi,t(tmphdi[,,i])),2) };
}else{dhdi <- t(tmphdi)}; dhdi <- data.frame(dhdi)
for(i in seq(from=1,to=(cctfit$V*2),by=2)){dimnames(dhdi)[[2]][i] <- paste("l_diff",ceiling(i/2),sep=""); dimnames(dhdi)[[2]][i+1] <- paste("u_diff",ceiling(i/2),sep="")}
ahdi <- cbind(ahdi,dhdi)
}
cctfit$itemhdi <- data.frame(item=1:cctfit$m,ahdi);
tmphdi <- NULL; tmpn <- NULL; pp <- cctfit$params[cctfit$params %in% c("th","E","a","b","g")]
for(i in 1:length(pp)){
tmphdi <- cbind(tmphdi,round(t(apply(cctfit$BUGSoutput$sims.list[[pp[i]]],2,hdi)),2))
tmpn <- c(tmpn,c(paste("l_",pp[i],sep=""),paste("u_",pp[i],sep="")))
}
tmphdi <- data.frame(tmphdi); dimnames(tmphdi)[[2]] <- tmpn;
cctfit$subjhdi <- data.frame(participant=1:cctfit$n,tmphdi)
if(cctfit$whmodel=="LTRM"){
pp <- "gam"
tmphdi <- apply(cctfit$BUGSoutput$sims.list[[pp]],appdims,hdi)
ahdi <- NULL;
a <- data.frame(gam=round(cctfit$BUGSoutput$mean[[pp]],2));
dimnames(a)[[2]] <- gsub(pattern="m.",replacement=paste("m",sep=""),x=dimnames(a)[[2]]);
a <- data.frame(boundary=1:(cctfit$C-1),a)
tmphdi <- apply(cctfit$BUGSoutput$sims.list[[pp]],appdims,hdi)
ahdi <- NULL;
if(cctfit$V>1){for(i in 1:cctfit$V){ ahdi <- cbind(ahdi,t(tmphdi[,,i])) };
}else{ahdi <- t(tmphdi)}; ahdi <- data.frame(ahdi)
for(i in seq(from=1,to=(cctfit$V*2),by=2)){dimnames(ahdi)[[2]][i] <- paste("l_gam",ceiling(i/2),sep=""); dimnames(ahdi)[[2]][i+1] <- paste("u_gam",ceiling(i/2),sep="")}
a <- data.frame(a,round(ahdi,digits=2))
cctfit$cat <- a
}
######################
#DIC is calculated for the model that was applied
#The likelihood of the model is evaluated at each node of each sample and saved to cctfit$Lik
######################
message("\n ...Calculating DIC")
cctfit$BUGSoutput$pD <- var(cctfit$BUGSoutput$sims.list$deviance[,1])/2
nsimstouse <- min(cctfit$BUGSoutput$n.sims,1000)
ind <- sample(1:cctfit$BUGSoutput$n.sims,nsimstouse)
storelik <- 0
if(cctfit$whmodel=="GCM"){
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list$Z)) < 3){
cctfit$BUGSoutput$sims.list$Z <- array(cctfit$BUGSoutput$sims.list[["Z"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(.5,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(.5,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
}
}
cctfit$BUGSoutput$sims.list$D <- array(-1,c(cctfit$BUGSoutput$n.sims,cctfit$n,cctfit$m))
storefulllik <- 0
if(storefulllik==1){
cctfit$Lik <- array(NA, c(cctfit$n,cctfit$m,cctfit$BUGSoutput$n.sims));
for(samp in 1:cctfit$BUGSoutput$n.sims){
cctfit$BUGSoutput$sims.list[["D"]][samp,,] <- (cctfit$BUGSoutput$sims.list[["th"]][samp,]*t(1-cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) /
( (cctfit$BUGSoutput$sims.list[["th"]][samp,]*t(1-cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) +
((1-cctfit$BUGSoutput$sims.list[["th"]][samp,])*t(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) )
cctfit$Lik[,,samp] <- t( ( (t(cctfit$BUGSoutput$sims.list[["D"]][samp,,])+(t(1-cctfit$BUGSoutput$sims.list[["D"]][samp,,])%*%diag(cctfit$BUGSoutput$sims.list[["g"]][samp,])))^(t(cctfit$data[,])*cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]))*(t(1-cctfit$BUGSoutput$sims.list[["D"]][samp,,])%*%diag(cctfit$BUGSoutput$sims.list[["g"]][samp,]))^(t(cctfit$data[,])*(1-cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]))*(t(1-cctfit$BUGSoutput$sims.list[["D"]][samp,,])%*%diag(1-cctfit$BUGSoutput$sims.list[["g"]][samp,]))^((1-t(cctfit$data[,]))*cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])*(t(cctfit$BUGSoutput$sims.list[["D"]][samp,,])+t(1-cctfit$BUGSoutput$sims.list[["D"]][samp,,])%*%diag(1-cctfit$BUGSoutput$sims.list[["g"]][samp,]))^((1-t(cctfit$data[,]))*(1-cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) )
if(cctfit$mval==TRUE){cctfit$Lik[cbind(datob$thena,samp)] <- 1}
}
cctfit$BUGSoutput$sims.list$deviance <- array(-2*apply(log(cctfit$Lik),3,sum),c(cctfit$BUGSoutput$n.sims,1))
}else{
cctfit$LogLik <- array(NA, c(cctfit$BUGSoutput$n.sims));
for(samp in 1:cctfit$BUGSoutput$n.sims){
Dtmp <- (cctfit$BUGSoutput$sims.list[["th"]][samp,]*t(1-cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) /
( (cctfit$BUGSoutput$sims.list[["th"]][samp,]*t(1-cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) +
((1-cctfit$BUGSoutput$sims.list[["th"]][samp,])*t(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) )
Liktmp <- t( ( (t(Dtmp)+(t(1-Dtmp)%*%diag(cctfit$BUGSoutput$sims.list[["g"]][samp,])))^(t(cctfit$data[,])*cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]))*(t(1-Dtmp)%*%diag(cctfit$BUGSoutput$sims.list[["g"]][samp,]))^(t(cctfit$data[,])*(1-cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]))*(t(1-Dtmp)%*%diag(1-cctfit$BUGSoutput$sims.list[["g"]][samp,]))^((1-t(cctfit$data[,]))*cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])*(t(Dtmp)+t(1-Dtmp)%*%diag(1-cctfit$BUGSoutput$sims.list[["g"]][samp,]))^((1-t(cctfit$data[,]))*(1-cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) )
if(cctfit$mval==TRUE){Liktmp[datob$thena] <- 1}
cctfit$LogLik[samp] <- sum(log(Liktmp))
}
cctfit$BUGSoutput$sims.list$deviance <- array(-2*(cctfit$LogLik),c(cctfit$BUGSoutput$n.sims,1))
}
cctfit$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="deviance")]]] <- array(cctfit$BUGSoutput$sims.list$deviance,c(cctfit$BUGSoutput$n.keep,cctfit$BUGSoutput$n.chains))
cctfit$BUGSoutput$sims.matrix[,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="deviance")]]] <- cctfit$BUGSoutput$sims.list$deviance[,1]
if(sum(cctfit$BUGSoutput$sims.list$deviance==Inf) >0){
cctfit$BUGSoutput$mean$deviance <- mean(cctfit$BUGSoutput$sims.list$deviance[cctfit$BUGSoutput$sims.list$deviance!=Inf,1],na.rm=TRUE) #Dbar, also known as deviance
cctfit$BUGSoutput$pD <- var(cctfit$BUGSoutput$sims.list$deviance[cctfit$BUGSoutput$sims.list$deviance!=Inf,1],na.rm=TRUE)/2 #pD, variance of the deviance, divided by 2
cctfit$BUGSoutput$DIC <- cctfit$BUGSoutput$mean$deviance + cctfit$BUGSoutput$pD
}else{
cctfit$BUGSoutput$mean$deviance <- mean(cctfit$BUGSoutput$sims.list$deviance) #Dbar, also known as deviance
cctfit$BUGSoutput$pD <- var(cctfit$BUGSoutput$sims.list$deviance[,1])/2 #pD, variance of the deviance, divided by 2
cctfit$BUGSoutput$DIC <- cctfit$BUGSoutput$mean$deviance + cctfit$BUGSoutput$pD
}
}
if(cctfit$whmodel=="LTRM"){
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list$T)) < 3){
cctfit$BUGSoutput$sims.list$T <- array(cctfit$BUGSoutput$sims.list[["T"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(length(dim(cctfit$BUGSoutput$sims.list$gam))<3){cctfit$BUGSoutput$sims.list$gam <- array(cctfit$BUGSoutput$sims.list[["gam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$C-1,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
}
}
storefulllik <- 0
if(storefulllik==1){
cctfit$BUGSoutput$sims.list$tau <- array(-1,c(cctfit$BUGSoutput$n.sims,cctfit$n,cctfit$m))
cctfit$ppdelta <- array(NA, c(cctfit$n,cctfit$C-1,cctfit$BUGSoutput$n.sims))
cctfit$ppdeltafull <- array(NA, c(cctfit$n,cctfit$C+1,cctfit$BUGSoutput$n.sims))
cctfit$ppdeltafull[,1,] <- -1000000; cctfit$ppdeltafull[,cctfit$C+1,] <- 1000000
cctfit$Lik <- array(NA, c(cctfit$n,cctfit$m,cctfit$BUGSoutput$n.sims));
for(samp in 1:cctfit$BUGSoutput$n.sims){
cctfit$BUGSoutput$sims.list[["tau"]][samp,,] <- cctfit$BUGSoutput$sims.list[["E"]][samp,]*t(1/cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])
cctfit$ppdeltafull[,2:(cctfit$C),samp] <- cctfit$BUGSoutput$sims.list[["a"]][samp,]*t(cctfit$BUGSoutput$sims.list[["gam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])+cctfit$BUGSoutput$sims.list[["b"]][samp,]
for(i in 1:cctfit$n){
cctfit$Lik[i,,samp] <- pnorm(cctfit$ppdeltafull[i,cctfit$data[i,]+1,samp] ,cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,i]],cctfit$BUGSoutput$sims.list[["tau"]][samp,i,]^-.5)-pnorm(cctfit$ppdeltafull[i,cctfit$data[i,],samp] ,cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,i]],cctfit$BUGSoutput$sims.list[["tau"]][samp,i,]^-.5)
if(cctfit$mval==TRUE){cctfit$Lik[cbind(datob$thena,samp)] <- 1}
}
}
if(cctfit$C==2){cctfit$Lik[cctfit$Lik==0] <- 0.001}
cctfit$BUGSoutput$sims.list$deviance <- array(-2*apply(log(cctfit$Lik),3,sum),c(cctfit$BUGSoutput$n.sims,1))
}else{
cctfit$LogLik <- array(NA, c(cctfit$BUGSoutput$n.sims));
Liktmp <- array(NA, c(cctfit$n,cctfit$m))
deltatmp <- array(NA, c(cctfit$n,cctfit$C+1))
deltatmp[,1] <- -100000; deltatmp[,cctfit$C+1] <- 1000000
for(samp in 1:cctfit$BUGSoutput$n.sims){
tautmp <- (cctfit$BUGSoutput$sims.list[["E"]][samp,]*t(exp(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])))^-2
deltatmp[,2:(cctfit$C)] <- cctfit$BUGSoutput$sims.list[["a"]][samp,]*t(cctfit$BUGSoutput$sims.list[["gam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])+cctfit$BUGSoutput$sims.list[["b"]][samp,]
for(i in 1:cctfit$n){
Liktmp[i,] <- pnorm(deltatmp[i,cctfit$data[i,]+1],cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,i]],tautmp[i,]^-.5)-pnorm(deltatmp[i,cctfit$data[i,]],cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,i]],tautmp[i,]^-.5)
if(cctfit$mval==TRUE){cctfit$Lik[datob$thena] <- 1}
}
if(cctfit$C==2){Liktmp[Liktmp==0] <- 0.001}
cctfit$LogLik[samp] <- sum(log(Liktmp))
}
cctfit$BUGSoutput$sims.list$deviance <- array(-2*(cctfit$LogLik),c(cctfit$BUGSoutput$n.sims,1))
}
cctfit$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="deviance")]]] <- array(cctfit$BUGSoutput$sims.list$deviance,c(cctfit$BUGSoutput$n.keep,cctfit$BUGSoutput$n.chains))
cctfit$BUGSoutput$sims.matrix[,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="deviance")]]] <- cctfit$BUGSoutput$sims.list$deviance[,1]
if(sum(cctfit$BUGSoutput$sims.list$deviance==Inf) >0){
cctfit$BUGSoutput$mean$deviance <- mean(cctfit$BUGSoutput$sims.list$deviance[cctfit$BUGSoutput$sims.list$deviance!=Inf,1],na.rm=TRUE) #Dbar, also known as deviance
cctfit$BUGSoutput$pD <- var(cctfit$BUGSoutput$sims.list$deviance[cctfit$BUGSoutput$sims.list$deviance!=Inf,1],na.rm=TRUE)/2 #pD, variance of the deviance, divided by 2
cctfit$BUGSoutput$DIC <- cctfit$BUGSoutput$mean$deviance + cctfit$BUGSoutput$pD
}else{
cctfit$BUGSoutput$mean$deviance <- mean(cctfit$BUGSoutput$sims.list$deviance) #Dbar, also known as deviance
cctfit$BUGSoutput$pD <- var(cctfit$BUGSoutput$sims.list$deviance[,1])/2 #pD, variance of the deviance, divided by 2
cctfit$BUGSoutput$DIC <- cctfit$BUGSoutput$mean$deviance + cctfit$BUGSoutput$pD
}
}
if(cctfit$whmodel=="CRM"){
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list$T)) < 3){
cctfit$BUGSoutput$sims.list$T <- array(cctfit$BUGSoutput$sims.list[["T"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(0,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(0,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
}
}
storefulllik <- 0
if(storefulllik==1){
cctfit$BUGSoutput$sims.list$tau <- array(-1,c(cctfit$BUGSoutput$n.sims,cctfit$n,cctfit$m))
cctfit$Lik <- array(NA, c(cctfit$n,cctfit$m,cctfit$BUGSoutput$n.sims));
for(samp in 1:cctfit$BUGSoutput$n.sims){
cctfit$BUGSoutput$sims.list[["tau"]][samp,,] <- (cctfit$BUGSoutput$sims.list[["E"]][samp,]*t(exp(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])))^-2
cctfit$Lik[,,samp] <- dnorm(cctfit$data,mean=(cctfit$BUGSoutput$sims.list[["a"]][samp,]*t(cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]))+array(cctfit$BUGSoutput$sims.list[["b"]][samp,],c(cctfit$n,cctfit$m)),sd=cctfit$BUGSoutput$sims.list[["a"]][samp,]*(cctfit$BUGSoutput$sims.list[["tau"]][samp,,]^-.5))
if(cctfit$mval==TRUE){cctfit$Lik[cbind(datob$thena,samp)] <- 1}
}
cctfit$BUGSoutput$sims.list$deviance <- array(-2*apply(log(cctfit$Lik),3,sum),c(cctfit$BUGSoutput$n.sims,1))
}else{
cctfit$LogLik <- array(NA, c(cctfit$BUGSoutput$n.sims));
for(samp in 1:cctfit$BUGSoutput$n.sims){
tautmp <- (cctfit$BUGSoutput$sims.list[["E"]][samp,]*t(exp(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])))^-2
Liktmp <- dnorm(cctfit$data,mean=(cctfit$BUGSoutput$sims.list[["a"]][samp,]*t(cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]))+array(cctfit$BUGSoutput$sims.list[["b"]][samp,],c(cctfit$n,cctfit$m)),sd=cctfit$BUGSoutput$sims.list[["a"]][samp,]*(tautmp^-.5))
if(cctfit$mval==TRUE){Liktmp[datob$thena] <- 1}
cctfit$LogLik[samp] <- sum(log(Liktmp))
}
cctfit$BUGSoutput$sims.list$deviance <- array(-2*(cctfit$LogLik),c(cctfit$BUGSoutput$n.sims,1))
}
cctfit$BUGSoutput$sims.array[,,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="deviance")]]] <- array(cctfit$BUGSoutput$sims.list$deviance,c(cctfit$BUGSoutput$n.keep,cctfit$BUGSoutput$n.chains))
cctfit$BUGSoutput$sims.matrix[,cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="deviance")]]] <- cctfit$BUGSoutput$sims.list$deviance[,1]
if(sum(cctfit$BUGSoutput$sims.list$deviance==Inf) >0){
cctfit$BUGSoutput$mean$deviance <- mean(cctfit$BUGSoutput$sims.list$deviance[cctfit$BUGSoutput$sims.list$deviance!=Inf,1],na.rm=TRUE) #Dbar, also known as deviance
cctfit$BUGSoutput$pD <- var(cctfit$BUGSoutput$sims.list$deviance[cctfit$BUGSoutput$sims.list$deviance!=Inf,1],na.rm=TRUE)/2 #pD, variance of the deviance, divided by 2
cctfit$BUGSoutput$DIC <- cctfit$BUGSoutput$mean$deviance + cctfit$BUGSoutput$pD
}else{
cctfit$BUGSoutput$mean$deviance <- mean(cctfit$BUGSoutput$sims.list$deviance) #Dbar, also known as deviance
cctfit$BUGSoutput$pD <- var(cctfit$BUGSoutput$sims.list$deviance[,1])/2 #pD, variance of the deviance, divided by 2
cctfit$BUGSoutput$DIC <- cctfit$BUGSoutput$mean$deviance + cctfit$BUGSoutput$pD
}
}
message(paste("DIC : ",round(cctfit$BUGSoutput$DIC,2)," pD : ",round(cctfit$BUGSoutput$pD,2),sep=""))
if(gui==TRUE){
guidat <- get("guidat", pkg_globals)
tkconfigure(guidat$plotresults.but, state="normal")
tkconfigure(guidat$doppc.but, state="normal")
tkconfigure(guidat$exportresults.but, state="normal")
tkconfigure(guidat$printfit.but, state="normal")
tkconfigure(guidat$summary.but, state="normal")
tkconfigure(guidat$sendconsole.but, state="normal")
tkconfigure(guidat$memb.but, state="normal")
tkconfigure(guidat$mvest.but, state="normal")
#if(guidat$mval == TRUE){tkconfigure(guidat$mvest.but, state="normal")}
tkconfigure(guidat$traceplotdiscrete.but, state="normal")
tkconfigure(guidat$traceplotall.but, state="normal")
cctfit$guidat <- guidat
assign("guidat", guidat, pkg_globals)
class(cctfit) <- c("cct",class(cctfit))
return(cctfit)
}else{
class(cctfit) <- c("cct",class(cctfit))
return(cctfit)
}
}
######################
#Function for the 'Plot Results' Button
#- Creates a sophisticated plot of the posterior results, which includes
# the posterior means of each parameters and their highest density intervals (HDIs, see Kruschke 2011)
#- Denotes a different symbol for the parameters pertaining to each culture
#- This function is also called during the file export, and .eps and .jpeg's of the plot are saved
######################
plotresultsfuncbutton <- function() {
guidat <- get("guidat", pkg_globals);
plotresultsfunc(cctfit=get(guidat$varname, pkg_globals),gui=TRUE)
}
plotresultsfunc <- function(cctfit,saveplots=0,savedir="",gui=FALSE) {
hdi <- function(sampleVec, credMass=0.95){
sortedPts = sort(sampleVec)
ciIdxInc = floor(credMass * length( sortedPts) )
nCIs = length( sortedPts) - ciIdxInc
ciwidth = rep(0, nCIs)
for(i in 1:nCIs){
ciwidth[i] = sortedPts[i + ciIdxInc] - sortedPts[i]}
HDImin = sortedPts[which.min(ciwidth)]
HDImax = sortedPts[which.min(ciwidth)+ciIdxInc]
HDIlim = c(HDImin,HDImax)
return(HDIlim)
}
Mode <- function(x) {ux <- unique(x); ux[which.max(tabulate(match(x, ux)))] }
cctfit$respmem <- apply(cctfit$BUGSoutput$sims.list$Om[,],2,Mode)
if(saveplots==1){jpeg(file.path(gsub(".Rdata","results.jpg",savedir)),width = 6, height = 6, units = "in", pointsize = 12,quality=100,res=400)}
if(saveplots==2){postscript(file=file.path(gsub(".Rdata","results.eps",savedir)), onefile=FALSE, horizontal=FALSE, width = 6, height = 6, paper="special", family="Times")}
if(cctfit$whmodel=="GCM"){
par(oma=c(0,0,0,0),mar=c(4,4,3,1),mgp=c(2.25,.75,0),mfrow=c(2,2))
sym <- c(21,22, 23, 24, 25, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14) # possible symbols:
bgcol <- c("black",NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA)
#if(cctfit$V==1){bgcol <- c(NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA)}
if(cctfit$V==1){
if(length(dim(cctfit$BUGSoutput$sims.list[["Z"]])) < 3){
cctfit$BUGSoutput$sims.list[["Z"]] <- array(cctfit$BUGSoutput$sims.list[["Z"]],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Truth (",Z[vk],")")),xlab="Item",ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=21,bg="white")
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["Z"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["Z"]][,,i],c(2),mean),xlab=expression(paste("Item Truth (",Z[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}}else{
plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Truth (",Z[vk],") Per Culture")),xlab="Item",ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=21,bg="white")
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["Z"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["Z"]][,,i],c(2),mean),xlab=expression(paste("Item Truth (",Z[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}
}
if(cctfit$itemdiff==TRUE){
if(cctfit$V==1){
if(length(dim(cctfit$BUGSoutput$sims.list[["lam"]])) < 3){
cctfit$BUGSoutput$sims.list[["lam"]] <- array(cctfit$BUGSoutput$sims.list[["lam"]],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
hditmp <- apply(cctfit$BUGSoutput$sims.list[["lam"]][,,1],2,hdi)
plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],")")),xlab="Item",ylim=c(0,1),ylab="Posterior Mean Value",las=1,pch=21,bg="white")
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["lam"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["lam"]][,,i],c(2),mean),xlab=expression(paste("Item Difficulty (",lambda[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}
segments(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,])
arrows(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,],code=3,angle=90,length=.025)
}else{plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],") Per Culture")),xlab="Item",ylim=c(0,1),ylab="Posterior Mean Value",las=1,pch=21)
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["lam"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["lam"]][,,i],c(2),mean),xlab=expression(paste("Item Difficulty (",lambda[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}
}
}else{
plot(c(1:cctfit$m),rep(.5,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],")")),xlab="Item",ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[1],bg="white",col="grey")
points(c(par("usr")[1],par("usr")[2]),c(par("usr")[3],par("usr")[4]),type="l",col="grey")
points(c(par("usr")[1],par("usr")[2]),c(par("usr")[4],par("usr")[3]),type="l",col="grey")
}
plot(cctfit$BUGSoutput$mean$th,main=expression(paste("Respondent Competency (",theta[i],")")),xlab="Respondent",ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[cctfit$respmem],bg=bgcol[cctfit$respmem])
hditmp <- apply(cctfit$BUGSoutput$sims.list$th,2,hdi)
segments(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,])
arrows(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,],code=3,angle=90,length=.025)
plot(cctfit$BUGSoutput$mean$g,main=expression(paste("Respondent Guessing Bias (",g[i],")")),xlab="Respondent",ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[cctfit$respmem],bg=bgcol[cctfit$respmem])
hditmp <- apply(cctfit$BUGSoutput$sims.list$g,2,hdi)
segments(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,])
arrows(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,],code=3,angle=90,length=.025)
}
if(cctfit$whmodel=="LTRM"){
invlogit <- function(x){x <- 1 / (1 + exp(-x)); return(x)}
par(oma=c(0,0,0,0),mar=c(4,4,3,1),mgp=c(2.25,.75,0),mfrow=c(2,2))
sym <- c(21,22, 23, 24, 25, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14) # possible symbols:
bgcol <- c("black",NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA)
if(cctfit$C==2){useinvlogit <- TRUE}else{useinvlogit <- FALSE}
if(useinvlogit==TRUE){
#tmp1 <- cctfit$BUGSoutput$sims.list[["T"]]; cctfit$BUGSoutput$sims.list[["T"]] <- invlogit(cctfit$BUGSoutput$sims.list[["T"]])
#tmp2 <- cctfit$BUGSoutput$sims.list[["gam"]]; cctfit$BUGSoutput$sims.list[["gam"]] <- invlogit(cctfit$BUGSoutput$sims.list[["gam"]])
#tmp3 <- cctfit$BUGSoutput$sims.list[["b"]]; cctfit$BUGSoutput$sims.list[["b"]] <- invlogit(cctfit$BUGSoutput$sims.list[["b"]])
tmp1 <- cctfit$BUGSoutput$sims.list[["T"]]; cctfit$BUGSoutput$sims.list[["T"]] <- invlogit(cctfit$BUGSoutput$sims.list[["T"]])
tmp2 <- cctfit$BUGSoutput$sims.list[["gam"]]; cctfit$BUGSoutput$sims.list[["gam"]] <- invlogit(cctfit$BUGSoutput$sims.list[["gam"]])
tmp3 <- cctfit$BUGSoutput$sims.list[["b"]]; cctfit$BUGSoutput$sims.list[["b"]] <- invlogit(cctfit$BUGSoutput$sims.list[["b"]])
}
if(cctfit$V==1){
newm <- ceiling(cctfit$m*1.092)
if(length(dim(cctfit$BUGSoutput$sims.list[["T"]])) <3){
cctfit$BUGSoutput$sims.list[["T"]] <- array(cctfit$BUGSoutput$sims.list[["T"]],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(length(dim(cctfit$BUGSoutput$sims.list[["gam"]])) <3){
cctfit$BUGSoutput$sims.list[["gam"]] <- array(cctfit$BUGSoutput$sims.list[["gam"]],c(cctfit$BUGSoutput$n.sims,cctfit$C-1,1))
}
hditmp <- apply(cctfit$BUGSoutput$sims.list[["T"]][,,1],2,hdi)
if(useinvlogit==TRUE){
plot(1:newm,rep(NA,newm),main=expression(paste("Item Truth (",T[vk],") and Thresholds (",gamma[vc],")")),xlab="Item",ylim=c(0,1),ylab="Posterior Mean Invlogit Value",las=1,pch=21,bg="white",axes=FALSE)
}else{plot(1:newm,rep(NA,newm),main=expression(paste("Item Truth (",T[vk],") and Thresholds (",gamma[vc],")")),xlab="Item",ylim=c(min(hditmp,min(apply(cctfit$BUGSoutput$sims.list[["gam"]],c(2,3),mean))),max(hditmp,max(apply(cctfit$BUGSoutput$sims.list[["gam"]],c(2,3),mean)))),ylab="Posterior Mean Value",las=1,pch=21,bg="white",axes=FALSE)
}
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["T"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["T"]][,,i],c(2),mean),xlab=expression(paste("Item Truth (",T[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
if(cctfit$C==2){
text(newm,mean(cctfit$BUGSoutput$sims.list[["gam"]][,,i]),labels=sapply(c(1:(cctfit$C-1)),function(x) as.expression(substitute(list(gamma[x]),list(x=x)))))
segments(1,mean(cctfit$BUGSoutput$sims.list[["gam"]][,,i]),max(cctfit$m+1,newm-2),mean(cctfit$BUGSoutput$sims.list[["gam"]][,,i]),lty=2);
}
else{
text(newm,apply(cctfit$BUGSoutput$sims.list[["gam"]][,,i],c(2),mean),labels=sapply(c(1:(cctfit$C-1)),function(x) as.expression(substitute(list(gamma[x]),list(x=x)))))
segments(1,apply(cctfit$BUGSoutput$sims.list[["gam"]][,,i],c(2),mean),max(cctfit$m+1,newm-2),apply(cctfit$BUGSoutput$sims.list[["gam"]][,,i],c(2),mean),lty=2);
}
segments(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,])
arrows(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,],code=3,angle=90,length=.025)
box()
axis(2, labels = TRUE,las=1)
axis(side = 1,labels=TRUE)
axis(side = 1, at = newm, labels = expression(gamma[c]) )
}}else{
newm <- ceiling(cctfit$m*1.14)
if(cctfit$C==2){
if(useinvlogit==TRUE){
plot(1:newm,rep(NA,newm),main=expression(paste("Item Truth (",T[vk],") and Thresholds (",gamma[vc],") Per Culture")),xlab="Item",ylim=c(0,1),ylab="Posterior Mean Value",las=1,pch=21,bg="white",axes=FALSE)
}else{plot(1:newm,rep(NA,newm),main=expression(paste("Item Truth (",T[vk],") and Thresholds (",gamma[vc],") Per Culture")),xlab="Item",ylim=c(min(min(apply(cctfit$BUGSoutput$sims.list[["T"]],c(2,3),mean))
,min(apply(cctfit$BUGSoutput$sims.list[["gam"]],c(3),mean))),max(max(apply(cctfit$BUGSoutput$sims.list[["T"]],c(2,3),mean))
,max(apply(cctfit$BUGSoutput$sims.list[["gam"]],c(3),mean)))),ylab="Posterior Mean Value",las=1,pch=21,bg="white",axes=FALSE)
}
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["T"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["T"]][,,i],c(2),mean),xlab=expression(paste("Item Truth (",T[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
text(cctfit$m+(((newm-cctfit$m)/dim(cctfit$BUGSoutput$sims.list[["T"]])[3])*i),mean(cctfit$BUGSoutput$sims.list[["gam"]][,,i]),labels=sapply(c(1:(cctfit$C-1)),function(x) as.expression(substitute(list(gamma[x]),list(x=x)))))
}
}else{
if(useinvlogit==TRUE){
plot(1:newm,rep(NA,newm),main=expression(paste("Item Truth (",T[vk],") and Thresholds (",gamma[vc],") Per Culture")),xlab="Item",ylim=c(0,1),ylab="Posterior Mean Value",las=1,pch=21,bg="white",axes=FALSE)
}else{
plot(1:newm,rep(NA,newm),main=expression(paste("Item Truth (",T[vk],") and Thresholds (",gamma[vc],") Per Culture")),xlab="Item",ylim=c(min(min(apply(cctfit$BUGSoutput$sims.list[["T"]],c(2,3),mean))
,min(apply(cctfit$BUGSoutput$sims.list[["gam"]][,,],c(2,3),mean))),max(max(apply(cctfit$BUGSoutput$sims.list[["T"]],c(2,3),mean))
,max(apply(cctfit$BUGSoutput$sims.list[["gam"]][,,],c(2,3),mean)))),ylab="Posterior Mean Value",las=1,pch=21,bg="white",axes=FALSE)
}
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["T"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["T"]][,,i],c(2),mean),xlab=expression(paste("Item Truth (",T[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
text(cctfit$m+(((newm-cctfit$m)/dim(cctfit$BUGSoutput$sims.list[["T"]])[3])*i),apply(cctfit$BUGSoutput$sims.list[["gam"]][,,i],c(2),mean),labels=sapply(c(1:(cctfit$C-1)),function(x) as.expression(substitute(list(gamma[x]),list(x=x)))))
}
}
box()
axis(2, labels = TRUE,las=1)
axis(side=1,at=axTicks(side=1)[axTicks(side=1)<= cctfit$m])
axis(side = 1, at = cctfit$m+(((newm-cctfit$m)/dim(cctfit$BUGSoutput$sims.list[["T"]])[3])*(1:2)),
labels = sapply(1:2,function(x) as.expression(substitute(list(gamma[x*c]),list(x=x)))) )
}
if(cctfit$itemdiff==TRUE){
if(cctfit$V==1){
if(length(dim(cctfit$BUGSoutput$sims.list[["lam"]])) < 3){
cctfit$BUGSoutput$sims.list[["lam"]] <- array(cctfit$BUGSoutput$sims.list[["lam"]],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
hditmp <- apply(cctfit$BUGSoutput$sims.list[["lam"]][,,1],2,hdi)
plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],")")),xlab="Item",ylim=c(min(hditmp),max(hditmp)),ylab="Posterior Mean Log Value",las=1,pch=21,bg="white")
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["lam"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["lam"]][,,i],c(2),mean),xlab=expression(paste("Item Difficulty (",lambda[vk],") Per Cluster")),ylab="Posterior Mean Log Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}
segments(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,])
arrows(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,],code=3,angle=90,length=.025)
}else{plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],") Per Culture")),xlab="Item",ylim=c(min(apply(cctfit$BUGSoutput$sims.list[["lam"]],c(2,3),mean)),max(apply(cctfit$BUGSoutput$sims.list[["lam"]],c(2,3),mean))),ylab="Posterior Mean Value",las=1,pch=21,bg="white")
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["lam"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["lam"]][,,i],c(2),mean),xlab=expression(paste("Item Difficulty (",lambda[vk],") Per Cluster")),ylab="Posterior Mean Log Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}
}
}else{
plot(c(1:cctfit$m),rep(.5,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],")")),xlab="Item",ylab="Posterior Mean Log Value",las=1,ylim=c(0,1),pch=sym[1],bg="white",col="grey")
points(c(par("usr")[1],par("usr")[2]),c(par("usr")[3],par("usr")[4]),type="l",col="grey")
points(c(par("usr")[1],par("usr")[2]),c(par("usr")[4],par("usr")[3]),type="l",col="grey")
}
hditmp <- apply(cctfit$BUGSoutput$sims.list$E,2,hdi)
plot(cctfit$BUGSoutput$mean$E,main=expression(paste("Respondent Standard Error (",E[i],")")),xlab="Respondent",ylab="Posterior Mean Value",las=1,ylim=c(0,max(hditmp)),pch=sym[cctfit$respmem],bg=bgcol[cctfit$respmem])
segments(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,])
arrows(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,],code=3,angle=90,length=.025)
if(useinvlogit==TRUE){
plot(invlogit(cctfit$BUGSoutput$mean$b)-.5,main=expression(paste("Respondent Shift Bias (",b[i],")")),xlab="Respondent",ylab="Posterior Mean Value",las=1,ylim=c(-.5,.5),pch=sym[cctfit$respmem],bg=bgcol[cctfit$respmem])
hditmp <- apply(cctfit$BUGSoutput$sims.list$b-.5,2,hdi) # because this is invprobit transformed still
segments(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,])
arrows(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,],code=3,angle=90,length=.025)
}else{
loga <- apply(log(cctfit$BUGSoutput$sims.list[["a"]]),2,mean)
plot(-5000, -5000, main=expression(paste("Category Usage Bias (",a[i]," and ",b[i],")")),xlim=c(min(-1.6,-abs(cctfit$BUGSoutput$mean$b)),max(1.6,cctfit$BUGSoutput$mean$b)), ylim=c(min(-1,loga),max(1,loga)),xlab=expression(paste("Respondent Shift Bias (",b[i],")")),
ylab=expression(paste("Log Respondent Scale Bias (",a[i],")")),las=1,pch=21)
points(cbind(cctfit$BUGSoutput$mean$b,loga),xlab="Respondent",ylab="Posterior Mean Value",las=1,ylim=c(0,max(hditmp)),pch=sym[cctfit$respmem],bg=bgcol[cctfit$respmem])
segments(.625*par("usr")[1],0,.625*par("usr")[2],0)
segments(0,.725*par("usr")[3],0,.725*par("usr")[4])
text(0,.875*par("usr")[3],"Middle Categories",cex=.8)
text(0,.875*par("usr")[4],"Outer Categories",cex=.8)
text(.775*par("usr")[1],0,"Left \n Categories",cex=.8)
text(.775*par("usr")[2],0,"Right \n Categories",cex=.8)
}
if(useinvlogit==TRUE){
cctfit$BUGSoutput$sims.list[["T"]] <- tmp1
cctfit$BUGSoutput$sims.list[["gam"]] <- tmp2
cctfit$BUGSoutput$sims.list[["b"]] <- tmp3
}
}
if(cctfit$whmodel=="CRM"){
par(oma=c(0,0,0,0),mar=c(4,4,3,1),mgp=c(2.25,.75,0),mfrow=c(2,2))
sym <- c(21,22, 23, 24, 25, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14) # possible symbols:
bgcol <- c("black",NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA)
if(cctfit$V==1){
if(length(dim(cctfit$BUGSoutput$sims.list[["T"]])) < 3){
cctfit$BUGSoutput$sims.list[["T"]] <- array(cctfit$BUGSoutput$sims.list[["T"]],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
hditmp <- apply(cctfit$BUGSoutput$sims.list[["T"]][,,1],2,hdi)
plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Truth (",T[vk],")")),xlab="Item",ylim=c(min(hditmp),max(hditmp)),ylab="Posterior Mean Value",las=1,pch=21,bg="white")
}else{plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Truth (",T[vk],") Per Culture")),xlab="Item",ylim=c(min(apply(cctfit$BUGSoutput$sims.list[["T"]],c(2,3),mean)),max(apply(cctfit$BUGSoutput$sims.list[["T"]],c(2,3),mean))),ylab="Posterior Mean Value",las=1,pch=21,bg="white")}
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["T"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["T"]][,,i],c(2),mean),xlab=expression(paste("Item Truth (",T[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}
if(cctfit$V==1){
segments(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,])
arrows(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,],code=3,angle=90,length=.025)
}
if(cctfit$itemdiff==TRUE){
if(cctfit$V==1){
if(length(dim(cctfit$BUGSoutput$sims.list[["lam"]])) < 3){
cctfit$BUGSoutput$sims.list[["lam"]] <- array(cctfit$BUGSoutput$sims.list[["lam"]],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
hditmp <- apply(cctfit$BUGSoutput$sims.list[["lam"]][,,1],2,hdi)
plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],")")),xlab="Item",ylim=c(min(hditmp),max(hditmp)),ylab="Posterior Mean Value",las=1,pch=21,bg="white")
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["lam"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["lam"]][,,i],c(2),mean),xlab=expression(paste("Item Difficulty (",lambda[vk],") Per Cluster")),ylab="Posterior Mean Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}
segments(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,])
arrows(1:cctfit$m,hditmp[1,], 1:cctfit$m, hditmp[2,],code=3,angle=90,length=.025)
}else{plot(1:cctfit$m,rep(NA,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],") Per Culture")),xlab="Item",ylim=c(min(apply(cctfit$BUGSoutput$sims.list[["lam"]],c(2,3),mean)),max(apply(cctfit$BUGSoutput$sims.list[["lam"]],c(2,3),mean))),ylab="Posterior Mean Log Value",las=1,pch=21,bg="white")
for(i in 1:dim(cctfit$BUGSoutput$sims.list[["lam"]])[3]){
points(apply(cctfit$BUGSoutput$sims.list[["lam"]][,,i],c(2),mean),xlab=expression(paste("Item Difficulty (",lambda[vk],") Per Cluster")),ylab="Posterior Mean Log Value",las=1,ylim=c(0,1),pch=sym[i],bg=bgcol[i])
}
}
}else{
plot(c(1:cctfit$m),rep(.5,cctfit$m),main=expression(paste("Item Difficulty (",lambda[vk],")")),xlab="Item",ylab="Posterior Mean Log Value",las=1,ylim=c(0,1),pch=sym[1],bg="white",col="grey")
points(c(par("usr")[1],par("usr")[2]),c(par("usr")[3],par("usr")[4]),type="l",col="grey")
points(c(par("usr")[1],par("usr")[2]),c(par("usr")[4],par("usr")[3]),type="l",col="grey")
}
hditmp <- apply(cctfit$BUGSoutput$sims.list$E,2,hdi)
plot(cctfit$BUGSoutput$mean$E,main=expression(paste("Respondent Standard Error (",E[i],")")),xlab="Respondent",ylab="Posterior Mean Value",las=1,ylim=c(min(hditmp),max(hditmp)),pch=sym[cctfit$respmem],bg=bgcol[cctfit$respmem])
segments(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,])
arrows(1:cctfit$n,hditmp[1,], 1:cctfit$n, hditmp[2,],code=3,angle=90,length=.025)
#text(cctfit$n/4.25,1.3*par("usr")[3],"More Knowledgeable",cex=.8)
#text(cctfit$n/4.25,.9*par("usr")[4],"Less Knowledgeable",cex=.8)
loga <- apply(log(cctfit$BUGSoutput$sims.list[["a"]]),2,mean)
plot(-5000, -5000, main=expression(paste("Category Usage Bias (",a[i]," and ",b[i],")")),xlim=c(min(-1.6,-abs(cctfit$BUGSoutput$mean$b)),max(1.6,cctfit$BUGSoutput$mean$b)), ylim=c(min(-1,loga),max(1,loga)),xlab=expression(paste("Respondent Shift Bias (",b[i],")")),
ylab=expression(paste("Log Respondent Scale Bias (",a[i],")")),las=1,pch=21)
points(cbind(cctfit$BUGSoutput$mean$b,loga),xlab="Respondent",ylab="Posterior Mean Value",las=1,ylim=c(0,max(hditmp)),pch=sym[cctfit$respmem],bg=bgcol[cctfit$respmem])
segments(.625*par("usr")[1],0,.625*par("usr")[2],0)
segments(0,.725*par("usr")[3],0,.725*par("usr")[4])
text(0,.875*par("usr")[3],"Middle Categories",cex=.8)
text(0,.875*par("usr")[4],"Outer Categories",cex=.8)
text(.775*par("usr")[1],0,"Left \n Categories",cex=.8)
text(.775*par("usr")[2],0,"Right \n Categories",cex=.8)
}
if(saveplots==1 || saveplots==2){dev.off()}
saveplots <- 0
}
######################
#Function for the 'Run Checks' Button
#- Calculates the posterior predictive data for the model that was applied
#- Calculates 2 important posterior predictive checks and plots them
#- The VDI check percentiles are reported in the R console, and saved to cctfit$VDIperc
#- Performs factor analysis using fa() and polychoric() (if selected)
#- This function is also called in the file export and saves .eps and .jpegs of the plot
######################
ppcfuncbutton <- function(){
guidat <- get("guidat", pkg_globals)
cctfit <- get(guidat$varname, pkg_globals)
recalc <- FALSE
if(cctfit$whmodel=="LTRM" && cctfit$checksrun==TRUE){
if(cctfit$polycor!=as.logical(as.numeric(tclvalue(guidat$polyvar)))){
recalc <- TRUE
}
}
assign(guidat$varname,
ppcfunc(cctfit=cctfit,gui=TRUE,rerunchecks=recalc,polych=as.logical(as.numeric(tclvalue(guidat$polyvar)))),
pkg_globals
)
}
ppcfunc <- function(cctfit,saveplots=0,savedir="",gui=FALSE,polych=FALSE,rerunchecks=FALSE,doplot=TRUE) {
if(gui==TRUE){guidat <- get("guidat", pkg_globals)}
if(cctfit$checksrun==FALSE || rerunchecks==TRUE){
message("\n ...One moment, calculating posterior predictive checks")
usesubset <- 1
if(usesubset==1){
subsetsize <- min(500,cctfit$BUGSoutput$n.sims)
indices <- sample(cctfit$BUGSoutput$n.sims,min(subsetsize,cctfit$BUGSoutput$n.sims))
if(cctfit$whmodel=="GCM"){
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list$Z)) < 3){
cctfit$BUGSoutput$sims.list$Z <- array(cctfit$BUGSoutput$sims.list[["Z"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(.5,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(.5,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
} }
cctfit$ppY <- array(NA, c(cctfit$n,cctfit$m,subsetsize));
for(samp in indices){
tautmp <- (cctfit$BUGSoutput$sims.list[["th"]][samp,]*t(1-cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) /
( (cctfit$BUGSoutput$sims.list[["th"]][samp,]*t(1-cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) +
((1-cctfit$BUGSoutput$sims.list[["th"]][samp,])*t(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) )
cctfit$ppY[,,which(indices==samp)] <- matrix(rbinom((cctfit$n*cctfit$m),1,
(t(cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])*tautmp ) +
t(t(1-tautmp)%*%diag(cctfit$BUGSoutput$sims.list[["g"]][samp,])) ), cctfit$n,cctfit$m)
}
if(cctfit$mval==TRUE){
for(i in 1:dim(cctfit$datob$thena)[1]){cctfit$data[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2]] <- Mode(cctfit$ppY[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2],])}
cctfit$MVest <- cbind(cctfit$datob$thena,cctfit$data[cctfit$datob$thena])
colnames(cctfit$MVest) <- c("Pers","Item","Resp")
}
cctfit$mean$ppY <- rowMeans(cctfit$ppY[,,],dims=2)
leigv <- 12
options(warn=-3)
ind <- indices
eigv <- matrix(-1,length(ind),leigv)
tmp <- apply(cctfit$ppY,c(1,3),function(x) t(x))
tmp2 <- apply(tmp[,,],3,function(x) cor(x))
tmp3 <- array(tmp2,c(cctfit$n,cctfit$n,subsetsize))
for(i in 1:length(ind)){
suppressMessages(try(eigv[i,] <- fa(tmp3[,,i])$values[1:leigv],silent=TRUE))}
wch <- -which(eigv[,1]==-1);
if(length(wch)==0){cctfit$ppeig <- eigv}else{cctfit$ppeig <- eigv[-which(eigv[,1]==-1),]}
if(sum(apply(cctfit$data,1,function(x) sd(x,na.rm=TRUE))==0) > 0){
tmp <- cctfit$data
if(sum(apply(cctfit$datob$dat,1,function(x) sd(x,na.rm=TRUE))==0)==1){
tmp[which(apply(tmp,1,function(x) sd(x,na.rm=TRUE))==0),1] <- min(tmp[which(apply(tmp,1,function(x) sd(x,na.rm=TRUE))==0),1]+.01,.99)
}else{
tmp[which(apply(tmp,1,function(x) sd(x,na.rm=TRUE))==0),1] <- sapply(apply(tmp[which(apply(tmp,1,function(x) sd(x,na.rm=TRUE))==0),],1,mean),function(x) min(x+.01,.99))
}
cctfit$dateig <- suppressMessages(fa(cor(t(tmp)))$values[1:leigv])
}else{
cctfit$dateig <- suppressMessages(fa(cor(t(cctfit$data)))$values[1:leigv])
}
options(warn=0)
if(cctfit$V==1){
varvec <- matrix(-1,length(ind),dim(cctfit$ppY)[2])
vdi <- matrix(-1,dim(cctfit$ppY)[3],1)
for(i in 1:length(ind)){
varvec[i,] <- apply(cctfit$ppY[,,i],2,var)
}
vdi <- apply(varvec,1,var)
cctfit$ppVDI <- vdi
cctfit$datVDI <- var(apply(cctfit$data,2,var))
}
options(warn=-3)
if(cctfit$V>1){
varvec <- array(NA,c(length(ind),dim(cctfit$ppY)[2],cctfit$V))
vdi <- matrix(NA,dim(cctfit$ppY)[3],cctfit$V)
cctfit$datVDI <- array(-1,c(1,cctfit$V))
for(v in 1:cctfit$V){
for(i in 1:length(ind)){
if(sum(cctfit$BUGSoutput$sims.list$Om[ind[i],]==v)>1){
suppressMessages(try(varvec[i,,v] <- apply(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i],2,var),silent=TRUE))
}else{
suppressMessages(try(varvec[i,,v] <- var(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i]),silent=TRUE))
}
}
if(sum(cctfit$respmem==v)>1){
cctfit$datVDI[v] <- var(apply(cctfit$data[cctfit$respmem==v,],2,var))
}else{
cctfit$datVDI[v] <- var(cctfit$data[cctfit$respmem==v,])
}
}
vdi <- apply(varvec,c(1,3),var)
cctfit$ppVDI <- vdi
options(warn=0)
if(sum(apply(cctfit$ppVDI,2,function(x) all(x==0,na.rm=TRUE)))>=1){
for(i in which(apply(cctfit$ppVDI,2,function(x) all(x==0)))){
cctfit$ppVDI[,i] <- NA
}
}
for(v in 1:dim(cctfit$ppVDI)[2]){
if(identical(unique(cctfit$ppVDI[,v]),c(NA,0)) || identical(unique(cctfit$ppVDI[,v]),c(0,NA))){cctfit$ppVDI[,v] <- NA}
}
}
rm(vdi, varvec)
rm(eigv,leigv,tmp,tmp2,tmp3,ind);
cctfit$checksrun <- TRUE
}
if(cctfit$whmodel=="LTRM"){
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list[["T"]])) < 3){
cctfit$BUGSoutput$sims.list$T <- array(cctfit$BUGSoutput$sims.list[["T"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(length(dim(cctfit$BUGSoutput$sims.list[["gam"]])) < 3){
cctfit$BUGSoutput$sims.list$gam <- array(cctfit$BUGSoutput$sims.list[["gam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$C-1,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
}
}
cctfit$ppY <- array(NA, c(cctfit$n,cctfit$m,subsetsize));
cctfit$ppX <- array(NA, c(cctfit$n,cctfit$m,subsetsize));
for(samp in indices){
tautmp <- (cctfit$BUGSoutput$sims.list[["E"]][samp,]*t(exp(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])))^-2
cctfit$ppX[,,which(indices==samp)] <- matrix(
rnorm((cctfit$n*cctfit$m),t(cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]),(tautmp^(-.5))),
cctfit$n,cctfit$m)
deltatmp <- cctfit$BUGSoutput$sims.list[["a"]][samp,]*t(cctfit$BUGSoutput$sims.list[["gam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])+cctfit$BUGSoutput$sims.list[["b"]][samp,]
rc <- which(cctfit$ppX[,,which(indices==samp)] < deltatmp[,1],arr.ind=TRUE)
cctfit$ppY[cbind(rc,array(which(indices==samp),dim(rc)[1]))] <- 1
for(c in 1:(cctfit$C-1)){
rc <- which(cctfit$ppX[,,which(indices==samp)] > deltatmp[,c],arr.ind=TRUE)
cctfit$ppY[cbind(rc,array(which(indices==samp),dim(rc)[1]))] <- (c+1) }
}
cctfit$mean$ppY <- rowMeans(cctfit$ppY[,,],dims=2)
if(cctfit$mval==TRUE){
for(i in 1:dim(cctfit$datob$thena)[1]){cctfit$data[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2]] <- Mode(cctfit$ppY[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2],])}
cctfit$MVest <- cbind(cctfit$datob$thena,cctfit$data[cctfit$datob$thena])
colnames(cctfit$MVest) <- c("Pers","Item","Resp")
}
leigv <- 12
eigv <- matrix(-1,dim(cctfit$ppY)[3],leigv)
options(warn=-3)
ind <- sample(indices,min(cctfit$BUGSoutput$n.sims,250,subsetsize)) #250 is the number of samples
tmp <- apply(cctfit$ppY,c(1,3),function(x) t(x))
if(polych==TRUE){
message(" note: utilizing polychoric correlations (time intensive)");
tmp2 <- apply(tmp[,,],3,function(x) suppressMessages(polychoric(x,global=FALSE))$rho);
tmp2 <- sapply(tmp2,function(x) array(x,c(cctfit$n,cctfit$n))) }else{
tmp2 <- apply(tmp[,,],3,function(x) cor(x))}
tmp3 <- array(tmp2,c(cctfit$n,cctfit$n,length(ind)))
for(i in 1:length(ind)){
suppressMessages(try(eigv[i,] <- fa(tmp3[,,i])$values[1:leigv],silent=TRUE))}
wch <- -which(eigv[,1]==-1);
if(length(wch)==0){cctfit$ppeig <- eigv}else{cctfit$ppeig <- eigv[-which(eigv[,1]==-1),]}
if(polych==TRUE){
cctfit$dateig <- suppressMessages(fa(polychoric(t(cctfit$data),global=FALSE)$rho)$values[1:leigv])}else{
cctfit$dateig <- suppressMessages(fa(cor(t(cctfit$data)))$values[1:leigv])
}
options(warn=0)
if(cctfit$V==1){
varvec <- matrix(NA,length(ind),dim(cctfit$ppY)[2])
vdi <- matrix(NA,dim(cctfit$ppY)[3],1)
for(i in 1:length(ind)){
varvec[i,] <- apply(cctfit$ppY[,,i],2,var)
}
vdi <- apply(varvec,1,var)
cctfit$ppVDI <- vdi
cctfit$datVDI <- var(apply(cctfit$data,2,var))
}
options(warn=-3)
if(cctfit$V>1){
varvec <- array(NA,c(length(ind),dim(cctfit$ppY)[2],cctfit$V))
vdi <- matrix(NA,dim(cctfit$ppY)[3],cctfit$V)
cctfit$datVDI <- array(-1,c(1,cctfit$V))
for(v in 1:cctfit$V){
for(i in 1:length(ind)){
if(sum(cctfit$BUGSoutput$sims.list$Om[ind[i],]==v)>1){
suppressMessages(try(varvec[i,,v] <- apply(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i],2,var),silent=TRUE))
}else{
suppressMessages(try(varvec[i,,v] <- var(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i]),silent=TRUE))
}
}
if(sum(cctfit$respmem==v)>1){
cctfit$datVDI[v] <- var(apply(cctfit$data[cctfit$respmem==v,],2,var))
}else{
cctfit$datVDI[v] <- var(cctfit$data[cctfit$respmem==v,])
}
}
vdi <- apply(varvec,c(1,3),var)
cctfit$ppVDI <- vdi
options(warn=0)
if(sum(apply(cctfit$ppVDI,2,function(x) all(x==0,na.rm=TRUE)))>=1){
for(i in which(apply(cctfit$ppVDI,2,function(x) all(x==0)))){
cctfit$ppVDI[,i] <- NA
}
}
for(v in 1:dim(cctfit$ppVDI)[2]){
if(identical(unique(cctfit$ppVDI[,v]),c(NA,0)) || identical(unique(cctfit$ppVDI[,v]),c(0,NA))){cctfit$ppVDI[,v] <- NA}
}
}
cctfit$polycor <- polych
rm(vdi, varvec)
rm(eigv,leigv,tmp,tmp2,tmp3,ind);
cctfit$checksrun <- TRUE
}
if(cctfit$whmodel=="CRM"){
invlogit <- function(x){x <- 1 / (1 + exp(-x)); return(x)}
logit <- function(x){x <- log(x/(1-x)); return(x)}
usetransform <- 0
version2 <- 1
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list[["T"]])) < 3){
cctfit$BUGSoutput$sims.list$T <- array(cctfit$BUGSoutput$sims.list[["T"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(0,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(0,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
}
}
cctfit$ppY <- array(NA, c(cctfit$n,cctfit$m,subsetsize));
cctfit$ppX <- array(NA, c(cctfit$n,cctfit$m,subsetsize));
for(samp in indices){
tautmp <- (cctfit$BUGSoutput$sims.list[["E"]][samp,]*t(exp(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])))^-2
cctfit$ppY[,,which(indices==samp)] <- matrix(
rnorm((cctfit$n*cctfit$m),(cctfit$BUGSoutput$sims.list[["a"]][samp,]*t(cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]))+matrix(rep(cctfit$BUGSoutput$sims.list[["b"]][samp,],cctfit$m),cctfit$n,cctfit$m),
(cctfit$BUGSoutput$sims.list[["a"]][samp,]*(tautmp^(-.5)))),
cctfit$n,cctfit$m)
cctfit$ppX[,,which(indices==samp)] <- matrix(
rnorm((cctfit$n*cctfit$m),t(cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]),tautmp^(-.5)),c(cctfit$n,cctfit$m))
}
if(usetransform==1){
if(sum(cctfit$ppX < logit(.001)) > 0){cctfit$ppX[cctfit$ppX < logit(.001)] <- logit(.001)}
if(sum(cctfit$ppY < logit(.001)) > 0){cctfit$ppY[cctfit$ppY < logit(.001)] <- logit(.001)}
if(sum(cctfit$ppX > logit(.999)) > 0){cctfit$ppX[cctfit$ppX > logit(.999)] <- logit(.999)}
if(sum(cctfit$ppY > logit(.999)) > 0){cctfit$ppY[cctfit$ppY > logit(.999)] <- logit(.999)}
}
if(usetransform==2){
if(sum(cctfit$ppX < logit(.0001)) > 0){cctfit$ppX[cctfit$ppX < logit(.0001)] <- logit(.0001)}
if(sum(cctfit$ppY < logit(.0001)) > 0){cctfit$ppY[cctfit$ppY < logit(.0001)] <- logit(.0001)}
if(sum(cctfit$ppX > logit(.9999)) > 0){cctfit$ppX[cctfit$ppX > logit(.9999)] <- logit(.9999)}
if(sum(cctfit$ppY > logit(.9999)) > 0){cctfit$ppY[cctfit$ppY > logit(.9999)] <- logit(.9999)}
}
cctfit$mean$ppY <- rowMeans(cctfit$ppY[,,],dims=2)
if(cctfit$mval==TRUE){
for(i in 1:dim(cctfit$datob$thena)[1]){cctfit$data[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2]] <- mean(cctfit$ppY[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2],])}
cctfit$MVest <- cbind(cctfit$datob$thena,cctfit$data[cctfit$datob$thena])
colnames(cctfit$MVest) <- c("Pers","Item","Resp")
}
leigv <- 12
options(warn=-3)
ind <- indices #500 is the number of samples
eigv <- matrix(-1,length(ind),leigv)
tmp <- apply(cctfit$ppY,c(1,3),function(x) t(x))
tmp2 <- apply(tmp[,,],3,function(x) cor(x))
tmp3 <- array(tmp2,c(cctfit$n,cctfit$n,subsetsize))
for(i in 1:length(ind)){
suppressMessages(try(eigv[i,] <- fa(tmp3[,,i])$values[1:leigv],silent=TRUE))}
wch <- -which(eigv[,1]==-1);
if(length(wch)==0){cctfit$ppeig <- eigv}else{cctfit$ppeig <- eigv[-which(eigv[,1]==-1),]}
cctfit$dateig <- suppressMessages(fa(cor(t(cctfit$data)))$values[1:leigv])
options(warn=0)
#VDI Check
usetransform <- 0
if(usetransform==0){
invlogit <- function(x){return(x)}
}
if(cctfit$V==1){
vdi <- matrix(-1,dim(cctfit$ppY)[3],1)
varvec <- array(-1,c(length(ind),dim(cctfit$ppY)[2]))
for(i in 1:length(ind)){
varvec[i,] <- apply(invlogit(cctfit$ppY[,,i]),2,var)
if(version2==1){
varvec[i,] <- apply(invlogit(cctfit$ppX[,,i]),2,var)
}
}
vdi <- apply(varvec,1,var)
cctfit$ppVDI <- apply(varvec,1,var)
cctfit$datVDI <- var(apply(invlogit(cctfit$data),2,var))
if(version2==1){
cctfit$datVDI <- var(apply(invlogit((array(rep(1/cctfit$BUGSoutput$mean$a,times=cctfit$m),c(cctfit$n,cctfit$m))*cctfit$data)-matrix(rep(cctfit$BUGSoutput$mean$b,cctfit$m),cctfit$n,cctfit$m)),2,var))
}
}
if(cctfit$V>1){
varvec <- array(NA,c(length(ind),dim(cctfit$ppY)[2],cctfit$V))
cctfit$datVDI <- array(NA,c(1,cctfit$V))
options(warn=-3)
datest <- t(sapply(1:cctfit$n,function(i) ((1/mean(cctfit$BUGSoutput$sims.list$a[cctfit$BUGSoutput$sims.list$Om[,i]==cctfit$respmem[i],i]))*
cctfit$data[i,])-(mean(cctfit$BUGSoutput$sims.list$b[cctfit$BUGSoutput$sims.list$Om[,i]==cctfit$respmem[i],i]))
))
for(v in 1:cctfit$V){
for(i in 1:length(ind)){
if(sum(cctfit$BUGSoutput$sims.list$Om[ind[i],]==v)>1){
suppressMessages(try(varvec[i,,v] <- apply(invlogit(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i]),2,var),silent=TRUE))
if(version2==1){
suppressMessages(try(varvec[i,,v] <- apply(invlogit(cctfit$ppX[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i]),2,var),silent=TRUE))
}
}else{
suppressMessages(try(varvec[i,,v] <- var(invlogit(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i])),silent=TRUE))
if(version2==1){
suppressMessages(try(varvec[i,,v] <- var(invlogit(cctfit$ppX[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i])),silent=TRUE))
}
}
}
if(sum(cctfit$respmem==v)>1){
cctfit$datVDI[v] <- var(apply(datest[cctfit$respmem==v ,],2,var))
}else{
cctfit$datVDI[v] <- var(datest[cctfit$respmem==v ,])
}
}
options(warn=0)
vdi <- apply(varvec,c(1,3),function(x) var(x,na.rm=TRUE))
cctfit$ppVDI <- vdi
if(sum(apply(cctfit$ppVDI,2,function(x) all(x==0,na.rm=TRUE)))>=1){
for(i in which(apply(cctfit$ppVDI,2,function(x) all(x==0)))){
cctfit$ppVDI[,i] <- NA
}
}
for(v in 1:dim(cctfit$ppVDI)[2]){
if(identical(unique(cctfit$ppVDI[,v]),c(NA,0)) || identical(unique(cctfit$ppVDI[,v]),c(0,NA))){cctfit$ppVDI[,v] <- NA}
}
}
if(usetransform==0){
invlogit <- function(x){x <- 1 / (1 + exp(-x)); return(x)}
}
rm(vdi, varvec)
rm(eigv,leigv,tmp,tmp2,tmp3,ind);
cctfit$checksrun <- TRUE
}
}else{
#########################################
##### Calculate Posterior Predictive Data From All Samples (memory intensive)
#########################################
if(cctfit$whmodel=="GCM"){
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list$Z)) < 3){
cctfit$BUGSoutput$sims.list$Z <- array(cctfit$BUGSoutput$sims.list[["Z"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(.5,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(.5,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
} }
cctfit$ppY <- array(NA, c(cctfit$n,cctfit$m,cctfit$BUGSoutput$n.sims));
cctfit$BUGSoutput$sims.list$tau <- array(-1,c(cctfit$BUGSoutput$n.sims,cctfit$n,cctfit$m))
for(samp in 1:cctfit$BUGSoutput$n.sims){
cctfit$BUGSoutput$sims.list[["tau"]][samp,,] <- (cctfit$BUGSoutput$sims.list[["th"]][samp,]*t(1-cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) /
( (cctfit$BUGSoutput$sims.list[["th"]][samp,]*t(1-cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) +
((1-cctfit$BUGSoutput$sims.list[["th"]][samp,])*t(cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])) )
cctfit$ppY[,,samp] <- matrix(rbinom((cctfit$n*cctfit$m),1,
(t(cctfit$BUGSoutput$sims.list[["Z"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])*cctfit$BUGSoutput$sims.list[["tau"]][samp,,] ) +
t(t(1-cctfit$BUGSoutput$sims.list[["tau"]][samp,,])%*%diag(cctfit$BUGSoutput$sims.list[["g"]][samp,])) ), cctfit$n,cctfit$m)
}
if(cctfit$mval==TRUE){
for(i in 1:dim(cctfit$datob$thena)[1]){cctfit$data[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2]] <- Mode(cctfit$ppY[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2],])}
cctfit$MVest <- cbind(cctfit$datob$thena,cctfit$data[cctfit$datob$thena])
colnames(cctfit$MVest) <- c("Pers","Item","Resp")
}
cctfit$mean$ppY <- rowMeans(cctfit$ppY[,,],dims=2)
leigv <- 12
options(warn=-3)
ind <- sample(cctfit$BUGSoutput$n.sims,min(500,cctfit$BUGSoutput$n.sims)) #500 is the number of samples
eigv <- matrix(-1,length(ind),leigv)
tmp <- apply(cctfit$ppY[,,ind],c(1,3),function(x) t(x))
tmp2 <- apply(tmp[,,],3,function(x) cor(x))
tmp3 <- array(tmp2,c(cctfit$n,cctfit$n,cctfit$BUGSoutput$n.sims))
for(i in 1:length(ind)){
suppressMessages(try(eigv[i,] <- fa(tmp3[,,i])$values[1:leigv],silent=TRUE))}
wch <- -which(eigv[,1]==-1);
if(length(wch)==0){cctfit$ppeig <- eigv}else{cctfit$ppeig <- eigv[-which(eigv[,1]==-1),]}
cctfit$dateig <- suppressMessages(fa(cor(t(cctfit$data)))$values[1:leigv])
options(warn=0)
if(cctfit$V==1){
varvec <- matrix(-1,length(ind),dim(cctfit$ppY)[2])
vdi <- matrix(-1,dim(cctfit$ppY)[3],1)
for(i in 1:length(ind)){
varvec[i,] <- apply(cctfit$ppY[,,i],2,var)
}
vdi <- apply(varvec,1,var)
cctfit$ppVDI <- vdi
cctfit$datVDI <- var(apply(cctfit$data,2,var))
}
options(warn=-3)
if(cctfit$V>1){
varvec <- array(NA,c(length(ind),dim(cctfit$ppY)[2],cctfit$V))
vdi <- matrix(NA,dim(cctfit$ppY)[3],cctfit$V)
cctfit$datVDI <- array(-1,c(1,cctfit$V))
for(v in 1:cctfit$V){
for(i in 1:length(ind)){
if(sum(cctfit$BUGSoutput$sims.list$Om[ind[i],]==v)>1){
suppressMessages(try(varvec[i,,v] <- apply(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i],2,var),silent=TRUE))
}else{
suppressMessages(try(varvec[i,,v] <- var(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i]),silent=TRUE))
}
}
if(sum(cctfit$respmem==v)>1){
cctfit$datVDI[v] <- var(apply(cctfit$data[cctfit$respmem==v,],2,var))
}else{
cctfit$datVDI[v] <- var(cctfit$data[cctfit$respmem==v,])
}
}
vdi <- apply(varvec,c(1,3),var)
cctfit$ppVDI <- vdi
options(warn=0)
if(sum(apply(cctfit$ppVDI,2,function(x) all(x==0,na.rm=TRUE)))>=1){
for(i in which(apply(cctfit$ppVDI,2,function(x) all(x==0)))){
cctfit$ppVDI[,i] <- NA
}
}
for(v in 1:dim(cctfit$ppVDI)[2]){
if(identical(unique(cctfit$ppVDI[,v]),c(NA,0)) || identical(unique(cctfit$ppVDI[,v]),c(0,NA))){cctfit$ppVDI[,v] <- NA}
}
}
rm(vdi, varvec)
rm(eigv,leigv,tmp,tmp2,tmp3,ind);
cctfit$checksrun <- TRUE
}
if(cctfit$whmodel=="LTRM"){
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list[["T"]])) < 3){
cctfit$BUGSoutput$sims.list$T <- array(cctfit$BUGSoutput$sims.list[["T"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(length(dim(cctfit$BUGSoutput$sims.list[["gam"]])) < 3){
cctfit$BUGSoutput$sims.list$gam <- array(cctfit$BUGSoutput$sims.list[["gam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$C-1,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
}
}
cctfit$ppY <- array(NA, c(cctfit$n,cctfit$m,cctfit$BUGSoutput$n.sims));
cctfit$ppX <- array(NA, c(cctfit$n,cctfit$m,cctfit$BUGSoutput$n.sims));
cctfit$ppdelta <- array(NA, c(cctfit$n,cctfit$C-1,cctfit$BUGSoutput$n.sims))
cctfit$BUGSoutput$sims.list$tau <- array(-1,c(cctfit$BUGSoutput$n.sims,cctfit$n,cctfit$m))
for(samp in 1:cctfit$BUGSoutput$n.sims){
cctfit$BUGSoutput$sims.list[["tau"]][samp,,] <- cctfit$BUGSoutput$sims.list[["E"]][samp,]*t(1/cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])
cctfit$ppX[,,samp] <- matrix(
rnorm((cctfit$n*cctfit$m),t(cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]),(cctfit$BUGSoutput$sims.list[["tau"]][samp,,]^(-.5))),
cctfit$n,cctfit$m)
cctfit$ppdelta[,,samp] <- cctfit$BUGSoutput$sims.list[["a"]][samp,]*t(cctfit$BUGSoutput$sims.list[["gam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])+cctfit$BUGSoutput$sims.list[["b"]][samp,]
rc <- which(cctfit$ppX[,,samp] < cctfit$ppdelta[,1,samp],arr.ind=TRUE)
cctfit$ppY[cbind(rc,array(samp,dim(rc)[1]))] <- 1
for(c in 1:(cctfit$C-1)){
rc <- which(cctfit$ppX[,,samp] > cctfit$ppdelta[,c,samp],arr.ind=TRUE)
cctfit$ppY[cbind(rc,array(samp,dim(rc)[1]))] <- (c+1) }
}
cctfit$mean$ppY <- rowMeans(cctfit$ppY[,,],dims=2)
if(cctfit$mval==TRUE){
for(i in 1:dim(cctfit$datob$thena)[1]){cctfit$data[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2]] <- Mode(cctfit$ppY[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2],])}
cctfit$MVest <- cbind(cctfit$datob$thena,cctfit$data[cctfit$datob$thena])
colnames(cctfit$MVest) <- c("Pers","Item","Resp")
}
leigv <- 12
eigv <- matrix(-1,dim(cctfit$ppY)[3],leigv)
options(warn=-3)
ind <- sample(cctfit$BUGSoutput$n.sims,min(250,cctfit$BUGSoutput$n.sims)) #250 is the number of samples
tmp <- apply(cctfit$ppY[,,ind],c(1,3),function(x) t(x))
if(polych==TRUE){tmp2 <- apply(tmp[,,],3,function(x) suppressMessages(polychoric(x,global=FALSE))$rho)}else{
tmp2 <- apply(tmp[,,],3,function(x) cor(x))
}
tmp3 <- array(tmp2,c(cctfit$n,cctfit$n,length(ind)))
for(i in 1:length(ind)){
suppressMessages(try(eigv[i,] <- fa(tmp3[,,i])$values[1:leigv],silent=TRUE))}
wch <- -which(eigv[,1]==-1);
if(length(wch)==0){cctfit$ppeig <- eigv}else{cctfit$ppeig <- eigv[-which(eigv[,1]==-1),]}
if(polych==TRUE){
cctfit$dateig <- suppressMessages(fa(polychoric(t(cctfit$data),global=FALSE)$rho)$values[1:leigv])}else{
cctfit$dateig <- suppressMessages(fa(cor(t(cctfit$data)))$values[1:leigv])
}
options(warn=0)
if(cctfit$V==1){
varvec <- matrix(NA,length(ind),dim(cctfit$ppY)[2])
vdi <- matrix(NA,dim(cctfit$ppY)[3],1)
for(i in 1:length(ind)){
varvec[i,] <- apply(cctfit$ppY[,,i],2,var)
}
vdi <- apply(varvec,1,var)
cctfit$ppVDI <- vdi
cctfit$datVDI <- var(apply(cctfit$data,2,var))
}
options(warn=-3)
if(cctfit$V>1){
varvec <- array(NA,c(length(ind),dim(cctfit$ppY)[2],cctfit$V))
vdi <- matrix(NA,dim(cctfit$ppY)[3],cctfit$V)
cctfit$datVDI <- array(-1,c(1,cctfit$V))
for(v in 1:cctfit$V){
for(i in 1:length(ind)){
if(sum(cctfit$BUGSoutput$sims.list$Om[ind[i],]==v)>1){
suppressMessages(try(varvec[i,,v] <- apply(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i],2,var),silent=TRUE))
}else{
suppressMessages(try(varvec[i,,v] <- var(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i]),silent=TRUE))
}
}
if(sum(cctfit$respmem==v)>1){
cctfit$datVDI[v] <- var(apply(cctfit$data[cctfit$respmem==v,],2,var))
}else{
cctfit$datVDI[v] <- var(cctfit$data[cctfit$respmem==v,])
}
}
vdi <- apply(varvec,c(1,3),var)
cctfit$ppVDI <- vdi
options(warn=0)
if(sum(apply(cctfit$ppVDI,2,function(x) all(x==0,na.rm=TRUE)))>=1){
for(i in which(apply(cctfit$ppVDI,2,function(x) all(x==0)))){
cctfit$ppVDI[,i] <- NA
}
}
for(v in 1:dim(cctfit$ppVDI)[2]){
if(identical(unique(cctfit$ppVDI[,v]),c(NA,0)) || identical(unique(cctfit$ppVDI[,v]),c(0,NA))){cctfit$ppVDI[,v] <- NA}
}
}
cctfit$polycor <- polych
rm(vdi, varvec)
rm(eigv,leigv,tmp,tmp2,tmp3,ind);
cctfit$checksrun <- TRUE
}
if(cctfit$whmodel=="CRM"){
invlogit <- function(x){x <- 1 / (1 + exp(-x)); return(x)}
logit <- function(x){x <- log(x/(1-x)); return(x)}
if(cctfit$V==1){
cctfit$V <- 1;
cctfit$BUGSoutput$sims.list$Om <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$n));
if(length(dim(cctfit$BUGSoutput$sims.list[["T"]])) < 3){
cctfit$BUGSoutput$sims.list$T <- array(cctfit$BUGSoutput$sims.list[["T"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
if(cctfit$itemdiff==TRUE){
if(length(dim(cctfit$BUGSoutput$sims.list$lam)) < 3){
cctfit$BUGSoutput$sims.list$lam <- array(cctfit$BUGSoutput$sims.list[["lam"]][,],c(cctfit$BUGSoutput$n.sims,cctfit$m,1))}
}
}
if(cctfit$itemdiff==FALSE){
if(cctfit$V==1){
cctfit$BUGSoutput$sims.list$lam <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$m,1))
}
if(cctfit$V > 1){
cctfit$BUGSoutput$sims.list$lam <- array(1,c(cctfit$BUGSoutput$n.sims,cctfit$m,cctfit$V))
}
}
cctfit$ppY <- array(NA, c(cctfit$n,cctfit$m,cctfit$BUGSoutput$n.sims));
cctfit$ppX <- array(NA, c(cctfit$n,cctfit$m,cctfit$BUGSoutput$n.sims));
cctfit$BUGSoutput$sims.list$tau <- array(-1,c(cctfit$BUGSoutput$n.sims,cctfit$n,cctfit$m))
for(samp in 1:cctfit$BUGSoutput$n.sims){
cctfit$BUGSoutput$sims.list[["tau"]][samp,,] <- cctfit$BUGSoutput$sims.list[["E"]][samp,]*t(1/cctfit$BUGSoutput$sims.list[["lam"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]])
cctfit$ppY[,,samp] <- matrix(
rnorm((cctfit$n*cctfit$m),(cctfit$BUGSoutput$sims.list[["a"]][samp,]*t(cctfit$BUGSoutput$sims.list[["T"]][samp,,cctfit$BUGSoutput$sims.list[["Om"]][samp,]]))+matrix(rep(cctfit$BUGSoutput$sims.list[["b"]][samp,],cctfit$m),cctfit$n,cctfit$m),
(cctfit$BUGSoutput$sims.list[["a"]][samp,]*(cctfit$BUGSoutput$sims.list[["tau"]][samp,,]^(-.5)))),
cctfit$n,cctfit$m)
cctfit$ppX[,,samp] <- (array(rep(1/cctfit$BUGSoutput$sims.list[["a"]][samp,],times=cctfit$m),c(cctfit$n,cctfit$m))*(cctfit$ppY[,,samp]))-matrix(rep(cctfit$BUGSoutput$sims.list[["b"]][samp,],times=cctfit$m),c(cctfit$n,cctfit$m))
}
cctfit$mean$ppY <- rowMeans(cctfit$ppY[,,],dims=2)
if(cctfit$mval==TRUE){
for(i in 1:dim(cctfit$datob$thena)[1]){cctfit$data[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2]] <- mean(cctfit$ppY[cctfit$datob$thena[i,1],cctfit$datob$thena[i,2],])}
cctfit$MVest <- cbind(cctfit$datob$thena,cctfit$data[cctfit$datob$thena])
colnames(cctfit$MVest) <- c("Pers","Item","Resp")
}
leigv <- 12
options(warn=-3)
ind <- sample(cctfit$BUGSoutput$n.sims,min(500,cctfit$BUGSoutput$n.sims)) #500 is the number of samples
eigv <- matrix(-1,length(ind),leigv)
tmp <- apply(cctfit$ppY[,,ind],c(1,3),function(x) t(x))
tmp2 <- apply(tmp[,,],3,function(x) cor(x))
tmp3 <- array(tmp2,c(cctfit$n,cctfit$n,cctfit$BUGSoutput$n.sims))
for(i in 1:length(ind)){
suppressMessages(try(eigv[i,] <- fa(tmp3[,,i])$values[1:leigv],silent=TRUE))}
wch <- -which(eigv[,1]==-1);
if(length(wch)==0){cctfit$ppeig <- eigv}else{cctfit$ppeig <- eigv[-which(eigv[,1]==-1),]}
cctfit$dateig <- suppressMessages(fa(cor(t(cctfit$data)))$values[1:leigv])
options(warn=0)
if(cctfit$V==1){
vdi <- matrix(-1,dim(cctfit$ppY)[3],1)
varvec <- array(-1,c(length(ind),dim(cctfit$ppY)[2]))
for(i in 1:length(ind)){
#varvec[i,] <- apply(invlogit(cctfit$ppY[,,i]),2,var)
varvec[i,] <- apply(invlogit(cctfit$ppY[,,i]),2,var)
}
vdi <- apply(varvec,1,var)
cctfit$ppVDI <- apply(varvec,1,var)
#cctfit$datVDI <- var(apply(invlogit(cctfit$data),2,var))
cctfit$datVDI <- var(apply(invlogit(cctfit$data),2,var))
}
if(cctfit$V>1){
varvec <- array(NA,c(length(ind),dim(cctfit$ppY)[2],cctfit$V))
cctfit$datVDI <- array(NA,c(1,cctfit$V))
options(warn=-3)
for(v in 1:cctfit$V){
for(i in 1:length(ind)){
if(sum(cctfit$BUGSoutput$sims.list$Om[ind[i],]==v)>1){
#suppressMessages(try(varvec[i,,v] <- apply(invlogit(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i]),2,var),silent=TRUE))
suppressMessages(try(varvec[i,,v] <- apply(invlogit(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i]),2,var),silent=TRUE))
}else{
#suppressMessages(try(varvec[i,,v] <- var(invlogit(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i])),silent=TRUE))
suppressMessages(try(varvec[i,,v] <- var(invlogit(cctfit$ppY[cctfit$BUGSoutput$sims.list$Om[ind[i],]==v,,i])),silent=TRUE))
}
}
if(sum(cctfit$respmem==v)>1){
#cctfit$datVDI[v] <- var(apply(invlogit(cctfit$data[cctfit$respmem==v,]),2,var))
cctfit$datVDI[v] <- var(apply(invlogit(cctfit$data[cctfit$respmem==v,]),2,var))
}else{
#cctfit$datVDI[v] <- var(invlogit(cctfit$data[cctfit$respmem==v,]))
cctfit$datVDI[v] <- var(invlogit(cctfit$data[cctfit$respmem==v,]))
}
}
options(warn=0)
vdi <- apply(varvec,c(1,3),function(x) var(x,na.rm=TRUE))
cctfit$ppVDI <- vdi
if(sum(apply(cctfit$ppVDI,2,function(x) all(x==0,na.rm=TRUE)))>=1){
for(i in which(apply(cctfit$ppVDI,2,function(x) all(x==0)))){
cctfit$ppVDI[,i] <- NA
}
}
for(v in 1:dim(cctfit$ppVDI)[2]){
if(identical(unique(cctfit$ppVDI[,v]),c(NA,0)) || identical(unique(cctfit$ppVDI[,v]),c(0,NA))){cctfit$ppVDI[,v] <- NA}
}
}
rm(vdi, varvec)
rm(eigv,leigv,tmp,tmp2,tmp3,ind);
cctfit$checksrun <- TRUE
}
}
if(cctfit$mval==TRUE && gui==FALSE){
message(paste("\n ...Use function 'cctmvest()' to view model estimates for missing data",sep=""))
# message(paste("\n ...Use '",guidat$varname,"$MVest' to view posterior predictive estimates for missing data\n ... '",guidat$varname,"$data' to view the full data matrix \n ... '",guidat$varname,"$datamiss' to view the matrix with missing values",sep=""))
}
message("\n ...Posterior predictive checks complete")
}
if(doplot == TRUE){
if(saveplots==1){jpeg(file.path(gsub(".Rdata","ppc.jpg",savedir)),width = 6, height = 3, units = "in", pointsize = 12,quality=100,res=400)}
if(saveplots==2){postscript(file=file.path(gsub(".Rdata","ppc.eps",savedir)), onefile=FALSE, horizontal=FALSE, width = 6, height = 6, paper="special", family="Times")}
par(oma=c(0,0,0,0),mar=c(4,4,3,1),mgp=c(2.25,.75,0),mfrow=c(1,2))
plot(NA, main="Culture Number Check",xlim=c(1,min(cctfit$n,8)),ylim=c(min(cctfit$dateig[min(cctfit$n,8)],cctfit$ppeig[,min(cctfit$n,8)]),ceiling(max(cctfit$ppeig[,1],cctfit$dateig[1]))),xlab="Eigenvalue",ylab="Value",las=1,pch=21,type="l",col="black")
for(i in 1:dim(cctfit$ppeig)[1]){
points(cctfit$ppeig[i,],col="grey",type="l") }
points(cctfit$dateig,col="black",type="l")
if(cctfit$V>1){
cctfit$VDIperc <- array(NA,c(cctfit$V,1))
color <- "black"; color2 <- "black"
color <- c("black","dark grey","light grey",rainbow(cctfit$V))
minmax <- array(NA,c(cctfit$V,2))
minmax2 <- array(NA,c(cctfit$V,1))
for(v in which(sort(which(!apply(cctfit$ppVDI,2,function(x) all(is.na(x))))) %in% sort(unique(cctfit$respmem)))){
tmpdist <-ecdf(cctfit$ppVDI[,v])
minmax[v,] <- c(quantile(tmpdist, .005),quantile(tmpdist, .995))
minmax2[v] <- max(density(cctfit$ppVDI[,v],na.rm=TRUE)$y)
}
plot(NA,main="Item Difficulty Check", xlab= "VDI", xlim=c(min(cctfit$datVDI[!is.na(cctfit$datVDI)],minmax,na.rm=TRUE),max(cctfit$datVDI[!is.na(cctfit$datVDI)],minmax,na.rm=TRUE)), ylim=c(0,max(minmax2,na.rm=TRUE)), ylab="Value",las=1,col=color[1],type="l")
for(v in which(sort(which(!apply(cctfit$ppVDI,2,function(x) all(is.na(x))))) %in% sort(unique(cctfit$respmem)))){
tmpdist <-ecdf(cctfit$ppVDI[,v])
points(density(cctfit$ppVDI[,v],na.rm=TRUE),lwd=1.5,main="Item Difficulty Check", xlab= "VDI", xlim=c(min(cctfit$datVDI[!is.na(cctfit$datVDI)],quantile(tmpdist, .005),na.rm=TRUE),max(cctfit$datVDI[!is.na(cctfit$datVDI)],quantile(tmpdist, .995),na.rm=TRUE)), ylim=c(0,max(density(cctfit$ppVDI,na.rm=TRUE)$y,na.rm=TRUE)), ylab="Value",las=1,col=color[v],type="l")
if(saveplots!=1 && saveplots!=2){print(paste("VDI Culture ",v," : ",round(100*tmpdist(cctfit$datVDI[,v]),digits=2)," percentile"),col=color2)
cctfit$VDIperc[v,1] <- round(100*tmpdist(cctfit$datVDI[,v]),digits=2)
}
}
rm(tmpdist)
segments(cctfit$datVDI,0,cctfit$datVDI,par("usr")[4],col=color,lwd=1.5)
}else{
color <- "black"; color2 <- "black"
tmpdist <-ecdf(cctfit$ppVDI)
plot(density(cctfit$ppVDI,na.rm=TRUE),main="Item Difficulty Check", xlab= "VDI", xlim=c(min(cctfit$datVDI,quantile(tmpdist, .005)),max(cctfit$datVDI,quantile(tmpdist, .995))), ylim=c(0,max(density(cctfit$ppVDI,na.rm=TRUE)$y,na.rm=TRUE)), ylab="Value",las=1,col=color2)
segments(cctfit$datVDI,0,cctfit$datVDI,par("usr")[4],col=color2)
text(.7*par("usr")[2],.7*par("usr")[4],labels=paste(round(100*tmpdist(cctfit$datVDI),digits=2)," percentile"),col=color2)
if(saveplots!=1 && saveplots!=2){cctfit$VDIperc <- round(100*tmpdist(cctfit$datVDI),digits=2)
print(paste("VDI Culture 1 : ",round(100*tmpdist(cctfit$datVDI),digits=2)," percentile"),col=color2)
}; rm(tmpdist)
}
rm(color,color2)
if(saveplots==1 || saveplots==2){dev.off()}
saveplots <- 0
}
return(cctfit)
}
#######################
#Accessor Function for Missing Value Estimates
#######################
cctmvest <- function(cctfit){
if(cctfit$mval==FALSE){
message("\n ...Data has no missing values to estimate",sep="")
return()
}
if(cctfit$checksrun==FALSE){
message("\n ...Please use 'cctppc()' first",sep="")
}else{
return(cctfit$MVest)
}
}
#######################
#Accessor Function for the Factor Coefficients
#######################
cctfac <- function(dat){
return(print(dat$factors,digits=2))
}
#######################
#Accessor Function for the Subject Parameters
#######################
cctsubj <- function(cctfit){
return(print(cctfit$subj,digits=2))
}
#######################
#Accessor Function for the Credible Intervals of the Subject Parameters
#######################
cctsubjhdi <- function(cctfit){
return(print(cctfit$subjhdi,digits=2))
}
#######################
#Accessor Function for the Item Parameters
#######################
cctitem <- function(cctfit){
return(print(cctfit$item,digits=2))
}
#######################
#Accessor Function for the Credible Intervals of the Item Parameters
#######################
cctitemhdi <- function(cctfit){
return(print(cctfit$itemhdi,digits=2))
}
#######################
#Accessor Function for the Category Boundary Parameters and Credible Intervals (LTRM only)
#######################
cctcat <- function(cctfit){
return(print(cctfit$cat,digits=2))
}
#######################
#Accessor Function for Cluster Memberships
#######################
cctmemb <- function(cctfit){
return(cctfit$respmem)
}
#######################
#cctfit Summary Function
#######################
cctsum <- function(cctfit){
tmp <- c(" ","X")
if(cctfit$checksrun==FALSE){
cctfit$sumtab <- t(array(
c(paste("Data:"),cctfit$datob$datatype,paste("Model:"),cctfit$whmodel,
paste("Respondents:"),cctfit$n,paste("Items:"),cctfit$m,
paste("Observations: "),paste(100*round(cctfit$datob$nobs / (cctfit$datob$nobs+cctfit$datob$nmiss),2),"%",sep=""),paste("Missing Values: "),paste(100*round(cctfit$datob$nmiss / (cctfit$datob$nobs+cctfit$datob$nmiss),2),"%",sep=""),
paste("Cultures:"),cctfit$V,paste("Item Difficulty"),paste("[",tmp[cctfit$itemdiff+1],"]",sep=""),
paste("DIC:"),round(cctfit$BUGSoutput$DIC,2),paste("pD:"),round(cctfit$BUGSoutput$pD,2),
paste("Rhats > 1.10:"),paste(cctfit$Rhat$above110,"/",cctfit$Rhat$ncp),paste("Rhats > 1.05:"),paste(cctfit$Rhat$above105,"/",cctfit$Rhat$ncp),
paste("Samples:"),cctfit$BUGSoutput$n.iter,paste("Chains:"),cctfit$BUGSoutput$n.chains,
paste("Burn-in:"),cctfit$BUGSoutput$n.burnin,paste("Thinning:"),cctfit$BUGSoutput$n.thin
#,paste("PPC Calculated"),paste("[",tmp[cctfit$checksrun+1],"]",sep=""),paste(""),paste("")
),c(4,8)))
}else{
cctfit$sumtab <- t(array(
c(paste("Data:"),cctfit$datob$datatype,paste("Model:"),cctfit$whmodel,
paste("Respondents:"),cctfit$n,paste("Items:"),cctfit$m,
paste("Observations: "),paste(100*round(cctfit$datob$nobs / (cctfit$datob$nobs+cctfit$datob$nmiss),2),"%",sep=""),paste("Missing Values: "),paste(100*round(cctfit$datob$nmiss / (cctfit$datob$nobs+cctfit$datob$nmiss),2),"%",sep=""),
paste("Cultures:"),cctfit$V,paste("Item Difficulty"),paste("[",tmp[cctfit$itemdiff+1],"]",sep=""),
paste("DIC:"),round(cctfit$BUGSoutput$DIC,2),paste("pD:"),round(cctfit$BUGSoutput$pD,2),
paste("Rhats > 1.10:"),paste(cctfit$Rhat$above110,"/",cctfit$Rhat$ncp),paste("Rhats > 1.05:"),paste(cctfit$Rhat$above105,"/",cctfit$Rhat$ncp),
paste("PPC Calculated"),paste("[",tmp[cctfit$checksrun+1],"]",sep=""),paste("VDI"),paste(round(c(cctfit$VDI)),collapse=', '),
paste("Samples:"),cctfit$BUGSoutput$n.iter,paste("Chains:"),cctfit$BUGSoutput$n.chains,
paste("Burn-in:"),cctfit$BUGSoutput$n.burnin,paste("Thinning:"),cctfit$BUGSoutput$n.thin
),c(4,9)))
}
rownames(cctfit$sumtab) <- rep("", nrow(cctfit$sumtab))
colnames(cctfit$sumtab) <- rep("", ncol(cctfit$sumtab))
print(cctfit$sumtab,quote=F)
}
######################
#Function for the 'Export Results' Button
#- Prompts user where to save, and the filename to use
#- Saves the inference results (cctfit) to an .Rdata file of that filename
#- Saves .eps and .jpeg plots of the scree plot, plot results button, and run checks button
# if the checks were calculated (the checks button was pressed)
######################
exportfuncbutton <- function() {
guidat <- get("guidat", pkg_globals)
exportfunc(cctfit=get(guidat$varname, pkg_globals),gui=TRUE,guidat=guidat)
}
exportfunc <- function(cctfit,filename=paste(getwd(),"/CCTpackdata.Rdata",sep=""),gui=FALSE,guidat=NULL) {
if(gui==TRUE){
savedir <- tclvalue(tkgetSaveFile(initialfile = "CCTpackdata.Rdata",filetypes = "{{Rdata Files} {.Rdata}}"))
if (!nchar(savedir)) {
message("\n ...Export cancelled\n")
return()}
}else{
savedir <- filename
}
if (savedir=="" && !file.exists("CCTpack")){dir.create(file.path(getwd(), "CCTpack"));
savedir <- file.path(getwd(),"CCTpack","CCTpackdata.Rdata")
}
if(substr(savedir, nchar(savedir)-6+1, nchar(savedir))!=".Rdata"){
savedir <- paste(savedir,".Rdata",sep="")
}
message("\n ...Exporting results")
write.csv(cctfit$BUGSoutput$summary,file.path(gsub(".Rdata","posterior.csv",savedir)))
save(cctfit,file=file.path(savedir))
if(cctfit$checksrun==TRUE){
ppcfunc(cctfit=cctfit,saveplots=1,savedir); ppcfunc(cctfit=cctfit,saveplots=2,savedir)}
plotresultsfunc(cctfit=cctfit,saveplots=1,savedir); plotresultsfunc(cctfit=cctfit,saveplots=2,savedir);
screeplotfunc(datob=cctfit$datob,saveplots=1,savedir); screeplotfunc(datob=cctfit$datob,saveplots=2,savedir)
message("\n ...Export complete\n")
}
######################
#Function for the 'Fit Summary' Button
#- Gives a basic summary of the fit
######################
summaryfuncbutton <- function() {
guidat <- get("guidat", pkg_globals)
summary(get(guidat$varname, pkg_globals))
}
######################
#Function for the 'Print Fit' Button
#- Prints the cctfit object in the console
######################
printfitfuncbutton <- function() {
guidat <- get("guidat", pkg_globals)
print(get(guidat$varname, pkg_globals))
}
######################
#Function for the 'Send to Console' Button
#- Gives user the code to load the cctfit object into the console
######################
sendconsolefuncbutton <- function() {
guidat <- get("guidat", pkg_globals)
message("\n ...Paste the following to send your fit object into the R console
\n ",guidat$varname," <- CCTpack:::pkg_globals$",guidat$varname,
"\n",sep="")
}
######################
#Function for the 'Send to Console' Button
#- Gives user the code to load the cctfit object into the console
######################
sendconsolefuncbutton <- function() {
guidat <- get("guidat", pkg_globals)
message("",sep="")
message("\n ...Paste the following to send your fit object into the R console
\n ",guidat$varname," <- CCTpack:::pkg_globals$",guidat$varname,
"\n")
}
######################
#Function for the 'Resp Memberships' Button
#- Outputs the respondent memberships from the model fit
######################
membfuncbutton <- function(){
guidat <- get("guidat", pkg_globals)
message("\n ...Model-based cluster memberships for each respondent \n",sep="")
print(get(guidat$varname, pkg_globals)$respmem)
#print(get(guidat$varname, pkg_globals)$MVest)
}
######################
#Function for the 'NA Value Est' Button
#- Plot traceplots for all discrete parameters 3x3 plot size
######################
mvestfuncbutton <- function(){
guidat <- get("guidat", pkg_globals)
cctfit <- get(guidat$varname, pkg_globals)
if(cctfit$mval==FALSE){
message("\n ...Data has no missing values to estimate\n",sep="")
return()
}
if(cctfit$checksrun==FALSE){
message("\n ...Please use 'Run Checks' first",sep="")
}else{
message("\n ...Model estimates for missing values \n",sep="")
print(cctfit$MVest)
}
}
######################
#Function for the 'Traceplot Discrete' Button
#- Plot traceplots for all discrete parameters 3x3 plot size
######################
traceplotdiscretefuncbutton <- function() {
guidat <- get("guidat", pkg_globals)
dtraceplot(get(guidat$varname, pkg_globals))
}
######################
#Function for the 'Traceplot Continuous' Button
#- Plot traceplots for all parameters 3x3 plot size
######################
traceplotallfuncbutton <- function() {
guidat <- get("guidat", pkg_globals)
traceplot(get(guidat$varname, pkg_globals),mfrow=c(3,3), ask = FALSE)
}
dtraceplot <- function(cctfit,ask=FALSE){
if(cctfit$V==1 && cctfit$whmodel!="GCM"){
message("\n ...There are no discrete nodes in this inference")
return()
}
if(cctfit$whmodel!="GCM"){
inds <- c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]])
}else{
if(cctfit$V==1){
inds <- c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]])
}
if(cctfit$V>1){
inds <- c(cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Z")]],cctfit$BUGSoutput$long.short[[which(cctfit$BUGSoutput$root.short=="Om")]])
}
}
if(cctfit$BUGSoutput$n.chains > 1){
cctfit$BUGSoutput$sims.array <- cctfit$BUGSoutput$sims.array[,,inds]
}else{
dmnames <- dimnames(cctfit$BUGSoutput$sims.array); dmnames[[3]] <- dmnames[[3]][inds]
tmp <- array(cctfit$BUGSoutput$sims.array[,,inds],c(cctfit$BUGSoutput$n.keep,length(inds),1))
cctfit$BUGSoutput$sims.array <- aperm(tmp,c(1,3,2)); dimnames(cctfit$BUGSoutput$sims.array) <- dmnames;
}
traceplot(cctfit,ask=ask,mfrow=c(3,3))
}
#######################
#End of Functions for the GUI and/or Standalone Functions
#######################
#######################
#Package Methods
#######################
setClass("cct",contains=c("rjags"));
setGeneric("plot"); setGeneric("screeplot"); setGeneric("summary")
setMethod("plot",signature=c(x="cct"),definition=function(x) cctresults(x))
setMethod("summary",signature=c(object="cct"),definition=function(object) cctsum(object))
setMethod("screeplot",signature=c(x="data.frame"),definition=function(x,polych=F) cctscree(x,polych=polych))
setMethod("screeplot",signature=c(x="matrix"),definition=function(x,polych=F) cctscree(x,polych=polych))
setMethod("screeplot",signature=c(x="cct"),definition=function(x,polych=F) cctscree(x$datob$dat,polych=polych))
######################
#END CCTpack
######################
|
/scratch/gouwar.j/cran-all/cranData/CCTpack/R/cctgui.r
|
#' expData
#'
#' Two example data set: one with internal standards (IS), and one without IS
#'
#' @format A list with 2 data frames:
#' \describe{
#' \item{noSTD}{the example data without IS}
#' \item{STD}{the example data with IS}
#' }
"expData"
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/R/data.R
|
#' @title Perform Calibration
#' @description Perform calibration
#' @author Yonghui Dong
#' @param DF data frame, it must contain a column named 'Concentration' and a column named 'Response'
#' @param weights default is NULL
#' @importFrom stats predict
#' @importFrom magrittr %>%
#' @export
#' @return dataframe, the quantification result
#' @examples
#' Concentration <- rep(c(10, 50, 100, "unknown"), each = 3)
#' Response <- c(133, 156, 177, 6650, 7800, 8850, 13300, 15600, 17700, 156, 1450, 1400)
#' DF <- cbind.data.frame(Concentration = Concentration, Response = Response)
#' result <- doCalibration(DF)
doCalibration <- function(DF, weights = NULL){
## suppress the warning: no visible binding for global variable ‘Concentration’, 'Attention' and 'Compound'
Concentration <- NULL
Attention <- NULL
Compound <- NULL
Response <- NULL
minR <- NULL
maxR <- NULL
## Get the calibration range for each compound
if (is.null(DF$Compound)) {DF$Compound = "X"}
DFC <- DF %>%
dplyr::filter(Concentration != 'unknown') %>%
dplyr::group_by(Compound) %>%
dplyr::mutate(minR = min(Response), maxR = max(Response)) %>%
dplyr::select(Compound, minR, maxR) %>%
dplyr::distinct_all()
## select only samples
DFS <- DF %>%
dplyr::filter(Concentration == 'unknown')
## join the two DF
DFS2 <- dplyr::right_join(DFS, DFC, by = "Compound")
## set attention for compound responses that is out of calibration range
DFS2$Attention = "no"
DFA <- DFS2 %>%
dplyr::mutate(Attention = ifelse(Response > maxR | Response < minR , 'response out of calibration range', Attention)) %>%
dplyr::select(Concentration, Response, Compound, Attention)
## Quantification
if(nrow(DFA) > 0){
# get ratio
if (is.null(DFA$IS)) {
DFA$Ratio = DFA$Response
} else {
DFA$Ratio = DFA$Response/DFA$IS
}
# get model
model <- if(inherits(try(doWlm(DF, weights = weights)$model, silent = TRUE), "try-error")){NULL} else {doWlm(DF, weights = weights)$model}
# get y
if (!is.null(model)){
for (i in 1:dim(DFA)[1]) {
DFA$Concentration[i] <- round((DFA$Ratio[i] - coef(model)[1])/coef(model)[2], 3)
}
}
if (is.null(weights)){weights = "1"}
DFA$Ratio <- NULL
calResult <- cbind.data.frame(DFA, Model = weights)
} else {
if (is.null(weights)){weights = "1"}
calResult <- cbind.data.frame(Sample = "No sample detected", Model = weights)
}
return(calResult)
}
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/R/doCalibration.R
|
#' @title Evaluate Different Weighting Factors
#' @description Evaluate different weighting factors.
#' @author Yonghui Dong
#' @param DF data frame, it must contain a column named 'Concentration' and a column named 'Response'
#' @param p p-value, default is 0.05
#' @param userWeights user defined weights in linear regression, default is NULL. User can easily define weights, e.g., "1/x", "1/x^2", "1/y"
#' @export
#' @return dataframe, weighting factor evaluation result
#' @examples
#' Concentration <- rep(c(10, 50, 100, 500), each = 3)
#' Response <- c(133, 156, 177, 1300, 1450, 1600, 4000, 3881, 3700, 140000, 139000, 140000)
#' DF <- cbind.data.frame(Concentration = Concentration, Response = Response)
#' result <- doEvaluation(DF)
doEvaluation <- function(DF, p = 0.05, userWeights = NULL) {
Compound <- NULL
if (is.null(DF$Compound)) {DF$Compound = "X"}
Homo <- unique(doFtest(DF, p = p)$Homoscedasticity)
Compound <- unique(DF$Compound)
if(is.null(userWeights)){userWeights = "None"}
Model <- c("1", "1/x", "1/x^2", "1/y", "1/y^2", paste("user: ", userWeights, sep = ""))
W0 <- doWlm(DF, weights = NULL)
W1x <- doWlm(DF, weights = "1/x")
Wx2<- doWlm(DF, weights = "1/x^2")
W1y <- doWlm(DF, weights = "1/y")
Wy2 <- doWlm(DF, weights = "1/y^2")
if(!is.null(userWeights)){
Wuser <- if(inherits(try(doWlm(DF, weights = userWeights), silent = TRUE), "try-error")){NULL} else {doWlm(DF, weights = userWeights)}
}
if(is.null(Wuser)){
sumRE = c(W0$sumResid, W1x$sumResid, Wx2$sumResid, W1y$sumResid, Wy2$sumResid, NA)
R2 = c(W0$R2, W1x$R2, Wx2$R2, W1y$R2, Wy2$R2, Wuser$R2, NA)
} else{
sumRE = c(W0$sumResid, W1x$sumResid, Wx2$sumResid, W1y$sumResid, Wy2$sumResid, Wuser$sumResid)
R2 = c(W0$R2, W1x$R2, Wx2$R2, W1y$R2, Wy2$R2, Wuser$R2)
}
Recommendation <- rep("--", 6)
if(Homo == "Yes") {
Recommendation[1] <- "Yes"
} else {
Recommendation[which.min(sumRE)] <- "Yes"
}
Result <- cbind.data.frame(Compound = Compound,
Homoscedasticity = Homo,
Model = Model,
R2 = R2 ,
"sum%RE" = sumRE,
Recommendation = Recommendation)
return(Result)
}
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/R/doEvaluation.R
|
#' @title Perform F Test
#' @description perform F test to evaluate homoscedasticity.
#' @author Yonghui Dong
#' @param DF data frame, it must contain a column named 'Concentration' and a column named 'Response'
#' @param p p-value
#' @param lower.tail default is FALSE
#' @importFrom stats qf var
#' @importFrom magrittr %>%
#' @export
#' @return dataframe, F test result
#' @examples
#' Concentration <- rep(c(10, 50, 100, 500), each = 3)
#' Response <- c(133, 156, 177, 1300, 1450, 1600, 4000, 3881, 3700, 140000, 139000, 140000)
#' DF <- cbind.data.frame(Concentration, Response)
#' result <- doFtest(DF, p = 0.01)
doFtest <- function(DF, p = 0.01, lower.tail = FALSE){
## suppress the warning: no visible binding for global variable ‘Concentration’ and 'Compound'
Concentration <- Compound <- NULL
# calculate IS normalized peak areas if IS are used
if (is.null(DF$IS)) {
DF$Ratio = DF$Response
} else {
DF$Ratio = DF$Response/DF$IS
}
# Assign the compound name if it is not specified
if (is.null(DF$Compound)) {DF$Compound = "X"}
# remove samples, keep only STD
DF <- DF %>%
dplyr::filter(Concentration != 'unknown') %>%
dplyr::mutate(Concentration = as.numeric(Concentration))
# test homoscedasticity per compound
DF$Compound <- as.factor(DF$Compound)
n = length(levels(DF$Compound))
myTest <- setNames(data.frame(matrix(ncol = 4, nrow = n)), c("Compound", "Experimental_F-value", "Critical_F-Value", "Homoscedasticity"))
for (i in 1:n){
minCon <- DF %>%
dplyr::filter(Compound == levels(DF$Compound)[i]) %>%
dplyr::slice_min(order_by = Concentration)
maxCon <- DF %>%
dplyr::filter(Compound == levels(DF$Compound)[i]) %>%
dplyr::slice_max(order_by = Concentration)
## Skip F test if there are no replicates
if(nrow(minCon) > 1 & nrow(maxCon) > 1){
varMin <- var(minCon$Ratio)
nMin <- dim(minCon)[1] - 1
varMax <- var(maxCon$Ratio)
nMax <- dim(maxCon)[1] -1
fExp <- round(varMax/varMin, 3)
fTab <- round(qf(p = p, df1 = nMax, df2 = nMin, lower.tail = lower.tail), 3)
myTest[i, "Compound"] <- levels(DF$Compound)[i]
myTest[i, "Experimental_F-value"] <- fExp
myTest[i, "Critical_F-Value"] <- fTab
if (fExp > fTab) {
myTest[i, "Homoscedasticity"] <- "No"
} else {
myTest[i, "Homoscedasticity"] <- "Yes"
}
} else {
myTest[i, "Compound"] <- levels(DF$Compound)[i]
myTest[i, "Experimental_F-value"] <- "unknown: no replicates"
myTest[i, "Critical_F-Value"] <- "unknown: no replicates"
myTest[i, "Homoscedasticity"] <- "unknown"
}
}
return(myTest)
}
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/R/doFtest.R
|
#' @title Perform Weighted Linear Regression
#' @description Perform weighted linear regression and evaluate by using summed residual.
#' @author Yonghui Dong
#' @param DF data frame, it must contain a column named 'Concentration' and a column named 'Response'
#' @param weights the weights used in linear regression, default is NULL. User can easily define weights, e.g., "1/x", "1/x^2", "1/y"
#' @importFrom stats coef fitted lm resid setNames
#' @export
#' @return list, weighted linear regression result
#' @examples
#' Concentration <- rep(c(10, 50, 100, 500), each = 3)
#' Response <- c(133, 156, 177, 1300, 1450, 1600, 4000, 3881, 3700, 140000, 139000, 140000)
#' DF <- cbind.data.frame(Concentration = Concentration, Response = Response)
#' result <- doWlm(DF, weights = "1/x^2")
doWlm <- function(DF, weights = NULL) {
## suppress the warning: no visible binding for global variable ‘Concentration’ and 'Compound'
Concentration <- NULL
#(1) prepare the data
# remove samples, keep only STD
DF <- DF %>%
dplyr::filter(Concentration != 'unknown') %>%
dplyr::mutate(Concentration = as.numeric(Concentration))
## calculate IS normalized peak areas if IS are used
if (is.null(DF$IS)) {
DF$Ratio = DF$Response
} else {
DF$Ratio = DF$Response/DF$IS
}
# Assign the compound name if it is not specified
if (is.null(DF$Compound)) {DF$Compound = "X"}
x <- DF$Concentration
y <- DF$Ratio
if(is.null(weights)){
models <- lm(y ~ x)
weights = "1"
} else {
models <- lm(y ~ x, weights = eval(parse(text = weights)))
}
if(is.null(weights)){
models <- lm(y ~ x)
weights = "1"
}
#(2) residual plot
myResid <- resid(models)
dfResid <- cbind.data.frame(Concentration = x, RE = myResid/y * 100)
## H-line
hline <- function(y = 0, color = 'rgba(1, 50, 67, 1)') {
list(
width = 2,
x0 = 0,
x1 = 1,
xref = "paper",
y0 = y,
y1 = y,
line = list(color = color)
)
}
pResid <- plotly::plot_ly(dfResid,
x = ~ Concentration,
y = ~ RE,
type = "scatter",
mode = "markers") %>%
plotly::add_markers(marker = list(size = 10,
color = 'rgba(107, 185, 240, 1)',
line = list(color = 'rgba(1, 50, 67, 1)', width = 2))) %>%
plotly::layout(yaxis = list(title = "% Relative Error"),
shapes = list(hline(0)))
#(3) regression plot
## get expression
a = format(unname(coef(models)[1]), digits = 4)
b = format(unname(coef(models)[2]), digits = 4)
r2 = format(summary(models)$r.squared, digits = 4)
## get regression plot
PLinear <- plotly::plot_ly(DF,
x = ~Concentration,
y = ~Ratio,
type = "scatter",
mode = "markers") %>%
plotly::add_markers(marker = list(size = 10,
color = 'rgba(255, 182, 193, .9)',
line = list(color = 'rgba(152, 0, 0, .8)', width = 2))) %>%
plotly::add_lines(x = ~ Concentration,
y = fitted(models),
line = list(width = 2, dash = "dot", color = 'rgba(152, 0, 0, .8)')) %>%
plotly::layout(yaxis = list(title = "Reponse")) %>%
plotly::add_annotations(x = mean(x) * 0.8, y = max(y) * 0.9,
text = paste("y = ", a, " + ", b, "x", " , ", "R<sup>2</sup>", " = ", r2, sep = ""),
showarrow = F)
## combine the two plots
figResult <- plotly::subplot(PLinear, pResid, nrows = 2, shareX = T, shareY = F,
titleX = T, titleY = T) %>%
plotly::layout(showlegend = F,
title = paste("<b>weights: </b>", weights, sep = "")) %>%
plotly::config(
toImageButtonOptions = list(
format = "svg",
filename = "myplot",
width = 600,
height = 700
)
)
#(4) get sum residual
sumResid <- round(sum(abs(myResid/y * 100)), 2)
#(5) save needed results
resultList <- list(sumResid = sumResid, figResult = figResult, R2 = r2, model = models)
return(resultList)
}
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/R/doWlm.R
|
#' @title Run CCWeights Gui
#' @description Run CCWeights Gui.
#' @author Yonghui Dong
#' @import bs4Dash fresh DT tools readxl rmarkdown readr
#' @export
#' @return Gui
#' @examples
#' if(interactive()){}
runGui <- function() {
appDir <- system.file("shiny", "Gui", package = "CCWeights")
if (appDir == "") {
stop("Could not find Shiny Gui directory. Try re-installing `CCWeightd`.", call. = FALSE)
}
shiny::runApp(appDir, display.mode = "normal")
}
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/R/runGui.R
|
# for shiny
library(bs4Dash)
library(shiny)
library(DT)
library(plotly)
library(tools)
library(readxl)
library(rmarkdown)
library(readr)
#library(shinyWidgets)
library(fresh)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/helpers.R
|
userWeightsexist <- reactive({
if(is.null(userWeights())){
return("user: None")
} else {
return(userWeights())
}
})
observeEvent(input$caliDo, {
shiny::validate(need(nrow(userInput()) > 0, "No data"))
suppressWarnings(
shiny::withProgress(message = 'Quantification in progress',
detail = 'It may take a while...', value = 0.3,{
M1 <- userInput() %>%
dplyr::group_by(Compound) %>%
dplyr::do(CCWeights::doCalibration(., weights = NULL))
M2 <- userInput() %>%
dplyr::group_by(Compound) %>%
dplyr::do(CCWeights::doCalibration(., weights = "1/x"))
M3 <- userInput() %>%
dplyr::group_by(Compound) %>%
dplyr::do(CCWeights::doCalibration(., weights = "1/x^2"))
M4 <- userInput() %>%
dplyr::group_by(Compound) %>%
dplyr::do(CCWeights::doCalibration(., weights = "1/y"))
M5 <- userInput() %>%
dplyr::group_by(Compound) %>%
dplyr::do(CCWeights::doCalibration(., weights = "1/y^2"))
M6 <- userInput() %>%
dplyr::group_by(Compound) %>%
dplyr::do(CCWeights::doCalibration(., weights = userWeightsexist()))
CaliFinal <- rbind.data.frame(M1, M2, M3, M4, M5, M6)
output$caliResult <- renderDataTable({
datatable(CaliFinal,
class = 'cell-border stripe',
rownames = FALSE,
options = list(scrollX = TRUE))
})
output$caliSave<- downloadHandler(
filename = function() {
paste("quantificationResults", ".csv", sep="")
},
content = function(file) {
write.csv(CaliFinal, file, row.names = FALSE)
}
)
})
)
})
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/server-calibration.R
|
# F-test Function
pval_selected <- reactive(
return(input$pval_cutoff)
)
observeEvent(input$homoTest, {
output$homescedasticityResult <- renderDataTable({
validate(need(nrow(userInput()) > 0, "No data"))
datatable(CCWeights::doFtest(DF = userInput(), p = pval_selected()),
class = 'cell-border stripe',
rownames = FALSE,
options = list(scrollX = TRUE))
})
})
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/server-homoscedasticity.R
|
#### load Data
userInput <- reactive({
if(input$example_data == "yes") {
if(input$example_dataset == "std"){
target <- CCWeights::expData$STD
} else{
target <- CCWeights::expData$noSTD
}
return(target)
}
else if (input$example_data == "umd") {
infile <- input$target
if (is.null(infile)){
return(NULL)
}
else {
extension <- tools::file_ext(infile$name)
filepath <- infile$datapath
target = switch(extension,
csv = readr::read_csv(filepath),
xls = readxl::read_xls(filepath),
xlsx = readxl::read_xlsx(filepath)
)
# Assign the compound name if it is not specified
if (is.null(target$Compound)) {target$Compound = "X"}
return(as.data.frame(target))
}
}
})
observeEvent(input$upload_data, {
output$rawData <- DT::renderDataTable({
shiny::validate(need(all(c("Concentration", "Response") %in% colnames(userInput())),
"You data should contain at least 'Concentration' and 'Response' columns"))
datatable(userInput(),
class = 'cell-border stripe',
rownames = FALSE,
filter = "top",
extensions = 'Buttons'
)
})
output$summaryData <- DT::renderDataTable({
shiny::validate(need(all(c("Concentration", "Response") %in% colnames(userInput())),
"You data should contain at least 'Concentration' and 'Response' columns"))
# get summary
dataSummary <- userInput() %>%
dplyr::group_by(Compound, Concentration) %>%
dplyr::summarise(Count = dplyr::n(), .groups = 'drop')
datatable(dataSummary,
options = list(ordering = FALSE),
class = 'cell-border stripe',
rownames = FALSE,
extensions = 'Buttons',
editable = FALSE
)
})
})
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/server-inputdata.R
|
#weights
observe({
if(!is.null((userInput()))){
x <- unique(userInput()$Compound)
updateSelectInput(session,
"selected_compound",
choices = x,
selected = x[1])
}
})
selectedDF <- reactive({
userInput()[userInput()$Compound == input$selected_compound, ]
})
## user defined weights
userWeights <- reactive({
if(shiny::isTruthy(input$userWeights)){
return(input$userWeights)
}
})
observeEvent(input$evaluate, {
shiny::withProgress(message = 'Evaluation in progress',
detail = 'It may take a while...', value = 0.7,{
output$Weights_recommondation <- renderDataTable({
shiny::validate(need(nrow(selectedDF()) > 0, "No data"))
datatable(cbind.data.frame("p-value used" = pval_selected(),
CCWeights::doEvaluation(selectedDF(), p = pval_selected(), userWeights = userWeights())),
class = 'cell-border stripe',
rownames = FALSE,
options = list(scrollX = TRUE))
})
output$weightPlot1 <- renderPlotly({
validate(need(nrow(selectedDF()) > 0, "No data"))
CCWeights::doWlm(selectedDF(), weights = NULL)$figResult
})
output$weightPlot2 <- renderPlotly({
validate(need(nrow(selectedDF()) > 0, "No data"))
CCWeights::doWlm(selectedDF(), weights = "1/x")$figResult
})
output$weightPlot3 <- renderPlotly({
validate(need(nrow(selectedDF()) > 0, "No data"))
CCWeights::doWlm(selectedDF(), weights = "1/x^2")$figResult
})
output$weightPlot4 <- renderPlotly({
validate(need(nrow(selectedDF()) > 0, "No data"))
CCWeights::doWlm(selectedDF(), weights = "1/y")$figResult
})
output$weightPlot5 <- renderPlotly({
validate(need(nrow(selectedDF()) > 0, "No data"))
CCWeights::doWlm(selectedDF(), weights = "1/y^2")$figResult
})
output$weightPlot6 <- renderPlotly({
validate(need(!is.null(userWeights()), "No defined weights from user"))
validate(need(nrow(selectedDF()) > 0, "No data"))
## skip the wrong input weights
if(inherits(try(CCWeights::doWlm(selectedDF(), weights = userWeights())$figResult, silent = TRUE), "try-error")){NULL
} else {
CCWeights::doWlm(selectedDF(), weights = userWeights())$figResult
}
})
})
})
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/server-weights.R
|
shinyServer(function(input, output, session) {
options(shiny.maxRequestSize = 100 * 1024^2) ## file size limit: 100MB
source("server-inputdata.R",local = TRUE)
source("server-homoscedasticity.R",local = TRUE)
source("server-weights.R",local = TRUE)
source("server-calibration.R",local = TRUE)
}
)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/server.R
|
my_theme <- create_theme(
# navbar
bs4dash_vars(
navbar_dark_color = "#FFFFFF",
navbar_dark_active_color = "#F17F42",
navbar_dark_hover_color = "#F17F42"
),
# main bg
bs4dash_layout(
main_bg = "#FFFFFF"
),
# sidebar
bs4dash_sidebar_dark(
bg = "#9DC8C8",
color = "#FFFFFF",
hover_color = "#F17F42",
active_color = "000000",
# submenu
submenu_bg = "#9DC8C8",
submenu_active_color = "#000000",
submenu_active_bg = "#F17F42",
submenu_color = "#FFFFFF",
submenu_hover_color = "#F17F42"
),
# status
bs4dash_status(
primary = "#9DC8C8", warning = "#F17F42"
)
)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/themes.R
|
fluidRow(
column(width = 12,
bs4Card(
width = 12,
title = "Instruction",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
p("In this section you can quantify your samples based on the calibration curve."),
p("Data with", span("unknown", style = "color:#f15c42"), "concentration is quantified here."),
p("Although optimum weighting scheme has been suggested, here different weighting schemes including the user defined one if available,
are used to quantify each compound in the sample. This allows the user to compare the results and make their final desicion."),
p("1. You can click", strong("Quantify"), "button to perform calibration."),
p("2. Subsequently, you can save the result by clicking the", strong("Save Result"), "button."),
p("3. Note: ", span("when sample responses fall out of the linear range, the predicted concentrations are under- or over-estimated", style = "color:#f15c42"),
".Therefore, we have included a column named", span("Attention", style = "color:#f15c42"), "in the result file. If the sample response is within the linear range,",
span("Attention = no;", style = "color:#f15c42"), "otherwise,", span("Attention = response out of calibration range.",style = "color:#f15c42"),
"Users should carefully examine the quantification results in this case."),
p("4. Note: ", span("when the user defined weighting factor is not available", style = "color:#f15c42"), ", quantification will not be perfromed and analyte concentration
will remain unknown under this weighting factor in the result.")
)
),
column(width = 3,
bs4Card(
width = 12,
inputId = "caliResult_card",
title = "Perform Quantification",
status = "primary",
solidHeader = FALSE,
collapsible = FALSE,
collapsed = FALSE,
closable = FALSE,
p("Perform calibration with different weights"),
actionButton("caliDo", "Quantify", icon("paper-plane"),
style="color: #fff; background-color: #CD0000; border-color: #9E0000")
),
bs4Card(
width = 12,
inputId = "caliResult_card",
title = "Save Quantification Result",
status = "primary",
solidHeader = FALSE,
collapsible = FALSE,
collapsed = FALSE,
closable = FALSE,
p("Quantification results can be downloaded in csv format"),
shinyjs::hidden(downloadButton("caliSave", "Save Result", icon("download"),
style="color: #fff; background-color: #0091ff; border-color: #0091ff"))
)
),
column(width = 9,
bs4Card(
width = 12,
inputId = "caliResult_card",
title = "Quantification Result",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
DT::dataTableOutput("caliResult")
)
)
)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/ui-tab-calibration.R
|
fluidRow(
column(10,
includeMarkdown("mds/contact.md"))
)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/ui-tab-contact.R
|
fluidRow(
column(width = 12,
bs4Card(
width = 12,
title = "Instruction",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
p("It has been suggested that a weighting factor should only be used when homoscedasticity is not met for analytical data.
CCWeights first tests data homoscedasticity by calculating the probability that the variance of measurements at the highest
concentration level is smaller than the variance of measurements at the lowest concentration level using an F-test."),
p("The test of homoscedasticity is accepted when", span("Experimental F value", style = "color:#f15c42"), "is smaller than corresponding",
span("Critical F value (or F Table value)", style = "color:#f15c42"), "at confidence of", span("99% (i.e., 1 - p-value).", style = "color:#f15c42")),
p("1. You can customize the p-value to test the homoscedasticity of your dataset."),
p("2. You can click", strong('+'), "and", strong('-'), "in the tab to show or hide the contents in the tab.")
)
),
column(width = 3,
bs4Card(
width = 12,
inputId = "homoTest_card",
title = "Homoscedasticity Test Parameters",
status = "primary",
solidHeader = FALSE,
collapsible = FALSE,
collapsed = FALSE,
closable = FALSE,
numericInput("pval_cutoff", strong("p-value threshold"), value = 0.01, min = 0, max = 1, step = 0.01),
actionButton("homoTest", "Start Test", icon("paper-plane"),
style="color: #fff; background-color: #CD0000; border-color: #9E0000")
)
),
column(width = 9,
bs4Card(
width = 12,
inputId = "homoResult_card",
title = "Homoscedasticity Test Result",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
DT::dataTableOutput("homescedasticityResult")
)
)
)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/ui-tab-homoscedasticity.R
|
fluidRow(
column(width = 12,
bs4Card(
width = 12,
title = "Instruction",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
p("1. You can upload your data in", strong("Upload Data Panel"), "tab. CCWeights accepts csv, xls and xlsx formats."),
p("2. Your data should contain at least two columns, i.e.,", span("Concentration", style = "color:#f15c42"), "and", span("Response", style = "color:#f15c42"),
". If your data contains information from more than one compounds, you need to add an additional column, named", span("Compound", style = "color:#f15c42"),
". If you have internal standards in your data, you need to add a column named", span("IS", style = "color:#f15c42"), ". Note that column names
are case-sensitive."),
p("3. You can load the two example datasets in", strong("Upload Data Panel"), "tab to check the data format."),
p("4. You can view the data in", strong("Loaded Data"), "tab,
and view the summary statistics of the loaded data in", strong("Data Summary"), "."),
p("5. You can click", strong('+'), "and", strong('-'), "in the tab to show or hide the contents in the tab.")
)
),
column(width = 3,
bs4Card(
width = 12,
inputId = "input_card",
title = "Upload data panel",
status = "primary",
solidHeader = FALSE,
collapsible = FALSE,
collapsed = FALSE,
closable = FALSE,
radioButtons("example_data", "Do you want to view the example data?",
choices = c("Yes" = 'yes',
"No, upload my data" = 'umd'),
selected = 'yes'),
conditionalPanel(condition = "input.example_data == 'yes'",
radioButtons("example_dataset", "Please choose an example dataset:",
choices = c("Example without internal standard" = 'nostd',
"Example with internal standard" = 'std'
),
selected = 'nostd')
),
conditionalPanel(condition = "input.example_data == 'umd'",
fileInput("target","Upload your file (csv/xls/xlsx format):")
),
actionButton("upload_data", "Submit", icon("paper-plane"),
style="color: #fff; background-color: #CD0000; border-color: #9E0000"
)
)
),
column(width = 9,
bs4Card(
width = 12,
inputId = "rawData_card",
title = "Loaded Data",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
DT::dataTableOutput("rawData")
),
bs4Card(
width = 12,
inputId = "summary_card",
title = "Data Summary",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = TRUE,
closable = FALSE,
DT::dataTableOutput("summaryData")
)
)
)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/ui-tab-inputdata.R
|
fluidRow(
column(width = 10,
includeMarkdown("mds/landing.md"))
)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/ui-tab-landing.R
|
fluidRow(
column(width = 12,
bs4Card(
width = 12,
title = "Instruction",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
strong("*How is the best weighting factor selected?"),
br(),
p("(a)", span("If the data are homoscedastic,", style = "color:#f15c42"), "weighting factor = 1 (1/x^0, unweight linear regression) is suggested."),
p("(b)", span("If the data are heteroscedastic,", style = "color:#f15c42"), "five commonly used weighting factors, i.e., 1/x^0, 1/x, 1/x^2, 1/y and 1/y^2,
together with user-defined weighting factors (if present) are tested. By applying regression with different weighting
factors on a set of calibration curve standard data, the best weighting factor is identified by choosing the
one generating the smallest sum of the absolute relative errors (sum%RE)."),
strong("*Instruction"),
br(),
p("1. The results are displayed for each compound, you can select the compound name in", strong("View Result"), "tab to check
the corresponding result."),
p("2. Additionally, you can define and test your own preferred weighting factors in", strong("Add your own weights"), "tab (e.g., 1/x^3).
Don't worry if you input some wrong weighting schemes. CCWeights knows how to skip them."),
p("3. Two types of results are given here. One is a summerized table, which contains the evaluation results of each model, and
the suggested model. The residual and linear regression plots for each model are also provided here to allow the user
to interactively visulize the results."),
p("4. You can download the figures of interest in", span("svg", style = "color:#f15c42"), "format by clicking the", span("Camera", style = "color:#f15c42"), "icon (download plot) in the figure."),
p("5. You can click", strong('+'), "and", strong('-'), "in the tab to show or hide the contents in the tab.")
)
),
column(width = 3,
bs4Card(
width = 12,
inputId = "weightView_card",
title = "View Result",
status = "primary",
solidHeader = FALSE,
collapsible = FALSE,
collapsed = FALSE,
closable = FALSE,
selectInput("selected_compound", label = "Select compound to view:", list()),
p("Optionally: "),
textInput("userWeights", label = "Add your own weights"),
actionButton("evaluate", "Evaluate", icon("paper-plane"),
style="color: #fff; background-color: #CD0000; border-color: #9E0000")
)
),
column(width = 9,
bs4Card(
width = 12,
inputId = "weightBest",
title = "Recommondated weights for the selected compound",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
DT::dataTableOutput("Weights_recommondation")
),
fixedRow(
column(6,
box(
width = 12,
title = "Regression (red) and Residual (blue) Plots",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
plotlyOutput("weightPlot1")
),
box(
width = 12,
title = "Regression (red) and Residual (blue) Plots",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
plotlyOutput("weightPlot2")
),
box(
width = 12,
title = "Regression (red) and Residual (blue) Plots",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
plotlyOutput("weightPlot3")
)
),
column(6,
box(
width = 12,
title = "Regression (red) and Residual (blue) Plots",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
plotlyOutput("weightPlot4")
),
box(
width = 12,
title = "Regression (red) and Residual (blue) Plots",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
plotlyOutput("weightPlot5")
),
box(
width = 12,
title = "@user defined weights",
status = "secondary",
solidHeader = FALSE,
collapsible = TRUE,
collapsed = FALSE,
closable = FALSE,
plotlyOutput("weightPlot6")
)
)
)
)
)
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/ui-tab-weights.R
|
source("helpers.R")
source("themes.R")
bs4DashPage(
old_school = FALSE,
sidebar_min = TRUE,
sidebar_collapsed = FALSE,
controlbar_collapsed = TRUE,
controlbar_overlay = TRUE,
title = "CCWeights",
## NAVBAR ----------------------------------------------------------------------
bs4DashNavbar(
skin = "dark",
status = "primary",
border = TRUE,
sidebarIcon = "chevron-left",
controlbarIcon = "th",
fixed = FALSE
),
## SIDEBAR ----------------------------------------------------------------------
bs4DashSidebar(
skin = "dark",
status = "warning",
title = HTML("<b>CCWeights</b>"),
brandColor = "warning",
src = "https://github.com/YonghuiDong/CCWeights/blob/main/inst/shiny/Gui/mds/pix/logo.png?raw=true",
elevation = 3,
opacity = 0.8,
bs4SidebarMenu(
bs4SidebarMenuItem("Home", tabName = "home", icon = "home"),
bs4SidebarMenuItem("Upload Data", tabName = "inputdata", icon = "upload"),
bs4SidebarMenuItem("Homoscedasticity Test", tabName = "homoscedasticity", icon = "check"),
bs4SidebarMenuItem("Weights Test", tabName = "weights", icon = "balance-scale"),
bs4SidebarMenuItem("Quantification", tabName = "quantification", icon = "chart-bar"),
bs4SidebarMenuItem("Contact", tabName = "contact", icon = "user")
)
),
## BODY ----------------------------------------------------------------------
bs4DashBody(
use_theme(my_theme),
bs4TabItems(
bs4TabItem("home",
source("ui-tab-landing.R", local=TRUE)$value),
bs4TabItem("inputdata",
source("ui-tab-inputdata.R", local=TRUE)$value),
bs4TabItem("homoscedasticity",
source("ui-tab-homoscedasticity.R", local=TRUE)$value),
bs4TabItem("weights",
source("ui-tab-weights.R", local=TRUE)$value),
bs4TabItem("quantification",
source("ui-tab-calibration.R", local=TRUE)$value),
bs4TabItem("contact",
source("ui-tab-contact.R", local=TRUE)$value)
) # bs4TabItems
), # bs4DashBody
## FOOTER ----------------------------------------------------------------------
bs4DashFooter(
fluidRow(
column(
width = 12,
align = "center",
"Blavatnik Center for Drug Discovery (BCDD)",
br(),
"Tel Aviv University",
br(),
"Copyright (C) 2021, code licensed under GPL-3.0",
br()
)
),
right_text = NULL
)
) # bs4DashPage
|
/scratch/gouwar.j/cran-all/cranData/CCWeights/inst/shiny/Gui/ui.R
|
#' View the 'CDC PLACES' data dictionary
#'
#' This function provides the user with a data frame that shows all of the available measures in the PLACES data set and for which release years the measures are included.
#'#'
#'@importFrom httr2 request req_perform resp_body_string
#'@importFrom jsonlite fromJSON
#'@importFrom curl has_internet
#'
#'@examples
#'# First save the data
#'dictionary <- get_dictionary()
#'# Then view the data frame
#'# View(dictionary)
#'
#'@export get_dictionary
#'@returns a dataframe with the current PLACES data dictionary.
get_dictionary <- function(){
if(!curl::has_internet()){
message("Request could not be completed. No internet connection.")
return(invisible(NULL))
}
check_api("https://data.cdc.gov/resource/m35w-spkz.json")
resp <- httr2::request("https://data.cdc.gov/resource/m35w-spkz.json") |>
httr2::req_perform()
resp |>
httr2::resp_body_string() |>
jsonlite::fromJSON()
}
|
/scratch/gouwar.j/cran-all/cranData/CDCPLACES/R/get_dictionary.R
|
#'Obtain data from the CDC PLACES APIs.
#'
#'Use this function to access CDC PLACES API data. Measures are sourced from the Behavioral Risk Factor Surveillance System and the American Community Survey ACS.
#'
#'@param geography The level of desired geography. Currently supports 'county' and 'census'.
#'@param state Specify the state of the desired data using the two letter abbreviation. Supports multiple states if desired.
#'@param measure Specify the measures of the data pull. Supports multiple states if desired. For a full list of available measures, see the function 'get_dictionary'.
#'@param county Specify the county of the desired data using the full name of the county, with a capital letter.
#'@param release Specify the year of release for the PLACES data set. Currently supports years 2020-2023.
#'@param geometry if FALSE (the default), return a regular data frame of PLACES data. If TRUE, uses the tigris package to return an sf data frame with simple feature geometry in the 'geometry' column.
#'
#'@examples
#'get_places(geography = "county", state = "MI", measure = "SLEEP", release = "2023")
#'get_places(geography = "county", state = c("MI", "OH"),
#'measure = c("SLEEP", "ACCESS2"), release = "2023")
#'
#'@importFrom httr2 request req_perform resp_body_string
#'@importFrom jsonlite fromJSON
#'@importFrom tidyr unnest
#'@importFrom dplyr filter rename mutate left_join select
#'@importFrom httr http_error timeout GET message_for_status
#'@importFrom curl has_internet
#'@importFrom tigris counties tracts
#'@importFrom sf st_as_sf
#'
#'@export get_places
#'@returns A tibble that contains observations for each measure (adjusted and unadjusted prevalence) and geographic level.
get_places <- function(geography = "county", state = NULL, measure = NULL, county = NULL,
release = "2023", geometry = FALSE){
# Assigning base url
if(release == "2023"){
if(geography == "county"){
base <- "https://data.cdc.gov/resource/swc5-untb.json"
} else if(geography == "census"){
base <- "https://data.cdc.gov/resource/cwsq-ngmh.json"
}else{
stop("Geographic level not supported. Please enter 'census' or 'county'.")
}
}else if(release == "2022"){
if(geography == "county"){
base <- "https://data.cdc.gov/resource/duw2-7jbt.json"
} else if(geography == "census"){
base <- "https://data.cdc.gov/resource/nw2y-v4gm.json"
}else{
stop("Geographic level not supported. Please enter 'census' or 'county'.")
}
}else if(release == "2021"){
if(geography == "county"){
base <- "https://data.cdc.gov/resource/pqpp-u99h.json"
} else if(geography == "census"){
base <- "https://data.cdc.gov/resource/373s-ayzu.json"
}else{
stop("Geographic level not supported. Please enter 'census' or 'county'.")
}
}else if(release == "2020"){
if(geography == "county"){
base <- "https://data.cdc.gov/resource/dv4u-3x3q.json"
} else if(geography == "census"){
base <- "https://data.cdc.gov/resource/4ai3-zynv.json"
}else{
stop("Geographic level not supported. Please enter 'census' or 'county'.")
}
}else{
stop("Release year is not available. Please enter a year 2020-2023.")
}
# Check for internet
if(!curl::has_internet()){
message("Request could not be completed. No internet connection.")
return(invisible(NULL))
}
# Data pull
# if county is null
if(is.null(county)){
if(is.null(state) & is.null(measure)){
message("Pulling data for all geographies. This may take some time...")
check_api(base)
places1 <- httr2::request(base) |>
httr2::req_perform()
places_out <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation) |>
dplyr::filter(stateabbr != "US")
}else if(is.null(measure)){
lapply(state, check_states)
check_api(base)
places_out <- data.frame()
for(i in state){
places1 <- httr2::request(paste0(base, "?$limit=5000000", "&stateabbr=", i)) |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}else if(is.null(state)){
lapply(measure, check_measures, ryear=release)
check_api(base)
places_out <- data.frame()
for(i in measure){
places1 <- httr2::request(paste0(base, "?$limit=5000000", "&measureid=", i)) |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation) |>
dplyr::filter(stateabbr != "US")
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}else if (length(measure) > 1 & length(state) > 1){ # multiple states, multiple measures
lapply(state, check_states)
lapply(measure, check_measures, ryear=release)
check_api(base)
places_out <- data.frame()
if(length(measure) > length(state)){
for(i in measure){
p1 <- paste0(base, "?$limit=5000000", "&stateabbr=", state, "&measureid=", i)
for(b in seq(state)){
places1 <- p1[b] |>
httr2::request() |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}
}else{
for(i in state){
p1 <- paste0(base, "?$limit=5000000", "&stateabbr=", i, "&measureid=", measure)
for(b in seq(measure)){
places1 <- p1[b] |>
httr2::request() |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}
}
}else if(length(state) >= 1 & length(measure) < 2){
lapply(state, check_states)
lapply(measure, check_measures, ryear=release)
check_api(base)
places_out <- data.frame()
for(i in state){
base_url <- paste0(base, "?$limit=5000000", "&measureid=", measure, "&stateabbr=", i)
places1 <- httr2::request(base_url) |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}else if (length(measure >= 1 & length(state) < 2)){
lapply(state, check_states)
lapply(measure, check_measures, ryear=release)
check_api(base)
places_out <- data.frame()
for(i in measure){
places1 <- httr2::request(paste0(base, "?$limit=5000000", "&stateabbr=", state, "&measureid=", i)) |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}
}else{ # if county is provided
lapply(county, check_counties)
if(is.null(state) & is.null(measure)){
stop("If querying counties, you must supply the argument 'state'.")
}else if(is.null(measure)){ # all measures
lapply(state, check_states)
check_api(base)
places_out <- data.frame()
for(i in state){
places1 <- httr2::request(paste0(base, "?$limit=5000000", "&stateabbr=", i)) |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}else if(is.null(state)){
stop("If querying counties, you must supply the argument 'state'.")
}else if (length(measure) > 1 & length(state) > 1){ # multiple states, multiple measures
lapply(state, check_states)
lapply(measure, check_measures, ryear=release)
check_api(base)
places_out <- data.frame()
if(length(measure) > length(state)){
for(i in measure){
p1 <- paste0(base, "?$limit=5000000", "&stateabbr=", state, "&measureid=", i)
for(b in seq(state)){
places1 <- p1[b] |>
httr2::request() |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}
}else{
for(i in state){
p1 <- paste0(base, "?$limit=5000000", "&stateabbr=", i, "&measureid=", measure)
for(b in seq(measure)){
places1 <- p1[b] |>
httr2::request() |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}
}
}else if(length(state) >= 1 & length(measure) < 2){
lapply(state, check_states)
lapply(measure, check_measures, ryear=release)
check_api(base)
places_out <- data.frame()
for(i in state){
base_url <- paste0(base, "?$limit=5000000", "&measureid=", measure, "&stateabbr=", i)
places1 <- httr2::request(base_url) |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}else if (length(measure >= 1 & length(state) < 2)){
lapply(state, check_states)
lapply(measure, check_measures, ryear=release)
check_api(base)
places_out <- data.frame()
for(i in measure){
places1 <- httr2::request(paste0(base, "?$limit=5000000", "&stateabbr=", state, "&measureid=", i)) |>
httr2::req_perform()
places_out_add <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation)
places_out <- rbind(places_out, places_out_add, row.names = NULL)
}
}
}
# Spatial data transformations
if(!is.null(county)){
if(geography == "county"){
places_out <- places_out |>
filter(locationname %in% county)
}else if(geography == "census"){
places_out <- places_out |>
filter(countyname %in% county)
}
}
places_out$coordinates <- lapply(places_out$coordinates, function(x) as.data.frame(t(x)))
places_out <- places_out |>
tidyr::unnest(coordinates) |>
dplyr::rename(lon = V1, lat = V2) |>
dplyr::mutate(data_value = as.numeric(data_value),
low_confidence_limit = as.numeric(low_confidence_limit),
high_confidence_limit = as.numeric(high_confidence_limit))
if(isTRUE(geometry)){
if(geography == "county"){
if(release == "2020"){
# add locationid for county 2020
fips <- tigris::fips_codes |>
dplyr::mutate(locationid = paste0(state_code, county_code),
locationname_p = paste0(county, ", ", state)) |>
dplyr::select(locationname_p, locationid)
places_out <- places_out |>
dplyr::mutate(locationname_p = paste0(locationname, " County, ", stateabbr))
places_out <- dplyr::left_join(places_out, fips, by = "locationname_p")
geo <- tigris::counties(state = state, year = 2020, cb = TRUE) |>
dplyr::select(GEOID, geometry)
places_out <- dplyr::left_join(places_out, geo, by = c("locationid" = "GEOID")) |>
sf::st_as_sf()
}else{
geo <- tigris::counties(state = state, year = 2020, cb = TRUE) |>
dplyr::select(GEOID, geometry)
places_out <- dplyr::left_join(places_out, geo, by = c("locationid" = "GEOID")) |>
sf::st_as_sf()
}
}else if(geography == "census"){
geo <- tigris::tracts(state = state, year = 2010) |>
dplyr::select(GEOID10, geometry)
places_out <- dplyr::left_join(places_out, geo, by = c("locationid" = "GEOID10")) |>
sf::st_as_sf()
}
}
return(places_out)
}
#'check if measures can be queried, or if entered properly
#'@param x The measure to be compared to the list
#'@param ryear The release year of the query
#'@noRd
check_measures <- function(x, ryear){
if(ryear == "2023"){
if(!(x %in% measures23$measureid)){
stop(paste("Please enter a valid measure for release year", paste0(ryear, "."), "For a full list of valid measures, use the function 'get_measures'."))
}
}else if(ryear == "2022"){
if(!(x %in% measures22$measureid)){
stop(paste("Please enter a valid measure for release year", paste0(ryear, "."), "For a full list of valid measures, use the function 'get_measures'."))
}
}else if(ryear == "2021"){
if(!(x %in% measures21$measureid)){
stop(paste("Please enter a valid measure for release year", paste0(ryear, "."), "For a full list of valid measures, use the function 'get_measures'."))
}
}else if(ryear == "2020"){
if(!(x %in% measures20$measureid)){
stop(paste("Please enter a valid measure for release year", paste0(ryear, "."), "For a full list of valid measures, use the function 'get_measures'."))
}
}
}
#'check if states can be queried or if entered correctly
#'@param x The state to be compared to the US state list
#'@noRd
check_states <- function(x){
us_states <- c("CA", "AK", "AL", "AZ", "AR", "GA", "DC", "CO", "DE", "CT", "IN", "IL", "ID", "HI", "KS", "IA", "KY", "MD", "LA", "MA", "ME", "MI", "MS",
"MN", "MO", "MT", "NE", "NV", "NJ", "NM", "NC", "NY", "NH", "OH", "OK", "ND", "OR", "SD", "SC", "PA", "RI", "TN", "TX", "VA", "UT", "VT",
"WA", "WI", "WV", "WY")
if(!(x %in% us_states)){
stop("\nPlease enter a valid US State name.")
}
}
#'check if counties can be queried or if entered correctly
#'@param x The counties to be compared to the US counties list
#'@noRd
check_counties <- function(x){
us_counties <- unique(usa::counties$name)
if(!(x %in% us_counties)){
stop("\nPlease enter a valid US County name.")
}
}
#'check if api returns error, if so: fail gracefully.
#'@param x The base url used in API query
#'@noRd
check_api <- function(x){
stop_quietly <- function() {
opt <- options(show.error.messages = FALSE)
on.exit(options(opt))
stop()
}
try_GET <- function(x, ...) {
tryCatch(
httr::GET(url = x, httr::timeout(10), ...),
error = function(e) conditionMessage(e),
warning = function(w) conditionMessage(w)
)
}
resp <- try_GET(x)
if(httr::http_error(resp)){
httr::message_for_status(resp)
message("\nFor full response code details visit: https://dev.socrata.com/docs/response-codes.html.")
stop_quietly()
#return(invisible(NULL))
}
}
#' internal test check to see if API is online
#'@param x The base url used in API query
#'@noRd
test_check_api <- function(x){
try_GET <- function(x, ...) {
tryCatch(
httr::GET(url = x, httr::timeout(10), ...),
error = function(e) conditionMessage(e),
warning = function(w) conditionMessage(w)
)
}
resp <- try_GET(x)
if(httr::http_error(resp)){
httr::message_for_status(resp)
return(invisible(1))
}else{
return(invisible(0))
}
}
testfunc <- function(base){
check_api(base)
places1 <- httr2::request(base) |>
httr2::req_perform()
places_out <- places1 |>
httr2::resp_body_string() |>
jsonlite::fromJSON() |>
tidyr::unnest(cols = geolocation) |>
dplyr::filter(stateabbr != "US")
}
|
/scratch/gouwar.j/cran-all/cranData/CDCPLACES/R/get_places.R
|
utils::globalVariables(c("V1", "V2", "coordinates", "data_value", "geolocation",
"high_confidence_limit",
"low_confidence_limit", "measures23", "measures22",
"measures21", "measures20",
"stateabbr", "release", "state_code",
"county_code", "county", "locationid", "locationname_p",
"locationname", "GEOID", "GEOID10", "countyname"))
|
/scratch/gouwar.j/cran-all/cranData/CDCPLACES/R/globals.R
|
CDFt <- function(ObsRp, DataGp, DataGf, npas = 1000, dev = 2){
mO = mean(ObsRp, na.rm=TRUE)
mGp= mean(DataGp, na.rm=TRUE)
DataGp2 = DataGp + (mO-mGp)
DataGf2 = DataGf + (mO-mGp)
FRp=ecdf(ObsRp)
FGp=ecdf(DataGp2)
FGf=ecdf(DataGf2)
a=abs(mean(DataGf, na.rm=TRUE)-mean(DataGp, na.rm=TRUE))
m=min(ObsRp, DataGp, DataGf, na.rm=TRUE)-dev*a
M=max(ObsRp, DataGp, DataGf, na.rm=TRUE)+dev*a
x=seq(m,M,,npas)
FGF=FGf(x)
FGP=FGp(x)
FRP=FRp(x)
FGPm1.FGF=quantile(DataGp2,probs=FGF, na.rm=TRUE)
FRF=FRp(FGPm1.FGF)
######################################
# FRf=FRp with shift for x<min(DataGf)
if(min(ObsRp, na.rm=TRUE)<min(DataGf2, na.rm=TRUE)){
i=1
while(x[i]<=quantile(ObsRp,probs=FRF[1],na.rm=TRUE)){
i=i+1
}
j=1
while(x[j]<min(DataGf2, na.rm=TRUE)){
j=j+1
}
k=i
while(j>0 && k>0){
FRF[j]=FRP[k]
j=j-1
k=k-1
}
##########
if(j>0){
for(k in j:1){
FRF[k]=0
}
}
}
######################################
# FRf=FRp with shift for x>max(DataGf)
if(FRF[length(x)]<1){
i=length(x)
QQ=quantile(ObsRp,probs=FRF[length(x)], na.rm=TRUE)
while(x[i]>=QQ){
i=i-1
}
i=i+1
j=length(x)-1
while(j>0 && FRF[j]==FRF[length(x)]){
j=j-1
}
if(j==0){
stop("In CDFt, dev must be higher\n")
}
dif=min((length(x)-j),(length(x)-i))
FRF[j:(j+dif)]=FRP[i:(i+dif)]
k=j+dif
if(k<length(x)){
FRF[k:(length(x))]=1
}
}
######################################################################################
### Quantile-matching based on the new large-scale CDF and downscaled local-scale CDF.
NaNs.indices = which(is.na(DataGf2))
No.NaNs.indices = which(!is.na(DataGf2))
qntl = array(NaN, dim=length(DataGf2))
qntl[No.NaNs.indices] = FGf(DataGf2[No.NaNs.indices])
#qntl[NaNs.indices] = NaN
xx = array(NaN, dim=length(DataGf2))
xx = approx(FRF,x,qntl,yleft=x[1],yright=x[length(x)],ties='mean')
#qntl = FGf(DataGf2)
#xx = approx(FRF,x,qntl,yleft=x[1],yright=x[length(x)],ties='mean')
#######################################################################################
FGp=ecdf(DataGp)
FGf=ecdf(DataGf)
FGP=FGp(x)
FGF=FGf(x)
return(list(x=x,FRp=FRP,FGp=FGP,FGf=FGF,FRf=FRF,DS=xx$y))
}
|
/scratch/gouwar.j/cran-all/cranData/CDFt/R/CDFt.R
|
CramerVonMisesTwoSamples <- function(S1, S2){
xS1=sort(S1)
M=length(xS1)
xS2=sort(S2)
N=length(xS2)
a=data.frame(val=xS1,rang=seq(M),ens=rep(1,M))
b=data.frame(val=xS2,rang=seq(N),ens=rep(2,N))
c=rbind(a,b)
c=c[order(c$val),]
c=data.frame(c,rangTot=seq(M+N))
dtfM=c[which(c$ens==1),]
dtfN=c[which(c$ens==2),]
somN = sum( (dtfN$rang - dtfN$rangTot)**2 )
somM = sum( (dtfM$rang - dtfM$rangTot)**2 )
U = N*somN + M*somM
#CvM = (U / (N*M*(N+M))) - ((4*M*N - 1)/(6*(M+N)))
CvM = ( (U / (N*M)) / (N+M) ) - ((4*M*N - 1)/(6*(M+N)))
return(CvM)
}
|
/scratch/gouwar.j/cran-all/cranData/CDFt/R/CramerVonMisesTwoSamples.R
|
KolmogorovSmirnov <- function(S1, S2){
xS1=sort(S1)
cdftmp=ecdf(xS1)
cdf1=cdftmp(xS1)
xS2=sort(S2)
cdftmp=ecdf(xS2)
cdfEstim=cdftmp(xS2)
cdfRef=approx(xS1,cdf1,xS2,yleft=0,yright=1, ties='mean')
dif=cdfRef$y-cdfEstim
dif=abs(dif)
Ks=max(dif)
return(Ks)
}
|
/scratch/gouwar.j/cran-all/cranData/CDFt/R/KolmogorovSmirnov.R
|
## File Name: CDM_rbind_fill.R
## File Version: 0.04
CDM_rbind_fill <- function( x, y )
{
nx <- nrow(x)
ny <- nrow(y)
vars <- c( colnames(x), setdiff( colnames(y), colnames(x) ) )
z <- matrix( NA, nrow=nx+ny, ncol=length(vars) )
colnames(z) <- vars
z <- as.data.frame(z)
z[ 1:nx, colnames(x) ] <- x
z[ nx + 1:ny, colnames(y) ] <- y
return(z)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/CDM_rbind_fill.R
|
## File Name: CDM_require_namespace.R
## File Version: 0.08
CDM_require_namespace <- function(pkg)
{
if ( ! requireNamespace( pkg, quietly=TRUE) ){
stop( paste0("Package '", pkg, "' is needed for applying this
function. Please install it." ), call.=FALSE)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/CDM_require_namespace.R
|
## File Name: CDM_rmvnorm.R
## File Version: 0.03
CDM_rmvnorm <- function(n, mean=NULL, sigma, ...)
{
add_means <- FALSE
if ( missing(n) ){
n <- nrow(mean)
add_means <- TRUE
mean0 <- mean
mean <- rep(0,ncol(mean))
}
if (is.null(mean)){
mean <- rep(0,ncol(sigma) )
}
x <- mvtnorm::rmvnorm(n=n, mean=mean, sigma=sigma, ...)
if (n==1){
x <- as.vector(x)
}
if (add_means){
x <- x + mean0
}
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/CDM_rmvnorm.R
|
## File Name: IRT.IC.R
## File Version: 0.121
#--- information criteria
IRT.IC <- function( object )
{
ll <- logLik(object)
res <- c( ll, -2*ll, attr(ll, "df"), attr(ll,"nobs" ) )
names(res) <- c("loglike", "Deviance", "Npars", "Nobs" )
p <- Npars <- res["Npars"]
n <- res["Nobs"]
res["AIC"] <- -2*ll + 2*Npars
res["BIC"] <- -2*ll + log(n)*p
res["AIC3"] <- -2*ll + 3*Npars
res["AICc"] <- -2*ll + 2*p + 2*p*(p+1)/(n-p-1)
res["CAIC"] <- -2*ll + (log(n)+1)*p
#- add GHP if included
if ( !is.null(object$ic$GHP)){
res["GHP"] <- object$ic$GHP
}
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.IC.R
|
## File Name: IRT.RMSD.R
## File Version: 0.45
IRT.RMSD <- function(object)
{
CALL <- match.call()
mod <- object
mod_counts <- IRT.expectedCounts(mod)
G <- attr(mod_counts, "G" )
#--- item response probabilities
mod_irfprob <- IRT.irfprob(mod)
prob.theta <- attr(mod_irfprob, "prob.theta")
prob.theta <- matrix( prob.theta, ncol=G )
attr(mod_irfprob, "prob.theta") <- prob.theta
I <- dim(mod_counts)[1]
#*** create matrix with results
RMSD <- matrix( NA, nrow=I, ncol=G+1)
RMSD <- as.data.frame(RMSD)
colnames(RMSD) <- c("item", paste0("Group", 1:G) )
RMSD$item <- dimnames(mod_counts)[[1]]
RMSD_bc <- chisquare_stat <- MD <- MAD <- RMSD
RMSD$WRMSD <- NULL
# sample sizes per group
weight_group <- matrix( NA, nrow=I, ncol=G )
for (gg in 1:G){
mc_gg <- apply( mod_counts[,,,gg], c(1), sum )
weight_group[,gg] <- as.vector( mc_gg )
}
weight_group <- t( apply( weight_group, 1, FUN=function(ww){
ww / sum(ww) } ) )
# weight_group <- weight_group / sum( weight_group )
#*** extract objects
for (gg in 1:G){
pi.k <- attr(mod_irfprob, "prob.theta")[, gg, drop=FALSE ]
probs <- aperm( mod_irfprob, perm=c(3,1,2) )
n.ik <- aperm( mod_counts, perm=c(3,1,2,4) )[,,,gg,drop=FALSE]
#-- chi square calculation
chisquare_stat[,gg+1] <- rmsd_chisquare( n.ik=n.ik, pi.k=pi.k, probs=probs )
#-- RMSD calculations
res0 <- IRT_RMSD_calc_rmsd( n.ik=n.ik, pi.k=pi.k, probs=probs )
RMSD[,gg+1] <- res0$RMSD # RMSD
RMSD_bc[,gg+1] <- res0$RMSD_bc # RMSD_bc
#-- MD calculation
md_gg <- IRT_RMSD_calc_md( n.ik=n.ik, pi.k=pi.k, probs=probs )
MD[,gg+1] <- md_gg
#-- MAD calculation
MAD[,gg+1] <- res0$MAD # MAD
}
M1 <- rowSums( RMSD[,2:(G+1) ]^2 * weight_group, na.rm=TRUE )
RMSD$WRMSD <- sqrt( M1 )
M1 <- rowSums( RMSD_bc[,2:(G+1) ]^2 * weight_group, na.rm=TRUE )
RMSD_bc$WRMSD <- sqrt( M1 )
if ( G==1 ){
RMSD$WRMSD <- NULL
RMSD_bc$WRMSD <- NULL
}
#*** summaries of statistics
RMSD_summary <- dataframe_summary( dfr=RMSD, exclude_index=1,
labels=colnames(RMSD)[-1] )
RMSD_bc_summary <- dataframe_summary( dfr=RMSD_bc, exclude_index=1,
labels=colnames(RMSD_bc)[-1] )
MD_summary <- dataframe_summary( dfr=MD, exclude_index=1,
labels=colnames(MD)[-1] )
MAD_summary <- dataframe_summary( dfr=MAD, exclude_index=1,
labels=colnames(MAD)[-1] )
#*** output
res <- list( MD=MD, RMSD=RMSD, RMSD_bc=RMSD_bc, MAD=MAD,
chisquare_stat=chisquare_stat,
call=CALL, G=G, RMSD_summary=RMSD_summary,
RMSD_bc_summary=RMSD_bc_summary, MD_summary=MD_summary,
MAD_summary=MAD_summary)
class(res) <- "IRT.RMSD"
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.RMSD.R
|
## File Name: IRT.anova.R
## File Version: 0.09
###########################################
# general ANOVA function
IRT.anova <- function( object, ... )
{
cl <- match.call()
cl2 <- paste(cl)[-1]
if (length(list(object, ...)) !=2){
stop("anova method can only be applied for comparison of two models.\n")
}
objects <- list(object, ...)
model1a <- objects[[1]]
model2a <- objects[[2]]
model1 <- IRT.IC( model1a )
model2 <- IRT.IC( model2a )
dfr1 <- data.frame( "Model"=cl2[1],
"loglike"=model1["loglike"],
"Deviance"=-2*model1["loglike"] )
dfr1$Npars <- model1["Npars"]
dfr1$AIC <- model1["AIC"]
dfr1$BIC <- model1["BIC"]
dfr2 <- data.frame( "Model"=cl2[2],
"loglike"=model2["loglike"],
"Deviance"=-2*model2["loglike"] )
dfr2$Npars <- model2["Npars"]
dfr2$AIC <- model2["AIC"]
dfr2$BIC <- model2["BIC"]
dfr <- rbind( dfr1, dfr2 )
dfr <- dfr[ order( dfr$Npars ), ]
dfr$Chisq <- NA
dfr$df <- NA
dfr$p <- NA
dfr[1, "Chisq"] <- dfr[1,"Deviance"] - dfr[2,"Deviance"]
dfr[1, "df"] <- abs( dfr[1,"Npars"] - dfr[2,"Npars"] )
dfr[1, "p" ] <- round( 1 - stats::pchisq( dfr[1,"Chisq"], df=dfr[1,"df"] ), 5 )
for ( vv in 2:( ncol(dfr))){
dfr[,vv] <- round( dfr[,vv], 5 )
}
rownames(dfr) <- NULL
print(dfr)
invisible(dfr)
}
#######################################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.anova.R
|
## File Name: IRT.classify.R
## File Version: 0.05
IRT.classify <- function(object, type="MLE")
{
if (type=="MLE"){
like <- IRT.likelihood(object)
} else { # type=="MAP"
like <- IRT.posterior(object)
}
theta <- attr(like, "theta")
#-- individual classification
res <- cdm_rcpp_irt_classify_individuals( like=like )
class_index <- res$class_index
class_maxval <- res$class_maxval
class_theta <- theta[ class_index, ]
#--- output
res <- list( class_theta=class_theta, class_index=class_index,
class_maxval=class_maxval, type=type )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.classify.R
|
## File Name: IRT.compareModels.R
## File Version: 0.24
#--- compare models based on likelihood and information criteria
IRT.compareModels <- function( object, ... )
{
cl <- match.call()
cl1 <- paste(cl)[-c(1)]
object_list <- list(...)
#---- information criteria
irtmodfit <- FALSE
cm1 <- NULL
if ( length( grep("IRT.modelfit", class(object) ) ) > 0 ){
irtmodfit <- TRUE
cm1 <- c( cm1, object$objname )
} else {
cm1 <- c( cm1, cl1[1] )
}
if (irtmodfit){
dfr <- t(object$IRT.IC)
dfr <- as.data.frame(dfr)
statlist <- object$statlist
LS <- length(statlist)
for (ll in 1:LS){
dfr[, colnames(statlist)[ll] ] <- statlist[,ll]
}
} else {
dfr <- IRT.IC(object)
}
LO <- length(object_list)
#****************************
#**** loop over remaining objects
for (vv in 1:LO){
irtmodfit <- FALSE
if ( length( grep("IRT.modelfit", class(object_list[[vv]]) ) ) > 0 ){
irtmodfit <- TRUE
obj_vv <- object_list[[vv]]
cm1 <- c( cm1, obj_vv$objname )
} else {
cm1 <- c( cm1, cl1[vv+1] )
}
if ( irtmodfit ){
dfr1 <- t(obj_vv$IRT.IC)
dfr1 <- as.data.frame(dfr1)
statlist <- obj_vv$statlist
LS <- length(statlist)
for (ll in 1:LS){
dfr1[, colnames(statlist)[ll] ] <- statlist[,ll]
}
} else {
dfr1 <- IRT.IC( object_list[[vv]] )
}
if ( ! irtmodfit ){
dfr <- rbind( dfr, dfr1 )
}
if (irtmodfit ){
dfr <- CDM_rbind_fill( as.data.frame(dfr), as.data.frame(dfr1 ) )
}
}
rownames(dfr) <- NULL
dfr <- data.frame( "Model"=cm1, dfr )
IC <- dfr
# rownames(IC) <- paste(dfr$Model)
rownames(IC) <- NULL
res <- list("IC"=IC )
#--- collect all likelihood ratio tests
dfr <- NULL
M0 <- nrow(IC)
for (ii in 1:(M0-1) ){
for (jj in (ii+1):M0){
ii0 <- ii
jj0 <- jj
if ( IC[ii,"Npars" ] > IC[jj,"Npars"] ){
tt <- ii
ii0 <- jj
jj0 <- tt
}
if ( IC[ii,"Npars" ] !=IC[jj,"Npars"] ){
dfr1 <- data.frame( "Model1"=IC[ii0,"Model"], "Model2"=IC[jj0,"Model"] )
dfr1$Chi2 <- IC[ii0,"Deviance"] - IC[jj0,"Deviance"]
dfr1$df <- - ( IC[ii0,"Npars"] - IC[jj0,"Npars"] )
dfr1$p <- 1 - stats::pchisq( dfr1$Chi2, df=dfr1$df )
dfr <- rbind( dfr, dfr1 )
}
}
}
res$LRtest <- dfr
class(res) <- "IRT.compareModels"
return(res)
}
#--- summary method for IRT.compareModels
summary.IRT.compareModels <- function( object, extended=TRUE, ... )
{
dfr1 <- object$IC
if ( ! extended ){
vars <- c( "AICc", "CAIC", "maxX2", "MADQ3", "MADaQ3","SRMR" )
dfr1 <- dfr1[, ! (colnames(dfr1) %in% vars ) ]
}
cat("Absolute and relative model fit\n\n")
for ( vv in 2:(ncol(dfr1) ) ){
dfr1[,vv] <- round( dfr1[,vv], 3 )
}
print(dfr1, ...)
dfr2 <- object$LRtest
if ( ! is.null(dfr2) ){
cat("\nLikelihood ratio tests - model comparison \n\n")
obji <- object$LRtest
for (vv in seq(3,ncol(obji) ) ){
obji[,vv] <- round( obji[,vv], 4 )
}
print( obji)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.compareModels.R
|
## File Name: IRT.data.R
## File Version: 0.11
###########################################################
# extracts used dataset
IRT.data <- function(object, ...)
{
UseMethod("IRT.data")
}
###########################################################
IRT.data.din <- function( object, ... ){
dat <- object$dat
attr(dat,"weights") <- object$control$weights
attr(dat,"group") <- object$control$group
return(dat)
}
############################################################
IRT.data.gdina <- IRT.data.din
IRT.data.gdm <- IRT.data.din
IRT.data.mcdina <- IRT.data.din
IRT.data.slca <- IRT.data.din
#############################################################
IRT.data.reglca <- function( object, ... )
{
dat <- object$dat0
attr(dat,"weights") <- object$weights
attr(dat,"group") <- NULL
return(dat)
}
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.data.R
|
## File Name: IRT.derivedParameters.R
## File Version: 0.10
######################################################################
IRT.derivedParameters <- function( jkobject, derived.parameters )
{
object <- jkobject
parsM <- object$parsM
est <- object$jpartable$value
names(est) <- rownames(parsM)
parsM <- t(parsM)
allformulas <- derived.parameters[[1]]
FF <- length(derived.parameters)
if (FF>1){
for (ff in 2:FF){
t1 <- stats::terms( allformulas)
t2 <- paste( c( attr( t1, "term.labels" ),
attr( stats::terms( derived.parameters[[ff]] ), "term.labels" ) ),
collapse=" + " )
allformulas <- stats::as.formula( paste( " ~ 0 + ", t2 ) )
}
}
# create matrices of derived parameters
der.pars <- stats::model.matrix( allformulas, as.data.frame( t(est) ) )
colnames(der.pars) <- names(derived.parameters)
der.pars.rep <- stats::model.matrix( allformulas, as.data.frame( parsM) )
colnames(der.pars.rep) <- names(derived.parameters)
parsM <- t(der.pars.rep)
res0 <- jkestimates( est=as.vector(der.pars), parsM=parsM, fayfac=object$fayfac )
jpartable <- data.frame( "parnames"=names(derived.parameters),
"value"=as.vector(der.pars) )
jpartable$jkest <- res0$dfr$jkest
jpartable$jkse <- res0$dfr$jkse
res <- list( "parsM"=parsM, "vcov"=res0$vcov_pars,
"jpartable"=jpartable, "fayfac"=object$fayfac )
class(res) <- "IRT.jackknife"
return(res)
}
###############################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.derivedParameters.R
|
## File Name: IRT.expectedCounts.R
## File Version: 0.21
###########################################################
# extracts expected counts
IRT.expectedCounts <- function(object, ...)
{
UseMethod("IRT.expectedCounts")
}
###########################################################
###########################################################
# object of class gdm
IRT.expectedCounts.gdm <- function( object, ... )
{
ll <- aperm( object$n.ik, c(2,3,1,4) )
attr(ll,"theta") <- object$theta.k
attr(ll,"prob.theta") <- object$pi.k
attr(ll,"G") <- object$G
return(ll)
}
###########################################################
###########################################################
# object of class din
IRT.expectedCounts.din <- function( object, ... )
{
Ilj <- object$I.lj
D1 <- dim(Ilj)
ll <- array( 0, dim=c( D1[1], 2, D1[2], 1) )
ll[,2,,1] <- object$R.lj
ll[,1,,1] <- object$I.lj - object$R.lj
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt$class.prob
attr(ll,"G") <- 1
attr(ll,"dimnames")[[1]] <- colnames(object$dat)
return(ll)
}
###########################################################
###########################################################
# object of class gdina
IRT.expectedCounts.gdina <- function( object, ... )
{
G <- object$G
Ilj <- object$control$I.lj
D1 <- dim(Ilj)
ll <- array( 0, dim=c( D1[1], 2, D1[2], G ) )
if (G==1){
ll[,2,,1] <- object$control$R.lj
ll[,1,,1] <- Ilj - object$control$R.lj
}
if (G>1){
ll[,2,,] <- object$control$R.lj.gg
ll[,1,,] <- object$control$I.lj.gg - object$control$R.lj.gg
}
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt[, 1:object$G ]
attr(ll,"G") <- object$G
attr(ll,"dimnames")[[1]] <- colnames(object$dat)
return(ll)
}
############################################################
###########################################################
# object of class slca
IRT.expectedCounts.slca <- function( object, ... )
{
ll <- aperm( object$n.ik, c(2,3,1,4) )
res <- list( "delta"=object$delta,
"delta.designmatrix"=object$delta.designmatrix )
attr(ll,"skillspace") <- res
attr(ll,"prob.theta") <- object$pi.k
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class mcdina
IRT.expectedCounts.mcdina <- function( object, ... )
{
ll <- object$n.ik
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class reglca
IRT.expectedCounts.reglca <- function( object, ... )
{
ll <- aperm( object$n.ik, c(2,3,1,4) )
attr(ll,"theta") <- NA
attr(ll,"prob.theta") <- object$class_probs
attr(ll,"G") <- object$G
return(ll)
}
############################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.expectedCounts.R
|
## File Name: IRT.factor.scores.R
## File Version: 0.17
###########################################################
IRT.factor.scores <- function (object, ...)
{
UseMethod("IRT.factor.scores")
}
###########################################################
###########################################################
# object of class din
IRT.factor.scores.din <- function( object, type="MLE", ... )
{
patt1 <- object$pattern
K <- ncol( object$q.matrix )
N <- nrow( object$pattern )
make.split <- FALSE
if ( ! ( type %in% c("MLE","MAP","EAP") ) ){
stop("Requested type is not supported!\n")
}
ll <- matrix( 0, nrow=N, ncol=K )
if (type=="MLE"){
class1 <- paste(patt1$mle.est)
colnames(ll) <- paste0("MLE.skill", 1:K)
make.split <- TRUE
}
if (type=="MAP"){
class1 <- paste(patt1$map.est)
make.split <- TRUE
colnames(ll) <- paste0("MAP.skill", 1:K)
}
if (type=="EAP"){
ind <- grep( "attr", colnames(patt1) )
ll <- patt1[, ind ]
colnames(ll) <- paste0("EAP.skill", 1:K)
}
if ( make.split){
for (kk in 1:K){
ll[,kk] <- as.numeric(substring( class1, kk, kk ))
}
}
attr(ll,"type") <- type
return(ll)
}
###########################################################
###########################################################
# object of class gdina
IRT.factor.scores.gdina <- function( object, type="MLE", ... )
{
patt1 <- object$pattern
K <- ncol( object$q.matrix )
N <- nrow( object$pattern )
make.split <- FALSE
if ( ! ( type %in% c("MLE","MAP","EAP") ) ){
stop("Requested type is not supported!\n")
}
ll <- matrix( 0, nrow=N, ncol=K )
if (type=="MLE"){
class1 <- paste(patt1$mle.est)
colnames(ll) <- paste0("MLE.skill", 1:K)
make.split <- TRUE
}
if (type=="MAP"){
class1 <- paste(patt1$map.est)
colnames(ll) <- paste0("MAP.skill", 1:K)
make.split <- TRUE
}
if (type=="EAP"){
ind <- grep( "attr", colnames(patt1) )
ll <- patt1[, ind ]
colnames(ll) <- paste0("EAP.skill", 1:K)
}
if ( make.split){
for (kk in 1:K){
ll[,kk] <- as.numeric(substring( class1, kk, kk ))
}
}
attr(ll,"type") <- type
return(ll)
}
###########################################################
###########################################################
# object of class mcdina
IRT.factor.scores.mcdina <- function( object, type="MLE", ... )
{
if ( ! ( type %in% c("MLE","MAP","EAP") ) ){
stop("Requested type is not supported!\n")
}
if (type=="MLE"){
ll <- object$MLE.class
}
if (type=="MAP"){
ll <- object$MLE.class
}
if (type=="EAP"){
ll <- object$MLE.class
}
attr(ll,"type") <- type
return(ll)
}
###########################################################
###########################################################
# object of class gdm
IRT.factor.scores.gdm <- function( object, type="EAP", ... )
{
patt1 <- object$person
if ( ! ( type %in% c("MLE","MAP","EAP") ) ){
stop("Requested type is not supported!\n")
}
cn1 <- colnames(patt1)
if (type=="MLE"){
ind <- grep( "MLE", cn1 )
ll <- patt1[, ind, drop=FALSE ]
}
if (type=="MAP"){
ind <- grep( "MAP", cn1 )
ll <- patt1[, ind, drop=FALSE ]
}
if (type=="EAP"){
ind <- grep( "EAP", cn1 )
F2 <- length(ind)
ll <- patt1[, ind, drop=FALSE ]
}
attr(ll,"type") <- type
return(ll)
}
###########################################################
###########################################################
# object of class slca
IRT.factor.scores.slca <- function( object, type="MLE", ... )
{
if ( ! ( type %in% c("MLE","MAP") ) ){
stop("Requested type is not supported!\n")
}
if (type=="MLE"){
ll <- object$MLE.class
}
if (type=="MAP"){
ll <- object$MLE.class
}
attr(ll,"type") <- type
return(ll)
}
###########################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.factor.scores.R
|
## File Name: IRT.frequencies.R
## File Version: 0.05
###########################################################
# extracts used dataset
IRT.frequencies <- function(object, ...)
{
UseMethod("IRT.frequencies")
}
IRT_frequencies_wrapper <- function(object, ...)
{
data <- IRT.data(object=object)
weights <- attr(data, "weights")
post <- IRT.posterior(object=object)
probs <- IRT.irfprob(object=object)
res <- IRT_frequencies_default(data=data, post=post, probs=probs, weights=weights)
return(res)
}
IRT.frequencies.din <- IRT_frequencies_wrapper
IRT.frequencies.gdina <- IRT_frequencies_wrapper
IRT.frequencies.gdm <- IRT_frequencies_wrapper
IRT.frequencies.mcdina <- IRT_frequencies_wrapper
IRT.frequencies.slca <- IRT_frequencies_wrapper
#############################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.frequencies.R
|
## File Name: IRT.irfprob.R
## File Version: 0.18
###########################################################
# extracts the individual irfprob
IRT.irfprob <- function(object, ...)
{
UseMethod("IRT.irfprob")
}
###########################################################
###########################################################
# object of class din
IRT.irfprob.din <- function( object, ... )
{
ll <- object$pjk
dimnames(ll)[[1]] <- colnames(object$data)
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt$class.prob
attr(ll,"G") <- 1
return(ll)
}
###########################################################
###########################################################
# object of class gdina
IRT.irfprob.gdina <- function( object, ... )
{
ll <- object$pjk
dimnames(ll)[[1]] <- colnames(object$data)
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt[, 1:object$G ]
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class mcdina
IRT.irfprob.mcdina <- function( object, ... )
{
ll <- object$pik
dimnames(ll)[[1]] <- colnames(object$data)
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class gdm
IRT.irfprob.gdm <- function( object, ... )
{
ll <- aperm( object$pjk, c(2, 3, 1 ) )
dimnames(ll)[[1]] <- colnames(object$data)
attr(ll,"theta") <- object$theta.k
attr(ll,"prob.theta") <- object$pi.k
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class slca
IRT.irfprob.slca <- function( object, ... )
{
ll <- aperm( object$pjk, c(2, 3, 1 ) )
dimnames(ll)[[1]] <- colnames(object$data)
attr(ll,"theta") <- NA
res <- list( "delta"=object$delta,
"delta.designmatrix"=object$delta.designmatrix )
attr(ll,"skillspace") <- res
attr(ll,"prob.theta") <- object$pi.k
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class reglca
IRT.irfprob.reglca <- function( object, ... )
{
ll <- object$pjk
dimnames(ll)[[1]] <- colnames(object$data)
attr(ll,"theta") <- NA
attr(ll,"prob.theta") <- object$class_probs
attr(ll,"G") <- object$G
return(ll)
}
############################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.irfprob.R
|
## File Name: IRT.irfprobPlot.R
## File Version: 1.19
###################################################
# plot item response functions
# fitted object for which the class IRT.irfprob exists
IRT.irfprobPlot <- function( object, items=NULL,
min.theta=-4, max.theta=4, cumul=FALSE,
smooth=TRUE, ask=TRUE,
n.theta=40, package="lattice", ... )
{
if (package=="lattice"){
CDM_require_namespace("lattice")
}
#************************************
# extract item response functions
irfprob <- IRT.irfprob( object )
irfprob[ is.na(irfprob) ] <- 0
theta <- attr( irfprob, "theta" )
D <- ncol(theta)
if ( ! is.null( items) ){
irfprob <- irfprob[ items,,,drop=FALSE ]
}
items.labels <- dimnames(irfprob)[[1]]
I <- length(items.labels)
#***********************************
# theta grid
theta.grid <- seq( min.theta, max.theta, length=n.theta )
#***********************************
#**** plot
for (ii in 1:I){
# ii <- 1
irf.ii <- irfprob[ ii,,]
# compute maximum number of categories
rs <- rowSums( irf.ii, 1, na.rm=TRUE )
K <- sum( rs > 0 )
vv <- 0
for (dd in 1:D){
# dd <- 1
a1 <- stats::aggregate( irf.ii[2,], list(theta[,dd]), mean )
if ( stats::sd(a1[,2])> 1E-7 ){
vv <- dd
}
}
dd <- vv
# compute functions
irf1 <- t( irf.ii )
theta1 <- theta[,dd]
a1 <- stats::aggregate( irf1, list( theta1 ), mean )
theta1 <- a1[,1]
dfr <- NULL
dfr1 <- data.frame( "theta"=theta.grid )
# btheta <- bs( theta.grid )
# create data frame for plot in lattice
hh <- 1
if ( cumul ){ hh <- 2 }
for (kk in hh:K){
v1 <- as.numeric(a1[,kk+1])
if ( cumul ){
v1 <- rowSums( a1[, seq( kk+1, K+1), drop=FALSE] )
}
if ( smooth ){
eps <- 1E-5
v1 <- ( v1 + eps ) / ( 1 + 2*eps )
v1 <- stats::qlogis(v1)
dat <- data.frame( "theta"=theta1, "y"=v1 )
mod <- stats::loess( y ~ theta, data=dat)
ypred <- stats::plogis( stats::predict( mod, dfr1 ) )
} else {
ypred <- v1
theta.grid <- theta1
}
dfr1 <- data.frame( "theta"=theta.grid, "cat"=kk - 1, "prob"=ypred )
dfr <- rbind( dfr, dfr1 )
}
item <- items.labels[ii]
main <- paste0('Trace lines for item ', item, ' (Item ', ii, ')')
vkey <- paste0("Cat ", 0:(K-1) )
L1 <- K
#**************************************
# package lattice
if ( package=="lattice"){
print(
lattice::xyplot( prob ~ theta, data=dfr, group=cat, ylim=c(-.1, 1.1), type="o",
auto.key=TRUE,
par.settings=list(superpose.symbol=list(pch=1:L1)) ,
ylab=expression(P(theta)), xlab=expression(theta),
main=main, lty=1:L1, pch=1:L1,
...
)
)
}
#******************************************
# package graphics
if ( package=="graphics" ){
kk <- 0
dfr1a <- dfr[ dfr$cat==kk, ]
graphics::plot( dfr1a$theta, dfr1a$prob, ylim=c(-.1,1.1),
ylab=expression(P(theta)), xlab=expression(theta),
col=kk+2, pch=kk+1, type="o", main=main, ... )
for (kk in seq(1,K-1) ){
dfr1a <- dfr[ dfr$cat==kk, ]
graphics::lines( dfr1a$theta, dfr1a$prob, pch=kk+1, col=kk+2 )
graphics::points( dfr1a$theta, dfr1a$prob, pch=kk+1, col=kk+2 )
}
graphics::legend( min( dfr1a$theta), 1.1, vkey, pch=1:K, col=1 + 1:K,
horiz=TRUE, lty=1)
}
graphics::par( ask=ask )
}
}
######################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.irfprobPlot.R
|
## File Name: IRT.itemfit.R
## File Version: 0.08
###########################################################
IRT.itemfit <- function (object, ...)
{
UseMethod("IRT.itemfit")
}
###########################################################
###########################################################
# object of class din
IRT.itemfit.din <- function( object, method="RMSEA", ... )
{
if (method=="RMSEA"){
ll <- object$itemfit.rmsea
}
attr(ll,"method") <- method
return(ll)
}
###########################################################
###########################################################
# object of class gdina
IRT.itemfit.gdina <- function( object, method="RMSEA", ... )
{
if (method=="RMSEA"){
ll <- object$itemfit.rmsea
}
attr(ll,"method") <- method
return(ll)
}
###########################################################
###########################################################
# object of class gdm
IRT.itemfit.gdm <- function( object, method="RMSEA", ... )
{
if (method=="RMSEA"){
ll <- object$itemfit.rmsea$rmsea
names(ll) <- colnames(object$data)
}
attr(ll,"method") <- method
return(ll)
}
###########################################################
###########################################################
# object of class slca
IRT.itemfit.slca <- function( object, method="RMSEA", ... )
{
if (method=="RMSEA"){
n.ik <- object$n.ik
probs <- object$pjk
pi.k <- object$pi.k
ll <- itemfit.rmsea( n.ik, pi.k, probs )$rmsea
names(ll) <- colnames(object$data)
}
attr(ll,"method") <- method
return(ll)
}
###########################################################
###########################################################
# object of class reglca
IRT.itemfit.reglca <- function( object, method="RMSEA", ... )
{
if (method=="RMSEA"){
n.ik <- object$n.ik
probs <- aperm( object$pjk, perm=c(3,1,2))
pi.k <- object$class_probs
ll <- itemfit.rmsea( n.ik, pi.k, probs )$rmsea
names(ll) <- colnames(object$data)
}
attr(ll,"method") <- method
return(ll)
}
###########################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.itemfit.R
|
## File Name: IRT.jackknife.R
## File Version: 0.04
###########################################################
IRT.jackknife <- function (object, repDesign, ...)
{
UseMethod("IRT.jackknife")
}
###########################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.jackknife.R
|
## File Name: IRT.jackknife.gdina.R
## File Version: 0.26
###########################################################################
IRT.jackknife.gdina <- function( object, repDesign, ... )
{
rdes <- repDesign
# read control arguments
ctl <- object$control
# replicate weights
wgtrep <- repDesign$wgtrep
RR <- ncol(wgtrep)
# convert polychoric correlations
pcvec <- CDM.polychorList2vec(polychorList=object$polychor)
# assess modelfit
fmod <- IRT.modelfit( object )$modelfit.stat
fitvars <- c("MADcor","SRMSR", "100*MADRESIDCOV")
# read parameter table
partable <- object$partable
#**** create parameter table
jpartable <- partable
jpartable$skillclass <- jpartable$varyindex <- jpartable$fixed <-
jpartable$free <- jpartable$totindex <- jpartable$rule <- NULL
jpartable$group <- NULL
#---- polychoric correlation
dfr <- data.frame("partype"="polychor", "parindex"=NA, "item"=0,
"item.name"="", "parnames"=names(pcvec),
"value"=pcvec )
rownames(dfr) <- NULL
jpartable <- rbind( jpartable, dfr )
#----- model fit
dfr <- data.frame("partype"="modelfit", "parindex"=NA, "item"=0,
"item.name"="", "parnames"=fitvars,
"value"=fmod[ fitvars, "est" ] )
rownames(dfr) <- NULL
jpartable <- rbind( jpartable, dfr )
#---------------------------------------
# read control parameters for GDINA function
args1 <- c( "skillclasses", "q.matrix", "conv.crit",
"dev.crit", "maxit", "linkfct", "Mj",
"group","method","delta.designmatrix","delta.basispar.lower",
"delta.basispar.upper","delta.basispar.init","zeroprob.skillclasses",
"reduced.skillspace","HOGDINA","Z.skillspace",
"weights","rule", "increment.factor",
"fac.oldxsi","avoid.zeroprobs", "delta.fixed"
)
inputlist <- list( "data"=object$data,
"delta.init"=object$delta, "attr.prob.init"=ctl$attr.prob )
A1 <- length(args1)
for (vv in 1:A1){
a.vv <- args1[vv]
inputlist[[ a.vv ]] <- ctl[[ a.vv ]]
}
inputlist$progress <- FALSE
inputlist$calc.se <- FALSE
#-----------------------------------
# create jackknife parameter table
NP <- nrow(jpartable)
parsM <- matrix( NA, nrow=NP, ncol=RR)
rownames(parsM) <- jpartable$parnames
NP1 <- nrow( object$partable )
#*****************************************
# loop over datasets
# cat("0 |" )
for (rr in 1:RR){
if ( rr %% 10==1 ){
cat( paste0( "\n",rr-1, " |" ))
utils::flush.console()
}
inputlist$weights <- rdes$wgtrep[,rr]
mod1a <- do.call( gdina, inputlist )
# convert polychoric correlations
pcvec <- CDM.polychorList2vec(polychorList=mod1a$polychor)
# assess modelfit
fmod <- IRT.modelfit( mod1a)$modelfit.stat
parsM[ 1:NP1, rr ] <- mod1a$partable$value
parsM[ jpartable$partype=="polychor", rr ] <- pcvec
parsM[ jpartable$partype=="modelfit", rr ] <- fmod[ fitvars, "est" ]
cat("-") ; utils::flush.console()
if ( rr %% 10==0 ){
cat( paste0( "|" ))
utils::flush.console()
}
}
cat("\n")
fayfac <- rdes$fayfac
res0 <- jkestimates( est=jpartable$value, parsM, fayfac )
jpartable$jkest <- res0$dfr$jkest
jpartable$jkse <- res0$dfr$jkse
jpartable$t <- jpartable$jkest / jpartable$jkse
jpartable$p <- 2*stats::pnorm( - abs( jpartable$t ) )
res <- list( "parsM"=parsM, "vcov"=res0$vcov_pars,
"jpartable"=jpartable, "fayfac"=fayfac )
class(res) <- "IRT.jackknife"
return(res)
}
###########################################################################
summary.IRT.jackknife <- function( object, digits=3, ... )
{
obji <- object$jpartable
V1 <- which( colnames(obji)=="value" )
V2 <- ncol(obji)
for (vv in V1:V2){
obji[,vv] <- round( obji[,vv], digits )
}
print(obji)
}
################################################
coef.IRT.jackknife <- function( object, bias.corr=FALSE, ... )
{
obji <- object$jpartable
if ( bias.corr ){
vari <- "jkest"
} else {
vari <- "value"
}
vec <- obji[, vari ]
names(vec) <- obji$parnames
return(vec)
}
##################################################
vcov.IRT.jackknife <- function( object, ... )
{
return(object$vcov)
}
##################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.jackknife.gdina.R
|
## File Name: IRT.likelihood.R
## File Version: 0.20
###########################################################
# extracts the individual likelihood
IRT.likelihood <- function (object, ...)
{
UseMethod("IRT.likelihood")
}
###########################################################
#....................................
# How to remove attributes:
# l6 <- IRT.likelihood(mod1)
# attributes(l6) <- NULL
#....................................
###########################################################
# object of class din
IRT.likelihood.din <- function( object, ... )
{
ll <- object$like
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt$class.prob
attr(ll,"G") <- 1
return(ll)
}
###########################################################
###########################################################
# object of class gdina
IRT.likelihood.gdina <- function( object, ... )
{
ll <- object$like
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt[, 1:object$G ]
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class mcdina
IRT.likelihood.mcdina <- function( object, ... )
{
ll <- object$like
attr(ll,"theta") <- object$attribute.patt.splitted
attr(ll,"prob.theta") <- object$attribute.patt
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class gdm
IRT.likelihood.gdm <- function( object, ... )
{
ll <- object$p.xi.aj
attr(ll,"theta") <- object$theta.k
attr(ll,"prob.theta") <- object$pi.k
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class slca
IRT.likelihood.slca <- function( object, ... )
{
ll <- object$p.xi.aj
attr(ll,"theta") <- NA
res <- list( "delta"=object$delta,
"delta.designmatrix"=object$delta.designmatrix )
attr(ll,"skillspace") <- res
attr(ll,"prob.theta") <- object$pi.k
attr(ll,"G") <- object$G
return(ll)
}
############################################################
###########################################################
# object of class reglca
IRT.likelihood.reglca <- function( object, ... )
{
ll <- object$p.xi.aj
attr(ll,"theta") <- NA
attr(ll,"prob.theta") <- object$class_probs
attr(ll,"G") <- object$G
return(ll)
}
############################################################
|
/scratch/gouwar.j/cran-all/cranData/CDM/R/IRT.likelihood.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.