gate.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. """An implementation of gates that act on qubits.
  2. Gates are unitary operators that act on the space of qubits.
  3. Medium Term Todo:
  4. * Optimize Gate._apply_operators_Qubit to remove the creation of many
  5. intermediate Qubit objects.
  6. * Add commutation relationships to all operators and use this in gate_sort.
  7. * Fix gate_sort and gate_simp.
  8. * Get multi-target UGates plotting properly.
  9. * Get UGate to work with either sympy/numpy matrices and output either
  10. format. This should also use the matrix slots.
  11. """
  12. from itertools import chain
  13. import random
  14. from sympy.core.add import Add
  15. from sympy.core.containers import Tuple
  16. from sympy.core.mul import Mul
  17. from sympy.core.numbers import (I, Integer)
  18. from sympy.core.power import Pow
  19. from sympy.core.numbers import Number
  20. from sympy.core.singleton import S as _S
  21. from sympy.core.sorting import default_sort_key
  22. from sympy.core.sympify import _sympify
  23. from sympy.functions.elementary.miscellaneous import sqrt
  24. from sympy.printing.pretty.stringpict import prettyForm, stringPict
  25. from sympy.physics.quantum.anticommutator import AntiCommutator
  26. from sympy.physics.quantum.commutator import Commutator
  27. from sympy.physics.quantum.qexpr import QuantumError
  28. from sympy.physics.quantum.hilbert import ComplexSpace
  29. from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
  30. HermitianOperator)
  31. from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
  32. from sympy.physics.quantum.matrixcache import matrix_cache
  33. from sympy.matrices.matrices import MatrixBase
  34. from sympy.utilities.iterables import is_sequence
  35. __all__ = [
  36. 'Gate',
  37. 'CGate',
  38. 'UGate',
  39. 'OneQubitGate',
  40. 'TwoQubitGate',
  41. 'IdentityGate',
  42. 'HadamardGate',
  43. 'XGate',
  44. 'YGate',
  45. 'ZGate',
  46. 'TGate',
  47. 'PhaseGate',
  48. 'SwapGate',
  49. 'CNotGate',
  50. # Aliased gate names
  51. 'CNOT',
  52. 'SWAP',
  53. 'H',
  54. 'X',
  55. 'Y',
  56. 'Z',
  57. 'T',
  58. 'S',
  59. 'Phase',
  60. 'normalized',
  61. 'gate_sort',
  62. 'gate_simp',
  63. 'random_circuit',
  64. 'CPHASE',
  65. 'CGateS',
  66. ]
  67. #-----------------------------------------------------------------------------
  68. # Gate Super-Classes
  69. #-----------------------------------------------------------------------------
  70. _normalized = True
  71. def _max(*args, **kwargs):
  72. if "key" not in kwargs:
  73. kwargs["key"] = default_sort_key
  74. return max(*args, **kwargs)
  75. def _min(*args, **kwargs):
  76. if "key" not in kwargs:
  77. kwargs["key"] = default_sort_key
  78. return min(*args, **kwargs)
  79. def normalized(normalize):
  80. r"""Set flag controlling normalization of Hadamard gates by `1/\sqrt{2}`.
  81. This is a global setting that can be used to simplify the look of various
  82. expressions, by leaving off the leading `1/\sqrt{2}` of the Hadamard gate.
  83. Parameters
  84. ----------
  85. normalize : bool
  86. Should the Hadamard gate include the `1/\sqrt{2}` normalization factor?
  87. When True, the Hadamard gate will have the `1/\sqrt{2}`. When False, the
  88. Hadamard gate will not have this factor.
  89. """
  90. global _normalized
  91. _normalized = normalize
  92. def _validate_targets_controls(tandc):
  93. tandc = list(tandc)
  94. # Check for integers
  95. for bit in tandc:
  96. if not bit.is_Integer and not bit.is_Symbol:
  97. raise TypeError('Integer expected, got: %r' % tandc[bit])
  98. # Detect duplicates
  99. if len(set(tandc)) != len(tandc):
  100. raise QuantumError(
  101. 'Target/control qubits in a gate cannot be duplicated'
  102. )
  103. class Gate(UnitaryOperator):
  104. """Non-controlled unitary gate operator that acts on qubits.
  105. This is a general abstract gate that needs to be subclassed to do anything
  106. useful.
  107. Parameters
  108. ----------
  109. label : tuple, int
  110. A list of the target qubits (as ints) that the gate will apply to.
  111. Examples
  112. ========
  113. """
  114. _label_separator = ','
  115. gate_name = 'G'
  116. gate_name_latex = 'G'
  117. #-------------------------------------------------------------------------
  118. # Initialization/creation
  119. #-------------------------------------------------------------------------
  120. @classmethod
  121. def _eval_args(cls, args):
  122. args = Tuple(*UnitaryOperator._eval_args(args))
  123. _validate_targets_controls(args)
  124. return args
  125. @classmethod
  126. def _eval_hilbert_space(cls, args):
  127. """This returns the smallest possible Hilbert space."""
  128. return ComplexSpace(2)**(_max(args) + 1)
  129. #-------------------------------------------------------------------------
  130. # Properties
  131. #-------------------------------------------------------------------------
  132. @property
  133. def nqubits(self):
  134. """The total number of qubits this gate acts on.
  135. For controlled gate subclasses this includes both target and control
  136. qubits, so that, for examples the CNOT gate acts on 2 qubits.
  137. """
  138. return len(self.targets)
  139. @property
  140. def min_qubits(self):
  141. """The minimum number of qubits this gate needs to act on."""
  142. return _max(self.targets) + 1
  143. @property
  144. def targets(self):
  145. """A tuple of target qubits."""
  146. return self.label
  147. @property
  148. def gate_name_plot(self):
  149. return r'$%s$' % self.gate_name_latex
  150. #-------------------------------------------------------------------------
  151. # Gate methods
  152. #-------------------------------------------------------------------------
  153. def get_target_matrix(self, format='sympy'):
  154. """The matrix representation of the target part of the gate.
  155. Parameters
  156. ----------
  157. format : str
  158. The format string ('sympy','numpy', etc.)
  159. """
  160. raise NotImplementedError(
  161. 'get_target_matrix is not implemented in Gate.')
  162. #-------------------------------------------------------------------------
  163. # Apply
  164. #-------------------------------------------------------------------------
  165. def _apply_operator_IntQubit(self, qubits, **options):
  166. """Redirect an apply from IntQubit to Qubit"""
  167. return self._apply_operator_Qubit(qubits, **options)
  168. def _apply_operator_Qubit(self, qubits, **options):
  169. """Apply this gate to a Qubit."""
  170. # Check number of qubits this gate acts on.
  171. if qubits.nqubits < self.min_qubits:
  172. raise QuantumError(
  173. 'Gate needs a minimum of %r qubits to act on, got: %r' %
  174. (self.min_qubits, qubits.nqubits)
  175. )
  176. # If the controls are not met, just return
  177. if isinstance(self, CGate):
  178. if not self.eval_controls(qubits):
  179. return qubits
  180. targets = self.targets
  181. target_matrix = self.get_target_matrix(format='sympy')
  182. # Find which column of the target matrix this applies to.
  183. column_index = 0
  184. n = 1
  185. for target in targets:
  186. column_index += n*qubits[target]
  187. n = n << 1
  188. column = target_matrix[:, int(column_index)]
  189. # Now apply each column element to the qubit.
  190. result = 0
  191. for index in range(column.rows):
  192. # TODO: This can be optimized to reduce the number of Qubit
  193. # creations. We should simply manipulate the raw list of qubit
  194. # values and then build the new Qubit object once.
  195. # Make a copy of the incoming qubits.
  196. new_qubit = qubits.__class__(*qubits.args)
  197. # Flip the bits that need to be flipped.
  198. for bit, target in enumerate(targets):
  199. if new_qubit[target] != (index >> bit) & 1:
  200. new_qubit = new_qubit.flip(target)
  201. # The value in that row and column times the flipped-bit qubit
  202. # is the result for that part.
  203. result += column[index]*new_qubit
  204. return result
  205. #-------------------------------------------------------------------------
  206. # Represent
  207. #-------------------------------------------------------------------------
  208. def _represent_default_basis(self, **options):
  209. return self._represent_ZGate(None, **options)
  210. def _represent_ZGate(self, basis, **options):
  211. format = options.get('format', 'sympy')
  212. nqubits = options.get('nqubits', 0)
  213. if nqubits == 0:
  214. raise QuantumError(
  215. 'The number of qubits must be given as nqubits.')
  216. # Make sure we have enough qubits for the gate.
  217. if nqubits < self.min_qubits:
  218. raise QuantumError(
  219. 'The number of qubits %r is too small for the gate.' % nqubits
  220. )
  221. target_matrix = self.get_target_matrix(format)
  222. targets = self.targets
  223. if isinstance(self, CGate):
  224. controls = self.controls
  225. else:
  226. controls = []
  227. m = represent_zbasis(
  228. controls, targets, target_matrix, nqubits, format
  229. )
  230. return m
  231. #-------------------------------------------------------------------------
  232. # Print methods
  233. #-------------------------------------------------------------------------
  234. def _sympystr(self, printer, *args):
  235. label = self._print_label(printer, *args)
  236. return '%s(%s)' % (self.gate_name, label)
  237. def _pretty(self, printer, *args):
  238. a = stringPict(self.gate_name)
  239. b = self._print_label_pretty(printer, *args)
  240. return self._print_subscript_pretty(a, b)
  241. def _latex(self, printer, *args):
  242. label = self._print_label(printer, *args)
  243. return '%s_{%s}' % (self.gate_name_latex, label)
  244. def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
  245. raise NotImplementedError('plot_gate is not implemented.')
  246. class CGate(Gate):
  247. """A general unitary gate with control qubits.
  248. A general control gate applies a target gate to a set of targets if all
  249. of the control qubits have a particular values (set by
  250. ``CGate.control_value``).
  251. Parameters
  252. ----------
  253. label : tuple
  254. The label in this case has the form (controls, gate), where controls
  255. is a tuple/list of control qubits (as ints) and gate is a ``Gate``
  256. instance that is the target operator.
  257. Examples
  258. ========
  259. """
  260. gate_name = 'C'
  261. gate_name_latex = 'C'
  262. # The values this class controls for.
  263. control_value = _S.One
  264. simplify_cgate = False
  265. #-------------------------------------------------------------------------
  266. # Initialization
  267. #-------------------------------------------------------------------------
  268. @classmethod
  269. def _eval_args(cls, args):
  270. # _eval_args has the right logic for the controls argument.
  271. controls = args[0]
  272. gate = args[1]
  273. if not is_sequence(controls):
  274. controls = (controls,)
  275. controls = UnitaryOperator._eval_args(controls)
  276. _validate_targets_controls(chain(controls, gate.targets))
  277. return (Tuple(*controls), gate)
  278. @classmethod
  279. def _eval_hilbert_space(cls, args):
  280. """This returns the smallest possible Hilbert space."""
  281. return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
  282. #-------------------------------------------------------------------------
  283. # Properties
  284. #-------------------------------------------------------------------------
  285. @property
  286. def nqubits(self):
  287. """The total number of qubits this gate acts on.
  288. For controlled gate subclasses this includes both target and control
  289. qubits, so that, for examples the CNOT gate acts on 2 qubits.
  290. """
  291. return len(self.targets) + len(self.controls)
  292. @property
  293. def min_qubits(self):
  294. """The minimum number of qubits this gate needs to act on."""
  295. return _max(_max(self.controls), _max(self.targets)) + 1
  296. @property
  297. def targets(self):
  298. """A tuple of target qubits."""
  299. return self.gate.targets
  300. @property
  301. def controls(self):
  302. """A tuple of control qubits."""
  303. return tuple(self.label[0])
  304. @property
  305. def gate(self):
  306. """The non-controlled gate that will be applied to the targets."""
  307. return self.label[1]
  308. #-------------------------------------------------------------------------
  309. # Gate methods
  310. #-------------------------------------------------------------------------
  311. def get_target_matrix(self, format='sympy'):
  312. return self.gate.get_target_matrix(format)
  313. def eval_controls(self, qubit):
  314. """Return True/False to indicate if the controls are satisfied."""
  315. return all(qubit[bit] == self.control_value for bit in self.controls)
  316. def decompose(self, **options):
  317. """Decompose the controlled gate into CNOT and single qubits gates."""
  318. if len(self.controls) == 1:
  319. c = self.controls[0]
  320. t = self.gate.targets[0]
  321. if isinstance(self.gate, YGate):
  322. g1 = PhaseGate(t)
  323. g2 = CNotGate(c, t)
  324. g3 = PhaseGate(t)
  325. g4 = ZGate(t)
  326. return g1*g2*g3*g4
  327. if isinstance(self.gate, ZGate):
  328. g1 = HadamardGate(t)
  329. g2 = CNotGate(c, t)
  330. g3 = HadamardGate(t)
  331. return g1*g2*g3
  332. else:
  333. return self
  334. #-------------------------------------------------------------------------
  335. # Print methods
  336. #-------------------------------------------------------------------------
  337. def _print_label(self, printer, *args):
  338. controls = self._print_sequence(self.controls, ',', printer, *args)
  339. gate = printer._print(self.gate, *args)
  340. return '(%s),%s' % (controls, gate)
  341. def _pretty(self, printer, *args):
  342. controls = self._print_sequence_pretty(
  343. self.controls, ',', printer, *args)
  344. gate = printer._print(self.gate)
  345. gate_name = stringPict(self.gate_name)
  346. first = self._print_subscript_pretty(gate_name, controls)
  347. gate = self._print_parens_pretty(gate)
  348. final = prettyForm(*first.right(gate))
  349. return final
  350. def _latex(self, printer, *args):
  351. controls = self._print_sequence(self.controls, ',', printer, *args)
  352. gate = printer._print(self.gate, *args)
  353. return r'%s_{%s}{\left(%s\right)}' % \
  354. (self.gate_name_latex, controls, gate)
  355. def plot_gate(self, circ_plot, gate_idx):
  356. """
  357. Plot the controlled gate. If *simplify_cgate* is true, simplify
  358. C-X and C-Z gates into their more familiar forms.
  359. """
  360. min_wire = int(_min(chain(self.controls, self.targets)))
  361. max_wire = int(_max(chain(self.controls, self.targets)))
  362. circ_plot.control_line(gate_idx, min_wire, max_wire)
  363. for c in self.controls:
  364. circ_plot.control_point(gate_idx, int(c))
  365. if self.simplify_cgate:
  366. if self.gate.gate_name == 'X':
  367. self.gate.plot_gate_plus(circ_plot, gate_idx)
  368. elif self.gate.gate_name == 'Z':
  369. circ_plot.control_point(gate_idx, self.targets[0])
  370. else:
  371. self.gate.plot_gate(circ_plot, gate_idx)
  372. else:
  373. self.gate.plot_gate(circ_plot, gate_idx)
  374. #-------------------------------------------------------------------------
  375. # Miscellaneous
  376. #-------------------------------------------------------------------------
  377. def _eval_dagger(self):
  378. if isinstance(self.gate, HermitianOperator):
  379. return self
  380. else:
  381. return Gate._eval_dagger(self)
  382. def _eval_inverse(self):
  383. if isinstance(self.gate, HermitianOperator):
  384. return self
  385. else:
  386. return Gate._eval_inverse(self)
  387. def _eval_power(self, exp):
  388. if isinstance(self.gate, HermitianOperator):
  389. if exp == -1:
  390. return Gate._eval_power(self, exp)
  391. elif abs(exp) % 2 == 0:
  392. return self*(Gate._eval_inverse(self))
  393. else:
  394. return self
  395. else:
  396. return Gate._eval_power(self, exp)
  397. class CGateS(CGate):
  398. """Version of CGate that allows gate simplifications.
  399. I.e. cnot looks like an oplus, cphase has dots, etc.
  400. """
  401. simplify_cgate=True
  402. class UGate(Gate):
  403. """General gate specified by a set of targets and a target matrix.
  404. Parameters
  405. ----------
  406. label : tuple
  407. A tuple of the form (targets, U), where targets is a tuple of the
  408. target qubits and U is a unitary matrix with dimension of
  409. len(targets).
  410. """
  411. gate_name = 'U'
  412. gate_name_latex = 'U'
  413. #-------------------------------------------------------------------------
  414. # Initialization
  415. #-------------------------------------------------------------------------
  416. @classmethod
  417. def _eval_args(cls, args):
  418. targets = args[0]
  419. if not is_sequence(targets):
  420. targets = (targets,)
  421. targets = Gate._eval_args(targets)
  422. _validate_targets_controls(targets)
  423. mat = args[1]
  424. if not isinstance(mat, MatrixBase):
  425. raise TypeError('Matrix expected, got: %r' % mat)
  426. #make sure this matrix is of a Basic type
  427. mat = _sympify(mat)
  428. dim = 2**len(targets)
  429. if not all(dim == shape for shape in mat.shape):
  430. raise IndexError(
  431. 'Number of targets must match the matrix size: %r %r' %
  432. (targets, mat)
  433. )
  434. return (targets, mat)
  435. @classmethod
  436. def _eval_hilbert_space(cls, args):
  437. """This returns the smallest possible Hilbert space."""
  438. return ComplexSpace(2)**(_max(args[0]) + 1)
  439. #-------------------------------------------------------------------------
  440. # Properties
  441. #-------------------------------------------------------------------------
  442. @property
  443. def targets(self):
  444. """A tuple of target qubits."""
  445. return tuple(self.label[0])
  446. #-------------------------------------------------------------------------
  447. # Gate methods
  448. #-------------------------------------------------------------------------
  449. def get_target_matrix(self, format='sympy'):
  450. """The matrix rep. of the target part of the gate.
  451. Parameters
  452. ----------
  453. format : str
  454. The format string ('sympy','numpy', etc.)
  455. """
  456. return self.label[1]
  457. #-------------------------------------------------------------------------
  458. # Print methods
  459. #-------------------------------------------------------------------------
  460. def _pretty(self, printer, *args):
  461. targets = self._print_sequence_pretty(
  462. self.targets, ',', printer, *args)
  463. gate_name = stringPict(self.gate_name)
  464. return self._print_subscript_pretty(gate_name, targets)
  465. def _latex(self, printer, *args):
  466. targets = self._print_sequence(self.targets, ',', printer, *args)
  467. return r'%s_{%s}' % (self.gate_name_latex, targets)
  468. def plot_gate(self, circ_plot, gate_idx):
  469. circ_plot.one_qubit_box(
  470. self.gate_name_plot,
  471. gate_idx, int(self.targets[0])
  472. )
  473. class OneQubitGate(Gate):
  474. """A single qubit unitary gate base class."""
  475. nqubits = _S.One
  476. def plot_gate(self, circ_plot, gate_idx):
  477. circ_plot.one_qubit_box(
  478. self.gate_name_plot,
  479. gate_idx, int(self.targets[0])
  480. )
  481. def _eval_commutator(self, other, **hints):
  482. if isinstance(other, OneQubitGate):
  483. if self.targets != other.targets or self.__class__ == other.__class__:
  484. return _S.Zero
  485. return Operator._eval_commutator(self, other, **hints)
  486. def _eval_anticommutator(self, other, **hints):
  487. if isinstance(other, OneQubitGate):
  488. if self.targets != other.targets or self.__class__ == other.__class__:
  489. return Integer(2)*self*other
  490. return Operator._eval_anticommutator(self, other, **hints)
  491. class TwoQubitGate(Gate):
  492. """A two qubit unitary gate base class."""
  493. nqubits = Integer(2)
  494. #-----------------------------------------------------------------------------
  495. # Single Qubit Gates
  496. #-----------------------------------------------------------------------------
  497. class IdentityGate(OneQubitGate):
  498. """The single qubit identity gate.
  499. Parameters
  500. ----------
  501. target : int
  502. The target qubit this gate will apply to.
  503. Examples
  504. ========
  505. """
  506. gate_name = '1'
  507. gate_name_latex = '1'
  508. # Short cut version of gate._apply_operator_Qubit
  509. def _apply_operator_Qubit(self, qubits, **options):
  510. # Check number of qubits this gate acts on (see gate._apply_operator_Qubit)
  511. if qubits.nqubits < self.min_qubits:
  512. raise QuantumError(
  513. 'Gate needs a minimum of %r qubits to act on, got: %r' %
  514. (self.min_qubits, qubits.nqubits)
  515. )
  516. return qubits # no computation required for IdentityGate
  517. def get_target_matrix(self, format='sympy'):
  518. return matrix_cache.get_matrix('eye2', format)
  519. def _eval_commutator(self, other, **hints):
  520. return _S.Zero
  521. def _eval_anticommutator(self, other, **hints):
  522. return Integer(2)*other
  523. class HadamardGate(HermitianOperator, OneQubitGate):
  524. """The single qubit Hadamard gate.
  525. Parameters
  526. ----------
  527. target : int
  528. The target qubit this gate will apply to.
  529. Examples
  530. ========
  531. >>> from sympy import sqrt
  532. >>> from sympy.physics.quantum.qubit import Qubit
  533. >>> from sympy.physics.quantum.gate import HadamardGate
  534. >>> from sympy.physics.quantum.qapply import qapply
  535. >>> qapply(HadamardGate(0)*Qubit('1'))
  536. sqrt(2)*|0>/2 - sqrt(2)*|1>/2
  537. >>> # Hadamard on bell state, applied on 2 qubits.
  538. >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
  539. >>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
  540. sqrt(2)*|00>/2 + sqrt(2)*|11>/2
  541. """
  542. gate_name = 'H'
  543. gate_name_latex = 'H'
  544. def get_target_matrix(self, format='sympy'):
  545. if _normalized:
  546. return matrix_cache.get_matrix('H', format)
  547. else:
  548. return matrix_cache.get_matrix('Hsqrt2', format)
  549. def _eval_commutator_XGate(self, other, **hints):
  550. return I*sqrt(2)*YGate(self.targets[0])
  551. def _eval_commutator_YGate(self, other, **hints):
  552. return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
  553. def _eval_commutator_ZGate(self, other, **hints):
  554. return -I*sqrt(2)*YGate(self.targets[0])
  555. def _eval_anticommutator_XGate(self, other, **hints):
  556. return sqrt(2)*IdentityGate(self.targets[0])
  557. def _eval_anticommutator_YGate(self, other, **hints):
  558. return _S.Zero
  559. def _eval_anticommutator_ZGate(self, other, **hints):
  560. return sqrt(2)*IdentityGate(self.targets[0])
  561. class XGate(HermitianOperator, OneQubitGate):
  562. """The single qubit X, or NOT, gate.
  563. Parameters
  564. ----------
  565. target : int
  566. The target qubit this gate will apply to.
  567. Examples
  568. ========
  569. """
  570. gate_name = 'X'
  571. gate_name_latex = 'X'
  572. def get_target_matrix(self, format='sympy'):
  573. return matrix_cache.get_matrix('X', format)
  574. def plot_gate(self, circ_plot, gate_idx):
  575. OneQubitGate.plot_gate(self,circ_plot,gate_idx)
  576. def plot_gate_plus(self, circ_plot, gate_idx):
  577. circ_plot.not_point(
  578. gate_idx, int(self.label[0])
  579. )
  580. def _eval_commutator_YGate(self, other, **hints):
  581. return Integer(2)*I*ZGate(self.targets[0])
  582. def _eval_anticommutator_XGate(self, other, **hints):
  583. return Integer(2)*IdentityGate(self.targets[0])
  584. def _eval_anticommutator_YGate(self, other, **hints):
  585. return _S.Zero
  586. def _eval_anticommutator_ZGate(self, other, **hints):
  587. return _S.Zero
  588. class YGate(HermitianOperator, OneQubitGate):
  589. """The single qubit Y gate.
  590. Parameters
  591. ----------
  592. target : int
  593. The target qubit this gate will apply to.
  594. Examples
  595. ========
  596. """
  597. gate_name = 'Y'
  598. gate_name_latex = 'Y'
  599. def get_target_matrix(self, format='sympy'):
  600. return matrix_cache.get_matrix('Y', format)
  601. def _eval_commutator_ZGate(self, other, **hints):
  602. return Integer(2)*I*XGate(self.targets[0])
  603. def _eval_anticommutator_YGate(self, other, **hints):
  604. return Integer(2)*IdentityGate(self.targets[0])
  605. def _eval_anticommutator_ZGate(self, other, **hints):
  606. return _S.Zero
  607. class ZGate(HermitianOperator, OneQubitGate):
  608. """The single qubit Z gate.
  609. Parameters
  610. ----------
  611. target : int
  612. The target qubit this gate will apply to.
  613. Examples
  614. ========
  615. """
  616. gate_name = 'Z'
  617. gate_name_latex = 'Z'
  618. def get_target_matrix(self, format='sympy'):
  619. return matrix_cache.get_matrix('Z', format)
  620. def _eval_commutator_XGate(self, other, **hints):
  621. return Integer(2)*I*YGate(self.targets[0])
  622. def _eval_anticommutator_YGate(self, other, **hints):
  623. return _S.Zero
  624. class PhaseGate(OneQubitGate):
  625. """The single qubit phase, or S, gate.
  626. This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
  627. does nothing if the state is ``|0>``.
  628. Parameters
  629. ----------
  630. target : int
  631. The target qubit this gate will apply to.
  632. Examples
  633. ========
  634. """
  635. gate_name = 'S'
  636. gate_name_latex = 'S'
  637. def get_target_matrix(self, format='sympy'):
  638. return matrix_cache.get_matrix('S', format)
  639. def _eval_commutator_ZGate(self, other, **hints):
  640. return _S.Zero
  641. def _eval_commutator_TGate(self, other, **hints):
  642. return _S.Zero
  643. class TGate(OneQubitGate):
  644. """The single qubit pi/8 gate.
  645. This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
  646. does nothing if the state is ``|0>``.
  647. Parameters
  648. ----------
  649. target : int
  650. The target qubit this gate will apply to.
  651. Examples
  652. ========
  653. """
  654. gate_name = 'T'
  655. gate_name_latex = 'T'
  656. def get_target_matrix(self, format='sympy'):
  657. return matrix_cache.get_matrix('T', format)
  658. def _eval_commutator_ZGate(self, other, **hints):
  659. return _S.Zero
  660. def _eval_commutator_PhaseGate(self, other, **hints):
  661. return _S.Zero
  662. # Aliases for gate names.
  663. H = HadamardGate
  664. X = XGate
  665. Y = YGate
  666. Z = ZGate
  667. T = TGate
  668. Phase = S = PhaseGate
  669. #-----------------------------------------------------------------------------
  670. # 2 Qubit Gates
  671. #-----------------------------------------------------------------------------
  672. class CNotGate(HermitianOperator, CGate, TwoQubitGate):
  673. """Two qubit controlled-NOT.
  674. This gate performs the NOT or X gate on the target qubit if the control
  675. qubits all have the value 1.
  676. Parameters
  677. ----------
  678. label : tuple
  679. A tuple of the form (control, target).
  680. Examples
  681. ========
  682. >>> from sympy.physics.quantum.gate import CNOT
  683. >>> from sympy.physics.quantum.qapply import qapply
  684. >>> from sympy.physics.quantum.qubit import Qubit
  685. >>> c = CNOT(1,0)
  686. >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
  687. |11>
  688. """
  689. gate_name = 'CNOT'
  690. gate_name_latex = r'\text{CNOT}'
  691. simplify_cgate = True
  692. #-------------------------------------------------------------------------
  693. # Initialization
  694. #-------------------------------------------------------------------------
  695. @classmethod
  696. def _eval_args(cls, args):
  697. args = Gate._eval_args(args)
  698. return args
  699. @classmethod
  700. def _eval_hilbert_space(cls, args):
  701. """This returns the smallest possible Hilbert space."""
  702. return ComplexSpace(2)**(_max(args) + 1)
  703. #-------------------------------------------------------------------------
  704. # Properties
  705. #-------------------------------------------------------------------------
  706. @property
  707. def min_qubits(self):
  708. """The minimum number of qubits this gate needs to act on."""
  709. return _max(self.label) + 1
  710. @property
  711. def targets(self):
  712. """A tuple of target qubits."""
  713. return (self.label[1],)
  714. @property
  715. def controls(self):
  716. """A tuple of control qubits."""
  717. return (self.label[0],)
  718. @property
  719. def gate(self):
  720. """The non-controlled gate that will be applied to the targets."""
  721. return XGate(self.label[1])
  722. #-------------------------------------------------------------------------
  723. # Properties
  724. #-------------------------------------------------------------------------
  725. # The default printing of Gate works better than those of CGate, so we
  726. # go around the overridden methods in CGate.
  727. def _print_label(self, printer, *args):
  728. return Gate._print_label(self, printer, *args)
  729. def _pretty(self, printer, *args):
  730. return Gate._pretty(self, printer, *args)
  731. def _latex(self, printer, *args):
  732. return Gate._latex(self, printer, *args)
  733. #-------------------------------------------------------------------------
  734. # Commutator/AntiCommutator
  735. #-------------------------------------------------------------------------
  736. def _eval_commutator_ZGate(self, other, **hints):
  737. """[CNOT(i, j), Z(i)] == 0."""
  738. if self.controls[0] == other.targets[0]:
  739. return _S.Zero
  740. else:
  741. raise NotImplementedError('Commutator not implemented: %r' % other)
  742. def _eval_commutator_TGate(self, other, **hints):
  743. """[CNOT(i, j), T(i)] == 0."""
  744. return self._eval_commutator_ZGate(other, **hints)
  745. def _eval_commutator_PhaseGate(self, other, **hints):
  746. """[CNOT(i, j), S(i)] == 0."""
  747. return self._eval_commutator_ZGate(other, **hints)
  748. def _eval_commutator_XGate(self, other, **hints):
  749. """[CNOT(i, j), X(j)] == 0."""
  750. if self.targets[0] == other.targets[0]:
  751. return _S.Zero
  752. else:
  753. raise NotImplementedError('Commutator not implemented: %r' % other)
  754. def _eval_commutator_CNotGate(self, other, **hints):
  755. """[CNOT(i, j), CNOT(i,k)] == 0."""
  756. if self.controls[0] == other.controls[0]:
  757. return _S.Zero
  758. else:
  759. raise NotImplementedError('Commutator not implemented: %r' % other)
  760. class SwapGate(TwoQubitGate):
  761. """Two qubit SWAP gate.
  762. This gate swap the values of the two qubits.
  763. Parameters
  764. ----------
  765. label : tuple
  766. A tuple of the form (target1, target2).
  767. Examples
  768. ========
  769. """
  770. gate_name = 'SWAP'
  771. gate_name_latex = r'\text{SWAP}'
  772. def get_target_matrix(self, format='sympy'):
  773. return matrix_cache.get_matrix('SWAP', format)
  774. def decompose(self, **options):
  775. """Decompose the SWAP gate into CNOT gates."""
  776. i, j = self.targets[0], self.targets[1]
  777. g1 = CNotGate(i, j)
  778. g2 = CNotGate(j, i)
  779. return g1*g2*g1
  780. def plot_gate(self, circ_plot, gate_idx):
  781. min_wire = int(_min(self.targets))
  782. max_wire = int(_max(self.targets))
  783. circ_plot.control_line(gate_idx, min_wire, max_wire)
  784. circ_plot.swap_point(gate_idx, min_wire)
  785. circ_plot.swap_point(gate_idx, max_wire)
  786. def _represent_ZGate(self, basis, **options):
  787. """Represent the SWAP gate in the computational basis.
  788. The following representation is used to compute this:
  789. SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
  790. """
  791. format = options.get('format', 'sympy')
  792. targets = [int(t) for t in self.targets]
  793. min_target = _min(targets)
  794. max_target = _max(targets)
  795. nqubits = options.get('nqubits', self.min_qubits)
  796. op01 = matrix_cache.get_matrix('op01', format)
  797. op10 = matrix_cache.get_matrix('op10', format)
  798. op11 = matrix_cache.get_matrix('op11', format)
  799. op00 = matrix_cache.get_matrix('op00', format)
  800. eye2 = matrix_cache.get_matrix('eye2', format)
  801. result = None
  802. for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
  803. product = nqubits*[eye2]
  804. product[nqubits - min_target - 1] = i
  805. product[nqubits - max_target - 1] = j
  806. new_result = matrix_tensor_product(*product)
  807. if result is None:
  808. result = new_result
  809. else:
  810. result = result + new_result
  811. return result
  812. # Aliases for gate names.
  813. CNOT = CNotGate
  814. SWAP = SwapGate
  815. def CPHASE(a,b): return CGateS((a,),Z(b))
  816. #-----------------------------------------------------------------------------
  817. # Represent
  818. #-----------------------------------------------------------------------------
  819. def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
  820. """Represent a gate with controls, targets and target_matrix.
  821. This function does the low-level work of representing gates as matrices
  822. in the standard computational basis (ZGate). Currently, we support two
  823. main cases:
  824. 1. One target qubit and no control qubits.
  825. 2. One target qubits and multiple control qubits.
  826. For the base of multiple controls, we use the following expression [1]:
  827. 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
  828. Parameters
  829. ----------
  830. controls : list, tuple
  831. A sequence of control qubits.
  832. targets : list, tuple
  833. A sequence of target qubits.
  834. target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
  835. The matrix form of the transformation to be performed on the target
  836. qubits. The format of this matrix must match that passed into
  837. the `format` argument.
  838. nqubits : int
  839. The total number of qubits used for the representation.
  840. format : str
  841. The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
  842. Examples
  843. ========
  844. References
  845. ----------
  846. [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
  847. """
  848. controls = [int(x) for x in controls]
  849. targets = [int(x) for x in targets]
  850. nqubits = int(nqubits)
  851. # This checks for the format as well.
  852. op11 = matrix_cache.get_matrix('op11', format)
  853. eye2 = matrix_cache.get_matrix('eye2', format)
  854. # Plain single qubit case
  855. if len(controls) == 0 and len(targets) == 1:
  856. product = []
  857. bit = targets[0]
  858. # Fill product with [I1,Gate,I2] such that the unitaries,
  859. # I, cause the gate to be applied to the correct Qubit
  860. if bit != nqubits - 1:
  861. product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
  862. product.append(target_matrix)
  863. if bit != 0:
  864. product.append(matrix_eye(2**bit, format=format))
  865. return matrix_tensor_product(*product)
  866. # Single target, multiple controls.
  867. elif len(targets) == 1 and len(controls) >= 1:
  868. target = targets[0]
  869. # Build the non-trivial part.
  870. product2 = []
  871. for i in range(nqubits):
  872. product2.append(matrix_eye(2, format=format))
  873. for control in controls:
  874. product2[nqubits - 1 - control] = op11
  875. product2[nqubits - 1 - target] = target_matrix - eye2
  876. return matrix_eye(2**nqubits, format=format) + \
  877. matrix_tensor_product(*product2)
  878. # Multi-target, multi-control is not yet implemented.
  879. else:
  880. raise NotImplementedError(
  881. 'The representation of multi-target, multi-control gates '
  882. 'is not implemented.'
  883. )
  884. #-----------------------------------------------------------------------------
  885. # Gate manipulation functions.
  886. #-----------------------------------------------------------------------------
  887. def gate_simp(circuit):
  888. """Simplifies gates symbolically
  889. It first sorts gates using gate_sort. It then applies basic
  890. simplification rules to the circuit, e.g., XGate**2 = Identity
  891. """
  892. # Bubble sort out gates that commute.
  893. circuit = gate_sort(circuit)
  894. # Do simplifications by subing a simplification into the first element
  895. # which can be simplified. We recursively call gate_simp with new circuit
  896. # as input more simplifications exist.
  897. if isinstance(circuit, Add):
  898. return sum(gate_simp(t) for t in circuit.args)
  899. elif isinstance(circuit, Mul):
  900. circuit_args = circuit.args
  901. elif isinstance(circuit, Pow):
  902. b, e = circuit.as_base_exp()
  903. circuit_args = (gate_simp(b)**e,)
  904. else:
  905. return circuit
  906. # Iterate through each element in circuit, simplify if possible.
  907. for i in range(len(circuit_args)):
  908. # H,X,Y or Z squared is 1.
  909. # T**2 = S, S**2 = Z
  910. if isinstance(circuit_args[i], Pow):
  911. if isinstance(circuit_args[i].base,
  912. (HadamardGate, XGate, YGate, ZGate)) \
  913. and isinstance(circuit_args[i].exp, Number):
  914. # Build a new circuit taking replacing the
  915. # H,X,Y,Z squared with one.
  916. newargs = (circuit_args[:i] +
  917. (circuit_args[i].base**(circuit_args[i].exp % 2),) +
  918. circuit_args[i + 1:])
  919. # Recursively simplify the new circuit.
  920. circuit = gate_simp(Mul(*newargs))
  921. break
  922. elif isinstance(circuit_args[i].base, PhaseGate):
  923. # Build a new circuit taking old circuit but splicing
  924. # in simplification.
  925. newargs = circuit_args[:i]
  926. # Replace PhaseGate**2 with ZGate.
  927. newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
  928. (Integer(circuit_args[i].exp/2)), circuit_args[i].base**
  929. (circuit_args[i].exp % 2))
  930. # Append the last elements.
  931. newargs = newargs + circuit_args[i + 1:]
  932. # Recursively simplify the new circuit.
  933. circuit = gate_simp(Mul(*newargs))
  934. break
  935. elif isinstance(circuit_args[i].base, TGate):
  936. # Build a new circuit taking all the old elements.
  937. newargs = circuit_args[:i]
  938. # Put an Phasegate in place of any TGate**2.
  939. newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
  940. Integer(circuit_args[i].exp/2), circuit_args[i].base**
  941. (circuit_args[i].exp % 2))
  942. # Append the last elements.
  943. newargs = newargs + circuit_args[i + 1:]
  944. # Recursively simplify the new circuit.
  945. circuit = gate_simp(Mul(*newargs))
  946. break
  947. return circuit
  948. def gate_sort(circuit):
  949. """Sorts the gates while keeping track of commutation relations
  950. This function uses a bubble sort to rearrange the order of gate
  951. application. Keeps track of Quantum computations special commutation
  952. relations (e.g. things that apply to the same Qubit do not commute with
  953. each other)
  954. circuit is the Mul of gates that are to be sorted.
  955. """
  956. # Make sure we have an Add or Mul.
  957. if isinstance(circuit, Add):
  958. return sum(gate_sort(t) for t in circuit.args)
  959. if isinstance(circuit, Pow):
  960. return gate_sort(circuit.base)**circuit.exp
  961. elif isinstance(circuit, Gate):
  962. return circuit
  963. if not isinstance(circuit, Mul):
  964. return circuit
  965. changes = True
  966. while changes:
  967. changes = False
  968. circ_array = circuit.args
  969. for i in range(len(circ_array) - 1):
  970. # Go through each element and switch ones that are in wrong order
  971. if isinstance(circ_array[i], (Gate, Pow)) and \
  972. isinstance(circ_array[i + 1], (Gate, Pow)):
  973. # If we have a Pow object, look at only the base
  974. first_base, first_exp = circ_array[i].as_base_exp()
  975. second_base, second_exp = circ_array[i + 1].as_base_exp()
  976. # Use SymPy's hash based sorting. This is not mathematical
  977. # sorting, but is rather based on comparing hashes of objects.
  978. # See Basic.compare for details.
  979. if first_base.compare(second_base) > 0:
  980. if Commutator(first_base, second_base).doit() == 0:
  981. new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
  982. (circuit.args[i],) + circuit.args[i + 2:])
  983. circuit = Mul(*new_args)
  984. changes = True
  985. break
  986. if AntiCommutator(first_base, second_base).doit() == 0:
  987. new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
  988. (circuit.args[i],) + circuit.args[i + 2:])
  989. sign = _S.NegativeOne**(first_exp*second_exp)
  990. circuit = sign*Mul(*new_args)
  991. changes = True
  992. break
  993. return circuit
  994. #-----------------------------------------------------------------------------
  995. # Utility functions
  996. #-----------------------------------------------------------------------------
  997. def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
  998. """Return a random circuit of ngates and nqubits.
  999. This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
  1000. gates.
  1001. Parameters
  1002. ----------
  1003. ngates : int
  1004. The number of gates in the circuit.
  1005. nqubits : int
  1006. The number of qubits in the circuit.
  1007. gate_space : tuple
  1008. A tuple of the gate classes that will be used in the circuit.
  1009. Repeating gate classes multiple times in this tuple will increase
  1010. the frequency they appear in the random circuit.
  1011. """
  1012. qubit_space = range(nqubits)
  1013. result = []
  1014. for i in range(ngates):
  1015. g = random.choice(gate_space)
  1016. if g == CNotGate or g == SwapGate:
  1017. qubits = random.sample(qubit_space, 2)
  1018. g = g(*qubits)
  1019. else:
  1020. qubit = random.choice(qubit_space)
  1021. g = g(qubit)
  1022. result.append(g)
  1023. return Mul(*result)
  1024. def zx_basis_transform(self, format='sympy'):
  1025. """Transformation matrix from Z to X basis."""
  1026. return matrix_cache.get_matrix('ZX', format)
  1027. def zy_basis_transform(self, format='sympy'):
  1028. """Transformation matrix from Z to Y basis."""
  1029. return matrix_cache.get_matrix('ZY', format)