# How to calculate quantum circuit with given quantum state?

I have task to calculate this quantum circuit

Where psi is:

x1 = 5
x2 = 1
r = x1 * x1 + x2 * x2
a = np.sqrt(1 + 2*r)
psi = [0, 0, 0.5, 0, 0, -0.5, 0, 0, 1/(np.sqrt(2)*a), 0, x1/(np.sqrt(2)*a), x2/(np.sqrt(2)*a), x1/(np.sqrt(2)*a), x2/(np.sqrt(2)*a), 0, 0]


I am doing this type of code:

circ = QuantumCircuit(4)

circ.h(0)

meas = QuantumCircuit(4, 4)
meas.barrier(range(4))
# map the quantum measurement to the classical bits
meas.measure(range(4), range(4))

# The Qiskit circuit object supports composition using
qc = circ + meas
qc.initialize(psi, 4)
#drawing the circuit
backend_sim = Aer.get_backend('qasm_simulator')

# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
qc.draw('mpl')

job_sim = execute(qc, backend_sim, shots=1000)

# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)


But getting this error:

CircuitError: 'Index out of range.'


If I change qc.initialize like this:

qc.initialize(psi, 3)


I get this:

QiskitError: 'Initialize parameter vector has 16 elements, therefore expects 4 qubits. However, 1 were provided.'


As stated here, for initialization, you should make it as a list. Hence for your case, since it only uses 4 qubits, you could write

qc.initialize(psi, [0,1,2,3])


However, your circuit seems to be a bit off: the resulting circuit of yours would be a Hadamard gate first, followed by a series of measurements, and then the initialization at the end.

To build the circuit as in your picture, this code will do:

qc = QuantumCircuit(4)

qc.initialize(psi, [0,1,2,3])

qc.h(0)

qc.measure_all()


The resulting circuit would be: