#!/bin/tcsh

# ----------------------------------------------------------------------
# output some basic details about this subjects input and results:
#   - subject ID, TRs removed, num stim files, motion limit, outlier limit
#   - num runs, TRs per run, total TRs
#   - TRs censored, fraction, num regs of interest
#   - per reg: num TRs applied, num TRs censored, fraction censored
#   - num stim files found, TSNR average, max F-stat, blur estimates
#
# This script should be run from a '.results' directory, produced by an
# afni_proc.py processing script.
# 
# NOTE: this script is not particularly meant to be easy to read and follow,
#       but is more to just be executed.  Yanking numbers from datasets is
#       not such a common need.
#
# NOTE: this script creates one new file: X.stim.xmat.1D
#
#       - an X-matrix containing only uncensored regressors of interest
#
#       This new file is used to compute fractions of "response TRs" censored,
#       per stimulus class of interest, where a "response TR" means the given
#       regressor was non-zero at that TR.
#

# ------------------------------------------------------------
# try to avoid any oblique warnings throughout script
setenv AFNI_NO_OBLIQUE_WARNING YES

# ----------------------------------------------------------------------
# main variables regarding this single subject analysis
set subj             = sub-024
set afni_ver         = AFNI_24.1.22
set afni_package     = linux_rocky_8
set tr               = 2.0
set rm_trs           = 0
set num_stim         = 2
set mot_limit        = 0.3
set out_limit        = 0.05
set final_view       = tlrc
set was_censored     = 1

set tcat_dset        = pb00.sub-024.r01.tcat+orig.HEAD
set gcor_dset        = out.gcor.1D
set mask_corr_dset   = out.mask_ae_dice.txt
set mask_anat_templ_corr_dset = out.mask_at_dice.txt
set enorm_dset       = motion_sub-024_enorm.1D
set motion_dset      = dfile_rall.1D
set outlier_dset     = outcount_rall.1D
set flip_check_dset  = aea_checkflip_results.txt
set xmat_regress     = X.xmat.1D
set stats_dset       = stats.sub-024_REML+tlrc.HEAD
set errts_dset       = errts.sub-024_REML+tlrc.HEAD
set censor_dset      = censor_sub-024_combined_2.1D
set xmat_uncensored  = X.nocensor.xmat.1D
set final_anat       = anat_final.sub-024+tlrc.HEAD
set mask_dset        = mask_epi_anat.sub-024+tlrc.HEAD
set tsnr_dset        = TSNR.sub-024+tlrc.HEAD

# derived variables
set flip_guess       = NO_FLIP


# ------------------------------------------------------------
# some overview details
echo ""
echo "subject ID                : $subj"

if ( $?afni_ver ) then
   echo "AFNI version              : $afni_ver"
endif
if ( $?afni_package ) then
   echo "AFNI package              : $afni_package"
endif

if ( $?tr ) then
   set value = $tr
else
   set value = UNKNOWN
endif
echo "TR                        : $value"

if ( $?rm_trs ) then
   set value = $rm_trs
else
   set value = UNKNOWN
endif
echo "TRs removed (per run)     : $value"
echo "multiband level           : 1"
echo "slice timing pattern      : simult"
echo "num stim classes provided : $num_stim"
echo "final anatomy dset        : $final_anat"
echo "final stats dset          : $stats_dset"
if ( -f $tcat_dset ) then
   echo "orig voxel counts         : `3dinfo -ni -nj -nk $tcat_dset`"
   echo "orig voxel resolution     : `3dinfo -ad3 $tcat_dset`"
   echo "orig volume center        : `3dinfo -dc3 $tcat_dset`"
endif
echo "final voxel resolution    : `3dinfo -ad3 $stats_dset`"
echo ""

# ------------------------------------------------------------
# report motion limit, average motion and number of TRs exceeding limit

echo "motion limit              : $mot_limit"

set mcount = `1deval -a $enorm_dset -expr "step(a-$mot_limit)"      \
                        | awk '$1 != 0 {print}' | wc -l`
echo "num TRs above mot limit   : $mcount"

set mmean = `3dTstat -prefix - -nzmean $enorm_dset\' | & tail -n 1`
echo "average motion (per TR)   : $mmean"

if ( $?motion_dset ) then
    if ( $was_censored ) then
        # compute average censored motion
        1deval -a $enorm_dset -b $censor_dset -expr 'a*b' > rm.ec.1D
        set mmean = `3dTstat -prefix - -nzmean rm.ec.1D\' | & tail -n 1`
        echo "average censored motion   : $mmean"
        \rm -f rm.ec.1D
    endif

    # compute the maximum motion displacement over all TR pairs
    set disp = `1d_tool.py -infile $motion_dset -show_max_displace -verb 0`
    echo "max motion displacement   : $disp"

    if ( $was_censored ) then
        # compute the maximum motion displacement over all TR pairs
        set disp = `1d_tool.py -infile $motion_dset -show_max_displace \
                               -censor_infile $censor_dset -verb 0`
        echo "max censored displacement : $disp"
    endif
endif

# ------------------------------------------------------------
# report outlier limit, average and number of TRs exceeding limit
# also, report any flip guess

if ( $?out_limit ) then
   echo "outlier limit             : $out_limit"
endif

set mmean = `3dTstat -prefix - -mean $outlier_dset\' | & tail -n 1`
echo "average outlier frac (TR) : $mmean"

if ( $?out_limit ) then
   set mcount = `1deval -a $outlier_dset -expr "step(a-$out_limit)"      \
                           | awk '$1 != 0 {print}' | wc -l`
   echo "num TRs above out limit   : $mcount"
endif

if ( $?flip_guess ) then
   echo "flip guess                : $flip_guess"
endif

echo ""

# ------------------------------------------------------------
# note number of runs, TRs per run, and possibly censored TRs per run
set nruns = ( `1d_tool.py -infile X.xmat.1D -show_num_runs` )
set trs   = ( `1d_tool.py -infile X.xmat.1D -show_tr_run_counts trs_no_cen` )
echo "num runs found            : $nruns"
echo "num TRs per run           : $trs"

if ( $was_censored ) then
   set tra = ( `1d_tool.py -infile $xmat_regress -show_tr_run_counts trs`)
   set trc = ( `1d_tool.py -infile $xmat_regress -show_tr_run_counts trs_cen`)
   set trf = ( `1d_tool.py -infile $xmat_regress -show_tr_run_counts frac_cen`)
   echo "num TRs per run (applied) : $tra"
   echo "num TRs per run (censored): $trc"
   echo "fraction censored per run : $trf"
endif

# ------------------------------------------------------------
# count total TRs (uncensored and censored) from X-matrix

# note X-matrix dimensions
set rows_cols = ( `1d_tool.py -infile $xmat_regress -show_rows_cols -verb 0` )
set num_trs = $rows_cols[1]
set total_trs = $num_trs        # total might change if censoring

if ( $?xmat_uncensored ) then
   set xmat = $xmat_uncensored
   set urc = ( `1d_tool.py -infile $xmat -show_rows_cols -verb 0` )
   set total_trs = $urc[1]
   echo "TRs total (uncensored)    : $total_trs"
endif

echo "TRs total                 : $num_trs"

@ dof_rem = $rows_cols[1] - $rows_cols[2]
set dof_rfrac = `ccalc -nice "$dof_rem/$total_trs"`

echo "degrees of freedom used   : $rows_cols[2]"
echo "degrees of freedom left   : $dof_rem"
echo "final DF fraction         : $dof_rfrac"
echo ""
# ------------------------------------------------------------
# make non-basline X-matrix, if one is not already here
if ( $?xmat_uncensored ) then
    set xmat = $xmat_uncensored
else
    set xmat = $xmat_regress
endif

set xstim = X.stim.xmat.1D
if ( ! -f $xstim ) then
   1d_tool.py -infile $xmat -verb 0 -write_xstim $xstim
endif

# ----------------------------------------------------------------------
# report TR counts per stim, and possibly censor counts

# note number of regressors of interest
set rc = ( `1d_tool.py -infile $xstim -show_rows_cols -verb 0` )
set nint = $rc[2]
@ nm1 = $nint - 1

# if censoring, print main censor fraction
if ( $was_censored ) then
    set ntr_censor = `cat $censor_dset | grep 0 | wc -l`
    echo "TRs censored              : $ntr_censor"
    echo "censor fraction           : `ccalc $ntr_censor/$total_trs`"
endif

# print num regressors of interest
if ( $num_stim > 0 ) then
    echo "num regs of interest      : $nint"
else
    echo "num regs of interest      : $num_stim"
endif


# report per-stim censoring
if ( $was_censored && $num_stim > 0 ) then
    # compute fractions of stimulus TRs censored in each
    set stim_trs = ()
    set stim_trs_censor = ()
    set stim_frac_censor = ()
    foreach index ( `count_afni -digits 1 0 $nm1` )
        # count response TRs, with and without censoring
        # (their difference is the number of TRs lost to censoring)
        set st = `1deval -a $xstim"[$index]" -expr 'bool(a)' | grep 1 | wc -l`
        set sc = `1deval -a $xstim"[$index]" -b $censor_dset -expr 'bool(a*b)'\
                         | grep 1 | wc -l`
        set sc = `ccalc -i "$st-$sc"`           # change to num censored
        set ff = `ccalc -form '%.3f' "$sc/$st"` # and the fraction censored

        # keep lists of response TRs, # censored and fractions censored
        # (across all stimulus regressors)
        set stim_trs = ( $stim_trs $st )
        set stim_trs_censor = ( $stim_trs_censor $sc )
        set stim_frac_censor = ( $stim_frac_censor $ff )
    end

    echo "num TRs per stim (orig)   : $stim_trs"
    echo "num TRs censored per stim : $stim_trs_censor"
    echo "fraction TRs censored     : $stim_frac_censor"
else if ( $num_stim > 0 ) then
    # no censoring - just compute num TRs per regressor
    set stim_trs = ()
    foreach index ( `count_afni -digits 1 0 $nm1` )
        set st = `1deval -a $xstim"[$index]" -expr 'bool(a)' | grep 1 | wc -l`
        set stim_trs = ( $stim_trs $st )
    end
    echo "num TRs per stim          : $stim_trs"
endif


# ----------------------------------------------------------------------
# compute average motion per stim response

if ( $was_censored && $num_stim > 0 ) then
    set sresp_mot = ()
    set sresp_mot_cen = ()
    foreach index ( `count_afni -digits 1 0 $nm1` )
        set st  = `1deval -a $xstim"[$index]" -expr 'bool(a)' | grep 1 | wc -l`
        set snc = `1deval -a $xstim"[$index]" -b $censor_dset   \
                   -expr 'bool(a*b)' | grep 1 | wc -l`
        set sm  = `1deval -a $xstim"[$index]" -b $enorm_dset -expr 'bool(a)*b'\
                   | 3dTstat -sum -prefix - 1D:stdin\' |& tail -n 1`
        set smc = `1deval -a $xstim"[$index]" -b $enorm_dset -c $censor_dset \
                   -expr 'bool(a)*b*c' | 3dTstat -sum -prefix - 1D:stdin\'  \
                   |& tail -n 1`
        set sm  = `ccalc $sm/$st`
        set smc = `ccalc $smc/$snc`

        set sresp_mot = ( $sresp_mot $sm )
        set sresp_mot_cen = ( $sresp_mot_cen $smc )
    end

    echo "ave mot per sresp (orig)  : $sresp_mot"
    echo "ave mot per sresp (cens)  : $sresp_mot_cen"

else if ( $num_stim > 0 ) then
    set sresp_mot = ()
    foreach index ( `count_afni -digits 1 0 $nm1` )
        set st = `1deval -a $xstim"[$index]" -expr 'bool(a)' | grep 1 | wc -l`
        set sm = `1deval -a $xstim"[$index]" -b $enorm_dset -expr 'bool(a)*b'\
                  | 3dTstat -sum -prefix - 1D:stdin\' |& tail -n 1`
        set sm = `ccalc $sm/$st`
        set sresp_mot = ( $sresp_mot $sm )
    end
    echo "ave mot per sresp         : $sresp_mot"
endif

echo ""


# ------------------------------------------------------------
# get TSNR average
if ( -f $tsnr_dset && -f $mask_dset ) then
    eval 'set tsnr_ave = `3dmaskave -quiet -mask $mask_dset $tsnr_dset`' \
         >& /dev/null
    echo "TSNR average              : $tsnr_ave"
endif

# ------------------------------------------------------------
# get global correlation
if ( -f $gcor_dset ) then
    set gcor_val = `cat $gcor_dset`
    echo "global correlation (GCOR) : $gcor_val"
endif

# ------------------------------------------------------------
# get anat/EPI mask Dice coefficient
if ( -f $mask_corr_dset ) then
    set val = `cat $mask_corr_dset`
    echo "anat/EPI mask Dice coef   : $val"
endif

# ------------------------------------------------------------
# get anat/template mask Dice coefficient
if ( -f $mask_anat_templ_corr_dset ) then
    set val = `cat $mask_anat_templ_corr_dset`
    echo "anat/templ mask Dice coef : $val"
endif

# ------------------------------------------------------------
# note maximum masked F-stat
if ( -f "$stats_dset" && -f $mask_dset ) then
  set fmax = `3dBrickStat -slow -max -mask $mask_dset $stats_dset"[Full_Fstat]"`
  echo "maximum F-stat (masked)   : $fmax"
endif

# ------------------------------------------------------------'
# note blur estimates (try for ACF and FWHM, first)
set blur_file = blur_est.$subj.1D
if ( -f $blur_file ) then
    set found = 0
    set best_acf = `grep ACF $blur_file | tail -n 1 | awk '{print $1, $2, $3}'`
    set best_fw = `grep FWHM $blur_file | tail -n 1 | awk '{print $1, $2, $3}'`
    if ( $#best_acf == 3 ) then
        set found = 1
        echo "blur estimates (ACF)      : $best_acf"
    endif
    if ( $#best_fw == 3 ) then
        set found = 1
        echo "blur estimates (FWHM)     : $best_fw"
    endif

    # fallback
    if ( ! $found ) then
       set best = `tail -n 1 $blur_file | awk '{print $1, $2, $3}'`
       if ( $#best == 3 ) then
           echo "blur estimates            : $best"
       endif
    endif
endif

echo ""



# ==========================================================================
# script generated by the command:
#
# gen_ss_review_scripts.py -exit0 -init_uvars_json out.ap_uvars.json \
#     -write_uvars_json out.ss_review_uvars.json

