gate.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. """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(list(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 rep. 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 in range(len(targets)):
  199. if new_qubit[targets[bit]] != (index >> bit) & 1:
  200. new_qubit = new_qubit.flip(targets[bit])
  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. def get_target_matrix(self, format='sympy'):
  509. return matrix_cache.get_matrix('eye2', format)
  510. def _eval_commutator(self, other, **hints):
  511. return _S.Zero
  512. def _eval_anticommutator(self, other, **hints):
  513. return Integer(2)*other
  514. class HadamardGate(HermitianOperator, OneQubitGate):
  515. """The single qubit Hadamard gate.
  516. Parameters
  517. ----------
  518. target : int
  519. The target qubit this gate will apply to.
  520. Examples
  521. ========
  522. >>> from sympy import sqrt
  523. >>> from sympy.physics.quantum.qubit import Qubit
  524. >>> from sympy.physics.quantum.gate import HadamardGate
  525. >>> from sympy.physics.quantum.qapply import qapply
  526. >>> qapply(HadamardGate(0)*Qubit('1'))
  527. sqrt(2)*|0>/2 - sqrt(2)*|1>/2
  528. >>> # Hadamard on bell state, applied on 2 qubits.
  529. >>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
  530. >>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
  531. sqrt(2)*|00>/2 + sqrt(2)*|11>/2
  532. """
  533. gate_name = 'H'
  534. gate_name_latex = 'H'
  535. def get_target_matrix(self, format='sympy'):
  536. if _normalized:
  537. return matrix_cache.get_matrix('H', format)
  538. else:
  539. return matrix_cache.get_matrix('Hsqrt2', format)
  540. def _eval_commutator_XGate(self, other, **hints):
  541. return I*sqrt(2)*YGate(self.targets[0])
  542. def _eval_commutator_YGate(self, other, **hints):
  543. return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
  544. def _eval_commutator_ZGate(self, other, **hints):
  545. return -I*sqrt(2)*YGate(self.targets[0])
  546. def _eval_anticommutator_XGate(self, other, **hints):
  547. return sqrt(2)*IdentityGate(self.targets[0])
  548. def _eval_anticommutator_YGate(self, other, **hints):
  549. return _S.Zero
  550. def _eval_anticommutator_ZGate(self, other, **hints):
  551. return sqrt(2)*IdentityGate(self.targets[0])
  552. class XGate(HermitianOperator, OneQubitGate):
  553. """The single qubit X, or NOT, gate.
  554. Parameters
  555. ----------
  556. target : int
  557. The target qubit this gate will apply to.
  558. Examples
  559. ========
  560. """
  561. gate_name = 'X'
  562. gate_name_latex = 'X'
  563. def get_target_matrix(self, format='sympy'):
  564. return matrix_cache.get_matrix('X', format)
  565. def plot_gate(self, circ_plot, gate_idx):
  566. OneQubitGate.plot_gate(self,circ_plot,gate_idx)
  567. def plot_gate_plus(self, circ_plot, gate_idx):
  568. circ_plot.not_point(
  569. gate_idx, int(self.label[0])
  570. )
  571. def _eval_commutator_YGate(self, other, **hints):
  572. return Integer(2)*I*ZGate(self.targets[0])
  573. def _eval_anticommutator_XGate(self, other, **hints):
  574. return Integer(2)*IdentityGate(self.targets[0])
  575. def _eval_anticommutator_YGate(self, other, **hints):
  576. return _S.Zero
  577. def _eval_anticommutator_ZGate(self, other, **hints):
  578. return _S.Zero
  579. class YGate(HermitianOperator, OneQubitGate):
  580. """The single qubit Y gate.
  581. Parameters
  582. ----------
  583. target : int
  584. The target qubit this gate will apply to.
  585. Examples
  586. ========
  587. """
  588. gate_name = 'Y'
  589. gate_name_latex = 'Y'
  590. def get_target_matrix(self, format='sympy'):
  591. return matrix_cache.get_matrix('Y', format)
  592. def _eval_commutator_ZGate(self, other, **hints):
  593. return Integer(2)*I*XGate(self.targets[0])
  594. def _eval_anticommutator_YGate(self, other, **hints):
  595. return Integer(2)*IdentityGate(self.targets[0])
  596. def _eval_anticommutator_ZGate(self, other, **hints):
  597. return _S.Zero
  598. class ZGate(HermitianOperator, OneQubitGate):
  599. """The single qubit Z gate.
  600. Parameters
  601. ----------
  602. target : int
  603. The target qubit this gate will apply to.
  604. Examples
  605. ========
  606. """
  607. gate_name = 'Z'
  608. gate_name_latex = 'Z'
  609. def get_target_matrix(self, format='sympy'):
  610. return matrix_cache.get_matrix('Z', format)
  611. def _eval_commutator_XGate(self, other, **hints):
  612. return Integer(2)*I*YGate(self.targets[0])
  613. def _eval_anticommutator_YGate(self, other, **hints):
  614. return _S.Zero
  615. class PhaseGate(OneQubitGate):
  616. """The single qubit phase, or S, gate.
  617. This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
  618. does nothing if the state is ``|0>``.
  619. Parameters
  620. ----------
  621. target : int
  622. The target qubit this gate will apply to.
  623. Examples
  624. ========
  625. """
  626. gate_name = 'S'
  627. gate_name_latex = 'S'
  628. def get_target_matrix(self, format='sympy'):
  629. return matrix_cache.get_matrix('S', format)
  630. def _eval_commutator_ZGate(self, other, **hints):
  631. return _S.Zero
  632. def _eval_commutator_TGate(self, other, **hints):
  633. return _S.Zero
  634. class TGate(OneQubitGate):
  635. """The single qubit pi/8 gate.
  636. This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
  637. does nothing if the state is ``|0>``.
  638. Parameters
  639. ----------
  640. target : int
  641. The target qubit this gate will apply to.
  642. Examples
  643. ========
  644. """
  645. gate_name = 'T'
  646. gate_name_latex = 'T'
  647. def get_target_matrix(self, format='sympy'):
  648. return matrix_cache.get_matrix('T', format)
  649. def _eval_commutator_ZGate(self, other, **hints):
  650. return _S.Zero
  651. def _eval_commutator_PhaseGate(self, other, **hints):
  652. return _S.Zero
  653. # Aliases for gate names.
  654. H = HadamardGate
  655. X = XGate
  656. Y = YGate
  657. Z = ZGate
  658. T = TGate
  659. Phase = S = PhaseGate
  660. #-----------------------------------------------------------------------------
  661. # 2 Qubit Gates
  662. #-----------------------------------------------------------------------------
  663. class CNotGate(HermitianOperator, CGate, TwoQubitGate):
  664. """Two qubit controlled-NOT.
  665. This gate performs the NOT or X gate on the target qubit if the control
  666. qubits all have the value 1.
  667. Parameters
  668. ----------
  669. label : tuple
  670. A tuple of the form (control, target).
  671. Examples
  672. ========
  673. >>> from sympy.physics.quantum.gate import CNOT
  674. >>> from sympy.physics.quantum.qapply import qapply
  675. >>> from sympy.physics.quantum.qubit import Qubit
  676. >>> c = CNOT(1,0)
  677. >>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
  678. |11>
  679. """
  680. gate_name = 'CNOT'
  681. gate_name_latex = r'\text{CNOT}'
  682. simplify_cgate = True
  683. #-------------------------------------------------------------------------
  684. # Initialization
  685. #-------------------------------------------------------------------------
  686. @classmethod
  687. def _eval_args(cls, args):
  688. args = Gate._eval_args(args)
  689. return args
  690. @classmethod
  691. def _eval_hilbert_space(cls, args):
  692. """This returns the smallest possible Hilbert space."""
  693. return ComplexSpace(2)**(_max(args) + 1)
  694. #-------------------------------------------------------------------------
  695. # Properties
  696. #-------------------------------------------------------------------------
  697. @property
  698. def min_qubits(self):
  699. """The minimum number of qubits this gate needs to act on."""
  700. return _max(self.label) + 1
  701. @property
  702. def targets(self):
  703. """A tuple of target qubits."""
  704. return (self.label[1],)
  705. @property
  706. def controls(self):
  707. """A tuple of control qubits."""
  708. return (self.label[0],)
  709. @property
  710. def gate(self):
  711. """The non-controlled gate that will be applied to the targets."""
  712. return XGate(self.label[1])
  713. #-------------------------------------------------------------------------
  714. # Properties
  715. #-------------------------------------------------------------------------
  716. # The default printing of Gate works better than those of CGate, so we
  717. # go around the overridden methods in CGate.
  718. def _print_label(self, printer, *args):
  719. return Gate._print_label(self, printer, *args)
  720. def _pretty(self, printer, *args):
  721. return Gate._pretty(self, printer, *args)
  722. def _latex(self, printer, *args):
  723. return Gate._latex(self, printer, *args)
  724. #-------------------------------------------------------------------------
  725. # Commutator/AntiCommutator
  726. #-------------------------------------------------------------------------
  727. def _eval_commutator_ZGate(self, other, **hints):
  728. """[CNOT(i, j), Z(i)] == 0."""
  729. if self.controls[0] == other.targets[0]:
  730. return _S.Zero
  731. else:
  732. raise NotImplementedError('Commutator not implemented: %r' % other)
  733. def _eval_commutator_TGate(self, other, **hints):
  734. """[CNOT(i, j), T(i)] == 0."""
  735. return self._eval_commutator_ZGate(other, **hints)
  736. def _eval_commutator_PhaseGate(self, other, **hints):
  737. """[CNOT(i, j), S(i)] == 0."""
  738. return self._eval_commutator_ZGate(other, **hints)
  739. def _eval_commutator_XGate(self, other, **hints):
  740. """[CNOT(i, j), X(j)] == 0."""
  741. if self.targets[0] == other.targets[0]:
  742. return _S.Zero
  743. else:
  744. raise NotImplementedError('Commutator not implemented: %r' % other)
  745. def _eval_commutator_CNotGate(self, other, **hints):
  746. """[CNOT(i, j), CNOT(i,k)] == 0."""
  747. if self.controls[0] == other.controls[0]:
  748. return _S.Zero
  749. else:
  750. raise NotImplementedError('Commutator not implemented: %r' % other)
  751. class SwapGate(TwoQubitGate):
  752. """Two qubit SWAP gate.
  753. This gate swap the values of the two qubits.
  754. Parameters
  755. ----------
  756. label : tuple
  757. A tuple of the form (target1, target2).
  758. Examples
  759. ========
  760. """
  761. gate_name = 'SWAP'
  762. gate_name_latex = r'\text{SWAP}'
  763. def get_target_matrix(self, format='sympy'):
  764. return matrix_cache.get_matrix('SWAP', format)
  765. def decompose(self, **options):
  766. """Decompose the SWAP gate into CNOT gates."""
  767. i, j = self.targets[0], self.targets[1]
  768. g1 = CNotGate(i, j)
  769. g2 = CNotGate(j, i)
  770. return g1*g2*g1
  771. def plot_gate(self, circ_plot, gate_idx):
  772. min_wire = int(_min(self.targets))
  773. max_wire = int(_max(self.targets))
  774. circ_plot.control_line(gate_idx, min_wire, max_wire)
  775. circ_plot.swap_point(gate_idx, min_wire)
  776. circ_plot.swap_point(gate_idx, max_wire)
  777. def _represent_ZGate(self, basis, **options):
  778. """Represent the SWAP gate in the computational basis.
  779. The following representation is used to compute this:
  780. SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
  781. """
  782. format = options.get('format', 'sympy')
  783. targets = [int(t) for t in self.targets]
  784. min_target = _min(targets)
  785. max_target = _max(targets)
  786. nqubits = options.get('nqubits', self.min_qubits)
  787. op01 = matrix_cache.get_matrix('op01', format)
  788. op10 = matrix_cache.get_matrix('op10', format)
  789. op11 = matrix_cache.get_matrix('op11', format)
  790. op00 = matrix_cache.get_matrix('op00', format)
  791. eye2 = matrix_cache.get_matrix('eye2', format)
  792. result = None
  793. for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
  794. product = nqubits*[eye2]
  795. product[nqubits - min_target - 1] = i
  796. product[nqubits - max_target - 1] = j
  797. new_result = matrix_tensor_product(*product)
  798. if result is None:
  799. result = new_result
  800. else:
  801. result = result + new_result
  802. return result
  803. # Aliases for gate names.
  804. CNOT = CNotGate
  805. SWAP = SwapGate
  806. def CPHASE(a,b): return CGateS((a,),Z(b))
  807. #-----------------------------------------------------------------------------
  808. # Represent
  809. #-----------------------------------------------------------------------------
  810. def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
  811. """Represent a gate with controls, targets and target_matrix.
  812. This function does the low-level work of representing gates as matrices
  813. in the standard computational basis (ZGate). Currently, we support two
  814. main cases:
  815. 1. One target qubit and no control qubits.
  816. 2. One target qubits and multiple control qubits.
  817. For the base of multiple controls, we use the following expression [1]:
  818. 1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
  819. Parameters
  820. ----------
  821. controls : list, tuple
  822. A sequence of control qubits.
  823. targets : list, tuple
  824. A sequence of target qubits.
  825. target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
  826. The matrix form of the transformation to be performed on the target
  827. qubits. The format of this matrix must match that passed into
  828. the `format` argument.
  829. nqubits : int
  830. The total number of qubits used for the representation.
  831. format : str
  832. The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
  833. Examples
  834. ========
  835. References
  836. ----------
  837. [1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
  838. """
  839. controls = [int(x) for x in controls]
  840. targets = [int(x) for x in targets]
  841. nqubits = int(nqubits)
  842. # This checks for the format as well.
  843. op11 = matrix_cache.get_matrix('op11', format)
  844. eye2 = matrix_cache.get_matrix('eye2', format)
  845. # Plain single qubit case
  846. if len(controls) == 0 and len(targets) == 1:
  847. product = []
  848. bit = targets[0]
  849. # Fill product with [I1,Gate,I2] such that the unitaries,
  850. # I, cause the gate to be applied to the correct Qubit
  851. if bit != nqubits - 1:
  852. product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
  853. product.append(target_matrix)
  854. if bit != 0:
  855. product.append(matrix_eye(2**bit, format=format))
  856. return matrix_tensor_product(*product)
  857. # Single target, multiple controls.
  858. elif len(targets) == 1 and len(controls) >= 1:
  859. target = targets[0]
  860. # Build the non-trivial part.
  861. product2 = []
  862. for i in range(nqubits):
  863. product2.append(matrix_eye(2, format=format))
  864. for control in controls:
  865. product2[nqubits - 1 - control] = op11
  866. product2[nqubits - 1 - target] = target_matrix - eye2
  867. return matrix_eye(2**nqubits, format=format) + \
  868. matrix_tensor_product(*product2)
  869. # Multi-target, multi-control is not yet implemented.
  870. else:
  871. raise NotImplementedError(
  872. 'The representation of multi-target, multi-control gates '
  873. 'is not implemented.'
  874. )
  875. #-----------------------------------------------------------------------------
  876. # Gate manipulation functions.
  877. #-----------------------------------------------------------------------------
  878. def gate_simp(circuit):
  879. """Simplifies gates symbolically
  880. It first sorts gates using gate_sort. It then applies basic
  881. simplification rules to the circuit, e.g., XGate**2 = Identity
  882. """
  883. # Bubble sort out gates that commute.
  884. circuit = gate_sort(circuit)
  885. # Do simplifications by subing a simplification into the first element
  886. # which can be simplified. We recursively call gate_simp with new circuit
  887. # as input more simplifications exist.
  888. if isinstance(circuit, Add):
  889. return sum(gate_simp(t) for t in circuit.args)
  890. elif isinstance(circuit, Mul):
  891. circuit_args = circuit.args
  892. elif isinstance(circuit, Pow):
  893. b, e = circuit.as_base_exp()
  894. circuit_args = (gate_simp(b)**e,)
  895. else:
  896. return circuit
  897. # Iterate through each element in circuit, simplify if possible.
  898. for i in range(len(circuit_args)):
  899. # H,X,Y or Z squared is 1.
  900. # T**2 = S, S**2 = Z
  901. if isinstance(circuit_args[i], Pow):
  902. if isinstance(circuit_args[i].base,
  903. (HadamardGate, XGate, YGate, ZGate)) \
  904. and isinstance(circuit_args[i].exp, Number):
  905. # Build a new circuit taking replacing the
  906. # H,X,Y,Z squared with one.
  907. newargs = (circuit_args[:i] +
  908. (circuit_args[i].base**(circuit_args[i].exp % 2),) +
  909. circuit_args[i + 1:])
  910. # Recursively simplify the new circuit.
  911. circuit = gate_simp(Mul(*newargs))
  912. break
  913. elif isinstance(circuit_args[i].base, PhaseGate):
  914. # Build a new circuit taking old circuit but splicing
  915. # in simplification.
  916. newargs = circuit_args[:i]
  917. # Replace PhaseGate**2 with ZGate.
  918. newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
  919. (Integer(circuit_args[i].exp/2)), circuit_args[i].base**
  920. (circuit_args[i].exp % 2))
  921. # Append the last elements.
  922. newargs = newargs + circuit_args[i + 1:]
  923. # Recursively simplify the new circuit.
  924. circuit = gate_simp(Mul(*newargs))
  925. break
  926. elif isinstance(circuit_args[i].base, TGate):
  927. # Build a new circuit taking all the old elements.
  928. newargs = circuit_args[:i]
  929. # Put an Phasegate in place of any TGate**2.
  930. newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
  931. Integer(circuit_args[i].exp/2), circuit_args[i].base**
  932. (circuit_args[i].exp % 2))
  933. # Append the last elements.
  934. newargs = newargs + circuit_args[i + 1:]
  935. # Recursively simplify the new circuit.
  936. circuit = gate_simp(Mul(*newargs))
  937. break
  938. return circuit
  939. def gate_sort(circuit):
  940. """Sorts the gates while keeping track of commutation relations
  941. This function uses a bubble sort to rearrange the order of gate
  942. application. Keeps track of Quantum computations special commutation
  943. relations (e.g. things that apply to the same Qubit do not commute with
  944. each other)
  945. circuit is the Mul of gates that are to be sorted.
  946. """
  947. # Make sure we have an Add or Mul.
  948. if isinstance(circuit, Add):
  949. return sum(gate_sort(t) for t in circuit.args)
  950. if isinstance(circuit, Pow):
  951. return gate_sort(circuit.base)**circuit.exp
  952. elif isinstance(circuit, Gate):
  953. return circuit
  954. if not isinstance(circuit, Mul):
  955. return circuit
  956. changes = True
  957. while changes:
  958. changes = False
  959. circ_array = circuit.args
  960. for i in range(len(circ_array) - 1):
  961. # Go through each element and switch ones that are in wrong order
  962. if isinstance(circ_array[i], (Gate, Pow)) and \
  963. isinstance(circ_array[i + 1], (Gate, Pow)):
  964. # If we have a Pow object, look at only the base
  965. first_base, first_exp = circ_array[i].as_base_exp()
  966. second_base, second_exp = circ_array[i + 1].as_base_exp()
  967. # Use SymPy's hash based sorting. This is not mathematical
  968. # sorting, but is rather based on comparing hashes of objects.
  969. # See Basic.compare for details.
  970. if first_base.compare(second_base) > 0:
  971. if Commutator(first_base, second_base).doit() == 0:
  972. new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
  973. (circuit.args[i],) + circuit.args[i + 2:])
  974. circuit = Mul(*new_args)
  975. changes = True
  976. break
  977. if AntiCommutator(first_base, second_base).doit() == 0:
  978. new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
  979. (circuit.args[i],) + circuit.args[i + 2:])
  980. sign = _S.NegativeOne**(first_exp*second_exp)
  981. circuit = sign*Mul(*new_args)
  982. changes = True
  983. break
  984. return circuit
  985. #-----------------------------------------------------------------------------
  986. # Utility functions
  987. #-----------------------------------------------------------------------------
  988. def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
  989. """Return a random circuit of ngates and nqubits.
  990. This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
  991. gates.
  992. Parameters
  993. ----------
  994. ngates : int
  995. The number of gates in the circuit.
  996. nqubits : int
  997. The number of qubits in the circuit.
  998. gate_space : tuple
  999. A tuple of the gate classes that will be used in the circuit.
  1000. Repeating gate classes multiple times in this tuple will increase
  1001. the frequency they appear in the random circuit.
  1002. """
  1003. qubit_space = range(nqubits)
  1004. result = []
  1005. for i in range(ngates):
  1006. g = random.choice(gate_space)
  1007. if g == CNotGate or g == SwapGate:
  1008. qubits = random.sample(qubit_space, 2)
  1009. g = g(*qubits)
  1010. else:
  1011. qubit = random.choice(qubit_space)
  1012. g = g(qubit)
  1013. result.append(g)
  1014. return Mul(*result)
  1015. def zx_basis_transform(self, format='sympy'):
  1016. """Transformation matrix from Z to X basis."""
  1017. return matrix_cache.get_matrix('ZX', format)
  1018. def zy_basis_transform(self, format='sympy'):
  1019. """Transformation matrix from Z to Y basis."""
  1020. return matrix_cache.get_matrix('ZY', format)