#!/bin/tcsh

@global_parse `basename $0` "$*" ; if ($status) exit 0

# set ver = 1.1 ; set date = April 2, 2019
# + [PA Taylor] Change looks of output: nicer without "-boxes" for
#   shapes, and with "-sepscl" to scale each row independently.
# + [PA Taylor] Also, use 1d_tool to calculate enorm (for consistency).
#
#set ver = "1.2" ; set date = "Jan 30, 2020"
# + [PA Taylor] put explicit path for AFNI_scripts dir to get loc of
#               do*.py prog
#
#set ver = "2.0";  set rev_dat   = "Nov 5, 2020"
#   + move to more formal version with options
#
set ver = "2.1";  set rev_dat   = "Nov 5, 2020"
#   + add functionality, opts
#
# ----------------------------------------------------------------

set this_prog = "adjunct_tort_plot_dp_align"
set here      = "$PWD"

# ----------------------- set defaults --------------------------

set ifile   = ""
set oimage  = ""

set odir    = "$here"
set opref   = ""

set xlab        = "vol index"
set enorm_max   = ""
set enorm_min   = ""
set enorm_hline = ""

set DO_SVG  = 1

set wdir      = ""

# ------------------- process options, a la rr ----------------------

if ( $#argv == 0 ) goto SHOW_HELP

set ac = 1
while ( $ac <= $#argv )
    # terminal options
    if ( ("$argv[$ac]" == "-h" ) || ("$argv[$ac]" == "-help" )) then
        goto SHOW_HELP
    endif
    if ( "$argv[$ac]" == "-ver" ) then
        goto SHOW_VERSION
    endif

    # required
    if ( "$argv[$ac]" == "-input" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set ifile = "$argv[$ac]"

    else if ( "$argv[$ac]" == "-prefix" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set opref = `basename "$argv[$ac]"`
        set odir  = `dirname  "$argv[$ac]"`

    else if ( "$argv[$ac]" == "-enorm_max" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set enorm_max = "$argv[$ac]"
        set enorm_min = `echo "scale=2; - ${enorm_max} / 10.0" | bc`

    else if ( "$argv[$ac]" == "-enorm_hline" ) then
        if ( $ac >= $#argv ) goto FAIL_MISSING_ARG
        @ ac += 1
        set enorm_hline = "$argv[$ac]"

    else if ( "$argv[$ac]" == "-no_svg" ) then
        set DO_SVG   = 0

    else
        echo "\n\n** ERROR: unexpected option #$ac = '$argv[$ac]'\n\n"
        goto BAD_EXIT
        
    endif
    @ ac += 1
end

# =======================================================================
# ============================ ** SETUP ** ==============================
# =======================================================================

if ( "${ifile}" == "" ) then
    echo "** ERROR: need to provide a file with '-input ..'"
    goto BAD_EXIT
endif

if ( "${opref}" == "" ) then
    echo "** ERROR: need to provide an output file prefix with '-prefix ..'"
    goto BAD_EXIT
endif
 
set o_alpar  = "${odir}/${opref}_align.1D"
set o_enorm  = "${odir}/${opref}_enorm.1D"
set ojpg     = "${odir}/${opref}.jpg"
set osvg     = "${odir}/${opref}.svg"

set ifile_base  = `basename "${ifile}"`
set title_jpg   = "DIFFPREP alignment params and enorm"
set title_svg   = "${title_jpg}: ${ifile_base}"

if ( "${enorm_max}" != "" ) then
    if ( "${enorm_hline}" == "" ) then
        set enorm_hline = `echo "scale=3; ${enorm_max} / 2.0" | bc`
    endif
endif

# ===================== output dir =======================
 
# check output directory, use input one if nothing given

if ( ! -e "$odir" ) then
    echo "++ Making new output directory: $odir"
    \mkdir -p "$odir"
endif

# --------- check for SVG plotting

if ( $DO_SVG ) then
    python -c "import matplotlib"
    if ( $status ) then
        echo "+* WARNING: matplotlib not present.  Cannot make SVG."
        set DO_SVG = 0
    endif
endif

# ====================================================================

echo "++ Starting the work for: $this_prog (ver = ${ver})"

# make 6 col file of align pars
adjunct_tort_read_dp_align.py        \
    "${ifile}"                       \
    "${o_alpar}"

# output enorm
1d_tool.py                                              \
    -overwrite                                          \
    -infile         "${o_alpar}"                        \
    -set_nruns      1                                   \
    -derivative                                         \
    -collapse_cols  euclidean_norm                      \
    -write          "${o_enorm}"

# ----------------- make plot(s) --------------------------

# jpg
1dplot                                                    \
    -overwrite                                            \
    -sep                                                  \
    -sepscl                                               \
    -DAFNI_1DPLOT_COLOR_01=green                          \
    -DAFNI_1DPLOT_COLOR_02=green                          \
    -DAFNI_1DPLOT_COLOR_03=green                          \
    -DAFNI_1DPLOT_COLOR_04=cyan                           \
    -DAFNI_1DPLOT_COLOR_05=cyan                           \
    -DAFNI_1DPLOT_COLOR_06=cyan                           \
    -DAFNI_1DPLOT_COLOR_07=black                          \
    -jpg      "$ojpg"                                     \
    -xlabel   "${xlab}"                                   \
    -ynames   'Tx (mm)' 'Ty (mm)' 'Tz (mm)'               \
              'Rx (deg)' 'Ry (deg)' 'Rz (deg)' 'enorm' -  \
    -plabel   "${title_jpg}"                              \
    "${o_alpar}" "${o_enorm}"

# maybe svg
if ( $DO_SVG ) then
    echo "++ Have Python+Matplotlib.  Making (fancy) SVG"

    1dplot.py                                             \
        -sepscl                                           \
        -boxplot_on                                       \
        -reverse_order                                    \
        -infiles  "${o_alpar}" "${o_enorm}"               \
        -colors   "black"                                 \
                  "tab:cyan"  "tab:cyan"  "tab:cyan"      \
                  "tab:green" "tab:green" "tab:green"     \
        -ylabels  "Tx\n(mm)"  "Ty\n(mm)"  "Tz\n(mm)"      \
                  "Rx\n(deg)" "Ry\n(deg)" "Rz\n(deg)"     \
                  "enorm\n(~mm)"                          \
        -xlabel   "${xlab}"                               \
        -censor_hline   NONE NONE NONE NONE NONE NONE "${enorm_hline}" \
        -yaxis    : : : : : : "${enorm_min}:${enorm_max}" \
        -title    "${title_svg}"                          \
        -prefix   "${osvg}"
endif

# ---------------------------------------------------------------------

echo ""
echo "++ Produced image(s):"
echo "      $ojpg"

if ( $DO_SVG ) then
echo "      ${osvg}"
endif

echo ""

goto GOOD_EXIT

# ========================================================================
# ========================================================================

SHOW_HELP:
cat << EOF

OVERVIEW ~1~

When processing DWI data with TORTOISE's DIFFPREP, you (yes, you!) can
view some of the output alignment parameters.  In particular, this
program displays the rigid-body alignment parameters (3 rotations and
3 translations), which might give you a sense of subject motion.
(Note that due to the presence of other distortions and effects in DWI
data, more than just subject motion is likely shown via these params.)

This (AFNI) program has been tested on TORTOISE versions 3.1* - 3.2.
We hope to keep it up-to-date on future versions, as well.

auth = PA Taylor (NIMH, NIH, USA)

OUTPUTS ~1~

This program outputs multiple files with the user's specified PREFIX:

  PREFIX_align.1D : text file, 6 columns of data corresponding to the
                    6 rigid-body alignment parameters estimated by
                    DIFFPREP (in order, left-to-right):
                      del x (for axial data, RL translation)
                      del y (for axial data, AP translation)
                      del z (for axial data, IS translation)
                      Rx    (for axial data, rotation around x axis)
                      Ry    (for axial data, rotation around y axis)
                      Rz    (for axial data, rotation around z axis)
                    Units are mm and deg.  One row per input DWI volume.

  PREFIX_enorm.1D : text file with 1 column of data, the Euclidean
                    norm (enorm) of the differences of the rigid body
                    alignment parameters.  Essentially, a scalar
                    estimate of motion.  Units are "~mm", which means
                    "approx mm":
                    ... Combining rotation+translation is at first odd
                    to see, but for the typical human brain, rotation
                    by 1 deg causes the edge of the brain to move
                    about 1 mm.  Hence this approximation.  This seems
                    to provide a good sense of when motion is "large"
                    and when it isn't (because this is an L2-norm of
                    motion estimates).

   PREFIX.jpg     : a plot of enorm and the alignment parameters, made
                    using AFNI's 1dplot.  

   PREFIX.svg     : a plot of enorm and the alignment parameters, made
                    using AFNI's 1dplot.py -- this is a fancier plot,
                    requiring Python+Matplotlib to be installed on the
                    computer.  This script automatically checks to see
                    if those dependencies are installed, and will make
                    this image if it can; otherwise, it skips it.
                    SVG is a vector graphic format, so it makes for nice
                    line plots.
                    Some aspects of the enorm plot (e.g., y-axis range
                    and an extra horizontal line for visualization
                    fun) can be controlled for this image.

USAGE ~1~

    adjunct_tort_plot_dp_align               \\
        -input   DIFFPREP_TRANSFORM_FILE     \\
        -prefix  OUTPUT                      \\
        ...

where:

    -input III    : name of DIFFPREP-produced file to parse, probably
                    ending  in "_transformations.txt".

    -prefix PPP   : base of output files;  can contain path information.
                    Should *not* include any extension (each output adds
                    their own appropriate one). 

    -enorm_max EM : specify max value of y-axis of enorm plot in SVG image.
                    (Def value of y-axis range is to just show all values.)
                    Can be useful to have a constant value across a study,
                    so you see relative differences easily when flipping 
                    through images.      

  -enorm_hline EH : specify value of a horizontal, dotted, bright cyan
                    line for the enorm plot in SVG image. (Default: none.)
                    Can help with visualization.  No censoring happens
                    from this.
                    
  -no_svg         : opt to turn off even *checking* to plot an SVG version
                    of the figure (default is to check+do if possible).
                    I don't know why you would use this option... the SVG
                    is nice.

EXAMPLE ~1~

  # 1.  Make plots of the transformation information, with "-enorm_*
        .." values picked for convenience, as a good fraction of voxel
        size (say, max is 50-75% of voxel edge length):

  adjunct_tort_plot_dp_align                                              \\
        -input       SUBJ_001/dwi_03_ap/ap_proc_eddy_transformations.txt  \\
        -prefix      SUBJ_001/dwi_03_ap/QC/ap_proc                        \\
        -enorm_max   1                                                    \\
        -enorm_hline 0.5

EOF

# ----------------------------------------------------------------------

    goto GOOD_EXIT

SHOW_VERSION:
   echo "$ver"
   goto GOOD_EXIT

FAIL_MISSING_ARG:
    echo "** ERROR! Missing an argument after option flag: '$argv[$ac]'"
    goto BAD_EXIT

BAD_EXIT:
    exit 1

GOOD_EXIT:
    exit 0
