isomorphism-impl-v3.w 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. \documentclass[11pt,awpaper]{book}
  2. \usepackage{math}
  3. \usepackage{jweb}
  4. \usepackage[nolineno]{lgrind}
  5. \usepackage{awpaper}
  6. \usepackage{graphicx}
  7. \setlength{\evensidemargin}{-0.25in}% was -0.17in
  8. \setlength{\oddsidemargin}{0in}%was -0.25in
  9. \setlength{\textwidth}{5.625in}%was 5.75in
  10. \setlength{\textheight}{7.75in}
  11. \setlength{\topmargin}{-0.125in}%was -0.25
  12. \addtolength{\topmargin}{-\headheight}
  13. \addtolength{\topmargin}{-\headsep}
  14. \newif\ifpdf
  15. \ifx\pdfoutput\undefined
  16. \pdffalse
  17. \else
  18. \pdfoutput=1
  19. \pdftrue
  20. \fi
  21. \ifpdf
  22. \usepackage[
  23. pdftex,
  24. colorlinks=true, %change to true for the electronic version
  25. linkcolor=blue,filecolor=blue,pagecolor=blue,urlcolor=blue
  26. ]{hyperref}
  27. \fi
  28. \ifpdf
  29. \newcommand{\stlconcept}[1]{\href{https://boost.org/sgi/stl/#1.html}{{\small \textsf{#1}}}}
  30. \newcommand{\bglconcept}[1]{\href{http://www.boost.org/libs/graph/doc/#1.html}{{\small \textsf{#1}}}}
  31. \newcommand{\pmconcept}[1]{\href{http://www.boost.org/libs/property_map/#1.html}{{\small \textsf{#1}}}}
  32. \newcommand{\myhyperref}[2]{\hyperref[#1]{#2}}
  33. \newcommand{\vizfig}[2]{\begin{figure}[htbp]\centerline{\includegraphics*{#1.pdf}}\caption{#2}\label{fig:#1}\end{figure}}
  34. \else
  35. \newcommand{\myhyperref}[2]{#2}
  36. \newcommand{\bglconcept}[1]{{\small \textsf{#1}}}
  37. \newcommand{\pmconcept}[1]{{\small \textsf{#1}}}
  38. \newcommand{\stlconcept}[1]{{\small \textsf{#1}}}
  39. \newcommand{\vizfig}[2]{\begin{figure}[htbp]\centerline{\includegraphics*{#1.eps}}\caption{#2}\label{fig:#1}\end{figure}}
  40. \fi
  41. \newcommand{\code}[1]{{\small{\em \textbf{#1}}}}
  42. \newcommand{\isomorphic}{\cong}
  43. \begin{document}
  44. \title{An Implementation of Graph Isomorphism Testing}
  45. \author{Jeremy G. Siek}
  46. \maketitle
  47. % Ideas: use BFS instead of DFS, don't have to sort edges?
  48. % No, you would still have to sort the edges.
  49. %
  50. %Figure~\ref{fig:iso-eg2}.
  51. % 0 0 0 1 1 2 5 6 6 7
  52. % 1 2 3 4 2 4 6 3 7 5
  53. %\vizfig{iso-eg2}{Vertices numbered by BFS discover time. The BFS tree
  54. %edges are the solid lines. Nodes $0$ and $5$ are BFS tree root nodes.}
  55. %
  56. % You could do a modified Dijkstra, where the priority in the queue
  57. % would be the BFS discover time of the target vertex.
  58. % Use w(u,v) = |Adj[u] \intersect Adj[v]| as an edge invariant.
  59. % Has anyone used edge invariants before?
  60. \section{Introduction}
  61. This paper documents the implementation of the \code{isomorphism()}
  62. function of the Boost Graph Library. The implementation was by Jeremy
  63. Siek with algorithmic improvements and test code from Douglas Gregor
  64. and Brian Osman. The \code{isomorphism()} function answers the
  65. question, ``are these two graphs equal?'' By \emph{equal} we mean
  66. the two graphs have the same structure---the vertices and edges are
  67. connected in the same way. The mathematical name for this kind of
  68. equality is \emph{isomorphism}.
  69. More precisely, an \emph{isomorphism} is a one-to-one mapping of the
  70. vertices in one graph to the vertices of another graph such that
  71. adjacency is preserved. Another words, given graphs $G_{1} =
  72. (V_{1},E_{1})$ and $G_{2} = (V_{2},E_{2})$, an isomorphism is a
  73. function $f$ such that for all pairs of vertices $a,b$ in $V_{1}$,
  74. edge $(a,b)$ is in $E_{1}$ if and only if edge $(f(a),f(b))$ is in
  75. $E_{2}$.
  76. The graph $G_1$ is \emph{isomorphic} to $G_2$ if an isomorphism exists
  77. between the two graphs, which we denote by $G_1 \isomorphic G_2$.
  78. Both graphs must be the same size, so let $N = |V_1| = |V_2|$.
  79. In the following discussion we will need to use several more notions
  80. from graph theory. The graph $G_s=(V_s,E_s)$ is a \emph{subgraph} of
  81. graph $G=(V,E)$ if $V_s \subseteq V$ and $E_s \subseteq E$. An
  82. \emph{induced subgraph}, denoted by $G[V_s]$, of a graph $G=(V,E)$
  83. consists of the vertices in $V_s$, which is a subset of $V$, and every
  84. edge $(u,v)$ in $E$ such that both $u$ and $v$ are in $V_s$. We use
  85. the notation $E[V_s]$ to mean the edges in $G[V_s]$.
  86. \section{Backtracking Search}
  87. \label{sec:backtracking}
  88. The algorithm used by the \code{isomorphism()} function is, at first
  89. approximation, an exhaustive search implemented via backtracking. The
  90. backtracking algorithm is a recursive function. At each stage we will
  91. try to extend the match that we have found so far. So suppose that we
  92. have already determined that some subgraph of $G_1$ is isomorphic to a
  93. subgraph of $G_2$. We then try to add a vertex to each subgraph such
  94. that the new subgraphs are still isomorphic to one another. At some
  95. point we may hit a dead end---there are no vertices that can be added
  96. to extend the isomorphic subgraphs. We then backtrack to previous
  97. smaller matching subgraphs, and try extending with a different vertex
  98. choice. The process ends by either finding a complete mapping between
  99. $G_1$ and $G_2$ and returning true, or by exhausting all possibilities
  100. and returning false.
  101. The problem with the exhaustive backtracking algorithm is that there
  102. are $N!$ possible vertex mappings, and $N!$ gets very large as $N$
  103. increases, so we need to prune the search space. We use the pruning
  104. techniques described in
  105. \cite{deo77:_new_algo_digraph_isomorph,fortin96:_isomorph,reingold77:_combin_algo},
  106. some of which originated in
  107. \cite{sussenguth65:_isomorphism,unger64:_isomorphism}. Also, the
  108. specific backtracking method we use is the one from
  109. \cite{deo77:_new_algo_digraph_isomorph}.
  110. We consider the vertices of $G_1$ for addition to the matched subgraph
  111. in a specific order, so assume that the vertices of $G_1$ are labeled
  112. $1,\ldots,N$ according to that order. As we will see later, a good
  113. ordering of the vertices is by DFS discover time. Let $G_1[k]$ denote
  114. the subgraph of $G_1$ induced by the first $k$ vertices, with $G_1[0]$
  115. being an empty graph. We also consider the edges of $G_1$ in a
  116. specific order. We always examine edges in the current subgraph
  117. $G_1[k]$ first, that is, edges $(u,v)$ where both $u \leq k$ and $v
  118. \leq k$. This ordering of edges can be acheived by sorting each edge
  119. $(u,v)$ by lexicographical comparison on the tuple $\langle \max(u,v),
  120. u, v \rangle$. Figure~\ref{fig:iso-eg} shows an example of a graph
  121. with the vertices labelled by DFS discover time. The edge ordering for
  122. this graph is as follows:
  123. \begin{tabular}{lccccccccc}
  124. source: &0&1&0&1&3&0&5&6&6\\
  125. target: &1&2&3&3&2&4&6&4&7
  126. \end{tabular}
  127. \vizfig{iso-eg}{Vertices numbered by DFS discover time. The DFS tree
  128. edges are the solid lines. Nodes $0$ and $5$ are DFS tree root nodes.}
  129. Each step of the backtracking search moves from left to right though
  130. the ordered edges. At each step it examines an edge $(i,j)$ of $G_1$
  131. and decides whether to continue to the left or to go back. There are
  132. three cases to consider:
  133. \begin{enumerate}
  134. \item \label{case:1} $i > k$
  135. \item \label{case:2} $i \leq k$ and $j > k$.
  136. \item \label{case:3} $i \leq k$ and $j \leq k$.
  137. \end{enumerate}
  138. \paragraph{Case 1: $i > k$.}
  139. $i$ is not in the matched subgraph $G_1[k]$. This situation only
  140. happens at the very beginning of the search, or when $i$ is not
  141. reachable from any of the vertices in $G_1[k]$. This means that we
  142. are finished with $G_1[k]$. We increment $k$ and find a match for it
  143. amongst any of the eligible vertices in $V_2 - S$. We then proceed to
  144. Case 2. It is usually the case that $i$ is equal to the new $k$, but
  145. when there is another DFS root $r$ with no in-edges or out-edges
  146. and if $r < i$ then it will be the new $k$.
  147. \paragraph{Case 2: $i \leq k$ and $j > k$.}
  148. $i$ is in the matched subgraph $G_1[k]$, but $j$ is not. We are about
  149. to increment $k$ to try and grow the matched subgraph to include
  150. $j$. However, first we need to finish verifying that $G_1[k]
  151. \isomorphic G_2[S]$. In previous steps we proved that $G_1[k-1]
  152. \isomorphic G_2[S-\{f(k)\}]$, so now we just need to verify the
  153. extension of the isomorphism to $k$. At this point we are guaranteed
  154. to have seen all the edges to and from vertex $k$ (because the edges
  155. are sorted), and in previous steps we have checked that for each edge
  156. incident on $k$ in $E_1[k]$ there is a matching edge in
  157. $E_2[S]$. However we still need to check the ``only if'' part of the
  158. ``if and only if''. So we check that for every edge $(u,v)$ incident
  159. on $f(k)$ there is $(f^{-1}(u),f^{-1}(v)) \in E_1[k]$. A quick way to
  160. verify this is to make sure that the number of edges incident on $k$
  161. in $E_1[k]$ is the same as the number of edges incident on $f(k)$ in
  162. $E_2[S]$. We create an edge counter that we increment every time we
  163. see an edge incident on $k$ and decrement for each edge incident on
  164. $f(k)$. If the counter gets back to zero we know the edges match up.
  165. Once we have verified that $G_1[k] \isomorphic G_2[S]$ we add $f(k)$
  166. to $S$, increment $k$, and then try assigning $j$ to
  167. any of the eligible vertices in $V_2 - S$. More about what
  168. ``eligible'' means below.
  169. \paragraph{Case 3: $i \leq k$ and $j \leq k$.}
  170. Both $i$ and $j$ are in $G_1[k]$. We check to make sure that
  171. $(f(i),f(j)) \in E_2[S]$ and then proceed to the next edge.
  172. \subsection{Vertex Invariants}
  173. \label{sec:vertex-invariants}
  174. One way to reduce the search space is through the use of \emph{vertex
  175. invariants}. The idea is to compute a number for each vertex $i(v)$
  176. such that $i(v) = i(v')$ if there exists some isomorphism $f$ where
  177. $f(v) = v'$. Then when we look for a match to some vertex $v$, only
  178. those vertices that have the same vertex invariant number are
  179. ``eligible''. The number of vertices in a graph with the same vertex
  180. invariant number $i$ is called the \emph{invariant multiplicity} for
  181. $i$. In this implementation, by default we use the function $i(v) =
  182. (|V|+1) \times \outdegree(v) + \indegree(v)$, though the user can also
  183. supply there own invariant function. The ability of the invariant
  184. function to prune the search space varies widely with the type of
  185. graph.
  186. The following is the definition of the functor that implements the
  187. default vertex invariant. The functor models the
  188. \stlconcept{AdaptableUnaryFunction} concept.
  189. @d Degree vertex invariant functor
  190. @{
  191. template <typename InDegreeMap, typename Graph>
  192. class degree_vertex_invariant
  193. {
  194. typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
  195. typedef typename graph_traits<Graph>::degree_size_type size_type;
  196. public:
  197. typedef vertex_t argument_type;
  198. typedef size_type result_type;
  199. degree_vertex_invariant(const InDegreeMap& in_degree_map, const Graph& g)
  200. : m_in_degree_map(in_degree_map), m_g(g) { }
  201. size_type operator()(vertex_t v) const {
  202. return (num_vertices(m_g) + 1) * out_degree(v, m_g)
  203. + get(m_in_degree_map, v);
  204. }
  205. // The largest possible vertex invariant number
  206. size_type max() const {
  207. return num_vertices(m_g) * num_vertices(m_g) + num_vertices(m_g);
  208. }
  209. private:
  210. InDegreeMap m_in_degree_map;
  211. const Graph& m_g;
  212. };
  213. @}
  214. \subsection{Vertex Order}
  215. A good choice of the labeling for the vertices (which determines the
  216. order in which the subgraph $G_1[k]$ is grown) can also reduce the
  217. search space. In the following we discuss two labeling heuristics.
  218. \subsubsection{Most Constrained First}
  219. Consider the most constrained vertices first. That is, examine
  220. lower-degree vertices before higher-degree vertices. This reduces the
  221. search space because it chops off a trunk before the trunk has a
  222. chance to blossom out. We can generalize this to use vertex
  223. invariants. We examine vertices with low invariant multiplicity
  224. before examining vertices with high invariant multiplicity.
  225. \subsubsection{Adjacent First}
  226. It only makes sense to examine an edge if one or more of its vertices
  227. has been assigned a mapping. This means that we should visit vertices
  228. adjacent to those in the current matched subgraph before proceeding.
  229. \subsubsection{DFS Order, Starting with Lowest Multiplicity}
  230. For this implementation, we combine the above two heuristics in the
  231. following way. To implement the ``adjacent first'' heuristic we apply
  232. DFS to the graph, and use the DFS discovery order as our vertex
  233. order. To comply with the ``most constrained first'' heuristic we
  234. order the roots of our DFS trees by invariant multiplicity.
  235. \subsection{Implementation of the \code{match} function}
  236. The \code{match} function implements the recursive backtracking,
  237. handling the four cases described in \S\ref{sec:backtracking}.
  238. @d Match function
  239. @{
  240. bool match(edge_iter iter, int dfs_num_k)
  241. {
  242. if (iter != ordered_edges.end()) {
  243. vertex1_t i = source(*iter, G1), j = target(*iter, G2);
  244. if (dfs_num[i] > dfs_num_k) {
  245. @<Find a match for the DFS tree root $k+1$@>
  246. }
  247. else if (dfs_num[j] > dfs_num_k) {
  248. @<Verify $G_1[k] \isomorphic G_2[S]$ and then find match for $j$@>
  249. }
  250. else {
  251. @<Check to see if $(f(i),f(j)) \in E_2[S]$ and continue@>
  252. }
  253. } else
  254. return true;
  255. return false;
  256. }
  257. @}
  258. \noindent Now to describe how each of the four cases is implemented.
  259. \paragraph{Case 1: $i \not\in G_1[k]$.}
  260. We increment $k$ and try to map it to any of the eligible vertices of
  261. $V_2 - S$. After matching the new $k$ we proceed by invoking
  262. \code{match}. We do not yet move on to the next edge, since we have
  263. not yet found a match for edge, or for target $j$. We reset the edge
  264. counter to zero.
  265. @d Find a match for the DFS tree root $k+1$
  266. @{
  267. vertex1_t kp1 = dfs_vertices[dfs_num_k + 1];
  268. BGL_FORALL_VERTICES_T(u, G2, Graph2) {
  269. if (invariant1(kp1) == invariant2(u) && in_S[u] == false) {
  270. f[kp1] = u;
  271. in_S[u] = true;
  272. num_edges_on_k = 0;
  273. if (match(iter, dfs_num_k + 1));
  274. return true;
  275. in_S[u] = false;
  276. }
  277. }
  278. @}
  279. \paragraph{Case 2: $i \in G_1[k]$ and $j \not\in G_1[k]$.}
  280. Before we extend the subgraph by incrementing $k$, we need to finish
  281. verifying that $G_1[k]$ and $G_2[S]$ are isomorphic. We decrement the
  282. edge counter for every edge incident to $f(k)$ in $G_2[S]$, which
  283. should bring the counter back down to zero. If not we return false.
  284. @d Verify $G_1[k] \isomorphic G_2[S]$ and then find match for $j$
  285. @{
  286. vertex1_t k = dfs_vertices[dfs_num_k];
  287. @<Count out-edges of $f(k)$ in $G_2[S]$@>
  288. @<Count in-edges of $f(k)$ in $G_2[S]$@>
  289. if (num_edges_on_k != 0)
  290. return false;
  291. @<Find a match for $j$ and continue@>
  292. @}
  293. \noindent We decrement the edge counter for every vertex in
  294. $Adj[f(k)]$ that is also in $S$. We call \code{count\_if} to do the
  295. counting, using \code{boost::bind} to create the predicate functor.
  296. @d Count out-edges of $f(k)$ in $G_2[S]$
  297. @{
  298. num_edges_on_k -=
  299. count_if(adjacent_vertices(f[k], G2), make_indirect_pmap(in_S));
  300. @}
  301. \noindent Next we iterate through all the vertices in $S$ and for each
  302. we decrement the counter for each edge whose target is $k$.
  303. % We could specialize this for the case when G_2 is bidirectional.
  304. @d Count in-edges of $f(k)$ in $G_2[S]$
  305. @{
  306. for (int jj = 0; jj < dfs_num_k; ++jj) {
  307. vertex1_t j = dfs_vertices[jj];
  308. num_edges_on_k -= count(adjacent_vertices(f[j], G2), f[k]);
  309. }
  310. @}
  311. Now that we have finished verifying that $G_1[k] \isomorphic G_2[S]$,
  312. we can now consider extending the isomorphism. We need to find a match
  313. for $j$ in $V_2 - S$. Since $j$ is adjacent to $i$, we can further
  314. narrow down the search by only considering vertices adjacent to
  315. $f(i)$. Also, the vertex must have the same vertex invariant. Once we
  316. have a matching vertex $v$ we extend the matching subgraphs by
  317. incrementing $k$ and adding $v$ to $S$, we set $f(j) = v$, and we set
  318. the edge counter to $1$ (since $(i,j)$ is the first edge incident on
  319. our new $k$). We continue to the next edge by calling \code{match}. If
  320. that fails we undo the assignment $f(j) = v$.
  321. @d Find a match for $j$ and continue
  322. @{
  323. BGL_FORALL_ADJ_T(f[i], v, G2, Graph2)
  324. if (invariant2(v) == invariant1(j) && in_S[v] == false) {
  325. f[j] = v;
  326. in_S[v] = true;
  327. num_edges_on_k = 1;
  328. int next_k = std::max(dfs_num_k, std::max(dfs_num[i], dfs_num[j]));
  329. if (match(next(iter), next_k))
  330. return true;
  331. in_S[v] = false;
  332. }
  333. @}
  334. \paragraph{Case 3: both $i$ and $j$ are in $G_1[k]$.}
  335. Our goal is to check whether $(f(i),f(j)) \in E_2[S]$. If $f(j)$ is
  336. in $Adj[f(i)]$ then we have a match for the edge $(i,j)$, and can
  337. increment the counter for the number of edges incident on $k$ in
  338. $E_1[k]$. We continue by calling \code{match} on the next edge.
  339. @d Check to see if $(f(i),f(j)) \in E_2[S]$ and continue
  340. @{
  341. edge2_t e2;
  342. bool fi_fj_exists = false;
  343. typename graph_traits<Graph2>::out_edge_iterator io, io_end;
  344. for (tie(io, io_end) = out_edges(f[i], G2); io != io_end; ++io)
  345. if (target(*io, G2) == f[j]) {
  346. fi_fj_exists = true;
  347. e2 = *io;
  348. }
  349. if (fi_fj_exists && edge_compare(e2, *iter)) {
  350. ++num_edges_on_k;
  351. if (match(next(iter), dfs_num_k))
  352. return true;
  353. }
  354. @}
  355. \section{Public Interface}
  356. The following is the public interface for the \code{isomorphism}
  357. function. The input to the function is the two graphs $G_1$ and $G_2$,
  358. mappings from the vertices in the graphs to integers (in the range
  359. $[0,|V|)$), and a vertex invariant function object. The output of the
  360. function is an isomorphism $f$ if there is one. The \code{isomorphism}
  361. function returns true if the graphs are isomorphic and false
  362. otherwise. The invariant parameters are function objects that compute
  363. the vertex invariants for vertices of the two graphs. The
  364. \code{max\_invariant} parameter is to specify one past the largest
  365. integer that a vertex invariant number could be (the invariants
  366. numbers are assumed to span from zero to \code{max\_invariant-1}).
  367. The requirements on the template parameters are described below in the
  368. ``Concept checking'' code part.
  369. @d Isomorphism function interface
  370. @{
  371. template <typename Graph1, typename Graph2, typename IsoMapping,
  372. typename Invariant1, typename Invariant2, typename EdgeCompare,
  373. typename IndexMap1, typename IndexMap2>
  374. bool isomorphism(const Graph1& G1, const Graph2& G2, IsoMapping f,
  375. Invariant1 invariant1, Invariant2 invariant2,
  376. std::size_t max_invariant, EdgeCompare edge_compare,
  377. IndexMap1 index_map1, IndexMap2 index_map2)
  378. @}
  379. The function body consists of the concept checks followed by a quick
  380. check for empty graphs or graphs of different size and then constructs
  381. an algorithm object. We then call the \code{test\_isomorphism} member
  382. function, which runs the algorithm. The reason that we implement the
  383. algorithm using a class is that there are a fair number of internal
  384. data structures required, and it is easier to make these data members
  385. of a class and make each section of the algorithm a member
  386. function. This relieves us from the burden of passing lots of
  387. arguments to each function, while at the same time avoiding the evils
  388. of global variables (non-reentrant, etc.).
  389. @d Isomorphism function body
  390. @{
  391. {
  392. @<Concept checking@>
  393. @<Quick return based on size@>
  394. detail::isomorphism_algo<Graph1, Graph2, IsoMapping, Invariant1,
  395. Invariant2, EdgeCompare, IndexMap1, IndexMap2>
  396. algo(G1, G2, f, invariant1, invariant2, max_invariant,
  397. edge_compare,
  398. index_map1, index_map2);
  399. return algo.test_isomorphism();
  400. }
  401. @}
  402. \noindent If there are no vertices in either graph, then they are
  403. trivially isomorphic. If the graphs have different numbers of vertices
  404. then they are not isomorphic. We could also check the number of edges
  405. here, but that would introduce the \bglconcept{EdgeListGraph}
  406. requirement, which we otherwise do not need.
  407. @d Quick return based on size
  408. @{
  409. if (num_vertices(G1) != num_vertices(G2))
  410. return false;
  411. if (num_vertices(G1) == 0 && num_vertices(G2) == 0)
  412. return true;
  413. @}
  414. We use the Boost Concept Checking Library to make sure that the
  415. template arguments fulfill certain requirements. The graph types must
  416. model the \bglconcept{VertexListGraph} and \bglconcept{AdjacencyGraph}
  417. concepts. The vertex invariants must model the
  418. \stlconcept{AdaptableUnaryFunction} concept, with a vertex as their
  419. argument and an integer return type. The \code{IsoMapping} type
  420. representing the isomorphism $f$ must be a
  421. \pmconcept{ReadWritePropertyMap} that maps from vertices in $G_1$ to
  422. vertices in $G_2$. The two other index maps are
  423. \pmconcept{ReadablePropertyMap}s from vertices in $G_1$ and $G_2$ to
  424. unsigned integers.
  425. @d Concept checking
  426. @{
  427. // Graph requirements
  428. BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph1> ));
  429. BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph1> ));
  430. BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph2> ));
  431. BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph2> ));
  432. typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_t;
  433. typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
  434. typedef typename graph_traits<Graph1>::vertices_size_type size_type;
  435. // Vertex invariant requirement
  436. BOOST_CONCEPT_ASSERT(( AdaptableUnaryFunctionConcept<Invariant1,
  437. size_type, vertex1_t> ));
  438. BOOST_CONCEPT_ASSERT(( AdaptableUnaryFunctionConcept<Invariant2,
  439. size_type, vertex2_t> ));
  440. // Property map requirements
  441. BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<IsoMapping, vertex1_t> ));
  442. typedef typename property_traits<IsoMapping>::value_type IsoMappingValue;
  443. BOOST_STATIC_ASSERT((is_same<IsoMappingValue, vertex2_t>::value));
  444. BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap1, vertex1_t> ));
  445. typedef typename property_traits<IndexMap1>::value_type IndexMap1Value;
  446. BOOST_STATIC_ASSERT((is_convertible<IndexMap1Value, size_type>::value));
  447. BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap2, vertex2_t> ));
  448. typedef typename property_traits<IndexMap2>::value_type IndexMap2Value;
  449. BOOST_STATIC_ASSERT((is_convertible<IndexMap2Value, size_type>::value));
  450. @}
  451. \section{Data Structure Setup}
  452. The following is the outline of the isomorphism algorithm class. The
  453. class is templated on all of the same parameters as the
  454. \code{isomorphism} function, and all of the parameter values are
  455. stored in the class as data members, in addition to the internal data
  456. structures.
  457. @d Isomorphism algorithm class
  458. @{
  459. template <typename Graph1, typename Graph2, typename IsoMapping,
  460. typename Invariant1, typename Invariant2, typename EdgeCompare,
  461. typename IndexMap1, typename IndexMap2>
  462. class isomorphism_algo
  463. {
  464. @<Typedefs for commonly used types@>
  465. @<Data members for the parameters@>
  466. @<Internal data structures@>
  467. friend struct compare_multiplicity;
  468. @<Invariant multiplicity comparison functor@>
  469. @<DFS visitor to record vertex and edge order@>
  470. @<Edge comparison predicate@>
  471. public:
  472. @<Isomorphism algorithm constructor@>
  473. @<Test isomorphism member function@>
  474. private:
  475. @<Match function@>
  476. };
  477. @}
  478. The interesting parts of this class are the \code{test\_isomorphism}
  479. function and the \code{match} function. We focus on those in the
  480. following sections, and leave the other parts of the class to the
  481. Appendix.
  482. The \code{test\_isomorphism} function does all of the setup required
  483. of the algorithm. This consists of sorting the vertices according to
  484. invariant multiplicity, and then by DFS order. The edges are then
  485. sorted as previously described. The last step of this function is to
  486. begin the backtracking search.
  487. @d Test isomorphism member function
  488. @{
  489. bool test_isomorphism()
  490. {
  491. @<Quick return if the vertex invariants do not match up@>
  492. @<Sort vertices according to invariant multiplicity@>
  493. @<Order vertices and edges by DFS@>
  494. @<Sort edges according to vertex DFS order@>
  495. int dfs_num_k = -1;
  496. return this->match(ordered_edges.begin(), dfs_num_k);
  497. }
  498. @}
  499. As a first check to rule out graphs that have no possibility of
  500. matching, one can create a list of computed vertex invariant numbers
  501. for the vertices in each graph, sort the two lists, and then compare
  502. them. If the two lists are different then the two graphs are not
  503. isomorphic. If the two lists are the same then the two graphs may be
  504. isomorphic.
  505. @d Quick return if the vertex invariants do not match up
  506. @{
  507. {
  508. std::vector<invar1_value> invar1_array;
  509. BGL_FORALL_VERTICES_T(v, G1, Graph1)
  510. invar1_array.push_back(invariant1(v));
  511. sort(invar1_array);
  512. std::vector<invar2_value> invar2_array;
  513. BGL_FORALL_VERTICES_T(v, G2, Graph2)
  514. invar2_array.push_back(invariant2(v));
  515. sort(invar2_array);
  516. if (! equal(invar1_array, invar2_array))
  517. return false;
  518. }
  519. @}
  520. Next we compute the invariant multiplicity, the number of vertices
  521. with the same invariant number. The \code{invar\_mult} vector is
  522. indexed by invariant number. We loop through all the vertices in the
  523. graph to record the multiplicity. We then order the vertices by their
  524. invariant multiplicity. This will allow us to search the more
  525. constrained vertices first.
  526. @d Sort vertices according to invariant multiplicity
  527. @{
  528. std::vector<vertex1_t> V_mult;
  529. BGL_FORALL_VERTICES_T(v, G1, Graph1)
  530. V_mult.push_back(v);
  531. {
  532. std::vector<size_type> multiplicity(max_invariant, 0);
  533. BGL_FORALL_VERTICES_T(v, G1, Graph1)
  534. ++multiplicity[invariant1(v)];
  535. sort(V_mult, compare_multiplicity(invariant1, &multiplicity[0]));
  536. }
  537. @}
  538. \noindent The definition of the \code{compare\_multiplicity} predicate
  539. is shown below. This predicate provides the glue that binds
  540. \code{std::sort} to our current purpose.
  541. @d Invariant multiplicity comparison functor
  542. @{
  543. struct compare_multiplicity
  544. {
  545. compare_multiplicity(Invariant1 invariant1, size_type* multiplicity)
  546. : invariant1(invariant1), multiplicity(multiplicity) { }
  547. bool operator()(const vertex1_t& x, const vertex1_t& y) const {
  548. return multiplicity[invariant1(x)] < multiplicity[invariant1(y)];
  549. }
  550. Invariant1 invariant1;
  551. size_type* multiplicity;
  552. };
  553. @}
  554. \subsection{Ordering by DFS Discover Time}
  555. Next we order the vertices and edges by DFS discover time. We would
  556. normally call the BGL \code{depth\_first\_search} function to do this,
  557. but we want the roots of the DFS tree's to be ordered by invariant
  558. multiplicity. Therefore we implement the outer-loop of the DFS here
  559. and then call \code{depth\_\-first\_\-visit} to handle the recursive
  560. portion of the DFS. The \code{record\_dfs\_order} adapts the DFS to
  561. record the ordering, storing the results in in the
  562. \code{dfs\_vertices} and \code{ordered\_edges} arrays. We then create
  563. the \code{dfs\_num} array which provides a mapping from vertex to DFS
  564. number.
  565. @d Order vertices and edges by DFS
  566. @{
  567. std::vector<default_color_type> color_vec(num_vertices(G1));
  568. safe_iterator_property_map<std::vector<default_color_type>::iterator, IndexMap1>
  569. color_map(color_vec.begin(), color_vec.size(), index_map1);
  570. record_dfs_order dfs_visitor(dfs_vertices, ordered_edges);
  571. typedef color_traits<default_color_type> Color;
  572. for (vertex_iter u = V_mult.begin(); u != V_mult.end(); ++u) {
  573. if (color_map[*u] == Color::white()) {
  574. dfs_visitor.start_vertex(*u, G1);
  575. depth_first_visit(G1, *u, dfs_visitor, color_map);
  576. }
  577. }
  578. // Create the dfs_num array and dfs_num_map
  579. dfs_num_vec.resize(num_vertices(G1));
  580. dfs_num = make_safe_iterator_property_map(dfs_num_vec.begin(),
  581. dfs_num_vec.size(), index_map1);
  582. size_type n = 0;
  583. for (vertex_iter v = dfs_vertices.begin(); v != dfs_vertices.end(); ++v)
  584. dfs_num[*v] = n++;
  585. @}
  586. \noindent The definition of the \code{record\_dfs\_order} visitor
  587. class is as follows.
  588. @d DFS visitor to record vertex and edge order
  589. @{
  590. struct record_dfs_order : default_dfs_visitor
  591. {
  592. record_dfs_order(std::vector<vertex1_t>& v, std::vector<edge1_t>& e)
  593. : vertices(v), edges(e) { }
  594. void discover_vertex(vertex1_t v, const Graph1&) const {
  595. vertices.push_back(v);
  596. }
  597. void examine_edge(edge1_t e, const Graph1& G1) const {
  598. edges.push_back(e);
  599. }
  600. std::vector<vertex1_t>& vertices;
  601. std::vector<edge1_t>& edges;
  602. };
  603. @}
  604. The final stage of the setup is to reorder the edges so that all edges
  605. belonging to $G_1[k]$ appear before any edges not in $G_1[k]$, for
  606. $k=1,...,n$.
  607. @d Sort edges according to vertex DFS order
  608. @{
  609. sort(ordered_edges, edge_cmp(G1, dfs_num));
  610. @}
  611. \noindent The edge comparison function object is defined as follows.
  612. @d Edge comparison predicate
  613. @{
  614. struct edge_cmp {
  615. edge_cmp(const Graph1& G1, DFSNumMap dfs_num)
  616. : G1(G1), dfs_num(dfs_num) { }
  617. bool operator()(const edge1_t& e1, const edge1_t& e2) const {
  618. using namespace std;
  619. vertex1_t u1 = dfs_num[source(e1,G1)], v1 = dfs_num[target(e1,G1)];
  620. vertex1_t u2 = dfs_num[source(e2,G1)], v2 = dfs_num[target(e2,G1)];
  621. int m1 = max(u1, v1);
  622. int m2 = max(u2, v2);
  623. // lexicographical comparison
  624. return make_pair(m1, make_pair(u1, v1))
  625. < make_pair(m2, make_pair(u2, v2));
  626. }
  627. const Graph1& G1;
  628. DFSNumMap dfs_num;
  629. };
  630. @}
  631. \section{Appendix}
  632. @d Typedefs for commonly used types
  633. @{
  634. typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_t;
  635. typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
  636. typedef typename graph_traits<Graph1>::edge_descriptor edge1_t;
  637. typedef typename graph_traits<Graph2>::edge_descriptor edge2_t;
  638. typedef typename graph_traits<Graph1>::vertices_size_type size_type;
  639. typedef typename Invariant1::result_type invar1_value;
  640. typedef typename Invariant2::result_type invar2_value;
  641. @}
  642. @d Data members for the parameters
  643. @{
  644. const Graph1& G1;
  645. const Graph2& G2;
  646. IsoMapping f;
  647. Invariant1 invariant1;
  648. Invariant2 invariant2;
  649. std::size_t max_invariant;
  650. EdgeCompare edge_compare;
  651. IndexMap1 index_map1;
  652. IndexMap2 index_map2;
  653. @}
  654. @d Internal data structures
  655. @{
  656. std::vector<vertex1_t> dfs_vertices;
  657. typedef typename std::vector<vertex1_t>::iterator vertex_iter;
  658. std::vector<int> dfs_num_vec;
  659. typedef safe_iterator_property_map<typename std::vector<int>::iterator,
  660. IndexMap1> DFSNumMap;
  661. DFSNumMap dfs_num;
  662. std::vector<edge1_t> ordered_edges;
  663. typedef typename std::vector<edge1_t>::iterator edge_iter;
  664. std::vector<char> in_S_vec;
  665. typedef safe_iterator_property_map<typename std::vector<char>::iterator,
  666. IndexMap2> InSMap;
  667. InSMap in_S;
  668. int num_edges_on_k;
  669. @}
  670. @d Isomorphism algorithm constructor
  671. @{
  672. isomorphism_algo(const Graph1& G1, const Graph2& G2, IsoMapping f,
  673. Invariant1 invariant1, Invariant2 invariant2,
  674. std::size_t max_invariant,
  675. EdgeCompare edge_compare,
  676. IndexMap1 index_map1, IndexMap2 index_map2)
  677. : G1(G1), G2(G2), f(f), invariant1(invariant1), invariant2(invariant2),
  678. max_invariant(max_invariant), edge_compare(edge_compare),
  679. index_map1(index_map1), index_map2(index_map2)
  680. {
  681. in_S_vec.resize(num_vertices(G1));
  682. in_S = make_safe_iterator_property_map
  683. (in_S_vec.begin(), in_S_vec.size(), index_map2);
  684. }
  685. @}
  686. @o isomorphism.hpp
  687. @{
  688. // Copyright (C) 2001 Jeremy Siek, Douglas Gregor, Brian Osman
  689. //
  690. // Permission to copy, use, sell and distribute this software is granted
  691. // provided this copyright notice appears in all copies.
  692. // Permission to modify the code and to distribute modified code is granted
  693. // provided this copyright notice appears in all copies, and a notice
  694. // that the code was modified is included with the copyright notice.
  695. //
  696. // This software is provided "as is" without express or implied warranty,
  697. // and with no claim as to its suitability for any purpose.
  698. #ifndef BOOST_GRAPH_ISOMORPHISM_HPP
  699. #define BOOST_GRAPH_ISOMORPHISM_HPP
  700. #include <utility>
  701. #include <vector>
  702. #include <iterator>
  703. #include <algorithm>
  704. #include <boost/graph/iteration_macros.hpp>
  705. #include <boost/graph/depth_first_search.hpp>
  706. #include <boost/utility.hpp>
  707. #include <boost/detail/algorithm.hpp>
  708. #include <boost/pending/indirect_cmp.hpp> // for make_indirect_pmap
  709. namespace boost {
  710. namespace detail {
  711. @<Isomorphism algorithm class@>
  712. template <typename Graph, typename InDegreeMap>
  713. void compute_in_degree(const Graph& g, InDegreeMap in_degree_map)
  714. {
  715. BGL_FORALL_VERTICES_T(v, g, Graph)
  716. put(in_degree_map, v, 0);
  717. BGL_FORALL_VERTICES_T(u, g, Graph)
  718. BGL_FORALL_ADJ_T(u, v, g, Graph)
  719. put(in_degree_map, v, get(in_degree_map, v) + 1);
  720. }
  721. } // namespace detail
  722. @<Degree vertex invariant functor@>
  723. @<Isomorphism function interface@>
  724. @<Isomorphism function body@>
  725. namespace detail {
  726. struct default_edge_compare {
  727. template <typename Edge1, typename Edge2>
  728. bool operator()(Edge1 e1, Edge2 e2) const { return true; }
  729. };
  730. template <typename Graph1, typename Graph2,
  731. typename IsoMapping,
  732. typename IndexMap1, typename IndexMap2,
  733. typename P, typename T, typename R>
  734. bool isomorphism_impl(const Graph1& G1, const Graph2& G2,
  735. IsoMapping f, IndexMap1 index_map1, IndexMap2 index_map2,
  736. const bgl_named_params<P,T,R>& params)
  737. {
  738. std::vector<std::size_t> in_degree1_vec(num_vertices(G1));
  739. typedef safe_iterator_property_map<std::vector<std::size_t>::iterator,
  740. IndexMap1> InDeg1;
  741. InDeg1 in_degree1(in_degree1_vec.begin(), in_degree1_vec.size(), index_map1);
  742. compute_in_degree(G1, in_degree1);
  743. std::vector<std::size_t> in_degree2_vec(num_vertices(G2));
  744. typedef safe_iterator_property_map<std::vector<std::size_t>::iterator,
  745. IndexMap2> InDeg2;
  746. InDeg2 in_degree2(in_degree2_vec.begin(), in_degree2_vec.size(), index_map2);
  747. compute_in_degree(G2, in_degree2);
  748. degree_vertex_invariant<InDeg1, Graph1> invariant1(in_degree1, G1);
  749. degree_vertex_invariant<InDeg2, Graph2> invariant2(in_degree2, G2);
  750. default_edge_compare edge_cmp;
  751. return isomorphism(G1, G2, f,
  752. choose_param(get_param(params, vertex_invariant1_t()), invariant1),
  753. choose_param(get_param(params, vertex_invariant2_t()), invariant2),
  754. choose_param(get_param(params, vertex_max_invariant_t()),
  755. invariant2.max()),
  756. choose_param(get_param(params, edge_compare_t()), edge_cmp),
  757. index_map1, index_map2
  758. );
  759. }
  760. } // namespace detail
  761. // Named parameter interface
  762. template <typename Graph1, typename Graph2, class P, class T, class R>
  763. bool isomorphism(const Graph1& g1,
  764. const Graph2& g2,
  765. const bgl_named_params<P,T,R>& params)
  766. {
  767. typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
  768. typename std::vector<vertex2_t>::size_type n = num_vertices(g1);
  769. std::vector<vertex2_t> f(n);
  770. return detail::isomorphism_impl
  771. (g1, g2,
  772. choose_param(get_param(params, vertex_isomorphism_t()),
  773. make_safe_iterator_property_map(f.begin(), f.size(),
  774. choose_const_pmap(get_param(params, vertex_index1),
  775. g1, vertex_index), vertex2_t())),
  776. choose_const_pmap(get_param(params, vertex_index1), g1, vertex_index),
  777. choose_const_pmap(get_param(params, vertex_index2), g2, vertex_index),
  778. params
  779. );
  780. }
  781. // All defaults interface
  782. template <typename Graph1, typename Graph2>
  783. bool isomorphism(const Graph1& g1, const Graph2& g2)
  784. {
  785. return isomorphism(g1, g2,
  786. bgl_named_params<int, buffer_param_t>(0));// bogus named param
  787. }
  788. // Verify that the given mapping iso_map from the vertices of g1 to the
  789. // vertices of g2 describes an isomorphism.
  790. // Note: this could be made much faster by specializing based on the graph
  791. // concepts modeled, but since we're verifying an O(n^(lg n)) algorithm,
  792. // O(n^4) won't hurt us.
  793. template<typename Graph1, typename Graph2, typename IsoMap>
  794. inline bool verify_isomorphism(const Graph1& g1, const Graph2& g2, IsoMap iso_map)
  795. {
  796. #if 0
  797. // problematic for filtered_graph!
  798. if (num_vertices(g1) != num_vertices(g2) || num_edges(g1) != num_edges(g2))
  799. return false;
  800. #endif
  801. for (typename graph_traits<Graph1>::edge_iterator e1 = edges(g1).first;
  802. e1 != edges(g1).second; ++e1) {
  803. bool found_edge = false;
  804. for (typename graph_traits<Graph2>::edge_iterator e2 = edges(g2).first;
  805. e2 != edges(g2).second && !found_edge; ++e2) {
  806. if (source(*e2, g2) == get(iso_map, source(*e1, g1)) &&
  807. target(*e2, g2) == get(iso_map, target(*e1, g1))) {
  808. found_edge = true;
  809. }
  810. }
  811. if (!found_edge)
  812. return false;
  813. }
  814. return true;
  815. }
  816. } // namespace boost
  817. #include <boost/graph/iteration_macros_undef.hpp>
  818. #endif // BOOST_GRAPH_ISOMORPHISM_HPP
  819. @}
  820. \bibliographystyle{abbrv}
  821. \bibliography{ggcl}
  822. \end{document}
  823. % LocalWords: Isomorphism Siek isomorphism adjacency subgraph subgraphs OM DFS
  824. % LocalWords: ISOMORPH Invariants invariants typename IsoMapping bool const
  825. % LocalWords: VertexInvariant VertexIndexMap iterator typedef VertexG Idx num
  826. % LocalWords: InvarValue struct invar vec iter tmp_matches mult inserter permute ui
  827. % LocalWords: dfs cmp isomorph VertexIter edge_iter_t IndexMap desc RPH ATCH pre
  828. % LocalWords: iterators VertexListGraph EdgeListGraph BidirectionalGraph tmp
  829. % LocalWords: ReadWritePropertyMap VertexListGraphConcept EdgeListGraphConcept
  830. % LocalWords: BidirectionalGraphConcept ReadWritePropertyMapConcept indices ei
  831. % LocalWords: IsoMappingValue ReadablePropertyMapConcept namespace InvarFun
  832. % LocalWords: MultMap vip inline bitset typedefs fj hpp ifndef adaptor params
  833. % LocalWords: bgl param pmap endif