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