# The Spinning Effective One-Body Initial Condition Solver

### Author: Tyler Knowles

## This module documents the reduced spinning effective one-body initial condition solver as numerically implemented in LALSuite's SEOBNRv3 gravitational waveform approximant.  That is, we follow Section IV A of [Buonanno, Chen, and Damour (2006)](https://arxiv.org/abs/gr-qc/0508067).

### Throughout this module, we will refer to
* [Pan, Buonanno, Buchman et. al. (2010)](https://arxiv.org/abs/0912.3466v2) as PBB2010,
* [Buonanno, Chen, and Damour (2006)](https://arxiv.org/abs/gr-qc/0508067) as BCD2006, and
* [Barausse and Buonanno (2010)](https://arxiv.org/abs/0912.3517) as BB2010.

**This module has been validated against the LALSuite SEOBNRv3/SEOBNRv3_opt code that was reviewed and approved for LIGO parameter estimation by the LIGO Scientific Collaboration.**

# Table of Contents
$$\label{toc}$$

This module is organized as follows, matching the "steps" listed in [BCD2006](https://arxiv.org/abs/gr-qc/0508067):

0. [Introduction:](#intro) The Physical System of Interest
1. [Step 1:](#step1) Initial Coordinate Choice
1. [Step 2:](#step2) Compute ${\bf r}$, ${\bf p}_{r}$, ${\bf p}_{\theta}$, and ${\bf p}_{\phi}$
1. [Step 3:](#step3) Rotate $\hat{\bf L} \to {\bf e}_{z}$
1. [Step 4:](#step4) Compute $\dot{\bf r}$
1. [Step 5:](#step5) Invert the rotation of Step 3
1. [Output](#latex_pdf_output): Output this module to $\LaTeX$-formatted PDF

# Introduction: The Physical System of Interest \[Back to [top](#toc)\]
$$\label{intro}$$

Consider two compact objects (e.g. black holes or neutron stars) with masses $m_{1}$, $m_{2}$ (in solar masses) and spin angular momenta ${\bf S}_{1}$, ${\bf S}_{2}$ in a binary system.  The spinning effective one-body ("SEOB") Hamiltonian $H_{\rm real}$ (see [BB2010](https://arxiv.org/abs/0912.3517) Equation (5.69)) describes the dynamics of this system.  We seek initial conditions for nonadiabatic evolutions of such a system, and follow [BCD2006](https://arxiv.org/abs/gr-qc/0508067) Section IV A.

Please note that throughout this notebook we adpot the following conventions:
1. $c = G = 1$ where $c$ is the speed of light in a vacuum and $G$ is Newton's gravitational constant,
1. hatted vectors (e.g. $\hat{\bf L}_{N}$) usually denote scaled or unit vectors, and
1. the initial inclination angle $\iota$ is chosen to be zero.

Choose a spatial coordinate basis $\left\{ {\bf e}_{0}, {\bf e}_{1}, {\bf e}_{2} \right\}$ so that the initial separation vector ${\bf r}$ between the compact objects lies along the ${\bf e}_{0}$-axis.  We start with the following parameters:
1. binary parameters $m_{1}$, $m_{2}$, ${\bf S}_{1}$, and ${\bf S}_{2}$,
1. initial frequency $f$, and
1. SEOB model parameters (constants dependent on $m_{1}$, $m_{2}$).

Our goal is to produce initial dynamical variables
1. ${\bf x} = \left( x, y, z \right)$, and
1. ${\bf p} = \left( p_{x}, p_{y}, p_{z} \right)$.

We include below the physical parameters necessary to compute the initial conditions.  Solving for the initial conditions requires computing $\frac{ \partial H_{\rm real} }{ \partial p_{i} }$ for $i \in \left\{ r, \theta, \phi \right\}$, which we defer to another module.

Please note that in [BCD2006](https://arxiv.org/abs/gr-qc/0508067) the initial conditions are solved for given an initial separation; here we use a given initial frequency instead.  The difference is in our approach to solving Equation (4.8).  Our approach also differs from that found in LALSuite's XLALSimIMRSpinEOBInitialConditionsPrec() function (file: LALSimIMRSpinEOBInitialConditionsPrec.c) because we choose our intial coordinate system so that the inclination angle $\iota$ is zero (this simplifies their step one and step five).

Besides the physical parameters, we also need the [Euler–Mascheroni constant](https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant) $\gamma$ and the [geomtrized](https://en.wikipedia.org/wiki/Geometrized_unit_system) solar mass $\mathcal{M}_{\odot}$, both hard-coded in LALSuite with the significant digits shown below.  (The following links are directed to the appropriate LALSuite documentation: [$\gamma$](https://lscsoft.docs.ligo.org/lalsuite/lal/group___l_a_l_constants__h.html#gac6af32574ff8acaeeafe8bf422281e98) and [$\mathcal{M}_{\odot}$](https://lscsoft.docs.ligo.org/lalsuite/lal/group___l_a_l_constants__h.html#gab83f8c705dda3fd0bb2d5f2470bb9cdd).)

```python
import sympy as sp
m1,m2,S10,S11,S12,S20,S21,S22,f = sp.symbols("m1 m2 S10 S11 S12 S20 S21 S22 f",real=True)
dHdpx,dHdpy,dHdpz = sp.symbols("dHdpx dHdpy dHdpz",real=True)

gamma = 0.577215664901532860606512090082402431
Msol = 4.925491025543575903411922162094833998e-6
```

# Step 1: Initial Coordinate Choice \[Back to [top](#toc)\]
$$\label{step1}$$

## Mass terms \[Back to [top](#toc)\]
$$\label{massterms}$$

We begin by defining the following useful quantities:

\begin{align*}
    M &= m_{1} + m_{2} \\
    \eta &= \frac{ m_{1} m_{2} }{ M^{2} }
\end{align*}

```python
M = m1 + m2
Msq = M*M
eta = m1*m2/Msq
```

## Spin terms \[Back to [top](#toc)\]
$$\label{spinterms}$$

Can we find a source that says how the basis for the orientation of ${\bf S}_{1}$, ${\bf S}_{2}$ is chosen?  For now I assume it's in the $\hat{\bf r}, \hat{\bf v}, \hat{\bf L}_{N}$-frame, which is suggestd by the fact that LALSuite rotates them using the same rotation matrix as rotates $\hat{\bf r}$, $\hat{\bf v}$, and $\hat{\bf L}_{N}$ if $\iota \not= 0$.  Since we assumed $G = c = 1$, we make the spin angular momenta dimensionless via:

\begin{align*}
    \hat{\bf S}_{1} &= \frac{ 1 }{ M^{2} } {\bf S}_{1} \\
    \hat{\bf S}_{2} &= \frac{ 1 }{ M^{2} } {\bf S}_{2}
\end{align*}

```python
S1hat0 = S10/Msq
S1hat1 = S11/Msq
S1hat2 = S12/Msq
S2hat0 = S20/Msq
S2hat1 = S21/Msq
S2hat2 = S22/Msq
```

## Normalized Position $\hat{\bf r}$ \[Back to [top](#toc)\]
$$\label{rhat}$$

We assumed that the initial separation vector ${\bf r}$ lies along the ${\bf e}_{0}$-axis, so the normalized initial separation vector $\hat{\bf r}$ is given by

\begin{align*}
    \hat{\bf r}^{0} &= 1 \\
    \hat{\bf r}^{1} &= 0 \\
    \hat{\bf r}^{2} &= 0.
\end{align*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Lines 803--805.

```python
rhat0 = 1.
rhat1 = 0.
rhat2 = 0.
```

## Normalized Orbital Angular Momenutm $\hat{\bf L}_{N}$ \[Back to [top](#toc)\]
$$\label{ln}$$

Since we assume that the initial separation vector ${\bf r}$ between $m_{1}$ and $m_{2}$ lies along the ${\bf e}_{0}$-axis, the initial orbital plane coincides with the ${\bf e}_{0},{\bf e}_{1}$-plane.  Thus the normalized inital orbital angular momentum vector $\hat{\bf L}_{N}$ is given by

\begin{align*}
    \hat{\bf L}_{N}^{0} &= 0 \\
    \hat{\bf L}_{N}^{1} &= 0 \\
    \hat{\bf L}_{N}^{2} &= 1.
\end{align*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Lines 788--790.

```python
LNhat0 = 0.
LNhat1 = 0.
LNhat2 = 1.
```

## Normalized Velocity $\hat{\bf v}$ \[Back to [top](#toc)\]
$$\label{vhat}$$

Given normalized orbital angular momentum ($\hat{\bf L}_{N}$) and normalized position ($\hat{\bf r}$), the normalized velocity vector ($\hat{\bf v}$) is given by

\begin{equation*}
    \hat{\bf v} = \frac{ \hat{\bf L}_{N} \times \hat{\bf r} }{ \left\lvert \hat{\bf L}_{N} \times \hat{\bf r} \right\rvert }.
\end{equation*}

Given $\hat{\bf L}_{N} = \begin{bmatrix} 0 \\ 0 \\ 1 \end{bmatrix}$ and $\hat{\bf r} = \begin{bmatrix} 1 \\ 0 \\ 0 \end{bmatrix}$ it is clear that $\hat{\bf v} = \begin{bmatrix} 0 \\ 1 \\ 0 \end{bmatrix}$.

See LALSimIMRSpinEOBInitialConditionsPrec.c Lines 812--814.

```python
vhat0 = 0.
vhat1 = 1.
vhat2 = 0.
```

## Note \[Back to [top](#toc)\]

Since we began assuming $\iota = 0$, we do not need to rotate $\hat{\bf r}$, $\hat{\bf v}$, $\hat{\bf L}_{N}$, ${\bf S}_{1}$, ${\bf S}_{2}$, $\hat{\bf S}_{1}$, or $\hat{\bf S}_{2}$ as is done at LALSimIMRSpinEOBInitialConditionsPrec.c Lines 840.

# Step 2: Compute ${\bf r}$ and ${\bf p}$ in spherical coordinates \[Back to [top](#toc)\]
$$\label{step2}$$

## $\omega$ \[Back to [top](#toc)\]
$$\label{omega}$$

Is there a paper reference for this formula?  It's not quite Newtonian ($\omega = 2 \pi f)$.

\begin{equation*}
    \omega = M \mathcal{M}_{\odot} \pi f.
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 893.

```python
omega = M*Msol*sp.pi*f
```

## Initial Velocity $v$ \[Back to [top](#toc)\]
$$\label{velocity}$$

Is there a paper reference for this formula?

\begin{equation*}
    v = \sqrt[3]{ \omega }.
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 894.

```python
v = sp.cbrt(omega)
```

## Root-finding...

$$\label{roots}$$

**Note: LALSuite scales the initial guesses given to the root-finding routine; see LALSimIMRSpinEOBInitialConditionsPrec.c Line 899.**

We will write components of the momentum vector ${\bf p}$ in spherical coordinates with components ${\bf p}^{r}$, ${\bf p}^{\theta}$, and ${\bf p}^{\phi}$.

These are initial guesses for the root-finding routine:

\begin{align*}
    {\bf r}^{r} &= \frac{ 1 }{ v^{2} } \\
    {\bf p}^{\phi} &= v \\
    {\bf p}^{\theta} &= 0.2.
\end{align*}

The root finder seeks to solve

\begin{equation*}
    \begin{bmatrix} \frac{ \partial H }{ \partial {\bf r}^{r} } \\ \frac{ \partial H }{ \partial {\bf p}^{\theta} } \\ \frac{ \partial H }{ \partial {\bf p}^{\phi} } - \omega \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \\ 0 \end{bmatrix}.
\end{equation*}

As the Hamiltonian is given in Cartesian coordinates, this requires computing $\frac{ \partial H }{ \partial {\bf r}^{0} }$, $\frac{ \partial H }{ \partial {\bf p}^{1} }$, and $\frac{ \partial H }{ \partial {\bf p}^{2} }$ and then converting to spherical coordinates via

\begin{align*}
    \frac{\partial H}{\partial {\bf r}^{r}} &= \frac{\partial H}{\partial {\bf r}^{0}} - \frac{\frac{\partial H}{\partial {\bf p}^{1}}{\bf p}^{\phi}}{\left({\bf r}^{r}\right)^{2}} + \frac{\frac{\partial H}{\partial {\bf p}^{2}}{\bf p}^{\theta}}{\left({\bf r}^{r}\right)^{2}} \\
    \frac{\partial H}{\partial {\bf p}^{\theta}} &= -\frac{\frac{\partial H}{\partial {\bf p}^{2}}}{{\bf r}^{r}} \\
    \frac{\partial H}{\partial {\bf p}^{\phi}} &= \frac{\frac{\partial H}{\partial {\bf p}^{1}}}{{\bf r}^{r}}.
\end{align*}

In the end, we should have a cartesian postition vector ${\bf q}$ and momentum vector ${\bf p}$.  It seems that because we stared with $\iota = 0$ that we can use $\hat{\bf r}$ instead of $\hat{\bf q}$?

```python
q0 = 1.
q1 = 1.
q2 = 1.
p0 = 1.
p1 = 1.
p2 = 1.
```

# Step 3: Rotate $\hat{\bf L} \to {\bf e}_{z}$ \[Back to [top](#toc)\]
$$\label{step3}$$

## Note \[Back to [top](#toc)\]

At this point, see LALSimIMRSpinEOBInitialConditionsPrec.c normalizes the Cartesian separation and momentum vectors constructed in [Step 2](#step2).  We already have a normalized separation vector $\hat{\bf r}$, so we skip that step.

## Normalize ${\bf p}$ \[Back to [top](#toc)\]
$$\label{normp}$$

Next we normalize the new position vector ${\bf p}$ that we found in [Step 2](#step2):

\begin{equation*}
    \hat{\bf p} = \frac{ {\bf p} }{ \left\lvert {\bf p} \right\rvert}.
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1101.

```python
pnorminv = 1/sp.sqrt(p0*p0 + p1*p1 + p2*p2)
phat0 = p0*pnorminv
phat1 = p1*pnorminv
phat2 = p2*pnorminv
```

## $\hat{\bf L}$ \[Back to [top](#toc)\]
$$\label{lhat}$$

We compute the normalized relativistic angular momentum vector $\hat{\bf L}$ (find source for this formula?):

\begin{equation*}
    \hat{\bf L} = \frac{ \hat{\bf r} \times \hat{\bf p} }{ \left\lvert \hat{\bf r} \times \hat{\bf p} \right\rvert }.
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Lines 1098--1100.

```python
Lhat0 = rhat1*phat2 - rhat2*phat1
Lhat1 = rhat2*phat0 - rhat0*phat2
Lhat2 = rhat0*phat1 - rhat1*phat0
Lhatnorminv = 1./sp.sqrt(Lhat0*Lhat0 + Lhat1*Lhat1 + Lhat2*Lhat2)
Lhat0 /= Lhatnorminv
Lhat1 /= Lhatnorminv
Lhat2 /= Lhatnorminv
```

## Rotation matrix \[Back to [top](#toc)\]
$$\label{rotationmatrix}$$

The rotation matrix from the $\left\{ \hat{\bf r}, {\bf v}, \hat{\bf L}_{N} \right\}$ frame to the $\left\{ \hat{\bf r}, {\bf p}, \hat{\bf L} \right\}$ frame is given by

\begin{equation*}
    \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}.
\end{equation*}

The matrix to invert the rotation is simply the transpose:

\begin{equation*}
    \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf p}^{0} & \hat{\bf L}^{0} \\
        \hat{\bf r}^{1} & \hat{\bf p}^{1} & \hat{\bf L}^{1} \\
        \hat{\bf r}^{2} & \hat{\bf p}^{2} & \hat{\bf L}^{2}\end{bmatrix}.
\end{equation*}

To see that this is indeed the correct matrix inverse, note that by construction $\hat{\bf q}$, $\hat{\bf p}$, and $\hat{\bf L}$ are all unit vectors orthogonal to one another.  See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1107.

```python
rotate00 = rhat0
rotate01 = rhat1
rotate02 = rhat2
rotate10 = phat0
rotate11 = phat1
rotate12 = phat2
rotate20 = Lhat0
rotate21 = Lhat1
rotate22 = Lhat2
```

## Rotate $\hat{\bf r}$ \[Back to [top](#toc)\]
$$\label{rotatesrhat}$$

We now rotate $\hat{\bf r}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    \hat{\bf r}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} \hat{\bf r}^{0} \\ \hat{\bf r}^{1} \\ \hat{\bf r}^{2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1112.

```python
rhatprm0 = rhat0*rhat0 + rhat1*rhat1 + rhat2*rhat2
rhatprm1 = phat0*rhat0 + phat1*rhat1 + phat2*rhat2
rhatprm2 = Lhat0*rhat0 + Lhat1*rhat1 + Lhat2*rhat2
```

## Rotate $\hat{\bf v}$ \[Back to [top](#toc)\]
$$\label{rotatevhat}$$

We rotate $\hat{\bf v}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    \hat{\bf v}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} \hat{\bf v}^{0} \\ \hat{\bf v}^{1} \\ \hat{\bf v}^{2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1113.

```python
vhatprm0 = rhat0*vhat0 + rhat1*vhat1 + rhat2*vhat2
vhatprm1 = phat0*vhat0 + phat1*vhat1 + phat2*vhat2
vhatprm2 = Lhat0*vhat0 + Lhat1*vhat1 + Lhat2*vhat2
```

## Rotate $\hat{\bf L}_{N}$ \[Back to [top](#toc)\]
$$\label{rotatelnhat}$$

We rotate $\hat{\bf L}_{N}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    \hat{\bf L}_{N}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} \hat{\bf L}_{N}^{0} \\ \hat{\bf L}_{N}^{1} \\ \hat{\bf L}_{N}^{2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1114.

```python
LNhatprm0 = rhat0*LNhat0 + rhat1*LNhat1 + rhat2*LNhat2
LNhatprm1 = phat0*LNhat0 + phat1*LNhat1 + phat2*LNhat2
LNhatprm2 = Lhat0*LNhat0 + Lhat1*LNhat1 + Lhat2*LNhat2
```

## Rotate ${\bf S}_{1}$ \[Back to [top](#toc)\]
$$\label{rotates1}$$

We rotate ${\bf S}_{1}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    {\bf S}_{1}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} {\bf S}_{1}^{0} \\ {\bf S}_{1}^{1} \\ {\bf S}_{1}^{2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1115.

```python
S1prm0 = rhat0*S10 + rhat1*S11 + rhat2*S12
S1prm1 = phat0*S10 + phat1*S11 + phat2*S12
S1prm2 = Lhat0*S10 + Lhat1*S11 + Lhat2*S12
```

## Rotate ${\bf S}_{2}$ \[Back to [top](#toc)\]
$$\label{rotates2}$$

We rotate ${\bf S}_{2}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    {\bf S}_{2}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} {\bf S}_{2}^{0} \\ {\bf S}_{2}^{1} \\ {\bf S}_{2}^{z} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1116.

```python
S2prm0 = rhat0*S20 + rhat1*S21 + rhat2*S22
S2prm1 = phat0*S20 + phat1*S21 + phat2*S22
S2prm2 = Lhat0*S20 + Lhat1*S21 + Lhat2*S22
```

## Rotate $\hat{\bf S}_{1}$ \[Back to [top](#toc)\]
$$\label{rotates1hat}$$

We rotate $\hat{\bf S}_{1}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    \hat{\bf S}_{1}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} \hat{\bf S}_{1}^{0} \\ \hat{\bf S}_{1}^{1} \\ \hat{\bf S}_{1}^{1} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1117.

```python
S1hatprm0 = rhat0*S1hat0 + rhat1*S1hat1 + rhat2*S1hat2
S1hatprm1 = phat0*S1hat0 + phat1*S1hat1 + phat2*S1hat2
S1hatprm2 = Lhat0*S1hat0 + Lhat1*S1hat1 + Lhat2*S1hat2
```

## Rotate $\hat{\bf S}_{2}$ \[Back to [top](#toc)\]
$$\label{rotates2hat\hat}$$

We rotate $\hat{\bf S}_{2}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    \hat{\bf S}_{2}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} \hat{\bf S}_{2}^{0} \\ \hat{\bf S}_{2}^{1} \\ \hat{\bf S}_{2}^{2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1118.

```python
S2hatprm0 = rhat0*S2hat0 + rhat1*S2hat1 + rhat2*S2hat2
S2hatprm1 = phat0*S2hat0 + phat1*S2hat1 + phat2*S2hat2
S2hatprm2 = Lhat0*S2hat0 + Lhat1*S2hat1 + Lhat2*S2hat2
```

## Rotate ${\bf r}$ \[Back to [top](#toc)\]
$$\label{rotater}$$

We rotate ${\bf p}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    {\bf r}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} {\bf r}^{0} \\ {\bf r}^{1} \\ {\bf r}^{2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1119.

```python
rprm0 = rhat0*p0 + rhat1*p1 + rhat2*p2
rprm1 = phat0*p0 + phat1*p1 + phat2*p2
rprm2 = Lhat0*p0 + Lhat1*p1 + Lhat2*p2
```

## Rotate ${\bf p}$ \[Back to [top](#toc)\]
$$\label{rotatep}$$

We rotate ${\bf p}$.  We'll use primes to denote the rotated vector.

\begin{equation*}
    {\bf p}^{\prime} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf r}^{1} & \hat{\bf r}^{2} \\
        \hat{\bf p}^{0} & \hat{\bf p}^{1} & \hat{\bf p}^{2} \\
        \hat{\bf L}^{0} & \hat{\bf L}^{1} & \hat{\bf L}^{2}\end{bmatrix}
        \begin{bmatrix} {\bf p}^{0} \\ {\bf p}^{y} \\ {\bf p}^{2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1120.

```python
pprm0 = rhat0*p0 + rhat1*p1 + rhat2*p2
pprm1 = phat0*p0 + phat1*p1 + phat2*p2
pprm2 = Lhat0*p0 + Lhat1*p1 + Lhat2*p2
```

# Step 4: Compute $\dot{\bf r}$ \[Back to [top](#toc)\]
$$\label{step4}$$

## Convert from Cartesian to Spherical \[Back to [top](#toc)\]
$$\label{carttosph}$$

We convert position and momentum into spherical coordinates.  In the special case where $\theta = \frac{ \pi }{ 2 }$ and $\phi = 0$, the spherical position vector ${\bf r} = \left( {\bf r}^{r}, {\bf r}^{\theta}, {\bf r}^{\phi} \right)$ is given by

\begin{align*}
    {\bf r}^{r} &= {\bf r}^{0} \\
    {\bf r}^{\theta} &= \frac{ \pi }{ 2 } \\
    {\bf r}^{\phi} &= 0
\end{align*}

and the spherical momentum vector ${\bf p} = \left( {\bf p}^{r}, {\bf p}^{\theta}, {\bf p}^{\phi} \right)$ is given by

\begin{align*}
    {\bf p}^{r} &= {\bf p}^{0} \\
    {\bf p}^{\theta} &= - {\bf r}^{0}{\bf p}^{2} \\
    {\bf p}^{\phi} &= {\bf r}^{0}{\bf p}^{1} \\
\end{align*}

We call a Cartesian to spherical routine at LALSimIMRSpinEOBInitialConditionsPrec.c Line 1139, and the function itself is defined on Lines 243--285.

```python
rr = rprm0
rtheta = sp.pi/2.
rphi = 0.
pr = pprm0
ptheta = -rprm0*pprm2
pphi = rprm0*pprm1
```

## Second derivatives of $H_{\rm real}$ \[Back to [top](#toc)\]
$$\label{seconderiv}$$

We need to compute $\frac{ \partial H }{ \partial {\bf p}^{\phi} }$, $\frac{ \partial^{2} H_{\rm real} }{ \partial r^{2} }$, and $\frac{ \partial^{2} H_{\rm real} }{ \partial r \partial {\bf p}^{\phi} }$ (in another module).

Note: be sure that, following this, we use normalized spins.

```python
dHdpphi = 0.
d2Hdr2 = 0.
d2Hdrdpphi = 1.
```

## $\frac{ \partial E }{ \partial r }$ \[Back to [top](#toc)\]
$$\label{dEdr}$$

I don't know what this is or means (see [BCD2006](https://arxiv.org/abs/gr-qc/0508067) Equations (4.14) and (3.7)), but we compute $\frac{ \partial E }{ \partial r }$ in spherical coordinates (when ${\bf r}$ is directed along the ${\bf e}_{0}$ axis) via

\begin{equation*}
    \frac{ \partial E }{ \partial r } = -\frac{ \frac{ \partial H }{ \partial {\bf p}^{\phi} } \frac{ \partial^{2} H }{ \left(\partial {\bf r}^{r} \right)^{2} } }{ \frac{ \partial^{2} H }{ \partial H \partial {\bf p}^{\phi} } }.
\end{equation*}

```python
dEdr = -dHdpphi*d2Hdr2/d2Hdrdpphi
```

## ${\bf S}_{\rm Kerr}$ \[Back to [top](#toc)\]
$$\label{skerr}$$

From [BB2010](https://arxiv.org/abs/0912.3517) Equations (5.2), (5.63), and (5.67) we have

\begin{equation*}
    {\bf S}_{\rm Kerr} = {\bf S}_{1} + {\bf S}_{2}.
\end{equation*}

Taking the square of [BB2010](https://arxiv.org/abs/0912.3517) Equation (4.9) (be careful with the factor or $M$...),

\begin{equation*}
    a^{2} = \frac{ {\bf S}_{Kerr} \cdot {\bf S}_{Kerr} }{ M^{2} }
\end{equation*}

so that

\begin{equation*}
    a = \sqrt{ a^{2} }.
\end{equation*}

```python
SKerr0 = S10 + S20
SKerr1 = S11 + S21
SKerr2 = S12 + S22
asq = (SKerr0*SKerr0 + SKerr1*SKerr1 + SKerr2*SKerr2)/(M*M)
a = sp.sqrt(asq)
```

## $\boldsymbol{\sigma}^{*}$ \[Back to [top](#toc)\]
$$\label{sigmastar}$$

From [BB2010](https://arxiv.org/abs/0912.3517) Equation (5.3),

\begin{equation*}
    \boldsymbol{\sigma}^{*} = \frac{ m_{2} }{ m_{1} } {\bf S}_{1} + \frac{ m_{1} }{ m_{2} }{\bf S}_{2}.
\end{equation*}

```python
sigmastar0 = S10*m2/m1 + S20*m1/m2
sigmastar1 = S11*m2/m1 + S21*m1/m2
sigmastar2 = S12*m2/m1 + S22*m1/m2
```

## $H_{\rm real}$ \[Back to [top](#toc)\]
$$\label{Hreal}$$

We now compute $H_{\rm real}$ (LALSimIMRSpinEOBInitialConditionsPrec.c Line 1217) (another module).

```python
Hreal = 0
```

## Polar data \[Back to [top](#toc)\]
$$\label{polardata}$$

At LALSimIMRSpinEOBInitialConditionsPrec.c Lines 1234--1238, we set the following polar data ${\bf P}$ (need to find reference for this?):

\begin{align*}
    {\bf P}^{0} &= {\bf r}^{r} \\
    {\bf P}^{1} &= 0 \\
    {\bf P}^{2} &= {\bf p}^{r} \\
    {\bf P}^{3} &= {\bf p}^{\phi}
\end{align*}

```python
polar0 = rr
polar1 = 0.
polar2 = pr
polar3 = pphi
```

## Compute ${\bf L}$ \[Back to [top](#toc)\]
$$\label{l}$$

We compute ${\bf L} = {\bf r}^{\prime}\times{\bf p}^{\prime}$ and normalize as follows.

\begin{equation*}
    {\bf L} = \frac{ {\bf r}^{\prime} \times {\bf p}^{\prime} }{ \left\lvert {\bf r}^{\prime} \times {\bf p}^{\prime} \right\rvert }
\end{equation*}

See LALSimIMRSpinEOBFactorizedFluxPrec_v3opt.c lines 121--129.

```python
L0 = rprm1*pprm2 - rprm2*pprm1
L1 = rprm2*pprm0 - rprm0*pprm2
L2 = rprm0*pprm1 - rprm1*pprm0
Lmaginv = 1./sp.sqrt(rprmcrosspprm0*rprmcrosspprm0
                                 + rprmcrosspprm1*rprmcrosspprm1
                                 + rprmcrosspprm2*rprmcrosspprm2)
L0 /= Lmaginv
L1 /= Lmaginv
L2 /= Lmaginv
```

## ${\bf S}_{1}\cdot{\bf L}$ \[Back to [top](#toc)\]
$$\label{s1dotl}$$

We compute ${\bf r}^{\prime}\times{\bf p}^{\prime}$ and normalize as follows.

See LALSimIMRSpinEOBFactorizedFluxPrec_v3opt.c lines 121--129.

# Step 5: Invert the rotation of Step 3 \[Back to [top](#toc)\]
$$\label{step5}$$

## Inverse Rotation Matrix \[Back to [top](#toc)\]
$$\label{invrotationmatrix}$$

The matrix to invert the rotation applied in [Step 3](#step3) is:

\begin{equation*}
    \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf p}^{0} & \hat{\bf L}^{0} \\
        \hat{\bf r}^{1} & \hat{\bf p}^{1} & \hat{\bf L}^{1} \\
        \hat{\bf r}^{2} & \hat{\bf p}^{2} & \hat{\bf L}^{2}\end{bmatrix}.
\end{equation*}

To see that this is indeed the correct matrix inverse, note that by construction $\hat{\bf q}$, $\hat{\bf p}$, and $\hat{\bf L}$ are all unit vectors orthogonal to one another.  See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1107.

```python
invert00 = rhat0
invert01 = phat0
invert02 = Lhat0
invert10 = rhat1
invert11 = phat1
invert12 = Lhat1
invert20 = rhat2
invert21 = phat2
invert22 = Lhat2
```

## Rotate $\hat{\bf r}^{\prime}$ \[Back to [top](#toc)\]
$$\label{invrotaterhat}$$

We rotate $\hat{\bf r}^{\prime}$ and call the new separation vector ${\bf r}$.

\begin{equation*}
    \hat{\bf r} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf p}^{0} & \hat{\bf L}^{0} \\
        \hat{\bf r}^{1} & \hat{\bf p}^{1} & \hat{\bf L}^{1} \\
        \hat{\bf r}^{2} & \hat{\bf p}^{2} & \hat{\bf L}^{2} \end{bmatrix}
        \begin{bmatrix} \hat{\bf r}^{\prime 0} \\ \hat{\bf r}^{\prime 1} \\ \hat{\bf r}^{\prime 2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1315.

```python
rhat0 = rhat0*rhatprm0 + phat0*rhatprm1 + Lhat0*rhatprm2
rhat1 = rhat1*rhatprm0 + phat1*rhatprm1 + Lhat1*rhatprm2
rhat0 = rhat2*rhatprm0 + phat2*rhatprm1 + Lhat2*rhatprm2
```

## Rotate $\hat{\bf v}^{\prime}$ \[Back to [top](#toc)\]
$$\label{invrotatevhat}$$

We rotate $\hat{\bf v}^{\prime}$ and call the new separation vector ${\bf v}$.

\begin{equation*}
    \hat{\bf v} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf p}^{0} & \hat{\bf L}^{0} \\
        \hat{\bf r}^{1} & \hat{\bf p}^{1} & \hat{\bf L}^{1} \\
        \hat{\bf r}^{2} & \hat{\bf p}^{2} & \hat{\bf L}^{2} \end{bmatrix}
        \begin{bmatrix} \hat{\bf v}^{\prime 0} \\ \hat{\bf v}^{\prime 1} \\ \hat{\bf v}^{\prime 2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1316.

```python
vhat0 = rhat0*vhatprm0 + phat0*vhatprm1 + Lhat0*vhatprm2
vhat1 = rhat1*vhatprm0 + phat1*vhatprm1 + Lhat1*vhatprm2
vhat2 = rhat2*vhatprm0 + phat2*vhatprm1 + Lhat2*vhatprm2
```

## Rotate $\hat{\bf L}_{N}^{\prime}$ \[Back to [top](#toc)\]
$$\label{invrotatelnhat}$$

We rotate $\hat{\bf L}_{N}^{\prime}$ and call the new separation vector ${\bf L}_{N}$.

\begin{equation*}
    \hat{\bf L}_{N} = \begin{bmatrix} \hat{\bf r}^{0} & \hat{\bf p}^{0} & \hat{\bf L}^{0} \\
        \hat{\bf r}^{1} & \hat{\bf p}^{1} & \hat{\bf L}^{1} \\
        \hat{\bf r}^{2} & \hat{\bf p}^{2} & \hat{\bf L}^{2} \end{bmatrix}
        \begin{bmatrix} \hat{\bf L}_{N}^{\prime 0} \\ \hat{\bf L}_{N}^{\prime 1} \\ \hat{\bf L}_{N}^{\prime 2} \end{bmatrix}
\end{equation*}

See LALSimIMRSpinEOBInitialConditionsPrec.c Line 1317.

```python
LNhat0 = rhat0*LNhatprm0 + phat0*LNhatprm1 + Lhat0*LNhatprm2
LNhat1 = rhat1*LNhatprm0 + phat1*LNhatprm1 + Lhat1*LNhatprm2
LNhat2 = rhat2*LNhatprm0 + phat2*LNhatprm1 + Lhat2*LNhatprm2
```

# Tortoise Conversion Matrix \[Back to [top](#toc)\]
$$\label{tortoise_matrix}$$

We're now back to LALSpinPrecHcapRvecDerivative_v3opt.c, Lines 92--96.

From [Pan, Buonanno, Buchman, et. al. (2010)](https://arxiv.org/abs/0912.3466v2) Equation (A3) the matrix for the coordinate conversion to tortoise coordinates is

\begin{align*}
    \begin{pmatrix} 1 + \frac{ x^{2} }{ r^{2} } \left( \xi - 1 \right) & \frac{ x y }{ r^{2} } \left( \xi - 1 \right) & \frac{ x z }{ r^{2} } \left( \xi - 1 \right) \\
        \frac{ x y }{ r^{2} } \left( \xi - 1 \right) & 1 + \frac{ y^{2} }{ r^{2} } \left( \xi - 1 \right) & \frac{ y z }{ r^{2} } \left( \xi - 1 \right) \\
        \frac{ x z }{ r^{2} } \left( \xi - 1 \right) & \frac{ y z }{ r^{2} } \left( \xi - 1 \right) & 1 + \frac{ z^{2} }{ r^{2} } \left( \xi - 1 \right) \end{pmatrix}
\end{align*}

```python
ximinus1 = xi - 1
toTort = sp.Array([[1 + x*x*ximinus1/(r*r), x*y*ximinus1/(r*r), x*z*ximinus1/(r*r)],
                   [x*y*ximinus1/(r*r), 1 + y*y*ximinus1/(r*r), y*z*ximinus1/(r*r)],
                   [x*z*ximinus1/(r*r), y*z*ximinus1/(r*r), 1 + z*z*ximinus1/(r*r)]])
```

# Output: Output this module to $\LaTeX$-formatted PDF file \[Back to [top](#toc)\]
$$\label{latex_pdf_output}$$

```python
!jupyter nbconvert --to latex --template latex_nrpy_style.tplx Tutorial-SEOBNR_Initial_Conditions.ipynb
!pdflatex -interaction=batchmode Tutorial-SEOBNR_Initial_Conditions.tex
!pdflatex -interaction=batchmode Tutorial-SEOBNR_Initial_Conditions.tex
!pdflatex -interaction=batchmode Tutorial-SEOBNR_Initial_Conditions.tex
!rm -f Tut*.out Tut*.aux Tut*.log
```


 Trusted Notebook" width="500 px" align="left">

## _*Relaxation and Decoherence*_

The latest version of this notebook is available on https://github.com/qiskit/qiskit-tutorial.

***
### Contributors
Martin Sandberg, Hanhee Paik, Antonio Córcoles, Doug McClure, Jay Gambetta, and Yael Ben-Haim

```python
import numpy as np
import matplotlib.pyplot as plt

import qiskit
from qiskit.providers.aer.noise.errors.standard_errors import amplitude_damping_error
from qiskit.providers.aer.noise.errors.standard_errors import phase_damping_error
from qiskit.providers.aer.noise import NoiseModel

from qiskit.ignis.characterization.coherence import T1Fitter, T2StarFitter, T2Fitter
from qiskit.ignis.characterization.coherence import t1_circuits, t2_circuits, t2star_circuits
```

## Introduction

In an ideal world, quantum systems would be well-isolated from their environment, which would prevent unwanted dynamics of the quantum information we encode in them. For example, suppose we prepared a qubit in the $|1>$ state, but through interaction with the environment, the state is flipped to $|0>$. That flip could affect the outcome of a quantum algorithm that's being run using that qubit, meaning the answers we get out of the quantum device would change. For this reason, we seek to isolate quantum computers from the surrounding environment.

However, perfect isolation is not possible: after all, we have to be able to control the quantum computer, which means coupling it to external systems to manipulate quantum information. This tradeoff is sometimes referred to as the "Tao of quantum computing". Because our controls introduce coupling between qubits and the environment, we expect some unwanted interactions can occur.

These unwanted interactions introduce _noise_ into the qubits, which affects their behavior. The rate of these interactions sets characteristic timescales over which information encoded in qubits can be reliably stored and manipulated. (If the interaction has a rate $\Gamma$, the characteristic timescale is $\sim 1/\Gamma$.) In this tutorial, we discuss two timescales that arise from energy relaxation and decoherence -- usually referred to as $T_{1}$ and $T_{2}$, respectively -- and show how they can be measured.

# Measuring $T_1$ time

**Theory**

The $T_{1}$ time is the characteristic timescale over which the state of a qubit damps toward the $|0>$ state. Given an arbitrary initial single-qubit state $\rho(0)$, represented by a $2\times 2$ matrix as
$$\rho(0) = \begin{pmatrix}\rho_{00} & \rho_{01} \\ \rho_{01}^{\star} & \rho_{11}\end{pmatrix},$$
under amplitude damping noise, the state of the changes as
$$\rho(t) = \begin{pmatrix}\rho_{00} + (1-e^{-\Gamma_{1}t})\rho_{11} & e^{-\Gamma_{1}t/2}\rho_{01} \\ e^{-\Gamma_{1}t/2}\rho_{01}^{\star} & e^{-\Gamma_{1} t}\rho_{11}\end{pmatrix} \underset{t\rightarrow \infty}{\longrightarrow} |0><0|.$$

Notice that amplitude damping noise also removes any coherences between $|0>$ and $|1>$ of the state (the off-diagonal elements.) The rate at which this _decoherence_ occurs is half that of $\Gamma_{1}$.

The time evolution of the state under amplitude damping noise can be derived as the continuous-time limit of an amplitude damping channel
$$\mathcal{E}[\rho] = M_{0} \rho M_{0}^{\dagger} + M_{1}\rho M_{1}^{\dagger},$$
where
$$M_{0} = \begin{pmatrix} 1 & 0 \\0& \sqrt{1-p}\end{pmatrix}~,~M_{1} = \begin{pmatrix} 0 & \sqrt{p} \\ 0 & 0 \end{pmatrix},$$
and the probability of decay $p$ is $\Gamma_{1}\Delta t$.

The decay rate $\Gamma_{1}$ sets a natural time scale for the decay process; namely, $\Gamma^{-1}$. This number is often called the $T_{1}$ time. Notice the off-diagonal elements also decay, with characteristic decay rate $\Gamma /2$.

Notice that the probability of the qubit remaining in the $|1>$ state is given by

$$P_{1}(t) = \mathrm{Tr}\left[ |1><1| \rho(t)\right] = e^{-\Gamma_{1} t}\rho_{11}.$$

If the qubit was prepared in the $|1>$ state, then $P_{1}(t) =e^{-\Gamma_{1} t}$.

A simple way of estimating the $T_{1}$ time is to collect statistics about the decay curve for $P_{1}(t)$ when the qubit is initialized to $|1>$. This can be done by choosing a variety of times $t_{1}, t_{2}, \cdots t_{N}$, and then running the following experiment many times:
* Prepare the qubit in $|1>$.
* Wait a delay time $t_{j}$.
* Measure the qubit in the $|0>, |1>$ basis.

An estimate of $P_{1}(t_{j})$ is the number of times the qubit was observed to be in $|1>$, divided by the total number of times the experiment was repeated. Given several estimated values of $P_{1}$ for a variety of $(t_{j})$, we can fit the resulting decay curve is fit to an exponential and extract an estimate of $\Gamma_{1}$, and hence, the $T_{1}$ time.

The IBM Q Experience does not currently support delays of arbitrary length, so for now, we just append a series of identity operations after the initial excitation pulse. Each identity operation has the same duration of a single-qubit gate and is followed by a -shorter- buffer time. These parameters are backend-dependent.

**Code**

The code blocks below walk through constructing the requisite experiments to estimate the $T_{1}$ time of a qubit, sending those experiments to a simulator, and then fitting the data the simulator sends back.

```python
# 12 numbers ranging from 10 to 1000, logarithmically spaced
# extra point at 1500
num_of_gates = np.append((np.logspace(1, 3, 12)).astype(int), np.array([1500]))
gate_time = 0.1

# Select the qubits whose T1 are to be measured
qubits = [0]

# Generate experiments
circs, xdata = t1_circuits(num_of_gates, gate_time, qubits)
```

One of the features of the fitters are that we can split the circuits into multiple jobs and then give the results to the fitter as a list. Demonstrated below.

```python
# Set the simulator with amplitude damping noise
t1 = 25.0
gamma = 1 - np.exp(-gate_time/t1)
error = amplitude_damping_error(gamma)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])

# Run the simulator
backend = qiskit.Aer.get_backend('qasm_simulator')
shots = 200
backend_result = qiskit.execute(circs, backend,
                                shots=shots, noise_model=noise_model).result()
```

```python
%matplotlib inline
# Fit the data to an exponential
# The correct answers are a=1, and c=0, and t1=25/15 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location

initial_t1 = t1*1.2
initial_a = 1.0
initial_c = 0.0

fit = T1Fitter(backend_result, xdata, qubits,
               fit_p0=[initial_a, initial_t1, initial_c],
               fit_bounds=([0, 0, -1], [2, initial_t1*2, 1]))

fit.plot(0)
```

# Measuring $T_2^*$ time

**Theory**

Amplitude damping noise affects the off-diagonal elements of the density matrix in addition to the on-diagonal elements. However, there are other noise processes that only affect the off-diagonal elements, while keeping the on-diagonal elements the same. These kinds of noise processes cause _decoherence_.

As a simple example of decoherence, consider the pure superposition state
$$| \psi(\theta) > = \frac{1}{\sqrt{2}}\left(|0> + e^{i\theta} |1>\right).$$
Expressed as a density matrix, this state is
$$\rho(\theta) = | \psi(\theta) >< \psi(\theta) | = \frac{1}{2}\begin{pmatrix}1 & e^{-i\theta} \\ e^{i\theta} & 1\end{pmatrix}.$$

This state has _coherence_ between $|0>$ and $|1>$, which manifests itself in the non-zero off-diagonal terms. If the state had _decohered_, those off-diagonal terms would be zero:
$$\rho_{\mathrm{decohered}} =  \frac{1}{2}\begin{pmatrix}1 & 0 \\ 0 & 1\end{pmatrix}.$$
When the state has decohered, it can be written as a classical _mixture_:
$$\rho_{\mathrm{decohered}} = \frac{1}{2}\left(|0><0| + |1><1| \right).$$

One mechanism by which decoherence happens is _dephasing_. Under dephasing noise, the state of the qubit evolves as
$$\rho(t) = \begin{pmatrix}\rho_{00} & e^{-\Gamma_{2}t}\rho_{01} \\ e^{-\Gamma_{2}t}\rho_{01}^{\star} & \rho_{11}\end{pmatrix} \underset{t\rightarrow \infty}{\longrightarrow} \begin{pmatrix}\rho_{00} & 0\\ 0& \rho_{11}\end{pmatrix}.$$

The time evolution of $\rho$ under dephasing noise can be derived as the continuous-time limit of the following noise channel:
$$\mathcal{E}[\rho] = M_{0}\rho M_{0}^{\dagger} + M_{1} \rho M_{1}^{\dagger} + M_{2}\rho M_{2}^{\dagger},$$
where
$$M_{0} =\sqrt{1-p}I~,~M_{1} = \sqrt{p}\begin{pmatrix}1 &0 \\ 0 & 0 \end{pmatrix}~,~M_{2} = \sqrt{p}\begin{pmatrix}0 & 0 \\ 0 & 1\end{pmatrix}.$$

The rate of decay in the coherences can be measured by the following experiment:

* Prepare the qubit in the $|+>$ state, which can be done by initializing the qubit to $|0>$ and applying a Hadamard gate, $H$.
* Wait a delay time $t_{j}$.
* Measure the qubit in the $| \pm >$ basis, which can be done by applying a Hadamard and then measuring in the computational basis.

If decoherence processes are present, then after a delay time $t_{j}$, the state of the qubit is

$$\rho(t_{j}) = \frac{1}{2}\begin{pmatrix}1 & e^{-\Gamma_{2}t_{j}} \\ e^{-\Gamma_{2}t_{j}} & 1\end{pmatrix}.$$

Measuring in the $| \pm >$ basis, the probability of observing the outcome $|+>$ is given by

$$P_{+}(t_{j}) = \mathrm{Tr}\left(|+><+| \rho(t_{j})\right) = \frac{1}{2}\left(1 + e^{-\Gamma_{2}t_{j}}\right).$$

Again, by estimating $P_{+}(t_{j})$ for a variety of $t_{j}$, we can then fit a decay curve to extract an estimate of $\Gamma_{2}$.

In the actual experiment, we change the phase of the pulse before the measurement in order to create oscillations in the observed dynamics of $P_{+}(t_{j})$. If we just did two Hadamard gates separated by a delay, we would observe a decay of characteristic time $T^*_2$, but with a strong dependence on any deviation of the calibrated qubit frequency from the actual one. By implementing the qubit pulses with different phases, we shift the frequency dependence into the oscillating feature of the dynamics, and can fit the decaying envelope for a more faithful measure of the coherence time.

<div class="alert alert-block alert-danger">

There is one subtle point of note. In the discussion of $T_{1}$ time above, we saw that amplitude damping noise also causes the off-diagonal elements to decay (at a rate $\Gamma_{1}/2$). Suppose a qubit was affected by only amplitude damping noise, and dephasing noise was absent. In this scenaro, _the rate of decay of coherences can be non-zero, even in the absense of dephasing noise_.

For this reason, it's important to recognize there are many noise processes contributing to the rate at which coherences decay. In this tutorial, we assume that the total rate of decoherence, $\Gamma$, can be decomposed into a sum of independent rates:

$$\Gamma = \Gamma_{T_{1}} + \Gamma_{2} + \Gamma_{\mathrm{other}}. $$

Phenomenologically, the rate $\Gamma_{\mathrm{other}}$ quantifies the rate of decoherence due to other noise processes in addition to pure amplitude damping and pure dephasing about the $Z$-axis. Note that because general noise can cause dephasing about the $Z$-axis -- in addition to doing other things to the qubit -- echo sequences are typically used to help mitigate the effects of those kind(s) of noise on $T_{2}^{\star}$. (Echo sequences are discussed below, in the sections $T_{2}$ echo  and CPMG measurement.)

If decoherence at a rate $\Gamma$ is taking place, then the state of the qubit changes as
$$\begin{equation}
\rho(t) = \begin{pmatrix}\rho_{00} & e^{-\Gamma t}\rho_{01} \\ e^{-\Gamma t}\rho_{01}^{\star} & 1-\rho_{00}\end{pmatrix}.
\end{equation}$$

The timescale associated with this decay rate is called $T_{2}$, and is given by $T_{2} = 1/\Gamma$.

$T_{2}$ relates to the other timescales introduced previously as
$$T_{2} = \left(\frac{2}{T_{1}} + \frac{1}{T_{2}} + \frac{1}{T_{\mathrm{other}}}\right)^{-1} = T_{2}^{\star}\left( 1 + \frac{2T_{2}^{\star}}{T_{1}} + \frac{T^{\star}_{2}}{T_{\mathrm{other}}}\right)^{-1} \leq T_{2}^{\star},$$
where we've defined $T_{\mathrm{other}}  = 1 /\Gamma_{\mathrm{other}}$.

</div>

```python
# 50 points linearly spaced in two regions (fine and coarse)
# 30 from 10->150, 20 from 160->450
num_of_gates = np.append((np.linspace(10, 150, 30)).astype(int), (np.linspace(160,450,20)).astype(int))
gate_time = 0.1

# Select the qubits whose T2* are to be measured
qubits = [0]

# Generate experiments
circs, xdata, osc_freq = t2star_circuits(num_of_gates, gate_time, qubits, nosc=5)
```

```python
backend = qiskit.Aer.get_backend('qasm_simulator')

# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])

# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
                                shots=shots, noise_model=noise_model).result()
```

```python
%matplotlib inline
# Fit the data to an oscillator
# The correct answers are a=0.5, f=osc_freq, phi=0, c=0.5, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location

initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5
initial_f = osc_freq
initial_phi = -np.pi/20

fit = T2StarFitter(backend_result, xdata, qubits,
                   fit_p0=[initial_a, initial_t2, initial_f, initial_phi, initial_c],
                   fit_bounds=([-0.5, 0, 0, -np.pi, -0.5],
                               [1.5, 2*t2, 2*osc_freq, np.pi, 1.5]))

fit.plot(0)
```

## Measuring T2 Time using a single echo pulse

We have referred to the previous experiment's characteristic time as 𝑇∗2 and not 𝑇2

by analogy to nuclear magnetic resonance (NMR). Indeed, one can isolate different frequency components to the decoherence process by devising increasingly elaborated pulse sequences. To illustrate the analogy with NMR, one can think about an ensemble of nuclear spins precessing in an external DC magnetic field. Due to field inhomogeneities, each spin might precess with a slightly different Larmor frequency. This certainly will affect the observed coherence time of the ensemble. However, it is possible to echo away this low-frequency decoherence process by applying a pi-pulse to the system halfway through the delay. The effect of this pi-pulse is to reverse the direction of the precession of each individual spin due to field inhomogeneities. Thus, the spins that had precessed more now start precessing in the opposite direction faster than the spins that had precessed less, and after an equal delay, all the spins in the system recover the initial coherence, except for other, higher-frequency, decoherence mechanisms.

Here, we are measuring only a single qubit rather than an ensemble of spins. Consequently coherence measurements require averaging an ensemble of measurements in order to eliminate projection noise, and run-to-run fluctuations in the qubit's frequency which will similarly manifest themselves as decoherence if they are not canceled out. By running this 𝑇2
echo sequence, we can therefore remove low-frequency components of the decoherence.

```python
# 50 points linearly spaced to 300
num_of_gates = (np.linspace(10, 300, 50)).astype(int)
gate_time = 0.1

# Select the qubits whose T2 are to be measured
qubits = [0]

# Generate experiments
circs, xdata = t2_circuits(num_of_gates, gate_time, qubits)
```

```python
backend = qiskit.Aer.get_backend('qasm_simulator')

# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])

# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
                                shots=shots, noise_model=noise_model).result()
```

```python
%matplotlib inline
# Fit the data to an exponent
# The correct answers are a=1, c=0, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location

initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5

fit = T2Fitter(backend_result, xdata, qubits,
               fit_p0=[initial_a, initial_t2, initial_c],
               fit_bounds=([-0.5, 0, -0.5],
                           [1.5, 2*t2, 1.5]))

fit.plot(0)
```

## Measuring T2 Time by a  CPMG sequence

As explained above, the echo sequence removes low-frequency decoherence mechanisms. This noise-filtering procedure can be extended with increased number of pi-pulses within the delay. In the following experiment, we implement an echo experiment with seven pi-pulses during the delay between the initial and final pulses. This kind of echo with several pi-pulses is referred to as a CPMG experiment, after Carr, Purcell, Meiboom, and Gill.

```python
num_of_gates = (np.linspace(1, 30, 30)).astype(int)
gate_time = 0.1

# Select the qubits whose T2 are to be measured
qubits = [0]

# Echo parameters
n_echos = 5
alt_phase_echo = True

# Generate experiments
circs, xdata = t2_circuits(num_of_gates, gate_time, qubits, n_echos, alt_phase_echo)
```

```python
backend = qiskit.Aer.get_backend('qasm_simulator')

# Set the simulator with phase damping noise
t2 = 10
p = 1 - np.exp(-2*gate_time/t2)
error = phase_damping_error(p)
noise_model = NoiseModel()
noise_model.add_quantum_error(error, 'id', [0])

# Run the simulator
shots = 300
backend_result = qiskit.execute(circs, backend,
                                shots=shots, noise_model=noise_model).result()
```

```python
%matplotlib inline
# Fit the data to an exponent
# The correct answers are a=1, c=0, and t2=10/5 for qubit 0/2
# The user does not know the correct answer exactly,
# so starts the fit from a different but close location

initial_t2 = t2*1.1
initial_a = 0.5
initial_c = 0.5

fit = T2Fitter(backend_result, xdata, qubits,
               fit_p0=[initial_a, initial_t2, initial_c],
               fit_bounds=([-0.5, 0, -0.5],
                           [1.5, 2*t2, 1.5]))

fit.plot(0)
```


```python
import gk
```

```python
import sympy as sym
```

```python
dir(gk)
```

    ['AA',
     'AbelianGroup',
     'AbelianGroupMorphism',
     'AbelianGroupWithValues',
     'AbelianVariety',
     'AdditiveAbelianGroup',
     'AdditiveAbelianGroupWrapper',
     'AdditiveAbelianGroupWrapperElement',
     'AdditiveMagmas',
     'AffineCryptosystem',
     'AffineGroup',
     'AffineHypersurface',
     'AffineNilTemperleyLiebTypeA',
     'AffinePermutationGroup',
     'AffineSpace',
     'AffineToricVariety',
     'AffineWeylGroups',
     'AlarmInterrupt',
     'Algebra',
     'AlgebraIdeals',
     'AlgebraModules',
     'AlgebraicField',
     'AlgebraicNumber',
     'AlgebraicReal',
     'AlgebraicRealField',
     'Algebras',
     'AlgebrasWithBasis',
     'AllCusps',
     'AllExactCovers',
     'Alphabet',
     'AlphabeticStrings',
     'AlternatingGroup',
     'AlternatingSignMatrices',
     'AlternatingSignMatrix',
     'ArithmeticSubgroup_Permutation',
     'Arrangements',
     'ArtinGroup',
     'AsymptoticRing',
     'AtkinModularCorrespondenceDatabase',
     'AtkinModularPolynomialDatabase',
     'AugmentedLatticeDiagramFilling',
     'Automaton',
     'Axiom',
     'BackslashOperator',
     'BaxterPermutations',
     'Bessel',
     'BezoutianQuadraticForm',
     'Bialgebras',
     'BialgebrasWithBasis',
     'Bimodules',
     'BinaryQF',
     'BinaryQF_reduced_representatives',
     'BinaryRecurrenceSequence',
     'BinaryStrings',
     'BinaryTree',
     'BinaryTrees',
     'BipartiteGraph',
     'Bitset',
     'BlockDesign',
     'BooleanPolynomialRing',
     'BraidGroup',
     'BranchingRule',
     'BrandtModule',
     'BrauerAlgebra',
     'BruhatTitsQuotient',
     'CBF',
     'CC',
     'CDF',
     'CFiniteSequence',
     'CFiniteSequences',
     'CIF',
     'CLF',
     'CPRFanoToricVariety',
     'CRT',
     'CRT_basis',
     'CRT_list',
     'CRT_vectors',
     'CachedFunction',
     'CallableSymbolicExpressionRing',
     'CartanMatrix',
     'CartanType',
     'CartesianProduct',
     'Category',
     'ChainComplex',
     'ChainComplexMorphism',
     'ChainComplexes',
     'Chi',
     'Ci',
     'ClassFunction',
     'ClassicalCrystals',
     'ClassicalModularPolynomialDatabase',
     'CliffordAlgebra',
     'ClusterAlgebra',
     'ClusterComplex',
     'ClusterQuiver',
     'ClusterSeed',
     'Coalgebras',
     'CoalgebrasWithBasis',
     'Color',
     'ColoredPermutations',
     'Combinations',
     'CombinatorialAlgebra',
     'CombinatorialClass',
     'CombinatorialFreeModule',
     'CombinatorialObject',
     'CombinatorialSpecies',
     'CommutativeAdditiveGroups',
     'CommutativeAdditiveMonoids',
     'CommutativeAdditiveSemigroups',
     'CommutativeAlgebraElement',
     'CommutativeAlgebraIdeals',
     'CommutativeAlgebras',
     'CommutativeRing',
     'CommutativeRingElement',
     'CommutativeRingIdeals',
     'CommutativeRings',
     'CompleteDiscreteValuationFields',
     'CompleteDiscreteValuationRings',
     'ComplexBallField',
     'ComplexDoubleElement',
     'ComplexDoubleField',
     'ComplexField',
     'ComplexIntervalField',
     'ComplexIntervalFieldElement',
     'ComplexLazyField',
     'ComplexNumber',
     'Complexes',
     'Composition',
     'CompositionTableau',
     'CompositionTableaux',
     'Compositions',
     'Cone',
     'CongruenceSubgroup',
     'Conic',
     'ConjugacyClass',
     'ConjugacyClassGAP',
     'ConstantFunction',
     'Constellation',
     'Constellations',
     'ContreTableaux',
     'ConwayPolynomials',
     'CooperativeGame',
     'CoordinatePatch',
     'Core',
     'Cores',
     'CoveringDesign',
     'CoxeterGroup',
     'CoxeterGroups',
     'CoxeterMatrix',
     'CoxeterType',
     'CremonaDatabase',
     'CremonaModularSymbols',
     'Crystals',
     'CubeGroup',
     'CubicalComplex',
     'Curve',
     'Cusp',
     'CuspFamily',
     'CuspForms',
     'Cusps',
     'CyclicPermutationGroup',
     'CyclicPermutations',
     'CyclicPermutationsOfPartition',
     'CyclicSievingCheck',
     'CyclicSievingPolynomial',
     'CyclotomicField',
     'Cylindrical',
     'DLXCPP',
     'DLXMatrix',
     'DOT_SAGE',
     'DWT',
     'DeBruijnSequences',
     'DedekindDomain',
     'DedekindDomainElement',
     'DedekindEtaModularCorrespondenceDatabase',
     'DedekindEtaModularPolynomialDatabase',
     'DegreeSequences',
     'DeltaComplex',
     'Derangements',
     'DescentAlgebra',
     'DiCyclicGroup',
     'DiGraph',
     'DiagonalQuadraticForm',
     'DifferentialForm',
     'DifferentialForms',
     'DifferentialWeylAlgebra',
     'DihedralGroup',
     'DirichletGroup',
     'DiscreteProbabilitySpace',
     'DiscreteRandomVariable',
     'DiscreteValuationFields',
     'DiscreteValuationRings',
     'DiscreteValueGroup',
     'DisjointSet',
     'DisjointUnionEnumeratedSets',
     'DivisionRings',
     'Dokchitser',
     'Domains',
     'DyckWord',
     'DyckWords',
     'DynamicalSystem',
     'DynamicalSystem_affine',
     'DynamicalSystem_projective',
     'DynkinDiagram',
     'E',
     'ECM',
     'Ei',
     'EisensteinForms',
     'EisensteinIntegers',
     'ElementWrapper',
     'Elements',
     'EllipticCurve',
     'EllipticCurveIsogeny',
     'EllipticCurve_from_c4c6',
     'EllipticCurve_from_cubic',
     'EllipticCurve_from_j',
     'EllipticCurves_with_good_reduction_outside_S',
     'EmptySetError',
     'End',
     'EnumeratedSets',
     'EquationOrder',
     'EtaGroup',
     'EtaGroupElement',
     'EtaProduct',
     'EuclideanDomain',
     'EuclideanDomainElement',
     'EuclideanDomains',
     'EuclideanGroup',
     'EuclideanSpace',
     'Euler_Phi',
     'Expression',
     'ExtendedAffineWeylGroup',
     'ExteriorAlgebra',
     'FFT',
     'FaceFan',
     'Factorization',
     'Family',
     'Fan',
     'Fan2d',
     'FanMorphism',
     'FareySymbol',
     'FastFourierTransform',
     'Field',
     'FieldElement',
     'Fields',
     'FilteredCombinatorialClass',
     'FilteredVectorSpace',
     'FiniteCoxeterGroups',
     'FiniteCrystals',
     'FiniteDimensionalAlgebra',
     'FiniteDimensionalAlgebrasWithBasis',
     'FiniteDimensionalBialgebrasWithBasis',
     'FiniteDimensionalCoalgebrasWithBasis',
     'FiniteDimensionalHopfAlgebrasWithBasis',
     'FiniteDimensionalModulesWithBasis',
     'FiniteEnumeratedSet',
     'FiniteEnumeratedSets',
     'FiniteField',
     'FiniteFields',
     'FiniteGroups',
     'FiniteLatticePosets',
     'FiniteMonoids',
     'FinitePermutationGroups',
     'FinitePosets',
     'FiniteRankFreeModule',
     'FiniteSemigroups',
     'FiniteSetMaps',
     'FiniteSets',
     'FiniteStateMachine',
     'FiniteWeylGroups',
     'FiniteWords',
     'FockSpace',
     'ForgetfulFunctor',
     'FormalSum',
     'FormalSums',
     'Frac',
     'FractionField',
     'FreeAbelianMonoid',
     'FreeAlgebra',
     'FreeAlgebraQuotient',
     'FreeGroup',
     'FreeModule',
     'FreeModules',
     'FreeMonoid',
     'FreeQuadraticModule',
     'FreeQuasisymmetricFunctions',
     'FreeSymmetricFunctions',
     'FriCAS',
     'FrozenBitset',
     'FullyPackedLoop',
     'FullyPackedLoops',
     'FunctionField',
     'FunctionFields',
     'FusionRing',
     'G1list',
     'GCD',
     'GF',
     'GHlist',
     'GL',
     'GO',
     'GSets',
     'GU',
     'Gamma',
     'Gamma0',
     'Gamma0_NFCusps',
     'Gamma1',
     'GammaH',
     'Gap',
     'Gap3',
     'GaussValuation',
     'GaussianIntegers',
     'GcdDomains',
     'GelfandTsetlinPattern',
     'GelfandTsetlinPatterns',
     'GeneralDihedralGroup',
     'GeneralDiscreteDistribution',
     'GenericGraphQuery',
     'Genus',
     'Genus2reduction',
     'Gfan',
     'Giac',
     'Gp',
     'GradedAlgebras',
     'GradedAlgebrasWithBasis',
     'GradedBialgebras',
     'GradedBialgebrasWithBasis',
     'GradedCoalgebras',
     'GradedCoalgebrasWithBasis',
     'GradedCommutativeAlgebra',
     'GradedHopfAlgebras',
     'GradedHopfAlgebrasWithBasis',
     'GradedModules',
     'GradedModulesWithBasis',
     'Graph',
     'GraphDatabase',
     'GraphPaths',
     'GraphQuery',
     'Graphics',
     'GroupAlgebra',
     'GroupAlgebras',
     'GroupExp',
     'GroupExpElement',
     'GroupExp_Class',
     'GroupSemidirectProduct',
     'GroupSemidirectProductElement',
     'Groupoid',
     'Groups',
     'GrowthDiagram',
     'GrowthDiagramBinWord',
     'GrowthDiagramBurge',
     'GrowthDiagramDomino',
     'GrowthDiagramRSK',
     'GrowthDiagramSylvester',
     'GrowthDiagramYoungFibonacci',
     'HallAlgebra',
     'Hasse_bounds',
     'HeckeAlgebraSymmetricGroupT',
     'HeckeModules',
     'HeilbronnCremona',
     'HeilbronnMerel',
     'HexadecimalStrings',
     'HighestWeightCrystals',
     'HilbertClassPolynomialDatabase',
     'HillCryptosystem',
     'Hom',
     'Homset',
     'HomsetWithBase',
     'HopfAlgebras',
     'HopfAlgebrasWithBasis',
     'HyperbolicPlane',
     'HyperbolicPlane_quadratic_form',
     'HyperellipticCurve',
     'HyperellipticCurve_from_invariants',
     'Hypergraph',
     'HyperplaneArrangements',
     'I',
     'Ideal',
     'Ideals',
     'IdentityFunctor',
     'IncidenceStructure',
     'IncreasingTableau',
     'IncreasingTableaux',
     'IndexedSequence',
     'InfiniteAbstractCombinatorialClass',
     'InfiniteEnumeratedSets',
     'InfinitePolynomialRing',
     'InfiniteWords',
     'Infinity',
     'InfinityRing',
     'InnerProductSpace',
     'IntList',
     'Integer',
     'IntegerListsLex',
     'IntegerMod',
     'IntegerModRing',
     'IntegerRange',
     'IntegerRing',
     'IntegerVectors',
     'IntegerVectorsModPermutationGroup',
     'Integers',
     'IntegrableRepresentation',
     'IntegralDomain',
     'IntegralDomainElement',
     'IntegralDomains',
     'IntegralLattice',
     'InteractiveLPProblem',
     'InteractiveLPProblemStandardForm',
     'IwahoriHeckeAlgebra',
     'J0',
     'J1',
     'JH',
     'Jacobian',
     'JoinSemilattice',
     'JonesDatabase',
     'JordanAlgebra',
     'Kash',
     'KazhdanLusztigPolynomial',
     'KleinFourGroup',
     'KleshchevPartitions',
     'Knot',
     'Knots',
     'KnutsonTaoPuzzleSolver',
     'KodairaSymbol',
     'KostkaFoulkesPolynomial',
     'KoszulComplex',
     'KummerSurface',
     'LCM',
     'LFSRCryptosystem',
     'LFunctionZeroSum',
     'LabelledBinaryTree',
     'LabelledBinaryTrees',
     'LabelledOrderedTree',
     'LabelledOrderedTrees',
     'LabelledRootedTree',
     'LabelledRootedTrees',
     'LatexExpr',
     'LatinSquare',
     'LatinSquare_generator',
     'LatticeDiagram',
     'LatticePolytope',
     'LatticePoset',
     'LatticePosets',
     'LaurentPolynomialRing',
     'LaurentSeries',
     'LaurentSeriesRing',
     'LazyLaurentSeriesRing',
     'LazyPowerSeriesRing',
     'LeftModules',
     'Li',
     'LiE',
     'LieAlgebra',
     'LieAlgebras',
     'LinearCode',
     'LinearCodeFromVectorSpace',
     'Link',
     'Lisp',
     'LittlewoodRichardsonTableau',
     'LittlewoodRichardsonTableaux',
     'LocalComponent',
     'LyndonWord',
     'LyndonWords',
     'MPComplexField',
     'MSymbol',
     'MacMahonOmega',
     'Macaulay2',
     'Magma',
     'Magmas',
     'Manifold',
     'MapCombinatorialClass',
     'Maple',
     'Mat',
     'MatchingGame',
     'Mathematica',
     'MathieuGroup',
     'Matlab',
     'Matrix',
     'MatrixAlgebras',
     'MatrixGroup',
     'MatrixSpace',
     'Matroid',
     'Maxima',
     'MeetSemilattice',
     'Mestre_conic',
     'Minimog',
     'MixedIntegerLinearProgram',
     'Mod',
     'ModularAbelianVarieties',
     'ModularForms',
     'ModularFormsRing',
     'ModularSymbols',
     'ModularSymbols_clear_cache',
     'Modules',
     'ModulesWithBasis',
     'Moebius',
     'MonoidAlgebras',
     'Monoids',
     'MonotoneTriangles',
     'Morphism',
     'MultiFilteredVectorSpace',
     'MultiSkewTableau',
     'MultiSkewTableaux',
     'Mupad',
     'Mutability',
     'Mwrank',
     'N',
     'NFCusp',
     'NFCusps',
     'NN',
     'NaN',
     'Necklaces',
     'NefPartition',
     'Newform',
     'Newforms',
     'NilCoxeterAlgebra',
     'NonCommutativeSymmetricFunctions',
     'NonDecreasingParkingFunction',
     'NonDecreasingParkingFunctions',
     'NonNegativeIntegerSemiring',
     'NonNegativeIntegers',
     'NonSymmetricMacdonaldPolynomials',
     'NonattackingFillings',
     'NormalFan',
     'NormalFormGame',
     'NumberField',
     'NumberFieldElement',
     'NumberFieldTower',
     'NumberFields',
     'O',
     'Objects',
     'OctalStrings',
     'Octave',
     'OneExactCover',
     'OpenInterval',
     'OrderedMonoids',
     'OrderedMultisetPartitionIntoSets',
     'OrderedMultisetPartitionsIntoSets',
     'OrderedPartitions',
     'OrderedSetPartition',
     'OrderedSetPartitions',
     'OrderedSets',
     'OrderedTree',
     'OrderedTrees',
     'OverconvergentDistributions',
     'OverconvergentModularForms',
     'P1List',
     'P1NFList',
     'PGL',
     'PGU',
     'PSL',
     'PSU',
     'PSage',
     'PSp',
     'Parallelism',
     'ParallelogramPolyomino',
     'ParallelogramPolyominoes',
     'ParametrizedSurface3D',
     'Parent',
     'ParentWithBase',
     'ParentWithGens',
     'Pari',
     'PariError',
     'PariGroup',
     'PariRing',
     'ParkingFunction',
     'ParkingFunctions',
     'PartiallyOrderedMonoids',
     'PartiallyOrderedSets',
     'Partition',
     'PartitionAlgebra',
     'PartitionTuple',
     'PartitionTuples',
     'Partitions',
     'PartitionsGreatestEQ',
     'PartitionsGreatestLE',
     'PartitionsInBox',
     'PerfectMatching',
     'PerfectMatchings',
     'PeriodicSolitonCellularAutomata',
     'Permutation',
     'PermutationGroup',
     'PermutationGroupElement',
     'PermutationGroupMap',
     'PermutationGroupMorphism',
     'PermutationGroupMorphism_id',
     'PermutationGroupMorphism_im_gens',
     'PermutationGroup_generic',
     'PermutationGroup_subgroup',
     'PermutationGroups',
     'Permutations',
     'PlanarAlgebra',
     'PlanePartition',
     'PlanePartitions',
     'PointConfiguration',
     'PointedSets',
     'PollackStevensModularSymbols',
     'PolyhedralSets',
     'Polyhedron',
     'Polynomial',
     'PolynomialQuotientRing',
     'PolynomialQuotientRingElement',
     'PolynomialRing',
     'Poset',
     'Posets',
     'PositiveIntegers',
     'PowComputer',
     'PowComputer_ext_maker',
     'PowerSeries',
     'PowerSeriesRing',
     'PrimarySimilarityClassType',
     'PrimarySimilarityClassTypes',
     'Primes',
     'PrimitiveGroup',
     'PrimitiveGroups',
     'PrincipalIdealDomain',
     'PrincipalIdealDomainElement',
     'PrincipalIdealDomains',
     'ProductProjectiveSpaces',
     'Profiler',
     'ProjectiveHypersurface',
     'ProjectiveSpace',
     'PropagatingIdeal',
     'QQ',
     'QQbar',
     'QSystem',
     'Qp',
     'QpCR',
     'QpFP',
     'QpLC',
     'QpLF',
     'Qq',
     'QqCR',
     'QqFP',
     'QuadraticBernoulliNumber',
     'QuadraticField',
     'QuadraticForm',
     'QuadraticSpace',
     'QuantumGroup',
     'QuarticCurve',
     'QuasiSymmetricFunctions',
     'QuaternionAlgebra',
     'QuaternionGroup',
     'QuaternionMatrixGroupGF3',
     'QuiverMutationType',
     'QuotientFields',
     'QuotientRing',
     'R',
     'RBF',
     'RDF',
     'RIF',
     'RLF',
     'RR',
     'RSK',
     'RSK_inverse',
     'Radix64Strings',
     'Rational',
     'RationalCherednikAlgebra',
     'RationalField',
     'Rationals',
     'RealBallField',
     'RealDistribution',
     'RealDoubleElement',
     'RealDoubleField',
     'RealField',
     'RealInterval',
     'RealIntervalField',
     'RealLazyField',
     'RealLine',
     'RealNumber',
     'RealSet',
     'Realizations',
     'Reals',
     'RecursivelyEnumeratedSet',
     'ReflectionGroup',
     'ReflexivePolytope',
     'ReflexivePolytopes',
     'RegularCrystals',
     'ResidueField',
     'RibbonGraph',
     'RibbonShapedTableau',
     'RibbonShapedTableaux',
     'RibbonTableau',
     'RibbonTableaux',
     'Riemann_Map',
     'RiggedConfigurations',
     'RightAngledArtinGroup',
     'RightModules',
     'Ring',
     'RingElement',
     'RingIdeals',
     'RingModules',
     'Rings',
     'Rngs',
     'RootSystem',
     'RootedTree',
     'RootedTrees',
     'RowStandardTableau',
     'RowStandardTableauTuple',
     'RowStandardTableauTuples',
     'RowStandardTableaux',
     'RubiksCube',
     'SAGE_DB',
     'SAGE_DOC_SRC',
     'SAGE_ENV',
     'SAGE_LOCAL',
     'SAGE_ROOT',
     'SAGE_SRC',
     'SAGE_TMP',
     'SAT',
     'SL',
     'SL2Z',
     'SO',
     'SQLDatabase',
     'SQLQuery',
     'SR',
     'SU',
     'Sage',
     'SageObject',
     'Sandpile',
     'SandpileConfig',
     'SandpileDivisor',
     'Schemes',
     'SchubertPolynomialRing',
     'SchurAlgebra',
     'SchurTensorModule',
     'SemidefiniteProgram',
     'SemidihedralGroup',
     'Semigroups',
     'SemimonomialTransformationGroup',
     'Semirings',
     'SemistandardMultiSkewTableaux',
     'SemistandardSkewTableaux',
     'SemistandardTableau',
     'SemistandardTableaux',
     'Sequence',
     'Set',
     'SetPartition',
     'SetPartitions',
     'SetPartitionsAk',
     'SetPartitionsBk',
     'SetPartitionsIk',
     'SetPartitionsPRk',
     'SetPartitionsPk',
     'SetPartitionsRk',
     'SetPartitionsSk',
     'SetPartitionsTk',
     'Sets',
     'SetsWithGrading',
     'SetsWithPartialMaps',
     'Shi',
     'ShiftCryptosystem',
     'ShiftedPrimedTableau',
     'ShiftedPrimedTableaux',
     'ShrinkingGeneratorCryptosystem',
     'ShuffleAlgebra',
     'Si',
     'Sigma',
     'SignalError',
     'SignedCompositions',
     'SignedPermutations',
     'SimilarityClassType',
     'SimilarityClassTypes',
     'Simplex',
     'SimplicialComplex',
     'SimplicialComplexMorphism',
     'SimplicialComplexes',
     'SineGordonYsystem',
     'Singular',
     'SixVertexModel',
     'SkewPartition',
     'SkewPartitions',
     'SkewPolynomialRing',
     'SkewTableau',
     'SkewTableaux',
     'SloaneEncyclopedia',
     'SolitonCellularAutomata',
     'Sp',
     'Spec',
     'Spherical',
     'SphericalDistribution',
     'SphericalElevation',
     'Spline',
     'SplitMetacyclicGroup',
     'Sq',
     'StandardBracketedLyndonWords',
     'StandardRibbonShapedTableaux',
     'StandardSkewTableaux',
     'StandardTableau',
     'StandardTableauTuple',
     'StandardTableauTuples',
     'StandardTableaux',
     'SteenrodAlgebra',
     'SteinWatkinsAllData',
     'SteinWatkinsPrimeData',
     'StrongTableau',
     'StrongTableaux',
     'Subsets',
     'SubstitutionCryptosystem',
     'SubwordComplex',
     'Subwords',
     'Sudoku',
     'SuperPartition',
     'SuperPartitions',
     'SupersingularModule',
     'SuzukiGroup',
     'SymbolicData',
     'SymbolicLogic',
     'Symk',
     'SymmetricFunctions',
     'SymmetricFunctionsNonCommutingVariables',
     'SymmetricFunctionsNonCommutingVariablesDual',
     'SymmetricGroup',
     'SymmetricGroupAlgebra',
     'SymmetricGroupRepresentation',
     'SymmetricGroupRepresentations',
     'Tableau',
     'TableauTuple',
     'TableauTuples',
     'Tableaux',
     'Tachyon',
     'TamariIntervalPoset',
     'TamariIntervalPosets',
     'TateAlgebra',
     'TemperleyLiebAlgebra',
     'TensorAlgebra',
     'TermOrder',
     'TernaryQF',
     'TestSuite',
     'TimeSeries',
     'ToricIdeal',
     'ToricLattice',
     'ToricVariety',
     'TorsionQuadraticForm',
     'TotallyOrderedFiniteSet',
     'Transducer',
     'TransitiveGroup',
     'TransitiveGroups',
     'TranspositionCryptosystem',
     'TropicalSemiring',
     'TruncatedStaircases',
     'Tuples',
     'UnionCombinatorialClass',
     'UniqueFactorizationDomains',
     'UniqueRepresentation',
     'UnitGroup',
     'UniversalCyclotomicField',
     'Unknown',
     'UnorderedTuples',
     'UnsignedInfinityRing',
     'UnwrappingMorphism',
     'VectorPartition',
     'VectorPartitions',
     'VectorSpace',
     'VectorSpaces',
     'VigenereCryptosystem',
     'VoronoiDiagram',
     'WaveletTransform',
     'WeakReversePlanePartition',
     'WeakReversePlanePartitions',
     'WeakTableau',
     'WeakTableaux',
     'WehlerK3Surface',
     'WeierstrassForm',
     'WeightRing',
     'WeightedIntegerVectors',
     'WeylCharacterRing',
     'WeylDim',
     'WeylGroup',
     'WeylGroupElement',
     'WeylGroups',
     'Word',
     'WordMorphism',
     'WordOptions',
     'WordPaths',
     'WordQuasiSymmetricFunctions',
     'Words',
     'YangBaxterGraph',
     'Yangian',
     'ZZ',
     'Zmod',
     'Zp',
     'ZpCA',
     'ZpCR',
     'ZpFM',
     'ZpFP',
     'ZpLC',
     'ZpLF',
     'Zq',
     'ZqCA',
     'ZqCR',
     'ZqFM',
     'ZqFP',
     '__builtins__',
     '__cached__',
     '__doc__',
     '__file__',
     '__loader__',
     '__name__',
     '__package__',
     '__spec__',
     'a0',
     'a1',
     'a2',
     'a3',
     'a4',
     'a5',
     'a6',
     'abs_symbolic',
     'absolute_igusa_invariants_kohel',
     'absolute_igusa_invariants_wamelen',
     'absolute_import',
     'abstract_method',
     'acos',
     'acosh',
     'acot',
     'acoth',
     'acsc',
     'acsch',
     'add',
     'addgp',
     'addition_names',
     'additive_order',
     'affinity_network',
     'airy_ai',
     'airy_ai_prime',
     'airy_bi',
     'airy_bi_prime',
     'alarm',
     'algdep',
     'algebras',
     'all_max_clique',
     'animate',
     'arc',
     'arccos',
     'arccosh',
     'arccot',
     'arccoth',
     'arccsc',
     'arccsch',
     'arcsec',
     'arcsech',
     'arcsin',
     'arcsinh',
     'arctan',
     'arctan2',
     'arctanh',
     'arg',
     'arrow',
     'arrow2d',
     'arrow3d',
     'ascii_art',
     'asec',
     'asech',
     'asin',
     'asinh',
     'assume',
     'assuming',
     'assumptions',
     'asym',
     'asymptotic_expansions',
     'atan',
     'atan2',
     'atanh',
     'attach',
     'attached_files',
     'attrcall',
     'automata',
     'axiom',
     'backtrack_all',
     'balanced_sum',
     'banner',
     'bar_chart',
     'base_field',
     'base_ring',
     'basis',
     'bell_number',
     'bell_polynomial',
     'benchmark',
     'berlekamp_massey',
     'bernoulli',
     'bernoulli_mod_p',
     'bernoulli_mod_p_single',
     'bernoulli_polynomial',
     'bessel_I',
     'bessel_J',
     'bessel_K',
     'bessel_Y',
     'beta',
     'betavariate',
     'bezier3d',
     'bezier_path',
     'binomial',
     'binomial_coefficients',
     'block_diagonal_matrix',
     'block_matrix',
     'branching_rule',
     'branching_rule_from_plethysm',
     'browse_sage_doc',
     'bsgs',
     'build_alphabet',
     'buzzard_tpslopes',
     'cached_function',
     'cached_in_parent_method',
     'cached_method',
     'cancel_alarm',
     'canonical_coercion',
     'cartesian_product',
     'cartesian_product_iterator',
     'cases',
     'catalan',
     'catalan_number',
     'category',
     'ceil',
     'channels',
     'characteristic_polynomial',
     'charpoly',
     'chebyshev_T',
     'chebyshev_U',
     'choice',
     'circle',
     'class_graph',
     'clear_vars',
     'clebsch_gordan',
     'clebsch_invariants',
     'clique_number',
     'cm_j_invariants',
     'cm_j_invariants_and_orders',
     'cm_orders',
     'codes',
     'coerce',
     'coercion_model',
     'coercion_traceback',
     'coincidence_discriminant',
     'coincidence_index',
     'colormaps',
     'colors',
     'column_matrix',
     'companion_matrix',
     'complex_cubic_spline',
     'complex_plot',
     'complex_root_of',
     'compose',
     'conjugate',
     'constructions',
     'continuant',
     'continued_fraction',
     'continued_fraction_list',
     'contour_plot',
     'convergents',
     'convolution',
     'conway_polynomial',
     'copy',
     'copying',
     'copyright',
     'cos',
     'cos_integral',
     'cosh',
     'cosh_integral',
     'cot',
     'coth',
     'cputime',
     'cremona_curves',
     'cremona_optimal_curves',
     'crt',
     'crt_basis',
     'crystals',
     'csc',
     'csch',
     'cube',
     'cubical_complexes',
     'cunningham_prime_factors',
     'current_randstate',
     'cyclotomic_polynomial',
     'cyclotomic_value',
     'cylindrical_plot3d',
     'cython',
     'cython_create_local_so',
     'cython_lambda',
     'db',
     'db_save',
     'debug',
     'decomposition',
     'dedekind_sum',
     'deepcopy',
     'default_mip_solver',
     'default_sdp_solver',
     'degree_lowest_rational_function',
     'delta_complexes',
     'delta_lseries',
     'delta_qexp',
     'denominator',
     'density_plot',
     'derivative',
     'designs',
     'designs_from_XML',
     'designs_from_XML_url',
     'desolve',
     'desolve_laplace',
     'desolve_mintides',
     'desolve_odeint',
     'desolve_rk4',
     'desolve_system',
     'desolve_system_rk4',
     'desolve_tides_mpfr',
     'desolvers',
     'det',
     'detach',
     'developer',
     'diagonal_matrix',
     'dickman_rho',
     'diff',
     'differences',
     'digraphs',
     'dilog',
     'dim',
     'dimension',
     'dimension_cusp_forms',
     'dimension_eis',
     'dimension_modular_forms',
     'dimension_new_cusp_forms',
     'dimension_supersingular_module',
     'dirac_delta',
     'direct_product_permgroups',
     'disc',
     'discrete_log',
     'discrete_log_generic',
     'discrete_log_lambda',
     'discrete_log_rho',
     'discriminant',
     'disk',
     'disk_cached_function',
     'divisors',
     'dodecahedron',
     'dumps',
     'e',
     'ecm',
     'edit',
     'eisenstein_series_lseries',
     'eisenstein_series_qexp',
     'elementary_matrix',
     'ellipse',
     'ellipsis_iter',
     'ellipsis_range',
     'elliptic_curves',
     'elliptic_e',
     'elliptic_ec',
     'elliptic_eu',
     'elliptic_f',
     'elliptic_j',
     'elliptic_kc',
     'elliptic_pi',
     'email',
     'end',
     'enum_affine_finite_field',
     'enum_affine_rational_field',
     'enumerate_totallyreal_fields_all',
     'enumerate_totallyreal_fields_prim',
     'enumerate_totallyreal_fields_rel',
     'eratosthenes',
     'erf',
     'erfc',
     'erfi',
     'erfinv',
     'eta',
     'eta_poly_relations',
     'euler_gamma',
     'euler_number',
     'euler_phi',
     'eulers_method',
     'eulers_method_2x2',
     'eulers_method_2x2_plot',
     'exists',
     'exists_conway_polynomial',
     'exp',
     'exp_integral_e',
     'exp_integral_e1',
     'exp_integral_ei',
     'exp_polar',
     'expand',
     'experimental_packages',
     'explain_pickle',
     'expnums',
     'exponential_integral_1',
     'expovariate',
     'extend_to_primitive',
     'external_ray',
     'factor',
     'factorial',
     'falling_factorial',
     'false',
     'fast_callable',
     'fast_float',
     'fcp',
     'fibonacci',
     'fibonacci_sequence',
     'fibonacci_xrange',
     'finance',
     'find_a_ternary_qf_by_level_disc',
     'find_all_ternary_qf_by_level_disc',
     'find_fit',
     'find_local_maximum',
     'find_local_minimum',
     'find_root',
     'findstat',
     'firing_graph',
     'flatten',
     'floor',
     'forall',
     'forget',
     'fork',
     'fortran',
     'four_squares',
     'four_ti_2',
     'frac',
     'free_module_element',
     'frequency_distribution',
     'fresnel_cos',
     'fresnel_sin',
     'fricas',
     'frobby',
     'func_persist',
     'function',
     'fundamental_discriminant',
     'game_theory',
     'gamma',
     'gamma__exact',
     'gamma_inc',
     'gamma_inc_lower',
     'gammavariate',
     'gap',
     'gap3',
     'gap3_version',
     'gap_reset_workspace',
     'gaunt',
     'gauss',
     'gaussian_binomial',
     'gcd',
     'gegenbauer',
     'gen',
     'gen_laguerre',
     'gen_legendre_P',
     'gen_legendre_Q',
     'gens',
     'genus2reduction',
     'get_coercion_model',
     'get_display_manager',
     'get_gcd',
     'get_inverse_mod',
     'get_memory_usage',
     'get_remote_file',
     'get_verbose',
     'get_verbose_files',
     'getattr_debug',
     'getrandbits',
     'gfan',
     'giac',
     'glaisher',
     'gnuplot',
     'golden_ratio',
     'gp',
     'gp_version',
     'graph_classes',
     'graph_coloring',
     'graph_db_info',
     'graph_editor',
     'graphics_array',
     'graphs',
     'graphs_list',
     'groups',
     'hadamard_matrix',
     'hadamard_matrix_www',
     'half_integral_weight_modform_basis',
     'hankel1',
     'hankel2',
     'harmonic_number',
     'heaviside',
     'hecke_operator',
     'hecke_operator_on_basis',
     'hecke_operator_on_qexp',
     'hecke_series',
     'heegner_point',
     'heegner_points',
     'help',
     'hermite',
     'hermite_constant',
     'hilbert_class_polynomial',
     'hilbert_conductor',
     'hilbert_conductor_inverse',
     'hilbert_symbol',
     'histogram',
     'hmm',
     'hold',
     'hom',
     'html',
     'hue',
     'hurwitz_zeta',
     'hyperbolic_arc',
     'hyperbolic_polygon',
     'hyperbolic_regular_polygon',
     'hyperbolic_triangle',
     'hypergeometric',
     'hypergeometric_M',
     'hypergeometric_U',
     'hypergraphs',
     'hyperplane_arrangements',
     'i',
     'icosahedron',
     'ideal',
     'identity_matrix',
     'igusa_clebsch_invariants',
     'imag',
     'imag_part',
     'image',
     'imaginary',
     'implicit_multiplication',
     'implicit_plot',
     'implicit_plot3d',
     'import_statements',
     'infinity',
     'infix_operator',
     'initial_seed',
     'inotebook',
     'install_scripts',
     'installed_packages',
     'integer_ceil',
     'integer_floor',
     'integral',
     'integral_closure',
     'integral_numerical',
     'integrate',
     'interact',
     'interacts',
     'interfaces',
     'interval',
     'invariant_theory',
     'inverse_jacobi',
     'inverse_jacobi_cd',
     'inverse_jacobi_cn',
     'inverse_jacobi_cs',
     'inverse_jacobi_dc',
     'inverse_jacobi_dn',
     'inverse_jacobi_ds',
     'inverse_jacobi_nc',
     'inverse_jacobi_nd',
     'inverse_jacobi_ns',
     'inverse_jacobi_sc',
     'inverse_jacobi_sd',
     'inverse_jacobi_sn',
     'inverse_laplace',
     'inverse_mod',
     'is_ProductProjectiveSpaces',
     'is_ProjectiveSpace',
     'is_commutative',
     'is_even',
     'is_field',
     'is_fundamental_discriminant',
     'is_integrally_closed',
     'is_iterator',
     'is_odd',
     'is_pAdicField',
     'is_pAdicRing',
     'is_package_installed',
     'is_power_of_two',
     'is_prime',
     'is_prime_power',
     'is_pseudoprime',
     'is_pseudoprime_power',
     'is_real_place',
     'is_square',
     'is_squarefree',
     'is_triangular_number',
     'isogeny_codomain_from_kernel',
     'isqrt',
     'j_invariant_qexp',
     'jacobi',
     'jacobi_P',
     'jacobi_am',
     'jacobi_cd',
     'jacobi_cn',
     'jacobi_cs',
     'jacobi_dc',
     'jacobi_dn',
     'jacobi_ds',
     'jacobi_nc',
     'jacobi_nd',
     'jacobi_ns',
     'jacobi_sc',
     'jacobi_sd',
     'jacobi_sn',
     'jacobi_symbol',
     'jacobian',
     'jordan_block',
     'julia_plot',
     'kash',
     'kash_version',
     'kernel',
     'khinchin',
     'kronecker',
     'kronecker_character',
     'kronecker_character_upside_down',
     'kronecker_delta',
     'kronecker_symbol',
     'krull_dimension',
     'laguerre',
     'lambert_w',
     'laplace',
     'latex',
     'lattice_polytope',
     'lazy_attribute',
     'lazy_class_attribute',
     'lazy_import',
     'lcalc',
     'lcm',
     'least_quadratic_nonresidue',
     'legendre_P',
     'legendre_Q',
     'legendre_phi',
     'legendre_symbol',
     'lfsr_autocorrelation',
     'lfsr_connection_polynomial',
     'lfsr_sequence',
     'li',
     'libgap',
     'license',
     'lie',
     'lie_algebras',
     'lift',
     'lift_to_sl2z',
     'lim',
     'limit',
     'line',
     'line2d',
     'line3d',
     'linear_program',
     'linear_relation',
     'linear_transformation',
     'lisp',
     'list_plot',
     'list_plot3d',
     'list_plot_loglog',
     'list_plot_semilogx',
     'list_plot_semilogy',
     'ln',
     'load',
     'load_attach_mode',
     'load_attach_path',
     'load_session',
     'loads',
     'local_print_mode',
     'localvars',
     'log',
     'log2',
     'log_b',
     'log_gamma',
     'log_integral',
     'log_integral_offset',
     'lognormvariate',
     'logstr',
     'lucas_number1',
     'lucas_number2',
     'macaulay2',
     'magma',
     'magma_free',
     'mandelbrot_plot',
     'manifolds',
     'manual',
     'map_threaded',
     'maple',
     'math',
     'mathematica',
     'mathml',
     'matlab',
     'matlab_version',
     'matrix',
     'matrix_plot',
     'matroids',
     'max_clique',
     'max_symbolic',
     'maxima',
     'maxima_calculus',
     'mean',
     'median',
     'merge_points',
     'mertens',
     'min_symbolic',
     'minimal_polynomial',
     'minimize',
     'minimize_constrained',
     'minpoly',
     'mod',
     'mode',
     'moebius',
     'monomials',
     'monsky_washnitzer',
     'moving_average',
     'mq',
     'mqrr_rational_reconstruction',
     'mrange',
     'mrange_iter',
     'mul',
     'multinomial',
     'multinomial_coefficients',
     'multiple',
     'multiples',
     'multiplication_names',
     'multiplicative_order',
     'mupad',
     'mwrank',
     'mwrank_EllipticCurve',
     'mwrank_MordellWeil',
     'mwrank_get_precision',
     'mwrank_initprimes',
     'mwrank_set_precision',
     'n',
     'nest',
     'newton_method_sizes',
     'next_prime',
     'next_prime_power',
     'next_probable_prime',
     'ngens',
     'norm',
     'normalvariate',
     'notebook',
     'nth_prime',
     'ntl',
     'num_cusps_of_width',
     'number_field_elements_from_algebraics',
     'number_of_divisors',
     'number_of_partitions',
     'number_of_tuples',
     'number_of_unordered_tuples',
     'numbers_abc',
     'numerator',
     'numerical_approx',
     'numerical_eigenforms',
     'numerical_integral',
     'objgen',
     'objgens',
     'octahedron',
     'octave',
     'odd_part',
     'ode_solver',
     'ode_system',
     'oeis',
     'ones_matrix',
     'oo',
     'operator',
     'optional_packages',
     'order',
     'order_from_bounds',
     'order_from_multiple',
     'os',
     'pAdicExtension',
     'pAdicField',
     'pAdicRing',
     'pAdicWeightSpace',
     'package_versions',
     'pad_zeros',
     'padic_printing',
     'pager',
     'parallel',
     'parallel_firing_graph',
     'parametric_plot',
     'parametric_plot3d',
     'parent',
     'paretovariate',
     'pari',
     'pari_gen',
     'partial_sieve_function',
     'permutation_action',
     'pi',
     'pickle_function',
     'piecewise',
     'plot',
     'plot3d',
     'plot_loglog',
     'plot_semilogx',
     'plot_semilogy',
     'plot_slope_field',
     'plot_step_function',
     'plot_vector_field',
     'plot_vector_field3d',
     'point',
     'point2d',
     'point3d',
     'points',
     'polar_plot',
     'polygen',
     'polygens',
     'polygon',
     'polygon2d',
     'polygon3d',
     'polygon_spline',
     'polygons3d',
     'polylog',
     'polymake',
     'polytopes',
     'posets',
     'povray',
     'power',
     'power_mod',
     'powerset',
     'preparse',
     'preparser',
     'pretty_print',
     'pretty_print_default',
     'previous_prime',
     'previous_prime_power',
     'prime_divisors',
     'prime_factors',
     'prime_pi',
     'prime_powers',
     'prime_range',
     'prime_to_m_part',
     'primes',
     'primes_first_n',
     'primitive_root',
     'prod',
     'product',
     'proof',
     'propcalc',
     'psi',
     'python_help',
     'q_binomial',
     'qepcad',
     'qepcad_formula',
     'qepcad_version',
     'qexp_eta',
     'qsieve',
     'quadratic_L_function__exact',
     'quadratic_L_function__numerical',
     'quadratic_residues',
     'quit_sage',
     'quo',
     'quotient',
     'r',
     'r_version',
     'racah',
     'radical',
     'rainbow',
     'randint',
     'random',
     'random_DAG',
     'random_WehlerK3Surface',
     'random_cone',
     'random_matrix',
     'random_prime',
     'random_quadraticform',
     'random_quadraticform_with_conditions',
     'random_sublist',
     'random_ternaryqf',
     'random_ternaryqf_with_conditions',
     'random_vector',
     'randrange',
     'rank',
     'ranker',
     'rational_reconstruction',
     'raw_getattr',
     'read_data',
     'real',
     'real_part',
     'reciprocal_trig_functions',
     'reduce',
     'reference',
     'region_plot',
     'register_unpickle_override',
     'regulator',
     'repr_lincomb',
     'reset',
     'reset_load_attach_path',
     'restore',
     'revolution_plot3d',
     'rising_factorial',
     'robinson_schensted_knuth',
     'robinson_schensted_knuth_inverse',
     'round',
     'run_doctests',
     'running_total',
     'runsnake',
     'sage',
     'sage0',
     'sage0_version',
     'sage_eval',
     'sage_globals',
     'sage_input',
     'sage_wraps',
     'sageobj',
     'sample',
     'sandpiles',
     'save',
     'save_session',
     'scatter_plot',
     'schonheim',
     'scilab',
     'search_def',
     'search_doc',
     'search_src',
     'sec',
     'sech',
     'seed',
     'self_orthogonal_binary_codes',
     'seq',
     'series_precision',
     'set_default_variable_name',
     'set_edit_template',
     'set_gap_memory_pool_size',
     'set_modsym_print_mode',
     'set_random_seed',
     'set_series_precision',
     'set_verbose',
     'set_verbose_files',
     'sgn',
     'sh',
     'show',
     'show_identifiers',
     'shuffle',
     'sidon_sets',
     'sig_on_count',
     'sigma',
     'sign',
     'simplicial_complexes',
     'simplicial_sets',
     'simplify',
     'sin',
     'sin_integral',
     'singular',
     'singular_version',
     'sinh',
     'sinh_integral',
     'sleep',
     'sloane',
     'solve',
     'solve_diophantine',
     'solve_ineq',
     'solve_mod',
     'sort_complex_numbers_for_display',
     'span',
     'specialize',
     'species',
     'sphere',
     'spherical_bessel_J',
     'spherical_bessel_Y',
     'spherical_hankel1',
     'spherical_hankel2',
     'spherical_harmonic',
     'spherical_plot3d',
     'spike_function',
     'spline',
     'sqrt',
     'squarefree_divisors',
     'squarefree_part',
     'srange',
     'standard_packages',
     'stats',
     'std',
     'steenrod_algebra_basis',
     'stieltjes',
     'stirling_number1',
     'stirling_number2',
     'streamline_plot',
     'strip_encoding',
     'structure_description',
     'struve_H',
     'struve_L',
     'sturm_bound',
     'subfactorial',
     'subsets',
     'sudoku',
     'sum',
     'sum_of_k_squares',
     'supersingular_D',
     'supersingular_j',
     'surfaces',
     'sxrange',
     'sym',
     'symbolic_expression',
     'symmetrica',
     'sympow',
     'sys',
     'table',
     'tachyon_rt',
     'tan',
     'tanh',
     'taylor',
     'tensor',
     'tests',
     'tetrahedron',
     'text',
     'text3d',
     'theta2_qexp',
     'theta_qexp',
     'three_squares',
     'timeit',
     'tmp_dir',
     'tmp_filename',
     'toric_plotter',
     'toric_varieties',
     'trace',
     'transducers',
     'transpose',
     'trial_division',
     'triangle_sandpile',
     'trivial_character',
     'trivial_covering_design',
     'true',
     'ttest',
     'tuples',
     'tutorial',
     'twinprime',
     'two_squares',
     'type_debug',
     'ultraspherical',
     'unicode_art',
     'uniform',
     'union',
     'uniq',
     'unit_step',
     'units',
     'unordered_tuples',
     'unpickle_appends',
     'unpickle_build',
     'unpickle_extension',
     'unpickle_function',
     'unpickle_global',
     'unpickle_instantiate',
     'unpickle_newobj',
     'unpickle_persistent',
     'unset_verbose_files',
     'unsigned_infinity',
     'v',
     'valuation',
     'valuations',
     'var',
     'variance',
     'varmap',
     'varmapsr',
     'vector',
     'verbose',
     'version',
     'victor_miller_basis',
     'view',
     'vonmisesvariate',
     'walltime',
     'walsh_matrix',
     'warnings',
     'wave',
     'wedge',
     'weibullvariate',
     'wigner_3j',
     'wigner_6j',
     'wigner_9j',
     'wilmes_algorithm',
     'word_problem',
     'words',
     'wronskian',
     'x',
     'x0',
     'x1',
     'xgcd',
     'xinterval',
     'xkcd',
     'xlcm',
     'xmrange',
     'xmrange_iter',
     'xsr',
     'xsrange',
     'xsym',
     'y',
     'y0',
     'ysr',
     'ysym',
     'ysymraw',
     'zero_matrix',
     'zero_vector',
     'zeta',
     'zeta__exact',
     'zeta_symmetric',
     'zeta_zeros',
     'zetaderiv']

```python
gk.ysymraw
```

    [0, a0 + a1 + a2*x1 - x1 + (-a3*x1 + (a4 + a5 + a6*x1 - x1)**2.0)**0.5]

```python
gk.ysym[1]
```

$\displaystyle a_{0} + a_{1} + a_{2} x_{1} - x_{1} + \left(- a_{3} x_{1} + \left(a_{4} + a_{5} + a_{6} x_{1} - x_{1}\right)^{2.0}\right)^{0.5}$

```python
varmap = {
#     'x0': 'S',
#     'x1': 1,
#     #'a0': 'u',
#     'a0': 'v',
#     'a1': 'u',
#     'a2': 'J',
#     'a3': 'K',
    'x1': 'R',
    'a6': 'v',
    'a4': "v",
    'a5': -sym.var("u")*sym.var("R"),
}
```

```python
gk.ysym[1].subs(varmap)
```

$\displaystyle R a_{2} - R + a_{0} + a_{1} + \left(- R a_{3} + \left(- R u + R v - R + v\right)^{2.0}\right)^{0.5}$

```python

```