Anders and Briegel in Python
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

201 lines
6.3KB

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