forked from MoradMMokhtar/MegaSSR
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMegaSSR.sh
More file actions
executable file
·2376 lines (1982 loc) · 97.4 KB
/
Copy pathMegaSSR.sh
File metadata and controls
executable file
·2376 lines (1982 loc) · 97.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
# MegaSSR v3.0 - SSR Identification and Primer Design Pipeline
# Author: Zakaria Mahmoud
# Website: www.mahmoud.ma
# Date: March 01, 2026
#
# Clean rebuild with modular architecture
#
#=============================================================================
# Strict Error Handling
#=============================================================================
set -eo pipefail
# Temporarily disable error trap for debugging
# trap 'error_handler $? $LINENO' ERR
#=============================================================================
# Script Constants
#=============================================================================
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_NAME="$(basename "${BASH_SOURCE[0]}")"
readonly VERSION="3.0.0"
readonly TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
# Load configuration
if [[ -f "${SCRIPT_DIR}/config/megassr.env" ]]; then
source "${SCRIPT_DIR}/config/megassr.env"
fi
# Load utility functions
if [[ -f "${SCRIPT_DIR}/utils/functions.sh" ]]; then
source "${SCRIPT_DIR}/utils/functions.sh"
fi
# Default paths
BIN_DIR="${SCRIPT_DIR}/bin/Script"
RESULTS_DIR="${SCRIPT_DIR}/results"
LOG_DIR="${SCRIPT_DIR}/logs"
TMP_DIR="${SCRIPT_DIR}/tmp"
#=============================================================================
# Global Variables
#=============================================================================
ANALYSIS_TYPE=1
FASTA_FILE=""
GFF_FILE=""
PROJECT_NAME="megassr_${TIMESTAMP}"
OUTPUT_DIR=""
EMAIL=""
THREADS="${NUM_THREADS:-4}"
# Additional parameters for compatibility
ALLELES="no"
MAX_ALLELE_LENGTH="1000"
PRIMER_IMAGE="50"
# SSR detection parameters (from config or defaults)
MONO_THRESHOLD="${MONO_THRESHOLD:-20}"
DI_THRESHOLD="${DI_THRESHOLD:-6}"
TRI_THRESHOLD="${TRI_THRESHOLD:-5}"
TETRA_THRESHOLD="${TETRA_THRESHOLD:-4}"
PENTA_THRESHOLD="${PENTA_THRESHOLD:-3}"
HEXA_THRESHOLD="${HEXA_THRESHOLD:-3}"
COMPOUND_DISTANCE="${COMPOUND_DISTANCE:-100}"
# Primer design parameters
PRIMER_MIN="${PRIMER_MIN_SIZE:-18}"
PRIMER_OPT="${PRIMER_OPT_SIZE:-20}"
PRIMER_MAX="${PRIMER_MAX_SIZE:-22}"
PCR_MIN="${PCR_MIN_SIZE:-250}"
PCR_MAX="${PCR_MAX_SIZE:-500}"
# Feature type for annotation
GENIC_FEATURE="gene"
# Checkpoint/Resume options
RESUME_MODE=false
RESTART_MODE=false
CHECKPOINT_FILE=""
# NCBI FTP download options
NCBI_FASTA_URL=""
NCBI_GFF_URL=""
#=============================================================================
# Usage Information
#=============================================================================
usage() {
cat << EOF
MegaSSR v${VERSION} - SSR Identification and Primer Design Pipeline
USAGE:
$SCRIPT_NAME --analysis <type> --fasta <file> --project <name> [options]
REQUIRED:
--analysis, -A <1|2> Analysis type:
1 = SSR detection + primer design (no GFF needed)
- Identifies all SSRs in the genome
- Designs primers for ALL SSRs
- Generates statistics and 3 visualization plots
2 = Full analysis with gene annotation (requires GFF)
- Identifies all SSRs in the genome
- Classifies SSRs as genic/intergenic using GFF
- Designs primers for both genic and intergenic SSRs
- Generates detailed statistics and 7 plots
--fasta, -F <file> Input FASTA file (genome sequence)
--project, -P <name> Project name
OPTIONAL:
--gff, -G <file> GFF annotation file (required for --analysis 2)
--feature, -g <type> Genic feature type (default: ${GENIC_FEATURE})
--threads, -T <n> Number of threads (default: ${THREADS})
--email, -E <addr> Email for notifications
SSR Mining Parameters:
--mono <n> Mononucleotide threshold (default: ${MONO_THRESHOLD})
--di <n> Dinucleotide threshold (default: ${DI_THRESHOLD})
--tri <n> Trinucleotide threshold (default: ${TRI_THRESHOLD})
--tetra <n> Tetranucleotide threshold (default: ${TETRA_THRESHOLD})
--penta <n> Pentanucleotide threshold (default: ${PENTA_THRESHOLD})
--hexa <n> Hexanucleotide threshold (default: ${HEXA_THRESHOLD})
--compound <n> Max distance between 2 SSRs (default: ${COMPOUND_DISTANCE})
Primer Design Options:
--primer-min, -s <n> Minimum primer size (default: ${PRIMER_MIN})
--primer-opt, -o <n> Optimal primer size (default: ${PRIMER_OPT})
--primer-max, -S <n> Maximum primer size (default: ${PRIMER_MAX})
--product-min, -r <n> Min product size range (default: ${PCR_MIN})
--product-max, -R <n> Max product size range (default: ${PCR_MAX})
In Silico Validation:
--validate, -v <yes|no> Validate designed SSR primers (default: ${ALLELES})
--allele-length, -l <n> Max length for allele search (default: ${MAX_ALLELE_LENGTH})
--primers-per-image, -i <n> Max primers per image (default: ${PRIMER_IMAGE})
Checkpoint/Resume:
--resume Resume from last completed phase
--restart Restart from beginning (clear checkpoints)
NCBI Download:
--ncbi-fasta <url> Download FASTA from NCBI FTP link
Example: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/.../xxx_genomic.fna.gz
--ncbi-gff <url> Download GFF from NCBI FTP link
Example: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/.../xxx_genomic.gff.gz
-h, --help Show this help message
EXAMPLES:
# SSR identification with primer design (no GFF needed)
$SCRIPT_NAME --analysis 1 --fasta genome.fa --project my_project
# Full analysis with gene annotation and custom parameters
$SCRIPT_NAME --analysis 2 --fasta genome.fa --gff annotation.gff --project my_project \\
--mono 20 --di 6 --tri 5 --tetra 4 --penta 3 --hexa 3 \\
--primer-min 18 --primer-opt 20 --primer-max 22 \\
--product-min 250 --product-max 500 --feature gene
# Resume from last checkpoint (if pipeline failed or was interrupted)
$SCRIPT_NAME --analysis 2 --fasta genome.fa --gff annotation.gff --project my_project --resume
# Download from NCBI FTP and run analysis
$SCRIPT_NAME --analysis 2 --project my_project \\
--ncbi-fasta https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/002/846/995/GCF_002846995.1_ASM284699v1/GCF_002846995.1_ASM284699v1_genomic.fna.gz \\
--ncbi-gff https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/002/846/995/GCF_002846995.1_ASM284699v1/GCF_002846995.1_ASM284699v1_genomic.gff.gz
# Mix local file and NCBI download
$SCRIPT_NAME --analysis 2 --project my_project \\
--fasta local_genome.fa \\
--ncbi-gff https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/.../xxx_genomic.gff.gz
# Restart fresh (ignore previous checkpoints)
$SCRIPT_NAME --analysis 2 --fasta genome.fa --gff annotation.gff --project my_project --restart
CHECKPOINT SYSTEM:
MegaSSR automatically saves progress after each phase. If the pipeline fails
or is interrupted, use --resume to continue from the last completed phase.
Phases: 2=SSR Detection, 3=Gene Annotation, 4=Genic Primers,
5=Intergenic Primers, 6=Post-processing, 7=Statistics, 8=Visualizations
Checkpoint file: results/<project>/.megassr_checkpoint
EOF
exit 0
}
#=============================================================================
# Parse Command Line Arguments
#=============================================================================
parse_arguments() {
while [[ $# -gt 0 ]]; do
case $1 in
# Required arguments
--analysis|-A) ANALYSIS_TYPE="$2"; shift 2 ;;
--fasta|-F) FASTA_FILE="$2"; shift 2 ;;
--gff|-G) GFF_FILE="$2"; shift 2 ;;
--project|-P) PROJECT_NAME="$2"; shift 2 ;;
# General options
--feature|-g) GENIC_FEATURE="$2"; shift 2 ;;
--threads|-T|-t) THREADS="$2"; shift 2 ;;
--email|-e|-E) EMAIL="$2"; shift 2 ;;
# SSR mining parameters
--mono) MONO_THRESHOLD="$2"; shift 2 ;;
--di) DI_THRESHOLD="$2"; shift 2 ;;
--tri) TRI_THRESHOLD="$2"; shift 2 ;;
--tetra) TETRA_THRESHOLD="$2"; shift 2 ;;
--penta) PENTA_THRESHOLD="$2"; shift 2 ;;
--hexa) HEXA_THRESHOLD="$2"; shift 2 ;;
--compound|-C) COMPOUND_DISTANCE="$2"; shift 2 ;;
# Primer design options
--primer-min|-s) PRIMER_MIN="$2"; shift 2 ;;
--primer-opt|-o|-O) PRIMER_OPT="$2"; shift 2 ;;
--primer-max|-S) PRIMER_MAX="$2"; shift 2 ;;
--product-min|-r) PCR_MIN="$2"; shift 2 ;;
--product-max|-R) PCR_MAX="$2"; shift 2 ;;
# In silico validation options
--validate|-v|-B) ALLELES="$2"; shift 2 ;;
--allele-length|-l|-L) MAX_ALLELE_LENGTH="$2"; shift 2 ;;
--primers-per-image|-i|-I) PRIMER_IMAGE="$2"; shift 2 ;;
# Checkpoint/Resume options
--resume) RESUME_MODE=true; shift ;;
--restart) RESTART_MODE=true; shift ;;
# NCBI FTP download
--ncbi-fasta) NCBI_FASTA_URL="$2"; shift 2 ;;
--ncbi-gff) NCBI_GFF_URL="$2"; shift 2 ;;
-h|--help) usage ;;
*) log ERROR "Unknown option: $1"; usage ;;
esac
done
# Validate required arguments
# If NCBI URL is provided, local file is not required (will be downloaded)
if [[ -z "$NCBI_FASTA_URL" ]] && [[ -z "$FASTA_FILE" ]]; then
log ERROR "Missing required arguments: provide --fasta or --ncbi-fasta"
usage
fi
if [[ -z "$PROJECT_NAME" ]]; then
log ERROR "Missing required argument: --project"
usage
fi
# For Analysis Type 2, GFF is required (from local file or NCBI)
if [[ "$ANALYSIS_TYPE" == "2" ]] && [[ -z "$GFF_FILE" ]] && [[ -z "$NCBI_GFF_URL" ]]; then
log ERROR "Analysis type 2 requires GFF file: use --gff or --ncbi-gff"
exit 1
fi
}
#=============================================================================
# NCBI FTP Download Functions
#=============================================================================
# Validate NCBI FTP URL format
validate_ncbi_url() {
local url="$1"
local file_type="$2" # "FASTA" or "GFF"
if [[ ! "$url" =~ ^https://ftp\.ncbi\.nlm\.nih\.gov/ ]]; then
log ERROR "Invalid NCBI FTP URL for $file_type"
log ERROR "URL must start with: https://ftp.ncbi.nlm.nih.gov/"
log ERROR "Provided: $url"
return 1
fi
return 0
}
# Download a file from NCBI FTP
download_ncbi_file() {
local url="$1"
local output_path="$2"
local file_type="$3" # "FASTA" or "GFF"
log INFO "Downloading $file_type from NCBI FTP..."
log INFO "URL: $url"
# Validate URL
validate_ncbi_url "$url" "$file_type" || exit 1
# Download using wget or curl
if command -v wget &> /dev/null; then
wget -q --show-progress -O "$output_path" "$url" || {
log ERROR "Failed to download $file_type file"
exit 1
}
elif command -v curl &> /dev/null; then
curl -# -L -o "$output_path" "$url" || {
log ERROR "Failed to download $file_type file"
exit 1
}
else
log ERROR "Neither wget nor curl is available for downloading"
exit 1
fi
log INFO "$file_type downloaded: $output_path"
}
# Download FASTA from NCBI if URL provided
download_ncbi_fasta() {
local url="$1"
local download_dir="$2"
mkdir -p "$download_dir"
local filename=$(basename "$url")
local output_path="${download_dir}/${filename}"
download_ncbi_file "$url" "$output_path" "FASTA"
# Set global variable
FASTA_FILE="$output_path"
}
# Download GFF from NCBI if URL provided
download_ncbi_gff() {
local url="$1"
local download_dir="$2"
mkdir -p "$download_dir"
local filename=$(basename "$url")
local output_path="${download_dir}/${filename}"
download_ncbi_file "$url" "$output_path" "GFF"
# Set global variable
GFF_FILE="$output_path"
}
#=============================================================================
# Checkpoint Functions
#=============================================================================
# Initialize checkpoint file path
init_checkpoint() {
CHECKPOINT_FILE="${OUTPUT_DIR}/.megassr_checkpoint"
}
# Save checkpoint after completing a phase
# NOTE: Prevents duplicate entries by removing any existing entry for the same phase
save_checkpoint() {
local phase="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
# Remove any existing entry for this phase to prevent duplicates
if [[ -f "$CHECKPOINT_FILE" ]]; then
local temp_file=$(mktemp)
grep -v "^${phase}|" "$CHECKPOINT_FILE" > "$temp_file" 2>/dev/null || true
mv "$temp_file" "$CHECKPOINT_FILE"
fi
echo "${phase}|${timestamp}" >> "$CHECKPOINT_FILE"
log DEBUG "Checkpoint saved: Phase $phase completed at $timestamp"
}
# Get the last completed phase number
get_last_checkpoint() {
if [[ -f "$CHECKPOINT_FILE" ]]; then
local last_line=$(tail -1 "$CHECKPOINT_FILE" 2>/dev/null)
local phase=$(echo "$last_line" | cut -d'|' -f1)
echo "$phase"
else
echo "0"
fi
}
# Check if a phase should be skipped (already completed)
should_skip_phase() {
local phase="$1"
local last_completed=$(get_last_checkpoint)
if [[ "$RESUME_MODE" == "true" ]] && [[ "$last_completed" -ge "$phase" ]]; then
return 0 # true - skip this phase
fi
return 1 # false - run this phase
}
# Clear all checkpoints
clear_checkpoints() {
if [[ -f "$CHECKPOINT_FILE" ]]; then
rm -f "$CHECKPOINT_FILE"
log INFO "Checkpoints cleared - starting fresh"
fi
}
# Display checkpoint status
show_checkpoint_status() {
if [[ -f "$CHECKPOINT_FILE" ]]; then
log INFO "Previous run detected. Checkpoint history:"
while IFS='|' read -r phase timestamp; do
log INFO " Phase $phase completed at $timestamp"
done < "$CHECKPOINT_FILE"
local last=$(get_last_checkpoint)
log INFO "Resuming from Phase $((last + 1))"
fi
}
#=============================================================================
# Initialize Pipeline
#=============================================================================
initialize_pipeline() {
log INFO "=========================================="
log INFO "MegaSSR v${VERSION}"
log INFO "=========================================="
log INFO "Project: $PROJECT_NAME"
log INFO "Analysis Type: $ANALYSIS_TYPE"
# Create output directory first (needed for NCBI download)
OUTPUT_DIR="${RESULTS_DIR}/${PROJECT_NAME}"
mkdir -p "$OUTPUT_DIR"
mkdir -p "${OUTPUT_DIR}/fasta"
mkdir -p "${OUTPUT_DIR}/intermediate"
mkdir -p "${LOG_DIR}"
mkdir -p "${TMP_DIR}/${PROJECT_NAME}"
# Download from NCBI if URLs provided
local download_dir="${OUTPUT_DIR}/ncbi_download"
if [[ -n "$NCBI_FASTA_URL" ]]; then
log INFO "=========================================="
log INFO "Downloading from NCBI FTP"
log INFO "=========================================="
download_ncbi_fasta "$NCBI_FASTA_URL" "$download_dir"
fi
if [[ -n "$NCBI_GFF_URL" ]]; then
if [[ -z "$NCBI_FASTA_URL" ]]; then
log INFO "=========================================="
log INFO "Downloading from NCBI FTP"
log INFO "=========================================="
fi
download_ncbi_gff "$NCBI_GFF_URL" "$download_dir"
fi
if [[ -n "$NCBI_FASTA_URL" ]] || [[ -n "$NCBI_GFF_URL" ]]; then
log INFO "NCBI download complete!"
log INFO "=========================================="
fi
log INFO "FASTA: $FASTA_FILE"
[[ -n "$GFF_FILE" ]] && log INFO "GFF: $GFF_FILE"
log INFO "Threads: $THREADS"
log INFO "=========================================="
# Initialize checkpoint system
init_checkpoint
# Handle restart mode - clear existing checkpoints
if [[ "$RESTART_MODE" == "true" ]]; then
clear_checkpoints
fi
# Handle resume mode - show status
if [[ "$RESUME_MODE" == "true" ]]; then
show_checkpoint_status
fi
# Validate input files
validate_fasta "$FASTA_FILE" || exit 1
if [[ -n "$GFF_FILE" ]]; then
validate_gff "$GFF_FILE" || exit 1
# Check chromosome ID consistency between FASTA and GFF
validate_chromosome_consistency "$FASTA_FILE" "$GFF_FILE"
fi
# Activate conda environment (non-critical)
log DEBUG "About to call activate_conda_env"
set +e # Disable exit on error
activate_conda_env "$CONDA_ENV"
local conda_result=$?
set -e # Re-enable exit on error
log DEBUG "activate_conda_env returned: $conda_result"
log INFO "Initialization complete"
}
#=============================================================================
# Phase 2: SSR Identification using MISA
#=============================================================================
run_ssr_identification() {
log INFO "=========================================="
log INFO "PHASE 2: SSR Identification (MISA)"
log INFO "=========================================="
local fasta_dir="${OUTPUT_DIR}/fasta"
local genome_fasta="${fasta_dir}/${PROJECT_NAME}_genomic.fa"
# Copy FASTA to working directory (decompress if gzipped)
log DEBUG "Preparing genome FASTA file"
if [[ "$FASTA_FILE" == *.gz ]]; then
log DEBUG "Decompressing gzipped FASTA file"
zcat "$FASTA_FILE" > "${genome_fasta}.tmp"
else
cp "$FASTA_FILE" "${genome_fasta}.tmp"
fi
# Normalize FASTA headers: replace spaces with underscores for consistency
# MISA converts spaces to underscores in chromosome IDs, so we do the same in the FASTA
# This ensures extraction scripts can match chromosome IDs correctly
log DEBUG "Normalizing FASTA headers (spaces → underscores)"
sed 's/^>\([^ ]*\) />\1_/; :a; s/^\(>[^ ]*\) /\1_/; ta' "${genome_fasta}.tmp" > "$genome_fasta"
rm -f "${genome_fasta}.tmp"
# Create MISA configuration file
local misa_ini="${fasta_dir}/misa.ini"
cat > "$misa_ini" << EOF
definition(unit_size,min_repeats): 1-${MONO_THRESHOLD} 2-${DI_THRESHOLD} 3-${TRI_THRESHOLD} 4-${TETRA_THRESHOLD} 5-${PENTA_THRESHOLD} 6-${HEXA_THRESHOLD}
interruptions(max_difference_between_2_SSRs): ${COMPOUND_DISTANCE}
EOF
log DEBUG "MISA configuration:"
log DEBUG " Mono: ${MONO_THRESHOLD}, Di: ${DI_THRESHOLD}, Tri: ${TRI_THRESHOLD}"
log DEBUG " Tetra: ${TETRA_THRESHOLD}, Penta: ${PENTA_THRESHOLD}, Hexa: ${HEXA_THRESHOLD}"
log DEBUG " Compound distance: ${COMPOUND_DISTANCE}"
# Run MISA
log INFO "Running MISA for SSR detection"
cd "$fasta_dir" || exit 1
perl "${BIN_DIR}/misa.pl" "$genome_fasta" "$fasta_dir" 2>&1 | tee -a "${LOG_DIR}/${PROJECT_NAME}.log" || {
log ERROR "MISA execution failed"
exit 1
}
cd - > /dev/null
# Check MISA output
local misa_output="${genome_fasta}.misa"
if [[ ! -f "$misa_output" ]] || [[ ! -s "$misa_output" ]]; then
log ERROR "MISA did not produce output file"
exit 1
fi
# Create formatted SSR list (add organism ID and convert type codes)
local ssr_file="${OUTPUT_DIR}/intermediate/${PROJECT_NAME}_SSR.txt"
awk -F'\t' -v org="$PROJECT_NAME" '{print "\t" org "\t" $1 "\t" $2 "\t" $3 "\t" $4 "\t" $5 "\t" $6 "\t" $7}' "$misa_output" | \
sed 's/\tp1\t/\tMono\t/g' | \
sed 's/\tp2\t/\tDi\t/g' | \
sed 's/\tp3\t/\tTri\t/g' | \
sed 's/\tp4\t/\tTetra\t/g' | \
sed 's/\tp5\t/\tPenta\t/g' | \
sed 's/\tp6\t/\tHexa\t/g' | \
sed 's/\tc\t/\tCompound\t/g' | \
sed 's/\tc\*\t/\tCompound\t/g' > "$ssr_file"
local ssr_count=$(wc -l < "$ssr_file")
log INFO "SSR identification complete: $ssr_count SSRs found"
# Create SSR statistics summary
local stats_file="${genome_fasta}.statistics"
if [[ -f "$stats_file" ]]; then
log DEBUG "MISA statistics generated"
cp "$stats_file" "${OUTPUT_DIR}/${PROJECT_NAME}-MegaSSR_Results/SSR_statistics.txt" 2>/dev/null || true
fi
# For Analysis Type 1 (no GFF): treat ALL SSRs as intergenic
# This matches the behavior of the old MegaSSR where -A 1 designed primers for all SSRs
if [[ "$ANALYSIS_TYPE" == "1" ]]; then
log INFO "Analysis Type 1: Treating all $ssr_count SSRs as intergenic (no gene annotation)"
local intergenic_file="${OUTPUT_DIR}/intermediate/${PROJECT_NAME}_Accept_Intergenic_SSR.txt"
cp "$ssr_file" "$intergenic_file"
log DEBUG "Created intergenic SSR file from all SSRs"
fi
log INFO "SSR identification phase complete"
}
#=============================================================================
# Phase 3: Gene Annotation (Genic vs Intergenic Classification)
#=============================================================================
run_gene_annotation() {
log INFO "=========================================="
log INFO "PHASE 3: Gene Annotation"
log INFO "=========================================="
local intermediate_dir="${OUTPUT_DIR}/intermediate"
local ssr_file="${intermediate_dir}/${PROJECT_NAME}_SSR.txt"
local gff_features="${intermediate_dir}/${PROJECT_NAME}_gff_features.txt"
# Extract specified features from GFF
log INFO "Extracting '$GENIC_FEATURE' features from GFF"
python3 "${BIN_DIR}/extract_gff_features.py" \
"$GFF_FILE" \
"$GENIC_FEATURE" \
"$gff_features" || {
log ERROR "Failed to extract GFF features"
exit 1
}
local feature_count=$(wc -l < "$gff_features")
log DEBUG "Extracted $feature_count $GENIC_FEATURE features"
# Run genic SSR classification
log INFO "Classifying SSRs as genic or intergenic"
local genic_with_feature="${intermediate_dir}/${PROJECT_NAME}.Genic_SSR_with_feature.txt"
local genic_for_db="${OUTPUT_DIR}/${PROJECT_NAME}-MegaSSR_Results/${PROJECT_NAME}.Genic_SSR_with_feature.txt"
local genic_no_feature="${intermediate_dir}/${PROJECT_NAME}.Genic_SSR_none_feature.txt"
mkdir -p "${OUTPUT_DIR}/${PROJECT_NAME}-MegaSSR_Results"
perl "${BIN_DIR}/get-genic-SSR.pl" \
"$ssr_file" \
"$gff_features" \
"$genic_with_feature" \
"$genic_for_db" \
"$genic_no_feature" 2>&1 | tee -a "${LOG_DIR}/${PROJECT_NAME}.log" || {
log WARN "Genic annotation completed with warnings"
}
# Count results
local genic_count=0
[[ -f "$genic_with_feature" ]] && genic_count=$(wc -l < "$genic_with_feature")
log INFO "Genic SSRs identified: $genic_count"
# Create intergenic SSR file using grep to exclude genic SSRs
# The genic_no_feature file contains SSRs that ARE in genes (despite the name)
# It may contain duplicates (SSRs overlapping multiple genes), so deduplicate first
# Use grep -F -x -v -f to find SSRs in original list NOT in genic list
local intergenic_file="${intermediate_dir}/${PROJECT_NAME}_Accept_Intergenic_SSR.txt"
if [[ -f "$genic_no_feature" ]] && [[ -s "$genic_no_feature" ]]; then
log DEBUG "Finding intergenic SSRs using grep exclusion (after deduplication)"
# Deduplicate genic file first to avoid grep issues with duplicate patterns
sort -u "$genic_no_feature" > "${genic_no_feature}.uniq"
grep -F -x -v -f "${genic_no_feature}.uniq" "$ssr_file" > "$intergenic_file" || {
log WARN "No intergenic SSRs found (all SSRs are genic)"
touch "$intergenic_file"
}
rm -f "${genic_no_feature}.uniq"
else
# If no genic SSRs found, all SSRs are intergenic
log DEBUG "No genic SSRs found, all SSRs are intergenic"
cp "$ssr_file" "$intergenic_file"
fi
local intergenic_count=0
[[ -f "$intergenic_file" ]] && intergenic_count=$(wc -l < "$intergenic_file")
log INFO "Intergenic SSRs identified: $intergenic_count"
# Validation
local total_ssr=$(wc -l < "$ssr_file")
log INFO "Total SSRs: $total_ssr (Genic: $genic_count, Intergenic: $intergenic_count)"
log INFO "Gene annotation phase complete"
}
#=============================================================================
# Phase 4: Genic Primer Design
#=============================================================================
run_genic_primer_design() {
log INFO "=========================================="
log INFO "PHASE 4: Genic Primer Design"
log INFO "=========================================="
local intermediate_dir="${OUTPUT_DIR}/intermediate"
local results_dir="${OUTPUT_DIR}/${PROJECT_NAME}-MegaSSR_Results"
local genic_with_feature="${results_dir}/${PROJECT_NAME}.Genic_SSR_with_feature.txt"
# Check if genic SSR file exists
if [[ ! -f "$genic_with_feature" ]] || [[ ! -s "$genic_with_feature" ]]; then
log WARN "No genic SSRs found, skipping genic primer design"
return 0
fi
local genic_count=$(wc -l < "$genic_with_feature")
# Subtract 1 for header if present
if head -1 "$genic_with_feature" | grep -q "Process Id"; then
genic_count=$((genic_count - 1))
fi
log INFO "Designing primers for $genic_count genic SSRs"
# Create formatted genic SSR file for primer design (like reference table11_Genic_misa_feature.txt)
# Input format (16 fields): empty, project_id, chr_id, repeat_num, repeat_type, repeat_seq, repeat_len, start, end, gene, gene_start, gene_end, ., strand, ., annotation
# Output format (14 fields): empty, project_id, chr_id, repeat_num, repeat_type, repeat_seq, repeat_len, start, end, gene, gene_start, gene_end, strand, annotation
local genic_formatted="${intermediate_dir}/${PROJECT_NAME}_Genic_SSR_for_primer.txt"
# Note: Input file has NO header at this point (header is added in Phase 6 post-processing)
# Reformat 16-field input to 14-field output for primer design
awk -F '\t' '{ print $1"\t"$2"\t"$3"\t"$4"\t"$5"\t"$6"\t"$7"\t"$8"\t"$9"\t"$10"\t"$11"\t"$12"\t"$14"\t"$16 }' "$genic_with_feature" > "$genic_formatted"
log DEBUG "Created formatted genic SSR file for primer design ($(wc -l < "$genic_formatted") entries)"
# Create working directories (clean first to avoid append issues)
local gdesignprimer_dir="${OUTPUT_DIR}/gdesignprimer"
local gdesignprimer_results="${OUTPUT_DIR}/gdesignprimerresults"
rm -rf "$gdesignprimer_dir" "$gdesignprimer_results"
mkdir -p "$gdesignprimer_dir" "$gdesignprimer_results"
# Split formatted genic SSR file into chunks of 500 for parallel processing
log DEBUG "Splitting genic SSRs into chunks of 500"
cd "$gdesignprimer_dir" || exit 1
split -d -l 500 "$genic_formatted"
local split_count=$(ls -1 x* 2>/dev/null | wc -l)
log DEBUG "Created $split_count split files for processing"
if [[ $split_count -eq 0 ]]; then
log ERROR "Failed to create split files"
exit 1
fi
# Process each split file with gdesignprimer_threads.py
log INFO "Extracting flanking sequences for genic SSRs"
local genome_fasta="${OUTPUT_DIR}/fasta/${PROJECT_NAME}_genomic.fa"
# gdesignprimer_threads.py expects: genome_fasta split_dir results_dir threads extractseq_script p3_in_script
python3 "${BIN_DIR}/gdesignprimer_threads.py" \
"$genome_fasta" \
"$gdesignprimer_dir" \
"$gdesignprimer_results" \
"$THREADS" \
"${BIN_DIR}/extractseq-id-start-end-genic.pl" \
"${BIN_DIR}/modified_p3_in_genic.pl" || {
log WARN "Warning during sequence extraction"
}
# Concatenate all extracted sequences
local flanking_fa="${results_dir}/Genic_SSR_flanking_regions.fa"
if ls "$gdesignprimer_results"/*.fa 1>/dev/null 2>&1; then
cat "$gdesignprimer_results"/*.fa > "$flanking_fa"
local flanking_count=$(grep -c "^>" "$flanking_fa" || echo "0")
log INFO "Extracted flanking sequences: $flanking_count"
else
log WARN "No flanking sequences extracted"
touch "$flanking_fa"
fi
# Run actual primer design using gdesignprimer2_threads.py
log INFO "Running Primer3 for genic SSR primer design"
python3 "${BIN_DIR}/gdesignprimer2_threads.py" \
"$gdesignprimer_dir" \
"$gdesignprimer_results" \
"$THREADS" \
"${BIN_DIR}/extractseq-id-start-end-genic.pl" \
"${BIN_DIR}/modified_p3_in_genic.pl" \
"$PROJECT_NAME" \
"${BIN_DIR}/modified_p3_out-genic.pl" \
"${BIN_DIR}/print-primers-line-genicCCC.pl" \
"$intermediate_dir" || {
log ERROR "Primer design failed"
exit 1
}
# Deduplicate primers (by strand and GC%)
local primers_raw="${intermediate_dir}/${PROJECT_NAME}.Extract-Genic-seq-out.fasta.results2.txt"
local primers_dedup1="${intermediate_dir}/${PROJECT_NAME}.Extract-Genic-seq-out.fasta.results2_2.txt"
local primers_final="${results_dir}/${PROJECT_NAME}.Genic-primers.txt"
if [[ -f "$primers_raw" ]] && [[ -s "$primers_raw" ]]; then
log DEBUG "Deduplicating primers by strand (field 15)"
awk '!seen[$15]++' "$primers_raw" > "$primers_dedup1"
log DEBUG "Deduplicating primers by GC% (field 19)"
awk '!seen[$19]++' "$primers_dedup1" > "$primers_final"
local final_count=$(wc -l < "$primers_final")
log INFO "Genic primers designed: $final_count"
# Create statistics file
local stats_file="${intermediate_dir}/${PROJECT_NAME}.Extract-Genic-out.fasta.stat"
echo -e "$final_count\t${PROJECT_NAME}.Genic-primers.txt" > "$stats_file"
else
log WARN "No primers generated"
touch "$primers_final"
fi
log INFO "Genic primer design phase complete"
}
#=============================================================================
# Phase 5: Intergenic Primer Design
#=============================================================================
run_intergenic_primer_design() {
log INFO "=========================================="
log INFO "PHASE 5: Intergenic Primer Design"
log INFO "=========================================="
local intermediate_dir="${OUTPUT_DIR}/intermediate"
local results_dir="${OUTPUT_DIR}/${PROJECT_NAME}-MegaSSR_Results"
local intergenic_file="${intermediate_dir}/${PROJECT_NAME}_Accept_Intergenic_SSR.txt"
# Ensure results directory exists (important for Analysis Type 1 which skips Phase 3-4)
mkdir -p "$results_dir"
# Check if intergenic SSR file exists
if [[ ! -f "$intergenic_file" ]] || [[ ! -s "$intergenic_file" ]]; then
log WARN "No intergenic SSRs found, skipping intergenic primer design"
return 0
fi
local intergenic_count=$(wc -l < "$intergenic_file")
log INFO "Designing primers for $intergenic_count intergenic SSRs"
# Create working directories (clean first to avoid append issues)
local designprimer_dir="${OUTPUT_DIR}/designprimer"
local designprimer_results="${OUTPUT_DIR}/designprimerresults"
rm -rf "$designprimer_dir" "$designprimer_results"
mkdir -p "$designprimer_dir" "$designprimer_results"
# Split intergenic SSR file into chunks of 500 for parallel processing
log DEBUG "Splitting intergenic SSRs into chunks of 500"
cd "$designprimer_dir" || exit 1
split -d -l 500 "$intergenic_file"
local split_count=$(ls -1 x* 2>/dev/null | wc -l)
log DEBUG "Created $split_count split files for processing"
if [[ $split_count -eq 0 ]]; then
log ERROR "Failed to create split files"
exit 1
fi
# Process split files with xdesignprimer_threads.py for sequence extraction
log INFO "Extracting flanking sequences for intergenic SSRs"
local genome_fasta="${OUTPUT_DIR}/fasta/${PROJECT_NAME}_genomic.fa"
# xdesignprimer_threads.py expects: genome_fasta split_dir results_dir threads extractseq_script p3_in_script
python3 "${BIN_DIR}/xdesignprimer_threads.py" \
"$genome_fasta" \
"$designprimer_dir" \
"$designprimer_results" \
"$THREADS" \
"${BIN_DIR}/extractseq-id-start-end-intergenic.pl" \
"${BIN_DIR}/modified_p3_in.pl" || {
log WARN "Warning during sequence extraction"
}
# Concatenate all extracted sequences
local flanking_fa="${results_dir}/Intergenic_SSR_flanking_regions.fa"
if ls "$designprimer_results"/*.fa 1>/dev/null 2>&1; then
cat "$designprimer_results"/*.fa > "$flanking_fa"
local flanking_count=$(grep -c "^>" "$flanking_fa" || echo "0")
log INFO "Extracted flanking sequences: $flanking_count"
else
log WARN "No flanking sequences extracted"
touch "$flanking_fa"
fi
# Run actual primer design using designprimer3_threads.py
log INFO "Running Primer3 for intergenic SSR primer design"
python3 "${BIN_DIR}/designprimer3_threads.py" \
"$designprimer_dir" \
"$designprimer_results" \
"$THREADS" \
"${BIN_DIR}/extractseq-id-start-end-intergenic.pl" \
"${BIN_DIR}/modified_p3_in.pl" \
"$PROJECT_NAME" \
"${BIN_DIR}/modified_p3_out-intergenic.pl" \
"${BIN_DIR}/print-primers-line-nongenicCCC.pl" \
"$intermediate_dir" || {
log ERROR "Primer design failed"
exit 1
}
# Deduplicate primers (by SSR position field 9 and GC% field 13)
local primers_raw="${intermediate_dir}/${PROJECT_NAME}.interGenic-primers3.txt"
local primers_dedup1="${intermediate_dir}/${PROJECT_NAME}.interGenic-primers3_2.txt"
local primers_final="${results_dir}/${PROJECT_NAME}.interGenic-primers.txt"
if [[ -f "$primers_raw" ]] && [[ -s "$primers_raw" ]]; then
log DEBUG "Deduplicating primers by SSR position (field 9)"
awk '!seen[$9]++' "$primers_raw" > "$primers_dedup1"
log DEBUG "Deduplicating primers by GC% (field 13)"
awk '!seen[$13]++' "$primers_dedup1" > "$primers_final"
local final_count=$(wc -l < "$primers_final")
log INFO "Intergenic primers designed: $final_count"
# Create statistics file
local stats_file="${intermediate_dir}/${PROJECT_NAME}.Extract-intergenic-out.fasta.stat"
echo -e "$final_count\t${PROJECT_NAME}.interGenic-primers.txt" > "$stats_file"
else
log WARN "No primers generated"
touch "$primers_final"
fi
log INFO "Intergenic primer design phase complete"
}
#=============================================================================
# Phase 6: Post-processing and Output Formatting
#=============================================================================
run_post_processing() {
log INFO "=========================================="
log INFO "PHASE 6: Post-processing"
log INFO "=========================================="
local intermediate_dir="${OUTPUT_DIR}/intermediate"
local results_dir="${OUTPUT_DIR}/${PROJECT_NAME}-MegaSSR_Results"
# Generate SSR statistics from MISA output
generate_ssr_statistics
# Create non-redundant SSR library if usearch available
create_nonredundant_library
# Export final CSVs with friendly names
export_csv_files
log INFO "Post-processing complete"
}
generate_ssr_statistics() {
log INFO "Generating SSR statistics"
local misa_stats="${OUTPUT_DIR}/fasta/${PROJECT_NAME}_genomic.fa.statistics"
local results_dir="${OUTPUT_DIR}/${PROJECT_NAME}-MegaSSR_Results"
if [[ ! -f "$misa_stats" ]]; then
log WARN "MISA statistics file not found"
return 1
fi
# Copy MISA statistics to results
local stats_file="${results_dir}/SSR_statistics.txt"
cp "$misa_stats" "$stats_file"
log INFO "SSR statistics generated"
}
create_nonredundant_library() {
log INFO "Creating non-redundant SSR library"
local results_dir="${OUTPUT_DIR}/${PROJECT_NAME}-MegaSSR_Results"
local genic_fa="${results_dir}/Genic_SSR_flanking_regions.fa"
local intergenic_fa="${results_dir}/Intergenic_SSR_flanking_regions.fa"
local combined_fa="${OUTPUT_DIR}/intermediate/${PROJECT_NAME}_combined_SSR_flanking.fa"
local nonred_fa="${results_dir}/Non-redundant_SSR_library.fasta"
local nonred_log="${results_dir}/SSR.non-redundant.log"
# Check if both flanking region files exist
if [[ ! -f "$genic_fa" ]] && [[ ! -f "$intergenic_fa" ]]; then
log WARN "No flanking region files found, skipping non-redundant library"
return 0
fi
# Combine flanking regions (both files may not exist)
> "$combined_fa" # Create empty file first
[[ -f "$genic_fa" ]] && cat "$genic_fa" >> "$combined_fa"
[[ -f "$intergenic_fa" ]] && cat "$intergenic_fa" >> "$combined_fa"
local seq_count=$(grep -c "^>" "$combined_fa" || echo "0")
log INFO "Combined $seq_count flanking sequences"
# Define usearch binary path
# Priority: 1) USEARCH_BIN env var, 2) bundled binary, 3) system usearch
# NOTE: Bundled binary is i86linux32; set USEARCH_BIN for x86_64 systems if needed
local usearch_bin="${USEARCH_BIN:-${BIN_DIR}/usearch11.0.667_i86linux32}"
# Try to use usearch for clustering
local usearch_cmd=""
if [[ -n "${USEARCH_BIN:-}" ]] && [[ -x "$USEARCH_BIN" ]]; then
usearch_cmd="$USEARCH_BIN"
log INFO "Using custom usearch from USEARCH_BIN: $USEARCH_BIN"
elif [[ -x "$usearch_bin" ]]; then
# Test if bundled binary is architecture-compatible
if "$usearch_bin" --version >/dev/null 2>&1; then
usearch_cmd="$usearch_bin"
log INFO "Using bundled usearch for clustering"
else
log WARN "Bundled usearch binary not compatible with this architecture"
fi
fi
# Fallback to system usearch if bundled not available/compatible
if [[ -z "$usearch_cmd" ]] && command -v usearch >/dev/null 2>&1; then
usearch_cmd="usearch"
log INFO "Using system usearch for clustering"
fi
if [[ -n "$usearch_cmd" ]]; then
local temp_dir="${OUTPUT_DIR}/usearch_temp"
mkdir -p "$temp_dir"
# Step 1: Sort by length (as in original pipeline)
local sorted_fa="${temp_dir}/SSR_with_flanking_regions_sorted.fa"
"$usearch_cmd" -sortbylength "$combined_fa" \
-fastaout "$sorted_fa" \
-log "${temp_dir}/usearch_sort.log" 2>&1
# Step 2: Cluster at 90% identity
"$usearch_cmd" -cluster_fast "$sorted_fa" \
-id 0.90 \
-centroids "${temp_dir}/centroids.fa" \
-uc "${temp_dir}/result.uc" \
-consout "$nonred_fa" \
-msaout "${temp_dir}/aligned.fasta" \
-log "${temp_dir}/usearch_cluster.log" 2>&1
if [[ $? -eq 0 ]] && [[ -f "$nonred_fa" ]]; then
# Copy log and clean up sensitive lines
sed '2d;3d;11d' "${temp_dir}/usearch_cluster.log" > "$nonred_log" 2>/dev/null || \