-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGFFTree.pm
More file actions
executable file
·1808 lines (1630 loc) · 56.8 KB
/
GFFTree.pm
File metadata and controls
executable file
·1808 lines (1630 loc) · 56.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
=head1 NAME
GFFTree
=head1 SYNOPSIS
my $gff = GFFTree->new({});
$gff->name('GFF');
$gff->parse_file();
$gff->add_expectation('mrna','hasParent','gene','find');
$gff->add_expectation('mrna','<[_start,_end]','SELF','warn');
$gff->add_expectation('mrna','>=[_start]','PARENT','warn');
while (my $gene = $gff->next_feature('gene')){
while (my $mrna = $gene->next_feature('mrna')){
$mrna->validate;
}
}
=head1 DESCRIPTION
This module is intended to be as close as possible to a universal gff3 file parser.
Calling parse_file causes the gff3 file to be read into a graph structure, allowing
relationships to be queried and modified during an optional validation step, which can be
applied to individual features independently.
The parser makes no assumptions about the feature types expected in column 3 nor the
content of column 9 (other than that it is a set of key-value pairs). Expected properties
of, and relationships among and between, features may be defined as a set of expectations,
which can be tested during an optional validation step. The behaviour of the parser on
finding an unmet assumption (to ignore, warn, die, link to an existing feature or create a
new feature) can be defined independently for each assumption through the use of flags.
=cut
use strict;
use warnings;
package GFFTree;
use Tree::DAG_Node;
use IO::Unread;
our @ISA=qw(Tree::DAG_Node);
=head2 new
Function : Creates a new GFFTree
Example : $gff = GFFTree->new({});
=cut
sub new {
my $class = shift;
my $options = shift;
my $self = bless $class->SUPER::new();
$self->attributes($options);
return $self;
}
# use nesting to allow subs to share and retain access to private variables
{
my %ids;
my %suffices;
my %by_start;
my %type_map;
my %multiline;
my %parents;
my $separator = '\t';
my $has_comments = undef;
my $lastline;
my %override;
my $format = 'gff3';
=head2 format
Function : Sets/returns the file format to be used when parsing a gtf/gff file
Example : $gff->format('gff3');
Example : $gff->format('gtf');
=cut
sub format {
my ($self,$filetype) = @_;
$format = $filetype if $filetype;
return $format;
}
=head2 separator
Function : Sets/returns the separator to be used when parsing a gff file
Example : $gff->separator('\t');
=cut
sub separator {
my $sep = pop;
if (ref $sep ne 'HASH'){
$separator = $sep;
}
return $separator;
}
=head2 has_comments
Function : treat anything after (optionally between) specified characters as a comment
each call will overwrite any previous values
Example : $gff->has_comments('#'); # anything after the hash character will be ignored
$gff->has_comments(['[',']']); # anything in square brackets will be ignored
$gff->has_comments('#', ['[',']']); # multiple comments can be specified at once
$gff->has_comments(); # the file has no comments
=cut
sub has_comments {
my ($node,@arr) = @_;
$has_comments = \@arr;
return scalar @arr;
}
=head2 delete_comments
Function : delete comments from lines (as specified by has_comments)
Example : delete_comments($line);
=cut
sub delete_comments {
my $line = pop;
my @array = @$has_comments;
while (my $char = shift @array){
if (ref $char && ref $char eq 'ARRAY'){
my $pattern = $char->[0].'.+?'.$char->[1];
$line =~ s/$pattern//g;
}
else {
my $pattern = $char.'.+';
$line =~ s/$pattern//;
}
}
return $line;
}
=head2 map_types
Function : Loads a mapping of types to allow treating of features with different types
as one
Example : $gff->map_types({'internal' => 'exon'});
=cut
sub map_types {
my $mapping = pop;
foreach my $type (keys %{$mapping}){
$type_map{$type} = $mapping->{$type};
}
return scalar keys %type_map;
}
=head2 override
Function : remove existing attribute to be repaired during validation
Example : $gff->override({'cds'=>{'ID'=>1}});
=cut
sub override {
my $override = pop;
foreach my $type (keys %{$override}){
my $lctype = $type;
$lctype =~ tr/[A-Z]/[a-z]/;
$override{$lctype} = $override->{$type};
}
return scalar keys %override;
}
=head2 multiline
Function : Specify feature types that can be split over multiple lines use 'all' to
allow any feature be multiline
Example : $gff->multiline('cds');
=cut
sub multiline {
my $types = pop;
$types =~ tr/[A-Z]/[a-z]/;
my @types = split /\|/,$types;
while (my $type = shift @types){
$multiline{$type} = 1;
}
return scalar keys %multiline;
}
=head2 is_multiline
Function : Test whether feature type can be split ove multiple lines
Example : $gff->is_multiline('cds');
=cut
sub is_multiline {
return 1 if $multiline{'all'};
my $type = pop;
$type =~ tr/[A-Z]/[a-z]/;
return 1 if $multiline{$type};
return;
}
=head2 parse_file
Function : Convenience method, calls parse_chunk with no separator to read an entire
gff3 file into a tree structure.
Example : $gff->parse_file();
=cut
sub parse_file {
my $node = shift;
$node->parse_chunk();
return 1;
}
=head2 parse_chunk
Function : Reads a chunk of a gff3 file into a tree structure, handling multiline
features and ordering features on the same region. if called with no
parameters the whole file will be parsed.
Example : $gff->parse_chunk('separator','###');
Example : $gff->parse_chunk('change','region');
Example : $gff->parse_chunk('separator','###');
=cut
sub parse_chunk {
my ($node,$split_by,$break_on) = @_;
foreach my $it ($node->clear_daughters) { $it->delete_tree }
if ($lastline){
$lastline = undef;
undef %ids;
return;
}
#$ids{'root'} = $node;
if ($split_by){
return unless $break_on;
if ($split_by eq 'change'){
return unless $break_on eq 'region';
# TODO: consider adding support for other changes
}
}
my $fasta;
my $region;
my $seq = '';
my $ctr = 0;
while (<>){
$lastline = $_ if eof();
chomp;
if ($split_by && $split_by eq 'separator'){
last if $_ =~ m/^$break_on/;
}
if (my $ret = is_comment($_)){
if ($ret == -9){
$fasta = substr $_,1;
}
else {
$fasta = undef;
$seq = '';
$region = undef;
}
next;
}
elsif ($fasta){
$seq .= $_;
$region = $node->by_attributes(['_type','region'],['_seq_name',$fasta]) unless $region;
unless ($region){
$region = $node->make_region($fasta,'region');
}
$region->{attributes}->{_seq} = $seq;
$region->{attributes}->{_end} = length $seq;
next;
}
my $parent = $node;
if ($has_comments){
$_ = delete_comments($_);
}
my ($data,$attribs) = $format eq 'gtf' ? parse_gtf_line($_,$separator) : parse_gff_line($_,$separator);
next unless $data;
my %attributes;
$attributes{'_seq_name'} = $data->[0];
$attributes{'_source'} = $data->[1];
$attributes{'_type'} = $type_map{$data->[2]} ? $type_map{$data->[2]} : $data->[2];
$attributes{'_start'} = $data->[3];
$attributes{'_end'} = $data->[4];
$attributes{'_score'} = $data->[5];
$attributes{'_strand'} = $data->[6];
$attributes{'_phase'} = $data->[7];
my $lctype = lc $attributes{'_type'};
if ($override{$lctype}){
foreach my $attr (keys %{$override{$lctype}}){
delete $attribs->{$attr};
}
}
if ($attribs->{'Parent'} && $ids{$attribs->{'Parent'}}){
$parent = $ids{$attribs->{'Parent'}};
$ctr++;
}
else {
# use the root node as an orphanage
$parent = $node;
#$attribs->{'Parent'} = 'root';
}
if (!$attribs->{'ID'}){ # need to do something about features that lack IDs
my $behaviour = $node->lacks_id($attributes{'_type'});
next if $behaviour eq 'ignore';
if ($behaviour eq 'warn'){
warn "WARNING: the feature on line $. does not have an ID, skipping feature\n";
next;
}
elsif ($behaviour eq 'die'){
die "ERROR: the feature on line $. does not have an ID, cannot continue\n";
}
elsif ($behaviour ne 'make'){
if ($attribs->{$behaviour}){
$attribs->{'ID'} = $attribs->{$behaviour};
}
else {
$behaviour = 'make';
}
}
if ($behaviour eq 'make'){
if (is_multiline($attributes{'_type'})){
# test whether parent has a child of this type with an ID already
if ($attribs->{'Parent'} && $parents{$attribs->{'Parent'}}{$attributes{'_type'}}){
$attribs->{'ID'} = $parents{$attribs->{'Parent'}}{$attributes{'_type'}};
}
}
if (!$attribs->{'ID'}){
my $prefix = $attributes{'_type'}.'___';
my $suffix = 0;
if ($suffices{$prefix}){
$suffix = $suffices{$prefix};
$suffices{$prefix}++;
}
while (by_id($prefix.$suffix)){
$suffix++;
$suffices{$prefix} = $suffix + 1;
}
$attribs->{'ID'} = $prefix.$suffix;
if (is_multiline($attributes{'_type'}) && $attribs->{'Parent'}){
$parents{$attribs->{'Parent'}}{$attributes{'_type'}} = $attribs->{'ID'};
}
}
}
}
$attribs->{'ID'} =~ s/'//g;
if (ref $attribs->{'Parent'} eq 'ARRAY'){ # multiparent feature
my $base_id = $attribs->{'ID'};
delete $attribs->{'ID'};
my @parents = @{$attribs->{'Parent'}};
$attribs->{'_parents'} = \@parents;
delete $attribs->{'Parent'};
for (my $p = 0; $p < @parents; $p++){
$attributes{'Parent'} = $parents[$p];
my $id;
if ($p == 0){
$attributes{'_duplicate'} = 0;
$id = $base_id;
}
else {
$attributes{'_duplicate'} = 1;
$id = $base_id.'._'.$p;
}
$id = $p == 0 ? $base_id : $base_id.'._'.$p;
$attributes{'ID'} = $id;
if ($ids{$parents[$p]}){
$ids{$id} = $ids{$parents[$p]}->new_daughter({%attributes,%$attribs});
}
else {
$ids{$id} = $node->new_daughter({%attributes,%$attribs});
}
$ids{$id}->id($id);
if ($attribs->{'Name'}){
$ids{$id}->name($attribs->{'Name'});
}
else {
$ids{$id}->name($id);
}
push @{$by_start{$attributes{'_seq_name'}}{$attributes{'_strand'}}{$attributes{'_type'}}{$attributes{'_start'}}},$id;
}
}
elsif (my $existing = $ids{$attribs->{'ID'}}){ # test if ID already exists, then treat as clash or multline
if (is_multiline($attributes{'_type'}) &&
$existing->{attributes}->{'_seq_name'} eq $attributes{'_seq_name'} &&
$existing->{attributes}->{'_type'} eq $attributes{'_type'} &&
$existing->{attributes}->{'_strand'} eq $attributes{'_strand'} &&
(!$attribs->{'Parent'} ||
($attribs->{'Parent'} &&
$existing->{attributes}->{'Parent'} eq $attribs->{'Parent'}))
){
unless ($existing->{attributes}->{'_attributes'}){
foreach my $attr (keys %{$existing->{attributes}}){
$existing->{attributes}->{'_attributes'}->{$attr} = 1;
push @{$existing->{attributes}->{$attr.'_array'}},$existing->{attributes}->{$attr};
}
}
# change _start and _end, storing individual component values in an array
if ($attributes{'_start'} > $existing->{attributes}->{'_start'}){
# don't use unshift but choose between push and splice according to the existing values
if ($attributes{'_end'} > $existing->{attributes}->{'_end'}){
foreach my $attr (keys %{$existing->{attributes}->{'_attributes'}}){
push @{$existing->{attributes}->{$attr.'_array'}},defined $attributes{$attr} ? $attributes{$attr} : defined $attribs->{$attr} ? $attribs->{$attr} : undef;
}
foreach my $attr (keys %$attribs){
unless ($existing->{attributes}->{'_attributes'}->{$attr}){
for (my $i = 0; $i - 1 < @{$existing->{attributes}->{'_start_array'}}; $i++){
push @{$existing->{attributes}->{$attr.'_array'}},undef;
}
push @{$existing->{attributes}->{$attr.'_array'}},$attribs -> {$attr};
$existing->{attributes}->{'_attributes'}->{$attr} = 1;
}
}
$existing->{attributes}->{'_end'} = $attributes{'_end'};
}
else {
# find the position in the array to insert the current values
my $index = 0;
while ($index < @{$existing->{attributes}->{'_start_array'}} && $attributes{'_start'} > $existing->{attributes}->{'_start_array'}[$index]){
$index++;
}
foreach my $attr (keys %{$existing->{attributes}->{'_attributes'}}){
splice @{$existing->{attributes}->{$attr.'_array'}},$index,0,defined $attributes{$attr} ? $attributes{$attr} : defined $attribs->{$attr} ? $attribs->{$attr} : undef;
}
foreach my $attr (keys %$attribs){
unless ($existing->{attributes}->{'_attributes'}->{$attr}){
for (my $i = 0; $i - 1 < @{$existing->{attributes}->{'_start_array'}}; $i++){
push @{$existing->{attributes}->{$attr.'_array'}},undef;
}
splice @{$existing->{attributes}->{$attr.'_array'}},$index,0,$attribs -> {$attr};
$existing->{attributes}->{'_attributes'}->{$attr} = 1;
}
}
}
}
else {
foreach my $attr (keys %{$existing->{attributes}->{'_attributes'}}){
unshift @{$existing->{attributes}->{$attr.'_array'}},defined $attributes{$attr} ? $attributes{$attr} : defined $attribs->{$attr} ? $attribs->{$attr} : undef;
}
for (my $s = 0; $s < @{$by_start{$attributes{'_seq_name'}}{$attributes{'_strand'}}{$attributes{'_type'}}{$existing->{attributes}->{'_start'}}}; $s++){
my $possible = $by_start{$attributes{'_seq_name'}}{$attributes{'_strand'}}{$attributes{'_type'}}{$existing->{attributes}->{'_start'}}[$s];
if ($possible eq $existing){
# remove and replace
splice(@{$by_start{$attributes{'_seq_name'}}{$attributes{'_strand'}}{$attributes{'_type'}}{$existing->{attributes}->{'_start'}}}, $s, 1);
$existing->{attributes}->{'_start'} = $attributes{'_start'};
push @{$by_start{$attributes{'_seq_name'}}{$attributes{'_strand'}}{$attributes{'_type'}}{$attributes{'_start'}}},$existing;
last;
}
}
foreach my $attr (keys %$attribs){
unless ($existing->{attributes}->{'_attributes'}->{$attr}){
for (my $i = 1; $i < @{$existing->{attributes}->{'_start_array'}}; $i++){
unshift @{$existing->{attributes}->{$attr.'_array'}},undef;
}
unshift @{$existing->{attributes}->{$attr.'_array'}},$attribs -> {$attr};
$existing->{attributes}->{'_attributes'}->{$attr} = 1;
}
}
$existing->{attributes}->{'_start'} = $attributes{'_start'};
}
}
else {
# ID clash
#print $parent->id(),"\n";
#print $attributes{'_type'},"\n";
#print is_multiline($attributes{'_type'}),"\n";
die "ERROR: feature ID $attribs->{'ID'} has already been used (line $.)\nERROR: should you call multiline('".$attributes{'_type'}."') before parse_file()?\n";
}
}
else {
#print "$attribs->{'ID'}\n";
$ids{$attribs->{'ID'}} = $parent->new_daughter({%attributes,%$attribs});
$ids{$attribs->{'ID'}}->id($attribs->{'ID'});
if ($attribs->{'Name'}){
$ids{$attribs->{'ID'}}->name($attribs->{'Name'});
}
else {
$ids{$attribs->{'ID'}}->name($attribs->{'ID'});
}
push @{$by_start{$attributes{'_seq_name'}}{$attributes{'_strand'}}{$attributes{'_type'}}{$attributes{'_start'}}},$ids{$attribs->{'ID'}};
}
if ($split_by && $split_by eq 'change'){
my $nextline = <>;
if (defined($nextline)){
next if is_comment($nextline);
IO::Unread::unread ARGV, $nextline;
next if $fasta;
if ($has_comments){
$nextline = delete_comments($nextline);
}
my ($nextdata,undef) = $format eq 'gtf' ? parse_gtf_line($_,$separator) : parse_gff_line($nextline,$separator);
last if $nextdata && $nextdata->[0] ne $data->[0];
}
else {
last;
}
}
}
# loop through orphanage to see if anything can be done with unparented features
my $orphans = 0;
my @orphans = $node->daughters();
while (scalar @orphans != $orphans){
$orphans = scalar @orphans;
for (my $o = 0; $o < @orphans; $o++){
if ($orphans[$o]->{attributes}->{'Parent'} && $ids{$orphans[$o]->{attributes}->{'Parent'}}){
# move the orphan node to a new parent
$orphans[$o]->unlink_from_mother();
$ids{$orphans[$o]->{attributes}->{'Parent'}}->add_daughter($orphans[$o]);
}
}
@orphans = $node->daughters();
}
for (my $o = 0; $o < @orphans; $o++){
if ($orphans[$o]->{attributes}->{'Parent'}){
my $behaviour = $node->undefined_parent();
if ($behaviour eq 'die'){
die "ERROR: no parent feature exists for ",$orphans[$o]->{attributes}->{_type}," ",$orphans[$o]->id()," with the ID $orphans[$o]->{attributes}->{'Parent'}, cannot continue\n";
}
else {
# wait for validation to take care of things - needs improving
}
}
}
return 1;
}
=head2 by_id
Function : Fetch a node by unique id
Example : $node = by_id('id');
=cut
sub by_id {
my $id = pop;
return $ids{$id};
}
=head2 make_id
Function : generate a unique id for a node
Example : $id = $node->make_id('prefix');
=cut
sub make_id {
my $node = shift;
my $prefix = shift;
$prefix = 'GFFTree_'.$prefix;
my $suffix = 0;
$suffix = 0 unless $suffix;
if ($suffices{$prefix}){
$suffix = $suffices{$prefix};
$suffices{$prefix}++;
}
while (by_id($prefix.$suffix)){
$suffix++;
$suffices{$prefix} = $suffix + 1;
}
my $id = $prefix.$suffix;
$node->id($id);
$node->{attributes}->{'ID'} = $id;
if ($node->{attributes}->{'Name'}){
$node->name($node->{attributes}->{'Name'});
}
else {
$node->name($id);
}
$ids{$id} = $node;
push @{$by_start{$node->{attributes}->{_seq_name}}{$node->{attributes}->{_strand}}{$node->{attributes}->{_type}}{$node->{attributes}->{_start}}},$node;
return $id;
}
=head2 by_start
Function : Fetch an arrayref of nodes start position. If multiple types are given, and
more than one type has a match, the first specified type will be returned
preferentially.
Example : $node_arrayref = by_start('scaf1','-','exon',432);
$node_arrayref = by_start('scaf1','-','mrna|exon',432);
=cut
sub by_start {
my $start = pop;
my $type = pop;
my $strand = pop;
my $seq_name = pop;
if ($type =~ m/\|/){
my @types = split /\|/,$type;
while ($type = shift @types){
return $by_start{$seq_name}{$strand}{$type}{$start} if $by_start{$seq_name}{$strand}{$type};
}
}
return $by_start{$seq_name}{$strand}{$type}{$start} if $type;
return;
}
=head2 nearest_start
Function : Fetch an arrayref of nodes as close as possible to the start position. If
multiple types are given, and more than one type has a closest match, the
first specified type will be returned preferentially.
Example : $node_arrayref = nearest_start('scaf1','exon',432);
=cut
sub nearest_start {
my $start = pop;
my $type = pop;
my $strand = pop;
my $seq_name = pop;
my $prev_begin = 0;
my @types;
if ($type =~ m/\|/){
@types = split /\|/,$type;
}
else {
push @types, $type;
}
while (my $mtype = shift @types){
next unless $by_start{$seq_name}{$strand}{$mtype};
foreach my $begin (sort { $a <=> $b } keys %{$by_start{$seq_name}{$strand}{$mtype}}){
next if $begin < $prev_begin;
last if $begin > $start;
$prev_begin = $begin;
$type = $mtype;
}
}
return $by_start{$seq_name}{$strand}{$type}{$prev_begin};
}
}
# use nesting to allow sub to retain access to private variables
{
my %lacks;
=head2 lacks_id
Function : get/set behaviour for features that lack an id
Example : $gff->lacks_id('region','ignore'); # default
Example : $gff->lacks_id('exon','warn');
Example : $gff->lacks_id('gene','die');
Example : $gff->lacks_id('all','make');
Example : $behaviour = $gff->lacks_id('gene');
=cut
sub lacks_id {
my $node = shift;
my $type = shift || 'all';
my $behaviour = shift;
$type =~ tr/[A-Z]/[a-z]/;
$lacks{$node}{$type} = $behaviour if $behaviour;
return $lacks{$node}{$type} ? $lacks{$node}{$type} : $lacks{$node}{'all'} ? $lacks{$node}{'all'} : 'ignore';
}
}
=head2 undefined_parent
Function : get/set behaviour for features that should have a parent but don't
Example : $gff->undefined_parent('die');
Example : $gff->undefined_parent('make'); # default
Example : $behaviour = $gff->undefined_parent();
=cut
sub undefined_parent {
my $node = shift;
my $behaviour = shift;
$node->{_attributes}->{'_undefined_parent'} = $behaviour if $behaviour;
return $node->{_attributes}->{'_undefined_parent'} ? $node->{_attributes}->{'_undefined_parent'} : 'make';
}
# use nesting to allow sub to retain access to private variables
{
my %features;
my %parents;
=head2 by_type
Function : returns an ordered array of features of a given type
Example : @nodes = $gff->by_type('exon');
=cut
sub by_type {
my ($self, $type) = @_;
$self->order_features($type);
return @{$features{$type}}[ -@{$features{$type}} .. -2 ];;
}
=head2 next_feature
Function : Sequentially fetch daughter features of a node by type
Example : $gene->next_feature('exon');
=cut
sub next_feature {
my ($self, $type) = @_;
unless ($features{$type} && @{$features{$type}} && $parents{$type} && $parents{$type} eq $self->id()){
$self->order_features($type);
}
return shift @{$features{$type}};
}
=head2 order_features
Function : order daughter features of a given type sequentially
Example : $gene->order_feature('exon');
=cut
sub order_features {
my ($self, $type, $strand) = @_;
my @unsorted = by_attribute($self,'_type',$type);
@{$features{$type}} = ($strand && $strand eq '-') ? sort { $b->{attributes}->{_start} <=> $a->{attributes}->{_start} } @unsorted : sort { $a->{attributes}->{_start} <=> $b->{attributes}->{_start} } @unsorted;
push @{$features{$type}},0;
$parents{$type} = $self->id;
return (scalar(@{$features{$type}})-1);
}
=head2 fill_gaps
Function : fill in gaps between features, eg make introns based on exons, should check
whether such features exist before running this (maybe need a fill_gaps_unless sub)
Example : $gene->fill_gaps('exon','intron','internal');
$gene->fill_gaps('exon','utr','external');
$gene->fill_gaps('exon','5utr','before');
$gene->fill_gaps('exon','3utr','after');
=cut
sub fill_gaps {
my ($self, $type, $new_type, $location) = @_;
$self->order_features($type);
my %attributes;
$attributes{'_seq_name'} = $self->{attributes}->{_seq_name};
$attributes{'_source'} = 'GFFTree';
$attributes{'_type'} = $new_type;
$attributes{'_score'} = '.';
$attributes{'_strand'} = $self->{attributes}->{_strand};
$attributes{'_phase'} = '.';
$attributes{'Parent'} = $self->id;
if ($location eq 'internal'){
if (@{$features{$type}} > 2){
for (my $i = 1; $i < @{$features{$type}} - 1; $i++){
$attributes{'_start'} = $features{$type}[($i-1)]->{attributes}->{_end} + 1;
$attributes{'_end'} = $features{$type}[$i]->{attributes}->{_start} - 1;
next if $attributes{'_end'} <= $attributes{'_start'};
my %attr = %attributes;
if (my $feature = $self->find_daughter(\%attr)){
$self->add_daughter($feature);
}
else {
my $node = $self->new_daughter(\%attr);
$node->make_id($new_type);
}
}
}
}
if ($features{$type} > 1){
if ($location eq 'before' || $location eq 'external'){
if ($features{$type}[0]->{attributes}->{_end} < $self->{attributes}->{_end}){
if ($features{$type}[0]->{attributes}->{_strand} eq '-'){
$attributes{'_start'} = $features{$type}[0]->{attributes}->{_end} + 1;
$attributes{'_end'} = $self->{attributes}->{_end};
}
else {
$attributes{'_start'} = $self->{attributes}->{_start};
$attributes{'_end'} = $features{$type}[0]->{attributes}->{_start} - 1;
}
return if $attributes{'_end'} <= $attributes{'_start'};
my %attr = %attributes;
if (my $feature = $self->find_daughter(\%attr)){
$self->add_daughter($feature);
}
else {
my $node = $self->new_daughter(\%attr);
$node->make_id($new_type);
}
}
}
if ($location eq 'after' || $location eq 'external'){
if ($features{$type}[-2]->{attributes}->{_end} < $self->{attributes}->{_end}){
if ($features{$type}[0]->{attributes}->{_strand} eq '-'){
$attributes{'_end'} = $features{$type}[-2]->{attributes}->{_start} - 1;
$attributes{'_start'} = $self->{attributes}->{_start};
}
else {
$attributes{'_end'} = $self->{attributes}->{_end};
$attributes{'_start'} = $features{$type}[-2]->{attributes}->{_end} + 1;
}
return if $attributes{'_end'} <= $attributes{'_start'};
my %attr = %attributes;
if (my $feature = $self->find_daughter(\%attr)){
$self->add_daughter($feature);
}
else {
my $node = $self->new_daughter(\%attr);
$node->make_id($new_type);
}
}
}
}
return;
}
=head2 find_daughter
Function : Find out whether an element already has a daughter with a given set of
attributes
Example : $gene->find_daughter(\%attributes);
=cut
sub find_daughter {
my $self = shift;
my $attributes = shift;
my @possibles = by_start($attributes->{'_seq_name'},$attributes->{'_strand'},$attributes->{'_type'},$attributes->{'_start'});
while (my $feature = shift @possibles){
if ($attributes->{'_end'} == $feature->[0]->{attributes}->{'_end'}){
return $feature->[0];
}
}
return;
}
}
# use nesting to allow subs to share and retain access to private variables
{
my %expectations;
# lookup table for flags
my %actions = ( 'ignore' => \&validation_ignore,
'warn' => \&validation_warning,
'die' => \&validation_die,
'find' => \&validation_find,
'make' => \&validation_make,
'skip' => \&validation_skip,
'force' => \&validation_force,
);
=head2 add_expectation
Function : Specify conditions that feature-types should meet in order to pass validation
expectations can be applied to multiple feature types using the pipe symbol in
$Arg[0]. More documentation to be written...
Example : $gff->add_expectation('mrna','hasParent','gene','find');
=cut
sub add_expectation {
# define expectations for gff validation
# feature_type,relation,alt_type,flag
# flags: ignore, warn, die, find, make, force
# relations: hasParent, hasChild, hasSister, >, gt, <, lt, ==, eq, >=, <=, !=, ne
# mrna hasParent gene
# mrna|exon <[start,end] SELF
# mrna <=[end] PARENT warn
# exon hasParent mrna|transcript|gene
# cds hasSister exon
my ($self,$type,$relation,$alt_type,$flag) = @_;
$type =~ tr/[A-Z]/[a-z]/;
my @type = split /\|/,$type;
for (my $t = 0; $t < @type; $t++){
push @{$expectations{$type[$t]}},{'relation' => $relation, 'alt_type' => $alt_type, 'flag' => $flag} || return;
}
return scalar keys %expectations;
}
=head2 find_sister
Function : find sister features accounting for multiline, nested matching and encompassing
features
Example : $sister = $cds->find_sister('exon');
: $sister = $exon->find_sister('cds');
=cut
sub find_sister {
my $self = shift;
my $alt_type = shift;
my $scale = shift;
my $parent = $self->mother();
my ($sister,$size);
if (!is_multiline($self->{attributes}->{_type}) && !is_multiline($alt_type) ||
is_multiline($self->{attributes}->{_type}) && is_multiline($alt_type)){
while (my $feature = $parent->next_feature($alt_type)){
if ($self->{attributes}->{_start} == $feature->{attributes}->{_start} && $self->{attributes}->{_end} == $feature->{attributes}->{_end}){
# twinSister
$sister = $feature;
$size = 'twin';
last; # match found, don't check any more features
}
elsif ($self->{attributes}->{_start} >= $feature->{attributes}->{_start} && $self->{attributes}->{_end} >= $feature->{attributes}->{_end}){
# littleSister
$sister = $feature;
$size = 'little';
# continue the loop to find a better match (i.e. twin sister)
}
elsif ($self->{attributes}->{_start} >= $feature->{attributes}->{_start} && $self->{attributes}->{_end} <= $feature->{attributes}->{_end}){
# bigSister
$sister = $feature;
$size = 'big';
# continue the loop to find a better match (i.e. twin sister)
}
}
}
elsif (is_multiline($self->{attributes}->{_type}) && !is_multiline($alt_type)){
my @starts = $self->{attributes}->{_start_array} ? @{$self->{attributes}->{_start_array}} : ($self->{attributes}->{_start});
my @ends = $self->{attributes}->{_end_array} ? @{$self->{attributes}->{_end_array}} : ($self->{attributes}->{_end});
for (my $i = 0; $i < @starts; $i++){
my @features = $parent->by_type($alt_type);
while (my $feature = shift @features){
$sister = undef;
if ($starts[$i] == $feature->{attributes}->{_start} && $ends[$i] == $feature->{attributes}->{_end}){
# twinSister
$sister = $feature;
$size = 'twin';
}
elsif ($starts[$i] <= $feature->{attributes}->{_start} && $ends[$i] >= $feature->{attributes}->{_end}){
# littleSister
$sister = $feature;
$size = 'little';
}
elsif ($starts[$i] >= $feature->{attributes}->{_start} && $ends[$i] <= $feature->{attributes}->{_end}){
# bigSister
$sister = $feature;
$size = 'big';
}
last if $sister; # # match found for this part of the multiline feature, don't check any more features
}
last unless $sister; # all parts of the multiline feature must have a match
}
}
else { # !is_multiline($self->{attributes}->{_type}) and is_multiline($alt_type)
my @features = $parent->by_type($alt_type);
while (my $feature = shift @features){
my @starts = $feature->{attributes}->{_start_array} ? @{$feature->{attributes}->{_start_array}} : ($feature->{attributes}->{_start});
my @ends = $feature->{attributes}->{_end_array} ? @{$feature->{attributes}->{_end_array}} : ($feature->{attributes}->{_end});
for (my $i = 0; $i < @starts; $i++){
$sister = undef;
if ($starts[$i] == $self->{attributes}->{_start} && $ends[$i] == $self->{attributes}->{_end}){
# twinSister
$sister = $feature;
$size = 'twin';
}
elsif ($starts[$i] <= $self->{attributes}->{_start} && $ends[$i] >= $self->{attributes}->{_end}){
# littleSister
$sister = $feature;
$size = 'big';
}
elsif ($starts[$i] >= $self->{attributes}->{_start} && $ends[$i] <= $self->{attributes}->{_end}){
# bigSister
$sister = $feature;
$size = 'little';
}
last if $sister; # match found for this part of the multiline feature, don't check any more features
}
last unless $sister; # all parts of the multiline feature must have a match
}
}
return $sister;
}
=head2 make_sister
Function : make sister features accounting for multiline and single line interactions
Example : $sister = $cds->make_sister('exon');
: $sister = $exon->make_sister('cds');
=cut
sub make_sister {
my $self = shift;
my $alt_type = shift;
my $parent = $self->mother();
my $sister;
my @attributes = ('_seq_name','_source','_start','_end','_score','_strand','_phase','Parent');
if (is_multiline($self->{attributes}->{_type}) && is_multiline($alt_type) ||
!is_multiline($self->{attributes}->{_type}) && !is_multiline($alt_type)){
$sister = $self->copy({no_attribute_copy => 1});
foreach my $attribute (@attributes){
$sister->{attributes}->{$attribute} = $self->{attributes}->{$attribute};
if ($self->{attributes}->{$attribute.'_array'}){
$sister->{attributes}->{$attribute.'_array'} = $self->{attributes}->{$attribute.'_array'};
}
}
$parent->add_daughter($sister);
$sister->{attributes}->{_type} = $alt_type;
$sister->make_id($alt_type);
$sister->{attributes}->{Name} = $sister->name();
}
elsif (is_multiline($self->{attributes}->{_type}) && !is_multiline($alt_type)){
my @starts = $self->{attributes}->{_start_array} ? @{$self->{attributes}->{_start_array}} : ($self->{attributes}->{_start});
my @ends = $self->{attributes}->{_end_array} ? @{$self->{attributes}->{_end_array}} : ($self->{attributes}->{_end});
for (my $i = 0; $i < @starts; $i++){
my @features = $parent->by_type($alt_type);
while (my $feature = shift @features){
$sister = undef;
if ($starts[$i] == $feature->{attributes}->{_start} && $ends[$i] == $feature->{attributes}->{_end}){
# twinSister
$sister = $feature;
}
elsif ($starts[$i] <= $feature->{attributes}->{_start} && $ends[$i] >= $feature->{attributes}->{_end}){
# littleSister
$sister = $feature;
}
elsif ($starts[$i] >= $feature->{attributes}->{_start} && $ends[$i] <= $feature->{attributes}->{_end}){