Good luck (*) with IntervalTree.
The idea is that you insert your items in a tree, their interval being the discriminating characteristic.
Traversing the tree will be in the same order as if you lined up all those intervals (on a line).
In traverse()'s order, calculate distance between an item's "before" and "after" neighbour and develop the logic to merge them or not.
Here is a quick demo, notice the line-up of the items at the end:
#!/usr/bin/perl # # author: Bliako # date: 10/09/2018 # for: https://perlmonks.org/?node_id=1222031 # use strict; use warnings; use IntervalTree; use Data::Dumper; # create the tree my $tree = IntervalTree->new(); while(<DATA>){ chomp; next if $_ =~ /^\s*$/; my @items = split /\s+/; $tree->insert(@items[1,2,3]); } close(DATA); print_tree($tree); # print all the intervals sub print_tree { my $atree = shift; $atree->traverse( # specify a func to be run on every node as returned b +y traverse() sub { my $anode = $_[0]; print "traverse() : ".$anode->{interval}." => +".$anode->str()."\n"; } ); } __DATA__ Chr1 30000 32000 A3 Chr1 28000 29000 B2 Chr1 12000 18500 B1 Chr1 1000 4000 A1 Chr1 42000 44000 A4 Chr1 15000 22000 A2
Result:
traverse() : (A1) => Node(1000, 4000) traverse() : (B1) => Node(12000, 18500) traverse() : (A2) => Node(15000, 22000) traverse() : (B2) => Node(28000, 29000) traverse() : (A3) => Node(30000, 32000) traverse() : (A4) => Node(42000, 44000)
(*) : personally I found this module very frustrating to work with as it mixes together Node objects, Interval objects and Interval names. I had to modify the source of _seek_left and _seek_right to save $self rather than $self->{interval}. But for your modest need, the above will do nicely. There are even worst alternatives, search at cpan.
If you are a Bioinformatician and have more serious bioinformatics needs I am available for hire - in the spirit of appeasing and keeping content the general anonymous public. If you are not, well I can always help for free when I can as I always do.
bw, bliako
Edit - Clarification: my program lines up all your items in a line wrt their intervals (compare Result above and your sample output A1, B1, A2, B2, A3, A4.). The program will not do the merging as I was too lazy to read your requirements and translate to code. Now all you have to do is to check each item with its 2 or 4 neighbours (for when A neighbours A) following your rules. The important thing is that the "line-up" is done using the Interval Tree in O(n log n) time and will persist for classifying unknown intervals too.
In reply to Re: Merging intervals; Chaining intervals
by bliako
in thread Merging intervals; Chaining intervals
by onlyIDleft
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |