Manually colouring of boost's graphs

前端 未结 1 471
遇见更好的自我
遇见更好的自我 2021-01-25 18:07

I\'m struggling trying to manually colouring graph\'s vertices using boost. I wrote the code below but I can\'t figure it out why the generated file does not have any colour.

1条回答
  •  花落未央
    2021-01-25 18:42

    Vertex colourings are really an algorithmic detail. There is no "automatic" provision to translate it to graphviz, as far as I know.

    You can add custom attributes though.

    I'd usually change it around to use dynamic properties:

    std::ofstream outf("example.gv");
    
    dynamic_properties dp;
    dp.property("node_id", get(vertex_index, g));
    dp.property("label", vertex_label);
    dp.property("label", edge_label);
    
    write_graphviz_dp(outf, g, dp);
    

    Now it's as simple as adding a new vertex attribute to the dynamic set:

    dp.property("color", make_transform_value_property_map(&color_to_string, color_map));
    

    The only complication is that you need to supply the conversion from default_color_type to text. This is another symptom of the fact that the color maps aren't usually used for representational purposes. Here's a fully working sample:

    Live On Coliru

    #include 
    #include 
    #include 
    using namespace boost;
    
    inline char const* color_to_string(default_color_type c) {
        switch(c) {
            case default_color_type::red_color:   return "red";
            case default_color_type::green_color: return "green";
            case default_color_type::gray_color:  return "gray";
            case default_color_type::white_color: return "white";
            case default_color_type::black_color: return "black";
        }
        return ""; // not known
    }
    
    
    int main() {
        typedef property EdgeProperties;
        typedef property> VertexProperties;
        typedef adjacency_list Graph;
        typedef graph_traits::vertex_descriptor Vertex;
    
        Graph g;
        property_map::type vertex_label = get(vertex_name, g);
        property_map::type color_map = get(vertex_color, g);
        property_map::type edge_label = get(edge_name, g);
    
        Vertex v1 = add_vertex(g);
        vertex_label[v1] = "v1";
    
        put(color_map, v1, boost::red_color);
    
        dynamic_properties dp;
        dp.property("node_id", get(vertex_index, g));
        dp.property("label", vertex_label);
        dp.property("label", edge_label);
        dp.property("color", make_transform_value_property_map(&color_to_string, color_map));
    
        write_graphviz_dp(std::cout, g, dp);
    }
    

    Prints:

    digraph G {
    0 [color=red, label=v1];
    }
    

    0 讨论(0)
提交回复
热议问题