generator.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. import graph
  17. # import numpy as np
  18. import math
  19. import collections
  20. import random
  21. class GraphGenerator(object):
  22. """
  23. Generates a random Graph with dv an array containing all vertices (there type),
  24. de an array containing all edges (their type) and dc_inc an array representing
  25. the incoming edges (analogue for dc_out)
  26. """
  27. def __init__(self, dv, de, dc_inc, dc_out, debug=False):
  28. if len(de) != len(dc_inc):
  29. raise ValueError('de and dc_inc should be the same length.')
  30. if len(de) != len(dc_out):
  31. raise ValueError('de and dc_out should be the same length.')
  32. self.dv = dv
  33. self.de = de
  34. self.dc_inc = dc_inc
  35. self.dc_out = dc_out
  36. # print for debugging, so you know the used values
  37. if debug:
  38. print('dv')
  39. print('[',','.join(map(str,dv)),']')
  40. print('_____')
  41. print('de')
  42. print('[',','.join(map(str,de)),']')
  43. print('_____')
  44. print('dc_inc')
  45. print('[',','.join(map(str,dc_inc)),']')
  46. print('_____')
  47. print('dc_out')
  48. print('[',','.join(map(str,dc_out)),']')
  49. print('_____')
  50. self.graph = graph.Graph()
  51. self.vertices = []
  52. # create all the vertices:
  53. for v_type in self.dv:
  54. # v_type represents the type of the vertex
  55. self.vertices.append(self.graph.addCreateVertex('v' + str(v_type)))
  56. index = 0
  57. # create all edges
  58. for e_type in self.de:
  59. # e_type represents the type of the edge
  60. src = self.vertices[self.dc_out[index]] # get src vertex
  61. tgt = self.vertices[self.dc_inc[index]] # get tgt vertex
  62. self.graph.addCreateEdge(src, tgt, 'e' + str(e_type)) # create edge
  63. index += 1
  64. def getRandomGraph(self):
  65. return self.graph
  66. def getRandomPattern(self, max_nr_of_v, max_nr_of_e, start=0, debug=False):
  67. # create pattern
  68. pattern = graph.Graph()
  69. # map from graph to new pattern
  70. graph_to_pattern = {}
  71. # map of possible edges
  72. # we don't need a dict, but python v2.7 does not have an OrderedSet
  73. possible_edges = collections.OrderedDict()
  74. # set of chosen edges
  75. chosen_edges = set()
  76. # start node from graph
  77. g_node = self.vertices[start]
  78. p_node = pattern.addCreateVertex(g_node.type)
  79. # for debuging, print the order in which the pattern gets created and
  80. # connects it edges
  81. if debug:
  82. print('v'+str(id(p_node))+'=pattern.addCreateVertex('+"'"+str(g_node.type)+"'"+')')
  83. # save corrolation
  84. graph_to_pattern[g_node] = p_node
  85. def insertAllEdges(edges, possible_edges, chosen_edges):
  86. for edge in edges:
  87. # if we did not chose the edge
  88. if edge not in chosen_edges:
  89. # if inc_edge not in possible edges, add it with value 1
  90. possible_edges[edge] = None
  91. def insertEdges(g_vertex, possible_edges, chosen_edges):
  92. insertAllEdges(g_vertex.incoming_edges, possible_edges, chosen_edges)
  93. insertAllEdges(g_vertex.outgoing_edges, possible_edges, chosen_edges)
  94. insertEdges(g_node, possible_edges, chosen_edges)
  95. while max_nr_of_v > len(graph_to_pattern) and max_nr_of_e > len(chosen_edges):
  96. candidate = None
  97. if len(possible_edges) == 0:
  98. break
  99. # get a random number between 0 and len(possible_edges)
  100. # We us a triangular distribution to approximate the fact that
  101. # the first element is the longest in the possible_edges and
  102. # already had the post chance of beeing choosen.
  103. # (The approximation is because the first few ellements where
  104. # added in the same itteration, but doing this exact is
  105. # computationally expensive.)
  106. if len(possible_edges) == 1:
  107. randie = 0
  108. else:
  109. randie = int(round(random.triangular(1, len(possible_edges), len(possible_edges)))) - 1
  110. candidate = list(possible_edges.keys())[randie]
  111. del possible_edges[candidate]
  112. chosen_edges.add(candidate)
  113. src = graph_to_pattern.get(candidate.src)
  114. tgt = graph_to_pattern.get(candidate.tgt)
  115. src_is_new = True
  116. if src != None and tgt != None:
  117. # create edge between source and target
  118. pattern.addCreateEdge(src, tgt, candidate.type)
  119. if debug:
  120. print('pattern.addCreateEdge('+'v'+str(id(src))+', '+'v'+str(id(tgt))+', '+"'"+str(candidate.type)+"'"+')')
  121. # skip adding new edges
  122. continue
  123. elif src == None:
  124. # create pattern vertex
  125. src = pattern.addCreateVertex(candidate.src.type)
  126. if debug:
  127. print('v'+str(id(src))+'=pattern.addCreateVertex('+"'"+str(candidate.src.type)+"'"+')')
  128. # map newly created pattern vertex
  129. graph_to_pattern[candidate.src] = src
  130. # create edge between source and target
  131. pattern.addCreateEdge(src, tgt, candidate.type)
  132. if debug:
  133. print('pattern.addCreateEdge('+'v'+str(id(src))+', '+'v'+str(id(tgt))+', '+"'"+str(candidate.type)+"'"+')')
  134. elif tgt == None:
  135. src_is_new = False
  136. # create pattern vertex
  137. tgt = pattern.addCreateVertex(candidate.tgt.type)
  138. if debug:
  139. print('v'+str(id(tgt))+'=pattern.addCreateVertex('+"'"+str(candidate.tgt.type)+"'"+')')
  140. # map newly created pattern vertex
  141. graph_to_pattern[candidate.tgt] = tgt
  142. # create edge between source and target
  143. pattern.addCreateEdge(src, tgt, candidate.type)
  144. if debug:
  145. print('pattern.addCreateEdge('+'v'+str(id(src))+', '+'v'+str(id(tgt))+', '+"'"+str(candidate.type)+"'"+')')
  146. else:
  147. raise RuntimeError('Bug: src or tgt of edge should be in out pattern')
  148. # select the vertex from the chosen edge that was not yet part of the pattern
  149. if src_is_new:
  150. new_vertex = candidate.src
  151. else:
  152. new_vertex = candidate.tgt
  153. # insert all edges from the new vertex
  154. insertEdges(new_vertex, possible_edges, chosen_edges)
  155. return pattern
  156. def createConstantPattern():
  157. """
  158. Use this to create the same pattern over and over again.
  159. """
  160. # create pattern
  161. pattern = graph.Graph()
  162. # copy and paste printed pattern from debug output or create a pattern
  163. # below the following line:
  164. # ----------------------------------------------------------------------
  165. v4447242448=pattern.addCreateVertex('v4')
  166. v4457323088=pattern.addCreateVertex('v6')
  167. pattern.addCreateEdge(v4447242448, v4457323088, 'e4')
  168. v4457323216=pattern.addCreateVertex('v8')
  169. pattern.addCreateEdge(v4457323216, v4447242448, 'e4')
  170. v4457323344=pattern.addCreateVertex('v7')
  171. pattern.addCreateEdge(v4457323216, v4457323344, 'e3')
  172. v4457323472=pattern.addCreateVertex('v7')
  173. pattern.addCreateEdge(v4457323344, v4457323472, 'e1')
  174. # ----------------------------------------------------------------------
  175. return pattern
  176. def get_random_host_and_guest(nr_vtxs, nr_vtx_types, nr_edges, nr_edge_types, pattern_nr_vtxs=3, pattern_nr_edges=15):
  177. dv = [random.randint(0, nr_vtx_types) for _ in range(nr_vtxs)]
  178. de = [random.randint(0, nr_edge_types) for _ in range(nr_edges)]
  179. dc_inc = [random.randint(0, nr_vtxs-1) for _ in range(nr_edges)]
  180. dc_out = [random.randint(0, nr_vtxs-1) for _ in range(nr_edges)]
  181. return get_host_and_guest(dv, de, dc_inc, dc_out, pattern_nr_vtxs, pattern_nr_edges)
  182. def get_host_and_guest(dv, de, dc_inc, dc_out, pattern_nr_vtxs=3, pattern_nr_edges=15):
  183. gg = GraphGenerator(dv, de, dc_inc, dc_out)
  184. graph = gg.getRandomGraph()
  185. pattern = gg.getRandomPattern(pattern_nr_vtxs, pattern_nr_edges, debug=False)
  186. return (graph, pattern)
  187. def get_large_host_and_guest():
  188. dv = [ 10,5,4,0,8,6,8,0,4,8,5,5,7,0,10,0,5,6,10,4,0,3,0,8,2,7,5,8,1,0,2,10,0,0,1,6,8,4,7,6,4,2,10,10,6,4,6,0,2,7 ]
  189. de = [ 8,10,8,1,6,7,4,3,5,2,0,0,9,6,0,3,8,3,2,7,2,3,10,8,10,8,10,2,5,5,10,6,7,5,1,2,1,2,2,3,7,7,2,1,7,2,9,10,8,1,9,4,1,3,1,1,8,2,2,9,10,9,1,9,4,10,10,10,9,3,5,3,6,6,9,1,2,6,3,2,4,10,9,6,5,6,2,4,3,2,4,10,6,2,8,8,0,5,1,7,3,4,3,8,7,3,0,8,3,3,8,5,10,5,9,3,1,10,3,2,6,3,10,0,5,10,9,10,0,1,4,7,10,3,1,9,1,2,3,7,4,3,7,8,8,4,5,10,1,4 ]
  190. dc_inc = [ 0,25,18,47,22,25,16,45,38,25,5,45,15,44,17,46,6,17,35,8,16,29,48,47,25,34,4,20,24,1,47,44,8,25,32,3,16,6,33,21,6,13,41,10,17,25,21,33,31,30,5,4,45,26,16,42,12,25,29,3,32,30,14,26,11,13,7,13,3,43,43,22,48,37,20,28,15,40,19,33,43,16,49,36,11,25,9,42,3,22,16,40,42,44,27,30,1,18,10,35,19,6,9,43,37,38,45,19,41,14,37,45,0,31,29,31,24,20,44,46,8,45,43,3,38,38,35,12,19,45,7,34,20,28,12,17,45,17,35,49,20,21,49,1,35,38,38,36,33,30 ]
  191. dc_out = [ 9,2,49,49,37,33,16,21,5,46,4,15,9,6,14,22,16,33,23,21,15,31,37,23,47,3,30,26,35,9,29,21,39,32,22,43,5,9,41,30,31,30,37,33,31,34,23,22,34,26,44,36,38,33,48,5,9,34,13,7,48,41,43,26,26,7,12,6,12,28,22,8,29,22,24,27,16,4,31,41,32,15,19,20,38,0,26,18,43,46,40,17,29,14,34,14,32,17,32,47,16,45,7,4,35,22,42,11,38,2,0,29,4,38,17,44,9,23,5,10,31,17,1,11,16,5,37,27,35,32,45,16,18,1,14,4,42,24,43,31,21,38,6,34,39,46,20,1,38,47 ]
  192. return get_host_and_guest(dv, de, dc_inc, dc_out)
  193. def get_small_host_and_guest():
  194. dv = [0, 1, 0, 1, 0]
  195. de = [0, 0, 0]
  196. dc_inc = [0, 2, 4]
  197. dc_out = [1, 3, 3]
  198. return get_host_and_guest(dv, de, dc_inc, dc_out)