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.

211 lines
6.7KB

  1. """
  2. Provides an extremely basic graph structure, based on neighbour lists
  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. #TODO: inefficient
  54. others = set(self.adj[a]) - {avoid}
  55. swap_qubit = others.pop() if others else avoid
  56. for v in reversed(clifford.decompositions[self.node[a]["vop"]]):
  57. self.local_complementation(a if v == "x" else swap_qubit)
  58. def local_complementation(self, v):
  59. """ As defined in LISTING 1 of Anders & Briegel """
  60. for i, j in it.combinations(self.adj[v], 2):
  61. self.toggle_edge(i, j)
  62. msqx_h = clifford.conjugation_table[clifford.by_name["msqx"]]
  63. sqz_h = clifford.conjugation_table[clifford.by_name["sqz"]]
  64. self.node[v]["vop"] = clifford.times_table[self.node[v]["vop"], msqx_h]
  65. for i in self.adj[v]:
  66. self.node[i]["vop"] = clifford.times_table[self.node[i]["vop"], sqz_h]
  67. def act_local_rotation(self, v, op):
  68. """ Act a local rotation """
  69. rotation = clifford.by_name[str(op)]
  70. self.node[v]["vop"] = clifford.times_table[rotation, self.node[v]["vop"]]
  71. def act_hadamard(self, qubit):
  72. """ Shorthand """
  73. self.act_local_rotation(qubit, 10)
  74. def act_cz(self, a, b):
  75. """ Act a controlled-phase gate on two qubits """
  76. ci = self.get_connection_info(a, b)
  77. if ci["non1"]:
  78. self.remove_vop(a, b)
  79. ci = self.get_connection_info(a, b)
  80. if ci["non2"]:
  81. self.remove_vop(b, a)
  82. ci = self.get_connection_info(a, b)
  83. if ci["non1"] and not clifford.is_diagonal(self.node[a]["vop"]):
  84. self.remove_vop(b, a)
  85. self.cz_with_table(a, b, ci["was_edge"])
  86. def get_connection_info(self, a, b):
  87. if self.has_edge(a, b):
  88. return {"was_edge": True,
  89. "non1": len(self.node.get(a, [])) > 0,
  90. "non2": len(self.node.get(b, [])) > 0}
  91. else:
  92. return {"was_edge": False,
  93. "non1": len(self.node.get(a, [])) > 1,
  94. "non2": len(self.node.get(b, [])) > 1}
  95. def cz_with_table(self, a, b, edge):
  96. """ Run the table """
  97. new_edge, self.node[a]["vop"], self.node[
  98. b]["vop"] = clifford.cz_table[edge, self.node[a]["vop"], self.node[b]["vop"]]
  99. if new_edge != edge:
  100. self.toggle_edge(a, b)
  101. def measure_z(self, node, force=None):
  102. """ Measure the graph in the Z-basis """
  103. res = force if force!=None else random.choice([0, 1])
  104. # Disconnect
  105. for neighbour in self.adj[node]:
  106. self.del_edge(node, neighbour)
  107. if res:
  108. self.act_local_rotation(neighbour, "pz")
  109. # Rotate
  110. if res:
  111. self.act_local_rotation(node, "px")
  112. self.act_local_rotation(node, "hadamard")
  113. else:
  114. self.act_local_rotation(node, "hadamard")
  115. return res
  116. def measure_x(self, i):
  117. """ Measure the graph in the X-basis """
  118. # TODO
  119. pass
  120. def measure_y(self, i):
  121. """ Measure the graph in the Y-basis """
  122. # TODO
  123. pass
  124. def order(self):
  125. """ Get the number of qubits """
  126. return len(self.node)
  127. def __str__(self):
  128. """ Represent as a string for quick debugging """
  129. node = {key: clifford.get_name(value["vop"])
  130. for key, value in self.node.items()}
  131. nbstr = str(self.adj)
  132. return "graph:\n node: {}\n adj: {}\n".format(node, nbstr)
  133. def to_json(self):
  134. """ Convert the graph to JSON form """
  135. return {"node": self.node, "adj": self.adj}
  136. def from_json(self, data):
  137. """ Reconstruct from JSON """
  138. self.__init__([])
  139. #TODO
  140. def to_state_vector(self):
  141. """ Get the full state vector """
  142. if len(self.node) > 15:
  143. raise ValueError("Cannot build state vector: too many qubits")
  144. state = qi.CircuitModel(len(self.node))
  145. for i in range(len(self.node)):
  146. state.act_hadamard(i)
  147. for i, j in self.edgelist():
  148. state.act_cz(i, j)
  149. for i, n in self.node.items():
  150. state.act_local_rotation(i, clifford.unitaries[n["vop"]])
  151. return state
  152. def to_stabilizer(self):
  153. """ Get the stabilizer of this graph """
  154. output = {a:{} for a in self.node}
  155. for a, b in it.product(self.node, self.node):
  156. if a == b:
  157. output[a][b] = "X"
  158. elif a in self.adj[b]:
  159. output[a][b] = "Z"
  160. else:
  161. output[a][b] = "I"
  162. return output
  163. def adj_list(self):
  164. """ For comparison with Anders and Briegel's C++ implementation """
  165. rows = []
  166. for key, node in self.node.items():
  167. adj = " ".join(map(str, sorted(self.adj[key])))
  168. vop = clifford.get_name(node["vop"])
  169. s = "Vertex {}: VOp {}, neighbors {}".format(key, vop, adj)
  170. rows.append(s)
  171. return " \n".join(rows) + " \n"
  172. def __eq__(self, other):
  173. """ Check equality between graphs """
  174. return self.adj == other.adj and self.node == other.node