mindquantum.nn.MindQuantumAnsatzOnlyLayer

class mindquantum.nn.MindQuantumAnsatzOnlyLayer(param_names, circuit, measurements, weight_init='normal', n_threads=1)[source]

An ansatz only trainable Mindquantum layer.

A mindquantum layer simulate a parameterized quantum circuit and get the measurement result. The quantum circuit is construct only by an ansatz circuit.

Parameters
  • param_names (list[str]) – Parameters names of ansatz circuit. The order of this parameters is the same as the order of trainable parameters.

  • circuit (Circuit) – The ansatz circuit.

  • measurements (Union[Hamiltonian, list[Hamiltonian], Projector, list[Projector]]) – Hamiltonian or a list of Hamiltonian for measurement.

  • weight_init (Union[Tensor, str, Initializer, numbers.Number]) – The trainable weight_init parameter. The dtype is same as input x. The values of str refer to the function initializer. Default: ‘normal’.

  • n_threads (int) – Number of threads for data parallel. Default: 1.

Inputs:

No inputs needed.

Outputs:

Tensor of shape \((1, 1)\).

Supported Platforms:

CPU

Examples

>>> from mindquantum import Circuit, H, RX, RY, RZ, Hamiltonian
>>> from mindquantum.nn import MindQuantumAnsatzOnlyLayer
>>> from mindquantum.ops import QubitOperator
>>> from mindspore import Tensor
>>> import mindspore.nn as nn
>>> import numpy as np
>>> circuit = Circuit([H.on(0), RZ(0.4).on(0), RX('a').on(0), RY('b').on(0)])
>>> ham = Hamiltonian(QubitOperator('Z0'))
>>> init = Tensor(np.array([0, 0]).astype(np.float32))
>>> net = MindQuantumAnsatzOnlyLayer(circuit.para_name, circuit, ham, init)
>>> opti = nn.Adam(net.trainable_params(), learning_rate=0.8)
>>> train_net = nn.TrainOneStepCell(net, opti)
>>> for i in range(1000):
...     train_net()
>>> net()
Tensor(shape=[1, 1], dtype=Float32, value=
[[-1.00000000e+00]])
>>> net.weight.asnumpy()
array([-4.712389 ,  1.9707963], dtype=float32)
final_state(measurements=None)[source]

Get the quantum state after evolution.

Parameters

measurements (Hamiltonian) – Hamiltonian for measurement. If None, no hamiltonians will be used. Default: None.

Returns

numpy.ndarray, the final quantum state.