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.

230 lines
7.9KB

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