state.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from backend import Backend
  2. import pyopencl as cl
  3. import numpy as np
  4. class State:
  5. """Represents the state of a quantum register"""
  6. def __init__(self, num_qubits):
  7. if not isinstance(num_qubits, int):
  8. raise ValueError("num_qubits must be an int")
  9. if num_qubits <= 0:
  10. raise ValueError("num_qubits must be a positive integer")
  11. self.num_qubits = num_qubits
  12. self.backend = Backend(num_qubits)
  13. def apply_gate(self, gate, target):
  14. if not isinstance(target, int) or target < 0:
  15. raise ValueError("target must be an int > 0")
  16. # TODO: Check that gate is correct
  17. self.backend.apply_gate(gate, target)
  18. def apply_all(self, gate):
  19. # TODO: Check that gate is correct
  20. for i in range(self.num_qubits):
  21. self.apply_gate(gate, i)
  22. def apply_controlled_gate(self, gate, control, target):
  23. if not isinstance(target, int) or target < 0:
  24. raise ValueError("target must be an int > 0")
  25. if not isinstance(control, int) or control < 0:
  26. raise ValueError("control must be an int > 0")
  27. # TODO: Check that gate is correct
  28. self.backend.apply_controlled_gate(gate, control, target)
  29. def amplitudes(self):
  30. return self.backend.amplitudes()
  31. def probabilities(self):
  32. return self.backend.probabilities()
  33. def __repr__(self):
  34. """A string representation of the state"""
  35. # TODO: Finish this method
  36. return np.array_str(self.backend.buffer)