File: filter.pl

package info (click to toggle)
murasaki 1.68.6-6
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,928 kB
  • ctags: 3,100
  • sloc: cpp: 16,010; perl: 8,365; makefile: 186
file content (1743 lines) | stat: -rwxr-xr-x 55,969 bytes parent folder | download | duplicates (4)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
#!/usr/bin/perl

#Copyright (C) 2006-2008 Keio University
#(Kris Popendorf) <comp@bio.keio.ac.jp> (2006)
#
#This file is part of Murasaki.
#
#Murasaki is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#Murasaki is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with Murasaki.  If not, see <http://www.gnu.org/licenses/>.

use Getopt::Long;
use Pod::Usage;
use File::Basename;
use IO::Handle;
#use Data::Dump qw {dump};
#use Math::BigRat;
no Carp::Assert;

use strict;

#open(DEBUG,">-");

BEGIN {
  unshift(@INC,(fileparse($0))[1].'perlmodules');
}
use Murasaki;
use Murasaki::KOG;
use Murasaki::OrthoList;
use Murasaki::OrthoPairs;
use Murasaki::OrthoConsistency;

my $tentative=1;
my (@seqlen);
my ($help,$man,%min,%max,$fwd,$rev,$noDetails,@plotWhat,$bins,%plotopts,$showall,$noTags,$bwPlot,$noImaginaryExtend,$noQuick,$kogfile,$widen,$randomWiden,$statDump,@dumpStats,$anchorFormat,$opt_pdf,$opt_pointsize,$opt_lwd,$opt_roclegendpos);
my ($rocrTarget)='ortholog';
my @validRocrTargets=qw{ortholog paralog tagged miss};
my (@rocrWhat,$seqCount);
my @rocrPlot=qw{tpr,fpr};
my @rocrEval=qw{auc};
our @knownKogs=(Murasaki::KOG->knownKogs,Murasaki::KOG->knownCogs); #they're identical for all i care
our $infh={}; #global filepointer handler
our ($knownKogs,$expKogs,@kogmap,$statsPass,%knownLocs,$knownOList,$expOList,$knownOPairs,$expOPairs,$knownOCons,$expOCons);
my ($useOCons,$useOPairs,$useOList,$useKogs)=(1,1,1,1);
our @reservedTypes=qw{label all}; #dont get printed/plotted or always available. hidden
our @mixPlotableTypes=qw{bitscore length tfitf tfidf hits cds score bitrate homology};
our @annotationTypes=qw{cds}; #data that comes from annotation, ie: cheating
our @defaultRocrTypes=grep {my $a=$_; grep {$a ne $_} @annotationTypes} @mixPlotableTypes;
our @kogTypes=qw{kogtp kogfp oltp olfp};
our @alignTypes=qw{miss untagged distant paralog ortholog};
our @allStatTypes=(@mixPlotableTypes,@alignTypes,@kogTypes);
our @statTypes=@allStatTypes;
our %kogpref;
our %statreqs=(etfidf => sub{!$noDetails},
	       tfitf => sub{!$noDetails},
	       ortholog => sub{!$noTags},
	       miss => sub{!$noTags},
	       distant => sub{!$noTags},
	       paralog => sub{!$noTags},
	       untagged => sub{!$noTags},
	       cds => sub{!$noTags},
	       bitscore => sub{$tentative || $infh->{bitscore}},
	       bitrate => sub{$tentative || $infh->{bitscore}},
	       homology => sub{$tentative || $infh->{homology}},
	       kogtp => sub{$kogfile},
	       kogfp => sub{$kogfile},
	       score => sub{$anchorFormat>1},
	       hits => sub{$anchorFormat>0}
	      );
our %userStats;
our %externalStats; #statname -> infh name
our $searcher=\&binarySearch;
resetStatTypes();
$bins=100;
$showall='scale';

our $podusageOpts={-message=>'Use --help or --man for more detailed help.',-verbose => 0,-exitval=>2};

my $opterr=
  GetOptions('help|?' => \$help, man => \$man,
	     'lwd=f'=>\$opt_lwd,'pointsize=f'=>\$opt_pointsize,
	     'roclegendpos=s'=>\$opt_roclegendpos,
	     'min=s%' => sub {
	       pod2usage({%$podusageOpts,-msg=>"Syntax error: $_[0] $_[1]=$_[2]\n"}) unless ($_[1] and $_[2]);
#	       pod2usage({%$podusageOpts,-msg=>"Unknown stat: $_[1]\n"}) unless(grep {$_[1] eq $_} @statTypes);
	       $min{$_[1]}=$_[2];
	     },
	     'max=s%' => sub {
	       pod2usage({%$podusageOpts,-msg=>"Syntax error: $_[0] $_[1]=$_[2]\n"}) unless ($_[1] and $_[2]);
#	       pod2usage({%$podusageOpts,-msg=>"Unknown stat: $_[1]\n"}) unless grep {$_[1] eq $_} @statTypes;
	       $max{$_[1]}=$_[2];
	     },
	     'def=s%' => sub {
	       pod2usage({%$podusageOpts,-msg=>"Syntax error: $_[0] $_[1]=$_[2]\n"})  unless $_[1] and $_[2];
	       pod2usage({%$podusageOpts,-msg=>"Cannot redefine existing stats: $_[1]\n"}) if grep {$_[1] eq $_} @statTypes;
	       pod2usage({%$podusageOpts,-msg=>"Cannot $_[1] is a reserved type, sorry.\n"}) if grep {$_[1] eq $_} @reservedTypes;
	       $userStats{$_[1]}=userStatFun(@_);
	       addStat($_[1]);
	       my $func="sub {" . join(" && ",(map {"statReqsOk('$_')"} statReqs(@_)))."}";
	       $statreqs{$_[1]}=eval($func);
	     },
	     'minscore=s' => \$min{score}, 'maxscore=s' => \$max{score},
	     'minlength=s' => \$min{length}, 'maxlength=s' => \$max{length},
	     'mintfidf=s' => \$min{tfidf}, 'maxtfidf=s' => \$max{tfidf},
	     'minhits=s' => \$min{hits}, 'maxhits=s' => \$max{hits},
	     fwd => \$fwd, rev => \$rev,
	     details => sub{$noDetails=0;resetStatTypes()},
	     nodetails => sub{$noDetails=1;resetStatTypes()},
	     'plot:s' => sub {
	       @plotWhat=parseStatTypeList($_[1] ? $_[1]:'all')},
	     'bins=i' => \$bins,
	     'nobins' => sub {$bins=0},
	     'plotopts:s%' => sub {
	       my ($type,$target,$data)=('all',$_[1],$_[2] ? $_[2]:1);
	       ($type,$target)=($1,$2) if($_[1]=~m/(\w+)\.(\w+)/);
	       my @targets=parseStatTypeList($type);
	       foreach my $t (@targets){
		 ${$plotopts{$t}}{$target}=$data;
		 #	       print "Setting $t.$target = $data\n";
	       }
	     },
	     'color' => sub {$bwPlot=0},
	     'bw' => \$bwPlot,
	     'tags' => sub {$noTags=0;resetStatTypes()},
	     'notags' => sub {$noTags=1;resetStatTypes()},
	     'showall:s' => sub {$showall=0;$showall=$_[1] if $_[1]},
	     'noextend' => \$noImaginaryExtend,
	     'all' => \$noQuick,
	     'quick' => sub {$noQuick=0},
	     'kogfile=s' => sub {$kogfile=$_[1];resetStatTypes()},
	     'kog=s%' => sub {pod2usage({%$podusageOpts,-msg=>"Need values for --kog $_[1]=$_[2] (lhs and rhs!)"})
				unless(defined $_[1] and $_[2]);
			      pod2usage({%$podusageOpts,-msg=>"Bad --kog $_[1]= (lhs)"})
				unless(defined $_[1] and $_[2] and $_[1]>=0);
			      pod2usage({%$podusageOpts,-msg=>"Bad --kog $_[1]=$_[2] (rhs)"})
				unless(defined $_[1] and $_[2] and $_[1]>=0 and $_[2]);
			      my $newname=scalar(Murasaki::KOG->guessKogMember($_[2]));
			      $kogmap[$_[1]]=$newname ? $newname:$_[2]},
	     'widen=i' => \$widen,
	     'randomwiden=i' => \$randomWiden,
	     'statdump' => \$statDump,
	     'dumpstats=s' => sub{@dumpStats=parseStatTypeList($_[1] ? $_[1]:'all',\@defaultRocrTypes)},
	     'ROCR|rocr:s' => sub{pod2usage({%$podusageOpts,-msg=>"ROCR requires kog support (make sure --kogfile comes before --rocr)"})
				    unless $kogfile;
				  @rocrWhat=parseStatTypeList($_[1] ? $_[1]:'all',\@defaultRocrTypes)},
	     'rocreval=s' => sub{push(@rocrEval,$_[1])},
	     'rocrplot=s' => sub{push(@rocrPlot,$_[1])},
	     'rocrtarget=s' => sub{pod2usage({%$podusageOpts,-msg=>"Unknown rocrtarget: $_[1]"}) unless
				     grep {$_ eq $_[1]} @validRocrTargets;
				   $rocrTarget=$_[1]},
	     'linear' => sub{$searcher=\&linearSearch},
	     'pdf' => \$opt_pdf,
	     'kogpref=s%' => \%kogpref,
	     'usekogs!'=>\$useKogs,
	     'useolist!'=>\$useOList,
	     'useopairs!'=>\$useOPairs,
	     'useocons!'=>\$useOCons
	    );
pod2usage(-exitstatus => 0, -verbose => 2) if $man;
pod2usage(-exitstatus => 0, -verbose => 99, -section=>"SYNOPSIS|OPTIONS|DESCRIPTION") if $help;
pod2usage($podusageOpts) if $#ARGV<0 or !$opterr;


sub addStat {
  my ($stat)=@_;
  push(@allStatTypes,$stat);
  push(@statTypes,$stat);
  push(@defaultRocrTypes,$stat);
  push(@mixPlotableTypes,$stat);
}

sub statReqsOk {
  local $_=pop;
  my $subres;
  $subres=&{$statreqs{$_}} if $statreqs{$_};
  return ($subres || !$statreqs{$_});
}
sub resetStatTypes {
#must amend @statTypes if user disabled some of them
  @statTypes=grep {statReqsOk($_)} @allStatTypes; #how can you not love perl?
  @plotWhat=grep {statReqsOk($_)} @plotWhat;
  @rocrWhat=grep {statReqsOk($_)} @rocrWhat; #how can you not love perl?
}

our $screenwidth=$ENV{COLUMNS};
$screenwidth=75 unless $screenwidth>0;
my ($inf,$outf)=@ARGV;
open(STDOUT,"|tee $inf.filterstats"); #log output!

our $basepath=getPath($inf);
our $basename=(fileparse($inf,qr{\.anchors\.details?|\.anchors}))[0];
our $basefile=getPath($inf).$basename;
#my $hash_inf="$basefile.histogram.details";

open($infh->{anchors},"$inf") or die "Can't open $inf for input";
open($infh->{bitscore},"$basefile.anchors.bitscore") or delete($inf->{bitscore}) if -f "$basefile.anchors.bitscore";
open($infh->{homology},"$basefile.homology") or delete($inf->{homology}) if -f "$basefile.homology";
do{print "Bitscore data found.\n"} if exists $infh->{bitscore};
do{print "Homology data found.\n"} if exists $infh->{homology};
foreach my $statFile (<$inf.stats.*>){
  open(my $fh,$statFile) or next;
  my ($statName)=$statFile=~m/\.stats\.(.*)$/;
  next unless $statName;
  print "Found external stat ($statName) file: $statFile\n";
  if(exists $infh->{$statName} or (grep {$_ eq $statName} @statTypes)){
    print "$statName conflicts with existing stat. Ignoring.\n";
    next;
  }
  $infh->{$statName}=$fh;
  addStat($statName);
  $externalStats{$statName}=$statName;
}
#our @hashCount=loadHistogramDetails($hash_inf) if -e $hash_inf and !$noDetails;
$anchorFormat=anchorFormat($infh->{anchors});
do {print "Disabling 'details' due to insufficient detail in anchors.details file.\n";
    $noDetails=1} unless $anchorFormat>2 or $noDetails;

resetStatTypes();
@plotWhat=split(/,/,join(',',@plotWhat));
@plotWhat=@statTypes if grep {$_ eq 'all'} @plotWhat;
our (@hashCount,@docCount,@seqcds,%commonNames,@usedNames,%namecon); #data used while running statistics
our $annotation;
our $anchorCount=lineCount($infh->{anchors});
reverseDetails($inf) unless $noDetails;
print "Assuming sequence file: $basefile.seqs\n";
setupKogmap("$basefile.seqs") if $kogfile;
getTags("$basefile.seqs") unless $noTags;
setupKogs("$basefile.seqs") if $kogfile;
getLens("$basefile.seqs") if $randomWiden;
$tentative=0; #major inits done...
resetStatTypes();

#make sure each min/max actually has supporting stats
foreach my $req (\%max,\%min){
  foreach my $k (keys %$req){
    do {
      warn "Requisite stats not found for: $k ($req->{$k})" if $req->{$k};
      delete $req->{$k}
    } unless grep {$k eq $_} @statTypes;
  }
}
#can't dump stats for which we're also reading from their file
@dumpStats=grep {!exists $externalStats{$_}} @dumpStats;

my %userReqs;
%userReqs=statReplace(\%max,{},"max","preview");
hashSum(\%userReqs,{statReplace(\%min,{},"min","preview")});

#Gather stats!
my $prestats=gatherStats($infh,"Initial stats:\n",0,$anchorCount);

%userReqs=statReplace(\%max,$prestats,"max");
hashSum(\%userReqs,{statReplace(\%min,$prestats,"min")});
$userReqs{count}++ if $rev;
$userReqs{count}++ if $fwd;

if(!$userReqs{count}){
  print "No user requirements.\n";
  exit(0);
}

$outf=getPath($inf).getName(getName($inf)).".filtered" if !$outf and $inf=~m/.+\.anchors(?:\.details)?/;
die "Could not find an filename to use for output" unless $outf;
open(OUTF,">$outf") or die "Can't open $outf for output";
print "Writing output to $outf\n";

print "Filtering $anchorCount anchors....\n";
seekAll($infh,0,0);
resetTick();
my $keptCount=0;
my $anchor=0;
my @kept;
my $linedat;
LINE: while($linedat=readlineAll($infh)){
  tick();
  my %stats=getStats($linedat);
  chomp;
  my @vals=split(/\t/,$_);
  do{next unless grep {$_ eq "-"} @vals} if $rev;
  do{next unless grep {$_ eq "+"} @vals} if $fwd;
  foreach my $k (@statTypes){
    do{next LINE unless $min{$k}<=$stats{$k}} if defined($min{$k});
    do{next LINE unless $max{$k}>=$stats{$k}} if defined($max{$k});
  }
  $kept[$anchor]=1;
  $keptCount++;
  print OUTF join("\t",@vals[0..($seqCount*3-1)])."\n";
} continue { $anchor++; }
close(OUTF);
print "\n";

my $poststats=gatherStats($infh,"Retained value stats:\n",\@kept,$keptCount);

###end of main stuff###

sub avgLength {
  my $all=join("\t",@_);
  my @lens;
  while($all=~m/(-?\d+)\t(-?\d+)\t(.)/g){
    my $length=abs($2-$1+1);
    push(@lens,$length);
  }
  return 0 unless $#lens>=0;
  return mean(@lens);
}

sub sum {
  my $sum=0;
  grep {$sum+=$_} @_;
  return $sum;
}

sub mean {
  my $total;
  foreach(@_){
    $total+=$_;
  }
  return $total/($#_+1);
}

sub min {
  my $best=$_[0];
  foreach(@_){
    $best=$_ if $_<$best;
  }
  return $best;
}

sub max {
  my $best=$_[0];
  foreach(@_){
    $best=$_ if $_>$best;
  }
  return $best;
}

sub stddev {
  my $sumosqrs;
  my $s=mean(@_);
  foreach(@_){
    $_-=$s;
    $sumosqrs+=$_*$_;
  }
  return sqrt($sumosqrs);
}

sub getName {
  my @ret=map {
    my ($name,$path,$suffix) = fileparse($_, qr{\.[^.]*});
    $name
    } @_;
  return @ret if $#_;
  return $ret[0];
}

sub getPath {
  my @ret=map {
    my ($name,$path,$suffix) = fileparse($_, qr{\.[^.]*});
    $path
    } @_;
  return @ret if $#_;
  return $ret[0];
}

sub loadHistogramDetails {
  my $inf=pop;
  print "Loading histogram details from $inf.\n";
  my (@hashcount,$format);
  our $screenwidth;
  my $fh;
  open($fh,$inf) or die "Couldn't open $inf for reading";
  $_=<$fh>;
  $format=1 if m/^\d+:\d+$/;
  $format=2 if m/^\d+\s+[ACGT.]+\s+\d+$/;
  die "Unknown histogram details format...\n" unless $format;
  my $stats=lineCount($fh);
  $stats*=1;
  print "Histogram details is format: $format and has $stats lines\n";
  resetTick($stats,$screenwidth);
  seek($fh,0,0);
  my $moo;
  while(<$fh>){
    m/^(\d+):(\d+)$/ if $format=1;
    m/^(\d+)\s+[ACGT.]+\s+(\d+)$/ if $format=1;;
    $hashcount[$1]+=$2;
    tick();
  }
  print "\n";
  print "Histogram details loaded.\n";
  close($fh);
  return @hashcount;
}

sub reverseDetails {
  print "Deriving term index...\n";
  our ($anchorCount,@hashCount);
  resetTick();
  my $inf=pop;
  my ($infh);
  open($infh,$inf);
  while(<$infh>){
    my @vals=split(/\t/,$_);
    my @meta=@vals[($#vals-2)..$#vals];
    my ($hits,$score,$members)=@meta;
    foreach (split(/,/,$members)){
      my ($idx,$count)=m/(\d+):(\d+)/;
      $hashCount[$idx]+=$count;
      $docCount[$idx]++;
    }
    tick();
  }
  print "\n";
}

sub tfitf {
  my $wi;
  my $dat=pop;
  our (@hashCount,$anchorCount);
  foreach (split(/,/,$dat)){
    my ($idx,$count)=m/(\d+):(\d+)/;
    $wi+=$count*log($anchorCount/$hashCount[$idx]);
  }
  return $wi;
}

sub tfidf {
  my $wi;
  my $dat=pop;
  our (@hashCount,$anchorCount);
  foreach (split(/,/,$dat)){
    my ($idx,$count)=m/(\d+):(\d+)/;
    $wi+=$count*log($anchorCount/$docCount[$idx]);
  }
  return $wi;
}

sub resetTick {
  my ($total,$div)=@_;
  our ($anchorCount,$screenwidth);
  ($total,$div)=($anchorCount,$screenwidth) unless $total;
  our ($ticksper,$ticksleft)=(int($total/$div),int($total/$div));
  print "|",(map {"-"} (3..$div)),"|\n";
}

sub tick {
  our ($ticksper,$ticksleft);
  $ticksleft--;
  if(!$ticksleft){
    print STDOUT '.';
    STDOUT->flush();
    $ticksleft=$ticksper;
  }
}

sub getStats {
  my $dats=pop;
  $_=$dats->{anchors};
  my (%bitdata,%homdata,%kogorthos,%listOrthos,%pairOrthos,%consOrthos);
  my (%namealign,%namescores,@cds);
  if($dats->{bitscore}){
    my ($bitscore,$maxbits)=split(/\t/,$dats->{bitscore});
    %bitdata=(bitscore=>$bitscore,bitrate=>$bitscore/$maxbits);
  }
  if($dats->{homology}){
    my @homvals=split(/\t/,$dats->{homology});
    %homdata=(homology=>mean(@homvals));
  }
  my @vals=split(/\t/,$_);
  my $lastval=$anchorFormat>0 ? ($#vals-$anchorFormat):$#vals;
  my @meta=@vals[$lastval+1..$#vals];
  @vals=@vals[0..$lastval];
  my ($hits,$score,$members)=@meta;
  $hits=undef if $anchorFormat<1;
  ($score,$members)=(undef,undef) unless $anchorFormat>1; #only use @meta if there -is- meta
  my $length=avgLength(@vals);
  my $tfitf=tfitf($members) if $members && !$noDetails;
  my $tfidf=tfidf($members) if $members && !$noDetails;

  unless($noTags){
    @cds=findIncidentCDS(@vals);
    %namealign=nameComp(@cds);
    %namescores=hashHistogram(%namealign);
    %kogorthos=updateKogs($expKogs,@cds) if $expKogs;
    %listOrthos=updateOList($expOList,@cds) if $expOList;
    %pairOrthos=updateOPairs($expOPairs,@cds) if $expOPairs; #we don't construct new pair lists, just score old.
    %consOrthos=updateOPairs($expOCons,@cds) if $expOCons; #orthoCons work just like opairs so we can actually reuse the same func
    %namescores=(untagged=>1) unless %namescores; #if no tags, untagged!
  }
  
  my %stats=(length=>$length,
	     hits=>$hits,
	     score=>$score,
	     tfitf=>$tfitf,
	     tfidf=>$tfidf,
	     cds=>(scalar(values(%namealign))),
	     %namescores, #isnt perl spiffy?
	     %bitdata,%homdata,%kogorthos,%listOrthos,
	     %pairOrthos,
	     namealign=>\%namealign);

  foreach my $estat (keys %externalStats){
    $stats{$estat}=$dats->{$externalStats{$estat}};
  }

  foreach my $ustat (keys(%userStats)){
#    print "Run $ustat = ";
    $stats{$ustat}=&{$userStats{$ustat}}(%stats);
#    print "$stats{$ustat}\n";
  }
  return %stats;
}

sub updateOPairs {
  my ($olist,@cds)=@_;
  my @bits;
  for my $i (0..$#cds){
    next unless $kogmap[$i];
    my @locs=map {{$_->{locus}=>$kogmap[$i]}} (grep {$_->{locus}} @{$cds[$i]});
    push(@bits,\@locs);
  }
  my %res=$olist->hitAllKnown(@bits);
  return (opc=>$res{hits},opic=>$res{misses});
}

sub updateOList {
  my ($olist,@cds)=@_;
  my @bits;
  for my $i (0..$#cds){
    next unless $kogmap[$i];
    my @locs=map {{$_->{locus}=>$kogmap[$i]}} (grep {$_->{locus}} @{$cds[$i]});
    return unless @locs; #cant use if missing a locus in a genome
    push(@bits,\@locs);
  }
  $olist->addOrtho(@bits);
  my %res=$knownOList->isOrtho(@bits);
  return (oltp=>$res{yes},olfp=>$res{no});
}

sub updateKogs {
  my ($kogs,@cds)=@_;
  my @koggedbits=grep {$kogmap[$_]} (0..$#cds);
  my %res=(kogtp=>0,kogfp=>0);
  for my $i (@koggedbits){
    for my $j (@koggedbits){
      next if $i==$j;
      foreach my $l1 (map {$_->{locus}} @{$cds[$i]}){
	foreach my $l2 (map {$_->{locus}} @{$cds[$j]}){
	  #oh dear god, the combinatorial explosion of it!
	  $expKogs->add({$l1=>$kogmap[$i]},{$l2=>$kogmap[$j]}) if $statsPass<2; #only do this once
	  $res{($knownKogs->isOrtho($l1,$l2)) ? 'kogtp':'kogfp'}++;
	}
      }
    }
  }
  return %res;
}

sub hashHistogram {
  my (%hist,%in);
  %in=@_;
  foreach(values(%in)){
    $hist{$_}++;
  }
  return %hist;
}

sub seekAll {
  my ($fhr,$pos,$whence)=@_;
  foreach my $file (keys(%{$fhr})){
    seek($fhr->{$file},$pos,$whence);
  }
}

sub readlineAll {
  my ($fh)=(@_);
  my %res;
  my %failed;
  foreach my $key (keys(%$fh)){
    $res{$key}=readline($$fh{$key});
    $failed{$key}=1 unless $res{$key};
  }
  if(keys %failed){#if one file fails, fail all
    warn join(",",keys %failed)." file(s) ended before other files" unless keys(%failed)==keys(%res);
    return undef;
  }
  return \%res;
}

sub gatherStats {
  my ($fh,$subtitle,$kept,$input_count)=@_;
  our ($anchorCount);
  my ($anchor,$anchors)=(0,0);
  my (%sum,%avg,%variance,%stddev);
  my (%histo);
  my ($tp,$fp,$fn);
  @usedNames=();%namecon=();
  my %rocrUsedLabels;
  my $plotPhase=($subtitle=~m/initial/i ? 1:2);
  $expKogs=Murasaki::KOG->empty($plotPhase<2 ? "unfiltered experimental":"filtered experimental") if $knownKogs and $useKogs;
  $expOList=Murasaki::OrthoList->empty($plotPhase<2 ? "unfiltered experimental":"filtered experimental",\@kogmap,\%knownLocs) if $knownOList and $useOList;
  $expOPairs=Murasaki::OrthoPairs->clone($knownOPairs,$plotPhase<2 ? "unfiltered experimental":"filtered experimental",\@kogmap,\%knownLocs) if $knownOPairs and $useOPairs;
  $expOCons=Murasaki::OrthoConsistency->clone($knownOCons,$plotPhase<2 ? "unfiltered experimental":"filtered experimental",\@kogmap,\%knownLocs) if $knownOCons and $useOCons;
  my $prefix=$plotPhase<2 ? "":"filtered";
  my %outfhs;
  if($statDump){
    my $statdumpPath="$basefile.".($prefix ? "$prefix.":"")."stats";
    open($outfhs{statdump},'>',$statdumpPath) or die "Couldn't write to $statdumpPath";
    print "Dumping per-anchor stats to $statdumpPath\n";
    print {$outfhs{statdump}} join("\t",@statTypes),"\n";
  }
  foreach my $stat (@dumpStats){
    my $statdumpPath="$basefile.".($prefix ? "$prefix.":"")."filterstats.$stat";
    open($outfhs{"dump-$stat"},'>',$statdumpPath);
    print "Dumping per-anchor $stat stats to $statdumpPath\n";
  }
  my $rocrPath;
  if(@rocrWhat){
    $rocrPath="$basefile.".($prefix ? "$prefix.":"")."rocr";
    open($outfhs{rocr},'>',$rocrPath) or die "Couldn't write to $rocrPath";
    print {$outfhs{rocr}} join("\t","label",@rocrWhat),"\n";
  }

  my @business=qw{averages};
  push(@business,'histogram') if @plotWhat;
  push(@business,'classification') unless $noTags;
  push(@business,'KOGs') if $knownKogs;
  $statsPass=1;
  print "Analyzing $input_count anchors (phase 1: ".
    (join(", ",@business)).")\n";

  resetTick();
  seekAll($fh,0,0);
  my $linedat;
  while($linedat=readlineAll($fh)){
    next if($kept and !$$kept[$anchor]);
    my %stats=getStats($linedat);
    foreach my $k (@statTypes){
      next unless $stats{$k};
      my $kval=$stats{$k};
      $sum{$k}+=$kval;
      if(grep {$_ eq $k} @plotWhat){
	if($stats{cds}){ #has annotation data
	  foreach my $aligned (@alignTypes){
	    next unless $stats{$aligned};
	    ${$histo{$k}}{$kval}->{$aligned}+=$stats{$aligned}/$stats{cds}; #mmm fractional histograms
	  };
	}else{ #belongs to "unknown"
	  ${$histo{$k}}{$kval}->{untagged}++;
	}
      }
      if($stats{cds}){ #hit some annotation data
	my %aligned=%{$stats{namealign}};
	foreach my $name (keys(%aligned)){
	  $namecon{$name}->{$aligned{$name}}++;
	  ($aligned{$name} eq "miss" ? $fp:$tp)+=$stats{length}/scalar(keys(%aligned));
	}
      }else{
	$fp+=$stats{length};
      }
    }
    $anchors++;
    print {$outfhs{statdump}} join("\t",map {$stats{$_}} @statTypes),"\n" if $statDump;
    foreach my $stat (@dumpStats){
      print {$outfhs{"dump-$stat"}} $stats{$stat}."\n";
    }
    if(@rocrWhat){
      foreach my $label (rocrLabels(\%stats)){
	foreach my $stat (@rocrWhat){
	  ${$rocrUsedLabels{$stat}}[$label]=1;
	}
	print {$outfhs{rocr}} join("\t",$label,
				   map {$stats{$_}} @rocrWhat),"\n";
      }
    }
  } continue { $anchor++; tick();}


  my %imaginary=hitCdsSize();
  $fn=$imaginary{fn};
  $imaginary{fp}=$fp;
  print "\n";

  foreach my $k (@plotWhat){
    plotHistogram($histo{$k},$k,$plotPhase);
  }

  my $rocrRes=plotRocr($rocrPath,$plotPhase,
		      [grep {${$rocrUsedLabels{$_}}[0]
			    && ${$rocrUsedLabels{$_}}[1]} @rocrWhat]) if @rocrWhat;

  #averages
  foreach my $k (keys(%sum)){
    $avg{$k}=$sum{$k}/$anchors;
  }


  $statsPass=2;
  if($noQuick or $userReqs{s} or $userReqs{v}){
    print "Analyzing $input_count anchors (phase 2: stddev)\n";
    seekAll($fh,0,0);
    $anchor=0;
    resetTick();
    while($linedat=readlineAll($fh)){
      next if($kept and !$$kept[$anchor]);
      my %stats=getStats($linedat);
      foreach my $k (@statTypes){
	next unless $stats{$k};
	my $dif=$stats{$k}-$avg{$k};
	$variance{$k}+=$dif*$dif;
      }
    } continue { $anchor++ ; tick();}
    foreach my $k (keys(%variance)){
      $variance{$k}/=$anchors;
      $stddev{$k}=sqrt($variance{$k});
    }
  }else{
    print "Skipping Phase 2 (standard deviation/variation) as it's not necessary.\n";
  }
  seekAll($fh,0,0);

  my %kogres=$knownKogs->compare($expKogs) if $knownKogs and $expKogs;
  my %olres=$knownOList->compare($expOList) if $knownOList and $expOList;

  print "\n";
  print $subtitle if $subtitle;
  print "Total anchors: $anchors\n";
  foreach my $k (@statTypes){
    print "$k mean: $avg{$k}".($stddev{$k} ? " stddev $stddev{$k}":"")."\n";
  }

  print "ROCR derived predictor stats:\n$rocrRes" if $rocrRes;

  unless($noTags){
    print "CDS/".($knownKogs ? "KOG/Name":"Name")."-based Paralog ROC:\n";
    printf("Sensitivity: %s (with extend: %s)\n",
	   percent($tp,$tp+$fn),
	   percent($imaginary{tp},$imaginary{tp}+$imaginary{fn}));
      printf("Specificity: %s (with extend: %s)\n",
	     percent($tp,($tp+$fp)),
	     percent($imaginary{tp},$imaginary{tp}+$imaginary{fp}));
  }
  if($knownKogs and $expKogs){
    print "KOG-based Ortholog ROC:\n";
    print "Known KOGs: ".$knownKogs->summary."\n";
    print "Experimental KOGs: ".$expKogs->summary."\n";
    my %kogroc=(tp=>$kogres{inboth},fn=>$kogres{in1},fp=>$kogres{in2},tn=>$kogres{in0});
    print(join(" ",map {uc($_).": $kogroc{$_}"} qw{tp fp fn tn}),"\n");
    printf("Sensitivity: %s\n",
	   percent($kogroc{tp},$kogroc{tp}+$kogroc{fn}));
    printf("Specificity: %s\n",
	     percent($kogroc{tp},$kogroc{tp}+$kogroc{fp}));
    printf("Precision: %s\n",
	     percent($kogroc{tp}+$kogroc{tn},$kogroc{tp}+$kogroc{fp}+$kogroc{tn}+$kogroc{fn}));
    printf("MCC: %f\n",
	   (($kogroc{tp}*$kogroc{tn})/sqrt(($kogroc{tp}+$kogroc{fp})*
					   ($kogroc{tp}+$kogroc{fn})*
					   ($kogroc{tn}+$kogroc{fp})*
					   ($kogroc{tn}+$kogroc{fn}))))
      if (($kogroc{tp}+$kogroc{fp})* #no dividing by zero!
	  ($kogroc{tp}+$kogroc{fn})*
	  ($kogroc{tn}+$kogroc{fp})*
	  ($kogroc{tn}+$kogroc{fn}));
  }
  if($knownOList and $expOList){
    print "Non-transitive Ortholog ROC:\n";
    print "Known Orthos: ".$knownOList->summary."\n";
    print "Experimental Orthos: ".$expOList->summary."\n";
    my %olroc=(tp=>$olres{inboth},fn=>$olres{in1},fp=>$olres{in2},tn=>$olres{in0});
    print(join(" ",map {uc($_).": $olroc{$_}"} qw{tp fp fn tn}),"\n");
    printf("Sensitivity: %s\n",
	   percent($olroc{tp},$olroc{tp}+$olroc{fn}));
    printf("Specificity: %s\n",
	     percent($olroc{tp},$olroc{tp}+$olroc{fp}));
    printf("Precision: %s\n",
	     percent($olroc{tp}+$olroc{tn},$olroc{tp}+$olroc{fp}+$olroc{tn}+$olroc{fn}));
    printf("MCC: %f\n",
	     (($olroc{tp}*$olroc{tn})/sqrt(($olroc{tp}+$olroc{fp})*
					   ($olroc{tp}+$olroc{fn})*
					   ($olroc{tn}+$olroc{fp})*
					   ($olroc{tn}+$olroc{fn}))))
      if (($olroc{tp}+$olroc{fp})* #no dividing by zero!
	  ($olroc{tp}+$olroc{fn})*
	  ($olroc{tn}+$olroc{fp})*
	  ($olroc{tn}+$olroc{fn}));
  }
  if($knownOPairs and $expOPairs){
    print "Orhtolog-pair based statistics:\n";
    print "Known pairs: ".$knownOPairs->summary."\n";
    my %opres=($expOPairs->stats); #gives sens and spec
    assert(defined $opres{con});
    assert(defined $opres{incon});
    $opres{fscore}=(2*$opres{sens}*$opres{spec})/($opres{sens}+$opres{spec}) if ($opres{sens}+$opres{spec});
    local $,="\n";
    local $\="\n";
    print("Consistent: ".$opres{con},
	  "Inconsistent: ".$opres{incon},
	  "Recall: ".$opres{sens},
	  "Precision: ".$opres{spec},
	  "F-Score: ".$opres{fscore});
  }
  if($knownOCons and $expOCons){
    print "Orhtolog-constitency based statistics:\n";
    print "Known orthologs: ".$knownOCons->summary."\n";
    my %opres=($expOCons->stats); #gives sens and spec
    assert(defined $opres{con});
    assert(defined $opres{incon});
    $opres{fscore}=(2*$opres{sens}*$opres{spec})/($opres{sens}+$opres{spec}) if ($opres{sens}+$opres{spec});
    local $,="\n";
    local $\="\n";
    print("Consistent: ".$opres{con},
	  "Inconsistent: ".$opres{incon},
	  "Recall: ".$opres{sens},
	  "Precision: ".$opres{spec},
	  "F-Score: ".$opres{fscore});
  }
  return {anchors=>$anchors,avg=>\%avg,variance=>\%variance,stddev=>\%stddev};
}

sub rocrLabels {
  my $stats=pop;
  local $_=$rocrTarget;
  if(m/^ortholog$/){
    return ((map {1} (1..$stats->{oltp})),
	    (map {0} (1..$stats->{olfp})))
  }elsif(m/^kogolog$/){
    return ((map {1} (1..$stats->{kogtp})),
	    (map {0} (1..$stats->{kogfp})))
  }elsif(m/^tagged$/){
    return ($stats->{cds} ? 1:0);
  }elsif(m/^paralog$/){
    my $hits=sum(@{$stats}{qw{paralog ortholog}});
    my $misses=sum(@{$stats}{qw{miss untagged distant}});
    return ((1) x $hits, (0) x $misses);
  }elsif(m/^miss$/){
    my $hits=sum(@{$stats}{qw{paralog ortholog untagged distant}});
    my $misses=sum(@{$stats}{qw{miss}});
    return ((1) x $hits, (0) x $misses);
  }
  return ();
}

sub writeList {
  open(my $outfh,'>',shift);
  foreach(@_){
    print $outfh ($_,"\n");
  }
}

sub percent {
  return 'N/A%' unless $_[1];
  return sprintf("%.2f%%",$_[0]/$_[1]*100);
}

sub statReqs {
  my ($opt,$stat,$exp)=@_;
  my @available=grep {$_ ne $stat} @statTypes;
  my @reqs;
  foreach my $ustat (@available){
    push(@reqs,$ustat) if $exp=~m/(?<=\W)$ustat(?=\W|$)/;
    push(@reqs,$ustat) if $exp=~m/^$ustat(?=\W|$)/;
  }
  return @reqs;
}

sub userStatFun {
  my ($opt,$stat,$exp)=@_;
  my @available=grep {$_ ne $stat} @statTypes;
  my @reqs;
  foreach my $ustat (@available){
    my $rep='$stats{'.$ustat.'}';
    $exp=~s/(?<=\W)$ustat(?=\W|$)/$rep/g;
    $exp=~s/^$ustat(?=\W|$)/$rep/g;
  }
  return eval('sub { my %stats=@_; return '.$exp.'}');
}

sub statReplace {
  my ($reqsr,$statsr,$desc,$preview)=@_;
  my %reqs=%{$reqsr};
  my %stats=%{$statsr};
  my %using;
  my ($count,$first,$converts)=(0,1,0);
  foreach my $k (keys(%reqs)){
    next unless defined($reqs{$k});
    $count++;
    next unless $reqs{$k}=~m/x|s|v|a/; #only fiddle with things that have an x or an s
    if($first and !$preview){print "\n";$first=0}
    if($preview){
      $using{x}+=($reqs{$k}=~m/x/g);
      $using{s}+=($reqs{$k}=~m/s/g);
      $using{v}+=($reqs{$k}=~m/v/g);
      $using{a}+=($reqs{$k}=~m/a/g);
    }else{
      print "Converting $desc$k: $reqs{$k} -> ";
      $reqs{$k}=~s/(\d\.?\d*)(x|s|v|a)/\1*\2/g;
      $using{x}+=($reqs{$k}=~s/x/${$stats{avg}}{$k}/g);
      $using{s}+=($reqs{$k}=~s/s/${$stats{stddev}}{$k}/g);
      $using{v}+=($reqs{$k}=~s/v/${$stats{variance}}{$k}/g);
      $using{a}+=($reqs{$k}=~s/a/$stats{anchors}/g);
      print $reqs{$k}." = ";
      $reqs{$k}=eval($reqs{$k});
      print $reqs{$k}."\n";
    }
    $converts++;
  }
  print "\n" if $converts and !$preview;
  %{$reqsr}=%reqs;
  return (%using,count=>$count,converts=>$converts);
}

sub anchorFormat {
  my $fh=pop;
  my $format=0;
  $seqCount=0;
  seek($fh,0,0);
  $_=<$fh>;
  $format=1 if m/^(-?\d+\s-?\d+\s[+-]\s*)+\d+$/;
  $format=2 if m/^(-?\d+\s-?\d+\s[+-]\s*)+\d+\s(\d+.?\d*)$/;
  $format=3 if m/^(-?\d+\s-?\d+\s[+-]\s*)+\d+\s(\S+)\s(\d+:\d+,?)+$/;
  while(m/(-?\d+\s-?\d+\s[+-]\s*)/g){
    $seqCount++;
  }
  seek($fh,0,0);
  return $format;
}

sub lineCount {
  my $count=0;
  my $fh=pop;
  seek($fh,0,0);
  while(<$fh>){
    $count++;
  }
  seek($fh,0,0);
  return $count;
}

sub plotHistogram {
  my ($histr,$type,$phase) = @_;
  my (@bins,%hist);
  unless(keys(%$histr)){
    print "Cowardly refusing to graph an empty $type histogram.\n";
    return;
  }
  if($bins){
    ${$plotopts{$type}}{with}="boxes" unless ${$plotopts{$type}}{with}; #lines for bins doesnt make sense
    if($bwPlot){
      ${$plotopts{$type}}{style}="fill pattern 3 border 6" unless ${$plotopts{$type}}{style}; #and we like our bins visible
    }else{
      ${$plotopts{$type}}{style}="fill solid border 7" unless ${$plotopts{$type}}{style}; #and we like our bins visible (and in multiple colors!)
    }
    my @skeys=sort {$a <=> $b} keys(%$histr);
#    print "Rebinning $type data into $bins ".
#      (${$plotopts{$type}}{flatx} ? "":"logscaled ")."bins...\n";
    my ($min,$max)=($skeys[0],$skeys[$#skeys]);
    my $range=$max-$min;
    unless(${$plotopts{$type}}{flatx}){
      ($min,$max)=map(log,($min!=0 ? $min:0.1,$max!=0 ? $max:0.1));
      $range=$max-$min;
      @bins=map {exp($min+$range*($_/$bins))} (0..($bins-1));
    }else{
      @bins=map {$min+$range*($_/$bins)} (0..($bins-1));
    }
    my $i=0;
    foreach my $k (@skeys){
      while($k>$bins[$i] && $i<$#bins){
	$i++;
      }
      foreach my $aligntype (keys(%{$$histr{$k}})){
	$hist{$bins[$i]}->{$aligntype}+=$$histr{$k}->{$aligntype};
      }
    }
  }else{
    @bins=sort {$a <=> $b} keys(%$histr);
    %hist=%$histr;
  }

  my $hdata="$basefile.$type.".($phase>1 ? "filtered.":"")."histogram.data";
  open(HDATA,">$hdata") or die "Couldn't open $hdata for writing";
  if(!${$plotopts{$type}}{flaty}){
    if($showall eq "scale"){
      my ($ymin,$xmin)=(min(map {sum(values(%$_))} values(%$histr)),min(keys(%$histr)));
      my ($ymax,$xmax)=(max(map {sum(values(%$_))} values(%$histr)),max(keys(%$histr)));
      $ymin-=$ymin/10;$ymax+=$ymax/10;
      $xmin-=$xmin/10;$xmax+=$xmax/10;
      $ymin=.9 unless $xmin;
      $xmin=.9 unless $xmin;
      ${$plotopts{$type}}{yrange}="[$ymin:$ymax]";
      ${$plotopts{$type}}{xrange}="[$xmin:$xmax]";
      ${$plotopts{$type}}{tics}="out";
    }elsif($showall eq 'crop'){
      my ($lastvisible,$i)=(0,0);
      foreach my $k (@bins){
	$lastvisible=$i if $hist{$k}>1;
	$i++;
      }
      @bins=@bins[0..$lastvisible];
    }
  }
#  print "Writing $type histogram data to $hdata: @alignTypes\n";
  foreach my $k (@bins){
    print HDATA join("\t",$k, map {
      $_ ? $_:0 } ($hist{$k} ? (@{$hist{$k}}{@alignTypes}):
		  map {0} @alignTypes))."\n";
  }
  close(HDATA);
  makePlot($hdata,$type);
}

sub makePlot {
  my ($datafile,$type)=@_;
  my $title="$basename anchor $type histogram";
  my %opts;
  my $plotwith='linespoints';
  %opts=%{$plotopts{$type}} if ref $plotopts{$type} eq "HASH";
  my $extra_opts;
  while(my ($opt,$val)=each %opts){
    if($opt eq 'with'){
      $plotwith=$val;
    }elsif($opt=~m/^flat(x|y)$/){
      $extra_opts.="unset logscale $1\n";
    }
    else{
      $extra_opts.="set $opt $val\n";
    }
  }
  my @serieslist;
  my $hiIdx=$#alignTypes+2;
  for(my $i=0;$i<=$#alignTypes;$i++){
    my $align=$alignTypes[$i];
    my $y=($plotwith eq 'boxes') ?
      join("+",map {"\$$_"} (reverse($i+2..$hiIdx)))
	: '\$'.($i+2);
    push(@serieslist,
	 qq!"$datafile" using 1:($y) title '$align' with $plotwith!);
  }
  my $series=join(",\\\n",@serieslist);
  my ($xlabel,$ylabel)=("$type value","count");
  my $outbase=getPath($datafile).getName($datafile);
  my $gnuplot_cmds=<<ENDTEXT;
set title "$title"
set logscale x
set logscale y
set xlabel "$xlabel"
set ylabel "$ylabel"
$extra_opts
plot $series
ENDTEXT

  my $terminal_setup=<<ENDTEXT;
#plot "$datafile" with linespoints
set terminal png transparent size 800,800
set output "$outbase.png"
ENDTEXT

  open(PLOTCMDS,">$outbase.plot");
#  print "Writing plot commands to $outbase.plot\n";
  print PLOTCMDS $gnuplot_cmds;
  close(PLOTCMDS);

  print ">Gnuplotting $outbase.png\n";
  open(GNUPLOT,"|gnuplot");
  print GNUPLOT $terminal_setup;
  print GNUPLOT $gnuplot_cmds;
  close(GNUPLOT);
}

sub plotRocr {
  my ($rocrPath,$plotPhase,$targetStats)=@_;
  my @rocrWhat=@$targetStats; #make local screened copy
  my ($pointsize_str,$lwd);
  $lwd=$opt_lwd ? $opt_lwd:1;
  $pointsize_str=",pointsize=$opt_pointsize" if $opt_pointsize;
  unless(@rocrWhat){
    print "Nothing to ROCR...\n";
    return;
  }
  print "ROCR-$rocrTarget: @rocrWhat\n";
  open(my $R,'>',"$rocrPath.R") or die "Couldn't write to $rocrPath.R";
  print $R <<ENDR_COMMANDS;
library(ROCR)
dat<-read.delim("$rocrPath")
ENDR_COMMANDS

#individual plots and stats
  foreach my $stat (@rocrWhat){
    foreach my $plot (@rocrPlot){
      my ($yax,$xax)=split(/,/,$plot);
      my ($perfname,$perfcmd)=((join("-",$yax,$xax)),
			       (join(",",(map {qq!"$_"!} ($yax,$xax)))));
    print $R <<ENDR_COMMANDS;
#bitmap(file="$rocrPath.$stat.$perfname.png",type="png256",width=9,height=9,res=96$pointsize_str)
pred_$stat<-prediction(dat[,"$stat"],dat[,1])
#plot(performance(pred_$stat,$perfcmd))
#title(main="$stat prediction of $rocrTarget")
#dev.off()
ENDR_COMMANDS
    }
    foreach my $eval (@rocrEval){
      print $R <<ENDR_COMMANDS;
performance(pred_$stat,"$eval")\@y.values[[1]]
ENDR_COMMANDS
    }
  }

  #all combined multicolored magic plot
  if(@rocrWhat>1){
    foreach my $plot (@rocrPlot){
      my ($yax,$xax)=split(/,/,$plot);
      my ($perfname,$perfcmd)=((join("-",$yax,$xax)),
			       (join(",",(map {qq!"$_"!} ($yax,$xax)))));
      if($opt_pdf){
	print $R <<ENDTEXT;
pdf(file="$rocrPath.all.$perfname.pdf",width=9,height=9$pointsize_str)
ENDTEXT
      }else{
	print $R <<ENDTEXT;
bitmap(file="$rocrPath.all.$perfname.png",type="png256",width=9,height=9,res=96$pointsize_str)
ENDTEXT
      }
      my $color=2;
      my $add;
      foreach my $stat (@rocrWhat){
	print $R <<ENDR_COMMANDS;
plot(performance(pred_$stat,$perfcmd),col=$color$add,lwd=$lwd$pointsize_str)
ENDR_COMMANDS
      }continue{
	$color++;$add=",add=T";
      }
      my ($statbits,$colorbits)=(join(",",map{"'$_'"} @rocrWhat),
				 join(",",2..$color));
      my $legendpos="0.75,0.5";
      $legendpos=$opt_roclegendpos if $opt_roclegendpos;
      print $R "legend($legendpos,c($statbits),col=c($colorbits),lwd=$lwd)\n";
      print $R qq!title(main='Predictors of $rocrTarget')\n!;
      print $R "dev.off()\n";
    }
  }
  close($R);
  print "Plotting ROC data via ROCR\n";
  my $RresCode=system("R --silent --vanilla --no-save < $rocrPath.R >& $rocrPath.Rout");
  my $Rres=slurp("$rocrPath.Rout");
  if($RresCode){
    print "R had an error! ($RresCode) R said:\n$Rres--END--\n";
  }
  my (%evalRes,$i);
  while($Rres=~m/^\[1\]\s+(\d+\.?\d+)/gsm){
    my ($eval,$stat)=($rocrEval[$i%(@rocrEval)],
		      $rocrWhat[int($i/(@rocrEval))]);
    $evalRes{$stat}->{$eval}=$1;
    $i++;
  }
  return makeTable(\%evalRes,@rocrEval);
}

sub slurp {
  local $/;
  open(my $fh,"@_") or return;
  return <$fh>;
}

sub makeTable {
  my ($data,@cols)=@_;
  return unless @cols;
  my %longest;
  $longest{label}=max(map(length,keys(%$data)));
  foreach my $col (@cols){
    $longest{$col}=max(map {length($data->{$_}->{$col})} keys(%$data));
  }
  my $res=join(" ",sprintf("%$longest{label}s",''),map{sprintf("%-$longest{$_}s",$_)} @cols)."\n";
  foreach my $stat (keys(%$data)){
    $res.=join(" ",sprintf("%$longest{label}s",$stat),
	       (map {sprintf("%-$longest{$_}f",$data->{$stat}->{$_})} @cols))."\n";
  }
  return $res;
}

sub parseStatTypeList {
  my ($types,$all)=@_;
  $all=\@mixPlotableTypes unless $all;
  my @l;
  foreach my $t (split(/,/,$types)){
    unless(grep {$_ eq $t} (@mixPlotableTypes,'all')){
      pod2usage({%$podusageOpts,-msg=>qq!"$t" is not a recognized statistic to plot!});
    }

    if($t eq 'all'){
      push(@l,@$all);
    }else{
      push(@l,$t);
    }
  }
  return @l;
}

sub fixCoords {
  my $cd=pop;
#actually nothing to do
  return unless $cd->{strand};
  delete $cd->{strand};
}

sub getLens {
  my ($seqsfile)=@_;
  open(SEQSFH,$seqsfile) or do {print "Couldn't open sequence list to find sequence length.\nDisabling randomwiden.\n";
				undef $randomWiden}; #no seqs file for reference
  print "Reading sequence lengths...\n";
  my $i=0;
 LoadLenSeqs: while(<SEQSFH>){
    chomp;
    my $seq=$_;
    my $length=`$root/geneparse.pl -lf $seq`;
    chomp $length;
    $seqlen[$i]=$length;
  }continue{$i++}
  close SEQSFH;
}

sub getTags {
  my ($seqsfile)=@_;
  our @seqcds=();
  open(SEQSFH,$seqsfile) or return; #no seqs file for reference
  print "Checking for annotation...\n";
  my ($seqcount,$cdscount);
  $annotation=0;
 LoadSeqs: while(<SEQSFH>){
    chomp;
    my $seq=$_;
    $cdscount=0;
    $seqcount++;
    if(!-f "$seq.cds"){
      print "CDS file not found for $seq. Generating...\n";
      my $res=system("$root/getcds.pl $seq");
      unless(-f "$seq.cds"){
	print "Generation of CDS file for $seq failed\n" unless -f "$seq.cds\n";
	push(@seqcds,undef);
	next LoadSeqs;
      }
    }
    open(CDS,"$seq.cds") or die "Couldn't read $seq.cds";
    our ($overlaps,$messyoverlaps)=(0,0);
    print "Loading annotation for $seq...\n";
    my @cds;
    my $kogSpec=$seqcount-1;
    $kogSpec=$kogmap[$kogSpec] if $kogmap[$kogSpec];
  LoadCDS: while(<CDS>){
      chomp;
      my ($name,$start,$stop,$strand,$locus) = split(/\t/,$_);
      $locus=$name if $name && !$locus;
      $locus=uc $locus;
      my $cd={name => $name,start=>$start,stop=>$stop,strand=>$strand,locus=>$locus};
      $commonNames{$name}++;
      $knownLocs{$locus}=$kogSpec;
      fixCoords($cd);
      inorderInsert(\@cds,$cd);
#      print "CD-tree: ".dump(@cds)."\n";
      $cdscount++;
    }
    close CDS;
    cdsSanityCheck(@cds);
    print("$cdscount CDS's loaded into ",($#cds+1)," regions ($overlaps overlaps, $messyoverlaps of them out of order).\n");
    push(@seqcds,\@cds);
    $annotation++;
  }
  close SEQSFH;
  unless($annotation){
    print "No annotation data found. Disabling annotation based analysis.\n";
    $noTags=1;
    resetStatTypes();
    return;
  }
  print "Establishing shared names list from $annotation sequences... ";
  foreach my $name (keys(%commonNames)){
    do{
      delete $commonNames{$name}} unless $commonNames{$name}==$annotation;
  }
  print (scalar(keys(%commonNames))," shared name",(keys(%commonNames)==1 ? "":"s"),".\n");
}

sub cdsSanityCheck {
  my ($first,@cds)=@_;

  foreach my $chunkr (@_){
    die "Bad start bounds (should be ".(min(map {$_->{start}} @{$chunkr->{regions}})).") on ".dump($chunkr) if min(map {$_->{start}} @{$chunkr->{regions}})!=$chunkr->{bounds}->{start};
    die "Bad stop bounds (should be ".(max(map {$_->{stop}} @{$chunkr->{regions}})).") on ".dump($chunkr) if max(map {$_->{stop}} @{$chunkr->{regions}})!=$chunkr->{bounds}->{stop};
  }

  my ($lastStart,$lastStop);
  foreach (@{$first->{regions}}){
    $lastStart=min($_->{start},defined($lastStart) ? $lastStart:());
    $lastStop=max($_->{stop},defined($lastStop) ? $lastStop:());
  }
  foreach (map {$_->{regions}} @cds){
    my ($nowStart,$nowStop);
    foreach (@$_){
      if($_->{start}<=$lastStart || $_->{stop}<=$lastStop){
	print dump($first,@cds);
	die "Out of order cds! ".dump($_);
      }
      if(defined($nowStart)){
	$nowStart=min($_->{start},$nowStart);
	$nowStop=max($_->{stop},$nowStop);
      }else{
	$nowStart=$_->{start};
	$nowStop=$_->{stop};
      }
    }
  }
}

sub regionCmp {
#  print DEBUG "Comp: ($_[0]->{stop}<=>$_[1]->{stop}) --> ";
  return 0 if overlaps(@_);
#  print DEBUG (($_[0]->{stop}<=>$_[1]->{stop}),"\n");
  return ($_[0]->{stop}<=>$_[1]->{stop})
}

sub overlaps {
  return ($_[0]->{start}<=$_[1]->{stop} and $_[1]->{start}<=$_[0]->{stop});
}

sub fixAnchor {
  my ($r)=@_;
  ($r->{start},$r->{stop})=($r->{stop},$r->{start}) if($r->{stop} < $r->{start}); #dumb dumb dumb
}

sub findIncidentCDS {
  my $seqi=0;
  my @allhits;
  while(@_){
    do{shift;shift;shift;next} unless $seqcds[$seqi]; #skip sequences for which we don't have annotation
    my %anchor=(start=>abs(shift)-$widen,stop=>abs(shift)+$widen,strand=>shift);
    fixAnchor(\%anchor);
    my @hits=&$searcher(\%anchor,@{$seqcds[$seqi]});
    if($randomWiden){
      my $base=int($randomWiden+rand(max(0,$seqlen[$seqi]-$randomWiden)));
      my @newhits=&$searcher({start=>$base-$randomWiden,stop=>$base+$randomWiden,strand=>'+'},@{$seqcds[$seqi]});
      my %done=map {$_=>1} @hits;
      push(@hits,grep {!$done{$_}} @newhits); # dont read the same CDS twice
    }
    foreach my $cds (@hits){
      $usedNames[$seqi]->{$cds->{name}}=1;
    }
    push(@{$allhits[$seqi]},@hits);
  }continue{
    $seqi++;
  }
  return @allhits;
}

sub nameComp {
  my (%ref,@ref,$inited);
  my %res;
  my $i=0;
  for(;$i<$#_;$i++){ #make intial set
    next unless $seqcds[$i];
    foreach my $cds (@{$_[$i]}){
      push(@ref,$cds->{name});
      $ref{$cds->{name}}=$cds;
      $res{$cds->{name}}='unknown';
      $inited=1;
    }
    last if $inited;
  }

  for(;$i<$#_;$i++){ #compare others
    unless(@{$_[$i]}){ #if it didnt hit any CDS
      if(($knownKogs && $kogmap[$i]) ||
	 $seqcds[$i]){ #and that seq has annotation...
	#then this anchor is a miss
	foreach my $k (keys(%res)){
	  $res{$k}='miss';
	}
      }
    }
    foreach my $cds (@{$_[$i]}){
      my $name=$cds->{name};
      if($knownKogs && $kogmap[$i]){ #if KOG is available, use that
	my $loc=$cds->{locus};
	#if it's not in the KOG database, it has no known relatives
	#and is likely only distantly related at best...
	$res{$name}='distant' unless $knownKogs->isIn($loc);
	if($res{$name} eq 'ortholog'){
	  #must be an ortho to something on %ref or downgrade to paralog
	  $res{$name}='paralog' unless 
	    grep {$knownKogs->isOrtho($loc,$_->{locus})} values(%ref);
	}elsif($res{$name} eq 'unknown'){
	  #ok, it's similar so at least paralog
	  $res{$name}='paralog';
	  #if KOG aligns it, then ortholog
	  $res{$name}='ortholog' if
	    grep {$knownKogs->isOrtho($loc,$_->{locus})} values(%ref);
	}
      }else{ #no KOGs, guess based on names (wee!)
	unless($ref{$name}){ #name not present in ref seq?
	  if($commonNames{$name}){ #name exists elsewhere...
	    $res{$name}='distant';
	  }else{
	    #it's not a common name. might just be unannotated in other seq
	    $res{$name}='paralog';
	  }
	}else{ #names match!
	  $res{$name}='ortholog' if($res{$name} eq 'unknown');
	}
      }
    }
  }
  foreach my $k (keys(%res)){
    $res{$k}='miss' if $res{$k} eq 'unknown'; #never hit another tag
  }
  return %res;
}

sub linearSearch {
  my $needle=shift;
  return map {grep {overlaps($needle,$_)} @{$_->{regions}}} @_;
}

sub binarySearch { #(needle,haystack)
  my ($needle,$low,$high)=($_[0],1,$#_);
  my $mid;
  my @hits;
#  print "Looking for ".dump($needle)."\n";
  do {
    $mid=int(($low+$high)/2);
    my $res=regionCmp($_[$mid]->{bounds},$needle);
    goto MONKIES if $res==0;
    $low=$mid+1 if $res<0;
    $high=$mid-1 if $res>0;
  }while($low<$high);
 MONKIES:
  $mid++ if $low==$mid;
  my ($start,$stop)=($mid,$mid); #check for needle overlapping lots of hay
  @hits=grep {overlaps($needle,$_)} (@{$_[$mid]->{regions}});
  my $shits=$#hits;
  while(--$start>=1){
    my @new=grep {overlaps($needle,$_)} (@{$_[$start]->{regions}});
    last unless @new;
    push(@hits,@new);
  }
  my $lhits=$#hits;
  while(++$stop<=$#_){
    my @new=grep {overlaps($needle,$_)} (@{$_[$stop]->{regions}});
    last unless @new;
    push(@hits,@new);
  }
  my $rhits=$#hits;
#  print "Got bits! ".join(",",map {$_->{locus}} @hits)."\n" if $rhits>=0;
#  print "Got bits! ".scalar(@hits)."\n" if $rhits>=0;
  return @hits;
}

sub inorderInsert { #(haystack,needle) too match push/unshift
#ewww remind me to write recursively...
  our ($overlaps,$messyoverlaps);
  my ($hayr,$needle)=(@_);
  my ($low,$high)=(0,$#$hayr);
#  print "Insert $needle->{start} ~ $needle->{stop}\n";

  return push(@$hayr,newChunk($needle)) if($high<0); #first element (supergreen! baboomching!)
  return push(@$hayr,newChunk($needle)) if ($$hayr[$high]->{bounds}->{stop}<=>$needle->{start})<0 and !overlaps($needle,$$hayr[$high]->{bounds}); #biggest needle
  return unshift(@$hayr,newChunk($needle)) if ($$hayr[$low]->{bounds}->{start}<=>$needle->{stop})>0 and !overlaps($needle,$$hayr[$low]->{bounds}); #smallest needle

  my $mid;
  do {
#    print "Looping at $low ~ $high\n";
    #check current
    $mid=int(($low+$high)/2);
    my $hits=overlaps($needle,$$hayr[$mid]->{bounds});
#    print "Overlaps in $mid!\n" if $hits;
    if($hits){ #ok, does it overlap neighbors?
      $overlaps++;
      my ($start,$stop)=($mid,$mid); #check for needle overlapping lots of hay
      my ($lefthits,$righthits);
      while(--$start>=0){
	my $new=overlaps($needle,$$hayr[$start]->{bounds});
	last unless $new;
	$lefthits+=$new;
      }
      $start++;
      while(++$stop<=$#{$hayr}){
	my $new=grep {overlaps($needle,$_)} (@{$$hayr[$stop]->{regions}});
	last unless $new;
	$righthits+=$new;
      }
      $stop--;
      if($lefthits || $righthits){ #oh fuck...
	$messyoverlaps++;
#	print "Messy insert of ".dump($needle)."!\n";
	#everything from $start to $stop now goes into 1 blob
	my (@pre,@mid,@post);
	if($start>0){
	  @pre=@{$hayr}[0..$start-1];
	}
	if($stop<$#{$hayr}){
	  @post=@{$hayr}[$stop+1..$#{$hayr}];
	}
	# $start..$stop should contain multiple anons that need to be flattened
	foreach (@{$hayr}[$start..$stop]){
	  push(@mid,(map {@{$_->{regions}}} $_));
	}
	push(@mid,$needle); #the new guy
	#now reassemble...
	@$hayr=(@pre,newChunk(@mid),@post);
      }else{ #simple overlap. yay!
	addRegion($$hayr[$mid],$needle);
      }
      return; #either way, resolved.
    }
    $_=regionCmp($$hayr[$mid]->{bounds},$needle);
    $low=$mid+1 if $_<0;
    $high=$mid-1 if $_>0;
  }while($low<=$high);
  for(regionCmp($$hayr[$mid]->{bounds},$needle)){
    @$hayr=(@$hayr[0..$mid],newChunk($needle),@$hayr[($mid+1)..$#$hayr]) and last if $_<0;
    @$hayr=(@$hayr[0..($mid-1)],newChunk($needle),@$hayr[$mid..$#$hayr]) and last if $_>0;
    last;
  }
}

sub newChunk {
  if(@_==1){
    my ($needle)=@_;
    return {bounds=>{start=>$needle->{start},stop=>$needle->{stop}},regions=>[$needle]};
  }else{
    my $chunkr={bounds=>{},regions=>[@_]};
    resetBounds($chunkr);
    return $chunkr;
  }
}

sub addRegion {
  my ($chunkr,$needle)=@_;
  push(@{$chunkr->{regions}},$needle);
  resetBounds($chunkr);
}

sub resetBounds {
  my ($chunkr)=@_;
  $chunkr->{bounds}->{start}=min(map {$_->{start}} @{$chunkr->{regions}});
  $chunkr->{bounds}->{stop}=max(map {$_->{stop}} @{$chunkr->{regions}});
}

sub hitCdsSize {
  my ($tp,$fp,$fn);
  for(my $i=0;$i<@seqcds;$i++){
    foreach my $cdsl (@{$seqcds[$i]}){
      foreach my $cds (@{$cdsl->{regions}}){
	next unless $commonNames{$cds->{name}};
	my ($consensus,$conscore);
	foreach my $align (sort {$a cmp $b} (keys(%{$namecon{$cds->{name}}}))){
	  my $thisScore=$namecon{$cds->{name}}->{$align};
	  if($thisScore>$conscore){
	    $consensus=$align;
	    $conscore=$thisScore;
	  }
	}
	unless($usedNames[$i]->{$cds->{name}} or !$consensus){
	  $fn+=($cds->{stop}-$cds->{start}+1);
	}elsif($consensus ne 'miss' && $consensus ne 'untagged'){
	  $tp+=($cds->{stop}-$cds->{start}+1);
	}
      }
    }
  }
  return (tp=>$tp,fp=>$fp,fn=>$fn);
}

sub hashSum {
  my $r=shift;
  foreach(@_){
    foreach my $k (keys(%{$_})){
      $r->{$k}+=$_->{$k};
    }
  }
}

sub setupKogmap {
  my $seqdata=shift;
  open(my $seqfh,$seqdata) or die "Couldn't read sequence file";
  my $i=0;
  my %aliases=Murasaki::KOG->commonAliases;
  foreach(<$seqfh>){
    next if $kogmap[$i];
    chomp;
    my ($id)=Murasaki::KOG->guessKogMember($_);
    unless($id){ #load kogfile and try again
      Murasaki::KOG->learnKogSpecs($kogfile);
      $id=Murasaki::KOG->guessKogMember($_);
    }
    next unless $id;
    print "Identified $_ as KOG member $id\n";
    $kogmap[$i]=$id;
  }continue{$i++}
}

sub setupKogs {
  our @kogmap;
  if(!@kogmap){
    print "Kogfile supplied, but no input sequences associated with Kogs?\n";
    print " >> Maybe try --kog 1=<kog abbreviation> (eg. --kog 0=sce) to\n",
      " >> force associations?\n";
    $kogfile=undef;
    print "Disabling ROCR...\n";
    @rocrWhat=undef;
    return;
  }

  print "knownlocs contains: ".scalar(keys %knownLocs)." entries\n";
  $knownKogs=Murasaki::KOG->kogFrom($kogfile,[grep {$_} @kogmap],\%knownLocs,\%kogpref);
  $knownOList=Murasaki::OrthoList->orthosFromKog($knownKogs,\@kogmap,\%knownLocs) if $useOList;
  $knownOPairs=Murasaki::OrthoPairs->orthosFromKog($knownKogs,\@kogmap,\%knownLocs) if $useOPairs;
  $knownOCons=Murasaki::OrthoConsistency->orthosFromKog($knownKogs,\@kogmap,\%knownLocs) if $useOCons;
  unless($knownKogs){
    print "Disabling ROCR...";
    @rocrWhat=undef;
  }
}

__END__

=head1 NAME

filter.pl - filters output from murasaki based on various filters

=head1 SYNOPSIS

filter.pl [options] <detailed murasaki ailgnment file> [output file]

=head1 OPTIONS

 Filtering options:
Filtering can be performed on "length", "hits", "tfidf", or "score".
You can filter by either setting either a "min" or "max".
For example: "--minlength 50" filters out any anchors with an average
length shorter than 50. (average length is used because an anchor
may be different sizes on different sequences).
Filters can also use the average(x), standard deviation(s),
variance(v), or anchor count(a) in an expression to set a filter.
For example: "--minscore=2x" sets the minimum score threshold to
twice the average score. "--minlength=x+s/2" sets the minimum length
threshold to the average length plus half a standard deviation.

 Input modification:
 "--widen=500" => extends each anchor 500 bases in both directions
 "--randomwiden=500" => extends each anchor 500 bases _at random_
   (ie: to compare to --widen)

 Output options:
 "--statdump" => dump all available stats into 1 file with a header row
 "--dumpstats tfidf,length" => dumps stats tfidf and length to separate files
                               one line per anchor
 "--dumpstats" => assumes "--dumpstats all"

 Plot options:
filter.pl can plot any or all of the statistics gathered by using
the "--plot" option.
 Examples:
 "--plot hits,length" => plots both hits and length
 "--plot" => assumes "--plot all"

 "--plotopts" allows setting of various gnuplot and special plot options.
Different statistics can be targeted separately by prefixing the setting
name with the statistic(s) of your choice followed by a "."
For example:
  "--plotopts hits,length.flatx" => disables the log scale on the x axis
                                    of the hits and length plots only
  "--plotopts with=points" => uses points instead of bars on all plots
  "--plotopts <gnuplot option>=<value>" => can be used to set arbitrary
       gnuplot options of the form "set <gnuplot option> <value>"

 "--bins" can be used to specify the number of bins.
 "--nobins" turns off binning and plots a raw (likely bumpy) histogram
 "--showall=crop" sends all data to gnuplot even on logscale plots (by
    default for logscale plots values <=1 at the extreme right end are
    chopped off because they don't show up in gnuplot (1 is the baseline)
    but they  do affect the visible range, and thus causes some scrunching.
 "--showall=scale" manually sets to the X and Y ranges to the range of the
    data (so 1's are visibly different from 0's).
 "--showall=<anything else>" disables scaling/cropping

The Gnuplot commands for generating the plots are also dumped to
<something>.<stat-type>.plot and can be run interactively in gnuplot
by typing: load "<something>.<stat-type>.plot"

 Statistical Options:
 "--all/--quick" => standard deviation calculations require a second
    pass through the data, and as histogram plots are generally much
    more useful than a standard deviation statistic (especially considering
    not all of these statistics may be gaussian), so unless one of your
    constraints calls for standard deviation, this calculation is skipped.
    It can be forced by applying --all. (--quick is the default)
 "--nodetails" => disables reconstruction of term indicies (this will
    disable tfidf stats).
 "--tags" => enables reading of annotation.
    This produces "good, miss, shuffle" stats (which can also be plotted)
    and specificity/sensitivity information
 "--notags" => disables reading of annotation (by default)

 COG/KOG Statistics:
 At any rate:
 "--kogfile=path/to/kog" => enables kog-based alignment
 "--kogmap 3=hsa" => forces sequence 3 (note: sequences are 0 indexed) to
    be assigned to the "hsa" kog. If the file name includes one of the
    kog species abbreviations, it is assumed to belong to that kog.

 Debugging:
 "--linear" => forces linear scans for CDS's instead of binary searches
    (if this returns different results, it means something is very wrong)

 [output file]:
If the input filename is of the form <something>.anchors.details, then the
[output file] defaults to <something>.filtered.

Incidentally, if you don't provide a <something>.anchors.details file,
it probably won't work anyway...

=head1 DESCRIPTION

Filters murasaki alignments based on various statistics. Various statistics can be plotted using --plot. Annotation data is processed from input files
using BioPerl.

ROC data can be calculated using KOG data (which is much more reliable
than just gene names). To do so you need to specify a KOG data file
which can be downloaded from the COG database at:
http://www.ncbi.nlm.nih.gov/COG/
You'll be looking for either the "whog" file for COGs or the "kog" file
on the KOG side. KOG locus naming sometimes differs from GBK file to
file, and locus names are sometimes missing, so KOG based assessment
is currently best effort (capitalization is ignored, locii which don't
appear in the annotation are ignored, and domain-specific _x endings
are ignored).

=cut