#! /bin/bash
# Last edited on 2023-11-29 10:31:12 by stolfi

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

# Requires a file "${runDir}/garbage.dir" with the runs to exclude from analysis. 

runDir="$1"; shift # Parent diretory of all subjects and runs, e.g. "raw" or "pre".
runs=( "$@" )

show="SHOW"  # Should display the plot? SHOW or NOSHOW.
hsize=1400   # Horz plot size (pixels). 
vsize=500    # Vert plot size (pixels). 
  
( 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 )
( cd ~/programs/c/NEUROMAT/nmeeg_comp_analysis  && make uninstall build install )

echo "######################################################################" 1>&2
echo "=== do_basic_pca.sh for segments ${runs[@]} ===" 1>&2
 
pushd ${runDir}

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

ls `echo ${runs[@]} | tr ' ' '\012' | sed -e 's:$:.txt:g' | 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

# Get the list of electrode names to process:
someFile=`cat .sel | 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}" 
mkdir -pv ${pcaDir}

rm -fv ${pcaDir}/*.{txt,png,stats}

# ----------------------------------------------------------------------
echo "Performing the PCA..." 1>&2

cat `cat .sel` \
  | nmeeg_correl \
      -outPrefix ${pcaDir}/ \
      -capType FN3 \
      -normAvg 1 \
      -normVar 0 \
      -minMag 1.0
      
# ----------------------------------------------------------------------
echo "Plotting electrode correlation distances..." 1>&2
nmeeg_plot_dst_cor.sh ${SHOW} ${pcaDir}/dst_cov.txt  ${pcaDir}/dst_cov.png 

# ----------------------------------------------------------------------
echo "Separating the principal components..." 1>&2

for run in ${runs[@]} ; do

  nmeeg_comp_analysis \
    -normalize \
    -pattern F2B ${pcaDir}/P000_eig.txt \
    -pattern SG1 ${pcaDir}/P001_eig.txt \
    -pattern SG2 ${pcaDir}/P002_eig.txt \
    -writeComp F2B ${pcaDir}/${run}_F2B.txt = F2B \
    -writeComp SG1 ${pcaDir}/${run}_SG1.txt = SG1 \
    -writeComp SG2 ${pcaDir}/${run}_SG2.txt = SG2 \
    -writeComp SGN ${pcaDir}/${run}_SGN.txt = SG1 SG2 \
    -delete RPF LPF OCC \
    < ${run}.txt \
    > ${pcaDir}/${run}_PCA.txt

  for chvm in SGN:8 PCA:50 ; do 
  
    ch="${chvm/:*/}"
    vmax="${chvm/*:/}"

    nmeeg_plot_channels.sh \
      ${show} \
      ${pcaDir}/${run}_${ch} \
      0 ${vmax} \
      0 2 \
      0 0 \
      ${hsize} ${vsize} \
    || rm -f ${fname}.png

  done
done

# ----------------------------------------------------------------------
# Visualize it:

visualize_basic_pca.sh ${pcaDir} "`echo ${chnames[@]} | tr ' ' ','`" `cat .sel`

popd

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