In Quantum Machine Learning for data scientists, Page 34 gives an algorithm to calculate the distance between two classifical vectors. As mentioned in this question, it is not clear how the SwapTest is done and used to derive the distance. One answer from @cnada suggested that the swap is on the ancilla qubit only, per the original paper Quantum algorithms for supervised and unsupervised machine learning. However, the SwapTest was not designed on partial inputs.
I try to adapt SwapTest (on Page 33 of Quantum Machine Learning for data scientists) to derive as follows (by updating formula 131 with a minus sign, per the same answer from @cnada above), but cannot find the distance from the measurement at all.
First, initialize per DistCalc: $$ |\psi\rangle = \frac{1}{\sqrt{2}} (|0,a\rangle + |1,b\rangle) $$ $$ |\phi\rangle = \frac{1}{\sqrt{Z}} (|a||0\rangle - |b||1\rangle) $$ Also let: $$ |\psi'\rangle = \frac{1}{\sqrt{2}} (|a,0\rangle + |b,1\rangle) $$ Note that $\psi'$ is a valid (normalized) qubit as it can be obtained by swapping qubits from $|\psi\rangle$.
Now, initialize per SwapTest: $$ | 0, \psi, \phi \rangle = \frac{1}{\sqrt{2Z}} (|a|| 0,0,a,0\rangle - |b|| 0,0,a,1\rangle +|a|| 0,1,b,0\rangle - |b|| 0,1,b,1\rangle $$
Apply Hadamard gate on first qubit: $$ | 0, \psi, \phi \rangle = \frac{1}{2\sqrt{Z}} (|a|| 0,0,a,0\rangle + |a|| 1,0,a,0\rangle - |b|| 0,0,a,1\rangle -|b|| 1,0,a,1\rangle$$ $$+ |a|| 0,1,b,0\rangle+|a|| 1,1,b,0\rangle - |b|| 0,1,b,1\rangle - |b|| 1,1,b,1\rangle ) $$
Apply Swap gate on the ancilla qubit of $\psi$ (before $a$ or $b$) and the only qubit on $\phi$ (after $a$ or $b$): $$ | 0, \psi, \phi \rangle = \frac{1}{2\sqrt{Z}} (|a|| 0,0,a,0\rangle + |a|| 1,0,a,0\rangle - |b|| 0,1,a,0\rangle -|b|| 1,1,a,0\rangle$$ $$+ |a|| 0,0,b,1\rangle+|a|| 1,0,b,1\rangle - |b|| 0,1,b,1\rangle - |b|| 1,1,b,1\rangle ) $$ $$= \frac{1}{\sqrt{2Z}} (|a|\frac{| 0 \rangle+| 1 \rangle}{\sqrt{2}}| 0 \rangle - |b|\frac{| 0 \rangle+| 1 \rangle}{\sqrt{2}}| 1 \rangle)(| a,0 \rangle+| b,1 \rangle)$$
Apply Hadamard on first qubit: $$ \frac{1}{\sqrt{2Z}} (|a|| 0,0 \rangle - |b|| 0,1 \rangle)(| a,0 \rangle+| b,1 \rangle)$$
Measure on first qubit to get probability in getting first qubit in $| 0 \rangle$: $$ \vert \frac{1}{\sqrt{2Z}} (|a|\langle 0| 0,0 \rangle - |b|\langle 0| 0,1 \rangle)(| a,0 \rangle+| b,1 \rangle)]\vert^2$$ $$=\frac{1}{2Z} \vert(|a||0 \rangle - |b||1 \rangle)(| a,0 \rangle+| b,1 \rangle)\vert^2$$ $$=\vert\frac{|a||0 \rangle - |b||1 \rangle}{\sqrt{Z}}\vert^2 \vert\frac{| a,0 \rangle+| b,1 \rangle}{\sqrt{2}}\vert^2$$ $$=||\phi\rangle|^2||\psi'\rangle|^2 = 1$$.
However, this is independent of the distance $|a - b|$=$||a||a\rangle - |b||b\rangle|$.
Another way to think about this is that in the SwapTest, both $|a\rangle$ and $|b\rangle$ are $|0\rangle$ if the swap is indeed done on the ancilla bit of $\psi$. Then $|\langle a| b\rangle|=1$.
Is there anything wrong in my derivation above?