
#############################################
#  Sept 29, 2011
#  Authors: Vlad Makarov, Chris Yoon
#  Language: R
#  OS: UNIX/Linux, MAC OSX

#  Purpose:  generate ped file format from the genotype file and sample info file. Sample info file is a
#  three columns file as follows:
#  Sample - sample name
#  case_control - accepted values "case" or "control"
#  Gender accepted values "Female" or "Male"

#  Input:  genotype matrix file generated by the "genotype.py" script and the sample information file as above
#  Output: ped file


#  Arguments:
#  filename - name of VCF file, name of the sample file

#  Note:
#  Current script is rather memory intensive for large files


#  Example to run:
# Start up R
#  > source("ped_builder_prod.R")
#  > ped(matrixfile="matrix.txt", samfile='sample_info.txt')
#

##############################################


ped<-function(matrixfile, samfile){

    matr<-read.csv(file=matrixfile, header=TRUE, sep='\t',as.is=T)
    #Sample  case_control (case/control)   Gender (Female/Male)
    sam<-read.csv(file=samfile, header=TRUE, sep='\t',as.is=T)
    samples<-data.frame(samid=I(sam$Sample),class=I(sam$case_control), gender=I(sam$Gender))


    ## all samples
    samlist<-as.character(samples$samid)

    ## As R replaces the the column names starting with digit by "X" and "-" character by ".", replace them back
    ## to keep original samples names

    matrcols<-as.character(colnames(matr))
    matrcols<-gsub("^X", "", matrcols)
    matrcols<-gsub('\\.', "-", matrcols)
    names(matr) <- matrcols

    #in VCF file first 9 columns are information
    matr.t<-t(matr)

    ## generate placeholders
    FamilyID<-c(1:dim(matr.t)[1])
    IndividualID<-rep(1, dim(matr.t)[1])
    PaternalID<-rep(0, dim(matr.t)[1])
    MaternalID<-rep(0, dim(matr.t)[1])
    Sex<-rep(1, dim(matr.t)[1])
    Phenotype<-rep(1, dim(matr.t)[1])

    ## assign 2 for Female
    Sex[which(samples$gender=="Female")]<-2
    ## assign 2 for case, 1 stays for control
    Phenotype[which(samples$class=="case")]<-2

    ped<-data.frame(FamilyID, IndividualID, PaternalID, MaternalID, Sex, Phenotype, matr.t)

    write.table( ped, file = paste(matrixfile, '.ped', sep=''), append = FALSE, quote = FALSE, sep = "\t", eol = "\n", na = "NA", dec = ".", row.names = FALSE, col.names = FALSE, qmethod = c("escape", "double"))

}
