source: NonGTP/Boost/boost/graph/isomorphism.hpp @ 857

Revision 857, 18.2 KB checked in by igarcia, 18 years ago (diff)
Line 
1// Copyright (C) 2001 Jeremy Siek, Douglas Gregor, Brian Osman
2//
3// Permission to copy, use, sell and distribute this software is granted
4// provided this copyright notice appears in all copies.
5// Permission to modify the code and to distribute modified code is granted
6// provided this copyright notice appears in all copies, and a notice
7// that the code was modified is included with the copyright notice.
8//
9// This software is provided "as is" without express or implied warranty,
10// and with no claim as to its suitability for any purpose.
11#ifndef BOOST_GRAPH_ISOMORPHISM_HPP
12#define BOOST_GRAPH_ISOMORPHISM_HPP
13
14#include <utility>
15#include <vector>
16#include <iterator>
17#include <algorithm>
18#include <boost/config.hpp>
19#include <boost/graph/depth_first_search.hpp>
20#include <boost/utility.hpp>
21#include <boost/detail/algorithm.hpp>
22#include <boost/pending/indirect_cmp.hpp> // for make_indirect_pmap
23
24#ifndef BOOST_GRAPH_ITERATION_MACROS_HPP
25#define BOOST_ISO_INCLUDED_ITER_MACROS // local macro, see bottom of file
26#include <boost/graph/iteration_macros.hpp>
27#endif
28
29namespace boost {
30
31  namespace detail {
32
33    template <typename Graph1, typename Graph2, typename IsoMapping,
34      typename Invariant1, typename Invariant2,
35      typename IndexMap1, typename IndexMap2>
36    class isomorphism_algo
37    {
38      typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_t;
39      typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
40      typedef typename graph_traits<Graph1>::edge_descriptor edge1_t;
41      typedef typename graph_traits<Graph1>::vertices_size_type size_type;
42      typedef typename Invariant1::result_type invar1_value;
43      typedef typename Invariant2::result_type invar2_value;
44   
45      const Graph1& G1;
46      const Graph2& G2;
47      IsoMapping f;
48      Invariant1 invariant1;
49      Invariant2 invariant2;
50      std::size_t max_invariant;
51      IndexMap1 index_map1;
52      IndexMap2 index_map2;
53   
54      std::vector<vertex1_t> dfs_vertices;
55      typedef typename std::vector<vertex1_t>::iterator vertex_iter;
56      std::vector<int> dfs_num_vec;
57      typedef safe_iterator_property_map<typename std::vector<int>::iterator,
58                                         IndexMap1
59#ifdef BOOST_NO_STD_ITERATOR_TRAITS
60                                         , int, int&
61#endif /* BOOST_NO_STD_ITERATOR_TRAITS */
62                                         > DFSNumMap;
63      DFSNumMap dfs_num;
64      std::vector<edge1_t> ordered_edges;
65      typedef typename std::vector<edge1_t>::iterator edge_iter;
66   
67      std::vector<char> in_S_vec;
68      typedef safe_iterator_property_map<typename std::vector<char>::iterator,
69                                         IndexMap2
70#ifdef BOOST_NO_STD_ITERATOR_TRAITS
71                                         , char, char&
72#endif /* BOOST_NO_STD_ITERATOR_TRAITS */
73                                         > InSMap;
74      InSMap in_S;
75   
76      int num_edges_on_k;
77   
78      friend struct compare_multiplicity;
79      struct compare_multiplicity
80      {
81        compare_multiplicity(Invariant1 invariant1, size_type* multiplicity)
82          : invariant1(invariant1), multiplicity(multiplicity) { }
83        bool operator()(const vertex1_t& x, const vertex1_t& y) const {
84          return multiplicity[invariant1(x)] < multiplicity[invariant1(y)];
85        }
86        Invariant1 invariant1;
87        size_type* multiplicity;
88      };
89   
90      struct record_dfs_order : default_dfs_visitor
91      {
92        record_dfs_order(std::vector<vertex1_t>& v, std::vector<edge1_t>& e)
93          : vertices(v), edges(e) { }
94   
95        void discover_vertex(vertex1_t v, const Graph1&) const {
96          vertices.push_back(v);
97        }
98        void examine_edge(edge1_t e, const Graph1& G1) const {
99          edges.push_back(e);
100        }
101        std::vector<vertex1_t>& vertices;
102        std::vector<edge1_t>& edges;
103      };
104   
105      struct edge_cmp {
106        edge_cmp(const Graph1& G1, DFSNumMap dfs_num)
107          : G1(G1), dfs_num(dfs_num) { }
108        bool operator()(const edge1_t& e1, const edge1_t& e2) const {
109          using namespace std;
110          int u1 = dfs_num[source(e1,G1)], v1 = dfs_num[target(e1,G1)];
111          int u2 = dfs_num[source(e2,G1)], v2 = dfs_num[target(e2,G1)];
112          int m1 = (max)(u1, v1);
113          int m2 = (max)(u2, v2);
114          // lexicographical comparison
115          return std::make_pair(m1, std::make_pair(u1, v1))
116            < std::make_pair(m2, std::make_pair(u2, v2));
117        }
118        const Graph1& G1;
119        DFSNumMap dfs_num;
120      };
121   
122    public:
123      isomorphism_algo(const Graph1& G1, const Graph2& G2, IsoMapping f,
124                       Invariant1 invariant1, Invariant2 invariant2, std::size_t max_invariant,
125                       IndexMap1 index_map1, IndexMap2 index_map2)
126        : G1(G1), G2(G2), f(f), invariant1(invariant1), invariant2(invariant2),
127          max_invariant(max_invariant),
128          index_map1(index_map1), index_map2(index_map2)
129      {
130        in_S_vec.resize(num_vertices(G1));
131        in_S = make_safe_iterator_property_map
132          (in_S_vec.begin(), in_S_vec.size(), index_map2
133#ifdef BOOST_NO_STD_ITERATOR_TRAITS
134           , in_S_vec.front()
135#endif /* BOOST_NO_STD_ITERATOR_TRAITS */
136           );
137      }
138   
139      bool test_isomorphism()
140      {
141        {
142          std::vector<invar1_value> invar1_array;
143          BGL_FORALL_VERTICES_T(v, G1, Graph1)
144            invar1_array.push_back(invariant1(v));
145          sort(invar1_array);
146       
147          std::vector<invar2_value> invar2_array;
148          BGL_FORALL_VERTICES_T(v, G2, Graph2)
149            invar2_array.push_back(invariant2(v));
150          sort(invar2_array);
151          if (! equal(invar1_array, invar2_array))
152            return false;
153        }
154       
155        std::vector<vertex1_t> V_mult;
156        BGL_FORALL_VERTICES_T(v, G1, Graph1)
157          V_mult.push_back(v);
158        {
159          std::vector<size_type> multiplicity(max_invariant, 0);
160          BGL_FORALL_VERTICES_T(v, G1, Graph1)
161            ++multiplicity[invariant1(v)];
162          sort(V_mult, compare_multiplicity(invariant1, &multiplicity[0]));
163        }
164       
165        std::vector<default_color_type> color_vec(num_vertices(G1));
166        safe_iterator_property_map<std::vector<default_color_type>::iterator,
167                                   IndexMap1
168#ifdef BOOST_NO_STD_ITERATOR_TRAITS
169                                   , default_color_type, default_color_type&
170#endif /* BOOST_NO_STD_ITERATOR_TRAITS */
171                                   >
172          color_map(color_vec.begin(), color_vec.size(), index_map1);
173        record_dfs_order dfs_visitor(dfs_vertices, ordered_edges);
174        typedef color_traits<default_color_type> Color;
175        for (vertex_iter u = V_mult.begin(); u != V_mult.end(); ++u) {
176          if (color_map[*u] == Color::white()) {
177            dfs_visitor.start_vertex(*u, G1);
178            depth_first_visit(G1, *u, dfs_visitor, color_map);
179          }
180        }
181        // Create the dfs_num array and dfs_num_map
182        dfs_num_vec.resize(num_vertices(G1));
183        dfs_num = make_safe_iterator_property_map(dfs_num_vec.begin(),
184                                                  dfs_num_vec.size(),
185                                                  index_map1
186#ifdef BOOST_NO_STD_ITERATOR_TRAITS
187                                                  , dfs_num_vec.front()
188#endif /* BOOST_NO_STD_ITERATOR_TRAITS */
189                                                  );
190        size_type n = 0;
191        for (vertex_iter v = dfs_vertices.begin(); v != dfs_vertices.end(); ++v)
192          dfs_num[*v] = n++;
193       
194        sort(ordered_edges, edge_cmp(G1, dfs_num));
195       
196   
197        int dfs_num_k = -1;
198        return this->match(ordered_edges.begin(), dfs_num_k);
199      }
200   
201    private:
202      bool match(edge_iter iter, int dfs_num_k)
203      {
204        if (iter != ordered_edges.end()) {
205          vertex1_t i = source(*iter, G1), j = target(*iter, G2);
206          if (dfs_num[i] > dfs_num_k) {
207            vertex1_t kp1 = dfs_vertices[dfs_num_k + 1];
208            BGL_FORALL_VERTICES_T(u, G2, Graph2) {
209              if (invariant1(kp1) == invariant2(u) && in_S[u] == false) {
210                f[kp1] = u;
211                in_S[u] = true;
212                num_edges_on_k = 0;
213               
214                if (match(iter, dfs_num_k + 1))
215#if 0
216                    // dwa 2003/7/11 -- this *HAS* to be a bug!
217                    ;
218#endif
219                    return true;
220                   
221                in_S[u] = false;
222              }
223            }
224               
225          }
226          else if (dfs_num[j] > dfs_num_k) {
227            vertex1_t k = dfs_vertices[dfs_num_k];
228            num_edges_on_k -=
229              count_if(adjacent_vertices(f[k], G2), make_indirect_pmap(in_S));
230               
231            for (int jj = 0; jj < dfs_num_k; ++jj) {
232              vertex1_t j = dfs_vertices[jj];
233              num_edges_on_k -= count(adjacent_vertices(f[j], G2), f[k]);
234            }
235               
236            if (num_edges_on_k != 0)
237              return false;
238            BGL_FORALL_ADJ_T(f[i], v, G2, Graph2)
239              if (invariant2(v) == invariant1(j) && in_S[v] == false) {
240                f[j] = v;
241                in_S[v] = true;
242                num_edges_on_k = 1;
243                BOOST_USING_STD_MAX();
244                int next_k = max BOOST_PREVENT_MACRO_SUBSTITUTION(dfs_num_k, max BOOST_PREVENT_MACRO_SUBSTITUTION(dfs_num[i], dfs_num[j]));
245                if (match(next(iter), next_k))
246                  return true;
247                in_S[v] = false;
248              }
249               
250               
251          }
252          else {
253            if (contains(adjacent_vertices(f[i], G2), f[j])) {
254              ++num_edges_on_k;
255              if (match(next(iter), dfs_num_k))
256                return true;
257            }
258               
259          }
260        } else
261          return true;
262        return false;
263      }
264   
265    };
266
267   
268    template <typename Graph, typename InDegreeMap>
269    void compute_in_degree(const Graph& g, InDegreeMap in_degree_map)
270    {
271      BGL_FORALL_VERTICES_T(v, g, Graph)
272        put(in_degree_map, v, 0);
273
274      BGL_FORALL_VERTICES_T(u, g, Graph)
275        BGL_FORALL_ADJ_T(u, v, g, Graph)
276        put(in_degree_map, v, get(in_degree_map, v) + 1);
277    }
278
279  } // namespace detail
280
281
282  template <typename InDegreeMap, typename Graph>
283  class degree_vertex_invariant
284  {
285    typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
286    typedef typename graph_traits<Graph>::degree_size_type size_type;
287  public:
288    typedef vertex_t argument_type;
289    typedef size_type result_type;
290
291    degree_vertex_invariant(const InDegreeMap& in_degree_map, const Graph& g)
292      : m_in_degree_map(in_degree_map), m_g(g) { }
293
294    size_type operator()(vertex_t v) const {
295      return (num_vertices(m_g) + 1) * out_degree(v, m_g)
296        + get(m_in_degree_map, v);
297    }
298    // The largest possible vertex invariant number
299    size_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const {
300      return num_vertices(m_g) * num_vertices(m_g) + num_vertices(m_g);
301    }
302  private:
303    InDegreeMap m_in_degree_map;
304    const Graph& m_g;
305  };
306
307
308  template <typename Graph1, typename Graph2, typename IsoMapping,
309    typename Invariant1, typename Invariant2,
310    typename IndexMap1, typename IndexMap2>
311  bool isomorphism(const Graph1& G1, const Graph2& G2, IsoMapping f,
312                   Invariant1 invariant1, Invariant2 invariant2,
313                   std::size_t max_invariant,
314                   IndexMap1 index_map1, IndexMap2 index_map2)
315
316  {
317    // Graph requirements
318    function_requires< VertexListGraphConcept<Graph1> >();
319    function_requires< EdgeListGraphConcept<Graph1> >();
320    function_requires< VertexListGraphConcept<Graph2> >();
321    function_requires< BidirectionalGraphConcept<Graph2> >();
322   
323    typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_t;
324    typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
325    typedef typename graph_traits<Graph1>::vertices_size_type size_type;
326   
327    // Vertex invariant requirement
328    function_requires< AdaptableUnaryFunctionConcept<Invariant1,
329      size_type, vertex1_t> >();
330    function_requires< AdaptableUnaryFunctionConcept<Invariant2,
331      size_type, vertex2_t> >();
332   
333    // Property map requirements
334    function_requires< ReadWritePropertyMapConcept<IsoMapping, vertex1_t> >();
335    typedef typename property_traits<IsoMapping>::value_type IsoMappingValue;
336    BOOST_STATIC_ASSERT((is_same<IsoMappingValue, vertex2_t>::value));
337   
338    function_requires< ReadablePropertyMapConcept<IndexMap1, vertex1_t> >();
339    typedef typename property_traits<IndexMap1>::value_type IndexMap1Value;
340    BOOST_STATIC_ASSERT((is_convertible<IndexMap1Value, size_type>::value));
341   
342    function_requires< ReadablePropertyMapConcept<IndexMap2, vertex2_t> >();
343    typedef typename property_traits<IndexMap2>::value_type IndexMap2Value;
344    BOOST_STATIC_ASSERT((is_convertible<IndexMap2Value, size_type>::value));
345   
346    if (num_vertices(G1) != num_vertices(G2))
347      return false;
348    if (num_vertices(G1) == 0 && num_vertices(G2) == 0)
349      return true;
350   
351    detail::isomorphism_algo<Graph1, Graph2, IsoMapping, Invariant1,
352      Invariant2, IndexMap1, IndexMap2>
353      algo(G1, G2, f, invariant1, invariant2, max_invariant,
354           index_map1, index_map2);
355    return algo.test_isomorphism();
356  }
357
358
359  namespace detail {
360 
361    template <typename Graph1, typename Graph2,
362      typename IsoMapping,
363      typename IndexMap1, typename IndexMap2,
364      typename P, typename T, typename R>
365    bool isomorphism_impl(const Graph1& G1, const Graph2& G2,
366                          IsoMapping f, IndexMap1 index_map1, IndexMap2 index_map2,
367                          const bgl_named_params<P,T,R>& params)
368    {
369      std::vector<std::size_t> in_degree1_vec(num_vertices(G1));
370      typedef safe_iterator_property_map<std::vector<std::size_t>::iterator,
371                                         IndexMap1
372#ifdef BOOST_NO_STD_ITERATOR_TRAITS
373                                         , std::size_t, std::size_t&
374#endif /* BOOST_NO_STD_ITERATOR_TRAITS */
375                                         > InDeg1;
376      InDeg1 in_degree1(in_degree1_vec.begin(), in_degree1_vec.size(), index_map1);
377      compute_in_degree(G1, in_degree1);
378
379      std::vector<std::size_t> in_degree2_vec(num_vertices(G2));
380      typedef safe_iterator_property_map<std::vector<std::size_t>::iterator,
381                                         IndexMap2
382#ifdef BOOST_NO_STD_ITERATOR_TRAITS
383                                         , std::size_t, std::size_t&
384#endif /* BOOST_NO_STD_ITERATOR_TRAITS */
385                                         > InDeg2;
386      InDeg2 in_degree2(in_degree2_vec.begin(), in_degree2_vec.size(), index_map2);
387      compute_in_degree(G2, in_degree2);
388
389      degree_vertex_invariant<InDeg1, Graph1> invariant1(in_degree1, G1);
390      degree_vertex_invariant<InDeg2, Graph2> invariant2(in_degree2, G2);
391
392      return isomorphism(G1, G2, f,
393                         choose_param(get_param(params, vertex_invariant1_t()), invariant1),
394                         choose_param(get_param(params, vertex_invariant2_t()), invariant2),
395                         choose_param(get_param(params, vertex_max_invariant_t()), (invariant2.max)()),
396                         index_map1, index_map2
397                         ); 
398    } 
399   
400  } // namespace detail
401
402
403  // Named parameter interface
404  template <typename Graph1, typename Graph2, class P, class T, class R>
405  bool isomorphism(const Graph1& g1,
406                   const Graph2& g2,
407                   const bgl_named_params<P,T,R>& params)
408  {
409    typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
410    typename std::vector<vertex2_t>::size_type n = num_vertices(g1);
411    std::vector<vertex2_t> f(n);
412    return detail::isomorphism_impl
413      (g1, g2,
414       choose_param(get_param(params, vertex_isomorphism_t()),
415                    make_safe_iterator_property_map(f.begin(), f.size(),
416                                                    choose_const_pmap(get_param(params, vertex_index1),
417                                                                      g1, vertex_index), vertex2_t())),
418       choose_const_pmap(get_param(params, vertex_index1), g1, vertex_index),
419       choose_const_pmap(get_param(params, vertex_index2), g2, vertex_index),
420       params
421       );
422  }
423
424  // All defaults interface
425  template <typename Graph1, typename Graph2>
426  bool isomorphism(const Graph1& g1, const Graph2& g2)
427  {
428    return isomorphism(g1, g2,
429                       bgl_named_params<int, buffer_param_t>(0));// bogus named param
430  }
431
432
433  // Verify that the given mapping iso_map from the vertices of g1 to the
434  // vertices of g2 describes an isomorphism.
435  // Note: this could be made much faster by specializing based on the graph
436  // concepts modeled, but since we're verifying an O(n^(lg n)) algorithm,
437  // O(n^4) won't hurt us.
438  template<typename Graph1, typename Graph2, typename IsoMap>
439  inline bool verify_isomorphism(const Graph1& g1, const Graph2& g2, IsoMap iso_map)
440  {
441#if 0
442    // problematic for filtered_graph!
443    if (num_vertices(g1) != num_vertices(g2) || num_edges(g1) != num_edges(g2))
444      return false;
445#endif
446 
447    for (typename graph_traits<Graph1>::edge_iterator e1 = edges(g1).first;
448         e1 != edges(g1).second; ++e1) {
449      bool found_edge = false;
450      for (typename graph_traits<Graph2>::edge_iterator e2 = edges(g2).first;
451           e2 != edges(g2).second && !found_edge; ++e2) {
452        if (source(*e2, g2) == get(iso_map, source(*e1, g1)) &&
453            target(*e2, g2) == get(iso_map, target(*e1, g1))) {
454          found_edge = true;
455        }
456      }
457   
458      if (!found_edge)
459        return false;
460    }
461 
462    return true;
463  }
464
465} // namespace boost
466
467#ifdef BOOST_ISO_INCLUDED_ITER_MACROS
468#undef BOOST_ISO_INCLUDED_ITER_MACROS
469#include <boost/graph/iteration_macros_undef.hpp>
470#endif
471
472#endif // BOOST_GRAPH_ISOMORPHISM_HPP
Note: See TracBrowser for help on using the repository browser.