Anders and Briegel in Python
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

276 lines
8.9KB

  1. """
  2. Provides an extremely basic graph structure, based on key/value pairs
  3. """
  4. import itertools as it
  5. import json
  6. import qi, clifford, util
  7. import random
  8. class GraphState(object):
  9. def __init__(self, nodes=[]):
  10. self.adj, self.node = {}, {}
  11. self.add_nodes(nodes)
  12. def add_node(self, v, **kwargs):
  13. """ Add a node """
  14. assert not v in self.node
  15. self.adj[v] = {}
  16. self.node[v] = {"vop": clifford.by_name["hadamard"]}
  17. self.node[v].update(kwargs)
  18. def add_nodes(self, nodes):
  19. """ Add a buncha nodes """
  20. for n in nodes:
  21. self.add_node(n)
  22. def add_edge(self, v1, v2, data={}):
  23. """ Add an edge between two vertices in the self """
  24. assert v1 != v2
  25. self.adj[v1][v2] = data
  26. self.adj[v2][v1] = data
  27. def add_edges(self, edges):
  28. """ Add a buncha edges """
  29. for (v1, v2) in edges:
  30. self.add_edge(v1, v2)
  31. def del_edge(self, v1, v2):
  32. """ Delete an edge between two vertices in the self """
  33. del self.adj[v1][v2]
  34. del self.adj[v2][v1]
  35. def has_edge(self, v1, v2):
  36. """ Test existence of an edge between two vertices in the self """
  37. return v2 in self.adj[v1]
  38. def toggle_edge(self, v1, v2):
  39. """ Toggle an edge between two vertices in the self """
  40. if self.has_edge(v1, v2):
  41. self.del_edge(v1, v2)
  42. else:
  43. self.add_edge(v1, v2)
  44. def edgelist(self):
  45. """ Describe a graph as an edgelist """
  46. # TODO: inefficient
  47. edges = set(tuple(sorted((i, n)))
  48. for i, v in self.adj.items()
  49. for n in v)
  50. return tuple(edges)
  51. def remove_vop(self, a, avoid):
  52. """ Reduces VOP[a] to the identity """
  53. others = set(self.adj[a]) - {avoid}
  54. swap_qubit = others.pop() if others else avoid
  55. for v in reversed(clifford.decompositions[self.node[a]["vop"]]):
  56. if v == "x":
  57. self.local_complementation(a, "U ->")
  58. else:
  59. self.local_complementation(swap_qubit, "V ->")
  60. def local_complementation(self, v, prefix=""):
  61. """ As defined in LISTING 1 of Anders & Briegel """
  62. for i, j in it.combinations(self.adj[v], 2):
  63. self.toggle_edge(i, j)
  64. self.node[v]["vop"] = clifford.times_table[
  65. self.node[v]["vop"], clifford.by_name["msqx_h"]]
  66. for i in self.adj[v]:
  67. self.node[i]["vop"] = clifford.times_table[
  68. self.node[i]["vop"], clifford.by_name["sqz_h"]]
  69. def act_local_rotation(self, v, op):
  70. """ Act a local rotation """
  71. rotation = clifford.by_name[str(op)]
  72. self.node[v]["vop"] = clifford.times_table[
  73. rotation, self.node[v]["vop"]]
  74. def act_hadamard(self, qubit):
  75. """ Shorthand """
  76. self.act_local_rotation(qubit, 10)
  77. def lonely(self, a, b):
  78. """ Is this qubit lonely ? """
  79. return len(self.adj[a]) > (b in self.adj[a])
  80. def act_cz(self, a, b):
  81. """ Act a controlled-phase gate on two qubits """
  82. if self.lonely(a, b):
  83. self.remove_vop(a, b)
  84. if self.lonely(b, a):
  85. self.remove_vop(b, a)
  86. if self.lonely(a, b) and not clifford.is_diagonal(self.node[a]["vop"]):
  87. self.remove_vop(a, b)
  88. edge = self.has_edge(a, b)
  89. va = self.node[a]["vop"]
  90. vb = self.node[b]["vop"]
  91. new_edge, self.node[a]["vop"], self.node[b]["vop"] = \
  92. clifford.cz_table[edge, va, vb]
  93. if new_edge != edge:
  94. self.toggle_edge(a, b)
  95. def measure(self, node, basis, force=None):
  96. """ Measure in an arbitrary basis """
  97. basis = clifford.by_name[basis]
  98. old_basis = basis
  99. ha = clifford.conjugation_table[self.node[node]["vop"]]
  100. basis, phase = clifford.conjugate(basis, ha)
  101. assert phase in (-1, 1) # TODO: remove
  102. # TODO: wtf
  103. force = force ^ 0x01 if force != -1 and phase == 0 else force
  104. which = {1: self.measure_x, 2:
  105. self.measure_y, 3: self.measure_z}[basis]
  106. res = which(node, force)
  107. res = res if phase == 1 else not res
  108. # TODO: put the asserts from graphsim.cpp into tests
  109. return res
  110. def toggle_edges(a, b):
  111. """ Toggle edges between vertex sets a and b """
  112. done = {}
  113. for i, j in it.product(a, b):
  114. if i == j and not (i, j) in done:
  115. done.add((i, j), (j, i))
  116. self.toggle_edge(i, j)
  117. def measure_x(self, node, force=None):
  118. """ Measure the graph in the X-basis """
  119. if len(self.adj[node]) == 0:
  120. return 0
  121. # Flip a coin
  122. result = force if force != None else random.choice([0, 1])
  123. # Pick a vertex
  124. friend = next(self.adj[node].iterkeys())
  125. # TODO: yuk yuk yuk
  126. if result:
  127. # Do a z on all ngb(vb) \ ngb(v) \ {v}, and some other stuff
  128. self.act_local_rotation(node, "pz")
  129. self.act_local_rotation(friend, "msqy")
  130. for n in set(self.adj[friend]) - set(self.adj(node)) - {node}:
  131. self.act_local_rotation(n, "pz")
  132. else:
  133. # Do a z on all ngb(v) \ ngb(vb) \ {vb}, and sqy on the friend
  134. self.act_local_rotation(friend, "sqy")
  135. for n in set(self.adj[node]) - set(self.adj(friend)) - {friend}:
  136. self.act_local_rotation(n, "pz")
  137. # TODO: Yuk. Just awful!
  138. a = set(self.adj[node].keys())
  139. b = set(self.adj[friend].keys())
  140. self.toggle_edges(a, b)
  141. intersection = a & b
  142. for i, j in it.combinations(intersection, 2):
  143. self.toggle_edge(i, j)
  144. for n in a - {friend}:
  145. self.toggle_edge(friend, n)
  146. return result
  147. def measure_y(self, node, force=None):
  148. """ Measure the graph in the Y-basis """
  149. # Flip a coin
  150. result = force if force != None else random.choice([0, 1])
  151. # Do some rotations
  152. for neighbour in self.adj[node]:
  153. # NB: should these be hermitian_conjugated?
  154. self.act_local_rotation(neighbour, "sqz" if result else "msqz")
  155. # A sort of local complementation
  156. vngbh = set(self.adj[node]) | {node}
  157. for i, j in it.combinations(vngbh, 2):
  158. self.toggle_edge(i, j)
  159. self.act_local_rotation(node, "msqz" if result else "msqz_h")
  160. return result
  161. def measure_z(self, node, force=None):
  162. """ Measure the graph in the Z-basis """
  163. # Flip a coin
  164. result = force if force != None else random.choice([0, 1])
  165. # Disconnect
  166. for neighbour in self.adj[node]:
  167. self.del_edge(node, neighbour)
  168. if result:
  169. self.act_local_rotation(neighbour, "pz")
  170. # Rotate
  171. if result:
  172. self.act_local_rotation(node, "px")
  173. self.act_local_rotation(node, "hadamard")
  174. return result
  175. def order(self):
  176. """ Get the number of qubits """
  177. return len(self.node)
  178. def __str__(self):
  179. """ Represent as a string for quick debugging """
  180. node = {key: clifford.get_name(value["vop"])
  181. for key, value in self.node.items()}
  182. nbstr = str(self.adj)
  183. return "graph:\n node: {}\n adj: {}\n".format(node, nbstr)
  184. def to_json(self, stringify=False):
  185. """
  186. Convert the graph to JSON form.
  187. JSON keys must be strings, But sometimes it is useful to have
  188. a JSON-like object whose keys are tuples!
  189. """
  190. if stringify:
  191. node = {str(key): value for key, value in self.node.items()}
  192. adj = {str(key): {str(key): value for key, value in ngbh.items()}
  193. for key, ngbh in self.adj.items()}
  194. return {"node": node, "adj": adj}
  195. else:
  196. return {"node": self.node, "adj": self.adj}
  197. def from_json(self, data):
  198. """ Reconstruct from JSON """
  199. self.__init__([])
  200. # TODO
  201. def to_state_vector(self):
  202. """ Get the full state vector """
  203. if len(self.node) > 15:
  204. raise ValueError("Cannot build state vector: too many qubits")
  205. state = qi.CircuitModel(len(self.node))
  206. for i in range(len(self.node)):
  207. state.act_hadamard(i)
  208. for i, j in self.edgelist():
  209. state.act_cz(i, j)
  210. for i, n in self.node.items():
  211. state.act_local_rotation(i, clifford.unitaries[n["vop"]])
  212. return state
  213. def to_stabilizer(self):
  214. """ Get the stabilizer of this graph """
  215. output = {a: {} for a in self.node}
  216. for a, b in it.product(self.node, self.node):
  217. if a == b:
  218. output[a][b] = "X"
  219. elif a in self.adj[b]:
  220. output[a][b] = "Z"
  221. else:
  222. output[a][b] = "I"
  223. return output
  224. def __eq__(self, other):
  225. """ Check equality between graphs """
  226. return self.adj == other.adj and self.node == other.node