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.

196 lines
6.2KB

  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. class GraphState(object):
  8. def __init__(self, nodes=[]):
  9. self.adj, self.node = {}, {}
  10. self.add_nodes(nodes)
  11. def add_node(self, v, **kwargs):
  12. """ Add a node """
  13. assert not v in self.node
  14. self.adj[v] = {}
  15. self.node[v] = {"vop": clifford.by_name["hadamard"]}
  16. self.node[v].update(kwargs)
  17. def add_nodes(self, nodes):
  18. """ Add a buncha nodes """
  19. for n in nodes:
  20. self.add_node(n)
  21. def add_edge(self, v1, v2, data = {}):
  22. """ Add an edge between two vertices in the self """
  23. assert v1 != v2
  24. self.adj[v1][v2] = data
  25. self.adj[v2][v1] = data
  26. def add_edges(self, edges):
  27. """ Add a buncha edges """
  28. for (v1, v2) in edges:
  29. self.add_edge(v1, v2)
  30. def del_edge(self, v1, v2):
  31. """ Delete an edge between two vertices in the self """
  32. del self.adj[v1][v2]
  33. del self.adj[v2][v1]
  34. def has_edge(self, v1, v2):
  35. """ Test existence of an edge between two vertices in the self """
  36. return v2 in self.adj[v1]
  37. def toggle_edge(self, v1, v2):
  38. """ Toggle an edge between two vertices in the self """
  39. if self.has_edge(v1, v2):
  40. self.del_edge(v1, v2)
  41. else:
  42. self.add_edge(v1, v2)
  43. def edgelist(self):
  44. """ Describe a graph as an edgelist """
  45. # TODO: inefficient
  46. edges = set(tuple(sorted((i, n)))
  47. for i, v in self.adj.items()
  48. for n in v)
  49. return tuple(edges)
  50. def remove_vop(self, a, avoid):
  51. """ Reduces VOP[a] to the identity """
  52. #TODO: inefficient
  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. self.local_complementation(a if v == "x" else swap_qubit)
  57. def local_complementation(self, v):
  58. """ As defined in LISTING 1 of Anders & Briegel """
  59. for i, j in it.combinations(self.adj[v], 2):
  60. self.toggle_edge(i, j)
  61. msqx_h = clifford.conjugation_table[clifford.by_name["msqx"]]
  62. sqz_h = clifford.conjugation_table[clifford.by_name["sqz"]]
  63. self.node[v]["vop"] = clifford.times_table[self.node[v]["vop"], msqx_h]
  64. for i in self.adj[v]:
  65. self.node[i]["vop"] = clifford.times_table[self.node[i]["vop"], sqz_h]
  66. def act_local_rotation(self, v, op):
  67. """ Act a local rotation """
  68. rotation = clifford.by_name[str(op)]
  69. self.node[v]["vop"] = clifford.times_table[rotation, self.node[v]["vop"]]
  70. def act_hadamard(self, qubit):
  71. """ Shorthand """
  72. self.act_local_rotation(qubit, 10)
  73. def act_cz(self, a, b):
  74. """ Act a controlled-phase gate on two qubits """
  75. #TODO: inefficient
  76. if set(self.adj[a]) - {b}:
  77. self.remove_vop(a, b)
  78. if set(self.adj[b]) - {a}:
  79. self.remove_vop(b, a)
  80. if set(self.adj[a]) - {b}:
  81. self.remove_vop(a, b)
  82. edge = int(self.has_edge(a, b))
  83. new_edge, self.node[a]["vop"], self.node[
  84. b]["vop"] = clifford.cz_table[edge, self.node[a]["vop"], self.node[b]["vop"]]
  85. if new_edge != edge:
  86. self.toggle_edge(a, b)
  87. def measure_z(self, node, force=None):
  88. """ Measure the graph in the Z-basis """
  89. res = force if force else np.random.choice([0, 1])
  90. # Disconnect
  91. for neighbour in self.adj[node]:
  92. self.del_edge(node, neighbour)
  93. if res:
  94. self.act_local_rotation(neighbour, "pz")
  95. # Rotate
  96. if res:
  97. self.act_local_rotation(node, "px")
  98. self.act_local_rotation(node, "hadamard")
  99. else:
  100. self.act_local_rotation(node, "hadamard")
  101. return res
  102. def measure_x(self, i):
  103. """ Measure the graph in the X-basis """
  104. # TODO
  105. pass
  106. def measure_y(self, i):
  107. """ Measure the graph in the Y-basis """
  108. # TODO
  109. pass
  110. def order(self):
  111. """ Get the number of qubits """
  112. return len(self.node)
  113. def __str__(self):
  114. """ Represent as a string for quick debugging """
  115. node = {key: clifford.get_name(value["vop"])
  116. for key, value in self.node.items()}
  117. nbstr = str(self.adj)
  118. return "graph:\n node: {}\n adj: {}\n".format(node, nbstr)
  119. def to_json(self):
  120. """ Convert the graph to JSON form """
  121. return {"node": self.node, "adj": self.adj}
  122. def from_json(self, data):
  123. """ Reconstruct from JSON """
  124. self.__init__([])
  125. #TODO
  126. def to_state_vector(self):
  127. """ Get the full state vector """
  128. if len(self.node) > 15:
  129. raise ValueError("Cannot build state vector: too many qubits")
  130. state = qi.CircuitModel(len(self.node))
  131. for i in range(len(self.node)):
  132. state.act_hadamard(i)
  133. for i, j in self.edgelist():
  134. state.act_cz(i, j)
  135. for i, n in self.node.items():
  136. state.act_local_rotation(i, clifford.unitaries[n["vop"]])
  137. return state
  138. def to_stabilizer(self):
  139. """ Get the stabilizer of this graph """
  140. # TODO: VOPs are not implemented yet
  141. output = ""
  142. for a in self.adj:
  143. for b in self.adj:
  144. if a == b:
  145. output += " X "
  146. elif a in self.adj[b]:
  147. output += " Z "
  148. else:
  149. output += " I "
  150. output += "\n"
  151. return output
  152. def adj_list(self):
  153. """ For comparison with Anders and Briegel's C++ implementation """
  154. rows = []
  155. for key, node in self.node.items():
  156. adj = " ".join(map(str, sorted(self.adj[key])))
  157. vop = clifford.get_name(node["vop"])
  158. s = "Vertex {}: VOp {}, neighbors {}".format(key, vop, adj)
  159. rows.append(s)
  160. return " \n".join(rows) + " \n"
  161. def __eq__(self, other):
  162. """ Check equality between graphs """
  163. return self.adj == other.adj and self.node == other.node