<jupyter_start><jupyter_text>Exercise 4: Circuit DecompositionWow! If you managed to solve the first three exercises, congratulations! The fourth problem is supposed to puzzle even the quantum experts among you, so don’t worry if you cannot solve it. If you can, hats off to you!You may recall from your quantum mechanics course that quantum theory is unitary. Therefore, the evolution of any (closed) system can be described by a unitary. But given an arbitrary unitary, can you actually implement it on your quantum computer?**"A set of quantum gates is said to be universal if any unitary transformation of the quantum data can be efficiently approximated arbitrarily well as a sequence of gates in the set."** (https://qiskit.org/textbook/ch-algorithms/defining-quantum-circuits.html)Every gate you run on the IBM Quantum Experience is transpiled into single qubit rotations and CNOT (CX) gates. We know that these constitute a universal gate set, which implies that any unitary can be implemented using only these gates. However, in general it is not easy to find a good decomposition for an arbitrary unitary. Your task is to find such a decomposition.You are given the following unitary:<jupyter_code>from may4_challenge.ex4 import get_unitary
U = get_unitary()
# print(U)
print("U has shape", U.shape)<jupyter_output>U has shape (16, 16)<jupyter_text>What circuit would make such a complicated unitary?Is there some symmetry, or is it random? We just updated Qiskit with the introduction of a quantum circuit library (https://github.com/Qiskit/qiskit-terra/tree/master/qiskit/circuit/library). This library gives users access to a rich set of well-studied circuit families, instances of which can be used as benchmarks (quantum volume), as building blocks in building more complex circuits (adders), or as tools to explore quantum computational advantage over classical computation (instantaneous quantum polynomial complexity circuits).<jupyter_code>from qiskit import QuantumCircuit
from may4_challenge.ex4 import check_circuit, submit_circuit<jupyter_output><empty_output><jupyter_text>**Using only single qubit rotations and CNOT gates, find a quantum circuit that approximates that unitary $U$ by a unitary $V$ up to an error $\varepsilon = 0.01$, such that $\lVert U - V\rVert_2 \leq \varepsilon$ !** Note that the norm we are using here is the spectral norm, $\qquad \lVert A \rVert_2 = \max_{\lVert \psi \rVert_2= 1} \lVert A \psi \rVert$.This can be seen as the largest scaling factor that the matrix $A$ has on any initial (normalized) state $\psi$. One can show that this norm corresponds to the largest singular value of $A$, i.e., the square root of the largest eigenvalue of the matrix $A^\dagger A$, where $A^{\dagger}$ denotes the conjugate transpose of $A$.**When you submit a circuit, we remove the global phase of the corresponding unitary $V$ before comparing it with $U$ using the spectral norm. For example, if you submit a circuit that generates $V = \text{e}^{i\theta}U$, we remove the global phase $\text{e}^{i\theta}$ from $V$ before computing the norm, and you will have a successful submission. As a result, you do not have to worry about matching the desired unitary, $U$, up to a global phase.**As the single-qubit gates have a much higher fidelity than the two-qubit gates, we will look at the number of CNOT-gates, $n_{cx}$, and the number of u3-gates, $n_{u3}$, to determine the cost of your decomposition as $$\qquad \text{cost} = 10 \cdot n_{cx} + n_{u3}$$Try to optimize the cost of your decomposition. **Note that you will need to ensure that your circuit is composed only of $u3$ and $cx$ gates. The exercise is considered correctly solved if your cost is smaller than 1600.**---For useful tips to complete this exercise as well as pointers for communicating with other participants and asking questions, please take a look at the following [repository](https://github.com/qiskit-community/may4_challenge_exercises). You will also find a copy of these exercises, so feel free to edit and experiment with these notebooks.---<jupyter_code># It can be helpful to visualize the elements of the unitary matrix
import matplotlib.pyplot as plotter, numpy as np
fig, (ax1, ax2) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6))
ax1.imshow(np.real(U))
ax2.imshow(np.imag(U))<jupyter_output><empty_output><jupyter_text>Attempt 1<jupyter_code>##### build your quantum circuit here
from qiskit import transpile
qc = QuantumCircuit(4)

qc.unitary(U, qc.qubits)
qc = transpile(qc, basis_gates = ['u3', 'cx'], optimization_level=3)
check_circuit(qc)
qc.draw()
# apply operations to your quantum circuit here<jupyter_output>Circuit stats:
||U-V||_2 = 2.7360571625960244e-12
(U is the reference unitary, V is yours, and the global phase has been removed from both of them).
Cost is 1676

Something is not right with your circuit: the cost of the circuit is too high (above 1600)<jupyter_text>Attempt 2<jupyter_code># Apply H*U*H operations to make the unitary diagonal
import matplotlib.pyplot as plotter, numpy as np
fig, (ax1, ax2) = plotter.subplots(nrows = 1, ncols = 2, figsize=(12,6))

import qiskit.quantum_info as qi
H4_circuit = QuantumCircuit(4)
H4_circuit.h(range(4))
H4 = qi.Operator(H4_circuit).data

Uprime = np.matmul(np.matmul(H4, U), H4)

ax1.imshow(np.real(Uprime))
ax2.imshow(np.imag(Uprime))
##### build your quantum circuit here
from qiskit import transpile
qc = QuantumCircuit(4)

qc.h(range(4))
qc.unitary(Uprime, qc.qubits)
qc.h(range(4))
qc = transpile(qc, basis_gates = ['u3', 'cx'], optimization_level=3)
check_circuit(qc)
qc.draw()
# apply operations to your quantum circuit here<jupyter_output>Circuit stats:
||U-V||_2 = 5.470975623515672e-15
(U is the reference unitary, V is yours, and the global phase has been removed from both of them).
Cost is 149

Great! Your circuit meets all the constrains.
Your score is 149. The lower, the better!
Feel free to submit your answer and remember you can re-submit a new circuit at any time!<jupyter_text>Attempt 3 -- IQP Circuit HintYou can use an IQP circuit as the baseline for any learning algorithm (see https://qiskit.org/documentation/stubs/qiskit.circuit.library.IQP.html).  Analytical Solution [See this solution sheet for worked out details](ibm_quantum_challenge_2020_ex4_solutions.pdf)  The original circuitWe give here the original IQP circuit that was used to generate the unitary $U$.<jupyter_code>qc = QuantumCircuit(4)
qc.h(range(4))
qc.cz(0,1)
qc.cz(1,2)
qc.cz(1,3)
qc.cz(0,2)
qc.t(0)
qc.t(1); qc.t(1); qc.t(1); qc.t(1); qc.t(1)
qc.t(2); qc.t(2);
qc.t(3); qc.t(3); qc.t(3)
qc.h(range(4))

qc = transpile(qc, basis_gates = ['u3', 'cx'], optimization_level=1) 
check_circuit(qc)
qc.draw()<jupyter_output>Circuit stats:
||U-V||_2 = 1.8188110575071797e-15
(U is the reference unitary, V is yours, and the global phase has been removed from both of them).
Cost is 46

Great! Your circuit meets all the constrains.
Your score is 46. The lower, the better!
Feel free to submit your answer and remember you can re-submit a new circuit at any time!<jupyter_text>Community shoutouts cost = 45 - <NAME>, Universidad Autónoma de Madrid: [code](community/luciano.ipynb), [meetup](https://www.meetup.com/Computacion-Cuantica-en-Madrid/events/270722706/?isFirstPublish=true)- <NAME>, Los Alamos National Laboratory, [code coming soon](), https://iopscience.iop.org/article/10.1088/1367-2630/aae94a- <NAME>, Institute for Theoretical Physics (THP), University of Cologne, [analytical writeup coming soon]() Honorable mentions- <NAME>-Kerstjens, [writeup coming soon]()- <NAME>, [writeup](https://quantumzeitgeist.com/machine-learning-for-decomposing-arbitrary-unitary-matrices-of-any-size/) Survey about the IBM Quantum Challenge- https://qiskit.typeform.com/to/qgdGVl You can check whether your circuit is valid before submitting it with `check_circuit(qc)`. Once you have a valid solution, please submit it by running the following cell (delete the `` before `submit_circuit`). You can re-submit at any time.<jupyter_code># Send the circuit as the final answer, can re-submit at any time
#submit_circuit(qc)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09524978519700503, 'fraction_numerical': 0.024180680004909784, 'mean_word_length': 5.224598930481283, 'pattern_counts': {'":': 0, '<': 30, '<?xml version=': 0, '>': 30, 'https://': 8, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '336145', 'license': 'MIT', 'n_tokens_mistral': 2681, 'n_tokens_neox': 2420, 'n_words': 1038, 'path': 'ibm/circuit_optimization/Challenge4_CircuitDecomposition_Solutions.ipynb', 'repo_name': 'sdabhi23/q-cloud-programming', 'size': '8195'}