mindquantum.framework.MQN2AnsatzOnlyOps

class mindquantum.framework.MQN2AnsatzOnlyOps(expectation_with_grad)[source]

MindQuantum operator that get the square of absolute value of expectation of a hamiltonian on a quantum state evaluated by a parameterized quantum circuit (PQC). This PQC should contains an ansatz circuit only. This ops is PYNATIVE_MODE supported only.

Parameters

expectation_with_grad (GradOpsWrapper) – a grad ops that receive encoder data and ansatz data and return the square of absolute value of expectation value and gradient value of parameters respect to expectation.

Inputs:
  • ans_data (Tensor) - Tensor with shape \(N\) for ansatz circuit, where \(N\) means the number of ansatz parameters.

Outputs:

Tensor, The square of absolute value of expectation value of the hamiltonian.

Supported Platforms:

GPU, CPU

Examples

>>> import numpy as np
>>> from mindquantum import Circuit, Hamiltonian, QubitOperator
>>> from mindquantum import Simulator, MQN2AnsatzOnlyOps
>>> import mindspore as ms
>>> ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target="CPU")
>>> circ = Circuit().ry('a', 0).h(0).rx('b', 0)
>>> ham = Hamiltonian(QubitOperator('Z0'))
>>> sim = Simulator('projectq', 1)
>>> grad_ops = sim.get_expectation_with_grad(ham, circ)
>>> data = np.array([0.1, 0.2])
>>> f, g = grad_ops(data)
>>> np.abs(f) ** 2
array([[0.00957333]])
>>> net = MQN2AnsatzOnlyOps(grad_ops)
>>> f_ms = net(ms.Tensor(data))
>>> f_ms
Tensor(shape=[1], dtype=Float32, value= [ 9.57333017e-03])