Project: ArangoDB (App Definition and Development / Database)
File: isomorphism-impl.pdf

An Implementation of Graph Isomorphism Testing
Jeremy G. Siek
December 9, 20012
0.1 Introduction
This paper documents the implementation of the isomorphism() function of the Boost
Graph Library. The implementation was by Jeremy Siek with algorithmic improve-
ments and test code from Douglas Gregor and Brian Osman. The isomorphism()
function answers the question, \are these two graphs equal?" By equal we mean the
two graphs have the same structure|the vertices and edges are connected in the same
way. The mathematical name for this kind of equality is isomorphism .
More precisely, an isomorphism is a one-to-one mapping of the vertices in one
graph to the vertices of another graph such that adjacency is preserved. Another
words, given graphs G1= (V1;E1) andG2= (V2;E2), an isomorphism is a function
fsuch that for all pairs of vertices a;binV1, edge (a;b) is inE1if and only if edge
(f(a);f(b)) is inE2.
The graph G1isisomorphic toG2if an isomorphism exists between the two
graphs, which we denote by G1=G2. Both graphs must be the same size, so let
N=jV1j=jV2j.
In the following discussion we will need to use several more notions from graph
theory. The graph Gs= (Vs;Es) is a subgraph of graphG= (V;E) ifVsVand
EsE. An induced subgraph , denoted by G[Vs], of a graph G= (V;E) consists of
the vertices in Vs, which is a subset of V, and every edge ( u;v) inEsuch that both
uandvare inVs. We use the notation E[Vs] to mean the edges in G[Vs].
0.2 Backtracking Search
The algorithm used by the isomorphism() function is, at rst approximation, an
exhaustive search implemented via backtracking. The backtracking algorithm is a
recursive function. At each stage we will try to extend the match that we have found
so far. So suppose that we have already determined that some subgraph of G1is
isomorphic to a subgraph of G2. We then try to add a vertex to each subgraph such
that the new subgraphs are still isomorphic to one another. At some point we may hit a
dead end|there are no vertices that can be added to extend the isomorphic subgraphs.
We then backtrack to previous smaller matching subgraphs, and try extending with
a dierent vertex choice. The process ends by either nding a complete mapping
betweenG1andG2and returning true, or by exhausting all possibilities and returning
false.
The problem with the exhaustive backtracking algorithm is that there are N!
possible vertex mappings, and N! gets very large as Nincreases, so we need to prune
the search space. We use the pruning techniques described in [ 1,2,3], some of which
originated in [ 4,5]. Also, the specic backtracking method we use is the one from [ 1].
We consider the vertices of G1for addition to the matched subgraph in a specic
order, so assume that the vertices of G1are labeled 1 ;:::;N according to that order.0.2. BACKTRACKING SEARCH 3
As we will see later, a good ordering of the vertices is by DFS discover time. Let G1[k]
denote the subgraph of G1induced by the rst kvertices, with G1[0] being an empty
graph. We also consider the edges of G1in a specic order. We always examine edges
in the current subgraph G1[k] rst, that is, edges ( u;v) where both ukandvk.
This ordering of edges can be acheived by sorting each edge ( u;v) by lexicographical
comparison on the tuple hmax(u;v);u;vi. Figure 1shows an example of a graph with
the vertices labelled by DFS discover time. The edge ordering for this graph is as
follows:
source: 0 1 0 1 3 0 5 6 6
target: 1 2 3 3 2 4 6 4 7
c (0)
a (1)
d (3)e (4)
b (2)f (5)g (6)
h (7)
Figure 1: Vertices numbered by DFS discover time. The DFS tree edges are the solid
lines. Nodes 0 and 5 are DFS tree root nodes.
Each step of the backtracking search moves from left to right though the ordered
edges. At each step it examines an edge ( u;v) ofG1and decides whether to continue
to the left or to go back. There are three cases to consider:
1.i>k
2.ikandj >k .
3.ikandjk.
Case 1:i>k.iis not in the matched subgraph G1[k]. This situation only happens
at the very beginning of the search, or when iis not reachable from any of the vertices
inG1[k]. This means that we are nished with G1[k]. We increment kand nd match
for it amongst any of the eligible vertices in V2S. We then proceed to Case 2. It is4
usually the case that iis equal to the new k, but when there is another DFS root r
with no in-edges or out-edges and if r<i then it will be the new k.
Case 2:ikandj >k.iis in the matched subgraph G1[k], butjis not. We are
about to increment kto try and grow the matched subgraph to include j. However,
rst we need to nish verifying that G1[k]=G2[S]. In previous steps we proved
thatG1[k1]=G2[Sff(k)g], so now we just need to verify the extension of the
isomorphism to k. At this point we are guaranteed to have seen all the edges to and
from vertex k(because the edges are sorted), and in previous steps we have checked
that for each edge incident on kinE1[k] there is a matching edge in E2[S]. However
we still need to check the \only if" part of the \if and only if". So we check that for
every edge ( u;v) incident on f(k) there is (f1(u);f1(v))2E1[k]. A quick way to
verify this is to make sure that the number of edges incident on kinE1[k] is the same
as the number of edges incident on f(k) inE2[S]. We create an edge counter that
we increment every time we see an edge incident on kand decrement for each edge
incident on f(k). If the counter gets back to zero we know the edges match up.
Once we have veried that G1[k]=G2[S] we addf(k) toS, increment k, and then
try assigning jto any of the eligible vertices in V2S. More about what \eligible"
means below.
Case 3:ikandjk.Bothiandjare inG1[k]. We check to make sure that
(f(i);f(j))2E2[S] and then proceed to the next edge.
0.2.1 Vertex Invariants
One way to reduce the search space is through the use of vertex invariants . The idea
is to compute a number for each vertex i(v) such that i(v) =i(v0) if there exists some
isomorphism fwheref(v) =v0. Then when we look for a match to some vertex v,
only those vertices that have the same vertex invariant number are \eligible". The
number of vertices in a graph with the same vertex invariant number iis called the
invariant multiplicity fori. In this implementation, by default we use the function
i(v) = (jVj+ 1)out-degree( v) + in-degree( v), though the user can also supply there
own invariant function. The ability of the invariant function to prune the search space
varies widely with the type of graph.
The following is the denition of the functor that implements the default vertex
invariant. The functor models the AdaptableUnaryFunction concept.
hDegree vertex invariant functor 4i
template<typename InDegreeMap ,typename Graph >
class degree vertex invariant
f0.2. BACKTRACKING SEARCH 5
typedef typename graph traits<Graph>::vertex descriptor vertex t;
typedef typename graph traits<Graph>::degree size type size type;
public:
typedef vertex t argument type;
typedef size type result type;
degree vertex invariant (const InDegreeMap &indegree map,const Graph &g)
: m indegree map(indegree map),mg(g)fg
size type operator ()(vertex t v)constf
return(num vertices(mg) +1) *outdegree(v,mg)
+get(mindegree map,v);
g
// The largest possible vertex invariant number
size type max ()constf
return num vertices(mg) *num vertices(mg) +num vertices(mg);
g
private:
InDegreeMap m indegree map;
const Graph &mg;
g;
0.2.2 Vertex Order
A good choice of the labeling for the vertices (which determines the order in which
the subgraph G1[k] is grown) can also reduce the search space. In the following we
discuss two labeling heuristics.
Most Constrained First
Consider the most constrained vertices rst. That is, examine lower-degree vertices
before higher-degree vertices. This reduces the search space because it chops o
a trunk before the trunk has a chance to blossom out. We can generalize this to
use vertex invariants. We examine vertices with low invariant multiplicity before
examining vertices with high invariant multiplicity.
Adjacent First
It only makes sense to examine an edge if one or more of its vertices has been assigned
a mapping. This means that we should visit vertices adjacent to those in the current
matched subgraph before proceeding.6
DFS Order, Starting with Lowest Multiplicity
For this implementation, we combine the above two heuristics in the following way.
To implement the \adjacent rst" heuristic we apply DFS to the graph, and use the
DFS discovery order as our vertex order. To comply with the \most constrained rst"
heuristic we order the roots of our DFS trees by invariant multiplicity.
0.2.3 Implementation of the match function
The match function implements the recursive backtracking, handling the four cases
described inx0.2.
hMatch function 6ai
bool match (edge iter iter ,int dfs num k)
f
if(iter!=ordered edges.end())f
vertex1 t i=source(*iter,G1),j=target(*iter,G2);
if(dfsnum[i]>dfsnum k)f
hFind a match for the DFS tree root k+ 16bi
g
else if(dfsnum[j]>dfsnum k)f
hVerifyG1[k]=G2[S]and then nd match for j7ai
g
elsef
hCheck to see if (f(i);f(j))2E2[S]and continue 8bi
g
gelse
return true ;
return false ;
g
Now to describe how each of the four cases is implemented.
Case 1:i62G1[k].We increment kand try to map it to any of the eligible vertices
ofV2S. After matching the new kwe proceed by invoking match . We do not yet
move on to the next edge, since we have not yet found a match for edge, or for target
j. We reset the edge counter to zero.
hFind a match for the DFS tree root k+ 16bi
vertex1 t kp1=dfsvertices[dfsnum k+1];
BGL FORALL VERTICES T(u,G2,Graph2)f
if(invariant1 (kp1) == invariant2 (u) && inS[u] == false)f
f[kp1] =u;
inS[u] =true;
num edges onk=0;0.2. BACKTRACKING SEARCH 7
if(match(iter,dfsnum k+1));
return true ;
inS[u] =false;
g
g
Case 2:i2G1[k]andj62G1[k].Before we extend the subgraph by incrementing
k, we need to nish verifying that G1[k] andG2[S] are isomorphic. We decrement the
edge counter for every edge incident to f(k) inG2[S], which should bring the counter
back down to zero. If not we return false.
hVerifyG1[k]=G2[S] and then nd match for j7ai
vertex1 t k=dfsvertices[dfsnum k];
hCount out-edges of f(k)inG2[S]7bi
hCount in-edges of f(k)inG2[S]7ci
if(num edges onk!=0)
return false ;
hFind a match for jand continue 8ai
We decrement the edge counter for every vertex in Adj[f(k)] that is also in S. We
callcount ifto do the counting, using boost::bind to create the predicate functor.
hCount out-edges of f(k) inG2[S]7bi
num edges onk=
count if(adjacent vertices(f[k],G2),make indirect pmap(inS));
Next we iterate through all the vertices in Sand for each we decrement the counter
for each edge whose target is k.
hCount in-edges of f(k) inG2[S]7ci
for(int jj=0;jj<dfsnum k; ++jj)f
vertex1 t j=dfsvertices[jj];
num edges onk=count(adjacent vertices(f[j],G2),f[k]);
g
Now that we have nished verifying that G1[k]=G2[S], we can now consider
extending the isomorphism. We need to nd a match for jinV2S. Sincejis
adjacent to i, we can further narrow down the search by only considering vertices
adjacent to f(i). Also, the vertex must have the same vertex invariant. Once we have
a matching vertex vwe extend the matching subgraphs by incrementing kand adding
vtoS, we setf(j) =v, and we set the edge counter to 1 (since ( i;j) is the rst edge
incident on our new k). We continue to the next edge by calling match . If that fails
we undo the assignment f(j) =v.8
hFind a match for jand continue 8ai
BGL FORALL ADJ T(f[i],v,G2,Graph2)
if(invariant2 (v) == invariant1 (j) && inS[v] == false)f
f[j] =v;
inS[v] =true;
num edges onk=1;
int next k=std::max (dfsnum k,std::max (dfsnum[i],dfsnum[j]));
if(match(next(iter),next k))
return true ;
inS[v] =false;
g
Case 3: both iandjare inG1[k].Our goal is to check whether ( f(i);f(j))2
E2[S]. We examine the vertices Adj[f(i)] to see if any of them is equal to f(j). If
so, then we have a match for the edge ( i;j), and can increment the counter for the
number of edges incident on kinE1[k]. We continue by calling match on the next
edge.
hCheck to see if ( f(i);f(j))2E2[S] and continue 8bi
if(any equal(adjacent vertices(f[i],G2),f[j]))f
++num edges onk;
if(match(next(iter),dfsnum k))
return true ;
g
0.3 Public Interface
The following is the public interface for the isomorphism function. The input to the
function is the two graphs G1andG2, mappings from the vertices in the graphs to
integers (in the range [0 ;jVj)), and a vertex invariant function object. The output of
the function is an isomorphism fif there is one. The isomorphism function returns
true if the graphs are isomorphic and false otherwise. The invariant parameters are
function objects that compute the vertex invariants for vertices of the two graphs.
The max invariant parameter is to specify one past the largest integer that a vertex
invariant number could be (the invariants numbers are assumed to span from zero to
max invariant-1 ). The requirements on the template parameters are described below
in the \Concept checking" code part.
hIsomorphism function interface 8ci
template<typename Graph1 ,typename Graph2 ,typename IsoMapping ,
typename Invariant1 ,typename Invariant2 ,0.3. PUBLIC INTERFACE 9
typename IndexMap1 ,typename IndexMap2 >
bool isomorphism (const Graph1 &G1,const Graph2 &G2,IsoMapping f ,
Invariant1 invariant1 ,Invariant2 invariant2 ,
std::size t max invariant ,
IndexMap1 index map1,IndexMap2 index map2)
The function body consists of the concept checks followed by a quick check for
empty graphs or graphs of dierent size and then constructs an algorithm object.
We then call the testisomorphism member function, which runs the algorithm. The
reason that we implement the algorithm using a class is that there are a fair number
of internal data structures required, and it is easier to make these data members of
a class and make each section of the algorithm a member function. This relieves us
from the burden of passing lots of arguments to each function, while at the same time
avoiding the evils of global variables (non-reentrant, etc.).
hIsomorphism function body 9ai
f
hConcept checking 10ai
hQuick return based on size 9bi
detail::isomorphism algo<Graph1,Graph2,IsoMapping ,Invariant1 ,
Invariant2 ,IndexMap1 ,IndexMap2 >
algo(G1,G2,f,invariant1 ,invariant2 ,max invariant ,
index map1,index map2);
return algo .test isomorphism ();
g
If there are no vertices in either graph, then they are trivially isomorphic. If the graphs
have dierent numbers of vertices then they are not isomorphic. We could also check
the number of edges here, but that would introduce the EdgeListGraph requirement,
which we otherwise do not need.
hQuick return based on size 9bi
if(num vertices(G1) != num vertices(G2))
return false ;
if(num vertices(G1) == 0&&num vertices(G2) == 0)
return true ;
We use the Boost Concept Checking Library to make sure that the template argu-
ments fulll certain requirements. The graph types must model the VertexListGraph and
AdjacencyGraph concepts. The vertex invariants must model the AdaptableUnaryFunction
concept, with a vertex as their argument and an integer return type. The IsoMapping
type representing the isomorphism fmust be a ReadWritePropertyMap that maps from
vertices inG1to vertices in G2. The two other index maps are ReadablePropertyMap s
from vertices in G1andG2to unsigned integers.10
hConcept checking 10ai
// Graph requirements
function requires<VertexListGraphConcept <Graph1> >();
function requires<EdgeListGraphConcept <Graph1> >();
function requires<VertexListGraphConcept <Graph2> >();
function requires<BidirectionalGraphConcept <Graph2> >();
typedef typename graph traits<Graph1>::vertex descriptor vertex1 t;
typedef typename graph traits<Graph2>::vertex descriptor vertex2 t;
typedef typename graph traits<Graph1>::vertices size type size type;
// Vertex invariant requirement
function requires<AdaptableUnaryFunctionConcept <Invariant1 ,
size type,vertex1 t> >();
function requires<AdaptableUnaryFunctionConcept <Invariant2 ,
size type,vertex2 t> >();
// Property map requirements
function requires<ReadWritePropertyMapConcept <IsoMapping ,vertex1 t> >();
typedef typename property traits<IsoMapping >::value type IsoMappingValue ;
BOOST STATIC ASSERT ((issame<IsoMappingValue ,vertex2 t>::value));
function requires<ReadablePropertyMapConcept <IndexMap1 ,vertex1 t> >();
typedef typename property traits<IndexMap1 >::value type IndexMap1Value ;
BOOST STATIC ASSERT ((isconvertible <IndexMap1Value ,size type>::value));
function requires<ReadablePropertyMapConcept <IndexMap2 ,vertex2 t> >();
typedef typename property traits<IndexMap2 >::value type IndexMap2Value ;
BOOST STATIC ASSERT ((isconvertible <IndexMap2Value ,size type>::value));
0.4 Data Structure Setup
The following is the outline of the isomorphism algorithm class. The class is tem-
plated on all of the same parameters as the isomorphism function, and all of the
parameter values are stored in the class as data members, in addition to the internal
data structures.
hIsomorphism algorithm class 10bi
template<typename Graph1 ,typename Graph2 ,typename IsoMapping ,
typename Invariant1 ,typename Invariant2 ,
typename IndexMap1 ,typename IndexMap2 >
class isomorphism algo
f
hTypedefs for commonly used types 14ci0.4. DATA STRUCTURE SETUP 11
hData members for the parameters 14di
hInternal data structures 15ai
friend struct compare multiplicity ;
hInvariant multiplicity comparison functor 12bi
hDFS visitor to record vertex and edge order 13bi
hEdge comparison predicate 14bi
public:
hIsomorphism algorithm constructor 15bi
hTest isomorphism member function 11ai
private:
hMatch function 6ai
g;
The interesting parts of this class are the testisomorphism function and the
match function. We focus on those in in the following sections, and leave the other
parts of the class to the Appendix.
The testisomorphism function does all of the setup required of the algorithm.
This consists of sorting the vertices according to invariant multiplicity, and then by
DFS order. The edges are then sorted as previously described. The last step of this
function is to begin the backtracking search.
hTest isomorphism member function 11ai
bool test isomorphism ()
f
hQuick return if the vertex invariants do not match up 11bi
hSort vertices according to invariant multiplicity 12ai
hOrder vertices and edges by DFS 13ai
hSort edges according to vertex DFS order 14ai
int dfs num k=1;
return this>match(ordered edges.begin(),dfsnum k);
g
As a rst check to rule out graphs that have no possibility of matching, one can
create a list of computed vertex invariant numbers for the vertices in each graph,
sort the two lists, and then compare them. If the two lists are dierent then the two
graphs are not isomorphic. If the two lists are the same then the two graphs may be
isomorphic.
hQuick return if the vertex invariants do not match up 11bi
f
std::vector <invar1 value>invar1 array;
BGL FORALL VERTICES T(v,G1,Graph1)
invar1 array.push back(invariant1 (v));
sort(invar1 array);12
std::vector <invar2 value>invar2 array;
BGL FORALL VERTICES T(v,G2,Graph2)
invar2 array.push back(invariant2 (v));
sort(invar2 array);
if(!equal(invar1 array,invar2 array))
return false ;
g
Next we compute the invariant multiplicity, the number of vertices with the same
invariant number. The invar mult vector is indexed by invariant number. We loop
through all the vertices in the graph to record the multiplicity. We then order the ver-
tices by their invariant multiplicity. This will allow us to search the more constrained
vertices rst.
hSort vertices according to invariant multiplicity 12ai
std::vector <vertex1 t>Vmult;
BGL FORALL VERTICES T(v,G1,Graph1)
Vmult.push back(v);
f
std::vector <size type>multiplicity (max invariant ,0);
BGL FORALL VERTICES T(v,G1,Graph1)
++multiplicity [invariant1 (v)];
sort(Vmult,compare multiplicity (invariant1 , &multiplicity [0]));
g
The denition of the compare multiplicity predicate is shown below. This predicate
provides the glue that binds std::sort to our current purpose.
hInvariant multiplicity comparison functor 12bi
struct compare multiplicity
f
compare multiplicity (Invariant1 invariant1 ,size type*multiplicity )
: invariant1 (invariant1 ),multiplicity (multiplicity )fg
bool operator ()(const vertex1 t&x,const vertex1 t&y)constf
return multiplicity [invariant1 (x)]<multiplicity [invariant1 (y)];
g
Invariant1 invariant1 ;
size type*multiplicity ;
g;
0.4.1 Ordering by DFS Discover Time
Next we order the vertices and edges by DFS discover time. We would normally call
the BGL depth rst search function to do this, but we want the roots of the DFS0.4. DATA STRUCTURE SETUP 13
tree's to be ordered by invariant multiplicity. Therefore we implement the outer-loop
of the DFS here and then call depth rst visit to handle the recursive portion of the
DFS. The record dfsorder adapts the DFS to record the ordering, storing the results
in in the dfsvertices andordered edges arrays. We then create the dfsnum array
which provides a mapping from vertex to DFS number.
hOrder vertices and edges by DFS 13ai
std::vector <default color type>color vec(num vertices(G1));
safe iterator property map<std::vector <default color type>::iterator ,IndexMap1 >
color map(color vec.begin(),color vec.size(),index map1);
record dfsorder dfs visitor(dfsvertices,ordered edges);
typedef color traits<default color type>Color;
for(vertex iter u=Vmult.begin();u!=Vmult.end(); ++ u)f
if(color map[*u] == Color::white ())f
dfsvisitor.start vertex(*u,G1);
depth rst visit(G1, *u,dfsvisitor,color map);
g
g
// Create the dfs num array and dfs num map
dfsnum vec.resize(num vertices(G1));
dfsnum=make safe iterator property map(dfsnum vec.begin(),
dfsnum vec.size(),index map1);
size type n=0;
for(vertex iter v=dfsvertices.begin();v!=dfsvertices.end(); ++ v)
dfsnum[*v] =n++;
The denition of the record dfsorder visitor class is as follows.
hDFS visitor to record vertex and edge order 13bi
struct record dfsorder : default dfsvisitor
f
record dfsorder(std::vector <vertex1 t>&v,std::vector <edge1 t>&e)
: vertices (v),edges(e)fg
void discover vertex(vertex1 t v,const Graph1 &)constf
vertices.push back(v);
g
void examine edge(edge1 t e,const Graph1 &G1)constf
edges.push back(e);
g
std::vector <vertex1 t>&vertices;
std::vector <edge1 t>&edges;
g;14
The nal stage of the setup is to reorder the edges so that all edges belonging to
G1[k] appear before any edges not in G1[k], fork= 1;:::;n .
hSort edges according to vertex DFS order 14ai
sort(ordered edges,edge cmp(G1,dfsnum));
The edge comparison function object is dened as follows.
hEdge comparison predicate 14bi
struct edge cmpf
edge cmp(const Graph1 &G1,DFSNumMap dfs num)
: G1(G1),dfsnum(dfsnum)fg
bool operator ()(const edge1 t&e1,const edge1 t&e2)constf
using namespace std ;
vertex1 t u1=dfsnum[source(e1,G1)],v1=dfsnum[target(e1,G1)];
vertex1 t u2=dfsnum[source(e2,G1)],v2=dfsnum[target(e2,G1)];
int m1 =max(u1,v1);
int m2 =max(u2,v2);
// lexicographical comparison
return make pair(m1,make pair(u1,v1))
<make pair(m2,make pair(u2,v2));
g
const Graph1 &G1;
DFSNumMap dfs num;
g;
0.5 Appendix
hTypedefs for commonly used types 14ci
typedef typename graph traits<Graph1>::vertex descriptor vertex1 t;
typedef typename graph traits<Graph2>::vertex descriptor vertex2 t;
typedef typename graph traits<Graph1>::edge descriptor edge1 t;
typedef typename graph traits<Graph1>::vertices size type size type;
typedef typename Invariant1::result type invar1 value;
typedef typename Invariant2::result type invar2 value;
hData members for the parameters 14di
const Graph1 &G1;
const Graph2 &G2;
IsoMapping f ;
Invariant1 invariant1 ;
Invariant2 invariant2 ;0.5. APPENDIX 15
std::size t max invariant ;
IndexMap1 index map1;
IndexMap2 index map2;
hInternal data structures 15ai
std::vector <vertex1 t>dfsvertices;
typedef std::vector <vertex1 t>::iterator vertex iter;
std::vector <int>dfsnum vec;
typedef safe iterator property map<typename std::vector <int>::iterator ,IndexMap1 >DFSNumMap ;
DFSNumMap dfs num;
std::vector <edge1 t>ordered edges;
typedef std::vector <edge1 t>::iterator edge iter;
std::vector <char>inSvec;
typedef safe iterator property map<typename std::vector <char>::iterator ,
IndexMap2 >InSMap ;
InSMap in S;
int num edges onk;
hIsomorphism algorithm constructor 15bi
isomorphism algo(const Graph1 &G1,const Graph2 &G2,IsoMapping f ,
Invariant1 invariant1 ,Invariant2 invariant2 ,std::size t max invariant ,
IndexMap1 index map1,IndexMap2 index map2)
: G1(G1),G2(G2),f(f),invariant1 (invariant1 ),invariant2 (invariant2 ),
max invariant (max invariant ),
index map1(index map1),index map2(index map2)
f
inSvec.resize(num vertices(G1));
inS=make safe iterator property map
(inSvec.begin(),inSvec.size(),index map2);
g
hisomorphism.hpp 15ci
// Copyright (C) 2001 Jeremy Siek, Doug Gregor, Brian Osman
//
// Permission to copy, use, sell and distribute this software is granted
// provided this copyright notice appears in all copies.
// Permission to modify the code and to distribute modied code is granted
// provided this copyright notice appears in all copies, and a notice
// that the code was modied is included with the copyright notice.
//
// This software is provided \as is" without express or implied warranty,16
// and with no claim as to its suitability for any purpose.
#ifndef BOOST GRAPH ISOMORPHISM HPP
#dene BOOST GRAPH ISOMORPHISM HPP
#include <utility>
#include <vector>
#include <iterator>
#include <algorithm >
#include <boost/graph/iteration macros.hpp>
#include <boost/graph/depth rst search.hpp>
#include <boost/utility.hpp>
#include <boost/algorithm .hpp>
#include <boost/pending /indirect cmp.hpp>// for make indirect pmap
namespace boost f
namespace detail f
hIsomorphism algorithm class 10bi
template<typename Graph ,typename InDegreeMap >
void compute indegree(const Graph &g,InDegreeMap in degree map)
f
BGL FORALL VERTICES T(v,g,Graph)
put(indegree map,v,0);
BGL FORALL VERTICES T(u,g,Graph)
BGL FORALL ADJ T(u,v,g,Graph)
put(indegree map,v,get(indegree map,v) +1);
g
g// namespace detail
hDegree vertex invariant functor 4i
hIsomorphism function interface 8ci
hIsomorphism function body 9ai
namespace detail f
template<typename Graph1 ,typename Graph2 ,
typename IsoMapping ,
typename IndexMap1 ,typename IndexMap2 ,
typename P ,typename T ,typename R >
bool isomorphism impl(const Graph1 &G1,const Graph2 &G2,0.5. APPENDIX 17
IsoMapping f ,IndexMap1 index map1,IndexMap2 index map2,
const bgl named params<P,T,R>&params)
f
std::vector <std::size t>indegree1 vec(num vertices(G1));
typedef safe iterator property map<std::vector <std::size t>::iterator ,IndexMap1 >InDeg1;
InDeg1 in degree1(indegree1 vec.begin(),indegree1 vec.size(),index map1);
compute indegree(G1,indegree1);
std::vector <std::size t>indegree2 vec(num vertices(G2));
typedef safe iterator property map<std::vector <std::size t>::iterator ,IndexMap2 >InDeg2;
InDeg2 in degree2(indegree2 vec.begin(),indegree2 vec.size(),index map2);
compute indegree(G2,indegree2);
degree vertex invariant<InDeg1,Graph1>invariant1 (indegree1,G1);
degree vertex invariant<InDeg2,Graph2>invariant2 (indegree2,G2);
return isomorphism (G1,G2,f,
choose param(getparam(params,vertex invariant1 t()), invariant1 ),
choose param(getparam(params,vertex invariant2 t()), invariant2 ),
choose param(getparam(params,vertex max invariant t()), invariant2 .max()),
index map1,index map2
);
g
g// namespace detail
// Named parameter interface
template<typename Graph1 ,typename Graph2 ,class P,class T,class R>
bool isomorphism (const Graph1 &g1,
const Graph2 &g2,
const bgl named params<P,T,R>&params)
f
typedef typename graph traits<Graph2>::vertex descriptor vertex2 t;
typename std::vector <vertex2 t>::size type n=num vertices(g1);
std::vector <vertex2 t>f(n);
return detail::isomorphism impl
(g1,g2,
choose param(getparam(params,vertex isomorphism t()),
make safe iterator property map(f.begin(),f.size(),
choose const pmap(getparam(params,vertex index1),
g1,vertex index),vertex2 t())),
choose const pmap(getparam(params,vertex index1),g1,vertex index),
choose const pmap(getparam(params,vertex index2),g2,vertex index),
params
);18
g
// All defaults interface
template<typename Graph1 ,typename Graph2 >
bool isomorphism (const Graph1 &g1,const Graph2 &g2)
f
return isomorphism (g1,g2,
bglnamed params<int,buer param t>(0));// bogus named param
g
// Verify that the given mapping iso map from the vertices of g1 to the
// vertices of g2 describes an isomorphism.
// Note: this could be made much faster by specializing based on the graph
// concepts modeled, but since we're verifying an O(n ^(lg n)) algorithm,
// O(n^4) won't hurt us.
template<typename Graph1 ,typename Graph2 ,typename IsoMap >
inline bool verify isomorphism (const Graph1 &g1,const Graph2 &g2,IsoMap iso map)
f
if(num vertices(g1) != num vertices(g2)jjnum edges(g1) != num edges(g2))
return false ;
for(typename graph traits<Graph1>::edge iterator e1 =edges(g1).rst;
e1!=edges(g1).second; ++e1)f
bool found edge=false;
for(typename graph traits<Graph2>::edge iterator e2 =edges(g2).rst;
e2!=edges(g2).second&& !found edge; ++e2)f
if(source(*e2,g2) == get(isomap,source(*e1,g1)) &&
target(*e2,g2) == get(isomap,target(*e1,g1)))f
found edge=true;
g
g
if(!found edge)
return false ;
g
return true ;
g
g// namespace boost
#include <boost/graph/iteration macros undef.hpp>
#endif // BOOST GRAPH ISOMORPHISM HPPBibliography
[1]N. Deo, J. M. Davis, and R. E. Lord. A new algorithm for digraph isomorphism.
BIT, 17:16{30, 1977.
[2]S. Fortin. Graph isomorphism problem. Technical Report 96-20, University of
Alberta, Edomonton, Alberta, Canada, 1996.
[3]E. M. Reingold, J. Nievergelt, and N. Deo. Combinatorial Algorithms: Theory
and Practice . Prentice Hall, 1977.
[4]E. Sussenguth. A graph theoretic algorithm for matching chemical structure. J.
Chem. Doc. , 5:36{43, 1965.
[5]S. H. Unger. Git|a heuristic program for testing pairs of directed line graphs for
isomorphism. Comm. ACM , 7:26{34, 1964.
19