-
Notifications
You must be signed in to change notification settings - Fork 10
/
MATAFILER.pl
executable file
·4559 lines (4104 loc) · 190 KB
/
MATAFILER.pl
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 perl
#The Metagenomic Assembly, Genomic Recovery and Assembly Independent Mapping Tool
#main MATAFILER routine
#ex
#./MATAFILER.pl map2tar /g/scb/bork/hildebra/SNP/test/refCtg.fasta,/g/scb/bork/hildebra/SNP/test/refCtg.fasta test1,test2
#./MATAFILER.pl map2tar /g/bork3/home/hildebra/results/TEC2/v5/TEC2.MM4.BEE.GF.rn.fa TEC2
#./MATAFILER.pl map2tar /g/bork3/home/hildebra/results/prelimGenomes/TEC3/MM3.TEC3.scaffs.fna,/g/bork3/home/hildebra/results/prelimGenomes/TEC3/TEC3ref.fasta,/g/bork3/home/hildebra/results/prelimGenomes/TEC4/MM3.TEC4.scaffs.fna,/g/bork3/home/hildebra/results/prelimGenomes/TEC4/TEC4ref.fasta,/g/bork3/home/hildebra/results/prelimGenomes/TEC5/MM4.TEC5.scaffs.fna,/g/bork3/home/hildebra/results/prelimGenomes/TEC5/TEC5ref.fasta,/g/bork3/home/hildebra/results/prelimGenomes/TEC6/MM29.TEC6.scaffs.fna,/g/bork3/home/hildebra/results/prelimGenomes/TEC6/TEC6ref.fasta TEC3,TEC3r,TEC4,TEC4r,TEC5,TEC5r,TEC6,TEC6r
#/g/bork5/hildebra/results/TEC2/v5/T6/TEC6.ctgs.rn.fna
#./MATAFILER.pl map2DB /g/bork3/home/hildebra/DB/freeze11/freeze11.genes.representatives.fa frz11; ./MATAFILER.pl map2DB /g/bork3/home/hildebra/DB/GeneCats/Tara/Tara.fna Tara; ./TAMOC.pl map2DB /g/bork3/home/hildebra/DB/GeneCats/IGC/1000RefGeneCat.fna IGC
#./MATAFILER.pl map2tar /g/bork3/home/hildebra/results/TEC2/v5/TEC2.MM4.BEE.GF.rn.fa,/g/bork3/home/hildebra/results/TEC2/v5/T6/TEC6.ctgs.rn.fna T2d,T6d
# GGC279
use warnings;
use strict;
use File::Basename;
use Cwd 'abs_path';
use POSIX;
use Getopt::Long qw( GetOptions );
use Mods::GenoMetaAss qw(readMap qsubSystem emptyQsubOpt findQsubSys readFastHD prefix_find gzipopen readFasta writeFasta);
use Mods::IO_Tamoc_progs qw(getProgPaths setConfigFile jgi_depth_cmd inputFmtSpades inputFmtMegahit createGapFillopt buildMapperIdx);
use vars qw($CONFIG_FILE);
use Mods::TamocFunc qw (getSpecificDBpaths getFileStr);
use Mods::phyloTools qw(fixHDs4Phylo);
sub help; sub annoucnce_MATAFILER;
sub seedUnzip2tmp; sub clean_tmp; sub cleanInput; #unzipping reads; removing these at later stages ; remove tmp dirs
sub readG2M; sub check_matesL;
sub mapReadsToRef; sub bamDepth;
sub ReadsFromMapping;
sub spadesAssembly; #main Assembler
sub megahitAssembly; #secondary Assembler
sub createPsAssLongReads; #pseudo assembler
sub scaffoldCtgs; #scaffold assemblies / external contigs
sub GapFillCtgs; #post scaffolding using reads from samples
sub filterSizeFasta;
sub sdmClean; sub check_sdm_loc; #qual filter reads
sub mergeReads; #merge reads via flash
sub SEEECER;
sub run_prodigal_augustus; sub run_prodigal; #gene prediction
#sub randStr;
sub contigStats;sub smplStats;
sub adaptSDMopt;#sub readMap; sub qsubSystem;
sub checkDrives;sub bam2cram;
sub mocat_reorder; sub postSubmQsub;
sub detectRibo;
sub runOrthoPlacement;
sub runDiamond; sub DiaPostProcess; sub IsDiaRunFinished;
sub nopareil; sub calcCoverage;
sub prepKraken;sub krakHSap; sub krakenTaxEst;
sub d2metaDist;
sub metphlanMapping; sub mergeMP2Table;
sub mOTU2Mapping; sub mergeMotu2Table; sub prepMOTU2;
sub genoSize;
#bjobs | awk '$3=="CDDB" {print $1}' |xargs bkill
#bjobs | grep 'dWXmOT' | cut -f11 -d' ' | xargs -t -i bkill {}
#squ | grep _UZ | cut -f11 -d' ' | xargs -t -i scancel {}
#bhosts | cut -f1 -d' ' | grep -v HOST_NAME | xargs -t -i ssh {} 'killall -u hildebra'
#hosts=`bhosts | grep ok | cut -d" " -f 1 | grep compute | tr "\\n" ","`; pdsh -w $hosts "rm -rf /tmp/hildebra"
my $MATFILER_ver = 0.16;
#----------------- defaults -----------------
my $rawFileSrchStr1 = '.*1\.f[^\.]*q\.gz$';
my $rawFileSrchStr2 = '.*2\.f[^\.]*q\.gz$';
my $rawFileSrchStrSingl = "";
my $rawFileSrchStrXtra1= '.*1_sequence\.f[^\.]*q\.gz$';
my $rawFileSrchStrXtra2= '.*2_sequence\.f[^\.]*q\.gz$';
my $submSytem = "";
my %sdm_opt; #empty object that can be used to modify default sdm parameters
my $tmpSdmminSL=0; my $tmpSdmmaxSL=0;
my $mateInsertLength =20000; #controls expected mate insert size , import for bowtie2 mappings
my %jmp=();
my $logDir = "";
my $sharedTmpDirP = ""; #e.g. /scratch/MATAFILER/
#$sharedTmpDirP = "/g/scb/bork/hildebra/tmp/" if (`hostname` !~ m/submaster/);
my $nodeTmpDirBase = "";#/tmp/MATAFILER/
my $nodeHDDspace = 30720;
my $baseDir = ""; my $baseOut = "";
my $mapFile = ""; my $baseID = "";
my $configFile = "";
#databases empty structs --------------------------
my $globalKraTaxkDB = "";
my %globalRiboDependence =(DBcp => "");
my %globalDiamondDependence = (CZy=>"",MOH=>"",NOG=>"",ABR=>"",ABRc=>"",KGB=>"",KGE=>"",ACL=>"",KGM=>"", PTV=>"", PAB => "");
#more specific control: unfiniRew=rewrite unfinished sample dir; $redoCS = redo ContigStats completely;
#removeInputAgain=remove unzipped files from scratch, after sdm; remove_reads_tmpDir = leave cleaned reads on scratch after everything finishes
my $unfiniRew=0; my $redoCS=0; my $removeInputAgain=1; my $remove_reads_tmpDir=0;
my $silent = 0;
my $redoFails = 0;
my $readsRpairs=-1; #are reads given in pairs? default: -1 = no clue
my $useTrimomatic=1;
my $prefSinglFQgreps = 0; #if grep of files (rawSrchString) has multi assignments, which grep to trust more?
my $unzipCores = 3;
my $splitFastaInput = 0; #assembly as input..
my $importMocat = 0; my $mocatFiltPath = "reads.screened.screened.adapter.on.hg19.solexaqa/";
my $gzipSDMOut = 1;#zip sdm filtered files
my $sdmProbabilisticFilter=1;
my $alwaysDoStats = 1;
my $rmScratchTmp=0;#Default; extremely important option as this adds a lot of overhead and scratch usage space, but reduces later overhead a lot and makes IO more stable
my $humanFilter = 1; #use kraken to filter out human reads
my $unpackZip = 0; #only goes through with read filtering, needed to get files for luis
my $filterFromSource=0;
my $DoMetaPhlan = 0; my $metaPhl2FailCnts=0; #non-asembly based tax + functional assignments
my $DoMOTU2 = 0;my $mOTU2FailCnts=0;
my $DoRibofind = 0; my $doRiboAssembl = 0; my $RedoRiboFind = 0; my $riboFindFailCnts=0; #ITS/SSU/LSU detection
my $riboLCAmaxRds = 50000; #set to 50k by default, larger gets slower too fast
my $riboStoreRds = 0; #store original sequence for later work on them?
my $RedoRiboAssign = 0; my $checkRiboNonEmpty=0;
my $RedoRiboThatFailed= 0;#this option is used for debugging: redo ribo completely, if something failed in run
my $DoBinning = 0;
my $doReadMerge = 0;
my $DoAssembly = 1; my $SpadesAlwaysHDDnode = 1;my $spadesBayHam = 0; my $useSDM = 2;my $spadesMisMatCor = 0; my $redoAssembly =0 ;
my $map2Assembly = 0; my $SaveUnalignedReads=0;
my $bwtIdxAssMem = 40; #total mem in GB, not core adjusted, for building index from assembly
my $doBam2Cram= 1; my $redoAssMapping=0;
my $DoJGIcoverage = 0; #only required for metabat binning, not required any longer..
my $DoNP=0; #non-pareil
my $doDateFileCheck = 0; #very specific option for Moh's reads that were of different dates..
my $DoDiamond = 0; my $rewriteDiamond =0; my $redoDiamondParse = 0; #redoes matching of reads; redoes interpretation
my $MapperProg = 1;#1=bowtie2, 2=bwa
my $DO_EUK_GENE_PRED = 0;
my $DoCalcD2s = 0;
my $calcOrthoPlacement=0; #Jaime's 6 frame translation and hmmersearch (AB production)
my $DoKraken = 0; my $RedoKraken = 0; my $KrakTaxFailCnts=0;
my $pseudoAssembly = 0; #in case no assembly is possible (soil single reads), just filter for reads X long
my $DoFreeGlbTmp = 0; my $defaultReadLength = 100;
my $maxReqDiaDB = 6; #max number of databases supported by METAFILER
my $reqDiaDB = "";#,NOG,MOH,ABR,ABRc,ACL,KGM,PTV,PAB";#,ACL,KGM,ABRc,CZy";#"NOG,CZy"; #"NOG,MOH,CZy,ABR,ABRc,ACL,KGM" #old KGE,KGB
#program configuration
my $Assembly_Cores=48; my $Assembly_Memory = 200; #in GB
my $Spades_HDspace = 100; #required space in GB
my $Assembly_Kmers = "27,33,55,71";
my $bwt_Cores = 12; my $map_DoConsensus = 1; my $doRmDup = 1; #mapping cores; ??? ; remove Dups (can be costly if many ref seqs present)
my $diaEVal = "1e-7"; my $dia_Cores = 16; my $krakenCores = 9;
my $DiaMinAlignLen = 20; my $DiaMinFracQueryCov = 0.1; my $DiaPercID =40;
my $MappingMem = "3G";
my $oldStylFolders=0; #0=smpl name as out folder; 1=inputdir as out foler (legacy)
my $DoGenoSize=0;
#----------- map all reads to a specific reference - options ---------
my $map2ndDeps= "";my $mapModeActive=0; my $mapModeCovDo=1;#get the coverage per gene etc
my $mapModeTogether = 1; my %map2ndTogRefDB;
my $mapModeDecoyDo=1;my %make2ndMapDecoy;my $rewrite2ndMap = 0;
my @bwt2outD =(); my @DBbtRefX = (); my @DBbtRefGFF=(); #my $bwt2Name="";
my $refDBall; my $bwt2NameAll ;
#control broad flow
my $from=0; my $to=100000;
my $doSubmit=1;
my $rewrite=0;
GetOptions(
"help|?" => \&help,
"map=s" => \$mapFile,
"config=s" => \$configFile,
#flow related
"rm_tmpdir_reads=i" => \$remove_reads_tmpDir,
"rm_tmpInput=i" => \$removeInputAgain,
"globalTmpDir=s" => \$sharedTmpDirP,#absolute path to global shared tmp dir (like a scratch dir)
"nodeTmpDir=s" => \$nodeTmpDirBase,#absolute path to tmp dir on local HDD of each executing node
"nodeHDDspace=s" => \$nodeHDDspace,#HDD tmp space to be requested for each node. Some systems don't support this
"legacyFolders=i" => \$oldStylFolders, #legacy option, controls if output folders will use the read dir as name (1) or the name in the mapping file (0). Default=0
"submSystem=s" => \$submSytem, #qsub,SGE,bsub,LSF
"submit=i" => \$doSubmit,
"from=i" => \$from,
"to=i" => \$to,
"useTrimomatic=i" => \$useTrimomatic, #rm adapter seq from input reads
#"rmRawRds=i" => \$DoFreeGlbTmp, #rm raw sequences, once all jobs have finished <-- redundant with reduceScratchUse
"silent" => \$silent,
"reduceScratchUse=i" => \$rmScratchTmp,
"redoFails=i" =>\$redoFails, #if any step of requested analysis failed, just redo everything (extraction etc)
#input FQ related
"inputFQregex1=s" => \$rawFileSrchStr1,
"inputFQregex2=s" => \$rawFileSrchStr2,
"inputFQregexSingle=s" => \$rawFileSrchStrSingl,
"inputFQregexTrustSingle=i" => \$prefSinglFQgreps , #if grep of files (rawSrchString) has multi assignments, which grep to trust more?
"splitFastaInput=i" => \$splitFastaInput,
"mergeReads=i" => \$doReadMerge,
"ProbRdFilter=i" => \$sdmProbabilisticFilter,
"pairedReadInput=i" => \$readsRpairs, #determines if read pairs are expected in each in dir
"inputReadLength=i" => \$defaultReadLength,
"filterHumanRds=i" => \$humanFilter,
"onlyFilterZip=i" => \$unpackZip,
"mocatFiltered=i" => \$importMocat,
#sdm related
"minReadLength=i" => \$tmpSdmminSL,
"maxReadLength=i" => \$tmpSdmmaxSL,
#assembly related
"spadesCores=i" => \$Assembly_Cores,
"spadesMemory=i" => \$Assembly_Memory, #in GB
"spadesKmers=s" => \$Assembly_Kmers, #comma delimited list
"binSpeciesMG=i" => \$DoBinning,
"reAssembleMG=i" => \$redoAssembly,
"assembleMG=i" => \$DoAssembly, #1=Spades, 2=MegaHIT
#mapping related (asselmbly)
"remap2assembly=i" => \$redoAssMapping,
"JGIdepths=i" => \$DoJGIcoverage,
"mapReadsOntoAssembly=i" => \$map2Assembly , #map original reads back on assembly, to estimate abundance etc
"saveReadsNotMap2Assembly=i" => \$SaveUnalignedReads,
#gene prediction on assembly
"predictEukGenes=i" => \$DO_EUK_GENE_PRED,#severely limits total predicted gene amount (~25% of total genes)
#mapping
"mappingCoverage=i" => \$mapModeCovDo,
"mappingMem=i" => \$MappingMem, #mem for bwa/bwt2 in GB
"rmDuplicates=i" => \$doRmDup,
"mappingCores=i" => \$bwt_Cores,
#map2tar / map2DB
"decoyMapping=i" => \$mapModeDecoyDo,
"competitive2ndmap" => \$mapModeTogether,
"ref=s" => \$refDBall,
"mapnms=s" => \$bwt2NameAll, #name for this final files
"reado2ndmap=i" => \$rewrite2ndMap,
#functional profiling (diamond)
"profileFunct=i"=> \$DoDiamond,
"reParseFunct=i" => \$redoDiamondParse,
"reProfileFunct=i" => \$rewriteDiamond,
"diamondCores=i" => \$dia_Cores,
"DiaParseEvals=s" => \$diaEVal, #evalues at which to accept hits to func database
"DiaMinAlignLen=i" => \$DiaMinAlignLen,
"DiaMinFracQueryCov=f" => \$DiaMinFracQueryCov,
"DiaPercID=i" => \$DiaPercID,
"diamondDBs=s" => \$reqDiaDB,#NOG,MOH,ABR,ABRc,ACL,KGM,CZy,PTV,PAB
#functional profiling (Jaime tree)
"orthoExtract=i" => \$calcOrthoPlacement,
#ribo profiling (miTag)
"profileRibosome=i" => \$DoRibofind,
"riobsomalAssembly=i" => \$doRiboAssembl,
"reProfileRibosome=i" => \$RedoRiboFind ,
"reRibosomeLCA=i"=> \$RedoRiboAssign,
"riboMaxRds=i" => \$riboLCAmaxRds,
"saveRiboRds=i" => \$riboStoreRds,
"thoroughCheckRiboFinish=i" => \$checkRiboNonEmpty,
#other tax profilers..
"profileMetaphlan2=i"=> \$DoMetaPhlan,
"profileMOTU2=i" => \$DoMOTU2,
"profileKraken=i"=> \$DoKraken,
"estGenoSize=i" => \$DoGenoSize, #estimate average size of genomes in data
"krakenDB=s"=> \$globalKraTaxkDB, #"virusDB";#= "minikraken_2015/";
#D2s distance
"calcInterMGdistance=i" => \$DoCalcD2s,
);
setConfigFile($configFile);
# die "$DoAssembly\n";
# ------------------------------------------ options post processing ------------------------------------------
die "No mapping file provided (-map)\b" if ($mapFile eq "");
$map2Assembly=0 if (!$DoAssembly);
$MappingMem .= "G"unless($MappingMem =~ m/G$/);
if ($DoDiamond && $reqDiaDB eq ""){die "Functional profiling was requested (-profileFunct 1), but no DB to map against was defined (-diamondDBs)\n";}
$Assembly_Kmers = "-k $Assembly_Kmers" unless ($Assembly_Kmers =~ m/^-k/);
$sdm_opt{minSeqLength}=$tmpSdmminSL if ($tmpSdmminSL > 0);
$sdm_opt{maxSeqLength}=$tmpSdmmaxSL if ($tmpSdmmaxSL > 0);
$remove_reads_tmpDir = 1 if ($DoFreeGlbTmp || $rmScratchTmp);
$filterFromSource=1 if ($unpackZip );
#$nodeHDDspace .= "G" unless($nodeHDDspace =~ m/G$/);
#dirs from config file--------------------------
$sharedTmpDirP = getProgPaths("globalTmpDir",0) unless ($sharedTmpDirP ne "");
$nodeTmpDirBase = getProgPaths("nodeTmpDir",0) unless ($nodeTmpDirBase ne "");
#programs --------------------------
my $smtBin = getProgPaths("samtools");#"/g/bork5/hildebra/bin/samtools-1.2/samtools";
my $metPhl2Bin = getProgPaths("metPhl2");#"/g/bork3/home/hildebra/bin/metaphlan2/metaphlan2.py";
my $metPhl2Merge = getProgPaths("metPhl2Merge");#"/g/bork3/home/hildebra/bin/metaphlan2/utils/merge_metaphlan_tables.py";
#my $spadesBin = "/g/bork5/hildebra/bin/SPAdes-3.7.0-dev-Linux/bin/spades.py";
my $spadesBin = getProgPaths("spades");#"/g/bork3/home/hildebra/bin/SPAdes-3.7.1-Linux/bin/spades.py";
my $megahitBin = getProgPaths("megahit");
#my $usBin = getProgPaths("usearch");#"/g/bork5/hildebra/bin/usearch/usearch8.0.1421M_i86linux32_fh";
my $bwt2Bin = getProgPaths("bwt2");#"/g/bork5/hildebra/bin/bowtie2-2.2.9/bowtie2";
my $bwaBin = getProgPaths("bwa");#"/g/bork3/home/hildebra/bin/bwa-0.7.12/bwa";
my $d2metaBin = getProgPaths("d2meta");#"/g/bork3/home/hildebra/bin/d2Meta/d2Meta/d2Meta.out";
my $prodigalBin = getProgPaths("prodigal");#"/g/bork5/hildebra/bin/Prodigal-2.6.1/prodigal";
my $augustusBin = getProgPaths("augustus");#"/g/bork3/home/hildebra/bin/augustus-3.2.1/bin/augustus";
my $sambambaBin = getProgPaths("sambamba");#"/g/bork3/home/hildebra/bin/sambamba/sambamba_v0.5.9";
my $npBin = getProgPaths("nonpareil");#"/g/bork5/hildebra/bin/nonpareil/nonpareil";
my $krkBin = getProgPaths("kraken");#"/g/scb/bork/hildebra/DB/kraken/./kraken";
my $diaBin = getProgPaths("diamond");#"/g/bork5/hildebra/bin/diamond/./diamond";
my $nxtrimBin = getProgPaths("nxtrim");#"/g/bork3/home/hildebra/bin/NxTrim/./nxtrim";
my $besstBin = getProgPaths("BESST");#"/g/bork3/home/hildebra/bin/BESST/./runBESST";
#my $novosrtBin = getProgPaths("novosrt");#"/g/bork5/hildebra/bin/novocraft/novosort";
my $GFbin = getProgPaths("gapfiller");#"perl /g/bork5/hildebra/bin/GapFiller/GapFiller_n.pl";
my $flashBin = getProgPaths("flash");
my $pigzBin = getProgPaths("pigz");
my $sdmBin = getProgPaths("sdm");#"/g/bork3/home/hildebra/dev/C++/sdm/./sdm";
my $rareBin = getProgPaths("rare");#"/g/bork3/home/hildebra/dev/C++/rare/rare";
my $readCov_Bin =getProgPaths("readCov");
my $jgiDepthBin = getProgPaths("jgiDepth");#"/g/bork3/home/hildebra/bin/metabat/./jgi_summarize_bam_contig_depths";
my $bedCovBin = getProgPaths("bedCov");#"/g/bork5/hildebra/bin/bedtools2-2.21.0/bin/genomeCoverageBed";
my $srtMRNA_path = getProgPaths("srtMRNA_path");
my $lambdaIdxBin = getProgPaths("lambdaIdx");
my $trimJar = getProgPaths("trimomatic");
my $fna2faaBin = getProgPaths("fna2faa");
#databases --------------------------
my $himipeSeqAd = getProgPaths("illuminaTS3pe"); #for trimomatic
my $himiseSeqAd = getProgPaths("illuminaTS3se");
#local MATAFILER scripts --------------------------
my $cLSUSSUscript = getProgPaths("cLSUSSU_scr");#"perl /g/bork3/home/hildebra/dev/Perl/16Stools/catchLSUSSU.pl";
my $lotusLCA_cLSU = getProgPaths("lotusLCA_cLSU_scr");#"perl /g/bork3/home/hildebra/dev/Perl/16Stools/lotus_LCA_blast2.pl";
my $krakCnts1 = getProgPaths("krakCnts_scr");#"perl /g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/secScripts/krak_count_tax.pl";
my $genelengthScript = getProgPaths("genelength_scr");#= "/g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/secScripts/geneLengthFasta.pl";
my $secCogBin = getProgPaths("secCogBin_scr");#"perl /g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/secScripts/parseBlastFunct.pl";
my $KrisABR = getProgPaths("KrisABR_scr");#"perl /g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/secScripts/ABRblastFilter.pl";
my $sepCtsScript = getProgPaths("sepCts_scr");#"perl /g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/secScripts/separateContigs.pl";
my $assStatScr = getProgPaths("assStat_scr");#"perl /g/bork3/home/hildebra/dev/Perl/assemblies/assemblathon_stats.pl";
my $renameCtgScr = getProgPaths("renameCtg_scr");#"perl /g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/secScripts/renameCtgs.pl";
my $sizFiltScr = getProgPaths("sizFilt_scr");#"perl /g/bork3/home/hildebra/dev/Perl/assemblies/sizeFilterFas.pl";
my $sizSplitScr = getProgPaths("sizSplit_scr");#"perl /g/bork3/home/hildebra/dev/Perl/assemblies/splitFNAbyLength.pl";
my $splitKgdContig = getProgPaths("contigKgdSplit_scr");
my $decoyDBscr = getProgPaths("decoyDB_scr"); #
my $bamHdFilt_scr = getProgPaths("bamHdFilt_scr");
#merge of output tables scripts --------------------------
my $mergeTblScript = getProgPaths("metPhl2Merge");#"/g/bork3/home/hildebra/bin/metaphlan2/utils/merge_metaphlan_tables.py";
#say hello to user
annoucnce_MATAFILER();
#die $mapFile;
#die $baseOut;
#queing capability
my $JNUM=0;
#my $LocationCheckStrg=""; #command that is put in front of every qsub, to check if drives are connected, sub checkDrives
$submSytem = findQsubSys($submSytem);
my $QSBoptHR = emptyQsubOpt($doSubmit,"",$submSytem);
my %QSBopt = %{$QSBoptHR};
$QSBopt{tmpSpace} = $nodeHDDspace;
my @Spades_Hosts = (); my @General_Hosts = ();
#figure out if only certain node subset has enough HDD space
if (0 && $Spades_HDspace > 100){
my $locHosts = `bhosts | grep ok | cut -d" " -f 1 | grep compute | tr "\\n" ","`;
my $tmpStr = `pdsh -w $locHosts -u 4 "df -l" `;
my $srchTerm = '/$';
if (`hostname` =~ m/submaster$/){
$srchTerm = '/tmp';
}
#print "psdh done\n";
#die $tmpStr;
#54325072 = 52G
foreach my $l (split(/\n/,$tmpStr)){
next if ($l !~ m/compute\S+:/);
next unless ($l =~ m/$srchTerm/);
#print $l."\n";
my @hosts = split(/:/,$l);
my @spl = split(/\s+/,$hosts[1]);
#die $spl[1]." XX ".$spl[2]." XX ".$spl[3]." XX ".$spl[4]." \n ";
#print $spl[4] / 1024 / 1024 . "\n";
if (($spl[4] / 1024 / 1024) > $Spades_HDspace){
push(@Spades_Hosts,$hosts[0]);
}
if (($spl[4] / 1024 / 1024) > 40){
push(@General_Hosts,$hosts[0]);
}
}
print "Found ".scalar @Spades_Hosts." host machines with > $Spades_HDspace G space\n";
print "Found ".scalar @General_Hosts." host machines with > 40 G space\n";
if (scalar @Spades_Hosts ==0 ){die "Not enough hosts for spades temp space found\n";}
sleep (2);
}
#----------- here are scaffolding external contigs parameters
my $scaffTarExternal = "";my $scaffTarExternalName = ""; my @scaffTarExternalOLib1; my @scaffTarExternalOLib2;
my $scaffTarExtLibTar = ""; my $bwt2ndMapDep = ""; my @bwt2ndMapNmds;
#here the map and some base parameters (base ID, in path, out path) can be (re)set
my %map; my %AsGrps;
my ($hr,$hr2) = readMap($mapFile,0,\%map,\%AsGrps,$oldStylFolders);
%AsGrps = %{$hr2};
%map = %{$hr};
#$baseDir = $map{inDir} if (exists($map{inDir} ));
$baseOut = $map{outDir} if (exists($map{outDir} ));
$baseID = $map{baseID} if (exists($map{baseID} ));
die "provide an outdir in the mapping file\n" if ($baseOut eq "");
die "provide a baseID in the mapping file\n" if ($baseID eq "");
my $runTmpDirGlobal = "$sharedTmpDirP/$baseID/";
my $runTmpDBDirGlobal = "$runTmpDirGlobal/DB/";
system "mkdir -p $runTmpDBDirGlobal" unless (-d $runTmpDBDirGlobal);
#and check that this dir exists...
die "Can't create $runTmpDBDirGlobal\n" unless (-d $runTmpDBDirGlobal);
my $globaldDiaDBdir = $runTmpDBDirGlobal."DiamDB/";
system "mkdir -p $globaldDiaDBdir" unless (-d $globaldDiaDBdir);
#----------- map all reads to a specific reference ---------
#die "@ARGV $ARGV[0]\n";
if (@ARGV>0 && ($ARGV[0] eq "map2tar" || $ARGV[0] eq "map2DB")){
#in this case primary focus is on mapping and not on assemblies
if ($ARGV[0] eq "map2DB"){$mapModeCovDo=0;$mapModeDecoyDo=0;$mapModeTogether=0;}
if ($map2Assembly || $DoAssembly){
print "Mapping mode: Deactivating mapping and assembly modules\n";
$map2Assembly=0; $DoAssembly =0;
}
my @refDB1 = split(/,/,$refDBall);
my @bwt2Name1;
if (defined $bwt2NameAll){
@bwt2Name1 = split(/,/,$bwt2NameAll) ;
} elsif ($ARGV[0] eq "map2DB"){
@bwt2Name1 = ("refDB");
}
my @refDB;my @bwt2Name ;
my %FNrefDB2ndmap;
for (my $i=0;$i<@refDB1;$i++){
my @sfiles = glob($refDB1[$i]);
#die "@sfiles\n$refDB1[$i]\n";
if (@sfiles>1){
for (my $j=0;$j<@sfiles;$j++){
push(@refDB,$sfiles[$j]);
if ($bwt2Name1[$i] eq "auto"){
#$sfiles[$j] =~ m/ssemblyfind_list_(.*)\.txt\/(.*)\.contigs_/; my $nmnew = $1.$2; $nmnew =~ s/#/_/g;
$sfiles[$j] =~ m/\/([^\/]+)\.f.*a$/;
my $nmnew = $1;
#die "$nmnew\n";
push(@bwt2Name,$nmnew);
} else {
push(@bwt2Name,$bwt2Name1[$i].$j);
}
}
} elsif (@sfiles == 1) {
push(@refDB,$sfiles[0]);push(@bwt2Name,$bwt2Name1[$i]);
} else {
die "Could not find file for entry $refDB1[$i]\n";
}
}
#die "@refDB\n@bwt2Name\n";
#decoy mapping setup (only required in map2tar
$make2ndMapDecoy{Lib} = "";
#die "decoy mapping not ready for multi fastas\n" if (@refDB > 1);
for (my $i=0;$i<@refDB; $i++){ #take care of ref DB decoy prep
if ($mapModeDecoyDo || $mapModeTogether){
my $aref;
if ($mapModeTogether){
my $hr = readFasta($refDB[$i]); my %FN = %{$hr};
%FNrefDB2ndmap = (%FNrefDB2ndmap , %FN);
$aref = [keys %FN];
} else {
$aref = readFastHD($refDB[$i]);
}
push(@{$make2ndMapDecoy{regions}}, join(" ",@{$aref}) );
#die "@{$aref}\n".prefix_find($aref)."\n";
push(@{$make2ndMapDecoy{region_lcs}}, prefix_find($aref) );
}
}
my $shrtMapNm = "";
for ( my $i=0;$i< @bwt2Name; $i++){
my $substrl = length($bwt2Name[$i]);
if (@bwt2Name > 3){$substrl = 10;}
if (@bwt2Name > 5){$substrl = 7;}
if (@bwt2Name > 7){$substrl = 4;}
if ($i==0){
$shrtMapNm .= substr($bwt2Name[$i],0,$substrl);
} else {
$shrtMapNm .= ".". substr($bwt2Name[$i],0,$substrl);
}
if ($i>7){$shrtMapNm .= ".X".(@bwt2Name - $i)."X"; last;}
}
#build of combined refDB, if competitive mapping..
my $bwtDBcore = 10; my $largeDB = 0;
if ($mapModeTogether){
system "mkdir -p $baseOut/GlbMap/LOGandSUB/" unless (-d "$baseOut/GlbMap/LOGandSUB/");
system "mkdir -p $runTmpDBDirGlobal/$shrtMapNm" unless (-d "$runTmpDBDirGlobal/$shrtMapNm");
$map2ndTogRefDB{DB} = "$runTmpDBDirGlobal/$shrtMapNm/$shrtMapNm.fa";
#die "$map2ndTogRefDB{DB}\n";
writeFasta(\%FNrefDB2ndmap,"$map2ndTogRefDB{DB}");
print "$map2ndTogRefDB{DB}\n";
my ($cmd,$DBbtRef) = buildMapperIdx($map2ndTogRefDB{DB},$bwtDBcore,$largeDB,$MapperProg) ;
unless (-e "$DBbtRef.bw2.0.sa" || -e "$DBbtRef.bw2.rev.1.bt2l" ){
($bwt2ndMapDep,$cmd) = qsubSystem("$baseOut/GlbMap/LOGandSUB/builBwtIdx_comp.sh",$cmd,$bwtDBcore,(int(20/$bwtDBcore)+1) ."G","BWI_compe","","",1,[],\%QSBopt) ;
}
}
print "\n=======================\nmap to $refDBall\n=======================\n\n";
$mapModeActive =1;
for (my $i=0;$i<@refDB; $i++){
#$refDB[$i] =~ m/(.*\/)[^\/]+/;
#my $refDir = $1;
my $bwt2outDl = "$baseOut/GlbMap/$bwt2Name[$i]/";
push @bwt2ndMapNmds , $bwt2Name[$i];
push(@bwt2outD,$bwt2outDl);
#die $bwt2Name."\n";
#my $mapFile = "$baseOut/LOGandSUB/inmap.txt";
if ($rewrite || $rewrite2ndMap){
print "Deleting previous mapping results..\n";
$refDB[$i] =~ m/.*\/([^\/]+)$/;
system("rm -r -f $runTmpDBDirGlobal/$1*");#;mkdir -p $bwt2outDl
}
$refDB[$i] =~ m/.*\/([^\/]+)$/;
#print "\n$refDB[$i]\n";
#die "$bwt2outDl/$1\n";
system "mkdir -p $bwt2outDl/LOGandSUB" unless (-d "$bwt2outDl/LOGandSUB");
system "cp $refDB[$i] $bwt2outDl" if ($mapModeCovDo && !-e "$bwt2outDl/$1");
my ($cmd,$DBbtRef) = buildMapperIdx($refDB[$i],$bwtDBcore,$largeDB,$MapperProg) ;
$DBbtRef =~ s/\.bw2$//;
$DBbtRef =~ m/.*\/([^\/]+)$/;
$DBbtRef = "$runTmpDBDirGlobal/$1";#set up to scratch dir to map onto
$cmd.= "\ncp $refDB[$i]* $runTmpDBDirGlobal\n" unless (-e "$DBbtRef.pak" || ($MapperProg==1 && -e "$DBbtRef"));# if (!$mapModeCovDo && !-e "$bwt2outDl/$1");
#print $cmd."\n";
#die $DBbtRef."\n$runTmpDBDirGlobal/\n";
unless (-e "$DBbtRef.bw2.0.sa" || -e "$DBbtRef.bw2.rev.1.bt2l" || $mapModeTogether || $mapModeDecoyDo){ #not required for these map mody
#system $cmd
my ($bwt2ndMapDep2,$cmd2) = qsubSystem($bwt2outDl."/LOGandSUB/builBwtIdx$i.sh",$cmd,$bwtDBcore,(int(20/$bwtDBcore)+1) ."G","BWI".$i,"","",1,[],\%QSBopt) ;
$bwt2ndMapDep .= ";$bwt2ndMapDep2";
}
#$DBbtRefX = $DBbtRef;
push(@DBbtRefX,$DBbtRef);
if($mapModeCovDo){ #get the coverage per gene etc; for this I need a gene prediction
my $gDir = $bwt2outDl."";
my $nativeGFF = $refDB[$i];$nativeGFF =~ s/\.[^\.]+$/\.gff/;
my $gffF = "genes.$bwt2Name[$i].gff";
#die "$nativeGFF\n";
if (-e $nativeGFF){
system "cp $nativeGFF $gDir/$gffF";
} else {
system "mkdir -p $gDir";
$logDir = $gDir;
my $dEGP = $DO_EUK_GENE_PRED; $DO_EUK_GENE_PRED = 0;
my $tmpDep1 = run_prodigal_augustus($refDB[$i],$gDir,"",$gDir,"iGP$i","");
$DO_EUK_GENE_PRED = $dEGP;
my ($tmpDep,$tmpCmd) = qsubSystem( $bwt2outDl."/LOGandSUB/cpGenes.sh", "cp $gDir/genes.gff $nativeGFF; mv $gDir/genes.gff $gDir/$gffF",
1,"1G","genecop".$i,$tmpDep1,"",1,[],\%QSBopt);
$map2ndDeps .= ";".$tmpDep;
}
push(@DBbtRefGFF,$gDir."/$gffF");#"genePred/genes.gff"
# die "C";
}
$logDir="";
}
#die @bwt2outD." @bwt2outD\n";
#die $map2ndDeps;
} elsif (@ARGV > 2 && $ARGV[0] eq "scaffold"){
$scaffTarExternal = $ARGV[1];
if (!-f $scaffTarExternal){
die "Could not find scaffold file:\n$scaffTarExternal\n";
}
$scaffTarExternalName = $ARGV[2];
if (@ARGV>3){
$scaffTarExtLibTar = $ARGV[3];
}
} else { #make sure all switches are deactivated
$mapModeTogether = 0; $mapModeDecoyDo = 0; $mapModeActive = 0;
}
#die "@DBbtRefGFF\n";
#die "@{$make2ndMapDecoy{regions}}\n";
#some base stats kept in vars
my $sequencer = "hiSeq";#plattform the algos have to deal with
#my $DBpath="";
my $assDir="";
my $continue_JNUM = 0; #debug, set to 0 for full run
my $prevAssembly = ""; my $shortAssembly = "";#files with full length and short length assemblies
my $mmpuOutTab = "";
#fixed dirs for specific set of samples
my $dir_MP2 = $baseOut."pseudoGC/Phylo/MP2/"; #metaphlan 2 dir
my $dir_mOTU2 = $baseOut."pseudoGC/Phylo/mOTU2/"; #mOUT 2 dir
my $dir_RibFind = $baseOut."pseudoGC/Phylo/RiboFind/"; #ribofinder dir
my $dir_KrakFind = $baseOut."pseudoGC/Phylo/KrakenTax/$globalKraTaxkDB/"; #kraken dir
system("mkdir -p $baseOut") unless (-d $baseOut);
my $globalLogDir = $baseOut."LOGandSUB/";
system("mkdir -p $globalLogDir/sdm") unless (-d "$globalLogDir/sdm");
open $QSBopt{LOG},">",$globalLogDir."qsub.log";# unless ($doSubmit == 0);
print $globalLogDir."qsub.log\n";
my $collectFinished = $baseOut."runFinished.log\n";
my $globalNPD = $baseOut."NonPareil/";
system "mkdir -p $globalNPD" unless (-d "$globalNPD");
system "cp $mapFile $globalLogDir/inmap.txt";
my $presentAssemblies = 0; my $totalChecked=0;
my @samples = @{$map{smpl_order}}; my @allSmplNames;
my @allFilter1; my @allFilter2; my @inputRawFQs;
if ($to > @samples){
print "Reset range of samples to ". @samples."\n";
$to = @samples;
#die();
}
my $statStr = ""; my $statStr5 = "";
my %sampleSDMs;
my $baseSDMopt = getProgPaths("baseSDMopt_rel"); #"/g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/data/sdm_opt_inifilter_relaxed.txt";
if ($useSDM ==2 ){$baseSDMopt = getProgPaths("baseSDMopt");}#"/g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/data/sdm_opt_inifilter.txt";}
my $baseSDMoptMiSeq = getProgPaths("baseSDMoptMiSeq_rel");#"/g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/data/sdm_opt_miSeq.txt";
if ($useSDM ==2 ){$baseSDMoptMiSeq = getProgPaths("baseSDMoptMiSeq");}#"/g/bork3/home/hildebra/dev/Perl/reAssemble2Spec/data/sdm_opt_miSeq_relaxed.txt"; }
my @unzipjobs; my $curUnzipDep = "";
my $sdmjNamesAll = "";
my $waitTime = 0;
my $emptCmd = "sleep 333";
#qsubSystem($globalLogDir."emptyrun.sh","sleep 333",1,"1G",0,"empty","","",1);
#set up kraken human filter
my $krakDeps = ""; my $krakenDBDirGlobal = $runTmpDirGlobal;
if ($DoKraken && $globalKraTaxkDB eq ""){die "Kraken tax specified, but no DB specified\n";}
if ($humanFilter || ($DoKraken) || $DO_EUK_GENE_PRED){
$krakDeps = prepKraken();
}
my $mOTU2Deps = ""; my $mOTU2Bin = "";
if ($DoMOTU2){
($mOTU2Deps,$mOTU2Bin) = prepMOTU2();
}
#redo d2s intersample distance?
if ($DoCalcD2s) {$DoCalcD2s = !-e "$baseOut/d2StarComp/d2meta.stone";}
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
#--------------------------------------------------------------------------------
#die $to."\n";
for ($JNUM=$from; $JNUM<$to;$JNUM++){
#die $samples[$JNUM]."\n";
next if (exists($jmp{$JNUM}));
#locally used paths for a specific sample
my $dir2rd=""; my $curDir = "";my $curOutDir = "";
my $curSmpl = $samples[$JNUM];
$dir2rd = $map{$curSmpl}{dir};
$dir2rd = $map{$curSmpl}{prefix} if ($dir2rd eq "");
#print "$curSmpl $map{$curSmpl}{dir} $map{$curSmpl}{rddir} $map{$curSmpl}{wrdir}\n"; next;
my $SmplName = $map{$curSmpl}{SmplID};
push (@allSmplNames,$SmplName);
if ($dir2rd eq "" ){#very specific read dir..
if ($map{$curSmpl}{SupportReads} ne ""){
$curDir = ""; $curOutDir = "$baseOut$SmplName/";
} else {
die "Can;t find valid path for $SmplName\n";
}
$dir2rd = $SmplName;
} else {
$curDir = $map{$curSmpl}{rddir}; $curOutDir = $map{$curSmpl}{wrdir};
}
#die "$curDir\n$curOutDir\n$baseOut\n";
my $samplReadLength = $defaultReadLength; #some default value
if (exists $map{$curSmpl}{readLength} && $map{$curSmpl}{readLength} != 0){
$samplReadLength = $map{$curSmpl}{readLength};
}
my $curSDMopt = $baseSDMopt;
#my $iqualOff = 33; #62 for 1st illu
if (exists($map{$curSmpl}{SeqTech})){
if ($map{$curSmpl}{SeqTech} eq "GAII_solexa" || $map{$curSmpl}{SeqTech} eq "GAII"){
#$iqualOff = 59; #really that old??
} elsif ($map{$curSmpl}{SeqTech} eq "miSeq"){
$curSDMopt = $baseSDMoptMiSeq;
}
}
if (!exists($sampleSDMs{$samplReadLength})){
$sampleSDMs{$samplReadLength} = adaptSDMopt($curSDMopt,$globalLogDir,$samplReadLength);
}
my $cAssGrp = $JNUM;
#print $map{$curSmpl}{AssGroup}."\n";
if ($map{$curSmpl}{AssGroup} ne "-1"){ $cAssGrp = $map{$curSmpl}{AssGroup};}
my $cMapGrp = $map{$curSmpl}{MapGroup};
$curSDMopt = $sampleSDMs{$samplReadLength};
$totalChecked++;
#die $SmplName." $samplReadLength\n";
print "\n======= $dir2rd - $JNUM - $SmplName =======\n" unless($silent);
#my $dir2rd = "alien2-11-0-0";
my $GlbTmpPath = "$runTmpDirGlobal$dir2rd/"; #curTmpDir
my $nodeSpTmpD = "$nodeTmpDirBase/$SmplName";
$logDir = "$curOutDir/LOGandSUB/";
my @checkLocs = ($GlbTmpPath);
push(@checkLocs,$curDir) if ($curDir ne "");
my $mapOut = "$GlbTmpPath/mapping/";
#$DBpath="$curOutDir/readDB/";
my $finalCommAssDir = "$curOutDir/assemblies/metag/";
my $finalMapDir = "$curOutDir/mapping";
my $KrakenOD = $curOutDir."Tax/kraken/$globalKraTaxkDB/";
#tmp hack to clean single sample mappings <- in the end not used, just stick to old structure..
#if ($AsGrps{$cMapGrp}{CntAimMap} > 1 ){die "rm -r $finalMapDir $mapOut\n"; next; }
#if (-d "$finalCommAssDir/mismatch_corrector" || -d "$finalCommAssDir/tmp"){
# print "Removing temporary Spades Dirs..\n";
# system "rm -rf $finalCommAssDir/mismatch_corrector/ $finalCommAssDir/tmp";
#}
$AsGrps{$cAssGrp}{AssemblSmplDirs} .= $curOutDir."\n";
my $AssemblyGo=0; my $MappingGo=0; #controls if assemblies / mappings are done in respective groups
#complicated flow control for multi sample assemblies
$assDir="$runTmpDirGlobal/AssmblGrp_$cAssGrp/";
die $baseID."\n" if ($cAssGrp eq "");
$finalCommAssDir = "$baseOut/AssmblGrp_$cAssGrp/metag/" if ( !exists($AsGrps{$cAssGrp}{CntAimAss}) || $AsGrps{$cAssGrp}{CntAimAss}>1);
#assign job name (dependency) only ONCE
if ( !exists($AsGrps{$cAssGrp}{CntAss}) || $AsGrps{$cAssGrp}{CntAss} == 0){
$AsGrps{$cAssGrp}{AssemblJobName} = "_XXASpl$cAssGrp"."XX_" ;
$AsGrps{$cAssGrp}{CSfinJobName} = "_XXCSpl$cAssGrp"."XX_" ;
}
$AsGrps{$cAssGrp}{CntAss} ++;
print $AsGrps{$cAssGrp}{CntAss} .":".$AsGrps{$cAssGrp}{CntAimAss} unless ($silent);
if ($AsGrps{$cAssGrp}{CntAss} >= $AsGrps{$cAssGrp}{CntAimAss} ){
#print "running assembluy";
$AssemblyGo = 1;
if ($AsGrps{$cAssGrp}{CntAimAss}==1){
$assDir="$GlbTmpPath/assemblies/";
}
}
#mapping groups?
$AsGrps{$cMapGrp}{CntMap} ++;
print " ".$AsGrps{$cMapGrp}{CntMap} .":".$AsGrps{$cMapGrp}{CntAimMap}."\n" unless ($silent);
if (!exists($AsGrps{$cMapGrp}{CntMap})){ die "Can;t find CntMap for $cMapGrp";}
if ($AsGrps{$cMapGrp}{CntMap} >= $AsGrps{$cMapGrp}{CntAimMap} ){
#print "running mapping";
$MappingGo = 1;
}
if ($DoAssembly ==0 ){$AssemblyGo=0;}
my $statsDone=0;
#DELETION SECTION
#redo run - or parts thereof
if ($rewrite){
print "Deleting previous results..\n";
system ("rm -r -f $assDir $finalCommAssDir");
system("rm -f -r $curOutDir $GlbTmpPath $collectFinished ");
}
my $finAssLoc = "$finalCommAssDir/scaffolds.fasta.filt";
#die "$finAssLoc\n";
#automatically delete mapping, if assembly no longer exists..
my $locRedoAssMapping = $redoAssMapping;
$locRedoAssMapping =1 if (!-e $finAssLoc && -e "$finalMapDir/$SmplName-smd.bam.coverage.gz");
#delete assembly
if ($redoAssembly){
system "rm -fr $finalCommAssDir";
$locRedoAssMapping=1;
}
#delete mapping to assembly
if ($locRedoAssMapping){
print "Deleting previous mapping onto assembly\n";
system "rm -fr $finalMapDir $mapOut";
}
system "rm -r $KrakenOD" if ($RedoKraken && -d $KrakenOD);
if ($RedoRiboFind){system "rm -rf $curOutDir/ribos";}
if ($RedoRiboAssign){system "rm $curOutDir/ribos//ltsLCA/*.sto";}
if ($DoRibofind && -e "$curOutDir/LOGandSUB/RiboLCA.sh.etxt"){
my $LCAetxt = `cat $curOutDir/LOGandSUB/RiboLCA.sh.etxt`;
if ($LCAetxt =~ m/ParseError thrown: Unexpected character .\@. found/){system "rm -rf $curOutDir/ribos";}
}
if ($alwaysDoStats){
my ($statsHD,$curStats,$statsHD5,$curStats5) = smplStats($curOutDir,$assDir);
$statsDone=1;
if ($statStr eq ""){
$statStr.="SMPLID\tDIR\t".$statsHD."\n".$curSmpl."\t$dir2rd\t".$curStats."\n";
$statStr5.="SMPLID\tDIR\t".$statsHD5."\n".$curSmpl."\t$dir2rd\t".$curStats5."\n";
} else {$statStr.=$curSmpl."\t$dir2rd\t".$curStats."\n"; $statStr5.=$curSmpl."\t$dir2rd\t".$curStats5."\n";}
}
my $boolGenePredOK=0;
if ($DO_EUK_GENE_PRED){
$boolGenePredOK = 1 if (-s "$finalCommAssDir/genePred/proteins.bac.shrtHD.faa" || ($pseudoAssembly && -e "$finalCommAssDir/genePred/proteins.bac.shrtHD.faa"));
} else {
$boolGenePredOK = 1 if (-s "$finalCommAssDir/genePred/proteins.shrtHD.faa" || ($pseudoAssembly && -e "$finalCommAssDir/genePred/proteins.shrtHD.faa") );
}
#die "$boolGenePredOK\n$finalCommAssDir/genePred/proteins.bac.shrtHD.faa\n";
my $boolAssemblyOK=0;
#die $finalCommAssDir;
#quick fix
if (!-e "$finalCommAssDir/genePred/genes.per.ctg" && -e "$finalCommAssDir/genePred/genes.gff"){my $tmpGene = "$finalCommAssDir/genePred";
system "cut -f1 $tmpGene/genes.gff | sort | uniq -c | grep -v '#' | awk -v OFS='\\t' {'print \$2, \$1'} > $tmpGene/genes.per.ctg"}
#central flag
$boolAssemblyOK=1 if ($boolGenePredOK && -e "$finAssLoc" && #-e "$finalCommAssDir/genePred/proteins.shrtHD.faa" &&
(!$map2Assembly || (-e "$finAssLoc.bw2.4.bt2" && -e "$finAssLoc.bw2.3.bt2" && -e "$finalMapDir/$SmplName-smd.bam.coverage.gz") ) );
#&& (-s "$finalMapDir/$SmplName-smd.bam" || -s "$finalMapDir/$SmplName-smd.cram")
#die "$boolAssemblyOK $AssemblyGo ass $finalCommAssDir\n";
#print "$boolAssemblyOK\n$finalCommAssDir/genePred/proteins.shrtHD.faa\n";
my $boolScndMappingOK = 1; my $iix =0;
my $boolScndCoverageOK = 1;
if ($rewrite2ndMap){
foreach my $bwt2outDTT (@bwt2outD){
my $expectedMapCovGZ = "$bwt2outDTT/$bwt2ndMapNmds[$iix]"."_".$SmplName."-0-smd.bam.coverage.gz";
system "rm -f $expectedMapCovGZ*";
}
}
foreach my $bwt2outDTT (@bwt2outD){
my $expectedMapCovGZ = "$bwt2outDTT/$bwt2ndMapNmds[$iix]"."_".$SmplName."-0-smd.bam.coverage.gz";
my $expectedMapBam = "$bwt2outDTT/$bwt2ndMapNmds[$iix]"."_".$SmplName."-0-smd.bam";
$iix++;
#print $expectedMapCovGZ."\n";
if ( -e "$expectedMapCovGZ" && -e $expectedMapBam && $MappingGo ){
$boolScndMappingOK=1;
}else{
$boolScndMappingOK=0; $boolScndCoverageOK=0;
#be clean
system "rm -f $expectedMapBam*";
last;
}
if ($mapModeCovDo && (!-e $expectedMapCovGZ.".median.percontig" || !-e $expectedMapCovGZ.".percontig"|| !-e $expectedMapCovGZ.".pergene")){
$boolScndCoverageOK=0;
system "rm -f $expectedMapCovGZ.*";
}
}
if (@bwt2outD == 0 ){$boolScndMappingOK = 1 ; $boolScndCoverageOK=1;}#|| !$MappingGo);
#print $boolScndMappingOK."\n$boolAssemblyOK\n";
#Kraken flag
my $calcKraken =0;
$calcKraken = 1 if ($DoKraken && (!-d $KrakenOD || !-e "$KrakenOD/krakDone.sto"));
if (!$calcKraken && $DoKraken){
opendir D, $KrakenOD; my @krkF = grep {/krak\./} readdir(D); closedir D;
foreach my $kf (@krkF){
$kf =~ m/krak\.(.*)\.cnt\.tax/; my $thr = $1;# die $thr." $kf\n";
system "mkdir -p $dir_KrakFind/$thr" unless (-d "$dir_KrakFind/$thr"); #system "mkdir -p $dir_RibFind/SSU/" unless (-d "$dir_RibFind/SSU/"); system "mkdir -p $dir_RibFind/LSU/" unless (-d "$dir_RibFind/LSU/");
system "cp $KrakenOD/$kf $dir_KrakFind/$thr/$SmplName.$thr.krak.txt";
}
} else {$KrakTaxFailCnts++;}
#system "rm -f $curOutDir/ribos//ltsLCA/LSU_ass.sto $curOutDir/ribos//ltsLCA/Assigned.sto"; fix for new LSU assignments
my $calcGenoSize=0; $calcGenoSize=1 if ($DoGenoSize && !-e "$curOutDir/MicroCens/MC.0.result");
my $calcRibofind = 0; my $calcRiboAssign = 0;
$calcRibofind = 1 if ($DoRibofind && (!-e "$curOutDir/ribos//SSU_pull.sto"|| !-e "$curOutDir/ribos//LSU_pull.sto" || ($doRiboAssembl && !-e "$curOutDir/ribos/Ass/allAss.sto" ))); #!-e "$curOutDir/ribos//ITS_pull.sto"||
$calcRiboAssign = 1 if ($DoRibofind && ( #!-e "$curOutDir/ribos//ltsLCA/ITS_ass.sto"|| #ITS no longer required.. unreliable imo
!-e "$curOutDir/ribos//ltsLCA/Assigned.sto" || !-e "$curOutDir/ribos//ltsLCA/LSU_ass.sto" || !-e "$curOutDir/ribos//ltsLCA/SSU_ass.sto") );
#if ($calcRiboAssign) {$calcRibofind=1;}
#die "$calcRibofind $calcRiboAssign\n";
if ($calcRibofind || $calcRiboAssign){
if ($RedoRiboThatFailed ){
system "rm -r $curOutDir/ribos/";
$calcRibofind = 1;
}
$riboFindFailCnts ++ ;
} elsif ($DoRibofind && !$calcRiboAssign) { #copy files to central dir for postprocessing..
my @RFtags = ("SSU","LSU");#"ITS",
foreach my $RFtag (@RFtags){
system "mkdir -p $dir_RibFind/$RFtag/" unless (-d "$dir_RibFind/$RFtag/"); #system "mkdir -p $dir_RibFind/SSU/" unless (-d "$dir_RibFind/SSU/"); system "mkdir -p $dir_RibFind/LSU/" unless (-d "$dir_RibFind/LSU/");
my $fromCp = "$curOutDir/ribos/ltsLCA/${RFtag}riboRun_bl.hiera.txt"; my $toCpy = "$dir_RibFind/$RFtag/$SmplName.$RFtag.hiera.txt";
if ($checkRiboNonEmpty){
#pretty hard check
my $numLines=0;
if (-e "$fromCp.gz"){$numLines = `zcat $fromCp.gz | wc -l`;
} else {$numLines = `wc -l $fromCp`;} $numLines =~ /(\d+)/; $numLines=$1;
#die $numLines."\n";
if ($numLines<=1){$calcRiboAssign=1;$calcRibofind=1;
system "rm -r $curOutDir/ribos//ltsLCA $curOutDir/ribos/*.sto ";last;
}
}
if (!-e $toCpy || ( (-e $toCpy || -e "$toCpy.gz" ) && -e $fromCp && -s $fromCp != -s $toCpy)){
unlink "$toCpy" if -e ($toCpy);
if (-e "$fromCp.gz" ){
#system "zcat $fromCp.gz > $toCpy" ;
system "ln -s $fromCp.gz $toCpy.gz" if (!-e "$toCpy.gz");
} elsif (-e $fromCp) {
system "gzip $fromCp";
system "ln -s $fromCp.gz $toCpy.gz" ;
} else {#just redo..
system "rm -rf $curOutDir/ribos\n";
$calcRibofind = 1; $calcRiboAssign=1;
last;
}
}
#system "gzip $fromCp" unless (-e "$fromCp.gz");
system "rm -f $curOutDir/ribos/ltsLCA/inter${RFtag}riboRun_bl.fna" if (-e "$curOutDir/ribos/ltsLCA/inter${RFtag}riboRun_bl.fna");
}
}
my ($calcDiamond,$calcDiaParse) = IsDiaRunFinished($curOutDir);
#die "XX $calcDiamond $calcDiaParse\n";
my $calcMetaPhlan=0;$calcMetaPhlan=1 if ($DoMetaPhlan && !-e $dir_MP2."$SmplName.MP2.sto");
if (!-e $dir_MP2."$SmplName.MP2.sto"){$metaPhl2FailCnts++;}
my $calcMOTU2=0;$calcMOTU2=1 if ($DoMOTU2 && !-e $dir_mOTU2."$SmplName.Motu2.sto");
if (!-e $dir_mOTU2."$SmplName.Motu2.sto"){$mOTU2FailCnts++;}
if ($redoCS){
system("rm -r -f $finalCommAssDir/ContigStats/ $curOutDir/assemblies/metag/ContigStats/ $curOutDir/Binning/");
}
if ($map2Assembly && -e "$finalMapDir/$SmplName-smd.bam.coverage.gz" && !-s "$finalMapDir/done.sto"){system "rm -r $finalMapDir";$boolAssemblyOK=0;}
if ( $boolAssemblyOK ){#causes a lot of overhead but mainly to avoid unpacking reads again..
print "present: $curOutDir \n"; $presentAssemblies ++;#= $AsGrps{$cAssGrp}{CntAimAss};
#base is present, but is the additions?
my $CRAMsto = "$finalMapDir/$SmplName-smd.cram.sto";
if ($map2Assembly && $doBam2Cram && !-e $CRAMsto){#.cram.sto to check that everything went well
$QSBopt{LocationCheckStrg}="";
bam2cram("$finalMapDir/$SmplName-smd.bam", "$finalCommAssDir/scaffolds.fasta.filt",1,1,$doBam2Cram,$CRAMsto,4);
}
my $CSfilesComplete = 1;
$CSfilesComplete = 0 if (!-s "$finalCommAssDir/ContigStats/scaff.pergene.GC3" || !-s "$finalCommAssDir/ContigStats/scaff.4kmer.gz"
|| !-s "$curOutDir/assemblies/metag/ContigStats/Coverage.pergene" || !-s "$finalCommAssDir/ContigStats/FMG/FMGids.txt"
|| !-s "$curOutDir/assemblies/metag/ContigStats/Coverage.count_pergene" || !-e "$curOutDir/assemblies/metag/assembly.txt");
#print "$CSfilesComplete CScompl\n";
#die "$finalCommAssDir/genePred/genes.gff\n$curOutDir/assemblies/metag/ContigStats/Coverage.median.percontig\n".(stat("$finalCommAssDir/genePred/genes.gff"))[9]." > ".(stat("$curOutDir/assemblies/metag/ContigStats/Coverage.median.percontig"))[9]."\n";
if ($CSfilesComplete && (stat("$finalCommAssDir/genePred/genes.gff"))[9] > (stat("$curOutDir/assemblies/metag/ContigStats/Coverage.median.percontig"))[9]){
system("rm -r -f $curOutDir/assemblies/metag/ContigStats ");
}
if ($AssemblyGo && !$CSfilesComplete || ($DoBinning && !-s "$finalCommAssDir/Binning/MaxBin/MB.summary") ) {
print "Running Contig Stats on assembly\n";
#print "$finalCommAssDir/ContigStats/scaff.pergene.GC\n";
my $subprts = "agkes"; $subprts .= "m" if ($DoBinning);
#die "$subprts\n";
contigStats($curOutDir ,"",$GlbTmpPath,$finalCommAssDir,$subprts,1,1,$samplReadLength);
} elsif (!$AssemblyGo && (!$CSfilesComplete || ($DoBinning && !-s "$curOutDir/Binning/MaxBin/MB.summary" )
|| ($DoBinning && !-s "$curOutDir/Binning/MetaBat/MeBa.sto") )){
print "Running Gene Coverage & Binning\n";
#die -s "$curOutDir/assemblies/metag/ContigStats/Coverage.pergene" .-s "$curOutDir/Binning/MaxBin/MB.summary" .-s "$curOutDir/Binning/MetaBat/MeBa.sto"."\n";
#my ($jn,$delaySubmCmd2) = contigStats($curOutDir ,$AsGrps{$cAssGrp}{CSfinJobName},$GlbTmpPath,$finalCommAssDir,"a",$AssemblyGo);
my $subprts = "as"; $subprts .= "m" if ($DoBinning);
contigStats($curOutDir ,"",$GlbTmpPath,$finalCommAssDir,$subprts,1,1,$samplReadLength);
} elsif (!$statsDone) {#ready to collect some stats
my ($statsHD,$curStats,$statsHD5,$curStats5) = smplStats($curOutDir,$assDir);
$statsDone=1;
if ($statStr eq ""){
$statStr.="SMPLID\tDIR\t".$statsHD."\n".$curSmpl."\t$dir2rd\t".$curStats."\n";
$statStr5.="SMPLID\tDIR\t".$statsHD5."\n".$curSmpl."\t$dir2rd\t".$curStats5."\n";
} else {$statStr.=$curSmpl."\t$dir2rd\t".$curStats."\n"; $statStr5.=$curSmpl."\t$dir2rd\t".$curStats5."\n";}
}
#die "$boolScndMappingOK && !$DoCalcD2s && !$calcRibofind && !$calcDiamond && !$calcMetaPhlan && !$calcKraken\n";
if ($boolScndCoverageOK && $boolScndMappingOK && !$DoCalcD2s && !$calcRibofind&& !$calcOrthoPlacement && !$calcGenoSize && !$calcDiamond && !$calcDiaParse && !$calcMetaPhlan && !$calcMOTU2 && !$calcKraken && $scaffTarExternal eq ""){
#free some scratch
#system "rm -rf $GlbTmpPath &" if ($DoFreeGlbTmp);
system "rm -rf $GlbTmpPath &" if ($rmScratchTmp );
print "next";next;
}
} elsif ($unfiniRew==1){
print "Deleting previous results..\n";
system("rm -f -r $curOutDir $GlbTmpPath $collectFinished");
} elsif (0&&$doSubmit == 0){
#system("mkdir -p $GlbTmpPath\nmkdir -p $DBpath\nmkdir -p $assDir\n mkdir -p $logDir");
next;
}
#die "X";
if ($redoFails && ($calcRibofind||$calcDiamond || $calcDiaParse ||$calcMOTU2 || $calcMetaPhlan)){
die "now recalc $curSmpl\n";
system ("rm -r -f $assDir $finalCommAssDir");
system("rm -f -r $curOutDir $GlbTmpPath $collectFinished ");
}
#next;
system("mkdir -p $logDir"); #mkdir -p $GlbTmpPath\n mkdir -p $DBpath\n mkdir -p $assDir\n