Parse a known stemma hypothesis from a dotfile
[scpubgit/stemmatology.git] / lib / Text / Tradition / Stemma.pm
1 package Text::Tradition::Stemma;
2
3 use File::chdir;
4 use File::Temp;
5 use IPC::Run qw/ run /;
6 use Moose;
7 use Text::Tradition::Collation::Position;
8 use Graph;
9 use Graph::Reader::Dot;
10
11 has collation => (
12     is => 'ro',
13     isa => 'Text::Tradition::Collation',
14     required => 1,
15     );  
16
17 has character_matrix => (
18     is => 'ro',
19     isa => 'ArrayRef[ArrayRef[Str]]',
20     writer => '_save_character_matrix',
21     predicate => 'has_character_matrix',
22     );
23     
24 has graph => (
25     is => 'rw',
26     isa => 'Graph',
27     predicate => 'has_graph',
28     );
29     
30 has apsp => (
31     is => 'rw',
32     isa => 'Graph',
33     );
34         
35 sub BUILD {
36     my( $self, $args ) = @_;
37     # If we have been handed a dotfile, initialize it into a graph.
38     if( exists $args->{'dot'} ) {
39         my $reader = Graph::Reader::Dot->new();
40         my $graph = $reader->read_graph( $args->{'dot'} );
41         $graph 
42             ? $self->graph( $graph ) 
43             : warn "Failed to parse dot file " . $args->{'dot'};
44     }
45     
46     # If we have a graph, calculate all the shortest paths between nodes,
47     # disregarding direction.
48     if( $self->has_graph ) {
49         my $undirected;
50         if( $self->graph->is_directed ) {
51             # Make an undirected version.
52             $undirected = Graph->new( 'undirected' => 1 );
53             foreach my $v ( $self->graph->vertices ) {
54                 $undirected->add_vertex( $v );
55             }
56             foreach my $e ( $self->graph->edges ) {
57                 $undirected->add_edge( @$e );
58             }
59         } else {
60             $undirected = $self->graph;
61         }
62         $self->apsp( $undirected->APSP_Floyd_Warshall() );
63     }
64 }
65         
66         
67 sub make_character_matrix {
68     my $self = shift;
69     unless( $self->collation->linear ) {
70         warn "Need a linear graph in order to make an alignment table";
71         return;
72     }
73     my $table = $self->collation->make_alignment_table;
74     # Push the names of the witnesses to initialize the rows of the matrix.
75     my @matrix = map { [ $self->_normalize_ac( $_ ) ] } @{$table->[0]};
76     $DB::single = 1;
77     foreach my $token_index ( 1 .. $#{$table} ) {
78         # First implementation: make dumb alignment table, caring about
79         # nothing except which reading is in which position.
80         my @chars = convert_characters( $table->[$token_index] );
81         foreach my $idx ( 0 .. $#matrix ) {
82             push( @{$matrix[$idx]}, $chars[$idx] );
83         }
84     }
85     $self->_save_character_matrix( \@matrix );
86
87
88 sub _normalize_ac {
89     my( $self, $witname ) = @_;
90     my $ac = $self->collation->ac_label;
91     if( $witname =~ /(.*)\Q$ac\E$/ ) {
92         $witname = $1 . '_ac';
93     }
94     return sprintf( "%-10s", $witname );
95 }
96
97 sub convert_characters {
98     my $row = shift;
99     # This is a simple algorithm that treats every reading as different.
100     # Eventually we will want to be able to specify how relationships
101     # affect the character matrix.
102     my %unique = ( '__UNDEF__' => 'X',
103                    '#LACUNA#'  => '?',
104                  );
105     my $ctr = 0;
106     foreach my $word ( @$row ) {
107         if( $word && !exists $unique{$word} ) {
108             $unique{$word} = chr( 65 + $ctr );
109             $ctr++;
110         }
111     }
112     if( scalar( keys %unique ) > 8 ) {
113         warn "Have more than 8 variants on this location; pars will break";
114     }
115     my @chars = map { $_ ? $unique{$_} : $unique{'__UNDEF__' } } @$row;
116     return @chars;
117 }
118
119 sub pars_input {
120     my $self = shift;
121     $self->make_character_matrix unless $self->has_character_matrix;
122     my $matrix = '';
123     my $rows = scalar @{$self->character_matrix};
124     my $columns = scalar @{$self->character_matrix->[0]} - 1;
125     $matrix .= "\t$rows\t$columns\n";
126     foreach my $row ( @{$self->character_matrix} ) {
127         $matrix .= join( '', @$row ) . "\n";
128     }
129     return $matrix;
130 }
131
132 sub run_pars {
133     my $self = shift;
134
135     # Set up a temporary directory for all the default Phylip files.
136     my $phylip_dir = File::Temp->newdir();
137     print STDERR $phylip_dir . "\n";
138     # $phylip_dir->unlink_on_destroy(0);
139     # We need an infile, and we need a command input file.
140     open( MATRIX, ">$phylip_dir/infile" ) or die "Could not write $phylip_dir/infile";
141     print MATRIX $self->pars_input();
142     close MATRIX;
143
144     open( CMD, ">$phylip_dir/cmdfile" ) or die "Could not write $phylip_dir/cmdfile";
145     ## TODO any configuration parameters we want to set here
146 #   U                 Search for best tree?  Yes
147 #   S                        Search option?  More thorough search
148 #   V              Number of trees to save?  100
149 #   J     Randomize input order of species?  No. Use input order
150 #   O                        Outgroup root?  No, use as outgroup species 1
151 #   T              Use Threshold parsimony?  No, use ordinary parsimony
152 #   W                       Sites weighted?  No
153 #   M           Analyze multiple data sets?  No
154 #   I            Input species interleaved?  Yes
155 #   0   Terminal type (IBM PC, ANSI, none)?  ANSI
156 #   1    Print out the data at start of run  No
157 #   2  Print indications of progress of run  Yes
158 #   3                        Print out tree  Yes
159 #   4          Print out steps in each site  No
160 #   5  Print character at all nodes of tree  No
161 #   6       Write out trees onto tree file?  Yes
162     print CMD "Y\n";
163     close CMD;
164
165     # And then we run the program.
166     ### HACKY HACKY
167     my $PHYLIP_PATH = '/Users/tla/Projects/phylip-3.69/exe';
168     my $program = "pars";
169     if( $^O eq 'darwin' ) {
170         $program = "$PHYLIP_PATH/$program.app/Contents/MacOS/$program";
171     } else {
172         $program = "$PHYLIP_PATH/$program";
173     }
174
175     {
176         # We need to run it in our temporary directory where we have created
177         # all the expected files.
178         local $CWD = $phylip_dir;
179         my @cmd = ( $program );
180         run \@cmd, '<', 'cmdfile', '>', '/dev/null';
181     }
182     # Now our output should be in 'outfile' and our tree in 'outtree',
183     # both in the temp directory.
184
185     my @outtree;
186     if( -f "$phylip_dir/outtree" ) {
187         open( TREE, "$phylip_dir/outtree" ) or die "Could not open outtree for read";
188         @outtree = <TREE>;
189         close TREE;
190     }
191     return( 1, join( '', @outtree ) ) if @outtree;
192
193     my @error;
194     if( -f "$phylip_dir/outfile" ) {
195         open( OUTPUT, "$phylip_dir/outfile" ) or die "Could not open output for read";
196         @error = <OUTPUT>;
197         close OUTPUT;
198     } else {
199         push( @error, "Neither outtree nor output file was produced!" );
200     }
201     return( undef, join( '', @error ) );
202 }
203
204 no Moose;
205 __PACKAGE__->meta->make_immutable;
206     
207 1;