06f2c8f3c60f396980d5762cf297a449cac2066c
[migration-tools.git] / cleanup_merge_map.pl
1 #!/usr/bin/perl
2
3 # Copyright 2011-2014, Equinox Software, Inc.
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 use strict;
20 use warnings;
21
22 =head1 NAME
23
24 cleanup_merge_map.pl
25
26 =head2 SUMMARY
27
28 Little helper script used when consoldating
29 multiple merge maps.
30
31 =cut
32
33 my %leads = ();
34
35 # load merge map
36 while (<>) {
37     chomp;
38     my ($lead, $sub) = split /\t/, $_, -1;
39     $leads{$sub}->{$lead}++; 
40 }
41
42 # run this twice to ensure that cycles are
43 # excluded
44 cleanup_map() foreach (1..2);
45
46 foreach my $sub (sort numerically keys %leads) {
47     if (1 == keys(%{ $leads{$sub} })) {
48         print join("\t", keys($leads{$sub}), $sub), "\n";
49     }
50 }
51
52 sub cleanup_map {
53     foreach my $sub (keys %leads) {
54         my @leads_to_prune = ();
55         my @leads_to_add = ();
56         foreach my $lead (keys %{ $leads{$sub} }) {
57             if (exists($leads{$lead})) {
58                 # lead bib itself is slated to be merged,
59                 # so it's no longer going to be the direct
60                 # lead for the current sub
61                 push @leads_to_prune, $lead;
62
63                 # the current sub gets potential
64                 # leads from its previous lead
65                 foreach my $second_lead (keys %{ $leads{$lead} }) {
66                     push @leads_to_add, $second_lead unless exists($leads{$sub}->{$second_lead});
67                 }
68             }
69         }
70         delete($leads{$sub}->{$_}) foreach @leads_to_prune;
71         $leads{$sub}->{$_}++ foreach @leads_to_add;
72     }
73 }
74
75 sub numerically {
76     return $a <=> $b;
77 }