#!/bin/bash

#########
# This script will regenerate the files
#
# 4_globins_topo.probs
# 4_globins_MinRisk_topo.probs
#
# using the alignment samples contained in 4_globins.log, and
# the tree samples contained in 4_globins.tree.
#
# For further details see README
#########

ali_sample_rate=20
tree_sample_rate=4
#########
# Compute tree probabilities on individual alignment samples 
echo "Computing probabilities for individual alignments..."
for i in `seq 0 $ali_sample_rate 1980`; do 
    printf "\r$i"
    java -jar ../WeaveAlign.jar -scoreTrees 4_globins.tree -nexusSampleRate=$tree_sample_rate -f=$i -n=1 4_globins.log &> /dev/null 
    mv 4_globins.tree.ll 4_globins_$i.tree.ll
done
echo ""
# Note that the above analysis of individual alignments requires the set
# of tree samples to be read in multiple times, which constitutes the 
# majority of the runtime for the above procedure (around 1-2 minutes
# on a 2.3GHz Intel core). This could be reduced significantly by 
# modifying WeaveAlign to carry out separate analyses on each sample
# rather than invoking the program many times.
#########

#########
# Tabulate the split probabilities for the alignment samples
echo "Tabulating split probabilities..."

a="\[\[2hhba, 2mm1\], \[1lh1, 1urva\]\]"
b="\[\[1urva, 2mm1\], \[1lh1, 2hhba\]\]"
c="\[\[1urva, 2hhba\], \[1lh1, 2mm1\]\]"

for i in `seq 0 $ali_sample_rate 1980`; do 
    probs=()
    f=4_globins_$i.tree.ll
    for x in "$a" "$b" "$c"; do 
	probs+=$( cat $f | grep "$x" | awk '{ print $NF; print " " }' )
    done 
    echo ${probs[*]} 
    rm $f
done > 4_globins_topo.probs
#########

#########
# Compute tree probabilities marginalised over all alignments 
# in the DAG created from 4_globins.log
echo "Computing probabilities for DAG..."
java -jar ../WeaveAlign.jar -scoreTrees 4_globins.tree -nexusSampleRate=$tree_sample_rate -r=$ali_sample_rate 4_globins.log  &> /dev/null 
probs=()
for x in "$a" "$b" "$c"; do 
    probs+=$( cat 4_globins.tree.ll | grep "$x" | awk '{ print $NF; print " " }' ); 
done; 
echo ${probs[*]} > 4_globins_MinRisk_topo.probs
rm 4_globins.tree.ll
#########

#########
# Generate figure using R (requires 'ape' package to be installed)
echo "Generating figure..."
Rscript plot_output.R &> /dev/null
#########
echo "...done"
