R/trxread.R

#' CTrax input utility
#'
#' Input function for \code{.mat} files generated by CTrax.
#' Creates a list object including experimental parameters and tracking data.
#'
#' Uses \code{readMat} from \code{\link{R.matlab}} to read the file.
#'
#' CTrax files exist in two very different formats depending on whether they have been processed
#' through the \code{fixerrors} GUI or not. This input function can read both but some data will
#' only be available for the latter (video info, framerate etc).
#'
#' @param trxfile filename: defaults to browsing window
#'
#' @return A list object containing a list of experimental details (\code{$exp}) and a data frame
#' of tracking data (\code{$trx}). \code{exp} contains the filename and, for \code{fixerrors}-processed
#' data, video filename, framerate, pixel size. \code{trx} always contains the same format of
#' tracking data with the columns \code{id}, \code{x}, \code{y}, \code{a}, \code{b}, \code{theta} and \code{time}.
#'
#' @export

trxread <- function (trxfile=file.choose())
  {
   trxdata<-R.matlab::readMat(trxfile)
   content<-names(trxdata)
   if ("trx" %in% content) {
        trx<-trxdata$trx[,1,]
	    items<-rownames(trx)
	    trxtable<-data.frame()
	    flies<-dim(trx)[2]
	    for (i in 1:flies)
		  {
		   thisfly<-trx[,i]
		   thistable<-with(thisfly,data.frame(t(id),t(x),t(y),t(a),t(b),t(theta),firstframe:endframe))
		   colnames(thistable)<-c("id","x","y","a","b","theta","time")
		   trxtable<-rbind(trxtable,thistable)
		  }
	    trxtable$id<-factor(trxtable$id)
	    exp<-list()
	    exp$moviename<-thisfly$moviename
	    exp$matname<-thisfly$matname
	    exp$filename<-trxfile
	    exp$fps<-thisfly$fps
	    exp$pxpermm<-thisfly$pxpermm
	    export<-list("exp"=exp,"trx"=trxtable)
	    return(export)
	    }
	else if ("ntargets" %in% content) {
		trxtable<-with(trxdata,data.frame("id"=identity,"x"=x.pos,"y"=y.pos,"a"=maj.ax,"b"=min.ax,"theta"=angle,"time"=rep(1:length(ntargets),ntargets)))
        exp<-list()
		exp$filename<-trxfile
		export<-list("exp"=exp,"trx"=trxtable)
        return(export)
	   }
		else print ("this is not a Ctrax file")
		return(NULL)
  }
PaolaCognigni/CTraxHelper documentation built on May 7, 2019, 11:57 p.m.