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.

215 lines
7.5KB

  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(vop, transform):
  15. """ Returns transform * vop * transform^dagger and a phase in {+1, -1} """
  16. return measurement_table[vop, transform]
  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_table():
  78. """
  79. Compute a table of transform * operation * transform^dagger
  80. This is pretty unintelligible right now, we should probably compute the phase from unitaries instead
  81. """
  82. measurement_table = np.zeros((4, 24, 2), dtype=complex)
  83. for vop, transform in it.product(range(4), range(24)):
  84. assert vop in set(xrange(4))
  85. op = times_table[transform, vop]
  86. op = times_table[op, conjugation_table[transform]]
  87. is_id_or_vop = (transform % 4 == 0) or (transform % 4 == vop)
  88. is_non_pauli = (transform >= 4) and (transform <= 15)
  89. phase = ((-1, 1), (1, -1))[is_id_or_vop][is_non_pauli]
  90. if vop == 0:
  91. phase = 1
  92. measurement_table[vop, transform] = [op, phase]
  93. return measurement_table
  94. def get_commuters(unitaries):
  95. """ Get the indeces of gates which commute with CZ """
  96. commuters = (qi.id, qi.pz, qi.ph, qi.hermitian_conjugate(qi.ph))
  97. return [find_clifford(u, unitaries) for u in commuters]
  98. def get_cz_table(unitaries):
  99. """ Compute the lookup table for the CZ (A&B eq. 9) """
  100. # Get a cached state table and a list of gates which commute with CZ
  101. commuters = get_commuters(unitaries)
  102. state_table = get_state_table(unitaries)
  103. # And now build the CZ table
  104. cz_table = np.zeros((2, 24, 24, 3), dtype=int)
  105. rows = list(
  106. it.product([0, 1], it.combinations_with_replacement(range(24), 2)))
  107. # CZ is symmetric so we only need combinations
  108. for bond, (c1, c2) in tqdm(rows, desc="Building CZ table"):
  109. newbond, c1p, c2p = find_cz(
  110. bond, c1, c2, commuters, state_table)
  111. cz_table[bond, c1, c2] = [newbond, c1p, c2p]
  112. cz_table[bond, c2, c1] = [newbond, c2p, c1p]
  113. return cz_table
  114. def write_javascript_tables():
  115. """ Write the tables to javascript files for consumption in the browser """
  116. path = os.path.dirname(sys.argv[0])
  117. path = os.path.split(path)[0]
  118. with open(os.path.join(path, "static/scripts/tables.js"), "w") as f:
  119. f.write("var tables = {\n");
  120. f.write("\tdecompositions : {},\n"\
  121. .format(json.dumps(decompositions)))
  122. f.write("\tconjugation_table : {},\n"\
  123. .format(json.dumps(conjugation_table.tolist())))
  124. f.write("\ttimes_table : {},\n"\
  125. .format(json.dumps(times_table.tolist())))
  126. f.write("\tcz_table : {},\n"\
  127. .format(json.dumps(cz_table.tolist())))
  128. f.write("\tclifford : {}\n"\
  129. .format(json.dumps(by_name)))
  130. f.write("};");
  131. def temp(filename):
  132. """ Get a temporary path """
  133. tempdir = tempfile.gettempdir()
  134. return os.path.join(tempdir, filename)
  135. def compute_everything():
  136. """ Compute all lookup tables """
  137. global unitaries, by_name, conjugation_table, times_table, cz_table, measurement_table
  138. unitaries = get_unitaries()
  139. by_name = get_by_name(unitaries)
  140. conjugation_table = get_conjugation_table(unitaries)
  141. times_table = get_times_table(unitaries)
  142. cz_table = get_cz_table(unitaries)
  143. measurement_table = get_measurement_table()
  144. def save_to_disk():
  145. """ Save all tables to disk """
  146. global unitaries, by_name, conjugation_table, times_table, cz_table, measurement_table
  147. np.save(temp("unitaries.npy"), unitaries)
  148. np.save(temp("conjugation_table.npy"), conjugation_table)
  149. np.save(temp("times_table.npy"), times_table)
  150. np.save(temp("cz_table.npy"), cz_table)
  151. np.save(temp("measurement_table.npy"), measurement_table)
  152. write_javascript_tables()
  153. with open(temp("by_name.json"), "wb") as f:
  154. json.dump(by_name, f)
  155. def load_from_disk():
  156. """ Load all the tables from disk """
  157. global unitaries, by_name, conjugation_table, times_table, cz_table, measurement_table
  158. unitaries = np.load(temp("unitaries.npy"))
  159. conjugation_table = np.load(temp("conjugation_table.npy"))
  160. times_table = np.load(temp("times_table.npy"))
  161. measurement_table = np.load(temp("measurement_table.npy"))
  162. cz_table = np.load(temp("cz_table.npy"))
  163. with open(temp("by_name.json")) as f:
  164. by_name = json.load(f)
  165. if __name__ == "__main__":
  166. compute_everything()
  167. save_to_disk()
  168. else:
  169. try:
  170. load_from_disk()
  171. except IOError:
  172. compute_everything()
  173. save_to_disk()