-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathestimateSelfSimilarity.pl
More file actions
executable file
·2160 lines (1817 loc) · 67.1 KB
/
estimateSelfSimilarity.pl
File metadata and controls
executable file
·2160 lines (1817 loc) · 67.1 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
#!/usr/bin/perl -w
# Example command:
# ./estimateWithinTreeDistances.pl.pl --action dbDir ../db/refseq --taxonomyDir /data/projects/phillippy/projects/mashsim/NCBI/refseq/taxonomy/
use strict;
use List::MoreUtils qw/all mesh any /;
use List::Util qw/sum min max/;
use Data::Dumper;
use Getopt::Long;
use File::Find;
use Math::GSL::Randist qw/gsl_ran_binomial_pdf/;
use FindBin;
use lib "$FindBin::Bin/perlLib";
use Cwd qw/getcwd abs_path/;
use File::Copy;
$| = 1;
use taxTree;
use Util;
my @taxonomy_fields = qw/species genus family order phylum superkingdom/;
my $metamap_bin = Util::get_metaMap_bin_and_enforce_mainDir();
my $classical_mashmap_bin = '/data/projects/phillippy/software/mashmap/mashmap';
my $action = '';
my $DB = '';
my $templateDB;
my $mode;
my $jobI;
my $jobITemplate;
my $autoSubmit = 0;
my $readSimSize = 2000;
my $readSimDelta = 1000;
my $readSimSizeFrom = 2000;
my $readSimSizeTo = 50000;
my $readSimSizeStep = 1000;
my $target_max_simulatedChunks = 2000;
my $path_to_myself = $FindBin::Bin . '/estimateSelfSimilarity.pl';
my $path_to_cwd = getcwd();
GetOptions (
'DB:s' => \$DB,
'templateDB:s' => \$templateDB,
'jobITemplate:s' => \$jobITemplate,
'mode:s' => \$mode,
'jobI:s' => \$jobI,
'autoSubmit:s' => \$autoSubmit,
);
unless($DB and (-d $DB))
{
die "Please specify valid DB directory via --DB";
}
my $taxonomyDir = $DB . '/taxonomy';
my $file_ref = $DB . '/DB.fa';
die "File $file_ref not existing" unless(-e $file_ref);
my $outputDir = $DB . '/selfSimilarity';
my $outputDir_computation = $outputDir . '/computation';
my $outputDir_results = $outputDir . '/results';
my $outputFn_jobs = $outputDir . '/jobs';
my $outputFn_jobs_fromTemplate = $outputDir . '/jobs.fromTemplate';
my $outputFn_qsub = $outputDir . '/jobs.qsub';
my $outputFn_reads_results_many = $outputDir . '/results.reads.many.byNode';
my $finalResultsFile = $DB . '/selfSimilarities.txt';
my $finalResultsFile_expectedGenomeSizes = $DB . '/selfSimilarities.txt.expectedGenomeSizes';
my $outputDir_templateDB = ($templateDB // '') . '/selfSimilarity';
my $outputDir_results_templateDB = $outputDir_templateDB . '/results';
my $outputFn_jobs_inTemplateDir = $outputDir_templateDB . '/jobs';
if(not $mode)
{
die "Please specify --mode; e.g.: prepareFromScratch, prepareFromTemplate";
}
elsif($mode eq 'prepareFromScratch')
{
(mkdir($outputDir) or die "Cannot mkdir $outputDir") unless(-d $outputDir);
(mkdir($outputDir_computation) or die "Cannot mkdir $outputDir") unless(-d $outputDir_computation);
(mkdir($outputDir_results) or die "Cannot mkdir $outputDir") unless(-d $outputDir_results);
print "Prepare self-similarity computation from scratch - output directory $outputDir\n";
# read taxonID -> contigs
my %taxonID_2_contigs;
my %contigLength;
Util::read_taxonIDs_and_contigs($DB, \%taxonID_2_contigs, \%contigLength);
# sanity check: get contig lengths from actual DB
my $actualContigLengths_href = Util::extractContigLengths($file_ref);
die Dumper("Discrepancy number of contig ID keys", scalar(keys %$actualContigLengths_href), scalar(keys %contigLength)) unless(scalar(keys %$actualContigLengths_href) == scalar(keys %contigLength));
die unless(all {$contigLength{$_} == $actualContigLengths_href->{$_}} keys %contigLength);
# read taxonomy
my $taxonomy = taxTree::readTaxonomy($taxonomyDir);
# strip down to mappable components
taxTree::removeUnmappableParts($taxonomy, \%taxonID_2_contigs);
# get leaves that we want to estimate potentially new node distances for
my @nodesForAttachment = taxTree::getNodesForPotentialAttachmentOfNovelSpecies($taxonomy);
# sanity check that really all leaf nodes are mappable
my @nodesForAttachment_leaves = map {taxTree::descendants_leaves($taxonomy, $_)} @nodesForAttachment;
die unless(all {exists $taxonID_2_contigs{$_}} @nodesForAttachment_leaves);
print "Have ", scalar(@nodesForAttachment), " nodes that hypothetical new species could be attached to.\n";
# open jobs file
open(JOBS, '>', $outputFn_jobs) or die "Canot open $outputFn_jobs";
# derive subcomputations for each node
my $total_computations = 0;
my $computations_max_per_node = 0;
my $computations_max_per_node_which;
foreach my $nodeID (sort @nodesForAttachment)
{
my @thisNode_self_simililarity_subcomputations = taxTree::getSubComputationsForAttachment($taxonomy, $nodeID, \%taxonID_2_contigs);
die Dumper("Fewer subcomputations than expected", scalar(@thisNode_self_simililarity_subcomputations), scalar(@{$taxonomy->{$nodeID}{children}})) unless(scalar(@thisNode_self_simililarity_subcomputations) >= scalar(@{$taxonomy->{$nodeID}{children}}));
my $computations_thisNode = scalar(@thisNode_self_simililarity_subcomputations);
$total_computations += $computations_thisNode;
if($computations_thisNode > $computations_max_per_node)
{
$computations_max_per_node = $computations_thisNode;
$computations_max_per_node_which = $nodeID;
}
# print "Node $nodeID, $computations_thisNode computations.\n";
foreach my $node_computation (@thisNode_self_simililarity_subcomputations)
{
my $targetLeafID = $node_computation->[1];
my $targetLeaf_genomeSize = Util::getGenomeLength($targetLeafID, \%taxonID_2_contigs, \%contigLength);
my @targetLeaf_compareAgainst = sort @{$node_computation->[2]};
my @targetLeaf_contigs = sort keys %{$taxonID_2_contigs{$targetLeafID}};
my $targetLeaf_compareAgainst_combinedSize = 0;
my @compareAgainst_contigs;
my %ranks_compareAgainst;
foreach my $taxonID (@targetLeaf_compareAgainst)
{
$targetLeaf_compareAgainst_combinedSize += Util::getGenomeLength($taxonID, \%taxonID_2_contigs, \%contigLength);
push(@compareAgainst_contigs, keys %{$taxonID_2_contigs{$taxonID}});
$ranks_compareAgainst{$taxonomy->{$taxonID}{rank}}++;
}
@compareAgainst_contigs = sort @compareAgainst_contigs;
print JOBS join("\t",
$nodeID, # the node we're attaching new species todo
$taxonomy->{$nodeID}{rank},
$node_computation->[0], # the node's immediate child we're taking the to-map-genome from
$taxonomy->{$node_computation->[0]}{rank},
$targetLeafID, # the node which we're now mapping against the genomes of the other children
$taxonomy->{$targetLeafID}{rank},
$targetLeaf_genomeSize,
scalar(@targetLeaf_compareAgainst),
join(";", @targetLeaf_compareAgainst),
$targetLeaf_compareAgainst_combinedSize,
join(";", @targetLeaf_contigs),
join(";", @compareAgainst_contigs),
join(';', sort keys %ranks_compareAgainst)
), "\n";
}
}
print "Need to carry out $total_computations computations in total; max $computations_max_per_node per node ($computations_max_per_node_which, " . taxTree::taxon_id_get_name($computations_max_per_node_which, $taxonomy), ").\n";
close(JOBS);
print "Generated file $outputFn_jobs\n";
open(QSUB, '>', $outputFn_qsub) or die "Cannot open $outputFn_qsub";
print QSUB qq(#!/bin/bash
#\$ -t 1-${total_computations}
jobID=\$(expr \$SGE_TASK_ID - 1)
cd $path_to_cwd
perl $path_to_myself --mode doJobI --DB $DB --jobI \$jobID
);
close(QSUB);
print "\nIf you use an SGE environment, you can do 'qsub $outputFn_qsub' to submit inidividual computation jobs.\n\n";
if($autoSubmit)
{
system("qsub $outputFn_qsub") and die "Could not qsub $outputFn_qsub";
}
}
elsif($mode eq 'prepareFromTemplate')
{
die "Please specify --templateDB" unless(defined $templateDB);
die "Template DB $templateDB does not have self-similarity results" unless(-e $templateDB . '/selfSimilarities.txt');
(mkdir($outputDir) or die "Cannot mkdir $outputDir") unless(-d $outputDir);
(mkdir($outputDir_computation) or die "Cannot mkdir $outputDir") unless(-d $outputDir_computation);
(mkdir($outputDir_results) or die "Cannot mkdir $outputDir") unless(-d $outputDir_results);
# read existing computation details
my $get_computation_key = sub {
my $contigs_A_str = shift;
my $contigs_B_str = shift;
return $contigs_A_str . '///' . $contigs_B_str;
};
my $fn_template_jobs = $templateDB . '/selfSimilarity/jobs';
die "Template DB $templateDB does not have self-similarity jobs file" unless(-e $fn_template_jobs);
my %templateDB_existingComputation_toJobID;
my %templateDB_attachableNodes;
my %templateDB_A_to_B;
{
open(JOBS, '<', $fn_template_jobs) or die "Cannot open $outputFn_jobs";
my $jobI = -1;
while(<JOBS>)
{
my $line = $_;
$jobI++;
chomp($line);
my @fields = split(/\t/, $line);
die unless($#fields == 12);
my $nodeID = $fields[0];
my $A_taxonID = $fields[4];
my $B_taxonIDs = $fields[8];
my $contigs_A = $fields[10];
my $contigs_B = $fields[11];
my $computation_key = $get_computation_key->($contigs_A, $contigs_B);
die if(exists $templateDB_existingComputation_toJobID{$computation_key});
$templateDB_existingComputation_toJobID{$computation_key} = $jobI;
$templateDB_attachableNodes{$nodeID} = 1;
my %contigs_B_href = map {$_ => 1} split(/;/, $contigs_B);
push(@{$templateDB_A_to_B{$contigs_A}}, [\%contigs_B_href, $jobI]);
}
close(JOBS);
}
print "Prepare self-similarity for $DB, based on $templateDB \n";
# details for reduced DB
my %reduced_taxonID_2_contigs;
my %reduced_contigLength;
Util::read_taxonIDs_and_contigs($DB, \%reduced_taxonID_2_contigs, \%reduced_contigLength);
# read reduced taxonomy
my $reduced_taxonomy = taxTree::readTaxonomy($taxonomyDir);
taxTree::removeUnmappableParts($reduced_taxonomy, \%reduced_taxonID_2_contigs);
my @nodesForAttachment = taxTree::getNodesForPotentialAttachmentOfNovelSpecies($reduced_taxonomy);
# template data
my %template_taxonID_2_contigs;
my %template_contigLength;
my $template_taxonomy = taxTree::readTaxonomy($templateDB . '/taxonomy');
Util::read_taxonIDs_and_contigs($templateDB, \%template_taxonID_2_contigs, \%template_contigLength);
taxTree::removeUnmappableParts($template_taxonomy, \%template_taxonID_2_contigs);
# check that this is a valid template
foreach my $contigID_in_reduced (keys %reduced_contigLength)
{
die unless(defined $template_contigLength{$contigID_in_reduced});
}
# sanity check that really all leaf nodes are mappable
my @nodesForAttachment_leaves = map {taxTree::descendants_leaves($reduced_taxonomy, $_)} @nodesForAttachment;
die unless(all {exists $reduced_taxonID_2_contigs{$_}} @nodesForAttachment_leaves);
print "\nHave nodes ", scalar(@nodesForAttachment), " that hypothetical new species could be attached to.\n";
# derive subcomputations for each node
# open jobs file
open(JOBS, '>', $outputFn_jobs_fromTemplate) or die "Canot open $outputFn_jobs_fromTemplate";
my @missingData_computations;
my $total_computations = 0;
my $total_computations_haveResult = 0;
my $jobI = -1;
foreach my $nodeID (sort @nodesForAttachment)
{
die unless($templateDB_attachableNodes{$nodeID});
my @thisNode_self_simililarity_subcomputations = taxTree::getSubComputationsForAttachment($reduced_taxonomy, $nodeID, \%reduced_taxonID_2_contigs);
die Dumper("Fewer subcomputations than expected", scalar(@thisNode_self_simililarity_subcomputations), scalar(@{$reduced_taxonomy->{$nodeID}{children}})) unless(scalar(@thisNode_self_simililarity_subcomputations) >= scalar(@{$reduced_taxonomy->{$nodeID}{children}}));
foreach my $node_computation (@thisNode_self_simililarity_subcomputations)
{
$jobI++;
my $targetLeafID = $node_computation->[1];
my $targetLeaf_genomeSize = Util::getGenomeLength($targetLeafID, \%reduced_taxonID_2_contigs, \%reduced_contigLength);
my @targetLeaf_compareAgainst = sort @{$node_computation->[2]};
my @targetLeaf_contigs = sort keys %{$reduced_taxonID_2_contigs{$targetLeafID}};
my $targetLeaf_compareAgainst_combinedSize = 0;
my @compareAgainst_contigs;
my %ranks_compareAgainst;
foreach my $taxonID (@targetLeaf_compareAgainst)
{
$targetLeaf_compareAgainst_combinedSize += Util::getGenomeLength($taxonID, \%reduced_taxonID_2_contigs, \%reduced_contigLength);
push(@compareAgainst_contigs, keys %{$reduced_taxonID_2_contigs{$taxonID}});
$ranks_compareAgainst{$reduced_taxonomy->{$taxonID}{rank}}++;
}
@compareAgainst_contigs = sort @compareAgainst_contigs;
my $contigs_A = join(';', @targetLeaf_contigs);
my $computation_key = $get_computation_key->($contigs_A, join(';', @compareAgainst_contigs));
$total_computations++;
print JOBS join("\t",
$nodeID, # the node we're attaching new species todo
$reduced_taxonomy->{$nodeID}{rank},
$node_computation->[0], # the node's immediate child we're taking the to-map-genome from
$reduced_taxonomy->{$node_computation->[0]}{rank},
$targetLeafID, # the node which we're now mapping against the genomes of the other children
$reduced_taxonomy->{$targetLeafID}{rank},
$targetLeaf_genomeSize,
scalar(@targetLeaf_compareAgainst),
join(";", @targetLeaf_compareAgainst),
$targetLeaf_compareAgainst_combinedSize,
join(";", @targetLeaf_contigs),
join(";", @compareAgainst_contigs),
join(';', sort keys %ranks_compareAgainst)
), "\n";
if(exists $templateDB_existingComputation_toJobID{$computation_key})
{
$total_computations_haveResult++;
my $template_jobI = $templateDB_existingComputation_toJobID{$computation_key};
my $existing_results_file = get_results_file_for_jobI_fromTemplateDB($template_jobI);
my $new_results_file = get_results_file_for_jobI($jobI);
copy($existing_results_file, $new_results_file) or die "Cannot copy $existing_results_file --> $new_results_file";
# print "Have 1:1 template for $computation_key - copy $existing_results_file --> $new_results_file \n"; # todo remove
}
else
{
die unless(exists $templateDB_A_to_B{$contigs_A});
my %alternativeI_to_distance;
for(my $alternativeI = 0; $alternativeI <= $#{$templateDB_A_to_B{$contigs_A}}; $alternativeI++)
{
my $alternative = $templateDB_A_to_B{$contigs_A}[$alternativeI][0];
next unless(all {exists $alternative->{$_}} @compareAgainst_contigs);
my $d = scalar(keys %$alternative) - scalar(@compareAgainst_contigs);
$alternativeI_to_distance{$alternativeI} = $d;
}
die unless(keys %alternativeI_to_distance);
my @sorted_alternative_Is = sort {$alternativeI_to_distance{$a} <=> $alternativeI_to_distance{$a}} keys %alternativeI_to_distance;
if(scalar(@sorted_alternative_Is) > 1)
{
die unless($alternativeI_to_distance{$sorted_alternative_Is[0]} <= $alternativeI_to_distance{$sorted_alternative_Is[1]});
}
my $best_template_idx = $sorted_alternative_Is[0];
my $best_template_jobI = $templateDB_A_to_B{$contigs_A}[$best_template_idx][1];
# print "Don't have 1:1 template for $computation_key \n";
# print "\tClosest existing computation: $best_template_jobI with distance $alternativeI_to_distance{$sorted_alternative_Is[0]}\n";
# print "\t\t", join(' ', @compareAgainst_contigs), "\n";
# print "\t\t", join(' ', keys %{$templateDB_A_to_B{$contigs_A}->[$best_template_idx][0]}), "\n\n";
# print "\t--mode doJobIFromTemplate --jobI $jobI --jobITemplate $best_template_jobI --DB $DB --templateDB $templateDB \n";
push(@missingData_computations, [$jobI, $best_template_jobI]);
}
}
}
close(JOBS);
print "\nTotal required computations: $total_computations / of which we have results for from template: $total_computations_haveResult\n";
print "\n";
foreach my $computation (@missingData_computations)
{
my $jobI = $computation->[0];
my $best_template_jobI = $computation->[1];
# print "Do \t--mode doJobIFromTemplate --jobI $jobI --jobITemplate $best_template_jobI --DB $DB --templateDB $templateDB \n";
doJobIFromTemplate($jobI, $best_template_jobI);
}
doCollect(1);
}
elsif($mode eq 'doJobIFromTemplate')
{
doJobIFromTemplate($jobI, $jobITemplate);
}
elsif($mode eq 'doJobI')
{
die "Please specify --jobI" unless(defined $jobI);
my ($A_taxonID, $B_taxonIDs, $contigs_A, $contigs_B) = get_job_info($outputFn_jobs, $jobI);
print "Job $jobI";
print "\tMapping from: $A_taxonID\n";
print "\tMapping to : $B_taxonIDs\n";
my @contigIDs_A = split(/;/, $contigs_A);
my @contigIDs_B = split(/;/, $contigs_B);
my %contigIDs_A_to_i = Util::get_index_hash(\@contigIDs_A);
my %contigIDs_B_to_i = Util::get_index_hash(\@contigIDs_B);
my $dir_computation = $outputDir_computation . '/' . $jobI;
mkdir($dir_computation);
my $file_A = $dir_computation . '/A';
my $file_B = $dir_computation . '/B';
construct_A_B_files($file_ref, $file_A, $file_B, \@contigIDs_A, \@contigIDs_B);
my $results_fn_reads_many = get_results_file_for_jobI($jobI);
my $readInfo_fn_reads_many = get_readInfo_file_for_jobI($jobI);
my $readResults_fn_reads_many = get_readResults_file_for_jobI($jobI);
my $seed_rand = rand(1024); # todo
srand($seed_rand);
open(READINFO, '>', $readInfo_fn_reads_many) or die "Cannot open $readInfo_fn_reads_many";
print READINFO $contigs_A, "\t", $contigs_B, "\n";
print READINFO join("\t", $readSimSizeFrom, $readSimSizeTo, $readSimSizeStep), "\n";
print READINFO $readSimDelta, "\n";
print READINFO $seed_rand, "\n";
open(READDETAILRESULTS, '>', $readResults_fn_reads_many) or die "Cannot open $readResults_fn_reads_many";
my $sub_call_each_simulatedRead = sub {
my ($readID, $contigID, $posI, $chunkLength) = @_;
my $contigI = $contigIDs_A_to_i{$contigID};
die unless(defined $contigI);
print READINFO $contigI, "\t", $posI, "\n";
};
my $sub_call_each_readResult = sub {
my ($readID, $bestContig, $bestIdentity) = @_;
my $bestContig_index = $contigIDs_B_to_i{$bestContig};
die unless(defined $bestContig_index);
print READDETAILRESULTS join("\t", $readID, $bestContig_index, $bestIdentity), "\n";
};
my $identities_by_length_href = {};
map_reads_keepTrack_similarity(
$file_A,
$file_B,
$dir_computation,
$seed_rand,
\@contigIDs_A,
undef,
$sub_call_each_simulatedRead,
$sub_call_each_readResult,
$identities_by_length_href
);
open(RESULTS, '>', $results_fn_reads_many) or die "Cannot open $results_fn_reads_many";
print RESULTS $contigs_A, "\t", $contigs_B, "\n";
foreach my $chunkLength (sort {$a <=> $b} keys %$identities_by_length_href)
{
foreach my $k (sort {$a <=> $b} keys %{$identities_by_length_href->{$chunkLength}})
{
print RESULTS join("\t", $chunkLength, $k, $identities_by_length_href->{$chunkLength}{$k}), "\n";
}
}
close(RESULTS);
print "--------\nJob $jobI done. Produced $results_fn_reads_many.\n";
close(READDETAILRESULTS);
close(READINFO);
}
elsif($mode eq 'collect')
{
doCollect();
}
else
{
die "Unknown mode";
}
sub map_reads_keepTrack_similarity
{
my $file_A = shift;
my $file_B = shift;
my $tmpDir = shift;
my $v_for_srand = shift;
my $contigs_A_order = shift;
my $limitToReadsIDs = shift;
my $call_eachSimulatedRead = shift;
my $call_eachReadResult = shift;
my $readCounts_toPopulate_href = shift;
die unless(defined $v_for_srand);
die unless(defined $readCounts_toPopulate_href);
my $A_contigs_href = Util::readFASTA($file_A);
my $file_A_reads_many = $tmpDir . '/A.reads.many';
my $outputFn_MetaMap = $tmpDir . '/MetaMap.many';
my %readID_2_chunkLength;
my %readCounts_toPopulate_local;
my $useClassicalMashmap = 0;
my $processAndClearReads = sub {
my $chunkLength = shift;
die unless(defined $chunkLength);
close(READS) or die;
my $mapping_cmd = qq($metamap_bin mapDirectly -r $file_B -q $file_A_reads_many -m $chunkLength -o $outputFn_MetaMap --pi 80);
if($useClassicalMashmap)
{
die unless(-e $classical_mashmap_bin);
$mapping_cmd = qq($classical_mashmap_bin mapDirectly -s $file_B -q $file_A_reads_many -m $chunkLength -o $outputFn_MetaMap --pi 80);
}
print "\t\tExecute command $mapping_cmd\n";
system($mapping_cmd) and die "MetaMap command $mapping_cmd failed";
my $currentReadID = '';
my @currentReadLines;
my $processAlignments_oneRead = sub {
my $bestIdentity;
my $bestIdentity_which;
my $readID;
foreach my $line (@currentReadLines)
{
my @fields = split(/ /, $line);
die Dumper($fields[0], $currentReadID) unless($fields[0] eq $currentReadID);
if(not defined $readID)
{
$readID = $fields[0];
}
else
{
die unless($readID eq $fields[0]);
}
my $targetContig = $fields[5];
my $identity = $fields[9];
die unless(($identity >= 0) and ($identity <= 100));
if((not defined $bestIdentity) or ($bestIdentity < $identity))
{
$bestIdentity = $identity;
$bestIdentity_which = $targetContig;
}
}
$bestIdentity = int($bestIdentity + 0.5);
die unless(defined $readID_2_chunkLength{$readID});
my $chunkLength = $readID_2_chunkLength{$readID};
$readCounts_toPopulate_local{$chunkLength}{$bestIdentity}++;
if($call_eachReadResult)
{
$call_eachReadResult->($readID, $bestIdentity_which, $bestIdentity);
}
};
open(MetaMapOUTPUT, '<', $outputFn_MetaMap) or die "Cannot open $outputFn_MetaMap";
while(<MetaMapOUTPUT>)
{
chomp;
next unless($_);
die "Weird input" unless($_ =~ /^(.+?) /);
my $readID = $1;
if($currentReadID ne $readID)
{
if(@currentReadLines)
{
$processAlignments_oneRead->();
}
$currentReadID = $readID;
@currentReadLines = ();
}
push(@currentReadLines, $_);
}
if(@currentReadLines)
{
$processAlignments_oneRead->();
}
close(MetaMapOUTPUT) or die;
open(READS, '>', $file_A_reads_many) or die "Cannot open $file_A_reads_many";
};
my %generated_reads_chunkLength;
my @chunk_positions = getChunkPositions($file_A, $contigs_A_order, $v_for_srand);
# print Dumper(@chunk_positions[0 .. 2]);
# ;
my $actually_map_reads = 0;
foreach my $oneChunk (@chunk_positions)
{
my $readID = $oneChunk->[4];
if(defined $limitToReadsIDs)
{
next unless($limitToReadsIDs->{$readID});
}
$actually_map_reads++;
}
my $splitByReadLength = 1;
if($splitByReadLength)
{
my %chunks_by_length;
my $generatedSequence = 0;
foreach my $oneChunk (@chunk_positions)
{
my $chunkLength = $oneChunk->[0];
push(@{$chunks_by_length{$chunkLength}}, $oneChunk);
}
open(READS, '>', $file_A_reads_many) or die "Cannot open $file_A_reads_many";
foreach my $oneChunk (@chunk_positions)
{
my $chunkLength = $oneChunk->[0];
my $readI_within_chunkLength_1based = $oneChunk->[1];
my $contigID = $oneChunk->[2];
my $posI = $oneChunk->[3];
my $readID = $oneChunk->[4];
if(defined $limitToReadsIDs)
{
next unless($limitToReadsIDs->{$readID});
}
if(defined $call_eachSimulatedRead)
{
$call_eachSimulatedRead->($readID, $contigID, $posI, $chunkLength);
}
}
my $totalChunkI = 0;
foreach my $chunkLength (keys %chunks_by_length)
{
my @chunks_thisLength = @{$chunks_by_length{$chunkLength}};
foreach my $oneChunk (@chunks_thisLength)
{
my $chunkLength = $oneChunk->[0];
my $readI_within_chunkLength_1based = $oneChunk->[1];
my $contigID = $oneChunk->[2];
my $posI = $oneChunk->[3];
my $readID = $oneChunk->[4];
$totalChunkI++;
# todo
# if($totalChunkI <= 3)
# {
# print "CHUNK $totalChunkI posI: $posI\n";
# print Dumper($oneChunk), "\n";
# }
# else
# {
# exit;
# }
if(defined $limitToReadsIDs)
{
next unless($limitToReadsIDs->{$readID});
}
if(defined $call_eachSimulatedRead)
{
$call_eachSimulatedRead->($readID, $contigID, $posI, $chunkLength);
}
die unless(defined $A_contigs_href->{$contigID});
my $S = substr($A_contigs_href->{$contigID}, $posI, $chunkLength);
die unless(length($S) == $chunkLength);
print READS '>', $readID, "\n";
print READS $S, "\n";
$generated_reads_chunkLength{$chunkLength}++;
$readID_2_chunkLength{$readID} = $chunkLength;
$generatedSequence += length($chunkLength);
}
$processAndClearReads->($chunkLength);
}
close(READS);
}
else
{
open(READS, '>', $file_A_reads_many) or die "Cannot open $file_A_reads_many";
my $generatedSequence = 0;
foreach my $oneChunk (@chunk_positions)
{
my $chunkLength = $oneChunk->[0];
my $readI_within_chunkLength_1based = $oneChunk->[1];
my $contigID = $oneChunk->[2];
my $posI = $oneChunk->[3];
my $readID = $oneChunk->[4];
if(defined $limitToReadsIDs)
{
next unless($limitToReadsIDs->{$readID});
}
if(defined $call_eachSimulatedRead)
{
$call_eachSimulatedRead->($readID, $contigID, $posI, $chunkLength);
}
die unless(defined $A_contigs_href->{$contigID});
my $S = substr($A_contigs_href->{$contigID}, $posI, $chunkLength);
die unless(length($S) == $chunkLength);
print READS '>', $readID, "\n";
print READS $S, "\n";
$generated_reads_chunkLength{$chunkLength}++;
$readID_2_chunkLength{$readID} = $chunkLength;
$generatedSequence += length($chunkLength);
if($generatedSequence >= 1e9)
{
$processAndClearReads->(2000);
$generatedSequence = 0;
}
}
$processAndClearReads->(2000);
close(READS);
}
print "\t\tReads file $file_A_reads_many with ", (sum(values %generated_reads_chunkLength) // 0), " reads\n\n";
foreach my $chunkLength (keys %generated_reads_chunkLength)
{
my $reads_for_mapping = $generated_reads_chunkLength{$chunkLength};
my $n_read_alignments = 0;
if(exists $readCounts_toPopulate_local{$chunkLength})
{
$n_read_alignments = sum values %{$readCounts_toPopulate_local{$chunkLength}};
}
my $n_missing_reads = $reads_for_mapping - $n_read_alignments;
die Dumper("Problem missing reads", $reads_for_mapping, $n_read_alignments) unless($n_missing_reads >= 0);
$readCounts_toPopulate_local{$chunkLength}{0} += $n_missing_reads;
}
foreach my $chunkLength (keys %readCounts_toPopulate_local)
{
foreach my $idty (keys %{$readCounts_toPopulate_local{$chunkLength}})
{
my $count = $readCounts_toPopulate_local{$chunkLength}{$idty};
$readCounts_toPopulate_href->{$chunkLength}{$idty} += $count;
}
}
system('rm ' . $tmpDir . '/*') and die "Cannot delete $tmpDir (I)";
system('rm -r ' . $tmpDir) and die "Cannot delete $tmpDir (II)"
}
sub getChunkPositions
{
my $file_A = shift;
my $contigs_A_order = shift;
my $srand_value = shift;
my $A_contigs_href = Util::readFASTA($file_A);
# todo
srand(length(join(';', @$contigs_A_order)));
# srand($srand_value);
my @forReturn;
my $totalReadI = 0;
for(my $chunkLength = $readSimSizeFrom; $chunkLength <= $readSimSizeTo; $chunkLength += $readSimSizeStep)
{
my $read_start_positions = 0;
die unless(scalar(keys %$A_contigs_href) == scalar(@$contigs_A_order));
foreach my $contigID (@$contigs_A_order)
{
my $contigSequence = $A_contigs_href->{$contigID};
die unless(defined $contigSequence);
for(my $posI = 0; $posI < length($contigSequence); $posI += $readSimDelta)
{
my $lastPos = $posI + $chunkLength - 1;
if($lastPos < length($contigSequence))
{
$read_start_positions++;
}
}
}
# todo
# print Dumper("Contigs: " . length(join(';', @$contigs_A_order)), $chunkLength, $read_start_positions);
my $start_rate = 1;
if($read_start_positions > $target_max_simulatedChunks)
{
$start_rate = $target_max_simulatedChunks / $read_start_positions;
# print "\t\t\t(Read lengths; $chunkLength) Adjusted start rate to $start_rate (eligible start positions: $read_start_positions, want $target_max_simulatedChunks)\n";
}
die unless(($start_rate >= 0) and ($start_rate <= 1));
my $readI_with_chunkLength = 0;
for(my $contigI = 0; $contigI <= $#{$contigs_A_order}; $contigI++)
{
my $contigID = $contigs_A_order->[$contigI];
my $contigSequence = $A_contigs_href->{$contigID};
POS: for(my $posI = 0; $posI < length($contigSequence); $posI += $readSimDelta)
{
my $lastPos = $posI + $chunkLength - 1;
if($lastPos < length($contigSequence))
{
if($start_rate != 1)
{
next POS if(rand(1) > $start_rate);
}
$readI_with_chunkLength++;
$totalReadI++;
my $readID = 'read' . $totalReadI;
push(@forReturn, [$chunkLength, $readI_with_chunkLength, $contigID, $posI, $readID]);
}
}
}
}
return @forReturn;
}
sub doJobIFromTemplate
{
my $jobI = shift;
my $jobITemplate = shift;
# todo
# return unless($jobI == 15);
print "Carying out job $jobI (DB $DB) based on template $jobITemplate ($templateDB)\n";
die "Please specify --jobI" unless(defined $jobI);
die "Please specify --jobITemplate" unless(defined $jobITemplate);
my ($A_taxonID, $B_taxonIDs, $contigs_A, $contigs_B) = get_job_info($outputFn_jobs_fromTemplate, $jobI);
my ($template_A_taxonID, $template_B_taxonIDs, $template_contigs_A, $template_contigs_B) = get_job_info($outputFn_jobs_inTemplateDir, $jobITemplate);
my @template_contigIDs_A = split(/;/, $template_contigs_A);
my @template_contigIDs_B = split(/;/, $template_contigs_B);
my %template_contigIDs_A_to_i = Util::get_index_hash(\@template_contigIDs_A);
my %template_contigIDs_B_to_i = Util::get_index_hash(\@template_contigIDs_B);
my %template_A_i_to_contigID = reverse %template_contigIDs_A_to_i;
my %template_B_i_to_contigID = reverse %template_contigIDs_B_to_i;
unless($contigs_A eq $template_contigs_A)
{
die "File $jobITemplate is not a valid template for job $jobI -- expect contigs_A = $contigs_A, but got $template_contigs_A";
}
my @contigIDs_A = split(/;/, $contigs_A);
my @contigIDs_B = split(/;/, $contigs_B);
my %contigs_A = map {$_ => 1} @contigIDs_A; die unless(scalar(keys %contigs_A));
my %contigs_B = map {$_ => 1} @contigIDs_B; die unless(scalar(keys %contigs_B));
my %contigIDs_A_to_i = Util::get_index_hash(\@contigIDs_A);
my %contigIDs_B_to_i = Util::get_index_hash(\@contigIDs_B);
foreach my $contigID (@contigIDs_B)
{
die Dumper("Invalid template $jobITemplate for job $jobI - mapping target (B) $contigID is not in list of template mapping targets", \@template_contigIDs_B) unless(exists $template_contigIDs_B_to_i{$contigID});
}
my ($_tmp_A, $_tmp_B, $v_for_srand, $readPositions_aref) = check_readsInfo_compatible_and_get_contigsA_contigsB_srand_readPositions(get_readInfo_file_for_jobI_fromTemplateDB($jobITemplate));
die Dumper("A contig discrepancy", $_tmp_A, $contigs_A) unless($_tmp_A eq $contigs_A);
die Dumper("B contig discrepancy", $_tmp_B, $template_contigs_B) unless($_tmp_B eq $template_contigs_B);
# get reads, and read info
my $dir_computation = $outputDir_computation . '/' . $jobI;
mkdir($dir_computation);
my $file_A = $dir_computation . '/A';
my $file_B = $dir_computation . '/B';
construct_A_B_files($file_ref, $file_A, $file_B, \@contigIDs_A, \@contigIDs_B);
my %n_reads_per_chunkLength;
my %readID_2_info;
my @chunk_positions = getChunkPositions($file_A, \@contigIDs_A, $v_for_srand);
# todo remove
# my @chunk_positions_2 = getChunkPositions($file_A, \@contigIDs_A, $v_for_srand);
# todo
# print Dumper(@chunk_positions[0 .. 2]);
my $readI = -1;
foreach my $oneChunk (@chunk_positions)
{
my $chunkLength = $oneChunk->[0];
my $readI_within_chunkLength_1based = $oneChunk->[1];
my $contigID = $oneChunk->[2];
my $posI = $oneChunk->[3];
my $readID = $oneChunk->[4];
$n_reads_per_chunkLength{$chunkLength}++;
die if(defined $readID_2_info{$readID});
$readID_2_info{$readID} = $oneChunk;
$readI++;
# todo remove
# my $contigID_supposed = $template_A_i_to_contigID{$readPositions_aref->[$readI][0]};
# print Dumper([$contigID, [$posI, $chunk_positions_2[$readI][3]]], [$readPositions_aref->[$readI][0], $contigID_supposed, $readPositions_aref->[$readI][1]], $contigs_A, $template_contigs_A), "\n";
if(defined $readPositions_aref)
{
die Dumper("Discrepancy read $readI", $jobI, $jobITemplate, $oneChunk, $readPositions_aref->[$readI][1], $readPositions_aref->[$readI], $outputFn_jobs_fromTemplate, $outputFn_jobs_inTemplateDir, get_readInfo_file_for_jobI_fromTemplateDB($jobITemplate)) unless($posI == $readPositions_aref->[$readI][1]);
die Dumper("Discrepancy", $posI, $readPositions_aref->[$readI][1], $readPositions_aref->[$readI], $jobI, $jobITemplate, $v_for_srand, [@chunk_positions[0 .. 10]], $readPositions_aref) unless($posI == $readPositions_aref->[$readI][1]);
}
else
{
die; # todo
}
}
# find reads that need to be remapped, and fill histogram with non-remapped reads
my %reads_for_remapping;
my $identities_by_length_href = {};
{
my $fn_mappings_details = get_readResults_file_for_jobI_fromTemplateDB($jobITemplate);
open(F, '<', $fn_mappings_details) or die "Cannot open $fn_mappings_details";
while(<F>)
{
chomp;
next unless($_);
my @f = split(/\t/, $_);
die Dumper("Weird line in $fn_mappings_details", $_) unless(scalar(@f) == 3);
my $readID = $f[0];
my $contigI = $f[1];
my $bestIdentity = $f[2];
my $contigID = $template_B_i_to_contigID{$contigI};
die Dumper("Unknown contigI $contigI", $fn_mappings_details, $., $_) unless(defined $contigID);
die unless(defined $readID_2_info{$readID});
if(exists $contigIDs_B_to_i{$contigID})
{
my $chunkLength = $readID_2_info{$readID}[0];
$identities_by_length_href->{$chunkLength}{$bestIdentity}++;
}
else
{
$reads_for_remapping{$readID} = 1;
}
}
close(F);
}
my $sub_call_each_simulatedRead = sub {
my ($readID, $contigID, $posI, $chunkLength) = @_;
if($readPositions_aref)
{
die unless($readID =~ /read(\d+)/);
my $readI = $1 - 1;
die "Weird readI $readI $readID" unless($readI >= 0);
die "Weird readI $readI $readID " . scalar(@$readPositions_aref) unless($readI < scalar(@$readPositions_aref));
my $contigI = $contigIDs_A_to_i{$contigID};
my $contigII = $template_contigIDs_A_to_i{$contigID};
die unless($contigI == $contigII);
die unless($readPositions_aref->[$readI][0] == $contigI);
die Dumper("Mismatch in generated reads", [$readID, $contigID, $contigI, $posI, $chunkLength], $readPositions_aref->[$readI], $v_for_srand) unless($readPositions_aref->[$readI][1] == $posI);
}
};
my $sub_call_each_readResult = sub {
};
print "\tNow remapping ", scalar(keys %reads_for_remapping), " / ", scalar(@chunk_positions), " genome chunks.\n";
map_reads_keepTrack_similarity(
$file_A,
$file_B,
$dir_computation,
$v_for_srand,
\@contigIDs_A,
\%reads_for_remapping,
$sub_call_each_simulatedRead,