#!/usr/bin/env perl

use Getopt::Long;
use Pod::Usage;
use File::Basename;
use FindBin;
use lib $FindBin::RealBin;
use rsem_perl_utils qw(runCommand collectResults showVersionInfo);

use Env qw(@PATH);
@PATH = ($FindBin::RealBin, "$FindBin::RealBin/sam", @PATH);

use strict;
use warnings;

#const
my $BURNIN = 200;
my $NCV = 1000;
my $SAMPLEGAP = 1;
my $CONFIDENCE = 0.95;
my $NSPC = 50;

my $NMB = 1024; # default
my $SortMem = "1G"; # default as 1G per thread

my $status = 0;

my $read_type = 1; # default, single end with qual

my $bowtie_path = "";
my $C = 2;
my $E = 99999999;
my $L = 25;
my $maxHits = 200;
my $chunkMbs = 0;	# 0 = use bowtie default
my $phred33 = 0;
my $phred64 = 0;
my $solexa = 0;

my $is_sam = 0;
my $is_bam = 0;
my $fn_list = "";
my $tagName = "XM";

my $probF = 0.5;

my $minL = 1;
my $maxL = 1000;
my $mean = -1;
my $sd = 0;

my $estRSPD = 0;
my $B = 20;

my $nThreads = 1;
my $genBamF = 1;  # default is generating transcript bam file
my $genGenomeBamF = 0;
my $sampling = 0;
my $calcPME = 0;
my $calcCI = 0;
my $quiet = 0;
my $help = 0;

my $paired_end = 0;
my $no_qual = 0;
my $keep_intermediate_files = 0;

my $strand_specific = 0;

my $bowtie2 = 0;
my $bowtie2_path = "";
my $bowtie2_mismatch_rate = 0.1;
my $bowtie2_k = 200;
my $bowtie2_sensitivity_level = "sensitive"; # must be one of "very_fast", "fast", "sensitive", "very_sensitive"

my $seed = "NULL";

my $version = 0;

my $mTime = 0;
my ($time_start, $time_end, $time_alignment, $time_rsem, $time_ci) = (0, 0, 0, 0, 0);

my $mate1_list = "";
my $mate2_list = "";
my $inpF = "";

my ($refName, $sampleName, $sampleToken, $temp_dir, $stat_dir, $imdName, $statName) = ('') x 7;
my $gap = 32;

my $alleleS = 0;

my $star = 0;
my $star_path  = '';
my $gzipped_read_file = 0;
my $bzipped_read_file = 0;
my $output_star_genome_bam = 0;
my $sort_bam_by_read_name = 0;
my $sort_bam_buffer_size = '60G';
my $run_prsem = 0;
my $chipseq_target_read_files  = '';
my $chipseq_control_read_files = '';
my $chipseq_peak_file          = '';
my $partition_model            = 'pk';
my $chipseq_read_files_multi_targets = ''; ## read files for multiple targets
                                           ## delimited by comma
my $chipseq_bed_files_multi_targets = '';  ## BED files for multiple targets
                                           ## delimited by comma
my $cap_stacked_chipseq_reads = 0; ## for multiple targets, remove redundant 
                                   ## reads aligned to the same position
my $n_max_stacked_chipseq_reads = 5; ## as above

GetOptions("keep-intermediate-files" => \$keep_intermediate_files,
	   "temporary-folder=s" => \$temp_dir,
	   "no-qualities" => \$no_qual,
	   "paired-end" => \$paired_end,
	   "strand-specific" => \$strand_specific,
	   "sam" => \$is_sam,
	   "bam" => \$is_bam,
	   "sam-header-info=s" => \$fn_list,
	   "tag=s" => \$tagName,
	   "seed-length=i" => \$L,
	   "bowtie-path=s" => \$bowtie_path,
	   "bowtie-n=i" => \$C,
	   "bowtie-e=i" => \$E,
	   "bowtie-m=i" => \$maxHits,
	   "bowtie-chunkmbs=i" => \$chunkMbs,
	   "phred33-quals" => \$phred33,
	   "phred64-quals" => \$phred64, #solexa1.3-quals" => \$phred64,
	   "solexa-quals" => \$solexa,
	   "bowtie2" => \$bowtie2,
	   "bowtie2-path=s" => \$bowtie2_path,
	   "bowtie2-mismatch-rate=f" => \$bowtie2_mismatch_rate,
	   "bowtie2-k=i" => \$bowtie2_k,
	   "bowtie2-sensitivity-level=s" => \$bowtie2_sensitivity_level,
	   "forward-prob=f" => \$probF,
	   "fragment-length-min=i" => \$minL,
	   "fragment-length-max=i" => \$maxL,
	   "fragment-length-mean=f" => \$mean,
	   "fragment-length-sd=f" => \$sd,
	   "estimate-rspd" => \$estRSPD,
	   "num-rspd-bins=i" => \$B,
	   "p|num-threads=i" => \$nThreads,
	   "no-bam-output" => sub { $genBamF = 0; },
	   "output-genome-bam" => \$genGenomeBamF,
	   "sampling-for-bam" => \$sampling,
	   "calc-pme" => \$calcPME,
	   "gibbs-burnin=i" => \$BURNIN,
	   "gibbs-number-of-samples=i" => \$NCV,
	   "gibbs-sampling-gap=i", \$SAMPLEGAP,
	   "calc-ci" => \$calcCI,
	   "ci-credibility-level=f" => \$CONFIDENCE,
	   "ci-memory=i" => \$NMB,
	   "ci-number-of-samples-per-count-vector=i" => \$NSPC,
	   "samtools-sort-mem=s" => \$SortMem,
	   'star' => \$star,
	   'star-path=s' => \$star_path,
	   "gzipped-read-file" => \$gzipped_read_file,
	   "bzipped-read-file" => \$bzipped_read_file,
	   "output-star-genome-bam" => \$output_star_genome_bam,
	   "sort-bam-by-read-name" => \$sort_bam_by_read_name,
	   "sort-bam-buffer-size=s" => \$sort_bam_buffer_size,
	   "seed=i" => \$seed,
	   'run-pRSEM' => \$run_prsem,
	   'chipseq-target-read-files=s' => \$chipseq_target_read_files, 
	                                      ## delimited by comma if more than one
	   'chipseq-control-read-files=s' => \$chipseq_control_read_files, 
	                                      ## delimited by comma if more than one
     'chipseq-read-files-multi-targets=s' => \$chipseq_read_files_multi_targets,
                                          ## delimited by comma
     'chipseq-bed-files-multi-targets=s' => \$chipseq_bed_files_multi_targets,
                                         ## delimited by comma
     'cap-stacked-chipseq-reads' => \$cap_stacked_chipseq_reads,
     'n-max-stacked-chipseq-reads=i' => \$n_max_stacked_chipseq_reads,
	   'chipseq-peak-file=s' => \$chipseq_peak_file,
	   'partition-model=s' => \$partition_model,
	   "time" => \$mTime,
	   "version" => \$version,
	   "q|quiet" => \$quiet,
	   "h|help" => \$help) or pod2usage(-exitval => 2, -verbose => 2);

pod2usage(-verbose => 2) if ($help == 1);
&showVersionInfo($FindBin::RealBin) if ($version == 1);

#check parameters and options

if ($is_sam || $is_bam) {
    pod2usage(-msg => "Invalid number of arguments!", -exitval => 2, -verbose => 2) if (scalar(@ARGV) != 3);
    pod2usage(-msg => "--sam and --bam cannot be active at the same time!", -exitval => 2, -verbose => 2) if ($is_sam == 1&& $is_bam == 1);
    pod2usage(-msg => "--bowtie-path, --bowtie-n, --bowtie-e, --bowtie-m, --phred33-quals, --phred64-quals, --solexa-quals, --bowtie2, --bowtie2-path, --bowtie2-mismatch-rate, --bowtie2-k and --bowtie2-sensitivity-level cannot be set if input is SAM/BAM format!", -exitval => 2, -verbose => 2) if ($bowtie_path ne "" || $C != 2 || $E != 99999999 || $maxHits != 200 || $phred33 || $phred64 || $solexa || $bowtie2 || $bowtie2_path ne "" || $bowtie2_mismatch_rate != 0.1 || $bowtie2_k != 200 || $bowtie2_sensitivity_level ne "sensitive");
}
else {
    pod2usage(-msg => "Invalid number of arguments!", -exitval => 2, -verbose => 2) if (!$paired_end && scalar(@ARGV) != 3 || $paired_end && scalar(@ARGV) != 4);    
    pod2usage(-msg => "If --no-qualities is set, neither --phred33-quals, --phred64-quals or --solexa-quals can be active!", -exitval => 2, -verbose => 2) if ($no_qual && ($phred33 + $phred64 + $solexa > 0));
    pod2usage(-msg => "Only one of --phred33-quals, --phred64-quals, and --solexa-quals can be active!", -exitval => 2, -verbose => 2) if ($phred33 + $phred64 + $solexa > 1);    
    pod2usage(-msg => "--sam , --bam or --sam-header-info cannot be set if use bowtie/bowtie2 aligner to produce alignments!", -exitval => 2, -verbose => 2) if ($is_sam || $is_bam || $fn_list ne "");
    pod2usage(-msg => "--bowtie2-path, --bowtie2-mismatch-rate, --bowtie2-k and --bowtie2-sensitivity-level cannot be set if bowtie aligner is used!", -exitval => 2, -verbose => 2) if (!$bowtie2 && ($bowtie2_path ne "" || $bowtie2_mismatch_rate != 0.1 || $bowtie2_k != 200 || $bowtie2_sensitivity_level ne "sensitive"));
    pod2usage(-msg => "--bowtie-path, --bowtie-n, --bowtie-e, --bowtie-m cannot be set if bowtie2 aligner is used!", -exitval => 2, -verbose => 2) if ($bowtie2 && ($bowtie_path ne "" || $C != 2 || $E != 99999999 || $maxHits != 200));
    pod2usage(-msg => "Mismatch rate must be within [0, 1]!", -exitval => 2, -verbose => 2) if ($bowtie2 && ($bowtie2_mismatch_rate < 0.0 || $bowtie2_mismatch_rate > 1.0));
    pod2usage(-msg => "Sensitivity level must be one of \"very_fast\", \"fast\", \"sensitive\", and \"very_sensitive\"!", -exitval => 2, -verbose => 2) if ($bowtie2 && (($bowtie2_sensitivity_level ne "very_fast") && ($bowtie2_sensitivity_level ne "fast") && ($bowtie2_sensitivity_level ne "sensitive") && ($bowtie2_sensitivity_level ne "very_sensitive"))); 
}

pod2usage(-msg => "Forward probability should be in [0, 1]!", -exitval => 2, -verbose => 2) if ($probF < 0 || $probF > 1);
pod2usage(-msg => "Min fragment length should be at least 1!", -exitval => 2, -verbose => 2) if ($minL < 1);
pod2usage(-msg => "Min fragment length should be smaller or equal to max fragment length!", -exitval => 2, -verbose => 2) if ($minL > $maxL);
pod2usage(-msg => "The memory allocated for calculating credibility intervals should be at least 1 MB!\n", -exitval => 2, -verbose => 2) if ($NMB < 1);
pod2usage(-msg => "Number of threads should be at least 1!\n", -exitval => 2, -verbose => 2) if ($nThreads < 1);
pod2usage(-msg => "Seed length should be at least 5!\n", -exitval => 2, -verbose => 2) if ($L < 5);
pod2usage(-msg => "--sampling-for-bam cannot be specified if --no-bam-output is specified!\n", -exitval => 2, -verbose => 2) if ($sampling && !$genBamF);
pod2usage(-msg => "--output-genome-bam cannot be specified if --no-bam-output is specified!\n", -exitval => 2, -verbose => 2) if ($genGenomeBamF && !$genBamF);
pod2usage(-msg => "The seed for random number generator must be a non-negative 32bit integer!\n", -exitval => 2, -verbose => 2) if (($seed ne "NULL") && ($seed < 0 || $seed > 0xffffffff));
pod2usage(-msg => "The credibility level should be within (0, 1)!\n", -exitval => 2, -verbose => 2) if ($CONFIDENCE <= 0.0 || $CONFIDENCE >= 1.0);
pod2usage(-msg => "Gzipped read files can only be used for aligner STAR\n", -exitval=>2, -verbose =>2) if ( ( $star == 0 ) && ( $gzipped_read_file != 0));
pod2usage(-msg => "Bzipped read files can only be used for aligner STAR\n", -exitval=>2, -verbose =>2) if ( ( $star == 0 ) && ( $bzipped_read_file != 0));

if ( $run_prsem ) {
  my $msg = '';
  if ( ( $chipseq_peak_file eq '' ) && 
       ( ( $chipseq_target_read_files eq ''  ) || 
         ( $chipseq_control_read_files eq '' ) || 
         ( $bowtie_path eq '' ) ) && 
       ( ( $chipseq_read_files_multi_targets eq '' ) ||
         ( $bowtie_path eq '' ) ) &&
       ( $chipseq_bed_files_multi_targets eq '' )
     ) {
    $msg = "please define one set of the following options to run pRSEM:\n" .
           "1. --chipseq-peak-file <string>\n" .
           "2. --chipseq-target-read-files <string> and\n" .
           "   --chipseq-control-read-files <string> and\n" .
           "   --bowtie-path <path>\n" .
           "3. --chipseq-read-files-multi-targets <string> and\n" .
           "   --bowtie-path <path>\n" .
           "4. --chipseq-bed-files-multi-targets <string>\n";
  }

  my @prsem_partition_models = ( 
     'pk', 'pk_lgtnopk', 
     'lm3', 'lm4', 'lm5', 'lm6',
     'nopk_lm2pk', 'nopk_lm3pk', 'nopk_lm4pk', 'nopk_lm5pk',
     'pk_lm2nopk', 'pk_lm3nopk', 'pk_lm4nopk', 'pk_lm5nopk',
     'cmb_lgt'
  );

  my %prtmdl2one = ();
  foreach my $prtmdl (@prsem_partition_models) {
    $prtmdl2one{$prtmdl} = 1;
  }

  if ( exists $prtmdl2one{$partition_model} ) {
    if ( ( $partition_model eq 'cmb_lgt' ) && 
         ( ( $chipseq_read_files_multi_targets eq '' ) &&
           ( $chipseq_bed_files_multi_targets  eq '' ) ) ){
      $msg = 'either --chipseq-read-files-multi-targets <string> or ' .
             '--chipseq-bed-files-multi-targets <string> needs to be ' .
             "defined for pRSEM's partition model: '$partition_model'";
    } elsif ( ( $partition_model ne 'pk' ) && 
              ( $partition_model ne 'cmb_lgt' ) &&
              ( ( $chipseq_target_read_files eq ''  ) || 
                ( $chipseq_control_read_files eq '' ) || 
                ( $bowtie_path eq '' ) ) ){
      $msg = '--chipseq-target-read-files <string> and ' .
             '--chipseq-control-read-files <string> and ' .
             '--bowtie-path <path> need to be defined for ' .
             "pRSEM's partition model: '$partition_model'";
    }
  } else {
    $msg = '--partition-model <string> must be one of [' .
           join(', ', @prsem_partition_models) . "]";
  }

  if ( $msg ne '' ) {
    pod2usage(-msg => "$msg\n", -exitval => 2, -verbose => 2);
  }

  if ( ( $partition_model ne 'cmb_lgt' ) && 
       ( ( $chipseq_read_files_multi_targets ne '' ) || 
         ( $chipseq_bed_files_multi_targets  ne '' ) ) ) {
    print "\nCombining signals from multiple sources, partition model is set to 'cmb_lgt'\n\n";
    $partition_model = 'cmb_lgt';
  }
}


if ($L < 25) { print "Warning: the seed length set is less than 25! This is only allowed if the references are not added poly(A) tails.\n"; }

if ($strand_specific) { $probF = 1.0; }

if ($paired_end) {
    if ($no_qual) { $read_type = 2; }
    else { $read_type = 3; }
}
else {
    if ($no_qual) { $read_type = 0; }
    else { $read_type = 1; }
}

if (scalar(@ARGV) == 3) {
    if ($is_sam || $is_bam) { $inpF = $ARGV[0]; } 
    else {$mate1_list = $ARGV[0]; }
    $refName = $ARGV[1];
    $sampleName = $ARGV[2];
}
else {
    $mate1_list = $ARGV[0];
    $mate2_list = $ARGV[1];
    $refName = $ARGV[2];
    $sampleName = $ARGV[3];
}

if (((-e "$refName.ta") && !(-e "$refName.gt")) || (!(-e "$refName.ta") && (-e "$refName.gt"))) {
    print "Allele-specific expression related reference files are corrupted!\n";
    exit(-1);
}

$alleleS = (-e "$refName.ta") && (-e "$refName.gt");

if ($genGenomeBamF) {
    open(INPUT, "$refName.ti");
    my $line = <INPUT>; chomp($line);
    close(INPUT);
    my ($M, $type) = split(/ /, $line);
    pod2usage(-msg => "No genome information provided, so genome bam file cannot be generated!\n", -exitval => 2, -verbose => 2) if ($type != 0);
}

my $pos = rindex($sampleName, '/');
if ($pos < 0) { $sampleToken = $sampleName; }
else { $sampleToken = substr($sampleName, $pos + 1); }

if ($temp_dir eq "") { $temp_dir = "$sampleName.temp"; }
$stat_dir = "$sampleName.stat";

if (!(-d $temp_dir) && !mkdir($temp_dir)) { print "Fail to create folder $temp_dir.\n"; exit(-1); }
if (!(-d $stat_dir) && !mkdir($stat_dir)) { print "Fail to create folder $stat_dir.\n"; exit(-1); }

$imdName = "$temp_dir/$sampleToken";
$statName = "$stat_dir/$sampleToken";

if (!$is_sam && !$is_bam && !$no_qual && ($phred33 + $phred64 + $solexa == 0)) { $phred33 = 1; }

my ($mate_minL, $mate_maxL) = (1, $maxL);

if ($bowtie_path ne "") { $bowtie_path .= "/"; }
if ($bowtie2_path ne "") { $bowtie2_path .= "/"; }
if ($star_path ne '') { $star_path .= '/'; }

my $command = "";

if (!$is_sam && !$is_bam) {
	if ( $star ) {
	  ## align reads by STAR
    my $star_genome_path = dirname($refName);
	  $command = "$star_path/STAR " . 
	               ## ENCODE3 pipeline parameters
	               " --genomeDir $star_genome_path " .
	               ' --outSAMunmapped Within ' .
	               ' --outFilterType BySJout ' .
	               ' --outSAMattributes NH HI AS NM MD ' .
	               ' --outFilterMultimapNmax 20 ' .
	               ' --outFilterMismatchNmax 999 ' .
	               ' --outFilterMismatchNoverLmax 0.04 ' .
	               ' --alignIntronMin 20 ' .
	               ' --alignIntronMax 1000000 ' .
	               ' --alignMatesGapMax 1000000 ' .
	               ' --alignSJoverhangMin 8 ' .
	               ' --alignSJDBoverhangMin 1 ' .
	               ' --sjdbScore 1 ' .
	               " --runThreadN $nThreads " .
	               ##
	
	               ## different than ENCODE3 pipeline 
	               ## do not allow using shared memory
	               ' --genomeLoad NoSharedMemory ' .
	               ##
	
	               ## different than ENCODE3 pipeline, which sorts output BAM
	               ## no need to do it here to save time and memory 
	               ' --outSAMtype BAM Unsorted ' .
	               ##
	
	               ## unlike ENCODE3, we don't output bedGraph files
	
	               ' --quantMode TranscriptomeSAM '.
	               ' --outSAMheaderHD \@HD VN:1.4 SO:unsorted '.
	
	               ## define output file prefix
	               " --outFileNamePrefix $imdName ";
	               ##
	
	  if ( $gzipped_read_file ) {
	    $command .= ' --readFilesCommand zcat ';
	  } elsif ( $bzipped_read_file ) {
	    $command .= ' --readFilesCommand bzcat ';
	  }
	
	  if ( $read_type == 0 || $read_type == 1 ) {
	    $command .= " --readFilesIn $mate1_list ";
	  } else {
	    $command .= " --readFilesIn $mate1_list $mate2_list";
	  }
	
	} elsif (!$bowtie2) {
	$command = $bowtie_path."bowtie";
	if ($no_qual) { $command .= " -f"; }
	else { $command .= " -q"; }
    
	if ($phred33) { $command .= " --phred33-quals"; }
	elsif ($phred64) { $command .= " --phred64-quals"; }
	elsif ($solexa) { $command .= " --solexa-quals"; }
    
	$command .= " -n $C -e $E -l $L";
	if ($read_type == 2 || $read_type == 3) { $command .= " -I $minL -X $maxL"; }
	if ($chunkMbs > 0) { $command .= " --chunkmbs $chunkMbs"; }
	
	if ($strand_specific || $probF == 1.0) { $command .= " --norc"; }
	elsif ($probF == 0.0) { $command .= " --nofw"; }
	
	$command .= " -p $nThreads -a -m $maxHits -S";
	if ($quiet) { $command .= " --quiet"; }    

	$command .= " $refName";
	if ($read_type == 0 || $read_type == 1) {
	    $command .= " $mate1_list"; 
	}
	else {
	    $command .= " -1 $mate1_list -2 $mate2_list";
	}

	# pipe to samtools to generate a BAM file
	$command .= " | samtools view -S -b -o $imdName.bam -";
    }
    else {
	$command = $bowtie2_path."bowtie2";
	if ($no_qual) { $command .= " -f"; }
	else { $command .= " -q"; }

	if ($phred33) { $command .= " --phred33"; }
	elsif ($phred64) { $command .= " --phred64"; }
	elsif ($solexa) { $command .= " --solexa-quals"; }

	if ($bowtie2_sensitivity_level eq "very_fast") { $command .= " --very-fast"; }
	elsif ($bowtie2_sensitivity_level eq "fast") { $command .= " --fast"; }
	elsif ($bowtie2_sensitivity_level eq "sensitive") { $command .= " --sensitive"; }
	else { $command .= " --very-sensitive"; }

	$command .= " --dpad 0 --gbar 99999999 --mp 1,1 --np 1 --score-min L,0,-$bowtie2_mismatch_rate";  

	if ($read_type == 2 || $read_type == 3) { $command .= " -I $minL -X $maxL --no-mixed --no-discordant"; }

	if ($strand_specific || $probF == 1.0) { $command .= " --norc"; }
	elsif ($probF == 0.0) { $command .= " --nofw"; }
	
	$command .= " -p $nThreads -k $bowtie2_k";
	if ($quiet) { $command .= " --quiet"; }    

	$command .= " -x $refName";
	if ($read_type == 0 || $read_type == 1) {
	    $command .= " -U $mate1_list"; 
	}
	else {
	    $command .= " -1 $mate1_list -2 $mate2_list";
	}

	# pipe to samtools to generate a BAM file
	$command .= " | samtools view -S -b -o $imdName.bam -";
    }

    if ($mTime) { $time_start = time(); }

    &runCommand($command);

    if ($mTime) { $time_end = time(); $time_alignment = $time_end - $time_start; }

    $inpF = "$imdName.bam";
    $is_bam = 1; # alignments are outputed as a BAM file

    if ( $star ) {
      my $star_tr_bam = $imdName . 'Aligned.toTranscriptome.out.bam';
      rename $star_tr_bam, $inpF
        or die "can't rename $star_tr_bam to $inpF: $!\n";
      rmdir $imdName . "_STARtmp/";
      my $star_genome_bam = $imdName . "Aligned.out.bam";
      my $rsem_star_genome_bam = $sampleName.'.STAR.genome.bam';
      if ( $output_star_genome_bam ) {
        rename $star_genome_bam, $rsem_star_genome_bam or die 
          "can't move $star_genome_bam to $rsem_star_genome_bam: $!\n";
      } else {
        unlink $star_genome_bam or die "can't remove $star_genome_bam: $!\n";
      }
    }
}

if ( $sort_bam_by_read_name ) {
  my $sorted_bam = "$imdName.mateSorted.bam";
  my $sort_workdir = dirname($imdName);
  $command = "cat <( samtools view -H $inpF ) " .
                 "<( samtools view -@ $nThreads $inpF | " .
                 q(awk '{printf "%s ", $0; getline; print}' | ) .
                 "sort -S $sort_bam_buffer_size -T $sort_workdir | " .
                 q(tr ' ' '\n' ) .
                 ") | samtools view -@ $nThreads -bS - > $sorted_bam"; 

  print "$command\n\n";

  ## have to invoke BASH to use the <()<() substitutions
  ## have to use LIST to invoke BASE
  system( ('bash', '-c', $command) );

  rename $sorted_bam, $inpF or die "can't rename $sorted_bam to $inpF: $!\n";
}

if ($mTime) { $time_start = time(); }

$command = "rsem-parse-alignments $refName $imdName $statName";

my $samInpType;
if ($is_sam) { $samInpType = "s"; } 
elsif ($is_bam) { $samInpType = "b"; }

$command .= " $samInpType $inpF -t $read_type";
if ($fn_list ne "") { $command .= " -l $fn_list"; }
if ($tagName ne "") { $command .= " -tag $tagName"; }
if ($quiet) { $command .= " -q"; }

&runCommand($command);

$command = "rsem-build-read-index $gap"; 
if ($read_type == 0) { $command .= " 0 $quiet $imdName\_alignable.fa"; }
elsif ($read_type == 1) { $command .= " 1 $quiet $imdName\_alignable.fq"; }
elsif ($read_type == 2) { $command .= " 0 $quiet $imdName\_alignable_1.fa $imdName\_alignable_2.fa"; }
elsif ($read_type == 3) { $command .= " 1 $quiet $imdName\_alignable_1.fq $imdName\_alignable_2.fq"; }
else { print "Impossible! read_type is not in [1,2,3,4]!\n"; exit(-1); }
&runCommand($command);

my $doesOpen = open(OUTPUT, ">$imdName.mparams");
if ($doesOpen == 0) { print "Cannot generate $imdName.mparams!\n"; exit(-1); }
print OUTPUT "$minL $maxL\n";
print OUTPUT "$probF\n";
print OUTPUT "$estRSPD\n";
print OUTPUT "$B\n";
print OUTPUT "$mate_minL $mate_maxL\n";
print OUTPUT "$mean $sd\n";
print OUTPUT "$L\n";
close(OUTPUT);  

my @seeds = ();
if ($seed ne "NULL") { 
    srand($seed); 
    for (my $i = 0; $i < 3; $i++) {
	push(@seeds, int(rand(1 << 32))); 
    }
}

$command = "rsem-run-em $refName $read_type $sampleName $imdName $statName -p $nThreads";
if ($genBamF) { 
    $command .= " -b $samInpType $inpF";
    if ($fn_list ne "") { $command .= " 1 $fn_list"; }
    else { $command .= " 0"; }
    if ($sampling) { $command .= " --sampling"; }
    if ($seed ne "NULL") { $command .= " --seed $seeds[0]"; }
}
if ($calcPME || $calcCI) { $command .= " --gibbs-out"; }
if ($quiet) { $command .= " -q"; }

&runCommand($command);

if ($alleleS) {
    &collectResults("allele", "$imdName.allele_res", "$sampleName.alleles.results"); # allele level
    &collectResults("isoform", "$imdName.iso_res", "$sampleName.isoforms.results"); # isoform level
    &collectResults("gene", "$imdName.gene_res", "$sampleName.genes.results"); # gene level
} 
else {
    &collectResults("isoform", "$imdName.iso_res", "$sampleName.isoforms.results"); # isoform level
    &collectResults("gene", "$imdName.gene_res", "$sampleName.genes.results"); # gene level
}

if ($genBamF) {
    $command = "samtools sort -@ $nThreads -m $SortMem $sampleName.transcript.bam $sampleName.transcript.sorted";
    &runCommand($command);
    $command = "samtools index $sampleName.transcript.sorted.bam";
    &runCommand($command);

    if ($genGenomeBamF) {
	$command = "rsem-tbam2gbam $refName $sampleName.transcript.bam $sampleName.genome.bam";
	&runCommand($command);
	$command = "samtools sort -@ $nThreads -m $SortMem $sampleName.genome.bam $sampleName.genome.sorted";
	&runCommand($command);
	$command = "samtools index $sampleName.genome.sorted.bam";
	&runCommand($command);
    }
}

if ($mTime) { $time_end = time(); $time_rsem = $time_end - $time_start; }

if ($mTime) { $time_start = time(); }

if ($calcPME || $calcCI ) {
    $command = "rsem-run-gibbs $refName $imdName $statName $BURNIN $NCV $SAMPLEGAP";
    $command .= " -p $nThreads";
    if ($seed ne "NULL") { $command .= " --seed $seeds[1]"; }
    if ($quiet) { $command .= " -q"; }
    &runCommand($command);
}

if ($calcPME || $calcCI) {
    if ($alleleS) {
	system("mv $sampleName.alleles.results $imdName.alleles.results.bak1");
	system("mv $sampleName.isoforms.results $imdName.isoforms.results.bak1");
	system("mv $sampleName.genes.results $imdName.genes.results.bak1");
	&collectResults("allele", "$imdName.allele_res", "$sampleName.alleles.results"); # allele level
	&collectResults("isoform", "$imdName.iso_res", "$sampleName.isoforms.results"); # isoform level
	&collectResults("gene", "$imdName.gene_res", "$sampleName.genes.results"); # gene level
    }
    else {
	system("mv $sampleName.isoforms.results $imdName.isoforms.results.bak1");
	system("mv $sampleName.genes.results $imdName.genes.results.bak1");
	&collectResults("isoform", "$imdName.iso_res", "$sampleName.isoforms.results"); # isoform level
	&collectResults("gene", "$imdName.gene_res", "$sampleName.genes.results"); # gene level
    }
}

if ($calcCI) {
    $command = "rsem-calculate-credibility-intervals $refName $imdName $statName $CONFIDENCE $NCV $NSPC $NMB";
    $command .= " -p $nThreads";
    if ($seed ne "NULL") { $command .= " --seed $seeds[2]"; }
    if ($quiet) { $command .= " -q"; }
    &runCommand($command);

    if ($alleleS) {
	system("mv $sampleName.alleles.results $imdName.alleles.results.bak2");
	system("mv $sampleName.isoforms.results $imdName.isoforms.results.bak2");
	system("mv $sampleName.genes.results $imdName.genes.results.bak2");
	&collectResults("allele", "$imdName.allele_res", "$sampleName.alleles.results"); # allele level
	&collectResults("isoform", "$imdName.iso_res", "$sampleName.isoforms.results"); # isoform level
	&collectResults("gene", "$imdName.gene_res", "$sampleName.genes.results"); # gene level
    }
    else {
	system("mv $sampleName.isoforms.results $imdName.isoforms.results.bak2");
	system("mv $sampleName.genes.results $imdName.genes.results.bak2");
	&collectResults("isoform", "$imdName.iso_res", "$sampleName.isoforms.results"); # isoform level
	&collectResults("gene", "$imdName.gene_res", "$sampleName.genes.results"); # gene level
    }
}

if ($mTime) { $time_end = time(); $time_ci = $time_end - $time_start; }

if ($mTime) { $time_start = time(); }

## To-do: only run gibbs sampling once, either for pRSEM or uniform prior 1
if ( $run_prsem ) {
  $command = "$FindBin::RealBin/pRSEM/prsem-calculate-expression " .
             " --num-threads $nThreads " .
             " --partition-model $partition_model " .
             " --gibbs-burnin $BURNIN " .
             " --gibbs-number-of-samples $NCV " .
             " --gibbs-sampling-gap $SAMPLEGAP ";
  ####

  ##  ChIP-seq peak file from single source
  if ( $chipseq_peak_file ne '') { ## only for partition model pk
                                   ## need to add sanity check!!
    $command .= " --chipseq-peak-file $chipseq_peak_file";
  } elsif ( $partition_model eq 'cmb_lgt' ) {  ## multi-sources
    if ( $chipseq_bed_files_multi_targets ne '' ) { ## use bed over read
      $command .= ' --chipseq-bed-files-multi-targets ' . 
                    $chipseq_bed_files_multi_targets;
    } elsif ( $chipseq_read_files_multi_targets ne '' ) { 
      $command .= ' --chipseq-read-files-multi-targets ' .
                    $chipseq_read_files_multi_targets .
                  " --bowtie-path $bowtie_path" ;
    }
    if ( $cap_stacked_chipseq_reads ) {
      $command .= ' --cap-stacked-chipseq-reads ' .
                  " --n-max-stacked-chipseq-reads $n_max_stacked_chipseq_reads";
    }
  } else { ## ChIP-seq reads files from single source
    $command .= " --chipseq-target-read-files $chipseq_target_read_files " .
                " --bowtie-path $bowtie_path" ;
    if ( $chipseq_control_read_files ne '' ) {
     $command .= " --chipseq-control-read-files $chipseq_control_read_files";
    }
  }

  if ( $quiet ) {
      $command .= ' --quiet ';
  }

  $command .= " $refName $sampleName $statName $imdName";
  &runCommand($command);

  ## collect pRSEM results
  my $fiso_res  = "$imdName.iso_res";
  my $fgene_res = "$imdName.gene_res";
  
  my $fprsem_iso_res  = "${imdName}_prsem.iso_res";
  my $fprsem_gene_res = "${imdName}_prsem.gene_res";
  
  system("head -8 $fiso_res  > $fprsem_iso_res" );
  system("tail -5 $fiso_res >> $fprsem_iso_res" );
  
  system("head -7 $fgene_res  > $fprsem_gene_res");
  system("tail -4 $fgene_res >> $fprsem_gene_res");

  my $fstat_iso_results  = "${statName}_uniform_prior_1.isoforms.results";
  my $fstat_gene_results = "${statName}_uniform_prior_1.genes.results";
  
  my $fiso_results  = "${sampleName}.isoforms.results";
  my $fgene_results = "${sampleName}.genes.results";

  rename $fiso_results, $fstat_iso_results or die 
    "can't rename $fiso_results to $fstat_iso_results: $!\n";
  
  rename $fgene_results, $fstat_gene_results or die 
    "can't rename $fgene_results to $fstat_gene_results: $!\n";
  
  collectResults("isoform", $fprsem_iso_res,  $fiso_results);
  collectResults("gene",    $fprsem_gene_res, $fgene_results);
}


if (!$keep_intermediate_files) {
    &runCommand("rm -rf $temp_dir", "Fail to delete the temporary folder!");
}

if ($mTime) { $time_end = time(); }

if ($mTime) { 
    open(OUTPUT, ">$sampleName.time");
    print OUTPUT "Aligning reads: $time_alignment s.\n";
    print OUTPUT "Estimating expression levels: $time_rsem s.\n";
    print OUTPUT "Calculating credibility intervals: $time_ci s.\n";
#    my $time_del = $time_end - $time_start;
#    print OUTPUT "Delete: $time_del s.\n";
    close(OUTPUT);
}

__END__

=head1 NAME

rsem-calculate-expression

=head1 SYNOPSIS

 rsem-calculate-expression [options] upstream_read_file(s) reference_name sample_name 
 rsem-calculate-expression [options] --paired-end upstream_read_file(s) downstream_read_file(s) reference_name sample_name 
 rsem-calculate-expression [options] --sam/--bam [--paired-end] input reference_name sample_name

=head1 ARGUMENTS

=over

=item B<upstream_read_files(s)>

Comma-separated list of files containing single-end reads or upstream reads for paired-end data.  By default, these files are assumed to be in FASTQ format.  If the --no-qualities option is specified, then FASTA format is expected.

=item B<downstream_read_file(s)>

Comma-separated list of files containing downstream reads which are paired with the upstream reads.  By default, these files are assumed to be in FASTQ format.  If the --no-qualities option is specified, then FASTA format is expected.

=item B<input>

SAM/BAM formatted input file.  If "-" is specified for the filename, SAM/BAM input is instead assumed to come from standard input. RSEM requires all alignments of the same read group together. For paired-end reads, RSEM also requires the two mates of any alignment be adjacent. See Description section for how to make input file obey RSEM's requirements.

=item B<reference_name>                        

The name of the reference used.  The user must have run 'rsem-prepare-reference' with this reference_name before running this program.

=item B<sample_name>

The name of the sample analyzed. All output files are prefixed by this name (e.g., sample_name.genes.results)

=back

=head1 BASIC OPTIONS

=over

=item B<--paired-end>

Input reads are paired-end reads. (Default: off)

=item B<--no-qualities>

Input reads do not contain quality scores. (Default: off)

=item B<--strand-specific>

The RNA-Seq protocol used to generate the reads is strand specific, i.e., all (upstream) reads are derived from the forward strand.  This option is equivalent to --forward-prob=1.0.  With this option set, if RSEM runs the Bowtie/Bowtie 2 aligner, the '--norc' Bowtie/Bowtie 2 option will be used, which disables alignment to the reverse strand of transcripts.  (Default: off)

=item B<--bowtie2>

Use Bowtie 2 instead of Bowtie to align reads. Since currently RSEM does not handle indel, local and discordant alignments, the Bowtie2 parameters are set in a way to avoid those alignments. In particular, we use options '--sensitive --dpad 0 --gbar 99999999 --mp 1,1 --np 1 --score-min L,0,-0.1' by default. The last parameter of '--score-min', '-0.1', is the negative of maximum mismatch rate. This rate can be set by option '--bowtie2-mismatch-rate'. If reads are paired-end, we additionally use options '--no-mixed' and '--no-discordant'. (Default: off)

=item B<--star>

Use STAR to align reads. Alignment parameters are from ENCODE3's STAR-RSEM pipeline. To save computational time and memory resources, STAR's Output BAM file is unsorted. It is stored in RSEM's temporary directory with name as 'sample_name.bam'. Each STAR job will have its own private copy of the genome in memory. (Default: off) 

=item B<--star-path> <path>

The path to STAR's executable. (Default: the path to STAR executable is assumed to be in user's PATH environment variable)

=item B<--sam>

Input file is in SAM format. (Default: off)

=item B<--bam>

Input file is in BAM format. (Default: off)

=item B<-p/--num-threads> <int>

Number of threads to use. Both Bowtie/Bowtie2, expression estimation and 'samtools sort' will use this many threads. (Default: 1)

=item B<--no-bam-output>

Do not output any BAM file. (Default: off)

=item B<--output-genome-bam>

Generate a BAM file, 'sample_name.genome.bam', with alignments mapped to genomic coordinates and annotated with their posterior probabilities. In addition, RSEM will call samtools (included in RSEM package) to sort and index the bam file. 'sample_name.genome.sorted.bam' and 'sample_name.genome.sorted.bam.bai' will be generated. (Default: off)

=item B<--sampling-for-bam>

When RSEM generates a BAM file, instead of outputing all alignments a read has with their posterior probabilities, one alignment is sampled according to the posterior probabilities. The sampling procedure includes the alignment to the "noise" transcript, which does not appear in the BAM file. Only the sampled alignment has a weight of 1. All other alignments have weight 0. If the "noise" transcript is sampled, all alignments appeared in the BAM file should have weight 0. (Default: off)

=item B<--seed> <uint32>

Set the seed for the random number generators used in calculating posterior mean estimates and credibility intervals. The seed must be a non-negative 32 bit interger. (Default: off)

=item B<--calc-pme>

Run RSEM's collapsed Gibbs sampler to calculate posterior mean estimates. (Default: off) 

=item B<--calc-ci>

Calculate 95% credibility intervals and posterior mean estimates. The credibility level can be changed by setting '--ci-credibility-level'. (Default: off)

=item B<-q/--quiet>

Suppress the output of logging information. (Default: off)

=item B<-h/--help>

Show help information.

=item B<--version>

Show version information.

=back

=head1 ADVANCED OPTIONS

=over

=item B<--sam-header-info> <file>

RSEM reads header information from input by default. If this option is on, header information is read from the specified file. For the format of the file, please see SAM official website. (Default: "")

=item B<--seed-length> <int>

Seed length used by the read aligner.  Providing the correct value is important for RSEM. If RSEM runs Bowtie, it uses this value for Bowtie's seed length parameter. Any read with its or at least one of its mates' (for paired-end reads) length less than this value will be ignored. If the references are not added poly(A) tails, the minimum allowed value is 5, otherwise, the minimum allowed value is 25. Note that this script will only check if the value >= 5 and give a warning message if the value < 25 but >= 5. (Default: 25)

=item B<--tag> <string>

The name of the optional field used in the SAM input for identifying a read with too many valid alignments. The field should have the format <tagName>:i:<value>, where a <value> bigger than 0 indicates a read with too many alignments. (Default: "")

=item B<--bowtie-path> <path>

The path to the Bowtie executables. (Default: the path to the Bowtie executables is assumed to be in the user's PATH environment variable)

=item B<--bowtie-n> <int>

(Bowtie parameter) max # of mismatches in the seed. (Range: 0-3, Default: 2)

=item B<--bowtie-e> <int>

(Bowtie parameter) max sum of mismatch quality scores across the alignment. (Default: 99999999)

=item B<--bowtie-m> <int>

(Bowtie parameter) suppress all alignments for a read if > <int> valid alignments exist. (Default: 200)

=item B<--bowtie-chunkmbs> <int>

(Bowtie parameter) memory allocated for best first alignment calculation (Default: 0 - use Bowtie's default)

=item B<--phred33-quals>

Input quality scores are encoded as Phred+33. (Default: on)

=item B<--phred64-quals>

Input quality scores are encoded as Phred+64 (default for GA Pipeline ver. >= 1.3). (Default: off)

=item B<--solexa-quals>

Input quality scores are solexa encoded (from GA Pipeline ver. < 1.3). (Default: off)

=item B<--bowtie2-path> <path>

(Bowtie 2 parameter) The path to the Bowtie 2 executables. (Default: the path to the Bowtie 2 executables is assumed to be in the user's PATH environment variable)

=item B<--bowtie2-mismatch-rate> <double>

(Bowtie 2 parameter) The maximum mismatch rate allowed. (Default: 0.1)

=item B<--bowtie2-k> <int>

(Bowtie 2 parameter) Find up to <int> alignments per read. (Default: 200)

=item B<--bowtie2-sensitivity-level> <string>

(Bowtie 2 parameter) Set Bowtie 2's preset options in --end-to-end mode. This option controls how hard Bowtie 2 tries to find alignments. <string> must be one of "very_fast", "fast", "sensitive" and "very_sensitive". The four candidates correspond to Bowtie 2's "--very-fast", "--fast", "--sensitive" and "--very-sensitive" options. (Default: "sensitive" - use Bowtie 2's default)

=item B<--gzipped-read-file>

Input read file(s) is compressed by gzip. This option can be only used when aligning reads by STAR, i.e. --star-genome-path <path> is defined (Default: off)

=item B<--bzipped-read-file>

Input read file(s) is compressed by bzip2. This option can be only used when aligning reads by STAR, i.e. --star-genome-path <path> is defined (Default: off)

=item B<--output-star-genome-bam>

Save the BAM file from STAR alignment under genomic coordinate to 'sample_name.STAR.genome.bam'. This file is NOT sorted by genomic coordinate. In this file, according to STAR's manual, 'paired ends of an alignment are always adjacent, and multiple alignments of a read are adjacent as well'. (Default: off)

=item B<--sort-bam-by-read-name>

Sort BAM file aligned under transcript coordidate by read name. Setting this option on will produce determinstic maximum likelihood estimations from independet runs. Note that sorting will take long time and lots of memory. (Default: off)

=item B<--sort-bam-buffer-size> <string>

Size for main memeory buffer when sorting BAM file. It can be any string acceptable to GNU sort's '-S' option. See "sort --help" for details. (Default: '60G')

=item B<--forward-prob> <double>

Probability of generating a read from the forward strand of a transcript. Set to 1 for a strand-specific protocol where all (upstream) reads are derived from the forward strand, 0 for a strand-specific protocol where all (upstream) read are derived from the reverse strand, or 0.5 for a non-strand-specific protocol. (Default: 0.5)

=item B<--fragment-length-min> <int>

Minimum read/insert length allowed. This is also the value for the Bowtie/Bowtie2 -I option. (Default: 1)

=item B<--fragment-length-max> <int>

Maximum read/insert length allowed. This is also the value for the Bowtie/Bowtie 2 -X option. (Default: 1000)

=item B<--fragment-length-mean> <double>

(single-end data only) The mean of the fragment length distribution, which is assumed to be a Gaussian. (Default: -1, which disables use of the fragment length distribution)

=item B<--fragment-length-sd> <double>

(single-end data only) The standard deviation of the fragment length distribution, which is assumed to be a Gaussian.  (Default: 0, which assumes that all fragments are of the same length, given by the rounded value of B<--fragment-length-mean>)

=item B<--estimate-rspd>

Set this option if you want to estimate the read start position distribution (RSPD) from data. Otherwise, RSEM will use a uniform RSPD. (Default: off)

=item B<--num-rspd-bins> <int>

Number of bins in the RSPD. Only relevant when '--estimate-rspd' is specified.  Use of the default setting is recommended. (Default: 20)

=item B<--gibbs-burnin> <int>

The number of burn-in rounds for RSEM's Gibbs sampler. Each round passes over the entire data set once. If RSEM can use multiple threads, multiple Gibbs samplers will start at the same time and all samplers share the same burn-in number. (Default: 200)

=item B<--gibbs-number-of-samples> <int>

The total number of count vectors RSEM will collect from its Gibbs samplers. (Default: 1000)

=item B<--gibbs-sampling-gap> <int>

The number of rounds between two succinct count vectors RSEM collects. If the count vector after round N is collected, the count vector after round N + <int> will also be collected. (Default: 1) 

=item B<--ci-credibility-level> <double>

The credibility level for credibility intervals. (Default: 0.95)

=item B<--ci-memory> <int>

Maximum size (in memory, MB) of the auxiliary buffer used for computing credibility intervals (CI). Set it larger for a faster CI calculation. However, leaving 2 GB memory free for other usage is recommended. (Default: 1024)

=item B<--ci-number-of-samples-per-count-vector> <int>

The number of read generating probability vectors sampled per sampled count vector. The crebility intervals are calculated by first sampling P(C | D) and then sampling P(Theta | C) for each sampled count vector. This option controls how many Theta vectors are sampled per sampled count vector. (Default: 50)

=item B<--samtools-sort-mem> <string>

Set the maximum memory per thread that can be used by 'samtools sort'. <string> represents the memory and accepts suffices 'K/M/G'. RSEM will pass <string> to the '-m' option of 'samtools sort'.  Please note that the default used here is different from the default used by samtools. (Default: 1G)

=item B<--keep-intermediate-files>

Keep temporary files generated by RSEM.  RSEM creates a temporary directory, 'sample_name.temp', into which it puts all intermediate output files. If this directory already exists, RSEM overwrites all files generated by previous RSEM runs inside of it. By default, after RSEM finishes, the temporary directory is deleted.  Set this option to prevent the deletion of this directory and the intermediate files inside of it. (Default: off)

=item B<--temporary-folder> <string>

Set where to put the temporary files generated by RSEM. If the folder specified does not exist, RSEM will try to create it. (Default: sample_name.temp)

=item B<--time>

Output time consumed by each step of RSEM to 'sample_name.time'. (Default: off)

=back

=head1 PRIOR-ENHANCED RSEM OPTIONS

=over

=item B<--run-pRSEM>

Running prior-enhanced RSEM (pRSEM). Prior parameters, i.e. isoform's initial pseudo-count for RSEM's Gibbs sampling, will be learned from input RNA-seq data and an external data set. When pRSEM needs and only needs ChIP-seq peak information to partition isoforms (e.g. in pRSEM's default partition model), either ChIP-seq peak file (with the '--chipseq-peak-file' option) or ChIP-seq FASTQ files for target and input and the path for Bowtie executables are required (with the '--chipseq-target-read-files <string>', '--chipseq-control-read-files <string>', and '--bowtie-path <path> options), otherwise, ChIP-seq FASTQ files for target and control and the path to Bowtie executables are required. (Default: off)

=item B<--chipseq-peak-file> <string>

Full path to a ChIP-seq peak file in ENCODE's narrowPeak, i.e. BED6+4, format. This file is used when running prior-enhanced RSEM in the default two-partition model. It partitions isoforms by whether they have ChIP-seq overlapping with their transcription start site region or not. Each partition will have its own prior parameter learned from a training set. This file can be either gzipped or ungzipped. (Default: "")

=item B<--chipseq-target-read-files> <string>

Comma-separated full path of FASTQ read file(s) for ChIP-seq target. This option is used when running prior-enhanced RSEM. It provides information to calculate ChIP-seq peaks and signals. The file(s) can be either ungzipped or gzipped with a suffix '.gz' or '.gzip'. The options '--bowtie-path <path>' and '--chipseq-control-read-files <string>' must be defined when this option is specified. (Default: "")

=item B<--chipseq-control-read-files> <string>

Comma-separated full path of FASTQ read file(s) for ChIP-seq conrol. This option is used when running prior-enhanced RSEM. It provides information to call ChIP-seq peaks. The file(s) can be either ungzipped or gzipped with a suffix '.gz' or '.gzip'. The options '--bowtie-path <path>' and '--chipseq-target-read-files <string>' must be defined when this option is specified. (Default: "")

=item B<--chipseq-read-files-multi-targets> <string>

Comma-separated full path of FASTQ read files for multiple ChIP-seq targets. This option is used when running prior-enhanced RSEM, where prior is learned from multiple complementary data sets. It provides information to calculate ChIP-seq signals. All files can be either ungzipped or gzipped with a suffix '.gz' or '.gzip'. When this option is specified, the option '--bowtie-path <path>' must be defined and the option '--partition-model <string>' will be set to 'cmb_lgt' automatically. (Default: "")

=item B<--chipseq-bed-files-multi-targets> <string>

Comma-separated full path of BED files for multiple ChIP-seq targets. This option is used when running prior-enhanced RSEM, where prior is learned from multiple complementary data sets. It provides information of ChIP-seq signals and must have at least the first six BED columns. All files can be either ungzipped or gzipped with a suffix '.gz' or '.gzip'. When this option is specified, the option '--partition-model <string>' will be set to 'cmb_lgt' automatically. (Default: "")

=item B<--cap-stacked-chipseq-reads>

Keep a maximum number of ChIP-seq reads that aligned to the same genomic interval. This option is used when running prior-enhanced RSEM, where prior is learned from multiple complementary data sets. This option is only in use when either '--chipseq-read-files-multi-targets <string>' or '--chipseq-bed-files-multi-targets <string>' is specified. (Default: off)

=item B<--n-max-stacked-chipseq-reads> <int>

The maximum number of stacked ChIP-seq reads to keep. This option is used when running prior-enhanced RSEM, where prior is learned from multiple complementary data sets. This option is only in use when the option '--cap-stacked-chipseq-reads' is set. (Default: 5)


=item B<--partition-model> <string>

A keyword to specify the partition model used by prior-enhanced RSEM. It must be one of the following keywords:

=over 2

=item - B<pk> 

Partitioned by whether an isoform has a ChIP-seq peak overlapping with its transcription start site (TSS) region. The TSS region is defined as [TSS-500bp, TSS+500bp]. For simplicity, we refer this type of peak as 'TSS peak' when explaining other keywords.

=item - B<pk_lgtnopk>

First partitioned by TSS peak. Then, for isoforms in the 'no TSS peak' set, a logistic model is employed to further classify them into two partitions.

=item - B<lm3>, B<lm4>, B<lm5>, or B<lm6>

Based on their ChIP-seq signals, isoforms are classified into 3, 4, 5, or 6 partitions by a linear regression model.

=item - B<nopk_lm2pk>, B<nopk_lm3pk>, B<nopk_lm4pk>, or B<nopk_lm5pk>

First partitioned by TSS peak. Then, for isoforms in the 'with TSS peak' set, a linear regression model is employed to further classify them into 2, 3, 4, or 5 partitions. 

=item - B<pk_lm2nopk>, B<pk_lm3nopk>, B<pk_lm4nopk>, or B<pk_lm5nopk>

First partitioned by TSS peak. Then, for isoforms in the 'no TSS peak' set, a linear regression model is employed to further classify them into 2, 3, 4, or 5 partitions. 

=item - B<cmb_lgt>

Using a logistic regression to combine TSS signals from multiple complementary data sets and partition training set isoform into 'expressed' and 'not expressed'. This partition model is only in use when either '--chipseq-read-files-multi-targets <string>' or '--chipseq-bed-files-multi-targets <string> is specified.

=back

Parameters for all the above models are learned from a training set. For detailed explainations, please see prior-enhanced RSEM's paper. (Default: 'pk')

=back

=head1 DESCRIPTION

In its default mode, this program aligns input reads against a reference transcriptome with Bowtie and calculates expression values using the alignments.  RSEM assumes the data are single-end reads with quality scores, unless the '--paired-end' or '--no-qualities' options are specified. Alternatively, users can use STAR to align reads using the '--star' option. RSEM has provided options in 'rsem-prepare-reference' to prepare STAR's genome indices. Users may use an alternative aligner by specifying one of the --sam and --bam options, and providing an alignment file in the specified format. However, users should make sure that they align against the indices generated by 'rsem-prepare-reference' and the alignment file satisfies the requirements mentioned in ARGUMENTS section. 

One simple way to make the alignment file satisfying RSEM's requirements (assuming the aligner used put mates in a paired-end read adjacent) is to use 'convert-sam-for-rsem' script. This script only accept SAM format files as input. If a BAM format file is obtained, please use samtools to convert it to a SAM file first. For example, if '/ref/mouse_125' is the 'reference_name' and the SAM file is named 'input.sam', you can run the following command: 

  convert-sam-for-rsem /ref/mouse_125 input.sam -o input_for_rsem.sam  

For details, please refer to 'convert-sam-for-rsem's documentation page.

The SAM/BAM format RSEM uses is v1.4. However, it is compatible with old SAM/BAM format. However, RSEM cannot recognize 0x100 in the FLAG field. In addition, RSEM requires SEQ and QUAL are not '*'. 

The user must run 'rsem-prepare-reference' with the appropriate reference before using this program.

For single-end data, it is strongly recommended that the user provide the fragment length distribution parameters (--fragment-length-mean and --fragment-length-sd).  For paired-end data, RSEM will automatically learn a fragment length distribution from the data.

Please note that some of the default values for the Bowtie parameters are not the same as those defined for Bowtie itself.

The temporary directory and all intermediate files will be removed when RSEM finishes unless '--keep-intermediate-files' is specified.

With the '--calc-pme' option, posterior mean estimates will be calculated in addition to maximum likelihood estimates.

With the '--calc-ci' option, 95% credibility intervals and posterior mean estimates will be calculated in addition to maximum likelihood estimates.

With the '--run-pRSEM' option and associated options (see section 'PRIOR-ENHANCED RSEM OPTIONS' above for details), prior-enhanced RSEM will be running. Prior parameters will be learned from supplied external data set(s) and assigned as initial pseudo-counts for isoforms in the corresponding partition for Gibbs sampling.

=head1 OUTPUT

=over

=item B<sample_name.isoforms.results> 

File containing isoform level expression estimates. The first line
contains column names separated by the tab character. The format of
each line in the rest of this file is:

transcript_id gene_id length effective_length expected_count TPM FPKM IsoPct [posterior_mean_count posterior_standard_deviation_of_count pme_TPM pme_FPKM IsoPct_from_pme_TPM TPM_ci_lower_bound TPM_ci_upper_bound FPKM_ci_lower_bound FPKM_ci_upper_bound]

Fields are separated by the tab character. Fields within "[]" are
optional. They will not be presented if neither '--calc-pme' nor
'--calc-ci' is set.

'transcript_id' is the transcript name of this transcript. 'gene_id'
is the gene name of the gene which this transcript belongs to (denote
this gene as its parent gene). If no gene information is provided,
'gene_id' and 'transcript_id' are the same.

'length' is this transcript's sequence length (poly(A) tail is not
counted). 'effective_length' counts only the positions that can
generate a valid fragment. If no poly(A) tail is added,
'effective_length' is equal to transcript length - mean fragment
length + 1. If one transcript's effective length is less than 1, this
transcript's both effective length and abundance estimates are set to
0.

'expected_count' is the sum of the posterior probability of each read
comes from this transcript over all reads. Because 1) each read
aligning to this transcript has a probability of being generated from
background noise; 2) RSEM may filter some alignable low quality reads,
the sum of expected counts for all transcript are generally less than
the total number of reads aligned.

'TPM' stands for Transcripts Per Million. It is a relative measure of
transcript abundance. The sum of all transcripts' TPM is 1
million. 'FPKM' stands for Fragments Per Kilobase of transcript per
Million mapped reads. It is another relative measure of transcript
abundance. If we define l_bar be the mean transcript length in a
sample, which can be calculated as

l_bar = \sum_i TPM_i / 10^6 * effective_length_i (i goes through every transcript), 

the following equation is hold:

FPKM_i = 10^3 / l_bar * TPM_i.

We can see that the sum of FPKM is not a constant across samples.

'IsoPct' stands for isoform percentage. It is the percentage of this
transcript's abandunce over its parent gene's abandunce. If its parent
gene has only one isoform or the gene information is not provided,
this field will be set to 100.

'posterior_mean_count', 'pme_TPM', 'pme_FPKM' are posterior mean
estimates calculated by RSEM's Gibbs
sampler. 'posterior_standard_deviation_of_count' is the posterior
standard deviation of counts. 'IsoPct_from_pme_TPM' is the isoform
percentage calculated from 'pme_TPM' values.

'TPM_ci_lower_bound', 'TPM_ci_upper_bound', 'FPKM_ci_lower_bound' and
'FPKM_ci_upper_bound' are lower(l) and upper(u) bounds of 95%
credibility intervals for TPM and FPKM values. The bounds are
inclusive (i.e. [l, u]).

=item B<sample_name.genes.results>

File containing gene level expression estimates. The first line
contains column names separated by the tab character. The format of
each line in the rest of this file is:

gene_id transcript_id(s) length effective_length expected_count TPM FPKM [posterior_mean_count posterior_standard_deviation_of_count pme_TPM pme_FPKM TPM_ci_lower_bound TPM_ci_upper_bound FPKM_ci_lower_bound FPKM_ci_upper_bound]

Fields are separated by the tab character. Fields within "[]" are
optional. They will not be presented if neither '--calc-pme' nor
'--calc-ci' is set.

'transcript_id(s)' is a comma-separated list of transcript_ids
belonging to this gene. If no gene information is provided, 'gene_id'
and 'transcript_id(s)' are identical (the 'transcript_id').

A gene's 'length' and 'effective_length' are
defined as the weighted average of its transcripts' lengths and
effective lengths (weighted by 'IsoPct'). A gene's abundance estimates
are just the sum of its transcripts' abundance estimates.

=item B<sample_name.alleles.results>

Only generated when the RSEM references are built with allele-specific
transcripts.

This file contains allele level expression estimates for
allele-specific expression calculation. The first line
contains column names separated by the tab character. The format of
each line in the rest of this file is:

allele_id transcript_id gene_id length effective_length expected_count TPM FPKM AlleleIsoPct AlleleGenePct [posterior_mean_count posterior_standard_deviation_of_count pme_TPM pme_FPKM AlleleIsoPct_from_pme_TPM AlleleGenePct_from_pme_TPM TPM_ci_lower_bound TPM_ci_upper_bound FPKM_ci_lower_bound FPKM_ci_upper_bound]

Fields are separated by the tab character. Fields within "[]" are
optional. They will not be presented if neither '--calc-pme' nor
'--calc-ci' is set.

'allele_id' is the allele-specific name of this allele-specific transcript.

'AlleleIsoPct' stands for allele-specific percentage on isoform
level. It is the percentage of this allele-specific transcript's
abundance over its parent transcript's abundance. If its parent
transcript has only one allele variant form, this field will be set to
100.

'AlleleGenePct' stands for allele-specific percentage on gene
level. It is the percentage of this allele-specific transcript's
abundance over its parent gene's abundance.

'AlleleIsoPct_from_pme_TPM' and 'AlleleGenePct_from_pme_TPM' have
similar meanings. They are calculated based on posterior mean
estimates.

Please note that if this file is present, the fields 'length' and
'effective_length' in 'sample_name.isoforms.results' should be
interpreted similarly as the corresponding definitions in
'sample_name.genes.results'.

=item B<sample_name.transcript.bam, sample_name.transcript.sorted.bam and sample_name.transcript.sorted.bam.bai>

Only generated when --no-bam-output is not specified.

'sample_name.transcript.bam' is a BAM-formatted file of read
alignments in transcript coordinates. The MAPQ field of each alignment
is set to min(100, floor(-10 * log10(1.0 - w) + 0.5)), where w is the
posterior probability of that alignment being the true mapping of a
read.  In addition, RSEM pads a new tag ZW:f:value, where value is a
single precision floating number representing the posterior
probability. Because this file contains all alignment lines produced
by bowtie or user-specified aligners, it can also be used as a
replacement of the aligner generated BAM/SAM file. For paired-end
reads, if one mate has alignments but the other does not, this file
marks the alignable mate as "unmappable" (flag bit 0x4) and appends an
optional field "Z0:A:!".

'sample_name.transcript.sorted.bam' and
'sample_name.transcript.sorted.bam.bai' are the sorted BAM file and
indices generated by samtools (included in RSEM package).

=item B<sample_name.genome.bam, sample_name.genome.sorted.bam and sample_name.genome.sorted.bam.bai>

Only generated when --no-bam-output is not specified and --output-genome-bam is specified.

'sample_name.genome.bam' is a BAM-formatted file of read alignments in
genomic coordinates. Alignments of reads that have identical genomic
coordinates (i.e., alignments to different isoforms that share the
same genomic region) are collapsed into one alignment.  The MAPQ field
of each alignment is set to min(100, floor(-10 * log10(1.0 - w) +
0.5)), where w is the posterior probability of that alignment being
the true mapping of a read.  In addition, RSEM pads a new tag
ZW:f:value, where value is a single precision floating number
representing the posterior probability. If an alignment is spliced, a
XS:A:value tag is also added, where value is either '+' or '-'
indicating the strand of the transcript it aligns to.

'sample_name.genome.sorted.bam' and 'sample_name.genome.sorted.bam.bai' are the
sorted BAM file and indices generated by samtools (included in RSEM package).

=item B<sample_name.time>

Only generated when --time is specified.

It contains time (in seconds) consumed by aligning reads, estimating expression levels and calculating credibility intervals.

=item B<sample_name.stat>

This is a folder instead of a file. All model related statistics are stored in this folder. Use 'rsem-plot-model' can generate plots using this folder. 

'sample_name.stat/sample_name.cnt' contains alignment statistics. The format and meanings of each field are described in 'cnt_file_description.txt' under RSEM directory.

'sample_name.stat/sample_name.model' stores RNA-Seq model parameters learned from the data. The format and meanings of each filed of this file are described in 'model_file_description.txt' under RSEM directory.

The following four output files will be generated only by prior-enhanced RSEM

=over 2

=item - 'sample_name.stat/sample_name_prsem.all_tr_features' 

It stores isofrom features for deriving and assigning pRSEM prior. The first line is a header and the rest is one isoform per line. The description for each column is:

=over 2

=item * B<trid>: transcript ID from input annotation

=item * B<geneid>: gene ID from input anntation

=item * B<chrom>: isoform's chromosome name

=item * B<strand>: isoform's strand name

=item * B<start>: isoform's end with the lowest genomic loci

=item * B<end>: isoform's end with the highest genomic loci

=item * B<tss_mpp>: average mappability of [TSS-500bp, TSS+500bp], where TSS is isoform's transcription start site, i.e. 5'-end

=item * B<body_mpp>: average mappability of (TSS+500bp, TES-500bp), where TES is isoform's transcription end site, i.e. 3'-end

=item * B<tes_mpp>: average mappability of [TES-500bp, TES+500bp]

=item * B<pme_count>: isoform's fragment or read count from RSEM's posterior mean estimates

=item * B<tss>: isoform's TSS loci 

=item * B<tss_pk>: equal to 1 if isoform's [TSS-500bp, TSS+500bp] region overlaps with a RNA Pol II peak; 0 otherwise

=item * B<is_training>: equal to 1 if isoform is in the training set where Pol II prior is learned; 0 otherwise

=back

=item - 'sample_name.stat/sample_name_prsem.all_tr_prior'

It stores prior parameters for every isoform. This file does not have a header. Each line contains a prior parameter and an isoform's transcript ID delimited by `  # `.

=item - 'sample_name.stat/sample_name_uniform_prior_1.isoforms.results'

RSEM's posterior mean estimates on the isoform level with an initial pseudo-count of one for every isoform. It is in the same format as the 'sample_name.isoforms.results'. 

=item - 'sample_name.stat/sample_name_uniform_prior_1.genes.results'

RSEM's posterior mean estimates on the gene level with an initial pseudo-count of one for every isoform. It is in the same format as the 'sample_name.genes.results'. 

=back

When learning prior from multiple external data sets in prior-enhanced RSEM, two additional output files will be generated.

=over 2

=item - 'sample_name.stat/sample_name.pval_LL'

It stores a p-value and a log-likelihood. The p-value indicates whether the combination of multiple complementary data sets is informative for RNA-seq quantification. The log-likelihood shows how well pRSEM's Dirichlet-multinomial model fits the read counts of partitioned training set isoforms.

=item - 'sample_name.stat/sample_name.lgt_mdl.RData'

It stores an R object named 'glmmdl', which is a logistic regression model on the training set isoforms and multiple external data sets.

=back

In addition, extra columns will be added to 'sample_name.stat/all_tr_features'

=over 2

=item * B<is_expr>: equal to 1 if isoform has an abundance >= 1 TPM and a non-zero read count from RSEM's posterior mean estimates; 0 otherwise

=item * B<"$external_data_set_basename">: log10 of external data's signal at [TSS-500, TSS+500]. Signal is the number of reads aligned within that interval and normalized to RPKM by read depth and interval length. It will be set to -4 if no read aligned to that interval. 

There are multiple columns like this one, where each represents an external data set.

=item * B<prd_expr_prob>: predicted probability from logistic regression model on whether this isoform is expressed or not. A probability higher than 0.5 is considered as expressed

=item * B<partition>: group index, to which this isoforms is partitioned
 
=item * B<prior>: prior parameter for this isoform

=back

=back

=head1 EXAMPLES

Assume the path to the bowtie executables is in the user's PATH environment variable. Reference files are under '/ref' with name 'mouse_125'. 

1) '/data/mmliver.fq', single-end reads with quality scores. Quality scores are encoded as for 'GA pipeline version >= 1.3'. We want to use 8 threads and generate a genome BAM file:

 rsem-calculate-expression --phred64-quals \
                           -p 8 \
                           --output-genome-bam \
                           /data/mmliver.fq \
                           /ref/mouse_125 \
                           mmliver_single_quals

2) '/data/mmliver_1.fq' and '/data/mmliver_2.fq', paired-end reads with quality scores. Quality scores are in SANGER format. We want to use 8 threads and do not generate a genome BAM file:

 rsem-calculate-expression -p 8 \
                           --paired-end \
                           /data/mmliver_1.fq \
                           /data/mmliver_2.fq \
                           /ref/mouse_125 \
                           mmliver_paired_end_quals

3) '/data/mmliver.fa', single-end reads without quality scores. We want to use 8 threads:

 rsem-calculate-expression -p 8 \
                           --no-qualities \
                           /data/mmliver.fa \
                           /ref/mouse_125 \
                           mmliver_single_without_quals

4) Data are the same as 1). This time we assume the bowtie executables are under '/sw/bowtie'. We want to take a fragment length distribution into consideration. We set the fragment length mean to 150 and the standard deviation to 35. In addition to a BAM file, we also want to generate credibility intervals. We allow RSEM to use 1GB of memory for CI calculation:

 rsem-calculate-expression --bowtie-path /sw/bowtie \
                           --phred64-quals \
                           --fragment-length-mean 150.0 \
                           --fragment-length-sd 35.0 \
                           -p 8 \
                           --output-genome-bam \
                           --calc-ci \
                           --ci-memory 1024 \
                           /data/mmliver.fq \
                           /ref/mouse_125 \
                           mmliver_single_quals

5) '/data/mmliver_paired_end_quals.bam', paired-end reads with quality scores. We want to use 8 threads:

 rsem-calculate-expression --paired-end \
                           --bam \
                           -p 8 \
                           /data/mmliver_paired_end_quals.bam \
                           /ref/mouse_125 \
                           mmliver_paired_end_quals

6) '/data/mmliver_1.fq.gz' and '/data/mmliver_2.fq.gz', paired-end reads with quality scores and read files are compressed by gzip. We want to use STAR to aligned reads and assume STAR executable is '/sw/STAR'. Suppose we want to use 8 threads and do not generate a genome BAM file:

 rsem-calculate-expression --star \
                           --star-path /sw/STAR \
                           --gzipped-read-file \
                           --paired-end \
                           -p 8 \
                           /data/mmliver_1.fq.gz \
                           /data/mmliver_2.fq.gz \
                           /ref/mouse_125 \
                           mmliver_paired_end_quals


7) In the above example, suppose we want to run prior-enhanced RSEM instead. Assuming we want to learn priors from a ChIP-seq peak file '/data/mmlive.narrowPeak.gz':

 rsem-calculate-expression --star \
                           --star-path /sw/STAR \
                           --gzipped-read-file \
                           --paired-end \
                           --calc-pme \
                           --run-pRSEM \
                           --chipseq-peak-file /data/mmliver.narrowPeak.gz \
                           -p 8 \
                           /data/mmliver_1.fq.gz \
                           /data/mmliver_2.fq.gz \
                           /ref/mouse_125 \
                           mmliver_paired_end_quals

8) Similar to the example in 7), suppose we want to use the partition model 'pk_lm2nopk' (partitioning isoforms by Pol II TSS peak first and then partitioning 'no TSS peak' isoforms into two bins by a linear regression model), and we want to partition isoforms by RNA Pol II's ChIP-seq read files '/data/mmliver_PolIIRep1.fq.gz' and '/data/mmliver_PolIIRep2.fq.gz', and the control ChIP-seq read files '/data/mmliver_ChIPseqCtrl.fq.gz'. Also, assuming Bowtie's executables are under '/sw/bowtie/': 

 rsem-calculate-expression --star \
                           --star-path /sw/STAR \
                           --gzipped-read-file \
                           --paired-end \
                           --calc-pme \
                           --run-pRSEM \
                           --chipseq-target-read-files /data/mmliver_PolIIRep1.fq.gz,/data/mmliver_PolIIRep2.fq.gz \
                           --chipseq-control-read-files /data/mmliver_ChIPseqCtrl.fq.gz \
                           --partition-model pk_lm2nopk \
                           --bowtie-path /sw/bowtie \
                           -p 8 \
                           /data/mmliver_1.fq.gz \
                           /data/mmliver_2.fq.gz \
                           /ref/mouse_125 \
                           mmliver_paired_end_quals

9) Similar to the example in 8), suppose we want to derive prior from four histone modification ChIP-seq read data sets: '/data/H3K27Ac.fastq.gz', '/data/H3K4me1.fastq.gz', '/data/H3K4me2.fastq.gz', and '/data/H3K4me3.fastq.gz'. Also, assuming Bowtie's executables are under '/sw/bowtie/': 

 rsem-calculate-expression --star \
                           --star-path /sw/STAR \
                           --gzipped-read-file \
                           --paired-end \
                           --calc-pme \
                           --run-pRSEM \
                           --partition-model cmb_lgt \
                           --chipseq-read-files-multi-targets /data/H3K27Ac.fastq.gz,/data/H3K4me1.fastq.gz,/data/H3K4me2.fastq.gz,/data/H3K4me3.fastq.gz \
                           --bowtie-path /sw/bowtie \
                           -p 8 \
                           /data/mmliver_1.fq.gz \
                           /data/mmliver_2.fq.gz \
                           /ref/mouse_125 \
                           mmliver_paired_end_quals

=cut
