DL4DistancePrediction4/Scripts/DeriveDistInfo4Threading.sh
#!/bin/sh

if [[ -z "${DL4DistancePredHome}" ]]; then
        echo "ERROR: please set environmental variable DL4DistancePredHome to the install folder of DL4DistancePrediction4"
        exit 1
fi

if [[ -z "${DistanceFoldingHome}" ]]; then
        echo "ERROR: please set environmental variable DistanceFoldingHome to the install folder of Folding"
        exit 1
fi

if [ $# -lt 1 ]; then
	echo "$0 predictedDistMatrixPKLfile [ResDir]"
	echo "	This script derives Cb-Cb distance prob and potential for protein threading"
	echo "	predictedDistMatrixPKLfile: the file containing predicted distance/orientation information generated by various programs such as PredictPairRelation4OneInput.sh or PredictPairRelation4OneProtein.sh"
	echo "	ResDir: the folder for result saving, default current work directory"
	echo "	Three result files will be generated: XXX.predictedDistMatrix414C.pkl, XXX.pairPotential.DFIRE16.pkl and XXX.epad_prob where XXX is protein name"
	exit 1
fi

cmd=`readlink -f $0`
cmdDir=`dirname $cmd`

inputfile=$1
if [ ! -$inputfile ]; then
	echo "ERROR: invalid input file $inputfile"
	exit 1
fi

ResDir=`pwd`
if [ $# -ge 2 ]; then
	ResDir=$2
	mkdir -p $ResDir
fi

reduceProgram=$DL4DistancePredHome/ReducePredictedDistMatrix.py
if [ ! -f $reduceProgram ]; then
	echo "ERROR: cannot find $reduceProgaram "
	exit 1
fi

EPADprogram=$cmdDir/ConvertDistancePKL2EPAD.py
if [ ! -f $EPADprogram ]; then
	echo "ERROR: cannot find $EPADprogram "
	exit 1
fi

## convert the distance matrix to 12C, and the 12C matrix to epad_prob
python $reduceProgram -r CbCb_Discrete12C -s $ResDir $inputfile

target=`basename $inputfile .predictedDistMatrix.pkl`
$EPADprogram $ResDir/${target}.predictedDistMatrix412C.pkl $ResDir/${target}.epad_prob
rm -f $ResDir/${target}.predictedDistMatrix412C.pkl

## the CbCb_Discrete14C matrix is needed for the new version of DeepThreader
python $reduceProgram -r CbCb_Discrete14C -s $ResDir $inputfile

potProgram=$DistanceFoldingHome/GenDistPotential4Threading.sh
if [ ! -x $potProgram ]; then
	echo "ERROR: invalid or non-executable program $potProgram"
	exit 1
fi

$potProgram -d $ResDir $ResDir/${target}.predictedDistMatrix414C.pkl

if [ ! -f $ResDir/${target}.epad_prob ]; then
	echo "ERROR: failed to generate the EPAD file from $inputfile"
	exit 1
fi

if [ ! -f $ResDir/${target}.pairPotential.DFIRE16.pkl ]; then
	echo "ERROR: failed to generate the CbCb potential file from $inputfile"
	exit 1
fi
