mindquantum.core.gates

functional

The gates blow are the pre-instantiated quantum gates, which can be used directly as an instance of quantum gate.

functional

gates

mindquantum.core.gates.CNOT

mindquantum.core.gates.CNOTGate

mindquantum.core.gates.I

mindquantum.core.gates.IGate

mindquantum.core.gates.ISWAP

mindquantum.core.gates.ISWAPGate

mindquantum.core.gates.H

mindquantum.core.gates.HGate

mindquantum.core.gates.S

mindquantum.core.gates.PhaseShift (numpy.pi/2)

mindquantum.core.gates.SWAP

mindquantum.core.gates.SWAPGate

mindquantum.core.gates.T

mindquantum.core.gates.PhaseShift (numpy.pi/4)

mindquantum.core.gates.X

mindquantum.core.gates.XGate

mindquantum.core.gates.Y

mindquantum.core.gates.YGate

mindquantum.core.gates.Z

mindquantum.core.gates.ZGate

Quantum Gates

Gate module that provides different quantum gate.

class mindquantum.core.gates.AmplitudeDampingChannel(gamma: float, **kwargs)[source]

Quantum channel that express the incoherent noise in quantum computing.

Amplitude damping channel express error that qubit is affected by the energy dissipation.

Amplitude damping channel applies noise as:

\[ \begin{align}\begin{aligned}\epsilon(\rho) = E_0 \rho E_0^\dagger + E_1 \rho E_1^\dagger\\\begin{split}where\ {E_0}=\begin{bmatrix}1&0\\ 0&\sqrt{1-\gamma}\end{bmatrix}, \ {E_1}=\begin{bmatrix}0&\sqrt{\gamma}\\ 0&0\end{bmatrix}\end{split}\end{aligned}\end{align} \]

where \(\rho\) is quantum state as density matrix type; \(\gamma\) is the coefficient of energy dissipation.

Parameters

gamma (int, float) – damping coefficient.

Examples

>>> from mindquantum.core.gates import AmplitudeDampingChannel
>>> from mindquantum.core.circuit import Circuit
>>> circ = Circuit()
>>> circ += AmplitudeDampingChannel(0.02).on(0)
>>> circ += AmplitudeDampingChannel(0.01).on(1, 0)
>>> print(circ)
q0: ──AD(0.02)───────●──────

q1: ──────────────AD(0.01)──
define_projectq_gate()[source]

Define the corresponded projectq gate.

get_cpp_obj()[source]

Get underlying C++ object.

class mindquantum.core.gates.BarrierGate(show=True)[source]

Barrier gate will separate two gate in two different layer.

Parameters

show (bool) – whether show the barrier gate. Default: True.

on(obj_qubits, ctrl_qubits=None)[source]

Define which qubits the gate act on.

The control qubits should always be none, since this gate can never be controlled by other qubits.

Parameters
  • obj_qubits (int, list[int]) – Specific which qubits the gate act on, can be a single qubit or a set of consecutive qubits.

  • ctrl_qubits (int, list[int]) – Specific the control qubits. Default, None.

Returns

Gate, Return a new gate.

class mindquantum.core.gates.BasicGate(name, n_qubits, obj_qubits=None, ctrl_qubits=None)[source]

BasicGate is the base class of all gates.

Parameters
  • name (str) – the name of this gate.

  • n_qubits (int) – how many qubits is this gate.

  • obj_qubits (int, list[int]) – Specific which qubits the gate act on.

  • ctrl_qubits (int, list[int]) – Specific the control qubits. Default, None.

property acted

Check whether this gate is acted on qubits.

define_projectq_gate()[source]

Define the corresponded projectq gate.

get_cpp_obj()[source]

Get the underlying C++ object.

hermitian()[source]

Return the hermitian gate of this gate.

matrix(*args)[source]

Matrix of the gate.

no_grad()[source]

Set this gate to not calculate gradient.

on(obj_qubits, ctrl_qubits=None)[source]

Define which qubit the gate act on and the control qubit.

Note

In this framework, the qubit that the gate act on is specified first, even for control gate, e.g. CNOT, the second arg is control qubits.

Parameters
  • obj_qubits (int, list[int]) – Specific which qubits the gate act on.

  • ctrl_qubits (int, list[int]) – Specific the control qubits. Default, None.

Returns

Gate, Return a new gate.

Examples

>>> from mindquantum.core.gates import X
>>> x = X.on(1)
>>> x.obj_qubits
[1]
>>> x.ctrl_qubits
[]
>>> x = X.on(2, [0, 1])
>>> x.ctrl_qubits
[0, 1]
property parameterized

Check whether this gate is a parameterized gate.

requires_grad()[source]

Set this gate to calculate gradient.

In default, a parameterized gate will requires grad when you init it.

class mindquantum.core.gates.BitFlipChannel(p: float, **kwargs)[source]

Quantum channel that express the incoherent noise in quantum computing.

Bit flip channel express error that randomly flip the qubit (applies \(X\) gate) with probability \(P\), or do noting (applies \(I\) gate) with probability \(1-P\).

Bit flip channel applies noise as:

\[\epsilon(\rho) = (1 - P)\rho + P X \rho X\]

where \(\rho\) is quantum state as density matrix type; \(P\) is the probability of applying an additional \(X\) gate.

Parameters

p (int, float) – probability of occurred error.

Examples

>>> from mindquantum.core.gates import BitFlipChannel
>>> from mindquantum.core.circuit import Circuit
>>> circ = Circuit()
>>> circ += BitFlipChannel(0.02).on(0)
>>> circ += BitFlipChannel(0.01).on(1, 0)
>>> print(circ)
q0: ──BF(0.02)───────●──────

q1: ──────────────BF(0.01)──
class mindquantum.core.gates.BitPhaseFlipChannel(p: float, **kwargs)[source]

Quantum channel that express the incoherent noise in quantum computing.

Bit phase flip channel express error that randomly flip both the state and phase of qubit (applies Y gate) with probability P, or do noting (applies I gate) with probability 1 - P.

Bit phase flip channel applies noise as:

\[\epsilon(\rho) = (1 - P)\rho + P Y \rho Y\]

where ρ is quantum state as density matrix type; P is the probability of applying an additional Y gate.

Parameters

p (int, float) – probability of occurred error.

Examples

>>> from mindquantum.core.gates import BitPhaseFlipChannel
>>> from mindquantum.core.circuit import Circuit
>>> circ = Circuit()
>>> circ += BitPhaseFlipChannel(0.02).on(0)
>>> circ += BitPhaseFlipChannel(0.01).on(1, 0)
>>> print(circ)
q0: ──BPF(0.02)────────●──────

q1: ───────────────BPF(0.01)──
class mindquantum.core.gates.CNOTGate[source]

Control-X gate.

More usage, please see mindquantum.core.gates.XGate.

on(obj_qubits, ctrl_qubits=None)[source]

Define which qubit the gate act on and the control qubit.

Note

In this framework, the qubit that the gate act on is specified first, even for control gate, e.g. CNOT, the second arg is control qubits.

Parameters
  • obj_qubits (int, list[int]) – Specific which qubits the gate act on.

  • ctrl_qubits (int, list[int]) – Specific the control qubits. Default, None.

Returns

Gate, Return a new gate.

class mindquantum.core.gates.DepolarizingChannel(p: float, **kwargs)[source]

Quantum channel that express the incoherent noise in quantum computing.

Depolarizing channel express errors that have probability P to turn qubit’s quantum state into maximally mixed state, by randomly applying one of the pauli gate(X,Y,Z) with same probability P/3. And it has probability 1 - P to change nothing (applies I gate).

Depolarizing channel applies noise as:

\[\epsilon(\rho) = (1 - P)\rho + P/3( X \rho X + Y \rho Y + Z \rho Z)\]

where ρ is quantum state as density matrix type; P is the probability of occurred the depolarizing error.

Parameters

p (int, float) – probability of occurred error.

Examples

>>> from mindquantum.core.gates import DepolarizingChannel
>>> from mindquantum.core.circuit import Circuit
>>> circ = Circuit()
>>> circ += DepolarizingChannel(0.02).on(0)
>>> circ += DepolarizingChannel(0.01).on(1, 0)
>>> print(circ)
q0: ──Dep(0.02)────────●──────

q1: ───────────────Dep(0.01)──
class mindquantum.core.gates.FSim(theta: ParameterResolver, phi: ParameterResolver)[source]

FSim gate represent fermionic simulation gate.

The matrix is:

\[\begin{split}FSim(\theta, \phi) = \begin{pmatrix} 1 & 0 & 0 & 0\\ 0 & \cos(\theta) & -i\sin(\theta) & 0\\ 0 & -i\sin(\theta) & \cos(\theta) & 0\\ 0 & 0 & 0 & e^{i\phi}\\ \end{pmatrix}\end{split}\]
Parameters

Examples

>>> from mindquantum.core.gates import FSim
>>> fsim = FSim('a', 'b').on([0, 1])
>>> fsim
FSim(𝜃=a, 𝜑=b|0 1)
get_cpp_obj()[source]

Get cpp object.

hermitian()[source]

Get the hermitian gate of FSim.

Examples

>>> from mindquantum.core.gates import FSim
>>> fsim = FSim('a', 'b').on([0, 1])
>>> fsim.hermitian()
FSim(𝜃=-a, 𝜑=-b|0 1)
matrix(pr: ParameterResolver = None)[source]

Get the matrix of FSim.

Parameters

pr (Union[ParameterResolver, dict]) – The parameter of fSim gate. Default: None.

property phi: mindquantum.core.parameterresolver.parameterresolver.ParameterResolver

Get phi parameter of FSim gate.

Returns

ParameterResolver, the phi.

property theta: mindquantum.core.parameterresolver.parameterresolver.ParameterResolver

Get theta parameter of FSim gate.

Returns

ParameterResolver, the theta.

class mindquantum.core.gates.GlobalPhase(pr)[source]

Global phase gate. More usage, please see mindquantum.core.gates.RX.

\[\begin{split}{\rm GlobalPhase}=\begin{pmatrix}\exp(-i\theta)&0\\ 0&\exp(-i\theta)\end{pmatrix}\end{split}\]
Parameters

pr (Union[int, float, str, dict, ParameterResolver]) – the parameters of parameterized gate, see above for detail explanation.

diff_matrix(pr=None, about_what=None, **kwargs)[source]

Differential form of this parameterized gate.

Parameters
  • pr (Union[ParameterResolver, dict]) – The parameter value for parameterized gate. Default: None.

  • about_what (str) – calculate the gradient w.r.t which parameter. Default: None.

  • kwargs (dict) – other key arguments.

Returns

numpy.ndarray, the differential form matrix.

matrix(pr=None, **kwargs)[source]

Matrix of parameterized gate.

Parameters
  • pr (Union[ParameterResolver, dict]) – The parameter value for parameterized gate. Default: None.

  • kwargs (dict) – other key arguments.

Returns

numpy.ndarray, the matrix of this gate.

class mindquantum.core.gates.HGate[source]

Hadamard gate.

Hadamard gate with matrix as:

\[\begin{split}{\rm H}=\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix}\end{split}\]

More usage, please see mindquantum.core.gates.XGate.

class mindquantum.core.gates.IGate[source]

Identity gate.

Identity gate with matrix as:

\[\begin{split}{\rm I}=\begin{pmatrix}1&0\\0&1\end{pmatrix}\end{split}\]

More usage, please see mindquantum.core.gates.XGate.

class mindquantum.core.gates.ISWAPGate[source]

ISWAP gate.

ISWAP gate that swaps two different qubits and phase the \(\left|01\right>\) and \(\left|10\right>\) amplitudes by \(i\).

More usage, please see mindquantum.core.gates.XGate.

class mindquantum.core.gates.KrausChannel(name: str, kraus_op, **kwargs)[source]

Quantum channel that express the incoherent noise in quantum computing.

Kraus channel accepts two or more 2x2 matrices as Kraus operator to construct custom (single-qubit) noise in quantum circuit.

Kraus channel applies noise as:

\[\epsilon(\rho) = \sum_{k=0}^{m-1} E_k \rho E_k^\dagger\]

where \(\rho\) is quantum state as density matrix type; {\(E_k\)} is Kraus operator, and it should satisfy the completeness condition: \(\sum_k E_k^\dagger E_k = I\).

Parameters
  • name (str) – the name of this custom noise channel.

  • kraus_op (list, np.ndarray) – Kraus operator, with two or more 2x2 matrices packaged as a list.

Examples

>>> from mindquantum.core.gates import KrausChannel
>>> from mindquantum.core.circuit import Circuit
>>> from cmath import sqrt
>>> gamma = 0.5
>>> kmat0 = [[1, 0], [0, sqrt(1 - gamma)]]
>>> kmat1 = [[0, sqrt(gamma)], [0, 0]]
>>> amplitude_damping = KrausChannel('damping', [kmat0, kmat1])
>>> circ = Circuit()
>>> circ += amplitude_damping.on(0)
>>> circ += amplitude_damping.on(1, 0)
>>> print(circ)
q0: ──damping───────●─────

q1: ─────────────damping──
define_projectq_gate()[source]

Define the corresponded projectq gate.

get_cpp_obj()[source]

Get underlying C++ object.

class mindquantum.core.gates.Measure(name='')[source]

Measurement gate that measure quantum qubits.

Parameters

name (str) – The key of this measurement gate. In a quantum circuit, the key of different measurement gate should be unique. Default: ‘’

Examples

>>> import numpy as np
>>> from mindquantum.algorithm.library import qft
>>> from mindquantum.core.circuit import Circuit
>>> from mindquantum.core.gates import Measure
>>> from mindquantum.simulator import Simulator
>>> circ = qft(range(2))
>>> circ += Measure('q0').on(0)
>>> circ += Measure().on(1)
>>> circ
q0: ──H────PS(π/2)─────────@────M(q0)──
              │            │
q1: ──────────●───────H────@────M(q1)──
>>> sim = Simulator('mqvector', circ.n_qubits)
>>> sim.apply_circuit(Circuit().h(0).x(1, 0))
>>> sim
mqvector simulator with 2 qubits (little endian).
Current quantum state:
√2/2¦00⟩
√2/2¦11⟩
>>> res = sim.sampling(circ, shots=2000, seed=42)
>>> res
shots: 2000
Keys: q1 q0│0.00   0.124       0.248       0.372       0.496       0.621
───────────┼───────────┴───────────┴───────────┴───────────┴───────────┴
         00│▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

         10│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

         11│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

{'00': 993, '10': 506, '11': 501}
>>> sim
mqvector simulator with 2 qubits (little endian).
Current quantum state:
√2/2¦00⟩
√2/2¦11⟩
>>> sim.apply_circuit(circ[:-2])
>>> sim
mqvector simulator with 2 qubits (little endian).
Current quantum state:
√2/2¦00⟩
(√2/4-√2/4j)¦10⟩
(√2/4+√2/4j)¦11⟩
>>> np.abs(sim.get_qs())**2
array([0.5 , 0.  , 0.25, 0.25])
get_cpp_obj()[source]

Get the underlying C++ object.

hermitian()[source]

Hermitian gate of measure return itself.

on(obj_qubits, ctrl_qubits=None)[source]

Define which qubit the gate act on and the control qubit.

Parameters
  • obj_qubits (Union[int, list[int]]) – measure on which qubit.

  • ctrl_qubits (Union[int, list[int]]) – for measurement, we can not set control qubits. Default: None.

Returns

Measure, a measurement gate with will defined obj_qubits .

class mindquantum.core.gates.MeasureResult[source]

Measurement result container.

Examples

>>> from mindquantum.algorithm.library import qft
>>> from mindquantum.simulator import Simulator
>>> sim = Simulator('mqvector', 2)
>>> res = sim.sampling(qft(range(2)).measure_all(), shots=1000, seed=42)
>>> res
shots: 1000
Keys: q1 q0│0.00   0.065        0.13       0.194       0.259       0.324
───────────┼───────────┴───────────┴───────────┴───────────┴───────────┴
         00│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

         01│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

         10│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

         11│▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

{'00': 230, '01': 254, '10': 257, '11': 259}
>>> res.data
{'00': 230, '01': 254, '10': 257, '11': 259}
add_measure(measure)[source]

Add a measurement gate into this measurement result container.

Measure key should be unique in this measurement result container.

Parameters

measure (Union[Iterable, Measure]) – One or more measure gates.

collect_data(samples)[source]

Collect the measured bit string.

Parameters

samples (numpy.ndarray) – A two dimensional (N x M) numpy array that stores the sampling bit string in 0 or 1, where N represents the number of shot times, and M represents the number of keys in this measurement container

property data

Get the sampling data.

Returns

dict, The sampling data.

property keys_map

Reverse mapping for the keys.

select_keys(*keys)[source]

Select certain measurement keys from this measurement container.

Parameters

keys (tuple[str]) – The key you want to select.

Examples

>>> from mindquantum.algorithm.library import qft
>>> from mindquantum.core.gates import H
>>> from mindquantum.simulator import Simulator
>>> circ = qft(range(2)).measure('q0_0', 0).measure('q1_0', 1)
>>> circ.h(0).measure('q0_1', 0)
>>> circ
q0: ──H────PS(π/2)─────────@────M(q0_0)────H────M(q0_1)──
              │            │
q1: ──────────●───────H────@────M(q1_0)──────────────────
>>> sim = Simulator('mqvector', circ.n_qubits)
>>> res = sim.sampling(circ, shots=500, seed=42)
>>> new_res = res.select_keys('q0_1', 'q1_0')
>>> new_res
shots: 500
Keys: q1_0 q0_1│0.00   0.068       0.136       0.204       0.272        0.34
───────────────┼───────────┴───────────┴───────────┴───────────┴───────────┴
             00│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

             01│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

             10│▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

             11│▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒

{'00': 127, '01': 107, '10': 136, '11': 130}
svg(style=None)[source]

Display current measurement result into SVG picture in jupyter notebook.

Parameters

style (dict, str) – the style to set svg style. Currently, we support ‘official’. Default: None.

class mindquantum.core.gates.NoneParameterGate(name, n_qubits, obj_qubits=None, ctrl_qubits=None)[source]

Base class for non-parametric gates.

Parameters
  • name (str) – the name of this gate.

  • n_qubits (int) – how many qubits is this gate.

  • obj_qubits (int, list[int]) – Specific which qubits the gate act on.

  • ctrl_qubits (int, list[int]) – Specific the control qubits. Default, None.

class mindquantum.core.gates.ParameterGate(pr: ParameterResolver, name, n_qubits, *args, obj_qubits=None, ctrl_qubits=None, **kwargs)[source]

Gate that is parameterized.

Parameters
  • pr (ParameterResolver) – the parameter for parameterized gate.

  • name (str) – the name of this parameterized gate.

  • n_qubits (int) – the qubit number of this parameterized gate.

  • args (list) – other arguments for quantum gate.

  • obj_qubits (Union[int, List[int]]) – the qubit that this gate act on. Default: None.

  • ctrl_qubits (Union[int, List[int]]) – the control qubit of this gate. Default: None.

  • kwargs (dict) – other arguments for quantum gate.

get_cpp_obj()[source]

Get the underlying C++ object.

get_parameters()[source]

Return a list of parameters of parameterized gate.

no_grad()[source]

Mark all parameters as not requiring gradient calculations.

no_grad_part(names)[source]

Set certain parameters that do not need grad. Inplace operation.

Parameters

names (tuple[str]) – Parameters that not requires grad.

Returns

BasicGate, with some part of parameters not need to update gradient.

requires_grad()[source]

Mark all parameters as requiring gradient calculations.

requires_grad_part(names)[source]

Set certain parameters that need grad. Inplace operation.

Parameters

names (tuple[str]) – Parameters that requires grad.

Returns

BasicGate, with some part of parameters need to update gradient.

class mindquantum.core.gates.PauliChannel(px: float, py: float, pz: float, **kwargs)[source]

Quantum channel that express the incoherent noise in quantum computing.

Pauli channel express error that randomly applies an additional X, Y or Z gate on qubits with different probabilities Px, Py and Pz, or do noting (applies I gate) with probability P = (1 - Px - Py - Pz).

Pauli channel applies noise as:

\[\epsilon(\rho) = (1 - P_x - P_y - P_z)\rho + P_x X \rho X + P_y Y \rho Y + P_z Z \rho Z\]

where ρ is quantum state as density matrix type; Px, Py and Pz is the probability of applying an additional X, Y and Z gate.

Parameters
  • px (int, float) – probability of applying X gate.

  • py (int, float) – probability of applying Y gate.

  • pz (int, float) – probability of applying Z gate.

Examples

>>> from mindquantum.core.gates import PauliChannel
>>> from mindquantum.core.circuit import Circuit
>>> circ = Circuit()
>>> circ += PauliChannel(0.8, 0.1, 0.1).on(0)
>>> circ += PauliChannel(0, 0.05, 0.9).on(1, 0)
>>> circ.measure_all()
>>> print(circ)
q0: ──PC────●─────M(q0)──

q1: ────────PC────M(q1)──
>>> from mindquantum.simulator import Simulator
>>> sim = Simulator('mqvector', 2)
>>> sim.sampling(circ, shots=1000, seed=42)
shots: 1000
Keys: q1 q0│0.00     0.2         0.4         0.6         0.8         1.0
───────────┼───────────┴───────────┴───────────┴───────────┴───────────┴
         00│▒▒▒▒▒▒▒

         01│▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓

         11│▒▒▒

{'00': 101, '01': 862, '11': 37}
define_projectq_gate()[source]

Define the corresponded projectq gate.

get_cpp_obj()[source]

Get underlying C++ object.

class mindquantum.core.gates.PhaseDampingChannel(gamma: float, **kwargs)[source]

Quantum channel that express the incoherent noise in quantum computing.

Phase damping channel express error that qubit loses quantum information without exchanging energy with environment.

Phase damping channel applies noise as:

\[ \begin{align}\begin{aligned}\epsilon(\rho) = E_0 \rho E_0^\dagger + E_1 \rho E_1^\dagger\\\begin{split}where\ {E_0}=\begin{bmatrix}1&0\\ 0&\sqrt{1-\gamma}\end{bmatrix}, \ {E_1}=\begin{bmatrix}0&0\\ 0&\sqrt{\gamma}\end{bmatrix}\end{split}\end{aligned}\end{align} \]

where ρ is quantum state as density matrix type; gamma is the coefficient of quantum information loss.

Parameters

gamma (int, float) – damping coefficient.

Examples

>>> from mindquantum.core.gates import PhaseDampingChannel
>>> from mindquantum.core.circuit import Circuit
>>> circ = Circuit()
>>> circ += PhaseDampingChannel(0.02).on(0)
>>> circ += PhaseDampingChannel(0.01).on(1, 0)
>>> print(circ)
q0: ──PD(0.02)───────●──────

q1: ──────────────PD(0.01)──
define_projectq_gate()[source]

Define the corresponded projectq gate.

get_cpp_obj()[source]

Get underlying C++ object.

class mindquantum.core.gates.PhaseFlipChannel(p: float, **kwargs)[source]

Quantum channel that express the incoherent noise in quantum computing.

Phase flip channel express error that randomly flip the phase of qubit (applies Z gate) with probability P, or do noting (applies I gate) with probability 1 - P.

Phase flip channel applies noise as:

\[\epsilon(\rho) = (1 - P)\rho + P Z \rho Z\]

where ρ is quantum state as density matrix type; P is the probability of applying an additional Z gate.

Parameters

p (int, float) – probability of occurred error.

Examples

>>> from mindquantum.core.gates import PhaseFlipChannel
>>> from mindquantum.core.circuit import Circuit
>>> circ = Circuit()
>>> circ += PhaseFlipChannel(0.02).on(0)
>>> circ += PhaseFlipChannel(0.01).on(1, 0)
>>> print(circ)
q0: ──PF(0.02)───────●──────

q1: ──────────────PF(0.01)──
class mindquantum.core.gates.PhaseShift(pr)[source]

Phase shift gate. More usage, please see mindquantum.core.gates.RX.

\[\begin{split}{\rm PhaseShift}=\begin{pmatrix}1&0\\ 0&\exp(i\theta)\end{pmatrix}\end{split}\]
Parameters

pr (Union[int, float, str, dict, ParameterResolver]) – the parameters of parameterized gate, see above for detail explanation.

diff_matrix(pr=None, about_what=None)[source]

Differential form of this parameterized gate.

Parameters
  • pr (Union[ParameterResolver, dict]) – The parameter value for parameterized gate. Default: None.

  • about_what (str) – calculate the gradient w.r.t which parameter.

Returns

numpy.ndarray, the differential form matrix.

matrix(pr=None)[source]

Get the matrix of this parameterized gate.

Parameters

pr (Union[ParameterResolver, dict]) – The parameter value for parameterized gate. Default: None.

Returns

numpy.ndarray, the matrix of this gate.

class mindquantum.core.gates.Power(gate, exponent=0.5)[source]

Power operator on a non parameterized gate.

Parameters

Examples

>>> from mindquantum.core.gates import Power
>>> import numpy as np
>>> rx1 = RX(0.5)
>>> rx2 = RX(1)
>>> assert np.all(np.isclose(Power(rx2,0.5).matrix(), rx1.matrix()))
get_cpp_obj()[source]

Get the underlying C++ object.

class mindquantum.core.gates.RX(pr)[source]

Rotation gate around x-axis.

\[\begin{split}{\rm RX}=\begin{pmatrix}\cos(\theta/2)&-i\sin(\theta/2)\\ -i\sin(\theta/2)&\cos(\theta/2)\end{pmatrix}\end{split}\]

The rotation gate can be initialized in three different ways.

1. If you initialize it with a single number, then it will be a non parameterized gate with a certain rotation angle.

2. If you initialize it with a single str, then it will be a parameterized gate with only one parameter and the default coefficient is one.

3. If you initialize it with a dict, e.g. {‘a’:1,’b’:2}, this gate can have multiple parameters with certain coefficients. In this case, it can be expressed as:

\[RX(a+2b)\]
Parameters

pr (Union[int, float, str, dict, ParameterResolver]) – the parameters of parameterized gate, see above for detail explanation.

Examples

>>> from mindquantum.core.gates import RX
>>> import numpy as np
>>> rx1 = RX(0.5)
>>> np.round(rx1.matrix(), 2)
array([[0.97+0.j  , 0.  -0.25j],
       [0.  -0.25j, 0.97+0.j  ]])
>>> rx2 = RX('a')
>>> np.round(rx2.matrix({'a':0.1}), 3)
array([[0.999+0.j  , 0.   -0.05j],
       [0.   -0.05j, 0.999+0.j  ]])
>>> rx3 = RX({'a' : 0.2, 'b': 0.5}).on(0, 2)
>>> print(rx3)
RX(0.2*a + 0.5*b|0 <-: 2)
>>> np.round(rx3.matrix({'a' : 1, 'b' : 2}), 2)
array([[0.83+0.j  , 0.  -0.56j],
       [0.  -0.56j, 0.83+0.j  ]])
>>> np.round(rx3.diff_matrix({'a' : 1, 'b' : 2}, about_what = 'a'), 2)
array([[-0.06+0.j  ,  0.  -0.08j],
       [ 0.  -0.08j, -0.06+0.j  ]])
>>> rx3.coeff
{'a': 0.2, 'b': 0.5}
class mindquantum.core.gates.RY(pr)[source]

Rotation gate around y-axis. More usage, please see mindquantum.core.gates.RX.

\[\begin{split}{\rm RY}=\begin{pmatrix}\cos(\theta/2)&-\sin(\theta/2)\\ \sin(\theta/2)&\cos(\theta/2)\end{pmatrix}\end{split}\]
Parameters

pr (Union[int, float, str, dict, ParameterResolver]) – the parameters of parameterized gate, see above for detail explanation.

class mindquantum.core.gates.RZ(pr)[source]

Rotation gate around z-axis. More usage, please see mindquantum.core.gates.RX.

\[\begin{split}{\rm RZ}=\begin{pmatrix}\exp(-i\theta/2)&0\\ 0&\exp(i\theta/2)\end{pmatrix}\end{split}\]
Parameters

pr (Union[int, float, str, dict, ParameterResolver]) – the parameters of parameterized gate, see above for detail explanation.

class mindquantum.core.gates.SGate[source]

S gate.

S gate with matrix as :

\[\begin{split}{\rm S}=\begin{pmatrix}1&0\\0&i\end{pmatrix}\end{split}\]

More usage, please see mindquantum.core.gates.XGate.

class mindquantum.core.gates.SWAPGate[source]

SWAP gate that swap two different qubits.

More usage, please see mindquantum.core.gates.XGate.

class mindquantum.core.gates.TGate[source]

T gate.

T gate with matrix as :

\[\begin{split}{\rm T}=\begin{pmatrix}1&0\\0&(1+i)/\sqrt(2)\end{pmatrix}\end{split}\]

More usage, please see mindquantum.core.gates.XGate.

class mindquantum.core.gates.U3(theta: ParameterResolver, phi: ParameterResolver, lamda: ParameterResolver)[source]

U3 gate represent arbitrary single qubit gate.

U3 gate with matrix as:

\[\begin{split}U3(\theta, \phi, \lambda) =\begin{pmatrix}\cos(\theta/2)&-e^{i\lambda}\sin(\theta/2)\\ e^{i\phi}\sin(\theta/2)&e^{i(\phi+\lambda)}\cos(\theta/2)\end{pmatrix}\end{split}\]

It can be decomposed as:

\[U3(\theta, \phi, \lambda) = RZ(\phi) RX(-\pi/2) RZ(\theta) RX(\pi/2) RZ(\lambda)\]
Parameters

Examples

>>> from mindquantum.core.gates import U3
>>> U3('theta','phi','lambda').on(0, 1)
U3(𝜃=theta, 𝜑=phi, 𝜆=lambda|0 <-: 1)
get_cpp_obj()[source]

Get cpp obj.

hermitian()[source]

Get hermitian form of U3 gate.

Examples

>>> from mindquantum.core.gates import U3
>>> u3 = U3('a', 'b', 0.5).on(0)
>>> u3.hermitian()
U3(𝜃=-a, 𝜑=-1/2, 𝜆=-b|0)
property lamda: mindquantum.core.parameterresolver.parameterresolver.ParameterResolver

Get lamda parameter of U3 gate.

Returns

ParameterResolver, the lamda.

matrix(pr: ParameterResolver = None)[source]

Get the matrix of U3 gate.

Parameters

pr (Union[ParameterResolver, dict]) – The parameter for U3 gate.

property phi: mindquantum.core.parameterresolver.parameterresolver.ParameterResolver

Get phi parameter of U3 gate.

Returns

ParameterResolver, the phi.

property theta: mindquantum.core.parameterresolver.parameterresolver.ParameterResolver

Get theta parameter of U3 gate.

Returns

ParameterResolver, the theta.

class mindquantum.core.gates.UnivMathGate(name, matrix_value)[source]

Universal math gate.

More usage, please see mindquantum.core.gates.XGate.

Parameters
  • name (str) – the name of this gate.

  • mat (np.ndarray) – the matrix value of this gate.

Examples

>>> from mindquantum.core.gates import UnivMathGate
>>> x_mat=np.array([[0,1],[1,0]])
>>> X_gate=UnivMathGate('X',x_mat)
>>> x1=X_gate.on(0,1)
>>> print(x1)
X(0 <-: 1)
get_cpp_obj()[source]

Get the underlying C++ object.

class mindquantum.core.gates.XGate[source]

Pauli-X gate.

Pauli X gate with matrix as:

\[\begin{split}{\rm X}=\begin{pmatrix}0&1\\1&0\end{pmatrix}\end{split}\]

For simplicity, we define `X` as a instance of `XGate()`. For more redefine, please refer to the functional table below.

Note

For simplicity, you can do power operator on pauli gate (only works for pauli gate at this time). The rule is set below as:

\[X^\theta = RX(\theta\pi)\]

Examples

>>> from mindquantum.core.gates import X
>>> x1 = X.on(0)
>>> cnot = X.on(0, 1)
>>> print(x1)
X(0)
>>> print(cnot)
X(0 <-: 1)
>>> x1.matrix()
array([[0, 1],
       [1, 0]])
>>> x1**2
RX(2π)
>>> (x1**'a').coeff
{'a': 3.141592653589793}, const: 0.0
>>> (x1**{'a' : 2}).coeff
{'a': 6.283185307179586}, const: 0.0
class mindquantum.core.gates.XX(pr)[source]

Ising XX gate. More usage, please see mindquantum.core.gates.RX.

\[{\rm XX_\theta}=\cos(\theta)I\otimes I-i\sin(\theta)\sigma_x\otimes\sigma_x\]
Parameters

pr (Union[int, float, str, dict, ParameterResolver]) – the parameters of parameterized gate, see above for detail explanation.

diff_matrix(pr=None, about_what=None, frac=1)[source]

Differential form of this parameterized gate.

Parameters
  • pr (Union[ParameterResolver, dict]) – The parameter value for parameterized gate. Default: None.

  • about_what (str) – calculate the gradient w.r.t which parameter. Default: None.

  • frac (numbers.Number) – The multiple of the coefficient. Default: 1.

Returns

numpy.ndarray, the differential form matrix.

matrix(pr=None, frac=1)[source]

Get the matrix of this parameterized gate.

Parameters
Returns

numpy.ndarray, the matrix of this gate.

class mindquantum.core.gates.YGate[source]

Pauli Y gate.

Pauli Y gate with matrix as:

\[\begin{split}{\rm Y}=\begin{pmatrix}0&-i\\i&0\end{pmatrix}\end{split}\]

More usage, please see mindquantum.core.gates.XGate.

class mindquantum.core.gates.YY(pr)[source]

Ising YY gate. More usage, please see mindquantum.core.gates.RX.

\[{\rm YY_\theta}=\cos(\theta)I\otimes I-i\sin(\theta)\sigma_y\otimes\sigma_y\]
Parameters

pr (Union[int, float, str, dict, ParameterResolver]) – the parameters of parameterized gate, see above for detail explanation.

diff_matrix(pr=None, about_what=None, frac=1)[source]

Differential form of this parameterized gate.

Parameters
  • pr (Union[ParameterResolver, dict]) – The parameter value for parameterized gate. Default: None.

  • about_what (str) – calculate the gradient w.r.t which parameter. Default: None.

  • frac (numbers.Number) – The multiple of the coefficient. Default: 1.

Returns

numpy.ndarray, the differential form matrix.

matrix(pr=None, frac=1)[source]

Get the matrix of this parameterized gate.

Parameters
Returns

numpy.ndarray, the matrix of this gate.

class mindquantum.core.gates.ZGate[source]

Pauli-Z gate.

Pauli Z gate with matrix as:

\[\begin{split}{\rm Z}=\begin{pmatrix}1&0\\0&-1\end{pmatrix}\end{split}\]

More usage, please see mindquantum.core.gates.XGate.

class mindquantum.core.gates.ZZ(pr)[source]

Ising ZZ gate. More usage, please see mindquantum.core.gates.RX.

\[{\rm ZZ_\theta}=\cos(\theta)I\otimes I-i\sin(\theta)\sigma_Z\otimes\sigma_Z\]
Parameters

pr (Union[int, float, str, dict, ParameterResolver]) – the parameters of parameterized gate, see above for detail explanation.

diff_matrix(pr=None, about_what=None, frac=1)[source]

Differential form of this parameterized gate.

Parameters
  • pr (Union[ParameterResolver, dict]) – The parameter value for parameterized gate. Default: None.

  • about_what (str) – calculate the gradient w.r.t which parameter. Default: None.

  • frac (numbers.Number) – The multiple of the coefficient. Default: 1.

Returns

numpy.ndarray, the differential form matrix.

matrix(pr=None, frac=1)[source]

Get the matrix of this parameterized gate.

Parameters
Returns

numpy.ndarray, the matrix of this gate.

mindquantum.core.gates.gene_univ_parameterized_gate(name, matrix_generator, diff_matrix_generator)[source]

Generate a customer parameterized gate based on the single parameter defined unitary matrix.

Parameters
  • name (str) – The name of this gate.

  • matrix_generator (Union[FunctionType, MethodType]) – A function or a method that take exactly one argument to generate a unitary matrix.

  • diff_matrix_generator (Union[FunctionType, MethodType]) – A function or a method that take exactly one argument to generate the derivative of this unitary matrix.

Returns

_ParamNonHerm, a customer parameterized gate.

Examples

>>> import numpy as np
>>> from mindquantum.core.circuit import Circuit
>>> from mindquantum.core.gates import gene_univ_parameterized_gate
>>> from mindquantum.simulator import Simulator
>>> def matrix(theta):
...     return np.array([[np.exp(1j * theta), 0],
...                      [0, np.exp(-1j * theta)]])
>>> def diff_matrix(theta):
...     return 1j*np.array([[np.exp(1j * theta), 0],
...                         [0, -np.exp(-1j * theta)]])
>>> TestGate = gene_univ_parameterized_gate('Test', matrix, diff_matrix)
>>> circ = Circuit().h(0)
>>> circ += TestGate('a').on(0)
>>> circ
q0: ──H────Test(a)──
>>> circ.get_qs(pr={'a': 1.2})
array([0.25622563+0.65905116j, 0.25622563-0.65905116j])