#!/bin/bash
###
### ViPTreeGen ver 1.1.2 (2018-09-10): a tool for viral proteomic tree generation
###
### Copyright: 2017 (C) Yosuke Nishimura (yosuke@kuicr.kyoto-u.ac.jp)
### Licence: MIT license
###

PROGNAME=$(basename $0)
VERSION="1.1.2"
Errmsg="[1;31m[error][0m"
Sccmsg="[1;32m[success][0m"
Modidate="2018-04-17"
incmd="$0 $*"


# {{{ usage
read -r -d '' usage <<EOF
[1;35m### $PROGNAME ver $VERSION ($Modidate) ###[0m

[1;32m[description][0m
$PROGNAME - tool for viral proteomic tree generation from viral genomic sequences.
$PROGNAME has been developed as the ViPTree server project (http://www.genome.jp/viptree).

$PROGNAME first computes genome-wide sequence similarity distance based on tBLASTx results,
then construct (bio)nj tree based on the distance (1 - similarity) matrix.

Complete genomes are recommended as input sequence for accurate distance/tree computation,
though genome fragments are also acceptable.

If you compute many sequences (e.g. n > 100) or large sequences (e.g. NCLDV genomes), it may take a long time.
In those cases, use '--ncpus' or '--queue' for parallel computating.

[1;32m[usage][0m
$ $PROGNAME [options] <input fasta> <output dir>

- <input fasta> should be in nucleotide FASTA format and include at least 3 sequences.
- If sequence name (before the first space in the header line) includes a character other than
  alphabets, numbers, dot(.), hyphen(-), or underscore(_), it will be replaced with underscore.
- <output dir> should not exist.

[1;32m[dependencies][0m
    - tblastx              -- included in the BLAST+ program;
                              https://blast.ncbi.nlm.nih.gov/Blast.cgi?PAGE_TYPE=BlastDocs&DOC_TYPE=Download
    - ruby (ver >=2.0) 

  (for tree generation)
    - R (ver >=3.0)
    - R package 'ape'      -- try install.packages('ape') in R terminal
    - R package 'phangorn' -- try install.packages('phangorn') in R terminal

[1;32m[options][0m
  (general)
    -h, --help
    -v, --version

  (tblastx)
    --cutlen       [>=10000]   (default: 100000)    -- length to split input sequences for faster tblastx computation
    --dbsize       [int]       (default: 200000000)
    --matrix       [str]       (default: BLOSUM45)
    --evalue       [num]       (default: 1e-2)
    --min-idt      [int]       (default: 30)
    --min-aalen    [int]       (default: 30)

  (tree)
    --notree                   (default: off)       -- generate only similarity/distance matrix
    --method       [nj|bionj]  (default: bionj)     -- proteomic tree generation method

  (2D mode)
    --2D           [query fasta] (default: off)     -- do not generate tree but similarity matrix of: 'query sequences' against 'input sequences'. 2D mode is designed to find the most related 'input sequence' for each 'query sequence'

  (use GNU parallel)
    --ncpus        [int]                            -- number of jobs in parallel	

  (for icr user)                                    -- for computation in the ICR supercomputer system
    --queue        [JP1]                            -- queue for computation

[1;32m[output files][0m
  (normal mode)
    result/all.sim.matrix              -- similarity (SG score) matrix
    result/all.dist.matrix             -- distance (1-SG score) matrix
    result/all.[bio]nj.[a|de]sc.newick -- Newick files of the viral proteomic tree, midpoint rooted and ladderized
                                          asc: (nodes with fewer children) --> (nodes with more children).
                                          desc: (nodes with more children) --> (nodes with fewer children).

  (2D mode)
    result/2D.sim.matrix               -- similarity (SG score) matrix (row-wise: query fasta, column-wise: input fasta)
    result/top10.sim.list              -- top10 SG scores for each query sequence. format: 1st column - query ID; from 2nd to 11st columns - ID:SG_score
EOF
# }}} usage


# {{{ parse command line
for OPT in "$@"
do
	case "$OPT" in
		'-h'|'--help' )
			echo "$usage"
			exit 1
			;;
		'-v'|'--version' )
			echo $VERSION
			exit 1
			;;
		'--notree' )
			notree=true
			shift 1
			;;
		'--cutlen' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			cutlen="$2"
			shift 2
			;;
		'--dbsize' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			dbsize="$2"
			shift 2
			;;
		'--matrix' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			matrix="$2"
			shift 2
			;;
		'--evalue' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			evalue="$2"
			shift 2
			;;
		'--min-idt' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			idt="$2"
			shift 2
			;;
		'--min-aalen' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			aalen="$2"
			shift 2
			;;
		'--method' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			method="$2"
			shift 2
			;;
		'--queue' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			queue="$2"
			shift 2
			;;
		'--ncpus' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			ncpus="$2"
			shift 2
			;;
		'--wtime' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires an argument -- $1" 1>&2
				exit 1
			fi
			wtime="$2"
			shift 2
			;;
		'--2D' )
			if [[ -z "$2" ]] || [[ "$2" =~ ^-+ ]] ; then
				echo "$Errmsg option requires a FASTA file -- $1" 1>&2
				exit 1
			fi
			twoD="$2"
			shift 2
			;;
		'--'|'-' )
			shift 1
			params+=( "$@" )
			break
			;;
		-*)
			echo "$Errmsg illegal option -- '$(echo $1 | sed 's/^-*//')'" 1>&2
			exit 1
			;;
		*)
			if [[ ! -z "$1" ]] && [[ ! "$1" =~ ^-+ ]] ; then
				#params=( ${params[@]} "$1" )
				params+=( "$1" )
				shift 1
			fi
			;;
	esac
done
if [ -z $params ] ; then
	echo "$Errmsg need 2 arguments" 1>&2
	echo 
	echo "$usage" 1>&2
	exit 1
elif [ ${#params[@]} -lt 2 ] ; then
	echo "$Errmsg need 2 arguments" 1>&2
	exit 1
elif ! [ -f "${params[0]}" ] ; then
	echo "$Errmsg  first argument should be a fasta file." 1>&2
	exit 1
elif [ -e "${params[1]}" ] ; then
	echo "$Errmsg  output directory already exists." 1>&2
	exit 1
fi
# }}} parse command line


# {{{ check dependencies
### check availablity of tblastx
command -v tblastx >/dev/null 2>&1 || { echo >&2 "$Errmsg tblastx (in BLAST+ package) is required but not available.  Aborting."; exit 1; }
command -v makeblastdb >/dev/null 2>&1 || { echo >&2 "$Errmsg makeblastdb (in BLAST+ package) is required but not available.  Aborting."; exit 1; }

### check availablity of R and ape
if [ -z $notree ]; then 
	command -v R >/dev/null 2>&1 || \
		{ echo >&2 "$Errmsg R is required but not available.  Aborting."; exit 1; }
	LANG=C R --quiet --no-save --no-restore -e "library('ape')" >/dev/null 2>&1 || \
		{ echo >&2 "$Errmsg R package 'ape' must be installed but not available.  Aborting."; exit 1; }
	LANG=C R --quiet --no-save --no-restore -e "library('phangorn')" >/dev/null 2>&1 || \
		{ echo >&2 "$Errmsg R package 'phangorn' must be installed but not available.  Aborting."; exit 1; }
fi

### check ruby version
ST=`ruby -e 'print RUBY_VERSION.to_f >= 2.0 ? 0 : 1'`
if [ $ST -ne 0 ]; then 
	echo >&2 "$Errmsg ruby (version >=2.0) is required.  Aborting."; exit 1;
fi

### check availablity of GNU parallel
if [ -n $ncpus ]; then 
	command -v parallel >/dev/null 2>&1 || { echo >&2 "$Errmsg GNU parallel is required but not available.  Aborting."; exit 1; }
fi
# }}} check dependencies


# {{{ assign variables 
### parse args
fin="${params[0]}"
dir="${params[1]}"

### param for split length for fast up
cutlen="${cutlen:-100000}"

### tblastx params
dbsize="${dbsize:-200000000}"
matrix="${matrix:-BLOSUM45}"
evalue="${evalue:-1e-2}"
idt="${idt:-30}"
aalen="${aalen:-30}"

### tree generation param
method="${method:-bionj}"

### 2D mode
twoD="${twoD:-}"

### computation params
queue="${queue}"
nthread="${nthread:-1}"
wtime="${wtime:-24:00:00}"

### rakefile/logdir
pushd `dirname $0` > /dev/null
scrdir=`pwd -P`
popd > /dev/null
jobname=`basename $0`
rakefile=$scrdir/$jobname.rake
logdir=$dir/log
# }}} assign variables 


# {{{ after run function
function after_run(){
  endTime=$(LC_ALL=C date +"%Y-%m-%d %H:%M:%S %z")

  if [[ $1 -gt 0 ]] ; then
    echo "$Errmsg run failed: $endTime" > "$logdir/$startTime.$jobname.error"
    echo "$Errmsg process is killed: $endTime" |tee -a "$logdir/$jobname.log"
    exit 1
  else
    echo "$Sccmsg run finished: $endTime" > "$logdir/$startTime.$jobname.success"
  fi
}
### }}} after run function


# {{{ input command
read -r -d '' incmdlog <<EOF

[1;32m===== command line[0m

$ $incmd

[1;32m===== log file[0m

$logdir/$jobname.log

[1;32m===== check version: $PROGNAME[0m

$VERSION

EOF
# }}} input command


### main
mkdir -p $logdir
startTime=$(LC_ALL=C date +"%Y-%m-%d %H:%M:%S")

## write input command
echo "$incmdlog" |tee -a $logdir/$jobname.log

## trap Ctrl-C etc...
trap 'after_run 1' 1 2 3 9 15

## run
rake -f $rakefile dir="$dir" fin="$fin" cutlen="$cutlen" dbsize="$dbsize" matrix="$matrix" evalue="$evalue" idt="$idt" aalen="$aalen" \
	twoD="$twoD" method="$method" queue="$queue" ncpus="$ncpus" wtime="$wtime" notree="$notree" 2>&1 |tee -a $logdir/$jobname.log
st=$(( ${PIPESTATUS[0]} + ${PIPESTATUS[1]} ))
after_run $st

