# How to create an arbitrary state in QISKit for a local_qasm_simulator?

I would like to play with a quantum circuit local_qasm_simulator in QISKit, but I do not want to implement a separate quantum circuit that would prepare an initial state.

The way I do it now is by falling back to NumPy. Specifically, first, I extract matrix u from a quantum program qp:

cname = 'circuit name'
results = qp.execute(cname, backend='local_unitary_simulator', shots=1)
data = results.get_data(cname)
u = data['unitary']


Then, I explicitly create the state I need (e.g., $|\psi\rangle = \frac{1}{2}(|00\rangle + |01\rangle + |10\rangle - |11\rangle)$):

num_qubits = 2
psi = np.ones(2**num_qubits) / 2.0
psi[3] = -psi[3]


Finally, I apply u to psi with NumPy:

u @ psi


The advantage of this approach is that I can explicitly obtain the state $U |\psi\rangle$. However, I cannot use local_qasm_simulator and the measure() function.

So, how could I prepare an arbitrary state, and supply it to a circuit, and run a local_qasm_simulator?

## 1 Answer

I think you can use the initialize function as detailed at the section "Arbitrary Initialization" at this tutorial.

As an example, this tutorial explicitly shows how to initialize the three qubit state

$$\frac{i}{\sqrt{16}} | 000 \rangle + \frac{1}{\sqrt{8}} | 001 \rangle + \frac{1+i}{\sqrt{16}} | 010 \rangle + \frac{1+2i}{\sqrt{8}} | 101 \rangle + \frac{1}{\sqrt{16}} | 110 \rangle .$$

Which is done using the following lines of QISKit code.

import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
initialize_circuit_3q = Q_program.create_circuit('initialize_circuit_3q', [qr], [cr])
initialize_circuit_3q.initialize("init", desired_vector, [qr[0],qr[1],qr[2]])

• What if I don't want to initialize with any hard-coded vector but something more general? Something like random_state from this link? qiskit.org/documentation/_modules/qiskit/quantum_info/random/… Oct 16 '19 at 4:46
• The link is broken... Jan 20 '20 at 21:55
• Could anyone please provide some explanations regarding Qiskit initialize? The new file does not seem to contain this info :( Jun 7 '20 at 22:59
• Please refer to this link on some details of the initialization. Basically, it only guarantees the transformation from all-zero state: github.com/Qiskit/qiskit-tutorials/blob/master/tutorials/… Jun 9 '20 at 4:17