isomorphism-impl.w 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  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. % jweb -np isomorphism-impl.w; dot -Tps out.dot -o out.eps; dot -Tps in.dot -o in.eps; latex isomorphism-impl.tex; dvips isomorphism-impl.dvi -o isomorphism-impl.ps
  38. \setlength\overfullrule{5pt}
  39. \tolerance=10000
  40. \sloppy
  41. \hfuzz=10pt
  42. \makeindex
  43. \newcommand{\isomorphic}{\cong}
  44. \begin{document}
  45. \title{An Implementation of Isomorphism Testing}
  46. \author{Jeremy G. Siek}
  47. \maketitle
  48. \section{Introduction}
  49. This paper documents the implementation of the \code{isomorphism()}
  50. function of the Boost Graph Library. The implementation was by Jeremy
  51. Siek with algorithmic improvements and test code from Douglas Gregor.
  52. The \code{isomorphism()} function answers the question, ``are these
  53. two graphs equal?'' By \emph{equal}, we mean the two graphs have the
  54. same structure---the vertices and edges are connected in the same
  55. way. The mathematical name for this kind of equality is
  56. \emph{isomorphic}.
  57. An \emph{isomorphism} is a one-to-one mapping of the vertices in one
  58. graph to the vertices of another graph such that adjacency is
  59. preserved. Another words, given graphs $G_{1} = (V_{1},E_{1})$ and
  60. $G_{2} = (V_{2},E_{2})$, an isomorphism is a function $f$ such that
  61. for all pairs of vertices $a,b$ in $V_{1}$, edge $(a,b)$ is in $E_{1}$
  62. if and only if edge $(f(a),f(b))$ is in $E_{2}$.
  63. Both graphs must be the same size, so let $N = |V_1| = |V_2|$. The
  64. graph $G_1$ is \emph{isomorphic} to $G_2$ if an isomorphism exists
  65. between the two graphs, which we denote by $G_1 \isomorphic G_2$.
  66. In the following discussion we will need to use several notions from
  67. graph theory. The graph $G_s=(V_s,E_s)$ is a \emph{subgraph} of graph
  68. $G=(V,E)$ if $V_s \subseteq V$ and $E_s \subseteq E$. An
  69. \emph{induced subgraph}, denoted by $G[V_s]$, of a graph $G=(V,E)$
  70. consists of the vertices in $V_s$, which is a subset of $V$, and every
  71. edge $(u,v)$ in $E$ such that both $u$ and $v$ are in $V_s$. We use
  72. the notation $E[V_s]$ to mean the edges in $G[V_s]$.
  73. In some places we express a function as a set of pairs, so the set $f
  74. = \{ \pair{a_1}{b_1}, \ldots, \pair{a_n}{b_n} \}$
  75. means $f(a_i) = b_i$ for $i=1,\ldots,n$.
  76. \section{Exhaustive Backtracking Search}
  77. The algorithm used by the \code{isomorphism()} function is, at
  78. first approximation, an exhaustive search implemented via
  79. backtracking. The backtracking algorithm is a recursive function. At
  80. each stage we will try to extend the match that we have found so far.
  81. So suppose that we have already determined that some subgraph of $G_1$
  82. is isomorphic to a subgraph of $G_2$. We then try to add a vertex to
  83. each subgraph such that the new subgraphs are still isomorphic to one
  84. another. At some point we may hit a dead end---there are no vertices
  85. that can be added to extend the isomorphic subgraphs. We then
  86. backtrack to previous smaller matching subgraphs, and try extending
  87. with a different vertex choice. The process ends by either finding a
  88. complete mapping between $G_1$ and $G_2$ and return true, or by
  89. exhausting all possibilities and returning false.
  90. We are going to consider the vertices of $G_1$ in a specific order
  91. (more about this later), so assume that the vertices of $G_1$ are
  92. labeled $1,\ldots,N$ according to the order that we plan to add them
  93. to the subgraph. Let $G_1[k]$ denote the subgraph of $G_1$ induced by
  94. the first $k$ vertices, with $G_1[0]$ being an empty graph. At each
  95. stage of the recursion we start with an isomorphism $f_{k-1}$ between
  96. $G_1[k-1]$ and a subgraph of $G_2$, which we denote by $G_2[S]$, so
  97. $G_1[k-1] \isomorphic G_2[S]$. The vertex set $S$ is the subset of
  98. $V_2$ that corresponds via $f_{k-1}$ to the first $k-1$ vertices in
  99. $G_1$. We try to extend the isomorphism by finding a vertex $v \in V_2
  100. - S$ that matches with vertex $k$. If a matching vertex is found, we
  101. have a new isomorphism $f_k$ with $G_1[k] \isomorphic G_2[S \union \{
  102. v \}]$.
  103. \begin{tabbing}
  104. IS\=O\=M\=O\=RPH($k$, $S$, $f_{k-1}$) $\equiv$ \\
  105. \>\textbf{if} ($k = |V_1|+1$) \\
  106. \>\>\textbf{return} true \\
  107. \>\textbf{for} each vertex $v \in V_2 - S$ \\
  108. \>\>\textbf{if} (MATCH($k$, $v$)) \\
  109. \>\>\>$f_k = f_{k-1} \union \pair{k}{v}$ \\
  110. \>\>\>ISOMORPH($k+1$, $S \union \{ v \}$, $f_k$)\\
  111. \>\>\textbf{else}\\
  112. \>\>\>\textbf{return} false \\
  113. \\
  114. ISOMORPH($0$, $G_1$, $\emptyset$, $G_2$)
  115. \end{tabbing}
  116. The basic idea of the match operation is to check whether $G_1[k]$ is
  117. isomorphic to $G_2[S \union \{ v \}]$. We already know that $G_1[k-1]
  118. \isomorphic G_2[S]$ with the mapping $f_{k-1}$, so all we need to do
  119. is verify that the edges in $E_1[k] - E_1[k-1]$ connect vertices that
  120. correspond to the vertices connected by the edges in $E_2[S \union \{
  121. v \}] - E_2[S]$. The edges in $E_1[k] - E_1[k-1]$ are all the
  122. out-edges $(k,j)$ and in-edges $(j,k)$ of $k$ where $j$ is less than
  123. or equal to $k$ according to the ordering. The edges in $E_2[S \union
  124. \{ v \}] - E_2[S]$ consists of all the out-edges $(v,u)$ and
  125. in-edges $(u,v)$ of $v$ where $u \in S$.
  126. \begin{tabbing}
  127. M\=ATCH($k$, $v$) $\equiv$ \\
  128. \>$out \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)$ \\
  129. \>$in \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)$ \\
  130. \>\textbf{return} $out \Land in$
  131. \end{tabbing}
  132. The problem with the exhaustive backtracking algorithm is that there
  133. are $N!$ possible vertex mappings, and $N!$ gets very large as $N$
  134. increases, so we need to prune the search space. We use the pruning
  135. techniques described in
  136. \cite{deo77:_new_algo_digraph_isomorph,fortin96:_isomorph,reingold77:_combin_algo}
  137. that originated in
  138. \cite{sussenguth65:_isomorphism,unger64:_isomorphism}.
  139. \section{Vertex Invariants}
  140. \label{sec:vertex-invariants}
  141. One way to reduce the search space is through the use of \emph{vertex
  142. invariants}. The idea is to compute a number for each vertex $i(v)$
  143. such that $i(v) = i(v')$ if there exists some isomorphism $f$ where
  144. $f(v) = v'$. Then when we look for a match to some vertex $v$, we only
  145. need to consider those vertices that have the same vertex invariant
  146. number. The number of vertices in a graph with the same vertex
  147. invariant number $i$ is called the \emph{invariant multiplicity} for
  148. $i$. In this implementation, by default we use the out-degree of the
  149. vertex as the vertex invariant, though the user can also supply their
  150. own invariant function. The ability of the invariant function to prune
  151. the search space varies widely with the type of graph.
  152. As a first check to rule out graphs that have no possibility of
  153. matching, one can create a list of computed vertex invariant numbers
  154. for the vertices in each graph, sort the two lists, and then compare
  155. them. If the two lists are different then the two graphs are not
  156. isomorphic. If the two lists are the same then the two graphs may be
  157. isomorphic.
  158. Also, we extend the MATCH operation to use the vertex invariants to
  159. help rule out vertices.
  160. \begin{tabbing}
  161. M\=A\=T\=C\=H-INVAR($k$, $v$) $\equiv$ \\
  162. \>$out \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] \Land i(v) = i(k) \Big)$ \\
  163. \>$in \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] \Land i(v) = i(k) \Big)$ \\
  164. \>\textbf{return} $out \Land in$
  165. \end{tabbing}
  166. \section{Vertex Order}
  167. A good choice of the labeling for the vertices (which determines the
  168. order in which the subgraph $G_1[k]$ is grown) can also reduce the
  169. search space. In the following we discuss two labeling heuristics.
  170. \subsection{Most Constrained First}
  171. Consider the most constrained vertices first. That is, examine
  172. lower-degree vertices before higher-degree vertices. This reduces the
  173. search space because it chops off a trunk before the trunk has a
  174. chance to blossom out. We can generalize this to use vertex
  175. invariants. We examine vertices with low invariant multiplicity
  176. before examining vertices with high invariant multiplicity.
  177. \subsection{Adjacent First}
  178. The MATCH operation only considers edges when the other vertex already
  179. has a mapping defined. This means that the MATCH operation can only
  180. weed out vertices that are adjacent to vertices that have already been
  181. matched. Therefore, when choosing the next vertex to examine, it is
  182. desirable to choose one that is adjacent a vertex already in $S_1$.
  183. \subsection{DFS Order, Starting with Lowest Multiplicity}
  184. For this implementation, we combine the above two heuristics in the
  185. following way. To implement the ``adjacent first'' heuristic we apply
  186. DFS to the graph, and use the DFS discovery order as our vertex
  187. order. To comply with the ``most constrained first'' heuristic we
  188. order the roots of our DFS trees by invariant multiplicity.
  189. \section{Implementation}
  190. The following is the public interface for the \code{isomorphism}
  191. function. The input to the function is the two graphs $G_1$ and $G_2$,
  192. mappings from the vertices in the graphs to integers (in the range
  193. $[0,|V|)$), and a vertex invariant function object. The output of the
  194. function is an isomorphism $f$ if there is one. The \code{isomorphism}
  195. function returns true if the graphs are isomorphic and false
  196. otherwise. The requirements on type template parameters are described
  197. below in the section ``Concept checking''.
  198. @d Isomorphism Function Interface
  199. @{
  200. template <typename Graph1, typename Graph2,
  201. typename IndexMapping,
  202. typename VertexInvariant1, typename VertexInvariant2,
  203. typename IndexMap1, typename IndexMap2>
  204. bool isomorphism(const Graph1& g1, const Graph2& g2,
  205. IndexMapping f,
  206. VertexInvariant1 invariant1, VertexInvariant2 invariant2,
  207. IndexMap1 index_map1, IndexMap2 index_map2)
  208. @}
  209. The main outline of the \code{isomorphism} function is as
  210. follows. Most of the steps in this function are for setting up the
  211. vertex ordering, first ordering the vertices by invariant multiplicity
  212. and then by DFS order. The last step is the call to the
  213. \code{isomorph} function which starts the backtracking search.
  214. @d Isomorphism Function Body
  215. @{
  216. {
  217. @<Some type definitions and iterator declarations@>
  218. @<Concept checking@>
  219. @<Quick return with false if $|V_1| \neq |V_2|$@>
  220. @<Compute vertex invariants@>
  221. @<Quick return if the graph's invariants do not match@>
  222. @<Compute invariant multiplicity@>
  223. @<Sort vertices by invariant multiplicity@>
  224. @<Order the vertices by DFS discover time@>
  225. @<Order the edges by DFS discover time@>
  226. @<Invoke recursive \code{isomorph} function@>
  227. }
  228. @}
  229. There are some types that will be used throughout the function, which
  230. we create shortened names for here. We will also need vertex
  231. iterators for \code{g1} and \code{g2} in several places, so we define
  232. them here.
  233. @d Some type definitions and iterator declarations
  234. @{
  235. typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_t;
  236. typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
  237. typedef typename graph_traits<Graph1>::vertices_size_type size_type;
  238. typename graph_traits<Graph1>::vertex_iterator i1, i1_end;
  239. typename graph_traits<Graph2>::vertex_iterator i2, i2_end;
  240. @}
  241. We use the Boost Concept Checking Library to make sure that the type
  242. arguments to the function fulfill there requirements. The
  243. \code{Graph1} type must be a \bglconcept{VertexListGraph} and a
  244. \bglconcept{EdgeListGraph}. The \code{Graph2} type must be a
  245. \bglconcept{VertexListGraph} and a
  246. \bglconcept{BidirectionalGraph}. The \code{IndexMapping} type that
  247. represents the isomorphism $f$ must be a
  248. \pmconcept{ReadWritePropertyMap} that maps from vertices in $G_1$ to
  249. vertices in $G_2$. The two other index maps are
  250. \pmconcept{ReadablePropertyMap}s from vertices in $G_1$ and $G_2$ to
  251. unsigned integers.
  252. @d Concept checking
  253. @{
  254. // Graph requirements
  255. BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph1> ));
  256. BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph1> ));
  257. BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph2> ));
  258. BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph2> ));
  259. // Property map requirements
  260. BOOST_CONCEPT_ASSERT(( ReadWritePropertyMapConcept<IndexMapping, vertex1_t> ));
  261. typedef typename property_traits<IndexMapping>::value_type IndexMappingValue;
  262. BOOST_STATIC_ASSERT((is_same<IndexMappingValue, vertex2_t>::value));
  263. BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap1, vertex1_t> ));
  264. typedef typename property_traits<IndexMap1>::value_type IndexMap1Value;
  265. BOOST_STATIC_ASSERT((is_convertible<IndexMap1Value, size_type>::value));
  266. BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap2, vertex2_t> ));
  267. typedef typename property_traits<IndexMap2>::value_type IndexMap2Value;
  268. BOOST_STATIC_ASSERT((is_convertible<IndexMap2Value, size_type>::value));
  269. @}
  270. \noindent If there are no vertices in either graph, then they are trivially
  271. isomorphic.
  272. @d Quick return with false if $|V_1| \neq |V_2|$
  273. @{
  274. if (num_vertices(g1) != num_vertices(g2))
  275. return false;
  276. @}
  277. \subsection{Ordering by Vertex Invariant Multiplicity}
  278. The user can supply the vertex invariant functions as a
  279. \stlconcept{AdaptableUnaryFunction} (with the addition of the
  280. \code{max} function) in the \code{invariant1} and \code{invariant2}
  281. parameters. We also define a default which uses the out-degree and
  282. in-degree of a vertex. The following is the definition of the function
  283. object for the default vertex invariant. User-defined vertex invariant
  284. function objects should follow the same pattern.
  285. @d Degree vertex invariant
  286. @{
  287. template <typename InDegreeMap, typename Graph>
  288. class degree_vertex_invariant
  289. {
  290. public:
  291. typedef typename graph_traits<Graph>::vertex_descriptor argument_type;
  292. typedef typename graph_traits<Graph>::degree_size_type result_type;
  293. degree_vertex_invariant(const InDegreeMap& in_degree_map, const Graph& g)
  294. : m_in_degree_map(in_degree_map), m_g(g) { }
  295. result_type operator()(argument_type v) const {
  296. return (num_vertices(m_g) + 1) * out_degree(v, m_g)
  297. + get(m_in_degree_map, v);
  298. }
  299. // The largest possible vertex invariant number
  300. result_type max() const {
  301. return num_vertices(m_g) * num_vertices(m_g) + num_vertices(m_g);
  302. }
  303. private:
  304. InDegreeMap m_in_degree_map;
  305. const Graph& m_g;
  306. };
  307. @}
  308. Since the invariant function may be expensive to compute, we
  309. pre-compute the invariant numbers for every vertex in the two
  310. graphs. The variables \code{invar1} and \code{invar2} are property
  311. maps for accessing the stored invariants, which are described next.
  312. @d Compute vertex invariants
  313. @{
  314. @<Setup storage for vertex invariants@>
  315. for (tie(i1, i1_end) = vertices(g1); i1 != i1_end; ++i1)
  316. invar1[*i1] = invariant1(*i1);
  317. for (tie(i2, i2_end) = vertices(g2); i2 != i2_end; ++i2)
  318. invar2[*i2] = invariant2(*i2);
  319. @}
  320. \noindent We store the invariants in two vectors, indexed by the vertex indices
  321. of the two graphs. We then create property maps for accessing these
  322. two vectors in a more convenient fashion (they go directly from vertex
  323. to invariant, instead of vertex to index to invariant).
  324. @d Setup storage for vertex invariants
  325. @{
  326. typedef typename VertexInvariant1::result_type InvarValue1;
  327. typedef typename VertexInvariant2::result_type InvarValue2;
  328. typedef std::vector<InvarValue1> invar_vec1_t;
  329. typedef std::vector<InvarValue2> invar_vec2_t;
  330. invar_vec1_t invar1_vec(num_vertices(g1));
  331. invar_vec2_t invar2_vec(num_vertices(g2));
  332. typedef typename invar_vec1_t::iterator vec1_iter;
  333. typedef typename invar_vec2_t::iterator vec2_iter;
  334. iterator_property_map<vec1_iter, IndexMap1, InvarValue1, InvarValue1&>
  335. invar1(invar1_vec.begin(), index_map1);
  336. iterator_property_map<vec2_iter, IndexMap2, InvarValue2, InvarValue2&>
  337. invar2(invar2_vec.begin(), index_map2);
  338. @}
  339. As discussed in \S\ref{sec:vertex-invariants}, we can quickly rule out
  340. the possibility of any isomorphism between two graphs by checking to
  341. see if the vertex invariants can match up. We sort both vectors of vertex
  342. invariants, and then check to see if they are equal.
  343. @d Quick return if the graph's invariants do not match
  344. @{
  345. { // check if the graph's invariants do not match
  346. invar_vec1_t invar1_tmp(invar1_vec);
  347. invar_vec2_t invar2_tmp(invar2_vec);
  348. std::sort(invar1_tmp.begin(), invar1_tmp.end());
  349. std::sort(invar2_tmp.begin(), invar2_tmp.end());
  350. if (! std::equal(invar1_tmp.begin(), invar1_tmp.end(),
  351. invar2_tmp.begin()))
  352. return false;
  353. }
  354. @}
  355. Next we compute the invariant multiplicity, the number of vertices
  356. with the same invariant number. The \code{invar\_mult} vector is
  357. indexed by invariant number. We loop through all the vertices in the
  358. graph to record the multiplicity.
  359. @d Compute invariant multiplicity
  360. @{
  361. std::vector<std::size_t> invar_mult(invariant1.max(), 0);
  362. for (tie(i1, i1_end) = vertices(g1); i1 != i1_end; ++i1)
  363. ++invar_mult[invar1[*i1]];
  364. @}
  365. \noindent We then order the vertices by their invariant multiplicity.
  366. This will allow us to search the more constrained vertices first.
  367. Since we will need to know the permutation from the original order to
  368. the new order, we do not sort the vertices directly. Instead we sort
  369. the vertex indices, creating the \code{perm} array. Once sorted, this
  370. array provides a mapping from the new index to the old index.
  371. We then use the \code{permute} function to sort the vertices of
  372. the graph, which we store in the \code{g1\_vertices} vector.
  373. @d Sort vertices by invariant multiplicity
  374. @{
  375. std::vector<size_type> perm;
  376. integer_range<size_type> range(0, num_vertices(g1));
  377. std::copy(range.begin(), range.end(), std::back_inserter(perm));
  378. std::sort(perm.begin(), perm.end(),
  379. detail::compare_invariant_multiplicity(invar1_vec.begin(),
  380. invar_mult.begin()));
  381. std::vector<vertex1_t> g1_vertices;
  382. for (tie(i1, i1_end) = vertices(g1); i1 != i1_end; ++i1)
  383. g1_vertices.push_back(*i1);
  384. permute(g1_vertices.begin(), g1_vertices.end(), perm.begin());
  385. @}
  386. \noindent The definition of the \code{compare\_multiplicity} predicate
  387. is shown below. This predicate provides the glue that binds
  388. \code{std::sort} to our current purpose.
  389. @d Compare multiplicity predicate
  390. @{
  391. namespace detail {
  392. template <typename InvarMap, typename MultMap>
  393. struct compare_invariant_multiplicity_predicate
  394. {
  395. compare_invariant_multiplicity_predicate(InvarMap i, MultMap m)
  396. : m_invar(i), m_mult(m) { }
  397. template <typename Vertex>
  398. bool operator()(const Vertex& x, const Vertex& y) const
  399. { return m_mult[m_invar[x]] < m_mult[m_invar[y]]; }
  400. InvarMap m_invar;
  401. MultMap m_mult;
  402. };
  403. template <typename InvarMap, typename MultMap>
  404. compare_invariant_multiplicity_predicate<InvarMap, MultMap>
  405. compare_invariant_multiplicity(InvarMap i, MultMap m) {
  406. return compare_invariant_multiplicity_predicate<InvarMap, MultMap>(i,m);
  407. }
  408. } // namespace detail
  409. @}
  410. \subsection{Ordering by DFS Discover Time}
  411. To implement the ``visit adjacent vertices first'' heuristic, we order
  412. the vertices according to DFS discover time. We replace the ordering
  413. in \code{perm} with the new DFS ordering. Again, we use \code{permute}
  414. to sort the vertices of graph \code{g1}.
  415. @d Order the vertices by DFS discover time
  416. @{
  417. {
  418. perm.clear();
  419. @<Compute DFS discover times@>
  420. g1_vertices.clear();
  421. for (tie(i1, i1_end) = vertices(g1); i1 != i1_end; ++i1)
  422. g1_vertices.push_back(*i1);
  423. permute(g1_vertices.begin(), g1_vertices.end(), perm.begin());
  424. }
  425. @}
  426. We implement the outer-loop of the DFS here, instead of calling the
  427. \code{depth\_first\_search} function, because we want the roots of the
  428. DFS tree's to be ordered by invariant multiplicity. We call
  429. \code{depth\_\-first\_\-visit} to implement the recursive portion of
  430. the DFS. The \code{record\_dfs\_order} adapts the DFS to record
  431. the order in which DFS discovers the vertices.
  432. @d Compute DFS discover times
  433. @{
  434. std::vector<default_color_type> color_vec(num_vertices(g1));
  435. for (typename std::vector<vertex1_t>::iterator ui = g1_vertices.begin();
  436. ui != g1_vertices.end(); ++ui) {
  437. if (color_vec[get(index_map1, *ui)]
  438. == color_traits<default_color_type>::white()) {
  439. depth_first_visit
  440. (g1, *ui, detail::record_dfs_order<Graph1, IndexMap1>(perm,
  441. index_map1),
  442. make_iterator_property_map(&color_vec[0], index_map1,
  443. color_vec[0]));
  444. }
  445. }
  446. @}
  447. \noindent The definition of the \code{record\_dfs\_order} visitor
  448. class is as follows. The index of each vertex is recorded in the
  449. \code{dfs\_order} vector (which is the \code{perm} vector) in the
  450. \code{discover\_vertex} event point.
  451. @d Record DFS ordering visitor
  452. @{
  453. namespace detail {
  454. template <typename Graph1, typename IndexMap1>
  455. struct record_dfs_order : public default_dfs_visitor {
  456. typedef typename graph_traits<Graph1>::vertices_size_type size_type;
  457. typedef typename graph_traits<Graph1>::vertex_descriptor vertex;
  458. record_dfs_order(std::vector<size_type>& dfs_order, IndexMap1 index)
  459. : dfs_order(dfs_order), index(index) { }
  460. void discover_vertex(vertex v, const Graph1& g) const {
  461. dfs_order.push_back(get(index, v));
  462. }
  463. std::vector<size_type>& dfs_order;
  464. IndexMap1 index;
  465. };
  466. } // namespace detail
  467. @}
  468. In the MATCH operation, we need to examine all the edges in the set
  469. $E_1[k] - E_1[k-1]$. That is, we need to loop through all the edges of
  470. the form $(k,j)$ or $(j,k)$ where $j \leq k$. To do this efficiently,
  471. we create an array of all the edges in $G_1$ that has been sorted so
  472. that $E_1[k] - E_1[k-1]$ forms a contiguous range. To each edge
  473. $e=(u,v)$ we assign the number $\max(u,v)$, and then sort the edges by
  474. this number. All the edges $(u,v) \in E_1[k] - E_1[k-1]$ can then be
  475. identified because $\max(u,v) = k$. The following code creates an
  476. array of edges and then sorts them. The \code{edge\_\-ordering\_\-fun}
  477. function object is described next.
  478. @d Order the edges by DFS discover time
  479. @{
  480. typedef typename graph_traits<Graph1>::edge_descriptor edge1_t;
  481. std::vector<edge1_t> edge_set;
  482. std::copy(edges(g1).first, edges(g1).second, std::back_inserter(edge_set));
  483. std::sort(edge_set.begin(), edge_set.end(),
  484. detail::edge_ordering
  485. (make_iterator_property_map(perm.begin(), index_map1, perm[0]), g1));
  486. @}
  487. \noindent The \code{edge\_order} function computes the ordering number
  488. for an edge, which for edge $e=(u,v)$ is $\max(u,v)$. The
  489. \code{edge\_\-ordering\_\-fun} function object simply returns
  490. comparison of two edge's ordering numbers.
  491. @d Isomorph edge ordering predicate
  492. @{
  493. namespace detail {
  494. template <typename VertexIndexMap, typename Graph>
  495. std::size_t edge_order(const typename graph_traits<Graph>::edge_descriptor e,
  496. VertexIndexMap index_map, const Graph& g) {
  497. return std::max(get(index_map, source(e, g)), get(index_map, target(e, g)));
  498. }
  499. template <typename VertexIndexMap, typename Graph>
  500. class edge_ordering_fun {
  501. public:
  502. edge_ordering_fun(VertexIndexMap vip, const Graph& g)
  503. : m_index_map(vip), m_g(g) { }
  504. template <typename Edge>
  505. bool operator()(const Edge& e1, const Edge& e2) const {
  506. return edge_order(e1, m_index_map, m_g) < edge_order(e2, m_index_map, m_g);
  507. }
  508. VertexIndexMap m_index_map;
  509. const Graph& m_g;
  510. };
  511. template <class VertexIndexMap, class G>
  512. inline edge_ordering_fun<VertexIndexMap,G>
  513. edge_ordering(VertexIndexMap vip, const G& g)
  514. {
  515. return edge_ordering_fun<VertexIndexMap,G>(vip, g);
  516. }
  517. } // namespace detail
  518. @}
  519. We are now ready to enter the main part of the algorithm, the
  520. backtracking search implemented by the \code{isomorph} function (which
  521. corresponds to the ISOMORPH algorithm). The set $S$ is not
  522. represented directly; instead we represent $V_2 - S$. Initially $S =
  523. \emptyset$ so $V_2 - S = V_2$. We use the permuted indices for the
  524. vertices of graph \code{g1}. We represent $V_2 - S$ with a bitset. We
  525. use \code{std::vector} instead of \code{boost::dyn\_bitset} for speed
  526. instead of space.
  527. @d Invoke recursive \code{isomorph} function
  528. @{
  529. std::vector<char> not_in_S_vec(num_vertices(g2), true);
  530. iterator_property_map<char*, IndexMap2, char, char&>
  531. not_in_S(&not_in_S_vec[0], index_map2);
  532. return detail::isomorph(g1_vertices.begin(), g1_vertices.end(),
  533. edge_set.begin(), edge_set.end(), g1, g2,
  534. make_iterator_property_map(perm.begin(), index_map1, perm[0]),
  535. index_map2, f, invar1, invar2, not_in_S);
  536. @}
  537. \subsection{Implementation of ISOMORPH}
  538. The ISOMORPH algorithm is implemented with the \code{isomorph}
  539. function. The vertices of $G_1$ are searched in the order specified by
  540. the iterator range \code{[k\_iter,last)}. The function returns true if
  541. a isomorphism is found between the vertices of $G_1$ in
  542. \code{[k\_iter,last)} and the vertices of $G_2$ in \code{not\_in\_S}.
  543. The mapping is recorded in the parameter \code{f}.
  544. @d Signature for the recursive isomorph function
  545. @{
  546. template <class VertexIter, class EdgeIter, class Graph1, class Graph2,
  547. class IndexMap1, class IndexMap2, class IndexMapping,
  548. class Invar1, class Invar2, class Set>
  549. bool isomorph(VertexIter k_iter, VertexIter last,
  550. EdgeIter edge_iter, EdgeIter edge_iter_end,
  551. const Graph1& g1, const Graph2& g2,
  552. IndexMap1 index_map1,
  553. IndexMap2 index_map2,
  554. IndexMapping f, Invar1 invar1, Invar2 invar2,
  555. const Set& not_in_S)
  556. @}
  557. \noindent The steps for this function are as follows.
  558. @d Body of the isomorph function
  559. @{
  560. {
  561. @<Some typedefs and variable declarations@>
  562. @<Return true if matching is complete@>
  563. @<Create a copy of $f_{k-1}$ which will become $f_k$@>
  564. @<Compute $M$, the potential matches for $k$@>
  565. @<Invoke isomorph for each vertex in $M$@>
  566. }
  567. @}
  568. \noindent Here we create short names for some often-used types
  569. and declare some variables.
  570. @d Some typedefs and variable declarations
  571. @{
  572. typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_t;
  573. typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
  574. typedef typename graph_traits<Graph1>::vertices_size_type size_type;
  575. vertex1_t k = *k_iter;
  576. @}
  577. \noindent We have completed creating an isomorphism if \code{k\_iter == last}.
  578. @d Return true if matching is complete
  579. @{
  580. if (k_iter == last)
  581. return true;
  582. @}
  583. In the pseudo-code for ISOMORPH, we iterate through each vertex in $v
  584. \in V_2 - S$ and check if $k$ and $v$ can match. A more efficient
  585. approach is to directly iterate through the potential matches for $k$,
  586. for this often is many fewer vertices than $V_2 - S$. Let $M$ be the
  587. set of potential matches for $k$. $M$ consists of all the vertices $v
  588. \in V_2 - S$ such that if $(k,j)$ or $(j,k) \in E_1[k] - E_1[k-1]$
  589. then $(v,f(j)$ or $(f(j),v) \in E_2$ with $i(v) = i(k)$. Note that
  590. this means if there are no edges in $E_1[k] - E_1[k-1]$ then $M = V_2
  591. - S$. In the case where there are edges in $E_1[k] - E_1[k-1]$ we
  592. break the computation of $M$ into two parts, computing $out$ sets
  593. which are vertices that can match according to an out-edge of $k$, and
  594. computing $in$ sets which are vertices that can match according to an
  595. in-edge of $k$.
  596. The implementation consists of a loop through the edges of $E_1[k] -
  597. E_1[k-1]$. The straightforward implementation would initialize $M
  598. \leftarrow V_2 - S$, and then intersect $M$ with the $out$ or $in$ set
  599. for each edge. However, to reduce the cost of the intersection
  600. operation, we start with $M \leftarrow \emptyset$, and on the first
  601. iteration of the loop we do $M \leftarrow out$ or $M \leftarrow in$
  602. instead of an intersection operation.
  603. @d Compute $M$, the potential matches for $k$
  604. @{
  605. std::vector<vertex2_t> potential_matches;
  606. bool some_edges = false;
  607. for (; edge_iter != edge_iter_end; ++edge_iter) {
  608. if (get(index_map1, k) != edge_order(*edge_iter, index_map1, g1))
  609. break;
  610. if (k == source(*edge_iter, g1)) { // (k,j)
  611. @<Compute the $out$ set@>
  612. if (some_edges == false) {
  613. @<Perform $M \leftarrow out$@>
  614. } else {
  615. @<Perform $M \leftarrow M \intersect out$@>
  616. }
  617. some_edges = true;
  618. } else { // (j,k)
  619. @<Compute the $in$ set@>
  620. if (some_edges == false) {
  621. @<Perform $M \leftarrow in$@>
  622. } else {
  623. @<Perform $M \leftarrow M \intersect in$@>
  624. }
  625. some_edges = true;
  626. }
  627. if (potential_matches.empty())
  628. break;
  629. } // for edge_iter
  630. if (some_edges == false) {
  631. @<Perform $M \leftarrow V_2 - S$@>
  632. }
  633. @}
  634. To compute the $out$ set, we iterate through the out-edges $(k,j)$ of
  635. $k$, and for each $j$ we iterate through the in-edges $(v,f(j))$ of
  636. $f(j)$, putting all of the $v$'s in $out$ that have the same vertex
  637. invariant as $k$, and which are in $V_2 - S$. Figure~\ref{fig:out}
  638. depicts the computation of the $out$ set. The implementation is as
  639. follows.
  640. @d Compute the $out$ set
  641. @{
  642. vertex1_t j = target(*edge_iter, g1);
  643. std::vector<vertex2_t> out;
  644. typename graph_traits<Graph2>::in_edge_iterator ei, ei_end;
  645. for (tie(ei, ei_end) = in_edges(get(f, j), g2); ei != ei_end; ++ei) {
  646. vertex2_t v = source(*ei, g2); // (v,f[j])
  647. if (invar1[k] == invar2[v] && not_in_S[v])
  648. out.push_back(v);
  649. }
  650. @}
  651. \noindent Here initialize $M$ with the $out$ set. Since we are
  652. representing sets with sorted vectors, we sort \code{out} before
  653. copying to \code{potential\_matches}.
  654. @d Perform $M \leftarrow out$
  655. @{
  656. indirect_cmp<IndexMap2,std::less<std::size_t> > cmp(index_map2);
  657. std::sort(out.begin(), out.end(), cmp);
  658. std::copy(out.begin(), out.end(), std::back_inserter(potential_matches));
  659. @}
  660. \noindent We use \code{std::set\_intersection} to implement $M
  661. \leftarrow M \intersect out$. Since there is no version of
  662. \code{std::set\_intersection} that works in-place, we create a
  663. temporary for the result and then swap.
  664. @d Perform $M \leftarrow M \intersect out$
  665. @{
  666. indirect_cmp<IndexMap2,std::less<std::size_t> > cmp(index_map2);
  667. std::sort(out.begin(), out.end(), cmp);
  668. std::vector<vertex2_t> tmp_matches;
  669. std::set_intersection(out.begin(), out.end(),
  670. potential_matches.begin(), potential_matches.end(),
  671. std::back_inserter(tmp_matches), cmp);
  672. std::swap(potential_matches, tmp_matches);
  673. @}
  674. % Shoot, there is some problem with f(j). Could have to do with the
  675. % change from the edge set to just using out_edges and in_edges.
  676. % Yes, have to visit edges in correct order to we don't hit
  677. % part of f that is not yet defined.
  678. \vizfig{out}{Computing the $out$ set.}
  679. @c out.dot
  680. @{
  681. digraph G {
  682. node[shape=circle]
  683. size="4,2"
  684. ratio="fill"
  685. subgraph cluster0 { label="G_1"
  686. k -> j_1
  687. k -> j_2
  688. k -> j_3
  689. }
  690. subgraph cluster1 { label="G_2"
  691. subgraph cluster2 { label="out" v_1 v_2 v_3 v_4 v_5 v_6 }
  692. v_1 -> fj_1
  693. v_2 -> fj_1
  694. v_3 -> fj_1
  695. v_4 -> fj_2
  696. v_5 -> fj_3
  697. v_6 -> fj_3
  698. fj_1[label="f(j_1)"]
  699. fj_2[label="f(j_2)"]
  700. fj_3[label="f(j_3)"]
  701. }
  702. j_1 -> fj_1[style=dotted]
  703. j_2 -> fj_2[style=dotted]
  704. j_3 -> fj_3[style=dotted]
  705. }
  706. @}
  707. The $in$ set is is constructed by iterating through the in-edges
  708. $(j,k)$ of $k$, and for each $j$ we iterate through the out-edges
  709. $(f(j),v)$ of $f(j)$. We put all of the $v$'s in $in$ that have the
  710. same vertex invariant as $k$, and which are in $V_2 -
  711. S$. Figure~\ref{fig:in} depicts the computation of the $in$ set. The
  712. following code computes the $in$ set.
  713. @d Compute the $in$ set
  714. @{
  715. vertex1_t j = source(*edge_iter, g1);
  716. std::vector<vertex2_t> in;
  717. typename graph_traits<Graph2>::out_edge_iterator ei, ei_end;
  718. for (tie(ei, ei_end) = out_edges(get(f, j), g2); ei != ei_end; ++ei) {
  719. vertex2_t v = target(*ei, g2); // (f[j],v)
  720. if (invar1[k] == invar2[v] && not_in_S[v])
  721. in.push_back(v);
  722. }
  723. @}
  724. \noindent Here initialize $M$ with the $in$ set. Since we are
  725. representing sets with sorted vectors, we sort \code{in} before
  726. copying to \code{potential\_matches}.
  727. @d Perform $M \leftarrow in$
  728. @{
  729. indirect_cmp<IndexMap2,std::less<std::size_t> > cmp(index_map2);
  730. std::sort(in.begin(), in.end(), cmp);
  731. std::copy(in.begin(), in.end(), std::back_inserter(potential_matches));
  732. @}
  733. \noindent Again we use \code{std::set\_intersection} on
  734. sorted vectors to implement $M \leftarrow M \intersect in$.
  735. @d Perform $M \leftarrow M \intersect in$
  736. @{
  737. indirect_cmp<IndexMap2, std::less<std::size_t> > cmp(index_map2);
  738. std::sort(in.begin(), in.end(), cmp);
  739. std::vector<vertex2_t> tmp_matches;
  740. std::set_intersection(in.begin(), in.end(),
  741. potential_matches.begin(), potential_matches.end(),
  742. std::back_inserter(tmp_matches), cmp);
  743. std::swap(potential_matches, tmp_matches);
  744. @}
  745. \vizfig{in}{Computing the $in$ set.}
  746. @c in.dot
  747. @{
  748. digraph G {
  749. node[shape=circle]
  750. size="3,2"
  751. ratio="fill"
  752. subgraph cluster0 { label="G1"
  753. j_1 -> k
  754. j_2 -> k
  755. }
  756. subgraph cluster1 { label="G2"
  757. subgraph cluster2 { label="in" v_1 v_2 v_3 }
  758. v_1 -> fj_1
  759. v_2 -> fj_1
  760. v_3 -> fj_2
  761. fj_1[label="f(j_1)"]
  762. fj_2[label="f(j_2)"]
  763. }
  764. j_1 -> fj_1[style=dotted]
  765. j_2 -> fj_2[style=dotted]
  766. }
  767. @}
  768. In the case where there were no edges in $E_1[k] - E_1[k-1]$, then $M
  769. = V_2 - S$, so here we insert all the vertices from $V_2$ that are not
  770. in $S$.
  771. @d Perform $M \leftarrow V_2 - S$
  772. @{
  773. typename graph_traits<Graph2>::vertex_iterator vi, vi_end;
  774. for (tie(vi, vi_end) = vertices(g2); vi != vi_end; ++vi)
  775. if (not_in_S[*vi])
  776. potential_matches.push_back(*vi);
  777. @}
  778. For each vertex $v$ in the potential matches $M$, we will create an
  779. extended isomorphism $f_k = f_{k-1} \union \pair{k}{v}$. First
  780. we create a local copy of $f_{k-1}$.
  781. @d Create a copy of $f_{k-1}$ which will become $f_k$
  782. @{
  783. std::vector<vertex2_t> my_f_vec(num_vertices(g1));
  784. typedef typename std::vector<vertex2_t>::iterator vec_iter;
  785. iterator_property_map<vec_iter, IndexMap1, vertex2_t, vertex2_t&>
  786. my_f(my_f_vec.begin(), index_map1);
  787. typename graph_traits<Graph1>::vertex_iterator i1, i1_end;
  788. for (tie(i1, i1_end) = vertices(g1); i1 != i1_end; ++i1)
  789. my_f[*i1] = get(f, *i1);
  790. @}
  791. Next we enter the loop through every vertex $v$ in $M$, and extend the
  792. isomorphism with $\pair{k}{v}$. We then update the set $S$ (by
  793. removing $v$ from $V_2 - S$) and make the recursive call to
  794. \code{isomorph}. If \code{isomorph} returns successfully, we have
  795. found an isomorphism for the complete graph, so we copy our local
  796. mapping into the mapping from the previous calling function.
  797. @d Invoke isomorph for each vertex in $M$
  798. @{
  799. for (std::size_t j = 0; j < potential_matches.size(); ++j) {
  800. my_f[k] = potential_matches[j];
  801. @<Perform $S' = S - \{ v \}$@>
  802. if (isomorph(boost::next(k_iter), last, edge_iter, edge_iter_end, g1, g2,
  803. index_map1, index_map2,
  804. my_f, invar1, invar2, my_not_in_S)) {
  805. for (tie(i1, i1_end) = vertices(g1); i1 != i1_end; ++i1)
  806. put(f, *i1, my_f[*i1]);
  807. return true;
  808. }
  809. }
  810. return false;
  811. @}
  812. We need to create the new set $S' = S - \{ v \}$, which will be the
  813. $S$ for the next invocation to \code{isomorph}. As before, we
  814. represent $V_2 - S'$ instead of $S'$ and use a bitset.
  815. @d Perform $S' = S - \{ v \}$
  816. @{
  817. std::vector<char> my_not_in_S_vec(num_vertices(g2));
  818. iterator_property_map<char*, IndexMap2, char, char&>
  819. my_not_in_S(&my_not_in_S_vec[0], index_map2);
  820. typename graph_traits<Graph2>::vertex_iterator vi, vi_end;
  821. for (tie(vi, vi_end) = vertices(g2); vi != vi_end; ++vi)
  822. my_not_in_S[*vi] = not_in_S[*vi];;
  823. my_not_in_S[potential_matches[j]] = false;
  824. @}
  825. \section{Appendix}
  826. Here we output the header file \code{isomorphism.hpp}. We add a
  827. copyright statement, include some files, and then pull the top-level
  828. code parts into namespace \code{boost}.
  829. @o isomorphism.hpp -d
  830. @{
  831. // (C) Copyright Jeremy Siek 2001. Permission to copy, use, modify,
  832. // sell and distribute this software is granted provided this
  833. // copyright notice appears in all copies. This software is provided
  834. // "as is" without express or implied warranty, and with no claim as
  835. // to its suitability for any purpose.
  836. // See http://www.boost.org/libs/graph/doc/isomorphism-impl.pdf
  837. // for a description of the implementation of the isomorphism function
  838. // defined in this header file.
  839. #ifndef BOOST_GRAPH_ISOMORPHISM_HPP
  840. #define BOOST_GRAPH_ISOMORPHISM_HPP
  841. #include <algorithm>
  842. #include <boost/graph/detail/set_adaptor.hpp>
  843. #include <boost/pending/indirect_cmp.hpp>
  844. #include <boost/graph/detail/permutation.hpp>
  845. #include <boost/graph/named_function_params.hpp>
  846. #include <boost/graph/graph_concepts.hpp>
  847. #include <boost/property_map/property_map.hpp>
  848. #include <boost/pending/integer_range.hpp>
  849. #include <boost/limits.hpp>
  850. #include <boost/static_assert.hpp>
  851. #include <boost/graph/depth_first_search.hpp>
  852. namespace boost {
  853. @<Degree vertex invariant@>
  854. namespace detail {
  855. @<Signature for the recursive isomorph function@>
  856. @<Body of the isomorph function@>
  857. } // namespace detail
  858. @<Record DFS ordering visitor@>
  859. @<Compare multiplicity predicate@>
  860. @<Isomorph edge ordering predicate@>
  861. @<Isomorphism Function Interface@>
  862. @<Isomorphism Function Body@>
  863. namespace detail {
  864. // Should move this, make is public
  865. template <typename Graph, typename InDegreeMap, typename Cat>
  866. void compute_in_degree(const Graph& g, const InDegreeMap& in_degree_map,
  867. Cat)
  868. {
  869. typename graph_traits<Graph>::vertex_iterator vi, vi_end;
  870. typename graph_traits<Graph>::out_edge_iterator ei, ei_end;
  871. for (tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
  872. for (tie(ei, ei_end) = out_edges(*vi, g); ei != ei_end; ++ei) {
  873. typename graph_traits<Graph>::vertex_descriptor v = target(*ei, g);
  874. put(in_degree_map, v, get(in_degree_map, v) + 1);
  875. }
  876. }
  877. template <typename Graph, typename InDegreeMap>
  878. void compute_in_degree(const Graph& g, const InDegreeMap& in_degree_map,
  879. edge_list_graph_tag)
  880. {
  881. typename graph_traits<Graph>::edge_iterator ei, ei_end;
  882. for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {
  883. typename graph_traits<Graph>::vertex_descriptor v = target(*ei, g);
  884. put(in_degree_map, v, get(in_degree_map, v) + 1);
  885. }
  886. }
  887. template <typename Graph, typename InDegreeMap>
  888. void compute_in_degree(const Graph& g, const InDegreeMap& in_degree_map)
  889. {
  890. typename graph_traits<Graph>::traversal_category cat;
  891. compute_in_degree(g, in_degree_map, cat);
  892. }
  893. template <typename Graph1, typename Graph2,
  894. typename IndexMapping, typename IndexMap1, typename IndexMap2,
  895. typename P, typename T, typename R>
  896. bool isomorphism_impl(const Graph1& g1, const Graph2& g2,
  897. IndexMapping f,
  898. IndexMap1 index_map1, IndexMap2 index_map2,
  899. const bgl_named_params<P,T,R>& params)
  900. {
  901. typedef typename graph_traits<Graph1>::vertices_size_type size_type;
  902. // Compute the in-degrees
  903. std::vector<size_type> in_degree_vec1(num_vertices(g1), 0);
  904. typedef iterator_property_map<size_type*, IndexMap1,
  905. size_type, size_type&> InDegreeMap1;
  906. InDegreeMap1 in_degree_map1(&in_degree_vec1[0], index_map1);
  907. detail::compute_in_degree(g1, in_degree_map1);
  908. degree_vertex_invariant<InDegreeMap1, Graph1>
  909. default_invar1(in_degree_map1, g1);
  910. std::vector<size_type> in_degree_vec2(num_vertices(g2), 0);
  911. typedef iterator_property_map<size_type*, IndexMap2,
  912. size_type, size_type&> InDegreeMap2;
  913. InDegreeMap2 in_degree_map2(&in_degree_vec2[0], index_map2);
  914. detail::compute_in_degree(g2, in_degree_map2);
  915. degree_vertex_invariant<InDegreeMap2, Graph2>
  916. default_invar2(in_degree_map2, g2);
  917. return isomorphism(g1, g2, f,
  918. choose_param(get_param(params, vertex_invariant_t()), default_invar1),
  919. choose_param(get_param(params, vertex_invariant_t()), default_invar2),
  920. index_map1, index_map2);
  921. }
  922. } // namespace detail
  923. // Named parameter interface
  924. template <typename Graph1, typename Graph2, class P, class T, class R>
  925. bool isomorphism(const Graph1& g1,
  926. const Graph2& g2,
  927. const bgl_named_params<P,T,R>& params)
  928. {
  929. typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
  930. typename std::vector<vertex2_t>::size_type
  931. n = is_default_param(get_param(params, vertex_isomorphism_t()))
  932. ? num_vertices(g1) : 1;
  933. std::vector<vertex2_t> f(n);
  934. vertex2_t x;
  935. return detail::isomorphism_impl
  936. (g1, g2,
  937. choose_param(get_param(params, vertex_isomorphism_t()),
  938. make_iterator_property_map(f.begin(),
  939. choose_const_pmap(get_param(params, vertex_index1),
  940. g1, vertex_index), x)),
  941. choose_const_pmap(get_param(params, vertex_index1),
  942. g1, vertex_index),
  943. choose_const_pmap(get_param(params, vertex_index2),
  944. g2, vertex_index),
  945. params);
  946. }
  947. // All defaults interface
  948. template <typename Graph1, typename Graph2>
  949. bool isomorphism(const Graph1& g1, const Graph2& g2)
  950. {
  951. typedef typename graph_traits<Graph1>::vertices_size_type size_type;
  952. typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_t;
  953. std::vector<vertex2_t> f(num_vertices(g1));
  954. // Compute the in-degrees
  955. std::vector<size_type> in_degree_vec1(num_vertices(g1), 0);
  956. typedef typename property_map<Graph1,vertex_index_t>::const_type IndexMap1;
  957. typedef iterator_property_map<size_type*, IndexMap1,
  958. size_type, size_type&> InDegreeMap1;
  959. InDegreeMap1 in_degree_map1(&in_degree_vec1[0], get(vertex_index, g1));
  960. detail::compute_in_degree(g1, in_degree_map1);
  961. degree_vertex_invariant<InDegreeMap1, Graph1>
  962. invariant1(in_degree_map, g1);
  963. std::vector<size_type> in_degree_vec2(num_vertices(g2), 0);
  964. typedef typename property_map<Graph2,vertex_index_t>::const_type IndexMap2;
  965. typedef iterator_property_map<size_type*, IndexMap2,
  966. size_type, size_type&> InDegreeMap2;
  967. InDegreeMap2 in_degree_map2(&in_degree_vec2[0], get(vertex_index, g2));
  968. detail::compute_in_degree(g2, in_degree_map2);
  969. degree_vertex_invariant<InDegreeMap2, Graph2>
  970. invariant2(in_degree_map, g2);
  971. return isomorphism
  972. (g1, g2, make_iterator_property_map(f.begin(), get(vertex_index, g1), vertex2_t()),
  973. invariant1, invariant2, get(vertex_index, g1), get(vertex_index, g2));
  974. }
  975. // Verify that the given mapping iso_map from the vertices of g1 to the
  976. // vertices of g2 describes an isomorphism.
  977. // Note: this could be made much faster by specializing based on the graph
  978. // concepts modeled, but since we're verifying an O(n^(lg n)) algorithm,
  979. // O(n^4) won't hurt us.
  980. template<typename Graph1, typename Graph2, typename IsoMap>
  981. inline bool verify_isomorphism(const Graph1& g1, const Graph2& g2,
  982. IsoMap iso_map)
  983. {
  984. if (num_vertices(g1) != num_vertices(g2) || num_edges(g1) != num_edges(g2))
  985. return false;
  986. for (typename graph_traits<Graph1>::edge_iterator e1 = edges(g1).first;
  987. e1 != edges(g1).second; ++e1) {
  988. bool found_edge = false;
  989. for (typename graph_traits<Graph2>::edge_iterator e2 = edges(g2).first;
  990. e2 != edges(g2).second && !found_edge; ++e2) {
  991. if (source(*e2, g2) == get(iso_map, source(*e1, g1)) &&
  992. target(*e2, g2) == get(iso_map, target(*e1, g1))) {
  993. found_edge = true;
  994. }
  995. }
  996. if (!found_edge)
  997. return false;
  998. }
  999. return true;
  1000. }
  1001. } // namespace boost
  1002. #endif // BOOST_GRAPH_ISOMORPHISM_HPP
  1003. @}
  1004. \bibliographystyle{abbrv}
  1005. \bibliography{ggcl}
  1006. \end{document}
  1007. % LocalWords: Isomorphism Siek isomorphism adjacency subgraph subgraphs OM DFS
  1008. % LocalWords: ISOMORPH Invariants invariants typename IndexMapping bool const
  1009. % LocalWords: VertexInvariant VertexIndexMap iterator typedef VertexG Idx num
  1010. % LocalWords: InvarValue struct invar vec iter tmp_matches mult inserter permute ui
  1011. % LocalWords: dfs cmp isomorph VertexIter EdgeIter IndexMap desc RPH ATCH pre
  1012. % LocalWords: iterators VertexListGraph EdgeListGraph BidirectionalGraph tmp
  1013. % LocalWords: ReadWritePropertyMap VertexListGraphConcept EdgeListGraphConcept
  1014. % LocalWords: BidirectionalGraphConcept ReadWritePropertyMapConcept indices ei
  1015. % LocalWords: IndexMappingValue ReadablePropertyMapConcept namespace InvarMap
  1016. % LocalWords: MultMap vip inline bitset typedefs fj hpp ifndef adaptor params
  1017. % LocalWords: bgl param pmap endif