#!/bin/zsh
#SBATCH --partition cssb
#SBATCH --time 7-00:00
#SBATCH --constraint Gold-6126&1536G
#SBATCH --nodes 5
#SBATCH --error MotionCorr/job178/run.err
#SBATCH --output MotionCorr/job178/run.out
#SBATCH --job-name relion4s
#SBATCH --open-mode append
#SBATCH --no-requeue
unset LD_PRELOAD
source /beegfs/cssb/software/etc/em/relion/4.0/relion4_variants.source

# run the job
echo "### start : $(date)  ###"
echo "### master: $(hostname)  ###"
echo "### jobid : ${SLURM_JOB_ID}  ###"
source /beegfs/cssb/software/spack/share/spack/setup-env.sh
source $(spack location -i environment-modules)/init/profile.sh
module purge
module load relion/4.0.b4
override_cpu
default_gpu_pascal

# check myself if the relion gpu flag is off
FOUND=$(grep '\-\-gpu' ${0})
if [ $? -ne 1 ]; then
    echo "Warning: This is a CPU submission script template!"
    echo "Warning: It seems that the 'Use GPU acceleration' flag in the Relion 'Compute' tab is enabled."
    echo "ERROR: The Relion gpu flag is turned on - exiting!!!"
    exit 1
fi

# detect allocated nodes
MY_NODELIST=($(scontrol show hostnames="$SLURM_NODELIST"))

# detect sockets
MY_SOCKETS=($(/beegfs/cssb/software/admin/bin/likwid-topology | grep Sockets | cut -f3))

# generate hostfile for mpirun (assuming all nodes have same processors)
echo "### MPI hostfile ###"
tmpname=MotionCorr/job178/run.out
MY_HOSTFILE=${tmpname%.out}.hostfile
rm -f ${MY_HOSTFILE}
master=1
for mynode in "${MY_NODELIST[@]}"; do
    echo "${mynode} slots=$((${MY_SOCKETS}+${master}))" >>${MY_HOSTFILE}
    master=0
done
cat ${MY_HOSTFILE}

# run relion
echo "### RELION ###"

mpirun --hostfile ${MY_HOSTFILE} --map-by socket \
    --mca pml ucx --mca mpi_cuda_support 0 --mca orte_base_help_aggregate 0 \
    `which relion_run_motioncorr_mpi` --i Import/job177/movies.star --o MotionCorr/job178/ --first_frame_sum 1 --last_frame_sum -1 --use_own  --j 23 --bin_factor 1 --bfactor 150 --dose_per_frame 1 --preexposure 0 --patch_x 5 --patch_y 5 --eer_grouping 32 --dose_weighting  --grouping_for_ps 4   --pipeline_control MotionCorr/job178/

echo "### end: $(date)  ###"


