mindquantum

mindquantum.circuit

Circuit.

Quantum circuit module.

class mindquantum.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.

Examples

>>> circuit1 = Circuit()
>>> circuit1 += RX('a').on(0)
>>> circuit1 *= 2
>>> print(circuit1)
RX(a|0)
RX(a|0)
>>> 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 |
=============================
property hermitian

Get the hermitian of this quantum circuit.

Examples

>>> 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
mindspore_data()[source]

Serialize the circuit. The result can be used by QNN operators.

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.

requires_grad()[source]

Set all parameterized gates in this quantum circuit require grad.

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.

Examples

>>> circuit = Circuit([RX('a').on(1), H.on(1), RX('b').on(0)])
>>> circuit.summary()
========Circuit Summary========
|Total number of gates:3.     |
|Blocks               :1.     |
|Non parameter gates  :1.     |
|Parameter gates      :2.     |
|with 2 parameters are: b, a. |
===============================
class mindquantum.circuit.SwapParts(a: collections.abc.Iterable, b: collections.abc.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

>>> SwapParts([1, 2], [3, 4], 0)
SWAP(1 3 <-: 0)
SWAP(2 4 <-: 0)
class mindquantum.circuit.UN(gate: mindquantum.gate.basic.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.

Returns

Circuit, Return a quantum circuit.

Examples

>>> circuit1 = UN(X, maps_obj = [0, 1], maps_ctrl = [2, 3])
>>> print(circuit1)
X(0 <-: 2)
X(1 <-: 3)
>>> circuit2 = UN(SWAP, maps_obj =[[0, 1], [2, 3]])
>>> print(circuit2)
SWAP(0 1)
SWAP(2 3)
mindquantum.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
  • term (tuple, QubitOperator) – the hamiltonian term of just the evolution qubit operator.

  • para (dict) – the parameters of evolution operator.

Returns

Circuit, a quantum circuit.

Example

>>> from projectq.ops import QubitOperator
>>> ham = QubitOperator('X0 Y1')
>>> circuit = decompose_single_term_time_evolution(ham, {'a':1})
>>> print(circuit)
H(0)
RX(1.571,1)
X(1 <-: 0)
RZ(a|1)
X(1 <-: 0)
RX(10.996,1)
H(0)
mindquantum.circuit.generate_uccsd(filename, th=0)[source]

Generate a uccsd quantum circuit based on a molecular data generated by HiQfermion or openfermion.

Parameters
  • filename (str) – the name of the molecular data file.

  • th (int) – the threshold to filt the uccsd amplitude. When th < 0, we will keep all amplitudes. When th == 0, we will keep all amplitude that are positive.

Returns

  • uccsd_circuit (Circuit), the ansatz circuit generated by uccsd method.

  • initial_amplitudes (numpy.ndarray), the initial parameter values of uccsd circuit.

  • parameters_name (list[str]), the name of initial parameters.

  • qubit_hamiltonian (QubitOperator), the hamiltonian of the molecule.

  • n_qubits (int), the number of qubits in simulation.

  • n_electrons, the number of electrons of the molecule.

mindquantum.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.

Examples

>>> from openfermion.ops import QubitOperator
>>> qubitops = QubitOperator('X0 Y1')
>>> pauli_word_to_circuits(qubitops)
X(0)
Y(1)

mindquantum.engine

Circuit engine module.

class mindquantum.engine.BasicQubit(qubit_id, circuit=None)[source]

A quantum qubit.

Parameters
  • qubit_id (int) – The id of this quantum qubit.

  • circuit (Circuit) – The quantum circuit that this qubit belongs to.

property circuit

Get the quantum circuit that this qubit belongs to.

class mindquantum.engine.CircuitEngine[source]

A simple circuit engine that allows you to generate quantum circuit as projectq style.

Note

For more usage, please refers to CircuitEngine.generator

allocate_qubit()[source]

Allocate a quantum qubit.

allocate_qureg(n)[source]

Allocate a quantum register.

Parameters

n (int) – Number of quantum qubits.

property circuit

Get the quantum circuit that construct by this engin.

static generator(n_qubits, *args, **kwds)[source]

Quantum circuit register.

Parameters

n_qubits (int) – qubit number of quantum circuit.

Examples

>>> import mindquantum.gate as G
>>> from mindquantum.engine import circuit_generator
>>> @circuit_generator(2,prefix='p')
>>> def ansatz(qubits, prefix):
>>>     G.X | (qubits[0], qubits[1])
>>>     G.RX(prefix+'_0') | qubits[1]
>>> print(ansatz)
X(1 <-: 0)
RX(p_0|1)
>>> print(type(ansatz))
<class 'mindquantum.circuit.circuit.Circuit'>

mindquantum.gate

Gate.

Gate provides different quantum gate.

class mindquantum.gate.BasicGate(name, isparameter=False)[source]

BasicGate is the base class of all gaets.

abstract define_projectq_gate()[source]

Define the corresponded projectq gate.

generate_description()[source]

Description generator.

abstract hermitian()[source]

Return the hermitian gate of this gate.

abstract matrix(*args)[source]

The matrix of the gate.

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 qbits. Defaults to None.

Returns

Gate, Return a new gate.

Examples

>>> x = X.on(1)
>>> x.obj_qubits
[1]
>>> x.ctrl_qubits
[]
>>> x = X.on(2, [0, 1])
>>> x.ctrl_qubits
[0, 1]
class mindquantum.gate.CNOTGate[source]

Control-X gate.

More usage, please see mindquantum.gate.XGate.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.HGate[source]

Hadamard gate with matrix as:

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

More usage, please see mindquantum.gate.XGate.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.Hamiltonian(hamiltonian)[source]

A QubitOperator hamiltonian wrapper.

Parameters

hamiltonian (QubitOperator) – The pauli word qubit operator.

Examples

>>> from projectq.ops import QubitOperator
>>> ham = Hamiltonian(QubitOperator('Z0 Y1', 0.3))
>>> ham.mindspore_data()
{'hams_pauli_coeff': [0.3],
 'hams_pauli_word': [['Z', 'Y']],
 'hams_pauli_qubit': [[0, 1]]}
mindspore_data()[source]

Generate hamiltonian information for PQC operator.

class mindquantum.gate.IGate[source]

Identity gate with matrix as:

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

More usage, please see mindquantum.gate.XGate.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.IntrinsicOneParaGate(name, coeff=None)[source]

The parameterized gate that can be intrinsicly described by only one parameter.

Note

A parameterized gate can also be a non parameterized gate, if the parameter you send in is only a number.

Examples

>>> rx1 = RX(1.2)
>>> rx1
RX(1.2)
>>> rx2 = RX({'a' : 0.5})
>>> rx2.coeff
{'a': 0.5}
>>> rx2.linearcombination(rx2.coeff,{'a' : 3})
1.5
diff_matrix(*paras_out, about_what=None)[source]

The differential form of this parameterized gate.

Parameters

about_what (str, optional) – Specific the differential is about which parameter. Defaults to None.

Returns

numpy.ndarray, Return the numpy array of the differential matrix.

Examples

>>> rx = RX('a')
>>> np.round(rx.diff_matrix({'a' : 2}), 2)
array([[-0.42+0.j  ,  0.  -0.27j],
       [ 0.  -0.27j, -0.42+0.j  ]])
hermitian()[source]

Get the mermitian gate of this parameterized gate.

Note

We only set the coeff to -coeff.

matrix(*paras_out)[source]

The matrix of parameterized gate.

Note

If the parameterized gate convert to non parameterized gate, then you don’t need any parameters to get this matrix.

Returns

np.array, Return the numpy array of the matrix.

Examples

>>> rx1 = RX(0)
>>> rx1.matrix()
array([[1.+0.j, 0.-0.j],
       [0.-0.j, 1.+0.j]])
>>> rx2 = RX({'a' : 1.2})
>>> np.round(rx2.matrix({'a': 2}), 2)
array([[0.36+0.j  , 0.  -0.93j],
       [0.  -0.93j, 0.36+0.j  ]])
class mindquantum.gate.NoneParameterGate(name)[source]

The basic class of gate that is not parametrized.

hermitian()[source]

Get hermitian gate of this none parameterized gate.

matrix(*args)[source]

Get the matrix of this none parameterized gate.

class mindquantum.gate.ParameterGate(name, coeff=None)[source]

The basic class of gate that is parameterized.

static linearcombination(coeff_in, paras_out)[source]

Combine the parameters and coefficient.

Parameters
Returns

float, Multiply the values of the common keys of these two dicts.

no_grad()[source]

All parameters do not need grad.

no_grad_part(names)[source]

Set certain parameters that not need grad.

Parameters

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

requires_grad()[source]

All parameters requires grad.

requires_grad_part(names)[source]

Set certain parameters that need grad.

Parameters

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

class mindquantum.gate.PhaseShift(coeff=None)[source]

Phase shift gate.

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

More usage, please see mindquantum.gate.RX.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.Power(gate: mindquantum.gate.basic.NoneParameterGate, t=erGate, t0.5)[source]

Power operator on a non parameterized gate.

Parameters

Examples

>>> rx1 = RX(0.5)
>>> rx2 = RX(1)
>>> assert np.all(np.isclose(Power(rx2,0.5).matrix(), rx1.matrix()))
define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.RX(coeff=None)[source]

Rotation gate around x-axis.

\[\begin{split}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 coefficience is one.

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

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

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

Examples

>>> 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(a 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}
define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.RY(coeff=None)[source]

Rotation gate around z-axis.

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

More usage, please see mindquantum.gate.RX.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.RZ(coeff=None)[source]

Rotation gate around z-axis.

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

More usage, please see mindquantum.gate.RX.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.SWAPGate[source]

SWAP gate that swap two different qubits.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.UnivMathGate(name, mat)[source]

Universal math gate.

More usage, please see mindquantum.gate.XGate.

Examples

>>> 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)
define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.XGate[source]

Pauli X gate with matrix as:

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

Note

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

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

Examples

>>> 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(6.283)
>>> (x1**'a').coeff
{'a': 3.141592653589793}
>>> (x1**{'a' : 2}).coeff
{'a': 6.283185307179586}
define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.XX(coeff=None)[source]

Ising XX gate.

\[XX_\theta=\cos(\theta)I\otimes I-i\sin(\theta)\sigma_x\otimes\sigma_x\]

More usage, please see mindquantum.gate.RX.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.YGate[source]

Pauli Y gate with matrix as:

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

More usage, please see mindquantum.gate.XGate.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.YY(coeff=None)[source]

Ising YY gate.

\[YY_\theta=\cos(\theta)I\otimes I-i\sin(\theta)\sigma_y\otimes\sigma_y\]

More usage, please see mindquantum.gate.RX.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.ZGate[source]

Pauli Z gate with matrix as:

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

More usage, please see mindquantum.gate.XGate.

define_projectq_gate()[source]

Define the corresponded projectq gate.

class mindquantum.gate.ZZ(coeff=None)[source]

Ising ZZ gate.

\[ZZ_\theta=\cos(\theta)I\otimes I-i\sin(\theta)\sigma_Z\otimes\sigma_Z\]

More usage, please see mindquantum.gate.RX.

define_projectq_gate()[source]

Define the corresponded projectq gate.

functional

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

functional

gates

mindquantum.gate.CNOT

mindquantum.gate.CNOTGate

mindquantum.gate.I

mindquantum.gate.IGate

mindquantum.gate.H

mindquantum.gate.HGate

mindquantum.gate.S

mindquantum.gate.PhaseShift (numpy.pi/2)

mindquantum.gate.SWAP

mindquantum.gate.SWAPGate

mindquantum.gate.X

mindquantum.gate.XGate

mindquantum.gate.Y

mindquantum.gate.YGate

mindquantum.gate.Z

mindquantum.gate.ZGate

mindquantum.nn

Quantum neural networks operators and cells.

mindquantum.nn.generate_evolution_operator(param_names, circuit: mindquantum.circuit.circuit.Circuit, hams=None)[source]

A method to generate a parameterized quantum circuit simulation operator.

Parameters
  • param_names (list[str]) – The list of parameter names.

  • circuit (Circuit) – The whole circuit combined with encoder circuit and ansatz circuit.

  • hams (Union[Hamiltonian, list[Hamiltonian]]) – The measurement hamiltonian.

Returns

Evolution, A parameterized quantum circuit simulator operator supported by mindspore framework.

Examples

>>> import numpy as np
>>> from mindspore import Tensor
>>> import mindquantum.gate as G
>>> from mindquantum import Circuit
>>> circ = Circuit(G.RX('a').on(0))
>>> evol = generate_evolution_operator(['a'], circ)
>>> state = evol(Tensor(np.array([0.5]).astype(np.float32)))
>>> state = state.asnumpy()
>>> state = state[:, 0] + 1j * state[:, 1]
array([0.9689124+0.j        , 0.       -0.24740396j], dtype=complex64)
>>> G.RX(0.5).matrix()[:, 0]
array([0.96891242+0.j        , 0.        -0.24740396j])
mindquantum.nn.generate_pqc_operator(encoder_params_names, ansatz_params_names, circuit: mindquantum.circuit.circuit.Circuit, hams, n_threads=1)[source]

A method to generate a parameterized quantum circuit simulation operator.

Parameters
  • encoder_params_names (list[str]) – The list of parameter names for encoder circuit.

  • ansatz_params_names (list[str]) – The list of parameter names for ansatz circuit.

  • circuit (Circuit) – The whole circuit combined with encoder circuit and ansatz circuit.

  • hams (Union[Hamiltonian, list[Hamiltonian]]) – The measurement hamiltonian.

  • n_threads (int) – Number of threads for data parallelize.

Returns

PQC, A parameterized quantum circuit simulator operator supported by mindspore framework.

Examples

>>> from projectq.ops import QubitOperator
>>> from mindquantum import Circuit
>>> import mindquantum.gate as G
>>> encoder_circ = Circuit([G.RX('a').on(0)])
>>> ansatz_circ = Circuit([G.RY('b').on(0)])
>>> circ = encoder_circ + ansatz_circ
>>> ham = G.Hamiltonian(QubitOperator('Z0'))
>>> pqc = generate_pqc_operator(['a'], ['b'], circ, ham)

Operators

API Name

Description

Supported Platforms

mindquantum.nn.Evolution

Inputs of this operation is generated by MindQuantum framework.

CPU

mindquantum.nn.MindQuantumLayer

A trainable Mindquantum layer.

CPU

mindquantum.nn.PQC

Evaluate a parameterized quantum circuit and calculate the gradient of each parameters.

CPU

mindquantum.parameterresolver

Parameter resolver.

class mindquantum.parameterresolver.ParameterResolver(data=None)[source]

A ParameterRsolver can set the parameter of parameterized quantum gate or parameterized quantum circuit.

By specific which part of parameters needs to calculate gradient, the PQC operator can only calculate gradient of these parameters.

Parameters

data (dict) – initial parameter names and its values.

Examples

>>> pr = ParameterResolver({'a': 0.3})
>>> pr['b'] = 0.5
>>> pr.no_grad_part('a')
>>> pr *= 2
>>> pr
{'a': 0.6, 'b': 1.0}
>>> pr.no_grad_parameters
{'a'}
mindspore_data()[source]

Generate data for PQC operator.

Returns

Dict.

no_grad()[source]

Set all parameters to not require gradient calculation.

Returns

mindquantum.parameterresolver.ParameterResolver

Examples

>>> pr = ParameterResolver({'a': 1, 'b': 2})
>>> pr.no_grad()
>>> pr.requires_grad_parameters
set()
no_grad_part(*names)[source]

Set part of parameters that not requires grad.

Parameters

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

Returns

mindquantum.parameterresolver.ParameterResolver

Examples

>>> pr = ParameterResolver({'a': 1, 'b': 2})
>>> pr.no_grad_part('a')
>>> pr.requires_grad_parameters
{'b'}
property para_name

Get the parameters name.

Returns

list[str], Parameters name.

Examples

>>> pr = ParameterResolver({'a': 1, 'b': 2})
>>> pr.para_name
['a', 'b']
property para_value

Get the parameters value.

Returns

list[float], Parameters value.

Examples

>>> pr = ParameterResolver({'a': 1, 'b': 2})
>>> pr.para_value
[1, 2]
requires_grad()[source]

Set all parameters of this parameter resolver to require gradient calculation.

Returns

mindquantum.parameterresolver.ParameterResolver

Examples

>>> pr = ParameterResolver({'a': 1, 'b': 2})
>>> pr.no_grad_part('a')
>>> pr.requires_grad()
>>> pr.requires_grad_parameters
{'a', 'b'}
requires_grad_part(*names)[source]

Set part of parameters that requires grad.

Parameters

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

Returns

mindquantum.parameterresolver.ParameterResolver

Examples

>>> pr = ParameterResolver({'a': 1, 'b': 2})
>>> pr.no_grad()
>>> pr.requires_grad_part('a')
>>> pr.requires_grad_parameters
{'a'}
update(others)[source]

Update this parameter resolver with other parameter resolver.

Parameters

others (mindquantum.parameterresolver.ParameterResolver) – other parameter resolver.

Raises

ValueError – If some parameters require grad and not require grad in other parameter resolver and vise versa.

Examples

>>> pr1 = ParameterResolver({'a': 1})
>>> pr2 = ParameterResolver({'b': 2})
>>> pr2.no_grad()
>>> pr1.update(pr2)
>>> pr1
{'a': 1, 'b': 2}
>>> pr1.no_grad_parameters
{'b'}

mindquantum.utils

Utils

mindquantum.utils.bprint(strings: list, align=':', title='', v_around='=', h_around='|', fill_char=' ')[source]

Print the information in block shape.

Parameters
  • strings (list[str]) – Information you want to output.

  • align (str) – The align char alone vertal direction.

  • title (str) – The title of this information block.

  • v_around (str) – Vertical boundary char.

  • h_around (str) – horizontal boundary char.

  • fill_char (str) – Empty space fill with this char.

Returns

list(str), Formatted string.

Examples

>>> title='Info of Bob'
>>> o = bprint(['Name:Bob', 'Age:17', 'Nationality:China'],
>>>     title=title)
>>> for i in o:
>>>     print(i)
====Info of Bob====
|Name       :Bob  |
|Age        :17   |
|Nationality:China|
===================
mindquantum.utils.mod(vec_in, axis=0)[source]

Calculate the mod of input vectors.

Parameters
  • vec_in (Union[list[number], numpy.ndarray]) – The vector you want to calculate mod.

  • axis (int) – Along which axis you want to calculate mod.

Returns

numpy.ndarray, The mod of input vector.

Examples

>>> vec_in = np.array([[1, 2, 3], [4, 5, 6]])
>>> mod(vec_in)
array([[4.12310563, 5.38516481, 6.70820393]])
>>> mod(vec_in, 1)
array([[3.74165739],
       [8.77496439]])
mindquantum.utils.normalize(vec_in, axis=0)[source]

Normalize the input vectors based on specified axis.

Parameters
  • vec_in (Union[list[number], numpy.ndarray]) – Vector you want to normalize.

  • axis (int) – Along which axis you want to normalize your vector.

Returns

numpy.ndarray, Vector after normalization.

Examples

>>> vec_in = np.array([[1, 2, 3], [4, 5, 6]])
>>> normalize(vec_in)
array([[0.24253563, 0.37139068, 0.4472136 ],
       [0.9701425 , 0.92847669, 0.89442719]])
>>> normalize(vec_in, 1)
array([[0.26726124, 0.53452248, 0.80178373],
       [0.45584231, 0.56980288, 0.68376346]])
mindquantum.utils.random_state(shapes, norm_axis=0, comp=True, seed=None)[source]

Generate some random quantum state.

Parameters
  • shapes (tuple) – shapes = (m, n) means m quantum states with each state formed by log2(n) qubits.

  • norm_axis (int) – which axis you want to apply normalization. Default, 0

  • comp (bool) – if True, each amplitude of the quantum state will be a complex number.

  • seed (int) – the random seed.

Returns

numpy.ndarray, A normalized random quantum state.

Examples

>>> random_state((2, 2), seed=42)
array([[0.44644744+0.18597239j, 0.66614846+0.10930256j],
       [0.87252821+0.06923499j, 0.41946926+0.60691409j]])