Anders and Briegel in Python
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

237 рядки
8.1KB

  1. """
  2. This program computes lookup tables and stores them as tables.py and tables.js
  3. # TODO: clifford naming discrepancy
  4. """
  5. import numpy as np
  6. from tqdm import tqdm
  7. import itertools as it
  8. from functools import reduce
  9. from os.path import dirname, join, split
  10. import json
  11. import qi, clifford
  12. DECOMPOSITIONS = (
  13. "xxxx", "xx", "zzxx", "zz", "zxx", "z", "zzz", "xxz", "xzx", "xzxxx", "xzzzx",
  14. "xxxzx", "xzz", "zzx", "xxx", "x", "zzzx", "xxzx", "zx", "zxxx", "xxxz", "xzzz", "xz", "xzxx")
  15. JS_TEMPLATE = """\
  16. var tables = {{
  17. decompositions : {decompositions},
  18. conjugation_table : {conjugation_table},
  19. times_table : {times_table},
  20. cz_table : {cz_table},
  21. clifford : {by_name},
  22. measurement_table: {measurement_table}
  23. }};
  24. """
  25. PY_TEMPLATE = """\
  26. import numpy as np
  27. # Define lookup tables
  28. ir2 = 1/np.sqrt(2)
  29. decompositions = {decompositions}
  30. conjugation_table = np.array({conjugation_table}, dtype=int)
  31. times_table = np.array({times_table}, dtype=int)
  32. cz_table = np.array({cz_table}, dtype=int)
  33. by_name = {by_name}
  34. measurement_table = np.array({measurement_table}, dtype=int)
  35. unitaries_real = np.array({unitaries_real}, dtype=complex)
  36. unitaries_imag = np.array({unitaries_imag}, dtype=complex)
  37. # Reconstruct
  38. unitaries = unitaries_real + 1j*unitaries_imag
  39. """
  40. def find_clifford(needle, haystack):
  41. """ Find the index of a given u within a list of unitaries, up to a global phase """
  42. needle = qi.normalize_global_phase(needle)
  43. for i, t in enumerate(haystack):
  44. if np.allclose(t, needle):
  45. return i
  46. raise IndexError
  47. def find_cz(bond, c1, c2, commuters, state_table):
  48. """ Find the output of a CZ operation """
  49. # Figure out the target state
  50. target = qi.cz.dot(state_table[bond, c1, c2])
  51. target = qi.normalize_global_phase(target)
  52. # Choose the sets to search over
  53. s1 = commuters if c1 in commuters else xrange(24)
  54. s2 = commuters if c2 in commuters else xrange(24)
  55. # Find a match
  56. for bondp, c1p, c2p in it.product([0, 1], s1, s2):
  57. if np.allclose(target, state_table[bondp, c1p, c2p]):
  58. return bondp, c1p, c2p
  59. # Didn't find anything - this should never happen
  60. raise IndexError
  61. def compose_u(decomposition):
  62. """ Get the unitary representation of a particular decomposition """
  63. matrices = ({"x": qi.msqx, "z": qi.sqz}[c] for c in decomposition)
  64. output = reduce(np.dot, matrices, np.eye(2, dtype=complex))
  65. return qi.normalize_global_phase(output)
  66. def get_unitaries():
  67. """ The Clifford group """
  68. return [compose_u(d) for d in DECOMPOSITIONS]
  69. def get_by_name(unitaries, conjugation_table):
  70. """ Get a lookup table of cliffords by name """
  71. a = {name: find_clifford(u, unitaries)
  72. for name, u in qi.by_name.items()}
  73. a.update({key+"_h": conjugation_table[value] for key, value in a.items()})
  74. a.update({clifford.get_name(i): i for i in range(24)})
  75. a.update({i: i for i in range(24)})
  76. return a
  77. def get_conjugation_table(unitaries):
  78. """ Construct the conjugation table """
  79. return np.array([find_clifford(qi.hermitian_conjugate(u), unitaries) for u in unitaries], dtype=int)
  80. def get_times_table(unitaries):
  81. """ Construct the times-table """
  82. return np.array([[find_clifford(u.dot(v), unitaries) for v in unitaries]
  83. for u in tqdm(unitaries, desc="Building times-table")], dtype=int)
  84. def get_state_table(unitaries):
  85. """ Cache a table of state to speed up a little bit """
  86. state_table = np.zeros((2, 24, 24, 4), dtype=complex)
  87. params = list(it.product([0, 1], range(24), range(24)))
  88. for bond, i, j in tqdm(params, desc="Building state table"):
  89. state = qi.bond if bond else qi.nobond
  90. kp = np.kron(unitaries[i], unitaries[j])
  91. state_table[bond, i, j, :] = qi.normalize_global_phase(
  92. np.dot(kp, state).T)
  93. return state_table
  94. def get_measurement_entry(operator, unitary):
  95. """
  96. Any Clifford group unitary will map an operator A in {I, X, Y, Z}
  97. to an operator B in +-{I, X, Y, Z}. This finds that mapping.
  98. """
  99. matrices = ({"x": qi.msqx, "z": qi.sqz}[c]
  100. for c in DECOMPOSITIONS[unitary])
  101. unitary = reduce(np.dot, matrices, np.eye(2, dtype=complex))
  102. operator = qi.operators[operator]
  103. new_operator = reduce(np.dot,
  104. (unitary, operator, qi.hermitian_conjugate(unitary)))
  105. for i, o in enumerate(qi.operators):
  106. if np.allclose(o, new_operator):
  107. return i, 1
  108. elif np.allclose(o, -new_operator):
  109. return i, -1
  110. raise IndexError
  111. def get_measurement_table():
  112. """
  113. Compute a table of transform * operation * transform^dagger
  114. This is pretty unintelligible right now, we should probably compute the phase from unitaries instead
  115. """
  116. measurement_table = np.zeros((4, 24, 2), dtype=int)
  117. for operator, unitary in it.product(range(4), range(24)):
  118. measurement_table[operator, unitary] = get_measurement_entry(
  119. operator, unitary)
  120. return measurement_table
  121. def get_commuters(unitaries):
  122. """ Get the indeces of gates which commute with CZ """
  123. commuters = (qi.id, qi.pz, qi.ph, qi.hermitian_conjugate(qi.ph))
  124. return [find_clifford(u, unitaries) for u in commuters]
  125. def get_cz_table(unitaries):
  126. """ Compute the lookup table for the CZ (A&B eq. 9) """
  127. # Get a cached state table and a list of gates which commute with CZ
  128. commuters = get_commuters(unitaries)
  129. state_table = get_state_table(unitaries)
  130. # And now build the CZ table
  131. cz_table = np.zeros((2, 24, 24, 3), dtype=int)
  132. rows = list(
  133. it.product([0, 1], it.combinations_with_replacement(range(24), 2)))
  134. # CZ is symmetric so we only need combinations
  135. for bond, (c1, c2) in tqdm(rows, desc="Building CZ table"):
  136. newbond, c1p, c2p = find_cz(
  137. bond, c1, c2, commuters, state_table)
  138. cz_table[bond, c1, c2] = [newbond, c1p, c2p]
  139. cz_table[bond, c2, c1] = [newbond, c2p, c1p]
  140. return cz_table
  141. def get_display_table(unitaries):
  142. """ Used to display VOPs in a human readable style """
  143. for u in unitaries:
  144. c = qi.CircuitModel(1)
  145. c.act_local_rotation(0, u)
  146. state = c.state.round(2)
  147. print "{:.2f}, {:.2f}".format(state[0][0], state[1][0])
  148. def compute_everything():
  149. """ Compute all lookup tables """
  150. unitaries = get_unitaries()
  151. conjugation_table = get_conjugation_table(unitaries)
  152. return {"decompositions": DECOMPOSITIONS,
  153. "unitaries": unitaries,
  154. "by_name": get_by_name(unitaries, conjugation_table),
  155. "conjugation_table": conjugation_table,
  156. "times_table": get_times_table(unitaries),
  157. "cz_table": get_cz_table(unitaries),
  158. "measurement_table": get_measurement_table()}
  159. def human_readable(data):
  160. """ Format the data """
  161. unitaries = np.array(data["unitaries"])
  162. return {"decompositions": json.dumps(DECOMPOSITIONS),
  163. "unitaries_real": json.dumps(unitaries.real.round(5).tolist()).replace("0.70711", "ir2"),
  164. "unitaries_imag": json.dumps(unitaries.imag.round(5).tolist()).replace("0.70711", "ir2"),
  165. "conjugation_table": json.dumps(data["conjugation_table"].tolist()),
  166. "times_table": json.dumps(data["times_table"].tolist()),
  167. "cz_table": json.dumps(data["cz_table"].tolist()),
  168. "by_name": json.dumps(data["by_name"]),
  169. "measurement_table": json.dumps(data["measurement_table"].tolist())}
  170. def write_python(data):
  171. """ Write the tables to a python module """
  172. path = join(dirname(__file__), "tables.py")
  173. content = PY_TEMPLATE.format(**data)
  174. with open(path, "w") as f:
  175. f.write(content)
  176. def write_javascript(data):
  177. """ Write the tables to javascript files for consumption in the browser """
  178. path = join(split(dirname(__file__))[0], "static/scripts/tables.js")
  179. content = JS_TEMPLATE.format(**data)
  180. with open(path, "w") as f:
  181. f.write(content)
  182. if __name__ == '__main__':
  183. get_display_table(get_unitaries())
  184. #data = compute_everything()
  185. #data = human_readable(data)
  186. #write_python(data)
  187. #write_javascript(data)