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