---
jupytext:
  formats: ipynb,md:myst
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.14.0
kernelspec:
  display_name: Python 3 (phys-555)
  language: python
  name: phys-555
---

```{code-cell}
:tags: [hide-cell]

import mmf_setup;mmf_setup.nbinit()
import logging;logging.getLogger('matplotlib').setLevel(logging.CRITICAL)
%matplotlib inline
import numpy as np, matplotlib.pyplot as plt
```

(sec:Fidelity)=
# Fidelity

:::{margin}
Note that some conventions define the fidelity as the square of this quantity, including
the definition on [Wikipedia](https://en.wikipedia.org/wiki/Fidelity_of_quantum_states):
\begin{gather*}
  F(\mat{\rho}, \mat{\sigma}) 
  = \Bigl(\Tr \sqrt{\mat{\rho}^{1/2}\mat{\sigma}\mat{\rho}^{1/2}}\Bigr)^2.
\end{gather*}
For consistency, we follow the textbook's convention here.
:::
In section §9.2.2 {cite:p}`Nielsen:2010`, they define the *fidelity* as a measure of the
distance between density matrices:
\begin{gather*}
  F(\mat{\rho}, \mat{\sigma}) = \Tr \sqrt{\mat{\rho}^{1/2}\mat{\sigma}\mat{\rho}^{1/2}}.
\end{gather*}
The advantage of this formulation is that, since density matrices are positive, the
matrix square-root is well defined.  However, in many cases, the following formulation
may be easier to use:
\begin{gather*}
  F(\mat{\rho}, \mat{\sigma}) = \Tr \sqrt{\mat{\rho}\mat{\sigma}}.
\end{gather*}

```{code-cell}
import numpy as np
from scipy.linalg import sqrtm

rng = np.random.default_rng(seed=2)
N = 5
for n in range(10):
    A, B = rng.normal(size=(2, N, N)) + 1j*rng.normal(size=(2, N, N))
    # Make these positive definite as density matrices must be
    A = A.T.conj() @ A
    B = B.T.conj() @ B
    assert not np.allclose(A @ B, B @ A)
    assert np.allclose(
        np.trace(sqrtm(sqrtm(A) @ B @ sqrtm(A))),
        np.trace(sqrtm(B @ A)))
```

:::{margin}
This $\mat{\sigma}$ is not positive, but demonstrates a potential issue.
:::
Qingze points out, however, that this is not always well defined.  Consider for example:
\begin{gather*}
  \mat{\rho} = \begin{pmatrix}
    0 & 0\\
    0 & 1
  \end{pmatrix}, \qquad
  \mat{\sigma} = \begin{pmatrix}
    1 & 1\\
    1 & 0
 \end{pmatrix}.
\end{gather*}
In this case, the product is then a [Jordan
matrix](https://en.wikipedia.org/wiki/Jordan_matrix) which has no well-defined matrix
square root, which is very unlikely to occur randomly, but can appear in special cases.
One can easily verify that $\mat{\rho}^2 = \mat{\rho} =
\sqrt{\mat{\rho}}$, hence the original form gives a well-defined fidelity:
\begin{gather*}
  F(\mat{\rho}, \mat{\sigma}) = \Tr\sqrt{\mat{\rho}\mat{\sigma}\mat{\rho}}
  = \Tr\sqrt{\mat{0}} = 0.
\end{gather*}
