-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathete_build_dsl2.nf
1364 lines (1188 loc) · 43.3 KB
/
ete_build_dsl2.nf
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
#!/usr/bin/env nextflow
import groovy.json.JsonOutput
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
params.input = "$baseDir/data/"
params.output = "$baseDir/result"
params.thread = 4
params.aligner = "none" // "mafft"
params.trimmer = "none" // "trimal"
params.tree_builder = "none" // "fasttree"
params.executor = 'local' // Default to local, change to 'slurm' for SLURM execution
params.queue = 'fast'
params.memory = '4GB'
params.time = '1h'
params.customConfig = null
params.supermatrix_mode = false // Whether to build a supermatrix
params.target_species = null // File path to target species list for supermatrix concatenation
params.coalescent_mode = false // Whether to run ASTRAL for coalescent species tree inference
params.clearall = true
params.spname_delimiter = '_'
params.spname_field = '0'
bin = "$baseDir/bin"
// Default configuration
def defaultConfig = [
aligner: [
mafft: [
name: "mafft",
op: 1.53,
ep: 0.123,
maxiterate: 0
],
muscle: [
name: "muscle"
],
tcoffee: [
name: "t_coffee"
],
clustalo: [
name: "clustalo",
dealign: false,
],
famsa: [
name: "famsa",
]
],
trimmer: [
trimal: [
name: "trimal",
gt: 0.1
],
clipkit: [
name: "clipkit",
mode: "smart-gap",
gaps: 0.9,
codon: false
],
trim_alg_v2: [
name: "trim_alg_v2.py",
min_res_abs: 3,
min_res_percent: 0.1
]
],
tree_builder: [
fasttree: [
name: "fasttree"
],
phyml: [
name: "phyml",
// datatype: 'aa',
aa_model: "LG", // Updated from the cfg
nt_model: "HKY85", // Updated from the cfg
pinv: "e", // Proportion of invariable sites, 'e' for estimation
alpha: "e", // Gamma distribution shape parameter, 'e' for estimation
nclasses: 4, // Number of rate categories
optimisation: "tlr", // Updated from the cfg
frequencies: "m", // Updated from the cfg
bootstrap: -2, // Updated to default Chi2-based parametric branch supports
tbe: false, // Disable TBE
r_seed: 123456, // Random seed
],
raxml: [
name: "raxmlHPC",
algorithm: "d",
r_seed: 31416,
aa_model: "PROTGAMMAJTT",
nt_model: "GTRGAMMA",
bootstrap: 100,
],
iqtree: [
name: "iqtree",
alrt: 1000,
seed: 31416,
model: "TESTONLY",
tbe: false, // Disable TBE
],
// mrbayes:[
// name: "mb",
// ],
mrbayes: [
name: "mb",
ngen: 100000, // Number of generations
nchains: 4, // Number of chains
nruns: 2, // Number of runs
nst: 1, // Substitution model for dna
rates: "equal", // Rates model for dna Equal/Gamma/LNorm/Propinv/Invgamma/Adgamma/Kmixture
aamodelpr: "fixed(wag)", // Amino acid model
diagnfreq: 5000, // Frequency of diagnosing
samplefreq: 500, // Frequency of sampling
printfreq: 1000, // Frequency of printing
burninfrac: 0.25, // Burn-in fraction
append: "no", // Append to last checkpoint
stoprule: "no",
seed: 1726956368, // Seed
swapseed: 1726956368 // Swap seed
],
astral: [
name: "astral",
//-a: "species_map.txt", // Path to the species mapping file, if needed
]
]
]
// Function to perform a deep copy of a map
def deepCopy(map) {
new groovy.json.JsonSlurper().parseText(new groovy.json.JsonBuilder(map).toString())
}
// Function to load and merge custom config
def loadAndMergeConfig(defaultConfig, customConfigFile) {
def config = [:] // Start with an empty map
if (customConfigFile) {
// Load the custom configuration first
def customConfig = new groovy.json.JsonSlurper().parseText(file(customConfigFile).text)
// Only overwrite the aligner, trimmer, and tree_builder if they are not empty
if (customConfig.containsKey('aligner') && !customConfig.aligner.isEmpty()) {
config.aligner = customConfig.aligner
} else {
config.aligner = defaultConfig.aligner
}
if (customConfig.containsKey('trimmer') && !customConfig.trimmer.isEmpty()) {
config.trimmer = customConfig.trimmer
} else {
config.trimmer = defaultConfig.trimmer
}
if (customConfig.containsKey('tree_builder') && !customConfig.tree_builder.isEmpty()) {
config.tree_builder = customConfig.tree_builder
} else {
config.tree_builder = defaultConfig.tree_builder
}
// Handle other potential sections of the config that are not aligner, trimmer, or tree_builder
customConfig.each { key, value ->
if (!['aligner', 'trimmer', 'tree_builder'].contains(key)) {
config[key] = value
}
}
} else {
// If no custom config is provided, just use the default
config = defaultConfig
}
// Then add any other sections from the default config that aren't in the custom config
config = defaultConfig + config
// Return the final merged configuration
return config
}
// Ensure the configuration is loaded before any processes run
def jsonConfig = loadAndMergeConfig(defaultConfig, params.customConfig)
// Handle input files or directory
FASTA_files = file(params.input).isDirectory() ? Channel.fromPath("${params.input}/*.{fa,faa,fasta}") : Channel.fromPath(params.input)
output_dir_structure = { fasta_name -> "${params.output}/${fasta_name}-${params.aligner}-${params.trimmer}-${params.tree_builder}" }
// Function to get MAFFT options
def getMafftOptions(alignConfig) {
def options = ""
// Handle basic parameters
if (alignConfig.ep != null) {
options += " --ep ${alignConfig.ep}"
}
if (alignConfig.op != null) {
options += " --op ${alignConfig.op}"
}
if (alignConfig.maxiterate != null) {
options += " --maxiterate ${alignConfig.maxiterate}"
}
if (alignConfig.retree != null) {
options += " --retree ${alignConfig.retree}"
}
// Add matrix options only if matrix is specified as "BLOSUM" or "PAM"
if (alignConfig.matrix == "BLOSUM") {
options += " --bl ${alignConfig.blosum_coefficient}"
} else if (alignConfig.matrix == "PAM") {
options += " --jtt ${alignConfig.pam_coefficient}"
}
// Handle boolean flags
println "AlignConfig: ${alignConfig.auto}"
if (alignConfig.auto) {
options += " --auto"
}
if (alignConfig.localpair) {
options += " --localpair"
}
if (alignConfig.globalpair) {
options += " --globalpair"
}
if (alignConfig.genafpair) {
options += " --genafpair"
}
if (alignConfig.nofft) {
options += " --nofft"
}
if (alignConfig.parttree) {
options += " --parttree"
}
println "MAFFT Options: ${options}"
return options
}
// Function to get MUSCLE options
def getMuscleOptions(alignConfig) {
def options = ""
if (alignConfig.replicates) {
options += " -replicates ${alignConfig.replicates}"
}
if (alignConfig.perturb) {
options += " -perturb ${alignConfig.perturb}"
}
if (alignConfig.perm) {
options += " -perm ${alignConfig.perm}"
}
if (alignConfig.consiters){
options += " -consiters ${alignConfig.consiters}"
}
if (alignConfig.refineiters) {
options += " -refineiters ${alignConfig.refineiters}"
}
if (alignConfig.stratified) {
options += " -stratified"
}
if (alignConfig.diversified) {
options += " -diversified"
}
println "MUSCLE Options: ${options}"
return options
}
// Function to get T-Coffee options
def getTcoffeeOptions(alignConfig) {
def options = "-n_core=${params.thread}"
return options
}
def getClustaloOptions(alignConfig) {
def options = ""
if (alignConfig.dealign) {
options += " --dealign"
}
if (alignConfig.full) {
options += " --full"
}
if (alignConfig.full_iter) {
options += " --full-iter"
}
if (alignConfig.iterations) {
options += " --iterations ${alignConfig.iterations}"
}
if (alignConfig.max_guidetree_iterations) {
options += " --max-guidetree-iterations ${alignConfig.max_guidetree_iterations}"
}
if (alignConfig.max_hmm_iterations) {
options += " --max-hmm-iterations ${alignConfig.max_hmm_iterations}"
}
println "Clustal Omega Options: ${options}"
return options
}
// Function to get FAMSA options
def getFamsaOptions(alignConfig) {
def options = ""
// Handle guide tree (gt)
if (alignConfig.gt) {
options += " -gt ${alignConfig.gt}"
}
// Handle medoid tree option
if (alignConfig.medoidtree ) {
options += " -medoidtree"
}
// Handle refine mode
if (alignConfig.refine_mode) {
options += " -refine_mode ${alignConfig.refine_mode}"
}
// Handle refinement iterations (r)
if (alignConfig.r != null) {
options += " -r ${alignConfig.r}"
}
// Handle gap penalties
if (alignConfig.go != null) {
options += " -go ${alignConfig.go}"
}
if (alignConfig.ge != null) {
options += " -ge ${alignConfig.ge}"
}
if (alignConfig.tgo != null) {
options += " -tgo ${alignConfig.tgo}"
}
if (alignConfig.tge != null) {
options += " -tge ${alignConfig.tge}"
}
// Handle gap cost scaler terms
if (alignConfig.gsd != null) {
options += " -gsd ${alignConfig.gsd}"
}
if (alignConfig.gsl != null) {
options += " -gsl ${alignConfig.gsl}"
}
// Handle disabling options (dgr, dgo, dsp)
if (alignConfig.dgr != null && alignConfig.dgr) {
options += " -dgr"
}
if (alignConfig.dgo != null && alignConfig.dgo) {
options += " -dgo"
}
if (alignConfig.dsp != null && alignConfig.dsp) {
options += " -dsp"
}
println "Famsa Options: ${options}"
return options
}
// Function to get Trimal options
def getTrimalOptions(trimConfig) {
def options = ""
// Handle gap threshold (gt)
if (trimConfig.gt != null) {
options += "-gt ${trimConfig.gt} "
}
// Handle minimum average similarity threshold (st)
if (trimConfig.st != null) {
options += "-st ${trimConfig.st} "
}
// Handle minimum percentage of positions to conserve (ct)
if (trimConfig.ct != null) {
options += "-ct ${trimConfig.ct} "
}
// Handle gappyout option
if (trimConfig.gappyout == true) {
options += "-gappyout "
}
// Handle sliding window size (w)
if (trimConfig.w != null) {
options += "-w ${trimConfig.w} "
}
// Handle strictplus option (for NJ tree reconstruction)
if (trimConfig.strictplus == true) {
options += "-strictplus "
}
// Handle automated1 option (for ML tree reconstruction)
if (trimConfig.automated1 == true) {
options += "-automated1 "
}
println "Trimal Options: ${options}"
// Return the assembled options string
return options
}
// Function to get Clipkit options
def getClipkitOptions(trimConfig) {
def options = ""
// Ensure mode is specified, otherwise use a default
if (trimConfig.mode) {
options += "--mode ${trimConfig.mode} "
} else {
options += "--mode smart-gap " // Default mode
}
// Handle gaps threshold
if (trimConfig.gaps != null) {
options += "--gaps ${trimConfig.gaps} "
} else {
options += "--gaps 0.9 " // Default gap threshold
}
// Handle codon mode
if (trimConfig.codon) {
options += "--codon "
}
println "Clipkit Options: ${options}"
return options
}
def getTrimAlgV2Options(trimConfig) {
def options = ""
options += trimConfig.min_res_abs ? "--min_res_abs ${trimConfig.min_res_abs} " : ""
options += trimConfig.min_res_percent ? "--min_res_percent ${trimConfig.min_res_percent} " : ""
println "TrimAlgV2 Options: ${options}"
return options
}
// Function to get FastTree options
def getFastTreeOptions(buildConfig) {
def options = ""
// Handle model for amino acids
if (buildConfig.aa_model) {
switch (buildConfig.aa_model) {
case "LG":
options += " -lg"
break
case "WAG":
options += " -wag"
break
case "JTT":
break
// No need to add anything for the default model (JTT+CAT)
}
}
// Handle model for nucleotides
if (buildConfig.nt_model) {
switch (buildConfig.nt_model) {
case "GTR":
options += " -gtr"
break
case "JC":
break
}
}
// Handle gamma distribution
if (buildConfig.gamma) {
options += " -gamma"
}
// Handle pseudo-likelihood support values
if (buildConfig.pseudo) {
options += " -pseudo"
}
// Handle bootstrap or nosupport
if (buildConfig.bootstrap == 0) {
options += " -nosupport"
} else if (buildConfig.bootstrap) {
options += " -boot ${buildConfig.bootstrap ?: 1000}"
}
// Handle SPR rounds (minimum-evolution SPR moves)
if (buildConfig.spr != null) {
options += " -spr ${buildConfig.spr}"
}
// Handle ML model accuracy categories (MLACC)
if (buildConfig.mlacc != null) {
options += " -mlacc ${buildConfig.mlacc}"
}
// Handle slow NNI moves
if (buildConfig.slownni) {
options += " -slownni"
}
println "FastTree Options: ${options}"
return options
}
// Function to get PhyML options
def getPhymlOptions(buildConfig, aln_type) {
def options = ""
// check point for datatype
// Handle amino acid models
if (aln_type == 'aa') {
if (buildConfig.aa_model) {
switch (buildConfig.aa_model) {
case "LG":
options += " -m LG"
break
case "WAG":
options += " -m WAG"
break
case "JTT":
options += " -m JTT"
break
case "MtREV":
options += " -m MtREV"
break
case "Dayhoff":
options += " -m Dayhoff"
break
case "DCMut":
options += " -m DCMut"
break
case "RtREV":
options += " -m RtREV"
break
case "CpREV":
options += " -m CpREV"
break
case "VT":
options += " -m VT"
break
case "AB":
options += " -m AB"
break
case "Blosum62":
options += " -m Blosum62"
break
case "MtMam":
options += " -m MtMam"
break
case "MtArt":
options += " -m MtArt"
break
case "HIVw":
options += " -m HIVw"
break
case "HIVb":
options += " -m HIVb"
break
case "custom":
options += " -m custom"
break
}
}
} else {
// Handle nucleotide models
if (buildConfig.nt_model) {
switch (buildConfig.nt_model) {
case "HKY85":
options += " -m HKY85"
break
case "JC69":
options += " -m JC69"
break
case "K80":
options += " -m K80"
break
case "F81":
options += " -m F81"
break
case "F84":
options += " -m F84"
break
case "TN93":
options += " -m TN93"
break
case "GTR":
options += " -m GTR"
break
case "custom":
options += " -m custom"
break
}
}
}
// Handle proportion of invariable sites (pinv)
if (buildConfig.pinv != null) {
options += buildConfig.pinv == "e" ? " --pinv e" : " --pinv ${buildConfig.pinv}"
}
// Handle gamma distribution shape parameter (alpha)
if (buildConfig.alpha != null) {
options += buildConfig.alpha == "e" ? " --alpha e" : " --alpha ${buildConfig.alpha}"
}
// Handle number of rate categories (nclasses)
if (buildConfig.nclasses) {
options += " --nclasses ${buildConfig.nclasses}"
}
// Handle tree optimisation (optimisation)
if (buildConfig.optimisation) {
options += " -o ${buildConfig.optimisation}"
}
// Handle frequencies (frequencies)
if (buildConfig.frequencies) {
switch (buildConfig.frequencies) {
case "e":
options += " -f e"
break
case "m":
options += " -f m"
break
case "o":
options += " -f o"
break
default:
options += " -f ${buildConfig.frequencies}"
break
}
}
// Handle bootstrap or branch support (-b)
if (buildConfig.bootstrap) {
options += " -b ${buildConfig.bootstrap}"
}
// Handle TBE instead of FBP if tbe is True
if (buildConfig.tbe) {
options += " --tbe"
}
// Handle random seed (-r)
if (buildConfig.r_seed) {
options += " --r_seed ${buildConfig.r_seed}"
}
options += " --quiet"
options += " --no_memory_check"
return options
}
def getRaxmlOptions(buildConfig, aln_type){
def options = ""
if (buildConfig.algorithm) {
options += "-f ${buildConfig.algorithm} "
}
if (aln_type == 'aa'){
if (buildConfig.aa_model) {
options += "-m ${buildConfig.aa_model} "
}
} else {
if (buildConfig.nt_model) {
options += "-m ${buildConfig.nt_model} "
}
}
println "RAxML Options: ${aln_type}, ${buildConfig.nt_model} "
if (buildConfig.r_seed) {
options += "-p ${buildConfig.r_seed} "
}
if (buildConfig.bootstrap) {
options += "-N ${buildConfig.bootstrap} "
}
return options
}
// Function to get IQ-TREE options
def getIqtreeOptions(buildConfig) {
def options = ""
if (buildConfig.alrt) {
options += "-alrt ${buildConfig.alrt} "
}
if (buildConfig.seed) {
options += "-seed ${buildConfig.seed} "
}
if (buildConfig.mode) {
options += "-m ${buildConfig.mode} "
}
if (buildConfig.st) {
options += "-st ${buildConfig.st} "
}
if (buildConfig.ufboot) {
options += "-B ${buildConfig.ufboot} "
}
// println "IQ-TREE Options: ${buildConfig.bootstrap_rep}"
if (buildConfig.tbe) {
options += "--tbe "
}
return options
}
// Function to filter only the used method in aligner
def filterUsedAlignerConfig(alignConfig) {
def usedAlignerConfig = alignConfig.clone()
if (alignConfig.methods) {
usedAlignerConfig.methods = [(alignConfig.mode): alignConfig.methods[alignConfig.mode]]
}
return usedAlignerConfig
}
// Function to filter only the used options in trimmer
def filterUsedTrimmerConfig(trimConfig) {
def usedTrimmerConfig = trimConfig.clone()
return usedTrimmerConfig
}
// Function to filter only the used options in tree builder
def filterUsedTreeBuilderConfig(buildConfig) {
def usedTreeBuilderConfig = buildConfig.clone()
return usedTreeBuilderConfig
}
def detectAlignmentType(alignmentFile) {
println "Checking alignment file: ${alignmentFile}"
// Ensure alignmentFile is treated as a Path object
int retryCount = 5
def lines = []
while (retryCount > 0) {
try {
lines = alignmentFile.readLines() // Try reading the file
println "Successfully read file: ${alignmentFile}"
break
} catch (Exception e) {
println "Error reading file: ${e.message}, retrying..."
retryCount--
sleep(2000) // Wait for 2 seconds before retrying
}
}
if (lines.isEmpty()) {
throw new Exception("Failed to read file after multiple retries: ${alignmentFile}")
}
// Concatenate all sequence lines (ignoring lines that look like headers or gaps)
def sequenceData = lines.findAll { line -> !line.startsWith(">") && line.trim() != "" }
.join("")
.replace("-", "") // Ignore gaps ("-")
// Regular expressions for nucleotides and amino acids (case-insensitive with (?i))
def nt_regex = /(?i)^[ACGTURYKMSWBDHVN]+$/ // IUPAC codes for nucleotides
def aa_regex = /(?i)^[ACDEFGHIKLMNPQRSTVWYBXZ]+$/ // IUPAC codes for amino acids
// Check if the sequence data matches nucleotide or amino acid patterns
if (sequenceData ==~ nt_regex) {
return "nt"
} else {
return "aa"
}
}
// def detectAlignmentType(alignmentFile) {
// println "check this ${alignmentFile}"
// // Read the alignment file as text
// def lines = file(alignmentFile).readLines()
// println "good file! ${alignmentFile}"
// // Concatenate all sequence lines (ignoring lines that look like headers or gaps)
// def sequenceData = lines.findAll { line -> !line.startsWith(">") && line.trim() != "" }
// .join("")
// .replace("-", "") // Ignore gaps ("-")
// // Regular expressions for nucleotides and amino acids (case-insensitive with (?i))
// def nt_regex = /(?i)^[ACGTURYKMSWBDHVN]+$/ // IUPAC codes for nucleotides
// def aa_regex = /(?i)^[ACDEFGHIKLMNPQRSTVWYBXZ]+$/ // IUPAC codes for amino acids
// // Check if the sequence data matches nucleotide or amino acid patterns
// if (sequenceData ==~ nt_regex) {
// return "nt"
// } else {
// return "aa"
// }
// }
process parseFasta {
cpus 1
memory '1GB'
time '10m'
errorStrategy 'ignore'
maxRetries 3
publishDir path: { "${params.output}/${fasta_name}-${params.aligner}-${params.trimmer}-${params.tree_builder}" }, mode: 'copy', overwrite: true
input:
path fasta_file
output:
stdout emit: info
script:
fasta_name = fasta_file.baseName
"""
echo $fasta_file
awk '/^>/{if (seq) {print seq; seq=""} print \$0} {seq=seq\$0} END {print seq}' $fasta_file | \
awk 'NR%2==0' | \
awk '{if (length(\$0) > max) max = length(\$0); sum+=length(\$0)} END {print "Longest sequence: " max " characters"; print "Total sequences: " NR; print "Average sequence length: " sum/NR}'
grep '^>' $fasta_file | sort | uniq -d > duplicates.txt
if [[ -s duplicates.txt ]]; then
echo "Duplicated names found:"
cat duplicates.txt
else
echo "No duplicated names found."
fi
rm duplicates.txt
"""
}
process align {
cpus params.thread
memory params.memory
time params.time
errorStrategy 'ignore'
maxRetries 2
executor params.executor
//publishDir path: { "${params.output}/${fasta_name}-${params.aligner}-${params.trimmer}-${params.tree_builder}" }, mode: 'copy', overwrite: true
publishDir path: {
def dir = "${params.output}/${fasta_name}-${params.aligner}-${params.trimmer}-${params.tree_builder}"
// If params.clearall is true and the workflow is not resumed, check if the directory exists and delete files
if (params.clearall && !workflow.resume) {
def dirPath = new File(dir)
if (dirPath.exists()) {
println "Clearing previous output files in: ${dir}"
dirPath.eachFile { file ->
if (!file.delete()) {
println "Failed to delete: ${file.path}"
}
}
} else {
println "Directory does not exist, nothing to clear."
}
}
return dir
}, mode: 'copy'
input:
path fasta_file
output:
path "${fasta_name}.aln.faa", emit: aln_seqs
path "*.*", emit: aln_files
stdout emit: align_stdout
path "align.err", emit: align_err
path "${fasta_name}_aln_timing.log"
script:
fasta_name = fasta_file.baseName
if (params.aligner == "none") {
// If no aligner is specified, just copy the input file to the output
"""
cp $fasta_file ${fasta_name}.aln.faa
"""
} else {
def alignConfig = jsonConfig.aligner[params.aligner]
if (!alignConfig) {
throw new Exception("Aligner configuration for '${params.aligner}' is not found.")
}
def alignCmd = "mafft"
def alignOptions = ""
switch(params.aligner) {
case "mafft":
alignOptions = getMafftOptions(alignConfig)
break
case "muscle":
alignCmd = "muscle"
alignOptions = getMuscleOptions(alignConfig)
break
case "tcoffee":
alignCmd = "t_coffee"
alignOptions = getTcoffeeOptions(alignConfig)
break
case "clustalo":
alignCmd = "clustalo"
alignOptions = getClustaloOptions(alignConfig)
break
case "famsa":
alignCmd = "famsa"
alignOptions = getFamsaOptions(alignConfig)
break
default:
throw new Exception("Invalid aligner: ${params.aligner}")
}
// Additional debug print for alignOptions
// println "Align Options: ${alignOptions}"
//num_sequences=\$(grep -c '^>' $fasta_file)
"""
start_time=\$(date +%s)
echo "run ${alignCmd} with options: $alignOptions"
if [ "${params.aligner}" == "mafft" ]; then
${alignCmd} ${alignOptions} --anysymbol --thread ${params.thread} $fasta_file > ${fasta_name}.aln.faa 2> align.err
elif [ "${params.aligner}" == "muscle" ]; then
${alignCmd} -align $fasta_file -output ${fasta_name}.aln.faa ${alignOptions} 2> align.err
elif [ "${params.aligner}" == "tcoffee" ]; then
${alignCmd} ${alignOptions} -in $fasta_file -output=fasta_aln -outfile=${fasta_name}.aln.faa 2> align.err
elif [ "${params.aligner}" == "clustalo" ]; then
${alignCmd} ${alignOptions} --threads ${params.thread} -i $fasta_file -o ${fasta_name}.aln.faa 2> align.err
elif [ "${params.aligner}" == "famsa" ]; then
${alignCmd} ${alignOptions} -t ${params.thread} $fasta_file ${fasta_name}.aln.faa 2> align.err
fi
end_time=\$(date +%s)
echo "Alignment $fasta_file took \$((end_time - start_time)) seconds." >> ${fasta_name}_aln_timing.log
"""
}
}
process trim {
cpus params.thread
memory params.memory
time params.time
errorStrategy 'ignore'
maxRetries 2
publishDir path: { "${params.output}/${fasta_name}-${params.aligner}-${params.trimmer}-${params.tree_builder}" }, mode: 'copy', overwrite: true
executor params.executor
input:
path aln_file
output:
path "${fasta_name}.clean.alg.faa", emit: clean_aln_seqs
path "*.*", emit: trim_files, optional: true
stdout emit: trim_stdout
path "trim.out", optional: true
path "trim.err", optional: true
script:
fasta_name = aln_file.baseName.replace(".aln", "")
if (params.trimmer == "none") {
// If no trimmer is specified, just copy the input file to the output
println "No trimmer specified, copying the input file to the output."
"""
cp $aln_file ${fasta_name}.clean.alg.faa
"""
} else {
def trimConfig = jsonConfig.trimmer[params.trimmer]
def trimCmd = ""
def trimOptions = ""
switch(params.trimmer) {
case "trimal":
trimCmd = "trimal"
trimOptions = getTrimalOptions(trimConfig)
break
case "clipkit":
trimCmd = "clipkit"
trimOptions = getClipkitOptions(trimConfig)
break
case "trim_alg_v2":
trimCmd = "trim_alg_v2.py"
trimOptions = getTrimAlgV2Options(trimConfig)
break
default:
throw new Exception("Invalid trimmer: ${params.trimmer}")
}
"""
start_time=\$(date +%s)
if [ "${params.trimmer}" == "trimal" ]; then
echo "Running trimal!"
${trimCmd} ${trimOptions} -in $aln_file -out ${fasta_name}.clean.alg.faa -fasta 1> trim.out 2> trim.err
elif [ "${params.trimmer}" == "clipkit" ]; then
echo "Running clipkit!"
${trimCmd} ${trimOptions} $aln_file -o ${fasta_name}.clean.alg.faa 1> trim.out 2> trim.err
elif [ "${params.trimmer}" == "trim_alg_v2" ]; then
echo "Running trim_alg_v2!"
python ${bin}/${trimCmd} ${trimOptions} -i $aln_file -o ${fasta_name}.clean.alg.faa 1> trim.out 2> trim.err
fi
end_time=\$(date +%s)
echo "Trimming $fasta_name took \$((end_time - start_time)) seconds."
"""
}
}
process concatSupermatrix {
cpus params.thread
memory params.memory
time params.time
errorStrategy 'retry'
maxRetries 2