def test_statefn_overlaps(self): """ state functions overlaps test """ wf = (4 * StateFn({'101010': .5, '111111': .3})) + ((3 + .1j) * (Zero ^ 6)) wf_vec = StateFn(wf.to_matrix()) self.assertAlmostEqual(wf.adjoint().eval(wf), 14.45) self.assertAlmostEqual(wf_vec.adjoint().eval(wf_vec), 14.45) self.assertAlmostEqual(wf_vec.adjoint().eval(wf), 14.45) self.assertAlmostEqual(wf.adjoint().eval(wf_vec), 14.45)
def test_wf_evals_x(self): """ wf evals x test """ qbits = 4 wf = ((Zero ^ qbits) + (One ^ qbits)) * (1 / 2**.5) # Note: wf = Plus^qbits fails because TensoredOp can't handle it. wf_vec = StateFn(wf.to_matrix()) op = X ^ qbits # op = I^6 self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 1) self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 1) self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 1) self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 1) # op = (H^X^Y)^2 op = H ^ 6 wf = ((Zero ^ 6) + (One ^ 6)) * (1 / 2**.5) wf_vec = StateFn(wf.to_matrix()) # print(wf.adjoint().to_matrix() @ op.to_matrix() @ wf.to_matrix()) self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), .25) self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), .25) self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), .25) self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), .25)
qp2ising = QuadraticProgramToIsing() # convert to Ising Hamiltonian H, offset = qp2ising.encode(qp) op = H.to_pauli_op() help(H) print(H) # Prepare the state qc = QuantumCircuit(3) qc.h(0) qc.cx(0, 1) qc.cy(1, 2) psi = StateFn(qc) # wrap it into a statefunction print(psi) # Calculate the expectation value for Ising Hamiltonian print('expectation_value:', psi.adjoint().compose(op).compose(psi).eval().real) # %% another way of calculating expectation # define your backend or quantum instance (where you can add settings) backend = Aer.get_backend('qasm_simulator') q_instance = QuantumInstance(backend, shots=1024) # define the state to sample measurable_expression = StateFn(op, is_measurement=True).compose(psi) # convert to expectation value expectation = PauliExpectation().convert(measurable_expression) # get state sampler (you can also pass the backend directly)