mindquantum.core.circuit

Quantum Circuit

Circuit.

Quantum circuit module.

class mindquantum.core.circuit.Circuit(gates=None)[source]

The quantum circuit module.

A quantum circuit contains one or more quantum gates, and can be evaluated in a quantum simulator. You can build a quantum circuit very easy by add a quantum gate or another circuit.

Parameters

gates (BasicGate, list[BasicGate]) – You can initialize the quantum circuit by a single quantum gate or a list of gates. gates: None.

Examples

>>> from mindquantum import Circuit, RX, X
>>> circuit1 = Circuit()
>>> circuit1 += RX('a').on(0)
>>> circuit1 *= 2
>>> circuit1
q0: ──RX(a)────RX(a)──
>>> circuit2 = Circuit([X.on(0,1)])
>>> circuit3= circuit1 + circuit2
>>> assert len(circuit3) == 3
>>> circuit3.summary()
=======Circuit Summary=======
|Total number of gates  : 3.|
|Parameter gates        : 2.|
|with 1 parameters are  : a.|
|Number qubit of circuit: 2 |
=============================
>>> circuit3
q0: ──RX(a)────RX(a)────X──

q1: ────────────────────●──
append(gate)[source]

Append a gate.

Parameters

gate (BasicGate) – The gate you want to append.

apply_value(pr)[source]

Convert this circuit to a non parameterized circuit with parameter you input.

Parameters

pr (Union[dict, ParameterResolver]) – parameters you want to apply into this circuit.

Returns

Circuit, a non parameterized circuit.

Examples

>>> from mindquantum.core.gates import X, RX
>>> from mindquantum.core.circuit import Circuit
>>> circuit = Circuit()
>>> circuit += X.on(0)
>>> circuit += RX({'a': 2}).on(0)
>>> circuit = circuit.apply_value({'a': 1.5})
>>> circuit
q0: ──X────RX(3)──
barrier(show=True)[source]

Add a barrier.

Parameters

show (bool) – Whether show barrier or not. Default: True.

compress()[source]

Remove all unused qubits, and map qubits to range(n_qubits).

Examples

>>> from mindquantum import qft
>>> qft([0, 2, 4])
q0: ──H────PS(π/2)────PS(π/4)─────────────────────────@──
              │          │                            │
q2: ──────────●──────────┼───────H────PS(π/2)─────────┼──
                         │               │            │
q4: ─────────────────────●───────────────●───────H────@──
>>> qft([0, 2, 4]).compress()
q0: ──H────PS(π/2)────PS(π/4)─────────────────────────@──
              │          │                            │
q1: ──────────●──────────┼───────H────PS(π/2)─────────┼──
                         │               │            │
q2: ─────────────────────●───────────────●───────H────@──
extend(gates)[source]

Extend a circuit.

Parameters

gates (Union[Circuit, list[BasicGate]]) –

get_cpp_obj(hermitian=False)[source]

Get cpp obj of circuit.

Parameters

hermitian (bool) – Whether to get cpp object of this circuit in hermitian version. Default: False.

get_qs(backend='projectq', pr=None, ket=False, seed=None)[source]

Get the final quantum state of this circuit.

Parameters
  • backend (str) – Which backend you want to use. Default: ‘projectq’.

  • pr (Union[numbers.Number, ParameterResolver, dict, numpy.ndarray]) – The parameter of this circuit, if this circuit is parameterized. Default: None.

  • ket (str) – Whether to return the quantum state in ket format. Default: False.

  • seed (int) – The random seed of simulator. Default: None

h(obj_qubits, ctrl_qubits=None)[source]

Add a hadamard gate.

Parameters
  • obj_qubits (Union[int, list[int]]) – The object qubits of H gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of H gate. Default: None.

property has_measure_gate

To check whether this circuit has measure gate.

Returns

bool, whether this circuit has measure gate.

hermitian()[source]

Get the hermitian of this quantum circuit.

Examples

>>> from mindquantum.core import Circuit
>>> from mindquantum.core import RX
>>> circ = Circuit(RX({'a': 0.2}).on(0))
>>> herm_circ = circ.hermitian()
>>> herm_circ[0].coeff
{'a': -0.2}
insert(index, gates)[source]

Insert a quantum gate or quantum circuit in index.

Parameters
property is_measure_end

Check whether the circuit is end with measurement gate that there is at most one measurement gate that act on each qubit, and this measurement gate should be at end of gate serial of this qubit.

Returns

bool, whether the circuit is end with measurement.

property is_noise_circuit

To check whether this circuit has pauli channel.

Returns

bool, whether this circuit has pauli channel.

matrix(pr=None, big_end=False, backend='projectq', seed=None)[source]

Get the matrix of this circuit.

Parameters
  • pr (ParameterResolver, dict, numpy.ndarray, list, numbers.Number) – The parameter resolver for parameterized quantum circuit. Default: None.

  • big_end (bool) – The low index qubit is place in the end or not. Default: False.

  • backend (str) – The backend to do simulation. Default: ‘projectq’.

  • seed (int) – The random to generate circuit matrix, if the circuit has noise channel.

Examples

>>> from mindquantum.core import Circuit
>>> circuit = Circuit().rx('a',0).h(0)
>>> circuit.matrix({'a': 1.0})
array([[ 0.62054458-0.33900505j,  0.62054458-0.33900505j],
    [ 0.62054458+0.33900505j, -0.62054458-0.33900505j]])
Returns

numpy.ndarray, two dimensional complex matrix of this circuit.

measure(key, obj_qubit=None)[source]

Add a measure gate.

Parameters
  • key (Union[int, str]) – If obj_qubit is None, then key should be a int and means which qubit to measure, otherwise, key should be a str and means the name of this measure gate.

  • obj_qubit (int) – Which qubit to measure. Default: None.

measure_all(subfix=None)[source]

Measure all qubits

Parameters

subfix (str) – The subfix string you want to add to the name of measure gate.

no_grad()[source]

Set all parameterized gate in this quantum circuit not require grad.

parameter_resolver()[source]

Get the parameter resolver of the whole circuit.

Note

This parameter resolver only tells you what are the parameters of this quantum circuit, and which part of parameters need grad, since the same parameter can be in different gate, and the coefficient can be different. The detail parameter resolver that shows the coefficient is in each gate of the circuit.

Returns

ParameterResolver, the parameter resolver of the whole circuit.

property parameterized

To check whether this circuit is a parameterized quantum circuit.

Returns

bool, whether this circuit is a parameterized quantum circuit.

property params_name

Get the parameter name of this circuit.

Returns

list, a list that contains the parameter name.

Examples

>>> from mindquantum.core.gates import RX
>>> from mindquantum.core.circuit import Circuit
>>> circuit = Circuit(RX({'a': 1, 'b': 2}).on(0))
>>> circuit.params_name
['a', 'b']
phase_shift(para, obj_qubits, ctrl_qubits=None)[source]

Add a Phase Shift gate.

Parameters
  • para (Union[dict, ParameterResolver]) – The parameter for PhaseShift gate.

  • obj_qubits (Union[int, list[int]]) – The object qubits of PhaseShift gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of PhaseShift gate. Default: None.

remove_barrier()[source]

Remove all barrier gates

remove_measure()[source]

Remove all measure gate.

remove_measure_on_qubits(qubits)[source]

Remove all measure gate on some certain qubits.

Parameters

qubit (Union[int, list[int]]) – The qubits you want to remove measure.

Examples

>>> from mindquantum import UN, H, Measure
>>> circ = UN(H, 3).x(0, 1).x(1, 2).measure_all()
>>> circ += H.on(0)
>>> circ += Measure('q0_1').on(0)
>>> circ.remove_measure_on_qubits(0)
q0: ──H────X────H───────────

q1: ──H────●────X────M(q1)──

q2: ──H─────────●────M(q2)──
requires_grad()[source]

Set all parameterized gates in this quantum circuit require grad.

reverse_qubits()[source]

Flip the circuit to big endian.

Examples

>>> from mindquantum.core import Circuit
>>> circ = Circuit().h(0).x(2, 0).y(3).x(3, 2)
>>> circ
q0: ──H────●───────

q2: ───────X────●──

q3: ──Y─────────X──
>>> circ.reverse_qubits()
q0: ──Y─────────X──

q1: ───────X────●──

q3: ──H────●───────
rx(para, obj_qubits, ctrl_qubits=None)[source]

Add a RX gate.

Parameters
  • para (Union[dict, ParameterResolver]) – The parameter for RX gate.

  • obj_qubits (Union[int, list[int]]) – The object qubits of RX gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of RX gate. Default: None.

ry(para, obj_qubits, ctrl_qubits=None)[source]

Add a RY gate.

Parameters
  • para (Union[dict, ParameterResolver]) – The parameter for RY gate.

  • obj_qubits (Union[int, list[int]]) – The object qubits of RY gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of RY gate. Default: None.

rz(para, obj_qubits, ctrl_qubits=None)[source]

Add a RZ gate.

Parameters
  • para (Union[dict, ParameterResolver]) – The parameter for RZ gate.

  • obj_qubits (Union[int, list[int]]) – The object qubits of RZ gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of RZ gate. Default: None.

s(obj_qubits, ctrl_qubits=None)[source]

Add a S gate.

Parameters
  • obj_qubits (Union[int, list[int]]) – The object qubits of S gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of S gate. Default: None.

summary(show=True)[source]

Print the information about current circuit, including block number, gate number, non-parameterized gate number, parameterized gate number and the total parameters.

Parameters

show (bool) – whether to show the information. Default: True.

Examples

>>> from mindquantum import Circuit, RX, H
>>> circuit = Circuit([RX('a').on(1), H.on(1), RX('b').on(0)])
>>> circuit.summary()
=========Circuit Summary=========
|Total number of gates  : 3.    |
|Parameter gates        : 2.    |
|with 2 parameters are  : a, b. |
|Number qubit of circuit: 2     |
=================================
svg(style=None)[source]

Display current quantum circuit into SVG picture in jupyter notebook.

Parameters

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

swap(obj_qubits, ctrl_qubits=None)[source]

Add a SWAP gate.

Parameters
  • obj_qubits (Union[int, list[int]]) – The object qubits of SWAP gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of SWAP gate. Default: None.

un(gate, maps_obj, maps_ctrl=None)[source]

Map a quantum gate to different objective qubits and control qubits. Please refers to UN.

Parameters
  • gate (BasicGate) – The BasicGate you want to map.

  • map_obj (Union[int, list[int]]) – object qubits.

  • maps_ctrl (Union[int, list[int]]) – control qubits. Default: None.

x(obj_qubits, ctrl_qubits=None)[source]

Add a X gate.

Parameters
  • obj_qubits (Union[int, list[int]]) – The object qubits of X gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of X gate. Default: None.

xx(para, obj_qubits, ctrl_qubits=None)[source]

Add a XX gate.

Parameters
  • para (Union[dict, ParameterResolver]) – The parameter for XX gate.

  • obj_qubits (Union[int, list[int]]) – The object qubits of XX gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of XX gate. Default: None.

y(obj_qubits, ctrl_qubits=None)[source]

Add a Y gate.

Parameters
  • obj_qubits (Union[int, list[int]]) – The object qubits of Y gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of Y gate. Default: None.

yy(para, obj_qubits, ctrl_qubits=None)[source]

Add a YY gate.

Parameters
  • para (Union[dict, ParameterResolver]) – The parameter for YY gate.

  • obj_qubits (Union[int, list[int]]) – The object qubits of YY gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of YY gate. Default: None.

z(obj_qubits, ctrl_qubits=None)[source]

Add a Z gate.

Parameters
  • obj_qubits (Union[int, list[int]]) – The object qubits of Z gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of Z gate. Default: None.

zz(para, obj_qubits, ctrl_qubits=None)[source]

Add a ZZ gate.

Parameters
  • para (Union[dict, ParameterResolver]) – The parameter for ZZ gate.

  • obj_qubits (Union[int, list[int]]) – The object qubits of ZZ gate.

  • ctrl_qubits (Union[int, list[int]]) – the control qubits of ZZ gate. Default: None.

class mindquantum.core.circuit.SwapParts(a: Iterable, b: Iterable, maps_ctrl=None)[source]

Swap two different part of quantum circuit, with or without control qubits.

Parameters
  • a (Iterable) – The first part you need to swap.

  • b (Iterable) – The second part you need to swap.

  • maps_ctrl (int, Iterable) – Control the swap by a single qubit or by different qubits or just no control qubit. Default: None.

Examples

>>> from mindquantum import SwapParts
>>> SwapParts([1, 2], [3, 4], 0)
q0: ──●────●──
      │    │
q1: ──@────┼──
      │    │
q2: ──┼────@──
      │    │
q3: ──@────┼──

q4: ───────@──
class mindquantum.core.circuit.U3(a, b, c, obj_qubit=None)[source]

This circuit represent arbitrary single qubit gate.

Parameters

Examples

>>> from mindquantum.core import U3
>>> U3('a','b','c')
q0: ──RZ(a)────RX(-π/2)────RZ(b)────RX(π/2)────RZ(c)──
class mindquantum.core.circuit.UN(gate: BasicGate, maps_obj, maps_ctrl=None)[source]

Map a quantum gate to different objective qubits and control qubits.

Parameters
  • gate (BasicGate) – A quantum gate.

  • maps_obj (Union[int, list[int]]) – Objective qubits.

  • maps_ctrl (Union[int, list[int]]) – Control qubits. Default: None.

Returns

Circuit, Return a quantum circuit.

Examples

>>> from mindquantum.core import UN, X
>>> circuit1 = UN(X, maps_obj = [0, 1], maps_ctrl = [2, 3])
>>> print(circuit1)
q0: ──X───────

q1: ──┼────X──
      │    │
q2: ──●────┼──

q3: ───────●──
>>> from mindquantum.core import SWAP
>>> circuit2 = UN(SWAP, maps_obj =[[0, 1], [2, 3]]).x(2, 1)
>>> print(circuit2)
q0: ──@───────

q1: ──@────●──

q2: ──@────X──

q3: ──@───────
mindquantum.core.circuit.add_prefix(circuit_fn, prefix)[source]

Add a prefix on the parameter of a parameterized quantum circuit or a parameterized quantum operator (a function that can generate a parameterized quantum circuit).

Parameters
  • circuit_fn (Union[Circuit, FunctionType, MethodType]) – A quantum circuit, or a function that can generate a quantum circuit.

  • prefix (str) – The prefix you want to add to every parameters.

Raises
  • TypeError – If prefix is not a string.

  • TypeError – circuit_fn is not a Circuit or can not return a Circuit.

Returns

Circuit or a function that can generate a Circuit.

Examples

>>> from mindquantum.algorithm.library import qft
>>> from mindquantum.core.circuit import add_prefix
>>> from mindquantum import RX, H, Circuit
>>> u = lambda qubit: Circuit([H.on(0), RX('a').on(qubit)])
>>> u1 = u(0)
>>> u2 = add_prefix(u1, 'ansatz')
>>> u3 = add_prefix(u, 'ansatz')
>>> u3 = u3(0)
>>> u2
q0: ──H────RX(ansatz_a)──
>>> u3
q0: ──H────RX(ansatz_a)──
mindquantum.core.circuit.apply(circuit_fn, qubits)[source]

Apply a quantum circuit or a quantum operator (a function that can generate a quantum circuit) to different qubits.

Parameters
  • circuit_fn (Union[Circuit, FunctionType, MethodType]) – A quantum circuit, or a function that can generate a quantum circuit.

  • qubits (list[int]) – The new qubits that you want to apply.

Raises
  • TypeError – If qubits is not a list.

  • ValueError – If any element of qubits is negative.

  • TypeError – If circuit_fn is not Circuit or can not return a Circuit.

Returns

Circuit or a function that can generate a Circuit.

Examples

>>> from mindquantum.algorithm.library import qft
>>> from mindquantum.core.circuit import apply
>>> u1 = qft([0, 1])
>>> u2 = apply(u1, [1, 0])
>>> u3 = apply(qft, [1, 0])
>>> u3 = u3([0, 1])
>>> u2
q0: ──────────●───────H────@──
              │            │
q1: ──H────PS(π/2)─────────@──
>>> u3
q0: ──────────●───────H────@──
              │            │
q1: ──H────PS(π/2)─────────@──
mindquantum.core.circuit.change_param_name(circuit_fn, name_map)[source]

Change the parameter name of a parameterized quantum circuit or a parameterized quantum operator (a function that can generate a parameterized quantum circuit).

Parameters
  • circuit_fn (Union[Circuit, FunctionType, MethodType]) – A quantum circuit, or a function that can generate a quantum circuit.

  • name_map (dict) – The parameter name mapping dict.

Raises
  • TypeError – If name_map is not a map.

  • TypeError – If key of name_map is not string.

  • TypeError – If value of name_map is not string.

  • TypeError – If circuit_fn is not a Circuit or can not return a Circuit.

Returns

Circuit or a function that can generate a Circuit.

Examples

>>> from mindquantum.algorithm.library import qft
>>> from mindquantum.core.circuit import change_param_name
>>> from mindquantum import RX, H, Circuit
>>> u = lambda qubit: Circuit([H.on(0), RX('a').on(qubit)])
>>> u1 = u(0)
>>> u2 = change_param_name(u1, {'a': 'b'})
>>> u3 = change_param_name(u, {'a': 'b'})
>>> u3 = u3(0)
>>> u2
q0: ──H────RX(b)──
>>> u3
q0: ──H────RX(b)──
mindquantum.core.circuit.controlled(circuit_fn)[source]

Add control qubits on a quantum circuit or a quantum operator (a function that can generate a quantum circuit)

Parameters

circuit_fn (Union[Circuit, FunctionType, MethodType]) – A quantum circuit, or a function that can generate a quantum circuit.

Raises

TypeError – circuit_fn is not a Circuit or can not return a Circuit.

Returns

function that can generate a Circuit.

Examples

>>> from mindquantum.algorithm.library import qft
>>> from mindquantum.core.circuit import controlled
>>> u1 = qft([0, 1])
>>> u2 = controlled(u1)
>>> u3 = controlled(qft)
>>> u3 = u3(2, [0, 1])
>>> u2(2)
q0: ──H────PS(π/2)─────────@──
      │       │            │
q1: ──┼───────●───────H────@──
      │       │       │    │
q2: ──●───────●───────●────●──
>>> u3
q0: ──H────PS(π/2)─────────@──
      │       │            │
q1: ──┼───────●───────H────@──
      │       │       │    │
q2: ──●───────●───────●────●──
mindquantum.core.circuit.dagger(circuit_fn)[source]

Get the hermitian dagger of a quantum circuit or a quantum operator (a function that can generate a quantum circuit)

Parameters

circuit_fn (Union[Circuit, FunctionType, MethodType]) – A quantum circuit, or a function that can generate a quantum circuit.

Raises

TypeError – If circuit_fn is not a Circuit or can not return a Circuit.

Returns

Circuit or a function that can generate Circuit.

Examples

>>> from mindquantum.algorithm.library import qft
>>> from mindquantum.core.circuit import dagger
>>> u1 = qft([0, 1])
>>> u2 = dagger(u1)
>>> u3 = dagger(qft)
>>> u3 = u3([0, 1])
>>> u2
q0: ──@─────────PS(-π/2)────H──
      │            │
q1: ──@────H───────●───────────
>>> u3
q0: ──@─────────PS(-π/2)────H──
      │            │
q1: ──@────H───────●───────────
mindquantum.core.circuit.decompose_single_term_time_evolution(term, para)[source]

Decompose a time evolution gate into basic quantum gates.

This function only work for the hamiltonian with only single pauli word. For example, exp(-i * t * ham), ham can only be a single pauli word, such as ham = X0 x Y1 x Z2, and at this time, term will be ((0, ‘X’), (1, ‘Y’), (2, ‘Z’)). When the evolution time is expressd as t = a*x + b*y, para would be {‘x’:a, ‘y’:b}.

Parameters
Returns

Circuit, a quantum circuit.

Raises

Example

>>> from mindquantum.core.operators import QubitOperator
>>> from mindquantum.core.circuit import decompose_single_term_time_evolution
>>> ham = QubitOperator('X0 Y1')
>>> circuit = decompose_single_term_time_evolution(ham, {'a':1})
>>> print(circuit)
q0: ─────H───────●───────────────●───────H──────
                 │               │
q1: ──RX(π/2)────X────RZ(2*a)────X────RX(7π/2)──
mindquantum.core.circuit.pauli_word_to_circuits(qubitops)[source]

Convert a single pauli word qubit operator to a quantum circuit.

Parameters

qubitops (QubitOperator, Hamiltonian) – The single pauli word qubit operator.

Returns

Circuit, a quantum circuit.

Raises
  • TypeError – If qubitops is not a QubitOperator or a Hamiltonian.

  • ValueError – If qubitops is Hamiltonian but not in origin mode.

  • ValueError – If qubitops has more than one pauliwords.

Examples

>>> from mindquantum.core import X
>>> from mindquantum.core.operators import QubitOperator
>>> from mindquantum.core.circuit import pauli_word_to_circuits
>>> qubitops = QubitOperator('X0 Y1')
>>> pauli_word_to_circuits(qubitops) + X(1, 0)
q0: ──X────●──

q1: ──Y────X──
mindquantum.core.circuit.shift(circ, p)[source]

Shift the qubit range of the given circuit.

Parameters
  • circ (circuit) – The circuit that you want to do shift operator.

  • p (int) – The qubit distance you want to shift.

Examples

>>> from mindquantum.core.circuit import shift
>>> from mindquantum.core.circuit import Circuit
>>> circ = Circuit().x(1, 0)
>>> circ
q0: ──●──

q1: ──X──
>>> shift(circ, 1)
q1: ──●──

q2: ──X──
Returns

Circuit, the shifted circuit.

functional

The functional operators are shortcut of some pre-instantiated quantum circuit operators.

functional

high level circuit operators

mindquantum.core.circuit.C

mindquantum.core.circuit.controlled

mindquantum.core.circuit.D

mindquantum.core.circuit.dagger

mindquantum.core.circuit.A

mindquantum.core.circuit.apply

mindquantum.core.circuit.AP

mindquantum.core.circuit.add_prefix

mindquantum.core.circuit.CPN

mindquantum.core.circuit.change_param_name