c29f78a0a1211116754f49d128c6e7b39ab4d3d4
[scpubgit/stemmatology.git] / lib / Text / Tradition / Parser / GraphML.pm
1 package Text::Tradition::Parser::GraphML;
2
3 use strict;
4 use warnings;
5 use XML::LibXML;
6 use XML::LibXML::XPathContext;
7
8 =head1 NAME
9
10 Text::Tradition::Parser::GraphML
11
12 =head1 DESCRIPTION
13
14 Parser module for Text::Tradition, given a GraphML file that describes
15 a collation graph.  Returns the information about the graph that has
16 been parsed out from the GraphML.  This module is meant to be used
17 with a module (e.g. CollateX or Self) that interprets the specific
18 GraphML conventions of the source program.
19
20 =head1 METHODS
21
22 =over
23
24 =item B<parse>
25
26 parse( $init_opts );
27
28 Takes a set of Tradition initialization options, among which should be either
29 'file' or 'string'; parses that file or string and returns a list of nodes, edges,
30 and their associated data.
31
32 =cut
33
34 use vars qw/ $xpc $graphattr $nodedata $witnesses /;
35
36 # Return graph -> nodeid -> { key1/val1, key2/val2, key3/val3 ... }
37 #              -> edgeid -> { source, target, wit1/val1, wit2/val2 ...}
38
39 sub parse {
40     my( $opts ) = @_;
41
42     my $graph_hash = { 'nodes' => [],
43                        'edges' => [] };
44
45     my $parser = XML::LibXML->new();
46     my $doc;
47     if( exists $opts->{'string'} ) {
48         $doc = $parser->parse_string( $opts->{'string'} );
49     } elsif ( exists $opts->{'file'} ) {
50         $doc = $parser->parse_file( $opts->{'file'} );
51     } else {
52         warn "Could not find string or file option to parse";
53         return;
54     }
55     
56     my $graphml = $doc->documentElement();
57     $xpc = XML::LibXML::XPathContext->new( $graphml );
58     $xpc->registerNs( 'g', 'http://graphml.graphdrawing.org/xmlns' );
59     
60     # First get the ID keys, for witnesses and for collation data
61     foreach my $k ( $xpc->findnodes( '//g:key' ) ) {
62         # Each key has a 'for' attribute; the edge keys are witnesses, and
63         # the node keys contain an ID and string for each node.
64         my $keyid = $k->getAttribute( 'id' );
65         my $keyname = $k->getAttribute( 'attr.name' );
66
67                 # Keep track of the XML identifiers for the data carried
68                 # in each node element.
69                 my $dtype = $k->getAttribute( 'for' );
70                 if( $dtype eq 'graph' ) {
71                         $graphattr->{$keyid} = $keyname;
72         } elsif( $dtype eq 'node' ) {
73             $nodedata->{$keyid} = $keyname;
74         } else {
75             $witnesses->{$keyid} = $keyname;
76         }
77     }
78
79     my $graph_el = $xpc->find( '/g:graphml/g:graph' )->[0];
80
81     my $node_reg = {};
82     
83     # Read in graph globals (if any).
84     print STDERR "Reading graphml global data\n";
85     foreach my $dkey ( keys %$graphattr ) {
86         my $keyname = $graphattr->{$dkey};
87         my $keyvalue = _lookup_node_data( $graph_el, $dkey );
88         $graph_hash->{'global'}->{$keyname} = $keyvalue;
89     }
90
91     # Add the nodes to the graph hash.
92     print STDERR "Reading graphml nodes\n"; 
93     my @nodes = $xpc->findnodes( '//g:node' );
94     foreach my $n ( @nodes ) {
95         # Could use a better way of registering these
96         my $node_hash = {};
97         foreach my $dkey ( keys %$nodedata ) {
98             my $keyname = $nodedata->{$dkey};
99             my $keyvalue = _lookup_node_data( $n, $dkey );
100             $node_hash->{$keyname} = $keyvalue if defined $keyvalue;
101         }
102         $node_reg->{$n->getAttribute( 'id' )} = $node_hash;
103         push( @{$graph_hash->{'nodes'}}, $node_hash );
104     }
105         
106     # Now add the edges, and cross-ref with the node objects.
107     print STDERR "Reading graphml edges\n";
108     my @edges = $xpc->findnodes( '//g:edge' );
109     foreach my $e ( @edges ) {
110         my $from = $e->getAttribute('source');
111         my $to = $e->getAttribute('target');
112
113         # We don't know whether the edge data is one per witness
114         # or one per witness type, or something else.  So we just
115         # save it and let our calling parser decide.
116         my $edge_hash = {
117             'source' => $node_reg->{$from},
118             'target' => $node_reg->{$to},
119         };
120         foreach my $wkey( keys %$witnesses ) {
121             my $wname = $witnesses->{$wkey};
122             my $wlabel = _lookup_node_data( $e, $wkey );
123             $edge_hash->{$wname} = $wlabel if $wlabel;
124         }
125         push( @{$graph_hash->{'edges'}}, $edge_hash );
126     }
127     return $graph_hash;
128 }
129
130 sub _lookup_node_data {
131     my( $xmlnode, $key ) = @_;
132     my $lookup_xpath = './g:data[@key="%s"]/child::text()';
133     my $data = $xpc->find( sprintf( $lookup_xpath, $key ), $xmlnode );
134     # If we get back an empty nodelist, we return undef.
135     if( ref( $data ) ) {
136         return undef unless $data->size;
137         return $data->to_literal->value;
138     }
139     # Otherwise we got back a value. Return it.
140     return $data;
141 }
142     
143 =back
144
145 =head1 LICENSE
146
147 This package is free software and is provided "as is" without express
148 or implied warranty.  You can redistribute it and/or modify it under
149 the same terms as Perl itself.
150
151 =head1 AUTHOR
152
153 Tara L Andrews, aurum@cpan.org
154
155 =cut
156
157 1;