patternMatching.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. # coding: utf-8
  2. """
  3. Author: Sten Vercamman
  4. Univeristy of Antwerp
  5. Example code for paper: Efficient model transformations for novices
  6. url: http://msdl.cs.mcgill.ca/people/hv/teaching/MSBDesign/projects/Sten.Vercammen
  7. The main goal of this code is to give an overview, and an understandable
  8. implementation, of known techniques for pattern matching and solving the
  9. sub-graph homomorphism problem. The presented techniques do not include
  10. performance adaptations/optimizations. It is not optimized to be efficient
  11. but rather for the ease of understanding the workings of the algorithms.
  12. The paper does list some possible extensions/optimizations.
  13. It is intended as a guideline, even for novices, and provides an in-depth look
  14. at the workings behind various techniques for efficient pattern matching.
  15. """
  16. from planGraph import *
  17. import collections
  18. import itertools
  19. # import numpy as np
  20. class PatternMatching(object):
  21. """
  22. Returns an occurrence of a given pattern from the given Graph
  23. """
  24. def __init__(self, matching_type='SP', optimize=True):
  25. # store the type of matching we want to use
  26. self.type = matching_type
  27. self.bound_vertices = {} # saves the currently bound vertices
  28. self.bound_edges = {} # saves the currently bound edges
  29. self.result = None
  30. self.previous = []
  31. self.optimize = optimize
  32. self.results = []
  33. def match(self, pattern, graph):
  34. """
  35. Call this function to find an occurrence of the pattern in the (host) graph.
  36. Setting the type of matching (naive, SP, Ullmann, VF2) is done by
  37. setting self.matching_type to its name.
  38. """
  39. if not (isinstance(pattern, SearchGraph) or isinstance(pattern, Graph)):
  40. raise TypeError('pattern must be a SearchGraph or Graph')
  41. if not (isinstance(graph, SearchGraph) or isinstance(graph, Graph)):
  42. raise TypeError('graph must be a SearchGraph or Graph')
  43. self.pattern = pattern
  44. self.graph = graph
  45. if self.type == 'naive':
  46. result = self.matchNaive(vertices=graph.vertices, edges=graph.edges)
  47. elif self.type == 'SP':
  48. result = self.matchSP()
  49. elif self.type == 'Ullmann':
  50. result = self.matchUllmann()
  51. elif self.type == 'VF2':
  52. result = self.matchVF2()
  53. else:
  54. raise ValueError('Unknown type for matching')
  55. # cleanup
  56. self.pattern = None
  57. self.graph = None
  58. self.bound_vertices = {}
  59. self.bound_edges = {}
  60. self.result = None
  61. self.results = []
  62. return result
  63. def matchNaive(self, pattern_vertices=None, vertices=None, edges=None):
  64. """
  65. Try to find an occurrence of the pattern in the Graph naively.
  66. """
  67. # allow call with specific arguments
  68. if pattern_vertices == None:
  69. pattern_vertices = self.pattern.vertices
  70. if vertices == None:
  71. vertices = self.bound_vertices
  72. if edges == None:
  73. edges = self.bound_edges
  74. def visitEdge(pattern_vertices, p_edge, inc, g_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  75. """
  76. Visit a pattern edge, and try to bind it to a graph edge.
  77. (If the first fails, try the second, and so on...)
  78. """
  79. for g_edge in g_edges:
  80. # only reckon the edge if its in edges and not visited
  81. # (as the graph might be a subgraph of a more complex graph)
  82. if g_edge not in edges.get(g_edge.type, []) or g_edge in visited_g_edges:
  83. continue
  84. if g_edge.type == p_edge.type and g_edge not in visited_g_edges:
  85. visited_p_edges[p_edge] = g_edge
  86. visited_g_edges.add(g_edge)
  87. if inc:
  88. p_vertex = p_edge.src
  89. else:
  90. p_vertex = p_edge.tgt
  91. if visitVertices(pattern_vertices, p_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  92. return True
  93. # remove added edges if they lead to no match, retry with others
  94. del visited_p_edges[p_edge]
  95. visited_g_edges.remove(g_edge)
  96. # no edge leads to a possitive match
  97. return False
  98. def visitEdges(pattern_vertices, p_edges, inc, g_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  99. """
  100. Visit all edges of the pattern vertex (edges given as argument).
  101. We need to try visiting them for all its permutations, as matching
  102. v -e1-> first and v -e2-> second and v -e3-> third, might not result
  103. in a matching an occurrence of the pattern, but matching v -e2->
  104. first and v -e3-> second and v -e1-> third might.
  105. """
  106. def removePrevEdge(visitedEdges, visited_p_edges, visited_g_edges):
  107. """
  108. Undo the binding of the brevious edge, (the current bindinds do
  109. not lead to an occurrence of the pattern in the graph).
  110. """
  111. for wrong_edge in visitedEdges:
  112. # remove binding (pattern edge to graph edge)
  113. wrong_g_edge = visited_p_edges.get(wrong_edge)
  114. del visited_p_edges[wrong_edge]
  115. # remove visited graph edge
  116. visited_g_edges.remove(wrong_g_edge)
  117. for it in itertools.permutations(p_edges):
  118. visitedEdges = []
  119. foundallEdges = True
  120. for edge in it:
  121. if visited_p_edges.get(edge) == None:
  122. if not visitEdge(pattern_vertices, edge, inc, g_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  123. # this did not work, so we have to undo all added edges
  124. # (the current edge is not added, as it failed)
  125. # we then can try a different permutation
  126. removePrevEdge(visitedEdges, visited_p_edges, visited_g_edges)
  127. foundallEdges = False
  128. break # try other order
  129. # add good visited (we know it succeeded)
  130. visitedEdges.append(edge)
  131. else:
  132. # we visited this pattern edge, and have the coressponding graph edge
  133. # if it is an incoming pattern edge, we need to make sure that
  134. # the graph target that is map from the pattern target
  135. # (of this incoming pattern edge, which has to be bound at this point)
  136. # has the graph adge as an incoming edge,
  137. # otherwise the graph is not properly connected
  138. if inc:
  139. if not visited_p_edges[edge] in visited_p_vertices[edge.tgt].incoming_edges:
  140. # did not work
  141. removePrevEdge(visitedEdges, visited_p_edges, visited_g_edges)
  142. foundallEdges = False
  143. break # try other order
  144. else:
  145. # analog for an outgoing edge
  146. if not visited_p_edges[edge] in visited_p_vertices[edge.src].outgoing_edges:
  147. # did not work
  148. removePrevEdge(visitedEdges, visited_p_edges, visited_g_edges)
  149. foundallEdges = False
  150. break # try other order
  151. # all edges are good, look no further
  152. if foundallEdges:
  153. break
  154. return foundallEdges
  155. def visitVertex(pattern_vertices, p_vertex, g_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  156. """
  157. Visit a pattern vertex, and try to bind it to the graph vertex
  158. (both are given as argument). A binding is successful if all the
  159. pattern vertex his incoming and outgoing edges can be bound
  160. (to the graph vertex).
  161. """
  162. if g_vertex in visited_g_vertices:
  163. return False
  164. # save visited graph vertex
  165. visited_g_vertices.add(g_vertex)
  166. # map pattern vertex to visited graph vertex
  167. visited_p_vertices[p_vertex] = g_vertex
  168. if visitEdges(pattern_vertices, p_vertex.incoming_edges, True, g_vertex.incoming_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  169. if visitEdges(pattern_vertices, p_vertex.outgoing_edges, False, g_vertex.outgoing_edges, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  170. return True
  171. # cleanup, remove from visited as this does not lead to
  172. # an occurrence of the pttern in the graph
  173. visited_g_vertices.remove(g_vertex)
  174. del visited_p_vertices[p_vertex]
  175. return False
  176. def visitVertices(pattern_vertices, p_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  177. """
  178. Visit a pattern vertex and try to bind a graph vertex to it.
  179. """
  180. # if already matched or if it is a vertex not in the pattern_vertices
  181. # (second is for when you want to match the pattern partionally)
  182. if visited_p_vertices.get(p_vertex) != None or p_vertex not in pattern_vertices.get(p_vertex.type, set()):
  183. return True
  184. # try visiting graph vertices of same type as pattern vertex
  185. for g_vertex in vertices.get(p_vertex.type, []):
  186. if g_vertex not in visited_g_vertices:
  187. if visitVertex(pattern_vertices, p_vertex, g_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  188. return True
  189. return False
  190. visited_p_vertices = {}
  191. visited_p_edges = {}
  192. visited_g_vertices = set()
  193. visited_g_edges = set()
  194. # for loop is need for when pattern consists of multiple not connected structures
  195. allVertices = []
  196. for _, p_vertices in pattern_vertices.items():
  197. allVertices.extend(p_vertices)
  198. foundIt = False
  199. for it_p_vertices in itertools.permutations(allVertices):
  200. foundIt = True
  201. for p_vertex in it_p_vertices:
  202. if not visitVertices(pattern_vertices, p_vertex, visited_p_vertices, visited_p_edges, visited_g_vertices, visited_g_edges, vertices, edges):
  203. foundIt = False
  204. # reset visited
  205. visited_p_vertices = {}
  206. visited_p_edges = {}
  207. visited_g_vertices = set()
  208. visited_g_edges = set()
  209. break
  210. if foundIt:
  211. break
  212. if foundIt:
  213. return (visited_p_vertices, visited_p_edges)
  214. else:
  215. return None
  216. def matchSP(self):
  217. """
  218. Find an occurrence of the pattern in the Graph
  219. by using the generated SearchPlan.
  220. """
  221. if isinstance(self.graph, Graph):
  222. sg = SearchGraph(self.graph)
  223. elif isinstance(self.graph, SearchGraph):
  224. sg = self.graph
  225. else:
  226. raise TypeError('Pattern matching with a SearchPlan must be given a Graph or SearchGraph')
  227. pg = PlanGraph(self.pattern)
  228. SP = pg.Edmonds(sg)
  229. self.fileIndex = 0
  230. def propConnected():
  231. """
  232. Checks if the found vertices and edges can be uniquely matched
  233. onto the pattern graph.
  234. """
  235. self.result = self.matchNaive()
  236. return self.result != None
  237. def matchOP(elem, bound, ops, index):
  238. """
  239. Execute a primitive operation, return whether ot not it succeeded.
  240. """
  241. type_bound = bound.setdefault(elem.type, set())
  242. # if elem not yet bound, bind it, and try matching the next operations
  243. if elem not in type_bound:
  244. type_bound.add(elem)
  245. # if matching of next operation failed, try with a different elem
  246. if matchAllOP(ops, index+1):
  247. return True
  248. else:
  249. type_bound.remove(elem)
  250. return False
  251. def matchAllOP(ops, index=0):
  252. """
  253. Try to match an occurrence of the pattern in the graph,
  254. by recursivly ,atching elements that adhere to the SearchPlan
  255. """
  256. # if we matched all elements,
  257. # check if the bound elements are properly connected
  258. if index == len(ops):
  259. return propConnected()
  260. op = ops[index]
  261. if op[0] == PRIM_OP.lkp: # lkp(elem)
  262. if op[2]: # lookup a vertex
  263. # If the graph does not have a vertex of the same vertex
  264. # type, we'll have to return False, happens if elems == [].
  265. elems = self.graph.vertices.get(op[1], [])
  266. bound = self.bound_vertices
  267. else: # loopup an edge
  268. # If the graph does not have an edge of the same edge
  269. # type, we'll have to return False, happens if elems == [].
  270. elems = self.graph.edges.get(op[1], [])
  271. bound = self.bound_edges
  272. # if elems == [], we'll skip the loop and return False
  273. for elem in elems:
  274. if matchOP(elem, bound, ops, index):
  275. return True
  276. # if all not bound elems fails, backtrack
  277. return False
  278. elif op[0] == PRIM_OP.src: # src(e): bind src of a bound edge e
  279. # Should always succeed, as the edge must be already bound
  280. # (there should be at least one elem in self.bound_edges[op[1]]).
  281. for edge in self.bound_edges[op[1]]:
  282. if matchOP(edge.src, self.bound_vertices, ops, index):
  283. return True
  284. # if all not bound elems fails, backtrack
  285. return False
  286. elif op[0] == PRIM_OP.tgt: # tgt(e): bind tgt of a bound edge e
  287. # Should always succeed, as the edge must be already bound
  288. # (there should be at least one elem in self.bound_edges[op[1]]).
  289. for edge in self.bound_edges[op[1]]:
  290. if matchOP(edge.tgt, self.bound_vertices, ops, index):
  291. return True
  292. # if all not bound elems fails, backtrack
  293. return False
  294. elif op[0] == PRIM_OP.inc: # in(v, e): bind incoming edge e of a bound vertex v
  295. # It's possible we will try to find a vertex of a certain type
  296. # in the bound_vertices which should be bound implicitly
  297. # (by a src/tgt op), that is not bound. Happens when implicit
  298. # binding bounded a "wrong" vertex. We then need to return False
  299. # (happens by skiping for loop by looping over [])
  300. for vertex in self.bound_vertices.get(op[1], []):
  301. for edge in vertex.incoming_edges:
  302. if edge.type == op[2]:
  303. if matchOP(edge, self.bound_edges, ops, index):
  304. return True
  305. # if all not bound elems fails, backtrack
  306. return False
  307. elif op[0] == PRIM_OP.out: # out(v, e): bind outgoing edge e of a bound vertex v
  308. # Return False if we expect an element to be bound that is not
  309. # bound (for the same reason as the inc op).
  310. for vertex in self.bound_vertices.get(op[1], []):
  311. for edge in vertex.outgoing_edges:
  312. if edge.type == op[2]:
  313. if matchOP(edge, self.bound_edges, ops, index):
  314. return True
  315. # if all not bound elems fails, backtrack
  316. return False
  317. else:
  318. raise TypeError('Unknown PRIM_OP type')
  319. # try and match all (primitive) operations from the SearchPlan
  320. matchAllOP(SP)
  321. # Either nothing is found, or we found an occurrence,
  322. # it is impossble to have a partionally matched occurrence
  323. for key, bound_elems in self.bound_vertices.items():
  324. if len(bound_elems) == 0:
  325. # The pattern does not exist in the Graph
  326. return None
  327. else:
  328. # We found a pattern
  329. return self.result
  330. def createAdjacencyMatrixMap(self, graph):
  331. """
  332. Return adjacency matrix and the order of the vertices.
  333. """
  334. matrix = collections.OrderedDict() # { vertex, (index, [has edge from index to pos?]) }
  335. # contains all vertices we'll use for the AdjacencyMatrix
  336. allVertices = []
  337. if self.optimize:
  338. # insert only the vertices from the graph which have a type
  339. # that is present in the pattern
  340. for vertex_type, _ in self.pattern.vertices.items():
  341. graph_vertices = graph.vertices.get(vertex_type)
  342. if graph_vertices != None:
  343. allVertices.extend(graph_vertices)
  344. else:
  345. # we will not be able to find the pattern
  346. # as the pattern contains a vertex of a certain type
  347. # that is not present in the host graph
  348. return False
  349. else:
  350. # insert all vertices from the graph
  351. for _, vertices in graph.vertices.items():
  352. allVertices.extend(vertices)
  353. # create squared zero matrix
  354. index = 0
  355. for vertex in allVertices:
  356. matrix[vertex] = (index, [False] * len(allVertices))
  357. index += 1
  358. for _, edges in graph.edges.items():
  359. for edge in edges:
  360. if self.optimize:
  361. if edge.tgt not in matrix or edge.src not in matrix:
  362. # skip adding edge if the target or source type
  363. # is not present in the pattern
  364. # (and therefor not added to the matrix)
  365. continue
  366. index = matrix[edge.tgt][0]
  367. matrix[edge.src][1][index] = True
  368. AM = []
  369. vertices_order = []
  370. for vertex, row in matrix.items():
  371. AM.append(row[1])
  372. vertices_order.append(vertex)
  373. return AM, vertices_order
  374. def matchUllmann(self):
  375. """
  376. Find an occurrence of the pattern in the Graph
  377. by using Ullmann for solving the Constraint Satisfaction Problem (CSP).
  378. """
  379. def createM_star(h, p):
  380. """
  381. Create M*[v, w] = 1 if deg(v) <= deg(w), for v in V_P, w in V_H
  382. = 0 otherwise
  383. M and P are given to ensure corect order.
  384. """
  385. m = [] # [[..], ...]
  386. for p_vertex in p:
  387. row = []
  388. for g_vertex in h:
  389. # for the degree function, we choose to look at the
  390. # outgoing edges AND the incoming edges
  391. # (one might prefer to use only one of them)
  392. if self.optimize:
  393. # also check if type matches
  394. if p_vertex.type != g_vertex.type:
  395. row.append(False)
  396. continue
  397. row.append( len(p_vertex.incoming_edges) <=
  398. len(g_vertex.incoming_edges) and
  399. len(p_vertex.outgoing_edges) <=
  400. len(g_vertex.outgoing_edges))
  401. m.append(row)
  402. return m
  403. def createDecreasingOrder(h):
  404. """
  405. It turns out that the more edges a vertex has, the sooner it will
  406. fail in matching the pattern. For efficiency reasons, we want it
  407. to fail as fast as possible.
  408. """
  409. order = [] # [(value, index), ...]
  410. index = 0
  411. for g_vertex in h:
  412. order.append(( len(g_vertex.outgoing_edges) +
  413. len(g_vertex.outgoing_edges), index))
  414. index += 1
  415. order.sort(key = lambda elem: elem[0])
  416. # sort and only return the indices (which specify the order)
  417. return [index for (_, index) in order]
  418. def propConnected(M, H, P, h, p):
  419. """
  420. Checks if the vertices represented in M are isomorphic to P and if
  421. they can be matched onto the pattern graph.
  422. """
  423. print(M, H, P, h, p)
  424. # P_candi = np.dot(M, np.transpose(np.dot(M, H)))
  425. """
  426. # If we do not aply the refineM function, we will want to check if
  427. # this succeeds, as it checks for isomorphism.
  428. # If we apply the refineM function, it is garanteed to be isomorphic.
  429. index_column = 0
  430. for row in P_candi:
  431. index_row = 0
  432. for item in row:
  433. # for all i,j: P[i, j] = 1 : M(MH)^T [j, i] = 1
  434. # (not the other way around)
  435. # (return False when item is 0 and P[i,j] is 1)
  436. if item < P[index_row][index_column]:
  437. return False
  438. index_row += 1
  439. index_column += 1
  440. """
  441. vertices = {}
  442. index_column = 0
  443. for row in M:
  444. index_row = 0
  445. for item in row:
  446. # there should only be one item per row
  447. if item:
  448. vertex = h[index_row]
  449. vertices.setdefault(vertex.type, set()).add(vertex)
  450. break
  451. index_row += 1
  452. index_column += 1
  453. self.result = self.matchNaive(vertices=vertices, edges=self.graph.edges)
  454. return self.result != None
  455. def refineM(M, H, P, h, pp):
  456. """
  457. Refine M, for every vertex from the pattern, check if each possible
  458. matching (candidate) his neighbours can also be matched. (M's column
  459. represents vertices from P, and the row represents its candidate.)
  460. If this is not possible set M[i,j] to false, refining/reducing the
  461. search space.
  462. """
  463. any_changes=True
  464. while any_changes:
  465. any_changes = False
  466. # for all vertices from the pattern
  467. for i in range(0, len(P)): # P is a nxn-matrix
  468. # for all its possible assignments
  469. for j in range(0, len(H[0])):
  470. # if bound vertex of P, check if all neigbours are matchable
  471. if M[i][j]:
  472. # for all the pattern his neighbours
  473. for k in range(0, len(P)):
  474. # if it is a neighbour (from outgoing edges)
  475. if P[i][k]:
  476. match = False
  477. for p in range(0, len(H[0])):
  478. # check if we can match a candidate neighbour
  479. # (from M* to to the graph (H))
  480. if M[k][p] and H[j][p]:
  481. if self.optimize:
  482. # also check correct type
  483. if pp[k].type != h[p].type:
  484. continue
  485. match = True
  486. break
  487. if not match:
  488. M[i][j] = False
  489. any_changes = True
  490. # if it is a neighbour (from incoming edges)
  491. if P[k][i]:
  492. match = False
  493. for p in range(0, len(H[0])):
  494. # check if we can match a candidate neighbour
  495. # (from M* to to the graph (H))
  496. if M[k][p] and H[p][j]:
  497. if self.optimize:
  498. # also check correct type
  499. if pp[i].type != h[j].type:
  500. continue
  501. match = True
  502. break
  503. if not match:
  504. M[i][j] = False
  505. any_changes = True
  506. def findM(M_star, M, order, H, P, h, p, index_M=0):
  507. """
  508. Find an isomorphic mapping for the vertices of P to H.
  509. This mapping is represented by a matrix M if,
  510. and only if M(MH)^T = P^T.
  511. """
  512. # We are at the end, we found an candidate.
  513. # Remember that we are at the end, bu first check if there is
  514. # a row with ony False, if so, we do not need to check if it is
  515. # properly connected.
  516. check_prop = False
  517. if index_M == len(M):
  518. check_prop = True
  519. index_M -= 1
  520. # we need to refer to this row
  521. old_row = M_star[index_M]
  522. # previous rows (these are sparse, 1 per row, save only its position)
  523. prev_pos = []
  524. for i in range(0, index_M):
  525. row = M[i]
  526. only_false = True
  527. for j in range(0, len(old_row)):
  528. if row[j]:
  529. only_false = False
  530. prev_pos.append(j)
  531. break
  532. if only_false:
  533. # check if a row with only False occurs,
  534. # if so, we will not find an occurence
  535. return False
  536. # We are at the end, we found an candidate.
  537. if check_prop:
  538. index_M += 1
  539. return propConnected(M, H, P, h, p)
  540. M[index_M] = [False] * len(old_row)
  541. index_order = 0
  542. for index_order in range(0, len(order)):
  543. index_row = order[index_order]
  544. # put previous True back on False
  545. if index_order > 0:
  546. M[index_M][order[index_order - 1]] = False
  547. if old_row[index_row]:
  548. M[index_M][index_row] = True
  549. findMPart = True
  550. # 1 0 0 Assume 3th round, and we select x,
  551. # 0 1 0 no element at the same possition in the row,
  552. # 0 x 0 of the elements above itselve in the same
  553. # column may be 1. In the example it is, then try
  554. # selecting an other element.
  555. for index_column in range(0, index_M):
  556. if M[index_column][index_row]:
  557. findMPart = False
  558. break
  559. if not findMPart:
  560. continue
  561. refineM(M, H, P, h, p)
  562. if findM(M_star, M, order, H, P, h, p, index_M + 1):
  563. return True
  564. # reset previous rows their True's
  565. prev_row = 0
  566. for pos in prev_pos:
  567. M[prev_row][pos] = True
  568. prev_row += 1
  569. # reset rows below current row
  570. for index_column in range(index_M + 1, len(M)):
  571. # deep copy, we do not want to just copy pointer to array/list
  572. M[index_column] = M_star[index_column][:]
  573. # reset current row (the rest is already reset)
  574. M[index_M] = M_star[index_M][:]
  575. return False
  576. # create adjecency matrix of the graph
  577. H, h = self.createAdjacencyMatrixMap(self.graph)
  578. # create adjecency matrix of the pattern
  579. P, p = self.createAdjacencyMatrixMap(self.pattern)
  580. # create M* binary matrix
  581. M_star = createM_star(h, p)
  582. # create the order we will use later on
  583. order = createDecreasingOrder(h)
  584. # deepcopy M_s into M
  585. M = [row[:] for row in M_star]
  586. if self.optimize:
  587. refineM(M, H, P, h, p)
  588. findM(M_star, M, order, H, P, h, p)
  589. return self.result
  590. def matchVF2(self):
  591. class VF2_Obj(object):
  592. """
  593. Structor for keeping the VF2 data.
  594. """
  595. def __init__(self, len_graph_vertices, len_pattern_vertices):
  596. # represents if n-the element (h[n] or p[n]) matched
  597. self.core_graph = [False]*len_graph_vertices
  598. self.core_pattern = [False]*len_pattern_vertices
  599. # save mapping from pattern to graph
  600. self.mapping = {}
  601. # preference lvl 1
  602. # ordered set of vertices adjecent to M_graph connected via an outgoing edge
  603. self.N_out_graph = [-1]*len_graph_vertices
  604. # ordered set of vertices adjecent to M_pattern connected via an outgoing edge
  605. self.N_out_pattern = [-1]*len_pattern_vertices
  606. # preference lvl 2
  607. # ordered set of vertices adjecent to M_graph connected via an incoming edge
  608. self.N_inc_graph = [-1]*len_graph_vertices
  609. # ordered set of vertices adjecent to M_pattern connected via an incoming edge
  610. self.N_inc_pattern = [-1]*len_pattern_vertices
  611. # preference lvl 3
  612. # not in the above
  613. def findM(H, P, h, p, VF2_obj, index_M=0):
  614. """
  615. Find an isomorphic mapping for the vertices of P to H.
  616. This mapping is represented by a matrix M if,
  617. and only if M(MH)^T = P^T.
  618. This operates in a simular way as Ullmann. Ullmann has a predefind
  619. order for matching (sorted on most edges first). VF2's order is to
  620. first try to match the adjacency vertices connected via outgoing
  621. edges, then thos connected via incoming edges and then those that
  622. not connected to the currently mathed vertices.
  623. """
  624. def addOutNeighbours(neighbours, N, index_M):
  625. """
  626. Given outgoing neighbours (a row from an adjacency matrix),
  627. label them as added by saving when they got added (index_M
  628. represents this, otherwise it is -1)
  629. """
  630. for neighbour_index in range(0, len(neighbours)):
  631. if neighbours[neighbour_index]:
  632. if N[neighbour_index] == -1:
  633. N[neighbour_index] = index_M
  634. def addIncNeighbours(G, j, N, index_M):
  635. """
  636. Given the adjacency matrix, and the colum j, representing that
  637. we want to add the incoming edges to vertex j,
  638. label them as added by saving when they got added (index_M
  639. represents this, otherwise it is -1)
  640. """
  641. for i in range(0, len(G)):
  642. if G[i][j]:
  643. if N[i] == -1:
  644. N[i] = index_M
  645. def delNeighbours(N, index_M):
  646. """
  647. Remove neighbours that where added at index_M.
  648. If we call this function, we are backtracking and we want to
  649. remove the added neighbours from the just tried matching (n, m)
  650. pair (whiched failed).
  651. """
  652. for n in range(0, len(N)):
  653. if N[n] == index_M:
  654. N[n] = -1
  655. def feasibilityTest(H, P, h, p, VF2_obj, n, m):
  656. """
  657. Examine all the nodes connected to n and m; if such nodes are
  658. in the current partial mapping, check if each branch from or to
  659. n has a corresponding branch from or to m and vice versa.
  660. If the nodes and the branches of the graphs being matched also
  661. carry semantic attributes, another condition must also hold for
  662. F(s, n, m) to be true; namely the attributes of the nodes and of
  663. the branches being paired must be compatible.
  664. Another pruning step is to check if the nr of ext_edges between
  665. the matched_vertices from the pattern and its adjecent vertices
  666. are less than or equal to the nr of ext_edges between
  667. matched_vertices from the graph and its adjecent vertices.
  668. And if the nr of ext_edges between those adjecent vertices from
  669. the pattern and the not connected vertices are less than or
  670. equal to the nr of ext_edges between those adjecent vertices from
  671. the graph and its adjecent vertices.
  672. """
  673. # Get all neighbours from graph node n and pattern node m
  674. # (including n and m)
  675. neighbours_graph = {}
  676. neighbours_graph[h[n].type] = set([h[n]])
  677. neighbours_pattern = {}
  678. neighbours_pattern[p[m].type] = set([p[m]])
  679. # add all neihgbours of pattern vertex m
  680. for i in range(0, len(P)): # P is a nxn-matrix
  681. if (P[m][i] or P[i][m]) and VF2_obj.core_pattern[i]:
  682. neighbours_pattern.setdefault(p[i].type, set()).add(p[i])
  683. # add all neihgbours of graph vertex n
  684. for i in range(0, len(H)): # P is a nxn-matrix
  685. if (H[n][i] or H[i][n]) and VF2_obj.core_graph[i]:
  686. neighbours_graph.setdefault(h[i].type, set()).add(h[i])
  687. # take a coding shortcut,
  688. # use self.matchNaive function to see if it is feasable.
  689. # this way, we immidiatly test the semantic attributes
  690. if not self.matchNaive(pattern_vertices=neighbours_pattern, vertices=neighbours_graph, edges=self.graph.edges):
  691. return False
  692. # count ext_edges from core_graph to a adjecent vertices and
  693. # cuotn ext_edges for adjecent vertices and not matched vertices
  694. # connected via the ext_edges
  695. ext_edges_graph_ca = 0
  696. ext_edges_graph_an = 0
  697. # for all core vertices
  698. for x in range(0, len(VF2_obj.core_graph)):
  699. # for all its neighbours
  700. for y in range(0, len(H)):
  701. if H[x][y]:
  702. # if it is a neighbor and not yet matched
  703. if (VF2_obj.N_out_graph[y] != -1 or VF2_obj.N_inc_graph[y] != -1) and VF2_obj.core_graph[y]:
  704. # if we matched it
  705. if VF2_obj.core_graph[x] != -1:
  706. ext_edges_graph_ca += 1
  707. else:
  708. ext_edges_graph_an += 1
  709. # count ext_edges from core_pattern to a adjecent vertices
  710. # connected via the ext_edges
  711. ext_edges_pattern_ca = 0
  712. ext_edges_pattern_an = 0
  713. # for all core vertices
  714. for x in range(0, len(VF2_obj.core_pattern)):
  715. # for all its neighbours
  716. for y in range(0, len(P)):
  717. if P[x][y]:
  718. # if it is a neighbor and not yet matched
  719. if (VF2_obj.N_out_pattern[y] != -1 or VF2_obj.N_inc_pattern[y] != -1) and VF2_obj.core_pattern[y]:
  720. # if we matched it
  721. if VF2_obj.core_pattern[x] != -1:
  722. ext_edges_pattern_ca += 1
  723. else:
  724. ext_edges_pattern_an += 1
  725. # The nr of ext_edges between matched_vertices from the pattern
  726. # and its adjecent vertices must be less than or equal to the nr
  727. # of ext_edges between matched_vertices from the graph and its
  728. # adjecent vertices, otherwise we wont find an occurrence
  729. if ext_edges_pattern_ca > ext_edges_graph_ca:
  730. return False
  731. # The nr of ext_edges between those adjancent vertices from the
  732. # pattern and its not connected vertices must be less than or
  733. # equal to the nr of ext_edges between those adjacent vertices
  734. # from the graph and its not connected vertices,
  735. # otherwise we wont find an occurrence
  736. if ext_edges_pattern_an > ext_edges_graph_an:
  737. return False
  738. return True
  739. def matchPhase(H, P, h, p, index_M, VF2_obj, n, m):
  740. """
  741. The matching fase of the VF2 algorithm. If the chosen n, m pair
  742. passes the feasibilityTest, the pair gets added and we start
  743. to search for the next matching pair.
  744. """
  745. # all candidate pair (n, m) represent graph x pattern
  746. candidate = frozenset(itertools.chain(
  747. ((i, j) for i,j in VF2_obj.mapping.items()),
  748. # ((self.reverseMapH[i], self.reverseMapP[j]) for i,j in VF2_obj.mapping.items()),
  749. [(h[n],p[m])],
  750. ))
  751. if candidate in self.alreadyVisited:
  752. # print(self.indent*" ", "candidate:", candidate)
  753. # for match in self.alreadyVisited.get(index_M, []):
  754. # if match == candidate:
  755. return False # already visited this (partial) match -> skip
  756. if feasibilityTest(H, P, h, p, VF2_obj, n, m):
  757. print(self.indent*" ","adding to match:", n, "->", m)
  758. # adapt VF2_obj
  759. VF2_obj.core_graph[n] = True
  760. VF2_obj.core_pattern[m] = True
  761. VF2_obj.mapping[h[n]] = p[m]
  762. addOutNeighbours(H[n], VF2_obj.N_out_graph, index_M)
  763. addIncNeighbours(H, n, VF2_obj.N_inc_graph, index_M)
  764. addOutNeighbours(P[m], VF2_obj.N_out_pattern, index_M)
  765. addIncNeighbours(P, m, VF2_obj.N_inc_pattern, index_M)
  766. if index_M > 0:
  767. # remember our partial match (shallow copy) so we don't visit it again
  768. self.alreadyVisited.add(frozenset([ (i, j) for i,j in VF2_obj.mapping.items()]))
  769. # self.alreadyVisited.setdefault(index_M, set()).add(frozenset([ (self.reverseMapH[i], self.reverseMapP[j]) for i,j in VF2_obj.mapping.items()]))
  770. # print(self.alreadyVisited)
  771. self.indent += 1
  772. if findM(H, P, h, p, VF2_obj, index_M + 1):
  773. # return True
  774. print(self.indent*" ","found match", len(self.results), ", continuing...")
  775. self.indent -= 1
  776. if True:
  777. # else:
  778. print(self.indent*" ","backtracking... remove", n, "->", m)
  779. # else, backtrack, adapt VF2_obj
  780. VF2_obj.core_graph[n] = False
  781. VF2_obj.core_pattern[m] = False
  782. del VF2_obj.mapping[h[n]]
  783. delNeighbours(VF2_obj.N_out_graph, index_M)
  784. delNeighbours(VF2_obj.N_inc_graph, index_M)
  785. delNeighbours(VF2_obj.N_out_pattern, index_M)
  786. delNeighbours(VF2_obj.N_inc_pattern, index_M)
  787. return False
  788. def preferred(H, P, h, p, index_M, VF2_obj, N_graph, N_pattern):
  789. """
  790. Try to match the adjacency vertices connected via outgoing
  791. or incoming edges. (Depending on what is given for N_graph and
  792. N_pattern.)
  793. """
  794. for n in range(0, len(N_graph)):
  795. # skip graph vertices that are not in VF2_obj.N_out_graph
  796. # (or already matched)
  797. if N_graph[n] == -1 or VF2_obj.core_graph[n]:
  798. # print(self.indent*" "," skipping")
  799. continue
  800. print(self.indent*" "," n:", n)
  801. for m in range(0, len(N_pattern)):
  802. # skip graph vertices that are not in VF2_obj.N_out_pattern
  803. # (or already matched)
  804. if N_pattern[m] == -1 or VF2_obj.core_pattern[m]:
  805. continue
  806. print(self.indent*" "," m:", m)
  807. if matchPhase(H, P, h, p, index_M, VF2_obj, n, m):
  808. return True
  809. return False
  810. def leastPreferred(H, P, h, p, index_M, VF2_obj):
  811. """
  812. Try to match the vertices that are not connected to the curretly
  813. matched vertices.
  814. """
  815. for n in range(0, len(VF2_obj.N_out_graph)):
  816. # skip vertices that are connected to the graph
  817. # (or already matched)
  818. if not (VF2_obj.N_out_graph[n] == -1 and VF2_obj.N_inc_graph[n] == -1) or VF2_obj.core_graph[n]:
  819. # print(self.indent*" "," skipping")
  820. continue
  821. print(" n:", n)
  822. for m in range(0, len(VF2_obj.N_out_pattern)):
  823. # skip vertices that are connected to the graph
  824. # (or already matched)
  825. if not (VF2_obj.N_out_pattern[m] == -1 and VF2_obj.N_inc_pattern[m] == -1) or VF2_obj.core_pattern[m]:
  826. # print(self.indent*" "," skipping")
  827. continue
  828. print(self.indent*" "," m:", m)
  829. if matchPhase(H, P, h, p, index_M, VF2_obj, n, m):
  830. return True
  831. return False
  832. print(self.indent*" ","index_M:", index_M)
  833. # We are at the end, we found an candidate.
  834. if index_M == len(p):
  835. print(self.indent*" ","end...")
  836. bound_graph_vertices = {}
  837. for vertex_bound, _ in VF2_obj.mapping.items():
  838. bound_graph_vertices.setdefault(vertex_bound.type, set()).add(vertex_bound)
  839. self.result = self.matchNaive(vertices=bound_graph_vertices, edges=self.graph.edges)
  840. if self.result != None:
  841. self.results.append(self.result)
  842. return self.result != None
  843. if index_M > 0:
  844. # try the candidates is the preffered order
  845. # first try the adjacent vertices connected via the outgoing edges.
  846. print(self.indent*" ","preferred L1")
  847. if preferred(H, P, h, p, index_M, VF2_obj, VF2_obj.N_out_graph, VF2_obj.N_out_pattern):
  848. return True
  849. print(self.indent*" ","preferred L2")
  850. # then try the adjacent vertices connected via the incoming edges.
  851. if preferred(H, P, h, p, index_M, VF2_obj, VF2_obj.N_inc_graph, VF2_obj.N_inc_pattern):
  852. return True
  853. print(self.indent*" ","leastPreferred")
  854. # and lastly, try the vertices not connected to the currently matched vertices
  855. if leastPreferred(H, P, h, p, index_M, VF2_obj):
  856. return True
  857. return False
  858. # create adjecency matrix of the graph
  859. H, h = self.createAdjacencyMatrixMap(self.graph)
  860. print("adjacency:", H)
  861. print("h:", len(h))
  862. # create adjecency matrix of the pattern
  863. P, p = self.createAdjacencyMatrixMap(self.pattern)
  864. VF2_obj = VF2_Obj(len(h), len(p))
  865. self.indent = 0
  866. # Only for debugging:
  867. self.reverseMapH = { h[i] : i for i in range(len(h))}
  868. self.reverseMapP = { p[i] : i for i in range(len(p))}
  869. # Set of partial matches already explored - prevents us from producing the same match multiple times
  870. # Encoded as a mapping from match size to the partial match
  871. self.alreadyVisited = set()
  872. findM(H, P, h, p, VF2_obj)
  873. # return self.results