-
Notifications
You must be signed in to change notification settings - Fork 1
/
apa_routines-1.1.pm
executable file
·1565 lines (1353 loc) · 58.3 KB
/
apa_routines-1.1.pm
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
#!/n/local/stage/perlbrew/perlbrew-0.43/perls/perl-5.16.0/bin/perl
use Data::Dumper;
use Roman;
use strict;
##!/n/site/inst/Linux-x86_64/sys/bin/perl
### GENERIC FUNCTIONS:
## timestamp : three different types of platform-independent timestamps
## runtime : takes 2 timestamps and returns elapsed time, in various scales
## monthconv : convert month names to numbers and vice versa
## benchmark : platform-independent system resource stamps
## logreport : send a message to screen & logfile simultaneously
## numjust : pad a digit with leading zeroes
## unique : return unique values from an array, in order of appearance
## pairs2subgraphs : given a 2-level hash describing a connectivity matrix (e.g. $hash{$key1}{$key2}, preferably reciprocal so that $hash{$key2}{$key1} also always exists), return all subgraphs.
### MATH FUNCTIONS:
## mean
## median
## stdev
## strip_NA
### BIOLOGICAL FUNCTIONS:
## revcomp : reverse complement for DNA/RNA, with full degeneracy/masking support
## revcomp_regex : reverse complement a DNA/RNA regular expression, with full degeneracy/masking support
## word_exp : get the expected frequency of a DNA/RNA/AA word, given background character frequencies
## coding_potential : calculate coding potential for a DNA sequence, using one of several methods ########## NOT WORKING PROPERLY ##########
## translate : translate a DNA sequence
## blockify : convert a sequence to a fasta block
## chrsort : sort a list of chromosomes the way I prefer. Special handling for roman chrnums (yeast) and drosophila chrs
## get_memedata : get a standard hash of data from a MEME run (DOES NOT WORK FOR 4.8.1)
## UTR_weld : take a hash of CDS entries + hash of UTR entries and return a hash of exons
### UNDER CONSTRUCTION: may have some functionality at this time, or may not
## getfile : read a tabular text file into an array-of-arrays or hash-of-arrays
## writefile : write an array, array-of-arrays, or hash-of-arrays back to a tabular text file
## getfasta : read a fasta file into a hash
## writefasta : write a fasta file from a hash
## get_fimodata : get a standard hash of data from a FIMO run (DOES NOT WORK FOR 4.8.1)
## get_tomdata : get a standard hash of data from a Tomtom run (DOES NOT WORK FOR 4.8.1)
## length_regex : calculate length of a regular expression, also report if length is fixed or minimum
sub timestamp {
## returns date, time, or date+time timestamps
my $timetype = shift; # FULL = date + time | DATE = date | TIME = time
my $timestamp;
my %daynames = (0,'Sun', 1,'Mon', 2,'Tue', 3,'Wed', 4,'Thu', 5,'Fri', 6,'Sat');
my %monthnames = (0,'Jan', 1,'Feb', 2,'Mar', 3,'Apr', 4,'May', 5,'Jun', 6,'Jul', 7,'Aug', 8,'Sep', 9,'Oct', 10,'Nov', 11,'Dec');
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
if ($timetype eq 'FULL') {
$timestamp = "$daynames{$wday} $monthnames{$mon} ".sprintf("%02d %4d %02d:%02d:%02d", $mday,$year+1900,$hour,$min,$sec);
} elsif ($timetype eq 'DATE') {
$timestamp = "$daynames{$wday} $monthnames{$mon} ".sprintf("%02d %4d", $mday,$year+1900);
} elsif ($timetype eq 'TIME') {
$timestamp = sprintf("%02d:%02d:%02d", $hour,$min,$sec);
}
return $timestamp;
}
sub runtime { # UNDER CONSTRUCTION
## takes 2 and returns the difference, in the specified timescale
## mode 1 = 'FULL' timestamp from above timestamp() function, e.g. "Fri May 4 2012 14:00:47"
## mode 2 = generic [YYYY-MM-DD HH:MM:SS] timestamp, e.g. "2012-05-04 14:00:47"
## mode 3 = Unix `date` style timestamp, e.g. "Fri May 4 14:00:47 CDT 2012"
### requires 2 timestamp('FULL') entries
my (%timestamps, %timediff, %timeparts, %absolute, $scale, $mode);
($timestamps{1}, $timestamps{2}, $scale, $mode) = @_; # timestamps with format e.g. 'Thu Jun 23 2011 12:57:08'; for $scale see %scales below
my %scales = map {($_=>1)} qw/ FULL YEAR MONTH DAY HOUR MINUTE SECOND /; # time scale to return results in; 'FULL' = full breakout
# note that scale 'MONTH' will return month breakdown as months elapsed + fraction of end-month elapsed
my %monthdays = (1,31, 2,28, 3,31, 4,30, 5,31, 6,30, 7,31, 8,31, 9,30, 10,31, 11,30, 12,31);
my %monthsecs = map {($_=>$monthdays{$_}*86400)} keys %monthdays;
my %monthnums = (1,'Jan', 2,'Feb', 3,'Mar', 4,'Apr', 5,'May', 6,'Jun', 7,'Jul', 8,'Aug', 9,'Sep', 10,'Oct', 11,'Nov', 12,'Dec');
my %timescales = ('YEAR',31536000, 'DAY',86400, 'HOUR',3600, 'MIN',60, 'SEC',1); # times in seconds | months variable, so not here
foreach my $t (1,2) {
my ($dname, $mname, $mon, $date, $yr, $zone, $hr, $min, $sec);
if ($mode == 1) {
($dname, $mon, $date, $yr, $hr, $min, $sec) = split /\s+/, $timestamps{$t};
$mon = monthconv($mname,2);
} elsif ($mode == 2) {
($yr, $mon, $date, $hr, $min, $sec) = split /[\s:-]+/, $timestamps{$t};
} elsif ($mode == 3) {
($dname, $mname, $date, $hr, $min, $sec, $zone, $yr) = split /[\s:]+/, $timestamps{$t};
}
$timeparts{$t}{YEAR} = $yr;
$timeparts{$t}{MONTH} = $mon;
$timeparts{$t}{DAY} = $date;
$timeparts{$t}{HOUR} = $hr;
$timeparts{$t}{MIN} = $min;
$timeparts{$t}{SEC} = $sec;
$absolute{$t} = ($yr-1)*31536000 + ($date-1)*86400 + $hr*3600 + $min*60 + $sec; # fully elapsed years, days only
$absolute{$t} += $monthsecs{$_} foreach 1..$timeparts{$t}{MONTH}; # add seconds per day of each fully elapsed month in YTD
}
my $seconds = $absolute{2} - $absolute{1}; # total seconds elapsed
if ($scale eq 'FULL' || $scale eq 'YEAR') {
if ($seconds > $timescales{YEAR}) {
$timediff{YEAR} = $seconds/$timescales{YEAR};
$seconds %= $timescales{YEAR};
}
}
if ($scale eq 'FULL' || $scale eq 'MONTH') {
my $thismonth = $timeparts{1}{MONTH};
if ($seconds > $monthsecs{$thismonth}) { # months begin elapsing from the start-time month
my $continue = 1;
while ($continue) {
$timediff{MONTH}++;
$seconds -= $monthsecs{$thismonth};
$thismonth++;
$continue = 0 if $seconds < $monthsecs{$thismonth}; # stop if fewer seconds exist than do in the next month
}
}
}
if ($scale eq 'FULL' || $scale eq 'DAY') {
if ($seconds > $timescales{DAY}) {
$timediff{DAY} = $seconds/$timescales{DAY};
$seconds %= $timescales{DAY};
}
}
if ($scale eq 'FULL' || $scale eq 'HOUR') {
# if ($seconds > $timescales{HOUR}) {
$timediff{HOUR} = $seconds/$timescales{HOUR};
$seconds %= $timescales{HOUR};
# }
}
if ($scale eq 'FULL' || $scale eq 'MIN') {
if ($seconds > $timescales{MIN}) {
$timediff{MIN} = $seconds/$timescales{MIN};
$seconds %= $timescales{MIN};
}
}
if ($scale eq 'FULL') {
my @elapsed;
push @elapsed, int($timediff{YEAR}), " years" if $timediff{YEAR};
push @elapsed, int($timediff{MONTH}), " months" if $timediff{MONTH};
push @elapsed, int($timediff{DAY}), " days" if $timediff{DAY};
push @elapsed, int($timediff{HOUR}), " hours" if $timediff{HOUR};
push @elapsed, int($timediff{MIN}), " minutes" if $timediff{MIN};
push @elapsed, int($timediff{SEC}), " seconds" if $timediff{SEC};
my $elapsed = join ', ', @elapsed;
return "Elapsed: $elapsed\n";
} else {
return $timediff{$scale};
}
}
sub monthconv {
## converting month names to numbers or vice versa
my ($inmonth, $dir) = @_; # $dir = 1 for num -> name | $dir = 2 for name -> num
my %monthnames1 = (1,'Jan', 2,'Feb', 3,'Mar', 4,'Apr', 5,'May', 6,'Jun', 7,'Jul', 8,'Aug', 9,'Sep', 10,'Oct', 11,'Nov', 12,'Dec');
my %monthnames2 = reverse %monthnames1;
if ($dir == 1) {
$inmonth =~ s/^0+//; # drop any leading zeroes
return $monthnames1{$inmonth};
} elsif ($dir == 2) {
my $outmonth = $monthnames2{$inmonth};
$outmonth = "0$outmonth" if $outmonth < 10;
return $outmonth;
} else {
die "Conversion direction '$dir' must be 1 (num->name) or 2 (name->num)!\n";
}
}
sub benchmark {
## captures 'top' info on a process (Linux -OR- Windows) and returns it, annotated (or writes it to file)
my ($pid, $platform, $file, $msg, $script) = @_; # $msg, $script, $file can be null
# print "Received benchmark request: '$pid', '$msg', '$script', '$platform', '$file'\n";
my $string;
if ($platform eq 'LINUX') {
my @output = split /\n/, `top -b -p $pid -n 1`;
my @stuff = split /\s+/, $output[7];
$string = join "\t", ($msg, $script, @stuff);
} elsif ($platform eq 'WIN2K') {
my @output = split /\n/, `tasklist /V /FI "PID eq $pid"`;
my @stuff = split /\s+/, $output[3];
$string = join "\t", ($msg, $script, @stuff);
} else {
$string = "\nBenchmark subroutine doesn't know what to do on $platform operating systems!\nNo RAM usage data will be available.";
warn $string;
}
if ($file) {
open OUT, ">> $file" or warn "\n&benchmark cannot append to $file: $!\n";
print OUT "$string\n";
close OUT;
} else {
return $string;
}
}
sub logreport {
## prints a message to STDOUT and to a given logfile
my ($msg, $logfile) = @_;
$msg =~ s/[\n\r]+$//; # so you don't have to remember if it needs newlines
open OUT, ">> $logfile" or warn "\nlogreport cannot append to $logfile: $!\n";
print OUT "$msg\n";
close OUT;
print "$msg\n";
}
sub revcomp {
## reverse-complement DNA/RNA with full degeneracy/masking support
my $SEQ = shift;
$SEQ = $$SEQ if $SEQ =~ /SCALAR/; # convert references
($SEQ = reverse $SEQ) =~ tr/ACGTURYSWKMHDVBNacgturyswkmhdvbn/TGCAAYRSWMKDHBVNtgcaayrswmkdhbvn/;
return \$SEQ; # return reference
}
sub revcomp_regex {
## reverse-complement DNA/RNA regular expressions with full degeneracy/masking support
## DOES NOT SUPPORT ALL POSSIBLE REGULAR EXPRESSIONS. Does not use regexp parse trees. Designed for revcomping simple DNA/RNA motif regexps.
## Basic and non-greedy quantifiers, custom classes, and simple groupings are supported, or at least as far as I have tested.
## Anchors, escaped chars and class shortcuts, lookarounds, backreferences, logicals, no-memory groupings, and nested groupings are NOT supported.
my $SEQ = shift;
return('') if $SEQ =~ /\(\?[<!=:]/; # no lookarounds or no-memory groupings
return('') if $SEQ =~ /(?<!\\)\\(?!\\)/; # no backrefs or escaped chars
return('') if $SEQ =~ /\([^\(]*\(/; # no nested groupings
return('') if $SEQ =~ /^\^/ || $SEQ =~ /(?<!\\)\$$/; # no anchors
my $nonparen = '[^\(\)]+';
my $nonbrack = '[^\[\]]+';
my $nonenc = '[\\\]?[^\(\)\[\]]'; # aiming to capture escaped single chars, too -- but in general, escaped things not supported
my $paren = '\('.$nonparen.'\)';
my $brack = '\['.$nonbrack.'\]';
my $quants = '(?<![\\\])[\*\+\?]{1,2}'; # NON-ESCAPED quantifiers -- but in general, escaped things not supported
my $braces = '\{[\d,]+\}';
my $anytarg = $paren.'|'.$brack.'|'.$nonenc;
$SEQ = $$SEQ if $SEQ =~ /SCALAR/; # convert references
($SEQ = reverse $SEQ) =~ tr/ACGTURYSWKMHDVBNacgturyswkmhdvbn\[\]\(\)\{\}/TGCAAYRSWMKDHBVNtgcaayrswmkdhbvn\]\[\)\(\}\{/;
$SEQ =~ s/\?([+*])($anytarg)/$2$1?/g; # un-reverse minimal quantifiers
$SEQ =~ s/($quants|$braces)($anytarg)/$2$1/g; # put quantifiers on the right side of targets
$SEQ =~ s/\[($nonbrack)\^\]/[^$1]/g; # put class negators on the left inside of brackets
$SEQ =~ s/\{(\d*)(,?)(\d+)?\}/{$3$2$1}/g; # un-reverse quantifier order inside braces
return \$SEQ; # return reference
}
sub length_regex {
##### UNDER CONSTRUCTION #####
## calculates the length of a regular expression
## also returns whether this length is a fixed length or a minimum length
## DOES NOT SUPPORT ALL POSSIBLE REGULAR EXPRESSIONS. Does not use regexp parse trees. Designed for revcomping simple DNA/RNA motif regexps.
## Basic and non-greedy quantifiers, custom classes, ^$-anchors, and simple groupings are supported, or at least as far as I have tested.
## Escaped chars, class shortcuts, and logicals are given SOME support.
## Non-^$ anchors, lookarounds, backreferences, no-memory groupings, and nested groupings are NOT supported.
my ($RE, $view) = @_;
my $nonparen = '[^\(\)]+';
my $nonbrack = '[^\[\]]+';
my $nonenc = '[\\\]?[^\(\)\[\]]'; # aiming to capture escaped chars, too
my $paren = '\('.$nonparen.'\)';
my $brack = '\['.$nonbrack.'\]';
my $quants = '(?<!\\\)[\*\+\?]{1,2}'; # NON-ESCAPED quantifiers
my $braces = '\{[\d,]+\}';
my $anytarg = $paren.'|'.$brack.'|'.$nonenc;
my ($minlen, $maxlen, $incr1, $incr2, $inf);
return('NA','NA') if $RE =~ /\(\?[<!=:]/; # no lookarounds or no-memory groupings
return('NA','NA') if $RE =~ /\\\d/; # no backrefs
return('NA','NA') if $RE =~ /\([^\(]*\(/; # no nested groupings
$RE =~ s/^\///g; # remove bouding slashes
$RE =~ s/\/$//g; # remove bouding slashes
$RE =~ s/^\^//; # remove anchors
$RE =~ s/(?<!\\)\$$//; # remove anchors
while ($RE =~ s/($brack)($quants)//) {
my ($m1, $q) = ($1, $2);
if ($q =~ /\+/) {
$incr1 = $incr2 = 1;
} else {
$incr1 = 0;
$incr2 = $q eq '?' ? 1 : 0;
}
$inf = 1 unless $q eq '?';
$minlen += $incr1;
$maxlen += $incr2;
print "1. /$m1$q/ = ($incr1, $incr2)\n" if $view;
}
while ($RE =~ s/($brack)\{(\d+)(,?)(\d*)\}//) {
$minlen += $2;
$maxlen += $4;
print "2. /$1\{$2$3$4\}/ = ($2, $4)\n" if $view;
}
while ($RE =~ s/($brack)//) {
$minlen++;
$maxlen++;
print "3. /$1/ = 1\n" if $view;
}
while ($RE =~ s/($paren)($quants)//) {
my ($m1, $q) = ($1, $2);
(my $m2 = $m1) =~ s/[\(\)]//g; # remove matched parens
my ($min, $max) = (sort {$a <=> $b} map {length($_)} split /\|/, $m2)[0,-1];
if ($q =~ /\+/) {
($incr1, $incr2) = ($min, $max);
} else {
$incr1 = 0;
$incr2 = $q eq '?' ? $max : 0;
$inf = 1 if $q =~ /\*/;
}
$inf = 1 unless $q eq '?';
$minlen += $incr1;
$maxlen += $incr2;
print "4. /$m1$q/ = ($incr1, $incr2)\n" if $view;
}
while ($RE =~ s/($paren)\{(\d+)(,?)(\d*)\}//) {
my ($m1, $b1, $b2, $b3) = ($1, $2, $3, $4);
(my $m2 = $m1) =~ s/[\(\)]//g; # remove matched parens
my ($min, $max) = (sort {$a <=> $b} map {length($_)} split /\|/, $m2)[0,-1];
$incr1 = $min*$b1;
if ($b2) {
$incr2 = $max*$b3; # zeroes out if infinite # use of '|' inside parens could be dealt with here
$inf = 1 unless $b3;
} else {
$incr2 = $incr1;
}
$minlen += $incr1;
$maxlen += $incr2;
print "5. /$m1\{$b1$b2$b3}/ = ($incr1, $incr2)\n" if $view;
}
while ($RE =~ s/($nonenc)($quants)//) {
my ($m1, $q) = ($1, $2);
if ($q =~ /\+/) {
$incr1 = $incr2 = 1;
} else {
$incr1 = 0;
$incr2 = $q eq '?' ? 1 : 0;
}
$inf = 1 unless $q eq '?';
$minlen += $incr1;
$maxlen += $incr2;
print "6. /$m1$q/ = ($incr1, $incr2)\n" if $view;
}
while ($RE =~ s/($nonenc)\{(\d+)(,?)(\d*)\}//) {
$incr1 = $2;
if ($3) {
$incr2 = $4; # zeroes out if infinite
$inf = 1 unless $4;
} else {
$incr2 = $incr1;
}
$minlen += $incr1;
$maxlen += $incr2;
print "7. /$1\{$2$3$4\}/ = ($incr1, $incr2)\n" if $view;
}
my $incr;
$incr += length($_) foreach (split /\\/, $RE); # add whatever loose chars remain -- split in escaped chars to get rid of backslashes
$minlen += $incr;
$maxlen += $incr;
$maxlen = 'Inf' if $inf;
print "8. /$RE/ = $incr\n" if $RE && $view;
print "Final: $minlen, $maxlen\n" if $view;
return($minlen, $maxlen);
}
sub word_exp {
## expected frequency of a DNA/RNA/AA word given known background frequencies
## divide search space size by return value to get expected number of words
my ($word, $alpha, $ref) = @_; # $word = motif, $ref = bkg hash ref (%s or counts), $alpha = DNA, RNA, AA, or FREE (last = use bkgfreq as-is; don't test)
my %alphabets = (
'DNA' => { 'required' => { map {($_=>1)} qw/ A C G T / },
'allowed' => { map {($_=>1)} qw/ A C G T R Y S W K M H D V B N / }
},
'RNA' => { 'required' => { map {($_=>1)} qw/ A C G U / },
'allowed' => { map {($_=>1)} qw/ A C G U R Y S W K M H D V B N / }
},
'AA' => { 'required' => { map {($_=>1)} qw/ A C D E F G H I K L M N P Q R S T V W Y / },
'allowed' => { map {($_=>1)} qw/ A C D E F G H I K L M N P Q R S T V W Y B Z J X U O / }
},
'FREE' => 1
);
my %convdegen = (
'DNA' => { 'R' => [qw/ A G /],
'Y' => [qw/ C T /],
'S' => [qw/ C G /],
'W' => [qw/ A T /],
'K' => [qw/ G T /],
'M' => [qw/ A C /],
'B' => [qw/ C G T /],
'D' => [qw/ A G T /],
'H' => [qw/ A C T /],
'V' => [qw/ A C G /],
'N' => [qw/ A C G T /]
},
'RNA' => { 'R' => [qw/ A G /],
'Y' => [qw/ C U /],
'S' => [qw/ C G /],
'W' => [qw/ A U /],
'K' => [qw/ G U /],
'M' => [qw/ A C /],
'B' => [qw/ C G U /],
'D' => [qw/ A G U /],
'H' => [qw/ A C U /],
'V' => [qw/ A C G /],
'N' => [qw/ A C G U /]
},
'AA' => { 'B' => [qw/ N D /],
'Z' => [qw/ E Q /],
'J' => [qw/ I L /],
'X' => [qw/ A C D E F G H I K L M N P Q R S T V W Y /]
}
);
$word = "\u$word";
$alpha = "\U$alpha";
die "Unknown alphabet '$alpha'! Must be one of 'DNA', 'RNA', 'AA', or 'FREE'.\n" unless $alphabets{$alpha};
### SET UP BKG FREQ HASH
my ($sum, %freqs); # background letter frequencies
if ($ref) { # known bkg; but are they frequencies?
my ($sub1, $sum1);
foreach (keys %$ref) {
$sub1++ if $$ref{$_} < 1;
$sum1 += $$ref{$_};
die "Cannot have negative background frequencies! &word_exp halting.\n" if $_ < 0;
}
if ($sub1 == scalar (keys %$ref)) { # all frequencies; ok
$freqs{ "\U$_" } = $$ref{$_} foreach keys %$ref; # copy from $ref; ensure capitalization
} elsif ($sub1 == 0) { # all counts; ok
$freqs{ "\U$_" } = $$ref{$_} / $sum1 foreach keys %$ref; # copy from $ref; divide by sum; ensure capitalization
} else { # mixed? bad
die "Cannot mix frequencies and counts in background hash! &word_exp halting.\n";
}
} elsif ($alpha eq 'FREE') { # calculate bkg as uniform distrib of extant letters?
my %letters = map {($_=>1)} (split //, $word);
my $N = scalar keys %letters;
$freqs{$_} = 1 / $N foreach keys %letters;
} else { # assume random bkg frequencies for known alphabet
my $N = scalar keys %{ $alphabets{$alpha}{required} };
$N += 2 if ($word =~ /[UO]/ && $alpha eq 'AA'); # add these too
$freqs{$_} = 1 / $N foreach keys %{ $alphabets{$alpha}{required} };
}
$sum += $freqs{$_} foreach keys %freqs;
die "Background frequencies sum to $sum, not 1! &word_exp halting.\n" if sprintf("%0.8f",$sum) != 1;
### QC INCOMING DATA | FIX DEGENERACIES
my (%lost, %wrong, %degen, %nondeg, %nonstd);
if ($alpha eq 'FREE') {
my @lost;
foreach my $letter (split //, $word) {
push @lost, $letter unless $freqs{$letter}; # freestyle still can't have letters without bkg freqs
}
my $lost = join ',', @lost;
die "Background frequency hash missing values for some given letters ($lost)! &word_exp halting.\n" if @lost; # freestyle still can't have letters without bkg freqs
$nondeg{W}{$_}++ foreach (split //, $word);
} else {
## test for all required letters
foreach my $req (keys %{ $alphabets{$alpha}{required} }) {
$lost{$req} unless exists $freqs{$req}; # must have values for all required letters
}
my $lost = join ', ', (sort keys %lost);
die "Background frequency hash missing values for required letters: $lost! &word_exp halting.\n" if $lost;
## test for unknown or degenerate letters in word
foreach my $letter (split //, $word) {
if ($alphabets{$alpha}{required}{$letter}) {
$nondeg{W}{$letter}++; # non-degenerate
} elsif ($letter =~ /^[UO]$/ && $alpha eq 'AA') {
$nonstd{W}{$letter}++; # non-required non-degenerate amino acids
} elsif ($alphabets{$alpha}{allowed}{$letter}) {
$degen{W}{$letter}++; # allowed & not non-degenerate = degenerate
} else {
$wrong{W}{$letter} = 1; # cannot have unknown letters
}
}
my $wrongletters1 = join ', ', (sort keys %{ $wrong{W} }); # hopefully the string gets 'undef'
die "Word contains non-$alpha letters: $wrongletters1! &word_exp halting.\n" if $wrongletters1;
## test for unknown or degenerate letters in bkg freq hash
foreach my $letter (keys %freqs) {
if ($alphabets{$alpha}{required}{$letter}) {
$nondeg{B}{$letter} = 1; # non-degenerate
} elsif ($letter =~ /^[UO]$/ && $alpha eq 'AA') {
$nonstd{B}{$letter} = 1; # non-required non-degenerate amino acids
} elsif ($alphabets{$alpha}{allowed}{$letter}) {
$degen{B}{$letter} = 1; # allowed & not non-degenerate = degenerate
} else {
$wrong{B}{$letter} = 1; # cannot have unknown letters
}
}
my $wrongletters2 = join ', ', (sort keys %{ $wrong{B} }); # hopefully the string gets 'undef'
die "Background frequency hash contains non-$alpha letters: $wrongletters2! &word_exp halting.\n" if $wrongletters2;
## distribute degenerates in bkg freq hash to non-degenerates
foreach my $deg (keys %{ $degen{B} }) { # nothing happens unless %degen2 has data
my @members = @{ $convdegen{$alpha}{$deg} };
my ($val, $N) = ($freqs{$deg}, scalar @members);
delete $freqs{$deg}; # remove degenerate entry
$freqs{$_} += $val / $N foreach @members; # distribute value evenly among possible real letters
}
## test for allowable nonstd chars which aren't in bkg hash (DO NOT test degenerates)
my %nslost;
foreach my $letter (keys %{ $nonstd{W} }) {
$nslost{$letter} = 1 unless $nonstd{B}{$letter};
}
my $nslost = join ', ', (sort keys %nslost); # hopefully the string gets 'undef'
die "Background frequency hash missing the following nonstandard letters in word: $nslost! &word_exp halting.\n" if $nslost;
}
### Calculate weighted expectations for the word
my $stdfreq = my $nonfreq = my $degfreq = 1;
foreach my $letter (keys %{ $nondeg{W} }) {
$stdfreq *= $freqs{$letter} foreach (1..$nondeg{W}{$letter}); # weighted product of frequencies for non-degenerates * number of occurrances
}
foreach my $letter (keys %{ $nonstd{W} }) {
$nonfreq *= $freqs{$letter} foreach (1..$nonstd{W}{$letter}); # weighted product of frequencies for non-standards * number of occurrances
}
foreach my $letter (keys %{ $degen{W} }) { # foreach degenerate base
foreach (1..$degen{W}{$letter}) { # foreach instance of degenerate base
my $dfreq;
$dfreq += $freqs{$_} foreach @{ $convdegen{$alpha}{$letter} }; # total frequency for degenerate letter * number of occurrances
$degfreq *= $dfreq;
}
}
my $expfreq = $stdfreq * $nonfreq * $degfreq;
if ($expfreq) {
my $hmean = 1 / $expfreq;
return $hmean; # where we expect to see 1 occurrence every $hmean bp.
} else {
print "Expected frequency is zero: did you specify a bkg frequency of zero for any letters in the word?\n";
return 0;
}
}
sub coding_potential {
## calculates DNA sequence coding potential, using one of several published methods
my %methods = ( # given in order of increasing sensitivity (and runtime)
'odds' => 1, # simple nucleotide odds ratio
'PSF' => 2, # position-specific nucleotide frequencies
'CSF' => 3, # codon structure factor | for methods 1-3 see Nikolaou & Almirantis, J Mol Evol 2004, PMID:15553086
'CSF+' => 4, # threshold-based RNY (allows for 'coding' calls, instead of just getting a value)
'UFM' => 5 # Universal Feature Method | for methods 4-5 see Carels & Frias, Bioinfo Biol Insights 2009, PMID:20140062
);
my %revord = (0,2, 1,1, 2,0); # inverted codon order
my %stopcodons = map {($_=>1)} qw/ TAA TAG TGA /; # ochre, amber, opal/umber
my ($NTSEQ, $method, $tmode, $threshold) = @_; # $threshold is 'coding' calling threshold for CSF+, UFM methods. See defaults below.
die "UFM method not yet fully implemented! Try 'CSF' instead.\n" if $method eq 'UFM';
my $mnames = join ', ', sort keys %methods;
die "Unknown method '$method'! Must be one of: '$mnames'\n" unless $methods{$method};
if ($method eq 'UFM' && $tmode != 6) {
warn "Method 'UFM' requires 6-frame translation: inceasing 'tmode' from $tmode to 6.\n";
$tmode = 6;
}
$threshold = 1 if $method eq 'UFM' && !$threshold; # see paper, section 'Optimization of classification thresholds'
$threshold = 75 if $method eq 'CSF+' && !$threshold; # ditto
my (%FREQ, $sum);
$FREQ{$_}++ foreach split //, $NTSEQ;
my $N = length($NTSEQ);
my $C = $N/3;
foreach (keys %FREQ) {
$FREQ{$_} /= $N;
$sum += $FREQ{$_};
}
die "Background frequencies sum to $sum, not 1! &coding_potential halting.\n" if sprintf("%0.8f",$sum) != 1;
my $M = scalar keys %FREQ;
my %CODONS = %{ &translate(\$NTSEQ, $tmode, 0, 0, 0, '', 1) }; # $NTSEQ, $tmode, $stats, $keepcase, $orfs, $stopchar, $ascodons
my (%COM, %STOP);
foreach my $frame (sort keys %CODONS) {
my (%NUM, %PSF, %AG, %CGA);
my ($NUMsum, %PSFsum, %AGsum, %CGAsum, @PSFfail);
# print "$frame: @{ $CODONS{$frame} }\n";
# print "$N, $C, ", (scalar @{ $CODONS{$frame} }), "\n";
my $ncodons = scalar @{ $CODONS{$frame} };
$NUM{$_} += 1/$ncodons foreach @{ $CODONS{$frame} }; # frequency per codon
$NUMsum += $NUM{$_} foreach keys %NUM;
die "Numerator codon frequencies sum to $NUMsum, not 1! &coding_potential halting.\n" if sprintf("%0.8f",$NUMsum) != 1;
my %DEN = map {($_=>1)} keys %NUM; # initialize
$STOP{$frame} = 0; # ensure printable, if printing debugging messages
unless ($method eq 'odds') {
foreach my $codon (@{ $CODONS{$frame} }) {
my @bases = split //, $codon;
$STOP{$frame}++ if $stopcodons{$codon};
if ($method eq 'UFM') {
$AG{A} += 1/$ncodons if $bases[0] eq 'A';
$AG{G} += 1/$ncodons if $bases[0] eq 'G';
$CGA{C} += 1/$ncodons if $bases[0] eq 'C';
$CGA{G} += 1/$ncodons if $bases[1] eq 'G';
$CGA{A} += 1/$ncodons if $bases[2] eq 'A';
} else {
$PSF{ $bases[$_] }{$_} += 1/$ncodons foreach (0..2);
}
}
if ($method eq 'UFM') {
$AGsum{$_} += $AG{$_} foreach qw/ A G /;
$CGAsum{$_} += $CGA{$_} foreach qw/ C G A /;
print "CGAsum: C=$CGAsum{C} G=$CGAsum{G} A=$CGAsum{A} | AGsum: A=$AGsum{A} G=$AGsum{G}\n";
} else {
foreach my $i (0..2) {
$PSFsum{$i} += $PSF{$_}{$i} foreach qw/ A C G T N /;
push @PSFfail, " $i=$PSFsum{$i}" if sprintf("%0.8f",$PSFsum{$i}) != 1;
}
if (@PSFfail) {
my $msg = join "\n", ("Codon-position frequencies have failed to sum to 1 at the following positions:", @PSFfail, " &coding_potential halting.\n");
die $msg;
}
}
}
if ($method eq 'UFM') { # see paper, section 'Scoring the coding potential of ORFs with UFM'
my $W = 0.01;
$COM{$frame} = ($AG{A}*$AG{G}) / ($CGA{C}*$CGA{G}*$CGA{A}+$STOP{$frame}+$W);
# print "$frame: ($AG{A}*$AG{G}) / ($CGA{C}*$CGA{G}*$CGA{A}+$STOP{$frame}+$W) = $COM{$frame}\n";
} else {
foreach my $codon (keys %NUM) {
my @bases = split //, $codon;
if ($method eq 'odds') {
$DEN{$codon} *= $FREQ{$_} foreach @bases;
} else {
if ($method eq 'PSF') {
$DEN{$codon} *= $PSF{ $bases[$_] }{$_} foreach (0..2);
} elsif ($method =~ /^CSF/) {
$DEN{$codon} *= $PSF{ $bases[$_] }{ $revord{$_} } foreach (0..2);
}
}
# print "$frame: $codon: $NUM{$codon} / $DEN{$codon}\n";
# print "$frame: $codon: $NUM{$codon} / $DEN{$codon} = ", ($NUM{$codon} / $DEN{$codon}), "\n";
$COM{$frame} += $NUM{$codon} / $DEN{$codon};
}
# print "$frame: COM = $COM{$frame}\n";
}
}
my $maxframe = (sort { $COM{$b} <=> $COM{$a} } keys %COM)[0];
my $minframe = (sort { $COM{$a} <=> $COM{$b} } keys %COM)[0];
my $maxcp = $COM{$maxframe};
my $mincp = $COM{$minframe};
my $iscoding = 0;
if ($method eq 'UFM' || $method eq 'CSF+') {
$iscoding = $maxcp - $mincp > $threshold ? 1 : -1;
} elsif ($method eq 'CSF+') {
$iscoding = $maxcp > $threshold ? 1 : -1;
}
return($maxframe, $maxcp, $minframe, $mincp, $maxcp-$mincp, $iscoding); # best & worst frames + scores; $iscoding gives 1=TRUE | -1=FALSE | 0=UNTESTED
}
sub numjust {
## justifies a number by adding leading zeroes
my ($num, $width) = @_;
my $len = length($num);
if ($len < $width) {
my $spacer = 0 x ($width - $len);
$num = "$spacer$num";
}
return $num;
}
sub blockify {
## breaks a sequence into lines of length $N; e.g. for fastas
## RETURNS A SCALAR REFERENCE
## block does NOT end with a newline
my @data = @_; # (sequence, line width)
my $SEQ = $data[0] =~ /SCALAR/ ? ${$data[0]} : $data[0];
my $WIDTH = $data[1] ? $data[1] : 50; # default width
my (@lines, $start);
my $blocks = length($SEQ) / $WIDTH;
$blocks++ if (length($SEQ) % $WIDTH != 0);
foreach (1..$blocks) {
push @lines, substr($SEQ, $start, $WIDTH);
$start += $WIDTH;
}
my $seqblock = join "\n", @lines;
return \$seqblock;
}
sub unique {
## uniques an array
my @array = @{ $_[0] };
my (@unique, %already);
foreach (@array) {
push @unique, $_ unless $already{$_}; # maintains input order w/o using a sort step
$already{$_} = 1;
}
return \@unique;
}
sub chrsort {
## sorts a list of chromosome names the way I prefer to sort them.
## Specifically designed for UCSC chromosome naming conventions; probably works with some others.
## 1. numeric first (increasing numeric sort),
## 2. alpha second (increasing alpha sort),
## 3. randoms third (same order as their non-random counterparts) unless $interleave = 1 (see below)
## 4. scaffolds fourth (increasing numeric sort ignoring prefix); multiple sets are sorted increasing by prefix.
## Tests for prefixes are of 2 types: "prefix_else" and "prefix####", the latter ignoring the prefix "chr"
## It takes 5 entries with the same prefix to flag that prefix as indicating a scaffold (or something like it)
# $dataref = chr names array ref
# $interleave: 1 = sort random chrs next to their nonrandom counterparts; 0 = sort them after the canonical chromosomes
# $scaflimit: threshold (>=) for prefix prevalence to trigger prefix=scaffold decision
my ($dataref, $interleave) = @_[0,1];
my $scaflimit = $_[2] ? $_[2] : 5;
my (%sets, %prefixes, %isscaf, %romanchrs, @final, $dscount, $drosophila);
my @dros_strings = qw/ 2L 2R 3L 3R Het /;
my @drosorder1 = qw/ 2 3 4 mitochondrion M U X Y /; # fixed order for drosophila chr name part 1 ('mitochondrion' takes precedence over M)
my @drosorder2 = qw/ L R /; # fixed order for drosophila chr name part 2
# my $Bclass = '\d._-';
my $troubleshoot = 0;
## scaffold prefix, Roman, Drosophila tests
foreach my $chr (@$dataref) {
my $chrflag = $chr =~ /^chr/ ? 1 : 0;
(my $ext = $chr) =~ s/^chr//;
if ($ext ne 'M' && isroman($ext)) { # roman numeral, BUT NOT 'M' THAT IS MITO
$romanchrs{$chr} = arabic($ext);
next;
} else {
foreach my $dstring (@dros_strings) {
$dscount++ if $chr =~ /$dstring/i;
# $dscount += 3 if $chr =~ /_mitochondrion_genome/; # flybase chrM string; guaranteed drosophila
}
}
# $prefixes{$1}++ if $ext =~ /^(\D+)[$Bclass]+$/;
$prefixes{$1}++ if $ext =~ /^(\D+)\d/;
}
if ($dscount >= 3) {
$drosophila = 1; # match any 3 drosophila strings, you are considered drosophila
} else {
%romanchrs = () if (scalar (keys %romanchrs) <= 2); # have to have > 2 romans to have any; otherwise just getting chrX and/or chrM
}
foreach my $prefix (keys %prefixes) {
$isscaf{$prefix} = 1 if $prefixes{$prefix} >= $scaflimit;
}
## chr breakout
if ($drosophila) {
my (%patterns, @search, @display, %drosordered); # chrom arrangement templates
if ($interleave) {
%patterns = ('numeric' => '^\d+[LR]?', 'alpha' => '^[MUXY]');
@search = @display = qw/ numeric alpha /;
} else {
%patterns = ('numeric' => '^\d+[LR]?', 'numHet' => '^\d+[LR]?H', 'alpha' => '^[MUXY]', 'alphaHet' => '^[MUXY][LR]?H');
@search = qw/ numHet numeric alphaHet alpha /; # Hets search first, else all go non-het
# @display = qw/ numeric numHet alpha alphaHet /; # Hets display second in types
@display = qw/ numeric alpha numHet alphaHet /; # Hets display last
}
$drosordered{$_} = [] foreach keys %patterns;
foreach my $chr (@$dataref) {
(my $ext = $chr) =~ s/^chr//;
my $matched;
if ($chr =~ /mitochondrion_genome/) { # flybase chrM
$matched = 'alpha';
} else {
foreach my $group (@search) {
next if $matched; # already defined
$matched = $group if $ext =~ /$patterns{$group}/i;
}
}
if ($matched) {
push @{ $drosordered{$matched} }, $chr;
} else {
print "Failed to classify '$chr'!\n";
}
}
foreach my $group (@display) {
my $flag = $troubleshoot ? "\t$group" : "";
push @final, "$_$flag" foreach sort @{ $drosordered{$group} };
}
} else {
foreach my $chr (@$dataref) {
my $chrflag = $chr =~ /^chr/ ? 1 : 0;
(my $ext = $chr) =~ s/^chr//;
my $scaffold;
foreach my $prefix (keys %isscaf) {
$scaffold = $prefix if $ext =~ s/^$prefix//;
}
if ($scaffold) {
$sets{scaf}{$scaffold}{$ext}{$chr} = 1;
} elsif ($romanchrs{$chr}) {
# do nothing; already stored in %romanchrs
} elsif ($chrflag && $ext =~ /^(\d+)(\D+)/) {
# chromosome, but extension starts with digits then nondigits? Add it the numeric randoms.
# TEST BEFORE "random" since this takes precedence!!!
my ($ext2, $etc) = ($1, $2);
$interleave ? ($sets{std}{numeric}{$ext2}{$chr} = 1) : ($sets{rand}{numeric}{$ext2}{$chr} = 1);
} elsif ($ext =~ s/_random$//) {
if ($ext =~ /\D/) {
$interleave ? ($sets{std}{alpha}{$ext}{$chr} = 1) : ($sets{rand}{alpha}{$ext}{$chr} = 1);
} else {
$interleave ? ($sets{std}{numeric}{$ext}{$chr} = 1) : ($sets{rand}{numeric}{$ext}{$chr} = 1);
}
} elsif ($ext =~ /^(\d+)(\D+)/) {
# not a chrom or scaffold, but extension starts with digits then nondigits? Add it the 'odds': list after standards but before randoms.
# TEST AFTER "random" since "random takes precedence!!!
$sets{odd}{alpha}{$ext}{$chr} = 1; # alpha only; no odd numeric
} elsif ($ext =~ /\D/) {
$sets{std}{alpha}{$ext}{$chr} = 1;
} else {
$sets{std}{numeric}{$ext}{$chr} = 1;
}
}
## sort & compile
# @final = ('ORIGINAL', @$dataref, "\n") if $troubleshoot;
my $flag = $troubleshoot ? "\troman" : "";
push @final, "$_$flag" foreach (sort { $romanchrs{$a} <=> $romanchrs{$b} } keys %romanchrs);
foreach my $type (qw/ std odd rand /) {
if ($sets{$type}{numeric}) {
my $flag = $troubleshoot ? "\t$type.numeric" : "";
foreach my $ext (sort {$a <=> $b} (keys %{ $sets{$type}{numeric} })) {
push @final, "$_$flag" foreach (sort keys %{ $sets{$type}{numeric}{$ext} });
}
}
if ($sets{$type}{alpha}) {
my $flag = $troubleshoot ? "\t$type.alpha" : "";
foreach my $ext (sort (keys %{ $sets{$type}{alpha} })) {
push @final, "$_$flag" foreach (sort keys %{ $sets{$type}{alpha}{$ext} });
}
}
}
foreach my $prefix (sort keys %isscaf) {
if ($sets{scaf}{$prefix}) {
my $flag = $troubleshoot ? "\tscaf.$prefix" : "";
foreach my $ext (sort {$a <=> $b} keys %{ $sets{scaf}{$prefix} }) {
push @final, "$_$flag" foreach (sort keys %{ $sets{scaf}{$prefix}{$ext} });
}
}
}
}
return \@final;
}
sub getfile {
## reads a text file into a standard format (array-of-arrays or hash-of-arrays) with various options
# $filename = filename | $delim is the file delimiter ("\t", ",", etc) | $chomp = [01] remove terminal [\r\n]+
# $header = integer: capture $header first lines as header | $skip = integer: skip $skip first lines
# $nfields = integer: return row broken into $nfields fields (as "split /$delim/, $_, $nfields")
# $keycol = integer: use data in column $keycol (USE 0-BASED!!!) as hash key for storing row (changes output from @-of-@ to %-of-@)
my ($filename, $delim, $chomp, $header, $skip, $nfields, $keycol) = @ARGV;
$chomp = 1 if !defined $chomp;
my (@header, @data, %data);
open MY_GETFILE_EXCLUSIVE_FILEHANDLE, $filename or die "Can't open '$filename': $!\n";
while (<MY_GETFILE_EXCLUSIVE_FILEHANDLE>) {
next if ($skip && $. <= $skip);
$_ =~ s/[\n\r]+$// if $chomp;
if ($header && $. <= $header) {
push @header, $_;
next;
}
if ($keycol) {
my @temp = split /$delim/, $_; # gets key from absolute column, not $nfields-split column
warn "Key '$temp[$keycol]' already seen! Overwriting...\n" if exists $data{$temp[$keycol]};
$data{$temp[$keycol]} = $nfields ? [split /$delim/, $_, $nfields] : [split /$delim/, $_];
} else {
($nfields) ? (push @data, [split /$delim/, $_, $nfields]) : (push @data, [split /$delim/, $_]);
}
}
close MY_GETFILE_EXCLUSIVE_FILEHANDLE;
if ($keycol) {
return(\%data, \@header);
} else {
return(\@data, \@header);
}
}
sub writefile {
## writes a text file from a contents block (must be single string, so join "\n" any arrays)
# $filename = filename | $contents = string to write | $mode = '>' or '>>'
my ($filename, $contents, $mode) = @ARGV;
$mode = '>' unless $mode;
open MY_WRITEFILE_EXCLUSIVE_FILEHANDLE, "$mode $filename" or die "Can't write to '$filename': $!\n";
print MY_WRITEFILE_EXCLUSIVE_FILEHANDLE $contents;
close MY_WRITEFILE_EXCLUSIVE_FILEHANDLE;
}
sub getfasta {
## reads a fasta into a hash (keys=headers, values=sequence)
# $filename = filename | $chomp = [01] remove terminal [\r\n]+ (affects sequence block only)
my ($filename, $chomp) = @ARGV;
$chomp = 1 if !defined $chomp;
my ($header, @headers, %data);
open MY_GETFASTA_EXCLUSIVE_FILEHANDLE, $filename or die "Can't open '$filename': $!\n";
while (<MY_GETFASTA_EXCLUSIVE_FILEHANDLE>) {
next if $_ =~ /^#/;
$_ =~ s/[\n\r]+$// if $chomp;
if ($_ =~ /^>(.*)/) {
$header = $1;
push @headers, $header; # record of header order
} else {
$data{$header} .= $_ if $_ =~ /\S/; # remove any lines with tabs or spaces
}
}
close MY_GETFASTA_EXCLUSIVE_FILEHANDLE;
return(\%data, \@headers);
}
sub writefasta {
## writes a sequence hash (keys=headers, values=sequence) to a fasta file
# $filename = filename | $contents = string to write | $mode = '>' or '>>' | $width = line width
my ($filename, $dataref, $mode, $width) = @ARGV;
$mode = '>' unless $mode;
$width = 50 unless $width;
open MY_WRITEFASTA_EXCLUSIVE_FILEHANDLE, "$mode $filename" or die "Can't write to '$filename': $!\n";
print MY_WRITEFASTA_EXCLUSIVE_FILEHANDLE ">$_\n", blockify($$dataref{$_}, $width), "\n" foreach keys %$dataref;
close MY_WRITEFASTA_EXCLUSIVE_FILEHANDLE;
}
sub get_memedata {
## takes a meme directory and reads the meme.txt and meme.html files, or returns error
## if files exist, returns a hash with a variety of data per motif, current keys:
## WIDTH, NSEQS, LOGLR, EVAL, INFO, ENTRO, CONSENSUS, PSSM (base => array), POS (seq => count), PVAL (pval => count).
## PVAL is per sequence. PSSM base-arrays are the width of the motif.
my $memedir = shift;
my $memetxt = "$memedir/meme.txt";
my $memehtml = "$memedir/meme.html";
die "'$memedir/meme.txt' is not readable!\n" unless -e $memetxt;
die "'$memedir/meme.html' is not readable!\n" unless -e $memehtml;
my %degen = ('AG'=>'R', 'CT'=>'Y', 'CG'=>'S', 'AT'=>'W', 'GT'=>'K', 'AC'=>'M', 'CGT'=>'B', 'AGT'=>'C', 'ACT'=>'H', 'ACG'=>'V', 'ACGT'=>'N');