Search code examples
c++boostgraphml

boost read_graphml discards the nodes' id


I am trying to read a graphml file using the BGL library. I can successfully read the file and gathers the properties linked to each node.

However the node entries in my graphml file also have a non trivial id I would like to retrieve. The best would be to be able to use this string id as a node index, but that may not be achievable due to the fact that would put a constraint on the VertexList further than being a container. So, at the very least, I would like the id information to be preserved and to be able to access it. When writing the graph immediately after, the node ids are replaced by "n0", "n1",... which hints me towards thinking that boost doesn't keep the node id information. Is that really so? Did I miss something?

Below is the code I use:

struct VertexProperty
{
    std::string name ;
};


typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, VertexProperty, boost::no_property> Graph;


int main(){
    std::ifstream inFile;
    inFile.open("in.graphml", std::ifstream::in);
    if(!inFile.good()){
        std::cout << "could not open file" << std::endl;
        return 1;
    }
    Graph g;
    boost::dynamic_properties dp(boost::ignore_other_properties);
    dp.property("name", boost::get(&VertexProperty::name, g));
    boost::read_graphml(inFile, g, dp);
    std::cout << boost::num_vertices(g) << std::endl;
    std::cout << g[0].name  << std::endl;  // I can access the node indexed by 0 properties like this
    std::cout << get(&VertexProperty::name, g, 0) << std::endl;  // I can retrieve a property value like that as well
    std::cout << get(boost::vertex_index, g, 0) << std::endl;  // doesn't give me the node id unfortunately
    std::ofstream out("out.graphml", std::ofstream::out);
    boost::write_graphml(out, g, dp);
    return 0;
}

Solution

  • Ok I found a simple enough solution: modify the graphml.cc code, and treat the nodes' id as a property. Which means:

    • add "id" to the possible node properties in run:

    m_keys["id"] = node_key; m_key_type["id"] = "string"; m_key_name["id"] = "id";

    • add the node's id to the dynamic properties when a new node is found in handle_vertex

    handle_node_property("id", v, v);