#!/bin/bash
# =============================================================================
# Script      : Obable_Conversion.sh
# Description : Conversion and energy minimization of ligands from SDF format
#               to PDBQT format (required by AutoDock Vina/GNINA)
#               using Open Babel with the MMFF94 force field
# Usage       : sbatch Obable_Conversion.sh
# =============================================================================

#SBATCH --job-name=Obabel               # Job name displayed in the SLURM queue
#SBATCH --partition=long30dq            # Target partition (long-duration jobs)
#SBATCH --output=slurm2-%j.out          # Log output file (%j = job ID)
#SBATCH --ntasks=1                      # Number of parallel tasks
#SBATCH --cpus-per-task=32              # Number of CPU cores allocated per task

# Load the Open Babel module (compiled with GCC 10.2.0)
module load openbabel-3.0.0-gcc-10.2.0-hensxki

# -----------------------------------------------------------------------------
# Define input and output directories
# -----------------------------------------------------------------------------
INPUT_DIR="Ligands_SDF"       # Directory containing ligands in SDF format
OUTPUT_DIR="Ligands_PDBQT"    # Destination directory for PDBQT output files

# Create the output directory if it does not exist (no error if already present)
mkdir -p "$OUTPUT_DIR"

# -----------------------------------------------------------------------------
# Conversion loop: process each SDF file individually
# -----------------------------------------------------------------------------
for f in "$INPUT_DIR"/*.sdf; do

    # Extract the base name of the file (without .sdf extension)
    b=$(basename "$f" .sdf)

    echo ">>> Processing ligand: $b"

    # Convert SDF -> PDBQT with energy minimization:
    #   -isdf           : input format SDF
    #   -opdbqt         : output format PDBQT (AutoDock-compatible)
    #   -O              : output file path
    #   --minimize      : enable geometry energy minimization
    #   --steps 2500    : maximum number of minimization steps
    #   --sd            : Steepest Descent algorithm for minimization
    #   --ff MMFF94     : Merck Molecular Force Field (suited for small molecules)
    obabel -isdf "$f" \
           -opdbqt \
           -O "$OUTPUT_DIR/$b.pdbqt" \
           --minimize \
           --steps 2500 \
           --sd \
           --ff MMFF94

    # Check whether the conversion was successful
    if [[ $? -eq 0 ]]; then
        echo "    [OK] $b.pdbqt successfully generated."
    else
        echo "    [ERROR] Conversion failed for: $b"
    fi

done

# -----------------------------------------------------------------------------
echo "====================================================="
echo " Conversion completed for all SDF files."
echo " PDBQT files available in: $OUTPUT_DIR"
echo "====================================================="