gate.py 987 B

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