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.

239 lines
8.0KB

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