qrisp.QuantumVariable.init_state#
- QuantumVariable.init_state(params, method='auto')[source]#
Initialize an arbitrary quantum state on this quantum variable.
This method supports two input formats:
1. Dictionary input
A dictionary
{value: amplitude}describing the (possibly non-normalized) wavefunction in the logical basis of the quantum variable. Any value not listed is assigned amplitude zero.2. Explicit statevector input
A flat vector of complex amplitudes of length \(2^{n}\), where \(n\) is the number of qubits. The vector is automatically normalized. The little-endian convention is assumed for indexing basis states. See prepare for details.
Note
In Jasp mode, Python-based shape and checks on the norm of the statevector are skipped to avoid tracing side effects.
- Parameters:
- paramsdict or array-like
Either a dictionary
{value: amplitude}or a length \(2^{n}\) complex statevector.- method{“auto”, “qiskit”, “qswitch”}, optional
Select the state-preparation backend. The possible options are:
"auto"(default):Use the Qiskit-based initializer outside Jasp mode and fall back to the internal
qswitchinitializer in Jasp mode.
"qiskit":Force the Qiskit state-preparation circuit. Not available in Jasp mode.
"qswitch":Use the q_switch-based implementation, which is compatible with Jasp mode.
Defaults to
"auto".
Examples
Dictionary input
We create a
QuantumFloatand encode the state\[\ket{\psi} = \sqrt{\tfrac{1}{3}}\,\ket{0.5} + i\sqrt{\tfrac{2}{3}}\,\ket{2.0}\]>>> from qrisp import QuantumFloat >>> qf = QuantumFloat(3, -1) >>> qf.init_state({0.5: (1/3)**0.5, 2.0: 1j*(2/3)**0.5})
or equivalently:
>>> qf[:] = {0.5: (1/3)**0.5, 2.0: 1j*(2/3)**0.5}
Explicit statevector input
In this example, we create a QuantumFloat and prepare the normalized state \(\sum_{i=0}^3 \tilde b_i\ket{i}\) for \(\tilde b=(0,1,2,3)/\sqrt{14}\).
>>> import numpy as np
>>> b = np.array([0, 1, 2, 3], dtype=float) >>> b /= np.linalg.norm(b) >>> qf = QuantumFloat(2) >>> qf.init_state(b)
We can use the
statevectormethod to get a function that maps basis states to amplitudes to verify the prepared state:>>> sv_function = qf.qs.statevector("function")
>>> print(f"b[1]: {b[1]:.6f} -> {sv_function({qf: 1}):.6f}") b[1]: 0.267261 -> 0.267261-0.000000j >>> print(f"b[2]: {b[2]:.6f} -> {sv_function({qf: 2}):.6f}") b[2]: 0.534522 -> 0.534522-0.000000j
where index 1 in little-endian corresponds to the basis state \(\ket{q_0=1, q_1=0}\) and index 2 to \(\ket{q_0=0, q_1=1}\).
Forcing a backend
We can also explicitly choose the state-preparation backend:
>>> qf.init_state(psi, method="qswitch") # Always allowed >>> qf.init_state(psi, method="qiskit") # Only outside Jasp mode
After initialization, the amplitudes can be inspected using
qf.qs.statevector("function")as above.