gate.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import numpy as np
  2. class Gate:
  3. def __init__(self, gate):
  4. gate = np.array(gate)
  5. if gate.shape != (2, 2):
  6. raise ValueError(
  7. "Gate is not a 2x2 matrix. " +
  8. "For larger gates, please decompose into 2x2 matrices " +
  9. "and/or use the controlled gate functionality."
  10. )
  11. # Check the gate is unitary
  12. if (not np.allclose(np.eye(gate.shape[0]), np.dot(gate.conjugate().transpose(), gate))):
  13. raise ValueError("gate is not unitary.")
  14. self.a = complex(gate[0, 0])
  15. self.b = complex(gate[0, 1])
  16. self.c = complex(gate[1, 0])
  17. self.d = complex(gate[1, 1])
  18. def __repr__(self):
  19. return '[{:.4f}, {:.4f}]\n[{:.4f}, {:.4f}]'.format(self.a, self.b, self.c, self.d)
  20. def h():
  21. return Gate(np.array([[1, 1], [1, -1]]) / np.sqrt(2))
  22. def x():
  23. return Gate(np.array([[0, 1], [1, 0]]))
  24. def y():
  25. return Gate(np.array([[0, -1j], [1j, 0]]))
  26. def z():
  27. return Gate(np.array([[1, 0], [0, -1]]))
  28. def s():
  29. return Gate(np.array([[1, 0], [0, 1j]]))
  30. def t():
  31. return Gate(np.array([[1, 0], [0, np.exp(np.pi * 1j / 4)]]))
  32. def sqrt_x():
  33. return Gate(0.5 * np.array([[1+1j, 1-1j], [1-1j, 1+1j]]))