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.

228 lines
7.7KB

  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 compute_everything():
  142. """ Compute all lookup tables """
  143. unitaries = get_unitaries()
  144. conjugation_table = get_conjugation_table(unitaries)
  145. return {"decompositions": DECOMPOSITIONS,
  146. "unitaries": unitaries,
  147. "by_name": get_by_name(unitaries, conjugation_table),
  148. "conjugation_table": conjugation_table,
  149. "times_table": get_times_table(unitaries),
  150. "cz_table": get_cz_table(unitaries),
  151. "measurement_table": get_measurement_table()}
  152. def human_readable(data):
  153. """ Format the data """
  154. unitaries = np.array(data["unitaries"])
  155. return {"decompositions": json.dumps(DECOMPOSITIONS),
  156. "unitaries_real": json.dumps(unitaries.real.round(5).tolist()).replace("0.70711", "ir2"),
  157. "unitaries_imag": json.dumps(unitaries.imag.round(5).tolist()).replace("0.70711", "ir2"),
  158. "conjugation_table": json.dumps(data["conjugation_table"].tolist()),
  159. "times_table": json.dumps(data["times_table"].tolist()),
  160. "cz_table": json.dumps(data["cz_table"].tolist()),
  161. "by_name": json.dumps(data["by_name"]),
  162. "measurement_table": json.dumps(data["measurement_table"].tolist())}
  163. def write_python(data):
  164. """ Write the tables to a python module """
  165. path = join(dirname(__file__), "tables.py")
  166. content = PY_TEMPLATE.format(**data)
  167. with open(path, "w") as f:
  168. f.write(content)
  169. def write_javascript(data):
  170. """ Write the tables to javascript files for consumption in the browser """
  171. path = join(split(dirname(__file__))[0], "static/scripts/tables.js")
  172. content = JS_TEMPLATE.format(**data)
  173. with open(path, "w") as f:
  174. f.write(content)
  175. if __name__ == '__main__':
  176. data = compute_everything()
  177. data = human_readable(data)
  178. write_python(data)
  179. write_javascript(data)