#! /bin/bash
# Last edited on 2021-09-01 22:42:59 by stolfi

# Does a preliminary principal component analysis of the
# filtered EEG runs of one subject.

runDir="$1"; shift # Parent diretory of all subjects and runs, e.g. "flt-runs-C"
sDir="$1"; shift   # Subject id, e.g. "s010".
  
( cd ~/programs/c/NEUROMAT/nmeeg_correl && make uninstall build install )
( cd ~/programs/c/NEUROMAT/nmeeg_make_imgbasis && make uninstall build install )
( cd ~/programs/c/NEUROMAT/nmeeg_animate && make uninstall build install )

echo "######################################################################" 1>&2
echo "=== do_basic_pca.sh for subject ${sDir} ===" 1>&2
 
pushd ${runDir}/${sDir} 

# ----------------------------------------------------------------------
# Compute a merged EEG file from a large enough sample of non-garbage runs:

ls r00[0-9][0-9][0-9].txt | sort > .all
cat garbage.dir | egrep -e '^ *r00[0-9][0-9][0-9][.]txt *$' | sort > .bad
bool 1-2 .all .bad \
  | gawk 'BEGIN { srand(4615); } // { printf "%10.8f %s\n", rand(), $1; }' \
  | sort -k1g \
  | cut -d ' ' -f 2 \
  | head -n 50 \
  | sort \
  > .sel
  
wc -l .all .bad .sel

# ---------------------------------------------------------------------
# Create the electrode interpolation basis:

width="0450"
height="0630"
# Just KILL the idiot who decided that '037' is octal not decimal!
width=`printf '%04d' $(( 10#${width} ))`
height=`printf '%04d' $(( 10#${height} ))`

# Interesting basis types: gauss:1:1:1, shepard:0:1:1, voronoi:0:0:2

btype=voronoi
interp=0
norm=0
msub=2

someFile=`ls r?????.txt | head -n 1`
echo "getting channel names from ${someFile}..." 1>&2
chnames=( `cat ${someFile} | egrep -m 1 -e '^channels[ ]*[=]' | sed -e 's:^.*= *::'` )
ne=$(( `cat ${someFile} | egrep -m 1 -e '^ne[ ]*[=]' | sed -e 's:^.*= *:10#:'` ))
chnames=( ${chnames[@]:0:${ne}} )
echo "found ${ne} electrodes: ${chnames[@]}" 1>&2 
if [[ ${ne} -le 1 ]]; then echo "** bad number of electrodes" 1>&2; exit 1; fi

pcaTag="A1"
pcaDir="${pcaTag}" 

maskDir="${pcaDir}/${width}_${height}"
basisDir="${maskDir}/${btype}_i${interp}_n${norm}"

echo "creating directory ${basisDir}" 1>&2
mkdir -p ${basisDir}

rm -f ${maskDir}/*.{fni,png} 
rm -f ${basisDir}/*.{fni,png} 

nmeeg_make_imgbasis \
  -electrodes ${chnames[@]} \
  -type ${btype} \
  -interp ${interp} \
  -norm ${norm} \
  -scalpSize 150 180 150 \
  -imageSize ${width} ${height} -extent 0.95 \
  -subsample ${msub} \
  -outDir ${pcaDir}

# Convert images and show:

for fname in \
  ${maskDir}/msk.fni \
  ${maskDir}/elp.fni \
  ${basisDir}/*.fni \
; do \
  pname="${fname%.*}.png" ; \
  fni_to_png \
      -isMask T \
      -min -2.0 -max +2.0 \
      -maxval 65535 \
      -nanval 0 \
    < ${fname} \
    > ${pname} 
done

display ${maskDir}/msk.png ${maskDir}/elp.png ${basisDir}/*.png

# ----------------------------------------------------------------------
# Perform the PCA:

rm -fv ${pcaDir}/P*_eig.txt ${pcaDir}/P*_eig_rgb.txt

cat `cat .sel` \
  | nmeeg_correl \
      -outPrefix ${pcaDir}/ \
      -normAvg 1 \
      -normVar 0 \
      -minMag 8.0
      
nmeeg_plot_dst_cor.sh SHOW ${pcaDir}/dst_cov.txt  ${pcaDir}/dst_cov.png 

# ----------------------------------------------------------------------
# Display the component patterns as images:

eigFiles=( `cd ${pcaDir} && ls P*_eig.txt | sort` )

sop=( )
for eigFile in ${eigFiles[@]} ; do
  eigName="${eigFile/.txt/}"
  sop+=( "-setName" ${eigName} )
  frameDir="${pcaDir}/${eigName}"
  mkdir -pv ${frameDir}
done

nmeeg_animate \
    -electrodes ${chnames[@]} \
    -maskDir "${maskDir}" \
    -basisDir "${basisDir}" \
    -skip 0 -read 1 -step 1 \
    -inDir "${pcaDir}" \
    ${sop[@]} \
    -outDir "${pcaDir}"

nshown=0
for eigFile in ${eigFiles[@]} ; do
  eigName="${eigFile/.txt/}"
  frameDir="${pcaDir}/${eigName}"
  frames=( `ls ${frameDir}/f*.png | sort` )
  if [[ ${#frames[@]} -eq 0 ]]; then 
    echo "nmeeg_animate yielded no frames" 1>&2 ; exit 1
  elif [[ ${#frames[@]} -gt 1 ]]; then 
    echo "nmeeg_animate yielded multiple frames" 1>&2 ; exit 1
  fi
  eigRGBName="${pcaDir}/${eigName}_rgb.png"
  mv -v "${frames[0]}" ${eigRGBName}
  if [[ ( "/${show}" == "/SHOW" ) && ( ${nshown} -lt 5 ) ]]; then
    display -title '%f' ${eigRGBName}
    nshown=$(( ${nshown} + 1 ))
  fi
done

ls ${pcaDir}/P???_eig_rgb.png | sort | head -n 8  > .imgs
convert `cat .imgs` -resize '50%' +append ${pcaDir}/pca.png
display ${pcaDir}/pca.png

popd

echo "######################################################################" 1>&2
