isomorphism-impl-v2.w 37 KB

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